Podręcznik PHP

Opracowany przez:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
I kilka innych
2012-01-26
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
© 1997-2012 the PHP Documentation Group
  • Copyright
  • Podręcznik PHP
    • Przedmowa
  • Na początek
    • Introduction
    • A simple tutorial
  • Instalacja i konfiguracja
    • Ogólnie o instalacji
    • Installation on Unix systems
    • Installation on Mac OS X
    • Installation on Windows systems
    • Installation on Cloud Computing platforms
    • FastCGI Process Manager (FPM)
    • Installation of PECL extensions
    • Problemy?
    • Runtime Configuration
  • Opis języka
    • Podstawowa składnia
    • Types
    • Zmienne
    • Stałe
    • Wyrażenia
    • Operators
    • Control Structures
    • Funkcje
    • Classes and Objects
    • Namespaces
    • Exceptions
    • Referencje
    • Predefined Variables
    • Predefined Exceptions
    • Predefined Interfaces
    • Context options and parameters
    • Supported Protocols and Wrappers
  • Bezpieczeństwo
    • Introduction
    • General considerations
    • Installed as CGI binary
    • Installed as an Apache module
    • Filesystem Security
    • Database Security
    • Error Reporting
    • Using Register Globals
    • User Submitted Data
    • Magic Quotes
    • Hiding PHP
    • Keeping Current
  • Możliwości
    • Uwierzytelnianie HTTP w PHP
    • Ciasteczka (cookies)
    • Sessions
    • Dealing with XForms
    • Handling file uploads
    • Korzystanie ze zdalnych plików
    • Obsługa połączeń
    • Stałe połączenia z bazami danych
    • Tryb bezpieczny
    • Command line usage — Using PHP from the command line
    • Garbage Collection
  • Opis funkcji
    • Wpływ na zachowanie PHP
    • Przetwarzanie formatów audio
    • Serwisy uwierzytelnienia
    • Rozszerzenia daty i czasu
    • Rozszerzenia wiersza poleceń
    • Rozszerzenia kompresji i archiwizacji
    • Przetwarzanie transakcji kartami płatniczymi
    • Rozszerzenia kryptograficzne
    • Rozszerzenia baz danych
    • Rozszerzenia powiązane z systemem plików
    • Język naturalny i obsługa kodowania znaków
    • Przetwarzanie i generowanie obrazów
    • Rozszerzenia powiązane z pocztą elektroniczną
    • Rozszerzenia matematyczne
    • Generowanie nietekstowych formatów danych
    • Rozszerzenia kontroli procesów
    • Inne podstawowe rozszerzenia
    • Inne serwisy
    • Systemy wyszukiwania informacji
    • Rozszerzenia przeznaczone dla serwera
    • Rozszerzenia sesji
    • Przetwarzanie tekstu
    • Zmienne i typy powiązanych rozszerzeń
    • Usługi sieciowe
    • Rozszerzenia przeznaczone dla Windows
    • Przetwarzanie XML
  • Rdzeń PHP: Poradnik hackerów o Zend Engine
    • Preface
    • The "counter" Extension - A Continuing Example
    • The PHP 5 build system
    • Extension structure
    • Memory management
    • Working with variables
    • Writing functions
    • Working with classes and objects
    • Working with resources
    • Working with INI settings
    • Working with streams
    • PDO Driver How-To
    • Extension FAQs
    • Zend Engine 2 API reference
    • Zend Engine 2 opcode list
    • Zend Engine 1
  • FAQ — FAQ: Często zadawane pytania
    • General Information
    • Mailing lists
    • Obtaining PHP
    • Database issues
    • Installation
    • Build Problems
    • Using PHP
    • Password Hashing — Safe Password Hashing
    • PHP and HTML
    • PHP and COM
    • PHP i inne języki
    • Migrating from PHP 4 to PHP 5
    • Miscellaneous Questions
  • Dodatki
    • History of PHP and Related Projects
    • Migrating from PHP 5.3.x to PHP 5.4.x
    • Migrating from PHP 5.2.x to PHP 5.3.x
    • Migrating from PHP 5.1.x to PHP 5.2.x
    • Migrating from PHP 5.0.x to PHP 5.1.x
    • Migrating from PHP 4 to PHP 5.0.x
    • Classes and Objects (PHP 4)
    • Debugging in PHP
    • Configure options
    • php.ini directives
    • Wykaz i klasyfikacja rozszerzeń
    • Lista aliasów funkcji
    • List of Reserved Words
    • Lista Rodzajów Zasobów
    • List of Available Filters
    • List of Supported Socket Transports
    • Tabele porównań typów PHP
    • List of Parser Tokens
    • Userland Naming Guide
    • About the manual
    • Creative Commons Attribution 3.0
    • Indeks
  • Wersja HTML Help
    • About This Edition
    • Using PHP Manual CHM Edition
    • The Full Text Search
    • Specialities of this Edition
    • Integrating the PHP Manual
    • Skin development
    • CHM Edition Credits
PHP Manual


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
Podręcznik PHP
Podręcznik PHP


Podręcznik PHP
PHP Manual

Podręcznik PHP

  • Przedmowa
Copyright
Przedmowa
Podręcznik PHP
PHP Manual


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.

Podręcznik PHP
Na początek
Podręcznik PHP


Na początek

  • Introduction
    • What is PHP?
    • What can PHP do?
  • A simple tutorial
    • What do I need?
    • Your first PHP-enabled page
    • Something Useful
    • Dealing with Forms
    • Using old code with new versions of PHP
    • What's next?
Przedmowa
Introduction
Podręcznik PHP


Introduction

Spis treści

  • What is PHP?
  • What can PHP do?
Na początek
What is PHP?
Na początek


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.

Introduction
What can PHP do?
Introduction


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.

What is PHP?
A simple tutorial
Introduction


A simple tutorial

Spis treści

  • What do I need?
  • Your first PHP-enabled page
  • Something Useful
  • Dealing with Forms
  • Using old code with new versions of PHP
  • What's next?

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 can PHP do?
What do I need?
Na początek


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.

A simple tutorial
Your first PHP-enabled page
A simple tutorial


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

What do I need?
Something Useful
A simple tutorial


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.

Your first PHP-enabled page
Dealing with Forms
A simple tutorial


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.

Something Useful
Using old code with new versions of PHP
A simple tutorial


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.

Dealing with Forms
What's next?
A simple tutorial


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/

Using old code with new versions of PHP
Instalacja i konfiguracja
A simple tutorial


Instalacja i konfiguracja

  • Ogólnie o instalacji
  • Installation on Unix systems
    • Apache 1.3.x on Unix systems
    • Apache 2.x on Unix systems
    • Lighttpd 1.4 on Unix systems
    • Sun, iPlanet and Netscape servers on Sun Solaris
    • CGI and command line setups
    • HP-UX specific installation notes
    • OpenBSD installation notes
    • Solaris specific installation tips
    • Debian GNU/Linux installation notes
  • Installation on Mac OS X
    • Using Packages
    • Using the bundled PHP
    • Compiling PHP on Mac OS X
  • Installation on Windows systems
    • Windows Installer (PHP 5.1.0 and earlier)
    • Windows Installer (PHP 5.2 and later)
    • Manual Installation Steps
    • Microsoft IIS
    • Microsoft IIS 5.1 and IIS 6.0
    • Microsoft IIS 7.0 and later
    • Apache 1.3.x on Microsoft Windows
    • Apache 2.x on Microsoft Windows
    • Sun, iPlanet and Netscape servers on Microsoft Windows
    • Sambar Server on Microsoft Windows
    • Xitami on Microsoft Windows
    • Building from source
    • Installation of extensions on Windows
    • Command Line PHP on Microsoft Windows
  • Installation on Cloud Computing platforms
    • Microsoft Azure
    • Amazon EC2
  • FastCGI Process Manager (FPM)
    • Installation
    • Configuration
  • Installation of PECL extensions
    • Introduction to PECL Installations
    • Downloading PECL extensions
    • Installing a PHP extension on Windows
    • Compiling shared PECL extensions with the pecl command
    • Compiling shared PECL extensions with phpize
    • php-config
    • Compiling PECL extensions statically into PHP
  • Problemy?
    • Przeczytaj FAQ
    • Inne problemy
    • Raporty o błędach
  • Runtime Configuration
    • The configuration file
    • .user.ini files
    • Where a configuration setting may be set
    • How to change configuration settings
What's next?
Ogólnie o instalacji
Podręcznik PHP


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.

Instalacja i konfiguracja
Installation on Unix systems
Instalacja i konfiguracja


Installation on Unix systems

Spis treści

  • Apache 1.3.x on Unix systems
  • Apache 2.x on Unix systems
  • Lighttpd 1.4 on Unix systems
  • Sun, iPlanet and Netscape servers on Sun Solaris
  • CGI and command line setups
  • HP-UX specific installation notes
  • OpenBSD installation notes
  • Solaris specific installation tips
  • Debian GNU/Linux installation notes

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.

Ogólnie o instalacji
Apache 1.3.x on Unix systems
Instalacja i konfiguracja


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.

Installation on Unix systems
Apache 2.x on Unix systems
Installation on Unix systems


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.

Apache 1.3.x on Unix systems
Lighttpd 1.4 on Unix systems
Installation on Unix systems


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 ))
)
Apache 2.x on Unix systems
Sun, iPlanet and Netscape servers on Sun Solaris
Installation on Unix systems


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

Lighttpd 1.4 on Unix systems
CGI and command line setups
Installation on Unix systems


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

Sun, iPlanet and Netscape servers on Sun Solaris
HP-UX specific installation notes
Installation on Unix systems


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

CGI and command line setups
OpenBSD installation notes
Installation on Unix systems


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

HP-UX specific installation notes
Solaris specific installation tips
Installation on Unix systems


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.

OpenBSD installation notes
Debian GNU/Linux installation notes
Installation on Unix systems


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.
Solaris specific installation tips
Installation on Mac OS X
Installation on Unix systems


Installation on Mac OS X

Spis treści

  • Using Packages
  • Using the bundled PHP
  • Compiling PHP on Mac OS X

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.

Debian GNU/Linux installation notes
Using Packages
Instalacja i konfiguracja


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:

  • MacPorts: » http://www.macports.org/
  • Entropy: » http://www.entropy.ch/software/macosx/php/
  • Fink: » http://www.finkproject.org/
  • Homebrew: » http://github.com/mxcl/homebrew

Installation on Mac OS X
Using the bundled PHP
Installation on Mac OS X


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.

Using Packages
Compiling PHP on Mac OS X
Installation on Mac OS X


Compiling PHP on Mac OS X

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

Using the bundled PHP
Installation on Windows systems
Installation on Mac OS X


Installation on Windows systems

Spis treści

  • Windows Installer (PHP 5.1.0 and earlier)
  • Windows Installer (PHP 5.2 and later)
  • Manual Installation Steps
  • Microsoft IIS
  • Microsoft IIS 5.1 and IIS 6.0
  • Microsoft IIS 7.0 and later
  • Apache 1.3.x on Microsoft Windows
  • Apache 2.x on Microsoft Windows
  • Sun, iPlanet and Netscape servers on Microsoft Windows
  • Sambar Server on Microsoft Windows
  • Xitami on Microsoft Windows
  • Building from source
  • Installation of extensions on Windows
  • Command Line PHP on Microsoft Windows

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.

Compiling PHP on Mac OS X
Windows Installer (PHP 5.1.0 and earlier)
Instalacja i konfiguracja


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.

Installation on Windows systems
Windows Installer (PHP 5.2 and later)
Installation on Windows systems


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.

Windows Installer (PHP 5.1.0 and earlier)
Manual Installation Steps
Installation on Windows systems


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.

Windows Installer (PHP 5.2 and later)
Microsoft IIS
Installation on Windows systems


Microsoft IIS

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

  • Manually installing PHP on Microsoft IIS 5.1 and IIS 6.0
  • Manually installing PHP on Microsoft IIS 7.0 and later
Manual Installation Steps
Microsoft IIS 5.1 and IIS 6.0
Installation on Windows systems


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
Microsoft IIS 7.0 and later
Installation on Windows systems


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

Microsoft IIS 5.1 and IIS 6.0
Apache 1.3.x on Microsoft Windows
Installation on Windows systems


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

Microsoft IIS 7.0 and later
Apache 2.x on Microsoft Windows
Installation on Windows systems


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.

Apache 1.3.x on Microsoft Windows
Sun, iPlanet and Netscape servers on Microsoft Windows
Installation on Windows systems


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

Apache 2.x on Microsoft Windows
Sambar Server on Microsoft Windows
Installation on Windows systems


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.

Sun, iPlanet and Netscape servers on Microsoft Windows
Xitami on Microsoft Windows
Installation on Windows systems


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.

Sambar Server on Microsoft Windows
Building from source
Installation on Windows systems


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

Xitami on Microsoft Windows
Installation of extensions on Windows
Installation on Windows systems


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

Building from source
Command Line PHP on Microsoft Windows
Installation on Windows systems


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 of extensions on Windows
Installation on Cloud Computing platforms
Installation on Windows systems


Installation on Cloud Computing platforms

Spis treści

  • Microsoft Azure
  • Amazon EC2

PHP installs on the cloud. To the PHP cloud!

Command Line PHP on Microsoft Windows
Microsoft Azure
Instalacja i konfiguracja


Microsoft Azure

PHP installs on the » Azure cloud platform.

See also the » Azure SDK for PHP.

Installation on Cloud Computing platforms
Amazon EC2
Installation on Cloud Computing platforms


Amazon EC2

PHP installs on the » EC2 cloud platform.

See also the » AWS SDK for PHP.

Microsoft Azure
FastCGI Process Manager (FPM)
Installation on Cloud Computing platforms


FastCGI Process Manager (FPM)

Spis treści

  • Installation
  • Configuration

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.

Amazon EC2
Installation
Instalacja i konfiguracja


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

FastCGI Process Manager (FPM)
Configuration
FastCGI Process Manager (FPM)


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, dynamic. This option is mandatory.

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

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
Installation of PECL extensions
FastCGI Process Manager (FPM)


Installation of PECL extensions

Spis treści

  • Introduction to PECL Installations
  • Downloading PECL extensions
  • Installing a PHP extension on Windows
  • Compiling shared PECL extensions with the pecl command
  • Compiling shared PECL extensions with phpize
  • php-config
  • Compiling PECL extensions statically into PHP
Configuration
Introduction to PECL Installations
Instalacja i konfiguracja


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.

Installation of PECL extensions
Downloading PECL extensions
Installation of PECL extensions


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.
Introduction to PECL Installations
Installing a PHP extension on Windows
Installation of PECL extensions


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.

Downloading PECL extensions
Compiling shared PECL extensions with the pecl command
Installation of PECL extensions


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.

Installing a PHP extension on Windows
Compiling shared PECL extensions with phpize
Installation of PECL extensions


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.

Compiling shared PECL extensions with the pecl command
php-config
Installation of PECL extensions


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 shared PECL extensions with phpize
Compiling PECL extensions statically into PHP
Installation of PECL extensions


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

php-config
Problemy?
Installation of PECL extensions


Problemy?

Spis treści

  • Przeczytaj FAQ
  • Inne problemy
  • Raporty o błędach
Compiling PECL extensions statically into PHP
Przeczytaj FAQ
Instalacja i konfiguracja


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.

Problemy?
Inne problemy
Problemy?


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.

Przeczytaj FAQ
Raporty o błędach
Problemy?


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!

Inne problemy
Runtime Configuration
Problemy?


Runtime Configuration

Spis treści

  • The configuration file
  • .user.ini files
  • Where a configuration setting may be set
  • How to change configuration settings
Raporty o błędach
The configuration file
Instalacja i konfiguracja


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

Runtime Configuration
.user.ini files
Runtime Configuration


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

The configuration file
Where a configuration setting may be set
Runtime Configuration


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

.user.ini files
How to change configuration settings
Runtime Configuration


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

Where a configuration setting may be set
Opis języka
Runtime Configuration


Opis języka

  • Podstawowa składnia
    • Wyskakiwanie z HTMLa
    • Oddzielanie instrukcji
    • Komentarze
  • Types
    • Introduction
    • Booleans
    • Integers
    • Floating point numbers
    • Strings
    • Arrays
    • Objects
    • Resources
    • NULL
    • Pseudo-types and variables used in this documentation
    • Type Juggling
  • Zmienne
    • Podstawy
    • Zmienne Predefiniowane
    • Zasięg zmiennych
    • Zmienne zmienne
    • Zmienne ze źródeł zewnętrznych
  • Stałe
    • Składnia
    • Magiczne stałe
  • Wyrażenia
  • Operators
    • Operator Precedence
    • Arithmetic Operators
    • Assignment Operators
    • Bitwise Operators
    • Comparison Operators
    • Error Control Operators
    • Execution Operators
    • Incrementing/Decrementing Operators
    • Logical Operators
    • String Operators
    • Array Operators
    • Type Operators
  • Control Structures
    • Introduction
    • if
    • else
    • elseif/else if
    • Alternative syntax for control structures
    • while
    • do-while
    • for
    • foreach
    • break
    • continue
    • switch
    • declare
    • return
    • require
    • include
    • require_once
    • include_once
    • goto
  • Funkcje
    • Funkcje definiowane przez użytkownika
    • Argumenty funkcji
    • Zwracanie wartości
    • Funkcje zmiennych
    • Wewnętrzne (wbudowane) funkcje
  • Classes and Objects
    • Introduction
    • The Basics
    • Properties
    • Class Constants
    • Autoloading Classes
    • Constructors and Destructors
    • Visibility
    • Object Inheritance
    • Scope Resolution Operator (::)
    • Static Keyword
    • Class Abstraction
    • Object Interfaces
    • Traits
    • Overloading
    • Object Iteration
    • Patterns
    • Magic Methods
    • Final Keyword
    • Object Cloning
    • Comparing Objects
    • Type Hinting
    • Late Static Bindings
    • Objects and references
    • Object Serialization
    • OOP Changelog
  • Namespaces
    • Namespaces overview
    • Defining namespaces
    • Declaring sub-namespaces
    • Defining multiple namespaces in the same file
    • Using namespaces: Basics
    • Namespaces and dynamic language features
    • namespace keyword and __NAMESPACE__ constant
    • Using namespaces: Aliasing/Importing
    • Global space
    • Using namespaces: fallback to global function/constant
    • Name resolution rules
    • FAQ: things you need to know about namespaces
  • Exceptions
    • Extending Exceptions
  • Referencje
    • Czym są referencje
    • Co robią referencje
    • Czym nie są referencje
    • Przekazywanie przez referencje
    • Zwracanie referencji
    • Niszczenie referencji
    • Znajdywanie referencji
  • Predefined Variables
    • Superglobals — Superglobals are built-in variables that are always available in all scopes
    • $GLOBALS — References all variables available in global scope
    • $_SERVER — Server and execution environment information
    • $_GET — HTTP GET variables
    • $_POST — HTTP POST variables
    • $_FILES — HTTP File Upload variables
    • $_REQUEST — HTTP Request variables
    • $_SESSION — Session variables
    • $_ENV — Environment variables
    • $_COOKIE — HTTP Cookies
    • $php_errormsg — The previous error message
    • $HTTP_RAW_POST_DATA — Raw POST data
    • $http_response_header — HTTP response headers
    • $argc — The number of arguments passed to script
    • $argv — Array of arguments passed to script
  • Predefined Exceptions
    • Exception
    • ErrorException
  • Predefined Interfaces
    • Traversable — The Traversable interface
    • Iterator — The Iterator interface
    • IteratorAggregate — The IteratorAggregate interface
    • ArrayAccess — The ArrayAccess interface
    • Serializable — The Serializable interface
    • Closure — The Closure class
  • Context options and parameters
    • Socket context options — Socket context option listing
    • HTTP context options — HTTP context option listing
    • FTP context options — FTP context option listing
    • SSL context options — SSL context option listing
    • CURL context options — CURL context option listing
    • Phar context options — Phar context option listing
    • Context parameters — Context parameter listing
  • Supported Protocols and Wrappers
    • file:// — Accessing local filesystem
    • http:// — Accessing HTTP(s) URLs
    • ftp:// — Accessing FTP(s) URLs
    • php:// — Accessing various I/O streams
    • zlib:// — Compression Streams
    • data:// — Data (RFC 2397)
    • glob:// — Find pathnames matching pattern
    • phar:// — PHP Archive
    • ssh2:// — Secure Shell 2
    • rar:// — RAR
    • ogg:// — Audio streams
    • expect:// — Process Interaction Streams
How to change configuration settings
Podstawowa składnia
Podręcznik PHP


Podstawowa składnia

Spis treści

  • Wyskakiwanie z HTMLa
  • Oddzielanie instrukcji
  • Komentarze
Opis języka
Wyskakiwanie z HTMLa
Opis języka


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.

Podstawowa składnia
Oddzielanie instrukcji
Podstawowa składnia


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.

Wyskakiwanie z HTMLa
Komentarze
Podstawowa składnia


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

Oddzielanie instrukcji
Types
Podstawowa składnia


Types

Spis treści

  • Introduction
  • Booleans
  • Integers
  • Floating point numbers
  • Strings
  • Arrays
  • Objects
  • Resources
  • NULL
  • Pseudo-types and variables used in this documentation
  • Type Juggling
Komentarze
Introduction
Opis języka


Introduction

PHP supports eight primitive types.

Four scalar types:

  • boolean
  • integer
  • float (floating-point number, aka double)
  • string

Two compound types:

  • array
  • object

And finally two special types:

  • resource
  • NULL

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

  • mixed
  • number
  • callback

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.

Types
Booleans
Types


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)
?>
Introduction
Integers
Types


Integers

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

See also:

  • Arbitrary length integer / GMP
  • Floating point numbers
  • Arbitrary precision / BCMath

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.

Booleans
Floating point numbers
Types


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 never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Converting to float

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

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

Integers
Strings
Types


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
  • double quoted
  • heredoc syntax
  • nowdoc syntax (since PHP 5.3.0)

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 = 1 + "10.5";                // $foo is float (11.5)
$foo = 1 + "-1.3e3";              // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo is integer (1)
$foo = 1 + "bob3";                // $foo is integer (1)
$foo = 1 + "10 Small Pigs";       // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1;          // $foo is float (11)
$foo = "10.0 pigs " + 1.0;        // $foo is float (11)
?>

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

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

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

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

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.

Floating point numbers
Arrays
Types


Arrays

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

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

Syntax

Specifying with array()

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

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

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

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

A value can be any PHP type.

Informacja:

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

<?php
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

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

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

<?php
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);

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

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

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

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

Creating/modifying with square bracket syntax

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

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

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

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

<?php
$arr = array(5 => 1, 12 => 2);

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

$arr["x"] = 42; // This adds a new element to
                // the array with key "x"

unset($arr[5]); // This removes the element from the array

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

Informacja:

As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).

Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);

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

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

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

Powyższy przykład wyświetli:

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

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

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

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

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(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo "\nChecking $i: \n";
    echo "Bad: " . $array['$i'] . "\n";
    echo "Good: " . $array[$i] . "\n";
    echo "Bad: {$array['$i']}\n";
    echo "Good: {$array[$i]}\n";
}
?>

Powyższy przykład wyświetli:

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

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

More examples to demonstrate this behaviour:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

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

because E_ERROR equals 1, etc.

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 A {
    private $A; // This will become '\0A\0A'
}

class B extends A {
    private $A; // This will become '\0B\0A'
    public $AA; // This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

Examples

The array type in PHP is very versatile. Here are some examples:

<?php
// This:
$a = array( 'color' => 'red',
            'taste' => 'sweet',
            'shape' => 'round',
            'name'  => 'apple',
            4        // key will be 0
          );

$b = array('a', 'b', 'c');

// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Przykład #1 Using array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              'OS'         => 'Linux',
              'lang'       => 'english',
              'short_tags' => true
            );

// strictly numerical keys
$array = array( 7,
                8,
                0,
                156,
                -10
              );
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10, // key = 0
                    5    =>  6,
                    3    =>  7,
                    'a'  =>  4,
                            11, // key = 6 (maximum of integer-indices was 5)
                    '8'  =>  2, // key = 8 (integer!)
                    '02' => 77, // key = '02'
                    0    => 12  // the value 10 will be overwritten by 12
                  );

// empty array
$empty = array();
?>

Przykład #2 Collection

<?php
$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}

?>

Powyższy przykład wyświetli:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Przykład #3 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 #4 One-based index

<?php
$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

Powyższy przykład wyświetli:

Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Przykład #5 Filling an array

<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
    $files[] = $file;
}
closedir($handle);
?>

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Przykład #6 Sorting an array

<?php
sort($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Przykład #7 Recursive and multi-dimensional arrays

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   => array (      "first",
                                       5 => "second",
                                            "third"
                                     )
                );

// Some examples to address values in the array above
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
Strings
Objects
Types


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'
?>
Arrays
Resources
Types


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.

Objects
NULL
Types


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

<?php
$var = NULL;
?>

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

Casting to NULL

Casting a variable to null will remove the variable and unset its value.

Resources
Pseudo-types and variables used in this documentation
Types


Pseudo-types and variables used in this documentation

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.

number

number indicates that a parameter can be either integer or float.

callback

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

A PHP function is passed by its name as a string. Any built-in
or user-defined function can be used, except language constructs such as:
array(), echo(),
empty(), eval(),
exit(), isset(),
list(), print() or
unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.

Przykład #1 Callback function examples

<?php

// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    static function myCallbackMethod() {
        echo 'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function');

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}

class B extends A {
    public static function who() {
        echo "B\n";
    }
}

call_user_func(array('B', 'parent::who')); // A
?>

Przykład #2 Callback example using a Closure

<?php
// Our closure
$double = function($a) {
    return $a * 2;
};

// This is our range of numbers
$numbers = range(1, 5);

// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

Powyższy przykład wyświetli:

2 4 6 8 10

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

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.

NULL
Type Juggling
Types


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 = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
?>

If the last two examples above seem odd, see String conversion to numbers.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.

To test any of the examples in this section, use the var_dump() function.

Informacja:

The behaviour of an automatic conversion to array is currently undefined.

Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    = 'car'; // $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

See the section titled String access by character for more information.

Type Casting

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:

  • Converting to boolean
  • Converting to integer
  • Converting to float
  • Converting to string
  • Converting to array
  • Converting to object
  • Converting to resource
  • Converting to NULL
  • The type comparison tables
Pseudo-types and variables used in this documentation
Zmienne
Types


Zmienne

Spis treści

  • Podstawy
  • Zmienne Predefiniowane
  • Zasięg zmiennych
  • Zmienne zmienne
  • Zmienne ze źródeł zewnętrznych
Type Juggling
Podstawy
Opis języka


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
Zmienne Predefiniowane
Zmienne


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.

Podstawy
Zasięg zmiennych
Zmienne


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 Predefiniowane
Zmienne zmienne
Zmienne


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.

Zasięg zmiennych
Zmienne ze źródeł zewnętrznych
Zmienne


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($_POST, true));
    echo '</pre>';
}
?>
<form action="" method="post">
    Nazwisko: <input type="text" name="personal[nazwisko]"><br />
    Email: <input type="text" name="personal[email]"><br />
    Piwo: <br />
    <select multiple name="piwo[]">
        <option value="zywiec">Żywiec</option>
        <option value="tyskie">Tyskie</option>
        <option value="lech">Lech</option>
    </select><br />
    <input type="submit" value="Wyślij mnie!" />
</form>

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', $ile, time()+3600);
setcookie("Cart[$ile]", $pozycja, time()+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.

Zmienne zmienne
Stałe
Zmienne


Stałe

Spis treści

  • Składnia
  • Magiczne stałe

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.

Zmienne ze źródeł zewnętrznych
Składnia
Opis języka


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.

Stałe
Magiczne stałe
Stałe


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

Składnia
Wyrażenia
Stałe


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.

Magiczne stałe
Operators
Opis języka


Operators

Spis treści

  • Operator Precedence
  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Comparison Operators
  • Error Control Operators
  • Execution Operators
  • Incrementing/Decrementing Operators
  • Logical Operators
  • String Operators
  • Array Operators
  • Type Operators

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.

Wyrażenia
Operator Precedence
Opis języka


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 = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5

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

Operators
Arithmetic Operators
Operators


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 (5 % 3)."\n";           // prints 2
echo (5 % -3)."\n";          // prints 2
echo (-5 % 3)."\n";          // prints -2
echo (-5 % -3)."\n";         // prints -2

?>

See also the manual page on Math functions.

Operator Precedence
Assignment Operators
Operators


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

/* 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.

Arithmetic Operators
Bitwise Operators
Operators


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(0, 1, 2, 4, 8);
$test = 1 + 4;

echo "\n Bitwise AND \n";
foreach ($values as $value) {
    $result = $value & $test;
    printf($format, $result, $value, '&', $test);
}

echo "\n Bitwise Inclusive OR \n";
foreach ($values as $value) {
    $result = $value | $test;
    printf($format, $result, $value, '|', $test);
}

echo "\n Bitwise Exclusive OR (XOR) \n";
foreach ($values as $value) {
    $result = $value ^ $test;
    printf($format, $result, $value, '^', $test);
}
?>

Powyższy przykład wyświetli:

 ---------     ---------  -- ---------
 result        value      op test
 ---------     ---------  -- ---------
 Bitwise AND
( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)

 Bitwise Inclusive OR
( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101)
( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101)
( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) | ( 5 = 0101)

 Bitwise Exclusive OR (XOR)
( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101)
( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101)
( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)

Przykład #2 Bitwise XOR operations on strings

<?php
echo 12 ^ 9; // Outputs '5'

echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4

echo 2 ^ "3"; // Outputs 1
              // 2 ^ ((int)"3") == 1

echo "2" ^ 3; // Outputs 1
              // ((int)"2") ^ 3 == 1
?>

Przykład #3 Bit shifting on integers

<?php
/*
 * Here are the examples.
 */

echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = 4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places);

$val = 4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = 4;
$places = 4;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0');

echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1');

echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 4;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = 4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places, 'sign bits get shifted out');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side');

echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = -4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = -4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side, including sign bit');

/*
 * Ignore this bottom section,
 * it is just formatting to make output clearer.
 */

function p($res, $val, $op, $places, $note = '') {
    $format = '%0' . (PHP_INT_SIZE * 8) . "b\n";

    printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);

    echo " Decimal:\n";
    printf("  val=%d\n", $val);
    printf("  res=%d\n", $res);

    echo " Binary:\n";
    printf('  val=' . $format, $val);
    printf('  res=' . $format, $res);

    if ($note) {
        echo " NOTE: $note\n";
    }

    echo "\n";
}
?>

Wyświetla następujący przykład na systemach 32 bitowych:

--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 1073741824 = 4 << 28
 Decimal:
  val=4
  res=1073741824
 Binary:
  val=00000000000000000000000000000100
  res=01000000000000000000000000000000

Expression: -2147483648 = 4 << 29
 Decimal:
  val=4
  res=-2147483648
 Binary:
  val=00000000000000000000000000000100
  res=10000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 30
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -2147483648 = -4 << 29
 Decimal:
  val=-4
  res=-2147483648
 Binary:
  val=11111111111111111111111111111100
  res=10000000000000000000000000000000

Expression: 0 = -4 << 30
 Decimal:
  val=-4
  res=0
 Binary:
  val=11111111111111111111111111111100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

Wyświetla następujący przykład na systemach 64 bitowych:

--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 4611686018427387904 = 4 << 60
 Decimal:
  val=4
  res=4611686018427387904
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0100000000000000000000000000000000000000000000000000000000000000

Expression: -9223372036854775808 = 4 << 61
 Decimal:
  val=4
  res=-9223372036854775808
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=1000000000000000000000000000000000000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 62
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -9223372036854775808 = -4 << 61
 Decimal:
  val=-4
  res=-9223372036854775808
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1000000000000000000000000000000000000000000000000000000000000000

Expression: 0 = -4 << 62
 Decimal:
  val=-4
  res=0
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

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

Assignment Operators
Comparison Operators
Operators


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(0 == "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.
?>

Bitwise Operators
Error Control Operators
Operators


Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Informacja: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

See also error_reporting() and the manual section for Error Handling and Logging functions.

Ostrzeżenie

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

Comparison Operators
Execution Operators
Operators


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.

Error Control Operators
Incrementing/Decrementing Operators
Operators


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.

Execution Operators
Logical Operators
Operators


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)
Incrementing/Decrementing Operators
String Operators
Operators


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.

Logical Operators
Array Operators
Operators


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(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

See also the manual sections on the Array type and Array functions.

String Operators
Type Operators
Operators


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

Array Operators
Control Structures
Operators


Control Structures

Spis treści

  • Introduction
  • if
  • else
  • elseif/else if
  • Alternative syntax for control structures
  • while
  • do-while
  • for
  • foreach
  • break
  • continue
  • switch
  • declare
  • return
  • require
  • include
  • require_once
  • include_once
  • goto
Type Operators
Introduction
Opis języka


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.

Control Structures
if
Control Structures


if

(PHP 4, PHP5)

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.

Introduction
else
Control Structures


else

(PHP 4, PHP5)

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

if
elseif/else if
Control Structures


elseif/else if

(PHP 4, PHP5)

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;

?>

else
Alternative syntax for control structures
Control Structures


Alternative syntax for control structures

(PHP 4, PHP5)

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.

elseif/else if
while
Control Structures


while

(PHP 4, PHP5)

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

Alternative syntax for control structures
do-while
Control Structures


do-while

(PHP 4, PHP5)

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.

while
for
Control Structures


for

(PHP 4, PHP5)

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3)
    statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

/* example 2 */

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}

/* example 3 */

$i = 1;
for (; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i;
    $i++;
}

/* example 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):
    statement
    ...
endfor;

Its a common thing to many users to iterate though arrays like in the example below.

<?php
/*
* This is an array with some data we want to modify
* when running through the for loop.
*/
$people = Array(
        Array('name' => 'Kalle', 'salt' => 856412),
        Array('name' => 'Pierre', 'salt' => 215863)
        );

for($i = 0; $i < sizeof($people); ++$i)
{
    $people[$i]['salt'] = rand(000000, 999999);
}
?>

The problem lies in the second for expression. This code can be slow because it has to calculate the size of the array on each iteration. Since the size never change, it can be optimized easily using an intermediate variable to store the size and use in the loop instead of sizeof. The example below illustrates this:

<?php
$people = Array(
        Array('name' => 'Kalle', 'salt' => 856412),
        Array('name' => 'Pierre', 'salt' => 215863)
        );

for($i = 0, $size = sizeof($people); $i < $size; ++$i)
{
    $people[$i]['salt'] = rand(000000, 999999);
}
?>

do-while
foreach
Control Structures


foreach

(PHP 4, PHP5)

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(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

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(1, 2, 3, 4) 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(1, 2, 3, 17);

foreach ($a as $v) {
    echo "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with its manual access notation printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "\$a[$i] => $v.\n";
    $i++;
}

/* foreach example 3: key and value */

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
    echo "$v\n";
}
?>

for
break
Control Structures


break

(PHP 4, PHP5)

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

foreach
continue
Control Structures


continue

(PHP 4, PHP5)

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

break
switch
Control Structures


switch

(PHP 4, PHP5)

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

continue
declare
Control Structures


declare

(PHP 4, PHP5)

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

switch
return
Control Structures


return

(PHP 4, PHP5)

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

declare
require
Control Structures


require

return
include
Control Structures
PHP Manual

require()

(PHP 4, PHP5)

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.

return
include
Control Structures


include

require
require_once
Control Structures
PHP Manual

include()

(PHP 4, PHP5)

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
require_once
Control Structures


require_once

include
include_once
Control Structures
PHP Manual

require_once()

(PHP 4, PHP5)

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
include_once
Control Structures


include_once

require_once
goto
Control Structures
PHP Manual

include_once()

(PHP 4, PHP5)

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.

require_once
goto
Control Structures


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

include_once
Funkcje
Control Structures


Funkcje

Spis treści

  • Funkcje definiowane przez użytkownika
  • Argumenty funkcji
  • Zwracanie wartości
  • Funkcje zmiennych
  • Wewnętrzne (wbudowane) funkcje
goto
Funkcje definiowane przez użytkownika
Opis języka


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 ($makefoo) foo();

function bar()
{
  echo "Istnieję od początku działania skryptu.\n";
}

?>

Przykład #3 Funkcje wewnątrz funkcji

<?php
function foo()
{
  function bar()
  {
    echo "Nie istnieję, dopóki foo() nie jest wywołana.\n";
  }
}

/* Nie możemy tu wywołać bar()
   ponieważ jeszcze nie istnieje. */

foo();

/* Teraz możemy wywołać bar(),
   wykonanie foo() spodowało
   że jest to już możliwe. */

bar();

?>

Wszystkie funkcje i klasy w PHP mają globalny zasięg - mogą być wykonane poza funkcją, nawet jeśli były zdefiniowane wewnątrz niej, i odwrotnie.

PHP nie umożliwia przeładowywania funkcji, nie jest też możliwe usunięcie jej definicji lub redefiniowanie poprzednio określonych funkcji.

Informacja: Nazwy funkcji nie rozróżniają wielkości liter, ale dobrym zwyczajem jest wywoływanie ich w formie, w której zostały zdefiniowane.

Zarówno przyjmowanie różnej ilości argumentów jak i wartości domyślne argumentów są obsługiwane w funkcjach. Zobacz także opisy funkcji func_num_args(), func_get_arg(), i func_get_args() aby uzyskać więcej informacji.

W PHP jest możliwe wykonywanie rekurencyjnych funkcji. Unikaj jednak wywoływania rekurencyjnych funkcji/metod które osiągają poziom rekurencji większy niż 100-200, ponieważ może to spowodować przepełnienie stosu i zakończenie wykonywania skryptu.

Przykład #4 Funkcje rekurencyjne

<?php
function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}
?>

Funkcje
Argumenty funkcji
Funkcje


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.

Funkcje definiowane przez użytkownika
Zwracanie wartości
Funkcje


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 (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

Aby zwrócić referencję, użyj operatora & zarówno w deklaracji funkcji jak i podczas przypisywania zwracanej wartości zmiennej:

Przykład #3 Zwracanie referencji

<?php
function &returns_reference()
{
    return $someref;
}

$newref =& returns_reference();
?>

Aby uzyskać więcej informacji o referencjach, przejdź do Wyjaśnienie Referencji.

Argumenty funkcji
Funkcje zmiennych
Funkcje


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

Zwracanie wartości
Wewnętrzne (wbudowane) funkcje
Funkcje


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

Funkcje zmiennych
Classes and Objects
Funkcje


Classes and Objects

Spis treści

  • Introduction
  • The Basics
  • Properties
  • Class Constants
  • Autoloading Classes
  • Constructors and Destructors
  • Visibility
  • Object Inheritance
  • Scope Resolution Operator (::)
  • Static Keyword
  • Class Abstraction
  • Object Interfaces
  • Traits
  • Overloading
  • Object Iteration
  • Patterns
  • Magic Methods
  • Final Keyword
  • Object Cloning
  • Comparing Objects
  • Type Hinting
  • Late Static Bindings
  • Objects and references
  • Object Serialization
  • OOP Changelog
Wewnętrzne (wbudowane) funkcje
Introduction
Opis języka


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.

Classes and Objects
The Basics
Classes and Objects


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
Introduction
Properties
Classes and Objects


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(true, false);

   // This is allowed only in PHP 5.3.0 and later.
   public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Informacja:

There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Unlike heredocs, nowdocs can be used in any static data context, including property declarations.

Przykład #2 Example of using a nowdoc to initialize a property

<?php
class foo {
   // As of PHP 5.3.0
   public $bar = <<<'EOT'
bar
EOT;
}
?>

Informacja:

Nowdoc support was added in PHP 5.3.0.

The Basics
Class Constants
Classes and Objects


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.

Properties
Autoloading Classes
Classes and Objects


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

Zobacz też:

  • unserialize()
  • unserialize_callback_func
  • spl_autoload()
  • spl_autoload_register()

Class Constants
Constructors and Destructors
Classes and Objects


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.

Autoloading Classes
Visibility
Classes and Objects


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.
Constructors and Destructors
Object Inheritance
Classes and Objects


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

?>
Visibility
Scope Resolution Operator (::)
Classes and Objects


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.

Object Inheritance
Static Keyword
Classes and Objects


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
?>
Scope Resolution Operator (::)
Class Abstraction
Classes and Objects


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.

Static Keyword
Object Interfaces
Classes and Objects


Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

implements

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Informacja:

A class cannot implement two interfaces that share function names, since it would cause ambiguity.

Informacja:

Interfaces can be extended like classes using the extends operator.

Informacja:

The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

Constants

Its possible for interfaces to have constants. Interface constants works exactly like class constants except they cannot be overridden by a class/interface that inherits it.

Przykłady

Przykład #1 Interface example

<?php

// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }

    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }

        return $template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
}
?>

Przykład #2 Extendable Interfaces

<?php
interface a
{
    public function foo();
}

interface b extends a
{
    public function baz(Baz $baz);
}

// This will work
class c implements b
{
    public function foo()
    {
    }

    public function baz(Baz $baz)
    {
    }
}

// This will not work and result in a fatal error
class d implements b
{
    public function foo()
    {
    }

    public function baz(Foo $foo)
    {
    }
}
?>

Przykład #3 Multiple interface inheritance

<?php
interface a
{
    public function foo();
}

interface b
{
    public function bar();
}

interface c extends a, b
{
    public function baz();
}

class d implements c
{
    public function foo()
    {
    }

    public function bar()
    {
    }

    public function baz()
    {
    }
}
?>

Przykład #4 Interfaces with constants

<?php
interface a
{
    const b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

// This will however not work because its not allowed to
// override constants.
class b implements a
{
    const b = 'Class constant';
}
?>

An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.

Class Abstraction
Traits
Classes and Objects


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 Hello, World;
    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 {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}

class Aliased_Talker {
    use A, B {
        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 Hello, World;
}

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
}
?>
Object Interfaces
Overloading
Classes and Objects


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->a = 1;
echo $obj->a . "\n\n";

var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";

echo $obj->declared . "\n\n";

echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>

Powyższy przykład wyświetli:

Setting 'a' to '1'
Getting 'a'
1

Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)

1

Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'

Notice:  Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

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
Traits
Object Iteration
Classes and Objects


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.

Overloading
Patterns
Classes and Objects


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.

Object Iteration
Magic Methods
Classes and Objects


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($a, true) . ';'); // $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"
}
Patterns
Final Keyword
Classes and Objects


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.

Magic Methods
Object Cloning
Classes and Objects


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
        )

)
Final Keyword
Comparing Objects
Classes and Objects


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.

Object Cloning
Type Hinting
Classes and Objects


Type Hinting

PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

Przykład #1 Type Hinting examples

<?php
// An example class
class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }

    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}
?>

Failing to satisfy the type hint results in a catchable fatal error.

<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);

// Fatal Error: Argument 1 must not be null
$myclass->test(null);

// Works: Prints Hello World
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');

// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
?>

Type hinting also works with functions:

<?php
// An example class
class MyClass {
    public $var = 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function MyFunction (MyClass $foo) {
    echo $foo->var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?>

Type hinting allowing NULL value:

<?php

/* Accepting NULL value */
function test(stdClass $obj = NULL) {

}

test(NULL);
test(new stdClass);

?>

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

Comparing Objects
Late Static Bindings
Classes and Objects


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 A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

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 A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Here comes Late Static Bindings
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

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 A {
    private function foo() {
        echo "success!\n";
    }
    public function test() {
        $this->foo();
        static::foo();
    }
}

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

class C extends A {
    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 A {
    public static function foo() {
        static::who();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}

class B extends A {
    public static function test() {
        A::foo();
        parent::foo();
        self::foo();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}
class C extends B {
    public static function who() {
        echo __CLASS__."\n";
    }
}

C::test();
?>

Powyższy przykład wyświetli:

A
C
C

Type Hinting
Objects and references
Classes and Objects


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 A {
    public $foo = 1;
}

$a = new A;
$b = $a;     // $a and $b are copies of the same identifier
             // ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";

$c = new A;
$d = &$c;    // $c and $d are references
             // ($c,$d) = <id>

$d->foo = 2;
echo $c->foo."\n";

$e = new A;

function foo($obj) {
    // ($obj) = ($e) = <id>
    $obj->foo = 2;
}

foo($e);
echo $e->foo."\n";

?>

Powyższy przykład wyświetli:

2
2
2
Late Static Bindings
Object Serialization
Classes and Objects


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 A {
      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 include the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of __PHP_Incomplete_Class_Name, which has no methods and would render the object useless.

So if in the example above $a became part of a session by running session_register("a"), you should include the file classa.inc on all of your pages, not only page1.php and page2.php.

Objects and references
OOP Changelog
Classes and Objects


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.

Object Serialization
Namespaces
Classes and Objects


Namespaces

Spis treści

  • Namespaces overview
  • Defining namespaces
  • Declaring sub-namespaces
  • Defining multiple namespaces in the same file
  • Using namespaces: Basics
  • Namespaces and dynamic language features
  • namespace keyword and __NAMESPACE__ constant
  • Using namespaces: Aliasing/Importing
  • Global space
  • Using namespaces: fallback to global function/constant
  • Name resolution rules
  • FAQ: things you need to know about namespaces
OOP Changelog
Namespaces overview
Opis języka


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.

Namespaces
Defining namespaces
Namespaces


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.

Namespaces overview
Declaring sub-namespaces
Namespaces


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 namespaces
Defining multiple namespaces in the same file
Namespaces


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

Declaring sub-namespaces
Using namespaces: Basics
Namespaces


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

Defining multiple namespaces in the same file
Namespaces and dynamic language features
Namespaces


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.

Using namespaces: Basics
namespace keyword and __NAMESPACE__ constant
Namespaces


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

Namespaces and dynamic language features
Using namespaces: Aliasing/Importing
Namespaces


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 Another, My\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 Another, My\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 Another, My\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.

namespace keyword and __NAMESPACE__ constant
Global space
Namespaces


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: Aliasing/Importing
Using namespaces: fallback to global function/constant
Namespaces


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

Global space
Name resolution rules
Namespaces


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\D, C\E 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"
?>
Using namespaces: fallback to global function/constant
FAQ: things you need to know about namespaces
Namespaces


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

Name resolution rules
Exceptions
Namespaces


Exceptions

Spis treści

  • Extending Exceptions

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!"
FAQ: things you need to know about namespaces
Extending Exceptions
Opis języka


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 = 0, Exception $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 = 0, Exception $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";
    }
}
?>

Exceptions
Referencje
Exceptions


Referencje

Spis treści

  • Czym są referencje
  • Co robią referencje
  • Czym nie są referencje
  • Przekazywanie przez referencje
  • Zwracanie referencji
  • Niszczenie referencji
  • Znajdywanie referencji
Extending Exceptions
Czym są referencje
Opis języka


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.

Referencje
Co robią referencje
Referencje


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 są referencje
Czym nie są referencje
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).

Co robią referencje
Przekazywanie przez referencje
Referencje


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.

Czym nie są referencje
Zwracanie referencji
Referencje


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->x = 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.

Przekazywanie przez referencje
Niszczenie referencji
Referencje


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.

Zwracanie referencji
Znajdywanie referencji
Referencje


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

Niszczenie referencji
Predefined Variables
Referencje


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

Spis treści

  • Superglobals — Superglobals are built-in variables that are always available in all scopes
  • $GLOBALS — References all variables available in global scope
  • $_SERVER — Server and execution environment information
  • $_GET — HTTP GET variables
  • $_POST — HTTP POST variables
  • $_FILES — HTTP File Upload variables
  • $_REQUEST — HTTP Request variables
  • $_SESSION — Session variables
  • $_ENV — Environment variables
  • $_COOKIE — HTTP Cookies
  • $php_errormsg — The previous error message
  • $HTTP_RAW_POST_DATA — Raw POST data
  • $http_response_header — HTTP response headers
  • $argc — The number of arguments passed to script
  • $argv — Array of arguments passed to script
Znajdywanie referencji
Superglobals
Opis języka


Superglobals are built-in variables that are always available in all scopes

Predefined Variables
$GLOBALS
Predefined Variables
PHP Manual

Superglobals

Superglobals — Superglobals 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:

  • $GLOBALS
  • $_SERVER
  • $_GET
  • $_POST
  • $_FILES
  • $_COOKIE
  • $_SESSION
  • $_REQUEST
  • $_ENV

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.

Zobacz też:

  • variable scope
  • The variables_order directive
  • The filter extension

Predefined Variables
$GLOBALS
Predefined Variables


References all variables available in global scope

Superglobals
$_SERVER
Predefined Variables
PHP Manual

$GLOBALS

(PHP 4, PHP 5)

$GLOBALS — References 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.

Superglobals
$_SERVER
Predefined Variables


Server and execution environment information

$GLOBALS
$_GET
Predefined Variables
PHP Manual

$_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. It is float with microseconds 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ż:

  • The filter extension

$GLOBALS
$_GET
Predefined Variables


HTTP GET variables

$_SERVER
$_POST
Predefined Variables
PHP Manual

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

Zobacz też:

  • Handling external variables
  • The filter extension

$_SERVER
$_POST
Predefined Variables


HTTP POST variables

$_GET
$_FILES
Predefined Variables
PHP Manual

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

Zobacz też:

  • Handling external variables
  • The filter extension

$_GET
$_FILES
Predefined Variables


HTTP File Upload variables

$_POST
$_REQUEST
Predefined Variables
PHP Manual

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

  • move_uploaded_file() - Przenieś uploadowany plik do innej lokalizacji
  • Handling File Uploads

$_POST
$_REQUEST
Predefined Variables


HTTP Request variables

$_FILES
$_SESSION
Predefined Variables
PHP Manual

$_REQUEST

(PHP 4 >= 4.1.0, PHP 5)

$_REQUEST — HTTP 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ż:

  • import_request_variables() - Import GET/POST/Cookie variables into the global scope
  • Handling external variables
  • The filter extension
$_FILES
$_SESSION
Predefined Variables


Session variables

$_REQUEST
$_ENV
Predefined Variables
PHP Manual

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

  • session_start() - Inicjalizuj dane sesji

$_REQUEST
$_ENV
Predefined Variables


Environment variables

$_SESSION
$_COOKIE
Predefined Variables
PHP Manual

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

  • getenv() - Gets the value of an environment variable
  • The filter extension

$_SESSION
$_COOKIE
Predefined Variables


HTTP Cookies

$_ENV
$php_errormsg
Predefined Variables
PHP Manual

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

Zobacz też:

  • setcookie() - Send a cookie
  • Handling external variables
  • The filter extension

$_ENV
$php_errormsg
Predefined Variables


The previous error message

$_COOKIE
$HTTP_RAW_POST_DATA
Predefined Variables
PHP Manual

$php_errormsg

(PHP 4, PHP 5)

$php_errormsg — The 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()

$_COOKIE
$HTTP_RAW_POST_DATA
Predefined Variables


Raw POST data

$php_errormsg
$http_response_header
Predefined Variables
PHP Manual

$HTTP_RAW_POST_DATA

(PHP 4, PHP 5)

$HTTP_RAW_POST_DATA — Raw POST data

Opis

$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data

$php_errormsg
$http_response_header
Predefined Variables


HTTP response headers

$HTTP_RAW_POST_DATA
$argc
Predefined Variables
PHP Manual

$http_response_header

(PHP 4 >= 4.0.4, PHP 5)

$http_response_header — HTTP 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

$HTTP_RAW_POST_DATA
$argc
Predefined Variables


The number of arguments passed to script

$http_response_header
$argv
Predefined Variables
PHP Manual

$argc

(PHP 4, PHP 5)

$argc — The 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)

$http_response_header
$argv
Predefined Variables


Array of arguments passed to script

$argc
Predefined Exceptions
Predefined Variables
PHP Manual

$argv

(PHP 4, PHP 5)

$argv — Array 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

$argc
Predefined Exceptions
Predefined Variables


Predefined Exceptions

Spis treści

  • Exception
  • ErrorException

See also the SPL Exceptions

$argv
Exception
Opis języka


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

Spis treści

  • Exception::__construct — Construct the exception
  • Exception::getMessage — Gets the Exception message
  • Exception::getPrevious — Returns previous Exception
  • Exception::getCode — Gets the Exception code
  • Exception::getFile — Gets the file in which the exception occurred
  • Exception::getLine — Gets the line in which the exception occurred
  • Exception::getTrace — Gets the stack trace
  • Exception::getTraceAsString — Gets the stack trace as a string
  • Exception::__toString — String representation of the exception
  • Exception::__clone — Clone the exception
Predefined Exceptions
Exception::__construct
Predefined Exceptions


Construct the exception

Exception
Exception::getMessage
Exception
PHP Manual

Exception::__construct

(PHP 5 >= 5.1.0)

Exception::__construct — Construct 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
Exception::getMessage
Exception


Gets the Exception message

Exception::__construct
Exception::getPrevious
Exception
PHP Manual

Exception::getMessage

(PHP 5 >= 5.1.0)

Exception::getMessage — Gets 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::__construct
Exception::getPrevious
Exception


Returns previous Exception

Exception::getMessage
Exception::getCode
Exception
PHP Manual

Exception::getPrevious

(PHP 5 >= 5.3.0)

Exception::getPrevious — Returns 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::getMessage
Exception::getCode
Exception


Gets the Exception code

Exception::getPrevious
Exception::getFile
Exception
PHP Manual

Exception::getCode

(PHP 5 >= 5.1.0)

Exception::getCode — Gets 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::getPrevious
Exception::getFile
Exception


Gets the file in which the exception occurred

Exception::getCode
Exception::getLine
Exception
PHP Manual

Exception::getFile

(PHP 5 >= 5.1.0)

Exception::getFile — Gets 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::getCode
Exception::getLine
Exception


Gets the line in which the exception occurred

Exception::getFile
Exception::getTrace
Exception
PHP Manual

Exception::getLine

(PHP 5 >= 5.1.0)

Exception::getLine — Gets 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::getFile
Exception::getTrace
Exception


Gets the stack trace

Exception::getLine
Exception::getTraceAsString
Exception
PHP Manual

Exception::getTrace

(PHP 5 >= 5.1.0)

Exception::getTrace — Gets 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::getLine
Exception::getTraceAsString
Exception


Gets the stack trace as a string

Exception::getTrace
Exception::__toString
Exception
PHP Manual

Exception::getTraceAsString

(PHP 5 >= 5.1.0)

Exception::getTraceAsString — Gets 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::getTrace
Exception::__toString
Exception


String representation of the exception

Exception::getTraceAsString
Exception::__clone
Exception
PHP Manual

Exception::__toString

(PHP 5 >= 5.1.0)

Exception::__toString — String 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::getTraceAsString
Exception::__clone
Exception


Clone the exception

Exception::__toString
ErrorException
Exception
PHP Manual

Exception::__clone

(PHP 5 >= 5.1.0)

Exception::__clone — Clone 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.

Exception::__toString
ErrorException
Exception


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($errstr, 0, $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

Spis treści

  • ErrorException::__construct — Constructs the exception
  • ErrorException::getSeverity — Gets the exception severity
Exception::__clone
ErrorException::__construct
Predefined Exceptions


Constructs the exception

ErrorException
ErrorException::getSeverity
ErrorException
PHP Manual

ErrorException::__construct

(PHP 5 >= 5.1.0)

ErrorException::__construct — Constructs 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
ErrorException::getSeverity
ErrorException


Gets the exception severity

ErrorException::__construct
Predefined Interfaces
ErrorException
PHP Manual

ErrorException::getSeverity

(PHP 5 >= 5.1.0)

ErrorException::getSeverity — Gets 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", 0, 75);
} catch(ErrorException $e) {
    echo "This exception severity is: " . $e->getSeverity();
}
?>

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

This exception severity is: 75

ErrorException::__construct
Predefined Interfaces
ErrorException


Predefined Interfaces

Spis treści

  • Traversable
  • Iterator
  • IteratorAggregate
  • ArrayAccess
  • Serializable
  • Closure

See also the SPL Interfaces

ErrorException::getSeverity
Traversable
Opis języka


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.

Predefined Interfaces
Iterator
Predefined Interfaces


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

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"

Spis treści

  • Iterator::current — Return the current element
  • Iterator::key — Return the key of the current element
  • Iterator::next — Move forward to next element
  • Iterator::rewind — Rewind the Iterator to the first element
  • Iterator::valid — Checks if current position is valid
Traversable
Iterator::current
Predefined Interfaces


Return the current element

Iterator
Iterator::key
Iterator
PHP Manual

Iterator::current

(PHP 5 >= 5.0.0)

Iterator::current — Return 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
Iterator::key
Iterator


Return the key of the current element

Iterator::current
Iterator::next
Iterator
PHP Manual

Iterator::key

(PHP 5 >= 5.0.0)

Iterator::key — Return 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::current
Iterator::next
Iterator


Move forward to next element

Iterator::key
Iterator::rewind
Iterator
PHP Manual

Iterator::next

(PHP 5 >= 5.0.0)

Iterator::next — Move 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::key
Iterator::rewind
Iterator


Rewind the Iterator to the first element

Iterator::next
Iterator::valid
Iterator
PHP Manual

Iterator::rewind

(PHP 5 >= 5.0.0)

Iterator::rewind — Rewind 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::next
Iterator::valid
Iterator


Checks if current position is valid

Iterator::rewind
IteratorAggregate
Iterator
PHP Manual

Iterator::valid

(PHP 5 >= 5.0.0)

Iterator::valid — Checks 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.

Iterator::rewind
IteratorAggregate
Iterator


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"

Spis treści

  • IteratorAggregate::getIterator — Retrieve an external iterator
Iterator::valid
IteratorAggregate::getIterator
Predefined Interfaces


Retrieve an external iterator

IteratorAggregate
ArrayAccess
IteratorAggregate
PHP Manual

IteratorAggregate::getIterator

(PHP 5 >= 5.0.0)

IteratorAggregate::getIterator — Retrieve 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.

IteratorAggregate
ArrayAccess
IteratorAggregate


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
        )

)

Spis treści

  • ArrayAccess::offsetExists — Whether a offset exists
  • ArrayAccess::offsetGet — Offset to retrieve
  • ArrayAccess::offsetSet — Offset to set
  • ArrayAccess::offsetUnset — Offset to unset
IteratorAggregate::getIterator
ArrayAccess::offsetExists
Predefined Interfaces


Whether a offset exists

ArrayAccess
ArrayAccess::offsetGet
ArrayAccess
PHP Manual

ArrayAccess::offsetExists

(PHP 5 >= 5.0.0)

ArrayAccess::offsetExists — Whether 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
ArrayAccess::offsetGet
ArrayAccess


Offset to retrieve

ArrayAccess::offsetExists
ArrayAccess::offsetSet
ArrayAccess
PHP Manual

ArrayAccess::offsetGet

(PHP 5 >= 5.0.0)

ArrayAccess::offsetGet — Offset 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::offsetExists() - Whether a offset exists

ArrayAccess::offsetExists
ArrayAccess::offsetSet
ArrayAccess


Offset to set

ArrayAccess::offsetGet
ArrayAccess::offsetUnset
ArrayAccess
PHP Manual

ArrayAccess::offsetSet

(PHP 5 >= 5.0.0)

ArrayAccess::offsetSet — Offset 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::offsetGet
ArrayAccess::offsetUnset
ArrayAccess


Offset to unset

ArrayAccess::offsetSet
Serializable
ArrayAccess
PHP Manual

ArrayAccess::offsetUnset

(PHP 5 >= 5.0.0)

ArrayAccess::offsetUnset — Offset 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ść.

ArrayAccess::offsetSet
Serializable
ArrayAccess


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 mixed unserialize ( string $serialized )
}

Przykład #1 Basic usage

<?php
class obj implements Serializable {
    private $data;
    public function __construct() {
        $this->data = "My private data";
    }
    public function serialize() {
        return serialize($this->data);
    }
    public function unserialize($data) {
        $this->data = unserialize($data);
    }
    public function getData() {
        return $this->data;
    }
}

$obj = new obj;
$ser = serialize($obj);

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"

Spis treści

  • Serializable::serialize — String representation of object
  • Serializable::unserialize — Constructs the object
ArrayAccess::offsetUnset
Serializable::serialize
Predefined Interfaces


String representation of object

Serializable
Serializable::unserialize
Serializable
PHP Manual

Serializable::serialize

(PHP 5 >= 5.1.0)

Serializable::serialize — String 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ż:

  • __sleep()

Serializable
Serializable::unserialize
Serializable


Constructs the object

Serializable::serialize
Closure
Serializable
PHP Manual

Serializable::unserialize

(PHP 5 >= 5.1.0)

Serializable::unserialize — Constructs the object

Opis

abstract public mixed Serializable::unserialize ( string $serialized )

Called during unserialization of the object.

Informacja:

This method acts as the constructor of the object. The __construct() method will not be called after this method.

Parametry

serialized

The string representation of the object.

Zwracane wartości

Returns the original value unserialized.

Zobacz też:

  • __wakeup()

Serializable::serialize
Closure
Serializable


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' ] )
}

Spis treści

  • Closure::__construct — Constructor that disallows instantiation
  • Closure::bind — Duplicates a closure with a specific bound object and class scope
  • Closure::bindTo — Duplicates the closure with a new bound object and class scope
Serializable::unserialize
Closure::__construct
Predefined Interfaces


Constructor that disallows instantiation

Closure
Closure::bind
Closure
PHP Manual

Closure::__construct

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

Closure::__construct — Constructor 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ż:

  • Anonymous functions
Closure
Closure::bind
Closure


Duplicates a closure with a specific bound object and class scope

Closure::__construct
Closure::bindTo
Closure
PHP Manual

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 A {
    private static $sfoo = 1;
    private $ifoo = 2;
}
$cl1 = static function() {
    return A::$sfoo;
};
$cl2 = function() {
    return $this->ifoo;
};

$bcl1 = Closure::bind($cl1, null, '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ż:

  • Anonymous functions
  • Closure::bindTo() - Duplicates the closure with a new bound object and class scope
Closure::__construct
Closure::bindTo
Closure


Duplicates the closure with a new bound object and class scope

Closure::bind
Context options and parameters
Closure
PHP Manual

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 A {
    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ż:

  • Anonymous functions
  • Closure::bind() - Duplicates a closure with a specific bound object and class scope
Closure::bind
Context options and parameters
Closure


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

Spis treści

  • Socket context options — Socket context option listing
  • HTTP context options — HTTP context option listing
  • FTP context options — FTP context option listing
  • SSL context options — SSL context option listing
  • CURL context options — CURL context option listing
  • Phar context options — Phar context option listing
  • Context parameters — Context parameter listing
Closure::bindTo
Socket context options
Opis języka


Socket context option listing

Context options and parameters
HTTP context options
Context options and parameters
PHP Manual

Socket context options

Socket context options — Socket 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);

?>

Context options and parameters
HTTP context options
Context options and parameters


HTTP context option listing

Socket context options
FTP context options
Context options and parameters
PHP Manual

HTTP context options

HTTP context options — HTTP 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).

Zobacz też:

  • http://
  • Socket context options
  • SSL context options

Socket context options
FTP context options
Context options and parameters


FTP context option listing

HTTP context options
SSL context options
Context options and parameters
PHP Manual

FTP context options

FTP context options — FTP 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.

Zobacz też:

  • ftp://
  • Socket context options
  • SSL context options

HTTP context options
SSL context options
Context options and parameters


SSL context option listing

FTP context options
CURL context options
Context options and parameters
PHP Manual

SSL context options

SSL context options — SSL 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ż:

  • Socket context options

FTP context options
CURL context options
Context options and parameters


CURL context option listing

SSL context options
Phar context options
Context options and parameters
PHP Manual

CURL context options

CURL context options — CURL 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ż:

  • Socket context options

SSL context options
Phar context options
Context options and parameters


Phar context option listing

CURL context options
Context parameters
Context options and parameters
PHP Manual

Phar context options

Phar context options — Phar context option listing

Opis

Context options for phar:// wrapper.

Opcje

compress int

One of Phar compression constants.

metadata mixed

Phar metadata. See Phar::setMetadata().

Zobacz też:

  • phar://
  • Phar stream wrapper

CURL context options
Context parameters
Context options and parameters


Context parameter listing

Phar context options
Supported Protocols and Wrappers
Context options and parameters
PHP Manual

Context parameters

Context parameters — Context parameter listing

Opis

These parameters can be set on a context using the stream_context_set_params() function.

Parametry

notification callback

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

See stream_notification_callback() for more details.

Phar context options
Supported Protocols and Wrappers
Context options and parameters


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.

Spis treści

  • file:// — Accessing local filesystem
  • http:// — Accessing HTTP(s) URLs
  • ftp:// — Accessing FTP(s) URLs
  • php:// — Accessing various I/O streams
  • zlib:// — Compression Streams
  • data:// — Data (RFC 2397)
  • glob:// — Find pathnames matching pattern
  • phar:// — PHP Archive
  • ssh2:// — Secure Shell 2
  • rar:// — RAR
  • ogg:// — Audio streams
  • expect:// — Process Interaction Streams
Context parameters
file://
Opis języka


Accessing local filesystem

Supported Protocols and Wrappers
http://
Supported Protocols and Wrappers
PHP Manual

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

Supported Protocols and Wrappers
http://
Supported Protocols and Wrappers


Accessing HTTP(s) URLs

file://
ftp://
Supported Protocols and Wrappers
PHP Manual

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($response, 0, 10)) == 'location: ') {

        /* update $url with where we were redirected to */
        $url = substr($response, 10);
    }

}

?>

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

  • HTTP context options
  • $http_response_header
  • stream_get_meta_data() - Retrieves header/meta data from streams/file pointers
file://
ftp://
Supported Protocols and Wrappers


Accessing FTP(s) URLs

http://
php://
Supported Protocols and Wrappers
PHP Manual

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

  • FTP context options
http://
php://
Supported Protocols and Wrappers


Accessing various I/O streams

ftp://
zlib://
Supported Protocols and Wrappers
PHP Manual

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 = 5 * 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");
?>
ftp://
zlib://
Supported Protocols and Wrappers


Compression Streams

php://
data://
Supported Protocols and Wrappers
PHP Manual

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

php://
data://
Supported Protocols and Wrappers


Data (RFC 2397)

zlib://
glob://
Supported Protocols and Wrappers
PHP Manual

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'];
?>
zlib://
glob://
Supported Protocols and Wrappers


Find pathnames matching pattern

data://
phar://
Supported Protocols and Wrappers
PHP Manual

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
data://
phar://
Supported Protocols and Wrappers


PHP Archive

glob://
ssh2://
Supported Protocols and Wrappers
PHP Manual

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

  • Phar context options
glob://
ssh2://
Supported Protocols and Wrappers


Secure Shell 2

phar://
rar://
Supported Protocols and Wrappers
PHP Manual

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');
?>
phar://
rar://
Supported Protocols and Wrappers


RAR

ssh2://
ogg://
Supported Protocols and Wrappers
PHP Manual

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 inidivual 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
)
ssh2://
ogg://
Supported Protocols and Wrappers


Audio streams

rar://
expect://
Supported Protocols and Wrappers
PHP Manual

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

rar://
expect://
Supported Protocols and Wrappers


Process Interaction Streams

ogg://
Bezpieczeństwo
Supported Protocols and Wrappers
PHP Manual

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

ogg://
Bezpieczeństwo
Supported Protocols and Wrappers


Bezpieczeństwo

  • Introduction
  • General considerations
  • Installed as CGI binary
    • Possible attacks
    • Case 1: only public files served
    • Case 2: using cgi.force_redirect
    • Case 3: setting doc_root or user_dir
    • Case 4: PHP parser outside of web tree
  • Installed as an Apache module
  • Filesystem Security
    • Null bytes related issues
  • Database Security
    • Designing Databases
    • Connecting to Database
    • Encrypted Storage Model
    • SQL Injection
  • Error Reporting
  • Using Register Globals
  • User Submitted Data
  • Magic Quotes
    • What are Magic Quotes
    • Why did we use Magic Quotes
    • Why not to use Magic Quotes
    • Disabling Magic Quotes
  • Hiding PHP
  • Keeping Current
expect://
Introduction
Podręcznik PHP


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.

Bezpieczeństwo
General considerations
Bezpieczeństwo


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.

Introduction
Installed as CGI binary
Bezpieczeństwo


Installed as CGI binary

Spis treści

  • Possible attacks
  • Case 1: only public files served
  • Case 2: using cgi.force_redirect
  • Case 3: setting doc_root or user_dir
  • Case 4: PHP parser outside of web tree
General considerations
Possible attacks
Bezpieczeństwo


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.
Installed as CGI binary
Case 1: only public files served
Installed as CGI binary


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

Possible attacks
Case 2: using cgi.force_redirect
Installed as CGI binary


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 1: only public files served
Case 3: setting doc_root or user_dir
Installed as CGI binary


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 2: using cgi.force_redirect
Case 4: PHP parser outside of web tree
Installed as CGI binary


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.

Case 3: setting doc_root or user_dir
Installed as an Apache module
Installed as CGI binary


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.

Case 4: PHP parser outside of web tree
Filesystem Security
Bezpieczeństwo


Filesystem Security

Spis treści

  • Null bytes related issues

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($logstring, ENT_QUOTES);

?>
However, even this is not without its flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:

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.

Installed as an Apache module
Null bytes related issues
Bezpieczeństwo


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';
}
?>
Filesystem Security
Database Security
Filesystem Security


Database Security

Spis treści

  • Designing Databases
  • Connecting to Database
  • Encrypted Storage Model
  • SQL Injection

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.

Null bytes related issues
Designing Databases
Bezpieczeństwo


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.

Database Security
Connecting to Database
Database Security


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.

Designing Databases
Encrypted Storage Model
Database Security


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

?>
Connecting to Database
SQL Injection
Database Security


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.

Encrypted Storage Model
Error Reporting
Database Security


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

SQL Injection
Using Register Globals
Bezpieczeństwo


Using Register Globals

Ostrzeżenie

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

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

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

Przykład #1 Example misuse with register_globals = on

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    $authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>

When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.

Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).

Przykład #2 Example use of sessions with register_globals on or off

<?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {

    echo "Hello <b>{$_SESSION['username']}</b>";

} else {

    echo "Hello <b>Guest</b><br />";
    echo "Would you like to login?";

}
?>

It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from external sources.

Przykład #3 Detecting simple variable poisoning

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    // MAGIC_COOKIE comes from a cookie.
    // Be sure to validate the cookie data!

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;

} else {

   // MAGIC_COOKIE isn't set through this REQUEST

}
?>

Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

For information about emulating register_globals being On or Off, see this FAQ.

Informacja: Tablice superglobalne: informacja o dostępności

Tablice superglobalne, takie jak $_GET, $_POST, $_SERVER, itd. są dostępne od PHP 4.1.0. Aby uzyskać więcej informacji, należy zapoznać się z superglobals

Error Reporting
User Submitted Data
Bezpieczeństwo


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

Using Register Globals
Magic Quotes
Bezpieczeństwo


Magic Quotes

Spis treści

  • What are Magic Quotes
  • Why did we use Magic Quotes
  • Why not to use Magic Quotes
  • Disabling Magic Quotes
Ostrzeżenie

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

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

User Submitted Data
What are Magic Quotes
Bezpieczeństwo


What are Magic Quotes

Ostrzeżenie

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

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.
Magic Quotes
Why did we use Magic Quotes
Magic Quotes


Why did we use Magic Quotes

Ostrzeżenie

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

  • There is no reason to use magic quotes because they are no longer a supported part of PHP. However, they did exist and did help a few beginners blissfully and unknowingly write better (more secure) code. But, when dealing with code that relies upon this behavior it's better to update the code instead of turning magic quotes on. So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.
What are Magic Quotes
Why not to use Magic Quotes
Magic Quotes


Why not to use Magic Quotes

Ostrzeżenie

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

  • Portability Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
  • Performance Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient. Although php.ini-development enables these directives by default, php.ini-production disables it. This recommendation is mainly due to performance reasons.
  • Inconvenience Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().
Why did we use Magic Quotes
Disabling Magic Quotes
Magic Quotes


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

Why not to use Magic Quotes
Hiding PHP
Magic Quotes


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.

Disabling Magic Quotes
Keeping Current
Bezpieczeństwo


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.

Hiding PHP
Możliwości
Bezpieczeństwo


Możliwości

  • Uwierzytelnianie HTTP w PHP
  • Ciasteczka (cookies)
  • Sessions
  • Dealing with XForms
  • Handling file uploads
    • POST method uploads
    • Error Messages Explained
    • Common Pitfalls
    • Uploading multiple files
    • PUT method support
  • Korzystanie ze zdalnych plików
  • Obsługa połączeń
  • Stałe połączenia z bazami danych
  • Tryb bezpieczny
    • Zabezpieczenia i tryb bezpieczny
    • Funkcje ograniczane/wyłączone w trybie bezpiecznym
  • Command line usage — Using PHP from the command line
    • Introduction
    • Differences to other SAPIs
    • Options — Command line options
    • Usage — Executing PHP files
    • I/O streams — Input/output streams
    • Interactive shell
    • Built-in web server
  • Garbage Collection
    • Reference Counting Basics
    • Collecting Cycles
    • Performance Considerations
Keeping Current
Uwierzytelnianie HTTP w PHP
Podręcznik PHP


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, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
?>

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'] == 1 && $_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.

Możliwości
Ciasteczka (cookies)
Możliwości


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

Uwierzytelnianie HTTP w PHP
Sessions
Możliwości


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.

Ciasteczka (cookies)
Dealing with XForms
Możliwości


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.

Sessions
Handling file uploads
Możliwości


Handling file uploads

Spis treści

  • POST method uploads
  • Error Messages Explained
  • Common Pitfalls
  • Uploading multiple files
  • PUT method support
Dealing with XForms
POST method uploads
Możliwoś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.

Handling file uploads
Error Messages Explained
Handling file uploads


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.

POST method uploads
Common Pitfalls
Handling file uploads


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

Error Messages Explained
Uploading multiple files
Handling file uploads


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.

Common Pitfalls
PUT method support
Handling file uploads


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($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>

Uploading multiple files
Korzystanie ze zdalnych plików
Handling file uploads


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 ($file, 1024);
    /* 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().

PUT method support
Obsługa połączeń
Możliwości


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.

Korzystanie ze zdalnych plików
Stałe połączenia z bazami danych
Możliwości


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

Obsługa połączeń
Tryb bezpieczny
Możliwości


Tryb bezpieczny

Spis treści

  • Zabezpieczenia i tryb bezpieczny
  • Funkcje ograniczane/wyłączone w trybie bezpiecznym

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.

Stałe połączenia z bazami danych
Zabezpieczenia i tryb bezpieczny
Możliwości


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.

Tryb bezpieczny
Funkcje ograniczane/wyłączone w trybie bezpiecznym
Tryb bezpieczny


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.

Zabezpieczenia i tryb bezpieczny
Command line usage
Tryb bezpieczny


Using PHP from the command line

Spis treści

  • Introduction
  • Differences to other SAPIs
  • Options
  • Usage
  • I/O streams
  • Interactive shell
  • Built-in web server
Funkcje ograniczane/wyłączone w trybie bezpiecznym
Introduction
Możliwoś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.

Command line usage
Differences to other SAPIs
Command line usage


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.

Introduction
Options
Command line usage


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

Differences to other SAPIs
Usage
Command line usage


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 != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>

This is a command line PHP script with one option.

  Usage:
  <?php echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
    echo $argv[1];
}
?>

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.

Options
I/O streams
Command line usage


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.

Usage
Interactive shell
Command line usage


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.

I/O streams
Built-in web server
Command line usage


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
Interactive shell
Garbage Collection
Command line usage


Garbage Collection

Spis treści

  • Reference Counting Basics
  • Collecting Cycles
  • Performance Considerations

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

Built-in web server
Reference Counting Basics
Możliwości


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.

Garbage Collection
Collecting Cycles
Garbage Collection


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.

Reference Counting Basics
Performance Considerations
Garbage Collection


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 === 0 )
    {
        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.

Collecting Cycles
Opis funkcji
Garbage Collection


Opis funkcji

Wskazówka

Zobacz też: Wykaz i klasyfikacja rozszerzeń.

  • Wpływ na zachowanie PHP
    • APC — Alternative PHP Cache
    • APD — Advanced PHP debugger
    • bcompiler — PHP bytecode Compiler
    • Error Handling — Error Handling and Logging
    • htscanner — htaccess-like support for all SAPIs
    • inclued — Inclusion hierarchy viewer
    • Memtrack
    • Output Control — Output Buffering Control
    • Object overloading — Object property and method call overloading
    • PHP Options/Info — PHP Options and Information
    • runkit
    • scream — Break the silence operator
    • Weakref — Weak References
    • WinCache — Windows Cache for PHP
    • Xhprof — Hierarchical Profiler
  • Przetwarzanie formatów audio
    • ID3 — Tagi ID3
    • KTaglib
    • oggvorbis — OGG/Vorbis
    • OpenAL — OpenAL Audio Bindings
  • Serwisy uwierzytelnienia
    • KADM5 — Kerberos V
    • Radius
  • Rozszerzenia daty i czasu
    • Calendar
    • data/czas — Data i Czas
  • Rozszerzenia wiersza poleceń
    • Ncurses — Ncurses Terminal Screen Control
    • Newt
    • Readline — GNU Readline
  • Rozszerzenia kompresji i archiwizacji
    • Bzip2
    • LZF
    • Phar
    • Rar — Rar Archiving
    • Zip
    • Zlib — Zlib Compression
  • Przetwarzanie transakcji kartami płatniczymi
    • MCVE — MCVE (Monetra) Payment
    • SPPLUS — SPPLUS Payment System
  • Rozszerzenia kryptograficzne
    • Crack — Cracklib
    • Hash — HASH Message Digest Framework
    • Mcrypt
    • Mhash
    • OpenSSL
  • Rozszerzenia baz danych
    • Warstwy abstrakcji
    • Rozszerzenia producentów baz danych
  • Rozszerzenia powiązane z systemem plików
    • Direct IO
    • Directories
    • Fileinfo — File Information
    • Filesystem
    • Inotify
    • Mimetype
    • Proctitle
    • xattr
    • xdiff
  • Język naturalny i obsługa kodowania znaków
    • Enchant — Enchant spelling library
    • FriBiDi
    • Gettext
    • iconv
    • intl — Internationalization Functions
    • Multibyte String
    • Pspell
    • Recode — GNU Recode
  • Przetwarzanie i generowanie obrazów
    • Cairo
    • Exif — Exchangeable image information
    • GD — Image Processing and GD
    • Gmagick
    • ImageMagick — Image Processing (ImageMagick)
  • Rozszerzenia powiązane z pocztą elektroniczną
    • Cyrus — Cyrus IMAP administration
    • IMAP — IMAP, POP3 and NNTP
    • Mail
    • Mailparse
    • vpopmail
  • Rozszerzenia matematyczne
    • BC Math — BCMath - arytmetyka liczb dużej precyzji
    • GMP — GNU Multiple Precision
    • Math — Mathematical Functions
    • Statistics
  • Generowanie nietekstowych formatów danych
    • FDF — Forms Data Format
    • GnuPG — GNU Privacy Guard
    • haru — Haru PDF
    • Ming — Ming (flash)
    • PDF
    • PS — PostScript document creation
    • RPM Reader — RPM Header Reading
    • SWF — Shockwave Flash
  • Rozszerzenia kontroli procesów
    • Eio
    • Expect
    • Libevent
    • PCNTL — Process Control
    • POSIX
    • Program execution — System program execution
    • Semaphore — Semaphore, Shared Memory and IPC
    • Shared Memory
  • Inne podstawowe rozszerzenia
    • GeoIP — Geo IP Location
    • JSON — JavaScript Object Notation
    • Judy — Judy Arrays
    • Lua
    • Misc. — Miscellaneous Functions
    • Parsekit
    • SPL — Standard PHP Library (SPL)
    • SPL Types — SPL Type Handling
    • Streams
    • Tidy
    • Tokenizer
    • URL Funkcje
    • V8js — V8 Javascript Engine Integration
    • Yaml — YAML Data Serialization
    • Yaf
  • Inne serwisy
    • AMQP
    • chdb — Constant hash database
    • cURL — Client URL Library
    • FAM — File Alteration Monitor
    • FTP
    • Gearman
    • Gopher — Net Gopher
    • Gupnp
    • HTTP
    • Hyperwave
    • Hyperwave API
    • Java — PHP / Java Integration
    • LDAP — Lightweight Directory Access Protocol
    • Lotus Notes
    • Memcache
    • Memcached
    • mqseries
    • Network
    • RRD — RRDtool
    • SAM — Simple Asynchronous Messaging
    • SNMP
    • Sockets
    • SSH2 — Secure Shell2
    • Stomp — Stomp Client
    • SVM — Support Vector Machine
    • SVN — Subversion
    • TCP — TCP Wrappers
    • Varnish
    • YAZ
    • YP/NIS
  • Systemy wyszukiwania informacji
    • mnoGoSearch
    • Solr — Apache Solr
    • Sphinx — Sphinx Client
    • Swish — Swish Indexing
  • Rozszerzenia przeznaczone dla serwera
    • Apache
    • IIS — IIS Administration
    • NSAPI
  • Rozszerzenia sesji
    • Msession — Mohawk Software Session Handler Functions
    • Sessions — Session Handling
    • Session PgSQL — PostgreSQL Session Save Handler
  • Przetwarzanie tekstu
    • BBCode — Funkcje BBCode
    • PCRE — Regular Expressions (Perl-Compatible)
    • POSIX Regex — Regular Expression (POSIX Extended)
    • ssdeep — ssdeep Fuzzy Hashing
    • Strings
  • Zmienne i typy powiązanych rozszerzeń
    • Tablice
    • Klasy/Obiekty — Informacje o klasach i obiektach
    • Classkit
    • Ctype — Character type checking
    • Filter — Data Filtering
    • Function Handling
    • Object Aggregation — Object Aggregation/Composition [PHP 4]
    • Quickhash
    • Reflection
    • Variable handling
  • Usługi sieciowe
    • OAuth
    • SCA
    • SOAP
    • XML-RPC
  • Rozszerzenia przeznaczone dla Windows
    • .NET
    • COM — COM and .Net (Windows)
    • Printer
    • W32api
    • win32ps
    • win32service
  • Przetwarzanie XML
    • DOM — Document Object Model
    • DOM XML (PHP 4)
    • libxml
    • qtdom
    • SDO — Service Data Objects
    • SDO-DAS-Relational — SDO Relational Data Access Service
    • SDO DAS XML — SDO XML Data Access Service
    • SimpleXML
    • WDDX
    • XML Parser
    • XMLReader
    • XMLWriter
    • XSL
    • XSLT (PHP 4)
Performance Considerations
Wpływ na zachowanie PHP
Podręcznik PHP


Wpływ na zachowanie PHP

  • APC — Alternative PHP Cache
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • APC Funkcje
    • APCIterator — The APCIterator class
  • APD — Advanced PHP debugger
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • APD Funkcje
  • bcompiler — PHP bytecode Compiler
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • bcompiler Funkcje
  • Error Handling — Error Handling and Logging
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Error Handling Funkcje
  • htscanner — htaccess-like support for all SAPIs
    • Wstęp
    • Instalacja/Konfiguracja
  • inclued — Inclusion hierarchy viewer
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • inclued Funkcje
  • Memtrack
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
  • Output Control — Output Buffering Control
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Output Control Funkcje
  • Object overloading — Object property and method call overloading
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Object overloading Funkcje
  • PHP Options/Info — PHP Options and Information
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • PHP Options/Info Funkcje
  • runkit
    • Wstęp
    • Stałe predefiniowane
    • Instalacja/Konfiguracja
    • runkit Funkcje
  • scream — Break the silence operator
    • Wstęp
    • Instalacja/Konfiguracja
    • Przykłady
  • Weakref — Weak References
    • Wstęp
    • Instalacja/Konfiguracja
    • Weakref — The Weakref class
  • WinCache — Windows Cache for PHP
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • WinCache Funkcje
    • Building for Windows
  • Xhprof — Hierarchical Profiler
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Xhprof Funkcje
Opis funkcji
APC
Opis funkcji


Alternative PHP Cache

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • APC Funkcje
    • apc_add — Cache a variable in the data store
    • apc_bin_dump — Get a binary dump of the given files and user variables
    • apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file
    • apc_bin_load — Load a binary dump into the APC file/user cache
    • apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache
    • apc_cache_info — Retrieves cached information from APC's data store
    • apc_cas — Updates an old value with a new value
    • apc_clear_cache — Clears the APC cache
    • apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
    • apc_dec — Decrease a stored number
    • apc_define_constants — Defines a set of constants for retrieval and mass-definition
    • apc_delete_file — Deletes files from the opcode cache
    • apc_delete — Removes a stored variable from the cache
    • apc_exists — Checks if APC key exists
    • apc_fetch — Fetch a stored variable from the cache
    • apc_inc — Increase a stored number
    • apc_load_constants — Loads a set of constants from the cache
    • apc_sma_info — Retrieves APC's Shared Memory Allocation information
    • apc_store — Cache a variable in the data store
  • APCIterator — The APCIterator class
    • APCIterator::__construct — Constructs an APCIterator iterator object
    • APCIterator::current — Get current item
    • APCIterator::getTotalCount — Get total count
    • APCIterator::getTotalHits — Get total cache hits
    • APCIterator::getTotalSize — Get total cache size
    • APCIterator::key — Get iterator key
    • APCIterator::next — Move pointer to next item
    • APCIterator::rewind — Rewinds iterator
    • APCIterator::valid — Checks if current position is valid
Wpływ na zachowanie PHP
Wstęp
Wpływ na zachowanie PHP


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.

APC
Instalacja/Konfiguracja
APC


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
APC


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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 .

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

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.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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)

Typy zasobów
APC Funkcje
APC


APC Funkcje

Spis treści

  • apc_add — Cache a variable in the data store
  • apc_bin_dump — Get a binary dump of the given files and user variables
  • apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file
  • apc_bin_load — Load a binary dump into the APC file/user cache
  • apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache
  • apc_cache_info — Retrieves cached information from APC's data store
  • apc_cas — Updates an old value with a new value
  • apc_clear_cache — Clears the APC cache
  • apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
  • apc_dec — Decrease a stored number
  • apc_define_constants — Defines a set of constants for retrieval and mass-definition
  • apc_delete_file — Deletes files from the opcode cache
  • apc_delete — Removes a stored variable from the cache
  • apc_exists — Checks if APC key exists
  • apc_fetch — Fetch a stored variable from the cache
  • apc_inc — Increase a stored number
  • apc_load_constants — Loads a set of constants from the cache
  • apc_sma_info — Retrieves APC's Shared Memory Allocation information
  • apc_store — Cache a variable in the data store
Stałe predefiniowane
apc_add
APC


Cache a variable in the data store

APC Funkcje
apc_bin_dump
APC Funkcje
PHP Manual

apc_add

(PECL apc >= 3.0.13)

apc_add — Cache a variable in the data store

Opis

bool apc_add ( string $key [, mixed $var [, int $ttl = 0 ]] )
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_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache

APC Funkcje
apc_bin_dump
APC Funkcje


Get a binary dump of the given files and user variables

apc_add
apc_bin_dumpfile
APC Funkcje
PHP Manual

apc_bin_dump

(PECL apc >= 3.1.4)

apc_bin_dump — Get 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() - Output a binary dump of cached files and user variables to a file
  • apc_bin_load() - Load a binary dump into the APC file/user cache
apc_add
apc_bin_dumpfile
APC Funkcje


Output a binary dump of cached files and user variables to a file

apc_bin_dump
apc_bin_load
APC Funkcje
PHP Manual

apc_bin_dumpfile

(PECL apc >= 3.1.4)

apc_bin_dumpfile — Output 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_dump() - Get a binary dump of the given files and user variables
  • apc_bin_load() - Load a binary dump into the APC file/user cache
apc_bin_dump
apc_bin_load
APC Funkcje


Load a binary dump into the APC file/user cache

apc_bin_dumpfile
apc_bin_loadfile
APC Funkcje
PHP Manual

apc_bin_load

(PECL apc >= 3.1.4)

apc_bin_load — Load 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(NULL, NULL);
apc_bin_load($data, APC_BIN_VERIFY_MD5 | APC_BIN_VERIFY_CRC32);
?>

Zobacz też:

  • apc_bin_dump() - Get a binary dump of the given files and user variables
  • apc_bin_loadfile() - Load a binary dump from a file into the APC file/user cache
apc_bin_dumpfile
apc_bin_loadfile
APC Funkcje


Load a binary dump from a file into the APC file/user cache

apc_bin_load
apc_cache_info
APC Funkcje
PHP Manual

apc_bin_loadfile

(PECL apc >= 3.1.4)

apc_bin_loadfile — Load 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_bin_dumpfile() - Output a binary dump of cached files and user variables to a file
  • apc_bin_load() - Load a binary dump into the APC file/user cache
apc_bin_load
apc_cache_info
APC Funkcje


Retrieves cached information from APC's data store

apc_bin_loadfile
apc_cas
APC Funkcje
PHP Manual

apc_cache_info

(PECL apc >= 2.0.0)

apc_cache_info — Retrieves cached information from APC's data store

Opis

array apc_cache_info ([ string $cache_type [, bool $limited = false ]] )

Retrieves cached information and meta-data from APC's data store.

Zwracane wartości

Array of cached data (and meta-data) 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.

Parametry

cache_type

If cache_type is "user", information about the user cache will be returned.

If cache_type is "filehits", information about which files have been served from the bytecode cache for the current request will be returned. This feature must be enabled at compile time using --enable-filehits .

If an invalid or no cache_type is specified, information about the system cache (cached files) will be returned.

limited

If limited is TRUE, the return value will exclude the individual list of cache entries. This is useful when trying to optimize calls for statistics gathering.

Rejestr zmian

Wersja | Opis
3.0.11 | The limited parameter was introduced.
3.0.16 | The "filehits" option for the cache_type parameter was introduced.

Przykłady

Przykład #1 A apc_cache_info() example

<?php
print_r(apc_cache_info());
?>

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

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apc_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...iterates for each cached file)
)

Zobacz też:

  • APC configuration directives
  • APCIterator::getTotalSize() - Get total cache size
  • APCIterator::getTotalHits() - Get total cache hits
  • APCIterator::getTotalCount() - Get total count

apc_bin_loadfile
apc_cas
APC Funkcje


Updates an old value with a new value

apc_cache_info
apc_clear_cache
APC Funkcje
PHP Manual

apc_cas

(PECL apc >= 3.1.1)

apc_cas — Updates 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', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar == 2 ? 1 : 2 = ', (apc_cas('foobar', 2, 1) ? 'ok' : 'fail'), PHP_EOL;

echo '$foobar = ', apc_fetch('foobar'), PHP_EOL;

echo '$f__bar == 1 ? 2 : 1 = ', (apc_cas('f__bar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;

apc_store('perfection', 'xyz');
echo '$perfection == 2 ? 1 : 2 = ', (apc_cas('perfection', 2, 1) ? '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_dec() - Decrease a stored number
  • apc_store() - Cache a variable in the data store
apc_cache_info
apc_clear_cache
APC Funkcje


Clears the APC cache

apc_cas
apc_compile_file
APC Funkcje
PHP Manual

apc_clear_cache

(PECL apc >= 2.0.0)

apc_clear_cache — Clears the APC cache

Opis

bool apc_clear_cache ([ string $cache_type ] )

Clears the user/system cache.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Parametry

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

Zobacz też:

  • apc_cache_info() - Retrieves cached information from APC's data store

apc_cas
apc_compile_file
APC Funkcje


Stores a file in the bytecode cache, bypassing all filters.

apc_clear_cache
apc_dec
APC Funkcje
PHP Manual

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_bin_dumpfile() - Output a binary dump of cached files and user variables to a file
  • apc_bin_loadfile() - Load a binary dump from a file into the APC file/user cache
apc_clear_cache
apc_dec
APC Funkcje


Decrease a stored number

apc_compile_file
apc_define_constants
APC Funkcje
PHP Manual

apc_dec

(PECL apc >= 3.1.1)

apc_dec — Decrease 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_EOL, PHP_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_inc() - Increase a stored number
apc_compile_file
apc_define_constants
APC Funkcje


Defines a set of constants for retrieval and mass-definition

apc_dec
apc_delete_file
APC Funkcje
PHP Manual

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 ONE, TWO, THREE;
?>

Powyższy przykład wyświetli:

123

Zobacz też:

  • apc_load_constants() - Loads a set of constants from the cache
  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • Or the PHP constants reference

apc_dec
apc_delete_file
APC Funkcje


Deletes files from the opcode cache

apc_define_constants
apc_delete
APC Funkcje
PHP Manual

apc_delete_file

(PECL apc >= 3.1.1)

apc_delete_file — Deletes 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_clear_cache() - Clears the APC cache
  • apc_delete() - Removes a stored variable from the cache
  • apc_exists() - Checks if APC key exists
apc_define_constants
apc_delete
APC Funkcje


Removes a stored variable from the cache

apc_delete_file
apc_exists
APC Funkcje
PHP Manual

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_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache

apc_delete_file
apc_exists
APC Funkcje


Checks if APC key exists

apc_delete
apc_fetch
APC Funkcje
PHP Manual

apc_exists

(PECL apc >= 3.1.4)

apc_exists — Checks 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_cache_info() - Retrieves cached information from APC's data store
  • apc_fetch() - Fetch a stored variable from the cache
apc_delete
apc_fetch
APC Funkcje


Fetch a stored variable from the cache

apc_exists
apc_inc
APC Funkcje
PHP Manual

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_store() - Cache a variable in the data store
  • apc_delete() - Removes a stored variable from the cache
  • APCIterator

apc_exists
apc_inc
APC Funkcje


Increase a stored number

apc_fetch
apc_load_constants
APC Funkcje
PHP Manual

apc_inc

(PECL apc >= 3.1.1)

apc_inc — Increase 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_EOL, PHP_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_dec() - Decrease a stored number
apc_fetch
apc_load_constants
APC Funkcje


Loads a set of constants from the cache

apc_inc
apc_sma_info
APC Funkcje
PHP Manual

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 ONE, TWO, THREE;
?>

Powyższy przykład wyświetli:

123

Zobacz też:

  • apc_define_constants() - Defines a set of constants for retrieval and mass-definition
  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • Or the PHP constants reference

apc_inc
apc_sma_info
APC Funkcje


Retrieves APC's Shared Memory Allocation information

apc_load_constants
apc_store
APC Funkcje
PHP Manual

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
                        )

                )

        )

)

Zobacz też:

  • APC configuration directives

apc_load_constants
apc_store
APC Funkcje


Cache a variable in the data store

apc_sma_info
APCIterator
APC Funkcje
PHP Manual

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 variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache

apc_sma_info
APCIterator
APC Funkcje


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

Spis treści

  • APCIterator::__construct — Constructs an APCIterator iterator object
  • APCIterator::current — Get current item
  • APCIterator::getTotalCount — Get total count
  • APCIterator::getTotalHits — Get total cache hits
  • APCIterator::getTotalSize — Get total cache size
  • APCIterator::key — Get iterator key
  • APCIterator::next — Move pointer to next item
  • APCIterator::rewind — Rewinds iterator
  • APCIterator::valid — Checks if current position is valid
apc_store
APCIterator::__construct
APC


Constructs an APCIterator iterator object

APCIterator
APCIterator::current
APCIterator
PHP Manual

APCIterator::__construct

(PECL apc >= 3.1.1)

APCIterator::__construct — Constructs 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.

Zobacz też:

  • apc_exists() - Checks if APC key exists
  • apc_cache_info() - Retrieves cached information from APC's data store
APCIterator
APCIterator::current
APCIterator


Get current item

APCIterator::__construct
APCIterator::getTotalCount
APCIterator
PHP Manual

APCIterator::current

(PECL apc >= 3.1.1)

APCIterator::current — Get 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::next() - Move pointer to next item
  • Iterator::current() - Return the current element
APCIterator::__construct
APCIterator::getTotalCount
APCIterator


Get total count

APCIterator::current
APCIterator::getTotalHits
APCIterator
PHP Manual

APCIterator::getTotalCount

(PECL apc >= 3.1.1)

APCIterator::getTotalCount — Get 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() - Get total cache hits
  • APCIterator::getTotalSize() - Get total cache size
  • apc_cache_info() - Retrieves cached information from APC's data store
APCIterator::current
APCIterator::getTotalHits
APCIterator


Get total cache hits

APCIterator::getTotalCount
APCIterator::getTotalSize
APCIterator
PHP Manual

APCIterator::getTotalHits

(PECL apc >= 3.1.1)

APCIterator::getTotalHits — Get 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::getTotalCount() - Get total count
  • APCIterator::getTotalSize() - Get total cache size
  • apc_cache_info() - Retrieves cached information from APC's data store
APCIterator::getTotalCount
APCIterator::getTotalSize
APCIterator


Get total cache size

APCIterator::getTotalHits
APCIterator::key
APCIterator
PHP Manual

APCIterator::getTotalSize

(PECL apc >= 3.1.1)

APCIterator::getTotalSize — Get 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::getTotalCount() - Get total count
  • APCIterator::getTotalHits() - Get total cache hits
  • apc_cache_info() - Retrieves cached information from APC's data store
APCIterator::getTotalHits
APCIterator::key
APCIterator


Get iterator key

APCIterator::getTotalSize
APCIterator::next
APCIterator
PHP Manual

APCIterator::key

(PECL apc >= 3.1.1)

APCIterator::key — Get 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::current() - Get current item
  • Iterator::key() - Return the key of the current element
APCIterator::getTotalSize
APCIterator::next
APCIterator


Move pointer to next item

APCIterator::key
APCIterator::rewind
APCIterator
PHP Manual

APCIterator::next

(PECL apc >= 3.1.1)

APCIterator::next — Move 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::current() - Get current item
  • APCIterator::rewind() - Rewinds iterator
  • Iterator::next() - Move forward to next element
APCIterator::key
APCIterator::rewind
APCIterator


Rewinds iterator

APCIterator::next
APCIterator::valid
APCIterator
PHP Manual

APCIterator::rewind

(PECL apc >= 3.1.1)

APCIterator::rewind — Rewinds 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::next() - Move pointer to next item
  • Iterator::next() - Move forward to next element
APCIterator::next
APCIterator::valid
APCIterator


Checks if current position is valid

APCIterator::rewind
APD
APCIterator
PHP Manual

APCIterator::valid

(PECL apc >= 3.1.1)

APCIterator::valid — Checks 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ż:

  • APCIterator::current() - Get current item
  • Iterator::valid() - Checks if current position is valid
APCIterator::rewind
APD
APCIterator


Advanced PHP debugger

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Building on Win32
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • How to use PHP-APD in your scripts
  • APD Funkcje
    • apd_breakpoint — Stops the interpreter and waits on a CR from the socket
    • apd_callstack — Returns the current call stack as an array
    • apd_clunk — Throw a warning and a callstack
    • apd_continue — Restarts the interpreter
    • apd_croak — Throw an error, a callstack and then exit
    • apd_dump_function_table — Outputs the current function table
    • apd_dump_persistent_resources — Return all persistent resources as an array
    • apd_dump_regular_resources — Return all current regular resources as an array
    • apd_echo — Echo to the debugging socket
    • apd_get_active_symbols — Get an array of the current variables names in the local scope
    • apd_set_pprof_trace — Starts the session debugging
    • apd_set_session_trace_socket — Starts the remote session debugging
    • apd_set_session_trace — Starts the session debugging
    • apd_set_session — Changes or sets the current debugging level
    • override_function — Overrides built-in functions
    • rename_function — Renames orig_name to new_name in the global function table
APCIterator::valid
Wstęp
Wpływ na zachowanie PHP


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

APD
Instalacja/Konfiguracja
APD


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Building on Win32
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
APD


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)

Wymagania
Building on Win32
Instalacja/Konfiguracja


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.

Instalacja
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Building on Win32
Typy zasobów
Instalacja/Konfiguracja


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 |
Typy zasobów
Przykłady
APD


Przykłady

Spis treści

  • How to use PHP-APD in your scripts
Stałe predefiniowane
How to use PHP-APD in your scripts
APD


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.

Przykłady
APD Funkcje
Przykłady


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.

Spis treści

  • apd_breakpoint — Stops the interpreter and waits on a CR from the socket
  • apd_callstack — Returns the current call stack as an array
  • apd_clunk — Throw a warning and a callstack
  • apd_continue — Restarts the interpreter
  • apd_croak — Throw an error, a callstack and then exit
  • apd_dump_function_table — Outputs the current function table
  • apd_dump_persistent_resources — Return all persistent resources as an array
  • apd_dump_regular_resources — Return all current regular resources as an array
  • apd_echo — Echo to the debugging socket
  • apd_get_active_symbols — Get an array of the current variables names in the local scope
  • apd_set_pprof_trace — Starts the session debugging
  • apd_set_session_trace_socket — Starts the remote session debugging
  • apd_set_session_trace — Starts the session debugging
  • apd_set_session — Changes or sets the current debugging level
  • override_function — Overrides built-in functions
  • rename_function — Renames orig_name to new_name in the global function table
How to use PHP-APD in your scripts
apd_breakpoint
APD


Stops the interpreter and waits on a CR from the socket

APD Funkcje
apd_callstack
APD Funkcje
PHP Manual

apd_breakpoint

(PECL apd >= 0.2)

apd_breakpoint — Stops 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 Funkcje
apd_callstack
APD Funkcje


Returns the current call stack as an array

apd_breakpoint
apd_clunk
APD Funkcje
PHP Manual

apd_callstack

(PECL apd 0.2-0.4)

apd_callstack — Returns 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_breakpoint
apd_clunk
APD Funkcje


Throw a warning and a callstack

apd_callstack
apd_continue
APD Funkcje
PHP Manual

apd_clunk

(PECL apd 0.2-0.4)

apd_clunk — Throw 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_callstack
apd_continue
APD Funkcje


Restarts the interpreter

apd_clunk
apd_croak
APD Funkcje
PHP Manual

apd_continue

(PECL apd >= 0.2)

apd_continue — Restarts 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_clunk
apd_croak
APD Funkcje


Throw an error, a callstack and then exit

apd_continue
apd_dump_function_table
APD Funkcje
PHP Manual

apd_croak

(PECL apd 0.2-0.4)

apd_croak — Throw 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_clunk() - Throw a warning and a callstack

apd_continue
apd_dump_function_table
APD Funkcje


Outputs the current function table

apd_croak
apd_dump_persistent_resources
APD Funkcje
PHP Manual

apd_dump_function_table

(Unknown)

apd_dump_function_table — Outputs 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_croak
apd_dump_persistent_resources
APD Funkcje


Return all persistent resources as an array

apd_dump_function_table
apd_dump_regular_resources
APD Funkcje
PHP Manual

apd_dump_persistent_resources

(PECL apd 0.2-0.4)

apd_dump_persistent_resources — Return 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() - Return all current regular resources as an array

apd_dump_function_table
apd_dump_regular_resources
APD Funkcje


Return all current regular resources as an array

apd_dump_persistent_resources
apd_echo
APD Funkcje
PHP Manual

apd_dump_regular_resources

(PECL apd 0.2-0.4)

apd_dump_regular_resources — Return 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_dump_persistent_resources() - Return all persistent resources as an array

apd_dump_persistent_resources
apd_echo
APD Funkcje


Echo to the debugging socket

apd_dump_regular_resources
apd_get_active_symbols
APD Funkcje
PHP Manual

apd_echo

(PECL apd >= 0.2)

apd_echo — Echo 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_dump_regular_resources
apd_get_active_symbols
APD Funkcje


Get an array of the current variables names in the local scope

apd_echo
apd_set_pprof_trace
APD Funkcje
PHP Manual

apd_get_active_symbols

(PECL apd 0.2)

apd_get_active_symbols — Get 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_echo
apd_set_pprof_trace
APD Funkcje


Starts the session debugging

apd_get_active_symbols
apd_set_session_trace_socket
APD Funkcje
PHP Manual

apd_set_pprof_trace

(PECL apd >= 0.2)

apd_set_pprof_trace — Starts 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() - Starts the session debugging

apd_get_active_symbols
apd_set_session_trace_socket
APD Funkcje


Starts the remote session debugging

apd_set_pprof_trace
apd_set_session_trace
APD Funkcje
PHP Manual

apd_set_session_trace_socket

(PECL apd >= 0.2)

apd_set_session_trace_socket — Starts 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_pprof_trace
apd_set_session_trace
APD Funkcje


Starts the session debugging

apd_set_session_trace_socket
apd_set_session
APD Funkcje
PHP Manual

apd_set_session_trace

(PECL apd 0.2-0.4)

apd_set_session_trace — Starts 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_trace_socket
apd_set_session
APD Funkcje


Changes or sets the current debugging level

apd_set_session_trace
override_function
APD Funkcje
PHP Manual

apd_set_session

(PECL apd 0.2-0.4)

apd_set_session — Changes 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);
?>

apd_set_session_trace
override_function
APD Funkcje


Overrides built-in functions

apd_set_session
rename_function
APD Funkcje
PHP Manual

override_function

(PECL apd >= 0.2)

override_function — Overrides 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;');
?>

apd_set_session
rename_function
APD Funkcje


Renames orig_name to new_name in the global function table

override_function
bcompiler
APD Funkcje
PHP Manual

rename_function

(PECL apd >= 0.2)

rename_function — Renames 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' );
?>

override_function
bcompiler
APD Funkcje


PHP bytecode Compiler

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • bcompiler Funkcje
    • bcompiler_load_exe — Reads and creates classes from a bcompiler exe file
    • bcompiler_load — Reads and creates classes from a bz compressed file
    • bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function
    • bcompiler_read — Reads and creates classes from a filehandle
    • bcompiler_write_class — Writes an defined class as bytecodes
    • bcompiler_write_constant — Writes a defined constant as bytecodes
    • bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file
    • bcompiler_write_file — Writes a php source file as bytecodes
    • bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data
    • bcompiler_write_function — Writes an defined function as bytecodes
    • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
    • bcompiler_write_header — Writes the bcompiler header
    • bcompiler_write_included_filename — Writes an included file as bytecodes
rename_function
Wstęp
Wpływ na zachowanie PHP


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.

bcompiler
Instalacja/Konfiguracja
bcompiler


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
bcompiler


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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
bcompiler Funkcje
bcompiler


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.

Spis treści

  • bcompiler_load_exe — Reads and creates classes from a bcompiler exe file
  • bcompiler_load — Reads and creates classes from a bz compressed file
  • bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function
  • bcompiler_read — Reads and creates classes from a filehandle
  • bcompiler_write_class — Writes an defined class as bytecodes
  • bcompiler_write_constant — Writes a defined constant as bytecodes
  • bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file
  • bcompiler_write_file — Writes a php source file as bytecodes
  • bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data
  • bcompiler_write_function — Writes an defined function as bytecodes
  • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
  • bcompiler_write_header — Writes the bcompiler header
  • bcompiler_write_included_filename — Writes an included file as bytecodes
Stałe predefiniowane
bcompiler_load_exe
bcompiler


Reads and creates classes from a bcompiler exe file

bcompiler Funkcje
bcompiler_load
bcompiler Funkcje
PHP Manual

bcompiler_load_exe

(PECL bcompiler >= 0.4)

bcompiler_load_exe — Reads 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() - Reads and creates classes from a bz compressed file

bcompiler Funkcje
bcompiler_load
bcompiler Funkcje


Reads and creates classes from a bz compressed file

bcompiler_load_exe
bcompiler_parse_class
bcompiler Funkcje
PHP Manual

bcompiler_load

(PECL bcompiler >= 0.4)

bcompiler_load — Reads 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_load_exe() - Reads and creates classes from a bcompiler exe file

bcompiler_load_exe
bcompiler_parse_class
bcompiler Funkcje


Reads the bytecodes of a class and calls back to a user function

bcompiler_load
bcompiler_read
bcompiler Funkcje
PHP Manual

bcompiler_parse_class

(PECL bcompiler >= 0.4)

bcompiler_parse_class — Reads 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_load
bcompiler_read
bcompiler Funkcje


Reads and creates classes from a filehandle

bcompiler_parse_class
bcompiler_write_class
bcompiler Funkcje
PHP Manual

bcompiler_read

(PECL bcompiler >= 0.4)

bcompiler_read — Reads 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_parse_class
bcompiler_write_class
bcompiler Funkcje


Writes an defined class as bytecodes

bcompiler_read
bcompiler_write_constant
bcompiler Funkcje
PHP Manual

bcompiler_write_class

(PECL bcompiler >= 0.4)

bcompiler_write_class — Writes an defined class as bytecodes

Opis

bool bcompiler_write_class ( resource $filehandle , string $className [, string $extends ] )

Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.

Parametry

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bcompiler_write_class() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Informacja:

This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.

Zobacz też:

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_read
bcompiler_write_constant
bcompiler Funkcje


Writes a defined constant as bytecodes

bcompiler_write_class
bcompiler_write_exe_footer
bcompiler Funkcje
PHP Manual

bcompiler_write_constant

(PECL bcompiler >= 0.5)

bcompiler_write_constant — Writes 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_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_class
bcompiler_write_exe_footer
bcompiler Funkcje


Writes the start pos, and sig to the end of a exe type file

bcompiler_write_constant
bcompiler_write_file
bcompiler Funkcje
PHP Manual

bcompiler_write_exe_footer

(PECL bcompiler >= 0.4)

bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file

Opis

bool bcompiler_write_exe_footer ( resource $filehandle , int $startpos )

An EXE (or self executable) file consists of 3 parts:

  • The stub (executable code, e.g. a compiled C program) that loads PHP interpreter, bcompiler extension, stored Bytecodes and initiates a call for the specified function (e.g. main) or class method (e.g. main::main)
  • The Bytecodes (uncompressed only for the moment)
  • The bcompiler EXE footer

To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.

Parametry

filehandle

A file handle as returned by fopen().

startpos

The file position at which the Bytecodes start, and can be obtained using ftell().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bcompiler_write_exe_footer() example

<?php

/* creating the output file (example.exe) */
$fh = fopen("example.exe", "w");

/* 1) writing a stub (phpe.exe) */
$size = filesize("phpe.exe");
$fr = fopen("phpe.exe", "r");
fwrite($fh, fread($fr, $size), $size);
$startpos = ftell($fh);

/* 2) writing bytecodes */
bcompiler_write_header($fh);
bcompiler_write_class($fh, "myclass");
bcompiler_write_function($fh, "main");
bcompiler_write_footer($fh);

/* 3) writing EXE footer */
bcompiler_write_exe_footer($fh, $startpos);

/* closing the output file */
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() - Writes the bcompiler header
  • bcompiler_write_class() - Writes an defined class as bytecodes
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_constant
bcompiler_write_file
bcompiler Funkcje


Writes a php source file as bytecodes

bcompiler_write_exe_footer
bcompiler_write_footer
bcompiler Funkcje
PHP Manual

bcompiler_write_file

(PECL bcompiler >= 0.6)

bcompiler_write_file — Writes 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_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_exe_footer
bcompiler_write_footer
bcompiler Funkcje


Writes the single character \x00 to indicate End of compiled data

bcompiler_write_file
bcompiler_write_function
bcompiler Funkcje
PHP Manual

bcompiler_write_footer

(PECL bcompiler >= 0.4)

bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data

Opis

bool bcompiler_write_footer ( resource $filehandle )

Writes the single character \x00 to indicate End of compiled data.

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

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_class($fh,"DB_common");
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() - Writes the bcompiler header

bcompiler_write_file
bcompiler_write_function
bcompiler Funkcje


Writes an defined function as bytecodes

bcompiler_write_footer
bcompiler_write_functions_from_file
bcompiler Funkcje
PHP Manual

bcompiler_write_function

(PECL bcompiler >= 0.5)

bcompiler_write_function — Writes an defined function as bytecodes

Opis

bool bcompiler_write_function ( resource $filehandle , string $functionName )

Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).

Parametry

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bcompiler_write_function() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notatki

Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Zobacz też:

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_footer
bcompiler_write_functions_from_file
bcompiler Funkcje


Writes all functions defined in a file as bytecodes

bcompiler_write_function
bcompiler_write_header
bcompiler Funkcje
PHP Manual

bcompiler_write_functions_from_file

(PECL bcompiler >= 0.5)

bcompiler_write_functions_from_file — Writes 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() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_function
bcompiler_write_header
bcompiler Funkcje


Writes the bcompiler header

bcompiler_write_functions_from_file
bcompiler_write_included_filename
bcompiler Funkcje
PHP Manual

bcompiler_write_header

(PECL bcompiler >= 0.3)

bcompiler_write_header — Writes 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_footer() - Writes the single character \x00 to indicate End of compiled data

bcompiler_write_functions_from_file
bcompiler_write_included_filename
bcompiler Funkcje


Writes an included file as bytecodes

bcompiler_write_header
Error Handling
bcompiler Funkcje
PHP Manual

bcompiler_write_included_filename

(PECL bcompiler >= 0.5)

bcompiler_write_included_filename — Writes 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.

bcompiler_write_header
Error Handling
bcompiler Funkcje


Error Handling and Logging

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Error Handling Funkcje
    • debug_backtrace — Generates a backtrace
    • debug_print_backtrace — Prints a backtrace
    • error_get_last — Get the last occurred error
    • error_log — Send an error message somewhere
    • error_reporting — Sets which PHP errors are reported
    • restore_error_handler — Restores the previous error handler function
    • restore_exception_handler — Restores the previously defined exception handler function
    • set_error_handler — Sets a user-defined error handler function
    • set_exception_handler — Sets a user-defined exception handler function
    • trigger_error — Generates a user-level error/warning/notice message
    • user_error — Alias of trigger_error
bcompiler_write_included_filename
Wstęp
Wpływ na zachowanie PHP


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.

Error Handling
Instalacja/Konfiguracja
Error Handling


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Error Handling


Instalacja

By używać tych funkcji, nie trzeba niczego instalować. Są one częścią jądra PHP.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

Typy zasobów
Przykłady
Error Handling


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_ERROR, E_USER_WARNING, E_USER_NOTICE);

    $err = "<errorentry>\n";
    $err .= "\t<datetime>" . $dt . "</datetime>\n";
    $err .= "\t<errornum>" . $errno . "</errornum>\n";
    $err .= "\t<errortype>" . $errortype[$errno] . "</errortype>\n";
    $err .= "\t<errormsg>" . $errmsg . "</errormsg>\n";
    $err .= "\t<scriptname>" . $filename . "</scriptname>\n";
    $err .= "\t<scriptlinenum>" . $linenum . "</scriptlinenum>\n";

    if (in_array($errno, $user_errors)) {
        $err .= "\t<vartrace>" . wddx_serialize_value($vars, "Variables") . "</vartrace>\n";
    }
    $err .= "</errorentry>\n\n";

    // for testing
    // echo $err;

    // save to the error log, and e-mail me if there is a critical user error
    error_log($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR) {
        mail("phpdev@example.com", "Critical User Error", $err);
    }
}

function distance($vect1, $vect2)
{
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero",
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero",
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

// generate a user error
$t1 = distance($c, $b) . "\n";

// generate another user error
$t2 = distance($b, "i am not an array") . "\n";

// generate a warning
$t3 = distance($a, $b) . "\n";

?>

Stałe predefiniowane
Error Handling Funkcje
Error Handling


Error Handling Funkcje

Zobacz też:

See also syslog().

Spis treści

  • debug_backtrace — Generates a backtrace
  • debug_print_backtrace — Prints a backtrace
  • error_get_last — Get the last occurred error
  • error_log — Send an error message somewhere
  • error_reporting — Sets which PHP errors are reported
  • restore_error_handler — Restores the previous error handler function
  • restore_exception_handler — Restores the previously defined exception handler function
  • set_error_handler — Sets a user-defined error handler function
  • set_exception_handler — Sets a user-defined exception handler function
  • trigger_error — Generates a user-level error/warning/notice message
  • user_error — Alias of trigger_error
Przykłady
debug_backtrace
Error Handling


Generates a backtrace

Error Handling Funkcje
debug_print_backtrace
Error Handling Funkcje
PHP Manual

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5)

debug_backtrace — Generates 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ż:

  • trigger_error() - Generates a user-level error/warning/notice message
  • debug_print_backtrace() - Prints a backtrace

Error Handling Funkcje
debug_print_backtrace
Error Handling Funkcje


Prints a backtrace

debug_backtrace
error_get_last
Error Handling Funkcje
PHP Manual

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

  • debug_backtrace() - Generates a backtrace

debug_backtrace
error_get_last
Error Handling Funkcje


Get the last occurred error

debug_print_backtrace
error_log
Error Handling Funkcje
PHP Manual

error_get_last

(PHP 5 >= 5.2.0)

error_get_last — Get 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
)

Zobacz też:

  • Error constants
  • Variable $php_errormsg
  • Directive display_errors
  • Directive html_errors
  • Directive xmlrpc_errors

debug_print_backtrace
error_log
Error Handling Funkcje


Send an error message somewhere

error_get_last
error_reporting
Error Handling Funkcje
PHP Manual

error_log

(PHP 4, PHP 5)

error_log — Send 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_get_last
error_reporting
Error Handling Funkcje


Sets which PHP errors are reported

error_log
restore_error_handler
Error Handling Funkcje
PHP Manual

error_reporting

(PHP 4, PHP 5)

error_reporting — Sets 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ż:

  • The display_errors directive
  • The html_errors directive
  • The xmlrpc_errors directive
  • ini_set() - Sets the value of a configuration option

error_log
restore_error_handler
Error Handling Funkcje


Restores the previous error handler function

error_reporting
restore_exception_handler
Error Handling Funkcje
PHP Manual

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5)

restore_error_handler — Restores 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ż:

  • error_reporting() - Sets which PHP errors are reported
  • set_error_handler() - Sets a user-defined error handler function
  • restore_exception_handler() - Restores the previously defined exception handler function
  • trigger_error() - Generates a user-level error/warning/notice message

error_reporting
restore_exception_handler
Error Handling Funkcje


Restores the previously defined exception handler function

restore_error_handler
set_error_handler
Error Handling Funkcje
PHP Manual

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_exception_handler() - Sets a user-defined exception handler function
  • set_error_handler() - Sets a user-defined error handler function
  • restore_error_handler() - Restores the previous error handler function
  • error_reporting() - Sets which PHP errors are reported

restore_error_handler
set_error_handler
Error Handling Funkcje


Sets a user-defined error handler function

restore_exception_handler
set_exception_handler
Error Handling Funkcje
PHP Manual

set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handler — Sets a user-defined error handler function

Opis

mixed set_error_handler ( callback $error_handler [, int $error_types = E_ALL | E_STRICT ] )

Sets a user function (error_handler) to handle errors in a script.

This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).

It is important to remember that the standard PHP error handler is completely bypassed 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(2, 3, "foo", 5.5, 43.3, 21.11);
print_r($a);

// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>

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

  • ErrorException
  • error_reporting() - Sets which PHP errors are reported
  • restore_error_handler() - Restores the previous error handler function
  • trigger_error() - Generates a user-level error/warning/notice message
  • error level constants
  • informacje o typie callback

restore_exception_handler
set_exception_handler
Error Handling Funkcje


Sets a user-defined exception handler function

set_error_handler
trigger_error
Error Handling Funkcje
PHP Manual

set_exception_handler

(PHP 5)

set_exception_handler — Sets a user-defined exception handler function

Opis

callback set_exception_handler ( callback $exception_handler )

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

Parametry

exception_handler

Name of the function to be called when an uncaught exception occurs. This function must be defined before calling set_exception_handler(). This handler function needs to accept one parameter, which will be the exception object that was thrown.

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

  • restore_exception_handler() - Restores the previously defined exception handler function
  • restore_error_handler() - Restores the previous error handler function
  • error_reporting() - Sets which PHP errors are reported
  • informacje o typie callback
  • PHP 5 Exceptions

set_error_handler
trigger_error
Error Handling Funkcje


Generates a user-level error/warning/notice message

set_exception_handler
user_error
Error Handling Funkcje
PHP Manual

trigger_error

(PHP 4 >= 4.0.1, PHP 5)

trigger_error — Generates 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ż:

  • error_reporting() - Sets which PHP errors are reported
  • set_error_handler() - Sets a user-defined error handler function
  • restore_error_handler() - Restores the previous error handler function
  • The error level constants

set_exception_handler
user_error
Error Handling Funkcje


Alias of trigger_error

trigger_error
htscanner
Error Handling Funkcje
PHP Manual

user_error

(PHP 4, PHP 5)

user_error — Alias of trigger_error()

Opis

Ta funkcja jest aliasem dla: trigger_error().

trigger_error
htscanner
Error Handling Funkcje


htaccess-like support for all SAPIs

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
user_error
Wstęp
Wpływ na zachowanie PHP


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

htscanner
Instalacja/Konfiguracja
htscanner


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
htscanner


Wymagania

PHP version 5.2.0 or greater.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
inclued
Instalacja/Konfiguracja


Inclusion hierarchy viewer

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Example that implements inclued into an application
  • inclued Funkcje
    • inclued_get_data — Get the inclued data
Typy zasobów
Wstęp
Wpływ na zachowanie PHP


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.

inclued
Instalacja/Konfiguracja
inclued


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
inclued


Wymagania

PHP version 5.1.0 or greater.

The included gengraph.php file utilizes the » graphviz library, however, this is not required.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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!

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

Typy zasobów
Przykłady
inclued


Przykłady

Spis treści

  • Example that implements inclued into an application
Stałe predefiniowane
Example that implements inclued into an application
inclued


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($fp, serialize($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

Przykłady
inclued Funkcje
Przykłady


inclued Funkcje

Spis treści

  • inclued_get_data — Get the inclued data
Example that implements inclued into an application
inclued_get_data
inclued


Get the inclued data

inclued Funkcje
Memtrack
inclued Funkcje
PHP Manual

inclued_get_data

(PECL inclued >= 0.1.0)

inclued_get_data — Get 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ż:

  • inclued examples
  • debug_backtrace() - Generates a backtrace
  • include()

inclued Funkcje
Memtrack
inclued Funkcje


Memtrack

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
inclued_get_data
Wstęp
Wpływ na zachowanie PHP


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.

Memtrack
Instalacja/Konfiguracja
Memtrack


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Memtrack


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Memtrack


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
Memtrack


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
Przykłady
Output Control
Przykłady


Output Buffering Control

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • Output Control Funkcje
    • flush — Flush the output buffer
    • ob_clean — Clean (erase) the output buffer
    • 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_flush — Flush (send) the output buffer
    • ob_get_clean — Get current buffer contents and delete current output buffer
    • ob_get_contents — Return the contents of the output buffer
    • ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
    • ob_get_length — Return the length of the output buffer
    • ob_get_level — Return the nesting level of the output buffering mechanism
    • ob_get_status — Get status of output buffers
    • ob_gzhandler — ob_start callback function to gzip output buffer
    • ob_implicit_flush — Turn implicit flush on/off
    • ob_list_handlers — List all output handlers in use
    • ob_start — Turn on output buffering
    • output_add_rewrite_var — Add URL rewriter values
    • output_reset_rewrite_vars — Reset URL rewriter values
Basic usage
Wstęp
Wpływ na zachowanie PHP


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.

Output Control
Instalacja/Konfiguracja
Output Control


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Output Control


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

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Output Control


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
Output Control


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

Przykłady
Output Control Funkcje
Przykłady


Output Control Funkcje

Zobacz też:

See also header() and setcookie().

Spis treści

  • flush — Flush the output buffer
  • ob_clean — Clean (erase) the output buffer
  • 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_flush — Flush (send) the output buffer
  • ob_get_clean — Get current buffer contents and delete current output buffer
  • ob_get_contents — Return the contents of the output buffer
  • ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
  • ob_get_length — Return the length of the output buffer
  • ob_get_level — Return the nesting level of the output buffering mechanism
  • ob_get_status — Get status of output buffers
  • ob_gzhandler — ob_start callback function to gzip output buffer
  • ob_implicit_flush — Turn implicit flush on/off
  • ob_list_handlers — List all output handlers in use
  • ob_start — Turn on output buffering
  • output_add_rewrite_var — Add URL rewriter values
  • output_reset_rewrite_vars — Reset URL rewriter values
Basic usage
flush
Output Control


Flush the output buffer

Output Control Funkcje
ob_clean
Output Control Funkcje
PHP Manual

flush

(PHP 4, PHP 5)

flush — Flush 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ść.

Output Control Funkcje
ob_clean
Output Control Funkcje


Clean (erase) the output buffer

flush
ob_end_clean
Output Control Funkcje
PHP Manual

ob_clean

(PHP 4 >= 4.2.0, PHP 5)

ob_clean — Clean (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

flush
ob_end_clean
Output Control Funkcje


Clean (erase) the output buffer and turn off output buffering

ob_clean
ob_end_flush
Output Control Funkcje
PHP Manual

ob_end_clean

(PHP 4, PHP 5)

ob_end_clean — Clean (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_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer
  • ob_flush() - Flush (send) the output buffer

ob_clean
ob_end_flush
Output Control Funkcje


Flush (send) the output buffer and turn off output buffering

ob_end_clean
ob_flush
Output Control Funkcje
PHP Manual

ob_end_flush

(PHP 4, PHP 5)

ob_end_flush — Flush (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_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer
  • ob_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_flush() - Flush (send) the output buffer
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

ob_end_clean
ob_flush
Output Control Funkcje


Flush (send) the output buffer

ob_end_flush
ob_get_clean
Output Control Funkcje
PHP Manual

ob_flush

(PHP 4 >= 4.2.0, PHP 5)

ob_flush — Flush (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_contents() - Return the contents of the output buffer
  • ob_clean() - Clean (erase) 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_flush
ob_get_clean
Output Control Funkcje


Get current buffer contents and delete current output buffer

ob_flush
ob_get_contents
Output Control Funkcje
PHP Manual

ob_get_clean

(PHP 4 >= 4.3.0, PHP 5)

ob_get_clean — Get 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() - Return the contents of the output buffer
  • ob_start() - Turn on output buffering

ob_flush
ob_get_contents
Output Control Funkcje


Return the contents of the output buffer

ob_get_clean
ob_get_flush
Output Control Funkcje
PHP Manual

ob_get_contents

(PHP 4, PHP 5)

ob_get_contents — Return 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_start() - Turn on output buffering
  • ob_get_length() - Return the length of the output buffer

ob_get_clean
ob_get_flush
Output Control Funkcje


Flush the output buffer, return it as a string and turn off output buffering

ob_get_contents
ob_get_length
Output Control Funkcje
PHP Manual

ob_get_flush

(PHP 4 >= 4.3.0, PHP 5)

ob_get_flush — Flush 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_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_list_handlers() - List all output handlers in use

ob_get_contents
ob_get_length
Output Control Funkcje


Return the length of the output buffer

ob_get_flush
ob_get_level
Output Control Funkcje
PHP Manual

ob_get_length

(PHP 4 >= 4.0.2, PHP 5)

ob_get_length — Return 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_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer

ob_get_flush
ob_get_level
Output Control Funkcje


Return the nesting level of the output buffering mechanism

ob_get_length
ob_get_status
Output Control Funkcje
PHP Manual

ob_get_level

(PHP 4 >= 4.2.0, PHP 5)

ob_get_level — Return 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_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer

ob_get_length
ob_get_status
Output Control Funkcje


Get status of output buffers

ob_get_level
ob_gzhandler
Output Control Funkcje
PHP Manual

ob_get_status

(PHP 4 >= 4.2.0, PHP 5)

ob_get_status — Get 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_get_level() - Return the nesting level of the output buffering mechanism
  • ob_list_handlers() - List all output handlers in use

ob_get_level
ob_gzhandler
Output Control Funkcje


ob_start callback function to gzip output buffer

ob_get_status
ob_implicit_flush
Output Control Funkcje
PHP Manual

ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5)

ob_gzhandler — ob_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_start() - Turn on output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering

ob_get_status
ob_implicit_flush
Output Control Funkcje


Turn implicit flush on/off

ob_gzhandler
ob_list_handlers
Output Control Funkcje
PHP Manual

ob_implicit_flush

(PHP 4, PHP 5)

ob_implicit_flush — Turn 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ż:

  • flush() - Flush the output buffer
  • ob_start() - Turn on output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering

ob_gzhandler
ob_list_handlers
Output Control Funkcje


List all output handlers in use

ob_implicit_flush
ob_start
Output Control Funkcje
PHP Manual

ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5)

ob_list_handlers — List 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_implicit_flush
ob_start
Output Control Funkcje


Turn on output buffering

ob_list_handlers
output_add_rewrite_var
Output Control Funkcje
PHP Manual

ob_start

(PHP 4, PHP 5)

ob_start — Turn on output buffering

Opis

bool ob_start ([ callback $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ż:

  • ob_get_contents() - Return the contents of the output buffer
  • 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_implicit_flush() - Turn implicit flush on/off
  • ob_gzhandler() - ob_start callback function to gzip output buffer
  • ob_iconv_handler() - Konwersja kodowania znaków jako uchwyt buforu wyjścia
  • mb_output_handler() - Callback function converts character encoding in output buffer
  • ob_tidyhandler() - Funkcja zwrotna do czyszczenia bufora wyjścia dla funkcji ob_start

ob_list_handlers
output_add_rewrite_var
Output Control Funkcje


Add URL rewriter values

ob_start
output_reset_rewrite_vars
Output Control Funkcje
PHP Manual

output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5)

output_add_rewrite_var — Add 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() - Reset URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use

ob_start
output_reset_rewrite_vars
Output Control Funkcje


Reset URL rewriter values

output_add_rewrite_var
Object overloading
Output Control Funkcje
PHP Manual

output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5)

output_reset_rewrite_vars — Reset 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ż:

  • output_add_rewrite_var() - Add URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use
  • session_start() - Inicjalizuj dane sesji

output_add_rewrite_var
Object overloading
Output Control Funkcje


Object property and method call overloading

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • Object overloading Funkcje
    • overload — Umożliwienie przeciążania właściwości i wołania metod dla klasy
output_reset_rewrite_vars
Wstęp
Wpływ na zachowanie PHP


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.

Object overloading
Instalacja/Konfiguracja
Object overloading


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Object overloading


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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Object overloading


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
Object overloading


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->x = 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->a = array($val);
var_dump($o->a[0]->prop);

?>

Przykłady
Object overloading Funkcje
Przykłady


Object overloading Funkcje

Spis treści

  • overload — Umożliwienie przeciążania właściwości i wołania metod dla klasy
Basic usage
overload
Object overloading


Umożliwienie przeciążania właściwości i wołania metod dla klasy

Object overloading Funkcje
PHP Options/Info
Object overloading Funkcje
PHP Manual

overload

(PHP 4 >= 4.3.0)

overload — Umoż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.

Object overloading Funkcje
PHP Options/Info
Object overloading Funkcje


PHP Options and Information

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • PHP Options/Info Funkcje
    • assert_options — Set/get the various assert flags
    • assert — Checks if assertion is FALSE
    • dl — Loads a PHP extension at runtime
    • extension_loaded — Find out whether an extension is loaded
    • gc_collect_cycles — Forces collection of any existing garbage cycles
    • gc_disable — Deactivates the circular reference collector
    • gc_enable — Activates the circular reference collector
    • gc_enabled — Returns status of the circular reference collector
    • get_cfg_var — Gets the value of a PHP configuration option
    • get_current_user — Gets the name of the owner of the current PHP script
    • get_defined_constants — Returns an associative array with the names of all the constants and their values
    • get_extension_funcs — Returns an array with the names of the functions of a module
    • get_include_path — Gets the current include_path configuration option
    • get_included_files — Returns an array with the names of included or required files
    • get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
    • get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc
    • get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
    • get_required_files — Alias dla get_included_files
    • getenv — Gets the value of an environment variable
    • getlastmod — Gets time of last page modification
    • getmygid — Get PHP script owner's GID
    • getmyinode — Gets the inode of the current script
    • getmypid — Gets PHP's process ID
    • getmyuid — Gets PHP script owner's UID
    • getopt — Gets options from the command line argument list
    • getrusage — Gets the current resource usages
    • ini_alter — Alias dla ini_set
    • ini_get_all — Gets all configuration options
    • ini_get — Gets the value of a configuration option
    • ini_restore — Restores the value of a configuration option
    • ini_set — Sets the value of a configuration option
    • magic_quotes_runtime — Alias dla set_magic_quotes_runtime
    • main — Dummy for main
    • memory_get_peak_usage — Returns the peak of memory allocated by PHP
    • memory_get_usage — Returns the amount of memory allocated to PHP
    • php_ini_loaded_file — Retrieve a path to the loaded php.ini file
    • php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir
    • php_logo_guid — Gets the logo guid
    • php_sapi_name — Returns the type of interface between web server and PHP
    • php_uname — Returns information about the operating system PHP is running on
    • phpcredits — Prints out the credits for PHP
    • phpinfo — Outputs information about PHP's configuration
    • phpversion — Gets the current PHP version
    • putenv — Sets the value of an environment variable
    • restore_include_path — Restores the value of the include_path configuration option
    • set_include_path — Sets the include_path configuration option
    • set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
    • set_time_limit — Limits the maximum execution time
    • sys_get_temp_dir — Returns directory path used for temporary files
    • version_compare — Compares two "PHP-standardized" version number strings
    • zend_logo_guid — Gets the Zend guid
    • zend_thread_id — Returns a unique identifier for the current thread
    • zend_version — Gets the version of the current Zend engine
overload
Wstęp
Wpływ na zachowanie PHP


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.

PHP Options/Info
Instalacja/Konfiguracja
PHP Options/Info


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
PHP Options/Info


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

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

Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.

Informacja:

In PHP 4, also $_ENV variables are escaped.

Informacja:

If the magic_quotes_sybase directive is also ON it will completely override magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NUL's will remain untouched and unescaped.

See also get_magic_quotes_gpc()

magic_quotes_runtime boolean
Ostrzeżenie

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

If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.

Functions affected by magic_quotes_runtime (does not include functions from PECL):

  • get_meta_tags()
  • file_get_contents()
  • file()
  • fgets()
  • fwrite()
  • fread()
  • fputcsv()
  • stream_socket_recvfrom()
  • exec()
  • system()
  • passthru()
  • stream_get_contents()
  • bzread()
  • gzfile()
  • gzgets()
  • gzwrite()
  • gzread()
  • exif_read_data()
  • dba_insert()
  • dba_replace()
  • dba_fetch()
  • ibase_fetch_row()
  • ibase_fetch_assoc()
  • ibase_fetch_object()
  • mssql_fetch_row()
  • mssql_fetch_object()
  • mssql_fetch_array()
  • mssql_fetch_assoc()
  • mysqli_fetch_row()
  • mysqli_fetch_array()
  • mysqli_fetch_assoc()
  • mysqli_fetch_object()
  • pg_fetch_row()
  • pg_fetch_assoc()
  • pg_fetch_array()
  • pg_fetch_object()
  • pg_fetch_all()
  • pg_select()
  • sybase_fetch_object()
  • sybase_fetch_array()
  • sybase_fetch_assoc()
  • SplFileObject::fgets()
  • SplFileObject::fgetcsv()
  • SplFileObject::fwrite()

zend.enable_gc boolean

Enables or disables the circular reference collector.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

Poniższe stałe są częścią jądra PHP a więc są zawsze widoczne.

Pre-defined phpcredits() constants
Constant | Value | Description
CREDITS_GROUP | 1 | A list of the core developers
CREDITS_GENERAL | 2 | General credits: Language design and concept, PHP authors and SAPI module.
CREDITS_SAPI | 4 | A list of the server API modules for PHP, and their authors.
CREDITS_MODULES | 8 | A list of the extension modules for PHP, and their authors.
CREDITS_DOCS | 16 | The credits for the documentation team.
CREDITS_FULLPAGE | 32 | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_QA | 64 | The credits for the quality assurance team.
CREDITS_ALL | -1 | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. This is the default value.
phpinfo() constants
Constant | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings.
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the » license faq.
INFO_ALL | -1 | Shows all of the above. This is the default value.

Assert constants, these values are used to set the assertion options in assert_options().

assert() constants
Constant | INI Setting | Description
ASSERT_ACTIVE | assert.active | Enable assert() evaluation.
ASSERT_CALLBACK | assert.callback | Callback to call on failed assertions.
ASSERT_BAIL | assert.bail | Terminate execution on failed assertions.
ASSERT_WARNING | assert.warning | Issues a PHP warning for each failed assertion
ASSERT_QUITE_EVAL | assert.quiet_eval | Disable error_reporting during assertion expression evaluation.

The following constants are only available if the host operating system is Windows, and can tell different versioning information so its possible to detect various features and make use of them. They are all available as of PHP 5.3.0.

Windows specific constants
Constant | Description
PHP_WINDOWS_VERSION_MAJOR | The major version of Windows, this can be either 4 (NT4/Me/98/95), 5 (XP/2003 R2/2003/2000) or 6 (Vista/2008).
PHP_WINDOWS_VERSION_MINOR | The minor version of Windows, this can be either 0 (Vista/2008/2000/NT4/95), 1 (XP), 2 (2003 R2/2003/XP x64), 10 (98) or 90 (ME).
PHP_WINDOWS_VERSION_BUILD | The Windows build number (for example, Windows Vista with SP1 applied is build 6001)
PHP_WINDOWS_VERSION_PLATFORM | The platform that PHP currently is running on, this value is 2 on Windows Vista/XP/2000/NT4, Server 2008/2003 and on Windows ME/98/95 this value is 1.
PHP_WINDOWS_VERSION_SP_MAJOR | The major version of the service pack installed, this value is 0 if no service pack is installed. For example, Windows XP with service pack 3 installed will make this value 3.
PHP_WINDOWS_VERSION_SP_MINOR | The minor version of the service pack installed, this value is 0 if no service pack is installed.
PHP_WINDOWS_VERSION_SUITEMASK | The suitemask is a bitmask that can tell if various features of Windows is installed, see the table below for possible bitfield values.
PHP_WINDOWS_VERSION_PRODUCTTYPE | This contains the value used to determine the PHP_WINDOWS_NT_* constants. This value may be one of the PHP_WINDOWS_NT_* constants indicating the platform type.
PHP_WINDOWS_NT_DOMAIN_CONTROLLER | This is a domain controller
PHP_WINDOWS_NT_SERVER | This is a server system (eg. Server 2008/2003/2000), note that if this is a domain controller its reported as PHP_WINDOWS_NT_DOMAIN_CONTROLLER.
PHP_WINDOWS_NT_WORKSTATION | This is a workstation system (eg. Vista/XP/2000/NT4)

This table shows a list of features that can be checked for using the PHP_WINDOWS_VERSION_SUITEMASK bitmask.

Windows suitemask bitfields
Bits | Description
0x00000004 | Microsoft BackOffice components are installed.
0x00000400 | Windows Server 2003, Web Edition is installed.
0x00004000 | Windows Server 2003, Compute Cluster Edition is installed.
0x00000080 | Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition or Windows 2000 Datacenter Server is installed.
0x00000002 | Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, Windows 2000 Advanced Server, or Windows NT Server 4.0 Enterprise Edition is installed.
0x00000040 | Windows XP Embedded is installed.
0x00000200 | Windows Vista Home Premium, Windows Vista Home Basic, or Windows XP Home Edition is installed.
0x00000100 | Remote Desktop is supported, but only one interactive session is supported. This value is set unless the system is running in application server mode.
0x00000001 | Microsoft Small Business Server was once installed on the system, but may have been upgraded to another version of Windows.
0x00000020 | Microsoft Small Business Server is installed with the restrictive client license in force.
0x00002000 | Windows Storage Server 2003 R2 or Windows Storage Server 2003 is installed.
0x00000010 | Terminal Services is installed. This value is always set. If this value is set but 0x00000100 is not set, then the system is running in application server mode.
0x00008000 | Windows Home Server is installed.
Typy zasobów
PHP Options/Info Funkcje
PHP Options/Info


PHP Options/Info Funkcje

Spis treści

  • assert_options — Set/get the various assert flags
  • assert — Checks if assertion is FALSE
  • dl — Loads a PHP extension at runtime
  • extension_loaded — Find out whether an extension is loaded
  • gc_collect_cycles — Forces collection of any existing garbage cycles
  • gc_disable — Deactivates the circular reference collector
  • gc_enable — Activates the circular reference collector
  • gc_enabled — Returns status of the circular reference collector
  • get_cfg_var — Gets the value of a PHP configuration option
  • get_current_user — Gets the name of the owner of the current PHP script
  • get_defined_constants — Returns an associative array with the names of all the constants and their values
  • get_extension_funcs — Returns an array with the names of the functions of a module
  • get_include_path — Gets the current include_path configuration option
  • get_included_files — Returns an array with the names of included or required files
  • get_loaded_extensions — Returns an array with the names of all modules compiled and loaded
  • get_magic_quotes_gpc — Gets the current configuration setting of magic_quotes_gpc
  • get_magic_quotes_runtime — Gets the current active configuration setting of magic_quotes_runtime
  • get_required_files — Alias dla get_included_files
  • getenv — Gets the value of an environment variable
  • getlastmod — Gets time of last page modification
  • getmygid — Get PHP script owner's GID
  • getmyinode — Gets the inode of the current script
  • getmypid — Gets PHP's process ID
  • getmyuid — Gets PHP script owner's UID
  • getopt — Gets options from the command line argument list
  • getrusage — Gets the current resource usages
  • ini_alter — Alias dla ini_set
  • ini_get_all — Gets all configuration options
  • ini_get — Gets the value of a configuration option
  • ini_restore — Restores the value of a configuration option
  • ini_set — Sets the value of a configuration option
  • magic_quotes_runtime — Alias dla set_magic_quotes_runtime
  • main — Dummy for main
  • memory_get_peak_usage — Returns the peak of memory allocated by PHP
  • memory_get_usage — Returns the amount of memory allocated to PHP
  • php_ini_loaded_file — Retrieve a path to the loaded php.ini file
  • php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir
  • php_logo_guid — Gets the logo guid
  • php_sapi_name — Returns the type of interface between web server and PHP
  • php_uname — Returns information about the operating system PHP is running on
  • phpcredits — Prints out the credits for PHP
  • phpinfo — Outputs information about PHP's configuration
  • phpversion — Gets the current PHP version
  • putenv — Sets the value of an environment variable
  • restore_include_path — Restores the value of the include_path configuration option
  • set_include_path — Sets the include_path configuration option
  • set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
  • set_time_limit — Limits the maximum execution time
  • sys_get_temp_dir — Returns directory path used for temporary files
  • version_compare — Compares two "PHP-standardized" version number strings
  • zend_logo_guid — Gets the Zend guid
  • zend_thread_id — Returns a unique identifier for the current thread
  • zend_version — Gets the version of the current Zend engine
Stałe predefiniowane
assert_options
PHP Options/Info


Set/get the various assert flags

PHP Options/Info Funkcje
assert
PHP Options/Info Funkcje
PHP Manual

assert_options

(PHP 4, PHP 5)

assert_options — Set/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

PHP Options/Info Funkcje
assert
PHP Options/Info Funkcje


Checks if assertion is FALSE

assert_options
dl
PHP Options/Info Funkcje
PHP Manual

assert

(PHP 4, PHP 5)

assert — Checks 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_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
    echo "<hr>Assertion Failed:
        File '$file'<br />
        Line '$line'<br />
        Code '$code'<br /><hr />";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?>

Zobacz też:

  • assert_options() - Set/get the various assert flags

assert_options
dl
PHP Options/Info Funkcje


Loads a PHP extension at runtime

assert
extension_loaded
PHP Options/Info Funkcje
PHP Manual

dl

(PHP 4, PHP 5)

dl — Loads 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_OS, 0, 3)) === 'WIN') {
        dl('php_sqlite.dll');
    } else {
        dl('sqlite.so');
    }
}

// Or, the PHP_SHLIB_SUFFIX constant is available as of PHP 4.3.0
if (!extension_loaded('sqlite')) {
    $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
    dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>

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 Loading Directives
  • extension_loaded() - Find out whether an extension is loaded

assert
extension_loaded
PHP Options/Info Funkcje


Find out whether an extension is loaded

dl
gc_collect_cycles
PHP Options/Info Funkcje
PHP Manual

extension_loaded

(PHP 4, PHP 5)

extension_loaded — Find 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ż:

  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • get_extension_funcs() - Returns an array with the names of the functions of a module
  • phpinfo() - Outputs information about PHP's configuration
  • dl() - Loads a PHP extension at runtime
  • function_exists() - Return TRUE if the given function has been defined

dl
gc_collect_cycles
PHP Options/Info Funkcje


Forces collection of any existing garbage cycles

extension_loaded
gc_disable
PHP Options/Info Funkcje
PHP Manual

gc_collect_cycles

(PHP 5 >= 5.3.0)

gc_collect_cycles — Forces 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ż:

  • Garbage Collection

extension_loaded
gc_disable
PHP Options/Info Funkcje


Deactivates the circular reference collector

gc_collect_cycles
gc_enable
PHP Options/Info Funkcje
PHP Manual

gc_disable

(PHP 5 >= 5.3.0)

gc_disable — Deactivates 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ż:

  • Garbage Collection

gc_collect_cycles
gc_enable
PHP Options/Info Funkcje


Activates the circular reference collector

gc_disable
gc_enabled
PHP Options/Info Funkcje
PHP Manual

gc_enable

(PHP 5 >= 5.3.0)

gc_enable — Activates 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ż:

  • Garbage Collection

gc_disable
gc_enabled
PHP Options/Info Funkcje


Returns status of the circular reference collector

gc_enable
get_cfg_var
PHP Options/Info Funkcje
PHP Manual

gc_enabled

(PHP 5 >= 5.3.0)

gc_enabled — Returns 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ż:

  • Garbage Collection

gc_enable
get_cfg_var
PHP Options/Info Funkcje


Gets the value of a PHP configuration option

gc_enabled
get_current_user
PHP Options/Info Funkcje
PHP Manual

get_cfg_var

(PHP 4, PHP 5)

get_cfg_var — Gets 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ż:

  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options

gc_enabled
get_current_user
PHP Options/Info Funkcje


Gets the name of the owner of the current PHP script

get_cfg_var
get_defined_constants
PHP Options/Info Funkcje
PHP Manual

get_current_user

(PHP 4, PHP 5)

get_current_user — Gets 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ż:

  • getmyuid() - Gets PHP script owner's UID
  • getmygid() - Get PHP script owner's GID
  • getmypid() - Gets PHP's process ID
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

get_cfg_var
get_defined_constants
PHP Options/Info Funkcje


Returns an associative array with the names of all the constants and their values

get_current_user
get_extension_funcs
PHP Options/Info Funkcje
PHP Manual

get_defined_constants

(PHP 4 >= 4.1.0, PHP 5)

get_defined_constants — Returns 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ż:

  • defined() - Checks whether a given named constant exists
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • get_defined_functions() - Returns an array of all defined functions
  • get_defined_vars() - Returns an array of all defined variables

get_current_user
get_extension_funcs
PHP Options/Info Funkcje


Returns an array with the names of the functions of a module

get_defined_constants
get_include_path
PHP Options/Info Funkcje
PHP Manual

get_extension_funcs

(PHP 4, PHP 5)

get_extension_funcs — Returns 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_loaded_extensions() - Returns an array with the names of all modules compiled and loaded

get_defined_constants
get_include_path
PHP Options/Info Funkcje


Gets the current include_path configuration option

get_extension_funcs
get_included_files
PHP Options/Info Funkcje
PHP Manual

get_include_path

(PHP 4 >= 4.3.0, PHP 5)

get_include_path — Gets 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ż:

  • ini_get() - Gets the value of a configuration option
  • restore_include_path() - Restores the value of the include_path configuration option
  • set_include_path() - Sets the include_path configuration option
  • include()

get_extension_funcs
get_included_files
PHP Options/Info Funkcje


Returns an array with the names of included or required files

get_include_path
get_loaded_extensions
PHP Options/Info Funkcje
PHP Manual

get_included_files

(PHP 4, PHP 5)

get_included_files — Returns 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_include_path
get_loaded_extensions
PHP Options/Info Funkcje


Returns an array with the names of all modules compiled and loaded

get_included_files
get_magic_quotes_gpc
PHP Options/Info Funkcje
PHP Manual

get_loaded_extensions

(PHP 4, PHP 5)

get_loaded_extensions — Returns 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_extension_funcs() - Returns an array with the names of the functions of a module
  • extension_loaded() - Find out whether an extension is loaded
  • dl() - Loads a PHP extension at runtime
  • phpinfo() - Outputs information about PHP's configuration

get_included_files
get_magic_quotes_gpc
PHP Options/Info Funkcje


Gets the current configuration setting of magic_quotes_gpc

get_loaded_extensions
get_magic_quotes_runtime
PHP Options/Info Funkcje
PHP Manual

get_magic_quotes_gpc

(PHP 4, PHP 5)

get_magic_quotes_gpc — Gets 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ż:

  • addslashes() - Quote string with slashes
  • stripslashes() - Un-quotes a quoted string
  • get_magic_quotes_runtime() - Gets the current active configuration setting of magic_quotes_runtime
  • ini_get() - Gets the value of a configuration option

get_loaded_extensions
get_magic_quotes_runtime
PHP Options/Info Funkcje


Gets the current active configuration setting of magic_quotes_runtime

get_magic_quotes_gpc
get_required_files
PHP Options/Info Funkcje
PHP Manual

get_magic_quotes_runtime

(PHP 4, PHP 5)

get_magic_quotes_runtime — Gets 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_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • set_magic_quotes_runtime() - Sets the current active configuration setting of magic_quotes_runtime

get_magic_quotes_gpc
get_required_files
PHP Options/Info Funkcje


Alias dla get_included_files

get_magic_quotes_runtime
getenv
PHP Options/Info Funkcje
PHP Manual

get_required_files

(PHP 4, PHP 5)

get_required_files — Alias dla get_included_files()

Opis

Ta funkcja jest aliasem dla: get_included_files().

get_magic_quotes_runtime
getenv
PHP Options/Info Funkcje


Gets the value of an environment variable

get_required_files
getlastmod
PHP Options/Info Funkcje
PHP Manual

getenv

(PHP 4, PHP 5)

getenv — Gets 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ż:

  • putenv() - Sets the value of an environment variable
  • apache_getenv() - Get an Apache subprocess_env variable
  • Superglobals

get_required_files
getlastmod
PHP Options/Info Funkcje


Gets time of last page modification

getenv
getmygid
PHP Options/Info Funkcje
PHP Manual

getlastmod

(PHP 4, PHP 5)

getlastmod — Gets 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ż:

  • date() - Formatuje lokalny czas/datę
  • getmyuid() - Gets PHP script owner's UID
  • getmygid() - Get PHP script owner's GID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getmypid() - Gets PHP's process ID
  • filemtime() - Pobiera czas ostatniej modyfikacji pliku

getenv
getmygid
PHP Options/Info Funkcje


Get PHP script owner's GID

getlastmod
getmyinode
PHP Options/Info Funkcje
PHP Manual

getmygid

(PHP 4 >= 4.1.0, PHP 5)

getmygid — Get 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ż:

  • getmyuid() - Gets PHP script owner's UID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

getlastmod
getmyinode
PHP Options/Info Funkcje


Gets the inode of the current script

getmygid
getmypid
PHP Options/Info Funkcje
PHP Manual

getmyinode

(PHP 4, PHP 5)

getmyinode — Gets 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ż:

  • getmygid() - Get PHP script owner's GID
  • getmyuid() - Gets PHP script owner's UID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getlastmod() - Gets time of last page modification

getmygid
getmypid
PHP Options/Info Funkcje


Gets PHP's process ID

getmyinode
getmyuid
PHP Options/Info Funkcje
PHP Manual

getmypid

(PHP 4, PHP 5)

getmypid — Gets 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ż:

  • getmygid() - Get PHP script owner's GID
  • getmyuid() - Gets PHP script owner's UID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

getmyinode
getmyuid
PHP Options/Info Funkcje


Gets PHP script owner's UID

getmypid
getopt
PHP Options/Info Funkcje
PHP Manual

getmyuid

(PHP 4, PHP 5)

getmyuid — Gets 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ż:

  • getmygid() - Get PHP script owner's GID
  • getmypid() - Gets PHP's process ID
  • get_current_user() - Gets the name of the owner of the current PHP script
  • getmyinode() - Gets the inode of the current script
  • getlastmod() - Gets time of last page modification

getmypid
getopt
PHP Options/Info Funkcje


Gets options from the command line argument list

getmyuid
getrusage
PHP Options/Info Funkcje
PHP Manual

getopt

(PHP 4 >= 4.3.0, PHP 5)

getopt — Gets 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) where as options takes a string (where each character is the option).

Zwracane wartości

This function will return an array of option / argument pairs or FALSE on failure.

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

  • $argv

getmyuid
getrusage
PHP Options/Info Funkcje


Gets the current resource usages

getopt
ini_alter
PHP Options/Info Funkcje
PHP Manual

getrusage

(PHP 4, PHP 5)

getrusage — Gets 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)

getopt
ini_alter
PHP Options/Info Funkcje


Alias dla ini_set

getrusage
ini_get_all
PHP Options/Info Funkcje
PHP Manual

ini_alter

(PHP 4, PHP 5)

ini_alter — Alias dla ini_set()

Opis

Ta funkcja jest aliasem dla: ini_set().

getrusage
ini_get_all
PHP Options/Info Funkcje


Gets all configuration options

ini_alter
ini_get
PHP Options/Info Funkcje
PHP Manual

ini_get_all

(PHP 4 >= 4.2.0, PHP 5)

ini_get_all — Gets 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(null, false)); // 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ż:

  • How to change configuration settings
  • ini_get() - Gets the value of a configuration option
  • ini_restore() - Restores the value of a configuration option
  • ini_set() - Sets the value of a configuration option
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • phpinfo() - Outputs information about PHP's configuration

ini_alter
ini_get
PHP Options/Info Funkcje


Gets the value of a configuration option

ini_get_all
ini_restore
PHP Options/Info Funkcje
PHP Manual

ini_get

(PHP 4, PHP 5)

ini_get — Gets 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ż:

  • get_cfg_var() - Gets the value of a PHP configuration option
  • ini_get_all() - Gets all configuration options
  • ini_restore() - Restores the value of a configuration option
  • ini_set() - Sets the value of a configuration option

ini_get_all
ini_restore
PHP Options/Info Funkcje


Restores the value of a configuration option

ini_get
ini_set
PHP Options/Info Funkcje
PHP Manual

ini_restore

(PHP 4, PHP 5)

ini_restore — Restores 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($setting, ini_get($setting) ? 0 : 1);
echo 'New value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_restore($setting);
echo 'Original value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
?>

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_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options
  • ini_set() - Sets the value of a configuration option

ini_get
ini_set
PHP Options/Info Funkcje


Sets the value of a configuration option

ini_restore
magic_quotes_runtime
PHP Options/Info Funkcje
PHP Manual

ini_set

(PHP 4, PHP 5)

ini_set — Sets 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ż:

  • get_cfg_var() - Gets the value of a PHP configuration option
  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options
  • ini_restore() - Restores the value of a configuration option
  • How to change configuration settings

ini_restore
magic_quotes_runtime
PHP Options/Info Funkcje


Alias dla set_magic_quotes_runtime

ini_set
main
PHP Options/Info Funkcje
PHP Manual

magic_quotes_runtime

(PHP 4, PHP 5)

magic_quotes_runtime — Alias dla set_magic_quotes_runtime()

Opis

Ta funkcja jest aliasem dla: set_magic_quotes_runtime()

ini_set
main
PHP Options/Info Funkcje


Dummy for main

magic_quotes_runtime
memory_get_peak_usage
PHP Options/Info Funkcje
PHP Manual

main

main — Dummy 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

Zobacz też:

  • html_errors
  • display_errors

magic_quotes_runtime
memory_get_peak_usage
PHP Options/Info Funkcje


Returns the peak of memory allocated by PHP

main
memory_get_usage
PHP Options/Info Funkcje
PHP Manual

memory_get_peak_usage

(PHP 5 >= 5.2.0)

memory_get_peak_usage — Returns 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() - Returns the amount of memory allocated to PHP
  • memory_limit

main
memory_get_usage
PHP Options/Info Funkcje


Returns the amount of memory allocated to PHP

memory_get_peak_usage
php_ini_loaded_file
PHP Options/Info Funkcje
PHP Manual

memory_get_usage

(PHP 4 >= 4.3.2, PHP 5)

memory_get_usage — Returns 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ż:

  • memory_get_peak_usage() - Returns the peak of memory allocated by PHP
  • memory_limit

memory_get_peak_usage
php_ini_loaded_file
PHP Options/Info Funkcje


Retrieve a path to the loaded php.ini file

memory_get_usage
php_ini_scanned_files
PHP Options/Info Funkcje
PHP Manual

php_ini_loaded_file

(PHP 5 >= 5.2.4)

php_ini_loaded_file — Retrieve 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() - Return a list of .ini files parsed from the additional ini dir
  • phpinfo() - Outputs information about PHP's configuration
  • The configuration file

memory_get_usage
php_ini_scanned_files
PHP Options/Info Funkcje


Return a list of .ini files parsed from the additional ini dir

php_ini_loaded_file
php_logo_guid
PHP Options/Info Funkcje
PHP Manual

php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5)

php_ini_scanned_files — Return 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ż:

  • ini_set() - Sets the value of a configuration option
  • phpinfo() - Outputs information about PHP's configuration
  • php_ini_loaded_file() - Retrieve a path to the loaded php.ini file

php_ini_loaded_file
php_logo_guid
PHP Options/Info Funkcje


Gets the logo guid

php_ini_scanned_files
php_sapi_name
PHP Options/Info Funkcje
PHP Manual

php_logo_guid

(PHP 4, PHP 5)

php_logo_guid — Gets 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ż:

  • phpinfo() - Outputs information about PHP's configuration
  • phpversion() - Gets the current PHP version
  • phpcredits() - Prints out the credits for PHP
  • zend_logo_guid() - Gets the Zend guid

php_ini_scanned_files
php_sapi_name
PHP Options/Info Funkcje


Returns the type of interface between web server and PHP

php_logo_guid
php_uname
PHP Options/Info Funkcje
PHP Manual

php_sapi_name

(PHP 4 >= 4.0.1, PHP 5)

php_sapi_name — Returns 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_type, 0, 3) == '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_SAPI

php_logo_guid
php_uname
PHP Options/Info Funkcje


Returns information about the operating system PHP is running on

php_sapi_name
phpcredits
PHP Options/Info Funkcje
PHP Manual

php_uname

(PHP 4 >= 4.0.2, PHP 5)

php_uname — Returns 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_OS, 0, 3)) === 'WIN') {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

?>

There are also some related Predefined PHP constants that may come in handy, for example:

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

  • phpversion() - Gets the current PHP version
  • php_sapi_name() - Returns the type of interface between web server and PHP
  • phpinfo() - Outputs information about PHP's configuration

php_sapi_name
phpcredits
PHP Options/Info Funkcje


Prints out the credits for PHP

php_uname
phpinfo
PHP Options/Info Funkcje
PHP Manual

phpcredits

(PHP 4, PHP 5)

phpcredits — Prints 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ż:

  • phpversion() - Gets the current PHP version
  • php_logo_guid() - Gets the logo guid
  • phpinfo() - Outputs information about PHP's configuration

php_uname
phpinfo
PHP Options/Info Funkcje


Outputs information about PHP's configuration

phpcredits
phpversion
PHP Options/Info Funkcje
PHP Manual

phpinfo

(PHP 4, PHP 5)

phpinfo — Outputs 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() - Gets the current PHP version
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • ini_get() - Gets the value of a configuration option
  • ini_set() - Sets the value of a configuration option
  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • Predefined Variables

phpcredits
phpversion
PHP Options/Info Funkcje


Gets the current PHP version

phpinfo
putenv
PHP Options/Info Funkcje
PHP Manual

phpversion

(PHP 4, PHP 5)

phpversion — Gets 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ż:

  • PHP_VERSION constants
  • version_compare() - Compares two "PHP-standardized" version number strings
  • phpinfo() - Outputs information about PHP's configuration
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • zend_version() - Gets the version of the current Zend engine

phpinfo
putenv
PHP Options/Info Funkcje


Sets the value of an environment variable

phpversion
restore_include_path
PHP Options/Info Funkcje
PHP Manual

putenv

(PHP 4, PHP 5)

putenv — Sets 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

phpversion
restore_include_path
PHP Options/Info Funkcje


Restores the value of the include_path configuration option

putenv
set_include_path
PHP Options/Info Funkcje
PHP Manual

restore_include_path

(PHP 4 >= 4.3.0, PHP 5)

restore_include_path — Restores 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ż:

  • ini_restore() - Restores the value of a configuration option
  • get_include_path() - Gets the current include_path configuration option
  • set_include_path() - Sets the include_path configuration option
  • include()

putenv
set_include_path
PHP Options/Info Funkcje


Sets the include_path configuration option

restore_include_path
set_magic_quotes_runtime
PHP Options/Info Funkcje
PHP Manual

set_include_path

(PHP 4 >= 4.3.0, PHP 5)

set_include_path — Sets 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ż:

  • ini_set() - Sets the value of a configuration option
  • get_include_path() - Gets the current include_path configuration option
  • restore_include_path() - Restores the value of the include_path configuration option
  • include()

restore_include_path
set_magic_quotes_runtime
PHP Options/Info Funkcje


Sets the current active configuration setting of magic_quotes_runtime

set_include_path
set_time_limit
PHP Options/Info Funkcje
PHP Manual

set_magic_quotes_runtime

(PHP 4, PHP 5)

set_magic_quotes_runtime — Sets 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($fp, 64), PHP_EOL;

// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);

echo 'With magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// Clean up
fclose($fp);
?>

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

  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • get_magic_quotes_runtime() - Gets the current active configuration setting of magic_quotes_runtime

set_include_path
set_time_limit
PHP Options/Info Funkcje


Limits the maximum execution time

set_magic_quotes_runtime
sys_get_temp_dir
PHP Options/Info Funkcje
PHP Manual

set_time_limit

(PHP 4, PHP 5)

set_time_limit — Limits 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.

Zobacz też:

  • max_execution_time
  • max_input_time

set_magic_quotes_runtime
sys_get_temp_dir
PHP Options/Info Funkcje


Returns directory path used for temporary files

set_time_limit
version_compare
PHP Options/Info Funkcje
PHP Manual

sys_get_temp_dir

(PHP 5 >= 5.2.1)

sys_get_temp_dir — Returns 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ż:

  • tmpfile() - Tworzy plik tymczasowy
  • tempnam() - Create file with unique file name

set_time_limit
version_compare
PHP Options/Info Funkcje


Compares two "PHP-standardized" version number strings

sys_get_temp_dir
zend_logo_guid
PHP Options/Info Funkcje
PHP Manual

version_compare

(PHP 4 >= 4.1.0, PHP 5)

version_compare — Compares 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ż:

  • phpversion() - Gets the current PHP version
  • php_uname() - Returns information about the operating system PHP is running on
  • function_exists() - Return TRUE if the given function has been defined

sys_get_temp_dir
zend_logo_guid
PHP Options/Info Funkcje


Gets the Zend guid

version_compare
zend_thread_id
PHP Options/Info Funkcje
PHP Manual

zend_logo_guid

(PHP 4, PHP 5)

zend_logo_guid — Gets 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ż:

  • php_logo_guid() - Gets the logo guid

version_compare
zend_thread_id
PHP Options/Info Funkcje


Returns a unique identifier for the current thread

zend_logo_guid
zend_version
PHP Options/Info Funkcje
PHP Manual

zend_thread_id

(PHP 5)

zend_thread_id — Returns 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_logo_guid
zend_version
PHP Options/Info Funkcje


Gets the version of the current Zend engine

zend_thread_id
runkit
PHP Options/Info Funkcje
PHP Manual

zend_version

(PHP 4, PHP 5)

zend_version — Gets 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ż:

  • phpinfo() - Outputs information about PHP's configuration
  • phpcredits() - Prints out the credits for PHP
  • php_logo_guid() - Gets the logo guid
  • phpversion() - Gets the current PHP version

zend_thread_id
runkit
PHP Options/Info Funkcje


runkit

  • Wstęp
  • Stałe predefiniowane
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • runkit Funkcje
    • Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine
    • Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class
    • runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate
    • runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral
    • runkit_constant_add — Similar to define(), but allows defining in class definitions as well
    • runkit_constant_redefine — Redefine an already defined constant
    • runkit_constant_remove — Remove/Delete an already defined constant
    • runkit_function_add — Add a new function, similar to create_function
    • runkit_function_copy — Copy a function to a new function name
    • runkit_function_redefine — Replace a function definition with a new implementation
    • runkit_function_remove — Remove a function definition
    • runkit_function_rename — Change a function's name
    • runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit_lint_file — Check the PHP syntax of the specified file
    • runkit_lint — Check the PHP syntax of the specified php code
    • runkit_method_add — Dynamically adds a new method to a given class
    • runkit_method_copy — Copies a method from class to another
    • runkit_method_redefine — Dynamically changes the code of the given method
    • runkit_method_remove — Dynamically removes the given method
    • runkit_method_rename — Dynamically changes the name of the given method
    • runkit_return_value_used — Determines if the current functions return value will be used
    • runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox
    • runkit_superglobals — Return numerically indexed array of registered superglobals
zend_version
Wstęp
Wpływ na zachowanie PHP


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.

runkit
Stałe predefiniowane
runkit


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.
Wstęp
Instalacja/Konfiguracja
runkit


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Stałe predefiniowane
Wymagania
runkit


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/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
runkit Funkcje
Instalacja/Konfiguracja


runkit Funkcje

Spis treści

  • Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine
  • Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class
  • runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate
  • runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral
  • runkit_constant_add — Similar to define(), but allows defining in class definitions as well
  • runkit_constant_redefine — Redefine an already defined constant
  • runkit_constant_remove — Remove/Delete an already defined constant
  • runkit_function_add — Add a new function, similar to create_function
  • runkit_function_copy — Copy a function to a new function name
  • runkit_function_redefine — Replace a function definition with a new implementation
  • runkit_function_remove — Remove a function definition
  • runkit_function_rename — Change a function's name
  • runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate
  • runkit_lint_file — Check the PHP syntax of the specified file
  • runkit_lint — Check the PHP syntax of the specified php code
  • runkit_method_add — Dynamically adds a new method to a given class
  • runkit_method_copy — Copies a method from class to another
  • runkit_method_redefine — Dynamically changes the code of the given method
  • runkit_method_remove — Dynamically removes the given method
  • runkit_method_rename — Dynamically changes the name of the given method
  • runkit_return_value_used — Determines if the current functions return value will be used
  • runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox
  • runkit_superglobals — Return numerically indexed array of registered superglobals
Typy zasobów
Runkit_Sandbox
runkit


Runkit Sandbox Class -- PHP Virtual Machine

runkit Funkcje
Runkit_Sandbox_Parent
runkit Funkcje
PHP Manual

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 Funkcje
Runkit_Sandbox_Parent
runkit Funkcje


Runkit Anti-Sandbox Class

Runkit_Sandbox
runkit_class_adopt
runkit Funkcje
PHP Manual

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_Sandbox
runkit_class_adopt
runkit Funkcje


Convert a base class to an inherited class, add ancestral methods when appropriate

Runkit_Sandbox_Parent
runkit_class_emancipate
runkit Funkcje
PHP Manual

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() - Convert an inherited class to a base class, removes any method whose scope is ancestral

Runkit_Sandbox_Parent
runkit_class_emancipate
runkit Funkcje


Convert an inherited class to a base class, removes any method whose scope is ancestral

runkit_class_adopt
runkit_constant_add
runkit Funkcje
PHP Manual

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_class_adopt
runkit_constant_add
runkit Funkcje


Similar to define(), but allows defining in class definitions as well

runkit_class_emancipate
runkit_constant_redefine
runkit Funkcje
PHP Manual

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

  • define() - Defines a named constant
  • runkit_constant_redefine() - Redefine an already defined constant
  • runkit_constant_remove() - Remove/Delete an already defined constant

runkit_class_emancipate
runkit_constant_redefine
runkit Funkcje


Redefine an already defined constant

runkit_constant_add
runkit_constant_remove
runkit Funkcje
PHP Manual

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_add() - Similar to define(), but allows defining in class definitions as well
  • runkit_constant_remove() - Remove/Delete an already defined constant

runkit_constant_add
runkit_constant_remove
runkit Funkcje


Remove/Delete an already defined constant

runkit_constant_redefine
runkit_function_add
runkit Funkcje
PHP Manual

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

  • define() - Defines a named constant
  • runkit_constant_add() - Similar to define(), but allows defining in class definitions as well
  • runkit_constant_redefine() - Redefine an already defined constant

runkit_constant_redefine
runkit_function_add
runkit Funkcje


Add a new function, similar to create_function

runkit_constant_remove
runkit_function_copy
runkit Funkcje
PHP Manual

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

  • create_function() - Create an anonymous (lambda-style) function
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition
  • runkit_method_add() - Dynamically adds a new method to a given class

runkit_constant_remove
runkit_function_copy
runkit Funkcje


Copy a function to a new function name

runkit_function_add
runkit_function_redefine
runkit Funkcje
PHP Manual

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_add() - Add a new function, similar to create_function
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition

runkit_function_add
runkit_function_redefine
runkit Funkcje


Replace a function definition with a new implementation

runkit_function_copy
runkit_function_remove
runkit Funkcje
PHP Manual

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_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition

runkit_function_copy
runkit_function_remove
runkit Funkcje


Remove a function definition

runkit_function_redefine
runkit_function_rename
runkit Funkcje
PHP Manual

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_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_rename() - Change a function's name

runkit_function_redefine
runkit_function_rename
runkit Funkcje


Change a function's name

runkit_function_remove
runkit_import
runkit Funkcje
PHP Manual

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_function_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_remove() - Remove a function definition

runkit_function_remove
runkit_import
runkit Funkcje


Process a PHP file importing function and class definitions, overwriting where appropriate

runkit_function_rename
runkit_lint_file
runkit Funkcje
PHP Manual

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_function_rename
runkit_lint_file
runkit Funkcje


Check the PHP syntax of the specified file

runkit_import
runkit_lint
runkit Funkcje
PHP Manual

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() - Check the PHP syntax of the specified php code

runkit_import
runkit_lint
runkit Funkcje


Check the PHP syntax of the specified php code

runkit_lint_file
runkit_method_add
runkit Funkcje
PHP Manual

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_lint_file() - Check the PHP syntax of the specified file

runkit_lint_file
runkit_method_add
runkit Funkcje


Dynamically adds a new method to a given class

runkit_lint
runkit_method_copy
runkit Funkcje
PHP Manual

runkit_method_add

(PECL runkit >= 0.7.0)

runkit_method_add — Dynamically 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(12, 4);
?>

Powyższy przykład wyświetli:

16

Zobacz też:

  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_add() - Add a new function, similar to create_function

runkit_lint
runkit_method_copy
runkit Funkcje


Copies a method from class to another

runkit_method_add
runkit_method_redefine
runkit Funkcje
PHP Manual

runkit_method_copy

(PECL runkit >= 0.7.0)

runkit_method_copy — Copies 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_add() - Dynamically adds a new method to a given class
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_copy() - Copy a function to a new function name

runkit_method_add
runkit_method_redefine
runkit Funkcje


Dynamically changes the code of the given method

runkit_method_copy
runkit_method_remove
runkit Funkcje
PHP Manual

runkit_method_redefine

(PECL runkit >= 0.7.0)

runkit_method_redefine — Dynamically 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_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_redefine() - Replace a function definition with a new implementation

runkit_method_copy
runkit_method_remove
runkit Funkcje


Dynamically removes the given method

runkit_method_redefine
runkit_method_rename
runkit Funkcje
PHP Manual

runkit_method_remove

(PECL runkit >= 0.7.0)

runkit_method_remove — Dynamically 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_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_remove() - Remove a function definition

runkit_method_redefine
runkit_method_rename
runkit Funkcje


Dynamically changes the name of the given method

runkit_method_remove
runkit_return_value_used
runkit Funkcje
PHP Manual

runkit_method_rename

(PECL runkit >= 0.7.0)

runkit_method_rename — Dynamically 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_method_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_function_rename() - Change a function's name

runkit_method_remove
runkit_return_value_used
runkit Funkcje


Determines if the current functions return value will be used

runkit_method_rename
runkit_sandbox_output_handler
runkit Funkcje
PHP Manual

runkit_return_value_used

(PECL runkit >= 0.8.0)

runkit_return_value_used — Determines 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_method_rename
runkit_sandbox_output_handler
runkit Funkcje


Specify a function to capture and/or process output from a runkit sandbox

runkit_return_value_used
runkit_superglobals
runkit Funkcje
PHP Manual

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_return_value_used
runkit_superglobals
runkit Funkcje


Return numerically indexed array of registered superglobals

runkit_sandbox_output_handler
scream
runkit Funkcje
PHP Manual

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

  • Variable Scope

runkit_sandbox_output_handler
scream
runkit Funkcje


Break the silence operator

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Przykłady
    • Example that shows the effect of scream
runkit_superglobals
Wstęp
Wpływ na zachowanie PHP


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.

scream
Instalacja/Konfiguracja
scream


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
scream


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
Przykłady
Instalacja/Konfiguracja


Przykłady

Spis treści

  • Example that shows the effect of scream
Typy zasobów
Example that shows the effect of scream
scream


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.

Przykłady
Weakref
Przykłady


Weak References

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Typy zasobów
  • Weakref — The Weakref class
    • Weakref::acquire — Acquires a strong reference on that object
    • Weakref::__construct — Constructs a new weak reference
    • Weakref::get — Returns the object pointed to by the weak reference
    • Weakref::release — Releases a previously acquired reference
    • Weakref::valid — Checks whether the object referenced still exists
Example that shows the effect of scream
Wstęp
Wpływ na zachowanie PHP


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!

Weakref
Instalacja/Konfiguracja
Weakref


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Typy zasobów
Wstęp
Wymagania
Weakref


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/

Wymagania
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Instalacja
Weakref
Instalacja/Konfiguracja


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!

Spis treści

  • Weakref::acquire — Acquires a strong reference on that object
  • Weakref::__construct — Constructs a new weak reference
  • Weakref::get — Returns the object pointed to by the weak reference
  • Weakref::release — Releases a previously acquired reference
  • Weakref::valid — Checks whether the object referenced still exists
Typy zasobów
Weakref::acquire
Weakref


Acquires a strong reference on that object

Weakref
Weakref::__construct
Weakref
PHP Manual

Weakref::acquire

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

Weakref::acquire — Acquires 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::release() - Releases a previously acquired reference

Weakref
Weakref::__construct
Weakref


Constructs a new weak reference

Weakref::acquire
Weakref::get
Weakref
PHP Manual

Weakref::__construct

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

Weakref::__construct — Constructs 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::acquire
Weakref::get
Weakref


Returns the object pointed to by the weak reference

Weakref::__construct
Weakref::release
Weakref
PHP Manual

Weakref::get

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

Weakref::get — Returns 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::valid() - Checks whether the object referenced still exists

Weakref::__construct
Weakref::release
Weakref


Releases a previously acquired reference

Weakref::get
Weakref::valid
Weakref
PHP Manual

Weakref::release

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

Weakref::release — Releases 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::acquire() - Acquires a strong reference on that object

Weakref::get
Weakref::valid
Weakref


Checks whether the object referenced still exists

Weakref::release
WinCache
Weakref
PHP Manual

Weakref::valid

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

Weakref::valid — Checks 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

Weakref::release
WinCache
Weakref


Windows Cache for PHP

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • WinCache Statistics Script
    • WinCache Session Handler
    • WinCache Functions Reroutes
    • Typy zasobów
  • Stałe predefiniowane
  • WinCache Funkcje
    • wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo — Retrieves information about file cache memory usage
    • wincache_lock — Acquires an exclusive lock on a given key
    • wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed — Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo — Retrieves information about resolve file path cache
    • wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
    • wincache_scache_info — Retrieves information about files cached in the session cache
    • wincache_scache_meminfo — Retrieves information about session cache memory usage
    • wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
    • wincache_ucache_cas — Compares the variable with old value and assigns new value to it
    • wincache_ucache_clear — Deletes entire content of the user cache
    • wincache_ucache_dec — Decrements the value associated with the key
    • wincache_ucache_delete — Deletes variables from the user cache
    • wincache_ucache_exists — Checks if a variable exists in the user cache
    • wincache_ucache_get — Gets a variable stored in the user cache
    • wincache_ucache_inc — Increments the value associated with the key
    • wincache_ucache_info — Retrieves information about data stored in the user cache
    • wincache_ucache_meminfo — Retrieves information about user cache memory usage
    • wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
    • wincache_unlock — Releases an exclusive lock on a given key
  • Building for Windows
    • Prerequisites
    • Compiling and building
    • Verifying the build
Weakref::valid
Wstęp
Wpływ na zachowanie 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.

WinCache
Instalacja/Konfiguracja
WinCache


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • WinCache Statistics Script
  • WinCache Session Handler
  • WinCache Functions Reroutes
  • Typy zasobów
Wstęp
Wymagania
WinCache


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/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Instalacja
WinCache Statistics Script
Instalacja/Konfiguracja


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.

Konfiguracja wykonawcza
WinCache Session Handler
Instalacja/Konfiguracja


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 Statistics Script
WinCache Functions Reroutes
Instalacja/Konfiguracja


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:

  • file_exists
  • file_get_contents
  • readfile
  • is_readable
  • is_writable
  • is_dir
  • realpath
  • filesize

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

WinCache Session Handler
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

WinCache Functions Reroutes
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
WinCache Funkcje
WinCache


WinCache Funkcje

Spis treści

  • wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo — Retrieves information about file cache memory usage
  • wincache_lock — Acquires an exclusive lock on a given key
  • wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
  • wincache_refresh_if_changed — Refreshes the cache entries for the cached files
  • wincache_rplist_fileinfo — Retrieves information about resolve file path cache
  • wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
  • wincache_scache_info — Retrieves information about files cached in the session cache
  • wincache_scache_meminfo — Retrieves information about session cache memory usage
  • wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_cas — Compares the variable with old value and assigns new value to it
  • wincache_ucache_clear — Deletes entire content of the user cache
  • wincache_ucache_dec — Decrements the value associated with the key
  • wincache_ucache_delete — Deletes variables from the user cache
  • wincache_ucache_exists — Checks if a variable exists in the user cache
  • wincache_ucache_get — Gets a variable stored in the user cache
  • wincache_ucache_inc — Increments the value associated with the key
  • wincache_ucache_info — Retrieves information about data stored in the user cache
  • wincache_ucache_meminfo — Retrieves information about user cache memory usage
  • wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_unlock — Releases an exclusive lock on a given key
Stałe predefiniowane
wincache_fcache_fileinfo
WinCache


Retrieves information about files cached in the file cache

WinCache Funkcje
wincache_fcache_meminfo
WinCache Funkcje
PHP Manual

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() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

WinCache Funkcje
wincache_fcache_meminfo
WinCache Funkcje


Retrieves information about file cache memory usage

wincache_fcache_fileinfo
wincache_lock
WinCache Funkcje
PHP Manual

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_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

wincache_fcache_fileinfo
wincache_lock
WinCache Funkcje


Acquires an exclusive lock on a given key

wincache_fcache_meminfo
wincache_ocache_fileinfo
WinCache Funkcje
PHP Manual

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($fp, 0); // 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_unlock() - Releases an exclusive lock on a given key
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

wincache_fcache_meminfo
wincache_ocache_fileinfo
WinCache Funkcje


Retrieves information about files cached in the opcode cache

wincache_lock
wincache_ocache_meminfo
WinCache Funkcje
PHP Manual

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_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

wincache_lock
wincache_ocache_meminfo
WinCache Funkcje


Retrieves information about opcode cache memory usage

wincache_ocache_fileinfo
wincache_refresh_if_changed
WinCache Funkcje
PHP Manual

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_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

wincache_ocache_fileinfo
wincache_refresh_if_changed
WinCache Funkcje


Refreshes the cache entries for the cached files

wincache_ocache_meminfo
wincache_rplist_fileinfo
WinCache Funkcje
PHP Manual

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_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

wincache_ocache_meminfo
wincache_rplist_fileinfo
WinCache Funkcje


Retrieves information about resolve file path cache

wincache_refresh_if_changed
wincache_rplist_meminfo
WinCache Funkcje
PHP Manual

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_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

wincache_refresh_if_changed
wincache_rplist_meminfo
WinCache Funkcje


Retrieves information about memory usage by the resolve file path cache

wincache_rplist_fileinfo
wincache_scache_info
WinCache Funkcje
PHP Manual

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_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

wincache_rplist_fileinfo
wincache_scache_info
WinCache Funkcje


Retrieves information about files cached in the session cache

wincache_rplist_meminfo
wincache_scache_meminfo
WinCache Funkcje
PHP Manual

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_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

wincache_rplist_meminfo
wincache_scache_meminfo
WinCache Funkcje


Retrieves information about session cache memory usage

wincache_scache_info
wincache_ucache_add
WinCache Funkcje
PHP Manual

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_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

wincache_scache_info
wincache_ucache_add
WinCache Funkcje


Adds a variable in user cache only if variable does not already exist in the cache

wincache_scache_meminfo
wincache_ucache_cas
WinCache Funkcje
PHP Manual

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_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __sleep()

wincache_scache_meminfo
wincache_ucache_cas
WinCache Funkcje


Compares the variable with old value and assigns new value to it

wincache_ucache_add
wincache_ucache_clear
WinCache Funkcje
PHP Manual

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', 2922, 1));
var_dump(wincache_ucache_get('counter'));
?>

Powyższy przykład wyświetli:

bool(true)
int(1)

Zobacz też:

  • wincache_ucache_inc() - Increments the value associated with the key
  • wincache_ucache_dec() - Decrements the value associated with the key

wincache_ucache_add
wincache_ucache_clear
WinCache Funkcje


Deletes entire content of the user cache

wincache_ucache_cas
wincache_ucache_dec
WinCache Funkcje
PHP Manual

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_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

wincache_ucache_cas
wincache_ucache_dec
WinCache Funkcje


Decrements the value associated with the key

wincache_ucache_clear
wincache_ucache_delete
WinCache Funkcje
PHP Manual

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_inc() - Increments the value associated with the key
  • wincache_ucache_cas() - Compares the variable with old value and assigns new value to it

wincache_ucache_clear
wincache_ucache_delete
WinCache Funkcje


Deletes variables from the user cache

wincache_ucache_dec
wincache_ucache_exists
WinCache Funkcje
PHP Manual

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_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

wincache_ucache_dec
wincache_ucache_exists
WinCache Funkcje


Checks if a variable exists in the user cache

wincache_ucache_delete
wincache_ucache_get
WinCache Funkcje
PHP Manual

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_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

wincache_ucache_delete
wincache_ucache_get
WinCache Funkcje


Gets a variable stored in the user cache

wincache_ucache_exists
wincache_ucache_inc
WinCache Funkcje
PHP Manual

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_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __wakeup()

wincache_ucache_exists
wincache_ucache_inc
WinCache Funkcje


Increments the value associated with the key

wincache_ucache_get
wincache_ucache_info
WinCache Funkcje
PHP Manual

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_dec() - Decrements the value associated with the key
  • wincache_ucache_cas() - Compares the variable with old value and assigns new value to it

wincache_ucache_get
wincache_ucache_info
WinCache Funkcje


Retrieves information about data stored in the user cache

wincache_ucache_inc
wincache_ucache_meminfo
WinCache Funkcje
PHP Manual

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_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

wincache_ucache_inc
wincache_ucache_meminfo
WinCache Funkcje


Retrieves information about user cache memory usage

wincache_ucache_info
wincache_ucache_set
WinCache Funkcje
PHP Manual

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_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

wincache_ucache_info
wincache_ucache_set
WinCache Funkcje


Adds a variable in user cache and overwrites a variable if it already exists in the cache

wincache_ucache_meminfo
wincache_unlock
WinCache Funkcje
PHP Manual

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_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __sleep()

wincache_ucache_meminfo
wincache_unlock
WinCache Funkcje


Releases an exclusive lock on a given key

wincache_ucache_set
Building for Windows
WinCache Funkcje
PHP Manual

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($fp, 0); // 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_lock() - Acquires an exclusive lock on a given key
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

wincache_ucache_set
Building for Windows
WinCache Funkcje


Building for Windows

Spis treści

  • Prerequisites
  • Compiling and building
  • Verifying the build
wincache_unlock
Prerequisites
WinCache


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.

Building for Windows
Compiling and building
Building for Windows


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

Prerequisites
Verifying the build
Building for Windows


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.

Compiling and building
Xhprof
Building for Windows


Hierarchical Profiler

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Xhprof Funkcje
    • xhprof_disable — Stops xhprof profiler
    • xhprof_enable — Start xhprof profiler
    • xhprof_sample_disable — Stops xhprof sample profiler
    • xhprof_sample_enable — Description
Verifying the build
Wstęp
Wpływ na zachowanie PHP


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.

Xhprof
Instalacja/Konfiguracja
Xhprof


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Xhprof


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/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.
Typy zasobów
Przykłady
Xhprof


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
Stałe predefiniowane
Xhprof Funkcje
Xhprof


Xhprof Funkcje

Spis treści

  • xhprof_disable — Stops xhprof profiler
  • xhprof_enable — Start xhprof profiler
  • xhprof_sample_disable — Stops xhprof sample profiler
  • xhprof_sample_enable — Description
Przykłady
xhprof_disable
Xhprof


Stops xhprof profiler

Xhprof Funkcje
xhprof_enable
Xhprof Funkcje
PHP Manual

xhprof_disable

(PECL xhprof >= 0.9.0)

xhprof_disable — Stops 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 Funkcje
xhprof_enable
Xhprof Funkcje


Start xhprof profiler

xhprof_disable
xhprof_sample_disable
Xhprof Funkcje
PHP Manual

xhprof_enable

(PECL xhprof >= 0.9.0)

xhprof_enable — Start 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_disable() - Stops xhprof profiler
  • xhprof_sample_enable() - Description
  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • getrusage() - Gets the current resource usages
xhprof_disable
xhprof_sample_disable
Xhprof Funkcje


Stops xhprof sample profiler

xhprof_enable
xhprof_sample_enable
Xhprof Funkcje
PHP Manual

xhprof_sample_disable

(PECL xhprof >= 0.9.0)

xhprof_sample_disable — Stops 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_enable
xhprof_sample_enable
Xhprof Funkcje


Description

xhprof_sample_disable
Przetwarzanie formatów audio
Xhprof Funkcje
PHP Manual

xhprof_sample_enable

(PECL xhprof >= 0.9.0)

xhprof_sample_enable — Description

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

  • xhprof_sample_disable() - Stops xhprof sample profiler
  • xhprof_enable() - Start xhprof profiler
  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • getrusage() - Gets the current resource usages
xhprof_sample_disable
Przetwarzanie formatów audio
Xhprof Funkcje


Przetwarzanie formatów audio

  • ID3 — Tagi ID3
    • Wstęp
    • Instalacja/Konfiguracja
    • Predefined Constants
    • Funkcje ID3
  • KTaglib
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • KTaglib_MPEG_File — The KTaglib_MPEG_File class
    • KTaglib_MPEG_AudioProperties — The KTaglib_MPEG_AudioProperties class
    • KTaglib_Tag — The KTaglib_Tag class
    • KTaglib_ID3v2_Tag — The KTaglib_ID3v2_Tag class
    • KTaglib_ID3v2_Frame — The KTaglib_ID3v2_Frame class
    • KTaglib_ID3v2_AttachedPictureFrame — The KTaglib_ID3v2_AttachedPictureFrame class
  • oggvorbis — OGG/Vorbis
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Context options
    • Przykłady
  • OpenAL — OpenAL Audio Bindings
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • OpenAL Funkcje
xhprof_sample_enable
ID3
Opis funkcji


Tagi ID3

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Predefined Constants
  • Funkcje ID3
    • id3_get_frame_long_name — Get the long name of an ID3v2 frame
    • id3_get_frame_short_name — Get the short name of an ID3v2 frame
    • id3_get_genre_id — Get the id for a genre
    • id3_get_genre_list — Get all possible genre values
    • id3_get_genre_name — Get the name for a genre id
    • id3_get_tag — Get all information stored in an ID3 tag
    • id3_get_version — Get version of an ID3 tag
    • id3_remove_tag — Remove an existing ID3 tag
    • id3_set_tag — Update information stored in an ID3 tag
Przetwarzanie formatów audio
Wstęp
Przetwarzanie formatów audio


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

ID3
Instalacja/Konfiguracja
ID3


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
ID3


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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
Predefined Constants
Instalacja/Konfiguracja


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.

Typy zasobów
Funkcje ID3
ID3


Funkcje ID3

Spis treści

  • id3_get_frame_long_name — Get the long name of an ID3v2 frame
  • id3_get_frame_short_name — Get the short name of an ID3v2 frame
  • id3_get_genre_id — Get the id for a genre
  • id3_get_genre_list — Get all possible genre values
  • id3_get_genre_name — Get the name for a genre id
  • id3_get_tag — Get all information stored in an ID3 tag
  • id3_get_version — Get version of an ID3 tag
  • id3_remove_tag — Remove an existing ID3 tag
  • id3_set_tag — Update information stored in an ID3 tag
Predefined Constants
id3_get_frame_long_name
ID3


Get the long name of an ID3v2 frame

Funkcje ID3
id3_get_frame_short_name
Funkcje ID3
PHP Manual

id3_get_frame_long_name

(PECL id3 >= 0.2)

id3_get_frame_long_name — Get 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() - Get the short name of an ID3v2 frame

Funkcje ID3
id3_get_frame_short_name
Funkcje ID3


Get the short name of an ID3v2 frame

id3_get_frame_long_name
id3_get_genre_id
Funkcje ID3
PHP Manual

id3_get_frame_short_name

(PECL id3 >= 0.2)

id3_get_frame_short_name — Get 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_frame_long_name() - Get the long name of an ID3v2 frame

id3_get_frame_long_name
id3_get_genre_id
Funkcje ID3


Get the id for a genre

id3_get_frame_short_name
id3_get_genre_list
Funkcje ID3
PHP Manual

id3_get_genre_id

(PECL id3 >= 0.1)

id3_get_genre_id — Get 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_name() - Get the name for a genre id
  • id3_get_genre_list() - Get all possible genre values

id3_get_frame_short_name
id3_get_genre_list
Funkcje ID3


Get all possible genre values

id3_get_genre_id
id3_get_genre_name
Funkcje ID3
PHP Manual

id3_get_genre_list

(PECL id3 >= 0.1)

id3_get_genre_list — Get 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() - Get the name for a genre id
  • id3_get_genre_id() - Get the id for a genre

id3_get_genre_id
id3_get_genre_name
Funkcje ID3


Get the name for a genre id

id3_get_genre_list
id3_get_tag
Funkcje ID3
PHP Manual

id3_get_genre_name

(PECL id3 >= 0.1)

id3_get_genre_name — Get 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_genre_list() - Get all possible genre values
  • id3_get_genre_id() - Get the id for a genre

id3_get_genre_list
id3_get_tag
Funkcje ID3


Get all information stored in an ID3 tag

id3_get_genre_name
id3_get_version
Funkcje ID3
PHP Manual

id3_get_tag

(PECL id3 >= 0.1)

id3_get_tag — Get 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_set_tag() - Update information stored in an ID3 tag
  • id3_remove_tag() - Remove an existing ID3 tag
  • id3_get_version() - Get version of an ID3 tag

id3_get_genre_name
id3_get_version
Funkcje ID3


Get version of an ID3 tag

id3_get_tag
id3_remove_tag
Funkcje ID3
PHP Manual

id3_get_version

(PECL id3 >= 0.1)

id3_get_version — Get 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_set_tag() - Update information stored in an ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_remove_tag() - Remove an existing ID3 tag

id3_get_tag
id3_remove_tag
Funkcje ID3


Remove an existing ID3 tag

id3_get_version
id3_set_tag
Funkcje ID3
PHP Manual

id3_remove_tag

(PECL id3 >= 0.1)

id3_remove_tag — Remove 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() - Update information stored in an ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_get_version() - Get version of an ID3 tag

id3_get_version
id3_set_tag
Funkcje ID3


Update information stored in an ID3 tag

id3_remove_tag
KTaglib
Funkcje ID3
PHP Manual

id3_set_tag

(PECL id3 >= 0.1)

id3_set_tag — Update 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", $data, ID3_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ż:

  • id3_remove_tag() - Remove an existing ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_get_version() - Get version of an ID3 tag

id3_remove_tag
KTaglib
Funkcje ID3


KTaglib

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
  • Stałe predefiniowane
  • KTaglib_MPEG_File — The KTaglib_MPEG_File class
    • KTaglib_MPEG_File::__construct — Opens a new file
    • KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
    • KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
    • KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object
  • KTaglib_MPEG_AudioProperties — The KTaglib_MPEG_AudioProperties class
    • KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
    • KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
    • KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
    • KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file
  • KTaglib_Tag — The KTaglib_Tag class
    • KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag
    • KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
    • KTaglib_Tag::getComment — Returns the comment from a ID3 tag
    • KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
    • KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
    • KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
    • KTaglib_Tag::getYear — Returns the year from a ID3 tag
    • KTaglib_Tag::isEmpty — Returns true if the tag is empty
  • KTaglib_ID3v2_Tag — The KTaglib_ID3v2_Tag class
    • KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
    • KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag
  • KTaglib_ID3v2_Frame — The KTaglib_ID3v2_Frame class
    • KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
    • KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame
  • KTaglib_ID3v2_AttachedPictureFrame — The KTaglib_ID3v2_AttachedPictureFrame class
    • KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
    • KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
    • KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
    • KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
    • KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image
id3_set_tag
Wstęp
Przetwarzanie formatów audio


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.

KTaglib
Instalacja/Konfiguracja
KTaglib


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
Wstęp
Wymagania
KTaglib


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/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/

Wymagania
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane z PHP, lub załadowane dynamicznie przy starcie.

KTaglib uses class constants. Most of the constants are mappings to the according Taglib enums and constants.

KTaglib_MPEG_Header::Version1 (integer)
ID3 version is 1.0
KTaglib_MPEG_Header::Version2 (integer)
ID3 version is 2.0
KTaglib_MPEG_Header::Version2_5 (integer)
ID3 version is 2.5
KTaglib_ID3v2_AttachedPictureFrame::Other (integer)
Picture type Other
KTaglib_ID3v2_AttachedPictureFrame::FileIcon (integer)
Picture type FileIcon
KTaglib_ID3v2_AttachedPictureFrame::OtherFileIcon (integer)
Picture type OtherFileIcon
KTaglib_ID3v2_AttachedPictureFrame::FrontCover (integer)
Picture type FrontCover
KTaglib_ID3v2_AttachedPictureFrame::BackCover (integer)
Picture type BackCover
KTaglib_ID3v2_AttachedPictureFrame::LeafletPage (integer)
Picture type LeafletPage
KTaglib_ID3v2_AttachedPictureFrame::Media (integer)
Picture type Media
KTaglib_ID3v2_AttachedPictureFrame::LeadArtist (integer)
Picture type LeadArtist
KTaglib_ID3v2_AttachedPictureFrame::Artist (integer)
Picture type Artist
KTaglib_ID3v2_AttachedPictureFrame::Conductor (integer)
Picture type Condutor
KTaglib_ID3v2_AttachedPictureFrame::Band (integer)
Picture type Band
KTaglib_ID3v2_AttachedPictureFrame::Composer (integer)
Picture type Composer
KTaglib_ID3v2_AttachedPictureFrame::Lyricist (integer)
Picture type Lyricist
KTaglib_ID3v2_AttachedPictureFrame::RecordingLocation (integer)
Picture type RecordingLocation
KTaglib_ID3v2_AttachedPictureFrame::DuringRecording (integer)
Picture type DuringRecording
KTaglib_ID3v2_AttachedPictureFrame::DuringPerformance (integer)
Picture type DuringPerformance
KTaglib_ID3v2_AttachedPictureFrame::MovieScreenCapture (integer)
Picture type MovieScreenCapture
KTaglib_ID3v2_AttachedPictureFrame::ColouredFish (integer)
Picture type ColouredFish
KTaglib_ID3v2_AttachedPictureFrame::Illustration (integer)
Picture type Illustration
KTaglib_ID3v2_AttachedPictureFrame::BandLogo (integer)
Picture type BandLogo
Instalacja
KTaglib_MPEG_File
KTaglib


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 ] )
}

Spis treści

  • KTaglib_MPEG_File::__construct — Opens a new file
  • KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
  • KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
  • KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object
Stałe predefiniowane
KTaglib_MPEG_File::__construct
KTaglib


Opens a new file

KTaglib_MPEG_File
KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File
PHP Manual

KTaglib_MPEG_File::__construct

(0.0.1)

KTaglib_MPEG_File::__construct — Opens 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
KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File


Returns an object that provides access to the audio properties

KTaglib_MPEG_File::__construct
KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_File
PHP Manual

KTaglib_MPEG_File::getAudioProperties

(0.0.1)

KTaglib_MPEG_File::getAudioProperties — Returns 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::__construct
KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_File


Returns an object representing an ID3v1 tag

KTaglib_MPEG_File::getAudioProperties
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_File
PHP Manual

KTaglib_MPEG_File::getID3v1Tag

(0.0.1)

KTaglib_MPEG_File::getID3v1Tag — Returns 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::getAudioProperties
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_File


Returns a ID3v2 object

KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_AudioProperties
KTaglib_MPEG_File
PHP Manual

KTaglib_MPEG_File::getID3v2Tag

(0.0.1)

KTaglib_MPEG_File::getID3v2Tag — Returns 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

KTaglib_MPEG_File::getID3v1Tag
KTaglib_MPEG_AudioProperties
KTaglib_MPEG_File


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.

Class synopsis

KTaglib_MPEG_AudioProperties {
/* Metody */
public int KTaglib_MPEG_AudioProperties::getBitrate ( void )
public int KTaglib_MPEG_AudioProperties::getChannels ( void )
public int KTaglib_MPEG_AudioProperties::getLayer ( void )
public int KTaglib_MPEG_AudioProperties::getLength ( void )
public int KTaglib_MPEG_AudioProperties::getSampleBitrate ( void )
public int KTaglib_MPEG_AudioProperties::getVersion ( void )
public bool KTaglib_MPEG_AudioProperties::isCopyrighted ( void )
public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )
public bool KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void )
}

Spis treści

  • KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
  • KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
  • KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
  • KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
  • KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
  • KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns the length of a MPEG file
KTaglib_MPEG_File::getID3v2Tag
KTaglib_MPEG_AudioProperties::getBitrate
KTaglib


Returns the bitrate of the MPEG file

KTaglib_MPEG_AudioProperties
KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getBitrate — Returns 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
KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties


Returns the amount of channels of a MPEG file

KTaglib_MPEG_AudioProperties::getBitrate
KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getChannels

(0.0.1)

KTaglib_MPEG_AudioProperties::getChannels — Returns 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::getBitrate
KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties


Returns the layer of a MPEG file

KTaglib_MPEG_AudioProperties::getChannels
KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getLayer

(0.0.1)

KTaglib_MPEG_AudioProperties::getLayer — Returns 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::getChannels
KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::getLayer
KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getLength

(0.0.1)

KTaglib_MPEG_AudioProperties::getLength — Returns 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::getLayer
KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties


Returns the sample bitrate of a MPEG file

KTaglib_MPEG_AudioProperties::getLength
KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getSampleBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns 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::getLength
KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties


Returns the version of a MPEG file

KTaglib_MPEG_AudioProperties::getSampleBitrate
KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::getVersion

(0.0.1)

KTaglib_MPEG_AudioProperties::getVersion — Returns 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::getSampleBitrate
KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::getVersion
KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isCopyrighted

(0.0.1)

KTaglib_MPEG_AudioProperties::isCopyrighted — Returns 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::getVersion
KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isOriginal

(0.0.1)

KTaglib_MPEG_AudioProperties::isOriginal — Returns the length of a MPEG file

Opis

public bool KTaglib_MPEG_AudioProperties::isOriginal ( void )

Returns true if the file is marked as the original file

Zwracane wartości

Returns true if the file is marked as the original file

KTaglib_MPEG_AudioProperties::isCopyrighted
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_MPEG_AudioProperties


Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_Tag
KTaglib_MPEG_AudioProperties
PHP Manual

KTaglib_MPEG_AudioProperties::isProtectionEnabled

(0.0.1)

KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns 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

KTaglib_MPEG_AudioProperties::isOriginal
KTaglib_Tag
KTaglib_MPEG_AudioProperties


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

Spis treści

  • KTaglib_Tag::getAlbum — Returns the title string from a ID3 tag
  • KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
  • KTaglib_Tag::getComment — Returns the comment from a ID3 tag
  • KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
  • KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
  • KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
  • KTaglib_Tag::getYear — Returns the year from a ID3 tag
  • KTaglib_Tag::isEmpty — Returns true if the tag is empty
KTaglib_MPEG_AudioProperties::isProtectionEnabled
KTaglib_Tag::getAlbum
KTaglib


Returns the title string from a ID3 tag

KTaglib_Tag
KTaglib_Tag::getArtist
KTaglib_Tag
PHP Manual

KTaglib_Tag::getAlbum

(0.0.1)

KTaglib_Tag::getAlbum — Returns 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
KTaglib_Tag::getArtist
KTaglib_Tag


Returns the artist string from a ID3 tag

KTaglib_Tag::getAlbum
KTaglib_Tag::getComment
KTaglib_Tag
PHP Manual

KTaglib_Tag::getArtist

(0.0.1)

KTaglib_Tag::getArtist — Returns 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::getAlbum
KTaglib_Tag::getComment
KTaglib_Tag


Returns the comment from a ID3 tag

KTaglib_Tag::getArtist
KTaglib_Tag::getGenre
KTaglib_Tag
PHP Manual

KTaglib_Tag::getComment

(0.0.1)

KTaglib_Tag::getComment — Returns 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::getArtist
KTaglib_Tag::getGenre
KTaglib_Tag


Returns the genre from a ID3 tag

KTaglib_Tag::getComment
KTaglib_Tag::getTitle
KTaglib_Tag
PHP Manual

KTaglib_Tag::getGenre

(0.0.1)

KTaglib_Tag::getGenre — Returns 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::getComment
KTaglib_Tag::getTitle
KTaglib_Tag


Returns the title string from a ID3 tag

KTaglib_Tag::getGenre
KTaglib_Tag::getTrack
KTaglib_Tag
PHP Manual

KTaglib_Tag::getTitle

(0.0.1)

KTaglib_Tag::getTitle — Returns 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::getGenre
KTaglib_Tag::getTrack
KTaglib_Tag


Returns the track number from a ID3 tag

KTaglib_Tag::getTitle
KTaglib_Tag::getYear
KTaglib_Tag
PHP Manual

KTaglib_Tag::getTrack

(0.0.1)

KTaglib_Tag::getTrack — Returns 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::getTitle
KTaglib_Tag::getYear
KTaglib_Tag


Returns the year from a ID3 tag

KTaglib_Tag::getTrack
KTaglib_Tag::isEmpty
KTaglib_Tag
PHP Manual

KTaglib_Tag::getYear

(0.0.1)

KTaglib_Tag::getYear — Returns 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::getTrack
KTaglib_Tag::isEmpty
KTaglib_Tag


Returns true if the tag is empty

KTaglib_Tag::getYear
KTaglib_ID3v2_Tag
KTaglib_Tag
PHP Manual

KTaglib_Tag::isEmpty

(0.0.1)

KTaglib_Tag::isEmpty — Returns 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.

KTaglib_Tag::getYear
KTaglib_ID3v2_Tag
KTaglib_Tag


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

Spis treści

  • KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
  • KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag
KTaglib_Tag::isEmpty
KTaglib_ID3v2_Tag::addFrame
KTaglib


Add a frame to the ID3v2 tag

KTaglib_ID3v2_Tag
KTaglib_ID3v2_Tag::getFrameList
KTaglib_ID3v2_Tag
PHP Manual

KTaglib_ID3v2_Tag::addFrame

(0.0.1)

KTaglib_ID3v2_Tag::addFrame — Add 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
KTaglib_ID3v2_Tag::getFrameList
KTaglib_ID3v2_Tag


Returns an array of ID3v2 frames, associated with the ID3v2 tag

KTaglib_ID3v2_Tag::addFrame
KTaglib_ID3v2_Frame
KTaglib_ID3v2_Tag
PHP Manual

KTaglib_ID3v2_Tag::getFrameList

(0.0.1)

KTaglib_ID3v2_Tag::getFrameList — Returns 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

KTaglib_ID3v2_Tag::addFrame
KTaglib_ID3v2_Frame
KTaglib_ID3v2_Tag


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

Spis treści

  • KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
  • KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame
KTaglib_ID3v2_Tag::getFrameList
KTaglib_ID3v2_Frame::getSize
KTaglib


Returns the size of the frame in bytes

KTaglib_ID3v2_Frame
KTaglib_ID3v2_Frame::__toString
KTaglib_ID3v2_Frame
PHP Manual

KTaglib_ID3v2_Frame::getSize

(0.0.1)

KTaglib_ID3v2_Frame::getSize — Returns 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
KTaglib_ID3v2_Frame::__toString
KTaglib_ID3v2_Frame


Returns a string representation of the frame

KTaglib_ID3v2_Frame::getSize
KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_Frame
PHP Manual

KTaglib_ID3v2_Frame::__toString

(0.0.1)

KTaglib_ID3v2_Frame::__toString — Returns 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.

KTaglib_ID3v2_Frame::getSize
KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_Frame


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

extends KTaglib_ID3v2_Frame {
/* 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 )
}

Spis treści

  • KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
  • KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
  • KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
  • KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
  • KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
  • KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
  • KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image
KTaglib_ID3v2_Frame::__toString
KTaglib_ID3v2_AttachedPictureFrame::getDescription
KTaglib


Returns a description for the picture in a picture frame

KTaglib_ID3v2_AttachedPictureFrame
KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::getDescription

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns 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
KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame


Returns the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::getDescription
KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::getMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns 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::getDescription
KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame


Returns the type of the image

KTaglib_ID3v2_AttachedPictureFrame::getMimeType
KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::getType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getType — Returns 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::getMimeType
KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame


Saves the picture to a file

KTaglib_ID3v2_AttachedPictureFrame::getType
KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::savePicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves 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::getType
KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame


Set's the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::savePicture
KTaglib_ID3v2_AttachedPictureFrame::setPicture
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::setMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set'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::savePicture
KTaglib_ID3v2_AttachedPictureFrame::setPicture
KTaglib_ID3v2_AttachedPictureFrame


Sets the frame picture to the given image

KTaglib_ID3v2_AttachedPictureFrame::setMimeType
KTaglib_ID3v2_AttachedPictureFrame::setType
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::setPicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets 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::setMimeType
KTaglib_ID3v2_AttachedPictureFrame::setType
KTaglib_ID3v2_AttachedPictureFrame


Set the type of the image

KTaglib_ID3v2_AttachedPictureFrame::setPicture
oggvorbis
KTaglib_ID3v2_AttachedPictureFrame
PHP Manual

KTaglib_ID3v2_AttachedPictureFrame::setType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setType — Set 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.

KTaglib_ID3v2_AttachedPictureFrame::setPicture
oggvorbis
KTaglib_ID3v2_AttachedPictureFrame


OGG/Vorbis

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Context options
  • Przykłady
    • Examples on using the ogg:// wrapper.
KTaglib_ID3v2_AttachedPictureFrame::setType
Wstęp
Przetwarzanie formatów audio


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.

oggvorbis
Instalacja/Konfiguracja
oggvorbis


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
oggvorbis


Wymagania

This extension requires PHP >= 4.3.0, » libogg >= 1.0, and » libvorbis >= 1.0.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.
Typy zasobów
Context options
oggvorbis


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')
Stałe predefiniowane
Przykłady
oggvorbis


Przykłady

Spis treści

  • Examples on using the ogg:// wrapper.
Context options
Examples on using the ogg:// wrapper.
oggvorbis


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($fp, 8192)) {
  /* Do something with the PCM audio we're extracting from the OGG.
     Copying to /dev/dsp is a good target on linux systems,
     just remember to setup the device for your sampling mode first. */
}

fclose($fp);

?>

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

Przykłady
OpenAL
Przykłady


OpenAL Audio Bindings

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • OpenAL Funkcje
    • openal_buffer_create — Generate OpenAL buffer
    • openal_buffer_data — Load a buffer with data
    • openal_buffer_destroy — Destroys an OpenAL buffer
    • openal_buffer_get — Retrieve an OpenAL buffer property
    • openal_buffer_loadwav — Load a .wav file into a buffer
    • openal_context_create — Create an audio processing context
    • openal_context_current — Make the specified context current
    • openal_context_destroy — Destroys a context
    • openal_context_process — Process the specified context
    • openal_context_suspend — Suspend the specified context
    • openal_device_close — Close an OpenAL device
    • openal_device_open — Initialize the OpenAL audio layer
    • openal_listener_get — Retrieve a listener property
    • openal_listener_set — Set a listener property
    • openal_source_create — Generate a source resource
    • openal_source_destroy — Destroy a source resource
    • openal_source_get — Retrieve an OpenAL source property
    • openal_source_pause — Pause the source
    • openal_source_play — Start playing the source
    • openal_source_rewind — Rewind the source
    • openal_source_set — Set source property
    • openal_source_stop — Stop playing the source
    • openal_stream — Begin streaming on a source
Examples on using the ogg:// wrapper.
Wstęp
Przetwarzanie formatów audio


Wstęp

Platform independent audio bindings. Requires the » OpenAL library.

OpenAL
Instalacja/Konfiguracja
OpenAL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
OpenAL


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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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
Typy zasobów
OpenAL Funkcje
OpenAL


OpenAL Funkcje

Spis treści

  • openal_buffer_create — Generate OpenAL buffer
  • openal_buffer_data — Load a buffer with data
  • openal_buffer_destroy — Destroys an OpenAL buffer
  • openal_buffer_get — Retrieve an OpenAL buffer property
  • openal_buffer_loadwav — Load a .wav file into a buffer
  • openal_context_create — Create an audio processing context
  • openal_context_current — Make the specified context current
  • openal_context_destroy — Destroys a context
  • openal_context_process — Process the specified context
  • openal_context_suspend — Suspend the specified context
  • openal_device_close — Close an OpenAL device
  • openal_device_open — Initialize the OpenAL audio layer
  • openal_listener_get — Retrieve a listener property
  • openal_listener_set — Set a listener property
  • openal_source_create — Generate a source resource
  • openal_source_destroy — Destroy a source resource
  • openal_source_get — Retrieve an OpenAL source property
  • openal_source_pause — Pause the source
  • openal_source_play — Start playing the source
  • openal_source_rewind — Rewind the source
  • openal_source_set — Set source property
  • openal_source_stop — Stop playing the source
  • openal_stream — Begin streaming on a source
Stałe predefiniowane
openal_buffer_create
OpenAL


Generate OpenAL buffer

OpenAL Funkcje
openal_buffer_data
OpenAL Funkcje
PHP Manual

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_loadwav() - Load a .wav file into a buffer
  • openal_buffer_data() - Load a buffer with data

OpenAL Funkcje
openal_buffer_data
OpenAL Funkcje


Load a buffer with data

openal_buffer_create
openal_buffer_destroy
OpenAL Funkcje
PHP Manual

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_loadwav() - Load a .wav file into a buffer
  • openal_stream() - Begin streaming on a source

openal_buffer_create
openal_buffer_destroy
OpenAL Funkcje


Destroys an OpenAL buffer

openal_buffer_data
openal_buffer_get
OpenAL Funkcje
PHP Manual

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_create() - Generate OpenAL buffer

openal_buffer_data
openal_buffer_get
OpenAL Funkcje


Retrieve an OpenAL buffer property

openal_buffer_destroy
openal_buffer_loadwav
OpenAL Funkcje
PHP Manual

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_create() - Generate OpenAL buffer

openal_buffer_destroy
openal_buffer_loadwav
OpenAL Funkcje


Load a .wav file into a buffer

openal_buffer_get
openal_context_create
OpenAL Funkcje
PHP Manual

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_buffer_data() - Load a buffer with data
  • openal_stream() - Begin streaming on a source

openal_buffer_get
openal_context_create
OpenAL Funkcje


Create an audio processing context

openal_buffer_loadwav
openal_context_current
OpenAL Funkcje
PHP Manual

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_device_open() - Initialize the OpenAL audio layer
  • openal_context_destroy() - Destroys a context

openal_buffer_loadwav
openal_context_current
OpenAL Funkcje


Make the specified context current

openal_context_create
openal_context_destroy
OpenAL Funkcje
PHP Manual

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_create() - Create an audio processing context

openal_context_create
openal_context_destroy
OpenAL Funkcje


Destroys a context

openal_context_current
openal_context_process
OpenAL Funkcje
PHP Manual

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_create() - Create an audio processing context

openal_context_current
openal_context_process
OpenAL Funkcje


Process the specified context

openal_context_destroy
openal_context_suspend
OpenAL Funkcje
PHP Manual

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_create() - Create an audio processing context
  • openal_context_current() - Make the specified context current
  • openal_context_suspend() - Suspend the specified context

openal_context_destroy
openal_context_suspend
OpenAL Funkcje


Suspend the specified context

openal_context_process
openal_device_close
OpenAL Funkcje
PHP Manual

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_context_create() - Create an audio processing context
  • openal_context_current() - Make the specified context current
  • openal_context_process() - Process the specified context

openal_context_process
openal_device_close
OpenAL Funkcje


Close an OpenAL device

openal_context_suspend
openal_device_open
OpenAL Funkcje
PHP Manual

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() - Initialize the OpenAL audio layer

openal_context_suspend
openal_device_open
OpenAL Funkcje


Initialize the OpenAL audio layer

openal_device_close
openal_listener_get
OpenAL Funkcje
PHP Manual

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_device_close() - Close an OpenAL device
  • openal_context_create() - Create an audio processing context

openal_device_close
openal_listener_get
OpenAL Funkcje


Retrieve a listener property

openal_device_open
openal_listener_set
OpenAL Funkcje
PHP Manual

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() - Set a listener property

openal_device_open
openal_listener_set
OpenAL Funkcje


Set a listener property

openal_listener_get
openal_source_create
OpenAL Funkcje
PHP Manual

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_listener_get() - Retrieve a listener property

openal_listener_get
openal_source_create
OpenAL Funkcje


Generate a source resource

openal_listener_set
openal_source_destroy
OpenAL Funkcje
PHP Manual

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_set() - Set source property
  • openal_source_play() - Start playing the source
  • openal_source_destroy() - Destroy a source resource

openal_listener_set
openal_source_destroy
OpenAL Funkcje


Destroy a source resource

openal_source_create
openal_source_get
OpenAL Funkcje
PHP Manual

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_create() - Generate a source resource

openal_source_create
openal_source_get
OpenAL Funkcje


Retrieve an OpenAL source property

openal_source_destroy
openal_source_pause
OpenAL Funkcje
PHP Manual

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_create() - Generate a source resource
  • openal_source_set() - Set source property
  • openal_source_play() - Start playing the source

openal_source_destroy
openal_source_pause
OpenAL Funkcje


Pause the source

openal_source_get
openal_source_play
OpenAL Funkcje
PHP Manual

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_stop() - Stop playing the source
  • openal_source_play() - Start playing the source
  • openal_source_rewind() - Rewind the source

openal_source_get
openal_source_play
OpenAL Funkcje


Start playing the source

openal_source_pause
openal_source_rewind
OpenAL Funkcje
PHP Manual

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_stop() - Stop playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

openal_source_pause
openal_source_rewind
OpenAL Funkcje


Rewind the source

openal_source_play
openal_source_set
OpenAL Funkcje
PHP Manual

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_stop() - Stop playing the source
  • openal_source_pause() - Pause the source
  • openal_source_play() - Start playing the source

openal_source_play
openal_source_set
OpenAL Funkcje


Set source property

openal_source_rewind
openal_source_stop
OpenAL Funkcje
PHP Manual

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_create() - Generate a source resource
  • openal_source_get() - Retrieve an OpenAL source property
  • openal_source_play() - Start playing the source

openal_source_rewind
openal_source_stop
OpenAL Funkcje


Stop playing the source

openal_source_set
openal_stream
OpenAL Funkcje
PHP Manual

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_source_play() - Start playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

openal_source_set
openal_stream
OpenAL Funkcje


Begin streaming on a source

openal_source_stop
Serwisy uwierzytelnienia
OpenAL Funkcje
PHP Manual

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

  • openal_source_create() - Generate a source resource
  • fwrite() - Zapis pliku binarnie bezpieczny

openal_source_stop
Serwisy uwierzytelnienia
OpenAL Funkcje


Serwisy uwierzytelnienia

  • KADM5 — Kerberos V
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • KADM5 Funkcje
  • Radius
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Radius Funkcje
openal_stream
KADM5
Opis funkcji


Kerberos V

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
    • Constants for Attribute Flags
    • Constants for Options
  • Przykłady
    • Basic usage
  • KADM5 Funkcje
    • kadm5_chpass_principal — Changes the principal's password
    • kadm5_create_principal — Creates a kerberos principal with the given parameters
    • kadm5_delete_principal — Deletes a kerberos principal
    • kadm5_destroy — Closes the connection to the admin server and releases all related resources
    • kadm5_flush — Flush all changes to the Kerberos database
    • kadm5_get_policies — Gets all policies from the Kerberos database
    • kadm5_get_principal — Gets the principal's entries from the Kerberos database
    • kadm5_get_principals — Gets all principals from the Kerberos database
    • kadm5_init_with_password — Opens a connection to the KADM5 library
    • kadm5_modify_principal — Modifies a kerberos principal with the given parameters
Serwisy uwierzytelnienia
Wstęp
Serwisy uwierzytelnienia


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.

KADM5
Instalacja/Konfiguracja
KADM5


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
KADM5


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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines a KADM5 handle returned by kadm5_init_with_password().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

Spis treści

  • Constants for Attribute Flags
  • Constants for Options

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.

Typy zasobów
Constants for Attribute Flags
KADM5


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

Stałe predefiniowane
Constants for Options
Stałe predefiniowane


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.

Constants for Attribute Flags
Przykłady
Stałe predefiniowane


Przykłady

Spis treści

  • Basic usage
Constants for Options
Basic usage
KADM5


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

Przykłady
KADM5 Funkcje
Przykłady


KADM5 Funkcje

Spis treści

  • kadm5_chpass_principal — Changes the principal's password
  • kadm5_create_principal — Creates a kerberos principal with the given parameters
  • kadm5_delete_principal — Deletes a kerberos principal
  • kadm5_destroy — Closes the connection to the admin server and releases all related resources
  • kadm5_flush — Flush all changes to the Kerberos database
  • kadm5_get_policies — Gets all policies from the Kerberos database
  • kadm5_get_principal — Gets the principal's entries from the Kerberos database
  • kadm5_get_principals — Gets all principals from the Kerberos database
  • kadm5_init_with_password — Opens a connection to the KADM5 library
  • kadm5_modify_principal — Modifies a kerberos principal with the given parameters
Basic usage
kadm5_chpass_principal
KADM5


Changes the principal's password

KADM5 Funkcje
kadm5_create_principal
KADM5 Funkcje
PHP Manual

kadm5_chpass_principal

(PECL kadm5 >= 0.2.3)

kadm5_chpass_principal — Changes 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 Funkcje
kadm5_create_principal
KADM5 Funkcje


Creates a kerberos principal with the given parameters

kadm5_chpass_principal
kadm5_delete_principal
KADM5 Funkcje
PHP Manual

kadm5_create_principal

(PECL kadm5 >= 0.2.3)

kadm5_create_principal — Creates 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_modify_principal() - Modifies a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal

kadm5_chpass_principal
kadm5_delete_principal
KADM5 Funkcje


Deletes a kerberos principal

kadm5_create_principal
kadm5_destroy
KADM5 Funkcje
PHP Manual

kadm5_delete_principal

(PECL kadm5 >= 0.2.3)

kadm5_delete_principal — Deletes 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_modify_principal() - Modifies a kerberos principal with the given parameters
  • kadm5_create_principal() - Creates a kerberos principal with the given parameters

kadm5_create_principal
kadm5_destroy
KADM5 Funkcje


Closes the connection to the admin server and releases all related resources

kadm5_delete_principal
kadm5_flush
KADM5 Funkcje
PHP Manual

kadm5_destroy

(PECL kadm5 >= 0.2.3)

kadm5_destroy — Closes 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_init_with_password() - Opens a connection to the KADM5 library

kadm5_delete_principal
kadm5_flush
KADM5 Funkcje


Flush all changes to the Kerberos database

kadm5_destroy
kadm5_get_policies
KADM5 Funkcje
PHP Manual

kadm5_flush

(PECL kadm5 >= 0.2.3)

kadm5_flush — Flush 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_destroy
kadm5_get_policies
KADM5 Funkcje


Gets all policies from the Kerberos database

kadm5_flush
kadm5_get_principal
KADM5 Funkcje
PHP Manual

kadm5_get_policies

(PECL kadm5 >= 0.2.3)

kadm5_get_policies — Gets 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_flush
kadm5_get_principal
KADM5 Funkcje


Gets the principal's entries from the Kerberos database

kadm5_get_policies
kadm5_get_principals
KADM5 Funkcje
PHP Manual

kadm5_get_principal

(PECL kadm5 >= 0.2.3)

kadm5_get_principal — Gets 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() - Gets all principals from the Kerberos database

kadm5_get_policies
kadm5_get_principals
KADM5 Funkcje


Gets all principals from the Kerberos database

kadm5_get_principal
kadm5_init_with_password
KADM5 Funkcje
PHP Manual

kadm5_get_principals

(PECL kadm5 >= 0.2.3)

kadm5_get_principals — Gets 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_get_principal() - Gets the principal's entries from the Kerberos database

kadm5_get_principal
kadm5_init_with_password
KADM5 Funkcje


Opens a connection to the KADM5 library

kadm5_get_principals
kadm5_modify_principal
KADM5 Funkcje
PHP Manual

kadm5_init_with_password

(PECL kadm5 >= 0.2.3)

kadm5_init_with_password — Opens 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_get_principals
kadm5_modify_principal
KADM5 Funkcje


Modifies a kerberos principal with the given parameters

kadm5_init_with_password
Radius
KADM5 Funkcje
PHP Manual

kadm5_modify_principal

(PECL kadm5 >= 0.2.3)

kadm5_modify_principal — Modifies 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ż:

  • kadm5_create_principal() - Creates a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal

kadm5_init_with_password
Radius
KADM5 Funkcje


Radius

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Radius Funkcje
    • radius_acct_open — Creates a Radius handle for accounting
    • radius_add_server — Adds a server
    • radius_auth_open — Creates a Radius handle for authentication
    • radius_close — Frees all ressources
    • radius_config — Causes the library to read the given configuration file
    • radius_create_request — Create accounting or authentication request
    • radius_cvt_addr — Converts raw data to IP-Address
    • radius_cvt_int — Converts raw data to integer
    • radius_cvt_string — Converts raw data to string
    • radius_demangle_mppe_key — Derives mppe-keys from mangled data
    • radius_demangle — Demangles data
    • radius_get_attr — Extracts an attribute
    • radius_get_vendor_attr — Extracts a vendor specific attribute
    • radius_put_addr — Attaches an IP-Address attribute
    • radius_put_attr — Attaches a binary attribute
    • radius_put_int — Attaches an integer attribute
    • radius_put_string — Attaches a string attribute
    • radius_put_vendor_addr — Attaches a vendor specific IP-Address attribute
    • radius_put_vendor_attr — Attaches a vendor specific binary attribute
    • radius_put_vendor_int — Attaches a vendor specific integer attribute
    • radius_put_vendor_string — Attaches a vendor specific string attribute
    • radius_request_authenticator — Returns the request authenticator
    • radius_send_request — Sends the request and waites for a reply
    • radius_server_secret — Returns the shared secret
    • radius_strerror — Returns an error message
kadm5_modify_principal
Wstęp
Serwisy uwierzytelnienia


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.

Radius
Instalacja/Konfiguracja
Radius


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Radius


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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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
RADIUS_FRAMED_APPLETALK_LINK (int)
Framed Appletalk Link
RADIUS_FRAMED_APPLETALK_NETWORK (int)
Framed Appletalk Network
RADIUS_FRAMED_APPLETALK_ZONE (int)
Framed Appletalk Zone
RADIUS_CHAP_CHALLENGE (string)
Challenge
RADIUS_NAS_PORT_TYPE (int)

NAS port type, one of:

  • RADIUS_ASYNC
  • RADIUS_SYNC
  • RADIUS_ISDN_SYNC
  • RADIUS_ISDN_ASYNC_V120
  • RADIUS_ISDN_ASYNC_V110
  • RADIUS_VIRTUAL
  • RADIUS_PIAFS
  • RADIUS_HDLC_CLEAR_CHANNEL
  • RADIUS_X_25
  • RADIUS_X_75
  • RADIUS_G_3_FAX
  • RADIUS_SDSL
  • RADIUS_ADSL_CAP
  • RADIUS_ADSL_DMT
  • RADIUS_IDSL
  • RADIUS_ETHERNET
  • RADIUS_XDSL
  • RADIUS_CABLE
  • RADIUS_WIRELESS_OTHER
  • RADIUS_WIRELESS_IEEE_802_11

RADIUS_PORT_LIMIT (int)
Port Limit
RADIUS_LOGIN_LAT_PORT (int)
Login LAT Port
RADIUS_CONNECT_INFO (string)
Connect info
RADIUS_ACCT_STATUS_TYPE (int)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (int)
Accounting delay time
RADIUS_ACCT_INPUT_OCTETS (int)
Accounting input bytes
RADIUS_ACCT_OUTPUT_OCTETS (int)
Accounting output bytes
RADIUS_ACCT_SESSION_ID (int)
Accounting session ID
RADIUS_ACCT_AUTHENTIC (int)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (int)
Accounting session time
RADIUS_ACCT_INPUT_PACKETS (int)
Accounting input packets
RADIUS_ACCT_OUTPUT_PACKETS (int)
Accounting output packets
RADIUS_ACCT_TERMINATE_CAUSE (int)

Accounting terminate cause, one of:

  • RADIUS_TERM_USER_REQUEST
  • RADIUS_TERM_LOST_CARRIER
  • RADIUS_TERM_LOST_SERVICE
  • RADIUS_TERM_IDLE_TIMEOUT
  • RADIUS_TERM_SESSION_TIMEOUT
  • RADIUS_TERM_ADMIN_RESET
  • RADIUS_TERM_ADMIN_REBOOT
  • RADIUS_TERM_PORT_ERROR
  • RADIUS_TERM_NAS_ERROR
  • RADIUS_TERM_NAS_REQUEST
  • RADIUS_TERM_NAS_REBOOT
  • RADIUS_TERM_PORT_UNNEEDED
  • RADIUS_TERM_PORT_PREEMPTED
  • RADIUS_TERM_PORT_SUSPENDED
  • RADIUS_TERM_SERVICE_UNAVAILABLE
  • RADIUS_TERM_CALLBACK
  • RADIUS_TERM_USER_ERROR
  • RADIUS_TERM_HOST_REQUEST

RADIUS_ACCT_MULTI_SESSION_ID (string)
Accounting multi session ID
RADIUS_ACCT_LINK_COUNT (int)
Accounting link count
RADIUS_VENDOR_MICROSOFT (int)

Microsoft specific vendor attributes (» RFC 2548), one of:

  • RADIUS_MICROSOFT_MS_CHAP_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP_ERROR
  • RADIUS_MICROSOFT_MS_CHAP_PW_1
  • RADIUS_MICROSOFT_MS_CHAP_PW_2
  • RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
  • RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
  • RADIUS_MICROSOFT_MS_RAS_VENDOR
  • RADIUS_MICROSOFT_MS_CHAP_DOMAIN
  • RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
  • RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
  • RADIUS_MICROSOFT_MS_BAP_USAGE
  • RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
  • RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
  • RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
  • RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
  • RADIUS_MICROSOFT_MS_RAS_VERSION
  • RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
  • RADIUS_MICROSOFT_MS_FILTER
  • RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
  • RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
  • RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
  • RADIUS_MICROSOFT_MS_CHAP2_PW
  • RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_ARAP_CHALLENGE

Typy zasobów
Przykłady
Radius


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.

Stałe predefiniowane
Radius Funkcje
Radius


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.

Spis treści

  • radius_acct_open — Creates a Radius handle for accounting
  • radius_add_server — Adds a server
  • radius_auth_open — Creates a Radius handle for authentication
  • radius_close — Frees all ressources
  • radius_config — Causes the library to read the given configuration file
  • radius_create_request — Create accounting or authentication request
  • radius_cvt_addr — Converts raw data to IP-Address
  • radius_cvt_int — Converts raw data to integer
  • radius_cvt_string — Converts raw data to string
  • radius_demangle_mppe_key — Derives mppe-keys from mangled data
  • radius_demangle — Demangles data
  • radius_get_attr — Extracts an attribute
  • radius_get_vendor_attr — Extracts a vendor specific attribute
  • radius_put_addr — Attaches an IP-Address attribute
  • radius_put_attr — Attaches a binary attribute
  • radius_put_int — Attaches an integer attribute
  • radius_put_string — Attaches a string attribute
  • radius_put_vendor_addr — Attaches a vendor specific IP-Address attribute
  • radius_put_vendor_attr — Attaches a vendor specific binary attribute
  • radius_put_vendor_int — Attaches a vendor specific integer attribute
  • radius_put_vendor_string — Attaches a vendor specific string attribute
  • radius_request_authenticator — Returns the request authenticator
  • radius_send_request — Sends the request and waites for a reply
  • radius_server_secret — Returns the shared secret
  • radius_strerror — Returns an error message
Przykłady
radius_acct_open
Radius


Creates a Radius handle for accounting

Radius Funkcje
radius_add_server
Radius Funkcje
PHP Manual

radius_acct_open

(PECL radius >= 1.1.0)

radius_acct_open — Creates 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 Funkcje
radius_add_server
Radius Funkcje


Adds a server

radius_acct_open
radius_auth_open
Radius Funkcje
PHP Manual

radius_add_server

(PECL radius >= 1.1.0)

radius_add_server — Adds 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', 3, 3)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br>";
    exit;
}
?>

Zobacz też:

  • radius_config() - Causes the library to read the given configuration file

radius_acct_open
radius_auth_open
Radius Funkcje


Creates a Radius handle for authentication

radius_add_server
radius_close
Radius Funkcje
PHP Manual

radius_auth_open

(PECL radius >= 1.1.0)

radius_auth_open — Creates 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_add_server
radius_close
Radius Funkcje


Frees all ressources

radius_auth_open
radius_config
Radius Funkcje
PHP Manual

radius_close

(PECL radius >= 1.1.0)

radius_close — Frees 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_auth_open
radius_config
Radius Funkcje


Causes the library to read the given configuration file

radius_close
radius_create_request
Radius Funkcje
PHP Manual

radius_config

(PECL radius >= 1.1.0)

radius_config — Causes 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_add_server() - Adds a server

radius_close
radius_create_request
Radius Funkcje


Create accounting or authentication request

radius_config
radius_cvt_addr
Radius Funkcje
PHP Manual

radius_create_request

(PECL radius >= 1.1.0)

radius_create_request — Create 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($res, RADIUS_ACCESS_REQUEST)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

Zobacz też:

  • radius_send_request() - Sends the request and waites for a reply

radius_config
radius_cvt_addr
Radius Funkcje


Converts raw data to IP-Address

radius_create_request
radius_cvt_int
Radius Funkcje
PHP Manual

radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addr — Converts 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() - Converts raw data to integer
  • radius_cvt_string() - Converts raw data to string

radius_create_request
radius_cvt_int
Radius Funkcje


Converts raw data to integer

radius_cvt_addr
radius_cvt_string
Radius Funkcje
PHP Manual

radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_int — Converts 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_addr() - Converts raw data to IP-Address
  • radius_cvt_string() - Converts raw data to string

radius_cvt_addr
radius_cvt_string
Radius Funkcje


Converts raw data to string

radius_cvt_int
radius_demangle_mppe_key
Radius Funkcje
PHP Manual

radius_cvt_string

(PECL radius >= 1.1.0)

radius_cvt_string — Converts 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_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_int() - Converts raw data to integer

radius_cvt_int
radius_demangle_mppe_key
Radius Funkcje


Derives mppe-keys from mangled data

radius_cvt_string
radius_demangle
Radius Funkcje
PHP Manual

radius_demangle_mppe_key

(PECL radius >= 1.2.0)

radius_demangle_mppe_key — Derives 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_cvt_string
radius_demangle
Radius Funkcje


Demangles data

radius_demangle_mppe_key
radius_get_attr
Radius Funkcje
PHP Manual

radius_demangle

(PECL radius >= 1.2.0)

radius_demangle — Demangles 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_demangle_mppe_key
radius_get_attr
Radius Funkcje


Extracts an attribute

radius_demangle
radius_get_vendor_attr
Radius Funkcje
PHP Manual

radius_get_attr

(PECL radius >= 1.1.0)

radius_get_attr — Extracts 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", $attr, strlen($data), bin2hex($data));
}
?>

Zobacz też:

  • radius_put_attr() - Attaches a binary attribute
  • radius_get_vendor_attr() - Extracts a vendor specific attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute
  • radius_send_request() - Sends the request and waites for a reply

radius_demangle
radius_get_vendor_attr
Radius Funkcje


Extracts a vendor specific attribute

radius_get_attr
radius_put_addr
Radius Funkcje
PHP Manual

radius_get_vendor_attr

(PECL radius >= 1.1.0)

radius_get_vendor_attr — Extracts 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", $attr, strlen($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", $attrv, strlen($datav), bin2hex($datav));
        }

    }
}
?>

Zobacz też:

  • radius_get_attr() - Extracts an attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

radius_get_attr
radius_put_addr
Radius Funkcje


Attaches an IP-Address attribute

radius_get_vendor_attr
radius_put_attr
Radius Funkcje
PHP Manual

radius_put_addr

(PECL radius >= 1.1.0)

radius_put_addr — Attaches 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_get_vendor_attr
radius_put_attr
Radius Funkcje


Attaches a binary attribute

radius_put_addr
radius_put_int
Radius Funkcje
PHP Manual

radius_put_attr

(PECL radius >= 1.1.0)

radius_put_attr — Attaches 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*',1 , 'sepp' . $chall));
$pass = pack('CH*', 1, $chapval);
if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

Zobacz też:

  • radius_get_attr() - Extracts an attribute
  • radius_get_vendor_attr() - Extracts a vendor specific attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

radius_put_addr
radius_put_int
Radius Funkcje


Attaches an integer attribute

radius_put_attr
radius_put_string
Radius Funkcje
PHP Manual

radius_put_int

(PECL radius >= 1.1.0)

radius_put_int — Attaches 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($res, RAD_FRAMED_PROTOCOL, RAD_PPP)) {
   echo 'RadiusError:' . radius_strerror($res). "\n<br />";
   exit;
}
?>

Zobacz też:

  • radius_put_string() - Attaches a string attribute
  • radius_put_vendor_int() - Attaches a vendor specific integer attribute
  • radius_put_vendor_string() - Attaches a vendor specific string attribute

radius_put_attr
radius_put_string
Radius Funkcje


Attaches a string attribute

radius_put_int
radius_put_vendor_addr
Radius Funkcje
PHP Manual

radius_put_string

(PECL radius >= 1.1.0)

radius_put_string — Attaches 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($res, RADIUS_USER_NAME, 'billy')) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

Zobacz też:

  • radius_put_int() - Attaches an integer attribute
  • radius_put_vendor_int() - Attaches a vendor specific integer attribute
  • radius_put_vendor_string() - Attaches a vendor specific string attribute

radius_put_int
radius_put_vendor_addr
Radius Funkcje


Attaches a vendor specific IP-Address attribute

radius_put_string
radius_put_vendor_attr
Radius Funkcje
PHP Manual

radius_put_vendor_addr

(PECL radius >= 1.1.0)

radius_put_vendor_addr — Attaches 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_string
radius_put_vendor_attr
Radius Funkcje


Attaches a vendor specific binary attribute

radius_put_vendor_addr
radius_put_vendor_int
Radius Funkcje
PHP Manual

radius_put_vendor_attr

(PECL radius >= 1.1.0)

radius_put_vendor_attr — Attaches 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($res, RADIUS_VENDOR_MICROSOFT, RAD_MICROSOFT_MS_CHAP_CHALLENGE, $challenge)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

Zobacz też:

  • radius_get_vendor_attr() - Extracts a vendor specific attribute

radius_put_vendor_addr
radius_put_vendor_int
Radius Funkcje


Attaches a vendor specific integer attribute

radius_put_vendor_attr
radius_put_vendor_string
Radius Funkcje
PHP Manual

radius_put_vendor_int

(PECL radius >= 1.1.0)

radius_put_vendor_int — Attaches 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() - Attaches a vendor specific string attribute

radius_put_vendor_attr
radius_put_vendor_string
Radius Funkcje


Attaches a vendor specific string attribute

radius_put_vendor_int
radius_request_authenticator
Radius Funkcje
PHP Manual

radius_put_vendor_string

(PECL radius >= 1.1.0)

radius_put_vendor_string — Attaches 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_put_vendor_int() - Attaches a vendor specific integer attribute

radius_put_vendor_int
radius_request_authenticator
Radius Funkcje


Returns the request authenticator

radius_put_vendor_string
radius_send_request
Radius Funkcje
PHP Manual

radius_request_authenticator

(PECL radius >= 1.1.0)

radius_request_authenticator — Returns 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_demangle() - Demangles data

radius_put_vendor_string
radius_send_request
Radius Funkcje


Sends the request and waites for a reply

radius_request_authenticator
radius_server_secret
Radius Funkcje
PHP Manual

radius_send_request

(PECL radius >= 1.1.0)

radius_send_request — Sends 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_create_request() - Create accounting or authentication request

radius_request_authenticator
radius_server_secret
Radius Funkcje


Returns the shared secret

radius_send_request
radius_strerror
Radius Funkcje
PHP Manual

radius_server_secret

(PECL radius >= 1.1.0)

radius_server_secret — Returns 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_send_request
radius_strerror
Radius Funkcje


Returns an error message

radius_server_secret
Rozszerzenia daty i czasu
Radius Funkcje
PHP Manual

radius_strerror

(PECL radius >= 1.1.0)

radius_strerror — Returns 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.

radius_server_secret
Rozszerzenia daty i czasu
Radius Funkcje


Rozszerzenia daty i czasu

  • Calendar
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Calendar Funkcje
  • data/czas — Data i Czas
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • DateTime — The DateTime class
    • DateTimeZone — The DateTimeZone class
    • DateInterval — The DateInterval class
    • DatePeriod — The DatePeriod class
    • Funkcje daty i czasu
    • Supported Date and Time Formats
    • Lista obsługiwanych stref czasowych
radius_strerror
Calendar
Opis funkcji


Calendar

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Calendar Funkcje
    • 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
Rozszerzenia daty i czasu
Wstęp
Rozszerzenia daty i czasu


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.

Calendar
Instalacja/Konfiguracja
Calendar


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Calendar


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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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)
Typy zasobów
Calendar Funkcje
Calendar


Calendar Funkcje

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
Stałe predefiniowane
cal_days_in_month
Calendar


Return the number of days in a month for a given year and calendar

Calendar Funkcje
cal_from_jd
Calendar Funkcje
PHP Manual

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5)

cal_days_in_month — Return 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_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?>

Calendar Funkcje
cal_from_jd
Calendar Funkcje


Converts from Julian Day Count to a supported calendar

cal_days_in_month
cal_info
Calendar Funkcje
PHP Manual

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_from_jd — Converts 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(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_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_days_in_month
cal_info
Calendar Funkcje


Returns information about a particular calendar

cal_from_jd
cal_to_jd
Calendar Funkcje
PHP Manual

cal_info

(PHP 4 >= 4.1.0, PHP 5)

cal_info — Returns 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_from_jd
cal_to_jd
Calendar Funkcje


Converts from a supported calendar to Julian Day Count

cal_info
easter_date
Calendar Funkcje
PHP Manual

cal_to_jd

(PHP 4 >= 4.1.0, PHP 5)

cal_to_jd — Converts 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

cal_info
easter_date
Calendar Funkcje


Get Unix timestamp for midnight on Easter of a given year

cal_to_jd
easter_days
Calendar Funkcje
PHP Manual

easter_date

(PHP 4, PHP 5)

easter_date — Get 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

cal_to_jd
easter_days
Calendar Funkcje


Get number of days after March 21 on which Easter falls for a given year

easter_date
FrenchToJD
Calendar Funkcje
PHP Manual

easter_days

(PHP 4, PHP 5)

easter_days — Get 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

easter_date
FrenchToJD
Calendar Funkcje


Converts a date from the French Republican Calendar to a Julian Day Count

easter_days
GregorianToJD
Calendar Funkcje
PHP Manual

FrenchToJD

(PHP 4, PHP 5)

FrenchToJD — Converts 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

easter_days
GregorianToJD
Calendar Funkcje


Converts a Gregorian date to Julian Day Count

FrenchToJD
JDDayOfWeek
Calendar Funkcje
PHP Manual

GregorianToJD

(PHP 4, PHP 5)

GregorianToJD — Converts 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(10, 11, 1970);
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

FrenchToJD
JDDayOfWeek
Calendar Funkcje


Returns the day of the week

GregorianToJD
JDMonthName
Calendar Funkcje
PHP Manual

JDDayOfWeek

(PHP 4, PHP 5)

JDDayOfWeek — Returns 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.

GregorianToJD
JDMonthName
Calendar Funkcje


Returns a month name

JDDayOfWeek
JDToFrench
Calendar Funkcje
PHP Manual

JDMonthName

(PHP 4, PHP 5)

JDMonthName — Returns 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.

JDDayOfWeek
JDToFrench
Calendar Funkcje


Converts a Julian Day Count to the French Republican Calendar

JDMonthName
JDToGregorian
Calendar Funkcje
PHP Manual

JDToFrench

(PHP 4, PHP 5)

JDToFrench — Converts 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

JDMonthName
JDToGregorian
Calendar Funkcje


Converts Julian Day Count to Gregorian date

JDToFrench
jdtojewish
Calendar Funkcje
PHP Manual

JDToGregorian

(PHP 4, PHP 5)

JDToGregorian — Converts 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ż:

  • gregoriantojd() - Converts a Gregorian date to Julian Day Count
  • cal_from_jd() - Converts from Julian Day Count to a supported calendar

JDToFrench
jdtojewish
Calendar Funkcje


Converts a Julian day count to a Jewish calendar date

JDToGregorian
JDToJulian
Calendar Funkcje
PHP Manual

jdtojewish

(PHP 4, PHP 5)

jdtojewish — Converts 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(10, 8, 2002), 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

JDToGregorian
JDToJulian
Calendar Funkcje


Converts a Julian Day Count to a Julian Calendar Date

jdtojewish
jdtounix
Calendar Funkcje
PHP Manual

JDToJulian

(PHP 4, PHP 5)

JDToJulian — Converts 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

jdtojewish
jdtounix
Calendar Funkcje


Convert Julian Day to Unix timestamp

JDToJulian
JewishToJD
Calendar Funkcje
PHP Manual

jdtounix

(PHP 4, PHP 5)

jdtounix — Convert 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

JDToJulian
JewishToJD
Calendar Funkcje


Converts a date in the Jewish Calendar to Julian Day Count

jdtounix
JulianToJD
Calendar Funkcje
PHP Manual

JewishToJD

(PHP 4, PHP 5)

JewishToJD — Converts 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

jdtounix
JulianToJD
Calendar Funkcje


Converts a Julian Calendar date to Julian Day Count

JewishToJD
unixtojd
Calendar Funkcje
PHP Manual

JulianToJD

(PHP 4, PHP 5)

JulianToJD — Converts 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

JewishToJD
unixtojd
Calendar Funkcje


Convert Unix timestamp to Julian Day

JulianToJD
data/czas
Calendar Funkcje
PHP Manual

unixtojd

(PHP 4, PHP 5)

unixtojd — Convert 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

JulianToJD
data/czas
Calendar Funkcje


Data i Czas

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • DateTime — The DateTime class
    • DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
    • DateTime::__construct — Returns new DateTime object
    • DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format
    • DateTime::diff — Returns the difference between two DateTime objects
    • DateTime::format — Returns date formatted according to given format
    • DateTime::getLastErrors — Returns the warnings and errors
    • DateTime::getOffset — Returns the timezone offset
    • DateTime::getTimestamp — Gets the Unix timestamp
    • DateTime::getTimezone — Return time zone relative to given DateTime
    • DateTime::modify — Alters the timestamp
    • DateTime::__set_state — The __set_state handler
    • DateTime::setDate — Sets the date
    • DateTime::setISODate — Sets the ISO date
    • DateTime::setTime — Sets the time
    • DateTime::setTimestamp — Sets the date and time based on an Unix timestamp
    • DateTime::setTimezone — Sets the time zone for the DateTime object
    • DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
    • DateTime::__wakeup — The __wakeup handler
  • DateTimeZone — The DateTimeZone class
    • DateTimeZone::__construct — Creates new DateTimeZone object
    • DateTimeZone::getLocation — Returns location information for a timezone
    • DateTimeZone::getName — Returns the name of the timezone
    • DateTimeZone::getOffset — Returns the timezone offset from GMT
    • DateTimeZone::getTransitions — Returns all transitions for the timezone
    • DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name
    • DateTimeZone::listIdentifiers — Returns numerically index array with all timezone identifiers
  • DateInterval — The DateInterval class
    • DateInterval::__construct — Creates new DateInterval object
    • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
    • DateInterval::format — Formats the interval
  • DatePeriod — The DatePeriod class
    • DatePeriod::__construct — Creates new DatePeriod object
  • Funkcje daty i czasu
    • checkdate — Waliduje datę gregoriańską
    • date_add — Alias dla DateTime::add
    • date_create_from_format — Alias dla DateTime::createFromFormat
    • date_create — Alias dla DateTime::__construct
    • date_date_set — Alias dla DateTime::setDate
    • date_default_timezone_get — Gets the default timezone used by all date/time functions in a script
    • date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
    • date_diff — Alias dla DateTime::diff
    • date_format — Alias dla DateTime::format
    • date_get_last_errors — Alias dla DateTime::getLastErrors
    • date_interval_create_from_date_string — Alias dla DateInterval::createFromDateString
    • date_interval_format — Alias dla DateInterval::format
    • date_isodate_set — Alias dla DateTime::setISODate
    • date_modify — Alias dla DateTime::modify
    • date_offset_get — Alias dla DateTime::getOffset
    • date_parse_from_format — Get info about given date formatted according to the specified format
    • date_parse — Returns associative array with detailed info about given date
    • date_sub — Alias dla DateTime::sub
    • date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
    • 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_time_set — Alias dla DateTime::setTime
    • date_timestamp_get — Alias dla DateTime::getTimestamp
    • date_timestamp_set — Alias dla DateTime::setTimestamp
    • date_timezone_get — Alias dla DateTime::getTimezone
    • date_timezone_set — Alias dla DateTime::setTimezone
    • date — Formatuje lokalny czas/datę
    • getdate — Pobiera informację o dacie/czasie
    • gettimeofday — Pobiera aktualny czas
    • gmdate — Formatuje datę/czas dla strefy GMT/UTC
    • gmmktime — Ustala uniksowy znacznik czasu dla daty ze strefy GMT
    • gmstrftime — Formatuje czas/datę ze strefy GMT/UTC zgodnie z lokalizacją
    • idate — Format a local time/date as integer
    • localtime — Pobiera czas lokalny
    • microtime — Zwraca aktualny uniksowy znacznik czasu z mikrosekundami
    • mktime — Oblicza uniksowy znacznik czasu dla podanej daty
    • strftime — Formatuje lokalną datę/czas zgodnie z lokalizacją
    • strptime — Parse a time/date generated with strftime
    • strtotime — Parsuje większość angielskich tekstowych opisów daty i czasu do uniksowego znacznika czasu
    • time — Zwraca aktualny uniksowy znacznik czasu
    • timezone_abbreviations_list — Alias dla DateTimeZone::listAbbreviations
    • timezone_identifiers_list — Alias dla DateTimeZone::listIdentifiers
    • timezone_location_get — Alias dla DateTimeZone::getLocation
    • timezone_name_from_abbr — Returns the timezone name from abbreviation
    • timezone_name_get — Alias dla DateTimeZone::getName
    • timezone_offset_get — Alias dla DateTimeZone::getOffset
    • timezone_open — Alias dla DateTimeZone::__construct
    • timezone_transitions_get — Alias dla DateTimeZone::getTransitions
    • timezone_version_get — Gets the version of the timezonedb
  • Supported Date and Time Formats
    • Time Formats
    • Date Formats
    • Compound Formats
    • Relative Formats
  • Lista obsługiwanych stref czasowych
    • Afryka
    • Ameryka
    • Antarktyda
    • Arktyka
    • Azja
    • Ocean Atlantycki
    • Australia
    • Europa
    • Ocean Indyjski
    • Ocean Spokojny
    • Inne
unixtojd
Wstęp
Rozszerzenia daty i czasu


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.

data/czas
Instalacja/Konfiguracja
data/czas


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
data/czas


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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)
Typy zasobów
DateTime
data/czas


Stałe predefiniowane
DateTime::add
data/czas
PHP Manual

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)

Spis treści

  • DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::__construct — Returns new DateTime object
  • DateTime::createFromFormat — Returns new DateTime object formatted according to the specified format
  • DateTime::diff — Returns the difference between two DateTime objects
  • DateTime::format — Returns date formatted according to given format
  • DateTime::getLastErrors — Returns the warnings and errors
  • DateTime::getOffset — Returns the timezone offset
  • DateTime::getTimestamp — Gets the Unix timestamp
  • DateTime::getTimezone — Return time zone relative to given DateTime
  • DateTime::modify — Alters the timestamp
  • DateTime::__set_state — The __set_state handler
  • DateTime::setDate — Sets the date
  • DateTime::setISODate — Sets the ISO date
  • DateTime::setTime — Sets the time
  • DateTime::setTimestamp — Sets the date and time based on an Unix timestamp
  • DateTime::setTimezone — Sets the time zone for the DateTime object
  • DateTime::sub — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::__wakeup — The __wakeup handler
Stałe predefiniowane
DateTime::add
data/czas


Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

DateTime
DateTime::__construct
DateTime
PHP Manual

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($date, date_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::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects
  • DateTime::modify() - Alters the timestamp
DateTime
DateTime::__construct
DateTime


Returns new DateTime object

DateTime::add
DateTime::createFromFormat
DateTime
PHP Manual

DateTime::__construct

date_create

(PHP 5 >= 5.2.0)

DateTime::__construct -- date_create — Returns 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() - Returns new DateTime object formatted according to the specified format
  • DateTimeZone::__construct() - Creates new DateTimeZone object
  • Date and Time Formats
  • date.timezone ini setting
  • date_default_timezone_set() - Sets the default timezone used by all date/time functions in a script
  • DateTime::getLastErrors() - Returns the warnings and errors
  • checkdate() - Waliduje datę gregoriańską
DateTime::add
DateTime::createFromFormat
DateTime


Returns new DateTime object formatted according to the specified format

DateTime::__construct
DateTime::diff
DateTime
PHP Manual

DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0)

DateTime::createFromFormat -- date_create_from_format — Returns 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::__construct() - Returns new DateTime object
  • DateTime::getLastErrors() - Returns the warnings and errors
  • checkdate() - Waliduje datę gregoriańską
  • strptime() - Parse a time/date generated with strftime
DateTime::__construct
DateTime::diff
DateTime


Returns the difference between two DateTime objects

DateTime::createFromFormat
DateTime::format
DateTime
PHP Manual

DateTime::diff

date_diff

(PHP 5 >= 5.3.0)

DateTime::diff -- date_diff — Returns 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::createFromFormat
DateTime::format
DateTime


Returns date formatted according to given format

DateTime::diff
DateTime::getLastErrors
DateTime
PHP Manual

DateTime::format

date_format

(PHP 5 >= 5.2.0)

DateTime::format -- date_format — Returns 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::diff
DateTime::getLastErrors
DateTime


Returns the warnings and errors

DateTime::format
DateTime::getOffset
DateTime
PHP Manual

DateTime::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0)

DateTime::getLastErrors -- date_get_last_errors — Returns 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::format
DateTime::getOffset
DateTime


Returns the timezone offset

DateTime::getLastErrors
DateTime::getTimestamp
DateTime
PHP Manual

DateTime::getOffset

date_offset_get

(PHP 5 >= 5.2.0)

DateTime::getOffset -- date_offset_get — Returns 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 $winter->getOffset() . "\n";
echo $summer->getOffset() . "\n";
?>

Powyższe przykłady wyświetlą:

-18000
-14400

Note: -18000 = -5 hours, -14400 = -4 hours.

DateTime::getLastErrors
DateTime::getTimestamp
DateTime


Gets the Unix timestamp

DateTime::getOffset
DateTime::getTimezone
DateTime
PHP Manual

DateTime::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0)

DateTime::getTimestamp -- date_timestamp_get — Gets 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::setTimestamp() - Sets the date and time based on an Unix timestamp
  • DateTime::format() - Returns date formatted according to given format
DateTime::getOffset
DateTime::getTimezone
DateTime


Return time zone relative to given DateTime

DateTime::getTimestamp
DateTime::modify
DateTime
PHP Manual

DateTime::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0)

DateTime::getTimezone -- date_timezone_get — Return time zone relative to given DateTime

Opis

Styl obiektowy

public DateTimeZone DateTime::getTimezone ( void )

Styl proceduralny

DateTimeZone date_timezone_get ( DateTime $object )

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(null, timezone_open('Europe/London'));
$tz = date_timezone_get($date);
echo timezone_name_get($tz);
?>

Powyższe przykłady wyświetlą:

Europe/London

Zobacz też:

  • DateTime::setTimezone() - Sets the time zone for the DateTime object
DateTime::getTimestamp
DateTime::modify
DateTime


Alters the timestamp

DateTime::getTimezone
DateTime::__set_state
DateTime
PHP Manual

DateTime::modify

date_modify

(PHP 5 >= 5.2.0)

DateTime::modify -- date_modify — Alters 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.0 | Zmieniono 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ż:

  • strtotime() - Parsuje większość angielskich tekstowych opisów daty i czasu do uniksowego znacznika czasu
  • 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::setDate() - Sets the date
  • DateTime::setISODate() - Sets the ISO date
  • DateTime::setTime() - Sets the time
  • DateTime::setTimestamp() - Sets the date and time based on an Unix timestamp
DateTime::getTimezone
DateTime::__set_state
DateTime


The __set_state handler

DateTime::modify
DateTime::setDate
DateTime
PHP Manual

DateTime::__set_state

(PHP 5 >= 5.2.0)

DateTime::__set_state — The __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::modify
DateTime::setDate
DateTime


Sets the date

DateTime::__set_state
DateTime::setISODate
DateTime
PHP Manual

DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0)

DateTime::setDate -- date_date_set — Sets 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.0 | Zmieniono 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(2001, 2, 3);
echo $date->format('Y-m-d');
?>

Styl proceduralny

<?php
$date = date_create();
date_date_set($date, 2001, 2, 3);
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(2001, 2, 28);
echo $date->format('Y-m-d') . "\n";

$date->setDate(2001, 2, 29);
echo $date->format('Y-m-d') . "\n";

$date->setDate(2001, 14, 3);
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() - Sets the ISO date
  • DateTime::setTime() - Sets the time
DateTime::__set_state
DateTime::setISODate
DateTime


Sets the ISO date

DateTime::setDate
DateTime::setTime
DateTime
PHP Manual

DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0)

DateTime::setISODate -- date_isodate_set — Sets 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.0 | Zmieniono 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(2008, 2);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";
?>

Styl proceduralny

<?php
$date = date_create();

date_isodate_set($date, 2008, 2);
echo date_format($date, 'Y-m-d') . "\n";

date_isodate_set($date, 2008, 2, 7);
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(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 2, 8);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 53, 7);
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(2008, 14);
echo $date->format('n');
?>

Powyższe przykłady wyświetlą:

3

Zobacz też:

  • DateTime::setDate() - Sets the date
  • DateTime::setTime() - Sets the time
DateTime::setDate
DateTime::setTime
DateTime


Sets the time

DateTime::setISODate
DateTime::setTimestamp
DateTime
PHP Manual

DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0)

DateTime::setTime -- date_time_set — Sets 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.0 | Zmieniono 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(14, 55);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
?>

Styl proceduralny

<?php
$date = date_create('2001-01-01');

date_time_set($date, 14, 55);
echo date_format($date, 'Y-m-d H:i:s') . "\n";

date_time_set($date, 14, 55, 24);
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(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 55, 65);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 65, 24);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(25, 55, 24);
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::setDate() - Sets the date
  • DateTime::setISODate() - Sets the ISO date
DateTime::setISODate
DateTime::setTimestamp
DateTime


Sets the date and time based on an Unix timestamp

DateTime::setTime
DateTime::setTimezone
DateTime
PHP Manual

DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0)

DateTime::setTimestamp -- date_timestamp_set — Sets 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($date, 1171502725);
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::getTimestamp() - Gets the Unix timestamp
DateTime::setTime
DateTime::setTimezone
DateTime


Sets the time zone for the DateTime object

DateTime::setTimestamp
DateTime::sub
DateTime
PHP Manual

DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0)

DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object

Opis

Styl obiektowy

public DateTime DateTime::setTimezone ( DateTimeZone $timezone )

Styl proceduralny

DateTime date_timezone_set ( DateTime $object , DateTimeZone $timezone )

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.0 | Zmieniono 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($date, timezone_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::getTimezone() - Return time zone relative to given DateTime
  • DateTimeZone::__construct() - Creates new DateTimeZone object
DateTime::setTimestamp
DateTime::sub
DateTime


Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

DateTime::setTimezone
DateTime::__wakeup
DateTime
PHP Manual

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($date, date_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::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects
  • DateTime::modify() - Alters the timestamp
DateTime::setTimezone
DateTime::__wakeup
DateTime


The __wakeup handler

DateTime::sub
DateTimeZone
DateTime
PHP Manual

DateTime::__wakeup

(PHP 5 >= 5.2.0)

DateTime::__wakeup — The __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.

DateTime::sub
DateTimeZone
DateTime


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.

Spis treści

  • DateTimeZone::__construct — Creates new DateTimeZone object
  • DateTimeZone::getLocation — Returns location information for a timezone
  • DateTimeZone::getName — Returns the name of the timezone
  • DateTimeZone::getOffset — Returns the timezone offset from GMT
  • DateTimeZone::getTransitions — Returns all transitions for the timezone
  • DateTimeZone::listAbbreviations — Returns associative array containing dst, offset and the timezone name
  • DateTimeZone::listIdentifiers — Returns numerically index array with all timezone identifiers
DateTime::__wakeup
DateTimeZone::__construct
data/czas


Creates new DateTimeZone object

DateTimeZone
DateTimeZone::getLocation
DateTimeZone
PHP Manual

DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0)

DateTimeZone::__construct -- timezone_open — Creates 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
DateTimeZone::getLocation
DateTimeZone


Returns location information for a timezone

DateTimeZone::__construct
DateTimeZone::getName
DateTimeZone
PHP Manual

DateTimeZone::getLocation

timezone_location_get

(PHP 5 >= 5.3.0)

DateTimeZone::getLocation -- timezone_location_get — Returns location information for a timezone

Opis

Styl obiektowy

public array DateTimeZone::getLocation ( void )

Styl proceduralny

array timezone_location_get ( DateTimeZone $object )

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::__construct
DateTimeZone::getName
DateTimeZone


Returns the name of the timezone

DateTimeZone::getLocation
DateTimeZone::getOffset
DateTimeZone
PHP Manual

DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0)

DateTimeZone::getName -- timezone_name_get — Returns 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::getLocation
DateTimeZone::getOffset
DateTimeZone


Returns the timezone offset from GMT

DateTimeZone::getName
DateTimeZone::getTransitions
DateTimeZone
PHP Manual

DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0)

DateTimeZone::getOffset -- timezone_offset_get — Returns 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::getName
DateTimeZone::getTransitions
DateTimeZone


Returns all transitions for the timezone

DateTimeZone::getOffset
DateTimeZone::listAbbreviations
DateTimeZone
PHP Manual

DateTimeZone::getTransitions

timezone_transitions_get

(PHP 5 >= 5.2.0)

DateTimeZone::getTransitions -- timezone_transitions_get — Returns 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($transitions, 0, 3));
?>

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::getOffset
DateTimeZone::listAbbreviations
DateTimeZone


Returns associative array containing dst, offset and the timezone name

DateTimeZone::getTransitions
DateTimeZone::listIdentifiers
DateTimeZone
PHP Manual

DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0)

DateTimeZone::listAbbreviations -- timezone_abbreviations_list — Returns associative array containing dst, offset and the timezone name

Opis

Styl obiektowy

public static array DateTimeZone::listAbbreviations ( void )

Styl proceduralny

array timezone_abbreviations_list ( void )

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

  • timezone_identifiers_list() - Alias dla DateTimeZone::listIdentifiers

DateTimeZone::getTransitions
DateTimeZone::listIdentifiers
DateTimeZone


Returns numerically index array with all timezone identifiers

DateTimeZone::listAbbreviations
DateInterval
DateTimeZone
PHP Manual

DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0)

DateTimeZone::listIdentifiers -- timezone_identifiers_list — Returns 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ż:

  • timezone_abbreviations_list() - Alias dla DateTimeZone::listAbbreviations

DateTimeZone::listAbbreviations
DateInterval
DateTimeZone


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.

Spis treści

  • DateInterval::__construct — Creates new DateInterval object
  • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
  • DateInterval::format — Formats the interval
DateTimeZone::listIdentifiers
DateInterval::__construct
data/czas


Creates new DateInterval object

DateInterval
DateInterval::createFromDateString
DateInterval
PHP Manual

DateInterval::__construct

(PHP 5 >= 5.3.0)

DateInterval::__construct — Creates 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::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::diff() - Returns the difference between two DateTime objects

DateInterval
DateInterval::createFromDateString
DateInterval


Sets up a DateInterval from the relative parts of the string

DateInterval::__construct
DateInterval::format
DateInterval
PHP Manual

DateInterval::createFromDateString

(PHP 5 >= 5.3.0)

DateInterval::createFromDateString — Sets 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::__construct
DateInterval::format
DateInterval


Formats the interval

DateInterval::createFromDateString
DatePeriod
DateInterval
PHP Manual

DateInterval::format

(PHP 5 >= 5.3.0)

DateInterval::format — Formats 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

DateInterval::createFromDateString
DatePeriod
DateInterval


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

Spis treści

  • DatePeriod::__construct — Creates new DatePeriod object
DateInterval::format
DatePeriod::__construct
data/czas


Creates new DatePeriod object

DatePeriod
Funkcje daty i czasu
DatePeriod
PHP Manual

DatePeriod::__construct

(PHP 5 >= 5.3.0)

DatePeriod::__construct — Creates 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.

DatePeriod
Funkcje daty i czasu
DatePeriod


Funkcje daty i czasu

Spis treści

  • checkdate — Waliduje datę gregoriańską
  • date_add — Alias dla DateTime::add
  • date_create_from_format — Alias dla DateTime::createFromFormat
  • date_create — Alias dla DateTime::__construct
  • date_date_set — Alias dla DateTime::setDate
  • date_default_timezone_get — Gets the default timezone used by all date/time functions in a script
  • date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
  • date_diff — Alias dla DateTime::diff
  • date_format — Alias dla DateTime::format
  • date_get_last_errors — Alias dla DateTime::getLastErrors
  • date_interval_create_from_date_string — Alias dla DateInterval::createFromDateString
  • date_interval_format — Alias dla DateInterval::format
  • date_isodate_set — Alias dla DateTime::setISODate
  • date_modify — Alias dla DateTime::modify
  • date_offset_get — Alias dla DateTime::getOffset
  • date_parse_from_format — Get info about given date formatted according to the specified format
  • date_parse — Returns associative array with detailed info about given date
  • date_sub — Alias dla DateTime::sub
  • date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
  • 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_time_set — Alias dla DateTime::setTime
  • date_timestamp_get — Alias dla DateTime::getTimestamp
  • date_timestamp_set — Alias dla DateTime::setTimestamp
  • date_timezone_get — Alias dla DateTime::getTimezone
  • date_timezone_set — Alias dla DateTime::setTimezone
  • date — Formatuje lokalny czas/datę
  • getdate — Pobiera informację o dacie/czasie
  • gettimeofday — Pobiera aktualny czas
  • gmdate — Formatuje datę/czas dla strefy GMT/UTC
  • gmmktime — Ustala uniksowy znacznik czasu dla daty ze strefy GMT
  • gmstrftime — Formatuje czas/datę ze strefy GMT/UTC zgodnie z lokalizacją
  • idate — Format a local time/date as integer
  • localtime — Pobiera czas lokalny
  • microtime — Zwraca aktualny uniksowy znacznik czasu z mikrosekundami
  • mktime — Oblicza uniksowy znacznik czasu dla podanej daty
  • strftime — Formatuje lokalną datę/czas zgodnie z lokalizacją
  • strptime — Parse a time/date generated with strftime
  • strtotime — Parsuje większość angielskich tekstowych opisów daty i czasu do uniksowego znacznika czasu
  • time — Zwraca aktualny uniksowy znacznik czasu
  • timezone_abbreviations_list — Alias dla DateTimeZone::listAbbreviations
  • timezone_identifiers_list — Alias dla DateTimeZone::listIdentifiers
  • timezone_location_get — Alias dla DateTimeZone::getLocation
  • timezone_name_from_abbr — Returns the timezone name from abbreviation
  • timezone_name_get — Alias dla DateTimeZone::getName
  • timezone_offset_get — Alias dla DateTimeZone::getOffset
  • timezone_open — Alias dla DateTimeZone::__construct
  • timezone_transitions_get — Alias dla DateTimeZone::getTransitions
  • timezone_version_get — Gets the version of the timezonedb
DatePeriod::__construct
checkdate
data/czas


Waliduje datę gregoriańską

Funkcje daty i czasu
date_add
Funkcje daty i czasu
PHP Manual

checkdate

(PHP 4, PHP 5)

checkdate — Waliduje 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(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

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

Funkcje daty i czasu
date_add
Funkcje daty i czasu


Alias dla DateTime::add

checkdate
date_create_from_format
Funkcje daty i czasu
PHP Manual

date_add

(PHP 5 >= 5.3.0)

date_add — Alias dla DateTime::add()

Opis

Ta funkcja jest aliasem dla: DateTime::add()

checkdate
date_create_from_format
Funkcje daty i czasu


Alias dla DateTime::createFromFormat

date_add
date_create
Funkcje daty i czasu
PHP Manual

date_create_from_format

(PHP 5 >= 5.3.0)

date_create_from_format — Alias dla DateTime::createFromFormat()

Opis

Ta funkcja jest aliasem dla: DateTime::createFromFormat()

date_add
date_create
Funkcje daty i czasu


Alias dla DateTime::__construct

date_create_from_format
date_date_set
Funkcje daty i czasu
PHP Manual

date_create

(PHP 5 >= 5.2.0)

date_create — Alias dla DateTime::__construct()

Opis

Ta funkcja jest aliasem dla: DateTime::__construct()

date_create_from_format
date_date_set
Funkcje daty i czasu


Alias dla DateTime::setDate

date_create
date_default_timezone_get
Funkcje daty i czasu
PHP Manual

date_date_set

(PHP 5 >= 5.2.0)

date_date_set — Alias dla DateTime::setDate()

Opis

Ta funkcja jest aliasem dla: DateTime::setDate()

date_create
date_default_timezone_get
Funkcje daty i czasu


Gets the default timezone used by all date/time functions in a script

date_date_set
date_default_timezone_set
Funkcje daty i czasu
PHP Manual

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() - Sets the default timezone used by all date/time functions in a script
  • Lista obsługiwanych stref czasowych

date_date_set
date_default_timezone_set
Funkcje daty i czasu


Sets the default timezone used by all date/time functions in a script

date_default_timezone_get
date_diff
Funkcje daty i czasu
PHP Manual

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_tz, ini_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_default_timezone_get() - Gets the default timezone used by all date/time functions in a script
  • Lista obsługiwanych stref czasowych

date_default_timezone_get
date_diff
Funkcje daty i czasu


Alias dla DateTime::diff

date_default_timezone_set
date_format
Funkcje daty i czasu
PHP Manual

date_diff

(PHP 5 >= 5.3.0)

date_diff — Alias dla DateTime::diff()

Opis

Ta funkcja jest aliasem dla: DateTime::diff()

date_default_timezone_set
date_format
Funkcje daty i czasu


Alias dla DateTime::format

date_diff
date_get_last_errors
Funkcje daty i czasu
PHP Manual

date_format

(PHP 5 >= 5.2.0)

date_format — Alias dla DateTime::format()

Opis

Ta funkcja jest aliasem dla: DateTime::format()

date_diff
date_get_last_errors
Funkcje daty i czasu


Alias dla DateTime::getLastErrors

date_format
date_interval_create_from_date_string
Funkcje daty i czasu
PHP Manual

date_get_last_errors

(PHP 5 >= 5.3.0)

date_get_last_errors — Alias dla DateTime::getLastErrors()

Opis

Ta funkcja jest aliasem dla: DateTime::getLastErrors()

date_format
date_interval_create_from_date_string
Funkcje daty i czasu


Alias dla DateInterval::createFromDateString

date_get_last_errors
date_interval_format
Funkcje daty i czasu
PHP Manual

date_interval_create_from_date_string

(PHP 5 >= 5.3.0)

date_interval_create_from_date_string — Alias dla DateInterval::createFromDateString()

Opis

Ta funkcja jest aliasem dla: DateInterval::createFromDateString()

date_get_last_errors
date_interval_format
Funkcje daty i czasu


Alias dla DateInterval::format

date_interval_create_from_date_string
date_isodate_set
Funkcje daty i czasu
PHP Manual

date_interval_format

(PHP 5 >= 5.3.0)

date_interval_format — Alias dla DateInterval::format()

Opis

Ta funkcja jest aliasem dla: DateInterval::format()

date_interval_create_from_date_string
date_isodate_set
Funkcje daty i czasu


Alias dla DateTime::setISODate

date_interval_format
date_modify
Funkcje daty i czasu
PHP Manual

date_isodate_set

(PHP 5 >= 5.2.0)

date_isodate_set — Alias dla DateTime::setISODate()

Opis

Ta funkcja jest aliasem dla: DateTime::setISODate()

date_interval_format
date_modify
Funkcje daty i czasu


Alias dla DateTime::modify

date_isodate_set
date_offset_get
Funkcje daty i czasu
PHP Manual

date_modify

(PHP 5 >= 5.2.0)

date_modify — Alias dla DateTime::modify()

Opis

Ta funkcja jest aliasem dla: DateTime::modify()

date_isodate_set
date_offset_get
Funkcje daty i czasu


Alias dla DateTime::getOffset

date_modify
date_parse_from_format
Funkcje daty i czasu
PHP Manual

date_offset_get

(PHP 5 >= 5.2.0)

date_offset_get — Alias dla DateTime::getOffset()

Opis

Ta funkcja jest aliasem dla: DateTime::getOffset()

date_modify
date_parse_from_format
Funkcje daty i czasu


Get info about given date formatted according to the specified format

date_offset_get
date_parse
Funkcje daty i czasu
PHP Manual

date_parse_from_format

(PHP 5 >= 5.3.0)

date_parse_from_format — Get 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ż:

  • DateTime::createFromFormat() - Returns new DateTime object formatted according to the specified format
  • checkdate() - Waliduje datę gregoriańską

date_offset_get
date_parse
Funkcje daty i czasu


Returns associative array with detailed info about given date

date_parse_from_format
date_sub
Funkcje daty i czasu
PHP Manual

date_parse

(PHP 5 >= 5.2.0)

date_parse — Returns 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ż:

  • checkdate() - Waliduje datę gregoriańską
  • getdate() - Pobiera informację o dacie/czasie

date_parse_from_format
date_sub
Funkcje daty i czasu


Alias dla DateTime::sub

date_parse
date_sun_info
Funkcje daty i czasu
PHP Manual

date_sub

(PHP 5 >= 5.3.0)

date_sub — Alias dla DateTime::sub()

Opis

Ta funkcja jest aliasem dla: DateTime::sub()

date_parse
date_sun_info
Funkcje daty i czasu


Returns an array with information about sunset/sunrise and twilight begin/end

date_sub
date_sunrise
Funkcje daty i czasu
PHP Manual

date_sun_info

(PHP 5 >= 5.1.2)

date_sun_info — Returns 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.7667, 35.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_sub
date_sunrise
Funkcje daty i czasu


Returns time of sunrise for a given day and location

date_sun_info
date_sunset
Funkcje daty i czasu
PHP Manual

date_sunrise

(PHP 5)

date_sunrise — Returns 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_STRING, 38.4, -9, 90, 1);

?>

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_sun_info
date_sunset
Funkcje daty i czasu


Returns time of sunset for a given day and location

date_sunrise
date_time_set
Funkcje daty i czasu
PHP Manual

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_STRING, 38.4, -9, 90, 1);

?>

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_sunrise
date_time_set
Funkcje daty i czasu


Alias dla DateTime::setTime

date_sunset
date_timestamp_get
Funkcje daty i czasu
PHP Manual

date_time_set

(PHP 5 >= 5.2.0)

date_time_set — Alias dla DateTime::setTime()

Opis

Ta funkcja jest aliasem dla: DateTime::setTime()

date_sunset
date_timestamp_get
Funkcje daty i czasu


Alias dla DateTime::getTimestamp

date_time_set
date_timestamp_set
Funkcje daty i czasu
PHP Manual

date_timestamp_get

(PHP 5 >= 5.3.0)

date_timestamp_get — Alias dla DateTime::getTimestamp()

Opis

Ta funkcja jest aliasem dla: DateTime::getTimestamp()

date_time_set
date_timestamp_set
Funkcje daty i czasu


Alias dla DateTime::setTimestamp

date_timestamp_get
date_timezone_get
Funkcje daty i czasu
PHP Manual

date_timestamp_set

(PHP 5 >= 5.3.0)

date_timestamp_set — Alias dla DateTime::setTimestamp()

Opis

Ta funkcja jest aliasem dla: DateTime::setTimestamp()

date_timestamp_get
date_timezone_get
Funkcje daty i czasu


Alias dla DateTime::getTimezone

date_timestamp_set
date_timezone_set
Funkcje daty i czasu
PHP Manual

date_timezone_get

(PHP 5 >= 5.2.0)

date_timezone_get — Alias dla DateTime::getTimezone()

Opis

Ta funkcja jest aliasem dla: DateTime::getTimezone()

date_timestamp_set
date_timezone_set
Funkcje daty i czasu


Alias dla DateTime::setTimezone

date_timezone_get
date
Funkcje daty i czasu
PHP Manual

date_timezone_set

(PHP 5 >= 5.2.0)

date_timezone_set — Alias dla DateTime::setTimezone()

Opis

Ta funkcja jest aliasem dla: DateTime::setTimezone()

date_timezone_get
date
Funkcje daty i czasu


Formatuje lokalny czas/datę

date_timezone_set
getdate
Funkcje daty i czasu
PHP Manual

date

(PHP 4, PHP 5)

date — Formatuje 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(0, 0, 0, 7, 1, 2000));

/* 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_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>

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(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$ostatni_miesiac = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nastepny_rok  = mktime(0, 0, 0, date("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

date_timezone_set
getdate
Funkcje daty i czasu


Pobiera informację o dacie/czasie

date
gettimeofday
Funkcje daty i czasu
PHP Manual

getdate

(PHP 4, PHP 5)

getdate — Pobiera 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

date
gettimeofday
Funkcje daty i czasu


Pobiera aktualny czas

getdate
gmdate
Funkcje daty i czasu
PHP Manual

gettimeofday

(PHP 4, PHP 5)

gettimeofday — Pobiera 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

getdate
gmdate
Funkcje daty i czasu


Formatuje datę/czas dla strefy GMT/UTC

gettimeofday
gmmktime
Funkcje daty i czasu
PHP Manual

gmdate

(PHP 4, PHP 5)

gmdate — Formatuje 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().

gettimeofday
gmmktime
Funkcje daty i czasu


Ustala uniksowy znacznik czasu dla daty ze strefy GMT

gmdate
gmstrftime
Funkcje daty i czasu
PHP Manual

gmmktime

(PHP 4, PHP 5)

gmmktime — Ustala 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.

gmdate
gmstrftime
Funkcje daty i czasu


Formatuje czas/datę ze strefy GMT/UTC zgodnie z lokalizacją

gmmktime
idate
Funkcje daty i czasu
PHP Manual

gmstrftime

(PHP 4, PHP 5)

gmstrftime — Formatuje 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(20, 0, 0, 12, 31, 98)) . "\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
?>

Zobacz też:

  • strftime() - Formatuje lokalną datę/czas zgodnie z lokalizacją

gmmktime
idate
Funkcje daty i czasu


Format a local time/date as integer

gmstrftime
localtime
Funkcje daty i czasu
PHP Manual

idate

(PHP 5)

idate — Format 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

gmstrftime
localtime
Funkcje daty i czasu


Pobiera czas lokalny

idate
microtime
Funkcje daty i czasu
PHP Manual

localtime

(PHP 4, PHP 5)

localtime — Pobiera 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
)

idate
microtime
Funkcje daty i czasu


Zwraca aktualny uniksowy znacznik czasu z mikrosekundami

localtime
mktime
Funkcje daty i czasu
PHP Manual

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

localtime
mktime
Funkcje daty i czasu


Oblicza uniksowy znacznik czasu dla podanej daty

microtime
strftime
Funkcje daty i czasu
PHP Manual

mktime

(PHP 4, PHP 5)

mktime — Oblicza 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().

microtime
strftime
Funkcje daty i czasu


Formatuje lokalną datę/czas zgodnie z lokalizacją

mktime
strptime
Funkcje daty i czasu
PHP Manual

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

mktime
strptime
Funkcje daty i czasu


Parse a time/date generated with strftime

strftime
strtotime
Funkcje daty i czasu
PHP Manual

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

  • checkdate() - Waliduje datę gregoriańską
  • strftime() - Formatuje lokalną datę/czas zgodnie z lokalizacją
  • date_parse_from_format() - Get info about given date formatted according to the specified format
  • DateTime::createFromFormat() - Returns new DateTime object formatted according to the specified format

strftime
strtotime
Funkcje daty i czasu


Parsuje większość angielskich tekstowych opisów daty i czasu do uniksowego znacznika czasu

strptime
time
Funkcje daty i czasu
PHP Manual

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

strptime
time
Funkcje daty i czasu


Zwraca aktualny uniksowy znacznik czasu

strtotime
timezone_abbreviations_list
Funkcje daty i czasu
PHP Manual

time

(PHP 4, PHP 5)

time — Zwraca 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() + (7 * 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

strtotime
timezone_abbreviations_list
Funkcje daty i czasu


Alias dla DateTimeZone::listAbbreviations

time
timezone_identifiers_list
Funkcje daty i czasu
PHP Manual

timezone_abbreviations_list

(PHP 5 >= 5.2.0)

timezone_abbreviations_list — Alias dla DateTimeZone::listAbbreviations()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::listAbbreviations()

time
timezone_identifiers_list
Funkcje daty i czasu


Alias dla DateTimeZone::listIdentifiers

timezone_abbreviations_list
timezone_location_get
Funkcje daty i czasu
PHP Manual

timezone_identifiers_list

(PHP 5 >= 5.2.0)

timezone_identifiers_list — Alias dla DateTimeZone::listIdentifiers()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::listIdentifiers()

timezone_abbreviations_list
timezone_location_get
Funkcje daty i czasu


Alias dla DateTimeZone::getLocation

timezone_identifiers_list
timezone_name_from_abbr
Funkcje daty i czasu
PHP Manual

timezone_location_get

(PHP 5 >= 5.3.0)

timezone_location_get — Alias dla DateTimeZone::getLocation()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getLocation()

timezone_identifiers_list
timezone_name_from_abbr
Funkcje daty i czasu


Returns the timezone name from abbreviation

timezone_location_get
timezone_name_get
Funkcje daty i czasu
PHP Manual

timezone_name_from_abbr

(PHP 5 >= 5.1.3)

timezone_name_from_abbr — Returns 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("", 3600, 0) . "\n";
?>

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

Europe/Berlin
Europe/Paris

Zobacz też:

  • timezone_abbreviations_list() - Alias dla DateTimeZone::listAbbreviations

timezone_location_get
timezone_name_get
Funkcje daty i czasu


Alias dla DateTimeZone::getName

timezone_name_from_abbr
timezone_offset_get
Funkcje daty i czasu
PHP Manual

timezone_name_get

(PHP 5 >= 5.2.0)

timezone_name_get — Alias dla DateTimeZone::getName()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getName()

timezone_name_from_abbr
timezone_offset_get
Funkcje daty i czasu


Alias dla DateTimeZone::getOffset

timezone_name_get
timezone_open
Funkcje daty i czasu
PHP Manual

timezone_offset_get

(PHP 5 >= 5.2.0)

timezone_offset_get — Alias dla DateTimeZone::getOffset()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getOffset()

timezone_name_get
timezone_open
Funkcje daty i czasu


Alias dla DateTimeZone::__construct

timezone_offset_get
timezone_transitions_get
Funkcje daty i czasu
PHP Manual

timezone_open

(PHP 5 >= 5.2.0)

timezone_open — Alias dla DateTimeZone::__construct()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::__construct()

timezone_offset_get
timezone_transitions_get
Funkcje daty i czasu


Alias dla DateTimeZone::getTransitions

timezone_open
timezone_version_get
Funkcje daty i czasu
PHP Manual

timezone_transitions_get

(PHP 5 >= 5.2.0)

timezone_transitions_get — Alias dla DateTimeZone::getTransitions()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getTransitions()

timezone_open
timezone_version_get
Funkcje daty i czasu


Gets the version of the timezonedb

timezone_transitions_get
Supported Date and Time Formats
Funkcje daty i czasu
PHP Manual

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

Zobacz też:

  • List of Supported Timezones

timezone_transitions_get
Supported Date and Time Formats
Funkcje daty i czasu


Supported Date and Time Formats

Spis treści

  • Time Formats
  • Date Formats
  • Compound Formats
  • Relative Formats

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

timezone_version_get
Time Formats
data/czas


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"
Supported Date and Time Formats
Date Formats
Supported Date and Time Formats


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

Time Formats
Compound Formats
Supported Date and Time Formats


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

Date Formats
Relative Formats
Supported Date and Time Formats


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.

Compound Formats
Lista obsługiwanych stref czasowych
Supported Date and Time Formats


Lista obsługiwanych stref czasowych

Spis treści

  • Afryka
  • Ameryka
  • Antarktyda
  • Arktyka
  • Azja
  • Ocean Atlantycki
  • Australia
  • Europa
  • Ocean Indyjski
  • Ocean Spokojny
  • Inne

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

Relative Formats
Afryka
data/czas


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 |
Lista obsługiwanych stref czasowych
Ameryka
Lista obsługiwanych stref czasowych


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/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 |  |
Afryka
Antarktyda
Lista obsługiwanych stref czasowych


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 |  |  |  |
Ameryka
Arktyka
Lista obsługiwanych stref czasowych


Arktyka

Arktyka
Arctic/Longyearbyen
Antarktyda
Azja
Lista obsługiwanych stref czasowych


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 |
Arktyka
Ocean Atlantycki
Lista obsługiwanych stref czasowych


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 |  |  |
Azja
Australia
Lista obsługiwanych stref czasowych


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 |  |
Ocean Atlantycki
Europa
Lista obsługiwanych stref czasowych


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 |  |
Australia
Ocean Indyjski
Lista obsługiwanych stref czasowych


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 |  |  |  |
Europa
Ocean Spokojny
Lista obsługiwanych stref czasowych


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 |  |  |
Ocean Indyjski
Inne
Lista obsługiwanych stref czasowych


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.

Ocean Spokojny
Rozszerzenia wiersza poleceń
Lista obsługiwanych stref czasowych


Rozszerzenia wiersza poleceń

  • Ncurses — Ncurses Terminal Screen Control
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Ncurses Funkcje
  • Newt
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Newt Funkcje
  • Readline — GNU Readline
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje Readline
Inne
Ncurses
Opis funkcji


Ncurses Terminal Screen Control

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
    • Error codes
    • Colors
    • Keys
    • Mouse
  • Ncurses Funkcje
    • ncurses_addch — Add character at current position and advance cursor
    • ncurses_addchnstr — Add attributed string with specified length at current position
    • ncurses_addchstr — Add attributed string at current position
    • ncurses_addnstr — Add string with specified length at current position
    • ncurses_addstr — Output text at current position
    • ncurses_assume_default_colors — Define default colors for color 0
    • ncurses_attroff — Turn off the given attributes
    • ncurses_attron — Turn on the given attributes
    • ncurses_attrset — Set given attributes
    • ncurses_baudrate — Returns baudrate of terminal
    • ncurses_beep — Let the terminal beep
    • ncurses_bkgd — Set background property for terminal screen
    • ncurses_bkgdset — Control screen background
    • ncurses_border — Draw a border around the screen using attributed characters
    • ncurses_bottom_panel — Moves a visible panel to the bottom of the stack
    • ncurses_can_change_color — Checks if terminal color definitions can be changed
    • ncurses_cbreak — Switch of input buffering
    • ncurses_clear — Clear screen
    • ncurses_clrtobot — Clear screen from current position to bottom
    • ncurses_clrtoeol — Clear screen from current position to end of line
    • ncurses_color_content — Retrieves RGB components of a color
    • ncurses_color_set — Set active foreground and background colors
    • ncurses_curs_set — Set cursor state
    • ncurses_def_prog_mode — Saves terminals (program) mode
    • ncurses_def_shell_mode — Saves terminals (shell) mode
    • ncurses_define_key — Define a keycode
    • ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)
    • ncurses_delay_output — Delay output on terminal using padding characters
    • ncurses_delch — Delete character at current position, move rest of line left
    • ncurses_deleteln — Delete line at current position, move rest of screen up
    • ncurses_delwin — Delete a ncurses window
    • ncurses_doupdate — Write all prepared refreshes to terminal
    • ncurses_echo — Activate keyboard input echo
    • ncurses_echochar — Single character output including refresh
    • ncurses_end — Stop using ncurses, clean up the screen
    • ncurses_erase — Erase terminal screen
    • ncurses_erasechar — Returns current erase character
    • ncurses_filter — Set LINES for iniscr() and newterm() to 1
    • ncurses_flash — Flash terminal screen (visual bell)
    • ncurses_flushinp — Flush keyboard input buffer
    • ncurses_getch — Read a character from keyboard
    • ncurses_getmaxyx — Returns the size of a window
    • ncurses_getmouse — Reads mouse event
    • ncurses_getyx — Returns the current cursor position for a window
    • ncurses_halfdelay — Put terminal into halfdelay mode
    • ncurses_has_colors — Checks if terminal has color capabilities
    • ncurses_has_ic — Check for insert- and delete-capabilities
    • ncurses_has_il — Check for line insert- and delete-capabilities
    • ncurses_has_key — Check for presence of a function key on terminal keyboard
    • ncurses_hide_panel — Remove panel from the stack, making it invisible
    • ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long
    • ncurses_inch — Get character and attribute at current position
    • ncurses_init_color — Define a terminal color
    • ncurses_init_pair — Define a color pair
    • ncurses_init — Initialize ncurses
    • ncurses_insch — Insert character moving rest of line including character at current position
    • ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)
    • ncurses_insertln — Insert a line, move rest of screen down
    • ncurses_insstr — Insert string at current position, moving rest of line right
    • ncurses_instr — Reads string from terminal screen
    • ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed
    • ncurses_keyok — Enable or disable a keycode
    • ncurses_keypad — Turns keypad on or off
    • ncurses_killchar — Returns current line kill character
    • ncurses_longname — Returns terminals description
    • ncurses_meta — Enables/Disable 8-bit meta key information
    • ncurses_mouse_trafo — Transforms coordinates
    • ncurses_mouseinterval — Set timeout for mouse button clicks
    • ncurses_mousemask — Sets mouse options
    • ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]
    • ncurses_move — Move output position
    • ncurses_mvaddch — Move current position and add character
    • ncurses_mvaddchnstr — Move position and add attributed string with specified length
    • ncurses_mvaddchstr — Move position and add attributed string
    • ncurses_mvaddnstr — Move position and add string with specified length
    • ncurses_mvaddstr — Move position and add string
    • ncurses_mvcur — Move cursor immediately
    • ncurses_mvdelch — Move position and delete character, shift rest of line left
    • ncurses_mvgetch — Move position and get character at new position
    • ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long
    • ncurses_mvinch — Move position and get attributed character at new position
    • ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long
    • ncurses_mvwaddstr — Add string at new position in window
    • ncurses_napms — Sleep
    • ncurses_new_panel — Create a new panel and associate it with window
    • ncurses_newpad — Creates a new pad (window)
    • ncurses_newwin — Create a new window
    • ncurses_nl — Translate newline and carriage return / line feed
    • ncurses_nocbreak — Switch terminal to cooked mode
    • ncurses_noecho — Switch off keyboard input echo
    • ncurses_nonl — Do not translate newline and carriage return / line feed
    • ncurses_noqiflush — Do not flush on signal characters
    • ncurses_noraw — Switch terminal out of raw mode
    • ncurses_pair_content — Retrieves foreground and background colors of a color pair
    • ncurses_panel_above — Returns the panel above panel
    • ncurses_panel_below — Returns the panel below panel
    • ncurses_panel_window — Returns the window associated with panel
    • ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen
    • ncurses_prefresh — Copies a region from a pad into the virtual screen
    • ncurses_putp — Apply padding information to the string and output it
    • ncurses_qiflush — Flush on signal characters
    • ncurses_raw — Switch terminal into raw mode
    • ncurses_refresh — Refresh screen
    • ncurses_replace_panel — Replaces the window associated with panel
    • ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode
    • ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode
    • ncurses_resetty — Restores saved terminal state
    • ncurses_savetty — Saves terminal state
    • ncurses_scr_dump — Dump screen content to file
    • ncurses_scr_init — Initialize screen from file dump
    • ncurses_scr_restore — Restore screen from file dump
    • ncurses_scr_set — Inherit screen from file dump
    • ncurses_scrl — Scroll window content up or down without changing current position
    • ncurses_show_panel — Places an invisible panel on top of the stack, making it visible
    • ncurses_slk_attr — Returns current soft label key attribute
    • ncurses_slk_attroff — Turn off the given attributes for soft function-key labels
    • ncurses_slk_attron — Turn on the given attributes for soft function-key labels
    • ncurses_slk_attrset — Set given attributes for soft function-key labels
    • ncurses_slk_clear — Clears soft labels from screen
    • ncurses_slk_color — Sets color for soft label keys
    • ncurses_slk_init — Initializes soft label key functions
    • ncurses_slk_noutrefresh — Copies soft label keys to virtual screen
    • ncurses_slk_refresh — Copies soft label keys to screen
    • ncurses_slk_restore — Restores soft label keys
    • ncurses_slk_set — Sets function key labels
    • ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed
    • ncurses_standend — Stop using 'standout' attribute
    • ncurses_standout — Start using 'standout' attribute
    • ncurses_start_color — Initializes color functionality
    • ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal
    • ncurses_termname — Returns terminals (short)-name
    • ncurses_timeout — Set timeout for special key sequences
    • ncurses_top_panel — Moves a visible panel to the top of the stack
    • ncurses_typeahead — Specify different filedescriptor for typeahead checking
    • ncurses_ungetch — Put a character back into the input stream
    • ncurses_ungetmouse — Pushes mouse event to queue
    • ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack
    • ncurses_use_default_colors — Assign terminal default colors to color id -1
    • ncurses_use_env — Control use of environment information about terminal size
    • ncurses_use_extended_names — Control use of extended names in terminfo descriptions
    • ncurses_vidattr — Display the string on the terminal in the video attribute mode
    • ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long
    • ncurses_waddch — Adds character at current position in a window and advance cursor
    • ncurses_waddstr — Outputs text at current postion in window
    • ncurses_wattroff — Turns off attributes for a window
    • ncurses_wattron — Turns on attributes for a window
    • ncurses_wattrset — Set the attributes for a window
    • ncurses_wborder — Draws a border around the window using attributed characters
    • ncurses_wclear — Clears window
    • ncurses_wcolor_set — Sets windows color pairings
    • ncurses_werase — Erase window contents
    • ncurses_wgetch — Reads a character from keyboard (window)
    • ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long
    • ncurses_wmouse_trafo — Transforms window/stdscr coordinates
    • ncurses_wmove — Moves windows output position
    • ncurses_wnoutrefresh — Copies window to virtual screen
    • ncurses_wrefresh — Refresh window on terminal screen
    • ncurses_wstandend — End standout mode for a window
    • ncurses_wstandout — Enter standout mode for a window
    • ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long
Rozszerzenia wiersza poleceń
Wstęp
Rozszerzenia wiersza poleceń


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

Ncurses
Instalacja/Konfiguracja
Ncurses


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Ncurses


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/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines window, panel and pad resources.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

Spis treści

  • Error codes
  • Colors
  • Keys
  • Mouse

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.

Typy zasobów
Error codes
Ncurses


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.

Stałe predefiniowane
Colors
Stałe predefiniowane


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
Error codes
Keys
Stałe predefiniowane


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
Colors
Mouse
Stałe predefiniowane


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
Keys
Ncurses Funkcje
Stałe predefiniowane


Ncurses Funkcje

Spis treści

  • ncurses_addch — Add character at current position and advance cursor
  • ncurses_addchnstr — Add attributed string with specified length at current position
  • ncurses_addchstr — Add attributed string at current position
  • ncurses_addnstr — Add string with specified length at current position
  • ncurses_addstr — Output text at current position
  • ncurses_assume_default_colors — Define default colors for color 0
  • ncurses_attroff — Turn off the given attributes
  • ncurses_attron — Turn on the given attributes
  • ncurses_attrset — Set given attributes
  • ncurses_baudrate — Returns baudrate of terminal
  • ncurses_beep — Let the terminal beep
  • ncurses_bkgd — Set background property for terminal screen
  • ncurses_bkgdset — Control screen background
  • ncurses_border — Draw a border around the screen using attributed characters
  • ncurses_bottom_panel — Moves a visible panel to the bottom of the stack
  • ncurses_can_change_color — Checks if terminal color definitions can be changed
  • ncurses_cbreak — Switch of input buffering
  • ncurses_clear — Clear screen
  • ncurses_clrtobot — Clear screen from current position to bottom
  • ncurses_clrtoeol — Clear screen from current position to end of line
  • ncurses_color_content — Retrieves RGB components of a color
  • ncurses_color_set — Set active foreground and background colors
  • ncurses_curs_set — Set cursor state
  • ncurses_def_prog_mode — Saves terminals (program) mode
  • ncurses_def_shell_mode — Saves terminals (shell) mode
  • ncurses_define_key — Define a keycode
  • ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)
  • ncurses_delay_output — Delay output on terminal using padding characters
  • ncurses_delch — Delete character at current position, move rest of line left
  • ncurses_deleteln — Delete line at current position, move rest of screen up
  • ncurses_delwin — Delete a ncurses window
  • ncurses_doupdate — Write all prepared refreshes to terminal
  • ncurses_echo — Activate keyboard input echo
  • ncurses_echochar — Single character output including refresh
  • ncurses_end — Stop using ncurses, clean up the screen
  • ncurses_erase — Erase terminal screen
  • ncurses_erasechar — Returns current erase character
  • ncurses_filter — Set LINES for iniscr() and newterm() to 1
  • ncurses_flash — Flash terminal screen (visual bell)
  • ncurses_flushinp — Flush keyboard input buffer
  • ncurses_getch — Read a character from keyboard
  • ncurses_getmaxyx — Returns the size of a window
  • ncurses_getmouse — Reads mouse event
  • ncurses_getyx — Returns the current cursor position for a window
  • ncurses_halfdelay — Put terminal into halfdelay mode
  • ncurses_has_colors — Checks if terminal has color capabilities
  • ncurses_has_ic — Check for insert- and delete-capabilities
  • ncurses_has_il — Check for line insert- and delete-capabilities
  • ncurses_has_key — Check for presence of a function key on terminal keyboard
  • ncurses_hide_panel — Remove panel from the stack, making it invisible
  • ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long
  • ncurses_inch — Get character and attribute at current position
  • ncurses_init_color — Define a terminal color
  • ncurses_init_pair — Define a color pair
  • ncurses_init — Initialize ncurses
  • ncurses_insch — Insert character moving rest of line including character at current position
  • ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)
  • ncurses_insertln — Insert a line, move rest of screen down
  • ncurses_insstr — Insert string at current position, moving rest of line right
  • ncurses_instr — Reads string from terminal screen
  • ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed
  • ncurses_keyok — Enable or disable a keycode
  • ncurses_keypad — Turns keypad on or off
  • ncurses_killchar — Returns current line kill character
  • ncurses_longname — Returns terminals description
  • ncurses_meta — Enables/Disable 8-bit meta key information
  • ncurses_mouse_trafo — Transforms coordinates
  • ncurses_mouseinterval — Set timeout for mouse button clicks
  • ncurses_mousemask — Sets mouse options
  • ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]
  • ncurses_move — Move output position
  • ncurses_mvaddch — Move current position and add character
  • ncurses_mvaddchnstr — Move position and add attributed string with specified length
  • ncurses_mvaddchstr — Move position and add attributed string
  • ncurses_mvaddnstr — Move position and add string with specified length
  • ncurses_mvaddstr — Move position and add string
  • ncurses_mvcur — Move cursor immediately
  • ncurses_mvdelch — Move position and delete character, shift rest of line left
  • ncurses_mvgetch — Move position and get character at new position
  • ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long
  • ncurses_mvinch — Move position and get attributed character at new position
  • ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long
  • ncurses_mvwaddstr — Add string at new position in window
  • ncurses_napms — Sleep
  • ncurses_new_panel — Create a new panel and associate it with window
  • ncurses_newpad — Creates a new pad (window)
  • ncurses_newwin — Create a new window
  • ncurses_nl — Translate newline and carriage return / line feed
  • ncurses_nocbreak — Switch terminal to cooked mode
  • ncurses_noecho — Switch off keyboard input echo
  • ncurses_nonl — Do not translate newline and carriage return / line feed
  • ncurses_noqiflush — Do not flush on signal characters
  • ncurses_noraw — Switch terminal out of raw mode
  • ncurses_pair_content — Retrieves foreground and background colors of a color pair
  • ncurses_panel_above — Returns the panel above panel
  • ncurses_panel_below — Returns the panel below panel
  • ncurses_panel_window — Returns the window associated with panel
  • ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen
  • ncurses_prefresh — Copies a region from a pad into the virtual screen
  • ncurses_putp — Apply padding information to the string and output it
  • ncurses_qiflush — Flush on signal characters
  • ncurses_raw — Switch terminal into raw mode
  • ncurses_refresh — Refresh screen
  • ncurses_replace_panel — Replaces the window associated with panel
  • ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode
  • ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode
  • ncurses_resetty — Restores saved terminal state
  • ncurses_savetty — Saves terminal state
  • ncurses_scr_dump — Dump screen content to file
  • ncurses_scr_init — Initialize screen from file dump
  • ncurses_scr_restore — Restore screen from file dump
  • ncurses_scr_set — Inherit screen from file dump
  • ncurses_scrl — Scroll window content up or down without changing current position
  • ncurses_show_panel — Places an invisible panel on top of the stack, making it visible
  • ncurses_slk_attr — Returns current soft label key attribute
  • ncurses_slk_attroff — Turn off the given attributes for soft function-key labels
  • ncurses_slk_attron — Turn on the given attributes for soft function-key labels
  • ncurses_slk_attrset — Set given attributes for soft function-key labels
  • ncurses_slk_clear — Clears soft labels from screen
  • ncurses_slk_color — Sets color for soft label keys
  • ncurses_slk_init — Initializes soft label key functions
  • ncurses_slk_noutrefresh — Copies soft label keys to virtual screen
  • ncurses_slk_refresh — Copies soft label keys to screen
  • ncurses_slk_restore — Restores soft label keys
  • ncurses_slk_set — Sets function key labels
  • ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed
  • ncurses_standend — Stop using 'standout' attribute
  • ncurses_standout — Start using 'standout' attribute
  • ncurses_start_color — Initializes color functionality
  • ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal
  • ncurses_termname — Returns terminals (short)-name
  • ncurses_timeout — Set timeout for special key sequences
  • ncurses_top_panel — Moves a visible panel to the top of the stack
  • ncurses_typeahead — Specify different filedescriptor for typeahead checking
  • ncurses_ungetch — Put a character back into the input stream
  • ncurses_ungetmouse — Pushes mouse event to queue
  • ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack
  • ncurses_use_default_colors — Assign terminal default colors to color id -1
  • ncurses_use_env — Control use of environment information about terminal size
  • ncurses_use_extended_names — Control use of extended names in terminfo descriptions
  • ncurses_vidattr — Display the string on the terminal in the video attribute mode
  • ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long
  • ncurses_waddch — Adds character at current position in a window and advance cursor
  • ncurses_waddstr — Outputs text at current postion in window
  • ncurses_wattroff — Turns off attributes for a window
  • ncurses_wattron — Turns on attributes for a window
  • ncurses_wattrset — Set the attributes for a window
  • ncurses_wborder — Draws a border around the window using attributed characters
  • ncurses_wclear — Clears window
  • ncurses_wcolor_set — Sets windows color pairings
  • ncurses_werase — Erase window contents
  • ncurses_wgetch — Reads a character from keyboard (window)
  • ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long
  • ncurses_wmouse_trafo — Transforms window/stdscr coordinates
  • ncurses_wmove — Moves windows output position
  • ncurses_wnoutrefresh — Copies window to virtual screen
  • ncurses_wrefresh — Refresh window on terminal screen
  • ncurses_wstandend — End standout mode for a window
  • ncurses_wstandout — Enter standout mode for a window
  • ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long
Mouse
ncurses_addch
Ncurses


Add character at current position and advance cursor

Ncurses Funkcje
ncurses_addchnstr
Ncurses Funkcje
PHP Manual

ncurses_addch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addch — Add 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 Funkcje
ncurses_addchnstr
Ncurses Funkcje


Add attributed string with specified length at current position

ncurses_addch
ncurses_addchstr
Ncurses Funkcje
PHP Manual

ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchnstr — Add 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_addch
ncurses_addchstr
Ncurses Funkcje


Add attributed string at current position

ncurses_addchnstr
ncurses_addnstr
Ncurses Funkcje
PHP Manual

ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchstr — Add 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_addchnstr
ncurses_addnstr
Ncurses Funkcje


Add string with specified length at current position

ncurses_addchstr
ncurses_addstr
Ncurses Funkcje
PHP Manual

ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addnstr — Add 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_addchstr
ncurses_addstr
Ncurses Funkcje


Output text at current position

ncurses_addnstr
ncurses_assume_default_colors
Ncurses Funkcje
PHP Manual

ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addstr — Output 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_addnstr
ncurses_assume_default_colors
Ncurses Funkcje


Define default colors for color 0

ncurses_addstr
ncurses_attroff
Ncurses Funkcje
PHP Manual

ncurses_assume_default_colors

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_assume_default_colors — Define 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_addstr
ncurses_attroff
Ncurses Funkcje


Turn off the given attributes

ncurses_assume_default_colors
ncurses_attron
Ncurses Funkcje
PHP Manual

ncurses_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attroff — Turn 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_assume_default_colors
ncurses_attron
Ncurses Funkcje


Turn on the given attributes

ncurses_attroff
ncurses_attrset
Ncurses Funkcje
PHP Manual

ncurses_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attron — Turn 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_attroff
ncurses_attrset
Ncurses Funkcje


Set given attributes

ncurses_attron
ncurses_baudrate
Ncurses Funkcje
PHP Manual

ncurses_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attrset — Set 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_attron
ncurses_baudrate
Ncurses Funkcje


Returns baudrate of terminal

ncurses_attrset
ncurses_beep
Ncurses Funkcje
PHP Manual

ncurses_baudrate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_baudrate — Returns 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_attrset
ncurses_beep
Ncurses Funkcje


Let the terminal beep

ncurses_baudrate
ncurses_bkgd
Ncurses Funkcje
PHP Manual

ncurses_beep

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_beep — Let 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_flash() - Flash terminal screen (visual bell)

ncurses_baudrate
ncurses_bkgd
Ncurses Funkcje


Set background property for terminal screen

ncurses_beep
ncurses_bkgdset
Ncurses Funkcje
PHP Manual

ncurses_bkgd

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgd — Set 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_beep
ncurses_bkgdset
Ncurses Funkcje


Control screen background

ncurses_bkgd
ncurses_border
Ncurses Funkcje
PHP Manual

ncurses_bkgdset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdset — Control 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_bkgd
ncurses_border
Ncurses Funkcje


Draw a border around the screen using attributed characters

ncurses_bkgdset
ncurses_bottom_panel
Ncurses Funkcje
PHP Manual

ncurses_border

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_border — Draw 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_wborder() - Draws a border around the window using attributed characters

ncurses_bkgdset
ncurses_bottom_panel
Ncurses Funkcje


Moves a visible panel to the bottom of the stack

ncurses_border
ncurses_can_change_color
Ncurses Funkcje
PHP Manual

ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bottom_panel — Moves 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_border
ncurses_can_change_color
Ncurses Funkcje


Checks if terminal color definitions can be changed

ncurses_bottom_panel
ncurses_cbreak
Ncurses Funkcje
PHP Manual

ncurses_can_change_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_can_change_color — Checks 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_has_colors() - Checks if terminal has color capabilities
  • ncurses_init_color() - Define a terminal color
  • ncurses_start_color() - Initializes color functionality

ncurses_bottom_panel
ncurses_cbreak
Ncurses Funkcje


Switch of input buffering

ncurses_can_change_color
ncurses_clear
Ncurses Funkcje
PHP Manual

ncurses_cbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_cbreak — Switch 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_nocbreak() - Switch terminal to cooked mode

ncurses_can_change_color
ncurses_clear
Ncurses Funkcje


Clear screen

ncurses_cbreak
ncurses_clrtobot
Ncurses Funkcje
PHP Manual

ncurses_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clear — Clear 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_erase() - Erase terminal screen

ncurses_cbreak
ncurses_clrtobot
Ncurses Funkcje


Clear screen from current position to bottom

ncurses_clear
ncurses_clrtoeol
Ncurses Funkcje
PHP Manual

ncurses_clrtobot

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtobot — Clear 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_clear() - Clear screen
  • ncurses_clrtoeol() - Clear screen from current position to end of line

ncurses_clear
ncurses_clrtoeol
Ncurses Funkcje


Clear screen from current position to end of line

ncurses_clrtobot
ncurses_color_content
Ncurses Funkcje
PHP Manual

ncurses_clrtoeol

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtoeol — Clear 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_clear() - Clear screen
  • ncurses_clrtobot() - Clear screen from current position to bottom

ncurses_clrtobot
ncurses_color_content
Ncurses Funkcje


Retrieves RGB components of a color

ncurses_clrtoeol
ncurses_color_set
Ncurses Funkcje
PHP Manual

ncurses_color_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_content — Retrieves 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_init_color() - Define a terminal color
  • ncurses_start_color() - Initializes color functionality

ncurses_clrtoeol
ncurses_color_set
Ncurses Funkcje


Set active foreground and background colors

ncurses_color_content
ncurses_curs_set
Ncurses Funkcje
PHP Manual

ncurses_color_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_set — Set 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(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

Zobacz też:

  • ncurses_init_pair() - Define a color pair
  • ncurses_start_color() - Initializes color functionality

ncurses_color_content
ncurses_curs_set
Ncurses Funkcje


Set cursor state

ncurses_color_set
ncurses_def_prog_mode
Ncurses Funkcje
PHP Manual

ncurses_curs_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_curs_set — Set 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_color_set
ncurses_def_prog_mode
Ncurses Funkcje


Saves terminals (program) mode

ncurses_curs_set
ncurses_def_shell_mode
Ncurses Funkcje
PHP Manual

ncurses_def_prog_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_def_prog_mode — Saves 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_reset_prog_mode() - Resets the prog mode saved by def_prog_mode

ncurses_curs_set
ncurses_def_shell_mode
Ncurses Funkcje


Saves terminals (shell) mode

ncurses_def_prog_mode
ncurses_define_key
Ncurses Funkcje
PHP Manual

ncurses_def_shell_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_def_shell_mode — Saves 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_reset_shell_mode() - Resets the shell mode saved by def_shell_mode

ncurses_def_prog_mode
ncurses_define_key
Ncurses Funkcje


Define a keycode

ncurses_def_shell_mode
ncurses_del_panel
Ncurses Funkcje
PHP Manual

ncurses_define_key

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_define_key — Define 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_def_shell_mode
ncurses_del_panel
Ncurses Funkcje


Remove panel from the stack and delete it (but not the associated window)

ncurses_define_key
ncurses_delay_output
Ncurses Funkcje
PHP Manual

ncurses_del_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_del_panel — Remove 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_define_key
ncurses_delay_output
Ncurses Funkcje


Delay output on terminal using padding characters

ncurses_del_panel
ncurses_delch
Ncurses Funkcje
PHP Manual

ncurses_delay_output

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delay_output — Delay 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_del_panel
ncurses_delch
Ncurses Funkcje


Delete character at current position, move rest of line left

ncurses_delay_output
ncurses_deleteln
Ncurses Funkcje
PHP Manual

ncurses_delch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delch — Delete 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() - Delete line at current position, move rest of screen up

ncurses_delay_output
ncurses_deleteln
Ncurses Funkcje


Delete line at current position, move rest of screen up

ncurses_delch
ncurses_delwin
Ncurses Funkcje
PHP Manual

ncurses_deleteln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_deleteln — Delete 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_delch
ncurses_delwin
Ncurses Funkcje


Delete a ncurses window

ncurses_deleteln
ncurses_doupdate
Ncurses Funkcje
PHP Manual

ncurses_delwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delwin — Delete 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_deleteln
ncurses_doupdate
Ncurses Funkcje


Write all prepared refreshes to terminal

ncurses_delwin
ncurses_echo
Ncurses Funkcje
PHP Manual

ncurses_doupdate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_doupdate — Write 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_delwin
ncurses_echo
Ncurses Funkcje


Activate keyboard input echo

ncurses_doupdate
ncurses_echochar
Ncurses Funkcje
PHP Manual

ncurses_echo

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echo — Activate 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_noecho() - Switch off keyboard input echo to disable echo mode

ncurses_doupdate
ncurses_echochar
Ncurses Funkcje


Single character output including refresh

ncurses_echo
ncurses_end
Ncurses Funkcje
PHP Manual

ncurses_echochar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echochar — Single 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_echo
ncurses_end
Ncurses Funkcje


Stop using ncurses, clean up the screen

ncurses_echochar
ncurses_erase
Ncurses Funkcje
PHP Manual

ncurses_end

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_end — Stop 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_echochar
ncurses_erase
Ncurses Funkcje


Erase terminal screen

ncurses_end
ncurses_erasechar
Ncurses Funkcje
PHP Manual

ncurses_erase

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erase — Erase 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_bkgd() - Set background property for terminal screen
  • ncurses_clear() - Clear screen

ncurses_end
ncurses_erasechar
Ncurses Funkcje


Returns current erase character

ncurses_erase
ncurses_filter
Ncurses Funkcje
PHP Manual

ncurses_erasechar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erasechar — Returns 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_killchar() - Returns current line kill character

ncurses_erase
ncurses_filter
Ncurses Funkcje


Set LINES for iniscr() and newterm() to 1

ncurses_erasechar
ncurses_flash
Ncurses Funkcje
PHP Manual

ncurses_filter

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_filter — Set 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_erasechar
ncurses_flash
Ncurses Funkcje


Flash terminal screen (visual bell)

ncurses_filter
ncurses_flushinp
Ncurses Funkcje
PHP Manual

ncurses_flash

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flash — Flash 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_beep() - Let the terminal beep

ncurses_filter
ncurses_flushinp
Ncurses Funkcje


Flush keyboard input buffer

ncurses_flash
ncurses_getch
Ncurses Funkcje
PHP Manual

ncurses_flushinp

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flushinp — Flush 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_flash
ncurses_getch
Ncurses Funkcje


Read a character from keyboard

ncurses_flushinp
ncurses_getmaxyx
Ncurses Funkcje
PHP Manual

ncurses_getch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getch — Read 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_flushinp
ncurses_getmaxyx
Ncurses Funkcje


Returns the size of a window

ncurses_getch
ncurses_getmouse
Ncurses Funkcje
PHP Manual

ncurses_getmaxyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmaxyx — Returns 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_getch
ncurses_getmouse
Ncurses Funkcje


Reads mouse event

ncurses_getmaxyx
ncurses_getyx
Ncurses Funkcje
PHP Manual

ncurses_getmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmouse — Reads 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_ungetmouse() - Pushes mouse event to queue

ncurses_getmaxyx
ncurses_getyx
Ncurses Funkcje


Returns the current cursor position for a window

ncurses_getmouse
ncurses_halfdelay
Ncurses Funkcje
PHP Manual

ncurses_getyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getyx — Returns 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_getmouse
ncurses_halfdelay
Ncurses Funkcje


Put terminal into halfdelay mode

ncurses_getyx
ncurses_has_colors
Ncurses Funkcje
PHP Manual

ncurses_halfdelay

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_halfdelay — Put 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_getyx
ncurses_has_colors
Ncurses Funkcje


Checks if terminal has color capabilities

ncurses_halfdelay
ncurses_has_ic
Ncurses Funkcje
PHP Manual

ncurses_has_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_colors — Checks 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(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

Zobacz też:

  • ncurses_can_change_color() - Checks if terminal color definitions can be changed
  • ncurses_start_color() - Initializes color functionality

ncurses_halfdelay
ncurses_has_ic
Ncurses Funkcje


Check for insert- and delete-capabilities

ncurses_has_colors
ncurses_has_il
Ncurses Funkcje
PHP Manual

ncurses_has_ic

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_ic — Check 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() - Check for line insert- and delete-capabilities

ncurses_has_colors
ncurses_has_il
Ncurses Funkcje


Check for line insert- and delete-capabilities

ncurses_has_ic
ncurses_has_key
Ncurses Funkcje
PHP Manual

ncurses_has_il

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_il — Check 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_ic() - Check for insert- and delete-capabilities

ncurses_has_ic
ncurses_has_key
Ncurses Funkcje


Check for presence of a function key on terminal keyboard

ncurses_has_il
ncurses_hide_panel
Ncurses Funkcje
PHP Manual

ncurses_has_key

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_key — Check 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_has_il
ncurses_hide_panel
Ncurses Funkcje


Remove panel from the stack, making it invisible

ncurses_has_key
ncurses_hline
Ncurses Funkcje
PHP Manual

ncurses_hide_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hide_panel — Remove 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_has_key
ncurses_hline
Ncurses Funkcje


Draw a horizontal line at current position using an attributed character and max. n characters long

ncurses_hide_panel
ncurses_inch
Ncurses Funkcje
PHP Manual

ncurses_hline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hline — Draw 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_hide_panel
ncurses_inch
Ncurses Funkcje


Get character and attribute at current position

ncurses_hline
ncurses_init_color
Ncurses Funkcje
PHP Manual

ncurses_inch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_inch — Get 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_hline
ncurses_init_color
Ncurses Funkcje


Define a terminal color

ncurses_inch
ncurses_init_pair
Ncurses Funkcje
PHP Manual

ncurses_init_color

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_color — Define 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_color_content() - Retrieves RGB components of a color
  • ncurses_start_color() - Initializes color functionality

ncurses_inch
ncurses_init_pair
Ncurses Funkcje


Define a color pair

ncurses_init_color
ncurses_init
Ncurses Funkcje
PHP Manual

ncurses_init_pair

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_pair — Define 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(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

Zobacz też:

  • ncurses_pair_content() - Retrieves foreground and background colors of a color pair
  • ncurses_start_color() - Initializes color functionality

ncurses_init_color
ncurses_init
Ncurses Funkcje


Initialize ncurses

ncurses_init_pair
ncurses_insch
Ncurses Funkcje
PHP Manual

ncurses_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init — Initialize 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_end() - Stop using ncurses, clean up the screen

ncurses_init_pair
ncurses_insch
Ncurses Funkcje


Insert character moving rest of line including character at current position

ncurses_init
ncurses_insdelln
Ncurses Funkcje
PHP Manual

ncurses_insch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insch — Insert 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_init
ncurses_insdelln
Ncurses Funkcje


Insert lines before current line scrolling down (negative numbers delete and scroll up)

ncurses_insch
ncurses_insertln
Ncurses Funkcje
PHP Manual

ncurses_insdelln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insdelln — Insert 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_insch
ncurses_insertln
Ncurses Funkcje


Insert a line, move rest of screen down

ncurses_insdelln
ncurses_insstr
Ncurses Funkcje
PHP Manual

ncurses_insertln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insertln — Insert 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_insdelln
ncurses_insstr
Ncurses Funkcje


Insert string at current position, moving rest of line right

ncurses_insertln
ncurses_instr
Ncurses Funkcje
PHP Manual

ncurses_insstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insstr — Insert 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_insertln
ncurses_instr
Ncurses Funkcje


Reads string from terminal screen

ncurses_insstr
ncurses_isendwin
Ncurses Funkcje
PHP Manual

ncurses_instr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_instr — Reads 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_insstr
ncurses_isendwin
Ncurses Funkcje


Ncurses is in endwin mode, normal screen output may be performed

ncurses_instr
ncurses_keyok
Ncurses Funkcje
PHP Manual

ncurses_isendwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_isendwin — Ncurses 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_end() - Stop using ncurses, clean up the screen
  • ncurses_wrefresh() - Refresh window on terminal screen

ncurses_instr
ncurses_keyok
Ncurses Funkcje


Enable or disable a keycode

ncurses_isendwin
ncurses_keypad
Ncurses Funkcje
PHP Manual

ncurses_keyok

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keyok — Enable 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_isendwin
ncurses_keypad
Ncurses Funkcje


Turns keypad on or off

ncurses_keyok
ncurses_killchar
Ncurses Funkcje
PHP Manual

ncurses_keypad

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keypad — Turns 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_keyok
ncurses_killchar
Ncurses Funkcje


Returns current line kill character

ncurses_keypad
ncurses_longname
Ncurses Funkcje
PHP Manual

ncurses_killchar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_killchar — Returns 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_erasechar() - Returns current erase character

ncurses_keypad
ncurses_longname
Ncurses Funkcje


Returns terminals description

ncurses_killchar
ncurses_meta
Ncurses Funkcje
PHP Manual

ncurses_longname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_longname — Returns 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_termname() - Returns terminals (short)-name

ncurses_killchar
ncurses_meta
Ncurses Funkcje


Enables/Disable 8-bit meta key information

ncurses_longname
ncurses_mouse_trafo
Ncurses Funkcje
PHP Manual

ncurses_meta

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_meta — Enables/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_longname
ncurses_mouse_trafo
Ncurses Funkcje


Transforms coordinates

ncurses_meta
ncurses_mouseinterval
Ncurses Funkcje
PHP Manual

ncurses_mouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouse_trafo — Transforms 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_meta
ncurses_mouseinterval
Ncurses Funkcje


Set timeout for mouse button clicks

ncurses_mouse_trafo
ncurses_mousemask
Ncurses Funkcje
PHP Manual

ncurses_mouseinterval

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouseinterval — Set 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_mouse_trafo
ncurses_mousemask
Ncurses Funkcje


Sets mouse options

ncurses_mouseinterval
ncurses_move_panel
Ncurses Funkcje
PHP Manual

ncurses_mousemask

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mousemask — Sets 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_getch() - Read a character from keyboard
  • ncurses_getmouse() - Reads mouse event
  • ncurses_ungetmouse() - Pushes mouse event to queue

ncurses_mouseinterval
ncurses_move_panel
Ncurses Funkcje


Moves a panel so that its upper-left corner is at [startx, starty]

ncurses_mousemask
ncurses_move
Ncurses Funkcje
PHP Manual

ncurses_move_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move_panel — Moves 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_mousemask
ncurses_move
Ncurses Funkcje


Move output position

ncurses_move_panel
ncurses_mvaddch
Ncurses Funkcje
PHP Manual

ncurses_move

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move — Move 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_move_panel
ncurses_mvaddch
Ncurses Funkcje


Move current position and add character

ncurses_move
ncurses_mvaddchnstr
Ncurses Funkcje
PHP Manual

ncurses_mvaddch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddch — Move 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_move
ncurses_mvaddchnstr
Ncurses Funkcje


Move position and add attributed string with specified length

ncurses_mvaddch
ncurses_mvaddchstr
Ncurses Funkcje
PHP Manual

ncurses_mvaddchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchnstr — Move 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_mvaddch
ncurses_mvaddchstr
Ncurses Funkcje


Move position and add attributed string

ncurses_mvaddchnstr
ncurses_mvaddnstr
Ncurses Funkcje
PHP Manual

ncurses_mvaddchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchstr — Move 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_mvaddchnstr
ncurses_mvaddnstr
Ncurses Funkcje


Move position and add string with specified length

ncurses_mvaddchstr
ncurses_mvaddstr
Ncurses Funkcje
PHP Manual

ncurses_mvaddnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddnstr — Move 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_mvaddchstr
ncurses_mvaddstr
Ncurses Funkcje


Move position and add string

ncurses_mvaddnstr
ncurses_mvcur
Ncurses Funkcje
PHP Manual

ncurses_mvaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddstr — Move 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_mvaddnstr
ncurses_mvcur
Ncurses Funkcje


Move cursor immediately

ncurses_mvaddstr
ncurses_mvdelch
Ncurses Funkcje
PHP Manual

ncurses_mvcur

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvcur — Move 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_mvaddstr
ncurses_mvdelch
Ncurses Funkcje


Move position and delete character, shift rest of line left

ncurses_mvcur
ncurses_mvgetch
Ncurses Funkcje
PHP Manual

ncurses_mvdelch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvdelch — Move 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_mvcur
ncurses_mvgetch
Ncurses Funkcje


Move position and get character at new position

ncurses_mvdelch
ncurses_mvhline
Ncurses Funkcje
PHP Manual

ncurses_mvgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvgetch — Move 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_mvdelch
ncurses_mvhline
Ncurses Funkcje


Set new position and draw a horizontal line using an attributed character and max. n characters long

ncurses_mvgetch
ncurses_mvinch
Ncurses Funkcje
PHP Manual

ncurses_mvhline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvhline — Set 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_mvgetch
ncurses_mvinch
Ncurses Funkcje


Move position and get attributed character at new position

ncurses_mvhline
ncurses_mvvline
Ncurses Funkcje
PHP Manual

ncurses_mvinch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvinch — Move 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_mvhline
ncurses_mvvline
Ncurses Funkcje


Set new position and draw a vertical line using an attributed character and max. n characters long

ncurses_mvinch
ncurses_mvwaddstr
Ncurses Funkcje
PHP Manual

ncurses_mvvline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvvline — Set 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_mvinch
ncurses_mvwaddstr
Ncurses Funkcje


Add string at new position in window

ncurses_mvvline
ncurses_napms
Ncurses Funkcje
PHP Manual

ncurses_mvwaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvwaddstr — Add 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_mvvline
ncurses_napms
Ncurses Funkcje


Sleep

ncurses_mvwaddstr
ncurses_new_panel
Ncurses Funkcje
PHP Manual

ncurses_napms

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_napms — Sleep

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_mvwaddstr
ncurses_new_panel
Ncurses Funkcje


Create a new panel and associate it with window

ncurses_napms
ncurses_newpad
Ncurses Funkcje
PHP Manual

ncurses_new_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_new_panel — Create 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_napms
ncurses_newpad
Ncurses Funkcje


Creates a new pad (window)

ncurses_new_panel
ncurses_newwin
Ncurses Funkcje
PHP Manual

ncurses_newpad

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newpad — Creates 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_new_panel
ncurses_newwin
Ncurses Funkcje


Create a new window

ncurses_newpad
ncurses_nl
Ncurses Funkcje
PHP Manual

ncurses_newwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newwin — Create 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_newpad
ncurses_nl
Ncurses Funkcje


Translate newline and carriage return / line feed

ncurses_newwin
ncurses_nocbreak
Ncurses Funkcje
PHP Manual

ncurses_nl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nl — Translate 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_newwin
ncurses_nocbreak
Ncurses Funkcje


Switch terminal to cooked mode

ncurses_nl
ncurses_noecho
Ncurses Funkcje
PHP Manual

ncurses_nocbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nocbreak — Switch 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_cbreak() - Switch of input buffering

ncurses_nl
ncurses_noecho
Ncurses Funkcje


Switch off keyboard input echo

ncurses_nocbreak
ncurses_nonl
Ncurses Funkcje
PHP Manual

ncurses_noecho

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noecho — Switch 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_echo() - Activate keyboard input echo
  • ncurses_getch() - Read a character from keyboard

ncurses_nocbreak
ncurses_nonl
Ncurses Funkcje


Do not translate newline and carriage return / line feed

ncurses_noecho
ncurses_noqiflush
Ncurses Funkcje
PHP Manual

ncurses_nonl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nonl — Do 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_noecho
ncurses_noqiflush
Ncurses Funkcje


Do not flush on signal characters

ncurses_nonl
ncurses_noraw
Ncurses Funkcje
PHP Manual

ncurses_noqiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noqiflush — Do 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_nonl
ncurses_noraw
Ncurses Funkcje


Switch terminal out of raw mode

ncurses_noqiflush
ncurses_pair_content
Ncurses Funkcje
PHP Manual

ncurses_noraw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noraw — Switch 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_raw() - Switch terminal into raw mode
  • ncurses_cbreak() - Switch of input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode

ncurses_noqiflush
ncurses_pair_content
Ncurses Funkcje


Retrieves foreground and background colors of a color pair

ncurses_noraw
ncurses_panel_above
Ncurses Funkcje
PHP Manual

ncurses_pair_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pair_content — Retrieves 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_init_pair() - Define a color pair
  • ncurses_start_color() - Initializes color functionality

ncurses_noraw
ncurses_panel_above
Ncurses Funkcje


Returns the panel above panel

ncurses_pair_content
ncurses_panel_below
Ncurses Funkcje
PHP Manual

ncurses_panel_above

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_above — Returns 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_pair_content
ncurses_panel_below
Ncurses Funkcje


Returns the panel below panel

ncurses_panel_above
ncurses_panel_window
Ncurses Funkcje
PHP Manual

ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_below — Returns 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_above
ncurses_panel_window
Ncurses Funkcje


Returns the window associated with panel

ncurses_panel_below
ncurses_pnoutrefresh
Ncurses Funkcje
PHP Manual

ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_window — Returns 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_panel_below
ncurses_pnoutrefresh
Ncurses Funkcje


Copies a region from a pad into the virtual screen

ncurses_panel_window
ncurses_prefresh
Ncurses Funkcje
PHP Manual

ncurses_pnoutrefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pnoutrefresh — Copies 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_panel_window
ncurses_prefresh
Ncurses Funkcje


Copies a region from a pad into the virtual screen

ncurses_pnoutrefresh
ncurses_putp
Ncurses Funkcje
PHP Manual

ncurses_prefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_prefresh — Copies 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_pnoutrefresh
ncurses_putp
Ncurses Funkcje


Apply padding information to the string and output it

ncurses_prefresh
ncurses_qiflush
Ncurses Funkcje
PHP Manual

ncurses_putp

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_putp — Apply 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_prefresh
ncurses_qiflush
Ncurses Funkcje


Flush on signal characters

ncurses_putp
ncurses_raw
Ncurses Funkcje
PHP Manual

ncurses_qiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_qiflush — Flush 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_putp
ncurses_raw
Ncurses Funkcje


Switch terminal into raw mode

ncurses_qiflush
ncurses_refresh
Ncurses Funkcje
PHP Manual

ncurses_raw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_raw — Switch 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_noraw() - Switch terminal out of raw mode
  • ncurses_cbreak() - Switch of input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode

ncurses_qiflush
ncurses_refresh
Ncurses Funkcje


Refresh screen

ncurses_raw
ncurses_replace_panel
Ncurses Funkcje
PHP Manual

ncurses_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_refresh — Refresh 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_raw
ncurses_replace_panel
Ncurses Funkcje


Replaces the window associated with panel

ncurses_refresh
ncurses_reset_prog_mode
Ncurses Funkcje
PHP Manual

ncurses_replace_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_replace_panel — Replaces 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_refresh
ncurses_reset_prog_mode
Ncurses Funkcje


Resets the prog mode saved by def_prog_mode

ncurses_replace_panel
ncurses_reset_shell_mode
Ncurses Funkcje
PHP Manual

ncurses_reset_prog_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_reset_prog_mode — Resets 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_replace_panel
ncurses_reset_shell_mode
Ncurses Funkcje


Resets the shell mode saved by def_shell_mode

ncurses_reset_prog_mode
ncurses_resetty
Ncurses Funkcje
PHP Manual

ncurses_reset_shell_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_reset_shell_mode — Resets 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_reset_prog_mode
ncurses_resetty
Ncurses Funkcje


Restores saved terminal state

ncurses_reset_shell_mode
ncurses_savetty
Ncurses Funkcje
PHP Manual

ncurses_resetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_resetty — Restores 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() - Saves terminal state

ncurses_reset_shell_mode
ncurses_savetty
Ncurses Funkcje


Saves terminal state

ncurses_resetty
ncurses_scr_dump
Ncurses Funkcje
PHP Manual

ncurses_savetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_savetty — Saves 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_resetty() - Restores saved terminal state

ncurses_resetty
ncurses_scr_dump
Ncurses Funkcje


Dump screen content to file

ncurses_savetty
ncurses_scr_init
Ncurses Funkcje
PHP Manual

ncurses_scr_dump

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_dump — Dump 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_savetty
ncurses_scr_init
Ncurses Funkcje


Initialize screen from file dump

ncurses_scr_dump
ncurses_scr_restore
Ncurses Funkcje
PHP Manual

ncurses_scr_init

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_init — Initialize 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_dump
ncurses_scr_restore
Ncurses Funkcje


Restore screen from file dump

ncurses_scr_init
ncurses_scr_set
Ncurses Funkcje
PHP Manual

ncurses_scr_restore

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_restore — Restore 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_init
ncurses_scr_set
Ncurses Funkcje


Inherit screen from file dump

ncurses_scr_restore
ncurses_scrl
Ncurses Funkcje
PHP Manual

ncurses_scr_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_set — Inherit 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_scr_restore
ncurses_scrl
Ncurses Funkcje


Scroll window content up or down without changing current position

ncurses_scr_set
ncurses_show_panel
Ncurses Funkcje
PHP Manual

ncurses_scrl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scrl — Scroll 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_scr_set
ncurses_show_panel
Ncurses Funkcje


Places an invisible panel on top of the stack, making it visible

ncurses_scrl
ncurses_slk_attr
Ncurses Funkcje
PHP Manual

ncurses_show_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_show_panel — Places 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_scrl
ncurses_slk_attr
Ncurses Funkcje


Returns current soft label key attribute

ncurses_show_panel
ncurses_slk_attroff
Ncurses Funkcje
PHP Manual

ncurses_slk_attr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attr — Returns 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_show_panel
ncurses_slk_attroff
Ncurses Funkcje


Turn off the given attributes for soft function-key labels

ncurses_slk_attr
ncurses_slk_attron
Ncurses Funkcje
PHP Manual

ncurses_slk_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attroff — Turn 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_attr
ncurses_slk_attron
Ncurses Funkcje


Turn on the given attributes for soft function-key labels

ncurses_slk_attroff
ncurses_slk_attrset
Ncurses Funkcje
PHP Manual

ncurses_slk_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attron — Turn 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_attroff
ncurses_slk_attrset
Ncurses Funkcje


Set given attributes for soft function-key labels

ncurses_slk_attron
ncurses_slk_clear
Ncurses Funkcje
PHP Manual

ncurses_slk_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attrset — Set 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_attron
ncurses_slk_clear
Ncurses Funkcje


Clears soft labels from screen

ncurses_slk_attrset
ncurses_slk_color
Ncurses Funkcje
PHP Manual

ncurses_slk_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_clear — Clears 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_attrset
ncurses_slk_color
Ncurses Funkcje


Sets color for soft label keys

ncurses_slk_clear
ncurses_slk_init
Ncurses Funkcje
PHP Manual

ncurses_slk_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_color — Sets 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_clear
ncurses_slk_init
Ncurses Funkcje


Initializes soft label key functions

ncurses_slk_color
ncurses_slk_noutrefresh
Ncurses Funkcje
PHP Manual

ncurses_slk_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_init — Initializes 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_color
ncurses_slk_noutrefresh
Ncurses Funkcje


Copies soft label keys to virtual screen

ncurses_slk_init
ncurses_slk_refresh
Ncurses Funkcje
PHP Manual

ncurses_slk_noutrefresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_noutrefresh — Copies 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_init
ncurses_slk_refresh
Ncurses Funkcje


Copies soft label keys to screen

ncurses_slk_noutrefresh
ncurses_slk_restore
Ncurses Funkcje
PHP Manual

ncurses_slk_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_refresh — Copies 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_noutrefresh
ncurses_slk_restore
Ncurses Funkcje


Restores soft label keys

ncurses_slk_refresh
ncurses_slk_set
Ncurses Funkcje
PHP Manual

ncurses_slk_restore

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_restore — Restores 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_refresh
ncurses_slk_set
Ncurses Funkcje


Sets function key labels

ncurses_slk_restore
ncurses_slk_touch
Ncurses Funkcje
PHP Manual

ncurses_slk_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_set — Sets 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_restore
ncurses_slk_touch
Ncurses Funkcje


Forces output when ncurses_slk_noutrefresh is performed

ncurses_slk_set
ncurses_standend
Ncurses Funkcje
PHP Manual

ncurses_slk_touch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_touch — Forces 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_slk_set
ncurses_standend
Ncurses Funkcje


Stop using 'standout' attribute

ncurses_slk_touch
ncurses_standout
Ncurses Funkcje
PHP Manual

ncurses_standend

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standend — Stop 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_slk_touch
ncurses_standout
Ncurses Funkcje


Start using 'standout' attribute

ncurses_standend
ncurses_start_color
Ncurses Funkcje
PHP Manual

ncurses_standout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standout — Start 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_standend
ncurses_start_color
Ncurses Funkcje


Initializes color functionality

ncurses_standout
ncurses_termattrs
Ncurses Funkcje
PHP Manual

ncurses_start_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_start_color — Initializes 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(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

Zobacz też:

  • ncurses_can_change_color() - Checks if terminal color definitions can be changed
  • ncurses_has_colors() - Checks if terminal has color capabilities

ncurses_standout
ncurses_termattrs
Ncurses Funkcje


Returns a logical OR of all attribute flags supported by terminal

ncurses_start_color
ncurses_termname
Ncurses Funkcje
PHP Manual

ncurses_termattrs

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termattrs — Returns 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_start_color
ncurses_termname
Ncurses Funkcje


Returns terminals (short)-name

ncurses_termattrs
ncurses_timeout
Ncurses Funkcje
PHP Manual

ncurses_termname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termname — Returns 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_longname() - Returns terminals description

ncurses_termattrs
ncurses_timeout
Ncurses Funkcje


Set timeout for special key sequences

ncurses_termname
ncurses_top_panel
Ncurses Funkcje
PHP Manual

ncurses_timeout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_timeout — Set 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_termname
ncurses_top_panel
Ncurses Funkcje


Moves a visible panel to the top of the stack

ncurses_timeout
ncurses_typeahead
Ncurses Funkcje
PHP Manual

ncurses_top_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_top_panel — Moves 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_timeout
ncurses_typeahead
Ncurses Funkcje


Specify different filedescriptor for typeahead checking

ncurses_top_panel
ncurses_ungetch
Ncurses Funkcje
PHP Manual

ncurses_typeahead

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_typeahead — Specify 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_top_panel
ncurses_ungetch
Ncurses Funkcje


Put a character back into the input stream

ncurses_typeahead
ncurses_ungetmouse
Ncurses Funkcje
PHP Manual

ncurses_ungetch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetch — Put 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_typeahead
ncurses_ungetmouse
Ncurses Funkcje


Pushes mouse event to queue

ncurses_ungetch
ncurses_update_panels
Ncurses Funkcje
PHP Manual

ncurses_ungetmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetmouse — Pushes 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_getmouse() - Reads mouse event

ncurses_ungetch
ncurses_update_panels
Ncurses Funkcje


Refreshes the virtual screen to reflect the relations between panels in the stack

ncurses_ungetmouse
ncurses_use_default_colors
Ncurses Funkcje
PHP Manual

ncurses_update_panels

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_update_panels — Refreshes 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_ungetmouse
ncurses_use_default_colors
Ncurses Funkcje


Assign terminal default colors to color id -1

ncurses_update_panels
ncurses_use_env
Ncurses Funkcje
PHP Manual

ncurses_use_default_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_default_colors — Assign 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_update_panels
ncurses_use_env
Ncurses Funkcje


Control use of environment information about terminal size

ncurses_use_default_colors
ncurses_use_extended_names
Ncurses Funkcje
PHP Manual

ncurses_use_env

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_env — Control 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_default_colors
ncurses_use_extended_names
Ncurses Funkcje


Control use of extended names in terminfo descriptions

ncurses_use_env
ncurses_vidattr
Ncurses Funkcje
PHP Manual

ncurses_use_extended_names

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_extended_names — Control 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_use_env
ncurses_vidattr
Ncurses Funkcje


Display the string on the terminal in the video attribute mode

ncurses_use_extended_names
ncurses_vline
Ncurses Funkcje
PHP Manual

ncurses_vidattr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vidattr — Display 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_use_extended_names
ncurses_vline
Ncurses Funkcje


Draw a vertical line at current position using an attributed character and max. n characters long

ncurses_vidattr
ncurses_waddch
Ncurses Funkcje
PHP Manual

ncurses_vline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vline — Draw 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_vidattr
ncurses_waddch
Ncurses Funkcje


Adds character at current position in a window and advance cursor

ncurses_vline
ncurses_waddstr
Ncurses Funkcje
PHP Manual

ncurses_waddch

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddch — Adds 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_vline
ncurses_waddstr
Ncurses Funkcje


Outputs text at current postion in window

ncurses_waddch
ncurses_wattroff
Ncurses Funkcje
PHP Manual

ncurses_waddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddstr — Outputs 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_waddch
ncurses_wattroff
Ncurses Funkcje


Turns off attributes for a window

ncurses_waddstr
ncurses_wattron
Ncurses Funkcje
PHP Manual

ncurses_wattroff

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattroff — Turns 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_waddstr
ncurses_wattron
Ncurses Funkcje


Turns on attributes for a window

ncurses_wattroff
ncurses_wattrset
Ncurses Funkcje
PHP Manual

ncurses_wattron

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattron — Turns 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_wattroff
ncurses_wattrset
Ncurses Funkcje


Set the attributes for a window

ncurses_wattron
ncurses_wborder
Ncurses Funkcje
PHP Manual

ncurses_wattrset

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattrset — Set 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_wattron
ncurses_wborder
Ncurses Funkcje


Draws a border around the window using attributed characters

ncurses_wattrset
ncurses_wclear
Ncurses Funkcje
PHP Manual

ncurses_wborder

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wborder — Draws 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_wattrset
ncurses_wclear
Ncurses Funkcje


Clears window

ncurses_wborder
ncurses_wcolor_set
Ncurses Funkcje
PHP Manual

ncurses_wclear

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wclear — Clears 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_wborder
ncurses_wcolor_set
Ncurses Funkcje


Sets windows color pairings

ncurses_wclear
ncurses_werase
Ncurses Funkcje
PHP Manual

ncurses_wcolor_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wcolor_set — Sets 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_wclear
ncurses_werase
Ncurses Funkcje


Erase window contents

ncurses_wcolor_set
ncurses_wgetch
Ncurses Funkcje
PHP Manual

ncurses_werase

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_werase — Erase 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_wcolor_set
ncurses_wgetch
Ncurses Funkcje


Reads a character from keyboard (window)

ncurses_werase
ncurses_whline
Ncurses Funkcje
PHP Manual

ncurses_wgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wgetch — Reads 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_werase
ncurses_whline
Ncurses Funkcje


Draws a horizontal line in a window at current position using an attributed character and max. n characters long

ncurses_wgetch
ncurses_wmouse_trafo
Ncurses Funkcje
PHP Manual

ncurses_whline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_whline — Draws 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_wgetch
ncurses_wmouse_trafo
Ncurses Funkcje


Transforms window/stdscr coordinates

ncurses_whline
ncurses_wmove
Ncurses Funkcje
PHP Manual

ncurses_wmouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmouse_trafo — Transforms 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_whline
ncurses_wmove
Ncurses Funkcje


Moves windows output position

ncurses_wmouse_trafo
ncurses_wnoutrefresh
Ncurses Funkcje
PHP Manual

ncurses_wmove

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmove — Moves 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_wmouse_trafo
ncurses_wnoutrefresh
Ncurses Funkcje


Copies window to virtual screen

ncurses_wmove
ncurses_wrefresh
Ncurses Funkcje
PHP Manual

ncurses_wnoutrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wnoutrefresh — Copies 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_wmove
ncurses_wrefresh
Ncurses Funkcje


Refresh window on terminal screen

ncurses_wnoutrefresh
ncurses_wstandend
Ncurses Funkcje
PHP Manual

ncurses_wrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wrefresh — Refresh 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_wnoutrefresh
ncurses_wstandend
Ncurses Funkcje


End standout mode for a window

ncurses_wrefresh
ncurses_wstandout
Ncurses Funkcje
PHP Manual

ncurses_wstandend

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandend — End 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_wrefresh
ncurses_wstandout
Ncurses Funkcje


Enter standout mode for a window

ncurses_wstandend
ncurses_wvline
Ncurses Funkcje
PHP Manual

ncurses_wstandout

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandout — Enter 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_wstandend
ncurses_wvline
Ncurses Funkcje


Draws a vertical line in a window at current position using an attributed character and max. n characters long

ncurses_wstandout
Newt
Ncurses Funkcje
PHP Manual

ncurses_wvline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wvline — Draws 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

ncurses_wstandout
Newt
Ncurses Funkcje


Newt

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
    • Newt form exit reasons
    • Newt colorsets
    • Newt argument flags
    • Newt Flags Sense
    • Newt Components Flags
    • File Descriptor Flags
    • Checkbox Tree Flags
    • Entry Flags
    • Listbox Flags
    • Textbox Flags
    • Form Flags
    • Newt Keys
    • Newt Anchors
    • Grid Flags
  • Przykłady
    • Basic usage
  • Newt Funkcje
    • newt_bell — Send a beep to the terminal
    • newt_button_bar — This function returns a grid containing the buttons created.
    • newt_button — Create a new button
    • newt_centered_window — Open a centered window of the specified size
    • newt_checkbox_get_value — Retreives value of checkox resource
    • newt_checkbox_set_flags — Configures checkbox resource
    • newt_checkbox_set_value — Sets the value of the checkbox
    • newt_checkbox_tree_add_item — Adds new item to the checkbox tree
    • newt_checkbox_tree_find_item — Finds an item in the checkbox tree
    • newt_checkbox_tree_get_current — Returns checkbox tree selected item
    • newt_checkbox_tree_get_entry_value — Opis
    • newt_checkbox_tree_get_multi_selection — Opis
    • newt_checkbox_tree_get_selection — Opis
    • newt_checkbox_tree_multi — Opis
    • newt_checkbox_tree_set_current — Opis
    • newt_checkbox_tree_set_entry_value — Opis
    • newt_checkbox_tree_set_entry — Opis
    • newt_checkbox_tree_set_width — Opis
    • newt_checkbox_tree — Opis
    • newt_checkbox — Opis
    • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls — Opis
    • newt_compact_button — Opis
    • newt_component_add_callback — Opis
    • newt_component_takes_focus — Opis
    • newt_create_grid — Opis
    • newt_cursor_off — Opis
    • newt_cursor_on — Opis
    • newt_delay — Opis
    • newt_draw_form — Opis
    • newt_draw_root_text — Displays the string text at the position indicated
    • newt_entry_get_value — Opis
    • newt_entry_set_filter — Opis
    • newt_entry_set_flags — Opis
    • newt_entry_set — Opis
    • newt_entry — Opis
    • newt_finished — Uninitializes newt interface
    • newt_form_add_component — Adds a single component to the form
    • newt_form_add_components — Add several components to the form
    • newt_form_add_hot_key — Opis
    • newt_form_destroy — Destroys a form
    • newt_form_get_current — Opis
    • newt_form_run — Runs a form
    • newt_form_set_background — Opis
    • newt_form_set_height — Opis
    • newt_form_set_size — Opis
    • newt_form_set_timer — Opis
    • newt_form_set_width — Opis
    • newt_form_watch_fd — Opis
    • newt_form — Create a form
    • newt_get_screen_size — Fills in the passed references with the current size of the terminal
    • newt_grid_add_components_to_form — Opis
    • newt_grid_basic_window — Opis
    • newt_grid_free — Opis
    • newt_grid_get_size — Opis
    • newt_grid_h_close_stacked — Opis
    • newt_grid_h_stacked — Opis
    • newt_grid_place — Opis
    • newt_grid_set_field — Opis
    • newt_grid_simple_window — Opis
    • newt_grid_v_close_stacked — Opis
    • newt_grid_v_stacked — Opis
    • newt_grid_wrapped_window_at — Opis
    • newt_grid_wrapped_window — Opis
    • newt_init — Initialize newt
    • newt_label_set_text — Opis
    • newt_label — Opis
    • newt_listbox_append_entry — Opis
    • newt_listbox_clear_selection — Opis
    • newt_listbox_clear — Opis
    • newt_listbox_delete_entry — Opis
    • newt_listbox_get_current — Opis
    • newt_listbox_get_selection — Opis
    • newt_listbox_insert_entry — Opis
    • newt_listbox_item_count — Opis
    • newt_listbox_select_item — Opis
    • newt_listbox_set_current_by_key — Opis
    • newt_listbox_set_current — Opis
    • newt_listbox_set_data — Opis
    • newt_listbox_set_entry — Opis
    • newt_listbox_set_width — Opis
    • newt_listbox — Opis
    • newt_listitem_get_data — Opis
    • newt_listitem_set — Opis
    • newt_listitem — Opis
    • newt_open_window — Open a window of the specified size and position
    • newt_pop_help_line — Replaces the current help line with the one from the stack
    • newt_pop_window — Removes the top window from the display
    • newt_push_help_line — Saves the current help line on a stack, and displays the new line
    • newt_radio_get_current — Opis
    • newt_radiobutton — Opis
    • newt_redraw_help_line — Opis
    • newt_reflow_text — Opis
    • newt_refresh — Updates modified portions of the screen
    • newt_resize_screen — Opis
    • newt_resume — Resume using the newt interface after calling newt_suspend
    • newt_run_form — Runs a form
    • newt_scale_set — Opis
    • newt_scale — Opis
    • newt_scrollbar_set — Opis
    • newt_set_help_callback — Opis
    • newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key
    • newt_suspend — Tells newt to return the terminal to its initial state
    • newt_textbox_get_num_lines — Opis
    • newt_textbox_reflowed — Opis
    • newt_textbox_set_height — Opis
    • newt_textbox_set_text — Opis
    • newt_textbox — Opis
    • newt_vertical_scrollbar — Opis
    • newt_wait_for_key — Doesn't return until a key has been pressed
    • newt_win_choice — Opis
    • newt_win_entries — Opis
    • newt_win_menu — Opis
    • newt_win_message — Opis
    • newt_win_messagev — Opis
    • newt_win_ternary — Opis
ncurses_wvline
Wstęp
Rozszerzenia wiersza poleceń


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.

Newt
Instalacja/Konfiguracja
Newt


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Newt


Wymagania

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

Spis treści

  • Newt form exit reasons
  • Newt colorsets
  • Newt argument flags
  • Newt Flags Sense
  • Newt Components Flags
  • File Descriptor Flags
  • Checkbox Tree Flags
  • Entry Flags
  • Listbox Flags
  • Textbox Flags
  • Form Flags
  • Newt Keys
  • Newt Anchors
  • Grid Flags

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.

Typy zasobów
Newt form exit reasons
Newt


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
Stałe predefiniowane
Newt colorsets
Stałe predefiniowane


Newt colorsets

Newt colorsets
constant | meaning
NEWT_COLORSET_ROOT |
NEWT_COLORSET_BORDER |
NEWT_COLORSET_WINDOW |
NEWT_COLORSET_SHADOW |
NEWT_COLORSET_TITLE |
NEWT_COLORSET_BUTTON |
NEWT_COLORSET_ACTBUTTON |
NEWT_COLORSET_CHECKBOX |
NEWT_COLORSET_ACTCHECKBOX |
NEWT_COLORSET_ENTRY |
NEWT_COLORSET_LABEL |
NEWT_COLORSET_LISTBOX |
NEWT_COLORSET_ACTLISTBOX |
NEWT_COLORSET_TEXTBOX |
NEWT_COLORSET_ACTTEXTBOX |
NEWT_COLORSET_HELPLINE |
NEWT_COLORSET_ROOTTEXT |
NEWT_COLORSET_ROOTTEXT |
NEWT_COLORSET_EMPTYSCALE |
NEWT_COLORSET_FULLSCALE |
NEWT_COLORSET_DISENTRY |
NEWT_COLORSET_COMPACTBUTTON |
NEWT_COLORSET_ACTSELLISTBOX |
NEWT_COLORSET_SELLISTBOX |
Newt form exit reasons
Newt argument flags
Stałe predefiniowane


Newt argument flags

Newt argument flags
constant | meaning
NEWT_ARG_LAST |
NEWT_ARG_APPEND |
Newt colorsets
Newt Flags Sense
Stałe predefiniowane


Newt Flags Sense

Newt Flags Sense
constant | meaning
NEWT_FLAGS_SET |
NEWT_FLAGS_RESET |
NEWT_FLAGS_TOGGLE |
Newt argument flags
Newt Components Flags
Stałe predefiniowane


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
Newt Flags Sense
File Descriptor Flags
Stałe predefiniowane


File Descriptor Flags

File Descriptor Flags
constant | meaning
NEWT_FD_READ |
NEWT_FD_WRITE |
NEWT_FD_EXCEPT |
Newt Components Flags
Checkbox Tree Flags
Stałe predefiniowane


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 |
File Descriptor Flags
Entry Flags
Stałe predefiniowane


Entry Flags

Entry Flags
constant | meaning
NEWT_ENTRY_SCROLL |
NEWT_ENTRY_HIDDEN |
NEWT_ENTRY_RETURNEXIT |
NEWT_ENTRY_DISABLED |
Checkbox Tree Flags
Listbox Flags
Stałe predefiniowane


Listbox Flags

Listbox Flags
constant | meaning
NEWT_LISTBOX_RETURNEXIT |
Entry Flags
Textbox Flags
Stałe predefiniowane


Textbox Flags

Textbox Flags
constant | meaning
NEWT_TEXTBOX_WRAP | Wrap text in the textbox
NEWT_TEXTBOX_SCROLL | Scroll text in the textbox
Listbox Flags
Form Flags
Stałe predefiniowane


Form Flags

Form Flags
constant | meaning
NEWT_FORM_NOF12 | Don't exit form on F12 press
Textbox Flags
Newt Keys
Stałe predefiniowane


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 |
Form Flags
Newt Anchors
Stałe predefiniowane


Newt Anchors

Newt Anchors
constant | meaning
NEWT_ANCHOR_LEFT |
NEWT_ANCHOR_RIGHT |
NEWT_ANCHOR_TOP |
NEWT_ANCHOR_BOTTOM |
Newt Keys
Grid Flags
Stałe predefiniowane


Grid Flags

Grid Flags
constant | meaning
NEWT_GRID_FLAG_GROWX |
NEWT_GRID_FLAG_GROWY |
NEWT_GRID_EMPTY |
NEWT_GRID_COMPONENT |
NEWT_GRID_SUBGRID |
Newt Anchors
Przykłady
Stałe predefiniowane


Przykłady

Spis treści

  • Basic usage
Grid Flags
Basic usage
Newt


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 (0, 0, "Test Mode Setup Utility 1.12");
newt_push_help_line (null);
newt_draw_root_text (-30, 0, "(c) 1999-2002 RedHat, Inc");

newt_get_screen_size ($rows, $cols);

newt_open_window ($rows/2-17, $cols/2-10, 34, 17, "Choose a Tool");

$form = newt_form ();

$list = newt_listbox (3, 2, 10);

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 (5, 12, "Run Tool");
$b2 = newt_button (21, 12, "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);
?>
Przykłady
Newt Funkcje
Przykłady


Newt Funkcje

Spis treści

  • newt_bell — Send a beep to the terminal
  • newt_button_bar — This function returns a grid containing the buttons created.
  • newt_button — Create a new button
  • newt_centered_window — Open a centered window of the specified size
  • newt_checkbox_get_value — Retreives value of checkox resource
  • newt_checkbox_set_flags — Configures checkbox resource
  • newt_checkbox_set_value — Sets the value of the checkbox
  • newt_checkbox_tree_add_item — Adds new item to the checkbox tree
  • newt_checkbox_tree_find_item — Finds an item in the checkbox tree
  • newt_checkbox_tree_get_current — Returns checkbox tree selected item
  • newt_checkbox_tree_get_entry_value — Opis
  • newt_checkbox_tree_get_multi_selection — Opis
  • newt_checkbox_tree_get_selection — Opis
  • newt_checkbox_tree_multi — Opis
  • newt_checkbox_tree_set_current — Opis
  • newt_checkbox_tree_set_entry_value — Opis
  • newt_checkbox_tree_set_entry — Opis
  • newt_checkbox_tree_set_width — Opis
  • newt_checkbox_tree — Opis
  • newt_checkbox — Opis
  • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
  • newt_cls — Opis
  • newt_compact_button — Opis
  • newt_component_add_callback — Opis
  • newt_component_takes_focus — Opis
  • newt_create_grid — Opis
  • newt_cursor_off — Opis
  • newt_cursor_on — Opis
  • newt_delay — Opis
  • newt_draw_form — Opis
  • newt_draw_root_text — Displays the string text at the position indicated
  • newt_entry_get_value — Opis
  • newt_entry_set_filter — Opis
  • newt_entry_set_flags — Opis
  • newt_entry_set — Opis
  • newt_entry — Opis
  • newt_finished — Uninitializes newt interface
  • newt_form_add_component — Adds a single component to the form
  • newt_form_add_components — Add several components to the form
  • newt_form_add_hot_key — Opis
  • newt_form_destroy — Destroys a form
  • newt_form_get_current — Opis
  • newt_form_run — Runs a form
  • newt_form_set_background — Opis
  • newt_form_set_height — Opis
  • newt_form_set_size — Opis
  • newt_form_set_timer — Opis
  • newt_form_set_width — Opis
  • newt_form_watch_fd — Opis
  • newt_form — Create a form
  • newt_get_screen_size — Fills in the passed references with the current size of the terminal
  • newt_grid_add_components_to_form — Opis
  • newt_grid_basic_window — Opis
  • newt_grid_free — Opis
  • newt_grid_get_size — Opis
  • newt_grid_h_close_stacked — Opis
  • newt_grid_h_stacked — Opis
  • newt_grid_place — Opis
  • newt_grid_set_field — Opis
  • newt_grid_simple_window — Opis
  • newt_grid_v_close_stacked — Opis
  • newt_grid_v_stacked — Opis
  • newt_grid_wrapped_window_at — Opis
  • newt_grid_wrapped_window — Opis
  • newt_init — Initialize newt
  • newt_label_set_text — Opis
  • newt_label — Opis
  • newt_listbox_append_entry — Opis
  • newt_listbox_clear_selection — Opis
  • newt_listbox_clear — Opis
  • newt_listbox_delete_entry — Opis
  • newt_listbox_get_current — Opis
  • newt_listbox_get_selection — Opis
  • newt_listbox_insert_entry — Opis
  • newt_listbox_item_count — Opis
  • newt_listbox_select_item — Opis
  • newt_listbox_set_current_by_key — Opis
  • newt_listbox_set_current — Opis
  • newt_listbox_set_data — Opis
  • newt_listbox_set_entry — Opis
  • newt_listbox_set_width — Opis
  • newt_listbox — Opis
  • newt_listitem_get_data — Opis
  • newt_listitem_set — Opis
  • newt_listitem — Opis
  • newt_open_window — Open a window of the specified size and position
  • newt_pop_help_line — Replaces the current help line with the one from the stack
  • newt_pop_window — Removes the top window from the display
  • newt_push_help_line — Saves the current help line on a stack, and displays the new line
  • newt_radio_get_current — Opis
  • newt_radiobutton — Opis
  • newt_redraw_help_line — Opis
  • newt_reflow_text — Opis
  • newt_refresh — Updates modified portions of the screen
  • newt_resize_screen — Opis
  • newt_resume — Resume using the newt interface after calling newt_suspend
  • newt_run_form — Runs a form
  • newt_scale_set — Opis
  • newt_scale — Opis
  • newt_scrollbar_set — Opis
  • newt_set_help_callback — Opis
  • newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key
  • newt_suspend — Tells newt to return the terminal to its initial state
  • newt_textbox_get_num_lines — Opis
  • newt_textbox_reflowed — Opis
  • newt_textbox_set_height — Opis
  • newt_textbox_set_text — Opis
  • newt_textbox — Opis
  • newt_vertical_scrollbar — Opis
  • newt_wait_for_key — Doesn't return until a key has been pressed
  • newt_win_choice — Opis
  • newt_win_entries — Opis
  • newt_win_menu — Opis
  • newt_win_message — Opis
  • newt_win_messagev — Opis
  • newt_win_ternary — Opis
Basic usage
newt_bell
Newt


Send a beep to the terminal

Newt Funkcje
newt_button_bar
Newt Funkcje
PHP Manual

newt_bell

(PECL newt >= 0.1)

newt_bell — Send 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 Funkcje
newt_button_bar
Newt Funkcje


This function returns a grid containing the buttons created.

newt_bell
newt_button
Newt Funkcje
PHP Manual

newt_button_bar

(PECL newt >= 0.1)

newt_button_bar — This 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_bell
newt_button
Newt Funkcje


Create a new button

newt_button_bar
newt_centered_window
Newt Funkcje
PHP Manual

newt_button

(PECL newt >= 0.1)

newt_button — Create 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(5, 12, "Run Tool");

newt_form_add_component($form, $ok_button);

?>

Zobacz też:

  • newt_button_bar() - This function returns a grid containing the buttons created.

newt_button_bar
newt_centered_window
Newt Funkcje


Open a centered window of the specified size

newt_button
newt_checkbox_get_value
Newt Funkcje
PHP Manual

newt_centered_window

(PECL newt >= 0.1)

newt_centered_window — Open 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_pop_window() - Removes the top window from the display
  • newt_open_window() - Open a window of the specified size and position

newt_button
newt_checkbox_get_value
Newt Funkcje


Retreives value of checkox resource

newt_centered_window
newt_checkbox_set_flags
Newt Funkcje
PHP Manual

newt_checkbox_get_value

(PECL newt >= 0.1)

newt_checkbox_get_value — Retreives 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_centered_window
newt_checkbox_set_flags
Newt Funkcje


Configures checkbox resource

newt_checkbox_get_value
newt_checkbox_set_value
Newt Funkcje
PHP Manual

newt_checkbox_set_flags

(PECL newt >= 0.1)

newt_checkbox_set_flags — Configures 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_get_value
newt_checkbox_set_value
Newt Funkcje


Sets the value of the checkbox

newt_checkbox_set_flags
newt_checkbox_tree_add_item
Newt Funkcje
PHP Manual

newt_checkbox_set_value

(PECL newt >= 0.1)

newt_checkbox_set_value — Sets 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_set_flags
newt_checkbox_tree_add_item
Newt Funkcje


Adds new item to the checkbox tree

newt_checkbox_set_value
newt_checkbox_tree_find_item
Newt Funkcje
PHP Manual

newt_checkbox_tree_add_item

(PECL newt >= 0.1)

newt_checkbox_tree_add_item — Adds 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_set_value
newt_checkbox_tree_find_item
Newt Funkcje


Finds an item in the checkbox tree

newt_checkbox_tree_add_item
newt_checkbox_tree_get_current
Newt Funkcje
PHP Manual

newt_checkbox_tree_find_item

(PECL newt >= 0.1)

newt_checkbox_tree_find_item — Finds 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_add_item
newt_checkbox_tree_get_current
Newt Funkcje


Returns checkbox tree selected item

newt_checkbox_tree_find_item
newt_checkbox_tree_get_entry_value
Newt Funkcje
PHP Manual

newt_checkbox_tree_get_current

(PECL newt >= 0.1)

newt_checkbox_tree_get_current — Returns 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_find_item
newt_checkbox_tree_get_entry_value
Newt Funkcje


newt_checkbox_tree_get_current
newt_checkbox_tree_get_multi_selection
Newt Funkcje
PHP Manual

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_current
newt_checkbox_tree_get_multi_selection
Newt Funkcje


newt_checkbox_tree_get_entry_value
newt_checkbox_tree_get_selection
Newt Funkcje
PHP Manual

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_entry_value
newt_checkbox_tree_get_selection
Newt Funkcje


newt_checkbox_tree_get_multi_selection
newt_checkbox_tree_multi
Newt Funkcje
PHP Manual

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_get_multi_selection
newt_checkbox_tree_multi
Newt Funkcje


newt_checkbox_tree_get_selection
newt_checkbox_tree_set_current
Newt Funkcje
PHP Manual

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_get_selection
newt_checkbox_tree_set_current
Newt Funkcje


newt_checkbox_tree_multi
newt_checkbox_tree_set_entry_value
Newt Funkcje
PHP Manual

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_multi
newt_checkbox_tree_set_entry_value
Newt Funkcje


newt_checkbox_tree_set_current
newt_checkbox_tree_set_entry
Newt Funkcje
PHP Manual

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_current
newt_checkbox_tree_set_entry
Newt Funkcje


newt_checkbox_tree_set_entry_value
newt_checkbox_tree_set_width
Newt Funkcje
PHP Manual

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_entry_value
newt_checkbox_tree_set_width
Newt Funkcje


newt_checkbox_tree_set_entry
newt_checkbox_tree
Newt Funkcje
PHP Manual

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_set_entry
newt_checkbox_tree
Newt Funkcje


newt_checkbox_tree_set_width
newt_checkbox
Newt Funkcje
PHP Manual

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_tree_set_width
newt_checkbox
Newt Funkcje


newt_checkbox_tree
newt_clear_key_buffer
Newt Funkcje
PHP Manual

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_checkbox_tree
newt_clear_key_buffer
Newt Funkcje


Discards the contents of the terminal's input buffer without waiting for additional input

newt_checkbox
newt_cls
Newt Funkcje
PHP Manual

newt_clear_key_buffer

(PECL newt >= 0.1)

newt_clear_key_buffer — Discards 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_wait_for_key() - Doesn't return until a key has been pressed

newt_checkbox
newt_cls
Newt Funkcje


newt_clear_key_buffer
newt_compact_button
Newt Funkcje
PHP Manual

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_clear_key_buffer
newt_compact_button
Newt Funkcje


newt_cls
newt_component_add_callback
Newt Funkcje
PHP Manual

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_cls
newt_component_add_callback
Newt Funkcje


newt_compact_button
newt_component_takes_focus
Newt Funkcje
PHP Manual

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_compact_button
newt_component_takes_focus
Newt Funkcje


newt_component_add_callback
newt_create_grid
Newt Funkcje
PHP Manual

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_component_add_callback
newt_create_grid
Newt Funkcje


newt_component_takes_focus
newt_cursor_off
Newt Funkcje
PHP Manual

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_component_takes_focus
newt_cursor_off
Newt Funkcje


newt_create_grid
newt_cursor_on
Newt Funkcje
PHP Manual

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_create_grid
newt_cursor_on
Newt Funkcje


newt_cursor_off
newt_delay
Newt Funkcje
PHP Manual

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_cursor_off
newt_delay
Newt Funkcje


newt_cursor_on
newt_draw_form
Newt Funkcje
PHP Manual

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_cursor_on
newt_draw_form
Newt Funkcje


newt_delay
newt_draw_root_text
Newt Funkcje
PHP Manual

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_delay
newt_draw_root_text
Newt Funkcje


Displays the string text at the position indicated

newt_draw_form
newt_entry_get_value
Newt Funkcje
PHP Manual

newt_draw_root_text

(PECL newt >= 0.1)

newt_draw_root_text — Displays 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 (2, 0, "Some root text");
 newt_refresh();
 sleep(1);

 newt_draw_root_text (-30, 0, "Root text in the other corner");
 newt_refresh();
 sleep(1);

 newt_finished();
?>

Zobacz też:

  • newt_push_help_line() - Saves the current help line on a stack, and displays the new line
  • newt_pop_help_line() - Replaces the current help line with the one from the stack

newt_draw_form
newt_entry_get_value
Newt Funkcje


newt_draw_root_text
newt_entry_set_filter
Newt Funkcje
PHP Manual

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_draw_root_text
newt_entry_set_filter
Newt Funkcje


newt_entry_get_value
newt_entry_set_flags
Newt Funkcje
PHP Manual

newt_entry_set_filter

(PECL newt >= 0.1)

newt_entry_set_filter —

Opis

void newt_entry_set_filter ( resource $entry , callback $filter , mixed $data )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

entry

filter

data

Zwracane wartości

Nie jest zwracana żadna wartość.

newt_entry_get_value
newt_entry_set_flags
Newt Funkcje


newt_entry_set_filter
newt_entry_set
Newt Funkcje
PHP Manual

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_filter
newt_entry_set
Newt Funkcje


newt_entry_set_flags
newt_entry
Newt Funkcje
PHP Manual

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_set_flags
newt_entry
Newt Funkcje


newt_entry_set
newt_finished
Newt Funkcje
PHP Manual

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_entry_set
newt_finished
Newt Funkcje


Uninitializes newt interface

newt_entry
newt_form_add_component
Newt Funkcje
PHP Manual

newt_finished

(PECL newt >= 0.1)

newt_finished — Uninitializes 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_init() - Initialize newt

newt_entry
newt_form_add_component
Newt Funkcje


Adds a single component to the form

newt_finished
newt_form_add_components
Newt Funkcje
PHP Manual

newt_form_add_component

(PECL newt >= 0.1)

newt_form_add_component — Adds 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(3, 2, 10);

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() - Add several components to the form

newt_finished
newt_form_add_components
Newt Funkcje


Add several components to the form

newt_form_add_component
newt_form_add_hot_key
Newt Funkcje
PHP Manual

newt_form_add_components

(PECL newt >= 0.1)

newt_form_add_components — Add 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(5, 12, "Run Tool");
$b2 = newt_button(21, 12, "Quit");

newt_form_add_components($form, array($b1, $b2));
?>

Zobacz też:

  • newt_form_add_component() - Adds a single component to the form

newt_form_add_component
newt_form_add_hot_key
Newt Funkcje


newt_form_add_components
newt_form_destroy
Newt Funkcje
PHP Manual

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_add_components
newt_form_destroy
Newt Funkcje


Destroys a form

newt_form_add_hot_key
newt_form_get_current
Newt Funkcje
PHP Manual

newt_form_destroy

(PECL newt >= 0.1)

newt_form_destroy — Destroys 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_run() - Runs a form
  • newt_run_form() - Runs a form

newt_form_add_hot_key
newt_form_get_current
Newt Funkcje


newt_form_destroy
newt_form_run
Newt Funkcje
PHP Manual

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_destroy
newt_form_run
Newt Funkcje


Runs a form

newt_form_get_current
newt_form_set_background
Newt Funkcje
PHP Manual

newt_form_run

(PECL newt >= 0.1)

newt_form_run — Runs 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_run_form() - Runs a form

newt_form_get_current
newt_form_set_background
Newt Funkcje


newt_form_run
newt_form_set_height
Newt Funkcje
PHP Manual

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_run
newt_form_set_height
Newt Funkcje


newt_form_set_background
newt_form_set_size
Newt Funkcje
PHP Manual

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_background
newt_form_set_size
Newt Funkcje


newt_form_set_height
newt_form_set_timer
Newt Funkcje
PHP Manual

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_height
newt_form_set_timer
Newt Funkcje


newt_form_set_size
newt_form_set_width
Newt Funkcje
PHP Manual

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_size
newt_form_set_width
Newt Funkcje


newt_form_set_timer
newt_form_watch_fd
Newt Funkcje
PHP Manual

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_set_timer
newt_form_watch_fd
Newt Funkcje


newt_form_set_width
newt_form
Newt Funkcje
PHP Manual

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_set_width
newt_form
Newt Funkcje


Create a form

newt_form_watch_fd
newt_get_screen_size
Newt Funkcje
PHP Manual

newt_form

(PECL newt >= 0.1)

newt_form — Create 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 (5, 12, "Quit");

newt_form_add_component ($myform, $button);
newt_refresh ();
newt_run_form ($myform);

newt_finished ();
newt_form_destroy ($myform);
?>

Zobacz też:

  • newt_form_run() - Runs a form
  • newt_run_form() - Runs a form
  • newt_form_add_component() - Adds a single component to the form
  • newt_form_add_components() - Add several components to the form
  • newt_form_destroy() - Destroys a form

newt_form_watch_fd
newt_get_screen_size
Newt Funkcje


Fills in the passed references with the current size of the terminal

newt_form
newt_grid_add_components_to_form
Newt Funkcje
PHP Manual

newt_get_screen_size

(PECL newt >= 0.1)

newt_get_screen_size — Fills 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_form
newt_grid_add_components_to_form
Newt Funkcje


newt_get_screen_size
newt_grid_basic_window
Newt Funkcje
PHP Manual

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_get_screen_size
newt_grid_basic_window
Newt Funkcje


newt_grid_add_components_to_form
newt_grid_free
Newt Funkcje
PHP Manual

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_add_components_to_form
newt_grid_free
Newt Funkcje


newt_grid_basic_window
newt_grid_get_size
Newt Funkcje
PHP Manual

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_basic_window
newt_grid_get_size
Newt Funkcje


newt_grid_free
newt_grid_h_close_stacked
Newt Funkcje
PHP Manual

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_free
newt_grid_h_close_stacked
Newt Funkcje


newt_grid_get_size
newt_grid_h_stacked
Newt Funkcje
PHP Manual

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_get_size
newt_grid_h_stacked
Newt Funkcje


newt_grid_h_close_stacked
newt_grid_place
Newt Funkcje
PHP Manual

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_h_close_stacked
newt_grid_place
Newt Funkcje


newt_grid_h_stacked
newt_grid_set_field
Newt Funkcje
PHP Manual

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_h_stacked
newt_grid_set_field
Newt Funkcje


newt_grid_place
newt_grid_simple_window
Newt Funkcje
PHP Manual

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_place
newt_grid_simple_window
Newt Funkcje


newt_grid_set_field
newt_grid_v_close_stacked
Newt Funkcje
PHP Manual

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_set_field
newt_grid_v_close_stacked
Newt Funkcje


newt_grid_simple_window
newt_grid_v_stacked
Newt Funkcje
PHP Manual

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_simple_window
newt_grid_v_stacked
Newt Funkcje


newt_grid_v_close_stacked
newt_grid_wrapped_window_at
Newt Funkcje
PHP Manual

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_v_close_stacked
newt_grid_wrapped_window_at
Newt Funkcje


newt_grid_v_stacked
newt_grid_wrapped_window
Newt Funkcje
PHP Manual

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_v_stacked
newt_grid_wrapped_window
Newt Funkcje


newt_grid_wrapped_window_at
newt_init
Newt Funkcje
PHP Manual

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_grid_wrapped_window_at
newt_init
Newt Funkcje


Initialize newt

newt_grid_wrapped_window
newt_label_set_text
Newt Funkcje
PHP Manual

newt_init

(PECL newt >= 0.1)

newt_init — Initialize 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_finished() - Uninitializes newt interface

newt_grid_wrapped_window
newt_label_set_text
Newt Funkcje


newt_init
newt_label
Newt Funkcje
PHP Manual

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_init
newt_label
Newt Funkcje


newt_label_set_text
newt_listbox_append_entry
Newt Funkcje
PHP Manual

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_label_set_text
newt_listbox_append_entry
Newt Funkcje


newt_label
newt_listbox_clear_selection
Newt Funkcje
PHP Manual

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_label
newt_listbox_clear_selection
Newt Funkcje


newt_listbox_append_entry
newt_listbox_clear
Newt Funkcje
PHP Manual

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_append_entry
newt_listbox_clear
Newt Funkcje


newt_listbox_clear_selection
newt_listbox_delete_entry
Newt Funkcje
PHP Manual

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_clear_selection
newt_listbox_delete_entry
Newt Funkcje


newt_listbox_clear
newt_listbox_get_current
Newt Funkcje
PHP Manual

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_clear
newt_listbox_get_current
Newt Funkcje


newt_listbox_delete_entry
newt_listbox_get_selection
Newt Funkcje
PHP Manual

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_delete_entry
newt_listbox_get_selection
Newt Funkcje


newt_listbox_get_current
newt_listbox_insert_entry
Newt Funkcje
PHP Manual

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_get_current
newt_listbox_insert_entry
Newt Funkcje


newt_listbox_get_selection
newt_listbox_item_count
Newt Funkcje
PHP Manual

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_get_selection
newt_listbox_item_count
Newt Funkcje


newt_listbox_insert_entry
newt_listbox_select_item
Newt Funkcje
PHP Manual

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_insert_entry
newt_listbox_select_item
Newt Funkcje


newt_listbox_item_count
newt_listbox_set_current_by_key
Newt Funkcje
PHP Manual

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_item_count
newt_listbox_set_current_by_key
Newt Funkcje


newt_listbox_select_item
newt_listbox_set_current
Newt Funkcje
PHP Manual

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_select_item
newt_listbox_set_current
Newt Funkcje


newt_listbox_set_current_by_key
newt_listbox_set_data
Newt Funkcje
PHP Manual

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_current_by_key
newt_listbox_set_data
Newt Funkcje


newt_listbox_set_current
newt_listbox_set_entry
Newt Funkcje
PHP Manual

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_current
newt_listbox_set_entry
Newt Funkcje


newt_listbox_set_data
newt_listbox_set_width
Newt Funkcje
PHP Manual

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_data
newt_listbox_set_width
Newt Funkcje


newt_listbox_set_entry
newt_listbox
Newt Funkcje
PHP Manual

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_set_entry
newt_listbox
Newt Funkcje


newt_listbox_set_width
newt_listitem_get_data
Newt Funkcje
PHP Manual

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_listbox_set_width
newt_listitem_get_data
Newt Funkcje


newt_listbox
newt_listitem_set
Newt Funkcje
PHP Manual

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_listbox
newt_listitem_set
Newt Funkcje


newt_listitem_get_data
newt_listitem
Newt Funkcje
PHP Manual

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_get_data
newt_listitem
Newt Funkcje


newt_listitem_set
newt_open_window
Newt Funkcje
PHP Manual

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_listitem_set
newt_open_window
Newt Funkcje


Open a window of the specified size and position

newt_listitem
newt_pop_help_line
Newt Funkcje
PHP Manual

newt_open_window

(PECL newt >= 0.1)

newt_open_window — Open 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_window() - Removes the top window from the display
  • newt_centered_window() - Open a centered window of the specified size

newt_listitem
newt_pop_help_line
Newt Funkcje


Replaces the current help line with the one from the stack

newt_open_window
newt_pop_window
Newt Funkcje
PHP Manual

newt_pop_help_line

(PECL newt >= 0.1)

newt_pop_help_line — Replaces 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_push_help_line() - Saves the current help line on a stack, and displays the new line

newt_open_window
newt_pop_window
Newt Funkcje


Removes the top window from the display

newt_pop_help_line
newt_push_help_line
Newt Funkcje
PHP Manual

newt_pop_window

(PECL newt >= 0.1)

newt_pop_window — Removes 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_open_window() - Open a window of the specified size and position
  • newt_centered_window() - Open a centered window of the specified size

newt_pop_help_line
newt_push_help_line
Newt Funkcje


Saves the current help line on a stack, and displays the new line

newt_pop_window
newt_radio_get_current
Newt Funkcje
PHP Manual

newt_push_help_line

(PECL newt >= 0.1)

newt_push_help_line — Saves 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_pop_help_line() - Replaces the current help line with the one from the stack

newt_pop_window
newt_radio_get_current
Newt Funkcje


newt_push_help_line
newt_radiobutton
Newt Funkcje
PHP Manual

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_push_help_line
newt_radiobutton
Newt Funkcje


newt_radio_get_current
newt_redraw_help_line
Newt Funkcje
PHP Manual

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_radio_get_current
newt_redraw_help_line
Newt Funkcje


newt_radiobutton
newt_reflow_text
Newt Funkcje
PHP Manual

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_radiobutton
newt_reflow_text
Newt Funkcje


newt_redraw_help_line
newt_refresh
Newt Funkcje
PHP Manual

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_redraw_help_line
newt_refresh
Newt Funkcje


Updates modified portions of the screen

newt_reflow_text
newt_resize_screen
Newt Funkcje
PHP Manual

newt_refresh

(PECL newt >= 0.1)

newt_refresh — Updates 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_reflow_text
newt_resize_screen
Newt Funkcje


newt_refresh
newt_resume
Newt Funkcje
PHP Manual

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_refresh
newt_resume
Newt Funkcje


Resume using the newt interface after calling newt_suspend

newt_resize_screen
newt_run_form
Newt Funkcje
PHP Manual

newt_resume

(PECL newt >= 0.1)

newt_resume — Resume 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_resize_screen
newt_run_form
Newt Funkcje


Runs a form

newt_resume
newt_scale_set
Newt Funkcje
PHP Manual

newt_run_form

(PECL newt >= 0.1)

newt_run_form — Runs 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_form_run() - Runs a form
  • newt_form_destroy() - Destroys a form

newt_resume
newt_scale_set
Newt Funkcje


newt_run_form
newt_scale
Newt Funkcje
PHP Manual

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_run_form
newt_scale
Newt Funkcje


newt_scale_set
newt_scrollbar_set
Newt Funkcje
PHP Manual

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_scale_set
newt_scrollbar_set
Newt Funkcje


newt_scale
newt_set_help_callback
Newt Funkcje
PHP Manual

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_scale
newt_set_help_callback
Newt Funkcje


newt_scrollbar_set
newt_set_suspend_callback
Newt Funkcje
PHP Manual

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_scrollbar_set
newt_set_suspend_callback
Newt Funkcje


Set a callback function which gets invoked when user presses the suspend key

newt_set_help_callback
newt_suspend
Newt Funkcje
PHP Manual

newt_set_suspend_callback

(PECL newt >= 0.1)

newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key

Opis

void newt_set_suspend_callback ( callback $function , mixed $data )

Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.

Parametry

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • newt_suspend() - Tells newt to return the terminal to its initial state
  • newt_resume() - Resume using the newt interface after calling newt_suspend

newt_set_help_callback
newt_suspend
Newt Funkcje


Tells newt to return the terminal to its initial state

newt_set_suspend_callback
newt_textbox_get_num_lines
Newt Funkcje
PHP Manual

newt_suspend

(PECL newt >= 0.1)

newt_suspend — Tells 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_set_suspend_callback
newt_textbox_get_num_lines
Newt Funkcje


newt_suspend
newt_textbox_reflowed
Newt Funkcje
PHP Manual

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_suspend
newt_textbox_reflowed
Newt Funkcje


newt_textbox_get_num_lines
newt_textbox_set_height
Newt Funkcje
PHP Manual

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_get_num_lines
newt_textbox_set_height
Newt Funkcje


newt_textbox_reflowed
newt_textbox_set_text
Newt Funkcje
PHP Manual

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_reflowed
newt_textbox_set_text
Newt Funkcje


newt_textbox_set_height
newt_textbox
Newt Funkcje
PHP Manual

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_set_height
newt_textbox
Newt Funkcje


newt_textbox_set_text
newt_vertical_scrollbar
Newt Funkcje
PHP Manual

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_textbox_set_text
newt_vertical_scrollbar
Newt Funkcje


newt_textbox
newt_wait_for_key
Newt Funkcje
PHP Manual

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_textbox
newt_wait_for_key
Newt Funkcje


Doesn't return until a key has been pressed

newt_vertical_scrollbar
newt_win_choice
Newt Funkcje
PHP Manual

newt_wait_for_key

(PECL newt >= 0.1)

newt_wait_for_key — Doesn'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_vertical_scrollbar
newt_win_choice
Newt Funkcje


newt_wait_for_key
newt_win_entries
Newt Funkcje
PHP Manual

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_wait_for_key
newt_win_entries
Newt Funkcje


newt_win_choice
newt_win_menu
Newt Funkcje
PHP Manual

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:", 50, 7, 7, 30, $entries, "Ok", "Back");
newt_finished ();

if ($rc != 2) {
    echo "Your name is: $f_name $l_name\n";
}
?>

newt_win_choice
newt_win_menu
Newt Funkcje


newt_win_entries
newt_win_message
Newt Funkcje
PHP Manual

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_entries
newt_win_message
Newt Funkcje


newt_win_menu
newt_win_messagev
Newt Funkcje
PHP Manual

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_menu
newt_win_messagev
Newt Funkcje


newt_win_message
newt_win_ternary
Newt Funkcje
PHP Manual

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_message
newt_win_ternary
Newt Funkcje


newt_win_messagev
Readline
Newt Funkcje
PHP Manual

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

newt_win_messagev
Readline
Newt Funkcje


GNU Readline

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje Readline
    • readline_add_history — Dodaje wiersz do historii
    • readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately
    • readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings
    • readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received
    • readline_clear_history — Czyści historię
    • readline_completion_function — Rejestruje funkcję dopełniania
    • readline_info — Pobiera/ustawia różne wewnętrzne zmienne biblioteki readline
    • readline_list_history — Zwraca historię wiersza poleceń
    • readline_on_new_line — Inform readline that the cursor has moved to a new line
    • readline_read_history — Czyta historię
    • readline_redisplay — Redraws the display
    • readline_write_history — Zapisuje historię
    • readline — Czyta linię
newt_win_ternary
Wstęp
Rozszerzenia wiersza poleceń


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.

Readline
Instalacja/Konfiguracja
Readline


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Readline


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/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Funkcje Readline
Readline


Funkcje Readline

Spis treści

  • readline_add_history — Dodaje wiersz do historii
  • readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  • readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings
  • readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received
  • readline_clear_history — Czyści historię
  • readline_completion_function — Rejestruje funkcję dopełniania
  • readline_info — Pobiera/ustawia różne wewnętrzne zmienne biblioteki readline
  • readline_list_history — Zwraca historię wiersza poleceń
  • readline_on_new_line — Inform readline that the cursor has moved to a new line
  • readline_read_history — Czyta historię
  • readline_redisplay — Redraws the display
  • readline_write_history — Zapisuje historię
  • readline — Czyta linię
Stałe predefiniowane
readline_add_history
Readline


Dodaje wiersz do historii

Funkcje Readline
readline_callback_handler_install
Funkcje Readline
PHP Manual

readline_add_history

(PHP 4, PHP 5)

readline_add_history — Dodaje 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.

Funkcje Readline
readline_callback_handler_install
Funkcje Readline


Initializes the readline callback interface and terminal, prints the prompt and returns immediately

readline_add_history
readline_callback_handler_remove
Funkcje Readline
PHP Manual

readline_callback_handler_install

(PHP 5 >= 5.1.0)

readline_callback_handler_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately

Opis

bool readline_callback_handler_install ( string $prompt , callback $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, $e, null);
    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() - Removes a previously installed callback handler and restores terminal settings
  • readline_callback_read_char() - Reads a character and informs the readline callback interface when a line is received
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

readline_add_history
readline_callback_handler_remove
Funkcje Readline


Removes a previously installed callback handler and restores terminal settings

readline_callback_handler_install
readline_callback_read_char
Funkcje Readline
PHP Manual

readline_callback_handler_remove

(PHP 5 >= 5.1.0)

readline_callback_handler_remove — Removes 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_handler_install() - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  • readline_callback_read_char() - Reads a character and informs the readline callback interface when a line is received

readline_callback_handler_install
readline_callback_read_char
Funkcje Readline


Reads a character and informs the readline callback interface when a line is received

readline_callback_handler_remove
readline_clear_history
Funkcje Readline
PHP Manual

readline_callback_read_char

(PHP 5 >= 5.1.0)

readline_callback_read_char — Reads 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_callback_handler_install() - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
  • readline_callback_handler_remove() - Removes a previously installed callback handler and restores terminal settings

readline_callback_handler_remove
readline_clear_history
Funkcje Readline


Czyści historię

readline_callback_read_char
readline_completion_function
Funkcje Readline
PHP Manual

readline_clear_history

(PHP 4, PHP 5)

readline_clear_history — Czyś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_callback_read_char
readline_completion_function
Funkcje Readline


Rejestruje funkcję dopełniania

readline_clear_history
readline_info
Funkcje Readline
PHP Manual

readline_completion_function

(PHP 4, PHP 5)

readline_completion_function — Rejestruje 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_clear_history
readline_info
Funkcje Readline


Pobiera/ustawia różne wewnętrzne zmienne biblioteki readline

readline_completion_function
readline_list_history
Funkcje Readline
PHP Manual

readline_info

(PHP 4, PHP 5)

readline_info — Pobiera/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_completion_function
readline_list_history
Funkcje Readline


Zwraca historię wiersza poleceń

readline_info
readline_on_new_line
Funkcje Readline
PHP Manual

readline_list_history

(PHP 4, PHP 5)

readline_list_history — Zwraca 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_info
readline_on_new_line
Funkcje Readline


Inform readline that the cursor has moved to a new line

readline_list_history
readline_read_history
Funkcje Readline
PHP Manual

readline_on_new_line

(PHP 5 >= 5.1.0)

readline_on_new_line — Inform 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_list_history
readline_read_history
Funkcje Readline


Czyta historię

readline_on_new_line
readline_redisplay
Funkcje Readline
PHP Manual

readline_read_history

(PHP 4, PHP 5)

readline_read_history — Czyta 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_on_new_line
readline_redisplay
Funkcje Readline


Redraws the display

readline_read_history
readline_write_history
Funkcje Readline
PHP Manual

readline_redisplay

(PHP 5 >= 5.1.0)

readline_redisplay — Redraws the display

Opis

void readline_redisplay ( void )

Redraws readline to redraw the display.

Zwracane wartości

Nie jest zwracana żadna wartość.

readline_read_history
readline_write_history
Funkcje Readline


Zapisuje historię

readline_redisplay
readline
Funkcje Readline
PHP Manual

readline_write_history

(PHP 4, PHP 5)

readline_write_history — Zapisuje 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_redisplay
readline
Funkcje Readline


Czyta linię

readline_write_history
Rozszerzenia kompresji i archiwizacji
Funkcje Readline
PHP Manual

readline

(PHP 4, PHP 5)

readline — Czyta 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());
?>
readline_write_history
Rozszerzenia kompresji i archiwizacji
Funkcje Readline


Rozszerzenia kompresji i archiwizacji

  • Bzip2
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Funkcje Bzip2
  • LZF
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • LZF Funkcje
  • Phar
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Using Phar Archives
    • Creating Phar Archives
    • What makes a phar a phar and not a tar or a zip?
    • Phar — The Phar class
    • PharData — The PharData class
    • PharFileInfo — The PharFileInfo class
    • PharException — The PharException class
  • Rar — Rar Archiving
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Rar Funkcje
    • RarArchive — The RarArchive class
    • RarEntry — The RarEntry class
    • RarException — The RarException class
  • Zip
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • ZipArchive — The ZipArchive class
    • Zip Funkcje
  • Zlib — Zlib Compression
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Zlib Funkcje
readline
Bzip2
Opis funkcji


Bzip2

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Funkcje Bzip2
    • 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
Rozszerzenia kompresji i archiwizacji
Wstęp
Rozszerzenia kompresji i archiwizacji


Wstęp

Funkcje bzip2 są używane do odczytu i zapisu skompresowanych plików bzip2 (.bz2).

Bzip2
Instalacja/Konfiguracja
Bzip2


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Bzip2


Wymagania

Ten moduł używa funkcji z biblioteki » bzip2 stworzonej przez Juliana Seward'a. Moduł wymaga bzip2/libbzip2 w wersji >= 1.0.x.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

To rozszeżenie definiuje jeden typ zasobów: wskaźnik pliku identyfikujący plik bz2, na którym pracuje.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Bzip2


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($bz, 10);

// wyświetlaj dopóki nie nastąpi koniec pliku (lub następne 1024 znaki) i zamknij go.
echo bzread($bz);

bzclose($bz);

?>
Stałe predefiniowane
Funkcje Bzip2
Bzip2


Funkcje 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
Przykłady
bzclose
Bzip2


Zamyka otwarty plik bzip2

Funkcje Bzip2
bzcompress
Funkcje Bzip2
PHP Manual

bzclose

(PHP 4 >= 4.0.4, PHP 5)

bzclose — Zamyka 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

Funkcje Bzip2
bzcompress
Funkcje Bzip2


Compress a string into bzip2 encoded data

bzclose
bzdecompress
Funkcje Bzip2
PHP Manual

bzcompress

(PHP 4 >= 4.0.4, PHP 5)

bzcompress — Compress 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($str, 9);
echo $bzstr;
?>

Zobacz też:

  • bzdecompress() - Decompresses bzip2 encoded data

bzclose
bzdecompress
Funkcje Bzip2


Decompresses bzip2 encoded data

bzcompress
bzerrno
Funkcje Bzip2
PHP Manual

bzdecompress

(PHP 4 >= 4.0.4, PHP 5)

bzdecompress — Decompresses 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ż:

  • bzcompress() - Compress a string into bzip2 encoded data

bzcompress
bzerrno
Funkcje Bzip2


Zwraca numer błędu biblioteki bzip2.

bzdecompress
bzerror
Funkcje Bzip2
PHP Manual

bzerrno

(PHP 4 >= 4.0.4, PHP 5)

bzerrno — Zwraca 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

bzdecompress
bzerror
Funkcje Bzip2


Zwraca numer błędu bzip2 oraz opis błędu w postaci tablicy.

bzerrno
bzerrstr
Funkcje Bzip2
PHP Manual

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

  • bzerrno() - Zwraca numer błędu biblioteki bzip2.
  • bzerrstr() - Zwraca opis błędu bzip2

bzerrno
bzerrstr
Funkcje Bzip2


Zwraca opis błędu bzip2

bzerror
bzflush
Funkcje Bzip2
PHP Manual

bzerrstr

(PHP 4 >= 4.0.4, PHP 5)

bzerrstr — Zwraca 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.

bzerror
bzflush
Funkcje Bzip2


Wymusza zapisanie do pliku wszystkich danych z bufora

bzerrstr
bzopen
Funkcje Bzip2
PHP Manual

bzflush

(PHP 4 >= 4.0.4, PHP 5)

bzflush — Wymusza 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

bzerrstr
bzopen
Funkcje Bzip2


Otwiera skompresowany plik bzip2

bzflush
bzread
Funkcje Bzip2
PHP Manual

bzopen

(PHP 4 >= 4.0.4, PHP 5)

bzopen — Otwiera 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ż:

  • bzclose() - Zamyka otwarty plik bzip2

bzflush
bzread
Funkcje Bzip2


Binarnie bezpieczny odczyt pliku bzip2

bzopen
bzwrite
Funkcje Bzip2
PHP Manual

bzread

(PHP 4 >= 4.0.4, PHP 5)

bzread — Binarnie 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($bz, 4096);
}
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

bzopen
bzwrite
Funkcje Bzip2


Binarnie bezpieczny zapis plików bzip2

bzread
LZF
Funkcje Bzip2
PHP Manual

bzwrite

(PHP 4 >= 4.0.4, PHP 5)

bzwrite — Binarnie 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, $str, strlen($str));
bzclose($bz);
?>

Zobacz też:

  • bzread() - Binarnie bezpieczny odczyt pliku bzip2
  • bzopen() - Otwiera skompresowany plik bzip2

bzread
LZF
Funkcje Bzip2


LZF

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • LZF Funkcje
    • lzf_compress — LZF compression
    • lzf_decompress — LZF decompression
    • lzf_optimized_for — Determines what LZF extension was optimized for
bzwrite
Wstęp
Rozszerzenia kompresji i archiwizacji


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.

LZF
Instalacja/Konfiguracja
LZF


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
LZF


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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
LZF Funkcje
LZF


LZF Funkcje

Spis treści

  • lzf_compress — LZF compression
  • lzf_decompress — LZF decompression
  • lzf_optimized_for — Determines what LZF extension was optimized for
Stałe predefiniowane
lzf_compress
LZF


LZF compression

LZF Funkcje
lzf_decompress
LZF Funkcje
PHP Manual

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

LZF Funkcje
lzf_decompress
LZF Funkcje


LZF decompression

lzf_compress
lzf_optimized_for
LZF Funkcje
PHP Manual

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_compress() - LZF compression

lzf_compress
lzf_optimized_for
LZF Funkcje


Determines what LZF extension was optimized for

lzf_decompress
Phar
LZF Funkcje
PHP Manual

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.

lzf_decompress
Phar
LZF Funkcje


Phar

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Using Phar Archives
    • Using Phar Archives: Introduction
    • Using Phar Archives: the phar stream wrapper
    • Using Phar Archives: the Phar and PharData class
  • Creating Phar Archives
    • Creating Phar Archives: Introduction
  • What makes a phar a phar and not a tar or a zip?
    • Ingredients of all Phar archives, independent of file format
    • Phar file stub
    • Head-to-head comparison of Phar, Tar and Zip
    • Tar-based phars
    • Zip-based phars
    • Phar File Format
    • Global Phar bitmapped flags
    • Phar manifest file entry definition
    • Phar Signature format
  • Phar — The Phar class
    • Phar::addEmptyDir — Add an empty directory to the phar archive
    • Phar::addFile — Add a file from the filesystem to the phar archive
    • Phar::addFromString — Add a file from the filesystem to the phar archive
    • Phar::apiVersion — Returns the api version
    • Phar::buildFromDirectory — Construct a phar archive from the files within a directory.
    • Phar::buildFromIterator — Construct a phar archive from an iterator.
    • Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
    • Phar::canWrite — Returns whether phar extension supports writing and creating phars
    • Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
    • Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression
    • Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression
    • Phar::compressFiles — Compresses all files in the current Phar archive
    • Phar::__construct — Construct a Phar archive object
    • Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
    • Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
    • Phar::copy — Copy a file internal to the phar archive to another new file within the phar
    • Phar::count — Returns the number of entries (files) in the Phar archive
    • Phar::createDefaultStub — Create a phar-file format specific stub
    • Phar::decompress — Decompresses the entire Phar archive
    • Phar::decompressFiles — Decompresses all files in the current Phar archive
    • Phar::delMetadata — Deletes the global metadata of the phar
    • Phar::delete — Delete a file within a phar archive
    • Phar::extractTo — Extract the contents of a phar archive to a directory
    • Phar::getMetadata — Returns phar archive meta-data
    • Phar::getModified — Return whether phar was modified
    • Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
    • Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
    • Phar::getSupportedCompression — Return array of supported compression algorithms
    • Phar::getSupportedSignatures — Return array of supported signature types
    • Phar::getVersion — Return version info of Phar archive
    • Phar::hasMetadata — Returns whether phar has global meta-data
    • Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
    • Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
    • Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
    • Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
    • Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
    • Phar::isWritable — Returns true if the phar archive can be modified
    • Phar::loadPhar — Loads any phar archive with an alias
    • Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
    • Phar::mount — Mount an external path or file to a virtual location within the phar archive
    • Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
    • Phar::offsetExists — determines whether a file exists in the phar
    • Phar::offsetGet — Gets a PharFileInfo object for a specific file
    • Phar::offsetSet — set the contents of an internal file to those of an external file
    • Phar::offsetUnset — remove a file from a phar
    • Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
    • Phar::setAlias — Set the alias for the Phar archive
    • Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
    • Phar::setMetadata — Sets phar archive meta-data
    • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.
    • Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
    • Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
    • Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
    • Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive
    • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
    • Phar::webPhar — mapPhar for web-based phars. front controller for web applications
  • PharData — The PharData class
    • PharData::addEmptyDir — Add an empty directory to the tar/zip archive
    • PharData::addFile — Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString — Add a file from the filesystem to the tar/zip archive
    • PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.
    • PharData::buildFromIterator — Construct a tar or zip archive from an iterator.
    • PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles — Compresses all files in the current tar/zip archive
    • PharData::__construct — Construct a non-executable tar or zip archive object
    • PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy — Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress — Decompresses the entire Phar archive
    • PharData::decompressFiles — Decompresses all files in the current zip archive
    • PharData::delMetadata — Deletes the global metadata of a zip archive
    • PharData::delete — Delete a file within a tar/zip archive
    • PharData::extractTo — Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable — Returns true if the tar/zip archive can be modified
    • PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset — remove a file from a tar/zip archive
    • PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)
    • Phar::setMetadata — Sets phar archive meta-data
    • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The
    • PharData::setStub — dummy function (Phar::setStub is not valid for PharData)
  • PharFileInfo — The PharFileInfo class
    • PharFileInfo::chmod — Sets file-specific permission bits
    • PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::__construct — Construct a Phar entry object
    • PharFileInfo::decompress — Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata — Deletes the metadata of the entry
    • PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags — Returns the Phar file entry flags
    • PharFileInfo::hasMetadata — Returns the metadata of the entry
    • PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
    • PharFileInfo::isCompressed — Returns whether the entry is compressed
    • PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
    • PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
    • PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression
    • PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression
    • PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file
    • PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed
  • PharException — The PharException class
    • PharException — The PharException class provides a phar-specific exception class for try/catch blocks.
lzf_optimized_for
Wstęp
Rozszerzenia kompresji i archiwizacji


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::TAR, Phar::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.

Phar
Instalacja/Konfiguracja
Phar


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Phar


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/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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()
Typy zasobów
Using Phar Archives
Phar


Using Phar Archives

Spis treści

  • Using Phar Archives: Introduction
  • Using Phar Archives: the phar stream wrapper
  • Using Phar Archives: the Phar and PharData class
Stałe predefiniowane
Using Phar Archives: Introduction
Phar


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::TAR, Phar::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
Using Phar Archives: the phar stream wrapper
Using Phar Archives


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: Introduction
Using Phar Archives: the Phar and PharData class
Using Phar Archives


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.

Using Phar Archives: the phar stream wrapper
Creating Phar Archives
Using Phar Archives


Creating Phar Archives

Spis treści

  • Creating Phar Archives: Introduction
Using Phar Archives: the Phar and PharData class
Creating Phar Archives: Introduction
Phar


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

Creating Phar Archives
What makes a phar a phar and not a tar or a zip?
Creating Phar Archives


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
  • Phar file stub
  • Head-to-head comparison of Phar, Tar and Zip
  • Tar-based phars
  • Zip-based phars
  • Phar File Format
  • Global Phar bitmapped flags
  • Phar manifest file entry definition
  • Phar Signature format
Creating Phar Archives: Introduction
Ingredients of all Phar archives, independent of file format
Phar


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)

What makes a phar a phar and not a tar or a zip?
Phar file stub
What makes a phar a phar and not a tar or a zip?


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.

Ingredients of all Phar archives, independent of file format
Head-to-head comparison of Phar, Tar and Zip
What makes a phar a phar and not a tar or a zip?


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.

Phar file stub
Tar-based phars
What makes a phar a phar and not a tar or a zip?


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

Head-to-head comparison of Phar, Tar and Zip
Zip-based phars
What makes a phar a phar and not a tar or a zip?


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/

Tar-based phars
Phar File Format
What makes a phar a phar and not a tar or a zip?


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

Zip-based phars
Global Phar bitmapped flags
What makes a phar a phar and not a tar or a zip?


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 File Format
Phar manifest file entry definition
What makes a phar a phar and not a tar or a zip?


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

Global Phar bitmapped flags
Phar Signature format
What makes a phar a phar and not a tar or a zip?


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.

Phar manifest file entry definition
Phar
What makes a phar a phar and not a tar or a zip?


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 ]]]]] )
}

Spis treści

  • Phar::addEmptyDir — Add an empty directory to the phar archive
  • Phar::addFile — Add a file from the filesystem to the phar archive
  • Phar::addFromString — Add a file from the filesystem to the phar archive
  • Phar::apiVersion — Returns the api version
  • Phar::buildFromDirectory — Construct a phar archive from the files within a directory.
  • Phar::buildFromIterator — Construct a phar archive from an iterator.
  • Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::canWrite — Returns whether phar extension supports writing and creating phars
  • Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression
  • Phar::compressFiles — Compresses all files in the current Phar archive
  • Phar::__construct — Construct a Phar archive object
  • Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
  • Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
  • Phar::copy — Copy a file internal to the phar archive to another new file within the phar
  • Phar::count — Returns the number of entries (files) in the Phar archive
  • Phar::createDefaultStub — Create a phar-file format specific stub
  • Phar::decompress — Decompresses the entire Phar archive
  • Phar::decompressFiles — Decompresses all files in the current Phar archive
  • Phar::delMetadata — Deletes the global metadata of the phar
  • Phar::delete — Delete a file within a phar archive
  • Phar::extractTo — Extract the contents of a phar archive to a directory
  • Phar::getMetadata — Returns phar archive meta-data
  • Phar::getModified — Return whether phar was modified
  • Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  • Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::getSupportedCompression — Return array of supported compression algorithms
  • Phar::getSupportedSignatures — Return array of supported signature types
  • Phar::getVersion — Return version info of Phar archive
  • Phar::hasMetadata — Returns whether phar has global meta-data
  • Phar::interceptFileFuncs — instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
  • Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
  • Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
  • Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
  • Phar::isWritable — Returns true if the phar archive can be modified
  • Phar::loadPhar — Loads any phar archive with an alias
  • Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
  • Phar::mount — Mount an external path or file to a virtual location within the phar archive
  • Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
  • Phar::offsetExists — determines whether a file exists in the phar
  • Phar::offsetGet — Gets a PharFileInfo object for a specific file
  • Phar::offsetSet — set the contents of an internal file to those of an external file
  • Phar::offsetUnset — remove a file from a phar
  • Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
  • Phar::setAlias — Set the alias for the Phar archive
  • Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
  • Phar::setMetadata — Sets phar archive meta-data
  • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it.
  • Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
  • Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive
  • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
  • Phar::webPhar — mapPhar for web-based phars. front controller for web applications
Phar Signature format
Phar::addEmptyDir
Phar


Add an empty directory to the phar archive

Phar
Phar::addFile
Phar
PHP Manual

Phar::addEmptyDir

(Unknown)

Phar::addEmptyDir — Add 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ż:

  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • Phar::addFromString() - Add a file from the filesystem to the phar archive

Phar
Phar::addFile
Phar


Add a file from the filesystem to the phar archive

Phar::addEmptyDir
Phar::addFromString
Phar
PHP Manual

Phar::addFile

(Unknown)

Phar::addFile — Add 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::offsetSet() - set the contents of an internal file to those of an external file
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • Phar::addFromString() - Add a file from the filesystem to the phar archive
  • Phar::addEmptyDir() - Add an empty directory to the phar archive

Phar::addEmptyDir
Phar::addFromString
Phar


Add a file from the filesystem to the phar archive

Phar::addFile
Phar::apiVersion
Phar
PHP Manual

Phar::addFromString

(Unknown)

Phar::addFromString — Add 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::offsetSet() - set the contents of an internal file to those of an external file
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • Phar::addEmptyDir() - Add an empty directory to the phar archive

Phar::addFile
Phar::apiVersion
Phar


Returns the api version

Phar::addFromString
Phar::buildFromDirectory
Phar
PHP Manual

Phar::apiVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::apiVersion — Returns 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::addFromString
Phar::buildFromDirectory
Phar


Construct a phar archive from the files within a directory.

Phar::apiVersion
Phar::buildFromIterator
Phar
PHP Manual

Phar::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromDirectory — Construct 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() - Construct a phar archive from an iterator.

Phar::apiVersion
Phar::buildFromIterator
Phar


Construct a phar archive from an iterator.

Phar::buildFromDirectory
Phar::canCompress
Phar
PHP Manual

Phar::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromIterator — Construct 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::buildFromDirectory() - Construct a phar archive from the files within a directory.

Phar::buildFromDirectory
Phar::canCompress
Phar


Returns whether phar extension supports compression using either zlib or bzip2

Phar::buildFromIterator
Phar::canWrite
Phar
PHP Manual

Phar::canCompress

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canCompress — Returns 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

Phar::buildFromIterator
Phar::canWrite
Phar


Returns whether phar extension supports writing and creating phars

Phar::canCompress
Phar::compress
Phar
PHP Manual

Phar::canWrite

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canWrite — Returns 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.readonly
  • Phar::isWritable() - Returns true if the phar archive can be modified

Phar::canCompress
Phar::compress
Phar


Compresses the entire Phar archive using Gzip or Bzip2 compression

Phar::canWrite
Phar::compressAllFilesBZIP2
Phar
PHP Manual

Phar::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compress — Compresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

Phar::canWrite
Phar::compressAllFilesBZIP2
Phar


Compresses all files in the current Phar archive using Bzip2 compression

Phar::compress
Phar::compressAllFilesGZ
Phar
PHP Manual

Phar::compressAllFilesBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::compressAllFilesBZIP2 — Compresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

Phar::compress
Phar::compressAllFilesGZ
Phar


Compresses all files in the current Phar archive using Gzip compression

Phar::compressAllFilesBZIP2
Phar::compressFiles
Phar
PHP Manual

Phar::compressAllFilesGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::compressAllFilesGZ — Compresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

Phar::compressAllFilesBZIP2
Phar::compressFiles
Phar


Compresses all files in the current Phar archive

Phar::compressAllFilesGZ
Phar::__construct
Phar
PHP Manual

Phar::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compressFiles — Compresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive

Phar::compressAllFilesGZ
Phar::__construct
Phar


Construct a Phar archive object

Phar::compressFiles
Phar::convertToData
Phar
PHP Manual

Phar::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::__construct — Construct 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::compressFiles
Phar::convertToData
Phar


Convert a phar archive to a non-executable tar or zip file

Phar::__construct
Phar::convertToExecutable
Phar
PHP Manual

Phar::convertToData

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::convertToData — Convert 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::TAR, Phar::BZ2, '.tbz');
    // creates myphar.phar.tgz
    $phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    // handle the error here
}
?>

Zobacz też:

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

Phar::__construct
Phar::convertToExecutable
Phar


Convert a phar archive to another executable phar archive file format

Phar::convertToData
Phar::copy
Phar
PHP Manual

Phar::convertToExecutable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::convertToExecutable — Convert 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::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}
?>

Zobacz też:

  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

Phar::convertToData
Phar::copy
Phar


Copy a file internal to the phar archive to another new file within the phar

Phar::convertToExecutable
Phar::count
Phar
PHP Manual

Phar::copy

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::copy — Copy 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::convertToExecutable
Phar::count
Phar


Returns the number of entries (files) in the Phar archive

Phar::copy
Phar::createDefaultStub
Phar
PHP Manual

Phar::count

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::count — Returns 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::copy
Phar::createDefaultStub
Phar


Create a phar-file format specific stub

Phar::count
Phar::decompress
Phar
PHP Manual

Phar::createDefaultStub

(Unknown)

Phar::createDefaultStub — Create 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::count
Phar::decompress
Phar


Decompresses the entire Phar archive

Phar::createDefaultStub
Phar::decompressFiles
Phar
PHP Manual

Phar::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompress — Decompresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

Phar::createDefaultStub
Phar::decompressFiles
Phar


Decompresses all files in the current Phar archive

Phar::decompress
Phar::delMetadata
Phar
PHP Manual

Phar::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompressFiles — Decompresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive

Phar::decompress
Phar::delMetadata
Phar


Deletes the global metadata of the phar

Phar::decompressFiles
Phar::delete
Phar
PHP Manual

Phar::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::delMetadata — Deletes 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::getMetadata() - Returns phar archive meta-data
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data

Phar::decompressFiles
Phar::delete
Phar


Delete a file within a phar archive

Phar::delMetadata
Phar::extractTo
Phar
PHP Manual

Phar::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::delete — Delete 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ż:

  • PharData::delete() - Delete a file within a tar/zip archive
  • Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory

Phar::delMetadata
Phar::extractTo
Phar


Extract the contents of a phar archive to a directory

Phar::delete
Phar::getMetadata
Phar
PHP Manual

Phar::extractTo

(Unknown)

Phar::extractTo — Extract 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', null, true); // extract all files, and overwrite
} catch (Exception $e) {
    // handle errors
}
?>

Zobacz też:

  • PharData::extractTo() - Extract the contents of a tar/zip archive to a directory

Phar::delete
Phar::getMetadata
Phar


Returns phar archive meta-data

Phar::extractTo
Phar::getModified
Phar
PHP Manual

Phar::getMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getMetadata — Returns 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::setMetadata() - Sets phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

Phar::extractTo
Phar::getModified
Phar


Return whether phar was modified

Phar::getMetadata
Phar::getSignature
Phar
PHP Manual

Phar::getModified

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getModified — Return 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::getMetadata
Phar::getSignature
Phar


Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::getModified
Phar::getStub
Phar
PHP Manual

Phar::getSignature

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getSignature — Return 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::getModified
Phar::getStub
Phar


Return the PHP loader or bootstrap stub of a Phar archive

Phar::getSignature
Phar::getSupportedCompression
Phar
PHP Manual

Phar::getStub

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getStub — Return 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::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

Phar::getSignature
Phar::getSupportedCompression
Phar


Return array of supported compression algorithms

Phar::getStub
Phar::getSupportedSignatures
Phar
PHP Manual

Phar::getSupportedCompression

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::getSupportedCompression — Return 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

Phar::getStub
Phar::getSupportedSignatures
Phar


Return array of supported signature types

Phar::getSupportedCompression
Phar::getVersion
Phar
PHP Manual

Phar::getSupportedSignatures

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::getSupportedSignatures — Return 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::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  • Phar::setSignatureAlgorithm() - set the signature algorithm for a phar and apply it. The

Phar::getSupportedCompression
Phar::getVersion
Phar


Return version info of Phar archive

Phar::getSupportedSignatures
Phar::hasMetadata
Phar
PHP Manual

Phar::getVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getVersion — Return 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::apiVersion() - Returns the api version

Phar::getSupportedSignatures
Phar::hasMetadata
Phar


Returns whether phar has global meta-data

Phar::getVersion
Phar::interceptFileFuncs
Phar
PHP Manual

Phar::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::hasMetadata — Returns 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::getMetadata() - Returns phar archive meta-data
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar

Phar::getVersion
Phar::interceptFileFuncs
Phar


instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::hasMetadata
Phar::isBuffering
Phar
PHP Manual

Phar::interceptFileFuncs

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::interceptFileFuncs — instructs 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::hasMetadata
Phar::isBuffering
Phar


Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Phar::interceptFileFuncs
Phar::isCompressed
Phar
PHP Manual

Phar::isBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::isBuffering — Used 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::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk

Phar::interceptFileFuncs
Phar::isCompressed
Phar


Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Phar::isBuffering
Phar::isFileFormat
Phar
PHP Manual

Phar::isCompressed

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::isCompressed — Returns 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

Phar::isBuffering
Phar::isFileFormat
Phar


Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Phar::isCompressed
Phar::isValidPharFilename
Phar
PHP Manual

Phar::isFileFormat

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::isFileFormat — Returns 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::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

Phar::isCompressed
Phar::isValidPharFilename
Phar


Returns whether the given filename is a valid phar filename

Phar::isFileFormat
Phar::isWritable
Phar
PHP Manual

Phar::isValidPharFilename

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::isValidPharFilename — Returns 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::isFileFormat
Phar::isWritable
Phar


Returns true if the phar archive can be modified

Phar::isValidPharFilename
Phar::loadPhar
Phar
PHP Manual

Phar::isWritable

(Unknown)

Phar::isWritable — Returns 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::canWrite() - Returns whether phar extension supports writing and creating phars
  • PharData::isWritable() - Returns true if the tar/zip archive can be modified

Phar::isValidPharFilename
Phar::loadPhar
Phar


Loads any phar archive with an alias

Phar::isWritable
Phar::mapPhar
Phar
PHP Manual

Phar::loadPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::loadPhar — Loads 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::isWritable
Phar::mapPhar
Phar


Reads the currently executed file (a phar) and registers its manifest

Phar::loadPhar
Phar::mount
Phar
PHP Manual

Phar::mapPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::mapPhar — Reads 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::loadPhar() - Loads any phar archive with an alias

Phar::loadPhar
Phar::mount
Phar


Mount an external path or file to a virtual location within the phar archive

Phar::mapPhar
Phar::mungServer
Phar
PHP Manual

Phar::mount

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::mount — Mount 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::mapPhar
Phar::mungServer
Phar


Defines a list of up to 4 $_SERVER variables that should be modified for execution

Phar::mount
Phar::offsetExists
Phar
PHP Manual

Phar::mungServer

(Unknown)

Phar::mungServer — Defines 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::mount
Phar::offsetExists
Phar


determines whether a file exists in the phar

Phar::mungServer
Phar::offsetGet
Phar
PHP Manual

Phar::offsetExists

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetExists — determines 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() - Gets a PharFileInfo object for a specific file
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::offsetUnset() - remove a file from a phar

Phar::mungServer
Phar::offsetGet
Phar


Gets a PharFileInfo object for a specific file

Phar::offsetExists
Phar::offsetSet
Phar
PHP Manual

Phar::offsetGet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetGet — Gets 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::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::offsetUnset() - remove a file from a phar

Phar::offsetExists
Phar::offsetSet
Phar


set the contents of an internal file to those of an external file

Phar::offsetGet
Phar::offsetUnset
Phar
PHP Manual

Phar::offsetSet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetSet — set 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::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetUnset() - remove a file from a phar

Phar::offsetGet
Phar::offsetUnset
Phar


remove a file from a phar

Phar::offsetSet
Phar::running
Phar
PHP Manual

Phar::offsetUnset

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetUnset — remove 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::offsetExists() - determines whether a file exists in the phar
  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetSet() - set the contents of an internal file to those of an external file
  • Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory
  • Phar::delete() - Delete a file within a phar archive

Phar::offsetSet
Phar::running
Phar


Returns the full path on disk or full phar URL to the currently executing Phar archive

Phar::offsetUnset
Phar::setAlias
Phar
PHP Manual

Phar::running

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::running — Returns 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::offsetUnset
Phar::setAlias
Phar


Set the alias for the Phar archive

Phar::running
Phar::setDefaultStub
Phar
PHP Manual

Phar::setAlias

(PHP >= 5.3.0, PECL phar >= 1.2.1)

Phar::setAlias — Set 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::__construct() - Construct a Phar archive object
  • Phar::interceptFileFuncs() - instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::running
Phar::setDefaultStub
Phar


Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Phar::setAlias
Phar::setMetadata
Phar
PHP Manual

Phar::setDefaultStub

(Unknown)

Phar::setDefaultStub — Used 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::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

Phar::setAlias
Phar::setMetadata
Phar


Sets phar archive meta-data

Phar::setDefaultStub
Phar::setSignatureAlgorithm
Phar
PHP Manual

Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadata — Sets 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::getMetadata() - Returns phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

Phar::setDefaultStub
Phar::setSignatureAlgorithm
Phar


set the signature algorithm for a phar and apply it.

Phar::setMetadata
Phar::setStub
Phar
PHP Manual

Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — set 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::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::setMetadata
Phar::setStub
Phar


Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::setSignatureAlgorithm
Phar::startBuffering
Phar
PHP Manual

Phar::setStub

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setStub — Used 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::getStub() - Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

Phar::setSignatureAlgorithm
Phar::startBuffering
Phar


Start buffering Phar write operations, do not modify the Phar object on disk

Phar::setStub
Phar::stopBuffering
Phar
PHP Manual

Phar::startBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::startBuffering — Start 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::setStub
Phar::stopBuffering
Phar


Stop buffering write requests to the Phar archive, and save changes to disk

Phar::startBuffering
Phar::uncompressAllFiles
Phar
PHP Manual

Phar::stopBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::stopBuffering — Stop 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::startBuffering
Phar::uncompressAllFiles
Phar


Uncompresses all files in the current Phar archive

Phar::stopBuffering
Phar::unlinkArchive
Phar
PHP Manual

Phar::uncompressAllFiles

(PECL phar < 2.0.0)

Phar::uncompressAllFiles — Uncompresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

Phar::stopBuffering
Phar::unlinkArchive
Phar


Completely remove a phar archive from disk and from memory

Phar::uncompressAllFiles
Phar::webPhar
Phar
PHP Manual

Phar::unlinkArchive

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::unlinkArchive — Completely 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::delete() - Delete a file within a phar archive
  • Phar::offsetUnset() - remove a file from a phar

Phar::uncompressAllFiles
Phar::webPhar
Phar


mapPhar for web-based phars. front controller for web applications

Phar::unlinkArchive
PharData
Phar
PHP Manual

Phar::webPhar

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::webPhar — mapPhar 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

Phar::unlinkArchive
PharData
Phar


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 ] )
bool Phar::compressAllFilesBZIP2 ( void )
bool Phar::compressAllFilesGZ ( void )
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 )
array Phar::getSupportedCompression ( void )
array Phar::getSupportedSignatures ( void )
string Phar::getVersion ( void )
bool Phar::hasMetadata ( void )
void Phar::interceptFileFuncs ( 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::uncompressAllFiles ( void )
bool Phar::unlinkArchive ( string $archive )
void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $rewrites ]]]]] )
}

Spis treści

  • PharData::addEmptyDir — Add an empty directory to the tar/zip archive
  • PharData::addFile — Add a file from the filesystem to the tar/zip archive
  • PharData::addFromString — Add a file from the filesystem to the tar/zip archive
  • PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory.
  • PharData::buildFromIterator — Construct a tar or zip archive from an iterator.
  • PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::compressFiles — Compresses all files in the current tar/zip archive
  • PharData::__construct — Construct a non-executable tar or zip archive object
  • PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::copy — Copy a file internal to the phar archive to another new file within the phar
  • PharData::decompress — Decompresses the entire Phar archive
  • PharData::decompressFiles — Decompresses all files in the current zip archive
  • PharData::delMetadata — Deletes the global metadata of a zip archive
  • PharData::delete — Delete a file within a tar/zip archive
  • PharData::extractTo — Extract the contents of a tar/zip archive to a directory
  • PharData::isWritable — Returns true if the tar/zip archive can be modified
  • PharData::offsetSet — set the contents of a file within the tar/zip to those of an external file or string
  • PharData::offsetUnset — remove a file from a tar/zip archive
  • PharData::setAlias — dummy function (Phar::setAlias is not valid for PharData)
  • PharData::setDefaultStub — dummy function (Phar::setDefaultStub is not valid for PharData)
  • Phar::setMetadata — Sets phar archive meta-data
  • Phar::setSignatureAlgorithm — set the signature algorithm for a phar and apply it. The
  • PharData::setStub — dummy function (Phar::setStub is not valid for PharData)
Phar::webPhar
PharData::addEmptyDir
Phar


Add an empty directory to the tar/zip archive

PharData
PharData::addFile
PharData
PHP Manual

PharData::addEmptyDir

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addEmptyDir — Add 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ż:

  • Phar::addEmptyDir() - Add an empty directory to the phar archive
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive

PharData
PharData::addFile
PharData


Add a file from the filesystem to the tar/zip archive

PharData::addEmptyDir
PharData::addFromString
PharData
PHP Manual

PharData::addFile

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addFile — Add 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::offsetSet() - set the contents of a file within the tar/zip to those of an external file or string
  • Phar::addFile() - Add a file from the filesystem to the phar archive
  • PharData::addFromString() - Add a file from the filesystem to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

PharData::addEmptyDir
PharData::addFromString
PharData


Add a file from the filesystem to the tar/zip archive

PharData::addFile
PharData::buildFromDirectory
PharData
PHP Manual

PharData::addFromString

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addFromString — Add 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::offsetSet() - set the contents of a file within the tar/zip to those of an external file or string
  • Phar::addFromString() - Add a file from the filesystem to the phar archive
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

PharData::addFile
PharData::buildFromDirectory
PharData


Construct a tar/zip archive from the files within a directory.

PharData::addFromString
PharData::buildFromIterator
PharData
PHP Manual

PharData::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::buildFromDirectory — Construct 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ż:

  • Phar::buildFromDirectory() - Construct a phar archive from the files within a directory.
  • PharData::buildFromIterator() - Construct a tar or zip archive from an iterator.

PharData::addFromString
PharData::buildFromIterator
PharData


Construct a tar or zip archive from an iterator.

PharData::buildFromDirectory
PharData::compress
PharData
PHP Manual

PharData::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::buildFromIterator — Construct 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ż:

  • Phar::buildFromIterator() - Construct a phar archive from an iterator.

PharData::buildFromDirectory
PharData::compress
PharData


Compresses the entire tar/zip archive using Gzip or Bzip2 compression

PharData::buildFromIterator
PharData::compressFiles
PharData
PHP Manual

PharData::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::compress — Compresses 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::buildFromIterator
PharData::compressFiles
PharData


Compresses all files in the current tar/zip archive

PharData::compress
PharData::__construct
PharData
PHP Manual

PharData::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::compressFiles — Compresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::decompressFiles() - Decompresses all files in the current zip archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::decompress() - Decompresses the entire Phar archive

PharData::compress
PharData::__construct
PharData


Construct a non-executable tar or zip archive object

PharData::compressFiles
PharData::convertToData
PharData
PHP Manual

PharData::__construct

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::__construct — Construct 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::compressFiles
PharData::convertToData
PharData


Convert a phar archive to a non-executable tar or zip file

PharData::__construct
PharData::convertToExecutable
PharData
PHP Manual

PharData::convertToData

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::convertToData — Convert 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::TAR, Phar::BZ2, '.tbz');
    // creates myphar.phar.tgz
    $phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    // handle the error here
}
?>

Zobacz też:

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive

PharData::__construct
PharData::convertToExecutable
PharData


Convert a non-executable tar/zip archive to an executable phar archive

PharData::convertToData
PharData::copy
PharData
PHP Manual

PharData::convertToExecutable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::convertToExecutable — Convert 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::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
    // handle the error here
}
?>

Zobacz też:

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

PharData::convertToData
PharData::copy
PharData


Copy a file internal to the phar archive to another new file within the phar

PharData::convertToExecutable
PharData::decompress
PharData
PHP Manual

PharData::copy

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::copy — Copy 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::convertToExecutable
PharData::decompress
PharData


Decompresses the entire Phar archive

PharData::copy
PharData::decompressFiles
PharData
PHP Manual

PharData::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::decompress — Decompresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compressFiles() - Compresses all files in the current tar/zip archive
  • PharData::decompressFiles() - Decompresses all files in the current zip archive

PharData::copy
PharData::decompressFiles
PharData


Decompresses all files in the current zip archive

PharData::decompress
PharData::delMetadata
PharData
PHP Manual

PharData::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::decompressFiles — Decompresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::compressFiles() - Compresses all files in the current tar/zip archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::decompress() - Decompresses the entire Phar archive

PharData::decompress
PharData::delMetadata
PharData


Deletes the global metadata of a zip archive

PharData::decompressFiles
PharData::delete
PharData
PHP Manual

PharData::delMetadata

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::delMetadata — Deletes 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ż:

  • Phar::delMetadata() - Deletes the global metadata of the phar

PharData::decompressFiles
PharData::delete
PharData


Delete a file within a tar/zip archive

PharData::delMetadata
PharData::extractTo
PharData
PHP Manual

PharData::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::delete — Delete 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ż:

  • Phar::delete() - Delete a file within a phar archive

PharData::delMetadata
PharData::extractTo
PharData


Extract the contents of a tar/zip archive to a directory

PharData::delete
PharData::isWritable
PharData
PHP Manual

PharData::extractTo

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::extractTo — Extract 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', null, true); // extract all files, and overwrite
} catch (Exception $e) {
    // handle errors
}
?>

Zobacz też:

  • Phar::extractTo() - Extract the contents of a phar archive to a directory

PharData::delete
PharData::isWritable
PharData


Returns true if the tar/zip archive can be modified

PharData::extractTo
PharData::offsetSet
PharData
PHP Manual

PharData::isWritable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::isWritable — Returns 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ż:

  • Phar::canWrite() - Returns whether phar extension supports writing and creating phars
  • Phar::isWritable() - Returns true if the phar archive can be modified

PharData::extractTo
PharData::offsetSet
PharData


set the contents of a file within the tar/zip to those of an external file or string

PharData::isWritable
PharData::offsetUnset
PharData
PHP Manual

PharData::offsetSet

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::offsetSet — set 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::isWritable
PharData::offsetUnset
PharData


remove a file from a tar/zip archive

PharData::offsetSet
PharData::setAlias
PharData
PHP Manual

PharData::offsetUnset

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::offsetUnset — remove 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ż:

  • Phar::offsetUnset() - remove a file from a phar

PharData::offsetSet
PharData::setAlias
PharData


dummy function (Phar::setAlias is not valid for PharData)

PharData::offsetUnset
PharData::setDefaultStub
PharData
PHP Manual

PharData::setAlias

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setAlias — dummy 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ż:

  • Phar::setAlias() - Set the alias for the Phar archive

PharData::offsetUnset
PharData::setDefaultStub
PharData


dummy function (Phar::setDefaultStub is not valid for PharData)

PharData::setAlias
Phar::setMetadata
PharData
PHP Manual

PharData::setDefaultStub

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setDefaultStub — dummy 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

PharData::setAlias
Phar::setMetadata
PharData


Sets phar archive meta-data

PharData::setDefaultStub
Phar::setSignatureAlgorithm
PharData
PHP Manual

Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadata — Sets 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::getMetadata() - Returns phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

PharData::setDefaultStub
Phar::setSignatureAlgorithm
PharData


set the signature algorithm for a phar and apply it. The

Phar::setMetadata
PharData::setStub
PharData
PHP Manual

Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — set 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ż:

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::setMetadata
PharData::setStub
PharData


dummy function (Phar::setStub is not valid for PharData)

Phar::setSignatureAlgorithm
PharFileInfo
PharData
PHP Manual

PharData::setStub

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setStub — dummy 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

Phar::setSignatureAlgorithm
PharFileInfo
PharData


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

Spis treści

  • PharFileInfo::chmod — Sets file-specific permission bits
  • PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::__construct — Construct a Phar entry object
  • PharFileInfo::decompress — Decompresses the current Phar entry within the phar
  • PharFileInfo::delMetadata — Deletes the metadata of the entry
  • PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
  • PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
  • PharFileInfo::getPharFlags — Returns the Phar file entry flags
  • PharFileInfo::hasMetadata — Returns the metadata of the entry
  • PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
  • PharFileInfo::isCompressed — Returns whether the entry is compressed
  • PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression
  • PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file
  • PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed
PharData::setStub
PharFileInfo::chmod
Phar


Sets file-specific permission bits

PharFileInfo
PharFileInfo::compress
PharFileInfo
PHP Manual

PharFileInfo::chmod

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::chmod — Sets 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
PharFileInfo::compress
PharFileInfo


Compresses the current Phar entry with either zlib or bzip2 compression

PharFileInfo::chmod
PharFileInfo::__construct
PharFileInfo
PHP Manual

PharFileInfo::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::compress — Compresses 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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

PharFileInfo::chmod
PharFileInfo::__construct
PharFileInfo


Construct a Phar entry object

PharFileInfo::compress
PharFileInfo::decompress
PharFileInfo
PHP Manual

PharFileInfo::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::__construct — Construct 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::compress
PharFileInfo::decompress
PharFileInfo


Decompresses the current Phar entry within the phar

PharFileInfo::__construct
PharFileInfo::delMetadata
PharFileInfo
PHP Manual

PharFileInfo::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::decompress — Decompresses 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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

PharFileInfo::__construct
PharFileInfo::delMetadata
PharFileInfo


Deletes the metadata of the entry

PharFileInfo::decompress
PharFileInfo::getCRC32
PharFileInfo
PHP Manual

PharFileInfo::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::delMetadata — Deletes 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::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

PharFileInfo::decompress
PharFileInfo::getCRC32
PharFileInfo


Returns CRC32 code or throws an exception if CRC has not been verified

PharFileInfo::delMetadata
PharFileInfo::getCompressedSize
PharFileInfo
PHP Manual

PharFileInfo::getCRC32

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getCRC32 — Returns 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::delMetadata
PharFileInfo::getCompressedSize
PharFileInfo


Returns the actual size of the file (with compression) inside the Phar archive

PharFileInfo::getCRC32
PharFileInfo::getMetadata
PharFileInfo
PHP Manual

PharFileInfo::getCompressedSize

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getCompressedSize — Returns 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::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compressFiles() - Compresses all files in the current Phar archive

PharFileInfo::getCRC32
PharFileInfo::getMetadata
PharFileInfo


Returns file-specific meta-data saved with a file

PharFileInfo::getCompressedSize
PharFileInfo::getPharFlags
PharFileInfo
PHP Manual

PharFileInfo::getMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getMetadata — Returns 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::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

PharFileInfo::getCompressedSize
PharFileInfo::getPharFlags
PharFileInfo


Returns the Phar file entry flags

PharFileInfo::getMetadata
PharFileInfo::hasMetadata
PharFileInfo
PHP Manual

PharFileInfo::getPharFlags

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getPharFlags — Returns 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::getMetadata
PharFileInfo::hasMetadata
PharFileInfo


Returns the metadata of the entry

PharFileInfo::getPharFlags
PharFileInfo::isCRCChecked
PharFileInfo
PHP Manual

PharFileInfo::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::hasMetadata — Returns 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::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

PharFileInfo::getPharFlags
PharFileInfo::isCRCChecked
PharFileInfo


Returns whether file entry has had its CRC verified

PharFileInfo::hasMetadata
PharFileInfo::isCompressed
PharFileInfo
PHP Manual

PharFileInfo::isCRCChecked

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCRCChecked — Returns 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::hasMetadata
PharFileInfo::isCompressed
PharFileInfo


Returns whether the entry is compressed

PharFileInfo::isCRCChecked
PharFileInfo::isCompressedBZIP2
PharFileInfo
PHP Manual

PharFileInfo::isCompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressed — Returns 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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compressFiles() - Compresses all files in the current Phar archive

PharFileInfo::isCRCChecked
PharFileInfo::isCompressedBZIP2
PharFileInfo


Returns whether the entry is compressed using bzip2

PharFileInfo::isCompressed
PharFileInfo::isCompressedGZ
PharFileInfo
PHP Manual

PharFileInfo::isCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedBZIP2 — Returns 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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::isCompressed
PharFileInfo::isCompressedGZ
PharFileInfo


Returns whether the entry is compressed using gz

PharFileInfo::isCompressedBZIP2
PharFileInfo::setCompressedBZIP2
PharFileInfo
PHP Manual

PharFileInfo::isCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedGZ — Returns 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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::isCompressedBZIP2
PharFileInfo::setCompressedBZIP2
PharFileInfo


Compresses the current Phar entry within the phar using Bzip2 compression

PharFileInfo::isCompressedGZ
PharFileInfo::setCompressedGZ
PharFileInfo
PHP Manual

PharFileInfo::setCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setCompressedBZIP2 — Compresses 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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::isCompressedGZ
PharFileInfo::setCompressedGZ
PharFileInfo


Compresses the current Phar entry within the phar using gz compression

PharFileInfo::setCompressedBZIP2
PharFileInfo::setMetadata
PharFileInfo
PHP Manual

PharFileInfo::setCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setCompressedGZ — Compresses 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::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::setCompressedBZIP2
PharFileInfo::setMetadata
PharFileInfo


Sets file-specific meta-data saved with a file

PharFileInfo::setCompressedGZ
PharFileInfo::setUncompressed
PharFileInfo
PHP Manual

PharFileInfo::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setMetadata — Sets 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::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

PharFileInfo::setCompressedGZ
PharFileInfo::setUncompressed
PharFileInfo


Uncompresses the current Phar entry within the phar, if it is compressed

PharFileInfo::setMetadata
PharException
PharFileInfo
PHP Manual

PharFileInfo::setUncompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setUncompressed — Uncompresses 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ż:

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive

PharFileInfo::setMetadata
PharException
PharFileInfo


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 */
}

Spis treści

  • PharException — The PharException class provides a phar-specific exception class for try/catch blocks.
PharFileInfo::setUncompressed
PharException
Phar


The PharException class provides a phar-specific exception class for try/catch blocks.

PharException
Rar
PharException
PHP Manual

PharException

(Unknown)

PharException — The PharException class provides a phar-specific exception class for try/catch blocks.

Opis

PharException
Rar
PharException
PHP Manual


Rar Archiving

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Rar Funkcje
    • rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper
  • RarArchive — The RarArchive class
    • RarArchive::close — Close RAR archive and free all resources
    • RarArchive::getComment — Get comment text from the RAR archive
    • RarArchive::getEntries — Get full list of entries from the RAR archive
    • RarArchive::getEntry — Get entry object from the RAR archive
    • RarArchive::isBroken — Test whether an archive is broken (incomplete)
    • RarArchive::isSolid — Check whether the RAR archive is solid
    • RarArchive::open — Open RAR archive
    • RarArchive::setAllowBroken — Whether opening broken archives is allowed
    • RarArchive::__toString — Get text representation
  • RarEntry — The RarEntry class
    • RarEntry::extract — Extract entry from the archive
    • RarEntry::getAttr — Get attributes of the entry
    • RarEntry::getCrc — Get CRC of the entry
    • RarEntry::getFileTime — Get entry last modification time
    • RarEntry::getHostOs — Get entry host OS
    • RarEntry::getMethod — Get pack method of the entry
    • RarEntry::getName — Get name of the entry
    • RarEntry::getPackedSize — Get packed size of the entry
    • RarEntry::getStream — Get file handler for entry
    • RarEntry::getUnpackedSize — Get unpacked size of the entry
    • RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry
    • RarEntry::isDirectory — Test whether an entry represents a directory
    • RarEntry::isEncrypted — Test whether an entry is encrypted
    • RarEntry::__toString — Get text representation of entry
  • RarException — The RarException class
    • RarException::isUsingExceptions — Check whether error handling with exceptions is in use
    • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions
PharException
Wstęp
Rozszerzenia kompresji i archiwizacji


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

Rar
Instalacja/Konfiguracja
Rar


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Rar


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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.
Typy zasobów
Przykłady
Rar


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($fp, 8192);
    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.

Stałe predefiniowane
Rar Funkcje
Rar


Rar Funkcje

Spis treści

  • rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper
Przykłady
rar_wrapper_cache_stats
Rar


Cache hits and misses for the URL wrapper

Rar Funkcje
RarArchive
Rar Funkcje
PHP Manual

rar_wrapper_cache_stats

(PECL rar >= 3.0.0)

rar_wrapper_cache_stats — Cache 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

Rar Funkcje
RarArchive
Rar Funkcje


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 [, callback $volume_callback = NULL ]] )
public bool setAllowBroken ( bool $allow_broken )
public string __toString ( void )
}

Spis treści

  • RarArchive::close — Close RAR archive and free all resources
  • RarArchive::getComment — Get comment text from the RAR archive
  • RarArchive::getEntries — Get full list of entries from the RAR archive
  • RarArchive::getEntry — Get entry object from the RAR archive
  • RarArchive::isBroken — Test whether an archive is broken (incomplete)
  • RarArchive::isSolid — Check whether the RAR archive is solid
  • RarArchive::open — Open RAR archive
  • RarArchive::setAllowBroken — Whether opening broken archives is allowed
  • RarArchive::__toString — Get text representation
rar_wrapper_cache_stats
RarArchive::close
Rar


Close RAR archive and free all resources

RarArchive
RarArchive::getComment
RarArchive
PHP Manual

RarArchive::close

rar_close

(PECL rar >= 2.0.0)

RarArchive::close -- rar_close — Close 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
RarArchive::getComment
RarArchive


Get comment text from the RAR archive

RarArchive::close
RarArchive::getEntries
RarArchive
PHP Manual

RarArchive::getComment

rar_comment_get

(PECL rar >= 2.0.0)

RarArchive::getComment -- rar_comment_get — Get 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::close
RarArchive::getEntries
RarArchive


Get full list of entries from the RAR archive

RarArchive::getComment
RarArchive::getEntry
RarArchive
PHP Manual

RarArchive::getEntries

rar_list

(PECL rar >= 2.0.0)

RarArchive::getEntries -- rar_list — Get 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() - Get entry object from the RAR archive
  • rar:// wrapper

RarArchive::getComment
RarArchive::getEntry
RarArchive


Get entry object from the RAR archive

RarArchive::getEntries
RarArchive::isBroken
RarArchive
PHP Manual

RarArchive::getEntry

rar_entry_get

(PECL rar >= 2.0.0)

RarArchive::getEntry -- rar_entry_get — Get 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::getEntries() - Get full list of entries from the RAR archive
  • rar:// wrapper

RarArchive::getEntries
RarArchive::isBroken
RarArchive


Test whether an archive is broken (incomplete)

RarArchive::getEntry
RarArchive::isSolid
RarArchive
PHP Manual

RarArchive::isBroken

rar_broken_is

(PECL rar >= 3.0.0)

RarArchive::isBroken -- rar_broken_is — Test 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($file, null, '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($file, null, 'retnull');
var_dump(rar_broken_is($arch));
?>

Zobacz też:

  • RarArchive::setAllowBroken() - Whether opening broken archives is allowed

RarArchive::getEntry
RarArchive::isSolid
RarArchive


Check whether the RAR archive is solid

RarArchive::isBroken
RarArchive::open
RarArchive
PHP Manual

RarArchive::isSolid

rar_solid_is

(PECL rar >= 2.0.0)

RarArchive::isSolid -- rar_solid_is — Check 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::isBroken
RarArchive::open
RarArchive


Open RAR archive

RarArchive::isSolid
RarArchive::setAllowBroken
RarArchive
PHP Manual

RarArchive::open

rar_open

(PECL rar >= 2.0.0)

RarArchive::open -- rar_open — Open RAR archive

Opis

Styl obiektowy (method):

public static RarArchive RarArchive::open ( string $filename [, string $password = NULL [, callback $volume_callback = NULL ]] )

Styl proceduralny:

RarArchive rar_open ( string $filename [, string $password = NULL [, callback $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(null, dirname(__FILE__) . "/temp_file2.txt");
?>

Zobacz też:

  • rar:// wrapper

RarArchive::isSolid
RarArchive::setAllowBroken
RarArchive


Whether opening broken archives is allowed

RarArchive::open
RarArchive::__toString
RarArchive
PHP Manual

RarArchive::setAllowBroken

(PECL rar >= 3.0.0)

RarArchive::setAllowBroken — Whether 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($file, null, '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($file, null, 'retnull');
rar_allow_broken_set($a, true);
foreach (rar_list($a) as $e) {
    echo "$e\n";
}
var_dump(count($a));
?>

Zobacz też:

  • RarArchive::isBroken() - Test whether an archive is broken (incomplete)

RarArchive::open
RarArchive::__toString
RarArchive


Get text representation

RarArchive::setAllowBroken
RarEntry
RarArchive
PHP Manual

RarArchive::__toString

(PECL rar >= 2.0.0)

RarArchive::__toString — Get 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)

RarArchive::setAllowBroken
RarEntry
RarArchive


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.

RarEntry::ATTRIBUTE_UNIX_SYM_LINK

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.

Spis treści

  • RarEntry::extract — Extract entry from the archive
  • RarEntry::getAttr — Get attributes of the entry
  • RarEntry::getCrc — Get CRC of the entry
  • RarEntry::getFileTime — Get entry last modification time
  • RarEntry::getHostOs — Get entry host OS
  • RarEntry::getMethod — Get pack method of the entry
  • RarEntry::getName — Get name of the entry
  • RarEntry::getPackedSize — Get packed size of the entry
  • RarEntry::getStream — Get file handler for entry
  • RarEntry::getUnpackedSize — Get unpacked size of the entry
  • RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry
  • RarEntry::isDirectory — Test whether an entry represents a directory
  • RarEntry::isEncrypted — Test whether an entry is encrypted
  • RarEntry::__toString — Get text representation of entry
RarArchive::__toString
RarEntry::extract
Rar


Extract entry from the archive

RarEntry
RarEntry::getAttr
RarEntry
PHP Manual

RarEntry::extract

(PECL rar >= 0.1)

RarEntry::extract — Extract 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::getStream() - Get file handler for entry
  • rar:// wrapper

RarEntry
RarEntry::getAttr
RarEntry


Get attributes of the entry

RarEntry::extract
RarEntry::getCrc
RarEntry
PHP Manual

RarEntry::getAttr

(PECL rar >= 0.1)

RarEntry::getAttr — Get 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::getHostOs() - Get entry host OS
  • The constants in RarEntry

RarEntry::extract
RarEntry::getCrc
RarEntry


Get CRC of the entry

RarEntry::getAttr
RarEntry::getFileTime
RarEntry
PHP Manual

RarEntry::getCrc

(PECL rar >= 0.1)

RarEntry::getCrc — Get 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::getAttr
RarEntry::getFileTime
RarEntry


Get entry last modification time

RarEntry::getCrc
RarEntry::getHostOs
RarEntry
PHP Manual

RarEntry::getFileTime

(PECL rar >= 0.1)

RarEntry::getFileTime — Get 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::getCrc
RarEntry::getHostOs
RarEntry


Get entry host OS

RarEntry::getFileTime
RarEntry::getMethod
RarEntry
PHP Manual

RarEntry::getHostOs

(PECL rar >= 0.1)

RarEntry::getHostOs — Get 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::extract() - Extract entry from the archive

RarEntry::getFileTime
RarEntry::getMethod
RarEntry


Get pack method of the entry

RarEntry::getHostOs
RarEntry::getName
RarEntry
PHP Manual

RarEntry::getMethod

(PECL rar >= 0.1)

RarEntry::getMethod — Get 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::getHostOs
RarEntry::getName
RarEntry


Get name of the entry

RarEntry::getMethod
RarEntry::getPackedSize
RarEntry
PHP Manual

RarEntry::getName

(PECL rar >= 0.1)

RarEntry::getName — Get 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::getMethod
RarEntry::getPackedSize
RarEntry


Get packed size of the entry

RarEntry::getName
RarEntry::getStream
RarEntry
PHP Manual

RarEntry::getPackedSize

(PECL rar >= 0.1)

RarEntry::getPackedSize — Get 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::getName
RarEntry::getStream
RarEntry


Get file handler for entry

RarEntry::getPackedSize
RarEntry::getUnpackedSize
RarEntry
PHP Manual

RarEntry::getStream

(PECL rar >= 2.0.0)

RarEntry::getStream — Get 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($stream, 8192);
    if ($buff !== false)
        echo $buff;
    else
        break; //fread error
}

fclose($stream);

?>

Zobacz też:

  • RarEntry::extract() - Extract entry from the archive
  • rar:// wrapper

RarEntry::getPackedSize
RarEntry::getUnpackedSize
RarEntry


Get unpacked size of the entry

RarEntry::getStream
RarEntry::getVersion
RarEntry
PHP Manual

RarEntry::getUnpackedSize

(PECL rar >= 0.1)

RarEntry::getUnpackedSize — Get 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::getStream
RarEntry::getVersion
RarEntry


Get minimum version of RAR program required to unpack the entry

RarEntry::getUnpackedSize
RarEntry::isDirectory
RarEntry
PHP Manual

RarEntry::getVersion

(PECL rar >= 0.1)

RarEntry::getVersion — Get 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::getUnpackedSize
RarEntry::isDirectory
RarEntry


Test whether an entry represents a directory

RarEntry::getVersion
RarEntry::isEncrypted
RarEntry
PHP Manual

RarEntry::isDirectory

(PECL rar >= 2.0.0)

RarEntry::isDirectory — Test 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::getVersion
RarEntry::isEncrypted
RarEntry


Test whether an entry is encrypted

RarEntry::isDirectory
RarEntry::__toString
RarEntry
PHP Manual

RarEntry::isEncrypted

(PECL rar >= 2.0.0)

RarEntry::isEncrypted — Test 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::isDirectory
RarEntry::__toString
RarEntry


Get text representation of entry

RarEntry::isEncrypted
RarException
RarEntry
PHP Manual

RarEntry::__toString

(PECL rar >= 2.0.0)

RarEntry::__toString — Get 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.

RarEntry::isEncrypted
RarException
RarEntry


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

Spis treści

  • RarException::isUsingExceptions — Check whether error handling with exceptions is in use
  • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions
RarEntry::__toString
RarException::isUsingExceptions
Rar


Check whether error handling with exceptions is in use

RarException
RarException::setUsingExceptions
RarException
PHP Manual

RarException::isUsingExceptions

(PECL rar >= 2.0.0)

RarException::isUsingExceptions — Check 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() - Activate and deactivate error handling with exceptions

RarException
RarException::setUsingExceptions
RarException


Activate and deactivate error handling with exceptions

RarException::isUsingExceptions
Zip
RarException
PHP Manual

RarException::setUsingExceptions

(PECL rar >= 2.0.0)

RarException::setUsingExceptions — Activate 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):

  • attempting some operations on a closed RarArchive object or a RarEntry object relative to the first;
  • attempting to get an entry that does not exist with RarArchive::getEntry().

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

  • RarException::isUsingExceptions() - Check whether error handling with exceptions is in use

RarException::isUsingExceptions
Zip
RarException


Zip

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • ZipArchive — The ZipArchive class
    • ZipArchive::addEmptyDir — Add a new directory
    • ZipArchive::addFile — Adds a file to a ZIP archive from the given path
    • ZipArchive::addFromString — Add a file to a ZIP archive using its contents
    • ZipArchive::close — Close the active archive (opened or newly created)
    • ZipArchive::deleteIndex — delete an entry in the archive using its index
    • ZipArchive::deleteName — delete an entry in the archive using its name
    • ZipArchive::extractTo — Extract the archive contents
    • ZipArchive::getArchiveComment — Returns the Zip archive comment
    • ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
    • ZipArchive::getCommentName — Returns the comment of an entry using the entry name
    • ZipArchive::getFromIndex — Returns the entry contents using its index
    • ZipArchive::getFromName — Returns the entry contents using its name
    • ZipArchive::getNameIndex — Returns the name of an entry using its index
    • ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
    • ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).
    • ZipArchive::locateName — Returns the index of the entry in the archive
    • ZipArchive::open — Open a ZIP file archive
    • ZipArchive::renameIndex — Renames an entry defined by its index
    • ZipArchive::renameName — Renames an entry defined by its name
    • ZipArchive::setArchiveComment — Set the comment of a ZIP archive
    • ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
    • ZipArchive::setCommentName — Set the comment of an entry defined by its name
    • ZipArchive::statIndex — Get the details of an entry defined by its index.
    • ZipArchive::statName — Get the details of an entry defined by its name.
    • ZipArchive::unchangeAll — Undo all changes done in the archive
    • ZipArchive::unchangeArchive — Revert all global changes done in the archive.
    • ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
    • ZipArchive::unchangeName — Revert all changes done to an entry with the given name.
  • Zip Funkcje
    • zip_close — Close a ZIP file archive
    • zip_entry_close — Close a directory entry
    • zip_entry_compressedsize — Retrieve the compressed size of a directory entry
    • zip_entry_compressionmethod — Retrieve the compression method of a directory entry
    • zip_entry_filesize — Retrieve the actual file size of a directory entry
    • zip_entry_name — Retrieve the name of a directory entry
    • zip_entry_open — Open a directory entry for reading
    • zip_entry_read — Read from an open directory entry
    • zip_open — Open a ZIP file archive
    • zip_read — Read next entry in a ZIP file archive
RarException::setUsingExceptions
Wstęp
Rozszerzenia kompresji i archiwizacji


Wstęp

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.

Zip
Instalacja/Konfiguracja
Zip


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Zip


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/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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
Typy zasobów
Przykłady
Zip


Przykłady

Przykład #1 Create a Zip archive

<?php

$zip = new ZipArchive();
$filename = "./test112.zip";

if ($zip->open($filename, ZIPARCHIVE::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_entry, zip_entry_filesize($zip_entry));
            echo "$buf\n";

            zip_entry_close($zip_entry);
        }
        echo "\n";

    }

    zip_close($zip);

}
?>
Stałe predefiniowane
ZipArchive
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

Spis treści

  • ZipArchive::addEmptyDir — Add a new directory
  • ZipArchive::addFile — Adds a file to a ZIP archive from the given path
  • ZipArchive::addFromString — Add a file to a ZIP archive using its contents
  • ZipArchive::close — Close the active archive (opened or newly created)
  • ZipArchive::deleteIndex — delete an entry in the archive using its index
  • ZipArchive::deleteName — delete an entry in the archive using its name
  • ZipArchive::extractTo — Extract the archive contents
  • ZipArchive::getArchiveComment — Returns the Zip archive comment
  • ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
  • ZipArchive::getCommentName — Returns the comment of an entry using the entry name
  • ZipArchive::getFromIndex — Returns the entry contents using its index
  • ZipArchive::getFromName — Returns the entry contents using its name
  • ZipArchive::getNameIndex — Returns the name of an entry using its index
  • ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
  • ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).
  • ZipArchive::locateName — Returns the index of the entry in the archive
  • ZipArchive::open — Open a ZIP file archive
  • ZipArchive::renameIndex — Renames an entry defined by its index
  • ZipArchive::renameName — Renames an entry defined by its name
  • ZipArchive::setArchiveComment — Set the comment of a ZIP archive
  • ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
  • ZipArchive::setCommentName — Set the comment of an entry defined by its name
  • ZipArchive::statIndex — Get the details of an entry defined by its index.
  • ZipArchive::statName — Get the details of an entry defined by its name.
  • ZipArchive::unchangeAll — Undo all changes done in the archive
  • ZipArchive::unchangeArchive — Revert all global changes done in the archive.
  • ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
  • ZipArchive::unchangeName — Revert all changes done to an entry with the given name.
Przykłady
ZipArchive::addEmptyDir
Zip


Add a new directory

ZipArchive
ZipArchive::addFile
ZipArchive
PHP Manual

ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PECL zip >= 1.8.0)

ZipArchive::addEmptyDir — Add 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
ZipArchive::addFile
ZipArchive


Adds a file to a ZIP archive from the given path

ZipArchive::addEmptyDir
ZipArchive::addFromString
ZipArchive
PHP Manual

ZipArchive::addFile

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::addFile — Adds 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::addEmptyDir
ZipArchive::addFromString
ZipArchive


Add a file to a ZIP archive using its contents

ZipArchive::addFile
ZipArchive::close
ZipArchive
PHP Manual

ZipArchive::addFromString

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::addFromString — Add 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::addFile
ZipArchive::close
ZipArchive


Close the active archive (opened or newly created)

ZipArchive::addFromString
ZipArchive::deleteIndex
ZipArchive
PHP Manual

ZipArchive::close

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::close — Close 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::addFromString
ZipArchive::deleteIndex
ZipArchive


delete an entry in the archive using its index

ZipArchive::close
ZipArchive::deleteName
ZipArchive
PHP Manual

ZipArchive::deleteIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::deleteIndex — delete 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::close
ZipArchive::deleteName
ZipArchive


delete an entry in the archive using its name

ZipArchive::deleteIndex
ZipArchive::extractTo
ZipArchive
PHP Manual

ZipArchive::deleteName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::deleteName — delete 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::deleteIndex
ZipArchive::extractTo
ZipArchive


Extract the archive contents

ZipArchive::deleteName
ZipArchive::getArchiveComment
ZipArchive
PHP Manual

ZipArchive::extractTo

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::extractTo — Extract 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::deleteName
ZipArchive::getArchiveComment
ZipArchive


Returns the Zip archive comment

ZipArchive::extractTo
ZipArchive::getCommentIndex
ZipArchive
PHP Manual

ZipArchive::getArchiveComment

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getArchiveComment — Returns the Zip archive comment

Opis

string ZipArchive::getArchiveComment ([ int $flags ] )

Returns the Zip archive comment.

Parametry

flags

If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original unchanged comment is returned.

Zwracane wartości

Returns the Zip archive comment lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Dump an archive comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test_with_comment.zip');
if ($res === TRUE) {
    var_dump($zip->getArchiveComment());
    /* Or using the archive property */
    var_dump($zip->comment);
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::extractTo
ZipArchive::getCommentIndex
ZipArchive


Returns the comment of an entry using the entry index

ZipArchive::getArchiveComment
ZipArchive::getCommentName
ZipArchive
PHP Manual

ZipArchive::getCommentIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index

Opis

string ZipArchive::getCommentIndex ( int $index [, int $flags ] )

Returns the comment of an entry using the entry index.

Parametry

index

Index of the entry

flags

If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original unchanged comment is returned.

Zwracane wartości

Returns the comment on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Dump an entry comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
    var_dump($zip->getCommentIndex(1));
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::getArchiveComment
ZipArchive::getCommentName
ZipArchive


Returns the comment of an entry using the entry name

ZipArchive::getCommentIndex
ZipArchive::getFromIndex
ZipArchive
PHP Manual

ZipArchive::getCommentName

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::getCommentName — Returns the comment of an entry using the entry name

Opis

string ZipArchive::getCommentName ( string $name [, int $flags ] )

Returns the comment of an entry using the entry name.

Parametry

name

Name of the entry

flags

If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original unchanged comment is returned.

Zwracane wartości

Returns the comment on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Dump an entry comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
    var_dump($zip->getCommentName('test/entry1.txt'));
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::getCommentIndex
ZipArchive::getFromIndex
ZipArchive


Returns the entry contents using its index

ZipArchive::getCommentName
ZipArchive::getFromName
ZipArchive
PHP Manual

ZipArchive::getFromIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.3.0)

ZipArchive::getFromIndex — Returns the entry contents using its index

Opis

mixed ZipArchive::getFromIndex ( int $index [, int $length = 0 [, int $flags ]] )

Returns the entry contents using its index.

Parametry

index

Index of the entry

length

The length to be read from the entry. If 0, then the entire entry is read.

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZIPARCHIVE::FL_UNCHANGED

  • ZIPARCHIVE::FL_COMPRESSED

Zwracane wartości

Returns the contents of the entry on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    echo $zip->getFromIndex(2);
    $zip->close();
} else {
    echo 'failed';
}
?>
ZipArchive::getCommentName
ZipArchive::getFromName
ZipArchive


Returns the entry contents using its name

ZipArchive::getFromIndex
ZipArchive::getNameIndex
ZipArchive
PHP Manual

ZipArchive::getFromName

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getFromName — Returns the entry contents using its name

Opis

mixed ZipArchive::getFromName ( string $name [, int $length = 0 [, int $flags ]] )

Returns the entry contents using its name.

Parametry

name

Name of the entry

length

The length to be read from the entry. If 0, then the entire entry is read.

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZIPARCHIVE::FL_UNCHANGED

  • ZIPARCHIVE::FL_COMPRESSED

Zwracane wartości

Returns the contents of the entry on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
    echo $zip->getFromName('testfromfile.php');
    $zip->close();
} else {
    echo 'failed';
}
?>

Przykład #2 Convert an image from a zip entry

<?php
$z = new ZipArchive();
if ($z->open(dirname(__FILE__) . '/test_im.zip')) {
    $im_string = $z->getFromName("pear_item.gif");
    $im = imagecreatefromstring($im_string);
    imagepng($im, 'b.png');
}
?>
ZipArchive::getFromIndex
ZipArchive::getNameIndex
ZipArchive


Returns the name of an entry using its index

ZipArchive::getFromName
ZipArchive::getStatusString
ZipArchive
PHP Manual

ZipArchive::getNameIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::getNameIndex — Returns the name of an entry using its index

Opis

string ZipArchive::getNameIndex ( int $index [, int $flags ] )

Returns the name of an entry using its index.

Parametry

index

Index of the entry.

flags

If flags is set to ZIPARCHIVE::FL_UNCHANGED, the original unchanged name is returned.

Zwracane wartości

Returns the name on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 getnameindex() example

<?php
if ($zip->open('test.zip') == TRUE) {
 for ($i = 0; $i < $zip->numFiles; $i++;) {
     $filename = $zip->getNameIndex($i);
     // ...
 }
}
?>

ZipArchive::getFromName
ZipArchive::getStatusString
ZipArchive


Returns the status error message, system and/or zip messages

ZipArchive::getNameIndex
ZipArchive::getStream
ZipArchive
PHP Manual

ZipArchive::getStatusString

(PHP 5 >= 5.2.7)

ZipArchive::getStatusString — Returns the status error message, system and/or zip messages

Opis

string ZipArchive::getStatusString ( void )

Returns the status error message, system and/or zip messages.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string with the status message on success lub FALSE w przypadku niepowodzenia.

ZipArchive::getNameIndex
ZipArchive::getStream
ZipArchive


Get a file handler to the entry defined by its name (read only).

ZipArchive::getStatusString
ZipArchive::locateName
ZipArchive
PHP Manual

ZipArchive::getStream

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).

Opis

resource ZipArchive::getStream ( string $name )

Get a file handler to the entry defined by its name. For now it only supports read operations.

Parametry

name

The name of the entry to use.

Zwracane wartości

Returns a file pointer (resource) on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Get the entry contents with fread() and store it

<?php
$content = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
    $fp = $z->getStream('test');
    if(!$fp) exit("failed\n");

    while (!feof($fp)) {
        $contents .= fread($fp, 2);
    }

    fclose($fp);
    file_put_contents('t',$contents);
    echo "done.\n";
}
?>

Przykład #2 Same as the previous example but with fopen() and the zip stream wrapper

<?php
$fp = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
if (!$fp) {
    exit("cannot open\n");
}
while (!feof($fp)) {
    $contents .= fread($fp, 2);
    echo "$contents\n";
}
fclose($fp);
echo "done.\n";
?>

Przykład #3 Stream wrapper and image, can be used with the xml function as well

<?php
$im = imagecreatefromgif('zip://' . dirname(__FILE__) . '/test_im.zip#pear_item.gif');
imagepng($im, 'a.png');
?>
ZipArchive::getStatusString
ZipArchive::locateName
ZipArchive


Returns the index of the entry in the archive

ZipArchive::getStream
ZipArchive::open
ZipArchive
PHP Manual

ZipArchive::locateName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::locateName — Returns the index of the entry in the archive

Opis

mixed ZipArchive::locateName ( string $name [, int $flags ] )

Locates an entry using its name.

Parametry

name

The name of the entry to look up

flags

The flags are specified by ORing the following values, or 0 for none of them.

  • ZIPARCHIVE::FL_NOCASE

  • ZIPARCHIVE::FL_NODIR

Zwracane wartości

Returns the index of the entry on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Create an archive and then use it with ZipArchive::locateName()

<?php
$file = 'testlocate.zip';

$zip = new ZipArchive;
if ($zip->open($file, ZIPARCHIVE::CREATE) !== TRUE) {
    exit('failed');
}

$zip->addFromString('entry1.txt', 'entry #1');
$zip->addFromString('entry2.txt', 'entry #2');
$zip->addFromString('dir/entry2d.txt', 'entry #2');

if (!$zip->status == ZIPARCHIVE::ER_OK) {
    echo "failed to write zip\n";
}
$zip->close();

if ($zip->open($file) !== TRUE) {
    exit('failed');
}

echo $zip->locateName('entry1.txt') . "\n";
echo $zip->locateName('eNtry2.txt') . "\n";
echo $zip->locateName('eNtry2.txt', ZIPARCHIVE::FL_NOCASE) . "\n";
echo $zip->locateName('enTRy2d.txt', ZIPARCHIVE::FL_NOCASE|ZIPARCHIVE::FL_NODIR) . "\n";
$zip->close();

?>

Powyższy przykład wyświetli:

0

1
2
ZipArchive::getStream
ZipArchive::open
ZipArchive


Open a ZIP file archive

ZipArchive::locateName
ZipArchive::renameIndex
ZipArchive
PHP Manual

ZipArchive::open

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::open — Open a ZIP file archive

Opis

mixed ZipArchive::open ( string $filename [, int $flags ] )

Opens a new zip archive for reading, writing or modifying.

Parametry

filename

The file name of the ZIP archive to open.

flags

The mode to use to open the archive.

  • ZIPARCHIVE::OVERWRITE

  • ZIPARCHIVE::CREATE

  • ZIPARCHIVE::EXCL

  • ZIPARCHIVE::CHECKCONS

Zwracane wartości

Error codes

Returns TRUE on success or the error code.

  • ZIPARCHIVE::ER_EXISTS

    File already exists.

  • ZIPARCHIVE::ER_INCONS

    Zip archive inconsistent.

  • ZIPARCHIVE::ER_INVAL

    Invalid argument.

  • ZIPARCHIVE::ER_MEMORY

    Malloc failure.

  • ZIPARCHIVE::ER_NOENT

    No such file.

  • ZIPARCHIVE::ER_NOZIP

    Not a zip archive.

  • ZIPARCHIVE::ER_OPEN

    Can't open file.

  • ZIPARCHIVE::ER_READ

    Read error.

  • ZIPARCHIVE::ER_SEEK

    Seek error.

Przykłady

Przykład #1 Open and extract

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    echo 'ok';
    $zip->extractTo('test');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

Przykład #2 Create an archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->addFile('data.txt', 'entryname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::locateName
ZipArchive::renameIndex
ZipArchive


Renames an entry defined by its index

ZipArchive::open
ZipArchive::renameName
ZipArchive
PHP Manual

ZipArchive::renameIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::renameIndex — Renames an entry defined by its index

Opis

bool ZipArchive::renameIndex ( int $index , string $newname )

Renames an entry defined by its index.

Parametry

index

Index of the entry to rename.

newname

New name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Rename one entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->renameIndex(2,'newname.txt');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::open
ZipArchive::renameName
ZipArchive


Renames an entry defined by its name

ZipArchive::renameIndex
ZipArchive::setArchiveComment
ZipArchive
PHP Manual

ZipArchive::renameName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::renameName — Renames an entry defined by its name

Opis

bool ZipArchive::renameName ( string $name , string $newname )

Renames an entry defined by its name.

Parametry

name

Name of the entry to rename.

newname

New name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Rename one entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->renameName('currentname.txt','newname.txt');
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>
ZipArchive::renameIndex
ZipArchive::setArchiveComment
ZipArchive


Set the comment of a ZIP archive

ZipArchive::renameName
ZipArchive::setCommentIndex
ZipArchive
PHP Manual

ZipArchive::setArchiveComment

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setArchiveComment — Set the comment of a ZIP archive

Opis

mixed ZipArchive::setArchiveComment ( string $comment )

Set the comment of a ZIP archive.

Parametry

comment

The contents of the comment.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Create an archive and set a comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->setArchiveComment('new archive comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::renameName
ZipArchive::setCommentIndex
ZipArchive


Set the comment of an entry defined by its index

ZipArchive::setArchiveComment
ZipArchive::setCommentName
ZipArchive
PHP Manual

ZipArchive::setCommentIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setCommentIndex — Set the comment of an entry defined by its index

Opis

mixed ZipArchive::setCommentIndex ( int $index , string $comment )

Set the comment of an entry defined by its index.

Parametry

index

Index of the entry.

comment

The contents of the comment.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Open an archive and set a comment for an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->setCommentIndex(2, 'new entry comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::setArchiveComment
ZipArchive::setCommentName
ZipArchive


Set the comment of an entry defined by its name

ZipArchive::setCommentIndex
ZipArchive::statIndex
ZipArchive
PHP Manual

ZipArchive::setCommentName

(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

ZipArchive::setCommentName — Set the comment of an entry defined by its name

Opis

mixed ZipArchive::setCommentName ( string $name , string $comment )

Set the comment of an entry defined by its name.

Parametry

name

Name of the entry.

comment

The contents of the comment.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Open an archive and set a comment for an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    $zip->setCommentName('entry1.txt', 'new entry comment');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>
ZipArchive::setCommentIndex
ZipArchive::statIndex
ZipArchive


Get the details of an entry defined by its index.

ZipArchive::setCommentName
ZipArchive::statName
ZipArchive
PHP Manual

ZipArchive::statIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::statIndex — Get the details of an entry defined by its index.

Opis

mixed ZipArchive::statIndex ( int $index [, int $flags ] )

The function obtains information about the entry defined by its index.

Parametry

index

Index of the entry

flags

ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

Zwracane wartości

Returns an array containing the entry details lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Dump the stat info of an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    print_r($zip->statIndex(3));
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

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

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)
ZipArchive::setCommentName
ZipArchive::statName
ZipArchive


Get the details of an entry defined by its name.

ZipArchive::statIndex
ZipArchive::unchangeAll
ZipArchive
PHP Manual

ZipArchive::statName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::statName — Get the details of an entry defined by its name.

Opis

mixed ZipArchive::statName ( name $name [, int $flags ] )

The function obtains information about the entry defined by its name.

Parametry

name

Name of the entry

flags

The flags argument specifies how the name lookup should be done. Also, ZIPARCHIVE::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

  • ZIPARCHIVE::FL_NOCASE

  • ZIPARCHIVE::FL_NODIR

  • ZIPARCHIVE::FL_UNCHANGED

Zwracane wartości

Returns an array containing the entry details lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Dump the stat info of an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
    print_r($zip->statName('foobar/baz'));
    $zip->close();
} else {
    echo 'failed, code:' . $res;
}
?>

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

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)
ZipArchive::statIndex
ZipArchive::unchangeAll
ZipArchive


Undo all changes done in the archive

ZipArchive::statName
ZipArchive::unchangeArchive
ZipArchive
PHP Manual

ZipArchive::unchangeAll

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeAll — Undo all changes done in the archive

Opis

mixed ZipArchive::unchangeAll ( void )

Undo all changes done in the archive.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ZipArchive::statName
ZipArchive::unchangeArchive
ZipArchive


Revert all global changes done in the archive.

ZipArchive::unchangeAll
ZipArchive::unchangeIndex
ZipArchive
PHP Manual

ZipArchive::unchangeArchive

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeArchive — Revert all global changes done in the archive.

Opis

mixed ZipArchive::unchangeArchive ( void )

Revert all global changes to the archive. For now, this only reverts archive comment changes.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ZipArchive::unchangeAll
ZipArchive::unchangeIndex
ZipArchive


Revert all changes done to an entry at the given index

ZipArchive::unchangeArchive
ZipArchive::unchangeName
ZipArchive
PHP Manual

ZipArchive::unchangeIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index

Opis

mixed ZipArchive::unchangeIndex ( int $index )

Revert all changes done to an entry at the given index.

Parametry

index

Index of the entry.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ZipArchive::unchangeArchive
ZipArchive::unchangeName
ZipArchive


Revert all changes done to an entry with the given name.

ZipArchive::unchangeIndex
Zip Funkcje
ZipArchive
PHP Manual

ZipArchive::unchangeName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::unchangeName — Revert all changes done to an entry with the given name.

Opis

mixed ZipArchive::unchangeName ( string $name )

Revert all changes done to an entry.

Parametry

name

Name of the entry.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ZipArchive::unchangeIndex
Zip Funkcje
ZipArchive


Zip Funkcje

Spis treści

  • zip_close — Close a ZIP file archive
  • zip_entry_close — Close a directory entry
  • zip_entry_compressedsize — Retrieve the compressed size of a directory entry
  • zip_entry_compressionmethod — Retrieve the compression method of a directory entry
  • zip_entry_filesize — Retrieve the actual file size of a directory entry
  • zip_entry_name — Retrieve the name of a directory entry
  • zip_entry_open — Open a directory entry for reading
  • zip_entry_read — Read from an open directory entry
  • zip_open — Open a ZIP file archive
  • zip_read — Read next entry in a ZIP file archive
ZipArchive::unchangeName
zip_close
Zip


Close a ZIP file archive

Zip Funkcje
zip_entry_close
Zip Funkcje
PHP Manual

zip_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_close — Close a ZIP file archive

Opis

void zip_close ( resource $zip )

Closes the given ZIP file archive.

Parametry

zip

A ZIP file previously opened with zip_open().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

Zip Funkcje
zip_entry_close
Zip Funkcje


Close a directory entry

zip_close
zip_entry_compressedsize
Zip Funkcje
PHP Manual

zip_entry_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_close — Close a directory entry

Opis

bool zip_entry_close ( resource $zip_entry )

Closes the specified directory entry.

Parametry

zip_entry

A directory entry previously opened zip_entry_open().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_read() - Read from an open directory entry

zip_close
zip_entry_compressedsize
Zip Funkcje


Retrieve the compressed size of a directory entry

zip_entry_close
zip_entry_compressionmethod
Zip Funkcje
PHP Manual

zip_entry_compressedsize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_compressedsize — Retrieve the compressed size of a directory entry

Opis

int zip_entry_compressedsize ( resource $zip_entry )

Returns the compressed size of the specified directory entry.

Parametry

zip_entry

A directory entry returned by zip_read().

Zwracane wartości

The compressed size.

Zobacz też:

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_close
zip_entry_compressionmethod
Zip Funkcje


Retrieve the compression method of a directory entry

zip_entry_compressedsize
zip_entry_filesize
Zip Funkcje
PHP Manual

zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_compressionmethod — Retrieve the compression method of a directory entry

Opis

string zip_entry_compressionmethod ( resource $zip_entry )

Returns the compression method of the directory entry specified by zip_entry.

Parametry

zip_entry

A directory entry returned by zip_read().

Zwracane wartości

The compression method.

Zobacz też:

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_compressedsize
zip_entry_filesize
Zip Funkcje


Retrieve the actual file size of a directory entry

zip_entry_compressionmethod
zip_entry_name
Zip Funkcje
PHP Manual

zip_entry_filesize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_filesize — Retrieve the actual file size of a directory entry

Opis

int zip_entry_filesize ( resource $zip_entry )

Returns the actual size of the specified directory entry.

Parametry

zip_entry

A directory entry returned by zip_read().

Zwracane wartości

The size of the directory entry.

Zobacz też:

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_compressionmethod
zip_entry_name
Zip Funkcje


Retrieve the name of a directory entry

zip_entry_filesize
zip_entry_open
Zip Funkcje
PHP Manual

zip_entry_name

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_name — Retrieve the name of a directory entry

Opis

string zip_entry_name ( resource $zip_entry )

Returns the name of the specified directory entry.

Parametry

zip_entry

A directory entry returned by zip_read().

Zwracane wartości

The name of the directory entry.

Zobacz też:

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive

zip_entry_filesize
zip_entry_open
Zip Funkcje


Open a directory entry for reading

zip_entry_name
zip_entry_read
Zip Funkcje
PHP Manual

zip_entry_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_open — Open a directory entry for reading

Opis

bool zip_entry_open ( resource $zip , resource $zip_entry [, string $mode ] )

Opens a directory entry in a zip file for reading.

Parametry

zip

A valid resource handle returned by zip_open().

zip_entry

A directory entry returned by zip_read().

mode

Any of the modes specified in the documentation of fopen().

Informacja:

Currently, mode is ignored and is always "rb". This is due to the fact that zip support in PHP is read only access.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja:

Unlike fopen() and other similar functions, the return value of zip_entry_open() only indicates the result of the operation and is not needed for reading or closing the directory entry.

Zobacz też:

  • zip_entry_close() - Close a directory entry
  • zip_entry_read() - Read from an open directory entry

zip_entry_name
zip_entry_read
Zip Funkcje


Read from an open directory entry

zip_entry_open
zip_open
Zip Funkcje
PHP Manual

zip_entry_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_entry_read — Read from an open directory entry

Opis

string zip_entry_read ( resource $zip_entry [, int $length ] )

Reads from an open directory entry.

Parametry

zip_entry

A directory entry returned by zip_read().

length

The number of bytes to return. If not specified, this function will attempt to read 1024 bytes.

Informacja:

This should be the uncompressed length you wish to read.

Zwracane wartości

Returns the data read, or FALSE if the end of the file is reached.

Zobacz też:

  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_close() - Close a directory entry
  • zip_entry_filesize() - Retrieve the actual file size of a directory entry

zip_entry_open
zip_open
Zip Funkcje


Open a ZIP file archive

zip_entry_read
zip_read
Zip Funkcje
PHP Manual

zip_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_open — Open a ZIP file archive

Opis

mixed zip_open ( string $filename )

Opens a new zip archive for reading.

Parametry

filename

The file name of the ZIP archive to open.

Zwracane wartości

Returns a resource handle for later use with zip_read() and zip_close() or returns the number of error if filename does not exist or in case of other error.

Zobacz też:

  • zip_read() - Read next entry in a ZIP file archive
  • zip_close() - Close a ZIP file archive

zip_entry_read
zip_read
Zip Funkcje


Read next entry in a ZIP file archive

zip_open
Zlib
Zip Funkcje
PHP Manual

zip_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PECL zip >= 1.0.0)

zip_read — Read next entry in a ZIP file archive

Opis

mixed zip_read ( resource $zip )

Reads the next entry in a zip file archive.

Parametry

zip

A ZIP file previously opened with zip_open().

Zwracane wartości

Returns a directory entry resource for later use with the zip_entry_... functions, or FALSE if there are no more entries to read, or an error code if an error occurred.

Zobacz też:

  • zip_open() - Open a ZIP file archive
  • zip_close() - Close a ZIP file archive
  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_read() - Read from an open directory entry

zip_open
Zlib
Zip Funkcje


Zlib Compression

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Zlib Funkcje
    • gzclose — Close an open gz-file pointer
    • gzcompress — Compress a string
    • gzdecode — Decodes a gzip compressed string
    • gzdeflate — Deflate a string
    • gzencode — Create a gzip compressed string
    • gzeof — Test for EOF on a gz-file pointer
    • gzfile — Read entire gz-file into an array
    • gzgetc — Get character from gz-file pointer
    • gzgets — Get line from file pointer
    • gzgetss — Get line from gz-file pointer and strip HTML tags
    • gzinflate — Inflate a deflated string
    • gzopen — Open gz-file
    • gzpassthru — Output all remaining data on a gz-file pointer
    • gzputs — Alias dla gzwrite
    • gzread — Binary-safe gz-file read
    • gzrewind — Rewind the position of a gz-file pointer
    • gzseek — Seek on a gz-file pointer
    • gztell — Tell gz-file pointer read/write position
    • gzuncompress — Uncompress a compressed string
    • gzwrite — Binary-safe gz-file write
    • readgzfile — Output a gz-file
    • zlib_get_coding_type — Returns the coding type used for output compression
zip_read
Wstęp
Rozszerzenia kompresji i archiwizacji


Wstęp

This module enables you to transparently read and write gzip (.gz) compressed files, through versions of most of the filesystem functions which work with gzip-compressed files (and uncompressed files, too, but not with sockets).

Informacja:

Version 4.0.4 introduced a fopen-wrapper for .gz-files, so that you can use a special zlib: URL to access compressed files transparently using the normal f*() file access functions if you prefix the filename or path with zlib: when calling fopen(). This feature requires a C runtime library that provides the fopencookie() function. Up to now the GNU libc seems to be the only library that provides this feature.

In PHP 4.3.0, zlib: has been changed to compress.zlib:// to prevent ambiguities with filenames containing ':' characters. The fopencookie() function is no longer required. More information is available in the section about zlib://.

Zlib
Instalacja/Konfiguracja
Zlib


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Zlib


Wymagania

This module uses the functions of » zlib by Jean-loup Gailly and Mark Adler. You have to use a zlib version >= 1.0.9 with this module.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]

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: Built-in support for zlib on Windows is available with PHP 4.3.0.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

The zlib extension offers the option to transparently compress your pages on-the-fly, if the requesting browser supports this. Therefore there are three options in the configuration file php.ini.

Zlib Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
zlib.output_compression | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
zlib.output_compression_level | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
zlib.output_handler | "" | PHP_INI_ALL | Available since PHP 4.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.

zlib.output_compression boolean/integer

Whether to transparently compress pages. If this option is set to "On" in php.ini or the Apache configuration, pages are compressed if the browser sends an "Accept-Encoding: gzip" or "deflate" header. "Content-Encoding: gzip" (respectively "deflate") and "Vary: Accept-Encoding" headers are added to the output. In runtime, it can be set only before sending any output.

This option also accepts integer values instead of boolean "On"/"Off", using this you can set the output buffer size (default is 4KB).

Informacja:

output_handler must be empty if this is set 'On' ! Instead you must use zlib.output_handler.

zlib.output_compression_level integer

Compression level used for transparent output compression. Specify a value between 0 (no compression) to 9 (most compression). The default value, -1, lets the server decide which level to use.

zlib.output_handler string

You cannot specify additional output handlers if zlib.output_compression is activated here. This setting does the same as output_handler but in a different order.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines a file pointer resource returned by gzopen().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

FORCE_GZIP (integer)
FORCE_DEFLATE (integer)
Typy zasobów
Przykłady
Zlib


Przykłady

This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

Przykład #1 Small Zlib Example

<?php

$filename = tempnam('/tmp', 'zlibtest') . '.gz';
echo "<html>\n<head></head>\n<body>\n<pre>\n";
$s = "Only a test, test, test, test, test, test, test, test!\n";

// open file for writing with maximum compression
$zp = gzopen($filename, "w9");

// write string to file
gzwrite($zp, $s);

// close file
gzclose($zp);

// open file for reading
$zp = gzopen($filename, "r");

// read 3 char
echo gzread($zp, 3);

// output until end of the file and close it.
gzpassthru($zp);
gzclose($zp);

echo "\n";

// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
        echo "Error with zlib functions!";
}
unlink($filename);
echo "</pre>\n</body>\n</html>\n";

?>
Stałe predefiniowane
Zlib Funkcje
Zlib


Zlib Funkcje

Spis treści

  • gzclose — Close an open gz-file pointer
  • gzcompress — Compress a string
  • gzdecode — Decodes a gzip compressed string
  • gzdeflate — Deflate a string
  • gzencode — Create a gzip compressed string
  • gzeof — Test for EOF on a gz-file pointer
  • gzfile — Read entire gz-file into an array
  • gzgetc — Get character from gz-file pointer
  • gzgets — Get line from file pointer
  • gzgetss — Get line from gz-file pointer and strip HTML tags
  • gzinflate — Inflate a deflated string
  • gzopen — Open gz-file
  • gzpassthru — Output all remaining data on a gz-file pointer
  • gzputs — Alias dla gzwrite
  • gzread — Binary-safe gz-file read
  • gzrewind — Rewind the position of a gz-file pointer
  • gzseek — Seek on a gz-file pointer
  • gztell — Tell gz-file pointer read/write position
  • gzuncompress — Uncompress a compressed string
  • gzwrite — Binary-safe gz-file write
  • readgzfile — Output a gz-file
  • zlib_get_coding_type — Returns the coding type used for output compression
Przykłady
gzclose
Zlib


Close an open gz-file pointer

Zlib Funkcje
gzcompress
Zlib Funkcje
PHP Manual

gzclose

(PHP 4, PHP 5)

gzclose — Close an open gz-file pointer

Opis

bool gzclose ( resource $zp )

Closes the given gz-file pointer.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 gzclose() example

<?php
$gz = gzopen('somefile.gz','w9');
gzputs ($gz, 'I was added to somefile.gz');
gzclose($gz);
?>

Zobacz też:

  • gzopen() - Open gz-file

Zlib Funkcje
gzcompress
Zlib Funkcje


Compress a string

gzclose
gzdecode
Zlib Funkcje
PHP Manual

gzcompress

(PHP 4 >= 4.0.1, PHP 5)

gzcompress — Compress a string

Opis

string gzcompress ( string $data [, int $level = -1 ] )

This function compress the given string using the ZLIB data format.

For details on the ZLIB compression algorithm see the document "» ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

Informacja:

This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

Parametry

data

The data to compress.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression.

Zwracane wartości

The compressed string or FALSE if an error occurred.

Przykłady

Przykład #1 gzcompress() example

<?php
$compressed = gzcompress('Compress me', 9);
echo $compressed;
?>

Zobacz też:

  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzclose
gzdecode
Zlib Funkcje


Decodes a gzip compressed string

gzcompress
gzdeflate
Zlib Funkcje
PHP Manual

gzdecode

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

gzdecode — Decodes a gzip compressed string

Opis

string gzdecode ( string $data [, int $length ] )

This function returns a decoded version of the input data.

Parametry

data

The data to decode, encoded by gzencode().

length

The maximum length of data to decode.

Zwracane wartości

The decoded string, or FALSE if an error occurred.

Zobacz też:

  • gzencode() - Create a gzip compressed string

gzcompress
gzdeflate
Zlib Funkcje


Deflate a string

gzdecode
gzencode
Zlib Funkcje
PHP Manual

gzdeflate

(PHP 4 >= 4.0.4, PHP 5)

gzdeflate — Deflate a string

Opis

string gzdeflate ( string $data [, int $level = -1 ] )

This function compress the given string using the DEFLATE data format.

For details on the DEFLATE compression algorithm see the document "» DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

Parametry

data

The data to deflate.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

Zwracane wartości

The deflated string or FALSE if an error occurred.

Przykłady

Przykład #1 gzdeflate() example

<?php
$compressed = gzdeflate('Compress me', 9);
echo $compressed;
?>

Zobacz też:

  • gzinflate() - Inflate a deflated string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzdecode
gzencode
Zlib Funkcje


Create a gzip compressed string

gzdeflate
gzeof
Zlib Funkcje
PHP Manual

gzencode

(PHP 4 >= 4.0.4, PHP 5)

gzencode — Create a gzip compressed string

Opis

string gzencode ( string $data [, int $level = -1 [, int $encoding_mode = FORCE_GZIP ]] )

This function returns a compressed version of the input data compatible with the output of the gzip program.

For more information on the GZIP file format, see the document: » GZIP file format specification version 4.3 (RFC 1952).

Parametry

data

The data to encode.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library.

encoding_mode

The encoding mode. Can be FORCE_GZIP (the default) or FORCE_DEFLATE.

If you use FORCE_DEFLATE, you get a standard zlib deflated string (inclusive zlib headers) after the gzip file header but without the trailing crc32 checksum.

Zwracane wartości

The encoded string, or FALSE if an error occurred.

Rejestr zmian

Wersja | Opis
4.2.0 | The encoding_mode parameter was added

Przykłady

The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:

Przykład #1 Creating a gzip file

<?php
$data = implode("", file("bigfile.txt"));
$gzdata = gzencode($data, 9);
$fp = fopen("bigfile.txt.gz", "w");
fwrite($fp, $gzdata);
fclose($fp);
?>

Zobacz też:

  • gzdecode() - Decodes a gzip compressed string
  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzcompress() - Compress a string

gzdeflate
gzeof
Zlib Funkcje


Test for EOF on a gz-file pointer

gzencode
gzfile
Zlib Funkcje
PHP Manual

gzeof

(PHP 4, PHP 5)

gzeof — Test for EOF on a gz-file pointer

Opis

int gzeof ( resource $zp )

Tests the given GZ file pointer for EOF.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Zwracane wartości

Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.

Przykłady

Przykład #1 gzeof() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

gzencode
gzfile
Zlib Funkcje


Read entire gz-file into an array

gzeof
gzgetc
Zlib Funkcje
PHP Manual

gzfile

(PHP 4, PHP 5)

gzfile — Read entire gz-file into an array

Opis

array gzfile ( string $filename [, int $use_include_path = 0 ] )

This function is identical to readgzfile(), except that it returns the file in an array.

Parametry

filename

The file name.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Zwracane wartości

An array containing the file, one line per cell.

Przykłady

Przykład #1 gzfile() example

<?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
    echo $line;
}
?>

Zobacz też:

  • readgzfile() - Output a gz-file
  • gzopen() - Open gz-file

gzeof
gzgetc
Zlib Funkcje


Get character from gz-file pointer

gzfile
gzgets
Zlib Funkcje
PHP Manual

gzgetc

(PHP 4, PHP 5)

gzgetc — Get character from gz-file pointer

Opis

string gzgetc ( resource $zp )

Returns a string containing a single (uncompressed) character read from the given gz-file pointer.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Zwracane wartości

The uncompressed character or FALSE on EOF (unlike gzeof()).

Przykłady

Przykład #1 gzgetc() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>

Zobacz też:

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer

gzfile
gzgets
Zlib Funkcje


Get line from file pointer

gzgetc
gzgetss
Zlib Funkcje
PHP Manual

gzgets

(PHP 4, PHP 5)

gzgets — Get line from file pointer

Opis

string gzgets ( resource $zp , int $length )

Gets a (uncompressed) string of up to length - 1 bytes read from the given file pointer. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

Zwracane wartości

The uncompressed string, or FALSE on error.

Przykłady

Przykład #1 gzgets() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgets($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?>

Zobacz też:

  • gzopen() - Open gz-file
  • gzgetc() - Get character from gz-file pointer
  • gzwrite() - Binary-safe gz-file write

gzgetc
gzgetss
Zlib Funkcje


Get line from gz-file pointer and strip HTML tags

gzgets
gzinflate
Zlib Funkcje
PHP Manual

gzgetss

(PHP 4, PHP 5)

gzgetss — Get line from gz-file pointer and strip HTML tags

Opis

string gzgetss ( resource $zp , int $length [, string $allowable_tags ] )

Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

allowable_tags

You can use this optional parameter to specify tags which should not be stripped.

Zwracane wartości

The uncompressed and striped string, or FALSE on error.

Przykłady

Przykład #1 gzgetss() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
   $buffer = gzgetss($handle, 4096);
   echo $buffer;
}
gzclose($handle);
?>

Zobacz też:

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • strip_tags() - Strip HTML and PHP tags from a string

gzgets
gzinflate
Zlib Funkcje


Inflate a deflated string

gzgetss
gzopen
Zlib Funkcje
PHP Manual

gzinflate

(PHP 4 >= 4.0.4, PHP 5)

gzinflate — Inflate a deflated string

Opis

string gzinflate ( string $data [, int $length = 0 ] )

This function inflate a deflated string.

Parametry

data

The data compressed by gzdeflate().

length

The maximum length of data to decode.

Zwracane wartości

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

Przykłady

Przykład #1 gzinflate() example

<?php
$compressed   = gzdeflate('Compress me', 9);
$uncompressed = gzinflate($compressed);
echo $uncompressed;
?>

Zobacz też:

  • gzdeflate() - Deflate a string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

gzgetss
gzopen
Zlib Funkcje


Open gz-file

gzinflate
gzpassthru
Zlib Funkcje
PHP Manual

gzopen

(PHP 4, PHP 5)

gzopen — Open gz-file

Opis

resource gzopen ( string $filename , string $mode [, int $use_include_path = 0 ] )

Opens a gzip (.gz) file for reading or writing.

gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.

Parametry

filename

The file name.

mode

As in fopen() (rb or wb) but can also include a compression level (wb9) or a strategy: f for filtered data as in wb6f, h for Huffman only compression as in wb1h. (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Zwracane wartości

Returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.

If the open fails, the function returns FALSE.

Przykłady

Przykład #1 gzopen() Example

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

Zobacz też:

  • gzclose() - Close an open gz-file pointer

gzinflate
gzpassthru
Zlib Funkcje


Output all remaining data on a gz-file pointer

gzopen
gzputs
Zlib Funkcje
PHP Manual

gzpassthru

(PHP 4, PHP 5)

gzpassthru — Output all remaining data on a gz-file pointer

Opis

int gzpassthru ( resource $zp )

Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.

Informacja:

You may need to call gzrewind() to reset the file pointer to the beginning of the file if you have already written data to it.

Wskazówka

If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readgzfile() function, which saves you the gzopen() call.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Zwracane wartości

The number of uncompressed characters read from gz and passed through to the input, or FALSE on error.

Przykłady

Przykład #1 gzpassthru() example

<?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?>

gzopen
gzputs
Zlib Funkcje


Alias dla gzwrite

gzpassthru
gzread
Zlib Funkcje
PHP Manual

gzputs

(PHP 4, PHP 5)

gzputs — Alias dla gzwrite()

Opis

Ta funkcja jest aliasem dla: gzwrite().

gzpassthru
gzread
Zlib Funkcje


Binary-safe gz-file read

gzputs
gzrewind
Zlib Funkcje
PHP Manual

gzread

(PHP 4, PHP 5)

gzread — Binary-safe gz-file read

Opis

string gzread ( resource $zp , int $length )

gzread() reads up to length bytes from the given gz-file pointer. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The number of bytes to read.

Zwracane wartości

The data that have been read.

Przykłady

Przykład #1 gzread() example

<?php
// get contents of a gz-file into a string
$filename = "/usr/local/something.txt.gz";
$zd = gzopen($filename, "r");
$contents = gzread($zd, 10000);
gzclose($zd);
?>

Zobacz też:

  • gzwrite() - Binary-safe gz-file write
  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • gzgetss() - Get line from gz-file pointer and strip HTML tags
  • gzfile() - Read entire gz-file into an array
  • gzpassthru() - Output all remaining data on a gz-file pointer

gzputs
gzrewind
Zlib Funkcje


Rewind the position of a gz-file pointer

gzread
gzseek
Zlib Funkcje
PHP Manual

gzrewind

(PHP 4, PHP 5)

gzrewind — Rewind the position of a gz-file pointer

Opis

bool gzrewind ( resource $zp )

Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gzseek() - Seek on a gz-file pointer
  • gztell() - Tell gz-file pointer read/write position

gzread
gzseek
Zlib Funkcje


Seek on a gz-file pointer

gzrewind
gztell
Zlib Funkcje
PHP Manual

gzseek

(PHP 4, PHP 5)

gzseek — Seek on a gz-file pointer

Opis

int gzseek ( resource $zp , int $offset [, int $whence = SEEK_SET ] )

Sets the file position indicator for the given file pointer to the given offset byte into the file stream. Equivalent to calling (in C) gzseek(zp, offset, SEEK_SET).

If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek() then compresses a sequence of zeroes up to the new starting position.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

offset

The seeked offset.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.

If whence is not specified, it is assumed to be SEEK_SET.

Zwracane wartości

Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.

Przykłady

Przykład #1 gzseek() example

<?php
$gz = gzopen('somefile.gz', 'r');
gzseek($gz,2);
echo gzgetc($gz);
gzclose($gz);
?>

Zobacz też:

  • gztell() - Tell gz-file pointer read/write position
  • gzrewind() - Rewind the position of a gz-file pointer

gzrewind
gztell
Zlib Funkcje


Tell gz-file pointer read/write position

gzseek
gzuncompress
Zlib Funkcje
PHP Manual

gztell

(PHP 4, PHP 5)

gztell — Tell gz-file pointer read/write position

Opis

int gztell ( resource $zp )

Gets the position of the given file pointer; i.e., its offset into the uncompressed file stream.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

Zwracane wartości

The position of the file pointer or FALSE if an error occurs.

Zobacz też:

  • gzopen() - Open gz-file
  • gzseek() - Seek on a gz-file pointer
  • gzrewind() - Rewind the position of a gz-file pointer

gzseek
gzuncompress
Zlib Funkcje


Uncompress a compressed string

gztell
gzwrite
Zlib Funkcje
PHP Manual

gzuncompress

(PHP 4 >= 4.0.1, PHP 5)

gzuncompress — Uncompress a compressed string

Opis

string gzuncompress ( string $data [, int $length = 0 ] )

This function uncompress a compressed string.

Parametry

data

The data compressed by gzcompress().

length

The maximum length of data to decode.

Zwracane wartości

The original uncompressed data or FALSE on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.

Przykłady

Przykład #1 gzuncompress() example

<?php
$compressed   = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>

Zobacz też:

  • gzcompress() - Compress a string
  • gzinflate() - Inflate a deflated string
  • gzdeflate() - Deflate a string
  • gzencode() - Create a gzip compressed string

gztell
gzwrite
Zlib Funkcje


Binary-safe gz-file write

gzuncompress
readgzfile
Zlib Funkcje
PHP Manual

gzwrite

(PHP 4, PHP 5)

gzwrite — Binary-safe gz-file write

Opis

int gzwrite ( resource $zp , string $string [, int $length ] )

gzwrite() writes the contents of string to the given gz-file.

Parametry

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

string

The string to write.

length

The number of uncompressed bytes to write. If supplied, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.

Informacja:

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Zwracane wartości

Returns the number of (uncompressed) bytes written to the given gz-file stream.

Przykłady

Przykład #1 gzwrite() example

<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>

Zobacz też:

  • gzread() - Binary-safe gz-file read
  • gzopen() - Open gz-file

gzuncompress
readgzfile
Zlib Funkcje


Output a gz-file

gzwrite
zlib_get_coding_type
Zlib Funkcje
PHP Manual

readgzfile

(PHP 4, PHP 5)

readgzfile — Output a gz-file

Opis

int readgzfile ( string $filename [, int $use_include_path = 0 ] )

Reads a file, decompresses it and writes it to standard output.

readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.

Parametry

filename

The file name. This file will be opened from the filesystem and its contents written to standard output.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Zwracane wartości

Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.

Zobacz też:

  • gzpassthru() - Output all remaining data on a gz-file pointer
  • gzfile() - Read entire gz-file into an array
  • gzopen() - Open gz-file

gzwrite
zlib_get_coding_type
Zlib Funkcje


Returns the coding type used for output compression

readgzfile
Przetwarzanie transakcji kartami płatniczymi
Zlib Funkcje
PHP Manual

zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5)

zlib_get_coding_type — Returns the coding type used for output compression

Opis

string zlib_get_coding_type ( void )

Returns the coding type used for output compression.

Zwracane wartości

Possible return values are gzip, deflate, or FALSE.

Zobacz też:

  • The zlib.output_compression directive

readgzfile
Przetwarzanie transakcji kartami płatniczymi
Zlib Funkcje


Przetwarzanie transakcji kartami płatniczymi

  • MCVE — MCVE (Monetra) Payment
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • MCVE Funkcje
  • SPPLUS — SPPLUS Payment System
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • SPPLUS Funkcje
zlib_get_coding_type
MCVE
Opis funkcji


MCVE (Monetra) Payment

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • MCVE Funkcje
    • m_checkstatus — Check to see if a transaction has completed
    • m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers
    • m_connect — Establish the connection to MCVE
    • m_connectionerror — Get a textual representation of why a connection failed
    • m_deletetrans — Delete specified transaction from MCVE_CONN structure
    • m_destroyconn — Destroy the connection and MCVE_CONN structure
    • m_destroyengine — Free memory associated with IP/SSL connectivity
    • m_getcell — Get a specific cell from a comma delimited response by column name
    • m_getcellbynum — Get a specific cell from a comma delimited response by column number
    • m_getcommadelimited — Get the RAW comma delimited data returned from MCVE
    • m_getheader — Get the name of the column in a comma-delimited response
    • m_initconn — Create and initialize an MCVE_CONN structure
    • m_initengine — Ready the client for IP/SSL Communication
    • m_iscommadelimited — Checks to see if response is comma delimited
    • m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE
    • m_monitor — Perform communication with MCVE (send/receive data) Non-blocking
    • m_numcolumns — Number of columns returned in a comma delimited response
    • m_numrows — Number of rows returned in a comma delimited response
    • m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work
    • m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction
    • m_responseparam — Get a custom response parameter
    • m_returnstatus — Check to see if the transaction was successful
    • m_setblocking — Set blocking/non-blocking mode for connection
    • m_setdropfile — Set the connection method to Drop-File
    • m_setip — Set the connection method to IP
    • m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate
    • m_setssl_files — Set certificate key files and certificates if server requires client certificate verification
    • m_setssl — Set the connection method to SSL
    • m_settimeout — Set maximum transaction time (per trans)
    • m_sslcert_gen_hash — Generate hash for SSL client certificate verification
    • m_transactionssent — Check to see if outgoing buffer is clear
    • m_transinqueue — Number of transactions in client-queue
    • m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()
    • m_transnew — Start a new transaction
    • m_transsend — Finalize and send the transaction
    • m_uwait — Wait x microsecs
    • m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to
    • m_verifyconnection — Set whether or not to PING upon connect to verify connection
    • m_verifysslcert — Set whether or not to verify the server ssl certificate
Przetwarzanie transakcji kartami płatniczymi
Wstęp
Przetwarzanie transakcji kartami płatniczymi


Wstęp

These functions interface the MCVE (Monetra) API (libmonetra, formerly known as libmcve), allowing you to work directly with MCVE/Monetra from your PHP scripts. MCVE/Monetra is Main Street Softworks' solution to direct credit/debit/gift card processing for Linux/Unix/MacOSX/Windows ( » http://www.mainstreetsoftworks.com/ ). It lets you directly address the credit card clearing houses via your *nix box, modem and/or internet connection (bypassing the need for an additional service such as Authorize.Net or Pay Flow Pro). Using the MCVE/Monetra module for PHP, you can process credit cards directly through MCVE/Monetra via your PHP scripts. The following references will outline the process.

Informacja:

MCVE/Monetra is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientele to the MCVE platform.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

MCVE
Instalacja/Konfiguracja
MCVE


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
MCVE


Wymagania

The LibMonetra (formerly libmcve) library.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/mcve.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

If installing without specifying the libmonetra path, PHP will attempt to look in the default LibMonetra Install location (/usr/local). If Monetra (MCVE) is in a non-standard location, run configure with: --with-mcve=$mcve_path , where $mcve_path is the path to your MCVE/Monetra installation. Please note that MCVE/Monetra support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h or monetra.h under the include directory and libmcve.so and/or libmcve.a and/or libmonetra.so and/or libmonetra.a under the lib directory.

Since MCVE/Monetra has true server/client separation, there are no additional requirements for running PHP with MCVE support. To test your MCVE/Monetra extension in PHP, you may connect to testbox.monetra.com on port 8333 for IP, or port 8444 for SSL using the MCVE/Monetra PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at » http://www.mainstreetsoftworks.com/.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines a MCVE_CONN resource returned by m_initconn().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

M_PENDING (integer)
M_DONE (integer)
M_ERROR (integer)
M_FAIL (integer)
M_SUCCESS (integer)
Typy zasobów
MCVE Funkcje
MCVE


MCVE Funkcje

Zobacz też:

Additional documentation about MCVE/Monetra's PHP API can be found at » http://www.mainstreetsoftworks.com/documentation.html. Main Street's documentation is complete and should be the primary reference for functions.

Spis treści

  • m_checkstatus — Check to see if a transaction has completed
  • m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers
  • m_connect — Establish the connection to MCVE
  • m_connectionerror — Get a textual representation of why a connection failed
  • m_deletetrans — Delete specified transaction from MCVE_CONN structure
  • m_destroyconn — Destroy the connection and MCVE_CONN structure
  • m_destroyengine — Free memory associated with IP/SSL connectivity
  • m_getcell — Get a specific cell from a comma delimited response by column name
  • m_getcellbynum — Get a specific cell from a comma delimited response by column number
  • m_getcommadelimited — Get the RAW comma delimited data returned from MCVE
  • m_getheader — Get the name of the column in a comma-delimited response
  • m_initconn — Create and initialize an MCVE_CONN structure
  • m_initengine — Ready the client for IP/SSL Communication
  • m_iscommadelimited — Checks to see if response is comma delimited
  • m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE
  • m_monitor — Perform communication with MCVE (send/receive data) Non-blocking
  • m_numcolumns — Number of columns returned in a comma delimited response
  • m_numrows — Number of rows returned in a comma delimited response
  • m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work
  • m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction
  • m_responseparam — Get a custom response parameter
  • m_returnstatus — Check to see if the transaction was successful
  • m_setblocking — Set blocking/non-blocking mode for connection
  • m_setdropfile — Set the connection method to Drop-File
  • m_setip — Set the connection method to IP
  • m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate
  • m_setssl_files — Set certificate key files and certificates if server requires client certificate verification
  • m_setssl — Set the connection method to SSL
  • m_settimeout — Set maximum transaction time (per trans)
  • m_sslcert_gen_hash — Generate hash for SSL client certificate verification
  • m_transactionssent — Check to see if outgoing buffer is clear
  • m_transinqueue — Number of transactions in client-queue
  • m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()
  • m_transnew — Start a new transaction
  • m_transsend — Finalize and send the transaction
  • m_uwait — Wait x microsecs
  • m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to
  • m_verifyconnection — Set whether or not to PING upon connect to verify connection
  • m_verifysslcert — Set whether or not to verify the server ssl certificate
Stałe predefiniowane
m_checkstatus
MCVE


Check to see if a transaction has completed

MCVE Funkcje
m_completeauthorizations
MCVE Funkcje
PHP Manual

m_checkstatus

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_checkstatus — Check to see if a transaction has completed

Opis

int m_checkstatus ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

MCVE Funkcje
m_completeauthorizations
MCVE Funkcje


Number of complete authorizations in queue, returning an array of their identifiers

m_checkstatus
m_connect
MCVE Funkcje
PHP Manual

m_completeauthorizations

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers

Opis

int m_completeauthorizations ( resource $conn , int &$array )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

array

Its description

Zwracane wartości

What the function returns, first on success, then on failure. See also the &return.success; entity

m_checkstatus
m_connect
MCVE Funkcje


Establish the connection to MCVE

m_completeauthorizations
m_connectionerror
MCVE Funkcje
PHP Manual

m_connect

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_connect — Establish the connection to MCVE

Opis

int m_connect ( resource $conn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

Zwracane wartości

m_completeauthorizations
m_connectionerror
MCVE Funkcje


Get a textual representation of why a connection failed

m_connect
m_deletetrans
MCVE Funkcje
PHP Manual

m_connectionerror

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_connectionerror — Get a textual representation of why a connection failed

Opis

string m_connectionerror ( resource $conn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

Zwracane wartości

m_connect
m_deletetrans
MCVE Funkcje


Delete specified transaction from MCVE_CONN structure

m_connectionerror
m_destroyconn
MCVE Funkcje
PHP Manual

m_deletetrans

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_deletetrans — Delete specified transaction from MCVE_CONN structure

Opis

bool m_deletetrans ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_connectionerror
m_destroyconn
MCVE Funkcje


Destroy the connection and MCVE_CONN structure

m_deletetrans
m_destroyengine
MCVE Funkcje
PHP Manual

m_destroyconn

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_destroyconn — Destroy the connection and MCVE_CONN structure

Opis

bool m_destroyconn ( resource $conn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

Zwracane wartości

Returns TRUE.

Zobacz też:

  • m_initconn() - Create and initialize an MCVE_CONN structure

m_deletetrans
m_destroyengine
MCVE Funkcje


Free memory associated with IP/SSL connectivity

m_destroyconn
m_getcell
MCVE Funkcje
PHP Manual

m_destroyengine

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_destroyengine — Free memory associated with IP/SSL connectivity

Opis

void m_destroyengine ( 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ść.

m_destroyconn
m_getcell
MCVE Funkcje


Get a specific cell from a comma delimited response by column name

m_destroyengine
m_getcellbynum
MCVE Funkcje
PHP Manual

m_getcell

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_getcell — Get a specific cell from a comma delimited response by column name

Opis

string m_getcell ( resource $conn , int $identifier , string $column , int $row )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

column

row

Zwracane wartości

m_destroyengine
m_getcellbynum
MCVE Funkcje


Get a specific cell from a comma delimited response by column number

m_getcell
m_getcommadelimited
MCVE Funkcje
PHP Manual

m_getcellbynum

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_getcellbynum — Get a specific cell from a comma delimited response by column number

Opis

string m_getcellbynum ( resource $conn , int $identifier , int $column , int $row )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

column

row

Zwracane wartości

m_getcell
m_getcommadelimited
MCVE Funkcje


Get the RAW comma delimited data returned from MCVE

m_getcellbynum
m_getheader
MCVE Funkcje
PHP Manual

m_getcommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_getcommadelimited — Get the RAW comma delimited data returned from MCVE

Opis

string m_getcommadelimited ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_getcellbynum
m_getheader
MCVE Funkcje


Get the name of the column in a comma-delimited response

m_getcommadelimited
m_initconn
MCVE Funkcje
PHP Manual

m_getheader

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_getheader — Get the name of the column in a comma-delimited response

Opis

string m_getheader ( resource $conn , int $identifier , int $column_num )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

column_num

Zwracane wartości

m_getcommadelimited
m_initconn
MCVE Funkcje


Create and initialize an MCVE_CONN structure

m_getheader
m_initengine
MCVE Funkcje
PHP Manual

m_initconn

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_initconn — Create and initialize an MCVE_CONN structure

Opis

resource m_initconn ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Returns an MCVE_CONN resource.

Zobacz też:

  • m_destroyconn() - Destroy the connection and MCVE_CONN structure

m_getheader
m_initengine
MCVE Funkcje


Ready the client for IP/SSL Communication

m_initconn
m_iscommadelimited
MCVE Funkcje
PHP Manual

m_initengine

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_initengine — Ready the client for IP/SSL Communication

Opis

int m_initengine ( string $location )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

location

Zwracane wartości

m_initconn
m_iscommadelimited
MCVE Funkcje


Checks to see if response is comma delimited

m_initengine
m_maxconntimeout
MCVE Funkcje
PHP Manual

m_iscommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_iscommadelimited — Checks to see if response is comma delimited

Opis

int m_iscommadelimited ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_initengine
m_maxconntimeout
MCVE Funkcje


The maximum amount of time the API will attempt a connection to MCVE

m_iscommadelimited
m_monitor
MCVE Funkcje
PHP Manual

m_maxconntimeout

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE

Opis

bool m_maxconntimeout ( resource $conn , int $secs )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

secs

Zwracane wartości

m_iscommadelimited
m_monitor
MCVE Funkcje


Perform communication with MCVE (send/receive data) Non-blocking

m_maxconntimeout
m_numcolumns
MCVE Funkcje
PHP Manual

m_monitor

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_monitor — Perform communication with MCVE (send/receive data) Non-blocking

Opis

int m_monitor ( resource $conn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

Zwracane wartości

m_maxconntimeout
m_numcolumns
MCVE Funkcje


Number of columns returned in a comma delimited response

m_monitor
m_numrows
MCVE Funkcje
PHP Manual

m_numcolumns

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_numcolumns — Number of columns returned in a comma delimited response

Opis

int m_numcolumns ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_monitor
m_numrows
MCVE Funkcje


Number of rows returned in a comma delimited response

m_numcolumns
m_parsecommadelimited
MCVE Funkcje
PHP Manual

m_numrows

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_numrows — Number of rows returned in a comma delimited response

Opis

int m_numrows ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_numcolumns
m_parsecommadelimited
MCVE Funkcje


Parse the comma delimited response so m_getcell, etc will work

m_numrows
m_responsekeys
MCVE Funkcje
PHP Manual

m_parsecommadelimited

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work

Opis

int m_parsecommadelimited ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_numrows
m_responsekeys
MCVE Funkcje


Returns array of strings which represents the keys that can be used for response parameters on this transaction

m_parsecommadelimited
m_responseparam
MCVE Funkcje
PHP Manual

m_responsekeys

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction

Opis

array m_responsekeys ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_parsecommadelimited
m_responseparam
MCVE Funkcje


Get a custom response parameter

m_responsekeys
m_returnstatus
MCVE Funkcje
PHP Manual

m_responseparam

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_responseparam — Get a custom response parameter

Opis

string m_responseparam ( resource $conn , int $identifier , string $key )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

key

Zwracane wartości

m_responsekeys
m_returnstatus
MCVE Funkcje


Check to see if the transaction was successful

m_responseparam
m_setblocking
MCVE Funkcje
PHP Manual

m_returnstatus

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_returnstatus — Check to see if the transaction was successful

Opis

int m_returnstatus ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_responseparam
m_setblocking
MCVE Funkcje


Set blocking/non-blocking mode for connection

m_returnstatus
m_setdropfile
MCVE Funkcje
PHP Manual

m_setblocking

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setblocking — Set blocking/non-blocking mode for connection

Opis

int m_setblocking ( resource $conn , int $tf )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

tf

Zwracane wartości

m_returnstatus
m_setdropfile
MCVE Funkcje


Set the connection method to Drop-File

m_setblocking
m_setip
MCVE Funkcje
PHP Manual

m_setdropfile

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setdropfile — Set the connection method to Drop-File

Opis

int m_setdropfile ( resource $conn , string $directory )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

directory

Zwracane wartości

m_setblocking
m_setip
MCVE Funkcje


Set the connection method to IP

m_setdropfile
m_setssl_cafile
MCVE Funkcje
PHP Manual

m_setip

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setip — Set the connection method to IP

Opis

int m_setip ( resource $conn , string $host , int $port )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

host

port

Zwracane wartości

m_setdropfile
m_setssl_cafile
MCVE Funkcje


Set SSL CA (Certificate Authority) file for verification of server certificate

m_setip
m_setssl_files
MCVE Funkcje
PHP Manual

m_setssl_cafile

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate

Opis

int m_setssl_cafile ( resource $conn , string $cafile )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

cafile

Zwracane wartości

m_setip
m_setssl_files
MCVE Funkcje


Set certificate key files and certificates if server requires client certificate verification

m_setssl_cafile
m_setssl
MCVE Funkcje
PHP Manual

m_setssl_files

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setssl_files — Set certificate key files and certificates if server requires client certificate verification

Opis

int m_setssl_files ( resource $conn , string $sslkeyfile , string $sslcertfile )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

sslkeyfile

sslcertfile

Zwracane wartości

m_setssl_cafile
m_setssl
MCVE Funkcje


Set the connection method to SSL

m_setssl_files
m_settimeout
MCVE Funkcje
PHP Manual

m_setssl

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_setssl — Set the connection method to SSL

Opis

int m_setssl ( resource $conn , string $host , int $port )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

host

port

Zwracane wartości

m_setssl_files
m_settimeout
MCVE Funkcje


Set maximum transaction time (per trans)

m_setssl
m_sslcert_gen_hash
MCVE Funkcje
PHP Manual

m_settimeout

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_settimeout — Set maximum transaction time (per trans)

Opis

int m_settimeout ( resource $conn , int $seconds )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

seconds

Zwracane wartości

m_setssl
m_sslcert_gen_hash
MCVE Funkcje


Generate hash for SSL client certificate verification

m_settimeout
m_transactionssent
MCVE Funkcje
PHP Manual

m_sslcert_gen_hash

(PECL mcve >= 5.2.0)

m_sslcert_gen_hash — Generate hash for SSL client certificate verification

Opis

string m_sslcert_gen_hash ( string $filename )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

filename

Zwracane wartości

m_settimeout
m_transactionssent
MCVE Funkcje


Check to see if outgoing buffer is clear

m_sslcert_gen_hash
m_transinqueue
MCVE Funkcje
PHP Manual

m_transactionssent

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transactionssent — Check to see if outgoing buffer is clear

Opis

int m_transactionssent ( resource $conn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

Zwracane wartości

m_sslcert_gen_hash
m_transinqueue
MCVE Funkcje


Number of transactions in client-queue

m_transactionssent
m_transkeyval
MCVE Funkcje
PHP Manual

m_transinqueue

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transinqueue — Number of transactions in client-queue

Opis

int m_transinqueue ( resource $conn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

Zwracane wartości

m_transactionssent
m_transkeyval
MCVE Funkcje


Add key/value pair to a transaction. Replaces deprecated transparam()

m_transinqueue
m_transnew
MCVE Funkcje
PHP Manual

m_transkeyval

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()

Opis

int m_transkeyval ( resource $conn , int $identifier , string $key , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

key

value

Zwracane wartości

m_transinqueue
m_transnew
MCVE Funkcje


Start a new transaction

m_transkeyval
m_transsend
MCVE Funkcje
PHP Manual

m_transnew

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transnew — Start a new transaction

Opis

int m_transnew ( resource $conn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

Zwracane wartości

m_transkeyval
m_transsend
MCVE Funkcje


Finalize and send the transaction

m_transnew
m_uwait
MCVE Funkcje
PHP Manual

m_transsend

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_transsend — Finalize and send the transaction

Opis

int m_transsend ( resource $conn , int $identifier )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

identifier

Zwracane wartości

m_transnew
m_uwait
MCVE Funkcje


Wait x microsecs

m_transsend
m_validateidentifier
MCVE Funkcje
PHP Manual

m_uwait

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_uwait — Wait x microsecs

Opis

int m_uwait ( int $microsecs )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

microsecs

Zwracane wartości

m_transsend
m_validateidentifier
MCVE Funkcje


Whether or not to validate the passed identifier on any transaction it is passed to

m_uwait
m_verifyconnection
MCVE Funkcje
PHP Manual

m_validateidentifier

(PHP 5 >= 5.0.5, PECL mcve >= 1.0.0)

m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to

Opis

int m_validateidentifier ( resource $conn , int $tf )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

tf

Zwracane wartości

m_uwait
m_verifyconnection
MCVE Funkcje


Set whether or not to PING upon connect to verify connection

m_validateidentifier
m_verifysslcert
MCVE Funkcje
PHP Manual

m_verifyconnection

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_verifyconnection — Set whether or not to PING upon connect to verify connection

Opis

bool m_verifyconnection ( resource $conn , int $tf )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

tf

Zwracane wartości

m_validateidentifier
m_verifysslcert
MCVE Funkcje


Set whether or not to verify the server ssl certificate

m_verifyconnection
SPPLUS
MCVE Funkcje
PHP Manual

m_verifysslcert

(PHP 4 >= 4.3.9, PHP 5 <= 5.0.5, PECL mcve >= 1.0.0)

m_verifysslcert — Set whether or not to verify the server ssl certificate

Opis

bool m_verifysslcert ( resource $conn , int $tf )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

conn

Zasób MCVE_CONN zwrócony przez m_initengine().

tf

Zwracane wartości

m_verifyconnection
SPPLUS
MCVE Funkcje


SPPLUS Payment System

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • SPPLUS Funkcje
    • calcul_hmac — Obtain a hmac key (needs 8 arguments)
    • calculhmac — Obtain a hmac key (needs 2 arguments)
    • nthmac — Obtain a nthmac key (needs 2 arguments)
    • signeurlpaiement — Obtain the payment url (needs 2 arguments)
m_verifysslcert
Wstęp
Przetwarzanie transakcji kartami płatniczymi


Wstęp

This extension gives you the possibility to use the » SPPLUS Payment System of the Caisse d'Epargne (a French Bank).

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

Refer to the README files in kit_php's source distribution for configuration details.

SPPLUS
Instalacja/Konfiguracja
SPPLUS


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SPPLUS


Wymagania

Informacja: You need at least PHP 4.1.0 and SPPLUS v.3

Informacja: You will need to get the new kit_php for spplus. Feel free to contact the maintainer if you can't get it.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/spplus.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Informacja:

PHP 4.3.0 or greater is required for the compression to work.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
SPPLUS Funkcje
SPPLUS


SPPLUS Funkcje

Spis treści

  • calcul_hmac — Obtain a hmac key (needs 8 arguments)
  • calculhmac — Obtain a hmac key (needs 2 arguments)
  • nthmac — Obtain a nthmac key (needs 2 arguments)
  • signeurlpaiement — Obtain the payment url (needs 2 arguments)
Stałe predefiniowane
calcul_hmac
SPPLUS


Obtain a hmac key (needs 8 arguments)

SPPLUS Funkcje
calculhmac
SPPLUS Funkcje
PHP Manual

calcul_hmac

(PECL spplus >= 1.0.0)

calcul_hmac — Obtain a hmac key (needs 8 arguments)

Opis

string calcul_hmac ( string $clent , string $siretcode , string $price , string $reference , string $validity , string $taxation , string $devise , string $language )
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.

SPPLUS Funkcje
calculhmac
SPPLUS Funkcje


Obtain a hmac key (needs 2 arguments)

calcul_hmac
nthmac
SPPLUS Funkcje
PHP Manual

calculhmac

(PECL spplus >= 1.0.0)

calculhmac — Obtain a hmac key (needs 2 arguments)

Opis

string calculhmac ( string $clent , string $data )
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.

calcul_hmac
nthmac
SPPLUS Funkcje


Obtain a nthmac key (needs 2 arguments)

calculhmac
signeurlpaiement
SPPLUS Funkcje
PHP Manual

nthmac

(PECL spplus >= 1.0.0)

nthmac — Obtain a nthmac key (needs 2 arguments)

Opis

string nthmac ( string $clent , string $data )
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.

calculhmac
signeurlpaiement
SPPLUS Funkcje


Obtain the payment url (needs 2 arguments)

nthmac
Rozszerzenia kryptograficzne
SPPLUS Funkcje
PHP Manual

signeurlpaiement

(PECL spplus >= 1.0.0)

signeurlpaiement — Obtain the payment url (needs 2 arguments)

Opis

string nthmac ( string $clent , string $data )
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.

nthmac
Rozszerzenia kryptograficzne
SPPLUS Funkcje


Rozszerzenia kryptograficzne

  • Crack — Cracklib
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Funkcje Crack
  • Hash — HASH Message Digest Framework
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Hash Funkcje
  • Mcrypt
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Mcrypt ciphers
    • Przykłady
    • Mcrypt Funkcje
  • Mhash
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Mhash Funkcje
  • OpenSSL
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Key/Certificate parameters
    • Certificate Verification
    • OpenSSL Funkcje
signeurlpaiement
Crack
Opis funkcji


Cracklib

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Funkcje Crack
    • crack_check — Rozpoczyna sprawdzanie podanego hasła
    • crack_closedict — Zamyka otwarty słownik CrackLib
    • crack_getlastmessage — Zwraca wiadomość ostatniego wykonanego testu hasła
    • crack_opendict — Otwiera nowy słownik CrackLib
Rozszerzenia kryptograficzne
Wstęp
Rozszerzenia kryptograficzne


Wstęp

These functions allow you to use the CrackLib library to test the 'strength' of a password. The 'strength' of a password is tested by that checks length, use of upper and lower case and checked against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0.

Crack
Instalacja/Konfiguracja
Crack


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Crack


Wymagania

More information regarding CrackLib along with the library can be found at » http://sourceforge.net/projects/cracklib.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/crack.

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. Aby zbudować PHP z obsługą Crack należy podać opcję --with-crack[=DIR] wywołania configure.

Użytkownicy Windows mogą włączyć obsługe funkcji Crack, poprzez dodanie php_crack.dll w pliku php.ini. W PHP 4 ten DLL znajduje się w podkatalogu extensions/ binarnej dystrybucji PHP dla Windows. DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracji
Nazwa | Domyślna wartość | Możliwość zmian | Rejestr zmian
crack.default_dictionary | NULL | PHP_INI_PERDIR | PHP_INI_SYSTEM w crack <= 0.2. Dostępne od PHP 4.0.5. Usunięte w PHP 5.0.0.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

The CrackLib extension defines a dictionary resource identifier returned by crack_opendict().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Crack


Przykłady

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Przykład #1 CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

Informacja:

If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

Stałe predefiniowane
Funkcje Crack
Crack


Funkcje Crack

Spis treści

  • crack_check — Rozpoczyna sprawdzanie podanego hasła
  • crack_closedict — Zamyka otwarty słownik CrackLib
  • crack_getlastmessage — Zwraca wiadomość ostatniego wykonanego testu hasła
  • crack_opendict — Otwiera nowy słownik CrackLib
Przykłady
crack_check
Crack


Rozpoczyna sprawdzanie podanego hasła

Funkcje Crack
crack_closedict
Funkcje Crack
PHP Manual

crack_check

(PECL crack >= 0.1)

crack_check — Rozpoczyna sprawdzanie podanego hasła

Opis

bool crack_check ( resource $dictionary , string $password )
bool crack_check ( string $password )

Rozpoczyna sprawdzanie podanego hasła według zadanego słownika.

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

dictionary

Biblioteka słownika. Jeśli nie podana, zostanie wykorzystana ostatnio użyta.

password

Sprawdzane hasło.

Zwracane wartości

Zwraca TRUE jeśli password jest 'silne', lub FALSE w przypadku 'słabego' hasła.

Funkcje Crack
crack_closedict
Funkcje Crack


Zamyka otwarty słownik CrackLib

crack_check
crack_getlastmessage
Funkcje Crack
PHP Manual

crack_closedict

(PECL crack >= 0.1)

crack_closedict — Zamyka otwarty słownik CrackLib

Opis

bool crack_closedict ([ resource $dictionary ] )

crack_closedict() zamyka wskaźnik dictionary słownika.

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

dictionary

Słownik do zamknięcia. Jeśli parametr ten nie zostanie podany zamyka aktualnie wykorzystywany słownik.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • crack_opendict() - Otwiera nowy słownik CrackLib

crack_check
crack_getlastmessage
Funkcje Crack


Zwraca wiadomość ostatniego wykonanego testu hasła

crack_closedict
crack_opendict
Funkcje Crack
PHP Manual

crack_getlastmessage

(PECL crack >= 0.1)

crack_getlastmessage — Zwraca wiadomość ostatniego wykonanego testu hasła

Opis

string crack_getlastmessage ( void )

crack_getlastmessage() zwraca wiadomość ostatniego wykonanego testu hasła.

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.

Zwracane wartości

Wiadomość ostatniego testu lub FALSE jeśli żaden test nie został wykonany do tej pory.

Zwracana wiadoość jest jedną z:

  • it's WAY too short (jest zdecydowanie za krótkie)
  • it is too short (jest za krótkie)
  • it does not contain enough DIFFERENT characters (nie zawiera wystarczająco różnych znaków)
  • it is all whitespace (zawiera same białe znaki)
  • it is too simplistic/systematic (jest zbyt proste/systematyczne)
  • it looks like a National Insurance number. (wygląda jak numer ubezpieczenia w USA)
  • it is based on a dictionary word (bazuje na słowie ze słownika)
  • it is based on a (reversed) dictionary word (bazuje na odwróconym słowie ze słownika)
  • strong password (mocne/dobre hasło)

Zobacz też:

  • crack_check() - Rozpoczyna sprawdzanie podanego hasła

crack_closedict
crack_opendict
Funkcje Crack


Otwiera nowy słownik CrackLib

crack_getlastmessage
Hash
Funkcje Crack
PHP Manual

crack_opendict

(PECL crack >= 0.1)

crack_opendict — Otwiera nowy słownik CrackLib

Opis

resource crack_opendict ( string $dictionary )

crack_opendict() otwiera słownik dictionary do użytku przez crack_check().

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:

Tylko jeden słownik może być otwarty w tej samej chwili.

Parametry

dictionary

Ścieżka do słownika CrackLib

Zwracane wartości

Zwraca wskaźnik zasobów słownika w przypadku sukcesu lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • crack_check() - Rozpoczyna sprawdzanie podanego hasła
  • crack_closedict() - Zamyka otwarty słownik CrackLib

crack_getlastmessage
Hash
Funkcje Crack


HASH Message Digest Framework

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Hash Funkcje
    • hash_algos — Return a list of registered hashing algorithms
    • hash_copy — Copy hashing context
    • hash_file — Generate a hash value using the contents of a given file
    • hash_final — Finalize an incremental hash and return resulting digest
    • hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file
    • hash_hmac — Generate a keyed hash value using the HMAC method
    • hash_init — Initialize an incremental hashing context
    • hash_update_file — Pump data into an active hashing context from a file
    • hash_update_stream — Pump data into an active hashing context from an open stream
    • hash_update — Pump data into an active hashing context
    • hash — Generate a hash value (message digest)
crack_opendict
Wstęp
Rozszerzenia kryptograficzne


Wstęp

Message Digest (hash) engine. Allows direct or incremental processing of arbitrary length messages using a variety of hashing algorithms.

Hash
Instalacja/Konfiguracja
Hash


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Hash


Wymagania

The Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2. It may be explicitly disabled by using the --disable-hash switch to configure. Earlier versions of PHP may incorporate the Hash extension by installing the » PECL module.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Typy zasobów

This extension defines a Hashing Context resource returned by hash_init().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

HASH_HMAC (integer)
Optional flag for hash_init(). Indicates that the HMAC digest-keying algorithm should be applied to the current hashing context.
Typy zasobów
Hash Funkcje
Hash


Hash Funkcje

Spis treści

  • hash_algos — Return a list of registered hashing algorithms
  • hash_copy — Copy hashing context
  • hash_file — Generate a hash value using the contents of a given file
  • hash_final — Finalize an incremental hash and return resulting digest
  • hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file
  • hash_hmac — Generate a keyed hash value using the HMAC method
  • hash_init — Initialize an incremental hashing context
  • hash_update_file — Pump data into an active hashing context from a file
  • hash_update_stream — Pump data into an active hashing context from an open stream
  • hash_update — Pump data into an active hashing context
  • hash — Generate a hash value (message digest)
Stałe predefiniowane
hash_algos
Hash


Return a list of registered hashing algorithms

Hash Funkcje
hash_copy
Hash Funkcje
PHP Manual

hash_algos

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_algos — Return a list of registered hashing algorithms

Opis

array hash_algos ( void )

Zwracane wartości

Returns a numerically indexed array containing the list of supported hashing algorithms.

Rejestr zmian

Wersja | Opis
5.4.0 | Support for joaat, fnv132 and fnv164 was added. Support for Salsa10 and Salsa20 was removed.
5.3.0 | Support for md2, ripemd256, ripemd320, salsa10, salsa20, snefru256 and sha224 was added

Przykłady

Przykład #1 hash_algos() example

As of PHP 5.3.0, hash_algos() will return the following list of algorithm names.

<?php
print_r(hash_algos());
?>

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

Array
(
    [0] => md2
    [1] => md4
    [2] => md5
    [3] => sha1
    [4] => sha224
    [5] => sha256
    [6] => sha384
    [7] => sha512
    [8] => ripemd128
    [9] => ripemd160
    [10] => ripemd256
    [11] => ripemd320
    [12] => whirlpool
    [13] => tiger128,3
    [14] => tiger160,3
    [15] => tiger192,3
    [16] => tiger128,4
    [17] => tiger160,4
    [18] => tiger192,4
    [19] => snefru
    [20] => snefru256
    [21] => gost
    [22] => adler32
    [23] => crc32
    [24] => crc32b
    [25] => salsa10
    [26] => salsa20
    [27] => haval128,3
    [28] => haval160,3
    [29] => haval192,3
    [30] => haval224,3
    [31] => haval256,3
    [32] => haval128,4
    [33] => haval160,4
    [34] => haval192,4
    [35] => haval224,4
    [36] => haval256,4
    [37] => haval128,5
    [38] => haval160,5
    [39] => haval192,5
    [40] => haval224,5
    [41] => haval256,5
)

Hash Funkcje
hash_copy
Hash Funkcje


Copy hashing context

hash_algos
hash_file
Hash Funkcje
PHP Manual

hash_copy

(PHP 5 >= 5.3.0)

hash_copy — Copy hashing context

Opis

resource hash_copy ( resource $context )

Parametry

context

Hashing context returned by hash_init().

Zwracane wartości

Returns a copy of Hashing Context resource.

Przykłady

Przykład #1 hash_copy() example

<?php
$context = hash_init("md5");
hash_update($context, "data");

/* copy context to be able to continue using it */
$copy_context = hash_copy($context);

echo hash_final($context), "\n";

hash_update($copy_context, "data");
echo hash_final($copy_context), "\n";
?>

Powyższy przykład wyświetli:

8d777f385d3dfec8815d20f7496026dc
511ae0b1c13f95e5f08f1a0dd3da3d93

hash_algos
hash_file
Hash Funkcje


Generate a hash value using the contents of a given file

hash_copy
hash_final
Hash Funkcje
PHP Manual

hash_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_file — Generate a hash value using the contents of a given file

Opis

string hash_file ( string $algo , string $filename [, bool $raw_output = false ] )

Parametry

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

filename

URL describing location of file to be hashed; Supports fopen wrappers.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Zwracane wartości

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Przykłady

Przykład #1 Using hash_file()

<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_file('md5', 'example.txt');
?>

Powyższy przykład wyświetli:

5c6ffbdd40d9556b73a21e63c3e0e904

Zobacz też:

  • hash() - Generate a hash value (message digest)
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file
  • hash_update_file() - Pump data into an active hashing context from a file
  • md5_file() - Calculates the md5 hash of a given file
  • sha1_file() - Calculate the sha1 hash of a file

hash_copy
hash_final
Hash Funkcje


Finalize an incremental hash and return resulting digest

hash_file
hash_hmac_file
Hash Funkcje
PHP Manual

hash_final

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_final — Finalize an incremental hash and return resulting digest

Opis

string hash_final ( resource $context [, bool $raw_output = false ] )

Parametry

context

Hashing context returned by hash_init().

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Zwracane wartości

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Przykłady

Przykład #1 hash_final() example

<?php
$ctx = hash_init('sha1');
hash_update($ctx, 'The quick brown fox jumped over the lazy dog.');
echo hash_final($ctx);
?>

Powyższy przykład wyświetli:

c0854fb9fb03c41cce3802cb0d220529e6eef94e

Zobacz też:

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_update_stream() - Pump data into an active hashing context from an open stream
  • hash_update_file() - Pump data into an active hashing context from a file

hash_file
hash_hmac_file
Hash Funkcje


Generate a keyed hash value using the HMAC method and the contents of a given file

hash_final
hash_hmac
Hash Funkcje
PHP Manual

hash_hmac_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_hmac_file — Generate a keyed hash value using the HMAC method and the contents of a given file

Opis

string hash_hmac_file ( string $algo , string $filename , string $key [, bool $raw_output = false ] )

Parametry

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_algos() for a list of supported algorithms.

filename

URL describing location of file to be hashed; Supports fopen wrappers.

key

Shared secret key used for generating the HMAC variant of the message digest.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Zwracane wartości

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Przykłady

Przykład #1 hash_hmac_file() example

<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_hmac_file('md5', 'example.txt', 'secret');
?>

Powyższy przykład wyświetli:

7eb2b5c37443418fc77c136dd20e859c

Zobacz też:

  • hash_algos() - Return a list of registered hashing algorithms
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_file() - Generate a hash value using the contents of a given file

hash_final
hash_hmac
Hash Funkcje


Generate a keyed hash value using the HMAC method

hash_hmac_file
hash_init
Hash Funkcje
PHP Manual

hash_hmac

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_hmac — Generate a keyed hash value using the HMAC method

Opis

string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )

Parametry

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_algos() for a list of supported algorithms.

data

Message to be hashed.

key

Shared secret key used for generating the HMAC variant of the message digest.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Zwracane wartości

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Przykłady

Przykład #1 hash_hmac() example

<?php
echo hash_hmac('ripemd160', 'The quick brown fox jumped over the lazy dog.', 'secret');
?>

Powyższy przykład wyświetli:

b8e7ae12510bdfb1812e463a7f086122cf37e4f7

Zobacz też:

  • hash() - Generate a hash value (message digest)
  • hash_algos() - Return a list of registered hashing algorithms
  • hash_init() - Initialize an incremental hashing context
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file

hash_hmac_file
hash_init
Hash Funkcje


Initialize an incremental hashing context

hash_hmac
hash_update_file
Hash Funkcje
PHP Manual

hash_init

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_init — Initialize an incremental hashing context

Opis

resource hash_init ( string $algo [, int $options = 0 [, string $key = NULL ]] )

Parametry

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

options

Optional settings for hash generation, currently supports only one option: HASH_HMAC. When specified, the key must be specified.

key

When HASH_HMAC is specified for options, a shared secret key to be used with the HMAC hashing method must be supplied in this parameter.

Zwracane wartości

Returns a Hashing Context resource for use with hash_update(), hash_update_stream(), hash_update_file(), and hash_final().

Przykłady

Przykład #1 Incremental hashing example

<?php
$ctx = hash_init('md5');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
echo hash_final($ctx);
?>

Powyższy przykład wyświetli:

5c6ffbdd40d9556b73a21e63c3e0e904

Zobacz też:

  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file

hash_hmac
hash_update_file
Hash Funkcje


Pump data into an active hashing context from a file

hash_init
hash_update_stream
Hash Funkcje
PHP Manual

hash_update_file

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_update_file — Pump data into an active hashing context from a file

Opis

bool hash_update_file ( resource $context , string $filename [, resource $context = NULL ] )

Parametry

context

Hashing context returned by hash_init().

filename

URL describing location of file to be hashed; Supports fopen wrappers.

context

Stream context as returned by stream_context_create().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_update_stream() - Pump data into an active hashing context from an open stream
  • hash_final() - Finalize an incremental hash and return resulting digest
  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file

hash_init
hash_update_stream
Hash Funkcje


Pump data into an active hashing context from an open stream

hash_update_file
hash_update
Hash Funkcje
PHP Manual

hash_update_stream

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_update_stream — Pump data into an active hashing context from an open stream

Opis

int hash_update_stream ( resource $context , resource $handle [, int $length = -1 ] )

Parametry

context

Hashing context returned by hash_init().

handle

Open file handle as returned by any stream creation function.

length

Maximum number of characters to copy from handle into the hashing context.

Zwracane wartości

Actual number of bytes added to the hashing context from handle.

Przykłady

Przykład #1 hash_update_stream() example

<?php
$fp = tmpfile();
fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
rewind($fp);

$ctx = hash_init('md5');
hash_update_stream($ctx, $fp);
echo hash_final($ctx);
?>

Powyższy przykład wyświetli:

5c6ffbdd40d9556b73a21e63c3e0e904

Zobacz też:

  • hash_init() - Initialize an incremental hashing context
  • hash_update() - Pump data into an active hashing context
  • hash_final() - Finalize an incremental hash and return resulting digest
  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file

hash_update_file
hash_update
Hash Funkcje


Pump data into an active hashing context

hash_update_stream
hash
Hash Funkcje
PHP Manual

hash_update

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash_update — Pump data into an active hashing context

Opis

bool hash_update ( resource $context , string $data )

Parametry

context

Hashing context returned by hash_init().

data

Message to be included in the hash digest.

Zwracane wartości

Returns TRUE.

Zobacz też:

  • hash_init() - Initialize an incremental hashing context
  • hash_update_file() - Pump data into an active hashing context from a file
  • hash_update_stream() - Pump data into an active hashing context from an open stream
  • hash_final() - Finalize an incremental hash and return resulting digest

hash_update_stream
hash
Hash Funkcje


Generate a hash value (message digest)

hash_update
Mcrypt
Hash Funkcje
PHP Manual

hash

(PHP 5 >= 5.1.2, PECL hash >= 1.1)

hash — Generate a hash value (message digest)

Opis

string hash ( string $algo , string $data [, bool $raw_output = false ] )

Parametry

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

data

Message to be hashed.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Zwracane wartości

Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true in which case the raw binary representation of the message digest is returned.

Przykłady

Przykład #1 A hash() example

<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
?>

Powyższy przykład wyświetli:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

Zobacz też:

  • hash_file() - Generate a hash value using the contents of a given file
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_init() - Initialize an incremental hashing context
  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string

hash_update
Mcrypt
Hash Funkcje


Mcrypt

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Mcrypt ciphers
  • Przykłady
  • Mcrypt Funkcje
    • mcrypt_cbc — Encrypts/decrypts data in CBC mode
    • mcrypt_cfb — Encrypts/decrypts data in CFB mode
    • mcrypt_create_iv — Creates an initialization vector (IV) from a random source
    • mcrypt_decrypt — Decrypts crypttext with given parameters
    • mcrypt_ecb — Deprecated: Encrypts/decrypts data in ECB mode
    • mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm
    • mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm
    • mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm
    • mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode
    • mcrypt_enc_get_modes_name — Returns the name of the opened mode
    • mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks
    • mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
    • mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks
    • mcrypt_enc_self_test — Runs a self test on the opened module
    • mcrypt_encrypt — Encrypts plaintext with given parameters
    • mcrypt_generic_deinit — This function deinitializes an encryption module
    • mcrypt_generic_end — This function terminates encryption
    • mcrypt_generic_init — This function initializes all buffers needed for encryption
    • mcrypt_generic — This function encrypts data
    • mcrypt_get_block_size — Gets the block size of the specified cipher
    • mcrypt_get_cipher_name — Gets the name of the specified cipher
    • mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination
    • mcrypt_get_key_size — Gets the key size of the specified cipher
    • mcrypt_list_algorithms — Gets an array of all supported ciphers
    • mcrypt_list_modes — Gets an array of all supported modes
    • mcrypt_module_close — Closes the mcrypt module
    • mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm
    • mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode
    • mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not
    • mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
    • mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not
    • mcrypt_module_open — Opens the module of the algorithm and the mode to be used
    • mcrypt_module_self_test — This function runs a self test on the specified module
    • mcrypt_ofb — Encrypts/decrypts data in OFB mode
    • mdecrypt_generic — Decrypts data
hash
Wstęp
Rozszerzenia kryptograficzne


Wstęp

This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free". CFB/OFB are 8bit by default.

Mcrypt
Instalacja/Konfiguracja
Mcrypt


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Mcrypt


Wymagania

These functions work using » mcrypt. To use it, download libmcrypt-x.x.tar.gz from » http://mcrypt.sourceforge.net/ and follow the included installation instructions.

As of PHP 5.0.0 you will need libmcrypt Version 2.5.6 or greater.

Windows users will find the library is the PHP 5.2 Windows binaries release. PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install directory. Make sure you compile libmcrypt with the option --disable-posix-threads .

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Mcrypt configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mcrypt.algorithms_dir | NULL | PHP_INI_ALL |
mcrypt.modes_dir | 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.

mcrypt.algorithms_dir string

The directory that contains the algorithms. Defaults to the directories compiled within libmcrypt, which is typically /usr/local/lib/libmcrypt. See mcrypt_list_algorithms() for additional details.

mcrypt.modes_dir string

The directory that contains the modes. Defaults to the directories compiled within libmcrypt, which is typically /usr/local/lib/libmcrypt. See mcrypt_list_modes() for additional details.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

mcrypt_module_open() returns an encryption descriptor.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).

  • MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.
  • MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
  • MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
  • MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
  • MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.
  • MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like "WAKE" or "RC4".

Some other mode and random device constants:

MCRYPT_ENCRYPT (integer)
MCRYPT_DECRYPT (integer)
MCRYPT_DEV_RANDOM (integer)
MCRYPT_DEV_URANDOM (integer)
MCRYPT_RAND (integer)

Typy zasobów
Mcrypt ciphers
Mcrypt


Mcrypt ciphers

Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().

  • MCRYPT_3DES
  • MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)
  • MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)
  • MCRYPT_BLOWFISH
  • MCRYPT_CAST_128
  • MCRYPT_CAST_256
  • MCRYPT_CRYPT
  • MCRYPT_DES
  • MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)
  • MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)
  • MCRYPT_GOST
  • MCRYPT_IDEA (non-free)
  • MCRYPT_LOKI97 (libmcrypt > 2.4.x only)
  • MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)
  • MCRYPT_PANAMA (libmcrypt > 2.4.x only)
  • MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)
  • MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)
  • MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)
  • MCRYPT_RC2
  • MCRYPT_RC4 (libmcrypt 2.2.x only)
  • MCRYPT_RC6 (libmcrypt > 2.4.x only)
  • MCRYPT_RC6_128 (libmcrypt 2.2.x only)
  • MCRYPT_RC6_192 (libmcrypt 2.2.x only)
  • MCRYPT_RC6_256 (libmcrypt 2.2.x only)
  • MCRYPT_SAFER64
  • MCRYPT_SAFER128
  • MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)
  • MCRYPT_SERPENT(libmcrypt > 2.4.x only)
  • MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)
  • MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)
  • MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)
  • MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)
  • MCRYPT_TEAN (libmcrypt 2.2.x only)
  • MCRYPT_THREEWAY
  • MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)
  • MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )
  • MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)
  • MCRYPT_TWOFISH192
  • MCRYPT_TWOFISH256
  • MCRYPT_WAKE (libmcrypt > 2.4.x only)
  • MCRYPT_XTEA (libmcrypt > 2.4.x only)

You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).

Stałe predefiniowane
Przykłady
Mcrypt


Przykłady

Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.

Przykład #1 Encrypt an input value with TripleDES under 2.2.x in ECB mode

<?php
$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>
This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Przykład #2 Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?php
    $key = "this is a secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
?>
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

Mcrypt ciphers
Mcrypt Funkcje
Mcrypt


Mcrypt Funkcje

Spis treści

  • mcrypt_cbc — Encrypts/decrypts data in CBC mode
  • mcrypt_cfb — Encrypts/decrypts data in CFB mode
  • mcrypt_create_iv — Creates an initialization vector (IV) from a random source
  • mcrypt_decrypt — Decrypts crypttext with given parameters
  • mcrypt_ecb — Deprecated: Encrypts/decrypts data in ECB mode
  • mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm
  • mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm
  • mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm
  • mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode
  • mcrypt_enc_get_modes_name — Returns the name of the opened mode
  • mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
  • mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks
  • mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
  • mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks
  • mcrypt_enc_self_test — Runs a self test on the opened module
  • mcrypt_encrypt — Encrypts plaintext with given parameters
  • mcrypt_generic_deinit — This function deinitializes an encryption module
  • mcrypt_generic_end — This function terminates encryption
  • mcrypt_generic_init — This function initializes all buffers needed for encryption
  • mcrypt_generic — This function encrypts data
  • mcrypt_get_block_size — Gets the block size of the specified cipher
  • mcrypt_get_cipher_name — Gets the name of the specified cipher
  • mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination
  • mcrypt_get_key_size — Gets the key size of the specified cipher
  • mcrypt_list_algorithms — Gets an array of all supported ciphers
  • mcrypt_list_modes — Gets an array of all supported modes
  • mcrypt_module_close — Closes the mcrypt module
  • mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm
  • mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode
  • mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm
  • mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not
  • mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
  • mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not
  • mcrypt_module_open — Opens the module of the algorithm and the mode to be used
  • mcrypt_module_self_test — This function runs a self test on the specified module
  • mcrypt_ofb — Encrypts/decrypts data in OFB mode
  • mdecrypt_generic — Decrypts data
Przykłady
mcrypt_cbc
Mcrypt


Encrypts/decrypts data in CBC mode

Mcrypt Funkcje
mcrypt_cfb
Mcrypt Funkcje
PHP Manual

mcrypt_cbc

(PHP 4, PHP 5)

mcrypt_cbc — Encrypts/decrypts data in CBC mode

Opis

string mcrypt_cbc ( int $cipher , string $key , string $data , int $mode [, string $iv ] )
string mcrypt_cbc ( string $cipher , string $key , string $data , int $mode [, string $iv ] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

Mcrypt Funkcje
mcrypt_cfb
Mcrypt Funkcje


Encrypts/decrypts data in CFB mode

mcrypt_cbc
mcrypt_create_iv
Mcrypt Funkcje
PHP Manual

mcrypt_cfb

(PHP 4, PHP 5)

mcrypt_cfb — Encrypts/decrypts data in CFB mode

Opis

string mcrypt_cfb ( int $cipher , string $key , string $data , int $mode , string $iv )
string mcrypt_cfb ( string $cipher , string $key , string $data , int $mode [, string $iv ] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_cbc
mcrypt_create_iv
Mcrypt Funkcje


Creates an initialization vector (IV) from a random source

mcrypt_cfb
mcrypt_decrypt
Mcrypt Funkcje
PHP Manual

mcrypt_create_iv

(PHP 4, PHP 5)

mcrypt_create_iv — Creates an initialization vector (IV) from a random source

Opis

string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )

Creates an initialization vector (IV) from a random source.

The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without losing security.

Parametry

size

The size of the IV.

source

The source of the IV. The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). Prior to 5.3.0, MCRYPT_RAND was the only one supported on Windows.

Zwracane wartości

Returns the initialization vector, or FALSE on error.

Rejestr zmian

Wersja | Opis
5.3.0 | MCRYPT_DEV_RANDOM and MCRYPT_DEV_URANDOM became available on Windows platforms.
5.3.0 | It is no longer required to call srand() first. This is now done automatically.

Przykłady

Przykład #1 mcrypt_create_iv() Example

<?php
    $size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
?>

Zobacz też:

  • » http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
  • » http://www.quadibloc.com/crypto/co0409.htm
  • Chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9)

mcrypt_cfb
mcrypt_decrypt
Mcrypt Funkcje


Decrypts crypttext with given parameters

mcrypt_create_iv
mcrypt_ecb
Mcrypt Funkcje
PHP Manual

mcrypt_decrypt

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_decrypt — Decrypts crypttext with given parameters

Opis

string mcrypt_decrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] )

Decrypts the data and returns the unencrypted data.

Parametry

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

key

The key with which the data was encrypted. If it's smaller than the required keysize, it is padded with '\0'.

data

The data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

iv

The iv parameter is used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all its bytes set to '\0'.

Zwracane wartości

Returns the decrypted data as a string.

mcrypt_create_iv
mcrypt_ecb
Mcrypt Funkcje


Deprecated: Encrypts/decrypts data in ECB mode

mcrypt_decrypt
mcrypt_enc_get_algorithms_name
Mcrypt Funkcje
PHP Manual

mcrypt_ecb

(PHP 4, PHP 5)

mcrypt_ecb — Deprecated: Encrypts/decrypts data in ECB mode

Opis

string mcrypt_ecb ( int $cipher , string $key , string $data , int $mode )
string mcrypt_ecb ( string $cipher , string $key , string $data , int $mode [, string $iv ] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function is deprecated and should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_decrypt
mcrypt_enc_get_algorithms_name
Mcrypt Funkcje


Returns the name of the opened algorithm

mcrypt_ecb
mcrypt_enc_get_block_size
Mcrypt Funkcje
PHP Manual

mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_algorithms_name — Returns the name of the opened algorithm

Opis

string mcrypt_enc_get_algorithms_name ( resource $td )

This function returns the name of the algorithm.

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns the name of the opened algorithm as a string.

Przykłady

Przykład #1 mcrypt_enc_get_algorithms_name() example

<?php
$td = mcrypt_module_open(MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";

$td = mcrypt_module_open('cast-256', '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_algorithms_name($td). "\n";
?>

Powyższy przykład wyświetli:

CAST-256
CAST-256

mcrypt_ecb
mcrypt_enc_get_block_size
Mcrypt Funkcje


Returns the blocksize of the opened algorithm

mcrypt_enc_get_algorithms_name
mcrypt_enc_get_iv_size
Mcrypt Funkcje
PHP Manual

mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_block_size — Returns the blocksize of the opened algorithm

Opis

int mcrypt_enc_get_block_size ( resource $td )

Gets the blocksize of the opened algorithm.

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns the block size of the specified algorithm in bytes.

mcrypt_enc_get_algorithms_name
mcrypt_enc_get_iv_size
Mcrypt Funkcje


Returns the size of the IV of the opened algorithm

mcrypt_enc_get_block_size
mcrypt_enc_get_key_size
Mcrypt Funkcje
PHP Manual

mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_iv_size — Returns the size of the IV of the opened algorithm

Opis

int mcrypt_enc_get_iv_size ( resource $td )

This function returns the size of the IV of the algorithm specified by the encryption descriptor in bytes. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns the size of the IV, or 0 if the IV is ignored by the algorithm.

mcrypt_enc_get_block_size
mcrypt_enc_get_key_size
Mcrypt Funkcje


Returns the maximum supported keysize of the opened mode

mcrypt_enc_get_iv_size
mcrypt_enc_get_modes_name
Mcrypt Funkcje
PHP Manual

mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_key_size — Returns the maximum supported keysize of the opened mode

Opis

int mcrypt_enc_get_key_size ( resource $td )

Gets the maximum supported key size of the algorithm in bytes.

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns the maximum supported key size of the algorithm in bytes.

mcrypt_enc_get_iv_size
mcrypt_enc_get_modes_name
Mcrypt Funkcje


Returns the name of the opened mode

mcrypt_enc_get_key_size
mcrypt_enc_get_supported_key_sizes
Mcrypt Funkcje
PHP Manual

mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_modes_name — Returns the name of the opened mode

Opis

string mcrypt_enc_get_modes_name ( resource $td )

This function returns the name of the mode.

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns the name as a string.

Przykłady

Przykład #1 mcrypt_enc_get_modes_name() example

<?php
$td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
echo mcrypt_enc_get_modes_name($td). "\n";

$td = mcrypt_module_open ('cast-256', '', 'ecb', '');
echo mcrypt_enc_get_modes_name($td). "\n";
?>

Powyższy przykład wyświetli:

CFB
ECB

mcrypt_enc_get_key_size
mcrypt_enc_get_supported_key_sizes
Mcrypt Funkcje


Returns an array with the supported keysizes of the opened algorithm

mcrypt_enc_get_modes_name
mcrypt_enc_is_block_algorithm_mode
Mcrypt Funkcje
PHP Manual

mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Opis

array mcrypt_enc_get_supported_key_sizes ( resource $td )

Gets the supported key sizes of the opened algorithm.

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.

Przykłady

Przykład #1 mcrypt_enc_get_supported_key_sizes() example

<?php
    $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
    var_dump(mcrypt_enc_get_supported_key_sizes($td));
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

mcrypt_enc_get_modes_name
mcrypt_enc_is_block_algorithm_mode
Mcrypt Funkcje


Checks whether the encryption of the opened mode works on blocks

mcrypt_enc_get_supported_key_sizes
mcrypt_enc_is_block_algorithm
Mcrypt Funkcje
PHP Manual

mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_algorithm_mode — Checks whether the encryption of the opened mode works on blocks

Opis

bool mcrypt_enc_is_block_algorithm_mode ( resource $td )

Tells whether the algorithm of the opened mode works on blocks (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb)..

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE.

mcrypt_enc_get_supported_key_sizes
mcrypt_enc_is_block_algorithm
Mcrypt Funkcje


Checks whether the algorithm of the opened mode is a block algorithm

mcrypt_enc_is_block_algorithm_mode
mcrypt_enc_is_block_mode
Mcrypt Funkcje
PHP Manual

mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm

Opis

bool mcrypt_enc_is_block_algorithm ( resource $td )

Tells whether the algorithm of the opened mode is a block algorithm.

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns TRUE if the algorithm is a block algorithm or FALSE if it is a stream one.

mcrypt_enc_is_block_algorithm_mode
mcrypt_enc_is_block_mode
Mcrypt Funkcje


Checks whether the opened mode outputs blocks

mcrypt_enc_is_block_algorithm
mcrypt_enc_self_test
Mcrypt Funkcje
PHP Manual

mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_is_block_mode — Checks whether the opened mode outputs blocks

Opis

bool mcrypt_enc_is_block_mode ( resource $td )

Tells whether the opened mode outputs blocks (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

Parametry

td

The encryption descriptor.

Zwracane wartości

Returns TRUE if the mode outputs blocks of bytes, or FALSE if it outputs just bytes.

mcrypt_enc_is_block_algorithm
mcrypt_enc_self_test
Mcrypt Funkcje


Runs a self test on the opened module

mcrypt_enc_is_block_mode
mcrypt_encrypt
Mcrypt Funkcje
PHP Manual

mcrypt_enc_self_test

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_self_test — Runs a self test on the opened module

Opis

int mcrypt_enc_self_test ( resource $td )

This function runs the self test on the algorithm specified by the descriptor td.

Parametry

td

The encryption descriptor.

Zwracane wartości

If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

mcrypt_enc_is_block_mode
mcrypt_encrypt
Mcrypt Funkcje


Encrypts plaintext with given parameters

mcrypt_enc_self_test
mcrypt_generic_deinit
Mcrypt Funkcje
PHP Manual

mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_encrypt — Encrypts plaintext with given parameters

Opis

string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] )

Encrypts the data and returns it.

Parametry

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

key

The key with which the data will be encrypted. If it's smaller than the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys.

It is recommended to use the mhash functions to create a key from a string.

data

The data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

The returned crypttext can be larger than the size of the data that was given by data.

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

iv

Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all its bytes set to '\0'.

Zwracane wartości

Returns the encrypted data, as a string.

Przykłady

Przykład #1 mcrypt_encrypt() Example

<?php
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
    $text = "Meet me at 11 o'clock behind the monument.";
    echo strlen($text) . "\n";

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo strlen($crypttext) . "\n";
?>

Powyższy przykład wyświetli:

42
64

See also mcrypt_module_open() for a more advanced API and an example.

mcrypt_enc_self_test
mcrypt_generic_deinit
Mcrypt Funkcje


This function deinitializes an encryption module

mcrypt_encrypt
mcrypt_generic_end
Mcrypt Funkcje
PHP Manual

mcrypt_generic_deinit

(PHP 4 >= 4.0.7, PHP 5)

mcrypt_generic_deinit — This function deinitializes an encryption module

Opis

bool mcrypt_generic_deinit ( resource $td )

This function terminates encryption specified by the encryption descriptor (td). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script.)

Parametry

td

The encryption descriptor.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption

mcrypt_encrypt
mcrypt_generic_end
Mcrypt Funkcje


This function terminates encryption

mcrypt_generic_deinit
mcrypt_generic_init
Mcrypt Funkcje
PHP Manual

mcrypt_generic_end

(PHP 4 >= 4.0.2, PHP 5 <= 5.1.6)

mcrypt_generic_end — This function terminates encryption

Opis

bool mcrypt_generic_end ( resource $td )

Ostrzeżenie

This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with mcrypt_module_close() due to multiple buffer frees.

This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on success.

mcrypt_generic_deinit
mcrypt_generic_init
Mcrypt Funkcje


This function initializes all buffers needed for encryption

mcrypt_generic_end
mcrypt_generic
Mcrypt Funkcje
PHP Manual

mcrypt_generic_init

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic_init — This function initializes all buffers needed for encryption

Opis

int mcrypt_generic_init ( resource $td , string $key , string $iv )

You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().

Parametry

td

The encryption descriptor.

key

The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal.

iv

The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended.

Zwracane wartości

The function returns a negative value on error: -3 when the key length was incorrect, -4 when there was a memory allocation problem and any other return value is an unknown error. If an error occurs a warning will be displayed accordingly. FALSE is returned if incorrect parameters were passed.

Zobacz też:

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

mcrypt_generic_end
mcrypt_generic
Mcrypt Funkcje


This function encrypts data

mcrypt_generic_init
mcrypt_get_block_size
Mcrypt Funkcje
PHP Manual

mcrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic — This function encrypts data

Opis

string mcrypt_generic ( resource $td , string $data )

This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer than the input, due to the padding of the data.

If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt_generic, or the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use mcrypt_enc_get_block_size() to determine the blocksize), you would need at least 16 characters in your database field. Note the string returned by mdecrypt_generic() will be 16 characters as well...use rtrim($str, "\0") to remove the padding.

If you are for example storing the data in a MySQL database remember that varchar fields automatically have trailing spaces removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store data in a tinyblob/tinytext (or larger) field instead.

Parametry

td

The encryption descriptor.

The encryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

data

The data to encrypt.

Zwracane wartości

Returns the encrypted data.

Zobacz też:

  • mdecrypt_generic() - Decrypts data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

mcrypt_generic_init
mcrypt_get_block_size
Mcrypt Funkcje


Gets the block size of the specified cipher

mcrypt_generic
mcrypt_get_cipher_name
Mcrypt Funkcje
PHP Manual

mcrypt_get_block_size

(PHP 4, PHP 5)

mcrypt_get_block_size — Gets the block size of the specified cipher

Opis

int mcrypt_get_block_size ( int $cipher )
int mcrypt_get_block_size ( string $cipher , string $module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().

Parametry

cipher

One of the MCRYPT_ciphername constants or the name of the algorithm as string.

module

The module.

Zwracane wartości

Gets the block size, as an integer.

Przykłady

Przykład #1 mcrypt_get_block_size() example

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

<?php

echo mcrypt_get_block_size('tripledes', 'ecb'); // 8

?>

Zobacz też:

  • mcrypt_get_key_size() - Gets the key size of the specified cipher
  • mcrypt_enc_get_block_size() - Returns the blocksize of the opened algorithm
  • mcrypt_encrypt() - Encrypts plaintext with given parameters

mcrypt_generic
mcrypt_get_cipher_name
Mcrypt Funkcje


Gets the name of the specified cipher

mcrypt_get_block_size
mcrypt_get_iv_size
Mcrypt Funkcje
PHP Manual

mcrypt_get_cipher_name

(PHP 4, PHP 5)

mcrypt_get_cipher_name — Gets the name of the specified cipher

Opis

string mcrypt_get_cipher_name ( int $cipher )
string mcrypt_get_cipher_name ( string $cipher )

mcrypt_get_cipher_name() is used to get the name of the specified cipher.

mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.

Parametry

cipher

One of the MCRYPT_ciphername constants or the name of the algorithm as string.

Zwracane wartości

This function returns the name of the cipher or FALSE, if the cipher does not exist.

Przykłady

Przykład #1 mcrypt_get_cipher_name() Example

<?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name($cipher);
?>

Powyższy przykład wyświetli:

3DES

mcrypt_get_block_size
mcrypt_get_iv_size
Mcrypt Funkcje


Returns the size of the IV belonging to a specific cipher/mode combination

mcrypt_get_cipher_name
mcrypt_get_key_size
Mcrypt Funkcje
PHP Manual

mcrypt_get_iv_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_get_iv_size — Returns the size of the IV belonging to a specific cipher/mode combination

Opis

int mcrypt_get_iv_size ( string $cipher , string $mode )

Gets the size of the IV belonging to a specific cipher/mode combination.

It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().

Parametry

cipher

One of the MCRYPT_ciphername constants, or the name of the algorithm as string.

mode

One of the MCRYPT_MODE_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.

Zwracane wartości

Returns the size of the Initialization Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

Przykłady

Przykład #1 mcrypt_get_iv_size() Example

<?php
    echo mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB) . "\n";

    echo mcrypt_get_iv_size('des', 'ecb') . "\n";
?>

Zobacz też:

  • mcrypt_get_block_size() - Gets the block size of the specified cipher
  • mcrypt_enc_get_iv_size() - Returns the size of the IV of the opened algorithm
  • mcrypt_create_iv() - Creates an initialization vector (IV) from a random source

mcrypt_get_cipher_name
mcrypt_get_key_size
Mcrypt Funkcje


Gets the key size of the specified cipher

mcrypt_get_iv_size
mcrypt_list_algorithms
Mcrypt Funkcje
PHP Manual

mcrypt_get_key_size

(PHP 4, PHP 5)

mcrypt_get_key_size — Gets the key size of the specified cipher

Opis

int mcrypt_get_key_size ( int $cipher )
int mcrypt_get_key_size ( string $cipher , string $module )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).

It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().

Przykłady

Przykład #1 mcrypt_get_key_size() Example

<?php
    echo mcrypt_get_key_size('tripledes', 'ecb');
?>

The example above shows how to use this function when linked against libmcrypt 2.4.x or 2.5.x.

Powyższy przykład wyświetli:

24

Zobacz też:

  • mcrypt_get_block_size() - Gets the block size of the specified cipher
  • mcrypt_enc_get_key_size() - Returns the maximum supported keysize of the opened mode
  • mcrypt_encrypt() - Encrypts plaintext with given parameters

mcrypt_get_iv_size
mcrypt_list_algorithms
Mcrypt Funkcje


Gets an array of all supported ciphers

mcrypt_get_key_size
mcrypt_list_modes
Mcrypt Funkcje
PHP Manual

mcrypt_list_algorithms

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_algorithms — Gets an array of all supported ciphers

Opis

array mcrypt_list_algorithms ([ string $lib_dir = ini_get("mcrypt.algorithms_dir") ] )

Gets the list of all supported algorithms in the lib_dir parameter.

Parametry

lib_dir

Specifies the directory where all algorithms are located. If not specified, the value of the mcrypt.algorithms_dir php.ini directive is used.

Zwracane wartości

Returns an array with all the supported algorithms.

Przykłady

Przykład #1 mcrypt_list_algorithms() Example

<?php
    $algorithms = mcrypt_list_algorithms("/usr/local/lib/libmcrypt");

    foreach ($algorithms as $cipher) {
        echo "$cipher<br />\n";
    }
?>

The example above will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.

mcrypt_get_key_size
mcrypt_list_modes
Mcrypt Funkcje


Gets an array of all supported modes

mcrypt_list_algorithms
mcrypt_module_close
Mcrypt Funkcje
PHP Manual

mcrypt_list_modes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_list_modes — Gets an array of all supported modes

Opis

array mcrypt_list_modes ([ string $lib_dir = ini_get("mcrypt.modes_dir") ] )

Gets the list of all supported modes in the lib_dir parameter.

Parametry

lib_dir

Specifies the directory where all modes are located. If not specified, the value of the mcrypt.modes_dir php.ini directive is used.

Zwracane wartości

Returns an array with all the supported modes.

Przykłady

Przykład #1 mcrypt_list_modes() Example

<?php
    $modes = mcrypt_list_modes();

    foreach ($modes as $mode) {
        echo "$mode <br />\n";
    }
?>

The example above will produce a list with all supported algorithms in the default mode directory. If it is not set with the mcrypt.modes_dir php.ini directive, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

mcrypt_list_algorithms
mcrypt_module_close
Mcrypt Funkcje


Closes the mcrypt module

mcrypt_list_modes
mcrypt_module_get_algo_block_size
Mcrypt Funkcje
PHP Manual

mcrypt_module_close

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_close — Closes the mcrypt module

Opis

bool mcrypt_module_close ( resource $td )

Closes the specified encryption handle.

Parametry

td

The encryption descriptor.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mcrypt_module_open() - Opens the module of the algorithm and the mode to be used

mcrypt_list_modes
mcrypt_module_get_algo_block_size
Mcrypt Funkcje


Returns the blocksize of the specified algorithm

mcrypt_module_close
mcrypt_module_get_algo_key_size
Mcrypt Funkcje
PHP Manual

mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_algo_block_size — Returns the blocksize of the specified algorithm

Opis

int mcrypt_module_get_algo_block_size ( string $algorithm [, string $lib_dir ] )

Gets the blocksize of the specified algorithm.

Parametry

algorithm

The algorithm name.

lib_dir

This optional parameter can contain the location where the mode module is on the system.

Zwracane wartości

Returns the block size of the algorithm specified in bytes.

mcrypt_module_close
mcrypt_module_get_algo_key_size
Mcrypt Funkcje


Returns the maximum supported keysize of the opened mode

mcrypt_module_get_algo_block_size
mcrypt_module_get_supported_key_sizes
Mcrypt Funkcje
PHP Manual

mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_algo_key_size — Returns the maximum supported keysize of the opened mode

Opis

int mcrypt_module_get_algo_key_size ( string $algorithm [, string $lib_dir ] )

Gets the maximum supported keysize of the opened mode.

Parametry

algorithm

The algorithm name.

lib_dir

This optional parameter can contain the location where the mode module is on the system.

Zwracane wartości

This function returns the maximum supported key size of the algorithm specified in bytes.

mcrypt_module_get_algo_block_size
mcrypt_module_get_supported_key_sizes
Mcrypt Funkcje


Returns an array with the supported keysizes of the opened algorithm

mcrypt_module_get_algo_key_size
mcrypt_module_is_block_algorithm_mode
Mcrypt Funkcje
PHP Manual

mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Opis

array mcrypt_module_get_supported_key_sizes ( string $algorithm [, string $lib_dir ] )

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm.

Parametry

algorithm

The algorithm to be used.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Zwracane wartości

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm.

Zobacz też:

  • mcrypt_enc_get_supported_key_sizes() - Returns an array with the supported keysizes of the opened algorithm

mcrypt_module_get_algo_key_size
mcrypt_module_is_block_algorithm_mode
Mcrypt Funkcje


Returns if the specified module is a block algorithm or not

mcrypt_module_get_supported_key_sizes
mcrypt_module_is_block_algorithm
Mcrypt Funkcje
PHP Manual

mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_algorithm_mode — Returns if the specified module is a block algorithm or not

Opis

bool mcrypt_module_is_block_algorithm_mode ( string $mode [, string $lib_dir ] )

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).

Parametry

mode

The mode to check.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Zwracane wartości

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).

mcrypt_module_get_supported_key_sizes
mcrypt_module_is_block_algorithm
Mcrypt Funkcje


This function checks whether the specified algorithm is a block algorithm

mcrypt_module_is_block_algorithm_mode
mcrypt_module_is_block_mode
Mcrypt Funkcje
PHP Manual

mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm

Opis

bool mcrypt_module_is_block_algorithm ( string $algorithm [, string $lib_dir ] )

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE if it is a stream one.

Parametry

algorithm

The algorithm to check.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Zwracane wartości

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE if it is a stream one.

mcrypt_module_is_block_algorithm_mode
mcrypt_module_is_block_mode
Mcrypt Funkcje


Returns if the specified mode outputs blocks or not

mcrypt_module_is_block_algorithm
mcrypt_module_open
Mcrypt Funkcje
PHP Manual

mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_is_block_mode — Returns if the specified mode outputs blocks or not

Opis

bool mcrypt_module_is_block_mode ( string $mode [, string $lib_dir ] )

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

Parametry

mode

The mode to check.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Zwracane wartości

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).

mcrypt_module_is_block_algorithm
mcrypt_module_open
Mcrypt Funkcje


Opens the module of the algorithm and the mode to be used

mcrypt_module_is_block_mode
mcrypt_module_self_test
Mcrypt Funkcje
PHP Manual

mcrypt_module_open

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_open — Opens the module of the algorithm and the mode to be used

Opis

resource mcrypt_module_open ( string $algorithm , string $algorithm_directory , string $mode , string $mode_directory )

This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, e.g. "twofish" or is one of the MCRYPT_ciphername constants. The module is closed by calling mcrypt_module_close().

Parametry

algorithm

The algorithm to be used.

algorithm_directory

The algorithm_directory parameter is used to locate the encryption module. When you supply a directory name, it is used. When you set it to an empty string (""), the value set by the mcrypt.algorithms_dir php.ini directive is used. When it is not set, the default directory that is used is the one that was compiled into libmcrypt (usually /usr/local/lib/libmcrypt).

mode

The mode to be used.

mode_directory

The mode_directory parameter is used to locate the encryption module. When you supply a directory name, it is used. When you set it to an empty string (""), the value set by the mcrypt.modes_dir php.ini directive is used. When it is not set, the default directory that is used is the one that was compiled-in into libmcrypt (usually /usr/local/lib/libmcrypt).

Zwracane wartości

Normally it returns an encryption descriptor, or FALSE on error.

Przykłady

Przykład #1 mcrypt_module_open() Examples

<?php
    $td = mcrypt_module_open(MCRYPT_DES, '',
        MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');

    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

Przykład #2 Using mcrypt_module_open() in encryption

<?php
    /* Open the cipher */
    $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');

    /* Create the IV and determine the keysize length, use MCRYPT_RAND
     * on Windows instead */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
    $ks = mcrypt_enc_get_key_size($td);

    /* Create key */
    $key = substr(md5('very secret key'), 0, $ks);

    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic($td, 'This is very important data');

    /* Terminate encryption handler */
    mcrypt_generic_deinit($td);

    /* Initialize encryption module for decryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($td, $encrypted);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    /* Show string */
    echo trim($decrypted) . "\n";
?>

Zobacz też:

  • mcrypt_module_close() - Closes the mcrypt module
  • mcrypt_generic() - This function encrypts data
  • mdecrypt_generic() - Decrypts data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

mcrypt_module_is_block_mode
mcrypt_module_self_test
Mcrypt Funkcje


This function runs a self test on the specified module

mcrypt_module_open
mcrypt_ofb
Mcrypt Funkcje
PHP Manual

mcrypt_module_self_test

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_module_self_test — This function runs a self test on the specified module

Opis

bool mcrypt_module_self_test ( string $algorithm [, string $lib_dir ] )

This function runs the self test on the algorithm specified.

Parametry

algorithm

The algorithm to test.

lib_dir

The optional lib_dir parameter can contain the location where the algorithm module is on the system.

Zwracane wartości

The function returns TRUE if the self test succeeds, or FALSE when it fails.

Przykłady

Przykład #1 mcrypt_module_self_test() example

<?php
var_dump(mcrypt_module_self_test(MCRYPT_RIJNDAEL_128)) . "\n";
var_dump(mcrypt_module_self_test(MCRYPT_BOGUS_CYPHER));
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)

mcrypt_module_open
mcrypt_ofb
Mcrypt Funkcje


Encrypts/decrypts data in OFB mode

mcrypt_module_self_test
mdecrypt_generic
Mcrypt Funkcje
PHP Manual

mcrypt_ofb

(PHP 4, PHP 5)

mcrypt_ofb — Encrypts/decrypts data in OFB mode

Opis

string mcrypt_ofb ( int $cipher , string $key , string $data , int $mode , string $iv )
string mcrypt_ofb ( string $cipher , string $key , string $data , int $mode [, string $iv ] )

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_module_self_test
mdecrypt_generic
Mcrypt Funkcje


Decrypts data

mcrypt_ofb
Mhash
Mcrypt Funkcje
PHP Manual

mdecrypt_generic

(PHP 4 >= 4.0.2, PHP 5)

mdecrypt_generic — Decrypts data

Opis

string mdecrypt_generic ( resource $td , string $data )

This function decrypts data. Note that the length of the returned string can in fact be longer than the unencrypted string, due to the padding of the data.

Parametry

td

An encryption descriptor returned by mcrypt_module_open()

data

Encrypted data.

Przykłady

Przykład #1 mdecrypt_generic() Example

<?php
    /* Data */
    $key = 'this is a very long key, even too long for the cipher';
    $plain_text = 'very important data';

    /* Open module, and create IV */
    $td = mcrypt_module_open('des', '', 'ecb', '');
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    /* Initialize encryption handle */
    if (mcrypt_generic_init($td, $key, $iv) != -1) {

        /* Encrypt data */
        $c_t = mcrypt_generic($td, $plain_text);
        mcrypt_generic_deinit($td);

        /* Reinitialize buffers for decryption */
        mcrypt_generic_init($td, $key, $iv);
        $p_t = mdecrypt_generic($td, $c_t);

        /* Clean up */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
    }

    if (strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
        echo "ok\n";
    } else {
        echo "error\n";
    }
?>

The example above shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.

The decryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

Zobacz też:

  • mcrypt_generic() - This function encrypts data
  • mcrypt_generic_init() - This function initializes all buffers needed for encryption
  • mcrypt_generic_deinit() - This function deinitializes an encryption module

mcrypt_ofb
Mhash
Mcrypt Funkcje


Mhash

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Mhash Funkcje
    • mhash_count — Gets the highest available hash ID
    • mhash_get_block_size — Gets the block size of the specified hash
    • mhash_get_hash_name — Gets the name of the specified hash
    • mhash_keygen_s2k — Generates a key
    • mhash — Computes hash
mdecrypt_generic
Wstęp
Rozszerzenia kryptograficzne


Wstęp

These functions are intended to work with » mhash. Mhash can be used to create checksums, message digests, message authentication codes, and more.

This is an interface to the mhash library. Mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others. For a complete list of supported hashes, refer to the constants page. The general rule is that you can access the hash algorithm from PHP with MHASH_hashname. For example, to access TIGER you use the PHP constant MHASH_TIGER.

Informacja:

This extension is obsoleted by Hash.

Mhash
Instalacja/Konfiguracja
Mhash


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Mhash


Wymagania

To use it, download the mhash distribution from » its web site and follow the included installation instructions.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash installation directory.

As of PHP 5.3.0, the mhash extension is emulated thru the Hash extension. This makes the mhash installation directory have no effect, and requires the hash extension enabled to make the mhash support available.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but it is listed in the mhash documentation as supported, you can safely assume that this documentation is outdated.

  • MHASH_ADLER32
  • MHASH_CRC32
  • MHASH_CRC32B
  • MHASH_GOST
  • MHASH_HAVAL128
  • MHASH_HAVAL160
  • MHASH_HAVAL192
  • MHASH_HAVAL224
  • MHASH_HAVAL256
  • MHASH_MD2
  • MHASH_MD4
  • MHASH_MD5
  • MHASH_RIPEMD128
  • MHASH_RIPEMD256
  • MHASH_RIPEMD320
  • MHASH_SHA1
  • MHASH_SHA192
  • MHASH_SHA224
  • MHASH_SHA256
  • MHASH_SHA384
  • MHASH_SHA512
  • MHASH_SNEFRU128
  • MHASH_SNEFRU256
  • MHASH_TIGER
  • MHASH_TIGER128
  • MHASH_TIGER160
  • MHASH_WHIRLPOOL

Typy zasobów
Przykłady
Mhash


Przykłady

Przykład #1 Computes the MD5 digest and hmac and print it out as hex

<?php
$input = "what do ya want for nothing?";
$hash = mhash(MHASH_MD5, $input);
echo "The hash is " . bin2hex($hash) . "<br />\n";
$hash = mhash(MHASH_MD5, $input, "Jefe");
echo "The hmac is " . bin2hex($hash) . "<br />\n";
?>

Powyższy przykład wyświetli:

The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738

Stałe predefiniowane
Mhash Funkcje
Mhash


Mhash Funkcje

Spis treści

  • mhash_count — Gets the highest available hash ID
  • mhash_get_block_size — Gets the block size of the specified hash
  • mhash_get_hash_name — Gets the name of the specified hash
  • mhash_keygen_s2k — Generates a key
  • mhash — Computes hash
Przykłady
mhash_count
Mhash


Gets the highest available hash ID

Mhash Funkcje
mhash_get_block_size
Mhash Funkcje
PHP Manual

mhash_count

(PHP 4, PHP 5)

mhash_count — Gets the highest available hash ID

Opis

int mhash_count ( void )

Gets the highest available hash ID.

Zwracane wartości

Returns the highest available hash ID. Hashes are numbered from 0 to this hash ID.

Przykłady

Przykład #1 Traversing all hashes

<?php

$nr = mhash_count();

for ($i = 0; $i <= $nr; $i++) {
    echo sprintf("The blocksize of %s is %d\n",
        mhash_get_hash_name($i),
        mhash_get_block_size($i));
}
?>

Mhash Funkcje
mhash_get_block_size
Mhash Funkcje


Gets the block size of the specified hash

mhash_count
mhash_get_hash_name
Mhash Funkcje
PHP Manual

mhash_get_block_size

(PHP 4, PHP 5)

mhash_get_block_size — Gets the block size of the specified hash

Opis

int mhash_get_block_size ( int $hash )

Gets the size of a block of the specified hash.

Parametry

hash

The hash ID. One of the MHASH_hashname constants.

Zwracane wartości

Returns the size in bytes or FALSE, if the hash does not exist.

Przykłady

Przykład #1 mhash_get_block_size() Example

<?php

echo mhash_get_block_size(MHASH_MD5); // 16

?>

mhash_count
mhash_get_hash_name
Mhash Funkcje


Gets the name of the specified hash

mhash_get_block_size
mhash_keygen_s2k
Mhash Funkcje
PHP Manual

mhash_get_hash_name

(PHP 4, PHP 5)

mhash_get_hash_name — Gets the name of the specified hash

Opis

string mhash_get_hash_name ( int $hash )

Gets the name of the specified hash.

Parametry

hash

The hash ID. One of the MHASH_hashname constants.

Zwracane wartości

Returns the name of the hash or FALSE, if the hash does not exist.

Przykłady

Przykład #1 mhash_get_hash_name() Example

<?php

echo mhash_get_hash_name(MHASH_MD5); // MD5

?>

mhash_get_block_size
mhash_keygen_s2k
Mhash Funkcje


Generates a key

mhash_get_hash_name
mhash
Mhash Funkcje
PHP Manual

mhash_keygen_s2k

(PHP 4 >= 4.0.4, PHP 5)

mhash_keygen_s2k — Generates a key

Opis

string mhash_keygen_s2k ( int $hash , string $password , string $salt , int $bytes )

Generates a key according to the given hash, using an user provided password.

This is the Salted S2K algorithm as specified in the OpenPGP document (» RFC 2440).

Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of transformation (like this function) to the user supplied key.

Parametry

hash

The hash ID used to create the key. One of the MHASH_hashname constants.

password

An user supplied password.

salt

Must be different and random enough for every key you generate in order to create different keys. Because salt must be known when you check the keys, it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.

bytes

The key length, in bytes.

Zwracane wartości

Returns the generated key as a string, or FALSE on error.

mhash_get_hash_name
mhash
Mhash Funkcje


Computes hash

mhash_keygen_s2k
OpenSSL
Mhash Funkcje
PHP Manual

mhash

(PHP 4, PHP 5)

mhash — Computes hash

Opis

string mhash ( int $hash , string $data [, string $key ] )

mhash() applies a hash function specified by hash to the data.

Parametry

hash

The hash ID. One of the MHASH_hashname constants.

data

The user input, as a string.

key

If specified, the function will return the resulting HMAC instead. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode.

Zwracane wartości

Returns the resulting hash (also called digest) or HMAC as a string, or FALSE on error.

mhash_keygen_s2k
OpenSSL
Mhash Funkcje


OpenSSL

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
    • Purpose checking flags
    • Padding flags for asymmetric encryption
    • Key types
    • PKCS7 Flags/Constants
    • Signature Algorithms
    • Ciphers
    • Version constants
    • Server Name Indication constants
  • Key/Certificate parameters
  • Certificate Verification
  • OpenSSL Funkcje
    • openssl_cipher_iv_length — Gets the cipher iv length
    • openssl_csr_export_to_file — Exports a CSR to a file
    • openssl_csr_export — Exports a CSR as a string
    • openssl_csr_get_public_key — Returns the public key of a CERT
    • openssl_csr_get_subject — Returns the subject of a CERT
    • openssl_csr_new — Generates a CSR
    • openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate
    • openssl_decrypt — Decrypts data
    • openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key
    • openssl_digest — Computes a digest
    • openssl_encrypt — Encrypts data
    • openssl_error_string — Return openSSL error message
    • openssl_free_key — Free key resource
    • openssl_get_cipher_methods — Gets available cipher methods
    • openssl_get_md_methods — Gets available digest methods
    • openssl_get_privatekey — Alias dla openssl_pkey_get_private
    • openssl_get_publickey — Alias dla openssl_pkey_get_public
    • openssl_open — Open sealed data
    • openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
    • openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.
    • openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
    • openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message
    • openssl_pkcs7_encrypt — Encrypt an S/MIME message
    • openssl_pkcs7_sign — Sign an S/MIME message
    • openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message
    • openssl_pkey_export_to_file — Gets an exportable representation of a key into a file
    • openssl_pkey_export — Gets an exportable representation of a key into a string
    • openssl_pkey_free — Frees a private key
    • openssl_pkey_get_details — Returns an array with the key details
    • openssl_pkey_get_private — Get a private key
    • openssl_pkey_get_public — Extract public key from certificate and prepare it for use
    • openssl_pkey_new — Generates a new private key
    • openssl_private_decrypt — Decrypts data with private key
    • openssl_private_encrypt — Encrypts data with private key
    • openssl_public_decrypt — Decrypts data with public key
    • openssl_public_encrypt — Encrypts data with public key
    • openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes
    • openssl_seal — Seal (encrypt) data
    • openssl_sign — Generate signature
    • openssl_verify — Verify signature
    • openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
    • openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
    • openssl_x509_export_to_file — Exports a certificate to file
    • openssl_x509_export — Exports a certificate as a string
    • openssl_x509_free — Free certificate resource
    • openssl_x509_parse — Parse an X509 certificate and return the information as an array
    • openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it
mhash
Wstęp
Rozszerzenia kryptograficzne


Wstęp

This module uses the functions of » OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.

OpenSSL
Instalacja/Konfiguracja
OpenSSL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
OpenSSL


Wymagania

In order to use the OpenSSL functions you need to install the » OpenSSL package. PHP between versions 4.0.5 and 4.3.1 will work with OpenSSL >= 0.9.5. Other versions (PHP <=4.0.4 and >= 4.3.2) require OpenSSL >= 0.9.6.

Ostrzeżenie

You are strongly encouraged to use the most recent OpenSSL version, otherwise your web server could be vulnerable to attack.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR] .

The OpenSSL library also has additional requirements for normal operation at run-time. Most notably, OpenSSL requires access to a random or pseudo-random number generator; on most Unix and Unix-like platforms (including Linux), this means that it must have access to a /dev/urandom or /dev/random device.

Informacja: Note to Win32 Users

Aby poprawnie działało rozszerzenie, pliki DLL muszą znajdować się w miejscu wskazanym przez PATH systemu Windows. Aby uzyskać więcej informacji zobacz FAQ zatytułowane "Jak mam dodać mój katalog PHP do PATH w Windows". Chociaż skopiowanie plików DLL z folderu PHP do systemowego katalogu Windows także zadziała (ponieważ katalog systemowy jest domyślnie w PATH systemu), ale nie jest to wymagane. To rozszerzenie wymaga następujących plików znajdujących się w PATH: libeay32.dll

Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf file on your system. As of PHP 4.3.0, we include a sample configuration file in our win32 binary distributions. PHP 4.3.x and 4.4.x has the file in the openssl directory. PHP 5.x and 6.x has the file in the extras/openssl directory. If you are either using PHP 4.2.x or missing the file, you can obtain it from » the OpenSSL binaries page or by downloading a recent PHP release. Be aware that Windows Explorer hides the .cnf extension by default and says the file Type is SpeedDial.

PHP will search for the openssl.cnf using the following logic:

  • the OPENSSL_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
  • the SSLEAY_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
  • The file openssl.cnf will be assumed to be found in the default certificate area, as configured at the time that the openssl DLL was compiled. This is usually means that the default filename is c:\usr\local\ssl\openssl.cnf.

In your installation, you need to decide whether to install the configuration file at c:\usr\local\ssl\openssl.cnf or whether to install it someplace else and use environmental variables (possibly on a per-virtual-host basis) to locate the configuration file. Note that it is possible to override the default path from the script using the configargs of the functions that require a configuration file.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

Spis treści

  • Purpose checking flags
  • Padding flags for asymmetric encryption
  • Key types
  • PKCS7 Flags/Constants
  • Signature Algorithms
  • Ciphers
  • Version constants
  • Server Name Indication constants

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.

Typy zasobów
Purpose checking flags
OpenSSL


Purpose checking flags

X509_PURPOSE_SSL_CLIENT (integer)
X509_PURPOSE_SSL_SERVER (integer)
X509_PURPOSE_NS_SSL_SERVER (integer)
X509_PURPOSE_SMIME_SIGN (integer)
X509_PURPOSE_SMIME_ENCRYPT (integer)
X509_PURPOSE_CRL_SIGN (integer)
X509_PURPOSE_ANY (integer)
Stałe predefiniowane
Padding flags for asymmetric encryption
Stałe predefiniowane


Padding flags for asymmetric encryption

OPENSSL_PKCS1_PADDING (integer)
OPENSSL_SSLV23_PADDING (integer)
OPENSSL_NO_PADDING (integer)
OPENSSL_PKCS1_OAEP_PADDING (integer)
Purpose checking flags
Key types
Stałe predefiniowane


Key types

OPENSSL_KEYTYPE_RSA (integer)
OPENSSL_KEYTYPE_DSA (integer)
OPENSSL_KEYTYPE_DH (integer)
Padding flags for asymmetric encryption
PKCS7 Flags/Constants
Stałe predefiniowane


PKCS7 Flags/Constants

The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:

PKCS7 CONSTANTS
Constant | Description
PKCS7_TEXT | Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur.
PKCS7_BINARY | Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this option is present, no translation occurs. This is useful when handling binary data which may not be in MIME format.
PKCS7_NOINTERN | When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however.
PKCS7_NOVERIFY | Do not verify the signers certificate of a signed message.
PKCS7_NOCHAIN | Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTS | When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example).
PKCS7_NOATTR | Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included.
PKCS7_DETACHED | When signing a message, use cleartext signing with the MIME type "multipart/signed". This is the default if you do not specify any flags to openssl_pkcs7_sign(). If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME.
PKCS7_NOSIGS | Don't try and verify the signatures on a message

Informacja:

These constants were added in 4.0.6.

Key types
Signature Algorithms
Stałe predefiniowane


Signature Algorithms

OPENSSL_ALGO_DSS1 (integer)
OPENSSL_ALGO_SHA1 (integer)
Used as default algorithm by openssl_sign() and openssl_verify().
OPENSSL_ALGO_MD5 (integer)
OPENSSL_ALGO_MD4 (integer)
OPENSSL_ALGO_MD2 (integer)

Informacja:

These constants were added in 5.0.0.

PKCS7 Flags/Constants
Ciphers
Stałe predefiniowane


Ciphers

OPENSSL_CIPHER_RC2_40 (integer)
OPENSSL_CIPHER_RC2_128 (integer)
OPENSSL_CIPHER_RC2_64 (integer)
OPENSSL_CIPHER_DES (integer)
OPENSSL_CIPHER_3DES (integer)

Informacja:

These constants were added in 4.3.0.

OPENSSL_CIPHER_AES_128_CBC (integer)
OPENSSL_CIPHER_AES_192_CBC (integer)
OPENSSL_CIPHER_AES_256_CBC (integer)

Informacja:

These constants were added in 5.4.0.

Signature Algorithms
Version constants
Stałe predefiniowane


Version constants

OPENSSL_VERSION_TEXT (string)
OPENSSL_VERSION_NUMBER (integer)

Informacja:

These constants were added in 5.2.0.

Ciphers
Server Name Indication constants
Stałe predefiniowane


Server Name Indication constants

OPENSSL_TLSEXT_SERVER_NAME (string)
Whether SNI support is available or not.

Informacja:

This constant were added in 5.3.2 and requires PHP to be built with OpenSSL 0.9.8j or greater.

Version constants
Key/Certificate parameters
Stałe predefiniowane


Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx() functions. Later versions may use one of the following methods:

  • Certificates

    1. An X.509 resource returned from openssl_x509_read()
    2. A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate
    3. A string containing the content of a certificate, PEM encoded

  • Public/Private Keys

    1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
    2. For public keys only: an X.509 resource
    3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)
    4. A string containing the content of a certificate/key, PEM encoded
    5. For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key

Server Name Indication constants
Certificate Verification
OpenSSL


Certificate Verification

When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.

Key/Certificate parameters
OpenSSL Funkcje
OpenSSL


OpenSSL Funkcje

Spis treści

  • openssl_cipher_iv_length — Gets the cipher iv length
  • openssl_csr_export_to_file — Exports a CSR to a file
  • openssl_csr_export — Exports a CSR as a string
  • openssl_csr_get_public_key — Returns the public key of a CERT
  • openssl_csr_get_subject — Returns the subject of a CERT
  • openssl_csr_new — Generates a CSR
  • openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate
  • openssl_decrypt — Decrypts data
  • openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key
  • openssl_digest — Computes a digest
  • openssl_encrypt — Encrypts data
  • openssl_error_string — Return openSSL error message
  • openssl_free_key — Free key resource
  • openssl_get_cipher_methods — Gets available cipher methods
  • openssl_get_md_methods — Gets available digest methods
  • openssl_get_privatekey — Alias dla openssl_pkey_get_private
  • openssl_get_publickey — Alias dla openssl_pkey_get_public
  • openssl_open — Open sealed data
  • openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
  • openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.
  • openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array
  • openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message
  • openssl_pkcs7_encrypt — Encrypt an S/MIME message
  • openssl_pkcs7_sign — Sign an S/MIME message
  • openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message
  • openssl_pkey_export_to_file — Gets an exportable representation of a key into a file
  • openssl_pkey_export — Gets an exportable representation of a key into a string
  • openssl_pkey_free — Frees a private key
  • openssl_pkey_get_details — Returns an array with the key details
  • openssl_pkey_get_private — Get a private key
  • openssl_pkey_get_public — Extract public key from certificate and prepare it for use
  • openssl_pkey_new — Generates a new private key
  • openssl_private_decrypt — Decrypts data with private key
  • openssl_private_encrypt — Encrypts data with private key
  • openssl_public_decrypt — Decrypts data with public key
  • openssl_public_encrypt — Encrypts data with public key
  • openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes
  • openssl_seal — Seal (encrypt) data
  • openssl_sign — Generate signature
  • openssl_verify — Verify signature
  • openssl_x509_check_private_key — Checks if a private key corresponds to a certificate
  • openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose
  • openssl_x509_export_to_file — Exports a certificate to file
  • openssl_x509_export — Exports a certificate as a string
  • openssl_x509_free — Free certificate resource
  • openssl_x509_parse — Parse an X509 certificate and return the information as an array
  • openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it
Certificate Verification
openssl_cipher_iv_length
OpenSSL


Gets the cipher iv length

OpenSSL Funkcje
openssl_csr_export_to_file
OpenSSL Funkcje
PHP Manual

openssl_cipher_iv_length

(PHP 5 >= PHP 5.3.3)

openssl_cipher_iv_length — Gets the cipher iv length

Opis

int openssl_cipher_iv_length ( string $method )

Gets the cipher iv length.

Parametry

method

The method.

Zwracane wartości

Returns the cipher length on success, or FALSE on failure.

Błędy/Wyjątki

Emits an E_WARNING level error when the cipher algorithm is unknown.

Przykłady

Przykład #1 openssl_cipher_iv_length() example

<?php
$method = 'AES-128-CBC';
$ivlen = openssl_cipher_iv_length($method);

echo $ivlen;
?>

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

16
OpenSSL Funkcje
openssl_csr_export_to_file
OpenSSL Funkcje


Exports a CSR to a file

openssl_cipher_iv_length
openssl_csr_export
OpenSSL Funkcje
PHP Manual

openssl_csr_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_export_to_file — Exports a CSR to a file

Opis

bool openssl_csr_export_to_file ( resource $csr , string $outfilename [, bool $notext = true ] )

openssl_csr_export_to_file() takes the Certificate Signing Request represented by csr and saves it as ascii-armoured text into the file named by outfilename.

Parametry

csr

outfilename

Path to the output file.

notext

Opcjonalny parametr notext wpływa na szczegółowość komunikatów wyjścia. Jeśli wynosi FALSE, wówczas do wyjścia dołączane są dodatkowe informacje zrozumiałe dla ludzi. Wartość domyślna parametru notext wynosi: TRUE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • openssl_csr_export() - Exports a CSR as a string
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

openssl_cipher_iv_length
openssl_csr_export
OpenSSL Funkcje


Exports a CSR as a string

openssl_csr_export_to_file
openssl_csr_get_public_key
OpenSSL Funkcje
PHP Manual

openssl_csr_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_export — Exports a CSR as a string

Opis

bool openssl_csr_export ( resource $csr , string &$out [, bool $notext = true ] )

openssl_csr_export() takes the Certificate Signing Request represented by csr and stores it as ascii-armoured text into out, which is passed by reference.

Parametry

csr

out

notext

Opcjonalny parametr notext wpływa na szczegółowość komunikatów wyjścia. Jeśli wynosi FALSE, wówczas do wyjścia dołączane są dodatkowe informacje zrozumiałe dla ludzi. Wartość domyślna parametru notext wynosi: TRUE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • openssl_csr_export_to_file() - Exports a CSR to a file
  • openssl_csr_new() - Generates a CSR
  • openssl_csr_sign() - Sign a CSR with another certificate (or itself) and generate a certificate

openssl_csr_export_to_file
openssl_csr_get_public_key
OpenSSL Funkcje


Returns the public key of a CERT

openssl_csr_export
openssl_csr_get_subject
OpenSSL Funkcje
PHP Manual

openssl_csr_get_public_key

(PHP 5 >= 5.2.0)

openssl_csr_get_public_key — Returns the public key of a CERT

Opis

resource openssl_csr_get_public_key ( mixed $csr [, bool $use_shortnames = true ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

openssl_csr_export
openssl_csr_get_subject
OpenSSL Funkcje


Returns the subject of a CERT

openssl_csr_get_public_key
openssl_csr_new
OpenSSL Funkcje
PHP Manual

openssl_csr_get_subject

(PHP 5 >= 5.2.0)

openssl_csr_get_subject — Returns the subject of a CERT

Opis

array openssl_csr_get_subject ( mixed $csr [, bool $use_shortnames = true ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

openssl_csr_get_public_key
openssl_csr_new
OpenSSL Funkcje


Generates a CSR

openssl_csr_get_subject
openssl_csr_sign
OpenSSL Funkcje
PHP Manual

openssl_csr_new

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_new — Generates a CSR

Opis

mixed openssl_csr_new ( array $dn , resource &$privkey [, array $configargs [, array $extraattribs ]] )

openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn, which represents the Distinguished Name to be used in the certificate.

Informacja: Aby ta funkcja prawidłowo działała wymaga poprawnie zainstalowanego openssl.cnf. Aby uzyskać więcej informacji przeczytaj rozdział instalacja openssl.

Parametry

dn

The Distinguished Name to be used in the certificate.

privkey

privkey should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.

configargs

By default, the information in your system openssl.conf is used to initialize the request; you can specify a configuration file section by setting the config_section_section key of configargs. You can also specify an alternative openssl configuration file by setting the value of the config key to the path of the file you want to use. The following keys, if present in configargs behave as their equivalents in the openssl.conf, as listed in the table below.

Configuration overrides
configargs key | type | openssl.conf equivalent | description
digest_alg | string | default_md | Selects which digest method to use
x509_extensions | string | x509_extensions | Selects which extensions should be used when creating an x509 certificate
req_extensions | string | req_extensions | Selects which extensions should be used when creating a CSR
private_key_bits | integer | default_bits | Specifies how many bits should be used to generate a private key
private_key_type | integer | none | Specifies the type of private key to create. This can be one of OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH or OPENSSL_KEYTYPE_RSA. The default value is OPENSSL_KEYTYPE_RSA which is currently the only supported key type.
encrypt_key | boolean | encrypt_key | Should an exported key (with passphrase) be encrypted?
encrypt_key_cipher | integer | none | One of cipher constants.

extraattribs

extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.

Zwracane wartości

Returns the CSR.

Przykłady

Przykład #1 Creating a self-signed-certificate

<?php
// Fill in data for the distinguished name to be used in the cert
// You must change the values of these keys to match your name and
// company, or more precisely, the name and company of the person/site
// that you are generating the certificate for.
// For SSL certificates, the commonName is usually the domain name of
// that will be using the certificate, but for S/MIME certificates,
// the commonName will be the name of the individual who will use the
// certificate.
$dn = array(
    "countryName" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@example.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey);

// You will usually want to create a self-signed certificate at this
// point until your CA fulfills your request.
// This creates a self-signed cert that is valid for 365 days
$sscert = openssl_csr_sign($csr, null, $privkey, 365);

// Now you will want to preserve your private key, CSR and self-signed
// cert so that they can be installed into your web server, mail server
// or mail client (depending on the intended use of the certificate).
// This example shows how to get those things into variables, but you
// can also store them directly into files.
// Typically, you will send the CSR on to your CA who will then issue
// you with the "real" certificate.
openssl_csr_export($csr, $csrout) and var_dump($csrout);
openssl_x509_export($sscert, $certout) and var_dump($certout);
openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout);

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?>

openssl_csr_get_subject
openssl_csr_sign
OpenSSL Funkcje


Sign a CSR with another certificate (or itself) and generate a certificate

openssl_csr_new
openssl_decrypt
OpenSSL Funkcje
PHP Manual

openssl_csr_sign

(PHP 4 >= 4.2.0, PHP 5)

openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate

Opis

resource openssl_csr_sign ( mixed $csr , mixed $cacert , mixed $priv_key , int $days [, array $configargs [, int $serial = 0 ]] )

openssl_csr_sign() generates an x509 certificate resource from the given CSR.

Informacja: Aby ta funkcja prawidłowo działała wymaga poprawnie zainstalowanego openssl.cnf. Aby uzyskać więcej informacji przeczytaj rozdział instalacja openssl.

Parametry

csr

A CSR previously generated by openssl_csr_new(). It can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by openssl_csr_export().

cacert

The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate.

priv_key

priv_key is the private key that corresponds to cacert.

days

days specifies the length of time for which the generated certificate will be valid, in days.

configargs

You can finetune the CSR signing by configargs. See openssl_csr_new() for more information about configargs.

serial

An optional the serial number of issued certificate. If not specified it will default to 0.

Zwracane wartości

Returns an x509 certificate resource on success, FALSE on failure.

Rejestr zmian

Wersja | Opis
4.3.3 | The serial parameter was added.

Przykłady

Przykład #1 openssl_csr_sign() example - signing a CSR (how to implement your own CA)

<?php
// Let's assume that this script is set to receive a CSR that has
// been pasted into a textarea from another page
$csrdata = $_POST["CSR"];

// We will sign the request using our own "certificate authority"
// certificate.  You can use any certificate to sign another, but
// the process is worthless unless the signing certificate is trusted
// by the software/users that will deal with the newly signed certificate

// We need our CA cert and its private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");

$usercert = openssl_csr_sign($csrdata, $cacert, $privkey, 365);

// Now display the generated certificate so that the user can
// copy and paste it into their local configuration (such as a file
// to hold the certificate for their SSL server)
openssl_x509_export($usercert, $certout);
echo $certout;

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}
?>

openssl_csr_new
openssl_decrypt
OpenSSL Funkcje


Decrypts data

openssl_csr_sign
openssl_dh_compute_key
OpenSSL Funkcje
PHP Manual

openssl_decrypt

(PHP 5 >= 5.3.0)

openssl_decrypt — Decrypts data

Opis

string openssl_decrypt ( string $data , string $method , string $password [, bool $raw_input = false [, string $iv = "" ]] )

Takes a raw or base64 encoded string and decrypts it using a given method and key.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

data

The data.

method

The cipher method.

password

The password.

raw_input

Setting to TRUE will take a raw encoded string, otherwise a base64 string is assumed for the data parameter.

iv

A non-NULL Initialization Vector.

Zwracane wartości

The decrypted string on success lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Emits an E_WARNING level error if an unknown cipher algorithm is passed via the method parameter.

Emits an E_WARNING level error if an empty value is passed in via the iv parameter.

Rejestr zmian

Wersja | Opis
5.3.3 | The iv parameter was added.

Zobacz też:

  • openssl_encrypt() - Encrypts data

openssl_csr_sign
openssl_dh_compute_key
OpenSSL Funkcje


Computes shared secret for public value of remote DH key and local DH key

openssl_decrypt
openssl_digest
OpenSSL Funkcje
PHP Manual

openssl_dh_compute_key

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

openssl_dh_compute_key — Computes shared secret for public value of remote DH key and local DH key

Opis

string openssl_dh_compute_key ( string $pub_key , resource $dh_key )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pub_key

Public key

dh_key

DH key

Zwracane wartości

Returns computed key on success lub FALSE w przypadku niepowodzenia.

openssl_decrypt
openssl_digest
OpenSSL Funkcje


Computes a digest

openssl_dh_compute_key
openssl_encrypt
OpenSSL Funkcje
PHP Manual

openssl_digest

(PHP 5 >= 5.3.0)

openssl_digest — Computes a digest

Opis

string openssl_digest ( string $data , string $method [, bool $raw_output = false ] )

Computes a digest hash value for the given data using a given method, and returns a raw or binhex encoded string.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

data

The data.

method

The digest method.

raw_output

Setting to TRUE will return as raw output data, otherwise the return value is binhex encoded.

Zwracane wartości

Returns the digested hash value on success lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Emits an E_WARNING level error if an unknown signature algorithm is passed via the method parameter.

Zobacz też:

  • openssl_get_cipher_methods() - Gets available cipher methods

openssl_dh_compute_key
openssl_encrypt
OpenSSL Funkcje


Encrypts data

openssl_digest
openssl_error_string
OpenSSL Funkcje
PHP Manual

openssl_encrypt

(PHP 5 >= 5.3.0)

openssl_encrypt — Encrypts data

Opis

string openssl_encrypt ( string $data , string $method , string $password [, bool $raw_output = false [, string $iv = "" ]] )

Encrypts given data with given method and key, returns a raw or base64 encoded string

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

data

The data.

method

The cipher method.

password

The password.

raw_output

Setting to TRUE will return as raw output data, otherwise the return value is base64 encoded.

iv

A non-NULL Initialization Vector.

Zwracane wartości

Returns the encrypted string on success lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Emits an E_WARNING level error if an unknown cipher algorithm is passed in via the method parameter.

Emits an E_WARNING level error if an empty value is passed in via the iv parameter.

Rejestr zmian

Wersja | Opis
5.3.3 | The iv parameter was added.

Zobacz też:

  • openssl_decrypt() - Decrypts data

openssl_digest
openssl_error_string
OpenSSL Funkcje


Return openSSL error message

openssl_encrypt
openssl_free_key
OpenSSL Funkcje
PHP Manual

openssl_error_string

(PHP 4 >= 4.0.6, PHP 5)

openssl_error_string — Return openSSL error message

Opis

string openssl_error_string ( void )

openssl_error_string() returns the last error from the openSSL library. Error messages are queued, so this function should be called multiple times to collect all of the information. The last error will be the most recent one.

Zwracane wartości

Returns an error message string, or FALSE if there are no more error messages to return.

Przykłady

Przykład #1 openssl_error_string() example

<?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
    echo $msg . "<br />\n";
?>

openssl_encrypt
openssl_free_key
OpenSSL Funkcje


Free key resource

openssl_error_string
openssl_get_cipher_methods
OpenSSL Funkcje
PHP Manual

openssl_free_key

(PHP 4 >= 4.0.4, PHP 5)

openssl_free_key — Free key resource

Opis

void openssl_free_key ( resource $key_identifier )

openssl_free_key() frees the key associated with the specified key_identifier from memory.

Parametry

key_identifier

Zwracane wartości

Nie jest zwracana żadna wartość.

openssl_error_string
openssl_get_cipher_methods
OpenSSL Funkcje


Gets available cipher methods

openssl_free_key
openssl_get_md_methods
OpenSSL Funkcje
PHP Manual

openssl_get_cipher_methods

(PHP 5 >= 5.3.0)

openssl_get_cipher_methods — Gets available cipher methods

Opis

array openssl_get_cipher_methods ([ bool $aliases = false ] )

Gets a list of available cipher methods.

Parametry

aliases

Set to TRUE if cipher aliases should be included within the returned array.

Zwracane wartości

An array of available cipher methods.

Przykłady

Przykład #1 openssl_get_cipher_methods() example

Shows how the available ciphers might look, and also which aliases might be available.

<?php
$ciphers             = openssl_get_cipher_methods();
$ciphers_and_aliases = openssl_get_cipher_methods(true);
$cipher_aliases      = array_diff($ciphers_and_aliases, $ciphers);

print_r($ciphers);

print_r($cipher_aliases);

?>

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

Array
(
    [0] => AES-128-CBC
    [1] => AES-128-CFB
    [2] => AES-128-CFB1
    [3] => AES-128-CFB8
    [4] => AES-128-ECB
    [5] => AES-128-OFB
    [6] => AES-192-CBC
    [7] => AES-192-CFB
    [8] => AES-192-CFB1
    [9] => AES-192-CFB8
    [10] => AES-192-ECB
    [11] => AES-192-OFB
    [12] => AES-256-CBC
    [13] => AES-256-CFB
    [14] => AES-256-CFB1
    [15] => AES-256-CFB8
    [16] => AES-256-ECB
    [17] => AES-256-OFB
    [18] => BF-CBC
    [19] => BF-CFB
    [20] => BF-ECB
    [21] => BF-OFB
    [22] => CAST5-CBC
    [23] => CAST5-CFB
    [24] => CAST5-ECB
    [25] => CAST5-OFB
    [26] => DES-CBC
    [27] => DES-CFB
    [28] => DES-CFB1
    [29] => DES-CFB8
    [30] => DES-ECB
    [31] => DES-EDE
    [32] => DES-EDE-CBC
    [33] => DES-EDE-CFB
    [34] => DES-EDE-OFB
    [35] => DES-EDE3
    [36] => DES-EDE3-CBC
    [37] => DES-EDE3-CFB
    [38] => DES-EDE3-OFB
    [39] => DES-OFB
    [40] => DESX-CBC
    [41] => IDEA-CBC
    [42] => IDEA-CFB
    [43] => IDEA-ECB
    [44] => IDEA-OFB
    [45] => RC2-40-CBC
    [46] => RC2-64-CBC
    [47] => RC2-CBC
    [48] => RC2-CFB
    [49] => RC2-ECB
    [50] => RC2-OFB
    [51] => RC4
    [52] => RC4-40
    [53] => aes-128-cbc
    [54] => aes-128-cfb
    [55] => aes-128-cfb1
    [56] => aes-128-cfb8
    [57] => aes-128-ecb
    [58] => aes-128-ofb
    [59] => aes-192-cbc
    [60] => aes-192-cfb
    [61] => aes-192-cfb1
    [62] => aes-192-cfb8
    [63] => aes-192-ecb
    [64] => aes-192-ofb
    [65] => aes-256-cbc
    [66] => aes-256-cfb
    [67] => aes-256-cfb1
    [68] => aes-256-cfb8
    [69] => aes-256-ecb
    [70] => aes-256-ofb
    [71] => bf-cbc
    [72] => bf-cfb
    [73] => bf-ecb
    [74] => bf-ofb
    [75] => cast5-cbc
    [76] => cast5-cfb
    [77] => cast5-ecb
    [78] => cast5-ofb
    [79] => des-cbc
    [80] => des-cfb
    [81] => des-cfb1
    [82] => des-cfb8
    [83] => des-ecb
    [84] => des-ede
    [85] => des-ede-cbc
    [86] => des-ede-cfb
    [87] => des-ede-ofb
    [88] => des-ede3
    [89] => des-ede3-cbc
    [90] => des-ede3-cfb
    [91] => des-ede3-ofb
    [92] => des-ofb
    [93] => desx-cbc
    [94] => idea-cbc
    [95] => idea-cfb
    [96] => idea-ecb
    [97] => idea-ofb
    [98] => rc2-40-cbc
    [99] => rc2-64-cbc
    [100] => rc2-cbc
    [101] => rc2-cfb
    [102] => rc2-ecb
    [103] => rc2-ofb
    [104] => rc4
    [105] => rc4-40
)
Array
(
    [18] => AES128
    [19] => AES192
    [20] => AES256
    [21] => BF
    [26] => CAST
    [27] => CAST-cbc
    [32] => DES
    [47] => DES3
    [48] => DESX
    [50] => IDEA
    [55] => RC2
    [82] => aes128
    [83] => aes192
    [84] => aes256
    [85] => bf
    [90] => blowfish
    [91] => cast
    [92] => cast-cbc
    [97] => des
    [112] => des3
    [113] => desx
    [115] => idea
    [120] => rc2
)

Zobacz też:

  • openssl_get_md_methods() - Gets available digest methods

openssl_free_key
openssl_get_md_methods
OpenSSL Funkcje


Gets available digest methods

openssl_get_cipher_methods
openssl_get_privatekey
OpenSSL Funkcje
PHP Manual

openssl_get_md_methods

(PHP 5 >= 5.3.0)

openssl_get_md_methods — Gets available digest methods

Opis

array openssl_get_md_methods ([ bool $aliases = false ] )

Gets a list of available digest methods.

Parametry

aliases

Set to TRUE if digest aliases should be included within the returned array.

Zwracane wartości

An array of available digest methods.

Przykłady

Przykład #1 openssl_get_md_methods() example

Shows how the available digests might look, and also which aliases might be available.

<?php
$digests             = openssl_get_md_methods();
$digests_and_aliases = openssl_get_md_methods(true);
$digest_aliases      = array_diff($digests_and_aliases, $digests);

print_r($digests);

print_r($digest_aliases);

?>

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

Array
(
    [0] => DSA
    [1] => DSA-SHA
    [2] => MD2
    [3] => MD4
    [4] => MD5
    [5] => RIPEMD160
    [6] => SHA
    [7] => SHA1
    [8] => SHA224
    [9] => SHA256
    [10] => SHA384
    [11] => SHA512
    [12] => dsaEncryption
    [13] => dsaWithSHA
    [14] => ecdsa-with-SHA1
    [15] => md2
    [16] => md4
    [17] => md5
    [18] => ripemd160
    [19] => sha
    [20] => sha1
    [21] => sha224
    [22] => sha256
    [23] => sha384
    [24] => sha512
)
Array
(
    [2] => DSA-SHA1
    [3] => DSA-SHA1-old
    [4] => DSS1
    [9] => RSA-MD2
    [10] => RSA-MD4
    [11] => RSA-MD5
    [12] => RSA-RIPEMD160
    [13] => RSA-SHA
    [14] => RSA-SHA1
    [15] => RSA-SHA1-2
    [16] => RSA-SHA224
    [17] => RSA-SHA256
    [18] => RSA-SHA384
    [19] => RSA-SHA512
    [28] => dsaWithSHA1
    [29] => dss1
    [32] => md2WithRSAEncryption
    [34] => md4WithRSAEncryption
    [36] => md5WithRSAEncryption
    [37] => ripemd
    [39] => ripemd160WithRSA
    [40] => rmd160
    [43] => sha1WithRSAEncryption
    [45] => sha224WithRSAEncryption
    [47] => sha256WithRSAEncryption
    [49] => sha384WithRSAEncryption
    [51] => sha512WithRSAEncryption
    [52] => shaWithRSAEncryption
    [53] => ssl2-md5
    [54] => ssl3-md5
    [55] => ssl3-sha1
)

Zobacz też:

  • openssl_digest() - Computes a digest
  • openssl_get_cipher_methods() - Gets available cipher methods

openssl_get_cipher_methods
openssl_get_privatekey
OpenSSL Funkcje


Alias dla openssl_pkey_get_private

openssl_get_md_methods
openssl_get_publickey
OpenSSL Funkcje
PHP Manual

openssl_get_privatekey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_privatekey — Alias dla openssl_pkey_get_private()

Opis

Ta funkcja jest aliasem dla: openssl_pkey_get_private().

openssl_get_md_methods
openssl_get_publickey
OpenSSL Funkcje


Alias dla openssl_pkey_get_public

openssl_get_privatekey
openssl_open
OpenSSL Funkcje
PHP Manual

openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5)

openssl_get_publickey — Alias dla openssl_pkey_get_public()

Opis

Ta funkcja jest aliasem dla: openssl_pkey_get_public().

openssl_get_privatekey
openssl_open
OpenSSL Funkcje


Open sealed data

openssl_get_publickey
openssl_pkcs12_export_to_file
OpenSSL Funkcje
PHP Manual

openssl_open

(PHP 4 >= 4.0.4, PHP 5)

openssl_open — Open sealed data

Opis

bool openssl_open ( string $sealed_data , string &$open_data , string $env_key , mixed $priv_key_id [, string $method ] )

openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.

Parametry

sealed_data

open_data

If the call is successful the opened data is returned in this parameter.

env_key

priv_key_id

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 openssl_open() example

<?php
// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $env_key, $pkeyid)) {
    echo "here is the opened data: ", $open;
} else {
    echo "failed to open data";
}

// free the private key from memory
openssl_free_key($pkeyid);
?>

Zobacz też:

  • openssl_seal() - Seal (encrypt) data

openssl_get_publickey
openssl_pkcs12_export_to_file
OpenSSL Funkcje


Exports a PKCS#12 Compatible Certificate Store File

openssl_open
openssl_pkcs12_export
OpenSSL Funkcje
PHP Manual

openssl_pkcs12_export_to_file

(PHP 5 >= 5.2.2)

openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File

Opis

bool openssl_pkcs12_export_to_file ( mixed $x509 , string $filename , mixed $priv_key , string $pass [, array $args ] )

openssl_pkcs12_export_to_file() stores x509 into a file named by filename in a PKCS#12 file format.

Parametry

x509

Zobacz Parametry Klucza/Certyfikatu, aby zapoznać się z prawidłowymi wartościami.

filename

Path to the output file.

priv_key

Private key component of PKCS#12 file.

pass

Encryption password for unlocking the PKCS#12 file.

args

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

openssl_open
openssl_pkcs12_export
OpenSSL Funkcje


Exports a PKCS#12 Compatible Certificate Store File to variable.

openssl_pkcs12_export_to_file
openssl_pkcs12_read
OpenSSL Funkcje
PHP Manual

openssl_pkcs12_export

(PHP 5 >= 5.2.2)

openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable.

Opis

bool openssl_pkcs12_export ( mixed $x509 , string &$out , mixed $priv_key , string $pass [, array $args ] )

openssl_pkcs12_export() stores x509 into a string named by out in a PKCS#12 file format.

Parametry

x509

Zobacz Parametry Klucza/Certyfikatu, aby zapoznać się z prawidłowymi wartościami.

out

On success, this will hold the PKCS#12.

priv_key

Private key component of PKCS#12 file.

pass

Encryption password for unlocking the PKCS#12 file.

args

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

openssl_pkcs12_export_to_file
openssl_pkcs12_read
OpenSSL Funkcje


Parse a PKCS#12 Certificate Store into an array

openssl_pkcs12_export
openssl_pkcs7_decrypt
OpenSSL Funkcje
PHP Manual

openssl_pkcs12_read

(PHP 5 >= 5.2.2)

openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array

Opis

bool openssl_pkcs12_read ( string $pkcs12 , array &$certs , string $pass )

openssl_pkcs12_read() parses the PKCS#12 certificate store supplied by pkcs12 into a array named certs.

Parametry

pkcs12

certs

On success, this will hold the Certificate Store Data.

pass

Encryption password for unlocking the PKCS#12 file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

openssl_pkcs12_export
openssl_pkcs7_decrypt
OpenSSL Funkcje


Decrypts an S/MIME encrypted message

openssl_pkcs12_read
openssl_pkcs7_encrypt
OpenSSL Funkcje
PHP Manual

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message

Opis

bool openssl_pkcs7_decrypt ( string $infilename , string $outfilename , mixed $recipcert [, mixed $recipkey ] )

Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and its associated private key specified by recipcert and recipkey.

Parametry

infilename

outfilename

The decrypted message is written to the file specified by outfilename.

recipcert

recipkey

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 openssl_pkcs7_decrypt() example

<?php
// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg";  // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key)) {
    echo "decrypted!";
} else {
    echo "failed to decrypt!";
}
?>

openssl_pkcs12_read
openssl_pkcs7_encrypt
OpenSSL Funkcje


Encrypt an S/MIME message

openssl_pkcs7_decrypt
openssl_pkcs7_sign
OpenSSL Funkcje
PHP Manual

openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_encrypt — Encrypt an S/MIME message

Opis

bool openssl_pkcs7_encrypt ( string $infile , string $outfile , mixed $recipcerts , array $headers [, int $flags = 0 [, int $cipherid = OPENSSL_CIPHER_RC2_40 ]] )

openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts.

Parametry

infile

outfile

recipcerts

Either a lone X.509 certificate, or an array of X.509 certificates.

headers

headers is an array of headers that will be prepended to the data after it has been encrypted.

headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.

flags

flags can be used to specify options that affect the encoding process - see PKCS7 constants.

cipherid

One of cipher constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.0.0 | The cipherid parameter was added.

Przykłady

Przykład #1 openssl_pkcs7_encrypt() example

<?php
// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = file_get_contents("nighthawk.pem");

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" => "nighthawk@example.com", // keyed syntax
          "From: HQ <hq@example.com>", // indexed syntax
          "Subject" => "Eyes only"))) {
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}
?>

openssl_pkcs7_decrypt
openssl_pkcs7_sign
OpenSSL Funkcje


Sign an S/MIME message

openssl_pkcs7_encrypt
openssl_pkcs7_verify
OpenSSL Funkcje
PHP Manual

openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_sign — Sign an S/MIME message

Opis

bool openssl_pkcs7_sign ( string $infilename , string $outfilename , mixed $signcert , mixed $privkey , array $headers [, int $flags = PKCS7_DETACHED [, string $extracerts ]] )

openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and its matching private key specified by signcert and privkey parameters.

Parametry

infilename

outfilename

signcert

privkey

headers

headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter).

flags

flags can be used to alter the output - see PKCS7 constants.

extracerts

extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 openssl_pkcs7_sign() example

<?php
// the message you want to sign so that recipient can be sure it was you that
// sent it
$data = <<<EOD

You have my authorization to spend $10,000 on dinner expenses.

The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
    array("file://mycert.pem", "mypassphrase"),
    array("To" => "joes@example.com", // keyed syntax
          "From: HQ <ceo@example.com>", // indexed syntax
          "Subject" => "Eyes only")
    )) {
    // message signed - send it!
    exec(ini_get("sendmail_path") . " < signed.txt");
}
?>

openssl_pkcs7_encrypt
openssl_pkcs7_verify
OpenSSL Funkcje


Verifies the signature of an S/MIME signed message

openssl_pkcs7_sign
openssl_pkey_export_to_file
OpenSSL Funkcje
PHP Manual

openssl_pkcs7_verify

(PHP 4 >= 4.0.6, PHP 5)

openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message

Opis

mixed openssl_pkcs7_verify ( string $filename , int $flags [, string $outfilename [, array $cainfo [, string $extracerts [, string $content ]]]] )

openssl_pkcs7_verify() reads the S/MIME message contained in the given file and examines the digital signature.

Parametry

filename

Path to the message.

flags

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

outfilename

If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.

cainfo

If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.

extracerts

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

content

You can specify a filename with content that will be filled with the verified data, but with the signature information stripped.

Zwracane wartości

Returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

Rejestr zmian

Wersja | Opis
5.1.0 | The content parameter was added.

Notatki

Informacja: As specified in RFC 2045, lines may not be longer than 76 characters in the filename parameter.

openssl_pkcs7_sign
openssl_pkey_export_to_file
OpenSSL Funkcje


Gets an exportable representation of a key into a file

openssl_pkcs7_verify
openssl_pkey_export
OpenSSL Funkcje
PHP Manual

openssl_pkey_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_export_to_file — Gets an exportable representation of a key into a file

Opis

bool openssl_pkey_export_to_file ( mixed $key , string $outfilename [, string $passphrase [, array $configargs ]] )

openssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of key into the file named by outfilename.

Informacja: Aby ta funkcja prawidłowo działała wymaga poprawnie zainstalowanego openssl.cnf. Aby uzyskać więcej informacji przeczytaj rozdział instalacja openssl.

Parametry

key

outfilename

Path to the output file.

passphrase

The key can be optionally protected by a passphrase.

configargs

configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

openssl_pkcs7_verify
openssl_pkey_export
OpenSSL Funkcje


Gets an exportable representation of a key into a string

openssl_pkey_export_to_file
openssl_pkey_free
OpenSSL Funkcje
PHP Manual

openssl_pkey_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_export — Gets an exportable representation of a key into a string

Opis

bool openssl_pkey_export ( mixed $key , string &$out [, string $passphrase [, array $configargs ]] )

openssl_pkey_export() exports key as a PEM encoded string and stores it into out (which is passed by reference).

Informacja: Aby ta funkcja prawidłowo działała wymaga poprawnie zainstalowanego openssl.cnf. Aby uzyskać więcej informacji przeczytaj rozdział instalacja openssl.

Parametry

key

out

passphrase

The key is optionally protected by passphrase.

configargs

configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

openssl_pkey_export_to_file
openssl_pkey_free
OpenSSL Funkcje


Frees a private key

openssl_pkey_export
openssl_pkey_get_details
OpenSSL Funkcje
PHP Manual

openssl_pkey_free

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_free — Frees a private key

Opis

void openssl_pkey_free ( resource $key )

This function frees a private key created by openssl_pkey_new().

Parametry

key

Resource holding the key.

Zwracane wartości

Nie jest zwracana żadna wartość.

openssl_pkey_export
openssl_pkey_get_details
OpenSSL Funkcje


Returns an array with the key details

openssl_pkey_free
openssl_pkey_get_private
OpenSSL Funkcje
PHP Manual

openssl_pkey_get_details

(PHP 5 >= 5.2.0)

openssl_pkey_get_details — Returns an array with the key details

Opis

array openssl_pkey_get_details ( resource $key )

This function returns the key details (bits, key, type).

Parametry

key

Resource holding the key.

Zwracane wartości

Returns an array with the key details in success or FALSE in failure. Returned array has indexes bits (number of bits), key (string representation of the public key) and type (type of the key which is one of OPENSSL_KEYTYPE_RSA, OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_EC or -1 meaning unknown).

Depending on the key type used, additional details may be returned. Note that some elements may not always be available.

  • OPENSSL_KEYTYPE_RSA, an additional array key named "rsa", containing the key data is returned.
    Key Opis
    "n"
    "e"
    "d"
    "p"
    "q"
    "dmp1"
    "dmq1"
    "iqmp"
  • OPENSSL_KEYTYPE_DSA, an additional array key named "dsa", containing the key data is returned.
    Key Opis
    "p"
    "q"
    "g"
    "priv_key"
    "pub_key"
  • OPENSSL_KEYTYPE_DH, an additional array key named "dh", containing the key data is returned.
    Key Opis
    "p"
    "g"
    "priv_key"
    "pub_key"
openssl_pkey_free
openssl_pkey_get_private
OpenSSL Funkcje


Get a private key

openssl_pkey_get_details
openssl_pkey_get_public
OpenSSL Funkcje
PHP Manual

openssl_pkey_get_private

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_private — Get a private key

Opis

resource openssl_pkey_get_private ( mixed $key [, string $passphrase = "" ] )

openssl_get_privatekey() parses key and prepares it for use by other functions.

Parametry

key

key can be one of the following:

  1. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
  2. A PEM formatted private key.

passphrase

The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

Zwracane wartości

Returns a positive key resource identifier on success, or FALSE on error.

openssl_pkey_get_details
openssl_pkey_get_public
OpenSSL Funkcje


Extract public key from certificate and prepare it for use

openssl_pkey_get_private
openssl_pkey_new
OpenSSL Funkcje
PHP Manual

openssl_pkey_get_public

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_get_public — Extract public key from certificate and prepare it for use

Opis

resource openssl_pkey_get_public ( mixed $certificate )

openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions.

Parametry

certificate

certificate can be one of the following:

  1. an X.509 certificate resource
  2. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
  3. A PEM formatted private key.

Zwracane wartości

Returns a positive key resource identifier on success, or FALSE on error.

openssl_pkey_get_private
openssl_pkey_new
OpenSSL Funkcje


Generates a new private key

openssl_pkey_get_public
openssl_private_decrypt
OpenSSL Funkcje
PHP Manual

openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5)

openssl_pkey_new — Generates a new private key

Opis

resource openssl_pkey_new ([ array $configargs ] )

openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public().

Informacja: Aby ta funkcja prawidłowo działała wymaga poprawnie zainstalowanego openssl.cnf. Aby uzyskać więcej informacji przeczytaj rozdział instalacja openssl.

Parametry

configargs

You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.

Zwracane wartości

Returns a resource identifier for the pkey on success, or FALSE on error.

openssl_pkey_get_public
openssl_private_decrypt
OpenSSL Funkcje


Decrypts data with private key

openssl_pkey_new
openssl_private_encrypt
OpenSSL Funkcje
PHP Manual

openssl_private_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_private_decrypt — Decrypts data with private key

Opis

bool openssl_private_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_private_decrypt() decrypts data that was previous encrypted via openssl_public_encrypt() and stores the result into decrypted.

You can use this function e.g. to decrypt data which were supposed only to you.

Parametry

data

decrypted

key

key must be the private key corresponding that was used to encrypt the data.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key

openssl_pkey_new
openssl_private_encrypt
OpenSSL Funkcje


Encrypts data with private key

openssl_private_decrypt
openssl_public_decrypt
OpenSSL Funkcje
PHP Manual

openssl_private_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_private_encrypt — Encrypts data with private key

Opis

bool openssl_private_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_private_encrypt() encrypts data with private key and stores the result into crypted. Encrypted data can be decrypted via openssl_public_decrypt().

This function can be used e.g. to sign data (or its hash) to prove that it is not written by someone else.

Parametry

data

crypted

key

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key

openssl_private_decrypt
openssl_public_decrypt
OpenSSL Funkcje


Decrypts data with public key

openssl_private_encrypt
openssl_public_encrypt
OpenSSL Funkcje
PHP Manual

openssl_public_decrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_public_decrypt — Decrypts data with public key

Opis

bool openssl_public_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_public_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted.

You can use this function e.g. to check if the message was written by the owner of the private key.

Parametry

data

decrypted

key

key must be the public key corresponding that was used to encrypt the data.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key

openssl_private_encrypt
openssl_public_encrypt
OpenSSL Funkcje


Encrypts data with public key

openssl_public_decrypt
openssl_random_pseudo_bytes
OpenSSL Funkcje
PHP Manual

openssl_public_encrypt

(PHP 4 >= 4.0.6, PHP 5)

openssl_public_encrypt — Encrypts data with public key

Opis

bool openssl_public_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] )

openssl_public_encrypt() encrypts data with public key and stores the result into crypted. Encrypted data can be decrypted via openssl_private_decrypt().

This function can be used e.g. to encrypt message which can be then read only by owner of the private key. It can be also used to store secure data in database.

Parametry

data

crypted

This will hold the result of the encryption.

key

The public key.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key

openssl_public_decrypt
openssl_random_pseudo_bytes
OpenSSL Funkcje


Generate a pseudo-random string of bytes

openssl_public_encrypt
openssl_seal
OpenSSL Funkcje
PHP Manual

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0)

openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes

Opis

string openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] )

Generates a string of pseudo-random bytes, with the number of bytes determined by the length parameter.

It also indicates if a cryptographically strong algorithm was used to produce the pseudo-random bytes, and does this via the optional crypto_strong parameter. It's rare for this to be FALSE, but some systems may be broken or old.

Parametry

length

The length of the desired string of bytes. Must be a positive integer. PHP will try to cast this parameter to a non-null integer to use it.

crypto_strong

If passed into the function, this will hold a boolean value that determines if the algorithm used was "cryptographically strong", e.g., safe for usage with GPG, passwords, etc. TRUE if it did, otherwise FALSE

Zwracane wartości

Returns the generated string of bytes on success, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 openssl_random_pseudo_bytes() example

<?php
for ($i = -1; $i <= 4; $i++) {
    $bytes = openssl_random_pseudo_bytes($i, $cstrong);
    $hex   = bin2hex($bytes);

    echo "Lengths: Bytes: $i and Hex: " . strlen($hex) . PHP_EOL;
    var_dump($hex);
    var_dump($cstrong);
    echo PHP_EOL;
}
?>

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

Lengths: Bytes: -1 and Hex: 0
string(0) ""
NULL

Lengths: Bytes: 0 and Hex: 0
string(0) ""
NULL

Lengths: Bytes: 1 and Hex: 2
string(2) "42"
bool(true)

Lengths: Bytes: 2 and Hex: 4
string(4) "dc6e"
bool(true)

Lengths: Bytes: 3 and Hex: 6
string(6) "288591"
bool(true)

Lengths: Bytes: 4 and Hex: 8
string(8) "ab86d144"
bool(true)

Zobacz też:

  • bin2hex() - Convert binary data into hexadecimal representation
  • crypt() - One-way string hashing
  • mt_rand() - Wygeneruj lepszą liczbę losową
  • uniqid() - Generate a unique ID
openssl_public_encrypt
openssl_seal
OpenSSL Funkcje


Seal (encrypt) data

openssl_random_pseudo_bytes
openssl_sign
OpenSSL Funkcje
PHP Manual

openssl_seal

(PHP 4 >= 4.0.4, PHP 5)

openssl_seal — Seal (encrypt) data

Opis

int openssl_seal ( string $data , string &$sealed_data , array &$env_keys , array $pub_key_ids [, string $method ] )

openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.

Parametry

data

sealed_data

env_keys

pub_key_ids

Zwracane wartości

Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys.

Przykłady

Przykład #1 openssl_seal() example

<?php
// $data is assumed to contain the data to be sealed

// fetch public keys for our recipients, and ready them
$fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk1 = openssl_get_publickey($cert);
// Repeat for second recipient
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk2 = openssl_get_publickey($cert);

// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
openssl_seal($data, $sealed, $ekeys, array($pk1, $pk2));

// free the keys from memory
openssl_free_key($pk1);
openssl_free_key($pk2);
?>

Zobacz też:

  • openssl_open() - Open sealed data

openssl_random_pseudo_bytes
openssl_sign
OpenSSL Funkcje


Generate signature

openssl_seal
openssl_verify
OpenSSL Funkcje
PHP Manual

openssl_sign

(PHP 4 >= 4.0.4, PHP 5)

openssl_sign — Generate signature

Opis

bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, int $signature_alg = OPENSSL_ALGO_SHA1 ] )

openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted.

Parametry

data

signature

If the call was successful the signature is returned in signature.

priv_key_id

signature_alg

For more information see the list of Signature Algorithms.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.0.0 | The signature_alg parameter was added.

Przykłady

Przykład #1 openssl_sign() example

<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?>

Zobacz też:

  • openssl_verify() - Verify signature

openssl_seal
openssl_verify
OpenSSL Funkcje


Verify signature

openssl_sign
openssl_x509_check_private_key
OpenSSL Funkcje
PHP Manual

openssl_verify

(PHP 4 >= 4.0.4, PHP 5)

openssl_verify — Verify signature

Opis

int openssl_verify ( string $data , string $signature , mixed $pub_key_id [, int $signature_alg = OPENSSL_ALGO_SHA1 ] )

openssl_verify() verifies that the signature is correct for the specified data using the public key associated with pub_key_id. This must be the public key corresponding to the private key used for signing.

Parametry

data

signature

pub_key_id

signature_alg

For more information see the list of Signature Algorithms.

Zwracane wartości

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

Rejestr zmian

Wersja | Opis
5.2.0 | The signature_alg parameter was added.

Przykłady

Przykład #1 openssl_verify() example

<?php
// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>

Zobacz też:

  • openssl_sign() - Generate signature

openssl_sign
openssl_x509_check_private_key
OpenSSL Funkcje


Checks if a private key corresponds to a certificate

openssl_verify
openssl_x509_checkpurpose
OpenSSL Funkcje
PHP Manual

openssl_x509_check_private_key

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_check_private_key — Checks if a private key corresponds to a certificate

Opis

bool openssl_x509_check_private_key ( mixed $cert , mixed $key )

Checks whether the given key is the private key that corresponds to cert.

Parametry

cert

The certificate.

key

The private key.

Zwracane wartości

Returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.

openssl_verify
openssl_x509_checkpurpose
OpenSSL Funkcje


Verifies if a certificate can be used for a particular purpose

openssl_x509_check_private_key
openssl_x509_export_to_file
OpenSSL Funkcje
PHP Manual

openssl_x509_checkpurpose

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose

Opis

int openssl_x509_checkpurpose ( mixed $x509cert , int $purpose [, array $cainfo = array() [, string $untrustedfile ]] )

openssl_x509_checkpurpose() examines a certificate to see if it can be used for the specified purpose.

Parametry

x509cert

The examined certificate.

purpose

openssl_x509_checkpurpose() purposes
Constant | Description
X509_PURPOSE_SSL_CLIENT | Can the certificate be used for the client side of an SSL connection?
X509_PURPOSE_SSL_SERVER | Can the certificate be used for the server side of an SSL connection?
X509_PURPOSE_NS_SSL_SERVER | Can the cert be used for Netscape SSL server?
X509_PURPOSE_SMIME_SIGN | Can the cert be used to sign S/MIME email?
X509_PURPOSE_SMIME_ENCRYPT | Can the cert be used to encrypt S/MIME email?
X509_PURPOSE_CRL_SIGN | Can the cert be used to sign a certificate revocation list (CRL)?
X509_PURPOSE_ANY | Can the cert be used for Any/All purposes?
These options are not bitfields - you may specify one only!

cainfo

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.

untrustedfile

If specified, this should be the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust is placed in the certificates that come from that file.

Zwracane wartości

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

openssl_x509_check_private_key
openssl_x509_export_to_file
OpenSSL Funkcje


Exports a certificate to file

openssl_x509_checkpurpose
openssl_x509_export
OpenSSL Funkcje
PHP Manual

openssl_x509_export_to_file

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_export_to_file — Exports a certificate to file

Opis

bool openssl_x509_export_to_file ( mixed $x509 , string $outfilename [, bool $notext = TRUE ] )

openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.

Parametry

x509

Zobacz Parametry Klucza/Certyfikatu, aby zapoznać się z prawidłowymi wartościami.

outfilename

Path to the output file.

notext

Opcjonalny parametr notext wpływa na szczegółowość komunikatów wyjścia. Jeśli wynosi FALSE, wówczas do wyjścia dołączane są dodatkowe informacje zrozumiałe dla ludzi. Wartość domyślna parametru notext wynosi: TRUE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

openssl_x509_checkpurpose
openssl_x509_export
OpenSSL Funkcje


Exports a certificate as a string

openssl_x509_export_to_file
openssl_x509_free
OpenSSL Funkcje
PHP Manual

openssl_x509_export

(PHP 4 >= 4.2.0, PHP 5)

openssl_x509_export — Exports a certificate as a string

Opis

bool openssl_x509_export ( mixed $x509 , string &$output [, bool $notext = TRUE ] )

openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.

Parametry

x509

Zobacz Parametry Klucza/Certyfikatu, aby zapoznać się z prawidłowymi wartościami.

output

On success, this will hold the PEM.

notext

Opcjonalny parametr notext wpływa na szczegółowość komunikatów wyjścia. Jeśli wynosi FALSE, wówczas do wyjścia dołączane są dodatkowe informacje zrozumiałe dla ludzi. Wartość domyślna parametru notext wynosi: TRUE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

openssl_x509_export_to_file
openssl_x509_free
OpenSSL Funkcje


Free certificate resource

openssl_x509_export
openssl_x509_parse
OpenSSL Funkcje
PHP Manual

openssl_x509_free

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_free — Free certificate resource

Opis

void openssl_x509_free ( resource $x509cert )

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

Parametry

x509cert

Zwracane wartości

Nie jest zwracana żadna wartość.

openssl_x509_export
openssl_x509_parse
OpenSSL Funkcje


Parse an X509 certificate and return the information as an array

openssl_x509_free
openssl_x509_read
OpenSSL Funkcje
PHP Manual

openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_parse — Parse an X509 certificate and return the information as an array

Opis

array openssl_x509_parse ( mixed $x509cert [, bool $shortnames = true ] )

openssl_x509_parse() returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc.

Parametry

x509cert

shortnames

shortnames controls how the data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.

Zwracane wartości

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

openssl_x509_free
openssl_x509_read
OpenSSL Funkcje


Parse an X.509 certificate and return a resource identifier for it

openssl_x509_parse
Rozszerzenia baz danych
OpenSSL Funkcje
PHP Manual

openssl_x509_read

(PHP 4 >= 4.0.6, PHP 5)

openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it

Opis

resource openssl_x509_read ( mixed $x509certdata )

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

Parametry

x509certdata

Zwracane wartości

Returns a resource identifier on success lub FALSE w przypadku niepowodzenia.

openssl_x509_parse
Rozszerzenia baz danych
OpenSSL Funkcje


Rozszerzenia baz danych

  • Warstwy abstrakcji
    • DBA — Database (dbm-style) Abstraction Layer
    • dbx
    • ODBC — ODBC (Unified)
    • PDO — PHP Data Objects
  • Rozszerzenia producentów baz danych
    • CUBRID
    • DB++
    • dBase
    • filePro
    • Firebird/InterBase
    • FrontBase
    • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Informix
    • Ingres — Ingres DBMS, EDBC, i Enterprise Access Gateways
    • MaxDB
    • Mongo — MongoDB Native Driver
    • mSQL
    • Mssql — Microsoft SQL Server
    • MySQL — MySQL Drivers and Plugins
    • OCI8 — Oracle OCI8
    • Ovrimos SQL
    • Paradox — Paradox File Access
    • PostgreSQL
    • SQLite
    • SQLite3
    • SQLSRV — Microsoft SQL Server Driver for PHP
    • Sybase
    • tokyo_tyrant
openssl_x509_read
Warstwy abstrakcji
Opis funkcji


Warstwy abstrakcji

  • DBA — Database (dbm-style) Abstraction Layer
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • DBA Funkcje
  • dbx
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • dbx Funkcje
  • ODBC — ODBC (Unified)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • ODBC Funkcje
  • PDO — PHP Data Objects
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Connections and Connection management
    • Transactions and auto-commit
    • Prepared statements and stored procedures
    • Errors and error handling
    • Large Objects (LOBs)
    • PDO — The PDO class
    • PDOStatement — The PDOStatement class
    • PDOException — The PDOException class
    • PDO Drivers
Rozszerzenia baz danych
DBA
Rozszerzenia baz danych


Database (dbm-style) Abstraction Layer

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • DBA Funkcje
    • dba_close — Close a DBA database
    • dba_delete — Delete DBA entry specified by key
    • dba_exists — Check whether key exists
    • dba_fetch — Fetch data specified by key
    • dba_firstkey — Fetch first key
    • dba_handlers — List all the handlers available
    • dba_insert — Insert entry
    • dba_key_split — Splits a key in string representation into array representation
    • dba_list — List all open database files
    • dba_nextkey — Fetch next key
    • dba_open — Open database
    • dba_optimize — Optimize database
    • dba_popen — Open database persistently
    • dba_replace — Replace or insert entry
    • dba_sync — Synchronize database
Warstwy abstrakcji
Wstęp
Warstwy abstrakcji


Wstęp

These functions build the foundation for accessing Berkeley DB style databases.

This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as » Oracle Berkeley DB.

DBA
Instalacja/Konfiguracja
DBA


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
DBA


Wymagania

The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.

List of DBA handlers
Handler | Notes
dbm | Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format.
ndbm | Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated).
gdbm | Gdbm is the » GNU database manager.
db2 | DB2 is for » Oracle Berkeley DB 2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications.
db3 | DB3 is for » Oracle Berkeley DB 3.
db4 | DB4 is for » Oracle Berkeley DB 4 or 5. This option is available from PHP 4.3.2. It can be used with BDB 5 from PHP 5.3.3.
cdb | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at » http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library.
cdb_make | Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundled cdb library is used.
flatfile | This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library.
inifile | This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE.
qdbm | This is available since PHP 5.0.0. The qdbm library can be loaded from » http://fallabs.com/qdbm/index.html.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX configure switch to your PHP configure line.

Ostrzeżenie

After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfunctioning single handlers but not combinations.

Supported DBA handlers
Handler | Configure Switch
dbm

To enable support for dbm add --with-dbm[=DIR] .

Informacja:

dbm normally is a wrapper which often results in failures. This means you should only use dbm if you are sure it works and if you really need this format.

ndbm

To enable support for ndbm add --with-ndbm[=DIR] .

Informacja:

ndbm normally is a wrapper which often results in failures. This means you should only use ndbm if you are sure it works and if you really need this format.

gdbm | To enable support for gdbm add --with-gdbm[=DIR] .
db2

To enable support for Oracle Berkeley DB 2 add --with-db2[=DIR] .

Informacja:

db2 conflicts with db3 and db4.

db3

To enable support for Oracle Berkeley DB 3 add --with-db3[=DIR] .

Informacja:

db3 conflicts with db2 and db4.

db4

To enable support for Oracle Berkeley DB 4 or 5 add --with-db4[=DIR] .

Informacja:

db4 conflicts with db2 and db3.

Informacja:

The db4 option was added in PHP 4.3.2. In earlier versions of PHP you need to use --with-db3=DIR with DIR being the path to db4 library. It is not possible to use db versions starting from 4.1 with PHP prior to version 4.3.0. Also, the db libraries with versions 4.1 through 4.1.24 cannot be used in any PHP version.

Support for BDB 5 was added in PHP 5.3.3.

cdb

To enable support for cdb add --with-cdb[=DIR] .

Informacja:

Since PHP 4.3.0 you can omit DIR to use the bundled cdb library that adds the cdb_make handler which allows creation of cdb files and allows to access cdb files on the network using PHP's streams.

flatfile

To enable support for flatfile add --with-flatfile .

Informacja:

This was added in PHP 4.3.0 to add compatibility with deprecated dbm extension. Use this handler only when you cannot install one of the libraries required by the other handlers and when you cannot use bundled cdb handler.

inifile

To enable support for inifile add --with-inifile .

Informacja:

This was added in PHP 5.0.0 and allows to read and set microsoft style .ini files (like the php.ini file).

qdbm

To enable support for qdbm add --with-qdbm[=DIR] .

Informacja:

qdbm conflicts with dbm and gdbm.

Informacja:

This was added in PHP 5.0.0. The qdbm library can be loaded from » http://fallabs.com/qdbm/index.html.

Informacja:

Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only one of them can be used internally. That means that you cannot have both file formats. Starting with PHP 5.0.0 there is a configuration check avoid such misconfigurations.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
DBA


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
DBA


Basic usage

Przykład #1 DBA example

<?php

$id = dba_open("/tmp/test.db", "n", "db2");

if (!$id) {
    echo "dba_open failed\n";
    exit;
}

dba_replace("key", "This is an example!", $id);

if (dba_exists("key", $id)) {
    echo dba_fetch("key", $id);
    dba_delete("key", $id);
}

dba_close($id);
?>

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

Przykład #2 Traversing a database

<?php

// ...open database...

$key = dba_firstkey($id);

while ($key != false) {
    if (true) {          // remember the key to perform some action later
        $handle_later[] = $key;
    }
    $key = dba_nextkey($id);
}

foreach ($handle_later as $val) {
    dba_delete($val, $id);
}

?>

Przykłady
DBA Funkcje
Przykłady


DBA Funkcje

Spis treści

  • dba_close — Close a DBA database
  • dba_delete — Delete DBA entry specified by key
  • dba_exists — Check whether key exists
  • dba_fetch — Fetch data specified by key
  • dba_firstkey — Fetch first key
  • dba_handlers — List all the handlers available
  • dba_insert — Insert entry
  • dba_key_split — Splits a key in string representation into array representation
  • dba_list — List all open database files
  • dba_nextkey — Fetch next key
  • dba_open — Open database
  • dba_optimize — Optimize database
  • dba_popen — Open database persistently
  • dba_replace — Replace or insert entry
  • dba_sync — Synchronize database
Basic usage
dba_close
DBA


Close a DBA database

DBA Funkcje
dba_delete
DBA Funkcje
PHP Manual

dba_close

(PHP 4, PHP 5)

dba_close — Close a DBA database

Opis

void dba_close ( resource $handle )

dba_close() closes the established database and frees all resources of the specified database handle.

Parametry

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • dba_open() - Open database
  • dba_popen() - Open database persistently

DBA Funkcje
dba_delete
DBA Funkcje


Delete DBA entry specified by key

dba_close
dba_exists
DBA Funkcje
PHP Manual

dba_delete

(PHP 4, PHP 5)

dba_delete — Delete DBA entry specified by key

Opis

bool dba_delete ( string $key , resource $handle )

dba_delete() deletes the specified entry from the database.

Parametry

key

The key of the entry which is deleted.

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • dba_exists() - Check whether key exists
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry

dba_close
dba_exists
DBA Funkcje


Check whether key exists

dba_delete
dba_fetch
DBA Funkcje
PHP Manual

dba_exists

(PHP 4, PHP 5)

dba_exists — Check whether key exists

Opis

bool dba_exists ( string $key , resource $handle )

dba_exists() checks whether the specified key exists in the database.

Parametry

key

The key the check is performed for.

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Returns TRUE if the key exists, FALSE otherwise.

Zobacz też:

  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry

dba_delete
dba_fetch
DBA Funkcje


Fetch data specified by key

dba_exists
dba_firstkey
DBA Funkcje
PHP Manual

dba_fetch

(PHP 4, PHP 5)

dba_fetch — Fetch data specified by key

Opis

string dba_fetch ( string $key , resource $handle )
string dba_fetch ( string $key , int $skip , resource $handle )

dba_fetch() fetches the data specified by key from the database specified with handle.

Parametry

key

The key the data is specified by.

Informacja:

When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().

skip

The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Returns the associated string if the key/data pair is found, FALSE otherwise.

Rejestr zmian

Wersja | Opis
4.3.0 | The skip parameter is available to support cdb's capability of multiple keys having the same name.

Zobacz też:

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry
  • dba_key_split() - Splits a key in string representation into array representation

dba_exists
dba_firstkey
DBA Funkcje


Fetch first key

dba_fetch
dba_handlers
DBA Funkcje
PHP Manual

dba_firstkey

(PHP 4, PHP 5)

dba_firstkey — Fetch first key

Opis

string dba_firstkey ( resource $handle )

dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.

Parametry

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Returns the key on success lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • dba_nextkey() - Fetch next key
  • dba_key_split() - Splits a key in string representation into array representation
  • Example 2 in the DBA examples

dba_fetch
dba_handlers
DBA Funkcje


List all the handlers available

dba_firstkey
dba_insert
DBA Funkcje
PHP Manual

dba_handlers

(PHP 4 >= 4.3.0, PHP 5)

dba_handlers — List all the handlers available

Opis

array dba_handlers ([ bool $full_info = false ] )

dba_handlers() list all the handlers supported by this extension.

Parametry

full_info

Turns on/off full information display in the result.

Zwracane wartości

Returns an array of database handlers. If full_info is set to TRUE, the array will be associative with the handlers names as keys, and their version information as value. Otherwise, the result will be an indexed array of handlers names.

Informacja:

When the internal cdb library is used you will see cdb and cdb_make.

Przykłady

Przykład #1 dba_handlers() Example

<?php

echo "Available DBA handlers:\n";
foreach (dba_handlers(true) as $handler_name => $handler_version) {
  // clean the versions
  $handler_version = str_replace('$', '', $handler_version);
  echo " - $handler_name: $handler_version\n";
}

?>

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

Available DBA handlers:
 - cdb: 0.75, Revision: 1.3.2.3
 - cdb_make: 0.75, Revision: 1.2.2.4
 - db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
 - inifile: 1.0, Revision: 1.6.2.3
 - flatfile: 1.0, Revision: 1.5.2.4

dba_firstkey
dba_insert
DBA Funkcje


Insert entry

dba_handlers
dba_key_split
DBA Funkcje
PHP Manual

dba_insert

(PHP 4, PHP 5)

dba_insert — Insert entry

Opis

bool dba_insert ( string $key , string $value , resource $handle )

dba_insert() inserts the entry described with key and value into the database.

Parametry

key

The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.

value

The value to be inserted.

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_replace() - Replace or insert entry

dba_handlers
dba_key_split
DBA Funkcje


Splits a key in string representation into array representation

dba_insert
dba_list
DBA Funkcje
PHP Manual

dba_key_split

(PHP 5)

dba_key_split — Splits a key in string representation into array representation

Opis

mixed dba_key_split ( mixed $key )

dba_key_split() splits a key (string representation) into an array representation.

Parametry

key

The key in string representation.

Zwracane wartości

Returns an array of the form array(0 => group, 1 => value_name). This function will return FALSE if key is NULL or FALSE.

Zobacz też:

  • dba_firstkey() - Fetch first key
  • dba_nextkey() - Fetch next key
  • dba_fetch() - Fetch data specified by key

dba_insert
dba_list
DBA Funkcje


List all open database files

dba_key_split
dba_nextkey
DBA Funkcje
PHP Manual

dba_list

(PHP 4 >= 4.3.0, PHP 5)

dba_list — List all open database files

Opis

array dba_list ( void )

dba_list() list all open database files.

Zwracane wartości

An associative array, in the form resourceid => filename.

dba_key_split
dba_nextkey
DBA Funkcje


Fetch next key

dba_list
dba_open
DBA Funkcje
PHP Manual

dba_nextkey

(PHP 4, PHP 5)

dba_nextkey — Fetch next key

Opis

string dba_nextkey ( resource $handle )

dba_nextkey() returns the next key of the database and advances the internal key pointer.

Parametry

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Returns the key on success lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • dba_firstkey() - Fetch first key
  • dba_key_split() - Splits a key in string representation into array representation
  • Example 2 in the DBA examples

dba_list
dba_open
DBA Funkcje


Open database

dba_nextkey
dba_optimize
DBA Funkcje
PHP Manual

dba_open

(PHP 4, PHP 5)

dba_open — Open database

Opis

resource dba_open ( string $path , string $mode [, string $handler [, mixed $... ]] )

dba_open() establishes a database instance for path with mode using handler.

Parametry

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access. The database is created in BTree mode, other modes (like Hash or Queue) are not supported.

Additionally you can set the database lock method with the next char. Use l to lock the database with a .lck file or d to lock the databasefile itself. It is important that all of your applications do this consistently.

If you want to test the access and do not want to wait for the lock you can add t as third character. When you are absolutely sure that you do not require database locking you can do so by using - instead of l or d. When none of d, l or - is used, dba will lock on the database file as it would with d.

Informacja:

There can only be one writer for one database file. When you use dba on a web server and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:

DBA locking
already open | mode = "rl" | mode = "rlt" | mode = "wl" | mode = "wlt" | mode = "rd" | mode = "rdt" | mode = "wd" | mode = "wdt"
not open | ok | ok | ok | ok | ok | ok | ok | ok
mode = "rl" | ok | ok | wait | false | illegal | illegal | illegal | illegal
mode = "wl" | wait | false | wait | false | illegal | illegal | illegal | illegal
mode = "rd" | illegal | illegal | illegal | illegal | ok | ok | wait | false
mode = "wd" | illegal | illegal | illegal | illegal | wait | false | wait | false
  • ok: the second call will be successfull.
  • wait: the second call waits until dba_close() is called for the first.
  • false: the second call returns false.
  • illegal: you must not mix "l" and "d" modifiers for mode parameter.

handler

The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them.

Zwracane wartości

Returns a positive handle on success lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja | Opis
4.3.0 | It's possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found.
4.3.0 | Locking and the mode modifiers "l", "d", "-" and "t" were added. In previous PHP versions, you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support.
before 4.3.5 | open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existent database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed).

Zobacz też:

  • dba_popen() - Open database persistently
  • dba_close() - Close a DBA database

dba_nextkey
dba_optimize
DBA Funkcje


Optimize database

dba_open
dba_popen
DBA Funkcje
PHP Manual

dba_optimize

(PHP 4, PHP 5)

dba_optimize — Optimize database

Opis

bool dba_optimize ( resource $handle )

dba_optimize() optimizes the underlying database.

Parametry

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • dba_sync() - Synchronize database

dba_open
dba_popen
DBA Funkcje


Open database persistently

dba_optimize
dba_replace
DBA Funkcje
PHP Manual

dba_popen

(PHP 4, PHP 5)

dba_popen — Open database persistently

Opis

resource dba_popen ( string $path , string $mode [, string $handler [, mixed $... ]] )

dba_popen() establishes a persistent database instance for path with mode using handler.

Parametry

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.

handler

The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them.

Zwracane wartości

Returns a positive handle on success lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • dba_open() - Open database
  • dba_close() - Close a DBA database

dba_optimize
dba_replace
DBA Funkcje


Replace or insert entry

dba_popen
dba_sync
DBA Funkcje
PHP Manual

dba_replace

(PHP 4, PHP 5)

dba_replace — Replace or insert entry

Opis

bool dba_replace ( string $key , string $value , resource $handle )

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

Parametry

key

The key of the entry to be replaced.

value

The value to be replaced.

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry

dba_popen
dba_sync
DBA Funkcje


Synchronize database

dba_replace
dbx
DBA Funkcje
PHP Manual

dba_sync

(PHP 4, PHP 5)

dba_sync — Synchronize database

Opis

bool dba_sync ( resource $handle )

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

Parametry

handle

The database handler, returned by dba_open() or dba_popen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • dba_optimize() - Optimize database

dba_replace
dbx
DBA Funkcje


dbx

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • dbx Funkcje
    • dbx_close — Close an open connection/database
    • dbx_compare — Compare two rows for sorting purposes
    • dbx_connect — Open a connection/database
    • dbx_error — Report the error message of the latest function call in the module
    • dbx_escape_string — Escape a string so it can safely be used in an sql-statement
    • dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
    • dbx_query — Send a query and fetch all results (if any)
    • dbx_sort — Sort a result from a dbx_query by a custom sort function
dba_sync
Wstęp
Warstwy abstrakcji


Wstęp

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0.

dbx
Instalacja/Konfiguracja
dbx


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
dbx


Wymagania

To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, the following databases are supported, but others will follow:

  • FrontBase (available from PHP 4.1.0).
  • Microsoft SQL Server
  • MySQL
  • ODBC
  • PostgreSQL
  • Sybase-CT (available from PHP 4.2.0).
  • Oracle (oci8) (available from PHP 4.3.0).
  • SQLite (PHP 5).

Documentation for adding additional database support to dbx can be found at » http://www.guidance.nl/php/dbx/doc/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR] . To get other supported databases to work with the dbx-module refer to their specific documentation.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

DBX Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. Removed in 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.

dbx.colnames_case string

Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which holds the result of a query.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

DBX_MYSQL (integer)
DBX_ODBC (integer)
DBX_PGSQL (integer)
DBX_MSSQL (integer)
DBX_FBSQL (integer)
DBX_OCI8 (integer) (available from PHP 4.3.0)
DBX_SYBASECT (integer)
DBX_SQLITE (integer) (PHP 5)
DBX_PERSISTENT (integer)
DBX_RESULT_INFO (integer)
DBX_RESULT_INDEX (integer)
DBX_RESULT_ASSOC (integer)
DBX_RESULT_UNBUFFERED (integer) (PHP 5)
DBX_COLNAMES_UNCHANGED (integer) (available from PHP 4.3.0)
DBX_COLNAMES_UPPERCASE (integer) (available from PHP 4.3.0)
DBX_COLNAMES_LOWERCASE (integer) (available from PHP 4.3.0)
DBX_CMP_NATIVE (integer)
DBX_CMP_TEXT (integer)
DBX_CMP_NUMBER (integer)
DBX_CMP_ASC (integer)
DBX_CMP_DESC (integer)
Typy zasobów
dbx Funkcje
dbx


dbx Funkcje

Spis treści

  • dbx_close — Close an open connection/database
  • dbx_compare — Compare two rows for sorting purposes
  • dbx_connect — Open a connection/database
  • dbx_error — Report the error message of the latest function call in the module
  • dbx_escape_string — Escape a string so it can safely be used in an sql-statement
  • dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
  • dbx_query — Send a query and fetch all results (if any)
  • dbx_sort — Sort a result from a dbx_query by a custom sort function
Stałe predefiniowane
dbx_close
dbx


Close an open connection/database

dbx Funkcje
dbx_compare
dbx Funkcje
PHP Manual

dbx_close

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_close — Close an open connection/database

Opis

int dbx_close ( object $link_identifier )

Parametry

link_identifier

The DBX link object to close.

Zwracane wartości

Returns 1 on success and 0 on errors.

Przykłady

Przykład #1 dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notatki

Informacja:

Always refer to the module-specific documentation as well.

Zobacz też:

  • dbx_connect() - Open a connection/database

dbx Funkcje
dbx_compare
dbx Funkcje


Compare two rows for sorting purposes

dbx_close
dbx_connect
dbx Funkcje
PHP Manual

dbx_compare

(PHP 4 >= 4.1.0, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_compare — Compare two rows for sorting purposes

Opis

int dbx_compare ( array $row_a , array $row_b , string $column_key [, int $flags = DBX_CMP_ASC | DBX_CMP_NATIVE ] )

dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.

Parametry

row_a

First row

row_b

Second row

column_key

The compared column

flags

The flags can be set to specify comparison direction:

  • DBX_CMP_ASC - ascending order
  • DBX_CMP_DESC - descending order
and the preferred comparison type:
  • DBX_CMP_NATIVE - no type conversion
  • DBX_CMP_TEXT - compare items as strings
  • DBX_CMP_NUMBER - compare items numerically
One of the direction and one of the type constant can be combined with bitwise OR operator (|).

Zwracane wartości

Returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC.

Przykłady

Przykład #1 dbx_compare() example

<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

Zobacz też:

  • dbx_sort() - Sort a result from a dbx_query by a custom sort function

dbx_close
dbx_connect
dbx Funkcje


Open a connection/database

dbx_compare
dbx_error
dbx Funkcje
PHP Manual

dbx_connect

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_connect — Open a connection/database

Opis

object dbx_connect ( mixed $module , string $host , string $database , string $username , string $password [, int $persistent ] )

Opens a connection to a database.

Parametry

module

The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.

  • DBX_MYSQL or "mysql"
  • DBX_ODBC or "odbc"
  • DBX_PGSQL or "pgsql"
  • DBX_MSSQL or "mssql"
  • DBX_FBSQL or "fbsql"
  • DBX_SYBASECT or "sybase_ct"
  • DBX_OCI8 or "oci8"
  • DBX_SQLITE or "sqlite"

host

The SQL server host

database

The database name

username

The username

password

The password

persistent

The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

The host, database, username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.

Zwracane wartości

Returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned.

The returned object has three properties:

database
It is the name of the currently selected database.
handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close($link->handle); // dbx_close($link) would be better here
?>

module
It is used internally by dbx only, and is actually the module number mentioned above.

Rejestr zmian

Wersja | Opis
5.0.0 | Introduced DBX_SQLITE.
4.3.0 | Introduced DBX_OCI8.
4.2.0 | Introduced DBX_SYBASECT.
4.1.0 | Introduced DBX_FBSQL.

Przykłady

Przykład #1 dbx_connect() example

<?php
$link = dbx_connect(DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notatki

Informacja:

Always refer to the module-specific documentation as well.

Zobacz też:

  • dbx_close() - Close an open connection/database

dbx_compare
dbx_error
dbx Funkcje


Report the error message of the latest function call in the module

dbx_connect
dbx_escape_string
dbx Funkcje
PHP Manual

dbx_error

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_error — Report the error message of the latest function call in the module

Opis

string dbx_error ( object $link_identifier )

dbx_error() returns the last error message.

Parametry

link_identifier

The DBX link object returned by dbx_connect()

Zwracane wartości

Returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

Przykłady

Przykład #1 dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

Notatki

Informacja:

Always refer to the module-specific documentation as well.

The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

The error message for Oracle (oci8) is not implemented yet.

dbx_connect
dbx_escape_string
dbx Funkcje


Escape a string so it can safely be used in an sql-statement

dbx_error
dbx_fetch_row
dbx Funkcje
PHP Manual

dbx_escape_string

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_escape_string — Escape a string so it can safely be used in an sql-statement

Opis

string dbx_escape_string ( object $link_identifier , string $text )

Escape the given string so that it can safely be used in an sql-statement.

Parametry

link_identifier

The DBX link object returned by dbx_connect()

text

The string to escape.

Zwracane wartości

Returns the text, escaped where necessary (such as quotes, backslashes etc). On error, NULL is returned.

Przykłady

Przykład #1 dbx_escape_string() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$text = dbx_escape_string($link, "It\'s quoted and backslashed (\\).");
$result = dbx_query($link, "insert into tbl (txt) values ('" . $text . "')");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

Zobacz też:

  • dbx_query() - Send a query and fetch all results (if any)

dbx_error
dbx_fetch_row
dbx Funkcje


Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

dbx_escape_string
dbx_query
dbx Funkcje
PHP Manual

dbx_fetch_row

(PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Opis

mixed dbx_fetch_row ( object $result_identifier )

dbx_fetch_row() fetches rows from a result identifier that had the DBX_RESULT_UNBUFFERED flag set.

When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.

As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().

Parametry

result_identifier

A result set returned by dbx_query().

Zwracane wartości

Returns an object on success that contains the same information as any row would have in the dbx_query() result data property, including columns accessible by index or fieldname when the flags for dbx_query() were set that way.

Upon failure, returns 0 (e.g. when no more rows are available).

Przykłady

Przykład #1 How to handle the returned value

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

Zobacz też:

  • dbx_query() - Send a query and fetch all results (if any)

dbx_escape_string
dbx_query
dbx Funkcje


Send a query and fetch all results (if any)

dbx_fetch_row
dbx_sort
dbx Funkcje
PHP Manual

dbx_query

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_query — Send a query and fetch all results (if any)

Opis

mixed dbx_query ( object $link_identifier , string $sql_statement [, int $flags ] )

Sends a query and fetch all results.

Parametry

link_identifier

The DBX link object returned by dbx_connect()

sql_statement

SQL statement.

Data inside the query should be properly escaped.

flags

The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.

DBX_RESULT_INDEX
It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0. If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.
DBX_RESULT_INFO
It provides info about columns, such as field names and field types.
DBX_RESULT_ASSOC
It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property. Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.
DBX_RESULT_UNBUFFERED
This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row. The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.
DBX_COLNAMES_UNCHANGED
The case of the returned column names will not be changed.
DBX_COLNAMES_UPPERCASE
The case of the returned column names will be changed to uppercase.
DBX_COLNAMES_LOWERCASE
The case of the returned column names will be changed to lowercase.
Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that only the following combinations are effective:
  • DBX_RESULT_INDEX
  • DBX_RESULT_INDEX | DBX_RESULT_INFO
  • DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.

Zwracane wartości

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).

The returned object has four or five properties depending on flags:

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

<?php
$result = dbx_query($link, "SELECT id FROM table");
mysql_field_len($result->handle, 0);
?>

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

<?php
$result = dbx_query($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields
?>

info (optional)
It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

Przykład #1 lists each field's name and type

<?php
$result = dbx_query($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";
}
?>
data
This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

Przykład #2 outputs the content of data property into HTML table

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ($result->data as $row) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

Przykład #3 How to handle UNBUFFERED queries

<?php

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Rejestr zmian

Wersja | Opis
5.0.0 | Introduced DBX_RESULT_UNBUFFERED.
4.3.0 | Introduced DBX_COLNAMES_UNCHANGED, DBX_COLNAMES_UPPERCASE, and DBX_COLNAMES_LOWERCASE.

Przykłady

Przykład #4 How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if (is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types
    // then, draw a table filled with the returned field values
} else {
    exit("Query failed");
}

dbx_close($link);
?>

Notatki

Informacja:

Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

Zobacz też:

  • dbx_escape_string() - Escape a string so it can safely be used in an sql-statement
  • dbx_fetch_row() - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
  • dbx_connect() - Open a connection/database

dbx_fetch_row
dbx_sort
dbx Funkcje


Sort a result from a dbx_query by a custom sort function

dbx_query
ODBC
dbx Funkcje
PHP Manual

dbx_sort

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL dbx >= 1.1.0)

dbx_sort — Sort a result from a dbx_query by a custom sort function

Opis

bool dbx_sort ( object $result , string $user_compare_function )

Sort a result from a dbx_query() call with a custom sort function.

Parametry

result

A result set returned by dbx_query().

user_compare_function

The user-defined comparison function. It must accept two arguments and return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 dbx_sort() example

<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

Notatki

Informacja:

It is always better to use ORDER BY SQL clause instead of dbx_sort() if possible.

Zobacz też:

  • dbx_compare() - Compare two rows for sorting purposes

dbx_query
ODBC
dbx Funkcje


ODBC (Unified)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • ODBC Funkcje
    • odbc_autocommit — Toggle autocommit behaviour
    • odbc_binmode — Handling of binary column data
    • odbc_close_all — Close all ODBC connections
    • odbc_close — Close an ODBC connection
    • odbc_columnprivileges — Lists columns and associated privileges for the given table
    • odbc_columns — Lists the column names in specified tables
    • odbc_commit — Commit an ODBC transaction
    • odbc_connect — Connect to a datasource
    • odbc_cursor — Get cursorname
    • odbc_data_source — Returns information about a current connection
    • odbc_do — Alias dla odbc_exec
    • odbc_error — Get the last error code
    • odbc_errormsg — Get the last error message
    • odbc_exec — Prepare and execute an SQL statement
    • odbc_execute — Execute a prepared statement
    • odbc_fetch_array — Fetch a result row as an associative array
    • odbc_fetch_into — Fetch one result row into array
    • odbc_fetch_object — Fetch a result row as an object
    • odbc_fetch_row — Fetch a row
    • odbc_field_len — Get the length (precision) of a field
    • odbc_field_name — Get the columnname
    • odbc_field_num — Return column number
    • odbc_field_precision — Alias dla odbc_field_len
    • odbc_field_scale — Get the scale of a field
    • odbc_field_type — Datatype of a field
    • odbc_foreignkeys — Retrieves a list of foreign keys
    • odbc_free_result — Free resources associated with a result
    • odbc_gettypeinfo — Retrieves information about data types supported by the data source
    • odbc_longreadlen — Handling of LONG columns
    • odbc_next_result — Checks if multiple results are available
    • odbc_num_fields — Number of columns in a result
    • odbc_num_rows — Number of rows in a result
    • odbc_pconnect — Open a persistent database connection
    • odbc_prepare — Prepares a statement for execution
    • odbc_primarykeys — Gets the primary keys for a table
    • odbc_procedurecolumns — Retrieve information about parameters to procedures
    • odbc_procedures — Get the list of procedures stored in a specific data source
    • odbc_result_all — Print result as HTML table
    • odbc_result — Get result data
    • odbc_rollback — Rollback a transaction
    • odbc_setoption — Adjust ODBC settings
    • odbc_specialcolumns — Retrieves special columns
    • odbc_statistics — Retrieve statistics about a table
    • odbc_tableprivileges — Lists tables and the privileges associated with each table
    • odbc_tables — Get the list of table names stored in a specific data source
dbx_sort
Wstęp
Warstwy abstrakcji


Wstęp

In addition to normal ODBC support, the Unified ODBC functions in PHP allow you to access several databases that have borrowed the semantics of the ODBC API to implement their own API. Instead of maintaining multiple database drivers that were all nearly identical, these drivers have been unified into a single set of ODBC functions.

The following databases are supported by the Unified ODBC functions: » Adabas D, » IBM DB2, » iODBC, » Solid, and » Sybase SQL Anywhere.

Informacja:

With the exception of iODBC, there is no ODBC involved when connecting to the above databases. The functions that you use to speak natively to them just happen to share the same names and syntax as the ODBC functions. However, building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. More information on iODBC, is available at » www.iodbc.org with the alternative unixODBC available at » www.unixodbc.org.

ODBC
Instalacja/Konfiguracja
ODBC


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
ODBC


Wymagania

To access any of the supported databases you need to have the required libraries installed.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

--with-adabas[=DIR]

Dołącz obsługę Adabas D. DIR jest katalogiem gdzie została zainstalowana baza Adabas, domyślnie /usr/local.

--with-sapdb[=DIR]

Dołącz obsługę SAP DB. DIR jest katalogiem gdzie została zainstalowana baza, domyślnie /usr/local.

--with-solid[=DIR]

Dołącz obsługę Solid. DIR to katalog instalacji Solid, domyślnie /usr/local/solid

--with-ibm-db2[=DIR]

Dołącz obsługę IBM DB2. DIR to katalog instalcji DB2, domyślnie /home/db2inst1/sqllib.

--with-empress[=DIR]

Dołącz obsługę Empress. DIR to katalog instalacji Empress, domyślnie $EMPRESSPATH. Od PHP 4, ta opcja dotyczy tylko Empress w wersjach 8.60 i nowszych.

--with-empress-bcs[=DIR]

Dołącz obsługę "Empress Local Access". DIR to katalog instalacji Empress, domyślnie $EMPRESSPATH. Od PHP 4, ta opcja dotyczy tylko Empress w wersjach 8.60 i nowszych.

--with-birdstep[=DIR]

Dołącz obsługę Birdstep. DIR to katalog instalacji Birdstep, domyślnie /usr/local/birdstep.

--with-custom-odbc[=DIR]

Dołącza obsługę niestandardowej biblioteki ODBC. DIR wskazuje na główny katalog instalacji, domyślnie /usr/local. Upewnij się, że zdefiniowałeś CUSTOM_ODBC_LIBS i masz plik odbc.h w katalogach include. Na przykład powinieneś zdefiniować następujące opcje w QNX dla bazy danych Sybase SQL Anywhere 5.5.00, zanim uruchomisz skrypt konfiguracyjny:

   CPPFLAGS="-DODBC_QNX -DSQLANY_BUG"
   LDFLAGS=-lunix
   CUSTOM_ODBC_LIBS="-ldblib -lodbc".

--with-iodbc[=DIR]

Dołącz obsługę iODBC. DIR jest to katalog instalacji iODBC, domyślnie /usr/local.

--with-esoob[=DIR]

Dołącz obsługę Easysoft OOB. DIR to katalog instalacji OOB, domyślnie /usr/local/easysoft/oob/client.

--with-unixODBC[=DIR]

Dołącz obsługę unixODBC. DIR to katalog instalacji unixODBC, domyślnie /usr/local.

--with-openlink[=DIR]

Dołącz obsługę OpenLink ODBC. DIR to katalog instalacji OpenLink, domyślnie /usr/local. Opcja jest taka sama jak iODBC.

--with-dbmaker[=DIR]

Dołącz obsługę DBMaker. DIR to katalog instalacji DBMakera domyślnie tam, gdzie została zainstalowana najnowsza wersja DBMakera (np. /home/dbmaker/3.6).

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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Unified ODBC Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
odbc.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.default_cursortype | "3" | PHP_INI_ALL | Available as of PHP 5.3.0

Informacja: Entries marked with * are not implemented yet.

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.

odbc.default_db string

ODBC data source to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_user string

User name to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_pw string

Password to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.allow_persistent boolean

Whether to allow persistent ODBC connections.

odbc.check_persistent boolean

Check that a connection is still valid before reuse.

odbc.max_persistent integer

The maximum number of persistent ODBC connections per process.

odbc.max_links integer

The maximum number of ODBC connections per process, including persistent connections.

odbc.defaultlrl integer

Handling of LONG fields. Specifies the number of bytes returned to variables.

Jeśli użyty zostanie typ integer, wartość zostanie liczona w bajtach. Można także użyć notacji skrótowej opisanej w FAQ.
odbc.defaultbinmode integer

Handling of binary data.

odbc.default_cursortype integer

Controls the ODBC cursor model. Possible values are SQL_CURSOR_FORWARD_ONLY, SQL_CURSOR_KEYSET_DRIVEN, SQL_CURSOR_DYNAMIC and SQL_CURSOR_STATIC (default).

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines two resource types: an ODBC connection identifier and an ODBC result identifier.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

ODBC_TYPE (integer)
ODBC_BINMODE_PASSTHRU (integer)
ODBC_BINMODE_RETURN (integer)
ODBC_BINMODE_CONVERT (integer)
SQL_ODBC_CURSORS (integer)
SQL_CUR_USE_DRIVER (integer)
SQL_CUR_USE_IF_NEEDED (integer)
SQL_CUR_USE_ODBC (integer)
SQL_CONCURRENCY (integer)
SQL_CONCUR_READ_ONLY (integer)
SQL_CONCUR_LOCK (integer)
SQL_CONCUR_ROWVER (integer)
SQL_CONCUR_VALUES (integer)
SQL_CURSOR_TYPE (integer)
SQL_CURSOR_FORWARD_ONLY (integer)
SQL_CURSOR_KEYSET_DRIVEN (integer)
SQL_CURSOR_DYNAMIC (integer)
SQL_CURSOR_STATIC (integer)
SQL_KEYSET_SIZE (integer)
SQL_CHAR (integer)
SQL_VARCHAR (integer)
SQL_LONGVARCHAR (integer)
SQL_DECIMAL (integer)
SQL_NUMERIC (integer)
SQL_BIT (integer)
SQL_TINYINT (integer)
SQL_SMALLINT (integer)
SQL_INTEGER (integer)
SQL_BIGINT (integer)
SQL_REAL (integer)
SQL_FLOAT (integer)
SQL_DOUBLE (integer)
SQL_BINARY (integer)
SQL_VARBINARY (integer)
SQL_LONGVARBINARY (integer)
SQL_DATE (integer)
SQL_TIME (integer)
SQL_TIMESTAMP (integer)
SQL_TYPE_DATE (integer)
SQL_TYPE_TIME (integer)
SQL_TYPE_TIMESTAMP (integer)
SQL_BEST_ROWID (integer)
SQL_ROWVER (integer)
SQL_SCOPE_CURROW (integer)
SQL_SCOPE_TRANSACTION (integer)
SQL_SCOPE_SESSION (integer)
SQL_NO_NULLS (integer)
SQL_NULLABLE (integer)
SQL_INDEX_UNIQUE (integer)
SQL_INDEX_ALL (integer)
SQL_ENSURE (integer)
SQL_QUICK (integer)
Typy zasobów
ODBC Funkcje
ODBC


ODBC Funkcje

Spis treści

  • odbc_autocommit — Toggle autocommit behaviour
  • odbc_binmode — Handling of binary column data
  • odbc_close_all — Close all ODBC connections
  • odbc_close — Close an ODBC connection
  • odbc_columnprivileges — Lists columns and associated privileges for the given table
  • odbc_columns — Lists the column names in specified tables
  • odbc_commit — Commit an ODBC transaction
  • odbc_connect — Connect to a datasource
  • odbc_cursor — Get cursorname
  • odbc_data_source — Returns information about a current connection
  • odbc_do — Alias dla odbc_exec
  • odbc_error — Get the last error code
  • odbc_errormsg — Get the last error message
  • odbc_exec — Prepare and execute an SQL statement
  • odbc_execute — Execute a prepared statement
  • odbc_fetch_array — Fetch a result row as an associative array
  • odbc_fetch_into — Fetch one result row into array
  • odbc_fetch_object — Fetch a result row as an object
  • odbc_fetch_row — Fetch a row
  • odbc_field_len — Get the length (precision) of a field
  • odbc_field_name — Get the columnname
  • odbc_field_num — Return column number
  • odbc_field_precision — Alias dla odbc_field_len
  • odbc_field_scale — Get the scale of a field
  • odbc_field_type — Datatype of a field
  • odbc_foreignkeys — Retrieves a list of foreign keys
  • odbc_free_result — Free resources associated with a result
  • odbc_gettypeinfo — Retrieves information about data types supported by the data source
  • odbc_longreadlen — Handling of LONG columns
  • odbc_next_result — Checks if multiple results are available
  • odbc_num_fields — Number of columns in a result
  • odbc_num_rows — Number of rows in a result
  • odbc_pconnect — Open a persistent database connection
  • odbc_prepare — Prepares a statement for execution
  • odbc_primarykeys — Gets the primary keys for a table
  • odbc_procedurecolumns — Retrieve information about parameters to procedures
  • odbc_procedures — Get the list of procedures stored in a specific data source
  • odbc_result_all — Print result as HTML table
  • odbc_result — Get result data
  • odbc_rollback — Rollback a transaction
  • odbc_setoption — Adjust ODBC settings
  • odbc_specialcolumns — Retrieves special columns
  • odbc_statistics — Retrieve statistics about a table
  • odbc_tableprivileges — Lists tables and the privileges associated with each table
  • odbc_tables — Get the list of table names stored in a specific data source
Stałe predefiniowane
odbc_autocommit
ODBC


Toggle autocommit behaviour

ODBC Funkcje
odbc_binmode
ODBC Funkcje
PHP Manual

odbc_autocommit

(PHP 4, PHP 5)

odbc_autocommit — Toggle autocommit behaviour

Opis

mixed odbc_autocommit ( resource $connection_id [, bool $OnOff = false ] )

Toggles autocommit behaviour.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

OnOff

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled.

Zwracane wartości

Without the OnOff parameter, this function returns auto-commit status for connection_id. Non-zero is returned if auto-commit is on, 0 if it is off, or FALSE if an error occurs.

If OnOff is set, this function returns TRUE on success and FALSE on failure.

Zobacz też:

  • odbc_commit() - Commit an ODBC transaction
  • odbc_rollback() - Rollback a transaction

ODBC Funkcje
odbc_binmode
ODBC Funkcje


Handling of binary column data

odbc_autocommit
odbc_close_all
ODBC Funkcje
PHP Manual

odbc_binmode

(PHP 4, PHP 5)

odbc_binmode — Handling of binary column data

Opis

bool odbc_binmode ( resource $result_id , int $mode )

Enables handling of binary column data. ODBC SQL types affected are BINARY, VARBINARY, and LONGVARBINARY.

When binary SQL data is converted to character C data, each byte (8 bits) of source data is represented as two ASCII characters. These characters are the ASCII character representation of the number in its hexadecimal form. For example, a binary 00000001 is converted to "01" and a binary 11111111 is converted to "FF".

LONGVARBINARY handling
binmode | longreadlen | result
ODBC_BINMODE_PASSTHRU | 0 | passthru
ODBC_BINMODE_RETURN | 0 | passthru
ODBC_BINMODE_CONVERT | 0 | passthru
ODBC_BINMODE_PASSTHRU | 0 | passthru
ODBC_BINMODE_PASSTHRU | >0 | passthru
ODBC_BINMODE_RETURN | >0 | return as is
ODBC_BINMODE_CONVERT | >0 | return as char

If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns.

Parametry

result_id

The result identifier.

If result_id is 0, the settings apply as default for new results.

Informacja: Default for longreadlen is 4096 and mode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen().

mode

Possible values for mode are:

  • ODBC_BINMODE_PASSTHRU: Passthru BINARY data
  • ODBC_BINMODE_RETURN: Return as is
  • ODBC_BINMODE_CONVERT: Convert to char and return

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

odbc_autocommit
odbc_close_all
ODBC Funkcje


Close all ODBC connections

odbc_binmode
odbc_close
ODBC Funkcje
PHP Manual

odbc_close_all

(PHP 4, PHP 5)

odbc_close_all — Close all ODBC connections

Opis

void odbc_close_all ( void )

odbc_close_all() will close down all connections to database server(s).

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja:

This function will fail if there are open transactions on a connection. This connection will remain open in this case.

odbc_binmode
odbc_close
ODBC Funkcje


Close an ODBC connection

odbc_close_all
odbc_columnprivileges
ODBC Funkcje
PHP Manual

odbc_close

(PHP 4, PHP 5)

odbc_close — Close an ODBC connection

Opis

void odbc_close ( resource $connection_id )

Closes down the connection to the database server.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja:

This function will fail if there are open transactions on this connection. The connection will remain open in this case.

odbc_close_all
odbc_columnprivileges
ODBC Funkcje


Lists columns and associated privileges for the given table

odbc_close
odbc_columns
ODBC Funkcje
PHP Manual

odbc_columnprivileges

(PHP 4, PHP 5)

odbc_columnprivileges — Lists columns and associated privileges for the given table

Opis

resource odbc_columnprivileges ( resource $connection_id , string $qualifier , string $owner , string $table_name , string $column_name )

Lists columns and associated privileges for the given table.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

column_name

The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

The owner, table_name, and column_name accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Zwracane wartości

Returns an ODBC result identifier lub FALSE w przypadku niepowodzenia. This result identifier can be used to fetch a list of columns and associated privileges.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • GRANTOR
  • GRANTEE
  • PRIVILEGE
  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

odbc_close
odbc_columns
ODBC Funkcje


Lists the column names in specified tables

odbc_columnprivileges
odbc_commit
ODBC Funkcje
PHP Manual

odbc_columns

(PHP 4, PHP 5)

odbc_columns — Lists the column names in specified tables

Opis

resource odbc_columns ( resource $connection_id [, string $qualifier [, string $schema [, string $table_name [, string $column_name ]]]] )

Lists all columns in the requested range.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

qualifier

The qualifier.

schema

The owner.

table_name

The table name.

column_name

The column name.

The schema, table_name, and column_name accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Zwracane wartości

Returns an ODBC result identifier lub FALSE w przypadku niepowodzenia.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_SCHEM
  • TABLE_NAME
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • RADIX
  • NULLABLE
  • REMARKS

The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.

Zobacz też:

  • odbc_columnprivileges() - Lists columns and associated privileges for the given table to retrieve associated privileges

odbc_columnprivileges
odbc_commit
ODBC Funkcje


Commit an ODBC transaction

odbc_columns
odbc_connect
ODBC Funkcje
PHP Manual

odbc_commit

(PHP 4, PHP 5)

odbc_commit — Commit an ODBC transaction

Opis

bool odbc_commit ( resource $connection_id )

Commits all pending transactions on the connection.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

odbc_columns
odbc_connect
ODBC Funkcje


Connect to a datasource

odbc_commit
odbc_cursor
ODBC Funkcje
PHP Manual

odbc_connect

(PHP 4, PHP 5)

odbc_connect — Connect to a datasource

Opis

resource odbc_connect ( string $dsn , string $user , string $password [, int $cursor_type ] )

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once as long as they either use different db or different credentials.

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.

Parametry

dsn

The database source name for the connection. Alternatively, a DSN-less connection string can be used.

user

The username.

password

The password.

cursor_type

This sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.

The following constants are defined for cursortype:

  • SQL_CUR_USE_IF_NEEDED
  • SQL_CUR_USE_ODBC
  • SQL_CUR_USE_DRIVER

Zwracane wartości

Returns an ODBC connection id or 0 (FALSE) on error.

Przykłady

Przykład #1 DSN-less connections

<?php
// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);

// Microsoft Access
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

// Microsoft Excel
$excelFile = realpath('C:/ExcelData.xls');
$excelDir = dirname($excelFile);
$connection = odbc_connect("Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=$excelFile;DefaultDir=$excelDir" , '', '');
?>

Zobacz też:

  • For persistent connections: odbc_pconnect() - Open a persistent database connection

odbc_commit
odbc_cursor
ODBC Funkcje


Get cursorname

odbc_connect
odbc_data_source
ODBC Funkcje
PHP Manual

odbc_cursor

(PHP 4, PHP 5)

odbc_cursor — Get cursorname

Opis

string odbc_cursor ( resource $result_id )

Gets the cursorname for the given result_id.

Parametry

result_id

The result identifier.

Zwracane wartości

Returns the cursor name, as a string.

odbc_connect
odbc_data_source
ODBC Funkcje


Returns information about a current connection

odbc_cursor
odbc_do
ODBC Funkcje
PHP Manual

odbc_data_source

(PHP 4 >= 4.3.0, PHP 5)

odbc_data_source — Returns information about a current connection

Opis

array odbc_data_source ( resource $connection_id , int $fetch_type )

This function will return the list of available DSN (after calling it several times).

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

fetch_type

The fetch_type can be one of two constant types: SQL_FETCH_FIRST, SQL_FETCH_NEXT. Use SQL_FETCH_FIRST the first time this function is called, thereafter use the SQL_FETCH_NEXT.

Zwracane wartości

Returns FALSE on error, and an array upon success.

odbc_cursor
odbc_do
ODBC Funkcje


Alias dla odbc_exec

odbc_data_source
odbc_error
ODBC Funkcje
PHP Manual

odbc_do

(PHP 4, PHP 5)

odbc_do — Alias dla odbc_exec()

Opis

Ta funkcja jest aliasem dla: odbc_exec().

odbc_data_source
odbc_error
ODBC Funkcje


Get the last error code

odbc_do
odbc_errormsg
ODBC Funkcje
PHP Manual

odbc_error

(PHP 4 >= 4.0.5, PHP 5)

odbc_error — Get the last error code

Opis

string odbc_error ([ resource $connection_id ] )

Returns a six-digit ODBC state, or an empty string if there has been no errors.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

Zwracane wartości

If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned FALSE).

Zobacz też:

  • odbc_errormsg() - Get the last error message
  • odbc_exec() - Prepare and execute an SQL statement

odbc_do
odbc_errormsg
ODBC Funkcje


Get the last error message

odbc_error
odbc_exec
ODBC Funkcje
PHP Manual

odbc_errormsg

(PHP 4 >= 4.0.5, PHP 5)

odbc_errormsg — Get the last error message

Opis

string odbc_errormsg ([ resource $connection_id ] )

Returns a string containing the last ODBC error message, or an empty string if there has been no errors.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

Zwracane wartości

If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned FALSE).

Zobacz też:

  • odbc_error() - Get the last error code
  • odbc_exec() - Prepare and execute an SQL statement

odbc_error
odbc_exec
ODBC Funkcje


Prepare and execute an SQL statement

odbc_errormsg
odbc_execute
ODBC Funkcje
PHP Manual

odbc_exec

(PHP 4, PHP 5)

odbc_exec — Prepare and execute an SQL statement

Opis

resource odbc_exec ( resource $connection_id , string $query_string [, int $flags ] )

Sends an SQL statement to the database server.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

query_string

The SQL statement.

flags

This parameter is currently not used.

Zwracane wartości

Returns an ODBC result identifier if the SQL command was executed successfully, or FALSE on error.

Zobacz też:

  • odbc_prepare() - Prepares a statement for execution
  • odbc_execute() - Execute a prepared statement

odbc_errormsg
odbc_execute
ODBC Funkcje


Execute a prepared statement

odbc_exec
odbc_fetch_array
ODBC Funkcje
PHP Manual

odbc_execute

(PHP 4, PHP 5)

odbc_execute — Execute a prepared statement

Opis

bool odbc_execute ( resource $result_id [, array $parameters_array ] )

Executes a statement prepared with odbc_prepare().

Parametry

result_id

The result id resource, from odbc_prepare().

parameters_array

Parameters in parameter_array will be substituted for placeholders in the prepared statement in order. Elements of this array will be converted to strings by calling this function.

Any parameters in parameter_array which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.

If you wish to store a string which actually begins and ends with single quotes, you must add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter from being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with odbc_exec()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be TRUE if all three parameters to myproc are IN parameters:

<?php
$a = 1;
$b = 2;
$c = 3;
$stmt    = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, mssql for MS SQL Server, or oci8 for Oracle).

Rejestr zmian

Wersja | Opis
4.2.0 | File reading is now subject to tryb bezpieczny and open-basedir restrictions in parameters_array.
4.1.1 | Remote files are no longer supported in parameters_array.

Zobacz też:

  • odbc_prepare() - Prepares a statement for execution

odbc_exec
odbc_fetch_array
ODBC Funkcje


Fetch a result row as an associative array

odbc_execute
odbc_fetch_into
ODBC Funkcje
PHP Manual

odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_array — Fetch a result row as an associative array

Opis

array odbc_fetch_array ( resource $result [, int $rownumber ] )

Fetch an associative array from an ODBC query. See the changelog below for when this function is available.

Parametry

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Rejestr zmian

Wersja | Opis
4.3.3 | This function exists when compiled with IBM DB2 or UnixODBC support.
4.3.2 | This function exists when compiled for Windows.
4.0.2 | This function exists when compiled with DBMaker support.

Zobacz też:

  • odbc_fetch_row() - Fetch a row
  • odbc_fetch_object() - Fetch a result row as an object
  • odbc_num_rows() - Number of rows in a result

odbc_execute
odbc_fetch_into
ODBC Funkcje


Fetch one result row into array

odbc_fetch_array
odbc_fetch_object
ODBC Funkcje
PHP Manual

odbc_fetch_into

(PHP 4, PHP 5)

odbc_fetch_into — Fetch one result row into array

Opis

int odbc_fetch_into ( resource $result_id , array &$result_array [, int $rownumber ] )

Fetch one result row into array.

Parametry

result_id

The result resource.

result_array

The result array that can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.

rownumber

The row number.

Zwracane wartości

Returns the number of columns in the result; FALSE on error.

Rejestr zmian

Wersja | Opis
4.2.0 | The result_array and rownumber parameters have been swapped. This allows the rownumber to be a constant again.
4.0.6 | The rownumber can no longer be passed in as a constant, but rather as a variable. This again changed in 4.2.0.
4.0.5 | The result_array parameter no longer needs to be passed in by reference.

Przykłady

Przykład #1 odbc_fetch_into() examples

<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>

or

<?php
$rc = odbc_fetch_into($res_id, $my_array, 2);
?>

odbc_fetch_array
odbc_fetch_object
ODBC Funkcje


Fetch a result row as an object

odbc_fetch_into
odbc_fetch_row
ODBC Funkcje
PHP Manual

odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5)

odbc_fetch_object — Fetch a result row as an object

Opis

object odbc_fetch_object ( resource $result [, int $rownumber ] )

Fetch an object from an ODBC query. See the changelog below for when this function is available.

Parametry

result

The result resource from odbc_exec().

rownumber

Optionally choose which row number to retrieve.

Zwracane wartości

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

Rejestr zmian

Wersja | Opis
4.3.3 | This function exists when compiled with IBM DB2 or UnixODBC support.
4.3.2 | This function exists when compiled for Windows.
4.0.2 | This function exists when compiled with DBMaker support.

Zobacz też:

  • odbc_fetch_row() - Fetch a row
  • odbc_fetch_array() - Fetch a result row as an associative array
  • odbc_num_rows() - Number of rows in a result

odbc_fetch_into
odbc_fetch_row
ODBC Funkcje


Fetch a row

odbc_fetch_object
odbc_field_len
ODBC Funkcje
PHP Manual

odbc_fetch_row

(PHP 4, PHP 5)

odbc_fetch_row — Fetch a row

Opis

bool odbc_fetch_row ( resource $result_id [, int $row_number ] )

Fetches a row of the data that was returned by odbc_do() or odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

Parametry

result_id

The result identifier.

row_number

If row_number is not specified, odbc_fetch_row() will try to fetch the next row in the result set. Calls to odbc_fetch_row() with and without row_number can be mixed.

To step through the result more than once, you can call odbc_fetch_row() with row_number 1, and then continue doing odbc_fetch_row() without row_number to review the result. If a driver doesn't support fetching rows by number, the row_number parameter is ignored.

Zwracane wartości

Returns TRUE if there was a row, FALSE otherwise.

odbc_fetch_object
odbc_field_len
ODBC Funkcje


Get the length (precision) of a field

odbc_fetch_row
odbc_field_name
ODBC Funkcje
PHP Manual

odbc_field_len

(PHP 4, PHP 5)

odbc_field_len — Get the length (precision) of a field

Opis

int odbc_field_len ( resource $result_id , int $field_number )

Gets the length of the field referenced by number in the given result identifier.

Parametry

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Zwracane wartości

Returns the field name as a string, or FALSE on error.

Zobacz też:

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number

odbc_fetch_row
odbc_field_name
ODBC Funkcje


Get the columnname

odbc_field_len
odbc_field_num
ODBC Funkcje
PHP Manual

odbc_field_name

(PHP 4, PHP 5)

odbc_field_name — Get the columnname

Opis

string odbc_field_name ( resource $result_id , int $field_number )

Gets the name of the field occupying the given column number in the given result identifier.

Parametry

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Zwracane wartości

Returns the field name as a string, or FALSE on error.

odbc_field_len
odbc_field_num
ODBC Funkcje


Return column number

odbc_field_name
odbc_field_precision
ODBC Funkcje
PHP Manual

odbc_field_num

(PHP 4, PHP 5)

odbc_field_num — Return column number

Opis

int odbc_field_num ( resource $result_id , string $field_name )

Gets the number of the column slot that corresponds to the named field in the given result identifier.

Parametry

result_id

The result identifier.

field_name

The field name.

Zwracane wartości

Returns the field number as a integer, or FALSE on error. Field numbering starts at 1.

odbc_field_name
odbc_field_precision
ODBC Funkcje


Alias dla odbc_field_len

odbc_field_num
odbc_field_scale
ODBC Funkcje
PHP Manual

odbc_field_precision

(PHP 4, PHP 5)

odbc_field_precision — Alias dla odbc_field_len()

Opis

Ta funkcja jest aliasem dla: odbc_field_len().

Zobacz też:

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number.

odbc_field_num
odbc_field_scale
ODBC Funkcje


Get the scale of a field

odbc_field_precision
odbc_field_type
ODBC Funkcje
PHP Manual

odbc_field_scale

(PHP 4, PHP 5)

odbc_field_scale — Get the scale of a field

Opis

int odbc_field_scale ( resource $result_id , int $field_number )

Gets the scale of the field referenced by number in the given result identifier.

Parametry

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Zwracane wartości

Returns the field scale as a integer, or FALSE on error.

odbc_field_precision
odbc_field_type
ODBC Funkcje


Datatype of a field

odbc_field_scale
odbc_foreignkeys
ODBC Funkcje
PHP Manual

odbc_field_type

(PHP 4, PHP 5)

odbc_field_type — Datatype of a field

Opis

string odbc_field_type ( resource $result_id , int $field_number )

Gets the SQL type of the field referenced by number in the given result identifier.

Parametry

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Zwracane wartości

Returns the field type as a string, or FALSE on error.

odbc_field_scale
odbc_foreignkeys
ODBC Funkcje


Retrieves a list of foreign keys

odbc_field_type
odbc_free_result
ODBC Funkcje
PHP Manual

odbc_foreignkeys

(PHP 4, PHP 5)

odbc_foreignkeys — Retrieves a list of foreign keys

Opis

resource odbc_foreignkeys ( resource $connection_id , string $pk_qualifier , string $pk_owner , string $pk_table , string $fk_qualifier , string $fk_owner , string $fk_table )

Retrieves a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

pk_qualifier

The primary key qualifier.

pk_owner

The primary key owner.

pk_table

The primary key table.

fk_qualifier

The foreign key qualifier.

fk_owner

The foreign key owner.

fk_table

The foreign key table.

Zwracane wartości

Returns an ODBC result identifier lub FALSE w przypadku niepowodzenia.

The result set has the following columns:

  • PKTABLE_QUALIFIER
  • PKTABLE_OWNER
  • PKTABLE_NAME
  • PKCOLUMN_NAME
  • FKTABLE_QUALIFIER
  • FKTABLE_OWNER
  • FKTABLE_NAME
  • FKCOLUMN_NAME
  • KEY_SEQ
  • UPDATE_RULE
  • DELETE_RULE
  • FK_NAME
  • PK_NAME

If pk_table contains a table name, odbc_foreignkeys() returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it.

If fk_table contains a table name, odbc_foreignkeys() returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer.

If both pk_table and fk_table contain table names, odbc_foreignkeys() returns the foreign keys in the table specified in fk_table that refer to the primary key of the table specified in pk_table. This should be one key at most.

odbc_field_type
odbc_free_result
ODBC Funkcje


Free resources associated with a result

odbc_foreignkeys
odbc_gettypeinfo
ODBC Funkcje
PHP Manual

odbc_free_result

(PHP 4, PHP 5)

odbc_free_result — Free resources associated with a result

Opis

bool odbc_free_result ( resource $result_id )

Free resources associated with a result.

odbc_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script is finished.

Parametry

result_id

The result identifier.

Zwracane wartości

Always returns TRUE.

Notatki

Informacja:

If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.

odbc_foreignkeys
odbc_gettypeinfo
ODBC Funkcje


Retrieves information about data types supported by the data source

odbc_free_result
odbc_longreadlen
ODBC Funkcje
PHP Manual

odbc_gettypeinfo

(PHP 4, PHP 5)

odbc_gettypeinfo — Retrieves information about data types supported by the data source

Opis

resource odbc_gettypeinfo ( resource $connection_id [, int $data_type ] )

Retrieves information about data types supported by the data source.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

data_type

The data type, which can be used to restrict the information to a single data type.

Zwracane wartości

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TYPE_NAME
  • DATA_TYPE
  • PRECISION
  • LITERAL_PREFIX
  • LITERAL_SUFFIX
  • CREATE_PARAMS
  • NULLABLE
  • CASE_SENSITIVE
  • SEARCHABLE
  • UNSIGNED_ATTRIBUTE
  • MONEY
  • AUTO_INCREMENT
  • LOCAL_TYPE_NAME
  • MINIMUM_SCALE
  • MAXIMUM_SCALE

The result set is ordered by DATA_TYPE and TYPE_NAME.

odbc_free_result
odbc_longreadlen
ODBC Funkcje


Handling of LONG columns

odbc_gettypeinfo
odbc_next_result
ODBC Funkcje
PHP Manual

odbc_longreadlen

(PHP 4, PHP 5)

odbc_longreadlen — Handling of LONG columns

Opis

bool odbc_longreadlen ( resource $result_id , int $length )

Enables handling of LONG and LONGVARBINARY columns.

Parametry

result_id

The result identifier.

length

The number of bytes returned to PHP is controlled by the parameter length. If it is set to 0, Long column data is passed through to the client.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

Handling of LONGVARBINARY columns is also affected by odbc_binmode().

odbc_gettypeinfo
odbc_next_result
ODBC Funkcje


Checks if multiple results are available

odbc_longreadlen
odbc_num_fields
ODBC Funkcje
PHP Manual

odbc_next_result

(PHP 4 >= 4.0.5, PHP 5)

odbc_next_result — Checks if multiple results are available

Opis

bool odbc_next_result ( resource $result_id )

Checks if there are more result sets available as well as allowing access to the next result set via odbc_fetch_array(), odbc_fetch_row(), odbc_result(), etc.

Parametry

result_id

The result identifier.

Zwracane wartości

Returns TRUE if there are more result sets, FALSE otherwise.

Przykłady

Przykład #1 odbc_next_result()

<?php
$r_Connection = odbc_connect($dsn, $username, $password);

$s_SQL = <<<END_SQL
SELECT 'A'
SELECT 'B'
SELECT 'C'
END_SQL;

$r_Results = odbc_exec($r_Connection, $s_SQL);

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump first result set";
var_dump($a_Row1, $a_Row2);

echo "Get second results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump second result set ";
var_dump($a_Row1, $a_Row2);

echo "Get third results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump third result set ";
var_dump($a_Row1, $a_Row2);

echo "Try for a fourth result set ";
var_dump(odbc_next_result($r_Results));
?>

Powyższy przykład wyświetli:

Dump first result set array(1) {
  ["A"]=>
  string(1) "A"
}
bool(false)
Get second results set bool(true)
Dump second result set array(1) {
  ["B"]=>
  string(1) "B"
}
bool(false)
Get third results set bool(true)
Dump third result set array(1) {
  ["C"]=>
  string(1) "C"
}
bool(false)
Try for a fourth result set bool(false)

odbc_longreadlen
odbc_num_fields
ODBC Funkcje


Number of columns in a result

odbc_next_result
odbc_num_rows
ODBC Funkcje
PHP Manual

odbc_num_fields

(PHP 4, PHP 5)

odbc_num_fields — Number of columns in a result

Opis

int odbc_num_fields ( resource $result_id )

Gets the number of fields (columns) in an ODBC result.

Parametry

result_id

The result identifier returned by odbc_exec().

Zwracane wartości

Returns the number of fields, or -1 on error.

odbc_next_result
odbc_num_rows
ODBC Funkcje


Number of rows in a result

odbc_num_fields
odbc_pconnect
ODBC Funkcje
PHP Manual

odbc_num_rows

(PHP 4, PHP 5)

odbc_num_rows — Number of rows in a result

Opis

int odbc_num_rows ( resource $result_id )

Gets the number of rows in a result. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.

Parametry

result_id

The result identifier returned by odbc_exec().

Zwracane wartości

Returns the number of rows in an ODBC result. This function will return -1 on error.

Notatki

Informacja:

Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

odbc_num_fields
odbc_pconnect
ODBC Funkcje


Open a persistent database connection

odbc_num_rows
odbc_prepare
ODBC Funkcje
PHP Manual

odbc_pconnect

(PHP 4, PHP 5)

odbc_pconnect — Open a persistent database connection

Opis

resource odbc_pconnect ( string $dsn , string $user , string $password [, int $cursor_type ] )

Opens a persistent database connection.

This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same dsn, user, password combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.

Parametry

See odbc_connect() for details.

Zwracane wartości

Returns an ODBC connection id or 0 (FALSE) on error.

Notatki

Informacja: Persistent connections have no effect if PHP is used as a CGI program.

Zobacz też:

  • odbc_connect() - Connect to a datasource
  • Persistent Database Connections

odbc_num_rows
odbc_prepare
ODBC Funkcje


Prepares a statement for execution

odbc_pconnect
odbc_primarykeys
ODBC Funkcje
PHP Manual

odbc_prepare

(PHP 4, PHP 5)

odbc_prepare — Prepares a statement for execution

Opis

resource odbc_prepare ( resource $connection_id , string $query_string )

Prepares a statement for execution. The result identifier can be used later to execute the statement with odbc_execute().

Some databases (such as IBM DB2, MS SQL Server, and Oracle) support stored procedures that accept parameters of type IN, INOUT, and OUT as defined by the ODBC specification. However, the Unified ODBC driver currently only supports parameters of type IN to stored procedures.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

query_string

The query string statement being prepared.

Zwracane wartości

Returns an ODBC result identifier if the SQL command was prepared successfully. Returns FALSE on error.

Przykłady

Przykład #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be TRUE if all three parameters to myproc are IN parameters:

<?php
$a = 1;
$b = 2;
$c = 3;
$stmt    = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, mssql for MS SQL Server, or oci8 for Oracle).

Zobacz też:

  • odbc_execute() - Execute a prepared statement

odbc_pconnect
odbc_primarykeys
ODBC Funkcje


Gets the primary keys for a table

odbc_prepare
odbc_procedurecolumns
ODBC Funkcje
PHP Manual

odbc_primarykeys

(PHP 4, PHP 5)

odbc_primarykeys — Gets the primary keys for a table

Opis

resource odbc_primarykeys ( resource $connection_id , string $qualifier , string $owner , string $table )

Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

qualifier

owner

table

Zwracane wartości

Returns an ODBC result identifier lub FALSE w przypadku niepowodzenia.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • COLUMN_NAME
  • KEY_SEQ
  • PK_NAME

odbc_prepare
odbc_procedurecolumns
ODBC Funkcje


Retrieve information about parameters to procedures

odbc_primarykeys
odbc_procedures
ODBC Funkcje
PHP Manual

odbc_procedurecolumns

(PHP 4, PHP 5)

odbc_procedurecolumns — Retrieve information about parameters to procedures

Opis

resource odbc_procedurecolumns ( resource $connection_id )
resource odbc_procedurecolumns ( resource $connection_id , string $qualifier , string $owner , string $proc , string $column )

Retrieve information about parameters to procedures.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

qualifier

The qualifier.

owner

The owner. Ten parametr przyjmuje również następujące wzorce wyszukiwania: "%" - dopasowanie oznacza brak znaków lub dowolną ilość znaków, oraz "_" - dopasowanie oznacza jeden znak.

proc

The proc. Ten parametr przyjmuje również następujące wzorce wyszukiwania: "%" - dopasowanie oznacza brak znaków lub dowolną ilość znaków, oraz "_" - dopasowanie oznacza jeden znak.

column

The column. Ten parametr przyjmuje również następujące wzorce wyszukiwania: "%" - dopasowanie oznacza brak znaków lub dowolną ilość znaków, oraz "_" - dopasowanie oznacza jeden znak.

Zwracane wartości

Returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Returns an ODBC result identifier lub FALSE w przypadku niepowodzenia.

The result set has the following columns:

  • PROCEDURE_QUALIFIER
  • PROCEDURE_OWNER
  • PROCEDURE_NAME
  • COLUMN_NAME
  • COLUMN_TYPE
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • RADIX
  • NULLABLE
  • REMARKS

The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME and COLUMN_TYPE.

odbc_primarykeys
odbc_procedures
ODBC Funkcje


Get the list of procedures stored in a specific data source

odbc_procedurecolumns
odbc_result_all
ODBC Funkcje
PHP Manual

odbc_procedures

(PHP 4, PHP 5)

odbc_procedures — Get the list of procedures stored in a specific data source

Opis

resource odbc_procedures ( resource $connection_id )
resource odbc_procedures ( resource $connection_id , string $qualifier , string $owner , string $name )

Lists all procedures in the requested range.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

qualifier

The qualifier.

owner

The owner. Ten parametr przyjmuje również następujące wzorce wyszukiwania: "%" - dopasowanie oznacza brak znaków lub dowolną ilość znaków, oraz "_" - dopasowanie oznacza jeden znak.

name

The name. Ten parametr przyjmuje również następujące wzorce wyszukiwania: "%" - dopasowanie oznacza brak znaków lub dowolną ilość znaków, oraz "_" - dopasowanie oznacza jeden znak.

Zwracane wartości

Returns an ODBC result identifier containing the information lub FALSE w przypadku niepowodzenia.

The result set has the following columns:

  • PROCEDURE_QUALIFIER
  • PROCEDURE_OWNER
  • PROCEDURE_NAME
  • NUM_INPUT_PARAMS
  • NUM_OUTPUT_PARAMS
  • NUM_RESULT_SETS
  • REMARKS
  • PROCEDURE_TYPE

odbc_procedurecolumns
odbc_result_all
ODBC Funkcje


Print result as HTML table

odbc_procedures
odbc_result
ODBC Funkcje
PHP Manual

odbc_result_all

(PHP 4, PHP 5)

odbc_result_all — Print result as HTML table

Opis

int odbc_result_all ( resource $result_id [, string $format ] )

Prints all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format.

Parametry

result_id

The result identifier.

format

Additional overall table formatting.

Zwracane wartości

Returns the number of rows in the result or FALSE on error.

odbc_procedures
odbc_result
ODBC Funkcje


Get result data

odbc_result_all
odbc_rollback
ODBC Funkcje
PHP Manual

odbc_result

(PHP 4, PHP 5)

odbc_result — Get result data

Opis

mixed odbc_result ( resource $result_id , mixed $field )

Get result data

Parametry

result_id

The ODBC resource.

field

The field name being retrieved. It can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field.

Zwracane wartości

Returns the string contents of the field, FALSE on error, NULL for NULL data, or TRUE for binary data.

Przykłady

The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.

Przykład #1 odbc_result() examples

<?php
$item_3   = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");
?>

Notatki

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

odbc_result_all
odbc_rollback
ODBC Funkcje


Rollback a transaction

odbc_result
odbc_setoption
ODBC Funkcje
PHP Manual

odbc_rollback

(PHP 4, PHP 5)

odbc_rollback — Rollback a transaction

Opis

bool odbc_rollback ( resource $connection_id )

Rolls back all pending statements on the connection.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

odbc_result
odbc_setoption
ODBC Funkcje


Adjust ODBC settings

odbc_rollback
odbc_specialcolumns
ODBC Funkcje
PHP Manual

odbc_setoption

(PHP 4, PHP 5)

odbc_setoption — Adjust ODBC settings

Opis

bool odbc_setoption ( resource $id , int $function , int $option , int $param )

This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work around to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options.

Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters.

Parametry

id

Is a connection id or result id on which to change the settings. For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id.

function

Is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().

option

The option to set.

param

The value for the given option.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 odbc_setoption() examples

<?php
// 1. Option 102 of SQLSetConnectOption() is SQL_AUTOCOMMIT.
//    Value 1 of SQL_AUTOCOMMIT is SQL_AUTOCOMMIT_ON.
//    This example has the same effect as
//    odbc_autocommit($conn, true);

odbc_setoption($conn, 1, 102, 1);

// 2. Option 0 of SQLSetStmtOption() is SQL_QUERY_TIMEOUT.
//    This example sets the query to timeout after 30 seconds.

$result = odbc_prepare($conn, $sql);
odbc_setoption($result, 2, 0, 30);
odbc_execute($result);
?>

odbc_rollback
odbc_specialcolumns
ODBC Funkcje


Retrieves special columns

odbc_setoption
odbc_statistics
ODBC Funkcje
PHP Manual

odbc_specialcolumns

(PHP 4, PHP 5)

odbc_specialcolumns — Retrieves special columns

Opis

resource odbc_specialcolumns ( resource $connection_id , int $type , string $qualifier , string $owner , string $table , int $scope , int $nullable )

Retrieves either the optimal set of columns that uniquely identifies a row in the table, or columns that are automatically updated when any value in the row is updated by a transaction.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

type
When the type argument is SQL_BEST_ROWID, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table. When the type argument is SQL_ROWVER, odbc_specialcolumns() returns the column or columns in the specified table, if any, that are automatically updated by the data source when any value in the row is updated by any transaction.
qualifier

The qualifier.

owner

The owner.

table

The table.

scope

The scope, which orders the result set.

nullable

The nullable option.

Zwracane wartości

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • SCOPE
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • PSEUDO_COLUMN

odbc_setoption
odbc_statistics
ODBC Funkcje


Retrieve statistics about a table

odbc_specialcolumns
odbc_tableprivileges
ODBC Funkcje
PHP Manual

odbc_statistics

(PHP 4, PHP 5)

odbc_statistics — Retrieve statistics about a table

Opis

resource odbc_statistics ( resource $connection_id , string $qualifier , string $owner , string $table_name , int $unique , int $accuracy )

Get statistics about a table and its indexes.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

unique

The unique attribute.

accuracy

The accuracy.

Zwracane wartości

Returns an ODBC result identifier lub FALSE w przypadku niepowodzenia.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • NON_UNIQUE
  • INDEX_QUALIFIER
  • INDEX_NAME
  • TYPE
  • SEQ_IN_INDEX
  • COLUMN_NAME
  • COLLATION
  • CARDINALITY
  • PAGES
  • FILTER_CONDITION

The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and SEQ_IN_INDEX.

odbc_specialcolumns
odbc_tableprivileges
ODBC Funkcje


Lists tables and the privileges associated with each table

odbc_statistics
odbc_tables
ODBC Funkcje
PHP Manual

odbc_tableprivileges

(PHP 4, PHP 5)

odbc_tableprivileges — Lists tables and the privileges associated with each table

Opis

resource odbc_tableprivileges ( resource $connection_id , string $qualifier , string $owner , string $name )

Lists tables in the requested range and the privileges associated with each table.

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

qualifier

The qualifier.

owner

The owner. Accepts the following search patterns: ('%' to match zero or more characters and '_' to match a single character)

name

The name. Accepts the following search patterns: ('%' to match zero or more characters and '_' to match a single character)

Zwracane wartości

An ODBC result identifier lub FALSE w przypadku niepowodzenia.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • GRANTOR
  • GRANTEE
  • PRIVILEGE
  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

odbc_statistics
odbc_tables
ODBC Funkcje


Get the list of table names stored in a specific data source

odbc_tableprivileges
PDO
ODBC Funkcje
PHP Manual

odbc_tables

(PHP 4, PHP 5)

odbc_tables — Get the list of table names stored in a specific data source

Opis

resource odbc_tables ( resource $connection_id [, string $qualifier [, string $owner [, string $name [, string $types ]]]] )

Lists all tables in the requested range.

To support enumeration of qualifiers, owners, and table types, the following special semantics for the qualifier, owner, name, and table_type are available:

  • If qualifier is a single percent character (%) and owner and name are empty strings, then the result set contains a list of valid qualifiers for the data source. (All columns except the TABLE_QUALIFIER column contain NULLs.)
  • If owner is a single percent character (%) and qualifier and name are empty strings, then the result set contains a list of valid owners for the data source. (All columns except the TABLE_OWNER column contain NULLs.)
  • If table_type is a single percent character (%) and qualifier, owner and name are empty strings, then the result set contains a list of valid table types for the data source. (All columns except the TABLE_TYPE column contain NULLs.)

Parametry

connection_id

Identyfikator połączenia ODBC. Zobacz opis funkcji odbc_connect() aby poznać szczegóły.

qualifier

The qualifier.

owner

The owner. Accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

name

The name. Accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

types

If table_type is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (') or unquoted. For example, "'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not support a specified table type, odbc_tables() does not return any results for that type.

Zwracane wartości

Returns an ODBC result identifier containing the information lub FALSE w przypadku niepowodzenia.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • TABLE_TYPE
  • REMARKS

The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

Zobacz też:

  • odbc_tableprivileges() - Lists tables and the privileges associated with each table

odbc_tableprivileges
PDO
ODBC Funkcje


PHP Data Objects

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Connections and Connection management
  • Transactions and auto-commit
  • Prepared statements and stored procedures
  • Errors and error handling
  • Large Objects (LOBs)
  • PDO — The PDO class
    • PDO::beginTransaction — Initiates a transaction
    • PDO::commit — Commits a transaction
    • PDO::__construct — Creates a PDO instance representing a connection to a database
    • PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
    • PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
    • PDO::exec — Execute an SQL statement and return the number of affected rows
    • PDO::getAttribute — Retrieve a database connection attribute
    • PDO::getAvailableDrivers — Return an array of available PDO drivers
    • PDO::inTransaction — Checks if inside a transaction
    • PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
    • PDO::prepare — Prepares a statement for execution and returns a statement object
    • PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object
    • PDO::quote — Quotes a string for use in a query.
    • PDO::rollBack — Rolls back a transaction
    • PDO::setAttribute — Set an attribute
  • PDOStatement — The PDOStatement class
    • PDOStatement::bindColumn — Bind a column to a PHP variable
    • PDOStatement::bindParam — Binds a parameter to the specified variable name
    • PDOStatement::bindValue — Binds a value to a parameter
    • PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again.
    • PDOStatement::columnCount — Returns the number of columns in the result set
    • PDOStatement::debugDumpParams — Dump an SQL prepared command
    • PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle
    • PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle
    • PDOStatement::execute — Executes a prepared statement
    • PDOStatement::fetch — Fetches the next row from a result set
    • PDOStatement::fetchAll — Returns an array containing all of the result set rows
    • PDOStatement::fetchColumn — Returns a single column from the next row of a result set
    • PDOStatement::fetchObject — Fetches the next row and returns it as an object.
    • PDOStatement::getAttribute — Retrieve a statement attribute
    • PDOStatement::getColumnMeta — Returns metadata for a column in a result set
    • PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle
    • PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement
    • PDOStatement::setAttribute — Set a statement attribute
    • PDOStatement::setFetchMode — Set the default fetch mode for this statement
  • PDOException — The PDOException class
  • PDO Drivers
    • CUBRID (PDO) — CUBRID Functions (PDO_CUBRID)
    • MS SQL Server (PDO) — Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
    • Firebird/Interbase (PDO) — Firebird/Interbase Functions (PDO_FIREBIRD)
    • IBM (PDO) — IBM Functions (PDO_IBM)
    • Informix (PDO) — Informix Functions (PDO_INFORMIX)
    • MySQL (PDO) — MySQL Functions (PDO_MYSQL)
    • MS SQL Server (PDO) — Microsoft SQL Server Functions (PDO_SQLSRV)
    • Oracle (PDO) — Oracle Functions (PDO_OCI)
    • ODBC and DB2 (PDO) — ODBC and DB2 Functions (PDO_ODBC)
    • PostgreSQL (PDO) — PostgreSQL Functions (PDO_PGSQL)
    • SQLite (PDO) — SQLite Functions (PDO_SQLITE)
    • 4D (PDO) — 4D Functions (PDO_4D)
odbc_tables
Wstęp
Warstwy abstrakcji


Wstęp

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.

PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.

PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.

PDO
Instalacja/Konfiguracja
PDO


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
PDO


Instalacja

Installing PDO on Unix systems

  1. PDO and the PDO_SQLITE driver is enabled by default as of PHP 5.1.0. You may need to enable the PDO driver for your database of choice; consult the documentation for database-specific PDO drivers to find out more about that. Note: When building PDO as a shared extension (not recommended) then all PDO drivers must be loaded after PDO itself.

  2. When installing PDO as a shared module, the php.ini file needs to be updated so that the PDO extension will be loaded automatically when PHP runs. You will also need to enable any database specific drivers there too; make sure that they are listed after the pdo.so line, as PDO must be initialized before the database-specific extensions can be loaded. If you built PDO and the database-specific extensions statically, you can skip this step.

    extension=pdo.so

Windows users

  1. PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file:

    extension=php_pdo.dll

    Informacja:

    This step is not necessary for PHP 5.3 and above, as a DLL is no longer required for PDO.

  2. Next, choose the other database-specific DLL files and either use dl() to load them at runtime, or enable them in php.ini below php_pdo.dll. For example:

    extension=php_pdo.dll
extension=php_pdo_firebird.dll
extension=php_pdo_informix.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_oci8.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll

    These DLLs should exist in the system's extension_dir.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

PDO Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
pdo.dsn.* |  | php.ini only |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

pdo.dsn.* string

Defines DSN alias. See PDO::__construct() for thorough explanation.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

Ostrzeżenie

PDO uses class constants since PHP 5.1. Prior releases use global constants in the form PDO_PARAM_BOOL.

PDO::PARAM_BOOL (integer)
Represents a boolean data type.
PDO::PARAM_NULL (integer)
Represents the SQL NULL data type.
PDO::PARAM_INT (integer)
Represents the SQL INTEGER data type.
PDO::PARAM_STR (integer)
Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_LOB (integer)
Represents the SQL large object data type.
PDO::PARAM_STMT (integer)
Represents a recordset type. Not currently supported by any drivers.
PDO::PARAM_INPUT_OUTPUT (integer)
Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.
PDO::FETCH_LAZY (integer)
Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set. PDO::FETCH_LAZY creates the object variable names as they are accessed.
PDO::FETCH_ASSOC (integer)
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.
PDO::FETCH_NAMED (integer)
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.
PDO::FETCH_NUM (integer)
Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_BOTH (integer)
Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_OBJ (integer)
Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.
PDO::FETCH_BOUND (integer)
Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.
PDO::FETCH_COLUMN (integer)
Specifies that the fetch method shall return only a single requested column from the next row in the result set.
PDO::FETCH_CLASS (integer)
Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.

Informacja: The magic __set() method is called if the property doesn't exist in the requested class

PDO::FETCH_INTO (integer)
Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.
PDO::FETCH_FUNC (integer)
PDO::FETCH_GROUP (integer)
PDO::FETCH_UNIQUE (integer)
PDO::FETCH_KEY_PAIR (integer)
Fetch a two-column result into an array where the first column is a key and the second column is the value. Available since PHP 5.2.3.
PDO::FETCH_CLASSTYPE (integer)
Determine the class name from the value of first column.
PDO::FETCH_SERIALIZE (integer)
As PDO::FETCH_INTO but object is provided as a serialized string. Available since PHP 5.1.0.
PDO::FETCH_PROPS_LATE (integer)
Available since PHP 5.2.0
PDO::ATTR_AUTOCOMMIT (integer)
If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.
PDO::ATTR_PREFETCH (integer)
Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.
PDO::ATTR_TIMEOUT (integer)
Sets the timeout value in seconds for communications with the database.
PDO::ATTR_ERRMODE (integer)
See the Errors and error handling section for more information about this attribute.
PDO::ATTR_SERVER_VERSION (integer)
This is a read only attribute; it will return information about the version of the database server to which PDO is connected.
PDO::ATTR_CLIENT_VERSION (integer)
This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.
PDO::ATTR_SERVER_INFO (integer)
This is a read only attribute; it will return some meta information about the database server to which PDO is connected.
PDO::ATTR_CONNECTION_STATUS (integer)
PDO::ATTR_CASE (integer)
Force column names to a specific case specified by the PDO::CASE_* constants.
PDO::ATTR_CURSOR_NAME (integer)
Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
PDO::ATTR_CURSOR (integer)
Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick with PDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
PDO::ATTR_DRIVER_NAME (string)
Returns the name of the driver.

Przykład #1 using PDO::ATTR_DRIVER_NAME

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
  echo "Running on mysql; doing something mysql specific here\n";
}
?>

PDO::ATTR_ORACLE_NULLS (integer)
Convert empty strings to SQL NULL values on data fetches.
PDO::ATTR_PERSISTENT (integer)
Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.
PDO::ATTR_STATEMENT_CLASS (integer)
PDO::ATTR_FETCH_CATALOG_NAMES (integer)
Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
PDO::ATTR_FETCH_TABLE_NAMES (integer)
Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
PDO::ATTR_STRINGIFY_FETCHES (integer)
PDO::ATTR_MAX_COLUMN_LEN (integer)
PDO::ATTR_DEFAULT_FETCH_MODE (integer)
Available since PHP 5.2.0
PDO::ATTR_EMULATE_PREPARES (integer)
Available since PHP 5.1.3.
PDO::ERRMODE_SILENT (integer)
Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_WARNING (integer)
Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_EXCEPTION (integer)
Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.
PDO::CASE_NATURAL (integer)
Leave column names as returned by the database driver.
PDO::CASE_LOWER (integer)
Force column names to lower case.
PDO::CASE_UPPER (integer)
Force column names to upper case.
PDO::NULL_NATURAL (integer)
PDO::NULL_EMPTY_STRING (integer)
PDO::NULL_TO_STRING (integer)
PDO::FETCH_ORI_NEXT (integer)
Fetch the next row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_PRIOR (integer)
Fetch the previous row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_FIRST (integer)
Fetch the first row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_LAST (integer)
Fetch the last row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_ABS (integer)
Fetch the requested row by row number from the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_REL (integer)
Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.
PDO::CURSOR_FWDONLY (integer)
Create a PDOStatement object with a forward-only cursor. This is the default cursor choice, as it is the fastest and most common data access pattern in PHP.
PDO::CURSOR_SCROLL (integer)
Create a PDOStatement object with a scrollable cursor. Pass the PDO::FETCH_ORI_* constants to control the rows fetched from the result set.
PDO::ERR_NONE (string)
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
PDO::PARAM_EVT_ALLOC (integer)
Allocation event
PDO::PARAM_EVT_FREE (integer)
Deallocation event
PDO::PARAM_EVT_EXEC_PRE (integer)
Event triggered prior to execution of a prepared statement.
PDO::PARAM_EVT_EXEC_POST (integer)
Event triggered subsequent to execution of a prepared statement.
PDO::PARAM_EVT_FETCH_PRE (integer)
Event triggered prior to fetching a result from a resultset.
PDO::PARAM_EVT_FETCH_POST (integer)
Event triggered subsequent to fetching a result from a resultset.
PDO::PARAM_EVT_NORMALIZE (integer)
Event triggered during bound parameter registration allowing the driver to normalize the parameter name.
Typy zasobów
Connections and Connection management
PDO


Connections and Connection management

Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).

Przykład #1 Connecting to MySQL

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>

If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().

Przykład #2 Handling connection errors

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    foreach($dbh->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

Ostrzeżenie

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler().

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Przykład #3 Closing a connection

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here

// and now we're done; close it
$dbh = null;
?>

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

Przykład #4 Persistent connections

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

Informacja:

If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.

Informacja:

If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.

Stałe predefiniowane
Transactions and auto-commit
PDO


Transactions and auto-commit

Now that you're connected via PDO, you must understand how PDO manages transactions before you start issuing queries. If you've never encountered transactions before, they offer 4 major features: Atomicity, Consistency, Isolation and Durability (ACID). In layman's terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed. Transactional work can also be automatically undone at your request (provided you haven't already committed it), which makes error handling in your scripts easier.

Transactions are typically implemented by "saving-up" your batch of changes to be applied all at once; this has the nice side effect of drastically improving the efficiency of those updates. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to reap that benefit).

Unfortunately, not every database supports transactions, so PDO needs to run in what is known as "auto-commit" mode when you first open the connection. Auto-commit mode means that every query that you run has its own implicit transaction, if the database supports it, or no transaction if the database doesn't support transactions. If you need a transaction, you must use the PDO::beginTransaction() method to initiate one. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your error handling settings: this is always a serious error condition). Once you are in a transaction, you may use PDO::commit() or PDO::rollBack() to finish it, depending on the success of the code you run during the transaction.

Ostrzeżenie

PDO only checks for transaction capabilities on driver level. If certain runtime conditions mean that transactions are unavailable, PDO::beginTransaction() will still return TRUE without error if the database server accepts the request to start a transaction.

An example of this would be trying to use transactions on MyISAM tables on a MySQL database.

When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. This is a safety measure to help avoid inconsistency in the cases where the script terminates unexpectedly--if you didn't explicitly commit the transaction, then it is assumed that something went awry, so the rollback is performed for the safety of your data.

Ostrzeżenie

The automatic rollback only happens if you initiate the transaction via PDO::beginTransaction(). If you manually issue a query that begins a transaction PDO has no way of knowing about it and thus cannot roll it back if something bad happens.

Przykład #1 Executing a batch in a transaction

In the following sample, let's assume that we are creating a set of entries for a new employee, who has been assigned an ID number of 23. In addition to entering the basic data for that person, we also need to record their salary. It's pretty simple to make two separate updates, but by enclosing them within the PDO::beginTransaction() and PDO::commit() calls, we are guaranteeing that no one else will be able to see those changes until they are complete. If something goes wrong, the catch block rolls back all changes made since the transaction was started, and then prints out an error message.

<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
      array(PDO::ATTR_PERSISTENT => true));
  echo "Connected\n";
} catch (Exception $e) {
  die("Unable to connect: " . $e->getMessage());
}

try {
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $dbh->beginTransaction();
  $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $dbh->exec("insert into salarychange (id, amount, changedate)
      values (23, 50000, NOW())");
  $dbh->commit();

} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

You're not limited to making updates in a transaction; you can also issue complex queries to extract data, and possibly use that information to build up more updates and queries; while the transaction is active, you are guaranteed that no one else can make changes while you are in the middle of your work. For further reading on transactions, refer to the documentation provided by your database server.

Connections and Connection management
Prepared statements and stored procedures
PDO


Prepared statements and stored procedures

Many of the more mature databases support the concept of prepared statements. What are they? They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:

  • The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
  • The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don't support them. This ensures that an application will be able to use the same data access paradigm regardless of the capabilities of the database.

Przykład #1 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the named placeholders.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Przykład #2 Repeated inserts using prepared statements

This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Przykład #3 Fetching data using prepared statements

This example fetches data based on a key value supplied by a form. The user input is automatically quoted, so there is no risk of a SQL injection attack.

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}
?>

If the database driver supports it, an application may also bind parameters for output as well as input. Output parameters are typically used to retrieve values from stored procedures. Output parameters are slightly more complex to use than input parameters, in that a developer must know how large a given parameter might be when they bind it. If the value turns out to be larger than the size they suggested, an error is raised.

Przykład #4 Calling a stored procedure with an output parameter

<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);

// call the stored procedure
$stmt->execute();

print "procedure returned $return_value\n";
?>

Developers may also specify parameters that hold values both input and output; the syntax is similar to output parameters. In this next example, the string 'hello' is passed into the stored procedure, and when it returns, hello is replaced with the return value of the procedure.

Przykład #5 Calling a stored procedure with an input/output parameter

<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);

// call the stored procedure
$stmt->execute();

print "procedure returned $value\n";
?>

Przykład #6 Invalid use of placeholder

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt->execute(array($_GET['name']));

// placeholder must be used in the place of the whole value
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(array("%$_GET[name]%"));
?>

Transactions and auto-commit
Errors and error handling
PDO


Errors and error handling

PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.

  • PDO::ERRMODE_SILENT

    This is the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.

  • PDO::ERRMODE_WARNING

    In addition to setting the error code, PDO will emit a traditional E_WARNING message. This setting is useful during debugging/testing, if you just want to see what problems occurred without interrupting the flow of the application.

  • PDO::ERRMODE_EXCEPTION

    In addition to setting the error code, PDO will throw a PDOException and set its properties to reflect the error code and error information. This setting is also useful during debugging, as it will effectively "blow up" the script at the point of the error, very quickly pointing a finger at potential problem areas in your code (remember: transactions are automatically rolled back if the exception causes the script to terminate).

    Exception mode is also useful because you can structure your error handling more clearly than with traditional PHP-style warnings, and with less code/nesting than by running in silent mode and explicitly checking the return value of each database call.

    See Exceptions for more information about Exceptions in PHP.

PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO::errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO::errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.

Przykład #1 Create a PDO instance and set the error mode

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Prepared statements and stored procedures
Large Objects (LOBs)
PDO


Large Objects (LOBs)

At some point in your application, you might find that you need to store "large" data in your database. Large typically means "around 4kb or more", although some databases can happily handle up to 32kb before data becomes "large". Large objects can be either textual or binary in nature. PDO allows you to work with this large data type by using the PDO::PARAM_LOB type code in your PDOStatement::bindParam() or PDOStatement::bindColumn() calls. PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.

Przykład #1 Displaying an image from a database

This example binds the LOB into the variable named $lob and then sends it to the browser using fpassthru(). Since the LOB is represented as a stream, functions such as fgets(), fread() and stream_get_contents() can be used on it.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
fpassthru($lob);
?>

Przykład #2 Inserting an image into a database

This example opens up a file and passes the file handle to PDO to insert it as a LOB. PDO will do its best to get the contents of the file up to the database in the most efficient manner possible.

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID

// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$db->beginTransaction();
$stmt->execute();
$db->commit();
?>

Przykład #3 Inserting an image into a database: Oracle

Oracle requires a slightly different syntax for inserting a lob from a file. It's also essential that you perform the insert under a transaction, otherwise your newly inserted LOB will be committed with a zero-length as part of the implicit commit that happens when the query is executed:

<?php
$db = new PDO('oci:', 'scott', 'tiger');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) " .
"VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // some function to allocate a new ID

// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$stmt->beginTransaction();
$stmt->execute();
$stmt->commit();
?>

Errors and error handling
PDO
PDO


The PDO class

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

Wstęp

Represents a connection between PHP and a database server.

Krótki opis klasy

PDO {
__construct ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
bool beginTransaction ( void )
bool commit ( void )
mixed errorCode ( void )
array errorInfo ( void )
int exec ( string $statement )
mixed getAttribute ( int $attribute )
array getAvailableDrivers ( void )
bool inTransaction ( void )
string lastInsertId ([ string $name = NULL ] )
PDOStatement prepare ( string $statement [, array $driver_options = array() ] )
PDOStatement query ( string $statement )
string quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )
bool rollBack ( void )
bool setAttribute ( int $attribute , mixed $value )
}

Spis treści

  • PDO::beginTransaction — Initiates a transaction
  • PDO::commit — Commits a transaction
  • PDO::__construct — Creates a PDO instance representing a connection to a database
  • PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
  • PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
  • PDO::exec — Execute an SQL statement and return the number of affected rows
  • PDO::getAttribute — Retrieve a database connection attribute
  • PDO::getAvailableDrivers — Return an array of available PDO drivers
  • PDO::inTransaction — Checks if inside a transaction
  • PDO::lastInsertId — Returns the ID of the last inserted row or sequence value
  • PDO::prepare — Prepares a statement for execution and returns a statement object
  • PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object
  • PDO::quote — Quotes a string for use in a query.
  • PDO::rollBack — Rolls back a transaction
  • PDO::setAttribute — Set an attribute
Large Objects (LOBs)
PDO::beginTransaction
PDO


Initiates a transaction

PDO
PDO::commit
PDO
PHP Manual

PDO::beginTransaction

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::beginTransaction — Initiates a transaction

Opis

bool PDO::beginTransaction ( void )

Turns off autocommit mode. While autocommit mode is turned off, changes made to the database via the PDO object instance are not committed until you end the transaction by calling PDO::commit(). Calling PDO::rollBack() will roll back all changes to the database and return the connection to autocommit mode.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Roll back a transaction

The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh->rollBack();

/* Database connection is now back in autocommit mode */
?>

Zobacz też:

  • PDO::commit() - Commits a transaction
  • PDO::rollBack() - Rolls back a transaction
  • Transactions and auto-commit

PDO
PDO::commit
PDO


Commits a transaction

PDO::beginTransaction
PDO::__construct
PDO
PHP Manual

PDO::commit

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::commit — Commits a transaction

Opis

bool PDO::commit ( void )

Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Commit a transaction

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema */
$sth = $dbh->exec("DROP TABLE fruit");

/* Commit the changes */
$dbh->commit();

/* Database connection is now back in autocommit mode */
?>

Zobacz też:

  • PDO::beginTransaction() - Initiates a transaction
  • PDO::rollBack() - Rolls back a transaction
  • Transactions and auto-commit

PDO::beginTransaction
PDO::__construct
PDO


Creates a PDO instance representing a connection to a database

PDO::commit
PDO::errorCode
PDO
PHP Manual

PDO::__construct

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::__construct — Creates a PDO instance representing a connection to a database

Opis

PDO::__construct() ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )

Creates a PDO instance to represent a connection to the requested database.

Parametry

dsn

The Data Source Name, or DSN, contains the information required to connect to the database.

In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

The dsn parameter supports three different methods of specifying the arguments required to create a database connection:

Driver invocation

dsn contains the full DSN.

URI invocation

dsn consists of uri: followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.

uri:file:///path/to/dsnfile

Aliasing

dsn consists of a name name that maps to pdo.dsn.name in php.ini defining the DSN string.

Informacja:

The alias must be defined in php.ini, and not .htaccess or httpd.conf

username

The user name for the DSN string. This parameter is optional for some PDO drivers.

password

The password for the DSN string. This parameter is optional for some PDO drivers.

driver_options

A key=>value array of driver-specific connection options.

Zwracane wartości

Returns a PDO object on success.

Błędy/Wyjątki

PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.

Przykłady

Przykład #1 Create a PDO instance via driver invocation

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Przykład #2 Create a PDO instance via URI invocation

The following example assumes that the file /usr/local/dbconnect exists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:

odbc:DSN=SAMPLE;UID=john;PWD=mypass

The PHP script can then create a database connection by simply passing the uri: parameter and pointing to the file URI:

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'uri:file:///usr/local/dbconnect';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Przykład #3 Create a PDO instance using an alias

The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias mydb:

[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"
<?php
/* Connect to an ODBC database using an alias */
$dsn = 'mydb';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

PDO::commit
PDO::errorCode
PDO


Fetch the SQLSTATE associated with the last operation on the database handle

PDO::__construct
PDO::errorInfo
PDO
PHP Manual

PDO::errorCode

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle

Opis

mixed PDO::errorCode ( void )

Zwracane wartości

Returns an SQLSTATE, a five characters alphanumeric identifier defined in the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two characters class value followed by a three characters subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the class 'IM', indicate an error. The class 'IM' is specific to warnings and errors that derive from the implementation of PDO (or perhaps ODBC, if you're using the ODBC driver) itself. The subclass value '000' in any class indicates that there is no subclass for that SQLSTATE.

PDO::errorCode() only retrieves error codes for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorCode() will not reflect that error. You must call PDOStatement::errorCode() to return the error code for an operation performed on a particular statement handle.

Returns NULL if no operation has been run on the database handle.

Przykłady

Przykład #1 Retrieving an SQLSTATE code

<?php
/* Provoke an error -- the BONES table does not exist */
$dbh->exec("INSERT INTO bones(skull) VALUES ('lucy')");

echo "\nPDO::errorCode(): ";
print $dbh->errorCode();
?>

Powyższy przykład wyświetli:

PDO::errorCode(): 42S02

Zobacz też:

  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle
  • PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

PDO::__construct
PDO::errorInfo
PDO


Fetch extended error information associated with the last operation on the database handle

PDO::errorCode
PDO::exec
PDO
PHP Manual

PDO::errorInfo

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle

Opis

array PDO::errorInfo ( void )

Zwracane wartości

PDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of the following fields:

Element | Information
0 | SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver-specific error code.
2 | Driver-specific error message.

Informacja:

If the SQLSTATE error code is not set or there is no driver-specific error, the elements following element 0 will be set to NULL.

PDO::errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorInfo() will not reflect the error from the statement handle. You must call PDOStatement::errorInfo() to return the error information for an operation performed on a particular statement handle.

Przykłady

Przykład #1 Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

<?php
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}
?>

Powyższy przykład wyświetli:

PDO::errorInfo():
Array
(
    [0] => HY000
    [1] => 1
    [2] => near "bogus": syntax error
)

Zobacz też:

  • PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
  • PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle
  • PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

PDO::errorCode
PDO::exec
PDO


Execute an SQL statement and return the number of affected rows

PDO::errorInfo
PDO::getAttribute
PDO
PHP Manual

PDO::exec

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::exec — Execute an SQL statement and return the number of affected rows

Opis

int PDO::exec ( string $statement )

PDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement.

PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query(). For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO::prepare() and issue the statement with PDOStatement::execute().

Parametry

statement

The SQL statement to prepare and execute.

Data inside the query should be properly escaped.

Zwracane wartości

PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

The following example incorrectly relies on the return value of PDO::exec(), wherein a statement that affected 0 rows results in a call to die():

<?php
$db->exec() or die(print_r($db->errorInfo(), true));
?>

Przykłady

Przykład #1 Issuing a DELETE statement

Count the number of rows deleted by a DELETE statement with no WHERE clause.

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

/* Delete all rows from the FRUIT table */
$count = $dbh->exec("DELETE FROM fruit WHERE colour = 'red'");

/* Return number of rows that were deleted */
print("Deleted $count rows.\n");
?>

Powyższy przykład wyświetli:

Deleted 1 rows.

Zobacz też:

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::execute() - Executes a prepared statement

PDO::errorInfo
PDO::getAttribute
PDO


Retrieve a database connection attribute

PDO::exec
PDO::getAvailableDrivers
PDO
PHP Manual

PDO::getAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDO::getAttribute — Retrieve a database connection attribute

Opis

mixed PDO::getAttribute ( int $attribute )

This function returns the value of a database connection attribute. To retrieve PDOStatement attributes, refer to PDOStatement::getAttribute().

Note that some database/driver combinations may not support all of the database connection attributes.

Parametry

attribute

One of the PDO::ATTR_* constants. The constants that apply to database connections are as follows:

  • PDO::ATTR_AUTOCOMMIT
  • PDO::ATTR_CASE
  • PDO::ATTR_CLIENT_VERSION
  • PDO::ATTR_CONNECTION_STATUS
  • PDO::ATTR_DRIVER_NAME
  • PDO::ATTR_ERRMODE
  • PDO::ATTR_ORACLE_NULLS
  • PDO::ATTR_PERSISTENT
  • PDO::ATTR_PREFETCH
  • PDO::ATTR_SERVER_INFO
  • PDO::ATTR_SERVER_VERSION
  • PDO::ATTR_TIMEOUT

Zwracane wartości

A successful call returns the value of the requested PDO attribute. An unsuccessful call returns null.

Przykłady

Przykład #1 Retrieving database connection attributes

<?php
$conn = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$attributes = array(
    "AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
    "ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
    "TIMEOUT"
);

foreach ($attributes as $val) {
    echo "PDO::ATTR_$val: ";
    echo $conn->getAttribute(constant("PDO::ATTR_$val")) . "\n";
}
?>

Zobacz też:

  • PDO::setAttribute() - Set an attribute
  • PDOStatement::getAttribute() - Retrieve a statement attribute
  • PDOStatement::setAttribute() - Set a statement attribute

PDO::exec
PDO::getAvailableDrivers
PDO


Return an array of available PDO drivers

PDO::getAttribute
PDO::inTransaction
PDO
PHP Manual

PDO::getAvailableDrivers

(PHP 5 >= 5.1.3, PECL pdo >= 1.0.3)

PDO::getAvailableDrivers — Return an array of available PDO drivers

Opis

array PDO::getAvailableDrivers ( void )
array pdo_drivers ( void )

This function returns all currently available PDO drivers which can be used in DSN parameter of PDO::__construct(). This is a static method.

Zwracane wartości

PDO::getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.

Przykłady

Przykład #1 A PDO::getAvailableDrivers() example

<?php
print_r(PDO::getAvailableDrivers());
?>

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

Array
(
    [0] => mysql
    [1] => sqlite
)

PDO::getAttribute
PDO::inTransaction
PDO


Checks if inside a transaction

PDO::getAvailableDrivers
PDO::lastInsertId
PDO
PHP Manual

PDO::inTransaction

(PHP 5 >= 5.3.3, Bundled pdo_pgsql)

PDO::inTransaction — Checks if inside a transaction

Opis

bool PDO::inTransaction ( void )

Checks if a transaction is currently active within the driver. This method only works for database drivers that support transactions.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if a transaction is currently active, and FALSE if not.

PDO::getAvailableDrivers
PDO::lastInsertId
PDO


Returns the ID of the last inserted row or sequence value

PDO::inTransaction
PDO::prepare
PDO
PHP Manual

PDO::lastInsertId

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::lastInsertId — Returns the ID of the last inserted row or sequence value

Opis

string PDO::lastInsertId ([ string $name = NULL ] )

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.

Informacja:

This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.

Parametry

name

Name of the sequence object from which the ID should be returned.

Zwracane wartości

If a sequence name was not specified for the name parameter, PDO::lastInsertId() returns a string representing the row ID of the last row that was inserted into the database.

If a sequence name was specified for the name parameter, PDO::lastInsertId() returns a string representing the last value retrieved from the specified sequence object.

If the PDO driver does not support this capability, PDO::lastInsertId() triggers an IM001 SQLSTATE.

PDO::inTransaction
PDO::prepare
PDO


Prepares a statement for execution and returns a statement object

PDO::lastInsertId
PDO::query
PDO
PHP Manual

PDO::prepare

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::prepare — Prepares a statement for execution and returns a statement object

Opis

PDOStatement PDO::prepare ( string $statement [, array $driver_options = array() ] )

Prepares an SQL statement to be executed by the PDOStatement::execute() method. The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed. You cannot use both named and question mark parameter markers within the same SQL statement; pick one or the other parameter style. Use these parameters to bind any user-input, do not include the user-input directly in the query.

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

Parametry

statement

This must be a valid SQL statement for the target database server.

driver_options

This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time.

Zwracane wartości

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

Informacja:

Emulated prepared statements does not communicate with the database server so PDO::prepare() does not check the statement.

Przykłady

Przykład #1 Prepare an SQL statement with named parameters

<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>

Przykład #2 Prepare an SQL statement with question mark parameters

<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>

Zobacz też:

  • PDO::exec() - Execute an SQL statement and return the number of affected rows
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::execute() - Executes a prepared statement

PDO::lastInsertId
PDO::query
PDO


Executes an SQL statement, returning a result set as a PDOStatement object

PDO::prepare
PDO::quote
PDO
PHP Manual

PDO::query

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object

Opis

PDOStatement PDO::query ( string $statement )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_COLUMN , int $colno )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
PDOStatement PDO::query ( string $statement , int $PDO::FETCH_INTO , object $object )

PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.

For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO::prepare() and issue the statement with multiple calls to PDOStatement::execute().

If you do not fetch all of the data in a result set before issuing your next call to PDO::query(), your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query().

Informacja:

Although this function is only documented as having a single parameter, you may pass additional arguments to this function. They will be treated as though you called PDOStatement::setFetchMode() on the resultant statement object.

Parametry

statement

The SQL statement to prepare and execute.

Data inside the query should be properly escaped.

Zwracane wartości

PDO::query() returns a PDOStatement object, or FALSE on failure.

Przykłady

Przykład #1 Demonstrate PDO::query

A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement.

<?php
function getFruit($conn) {
    $sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
    foreach ($conn->query($sql) as $row) {
        print $row['name'] . "\t";
        print $row['color'] . "\t";
        print $row['calories'] . "\n";
    }
}
?>

Powyższy przykład wyświetli:

apple   red     150
banana  yellow  250
kiwi    brown   75
lemon   yellow  25
orange  orange  300
pear    green   150
watermelon      pink    90

Zobacz też:

  • PDO::exec() - Execute an SQL statement and return the number of affected rows
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement

PDO::prepare
PDO::quote
PDO


Quotes a string for use in a query.

PDO::query
PDO::rollBack
PDO
PHP Manual

PDO::quote

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.1)

PDO::quote — Quotes a string for use in a query.

Opis

string PDO::quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )

PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, immune to SQL injection, but are often much faster to execute than interpolated queries, as both the server and client side can cache a compiled form of the query.

Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.

Parametry

string

The string to be quoted.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles.

Zwracane wartości

Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.

Przykłady

Przykład #1 Quoting a normal string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

Powyższy przykład wyświetli:

Unquoted string: Nice
Quoted string: 'Nice'

Przykład #2 Quoting a dangerous string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>

Powyższy przykład wyświetli:

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Przykład #3 Quoting a complex string

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* Complex string */
$string = "Co'mpl''ex \"st'\"ring";
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

Powyższy przykład wyświetli:

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

Zobacz też:

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement

PDO::query
PDO::rollBack
PDO


Rolls back a transaction

PDO::quote
PDO::setAttribute
PDO
PHP Manual

PDO::rollBack

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::rollBack — Rolls back a transaction

Opis

bool PDO::rollBack ( void )

Rolls back the current transaction, as initiated by PDO::beginTransaction(). A PDOException will be thrown if no transaction is active.

If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.

Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Roll back a transaction

The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.

<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/* Recognize mistake and roll back changes */
$dbh->rollBack();

/* Database connection is now back in autocommit mode */
?>

Zobacz też:

  • PDO::beginTransaction() - Initiates a transaction
  • PDO::commit() - Commits a transaction
  • Transactions and auto-commit

PDO::quote
PDO::setAttribute
PDO


Set an attribute

PDO::rollBack
PDOStatement
PDO
PHP Manual

PDO::setAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDO::setAttribute — Set an attribute

Opis

bool PDO::setAttribute ( int $attribute , mixed $value )

Sets an attribute on the database handle. Some of the available generic attributes are listed below; some drivers may make use of additional driver specific attributes.

  • PDO::ATTR_CASE: Force column names to a specific case.

    • PDO::CASE_LOWER: Force column names to lower case.

    • PDO::CASE_NATURAL: Leave column names as returned by the database driver.

    • PDO::CASE_UPPER: Force column names to upper case.

  • PDO::ATTR_ERRMODE: Error reporting.

    • PDO::ERRMODE_SILENT: Just set error codes.

    • PDO::ERRMODE_WARNING: Raise E_WARNING.

    • PDO::ERRMODE_EXCEPTION: Throw exceptions.

  • PDO::ATTR_ORACLE_NULLS (available with all drivers, not just Oracle): Conversion of NULL and empty strings.

    • PDO::NULL_NATURAL: No conversion.

    • PDO::NULL_EMPTY_STRING: Empty string is converted to NULL.

    • PDO::NULL_TO_STRING: NULL is converted to an empty string.

  • PDO::ATTR_STRINGIFY_FETCHES: Convert numeric values to strings when fetching. Requires bool.

  • PDO::ATTR_STATEMENT_CLASS: Set user-supplied statement class derived from PDOStatement. Cannot be used with persistent PDO instances. Requires array(string classname, array(mixed constructor_args)).

  • PDO::ATTR_TIMEOUT: Specifies the timeout duration in seconds. Not all drivers support this option, and it's meaning may differ from driver to driver. For example, sqlite will wait for up to this time value before giving up on obtaining an writable lock, but other drivers may interpret this as a connect or a read timeout interval. Requires int.

  • PDO::ATTR_AUTOCOMMIT (available in OCI, Firebird and MySQL): Whether to autocommit every single statement.

  • PDO::ATTR_EMULATE_PREPARES Enables or disables emulation of prepared statements. Some drivers do not support native prepared statements or have limited support for them. Use this setting to force PDO to either always emulate prepared statements (if TRUE), or to try to use native prepared statements (if FALSE). It will always fall back to emulating the prepared statement if the driver cannot successfully prepare the current query. Requires bool.

  • PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (available in MySQL): Use buffered queries.

  • PDO::ATTR_DEFAULT_FETCH_MODE: Set default fetch mode. Description of modes is available in PDOStatement::fetch() documentation.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDO::rollBack
PDOStatement
PDO


The PDOStatement class

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

Wstęp

Represents a prepared statement and, after the statement is executed, an associated result set.

Krótki opis klasy

PDOStatement implements Traversable {
/* Właściwości */
readonly string $queryString;
/* Metody */
bool bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )
bool bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
bool bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
bool closeCursor ( void )
int columnCount ( void )
bool debugDumpParams ( void )
string errorCode ( void )
array errorInfo ( void )
bool execute ([ array $input_parameters ] )
mixed fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
array fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )
string fetchColumn ([ int $column_number = 0 ] )
mixed fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )
mixed getAttribute ( int $attribute )
array getColumnMeta ( int $column )
bool nextRowset ( void )
int rowCount ( void )
bool setAttribute ( int $attribute , mixed $value )
bool setFetchMode ( int $mode )
}

Właściwości

queryString

Used query string.

Spis treści

  • PDOStatement::bindColumn — Bind a column to a PHP variable
  • PDOStatement::bindParam — Binds a parameter to the specified variable name
  • PDOStatement::bindValue — Binds a value to a parameter
  • PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again.
  • PDOStatement::columnCount — Returns the number of columns in the result set
  • PDOStatement::debugDumpParams — Dump an SQL prepared command
  • PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle
  • PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle
  • PDOStatement::execute — Executes a prepared statement
  • PDOStatement::fetch — Fetches the next row from a result set
  • PDOStatement::fetchAll — Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn — Returns a single column from the next row of a result set
  • PDOStatement::fetchObject — Fetches the next row and returns it as an object.
  • PDOStatement::getAttribute — Retrieve a statement attribute
  • PDOStatement::getColumnMeta — Returns metadata for a column in a result set
  • PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle
  • PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement
  • PDOStatement::setAttribute — Set a statement attribute
  • PDOStatement::setFetchMode — Set the default fetch mode for this statement
PDO::setAttribute
PDOStatement::bindColumn
PDO


Bind a column to a PHP variable

PDOStatement
PDOStatement::bindParam
PDOStatement
PHP Manual

PDOStatement::bindColumn

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::bindColumn — Bind a column to a PHP variable

Opis

bool PDOStatement::bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )

PDOStatement::bindColumn() arranges to have a particular variable bound to a given column in the result-set from a query. Each call to PDOStatement::fetch() or PDOStatement::fetchAll() will update all the variables that are bound to columns.

Informacja:

Since information about the columns is not always available to PDO until the statement is executed, portable applications should call this function after PDOStatement::execute().

However, to be able to bind a LOB column as a stream when using the PgSQL driver, applications should call this method before calling PDOStatement::execute(), otherwise the large object OID will be returned as an integer.

Parametry

column

Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver.

param

Name of the PHP variable to which the column will be bound.

type

Data type of the parameter, specified by the PDO::PARAM_* constants.

maxlen

A hint for pre-allocation.

driverdata

Optional parameter(s) for the driver.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Binding result set output to PHP variables

Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to your application. The following example demonstrates how PDO allows you to bind and retrieve columns with a variety of options and with intelligent defaults.

<?php
function readData($dbh) {
  $sql = 'SELECT name, colour, calories FROM fruit';
  try {
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    /* Bind by column number */
    $stmt->bindColumn(1, $name);
    $stmt->bindColumn(2, $colour);

    /* Bind by column name */
    $stmt->bindColumn('calories', $cals);

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
      $data = $name . "\t" . $colour . "\t" . $cals . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
readData($dbh);
?>

Powyższy przykład wyświetli:

apple   red     150
banana  yellow  175
kiwi    green   75
orange  orange  150
mango   red     200
strawberry      red     25

Zobacz też:

  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set

PDOStatement
PDOStatement::bindParam
PDOStatement


Binds a parameter to the specified variable name

PDOStatement::bindColumn
PDOStatement::bindValue
PDOStatement
PHP Manual

PDOStatement::bindParam

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::bindParam — Binds a parameter to the specified variable name

Opis

bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )

Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

Most parameters are input parameters, that is, parameters that are used in a read-only fashion to build up the query. Some drivers support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.

Parametry

parameter

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

variable

Name of the PHP variable to bind to the SQL statement parameter.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type parameter.

length

Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.

driver_options

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Execute a prepared statement with named placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Przykład #2 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Przykład #3 Call a stored procedure with an INOUT parameter

<?php
/* Call a stored procedure with an INOUT parameter */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print("After pureeing fruit, the colour is: $colour");
?>

Zobacz też:

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::bindValue() - Binds a value to a parameter

PDOStatement::bindColumn
PDOStatement::bindValue
PDOStatement


Binds a value to a parameter

PDOStatement::bindParam
PDOStatement::closeCursor
PDOStatement
PHP Manual

PDOStatement::bindValue

(PHP 5 >= 5.1.0, PECL pdo >= 1.0.0)

PDOStatement::bindValue — Binds a value to a parameter

Opis

bool PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )

Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.

Parametry

parameter

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

value

The value to bind to the parameter.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Execute a prepared statement with named placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>

Przykład #2 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>

Zobacz też:

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name

PDOStatement::bindParam
PDOStatement::closeCursor
PDOStatement


Closes the cursor, enabling the statement to be executed again.

PDOStatement::bindValue
PDOStatement::columnCount
PDOStatement
PHP Manual

PDOStatement::closeCursor

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again.

Opis

bool PDOStatement::closeCursor ( void )

PDOStatement::closeCursor() frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.

This method is useful for database drivers that do not support executing a PDOStatement object when a previously executed PDOStatement object still has unfetched rows. If your database driver suffers from this limitation, the problem may manifest itself in an out-of-sequence error.

PDOStatement::closeCursor() is implemented either as an optional driver specific method (allowing for maximum efficiency), or as the generic PDO fallback if no driver specific function is installed. The PDO generic fallback is semantically the same as writing the following code in your PHP script:

<?php
do {
    while ($stmt->fetch())
        ;
    if (!$stmt->nextRowset())
        break;
} while (true);
?>

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A PDOStatement::closeCursor() example

In the following example, the $stmt PDOStatement object returns multiple rows but the application fetches only the first row, leaving the PDOStatement object in a state of having unfetched rows. To ensure that the application will work with all database drivers, the author inserts a call to PDOStatement::closeCursor() on $stmt before executing the $otherStmt PDOStatement object.

<?php
/* Create a PDOStatement object */
$stmt = $dbh->prepare('SELECT foo FROM bar');

/* Create a second PDOStatement object */
$otherStmt = $dbh->prepare('SELECT foobaz FROM foobar');

/* Execute the first statement */
$stmt->execute();

/* Fetch only the first row from the results */
$stmt->fetch();

/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();

/* Now we can execute the second statement */
$otherStmt->execute();
?>

Zobacz też:

  • PDOStatement::execute() - Executes a prepared statement

PDOStatement::bindValue
PDOStatement::columnCount
PDOStatement


Returns the number of columns in the result set

PDOStatement::closeCursor
PDOStatement::debugDumpParams
PDOStatement
PHP Manual

PDOStatement::columnCount

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::columnCount — Returns the number of columns in the result set

Opis

int PDOStatement::columnCount ( void )

Use PDOStatement::columnCount() to return the number of columns in the result set represented by the PDOStatement object.

If the PDOStatement object was returned from PDO::query(), the column count is immediately available.

If the PDOStatement object was returned from PDO::prepare(), an accurate column count will not be available until you invoke PDOStatement::execute().

Zwracane wartości

Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.

Przykłady

Przykład #1 Counting columns

This example demonstrates how PDOStatement::columnCount() operates with and without a result set.

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

$sth = $dbh->prepare("SELECT name, colour FROM fruit");

/* Count the number of columns in the (non-existent) result set */
$colcount = $sth->columnCount();
print("Before execute(), result set has $colcount columns (should be 0)\n");

$sth->execute();

/* Count the number of columns in the result set */
$colcount = $sth->columnCount();
print("After execute(), result set has $colcount columns (should be 2)\n");

?>

Powyższy przykład wyświetli:

Before execute(), result set has 0 columns (should be 0)
After execute(), result set has 2 columns (should be 2)

Zobacz też:

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::rowCount() - Returns the number of rows affected by the last SQL statement

PDOStatement::closeCursor
PDOStatement::debugDumpParams
PDOStatement


Dump an SQL prepared command

PDOStatement::columnCount
PDOStatement::errorCode
PDOStatement
PHP Manual

PDOStatement::debugDumpParams

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement::debugDumpParams — Dump an SQL prepared command

Opis

bool PDOStatement::debugDumpParams ( void )

Dumps the informations contained by a prepared statement directly on the output. It will provide the SQL query in use, the number of parameters used (Params), the list of parameters, with their name, type (paramtype) as an integer, their key name or position, the value, and the position in the query (if this is supported by the PDO driver, otherwise, it will be -1).

This is a debug function, which dump directly the data on the normal output.

Wskazówka

Ze wszystkim, co wysyła dane bezpośrednio do przeglądarki, możesz używać funkcji kontroli wyjścia aby przejąć wyjście tej funkcji i zapisać je w zmiennej tekstowej (na przykład).

This will only dumps the parameters in the statement at the moment of the dump. Extra parameters are not stored in the statement, and not displayed.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 PDOStatement::debugDumpParams() example with named parameters

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

$sth->debugDumpParams();

?>

Powyższy przykład wyświetli:

SQL: [96] SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour
Params:  2
Key: Name: [9] :calories
paramno=-1
name=[9] ":calories"
is_param=1
param_type=1
Key: Name: [7] :colour
paramno=-1
name=[7] ":colour"
is_param=1
param_type=2

Przykład #2 PDOStatement::debugDumpParams() example with unnamed parameters

<?php

/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$name = 'apple';

$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();

$sth->debugDumpParams();

?>

Powyższy przykład wyświetli:

SQL: [82] SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?
Params:  2
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=1
Key: Position #1:
paramno=1
name=[0] ""
is_param=1
param_type=2

Zobacz też:

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name
  • PDOStatement::bindValue() - Binds a value to a parameter

PDOStatement::columnCount
PDOStatement::errorCode
PDOStatement


Fetch the SQLSTATE associated with the last operation on the statement handle

PDOStatement::debugDumpParams
PDOStatement::errorInfo
PDOStatement
PHP Manual

PDOStatement::errorCode

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle

Opis

string PDOStatement::errorCode ( void )

Zwracane wartości

Identical to PDO::errorCode(), except that PDOStatement::errorCode() only retrieves error codes for operations performed with PDOStatement objects.

Przykłady

Przykład #1 Retrieving an SQLSTATE code

<?php
/* Provoke an error -- the BONES table does not exist */
$err = $dbh->prepare('SELECT skull FROM bones');
$err->execute();

echo "\nPDOStatement::errorCode(): ";
print $err->errorCode();
?>

Powyższy przykład wyświetli:

PDOStatement::errorCode(): 42S02

Zobacz też:

  • PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorInfo() - Fetch extended error information associated with the last operation on the statement handle

PDOStatement::debugDumpParams
PDOStatement::errorInfo
PDOStatement


Fetch extended error information associated with the last operation on the statement handle

PDOStatement::errorCode
PDOStatement::execute
PDOStatement
PHP Manual

PDOStatement::errorInfo

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle

Opis

array PDOStatement::errorInfo ( void )

Zwracane wartości

PDOStatement::errorInfo() returns an array of error information about the last operation performed by this statement handle. The array consists of the following fields:

Element | Information
0 | SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver specific error code.
2 | Driver specific error message.

Przykłady

Przykład #1 Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

<?php
/* Provoke an error -- the BONES table does not exist */
$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
?>

Powyższy przykład wyświetli:

PDOStatement::errorInfo():
Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

Zobacz też:

  • PDO::errorCode() - Fetch the SQLSTATE associated with the last operation on the database handle
  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorCode() - Fetch the SQLSTATE associated with the last operation on the statement handle

PDOStatement::errorCode
PDOStatement::execute
PDOStatement


Executes a prepared statement

PDOStatement::errorInfo
PDOStatement::fetch
PDOStatement
PHP Manual

PDOStatement::execute

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::execute — Executes a prepared statement

Opis

bool PDOStatement::execute ([ array $input_parameters ] )

Execute the prepared statement. If the prepared statement included parameter markers, you must either:

  • call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers

  • or pass an array of input-only parameter values

Parametry

input_parameters

An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.

You cannot bind multiple values to a single parameter; for example, you cannot bind two values to a single named parameter in an IN() clause.

You cannot bind more values than specified; if more keys exist in input_parameters than in the SQL specified in the PDO::prepare(), then the statement will fail and an error is emitted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.2.0 | The keys from input_parameters must match the ones declared in the SQL. Before PHP 5.2.0 this was silently ignored.

Przykłady

Przykład #1 Execute a prepared statement with bound variables

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Przykład #2 Execute a prepared statement with an array of insert values (named parameters)

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>

Przykład #3 Execute a prepared statement with an array of insert values (placeholders)

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
?>

Przykład #4 Execute a prepared statement with question mark placeholders

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Notatki

Informacja:

Some drivers require to close cursor before executing next statement.

Zobacz też:

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::bindParam() - Binds a parameter to the specified variable name
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set

PDOStatement::errorInfo
PDOStatement::fetch
PDOStatement


Fetches the next row from a result set

PDOStatement::execute
PDOStatement::fetchAll
PDOStatement
PHP Manual

PDOStatement::fetch

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::fetch — Fetches the next row from a result set

Opis

mixed PDOStatement::fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )

Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.

Parametry

fetch_style

Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants, defaulting to value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH).

  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

  • PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindColumn() method

  • PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a value of the first column.

  • PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in the class

  • PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed

  • PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

  • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

cursor_orientation

For a PDOStatement object representing a scrollable cursor, this value determines which row will be returned to the caller. This value must be one of the PDO::FETCH_ORI_* constants, defaulting to PDO::FETCH_ORI_NEXT. To request a scrollable cursor for your PDOStatement object, you must set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you prepare the SQL statement with PDO::prepare().

offset

For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_ABS, this value specifies the absolute number of the row in the result set that shall be fetched.

For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_REL, this value specifies the row to fetch relative to the cursor position before PDOStatement::fetch() was called.

Zwracane wartości

The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.

Przykłady

Przykład #1 Fetching rows using different fetch styles

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");

print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");

print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");

print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
print("\n");
?>

Powyższy przykład wyświetli:

PDO::FETCH_ASSOC: Return next row as an array indexed by column name
Array
(
    [NAME] => apple
    [COLOUR] => red
)

PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
Array
(
    [NAME] => banana
    [0] => banana
    [COLOUR] => yellow
    [1] => yellow
)

PDO::FETCH_LAZY: Return next row as an anonymous object with column names as properties
PDORow Object
(
    [NAME] => orange
    [COLOUR] => orange
)

PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties
kiwi

Przykład #2 Fetching rows with a scrollable cursor

<?php
function readDataForwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
    while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    }
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
function readDataBackwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
  try {
    $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
    do {
      $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
      print $data;
    } while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}

print "Reading forwards:\n";
readDataForwards($conn);

print "Reading backwards:\n";
readDataBackwards($conn);
?>

Powyższy przykład wyświetli:

Reading forwards:
21    10    5
16    0     5
19    20    10

Reading backwards:
19    20    10
16    0     5
21    10    5

Zobacz też:

  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
  • PDOStatement::fetchObject() - Fetches the next row and returns it as an object.
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement

PDOStatement::execute
PDOStatement::fetchAll
PDOStatement


Returns an array containing all of the result set rows

PDOStatement::fetch
PDOStatement::fetchColumn
PDOStatement
PHP Manual

PDOStatement::fetchAll

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::fetchAll — Returns an array containing all of the result set rows

Opis

array PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )

Parametry

fetch_style

Controls the contents of the returned array as documented in
PDOStatement::fetch().
Defaults to value of PDO::ATTR_DEFAULT_FETCH_MODE
(which defaults to PDO::FETCH_BOTH)

To return an array consisting of all values of a single column from the result set, specify PDO::FETCH_COLUMN. You can specify which column you want with the column-index parameter.

To fetch only the unique values of a single column from the result set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE.

To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.

fetch_argument

This argument have a different meaning depending on the value of the fetch_style parameter:

  • PDO::FETCH_COLUMN: Returns the indicated 0-indexed column.

  • PDO::FETCH_CLASS: Returns instances of the specified class, mapping the columns of each row to named properties in the class.

  • PDO::FETCH_FUNC: Returns the results of calling the specified function, using each row's columns as parameters in the call.

ctor_args

Arguments of custom class constructor when the fetch_style parameter is PDO::FETCH_CLASS.

Zwracane wartości

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name.

Using this method to fetch large result sets will result in a heavy demand on system and possibly network resources. Rather than retrieving all of the data and manipulating it in PHP, consider using the database server to manipulate the result sets. For example, use the WHERE and ORDER BY clauses in SQL to restrict results before retrieving and processing them with PHP.

Przykłady

Przykład #1 Fetch all remaining rows in a result set

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

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

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [NAME] => pear
            [0] => pear
            [COLOUR] => green
            [1] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [0] => watermelon
            [COLOUR] => pink
            [1] => pink
        )

)

Przykład #2 Fetching all values of a single column from a result set

The following example demonstrates how to return all of the values of a single column from a result set, even though the SQL statement itself may return multiple columns per row.

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?>

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

Array(3)
(
    [0] =>
    string(5) => apple
    [1] =>
    string(4) => pear
    [2] =>
    string(10) => watermelon
)

Przykład #3 Grouping all values by a single column

The following example demonstrates how to return an associative array grouped by the values of the specified column in the result set. The array contains three keys: values apple and pear are returned as arrays that contain two different colours, while watermelon is returned as an array that contains only one colour.

<?php
$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>

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

array(3) {
  ["apple"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(3) "red"
  }
  ["pear"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(6) "yellow"
  }
  ["watermelon"]=>
  array(1) {
    [0]=>
    string(5) "green"
  }
}

Przykład #4 Instantiating a class for each result

The following example demonstrates the behaviour of the PDO::FETCH_CLASS fetch style.

<?php
class fruit {
    public $name;
    public $colour;
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
var_dump($result);
?>

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

array(3) {
  [0]=>
  object(fruit)#1 (2) {
    ["name"]=>
    string(5) "apple"
    ["colour"]=>
    string(5) "green"
  }
  [1]=>
  object(fruit)#2 (2) {
    ["name"]=>
    string(4) "pear"
    ["colour"]=>
    string(6) "yellow"
  }
  [2]=>
  object(fruit)#3 (2) {
    ["name"]=>
    string(10) "watermelon"
    ["colour"]=>
    string(4) "pink"
  }
}

Przykład #5 Calling a function for each result

The following example demonstrates the behaviour of the PDO::FETCH_FUNC fetch style.

<?php
function fruit($name, $colour) {
    return "{$name}: {$colour}";
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_FUNC, "fruit");
var_dump($result);
?>

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

array(3) {
  [0]=>
  string(12) "apple: green"
  [1]=>
  string(12) "pear: yellow"
  [2]=>
  string(16) "watermelon: pink"
}

Zobacz też:

  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement

PDOStatement::fetch
PDOStatement::fetchColumn
PDOStatement


Returns a single column from the next row of a result set

PDOStatement::fetchAll
PDOStatement::fetchObject
PDOStatement
PHP Manual

PDOStatement::fetchColumn

(PHP 5 >= 5.1.0, PECL pdo >= 0.9.0)

PDOStatement::fetchColumn — Returns a single column from the next row of a result set

Opis

string PDOStatement::fetchColumn ([ int $column_number = 0 ] )

Returns a single column from the next row of a result set or FALSE if there are no more rows.

Parametry

column_number

0-indexed number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement::fetchColumn() fetches the first column.

Zwracane wartości

PDOStatement::fetchColumn() returns a single column in the next row of a result set.

Ostrzeżenie

There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.

Przykłady

Przykład #1 Return first column of the next row

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch the first column from the next row in the result set */
print("Fetch the first column from the next row in the result set:\n");
$result = $sth->fetchColumn();
print("name = $result\n");

print("Fetch the second column from the next row in the result set:\n");
$result = $sth->fetchColumn(1);
print("colour = $result\n");
?>

Powyższy przykład wyświetli:

Fetch the first column from the next row in the result set:
name = lemon
Fetch the second column from the next row in the result set:
colour = red

Zobacz też:

  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement

PDOStatement::fetchAll
PDOStatement::fetchObject
PDOStatement


Fetches the next row and returns it as an object.

PDOStatement::fetchColumn
PDOStatement::getAttribute
PDOStatement
PHP Manual

PDOStatement::fetchObject

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.4)

PDOStatement::fetchObject — Fetches the next row and returns it as an object.

Opis

mixed PDOStatement::fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )

Fetches the next row and returns it as an object. This function is an
alternative to PDOStatement::fetch() with
PDO::FETCH_CLASS or
PDO::FETCH_OBJ style.

Parametry

class_name

Name of the created class.

ctor_args

Elements of this array are passed to the constructor.

Zwracane wartości

Returns an instance of the required class with property names that correspond to the column names lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • PDOStatement::fetch() - Fetches the next row from a result set

PDOStatement::fetchColumn
PDOStatement::getAttribute
PDOStatement


Retrieve a statement attribute

PDOStatement::fetchObject
PDOStatement::getColumnMeta
PDOStatement
PHP Manual

PDOStatement::getAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::getAttribute — Retrieve a statement attribute

Opis

mixed PDOStatement::getAttribute ( int $attribute )

Gets an attribute of the statement. Currently, no generic attributes exist but only driver specific:

  • PDO::ATTR_CURSOR_NAME (Firebird and ODBC specific): Get the name of cursor for UPDATE ... WHERE CURRENT OF.

Zwracane wartości

Returns the attribute value.

Zobacz też:

  • PDO::getAttribute() - Retrieve a database connection attribute
  • PDO::setAttribute() - Set an attribute
  • PDOStatement::setAttribute() - Set a statement attribute

PDOStatement::fetchObject
PDOStatement::getColumnMeta
PDOStatement


Returns metadata for a column in a result set

PDOStatement::getAttribute
PDOStatement::nextRowset
PDOStatement
PHP Manual

PDOStatement::getColumnMeta

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::getColumnMeta — Returns metadata for a column in a result set

Opis

array PDOStatement::getColumnMeta ( int $column )
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.

Retrieves the metadata for a 0-indexed column in a result set as an associative array.

Ostrzeżenie

Not all PDO drivers support PDOStatement::getColumnMeta().

Parametry

column

The 0-indexed column in the result set.

Zwracane wartości

Returns an associative array containing the following values representing the metadata for a single column:

Column metadata
Name | Value
native_type | The PHP native type used to represent the column value.
driver:decl_type | The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement::getColumnMeta().
flags | Any flags set for this column.
name | The name of this column as returned by the database.
table | The name of this column's table as returned by the database.
len | The length of this column. Normally -1 for types other than floating point decimals.
precision | The numeric precision of this column. Normally 0 for types other than floating point decimals.
pdo_type | The type of this column as represented by the PDO::PARAM_* constants.

Returns FALSE if the requested column does not exist in the result set, or if no result set exists.

Rejestr zmian

Wersja | Opis
5.2.3 | table field

Przykłady

Przykład #1 Retrieving column metadata

The following example shows the results of retrieving the metadata for a single column generated by a function (COUNT) in a PDO_SQLITE driver.

<?php
$select = $DB->query('SELECT COUNT(*) FROM fruit');
$meta = $select->getColumnMeta(0);
var_dump($meta);
?>

Powyższy przykład wyświetli:

array(6) {
  ["native_type"]=>
  string(7) "integer"
  ["flags"]=>
  array(0) {
  }
  ["name"]=>
  string(8) "COUNT(*)"
  ["len"]=>
  int(-1)
  ["precision"]=>
  int(0)
  ["pdo_type"]=>
  int(2)
}

Zobacz też:

  • PDOStatement::columnCount() - Returns the number of columns in the result set
  • PDOStatement::rowCount() - Returns the number of rows affected by the last SQL statement

PDOStatement::getAttribute
PDOStatement::nextRowset
PDOStatement


Advances to the next rowset in a multi-rowset statement handle

PDOStatement::getColumnMeta
PDOStatement::rowCount
PDOStatement
PHP Manual

PDOStatement::nextRowset

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle

Opis

bool PDOStatement::nextRowset ( void )

Some database servers support stored procedures that return more than one rowset (also known as a result set). PDOStatement::nextRowset() enables you to access the second and subsequent rowsets associated with a PDOStatement object. Each rowset can have a different set of columns from the preceding rowset.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Fetching multiple rowsets returned from a stored procedure

The following example shows how to call a stored procedure, MULTIPLE_ROWSETS, that returns three rowsets. We use a do / while loop to loop over the PDOStatement::nextRowset() method, which returns false and terminates the loop when no more rowsets can be returned.

<?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn->query($sql);
$i = 1;
do {
    $rowset = $stmt->fetchAll(PDO::FETCH_NUM);
    if ($rowset) {
        printResultSet($rowset, $i);
    }
    $i++;
} while ($stmt->nextRowset());

function printResultSet(&$rowset, $i) {
    print "Result set $i:\n";
    foreach ($rowset as $row) {
        foreach ($row as $col) {
            print $col . "\t";
        }
        print "\n";
    }
    print "\n";
}
?>

Powyższy przykład wyświetli:

Result set 1:
apple    red
banana   yellow

Result set 2:
orange   orange    150
banana   yellow    175

Result set 3:
lime     green
apple    red
banana   yellow

Zobacz też:

  • PDOStatement::columnCount() - Returns the number of columns in the result set
  • PDOStatement::execute() - Executes a prepared statement
  • PDOStatement::getColumnMeta() - Returns metadata for a column in a result set
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object

PDOStatement::getColumnMeta
PDOStatement::rowCount
PDOStatement


Returns the number of rows affected by the last SQL statement

PDOStatement::nextRowset
PDOStatement::setAttribute
PDOStatement
PHP Manual

PDOStatement::rowCount

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement

Opis

int PDOStatement::rowCount ( void )

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

Zwracane wartości

Returns the number of rows.

Przykłady

Przykład #1 Return the number of deleted rows

PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.

<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();

/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>

Powyższy przykład wyświetli:

Return number of rows that were deleted:
Deleted 9 rows.

Przykład #2 Counting rows returned by a SELECT statement

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.

<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res->fetchColumn() > 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT name FROM fruit WHERE calories > 100";
       foreach ($conn->query($sql) as $row) {
           print "Name: " .  $row['NAME'] . "\n";
         }
    }
    /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?>

Powyższy przykład wyświetli:

apple
banana
orange
pear

Zobacz też:

  • PDOStatement::columnCount() - Returns the number of columns in the result set
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object

PDOStatement::nextRowset
PDOStatement::setAttribute
PDOStatement


Set a statement attribute

PDOStatement::rowCount
PDOStatement::setFetchMode
PDOStatement
PHP Manual

PDOStatement::setAttribute

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::setAttribute — Set a statement attribute

Opis

bool PDOStatement::setAttribute ( int $attribute , mixed $value )

Sets an attribute on the statement. Currently, no generic attributes are set but only driver specific:

  • PDO::ATTR_CURSOR_NAME (Firebird and ODBC specific): Set the name of cursor for UPDATE ... WHERE CURRENT OF.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • PDO::getAttribute() - Retrieve a database connection attribute
  • PDO::setAttribute() - Set an attribute
  • PDOStatement::getAttribute() - Retrieve a statement attribute

PDOStatement::rowCount
PDOStatement::setFetchMode
PDOStatement


Set the default fetch mode for this statement

PDOStatement::setAttribute
PDOException
PDOStatement
PHP Manual

PDOStatement::setFetchMode

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)

PDOStatement::setFetchMode — Set the default fetch mode for this statement

Opis

bool PDOStatement::setFetchMode ( int $mode )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_COLUMN , int $colno )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_INTO , object $object )

Parametry

mode

The fetch mode must be one of the PDO::FETCH_* constants.

colno

Column number.

classname

Class name.

ctorargs

Constructor arguments.

object

Object.

Zwracane wartości

Returns 1 on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Setting the fetch mode

The following example demonstrates how PDOStatement::setFetchMode() changes the default fetch mode for a PDOStatement object.

<?php
$sql = 'SELECT name, colour, calories FROM fruit';
try {
  $stmt = $dbh->query($sql);
  $result = $stmt->setFetchMode(PDO::FETCH_NUM);
  while ($row = $stmt->fetch()) {
    print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
  }
}
catch (PDOException $e) {
  print $e->getMessage();
}
?>

Powyższy przykład wyświetli:

apple   red     150
banana  yellow  250
orange  orange  300
kiwi    brown   75
lemon   yellow  25
pear    green   150
watermelon      pink    90

PDOStatement::setAttribute
PDOException
PDOStatement


The PDOException class

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

Wstęp

Represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP.

Krótki opis klasy

PDOException extends RuntimeException {
/* Właściwości */
public array $errorInfo ;
protected string $message ;
protected string $code ;
/* 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

errorInfo

Corresponds to PDO::errorInfo() or PDOStatement::errorInfo()

message

Textual error message. Exception::getMessage() to access it.

code

SQLSTATE error code. Use Exception::getCode() to access it.

PDOStatement::setFetchMode
PDO Drivers
PDO


PDO Drivers

Spis treści

  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird/Interbase (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • MS SQL Server (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • 4D (PDO)

The following drivers currently implement the PDO interface:

Driver name | Supported databases
PDO_CUBRID | Cubrid
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD | Firebird/Interbase 6
PDO_IBM | IBM DB2
PDO_INFORMIX | IBM Informix Dynamic Server
PDO_MYSQL | MySQL 3.x/4.x/5.x
PDO_OCI | Oracle Call Interface
PDO_ODBC | ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL | PostgreSQL
PDO_SQLITE | SQLite 3 and SQLite 2
PDO_SQLSRV | Microsoft SQL Server / SQL Azure
PDO_4D | 4D

PDOException
CUBRID (PDO)
PDO


CUBRID Functions (PDO_CUBRID)

Wstęp

PDO_CUBRID is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to CUBRID databases.

Informacja:

Current version of PDO_CUBRID doesn't support persistent connection now.

Instalacja

To build the PDO_CUBRID extension, the CUBRID DBMS must be installed on the same system as PHP. PDO_CUBRID is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_CUBRID extension. Issue the configure command to point to the location of your CUBRID base dir as follows:

   $ ./configure --with-pdo-cubrid=/path/to/CUBRID[,shared]
The configure command defaults to the value of the CUBRID environment variable.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/ Detailed information about installation on Linux and Windows manually, please read build-guide.html in PECL package CUBRID for reference.

Features

PDO_CUBRID Features
Feature | Description
Scrollable cursors | PDO_CUBRID supports scrollable cursors. The default cursor type is forward only, and you can use parameter driver_options in PDO::prepare() to change cursor type.
Timeout | PDO_CUBRID supports sql statement execution timeout setting; You can use PDO::setAttribute() to set timeout value.
Autocommit_mode and Transaction PDO_CUBRID supports both autocommit_mode and transaction, and autocommit_mode is disabled by default. You can use PDO::setAttribute() to change its state.

If you use PDO::beginTransaction() to begin a transaction, it will disable autocommit_mode automatically and restore it after PDO::commit() or PDO::rollBack(). Note that before disabling the autocommit_mode, any pending work is automatically committed.

Multiple SQL Statements | PDO_CUBRID supports Multiple SQL statements. Multiple SQL statements are separated by semicolons (;)
Schema Information | PDO_CUBRID implements a function PDO::cubrid_schema() to get schema information.
LOBs PDO_CUBRID supports BLOB/CLOB data type. The LOB in PDO is represented as a stream, so you can insert LOBs by binding a stream, and get LOBs by reading a stream returned by CUBRID PDO. For example:

Przykład #1 Insert LOBs in CUBRID PDO

<?php
$fp = fopen('lob_test.png', 'rb');

$sql_stmt = "INSERT INTO lob_test(name, content) VALUES('lob_test.png', ?)";

$stmt = $dbh->prepare($sql_stmt);
$ret = $stmt->bindParam(1, $fp, PDO::PARAM_LOB);
$ret = $stmt->execute();
?>

Przykład #2 Fetch LOBs in CUBRID PDO

<?php
$sql_stmt = "SELECT content FROM lob_test WHERE name='lob_test.png'";

$stmt = $dbh->prepare($sql_stmt);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_NUM);

header("Content-Type: image/png");
fpassthru($result[0]);
?>

Column meta The PDOStatement::getColumnMeta() in CUBRID PDO will return an associative array containing the following values:
  • type
  • name
  • table
  • def
  • precision
  • scale
  • not_null
  • auto_increment
  • unique_key
  • multiple_key
  • primary_key
  • foreign_key
  • reverse_index
  • reverse_unique

Stałe predefiniowane

Poniższe stałe są definiowane przez ten sterownik, i będą dostępne tylko, gdy to rozszerzenie będzie skompilowane z PHP lub załadowane dynamicznie przy starcie. Dodatkowo, te specyficzne dla sterownika stałe powinny być używane tylko przy użyciu tego konkretnego sterownika. Używanie atrybutów bazy MySQL przy użyciu sterownika PostgreSQL może prowadzić do nieprzewidzianego zachowania. Jeśli skrypt korzysta z wielu sterowników, do pobrania atrybutu PDO_ATTR_DRIVER_NAME, zawierającego nazwę sterownika, można zastosować funkcję PDO::getAttribute().

The following constants can be used when setting the database attribute. They can be passed to PDO::getAttribute() or PDO::setAttribute().

PDO::CUBRID attribute flags
Constant | Description
PDO::CUBRID_ATTR_ISOLATION_LEVEL | Transaction isolation level for the database connection.
PDO::CUBRID_ATTR_LOCK_TIMEOUT | Transaction timeout in seconds.
PDO::CUBRID_ATTR_MAX_STRING_LENGTH | Read only. The maximum string length for bit, varbit, char, varchar, nchar, nchar varying data types when using CUBRID PDO API.

The following constants can be used when setting the transaction isolation level. They can be passed to PDO::getAttribute() or returned by PDO::setAttribute().

PDO::CUBRID isolation level flags
Constant | Description
PDO::TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE | The lowest isolation level (1). A dirty, non-repeatable or phantom read may occur for the tuple and a non-repeatable read may occur for the table as well.
PDO::TRAN_COMMIT_CLASS_COMMIT_INSTANCE | A relatively low isolation level (2). A dirty read does not occur, but non-repeatable or phantom read may occur.
PDO::TRAN_REP_CLASS_UNCOMMIT_INSTANCE | The default isolation of CUBRID (3). A dirty, non-repeatable or phantom read may occur for the tuple, but repeatable read is ensured for the table.
PDO::TRAN_REP_CLASS_COMMIT_INSTANCE | A relatively low isolation level (4). A dirty read does not occur, but non-repeatable or phantom read may.
PDO::TRAN_REP_CLASS_REP_INSTANCE | A relatively high isolation level (5). A dirty or non-repeatable read does not occur, but a phantom read may.
PDO::TRAN_SERIALIZABLE | The highest isolation level (6). Problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.

The following constants can be used when getting schema information. They can be passed to PDO::cubrid_schema().

PDO::CUBRID schema flags
Constant | Description
PDO::CUBRID_SCH_TABLE | Get name and type of table in CUBRID.
PDO::CUBRID_SCH_VIEW | Get name and type of view in CUBRID.
PDO::CUBRID_SCH_QUERY_SPEC | Get the query definition of view.
PDO::CUBRID_SCH_ATTRIBUTE | Get the attributes of table column.
PDO::CUBRID_SCH_TABLE_ATTRIBUTE | Get the attributes of table.
PDO::CUBRID_SCH_METHOD | Get the instance method. The instance method is a method called by a class instance. It is used more often than the class method because most operations are executed in the instance.
PDO::CUBRID_SCH_TABLE_METHOD | Get the class method. The class method is a method called by a class object. It is usually used to create a new class instance or to initialize it. It is also used to access or update class attributes.
PDO::CUBRID_SCH_METHOD_FILE | Get the information of the file where the method of the table is defined.
PDO::CUBRID_SCH_SUPER_TABLE | Get the name and type of table which table inherites attributes from.
PDO::CUBRID_SCH_SUB_TABLE | Get the name and type of table which inherites attributes from this table.
PDO::CUBRID_SCH_CONSTRAINT | Get the table constraints.
PDO::CUBRID_SCH_TRIGGER | Get the table triggers.
PDO::CUBRID_SCH_TABLE_PRIVILEGE | Get the privilege information of table.
PDO::CUBRID_SCH_COL_PRIVILEGE | Get the privilege information of column.
PDO::CUBRID_SCH_DIRECT_SUPER_TABLE | Get the direct super table of table.
PDO::CUBRID_SCH_PRIMARY_KEY | Get the table primary key.
PDO::CUBRID_SCH_IMPORTED_KEYS | Get imported keys of table.
PDO::CUBRID_SCH_EXPORTED_KEYS | Get exported keys of table.
PDO::CUBRID_SCH_CROSS_REFERENCE | Get reference relationship of tow tables.

Spis treści

  • PDO_CUBRID DSN — Connecting to CUBRID databases
  • PDO::cubrid_schema — Get the requested schema information
PDO Drivers
PDO_CUBRID DSN
PDO Drivers


Connecting to CUBRID databases

CUBRID (PDO)
PDO::cubrid_schema
CUBRID (PDO)
PHP Manual

PDO_CUBRID DSN

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

PDO_CUBRID DSN — Connecting to CUBRID databases

Opis

The PDO_CUBRID Data Source Name (DSN) is composed of the following elements, delimited by semicolons:

DSN prefix

The DSN prefix is cubrid:.

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

Przykłady

Przykład #1 PDO_CUBRID DSN examples

The following example shows a PDO_CUBRID DSN for connecting to a CUBRID database:

cubrid:host=localhost;port=33000;dbname=demodb

CUBRID (PDO)
PDO::cubrid_schema
CUBRID (PDO)


Get the requested schema information

PDO_CUBRID DSN
MS SQL Server (PDO)
CUBRID (PDO)
PHP Manual

PDO::cubrid_schema

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

PDO::cubrid_schema — Get the requested schema information

Opis

array PDO::cubrid_schema ( int $schema_type [, string $table_name [, string $col_name ]] )

This function is used to get the requested schema information from database. You have to designate table_name, if you want to get information on certain table, col_name, if you want to get information on certain column (can be used only with PDO::CUBRID_SCH_COL_PRIVILEGE).

The result of this function is returned as a two-dimensional array (column (associative array) * row (numeric array)). The following tables shows types of schema and the column structure of the result array to be returned based on the schema type.

Result Composition of Each Type
Schema | Column Number | Column Name | Value
PDO::CUBRID_SCH_TABLE | 1 | NAME |
 | 2 | TYPE | 0:system table 1:view 2:table
PDO::CUBRID_SCH_VIEW | 1 | NAME |
 | 2 | TYPE | 1:view
PDO::CUBRID_SCH_QUERY_SPEC | 1 | QUERY_SPEC |
PDO::CUBRID_SCH_ATTRIBUTE / PDO::CUBRID_SCH_TABLE_ATTRIBUTE | 1 | ATTR_NAME |
 | 2 | DOMAIN |
 | 3 | SCALE |
 | 4 | PRECISION |
 | 5 | INDEXED | 1:indexed
 | 6 | NOT NULL | 1:not null
 | 7 | SHARED | 1:shared
 | 8 | UNIQUE | 1:unique
 | 9 | DEFAULT |
 | 10 | ATTR_ORDER | base:1
 | 11 | CLASS_NAME |
 | 12 | SOURCE_CLASS |
 | 13 | IS_KEY | 1:key
PDO::CUBRID_SCH_METHOD / PDO::CUBRID_SCH_TABLE_METHOD | 1 | NAME |
 | 2 | RET_DOMAIN |
 | 3 | ARG_DOMAIN |
PDO::CUBRID_SCH_METHOD_FILE | 1 | METHOD_FILE |
PDO::CUBRID_SCH_SUPER_TABLE / PDO::CUBRID_SCH_DIRECT_SUPER_TABLE / PDO::CUBRID_SCH_SUB_TABLE | 1 | CLASS_NAME |
 | 2 | TYPE | 0:system table 1:view 2:table
PDO::CUBRID_SCH_CONSTRAINT | 1 | TYPE | 0:unique 1:index 2:reverse unique 3:reverse index
 | 2 | NAME |
 | 3 | ATTR_NAME |
 | 4 | NUM_PAGES |
 | 5 | NUM_KEYS |
 | 6 | PRIMARY_KEY | 1:primary key
 | 7 | KEY_ORDER | base:1
PDO::CUBRID_SCH_TRIGGER | 1 | NAME |
 | 2 | STATUS |
 | 3 | EVENT |
 | 4 | TARGET_CLASS |
 | 5 | TARGET_ATTR |
 | 6 | ACTION_TIME |
 | 7 | ACTION |
 | 8 | PRIORITY |
 | 9 | CONDITION_TIME |
 | 10 | CONDITION |
PDO::CUBRID_SCH_TABLE_PRIVILEGE / PDO::CUBRID_SCH_COL_PRIVILEGE | 1 | CLASS_NAME / ATTR_NAME |
 | 2 | PRIVILEGE |
 | 3 | GRANTABLE |
PDO::CUBRID_SCH_PRIMARY_KEY | 1 | CLASS_NAME |
 | 2 | ATTR_NAME |
 | 3 | KEY_SEQ | base:1
 | 4 | KEY_NAME |
PDO::CUBRID_SCH_IMPORTED_KEYS / PDO::CUBRID_SCH_EXPORTED_KEYS / PDO::CUBRID_SCH_CROSS_REFERENCE | 1 | PKTABLE_NAME |
 | 2 | PKCOLUMN_NAME |
 | 3 | FKTABLE_NAME | base:1
 | 4 | FKCOLUMN_NAME |
 | 5 | KEY_SEQ | base:1
 | 6 | UPDATE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 7 | DELETE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 8 | FK_NAME |
 | 9 | PK_NAME |

Parametry

schema_type

Schema type that you want to know.

table_name

Table you want to know the schema of.

col_name

Column you want to know the schema of.

Zwracane wartości

Array containing the schema information, when process is successful;

FALSE, when process is unsuccessful

Przykłady

Przykład #1 A PDO::cubrid_schema() example

This example shows how to get primary key and foreign keys of table game.

<?php
$pk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_PRIMARY_KEY, "game");
print_r($pk_list);

$fk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_IMPORTED_KEYS, "game");
print_r($fk_list);
?>

Powyższy przykład wyświetli:

Result:
Array
(
    [0] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => athlete_code
            [KEY_SEQ] => 3
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

    [1] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => event_code
            [KEY_SEQ] => 2
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

    [2] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => host_year
            [KEY_SEQ] => 1
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

)
Array
(
    [0] => Array
        (
            [PKTABLE_NAME] => athlete
            [PKCOLUMN_NAME] => code
            [FKTABLE_NAME] => game
            [FKCOLUMN_NAME] => athlete_code
            [KEY_SEQ] => 1
            [UPDATE_RULE] => 1
            [DELETE_RULE] => 1
            [FK_NAME] => fk_game_athlete_code
            [PK_NAME] => pk_athlete_code
        )

    [1] => Array
        (
            [PKTABLE_NAME] => event
            [PKCOLUMN_NAME] => code
            [FKTABLE_NAME] => game
            [FKCOLUMN_NAME] => event_code
            [KEY_SEQ] => 1
            [UPDATE_RULE] => 1
            [DELETE_RULE] => 1
            [FK_NAME] => fk_game_event_code
            [PK_NAME] => pk_event_code
        )

)

PDO_CUBRID DSN
MS SQL Server (PDO)
CUBRID (PDO)


Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

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.

PDO_DBLIB is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Microsoft SQL Server and Sybase databases through the FreeTDS libary.

This extension is not available anymore on Windows with PHP 5.3 or later.

On Windows, you should use SqlSrv, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .

If it is not possible to use SqlSrv, you can use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.

Spis treści

  • PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases
PDO::cubrid_schema
PDO_DBLIB DSN
PDO Drivers


Connecting to Microsoft SQL Server and Sybase databases

MS SQL Server (PDO)
Firebird/Interbase (PDO)
MS SQL Server (PDO)
PHP Manual

PDO_DBLIB DSN

(PECL PDO_DBLIB >= 0.9.0)

PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases

Opis

The PDO_DBLIB Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is sybase: if PDO_DBLIB was linked against the Sybase ct-lib libraries, mssql: if PDO_DBLIB was linked against the Microsoft SQL Server libraries, or dblib: if PDO_DBLIB was linked against the FreeTDS libraries.

host

The hostname on which the database server resides. Defaults to 127.0.0.1.

dbname

The name of the database.

charset

The client character set.

appname

The application name (used in sysprocesses). Defaults to "PHP Generic DB-lib" or "PHP freetds".

secure

Currently unused.

Przykłady

Przykład #1 PDO_DBLIB DSN examples

The following examples show a PDO_DBLIB DSN for connecting to Microsoft SQL Server and Sybase databases:

mssql:host=localhost;dbname=testdb
sybase:host=localhost;dbname=testdb
dblib:host=localhost;dbname=testdb

MS SQL Server (PDO)
Firebird/Interbase (PDO)
MS SQL Server (PDO)


Firebird/Interbase Functions (PDO_FIREBIRD)

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.

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird and Interbase databases.

Instalacja

Use --with-pdo-firebird[=DIR] to install the PDO Firebird extension, where the optional [=DIR] is the Firebird base install directory.

$ ./configure --with-pdo-firebird

Stałe predefiniowane

Poniższe stałe są definiowane przez ten sterownik, i będą dostępne tylko, gdy to rozszerzenie będzie skompilowane z PHP lub załadowane dynamicznie przy starcie. Dodatkowo, te specyficzne dla sterownika stałe powinny być używane tylko przy użyciu tego konkretnego sterownika. Używanie atrybutów bazy MySQL przy użyciu sterownika PostgreSQL może prowadzić do nieprzewidzianego zachowania. Jeśli skrypt korzysta z wielu sterowników, do pobrania atrybutu PDO_ATTR_DRIVER_NAME, zawierającego nazwę sterownika, można zastosować funkcję PDO::getAttribute().

PDO::FB_ATTR_DATE_FORMAT (integer)

Available since PHP 5.3.0.

Sets the date format.

PDO::FB_ATTR_TIME_FORMAT (integer)

Sets the time format.

Available since PHP 5.3.0.

PDO::FB_ATTR_TIMESTAMP_FORMAT (integer)

Sets the timestamp format.

Available since PHP 5.3.0.

Spis treści

  • PDO_FIREBIRD DSN — Connecting to Firebird and Interbase databases
PDO_DBLIB DSN
PDO_FIREBIRD DSN
PDO Drivers


Connecting to Firebird and Interbase databases

Firebird/Interbase (PDO)
IBM (PDO)
Firebird/Interbase (PDO)
PHP Manual

PDO_FIREBIRD DSN

(PECL PDO_FIREBIRD >= 0.1.0)

PDO_FIREBIRD DSN — Connecting to Firebird and Interbase databases

Opis

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is firebird:.

dbname

The name of the database.

charset

The character set.

role

The SQL role name.

Przykłady

Przykład #1 PDO_FIREBIRD DSN examples

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird and Interbase databases:

firebird:dbname=DATABASE.GDE

Firebird/Interbase (PDO)
IBM (PDO)
Firebird/Interbase (PDO)


IBM Functions (PDO_IBM)

Wstęp

PDO_IBM is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to IBM databases.

Instalacja

To build the PDO_IBM extension, the DB2 Client v9.1 or later must be installed on the same system as PHP. The DB2 Client can be downloaded from the IBM » Application Development Site.

Informacja: Note

The DB2 Client v9.1 or later supports direct access to DB2 for Linux, UNIX, and Windows v8 and v9.1 servers.

The DB2 Client v9.1 also supports access to DB2 UDB for i5 and DB2 UDB for z/OS servers using the separately purchased » DB2 Connect product.

PDO_IBM is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_IBM extension. Issue the configure command to point to the location of your DB2 Client header files and libraries as follows:

bash$ ./configure --with-pdo-ibm=/path/to/sqllib[,shared]
The configure command defaults to the value of the DB2DIR environment variable.

Spis treści

  • PDO_IBM DSN — Connecting to IBM databases
PDO_FIREBIRD DSN
PDO_IBM DSN
PDO Drivers


Connecting to IBM databases

IBM (PDO)
Informix (PDO)
IBM (PDO)
PHP Manual

PDO_IBM DSN

(PECL PDO_IBM >= 0.9.0)

PDO_IBM DSN — Connecting to IBM databases

Opis

The PDO_IBM Data Source Name (DSN) is based on the IBM CLI DSN. The major components of the PDO_IBM DSN are:

DSN prefix

The DSN prefix is ibm:.

DSN

The DSN can be any of the following:

  • a) Data source setup using db2cli.ini or odbc.ini

  • b) Catalogued database name i.e. database alias in the DB2 client catalog

  • c) Complete connection string in the following format: DRIVER={IBM DB2 ODBC DRIVER};DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password; where the parameters represent the following values:

    database

    The name of the database.

    hostname

    The hostname or IP address of the database server.

    port

    The TCP/IP port on which the database is listening for requests.

    username

    The username with which you are connecting to the database.

    password

    The password with which you are connecting to the database.

Przykłady

Przykład #1 PDO_IBM DSN example using db2cli.ini

The following example shows a PDO_IBM DSN for connecting to an DB2 database cataloged as DB2_9 in db2cli.ini:

$db = new PDO("ibm:DSN=DB2_9", "", "");

[DB2_9]
Database=testdb
Protocol=tcpip
Hostname=11.22.33.444
Servicename=56789

Przykład #2 PDO_IBM DSN example using a connection string

The following example shows a PDO_IBM DSN for connecting to an DB2 database named testdb using the DB2 CLI connection string syntax.

$db = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
  "HOSTNAME=11.22.33.444;PORT=56789;PROTOCOL=TCPIP;", "testuser", "tespass");

IBM (PDO)
Informix (PDO)
IBM (PDO)


Informix Functions (PDO_INFORMIX)

Wstęp

PDO_INFORMIX is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Informix databases.

Instalacja

To build the PDO_INFORMIX extension, the Informix Client SDK 2.81 UC1 or higher must be installed on the same system as PHP. The Informix Client SDK is available from the » IBM Informix Support Site.

PDO_INFORMIX is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the PDO_INFORMIX extension. Issue the configure command to point to the location of your Informix Client SDK header files and libraries as follows:

   bash$ ./configure --with-pdo-informix=/path/to/SDK[,shared]
The configure command defaults to the value of the INFORMIXDIR environment variable.

Scrollable cursors

PDO_INFORMIX supports scrollable cursors; however, they are not enabled by default. To enable scrollable cursor support, you must either set ENABLESCROLLABLECURSORS=1 in the corresponding ODBC connection settings in odbc.ini or pass the EnableScrollableCursors=1 clause in the DSN connection string.

Spis treści

  • PDO_INFORMIX DSN — Connecting to Informix databases
PDO_IBM DSN
PDO_INFORMIX DSN
PDO Drivers


Connecting to Informix databases

Informix (PDO)
MySQL (PDO)
Informix (PDO)
PHP Manual

PDO_INFORMIX DSN

(PECL PDO_INFORMIX >= 0.1.0)

PDO_INFORMIX DSN — Connecting to Informix databases

Opis

The PDO_INFORMIX Data Source Name (DSN) is based on the Informix ODBC DSN string. Details on configuring an Informix ODBC DSN are available from the » Informix Dynamic Server Information Center. The major components of the PDO_INFORMIX DSN are:

DSN prefix

The DSN prefix is informix:.

DSN

The DSN can be either a data source setup using odbc.ini or a complete » connection string.

Przykłady

Przykład #1 PDO_INFORMIX DSN example using odbc.ini

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database cataloged as Infdrv33 in odbc.ini:

$db = new PDO("informix:DSN=Infdrv33", "", "");

[ODBC Data Sources]
Infdrv33=INFORMIX 3.3 32-BIT

[Infdrv33]
Driver=/opt/informix/csdk_2.81.UC1G2/lib/cli/iclis09b.so
Description=INFORMIX 3.3 32-BIT
Database=common_db
LogonID=testuser
pwd=testpass
Servername=ids_server
DB_LOCALE=en_US.819
OPTIMIZEAUTOCOMMIT=1
ENABLESCROLLABLECURSORS=1

Przykład #2 PDO_INFORMIX DSN example using a connection string

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database named common_db using the Informix connection string syntax.

$db = new PDO("informix:host=host.domain.com; service=9800;
    database=common_db; server=ids_server; protocol=onsoctcp;
    EnableScrollableCursors=1", "testuser", "tespass");

Informix (PDO)
MySQL (PDO)
Informix (PDO)


MySQL Functions (PDO_MYSQL)

Wstęp

PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL 3.x, 4.x and 5.x databases.

PDO_MYSQL will take advantage of native prepared statement support present in MySQL 4.1 and higher. If you're using an older version of the mysql client libraries, PDO will emulate them for you.

Ostrzeżenie

Beware: Some MySQL table types (storage engines) do not support transactions. When writing transactional database code using a table type that does not support transactions, MySQL will pretend that a transaction was initiated successfully. In addition, any DDL queries issued will implicitly commit any pending transactions.

Instalacja

Use --with-pdo-mysql[=DIR] to install the PDO MySQL extension, where the optional [=DIR] is the MySQL base install directory. If mysqlnd is passed as [=DIR], then the MySQL native driver will be used.

Optionally, the --with-mysql-sock[=DIR] sets to location to the MySQL unix socket pointer for all MySQL extensions, including PDO_MYSQL. If unspecified, the default locations are searched.

Optionally, the --with-zlib-dir[=DIR] is used to set the path to the libz install prefix.

$ ./configure --with-pdo-mysql --with-mysql-sock=/var/mysql/mysql.sock

Rejestr zmian
Wersja | Opis
5.4.0 | MySQL client libraries 4.1 and below are no longer supported.

Stałe predefiniowane

Poniższe stałe są definiowane przez ten sterownik, i będą dostępne tylko, gdy to rozszerzenie będzie skompilowane z PHP lub załadowane dynamicznie przy starcie. Dodatkowo, te specyficzne dla sterownika stałe powinny być używane tylko przy użyciu tego konkretnego sterownika. Używanie atrybutów bazy MySQL przy użyciu sterownika PostgreSQL może prowadzić do nieprzewidzianego zachowania. Jeśli skrypt korzysta z wielu sterowników, do pobrania atrybutu PDO_ATTR_DRIVER_NAME, zawierającego nazwę sterownika, można zastosować funkcję PDO::getAttribute().

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (integer)
If this attribute is set to TRUE on a PDOStatement, the MySQL driver will use the buffered versions of the MySQL API. If you're writing portable code, you should use PDOStatement::fetchAll() instead.

Przykład #1 Forcing queries to be buffered in mysql

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
    $stmt = $db->prepare('select * from foo',
        array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
} else {
    die("my application only works with mysql; I should use \$stmt->fetchAll() instead");
}
?>

PDO::MYSQL_ATTR_LOCAL_INFILE (integer)

Enable LOAD LOCAL INFILE.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_INIT_COMMAND (integer)

Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_READ_DEFAULT_FILE (integer)

Read options from the named option file instead of from my.cnf. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_READ_DEFAULT_GROUP (integer)

Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_MAX_BUFFER_SIZE (integer)

Maximum buffer size. Defaults to 1 MiB. This constant is not supported when compiled against mysqlnd.

PDO::MYSQL_ATTR_DIRECT_QUERY (integer)

Perform direct queries, don't use prepared statements.

PDO::MYSQL_ATTR_FOUND_ROWS (integer)

Return the number of found (matched) rows, not the number of changed rows.

PDO::MYSQL_ATTR_IGNORE_SPACE (integer)

Permit spaces after function names. Makes all functions names reserved words.

PDO::MYSQL_ATTR_COMPRESS (integer)

Enable network communication compression. This is not supported when compiled against mysqlnd.

Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

PDO_MYSQL Configuration Options
Nazwa | Domyślnie | Możliwość zmian
pdo_mysql.default_socket | "/tmp/mysql.sock" | PHP_INI_SYSTEM
pdo_mysql.debug | 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.

pdo_mysql.default_socket string

Sets a Unix domain socket. This value can either be set at compile time if a domain socket is found at configure. This ini setting is Unix only.

pdo_mysql.debug boolean

Enables debugging for PDO_MYSQL. This setting is only available when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.

Spis treści

  • PDO_MYSQL DSN — Connecting to MySQL databases
PDO_INFORMIX DSN
PDO_MYSQL DSN
PDO Drivers


Connecting to MySQL databases

MySQL (PDO)
MS SQL Server (PDO)
MySQL (PDO)
PHP Manual

PDO_MYSQL DSN

(PECL PDO_MYSQL >= 0.1.0)

PDO_MYSQL DSN — Connecting to MySQL databases

Opis

The PDO_MYSQL Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is mysql:.

host

The hostname on which the database server resides.

port

The port number where the database server is listening.

dbname

The name of the database.

unix_socket

The MySQL Unix socket (shouldn't be used with host or port).

charset

The character set.

Prior to PHP 5.3.6, this element was silently ignored. The same behaviour can be partly replicated with the PDO::MYSQL_ATTR_INIT_COMMAND driver option, as the following example shows.

Ostrzeżenie

The method in the below example can only be used with character sets that share the same lower 7 bit representation as ASCII, such as ISO-8859-1 and UTF-8. Users using character sets that have different representations (such as UTF-16 or Big5) must use the charset option provided in PHP 5.3.6 and later versions.

Przykład #1 Setting the connection character set to UTF-8 prior to PHP 5.3.6

<?php
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

$dbh = new PDO($dsn, $username, $password, $options);
?>

Rejestr zmian

Wersja | Opis
5.3.6 | Prior to version 5.3.6, charset was ignored.

Przykłady

Przykład #2 PDO_MYSQL DSN examples

The following example shows a PDO_MYSQL DSN for connecting to MySQL databases:

mysql:host=localhost;dbname=testdb
More complete examples:
mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb

Notatki

Informacja: Unix only:

When the host name is set to "localhost", then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against libmysql then the location of the socket file is at libmysql's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.

MySQL (PDO)
MS SQL Server (PDO)
MySQL (PDO)


Microsoft SQL Server Functions (PDO_SQLSRV)

Wstęp

PDO_SQLSRV is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MS SQL Server (starting with SQL Server 2005) and SQL Azure databases.

Instalacja

The PDO_SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The PDO_SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_pdo_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_pdo_sqlsrv_52_ts_vc6.dll file.

For more information about system requirements, see » SQLSRV System Requirements.

The PDO_SQLSRV extension is only compatible with PHP running on Windows. For Linux, see ODBC and » Microsoft's SQL Server ODBC Driver for Linux.

Stałe predefiniowane

Poniższe stałe są definiowane przez ten sterownik, i będą dostępne tylko, gdy to rozszerzenie będzie skompilowane z PHP lub załadowane dynamicznie przy starcie. Dodatkowo, te specyficzne dla sterownika stałe powinny być używane tylko przy użyciu tego konkretnego sterownika. Używanie atrybutów bazy MySQL przy użyciu sterownika PostgreSQL może prowadzić do nieprzewidzianego zachowania. Jeśli skrypt korzysta z wielu sterowników, do pobrania atrybutu PDO_ATTR_DRIVER_NAME, zawierającego nazwę sterownika, można zastosować funkcję PDO::getAttribute().

PDO::SQLSRV_TXN_READ_UNCOMMITTED (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Uncommitted.
PDO::SQLSRV_TXN_READ_COMMITTED (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Committed.
PDO::SQLSRV_TXN_REPEATABLE_READ (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Repeateable Read.
PDO::SQLSRV_TXN_SNAPSHOT (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Snapshot.
PDO::SQLSRV_TXN_SERIALIZABLE (integer)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Serializable.
PDO::SQLSRV_ENCODING_BINARY (integer)
Specifies that data is sent/retrieved as a raw byte stream to/from the server without performing encoding or translation. This constant can be passed to PDOStatement::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_SYSTEM (integer)
Specifies that data is sent/retrieved to/from the server as 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_UTF8 (integer)
Specifies that data is sent/retrieved to/from the server in UTF-8 encoding. This is the default encoding. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_DEFAULT (integer)
Specifies that data is sent/retrieved to/from the server according to PDO::SQLSRV_ENCODING_SYSTEM if specified during connection. The connection's encoding is used if specified in a prepare statement. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ATTR_QUERY_TIMEOUT (integer)
A non-negative integer representing the timeout period, in seconds. Zero (0) is the default and means no timeout. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, and PDO::prepare.
PDO::SQLSRV_ATTR_DIRECT_QUERY (integer)
Indicates that a query should be executed directly, without being prepared. This constant can be passed to PDO::setAttribute, and PDO::prepare. For more information, see » Direct and Prepared Statement Execution.

Spis treści

  • PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases
PDO_MYSQL DSN
PDO_SQLSRV DSN
PDO Drivers


Connecting to MS SQL Server and SQL Azure databases

MS SQL Server (PDO)
Oracle (PDO)
MS SQL Server (PDO)
PHP Manual

PDO_SQLSRV DSN

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

PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases

Opis

The PDO_SQLSRV Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is sqlsrv:.

APP

The application name used in tracing.

ConnectionPooling

Specifies whether the connection is assigned from a connection pool (1 or TRUE) or not (0 or FALSE).

Database

The name of the database.

Encrypt

Specifies whether the communication with SQL Server is encrypted (1 or TRUE) or unencrypted (0 or FALSE).

Failover_Partner

Specifies the server and instance of the database's mirror (if enabled and configured) to use when the primary server is unavailable.

LoginTimeout

Specifies the number of seconds to wait before failing the connection attempt.

MultipleActiveResultSets

Disables or explicitly enables support for multiple active Result sets (MARS).

QuotedId

Specifies whether to use SQL-92 rules for quoted identifiers (1 or TRUE) or to use legacy Transact-SQL rules (0 or false).

Server

The name of the database server.

TraceFile

Specifies the path for the file used for trace data.

TraceOn

Specifies whether ODBC tracing is enabled (1 or TRUE) or disabled (0 or FALSE) for the connection being established.

TransactionIsolation

Specifies the transaction isolation level. The accepted values for this
option are PDO::SQLSRV_TXN_READ_UNCOMMITTED, PDO::SQLSRV_TXN_READ_COMMITTED,
PDO::SQLSRV_TXN_REPEATABLE_READ, PDO::SQLSRV_TXN_SNAPSHOT, and
PDO::SQLSRV_TXN_SERIALIZABLE.

TrustServerCertificate

Specifies whether the client should trust (1 or TRUE) or reject (0 or FALSE) a self-signed server certificate.

WSID

Specifies the name of the computer for tracing.

Przykłady

Przykład #1 PDO_SQLSRV DSN examples

The following example shows how to connecto to a specified MS SQL Server database:

$c = new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");

The following example shows how to connect to a MS SQL Server database on a specified port:

$c = new PDO("sqlsrv:Server=localhost,1521;Database=testdb", "UserName", "Password");

The following example shows how to connecto to a SQL Azure database with server ID 12345abcde. Note that when you connect to SQL Azure with PDO, your username will be UserName@12345abcde (UserName@ServerId).

$c = new PDO("sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName@12345abcde", "Password");

MS SQL Server (PDO)
Oracle (PDO)
MS SQL Server (PDO)


Oracle Functions (PDO_OCI)

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.

PDO_OCI is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Oracle databases through the OCI library.

Instalacja

Use --with-pdo-oci[=DIR] to install the PDO Oracle OCI extension, where the optional [=DIR] is the Oracle Home directory. [=DIR] defaults to the $ORACLE_HOME environment variable.

Use --with-pdo-oci=instantclient,prefix,version for an Oracle Instant Client SDK, where prefix and version are configured.

// Using $ORACLE_HOME
$ ./configure --with-pdo-oci

// Using OIC for Linux with 10.2.0.3 RPMs with a /usr prefix
$ ./configure --with-pdo-oci=instantclient,/usr,10.2.0.3

Spis treści

  • PDO_OCI DSN — Connecting to Oracle databases
PDO_SQLSRV DSN
PDO_OCI DSN
PDO Drivers


Connecting to Oracle databases

Oracle (PDO)
ODBC and DB2 (PDO)
Oracle (PDO)
PHP Manual

PDO_OCI DSN

(PECL PDO_OCI >= 0.1.0)

PDO_OCI DSN — Connecting to Oracle databases

Opis

The PDO_OCI Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is oci:.

dbname (Oracle Instant Client)

The URI for the Oracle Instant Client connection takes the form of dbname=//hostname:port-number/database. If you are connecting to a database defined in tnsnames.ora, use only the name of the database: dbname=database.

charset

The client-side character set for the current environment handle.

Przykłady

Przykład #1 PDO_OCI DSN examples

The following examples show a PDO_OCI DSN for connecting to Oracle databases:

// Connect to a database defined in tnsnames.ora
oci:dbname=mydb

// Connect using the Oracle Instant Client
oci:dbname=//localhost:1521/mydb

Oracle (PDO)
ODBC and DB2 (PDO)
Oracle (PDO)


ODBC and DB2 Functions (PDO_ODBC)

Wstęp

PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers or through the IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently supports three different "flavours" of database drivers:

ibm-db2

Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 client.

unixODBC

Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.

generic

Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.

On Windows, PDO_ODBC is built into the PHP core by default. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN, and is the recommended driver for connecting to Microsoft SQL Server databases.

Instalacja

PDO_ODBC on UNIX systems

  1. As of PHP 5.1, PDO_ODBC is included in the PHP source. You can compile the PDO_ODBC extension as either a static or shared module using the following configure commands.

    ibm_db2

    ./configure --with-pdo-odbc=ibm-db2,/opt/IBM/db2/V8.1/
    To build PDO_ODBC with the ibm-db2 flavour, you have to have previously installed the DB2 application development headers on the same machine on which you are compiling PDO_ODBC. The DB2 application development headers are an installable option in the DB2 servers, and are also available as part of the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database » support site.

    If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib.

    unixODBC

    ./configure --with-pdo-odbc=unixODBC,/usr/local
    If you do not supply a location for the unixODBC libraries and headers to the configure command, PDO_ODBC defaults to /usr/local.

    generic
    ./configure --with-pdo-odbc=generic,/usr/local,libname,ldflags,cflags

Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

PDO_ODBC Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Available since PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Available since PHP 5.1.1. Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
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.

pdo_odbc.connection_pooling string

Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off" (equals to ""). The parameter describes how strict the connection manager should be when matching connection parameters to existing pooled connections. strict is the recommend default, and will result in the use of cached connections only when all the connection parameters match exactly. relaxed will result in the use of cached connections when similar connection parameters are used. This can result in increased use of the cache, at the risk of bleeding connection information between (for example) virtual hosts.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

Ostrzeżenie

relaxed matching should not be used on a shared server, for security reasons.

Wskazówka

Leave this setting at the default strict setting unless you have good reason to change it.

pdo_odbc.db2_instance_name string

If you compile PDO_ODBC using the db2 flavour, this setting sets the value of the DB2INSTANCE environment variable on Linux and UNIX operating systems to the specified name of the DB2 instance. This enables PDO_ODBC to resolve the location of the DB2 libraries and make cataloged connections to DB2 databases.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

This setting has no effect on Windows.

Spis treści

  • PDO_ODBC DSN — Connecting to ODBC or DB2 databases
PDO_OCI DSN
PDO_ODBC DSN
PDO Drivers


Connecting to ODBC or DB2 databases

ODBC and DB2 (PDO)
PostgreSQL (PDO)
ODBC and DB2 (PDO)
PHP Manual

PDO_ODBC DSN

(PECL PDO_ODBC >= 0.1.0)

PDO_ODBC DSN — Connecting to ODBC or DB2 databases

Opis

The PDO_ODBC Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is odbc:. If you are connecting to a database cataloged in the ODBC driver manager or the DB2 catalog, you can append the cataloged name of the database to the DSN.

DSN

The name of the database as cataloged in the ODBC driver manager or the DB2 catalog. Alternately, you can provide a complete ODBC connection string to connect to a database as described at » http://www.connectionstrings.com/.

UID

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

PWD

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

Przykłady

Przykład #1 PDO_ODBC DSN example (ODBC driver manager)

The following example shows a PDO_ODBC DSN for connecting to an ODBC database cataloged as testdb in the ODBC driver manager:

odbc:testdb

Przykład #2 PDO_ODBC DSN example (IBM DB2 uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to an IBM DB2 database named SAMPLE using the full ODBC DSN syntax:

odbc:DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME=localhost;PORT=50000;DATABASE=SAMPLE;PROTOCOL=TCPIP;UID=db2inst1;PWD=ibmdb2;

Przykład #3 PDO_ODBC DSN example (Microsoft Access uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to a Microsoft Access database stored at C:\db.mdb using the full ODBC DSN syntax:

odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\db.mdb;Uid=Admin

ODBC and DB2 (PDO)
PostgreSQL (PDO)
ODBC and DB2 (PDO)


PostgreSQL Functions (PDO_PGSQL)

Wstęp

PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to PostgreSQL databases.

Typy zasobów

This extension defines a stream resource returned by PDO::pgsqlLOBOpen().

Instalacja

Use --with-pdo-pgsql[=DIR] to install the PDO PostgreSQL extension, where the optional [=DIR] is the PostgreSQL base install directory, or the path to pg_config.

$ ./configure --with-pdo-pgsql

Spis treści

  • PDO_PGSQL DSN — Connecting to PostgreSQL databases
  • PDO::pgsqlLOBCreate — Creates a new large object
  • PDO::pgsqlLOBOpen — Opens an existing large object stream
  • PDO::pgsqlLOBUnlink — Deletes the large object
PDO_ODBC DSN
PDO_PGSQL DSN
PDO Drivers


Connecting to PostgreSQL databases

PostgreSQL (PDO)
PDO::pgsqlLOBCreate
PostgreSQL (PDO)
PHP Manual

PDO_PGSQL DSN

(PECL PDO_PGSQL >= 0.1.0)

PDO_PGSQL DSN — Connecting to PostgreSQL databases

Opis

The PDO_PGSQL Data Source Name (DSN) is composed of the following elements, delimited by spaces or semicolons:

DSN prefix

The DSN prefix is pgsql:.

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

user

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

password

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

Informacja:

The bytea fields are returned as streams.

Przykłady

Przykład #1 PDO_PGSQL DSN examples

The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL database:

pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass

PostgreSQL (PDO)
PDO::pgsqlLOBCreate
PostgreSQL (PDO)


Creates a new large object

PDO_PGSQL DSN
PDO::pgsqlLOBOpen
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBCreate

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBCreate — Creates a new large object

Opis

string PDO::pgsqlLOBCreate ( void )

PDO::pgsqlLOBCreate() creates a large object and returns the OID of that object. You may then open a stream on the object using PDO::pgsqlLOBOpen() to read or write data to it. The OID can be stored in columns of type OID and be used to reference the large object, without causing the row to grow arbitrarily large. The large object will continue to live in the database until it is removed by calling PDO::pgsqlLOBUnlink().

Large objects can be up to 2GB in size, but are cumbersome to use; you need to ensure that PDO::pgsqlLOBUnlink() is called prior to deleting the last row that references its OID from your database. In addition, large objects have no access controls. As an alternative, try the bytea column type; recent versions of PostgreSQL allow bytea columns of up to 1GB in size and transparently manage the storage for optimal row size.

Informacja: This function must be called within a transaction.

Parametry

PDO::pgsqlLOBCreate() takes no parameters.

Zwracane wartości

Returns the OID of the newly created large object on success, or FALSE on failure.

Przykłady

Przykład #1 A PDO::pgsqlLOBCreate() example

This example creates a new large object and copies the contents of a file into it. The OID is then stored into a table.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$oid = $db->pgsqlLOBCreate();
$stream = $db->pgsqlLOBOpen($oid, 'w');
$local = fopen($filename, 'rb');
stream_copy_to_stream($local, $stream);
$local = null;
$stream = null;
$stmt = $db->prepare("INSERT INTO BLOBS (ident, oid) VALUES (?, ?)");
$stmt->execute(array($some_id, $oid));
$db->commit();
?>

Zobacz też:

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_create() - Tworzy wielki obiekt (Large Object - LO)

PDO_PGSQL DSN
PDO::pgsqlLOBOpen
PostgreSQL (PDO)


Opens an existing large object stream

PDO::pgsqlLOBCreate
PDO::pgsqlLOBUnlink
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBOpen

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBOpen — Opens an existing large object stream

Opis

resource PDO::pgsqlLOBOpen ( string $oid [, string $mode = "rb" ] )

PDO::pgsqlLOBOpen() opens a stream to access the data referenced by oid. If mode is r, the stream is opened for reading, if mode is w, then the stream will be opened for writing. You can use all the usual filesystem functions, such as fread(), fwrite() and fgets() to manipulate the contents of the stream.

Informacja: This function, and all manipulations of the large object, must be called and carried out within a transaction.

Parametry

oid

A large object identifier.

mode

If mode is r, open the stream for reading. If mode is w, open the stream for writing.

Zwracane wartości

Returns a stream resource on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 A PDO::pgsqlLOBOpen() example

Following on from the PDO::pgsqlLOBCreate() example, this code snippet retrieves the large object from the database and outputs it to the browser.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("select oid from BLOBS where ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
fpassthru($lob);
?>

Zobacz też:

  • PDO::pgsqlLOBCreate() - Creates a new large object
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_open() - Otwiera wielki obiekt (Large Object - LO)

PDO::pgsqlLOBCreate
PDO::pgsqlLOBUnlink
PostgreSQL (PDO)


Deletes the large object

PDO::pgsqlLOBOpen
SQLite (PDO)
PostgreSQL (PDO)
PHP Manual

PDO::pgsqlLOBUnlink

(PHP 5 >= 5.1.2, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBUnlink — Deletes the large object

Opis

bool PDO::pgsqlLOBUnlink ( string $oid )

Deletes a large object from the database identified by OID.

Informacja: This function must be called within a transaction.

Parametry

oid

A large object identifier

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A PDO::pgsqlLOBUnlink() example

This example unlinks a large object from the database prior to deleting the row that references it from the blobs table we've been using in our PDO::pgsqlLOBCreate() and PDO::pgsqlLOBOpen() examples.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$db->pgsqlLOBUnlink($oid);
$stmt = $db->prepare("DELETE FROM BLOBS where ident = ?");
$stmt->execute(array($some_id));
$db->commit();
?>

Zobacz też:

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBCreate() - Creates a new large object

PDO::pgsqlLOBOpen
SQLite (PDO)
PostgreSQL (PDO)


SQLite Functions (PDO_SQLITE)

Wstęp

PDO_SQLITE is a driver that implements the PHP Data Objects (PDO) interface to enable access to SQLite 3 databases.

In PHP 5.1, the SQLite extension also provides a driver for SQLite 2 databases; while it is not technically a part of the PDO_SQLITE driver, it behaves similarly, so it is documented alongside it. The SQLite 2 driver for PDO is provided primarily to make it easier to import legacy SQLite 2 database files into an application that uses the faster, more efficient SQLite 3 driver. As a result, the SQLite 2 driver is not as feature-rich as the SQLite 3 driver.

Informacja:

PDO_SQLITE allows using strings apart from streams together with PDO::PARAM_LOB.

Instalacja

The PDO_SQLITE PDO driver is enabled by default. To disable, --without-pdo-sqlite[=DIR] may be used, where the optional [=DIR] is the sqlite base install directory.

Spis treści

  • PDO_SQLITE DSN — Connecting to SQLite databases
  • PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements
  • PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements
PDO::pgsqlLOBUnlink
PDO_SQLITE DSN
PDO Drivers


Connecting to SQLite databases

SQLite (PDO)
PDO::sqliteCreateAggregate
SQLite (PDO)
PHP Manual

PDO_SQLITE DSN

(PECL PDO_SQLITE >= 0.2.0)

PDO_SQLITE DSN — Connecting to SQLite databases

Opis

The PDO_SQLITE Data Source Name (DSN) is composed of the following elements:

DSN prefix (SQLite 3)

The DSN prefix is sqlite:.

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append :memory: to the DSN prefix.

DSN prefix (SQLite 2)

The SQLite extension in PHP 5.1 provides a PDO driver that supports accessing and creating SQLite 2 databases. This enables you to access databases you may have created with the SQLite extension in previous versions of PHP.

Informacja:

The sqlite2 driver is only available in PHP 5.1.x if you have enabled both PDO and ext/sqlite. It is not currently available via PECL.

The DSN prefix for connecting to SQLite 2 databases is sqlite2:.

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append :memory: to the DSN prefix.

Przykłady

Przykład #1 PDO_SQLITE DSN examples

The following examples show PDO_SQLITE DSN for connecting to SQLite databases:

sqlite:/opt/databases/mydb.sq3
sqlite::memory:
sqlite2:/opt/databases/mydb.sq2
sqlite2::memory:

SQLite (PDO)
PDO::sqliteCreateAggregate
SQLite (PDO)


Registers an aggregating User Defined Function for use in SQL statements

PDO_SQLITE DSN
PDO::sqliteCreateFunction
SQLite (PDO)
PHP Manual

PDO::sqliteCreateAggregate

(PHP 5 >= 5.1.0, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements

Opis

bool PDO::sqliteCreateAggregate ( string $function_name , callback $step_func , callback $finalize_func [, int $num_args ] )
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.

This method is similar to PDO::sqliteCreateFunction except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this method and PDO::sqliteCreateFunction is that two functions are required to manage the aggregate.

Parametry

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.

This function need to be defined as:

step ( mixed $context , int $rownumber , mixed $value1 [, mixed $value2 [, mixed $.. ]] )

context will be NULL for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.

rownumber will hold the current row number.

finalize_func

Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

fini ( mixed $context , int $rownumber )

context will hold the return value from the very last call to the step function.

rownumber will hold the number of rows over which the aggregate was performed.

The return value of this function will be used as the return value for the aggregate.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
    $insert->execute(array($str));
}
$insert = null;

function max_len_step(&$context, $rownumber, $string)
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
    return $context;
}

function max_len_finalize(&$context, $rownumber)
{
    return $context;
}

$db->sqliteCreateAggregate('max_len', 'max_len_step', 'max_len_finalize');

var_dump($db->query('SELECT max_len(a) from strings')->fetchAll());

?>

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Wskazówka

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Wskazówka

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

Informacja:

This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

Zobacz też:

  • PDO::sqliteCreateFunction
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

PDO_SQLITE DSN
PDO::sqliteCreateFunction
SQLite (PDO)


Registers a User Defined Function for use in SQL statements

PDO::sqliteCreateAggregate
4D (PDO)
SQLite (PDO)
PHP Manual

PDO::sqliteCreateFunction

(PHP 5 >= 5.1.0, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements

Opis

bool PDO::sqliteCreateFunction ( string $function_name , callback $callback [, int $num_args ] )
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.

This method allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Parametry

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Informacja: Callback functions should return a type understood by SQLite (i.e. scalar type).

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 PDO::sqliteCreateFunction() example

<?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

$db = new PDO('sqlite:sqlitedb');
$db->sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db->query('SELECT md5rev(filename) FROM files')->fetchAll();
?>

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach loop after you have queried for the data.

Wskazówka

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

Informacja:

This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

Zobacz też:

  • PDO::sqliteCreateAggregate
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

PDO::sqliteCreateAggregate
4D (PDO)
SQLite (PDO)


4D Functions (PDO_4D)

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.

PDO_4D is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to 4D databases.

4D is an integrated platform that speeds and simplifies the development and deployment of business applications, used in over 70 countries, by a community of thousands of developers and vertical solution providers, with millions of end-users worldwide.

By offering a suite of integrated tools such as an ANSI SQL relational and transactional database, a graphical development environment, a fourth-generation language with over 1000 high-level commands, a built-in HTTP server, application server, etc., 4D facilitates the creation and maintenance of applications from one to hundreds of simultaneous users, whether on Windows, Mac or from any Web client.

4D is also an open platform, offering a complete API for plug-in creation, including various connectors that allow it to act as a back-end or front-end for many environments (Oracle via OCI, SOAP client or server, Flex data source, all ODBC databases, XML over HTTP, etc.)

In addition to the ability to interact with 4D applications across Web Services, 4D databases can now be directly accessed using the PDO_4D driver.

More details about the 4D development environment on » http://www.4d.com/.

PDO_4D is known to work with 4D versions 12 beta and up, for Mac OS X and Windows. Older plat-forms may work, but are unsupported.

Spis treści

  • PDO_4D DSN — Connecting to 4D SQL server
  • Constants for PDO_4D — Constants for PDO_4D
  • SQL types with PDO_4D and PHP — SQL types with PDO_4D and PHP
  • SQL acceptable by 4D — PDO and SQL 4D
  • Examples with PDO_4D — Examples PDO_4D
PDO::sqliteCreateFunction
PDO_4D DSN
PDO Drivers


Connecting to 4D SQL server

4D (PDO)
Constants for PDO_4D
4D (PDO)
PHP Manual

PDO_4D DSN

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

PDO_4D DSN — Connecting to 4D SQL server

Opis

The PDO_4D DSN consists of:

DSN prefix

The DSN prefix is 4D:.

host

The host on which the 4D SQL server is.

port

The port number for the server. This is optional.

user

The login name when connecting to the database.

password

The password for the above login.

dbname

The name of the database. This parameter is optional, and it is not used.

charset

The 4D character set.

Przykłady

Przykład #1 DSN examples for PDO_4D

The following examples has two DSN for PDO_4D, that connects to a 4D database :

4D:host=localhost;charset=UTF-8
Other possible values :
4D:host=localhost
4D:

4D (PDO)
Constants for PDO_4D
4D (PDO)


Constants for PDO_4D

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

Constants for PDO_4D — Constants for PDO_4D

Stałe predefiniowane

Poniższe stałe są definiowane przez ten sterownik, i będą dostępne tylko, gdy to rozszerzenie będzie skompilowane z PHP lub załadowane dynamicznie przy starcie. Dodatkowo, te specyficzne dla sterownika stałe powinny być używane tylko przy użyciu tego konkretnego sterownika. Używanie atrybutów bazy MySQL przy użyciu sterownika PostgreSQL może prowadzić do nieprzewidzianego zachowania. Jeśli skrypt korzysta z wielu sterowników, do pobrania atrybutu PDO_ATTR_DRIVER_NAME, zawierającego nazwę sterownika, można zastosować funkcję PDO::getAttribute().

PDO::FOURD_ATTR_CHARSET (integer)

Change the charset in which 4D returns data. (Default is UTF-8).

PDO::FOURD_ATTR_PREFERRED_IMAGE_TYPES (integer)

The requested format of the image, when selecting a row with a column type PICTURE. It may be any type that 4D supports.

PDO_4D DSN
SQL types with PDO_4D and PHP
4D (PDO)


SQL types with PDO_4D and PHP

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

SQL types with PDO_4D and PHP — SQL types with PDO_4D and PHP

Supported SQL types
Type SQL 4D | Equivalent 4D | Note
ALPHA_NUMERIC | TEXT |
VARCHAR | TEXT |
TEXT | TEXT |
TIMESTAMP | DATE |
INTERVAL | HOUR |
DURATION | HOUR |
BOOLEAN | BOOLEAN |
BIT | BOOLEAN |
BYTE | INT32 |
INT16 | SMALLINT |
SMALLINT | SMALLINT |
INT32 | INT32 |
INT | INT32 |
INT64 | INT64 |
NUMERIC | INT64 |
REAL | REAL | Unsupported (use VARCHAR conversion)
FLOAT | FLOAT | Unsupported (use VARCHAR conversion)
DOUBLE PRECISION | FLOAT |
BLOB | BLOB | Must use a prepared statement, and PDO::PARAM_LOB
BIT VARYING | BLOB | Must use a prepared statement, and PDO::PARAM_LOB
CLOB | TEXT |
PICTURE | PICTURE | Must use a prepared statement, and PDO::PARAM_LOB

Constants for PDO_4D
SQL acceptable by 4D
4D (PDO)


PDO and SQL 4D

SQL types with PDO_4D and PHP
Examples with PDO_4D
4D (PDO)
PHP Manual

SQL acceptable by 4D

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

SQL acceptable by 4D — PDO and SQL 4D

Opis

4D implements strictly the ANSI 89 standard, and have it enforced. It is highly recommended to read the 4D SQL documentation to learn about the available commands. The URL of the manual is : » http://doc.4d.com/. Below is a list of 4D SQL characteristics: it is not exhaustive, but may serve as an introduction.

Characteristics of 4D SQL
Characteristics | Alternative | Note
INTEGER | Modify the SQL to use INT. | INT is the supported integer type in 4Dv12.0.
CHAR | Use VARCHAR instead. | Unsupported in 4Dv12.0
UNION | Unsupported. Make separate queries. | Unsupported in 4Dv12.0
SELECT 1 + 1; | SELECT 1 + 1 FROM _USER_SCHEMAS; | FROM is required
FLOAT | Cast the FLOAT value into a FLOAT or STRING, with an SQL 4D function (CAST, ROUND, TRUNC or TRUNCATE) | Unsupported in current versions of the PDO_4D driver
Strong typing | Take care your SQL query, or your PHP code provides data with the expected type | One must provide the right type that 4D expect. One can't insert '1' (as a string) in an INTEGER column.
PDO::execute($row)() : only works if all the table's column are of type TEXT or VARCHAR | Use the prepared statements, and use the right types. | The PDO extension cast all values through execute() as string, and expect the SQL database to parse the values.
SELECT NULL FROM TABLE | Do not use NULL constants. Extract them from the table | It is not allowed to use the NULL constant in the select list
SELECT * FROM TABLE WHERE 1 | Use WHERE 1 = 1 | A constant can't be used in a WHERE clause
SHOW TABLES | Use system tables | The list of tables, schemas, index, etc. are in these system tables : _USER_TABLES, _USER_COLUMNS, _USER_INDEXES, _USER_CONSTRAINTS, _USER_IND_COLUMNS, _USER_CONS_COLUMNS, and _USER_SCHEMAS.
SQL structure delimiter | Use the following function to protect SQL elements: function sqlEscapeElement(elem) { return '[' . str_replace(']',']]', $elem) . ']'; } | To escape SQL elements names (tables, fields, users, groups, schema, primary key, etc.), the whole identifier must be between square brackets, and the closing brackets ']' must be doubled.

SQL types with PDO_4D and PHP
Examples with PDO_4D
4D (PDO)


Examples PDO_4D

SQL acceptable by 4D
Rozszerzenia producentów baz danych
4D (PDO)
PHP Manual

Examples with PDO_4D

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

Examples with PDO_4D — Examples PDO_4D

This basic example show how to connect, execute a query, read data and disconnect from a 4D SQL server.

Przykład #1 Basic example with PDO_4D

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to the 4D SQL server
$db = new PDO($dsn, $user, $pass);

try {
    $db->exec('CREATE TABLE test(id varCHAR(1) NOT NULL, val VARCHAR(10))');
} catch (PDOException $e) {
    die("Erreur 4D : " . $e->getMessage());
}

$db->exec("INSERT INTO test VALUES('A', 'B')");
$db->exec("INSERT INTO test VALUES('C', 'D')");
$db->exec("INSERT INTO test VALUES('E', 'F')");

$stmt = $db->prepare('SELECT id, val from test');

$stmt->execute();
print_r($stmt->fetchAll());

unset($stmt);
unset($db);
?>

Powyższy przykład wyświetli:

    Array
(
    [0] => Array
        (
            [ID] => A
            [0] => A
            [VAL] => B
            [1] => B
        )

    [1] => Array
        (
            [ID] => C
            [0] => C
            [VAL] => D
            [1] => D
        )

    [2] => Array
        (
            [ID] => E
            [0] => E
            [VAL] => F
            [1] => F
        )

)

This example shows how to execute a query in 4D language, and how to read the result through PDO_4D.

Przykład #2 Accessing 4D language from pdo_4d

Set up a 4D method, called method. Make sure in the method properties that the option Available via SQL is checked. The 4D code is the following.

C_TEXTE($0)
$0:=Version application(*);

The PHP code to use the above 4D method is :

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to the 4D server
$db = new PDO($dsn, $user, $pass);

$stmt = $db->prepare('SELECT {FN method() AS VARCHAR } FROM _USER_SCHEMAS LIMIT 1');

$stmt->execute();
print_r($stmt->fetchAll());

unset($stmt);
unset($db);
?>

Powyższy przykład wyświetli:

(
    [0] => Array
        (
            [<expression>] => F0011140
            [0] => F0011140
        )

)

Przykład #3 Escaping 4D table names

This examples illustrates how to escape characters in a 4D SQL query.

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to 4D server 4D
$db = new PDO($dsn, $user, $pass);

$objects = array('[',']','[]','][','[[',']]','[[[',']]]','TBL ]]32[23');

foreach($objects as $id => $object) {
    $object = str_replace(']',']]', $object);
    print "$object\n";

    $db->exec('CREATE TABLE IF NOT EXISTS ['.$object.'](['.$object.'] FLOAT)');

    $req = "INSERT INTO [$object] ([$object]) VALUES ($id);";
    $db->query($req);

    $q = $db->prepare("SELECT [$object] FROM [$object]");
    $q->execute();
    $x[] = $q->fetch(PDO::FETCH_NUM);

    $db->exec('DROP TABLE ['.$object.'];');
}

?>

Powyższy przykład wyświetli:

[
]]
[]]
]][
[[
]]]]
[[[
]]]]]]
TBL ]]]]32[23

SQL acceptable by 4D
Rozszerzenia producentów baz danych
4D (PDO)


Rozszerzenia producentów baz danych

  • CUBRID
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • CUBRID Funkcje
    • CUBRID MySQL Compatibility Functions
    • CUBRID Obsolete Aliases and Functions
  • DB++
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • DB++ Funkcje
  • dBase
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • dBase Funkcje
  • filePro
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • filePro Funkcje
  • Firebird/InterBase
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje Firebird/InterBase
  • FrontBase
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje FrontBase
  • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • IBM DB2 Funkcje
  • Informix
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Informix Funkcje
  • Ingres — Ingres DBMS, EDBC, i Enterprise Access Gateways
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Funkcje Ingres
  • MaxDB
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • MaxDB Funkcje
  • Mongo — MongoDB Native Driver
    • Manual
    • Core Classes
    • Types
    • GridFS Classes
    • Miscellaneous
    • Functions
    • Exceptions
  • mSQL
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Funkcje mSQL
  • Mssql — Microsoft SQL Server
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje Mssql
  • MySQL — MySQL Drivers and Plugins
    • Overview of the MySQL PHP drivers
    • Mysql — Oryginalne API MySQL
    • Mysqli — MySQL Improved Extension
    • Mysqlnd — MySQL Native Driver
    • mysqlnd_ms — Mysqlnd replication and load balancing plugin
    • mysqlnd_qc — Mysqlnd query result cache plugin
    • mysqlnd_uh — Mysqlnd user handler plugin
  • OCI8 — Oracle OCI8
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Connection Handling
    • Supported Datatypes
    • OCI8 Funkcje
    • OCI8 Obsolete Aliases and Functions
  • Ovrimos SQL
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Funkcje Ovrimos SQL
  • Paradox — Paradox File Access
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Paradox Funkcje
  • PostgreSQL
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Funkcje PostgreSQL
  • SQLite
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • SQLite Funkcje
  • SQLite3
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • SQLite3 — The SQLite3 class
    • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Result — The SQLite3Result class
  • SQLSRV — Microsoft SQL Server Driver for PHP
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • SQLSRV Funkcje
  • Sybase
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Sybase Funkcje
  • tokyo_tyrant
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • TokyoTyrant — The TokyoTyrant class
    • TokyoTyrantTable — The TokyoTyrantTable class
    • TokyoTyrantQuery — The TokyoTyrantQuery class
    • TokyoTyrantIterator — The TokyoTyrantIterator class
    • TokyoTyrantException — The TokyoTyrantException class
Examples with PDO_4D
CUBRID
Rozszerzenia baz danych


CUBRID

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • CUBRID Funkcje
    • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
    • cubrid_bind — Bind variables to a prepared statement as parameters
    • cubrid_close_prepare — Close the request handle
    • cubrid_close_request — Close the request handle
    • cubrid_col_get — Get contents of collection type column using OID
    • cubrid_col_size — Get the number of elements in collection type column using OID
    • cubrid_column_names — Get the column names in result
    • cubrid_column_types — Get column types in result
    • cubrid_commit — Commit a transaction
    • cubrid_connect_with_url — Establish the environment for connecting to CUBRID server
    • cubrid_connect — Open a connection to a CUBRID Server
    • cubrid_current_oid — Get OID of the current cursor location
    • cubrid_disconnect — Close a database connection
    • cubrid_drop — Delete an instance using OID
    • cubrid_error_code_facility — Get the facility code of error
    • cubrid_error_code — Get error code for the most recent function call
    • cubrid_error_msg — Get last error message for the most recent function call
    • cubrid_execute — Execute a prepared SQL statement
    • cubrid_fetch — Fetch the next row from a result set
    • cubrid_free_result — Free the memory occupied by the result data
    • cubrid_get_autocommit — Get auto-commit mode of the connection
    • cubrid_get_charset — Return the current CUBRID connection charset
    • cubrid_get_class_name — Get the class name using OID
    • cubrid_get_client_info — Return the client library version
    • cubrid_get_db_parameter — Returns the CUBRID database parameters
    • cubrid_get_query_timeout — Get the query timeout value of the request
    • cubrid_get_server_info — Return the CUBRID server version
    • cubrid_get — Get a column using OID
    • cubrid_insert_id — Return the ID generated for the lastest updated AUTO_INCREMENT column
    • cubrid_is_instance — Check whether the instance pointed by OID exists
    • cubrid_lob_close — Close BLOB/CLOB data
    • cubrid_lob_export — Export BLOB/CLOB data to file
    • cubrid_lob_get — Get BLOB/CLOB data
    • cubrid_lob_send — Read BLOB/CLOB data and send straight to browser
    • cubrid_lob_size — Get BLOB/CLOB data size
    • cubrid_lock_read — Set a read lock on the given OID
    • cubrid_lock_write — Set a write lock on the given OID
    • cubrid_move_cursor — Move the cursor in the result
    • cubrid_next_result — Get result of next query when executing multiple SQL statements
    • cubrid_num_cols — Return the number of columns in the result set
    • cubrid_num_rows — Get the number of rows in the result set
    • cubrid_pconnect_with_url — Open a persistent connection to CUBRID server
    • cubrid_pconnect — Open a persistent connection to a CUBRID server
    • cubrid_prepare — Prepare an SQL statement for execution
    • cubrid_put — Update a column using OID
    • cubrid_rollback — Roll back a transaction
    • cubrid_schema — Get the requested schema information
    • cubrid_seq_drop — Delete an element from sequence type column using OID
    • cubrid_seq_insert — Insert an element to a sequence type column using OID
    • cubrid_seq_put — Update the element value of sequence type column using OID
    • cubrid_set_add — Insert a single element to set type column using OID
    • cubrid_set_autocommit — Set autocommit mode of the connection
    • cubrid_set_db_parameter — Sets the CUBRID database parameters
    • cubrid_set_drop — Delete an element from set type column using OID
    • cubrid_set_query_timeout — Set the timeout time of query execution
    • cubrid_version — Get the CUBRID PHP module's version
  • CUBRID MySQL Compatibility Functions
    • cubrid_client_encoding — Return the current CUBRID connection charset
    • cubrid_close — Close CUBRID connection
    • cubrid_data_seek — Move the internal row pointer of the CUBRID result
    • cubrid_db_name — Get db name from results of cubrid_list_dbs
    • cubrid_errno — Return the numerical value of the error message from previous CUBRID operation
    • cubrid_error — Get the error message
    • cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row
    • cubrid_fetch_field — Get column information from a result and return as an object
    • cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row
    • cubrid_fetch_object — Fetche the next row and returns it as an object
    • cubrid_fetch_row — Return a numerical array with the values of the current row
    • cubrid_field_flags — Return a string with the flags of the given field offset
    • cubrid_field_len — Get the maximum length of the specified field
    • cubrid_field_name — Return the name of the specified field index
    • cubrid_field_seek — Move the result set cursor to the specified field offset
    • cubrid_field_table — Return the name of the table of the specified field
    • cubrid_field_type — Return the type of the column corresponding to the given field offset
    • cubrid_list_dbs — Return an array with the list of all existing CUBRID databases
    • cubrid_num_fields — Return the number of columns in the result set
    • cubrid_ping — Ping a server connection or reconnect if there is no connection
    • cubrid_query — Send a CUBRID query
    • cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement
    • cubrid_result — Return the value of a specific field in a specific row
    • cubrid_unbuffered_query — Perform a query without fetching the results into memory
  • CUBRID Obsolete Aliases and Functions
    • cubrid_load_from_glo — Read data from a GLO instance and save it in a file
    • cubrid_new_glo — Create a glo instance
    • cubrid_save_to_glo — Save requested file in a GLO instance
    • cubrid_send_glo — Read data from glo and send it to std output
Rozszerzenia producentów baz danych
Wstęp
Rozszerzenia producentów baz danych


Wstęp

These functions allow you to access CUBRID database servers. More information about CUBRID can be found at » CUBRID.

Documentation for CUBRID can be found at » CUBRID Documentation.

CUBRID
Instalacja/Konfiguracja
CUBRID


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
CUBRID


Wymagania

In order to have these functions available, you must install CUBRID, and compile CUBRID PHP Library with CUBRID support.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/cubrid.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

For information about manual installation on Linux and Windows systems, please read the file build-guide.html included in the package.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

There is no runtime configuration now.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

There are three resource types used in CUBRID. The first one is the link identifier for a database connection, the second is the a resource which holds the result of a query, and the third a resource which holds the query results of BLOB/CLOB data types.

connection identifier

A connection identifier returned by cubrid_connect() and cubrid_connect_with_url().

request identifier

A request identifier returned by cubrid_prepare() and cubrid_execute().

LOB identifier

A LOB identifier returned by cubrid_lob_get().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

The following constants can be used when executing SQL statement. They can be passed to cubrid_prepare() and cubrid_execute().

CUBRID SQL execution flags
Constant | Description
CUBRID_INCLUDE_OID | Determine whether to get OID during query execution.
CUBRID_ASYNC | Execute the query in asynchronous mode.
CUBRID_EXEC_QUERY_ALL | Execute the query in synchronous mode. This flag must be set when executing multiple SQL statements.

The following constants can be used when fetching the results to specify fetch behaviour. They can be passed to cubrid_fetch() and cubrid_fetch_array().

CUBRID fetch flags
Constant | Description
CUBRID_NUM | Get query result as a numeric array (0-default).
CUBRID_ASSOC | Get query result as an associative array.
CUBRID_BOTH | Get query result as both numeric and associative arrays (default value).
CUBRID_OBJECT | Get query result an object.

The following constants can be used when positioning the cursor in query results. They can be passed to or returned by cubrid_move_cursor().

CUBRID cursor position flags
Constant | Description
CUBRID_CURSOR_FIRST | Move current cursor to the first position in the result.
CUBRID_CURSOR_CURRENT | Move current cursor as a default value if the origin is not specified.
CUBRID_CURSOR_LAST | Move current cursor to the last position in the result.
CUBRID_CURSOR_SUCCESS | Returned value of cubrid_move_cursor() function in case of success.
CUBRID_NO_MORE_DATA | Returned value of cubrid_move_cursor() function in case of failure.
CUBRID_CURSOR_ERROR | Returned value of cubrid_move_cursor() function in case of failure.

The following constants can be used when setting the auto-commit mode for the database connection. They can be passed to cubrid_set_autocommit() or returned by cubrid_get_autocommit().

CUBRID auto-commit mode flags
Constant | Description
CUBRID_AUTOCOMMIT_TRUE | Enable the auto-commit mode.
CUBRID_AUTOCOMMIT_FALSE | Disable the auto-commit mode.

The following constants can be used when setting the database parameter. They can be passed to cubrid_set_db_parameter().

CUBRID parameter flags
Constant | Description
CUBRID_PARAM_ISOLATION_LEVEL | Transaction isolation level for the database connection.
CUBRID_PARAM_LOCK_TIMEOUT | Transaction timeout in seconds.

The following constants can be used when setting the transaction isolation level. They can be passed to cubrid_set_db_parameter() or returned by cubrid_get_db_parameter().

CUBRID isolation level flags
Constant | Description
TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE | The lowest isolation level (1). A dirty, non-repeatable or phantom read may occur for the tuple and a non-repeatable read may occur for the table as well.
TRAN_COMMIT_CLASS_COMMIT_INSTANCE | A relatively low isolation level (2). A dirty read does not occur, but non-repeatable or phantom read may occur.
TRAN_REP_CLASS_UNCOMMIT_INSTANCE | The default isolation of CUBRID (3). A dirty, non-repeatable or phantom read may occur for the tuple, but repeatable read is ensured for the table.
TRAN_REP_CLASS_COMMIT_INSTANCE | A relatively low isolation level (4). A dirty read does not occur, but non-repeatable or phantom read may.
TRAN_REP_CLASS_REP_INSTANCE | A relatively high isolation level (5). A dirty or non-repeatable read does not occur, but a phantom read may.
TRAN_SERIALIZABLE | The highest isolation level (6). Problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.

The following constants can be used when getting schema information. They can be passed to cubrid_schema().

CUBRID schema flags
Constant | Description
CUBRID_SCH_CLASS | Get name and type of table in CUBRID.
CUBRID_SCH_VCLASS | Get name and type of view in CUBRID.
CUBRID_SCH_QUERY_SPEC | Get the query definition of view.
CUBRID_SCH_ATTRIBUTE | Get the attributes of table column.
CUBRID_SCH_CLASS_ATTRIBUTE | Get the attributes of table.
CUBRID_SCH_METHOD | Get the instance method. The instance method is a method called by a class instance. It is used more often than the class method because most operations are executed in the instance.
CUBRID_SCH_CLASS_METHOD | Get the class method. The class method is a method called by a class object. It is usually used to create a new class instance or to initialize it. It is also used to access or update class attributes.
CUBRID_SCH_METHOD_FILE | Get the information of the file where the method of the table is defined.
CUBRID_SCH_SUPERCLASS | Get the name and type of table which table inherites attributes from.
CUBRID_SCH_SUBCLASS | Get the name and type of table which inherites attributes from this table.
CUBRID_SCH_CONSTRAINT | Get the table constraints.
CUBRID_SCH_TRIGGER | Get the table triggers.
CUBRID_SCH_CLASS_PRIVILEGE | Get the privilege information of table.
CUBRID_SCH_ATTR_PRIVILEGE | Get the privilege information of column.
CUBRID_SCH_DIRECT_SUPER_CLASS | Get the direct super table of table.
CUBRID_SCH_PRIMARY_KEY | Get the table primary key.
CUBRID_SCH_IMPORTED_KEYS | Get imported keys of table.
CUBRID_SCH_EXPORTED_KEYS | Get exported keys of table.
CUBRID_SCH_CROSS_REFERENCE | Get reference relationship of tow tables.

The following constants can be used when reporting errors. They can be returned from cubrid_error_code_facility().

CUBRID error facility code
Constant | Description
CUBRID_FACILITY_DBMS | The error occured in CUBRID dbms.
CUBRID_FACILITY_CAS | The error occured in CUBRID broker cas.
CUBRID_FACILITY_CCI | The error occured in CUBRID cci.
CUBRID_FACILITY_CLIENT | The error occured in CUBRID PHP client.

Typy zasobów
Przykłady
CUBRID


Przykłady

The following is a simple example that establishes a connection between PHP and CUBRID. This section will cover the most basic and notable features. The following code required to connect to CUBRID database, which means CUBRID Server and CUBRID Broker have to be running.

The example below uses the demodb database as an examples. By default it is created during the installation. Make sure it has been created.

Przykład #1 Example of Data Retrieval

<html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=euc-kr">
    </head>
    <body>
    <center>
    <table border=2>
    <?php
        /**
         * Set server information for CUBRID connection. host_ip is the IP
         * address where the CUBRID Broker is installed (localhost in this
         * example), and host_port is the port number of the CUBRID Broker.
         * The port number is the default given during the installation.
         * For details, see "Administrator's Guide."
         */
        $host_ip = "localhost";
        $host_port = 33000;
        $db_name = "demodb";
        /**
         * Connect to CUBRID Server. Do not make the actual connection, but
         * only retain the connection information. The reason for not making
         * the actual connection is to handle transaction more efficiently
         * in the 3-tier architecture.
         */
        $cubrid_con = @cubrid_connect($host_ip, $host_port, $db_name);

        if (!$cubrid_con) {
            echo "Database Connection Error";
            exit;
        }
    ?>
    <?php
        $sql = "select sports, count(players) as players from event group by sports";
        /**
         * Request the CUBRID Server for the results of the SQL statement.
         * Now make the actual connection to the CUBRID Server.
         */
        $result = cubrid_execute($cubrid_con, $sql);

        if ($result) {
            /**
             * Get the column names from the result set created by the SQL query.
             */
            $columns = cubrid_column_names($result);
            /**
             * Get the number of columns in the result set created by the SQL query.
             */
            $num_fields = cubrid_num_cols($result);
            /**
             * List the column names of the result set on the screen.
             */
            echo("<tr>");

            while (list($key, $colname) = each($columns)) {
                echo("<td align=center>$colname</td>");
            }

            echo("</tr>");

            /**
             * Get the results from the result set.
             */
            while ($row = cubrid_fetch($result)) {
                echo("<tr>");

                for ($i = 0; $i < $num_fields; $i++) {
                    echo("<td align=center>");
                    echo($row[$i]);
                    echo("</td>");
                }

                echo("</tr>");
            }
        }
        /**
         * The PHP module in the CUBRID runs in a 3-tier architecture. Even when
         * calling SELECT for transaction processing, it is processed as a part
         * of the transaction. Therefore, the transaction needs to be rolled back
         * by calling commit or rollback even though SELECT was called for smooth
         * performance.
         */
        cubrid_commit($cubrid_con);
        cubrid_disconnect($cubrid_con);
    ?>
    </body>
    </html>

Przykład #2 Example of Data Insertion

<html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=euc- kr">
    </head>
    <body>
    <center>
    <table border=2>
    <?php
        /**
         * host_ip is the IP address where the CUBRID Broker is installed
         * host_port is the port number of the CUBRID Broker
         * db_name is the name of CUBRID Database
         */
        $host_ip = "localhost";
        $host_port = 33000;
        $db_name = "demodb";
        $cubrid_con = @cubrid_connect($host_ip, $host_port, $db_name);

        if (!$cubrid_con) {
            echo "Database Connection Error";
            exit;
        }
    ?>
    <?php
        $sql = "insert into olympic (host_year,host_nation,host_city,"
            . "opening_date,closing_date) values (2008, 'China', 'Beijing',"
            . "to_date('08-08-2008','mm-dd- yyyy'),to_date('08-24-2008','mm-dd-yyyy')) ;"
        $result = cubrid_execute($cubrid_con, $sql);
        if ($result) {
            /**
             * Handled successfully, so commit.
             */
            cubrid_commit($cubrid_con);
            echo("Inserted successfully ");
        } else {
            /**
             * Error occurred, so the error message is output and rollback is called.
             */
            echo(cubrid_error_msg());
            cubrid_rollback($cubrid_con);
        }
        cubrid_disconnect($cubrid_con);
    ?>
    </body>
    </html>
Stałe predefiniowane
CUBRID Funkcje
CUBRID


CUBRID Funkcje

Spis treści

  • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
  • cubrid_bind — Bind variables to a prepared statement as parameters
  • cubrid_close_prepare — Close the request handle
  • cubrid_close_request — Close the request handle
  • cubrid_col_get — Get contents of collection type column using OID
  • cubrid_col_size — Get the number of elements in collection type column using OID
  • cubrid_column_names — Get the column names in result
  • cubrid_column_types — Get column types in result
  • cubrid_commit — Commit a transaction
  • cubrid_connect_with_url — Establish the environment for connecting to CUBRID server
  • cubrid_connect — Open a connection to a CUBRID Server
  • cubrid_current_oid — Get OID of the current cursor location
  • cubrid_disconnect — Close a database connection
  • cubrid_drop — Delete an instance using OID
  • cubrid_error_code_facility — Get the facility code of error
  • cubrid_error_code — Get error code for the most recent function call
  • cubrid_error_msg — Get last error message for the most recent function call
  • cubrid_execute — Execute a prepared SQL statement
  • cubrid_fetch — Fetch the next row from a result set
  • cubrid_free_result — Free the memory occupied by the result data
  • cubrid_get_autocommit — Get auto-commit mode of the connection
  • cubrid_get_charset — Return the current CUBRID connection charset
  • cubrid_get_class_name — Get the class name using OID
  • cubrid_get_client_info — Return the client library version
  • cubrid_get_db_parameter — Returns the CUBRID database parameters
  • cubrid_get_query_timeout — Get the query timeout value of the request
  • cubrid_get_server_info — Return the CUBRID server version
  • cubrid_get — Get a column using OID
  • cubrid_insert_id — Return the ID generated for the lastest updated AUTO_INCREMENT column
  • cubrid_is_instance — Check whether the instance pointed by OID exists
  • cubrid_lob_close — Close BLOB/CLOB data
  • cubrid_lob_export — Export BLOB/CLOB data to file
  • cubrid_lob_get — Get BLOB/CLOB data
  • cubrid_lob_send — Read BLOB/CLOB data and send straight to browser
  • cubrid_lob_size — Get BLOB/CLOB data size
  • cubrid_lock_read — Set a read lock on the given OID
  • cubrid_lock_write — Set a write lock on the given OID
  • cubrid_move_cursor — Move the cursor in the result
  • cubrid_next_result — Get result of next query when executing multiple SQL statements
  • cubrid_num_cols — Return the number of columns in the result set
  • cubrid_num_rows — Get the number of rows in the result set
  • cubrid_pconnect_with_url — Open a persistent connection to CUBRID server
  • cubrid_pconnect — Open a persistent connection to a CUBRID server
  • cubrid_prepare — Prepare an SQL statement for execution
  • cubrid_put — Update a column using OID
  • cubrid_rollback — Roll back a transaction
  • cubrid_schema — Get the requested schema information
  • cubrid_seq_drop — Delete an element from sequence type column using OID
  • cubrid_seq_insert — Insert an element to a sequence type column using OID
  • cubrid_seq_put — Update the element value of sequence type column using OID
  • cubrid_set_add — Insert a single element to set type column using OID
  • cubrid_set_autocommit — Set autocommit mode of the connection
  • cubrid_set_db_parameter — Sets the CUBRID database parameters
  • cubrid_set_drop — Delete an element from set type column using OID
  • cubrid_set_query_timeout — Set the timeout time of query execution
  • cubrid_version — Get the CUBRID PHP module's version
Przykłady
cubrid_affected_rows
CUBRID


Return the number of rows affected by the last SQL statement

CUBRID Funkcje
cubrid_bind
CUBRID Funkcje
PHP Manual

cubrid_affected_rows

(PECL CUBRID >= 8.3.0)

cubrid_affected_rows — Return the number of rows affected by the last SQL statement

Opis

int cubrid_affected_rows ([ resource $result ] )

The cubrid_affected_rows() function is used to get the number of rows affected by the SQL statement (INSERT, DELETE, UPDATE).

Parametry

result

Result. If the result is not specified, the last result is assumed.

Zwracane wartości

Number of rows affected by the SQL statement, when process is successful.

-1, when SQL statement is not INSERT, DELETE or UPDATE.

FALSE, when the request identifier is not specified, and there is no last request.

Przykłady

Przykład #1 cubrid_affected_rows() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (t varchar)");

for ($i = 0; $i < 5; $i++) {
    cubrid_execute($conn, "INSERT INTO cubrid_test(t) VALUES('cubrid_test')");
}

cubrid_execute($conn, "DELETE FROM cubrid_test");

$affected_num = cubrid_affected_rows();
printf("Rows deleted: %d\n", $affected_num);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Rows deleted: 5

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement

CUBRID Funkcje
cubrid_bind
CUBRID Funkcje


Bind variables to a prepared statement as parameters

cubrid_affected_rows
cubrid_close_prepare
CUBRID Funkcje
PHP Manual

cubrid_bind

(PECL CUBRID >= 8.3.0)

cubrid_bind — Bind variables to a prepared statement as parameters

Opis

bool cubrid_bind ( resource $req_identifier , mixed $bind_param , mixed $bind_value [, string $bind_value_type ] )

The cubrid_bind() function is used to bind values to a corresponding named or question mark placeholder in the SQL statement that was passed to cubrid_prepare(). If bind_value_type is not given, string will be the default.

Informacja:

If the type of data to be bound is BLOB/CLOB, CUBRID will try to map the data as a PHP stream. If the actually bind value type is not stream, CUBRID will convert it to string, and use it as the full path and file name of a file on the client filesystem.

The following table shows the types of substitute values.

CUBRID Bind Date Types
Support | Bind Type | Corresponding SQL Type
Supported | STRING | CHAR, VARCHAR
 | NCHAR | NCHAR, NVARCHAR
 | BIT | BIT, VARBIT
 | NUMERIC or NUMBER | SHORT, INT, NUMERIC
 | FLOAT | FLOAT
 | DOUBLE | DOUBLE
 | TIME | TIME
 | DATE | DATE
 | TIMESTAMP | TIMESTAMP
 | OBJECT | OBJECT
 | BLOB | BLOB
 | CLOB | CLOB
 | NULL | NULL
Not supported | SET | SET
 | MULTISET | MULTISET
 | SEQUENCE | SEQUENCE

Parametry

req_identifier

Request identifier as a result of cubrid_prepare().

bind_param

Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name (Note that the name can only contain digit, alphabet, and underscore, and it can not begin with digit. The name length can not be longer than 32). For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.

bind_value

Actual value for binding.

bind_value_type

A type of the value to bind. (It is omitted by default. Thus, system internally use string by default. However, you need to specify the exact type of the value as an argument when they are NCHAR, BIT, or BLOB/CLOB).

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Rejestr zmian

Wersja | Opis
8.4.0 | Added named parameter support; When binding the LOB data type, it can directly binding the path name of a file.
8.3.1 | Added BLOB/CLOB data types support.

Przykłady

Przykład #1 cubrid_bind() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$result = cubrid_execute($conn, "SELECT code FROM event WHERE sports='Basketball' and gender='M'");
$row = cubrid_fetch_array($result, CUBRID_ASSOC);
$event_code = $row["code"];

cubrid_close_request($result);

$game_req = cubrid_prepare($conn, "SELECT athlete_code FROM game WHERE host_year=1992 and event_code=? and nation_code='USA'");
cubrid_bind($game_req, 1, $event_code, "number");
cubrid_execute($game_req);

printf("--- Dream Team (1992 United States men's Olympic basketball team) ---\n");
while ($athlete_code = cubrid_fetch_array($game_req, CUBRID_NUM)) {
    $athlete_req = cubrid_prepare($conn, "SELECT name FROM athlete WHERE code=? AND nation_code='USA' AND event='Basketball' AND gender='M'");
    cubrid_bind($athlete_req, 1, $athlete_code[0], "number");
    cubrid_execute($athlete_req);
    $row = cubrid_fetch_assoc($athlete_req);
    printf("%s\n", $row["name"]);
}

cubrid_close_request($game_req);
cubrid_close_request($athlete_req);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

--- Dream Team (1992 United States men's Olympic basketball team) ---
Stockton John
Robinson David
Pippen Scottie
Mullin C.
Malone Karl
Laettner C.
Jordan Michael
Johnson Earvin
Ewing Patrick
Drexler Clyde
Bird Larry
Barkley Charles

Przykład #2 cubrid_bind() named parameter example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$sql_stmt = <<<EOD
SELECT s.name FROM stadium s, game g
WHERE s.code = g.stadium_code AND g.medal = :medal_type
GROUP BY g.stadium_code ORDER BY count(medal) DESC LIMIT 1;
EOD;

$req = cubrid_prepare($conn, $sql_stmt);
printf("%-30s %s\n", "Medal Type", "Stadium where most medals were ever won");

cubrid_bind($req, ":medal_type", "G");
cubrid_execute($req);
$row = cubrid_fetch_assoc($req);
printf("%-30s %s\n", "Gold", $row["name"]);

cubrid_bind($req, ":medal_type", "S");
cubrid_execute($req);
$row = cubrid_fetch_assoc($req);
printf("%-30s %s\n", "Silver", $row["name"]);

cubrid_bind($req, ":medal_type", "B");
cubrid_execute($req);
$row = cubrid_fetch_assoc($req);
printf("%-30s %s\n", "Bronze", $row["name"]);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Medal Type                     Stadium where most medals were ever won
Gold                           Olympic Aquatic Centre
Silver                         Olympic Aquatic Centre
Bronze                         Sydney Convention and Exhibition Centre

Przykład #3 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "foo");
if ($con) {
    $sql = "INSERT INTO php_cubrid_lob_test(doc_content) VALUES(?)";
    $req = cubrid_prepare($con, $sql);

    $fp = fopen("book.txt", "rb");

    cubrid_bind($req, 1, $fp, "clob");
    cubrid_execute($req);
}
?>

Przykład #4 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "foo");
if ($con) {
    $sql = "INSERT INTO php_cubrid_lob_test(image) VALUES(?)";
    $req = cubrid_prepare($con, $sql);

    cubrid_bind($req, 1, "cubrid_logo.png", "blob");
    cubrid_execute($req);
}
?>

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_prepare() - Prepare an SQL statement for execution

cubrid_affected_rows
cubrid_close_prepare
CUBRID Funkcje


Close the request handle

cubrid_bind
cubrid_close_request
CUBRID Funkcje
PHP Manual

cubrid_close_prepare

(PECL CUBRID >= 8.3.0)

cubrid_close_prepare — Close the request handle

Opis

int cubrid_close_prepare ( resource $req_identifier )

The cubrid_close_prepare() function closes the request handle given by the req_identifier argument, and releases the memory region related to the handle. It is a alias of cubrid_close_request().

Parametry

req_identifier

Request identifier.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_close_prepare() example

<?php
$con = cubrid_connect ("dbsvr.cubrid.com", 12345, "demodb");
if ($con) {
   echo "connected successfully";
   $req = cubrid_execute ( $con, "select * from members",
                           CUBRID_INCLUDE_OID | CUBRID_ASYNC);
   if ($req) {
      while ( list ($id, $name) = cubrid_fetch ($req) ){
         echo $id;
         echo $name;
      }
      cubrid_close_prepare($req); // or you can use cubrid_close_request($req)
   }
   cubrid_disconnect($con);
}
?>

Zobacz też:

  • cubrid_close_request() - Close the request handle

cubrid_bind
cubrid_close_request
CUBRID Funkcje


Close the request handle

cubrid_close_prepare
cubrid_col_get
CUBRID Funkcje
PHP Manual

cubrid_close_request

(PECL CUBRID >= 8.3.0)

cubrid_close_request — Close the request handle

Opis

bool cubrid_close_request ( resource $req_identifier )

The cubrid_close_request() function closes the request handle given by the req_identifier argument, and releases the memory region related to the handle. It is a alias of cubrid_close_prepare().

Parametry

req_identifier

Request identifier.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_close_request() example

<?php
$con = cubrid_connect ("dbsvr.cubrid.com", 12345, "demodb");
if ($con) {
   echo "connected successfully";
   $req = cubrid_execute ( $con, "select * from members",
                           CUBRID_INCLUDE_OID | CUBRID_ASYNC);
   if ($req) {
      while ( list ($id, $name) = cubrid_fetch ($req) ){
         echo $id;
         echo $name;
      }
      cubrid_close_requst($req); // or you can use cubrid_close_prepare($req)
   }
   cubrid_disconnect($con);
}
?>

Zobacz też:

  • cubrid_close_prepare() - Close the request handle

cubrid_close_prepare
cubrid_col_get
CUBRID Funkcje


Get contents of collection type column using OID

cubrid_close_request
cubrid_col_size
CUBRID Funkcje
PHP Manual

cubrid_col_get

(PECL CUBRID >= 8.3.0)

cubrid_col_get — Get contents of collection type column using OID

Opis

array cubrid_col_get ( resource $conn_identifier , string $oid , string $attr_name )

The cubrid_col_get() function is used to get contents of the elements of the collection type (set, multiset, sequence) attribute you requested as an array.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance that you want to read.

attr_name

Attribute name that you want to read from the instance.

Zwracane wartości

Array (0-based numerical array) containing the elements you requested, when process is successful;

FALSE (to distinguish the error from the situation of attribute having empty collection or NULL, in case of error, a warning message is shown; in such case you can check the error by using cubrid_error_code()), when process is unsuccessful.

Przykłady

Przykład #1 cubrid_col_get() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

$size = cubrid_col_size($conn, $oid, "b");
var_dump($size);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
int(3)
cubrid_close_request
cubrid_col_size
CUBRID Funkcje


Get the number of elements in collection type column using OID

cubrid_col_get
cubrid_column_names
CUBRID Funkcje
PHP Manual

cubrid_col_size

(PECL CUBRID >= 8.3.0)

cubrid_col_size — Get the number of elements in collection type column using OID

Opis

int cubrid_col_size ( resource $conn_identifier , string $oid , string $attr_name )

The cubrid_col_size() function is used to get the number of elements in a collection type (set, multiset, sequence) attribute.

Parametry

conn_identifier

Connection identifier.

oid

OID the instance that you want to work with.

attr_name

Name of the attribute that you want to work with.

Zwracane wartości

Number of elements, when process is successful.

FALSE, when process is unsuccessful.

Rejestr zmian

Wersja | Opis
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

Przykłady

Przykład #1 cubrid_col_size() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

$size = cubrid_col_size($conn, $oid, "b");
var_dump($size);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
int(3)
cubrid_col_get
cubrid_column_names
CUBRID Funkcje


Get the column names in result

cubrid_col_size
cubrid_column_types
CUBRID Funkcje
PHP Manual

cubrid_column_names

(PECL CUBRID >= 8.3.0)

cubrid_column_names — Get the column names in result

Opis

array cubrid_column_names ( resource $req_identifier )

The cubrid_column_names() function is used to get the column names of the query result by using req_identifier.

Parametry

req_identifier

Request identifier.

Zwracane wartości

Array of string which containing column names, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_column_names() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
    $column_len = cubrid_field_len($result, $i);
    printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char(3)                        3
medal                          char(1)                        1
game_date                      date                           10

Zobacz też:

  • cubrid_prepare() - Prepare an SQL statement for execution
  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_column_types() - Get column types in result

cubrid_col_size
cubrid_column_types
CUBRID Funkcje


Get column types in result

cubrid_column_names
cubrid_commit
CUBRID Funkcje
PHP Manual

cubrid_column_types

(PECL CUBRID >= 8.3.0)

cubrid_column_types — Get column types in result

Opis

array cubrid_column_types ( resource $req_identifier )

The cubrid_column_types() function gets column types of query results by using req_identifier.

Parametry

req_identifier

Request identifier.

Zwracane wartości

Array of string which containing column types, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_column_types() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
    $column_len = cubrid_field_len($result, $i);
    printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char(3)                        3
medal                          char(1)                        1
game_date                      date                           10

Zobacz też:

  • cubrid_column_names() - Get the column names in result
  • cubrid_prepare() - Prepare an SQL statement for execution
  • cubrid_execute() - Execute a prepared SQL statement

cubrid_column_names
cubrid_commit
CUBRID Funkcje


Commit a transaction

cubrid_column_types
cubrid_connect_with_url
CUBRID Funkcje
PHP Manual

cubrid_commit

(PECL CUBRID >= 8.3.0)

cubrid_commit — Commit a transaction

Opis

bool cubrid_commit ( resource $conn_identifier )

The cubrid_commit() function is used to execute commit on the transaction pointed by conn_identifier, currently on progress. Connection to the server is closed after the cubrid_commit() function is called; the connection handle is still valid, however.

In CUBRID PHP, an auto-commit mode is disabled by default for transaction management, and you can set it by using cubrid_set_autocommit(), and get its status by using cubrid_get_autocommit(). Before you start a transaction, remember to disable the auto-commit mode.

Parametry

conn_identifier

Connection identifier.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_commit() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE publishers");

$sql = <<<EOD
CREATE TABLE publishers(
pub_id CHAR(3),
pub_name VARCHAR(20),
city VARCHAR(15),
state CHAR(2),
country VARCHAR(15)
)
EOD;

if (!cubrid_execute($conn, $sql)) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n", cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}

$req = cubrid_prepare($conn, "INSERT INTO publishers VALUES(?, ?, ?, ?, ?)");

$id_list = array("P01", "P02", "P03", "P04");
$name_list = array("Abatis Publishers", "Core Dump Books", "Schadenfreude Press", "Tenterhooks Press");
$city_list = array("New York", "San Francisco", "Hamburg", "Berkeley");
$state_list = array("NY", "CA", NULL, "CA");
$country_list = array("USA", "USA", "Germany", "USA");

for ($i = 0, $size = count($id_list); $i < $size; $i++) {
    cubrid_bind($req, 1, $id_list[$i]);
    cubrid_bind($req, 2, $name_list[$i]);
    cubrid_bind($req, 3, $city_list[$i]);
    cubrid_bind($req, 4, $state_list[$i]);
    cubrid_bind($req, 5, $country_list[$i]);

    if (!($ret = cubrid_execute($req))) {
        break;
    }
}

if (!$ret) {
    cubrid_rollback($conn);
} else {
    cubrid_commit($conn);

    $req = cubrid_execute($conn, "SELECT * FROM publishers");
    while ($result = cubrid_fetch_assoc($req)) {
        printf("%-3s %-20s %-15s %-3s %-15s\n",
            $result["pub_id"], $result["pub_name"], $result["city"], $result["state"], $result["country"]);
    }
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

P01 Abatis Publishers    New York        NY  USA
P02 Core Dump Books      San Francisco   CA  USA
P03 Schadenfreude Press  Hamburg             Germany
P04 Tenterhooks Press    Berkeley        CA  USA

Zobacz też:

  • cubrid_rollback() - Roll back a transaction
  • cubrid_get_autocommit() - Get auto-commit mode of the connection
  • cubrid_set_autocommit() - Set autocommit mode of the connection

cubrid_column_types
cubrid_connect_with_url
CUBRID Funkcje


Establish the environment for connecting to CUBRID server

cubrid_commit
cubrid_connect
CUBRID Funkcje
PHP Manual

cubrid_connect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_connect_with_url — Establish the environment for connecting to CUBRID server

Opis

resource cubrid_connect_with_url ( string $conn_url [, string $userid [, string $passwd [, bool $new_link = false ]]] )

The cubrid_connect_with_url() function is used to establish the environment for connecting to your server by using connection information passed with an url string argument. If the HA feature is enabled in CUBRID, you must specify the connection information of the standby server, which is used for failover when failure occurs, in the url string argument of this function. If the user name and password is not given, then the "PUBLIC" connection will be made by default.

<url> ::= CUBRID:<host>:<db_name>:<db_user>:<db_password>:[?<properties>]
<properties> ::= <property> [&<property>]
<properties> ::= autocommit=<autocommit_mode>
<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]
<host> := HOSTNAME | IP_ADDR
<time> := SECOND

or <url> ::= cci:CUBRID:<host>:<db_name>:......

  • host : A host name or IP address of the master database
  • db_name : A name of the database
  • db_user : A name of the database user
  • db_password : A database user password
  • autocommit : The database connection auto-commit mode
  • alhosts: Specifies the broker information of the standby server, which is used for failover when it is impossible to connect to the active server. You can specify multiple brokers for failover, and the connection to the brokers is attempted in the order listed in alhosts
  • rctime : An interval between the attempts to connect to the active broker in which failure occurred. After a failure occurs, the system connects to the broker specified by althosts (failover), terminates the transaction, and then attempts to connect to the active broker of the master database at every rctime. The default value is 600 seconds.

Parametry

conn_url

A character string that contains server connection information.

userid

User name for the database.

passwd

User password.

new_link

If a second call is made to cubrid_connect_with_url() with the same arguments, no new connection will be established, but instead, the connection identifier of the already opened connection will be returned. The new_link parameter modifies this behavior and makes cubrid_connect_with_url() always open a new connection, even if cubrid_connect_with_url() was called before with the same parameters.

Zwracane wartości

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_connect_with_url() url without properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33088:demodb:dba:123456:?autocommit=off"
$con = cubrid_connect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   $req =cubrid_execute($con, "insert into person values(1,'James')");

   if ($req) {
      cubrid_close_request ($req);
      cubrid_commit ($con);
   } else {
      cubrid_rollback ($con);
   }
   cubrid_disconnect ($con);
}
?>

Przykład #2 cubrid_connect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33088:demodb:dba:123456:?autocommit=off&althost=10.34.63.132:33088&rctime=100"
$con = cubrid_connect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   $req =cubrid_execute($con, "insert into person values(1,'James')");

   if ($req) {
      cubrid_close_request ($req);
      cubrid_commit ($con);
   } else {
      cubrid_rollback ($con);
   }
   cubrid_disconnect ($con);
}
?>

Zobacz też:

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

cubrid_commit
cubrid_connect
CUBRID Funkcje


Open a connection to a CUBRID Server

cubrid_connect_with_url
cubrid_current_oid
CUBRID Funkcje
PHP Manual

cubrid_connect

(PECL CUBRID >= 8.3.1)

cubrid_connect — Open a connection to a CUBRID Server

Opis

resource cubrid_connect ( string $host , int $port , string $dbname [, string $userid [, string $passwd [, bool $new_link = false ]]] )

The cubrid_connect() function is used to establish the environment for connecting to your server by using your server address, port number, database name, user name, and password. If the user name and password is not given, then the "PUBLIC" connection will be made by default.

Parametry

host

Host name or IP address of CUBRID CAS server.

port

Port number of CUBRID CAS server (BROKER_PORT configured in $CUBRID/conf/cubrid_broker.conf).

dbname

Name of database.

userid

User name for the database.

passwd

User password.

new_link

If a second call is made to cubrid_connect() with the same arguments, no new connection will be established, but instead, the connection identifier of the already opened connection will be returned. The new_link parameter modifies this behavior and makes cubrid_connect() always open a new connection, even if cubrid_connect() was called before with the same parameters.

Zwracane wartości

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_connect() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33000, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

CUBRID PHP Version:            8.3.1.0005

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

CUBRID Charset:                iso8859-1

Zobacz też:

  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

cubrid_connect_with_url
cubrid_current_oid
CUBRID Funkcje


Get OID of the current cursor location

cubrid_connect
cubrid_disconnect
CUBRID Funkcje
PHP Manual

cubrid_current_oid

(PECL CUBRID >= 8.3.0)

cubrid_current_oid — Get OID of the current cursor location

Opis

string cubrid_current_oid ( resource $req_identifier )

The cubrid_current_oid() function is used to get the oid of the current cursor location from the query result. To use cubrid_current_oid(), the query executed must be a updatable query, and the CUBRID_INCLUDE_OID option must be included during the query execution.

Parametry

req_identifier

Request identifier.

Zwracane wartości

Oid of current cursor location, when process is successful

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_current_oid() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code", CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$res = cubrid_get($conn, $oid);

print_r($res);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Array
(
    [s_name] => X
    [f_name] => Mixed
)

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement

cubrid_connect
cubrid_disconnect
CUBRID Funkcje


Close a database connection

cubrid_current_oid
cubrid_drop
CUBRID Funkcje
PHP Manual

cubrid_disconnect

(PECL CUBRID >= 8.3.0)

cubrid_disconnect — Close a database connection

Opis

bool cubrid_disconnect ( resource $conn_identifier )

The cubrid_disconnect() function closes the connection handle and disconnects from server. If there exists any request handle not closed yet at this point, it will be closed. It is similar to the CUBRID MySQL compatible function cubrid_close().

Parametry

conn_identifier

Connection identifier.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_disconnect() example

<?php
$con = cubrid_connect ("210.211.133.100", 12345, "demodb");
if ($con) {
   echo "connected successfully";
   $req = cubrid_execute( $con, "insert into person values(1,'James')");
   if ($req) {
      cubrid_close_request($req);
      cubrid_commit($con);
   } else {
      cubrid_rollback($con);
   }
   cubrid_disconnect($con);
}
?>

Zobacz też:

  • cubrid_close() - Close CUBRID connection
  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server

cubrid_current_oid
cubrid_drop
CUBRID Funkcje


Delete an instance using OID

cubrid_disconnect
cubrid_error_code_facility
CUBRID Funkcje
PHP Manual

cubrid_drop

(PECL CUBRID >= 8.3.0)

cubrid_drop — Delete an instance using OID

Opis

bool cubrid_drop ( resource $conn_identifier , string $oid )

The cubrid_drop() function is used to delete an instance from database by using oid.

Parametry

conn_identifier

Connection identifier.

oid

Oid of the instance that you want to delete.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

printf("--- Before Drop: ---\n");
$attr = cubrid_get($conn, $oid);
var_dump($attr);

if (cubrid_drop($conn, $oid)) {
    cubrid_commit($conn);
} else {
    cubrid_rollback($conn);
}

cubrid_close_request($req);

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

printf("\n--- After Drop: ---\n");
$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

--- Before Drop: ---
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

--- After Drop: ---
array(4) {
  ["a"]=>
  string(1) "2"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "4"
    [1]=>
    string(1) "5"
    [2]=>
    string(1) "7"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "44"
    [1]=>
    string(2) "55"
    [2]=>
    string(2) "66"
    [3]=>
    string(3) "666"
  }
  ["d"]=>
  string(10) "b         "
}

Zobacz też:

  • cubrid_is_instance() - Check whether the instance pointed by OID exists

cubrid_disconnect
cubrid_error_code_facility
CUBRID Funkcje


Get the facility code of error

cubrid_drop
cubrid_error_code
CUBRID Funkcje
PHP Manual

cubrid_error_code_facility

(PECL CUBRID >= 8.3.0)

cubrid_error_code_facility — Get the facility code of error

Opis

int cubrid_error_code_facility ( void )

The cubrid_error_code_facility() function is used to get the facility code (level in which the error occurred) from the error code of the error that occurred during the API execution. Usually, you can get the error code when API returns false as its return value.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Facility code of the error code that occurred: CUBRID_FACILITY_DBMS, CUBRID_FACILITY_CAS, CUBRID_FACILITY_CCI, CUBRID_FACILITY_CLIENT

Przykłady

Przykład #1 cubrid_error_code_facility() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = @cubrid_execute($conn, "SELECT * FROM unknown");
if (!$req) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n",
        cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}
?>

Powyższy przykład wyświetli:

Error facility: 1
Error code: -493
Error msg: Syntax: syntax error, unexpected UNKNOWN

Zobacz też:

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

cubrid_drop
cubrid_error_code
CUBRID Funkcje


Get error code for the most recent function call

cubrid_error_code_facility
cubrid_error_msg
CUBRID Funkcje
PHP Manual

cubrid_error_code

(PECL CUBRID >= 8.3.0)

cubrid_error_code — Get error code for the most recent function call

Opis

int cubrid_error_code ( void )

The cubrid_error_code() function is used to get the error code of the error that occurred during the API execution. Usually, it gets the error code when API returns false as its return value.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Error code of the error that occurred, or 0 (zero) if no error occurred.

Przykłady

Przykład #1 cubrid_error_code() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_prepare($conn , "SELECT * FROM code WHERE s_name=?");

$req = @cubrid_execute($req);
if (!$req) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n",
        cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}
?>

Powyższy przykład wyświetli:

Error facility: 4
Error code: -2015
Error msg: Some parameter not binded

Zobacz też:

  • cubrid_error_code_facility() - Get the facility code of error
  • cubrid_error_msg() - Get last error message for the most recent function call

cubrid_error_code_facility
cubrid_error_msg
CUBRID Funkcje


Get last error message for the most recent function call

cubrid_error_code
cubrid_execute
CUBRID Funkcje
PHP Manual

cubrid_error_msg

(PECL CUBRID >= 8.3.0)

cubrid_error_msg — Get last error message for the most recent function call

Opis

string cubrid_error_msg ( void )

The cubrid_error_msg() function is used to get the error message that occurred during the use of CUBRID API. Usually, it gets error message when API returns false as its return value.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Error message that occurred.

Przykłady

Przykład #1 cubrid_error_msg() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

if (!@cubrid_schema($conn, 100000)) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n",
        cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}
?>

Powyższy przykład wyświetli:

Error facility: 2
Error code: -1015
Error msg: Invalid T_CCI_SCH_TYPE value

Zobacz też:

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_code_facility() - Get the facility code of error

cubrid_error_code
cubrid_execute
CUBRID Funkcje


Execute a prepared SQL statement

cubrid_error_msg
cubrid_fetch
CUBRID Funkcje
PHP Manual

cubrid_execute

(PECL CUBRID >= 8.3.0)

cubrid_execute — Execute a prepared SQL statement

Opis

resource cubrid_execute ( resource $conn_identifier , string $sql [, int $option ] )
bool cubrid_execute ( resource $request_identifier [, int $option ] )

The cubrid_execute() function is used to execute the given SQL statement. It executes the query by using conn_identifier and SQL, and then returns the request identifier created. It is used for simple execution of query, where the parameter binding is not needed. In addition, the cubrid_execute() function is used to execute the prepared statement by means of cubrid_prepare() and cubrid_bind(). At this time, you need to specify arguments of request_identifier and option.

The option is used to determine whether to get OID after query execution and whether to execute the query in synchronous or asynchronous mode. CUBRID_INCLUDE_OID and CUBRID_ASYNC (or CUBRID_EXEC_QUERY_ALL if you want to execute multiple SQL statements) can be specified by using a bitwise OR operator. If not specified, neither of them isselected. If the flag CUBRID_EXEC_QUERY_ALL is set, a synchronous mode (sync_mode) is used to retrieve query results, and in such cases the following rules are applied:

  • The return value is the result of the first query.
  • If an error occurs in any query, the execution is processed as a failure.
  • For a query composed of in a query composed of q1 q2 q3 if an error occurs in q2 after q1 succeeds the execution, the result of q1 remains valid. That is, the previous successful query executions are not rolled back when an error occurs.
  • If a query is executed successfully, the result of the second query can be obtained using cubrid_next_result().

If the first argument is request_identifier to execute the cubrid_prepare() function, you can specify an option, CUBRID_ASYNC only.

Parametry

conn_identifier

Connection identifier.

sql

SQL to be executed.

option

Query execution option CUBRID_INCLUDE_OID, CUBRID_ASYNC, CUBRID_EXEC_QUERY_ALL.

request_identifier

cubrid_prepare() identifier.

Zwracane wartości

Request identifier, when process is successful and first param is conn_identifier; TRUE, when process is successful and first argument is request_identifier.

FALSE, when process is unsuccessful.

Rejestr zmian

Wersja | Opis
8.4.0 | Add new option CUBRID_EXEC_QUERY_ALL.

Przykłady

Przykład #1 cubrid_execute() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$result = cubrid_execute($conn, "SELECT code FROM event WHERE name='100m Butterfly' and gender='M'", CUBRID_ASYNC);
$row = cubrid_fetch_array($result, CUBRID_ASSOC);
$event_code = $row["code"];

cubrid_close_request($result);

$history_req = cubrid_prepare($conn, "SELECT * FROM history WHERE event_code=?");
cubrid_bind($history_req, 1, $event_code, "number");
cubrid_execute($history_req);

printf("%-20s %-9s %-10s %-5s\n", "athlete", "host_year", "score", "unit");
while ($row = cubrid_fetch_array($history_req, CUBRID_ASSOC)) {
    printf("%-20s %-9s %-10s %-5s\n",
        $row["athlete"], $row["host_year"], $row["score"], $row["unit"]);
}

cubrid_close_request($history_req);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

athlete              host_year score      unit
Phelps Michael       2004      51.25      time

Zobacz też:

  • cubrid_prepare() - Prepare an SQL statement for execution
  • cubrid_bind() - Bind variables to a prepared statement as parameters
  • cubrid_next_result() - Get result of next query when executing multiple SQL statements
  • cubrid_close_request() - Close the request handle
  • cubrid_commit() - Commit a transaction
  • cubrid_rollback() - Roll back a transaction

cubrid_error_msg
cubrid_fetch
CUBRID Funkcje


Fetch the next row from a result set

cubrid_execute
cubrid_free_result
CUBRID Funkcje
PHP Manual

cubrid_fetch

(PECL CUBRID >= 8.3.0)

cubrid_fetch — Fetch the next row from a result set

Opis

mixed cubrid_fetch ( resource $result [, int $type = CUBRID_BOTH ] )

The cubrid_fetch() function is used to get a single row from the query result. The cursor automatically moves to the next row after getting the result.

Parametry

result

result comes from a call to cubrid_execute()

type

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH, CUBRID_OBJECT.

Zwracane wartości

Result array or object, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

The result can be received either as an array or as an object, and you can decide which data type to use by setting the type argument. The type variable can be set to one of the following values:

  • CUBRID_NUM : Numerical array (0-based)
  • CUBRID_ASSOC : Associative array
  • CUBRID_BOTH : Numerical & Associative array (default)
  • CUBRID_OBJECT : object that has the attribute name as the column name of query result

When type argument is omitted, the result will be received using CUBRID_BOTH option as default. When you want to receive query result in object data type, the column name of the result must obey the naming rules for identifiers in PHP. For example, column name such as "count(*)" cannot be received in object type.

Przykłady

Przykład #1 cubrid_fetch() example

<?php
$conn = cubrid_connect("localhost", 33088, "demodb");
$req = cubrid_execute($conn, "SELECT * FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch($req)) {
    printf("%-40s %-10s %-6s %-20s\n",
        $row["name"], $row["area"], $row["seats"], $row["address"]);
}

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement

cubrid_execute
cubrid_free_result
CUBRID Funkcje


Free the memory occupied by the result data

cubrid_fetch
cubrid_get_autocommit
CUBRID Funkcje
PHP Manual

cubrid_free_result

(PECL CUBRID >= 8.3.0)

cubrid_free_result — Free the memory occupied by the result data

Opis

bool cubrid_free_result ( resource $req_identifier )

This function frees the memory occupied by the result data. It returns TRUE on success or FALSE on failure. Note that it can only frees the client fetch buffer now, and if you want free all memory, use function cubrid_close_request().

Parametry

req_identifier

This is the request identifier.

Zwracane wartości

TRUE on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_free_result() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM history WHERE host_year=2004 ORDER BY event_code");
$row = cubrid_fetch_assoc($req);
var_dump($row);

cubrid_free_result($req);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(5) {
  ["event_code"]=>
  string(5) "20005"
  ["athlete"]=>
  string(12) "Hayes Joanna"
  ["host_year"]=>
  string(4) "2004"
  ["score"]=>
  string(5) "12.37"
  ["unit"]=>
  string(4) "time"
}
cubrid_fetch
cubrid_get_autocommit
CUBRID Funkcje


Get auto-commit mode of the connection

cubrid_free_result
cubrid_get_charset
CUBRID Funkcje
PHP Manual

cubrid_get_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_get_autocommit — Get auto-commit mode of the connection

Opis

bool cubrid_get_autocommit ( resource $conn_identifier )

The cubrid_get_autocommit() function is used to get the status of CUBRID database connection auto-commit mode.

In CUBRID PHP, an auto-commit mode is disabled by default for transaction management.

Parametry

conn_identifier

Connection identifier.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Zobacz też:

  • cubrid_set_autocommit() - Set autocommit mode of the connection
  • cubrid_commit() - Commit a transaction

cubrid_free_result
cubrid_get_charset
CUBRID Funkcje


Return the current CUBRID connection charset

cubrid_get_autocommit
cubrid_get_class_name
CUBRID Funkcje
PHP Manual

cubrid_get_charset

(PECL CUBRID >= 8.3.0)

cubrid_get_charset — Return the current CUBRID connection charset

Opis

string cubrid_get_charset ( resource $conn_identifier )

This function returns the current CUBRID connection charset and is similar to the CUBRID MySQL compatible function cubrid_client_encoding().

Parametry

conn_identifier

The CUBRID connection.

Zwracane wartości

A string that represents the CUBRID connection charset; on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_get_charset() example

<?php

$con = cubrid_connect("localhost", 33000, "demodb");
if (!$con)
{
    die('Could not connect.');
}

printf("CUBRID current charset: %s\n", cubrid_client_encoding($con));

?>

Powyższy przykład wyświetli:

CUBRID current charset: iso8859-1

Zobacz też:

  • cubrid_client_encoding() - Return the current CUBRID connection charset

cubrid_get_autocommit
cubrid_get_class_name
CUBRID Funkcje


Get the class name using OID

cubrid_get_charset
cubrid_get_client_info
CUBRID Funkcje
PHP Manual

cubrid_get_class_name

(PECL CUBRID >= 8.3.0)

cubrid_get_class_name — Get the class name using OID

Opis

string cubrid_get_class_name ( resource $conn_identifier , string $oid )

The cubrid_get_class_name() function is used to get the class name from oid.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance that you want to check the existence.

Zwracane wartości

Class name when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_get_class_name() example

<?php
$conn = cubrid_connect("localhost", 33088, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code", CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$class_name = cubrid_get_class_name($conn, $oid);

print_r($class_name);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

code

Zobacz też:

  • cubrid_is_instance() - Check whether the instance pointed by OID exists
  • cubrid_drop() - Delete an instance using OID

cubrid_get_charset
cubrid_get_client_info
CUBRID Funkcje


Return the client library version

cubrid_get_class_name
cubrid_get_db_parameter
CUBRID Funkcje
PHP Manual

cubrid_get_client_info

(PECL CUBRID >= 8.3.0)

cubrid_get_client_info — Return the client library version

Opis

string cubrid_get_client_info ( void )

This function returns a string that represents the client library version.

Parametry

Zwracane wartości

A string that represents the client library version; on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_get_client_info() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

Powyższy przykład wyświetli:

CUBRID PHP Version:            8.3.1.0005

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

CUBRID Charset:                iso8859-1
cubrid_get_class_name
cubrid_get_db_parameter
CUBRID Funkcje


Returns the CUBRID database parameters

cubrid_get_client_info
cubrid_get_query_timeout
CUBRID Funkcje
PHP Manual

cubrid_get_db_parameter

(PECL CUBRID >= 8.3.0)

cubrid_get_db_parameter — Returns the CUBRID database parameters

Opis

array cubrid_get_db_parameter ( resource $conn_identifier )

This function returns the CUBRID database parameters or it returns FALSE on failure. It returns an associative array with the values for the following parameters:

  • PARAM_ISOLATION_LEVEL
  • PARAM_LOCK_TIMEOUT
  • PARAM_MAX_STRING_LENGTH
  • PARAM_AUTO_COMMIT

Database parameters
Parameter | Description
PARAM_ISOLATION_LEVEL | The transaction isolation level.
LOCK_TIMEOUT | CUBRID provides the lock timeout feature, which sets the waiting time (in seconds) for the lock until the transaction lock setting is allowed. The default value of the lock_timeout_in_secs parameter is -1, which means the application client will wait indefinitely until the transaction lock is allowed.
PARAM_AUTO_COMMIT | In CUBRID PHP, an auto-commit mode is disabled by default for transaction management. It can be set by using cubrid_set_autocommit().

The following table shows the isolation levels from 1 to 6. It consists of table schema (row) and isolation level:

Levels of Isolation Supported by CUBRID
Name | Description
SERIALIZABLE (6) | In this isolation level, problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.
REPEATABLE READ CLASS with REPEATABLE READ INSTANCES (5) | Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience phantom read for the record R that was inserted by another transaction T2 when it is repeatedly retrieving a specific record.
REPEATABLE READ CLASS with READ COMMITTED INSTANCES (or CURSOR STABILITY) (4) | Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience R read (non-repeatable read) that was updated and committed by another transaction T2 when it is repeatedly retrieving the record R.
REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES (3) | Default isolation level. Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience R' read (dirty read) for the record that was updated but not committed by another transaction T2.
READ COMMITTED CLASS with READ COMMITTED INSTANCES (2) | Transaction T1 may experience A' read (non-repeatable read) for the table that was updated and committed by another transaction T2 while it is viewing table A repeatedly. Transaction T1 may experience R' read (non-repeatable read) for the record that was updated and committed by another transaction T2 while it is retrieving the record R repeatedly.
READ COMMITTED CLASS with READ UNCOMMITTED INSTANCES (1) | Transaction T1 may experience A' read (non-repeatable read) for the table that was updated and committed by another transaction T2 while it is repeatedly viewing table A. Transaction T1 may experience R' read (dirty read) for the record that was updated but not committed by another transaction T2.

Parametry

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

Zwracane wartości

An associative array with CUBRID database parameters; on success.

FALSE on failure.

Rejestr zmian

Wersja | Opis
8.4.0 | Change LOCK_TIMEOUT to PARAM_LOCK_TIMEOUT, and MAX_STRING_LENGTH to PARAM_MAX_STRING_LENGTH in result.

Przykłady

Przykład #1 cubrid_get_db_parameter() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

Powyższy przykład wyświetli:

CUBRID PHP Version:            8.3.1.0005

PARAM_ISOLATION_LEVEL          3
PARAM_LOCK_TIMEOUT             -1
PARAM_MAX_STRING_LENGTH        1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

CUBRID Charset:                iso8859-1

Zobacz też:

  • cubrid_set_db_parameter() - Sets the CUBRID database parameters
  • cubrid_get_autocommit() - Get auto-commit mode of the connection

cubrid_get_client_info
cubrid_get_query_timeout
CUBRID Funkcje


Get the query timeout value of the request

cubrid_get_db_parameter
cubrid_get_server_info
CUBRID Funkcje
PHP Manual

cubrid_get_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_get_query_timeout — Get the query timeout value of the request

Opis

int cubrid_get_query_timeout ( resource $req_identifier )

The cubrid_get_query_timeout() function is used to get the query timeout of the request.

Parametry

req_identifier

Request identifier.

Zwracane wartości

Success: the query timeout value of the current request. Units of msec.

Failure: FALSE

Przykłady

Przykład #1 cubrid_get_query_timeout() example

<?php

$host = "localhost";
$port = 33000;
$db = "demodb";

$conn =
cubrid_connect_with_url("CUBRID:$host:$port:$db:::?&login_timeout=50000&query_timeout=5000&disconnect_on_query_timeout=yes");

$req = cubrid_prepare($conn, "SELECT * FROM code");

$timeout = cubrid_get_query_timeout($req);
var_dump($timeout);

cubrid_set_query_timeout($req, 1000);
$timeout = cubrid_get_query_timeout($req);
var_dump($timeout);

cubrid_close($conn);
?>

Powyższy przykład wyświetli:

int(5000)
int(1000)

Zobacz też:

  • cubrid_set_query_timeout() - Set the timeout time of query execution

cubrid_get_db_parameter
cubrid_get_server_info
CUBRID Funkcje


Return the CUBRID server version

cubrid_get_query_timeout
cubrid_get
CUBRID Funkcje
PHP Manual

cubrid_get_server_info

(PECL CUBRID >= 8.3.0)

cubrid_get_server_info — Return the CUBRID server version

Opis

string cubrid_get_server_info ( resource $conn_identifier )

This function returns a string that represents the CUBRID server version.

Parametry

conn_identifier

The CUBRID connection.

Zwracane wartości

A string that represents the CUBRID server version; on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_get_server_info() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

Powyższy przykład wyświetli:

CUBRID PHP Version:            8.3.1.0005

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

CUBRID Charset:                iso8859-1
cubrid_get_query_timeout
cubrid_get
CUBRID Funkcje


Get a column using OID

cubrid_get_server_info
cubrid_insert_id
CUBRID Funkcje
PHP Manual

cubrid_get

(PECL CUBRID >= 8.3.0)

cubrid_get — Get a column using OID

Opis

mixed cubrid_get ( resource $conn_identifier , string $oid [, mixed $attr ] )

The cubrid_get() function is used to get the attribute of the instance of the given oid. You can get single attribute by using string data type for the attr argument, or many attributes by using array data type for the attr argument.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance that you want to read.

attr

Name of the attribute that you want to read.

Zwracane wartości

Content of the requested attribute, when process is successful; When attr is set with string data type, the result is returned as a string; when attr is set with array data type (0-based numerical array), then the result is returned in associative array. When attr is omitted, then all attributes are received in array form.

FALSE when process is unsuccessful or result is NULL (If error occurs to distinguish empty string from NULL, then it prints the warning message. You can check the error by using cubrid_error_code())

Przykłady

Przykład #1 cubrid_get() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_get($conn, $oid, "b");
var_dump($attr);

$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

string(9) "{1, 2, 3}"
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

Zobacz też:

  • cubrid_put() - Update a column using OID

cubrid_get_server_info
cubrid_insert_id
CUBRID Funkcje


Return the ID generated for the lastest updated AUTO_INCREMENT column

cubrid_get
cubrid_is_instance
CUBRID Funkcje
PHP Manual

cubrid_insert_id

(PECL CUBRID >= 8.3.0)

cubrid_insert_id — Return the ID generated for the lastest updated AUTO_INCREMENT column

Opis

string cubrid_insert_id ([ resource $conn_identifier ] )

The cubrid_insert_id() function retrieves the ID generated for the AUTO_INCREMENT column which is updated by the previous INSERT query. It returns 0 if the previous query does not generate new rows, or FALSE on failure.

Informacja:

CUBRID supports AUTO_INCREMENT for more than one columns in a table. In most cases, there will be a single AUTO_INCREMENT column in a table. If there are multiple AUTO_INCREMENT columns, this function should not be used even if it will return a value.

Parametry

conn_identifier

The connection identifier previously obtained by a call to cubrid_connect().

Zwracane wartości

A string representing the ID generated for an AUTO_INCREMENT column by the previous query, on success.

0, if the previous query does not generate new rows.

FALSE on failure.

Rejestr zmian

Wersja | Opis
8.4.0 | Change the return value from an array to string; Remove the first parameter class_name.

Przykłady

Przykład #1 cubrid_insert_id() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (d int AUTO_INCREMENT(1, 2), t varchar)");

for ($i = 0; $i < 10; $i++) {
    cubrid_execute($conn, "INSERT INTO cubrid_test(t) VALUES('cubrid_test')");
}

$id = cubrid_insert_id();
var_dump($id);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

string(2) "19"
cubrid_get
cubrid_is_instance
CUBRID Funkcje


Check whether the instance pointed by OID exists

cubrid_insert_id
cubrid_lob_close
CUBRID Funkcje
PHP Manual

cubrid_is_instance

(PECL CUBRID >= 8.3.0)

cubrid_is_instance — Check whether the instance pointed by OID exists

Opis

int cubrid_is_instance ( resource $conn_identifier , string $oid )

The cubrid_is_instance() function is used to check whether the instance pointed by the given oid exists or not.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance that you want to check the existence.

Zwracane wartości

1, if such instance exists;

0, if such instance does not exist;

-1, in case of error

Przykłady

Przykład #1 cubrid_is_instance() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$sql = <<<EOD
SELECT host_year, medal, game_date
FROM game
WHERE athlete_code IN
    (SELECT code FROM athlete WHERE name='Thorpe Ian');
EOD;

$req = cubrid_execute($conn, $sql, CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);

$res = cubrid_is_instance ($conn, $oid);
if ($res == 1) {
    echo "Instance pointed by $oid exists.\n";
} else if ($res == 0){
    echo "Instance pointed by $oid doesn't exist.\n";
} else {
    echo "error\n";
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Instance pointed by @0|0|0 doesn't exist.

Zobacz też:

  • cubrid_drop() - Delete an instance using OID
  • cubrid_get_class_name() - Get the class name using OID

cubrid_insert_id
cubrid_lob_close
CUBRID Funkcje


Close BLOB/CLOB data

cubrid_is_instance
cubrid_lob_export
CUBRID Funkcje
PHP Manual

cubrid_lob_close

(PECL CUBRID >= 8.3.1)

cubrid_lob_close — Close BLOB/CLOB data

Opis

bool cubrid_lob_close ( array $lob_identifier_array )

cubrid_lob_close() is used to close all BLOB/CLOB returned from cubrid_lob_get().

Parametry

lob_identifier_array

LOB identifier array return from cubrid_lob_get.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_lob_close() example

<?php
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>

Zobacz też:

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

cubrid_is_instance
cubrid_lob_export
CUBRID Funkcje


Export BLOB/CLOB data to file

cubrid_lob_close
cubrid_lob_get
CUBRID Funkcje
PHP Manual

cubrid_lob_export

(PECL CUBRID >= 8.3.1)

cubrid_lob_export — Export BLOB/CLOB data to file

Opis

bool cubrid_lob_export ( resource $conn_identifier , resource $lob_identifier , string $path_name )

cubrid_lob_export() is used to get BLOB/CLOB data from CUBRID database, and saves its contents to a file. To use this function, you must use cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.

Parametry

conn_identifier

Connection identifier.

lob_identifier

LOB identifier.

path_name

Path name of the file.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_lob_export() example

<?php
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>

Zobacz też:

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

cubrid_lob_close
cubrid_lob_get
CUBRID Funkcje


Get BLOB/CLOB data

cubrid_lob_export
cubrid_lob_send
CUBRID Funkcje
PHP Manual

cubrid_lob_get

(PECL CUBRID >= 8.3.1)

cubrid_lob_get — Get BLOB/CLOB data

Opis

array cubrid_lob_get ( resource $conn_identifier , string $sql )

cubrid_lob_get() is used to get BLOB/CLOB meta info from CUBRID database, CUBRID gets BLOB/CLOB by executing the SQL statement, and returns all LOBs as a resource array. Be sure that the SQL retrieves only one column and its data type is BLOB or CLOB.

Remember to use cubrid_lob_close() to release the LOBs if you don't need it any more.

Parametry

conn_identifier

Connection identifier.

sql

SQL statement to be executed.

Zwracane wartości

Return an array of LOB resources, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_lob_get() example

<?php
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>

Zobacz też:

  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

cubrid_lob_export
cubrid_lob_send
CUBRID Funkcje


Read BLOB/CLOB data and send straight to browser

cubrid_lob_get
cubrid_lob_size
CUBRID Funkcje
PHP Manual

cubrid_lob_send

(PECL CUBRID >= 8.3.1)

cubrid_lob_send — Read BLOB/CLOB data and send straight to browser

Opis

bool cubrid_lob_send ( resource $conn_identifier , resource $lob_identifier )

cubrid_lob_send() reads BLOB/CLOB data and passes it straight through to the browser. To use this function, you must use cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.

Parametry

conn_identifier

Connection identifier.

lob_identifier

LOB identifier.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_lob_send() example

<?php
$lobs = cubrid_lob_get($con, "SELECT image FROM person WHERE id=1");
Header("Content-type: image/jpeg");
cubrid_lob_send($conn, $lobs[0]);
cubrid_lob_close($lobs);
?>

Zobacz też:

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file

cubrid_lob_get
cubrid_lob_size
CUBRID Funkcje


Get BLOB/CLOB data size

cubrid_lob_send
cubrid_lock_read
CUBRID Funkcje
PHP Manual

cubrid_lob_size

(PECL CUBRID >= 8.3.1)

cubrid_lob_size — Get BLOB/CLOB data size

Opis

string cubrid_lob_size ( resource $lob_identifier )

cubrid_lob_size() is used to get BLOB/CLOB data size.

Parametry

lob_identifier

LOB identifier.

Zwracane wartości

A string representing LOB data size, when process is successful.

FALSE, when process is unsuccessful.

Rejestr zmian

Wersja | Opis
8.4.0 | Change return value type from int to string.

Przykłady

Przykład #1 cubrid_lob_size() example

<?php
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
echo "Doc size:".cubrid_lob_size($lobs[0]);
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>

Zobacz też:

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

cubrid_lob_send
cubrid_lock_read
CUBRID Funkcje


Set a read lock on the given OID

cubrid_lob_size
cubrid_lock_write
CUBRID Funkcje
PHP Manual

cubrid_lock_read

(PECL CUBRID >= 8.3.0)

cubrid_lock_read — Set a read lock on the given OID

Opis

bool cubrid_lock_read ( resource $conn_identifier , string $oid )

The cubrid_lock_read() function is used to put read lock on the instance pointed by given oid.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance that you want to put read lock on.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_lock_read() example

<?php
$conn = cubrid_connect("localhost", 33088, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

cubrid_lock_read($conn, $oid);

$attr = cubrid_get($conn, $oid, "b");
var_dump($attr);

$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

string(9) "{1, 2, 3}"
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

Zobacz też:

  • cubrid_lock_write() - Set a write lock on the given OID

cubrid_lob_size
cubrid_lock_write
CUBRID Funkcje


Set a write lock on the given OID

cubrid_lock_read
cubrid_move_cursor
CUBRID Funkcje
PHP Manual

cubrid_lock_write

(PECL CUBRID >= 8.3.0)

cubrid_lock_write — Set a write lock on the given OID

Opis

bool cubrid_lock_write ( resource $conn_identifier , string $oid )

The cubrid_lock_write() function is used to put write lock on the instance pointed by the given oid.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance that you want to put write lock on.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_lock_write() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

cubrid_lock_write($conn, $oid);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_put($conn, $oid, "b", array(2, 4, 8));

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(3) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "8"
}

Zobacz też:

  • cubrid_lock_read() - Set a read lock on the given OID

cubrid_lock_read
cubrid_move_cursor
CUBRID Funkcje


Move the cursor in the result

cubrid_lock_write
cubrid_next_result
CUBRID Funkcje
PHP Manual

cubrid_move_cursor

(PECL CUBRID >= 8.3.0)

cubrid_move_cursor — Move the cursor in the result

Opis

int cubrid_move_cursor ( resource $req_identifier , int $offset [, int $origin = CUBRID_CURSOR_CURRENT ] )

The cubrid_move_cursor() function is used to move the current cursor location of req_identifier by the value set in the offset argument, to the direction set in the origin argument. To set the origin argument, you can use CUBRID_CURSOR_FIRST for the first part of the result, CUBRID_CURSOR_CURRENT for the current location of the result, or CUBRID_CURSOR_LAST for the last part of the result. If origin argument is not explicitly designated, then the function uses CUBRID_CURSOR_CURRENT as its default value.

If the value of cursor movement range goes over the valid limit, then the cursor moves to the next location after the valid range for the cursor. For example, if you move 20 units in the result with the size of 10, then the cursor will move to 11th place and return CUBRID_NO_MORE_DATA.

Parametry

req_identifier

Request identifier.

offset

Number of units you want to move the cursor.

origin

Location where you want to move the cursor from CUBRID_CURSOR_FIRST, CUBRID_CURSOR_CURRENT, CUBRID_CURSOR_LAST.

Zwracane wartości

CUBRID_CURSOR_SUCCESS, when process is successful.

CUBRID_NO_MORE_DATA, when it is not a valid cursor location.

CUBRID_CURSOR_ERROR, in case of error.

Przykłady

Przykład #1 cubrid_move_cursor() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");
cubrid_move_cursor($req, 1, CUBRID_CURSOR_LAST);

$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_CURRENT);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(2) {
  [0]=>
  string(1) "G"
  [1]=>
  string(4) "Gold"
}
array(2) {
  [0]=>
  string(1) "X"
  [1]=>
  string(5) "Mixed"
}
array(2) {
  [0]=>
  string(1) "M"
  [1]=>
  string(3) "Man"
}

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement

cubrid_lock_write
cubrid_next_result
CUBRID Funkcje


Get result of next query when executing multiple SQL statements

cubrid_move_cursor
cubrid_num_cols
CUBRID Funkcje
PHP Manual

cubrid_next_result

(PECL CUBRID >= 8.4.0)

cubrid_next_result — Get result of next query when executing multiple SQL statements

Opis

bool cubrid_next_result ( resource $result )

The cubrid_next_result() function is used to get results of next query if multiple SQL statements are executed and CUBRID_EXEC_QUERY_ALL flag is set upon cubrid_execute().

Parametry

result

result comes from a call to cubrid_execute()

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_next_result() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb");

$sql_stmt = "SELECT * FROM code; SELECT * FROM history WHERE host_year=2004 AND event_code=20281";
$res = cubrid_execute($conn, $sql_stmt, CUBRID_EXEC_QUERY_ALL);

get_result_info($res);
cubrid_next_result($res);
get_result_info($res);

function get_result_info($req)
{
    printf("\n------------ get_result_info --------------------\n");

    $row_num = cubrid_num_rows($req);
    $col_num = cubrid_num_cols($req);

    $column_name_list = cubrid_column_names($req);
    $column_type_list = cubrid_column_types($req);

    $column_last_name = cubrid_field_name($req, $col_num - 1);
    $column_last_table = cubrid_field_table($req, $col_num - 1);

    $column_last_type = cubrid_field_type($req, $col_num - 1);
    $column_last_len = cubrid_field_len($req, $col_num - 1);

    $column_1_flags = cubrid_field_flags($req, 1);

    printf("%-30s %d\n", "Row count:", $row_num);
    printf("%-30s %d\n", "Column count:", $col_num);
    printf("\n");

    printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Len");
    printf("------------------------------------------------------------------------------\n");

    $size = count($column_name_list);
    for($i = 0; $i < $size; $i++) {
        $column_len = cubrid_field_len($req, $i);
        printf("%-30s %-30s %-15s\n", $column_name_list[$i], $column_type_list[$i], $column_len);
    }
    printf("\n\n");

    printf("%-30s %s\n", "Last Column Name:", $column_last_name);
    printf("%-30s %s\n", "Last Column Table:", $column_last_table);
    printf("%-30s %s\n", "Last Column Type:", $column_last_type);
    printf("%-30s %d\n", "Last Column Len:", $column_last_len);
    printf("%-30s %s\n", "Second Column Flags:", $column_1_flags);

    printf("\n\n");
}
?>

Powyższy przykład wyświetli:

------------ get_result_info --------------------
Row count:                     6
Column count:                  2

Column Names                   Column Types                   Column Len
------------------------------------------------------------------------------
s_name                         char(1)                        1
f_name                         varchar(6)                     6

Last Column Name:              f_name
Last Column Table:             code
Last Column Type:              varchar(6)
Last Column Len:               6
Second Column Flags:

------------ get_result_info --------------------
Row count:                     4
Column count:                  5

Column Names                   Column Types                   Column Len
------------------------------------------------------------------------------
event_code                     integer                        11
athlete                        varchar(40)                    40
host_year                      integer                        11
score                          varchar(10)                    10
unit                           varchar(5)                     5

Last Column Name:              unit
Last Column Table:             history
Last Column Type:              varchar(5)
Last Column Len:               5
Second Column Flags:           not_null primary_key unique_key

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement

cubrid_move_cursor
cubrid_num_cols
CUBRID Funkcje


Return the number of columns in the result set

cubrid_next_result
cubrid_num_rows
CUBRID Funkcje
PHP Manual

cubrid_num_cols

(PECL CUBRID >= 8.3.0)

cubrid_num_cols — Return the number of columns in the result set

Opis

int cubrid_num_cols ( resource $result )

The cubrid_num_cols() function is used to get the number of columns from the query result. It can only be used when the query executed is a select statement.

Parametry

result

Result.

Zwracane wartości

Number of columns, when process is successful.

-1, if SQL statement is not SELECT.

Przykłady

Przykład #1 cubrid_num_cols() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Row Num: 6
Column Num: 2

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_num_rows() - Get the number of rows in the result set

cubrid_next_result
cubrid_num_rows
CUBRID Funkcje


Get the number of rows in the result set

cubrid_num_cols
cubrid_pconnect_with_url
CUBRID Funkcje
PHP Manual

cubrid_num_rows

(PECL CUBRID >= 8.3.0)

cubrid_num_rows — Get the number of rows in the result set

Opis

int cubrid_num_rows ( resource $result )

The cubrid_num_rows() function is used to get the number of rows from the query result. You can use it only when the query executed is a select statement. When you want to know such value for INSERT, UPDATE, or DELETE query, you have to use the cubrid_affected_rows() function.

Note: The cubrid_num_rows() function can only be used for synchronous query; it returns 0 when it is used for asynchronous query.

Parametry

result

Result.

Zwracane wartości

Number of rows, when process is successful.

0 when the query was done in async mode.

-1, if SQL statement is not SELECT.

Przykłady

Przykład #1 cubrid_num_rows() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Row Num: 6
Column Num: 2

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_num_cols() - Return the number of columns in the result set
  • cubrid_affected_rows() - Return the number of rows affected by the last SQL statement

cubrid_num_cols
cubrid_pconnect_with_url
CUBRID Funkcje


Open a persistent connection to CUBRID server

cubrid_num_rows
cubrid_pconnect
CUBRID Funkcje
PHP Manual

cubrid_pconnect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_pconnect_with_url — Open a persistent connection to CUBRID server

Opis

resource cubrid_pconnect_with_url ( string $conn_url [, string $userid [, string $passwd ]] )

Establishes a persistent connection to a CUBRID server.

cubrid_pconnect_with_url()() acts very much like cubrid_connect_with_url() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, port, dbname and userid. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (cubrid_close() or cubrid_disconnect() will not close links established by cubrid_pconnect_with_url()).

This type of link is therefore called 'persistent'.

<url> ::= CUBRID:<host>:<db_name>:<db_user>:<db_password>:[?<properties>]
<properties> ::= <property> [&<property>]
<properties> ::= autocommit=<autocommit_mode>
<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]
<host> := HOSTNAME | IP_ADDR
<time> := SECOND

or <url> ::= cci:CUBRID:<host>:<db_name>:......

  • host : A host name or IP address of the master database
  • db_name : A name of the database
  • db_user : A name of the database user
  • db_password : A database user password
  • autocommit : The database connection auto-commit mode
  • alhosts: Specifies the broker information of the standby server, which is used for failover when it is impossible to connect to the active server. You can specify multiple brokers for failover, and the connection to the brokers is attempted in the order listed in alhosts
  • rctime : An interval between the attempts to connect to the active broker in which failure occurred. After a failure occurs, the system connects to the broker specified by althosts (failover), terminates the transaction, and then attempts to connect to the active broker of the master database at every rctime. The default value is 600 seconds.

Parametry

conn_url

A character string that contains server connection information.

userid

User name for the database.

passwd

User password.

Zwracane wartości

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_connect_with_url() url without properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba:123456:?autocommit=off"
$con = cubrid_pconnect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   $req =cubrid_execute($con, "insert into person values(1,'James')");

   if ($req) {
      cubrid_close_request ($req);
      cubrid_commit ($con);
   } else {
      cubrid_rollback ($con);
   }
   cubrid_disconnect ($con);
}
?>

Przykład #2 cubrid_connect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba:123456:?autocommit=off&althost=10.34.63.132:33088&rctime=100"
$con = cubrid_connect_with_url ($conn_url);

if ($con) {
   echo "connected successfully";
   $req =cubrid_execute($con, "insert into person values(1,'James')");

   if ($req) {
      cubrid_close_request ($req);
      cubrid_commit ($con);
   } else {
      cubrid_rollback ($con);
   }
   cubrid_disconnect ($con);
}
?>

Zobacz też:

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_pconnect_with_url()
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

cubrid_num_rows
cubrid_pconnect
CUBRID Funkcje


Open a persistent connection to a CUBRID server

cubrid_pconnect_with_url
cubrid_prepare
CUBRID Funkcje
PHP Manual

cubrid_pconnect

(PECL CUBRID >= 8.3.1)

cubrid_pconnect — Open a persistent connection to a CUBRID server

Opis

resource cubrid_pconnect ( string $host , int $port , string $dbname [, string $userid [, string $passwd ]] )

Establishes a persistent connection to a CUBRID server.

cubrid_pconnect()() acts very much like cubrid_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, port, dbname and userid. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (cubrid_close() or cubrid_disconnect() will not close links established by cubrid_pconnect()).

This type of link is therefore called 'persistent'.

Parametry

host

Host name or IP address of CUBRID CAS server.

port

Port number of CUBRID CAS server (BROKER_PORT configured in $CUBRID/conf/cubrid_broker.conf).

dbname

Name of database.

userid

User name for the database.

passwd

User password.

Zwracane wartości

Connection identifier, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_connect() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_pconnect("localhost", 33000, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

CUBRID PHP Version:            8.4.1.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   0
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.4.1.0508
Client Info:                   8.4.1

CUBRID Charset:                iso8859-1

Zobacz też:

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

cubrid_pconnect_with_url
cubrid_prepare
CUBRID Funkcje


Prepare an SQL statement for execution

cubrid_pconnect
cubrid_put
CUBRID Funkcje
PHP Manual

cubrid_prepare

(PECL CUBRID >= 8.3.0)

cubrid_prepare — Prepare an SQL statement for execution

Opis

resource cubrid_prepare ( resource $conn_identifier , string $prepare_stmt [, int $option = 0 ] )

The cubrid_prepare() function is a sort of API which represents SQL statements compiled previously to a given connection handle. This pre-compiled SQL statement will be included in the cubrid_prepare().

Accordingly, you can use this statement effectively to execute several times repeatedly or to process long data. Only a single statement can be used and a parameter may put a question mark (?) to appropriate area in the SQL statement. Add a parameter when you bind a value in the VALUES clause of INSERT statement or in the WHERE clause. Note that it is allowed to bind a value to a MARK(?) by the cubrid_bind() only.

Parametry

conn_identifier

Connection identifier.

prepare_stmt

Prepare query.

option

OID return option CUBRID_INCLUDE_OID.

Zwracane wartości

Request identifier, if process is successful;

FALSE, if process is unsuccessful.

Przykłady

Przykład #1 cubrid_prepare() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$sql = <<<EOD
SELECT g.event_code, e.name
FROM game g
JOIN event e ON g.event_code=e.code
WHERE host_year = ? AND event_code NOT IN (SELECT event_code FROM game WHERE host_year=?) GROUP BY event_code;
EOD;

$req = cubrid_prepare($conn, $sql);

cubrid_bind($req, 1, 2004);
cubrid_bind($req, 2, 2000);
cubrid_execute($req);

$row_num = cubrid_num_rows($req);
printf("There are %d event that exits in 2004 olympic but not in 2000. For example:\n\n", $row_num);

printf("%-15s %s\n", "Event_code", "Event_name");
printf("----------------------------\n");

$row = cubrid_fetch_assoc($req);
printf("%-15d %s\n", $row["event_code"], $row["name"]);
$row = cubrid_fetch_assoc($req);
printf("%-15d %s\n", $row["event_code"], $row["name"]);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

There are 27 event that exits in 2004 olympic but not in 2000. For example:

Event_code      Event_name
----------------------------
20063           +91kg
20070           64kg

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_bind() - Bind variables to a prepared statement as parameters

cubrid_pconnect
cubrid_put
CUBRID Funkcje


Update a column using OID

cubrid_prepare
cubrid_rollback
CUBRID Funkcje
PHP Manual

cubrid_put

(PECL CUBRID >= 8.3.0)

cubrid_put — Update a column using OID

Opis

int cubrid_put ( resource $conn_identifier , string $oid [, string $attr ], mixed $value )

The cubrid_put() function is used to update an attribute of the instance of the given oid.

You can update single attribute by using string data type to set attr. In such case, you can use integer, float-point, or string type data for the value argument. To update multiple number of attributes, you can disregard the attr argument, and set value argument with associative array data type.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance that you want to update.

attr

Name of the attribute that you want to update.

value

New value that you want to assign to the attribute.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_put() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_put($conn, $oid, "b", array(2, 4, 8));

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(3) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "8"
}

Zobacz też:

  • cubrid_get() - Get a column using OID
  • cubrid_set_add() - Insert a single element to set type column using OID
  • cubrid_set_drop() - Delete an element from set type column using OID
  • cubrid_seq_insert() - Insert an element to a sequence type column using OID
  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

cubrid_prepare
cubrid_rollback
CUBRID Funkcje


Roll back a transaction

cubrid_put
cubrid_schema
CUBRID Funkcje
PHP Manual

cubrid_rollback

(PECL CUBRID >= 8.3.0)

cubrid_rollback — Roll back a transaction

Opis

bool cubrid_rollback ( resource $conn_identifier )

The cubrid_rollback() function executes rollback on the transaction pointed by conn_identifier, currently in progress.

Connection to server is closed after calling cubrid_rollback(). Connection handle, however, is still valid.

Parametry

conn_identifier

Connection identifier.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_rollback() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE publishers");

$sql = <<<EOD
CREATE TABLE publishers(
pub_id CHAR(3),
pub_name VARCHAR(20),
city VARCHAR(15),
state CHAR(2),
country VARCHAR(15)
)
EOD;

if (!cubrid_execute($conn, $sql)) {
    printf("Error facility: %d\nError code: %d\nError msg: %s\n", cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

    cubrid_disconnect($conn);
    exit;
}

$req = cubrid_prepare($conn, "INSERT INTO publishers VALUES(?, ?, ?, ?, ?)");

$id_list = array("P01", "P02", "P03", "P04");
$name_list = array("Abatis Publishers", "Core Dump Books", "Schadenfreude Press", "Tenterhooks Press");
$city_list = array("New York", "San Francisco", "Hamburg", "Berkeley");
$state_list = array("NY", "CA", NULL, "CA");
$country_list = array("USA", "USA", "Germany", "USA");

for ($i = 0, $size = count($id_list); $i < $size; $i++) {
    cubrid_bind($req, 1, $id_list[$i]);
    cubrid_bind($req, 2, $name_list[$i]);
    cubrid_bind($req, 3, $city_list[$i]);
    cubrid_bind($req, 4, $state_list[$i]);
    cubrid_bind($req, 5, $country_list[$i]);

    if (!($ret = cubrid_execute($req))) {
        break;
    }
}

if (!$ret) {
    cubrid_rollback($conn);
} else {
    cubrid_commit($conn);

    $req = cubrid_execute($conn, "SELECT * FROM publishers");
    while ($result = cubrid_fetch_assoc($req)) {
        printf("%-3s %-20s %-15s %-3s %-15s\n",
            $result["pub_id"], $result["pub_name"], $result["city"], $result["state"], $result["country"]);
    }
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

P01 Abatis Publishers    New York        NY  USA
P02 Core Dump Books      San Francisco   CA  USA
P03 Schadenfreude Press  Hamburg             Germany
P04 Tenterhooks Press    Berkeley        CA  USA

Zobacz też:

  • cubrid_commit() - Commit a transaction
  • cubrid_disconnect() - Close a database connection

cubrid_put
cubrid_schema
CUBRID Funkcje


Get the requested schema information

cubrid_rollback
cubrid_seq_drop
CUBRID Funkcje
PHP Manual

cubrid_schema

(PECL CUBRID >= 8.3.0)

cubrid_schema — Get the requested schema information

Opis

array cubrid_schema ( resource $conn_identifier , int $schema_type [, string $class_name [, string $attr_name ]] )

The cubrid_schema() function is used to get the requested schema information from database. You have to designate class_name, if you want to get information on certain class, attr_name, if you want to get information on certain attribute (can be used only with CUBRID_ SCH_ATTR_PRIVILEGE).

The result of the cubrid_schema function is returned as a two-dimensional array (column (associative array) * row (numeric array)). The following tables shows types of schema and the column structure of the result array to be returned based on the schema type.

Result Composition of Each Type
Schema | Column Number | Column Name | Value
CUBRID_SCH_CLASS | 1 | NAME |
 | 2 | TYPE | 0:system class 1:vclass 2:class
CUBRID_SCH_VCLASS | 1 | NAME |
 | 2 | TYPE | 1:vclass
CUBRID_SCH_QUERY_SPEC | 1 | QUERY_SPEC |
CUBRID_SCH_ATTRIBUTE / CUBRID_SCH_CLASS_ATTRIBUTE | 1 | ATTR_NAME |
 | 2 | DOMAIN |
 | 3 | SCALE |
 | 4 | PRECISION |
 | 5 | INDEXED | 1:indexed
 | 6 | NOT NULL | 1:not null
 | 7 | SHARED | 1:shared
 | 8 | UNIQUE | 1:unique
 | 9 | DEFAULT |
 | 10 | ATTR_ORDER | base:1
 | 11 | CLASS_NAME |
 | 12 | SOURCE_CLASS |
 | 13 | IS_KEY | 1:key
CUBRID_SCH_METHOD / CUBRID_SCH_CLASS_METHOD | 1 | NAME |
 | 2 | RET_DOMAIN |
 | 3 | ARG_DOMAIN |
CUBRID_SCH_METHOD_FILE | 1 | METHOD_FILE |
CUBRID_SCH_SUPERCLASS / CUBRID_SCH_DIRECT_SUPER_CLASS / CUBRID_SCH_SUBCLASS | 1 | CLASS_NAME |
 | 2 | TYPE | 0:system class 1:vclass 2:class
CUBRID_SCH_CONSTRAINT | 1 | TYPE | 0:unique 1:index 2:reverse unique 3:reverse index
 | 2 | NAME |
 | 3 | ATTR_NAME |
 | 4 | NUM_PAGES |
 | 5 | NUM_KEYS |
 | 6 | PRIMARY_KEY | 1:primary key
 | 7 | KEY_ORDER | base:1
CUBRID_SCH_TRIGGER | 1 | NAME |
 | 2 | STATUS |
 | 3 | EVENT |
 | 4 | TARGET_CLASS |
 | 5 | TARGET_ATTR |
 | 6 | ACTION_TIME |
 | 7 | ACTION |
 | 8 | PRIORITY |
 | 9 | CONDITION_TIME |
 | 10 | CONDITION |
CUBRID_SCH_CLASS_PRIVILEGE / CUBRID_SCH_ATTR_PRIVILEGE | 1 | CLASS_NAME / ATTR_NAME |
 | 2 | PRIVILEGE |
 | 3 | GRANTABLE |
CUBRID_SCH_PRIMARY_KEY | 1 | CLASS_NAME |
 | 2 | ATTR_NAME |
 | 3 | KEY_SEQ | base:1
 | 4 | KEY_NAME |
CUBRID_SCH_IMPORTED_KEYS / CUBRID_SCH_EXPORTED_KEYS / CUBRID_SCH_CROSS_REFERENCE | 1 | PKTABLE_NAME |
 | 2 | PKCOLUMN_NAME |
 | 3 | FKTABLE_NAME | base:1
 | 4 | FKCOLUMN_NAME |
 | 5 | KEY_SEQ | base:1
 | 6 | UPDATE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 7 | DELETE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 8 | FK_NAME |
 | 9 | PK_NAME |

Parametry

conn_identifier

Connection identifier.

schema_type

Schema data that you want to know.

class_name

Class you want to know the schema of.

attr_name

Attribute you want to know the schema of.

Zwracane wartości

Array containing the schema information, when process is successful;

FALSE, when process is unsuccessful

Rejestr zmian

Wersja | Opis
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

Przykłady

Przykład #1 cubrid_schema() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

printf("\n--- Primary Key ---\n");
$pk = cubrid_schema($conn, CUBRID_SCH_PRIMARY_KEY, "game");
var_dump($pk);

printf("\n--- Foreign Keys ---\n");
$fk = cubrid_schema($conn, CUBRID_SCH_IMPORTED_KEYS, "game");
var_dump($fk);

printf("\n--- Column Attribute ---\n");
$attr = cubrid_schema($conn, CUBRID_SCH_ATTRIBUTE, "stadium", "area");
var_dump($attr);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

--- Primary Key ---
array(3) {
  [0]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(12) "athlete_code"
    ["KEY_SEQ"]=>
    string(1) "3"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
  [1]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(10) "event_code"
    ["KEY_SEQ"]=>
    string(1) "2"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
  [2]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(9) "host_year"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
}

--- Foreign Keys ---
array(2) {
  [0]=>
  array(9) {
    ["PKTABLE_NAME"]=>
    string(7) "athlete"
    ["PKCOLUMN_NAME"]=>
    string(4) "code"
    ["FKTABLE_NAME"]=>
    string(4) "game"
    ["FKCOLUMN_NAME"]=>
    string(12) "athlete_code"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["UPDATE_RULE"]=>
    string(1) "1"
    ["DELETE_RULE"]=>
    string(1) "1"
    ["FK_NAME"]=>
    string(20) "fk_game_athlete_code"
    ["PK_NAME"]=>
    string(15) "pk_athlete_code"
  }
  [1]=>
  array(9) {
    ["PKTABLE_NAME"]=>
    string(5) "event"
    ["PKCOLUMN_NAME"]=>
    string(4) "code"
    ["FKTABLE_NAME"]=>
    string(4) "game"
    ["FKCOLUMN_NAME"]=>
    string(10) "event_code"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["UPDATE_RULE"]=>
    string(1) "1"
    ["DELETE_RULE"]=>
    string(1) "1"
    ["FK_NAME"]=>
    string(18) "fk_game_event_code"
    ["PK_NAME"]=>
    string(13) "pk_event_code"
  }
}

--- Column Attribute ---
array(1) {
  [0]=>
  array(13) {
    ["ATTR_NAME"]=>
    string(4) "area"
    ["DOMAIN"]=>
    string(1) "7"
    ["SCALE"]=>
    string(1) "2"
    ["PRECISION"]=>
    string(2) "10"
    ["INDEXED"]=>
    string(1) "0"
    ["NON_NULL"]=>
    string(1) "0"
    ["SHARED"]=>
    string(1) "0"
    ["UNIQUE"]=>
    string(1) "0"
    ["DEFAULT"]=>
    NULL
    ["ATTR_ORDER"]=>
    string(1) "4"
    ["CLASS_NAME"]=>
    string(7) "stadium"
    ["SOURCE_CLASS"]=>
    string(7) "stadium"
    ["IS_KEY"]=>
    string(1) "0"
  }
}
cubrid_rollback
cubrid_seq_drop
CUBRID Funkcje


Delete an element from sequence type column using OID

cubrid_schema
cubrid_seq_insert
CUBRID Funkcje
PHP Manual

cubrid_seq_drop

(PECL CUBRID >= 8.3.0)

cubrid_seq_drop — Delete an element from sequence type column using OID

Opis

bool cubrid_seq_drop ( resource $conn_identifier , string $oid , string $attr_name , int $index )

The cubrid_seq_drop() function is used to delete an element you request from the given sequence type attribute in the database.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute that you want to delete an element from.

index

Index of the element that you want to delete (1-based).

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_seq_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_drop($conn, $oid, "c", 4);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(3) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
}

Zobacz też:

  • cubrid_seq_insert() - Insert an element to a sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

cubrid_schema
cubrid_seq_insert
CUBRID Funkcje


Insert an element to a sequence type column using OID

cubrid_seq_drop
cubrid_seq_put
CUBRID Funkcje
PHP Manual

cubrid_seq_insert

(PECL CUBRID >= 8.3.0)

cubrid_seq_insert — Insert an element to a sequence type column using OID

Opis

bool cubrid_seq_insert ( resource $conn_identifier , string $oid , string $attr_name , int $index , string $seq_element )

The cubrid_col_insert() function is used to insert an element to a sequence type attribute in a requested location.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to insert an instance to.

index

Location of the element, you want to insert the element to (1-based).

seq_element

Content of the element that you want to insert.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_seq_insert() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_insert($conn, $oid, "c", 5, "44");

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(5) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
  [4]=>
  string(2) "44"
}

Zobacz też:

  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

cubrid_seq_drop
cubrid_seq_put
CUBRID Funkcje


Update the element value of sequence type column using OID

cubrid_seq_insert
cubrid_set_add
CUBRID Funkcje
PHP Manual

cubrid_seq_put

(PECL CUBRID >= 8.3.0)

cubrid_seq_put — Update the element value of sequence type column using OID

Opis

bool cubrid_seq_put ( resource $conn_identifier , string $oid , string $attr_name , int $index , string $seq_element )

The cubrid_seq_put() function is used to update the content of the requested element in a sequent type attribute using OID.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute that you want to update an element.

index

Index (1-based) of the element that you want to update.

seq_element

New content that you want to use for the update.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_seq_put() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_put($conn, $oid, "c", 1, "111");

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(4) {
  [0]=>
  string(3) "111"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}

Zobacz też:

  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_insert() - Insert an element to a sequence type column using OID

cubrid_seq_insert
cubrid_set_add
CUBRID Funkcje


Insert a single element to set type column using OID

cubrid_seq_put
cubrid_set_autocommit
CUBRID Funkcje
PHP Manual

cubrid_set_add

(PECL CUBRID >= 8.3.0)

cubrid_set_add — Insert a single element to set type column using OID

Opis

bool cubrid_set_add ( resource $conn_identifier , string $oid , string $attr_name , string $set_element )

The cubrid_set_add() function is used to insert a single element to a set type attribute (set, multiset, sequence) you requested.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to insert an element.

set_element

Content of the element you want to insert.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_set_add() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_set_add($conn, $oid, "b", "4");

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(4) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
}

Zobacz też:

  • cubrid_seq_drop() - Delete an element from sequence type column using OID

cubrid_seq_put
cubrid_set_autocommit
CUBRID Funkcje


Set autocommit mode of the connection

cubrid_set_add
cubrid_set_db_parameter
CUBRID Funkcje
PHP Manual

cubrid_set_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_set_autocommit — Set autocommit mode of the connection

Opis

bool cubrid_set_autocommit ( resource $conn_identifier , bool $mode )

The cubrid_set_autocommit() function is used to set the CUBRID database auto-commit mode of the current database connection.

In CUBRID PHP, an auto-commit mode is disabled by default for transaction management. When auto-commit mode is truned from off to on, any pending work is automatically committed.

Parametry

conn_identifier

Connection identifier.

mode

Auto-commit mode. The following constants can be used:

  • CUBRID_AUTOCOMMIT_FALSE
  • CUBRID_AUTOCOMMIT_TRUE

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Zobacz też:

  • cubrid_get_autocommit() - Get auto-commit mode of the connection
  • cubrid_commit() - Commit a transaction

cubrid_set_add
cubrid_set_db_parameter
CUBRID Funkcje


Sets the CUBRID database parameters

cubrid_set_autocommit
cubrid_set_drop
CUBRID Funkcje
PHP Manual

cubrid_set_db_parameter

(PECL CUBRID >= 8.4.0)

cubrid_set_db_parameter — Sets the CUBRID database parameters

Opis

bool cubrid_set_db_parameter ( resource $conn_identifier , int $param_type , int $param_value )

The cubrid_set_db_parameter() function is used to set the CUBRID database parameters. It can set the following CUBRID database parameters:

  • PARAM_ISOLATION_LEVEL
  • PARAM_LOCK_TIMEOUT

Informacja:

The auto-commit mode can be set by using cubrid_set_autocommit().

Parametry

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

param_type

Database parameter type.

param_value

Isolation level value (1-6) or lock timeout (in seconds) value.

Zwracane wartości

TRUE on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_get_db_parameter() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$params = cubrid_get_db_parameter($conn);
var_dump($params);

cubrid_set_autocommit($conn, CUBRID_AUTOCOMMIT_TRUE);
cubrid_set_db_parameter($conn, CUBRID_PARAM_ISOLATION_LEVEL, 2);

$params_new = cubrid_get_db_parameter($conn);
var_dump($params_new);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(4) {
  ["PARAM_ISOLATION_LEVEL"]=>
  int(3)
  ["PARAM_LOCK_TIMEOUT"]=>
  int(-1)
  ["PARAM_MAX_STRING_LENGTH"]=>
  int(1073741823)
  ["PARAM_AUTO_COMMIT"]=>
  int(0)
}
array(4) {
  ["PARAM_ISOLATION_LEVEL"]=>
  int(2)
  ["PARAM_LOCK_TIMEOUT"]=>
  int(-1)
  ["PARAM_MAX_STRING_LENGTH"]=>
  int(1073741823)
  ["PARAM_AUTO_COMMIT"]=>
  int(1)
}

Zobacz też:

  • cubrid_get_db_parameter() - Returns the CUBRID database parameters
  • cubrid_set_autocommit() - Set autocommit mode of the connection

cubrid_set_autocommit
cubrid_set_drop
CUBRID Funkcje


Delete an element from set type column using OID

cubrid_set_db_parameter
cubrid_set_query_timeout
CUBRID Funkcje
PHP Manual

cubrid_set_drop

(PECL CUBRID >= 8.3.0)

cubrid_set_drop — Delete an element from set type column using OID

Opis

bool cubrid_set_drop ( resource $conn_identifier , string $oid , string $attr_name , string $set_element )

The cubrid_set_drop() function is used to delete an element that you request from the given set type (set, multiset) attribute of the database.

Parametry

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to delete an element from.

set_element

Content of the element you want to delete.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_set_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_set_drop($conn, $oid, "b", "1");

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(2) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "3"
}

Zobacz też:

  • cubrid_set_add() - Insert a single element to set type column using OID

cubrid_set_db_parameter
cubrid_set_query_timeout
CUBRID Funkcje


Set the timeout time of query execution

cubrid_set_drop
cubrid_version
CUBRID Funkcje
PHP Manual

cubrid_set_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_set_query_timeout — Set the timeout time of query execution

Opis

bool cubrid_set_autocommit ( resource $req_identifier , int $timeout )

The cubrid_set_query_timeout() function is used to set the timeout time of query execution.

Parametry

req_identifier

Request identifier.

timeout

Timeout time, unit of msec.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Zobacz też:

  • cubrid_get_query_timeout() - Get the query timeout value of the request

cubrid_set_drop
cubrid_version
CUBRID Funkcje


Get the CUBRID PHP module's version

cubrid_set_query_timeout
CUBRID MySQL Compatibility Functions
CUBRID Funkcje
PHP Manual

cubrid_version

(PECL CUBRID >= 8.3.0)

cubrid_version — Get the CUBRID PHP module's version

Opis

string cubrid_version ( void )

The cubrid_version() function is used to get the CUBRID PHP module's version.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Version information (eg. "8.3.1.0001").

Przykłady

Przykład #1 cubrid_version() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

Powyższy przykład wyświetli:

CUBRID PHP Version:            8.3.1.0005

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              0

Server Info:                   8.3.1.0173
Client Info:                   8.3.1

CUBRID Charset:                iso8859-1

Zobacz też:

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_code_facility() - Get the facility code of error

cubrid_set_query_timeout
CUBRID MySQL Compatibility Functions
CUBRID Funkcje


CUBRID MySQL Compatibility Functions

Spis treści

  • cubrid_client_encoding — Return the current CUBRID connection charset
  • cubrid_close — Close CUBRID connection
  • cubrid_data_seek — Move the internal row pointer of the CUBRID result
  • cubrid_db_name — Get db name from results of cubrid_list_dbs
  • cubrid_errno — Return the numerical value of the error message from previous CUBRID operation
  • cubrid_error — Get the error message
  • cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row
  • cubrid_fetch_field — Get column information from a result and return as an object
  • cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row
  • cubrid_fetch_object — Fetche the next row and returns it as an object
  • cubrid_fetch_row — Return a numerical array with the values of the current row
  • cubrid_field_flags — Return a string with the flags of the given field offset
  • cubrid_field_len — Get the maximum length of the specified field
  • cubrid_field_name — Return the name of the specified field index
  • cubrid_field_seek — Move the result set cursor to the specified field offset
  • cubrid_field_table — Return the name of the table of the specified field
  • cubrid_field_type — Return the type of the column corresponding to the given field offset
  • cubrid_list_dbs — Return an array with the list of all existing CUBRID databases
  • cubrid_num_fields — Return the number of columns in the result set
  • cubrid_ping — Ping a server connection or reconnect if there is no connection
  • cubrid_query — Send a CUBRID query
  • cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement
  • cubrid_result — Return the value of a specific field in a specific row
  • cubrid_unbuffered_query — Perform a query without fetching the results into memory
cubrid_version
cubrid_client_encoding
CUBRID


Return the current CUBRID connection charset

CUBRID MySQL Compatibility Functions
cubrid_close
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_client_encoding

(PECL CUBRID >= 8.3.1)

cubrid_client_encoding — Return the current CUBRID connection charset

Opis

string cubrid_client_encoding ([ resource $conn_identifier ] )

This function returns the current CUBRID connection charset and is similar to the CUBRID function cubrid_get_charset().

Parametry

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

Zwracane wartości

A string that represents the CUBRID connection charset; on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_client_encoding() example

<?php

$con = cubrid_connect("localhost", 33000, "demodb");
if (!$con)
{
    die('Could not connect.');
}

printf("CUBRID current charset: %s\n", cubrid_client_encoding($con));

?>

Powyższy przykład wyświetli:

CUBRID current charset: iso8859-1

Zobacz też:

  • cubrid_get_charset() - Return the current CUBRID connection charset

CUBRID MySQL Compatibility Functions
cubrid_close
CUBRID MySQL Compatibility Functions


Close CUBRID connection

cubrid_client_encoding
cubrid_data_seek
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_close

(PECL CUBRID >= 8.3.1)

cubrid_close — Close CUBRID connection

Opis

bool cubrid_close ([ resource $conn_identifier ] )

The cubrid_close() function ends the transaction currently on process, closes the connection handle and disconnects from server. If there exists any request handle not closed yet at this point, it will be closed. It is similar to the CUBRID function cubrid_disconnect().

Parametry

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_close() example

<?php
$con = cubrid_connect ("210.211.133.100", 12345, "demodb");
if ($con) {
   echo "connected successfully";
   $req = cubrid_execute ( $con, "insert into person values(1,'James')");
   if ($req) {
      cubrid_close_request ($req);
      cubrid_commit ($con);
   } else {
      cubrid_rollback ($con);
   }
   cubrid_close ($con);
}
?>

Zobacz też:

  • cubrid_disconnect() - Close a database connection
  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server

cubrid_client_encoding
cubrid_data_seek
CUBRID MySQL Compatibility Functions


Move the internal row pointer of the CUBRID result

cubrid_close
cubrid_db_name
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_data_seek

(PECL CUBRID >= 8.3.0)

cubrid_data_seek — Move the internal row pointer of the CUBRID result

Opis

int cubrid_data_seek ( resource $result , int $row_number )

This function performs the moving of the internal row pointer of the CUBRID result (associated with the specified result identifier) to point to a specific row number. There are functions, such as cubrid_fetch_assoc(), which use the current stored value of row number.

Parametry

result

The result.

row_number

This is the desired row number of the new result pointer.

Zwracane wartości

CUBRID_CURSOR_SUCCESS, on success.

CUBRID_NO_MORE_DATA, when it is not a valid cursor location.

FALSE on CAS error, row count is 0, or invalid offset.

Przykłady

Przykład #1 cubrid_data_seek() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");
cubrid_data_seek($req, 0);

$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_data_seek($req, 2);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_data_seek($req, 4);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(2) {
  [0]=>
  string(1) "X"
  [1]=>
  string(5) "Mixed"
}
array(2) {
  [0]=>
  string(1) "M"
  [1]=>
  string(3) "Man"
}
array(2) {
  [0]=>
  string(1) "S"
  [1]=>
  string(6) "Silver"
}
cubrid_close
cubrid_db_name
CUBRID MySQL Compatibility Functions


Get db name from results of cubrid_list_dbs

cubrid_data_seek
cubrid_errno
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_db_name

(PECL CUBRID >= 8.3.1)

cubrid_db_name — Get db name from results of cubrid_list_dbs

Opis

string cubrid_db_name ( array $result , int $index )

Retrieve the database name from a call to cubrid_list_dbs().

Parametry

result

The result pointer from a call to cubrid_list_dbs().

index

The index into the result set.

Zwracane wartości

Returns the database name on success, and FALSE on failure. If FALSE is returned, use cubrid_error() to determine the nature of the error.

Przykłady

Przykład #1 cubrid_db_name() example

<?php
error_reporting(E_ALL);

$conn = cubrid_connect('dbhost', 33000, 'demodb', 'username', 'password');
$db_list = cubrid_list_dbs($conn);

$i = 0;
$cnt = cubrid_num_rows($db_list);
while ($i < $cnt) {
    echo cubrid_db_name($db_list, $i) . "\n";
    $i++;
}
?>

Zobacz też:

  • cubrid_list_dbs() - Return an array with the list of all existing CUBRID databases

cubrid_data_seek
cubrid_errno
CUBRID MySQL Compatibility Functions


Return the numerical value of the error message from previous CUBRID operation

cubrid_db_name
cubrid_error
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_errno

(PECL CUBRID >= 8.3.1)

cubrid_errno — Return the numerical value of the error message from previous CUBRID operation

Opis

int cubrid_errno ([ resource $conn_identifier ] )

Returns the error number from the last CUBRID function.

The cubrid_errno() function is used to get the error code of the error that occurred during the API execution. Usually, it gets the error code when API returns false as its return value.

Parametry

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Zwracane wartości

Returns the error number from the last CUBRID function, or 0 (zero) if no error occurred.

Przykłady

Przykład #1 cubrid_errno() example

<?php
$req = cubrid_execute($con, "select id, name from person");
if ($req) {
    while (list ($id, $name) = cubrid_fetch($req))
    echo $id, $name;
} else {
    echo "Error Code: ", cubrid_errno($con);
    echo "Error Message: ", cubrid_error($con);
}
?>

Zobacz też:

  • cubrid_error() - Get the error message
  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

cubrid_db_name
cubrid_error
CUBRID MySQL Compatibility Functions


Get the error message

cubrid_errno
cubrid_fetch_array
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_error

(PECL CUBRID >= 8.3.1)

cubrid_error — Get the error message

Opis

string cubrid_error ([ resource $connection ] )

The cubrid_error() function is used to get the error message that occurred during the use of CUBRID API. Usually, it gets error message when API returns false as its return value.

Parametry

connection

Zwracane wartości

Error message that occurred.

Przykłady

Przykład #1 cubrid_error() example

<?php
$req = cubrid_execute($con, "select id, name from person");
if ($req) {
    while (list ($id, $name) = cubrid_fetch($req))
    echo $id, $name;
} else {
    echo "Error Code: ", cubrid_errno($con);
    echo "Error Message: ", cubrid_error($con);
}
?>

Zobacz też:

  • cubrid_errno() - Return the numerical value of the error message from previous CUBRID operation
  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

cubrid_errno
cubrid_fetch_array
CUBRID MySQL Compatibility Functions


Fetch a result row as an associative array, a numeric array, or both

cubrid_error
cubrid_fetch_assoc
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_fetch_array

(PECL CUBRID >=8.3.0)

cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Opis

array cubrid_fetch_array ( resource $result [, int $type = CUBRID_BOTH ] )

The cubrid_fetch_array() function is used to get a single row from the query result and returns an array. The cursor automatically moves to the next row after getting the result.

Parametry

result

Result comes from a call to cubrid_execute()

type

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH.

Zwracane wartości

Returns an array of strings that corresponds to the fetched row, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

The type of returned array depends on how type is defined. By using CUBRID_BOTH (default), you'll get an array with both associative and number indices, and you can decide which data type to use by setting the type argument. The type variable can be set to one of the following values:

  • CUBRID_NUM : Numerical array (0-based)
  • CUBRID_ASSOC : Associative array
  • CUBRID_BOTH : Numerical & Associative array (default)

Przykłady

Przykład #1 cubrid_fetch_array() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_array($req, CUBRID_NUM)) {
    printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

Zobacz też:

  • cubrid_execute() - Execute a prepared SQL statement

cubrid_error
cubrid_fetch_assoc
CUBRID MySQL Compatibility Functions


Return the associative array that corresponds to the fetched row

cubrid_fetch_array
cubrid_fetch_field
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_fetch_assoc

(PECL CUBRID >= 8.3.0)

cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row

Opis

array cubrid_fetch_assoc ( resource $result )

This function returns the associative array, that corresponds to the fetched row, and then moves the internal data pointer ahead, or returns FALSE when the end is reached.

Parametry

result

result comes from a call to cubrid_execute()

Zwracane wartości

Associative array, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_fetch_assoc() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_assoc($req)) {
    printf("%-40s %-10s %-6s %-20s\n",
        $row["name"], $row["area"], $row["seats"], $row["address"]);
}

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece
cubrid_fetch_array
cubrid_fetch_field
CUBRID MySQL Compatibility Functions


Get column information from a result and return as an object

cubrid_fetch_assoc
cubrid_fetch_lengths
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_fetch_field

(PECL CUBRID >= 8.3.1)

cubrid_fetch_field — Get column information from a result and return as an object

Opis

object cubrid_fetch_field ( resource $result [, int $field_offset = 0 ] )

This function returns an object with certain properties of the specific column. The properties of the object are:

name

column name

table

name of the table that the column belongs to

def

default value of the column

max_length

maximum length of the column

not_null

1 if the column cannot be NULL

primary_key

1 if the column is a primary key

unique_key

1 if the column is an unique key

multiple_key

1 if the column is a non-unique key

numeric

1 if the column is numeric

blob

1 if the column is a BLOB

type

the type of the column

unsigned

1 if the column is unsigned

zerofill

1 if the column is zero-filled

Parametry

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. If the field offset is not specified, the next field (that was not yet retrieved by this function) is retrieved. The field_offset starts at 0.

Zwracane wartości

Object with certain properties of the specific column, when process is successful.

FALSE on failure.

Przykłady

Przykład #1 cubrid_fetch_field() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT event_code,athlete_code,nation_code,game_date FROM game WHERE host_year=1988 and event_code=20001;");

var_dump(cubrid_fetch_row($req));

cubrid_field_seek($req, 1);
$field = cubrid_fetch_field($req);

printf("\n--- Field Properties ---\n");
printf("%-30s %s\n", "name:", $field->name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max lenght:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "primary key:", $field->primary_key);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %d\n", "blob:", $field->blob);
printf("%-30s %s\n", "type:", $field->type);
printf("%-30s %d\n", "unsigned:", $field->unsigned);
printf("%-30s %d\n", "zerofill:", $field->zerofill);

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  string(5) "20001"
  [1]=>
  string(5) "16681"
  [2]=>
  string(3) "KOR"
  [3]=>
  string(9) "1988-9-30"
}

--- Field Properties ---
name:                          athlete_code
table:                         game
default value:                 ""
max lenght:                    5
not null:                      1
primary key:                   1
unique key:                    1
multiple key:                  0
numeric:                       1
blob:                          0
type:                          integer
unsigned:                      0
zerofill:                      0
cubrid_fetch_assoc
cubrid_fetch_lengths
CUBRID MySQL Compatibility Functions


Return an array with the lengths of the values of each field from the current row

cubrid_fetch_field
cubrid_fetch_object
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_fetch_lengths

(PECL CUBRID >= 8.3.0)

cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row

Opis

array cubrid_fetch_lengths ( resource $result )

This function returns an numeric array with the lengths of the values of each field from the current row of the result set or it returns FALSE on failure.

Informacja:

If field data type is BLOB/CLOB, you should get its length by using cubrid_lob_size().

Parametry

result

result comes from a call to cubrid_execute()

Zwracane wartości

An numeric array, when process is successful.

FALSE on failure.

Przykłady

Przykład #1 cubrid_fetch_lengths() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$row = cubrid_fetch_row($result);
print_r($row);

$lens = cubrid_fetch_lengths($result);
print_r($lens);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => 2004
    [1] => 20085
    [2] => 15118
    [3] => 30134
    [4] => AUS
    [5] => G
    [6] => 2004-8-20
)
Array
(
    [0] => 4
    [1] => 5
    [2] => 5
    [3] => 5
    [4] => 3
    [5] => 1
    [6] => 9
)
cubrid_fetch_field
cubrid_fetch_object
CUBRID MySQL Compatibility Functions


Fetche the next row and returns it as an object

cubrid_fetch_lengths
cubrid_fetch_row
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_fetch_object

(PECL CUBRID >= 8.3.0)

cubrid_fetch_object — Fetche the next row and returns it as an object

Opis

object cubrid_fetch_object ( resource $result [, string $class_name [, array $params ]] )

This function returns an object with the column names of the result set as properties. The values of these properties are extracted from the current row of the result.

Parametry

result

result comes from a call to cubrid_execute()

class_name

The name of the class to instantiate. If not specified, a stdClass (stdClass is PHP's generic empty class that's used when casting other types to objects) object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Zwracane wartości

An object, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_fetch_object() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$res = cubrid_execute($conn, "SELECT * FROM code");

var_dump(cubrid_fetch_object($res));

class demodb_code {
    public $s_name = null;
    public $f_name = null;

    public function toString() {
        var_dump($this);
    }
}

var_dump(cubrid_fetch_object($res, "demodb_code"));

class demodb_code_construct extends demodb_code {
    public function __construct($s, $f) {
        $this->s_name = $s;
        $this->f_name = $f;
    }
}

var_dump(cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name')));
var_dump(cubrid_fetch_object($res));

cubrid_close_request($res);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

object(stdClass)#1 (2) {
  ["s_name"]=>
  string(1) "X"
  ["f_name"]=>
  string(5) "Mixed"
}
object(demodb_code)#1 (2) {
  ["s_name"]=>
  string(1) "W"
  ["f_name"]=>
  string(5) "Woman"
}
object(demodb_code_construct)#1 (2) {
  ["s_name"]=>
  string(6) "s_name"
  ["f_name"]=>
  string(6) "f_name"
}
object(stdClass)#1 (2) {
  ["s_name"]=>
  string(1) "B"
  ["f_name"]=>
  string(6) "Bronze"
}
cubrid_fetch_lengths
cubrid_fetch_row
CUBRID MySQL Compatibility Functions


Return a numerical array with the values of the current row

cubrid_fetch_object
cubrid_field_flags
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_fetch_row

(PECL CUBRID >= 8.3.0)

cubrid_fetch_row — Return a numerical array with the values of the current row

Opis

array cubrid_fetch_row ( resource $result )

This function returns a numerical array with the values of the current row from the result set, starting from 0, and moves the internal data pointer ahead.

Parametry

result

result comes from a call to cubrid_execute()

Zwracane wartości

A numerical array, when process is successful.

FALSE, when there are no more rows; NULL, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_fetch_row() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_row($req)) {
    printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece
cubrid_fetch_object
cubrid_field_flags
CUBRID MySQL Compatibility Functions


Return a string with the flags of the given field offset

cubrid_fetch_row
cubrid_field_len
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_field_flags

(PECL CUBRID >= 8.3.0)

cubrid_field_flags — Return a string with the flags of the given field offset

Opis

string cubrid_field_flags ( resource $result , int $field_offset )

This function returns a string with the flags of the given field offset separated by space. You can split the returned value using explode. The possible flags could be: not_null, primary_key, unique_key, foreign_key, auto_increment, shared, reverse_index, reverse_unique and timestamp.

Parametry

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Zwracane wartości

A string with flags, when process is successful.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Przykłady

Przykład #1 cubrid_field_flags() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$col_num = cubrid_num_cols($result);

printf("%-30s %s\n", "Field Name", "Field Flags");
for($i = 0; $i < $col_num; $i++) {
    printf("%-30s %s\n", cubrid_field_name($result, $i), cubrid_field_flags($result, $i));
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Field Name                     Field Flags
host_year                      not_null primary_key unique_key
event_code                     not_null primary_key unique_key foreign_key
athlete_code                   not_null primary_key unique_key foreign_key
stadium_code                   not_null
nation_code
medal
game_date
cubrid_fetch_row
cubrid_field_len
CUBRID MySQL Compatibility Functions


Get the maximum length of the specified field

cubrid_field_flags
cubrid_field_name
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_field_len

(PECL CUBRID >= 8.3.0)

cubrid_field_len — Get the maximum length of the specified field

Opis

int cubrid_field_len ( resource $result , int $field_offset )

This function returns the maximum length of the specified field on success, or it returns FALSE on failure.

Parametry

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Zwracane wartości

Maximum length, when process is successful.

FALSE on failure.

Przykłady

Przykład #1 cubrid_field_len() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
    $column_len = cubrid_field_len($result, $i);
    printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char(3)                        3
medal                          char(1)                        1
game_date                      date                           10
cubrid_field_flags
cubrid_field_name
CUBRID MySQL Compatibility Functions


Return the name of the specified field index

cubrid_field_len
cubrid_field_seek
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_field_name

(PECL CUBRID >= 8.3.0)

cubrid_field_name — Return the name of the specified field index

Opis

string cubrid_field_name ( resource $result , int $field_offset )

This function returns the name of the specified field index on success or it returns FALSE on failure.

Parametry

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Zwracane wartości

Name of specified field index, on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_field_name() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$col_num = cubrid_num_cols($result);

printf("%-30s %s\n", "Field Name", "Field Flags");
for($i = 0; $i < $col_num; $i++) {
    printf("%-30s %s\n", cubrid_field_name($result, $i), cubrid_field_flags($result, $i));
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Field Name                     Field Flags
host_year                      not_null primary_key unique_key
event_code                     not_null primary_key unique_key foreign_key
athlete_code                   not_null primary_key unique_key foreign_key
stadium_code                   not_null
nation_code
medal
game_date
cubrid_field_len
cubrid_field_seek
CUBRID MySQL Compatibility Functions


Move the result set cursor to the specified field offset

cubrid_field_name
cubrid_field_table
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_field_seek

(PECL CUBRID >= 8.3.0)

cubrid_field_seek — Move the result set cursor to the specified field offset

Opis

bool cubrid_field_seek ( resource $result [, int $field_offset = 0 ] )

This function moves the result set cursor to the specified field offset. This offset is used by cubrid_fetch_field() if it doesn't include a field offset. It returns TRUE on success or FALSE on failure.

Parametry

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Zwracane wartości

TRUE on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_field_seek() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT event_code,athlete_code,nation_code,game_date FROM game WHERE host_year=1988 and event_code=20001;");

var_dump(cubrid_fetch_row($req));

cubrid_field_seek($req, 1);
$field = cubrid_fetch_field($req);

printf("\n--- Field Properties ---\n");
printf("%-30s %s\n", "name:", $field->name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max lenght:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %s\n", "type:", $field->type);

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  string(5) "20001"
  [1]=>
  string(5) "16681"
  [2]=>
  string(3) "KOR"
  [3]=>
  string(9) "1988-9-30"
}

--- Field Properties ---
name:                          athlete_code
table:                         game
default value:                 ""
max lenght:                    5
not null:                      1
unique key:                    1
multiple key:                  0
numeric:                       1
type:                          integer
cubrid_field_name
cubrid_field_table
CUBRID MySQL Compatibility Functions


Return the name of the table of the specified field

cubrid_field_seek
cubrid_field_type
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_field_table

(PECL CUBRID >= 8.3.0)

cubrid_field_table — Return the name of the table of the specified field

Opis

string cubrid_field_table ( resource $result , int $field_offset )

This function returns the name of the table of the specified field. This is useful when using large select queries with JOINS.

Parametry

result

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH.

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Zwracane wartości

Name of the table of the specified field, on success.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Przykłady

Przykład #1 cubrid_field_table() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM code");

$col_num = cubrid_num_cols($result);

printf("%-15s %-15s %s\n", "Field Table", "Field Name", "Field Type");
for($i = 0; $i < $col_num; $i++) {
    printf("%-15s %-15s %s\n",
        cubrid_field_table($result, $i), cubrid_field_name($result, $i), cubrid_field_type($result, $i));
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Field Table     Field Name      Field Type
code            s_name          char(1)
code            f_name          varchar(6)
cubrid_field_seek
cubrid_field_type
CUBRID MySQL Compatibility Functions


Return the type of the column corresponding to the given field offset

cubrid_field_table
cubrid_list_dbs
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_field_type

(PECL CUBRID >= 8.3.0)

cubrid_field_type — Return the type of the column corresponding to the given field offset

Opis

string cubrid_field_type ( resource $result , int $field_offset )

This function returns the type of the column corresponding to the given field offset. The returned field type could be one of the following: "int", "real", "string", etc.

Parametry

result

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH.

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

Zwracane wartości

Type of the column, on success.

FALSE when invalid field_offset value.

-1 if SQL sentence is not SELECT.

Przykłady

Przykład #1 cubrid_field_type() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM code");

$col_num = cubrid_num_cols($result);

printf("%-15s %-15s %s\n", "Field Table", "Field Name", "Field Type");
for($i = 0; $i < $col_num; $i++) {
    printf("%-15s %-15s %s\n",
        cubrid_field_table($result, $i), cubrid_field_name($result, $i), cubrid_field_type($result, $i));
}

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Field Table     Field Name      Field Type
code            s_name          char(1)
code            f_name          varchar(6)
cubrid_field_table
cubrid_list_dbs
CUBRID MySQL Compatibility Functions


Return an array with the list of all existing CUBRID databases

cubrid_field_type
cubrid_num_fields
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_list_dbs

(PECL CUBRID >= 8.3.0)

cubrid_list_dbs — Return an array with the list of all existing CUBRID databases

Opis

array cubrid_list_dbs ( resource $conn_identifier )

This function returns an array with the list of all existing Cubrid databases.

Parametry

conn_identifier

The CUBRID connection.

Zwracane wartości

An numeric array with all existing Cubrid databases; on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_list_dbs() example

<?php
$conn = cubrid_connect("localhost", 33088, "demodb");

$db_list = cubrid_list_dbs($conn);
var_dump($db_list);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(1) {
  [0]=>
  string(6) "demodb"
}
cubrid_field_type
cubrid_num_fields
CUBRID MySQL Compatibility Functions


Return the number of columns in the result set

cubrid_list_dbs
cubrid_ping
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_num_fields

(PECL CUBRID >= 8.3.0)

cubrid_num_fields — Return the number of columns in the result set

Opis

int cubrid_num_fields ( resource $result )

This function returns the number of columns in the result set, on success, or it returns FALSE on failure.

Parametry

result

result comes from a call to cubrid_execute()

Zwracane wartości

Number of columns, on success.

-1 if SQL sentence is not SELECT.

Przykłady

Przykład #1 cubrid_num_fields() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_fields($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

Row Num: 6
Column Num: 2
cubrid_list_dbs
cubrid_ping
CUBRID MySQL Compatibility Functions


Ping a server connection or reconnect if there is no connection

cubrid_num_fields
cubrid_query
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_ping

(PECL CUBRID >= 8.3.1)

cubrid_ping — Ping a server connection or reconnect if there is no connection

Opis

bool cubrid_ping ([ resource $conn_identifier ] )

Checks whether or not the connection to the server is working.

Parametry

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Zwracane wartości

Returns TRUE if the connection to the server CUBRID server is working, otherwise FALSE.

Przykłady

Przykład #1 cubrid_ping() example

<?php
set_time_limit(0);

$conn = cubrid_connect('localhost', 33000, 'demodb');

/* Assuming this query will take a long time */
$result = cubrid_query($sql);
if (!$result) {
    echo 'Query #1 failed, exiting.';
    exit;
}

/* Make sure the connection is still alive, if not, try to reconnect */
if (!cubrid_ping($conn)) {
    echo 'Lost connection, exiting after query #1';
    exit;
}
cubrid_free_result($result);

/* So the connection is still alive, let's run another query */
$result2 = cubrid_query($sql2);
?>

cubrid_num_fields
cubrid_query
CUBRID MySQL Compatibility Functions


Send a CUBRID query

cubrid_ping
cubrid_real_escape_string
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_query

(PECL CUBRID >= 8.3.1)

cubrid_query — Send a CUBRID query

Opis

resource cubrid_query ( string $query [, resource $conn_identifier ] )

cubrid_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified conn_identifier.

Parametry

query

An SQL query

Data inside the query should be properly escaped.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Zwracane wartości

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, cubrid_query() returns a resource on success, or FALSE on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, cubrid_query() returns TRUE on success or FALSE on error.

The returned result resource should be passed to cubrid_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use cubrid_num_rows() to find out how many rows were returned for a SELECT statement or cubrid_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

cubrid_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.

Przykłady

Przykład #1 Invalid Query

The following query is syntactically invalid, so cubrid_query() fails and returns FALSE.

<?php
$conn = cubrid_connect('localhost', 33000, 'foo');

$result = cubrid_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . cubrid_error());
}

?>

Przykład #2 Valid Query

The following query is valid, so cubrid_query() returns a resource.

<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname  = 'fox';

$conn = cubrid_connect('localhost', 33000, 'foo');

// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see cubrid_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
cubrid_real_escape_string($firstname),
cubrid_real_escape_string($lastname));

// Perform Query
$result = cubrid_query($query);

// Check result
// This shows the actual query sent to CUBRID, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . cubrid_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the cubrid result functions must be used
// See also cubrid_result(), cubrid_fetch_array(), cubrid_fetch_row(), etc.
while ($row = cubrid_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];
    echo $row['address'];
    echo $row['age'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
cubrid_free_result($result);
?>

Zobacz też:

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_error() - Get the error message
  • cubrid_real_escape_string() - Escape special characters in a string for use in an SQL statement
  • cubrid_result() - Return the value of a specific field in a specific row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_unbuffered_query() - Perform a query without fetching the results into memory

cubrid_ping
cubrid_real_escape_string
CUBRID MySQL Compatibility Functions


Escape special characters in a string for use in an SQL statement

cubrid_query
cubrid_result
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_real_escape_string

(PECL CUBRID >= 8.3.0)

cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement

Opis

string cubrid_real_escape_string ( string $unescaped_string [, resource $conn_identifier ] )

This function returns the escaped string version of the given string. It will escape the following characters: '. In general, single quotations are used to enclose character string. Double quotations may be used as well depending on the value of ansi_quotes, which is a parameter related to SQL statement. If the ansi_quotes value is set to no, character string enclosed by double quotations is handled as character string, not as an identifier. The default value is yes. If you want to include a single quote as part of a character string, enter two single quotes in a row.

Parametry

unescaped_string

The string that is to be escaped.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Zwracane wartości

Escaped string version of the given string, on success.

FALSE on failure.

Przykłady

Przykład #1 cubrid_real_escape_string() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$unescaped_str = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$escaped_str = cubrid_real_escape_string($unescaped_str);

$len = strlen($unescaped_str);

@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (t char($len))");
cubrid_execute($conn, "INSERT INTO cubrid_test (t) VALUES('$escaped_str')");

$req = cubrid_execute($conn, "SELECT * FROM cubrid_test");
$row = cubrid_fetch_assoc($req);

var_dump($row);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

array(1) {
  ["t"]=>
  string(95) " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
}
cubrid_query
cubrid_result
CUBRID MySQL Compatibility Functions


Return the value of a specific field in a specific row

cubrid_real_escape_string
cubrid_unbuffered_query
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_result

(PECL CUBRID >= 8.3.0)

cubrid_result — Return the value of a specific field in a specific row

Opis

string cubrid_result ( resource $result , int $row [, mixed $field = 0 ] )

This function returns the value of a specific field in a specific row from a result set.

Parametry

result

result comes from a call to cubrid_execute()

row

The row number from the result that is being retrieved. Row numbers start at 0.

field

The name or offset of the field being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved.

Zwracane wartości

Value of a specific field, on success (NULL if value if null).

FALSE on failure.

Przykłady

Przykład #1 cubrid_result() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");

$result = cubrid_result($req, 0);
var_dump($result);

$result = cubrid_result($req, 0, 1);
var_dump($result);

$result = cubrid_result($req, 5, "f_name");
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

Powyższy przykład wyświetli:

string(1) "X"
string(5) "Mixed"
string(4) "Gold"
cubrid_real_escape_string
cubrid_unbuffered_query
CUBRID MySQL Compatibility Functions


Perform a query without fetching the results into memory

cubrid_result
CUBRID Obsolete Aliases and Functions
CUBRID MySQL Compatibility Functions
PHP Manual

cubrid_unbuffered_query

(PECL CUBRID >= 8.3.0)

cubrid_unbuffered_query — Perform a query without fetching the results into memory

Opis

resource cubrid_unbuffered_query ( string $query [, resource $conn_identifier ] )

This function performs a query without waiting for that all query results have been complete. It will return when the results are being generated.

Parametry

query

A SQL query.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

Zwracane wartości

For SELECT, SHOW, DESCRIBE or EXPLAIN statements returns a connection identifier resource on success.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, returns TRUE on success.

FALSE on failure.

Notatki

Informacja:

The benefits of cubrid_unbuffered_query() come at a cost: you cannot use cubrid_num_rows() and cubrid_data_seek() on a result set returned from cubrid_unbuffered_query().

Przykłady

Przykład #1 cubrid_unbuffered_query() example

<?php
    $link = cubrid_connect("localhost", 30000, "demodb2", "dba", "");
    if (!$link)
    {
        die('Could not connect.');
    }
    $query = "insert into employees (name, address, salary) values ('Michael', 'Boston, MA', 3750)";
    cubrid_unbuffered_query($query, $link);
?>
cubrid_result
CUBRID Obsolete Aliases and Functions
CUBRID MySQL Compatibility Functions


CUBRID Obsolete Aliases and Functions

Spis treści

  • cubrid_load_from_glo — Read data from a GLO instance and save it in a file
  • cubrid_new_glo — Create a glo instance
  • cubrid_save_to_glo — Save requested file in a GLO instance
  • cubrid_send_glo — Read data from glo and send it to std output
cubrid_unbuffered_query
cubrid_load_from_glo
CUBRID


Read data from a GLO instance and save it in a file

CUBRID Obsolete Aliases and Functions
cubrid_new_glo
CUBRID Obsolete Aliases and Functions
PHP Manual

cubrid_load_from_glo

(PECL CUBRID >= 8.3.0)

cubrid_load_from_glo — Read data from a GLO instance and save it in a file

Opis

int cubrid_load_from_glo ( resource $conn_identifier , string $oid , string $file_name )

The cubrid_load_from_glo() function is used to read a data from a glo instance, and saves it in a designated file.

Parametry

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to read the data from.

file_name

Name of the file where you want to save the data in.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_load_from_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id=1");
if ($req) {
   list ($oid) = cubrid_fetch($req);
   cubrid_close_request($req);
   $res = cubrid_load_from_glo ($con, $oid, "output.jpg");
   if ($res) {
      echo "image changed successfully";
   }
}
?>

Notatki

Informacja:

Dla zachowania zgodności z poprzednimi wersjami PHP możliwe jest używanie aliasów: cubrid_load_from_glo()

Informacja:

This function is removed from CUBRID 3.1.

Zobacz też:

  • cubrid_new_glo() - Create a glo instance
  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_send_glo() - Read data from glo and send it to std output

CUBRID Obsolete Aliases and Functions
cubrid_new_glo
CUBRID Obsolete Aliases and Functions


Create a glo instance

cubrid_load_from_glo
cubrid_save_to_glo
CUBRID Obsolete Aliases and Functions
PHP Manual

cubrid_new_glo

(PECL CUBRID >= 8.3.0)

cubrid_new_glo — Create a glo instance

Opis

string cubrid_new_glo ( resource $conn_identifier , string $class_name , string $file_name )

The cubrid_new_glo() function is used to create a glo instance in the requested class (glo class). The glo created is a LO type, and is stored in the file_name file.

Parametry

conn_identifier

Connection identifier.

class_name

Name of the class that you want to create a glo in.

file_name

The file name that you want to save in the newly created glo.

Zwracane wartości

Oid of the instance created, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_new_glo() example

<?php
$oid = cubrid_new_glo ($con, "glo", "input.jpg");
if ($oid){
   // the type of column "image" is "object"
   $req = cubrid_execute ($con, "insert into person(image) values($oid)");
   if ($req) {
      echo "image inserted successfully";
      cubrid_close_request ($req);
      cubrid_commit($con);
   }
}
?>

Notatki

Informacja:

Dla zachowania zgodności z poprzednimi wersjami PHP możliwe jest używanie aliasów: cubrid_new_glo()

Informacja:

This function is removed from CUBRID 3.1.

Zobacz też:

  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file
  • cubrid_send_glo() - Read data from glo and send it to std output

cubrid_load_from_glo
cubrid_save_to_glo
CUBRID Obsolete Aliases and Functions


Save requested file in a GLO instance

cubrid_new_glo
cubrid_send_glo
CUBRID Obsolete Aliases and Functions
PHP Manual

cubrid_save_to_glo

(PECL CUBRID >= 8.3.0)

cubrid_save_to_glo — Save requested file in a GLO instance

Opis

int cubrid_save_to_glo ( resource $conn_identifier , string $oid , string $file_name )

The cubrid_save_to_glo() function is used to save requested file in a glo instance.

Parametry

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to save a file in.

file_name

The name of the file that you want to save.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_save_to_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id=1");
if ($req) {
   list ($oid) = cubrid_fetch($req);
   cubrid_close_request($req);
   $res = cubrid_save_to_glo ($con, $oid, "input.jpg");
   if ($res) {
      echo "image changed successfully";
   }
}
?>

Notatki

Informacja:

Dla zachowania zgodności z poprzednimi wersjami PHP możliwe jest używanie aliasów: cubrid_save_to_glo()

Informacja:

This function is removed from CUBRID 3.1.

Zobacz też:

  • cubrid_new_glo() - Create a glo instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file
  • cubrid_send_glo() - Read data from glo and send it to std output

cubrid_new_glo
cubrid_send_glo
CUBRID Obsolete Aliases and Functions


Read data from glo and send it to std output

cubrid_save_to_glo
DB++
CUBRID Obsolete Aliases and Functions
PHP Manual

cubrid_send_glo

(PECL CUBRID >= 8.3.0)

cubrid_send_glo — Read data from glo and send it to std output

Opis

int cubrid_send_glo ( resource $conn_identifier , string $oid )

The cubrid_send_glo() function is used to read data from glo instance and sends it to the PHP standard output.

Parametry

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to read data from.

Zwracane wartości

TRUE, when process is successful.

FALSE, when process is unsuccessful.

Przykłady

Przykład #1 cubrid_send_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id =1");
if ($req) {
  list ($oid) = cubrid_fetch($req);
  cubrid_close_request($req);
  Header ("Content-type: image/jpeg");
  cubrid_send_glo ($con, $oid);
}
?>

Notatki

Informacja:

Dla zachowania zgodności z poprzednimi wersjami PHP możliwe jest używanie aliasów: cubrid_send_glo()

Informacja:

This function is removed from CUBRID 3.1.

Zobacz też:

  • cubrid_new_glo() - Create a glo instance
  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file

cubrid_save_to_glo
DB++
CUBRID Obsolete Aliases and Functions


DB++

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
    • db++ error codes
  • DB++ Funkcje
    • dbplus_add — Add a tuple to a relation
    • dbplus_aql — Perform AQL query
    • dbplus_chdir — Get/Set database virtual current directory
    • dbplus_close — Close a relation
    • dbplus_curr — Get current tuple from relation
    • dbplus_errcode — Get error string for given errorcode or last error
    • dbplus_errno — Get error code for last operation
    • dbplus_find — Set a constraint on a relation
    • dbplus_first — Get first tuple from relation
    • dbplus_flush — Flush all changes made on a relation
    • dbplus_freealllocks — Free all locks held by this client
    • dbplus_freelock — Release write lock on tuple
    • dbplus_freerlocks — Free all tuple locks on given relation
    • dbplus_getlock — Get a write lock on a tuple
    • dbplus_getunique — Get an id number unique to a relation
    • dbplus_info — Get information about a relation
    • dbplus_last — Get last tuple from relation
    • dbplus_lockrel — Request write lock on relation
    • dbplus_next — Get next tuple from relation
    • dbplus_open — Open relation file
    • dbplus_prev — Get previous tuple from relation
    • dbplus_rchperm — Change relation permissions
    • dbplus_rcreate — Creates a new DB++ relation
    • dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices
    • dbplus_rcrtlike — Creates an empty copy of a relation with default indices
    • dbplus_resolve — Resolve host information for relation
    • dbplus_restorepos — Restore position
    • dbplus_rkeys — Specify new primary key for a relation
    • dbplus_ropen — Open relation file local
    • dbplus_rquery — Perform local (raw) AQL query
    • dbplus_rrename — Rename a relation
    • dbplus_rsecindex — Create a new secondary index for a relation
    • dbplus_runlink — Remove relation from filesystem
    • dbplus_rzap — Remove all tuples from relation
    • dbplus_savepos — Save position
    • dbplus_setindex — Set index
    • dbplus_setindexbynumber — Set index by number
    • dbplus_sql — Perform SQL query
    • dbplus_tcl — Execute TCL code on server side
    • dbplus_tremove — Remove tuple and return new current tuple
    • dbplus_undo — Undo
    • dbplus_undoprepare — Prepare undo
    • dbplus_unlockrel — Give up write lock on relation
    • dbplus_unselect — Remove a constraint from relation
    • dbplus_update — Update specified tuple in relation
    • dbplus_xlockrel — Request exclusive lock on relation
    • dbplus_xunlockrel — Free exclusive lock on relation
cubrid_send_glo
Wstęp
Rozszerzenia producentów baz danych


Wstęp

db++, made by the German company » Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really an SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra than SQL is.

Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.

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.

DB++
Instalacja/Konfiguracja
DB++


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
DB++


Wymagania

This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.

» Concept asa provides » db++ Demo versions and » documentation for Linux, some other Unix versions. There is also a Windows version of db++, but this extension doesn't support it (yet).

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.

configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path .

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

dbplus_relation

Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

Spis treści

  • db++ error codes

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.

Typy zasobów
db++ error codes
DB++


db++ error codes

DB++ Error Codes
PHP Constant | db++ constant | meaning
DBPLUS_ERR_NOERR (integer) | ERR_NOERR | Null error condition
DBPLUS_ERR_DUPLICATE (integer) | ERR_DUPLICATE | Tried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) | ERR_EOSCAN | End of scan from rget()
DBPLUS_ERR_EMPTY (integer) | ERR_EMPTY | Relation is empty (server)
DBPLUS_ERR_CLOSE (integer) | ERR_CLOSE | The server can't close
DBPLUS_ERR_WLOCKED (integer) | ERR_WLOCKED | The record is write locked
DBPLUS_ERR_LOCKED (integer) | ERR_LOCKED | Relation was already locked
DBPLUS_ERR_NOLOCK (integer) | ERR_NOLOCK | Relation cannot be locked
DBPLUS_ERR_READ (integer) | ERR_READ | Read error on relation
DBPLUS_ERR_WRITE (integer) | ERR_WRITE | Write error on relation
DBPLUS_ERR_CREATE (integer) | ERR_CREATE | Create() system call failed
DBPLUS_ERR_LSEEK (integer) | ERR_LSEEK | Lseek() system call failed
DBPLUS_ERR_LENGTH (integer) | ERR_LENGTH | Tuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) | ERR_OPEN | Open() system call failed
DBPLUS_ERR_WOPEN (integer) | ERR_WOPEN | Relation already opened for writing
DBPLUS_ERR_MAGIC (integer) | ERR_MAGIC | File is not a relation
DBPLUS_ERR_VERSION (integer) | ERR_VERSION | File is a very old relation
DBPLUS_ERR_PGSIZE (integer) | ERR_PGSIZE | Relation uses a different page size
DBPLUS_ERR_CRC (integer) | ERR_CRC | Invalid crc in the superpage
DBPLUS_ERR_PIPE (integer) | ERR_PIPE | Piped relation requires lseek()
DBPLUS_ERR_NIDX (integer) | ERR_NIDX | Too many secondary indices
DBPLUS_ERR_MALLOC (integer) | ERR_MALLOC | Malloc() call failed
DBPLUS_ERR_NUSERS (integer) | ERR_NUSERS | Error use of max users
DBPLUS_ERR_PREEXIT (integer) | ERR_PREEXIT | Caused by invalid usage
DBPLUS_ERR_ONTRAP (integer) | ERR_ONTRAP | Caused by a signal
DBPLUS_ERR_PREPROC (integer) | ERR_PREPROC | Error in the preprocessor
DBPLUS_ERR_DBPARSE (integer) | ERR_DBPARSE | Error in the parser
DBPLUS_ERR_DBRUNERR (integer) | ERR_DBRUNERR | Run error in db
DBPLUS_ERR_DBPREEXIT (integer) | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) | ERR_WAIT | Wait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) | ERR_CORRUPT_TUPLE | A client sent a corrupt tuple
DBPLUS_ERR_WARNING0 (integer) | ERR_WARNING0 | The Simple routines encountered a non fatal error which was corrected
DBPLUS_ERR_PANIC (integer) | ERR_PANIC | The server should not really die but after a disaster send ERR_PANIC to all its clients
DBPLUS_ERR_FIFO (integer) | ERR_FIFO | Can't create a fifo
DBPLUS_ERR_PERM (integer) | ERR_PERM | Permission denied
DBPLUS_ERR_TCL (integer) | ERR_TCL | TCL_error
DBPLUS_ERR_RESTRICTED (integer) | ERR_RESTRICTED | Only two users
DBPLUS_ERR_USER (integer) | ERR_USER | An error in the use of the library by an application programmer
DBPLUS_ERR_UNKNOWN (integer) | ERR_UNKNOWN |

Stałe predefiniowane
DB++ Funkcje
Stałe predefiniowane


DB++ Funkcje

Spis treści

  • dbplus_add — Add a tuple to a relation
  • dbplus_aql — Perform AQL query
  • dbplus_chdir — Get/Set database virtual current directory
  • dbplus_close — Close a relation
  • dbplus_curr — Get current tuple from relation
  • dbplus_errcode — Get error string for given errorcode or last error
  • dbplus_errno — Get error code for last operation
  • dbplus_find — Set a constraint on a relation
  • dbplus_first — Get first tuple from relation
  • dbplus_flush — Flush all changes made on a relation
  • dbplus_freealllocks — Free all locks held by this client
  • dbplus_freelock — Release write lock on tuple
  • dbplus_freerlocks — Free all tuple locks on given relation
  • dbplus_getlock — Get a write lock on a tuple
  • dbplus_getunique — Get an id number unique to a relation
  • dbplus_info — Get information about a relation
  • dbplus_last — Get last tuple from relation
  • dbplus_lockrel — Request write lock on relation
  • dbplus_next — Get next tuple from relation
  • dbplus_open — Open relation file
  • dbplus_prev — Get previous tuple from relation
  • dbplus_rchperm — Change relation permissions
  • dbplus_rcreate — Creates a new DB++ relation
  • dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices
  • dbplus_rcrtlike — Creates an empty copy of a relation with default indices
  • dbplus_resolve — Resolve host information for relation
  • dbplus_restorepos — Restore position
  • dbplus_rkeys — Specify new primary key for a relation
  • dbplus_ropen — Open relation file local
  • dbplus_rquery — Perform local (raw) AQL query
  • dbplus_rrename — Rename a relation
  • dbplus_rsecindex — Create a new secondary index for a relation
  • dbplus_runlink — Remove relation from filesystem
  • dbplus_rzap — Remove all tuples from relation
  • dbplus_savepos — Save position
  • dbplus_setindex — Set index
  • dbplus_setindexbynumber — Set index by number
  • dbplus_sql — Perform SQL query
  • dbplus_tcl — Execute TCL code on server side
  • dbplus_tremove — Remove tuple and return new current tuple
  • dbplus_undo — Undo
  • dbplus_undoprepare — Prepare undo
  • dbplus_unlockrel — Give up write lock on relation
  • dbplus_unselect — Remove a constraint from relation
  • dbplus_update — Update specified tuple in relation
  • dbplus_xlockrel — Request exclusive lock on relation
  • dbplus_xunlockrel — Free exclusive lock on relation
db++ error codes
dbplus_add
DB++


Add a tuple to a relation

DB++ Funkcje
dbplus_aql
DB++ Funkcje
PHP Manual

dbplus_add

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_add — Add a tuple to a relation

Opis

int dbplus_add ( resource $relation , array $tuple )

Adds a tuple to a relation.

Parametry

relation

tuple

An array of attribute/value pairs to be inserted into the given relation.

After successful execution this array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

Zwracane wartości

The function will return DBPLUS_ERR_NOERR on success or a db++ error code on failure.

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

  • dbplus_errcode() - Get error string for given errorcode or last error

DB++ Funkcje
dbplus_aql
DB++ Funkcje


Perform AQL query

dbplus_add
dbplus_chdir
DB++ Funkcje
PHP Manual

dbplus_aql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_aql — Perform AQL query

Opis

resource dbplus_aql ( string $query [, string $server [, string $dbpath ]] )

Executes an AQL query on the given server and dbpath.

Parametry

query

The AQL query to be executed. Further information on the AQL (Algebraic Query Language) is provided in the original db++ manual.

server

dbpath

Zwracane wartości

Returns a relation handle on success. The result data may be fetched from this relation by calling dbplus_next() and dbplus_curr(). Other relation access functions will not work on a result relation.

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.

dbplus_add
dbplus_chdir
DB++ Funkcje


Get/Set database virtual current directory

dbplus_aql
dbplus_close
DB++ Funkcje
PHP Manual

dbplus_chdir

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_chdir — Get/Set database virtual current directory

Opis

string dbplus_chdir ([ string $newdir ] )

Changes the virtual current directory where relation files will be looked for by dbplus_open().

Parametry

newdir

The new directory for relation files. You can omit this parameter to query the current working directory.

Zwracane wartości

Returns the absolute path of the current directory.

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.

dbplus_aql
dbplus_close
DB++ Funkcje


Close a relation

dbplus_chdir
dbplus_curr
DB++ Funkcje
PHP Manual

dbplus_close

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_close — Close a relation

Opis

mixed dbplus_close ( resource $relation )

Closes a relation previously opened by dbplus_open().

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

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.

dbplus_chdir
dbplus_curr
DB++ Funkcje


Get current tuple from relation

dbplus_close
dbplus_errcode
DB++ Funkcje
PHP Manual

dbplus_curr

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_curr — Get current tuple from relation

Opis

int dbplus_curr ( resource $relation , array &$tuple )

Reads the data for the current tuple for the given relation.

Parametry

relation

A relation opened by dbplus_open().

tuple

The data will be passed back in this parameter, as an associative array.

Zwracane wartości

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure.

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

  • dbplus_first() - Get first tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation
  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_close
dbplus_errcode
DB++ Funkcje


Get error string for given errorcode or last error

dbplus_curr
dbplus_errno
DB++ Funkcje
PHP Manual

dbplus_errcode

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errcode — Get error string for given errorcode or last error

Opis

string dbplus_errcode ([ int $errno ] )

Returns a clear error string for the given error code.

Parametry

errno

The error code. If not provided, the result code of the last db++ operation is assumed.

Zwracane wartości

Returns the error message.

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.

dbplus_curr
dbplus_errno
DB++ Funkcje


Get error code for last operation

dbplus_errcode
dbplus_find
DB++ Funkcje
PHP Manual

dbplus_errno

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errno — Get error code for last operation

Opis

int dbplus_errno ( void )

Returns the error code returned by the last db++ operation.

Zwracane wartości

Returns the error code, as an integer.

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

  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_errcode
dbplus_find
DB++ Funkcje


Set a constraint on a relation

dbplus_errno
dbplus_first
DB++ Funkcje
PHP Manual

dbplus_find

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_find — Set a constraint on a relation

Opis

int dbplus_find ( resource $relation , array $constraints , mixed $tuple )

Places a constraint on the given relation.

Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Parametry

relation

A relation opened by dbplus_open().

constraints

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

tuple

Zwracane wartości

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

  • dbplus_unselect() - Remove a constraint from relation

dbplus_errno
dbplus_first
DB++ Funkcje


Get first tuple from relation

dbplus_find
dbplus_flush
DB++ Funkcje
PHP Manual

dbplus_first

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_first — Get first tuple from relation

Opis

int dbplus_first ( resource $relation , array &$tuple )

Reads the data for the first tuple for the given relation, makes it the current tuple and pass it back as an associative array in tuple.

Parametry

relation

A relation opened by dbplus_open().

tuple

Zwracane wartości

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

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

  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation
  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_find
dbplus_flush
DB++ Funkcje


Flush all changes made on a relation

dbplus_first
dbplus_freealllocks
DB++ Funkcje
PHP Manual

dbplus_flush

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_flush — Flush all changes made on a relation

Opis

int dbplus_flush ( resource $relation )

Writes all changes applied to relation since the last flush to disk.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

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

  • dbplus_errcode() - Get error string for given errorcode or last error

dbplus_first
dbplus_freealllocks
DB++ Funkcje


Free all locks held by this client

dbplus_flush
dbplus_freelock
DB++ Funkcje
PHP Manual

dbplus_freealllocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freealllocks — Free all locks held by this client

Opis

int dbplus_freealllocks ( void )

Frees all tuple locks held by this client.

Zwracane wartości

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

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation

dbplus_flush
dbplus_freelock
DB++ Funkcje


Release write lock on tuple

dbplus_freealllocks
dbplus_freerlocks
DB++ Funkcje
PHP Manual

dbplus_freelock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freelock — Release write lock on tuple

Opis

int dbplus_freelock ( resource $relation , string $tuple )

Releases a write lock on the given tuple previously obtained by dbplus_getlock().

Parametry

relation

A relation opened by dbplus_open().

tuple

Zwracane wartości

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

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation
  • dbplus_freealllocks() - Free all locks held by this client

dbplus_freealllocks
dbplus_freerlocks
DB++ Funkcje


Free all tuple locks on given relation

dbplus_freelock
dbplus_getlock
DB++ Funkcje
PHP Manual

dbplus_freerlocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freerlocks — Free all tuple locks on given relation

Opis

int dbplus_freerlocks ( resource $relation )

Frees all tuple locks held on the given relation.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freealllocks() - Free all locks held by this client

dbplus_freelock
dbplus_getlock
DB++ Funkcje


Get a write lock on a tuple

dbplus_freerlocks
dbplus_getunique
DB++ Funkcje
PHP Manual

dbplus_getlock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getlock — Get a write lock on a tuple

Opis

int dbplus_getlock ( resource $relation , string $tuple )

Requests a write lock on the specified tuple.

Parametry

relation

A relation opened by dbplus_open().

tuple

Zwracane wartości

Returns zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED on failure.

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

  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation
  • dbplus_freealllocks() - Free all locks held by this client

dbplus_freerlocks
dbplus_getunique
DB++ Funkcje


Get an id number unique to a relation

dbplus_getlock
dbplus_info
DB++ Funkcje
PHP Manual

dbplus_getunique

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getunique — Get an id number unique to a relation

Opis

int dbplus_getunique ( resource $relation , int $uniqueid )

Obtains a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

Parametry

relation

A relation opened by dbplus_open().

uniqueid

Zwracane wartości

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

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.

dbplus_getlock
dbplus_info
DB++ Funkcje


Get information about a relation

dbplus_getunique
dbplus_last
DB++ Funkcje
PHP Manual

dbplus_info

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_info — Get information about a relation

Opis

int dbplus_info ( resource $relation , string $key , array &$result )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

relation

A relation opened by dbplus_open().

key

result

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.

dbplus_getunique
dbplus_last
DB++ Funkcje


Get last tuple from relation

dbplus_info
dbplus_lockrel
DB++ Funkcje
PHP Manual

dbplus_last

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_last — Get last tuple from relation

Opis

int dbplus_last ( resource $relation , array &$tuple )

Reads the data for the last tuple for the given relation, makes it the current tuple and pass it back as an associative array in tuple.

Parametry

relation

A relation opened by dbplus_open().

tuple

Zwracane wartości

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

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

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation

dbplus_info
dbplus_lockrel
DB++ Funkcje


Request write lock on relation

dbplus_last
dbplus_next
DB++ Funkcje
PHP Manual

dbplus_lockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_lockrel — Request write lock on relation

Opis

int dbplus_lockrel ( resource $relation )

Requests a write lock on the given relation.

Other clients may still query the relation, but can't alter it while it is locked.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_last
dbplus_next
DB++ Funkcje


Get next tuple from relation

dbplus_lockrel
dbplus_open
DB++ Funkcje
PHP Manual

dbplus_next

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_next — Get next tuple from relation

Opis

int dbplus_next ( resource $relation , array &$tuple )

Reads the data for the next tuple for the given relation, makes it the current tuple and will pass it back as an associative array in tuple.

Parametry

relation

A relation opened by dbplus_open().

tuple

Zwracane wartości

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

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

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_last() - Get last tuple from relation

dbplus_lockrel
dbplus_open
DB++ Funkcje


Open relation file

dbplus_next
dbplus_prev
DB++ Funkcje
PHP Manual

dbplus_open

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_open — Open relation file

Opis

resource dbplus_open ( string $name )

Opens the given relation file.

Parametry

name

Can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

Zwracane wartości

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

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.

dbplus_next
dbplus_prev
DB++ Funkcje


Get previous tuple from relation

dbplus_open
dbplus_rchperm
DB++ Funkcje
PHP Manual

dbplus_prev

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_prev — Get previous tuple from relation

Opis

int dbplus_prev ( resource $relation , array &$tuple )

Reads the data for the previous tuple for the given relation, makes it the current tuple and will pass it back as an associative array in tuple.

Parametry

relation

A relation opened by dbplus_open().

tuple

Zwracane wartości

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

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

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation

dbplus_open
dbplus_rchperm
DB++ Funkcje


Change relation permissions

dbplus_prev
dbplus_rcreate
DB++ Funkcje
PHP Manual

dbplus_rchperm

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rchperm — Change relation permissions

Opis

int dbplus_rchperm ( resource $relation , int $mask , string $user , string $group )

Changes access permissions as specified by mask, user and group. The values for these are operating system specific.

Parametry

relation

A relation opened by dbplus_open().

mask

user

group

Zwracane wartości

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.

dbplus_prev
dbplus_rcreate
DB++ Funkcje


Creates a new DB++ relation

dbplus_rchperm
dbplus_rcrtexact
DB++ Funkcje
PHP Manual

dbplus_rcreate

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcreate — Creates a new DB++ relation

Opis

resource dbplus_rcreate ( string $name , mixed $domlist [, bool $overwrite ] )

Creates a new relation. Any existing relation sharing the same name will be overwritten if the relation is currently not in use and overwrite is set to TRUE.

Parametry

name

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

This parameter should contain the domain specification for the new relation within an array of domain description strings. A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

Informacja:

This function will also accept a string with space delimited domain description strings, but it is recommended to use an array

overwrite

Zwracane wartości

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.

dbplus_rchperm
dbplus_rcrtexact
DB++ Funkcje


Creates an exact but empty copy of a relation including indices

dbplus_rcreate
dbplus_rcrtlike
DB++ Funkcje
PHP Manual

dbplus_rcrtexact

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices

Opis

mixed dbplus_rcrtexact ( string $name , resource $relation [, bool $overwrite ] )

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name.

Parametry

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Zwracane wartości

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

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.

dbplus_rcreate
dbplus_rcrtlike
DB++ Funkcje


Creates an empty copy of a relation with default indices

dbplus_rcrtexact
dbplus_resolve
DB++ Funkcje
PHP Manual

dbplus_rcrtlike

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcrtlike — Creates an empty copy of a relation with default indices

Opis

mixed dbplus_rcrtlike ( string $name , resource $relation [, int $overwrite ] )

dbplus_rcrtexact() will create an empty copy of the given relation under a new name, but with default indices.

Parametry

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Zwracane wartości

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

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.

dbplus_rcrtexact
dbplus_resolve
DB++ Funkcje


Resolve host information for relation

dbplus_rcrtlike
dbplus_restorepos
DB++ Funkcje
PHP Manual

dbplus_resolve

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_resolve — Resolve host information for relation

Opis

array dbplus_resolve ( string $relation_name )

dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host.

Parametry

relation_name

The relation name.

Zwracane wartości

Returns an array containing these values under the keys sid, host and host_path or FALSE on error.

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

  • dbplus_tcl() - Execute TCL code on server side

dbplus_rcrtlike
dbplus_restorepos
DB++ Funkcje


Restore position

dbplus_resolve
dbplus_rkeys
DB++ Funkcje
PHP Manual

dbplus_restorepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_restorepos — Restore position

Opis

int dbplus_restorepos ( resource $relation , array $tuple )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

relation

A relation opened by dbplus_open().

tuple

Zwracane wartości

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.

dbplus_resolve
dbplus_rkeys
DB++ Funkcje


Specify new primary key for a relation

dbplus_restorepos
dbplus_ropen
DB++ Funkcje
PHP Manual

dbplus_rkeys

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rkeys — Specify new primary key for a relation

Opis

mixed dbplus_rkeys ( resource $relation , mixed $domlist )

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

Parametry

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

Zwracane wartości

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

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.

dbplus_restorepos
dbplus_ropen
DB++ Funkcje


Open relation file local

dbplus_rkeys
dbplus_rquery
DB++ Funkcje
PHP Manual

dbplus_ropen

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_ropen — Open relation file local

Opis

resource dbplus_ropen ( string $name )

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_curr() and dbplus_next() may be applied to the returned relation.

Parametry

name

Zwracane wartości

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.

dbplus_rkeys
dbplus_rquery
DB++ Funkcje


Perform local (raw) AQL query

dbplus_ropen
dbplus_rrename
DB++ Funkcje
PHP Manual

dbplus_rquery

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rquery — Perform local (raw) AQL query

Opis

resource dbplus_rquery ( string $query [, string $dbpath ] )

dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.

Parametry

query

dbpath

Zwracane wartości

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.

dbplus_ropen
dbplus_rrename
DB++ Funkcje


Rename a relation

dbplus_rquery
dbplus_rsecindex
DB++ Funkcje
PHP Manual

dbplus_rrename

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rrename — Rename a relation

Opis

int dbplus_rrename ( resource $relation , string $name )

dbplus_rrename() will change the name of relation to name.

Parametry

relation

A relation opened by dbplus_open().

name

Zwracane wartości

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.

dbplus_rquery
dbplus_rsecindex
DB++ Funkcje


Create a new secondary index for a relation

dbplus_rrename
dbplus_runlink
DB++ Funkcje
PHP Manual

dbplus_rsecindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rsecindex — Create a new secondary index for a relation

Opis

mixed dbplus_rsecindex ( resource $relation , mixed $domlist , int $type )

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

Parametry

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

type

Zwracane wartości

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

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.

dbplus_rrename
dbplus_runlink
DB++ Funkcje


Remove relation from filesystem

dbplus_rsecindex
dbplus_rzap
DB++ Funkcje
PHP Manual

dbplus_runlink

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_runlink — Remove relation from filesystem

Opis

int dbplus_runlink ( resource $relation )

dbplus_runlink() will close and remove the relation.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_rsecindex
dbplus_rzap
DB++ Funkcje


Remove all tuples from relation

dbplus_runlink
dbplus_savepos
DB++ Funkcje
PHP Manual

dbplus_rzap

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rzap — Remove all tuples from relation

Opis

int dbplus_rzap ( resource $relation )

dbplus_rzap() will remove all tuples from relation.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_runlink
dbplus_savepos
DB++ Funkcje


Save position

dbplus_rzap
dbplus_setindex
DB++ Funkcje
PHP Manual

dbplus_savepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_savepos — Save position

Opis

int dbplus_savepos ( resource $relation )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_rzap
dbplus_setindex
DB++ Funkcje


Set index

dbplus_savepos
dbplus_setindexbynumber
DB++ Funkcje
PHP Manual

dbplus_setindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindex — Set index

Opis

int dbplus_setindex ( resource $relation , string $idx_name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

relation

A relation opened by dbplus_open().

idx_name

Zwracane wartości

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.

dbplus_savepos
dbplus_setindexbynumber
DB++ Funkcje


Set index by number

dbplus_setindex
dbplus_sql
DB++ Funkcje
PHP Manual

dbplus_setindexbynumber

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindexbynumber — Set index by number

Opis

int dbplus_setindexbynumber ( resource $relation , int $idx_number )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

relation

A relation opened by dbplus_open().

idx_number

Zwracane wartości

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.

dbplus_setindex
dbplus_sql
DB++ Funkcje


Perform SQL query

dbplus_setindexbynumber
dbplus_tcl
DB++ Funkcje
PHP Manual

dbplus_sql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_sql — Perform SQL query

Opis

resource dbplus_sql ( string $query [, string $server [, string $dbpath ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

query

server

dbpath

Zwracane wartości

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.

dbplus_setindexbynumber
dbplus_tcl
DB++ Funkcje


Execute TCL code on server side

dbplus_sql
dbplus_tremove
DB++ Funkcje
PHP Manual

dbplus_tcl

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tcl — Execute TCL code on server side

Opis

string dbplus_tcl ( int $sid , string $script )

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

Parametry

sid

script

Zwracane wartości

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

  • dbplus_resolve() - Resolve host information for relation

dbplus_sql
dbplus_tremove
DB++ Funkcje


Remove tuple and return new current tuple

dbplus_tcl
dbplus_undo
DB++ Funkcje
PHP Manual

dbplus_tremove

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tremove — Remove tuple and return new current tuple

Opis

int dbplus_tremove ( resource $relation , array $tuple [, array &$current ] )

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().

Parametry

relation

A relation opened by dbplus_open().

tuple

current

Zwracane wartości

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.

dbplus_tcl
dbplus_undo
DB++ Funkcje


Undo

dbplus_tremove
dbplus_undoprepare
DB++ Funkcje
PHP Manual

dbplus_undo

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undo — Undo

Opis

int dbplus_undo ( resource $relation )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_tremove
dbplus_undoprepare
DB++ Funkcje


Prepare undo

dbplus_undo
dbplus_unlockrel
DB++ Funkcje
PHP Manual

dbplus_undoprepare

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undoprepare — Prepare undo

Opis

int dbplus_undoprepare ( resource $relation )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_undo
dbplus_unlockrel
DB++ Funkcje


Give up write lock on relation

dbplus_undoprepare
dbplus_unselect
DB++ Funkcje
PHP Manual

dbplus_unlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unlockrel — Give up write lock on relation

Opis

int dbplus_unlockrel ( resource $relation )

Release a write lock previously obtained by dbplus_lockrel().

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_undoprepare
dbplus_unselect
DB++ Funkcje


Remove a constraint from relation

dbplus_unlockrel
dbplus_update
DB++ Funkcje
PHP Manual

dbplus_unselect

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unselect — Remove a constraint from relation

Opis

int dbplus_unselect ( resource $relation )

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_unlockrel
dbplus_update
DB++ Funkcje


Update specified tuple in relation

dbplus_unselect
dbplus_xlockrel
DB++ Funkcje
PHP Manual

dbplus_update

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_update — Update specified tuple in relation

Opis

int dbplus_update ( resource $relation , array $old , array $new )

dbplus_update() replaces the old tuple with the data from the new one, only if the old completely matches a tuple within relation.

Parametry

relation

A relation opened by dbplus_open().

old

The old tuple.

new

The new tuple.

Zwracane wartości

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.

dbplus_unselect
dbplus_xlockrel
DB++ Funkcje


Request exclusive lock on relation

dbplus_update
dbplus_xunlockrel
DB++ Funkcje
PHP Manual

dbplus_xlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xlockrel — Request exclusive lock on relation

Opis

int dbplus_xlockrel ( resource $relation )

Request an exclusive lock on relation preventing even read access from other clients.

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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

  • dbplus_xunlockrel() - Free exclusive lock on relation

dbplus_update
dbplus_xunlockrel
DB++ Funkcje


Free exclusive lock on relation

dbplus_xlockrel
dBase
DB++ Funkcje
PHP Manual

dbplus_xunlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xunlockrel — Free exclusive lock on relation

Opis

int dbplus_xunlockrel ( resource $relation )

Releases an exclusive lock previously obtained by dbplus_xlockrel().

Parametry

relation

A relation opened by dbplus_open().

Zwracane wartości

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.

dbplus_xlockrel
dBase
DB++ Funkcje


dBase

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • dBase Funkcje
    • dbase_add_record — Adds a record to a database
    • dbase_close — Closes a database
    • dbase_create — Creates a database
    • dbase_delete_record — Deletes a record from a database
    • dbase_get_header_info — Gets the header info of a database
    • dbase_get_record_with_names — Gets a record from a database as an associative array
    • dbase_get_record — Gets a record from a database as an indexed array
    • dbase_numfields — Gets the number of fields of a database
    • dbase_numrecords — Gets the number of records in a database
    • dbase_open — Opens a database
    • dbase_pack — Packs a database
    • dbase_replace_record — Replaces a record in a database
dbplus_xunlockrel
Wstęp
Rozszerzenia producentów baz danych


Wstęp

These functions allow you to access records stored in dBase-format (dbf) databases.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack().

The types of dBase fields available are:

Available types of fields
Field | dBase Type | Format | Additional information
M | Memo | n/a | This type is not supported by PHP, such field will be ignored
D | Date | YYYYMMDD | The field length is limited to 8
N | Number | A number | You must declare a length and a precision (the number of digits after the decimal point)
C | String | A string | You must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length.
L | Boolean | T or Y for TRUE, F or N for FALSE | Stored and returned as an integer (1 or 0)
F | Float | A float number | Support for this type of field was added in PHP 5.2.0

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.3.0.

Ostrzeżenie

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent web server processes modifying the same dBase file will very likely ruin your database.

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; » MySQL or » Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.

dBase
Instalacja/Konfiguracja
dBase


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
dBase


Instalacja

In order to enable the bundled dbase library and to use these functions, you must compile PHP with the --enable-dbase option.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
dBase Funkcje
dBase


dBase Funkcje

Przykłady

Many examples in this reference require a dBase database. We will use /tmp/test.dbf that will be created in the example of dbase_create().

Spis treści

  • dbase_add_record — Adds a record to a database
  • dbase_close — Closes a database
  • dbase_create — Creates a database
  • dbase_delete_record — Deletes a record from a database
  • dbase_get_header_info — Gets the header info of a database
  • dbase_get_record_with_names — Gets a record from a database as an associative array
  • dbase_get_record — Gets a record from a database as an indexed array
  • dbase_numfields — Gets the number of fields of a database
  • dbase_numrecords — Gets the number of records in a database
  • dbase_open — Opens a database
  • dbase_pack — Packs a database
  • dbase_replace_record — Replaces a record in a database
Stałe predefiniowane
dbase_add_record
dBase


Adds a record to a database

dBase Funkcje
dbase_close
dBase Funkcje
PHP Manual

dbase_add_record

(PHP 4, PHP 5)

dbase_add_record — Adds a record to a database

Opis

bool dbase_add_record ( int $dbase_identifier , array $record )

Adds the given data to the database.

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

Informacja:

If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Inserting a record in a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  dbase_add_record($db, array(
      date('Ymd'),
      'Maxim Topolov',
      '23',
      'max@example.com',
      'T'));
  dbase_close($db);
}

?>

Zobacz też:

  • dbase_delete_record() - Deletes a record from a database
  • dbase_replace_record() - Replaces a record in a database

dBase Funkcje
dbase_close
dBase Funkcje


Closes a database

dbase_add_record
dbase_create
dBase Funkcje
PHP Manual

dbase_close

(PHP 4, PHP 5)

dbase_close — Closes a database

Opis

bool dbase_close ( int $dbase_identifier )

Closes the given database link identifier.

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Closing a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..

  dbase_close($db);
}

?>

Zobacz też:

  • dbase_open() - Opens a database
  • dbase_create() - Creates a database

dbase_add_record
dbase_create
dBase Funkcje


Creates a database

dbase_close
dbase_delete_record
dBase Funkcje
PHP Manual

dbase_create

(PHP 4, PHP 5)

dbase_create — Creates a database

Opis

int dbase_create ( string $filename , array $fields )

dbase_create() creates a dBase database with the given definition.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Informacja:

Ta funkcja podlega restrykcjom open_basedir.

Parametry

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

fields

An array of arrays, each array describing the format of one field of the database. Each field consists of a name, a character indicating the field type, and optionally, a length, and a precision.

Informacja:

The fieldnames are limited in length and must not exceed 10 chars.

Zwracane wartości

Returns a database link identifier if the database is successfully created, or FALSE if an error occurred.

Przykłady

Przykład #1 Creating a dBase database file

<?php

// database "definition"
$def = array(
  array("date",     "D"),
  array("name",     "C",  50),
  array("age",      "N",   3, 0),
  array("email",    "C", 128),
  array("ismember", "L")
);

// creation
if (!dbase_create('/tmp/test.dbf', $def)) {
  echo "Error, can't create the database\n";
}

?>

Zobacz też:

  • dbase_open() - Opens a database
  • dbase_close() - Closes a database

dbase_close
dbase_delete_record
dBase Funkcje


Deletes a record from a database

dbase_create
dbase_get_header_info
dBase Funkcje
PHP Manual

dbase_delete_record

(PHP 4, PHP 5)

dbase_delete_record — Deletes a record from a database

Opis

bool dbase_delete_record ( int $dbase_identifier , int $record_number )

Marks the given record to be deleted from the database.

Informacja:

To actually remove the record from the database, you must also call dbase_pack().

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • dbase_add_record() - Adds a record to a database
  • dbase_replace_record() - Replaces a record in a database

dbase_create
dbase_get_header_info
dBase Funkcje


Gets the header info of a database

dbase_delete_record
dbase_get_record_with_names
dBase Funkcje
PHP Manual

dbase_get_header_info

(PHP 5)

dbase_get_header_info — Gets the header info of a database

Opis

array dbase_get_header_info ( int $dbase_identifier )

Returns information on the column structure of the given database link identifier.

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Zwracane wartości

An indexed array with an entry for each column in the database. The array index starts at 0.

Each array element contains an associative array of column information, as described here:

name
The name of the column
type
The human-readable name for the dbase type of the column (i.e. date, boolean, etc.)
length
The number of bytes this column can hold
precision
The number of digits of decimal precision for the column
format
A suggested printf() format specifier for the column
offset
The byte offset of the column from the start of the row

If the database header information cannot be read, FALSE is returned.

Przykłady

Przykład #1 Showing header information for a dBase database file

<?php
// Path to dbase file
$db_path = "/tmp/test.dbf";

// Open dbase file
$dbh = dbase_open($db_path, 0)
  or die("Error! Could not open dbase database file '$db_path'.");

// Get column information
$column_info = dbase_get_header_info($dbh);

// Display information
print_r($column_info);
?>

dbase_delete_record
dbase_get_record_with_names
dBase Funkcje


Gets a record from a database as an associative array

dbase_get_header_info
dbase_get_record
dBase Funkcje
PHP Manual

dbase_get_record_with_names

(PHP 4, PHP 5)

dbase_get_record_with_names — Gets a record from a database as an associative array

Opis

array dbase_get_record_with_names ( int $dbase_identifier , int $record_number )

Gets a record from a dBase database as an associative array.

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

Zwracane wartości

An associative array with the record. This will also include a key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.
  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record_with_names() will return FALSE.

Przykłady

Przykład #1 Listing all the registered members in the database

<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      $row = dbase_get_record_with_names($db, $i);
      if ($row['ismember'] == 1) {
          echo "Member #$i: " . trim($row['name']) . "\n";
      }
  }
}
?>

Zobacz też:

  • dbase_get_record() - Gets a record from a database as an indexed array

dbase_get_header_info
dbase_get_record
dBase Funkcje


Gets a record from a database as an indexed array

dbase_get_record_with_names
dbase_numfields
dBase Funkcje
PHP Manual

dbase_get_record

(PHP 4, PHP 5)

dbase_get_record — Gets a record from a database as an indexed array

Opis

array dbase_get_record ( int $dbase_identifier , int $record_number )

Gets a record from a database as an indexed array.

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_number

The index of the record.

Zwracane wartości

An indexed array with the record. This array will also include an associative key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings.
  • Integers that would have caused an overflow (> 32 bits) are returned as strings.

On error, dbase_get_record() will return FALSE.

Zobacz też:

  • dbase_get_record_with_names() - Gets a record from a database as an associative array

dbase_get_record_with_names
dbase_numfields
dBase Funkcje


Gets the number of fields of a database

dbase_get_record
dbase_numrecords
dBase Funkcje
PHP Manual

dbase_numfields

(PHP 4, PHP 5)

dbase_numfields — Gets the number of fields of a database

Opis

int dbase_numfields ( int $dbase_identifier )

Gets the number of fields (columns) in the specified database.

Informacja:

Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Zwracane wartości

The number of fields in the database, or FALSE if an error occurs.

Przykłady

Przykład #1 dbase_numfields() Example

<?php

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i = 0; $i < $nf; $i++) {
  echo $rec[$i], "\n";
}

?>

Zobacz też:

  • dbase_numrecords() - Gets the number of records in a database

dbase_get_record
dbase_numrecords
dBase Funkcje


Gets the number of records in a database

dbase_numfields
dbase_open
dBase Funkcje
PHP Manual

dbase_numrecords

(PHP 4, PHP 5)

dbase_numrecords — Gets the number of records in a database

Opis

int dbase_numrecords ( int $dbase_identifier )

Gets the number of records (rows) in the specified database.

Informacja:

Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Zwracane wartości

The number of records in the database, or FALSE if an error occurs.

Przykłady

Przykład #1 Looping over all the records of the database

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      // do something here, for each record
  }
}

?>

Zobacz też:

  • dbase_numfields() - Gets the number of fields of a database

dbase_numfields
dbase_open
dBase Funkcje


Opens a database

dbase_numrecords
dbase_pack
dBase Funkcje
PHP Manual

dbase_open

(PHP 4, PHP 5)

dbase_open — Opens a database

Opis

int dbase_open ( string $filename , int $mode )

dbase_open() opens a dBase database with the given access mode.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Informacja:

Ta funkcja podlega restrykcjom open_basedir.

Parametry

filename

The name of the database. It can be a relative or absolute path to the file where dBase will store your data.

mode

An integer which correspond to those for the open() system call (Typically 0 means read-only, 1 means write-only, and 2 means read and write).

Informacja:

You can't open a dBase file in write-only mode as the function will fail to read the headers information and thus you can't use 1 as mode.

Przykłady

Przykład #1 Opening a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
  // read some data ..

  dbase_close($db);
}

?>

Zwracane wartości

Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.

Zobacz też:

  • dbase_create() - Creates a database
  • dbase_close() - Closes a database

dbase_numrecords
dbase_pack
dBase Funkcje


Packs a database

dbase_open
dbase_replace_record
dBase Funkcje
PHP Manual

dbase_pack

(PHP 4, PHP 5)

dbase_pack — Packs a database

Opis

bool dbase_pack ( int $dbase_identifier )

Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record().

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Emptying a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  $record_numbers = dbase_numrecords($db);
  for ($i = 1; $i <= $record_numbers; $i++) {
      dbase_delete_record($db, $i);
  }
  // expunge the database
  dbase_pack($db);
}

?>

Zobacz też:

  • dbase_delete_record() - Deletes a record from a database

dbase_open
dbase_replace_record
dBase Funkcje


Replaces a record in a database

dbase_pack
filePro
dBase Funkcje
PHP Manual

dbase_replace_record

(PHP 4, PHP 5)

dbase_replace_record — Replaces a record in a database

Opis

bool dbase_replace_record ( int $dbase_identifier , array $record , int $record_number )

Replaces the given record in the database with the given data.

Parametry

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_replace_record() will fail.

Informacja:

If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

record_number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Updating a record in the database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
  // gets the old row
  $row = dbase_get_record_with_names($db, 1);

  // remove the 'deleted' entry
  unset($row['deleted']);

  // Update the date field with the current timestamp
  $row['date'] = date('Ymd');

  // Replace the record
  dbase_replace_record($db, $row, 1);
  dbase_close($db);
}

?>

Zobacz też:

  • dbase_add_record() - Adds a record to a database
  • dbase_delete_record() - Deletes a record from a database

dbase_pack
filePro
dBase Funkcje


filePro

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • filePro Funkcje
    • filepro_fieldcount — Find out how many fields are in a filePro database
    • filepro_fieldname — Gets the name of a field
    • filepro_fieldtype — Gets the type of a field
    • filepro_fieldwidth — Gets the width of a field
    • filepro_retrieve — Retrieves data from a filePro database
    • filepro_rowcount — Find out how many rows are in a filePro database
    • filepro — Read and verify the map file
dbase_replace_record
Wstęp
Rozszerzenia producentów baz danych


Wstęp

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at » http://www.fptech.com/.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.2.0.

filePro
Instalacja/Konfiguracja
filePro


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
filePro


Instalacja

filePro support in PHP is not enabled by default. To enable the bundled read-only filePro support you need to use the--enable-filepro configuration option when compiling PHP.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
filePro Funkcje
filePro


filePro Funkcje

Spis treści

  • filepro_fieldcount — Find out how many fields are in a filePro database
  • filepro_fieldname — Gets the name of a field
  • filepro_fieldtype — Gets the type of a field
  • filepro_fieldwidth — Gets the width of a field
  • filepro_retrieve — Retrieves data from a filePro database
  • filepro_rowcount — Find out how many rows are in a filePro database
  • filepro — Read and verify the map file
Stałe predefiniowane
filepro_fieldcount
filePro


Find out how many fields are in a filePro database

filePro Funkcje
filepro_fieldname
filePro Funkcje
PHP Manual

filepro_fieldcount

(PHP 4, PHP 5 <= 5.1.6)

filepro_fieldcount — Find out how many fields are in a filePro database

Opis

int filepro_fieldcount ( void )

Returns the number of fields (columns) in the opened filePro database.

Zwracane wartości

Returns the number of fields in the opened filePro database, or FALSE on errors.

Zobacz też:

  • filepro() - Read and verify the map file

filePro Funkcje
filepro_fieldname
filePro Funkcje


Gets the name of a field

filepro_fieldcount
filepro_fieldtype
filePro Funkcje
PHP Manual

filepro_fieldname

(PHP 4, PHP 5 <= 5.1.6)

filepro_fieldname — Gets the name of a field

Opis

string filepro_fieldname ( int $field_number )

Returns the name of the field corresponding to field_number.

Parametry

field_number

The field number.

Zwracane wartości

Returns the name of the field as a string, or FALSE on errors.

filepro_fieldcount
filepro_fieldtype
filePro Funkcje


Gets the type of a field

filepro_fieldname
filepro_fieldwidth
filePro Funkcje
PHP Manual

filepro_fieldtype

(PHP 4, PHP 5 <= 5.1.6)

filepro_fieldtype — Gets the type of a field

Opis

string filepro_fieldtype ( int $field_number )

Returns the edit type of the field corresponding to field_number.

Parametry

field_number

The field number.

Zwracane wartości

Returns the edit type of the field as a string, or FALSE on errors.

filepro_fieldname
filepro_fieldwidth
filePro Funkcje


Gets the width of a field

filepro_fieldtype
filepro_retrieve
filePro Funkcje
PHP Manual

filepro_fieldwidth

(PHP 4, PHP 5 <= 5.1.6)

filepro_fieldwidth — Gets the width of a field

Opis

int filepro_fieldwidth ( int $field_number )

Returns the width of the field corresponding to field_number.

Parametry

field_number

The field number.

Zwracane wartości

Returns the width of the field as a integer, or FALSE on errors.

filepro_fieldtype
filepro_retrieve
filePro Funkcje


Retrieves data from a filePro database

filepro_fieldwidth
filepro_rowcount
filePro Funkcje
PHP Manual

filepro_retrieve

(PHP 4, PHP 5 <= 5.1.6)

filepro_retrieve — Retrieves data from a filePro database

Opis

string filepro_retrieve ( int $row_number , int $field_number )

Returns the data from the specified location in the database.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Parametry

row_number

The row number. Must be between zero and the total number of rows minus one (0..filepro_rowcount() - 1)

field_number

The field number. Accepts values between zero and the total number of fields minus one (0..filepro_fieldcount() - 1)

Zwracane wartości

Returns the specified data, or FALSE on errors.

filepro_fieldwidth
filepro_rowcount
filePro Funkcje


Find out how many rows are in a filePro database

filepro_retrieve
filepro
filePro Funkcje
PHP Manual

filepro_rowcount

(PHP 4, PHP 5 <= 5.1.6)

filepro_rowcount — Find out how many rows are in a filePro database

Opis

int filepro_rowcount ( void )

Returns the number of rows in the opened filePro database.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Zwracane wartości

Returns the number of rows in the opened filePro database, or FALSE on errors.

Zobacz też:

  • filepro() - Read and verify the map file

filepro_retrieve
filepro
filePro Funkcje


Read and verify the map file

filepro_rowcount
Firebird/InterBase
filePro Funkcje
PHP Manual

filepro

(PHP 4, PHP 5 <= 5.1.6)

filepro — Read and verify the map file

Opis

bool filepro ( string $directory )

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Parametry

directory

The map directory.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

filepro_rowcount
Firebird/InterBase
filePro Funkcje


Firebird/InterBase

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje Firebird/InterBase
    • ibase_add_user — Dodaje użytkownika do bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)
    • ibase_affected_rows — Zwraca ilość wierszy przetworzonych przez ostatnie zapytanie
    • ibase_backup — Uruchamia zadanie wykonania kopii zapasowej w Menedżerze Usługi i natychmiast powraca
    • ibase_blob_add — Dodaje dane do nowo utworzonego BLOBa
    • ibase_blob_cancel — Odwołuje tworzenie BLOBa
    • ibase_blob_close — Zamyka BLOBa
    • ibase_blob_create — Tworzy nowego BLOBa w celu umieszczenia w nim danych
    • ibase_blob_echo — Wysyła zawartość BLOBa do przeglądarki
    • ibase_blob_get — Pobiera X bajtów danych z otwartego BLOBa
    • ibase_blob_import — Tworzy BLOBa, kopiuje do niego zawartość pliku i zamyka go.
    • ibase_blob_info — Zwraca długość i inne informacje dotyczące BLOBa
    • ibase_blob_open — Otwiera BLOBa w celu pobrania części danych
    • ibase_close — Zamyka połączenie z serwerem Firebird/InterBase
    • ibase_commit_ret — Potwierdza transakcję bez zamykania jej
    • ibase_commit — Zatwierdza transakcję
    • ibase_connect — Otwiera połączenie do serwera Firebird/InterBase
    • ibase_db_info — Pobiera szczegółowe informacje o bazie danych
    • ibase_delete_user — Usuwa użytkownika z bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)
    • ibase_drop_db — Usuwa bazę danych Firebird/InterBase
    • ibase_errcode — Zwraca kod błędu
    • ibase_errmsg — Zwraca tekst komunikatu błędu
    • ibase_execute — Wykonuje wcześniej przygotowane zapytanie
    • ibase_fetch_assoc — Pobiera wiersz wyniku zapytania w postaci tablicy asocjacyjnej
    • ibase_fetch_object — Pobiera wiersz wyniku zapytania w postaci obiektu
    • ibase_fetch_row — Pobiera wiersz wyniku zapytania w postaci tablicy numerycznej
    • ibase_field_info — Zwraca informację o polu
    • ibase_free_event_handler — Odwołuje funkcję zarejestrowaną do obsługiwania zdarzeń
    • ibase_free_query — Zwalnia pamięć zajmowaną przez przygotowane zapytanie
    • ibase_free_result — Zwalnia pamięć zajmowaną przez wynik
    • ibase_gen_id — Zwiększa generator i zwraca jego nową wartość
    • ibase_maintain_db — Uruchamia polecenie konserwacyjne na serwerze baz danych
    • ibase_modify_user — Modyfikuje użytkownika w bazie danych bezpieczeństwa (tylko dla IB6 i późniejszych)
    • ibase_name_result — Przypisuje nazwę do zbioru wynikowego
    • ibase_num_fields — Zwraca liczbę pól w zbiorze wynikowym
    • ibase_num_params — Zwraca liczbę parametrów w przygotowanym zapytaniu
    • ibase_param_info — Zwraca informację o parametrze w przygotowanym zapytaniu
    • ibase_pconnect — Otwiera stałe połączenie do serwera Firebird/InterBase
    • ibase_prepare — Przygotowuje zapytanie do późniejszego dowiązania parametrów w postaci zmiennych, i do wykonania
    • ibase_query — Wykonuje zapytanie w bazie danych Firebird/Interbase
    • ibase_restore — Uruchamia zadanie przywrócenia bazy danych z kopii zapasowej w Menedżerze Usługi i natychmiast powraca
    • ibase_rollback_ret — Wycofuje transakcję bez zamykania jej
    • ibase_rollback — Wycofuje transakcję
    • ibase_server_info — Pobiera informacje o serwerze baz danych
    • ibase_service_attach — Łączy się do Menedżera Usługi
    • ibase_service_detach — Odłącza się od Menedżera Usługi
    • ibase_set_event_handler — Rejestruje funkcję zwrotną, wywoływaną podczas występowania zadarzeń
    • ibase_timefmt — Ustawia format znacznika czasu, daty i czasu w typach kolum zwracanych przez zapytania
    • ibase_trans — Rozpoczyna transakcję
    • ibase_wait_event — Czeka na zdarzenie, które zostanie przesłane przez serwer
filepro
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Firebird/InterBase jest relacyjną bazą danych oferującą wiele cech ANSI SQL-92, działającą na systemach Linux, Windows i różnorodnych platformach Unixowych. Firebird/InterBase oferuje doskonałą współbieżność, dużą wydajność oraz rozbudowaną obsługę procedur składowanych i wyzwalaczy. Baza jest używana w systemach produkcyjnych, pod różnymi nazwami od 1981 r.

InterBase to nazwa jednego z wariantów tej bazy z zamkniętym kodem źródłowym, rozwijana przez Borland/Inprise. Więcej informacji na temat InterBase jest dostępnych na stronie » http://www.borland.com/interbase/.

Firebird jest komercyjnie niezależnym projektem programistów C i C++, doradców technicznych i zwolenników rozwiajania i ulepszania wieloplatformowego systemu zarządzania bazami danych bazującego na kodzie źródłowym wydanym przez Inprise Corp (znanej jako Borland Software Corp) na licencji InterBase Public License v.1.0 z dnia 25 lipca 2000 r. Więcej informacji na temat Firebird jest dostępnych na witrynie » http://www.firebirdsql.org/.

Informacja:

To rozszerzenie działa z InterBase 5 i późniejszymi wersjami oraz ze wszystkimi wersjami Firebird. Wsparcie techniczne dla InterBase 5.x zostanie zakończone w PHP 5.

Jako znaku unikowego ta baza danych używa pojedyńczego cudzysłowu ('), ( to zachowanie jest podobne do bazy danych Sybase ) i może zostać ustawione w php.ini przez następującą dyrektywę konfiguracyjną:

magic_quotes_sybase = On

Firebird/InterBase
Instalacja/Konfiguracja
Firebird/InterBase


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Firebird/InterBase


Instalacja

W celu uruchomienia wsparcia dla Firebird/InterBase, należy użyć opcji --with-interbase[=DIR] w czasie kompilacji PHP, gdzie DIR jest katalogiem instalacji InterBase - domyślnie /usr/interbase.

Informacja: Informacja dla użytkowników Windows

Aby poprawnie działało rozszerzenie, pliki DLL muszą znajdować się w miejscu wskazanym przez PATH systemu Windows. Aby uzyskać więcej informacji zobacz FAQ zatytułowane "Jak mam dodać mój katalog PHP do PATH w Windows". Chociaż skopiowanie plików DLL z folderu PHP do systemowego katalogu Windows także zadziała (ponieważ katalog systemowy jest domyślnie w PATH systemu), ale nie jest to wymagane. To rozszerzenie wymaga następujących plików znajdujących się w PATH: gds32.dll

Jeśli serwer Firebird/InterBase jest zainstalowany na tej samej naszynie, na której jest uruchomiony PHP, to biblioteka DLL gds32.dll jest dostępna za pomocą zmiennej środowiskowej PATH.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracji Firebird/InterBase
Nazwa | Domyślna wartość | Możliwość zmian | Rejestr zmian
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM | Dostępne od PHP 5.0.0.
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL | Dostępne od PHP 5.0.0.
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | 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.

ibase.allow_persistent boolean

Określa czy pozwolić bazie Firebird/InterBase na połączenia stałe.

ibase.max_persistent integer

Definiuje maksymalną liczbę połączeń stałych Firebird/InterBase na proces serwera. Jeżeli ta liczba zostanie przekroczona to nowe połączenia utworzone za pomocą ibase_pconnect() będą istniały tylko podczas działania skryptu.

ibase.max_links integer

Definiuje maksymalną liczbę połączeń Firebird/InterBase na proces serwera, włączając w to połączenia stałe.

ibase.default_db string

Definiuje domyślną bazę danych dla ibase_[p]connect() i jest używana w przypadku, gdy funkcja zostanie wywołana bez parametru. Jeżeli dodatkowo jest włączony tryb SQL safe mode, nie będą możliwe połączenia do innych baz danych, poza tą domyślną.

ibase.default_user string

Definiuje domyślną nazwę użytkownika, używaną podaczas połączenia do bazy danych, jeżeli nie jest podana jako parametr funkcji.

ibase.default_password string

Definiuje domyślne hasło, używane podaczas połączenia do bazy danych, jeżeli nie jest podane jako parametr funkcji.

ibase.default_charset string

Definiuje domyślne kodowanie znaków, używane podaczas połączenia do bazy danych jeżeli nie jest podane jako parametr funkcji.

ibase.timestampformat string

ibase.dateformat string

ibase.timeformat string

Te dyrektywy ustawiają formatowanie daty i czasu, które jest używane podczas zwracania wartości dat i czasów ze zbioru wynikowego lub podczas dowiązywania argumentów.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

Następujące stałe mogą być przekazane do ibase_trans() w celu określenia zachowania transakcji.

Flagi transakcji Firebird/InterBase
Stała | Opis
IBASE_DEFAULT | Standardowe ustawienia transakcji. Domyślnie są one określone przez bibliotekę klienta, w większości przypadków następująco: IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT .
IBASE_READ | Rozpoczyna transakcję w trybie tylko do odczytu.
IBASE_WRITE | Rozpoczyna transakcję w trybie odczytu i zapisu.
IBASE_CONSISTENCY | Rozpoczyna transakcję na poziomie izolacji ustawionym jako 'spójny', który oznacza że transakcja nie może czytać z tabel będących w trakcie modyfikacji przez równoległe transakcje.
IBASE_CONCURRENCY | Rozpoczyna transakcję na poziomie izolacji ustawionym jako 'współbieżny' (lub 'migawka'), który oznacza że transakcja ma dostęp do wszystkich tabel, ale nie widzi żadnych zmian zatwierdzonych w międzyczasie przez równoległe transakcje.
IBASE_COMMITTED | Rozpoczyna transakcję na poziomie izolacji ustawionym jako 'odczyt zatwierdzony'. Ta flaga powinna być połączona jedną z dwóch: IBASE_REC_VERSION lub IBASE_REC_NO_VERSION. Ten poziom izolacji pozwala uzyskać dostęp do zmian zatwierdzonych w międzyczasie przez inne transakcje. W połączeniu z IBASE_REC_NO_VERSION może być odczytana tylko ostatnia wartość wiersza. W połączeniu z IBASE_REC_VERSION może być zawsze odczytana aktualna wartość wiersza po zmodyfikowaniu jej przez równoległe transakcję.
IBASE_WAIT | Oznacza, że transakcja powinna czekać i ponawiać próbę w momencie wystąpienia konfliktu.
IBASE_NOWAIT | Oznacza, że transakcja powinna natychmiast zwrócić błąd w momencie wystąpienia konfliktu.

Następujące stałe mogą być przekazane do ibase_fetch_row(), ibase_fetch_assoc() lub ibase_fetch_object() w celu określenia zachowania tych funkcji podczas pobierania wierszy.

Flagi pobierania wierszy Firebird/InterBase
Stała | Opis
IBASE_FETCH_BLOBS | Równoważna z IBASE_TEXT w celu zachowania zgodności z poprzednimi wersjami. Powoduje pobranie zawartości BLOBa, zamiast zwrócenia identyfikatora BLOBa.
IBASE_FETCH_ARRAYS | Powoduje pobieranie tablic. W przeciwnym wypadku są zwracane identyfikatory tablic. Identyfikatory tablic mogą być używane tylko jako argumenty dla operacji INSERT, gdyż obecnie nie ma odpowiednich funkcji do ich obsługiwania.
IBASE_UNIXTIME | Powoduje że pola data i czas nie są zwracane w postaci sformatowanych łańcuchów, lecz jako unixowy znacznik czasu (liczba sekund, która upłynęła od początku epoki Uniksa, datowanej na 1 stycznia 1970 0:00 GTM). W niektórych systemach może to stanowić problem, w momencie gdy zostaną użyte daty sprzed 1970 r.

Następujące stałe przekazują żądania i opcje do funkcji usługi API (ibase_server_info(), ibase_db_info(), ibase_backup(), ibase_restore() i ibase_maintain_db()). Prosimy odnieść się do dokumentacji Firebird/InterBase żeby zapoznać się ze znaczeniem tych opcji.

IBASE_BKP_IGNORE_CHECKSUMS
IBASE_BKP_IGNORE_LIMBO
IBASE_BKP_METADATA_ONLY
IBASE_BKP_NO_GARBAGE_COLLECT
IBASE_BKP_OLD_DESCRIPTIONS
IBASE_BKP_NON_TRANSPORTABLE
IBASE_BKP_CONVERT
Opcje dla ibase_backup()
IBASE_RES_DEACTIVATE_IDX
IBASE_RES_NO_SHADOW
IBASE_RES_NO_VALIDITY
IBASE_RES_ONE_AT_A_TIME
IBASE_RES_REPLACE
IBASE_RES_CREATE
IBASE_RES_USE_ALL_SPACE
Opcje dla ibase_restore()
IBASE_PRP_PAGE_BUFFERS
IBASE_PRP_SWEEP_INTERVAL
IBASE_PRP_SHUTDOWN_DB
IBASE_PRP_DENY_NEW_TRANSACTIONS
IBASE_PRP_DENY_NEW_ATTACHMENTS
IBASE_PRP_RESERVE_SPACE
IBASE_PRP_RES_USE_FULL
IBASE_PRP_RES
IBASE_PRP_WRITE_MODE
IBASE_PRP_WM_ASYNC
IBASE_PRP_WM_SYNC
IBASE_PRP_ACCESS_MODE
IBASE_PRP_AM_READONLY
IBASE_PRP_AM_READWRITE
IBASE_PRP_SET_SQL_DIALECT
IBASE_PRP_ACTIVATE
IBASE_PRP_DB_ONLINE
IBASE_RPR_CHECK_DB
IBASE_RPR_IGNORE_CHECKSUM
IBASE_RPR_KILL_SHADOWS
IBASE_RPR_MEND_DB
IBASE_RPR_VALIDATE_DB
IBASE_RPR_FULL
IBASE_RPR_SWEEP_DB
Opcje dla ibase_maintain_db()
IBASE_STS_DATA_PAGES
IBASE_STS_DB_LOG
IBASE_STS_HDR_PAGES
IBASE_STS_IDX_PAGES
IBASE_STS_SYS_RELATIONS
Opcje dla ibase_db_info()
IBASE_SVC_SERVER_VERSION
IBASE_SVC_IMPLEMENTATION
IBASE_SVC_GET_ENV
IBASE_SVC_GET_ENV_LOCK
IBASE_SVC_GET_ENV_MSG
IBASE_SVC_USER_DBPATH
IBASE_SVC_SVR_DB_INFO
IBASE_SVC_GET_USERS
Opcje dla ibase_server_info()

Typy zasobów
Funkcje Firebird/InterBase
Firebird/InterBase


Funkcje Firebird/InterBase

Spis treści

  • ibase_add_user — Dodaje użytkownika do bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)
  • ibase_affected_rows — Zwraca ilość wierszy przetworzonych przez ostatnie zapytanie
  • ibase_backup — Uruchamia zadanie wykonania kopii zapasowej w Menedżerze Usługi i natychmiast powraca
  • ibase_blob_add — Dodaje dane do nowo utworzonego BLOBa
  • ibase_blob_cancel — Odwołuje tworzenie BLOBa
  • ibase_blob_close — Zamyka BLOBa
  • ibase_blob_create — Tworzy nowego BLOBa w celu umieszczenia w nim danych
  • ibase_blob_echo — Wysyła zawartość BLOBa do przeglądarki
  • ibase_blob_get — Pobiera X bajtów danych z otwartego BLOBa
  • ibase_blob_import — Tworzy BLOBa, kopiuje do niego zawartość pliku i zamyka go.
  • ibase_blob_info — Zwraca długość i inne informacje dotyczące BLOBa
  • ibase_blob_open — Otwiera BLOBa w celu pobrania części danych
  • ibase_close — Zamyka połączenie z serwerem Firebird/InterBase
  • ibase_commit_ret — Potwierdza transakcję bez zamykania jej
  • ibase_commit — Zatwierdza transakcję
  • ibase_connect — Otwiera połączenie do serwera Firebird/InterBase
  • ibase_db_info — Pobiera szczegółowe informacje o bazie danych
  • ibase_delete_user — Usuwa użytkownika z bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)
  • ibase_drop_db — Usuwa bazę danych Firebird/InterBase
  • ibase_errcode — Zwraca kod błędu
  • ibase_errmsg — Zwraca tekst komunikatu błędu
  • ibase_execute — Wykonuje wcześniej przygotowane zapytanie
  • ibase_fetch_assoc — Pobiera wiersz wyniku zapytania w postaci tablicy asocjacyjnej
  • ibase_fetch_object — Pobiera wiersz wyniku zapytania w postaci obiektu
  • ibase_fetch_row — Pobiera wiersz wyniku zapytania w postaci tablicy numerycznej
  • ibase_field_info — Zwraca informację o polu
  • ibase_free_event_handler — Odwołuje funkcję zarejestrowaną do obsługiwania zdarzeń
  • ibase_free_query — Zwalnia pamięć zajmowaną przez przygotowane zapytanie
  • ibase_free_result — Zwalnia pamięć zajmowaną przez wynik
  • ibase_gen_id — Zwiększa generator i zwraca jego nową wartość
  • ibase_maintain_db — Uruchamia polecenie konserwacyjne na serwerze baz danych
  • ibase_modify_user — Modyfikuje użytkownika w bazie danych bezpieczeństwa (tylko dla IB6 i późniejszych)
  • ibase_name_result — Przypisuje nazwę do zbioru wynikowego
  • ibase_num_fields — Zwraca liczbę pól w zbiorze wynikowym
  • ibase_num_params — Zwraca liczbę parametrów w przygotowanym zapytaniu
  • ibase_param_info — Zwraca informację o parametrze w przygotowanym zapytaniu
  • ibase_pconnect — Otwiera stałe połączenie do serwera Firebird/InterBase
  • ibase_prepare — Przygotowuje zapytanie do późniejszego dowiązania parametrów w postaci zmiennych, i do wykonania
  • ibase_query — Wykonuje zapytanie w bazie danych Firebird/Interbase
  • ibase_restore — Uruchamia zadanie przywrócenia bazy danych z kopii zapasowej w Menedżerze Usługi i natychmiast powraca
  • ibase_rollback_ret — Wycofuje transakcję bez zamykania jej
  • ibase_rollback — Wycofuje transakcję
  • ibase_server_info — Pobiera informacje o serwerze baz danych
  • ibase_service_attach — Łączy się do Menedżera Usługi
  • ibase_service_detach — Odłącza się od Menedżera Usługi
  • ibase_set_event_handler — Rejestruje funkcję zwrotną, wywoływaną podczas występowania zadarzeń
  • ibase_timefmt — Ustawia format znacznika czasu, daty i czasu w typach kolum zwracanych przez zapytania
  • ibase_trans — Rozpoczyna transakcję
  • ibase_wait_event — Czeka na zdarzenie, które zostanie przesłane przez serwer
Stałe predefiniowane
ibase_add_user
Firebird/InterBase


Dodaje użytkownika do bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)

Funkcje Firebird/InterBase
ibase_affected_rows
Funkcje Firebird/InterBase
PHP Manual

ibase_add_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_add_user — Dodaje użytkownika do bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)

Opis

bool ibase_add_user ( resource $połączenie_do_usługi , string $nazwa_użytkownika , string $hasło [, string $imię [, string $drugie_imię [, string $nazwisko ]]] )

PHP 4 używa parametrów serwer, login_administratora_serwera i hasło_administratora_serwera zamiast połączenie_do_usługi.

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

  • ibase_modify_user() - Modyfikuje użytkownika w bazie danych bezpieczeństwa (tylko dla IB6 i późniejszych)
  • ibase_delete_user() - Usuwa użytkownika z bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)

Funkcje Firebird/InterBase
ibase_affected_rows
Funkcje Firebird/InterBase


Zwraca ilość wierszy przetworzonych przez ostatnie zapytanie

ibase_add_user
ibase_backup
Funkcje Firebird/InterBase
PHP Manual

ibase_affected_rows

(PHP 5)

ibase_affected_rows — Zwraca ilość wierszy przetworzonych przez ostatnie zapytanie

Opis

int ibase_affected_rows ([ resource $identyfikator_połączenia ] )

Ta funkcja zwraca liczbę wierszy przetworzonych przez ostatnie zapytanie (INSERT, UPDATE lub DELETE), które zostało wykonane w kontekście określonej transakcji.

Parametry

identyfikator_połączenia

Kontekst transakcji. Jeśli identyfikator_połączenia jest zasobem połączenia, używana jest jego domyślna transakcja.

Zwracane wartości

Zwraca liczbę wierszy jako integer.

Zobacz też:

  • ibase_query() - Wykonuje zapytanie w bazie danych Firebird/Interbase
  • ibase_execute() - Wykonuje wcześniej przygotowane zapytanie

ibase_add_user
ibase_backup
Funkcje Firebird/InterBase


Uruchamia zadanie wykonania kopii zapasowej w Menedżerze Usługi i natychmiast powraca

ibase_affected_rows
ibase_blob_add
Funkcje Firebird/InterBase
PHP Manual

ibase_backup

(PHP 5)

ibase_backup — Uruchamia zadanie wykonania kopii zapasowej w Menedżerze Usługi i natychmiast powraca

Opis

mixed ibase_backup ( resource $połączenie_do_usługi , string $baza_źródłowa , string $plik_docelowy [, int $opcje = 0 [, bool $szczegółowe_komunikaty = false ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_affected_rows
ibase_blob_add
Funkcje Firebird/InterBase


Dodaje dane do nowo utworzonego BLOBa

ibase_backup
ibase_blob_cancel
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_add

(PHP 4, PHP 5)

ibase_blob_add — Dodaje dane do nowo utworzonego BLOBa

Opis

void ibase_blob_add ( resource $uchwyt_do_bloba , string $dane )

ibase_blob_add() dodaje dane do BLOBa utworzonego za pomocą ibase_blob_create().

Parametry

uchwyt_do_bloba

Uchwyt do BLOBa otwartego przez ibase_blob_create().

dane

Dane do dodania.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ibase_blob_cancel() - Odwołuje tworzenie BLOBa
  • ibase_blob_close() - Zamyka BLOBa
  • ibase_blob_create() - Tworzy nowego BLOBa w celu umieszczenia w nim danych
  • ibase_blob_import() - Tworzy BLOBa, kopiuje do niego zawartość pliku i zamyka go.

ibase_backup
ibase_blob_cancel
Funkcje Firebird/InterBase


Odwołuje tworzenie BLOBa

ibase_blob_add
ibase_blob_close
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_cancel

(PHP 4, PHP 5)

ibase_blob_cancel — Odwołuje tworzenie BLOBa

Opis

bool ibase_blob_cancel ( resource $uchwyt_do_bloba )

Ta funkcja odwołuje BLOBa, jeśli jeszcze nie został zamknięty za pomocą ibase_blob_close().

Parametry

uchwyt_do_bloba

Uchwyt do BLABa otwartego za pomocą ibase_blob_create().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ibase_blob_close() - Zamyka BLOBa
  • ibase_blob_create() - Tworzy nowego BLOBa w celu umieszczenia w nim danych
  • ibase_blob_import() - Tworzy BLOBa, kopiuje do niego zawartość pliku i zamyka go.

ibase_blob_add
ibase_blob_close
Funkcje Firebird/InterBase


Zamyka BLOBa

ibase_blob_cancel
ibase_blob_create
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_close

(PHP 4, PHP 5)

ibase_blob_close — Zamyka BLOBa

Opis

mixed ibase_blob_close ( resource $uchwyt_do_bloba )

Ta funkcja zamyka BLOBa, który wcześniej był otwarty do odczytu za pomocą ibase_blob_open() lub otwarty do zapisu za pomocą ibase_blob_create().

Parametry

uchwyt_do_bloba

Uchwyt do BLOBa otwartego za pomocą ibase_blob_create() lub ibase_blob_open().

Zwracane wartości

Jeśli BLOB był odczytywany, funkcja zwraca TRUE , natomiast jeśli BLOB był zapisywany, funkcja zwraca łańcuch zawierający identyfikator BLOBa przydzielony dla niego przez bazę danych. W przypadku niepowodzenia funkcja zwraca FALSE.

Zobacz też:

  • ibase_blob_cancel() - Odwołuje tworzenie BLOBa
  • ibase_blob_open() - Otwiera BLOBa w celu pobrania części danych

ibase_blob_cancel
ibase_blob_create
Funkcje Firebird/InterBase


Tworzy nowego BLOBa w celu umieszczenia w nim danych

ibase_blob_close
ibase_blob_echo
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_create

(PHP 4, PHP 5)

ibase_blob_create — Tworzy nowego BLOBa w celu umieszczenia w nim danych

Opis

resource ibase_blob_create ([ resource $identyfikator_połączenia = NULL ] )

ibase_blob_create() tworzy nowego BLOBa w celu wypełnienia go danymi.

Parametry

identyfikator_połączenia

Identyfikator połączenia do Firebird/Interbase. Jeśli został pominięty używane jest ostatnio otwarte połączenie.

Zwracane wartości

Zwraca uchwyt do BLOBa, do późniejszego użycia z ibase_blob_add() lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • ibase_blob_add() - Dodaje dane do nowo utworzonego BLOBa
  • ibase_blob_cancel() - Odwołuje tworzenie BLOBa
  • ibase_blob_close() - Zamyka BLOBa
  • ibase_blob_import() - Tworzy BLOBa, kopiuje do niego zawartość pliku i zamyka go.

ibase_blob_close
ibase_blob_echo
Funkcje Firebird/InterBase


Wysyła zawartość BLOBa do przeglądarki

ibase_blob_create
ibase_blob_get
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_echo

(PHP 4, PHP 5)

ibase_blob_echo — Wysyła zawartość BLOBa do przeglądarki

Opis

bool ibase_blob_echo ( string $identyfikator_bloba )
bool ibase_blob_echo ( resource $identyfikator_połączenia , string $identyfikator_bloba )

Ta funkcja otwiera BLOBa do odczytu i wysyła jego zawartość bezpośrednio na standardowe wyjście (najczęściej do przeglądarki internetowej).

Parametry

identyfikator_połączenia

Identyfikator połączenia do Firebird/Interbase. Jeśli został pominięty używane jest ostatnio otwarte połączenie.

identyfikator_bloba

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ibase_blob_open() - Otwiera BLOBa w celu pobrania części danych
  • ibase_blob_close() - Zamyka BLOBa
  • ibase_blob_get() - Pobiera X bajtów danych z otwartego BLOBa

ibase_blob_create
ibase_blob_get
Funkcje Firebird/InterBase


Pobiera X bajtów danych z otwartego BLOBa

ibase_blob_echo
ibase_blob_import
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_get

(PHP 4, PHP 5)

ibase_blob_get — Pobiera X bajtów danych z otwartego BLOBa

Opis

string ibase_blob_get ( resource $uchwyt_do_bloba , int $X )

Ta funkcja zwraca X bajtów danych z BLOBa, który został otwarty do odczytu za pomocą ibase_blob_open().

Informacja:

Nie jest możliwe odczytywanie informacji o BLOBie, który jest otwarty do zapisu za pomocą ibase_blob_create().

Parametry

uchwyt_do_bloba

Uchwyt do BLOBa otwartego za pomocą ibase_blob_open().

X

Rozmiar zwracanych danych.

Zwracane wartości

Zwraca maksymalnie X bajtów z BLOBa, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Przykład ibase_blob_get()

<?php
$wynik           = ibase_query("SELECT wartosc_bloba FROM tabela");
$dane            = ibase_fetch_object($wynik);
$dane_bloba      = ibase_blob_info($dane->WARTOSC_BLOBA);
$uchwyt_do_bloba = ibase_blob_open($dane->WARTOSC_BLOBA);
echo               ibase_blob_get($uchwyt_do_bloba, $dane_bloba[0]);
?>
Podczas gdy ten przykład nie robi niczego więcej, co można uzyskać wywołując 'ibase_blob_echo($dane->WARTOSC_BLOBA)', pokazuje natomiast jak możemy pobierać do $zmiennej informacje aby manipulować nimi tak, jak sobie tego życzymy.

Zobacz też:

  • ibase_blob_open() - Otwiera BLOBa w celu pobrania części danych
  • ibase_blob_close() - Zamyka BLOBa
  • ibase_blob_echo() - Wysyła zawartość BLOBa do przeglądarki

ibase_blob_echo
ibase_blob_import
Funkcje Firebird/InterBase


Tworzy BLOBa, kopiuje do niego zawartość pliku i zamyka go.

ibase_blob_get
ibase_blob_info
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_import

(PHP 4, PHP 5)

ibase_blob_import — Tworzy BLOBa, kopiuje do niego zawartość pliku i zamyka go.

Opis

string ibase_blob_import ( resource $identyfikator_połączenia , resource $uchwyt_do_pliku )
string ibase_blob_import ( resource $uchwyt_do_pliku )

Ta funkcja tworzy BLOBa, wczytuje do niego zawartość wskazanego pliku, zamyka go i zwraca przydzielony identyfikator BLOBa.

Parametry

identyfikator_połączenia

Identyfikator połączenia do Firebird/Interbase. Jeśli został pominięty używane jest ostatnio otwarte połączenie.

uchwyt_do_pliku

Uchwyt do pliku to uchwyt zwrócony przez fopen().

Zwracane wartości

W przypadku powodzenia zwraca identyfikator BLABa, a gdy wystąpi błąd zwraca FALSE.

Przykłady

Przykład #1 Przykład ibase_blob_import()

<?php
$dbh = ibase_connect($host, $username, $password);
$nazwa_pliku = '/tmp/bar';

$fd = fopen($nazwa_pliku, 'r');
if ($fd) {

    $blob = ibase_blob_import($dbh, $fd);
    fclose($fd);

    if (!is_string($blob)) {
        // nie udało się wczytać zawartości pliku do BLOBa
    } else {
        $query = "INSERT INTO foo (name, data) VALUES ('$nazwa_pliku', ?)";
        $prepared = ibase_prepare($dbh, $query);
        if (!ibase_execute($prepared, $blob)) {
            // nie powiodło się wykonanie zapytania
        }
    }
} else {
    // nie udało się otworzyć pliku
}
?>

Zobacz też:

  • ibase_blob_add() - Dodaje dane do nowo utworzonego BLOBa
  • ibase_blob_cancel() - Odwołuje tworzenie BLOBa
  • ibase_blob_close() - Zamyka BLOBa
  • ibase_blob_create() - Tworzy nowego BLOBa w celu umieszczenia w nim danych

ibase_blob_get
ibase_blob_info
Funkcje Firebird/InterBase


Zwraca długość i inne informacje dotyczące BLOBa

ibase_blob_import
ibase_blob_open
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_info

(PHP 4, PHP 5)

ibase_blob_info — Zwraca długość i inne informacje dotyczące BLOBa

Opis

array ibase_blob_info ( resource $identyfikator_połączenia , string $identyfikator_bloba )
array ibase_blob_info ( string $identyfikator_bloba )

Zwraca długość i inne informacje na temat BLOBa.

Parametry

identyfikator_połączenia

Identyfikator połączenia do Firebird/Interbase. Jeśli został pominięty używane jest ostatnio otwarte połączenie.

identyfikator_bloba

Identyfikator BLOBa.

Zwracane wartości

Zwraca tablicę zawierającą informacje o BLOBie. Zwrócona informacja składa się z długości BLOBa, liczby segmentów, wielkości największego segmentu i czy jest to BLOB strumieniowy czy segmentowy.

ibase_blob_import
ibase_blob_open
Funkcje Firebird/InterBase


Otwiera BLOBa w celu pobrania części danych

ibase_blob_info
ibase_close
Funkcje Firebird/InterBase
PHP Manual

ibase_blob_open

(PHP 4, PHP 5)

ibase_blob_open — Otwiera BLOBa w celu pobrania części danych

Opis

resource ibase_blob_open ( resource $identyfikator_połączenia , string $identyfikator_bloba )
resource ibase_blob_open ( string $identyfikator_bloba )

Otwiera istniejącego BLOBa do odczytu.

Parametry

identyfikator_połączenia

Identyfikator połączenia do Firebird/Interbase. Jeśli został pominięty używane jest ostatnio otwarte połączenie.

identyfikator_bloba

Identyfikator BLOBa.

Zwracane wartości

Zwraca uchwyt BLOBa do późniejszego użycia z ibase_blob_get() lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • ibase_blob_close() - Zamyka BLOBa
  • ibase_blob_echo() - Wysyła zawartość BLOBa do przeglądarki
  • ibase_blob_get() - Pobiera X bajtów danych z otwartego BLOBa

ibase_blob_info
ibase_close
Funkcje Firebird/InterBase


Zamyka połączenie z serwerem Firebird/InterBase

ibase_blob_open
ibase_commit_ret
Funkcje Firebird/InterBase
PHP Manual

ibase_close

(PHP 4, PHP 5)

ibase_close — Zamyka połączenie z serwerem Firebird/InterBase

Opis

bool ibase_close ([ resource $identyfikator_połączenia = NULL ] )

Zamyka połączenie z serwerem Firebird/InterBase wiązane za pomocą podanego identyfikator połączenia, zwróconego przez ibase_connect(). Domyślna transakcja jest potwierdzana, pozostałe są wycofywane.

Parametry

identyfikator_połączenia

Identyfikator połączenia z serwerem Firebird/InterBase, zwrócony przez ibase_connect(). Jeśli nie został podany, to używane jest ostatnio otwarte połączenie.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ibase_connect() - Otwiera połączenie do serwera Firebird/InterBase
  • ibase_pconnect() - Otwiera stałe połączenie do serwera Firebird/InterBase

ibase_blob_open
ibase_commit_ret
Funkcje Firebird/InterBase


Potwierdza transakcję bez zamykania jej

ibase_close
ibase_commit
Funkcje Firebird/InterBase
PHP Manual

ibase_commit_ret

(PHP 5)

ibase_commit_ret — Potwierdza transakcję bez zamykania jej

Opis

bool ibase_commit_ret ([ resource $identyfikator_połączenia lub identyfikator_transakcji = NULL ] )

Potwierdza transakcję bez zamykania jej.

Parametry

identyfikator_połączenia lub identyfikator_transakcji

Jeśli jest wywołana bez argumentu, potwierdza domyślną transakcję w domyślnym połączeniu. Jeśli argumentem jest identyfikator_połączenia potwierdza domyślną transakcję we wskazanym połączeniu. Jeśli argumentem jest identyfikator_transakcji potwierdza wskazaną transakcję. Kontekst transakcji powinien zostać zachowany, natomiast wykonane segmenty zapytań w tej transakcji nie mogą zostać wycofane.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ibase_close
ibase_commit
Funkcje Firebird/InterBase


Zatwierdza transakcję

ibase_commit_ret
ibase_connect
Funkcje Firebird/InterBase
PHP Manual

ibase_commit

(PHP 4, PHP 5)

ibase_commit — Zatwierdza transakcję

Opis

bool ibase_commit ([ resource $identyfikator_połączenia_lub_transakcji = NULL ] )

Zatwierdza transakcję.

Parametry

identyfikator_połączenia_lub_transakcji

Jeśli jest wywołana bez argumentu, zatwierdza domyślną transakcję w domyślnym połączeniu. Jeśli argumentem jest identyfikator połączenia zatwierdza domyślną transakcję we wskazanym połączeniu. Jeśli argumentem jest identyfikator transakcji zatwierdza wskazaną transakcję.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ibase_commit_ret
ibase_connect
Funkcje Firebird/InterBase


Otwiera połączenie do serwera Firebird/InterBase

ibase_commit
ibase_db_info
Funkcje Firebird/InterBase
PHP Manual

ibase_connect

(PHP 4, PHP 5)

ibase_connect — Otwiera połączenie do serwera Firebird/InterBase

Opis

resource ibase_connect ([ string $baza_danych [, string $użytkownik [, string $hasło [, string $kodowanie_znaków [, int $bufory [, int $dialekt [, string $rola [, int $synchronizacja ]]]]]]]] )

Nawiązuje połączenie z serwerem Firebird/InterBase.

W przypadku ponownego wywołania funkcji ibase_connect() z takimi samymi argumentami, nie jest otwierane nowe połączenie, jednak w to miejsce powinien zostać zwrócony identyfikator już otwartego połączenia. Połączenie do serwera powinno zostać zamknięte wkrótce po tym, gdy wykonywanie skryptu PHP się zakończy, o ile nie zostanie zamknięte wcześniej przez jawne wywołanie funkcji ibase_close().

Parametry

baza_danych

Parametr baza_danych jest ścieżką do pliku bazy danych (lub aliasem zapisanym w pliku aliases.conf) na serwerze, na którym się ona znajduje. Jeżeli serwer nie jest uruchomiony lokalnie, to ścieżka musi być poprzedzona łańcuchem 'nazwa_hosta:' (TCP/IP), '//nazwa_hosta/' (NetBEUI) lub 'nazwa_hosta@' (IPX/SPX), w zależności od używanego protokołu.

użytkownik

Nazwa użytkownika. Może być ona ustawiona za pomocą dyrektywy konfiguracyjnej PHP ibase.default_user w pliku php.ini.

hasło

Hasło użytkownika. Może być ono ustawione za pomocą dyrektywy konfiguracyjnej PHP ibase.default_password w pliku php.ini.

kodowanie_znaków

Parametr kodowanie_znaków jest domyślnym kodowaniem znaków narodowych w bazie danych.

bufory

Parametr bufory jest liczbą buforów bazy danych jaką ma zaalokować serwer w swojej pamięci podręcznej. Jeżeli jest ustawiony na 0, lub jest pominięty, to serwer użyje wartości domyślnej.

dialekt

Parametr dialekt ustawia domyślny dialekt SQL dla wszystkich instrukcji wykonywanych podczas połączenia. Domyślnie jest on ustawiony na najwyższy obsługiwany przez biblioteki klienta. Jest obsługiwany przez InterBase 6 i nowsze wersje.

rola

Są obsługiwane przez InterBase 5 i nowsze wersje.

synchronizacja

Zwracane wartości

Zwraca identyfikator połączenia do serwera Firebird/InterBase w przypadku powodzenia, lub FALSE w przypadku błędu.

Błędy/Wyjątki

Jeżeli są zwracane błędy takie jak "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (to może się zdarzyć w przypadku użycia niektórych znaków narodowych) po użyciu funkcji ibase_query(), to należy ustawić kodowanie znaków (np. ISO8859_2, WIN1250, UTF8).

Przykłady

Przykład #1 Przykład ibase_connect()

<?php
$host = 'localhost:/sciezka/do/mojej_bazy.fdb';

$dbh = ibase_connect($host, $username, $password, 'ISO8859_2');
$stmt = 'SELECT * FROM NAZWA_TABELI';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    echo $row->NAZWA_KOLUMNY, "\n";
}
ibase_free_result($sth);
ibase_close($dbh);
?>

Zobacz też:

  • ibase_pconnect() - Otwiera stałe połączenie do serwera Firebird/InterBase
  • ibase_close() - Zamyka połączenie z serwerem Firebird/InterBase

ibase_commit
ibase_db_info
Funkcje Firebird/InterBase


Pobiera szczegółowe informacje o bazie danych

ibase_connect
ibase_delete_user
Funkcje Firebird/InterBase
PHP Manual

ibase_db_info

(PHP 5)

ibase_db_info — Pobiera szczegółowe informacje o bazie danych

Opis

string ibase_db_info ( resource $połączenie_do_usługi , string $baza_danych , int $akcja [, int $argument = 0 ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_connect
ibase_delete_user
Funkcje Firebird/InterBase


Usuwa użytkownika z bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)

ibase_db_info
ibase_drop_db
Funkcje Firebird/InterBase
PHP Manual

ibase_delete_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_delete_user — Usuwa użytkownika z bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)

Opis

bool ibase_delete_user ( resource $połączenie_do_usługi , string $nazwa_użytkownika )

PHP 4 używa parametrów server, login_administratora_serwera i hasło_administratora_serwera zamiast service_handle.

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

  • ibase_add_user() - Dodaje użytkownika do bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)
  • ibase_modify_user() - Modyfikuje użytkownika w bazie danych bezpieczeństwa (tylko dla IB6 i późniejszych)

ibase_db_info
ibase_drop_db
Funkcje Firebird/InterBase


Usuwa bazę danych Firebird/InterBase

ibase_delete_user
ibase_errcode
Funkcje Firebird/InterBase
PHP Manual

ibase_drop_db

(PHP 5)

ibase_drop_db — Usuwa bazę danych Firebird/InterBase

Opis

bool ibase_drop_db ([ resource $połączenie = NULL ] )

Ta funkcja usuwa bazę danych otwartą za pomocą ibase_connect() lub ibase_pconnect(). Baza danych jest zamykana i usuwana z serwera.

Parametry

połączenie

Identyfikator połączenia Firebird/Interbase. Jeśli został pominięty używane jest ostatnio otwarte połączenie.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ibase_connect() - Otwiera połączenie do serwera Firebird/InterBase
  • ibase_pconnect() - Otwiera stałe połączenie do serwera Firebird/InterBase

ibase_delete_user
ibase_errcode
Funkcje Firebird/InterBase


Zwraca kod błędu

ibase_drop_db
ibase_errmsg
Funkcje Firebird/InterBase
PHP Manual

ibase_errcode

(PHP 5)

ibase_errcode — Zwraca kod błędu

Opis

int ibase_errcode ( void )

Zwraca kod ostatniego błędu, który powstał w wyniku wywołania funkcji FireBird/Interbase.

Zwracane wartości

Zwraca kod błędu jako integer, lub FALSE w przypadku gdy nie wystąpił żaden błąd.

Zobacz też:

  • ibase_errmsg() - Zwraca tekst komunikatu błędu

ibase_drop_db
ibase_errmsg
Funkcje Firebird/InterBase


Zwraca tekst komunikatu błędu

ibase_errcode
ibase_execute
Funkcje Firebird/InterBase
PHP Manual

ibase_errmsg

(PHP 4, PHP 5)

ibase_errmsg — Zwraca tekst komunikatu błędu

Opis

string ibase_errmsg ( void )

Zwraca tekst komunikatu błędu, który powstał w wyniku wywołania funkcji FireBird/Interbase.

Zwracane wartości

Zwraca tekst komunikatu błędu jako łańcuch, lub FALSE w przypadku gdy nie wystąpił żaden błąd.

Zobacz też:

  • ibase_errcode() - Zwraca kod błędu

ibase_errcode
ibase_execute
Funkcje Firebird/InterBase


Wykonuje wcześniej przygotowane zapytanie

ibase_errmsg
ibase_fetch_assoc
Funkcje Firebird/InterBase
PHP Manual

ibase_execute

(PHP 4, PHP 5)

ibase_execute — Wykonuje wcześniej przygotowane zapytanie

Opis

resource ibase_execute ( resource $zapytanie [, mixed $dowiązywany_argument_1 [, mixed $... ]] )

Wykonuje zapytanie przygotowane za pomocą ibase_prepare().

Funkcja jest o wiele bardziej efektywna niż ibase_query(), jeżeli wiele razy jest powtarzany taki sam rodzaj zapytania i zmieniane są tylko wartości niektórych parametrów.

Parametry

zapytanie

Zapytanie SQL przygotowane za pomocą ibase_prepare().

dowiązywany_argument_1

...

Zwracane wartości

Jeśli zapytanie powoduje błąd, zwraca FALSE. Jeśli zapytanie zostanie pomyślnie wykonane a jego rezultatem będzie (być może pusty) zbiór wynikowy (uzyskany za pomocą SELECT), zwraca identyfikator_wyniku. Jeśli zapytanie zostanie pomyślnie wykonane a nie powstanie zbiór wynikowy, zwraca TRUE.

Informacja:

W PHP 5.0.0 i nowszych wersjach ta funkcja zwraca liczbę wierszy przetworzonych przez ostatnie zapytanie (jeżeli jest > 0 i użyto odpowiedniej instrukcji SQL). W przypadku zapytania wykonanego prawidłowo, ale nie przetwarzającego żadnego wiersza (np. UPDATE z warunkiem nie pasującym do żadnego rekordu) funkcja zwraca TRUE.

Przykłady

Przykład #1 Przykład ibase_execute()

<?php

$dbh = ibase_connect($host, $username, $password, 'ISO8859_2');

$aktualizacje = array(
    1 => 'Gościsława',
    5 => 'Drogomysł',
    7 => 'Sjęgniewa'
);

$sql = ibase_prepare($dbh, "UPDATE NAZWA_TABELI SET IMIE = ? WHERE ID = ?");

foreach ($aktualizacje as $id => $imie) {
    ibase_execute($sql, $imie, $id);
}

?>

Zobacz też:

  • ibase_query() - Wykonuje zapytanie w bazie danych Firebird/Interbase

ibase_errmsg
ibase_fetch_assoc
Funkcje Firebird/InterBase


Pobiera wiersz wyniku zapytania w postaci tablicy asocjacyjnej

ibase_execute
ibase_fetch_object
Funkcje Firebird/InterBase
PHP Manual

ibase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

ibase_fetch_assoc — Pobiera wiersz wyniku zapytania w postaci tablicy asocjacyjnej

Opis

array ibase_fetch_assoc ( resource $identyfikator_wyniku [, int $znacznik_pobrania = 0 ] )

Pobiera wiersz wyniku zapytania w postaci tablicy asocjacyjnej.

ibase_fetch_assoc() pobiera jeden wiersz zawierający dane z identyfikatora_wyniku. Jeśli takie same nazwy pól mają dwie lub więcej kolumn, wówczas zostaną zapisane wartości z ostatnich kolumn. Aby uzyskać dostęp do wartości różnych kolumn o tych samych nazwach, powinniśmy pobrać wynik do tablicy z indeksami numerycznymi używając ibase_fetch_row() , albo stosowac aliasy nazw w naszych zapytaniach.

Parametry

identyfikator_wyniku

Identyfikator wyniku Firebird/Interbase.

znacznik_pobrania

znacznik_pobrania jest kombinacją stałych IBASE_TEXT i IBASE_UNIXTIME łączonych ze sobą przy pomocy operatora sumy bitowej. Przekazanie stałej IBASE_TEXT powoduje, że ta funkcja zwraca zawartość BLOBa zamiast identyfikatora BLOBa. Przekazanie stałej IBASE_UNIXTIME powoduje, że ta funkcja zwraca wartości daty/czasu w postaci unixowego znacznika czasu, zamiast sformatowanego łańcucha.

Zwracane wartości

Zwraca tablicę asocjacyjną, która jest odpowiednikiem pobranego wiersza. Kolejne wywołanie zwróci następny wiersz ze zbioru wynikowego, lub FALSE jeśli nie ma już więcej wierszy.

Zobacz też:

  • ibase_fetch_row() - Pobiera wiersz wyniku zapytania w postaci tablicy numerycznej
  • ibase_fetch_object() - Pobiera wiersz wyniku zapytania w postaci obiektu

ibase_execute
ibase_fetch_object
Funkcje Firebird/InterBase


Pobiera wiersz wyniku zapytania w postaci obiektu

ibase_fetch_assoc
ibase_fetch_row
Funkcje Firebird/InterBase
PHP Manual

ibase_fetch_object

(PHP 4, PHP 5)

ibase_fetch_object — Pobiera wiersz wyniku zapytania w postaci obiektu

Opis

object ibase_fetch_object ( resource $identyfikator_wyniku [, int $znacznik_pobrania = 0 ] )

Pobiera wiesz jako pseudo-obiekt z podanego zbioru wynikowego.

Kolejne wywołanie ibase_fetch_object() zwróci następny wiersz ze zbioru wynikowego.

Parametry

identyfikator_wyniku

Identyfikator wyniku Firebird/InterBase uzyskanego wcześniej przez wywołanie ibase_query() lub ibase_execute().

znacznik_pobrania

znacznik_pobrania jest kombinacją stałych IBASE_TEXT i IBASE_UNIXTIME łączonych ze sobą przy pomocy operatora sumy bitowej. Przekazanie stałej IBASE_TEXT powoduje, że ta funkcja zwraca zawartość BLOBa zamiast identyfikatora BLOBa. Przekazanie stałej IBASE_UNIXTIME powoduje, że ta funkcja zwraca wartości daty/czasu w postaci unixowego znacznika czasu, zamiast sformatowanego łańcucha.

Zwracane wartości

Zwraca obiekt zawierający dane kolejnego wiersza, lub FALSE jeśli nie ma już więcej wierszy.

Przykłady

Przykład #1 Przykład ibase_fetch_object()

<?php
$dbh = ibase_connect($host, $uzytkownik, $haslo);
$stmt = 'SELECT * FROM tabela';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    echo $row->EMAIL . "\n";
}
ibase_close($dbh);
?>

Zobacz też:

  • ibase_fetch_row() - Pobiera wiersz wyniku zapytania w postaci tablicy numerycznej
  • ibase_fetch_assoc() - Pobiera wiersz wyniku zapytania w postaci tablicy asocjacyjnej

ibase_fetch_assoc
ibase_fetch_row
Funkcje Firebird/InterBase


Pobiera wiersz wyniku zapytania w postaci tablicy numerycznej

ibase_fetch_object
ibase_field_info
Funkcje Firebird/InterBase
PHP Manual

ibase_fetch_row

(PHP 4, PHP 5)

ibase_fetch_row — Pobiera wiersz wyniku zapytania w postaci tablicy numerycznej

Opis

array ibase_fetch_row ( resource $identyfikator_wyniku [, int $znacznik_pobrania = 0 ] )

ibase_fetch_row() pobiera jeden wiersz zawierający dane z podanego zbioru wynikowego.

Kolejne wywołanie ibase_fetch_row() zwróci następny wiersz ze zbioru wynikowego, lub FALSE jeśli nie ma już więcej wierszy.

Parametry

identyfikator_wyniku

Identyfikator wyniku Firebird/Interbase.

znacznik_pobrania

znacznik_pobrania jest kombinacją stałych IBASE_TEXT i IBASE_UNIXTIME łączonych ze sobą przy pomocy operatora sumy bitowej. Przekazanie stałej IBASE_TEXT powoduje, że ta funkcja zwraca zawartość BLOBa zamiast identyfikatora BLOBa. Przekazanie stałej IBASE_UNIXTIME powoduje, że ta funkcja zwraca wartości daty/czasu w postaci unixowego znacznika czasu, zamiast sformatowanego łańcucha.

Zwracane wartości

Zwraca tablicę numeryczną odpowiadającą pobranemu wierszowi, lub FALSE jeśli nie ma już więcej wierszy. Wartości kolumn są umieszczane na kolejnych pozycjach tablicy, zaczynając od 0.

Zobacz też:

  • ibase_fetch_assoc() - Pobiera wiersz wyniku zapytania w postaci tablicy asocjacyjnej
  • ibase_fetch_object() - Pobiera wiersz wyniku zapytania w postaci obiektu

ibase_fetch_object
ibase_field_info
Funkcje Firebird/InterBase


Zwraca informację o polu

ibase_fetch_row
ibase_free_event_handler
Funkcje Firebird/InterBase
PHP Manual

ibase_field_info

(PHP 4, PHP 5)

ibase_field_info — Zwraca informację o polu

Opis

array ibase_field_info ( resource $wynik , int $numer_pola )

Zwraca tablicę zawierającą informacje o polu, po wykonaniu zapytania SELECT.

Parametry

wynik

Identyfikator wyniku.

numer_pola

Numer pola.

Zwracane wartości

Zwraca tablicę z następującymi kluczami: name, alias, relation, length, type - odpowiednio: nazwa, alias, relacja, długość i typ.

Przykłady

Przykład #1 Przykład ibase_field_info()

<?php
$rs = ibase_query("SELECT * FROM tabela");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "nazwa: ". $col_info['name']. "\n";
    echo "alias: ". $col_info['alias']. "\n";
    echo "relacja: ". $col_info['relation']. "\n";
    echo "długość: ". $col_info['length']. "\n";
    echo "typ: ". $col_info['type']. "\n";
}
?>

Zobacz też:

  • ibase_num_fields() - Zwraca liczbę pól w zbiorze wynikowym

ibase_fetch_row
ibase_free_event_handler
Funkcje Firebird/InterBase


Odwołuje funkcję zarejestrowaną do obsługiwania zdarzeń

ibase_field_info
ibase_free_query
Funkcje Firebird/InterBase
PHP Manual

ibase_free_event_handler

(PHP 5)

ibase_free_event_handler — Odwołuje funkcję zarejestrowaną do obsługiwania zdarzeń

Opis

bool ibase_free_event_handler ( resource $uchwyt_zdarzeń )

Ta funkcja powoduje, że zarejestrowana obsługa zdarzeń określona przez uchwyt_zdarzeń zostanie odwołana. Funkcja zwrotna nie będzie już wywoływana w przypadku przesyłania zdarzeń przez serwer.

Parametry

uchwyt_zdarzeń

Identyfikator zasobu do obsługiwania zdarzeń, utworzony przez ibase_set_event_handler().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ibase_set_event_handler() - Rejestruje funkcję zwrotną, wywoływaną podczas występowania zadarzeń

ibase_field_info
ibase_free_query
Funkcje Firebird/InterBase


Zwalnia pamięć zajmowaną przez przygotowane zapytanie

ibase_free_event_handler
ibase_free_result
Funkcje Firebird/InterBase
PHP Manual

ibase_free_query

(PHP 4, PHP 5)

ibase_free_query — Zwalnia pamięć zajmowaną przez przygotowane zapytanie

Opis

bool ibase_free_query ( resource $zapytanie )

Zwalnia pamięć zajmowaną przez przygotowane zapytanie.

Parametry

zapytanie

Zapytanie przygotowane za pomocą ibase_prepare().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ibase_free_event_handler
ibase_free_result
Funkcje Firebird/InterBase


Zwalnia pamięć zajmowaną przez wynik

ibase_free_query
ibase_gen_id
Funkcje Firebird/InterBase
PHP Manual

ibase_free_result

(PHP 4, PHP 5)

ibase_free_result — Zwalnia pamięć zajmowaną przez wynik

Opis

bool ibase_free_result ( resource $identyfikator_wyniku )

Zwalnia pamięć zajmowaną przez wynik.

Parametry

identyfikator_wyniku

Zwalnia pamięć zajmowaną przez wynik, przydzieloną w wyniku użycia ibase_query() lub ibase_execute().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ibase_free_query
ibase_gen_id
Funkcje Firebird/InterBase


Zwiększa generator i zwraca jego nową wartość

ibase_free_result
ibase_maintain_db
Funkcje Firebird/InterBase
PHP Manual

ibase_gen_id

(PHP 5)

ibase_gen_id — Zwiększa generator i zwraca jego nową wartość

Opis

mixed ibase_gen_id ( string $generator [, int $przyrost = 1 [, resource $identyfikator_połączenia = NULL ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Zwraca nową wartość generatora jako integer, lub jako string, w przypadku gdy przekroczy ona jego zakres.

ibase_free_result
ibase_maintain_db
Funkcje Firebird/InterBase


Uruchamia polecenie konserwacyjne na serwerze baz danych

ibase_gen_id
ibase_modify_user
Funkcje Firebird/InterBase
PHP Manual

ibase_maintain_db

(PHP 5)

ibase_maintain_db — Uruchamia polecenie konserwacyjne na serwerze baz danych

Opis

bool ibase_maintain_db ( resource $połączenie_do_usługi , string $baza_danych , int $akcja [, int $argument = 0 ] )
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.

ibase_gen_id
ibase_modify_user
Funkcje Firebird/InterBase


Modyfikuje użytkownika w bazie danych bezpieczeństwa (tylko dla IB6 i późniejszych)

ibase_maintain_db
ibase_name_result
Funkcje Firebird/InterBase
PHP Manual

ibase_modify_user

(PHP 4 >= 4.2.0, PHP 5)

ibase_modify_user — Modyfikuje użytkownika w bazie danych bezpieczeństwa (tylko dla IB6 i późniejszych)

Opis

bool ibase_modify_user ( resource $połączenie_do_usługi , string $nazwa_użytkownika , string $hasło [, string $imię [, string $drugie_imię [, string $nazwisko ]]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

PHP 4 używa parametrów serwer, login_administratora_serwera i hasło_administratora_serwera zamiast połączenie_do_usługi.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ibase_add_user() - Dodaje użytkownika do bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)
  • ibase_delete_user() - Usuwa użytkownika z bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)

ibase_maintain_db
ibase_name_result
Funkcje Firebird/InterBase


Przypisuje nazwę do zbioru wynikowego

ibase_modify_user
ibase_num_fields
Funkcje Firebird/InterBase
PHP Manual

ibase_name_result

(PHP 5)

ibase_name_result — Przypisuje nazwę do zbioru wynikowego

Opis

bool ibase_name_result ( resource $wynik , string $nazwa )

Ta funkcja przypisuje nazwę do wyniku. Nazwa może być później używana w segmentach: UPDATE|DELETE ... WHERE CURRENT OF nazwa.

Parametry

wynik

Wynik zapytania Firebird/InterBase.

nazwa

Nazwa do przypisania.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład ibase_name_result()

<?php
$result = ibase_query("SELECT pole1,pole2 FROM tabela FOR UPDATE");
ibase_name_result($result, "moj_kursor");

$updateqry = ibase_prepare("UPDATE tabela SET pole2 = ? WHERE CURRENT OF moj_kursor");

for ($i = 0; ibase_fetch_row($result); ++$i) {
    ibase_execute($updateqry, $i);
}
?>

Zobacz też:

  • ibase_prepare() - Przygotowuje zapytanie do późniejszego dowiązania parametrów w postaci zmiennych, i do wykonania
  • ibase_execute() - Wykonuje wcześniej przygotowane zapytanie

ibase_modify_user
ibase_num_fields
Funkcje Firebird/InterBase


Zwraca liczbę pól w zbiorze wynikowym

ibase_name_result
ibase_num_params
Funkcje Firebird/InterBase
PHP Manual

ibase_num_fields

(PHP 4, PHP 5)

ibase_num_fields — Zwraca liczbę pól w zbiorze wynikowym

Opis

int ibase_num_fields ( resource $id_wyniku )

Zwraca liczbę pól w zbiorze wynikowym.

Parametry

id_wyniku

Identyfikator zbioru wynikowego Firebird/Interbase.

Zwracane wartości

Zwraca liczbę pól jako integer.

Przykłady

Przykład #1 Przykład ibase_num_fields()

<?php
$rs = ibase_query("SELECT * FROM tabela");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i);
    echo "nazwa: " . $col_info['name'] . "\n";
    echo "alias: " . $col_info['alias'] . "\n";
    echo "relacja: " . $col_info['relation'] . "\n";
    echo "długość: " . $col_info['length'] . "\n";
    echo "typ: " . $col_info['type'] . "\n";
}
?>

Zobacz też:

  • ibase_field_info() - Zwraca informację o polu

ibase_name_result
ibase_num_params
Funkcje Firebird/InterBase


Zwraca liczbę parametrów w przygotowanym zapytaniu

ibase_num_fields
ibase_param_info
Funkcje Firebird/InterBase
PHP Manual

ibase_num_params

(PHP 5)

ibase_num_params — Zwraca liczbę parametrów w przygotowanym zapytaniu

Opis

int ibase_num_params ( resource $przygotowane_zapytanie )

Ta funkcja zwraca liczbę parametrów w przygotowanym zapytaniu, określonym przez przygotowane_zapytanie. Wynikiem jest liczba argumentów, które muszą zostać dowiązane podczas wywoływania ibase_execute().

Parametry

przygotowane_zapytanie

Uchwyt do przygotowanego zapytania.

Zwracane wartości

Zwraca liczbę parametrów jako integer.

Zobacz też:

  • ibase_prepare() - Przygotowuje zapytanie do późniejszego dowiązania parametrów w postaci zmiennych, i do wykonania
  • ibase_param_info() - Zwraca informację o parametrze w przygotowanym zapytaniu

ibase_num_fields
ibase_param_info
Funkcje Firebird/InterBase


Zwraca informację o parametrze w przygotowanym zapytaniu

ibase_num_params
ibase_pconnect
Funkcje Firebird/InterBase
PHP Manual

ibase_param_info

(PHP 5)

ibase_param_info — Zwraca informację o parametrze w przygotowanym zapytaniu

Opis

array ibase_param_info ( resource $przygotowane_zapytanie , int $numer_parametru )

Zwraca tablicę z informacją o parametrze we wcześniej przygotowanym zapytaniu.

Parametry

przygotowane_zapytanie

Uchwyt do przygotowanego zapytania Firebird/Interbase.

numer_parametru

Pozycja parametru.

Zwracane wartości

Zwraca tablicę zawierającą następujące klucze: name, alias, relation, length i type, odpowiednio - nazwę, alias, relację, długość i typ.

Zobacz też:

  • ibase_field_info() - Zwraca informację o polu
  • ibase_num_params() - Zwraca liczbę parametrów w przygotowanym zapytaniu

ibase_num_params
ibase_pconnect
Funkcje Firebird/InterBase


Otwiera stałe połączenie do serwera Firebird/InterBase

ibase_param_info
ibase_prepare
Funkcje Firebird/InterBase
PHP Manual

ibase_pconnect

(PHP 4, PHP 5)

ibase_pconnect — Otwiera stałe połączenie do serwera Firebird/InterBase

Opis

resource ibase_pconnect ([ string $baza_danych [, string $użytkownik [, string $hasło [, string $kodowanie_znaków [, int $bufory [, int $dialekt [, string $rola [, int $synchronizacja ]]]]]]]] )

Nawiązuje stałe połączenie z serwerem Firebird/InterBase.

ibase_pconnect() zachowuje się prawie jak ibase_connect(), z dwoma zasadniczymi różnicami.

Pierwsza - podczas łączenia funkcja najpierw spróbuje znaleźć połączenie (stałe), już otwarte z takimi samymi argumentami (host, użytkownik, hasło, ...) Jeżeli je znajdzie, to zostanie zwrócony jego identyfikator, zamiast otwierania nowego połączenia.

Druga - połączenie z serwerem Firebird/Interbase nie zostanie zamknięte po zakończeniu wykonywania skryptu. Zamiast tego połączenie pozostanie otwarte do późniejszego użycia (ibase_close() nie zamyka połączeń nawiązanych za pomocą ibase_pconnect()). Dlatego też ten typ połączeń nazywany jest 'stałym'.

Parametry

baza_danych

Parametr baza_danych jest ścieżką do pliku bazy danych (lub aliasem zapisanym w pliku aliases.conf) na serwerze, na którym się ona znajduje. Jeżeli serwer nie jest uruchomiony lokalnie, to ścieżka musi być poprzedzona łańcuchem 'nazwa_hosta:' (TCP/IP), '//nazwa_hosta/' (NetBEUI) lub 'nazwa_hosta@' (IPX/SPX), w zależności od używanego protokołu.

użytkownik

Nazwa użytkownika. Może być ona ustawiona za pomocą dyrektywy konfiguracyjnej PHP ibase.default_user w pliku php.ini.

hasło

Hasło użytkownika. Może być ono ustawione za pomocą dyrektywy konfiguracyjnej PHP ibase.default_password w pliku php.ini.

kodowanie_znaków

Parametr kodowanie_znaków jest domyślnym kodowaniem znaków narodowych w bazie danych.

bufory

Parametr bufory jest liczbą buforów bazy danych jaką ma zaalokować serwer w swojej pamięci podręcznej. Jeżeli jest ustawiony na 0, lub jest pominięty, to serwer użyje wartości domyślnej.

dialekt

Parametr dialekt ustawia domyślny dialekt SQL dla wszystkich instrukcji wykonywanych podczas połączenia. Domyślnie jest on ustawiony na najwyższy obsługiwany przez biblioteki klienta. Jest obsługiwany przez InterBase 6 i nowsze wersje.

rola

Są obsługiwane przez InterBase 5 i nowsze wersje.

synchronizacja

Zwracane wartości

Zwraca identyfikator połączenia do serwera Firebird/InterBase w przypadku powodzenia, lub FALSE w przypadku błędu.

Zobacz też:

  • ibase_close() - Zamyka połączenie z serwerem Firebird/InterBase
  • ibase_connect() - Otwiera połączenie do serwera Firebird/InterBase

ibase_param_info
ibase_prepare
Funkcje Firebird/InterBase


Przygotowuje zapytanie do późniejszego dowiązania parametrów w postaci zmiennych, i do wykonania

ibase_pconnect
ibase_query
Funkcje Firebird/InterBase
PHP Manual

ibase_prepare

(PHP 4, PHP 5)

ibase_prepare — Przygotowuje zapytanie do późniejszego dowiązania parametrów w postaci zmiennych, i do wykonania

Opis

resource ibase_prepare ( string $zapytanie )
resource ibase_prepare ( resource $identyfikator_połączenia , string $zapytanie )
resource ibase_prepare ( resource $identyfikator_połączenia , string $transakcja , string $zapytanie )

Przygotowuje zapytanie do późniejszego dowiązania parametrów w postaci zmiennych, i do wykonania (za pomocą ibase_execute()).

Parametry

zapytanie

Zapytanie SQL.

Zwracane wartości

Zwraca identyfikator przygotowanego zapytania, lub FALSE w przypadku błędu.

ibase_pconnect
ibase_query
Funkcje Firebird/InterBase


Wykonuje zapytanie w bazie danych Firebird/Interbase

ibase_prepare
ibase_restore
Funkcje Firebird/InterBase
PHP Manual

ibase_query

(PHP 4, PHP 5)

ibase_query — Wykonuje zapytanie w bazie danych Firebird/Interbase

Opis

resource ibase_query ([ resource $identyfikator_połączenia ], string $zapytanie [, int $dowiązywany_argument_1 ] )

Wykonuje zapytanie w bazie danych Firebird/Interbase.

Parametry

identyfikator_połączenia

Identyfikator połączenia do Firebird/Interbase. Jeżeli zostanie pominięty, to użyte będzie istniejące połączenie.

zapytanie

Zapytanie SQL.

dowiązywany_argument_1

Zwracane wartości

Jeśli zapytanie powoduje błąd, funkcja zwraca FALSE. Jeśli zapytanie zostanie pomyślnie wykonane a jego rezultatem będzie (być może pusty) zbiór wynikowy (uzyskany za pomocą SELECT), zwraca identyfikator_wyniku. Jeśli zapytanie zostanie pomyślnie wykonane, a nie powstanie zbiór wynikowy, zwraca TRUE.

Informacja:

W PHP 5.0.0 i nowszych wersjach ta funkcja zwraca liczbę wierszy przetworzonych przez ostatnie zapytanie (instrukcje INSERT, UPDATE lub DELETE). W celu zachowania zgodności z poprzednimi wersjami funkcja zwraca TRUE dla prawidłowo wykonanych zapytań, w których nie były przetwarzane wiersze.

Błędy/Wyjątki

Jeżeli są zwracane błędy takie jak "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (to może się zdarzyć w przypadku użycia niektórych znaków narodowych) po użyciu funkcji ibase_query(), to należy ustawić kodowanie znaków (np. ISO8859_2, WIN1250, UTF8).

Rejestr zmian

Wersja | Opis
5.3.1 | W przypadku powodzenia funkcja zwraca obecnie TRUE jeśli nie były przetworzone żadne wiersze. W poprzednich wersjach PHP funkcja zwracała 0 (zero i spację).

Przykłady

Przykład #1 Przykład ibase_query()

<?php

$host = 'localhost:alias_bazy_danych';

$dbh = ibase_connect($host, $username, $password, 'ISO8859_2');
$stmt = 'SELECT * FROM NAZWA_TABELI';

$sth = ibase_query($dbh, $stmt) or die(ibase_errmsg());

?>

Zobacz też:

  • ibase_errmsg() - Zwraca tekst komunikatu błędu
  • ibase_fetch_row() - Pobiera wiersz wyniku zapytania w postaci tablicy numerycznej
  • ibase_fetch_object() - Pobiera wiersz wyniku zapytania w postaci obiektu
  • ibase_free_result() - Zwalnia pamięć zajmowaną przez wynik

ibase_prepare
ibase_restore
Funkcje Firebird/InterBase


Uruchamia zadanie przywrócenia bazy danych z kopii zapasowej w Menedżerze Usługi i natychmiast powraca

ibase_query
ibase_rollback_ret
Funkcje Firebird/InterBase
PHP Manual

ibase_restore

(PHP 5)

ibase_restore — Uruchamia zadanie przywrócenia bazy danych z kopii zapasowej w Menedżerze Usługi i natychmiast powraca

Opis

mixed ibase_restore ( resource $połączenie_do_usługi , string $plik_źródłowy , string $baza_docelowa [, int $opcje = 0 [, bool $szczegółowe_komunikaty = false ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_query
ibase_rollback_ret
Funkcje Firebird/InterBase


Wycofuje transakcję bez zamykania jej

ibase_restore
ibase_rollback
Funkcje Firebird/InterBase
PHP Manual

ibase_rollback_ret

(PHP 5)

ibase_rollback_ret — Wycofuje transakcję bez zamykania jej

Opis

bool ibase_rollback_ret ([ resource $identyfikator_połączenia lub identyfikator_transakcji = NULL ] )

Wycofuje transakcję bez zamykania jej.

Parametry

identyfikator_połączenia lub identyfikator_transakcji

Jeśli jest wywołana bez argumentu, wycofuje domyślną transakcję w domyślnym połączeniu. Jeśli argumentem jest identyfikator_połączenia wycofuje domyślną transakcję we wskazanym połączeniu. Jeśli argumentem jest identyfikator_transakcji wycofuje wskazaną transakcję. Kontekst transakcji powinien zostać zachowany, natomiast wycofane segmenty zapytań w tej transakcji nie mogą zostać potwierdzone.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ibase_restore
ibase_rollback
Funkcje Firebird/InterBase


Wycofuje transakcję

ibase_rollback_ret
ibase_server_info
Funkcje Firebird/InterBase
PHP Manual

ibase_rollback

(PHP 4, PHP 5)

ibase_rollback — Wycofuje transakcję

Opis

bool ibase_rollback ([ resource $identyfikator_połączenia_lub_transakcji = NULL ] )

Wycofuje transakcję.

Parametry

identyfikator_połączenia_lub_transakcji

Jeśli jest wywołana bez argumentu, wycofuje domyślną transakcję w domyślnym połączeniu. Jeśli argumentem jest identyfikator połączenia wycofuje domyślną transakcję we wskazanym połączeniu. Jeśli argumentem jest identyfikator transakcji wycofuje wskazaną transakcję.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ibase_rollback_ret
ibase_server_info
Funkcje Firebird/InterBase


Pobiera informacje o serwerze baz danych

ibase_rollback
ibase_service_attach
Funkcje Firebird/InterBase
PHP Manual

ibase_server_info

(PHP 5)

ibase_server_info — Pobiera informacje o serwerze baz danych

Opis

string ibase_server_info ( resource $połączenie_do_usługi , int $akcja )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_rollback
ibase_service_attach
Funkcje Firebird/InterBase


Łączy się do Menedżera Usługi

ibase_server_info
ibase_service_detach
Funkcje Firebird/InterBase
PHP Manual

ibase_service_attach

(PHP 5)

ibase_service_attach — Łączy się do Menedżera Usługi

Opis

resource ibase_service_attach ( string $host , string $login_administratora_serwera , string $hasło_administratora_serwera )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ibase_server_info
ibase_service_detach
Funkcje Firebird/InterBase


Odłącza się od Menedżera Usługi

ibase_service_attach
ibase_set_event_handler
Funkcje Firebird/InterBase
PHP Manual

ibase_service_detach

(PHP 5)

ibase_service_detach — Odłącza się od Menedżera Usługi

Opis

bool ibase_service_detach ( resource $połączenie_do_usługi )
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.

ibase_service_attach
ibase_set_event_handler
Funkcje Firebird/InterBase


Rejestruje funkcję zwrotną, wywoływaną podczas występowania zadarzeń

ibase_service_detach
ibase_timefmt
Funkcje Firebird/InterBase
PHP Manual

ibase_set_event_handler

(PHP 5)

ibase_set_event_handler — Rejestruje funkcję zwrotną, wywoływaną podczas występowania zadarzeń

Opis

resource ibase_set_event_handler ( callback $nazwa_funkcji_zwrotnej , string $nazwa_zdarzenia1 [, string $nazwa_zdarzenia2 [, string $... ]] )
resource ibase_set_event_handler ( resource $identyfikator_połączenia , callback $nazwa_funkcji_zwrotnej , string $nazwa_zdarzenia1 [, string $nazwa_zdarzenia2 [, string $... ]] )

Ta funkcja rejestruje funkcję użytkownika PHP do obsługiwania zdarzeń przesyłanych przez bazę danych.

Parametry

nazwa_funkcji_zwrotnej

Funkcja zwrotna jest wywoływana z argumentami nazwa_zdarzenia i identyfikator_połączenia, gdy tylko baza danych prześle informację o wystąpieniu jednego z określonych zdarzeń.

Aby obsługa zdarzenia została wyrejestrowana, funkcja zwrotna musi zwrócić FALSE. Każda inna zwracana wartość jest ignorowana. Funkcja akceptuje maksymalnie 15 argumentów nazwa_zdarzenia.

nazwa_zdarzenia1

Nazwa zdarzenia.

nazwa_zdarzenia2

Można przekazać maksymalnie 15 zdarzeń.

Zwracane wartości

Zwracana wartość jest identyfikatorem zasobu do obsługiwania zdarzeń. Identyfikator może być użyty do odwołania funkcji obsługiwania zdarzeń za pomocą ibase_free_event_handler().

Przykłady

Przykład #1 Przykład ibase_set_event_handler()

<?php

function funkcja_zwrotna($nazwa_zdarzenia, $link)
{
    if ($nazwa_zdarzenia=="NOWE_ZAMOWIENIE") {
        // przetwarzanie NOWE_ZAMOWIENIE
        ibase_query($link, "UPDATE zamowienia SET status='zakonczone'");
      } else if ($nazwa_zdarzenia=="ZATRZYMANIE_SERWERA") {
        // wyrejestrowanie funkcji zwrotnej
        return false;
    }
}

ibase_set_event_handler($link, "funkcja_zwrotna", "NOWE_ZAMOWIENIE", "ZATRZYMANIE_SERWERA");
?>

Zobacz też:

  • ibase_free_event_handler() - Odwołuje funkcję zarejestrowaną do obsługiwania zdarzeń
  • ibase_wait_event() - Czeka na zdarzenie, które zostanie przesłane przez serwer

ibase_service_detach
ibase_timefmt
Funkcje Firebird/InterBase


Ustawia format znacznika czasu, daty i czasu w typach kolum zwracanych przez zapytania

ibase_set_event_handler
ibase_trans
Funkcje Firebird/InterBase
PHP Manual

ibase_timefmt

(PHP 4)

ibase_timefmt — Ustawia format znacznika czasu, daty i czasu w typach kolum zwracanych przez zapytania

Opis

bool ibase_timefmt ( string $format [, int $typ_kolumny = IBASE_TIMESTAMP ] )

Ustawia format znacznika czasu, daty i czasu w typach kolum zwracanych przez zapytania.

Można ustawić domyślne wartości dla tych formatów za pomocą dyrektyw konfiguracyjnych PHP ibase.timestampformat, ibase.dateformat i ibase.timeformat.

Informacja:

Ta funkcja została usunięta w PHP 5. Zamiast niej należy używać ini_set().

Parametry

format

Wewnętrznie (w PHP) kolumny są formatowane za pomocą funkcji języka C strftime(), więc odsyłamy do jej dokumentacji, w celu zapoznania się z możliwościami formatowania tego łańcucha.

typ_kolumny

typ_kolumny jest jedną ze stałych IBASE_TIMESTAMP, IBASE_DATE i IBASE_TIME. Jeśli zostanie pominięty, to domyślnie przyjmowana jest wartość IBASE_TIMESTAMP.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład ibase_timefmt()

<?php
/* InterBase 6 zwróci typ czasu
 * w formacie '05 godzin 37 minut'. */
ibase_timefmt("%H godzin %M minut", IBASE_TIME);
?>

ibase_set_event_handler
ibase_trans
Funkcje Firebird/InterBase


Rozpoczyna transakcję

ibase_timefmt
ibase_wait_event
Funkcje Firebird/InterBase
PHP Manual

ibase_trans

(PHP 4, PHP 5)

ibase_trans — Rozpoczyna transakcję

Opis

resource ibase_trans ([ int $opcje_transakcji [, resource $identyfikator_połączenia ]] )
resource ibase_trans ([ resource $identyfikator_połączenia [, int $opcje_transakcji ]] )

Rozpoczyna transakcję.

Informacja:

Zachowanie tej funkcji zostało zmienione w PHP 5.0.0. Pierwsze wywołanie ibase_trans() nie zwraca domyślnej transakcji w domyślnym połączeniu. Wszystkie transakcje rozpoczęte w wyniku wywołania ibase_trans() będą wycofane w momencie zakończenia działania skryptu, jeżeli nie zostaną jawnie potwierdzone lub wycofane, odpowiednio za pomocą ibase_commit() lub ibase_rollback().

Informacja:

W PHP 5.0.0. i nowszych wersjach ta funkcja akceptuje złożone argumenty opcje_transakcji i identyfikator_połączenia. To pozwala transakcjom na wielokrotne połączenia do baz danych i stosowanie algorytmu dwufazowego potwierdzania. Tym samym można mieć pewność, że we wszystkich bazach danych operacje zakończą się prawidłowo lub błędnie. To NIE oznacza, że można używać tabel z różnych baz danych w jednym zapytaniu!

Podczas korzystania w tym samym czasie z wielu baz danych, należy podawać obydwa parametry identyfikator_połączenia i identyfikator_transakcji przy wywoływaniu ibase_query() i ibase_prepare().

Parametry

opcje_transakcji

opcje_transakcji mogą być kombinacją stałych IBASE_READ, IBASE_WRITE, IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT i IBASE_NOWAIT.

identyfikator_połączenia

Identyfikator połączenia do Firebird/InterBase. Jeżeli zostanie pominięty, to użyte będzie istniejące połączenie.

Zwracane wartości

Zwraca identyfikator transakcji, lub FALSE w przypadku błędu.

ibase_timefmt
ibase_wait_event
Funkcje Firebird/InterBase


Czeka na zdarzenie, które zostanie przesłane przez serwer

ibase_trans
FrontBase
Funkcje Firebird/InterBase
PHP Manual

ibase_wait_event

(PHP 5)

ibase_wait_event — Czeka na zdarzenie, które zostanie przesłane przez serwer

Opis

string ibase_wait_event ( string $nazwa_zdarzenia1 [, string $nazwa_zdarzenia2 [, string $... ]] )
string ibase_wait_event ( resource $identyfikator_połączenia , string $nazwa_zdarzenia1 [, string $nazwa_zdarzenia2 [, string $... ]] )

Ta funkcja wstrzymuje wykonywanie skryptu, dopóki nie zostanie przesłana informacja przez bazę danych o wystąpieniu jednego określonych zdarzeń. Funkcja akceptuje maksymalnie 15 argumentów nazwa_zdarzenia.

Parametry

nazwa_zdarzenia1

Nazwa zdarzenia.

nazwa_zdarzenia2

...

Zwracane wartości

Zwraca nazwę zdarzenia, które zostało przesłane.

Zobacz też:

  • ibase_set_event_handler() - Rejestruje funkcję zwrotną, wywoływaną podczas występowania zadarzeń
  • ibase_free_event_handler() - Odwołuje funkcję zarejestrowaną do obsługiwania zdarzeń

ibase_trans
FrontBase
Funkcje Firebird/InterBase


FrontBase

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje FrontBase
    • fbsql_affected_rows — Get number of affected rows in previous FrontBase operation
    • fbsql_autocommit — Enable or disable autocommit
    • fbsql_blob_size — Get the size of a BLOB
    • fbsql_change_user — Change logged in user of the active connection
    • fbsql_clob_size — Get the size of a CLOB
    • fbsql_close — Zamyka połączenie z serwerem FrontBase
    • fbsql_commit — Commits a transaction to the database
    • fbsql_connect — Otwiera połączenie z serwerem FrontBase
    • fbsql_create_blob — Create a BLOB
    • fbsql_create_clob — Create a CLOB
    • fbsql_create_db — Create a FrontBase database
    • fbsql_data_seek — Move internal result pointer
    • fbsql_database_password — Sets or retrieves the password for a FrontBase database
    • fbsql_database — Get or set the database name used with a connection
    • fbsql_db_query — Send a FrontBase query
    • fbsql_db_status — Zwraca status dla podanej bazy danych
    • fbsql_drop_db — Drop (delete) a FrontBase database
    • fbsql_errno — Returns the error number from previous operation
    • fbsql_error — Returns the error message from previous operation
    • fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • fbsql_fetch_assoc — Fetch a result row as an associative array
    • fbsql_fetch_field — Get column information from a result and return as an object
    • fbsql_fetch_lengths — Get the length of each output in a result
    • fbsql_fetch_object — Fetch a result row as an object
    • fbsql_fetch_row — Get a result row as an enumerated array
    • fbsql_field_flags — Get the flags associated with the specified field in a result
    • fbsql_field_len — Returns the length of the specified field
    • fbsql_field_name — Get the name of the specified field in a result
    • fbsql_field_seek — Set result pointer to a specified field offset
    • fbsql_field_table — Zwraca nazwę tabeli dla określonego pola
    • fbsql_field_type — Get the type of the specified field in a result
    • fbsql_free_result — Zwalnia pamięć zajmowaną przez wynik
    • fbsql_get_autostart_info — Pobiera informacje o bazach automatycznie uruchamianych podczas startu serwera
    • fbsql_hostname — Zraca lub ustawia nazwę hosta używaną w połączeniu
    • fbsql_insert_id — Get the id generated from the previous INSERT operation
    • fbsql_list_dbs — List databases available on a FrontBase server
    • fbsql_list_fields — List FrontBase result fields
    • fbsql_list_tables — List tables in a FrontBase database
    • fbsql_next_result — Move the internal result pointer to the next result
    • fbsql_num_fields — Get number of fields in result
    • fbsql_num_rows — Get number of rows in result
    • fbsql_password — Zwraca lub ustawia hasło użytkownika używane w połączeniu
    • fbsql_pconnect — Otwiera stałe połączenie z serwerem FrontBase
    • fbsql_query — Wysyła zapytanie do serwera FrontBase
    • fbsql_read_blob — Read a BLOB from the database
    • fbsql_read_clob — Read a CLOB from the database
    • fbsql_result — Get result data
    • fbsql_rollback — Rollback a transaction to the database
    • fbsql_rows_fetched — Get the number of rows affected by the last statement
    • fbsql_select_db — Select a FrontBase database
    • fbsql_set_characterset — Zmienia kodowanie znaków na wejściu/wyjściu
    • fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
    • fbsql_set_password — Change the password for a given user
    • fbsql_set_transaction — Set the transaction locking and isolation
    • fbsql_start_db — Uruchamia bazę danych na serwerze lokalnym lub zdalnym
    • fbsql_stop_db — Zatrzymuje bazę danych na serwerze lokalnym lub zdalnym
    • fbsql_table_name — Get table name of field
    • fbsql_tablename — Alias dla fbsql_table_name
    • fbsql_username — Zraca lub ustawia nazwę użytkownika używaną w połączeniu
    • fbsql_warnings — Enable or disable FrontBase warnings
ibase_wait_event
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Te funkcje pozwalają uzyskać dostęp do serwerów baz danych FrontBase. Więcej informacji na temat FrontBase można znaleźć na witrynie » http://www.frontbase.com/.

Dokumentacja FrontBase jest dostępna na witrynie » http://www.frontbase.com/cgi-bin/WebObjects/FBWebSite.woa.

Obsługa FrontBase została dodana w PHP 4.0.6.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.3.0.

FrontBase
Instalacja/Konfiguracja
FrontBase


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
FrontBase


Wymagania

Aby używać tych funkcji, należy zainstalować serwer zarządzania bazami danych FrontBase, lub przynajmniej biblioteki klienta fbsql. FrontBase można pobrać z witryny » http://www.frontbase.com/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Aby te funkcje były dostępne, musimy skompilować PHP z obsługą fbsql używając opcji --with-fbsql[=DIR] . Jeśli użyjemy tej opcji bez określenia ścieżki do FrontBase, wówczas PHP będzie szukał bibliotek klienta fbsql w domyślnym katalogu instalacji dla danej platformy systemowej. Użytkownicy, którzy zainstalowali FrontBase w niestandardowym katalogu, zawsze powinni określić ścieżkę do fbsql: --with-fbsql=/ścieżka/do/fbsql . Podanie ścieżki wskaże PHP aby używał bibliotek klienta zainstalowanych z FrontBase, co pozwoli uniknąć problemów.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracyjne FrontBase
Nazwa | Wartość domyślna | Możliwość zmian | Rejestr zmian
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Dostępna od PHP 4.2.0.
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.max_links | "128" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.max_results | "128" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.batchSize | "1000" | PHP_INI_SYSTEM | Dostępna od PHP 4.2.0. Usunięta w PHP 5.1.0.
fbsql.default_host | NULL | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.default_password | "" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.default_database | "" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
fbsql.default_database_password | "" | PHP_INI_SYSTEM | Dostępna od PHP 4.0.6.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

FBSQL_ASSOC (integer)
FBSQL_NUM (integer)
FBSQL_BOTH (integer)
FBSQL_LOCK_DEFERRED (integer)
FBSQL_LOCK_OPTIMISTIC (integer)
FBSQL_LOCK_PESSIMISTIC (integer)
FBSQL_ISO_READ_UNCOMMITTED (integer)
FBSQL_ISO_READ_COMMITTED (integer)
FBSQL_ISO_REPEATABLE_READ (integer)
FBSQL_ISO_SERIALIZABLE (integer)
FBSQL_ISO_VERSIONED (integer)
FBSQL_UNKNOWN (integer)
FBSQL_STOPPED (integer)
FBSQL_STARTING (integer)
FBSQL_RUNNING (integer)
FBSQL_STOPPING (integer)
FBSQL_NOEXEC (integer)
FBSQL_LOB_DIRECT (integer)
FBSQL_LOB_HANDLE (integer)
Typy zasobów
Funkcje FrontBase
FrontBase


Funkcje FrontBase

Spis treści

  • fbsql_affected_rows — Get number of affected rows in previous FrontBase operation
  • fbsql_autocommit — Enable or disable autocommit
  • fbsql_blob_size — Get the size of a BLOB
  • fbsql_change_user — Change logged in user of the active connection
  • fbsql_clob_size — Get the size of a CLOB
  • fbsql_close — Zamyka połączenie z serwerem FrontBase
  • fbsql_commit — Commits a transaction to the database
  • fbsql_connect — Otwiera połączenie z serwerem FrontBase
  • fbsql_create_blob — Create a BLOB
  • fbsql_create_clob — Create a CLOB
  • fbsql_create_db — Create a FrontBase database
  • fbsql_data_seek — Move internal result pointer
  • fbsql_database_password — Sets or retrieves the password for a FrontBase database
  • fbsql_database — Get or set the database name used with a connection
  • fbsql_db_query — Send a FrontBase query
  • fbsql_db_status — Zwraca status dla podanej bazy danych
  • fbsql_drop_db — Drop (delete) a FrontBase database
  • fbsql_errno — Returns the error number from previous operation
  • fbsql_error — Returns the error message from previous operation
  • fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc — Fetch a result row as an associative array
  • fbsql_fetch_field — Get column information from a result and return as an object
  • fbsql_fetch_lengths — Get the length of each output in a result
  • fbsql_fetch_object — Fetch a result row as an object
  • fbsql_fetch_row — Get a result row as an enumerated array
  • fbsql_field_flags — Get the flags associated with the specified field in a result
  • fbsql_field_len — Returns the length of the specified field
  • fbsql_field_name — Get the name of the specified field in a result
  • fbsql_field_seek — Set result pointer to a specified field offset
  • fbsql_field_table — Zwraca nazwę tabeli dla określonego pola
  • fbsql_field_type — Get the type of the specified field in a result
  • fbsql_free_result — Zwalnia pamięć zajmowaną przez wynik
  • fbsql_get_autostart_info — Pobiera informacje o bazach automatycznie uruchamianych podczas startu serwera
  • fbsql_hostname — Zraca lub ustawia nazwę hosta używaną w połączeniu
  • fbsql_insert_id — Get the id generated from the previous INSERT operation
  • fbsql_list_dbs — List databases available on a FrontBase server
  • fbsql_list_fields — List FrontBase result fields
  • fbsql_list_tables — List tables in a FrontBase database
  • fbsql_next_result — Move the internal result pointer to the next result
  • fbsql_num_fields — Get number of fields in result
  • fbsql_num_rows — Get number of rows in result
  • fbsql_password — Zwraca lub ustawia hasło użytkownika używane w połączeniu
  • fbsql_pconnect — Otwiera stałe połączenie z serwerem FrontBase
  • fbsql_query — Wysyła zapytanie do serwera FrontBase
  • fbsql_read_blob — Read a BLOB from the database
  • fbsql_read_clob — Read a CLOB from the database
  • fbsql_result — Get result data
  • fbsql_rollback — Rollback a transaction to the database
  • fbsql_rows_fetched — Get the number of rows affected by the last statement
  • fbsql_select_db — Select a FrontBase database
  • fbsql_set_characterset — Zmienia kodowanie znaków na wejściu/wyjściu
  • fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
  • fbsql_set_password — Change the password for a given user
  • fbsql_set_transaction — Set the transaction locking and isolation
  • fbsql_start_db — Uruchamia bazę danych na serwerze lokalnym lub zdalnym
  • fbsql_stop_db — Zatrzymuje bazę danych na serwerze lokalnym lub zdalnym
  • fbsql_table_name — Get table name of field
  • fbsql_tablename — Alias dla fbsql_table_name
  • fbsql_username — Zraca lub ustawia nazwę użytkownika używaną w połączeniu
  • fbsql_warnings — Enable or disable FrontBase warnings
Stałe predefiniowane
fbsql_affected_rows
FrontBase


Get number of affected rows in previous FrontBase operation

Funkcje FrontBase
fbsql_autocommit
Funkcje FrontBase
PHP Manual

fbsql_affected_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_affected_rows — Get number of affected rows in previous FrontBase operation

Opis

int fbsql_affected_rows ([ resource $link_identifier ] )

fbsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with link_identifier.

Informacja:

If you are using transactions, you need to call fbsql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the commit.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero.

Informacja:

When using UPDATE, FrontBase will not update columns where the new value is the same as the old value. This creates the possibility that fbsql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

If the last query failed, this function will return -1.

Zobacz też:

  • fbsql_num_rows() - Get number of rows in result

Funkcje FrontBase
fbsql_autocommit
Funkcje FrontBase


Enable or disable autocommit

fbsql_affected_rows
fbsql_blob_size
Funkcje FrontBase
PHP Manual

fbsql_autocommit

(PHP 4 >= 4.0.6, PHP 5)

fbsql_autocommit — Enable or disable autocommit

Opis

bool fbsql_autocommit ( resource $link_identifier [, bool $OnOff ] )

Returns the current autocommit status.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

OnOff

If this optional parameter is given the auto commit status will be changed.

With OnOff set to TRUE each statement will be committed automatically, if no errors was found.

With OnOff set to FALSE the user must commit or rollback the transaction using either fbsql_commit() or fbsql_rollback().

Zwracane wartości

Returns the current autocommit status, as a boolean.

Zobacz też:

  • fbsql_commit() - Commits a transaction to the database
  • fbsql_rollback() - Rollback a transaction to the database

fbsql_affected_rows
fbsql_blob_size
Funkcje FrontBase


Get the size of a BLOB

fbsql_autocommit
fbsql_change_user
Funkcje FrontBase
PHP Manual

fbsql_blob_size

(PHP 4 >= 4.2.0, PHP 5)

fbsql_blob_size — Get the size of a BLOB

Opis

int fbsql_blob_size ( string $blob_handle [, resource $link_identifier ] )

Returns the size of the given BLOB.

Parametry

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns the BLOB size as an integer, or FALSE on error.

Zobacz też:

  • fbsql_clob_size() - Get the size of a CLOB

fbsql_autocommit
fbsql_change_user
Funkcje FrontBase


Change logged in user of the active connection

fbsql_blob_size
fbsql_clob_size
Funkcje FrontBase
PHP Manual

fbsql_change_user

(PHP 4 >= 4.0.6, PHP 5)

fbsql_change_user — Change logged in user of the active connection

Opis

bool fbsql_change_user ( string $user , string $password [, string $database [, resource $link_identifier ]] )

fbsql_change_user() changes the logged in user of the specified connection. If the new user and password authorization fails, the current connected user stays active.

Parametry

user

The new user name.

password

The new user password.

database

If specified, this will be the default or current database after the user has been changed.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

fbsql_blob_size
fbsql_clob_size
Funkcje FrontBase


Get the size of a CLOB

fbsql_change_user
fbsql_close
Funkcje FrontBase
PHP Manual

fbsql_clob_size

(PHP 4 >= 4.2.0, PHP 5)

fbsql_clob_size — Get the size of a CLOB

Opis

int fbsql_clob_size ( string $clob_handle [, resource $link_identifier ] )

Returns the size of the given CLOB.

Parametry

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns the CLOB size as an integer, or FALSE on error.

Zobacz też:

  • fbsql_blob_size() - Get the size of a BLOB

fbsql_change_user
fbsql_close
Funkcje FrontBase


Zamyka połączenie z serwerem FrontBase

fbsql_clob_size
fbsql_commit
Funkcje FrontBase
PHP Manual

fbsql_close

(PHP 4 >= 4.0.6, PHP 5)

fbsql_close — Zamyka połączenie z serwerem FrontBase

Opis

bool fbsql_close ([ resource $identyfikator_połączenia ] )

Zamyka połączenie z serwerem FrontBase skojarzone z podanym identyfikatorem połączenia.

Używanie fbsql_close() zazwyczaj nie jest konieczne, jako że niestałe połączenia są automatycznie zamykane po zakończeniu wykonywania skryptu.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład fbsql_close()

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "")
    or die("Nie można nawiązać połączenia");
echo "Połączenie zostało nawiązane";
fbsql_close($link);
?>

Zobacz też:

  • fbsql_connect() - Otwiera połączenie z serwerem FrontBase
  • fbsql_pconnect() - Otwiera stałe połączenie z serwerem FrontBase

fbsql_clob_size
fbsql_commit
Funkcje FrontBase


Commits a transaction to the database

fbsql_close
fbsql_connect
Funkcje FrontBase
PHP Manual

fbsql_commit

(PHP 4 >= 4.0.6, PHP 5)

fbsql_commit — Commits a transaction to the database

Opis

bool fbsql_commit ([ resource $link_identifier ] )

Ends the current transaction by writing all inserts, updates and deletes to the disk and unlocking all row and table locks held by the transaction. This command is only needed if autocommit is set to false.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fbsql_autocommit() - Enable or disable autocommit
  • fbsql_rollback() - Rollback a transaction to the database

fbsql_close
fbsql_connect
Funkcje FrontBase


Otwiera połączenie z serwerem FrontBase

fbsql_commit
fbsql_create_blob
Funkcje FrontBase
PHP Manual

fbsql_connect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_connect — Otwiera połączenie z serwerem FrontBase

Opis

 resource fbsql_connect
  ([ string $nazwa_hosta = ini_get("fbsql.default_host")
 [, string $użytkownik = ini_get("fbsql.default_user")
 [, string $hasło = ini_get("fbsql.default_password")
]]] )

fbsql_connect() nawiązuje połączenie z serwerem FrontBase.

W przypadku ponownego wywołania funkcji fbsql_connect() z takimi samymi argumentami, nie jest otwierane nowe połączenie, jednak w to miejsce powinien zostać zwrócony identyfikator już otwartego połączenia.

Połączenie do serwera powinno zostać zamknięte wkrótce po tym, kiedy wykonywanie skryptu PHP się zakończy, o ile nie zostanie zamknięte wcześniej przez jawne wywołanie funkcji fbsql_close().

Parametry

nazwa_hosta

Nazwa hosta, na którym jest uruchomiony serwer.

użytkownik

Nazwa użytkownika do nawiązania połączenia.

hasło

Hasło do nawiązania połączenia.

Zwracane wartości

Zwraca identyfikator połączenia do FrontBase w przypadku sukcesu lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Przykład fbsql_connect()

<?php

$link = fbsql_connect("localhost", "_SYSTEM", "")
    or die("Nie można nawiązać połączenia");
echo "Połączenie zostało nawiązane";
fbsql_close($link);

?>

Zobacz też:

  • fbsql_pconnect() - Otwiera stałe połączenie z serwerem FrontBase
  • fbsql_close() - Zamyka połączenie z serwerem FrontBase

fbsql_commit
fbsql_create_blob
Funkcje FrontBase


Create a BLOB

fbsql_connect
fbsql_create_clob
Funkcje FrontBase
PHP Manual

fbsql_create_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_create_blob — Create a BLOB

Opis

string fbsql_create_blob ( string $blob_data [, resource $link_identifier ] )

Creates a BLOB from the given data.

Parametry

blob_data

The BLOB data.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns a resource handle to the newly created BLOB, which can be used with insert and update commands to store the BLOB in the database.

Przykłady

Przykład #1 fbsql_create_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "blobfile.bin";
$fp = fopen($filename, "rb");
$blobdata = fread($fp, filesize($filename));
fclose($fp);

$blobHandle = fbsql_create_blob($blobdata, $link);

$sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
$rs = fbsql_query($sql, $link);
?>

Zobacz też:

  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

fbsql_connect
fbsql_create_clob
Funkcje FrontBase


Create a CLOB

fbsql_create_blob
fbsql_create_db
Funkcje FrontBase
PHP Manual

fbsql_create_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_create_clob — Create a CLOB

Opis

string fbsql_create_clob ( string $clob_data [, resource $link_identifier ] )

Creates a CLOB from the given data.

Parametry

clob_data

The CLOB data.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns a resource handle to the newly created CLOB, which can be used with insert and update commands to store the CLOB in the database.

Przykłady

Przykład #1 fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "clob_file.txt";
$fp = fopen($filename, "rb");
$clobdata = fread($fp, filesize($filename));
fclose($fp);

$clobHandle = fbsql_create_clob($clobdata, $link);

$sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
$rs = fbsql_query($sql, $link);
?>

Zobacz też:

  • fbsql_create_blob() - Create a BLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

fbsql_create_blob
fbsql_create_db
Funkcje FrontBase


Create a FrontBase database

fbsql_create_clob
fbsql_data_seek
Funkcje FrontBase
PHP Manual

fbsql_create_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_create_db — Create a FrontBase database

Opis

bool fbsql_create_db ( string $database_name [, resource $link_identifier [, string $database_options ]] )

Attempts to create a new database on the specified server.

Parametry

database_name

The database name, as a string.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

database_options

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 fbsql_create_db() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
if (fbsql_create_db("my_db")) {
    echo "Database created successfully\n";
} else {
    printf("Error creating database: %s\n", fbsql_error());
}
?>

Zobacz też:

  • fbsql_drop_db() - Drop (delete) a FrontBase database

fbsql_create_clob
fbsql_data_seek
Funkcje FrontBase


Move internal result pointer

fbsql_create_db
fbsql_database_password
Funkcje FrontBase
PHP Manual

fbsql_data_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_data_seek — Move internal result pointer

Opis

bool fbsql_data_seek ( resource $result , int $row_number )

Moves the internal row pointer of the FrontBase result associated with the specified result identifier to point to the specified row number.

The next call to fbsql_fetch_row() would return that row.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

row_number

The row number. Starts at 0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 fbsql_data_seek() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");

fbsql_select_db("samp_db")
    or die("Could not select database");

$query = "SELECT last_name, first_name FROM friends;";
$result = fbsql_query($query)
    or die("Query failed");

// fetch rows in reverse order

for ($i = fbsql_num_rows($result) - 1; $i >=0; $i--) {
    if (!fbsql_data_seek($result, $i)) {
        printf("Cannot seek to row %d\n", $i);
        continue;
    }

    if (!($row = fbsql_fetch_object($result)))
        continue;

    echo $row->last_name . $row->first_name . "<br />\n";
}

fbsql_free_result($result);
?>

fbsql_create_db
fbsql_database_password
Funkcje FrontBase


Sets or retrieves the password for a FrontBase database

fbsql_data_seek
fbsql_database
Funkcje FrontBase
PHP Manual

fbsql_database_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database_password — Sets or retrieves the password for a FrontBase database

Opis

string fbsql_database_password ( resource $link_identifier [, string $database_password ] )

Sets and retrieves the database password used by the connection. If a database is protected by a database password, the user must call this function before calling fbsql_select_db().

If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

This function does not change the database password in the database nor can it be used to retrieve the database password for a database.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

database_password

The database password, as a string. If given, the function sets the database password for the specified link identifier.

Zwracane wartości

Returns the database password associated with the link identifier.

Przykłady

Przykład #1 fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
fbsql_database_password($link, "secret db password");
fbsql_select_db($database, $link);
?>

Zobacz też:

  • fbsql_connect() - Otwiera połączenie z serwerem FrontBase
  • fbsql_pconnect() - Otwiera stałe połączenie z serwerem FrontBase
  • fbsql_select_db() - Select a FrontBase database

fbsql_data_seek
fbsql_database
Funkcje FrontBase


Get or set the database name used with a connection

fbsql_database_password
fbsql_db_query
Funkcje FrontBase
PHP Manual

fbsql_database

(PHP 4 >= 4.0.6, PHP 5)

fbsql_database — Get or set the database name used with a connection

Opis

string fbsql_database ( resource $link_identifier [, string $database ] )

Get or set the database name used with the connection.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

database

The database name. If given, the default database of the connexion will be changed to database.

Zwracane wartości

Returns the name of the database used with this connection.

fbsql_database_password
fbsql_db_query
Funkcje FrontBase


Send a FrontBase query

fbsql_database
fbsql_db_status
Funkcje FrontBase
PHP Manual

fbsql_db_query

(PHP 4 >= 4.0.6, PHP 5)

fbsql_db_query — Send a FrontBase query

Opis

resource fbsql_db_query ( string $database , string $query [, resource $link_identifier ] )

Selects a database and executes a query on it.

Parametry

database

The database to be selected.

query

The SQL query to be executed.

Informacja:

The query string shall always end with a semicolon.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns a positive FrontBase result identifier to the query result, or FALSE on error.

Zobacz też:

  • fbsql_query() - Wysyła zapytanie do serwera FrontBase
  • fbsql_connect() - Otwiera połączenie z serwerem FrontBase

fbsql_database
fbsql_db_status
Funkcje FrontBase


Zwraca status dla podanej bazy danych

fbsql_db_query
fbsql_drop_db
Funkcje FrontBase
PHP Manual

fbsql_db_status

(PHP 4 >= 4.0.7, PHP 5)

fbsql_db_status — Zwraca status dla podanej bazy danych

Opis

int fbsql_db_status ( string $nazwa_bazy_danych [, resource $identyfikator_połączenia ] )

Zwraca bieżący status dla określonej bazy danych.

Parametry

nazwa_bazy_danych

Nazwa bazy danych.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Zwraca wartość typu integer oznaczającą obecny status bazy danych. Może ona przyjmować następujące wartości:

  • FALSE - Identyfikator połączenia do hosta był nieprawidłowy. Ten błąd występuje wówczas, gdy identyfikator_połączenia jest zasobem utrzymującym bezpośrednie połączenie z bazą danych na ustalonym porcie. FBExec może być dostępny na serwerze, jednak nie zostało zdefiniowane dla niego połączenie.
  • FBSQL_UNKNOWN - Nieznany status.
  • FBSQL_STOPPED - Baza danych nie jest uruchomiona. Użyj fbsql_start_db() aby uruchomić bazę danych.
  • FBSQL_STARTING - Baza danych uruchamia się.
  • FBSQL_RUNNING - Baza danych jest uruchomiona i można wykonywać instrukcje SQL.
  • FBSQL_STOPPING - Baza danych zatrzymuje się.
  • FBSQL_NOEXEC - FBExec nie jest uruchomiony na serwerze i nie jest możliwe pobranie informacji o statusie bazy danych.

Zobacz też:

  • fbsql_start_db() - Uruchamia bazę danych na serwerze lokalnym lub zdalnym
  • fbsql_stop_db() - Zatrzymuje bazę danych na serwerze lokalnym lub zdalnym

fbsql_db_query
fbsql_drop_db
Funkcje FrontBase


Drop (delete) a FrontBase database

fbsql_db_status
fbsql_errno
Funkcje FrontBase
PHP Manual

fbsql_drop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_drop_db — Drop (delete) a FrontBase database

Opis

bool fbsql_drop_db ( string $database_name [, resource $link_identifier ] )

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

Parametry

database_name

The database name, as a string.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fbsql_create_db() - Create a FrontBase database

fbsql_db_status
fbsql_errno
Funkcje FrontBase


Returns the error number from previous operation

fbsql_drop_db
fbsql_error
Funkcje FrontBase
PHP Manual

fbsql_errno

(PHP 4 >= 4.0.6, PHP 5)

fbsql_errno — Returns the error number from previous operation

Opis

int fbsql_errno ([ resource $link_identifier ] )

Returns the numerical value of the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Przykłady

Przykład #1 fbsql_errno() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

Zobacz też:

  • fbsql_error() - Returns the error message from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings

fbsql_drop_db
fbsql_error
Funkcje FrontBase


Returns the error message from previous operation

fbsql_errno
fbsql_fetch_array
Funkcje FrontBase
PHP Manual

fbsql_error

(PHP 4 >= 4.0.6, PHP 5)

fbsql_error — Returns the error message from previous operation

Opis

string fbsql_error ([ resource $link_identifier ] )

Returns the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_error() to retrieve the error text. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Przykłady

Przykład #1 fbsql_error() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

Zobacz też:

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings

fbsql_errno
fbsql_fetch_array
Funkcje FrontBase


Fetch a result row as an associative array, a numeric array, or both

fbsql_error
fbsql_fetch_assoc
Funkcje FrontBase
PHP Manual

fbsql_fetch_array

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Opis

array fbsql_fetch_array ( resource $result [, int $result_type ] )

fbsql_fetch_array() is a combination of
fbsql_fetch_row() and
fbsql_fetch_assoc().

An important thing to note is that using fbsql_fetch_array() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

result_type

A constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, or FBSQL_BOTH.

When using FBSQL_BOTH, in addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must the numeric index of the column or make an alias for the column.

select t1.f1 as foo t2.f1 as bar from t1, t2

Przykłady

Przykład #1 fbsql_fetch_array() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select user_id, fullname from table");
while ($row = fbsql_fetch_array($result)) {
    echo "user_id: " . $row["user_id"] . "<br />\n";
    echo "user_id: " . $row[0] . "<br />\n";
    echo "fullname: " . $row["fullname"] . "<br />\n";
    echo "fullname: " . $row[1] . "<br />\n";
}
fbsql_free_result($result);
?>

Zobacz też:

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object

fbsql_error
fbsql_fetch_assoc
Funkcje FrontBase


Fetch a result row as an associative array

fbsql_fetch_array
fbsql_fetch_field
Funkcje FrontBase
PHP Manual

fbsql_fetch_assoc

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_assoc — Fetch a result row as an associative array

Opis

array fbsql_fetch_assoc ( resource $result )

Calling fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC as second parameter. It only returns an associative array.

This is the way fbsql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use fbsql_fetch_array().

An important thing to note is that using fbsql_fetch_assoc() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use fbsql_fetch_array() and have it return the numeric indices as well.

Przykłady

Przykład #1 fbsql_fetch_assoc() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_assoc($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result($result);
?>

Zobacz też:

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_object() - Fetch a result row as an object

fbsql_fetch_array
fbsql_fetch_field
Funkcje FrontBase


Get column information from a result and return as an object

fbsql_fetch_assoc
fbsql_fetch_lengths
Funkcje FrontBase
PHP Manual

fbsql_fetch_field

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_field — Get column information from a result and return as an object

Opis

object fbsql_fetch_field ( resource $result [, int $field_offset ] )

Used in order to obtain information about fields in a certain query result.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0. If not specified, the next field that wasn't yet retrieved by fbsql_fetch_field() is retrieved.

Zwracane wartości

Returns an object containing field information, or FALSE on errors.

The properties of the object are:

  • name - column name
  • table - name of the table the column belongs to
  • max_length - maximum length of the column
  • not_null - 1 if the column cannot be NULL
  • type - the type of the column

Przykłady

Przykład #1 fbsql_fetch_field() example

<?php
fbsql_connect($host, $user, $password)
    or die("Could not connect");
$result = fbsql_db_query("database", "select * from table")
    or die("Query failed");
# get column metadata
$i = 0;
while ($i < fbsql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = fbsql_fetch_field($result);
    if (!$meta) {
        echo "No information available<br />\n";
    }
    echo "<pre>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</pre>";
    $i++;
}
fbsql_free_result($result);
?>

Zobacz też:

  • fbsql_field_seek() - Set result pointer to a specified field offset

fbsql_fetch_assoc
fbsql_fetch_lengths
Funkcje FrontBase


Get the length of each output in a result

fbsql_fetch_field
fbsql_fetch_object
Funkcje FrontBase
PHP Manual

fbsql_fetch_lengths

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_lengths — Get the length of each output in a result

Opis

array fbsql_fetch_lengths ( resource $result )

Stores the lengths of each result column in the last row returned by
fbsql_fetch_row(),
fbsql_fetch_array() and
fbsql_fetch_object() in an array.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Returns an array, starting at offset 0, that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

Zobacz też:

  • fbsql_fetch_row() - Get a result row as an enumerated array

fbsql_fetch_field
fbsql_fetch_object
Funkcje FrontBase


Fetch a result row as an object

fbsql_fetch_lengths
fbsql_fetch_row
Funkcje FrontBase
PHP Manual

fbsql_fetch_object

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_object — Fetch a result row as an object

Opis

object fbsql_fetch_object ( resource $result )

fbsql_fetch_object() is similar to fbsql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to fbsql_fetch_array(), and almost as quick as fbsql_fetch_row() (the difference is insignificant).

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Przykłady

Przykład #1 fbsql_fetch_object() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result($result);
?>

Zobacz też:

  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_assoc() - Fetch a result row as an associative array

fbsql_fetch_lengths
fbsql_fetch_row
Funkcje FrontBase


Get a result row as an enumerated array

fbsql_fetch_object
fbsql_field_flags
Funkcje FrontBase
PHP Manual

fbsql_fetch_row

(PHP 4 >= 4.0.6, PHP 5)

fbsql_fetch_row — Get a result row as an enumerated array

Opis

array fbsql_fetch_row ( resource $result )

fbsql_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to fbsql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Returns an array that corresponds to the fetched row where each result column is stored in an offset, starting at offset 0, or FALSE if there are no more rows.

Zobacz też:

  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object
  • fbsql_data_seek() - Move internal result pointer
  • fbsql_fetch_lengths() - Get the length of each output in a result
  • fbsql_result() - Get result data

fbsql_fetch_object
fbsql_field_flags
Funkcje FrontBase


Get the flags associated with the specified field in a result

fbsql_fetch_row
fbsql_field_len
Funkcje FrontBase
PHP Manual

fbsql_field_flags

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_flags — Get the flags associated with the specified field in a result

Opis

string fbsql_field_flags ( resource $result [, int $field_offset ] )

Gets the flags associated with the specified field in a result.

Parametry

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Zwracane wartości

Returns the field flags of the specified field as a single word per flag separated by a single space, so that you can split the returned value using explode().

fbsql_fetch_row
fbsql_field_len
Funkcje FrontBase


Returns the length of the specified field

fbsql_field_flags
fbsql_field_name
Funkcje FrontBase
PHP Manual

fbsql_field_len

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_len — Returns the length of the specified field

Opis

int fbsql_field_len ( resource $result [, int $field_offset ] )

Returns the length of the specified field.

Parametry

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Zwracane wartości

Returns the length of the specified field.

fbsql_field_flags
fbsql_field_name
Funkcje FrontBase


Get the name of the specified field in a result

fbsql_field_len
fbsql_field_seek
Funkcje FrontBase
PHP Manual

fbsql_field_name

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_name — Get the name of the specified field in a result

Opis

string fbsql_field_name ( resource $result [, int $field_index ] )

Returns the name of the specified field index.

Parametry

result

A result pointer returned by fbsql_list_fields().

field_index

The numerical offset of the field. The field index starts at 0.

Zwracane wartości

Returns the name as a string, or FALSE if the field doesn't exist.

Przykłady

Przykład #1 fbsql_field_name() example

<?php
// The users table consists of three fields:
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);
?>

Powyższy przykład wyświetli:

user_id
password

Zobacz też:

  • fbsql_field_type() - Get the type of the specified field in a result

fbsql_field_len
fbsql_field_seek
Funkcje FrontBase


Set result pointer to a specified field offset

fbsql_field_name
fbsql_field_table
Funkcje FrontBase
PHP Manual

fbsql_field_seek

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_seek — Set result pointer to a specified field offset

Opis

bool fbsql_field_seek ( resource $result [, int $field_offset ] )

Seeks to the specified field offset. If the next call to fbsql_fetch_field() doesn't include a field offset, the field offset specified in fbsql_field_seek() will be returned.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fbsql_fetch_field() - Get column information from a result and return as an object

fbsql_field_name
fbsql_field_table
Funkcje FrontBase


Zwraca nazwę tabeli dla określonego pola

fbsql_field_seek
fbsql_field_type
Funkcje FrontBase
PHP Manual

fbsql_field_table

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_table — Zwraca nazwę tabeli dla określonego pola

Opis

string fbsql_field_table ( resource $wynik [, int $przesunięcie_pola ] )

Zwraca nazwę tabeli dla określonego pola w zbiorze wynikowym.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

przesunięcie_pola

Liczbowe przesunięcie pola. Przesunięcie pola zaczyna się od 0.

Zwracane wartości

Zwraca nazwę tabeli jako string.

fbsql_field_seek
fbsql_field_type
Funkcje FrontBase


Get the type of the specified field in a result

fbsql_field_table
fbsql_free_result
Funkcje FrontBase
PHP Manual

fbsql_field_type

(PHP 4 >= 4.0.6, PHP 5)

fbsql_field_type — Get the type of the specified field in a result

Opis

string fbsql_field_type ( resource $result [, int $field_offset ] )

fbsql_field_type() is similar to the fbsql_field_name() function, but the field type is returned instead.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Zwracane wartości

Returns the field type, as a string.

This can be one of int, real, string, blob, and others as detailed in the » FrontBase documentation.

Przykłady

Przykład #1 fbsql_field_type() example

<?php

fbsql_connect("localhost", "_SYSTEM", "");
fbsql_select_db("wisconsin");
$result = fbsql_query("SELECT * FROM onek;");
$fields = fbsql_num_fields($result);
$rows   = fbsql_num_rows($result);
$i = 0;
$table = fbsql_field_table($result, $i);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " records <br />";
echo "The table has the following fields <br />";
while ($i < $fields) {
    $type  = fbsql_field_type($result, $i);
    $name  = fbsql_field_name($result, $i);
    $len   = fbsql_field_len($result, $i);
    $flags = fbsql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "<br />";
    $i++;
}
fbsql_close();

?>

Zobacz też:

  • fbsql_field_name() - Get the name of the specified field in a result

fbsql_field_table
fbsql_free_result
Funkcje FrontBase


Zwalnia pamięć zajmowaną przez wynik

fbsql_field_type
fbsql_get_autostart_info
Funkcje FrontBase
PHP Manual

fbsql_free_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_free_result — Zwalnia pamięć zajmowaną przez wynik

Opis

bool fbsql_free_result ( resource $wynik )

Zwalnia pamięć zajmowaną przez wynik.

Wywołanie fbsql_free_result() jest potrzebne tylko wtedy, jeśli obawiamy się o ilość pamięci jaka zostanie użyta dla zapytań zwracających duży zbiór wyników. Cała pamięć przydzielona dla wyników jest automatycznie zwalniana, kiedy zakończy się wykonywanie skryptu.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

fbsql_field_type
fbsql_get_autostart_info
Funkcje FrontBase


Pobiera informacje o bazach automatycznie uruchamianych podczas startu serwera

fbsql_free_result
fbsql_hostname
Funkcje FrontBase
PHP Manual

fbsql_get_autostart_info

(PHP 4 >= 4.0.7, PHP 5)

fbsql_get_autostart_info — Pobiera informacje o bazach automatycznie uruchamianych podczas startu serwera

Opis

array fbsql_get_autostart_info ([ resource $identyfikator_połączenia ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

fbsql_free_result
fbsql_hostname
Funkcje FrontBase


Zraca lub ustawia nazwę hosta używaną w połączeniu

fbsql_get_autostart_info
fbsql_insert_id
Funkcje FrontBase
PHP Manual

fbsql_hostname

(PHP 4 >= 4.0.6, PHP 5)

fbsql_hostname — Zraca lub ustawia nazwę hosta używaną w połączeniu

Opis

string fbsql_hostname ( resource $identyfikator_połączenia [, string $nazwa_hosta ] )

Zraca lub ustawia nazwę hosta używaną w połączeniu.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

nazwa_hosta

Jeśli zostanie podana, wówczas będzie nową nazwą hosta w połączeniu.

Zwracane wartości

Zwraca nazwę aktualnego hosta używanego w połączeniu.

Zobacz też:

  • fbsql_username() - Zraca lub ustawia nazwę użytkownika używaną w połączeniu
  • fbsql_password() - Zwraca lub ustawia hasło użytkownika używane w połączeniu

fbsql_get_autostart_info
fbsql_insert_id
Funkcje FrontBase


Get the id generated from the previous INSERT operation

fbsql_hostname
fbsql_list_dbs
Funkcje FrontBase
PHP Manual

fbsql_insert_id

(PHP 4 >= 4.0.6, PHP 5)

fbsql_insert_id — Get the id generated from the previous INSERT operation

Opis

int fbsql_insert_id ([ resource $link_identifier ] )

Gets the id generated from the previous INSERT operation which created a DEFAULT UNIQUE value.

Informacja:

The value of the FrontBase SQL function fbsql_insert_id() always contains the most recently generated DEFAULT UNIQUE value, and is not reset between queries.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns the ID generated from the previous INSERT query, or 0 if the previous query does not generate an DEFAULT UNIQUE value.

If you need to save the value for later, be sure to call this function immediately after the query that generates the value.

Zobacz też:

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation

fbsql_hostname
fbsql_list_dbs
Funkcje FrontBase


List databases available on a FrontBase server

fbsql_insert_id
fbsql_list_fields
Funkcje FrontBase
PHP Manual

fbsql_list_dbs

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_dbs — List databases available on a FrontBase server

Opis

resource fbsql_list_dbs ([ resource $link_identifier ] )

Return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() to traverse this result pointer.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns a result pointer or FALSE on error.

Przykłady

Przykład #1 fbsql_list_dbs() example

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}
?>

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

database1
database2
database3
...

Informacja:

The above code would just as easily work with fbsql_fetch_row() or other similar functions.

Zobacz też:

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_tables() - List tables in a FrontBase database

fbsql_insert_id
fbsql_list_fields
Funkcje FrontBase


List FrontBase result fields

fbsql_list_dbs
fbsql_list_tables
Funkcje FrontBase
PHP Manual

fbsql_list_fields

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_fields — List FrontBase result fields

Opis

resource fbsql_list_fields ( string $database_name , string $table_name [, resource $link_identifier ] )

Retrieves information about the given table.

Parametry

database_name

The database name.

table_name

The table name.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns a result pointer which can be used with the fbsql_field_xxx functions, or FALSE on error.

Błędy/Wyjątki

A string describing the error will be placed in $phperrmsg, and unless the function was called as @fbsql() then this error string will also be printed out.

Przykłady

Przykład #1 fbsql_list_fields() example

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}
?>

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

field1
field2
field3
...

Zobacz też:

  • fbsql_field_len() - Returns the length of the specified field
  • fbsql_field_name() - Get the name of the specified field in a result
  • fbsql_field_type() - Get the type of the specified field in a result
  • fbsql_field_flags() - Get the flags associated with the specified field in a result

fbsql_list_dbs
fbsql_list_tables
Funkcje FrontBase


List tables in a FrontBase database

fbsql_list_fields
fbsql_next_result
Funkcje FrontBase
PHP Manual

fbsql_list_tables

(PHP 4 >= 4.0.6, PHP 5)

fbsql_list_tables — List tables in a FrontBase database

Opis

resource fbsql_list_tables ( string $database [, resource $link_identifier ] )

Returns a result pointer describing the database.

Parametry

database

The database name.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns a result pointer which can be used with the fbsql_tablename() function to read the actual table names, or FALSE on error.

Zobacz też:

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_dbs() - List databases available on a FrontBase server

fbsql_list_fields
fbsql_next_result
Funkcje FrontBase


Move the internal result pointer to the next result

fbsql_list_tables
fbsql_num_fields
Funkcje FrontBase
PHP Manual

fbsql_next_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_next_result — Move the internal result pointer to the next result

Opis

bool fbsql_next_result ( resource $result )

When sending more than one SQL statement to the server or executing a stored procedure with multiple results will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the words from the new result set.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Returns TRUE if an additional result set was available or FALSE otherwise.

Przykłady

Przykład #1 fbsql_next_result() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret");
fbsql_select_db("MyDB", $link);
$SQL = "Select * from table1; select * from table2;";
$rs = fbsql_query($SQL, $link);
do {
    while ($row = fbsql_fetch_row($rs)) {
    }
} while (fbsql_next_result($rs));
fbsql_free_result($rs);
fbsql_close($link);
?>

fbsql_list_tables
fbsql_num_fields
Funkcje FrontBase


Get number of fields in result

fbsql_next_result
fbsql_num_rows
Funkcje FrontBase
PHP Manual

fbsql_num_fields

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_fields — Get number of fields in result

Opis

int fbsql_num_fields ( resource $result )

Returns the number of fields in the given result set.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Returns the number of fields, as an integer.

Zobacz też:

  • fbsql_db_query() - Send a FrontBase query
  • fbsql_query() - Wysyła zapytanie do serwera FrontBase
  • fbsql_fetch_field() - Get column information from a result and return as an object
  • fbsql_num_rows() - Get number of rows in result

fbsql_next_result
fbsql_num_rows
Funkcje FrontBase


Get number of rows in result

fbsql_num_fields
fbsql_password
Funkcje FrontBase
PHP Manual

fbsql_num_rows

(PHP 4 >= 4.0.6, PHP 5)

fbsql_num_rows — Get number of rows in result

Opis

int fbsql_num_rows ( resource $result )

Gets the number of rows in the given result set.

This function is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Returns the number of rows returned by the last SELECT statement.

Przykłady

Przykład #1 fbsql_num_rows() example

<?php

$link = fbsql_connect("localhost", "username", "password");
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link);
$num_rows = fbsql_num_rows($result);

echo "$num_rows Rows\n";

?>

Zobacz też:

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_connect() - Otwiera połączenie z serwerem FrontBase
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_query() - Wysyła zapytanie do serwera FrontBase

fbsql_num_fields
fbsql_password
Funkcje FrontBase


Zwraca lub ustawia hasło użytkownika używane w połączeniu

fbsql_num_rows
fbsql_pconnect
Funkcje FrontBase
PHP Manual

fbsql_password

(PHP 4 >= 4.0.6, PHP 5)

fbsql_password — Zwraca lub ustawia hasło użytkownika używane w połączeniu

Opis

string fbsql_hasło ( resource $identyfikator_połączenia [, string $hasło ] )

Zwraca lub ustawia hasło użytkownika używane w połączeniu.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

hasło

Jeśli zostanie podane, to będzie nowym hasłem w połączeniu.

Zwracane wartości

Zwraca bieżące hasło używane w połączeniu.

Zobacz też:

  • fbsql_username() - Zraca lub ustawia nazwę użytkownika używaną w połączeniu
  • fbsql_hostname() - Zraca lub ustawia nazwę hosta używaną w połączeniu

fbsql_num_rows
fbsql_pconnect
Funkcje FrontBase


Otwiera stałe połączenie z serwerem FrontBase

fbsql_password
fbsql_query
Funkcje FrontBase
PHP Manual

fbsql_pconnect

(PHP 4 >= 4.0.6, PHP 5)

fbsql_pconnect — Otwiera stałe połączenie z serwerem FrontBase

Opis

 resource fbsql_pconnect
  ([ string $nazwa_hosta = ini_get("fbsql.default_host")
 [, string $użytkownik = ini_get("fbsql.default_user")
 [, string $hasło = ini_get("fbsql.default_password")
]]] )

Nawiązuje stałe połączenie z serwerem FrontBase.

Aby ustawić numer portu należy użyć fbsql_select_db().

fbsql_pconnect() zachowuje się prawie jak fbsql_connect() z dwoma zasadniczymi różnicami:

Pierwsza, podczas łączenia funkcja najpierw spróbuje znaleźć połączenie (stałe), już otwarte dla tych samych parametrów (host, użytkownik, hasło). Jeżeli je znajdzie, to jego identyfikator zostanie zwrócony zamiast otwierania nowego połączenia.

Druga, połączenie z serwerem FrontBase nie zostanie zamknięte po zakończeniu wykonywania skryptu. Zamiast tego połączenie pozostanie otwarte do późniejszego użycia.

Dlatego też ten typ połączeń nazywany jest 'stałym'.

Parametry

nazwa_hosta

Nazwa hosta, na którym jest uruchomiony serwer.

użytkownik

Nazwa użytkownika do nawiązania połączenia.

hasło

Hasło do nawiązania połączenia.

Zwracane wartości

Zwraca identyfikator stałego połączenia do FrontBase w przypadku sukcesu lub FALSE w przypadku błędu.

Zobacz też:

  • fbsql_connect() - Otwiera połączenie z serwerem FrontBase

fbsql_password
fbsql_query
Funkcje FrontBase


Wysyła zapytanie do serwera FrontBase

fbsql_pconnect
fbsql_read_blob
Funkcje FrontBase
PHP Manual

fbsql_query

(PHP 4 >= 4.0.6, PHP 5)

fbsql_query — Wysyła zapytanie do serwera FrontBase

Opis

resource fbsql_query ( string $zapytanie [, resource $identyfikator_połączenia [, int $rozmiar_partii_danych ]] )

Wysyła zapytanie do bieżącej bazy danych na serwerze.

Jeśli wykonanie zapytania się powiedzie, możemy wywołać fbsql_num_rows() aby się dowiedzieć jak dużo wierszy zostało zwróconych przez instrukcję SELECT, lub fbsql_affected_rows() żeby wykryć ile wierszy zostało przetworzonych przez instrukcję DELETE, INSERT, REPLACE, lub UPDATE.

Parametry

zapytanie

Zapytanie SQL do wykonania.

Informacja:

Zapytanie powinno zawsze kończyć się średnikiem.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

rozmiar_partii_danych

Zwracane wartości

fbsql_query() zwraca TRUE (nie zero) lub FALSE aby wskazać, czy zapytanie zostało wykonane prawidłowo. Zwrócenie TRUE oznacza, że zapytanie było prawidłowe i mogło zostać wykonane przez serwer. Funkcja nie informuje o liczbie przetworzonych lub zwróconych wieszy. Jest całkiem możliwe, że zapytanie było prawidłowe, jednak nie przetworzyło ani nie zwróciło żadnych wierszy.

Dla instrukcji SELECT fbsql_query() zwraca nowy identyfikator wyniku, który możemy przekazać do fbsql_result().

fbsql_query() może się nie powieść i zwrócić FALSE jeśli nie mamy uprawnień dostępu do tabel określonych w zapytaniu.

Przykłady

Poniższe zapytanie ma nieprawidłową składnię, a zatem wywołanie fbsql_query() się nie powiedzie i zwróci FALSE:

Przykład #1 Przykład fbsql_query()

<?php
$result = fbsql_query("SELECT * WHERE 1=1")
    or die ("Nieprawidłowe zapytanie");
?>

Poniższe zapytanie ma nieprawidłową składnię, jeżeli kolumna nie jest kolumną w tabeli tabela, tak więc wywołanie fbsql_query() się nie powiedzie i zwróci FALSE:

Przykład #2 Przykład fbsql_query()

<?php
$result = fbsql_query ("SELECT kolumna FROM tabela;")
    or die ("Nieprawidłowe zapytanie");
?>

Zobacz też:

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_db_query() - Send a FrontBase query
  • fbsql_free_result() - Zwalnia pamięć zajmowaną przez wynik
  • fbsql_result() - Get result data
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_connect() - Otwiera połączenie z serwerem FrontBase

fbsql_pconnect
fbsql_read_blob
Funkcje FrontBase


Read a BLOB from the database

fbsql_query
fbsql_read_clob
Funkcje FrontBase
PHP Manual

fbsql_read_blob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_blob — Read a BLOB from the database

Opis

string fbsql_read_blob ( string $blob_handle [, resource $link_identifier ] )

Reads BLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_blob() to get the actual BLOB data from the database.

Parametry

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns a string containing the specified BLOB data.

Przykłady

Przykład #1 fbsql_read_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the blob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the BLOB data in the first row
$blob_data = fbsql_read_blob($row_data[0]);
fbsql_free_result($rs);

?>

Zobacz też:

  • fbsql_create_blob() - Create a BLOB
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

fbsql_query
fbsql_read_clob
Funkcje FrontBase


Read a CLOB from the database

fbsql_read_blob
fbsql_result
Funkcje FrontBase
PHP Manual

fbsql_read_clob

(PHP 4 >= 4.2.0, PHP 5)

fbsql_read_clob — Read a CLOB from the database

Opis

string fbsql_read_clob ( string $clob_handle [, resource $link_identifier ] )

Reads CLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_clob() to get the actual CLOB data from the database.

Parametry

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Returns a string containing the specified CLOB data.

Przykłady

Przykład #1 fbsql_read_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the clob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the CLOB data in the first row
$clob_data = fbsql_read_clob($row_data[0]);
fbsql_free_result($rs);

?>

Zobacz też:

  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set

fbsql_read_blob
fbsql_result
Funkcje FrontBase


Get result data

fbsql_read_clob
fbsql_rollback
Funkcje FrontBase
PHP Manual

fbsql_result

(PHP 4 >= 4.0.6, PHP 5)

fbsql_result — Get result data

Opis

mixed fbsql_result ( resource $result [, int $row [, mixed $field ]] )

Returns the contents of one cell from a FrontBase result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than fbsql_result().

Calls to fbsql_result() should not be mixed with calls to other functions that deal with the result set.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

row

field

Can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname).

If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Informacja:

Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Zwracane wartości

Zobacz też:

Recommended high-performance alternatives:

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object

fbsql_read_clob
fbsql_rollback
Funkcje FrontBase


Rollback a transaction to the database

fbsql_result
fbsql_rows_fetched
Funkcje FrontBase
PHP Manual

fbsql_rollback

(PHP 4 >= 4.0.6, PHP 5)

fbsql_rollback — Rollback a transaction to the database

Opis

bool fbsql_rollback ([ resource $link_identifier ] )

Ends the current transaction by rolling back all statements issued since last commit.

This command is only needed if autocommit is set to false.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fbsql_autocommit() - Enable or disable autocommit
  • fbsql_commit() - Commits a transaction to the database

fbsql_result
fbsql_rows_fetched
Funkcje FrontBase


Get the number of rows affected by the last statement

fbsql_rollback
fbsql_select_db
Funkcje FrontBase
PHP Manual

fbsql_rows_fetched

(PHP 5 >= 5.1.0)

fbsql_rows_fetched — Get the number of rows affected by the last statement

Opis

int fbsql_rows_fetched ( resource $result )

Gets the number of rows affected by the last statement.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

Zwracane wartości

Returns the number of rows, as an integer.

fbsql_rollback
fbsql_select_db
Funkcje FrontBase


Select a FrontBase database

fbsql_rows_fetched
fbsql_set_characterset
Funkcje FrontBase
PHP Manual

fbsql_select_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_select_db — Select a FrontBase database

Opis

bool fbsql_select_db ([ string $database_name [, resource $link_identifier ]] )

Sets the current active database on the given link identifier.

The client contacts FBExec to obtain the port number to use for the connection to the database. If the database name is a number the system will use that as a port number and it will not ask FBExec for the port number. The FrontBase server can be stared as FRontBase -FBExec=No -port=<port number> <database name>.

Every subsequent call to fbsql_query() will be made on the active database.

Parametry

database_name

The name of the database to be selected.

If the database is protected with a database password, the you must call fbsql_database_password() before selecting the database.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fbsql_connect() - Otwiera połączenie z serwerem FrontBase
  • fbsql_pconnect() - Otwiera stałe połączenie z serwerem FrontBase
  • fbsql_database_password() - Sets or retrieves the password for a FrontBase database
  • fbsql_query() - Wysyła zapytanie do serwera FrontBase

fbsql_rows_fetched
fbsql_set_characterset
Funkcje FrontBase


Zmienia kodowanie znaków na wejściu/wyjściu

fbsql_select_db
fbsql_set_lob_mode
Funkcje FrontBase
PHP Manual

fbsql_set_characterset

(PHP 5 >= 5.1.0)

fbsql_set_characterset — Zmienia kodowanie znaków na wejściu/wyjściu

Opis

void fbsql_set_characterset ( resource $identyfikator_połączenia , int $kodowanie_znaków [, int $w_obie_strony ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

fbsql_select_db
fbsql_set_lob_mode
Funkcje FrontBase


Set the LOB retrieve mode for a FrontBase result set

fbsql_set_characterset
fbsql_set_password
Funkcje FrontBase
PHP Manual

fbsql_set_lob_mode

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set

Opis

bool fbsql_set_lob_mode ( resource $result , int $lob_mode )

Sets the mode for retrieving LOB data from the database.

When BLOB and CLOB data is retrieved in FrontBase it can be retrieved direct or indirect. Direct retrieved LOB data will always be fetched no matter the setting of the lob mode. If the LOB data is less than 512 bytes it will always be retrieved directly.

Parametry

result

Identyfikator wyniku zwrócony przez fbsql_query() lub fbsql_db_query().

lob_mode

Can be one of:

  • FBSQL_LOB_DIRECT - LOB data is retrieved directly. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, all CLOB and BLOB columns will be returned as ordinary columns. This is the default value on a new FrontBase result.
  • FBSQL_LOB_HANDLE - LOB data is retrieved as handles to the data. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, LOB data will be returned as a handle to the data if the data is stored indirect or the data if it is stored direct. If a handle is returned it will be a 27 byte string formatted as @'000000000000000000000000'.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fbsql_create_blob() - Create a BLOB
  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database

fbsql_set_characterset
fbsql_set_password
Funkcje FrontBase


Change the password for a given user

fbsql_set_lob_mode
fbsql_set_transaction
Funkcje FrontBase
PHP Manual

fbsql_set_password

(PHP 5)

fbsql_set_password — Change the password for a given user

Opis

bool fbsql_set_password ( resource $link_identifier , string $user , string $password , string $old_password )

Changes the password for the given user.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

user

The user name.

password

The new password to be set.

old_password

The old password to be replaced.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

fbsql_set_lob_mode
fbsql_set_transaction
Funkcje FrontBase


Set the transaction locking and isolation

fbsql_set_password
fbsql_start_db
Funkcje FrontBase
PHP Manual

fbsql_set_transaction

(PHP 4 >= 4.2.0, PHP 5)

fbsql_set_transaction — Set the transaction locking and isolation

Opis

void fbsql_set_transaction ( resource $link_identifier , int $locking , int $isolation )

Sets the transaction locking and isolation.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

locking

The type of locking to be set. It can be one of the following constants: FBSQL_LOCK_DEFERRED, FBSQL_LOCK_OPTIMISTIC, or FBSQL_LOCK_PESSIMISTIC.

isolation

The type of isolation to be set. It can be one of the following constants: FBSQL_ISO_READ_UNCOMMITTED, FBSQL_ISO_READ_COMMITTED, FBSQL_ISO_REPEATABLE_READ, FBSQL_ISO_SERIALIZABLE, or FBSQL_ISO_VERSIONED.

Zwracane wartości

Nie jest zwracana żadna wartość.

fbsql_set_password
fbsql_start_db
Funkcje FrontBase


Uruchamia bazę danych na serwerze lokalnym lub zdalnym

fbsql_set_transaction
fbsql_stop_db
Funkcje FrontBase
PHP Manual

fbsql_start_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_start_db — Uruchamia bazę danych na serwerze lokalnym lub zdalnym

Opis

bool fbsql_start_db ( string $nazwa_bazy_danych [, resource $identyfikator_połączenia [, string $opcje ]] )

Uruchamia bazę danych na serwerze lokalnym lub zdalnym.

Parametry

nazwa_bazy_danych

Nazwa bazy danych.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

opcje

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fbsql_db_status() - Zwraca status dla podanej bazy danych
  • fbsql_stop_db() - Zatrzymuje bazę danych na serwerze lokalnym lub zdalnym

fbsql_set_transaction
fbsql_stop_db
Funkcje FrontBase


Zatrzymuje bazę danych na serwerze lokalnym lub zdalnym

fbsql_start_db
fbsql_table_name
Funkcje FrontBase
PHP Manual

fbsql_stop_db

(PHP 4 >= 4.0.6, PHP 5)

fbsql_stop_db — Zatrzymuje bazę danych na serwerze lokalnym lub zdalnym

Opis

bool fbsql_stop_db ( string $nazwa_bazy_danych [, resource $identyfikator_połączenia ] )

Zatrzymuje bazę danych na serwerze lokalnym lub zdalnym.

Parametry

nazwa_bazy_danych

Nazwa bazy danych.

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fbsql_db_status() - Zwraca status dla podanej bazy danych
  • fbsql_start_db() - Uruchamia bazę danych na serwerze lokalnym lub zdalnym

fbsql_start_db
fbsql_table_name
Funkcje FrontBase


Get table name of field

fbsql_stop_db
fbsql_tablename
Funkcje FrontBase
PHP Manual

fbsql_table_name

(PHP 4 >= 4.2.0, PHP 5)

fbsql_table_name — Get table name of field

Opis

string fbsql_table_name ( resource $result , int $index )

fbsql_table_name() gets the name of the current table in the given result set.

The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

Parametry

result

A result pointer returned by fbsql_list_tables().

index

Integer index for the current table.

Zwracane wartości

Returns the name of the table, as a string.

Przykłady

Przykład #1 fbsql_table_name() example

<?php
fbsql_connect("localhost", "_SYSTEM", "");
$result = fbsql_list_tables("wisconsin");
$i = 0;
while ($i < fbsql_num_rows($result)) {
    $tb_names[$i] = fbsql_table_name($result, $i);
    echo $tb_names[$i] . "<br />";
    $i++;
}
?>

fbsql_stop_db
fbsql_tablename
Funkcje FrontBase


Alias dla fbsql_table_name

fbsql_table_name
fbsql_username
Funkcje FrontBase
PHP Manual

fbsql_tablename

(PHP 4 >= 4.2.0, PHP 5)

fbsql_tablename — Alias dla fbsql_table_name()

Opis

Ta funkcja jest aliasem dla: fbsql_table_name().

fbsql_table_name
fbsql_username
Funkcje FrontBase


Zraca lub ustawia nazwę użytkownika używaną w połączeniu

fbsql_tablename
fbsql_warnings
Funkcje FrontBase
PHP Manual

fbsql_username

(PHP 4 >= 4.0.6, PHP 5)

fbsql_username — Zraca lub ustawia nazwę użytkownika używaną w połączeniu

Opis

string fbsql_nazwa_użytkownika ( resource $identyfikator_połączenia [, string $nazwa_użytkownika ] )

Zraca lub ustawia nazwę użytkownika używaną w połączeniu.

Parametry

link_identifier

Identyfikator połączenia FrontBase zwrócony przez fbsql_connect() lub fbsql_pconnect().

Link jest opcjonalny i jeśli nie zostanie podany, to funkcja spróbuje znaleźć otwarte połączenie do serwera FrontBase. Jeśli funkcja nie znajdzie otwartego połączenia, to spróbuje utworzyć je tak jakby fbsql_connect() była wywołana bez argumentów.

nazwa_użytkownika

Jeśli zostanie podana, wówczas będzie nowym użytkownikiem w połączeniu.

Zwracane wartości

Zwraca jako string nazwę aktualnego użytkownka używanego w połączeniu.

Zobacz też:

  • fbsql_password() - Zwraca lub ustawia hasło użytkownika używane w połączeniu
  • fbsql_hostname() - Zraca lub ustawia nazwę hosta używaną w połączeniu

fbsql_tablename
fbsql_warnings
Funkcje FrontBase


Enable or disable FrontBase warnings

fbsql_username
IBM DB2
Funkcje FrontBase
PHP Manual

fbsql_warnings

(PHP 4 >= 4.0.6, PHP 5)

fbsql_warnings — Enable or disable FrontBase warnings

Opis

bool fbsql_warnings ([ bool $OnOff ] )

Enables or disables FrontBase warnings.

Parametry

OnOff

Whether to enable warnings or no.

Zwracane wartości

Returns TRUE if warnings is turned on, FALSE otherwise.

Zobacz też:

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_error() - Returns the error message from previous operation

fbsql_username
IBM DB2
Funkcje FrontBase


IBM DB2, Cloudscape and Apache Derby

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • IBM DB2 Funkcje
    • db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
    • db2_bind_param — Binds a PHP variable to an SQL statement parameter
    • db2_client_info — Returns an object with properties that describe the DB2 database client
    • db2_close — Closes a database connection
    • db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
    • db2_columns — Returns a result set listing the columns and associated metadata for a table
    • db2_commit — Commits a transaction
    • db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
    • db2_conn_errormsg — Returns the last connection error message and SQLCODE value
    • db2_connect — Returns a connection to a database
    • db2_cursor_type — Returns the cursor type used by a statement resource
    • db2_escape_string — Used to escape certain characters
    • db2_exec — Executes an SQL statement directly
    • db2_execute — Executes a prepared SQL statement
    • db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
    • db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
    • db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
    • db2_fetch_object — Returns an object with properties representing columns in the fetched row
    • db2_fetch_row — Sets the result set pointer to the next row or requested row
    • db2_field_display_size — Returns the maximum number of bytes required to display a column
    • db2_field_name — Returns the name of the column in the result set
    • db2_field_num — Returns the position of the named column in a result set
    • db2_field_precision — Returns the precision of the indicated column in a result set
    • db2_field_scale — Returns the scale of the indicated column in a result set
    • db2_field_type — Returns the data type of the indicated column in a result set
    • db2_field_width — Returns the width of the current value of the indicated column in a result set
    • db2_foreign_keys — Returns a result set listing the foreign keys for a table
    • db2_free_result — Frees resources associated with a result set
    • db2_free_stmt — Frees resources associated with the indicated statement resource
    • db2_get_option — Retrieves an option value for a statement resource or a connection resource
    • db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
    • db2_lob_read — Gets a user defined size of LOB files with each invocation
    • db2_next_result — Requests the next result set from a stored procedure
    • db2_num_fields — Returns the number of fields contained in a result set
    • db2_num_rows — Returns the number of rows affected by an SQL statement
    • db2_pclose — Closes a persistent database connection
    • db2_pconnect — Returns a persistent connection to a database
    • db2_prepare — Prepares an SQL statement to be executed
    • db2_primary_keys — Returns a result set listing primary keys for a table
    • db2_procedure_columns — Returns a result set listing stored procedure parameters
    • db2_procedures — Returns a result set listing the stored procedures registered in a database
    • db2_result — Returns a single column from a row in the result set
    • db2_rollback — Rolls back a transaction
    • db2_server_info — Returns an object with properties that describe the DB2 database server
    • db2_set_option — Set options for connection or statement resources
    • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
    • db2_statistics — Returns a result set listing the index and statistics for a table
    • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
    • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
    • db2_tables — Returns a result set listing the tables and associated metadata in a database
fbsql_warnings
Wstęp
Rozszerzenia producentów baz danych


Wstęp

These functions enable you to access IBM DB2 Universal Database, IBM Cloudscape, and Apache Derby databases using the DB2 Call Level Interface (DB2 CLI).

IBM DB2
Instalacja/Konfiguracja
IBM DB2


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
IBM DB2


Wymagania

To connect to IBM DB2 Universal Database for Linux, UNIX, and Windows, or IBM Cloudscape, or Apache Derby, you must install an IBM DB2 Universal Database client on the same computer on which you are running PHP. The extension has been developed and tested with DB2 Version 8.2.

To connect to IBM DB2 Universal Database for z/OS or iSeries, you also require IBM DB2 Connect or the equivalent DRDA gateway software.

Requirements on Linux or Unix

The user invoking the PHP executable or SAPI must specify the DB2 instance before accessing these functions. You can set the name of the DB2 instance in php.ini using the ibm_db2.instance_name configuration option, or you can source the DB2 instance profile before invoking the PHP executable.

If you created a DB2 instance named db2inst1 in /home/db2inst1/, for example, you can add the following line to php.ini:

ibm_db2.instance_name=db2inst1
If you do not set this option in php.ini, you must issue the following command to modify your environment variables to enable access to DB2:
bash$ source /home/db2inst1/sqllib/db2profile
To enable your PHP-enabled Web server to access these functions, you must either set the ibm_db2.instance_name configuration option in php.ini, or source the DB2 instance environment in your Web server start script (typically /etc/init.d/httpd or /etc/init.d/apache).

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on your system. DB2 does not install these by default, so you may have to return to your DB2 installer and add this option. The header files are included with the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database » support site.

If you add the DB2 application development header files and libraries to a Linux or Unix operating system on which DB2 was already installed, you must issue the command db2iupdt -e to update the symbolic links to the header files and libraries in your DB2 instances.

ibm_db2 is a » PECL extension, so follow the instructions in Installation of PECL extensions to install the ibm_db2 extension for PHP. Issue the configure command to point to the location of your DB2 header files and libraries as follows:

bash$ ./configure --with-IBM_DB2=/path/to/DB2
The configure command defaults to /opt/IBM/db2/V8.1.

Informacja: Note for IIS users

If you are using the ibm_db2 driver with Microsoft Internet Information Server (IIS) you may have to do the following:

  • Install DB2 with extended operating system security.
  • Add the PHP binary path to the PATH system environment variable (default C:\php\).
  • Create another system environment variable equal to the path where the PHP.INI file is located (eg: PHPRC = C:\php\).
  • Add the IUSR_COMPUTERNAME to the DB2USERS group.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

ibm_db2 Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Changelog
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

ibm_db2.binmode integer

This option controls the mode used for converting to and from binary data in the PHP application.

  • 1 (DB2_BINARY)

  • 2 (DB2_CONVERT)

  • 3 (DB2_PASSTHRU)

ibm_db2.i5_all_pconnect integer

This option overrides i5 db2_connect() full open and close in the PHP application. When ibm_db2.i5_all_pconnect = 1, all db2 connections become persistent (db2_pconnect()). On i5/OS, db2_pconnect() performs dramatically better with lower machine stress over db2_connect(). This is a convenience override of db2_connect() to evoke db2_pconnect() without PHP source code changes.

  • 0 db2_connect() default full open and close

  • 1 db2_connect() override to db2_pconnect() for persistent connection only

ibm_db2.i5_allow_commit integer

This option controls the commit mode used for i5 schema collections in the PHP application.

  • 0 no commit (see i5_commit for override)

  • 1 allow commit (see i5_commit for override)

ibm_db2.i5_dbcs_alloc integer

This option controls the internal ibm_db2 allocation scheme for large DBCS column buffers.

  • 0 no expanded allocations (see i5_dbcs_alloc for override)

  • 1 use expanded allocations (see i5_dbcs_alloc for override)

ibm_db2.instance_name string

On Linux and UNIX operating systems, this option defines the name of the instance to use for cataloged database connections. If this option is set, its value overrides the DB2INSTANCE environment variable setting.

This option is ignored on Windows operating systems.

ibm_db2.i5_ignore_userid integer

This option overrides i5 db2_(p)connect userid and password in the PHP application. When ibm_db2.i5_ignore_userid = 1, all db2 (p)connections become null userid and null password. Therefore Apache jobs connect with the current profile (NOBODY). Use of this override is only for simple DB2 based websites that never require profile switching and therefore can avoid all overhead of server mode additional QSQSRVR jobs. This is a convenience override of db2_(p)connect to set the userid and password values to null without PHP source code changes. This override can be used in combination with ibm_db2.i5_all_pconnect = 1.

  • 0 db2_(p)connect with specified userid and password

  • 1 db2_(p)connect override connect with null userid and null password

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

The ibm_db2 extension returns connection resources, statement resources, and result set resources.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

DB2_BINARY (integer)
Specifies that binary data shall be returned as is. This is the default mode.
DB2_CONVERT (integer)
Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.
DB2_PASSTHRU (integer)
Specifies that binary data shall be converted to a NULL value.
DB2_SCROLLABLE (integer)
Specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.
DB2_FORWARD_ONLY (integer)
Specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.
DB2_PARAM_IN (integer)
Specifies the PHP variable should be bound as an IN parameter for a stored procedure.
DB2_PARAM_OUT (integer)
Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.
DB2_PARAM_INOUT (integer)
Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.
DB2_PARAM_FILE (integer)
Specifies that the column should be bound directly to a file for input.
DB2_AUTOCOMMIT_ON (integer)
Specifies that autocommit should be turned on.
DB2_AUTOCOMMIT_OFF (integer)
Specifies that autocommit should be turned off.
DB2_DOUBLE (integer)
Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.
DB2_LONG (integer)
Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.
DB2_CHAR (integer)
Specifies that the variable should be bound as a CHAR or VARCHAR data type.
DB2_CASE_NATURAL (integer)
Specifies that column names will be returned in their natural case.
DB2_CASE_LOWER (integer)
Specifies that column names will be returned in lower case.
DB2_CASE_UPPER (integer)
Specifies that column names will be returned in upper case.
DB2_DEFERRED_PREPARE_ON (integer)
Specifies that deferred prepare should be turned on for the specified statement resource.
DB2_DEFERRED_PREPARE_OFF (integer)
Specifies that deferred prepare should be turned off for the specified statement resource.
Typy zasobów
IBM DB2 Funkcje
IBM DB2


IBM DB2 Funkcje

Spis treści

  • db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
  • db2_bind_param — Binds a PHP variable to an SQL statement parameter
  • db2_client_info — Returns an object with properties that describe the DB2 database client
  • db2_close — Closes a database connection
  • db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
  • db2_columns — Returns a result set listing the columns and associated metadata for a table
  • db2_commit — Commits a transaction
  • db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg — Returns the last connection error message and SQLCODE value
  • db2_connect — Returns a connection to a database
  • db2_cursor_type — Returns the cursor type used by a statement resource
  • db2_escape_string — Used to escape certain characters
  • db2_exec — Executes an SQL statement directly
  • db2_execute — Executes a prepared SQL statement
  • db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object — Returns an object with properties representing columns in the fetched row
  • db2_fetch_row — Sets the result set pointer to the next row or requested row
  • db2_field_display_size — Returns the maximum number of bytes required to display a column
  • db2_field_name — Returns the name of the column in the result set
  • db2_field_num — Returns the position of the named column in a result set
  • db2_field_precision — Returns the precision of the indicated column in a result set
  • db2_field_scale — Returns the scale of the indicated column in a result set
  • db2_field_type — Returns the data type of the indicated column in a result set
  • db2_field_width — Returns the width of the current value of the indicated column in a result set
  • db2_foreign_keys — Returns a result set listing the foreign keys for a table
  • db2_free_result — Frees resources associated with a result set
  • db2_free_stmt — Frees resources associated with the indicated statement resource
  • db2_get_option — Retrieves an option value for a statement resource or a connection resource
  • db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
  • db2_lob_read — Gets a user defined size of LOB files with each invocation
  • db2_next_result — Requests the next result set from a stored procedure
  • db2_num_fields — Returns the number of fields contained in a result set
  • db2_num_rows — Returns the number of rows affected by an SQL statement
  • db2_pclose — Closes a persistent database connection
  • db2_pconnect — Returns a persistent connection to a database
  • db2_prepare — Prepares an SQL statement to be executed
  • db2_primary_keys — Returns a result set listing primary keys for a table
  • db2_procedure_columns — Returns a result set listing stored procedure parameters
  • db2_procedures — Returns a result set listing the stored procedures registered in a database
  • db2_result — Returns a single column from a row in the result set
  • db2_rollback — Rolls back a transaction
  • db2_server_info — Returns an object with properties that describe the DB2 database server
  • db2_set_option — Set options for connection or statement resources
  • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
  • db2_statistics — Returns a result set listing the index and statistics for a table
  • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
  • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
  • db2_tables — Returns a result set listing the tables and associated metadata in a database
Stałe predefiniowane
db2_autocommit
IBM DB2


Returns or sets the AUTOCOMMIT state for a database connection

IBM DB2 Funkcje
db2_bind_param
IBM DB2 Funkcje
PHP Manual

db2_autocommit

(PECL ibm_db2 >= 1.0.0)

db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection

Opis

mixed db2_autocommit ( resource $connection [, bool $value ] )

Sets or gets the AUTOCOMMIT behavior of the specified connection resource.

Parametry

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

value

One of the following constants:

DB2_AUTOCOMMIT_OFF

Turns AUTOCOMMIT off.

DB2_AUTOCOMMIT_ON

Turns AUTOCOMMIT on.

Zwracane wartości

When db2_autocommit() receives only the connection parameter, it returns the current state of AUTOCOMMIT for the requested connection as an integer value. A value of 0 indicates that AUTOCOMMIT is off, while a value of 1 indicates that AUTOCOMMIT is on.

When db2_autocommit() receives both the connection parameter and autocommit parameter, it attempts to set the AUTOCOMMIT state of the requested connection to the corresponding state. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Retrieving the AUTOCOMMIT value for a connection

In the following example, a connection which has been created with AUTOCOMMIT turned off is tested with the db2_autocommit() function.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
$ac = db2_autocommit($conn);
if ($ac == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

Powyższy przykład wyświetli:

0 -- AUTOCOMMIT is off.

Przykład #2 Setting the AUTOCOMMIT value for a connection

In the following example, a connection which was initially created with AUTOCOMMIT turned off has its behavior changed to turn AUTOCOMMIT on.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);

// Turn AUTOCOMMIT on
$rc = db2_autocommit($conn, DB2_AUTOCOMMIT_ON);
if ($rc) {
    print "Turning AUTOCOMMIT on succeeded.\n";
}

// Check AUTOCOMMIT state
$ac = db2_autocommit($conn);
if ($ac == 0) {
    print "$ac -- AUTOCOMMIT is off.";
} else {
    print "$ac -- AUTOCOMMIT is on.";
}
?>

Powyższy przykład wyświetli:

Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.

Zobacz też:

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database

IBM DB2 Funkcje
db2_bind_param
IBM DB2 Funkcje


Binds a PHP variable to an SQL statement parameter

db2_autocommit
db2_client_info
IBM DB2 Funkcje
PHP Manual

db2_bind_param

(PECL ibm_db2 >= 1.0.0)

db2_bind_param — Binds a PHP variable to an SQL statement parameter

Opis

bool db2_bind_param ( resource $stmt , int $parameter-number , string $variable-name [, int $parameter-type [, int $data-type = 0 [, int $precision = -1 [, int $scale = 0 ]]]] )

Binds a PHP variable to an SQL statement parameter in a statement resource returned by db2_prepare(). This function gives you more control over the parameter type, data type, precision, and scale for the parameter than simply passing the variable as part of the optional input array to db2_execute().

Parametry

stmt

A prepared statement returned from db2_prepare().

parameter-number

Specifies the 1-indexed position of the parameter in the prepared statement.

variable-name

A string specifying the name of the PHP variable to bind to the parameter specified by parameter-number.

parameter-type

A constant specifying whether the PHP variable should be bound to the SQL parameter as an input parameter (DB2_PARAM_IN), an output parameter (DB2_PARAM_OUT), or as a parameter that accepts input and returns output (DB2_PARAM_INOUT). To avoid memory overhead, you can also specify DB2_PARAM_FILE to bind the PHP variable to the name of a file that contains large object (BLOB, CLOB, or DBCLOB) data.

data-type

A constant specifying the SQL data type that the PHP variable should be bound as: one of DB2_BINARY, DB2_CHAR, DB2_DOUBLE, or DB2_LONG .

precision

Specifies the precision with which the variable should be bound to the database. This parameter can also be used for retrieving XML output values from stored procedures. A non-negative value specifies the maximum size of the XML data that will be retrieved from the database. If this parameter is not used, a default of 1MB will be assumed for retrieving the XML output value from the stored procedure.

scale

Specifies the scale with which the variable should be bound to the database.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Binding PHP variables to a prepared statement

The SQL statement in the following example uses two input parameters in the WHERE clause. We call db2_bind_param() to bind two PHP variables to the corresponding SQL parameters. Notice that the PHP variables do not have to be declared or assigned before the call to db2_bind_param(); in the example, $lower_limit is assigned a value before the call to db2_bind_param(), but $upper_limit is assigned a value after the call to db2_bind_param(). The variables must be bound and, for parameters that accept input, must have any value assigned, before calling db2_execute().

<?php

$sql = 'SELECT name, breed, weight FROM animals
    WHERE weight > ? AND weight < ?';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

// We can declare the variable before calling db2_bind_param()
$lower_limit = 1;

db2_bind_param($stmt, 1, "lower_limit", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "upper_limit", DB2_PARAM_IN);

// We can also declare the variable after calling db2_bind_param()
$upper_limit = 15.0;

if (db2_execute($stmt)) {
    while ($row = db2_fetch_array($stmt)) {
        print "{$row[0]}, {$row[1]}, {$row[2]}\n";
    }
}
?>

Powyższy przykład wyświetli:

Pook, cat, 3.2
Rickety Ride, goat, 9.7
Peaches, dog, 12.3

Przykład #2 Calling stored procedures with IN and OUT parameters

The stored procedure match_animal in the following example accepts three different parameters:

  1. an input (IN) parameter that accepts the name of the first animal as input

  2. an input-output (INOUT) parameter that accepts the name of the second animal as input and returns the string TRUE if an animal in the database matches that name

  3. an output (OUT) parameter that returns the sum of the weight of the two identified animals

In addition, the stored procedure returns a result set consisting of the animals listed in alphabetic order starting at the animal corresponding to the input value of the first parameter and ending at the animal corresponding to the input value of the second parameter.

<?php

$sql = 'CALL match_animal(?, ?, ?)';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

$name = "Peaches";
$second_name = "Rickety Ride";
$weight = 0;

db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "second_name", DB2_PARAM_INOUT);
db2_bind_param($stmt, 3, "weight", DB2_PARAM_OUT);

print "Values of bound parameters _before_ CALL:\n";
print "  1: {$name} 2: {$second_name} 3: {$weight}\n\n";

if (db2_execute($stmt)) {
    print "Values of bound parameters _after_ CALL:\n";
    print "  1: {$name} 2: {$second_name} 3: {$weight}\n\n";

    print "Results:\n";
    while ($row = db2_fetch_array($stmt)) {
        print "  {$row[0]}, {$row[1]}, {$row[2]}\n";
    }
}
?>

Powyższy przykład wyświetli:

Values of bound parameters _before_ CALL:
  1: Peaches 2: Rickety Ride 3: 0

Values of bound parameters _after_ CALL:
  1: Peaches 2: TRUE 3: 22

Results:
  Peaches, dog, 12.3
  Pook, cat, 3.2
  Rickety Ride, goat, 9.7

Przykład #3 Inserting a binary large object (BLOB) directly from a file

The data for large objects are typically stored in files, such as XML documents or audio files. Rather than reading an entire file into a PHP variable, and then binding that PHP variable into an SQL statement, you can avoid some memory overhead by binding the file directly to the input parameter of your SQL statement. The following example demonstrates how to bind a file directly into a BLOB column.

<?php
$stmt = db2_prepare($conn, "INSERT INTO animal_pictures(picture) VALUES (?)");

$picture = "/opt/albums/spook/grooming.jpg";
$rc = db2_bind_param($stmt, 1, "picture", DB2_PARAM_FILE);
$rc = db2_execute($stmt);
?>

Zobacz też:

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

db2_autocommit
db2_client_info
IBM DB2 Funkcje


Returns an object with properties that describe the DB2 database client

db2_bind_param
db2_close
IBM DB2 Funkcje
PHP Manual

db2_client_info

(PECL ibm_db2 >= 1.1.1)

db2_client_info — Returns an object with properties that describe the DB2 database client

Opis

object db2_client_info ( resource $connection )

This function returns an object with read-only properties that return information about the DB2 database client. The following table lists the DB2 client properties:

DB2 client properties
Property name | Return type | Description
APPL_CODEPAGE | int | The application code page.
CONN_CODEPAGE | int | The code page for the current connection.
DATA_SOURCE_NAME | string | The data source name (DSN) used to create the current connection to the database.
DRIVER_NAME | string | The name of the library that implements the DB2 Call Level Interface (CLI) specification.
DRIVER_ODBC_VER | string | The version of ODBC that the DB2 client supports. This returns a string "MM.mm" where MM is the major version and mm is the minor version. The DB2 client always returns "03.51".
DRIVER_VER | string | The version of the client, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
ODBC_SQL_CONFORMANCE string

The level of ODBC SQL grammar supported by the client:

MINIMUM

Supports the minimum ODBC SQL grammar.

CORE

Supports the core ODBC SQL grammar.

EXTENDED

Supports extended ODBC SQL grammar.

ODBC_VER | string | The version of ODBC that the ODBC driver manager supports. This returns a string "MM.mm.rrrr" where MM is the major version, mm is the minor version, and rrrr is the release. The DB2 client always returns "03.01.0000".

Parametry

connection

Specifies an active DB2 client connection.

Zwracane wartości

Returns an object on a successful call. Returns FALSE on failure.

Przykłady

Przykład #1 A db2_client_info() example

To retrieve information about the client, you must pass a valid database connection resource to db2_client_info().

<?php
$conn = db2_connect( 'SAMPLE', 'db2inst1', 'ibmdb2' );
$client = db2_client_info( $conn );

if ($client) {
    echo "DRIVER_NAME: ";           var_dump( $client->DRIVER_NAME );
    echo "DRIVER_VER: ";            var_dump( $client->DRIVER_VER );
    echo "DATA_SOURCE_NAME: ";      var_dump( $client->DATA_SOURCE_NAME );
    echo "DRIVER_ODBC_VER: ";       var_dump( $client->DRIVER_ODBC_VER );
    echo "ODBC_VER: ";              var_dump( $client->ODBC_VER );
    echo "ODBC_SQL_CONFORMANCE: ";  var_dump( $client->ODBC_SQL_CONFORMANCE );
    echo "APPL_CODEPAGE: ";         var_dump( $client->APPL_CODEPAGE );
    echo "CONN_CODEPAGE: ";         var_dump( $client->CONN_CODEPAGE );
}
else {
    echo "Error retrieving client information.
     Perhaps your database connection was invalid.";
}
db2_close($conn);

?>

Powyższy przykład wyświetli:

DRIVER_NAME: string(8) "libdb2.a"
DRIVER_VER: string(10) "08.02.0001"
DATA_SOURCE_NAME: string(6) "SAMPLE"
DRIVER_ODBC_VER: string(5) "03.51"
ODBC_VER: string(10) "03.01.0000"
ODBC_SQL_CONFORMANCE: string(8) "EXTENDED"
APPL_CODEPAGE: int(819)
CONN_CODEPAGE: int(819)

Zobacz też:

  • db2_server_info() - Returns an object with properties that describe the DB2 database server

db2_bind_param
db2_close
IBM DB2 Funkcje


Closes a database connection

db2_client_info
db2_column_privileges
IBM DB2 Funkcje
PHP Manual

db2_close

(PECL ibm_db2 >= 1.0.0)

db2_close — Closes a database connection

Opis

bool db2_close ( resource $connection )

This function closes a DB2 client connection created with db2_connect() and returns the corresponding resources to the database server.

If you attempt to close a persistent DB2 client connection created with db2_pconnect(), the close request is ignored and the persistent DB2 client connection remains available for the next caller.

Parametry

connection

Specifies an active DB2 client connection.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Closing a connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2, Cloudscape, or Apache Derby database.

<?php
$conn = db2_connect('SAMPLE', 'db2inst1', 'ibmdb2');
$rc = db2_close($conn);
if ($rc) {
    echo "Connection was successfully closed.";
}
?>

Powyższy przykład wyświetli:

Connection was successfully closed.

Zobacz też:

  • db2_connect() - Returns a connection to a database
  • db2_pclose() - Closes a persistent database connection
  • db2_pconnect() - Returns a persistent connection to a database

db2_client_info
db2_column_privileges
IBM DB2 Funkcje


Returns a result set listing the columns and associated privileges for a table

db2_close
db2_columns
IBM DB2 Funkcje
PHP Manual

db2_column_privileges

(PECL ibm_db2 >= 1.0.0)

db2_column_privileges — Returns a result set listing the columns and associated privileges for a table

Opis

resource db2_column_privileges ( resource $connection [, string $qualifier [, string $schema [, string $table-name [, string $column-name ]]]] )

Returns a result set listing the columns and associated privileges for a table.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. To match all schemas, pass NULL or an empty string.

table-name

The name of the table or view. To match all tables in the database, pass NULL or an empty string.

column-name

The name of the column. To match all columns in the table, pass NULL or an empty string.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the column privileges for columns matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege for the column.
IS_GRANTABLE | Whether the GRANTEE is permitted to grant this privilege to other users.

Zobacz też:

  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_close
db2_columns
IBM DB2 Funkcje


Returns a result set listing the columns and associated metadata for a table

db2_column_privileges
db2_commit
IBM DB2 Funkcje
PHP Manual

db2_columns

(PECL ibm_db2 >= 1.0.0)

db2_columns — Returns a result set listing the columns and associated metadata for a table

Opis

resource db2_columns ( resource $connection [, string $qualifier [, string $schema [, string $table-name [, string $column-name ]]]] )

Returns a result set listing the columns and associated metadata for a table.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. To match all schemas, pass '%'.

table-name

The name of the table or view. To match all tables in the database, pass NULL or an empty string.

column-name

The name of the column. To match all columns in the table, pass NULL or an empty string.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the columns matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
DATA_TYPE | The SQL data type for the column represented as an integer value.
TYPE_NAME | A string representing the data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the column is nullable or not.
REMARKS | Description of the column.
COLUMN_DEF | Default value for the column.
SQL_DATA_TYPE | An integer value representing the size of the column.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type column, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the column in the table.
IS_NULLABLE | A string value where 'YES' means that the column is nullable and 'NO' means that the column is not nullable.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_column_privileges
db2_commit
IBM DB2 Funkcje


Commits a transaction

db2_columns
db2_conn_error
IBM DB2 Funkcje
PHP Manual

db2_commit

(PECL ibm_db2 >= 1.0.0)

db2_commit — Commits a transaction

Opis

bool db2_commit ( resource $connection )

Commits an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_commit() is not necessary unless AUTOCOMMIT has been turned off for the connection resource.

Parametry

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_rollback() - Rolls back a transaction

db2_columns
db2_conn_error
IBM DB2 Funkcje


Returns a string containing the SQLSTATE returned by the last connection attempt

db2_commit
db2_conn_errormsg
IBM DB2 Funkcje
PHP Manual

db2_conn_error

(PECL ibm_db2 >= 1.0.0)

db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt

Opis

string db2_conn_error ([ resource $connection ] )

db2_conn_error() returns an SQLSTATE value representing the reason the last attempt to connect to a database failed. As db2_connect() returns FALSE in the event of a failed connection attempt, you do not pass any parameters to db2_conn_error() to retrieve the SQLSTATE value.

If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the SQLSTATE value for a specific connection.

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_conn_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

Parametry

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Zwracane wartości

Returns the SQLSTATE value resulting from a failed connection attempt. Returns an empty string if there is no error associated with the last connection attempt.

Przykłady

Przykład #1 Retrieving an SQLSTATE value for a failed connection attempt

The following example demonstrates how to return an SQLSTATE value after deliberately passing invalid parameters to db2_connect().

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print "SQLSTATE value: " . db2_conn_error();
}
?>

Powyższy przykład wyświetli:

SQLSTATE value: 08001

Zobacz też:

  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_connect() - Returns a connection to a database
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

db2_commit
db2_conn_errormsg
IBM DB2 Funkcje


Returns the last connection error message and SQLCODE value

db2_conn_error
db2_connect
IBM DB2 Funkcje
PHP Manual

db2_conn_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_conn_errormsg — Returns the last connection error message and SQLCODE value

Opis

string db2_conn_errormsg ([ resource $connection ] )

db2_conn_errormsg() returns an error message and SQLCODE value representing the reason the last database connection attempt failed. As db2_connect() returns FALSE in the event of a failed connection attempt, do not pass any parameters to db2_conn_errormsg() to retrieve the associated error message and SQLCODE value.

If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the associated error message and SQLCODE value for a specific connection.

Parametry

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

Zwracane wartości

Returns a string containing the error message and SQLCODE value resulting from a failed connection attempt. If there is no error associated with the last connection attempt, db2_conn_errormsg() returns an empty string.

Przykłady

Przykład #1 Retrieving the error message returned by a failed connection attempt

The following example demonstrates how to return an error message and SQLCODE value after deliberately passing invalid parameters to db2_connect().

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
    print db2_conn_errormsg();
}
?>

Powyższy przykład wyświetli:

[IBM][CLI Driver] SQL1013N  The database alias name
or database name "BADNAME" could not be found.  SQLSTATE=42705
 SQLCODE=-1013

Zobacz też:

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_connect() - Returns a connection to a database
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

db2_conn_error
db2_connect
IBM DB2 Funkcje


Returns a connection to a database

db2_conn_errormsg
db2_cursor_type
IBM DB2 Funkcje
PHP Manual

db2_connect

(PECL ibm_db2 >= 1.0.0)

db2_connect — Returns a connection to a database

Opis

resource db2_connect ( string $database , string $username , string $password [, array $options ] )

Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

Parametry

database

For a cataloged connection to a database, database represents the database alias in the DB2 client catalog.

For an uncataloged connection to a database, database represents a complete connection string in the following format:

DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;
where the parameters represent the following values:
database

The name of the database.

hostname

The hostname or IP address of the database server.

port

The TCP/IP port on which the database is listening for requests.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

username

The username with which you are connecting to the database.

For uncataloged connections, you must pass a NULL value or empty string.

password

The password with which you are connecting to the database.

For uncataloged connections, you must pass a NULL value or empty string.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.

Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.

DB2_ATTR_CASE

Passing the DB2_CASE_NATURAL value specifies that column names are returned in natural case.

Passing the DB2_CASE_LOWER value specifies that column names are returned in lower case.

Passing the DB2_CASE_UPPER value specifies that column names are returned in upper case.

CURSOR

Passing the DB2_FORWARD_ONLY value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.

Passing the DB2_SCROLLABLE value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

The following new option is available in ibm_db2 version 1.7.0 and later.

trustedcontext

Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option().

This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection.

To catalog the database, use following commands:

db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
db2 "update dbm cfg using svcename <SERVICENAME>"
db2set DB2COMM=TCPIP

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

i5_lib

A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.

i5_naming

DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job.

DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.

i5_commit

The i5_commit attribute should be set before the db2_connect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_connect() for the connection handle.

Informacja:

The php.ini setting ibm_db2.i5_allow_commit==0 or DB2_I5_TXN_NO_COMMIT is the default, but may be overridden with the i5_commit option.

DB2_I5_TXN_NO_COMMIT - Commitment control is not used.

DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads, nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_READ_COMMITTED - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_REPEATABLE_READ - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible.

DB2_I5_TXN_SERIALIZABLE - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible

i5_query_optimize

DB2_FIRST_IO All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause.

DB2_ALL_IO All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.

i5_dbcs_alloc

DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation scheme for DBCS translation column size growth.

DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X allocation scheme for DBCS translation column size growth.

Note: php.ini setting ibm_db2.i5_dbcs_alloc==0 or DB2_I5_DBCS_ALLOC_OFF is the default, but may be overridden with the i5_dbcs_alloc option.

i5_date_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default.

DB2_I5_FMT_USA - The United States date format mm/dd/yyyy is used.

DB2_I5_FMT_EUR - The European date format dd.mm.yyyy is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard date format yyyy-mm-dd is used.

DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.

DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.

DB2_I5_FMT_YMD - The date format yy/mm/dd is used.

DB2_I5_FMT_JUL - The Julian date format yy/ddd is used.

DB2_I5_FMT_JOB - The job default is used.

i5_date_sep

DB2_I5_SEP_SLASH - A slash ( / ) is used as the date separator. This is the default.

DB2_I5_SEP_DASH - A dash ( - ) is used as the date separator.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the date separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the date separator.

DB2_I5_SEP_BLANK - A blank is used as the date separator.

DB2_I5_SEP_JOB - The job default is used

i5_time_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default.

DB2_I5_FMT_USA - The United States time format hh:mmxx is used, where xx is AM or PM.

DB2_I5_FMT_EUR - The European time format hh.mm.ss is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard time format hh:mm:ss is used.

DB2_I5_FMT_HMS - The hh:mm:ss format is used.

i5_time_sep

DB2_I5_SEP_COLON - A colon ( : ) is used as the time separator. This is the default.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the time separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the time separator.

DB2_I5_SEP_BLANK - A blank is used as the time separator.

DB2_I5_SEP_JOB - The job default is used.

i5_decimal_sep

DB2_I5_SEP_PERIOD - A period ( . ) is used as the decimal separator. This is the default.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the decimal separator.

DB2_I5_SEP_JOB - The job default is used.

The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

i5_libl

A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

Informacja:

i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

Zwracane wartości

Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns FALSE.

Przykłady

Przykład #1 Creating a cataloged connection

Cataloged connections require you to have previously cataloged the target database through the DB2 Command Line Processor (CLP) or DB2 Configuration Assistant.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$conn = db2_connect($database, $user, $password);

if ($conn) {
    echo "Connection succeeded.";
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

Powyższy przykład wyświetli:

Connection succeeded.

Przykład #2 Creating an uncataloged connection

An uncataloged connection enables you to dynamically connect to a database.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$hostname = 'localhost';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
  "HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

if ($conn) {
    echo "Connection succeeded.";
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

Powyższy przykład wyświetli:

Connection succeeded.

Przykład #3 Creating a connection with autocommit off by default

Passing an array of options to db2_connect() enables you to modify the default behavior of the connection handle.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);

$conn = db2_connect($database, $user, $password, $options);

if ($conn) {
    echo "Connection succeeded.\n";
    if (db2_autocommit($conn)) {
         echo "Autocommit is on.\n";
    }
    else {
         echo "Autocommit is off.\n";
    }
    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

Powyższy przykład wyświetli:

Connection succeeded.
Autocommit is off.

Przykład #4 i5/OS best performance

To achieve best performance for your i5/OS ibm_db2 1.5.1 PHP application use the default host, userid, and password for your db2_connect().

<?php
  $library = "ADC";
  $i5 = db2_connect("", "", "", array("i5_lib"=>"qsys2"));
  $result = db2_exec($i5,
       "select * from systables where table_schema = '$library'");
  while ($row = db2_fetch_both($result)) {
     echo $row['TABLE_NAME']."</br>";
  }
  db2_close($i5);
?>

Powyższy przykład wyświetli:

ANIMALS
NAMES
PICTURES

Przykład #5 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
  PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_connect($dsn, "", "", $options);
if($tc_conn) {
    echo "Explicit trusted connection succeeded.\n";

    if(db2_get_option($tc_conn, "trustedcontext")) {
        $userBefore = db2_get_option($tc_conn, "trusted_user");

        //Do some work as user 1.

        //Switching to trusted user.
        $parameters = array("trusted_user" => $tc_user,
          "trusted_password" => $tcuser_pass);
        $res = db2_set_option ($tc_conn, $parameters, 1);

        $userAfter = db2_get_option($tc_conn, "trusted_user");
        //Do more work as trusted user.

        if($userBefore != $userAfter) {
            echo "User has been switched." . "\n";
        }
    }

    db2_close($tc_conn);
}
else {
    echo "Explicit trusted connection failed.\n";
}
?>

Powyższy przykład wyświetli:

Explicit trusted connection succeeded.
User has been switched.

Zobacz też:

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

db2_conn_errormsg
db2_cursor_type
IBM DB2 Funkcje


Returns the cursor type used by a statement resource

db2_connect
db2_escape_string
IBM DB2 Funkcje
PHP Manual

db2_cursor_type

(PECL ibm_db2 >= 1.0.0)

db2_cursor_type — Returns the cursor type used by a statement resource

Opis

int db2_cursor_type ( resource $stmt )

Returns the cursor type used by a statement resource. Use this to determine if you are working with a forward-only cursor or scrollable cursor.

Parametry

stmt

A valid statement resource.

Zwracane wartości

Returns either DB2_FORWARD_ONLY if the statement resource uses a forward-only cursor or DB2_SCROLLABLE if the statement resource uses a scrollable cursor.

Zobacz też:

  • db2_prepare() - Prepares an SQL statement to be executed

db2_connect
db2_escape_string
IBM DB2 Funkcje


Used to escape certain characters

db2_cursor_type
db2_exec
IBM DB2 Funkcje
PHP Manual

db2_escape_string

(PECL ibm_db2 >= 1.6.0)

db2_escape_string — Used to escape certain characters

Opis

string db2_escape_string ( string $string_literal )

Prepends backslashes to special characters in the string argument.

Parametry

string_literal

The string that contains special characters that need to be modified. Characters that are prepended with a backslash are \x00, \n, \r, \, ', " and \x1a.

Zwracane wartości

Returns string_literal with the special characters noted above prepended with backslashes.

Przykłady

Przykład #1 A db2_escape_string() example

Result of using the db2_escape_string() function

<?php

$conn = db2_connect($database, $user, $password);

if ($conn) {
    $str[0] = "All characters: \x00 , \n , \r , \ , ' , \" , \x1a .";
    $str[1] = "Backslash (\). Single quote ('). Double quote (\")";
    $str[2] = "The NULL character \0 must be quoted as well";
    $str[3] = "Intersting characters: \x1a , \x00 .";
    $str[4] = "Nothing to quote";
    $str[5] = 200676;
    $str[6] = "";

    foreach( $str as $string ) {
        echo "db2_escape_string: " . db2_escape_string($string). "\n";
    }
}
?>

Powyższy przykład wyświetli:

db2_escape_string: All characters: \0 , \n , \r , \\ , \' , \" , \Z .
db2_escape_string: Backslash (\\). Single quote (\'). Double quote (\")
db2_escape_string: The NULL character \0 must be quoted as well
db2_escape_string: Intersting characters: \Z , \0 .
db2_escape_string: Nothing to quote
db2_escape_string: 200676
db2_escape_string:

Zobacz też:

  • db2_prepare() - Prepares an SQL statement to be executed

db2_cursor_type
db2_exec
IBM DB2 Funkcje


Executes an SQL statement directly

db2_escape_string
db2_execute
IBM DB2 Funkcje
PHP Manual

db2_exec

(PECL ibm_db2 >= 1.0.0)

db2_exec — Executes an SQL statement directly

Opis

resource db2_exec ( resource $connection , string $statement [, array $options ] )

Executes an SQL statement directly.

If you plan to interpolate PHP variables into the SQL statement, understand that this is one of the more common security exposures. Consider calling db2_prepare() to prepare an SQL statement with parameter markers for input values. Then you can call db2_execute() to pass in the input values and avoid SQL injection attacks.

If you plan to repeatedly issue the same SQL statement with different parameters, consider calling db2_prepare() and db2_execute() to enable the database server to reuse its access plan and increase the efficiency of your database access.

Parametry

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

statement

An SQL statement. The statement cannot contain any parameter markers.

options

An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.

For a description of valid statement options, see db2_set_option().

Zwracane wartości

Returns a statement resource if the SQL statement was issued successfully, or FALSE if the database failed to execute the SQL statement.

Przykłady

Przykład #1 Creating a table with db2_exec()

The following example uses db2_exec() to issue a set of DDL statements in the process of creating a table.

<?php
$conn = db2_connect($database, $user, $password);

// Create the test table
$create = 'CREATE TABLE animals (id INTEGER, breed VARCHAR(32),
    name CHAR(16), weight DECIMAL(7,2))';
$result = db2_exec($conn, $create);
if ($result) {
    print "Successfully created the table.\n";
}

// Populate the test table
$animals = array(
    array(0, 'cat', 'Pook', 3.2),
    array(1, 'dog', 'Peaches', 12.3),
    array(2, 'horse', 'Smarty', 350.0),
    array(3, 'gold fish', 'Bubbles', 0.1),
    array(4, 'budgerigar', 'Gizmo', 0.2),
    array(5, 'goat', 'Rickety Ride', 9.7),
    array(6, 'llama', 'Sweater', 150)
);

foreach ($animals as $animal) {
    $rc = db2_exec($conn, "INSERT INTO animals (id, breed, name, weight)
      VALUES ({$animal[0]}, '{$animal[1]}', '{$animal[2]}', {$animal[3]})");
    if ($rc) {
        print "Insert... ";
    }
}
?>

Powyższy przykład wyświetli:

Successfully created the table.
Insert... Insert... Insert... Insert... Insert... Insert... Insert...

Przykład #2 Executing a SELECT statement with a scrollable cursor

The following example demonstrates how to request a scrollable cursor for an SQL statement issued by db2_exec().

<?php
$conn = db2_connect($database, $user, $password);
$sql = "SELECT name FROM animals
    WHERE weight < 10.0
    ORDER BY name";
if ($conn) {
    require_once('prepare.inc');
    $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
    while ($row = db2_fetch_array($stmt)) {
        print "$row[0]\n";
    }
}
?>

Powyższy przykład wyświetli:

Bubbles
Gizmo
Pook
Rickety Ride

Przykład #3 Returning XML data as an SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in an SQL ResultSet format that most users are familiar with.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = 'SELECT * FROM XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" VARCHAR (50) PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) AS T
    WHERE NAME = \'Kathy Smith\'
    ';
$stmt = db2_exec($conn, $query);

while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE\n");
}
db2_close($conn);

?>

Powyższy przykład wyświetli:

1000     Kathy Smith     416-555-1358
1001     Kathy Smith     905-555-7258

Przykład #4 Performing a "JOIN" with XML data

The following example works with documents stored in 2 different XML columns in the SAMPLE database. It creates 2 temporary tables from the XML documents from 2 different columns and returns an SQL ResultSet with information regarding shipping status for the customer.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
    SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
    FROM
    XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" BIGINT PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) as A,
    PURCHASEORDER AS B,
    XMLTABLE (
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
    COLUMNS
    "PONUM"  BIGINT PATH \'@PoNum\',
    "STATUS" VARCHAR (50) PATH \'@Status\'
    ) as C
    WHERE A.CID = B.CUSTID AND
    B.POID = C.PONUM AND
    A.NAME = \'Kathy Smith\'
';

$stmt = db2_exec($conn, $query);

while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE     $row->PONUM     $row->STATUS\n");
}

db2_close($conn);

?>

Powyższy przykład wyświetli:

1001     Kathy Smith     905-555-7258     5002     Shipped

Przykład #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
    declare boundary-space strip;
    declare default element namespace "http://posample.org";
    <promoList> {
    for $prod in $doc/product
    where $prod/description/price < 10.00
    order by $prod/description/price ascending
    return(
        <promoitem> {
        $prod,
        <startdate> {$start} </startdate>,
        <enddate> {$end} </enddate>,
        <promoprice> {$promo} </promoprice>
        } </promoitem>
    )
    } </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = \'100-100-01\'
';

$stmt = db2_exec($conn, $query);

while($row = db2_fetch_array($stmt)){
    printf("$row[0]\n");
}
db2_close($conn);

?>

Powyższy przykład wyświetli:

<promoList xmlns="http://posample.org">
    <promoitem>
    <product pid="100-100-01">
        <description>
            <name>Snow Shovel, Basic 22 inch</name>
            <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
            <price>9.99</price>
            <weight>1 kg</weight>
        </description>
    </product>
    <startdate>2004-11-19</startdate>
    <enddate>2004-12-19</enddate>
    <promoprice>7.25</promoprice>
    </promoitem>
</promoList>

Zobacz też:

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

db2_escape_string
db2_execute
IBM DB2 Funkcje


Executes a prepared SQL statement

db2_exec
db2_fetch_array
IBM DB2 Funkcje
PHP Manual

db2_execute

(PECL ibm_db2 >= 1.0.0)

db2_execute — Executes a prepared SQL statement

Opis

bool db2_execute ( resource $stmt [, array $parameters ] )

db2_execute() executes an SQL statement that was prepared by db2_prepare().

If the SQL statement returns a result set, for example, a SELECT statement or a CALL to a stored procedure that returns one or more result sets, you can retrieve a row as an array from the stmt resource using db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array(). Alternatively, you can use db2_fetch_row() to move the result set pointer to the next row and fetch a column at a time from that row with db2_result().

Refer to db2_prepare() for a brief discussion of the advantages of using db2_prepare() and db2_execute() rather than db2_exec().

Parametry

stmt

A prepared statement returned from db2_prepare().

parameters

An array of input parameters matching any parameter markers contained in the prepared statement.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

<?php
$pet = array(0, 'cat', 'Pook', 3.2);

$insert = 'INSERT INTO animals (id, breed, name, weight)
    VALUES (?, ?, ?, ?)';

$stmt = db2_prepare($conn, $insert);
if ($stmt) {
    $result = db2_execute($stmt, $pet);
    if ($result) {
        print "Successfully added new pet.";
    }
}
?>

Powyższy przykład wyświetli:

Successfully added new pet.

Przykład #2 Calling a stored procedure with an OUT parameter

The following example prepares a CALL statement that accepts one parameter marker representing an OUT parameter, binds the PHP variable $my_pets to the parameter using db2_bind_param(), then issues db2_execute() to execute the CALL statement. After the CALL to the stored procedure has been made, the value of $num_pets changes to reflect the value returned by the stored procedure for that OUT parameter.

<?php
$num_pets = 0;
$res = db2_prepare($conn, "CALL count_my_pets(?)");
$rc = db2_bind_param($res, 1, "num_pets", DB2_PARAM_OUT);
$rc = db2_execute($res);
print "I have $num_pets pets!";
?>

Powyższy przykład wyświetli:

I have 7 pets!

Przykład #3 Returning XML data as an SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in an SQL ResultSet format that most users are familiar with.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = 'SELECT * FROM XMLTABLE(
    XMLNAMESPACES (DEFAULT \'http://posample.org\'),
    \'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
    COLUMNS
    "CID" VARCHAR (50) PATH \'@Cid\',
    "NAME" VARCHAR (50) PATH \'name\',
    "PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
    ) AS T
    WHERE NAME = ?
    ';

$stmt = db2_prepare($conn, $query);

$name = 'Kathy Smith';

if ($stmt) {
    db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE\n");
    }
}
db2_close($conn);

?>

Powyższy przykład wyświetli:

1000     Kathy Smith     416-555-1358
1001     Kathy Smith     905-555-7258

Przykład #4 Performing a "JOIN" with XML data

The following example works with documents stored in 2 different XML columns in the SAMPLE database. It creates 2 temporary tables from the XML documents from 2 different columns and returns an SQL ResultSet with information regarding shipping status for the customer.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
FROM
XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" BIGINT PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) as A,
PURCHASEORDER AS B,
XMLTABLE (
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
COLUMNS
"PONUM"  BIGINT PATH \'@PoNum\',
"STATUS" VARCHAR (50) PATH \'@Status\'
) as C
WHERE A.CID = B.CUSTID AND
    B.POID = C.PONUM AND
    A.NAME = ?
';

$stmt = db2_prepare($conn, $query);

$name = 'Kathy Smith';

if ($stmt) {
    db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_object($stmt)){
    printf("$row->CID     $row->NAME     $row->PHONE     $row->PONUM     $row->STATUS\n");
    }
}

db2_close($conn);

?>

Powyższy przykład wyświetli:

1001     Kathy Smith     905-555-7258     5002     Shipped

Przykład #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
    declare boundary-space strip;
    declare default element namespace "http://posample.org";
    <promoList> {
    for $prod in $doc/product
    where $prod/description/price < 10.00
    order by $prod/description/price ascending
    return(
        <promoitem> {
        $prod,
        <startdate> {$start} </startdate>,
        <enddate> {$end} </enddate>,
        <promoprice> {$promo} </promoprice>
            } </promoitem>
    )
    } </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = ?
';

$stmt = db2_prepare($conn, $query);

$pid = "100-100-01";

if ($stmt) {
    db2_bind_param($stmt, 1, "pid", DB2_PARAM_IN);
    db2_execute($stmt);

    while($row = db2_fetch_array($stmt)){
    printf("$row[0]\n");
    }
}

db2_close($conn);

?>

Powyższy przykład wyświetli:

<promoList xmlns="http://posample.org">
    <promoitem>
    <product pid="100-100-01">
        <description>
            <name>Snow Shovel, Basic 22 inch</name>
            <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
            <price>9.99</price>
            <weight>1 kg</weight>
        </description>
    </product>
    <startdate>2004-11-19</startdate>
    <enddate>2004-12-19</enddate>
    <promoprice>7.25</promoprice>
    </promoitem>
</promoList>

Zobacz też:

  • db2_exec() - Executes an SQL statement directly
  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_result() - Returns a single column from a row in the result set

db2_exec
db2_fetch_array
IBM DB2 Funkcje


Returns an array, indexed by column position, representing a row in a result set

db2_execute
db2_fetch_assoc
IBM DB2 Funkcje
PHP Manual

db2_fetch_array

(PECL ibm_db2 >= 1.0.1)

db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set

Opis

array db2_fetch_array ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.

Parametry

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Zwracane wartości

Returns a 0-indexed array with column values indexed by the column position representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Przykłady

Przykład #1 Iterating through a forward-only cursor

If you call db2_fetch_array() without a specific row number, it automatically retrieves the next row in the result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_array($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row[1], $row[2], $row[3]);
}
?>

Powyższy przykład wyświetli:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Przykład #2 Retrieving specific rows with db2_fetch_array() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_array() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_array($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row[1], $row[2], $row[3]);
    $i = $i + 2;
}
?>

Powyższy przykład wyświetli:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Zobacz też:

  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

db2_execute
db2_fetch_assoc
IBM DB2 Funkcje


Returns an array, indexed by column name, representing a row in a result set

db2_fetch_array
db2_fetch_both
IBM DB2 Funkcje
PHP Manual

db2_fetch_assoc

(PECL ibm_db2 >= 1.0.0)

db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set

Opis

array db2_fetch_assoc ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by column name, representing a row in a result set.

Parametry

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Zwracane wartości

Returns an associative array with column values indexed by the column name representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Przykłady

Przykład #1 Iterating through a forward-only cursor

If you call db2_fetch_assoc() without a specific row number, it automatically retrieves the next row in the result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_assoc($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
}
?>

Powyższy przykład wyświetli:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Przykład #2 Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_assoc($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
    $i = $i + 2;
}
?>

Powyższy przykład wyświetli:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Zobacz też:

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

db2_fetch_array
db2_fetch_both
IBM DB2 Funkcje


Returns an array, indexed by both column name and position, representing a row in a result set

db2_fetch_assoc
db2_fetch_object
IBM DB2 Funkcje
PHP Manual

db2_fetch_both

(PECL ibm_db2 >= 1.0.0)

db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set

Opis

array db2_fetch_both ( resource $stmt [, int $row_number = -1 ] )

Returns an array, indexed by both column name and position, representing a
row in a result set. Note that the row returned by
db2_fetch_both() requires more memory than the
single-indexed arrays returned by db2_fetch_assoc() or
db2_fetch_array().

Parametry

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Zwracane wartości

Returns an associative array with column values indexed by both the column name and 0-indexed column number. The array represents the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

Przykłady

Przykład #1 Iterating through a forward-only cursor

If you call db2_fetch_both() without a specific row number, it automatically retrieves the next row in the result set. The following example accesses columns in the returned array by both column name and by numeric index.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_both($stmt)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row['ID'], $row[0], $row['BREED'], $row[3]);
}
?>

Powyższy przykład wyświetli:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Przykład #2 Retrieving specific rows with db2_fetch_both() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_both() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_both($result, $i)) {
    printf ("%-5d %-16s %-32s %10s\n",
        $row[0], $row['NAME'], $row[2], $row['WEIGHT']);
    $i = $i + 2;
}
?>

Powyższy przykład wyświetli:

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Zobacz też:

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

db2_fetch_assoc
db2_fetch_object
IBM DB2 Funkcje


Returns an object with properties representing columns in the fetched row

db2_fetch_both
db2_fetch_row
IBM DB2 Funkcje
PHP Manual

db2_fetch_object

(PECL ibm_db2 >= 1.0.0)

db2_fetch_object — Returns an object with properties representing columns in the fetched row

Opis

object db2_fetch_object ( resource $stmt [, int $row_number = -1 ] )

Returns an object in which each property represents a column returned in the row fetched from a result set.

Parametry

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

Zwracane wartości

Returns an object representing a single row in the result set. The properties of the object map to the names of the columns in the result set.

The IBM DB2, Cloudscape, and Apache Derby database servers typically fold column names to upper-case, so the object properties will reflect that case.

If your SELECT statement calls a scalar function to modify the value of a column, the database servers return the column number as the name of the column in the result set. If you prefer a more descriptive column name and object property, you can use the AS clause to assign a name to the column in the result set.

Returns FALSE if no row was retrieved.

Przykłady

Przykład #1 A db2_fetch_object() example

The following example issues a SELECT statement with a scalar function, RTRIM, that removes whitespace from the end of the column. Rather than creating an object with the properties "BREED" and "2", we use the AS clause in the SELECT statement to assign the name "name" to the modified column. The database server folds the column names to upper-case, resulting in an object with the properties "BREED" and "NAME".

<?php
$conn = db2_connect($database, $user, $password);

$sql = "SELECT breed, RTRIM(name) AS name
    FROM animals
    WHERE id = ?";

if ($conn) {
    $stmt = db2_prepare($conn, $sql);
    db2_execute($stmt, array(0));

    while ($pet = db2_fetch_object($stmt)) {
        echo "Come here, {$pet->NAME}, my little {$pet->BREED}!";
    }
    db2_close($conn);
}
?>

Powyższy przykład wyświetli:

Come here, Pook, my little cat!

Zobacz też:

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

db2_fetch_both
db2_fetch_row
IBM DB2 Funkcje


Sets the result set pointer to the next row or requested row

db2_fetch_object
db2_field_display_size
IBM DB2 Funkcje
PHP Manual

db2_fetch_row

(PECL ibm_db2 >= 1.0.0)

db2_fetch_row — Sets the result set pointer to the next row or requested row

Opis

bool db2_fetch_row ( resource $stmt [, int $row_number ] )

Use db2_fetch_row() to iterate through a result set, or to point to a specific row in a result set if you requested a scrollable cursor.

To retrieve individual fields from the result set, call the db2_result() function.

Rather than calling db2_fetch_row() and db2_result(), most applications will call one of db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array() to advance the result set pointer and return a complete row as an array.

Parametry

stmt

A valid stmt resource.

row_number

With scrollable cursors, you can request a specific row number in the result set. Row numbering is 1-indexed.

Zwracane wartości

Returns TRUE if the requested row exists in the result set. Returns FALSE if the requested row does not exist in the result set.

Przykłady

Przykład #1 Iterating through a result set

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    $breed = db2_result($stmt, 1);
    print "$name $breed";
}
?>

Powyższy przykład wyświetli:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

Przykład #2 i5/OS recommended alternatives to db2_fetch_row/db2_result

On i5/OS it is recommended that you use db2_fetch_both(), db2_fetch_array(), or db2_fetch_object() over db2_fetch_row()/db2_result(). In general db2_fetch_row()/db2_result() have more issues with various column types in EBCIDIC to ASCII translation, including possible truncation in DBCS applications. You may also find the performance of db2_fetch_both(), db2_fetch_array(), and db2_fetch_object() to be superior to db2_fetch_row()/db2_result().

<?php
  $conn = db2_connect("","","");
  $sql = 'SELECT SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, ROUTINE_CREATED, ROUTINE_BODY, IN_PARMS, OUT_PARMS, INOUT_PARMS, PARAMETER_STYLE, EXTERNAL_NAME, EXTERNAL_LANGUAGE FROM QSYS2.SYSROUTINES FETCH FIRST 2 ROWS ONLY';
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_both($stmt)){
    echo "<br>db2_fetch_both {$row['SPECIFIC_NAME']} {$row['ROUTINE_CREATED']} {$row[5]}";
  }
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_array($stmt)){
    echo "<br>db2_fetch_array {$row[1]}  {$row[5]}";
  }
  $stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
  while ($row = db2_fetch_object($stmt)){
    echo "<br>db2_fetch_object {$row->SPECIFIC_NAME} {$row->ROUTINE_CREATED}";
  }
  db2_close($conn);
?>

Powyższy przykład wyświetli:

db2_fetch_both MATCH_ANIMAL 2006-08-25-17.10.23.775000 2006-08-25-17.10.23.775000
db2_fetch_both MULTIRESULTS 2006-10-17-10.11.05.308000 2006-10-17-10.11.05.308000
db2_fetch_array MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_array MULTIRESULTS 2006-10-17-10.11.05.308000
db2_fetch_object MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_object MULTIRESULTS 2006-10-17-10.11.05.308000

Zobacz też:

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_result() - Returns a single column from a row in the result set

db2_fetch_object
db2_field_display_size
IBM DB2 Funkcje


Returns the maximum number of bytes required to display a column

db2_fetch_row
db2_field_name
IBM DB2 Funkcje
PHP Manual

db2_field_display_size

(PECL ibm_db2 >= 1.0.0)

db2_field_display_size — Returns the maximum number of bytes required to display a column

Opis

int db2_field_display_size ( resource $stmt , mixed $column )

Returns the maximum number of bytes required to display a column in a result set.

Parametry

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Zwracane wartości

Returns an integer value with the maximum number of bytes required to display the specified column. If the column does not exist in the result set, db2_field_display_size() returns FALSE.

Zobacz też:

  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_fetch_row
db2_field_name
IBM DB2 Funkcje


Returns the name of the column in the result set

db2_field_display_size
db2_field_num
IBM DB2 Funkcje
PHP Manual

db2_field_name

(PECL ibm_db2 >= 1.0.0)

db2_field_name — Returns the name of the column in the result set

Opis

string db2_field_name ( resource $stmt , mixed $column )

Returns the name of the specified column in the result set.

Parametry

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Zwracane wartości

Returns a string containing the name of the specified column. If the specified column does not exist in the result set, db2_field_name() returns FALSE.

Zobacz też:

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_display_size
db2_field_num
IBM DB2 Funkcje


Returns the position of the named column in a result set

db2_field_name
db2_field_precision
IBM DB2 Funkcje
PHP Manual

db2_field_num

(PECL ibm_db2 >= 1.0.0)

db2_field_num — Returns the position of the named column in a result set

Opis

int db2_field_num ( resource $stmt , mixed $column )

Returns the position of the named column in a result set.

Parametry

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Zwracane wartości

Returns an integer containing the 0-indexed position of the named column in the result set. If the specified column does not exist in the result set, db2_field_num() returns FALSE.

Zobacz też:

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_name
db2_field_precision
IBM DB2 Funkcje


Returns the precision of the indicated column in a result set

db2_field_num
db2_field_scale
IBM DB2 Funkcje
PHP Manual

db2_field_precision

(PECL ibm_db2 >= 1.0.0)

db2_field_precision — Returns the precision of the indicated column in a result set

Opis

int db2_field_precision ( resource $stmt , mixed $column )

Returns the precision of the indicated column in a result set.

Parametry

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Zwracane wartości

Returns an integer containing the precision of the specified column. If the specified column does not exist in the result set, db2_field_precision() returns FALSE.

Zobacz też:

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_num
db2_field_scale
IBM DB2 Funkcje


Returns the scale of the indicated column in a result set

db2_field_precision
db2_field_type
IBM DB2 Funkcje
PHP Manual

db2_field_scale

(PECL ibm_db2 >= 1.0.0)

db2_field_scale — Returns the scale of the indicated column in a result set

Opis

int db2_field_scale ( resource $stmt , mixed $column )

Returns the scale of the indicated column in a result set.

Parametry

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Zwracane wartości

Returns an integer containing the scale of the specified column. If the specified column does not exist in the result set, db2_field_scale() returns FALSE.

Zobacz też:

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_precision
db2_field_type
IBM DB2 Funkcje


Returns the data type of the indicated column in a result set

db2_field_scale
db2_field_width
IBM DB2 Funkcje
PHP Manual

db2_field_type

(PECL ibm_db2 >= 1.0.0)

db2_field_type — Returns the data type of the indicated column in a result set

Opis

string db2_field_type ( resource $stmt , mixed $column )

Returns the data type of the indicated column in a result set.

Parametry

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Zwracane wartości

Returns a string containing the defined data type of the specified column. If the specified column does not exist in the result set, db2_field_type() returns FALSE.

Zobacz też:

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_field_scale
db2_field_width
IBM DB2 Funkcje


Returns the width of the current value of the indicated column in a result set

db2_field_type
db2_foreign_keys
IBM DB2 Funkcje
PHP Manual

db2_field_width

(PECL ibm_db2 >= 1.0.0)

db2_field_width — Returns the width of the current value of the indicated column in a result set

Opis

int db2_field_width ( resource $stmt , mixed $column )

Returns the width of the current value of the indicated column in a result set. This is the maximum width of the column for a fixed-length data type, or the actual width of the column for a variable-length data type.

Parametry

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

Zwracane wartości

Returns an integer containing the width of the specified character or binary data type column in a result set. If the specified column does not exist in the result set, db2_field_width() returns FALSE.

Zobacz też:

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set

db2_field_type
db2_foreign_keys
IBM DB2 Funkcje


Returns a result set listing the foreign keys for a table

db2_field_width
db2_free_result
IBM DB2 Funkcje
PHP Manual

db2_foreign_keys

(PECL ibm_db2 >= 1.0.0)

db2_foreign_keys — Returns a result set listing the foreign keys for a table

Opis

resource db2_foreign_keys ( resource $connection , string $qualifier , string $schema , string $table-name )

Returns a result set listing the foreign keys for a table.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. If schema is NULL, db2_foreign_keys() matches the schema for the current connection.

table-name

The name of the table.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the foreign keys for the specified table. The result set is composed of the following columns:

Column name | Description
PKTABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
PKTABLE_SCHEM | Name of the schema for the table containing the primary key.
PKTABLE_NAME | Name of the table containing the primary key.
PKCOLUMN_NAME | Name of the column containing the primary key.
FKTABLE_CAT | Name of the catalog for the table containing the foreign key. The value is NULL if this table does not have catalogs.
FKTABLE_SCHEM | Name of the schema for the table containing the foreign key.
FKTABLE_NAME | Name of the table containing the foreign key.
FKCOLUMN_NAME | Name of the column containing the foreign key.
KEY_SEQ | 1-indexed position of the column in the key.
UPDATE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is UPDATE.
DELETE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is DELETE.
FK_NAME | The name of the foreign key.
PK_NAME | The name of the primary key.
DEFERRABILITY | An integer value representing whether the foreign key deferrability is SQL_INITIALLY_DEFERRED, SQL_INITIALLY_IMMEDIATE, or SQL_NOT_DEFERRABLE.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_field_width
db2_free_result
IBM DB2 Funkcje


Frees resources associated with a result set

db2_foreign_keys
db2_free_stmt
IBM DB2 Funkcje
PHP Manual

db2_free_result

(PECL ibm_db2 >= 1.0.0)

db2_free_result — Frees resources associated with a result set

Opis

bool db2_free_result ( resource $stmt )

Frees the system and database resources that are associated with a result set. These resources are freed implicitly when a script finishes, but you can call db2_free_result() to explicitly free the result set resources before the end of the script.

Parametry

stmt

A valid statement resource.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • db2_free_stmt() - Frees resources associated with the indicated statement resource

db2_foreign_keys
db2_free_stmt
IBM DB2 Funkcje


Frees resources associated with the indicated statement resource

db2_free_result
db2_get_option
IBM DB2 Funkcje
PHP Manual

db2_free_stmt

(PECL ibm_db2 >= 1.0.0)

db2_free_stmt — Frees resources associated with the indicated statement resource

Opis

bool db2_free_stmt ( resource $stmt )

Frees the system and database resources that are associated with a statement resource. These resources are freed implicitly when a script finishes, but you can call db2_free_stmt() to explicitly free the statement resources before the end of the script.

Parametry

stmt

A valid statement resource.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • db2_free_result() - Frees resources associated with a result set

db2_free_result
db2_get_option
IBM DB2 Funkcje


Retrieves an option value for a statement resource or a connection resource

db2_free_stmt
db2_last_insert_id
IBM DB2 Funkcje
PHP Manual

db2_get_option

(PECL ibm_db2 >= 1.6.0)

db2_get_option — Retrieves an option value for a statement resource or a connection resource

Opis

string db2_get_option ( resource $resource , string $option )

Retrieves the value of a specified option value for a statement resource or a connection resource.

Parametry

resource

A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().

option

A valid statement or connection options. The following new options are available as of ibm_db2 version 1.6.0. They provide useful tracking information that can be set during execution with db2_get_option().

Informacja:

Prior versions of ibm_db2 do not support these new options.

When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value.

To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

userid

SQL_ATTR_INFO_USERID - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

Informacja:

DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

acctstr

SQL_ATTR_INFO_ACCTSTR - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

Informacja:

DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

applname

SQL_ATTR_INFO_APPLNAME - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

Informacja:

DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

wrkstnname

SQL_ATTR_INFO_WRKSTNNAME - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

Informacja:

DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
 |  | Connection | Statement | Result Set
userid | SQL_ATTR_INFO_USERID | X | X | -
acctstr | SQL_ATTR_INFO_ACCTSTR | X | X | -
applname | SQL_ATTR_INFO_APPLNAME | X | X | -
wrkstnname | SQL_ATTR_INFO_WRKSTNNAME | X | X | -

Zwracane wartości

Returns the current setting of the connection attribute provided on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Setting and retrieving parameters through a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$user     = 'db2inst1';
$password = 'ibmdb2';

/* Obtain Connection Resource */
$conn = db2_connect($database, $user, $password);

echo "Client attributes passed through connection string:\n";

/* Create the associative options array with valid key-value pairs */
/* Assign the attributes through connection string */
/* Access the options specified */
$options1 = array('userid' => 'db2inst1');
$conn1 = db2_connect($database, $user, $password, $options1);
$val = db2_get_option($conn1, 'userid');
echo $val . "\n";

$options2 = array('acctstr' => 'account');
$conn2 = db2_connect($database, $user, $password, $options2);
$val = db2_get_option($conn2, 'acctstr');
echo $val . "\n";

$options3 = array('applname' => 'myapp');
$conn3 = db2_connect($database, $user, $password, $options3);
$val = db2_get_option($conn3, 'applname');
echo $val . "\n";

$options4 = array('wrkstnname' => 'workstation');
$conn4 = db2_connect($database, $user, $password, $options4);
$val = db2_get_option($conn4, 'wrkstnname');
echo $val . "\n";

echo "Client attributes passed post-connection:\n";

/* Create the associative options array with valid key-value pairs */
/* Assign the attributes after a connection is made */
/* Access the options specified */
$options5 = array('userid' => 'db2inst1');
$conn5 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn5, $options5, 1);
$val = db2_get_option($conn5, 'userid');
echo $val . "\n";

$options6 = array('acctstr' => 'account');
$conn6 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn6, $options6, 1);
$val = db2_get_option($conn6, 'acctstr');
echo $val . "\n";

$options7 = array('applname' => 'myapp');
$conn7 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn7, $options7, 1);
$val = db2_get_option($conn7, 'applname');
echo $val . "\n";

$options8 = array('wrkstnname' => 'workstation');
$conn8 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn8, $options8, 1);
$val = db2_get_option($conn8, 'wrkstnname');
echo $val . "\n";
?>

Powyższy przykład wyświetli:

Client attributes passed through connection string:
db2inst1
account
myapp
workstation
Client attributes passed post-connection:
db2inst1
account
myapp
workstation

Zobacz też:

  • db2_connect() - Returns a connection to a database
  • db2_cursor_type() - Returns the cursor type used by a statement resource
  • db2_exec() - Executes an SQL statement directly
  • db2_set_option() - Set options for connection or statement resources
  • db2_pconnect() - Returns a persistent connection to a database
  • db2_prepare() - Prepares an SQL statement to be executed

db2_free_stmt
db2_last_insert_id
IBM DB2 Funkcje


Returns the auto generated ID of the last insert query that successfully executed on this connection

db2_get_option
db2_lob_read
IBM DB2 Funkcje
PHP Manual

db2_last_insert_id

(PECL ibm_db2 >= 1.7.1)

db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection

Opis

string db2_last_insert_id ( resource $resource )

Returns the auto generated ID of the last insert query that successfully executed on this connection.

The result of this function is not affected by any of the following:

  • A single row INSERT statement with a VALUES clause for a table without an identity column.

  • A multiple row INSERT statement with a VALUES clause.

  • An INSERT statement with a fullselect.

  • A ROLLBACK TO SAVEPOINT statement.

Parametry

resource

A valid connection resource as returned from db2_connect() or db2_pconnect(). The value of this parameter cannot be a statement resource or result set resource.

Zwracane wartości

Returns the auto generated ID of last insert query that successfully executed on this connection.

Przykłady

Przykład #1 A db2_last_insert_id() example

The following example shows how to return the auto generated ID of last insert query that successfully executed on this connection.

<?php

$database = "SAMPLE";
$user = "db2inst1";
$password = "ibmdb2";

$conn = db2_connect($database, $user, $password);
if($conn) {
    $createTable = "CREATE TABLE lastInsertID
      (id integer GENERATED BY DEFAULT AS IDENTITY, name varchar(20))";
    $insertTable = "INSERT INTO lastInsertID (name) VALUES ('Temp Name')";

    $stmt = @db2_exec($conn, $createTable);

    /* Checking for single row inserted. */
    $stmt = db2_exec($conn, $insertTable);
    $ret =  db2_last_insert_id($conn);
    if($ret) {
        echo "Last Insert ID is : " . $ret . "\n";
    } else {
        echo "No Last insert ID.\n";
    }

    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>

Powyższy przykład wyświetli:

Last Insert ID is : 1

db2_get_option
db2_lob_read
IBM DB2 Funkcje


Gets a user defined size of LOB files with each invocation

db2_last_insert_id
db2_next_result
IBM DB2 Funkcje
PHP Manual

db2_lob_read

(PECL ibm_db2 >= 1.6.0)

db2_lob_read — Gets a user defined size of LOB files with each invocation

Opis

string db2_lob_read ( resource $stmt , int $colnum , int $length )

Use db2_lob_read() to iterate through a specified column of a result set and retrieve a user defined size of LOB data.

Parametry

stmt

A valid stmt resource containing LOB data.

colnum

A valid column number in the result set of the stmt resource.

length

The size of the LOB data to be retrieved from the stmt resource.

Zwracane wartości

Returns the amount of data the user specifies. Returns FALSE if the data cannot be retrieved.

Przykłady

Przykład #1 Iterating through different types of data

<?php

/* Database Connection Parameters */
$db = 'SAMPLE';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Obtain Connection Resource */
$conn = db2_connect($db,$username,$password);

if ($conn) {
    $drop = 'DROP TABLE clob_stream';
    $result = @db2_exec( $conn, $drop );

    $create = 'CREATE TABLE clob_stream (id INTEGER, my_clob CLOB)';
    $result = db2_exec( $conn, $create );

    $variable = "";
    $stmt = db2_prepare($conn, "INSERT INTO clob_stream (id,my_clob) VALUES (1, ?)");
    $variable = "THIS IS A CLOB TEST. THIS IS A CLOB TEST.";
    db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
    db2_execute($stmt);

    $sql = "SELECT id,my_clob FROM clob_stream";
    $result = db2_prepare($conn, $sql);
    db2_execute($result);
    db2_fetch_row($result);
    $i = 0;
    /* Read LOB data */
    while ($data = db2_lob_read($result, 2, 6)) {
        echo "Loop $i: $data\n";
        $i = $i + 1;
    }

    $drop = 'DROP TABLE blob_stream';
    $result = @db2_exec( $conn, $drop );

    $create = 'CREATE TABLE blob_stream (id INTEGER, my_blob CLOB)';
    $result = db2_exec( $conn, $create );

    $variable = "";
    $stmt = db2_prepare($conn, "INSERT INTO blob_stream (id,my_blob) VALUES (1, ?)");
    $variable = "THIS IS A BLOB TEST. THIS IS A BLOB TEST.";
    db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
    db2_execute($stmt);

    $sql = "SELECT id,my_blob FROM blob_stream";
    $result = db2_prepare($conn, $sql);
    db2_execute($result);
    db2_fetch_row($result);
    $i = 0;
    /* Read LOB data */
    while ($data = db2_lob_read($result, 2, 6)) {
        echo "Loop $i: $data\n";
        $i = $i + 1;
    }
} else {
    echo 'no connection: ' . db2_conn_errormsg();
}

?>

Powyższy przykład wyświetli:

Loop 0: THIS I
Loop 1: S A CL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5:  CLOB
Loop 6: TEST.
Loop 0: THIS I
Loop 1: S A BL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5:  BLOB
Loop 6: TEST.

Zobacz też:

  • db2_bind_param() - Binds a PHP variable to an SQL statement parameter
  • db2_exec() - Executes an SQL statement directly
  • db2_execute() - Executes a prepared SQL statement
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_result() - Returns a single column from a row in the result set

db2_last_insert_id
db2_next_result
IBM DB2 Funkcje


Requests the next result set from a stored procedure

db2_lob_read
db2_num_fields
IBM DB2 Funkcje
PHP Manual

db2_next_result

(PECL ibm_db2 >= 1.0.0)

db2_next_result — Requests the next result set from a stored procedure

Opis

resource db2_next_result ( resource $stmt )

A stored procedure can return zero or more result sets. While you handle the first result set in exactly the same way you would handle the results returned by a simple SELECT statement, to fetch the second and subsequent result sets from a stored procedure you must call the db2_next_result() function and return the result to a uniquely named PHP variable.

Parametry

stmt

A prepared statement returned from db2_exec() or db2_execute().

Zwracane wartości

Returns a new statement resource containing the next result set if the stored procedure returned another result set. Returns FALSE if the stored procedure did not return another result set.

Przykłady

Przykład #1 Calling a stored procedure that returns multiple result sets

In the following example, we call a stored procedure that returns three result sets. The first result set is fetched directly from the same statement resource on which we invoked the CALL statement, while the second and third result sets are fetched from statement resources returned from our calls to the db2_next_result() function.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
  $stmt = db2_exec($conn, 'CALL multiResults()');

  print "Fetching first result set\n";
  while ($row = db2_fetch_array($stmt)) {
    var_dump($row);
  }

  print "\nFetching second result set\n";
  $res = db2_next_result($stmt);
  if ($res) {
    while ($row = db2_fetch_array($res)) {
      var_dump($row);
    }
  }

  print "\nFetching third result set\n";
  $res2 = db2_next_result($stmt);
  if ($res2) {
    while ($row = db2_fetch_array($res2)) {
      var_dump($row);
    }
  }

  db2_close($conn);
}
?>

Powyższy przykład wyświetli:

Fetching first result set
array(2) {
  [0]=>
  string(16) "Bubbles         "
  [1]=>
  int(3)
}
array(2) {
  [0]=>
  string(16) "Gizmo           "
  [1]=>
  int(4)
}

Fetching second result set
array(4) {
  [0]=>
  string(16) "Sweater         "
  [1]=>
  int(6)
  [2]=>
  string(5) "llama"
  [3]=>
  string(6) "150.00"
}
array(4) {
  [0]=>
  string(16) "Smarty          "
  [1]=>
  int(2)
  [2]=>
  string(5) "horse"
  [3]=>
  string(6) "350.00"
}

Fetching third result set
array(1) {
  [0]=>
  string(16) "Bubbles         "
}
array(1) {
  [0]=>
  string(16) "Gizmo           "
}

db2_lob_read
db2_num_fields
IBM DB2 Funkcje


Returns the number of fields contained in a result set

db2_next_result
db2_num_rows
IBM DB2 Funkcje
PHP Manual

db2_num_fields

(PECL ibm_db2 >= 1.0.0)

db2_num_fields — Returns the number of fields contained in a result set

Opis

int db2_num_fields ( resource $stmt )

Returns the number of fields contained in a result set. This is most useful for handling the result sets returned by dynamically generated queries, or for result sets returned by stored procedures, where your application cannot otherwise know how to retrieve and use the results.

Parametry

stmt

A valid statement resource containing a result set.

Zwracane wartości

Returns an integer value representing the number of fields in the result set associated with the specified statement resource. Returns FALSE if the statement resource is not a valid input value.

Przykłady

Przykład #1 Retrieving the number of fields in a result set

The following example demonstrates how to retrieve the number of fields returned in a result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, $sql);
$columns = db2_num_fields($stmt);

echo "There are {$columns} columns in the result set.";
?>

Powyższy przykład wyświetli:

There are 4 columns in the result set.

Zobacz też:

  • db2_execute() - Executes a prepared SQL statement
  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

db2_next_result
db2_num_rows
IBM DB2 Funkcje


Returns the number of rows affected by an SQL statement

db2_num_fields
db2_pclose
IBM DB2 Funkcje
PHP Manual

db2_num_rows

(PECL ibm_db2 >= 1.0.0)

db2_num_rows — Returns the number of rows affected by an SQL statement

Opis

int db2_num_rows ( resource $stmt )

Returns the number of rows deleted, inserted, or updated by an SQL statement.

To determine the number of rows that will be returned by a SELECT statement, issue SELECT COUNT(*) with the same predicates as your intended SELECT statement and retrieve the value.

If your application logic checks the number of rows returned by a SELECT statement and branches if the number of rows is 0, consider modifying your application to attempt to return the first row with one of db2_fetch_assoc(), db2_fetch_both(), db2_fetch_array(), or db2_fetch_row(), and branch if the fetch function returns FALSE.

Informacja:

If you issue a SELECT statement using a scrollable cursor, db2_num_rows() returns the number of rows returned by the SELECT statement. However, the overhead associated with scrollable cursors significantly degrades the performance of your application, so if this is the only reason you are considering using scrollable cursors, you should use a forward-only cursor and either call SELECT COUNT(*) or rely on the boolean return value of the fetch functions to achieve the equivalent functionality with much better performance.

Parametry

stmt

A valid stmt resource containing a result set.

Zwracane wartości

Returns the number of rows affected by the last SQL statement issued by the specified statement handle.

db2_num_fields
db2_pclose
IBM DB2 Funkcje


Closes a persistent database connection

db2_num_rows
db2_pconnect
IBM DB2 Funkcje
PHP Manual

db2_pclose

(PECL ibm_db2 >= 1.8.0)

db2_pclose — Closes a persistent database connection

Opis

bool db2_pclose ( resource $resource )

This function closes a DB2 client connection created with db2_pconnect() and returns the corresponding resources to the database server.

Informacja:

This function is only available on i5/OS in response to i5/OS system administration requests.

If you have a persistent DB2 client connection created with db2_pconnect(), you may use this function to close the connection. To avoid substantial connection performance penalties, this function should only be used in rare cases when the persistent connection has become unresponsive or the persistent connection will not be needed for a long period of time.

Parametry

connection

Specifies an active DB2 client connection.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Closing a persistent connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2 i5/OS database.

<?php
$conn = db2_pconnect('', '', '');
$rc = db2_pclose($conn);
if ($rc) {
    echo "Connection was successfully closed.";
}
?>

Powyższy przykład wyświetli:

Connection was successfully closed.

Zobacz też:

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

db2_num_rows
db2_pconnect
IBM DB2 Funkcje


Returns a persistent connection to a database

db2_pclose
db2_prepare
IBM DB2 Funkcje
PHP Manual

db2_pconnect

(PECL ibm_db2 >= 1.0.0)

db2_pconnect — Returns a persistent connection to a database

Opis

resource db2_pconnect ( string $database , string $username , string $password [, array $options ] )

Returns a persistent connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

For more information on persistent connections, refer to Stałe połączenia z bazami danych.

Calling db2_close() on a persistent connection always returns TRUE, but the underlying DB2 client connection remains open and waiting to serve the next matching db2_pconnect() request.

Users running version 1.9.0 or later of ibm_db2 should be aware that the extension will perform a transaction rollback on persistent connections at the end of a request, thus ending the transaction. This prevents the transaction block from carrying over to the next request which uses that connection if script execution ends before the transaction block does.

Parametry

database

The database alias in the DB2 client catalog.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.

Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.

DB2_ATTR_CASE

Passing the DB2_CASE_NATURAL value specifies that column names are returned in natural case.

Passing the DB2_CASE_LOWER value specifies that column names are returned in lower case.

Passing the DB2_CASE_UPPER value specifies that column names are returned in upper case.

CURSOR

Passing the DB2_FORWARD_ONLY value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.

Passing the DB2_SCROLLABLE value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

The following new option is available in ibm_db2 version 1.7.0 and later.

trustedcontext

Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option().

This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection.

To catalog the database, use following commands:

db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
db2 "update dbm cfg using svcename <SERVICENAME>"
db2set DB2COMM=TCPIP

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

Wskazówka

Conflicting connection attributes used in conjunction with persistent connections can produce indeterminate results on i5/OS. Site policies should be establish for all applications using each persistent connection user profile. The default DB2_AUTOCOMMIT_ON is suggested when using persistent connections.

i5_lib

A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.

i5_naming

DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job.

DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.

i5_commit

The i5_commit attribute should be set before the db2_pconnect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_pconnect() for the connection handle.

Informacja:

The php.ini setting ibm_db2.i5_allow_commit==0 or DB2_I5_TXN_NO_COMMIT is the default, but may be overridden with the i5_commit option.

DB2_I5_TXN_NO_COMMIT - Commitment control is not used.

DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads, nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_READ_COMMITTED - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_REPEATABLE_READ - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible.

DB2_I5_TXN_SERIALIZABLE - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible

i5_query_optimize

DB2_FIRST_IO All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause.

DB2_ALL_IO All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.

i5_dbcs_alloc

DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation scheme for DBCS translation column size growth.

DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X allocation scheme for DBCS translation column size growth.

Informacja:

The php.ini setting ibm_db2.i5_dbcs_alloc==0 or DB2_I5_DBCS_ALLOC_OFF is the default, but may be overridden with the i5_dbcs_alloc option.

i5_date_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default.

DB2_I5_FMT_USA - The United States date format mm/dd/yyyy is used.

DB2_I5_FMT_EUR - The European date format dd.mm.yyyy is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard date format yyyy-mm-dd is used.

DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.

DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.

DB2_I5_FMT_YMD - The date format yy/mm/dd is used.

DB2_I5_FMT_JUL - The Julian date format yy/ddd is used.

DB2_I5_FMT_JOB - The job default is used.

i5_date_sep

DB2_I5_SEP_SLASH - A slash ( / ) is used as the date separator. This is the default.

DB2_I5_SEP_DASH - A dash ( - ) is used as the date separator.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the date separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the date separator.

DB2_I5_SEP_BLANK - A blank is used as the date separator.

DB2_I5_SEP_JOB - The job default is used

i5_time_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default.

DB2_I5_FMT_USA - The United States time format hh:mmxx is used, where xx is AM or PM.

DB2_I5_FMT_EUR - The European time format hh.mm.ss is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard time format hh:mm:ss is used.

DB2_I5_FMT_HMS - The hh:mm:ss format is used.

i5_time_sep

DB2_I5_SEP_COLON - A colon ( : ) is used as the time separator. This is the default.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the time separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the time separator.

DB2_I5_SEP_BLANK - A blank is used as the time separator.

DB2_I5_SEP_JOB - The job default is used.

i5_decimal_sep

DB2_I5_SEP_PERIOD - A period ( . ) is used as the decimal separator. This is the default.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the decimal separator.

DB2_I5_SEP_JOB - The job default is used.

The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

i5_libl

A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

Informacja:

i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

Zwracane wartości

Returns a connection handle resource if the connection attempt is successful. db2_pconnect() tries to reuse an existing connection resource that exactly matches the database, username, and password parameters. If the connection attempt fails, db2_pconnect() returns FALSE.

Rejestr zmian

Wersja | Opis
ibm_db2 1.9.0 | Active transactions within a persistent connection will be rolled back at the end of each request.
ibm_db2 1.8.0 | The i5_libl option is available for i5/OS users.
ibm_db2 1.7.0 | The trustedcontext option is available.
ibm_db2 1.5.1 | The i5_lib, i5_naming, i5_commit, i5_query_optimize, i5_dbcs_alloc, i5_date_fmt, i5_date_sep, i5_time_fmt, i5_time_sep and i5_decimal_sep options are available for i5/OS users.

Przykłady

Przykład #1 A db2_pconnect() example

In the following example, the first call to db2_pconnect() returns a new persistent connection resource. The second call to db2_pconnect() returns a persistent connection resource that simply reuses the first persistent connection resource.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$pconn = db2_pconnect($database, $user, $password);

if ($pconn) {
    echo "Persistent connection succeeded.";
}
else {
    echo "Persistent connection failed.";
}

$pconn2 = db2_pconnect($database, $user, $password);
if ($pconn) {
    echo "Second persistent connection succeeded.";
}
else {
    echo "Second persistent connection failed.";
}
?>

Powyższy przykład wyświetli:

Persistent connection succeeded.
Second persistent connection succeeded.

Przykład #2 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
  PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_pconnect($dsn, "", "", $options);
if($tc_conn) {
    echo "Explicit trusted connection succeeded.\n";

    if(db2_get_option($tc_conn, "trustedcontext")) {
        $userBefore = db2_get_option($tc_conn, "trusted_user");

        //Do some work as user 1.

        //Switching to trusted user.
        $parameters = array("trusted_user" => $tc_user,
          "trusted_password" => $tcuser_pass);
        $res = db2_set_option ($tc_conn, $parameters, 1);

        $userAfter = db2_get_option($tc_conn, "trusted_user");
        //Do more work as trusted user.

        if($userBefore != $userAfter) {
            echo "User has been switched." . "\n";
        }
    }

    db2_close($tc_conn);
}
else {
    echo "Explicit trusted connection failed.\n";
}
?>

Powyższy przykład wyświetli:

Explicit trusted connection succeeded.
User has been switched.

Zobacz też:

  • db2_connect() - Returns a connection to a database

db2_pclose
db2_prepare
IBM DB2 Funkcje


Prepares an SQL statement to be executed

db2_pconnect
db2_primary_keys
IBM DB2 Funkcje
PHP Manual

db2_prepare

(PECL ibm_db2 >= 1.0.0)

db2_prepare — Prepares an SQL statement to be executed

Opis

resource db2_prepare ( resource $connection , string $statement [, array $options ] )

db2_prepare() creates a prepared SQL statement which can include 0 or more parameter markers (? characters) representing parameters for input, output, or input/output. You can pass parameters to the prepared statement using db2_bind_param(), or for input values only, as an array passed to db2_execute().

There are three main advantages to using prepared statements in your application:

  • Performance: when you prepare a statement, the database server creates an optimized access plan for retrieving data with that statement. Subsequently issuing the prepared statement with db2_execute() enables the statements to reuse that access plan and avoids the overhead of dynamically creating a new access plan for every statement you issue.

  • Security: when you prepare a statement, you can include parameter markers for input values. When you execute a prepared statement with input values for placeholders, the database server checks each input value to ensure that the type matches the column definition or parameter definition.

  • Advanced functionality: Parameter markers not only enable you to pass input values to prepared SQL statements, they also enable you to retrieve OUT and INOUT parameters from stored procedures using db2_bind_param().

Parametry

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

statement

An SQL statement, optionally containing one or more parameter markers..

options

An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.

For a description of valid statement options, see db2_set_option().

Zwracane wartości

Returns a statement resource if the SQL statement was successfully parsed and prepared by the database server. Returns FALSE if the database server returned an error. You can determine which error was returned by calling db2_stmt_error() or db2_stmt_errormsg().

Przykłady

Przykład #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

<?php
$animals = array(
    array(0, 'cat', 'Pook', 3.2),
    array(1, 'dog', 'Peaches', 12.3),
    array(2, 'horse', 'Smarty', 350.0),
);

$insert = 'INSERT INTO animals (id, breed, name, weight)
    VALUES (?, ?, ?, ?)';
$stmt = db2_prepare($conn, $insert);
if ($stmt) {
    foreach ($animals as $animal) {
        $result = db2_execute($stmt, $animal);
    }
}
?>

Zobacz też:

  • db2_bind_param() - Binds a PHP variable to an SQL statement parameter
  • db2_execute() - Executes a prepared SQL statement
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

db2_pconnect
db2_primary_keys
IBM DB2 Funkcje


Returns a result set listing primary keys for a table

db2_prepare
db2_procedure_columns
IBM DB2 Funkcje
PHP Manual

db2_primary_keys

(PECL ibm_db2 >= 1.0.0)

db2_primary_keys — Returns a result set listing primary keys for a table

Opis

resource db2_primary_keys ( resource $connection , string $qualifier , string $schema , string $table-name )

Returns a result set listing the primary keys for a table.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. If schema is NULL, db2_primary_keys() matches the schema for the current connection.

table-name

The name of the table.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the primary keys for the specified table. The result set is composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema for the table containing the primary key.
TABLE_NAME | Name of the table containing the primary key.
COLUMN_NAME | Name of the column containing the primary key.
KEY_SEQ | 1-indexed position of the column in the key.
PK_NAME | The name of the primary key.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_prepare
db2_procedure_columns
IBM DB2 Funkcje


Returns a result set listing stored procedure parameters

db2_primary_keys
db2_procedures
IBM DB2 Funkcje
PHP Manual

db2_procedure_columns

(PECL ibm_db2 >= 1.0.0)

db2_procedure_columns — Returns a result set listing stored procedure parameters

Opis

resource db2_procedure_columns ( resource $connection , string $qualifier , string $schema , string $procedure , string $parameter )

Returns a result set listing the parameters for one or more stored procedures.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.

procedure

The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.

parameter

The name of the parameter. This parameter accepts a search pattern containing _ and % as wildcards. If this parameter is NULL, all parameters for the specified stored procedures are returned.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the parameters for the stored procedures matching the specified parameters. The rows are composed of the following columns:

Column name | Description
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
COLUMN_NAME | Name of the parameter.
COLUMN_TYPE

An integer value representing the type of the parameter:

Return value | Parameter type
1 (SQL_PARAM_INPUT) | Input (IN) parameter.
2 (SQL_PARAM_INPUT_OUTPUT) | Input/output (INOUT) parameter.
3 (SQL_PARAM_OUTPUT) | Output (OUT) parameter.
DATA_TYPE | The SQL data type for the parameter represented as an integer value.
TYPE_NAME | A string representing the data type for the parameter.
COLUMN_SIZE | An integer value representing the size of the parameter.
BUFFER_LENGTH | Maximum number of bytes necessary to store data for this parameter.
DECIMAL_DIGITS | The scale of the parameter, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the parameter is nullable or not.
REMARKS | Description of the parameter.
COLUMN_DEF | Default value for the parameter.
SQL_DATA_TYPE | An integer value representing the size of the parameter.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type parameter, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the parameter in the CALL statement.
IS_NULLABLE | A string value where 'YES' means that the parameter accepts or returns NULL values and 'NO' means that the parameter does not accept or return NULL values.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_primary_keys
db2_procedures
IBM DB2 Funkcje


Returns a result set listing the stored procedures registered in a database

db2_procedure_columns
db2_result
IBM DB2 Funkcje
PHP Manual

db2_procedures

(PECL ibm_db2 >= 1.0.0)

db2_procedures — Returns a result set listing the stored procedures registered in a database

Opis

resource db2_procedures ( resource $connection , string $qualifier , string $schema , string $procedure )

Returns a result set listing the stored procedures registered in a database.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.

procedure

The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the stored procedures matching the specified parameters. The rows are composed of the following columns:

Column name | Description
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
NUM_INPUT_PARAMS | Number of input (IN) parameters for the stored procedure.
NUM_OUTPUT_PARAMS | Number of output (OUT) parameters for the stored procedure.
NUM_RESULT_SETS | Number of result sets returned by the stored procedure.
REMARKS | Any comments about the stored procedure.
PROCEDURE_TYPE | Always returns 1, indicating that the stored procedure does not return a return value.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_procedure_columns
db2_result
IBM DB2 Funkcje


Returns a single column from a row in the result set

db2_procedures
db2_rollback
IBM DB2 Funkcje
PHP Manual

db2_result

(PECL ibm_db2 >= 1.0.0)

db2_result — Returns a single column from a row in the result set

Opis

mixed db2_result ( resource $stmt , mixed $column )

Use db2_result() to return the value of a specified column in the current row of a result set. You must call db2_fetch_row() before calling db2_result() to set the location of the result set pointer.

Parametry

stmt

A valid stmt resource.

column

Either an integer mapping to the 0-indexed field in the result set, or a string matching the name of the column.

Zwracane wartości

Returns the value of the requested field if the field exists in the result set. Returns NULL if the field does not exist, and issues a warning.

Przykłady

Przykład #1 A db2_result() example

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
    $name = db2_result($stmt, 0);
    $breed = db2_result($stmt, 'BREED');
    print "$name $breed";
}
?>

Powyższy przykład wyświetli:

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

Zobacz też:

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row

db2_procedures
db2_rollback
IBM DB2 Funkcje


Rolls back a transaction

db2_result
db2_server_info
IBM DB2 Funkcje
PHP Manual

db2_rollback

(PECL ibm_db2 >= 1.0.0)

db2_rollback — Rolls back a transaction

Opis

bool db2_rollback ( resource $connection )

Rolls back an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_rollback() normally has no effect unless AUTOCOMMIT has been turned off for the connection resource.

Parametry

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Rolling back a DELETE statement

In the following example, we count the number of rows in a table, turn off AUTOCOMMIT mode on a database connection, delete all of the rows in the table and return the count of 0 to prove that the rows have been removed. We then issue db2_rollback() and return the updated count of rows in the table to show that the number is the same as before we issued the DELETE statement. The return to the original state of the table demonstrates that the roll back of the transaction succeeded.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
    $stmt = db2_exec($conn, "SELECT count(*) FROM animals");
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";

    // Turn AUTOCOMMIT off
    db2_autocommit($conn, DB2_AUTOCOMMIT_OFF);

    // Delete all rows from ANIMALS
    db2_exec($conn, "DELETE FROM animals");

    $stmt = db2_exec($conn, "SELECT count(*) FROM animals");
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";

    // Roll back the DELETE statement
    db2_rollback( $conn );

    $stmt = db2_exec( $conn, "SELECT count(*) FROM animals" );
    $res = db2_fetch_array( $stmt );
    echo $res[0] . "\n";
    db2_close($conn);
}
?>

Powyższy przykład wyświetli:

7
0
7

Zobacz też:

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_commit() - Commits a transaction

db2_result
db2_server_info
IBM DB2 Funkcje


Returns an object with properties that describe the DB2 database server

db2_rollback
db2_set_option
IBM DB2 Funkcje
PHP Manual

db2_server_info

(PECL ibm_db2 >= 1.1.1)

db2_server_info — Returns an object with properties that describe the DB2 database server

Opis

object db2_server_info ( resource $connection )

This function returns an object with read-only properties that return information about the IBM DB2, Cloudscape, or Apache Derby database server. The following table lists the database server properties:

Database server properties
Property name | Return type | Description
DBMS_NAME | string | The name of the database server to which you are connected. For DB2 servers this is a combination of DB2 followed by the operating system on which the database server is running.
DBMS_VER | string | The version of the database server, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
DB_CODEPAGE | int | The code page of the database to which you are connected.
DB_NAME | string | The name of the database to which you are connected.
DFT_ISOLATION string

The default transaction isolation level supported by the server:

UR

Uncommitted read: changes are immediately visible by all concurrent transactions.

CS

Cursor stability: a row read by one transaction can be altered and committed by a second concurrent transaction.

RS

Read stability: a transaction can add or remove rows matching a search condition or a pending transaction.

RR

Repeatable read: data affected by pending transaction is not available to other transactions.

NC

No commit: any changes are visible at the end of a successful operation. Explicit commits and rollbacks are not allowed.

IDENTIFIER_QUOTE_CHAR | string | The character used to delimit an identifier.
INST_NAME | string | The instance on the database server that contains the database.
ISOLATION_OPTION | array | An array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property.
KEYWORDS | array | An array of the keywords reserved by the database server.
LIKE_ESCAPE_CLAUSE | bool | TRUE if the database server supports the use of % and _ wildcard characters. FALSE if the database server does not support these wildcard characters.
MAX_COL_NAME_LEN | int | Maximum length of a column name supported by the database server, expressed in bytes.
MAX_IDENTIFIER_LEN | int | Maximum length of an SQL identifier supported by the database server, expressed in characters.
MAX_INDEX_SIZE | int | Maximum size of columns combined in an index supported by the database server, expressed in bytes.
MAX_PROC_NAME_LEN | int | Maximum length of a procedure name supported by the database server, expressed in bytes.
MAX_ROW_SIZE | int | Maximum length of a row in a base table supported by the database server, expressed in bytes.
MAX_SCHEMA_NAME_LEN | int | Maximum length of a schema name supported by the database server, expressed in bytes.
MAX_STATEMENT_LEN | int | Maximum length of an SQL statement supported by the database server, expressed in bytes.
MAX_TABLE_NAME_LEN | int | Maximum length of a table name supported by the database server, expressed in bytes.
NON_NULLABLE_COLUMNS | bool | TRUE if the database server supports columns that can be defined as NOT NULL, FALSE if the database server does not support columns defined as NOT NULL.
PROCEDURES | bool | TRUE if the database server supports the use of the CALL statement to call stored procedures, FALSE if the database server does not support the CALL statement.
SPECIAL_CHARS | string | A string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name.
SQL_CONFORMANCE string

The level of conformance to the ANSI/ISO SQL-92 specification offered by the database server:

ENTRY

Entry-level SQL-92 compliance.

FIPS127

FIPS-127-2 transitional compliance.

FULL

Full level SQL-92 compliance.

INTERMEDIATE

Intermediate level SQL-92 compliance.

Parametry

connection

Specifies an active DB2 client connection.

Zwracane wartości

Returns an object on a successful call. Returns FALSE on failure.

Przykłady

Przykład #1 A db2_server_info() example

To retrieve information about the server, you must pass a valid database connection resource to db2_server_info().

<?php

$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');

$server = db2_server_info( $conn );

if ($server) {
    echo "DBMS_NAME: ";                 var_dump( $server->DBMS_NAME );
    echo "DBMS_VER: ";                  var_dump( $server->DBMS_VER );
    echo "DB_CODEPAGE: ";               var_dump( $server->DB_CODEPAGE );
    echo "DB_NAME: ";                   var_dump( $server->DB_NAME );
    echo "INST_NAME: ";                 var_dump( $server->INST_NAME );
    echo "SPECIAL_CHARS: ";             var_dump( $server->SPECIAL_CHARS );
    echo "KEYWORDS: ";                  var_dump( sizeof($server->KEYWORDS) );
    echo "DFT_ISOLATION: ";             var_dump( $server->DFT_ISOLATION );
    echo "ISOLATION_OPTION: ";
    $il = '';
    foreach( $server->ISOLATION_OPTION as $opt )
    {
       $il .= $opt." ";
    }
    var_dump( $il );
    echo "SQL_CONFORMANCE: ";           var_dump( $server->SQL_CONFORMANCE );
    echo "PROCEDURES: ";                var_dump( $server->PROCEDURES );
    echo "IDENTIFIER_QUOTE_CHAR: ";     var_dump( $server->IDENTIFIER_QUOTE_CHAR );
    echo "LIKE_ESCAPE_CLAUSE: ";        var_dump( $server->LIKE_ESCAPE_CLAUSE );
    echo "MAX_COL_NAME_LEN: ";          var_dump( $server->MAX_COL_NAME_LEN );
    echo "MAX_ROW_SIZE: ";              var_dump( $server->MAX_ROW_SIZE );
    echo "MAX_IDENTIFIER_LEN: ";        var_dump( $server->MAX_IDENTIFIER_LEN );
    echo "MAX_INDEX_SIZE: ";            var_dump( $server->MAX_INDEX_SIZE );
    echo "MAX_PROC_NAME_LEN: ";         var_dump( $server->MAX_PROC_NAME_LEN );
    echo "MAX_SCHEMA_NAME_LEN: ";       var_dump( $server->MAX_SCHEMA_NAME_LEN );
    echo "MAX_STATEMENT_LEN: ";         var_dump( $server->MAX_STATEMENT_LEN );
    echo "MAX_TABLE_NAME_LEN: ";        var_dump( $server->MAX_TABLE_NAME_LEN );
    echo "NON_NULLABLE_COLUMNS: ";      var_dump( $server->NON_NULLABLE_COLUMNS );

    db2_close($conn);
}
?>

Powyższy przykład wyświetli:

DBMS_NAME: string(9) "DB2/LINUX"
DBMS_VER: string(10) "08.02.0000"
DB_CODEPAGE: int(1208)
DB_NAME: string(6) "SAMPLE"
INST_NAME: string(8) "db2inst1"
SPECIAL_CHARS: string(2) "@#"
KEYWORDS: int(179)
DFT_ISOLATION: string(2) "CS"
ISOLATION_OPTION: string(12) "UR CS RS RR "
SQL_CONFORMANCE: string(7) "FIPS127"
PROCEDURES: bool(true)
IDENTIFIER_QUOTE_CHAR: string(1) """
LIKE_ESCAPE_CLAUSE: bool(true)
MAX_COL_NAME_LEN: int(30)
MAX_ROW_SIZE: int(32677)
MAX_IDENTIFIER_LEN: int(18)
MAX_INDEX_SIZE: int(1024)
MAX_PROC_NAME_LEN: int(128)
MAX_SCHEMA_NAME_LEN: int(30)
MAX_STATEMENT_LEN: int(2097152)
MAX_TABLE_NAME_LEN: int(128)
NON_NULLABLE_COLUMNS: bool(true)

Zobacz też:

  • db2_client_info() - Returns an object with properties that describe the DB2 database client

db2_rollback
db2_set_option
IBM DB2 Funkcje


Set options for connection or statement resources

db2_server_info
db2_special_columns
IBM DB2 Funkcje
PHP Manual

db2_set_option

(PECL ibm_db2 >= 1.0.0)

db2_set_option — Set options for connection or statement resources

Opis

bool db2_set_option ( resource $resource , array $options , int $type )

Sets options for a statement resource or a connection resource. You cannot set options for result set resources.

Parametry

resource

A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().

options

An associative array containing valid statement or connection options. This parameter can be used to change autocommit values, cursor types (scrollable or forward), and to specify the case of the column names (lower, upper, or natural) that will appear in a result set.

autocommit

Passing DB2_AUTOCOMMIT_ON turns autocommit on for the specified connection resource.

Passing DB2_AUTOCOMMIT_OFF turns autocommit off for the specified connection resource.

cursor

Passing DB2_FORWARD_ONLY specifies a forward-only cursor for a statement resource. This is the default cursor type, and is supported by all database servers.

Passing DB2_SCROLLABLE specifies a scrollable cursor for a statement resource. Scrollable cursors enable result set rows to be accessed in non-sequential order, but are only supported by IBM DB2 Universal Database databases.

binmode

Passing DB2_BINARY specifies that binary data will be returned as is. This is the default mode. This is the equivalent of setting ibm_db2.binmode=1 in php.ini.

Passing DB2_CONVERT specifies that binary data will be converted to hexadecimal encoding, and will be returned as such. This is the equivalent of setting ibm_db2.binmode=2 in php.ini.

Passing DB2_PASSTHRU specifies that binary data will be converted to NULL. This is the equivalent of setting ibm_db2.binmode=3 in php.ini.

db2_attr_case

Passing DB2_CASE_LOWER specifies that column names of the result set are returned in lower case.

Passing DB2_CASE_UPPER specifies that column names of the result set are returned in upper case.

Passing DB2_CASE_NATURAL specifies that column names of the result set are returned in natural case.

deferred_prepare

Passing DB2_DEFERRED_PREPARE_ON turns deferred prepare on for the specified statement resource.

Passing DB2_DEFERRED_PREPARE_OFF turns deferred prepare off for the specified statement resource.

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later. These options apply only when running PHP and ibm_db2 natively on i5 systems.

i5_fetch_only

DB2_I5_FETCH_ON - Cursors are read-only and cannot be used for positioned updates or deletes. This is the default unless SQL_ATTR_FOR_FETCH_ONLY environment has been set to SQL_FALSE.

DB2_I5_FETCH_OFF - Cursors can be used for positioned updates and deletes.

The following new option is available in ibm_db2 version 1.8.0 and later.

rowcount

DB2_ROWCOUNT_PREFETCH_ON - Client can request the full row count prior to fetching, which means that db2_num_rows() returns the number of rows selected even when a ROLLFORWARD_ONLY cursor is used.

DB2_ROWCOUNT_PREFETCH_OFF - Client cannot request the full row count prior to fetching.

The following new options are available in ibm_db2 version 1.7.0 and later.

trusted_user

To switch the user to a trusted user, pass the User ID (String) of the trusted user as the value of this key. This option can be set on a connection resource only. To use this option, trusted context must be enabled on the connection resource.

trusted_password

The password (String) that corresponds to the user specified by the trusted_user key.

The following new options are available in ibm_db2 version 1.6.0 and later. These options provide useful tracking information that can be accessed during execution with db2_get_option().

Informacja:

When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value.

To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

userid

SQL_ATTR_INFO_USERID - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

Informacja:

DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

acctstr

SQL_ATTR_INFO_ACCTSTR - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

Informacja:

DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

applname

SQL_ATTR_INFO_APPLNAME - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

Informacja:

DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

wrkstnname

SQL_ATTR_INFO_WRKSTNNAME - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

Informacja:

DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

type

An integer value that specifies the type of resource that was passed into the function. The type of resource and this value must correspond.

Passing 1 as the value specifies that a connection resource has been passed into the function.

Passing any integer not equal to 1 as the value specifies that a statement resource has been passed into the function.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
 |  | Connection | Statement | Result Set
autocommit | DB2_AUTOCOMMIT_ON | X | - | -
autocommit | DB2_AUTOCOMMIT_OFF | X | - | -
cursor | DB2_SCROLLABLE | - | X | -
cursor | DB2_FORWARD_ONLY | - | X | -
binmode | DB2_BINARY | X | X | -
binmode | DB2_CONVERT | X | X | -
binmode | DB2_PASSTHRU | X | X | -
db2_attr_case | DB2_CASE_LOWER | X | X | -
db2_attr_case | DB2_CASE_UPPER | X | X | -
db2_attr_case | DB2_CASE_NATURAL | X | X | -
deferred_prepare | DB2_DEFERRED_PREPARE_ON | - | X | -
deferred_prepare | DB2_DEFERRED_PREPARE_OFF | - | X | -
i5_fetch_only | DB2_I5_FETCH_ON | - | X | -
i5_fetch_only | DB2_I5_FETCH_OFF | - | X | -
rowcount | DB2_ROWCOUNT_PREFETCH_ON | - | X | -
rowcount | DB2_ROWCOUNT_PREFETCH_OFF | - | X | -
trusted_user | <USER NAME> (String) | X | - | -
trusted_password | <PASSWORD> (String) | X | - | -
userid | SQL_ATTR_INFO_USERID | X | X | -
acctstr | SQL_ATTR_INFO_ACCTSTR | X | X | -
applname | SQL_ATTR_INFO_APPLNAME | X | X | -
wrkstnname | SQL_ATTR_INFO_WRKSTNNAME | X | X | -

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Setting one parameter with a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_ON);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

Powyższy przykład wyświetli:

Options Set Successfully

Przykład #2 Setting multiple parameters with a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

Powyższy przykład wyświetli:

Options Set Successfully

Przykład #3 Setting multiple parameters with an invalid key

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
             'MY_INVALID_KEY' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

Powyższy przykład wyświetli:

Could Not Set Options

Przykład #4 Setting multiple parameters with an invalid value

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => 'INVALID_VALUE',
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

Powyższy przykład wyświetli:

Could Not Set Options

Przykład #5 Setting multiple parameters with a connection resource and the wrong type

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and the wrong type value */
$result = db2_set_option($conn, $options, 2);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

Powyższy przykład wyświetli:

Could Not Set Options

Przykład #6 Setting multiple parameters with the wrong resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
                    'binmode' => DB2_PASSTHRU,
              'db2_attr_case' => DB2_CASE_UPPER,
                     'cursor' => DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE');

/* Call the function using the wrong resource, and the correct options array, and type values */
$result = db2_set_option($stmt, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
  echo 'Options Set Successfully';
}
else
{
  echo 'Could Not Set Options';
}
?>

Powyższy przykład wyświetli:

Could Not Set Options

Przykład #7 Putting it all together

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('db2_attr_case' => DB2_CASE_LOWER,
                        'cursor' => DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE WHERE EMPNO = ? OR EMPNO = ?');

/* Call the function using the correct resource, options array, and type values */
$option_result = db2_set_option($stmt, $options, 2);
$result = db2_execute($stmt, array('000130', '000140'));

/* Get Row 2 before Row 1 since Scrollable Cursor */
print_r(db2_fetch_assoc($stmt, 2));
print '<br /><br />';
print_r(db2_fetch_assoc($stmt, 1));

?>

Powyższy przykład wyświetli:

Array
(
    [empno] => 000140
    [firstnme] => HEATHER
    [midinit] => A
    [lastname] => NICHOLLS
    [workdept] => C01
    [phoneno] => 1793
    [hiredate] => 1976-12-15
    [job] => ANALYST
    [edlevel] => 18
    [sex] => F
    [birthdate] => 1946-01-19
    [salary] => 28420.00
    [bonus] => 600.00
    [comm] => 2274.00
)

Array
(
    [empno] => 000130
    [firstnme] => DELORES
    [midinit] => M
    [lastname] => QUINTANA
    [workdept] => C01
    [phoneno] => 4578
    [hiredate] => 1971-07-28
    [job] => ANALYST
    [edlevel] => 16
    [sex] => F
    [birthdate] => 1925-09-15
    [salary] => 23800.00
    [bonus] => 500.00
    [comm] => 1904.00
)

Przykład #8 i5/OS cursors are read-only

<?php
  $conn = db2_connect("", "", "", array("i5_lib"=>"nobody"));
  $stmt = db2_prepare($conn, 'select * from names where first = ?');
  $name = "first2";
  db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
  $options = array("i5_fetch_only"=>DB2_I5_FETCH_ON);
  db2_set_option($stmt,$options,0);
  if (db2_execute($stmt)) {
    while ($row = db2_fetch_array($stmt)) {
      echo "{$row[0]} {$row[1]}";
    }
  }
?>

Powyższy przykład wyświetli:

first2 last2

Zobacz też:

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database
  • db2_exec() - Executes an SQL statement directly
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_cursor_type() - Returns the cursor type used by a statement resource

db2_server_info
db2_special_columns
IBM DB2 Funkcje


Returns a result set listing the unique row identifier columns for a table

db2_set_option
db2_statistics
IBM DB2 Funkcje
PHP Manual

db2_special_columns

(PECL ibm_db2 >= 1.0.0)

db2_special_columns — Returns a result set listing the unique row identifier columns for a table

Opis

resource db2_special_columns ( resource $connection , string $qualifier , string $schema , string $table_name , int $scope )

Returns a result set listing the unique row identifier columns for a table.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables.

table_name

The name of the table.

scope

Integer value representing the minimum duration for which the unique row identifier is valid. This can be one of the following values:

Integer value | SQL constant | Description
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.

Zwracane wartości

Returns a statement resource with a result set containing rows with unique row identifier information for a table. The rows are composed of the following columns:

Column name | Description
SCOPE

Integer value | SQL constant | Description
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.
COLUMN_NAME | Name of the unique column.
DATA_TYPE | SQL data type for the column.
TYPE_NAME | Character string representation of the SQL data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable).
PSEUDO_COLUMN | Always returns 1.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_set_option
db2_statistics
IBM DB2 Funkcje


Returns a result set listing the index and statistics for a table

db2_special_columns
db2_stmt_error
IBM DB2 Funkcje
PHP Manual

db2_statistics

(PECL ibm_db2 >= 1.0.0)

db2_statistics — Returns a result set listing the index and statistics for a table

Opis

resource db2_statistics ( resource $connection , string $qualifier , string $schema , string $table-name , bool $unique )

Returns a result set listing the index and statistics for a table.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema that contains the targeted table. If this parameter is NULL, the statistics and indexes are returned for the schema of the current user.

table_name

The name of the table.

unique

An integer value representing the type of index information to return.

0

Return only the information for unique indexes on the table.

1

Return the information for all indexes on the table.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the statistics and indexes for the base tables matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
NON_UNIQUE

An integer value representing whether the index prohibits unique values, or whether the row represents statistics on the table itself:

Return value | Parameter type
0 (SQL_FALSE) | The index allows duplicate values.
1 (SQL_TRUE) | The index values must be unique.
NULL | This row is statistics information for the table itself.
INDEX_QUALIFIER | A string value representing the qualifier that would have to be prepended to INDEX_NAME to fully qualify the index.
INDEX_NAME | A string representing the name of the index.
TYPE

An integer value representing the type of information contained in this row of the result set:

Return value | Parameter type
0 (SQL_TABLE_STAT) | The row contains statistics about the table itself.
1 (SQL_INDEX_CLUSTERED) | The row contains information about a clustered index.
2 (SQL_INDEX_HASH) | The row contains information about a hashed index.
3 (SQL_INDEX_OTHER) | The row contains information about a type of index that is neither clustered nor hashed.
ORDINAL_POSITION | The 1-indexed position of the column in the index. NULL if the row contains statistics information about the table itself.
COLUMN_NAME | The name of the column in the index. NULL if the row contains statistics information about the table itself.
ASC_OR_DESC | A if the column is sorted in ascending order, D if the column is sorted in descending order, NULL if the row contains statistics information about the table itself.
CARDINALITY

If the row contains information about an index, this column contains an integer value representing the number of unique values in the index.

If the row contains information about the table itself, this column contains an integer value representing the number of rows in the table.

PAGES

If the row contains information about an index, this column contains an integer value representing the number of pages used to store the index.

If the row contains information about the table itself, this column contains an integer value representing the number of pages used to store the table.

FILTER_CONDITION | Always returns NULL.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_special_columns
db2_stmt_error
IBM DB2 Funkcje


Returns a string containing the SQLSTATE returned by an SQL statement

db2_statistics
db2_stmt_errormsg
IBM DB2 Funkcje
PHP Manual

db2_stmt_error

(PECL ibm_db2 >= 1.0.0)

db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement

Opis

string db2_stmt_error ([ resource $stmt ] )

Returns a string containing the SQLSTATE value returned by an SQL statement.

If you do not pass a statement resource as an argument to db2_stmt_error(), the driver returns the SQLSTATE value associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_stmt_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

Parametry

stmt

A valid statement resource.

Zwracane wartości

Returns a string containing an SQLSTATE value.

Zobacz też:

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

db2_statistics
db2_stmt_errormsg
IBM DB2 Funkcje


Returns a string containing the last SQL statement error message

db2_stmt_error
db2_table_privileges
IBM DB2 Funkcje
PHP Manual

db2_stmt_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_stmt_errormsg — Returns a string containing the last SQL statement error message

Opis

string db2_stmt_errormsg ([ resource $stmt ] )

Returns a string containing the last SQL statement error message.

If you do not pass a statement resource as an argument to db2_stmt_errormsg(), the driver returns the error message associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

Parametry

stmt

A valid statement resource.

Zwracane wartości

Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.

Zobacz też:

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement

db2_stmt_error
db2_table_privileges
IBM DB2 Funkcje


Returns a result set listing the tables and associated privileges in a database

db2_stmt_errormsg
db2_tables
IBM DB2 Funkcje
PHP Manual

db2_table_privileges

(PECL ibm_db2 >= 1.0.0)

db2_table_privileges — Returns a result set listing the tables and associated privileges in a database

Opis

resource db2_table_privileges ( resource $connection [, string $qualifier [, string $schema [, string $table_name ]]] )

Returns a result set listing the tables and associated privileges in a database.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.

table_name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the privileges for the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege that has been granted. This can be one of ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, or UPDATE.
IS_GRANTABLE | A string value of "YES" or "NO" indicating whether the grantee can grant the privilege to other users.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

db2_stmt_errormsg
db2_tables
IBM DB2 Funkcje


Returns a result set listing the tables and associated metadata in a database

db2_table_privileges
Informix
IBM DB2 Funkcje
PHP Manual

db2_tables

(PECL ibm_db2 >= 1.0.0)

db2_tables — Returns a result set listing the tables and associated metadata in a database

Opis

resource db2_tables ( resource $connection [, string $qualifier [, string $schema [, string $table-name [, string $table-type ]]]] )

Returns a result set listing the tables and associated metadata in a database.

Parametry

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.

schema

The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.

table-name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

table-type

A list of comma-delimited table type identifiers. To match all table types, pass NULL or an empty string. Valid table type identifiers include: ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW, NICKNAME, MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE, TYPED TABLE, TYPED VIEW, and VIEW.

Zwracane wartości

Returns a statement resource with a result set containing rows describing the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
TABLE_TYPE | Table type identifier for the table.
REMARKS | Description of the table.

Zobacz też:

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database

db2_table_privileges
Informix
IBM DB2 Funkcje


Informix

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Informix Funkcje
    • ifx_affected_rows — Get number of rows affected by a query
    • ifx_blobinfile_mode — Set the default blob mode for all select queries
    • ifx_byteasvarchar — Set the default byte mode
    • ifx_close — Close Informix connection
    • ifx_connect — Open Informix server connection
    • ifx_copy_blob — Duplicates the given blob object
    • ifx_create_blob — Creates an blob object
    • ifx_create_char — Creates an char object
    • ifx_do — Execute a previously prepared SQL-statement
    • ifx_error — Returns error code of last Informix call
    • ifx_errormsg — Returns error message of last Informix call
    • ifx_fetch_row — Get row as an associative array
    • ifx_fieldproperties — List of SQL fieldproperties
    • ifx_fieldtypes — List of Informix SQL fields
    • ifx_free_blob — Deletes the blob object
    • ifx_free_char — Deletes the char object
    • ifx_free_result — Releases resources for the query
    • ifx_get_blob — Return the content of a blob object
    • ifx_get_char — Return the content of the char object
    • ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query
    • ifx_htmltbl_result — Formats all rows of a query into a HTML table
    • ifx_nullformat — Sets the default return value on a fetch row
    • ifx_num_fields — Returns the number of columns in the query
    • ifx_num_rows — Count the rows already fetched from a query
    • ifx_pconnect — Open persistent Informix connection
    • ifx_prepare — Prepare an SQL-statement for execution
    • ifx_query — Send Informix query
    • ifx_textasvarchar — Set the default text mode
    • ifx_update_blob — Updates the content of the blob object
    • ifx_update_char — Updates the content of the char object
    • ifxus_close_slob — Deletes the slob object
    • ifxus_create_slob — Creates an slob object and opens it
    • ifxus_free_slob — Deletes the slob object
    • ifxus_open_slob — Opens an slob object
    • ifxus_read_slob — Reads nbytes of the slob object
    • ifxus_seek_slob — Sets the current file or seek position
    • ifxus_tell_slob — Returns the current file or seek position
    • ifxus_write_slob — Writes a string into the slob object
db2_tables
Wstęp
Rozszerzenia producentów baz danych


Wstęp

The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php_informix.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.2.1.

Informix
Instalacja/Konfiguracja
Informix


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Informix


Wymagania

Informacja: Configuration notes

You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.

Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with-informix[=DIR] , where DIR is the Informix base install directory, defaults to nothing.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Informacja:

Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo() before you start testing. The phpinfo() output should list these environment variables. This is true for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.

The Informix shared libraries should also be available to the loader (check LD_LIBRARY_PATH or ld.so.conf/ldconfig).

Informacja: Some notes on the use of BLOBs (TEXT and BYTE columns)

BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with: "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.

For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().

The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime:

configuration variable: ifx.textasvarchar

configuration variable: ifx.byteasvarchar

runtime functions:

ifx_textasvarchar(0): use blob id's for select queries with TEXT columns

ifx_byteasvarchar(0): use blob id's for select queries with BYTE columns

ifx_textasvarchar(1): return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

ifx_byteasvarchar(1): return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

configuration variable: ifx.blobinfile

runtime function:

ifx_blobinfile_mode(0): return BYTE columns in memory, the blob id lets you get at the contents.

ifx_blobinfile_mode(1): return BYTE columns in a file, the blob id lets you get at the file name.

If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.

If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.

The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like: putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").

Informacja: Automatically trimming "char" (SQLCHAR and SQLNCHAR) data

This can be set with the configuration variable

ifx.charasvarchar: if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".

Informacja: NULL values

The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.

Informix configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_links | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_host | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_user | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_password | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.blobinfile | "1" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.textasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.byteasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.charasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.nullformat | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
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.

ifx.allow_persistent boolean

Whether to allow persistent Informix connections.

ifx.max_persistent integer

The maximum number of persistent Informix connections per process.

ifx.max_links integer

The maximum number of Informix connections per process, including persistent connections.

ifx.default_host string

The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in tryb bezpieczny.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in tryb bezpieczny.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in tryb bezpieczny.

ifx.blobinfile boolean

Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().

ifx.textasvarchar boolean

Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.byteasvarchar boolean

Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.charasvarchar boolean

Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.

ifx.nullformat boolean

Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

IFX_SCROLL (integer)
IFX_HOLD (integer)
IFX_LO_RDONLY (integer)
IFX_LO_WRONLY (integer)
IFX_LO_APPEND (integer)
IFX_LO_RDWR (integer)
IFX_LO_BUFFER (integer)
IFX_LO_NOBUFFER (integer)
Typy zasobów
Informix Funkcje
Informix


Informix Funkcje

Spis treści

  • ifx_affected_rows — Get number of rows affected by a query
  • ifx_blobinfile_mode — Set the default blob mode for all select queries
  • ifx_byteasvarchar — Set the default byte mode
  • ifx_close — Close Informix connection
  • ifx_connect — Open Informix server connection
  • ifx_copy_blob — Duplicates the given blob object
  • ifx_create_blob — Creates an blob object
  • ifx_create_char — Creates an char object
  • ifx_do — Execute a previously prepared SQL-statement
  • ifx_error — Returns error code of last Informix call
  • ifx_errormsg — Returns error message of last Informix call
  • ifx_fetch_row — Get row as an associative array
  • ifx_fieldproperties — List of SQL fieldproperties
  • ifx_fieldtypes — List of Informix SQL fields
  • ifx_free_blob — Deletes the blob object
  • ifx_free_char — Deletes the char object
  • ifx_free_result — Releases resources for the query
  • ifx_get_blob — Return the content of a blob object
  • ifx_get_char — Return the content of the char object
  • ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query
  • ifx_htmltbl_result — Formats all rows of a query into a HTML table
  • ifx_nullformat — Sets the default return value on a fetch row
  • ifx_num_fields — Returns the number of columns in the query
  • ifx_num_rows — Count the rows already fetched from a query
  • ifx_pconnect — Open persistent Informix connection
  • ifx_prepare — Prepare an SQL-statement for execution
  • ifx_query — Send Informix query
  • ifx_textasvarchar — Set the default text mode
  • ifx_update_blob — Updates the content of the blob object
  • ifx_update_char — Updates the content of the char object
  • ifxus_close_slob — Deletes the slob object
  • ifxus_create_slob — Creates an slob object and opens it
  • ifxus_free_slob — Deletes the slob object
  • ifxus_open_slob — Opens an slob object
  • ifxus_read_slob — Reads nbytes of the slob object
  • ifxus_seek_slob — Sets the current file or seek position
  • ifxus_tell_slob — Returns the current file or seek position
  • ifxus_write_slob — Writes a string into the slob object
Stałe predefiniowane
ifx_affected_rows
Informix


Get number of rows affected by a query

Informix Funkcje
ifx_blobinfile_mode
Informix Funkcje
PHP Manual

ifx_affected_rows

(PHP 4, PHP <=5.2.0)

ifx_affected_rows — Get number of rows affected by a query

Opis

int ifx_affected_rows ( resource $result_id )

Returns the number of rows affected by a query associated with result_id.

For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).

Useful after ifx_prepare() to limit queries to reasonable result sets.

Parametry

result_id

A valid result id returned by ifx_query() or ifx_prepare().

Zwracane wartości

Returns the number of rows as an integer.

Przykłady

Przykład #1 Informix affected rows

<?php
$rid = ifx_prepare("select * from emp
                     where name like " . $name, $connid);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
?>

Zobacz też:

  • ifx_num_rows() - Count the rows already fetched from a query

Informix Funkcje
ifx_blobinfile_mode
Informix Funkcje


Set the default blob mode for all select queries

ifx_affected_rows
ifx_byteasvarchar
Informix Funkcje
PHP Manual

ifx_blobinfile_mode

(PHP 4, PHP <=5.2.0)

ifx_blobinfile_mode — Set the default blob mode for all select queries

Opis

bool ifx_blobinfile_mode ( int $mode )

Set the default blob mode for all select queries.

Parametry

mode

Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ifx_affected_rows
ifx_byteasvarchar
Informix Funkcje


Set the default byte mode

ifx_blobinfile_mode
ifx_close
Informix Funkcje
PHP Manual

ifx_byteasvarchar

(PHP 4, PHP <=5.2.0)

ifx_byteasvarchar — Set the default byte mode

Opis

bool ifx_byteasvarchar ( int $mode )

Sets the default byte mode for all select-queries.

Parametry

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifx_textasvarchar() - Set the default text mode

ifx_blobinfile_mode
ifx_close
Informix Funkcje


Close Informix connection

ifx_byteasvarchar
ifx_connect
Informix Funkcje
PHP Manual

ifx_close

(PHP 4, PHP <=5.2.0)

ifx_close — Close Informix connection

Opis

bool ifx_close ([ resource $link_identifier ] )

ifx_close() closes the link to an Informix database that's associated with the specified link identifier.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ifx_close() will not close persistent links generated by ifx_pconnect().

Parametry

link_identifier

The link identifier. If not specified, the last opened link is assumed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Closing a Informix connection

<?php
$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
/* ... some queries and stuff ... */
ifx_close($conn_id);
?>

Zobacz też:

  • ifx_connect() - Open Informix server connection
  • ifx_pconnect() - Open persistent Informix connection

ifx_byteasvarchar
ifx_connect
Informix Funkcje


Open Informix server connection

ifx_close
ifx_copy_blob
Informix Funkcje
PHP Manual

ifx_connect

(PHP 4, PHP <=5.2.0)

ifx_connect — Open Informix server connection

Opis

resource ifx_connect ([ string $database [, string $userid [, string $password ]]] )

ifx_connect() establishes a connection to an Informix server.

In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().

Parametry

All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php.ini (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

database

The database name, as a string.

userid

The username, as a string.

password

The password, as a string.

Zwracane wartości

Returns a connection identifier on success, or FALSE on error.

Przykłady

Przykład #1 Connect to a Informix database

<?php
$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");
?>

Zobacz też:

  • ifx_pconnect() - Open persistent Informix connection
  • ifx_close() - Close Informix connection

ifx_close
ifx_copy_blob
Informix Funkcje


Duplicates the given blob object

ifx_connect
ifx_create_blob
Informix Funkcje
PHP Manual

ifx_copy_blob

(PHP 4, PHP <=5.2.0)

ifx_copy_blob — Duplicates the given blob object

Opis

int ifx_copy_blob ( int $bid )

Duplicates the given blob object.

Parametry

bid

A BLOB identifier.

Zwracane wartości

Returns the new blob object-id, or FALSE on errors.

Zobacz też:

  • ifx_create_blob() - Creates an blob object
  • ifx_free_blob() - Deletes the blob object

ifx_connect
ifx_create_blob
Informix Funkcje


Creates an blob object

ifx_copy_blob
ifx_create_char
Informix Funkcje
PHP Manual

ifx_create_blob

(PHP 4, PHP <=5.2.0)

ifx_create_blob — Creates an blob object

Opis

int ifx_create_blob ( int $type , int $mode , string $param )

Creates a blob object.

Parametry

type

1 = TEXT, 0 = BYTE

mode

0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.

param

if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.

Zwracane wartości

Returns the new BLOB object-id, or FALSE on errors.

Zobacz też:

  • ifx_copy_blob() - Duplicates the given blob object
  • ifx_free_blob() - Deletes the blob object

ifx_copy_blob
ifx_create_char
Informix Funkcje


Creates an char object

ifx_create_blob
ifx_do
Informix Funkcje
PHP Manual

ifx_create_char

(PHP 4, PHP <=5.2.0)

ifx_create_char — Creates an char object

Opis

int ifx_create_char ( string $param )

Creates an char object.

Parametry

param

The char content.

Zwracane wartości

Returns the new char object id, or FALSE on errors.

Zobacz też:

  • ifx_free_char() - Deletes the char object

ifx_create_blob
ifx_do
Informix Funkcje


Execute a previously prepared SQL-statement

ifx_create_char
ifx_error
Informix Funkcje
PHP Manual

ifx_do

(PHP 4, PHP <=5.2.0)

ifx_do — Execute a previously prepared SQL-statement

Opis

bool ifx_do ( resource $result_id )

Executes a previously prepared query or opens a cursor for it.

Does NOT free result_id on error.

Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows().

Parametry

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

Przykład #1 ifx_do() Example

<?php
$conn = fx_connect( "db", "user", "password" );
$result = ifx_prepare("SELECT customer_num, company FROM customer", $conn);
ifx_do($result);
?>

Zobacz też:

  • ifx_prepare() - Prepare an SQL-statement for execution

ifx_create_char
ifx_error
Informix Funkcje


Returns error code of last Informix call

ifx_do
ifx_errormsg
Informix Funkcje
PHP Manual

ifx_error

(PHP 4, PHP <=5.2.0)

ifx_error — Returns error code of last Informix call

Opis

string ifx_error ([ resource $link_identifier ] )

Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed.

Parametry

link_identifier

The link identifier.

Zwracane wartości

The Informix error codes (SQLSTATE & SQLCODE) formatted as x [SQLSTATE = aa bbb SQLCODE=cccc].

where x = space : no error

E : error

N : no more data

W : warning

? : undefined

If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.

See the Informix manual for the description of SQLSTATE and SQLCODE

Zobacz też:

  • ifx_errormsg() - Returns error message of last Informix call

ifx_do
ifx_errormsg
Informix Funkcje


Returns error message of last Informix call

ifx_error
ifx_fetch_row
Informix Funkcje
PHP Manual

ifx_errormsg

(PHP 4, PHP <=5.2.0)

ifx_errormsg — Returns error message of last Informix call

Opis

string ifx_errormsg ([ int $errorcode ] )

Returns the Informix error message associated with the most recent Informix error.

Parametry

errorcode

If specified, the function will return the message corresponding to the specified code.

Zwracane wartości

Return the error message, as a string.

Przykłady

Przykład #1 ifx_errormsg() example

<?php
printf("%s\n<br>", ifx_errormsg(-201));
?>

Zobacz też:

  • ifx_error() - Returns error code of last Informix call

ifx_error
ifx_fetch_row
Informix Funkcje


Get row as an associative array

ifx_errormsg
ifx_fieldproperties
Informix Funkcje
PHP Manual

ifx_fetch_row

(PHP 4, PHP <=5.2.0)

ifx_fetch_row — Get row as an associative array

Opis

array ifx_fetch_row ( resource $result_id [, mixed $position ] )

Fetches one row of data from the result associated with the specified result identifier.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parametry

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

position

An optional parameter for a "fetch" operation on "scroll" cursors: NEXT, PREVIOUS, CURRENT, FIRST, LAST or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.

Zwracane wartości

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values.

Przykłady

Przykład #1 Informix fetch rows

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do ($rid)) {
   /* ... error ... */
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for (reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n<br />");
    $row = ifx_fetch_row($rid, "NEXT");
}
ifx_free_result ($rid);
?>

ifx_errormsg
ifx_fieldproperties
Informix Funkcje


List of SQL fieldproperties

ifx_fetch_row
ifx_fieldtypes
Informix Funkcje
PHP Manual

ifx_fieldproperties

(PHP 4, PHP <=5.2.0)

ifx_fieldproperties — List of SQL fieldproperties

Opis

array ifx_fieldproperties ( resource $result_id )

Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".

Parametry

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Zwracane wartości

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on errors.

Przykłady

Przykład #1 Informix SQL fieldproperties

<?php
$properties = ifx_fieldproperties($resultid);
if (!isset($properties)) {
    /* ... error ... */
}
foreach ($properties as $fname => $val) {
    echo "$fname:\t property = $val\n";
}
?>

Zobacz też:

  • ifx_fieldtypes() - List of Informix SQL fields

ifx_fetch_row
ifx_fieldtypes
Informix Funkcje


List of Informix SQL fields

ifx_fieldproperties
ifx_free_blob
Informix Funkcje
PHP Manual

ifx_fieldtypes

(PHP 4, PHP <=5.2.0)

ifx_fieldtypes — List of Informix SQL fields

Opis

array ifx_fieldtypes ( resource $result_id )

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for the query associated with result_id.

Parametry

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Zwracane wartości

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

Przykłady

Przykład #1 Fieldnames and SQL fieldtypes

<?php
$types = ifx_fieldtypes($resultid);
if (is_array($types)) {
    foreach ($types as $fname => $val) {
        echo "$fname:\t type = $val\n";
    }
}
?>

Zobacz też:

  • ifx_fieldproperties() - List of SQL fieldproperties

ifx_fieldproperties
ifx_free_blob
Informix Funkcje


Deletes the blob object

ifx_fieldtypes
ifx_free_char
Informix Funkcje
PHP Manual

ifx_free_blob

(PHP 4, PHP <=5.2.0)

ifx_free_blob — Deletes the blob object

Opis

bool ifx_free_blob ( int $bid )

Deletes the blobobject for the given blob object-id.

Parametry

bid

The BLOB object id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifx_create_blob() - Creates an blob object

ifx_fieldtypes
ifx_free_char
Informix Funkcje


Deletes the char object

ifx_free_blob
ifx_free_result
Informix Funkcje
PHP Manual

ifx_free_char

(PHP 4, PHP <=5.2.0)

ifx_free_char — Deletes the char object

Opis

bool ifx_free_char ( int $bid )

Deletes the charobject for the given char object-id.

Parametry

bid

The char object id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifx_create_char() - Creates an char object

ifx_free_blob
ifx_free_result
Informix Funkcje


Releases resources for the query

ifx_free_char
ifx_get_blob
Informix Funkcje
PHP Manual

ifx_free_result

(PHP 4, PHP <=5.2.0)

ifx_free_result — Releases resources for the query

Opis

bool ifx_free_result ( resource $result_id )

Releases resources for the query associated with result_id.

Parametry

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifx_do() - Execute a previously prepared SQL-statement

ifx_free_char
ifx_get_blob
Informix Funkcje


Return the content of a blob object

ifx_free_result
ifx_get_char
Informix Funkcje
PHP Manual

ifx_get_blob

(PHP 4, PHP <=5.2.0)

ifx_get_blob — Return the content of a blob object

Opis

string ifx_get_blob ( int $bid )

Returns the content of the blob object.

Parametry

bid

The BLOB object id.

Zwracane wartości

The contents of the BLOB as a string, or FALSE on errors.

Zobacz też:

  • ifx_get_char() - Return the content of the char object

ifx_free_result
ifx_get_char
Informix Funkcje


Return the content of the char object

ifx_get_blob
ifx_getsqlca
Informix Funkcje
PHP Manual

ifx_get_char

(PHP 4, PHP <=5.2.0)

ifx_get_char — Return the content of the char object

Opis

string ifx_get_char ( int $bid )

Returns the content of the char object.

Parametry

bid

The char object-id.

Zwracane wartości

Returns the contents as a string, or FALSE on errors.

Zobacz też:

  • ifx_get_blob() - Return the content of a blob object

ifx_get_blob
ifx_getsqlca
Informix Funkcje


Get the contents of sqlca.sqlerrd[0..5] after a query

ifx_get_char
ifx_htmltbl_result
Informix Funkcje
PHP Manual

ifx_getsqlca

(PHP 4, PHP <=5.2.0)

ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query

Opis

array ifx_getsqlca ( resource $result_id )

Returns a pseudo-row with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.

For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a SELECT dbinfo('sqlca.sqlerrdx') query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.

Parametry

result_id

result_id is a valid result id returned by ifx_query() or ifx_prepare() (select type queries only!).

Zwracane wartości

Returns an associative array with the following entries: sqlerrd0, sqlerrd1, sqlerrd2, sqlerrd3, sqlerrd4 and sqlerrd5.

Przykłady

Przykład #1 Retrieve Informix sqlca.sqlerrd[x] values

<?php
/* assume the first column of 'sometable' is a serial */
$qid = ifx_query("insert into sometable
                  values (0, '2nd column', 'another column') ", $connid);
if (!$qid) {
    /* ... error ... */
}
$sqlca = ifx_getsqlca($qid);
$serial_value = $sqlca["sqlerrd1"];
echo "The serial value of the inserted row is : $serial_value<br />\n";
?>

ifx_get_char
ifx_htmltbl_result
Informix Funkcje


Formats all rows of a query into a HTML table

ifx_getsqlca
ifx_nullformat
Informix Funkcje
PHP Manual

ifx_htmltbl_result

(PHP 4, PHP <=5.2.0)

ifx_htmltbl_result — Formats all rows of a query into a HTML table

Opis

int ifx_htmltbl_result ( resource $result_id [, string $html_table_options ] )

Formats and prints all rows of the result_id query into a HTML table.

Parametry

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

html_table_options

This optional argument is a string of <table> tag options.

Zwracane wartości

Returns the number of fetched rows, or FALSE on errors.

Przykłady

Przykład #1 Informix results as HTML table

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do($rid)) {
    /* ... error ... */
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);
?>

ifx_getsqlca
ifx_nullformat
Informix Funkcje


Sets the default return value on a fetch row

ifx_htmltbl_result
ifx_num_fields
Informix Funkcje
PHP Manual

ifx_nullformat

(PHP 4, PHP <=5.2.0)

ifx_nullformat — Sets the default return value on a fetch row

Opis

bool ifx_nullformat ( int $mode )

Sets the default return value of a NULL-value on a fetch row.

Parametry

mode

Mode "0" returns "", and mode "1" returns "NULL".

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ifx_htmltbl_result
ifx_num_fields
Informix Funkcje


Returns the number of columns in the query

ifx_nullformat
ifx_num_rows
Informix Funkcje
PHP Manual

ifx_num_fields

(PHP 4, PHP <=5.2.0)

ifx_num_fields — Returns the number of columns in the query

Opis

int ifx_num_fields ( resource $result_id )

After preparing or executing a query, this call gives you the number of columns in the query.

Parametry

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Zwracane wartości

Returns the number of columns in query for result_id, or FALSE on errors.

Przykłady

Przykład #1 ifx_num_fields() Example

<?php
$conn_id = ifx_connect("db", "user", "password");
$res_id = ifx_query("select * from systables", $conn_id);
echo ifx_num_fields($res_id);
?>

Zobacz też:

  • ifx_num_rows() - Count the rows already fetched from a query

ifx_nullformat
ifx_num_rows
Informix Funkcje


Count the rows already fetched from a query

ifx_num_fields
ifx_pconnect
Informix Funkcje
PHP Manual

ifx_num_rows

(PHP 4, PHP <=5.2.0)

ifx_num_rows — Count the rows already fetched from a query

Opis

int ifx_num_rows ( resource $result_id )

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

Parametry

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Zwracane wartości

Returns the number of fetched rows or FALSE on errors.

Zobacz też:

  • ifx_num_fields() - Returns the number of columns in the query

ifx_num_fields
ifx_pconnect
Informix Funkcje


Open persistent Informix connection

ifx_num_rows
ifx_prepare
Informix Funkcje
PHP Manual

ifx_pconnect

(PHP 4, PHP <=5.2.0)

ifx_pconnect — Open persistent Informix connection

Opis

resource ifx_pconnect ([ string $database [, string $userid [, string $password ]]] )

ifx_pconnect() acts very much like ifx_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).

This type of links is therefore called 'persistent'.

Parametry

All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php.ini (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

database

The database name, as a string.

userid

The username, as a string.

password

The password, as a string.

Zwracane wartości

Returns: valid Informix persistent link identifier on success, or FALSE on errors.

Zobacz też:

  • ifx_connect() - Open Informix server connection

ifx_num_rows
ifx_prepare
Informix Funkcje


Prepare an SQL-statement for execution

ifx_pconnect
ifx_query
Informix Funkcje
PHP Manual

ifx_prepare

(PHP 4, PHP <=5.2.0)

ifx_prepare — Prepare an SQL-statement for execution

Opis

resource ifx_prepare ( string $query , resource $link_identifier [, int $cursor_def ], mixed $blobidarray )

Prepares a query for later use with ifx_do().

For "select-type" queries a cursor is declared and opened. Non-select queries are "execute immediate".

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If the contents of the TEXT (or BYTE) column allow it, you can also use ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Parametry

query

The query string.

link_identifier

The link identifier.

cursor_def

This optional parameter allows you to make this a scroll and/or hold cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.

blobidarray

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

Zwracane wartości

Returns a valid result identifier for use by ifx_do(), or FALSE on errors.

Zobacz też:

  • ifx_do() - Execute a previously prepared SQL-statement

ifx_pconnect
ifx_query
Informix Funkcje


Send Informix query

ifx_prepare
ifx_textasvarchar
Informix Funkcje
PHP Manual

ifx_query

(PHP 4, PHP <=5.2.0)

ifx_query — Send Informix query

Opis

resource ifx_query ( string $query , resource $link_identifier [, int $cursor_type [, mixed $blobidarray ]] )

Sends a query to the currently active database on the server that's associated with the specified link identifier.

For "select-type" queries a cursor is declared and opened. Non-select queries are "execute immediate".

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If the contents of the TEXT (or BYTE) column allow it, you can also use ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Parametry

query

The query string.

link_identifier

The link identifier.

cursor_def

This optional parameter allows you to make this a scroll and/or hold cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. I you omit this parameter the cursor is a normal sequential cursor.

blobidarray

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

Zwracane wartości

Returns valid Informix result identifier on success, or FALSE on errors.

Przykłady

Przykład #1 Show all rows of the "orders" table as a HTML table

<?php
ifx_textasvarchar(1);      // use "text mode" for blobs
$res_id = ifx_query("select * from orders", $conn_id);
if (! $res_id) {
    printf("Can't select orders : %s\n<br />%s<br />\n", ifx_error(), ifx_errormsg());
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);
?>

Przykład #2 Insert some values into the "catalog" table

<?php

// create blob id's for a byte and text column
$textid = ifx_create_blob(0, 0, "Text column in memory");
$byteid = ifx_create_blob(1, 0, "Byte column in memory");

// store blob id's in a blobid array
$blobidarray[] = $textid;
$blobidarray[] = $byteid;

// launch query
$query = "insert into catalog (stock_num, manu_code, " .
         "cat_descr,cat_picture) values(1,'HRO',?,?)";
$res_id = ifx_query($query, $conn_id, $blobidarray);
if (! $res_id) {
    /* ... error ... */
}

// free result id
ifx_free_result($res_id);
?>

Zobacz też:

  • ifx_connect() - Open Informix server connection

ifx_prepare
ifx_textasvarchar
Informix Funkcje


Set the default text mode

ifx_query
ifx_update_blob
Informix Funkcje
PHP Manual

ifx_textasvarchar

(PHP 4, PHP <=5.2.0)

ifx_textasvarchar — Set the default text mode

Opis

bool ifx_textasvarchar ( int $mode )

Sets the default text mode for all select-queries.

Parametry

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifx_byteasvarchar() - Set the default byte mode

ifx_query
ifx_update_blob
Informix Funkcje


Updates the content of the blob object

ifx_textasvarchar
ifx_update_char
Informix Funkcje
PHP Manual

ifx_update_blob

(PHP 4, PHP <=5.2.0)

ifx_update_blob — Updates the content of the blob object

Opis

bool ifx_update_blob ( int $bid , string $content )

Updates the content of the blob object for the given blob object bid.

Parametry

bid

A BLOB object identifier.

content

The new data, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifx_update_char() - Updates the content of the char object

ifx_textasvarchar
ifx_update_char
Informix Funkcje


Updates the content of the char object

ifx_update_blob
ifxus_close_slob
Informix Funkcje
PHP Manual

ifx_update_char

(PHP 4, PHP <=5.2.0)

ifx_update_char — Updates the content of the char object

Opis

bool ifx_update_char ( int $bid , string $content )

Updates the content of the char object for the given char object bid.

Parametry

bid

A char object identifier.

content

The new data, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifx_update_blob() - Updates the content of the blob object

ifx_update_blob
ifxus_close_slob
Informix Funkcje


Deletes the slob object

ifx_update_char
ifxus_create_slob
Informix Funkcje
PHP Manual

ifxus_close_slob

(PHP 4, PHP <=5.2.0)

ifxus_close_slob — Deletes the slob object

Opis

bool ifxus_close_slob ( int $bid )

Deletes the slob object on the given slob object-id bid.

Parametry

bid

An existing slob id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifxus_open_slob() - Opens an slob object

ifx_update_char
ifxus_create_slob
Informix Funkcje


Creates an slob object and opens it

ifxus_close_slob
ifxus_free_slob
Informix Funkcje
PHP Manual

ifxus_create_slob

(PHP 4, PHP <=5.2.0)

ifxus_create_slob — Creates an slob object and opens it

Opis

int ifxus_create_slob ( int $mode )

Creates an slob object and opens it.

Parametry

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Zwracane wartości

Return the new slob object-id, or FALSE on errors.

Zobacz też:

  • ifxus_close_slob() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object

ifxus_close_slob
ifxus_free_slob
Informix Funkcje


Deletes the slob object

ifxus_create_slob
ifxus_open_slob
Informix Funkcje
PHP Manual

ifxus_free_slob

(PHP 4, PHP <=5.2.0)

ifxus_free_slob — Deletes the slob object

Opis

bool ifxus_free_slob ( int $bid )

Deletes the slob object.

Parametry

bid

An existing slob id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ifxus_close_slob() - Deletes the slob object

ifxus_create_slob
ifxus_open_slob
Informix Funkcje


Opens an slob object

ifxus_free_slob
ifxus_read_slob
Informix Funkcje
PHP Manual

ifxus_open_slob

(PHP 4, PHP <=5.2.0)

ifxus_open_slob — Opens an slob object

Opis

int ifxus_open_slob ( int $bid , int $mode )

Opens an slob object. bid should be an existing slob id.

Parametry

bid

An existing slob id.

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Zwracane wartości

Returns the new slob object-id, or FALSE on errors.

Zobacz też:

  • ifxus_close_slob() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object

ifxus_free_slob
ifxus_read_slob
Informix Funkcje


Reads nbytes of the slob object

ifxus_open_slob
ifxus_seek_slob
Informix Funkcje
PHP Manual

ifxus_read_slob

(PHP 4, PHP <=5.2.0)

ifxus_read_slob — Reads nbytes of the slob object

Opis

string ifxus_read_slob ( int $bid , int $nbytes )

Reads nbytes of the slob object.

Parametry

bid

An existing slob id.

nbytes

The number of bytes to read.

Zwracane wartości

Returns the slob contents as a string, or FALSE on errors.

Zobacz też:

  • ifxus_write_slob() - Writes a string into the slob object

ifxus_open_slob
ifxus_seek_slob
Informix Funkcje


Sets the current file or seek position

ifxus_read_slob
ifxus_tell_slob
Informix Funkcje
PHP Manual

ifxus_seek_slob

(PHP 4, PHP <=5.2.0)

ifxus_seek_slob — Sets the current file or seek position

Opis

int ifxus_seek_slob ( int $bid , int $mode , int $offset )

Sets the current file or seek position of an open slob object.

Parametry

bid

An existing slob id.

mode

0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END.

offset

A byte offset.

Zwracane wartości

Returns the seek position as an integer, or FALSE on errors.

Zobacz też:

  • ifxus_tell_slob() - Returns the current file or seek position

ifxus_read_slob
ifxus_tell_slob
Informix Funkcje


Returns the current file or seek position

ifxus_seek_slob
ifxus_write_slob
Informix Funkcje
PHP Manual

ifxus_tell_slob

(PHP 4, PHP <=5.2.0)

ifxus_tell_slob — Returns the current file or seek position

Opis

int ifxus_tell_slob ( int $bid )

Returns the current file or seek position of an open slob object

Parametry

bid

An existing slob id.

Zwracane wartości

Returns the seek position as an integer, or FALSE on errors.

Zobacz też:

  • ifxus_seek_slob() - Sets the current file or seek position

ifxus_seek_slob
ifxus_write_slob
Informix Funkcje


Writes a string into the slob object

ifxus_tell_slob
Ingres
Informix Funkcje
PHP Manual

ifxus_write_slob

(PHP 4, PHP <=5.2.0)

ifxus_write_slob — Writes a string into the slob object

Opis

int ifxus_write_slob ( int $bid , string $content )

Writes a string into the slob object.

Parametry

bid

An existing slob id.

content

The content to write, as a string.

Zwracane wartości

Returns the bytes written as an integer, or FALSE on errors.

Zobacz też:

  • ifxus_read_slob() - Reads nbytes of the slob object

ifxus_tell_slob
Ingres
Informix Funkcje


Ingres DBMS, EDBC, i Enterprise Access Gateways

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Podstawowe użycie
  • Funkcje Ingres
    • ingres_autocommit_state — Test if the connection is using autocommit
    • ingres_autocommit — Włącza lub wyłącza automatyczne zatwierdzanie
    • ingres_charset — Returns the installation character set
    • ingres_close — Zamyka połączenie z serwerem Ingres
    • ingres_commit — Zatwierdza transakcję
    • ingres_connect — Open a connection to an Ingres database
    • ingres_cursor — Get a cursor name for a given result resource
    • ingres_errno — Zwraca ostatnio wygenerowany numer błędu Ingres
    • ingres_error — Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie
    • ingres_errsqlstate — Zwraca ostatnio wygenerowany kod błędu SQLSTATE
    • ingres_escape_string — Escape special characters for use in a query
    • ingres_execute — Execute a prepared query
    • ingres_fetch_array — Fetch a row of result into an array
    • ingres_fetch_assoc — Fetch a row of result into an associative array
    • ingres_fetch_object — Fetch a row of result into an object
    • ingres_fetch_proc_return — Get the return value from a procedure call
    • ingres_fetch_row — Fetch a row of result into an enumerated array
    • ingres_field_length — Get the length of a field
    • ingres_field_name — Zwraca nazwę pola z wyniku zapytania
    • ingres_field_nullable — Sprawdza czy pole może przyjmować wartość NULL
    • ingres_field_precision — Get the precision of a field
    • ingres_field_scale — Get the scale of a field
    • ingres_field_type — Get the type of a field in a query result
    • ingres_free_result — Free the resources associated with a result identifier
    • ingres_next_error — Get the next Ingres error
    • ingres_num_fields — Pobiera liczbę pól zwracanych przez ostatnie zapytanie
    • ingres_num_rows — Get the number of rows affected or returned by a query
    • ingres_pconnect — Open a persistent connection to an Ingres database
    • ingres_prepare — Prepare a query for later execution
    • ingres_query — Send an SQL query to Ingres
    • ingres_result_seek — Set the row position before fetching data
    • ingres_rollback — Wycofuje transakcję
    • ingres_set_environment — Set environment features controlling output options
    • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres
ifxus_write_slob
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Rozszerzenie Ingres w PHP umożliwia połšczenie i wykonywanie zapytań w bazach danych Ingres DBMS, EDBC, i Enterprise Access Gateways.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0.

Ingres
Instalacja/Konfiguracja
Ingres


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Ingres


Wymagania

Aby zbudować lub używać rozszerzenia PHP z bazą danych Ingres należy mieć przygotowane działające środowisko Ingres. Oprogramowanie klienta Ingres można pobrać z adresu: » http://esd.ingres.com/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/ingres.

Biblioteki DLL tego rozszerzenia PECL można pobrać z » http://esd.ingres.com/product/drivers/PHP/.

Aby te funkcje były dostępne należy » pobrać i skompilować to rozszerzenie używając opcji konfiguracji Ingres --with-ingres[=DIR] , gdzie DIR jest katalogiem instalacji Ingres. Jeśli zmienna środowiskowa II_SYSTEM nie jest poprawnie ustawiona, należy użyć opcji --with-ingres=DIR aby określić katalog docelowy instalacji Ingres.

Kod PHP napisany dla wersji 2.x i późniejszych nie jest kompatybilny z poprzednimi wersjami rozszerzenia PHP. Jednakże jest możliwe uruchomienie dwóch niekompatybilnych wydań w tym samym środowisku PHP poprzez ustawienie opcji --enable-ingres2 . Ta opcja konfiguracyjna zmienia nazwę rozszerzenia na ingres2, tym samym zmienia nazwy funkcji, ustawienia konfiguracji i stałe. Gdy ta opcja jest włączona, to na przykład funkcja ingres_connect() staje się: ingres2_connect().

Aby używać tego rozszerzenia, musi być określona systemowa zmienna środowiskowa II_SYSTEM. Użytkownicy systemów Linux i UNIX muszą zdefiniować np. ścieżkę do bibliotek współdzielonych LD_LIBRARY_PATH. Gdy rozszerzenie jest używane z serwerem Apache, to zmienne muszą być wyraźnie określone w pliku konfiguracyjnym serwera Apache. Dodatkowo dyrektywa PassEnv jest wymagana dla rozszerzenia Ingres, aby zostały prawidłowo załadowane biblioteki współdzielone. Na przykład:

Przykład #1 Przykład użycia PassEnv dla Ingres

<IfModule mod_env.c>
    PassEnv II_SYSTEM
    PassEnv LD_LIBRARY_PATH
</IfModule>

Informacja:

Przykłady konfiguracji Ingres dla różnych serwerów WWW i systemów operacyjnych znajdują się pod adresem: » http://community.ingres.com/wiki/Ingres_Articles#Ingres_and_Web_Servers.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Ingres configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.array_index_start | "1" | PHP_INI_ALL | Available since ingres 1.4.0.
ingres.auto | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since ingres 1.1.0.
ingres.default_database | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_password | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_user | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.describe | 1 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.fetch_buffer_size | 100 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.reuse_connection | "1" | PHP_INI_ALL | Available since ingres 2.0.0
ingres.scrollable | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace | "0" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Available since ingres 1.2.1.
ingres.utf8 | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

ingres.allow_persistent boolean

Specifies whether to allow persistent connections to Ingres

ingres.array_index_start integer

Specifies the start value for an integer key for arrays generated by ingres_fetch_row() or ingres_fetch_array(). By default ingres.array_index_start is set to 1. If you wish to make the ingres extension behave like other database extensions set this configuration option to 0.

ingres.auto boolean

Enables or disables autocommit emulation. Ingres cannot have multiple cursors open with autocommit enabled. When enabled, the driver emulates autocommit.

ingres.blob_segment_length integer

Specifies the amount of memory to use when reading BLOB data, in bytes

ingres.cursor_mode integer

Specifies the default mode for cursors opened with ingres_prepare(). Valid values are INGRES_CURSOR_UPDATE or INGRES_CURSOR_READONLY.

ingres.default_database string

Specifies the default database name to use when connecting to the database server if no other name is specified. Does not apply in tryb bezpieczny SQL.

ingres.default_password string

Specifies the default password to use when connecting to the database server if no other name is specified. Does not apply in tryb bezpieczny SQL.

ingres.default_user string

Specifies the default user name to use when connecting to the database server if no other name is specified. Does not apply in tryb bezpieczny SQL.

ingres.describe boolean

Enables the use of DESCRIBE INPUT to determine the expected data types for queries that use parameters. Available with Ingres 9.1.0 and later. When disabled, queries that have parameters passed may need to manually describe the types of those parameters using the types parameter in ingres_query().

Informacja:

Enabling this feature with ingres_query() will cause additional communications traffic between this extension and the server. To minimize this additional traffic, use ingres_prepare() and ingres_execute().

ingres.fetch_buffer_size integer

Specifies the number of pre-fetch rows that ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row() will try and fetch in one fetch operation.

ingres.max_links integer

Specifies the maximum number of Ingres sessions allowed per process or thread. The number of sessions should not exceed the total number of connected sessions configured within Ingres.

ingres.max_persistent integer

Specifies the maximum number of persistent Ingres sessions allowed per process or thread. The number of sessions should not exceed the total number of connected sessions configured within Ingres.

ingres.reuse_connection boolean

Reuses an existing active connection if connecting to the same database with the same user name

ingres.scrollable boolean

Enables support for scrollable cursors. When fetching CLOB or BLOB data, this should be set to FALSE. Available with Ingres 9.2.0 or later.

ingres.trace boolean

Enables simple tracing using E_NOTICE messages

ingres.trace_connect boolean

Prints E_NOTICE messages during ingres_connect() or ingres_pconnect() calls

ingres.utf8 boolean

Assumes that strings being passed to National Character column types (NVARCHAR or NCHAR) are using UTF8 encoding and converts them to UTF16 for the server

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

ingres_connect() i ingres_pconnect() zwracają identyfikator połączenia Ingres.

ingres_query() i ingres_unbuffered_query() zwracają identyfikator wyniku Ingres.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

INGRES_ASSOC (integer)
Kolumny są zwracane do tablicy indeksowanej asocjacyjnie. Indeksy tablicy odpowiadają nazwom pól kolumn. Używane w: ingres_fetch_array().
INGRES_NUM (integer)
Kolumny są zwracane do tablicy indeksowanej numerycznie. Wartości pól są umieszczane na kolejnych pozycjach tablicy, zaczynając od 1. Aby zmienić tę wartość zobacz ingres.array_index_start. Używane w: ingres_fetch_array().
INGRES_BOTH (integer)
Kolumny są zwracane do tablicy indeksowanej zarówno asocjacyjnie, jak również numerycznie. Używane w: ingres_fetch_array().
INGRES_EXT_VERSION (string)
Określa wersję rozszerzenia Ingres. Dostępna od wersji 1.2.0 rozszerzenia PECL.
INGRES_API_VERSION (integer)
Określa wersję Ingres OpenAPI, z którą rozszerzenie zostało zbudowane. Dostępna od wersji 1.2.0 rozszerzenia PECL.
INGRES_CURSOR_READONLY (integer)
Określa, że kursory powinny być otwarte w trybie 'do odczytu'. Dostępna od wersji 1.2.0 rozszerzenia PECL. Używane w: ingres.cursor_mode.
INGRES_CURSOR_UPDATE (integer)
Określa, że kursory powinny być otwarte w trybie 'do modyfikacji'. Dostępna od wersji 1.2.0 rozszerzenia PECL. Używane w: ingres.cursor_mode.
INGRES_DATE_MULTINATIONAL (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na MULTINATIONAL. Dostępna od wersji 1.2.0 rozszerzenia PECL. Używane w: ingres_connect(), ingres_pconnect() i ingres_set_environment(). Zobacz opcje środowiskowe w ingres_set_environment().
INGRES_DATE_MULTINATIONAL4 (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na MULTINATIONAL4. Dostępna od wersji 1.2.0 rozszerzenia PECL.
Używane w:
ingres_connect(), ingres_pconnect()
i ingres_set_environment(). Zobacz opcje środowiskowe
w ingres_set_environment().
INGRES_DATE_FINNISH (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na FINNISH. Dostępna od wersji 1.2.0 rozszerzenia PECL.
Używane w:
ingres_connect(), ingres_pconnect()
i ingres_set_environment(). Zobacz opcje środowiskowe
w ingres_set_environment().
INGRES_DATE_ISO (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na ISO. Dostępna od wersji 1.2.0 rozszerzenia PECL.
Używane w:
ingres_connect(), ingres_pconnect()
i ingres_set_environment(). Zobacz opcje środowiskowe
w ingres_set_environment().
INGRES_DATE_ISO4 (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na ISO4. Dostępna od wersji 1.2.0 rozszerzenia PECL.
Używane w:
ingres_connect(), ingres_pconnect()
i ingres_set_environment(). Zobacz opcje środowiskowe
w ingres_set_environment().
INGRES_DATE_GERMAN (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na GERMAN. Dostępna od wersji 1.2.0 rozszerzenia PECL.
Używane w:
ingres_connect(), ingres_pconnect()
i ingres_set_environment(). Zobacz opcje środowiskowe
w ingres_set_environment().
INGRES_DATE_MDY (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na MDY. Dostępna od wersji 1.2.0 rozszerzenia PECL.
Używane w:
ingres_connect(), ingres_pconnect()
i ingres_set_environment(). Zobacz opcje środowiskowe
w ingres_set_environment().
INGRES_DATE_DMY (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na DMY. Dostępna od wersji 1.2.0 rozszerzenia PECL.
Używane w:
ingres_connect(), ingres_pconnect()
i ingres_set_environment(). Zobacz opcje środowiskowe
w ingres_set_environment().
INGRES_DATE_YMD (integer)
Równoważna z ustawieniem zmiennej środowiskowej II_DATE_FORMAT na YMD. Dostępna od wersji 1.2.0 rozszerzenia PECL.
Używane w:
ingres_connect(), ingres_pconnect()
i ingres_set_environment(). Zobacz opcje środowiskowe
w ingres_set_environment().
INGRES_MONEY_LEADING (integer)
Określa symbol waluty umieszczany przed wartością typu money. Równoważna z ustawieniem zmiennej środowiskowej II_MONEY_FORMAT na 'L:'. Dostępna od wersji 1.2.0 rozszerzenia PECL. Używane w: ingres_connect(), ingres_pconnect() i ingres_set_environment(). Zobacz opcje środowiskowe w ingres_set_environment().
INGRES_MONEY_TRAILING (integer)
Określa symbol pieniądza umieszczany na końcu wartości typu money. Równoważna z ustawieniem zmiennej środowiskowej II_MONEY_FORMAT na 'T:'. Dostępna od wersji 1.2.0 rozszerzenia PECL. Używane w: ingres_connect(), ingres_pconnect() i ingres_set_environment(). Zobacz opcje środowiskowe w ingres_set_environment().
INGRES_STRUCTURE_BTREE (integer)
Określa domyślną strukturę tabeli lub indeksu jako BTREE i może być podawana podczas nawiązywania połączenia
jako wartość opcji table_structure lub index_structure. Dostępna od wersji 1.4.0 rozszerzenia PECL.
Używane w: ingres_connect() i
ingres_pconnect(). Zobacz opcje
w ingres_connect().
INGRES_STRUCTURE_CBTREE (integer)
Określa domyślną strukturę tabeli lub indeksu jako COMPRESSED BTREE i może być podawana podczas nawiązywania połączenia
jako wartość opcji table_structure lub index_structure. Dostępna od wersji 1.4.0 rozszerzenia PECL.
Używane w: ingres_connect() i
ingres_pconnect(). Zobacz opcje
w ingres_connect().
INGRES_STRUCTURE_HASH (integer)
Określa domyślną strukturę tabeli lub indeksu jako HASH i może być podawana podczas nawiązywania połączenia
jako wartość opcji table_structure lub index_structure. Dostępna od wersji 1.4.0 rozszerzenia PECL.
Używane w: ingres_connect() i
ingres_pconnect(). Zobacz opcje
w ingres_connect().
INGRES_STRUCTURE_CHASH (integer)
Określa domyślną strukturę tabeli lub indeksu jako COMPRESSED HASH i może być podawana podczas nawiązywania połączenia
jako wartość opcji table_structure lub index_structure. Dostępna od wersji 1.4.0 rozszerzenia PECL.
Używane w: ingres_connect() i
ingres_pconnect(). Zobacz opcje
w ingres_connect().
INGRES_STRUCTURE_HEAP (integer)
Określa domyślną strukturę tabeli jako HEAP i może być podawana podczas nawiązywania połączenia
jako wartość opcji table_structure. Dostępna od wersji 1.4.0 rozszerzenia PECL.
Używane w: ingres_connect() i
ingres_pconnect(). Zobacz opcje
w ingres_connect().
INGRES_STRUCTURE_CHEAP (integer)
Określa domyślną strukturę tabeli jako COMPRESSED HEAP i może być podawana podczas nawiązywania połączenia
jako wartość opcji table_structure. Dostępna od wersji 1.4.0 rozszerzenia PECL.
Używane w: ingres_connect() i
ingres_pconnect(). Zobacz opcje
w ingres_connect().
INGRES_STRUCTURE_ISAM (integer)
Określa domyślną strukturę tabeli lub indeksu jako ISAM i może być podawana podczas nawiązywania połączenia
jako wartość opcji table_structure lub index_structure. Dostępna od wersji 1.4.0 rozszerzenia PECL.
Używane w: ingres_connect() i
ingres_pconnect(). Zobacz opcje
w ingres_connect().
INGRES_STRUCTURE_CISAM (integer)
Określa domyślną strukturę tabeli lub indeksu jako COMPRESSED ISAM i może być podawana podczas nawiązywania połączenia
jako wartość opcji table_structure lub index_structure. Dostępna od wersji 1.4.0 rozszerzenia PECL.
Używane w: ingres_connect() i
ingres_pconnect(). Zobacz opcje
w ingres_connect().
Typy zasobów
Przykłady
Ingres


Przykłady

Spis treści

  • Podstawowe użycie
Stałe predefiniowane
Podstawowe użycie
Ingres


Podstawowe użycie

Ten nieskomplikowany przykład pojazuje jak połączyć się z bazą Ingres, wykonać zapytanie, wyświetlić wyniki i zamknąć połączenie.

Przykład #1 Przykład połączenia z Ingres

<?php
// Nawiązanie połączenia, wybór bazy danych
$link = ingres_connect('database', 'user', 'password')
    or die('Nie można się połączyć: ' . ingres_error($link));
echo 'Połączenie zostało nawiązane pomyślnie';

// Pobieranie wyników z tabeli, która istnieje we wszystkich bazach danych Ingres
$query = 'SELECT * FROM iirelation';
$returncode = ingres_query($link,$query) or die('Zapytanie nie powiodło się: ' .
ingres_error($link));

// Wyświetla wyniki w formacie HTML
// relid - nazwa tabeli
// relowner - właściciel tabeli
echo "<table>\n";
while ($iirelation = ingres_fetch_object($link)) {
    echo "\t<tr>\n";
    echo "\t\t<td>" . $iirelation->relid . "</td>\n";
    echo "\t\t<td>" . $iirelation->relowner . "</td>\n";
    echo "\t</tr>\n";
}
echo "</table>\n";

// Zwolnienie bufora wyniku
ingres_free_result($result);

// Potwierdzenie transakcji
ingres_commit($link);

// Zamknięcie połączenia
ingres_close($link);
?>

Przykłady
Funkcje Ingres
Przykłady


Funkcje Ingres

Spis treści

  • ingres_autocommit_state — Test if the connection is using autocommit
  • ingres_autocommit — Włącza lub wyłącza automatyczne zatwierdzanie
  • ingres_charset — Returns the installation character set
  • ingres_close — Zamyka połączenie z serwerem Ingres
  • ingres_commit — Zatwierdza transakcję
  • ingres_connect — Open a connection to an Ingres database
  • ingres_cursor — Get a cursor name for a given result resource
  • ingres_errno — Zwraca ostatnio wygenerowany numer błędu Ingres
  • ingres_error — Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie
  • ingres_errsqlstate — Zwraca ostatnio wygenerowany kod błędu SQLSTATE
  • ingres_escape_string — Escape special characters for use in a query
  • ingres_execute — Execute a prepared query
  • ingres_fetch_array — Fetch a row of result into an array
  • ingres_fetch_assoc — Fetch a row of result into an associative array
  • ingres_fetch_object — Fetch a row of result into an object
  • ingres_fetch_proc_return — Get the return value from a procedure call
  • ingres_fetch_row — Fetch a row of result into an enumerated array
  • ingres_field_length — Get the length of a field
  • ingres_field_name — Zwraca nazwę pola z wyniku zapytania
  • ingres_field_nullable — Sprawdza czy pole może przyjmować wartość NULL
  • ingres_field_precision — Get the precision of a field
  • ingres_field_scale — Get the scale of a field
  • ingres_field_type — Get the type of a field in a query result
  • ingres_free_result — Free the resources associated with a result identifier
  • ingres_next_error — Get the next Ingres error
  • ingres_num_fields — Pobiera liczbę pól zwracanych przez ostatnie zapytanie
  • ingres_num_rows — Get the number of rows affected or returned by a query
  • ingres_pconnect — Open a persistent connection to an Ingres database
  • ingres_prepare — Prepare a query for later execution
  • ingres_query — Send an SQL query to Ingres
  • ingres_result_seek — Set the row position before fetching data
  • ingres_rollback — Wycofuje transakcję
  • ingres_set_environment — Set environment features controlling output options
  • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres
Podstawowe użycie
ingres_autocommit_state
Ingres


Test if the connection is using autocommit

Funkcje Ingres
ingres_autocommit
Funkcje Ingres
PHP Manual

ingres_autocommit_state

(PECL ingres >= 2.0.0)

ingres_autocommit_state — Test if the connection is using autocommit

Opis

bool ingres_autocommit_state ( resource $link )

ingres_autocommit_state() is called to determine whether the current link has autocommit enabled or not.

Parametry

link

The connection link identifier

Zwracane wartości

Returns TRUE if autocommit is enabled or FALSE when autocommit is disabled

Zobacz też:

  • ingres_autocommit() - Włącza lub wyłącza automatyczne zatwierdzanie
  • ingres_query() - Send an SQL query to Ingres

Funkcje Ingres
ingres_autocommit
Funkcje Ingres


Włącza lub wyłącza automatyczne zatwierdzanie

ingres_autocommit_state
ingres_charset
Funkcje Ingres
PHP Manual

ingres_autocommit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_autocommit — Włącza lub wyłącza automatyczne zatwierdzanie

Opis

bool ingres_autocommit ( resource $identyfikator_połączenia )

ingres_autocommit() jest wywoływana przed otwarciem transakcji (przed pierwszym wywołaniem ingres_query() lub po wywołaniu ingres_rollback() albo ingres_commit()) aby włączyć lub wyłączyć tryb "automatycznego zatwierdzania" na serwerze (gdy skrypt PHP jest uruchamiany, automatyczne zatwierdzanie jest wyłączone).

Gdy automatyczne zatwierdzanie jest włączone, każde zapytanie jest automatycznie zatwierdzane przez serwer, tak jakby była wywoływana ingres_commit() po każdej funkcji ingres_query(). Aby sprawdzić czy automatyczne zatwierdzanie jest włączone należy użyć funkcji ingres_autocommit_state().

Domyślnie Ingres wycofuje każde niezatwierdzone transakcje na koniec zapytania. Należy korzystać z funkcji ingres_commit(), aby zapewnić potwierdzenie zapisu danych w bazie danych Ingres.

Parametry

identyfikator_połączenia

Identyfikator połączenia

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ingres_autocommit_state() - Test if the connection is using autocommit
  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Wycofuje transakcję
  • ingres_commit() - Zatwierdza transakcję

ingres_autocommit_state
ingres_charset
Funkcje Ingres


Returns the installation character set

ingres_autocommit
ingres_close
Funkcje Ingres
PHP Manual

ingres_charset

(PECL ingres >= 2.1.0)

ingres_charset — Returns the installation character set

Opis

string ingres_charset ( resource $link )

ingres_charset() is called to determine the character set being used by the Ingres client, from II_CHARSETxx (where xx is the installation code).

Informacja:

You can override the value returned by using the function putenv(). Changing the value of II_CHARSETxx in a running Ingres installation can cause data corruption.

Parametry

link

The connection link identifier

Zwracane wartości

Returns a string with the value for II_CHARSETxx or returns NULL if the value could not be determined.

Przykłady

Przykład #1 ingres_charset() - Get the installation character set

<?php
$link = ingres_connect($database, $user, $password);

echo ingres_charset($link) . "\n";

ingres_close($link);
?>

Zobacz też:

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres

ingres_autocommit
ingres_close
Funkcje Ingres


Zamyka połączenie z serwerem Ingres

ingres_charset
ingres_commit
Funkcje Ingres
PHP Manual

ingres_close

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_close — Zamyka połączenie z serwerem Ingres

Opis

bool ingres_close ( resource $identyfikator_połączenia )

ingres_close() zamyka połączenie do serwera Ingres skojarzone z określonym indentyfikatorem połączenia.

ingres_close() zazwyczaj nie jest potrzebne, jako że połączenia stałe nie są zamykane, a wszystkie połączenia niestałe są automatycznie zamykane po zakończeniu wykonywania skryptu.

Parametry

identyfikator_połączenia

Identyfikator połączenia

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_pconnect() - Open a persistent connection to an Ingres database

ingres_charset
ingres_commit
Funkcje Ingres


Zatwierdza transakcję

ingres_close
ingres_connect
Funkcje Ingres
PHP Manual

ingres_commit

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_commit — Zatwierdza transakcję

Opis

bool ingres_commit ( resource $identyfikator_połączenia )

ingres_commit() zatwierdza bieżącą otwartą transakcję, utrwalając wszystkie zmiany dokonane w bazie danych.

Bieżąca transakcja jest zamykana. Nowa transakcja może być rozpoczęta poprzez wysłanie zapytania za pomocą ingres_query().

Można ustawić automatyczne zatwierdzanie transakcji przez serwer po każdym wysłanym zapytaniu, przez wywołanie ingres_autocommit() przed otwarciem transakcji.

Domyślnie Ingres wycofuje każde niezatwierdzone transakcje na koniec zapytania. Używaj tej funkcji albo ingres_autocommit(), aby zapewnić potwierdzenie zapisu danych w bazie danych Ingres.

Parametry

identyfikator_połączenia

Identyfikator połączenia

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Wycofuje transakcję
  • ingres_autocommit() - Włącza lub wyłącza automatyczne zatwierdzanie

ingres_close
ingres_connect
Funkcje Ingres


Open a connection to an Ingres database

ingres_commit
ingres_cursor
Funkcje Ingres
PHP Manual

ingres_connect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_connect — Open a connection to an Ingres database

Opis

resource ingres_connect ([ string $database [, string $username [, string $password [, array $options ]]]] )

ingres_connect() opens a connection with the given Ingres database.

The connection is closed when the script ends or when ingres_close() is called on this link.

Parametry

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user and ingres.default_password.

database

The database name. Must follow the syntax:

[vnode::]dbname[/svr_class]

username

The Ingres user name

password

The password associated with username

options

ingres_connect() options

Option name | Option type | Description | Example
date_century_boundary | integer | The threshold by which a 2-digit year is determined to be in the current century or in the next century. Equivalent to II_DATE_CENTURY_BOUNDARY. | 50
group | string | Specifies the group ID of the user, equivalent to the "-G" flag | payroll
role | string | The role ID of the application. If a role password is required, the parameter value should be specified as "role/password"
effective_user | string | The ingres user account being impersonated, equivalent to the "-u" flag | another_user
dbms_password | string | The internal database password for the user connecting to Ingres | s3cr3t
table_structure string

The default structure for new tables. Valid values for table_structure are:

  • INGRES_STRUCTURE_BTREE
  • INGRES_STRUCTURE_HASH
  • INGRES_STRUCTURE_HEAP
  • INGRES_STRUCTURE_ISAM
  • INGRES_STRUCTURE_CBTREE
  • INGRES_STRUCTURE_CISAM
  • INGRES_STRUCTURE_CHASH
  • INGRES_STRUCTURE_CHEAP

 INGRES_STRUCTURE_BTREE
index_structure string

The default structure for new secondary indexes. Valid values for index_structure are:

  • INGRES_STRUCTURE_CBTREE
  • INGRES_STRUCTURE_CISAM
  • INGRES_STRUCTURE_CHASH
  • INGRES_STRUCTURE_BTREE
  • INGRES_STRUCTURE_HASH
  • INGRES_STRUCTURE_ISAM

 INGRES_STRUCTURE_HASH
login_local | boolean | Determines how the connection user ID and password are used when a VNODE is included in the target database string. If set to TRUE, the user ID and password are used to locally access the VNODE, and the VNODE login information is used to establish the DBMS connection. If set to FALSE, the process user ID is used to access the VNODE, and the connection user ID and password are used in place of the VNODE login information to establish the DBMS connection. This parameter is ignored if no VNODE is included in the target database string. The default is FALSE. | TRUE
timezone | string | Controls the timezone of the session. If not set it will default to the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined, NA-PACIFIC (GMT-8 with Daylight Savings) is used.
date_format integer

Sets the allowable input and output format for Ingres dates. Defaults to the value defined by II_DATE_FORMAT. If II_DATE_FORMAT is not set the default date format is US, e.g. mm/dd/yy. Valid values for date_format are:

  • INGRES_DATE_DMY
  • INGRES_DATE_FINISH
  • INGRES_DATE_GERMAN
  • INGRES_DATE_ISO
  • INGRES_DATE_ISO4
  • INGRES_DATE_MDY
  • INGRES_DATE_MULTINATIONAL
  • INGRES_DATE_MULTINATIONAL4
  • INGRES_DATE_YMD
  • INGRES_DATE_US

 INGRES_DATE_MULTINATIONAL4
decimal_separator string The character identifier for decimal data ","
money_lort integer

Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING
  • INGRES_MONEY_TRAILING

 INGRES_MONEY_TRAILING
money_sign string The currency symbol to be used with the MONEY datatype €
money_precision | integer | The precision of the MONEY datatype | 3
float4_precision | integer | Precision of the FLOAT4 datatype | 10
float8_precision | integer | Precision of the FLOAT8 data | 10
blob_segment_length | integer | The amount of data in bytes to fetch at a time when retrieving BLOB or CLOB data, defaults to 4096 bytes when not explicitly set | 8192

Zwracane wartości

Returns a Ingres link resource on success lub FALSE w przypadku niepowodzenia

Przykłady

Przykład #1 Open a connection to an Ingres database

<?php
$link = ingres_connect("mydb", "user", "pass")
    or die("Could not connect");
echo "Connected successfully";
ingres_close($link);
?>

Zobacz też:

  • ingres_pconnect() - Open a persistent connection to an Ingres database
  • ingres_close() - Zamyka połączenie z serwerem Ingres

ingres_commit
ingres_cursor
Funkcje Ingres


Get a cursor name for a given result resource

ingres_connect
ingres_errno
Funkcje Ingres
PHP Manual

ingres_cursor

(PECL ingres >= 1.1.0)

ingres_cursor — Get a cursor name for a given result resource

Opis

string ingres_cursor ( resource $result )

Returns a string with the active cursor name. If no cursor is active then NULL is returned.

Parametry

result

The query result identifier

Zwracane wartości

Returns a string containing the active cursor name. If no cursor is active then NULL is returned.

Przykłady

Przykład #1 Get cursor name for a query resource

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_prepare($link, "select * from table");

$cursor_name = ingres_cursor($result);

echo $cursor_name;

?>

Zobacz też:

  • ingres_prepare() - Prepare a query for later execution
  • ingres_execute() - Execute a prepared query

ingres_connect
ingres_errno
Funkcje Ingres


Zwraca ostatnio wygenerowany numer błędu Ingres

ingres_cursor
ingres_error
Funkcje Ingres
PHP Manual

ingres_errno

(PECL ingres >= 1.1.0)

ingres_errno — Zwraca ostatnio wygenerowany numer błędu Ingres

Opis

int ingres_errno ([ resource $identyfikator_połączenia ] )

Zwraca liczbę typu integer zawierającą ostatni numer błędu. Jeśli nie wystąpił żaden błąd, zwracane jest 0.

Jeśli podano identyfikator_połączenia ingres_errno() zwraca ostatni numer błędu dla tego połączenia. Jeśli nie podano identyfikatora połączenia ingres_errno() zwraca numer ostatniego błędu dla domyślnego połączenia.

Ta funkcja, ingres_errno(), powinna być zawsze wywołana po wykonaniu zapytania. Wywołanie innej funkcji przed ingres_errno(), wyzeruje lub zmieni dla niej kod ostatniego błędu Ingres.

Parametry

identyfikator_połączenia

Identyfikator połączenia

Zwracane wartości

Zwraca liczbę typu integer zawierającą ostatni numer błędu. Jeśli nie wystąpił żaden błąd, zwracane jest 0.

Przykłady

Przykład #1 Przykład obsługi ostatnio wygenerowanego kodu błędu Ingres

<?php
$identyfikator_polaczenia = ingres_connect($baza_danych, $uzytkownik, $haslo);

$wynik = ingres_query($identyfikator_polaczenia, "select * from nazwa_tabeli");

$kod_bledu = ingres_errno($identyfikator_polaczenia);

if ( $kod_bledu != 0 ) {
   echo "Wystąpił błąd - " . $kod_bledu;
}
?>

Zobacz też:

  • ingres_error() - Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie
  • ingres_errsqlstate() - Zwraca ostatnio wygenerowany kod błędu SQLSTATE
  • ingres_next_error() - Get the next Ingres error

ingres_cursor
ingres_error
Funkcje Ingres


Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie

ingres_errno
ingres_errsqlstate
Funkcje Ingres
PHP Manual

ingres_error

(PECL ingres >= 1.1.0)

ingres_error — Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie

Opis

string ingres_error ([ resource $identyfikator_połączenia ] )

Zwraca łańcuch zawierający informację o ostatnim błędzie, lub NULL jeśli nie wystąpił żaden błąd.

Jeśli podano identyfikator_połączenia jako argument ingres_error() zwraca informację o błędzie dla tego połączenia. Jeśli pominięto identyfikator połączenia, ingres_error() zwraca informację o błędzie dla domyślnego połączenia.

Ta funkcja, ingres_error(), powinna być zawsze wywołana po wykonaniu zapytania. Wywołanie innej funkcji przed ingres_error(), zresetuje lub zmieni dla niej informację o ostatnim błędzie Ingres.

Parametry

identyfikator_połączenia

Identyfikator połączenia

Zwracane wartości

Zwraca łańcuch zawierający informację o ostatnim błędzie, lub NULL jeśli nie wystąpił żaden błąd.

Przykłady

Przykład #1 Przykład obsługi ostatnio wygenerowanego komunikatu o błędzie

<?php
$identyfikator_polaczenia = ingres_connect($baza_danych, $uzytkownik, $haslo);

$wynik = ingres_query("select * from nazwa_tabeli");

$tekst_bledu = ingres_error();

if (!is_null($tekst_bledu)) {
   echo "Wystąpił błąd - " . $tekst_bledu;
}
?>

Zobacz też:

  • ingres_errno() - Zwraca ostatnio wygenerowany numer błędu Ingres
  • ingres_errsqlstate() - Zwraca ostatnio wygenerowany kod błędu SQLSTATE
  • ingres_next_error() - Get the next Ingres error

ingres_errno
ingres_errsqlstate
Funkcje Ingres


Zwraca ostatnio wygenerowany kod błędu SQLSTATE

ingres_error
ingres_escape_string
Funkcje Ingres
PHP Manual

ingres_errsqlstate

(PECL ingres >= 1.1.0)

ingres_errsqlstate — Zwraca ostatnio wygenerowany kod błędu SQLSTATE

Opis

string ingres_errsqlstate ([ resource $identyfikator_połączenia ] )

Zwraca łańcuch zawierający ostatni kod SQLSTATE, lub NULL jeśli nie wystąpił żaden błąd.

Jeśli podano identyfikator_połączenia ingres_errsqlstate() zwraca ostatni numer błędu dla tego połączenia. Jeśli nie podano identyfikatora połączenia ingres_errsqlstate() zwraca numer ostatniego błędu dla domyślnego połączenia.

Ta funkcja, ingres_errsqlstate(), powinna być zawsze wywołana po wykonaniu zapytania. Wywołanie innej funkcji przed ingres_errsqlstate(), wyzeruje lub zmieni dla niej kod ostatniego błędu Ingres.

Parametry

identyfikator_połączenia

Identyfikator połączenia

Zwracane wartości

Zwraca łańcuch zawierający ostatni kod SQLSTATE, lub NULL jeśli nie wystąpił żaden błąd.

Przykłady

Przykład #1 Przykład pobrania ostatnio wygenerowanego kodu SQLSTATE

<?php
$identyfikator_polaczenia = ingres_connect($baza_danych, $uzytkownik, $haslo);

$wynik = ingres_query("select * from nazwa_tabeli");

$error_sqlstate = ingres_errsqlstate();

if (!is_null($error_sqlstate)) {
   echo "Wystąpił błąd - " . $error_sqlstate;
}
?>

Zobacz też:

  • ingres_errno() - Zwraca ostatnio wygenerowany numer błędu Ingres
  • ingres_error() - Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie
  • ingres_next_error() - Get the next Ingres error

ingres_error
ingres_escape_string
Funkcje Ingres


Escape special characters for use in a query

ingres_errsqlstate
ingres_execute
Funkcje Ingres
PHP Manual

ingres_escape_string

(PECL ingres >= 2.1.0)

ingres_escape_string — Escape special characters for use in a query

Opis

string ingres_escape_string ( resource $link , string $source_string )

ingres_escape_string() is used to escape certain characters within a string before it is sent to the database server.

Parametry

link

The connection link identifier

source_string

The source string to be parsed

Zwracane wartości

Returns a string containing the escaped data.

Przykłady

Przykład #1 Escape special characters for use in a query

<?php
$link = ingres_connect($database, $user, $password);

$last_name = "O'Connor";

$sql = sprintf("select * from user_profile where up_last = '%s'", ingres_escape_string( $link, $last_name));

$result = ingres_query($link, $sql);

while ($user = ingres_fetch_object($result))
{
  echo $user->up_first . '<BR/>';
}

ingres_commit($link);

ingres_close($link);

?>

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres

ingres_errsqlstate
ingres_execute
Funkcje Ingres


Execute a prepared query

ingres_escape_string
ingres_fetch_array
Funkcje Ingres
PHP Manual

ingres_execute

(PECL ingres >= 1.1.0)

ingres_execute — Execute a prepared query

Opis

bool ingres_execute ( resource $result [, array $params [, string $types ]] )

Execute a query prepared using ingres_prepare().

Informacja: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parametry

result

The result query identifier

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. See the types parameter in ingres_query() for the list of type codes.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Zatwierdza transakcję
  • ingres_rollback() - Wycofuje transakcję
  • ingres_autocommit() - Włącza lub wyłącza automatyczne zatwierdzanie
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Zwraca ostatnio wygenerowany numer błędu Ingres
  • ingres_error() - Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie

ingres_escape_string
ingres_fetch_array
Funkcje Ingres


Fetch a row of result into an array

ingres_execute
ingres_fetch_assoc
Funkcje Ingres
PHP Manual

ingres_fetch_array

( PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_array — Fetch a row of result into an array

Opis

array ingres_fetch_array ( resource $result [, int $result_type ] )

This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

If two or more columns of the result have the same field names, the last column will take precedence. To access the another column or columns of the same name, you must use the numeric index of the column or make an alias for the column. For example:

<?php

$result = ingres_query($link, "select ap_place as city, ap_ccode as country from airport where ap_iatacode = 'VLL'");
$result = ingres_fetch_array($result);
$foo = $result["city"];
$bar = $result["country"];

?>

With regard to speed, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

By default, arrays created by ingres_fetch_array() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Informacja: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parametry

result

The query result identifier

result_type

The result type. This result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Przykłady

Przykład #1 Fetch a row of result into an array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link,"select * from table");
while ($row = ingres_fetch_array($result)) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
    echo $row[1];          // using enumerated array
    echo $row[2];
}
?>

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Pobiera liczbę pól zwracanych przez ostatnie zapytanie
  • ingres_field_name() - Zwraca nazwę pola z wyniku zapytania
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_execute
ingres_fetch_assoc
Funkcje Ingres


Fetch a row of result into an associative array

ingres_fetch_array
ingres_fetch_object
Funkcje Ingres
PHP Manual

ingres_fetch_assoc

(PECL ingres >= 2.2.2)

ingres_fetch_assoc — Fetch a row of result into an associative array

Opis

array ingres_fetch_assoc ( resource $result )

This function is stores the data fetched from a query executed using ingres_query() in an associative array, using the field names as keys.

With regard to speed, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

By default, arrays created by ingres_fetch_assoc() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Informacja: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parametry

result

The query result identifier

Zwracane wartości

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows

Przykłady

Przykład #1 Fetch a row into an associative array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link,"select * from table");
while ($row = ingres_fetch_assoc($result)) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
}
?>

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Pobiera liczbę pól zwracanych przez ostatnie zapytanie
  • ingres_field_name() - Zwraca nazwę pola z wyniku zapytania
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_fetch_array
ingres_fetch_object
Funkcje Ingres


Fetch a row of result into an object

ingres_fetch_assoc
ingres_fetch_proc_return
Funkcje Ingres
PHP Manual

ingres_fetch_object

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_object — Fetch a row of result into an object

Opis

object ingres_fetch_object ( resource $result [, int $result_type ] )

This function is similar to ingres_fetch_array(), with one difference - an object is returned instead of an array. Indirectly, this means that you can access the data only by the field names and not by their offsets (numbers are illegal property names).

With regard to speed, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Informacja: Related Configurations

See also the ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parametry

link

The query result identifier

result_type

(Optional argument.) result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Zwracane wartości

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows

Przykłady

Przykład #1 Fetch a row into an object

<?php
$link = ingres_connect($database, $user, $password);
$result = ingres_query($link, "select * from table");
while ($row = ingres_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Pobiera liczbę pól zwracanych przez ostatnie zapytanie
  • ingres_field_name() - Zwraca nazwę pola z wyniku zapytania
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_fetch_assoc
ingres_fetch_proc_return
Funkcje Ingres


Get the return value from a procedure call

ingres_fetch_object
ingres_fetch_row
Funkcje Ingres
PHP Manual

ingres_fetch_proc_return

(PECL ingres >= 1.4.0)

ingres_fetch_proc_return — Get the return value from a procedure call

Opis

int ingres_fetch_proc_return ( resource $result )

This function is used to retrieve the return value following the execution of an Ingres database procedure (stored procedure).

Informacja:

If used with a row-producing procedure, this function should be called after all the rows from the procedure have been fetched using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row(). This function will eliminate any rows yet to be fetched should there be any left over.

Parametry

result

The result identifier for a query

Zwracane wartości

Returns an integer if there is a return value otherwise it will return NULL.

Przykłady

Przykład #1 Get the return value from a procedure call

<?php

$link = ingres_connect($database);

if ( ingres_errno() != 0 ) {
    $error_text = ingres_error();
    die($error_text);
}

$result = ingres_query($link, "execute procedure php_proc (value = 1000)");

if ( ingres_errno() != 0 ) {
    $error_text = ingres_error();
    die($error_text);
}

echo "return value - " . ingres_fetch_proc_return($result) . "\n";

ingres_close($link);

?>

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_fetch_object
ingres_fetch_row
Funkcje Ingres


Fetch a row of result into an enumerated array

ingres_fetch_proc_return
ingres_field_length
Funkcje Ingres
PHP Manual

ingres_fetch_row

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_fetch_row — Fetch a row of result into an enumerated array

Opis

array ingres_fetch_row ( resource $result )

ingres_fetch_row() returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 1.

Subsequent calls to ingres_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

By default, arrays created by ingres_fetch_row() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Informacja: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parametry

result

The query result identifier

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Przykłady

Przykład #1 Fetch a row of result into an enumerated array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Zobacz też:

  • ingres_num_fields() - Pobiera liczbę pól zwracanych przez ostatnie zapytanie
  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object

ingres_fetch_proc_return
ingres_field_length
Funkcje Ingres


Get the length of a field

ingres_fetch_row
ingres_field_name
Funkcje Ingres
PHP Manual

ingres_field_length

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_length — Get the length of a field

Opis

int ingres_field_length ( resource $result , int $index )

ingres_field_length() returns the length of a field. This is the number of bytes the server uses to store the field. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Informacja: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametry

result

The query result identifier

index

index is the column number whose length will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Zwracane wartości

Returns the length of a field.

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_fetch_row
ingres_field_name
Funkcje Ingres


Zwraca nazwę pola z wyniku zapytania

ingres_field_length
ingres_field_nullable
Funkcje Ingres
PHP Manual

ingres_field_name

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_name — Zwraca nazwę pola z wyniku zapytania

Opis

string ingres_field_name ( resource $identyfikator_wyniku , int $indeks )

ingres_field_name() zwraca nazwę danego pola z wyniku zapytania.

Informacja: Konfiguracja powiązana

Zobacz ingres.array_index_start w dziale Konfiguracja wykonawcza

Parametry

identyfikator_wyniku

Identyfikator wyniku

indeks

indeks jest numerem pola, którego zostanie zwrócona jego nazwa.

Możliwe wartości indeksu zależą od wartości ingres.array_index_start. Jeśli ingres.array_index_start wynosi 1 (domyślnie) wówczas indeks musi być liczbą pomiędzy 1 i wartością zwróconą przez ingres_num_fields(). Jeśli ingres.array_index_start wynosi 0 wówczas index musi być liczbą pomiędzy 0 i ingres_num_fields() - 1.

Zwracane wartości

Zwraca nazwę danego pola z wyniku zapytania lub FALSE w przypadku niepowodzenia

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_length
ingres_field_nullable
Funkcje Ingres


Sprawdza czy pole może przyjmować wartość NULL

ingres_field_name
ingres_field_precision
Funkcje Ingres
PHP Manual

ingres_field_nullable

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_nullable — Sprawdza czy pole może przyjmować wartość NULL

Opis

bool ingres_field_nullable ( resource $identyfikator_wyniku , int $indeks )

Sprawdza czy do pola można wprowadzić wartość NULL.

Informacja: Konfiguracja powiązana

Zobacz ingres.array_index_start w dziale Konfiguracja wykonawcza

Parametry

identyfikator_wyniku

Identyfikator połączenia

indeks

indeks jest numerem pola, które zostanie sprawdzone, czy może przyjmować wartość NULL.

Możliwe wartości indeksu zależą od wartości ingres.array_index_start. Jeśli ingres.array_index_start wynosi 1 (domyślnie) wówczas indeks musi być liczbą pomiędzy 1 i wartością zwróconą przez ingres_num_fields(). Jeśli ingres.array_index_start wynosi 0 wówczas index musi być liczbą pomiędzy 0 i ingres_num_fields() - 1.

Zwracane wartości

ingres_field_nullable() zwraca TRUE jeśli do pola może być wprowadzona wartość NULL, w przeciwnym przypadku zwraca FALSE

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_name
ingres_field_precision
Funkcje Ingres


Get the precision of a field

ingres_field_nullable
ingres_field_scale
Funkcje Ingres
PHP Manual

ingres_field_precision

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_precision — Get the precision of a field

Opis

int ingres_field_precision ( resource $result , int $index )

ingres_field_precision() returns the precision of a field. This value is used only for decimal, float, and money SQL data types. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Informacja: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametry

result

The query result identifier

index

index is the field whose precision will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Zwracane wartości

Returns the field precision as an integer

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_nullable
ingres_field_scale
Funkcje Ingres


Get the scale of a field

ingres_field_precision
ingres_field_type
Funkcje Ingres
PHP Manual

ingres_field_scale

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_scale — Get the scale of a field

Opis

int ingres_field_scale ( resource $result , int $index )

ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Informacja: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametry

result

The query result identifier

index

index is the field whose scale will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Zwracane wartości

Returns the scale of the field, as an integer

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_precision
ingres_field_type
Funkcje Ingres


Get the type of a field in a query result

ingres_field_scale
ingres_free_result
Funkcje Ingres
PHP Manual

ingres_field_type

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_field_type — Get the type of a field in a query result

Opis

string ingres_field_type ( resource $result , int $index )

Get the type of a field in a query result.

Informacja: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parametry

result

The query result identifier

index

index is the field whose type will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Zwracane wartości

ingres_field_type() returns the type of a field in a query result lub FALSE w przypadku niepowodzenia. Examples of types returned are IIAPI_BYTE_TYPE, IIAPI_CHA_TYPE, IIAPI_DTE_TYPE, IIAPI_FLT_TYPE, IIAPI_INT_TYPE, IIAPI_VCH_TYPE. Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example IIAPI_FLT_TYPE can be a float4 or a float8. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_field_scale
ingres_free_result
Funkcje Ingres


Free the resources associated with a result identifier

ingres_field_type
ingres_next_error
Funkcje Ingres
PHP Manual

ingres_free_result

(PECL ingres >= 2.0.0)

ingres_free_result — Free the resources associated with a result identifier

Opis

bool ingres_free_result ( resource $result )

Parametry

result

The query result identifier

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Free a result resource

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
ingres_free_result($result);

ingres_close($link)

?>

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres

ingres_field_type
ingres_next_error
Funkcje Ingres


Get the next Ingres error

ingres_free_result
ingres_num_fields
Funkcje Ingres
PHP Manual

ingres_next_error

(PECL ingres >= 2.0.0)

ingres_next_error — Get the next Ingres error

Opis

bool ingres_next_error ([ resource $link ] )

Get the next Ingres error for the last executed query. Each call to ingres_next_error() can be followed by a call to ingres_errno(), ingres_error() or ingres_errsqlstate() to get the respective error number, error text, or SQL STATE. While ingres_next_error() returns TRUE, there are more errors to fetch.

Parametry

link

The connection link identifier

Zwracane wartości

ingres_next_error() returns TRUE if there is another error to retrieve or FALSE when there are no more errors

Zobacz też:

  • ingres_errno() - Zwraca ostatnio wygenerowany numer błędu Ingres
  • ingres_error() - Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie
  • ingres_errsqlstate() - Zwraca ostatnio wygenerowany kod błędu SQLSTATE

ingres_free_result
ingres_num_fields
Funkcje Ingres


Pobiera liczbę pól zwracanych przez ostatnie zapytanie

ingres_next_error
ingres_num_rows
Funkcje Ingres
PHP Manual

ingres_num_fields

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_num_fields — Pobiera liczbę pól zwracanych przez ostatnie zapytanie

Opis

int ingres_num_fields ( resource $identyfikator_połączenia )

ingres_num_fields() zwraca liczbę pól dla wyniku zapytania, przekazanego przez serwer Ingres po wywołaniu ingres_query()

Parametry

identyfikator_połączenia

Identyfikator połączenia.

Zwracane wartości

Zwraca liczbę pól.

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_next_error
ingres_num_rows
Funkcje Ingres


Get the number of rows affected or returned by a query

ingres_num_fields
ingres_pconnect
Funkcje Ingres
PHP Manual

ingres_num_rows

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_num_rows — Get the number of rows affected or returned by a query

Opis

int ingres_num_rows ( resource $result )

This function primarily is meant to get the number of rows modified in the database. However, it can be used to retrieve the number of rows to fetch for a SELECT statement.

Informacja:

If scrollable cursors are disabled and this function is called before using ingres_fetch_array(), ingres_fetch_object(), or ingres_fetch_row(), the server will delete the result's data and the script will be unable to get them.

Instead, you should retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.

Parametry

result

The result identifier for a query

Zwracane wartości

For delete, insert, or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_num_fields
ingres_pconnect
Funkcje Ingres


Open a persistent connection to an Ingres database

ingres_num_rows
ingres_prepare
Funkcje Ingres
PHP Manual

ingres_pconnect

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_pconnect — Open a persistent connection to an Ingres database

Opis

resource ingres_pconnect ([ string $database [, string $username [, string $password [, array $options ]]]] )

Open a persistent connection to an Ingres database.

There are only two differences between this function and ingres_connect(): First, when connecting, the function will initially try to find a (persistent) link that is already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called "persistent".

Parametry

database

The database name. Must follow the syntax:

[vnode::]dbname[/svr_class]

username

The Ingres user name

password

The password associated with username

options

See ingres_connect() for the list of options that can be passed

Zwracane wartości

Returns an Ingres link resource on success lub FALSE w przypadku niepowodzenia

Zobacz też:

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_close() - Zamyka połączenie z serwerem Ingres

ingres_num_rows
ingres_prepare
Funkcje Ingres


Prepare a query for later execution

ingres_pconnect
ingres_query
Funkcje Ingres
PHP Manual

ingres_prepare

(PECL ingres >= 1.1.0)

ingres_prepare — Prepare a query for later execution

Opis

mixed ingres_prepare ( resource $link , string $query )

Prepares a query for execution by ingres_execute().

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed.

Informacja: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parametry

link

The connection link identifier

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation. See the query parameter in ingres_query() for a list of SQL statements which cannot be executed using ingres_prepare()

Zwracane wartości

ingres_prepare() returns a query result identifier that
is used with ingres_execute() to execute the query. To see
if an error occurred, use ingres_errno(),
ingres_error(), or
ingres_errsqlstate().

Zobacz też:

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Zatwierdza transakcję
  • ingres_rollback() - Wycofuje transakcję
  • ingres_autocommit() - Włącza lub wyłącza automatyczne zatwierdzanie
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Zwraca ostatnio wygenerowany numer błędu Ingres
  • ingres_error() - Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie

ingres_pconnect
ingres_query
Funkcje Ingres


Send an SQL query to Ingres

ingres_prepare
ingres_result_seek
Funkcje Ingres
PHP Manual

ingres_query

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_query — Send an SQL query to Ingres

Opis

mixed ingres_query ( resource $link , string $query [, array $params [, string $types ]] )

ingres_query() sends the given query to the Ingres server.

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed.

Informacja: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration

Parametry

link

The connection link identifier.

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation.

Data inside the query should be properly escaped.

The following types of SQL queries cannot be sent with this function:

  • close (see ingres_close())
  • commit (see ingres_commit())
  • connect (see ingres_connect())
  • disconnect (see ingres_close())
  • get dbevent
  • prepare to commit
  • rollback (see ingres_rollback())
  • savepoint
  • set autocommit (see ingres_autocommit())
  • all cursor-related queries are unsupported

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. When ingres.describe is enabled, this parameter can be ignored as the driver automatically fetches the expected parameter types from the server.

Type code | Ingres type
a | BOOLEAN
b | BYTE
B | LONG BYTE/BLOB
c | CHAR
d | DATE/ANSIDATE/TIMESTAMP/TIME
f | FLOAT
i | INTEGER
L | LONG TEXT
m | MONEY
M | LONG NVARCHAR
n | NCHAR
N | NVARCHAR
t | TEXT
v | VARCHAR
V | LONG VARCHAR

Zwracane wartości

ingres_query() returns a query result identifier on
success else it returns FALSE. To see if an error
occurred use ingres_errno(),
ingres_error() or
ingres_errsqlstate().

Przykłady

Przykład #1 Send a simple select

<?php
$link = ingres_connect("demodb");

$result = ingres_query($link, "select * from user_profile");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Przykład #2 Passing query parameters to ingres_query()

<?php
$link = ingres_connect("demodb");

$params[] = "Emma";
$query = "select * from user_profile where up_first = ?";
$result = ingres_query($link, $query, $params);
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Przykład #3 Inserting a BLOB with parameter types

<?php
$link = ingres_connect("demodb");

//Open a photo
$fh = fopen("photo.jpg","r");
$blob_data = stream_get_contents($fh);
fclose($fh);

//Prepare parameters
$params[] = $blob_data;
$params[] = 1201;

//Define parameter types
$param_types = "Bi";

$query = "update user_profile set up_image = ? where up_id = ?";
$result = ingres_query($link, $query , $params, $param_types);

if (ingres_errno())
{
    echo ingres_errno() . "-" . ingres_error() . "\n";
}

ingres_commit($link);

ingres_close($link);
?>

Zobacz też:

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Zatwierdza transakcję
  • ingres_rollback() - Wycofuje transakcję
  • ingres_autocommit() - Włącza lub wyłącza automatyczne zatwierdzanie
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Zwraca ostatnio wygenerowany numer błędu Ingres
  • ingres_error() - Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie

ingres_prepare
ingres_result_seek
Funkcje Ingres


Set the row position before fetching data

ingres_query
ingres_rollback
Funkcje Ingres
PHP Manual

ingres_result_seek

(PECL ingres >= 2.1.0)

ingres_result_seek — Set the row position before fetching data

Opis

bool ingres_result_seek ( resource $result , int $position )

This function is used to position the cursor associated with the result resource before issuing a fetch. If ingres.array_index_start is set to 0 then the first row is 0 else it is 1. ingres_result_seek() can be used only with queries that make use of scrollable cursors. It cannot be used with ingres_unbuffered_query().

Informacja: Related Configurations

See also the ingres.scrollable and ingres.array_index_start directives in Runtime Configuration.

Parametry

result

The result identifier for a query

position

The row to position the cursor on. If ingres.array_index_start is set to 0, then the first row is 0, else it is 1

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Position the cursor on the 3rd row

<?php

$result=ingres_query($link, "select * from airport where ap_ccode = 'ES' order by ap_place asc");

/* goto row 3 */
if (!ingres_result_seek($result, 3))
{
    echo ingres_errno() . " - " . ingres_error . "\n";
    die("i died");
}
else
{
    $airport = ingres_fetch_object ($result);
    {
        echo $airport->ap_iatacode . " - " .  $airport->ap_name . "\n";
    }
}

ingres_commit($link);

?>

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array

ingres_query
ingres_rollback
Funkcje Ingres


Wycofuje transakcję

ingres_result_seek
ingres_set_environment
Funkcje Ingres
PHP Manual

ingres_rollback

(PHP 4 >= 4.0.2, PHP 5 <= 5.0.5, PECL ingres >= 1.0.0)

ingres_rollback — Wycofuje transakcję

Opis

bool ingres_rollback ( resource $identyfikator_połączenia )

ingres_rollback() wycofuje bieżącą, otwartą transakcję, w rzeczywistości anulując wszystkie zmiany zrobione w bazie danych w czasie trwania tej transakcji.

Bieżąca transakcja jest zamykana. Nowa transakcja może być rozpoczęta przez wysłanie zapytania za pomocą ingres_query().

Parametry

identyfikator_połączenia

Identyfikator połączenia.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_commit() - Zatwierdza transakcję
  • ingres_autocommit() - Włącza lub wyłącza automatyczne zatwierdzanie

ingres_result_seek
ingres_set_environment
Funkcje Ingres


Set environment features controlling output options

ingres_rollback
ingres_unbuffered_query
Funkcje Ingres
PHP Manual

ingres_set_environment

(PECL ingres >= 1.2.0)

ingres_set_environment — Set environment features controlling output options

Opis

bool ingres_set_environment ( resource $link , array $options )

ingres_set_environment() is called to set environmental options that affect the output of certain values from Ingres, such as the timezone, date format, decimal character separator, and float precision.

Parametry

link

The connection link identifier

options

An enumerated array of option name/value pairs. The following table lists the option name and the expected type

Option name | Option type | Description | Example
date_century_boundary | integer | The threshold by which a 2-digit year is determined to be in the current century or in the next century. Equivalent to II_DATE_CENTURY_BOUNDARY | 50
timezone | string | Controls the timezone of the session. If not set, it will default the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined, NA-PACIFIC (GMT-8 with Daylight Savings) is used. | UNITED-KINGDOM
date_format integer

Sets the allowable input and output format for Ingres dates. Defaults to the value defined by II_DATE_FORMAT. If II_DATE_FORMAT is not set, the default date format is US, for example mm/dd/yy. Valid values for date_format are:

  • INGRES_DATE_DMY
  • INGRES_DATE_FINISH
  • INGRES_DATE_GERMAN
  • INGRES_DATE_ISO
  • INGRES_DATE_ISO4
  • INGRES_DATE_MDY
  • INGRES_DATE_MULTINATIONAL
  • INGRES_DATE_MULTINATIONAL4
  • INGRES_DATE_YMD
  • INGRES_DATE_US

 INGRES_DATE_ISO4
decimal_separator string The character identifier for decimal data ","
money_lort integer

Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING
  • INGRES_MONEY_TRAILING

 INGRES_MONEY_LEADING
money_sign string The currency symbol to be used with the MONEY datatype €
money_precision | integer | The precision of the MONEY datatype | 2
float4_precision | integer | Precision of the FLOAT4 datatype | 10
float8_precision | integer | Precision of the FLOAT8 data | 10
blob_segment_length | integer | The amount of data in bytes to fetch at a time when retrieving BLOB or CLOB data. Defaults to 4096 bytes when not set explicitly | 8192

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Set date_format to ISO4

<?php
$options = array( "date_format" => INGRES_DATE_ISO4 );

if (ingres_set_environment($link, $options))
{
    $result=ingres_query($link,"select date('now') as date");

    while ( $object = ingres_fetch_object ($result) ) {
        echo $object->date."\n";
    }
}
?>

Przykład #2 Set timezone to HONG-KONG

<?php

$options = array( "timezone" => "HONG-KONG");

if (ingres_set_environment($link, $options))
{
    $result=ingres_query($link,"select date('now') as date");

    while ( $object = ingres_fetch_object ($result) ) {
        echo $object->date."\n";
    }
}
?>

Zobacz też:

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres

ingres_rollback
ingres_unbuffered_query
Funkcje Ingres


Send an unbuffered SQL query to Ingres

ingres_set_environment
MaxDB
Funkcje Ingres
PHP Manual

ingres_unbuffered_query

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

ingres_unbuffered_query — Send an unbuffered SQL query to Ingres

Opis

mixed ingres_unbuffered_query ( resource $link , string $query [, array $params [, string $types ]] )

ingres_unbuffered_query() sends the given query to the Ingres server.

The query becomes part of the currently open transaction. If there is no open transaction, ingres_unbuffered_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed. Ingres allows only a single unbuffered statement to be active at any one time. The extension will close any active unbuffered statements before executing any SQL. In addition you cannot use ingres_result_seek() to position the row before fetching.

Informacja: Related Configurations

See also the ingres.describe and ingres.utf8 directives in Runtime Configuration.

Parametry

link

The connection link identifier

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation. See the query parameter in ingres_query() for a list of SQL statements that cannot be executed via ingres_unbuffered_query().

Data inside the query should be properly escaped.

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. See the types parameter in ingres_query() for the list of type codes.

Zwracane wartości

ingres_unbuffered_query() returns a query result identifier when there are rows to fetch; else it returns FALSE when there are no rows, as is the case of an INSERT, UPDATE, or DELETE statement. To see if an error occurred, use ingres_errno(), ingres_error(), or ingres_errsqlstate().

Przykłady

Przykład #1 Issue a simple un-buffered select

<?php
$link = ingres_connect("demodb");

$result = ingres_unbuffered_query($link, "select * from user_profile");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Przykład #2 Passing query parameters to ingres_unbuffered_query()

<?php
$link = ingres_connect("demodb");

$params[] = "Emma";
$query = "select * from user_profile where up_first = ?";
$result = ingres_unbuffered_query($link, $query, $params);
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Przykład #3 Inserting a BLOB with parameter types

<?php
$link = ingres_connect("demodb");

//Open a photo
$fh = fopen("photo.jpg","r");
$blob_data = stream_get_contents($fh);
fclose($fh);

//Prepare parameters
$params[] = $blob_data;
$params[] = 1201;

//Define parameter types
$param_types = "Bi";

$query = "update user_profile set up_image = ? where up_id = ?";
$result = ingres_unbuffered_query($link, $query , $params, $param_types);

if (ingres_errno())
{
    echo ingres_errno() . "-" . ingres_error() . "\n";
}
?>

Zobacz też:

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Zatwierdza transakcję
  • ingres_rollback() - Wycofuje transakcję
  • ingres_autocommit() - Włącza lub wyłącza automatyczne zatwierdzanie
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Zwraca ostatnio wygenerowany numer błędu Ingres
  • ingres_error() - Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie

ingres_set_environment
MaxDB
Funkcje Ingres


MaxDB

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • MaxDB Funkcje
    • maxdb_affected_rows — Gets the number of affected rows in a previous MaxDB operation
    • maxdb_autocommit — Turns on or off auto-commiting database modifications
    • maxdb_bind_param — Alias dla maxdb_stmt_bind_param
    • maxdb_bind_result — Alias dla maxdb_stmt_bind_result
    • maxdb_change_user — Changes the user of the specified database connection
    • maxdb_character_set_name — Returns the default character set for the database connection
    • maxdb_client_encoding — Alias dla maxdb_character_set_name
    • maxdb_close_long_data — Alias dla maxdb_stmt_close_long_data
    • maxdb_close — Closes a previously opened database connection
    • maxdb_commit — Commits the current transaction
    • maxdb_connect_errno — Returns the error code from last connect call
    • maxdb_connect_error — Returns a string description of the last connect error
    • maxdb_connect — Open a new connection to the MaxDB server
    • maxdb_data_seek — Adjusts the result pointer to an arbitary row in the result
    • maxdb_debug — Performs debugging operations
    • maxdb_disable_reads_from_master — Disable reads from master
    • maxdb_disable_rpl_parse — Disable RPL parse
    • maxdb_dump_debug_info — Dump debugging information into the log
    • maxdb_embedded_connect — Open a connection to an embedded MaxDB server
    • maxdb_enable_reads_from_master — Enable reads from master
    • maxdb_enable_rpl_parse — Enable RPL parse
    • maxdb_errno — Returns the error code for the most recent function call
    • maxdb_error — Returns a string description of the last error
    • maxdb_escape_string — Alias dla maxdb_real_escape_string
    • maxdb_execute — Alias dla maxdb_stmt_execute
    • maxdb_fetch_array — Fetch a result row as an associative, a numeric array, or both
    • maxdb_fetch_assoc — Fetch a result row as an associative array
    • maxdb_fetch_field_direct — Fetch meta-data for a single field
    • maxdb_fetch_field — Returns the next field in the result set
    • maxdb_fetch_fields — Returns an array of resources representing the fields in a result set
    • maxdb_fetch_lengths — Returns the lengths of the columns of the current row in the result set
    • maxdb_fetch_object — Returns the current row of a result set as an object
    • maxdb_fetch_row — Get a result row as an enumerated array
    • maxdb_fetch — Alias dla maxdb_stmt_fetch
    • maxdb_field_count — Returns the number of columns for the most recent query
    • maxdb_field_seek — Set result pointer to a specified field offset
    • maxdb_field_tell — Get current field offset of a result pointer
    • maxdb_free_result — Frees the memory associated with a result
    • maxdb_get_client_info — Returns the MaxDB client version as a string
    • maxdb_get_client_version — Get MaxDB client info
    • maxdb_get_host_info — Returns a string representing the type of connection used
    • maxdb_get_metadata — Alias dla maxdb_stmt_result_metadata
    • maxdb_get_proto_info — Returns the version of the MaxDB protocol used
    • maxdb_get_server_info — Returns the version of the MaxDB server
    • maxdb_get_server_version — Returns the version of the MaxDB server as an integer
    • maxdb_info — Retrieves information about the most recently executed query
    • maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect
    • maxdb_insert_id — Returns the auto generated id used in the last query
    • maxdb_kill — Disconnects from a MaxDB server
    • maxdb_master_query — Enforce execution of a query on the master in a master/slave setup
    • maxdb_more_results — Check if there any more query results from a multi query
    • maxdb_multi_query — Performs a query on the database
    • maxdb_next_result — Prepare next result from multi_query
    • maxdb_num_fields — Get the number of fields in a result
    • maxdb_num_rows — Gets the number of rows in a result
    • maxdb_options — Set options
    • maxdb_param_count — Alias dla maxdb_stmt_param_count
    • maxdb_ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • maxdb_prepare — Prepare an SQL statement for execution
    • maxdb_query — Performs a query on the database
    • maxdb_real_connect — Opens a connection to a MaxDB server
    • maxdb_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • maxdb_real_query — Execute an SQL query
    • maxdb_report — Enables or disables internal report functions
    • maxdb_rollback — Rolls back current transaction
    • maxdb_rpl_parse_enabled — Check if RPL parse is enabled
    • maxdb_rpl_probe — RPL probe
    • maxdb_rpl_query_type — Returns RPL query type
    • maxdb_select_db — Selects the default database for database queries
    • maxdb_send_long_data — Alias dla maxdb_stmt_send_long_data
    • maxdb_send_query — Send the query and return
    • maxdb_server_end — Shut down the embedded server
    • maxdb_server_init — Initialize embedded server
    • maxdb_set_opt — Alias dla maxdb_options
    • maxdb_sqlstate — Returns the SQLSTATE error from previous MaxDB operation
    • maxdb_ssl_set — Used for establishing secure connections using SSL
    • maxdb_stat — Gets the current system status
    • maxdb_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • maxdb_stmt_bind_param — Binds variables to a prepared statement as parameters
    • maxdb_stmt_bind_result — Binds variables to a prepared statement for result storage
    • maxdb_stmt_close_long_data — Ends a sequence of maxdb_stmt_send_long_data
    • maxdb_stmt_close — Closes a prepared statement
    • maxdb_stmt_data_seek — Seeks to an arbitray row in statement result set
    • maxdb_stmt_errno — Returns the error code for the most recent statement call
    • maxdb_stmt_error — Returns a string description for last statement error
    • maxdb_stmt_execute — Executes a prepared Query
    • maxdb_stmt_fetch — Fetch results from a prepared statement into the bound variables
    • maxdb_stmt_free_result — Frees stored result memory for the given statement handle
    • maxdb_stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare
    • maxdb_stmt_num_rows — Return the number of rows in statements result set
    • maxdb_stmt_param_count — Returns the number of parameter for the given statement
    • maxdb_stmt_prepare — Prepare an SQL statement for execution
    • maxdb_stmt_reset — Resets a prepared statement
    • maxdb_stmt_result_metadata — Returns result set metadata from a prepared statement
    • maxdb_stmt_send_long_data — Send data in blocks
    • maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation
    • maxdb_stmt_store_result — Transfers a result set from a prepared statement
    • maxdb_store_result — Transfers a result set from the last query
    • maxdb_thread_id — Returns the thread ID for the current connection
    • maxdb_thread_safe — Returns whether thread safety is given or not
    • maxdb_use_result — Initiate a result set retrieval
    • maxdb_warning_count — Returns the number of warnings from the last query for the given link
ingres_unbuffered_query
Wstęp
Rozszerzenia producentów baz danych


Wstęp

The MaxDB PHP extension allows you to access the functionality provided by MaxDB 7.5.0 and above. More information about the MaxDB Database server can be found at » http://www.sdn.sap.com/irj/sdn/maxdb.

The MaxDB PHP extension is compatible to the MySQL mysqli extension. There are only minor differences in the behaviour of some functions due to the differences of the underlying database servers, MaxDB and MySQL.

The main differences to mysqli are in the following functions:

  • maxdb_character_set_name() - Returns only ascii or unicode.
  • maxdb_get_client_info() - Returns a different version string.
  • maxdb_get_client_version() - Returns a different version string.
  • maxdb_get_host_info() - Returns localhost or hostname.
  • maxdb_get_server_info() - Returns a different version string.
  • maxdb_get_server_version() - Returns a different version string.
  • maxdb_kill() - Only disconnects the session.
  • maxdb_multi_query() - Can not handle multiple SQL statements.
  • maxdb_next_result() - Function returns always false.
  • maxdb_options() - Supports a different set of options.
  • maxdb_report() - Supports a different report mode.
  • maxdb_stat() - Returns a different system status string.
  • maxdb_stmt_store_result() - Is not necessary for MaxDB.
  • maxdb_store_result() - Is not necessary for MaxDB.

Documentation for MaxDB can be found at » http://maxdb.sap.com/documentation/.

MaxDB
Instalacja/Konfiguracja
MaxDB


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
MaxDB


Wymagania

In order to have these functions available, you must compile PHP with MaxDB support. Additionally, you must have the MaxDB SQLDBC runtime library available to access the MaxDB server.

Documentation for MaxDB SQLDBC can be found at » http://maxdb.sap.com/documentation/.

Download the MaxDB SQLDBC package from » http://www.sdn.sap.com/irj/sdn/maxdb-downloads.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

By using the --with-maxdb[=DIR] configuration option you enable PHP to access MaxDB databases. [DIR] points to the directory that contains the installed MaxDB SQLDBC package.

Windows users will need to enable php_maxdb.dll inside of php.ini.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

MaxDB Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
maxdb.default_host | NULL | PHP_INI_ALL |
maxdb.default_db | NULL | PHP_INI_ALL |
maxdb.default_user | NULL | PHP_INI_ALL |
maxdb.default_pw | NULL | PHP_INI_ALL |
maxdb.long_readlen | "200" | 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.

maxdb.default_host string

The default server host to use when connecting to the database server if no other host is specified.

maxdb.default_db string

The default server database to use when connecting if no other database is specified.

maxdb.default_user string

The default user name to use when connecting to the database server if no other name is specified.

maxdb.default_pw string

The default password to use when connecting to the database server if no other password is specified.

maxdb.long_readlen integer

The default maximum length of bytes that is transferred to the client if long data is retrieved from the MaxDB database server.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines resources.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

The following constants to use with maxdb_options() are defined. For further description of these constants see » http://maxdb.sap.com/documentation/.

MaxDB PHP client constants
Constant | Description
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATION | The application to be connected to the database.
MAXDB_APPVERSION | The version of the application.
MAXDB_SQLMODE | The SQL mode.
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not.
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system.
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released.
MAXDB_PACKETCOUNT | The number of different request packets used for the connection.
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use.
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named.

The function maxdb_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:

MaxDB fetch constants
Constant | Description
MAXDB_ASSOC | Columns are returned into the array having the fieldname as the array index.
MAXDB_ASSOC_UPPER | Columns are returned into the array having the upper case fieldname as the array index.
MAXDB_ASSOC_LOWER | Columns are returned into the array having the lower case fieldname as the array index.
MAXDB_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index.
MAXDB_NUM | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

Typy zasobów
Przykłady
MaxDB


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
MaxDB


Basic usage

All examples in the MaxDB PHP documentation use the HOTELDB demo database from MaxDB. More about this database can be found at » http://maxdb.sap.com/doc/7_7/44/d8c25164bb38d0e10000000a1553f7/content.htm.

To use the examples in the MaxDB PHP documentation, you have to load the tutorial data into your database. Then you have to set maxdb.default_db in php.ini to the database that contains the tutorial data.

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MaxDB database.

Przykład #1 MaxDB extension overview example

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$query = "SELECT * FROM hotel.city";
$result = maxdb_query($link, $query) or die("Query failed : " . maxdb_error());

/* Printing results in HTML */
echo "<table>\n";
while ($line = maxdb_fetch_array($result, MAXDB_ASSOC)) {
    echo "  <tr>\n";
    foreach ($line as $col_value) {
        echo "    <td>$col_value</td>\n";
    }
    echo "  </tr>\n";
}
echo "</table>\n";

/* Free resultset */
maxdb_free_result($result);

/* Closing connection */
maxdb_close($link);
?>

The following example shows how to bind variables to a SELECT INTO statement.

Przykład #2 Example for use of SELECT INTO statements

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT percentage INTO ? FROM hotel.countrylanguage where language = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$name = "Mbundu";

maxdb_stmt_bind_param($stmt, 'ds', $percentage, $name);
maxdb_stmt_execute($stmt);

printf ("%f\n", $percentage);

maxdb_stmt_close ($stmt);
?>

The following example shows how to use MaxDB database procedures.

Przykład #3 Example fore using database procedures

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?>

Przykłady
MaxDB Funkcje
Przykłady


Basic usage
maxdb_affected_rows
MaxDB
PHP Manual

MaxDB Funkcje

Klasy predefiniowane

maxdb

Represents a connection between PHP and a MaxDB database.

Konstruktor

  • maxdb - construct a new maxdb object

Metody

  • autocommit - turns on or off auto-commiting database modifications

  • change_user - changes the user of the specified database connection

  • character_set_name - returns the default character set for the database connection

  • close - closes a previously opened connection

  • commit - commits the current transaction

  • connect - opens a new connection to MaxDB database server

  • debug - performs debugging operations

  • dump_debug_info - dumps debug information

  • get_client_info - returns client version

  • get_host_info - returns type of connection used

  • get_server_info - returns version of the MaxDB server

  • get_server_version - returns version of the MaxDB server

  • init - initializes maxdb object

  • info - retrieves information about the most recently executed query

  • kill - asks the server to kill a MaxDB thread

  • multi_query - performs multiple queries

  • more_results - check if more results exist from currently executed multi-query

  • next_result - reads next result from currently executed multi-query

  • options - set options

  • ping - pings a server connection or reconnects if there is no connection

  • prepare - prepares an SQL query

  • query - performs a query

  • real_connect - attempts to open a connection to MaxDB database server

  • escape_string - escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

  • rollback - rolls back the current transaction

  • select_db - selects the default database

  • ssl_set - sets ssl parameters

  • stat - gets the current system status

  • stmt_init- initializes a statement for use with maxdb_stmt_prepare

  • store_result - transfers a resultset from last query

  • use_result - transfers an unbuffered resultset from last query

  • thread-safe - returns whether thread safety is given or not

Właściwości

  • affected_rows - gets the number of affected rows in a previous MaxDB operation

  • client_info - returns the MaxDB client version as a string

  • client_version - returns the MaxDB client version as an integer

  • errno - returns the error code for the most recent function call

  • error - returns the error string for the most recent function call

  • field_count - returns the number of columns for the most recent query

  • host_info - returns a string representing the type of connection used

  • info - retrieves information about the most recently executed query

  • insert_id - returns the auto generated id used in the last query

  • protocol_version - returns the version of the MaxDB protocol used

  • sqlstate - returns a string containing the SQLSTATE error code for the last error

  • thread_id - returns the thread ID for the current connection

  • warning_count - returns the number of warnings generated during execution of the previous SQL statement

maxdb_stmt

Represents a prepared statement.

Metody

  • bind_param - binds variables to a prepared statement

  • bind_result - binds variables to a prepared statement for result storage

  • close - closes a prepared statement

  • data-seek - seeks to an arbitrary row in a statement result set

  • execute - executes a prepared statement

  • fetch - fetches result from a prepared statement into bound variables

  • free_result - frees stored result memory for the given statement handle

  • result_metadata - retrieves a resultset from a prepared statement for metadata information

  • prepare - prepares an SQL query

  • send_long_data - sends data in chunks

  • close_long_data - end sending long data

  • reset - resets a prepared statement

  • store_result - buffers complete resultset from a prepared statement

Właściwości

  • affected_rows - returns affected rows from last statement execution

  • errno - returns errorcode for last statement function

  • errno - returns errormessage for last statement function

  • param_count - returns number of parameter for a given prepare statement

  • sqlstate - returns a string containing the SQLSTATE error code for the last statement function

maxdb_result

Represents the result set obtained from a query against the database.

Metody

  • close - closes resultset

  • data_seek - moves internal result pointer

  • fetch_field - gets column information from a resultset

  • fetch_fields - gets information for all columns from a resulset

  • fetch_field_direct - gets column information for specified column

  • fetch_array - fetches a result row as an associative array, a numeric array, or both.

  • fetch_assoc - fetches a result row as an associative array

  • fetch_object - fetches a result row as an object

  • fetch_row - gets a result row as an enumerated array

  • close - frees result memory

  • field_seek - set result pointer to a specified field offset

Właściwości

  • current_field - returns offset of current fieldpointer

  • field_count - returns number of fields in resultset

  • lengths - returns an array of columnlengths

  • num_rows - returns number of rows in resultset

Spis treści

  • maxdb_affected_rows — Gets the number of affected rows in a previous MaxDB operation
  • maxdb_autocommit — Turns on or off auto-commiting database modifications
  • maxdb_bind_param — Alias dla maxdb_stmt_bind_param
  • maxdb_bind_result — Alias dla maxdb_stmt_bind_result
  • maxdb_change_user — Changes the user of the specified database connection
  • maxdb_character_set_name — Returns the default character set for the database connection
  • maxdb_client_encoding — Alias dla maxdb_character_set_name
  • maxdb_close_long_data — Alias dla maxdb_stmt_close_long_data
  • maxdb_close — Closes a previously opened database connection
  • maxdb_commit — Commits the current transaction
  • maxdb_connect_errno — Returns the error code from last connect call
  • maxdb_connect_error — Returns a string description of the last connect error
  • maxdb_connect — Open a new connection to the MaxDB server
  • maxdb_data_seek — Adjusts the result pointer to an arbitary row in the result
  • maxdb_debug — Performs debugging operations
  • maxdb_disable_reads_from_master — Disable reads from master
  • maxdb_disable_rpl_parse — Disable RPL parse
  • maxdb_dump_debug_info — Dump debugging information into the log
  • maxdb_embedded_connect — Open a connection to an embedded MaxDB server
  • maxdb_enable_reads_from_master — Enable reads from master
  • maxdb_enable_rpl_parse — Enable RPL parse
  • maxdb_errno — Returns the error code for the most recent function call
  • maxdb_error — Returns a string description of the last error
  • maxdb_escape_string — Alias dla maxdb_real_escape_string
  • maxdb_execute — Alias dla maxdb_stmt_execute
  • maxdb_fetch_array — Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc — Fetch a result row as an associative array
  • maxdb_fetch_field_direct — Fetch meta-data for a single field
  • maxdb_fetch_field — Returns the next field in the result set
  • maxdb_fetch_fields — Returns an array of resources representing the fields in a result set
  • maxdb_fetch_lengths — Returns the lengths of the columns of the current row in the result set
  • maxdb_fetch_object — Returns the current row of a result set as an object
  • maxdb_fetch_row — Get a result row as an enumerated array
  • maxdb_fetch — Alias dla maxdb_stmt_fetch
  • maxdb_field_count — Returns the number of columns for the most recent query
  • maxdb_field_seek — Set result pointer to a specified field offset
  • maxdb_field_tell — Get current field offset of a result pointer
  • maxdb_free_result — Frees the memory associated with a result
  • maxdb_get_client_info — Returns the MaxDB client version as a string
  • maxdb_get_client_version — Get MaxDB client info
  • maxdb_get_host_info — Returns a string representing the type of connection used
  • maxdb_get_metadata — Alias dla maxdb_stmt_result_metadata
  • maxdb_get_proto_info — Returns the version of the MaxDB protocol used
  • maxdb_get_server_info — Returns the version of the MaxDB server
  • maxdb_get_server_version — Returns the version of the MaxDB server as an integer
  • maxdb_info — Retrieves information about the most recently executed query
  • maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_insert_id — Returns the auto generated id used in the last query
  • maxdb_kill — Disconnects from a MaxDB server
  • maxdb_master_query — Enforce execution of a query on the master in a master/slave setup
  • maxdb_more_results — Check if there any more query results from a multi query
  • maxdb_multi_query — Performs a query on the database
  • maxdb_next_result — Prepare next result from multi_query
  • maxdb_num_fields — Get the number of fields in a result
  • maxdb_num_rows — Gets the number of rows in a result
  • maxdb_options — Set options
  • maxdb_param_count — Alias dla maxdb_stmt_param_count
  • maxdb_ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • maxdb_prepare — Prepare an SQL statement for execution
  • maxdb_query — Performs a query on the database
  • maxdb_real_connect — Opens a connection to a MaxDB server
  • maxdb_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • maxdb_real_query — Execute an SQL query
  • maxdb_report — Enables or disables internal report functions
  • maxdb_rollback — Rolls back current transaction
  • maxdb_rpl_parse_enabled — Check if RPL parse is enabled
  • maxdb_rpl_probe — RPL probe
  • maxdb_rpl_query_type — Returns RPL query type
  • maxdb_select_db — Selects the default database for database queries
  • maxdb_send_long_data — Alias dla maxdb_stmt_send_long_data
  • maxdb_send_query — Send the query and return
  • maxdb_server_end — Shut down the embedded server
  • maxdb_server_init — Initialize embedded server
  • maxdb_set_opt — Alias dla maxdb_options
  • maxdb_sqlstate — Returns the SQLSTATE error from previous MaxDB operation
  • maxdb_ssl_set — Used for establishing secure connections using SSL
  • maxdb_stat — Gets the current system status
  • maxdb_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • maxdb_stmt_bind_param — Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result — Binds variables to a prepared statement for result storage
  • maxdb_stmt_close_long_data — Ends a sequence of maxdb_stmt_send_long_data
  • maxdb_stmt_close — Closes a prepared statement
  • maxdb_stmt_data_seek — Seeks to an arbitray row in statement result set
  • maxdb_stmt_errno — Returns the error code for the most recent statement call
  • maxdb_stmt_error — Returns a string description for last statement error
  • maxdb_stmt_execute — Executes a prepared Query
  • maxdb_stmt_fetch — Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_free_result — Frees stored result memory for the given statement handle
  • maxdb_stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_num_rows — Return the number of rows in statements result set
  • maxdb_stmt_param_count — Returns the number of parameter for the given statement
  • maxdb_stmt_prepare — Prepare an SQL statement for execution
  • maxdb_stmt_reset — Resets a prepared statement
  • maxdb_stmt_result_metadata — Returns result set metadata from a prepared statement
  • maxdb_stmt_send_long_data — Send data in blocks
  • maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation
  • maxdb_stmt_store_result — Transfers a result set from a prepared statement
  • maxdb_store_result — Transfers a result set from the last query
  • maxdb_thread_id — Returns the thread ID for the current connection
  • maxdb_thread_safe — Returns whether thread safety is given or not
  • maxdb_use_result — Initiate a result set retrieval
  • maxdb_warning_count — Returns the number of warnings from the last query for the given link
Basic usage
maxdb_affected_rows
MaxDB
PHP Manual


Gets the number of affected rows in a previous MaxDB operation

MaxDB Funkcje
maxdb_autocommit
MaxDB Funkcje
PHP Manual

maxdb_affected_rows

maxdb::affected_rows

(PECL maxdb >= 1.0)

maxdb_affected_rows -- maxdb::affected_rows — Gets the number of affected rows in a previous MaxDB operation

Opis

Styl proceduralny

int maxdb_affected_rows ( resource $link )

Styl obiektowy

int $maxdb->affected_rows;

maxdb_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If this number cannot be determined, this function will return -1.

Informacja:

For SELECT statements maxdb_affected_rows() works like maxdb_num_rows().

The maxdb_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the maxdb_num_rows() function instead.

Zwracane wartości

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the number of rows affected can not be determined.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
$maxdb->query("CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", $maxdb->affected_rows);

$maxdb->query("ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
$maxdb->query("UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", $maxdb->affected_rows);

/* delete rows */
$maxdb->query("DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", $maxdb->affected_rows);

/* select all rows */
$result = $maxdb->query("SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", $maxdb->affected_rows);

$result->close();

/* Delete table Language */
$maxdb->query("DROP TABLE mycustomer");

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
maxdb_query($link, "CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", maxdb_affected_rows($link));

maxdb_query($link, "ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
maxdb_query($link, "UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", maxdb_affected_rows($link));

/* delete rows */
maxdb_query($link, "DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", maxdb_affected_rows($link));

/* select all rows */
$result = maxdb_query($link, "SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", maxdb_affected_rows($link));

maxdb_free_result($result);

/* Delete table Language */
maxdb_query($link, "DROP TABLE mycustomer");

/* close connection */
maxdb_close($link);
?>

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

Affected rows (INSERT): 15
Affected rows (UPDATE): 15
Affected rows (DELETE): 0
Affected rows (SELECT): 15

Zobacz też:

  • maxdb_num_rows() - Gets the number of rows in a result
  • maxdb_info() - Retrieves information about the most recently executed query

MaxDB Funkcje
maxdb_autocommit
MaxDB Funkcje


Turns on or off auto-commiting database modifications

maxdb_affected_rows
maxdb_bind_param
MaxDB Funkcje
PHP Manual

maxdb_autocommit

maxdb::auto_commit

(PECL maxdb >= 1.0)

maxdb_autocommit -- maxdb::auto_commit — Turns on or off auto-commiting database modifications

Opis

Styl proceduralny

bool maxdb_autocommit ( resource $link , bool $mode )

Styl obiektowy

bool maxdb::auto_commit ( bool $mode )

maxdb_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link resource.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
$maxdb->autocommit(TRUE);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
maxdb_autocommit($link, TRUE);

/* close connection */
maxdb_close($link);
?>

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

Zobacz też:

  • maxdb_commit() - Commits the current transaction
  • maxdb_rollback() - Rolls back current transaction

maxdb_affected_rows
maxdb_bind_param
MaxDB Funkcje


Alias dla maxdb_stmt_bind_param

maxdb_autocommit
maxdb_bind_result
MaxDB Funkcje
PHP Manual

maxdb_bind_param

(PECL maxdb 1.0)

maxdb_bind_param — Alias dla maxdb_stmt_bind_param()

Opis

Ta funkcja jest aliasem dla: maxdb_stmt_bind_param()

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_autocommit
maxdb_bind_result
MaxDB Funkcje


Alias dla maxdb_stmt_bind_result

maxdb_bind_param
maxdb_change_user
MaxDB Funkcje
PHP Manual

maxdb_bind_result

(PECL maxdb 1.0)

maxdb_bind_result — Alias dla maxdb_stmt_bind_result()

Opis

Ta funkcja jest aliasem dla: maxdb_stmt_bind_result().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_bind_param
maxdb_change_user
MaxDB Funkcje


Changes the user of the specified database connection

maxdb_bind_result
maxdb_character_set_name
MaxDB Funkcje
PHP Manual

maxdb_change_user

maxdb::change_user

(PECL maxdb >= 1.0)

maxdb_change_user -- maxdb::change_user — Changes the user of the specified database connection

Opis

Styl proceduralny

bool maxdb_change_user ( resource $link , string $user , string $password , string $database )

Styl obiektowy

bool maxdb::change_user ( string $user , string $password , string $database )

maxdb_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

Informacja:

Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connect database test */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT * FROM dual")) {
   $row = $result->fetch_row();
   printf("Result: %s\n", $row[0]);
   $result->free();
}

/* reset all and select a new database */
if (!$maxdb->change_user("DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM dual")) {
   $row = maxdb_fetch_row($result);
   printf("Result: %s\n", $row[0]);
   maxdb_free_result($result);
}

/* reset all and select a new database */
if (!maxdb_change_user($link, "DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
maxdb_close($link);
?>

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

Result: a
Database running

Zobacz też:

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_select_db() - Selects the default database for database queries

maxdb_bind_result
maxdb_character_set_name
MaxDB Funkcje


Returns the default character set for the database connection

maxdb_change_user
maxdb_client_encoding
MaxDB Funkcje
PHP Manual

maxdb_character_set_name

maxdb::character_set_name

(PECL maxdb >= 1.0)

maxdb_character_set_name -- maxdb::character_set_name — Returns the default character set for the database connection

Opis

Styl proceduralny

string maxdb_character_set_name ( resource $link )

Styl obiektowy

string maxdb::character_set_name ( void )

Returns the current character set for the database connection specified by the link parameter.

Zwracane wartości

The default character set for the current connection, either ascii or unicode.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = $maxdb->character_set_name();
printf ("Current character set is %s\n", $charset);

$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = maxdb_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
maxdb_close($link);
?>

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

Current character set is ascii

Zobacz też:

  • maxdb_client_encoding() - Alias dla maxdb_character_set_name
  • maxdb_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

maxdb_change_user
maxdb_client_encoding
MaxDB Funkcje


Alias dla maxdb_character_set_name

maxdb_character_set_name
maxdb_close_long_data
MaxDB Funkcje
PHP Manual

maxdb_client_encoding

(PECL maxdb 1.0)

maxdb_client_encoding — Alias dla maxdb_character_set_name()

Opis

Ta funkcja jest aliasem dla: maxdb_character_set_name().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_character_set_name
maxdb_close_long_data
MaxDB Funkcje


Alias dla maxdb_stmt_close_long_data

maxdb_client_encoding
maxdb_close
MaxDB Funkcje
PHP Manual

maxdb_close_long_data

maxdb->close_long_data

(PECL maxdb >= 1.0)

maxdb_close_long_data -- maxdb->close_long_data — Alias dla maxdb_stmt_close_long_data()

Opis

Ta funkcja jest aliasem dla: maxdb_stmt_close_long_data().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_client_encoding
maxdb_close
MaxDB Funkcje


Closes a previously opened database connection

maxdb_close_long_data
maxdb_commit
MaxDB Funkcje
PHP Manual

maxdb_close

maxdb::close

(PECL maxdb >= 1.0)

maxdb_close -- maxdb::close — Closes a previously opened database connection

Opis

Styl proceduralny

bool maxdb_close ( resource $link )

Styl obiektowy

bool maxdb::close ( void )

The maxdb_close() function closes a previously opened database connection specified by the link parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_real_connect() - Opens a connection to a MaxDB server

maxdb_close_long_data
maxdb_commit
MaxDB Funkcje


Commits the current transaction

maxdb_close
maxdb_connect_errno
MaxDB Funkcje
PHP Manual

maxdb_commit

maxdb::commit

(PECL maxdb >= 1.0)

maxdb_commit -- maxdb::commit — Commits the current transaction

Opis

Styl proceduralny

bool maxdb_commit ( resource $link )

Styl obiektowy

bool maxdb::commit ( void )

Commits the current transaction for the database connection specified by the link parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
$maxdb->autocommit(FALSE);

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
$maxdb->query("INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
$maxdb->query("INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
$maxdb->commit();

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
maxdb_autocommit($link, FALSE);

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
maxdb_query($link, "INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
maxdb_query($link, "INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
maxdb_commit($link);

/* close connection */
maxdb_close($link);
?>

The above examples produces no output.

Zobacz też:

  • maxdb_autocommit() - Turns on or off auto-commiting database modifications
  • maxdb_rollback() - Rolls back current transaction

maxdb_close
maxdb_connect_errno
MaxDB Funkcje


Returns the error code from last connect call

maxdb_commit
maxdb_connect_error
MaxDB Funkcje
PHP Manual

maxdb_connect_errno

(PECL maxdb >= 1.0)

maxdb_connect_errno — Returns the error code from last connect call

Opis

int maxdb_connect_errno ( void )

The maxdb_connect_errno() function will return the last error code number for last call to maxdb_connect(). If no errors have occured, this function will return zero.

Zwracane wartości

An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.

Przykłady

Przykład #1 maxdb_connect_errno sample

<?php
$link = maxdb_connect("localhost", "XXXXXXXX", "YYYYYYYYY");

if (!$link) {
   printf("Can't connect to localhost. Errorcode: %d\n", maxdb_connect_errno());
}
?>

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

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...>
Can't connect to localhost. Errorcode: -4008

Zobacz też:

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_commit
maxdb_connect_error
MaxDB Funkcje


Returns a string description of the last connect error

maxdb_connect_errno
maxdb_connect
MaxDB Funkcje
PHP Manual

maxdb_connect_error

(PECL maxdb >= 1.0)

maxdb_connect_error — Returns a string description of the last connect error

Opis

string maxdb_connect_error ( void )

The maxdb_connect_error() function is identical to the corresponding maxdb_connect_errno() function in every way, except instead of returning an integer error code the maxdb_connect_error() function will return a string representation of the last error to occur for the last maxdb_connect() call. If no error has occured, this function will return an empty string.

Zwracane wartości

A string that describes the error. An empty string if no error occurred.

Przykłady

Przykład #1 maxdb_connect_error sample

<?php

$link = maxdb_connect("localhost", "nonexisting_user", "");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
}
?>

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

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination <...>
Can't connect to localhost. Error: POS(1) Unknown user name/password combination

Zobacz też:

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_connect_errno
maxdb_connect
MaxDB Funkcje


Open a new connection to the MaxDB server

maxdb_connect_error
maxdb_data_seek
MaxDB Funkcje
PHP Manual

maxdb_connect

maxdb::__construct

(PECL maxdb >= 1.0)

maxdb_connect -- maxdb::__construct — Open a new connection to the MaxDB server

Opis

Styl proceduralny

resource maxdb_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )

Styl obiektowy

maxdb::__construct() ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )

The maxdb_connect() function attempts to open a connection to the MaxDB Server running on host which can be either a host name or an IP address. Passing the string "localhost" to this parameter, the local host is assumed. If successful, the maxdb_connect() will return an resource representing the connection to the database lub FALSE w przypadku niepowodzenia.

The username and password parameters specify the username and password under which to connect to the MaxDB server. If the password is not provided (the NULL value is passed), the MaxDB server will attempt to authenticate the user against the maxdb.default_pw in php.ini.

The dbname parameter if provided will specify the default database to be used when performing queries. If not provied, the entry maxdb.default_db in php.ini is used.

The port and socket parameters are ignored for the MaxDB server.

Zwracane wartości

Returns a resource which represents the connection to a MaxDB Server or FALSE if the connection failed.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", $maxdb->host_info);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?>

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

Host information: localhost
maxdb_connect_error
maxdb_data_seek
MaxDB Funkcje


Adjusts the result pointer to an arbitary row in the result

maxdb_connect
maxdb_debug
MaxDB Funkcje
PHP Manual

maxdb_data_seek

maxdb_result::data_seek

(PECL maxdb >= 1.0)

maxdb_data_seek -- maxdb_result::data_seek — Adjusts the result pointer to an arbitary row in the result

Opis

Styl proceduralny

bool maxdb_data_seek ( resource $result , int $offset )

Styl obiektowy

bool maxdb_result::data_seek ( int $offset )

The maxdb_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_num_rows() - 1).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";
if ($result = $maxdb->query( $query)) {

   /* seek to row no. 10 */
   $result->data_seek(10);

   /* fetch row */
   $row = $result->fetch_row();

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* seek to row no. 400 */
   maxdb_data_seek($result, 10);

   /* fetch row */
   $row = maxdb_fetch_row($result);

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

City: Irvine  State: CA

Zobacz też:

  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_num_rows() - Gets the number of rows in a result

maxdb_connect
maxdb_debug
MaxDB Funkcje


Performs debugging operations

maxdb_data_seek
maxdb_disable_reads_from_master
MaxDB Funkcje
PHP Manual

maxdb_debug

(PECL maxdb >= 1.0)

maxdb_debug — Performs debugging operations

Opis

void maxdb_debug ( string $debug )

The maxdb_debug() can be used to trace the SQLDBC communication. The following strings can be used as a parameter to maxdb_debug():

  • TRACE SHORT ON|OFF - Enables/disables method call trace.
  • TRACE LONG ON|OFF - Enables/disables method argument and detail debug trace.
  • TRACE PACKET ON|OFF|<size> - Enables/disables packet trace, limiting the size of the traced object to the specified number of bytes, or 1000 if no size is specified.
  • TRACE SQL ON|OFF - Enables/disables high level api trace.
  • TRACE TIMESTAMP ON|OFF - Enables/disables a timestamp prefix on each line that is traced.
  • TRACE SIZE <size> - Limits the size of the trace file to <size> bytes, at least 8192 bytes are required.

Zwracane wartości

maxdb_debug() doesn't return any value.

Przykłady

Przykład #1 Styl proceduralny

<?php

maxdb_debug("trace packet 200");

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* close connection */
maxdb_close($link);
?>

The above example produces no output.

maxdb_data_seek
maxdb_disable_reads_from_master
MaxDB Funkcje


Disable reads from master

maxdb_debug
maxdb_disable_rpl_parse
MaxDB Funkcje
PHP Manual

maxdb_disable_reads_from_master

maxdb::disable_reads_from_master

(PECL maxdb >= 1.0)

maxdb_disable_reads_from_master -- maxdb::disable_reads_from_master — Disable reads from master

Opis

Styl proceduralny

bool maxdb_disable_reads_from_master ( resource $link )

Styl obiektowy

void maxdb::disable_reads_from_master ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_debug
maxdb_disable_rpl_parse
MaxDB Funkcje


Disable RPL parse

maxdb_disable_reads_from_master
maxdb_dump_debug_info
MaxDB Funkcje
PHP Manual

maxdb_disable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_disable_rpl_parse — Disable RPL parse

Opis

bool maxdb_disable_rpl_parse ( resource $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_disable_reads_from_master
maxdb_dump_debug_info
MaxDB Funkcje


Dump debugging information into the log

maxdb_disable_rpl_parse
maxdb_embedded_connect
MaxDB Funkcje
PHP Manual

maxdb_dump_debug_info

(PECL maxdb >= 1.0)

maxdb_dump_debug_info — Dump debugging information into the log

Opis

bool maxdb_dump_debug_info ( resource $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_disable_rpl_parse
maxdb_embedded_connect
MaxDB Funkcje


Open a connection to an embedded MaxDB server

maxdb_dump_debug_info
maxdb_enable_reads_from_master
MaxDB Funkcje
PHP Manual

maxdb_embedded_connect

(PECL maxdb >= 1.0)

maxdb_embedded_connect — Open a connection to an embedded MaxDB server

Opis

resource maxdb_embedded_connect ([ string $dbname ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_dump_debug_info
maxdb_enable_reads_from_master
MaxDB Funkcje


Enable reads from master

maxdb_embedded_connect
maxdb_enable_rpl_parse
MaxDB Funkcje
PHP Manual

maxdb_enable_reads_from_master

(PECL maxdb >= 1.0)

maxdb_enable_reads_from_master — Enable reads from master

Opis

bool maxdb_enable_reads_from_master ( resource $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_embedded_connect
maxdb_enable_rpl_parse
MaxDB Funkcje


Enable RPL parse

maxdb_enable_reads_from_master
maxdb_errno
MaxDB Funkcje
PHP Manual

maxdb_enable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_enable_rpl_parse — Enable RPL parse

Opis

bool maxdb_enable_rpl_parse ( resource $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_enable_reads_from_master
maxdb_errno
MaxDB Funkcje


Returns the error code for the most recent function call

maxdb_enable_rpl_parse
maxdb_error
MaxDB Funkcje
PHP Manual

maxdb_errno

maxdb::errno

(PECL maxdb >= 1.0)

maxdb_errno -- maxdb::errno — Returns the error code for the most recent function call

Opis

Styl proceduralny

int maxdb_errno ( resource $link )

Styl obiektowy

int $maxdb->errno;

The maxdb_errno() function will return the last error code for the most recent MaxDB function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.

Zwracane wartości

An error code value for the last call, if it failed. zero means no error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb->query("SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", $maxdb->errno);
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", maxdb_errno($link));
}

/* close connection */
maxdb_close($link);
?>

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

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...>
Errorcode: -4005

Zobacz też:

  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_enable_rpl_parse
maxdb_error
MaxDB Funkcje


Returns a string description of the last error

maxdb_errno
maxdb_escape_string
MaxDB Funkcje
PHP Manual

maxdb_error

maxdb::error

(PECL maxdb >= 1.0)

maxdb_error -- maxdb::error — Returns a string description of the last error

Opis

Styl proceduralny

string maxdb_error ( resource $link )

Styl obiektowy

string $maxdb->error;

The maxdb_error() function is identical to the corresponding maxdb_errno() function in every way, except instead of returning an integer error code the maxdb_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.

Zwracane wartości

A string that describes the error. An empty string if no error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb->query("SELECT xxx FROM hotel.city")) {
   printf("Errormessage: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errormessgae: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?>

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

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000]
Errormessgae: POS(8) Unknown column name:XXX

Zobacz też:

  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_errno
maxdb_escape_string
MaxDB Funkcje


Alias dla maxdb_real_escape_string

maxdb_error
maxdb_execute
MaxDB Funkcje
PHP Manual

maxdb_escape_string

(PECL maxdb 1.0)

maxdb_escape_string — Alias dla maxdb_real_escape_string()

Opis

Ta funkcja jest aliasem dla: maxdb_real_escape_string().

maxdb_error
maxdb_execute
MaxDB Funkcje


Alias dla maxdb_stmt_execute

maxdb_escape_string
maxdb_fetch_array
MaxDB Funkcje
PHP Manual

maxdb_execute

(PECL maxdb 1.0)

maxdb_execute — Alias dla maxdb_stmt_execute()

Opis

Ta funkcja jest aliasem dla: maxdb_stmt_execute().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_escape_string
maxdb_fetch_array
MaxDB Funkcje


Fetch a result row as an associative, a numeric array, or both

maxdb_execute
maxdb_fetch_assoc
MaxDB Funkcje
PHP Manual

maxdb_fetch_array

maxdb_result::fetch_array

(PECL maxdb >= 1.0)

maxdb_fetch_array -- maxdb_result::fetch_array — Fetch a result row as an associative, a numeric array, or both

Opis

Styl proceduralny

mixed maxdb_fetch_array ( resource $result [, int $resulttype ] )

Styl obiektowy

mixed maxdb_result::fetch_array ([ int $resulttype ] )

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

maxdb_fetch_array() is an extended version of the maxdb_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the maxdb_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Informacja: Nazwy pól zwracane przez tą funkcję rozróżniają wielkość znaków.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

The optional second argument resulttype is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MAXDB_ASSOC, MAXDB_ASSOC_UPPER, MAXDB_ASSOC_LOWER, MAXDB_NUM, or MAXDB_BOTH. By default the maxdb_fetch_array() function will assume MAXDB_BOTH, which is a combination of MAXDB_NUM and MAXDB_ASSOC for this parameter.

By using the MAXDB_ASSOC constant this function will behave identically to the maxdb_fetch_assoc(), while MAXDB_NUM will behave identically to the maxdb_fetch_row() function. The final option MAXDB_BOTH will create a single array with the attributes of both.

By using the MAXDB_ASSOC_UPPER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in upper case.

By using the MAXDB_ASSOC_LOWER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in lower case.

Zwracane wartości

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = $maxdb->query($query);

/* numeric array */
$row = $result->fetch_array(MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = $result->fetch_array(MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
$result->close();

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = maxdb_query($link, $query);

/* numeric array */
$row = maxdb_fetch_array($result, MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = maxdb_fetch_array($result, MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = maxdb_fetch_array($result, MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

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

New York (NY)
New York (NY)
Long Island (NY)

Zobacz też:

  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_fetch_resource()

maxdb_execute
maxdb_fetch_assoc
MaxDB Funkcje


Fetch a result row as an associative array

maxdb_fetch_array
maxdb_fetch_field_direct
MaxDB Funkcje
PHP Manual

maxdb_fetch_assoc

maxdb_result::fetch_assoc

(PECL maxdb >= 1.0)

maxdb_fetch_assoc -- maxdb_result::fetch_assoc — Fetch a result row as an associative array

Opis

Styl proceduralny

array maxdb_fetch_assoc ( resource $result )

Styl obiektowy

array maxdb_result::fetch_assoc ( void )

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

The maxdb_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using maxdb_fetch_row() or add alias names.

Informacja: Nazwy pól zwracane przez tą funkcję rozróżniają wielkość znaków.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Zwracane wartości

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch associative array */
   while ($row = $result->fetch_assoc()) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch associative array */
   while ($row = maxdb_fetch_assoc($result)) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

Zobacz też:

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_fetch_resource()

maxdb_fetch_array
maxdb_fetch_field_direct
MaxDB Funkcje


Fetch meta-data for a single field

maxdb_fetch_assoc
maxdb_fetch_field
MaxDB Funkcje
PHP Manual

maxdb_fetch_field_direct

maxdb_result::fetch_field_direct

(PECL maxdb >= 1.0)

maxdb_fetch_field_direct -- maxdb_result::fetch_field_direct — Fetch meta-data for a single field

Opis

Styl proceduralny

mixed maxdb_fetch_field_direct ( resource $result , int $fieldnr )

Styl obiektowy

mixed maxdb_result::fetch_field_direct ( int $fieldnr )

maxdb_fetch_field_direct() returns an resource which contains field definition information from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.

Zwracane wartości

Returns an resource which contains field definition information or FALSE if no field information for specified fieldnr is available.

Object attributes
Attribute | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = $maxdb->query($query)) {

   /* Get field information for column 'SurfaceArea' */
   $finfo = $result->fetch_field_direct(1);

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n", $finfo->type);

   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for column 'cno' */
   $finfo = maxdb_fetch_field_direct($result, 1);

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n", $finfo->type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

Zobacz też:

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_fetch_fields() - Returns an array of resources representing the fields in a result set

maxdb_fetch_assoc
maxdb_fetch_field
MaxDB Funkcje


Returns the next field in the result set

maxdb_fetch_field_direct
maxdb_fetch_fields
MaxDB Funkcje
PHP Manual

maxdb_fetch_field

maxdb_result::fetch_field

(PECL maxdb >= 1.0)

maxdb_fetch_field -- maxdb_result::fetch_field — Returns the next field in the result set

Opis

Styl proceduralny

mixed maxdb_fetch_field ( resource $result )

Styl obiektowy

mixed maxdb_result::fetch_field ( void )

The maxdb_fetch_field() returns the definition of one column of a result set as an resource. Call this function repeatedly to retrieve information about all columns in the result set. maxdb_fetch_field() returns FALSE when no more fields are left.

Zwracane wartości

Returns an resource which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result->fetch_field()) {

       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {

       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

Zobacz też:

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field_direct() - Fetch meta-data for a single field
  • maxdb_fetch_fields() - Returns an array of resources representing the fields in a result set
  • maxdb_field_seek() - Set result pointer to a specified field offset

maxdb_fetch_field_direct
maxdb_fetch_fields
MaxDB Funkcje


Returns an array of resources representing the fields in a result set

maxdb_fetch_field
maxdb_fetch_lengths
MaxDB Funkcje
PHP Manual

maxdb_fetch_fields

maxdb_result::fetch_fields

(PECL maxdb >= 1.0)

maxdb_fetch_fields -- maxdb_result::fetch_fields — Returns an array of resources representing the fields in a result set

Opis

Styl proceduralny

mixed maxdb_fetch_fields ( resource $result )

Styl obiektowy

mixed maxdb_result::fetch_fields ( void )

This function serves an identical purpose to the maxdb_fetch_field() function with the single difference that, instead of returning one resource at a time for each field, the columns are returned as an array of resources.

Zwracane wartości

Returns an array of resources which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   $finfo = $result->fetch_fields();

   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val->name);
       printf("Table:    %s\n", $val->table);
       printf("max. Len: %d\n", $val->max_length);
       printf("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all columns */
   $finfo = maxdb_fetch_fields($result);

   foreach ($finfo as $val) {
       printf("Name:     %s\n", $val->name);
       printf("Table:    %s\n", $val->table);
       printf("max. Len: %d\n", $val->max_length);
       printf("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

Zobacz też:

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_fetch_field_direct() - Fetch meta-data for a single field

maxdb_fetch_field
maxdb_fetch_lengths
MaxDB Funkcje


Returns the lengths of the columns of the current row in the result set

maxdb_fetch_fields
maxdb_fetch_object
MaxDB Funkcje
PHP Manual

maxdb_fetch_lengths

maxdb_result::lengths

(PECL maxdb >= 1.0)

maxdb_fetch_lengths -- maxdb_result::lengths — Returns the lengths of the columns of the current row in the result set

Opis

Styl proceduralny

array maxdb_fetch_lengths ( resource $result )

Styl obiektowy

array $maxdb_result->lengths;

The maxdb_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned lub FALSE w przypadku niepowodzenia.

Zwracane wartości

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

maxdb_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling maxdb_fetch_row/array/resource or after retrieving all rows in the result.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = $maxdb->query($query)) {

   $row = $result->fetch_row();

   /* display column lengths */
   foreach ($result->lengths as $i => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = maxdb_query($link, $query)) {

   $row = maxdb_fetch_row($result);

   /* display column lengths */
   foreach (maxdb_fetch_lengths($result) as $i => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

Field  1 has Length  4
Field  2 has Length  3
Field  3 has Length  5
Field  4 has Length  6
Field  5 has Length  5
Field  6 has Length 21
maxdb_fetch_fields
maxdb_fetch_object
MaxDB Funkcje


Returns the current row of a result set as an object

maxdb_fetch_lengths
maxdb_fetch_row
MaxDB Funkcje
PHP Manual

maxdb_fetch_object

maxdb_result::fetch_object

(PECL maxdb >= 1.0)

maxdb_fetch_object -- maxdb_result::fetch_object — Returns the current row of a result set as an object

Opis

Styl proceduralny

object maxdb_fetch_object ( object $result )

Styl obiektowy

object maxdb_result::fetch_object ( void )

The maxdb_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.

Zwracane wartości

Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.

Informacja: Nazwy pól zwracane przez tą funkcję rozróżniają wielkość znaków.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch object array */
   while ($obj = $result->fetch_object()) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch object array */
   while ($obj = maxdb_fetch_object($result)) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

Zobacz też:

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_row() - Get a result row as an enumerated array

maxdb_fetch_lengths
maxdb_fetch_row
MaxDB Funkcje


Get a result row as an enumerated array

maxdb_fetch_object
maxdb_fetch
MaxDB Funkcje
PHP Manual

maxdb_fetch_row

maxdb_result::fetch_row

(PECL maxdb >= 1.0)

maxdb_fetch_row -- maxdb_result::fetch_row — Get a result row as an enumerated array

Opis

Styl proceduralny

mixed maxdb_fetch_row ( resource $result )

Styl obiektowy

mixed maxdb_result::fetch_row ( void )

Returns an array that corresponds to the fetched row, or NULL if there are no more rows.

maxdb_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the maxdb_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.

Zwracane wartości

maxdb_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch enumerated array */
   while ($row = $result->fetch_row()) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch enumerated array */
   while ($row = maxdb_fetch_row($result)) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

Zobacz też:

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_resource()

maxdb_fetch_object
maxdb_fetch
MaxDB Funkcje


Alias dla maxdb_stmt_fetch

maxdb_fetch_row
maxdb_field_count
MaxDB Funkcje
PHP Manual

maxdb_fetch

(PECL maxdb 1.0)

maxdb_fetch — Alias dla maxdb_stmt_fetch()

Opis

Ta funkcja jest aliasem dla: maxdb_stmt_fetch().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_fetch_row
maxdb_field_count
MaxDB Funkcje


Returns the number of columns for the most recent query

maxdb_fetch
maxdb_field_seek
MaxDB Funkcje
PHP Manual

maxdb_field_count

maxdb::field_count

(PECL maxdb >= 1.0)

maxdb_field_count -- maxdb::field_count — Returns the number of columns for the most recent query

Opis

Styl proceduralny

int maxdb_field_count ( resource $link )

Styl obiektowy

int maxdb::field_count ( void )

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the maxdb_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Zwracane wartości

An integer representing the number of fields in a result set.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query( "CREATE TABLE friends (id int, name varchar(20))");

$maxdb->query( "INSERT INTO friends VALUES (1,'Hartmut')");
$maxdb->query( "INSERT INTO friends VALUES (2, 'Ulf')");

if ($maxdb->field_count()) {
   /* this was a select/show or describe query */
   $result = $maxdb->store_result();

   /* process resultset */
   $row = $result->fetch_row();

   /* free resultset */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE friends (id int, name varchar(20))");

maxdb_query($link, "INSERT INTO friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO friends VALUES (2, 'Ulf')");

if (maxdb_field_count($link)) {
   /* this was a select/show or describe query */
   $result = maxdb_store_result($link);

   /* process resultset */
   $row = maxdb_fetch_row($result);

   /* free resultset */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example produces no output.

maxdb_fetch
maxdb_field_seek
MaxDB Funkcje


Set result pointer to a specified field offset

maxdb_field_count
maxdb_field_tell
MaxDB Funkcje
PHP Manual

maxdb_field_seek

maxdb_result::field_seek

(PECL maxdb >= 1.0)

maxdb_field_seek -- maxdb_result::field_seek — Set result pointer to a specified field offset

Opis

Styl proceduralny

bool maxdb_field_seek ( resource $result , int $fieldnr )

Styl obiektowy

bool maxdb_result::field_seek ( int $fieldnr )

Sets the field cursor to the given offset. The next call to maxdb_fetch_field() will retrieve the field definition of the column associated with that offset.

Informacja:

To seek to the beginning of a row, pass an offset value of zero.

Zwracane wartości

maxdb_field_seek() returns previuos value of field cursor.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for 2nd column */
   $result->field_seek(1);
   $finfo = $result->fetch_field();

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n\n", $finfo->type);

   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for 2nd column */
   maxdb_field_seek($result, 1);
   $finfo = maxdb_fetch_field($result);

   printf("Name:     %s\n", $finfo->name);
   printf("Table:    %s\n", $finfo->table);
   printf("max. Len: %d\n", $finfo->max_length);
   printf("Flags:    %d\n", $finfo->flags);
   printf("Type:     %d\n\n", $finfo->type);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Zobacz też:

  • maxdb_fetch_field() - Returns the next field in the result set

maxdb_field_count
maxdb_field_tell
MaxDB Funkcje


Get current field offset of a result pointer

maxdb_field_seek
maxdb_free_result
MaxDB Funkcje
PHP Manual

maxdb_field_tell

maxdb_result::current_field

(PECL maxdb >= 1.0)

maxdb_field_tell -- maxdb_result::current_field — Get current field offset of a result pointer

Opis

Styl proceduralny

int maxdb_field_tell ( resource $result )

Styl obiektowy

int $maxdb_result->current_field;

Returns the position of the field cursor used for the last maxdb_fetch_field() call. This value can be used as an argument to maxdb_field_seek().

Zwracane wartości

Returns current offset of field cursor.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->query($query)) {

   /* Get field information for all columns */
   while ($finfo = $result->fetch_field()) {

       /* get fieldpointer offset */
       $currentfield = $result->current_field;

       printf("Column    %d:\n", $currentfield);
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {

       /* get fieldpointer offset */
       $currentfield = maxdb_field_tell($result);

       printf("Column    %d:\n", $currentfield);
       printf("Name:     %s\n", $finfo->name);
       printf("Table:    %s\n", $finfo->table);
       printf("max. Len: %d\n", $finfo->max_length);
       printf("Flags:    %d\n", $finfo->flags);
       printf("Type:     %d\n\n", $finfo->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

Column    1:
Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Column    2:
Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

Zobacz też:

  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_field_seek() - Set result pointer to a specified field offset

maxdb_field_seek
maxdb_free_result
MaxDB Funkcje


Frees the memory associated with a result

maxdb_field_tell
maxdb_get_client_info
MaxDB Funkcje
PHP Manual

maxdb_free_result

maxdb_result::free

(PECL maxdb >= 1.0)

maxdb_free_result -- maxdb_result::free — Frees the memory associated with a result

Opis

Styl proceduralny

void maxdb_free_result ( resource $result )

Styl obiektowy

void maxdb_result::free ( void )

The maxdb_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by maxdb_query(), maxdb_store_result() or maxdb_use_result().

Informacja:

You should always free your result with maxdb_free_result(), when your result resource is not needed anymore.

Zwracane wartości

This function doesn't return any value.

Zobacz też:

  • maxdb_query() - Performs a query on the database
  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_field_tell
maxdb_get_client_info
MaxDB Funkcje


Returns the MaxDB client version as a string

maxdb_free_result
maxdb_get_client_version
MaxDB Funkcje
PHP Manual

maxdb_get_client_info

(PECL maxdb >= 1.0)

maxdb_get_client_info — Returns the MaxDB client version as a string

Opis

string maxdb_get_client_info ( void )

The maxdb_get_client_info() function is used to return a string representing the client version being used in the MaxDB extension.

Zwracane wartości

A string that represents the MaxDB client library version

Przykłady

Przykład #1 maxdb_get_client_info

<?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %s\n", maxdb_get_client_info());
?>

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

Client library version: libSQLDBC <...>

Zobacz też:

  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_info() - Returns the version of the MaxDB server
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer

maxdb_free_result
maxdb_get_client_version
MaxDB Funkcje


Get MaxDB client info

maxdb_get_client_info
maxdb_get_host_info
MaxDB Funkcje
PHP Manual

maxdb_get_client_version

(PECL maxdb >= 1.0)

maxdb_get_client_version — Get MaxDB client info

Opis

int maxdb_get_client_version ( void )

Returns client version number as an integer.

Zwracane wartości

A number that represents the MaxDB client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 7.5.0 is returned as 70500.

This is useful to quickly determine the version of the client library to know if some capability exists.

Przykłady

Przykład #1 maxdb_get_client_version

<?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %d\n", maxdb_get_client_version());
?>

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

Client library version: 7.<...>

Zobacz też:

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_server_info() - Returns the version of the MaxDB server
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer

maxdb_get_client_info
maxdb_get_host_info
MaxDB Funkcje


Returns a string representing the type of connection used

maxdb_get_client_version
maxdb_get_metadata
MaxDB Funkcje
PHP Manual

maxdb_get_host_info

maxdb::get_host_info

(PECL maxdb >= 1.0)

maxdb_get_host_info -- maxdb::get_host_info — Returns a string representing the type of connection used

Opis

Styl proceduralny

string maxdb_get_host_info ( resource $link )

Styl obiektowy

string $maxdb->host_info;

The maxdb_get_host_info() function returns a string describing the connection represented by the link parameter is using.

Zwracane wartości

A character string representing the server hostname and the connection type.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", $maxdb->host_info);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?>

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

Host info: localhost

Zobacz też:

  • maxdb_get_proto_info() - Returns the version of the MaxDB protocol used

maxdb_get_client_version
maxdb_get_metadata
MaxDB Funkcje


Alias dla maxdb_stmt_result_metadata

maxdb_get_host_info
maxdb_get_proto_info
MaxDB Funkcje
PHP Manual

maxdb_get_metadata

(PECL maxdb 1.0)

maxdb_get_metadata — Alias dla maxdb_stmt_result_metadata()

Opis

Ta funkcja jest aliasem dla: maxdb_stmt_result_metadata().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_get_host_info
maxdb_get_proto_info
MaxDB Funkcje


Returns the version of the MaxDB protocol used

maxdb_get_metadata
maxdb_get_server_info
MaxDB Funkcje
PHP Manual

maxdb_get_proto_info

maxdb::protocol_version

(PECL maxdb >= 1.0)

maxdb_get_proto_info -- maxdb::protocol_version — Returns the version of the MaxDB protocol used

Opis

Styl proceduralny

int maxdb_get_proto_info ( resource $link )

Styl obiektowy

string $maxdb->protocol_version;

Returns an integer representing the MaxDB protocol version used by the connection represented by the link parameter.

Zwracane wartości

Returns an integer representing the protocol version (constant 10).

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $maxdb->protocol_version);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", maxdb_get_proto_info($link));

/* close connection */
maxdb_close($link);
?>

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

Protocol version: 10

Zobacz też:

  • maxdb_get_host_info() - Returns a string representing the type of connection used

maxdb_get_metadata
maxdb_get_server_info
MaxDB Funkcje


Returns the version of the MaxDB server

maxdb_get_proto_info
maxdb_get_server_version
MaxDB Funkcje
PHP Manual

maxdb_get_server_info

maxdb::server_info

(PECL maxdb >= 1.0)

maxdb_get_server_info -- maxdb::server_info — Returns the version of the MaxDB server

Opis

Styl proceduralny

string maxdb_get_server_info ( resource $link )

Styl obiektowy

string $maxdb->server_info;

Returns a string representing the version of the MaxDB server that the MaxDB extension is connected to (represented by the link parameter).

Zwracane wartości

A character string representing the server version.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", $maxdb->server_info);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", maxdb_get_server_info($link));

/* close connection */
maxdb_close($link);
?>

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

Server version: Kernel    7<...>

Zobacz też:

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer

maxdb_get_proto_info
maxdb_get_server_version
MaxDB Funkcje


Returns the version of the MaxDB server as an integer

maxdb_get_server_info
maxdb_info
MaxDB Funkcje
PHP Manual

maxdb_get_server_version

maxdb::server_version

(PECL maxdb >= 1.0)

maxdb_get_server_version -- maxdb::server_version — Returns the version of the MaxDB server as an integer

Opis

Styl proceduralny

int maxdb_get_server_version ( resource $link )

Styl obiektowy

int $maxdb->server_version;

The maxdb_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.

The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 7.5.0 is 70500).

Zwracane wartości

An integer representing the server version.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", $maxdb->server_version);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", maxdb_get_server_version($link));

/* close connection */
maxdb_close($link);
?>

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

Server version: 7<...>

Zobacz też:

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_info() - Returns the version of the MaxDB server

maxdb_get_server_info
maxdb_info
MaxDB Funkcje


Retrieves information about the most recently executed query

maxdb_get_server_version
maxdb_init
MaxDB Funkcje
PHP Manual

maxdb_info

maxdb::info

(PECL maxdb >= 1.0)

maxdb_info -- maxdb::info — Retrieves information about the most recently executed query

Opis

Styl proceduralny

string maxdb_info ( resource $link )

Styl obiektowy

string $maxdb->info;

The maxdb_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Possible maxdb_info return values
Query type | Example result string
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0

Informacja:

Queries which do not fall into one of the above formats are not supported. In these situations, maxdb_info() will return an empty string.

Zwracane wartości

A character string representing additional information about the most recently executed query.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
$maxdb->query("INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", $maxdb->info);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
maxdb_query($link, "INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", maxdb_info($link));

/* close connection */
maxdb_close($link);
?>

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

Records: 25 Duplicates: 0 Warnings: 0

Zobacz też:

  • maxdb_affected_rows() - Gets the number of affected rows in a previous MaxDB operation
  • maxdb_warning_count() - Returns the number of warnings from the last query for the given link
  • maxdb_num_rows() - Gets the number of rows in a result

maxdb_get_server_version
maxdb_init
MaxDB Funkcje


Initializes MaxDB and returns an resource for use with maxdb_real_connect

maxdb_info
maxdb_insert_id
MaxDB Funkcje
PHP Manual

maxdb_init

(PECL maxdb >= 1.0)

maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect

Opis

resource maxdb_init ( void )

Allocates or initializes a MaxDB resource suitable for maxdb_options() and maxdb_real_connect().

Informacja:

Any subsequent calls to any maxdb function (except maxdb_options()) will fail until maxdb_real_connect() was called.

Zwracane wartości

Returns an resource.

Zobacz też:

  • maxdb_options() - Set options
  • maxdb_close() - Closes a previously opened database connection
  • maxdb_real_connect() - Opens a connection to a MaxDB server
  • maxdb_connect() - Open a new connection to the MaxDB server

maxdb_info
maxdb_insert_id
MaxDB Funkcje


Returns the auto generated id used in the last query

maxdb_init
maxdb_kill
MaxDB Funkcje
PHP Manual

maxdb_insert_id

maxdb::insert_id

(PECL maxdb >= 1.0)

maxdb_insert_id -- maxdb::insert_id — Returns the auto generated id used in the last query

Opis

Styl proceduralny

mixed maxdb_insert_id ( resource $link )

Styl obiektowy

mixed $maxdb->insert_id;

The maxdb_insert_id() function returns the ID generated by a query on a table with a column having the DEFAULT SERIAL attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the DEFAULT SERIAL attribute, this function will return zero.

Zwracane wartości

The value of the DEFAULT SERIAL field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an DEFAULT_SERIAL value.

Informacja:

If the number is greater than maximal int value, maxdb_insert_id() will return a string.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycity LIKE hotel.city");
$maxdb->query("ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
$maxdb->query($query);

printf ("New Record has id %d.\n", $maxdb->insert_id);

/* drop table */
$maxdb->query("DROP TABLE mycity");

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city");
maxdb_query($link, "ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
maxdb_query($link, $query);

printf ("New Record has id %d.\n", maxdb_insert_id($link));

/* drop table */
maxdb_query($link, "DROP TABLE mycity");

/* close connection */
maxdb_close($link);
?>

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

New Record has id 1.
maxdb_init
maxdb_kill
MaxDB Funkcje


Disconnects from a MaxDB server

maxdb_insert_id
maxdb_master_query
MaxDB Funkcje
PHP Manual

maxdb_kill

maxdb::kill

(PECL maxdb >= 1.0)

maxdb_kill -- maxdb::kill — Disconnects from a MaxDB server

Opis

Styl proceduralny

bool maxdb_kill ( resource $link , int $processid )

Styl obiektowy

bool maxdb::kill ( int $processid )

This function is used to disconnect from a MaxDB server specified by the processid parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?>

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

Error: Session not connected

Zobacz też:

  • maxdb_thread_id() - Returns the thread ID for the current connection

maxdb_insert_id
maxdb_master_query
MaxDB Funkcje


Enforce execution of a query on the master in a master/slave setup

maxdb_kill
maxdb_more_results
MaxDB Funkcje
PHP Manual

maxdb_master_query

(PECL maxdb >= 1.0)

maxdb_master_query — Enforce execution of a query on the master in a master/slave setup

Opis

bool maxdb_master_query ( resource $link , string $query )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_kill
maxdb_more_results
MaxDB Funkcje


Check if there any more query results from a multi query

maxdb_master_query
maxdb_multi_query
MaxDB Funkcje
PHP Manual

maxdb_more_results

maxdb::more_results

(PECL maxdb >= 1.0)

maxdb_more_results -- maxdb::more_results — Check if there any more query results from a multi query

Opis

bool maxdb_more_results ( resource $link )

maxdb_more_results() indicates if one or more result sets are available from a previous call to maxdb_multi_query().

Zwracane wartości

Always FALSE.

Przykłady

See maxdb_multi_query().

Zobacz też:

  • maxdb_multi_query() - Performs a query on the database
  • maxdb_next_result() - Prepare next result from multi_query
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_master_query
maxdb_multi_query
MaxDB Funkcje


Performs a query on the database

maxdb_more_results
maxdb_next_result
MaxDB Funkcje
PHP Manual

maxdb_multi_query

maxdb::multi_query

(PECL maxdb >= 1.0)

maxdb_multi_query -- maxdb::multi_query — Performs a query on the database

Opis

Styl proceduralny

bool maxdb_multi_query ( resource $link , string $query )

Styl obiektowy

bool maxdb::multi_query ( string $query )

The maxdb_multi_query() works like the function maxdb_query(). Multiple queries are not yet supported.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM dual";

/* execute multi query */
if ($maxdb->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->store_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * FROM dual";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_store_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?>

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

a

Zobacz też:

  • maxdb_use_result() - Initiate a result set retrieval
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_next_result() - Prepare next result from multi_query
  • maxdb_more_results() - Check if there any more query results from a multi query

maxdb_more_results
maxdb_next_result
MaxDB Funkcje


Prepare next result from multi_query

maxdb_multi_query
maxdb_num_fields
MaxDB Funkcje
PHP Manual

maxdb_next_result

maxdb::next_result

(PECL maxdb >= 1.0)

maxdb_next_result -- maxdb::next_result — Prepare next result from multi_query

Opis

bool maxdb_next_result ( resource $link )

Since multiple queries are not yet supported, maxdb_next_result() returns always FALSE.

Zwracane wartości

Returns FALSE.

Zobacz też:

  • maxdb_multi_query() - Performs a query on the database
  • maxdb_more_results() - Check if there any more query results from a multi query
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_multi_query
maxdb_num_fields
MaxDB Funkcje


Get the number of fields in a result

maxdb_next_result
maxdb_num_rows
MaxDB Funkcje
PHP Manual

maxdb_num_fields

maxdb_result::field_count

(PECL maxdb >= 1.0)

maxdb_num_fields -- maxdb_result::field_count — Get the number of fields in a result

Opis

Styl proceduralny

int maxdb_num_fields ( resource $result )

Styl obiektowy

int $maxdb_result->field_count;

maxdb_num_fields() returns the number of fields from specified result set.

Zwracane wartości

The number of fields from a result set

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = $result->field_count;

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = maxdb_num_fields($result);

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

Result set has 3 fields.

Zobacz też:

  • maxdb_fetch_field() - Returns the next field in the result set

maxdb_next_result
maxdb_num_rows
MaxDB Funkcje


Gets the number of rows in a result

maxdb_num_fields
maxdb_options
MaxDB Funkcje
PHP Manual

maxdb_num_rows

maxdb::num_rows

(PECL maxdb >= 1.0)

maxdb_num_rows -- maxdb::num_rows — Gets the number of rows in a result

Opis

Styl proceduralny

int maxdb_num_rows ( resource $result )

Styl obiektowy

int $maxdb->num_rows;

Returns the number of rows in the result set.

The use of maxdb_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets maxdb_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.

Zwracane wartości

Returns number of rows in the result set.

Informacja:

If the number of rows is greater than maximal int value, the number will be returned as a string.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = $result->num_rows;

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = maxdb_num_rows($result);

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

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

Result set has 15 rows.

Zobacz też:

  • maxdb_affected_rows() - Gets the number of affected rows in a previous MaxDB operation
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval
  • maxdb_query() - Performs a query on the database

maxdb_num_fields
maxdb_options
MaxDB Funkcje


Set options

maxdb_num_rows
maxdb_param_count
MaxDB Funkcje
PHP Manual

maxdb_options

maxdb::options

(PECL maxdb >= 1.0)

maxdb_options -- maxdb::options — Set options

Opis

Styl proceduralny

bool maxdb_options ( resource $link , int $option , mixed $value )

Styl obiektowy

bool maxdb::options ( int $option , mixed $value )

maxdb_options() can be used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

maxdb_options() should be called after maxdb_init() and before maxdb_real_connect().

The parameter option is the option that you want to set, the value is the value for the option. For detailed description of the options see » http://maxdb.sap.com/documentation/ The parameter option can be one of the following values:

Valid options
Name | Description
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATION | The application to be connected to the database.
MAXDB_APPVERSION | The version of the application.
MAXDB_SQLMODE | The SQL mode.
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not.
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system.
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released.
MAXDB_PACKETCOUNT | The number of different request packets used for the connection.
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use.
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

See maxdb_real_connect().

Zobacz też:

  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_real_connect() - Opens a connection to a MaxDB server

maxdb_num_rows
maxdb_param_count
MaxDB Funkcje


Alias dla maxdb_stmt_param_count

maxdb_options
maxdb_ping
MaxDB Funkcje
PHP Manual

maxdb_param_count

(PECL maxdb 1.0)

maxdb_param_count — Alias dla maxdb_stmt_param_count()

Opis

Ta funkcja jest aliasem dla: maxdb_stmt_param_count().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_options
maxdb_ping
MaxDB Funkcje


Pings a server connection, or tries to reconnect if the connection has gone down

maxdb_param_count
maxdb_prepare
MaxDB Funkcje
PHP Manual

maxdb_ping

maxdb::ping

(PECL maxdb >= 1.0)

maxdb_ping -- maxdb::ping — Pings a server connection, or tries to reconnect if the connection has gone down

Opis

Styl proceduralny

bool maxdb_ping ( resource $link )

Styl obiektowy

bool maxdb::ping ( void )

Checks whether the connection to the server is working. If it has gone down, and global option maxdb.reconnect is enabled an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if ($maxdb->ping()) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if (maxdb_ping($link)) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?>

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

Our connection is ok!
maxdb_param_count
maxdb_prepare
MaxDB Funkcje


Prepare an SQL statement for execution

maxdb_ping
maxdb_query
MaxDB Funkcje
PHP Manual

maxdb_prepare

maxdb::prepare

(PECL maxdb >= 1.0)

maxdb_prepare -- maxdb::prepare — Prepare an SQL statement for execution

Opis

Styl proceduralny

resource maxdb_prepare ( resource $link , string $query )

Styl obiektowy

maxdb_stmt maxdb::prepare ( string $query )

maxdb_prepare() prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

Informacja:

You should not add a terminating semicolon or \g to the statement.

The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Informacja:

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.

Zwracane wartości

maxdb_prepare() returns a statement resource or FALSE if an error occured.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = $maxdb->prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt->bind_param("s", $city);

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($district);

   /* fetch value */
   $stmt->fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = maxdb_prepare($link, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

  /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

Rosemont is in district IL

Zobacz też:

  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_close() - Closes a prepared statement

maxdb_ping
maxdb_query
MaxDB Funkcje


Performs a query on the database

maxdb_prepare
maxdb_real_connect
MaxDB Funkcje
PHP Manual

maxdb_query

maxdb::query

(PECL maxdb >= 1.0)

maxdb_query -- maxdb::query — Performs a query on the database

Opis

Styl proceduralny

mixed maxdb_query ( resource $link , string $query [, int $resultmode ] )

Styl obiektowy

mixed maxdb::query ( string $query )

The maxdb_query() function is used to simplify the act of performing a query against the database represented by the link parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. For SELECT, SHOW, DESCRIBE or EXPLAIN maxdb_query() will return a result resource.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if ($maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $maxdb->query("SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", $result->num_rows);

   /* free result set */
   $result->close();
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = $maxdb->query("SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   $result->close();
}

$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if (maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = maxdb_query($link, "SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", maxdb_num_rows($result));

   /* free result set */
   maxdb_free_result($result);
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = maxdb_query($link, "SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   maxdb_free_result($result);
}

maxdb_close($link);
?>

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

Table mycity successfully created.
Select returned 25 rows.

Zobacz też:

  • maxdb_real_query() - Execute an SQL query
  • maxdb_multi_query() - Performs a query on the database
  • maxdb_free_result() - Frees the memory associated with a result

maxdb_prepare
maxdb_real_connect
MaxDB Funkcje


Opens a connection to a MaxDB server

maxdb_query
maxdb_real_escape_string
MaxDB Funkcje
PHP Manual

maxdb_real_connect

maxdb::real_connect

(PECL maxdb >= 1.0)

maxdb_real_connect -- maxdb::real_connect — Opens a connection to a MaxDB server

Opis

Styl proceduralny

bool maxdb_real_connect ( resource $link [, string $hostname [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )

Styl obiektowy

bool maxdb::real_connect ([ string $hostname [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )

maxdb_real_connect() attempts to establish a connection to a MaxDB database engine running on hostname.

This function differs from maxdb_connect():

  • maxdb_real_connect() needs a valid resource which has to be created by function maxdb_init()

  • With function maxdb_options() you can set various options for connection.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* create a connection object which is not connected */
$maxdb = maxdb_init();

/* set connection options */
$maxdb->options(MAXDB_UNICODE, "FALSE");
$maxdb->options(MAXDB_TIMEOUT, 5);

/* connect to server */
$maxdb->real_connect('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", $maxdb->host_info);

$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php

/* create a connection object which is not connected */
$link = maxdb_init();

/* set connection options */
maxdb_options($link, MAXDB_UNICODE, "FALSE");
maxdb_options($link, MAXDB_TIMEOUT, 5);

/* connect to server */
maxdb_real_connect($link, 'localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", maxdb_get_host_info($link));

maxdb_close($link);
?>

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

Connection: localhost <...>

Zobacz też:

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_options() - Set options
  • maxdb_ssl_set() - Used for establishing secure connections using SSL
  • maxdb_close() - Closes a previously opened database connection

maxdb_query
maxdb_real_escape_string
MaxDB Funkcje


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

maxdb_real_connect
maxdb_real_query
MaxDB Funkcje
PHP Manual

maxdb_real_escape_string

maxdb::real_escape_string

(PECL maxdb >= 1.0)

maxdb_real_escape_string -- maxdb::real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

Opis

Styl proceduralny

string maxdb_real_escape_string ( resource $link , string $escapestr )

Styl obiektowy

string maxdb::real_escape_sring ( string $escapestr )

This function is used to create a legal SQL string that you can use in an SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.

Characters encoded are ', ".

Zwracane wartości

Returns an escaped string.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$maxdb->query("INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", $maxdb->sqlstate);
}

$city = $maxdb->real_escape_string($city);

/* this query with escaped $city will work */
if ($maxdb->query("INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", $maxdb->affected_rows);
}

$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!maxdb_query($link, "INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", maxdb_sqlstate($link));
}

$city = maxdb_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (maxdb_query($link, "INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", maxdb_affected_rows($link));
}

maxdb_close($link);
?>

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

Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...>
Error: 42000
1 Row inserted.

Zobacz też:

  • maxdb_character_set_name() - Returns the default character set for the database connection

maxdb_real_connect
maxdb_real_query
MaxDB Funkcje


Execute an SQL query

maxdb_real_escape_string
maxdb_report
MaxDB Funkcje
PHP Manual

maxdb_real_query

maxdb::real_query

(PECL maxdb >= 1.0)

maxdb_real_query -- maxdb::real_query — Execute an SQL query

Opis

Styl proceduralny

bool maxdb_real_query ( resource $link , string $query )

Styl obiektowy

bool maxdb::real_query ( string $query )

The maxdb_real_query() is functionally identical with the maxdb_query().

Informacja:

In order to determine if a given query should return a result set or not, see maxdb_field_count().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • maxdb_query() - Performs a query on the database
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_real_escape_string
maxdb_report
MaxDB Funkcje


Enables or disables internal report functions

maxdb_real_query
maxdb_rollback
MaxDB Funkcje
PHP Manual

maxdb_report

(PECL maxdb 1.0)

maxdb_report — Enables or disables internal report functions

Opis

bool maxdb_report ( int $flags )

Parametry

flags

One of the MAXDB_REPORT_XXX constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl proceduralny

<?php
/* activate reporting */
maxdb_report(MAXDB_REPORT_ERROR);

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* this query should report an error */
$result = maxdb_query($link,"SELECT Name FROM Nonexistingtable WHERE population > 50000");

maxdb_close($link);
?>

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

Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...>
maxdb_real_query
maxdb_rollback
MaxDB Funkcje


Rolls back current transaction

maxdb_report
maxdb_rpl_parse_enabled
MaxDB Funkcje
PHP Manual

maxdb_rollback

maxdb::rollback

(PECL maxdb >= 1.0)

maxdb_rollback -- maxdb::rollback — Rolls back current transaction

Opis

Styl proceduralny

bool maxdb_rollback ( resource $link )

Styl obiektowy

bool maxdb::rollback ( void )

Rollbacks the current transaction for the database specified by the link parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
$maxdb->autocommit(FALSE);

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
$maxdb->commit();

/* delete all rows */
$maxdb->query("DELETE FROM temp.mycity");

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Rollback */
$maxdb->rollback();

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Drop table myCity */
$maxdb->query("DROP TABLE temp.mycity");

$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
maxdb_autocommit($link, FALSE);

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
maxdb_commit($link);

/* delete all rows */
maxdb_query($link, "DELETE FROM temp.mycity");

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Rollback */
maxdb_rollback($link);

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Drop table myCity */
maxdb_query($link, "DROP TABLE temp.mycity");

maxdb_close($link);
?>

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

0 rows in table mycity.
25 rows in table mycity (after rollback).

Zobacz też:

  • maxdb_commit() - Commits the current transaction
  • maxdb_autocommit() - Turns on or off auto-commiting database modifications

maxdb_report
maxdb_rpl_parse_enabled
MaxDB Funkcje


Check if RPL parse is enabled

maxdb_rollback
maxdb_rpl_probe
MaxDB Funkcje
PHP Manual

maxdb_rpl_parse_enabled

(PECL maxdb >= 1.0)

maxdb_rpl_parse_enabled — Check if RPL parse is enabled

Opis

int maxdb_rpl_parse_enabled ( resource $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_rollback
maxdb_rpl_probe
MaxDB Funkcje


RPL probe

maxdb_rpl_parse_enabled
maxdb_rpl_query_type
MaxDB Funkcje
PHP Manual

maxdb_rpl_probe

(PECL maxdb >= 1.0)

maxdb_rpl_probe — RPL probe

Opis

bool maxdb_rpl_probe ( resource $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_rpl_parse_enabled
maxdb_rpl_query_type
MaxDB Funkcje


Returns RPL query type

maxdb_rpl_probe
maxdb_select_db
MaxDB Funkcje
PHP Manual

maxdb_rpl_query_type

maxdb::rpl_query_type

(PECL maxdb >= 1.0)

maxdb_rpl_query_type -- maxdb::rpl_query_type — Returns RPL query type

Opis

Styl proceduralny

int maxdb_rpl_query_type ( resource $link )

Styl obiektowy

int maxdb::rpl_query_type ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_rpl_probe
maxdb_select_db
MaxDB Funkcje


Selects the default database for database queries

maxdb_rpl_query_type
maxdb_send_long_data
MaxDB Funkcje
PHP Manual

maxdb_select_db

maxdb::select_db

(PECL maxdb >= 1.0)

maxdb_select_db -- maxdb::select_db — Selects the default database for database queries

Opis

bool maxdb_select_db ( resource $link , string $dbname )

The maxdb_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.

Informacja:

This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in maxdb_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

/* change db to non existing db */
$maxdb->select_db("XXXXXXXX");

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

/* change db to non existing db */
maxdb_select_db($link, "XXXXXXXX");

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

maxdb_close($link);
?>

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

Default database is <...>.

Warning: maxdb_select_db(): -10709 Connection failed (RTE:database not running) <...>

Warning: maxdb_query(): -10821 Session not connected [] <...>

Warning: maxdb_close(): -10821 Session not connected [] <...>

Zobacz też:

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_real_connect() - Opens a connection to a MaxDB server

maxdb_rpl_query_type
maxdb_send_long_data
MaxDB Funkcje


Alias dla maxdb_stmt_send_long_data

maxdb_select_db
maxdb_send_query
MaxDB Funkcje
PHP Manual

maxdb_send_long_data

(PECL maxdb >= 1.0)

maxdb_send_long_data — Alias dla maxdb_stmt_send_long_data()

Opis

Ta funkcja jest aliasem dla: maxdb_stmt_send_long_data().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

maxdb_select_db
maxdb_send_query
MaxDB Funkcje


Send the query and return

maxdb_send_long_data
maxdb_server_end
MaxDB Funkcje
PHP Manual

maxdb_send_query

maxdb::send_query

(PECL maxdb >= 1.0)

maxdb_send_query -- maxdb::send_query — Send the query and return

Opis

Styl proceduralny

bool maxdb_send_query ( resource $link , string $query )

Styl obiektowy

bool maxdb::send_query ( string $query )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_send_long_data
maxdb_server_end
MaxDB Funkcje


Shut down the embedded server

maxdb_send_query
maxdb_server_init
MaxDB Funkcje
PHP Manual

maxdb_server_end

(PECL maxdb >= 1.0)

maxdb_server_end — Shut down the embedded server

Opis

void maxdb_server_end ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_send_query
maxdb_server_init
MaxDB Funkcje


Initialize embedded server

maxdb_server_end
maxdb_set_opt
MaxDB Funkcje
PHP Manual

maxdb_server_init

(PECL maxdb >= 1.0)

maxdb_server_init — Initialize embedded server

Opis

bool maxdb_server_init ([ array $server [, array $groups ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_server_end
maxdb_set_opt
MaxDB Funkcje


Alias dla maxdb_options

maxdb_server_init
maxdb_sqlstate
MaxDB Funkcje
PHP Manual

maxdb_set_opt

(PECL maxdb 1.0)

maxdb_set_opt — Alias dla maxdb_options()

Opis

Ta funkcja jest aliasem dla: maxdb_options().

maxdb_server_init
maxdb_sqlstate
MaxDB Funkcje


Returns the SQLSTATE error from previous MaxDB operation

maxdb_set_opt
maxdb_ssl_set
MaxDB Funkcje
PHP Manual

maxdb_sqlstate

maxdb::sqlstate

(PECL maxdb >= 1.0)

maxdb_sqlstate -- maxdb::sqlstate — Returns the SQLSTATE error from previous MaxDB operation

Opis

Styl proceduralny

string maxdb_sqlstate ( resource $link )

Styl obiektowy

string $maxdb->sqlstate;

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.

Informacja:

Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Zwracane wartości

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!$maxdb->query("CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", $maxdb->sqlstate);
}

$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!maxdb_query($link, "CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", maxdb_sqlstate($link));
}

maxdb_close($link);
?>

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

Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...>
Error - SQLSTATE I6000.

Zobacz też:

  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error

maxdb_set_opt
maxdb_ssl_set
MaxDB Funkcje


Used for establishing secure connections using SSL

maxdb_sqlstate
maxdb_stat
MaxDB Funkcje
PHP Manual

maxdb_ssl_set

maxdb::ssl_set

(PECL maxdb >= 1.0)

maxdb_ssl_set -- maxdb::ssl_set — Used for establishing secure connections using SSL

Opis

Styl proceduralny

bool maxdb_ssl_set ( resource $link , string $key , string $cert , string $ca , string $capath , string $cipher )

Styl obiektowy

bool maxdb::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_sqlstate
maxdb_stat
MaxDB Funkcje


Gets the current system status

maxdb_ssl_set
maxdb_stmt_affected_rows
MaxDB Funkcje
PHP Manual

maxdb_stat

maxdb::stat

(PECL maxdb >= 1.0)

maxdb_stat -- maxdb::stat — Gets the current system status

Opis

Styl proceduralny

string maxdb_stat ( resource $link )

Styl obiektowy

string maxdb::stat ( void )

maxdb_stat() returns a string containing several information about the MaxDB server running.

Zwracane wartości

A string describing the server status. FALSE if an error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("System status: %s\n", $maxdb->stat());

$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("System status: %s\n", maxdb_stat($link));

maxdb_close($link);
?>

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

System status: Kernel    7<...>

Zobacz też:

  • maxdb_get_server_info() - Returns the version of the MaxDB server

maxdb_ssl_set
maxdb_stmt_affected_rows
MaxDB Funkcje


Returns the total number of rows changed, deleted, or inserted by the last executed statement

maxdb_stat
maxdb_stmt_bind_param
MaxDB Funkcje
PHP Manual

maxdb_stmt_affected_rows

maxdb_stmt::affected_rows

(PECL maxdb >= 1.0)

maxdb_stmt_affected_rows -- maxdb_stmt::affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement

Opis

Styl proceduralny

int maxdb_stmt_affected_rows ( resource $stmt )

Styl obiektowy

int $maxdb_stmt->affected_rows;

maxdb_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid or the number of rows can not determined, this function will return -1.

Zwracane wartości

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error or the number of rows can not determined.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = $maxdb->prepare($query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   $stmt->bind_param("s", $code);

   /* execute statement */
   $stmt->execute();

   printf("rows inserted: %d\n", $stmt->affected_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = maxdb_prepare($link, $query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   maxdb_stmt_bind_param($stmt, "s", $code);

   /* execute statement */
   maxdb_stmt_execute($stmt);

   printf("rows inserted: %d\n", maxdb_stmt_affected_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

rows inserted: 4

Zobacz też:

  • maxdb_stmt_num_rows() - Return the number of rows in statements result set
  • maxdb_prepare() - Prepare an SQL statement for execution

maxdb_stat
maxdb_stmt_bind_param
MaxDB Funkcje


Binds variables to a prepared statement as parameters

maxdb_stmt_affected_rows
maxdb_stmt_bind_result
MaxDB Funkcje
PHP Manual

maxdb_stmt_bind_param

maxdb_stmt::bind_param

(PECL maxdb >= 1.0)

maxdb_stmt_bind_param -- maxdb_stmt::bind_param — Binds variables to a prepared statement as parameters

Opis

Styl proceduralny

bool maxdb_stmt_bind_param ( resource $stmt , string $types , mixed &$var1 [, mixed &$... ] )

Styl obiektowy

bool maxdb_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

Styl proceduralny (extended syntax):

bool maxdb_stmt_bind_param ( resource $stmt , string $types , array &$var )

Styl obiektowy (extended syntax):

bool maxdb_stmt::bind_param ( string $types , array &$var )

maxdb_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to maxdb_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables.

The extended syntax of maxdb_stmt_bind_param() allows to give the parameters as an array instead of a variable list of PHP variables to the function. If the array variable has not been used before calling maxdb_stmt_bind_param(), it has to be initialized as an emtpy array. See the examples how to use maxdb_stmt_bind_param() with extended syntax.

Variables for SELECT INTO SQL statements can also be bound using maxdb_stmt_bind_param(). Parameters for database procedures can be bound using maxdb_stmt_bind_param(). See the examples how to use maxdb_stmt_bind_param() in this cases.

If a variable bound as INTO variable to an SQL statement was used before, the content of this variable is overwritten by the data of the SELECT INTO statement. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().

For INOUT parameters of database procedures the content of the bound INOUT variable is overwritten by the output value of the database procedure. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().

Type specification chars
Character | Description
i | corresponding variable has type integer
d | corresponding variable has type double
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packages

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");
$stmt->bind_param('sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query ($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query ($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = maxdb_prepare($link, "INSERT INTO temp.mycity VALUES (?, ?, ?)");
maxdb_stmt_bind_param($stmt, 'sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
maxdb_stmt_execute($stmt);

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

/* close statement and connection */
maxdb_stmt_close($stmt);

/* Clean up table CountryLanguage */
maxdb_query($link, "DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", maxdb_affected_rows($link));

/* close connection */
maxdb_close($link);
?>

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

1 Row inserted.
1 Row deleted.

Przykład #3 Styl proceduralny (SELECT INTO)

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT price INTO ? FROM hotel.room where hno = ? and type = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$hno = "50";
$rtype = "suite";

maxdb_stmt_bind_param($stmt, 'dss', $price, $hno, $rtype);
maxdb_stmt_execute($stmt);

printf ("%f\n", $price);

maxdb_stmt_close ($stmt);
?>

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

21.600000

Przykład #4 Styl proceduralny (DB procedure)

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?>

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

a

Przykład #5 Styl obiektowy (extended syntax)

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");

$arr = array();

$stmt->bind_param('iss', $arr);

$arr[0] = 11111;
$arr[1] = 'Georgetown';
$arr[2] = 'NY';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

$arr[0] = 22222;
$arr[1] = 'New Orleans';
$arr[2] = 'LA';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

$result = $maxdb->query("SELECT * from temp.mycity WHERE zip = '11111' OR zip = '22222'");
if ($result) {
  while ($row = $result->fetch_row()) {
    printf ("%s %s %s\n", $row[0], $row[1], $row[2]);
  }
}

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
$maxdb->query("DELETE FROM temp.mycity WHERE name='New Orleans'");
printf("%d Rows deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

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

1 Row inserted.
1 Row inserted.
11111 Georgetown NY
22222 New Orleans LA
2 Rows deleted.

Zobacz też:

  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_send_long_data() - Send data in blocks
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

maxdb_stmt_affected_rows
maxdb_stmt_bind_result
MaxDB Funkcje


Binds variables to a prepared statement for result storage

maxdb_stmt_bind_param
maxdb_stmt_close_long_data
MaxDB Funkcje
PHP Manual

maxdb_stmt_bind_result

maxdb_stmt::bind_result

(PECL maxdb >= 1.0)

maxdb_stmt_bind_result -- maxdb_stmt::bind_result — Binds variables to a prepared statement for result storage

Opis

Styl proceduralny

bool maxdb_stmt_bind_result ( resource $stmt , mixed &$var1 [, mixed &$... ] )

Styl obiektowy

bool maxdb_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )

maxdb_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When maxdb_stmt_fetch() is called to fetch data, the MaxDB client/server protocol places the data for the bound columns into the specified variables var1, ....

Informacja:

Note that all columns must be bound prior to calling maxdb_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.

A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time maxdb_stmt_fetch() is called.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = $maxdb->prepare("SELECT zip, name FROM hotel.city ORDER BY name")) {
   $stmt->execute();

   /* bind variables to prepared statement */
   $stmt->bind_result($col1, $col2);

   /* fetch values */
   while ($stmt->fetch()) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   $stmt->close();
}
/* close connection */
$maxdb->close();

?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = maxdb_prepare($link, "SELECT zip, name FROM hotel.city ORDER BY name")) {
   maxdb_stmt_execute($stmt);

   /* bind variables to prepared statement */
   maxdb_stmt_bind_result($stmt, $col1, $col2);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

12203 Albany
60601 Chicago
60615 Chicago
45211 Cincinnati
33575 Clearwater
75243 Dallas
32018 Daytona Beach
33441 Deerfield Beach
48226 Detroit
90029 Hollywood
92714 Irvine
90804 Long Beach
11788 Long Island
90018 Los Angeles
70112 New Orleans
10019 New York
10580 New York
92262 Palm Springs
97213 Portland
60018 Rosemont
95054 Santa Clara
20903 Silver Spring
20005 Washington
20019 Washington
20037 Washington

Zobacz też:

  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_init() - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

maxdb_stmt_bind_param
maxdb_stmt_close_long_data
MaxDB Funkcje


Ends a sequence of maxdb_stmt_send_long_data

maxdb_stmt_bind_result
maxdb_stmt_close
MaxDB Funkcje
PHP Manual

maxdb_stmt_close_long_data

maxdb_stmt::close_long_data

(PECL maxdb 1.0)

maxdb_stmt_close_long_data -- maxdb_stmt::close_long_data — Ends a sequence of maxdb_stmt_send_long_data()

Opis

Styl proceduralny

bool maxdb_stmt_close_long_data ( resource $stmt , int $param_nr )

Styl obiektowy

bool maxdb_stmt::close_long_data ( void )

This function has to be called after a sequence of maxdb_stmt_send_long_data(), that was started after maxdb_execute().

param_nr indicates which parameter to associate the end of data with. Parameters are numbered beginning with 0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

maxdb_stmt_bind_result
maxdb_stmt_close
MaxDB Funkcje


Closes a prepared statement

maxdb_stmt_close_long_data
maxdb_stmt_data_seek
MaxDB Funkcje
PHP Manual

maxdb_stmt_close

maxdb_stmt::close

(PECL maxdb >= 1.0)

maxdb_stmt_close -- maxdb_stmt::close — Closes a prepared statement

Opis

Styl proceduralny

bool maxdb_stmt_close ( resource $stmt )

Styl obiektowy

bool maxdb_stmt::close ( void )

Closes a prepared statement. maxdb_stmt_close() also deallocates the statement handle pointed to by stmt. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution

maxdb_stmt_close_long_data
maxdb_stmt_data_seek
MaxDB Funkcje


Seeks to an arbitray row in statement result set

maxdb_stmt_close
maxdb_stmt_errno
MaxDB Funkcje
PHP Manual

maxdb_stmt_data_seek

maxdb_stmt::data_seek

(PECL maxdb >= 1.0)

maxdb_stmt_data_seek -- maxdb_stmt::data_seek — Seeks to an arbitray row in statement result set

Opis

Styl proceduralny

bool maxdb_stmt_data_seek ( resource $statement , int $offset )

Styl obiektowy

bool maxdb_stmt::data_seek ( int $offset )

The maxdb_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_stmt_num_rows() - 1).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* store result */
   $stmt->store_result();

   /* seek to row no. 5 */
   $stmt->data_seek(5);

   /* fetch values */
   $stmt->fetch();

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* store result */
   maxdb_stmt_store_result($stmt);

   /* seek to row no. 5 */
   maxdb_stmt_data_seek($stmt, 5);

   /* fetch values */
   maxdb_stmt_fetch($stmt);

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

City: Dallas  Zip: 75243

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution

maxdb_stmt_close
maxdb_stmt_errno
MaxDB Funkcje


Returns the error code for the most recent statement call

maxdb_stmt_data_seek
maxdb_stmt_error
MaxDB Funkcje
PHP Manual

maxdb_stmt_errno

maxdb_stmt::errno

(PECL maxdb >= 1.0)

maxdb_stmt_errno -- maxdb_stmt::errno — Returns the error code for the most recent statement call

Opis

Styl proceduralny

int maxdb_stmt_errno ( resource $stmt )

Styl obiektowy

int $maxdb_stmt->errno;

For the statement specified by stmt, maxdb_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.

Informacja:

For possible error codes see documentation of SQLDBC: » http://maxdb.sap.com/documentation/.

Zwracane wartości

An error code value. Zero means no error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %d.\n", $stmt->errno);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %d.\n", maxdb_stmt_errno($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: -4004.

Zobacz też:

  • maxdb_stmt_error() - Returns a string description for last statement error
  • maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

maxdb_stmt_data_seek
maxdb_stmt_error
MaxDB Funkcje


Returns a string description for last statement error

maxdb_stmt_errno
maxdb_stmt_execute
MaxDB Funkcje
PHP Manual

maxdb_stmt_error

maxdb_stmt::error

(PECL maxdb >= 1.0)

maxdb_stmt_error -- maxdb_stmt::error — Returns a string description for last statement error

Opis

Styl proceduralny

string maxdb_stmt_error ( resource $stmt )

Styl obiektowy

string $maxdb_stmt->error;

For the statement specified by stmt, maxdb_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.

Zwracane wartości

A string that describes the error. An empty string if no error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->error);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_error($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: POS(23) Unknown table name:MYCITY.

Zobacz też:

  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

maxdb_stmt_errno
maxdb_stmt_execute
MaxDB Funkcje


Executes a prepared Query

maxdb_stmt_error
maxdb_stmt_fetch
MaxDB Funkcje
PHP Manual

maxdb_stmt_execute

maxdb_stmt::execute

(PECL maxdb >= 1.0)

maxdb_stmt_execute -- maxdb_stmt::execute — Executes a prepared Query

Opis

Styl proceduralny

bool maxdb_stmt_execute ( resource $stmt )

Styl obiektowy

bool maxdb_stmt::execute ( void )

The maxdb_stmt_execute() function executes a query that has been previously prepared using the maxdb_prepare() function represented by the stmt resource. When executed any parameter markers which exist will automatically be replaced with the appropiate data.

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the maxdb_stmt_affected_rows() function. Likewise, if the query yields a result set the maxdb_fetch() function is used.

Informacja:

When using maxdb_stmt_execute(), the maxdb_fetch() function must be used to fetch the data prior to preforming any additional queries.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = $maxdb->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
$stmt->execute();

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = $maxdb->query($query)) {
   while ($row = $result->fetch_row()) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   $result->close();
}

/* remove table */
$maxdb->query("DROP TABLE temp.mycity");

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = maxdb_prepare($link, $query);

maxdb_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
maxdb_stmt_execute($stmt);

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
maxdb_stmt_execute($stmt);

/* close statement */
maxdb_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = maxdb_query($link, $query)) {
   while ($row = maxdb_fetch_row($result)) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   maxdb_free_result($result);
}

/* remove table */
maxdb_query($link, "DROP TABLE temp.mycity");

/* close connection */
maxdb_close($link);
?>

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

11111 (Georgetown,NY)
22222 (Hubbatown,CA)

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

maxdb_stmt_error
maxdb_stmt_fetch
MaxDB Funkcje


Fetch results from a prepared statement into the bound variables

maxdb_stmt_execute
maxdb_stmt_free_result
MaxDB Funkcje
PHP Manual

maxdb_stmt_fetch

maxdb_stmt::fetch

(PECL maxdb >= 1.0)

maxdb_stmt_fetch -- maxdb_stmt::fetch — Fetch results from a prepared statement into the bound variables

Opis

Styl proceduralny

bool maxdb_stmt_fetch ( resource $stmt )

Styl obiektowy

bool maxdb_stmt::fetch ( void )

maxdb_stmt_fetch() returns row data using the variables bound by maxdb_stmt_bind_result().

Informacja:

Note that all columns must be bound by the application before calling maxdb_stmt_fetch().

Zwracane wartości

Return values
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occured
NULL | No more rows/data exists

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = $maxdb->prepare($query)) {

   /* execute statement */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* fetch values */
   while ($stmt->fetch()) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = maxdb_prepare($link, $query)) {

   /* execute statement */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

12203 (Albany)
60601 (Chicago)
60615 (Chicago)
45211 (Cincinnati)
33575 (Clearwater)
75243 (Dallas)
32018 (Daytona Beach)
33441 (Deerfield Beach)
48226 (Detroit)
90029 (Hollywood)
92714 (Irvine)
90804 (Long Beach)
11788 (Long Island)
90018 (Los Angeles)
70112 (New Orleans)
10019 (New York)
10580 (New York)
92262 (Palm Springs)
97213 (Portland)
60018 (Rosemont)
95054 (Santa Clara)
20903 (Silver Spring)
20005 (Washington)
20019 (Washington)
20037 (Washington)

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage

maxdb_stmt_execute
maxdb_stmt_free_result
MaxDB Funkcje


Frees stored result memory for the given statement handle

maxdb_stmt_fetch
maxdb_stmt_init
MaxDB Funkcje
PHP Manual

maxdb_stmt_free_result

maxdb_stmt::free_result

(PECL maxdb >= 1.0)

maxdb_stmt_free_result -- maxdb_stmt::free_result — Frees stored result memory for the given statement handle

Opis

Styl proceduralny

void maxdb_stmt_free_result ( resource $stmt )

Styl obiektowy

void maxdb_stmt::free_result ( void )

The maxdb_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by maxdb_stmt_store_result().

Zwracane wartości

This function doesn't return any value.

Zobacz też:

  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement

maxdb_stmt_fetch
maxdb_stmt_init
MaxDB Funkcje


Initializes a statement and returns an resource for use with maxdb_stmt_prepare

maxdb_stmt_free_result
maxdb_stmt_num_rows
MaxDB Funkcje
PHP Manual

maxdb_stmt_init

maxdb::stmt_init

(PECL maxdb >= 1.0)

maxdb_stmt_init -- maxdb::stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare

Opis

Styl proceduralny

resource maxdb_stmt_init ( resource $link )

Styl obiektowy

object maxdb::stmt_init ( void )

Allocates and initializes a statement resource suitable for maxdb_stmt_prepare().

Informacja:

Any subsequent calls to any maxdb_stmt function will fail until maxdb_stmt_prepare() was called.

Zwracane wartości

Returns an resource.

Zobacz też:

  • maxdb_stmt_prepare() - Prepare an SQL statement for execution

maxdb_stmt_free_result
maxdb_stmt_num_rows
MaxDB Funkcje


Return the number of rows in statements result set

maxdb_stmt_init
maxdb_stmt_param_count
MaxDB Funkcje
PHP Manual

maxdb_stmt_num_rows

maxdb_stmt::num_rows

(PECL maxdb >= 1.0)

maxdb_stmt_num_rows -- maxdb_stmt::num_rows — Return the number of rows in statements result set

Opis

Styl proceduralny

int maxdb_stmt_num_rows ( resource $stmt )

Styl obiektowy

int $maxdb_stmt->num_rows;

Returns the number of rows in the result set.

Zwracane wartości

An integer representing the number of rows in result set.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

Number of rows: 25.

Zobacz też:

  • maxdb_stmt_affected_rows() - Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement

maxdb_stmt_init
maxdb_stmt_param_count
MaxDB Funkcje


Returns the number of parameter for the given statement

maxdb_stmt_num_rows
maxdb_stmt_prepare
MaxDB Funkcje
PHP Manual

maxdb_stmt_param_count

maxdb_stmt::param_count

(PECL maxdb >= 1.0)

maxdb_stmt_param_count -- maxdb_stmt::param_count — Returns the number of parameter for the given statement

Opis

Styl proceduralny

int maxdb_stmt_param_count ( resource $stmt )

Styl obiektowy

int $maxdb_stmt->param_count;

maxdb_stmt_param_count() returns the number of parameter markers present in the prepared statement.

Zwracane wartości

returns an integer representing the number of parameters.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = $maxdb->prepare("SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = $stmt->param_count;
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = maxdb_prepare($link, "SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = maxdb_stmt_param_count($stmt);
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

Statement has 2 markers.

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution

maxdb_stmt_num_rows
maxdb_stmt_prepare
MaxDB Funkcje


Prepare an SQL statement for execution

maxdb_stmt_param_count
maxdb_stmt_reset
MaxDB Funkcje
PHP Manual

maxdb_stmt_prepare

maxdb_stmt::prepare

(PECL maxdb >= 1.0)

maxdb_stmt_prepare -- maxdb_stmt::prepare — Prepare an SQL statement for execution

Opis

Styl proceduralny

bool maxdb_stmt_prepare ( resource $stmt , string $query )

Styl obiektowy

mixed maxdb_stmt::prepare ( string $query )

maxdb_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement resource has to be allocated by maxdb_stmt_init(). The query must consist of a single SQL statement.

Informacja:

You should not add a terminating semicolon or \g to the statement.

The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Informacja:

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt =  $maxdb->stmt_init();
if ($stmt->prepare("SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   $stmt->bind_param("s", $city);

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($district);

   /* fetch value */
   $stmt->fetch();

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt = maxdb_stmt_init($link);
if (maxdb_stmt_prepare($stmt, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

Portland is in district OR

Zobacz też:

  • maxdb_stmt_init() - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_close() - Closes a prepared statement

maxdb_stmt_param_count
maxdb_stmt_reset
MaxDB Funkcje


Resets a prepared statement

maxdb_stmt_prepare
maxdb_stmt_result_metadata
MaxDB Funkcje
PHP Manual

maxdb_stmt_reset

maxdb_stmt::reset

(PECL maxdb >= 1.0)

maxdb_stmt_reset -- maxdb_stmt::reset — Resets a prepared statement

Opis

Styl proceduralny

bool maxdb_stmt_reset ( resource $stmt )

Styl obiektowy

bool maxdb_stmt::reset ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

maxdb_stmt_prepare
maxdb_stmt_result_metadata
MaxDB Funkcje


Returns result set metadata from a prepared statement

maxdb_stmt_reset
maxdb_stmt_send_long_data
MaxDB Funkcje
PHP Manual

maxdb_stmt_result_metadata

maxdb_stmt::result_metadata

(PECL maxdb >= 1.0)

maxdb_stmt_result_metadata -- maxdb_stmt::result_metadata — Returns result set metadata from a prepared statement

Opis

Styl proceduralny

resource maxdb_stmt_result_metadata ( resource $stmt )

Styl obiektowy

resource maxdb_stmt::result_metadata ( void )

If a statement passed to maxdb_prepare() is one that produces a result set, maxdb_stmt_result_metadata() returns the result resource that can be used to process the meta information such as total number of fields and individual field information.

Informacja:

This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • maxdb_num_fields()

  • maxdb_fetch_field()

  • maxdb_fetch_field_direct()

  • maxdb_fetch_fields()

  • maxdb_field_count()

  • maxdb_field_seek()

  • maxdb_field_tell()

  • maxdb_free_result()

The result set structure should be freed when you are done with it, which you can do by passing it to maxdb_free_result()

Informacja:

The result set returned by maxdb_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with maxdb_fetch().

Zwracane wartości

maxdb_stmt_result_metadata() returns a result resource or FALSE if an error occured.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

$maxdb->query("CREATE TABLE temp.friends (id int, name varchar(20))");

$maxdb->query("INSERT INTO temp.friends VALUES (1,'Hartmut')");
$maxdb->query("INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = $maxdb->prepare("SELECT id, name FROM temp.friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_query($link, "CREATE TABLE temp.friends (id int, name varchar(20))");

maxdb_query($link, "INSERT INTO temp.friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = maxdb_prepare($link, "SELECT id, name FROM temp.friends");
maxdb_stmt_execute($stmt);

/* get resultset for metadata */
$result = maxdb_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = maxdb_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

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

Fieldname: ID

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_free_result() - Frees the memory associated with a result

maxdb_stmt_reset
maxdb_stmt_send_long_data
MaxDB Funkcje


Send data in blocks

maxdb_stmt_result_metadata
maxdb_stmt_sqlstate
MaxDB Funkcje
PHP Manual

maxdb_stmt_send_long_data

maxdb_stmt::send_long_data

(PECL maxdb 1.0)

maxdb_stmt_send_long_data -- maxdb_stmt::send_long_data — Send data in blocks

Opis

Styl proceduralny

bool maxdb_stmt_send_long_data ( resource $stmt , int $param_nr , string $data )

Styl obiektowy

bool maxdb_stmt::stmt_send_long_data ( int $param_nr , string $data )

Allows to send parameter data to the server in pieces (or chunks). This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.

Informacja:

For efficiency reasons, this function should be used after calling maxdb_execute(). In this case, the data is not stored on the client side. The end of the sequence must end with a call to maxdb_stmt_close_long_data().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters

maxdb_stmt_result_metadata
maxdb_stmt_sqlstate
MaxDB Funkcje


Returns SQLSTATE error from previous statement operation

maxdb_stmt_send_long_data
maxdb_stmt_store_result
MaxDB Funkcje
PHP Manual

maxdb_stmt_sqlstate

(PECL maxdb >= 1.0)

maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

Opis

string maxdb_stmt_sqlstate ( resource $stmt )

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.

Informacja:

Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Zwracane wartości

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->sqlstate);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_sqlstate($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: 42000.

Zobacz też:

  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error

maxdb_stmt_send_long_data
maxdb_stmt_store_result
MaxDB Funkcje


Transfers a result set from a prepared statement

maxdb_stmt_sqlstate
maxdb_store_result
MaxDB Funkcje
PHP Manual

maxdb_stmt_store_result

maxdb::store_result

(PECL maxdb >= 1.0)

maxdb_stmt_store_result -- maxdb::store_result — Transfers a result set from a prepared statement

Opis

Styl proceduralny

bool maxdb_stmt_store_result ( resource $stmt )

Styl obiektowy

object maxdb::store_result ( void )

maxdb_stmt_store_result() has no functionally effect and should not be used for retrieving data from MaxDB server.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* free result */
   $stmt->free_result();

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* free result */
   maxdb_stmt_free_result($stmt);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

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

Number of rows: 25.

Zobacz też:

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • maxdb_fetch() - Alias dla maxdb_stmt_fetch

maxdb_stmt_sqlstate
maxdb_store_result
MaxDB Funkcje


Transfers a result set from the last query

maxdb_stmt_store_result
maxdb_thread_id
MaxDB Funkcje
PHP Manual

maxdb_store_result

maxdb::store_result

(PECL maxdb >= 1.0)

maxdb_store_result -- maxdb::store_result — Transfers a result set from the last query

Opis

Styl proceduralny

resource maxdb_store_result ( resource $link )

Styl obiektowy

object maxdb::store_result ( void )

This function has no functionally effect.

Zwracane wartości

Returns a result resource or FALSE if an error occurred.

Przykłady

See maxdb_multi_query().

Zobacz też:

  • maxdb_real_query() - Execute an SQL query
  • maxdb_use_result() - Initiate a result set retrieval

maxdb_stmt_store_result
maxdb_thread_id
MaxDB Funkcje


Returns the thread ID for the current connection

maxdb_store_result
maxdb_thread_safe
MaxDB Funkcje
PHP Manual

maxdb_thread_id

maxdb::thread_id

(PECL maxdb >= 1.0)

maxdb_thread_id -- maxdb::thread_id — Returns the thread ID for the current connection

Opis

Styl proceduralny

int maxdb_thread_id ( resource $link )

Styl obiektowy

int $maxdb->thread_id;

The maxdb_thread_id() function returns the thread ID for the current connection which can then be killed using the maxdb_kill() function. If the connection is lost and you reconnect with maxdb_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.

Informacja:

The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.

Zwracane wartości

maxdb_thread_id() returns the Thread ID for the current connection.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?>

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

Warning: maxdb_query(): -10821 Session not connected <...>
Error: Session not connected

Zobacz też:

  • maxdb_kill() - Disconnects from a MaxDB server

maxdb_store_result
maxdb_thread_safe
MaxDB Funkcje


Returns whether thread safety is given or not

maxdb_thread_id
maxdb_use_result
MaxDB Funkcje
PHP Manual

maxdb_thread_safe

(PECL maxdb >= 7.6.06.04)

maxdb_thread_safe — Returns whether thread safety is given or not

Opis

bool maxdb_thread_safe ( void )

maxdb_thread_safe() indicates whether the client library is compiled as thread-safe.

Zwracane wartości

TRUE if the client library is thread-safe, otherwise FALSE.

maxdb_thread_id
maxdb_use_result
MaxDB Funkcje


Initiate a result set retrieval

maxdb_thread_safe
maxdb_warning_count
MaxDB Funkcje
PHP Manual

maxdb_use_result

maxdb::use_result

(PECL maxdb >= 1.0)

maxdb_use_result -- maxdb::use_result — Initiate a result set retrieval

Opis

Styl proceduralny

resource maxdb_use_result ( resource $link )

Styl obiektowy

resource maxdb::use_result ( void )

maxdb_use_result() has no effect.

Zwracane wartości

Returns result lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if ($maxdb->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->use_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_use_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?>

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

a

Zobacz też:

  • maxdb_real_query() - Execute an SQL query
  • maxdb_store_result() - Transfers a result set from the last query

maxdb_thread_safe
maxdb_warning_count
MaxDB Funkcje


Returns the number of warnings from the last query for the given link

maxdb_use_result
Mongo
MaxDB Funkcje
PHP Manual

maxdb_warning_count

maxdb::warning_count

(PECL maxdb >= 1.0)

maxdb_warning_count -- maxdb::warning_count — Returns the number of warnings from the last query for the given link

Opis

Styl proceduralny

int maxdb_warning_count ( resource $link )

Styl obiektowy

int $maxdb->warning_count;

maxdb_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.

Zwracane wartości

Number of warnings or zero if there are no warnings.

Przykłady

Przykład #1 Styl obiektowy

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable city in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$maxdb->query($query);

printf ("Number of warning: %d\n", $maxdb->warning_count);

/* close connection */
$maxdb->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable long city name in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

maxdb_query($link, $query);

printf ("Number of warning: %d\n", maxdb_warning_count($link));

/* close connection */
maxdb_close($link);
?>

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

Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...>
Number of warning: 0

Zobacz też:

  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation

maxdb_use_result
Mongo
MaxDB Funkcje


MongoDB Native Driver

  • Manual
    • Instalacja
    • Tutorial
    • SQL to Mongo Mapping Chart
    • Connecting
    • Writes
    • Querying
    • Updates
    • php.ini Options
    • Security
    • Troubleshooting
    • Running the Driver's Tests
  • Core Classes
    • Mongo — The Mongo class
    • MongoDB — The MongoDB class
    • MongoCollection — The MongoCollection class
    • MongoCursor — The MongoCursor class
  • Types
    • MongoId — The MongoId class
    • MongoCode — The MongoCode class
    • MongoDate — The MongoDate class
    • MongoRegex — The MongoRegex class
    • MongoBinData — The MongoBinData class
    • MongoInt32 — The MongoInt32 class
    • MongoInt64 — The MongoInt64 class
    • MongoDBRef — The MongoDBRef class
    • MongoMinKey — The MongoMinKey class
    • MongoMaxKey — The MongoMaxKey class
    • MongoTimestamp — The MongoTimestamp class
  • GridFS Classes
    • MongoGridFS — The MongoGridFS class
    • MongoGridFSFile — The MongoGridFSFile class
    • MongoGridFSCursor — The MongoGridFSCursor class
  • Miscellaneous
    • MongoLog — The MongoLog class
    • MongoPool — The MongoPool class
  • Functions
    • Mongo Funkcje
  • Exceptions
    • MongoException — The MongoException class
    • MongoCursorException — The MongoCursorException class
    • MongoCursorTimeoutException — The MongoCursorTimeoutException class
    • MongoConnectionException — The MongoConnectionException class
    • MongoGridFSException — The MongoGridFSException class
maxdb_warning_count
Manual
Rozszerzenia producentów baz danych


Manual

Spis treści

  • Instalacja
  • Tutorial
  • SQL to Mongo Mapping Chart
  • Connecting
  • Writes
  • Querying
  • Updates
  • php.ini Options
  • Security
  • Troubleshooting
  • Running the Driver's Tests

This manual goes into some detail about how to use MongoDB, but it mostly covers using the PHP driver. For information about how to design a schema, what terms means, and setting up the database server, check out the » MongoDB documentation.

Mongo
Instalacja
Mongo


Instalacja

The MongoDB PHP driver should work on nearly any system: Windows, Mac OS X, Unix, and Linux; little- and big-endian machines; 32- and 64-bit machines; PHP 5.1, 5.2, and 5.3.

To rozszerzenie » PECL nie jest dołączane do PHP. This page gives more specific information on installing on different systems and troubleshooting issues users have run into.

  • » Installing on *NIX

  • » Manual Installation

  • » OS X

  • » Gentoo

  • » Fedora

  • » Installing on Windows

  • » Third-Party Installation Instructions

Installing on *NIX

Run:

$ sudo pecl install mongo

If you are using CentOS or Redhat, Csoke Arpad created » RPMs for these distributions.

Add the following line to your php.ini file:

extension=mongo.so

If pecl runs out of memory while installing, make sure memory_limit in php.ini is set to at least 32MB.

Manual Installation

For driver developers and people interested in the latest bugfixes, you can compile the driver from the latest source code on » Github. Go to Github and click the "download" button. Then run:

$ tar zxvf mongodb-mongodb-php-driver-<commit_id>.tar.gz
$ cd mongodb-mongodb-php-driver-<commit_id>
$ phpize
$ ./configure
$ sudo make install

Make the following changes to php.ini:

  • Make sure the extension_dir variable is pointing to the location of mongo.so. The build will display where it is installing the PHP driver with output that looks something like:

      Installing '/usr/lib/php/extensions/no-debug-zts-20060613/mongo.so'
    Make sure that it is the same as the PHP extension directory by runnning:

      $ php -i | grep extension_dir
        extension_dir => /usr/lib/php/extensions/no-debug-zts-20060613 =>
      /usr/lib/php/extensions/no-debug-zts-20060613
    If it's not, change the extension_dir in php.ini or move mongo.so.

  • To load the extension on PHP startup, add a line:

      extension=mongo.so

OS X

If your system is unable to find autoconf, you'll need to install Xcode (available on your installation DVD or as a free download from the Apple website).

If you are using XAMPP, you may be able to compile the driver with the following command:

sudo /Applications/XAMPP/xamppfiles/bin/pecl install mongo

If you are using MAMP (or XAMPP and the above command does not work), precompiled binaries are available from » Github (download the latest one with "osx" in the name that matches your version of PHP). Extract mongo.so from the archive and add it to MAMP or XAMPP's extension directory. Add

      extension=mongo.so
to the php.ini file being used and restart the server.

Gentoo

Gentoo has a package for the PHP driver called dev-php5/mongo, which can be installed with:

$ sudo emerge -va dev-php5/mongo

If you use PECL, you may get an error that libtool is the wrong version. Compiling from source you'll need to run aclocal and autoconf.

$ phpize && aclocal && autoconf && ./configure && make && make install

Red Hat

This includes Fedora and CentOS.

The default Apache settings on these systems do not let requests make network connections, meaning that the driver will get "Permission denied" errors when it tries to connect to the database. If you run into this, try running:

$ /usr/sbin/setsebool -P httpd_can_network_connect 1
Then restart Apache. (This issue has also occurred with SELinux.)

Installing on Windows

Precompiled binaries for each release are available from » Github for a variety of combinations of versions, thread safety, and VC libraries. Unzip the archive and put php_mongo.dll in your PHP extension directory ("ext" by default).

The latest (non-release) code is compiled into Windows binaries on every commit. The zip consists of a .zip with php_mongo.dll and a version.txt. Please keep the version.txt around so that if you have a question or problem, you can give the developers the exact version you're using. (The number is long and nonsensical, but it will make sense to the developers!)

To get the latest bug fixes (and possibly bugs), download the binary corresponding to the PHP you have installed:

  • » PHP 5.2 VC6 Non-Thread-Safe Mongo extension

  • » PHP 5.2 VC6 Thread-Safe Mongo extension

  • » PHP 5.3 VC6 Non-Thread-Safe Mongo extension

  • » PHP 5.3 VC6 Thread-Safe Mongo extension

  • » PHP 5.3 VC8 Non-Thread-Safe Mongo extension

  • » PHP 5.3 VC8 Thread-Safe Mongo extension

  • » PHP 5.3 VC9 Non-Thread-Safe Mongo extension

  • » PHP 5.3 VC9 Thread-Safe Mongo extension

Add the following line to your php.ini file:

extension=php_mongo.dll

Third-Party Installation Instructions

A number of people have created excellent tutorials on installing the PHP driver.

  • » PHP 5.3.1 with Xdebug, MongoDB and Lithium on Ubuntu 9.10 / Apache 2.2

    An excellent video that takes you step-by-step through installing Apache, PHP, Xdebug, MongoDB, and Lithium by Jon Adams.

  • » Installing MongoDB and the PHP driver on Ubuntu 9.04

    Spanish article by Javier Aranda (» English translation).

  • » OS X: Installing MongoDB and the PHP Mongo Driver

    By Matt Butcher.

Manual
Tutorial
Manual


Tutorial

Introduction

This is the 10gen-supported PHP driver for MongoDB.

Here's a quick code sample that connects, inserts documents, queries for documents, iterates through query results, and disconnects from MongoDB. There are more details on each step in the tutorial below.

<?php

// connect
$m = new Mongo();

// select a database
$db = $m->comedy;

// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;

// add a record
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj);

// add another record, with a different "shape"
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);

// find everything in the collection
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $obj) {
    echo $obj["title"] . "\n";
}

?>

This would output:

Calvin and Hobbes
XKCD

Making a Connection

To connect to the database server, use one of the following:

<?php

$connection = new Mongo(); // connects to localhost:27017
$connection = new Mongo( "example.com" ); // connect to a remote host (default port: 27017)
$connection = new Mongo( "example.com:65432" ); // connect to a remote host at a given port

?>

You do not have to explicitly disconnect from the database. When $connection goes out of scope, the connection will be closed automatically and any database resources it was using will be freed.

See Also

The chapter on connecting covers different types of connections.

The API documentation on the Mongo class and Mongo::__construct() give a comprehensive look at all possible options with a number of examples.

Getting a Database

To select a database, use:

<?php

$db = $connection->dbname;

?>

The database does not need to be created in advance, you can create new databases by selecting them.

Be careful of typos! You can inadvertently create a new database, which can cause confusing errors:

<?php

$db = $connection->mybiglongdbname;
// do some stuff
$db = $connection->mybiglongdbanme;
// now connected to a different database!

?>

See Also

The API documentation on the MongoDB class contains more information about database objects.

Getting A Collection

Getting a collection has the same syntax as getting a database:

<?php

$db = $connection->baz;
$collection = $db->foobar;

// or, more succinctly
$collection = $connection->baz->foobar;

?>

A collection is analogous to a table (if you are familiar with relational databases).

See Also

The API documentation on the MongoCollection class contains more information about collection objects.

Inserting a Document

Associative arrays are the basic object that can be saved to a collection in the database. A somewhat random "document" might be:

<?php

$doc = array( "name" => "MongoDB",
   "type" => "database",
   "count" => 1,
   "info" => (object)array( "x" => 203, "y" => 102),
   "versions" => array("0.9.7", "0.9.8", "0.9.9")
);

?>

Note that you can have nested arrays and objects.

To insert this document, use MongoCollection::insert():

<?php

$collection->insert( $doc );

?>

See Also

The API documentation on MongoCollection::insert() contains more information about inserting data.

Finding Documents using MongoCollection::findOne()

To show that the document we inserted in the previous step is there, we can do a simple MongoCollection::findOne() operation to get a single document from the collection. This method is useful when there only is one document matching the query or you are only interested in one result.

<?php

$obj = $collection->findOne();
var_dump( $obj );

?>

This should print:

array(6) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "4e2995576803fab768000000"
  }
  ["name"]=>
  string(7) "MongoDB"
  ["type"]=>
  string(8) "database"
  ["count"]=>
  int(1)
  ["info"]=>
  array(2) {
    ["x"]=>
    int(203)
    ["y"]=>
    int(102)
  }
  ["versions"]=>
  array(3) {
    [0]=>
    string(5) "0.9.7"
    [1]=>
    string(5) "0.9.8"
    [2]=>
    string(5) "0.9.9"
  }
}

Note that there is an _id field that has been added automatically to your document. _id is the "primary key" field. If your document does not specify one, the driver will add one automatically.

If you specify your own _id field, it must be unique to the collection. See the example here:

<?php

$db->foo->insert(array("_id" => 1), array("safe" => true));
// this will throw an exception
$db->foo->insert(array("_id" => 1), array("safe" => true));

// this is fine, as it is a different collection
$db->bar->insert(array("_id" => 1), array("safe" => true));

?>

Note that these inserts pass a second array: array("safe" => true). This second field specifies options for the insert. By default, the driver does not wait for a database response for writes, so the driver would not catch the the _id. As we specify that this is a "safe" write, the driver will wait for a database response and see that the write did not go through. In general, all writes should use the "safe" option (it is omitted in previous examples for simplicity).

See Also

MongoCollection::findOne() for more information about finding data.

MongoId goes into more detail on unique ids.

The writes section covers safe
writes in more depth, as do the writing functions such as
MongoCollection::insert(),
MongoCollection::update(), and
MongoCollection::remove().

Adding Multiple Documents

In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be of the form array( "i" => value ); and we can do this fairly efficiently in a loop:

<?php

for($i=0; $i<100; $i++) {
    $collection->insert( array( "i" => $i ) );
}

?>

Notice that we can insert arrays with different key sets into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free".

Counting Documents in A Collection

Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the MongoCollection::count() method.

<?php

echo $collection->count();

?>
and it should print 101.

Using a Cursor to Get All of the Documents

In order to get all the documents in the collection, we will use MongoCollection::find(). The find() method returns a MongoCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out:

<?php

$cursor = $collection->find();
foreach ($cursor as $id => $value) {
    echo "$id: ";
    var_dump( $value );
}

?>
and that should print all 101 documents in the collection. $id is the _id field of a document (cast to a string) and $value is the document itself.

See Also

The API documentation on MongoCollection::find() contains more information about finding data.

Setting Criteria for a Query

We can create a query to pass to the MongoCollection::find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following:

<?php

$query = array( "i" => 71 );
$cursor = $collection->find( $query );

while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

?>

and it should just print just one document:

array(2) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["i"]=>
  int(71)
  ["_ns"]=>
  "testCollection"
}

Getting A Set of Documents With a Query

We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write:

<?php

$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $coll->find( $query );

while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

?>

which should print the documents where i > 50. We could also get a range, say 20 < i <= 30:

<?php

$query = array( "i" => array( "\$gt" => 20, "\$lte" => 30 ) );
$cursor = $coll->find( $query );

while( $cursor->hasNext() ) {
    var_dump( $cursor->getNext() );
}

?>

Remember to always escape the $-symbol or use single quotes. Otherwise PHP will interpret it to be the variable $gt.

Creating An Index

MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you specify the field name and direction: ascending (1) or descending (-1). The following creates an ascending index on the "i" field:

<?php

$coll->ensureIndex( array( "i" => 1 ) );  // create index on "i"
$coll->ensureIndex( array( "i" => -1, "j" => 1 ) );  // index on "i" descending, "j" ascending

?>

Indexing is critical for good read performance as your data grows. If you are not familiar with indexing, check out the MongoCollection::ensureIndex() documentation and the core » MongoDB indexing documentation.

Instalacja
SQL to Mongo Mapping Chart
Manual


SQL to Mongo Mapping Chart

This is a PHP-specific version of the » SQL to Mongo mapping chart in the main docs.

SQL Statement | Mongo Query Language Statement
CREATE TABLE USERS (a Number, b Number) | Implicit or use MongoDB::createCollection().
INSERT INTO USERS VALUES(1,1) | $db->users->insert(array("a" => 1, "b" => 1));
SELECT a,b FROM users | $db->users->find(array(), array("a" => 1, "b" => 1));
SELECT * FROM users WHERE age=33 | $db->users->find(array("age" => 33));
SELECT a,b FROM users WHERE age=33 | $db->users->find(array("age" => 33), array("a" => 1, "b" => 1));
SELECT a,b FROM users WHERE age=33 ORDER BY name | $db->users->find(array("age" => 33), array("a" => 1, "b" => 1))->sort(array("name" => 1));
SELECT * FROM users WHERE age>33 | $db->users->find(array("age" => array('$gt' => 33)));
SELECT * FROM users WHERE age<33 | $db->users->find(array("age" => array('$lt' => 33)));
SELECT * FROM users WHERE name LIKE "%Joe%" | $db->users->find(array("name" => new MongoRegex("/Joe/")));
SELECT * FROM users WHERE name LIKE "Joe%" | $db->users->find(array("name" => new MongoRegex("/^Joe/")));
SELECT * FROM users WHERE age>33 AND age<=40 | $db->users->find(array("age" => array('$gt' => 33, '$lte' => 40)));
SELECT * FROM users ORDER BY name DESC | $db->users->find()->sort(array("name" => -1));
CREATE INDEX myindexname ON users(name) | $db->users->ensureIndex(array("name" => 1));
CREATE INDEX myindexname ON users(name,ts DESC) | $db->users->ensureIndex(array("name" => 1, "ts" => -1));
SELECT * FROM users WHERE a=1 and b='q' | $db->users->find(array("a" => 1, "b" => "q"));
SELECT * FROM users LIMIT 10 SKIP 20 | $db->users->find()->limit(10)->skip(20);
SELECT * FROM users WHERE a=1 or b=2 | $db->users->find(array('$or' => array(array("a" => 1), array("b" => 2))));
SELECT * FROM users LIMIT 1 | $db->users->find()->limit(1);
EXPLAIN SELECT * FROM users WHERE z=3 | $db->users->find(array("z" => 3))->explain()
SELECT DISTINCT last_name FROM users | $db->command(array("distinct" => "users", "key" => "last_name"));
SELECT COUNT(*y) FROM users | $db->users->count();
SELECT COUNT(*y) FROM users where AGE > 30 | $db->users->find(array("age" => array('$gt' => 30)))->count();
SELECT COUNT(AGE) from users | $db->users->find(array("age" => array('$exists' => true)))->count();
UPDATE users SET a=1 WHERE b='q' | $db->users->update(array("b" => "q"), array('$set' => array("a" => 1)));
UPDATE users SET a=a+2 WHERE b='q' | $db->users->update(array("b" => "q"), array('$inc' => array("a" => 2)));
DELETE FROM users WHERE z="abc" | $db->users->remove(array("z" => "abc"));

Tutorial
Connecting
Manual


Connecting

Connecting to MongoDB can be as easy as new Mongo, but there are many additional options and configurations. The Mongo::__construct() page covers all of the API options, but this page gives some more details and advice for practical use cases.

Logging In on Connection

If MongoDB is started with the --auth or --keyFile options, you must log in before you can do any operations with the driver. You can log in on connection by supplying the username and password in the connection URI:

<?php

$m = new Mongo("mongodb://${username}:${password}@localhost");

?>

If your connection is dropped, the driver will automatically attempt to reconnect and reauthenticate you.

You can also authenticate on a per-database level with MongoDB::authenticate():

<?php

$m = new Mongo();
$db = $m->admin;

$db->authenticate($username, $password);

?>

There is a major disadvantage to this method: if the connection is dropped and then reconnects, the new connection will not be authenticated. If you use the URI format, the PHP driver will automatically authenticate the user whenever a new connection is made.

To authenticate with a different database, specify the database name after the hosts. This example will log the user into the "blog" database:

<?php

$m = new Mongo("mongodb://${username}:${password}@localhost/blog");

?>

Replica Sets

To connect to a replica set, specify one or more members of the set and use the replicaSet option.

<?php

$m = new Mongo("mongodb://localhost:27017", array("replicaSet" => "myReplSetName"));

?>

Version 1.0.9+ of the driver is required to connect to a replica set (earlier versions of the driver will not autodetect the master or reconnect correctly).

The PHP driver will query the database server(s) listed to figure out who is master. So long as it can connect to at least one host listed and find a master, the connection will succeed. If it cannot make a connection to any servers listed or cannot find a master, a MongoConnectionException will be thrown.

If the master becomes unavailable, the slaves will not promote a new master for a few seconds. During that time, this connection will not be able to perform any database operations (connections to slaves will still be able to perform reads). Thus, if you attempt to do any sort of read or write on this connection, it will throw an exception.

Once a master is elected, attempting to perform a read or write will allow the driver to detect the new master. The driver will make this its primary database connection and continue operating normally.

For more information on replica sets, see the » core documentation.

Domain Socket Support

If you are running MongoDB locally and have version 1.0.9 or better of the driver, you can connect to the database via file. MongoDB automatically opens a socket file on startup: /tmp/mongodb-<port>.sock.

To connect to the socket file, specify the path in your MongoDB connection string:

<?php

$m = new Mongo("mongodb:///tmp/mongo-27017.sock");

?>

If you would like to use authentication on connection (as described above) with a socket file, you must specify a port of 0 so that the connection string parser knows where the end of the connection string is.

<?php

$m = new Mongo("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");

?>

Connection Pooling (version 1.2.0+)

Creating connections is one of the most heavyweight things that the driver does. It can take hundreds of milliseconds to set up a connection correctly, even on a fast network. Thus, the driver tries to minimize the number of new connections created by reusing connections from a pool.

When a user creates a new instance of Mongo, all necessary connections will be taken from their pools (replica sets may require multple connections, one for each member of the set). When the Mongo instance goes out of scope, the connections will be returned to the pool. When the PHP process exits, all connections in the pools will be closed.

"Why do I have so many open connections?"

Connection pools can generate a large number of connections. This is expected and, using a little arithmetic, you can figure out how many connections to expect. There are three factors in the total number of connections:

  • connections_per_pool

    Each connection pool will create, by default, an unlimited number of connections. One might assume that this is a problem: if it can create an unlimited number of connections, couldn't it create thousands and the server would run out of file descriptors? In practice, this is unlikely, as unused connections are returned to the pool to be used later, so future connections will use the same connection instead of creating a new one. Unless you create thousands of connections at once without letting any go out of scope, the number of connections open should stay at a reasonable number.

    You can see how many connections you have in a pool using the MongoPool::info() function. Add up the "in use" and "in pool" fields for a given server. That is the total number of connections for that pool.

  • pools_per_process

    Each MongoDB server address you're connecting to gets its own connection pool. For example, if your local hostname is "example.net", connecting to "example.net:27017", "localhost:27017", and "/tmp/mongodb-27017.sock" will create three connection pools. You can see how many connection pools you have open using MongoPool::info().

  • processes

    Each PHP process has a separate set of pools. PHP-FPM and Apache generally create between 6 and a couple dozen PHP worker children. Check your settings to see what the max number of PHP processes is that can be spawned.

    If you are using PHP-FPM, estimating the number of connections can be tricky because it will spawn more PHP-FPM workers under heavy load. To be on the safe side, look at the max_children parameter or add up spare_servers+start_servers (choose whichever number is higher). That's how many PHP processes (and, thus sets of pools) you should plan for.

The three variables above can be multiplied together to give the max number of connections expected: connections_per_pool*pools_per_process*processes. Note that connections_per_pool can be different for different pools, so connections_per_pool should be the max.

For example, suppose we're getting 30 connections per pool, 10 pools per PHP process, and 128 PHP processes. Then we can expect 38400 connections from this machine. Thus, we should set this machine's file descriptor limit to be high enough to handle all of these connections or it may run out of file descriptors.

See MongoPool for more information on connection pooling.

Persistent Connections

Informacja:

This section is not relevant for 1.2.0+. In 1.2.0+, connections are always persistent and managed automatically by the driver. See MongoPool for more information on pooling.

Creating new connection to the database is very slow. To minimize the number of connections that you need to make, you can use persistent connections. A persistent connection is saved by PHP, so you can use the same connection for multiple requests.

For example, this simple program connects to the database 1000 times:

<?php

for ($i=0; $i<1000; $i++) {
  $m = new Mongo();
}

?>

It takes approximately 18 seconds to execute. If we change it to use a persistent connection:

<?php

for ($i=0; $i<1000; $i++) {
  $m = new Mongo("localhost:27017", array("persist" => "x"));
}

?>

...it takes less than .02 seconds to execute, as it only makes one database connection.

Persistent connections need an identifier string (which is "x" in the above example) to uniquely identify them. For a persistent connection to be used, the hostname, port, persist string, and username and password (if given) must match an existing persistent connection. Otherwise, a new connection will be created with this identifying information.

Persistent connections are highly recommended and should always be used in production unless there is a compelling reason not to. Most of the reasons that they are not recommended for relational databases are irrelevant to MongoDB.

SQL to Mongo Mapping Chart
Writes
Manual


Writes

Safe Operations

By default, the driver does not wait for a database response to writes (inserts, updates, and deletes). This means that writes can be performed extremely quickly, but you don't know whether or not they actually succeeded. Writes can fail for a number of reasons: if there are network problems, if a database server goes down, or if the write was simply invalid (e.g., writing to a system collection).

To get a response from the database, use the safe option, available for all types of writes. This option will make sure that the database has the write before returning success. If the write failed, it will throw a MongoCursorException() with an explanation of the failure.

While developing, you should always use safe writes (to protect against inadvertent mistakes, such as duplicate key errors and similar). In production, unsafe writes can be used for "unimportant" data. Unimportant data varies on application, but it's generally automatically (instead of user generated) data, such as click tracking or GPS locations, where you can get thousands of records per second.

To safely perform writes without incurring too large a performance penalty, it is recommended that you do a safe write at the end of a series of writes. For example:

<?php
$collection->insert($someDoc);
$collection->update($criteria, $newObj);
$collection->insert($somethingElse);
$collection->remove($something, array("safe" => true));
?>

Then, if the last write throws an exception, you know that there's a problem with your database.

There are a few other options available to ensure the safety of writes. You can specify "fsync" => true to force the database to fsync all writes up to this point to disk (by default, MongoDB fsyncs writes once per minute).

The safest way of doing a write is to use replication and specify the number of servers that must have this write before returning success. (You should always use replication in production, see the Connecting section for more information on replica sets.)

<?php
$collection->insert($someDoc, array("safe" => 3));
?>

If you specify "safe" => N, the MongoDB server will make sure that at least N servers have a copy of the write before returning success. So, if N is 3, the master and two slaves must have the write.

Updating Nested Objects

Suppose we wish to change the name of a comment's author in this document:

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "content" : "this is a blog post.",
    "comments" :
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}
In order to change an inner field, we use $set (so that all of the other fields are not removed!) with the index of comment to change:
<?php

$blog->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

?>

The Positional Operator

The positional operator $ is useful for updating objects that are in arrays. In the example above, for instance, suppose that we did not know the index of the comment that we needed to change, merely that we needed to change "John" to "Jim". We can use $ to do so.

<?php

$blog->update(
    array("comments.author" => "John"),
    array('$set' => array('comments.$.author' => "Jim")));

?>
Connecting
Querying
Manual


Querying

Distributing queries to slaves

Informacja: 1.1.0+

If you are using a » replica set and version 1.1.0 or above of the driver, the driver can automatically route reads to slaves. This behavior does not exist in earlier versions of the driver and cannot be used with "normal" master-slave.

By default, the driver will send all queries to the master. If you set the "slaveOkay" option, the driver will send all queries to a non-primary server, if possible. The "slaveOkay" option can be set at every "level": connection, database, collection, and cursor. Each class inherits the "slaveOkay" setting from the class above it, so if you do:

<?php

$db->setSlaveOkay(true);
$c = $db->myCollection;

$cursor = $c->find();

?>

then the query will be executed against a slave (the collection inherited "slaveOkay" from the database and the cursor inherited it from the collection).

How slaves are chosen

Each instance of Mongo chooses its own slave using the available slave with the lowest ping time. So, if we had a PHP client in Europe and one in Australia and we had one secondary in each of these data centers, we could do:

<?php

// P is the primary

// on the Australian client
$m1 = new Mongo("mongodb://P", array("replicaSet" => true));
$m1->foo->bar->find()->slaveOkay()->getNext();
echo "m1's slave is ".$m1->getSlave()."\n";

// on the European client
$m2 = new Mongo("mongodb://P", array("replicaSet" => true));
$m2->foo->bar->find()->slaveOkay()->getNext();
echo "m2's slave is ".$m2->getSlave()."\n";

?>

we'd probably end up with something like:

m1's slave is: australianHost
m2's slave is: europeanHost

Note that we have to do a query before a slave is chosen: slaves are chosen lazily by the driver. Mongo::getSlave() will return NULL until a slave is used.

You can see what the driver thinks is the current status of the set members by running Mongo::getHosts().

If no non-primary server is readable, the driver will send reads to the primary (even if "slaveOkay" is set). A server is considered readable if its state is 2 (SECONDARY) and its health is 1. You can check this with Mongo::getHosts().

If you enjoy twiddling knobs that you probably shouldn't mess with, you can request the driver to use a different slave by calling Mongo::switchSlave(). This may choose a new slave (if one is available) and shouldn't be used unless you know what you're doing.

Random notes

Writes are always sent to the primary. Database commands, even read-only commands, are also always sent to the primary.

The health and state of a slave is checked every 5 seconds or when the next operation occurs after 5 seconds. It will also recheck the configuration when the driver has a problem reaching a server.

Note that a non-primary server may be behind the primary in operations, so your application must be okay with getting out-of-date data (or you must use w for all writes).

Querying by _id

Every object inserted is automatically assigned a unique _id field, which is often a useful field to use in queries.

Suppose that we wish to find the document we just inserted. Inserting adds and _id field to the document, so we can query by that:

<?php

$person = array("name" => "joe");

$people->insert($person);

// now $joe has an _id field
$joe = $people->findOne(array("_id" => $person['_id']));

?>

Unless the user has specified otherwise, the _id field is a MongoId. The most common mistake is attepting to use a string to match a MongoId. Keep in mind that these are two different datatypes, and will not match each other in the same way that the string "array()" is not the same as an empty array. For example:

<?php

$person = array("name" => "joe");

$people->insert($person);

// convert the _id to a string
$pid = $person['_id'] . "";

// FAILS - $pid is a string, not a MongoId
$joe = $people->findOne(array("_id" => $pid));

?>

Arrays

Arrays are special in a couple ways. First, there are two types that MongoDB uses: "normal" arrays and associative arrays. Associative arrays can have any mix of key types and values. "Normal" arrays are defined as arrays with ascending numeric indexes starting at 0 and increasing by one for each element. These are, typically, just your usual PHP array.

For instance, if you want to save a list of awards in a document, you could say:

<?php

$collection->save(array("awards" => array("gold", "silver", "bronze")));

?>

Queries can reach into arrays to search for elements. Suppose that we wish to find all documents with an array element of a given value. For example, documents with a "gold" award, such as:

{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "awards" : ["gold", "silver", "bronze"]}

This can be done with a simple query, ignoring the fact that "awards" is an array:

<?php

  $cursor = $collection->find(array("awards" => "gold"));

?>

Suppose we are querying for a more complex object, if each element of the array were an object itself, such as:

{
     "_id" : ObjectId("4b06c282edb87a281e09dad9"),
     "awards" :
     [
        {
            "first place" : "gold"
        },
        {
            "second place" : "silver"
        },
        {
            "third place" :  "bronze"
        }
     ]
}

Still ignoring that this is an array, we can use dot notation to query the subobject:

<?php

$cursor = $collection->find(array("awards.first place" => "gold"));

?>

Notice that it doesn't matter that there is a space in the field name (although it may be best not to use spaces, just to make things more readable).

You can also use an array to query for a number of possible values. For instance, if we were looking for documents "gold" or "copper", we could do:

<?php

$cursor = $collection->find(array("awards" => array('$in' => array("gold", "copper"))));

?>
Writes
Updates
Manual


Updates

Updates can be one of the most complicated operation available with MongoDB. They combine a query with an action, modifying documents that match the criteria. They are also extremely powerful, allowing you to change documents quickly and replace them altogether. They are done in-place (when possible) with little overhead.

Modifying vs. replacing documents

There are two types of updates you can use: modifying updates and replacing updates. Modifying updates contain $-operators and change fields in a document: they might increment counters, push new elements onto an array, or change the type of a field.

For example, a modifying update could add a new field to a document.

<?php
/** suppose documents look like:
 * {"username" : "...", "password" : "...", "email" : "..."}
 */
$coll->update(array("username" => "joe"), array('$set' => array("twitter" => "@joe4153")));

/** now the document will look like:
 * {"username" : "joe", "password" : "...", "email" : "...", "twitter" : "@joe4153"}
 */
?>

Replacing updates replace the entire matching document with a new document. They are generally not as efficient as using $-modifiers, but can be very usefully for complex operations or updates that can't be expressed in terms of $-operators.

For example, a replacing update can completely change the structure of a document.

<?php
/** suppose documents look like:
 * {"username" : "...", "password" : "...", "email" : "..."}
 */
$coll->update(array("username" => "joe"), array("userId" => 12345, "info" => array(
    "name" => "joe", "twitter" => "@joe4153", "email" => "..."), "likes" => array()));

/** now the document will look like:
 * {
 *     "userId" : 12345,
 *     "info" : {
 *         "name" : "joe",
 *         "twitter" : "@joe4153",
 *         "email" : "..."
 *     },
 *     "likes" : []
 * }
 */
?>

Updating Nested Objects

Suppose we wish to change the name of a comment's author in this document:

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "content" : "this is a blog post.",
    "comments" :
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}
In order to change an inner field, we use $set (so that all of the other fields are not removed!) with the index of comment to change:
<?php

$blog->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

?>

The Positional Operator

The positional operator $ is useful for updating objects that are in arrays. In the example above, for instance, suppose that we did not know the index of the comment that we needed to change, merely that we needed to change "John" to "Jim". We can use $ to do so.

<?php

$blog->update(
    array("comments.author" => "John"),
    array('$set' => array('comments.$.author' => "Jim")));

?>
Querying
php.ini Options
Manual


php.ini Options

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Mongo Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian
mongo.native_long | false* | PHP_INI_ALL
mongo.long_as_object | false | PHP_INI_ALL
mongo.default_host | "localhost" | PHP_INI_ALL
mongo.default_port | 27017 | PHP_INI_ALL
mongo.auto_reconnect | true | PHP_INI_SYSTEM
mongo.allow_persistent | true | PHP_INI_SYSTEM
mongo.chunk_size | 262144 | PHP_INI_SYSTEM
mongo.cmd | "$" | PHP_INI_ALL
mongo.utf8 | "1" | PHP_INI_ALL
mongo.allow_empty_keys | false | 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.

mongo.native-long int

The default behavior for this will be changed to TRUE in 2.0.0, so make sure to set this variable to the value you want (probably TRUE) so that the driver's behavior doesn't suddenly change when you upgrade.

On 64-bit platforms, the mongo.native_long setting allows for 64-bit integers to be stored in MongoDB. If it is not set, only 32-bits of the integer will be saved. The MongoDB data type that is used in this case is the BSON LONG, instead of the BSON INT that is used if this setting is turned off.

The setting also changes the way how BSON LONGs behave when they are read back from MongoDB. Without mongo.native_long enabled, the driver would convert every BSON LONG to a PHP double which can result in a loss of precision.

On 32-bit platforms, the mongo.native_log setting changes nothing for storing integers in MongoDB: the integer is stored as a BSON INT as before. However, when the setting is enabled and a BSON LONG is read from MongoDB a MongoCursorException is thrown alerting you that the data could not be read back without losing precision.

On 32-bit systems especially, it is recommended that you combine this with enabling mongo.long_as_object.

mongo.long_as_object string

Return a BSON_LONG as an instance of MongoInt64 (instead of a primitive type).

mongo.default_host string

Default hostname when nothing is passed to the constructor.

mongo.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. The database's default is 27017.

mongo.auto_reconnect bool

Whether to reconnect to the database if the connection is lost.

mongo.allow_persistent bool

If persistent connections are allowed.

mongo.chunk_size int

The number of bytes-per-chunk. Used in divvying up GridFS files. This number must be at least 100 less than 4 megabytes (max: 4194204) and it is recommended that it be less than that.

mongo.cmd string

A character to be used in place of $ in modifiers and comparisons.

As it is easy to forget to escape the "$", you can also choose your own special character to use instead of '$'. Choose a character that will not occur in your key names, e.g. ":":

mongo.cmd = ":"

Then, to do a comparison, for example:

<?php

$query = array( "i" => array( ":gt" => 20, ":lte" => 30 ) );

?>

You can also change it in your code using ini_set("mongo.cmd", ":"). Of course, you can also just use single quotes or backslash-escape the $.

mongo.utf8 int

If an exception should be thrown for non-UTF8 strings. Until version 1.0.4, the PHP driver would ignore non-UTF8 strings, even though you're not supposed to insert them. As of 1.0.4, the driver throws a MongoException. To ease the transition for applications that insert non-UTF8 strings, you can turn this option off to emulate the old, non-exception-throwning behavior. This option will be eliminated and exceptions always thrown for non-UTF8 strings starting with version 1.1.0.

mongo.allow_empty_keys int

Added in version 1.0.11.

If empty strings ("") should be allowed as key names. By default, the driver will throw an exception if you attempt to pass the empty string as a key to the database. It is extremely easy to do this inavertently by using double quotes with $-operators, so it is recommended that you leave this setting as default. However, if you need to save keys that are empty strings, you can set this option to true and the driver will allow you to pass empty strings to the database.

Updates
Security
Manual


Security

Request Injection Attacks

If you are passing $_GET parameters to your queries, make sure that they are cast to strings first. Users can insert associative arrays in GET requests, which could then become unwanted $-queries.

A fairly innocuous example: suppose you are looking up a user's information with the request http://www.example.com?username=bob. Your application does the query $collection->find(array("username" => $_GET['username'])).

Someone could subvert this by getting http://www.example.com?username[$ne]=foo, which PHP will magically turn into an associative array, turning your query into $collection->find(array("username" => array('$ne' => "foo"))), which will return all users not named "foo" (all of your users, probably).

This is a fairly easy attack to defend against: make sure $_GET's parameters are the type you expect before you send them to the database (cast them to strings, in this case).

Note that this type of attack can be used with any databases interation that locates a document, including updates, upserts, find-and-modifies, and removes.

Thanks to » Phil for pointing this out.

See » the main documentation for more information about SQL-injection-like issues with MongoDB.

Script Injection Attacks

If you are using JavaScript, make sure that any variables that cross the PHP- to-JavaScript boundry are passed in the scope field of MongoCode, not interpolated into the JavaScript string. This can come up when using MongoDB::execute(), $where clauses, MapReduces, group-bys, and any other time you may pass JavaScript into the database.

Informacja:

MapReduce ignore the scope field of MongoCode, but there is a scope option on the command that can be used instead.

For example, suppose we have some JavaScript to greet a user in the database logs. We could do:

<?php

// don't do this!

$username = $_POST['username'];
$db->execute("print('Hello, $username!');");

?>

However, what if a malicious user passes in some JavaScript?

<?php

// don't do this!

// $username is set to "'); db.users.drop(); print('"
$db->execute("print('Hello, $username!');");

?>

Now MongoDB executes the JavaScript string "print('Hello, '); db.users.drop(); print('!');". This attack is easy to avoid: use scope to pass variables from PHP to JavaScript:

<?php

$scope = array("user" => $username);
$db->execute(new MongoCode("print('Hello, '+user+'!');", $scope));

?>

This adds a variable user to the JavaScript scope. Now if someone tries to send malicious code, MongoDB will harmlessly print Hello, '); db.dropDatabase(); print('!.

Using scope helps prevent malicious input from being executed by the database. However, you must make sure that your code does not turn around and execute the input anyway! For example, never use the JavaScript eval function on user input:

<?php

// don't do this!

// $jsShellInput is "db.users.drop();"
$scope = array("input" => $jsShellInput);
$db->execute(new MongoCode("eval(input);", $scope));

?>

Always use scope and never allow the database to execute user input as code.

php.ini Options
Troubleshooting
Manual


Troubleshooting

If you're having trouble, there are lots of resources you can turn to.

  • IRC

    The official MongoDB IRC room is irc.freenode.net/#mongodb. This is the fastest way to get help... if there are people around.

  • Mailing List

    » MongoDB's mailing list is a good (and usually very fast) way to get answers to questions.

  • Bug Tracker

    Found a bug? Want a feature? Have a question? File it in the » PHP driver's bug tracker.

You can turn on (very) verbose debugging output by compiling the driver with the debugging flag.

$ ./configure CFLAGS=-DDEBUG

DEBUG turns on all debugging. You can also turn on specific debug flags. In the latest code, these flags are:

  • DEBUG_CONN

    Debugging connections.

Security
Running the Driver's Tests
Manual


Running the Driver's Tests

The PECL package does not come with the tests, but they are available at » Github. There are two types of tests: the PHPUnit tests and the C tests.

PHPUnit Tests

To run the tests, you must download the driver from Github (the tests are in the tests/ directory). You'll also need » PHPUnit to run the tests. PHPUnit can be installed via PEAR (although you should look at the installation instructions, it requires a couple of prerequisites).

Some tests expect warnings or errors, so you must set error_reporting in php.ini to E_STRICT | E_ALL for these tests to pass. If you do not, you will get some failures that say the test was expecting a warning or error.

To run the tests, make sure that there is a MongoDB server running locally on port 27017. Before reporting errors, please try running the tests against the latest development version of MongoDB: often there are tests for features that aren't yet in the stable release.

The test suite uses the "phpunit" database. If you are using a database called "phpunit" in your application, make sure point MongoDB at a different data directory before running the tests.

Make sure you're in the main directory of the driver source you downloaded from Github. Run:

$ phpunit tests/MongoSuite.php

C Tests

The C tests mostly check internal functions that are not exposed through PHP. If you'd like to run these tests, you'll need to compile PHP with the --enable-embed flag. Then switch to the tests directory and run make. This will create a binary called unit. Run unit to execute the tests. These tests do no require a database to be running.

If a test passes, it will print a ".". If a test fails, it will assert and stop the tests. Please report any asserts.

If make cannot find your PHP embedded library (libphp5.so) or header files, you may have to specify the PHP_PATH variable.

Run make clean to remove all testing objects.

If you run these tests with valgrind, you should get no invalid memory access errors and the "no leaks are possible" message at the end.

Reporting Errors

Please report any failures or errors in the » bugtracker. There may be skipped tests, these are normal and can be ignored.

New tests are always welcome! Please feel free to contribute new tests of any type testing any functionality.

Troubleshooting
Core Classes
Manual


Core Classes

Spis treści

  • Mongo
  • MongoDB
  • MongoCollection
  • MongoCursor

The core classes are the most important part of the driver.

Running the Driver's Tests
Mongo
Mongo


The Mongo class

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

Wstęp

A connection between PHP and MongoDB.

This class is used to create and manage connections. A typical use is:

<?php

$m = new Mongo(); // connect
$db = $m->foo; // get the database named "foo"

?>

See Mongo::__construct() and the section on connecting for more information about creating connections.

Krótki opis klasy

Mongo {
/* Stałe */
const string VERSION ;
const string DEFAULT_HOST = "localhost" ;
const int DEFAULT_PORT = 27017 ;
/* Fields */
public boolean $connected = FALSE ;
public string $status = NULL ;
protected string $server = NULL ;
protected boolean $persistent = NULL ;
/* Metody */
public bool close ( void )
public bool connect ( void )
protected bool connectUtil ( void )
public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] )
public array dropDB ( mixed $db )
public MongoDB __get ( string $dbname )
public array getHosts ( void )
public static int getPoolSize ( void )
public string getSlave ( void )
public bool getSlaveOkay ( void )
public array listDBs ( void )
public array poolDebug ( void )
public MongoCollection selectCollection ( string $db , string $collection )
public MongoDB selectDB ( string $name )
public static bool setPoolSize ( int $size )
public bool setSlaveOkay ([ bool $ok = true ] )
public string switchSlave ( void )
public string __toString ( void )
}

Stałe predefiniowane

Mongo Constants

Mongo::VERSION
PHP driver version. May be suffixed with "+" or "-" if it is in-between versions.
Mongo::DEFAULT_HOST
"localhost"
Host to connect to if no host is given.
Mongo::DEFAULT_PORT
27017
Port to connect to if no port is given.

Fields

status
If this is a persistent connection, if the connection was created for this object or is being reused. If this is not a persistent connection, this field should be NULL.

Zobacz też:

MongoDB core docs on » connecting.

Spis treści

  • Mongo::close — Closes this connection
  • Mongo::connect — Connects to a database server
  • Mongo::connectUtil — Connects with a database server
  • Mongo::__construct — Creates a new database connection object
  • Mongo::dropDB — Drops a database [deprecated]
  • Mongo::__get — Gets a database
  • Mongo::getHosts — Updates status for all hosts associated with this
  • Mongo::getPoolSize — Get pool size for connection pools
  • Mongo::getSlave — Returns the address being used by this for slaveOkay reads
  • Mongo::getSlaveOkay — Get slaveOkay setting for this connection
  • Mongo::listDBs — Lists all of the databases available.
  • Mongo::poolDebug — Returns information about all connection pools.
  • Mongo::selectCollection — Gets a database collection
  • Mongo::selectDB — Gets a database
  • Mongo::setPoolSize — Set the size for future connection pools.
  • Mongo::setSlaveOkay — Change slaveOkay setting for this connection
  • Mongo::switchSlave — Choose a new slave for slaveOkay reads
  • Mongo::__toString — String representation of this connection
Core Classes
Mongo::close
Core Classes


Closes this connection

Mongo
Mongo::connect
Mongo
PHP Manual

Mongo::close

(PECL mongo >=0.9.0)

Mongo::close — Closes this connection

Opis

public bool Mongo::close ( void )

This method does not need to be called, except in unusual circumstances. The driver will cleanly close the database connection when this Mongo instance goes out of scope.

If objects do not go out of scope between requests, you may wish to call this method at the end of your program to keep old connections from hanging around. However, it is probably more efficient use a persistent connection, which will automatically create a connection if needed and use it for as many requests as possible.

If you are connected to a replica set, close() will only close the connection to the primary.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns if the connection was successfully closed.

Mongo
Mongo::connect
Mongo


Connects to a database server

Mongo::close
Mongo::connectUtil
Mongo
PHP Manual

Mongo::connect

(PECL mongo >=0.9.0)

Mongo::connect — Connects to a database server

Opis

public bool Mongo::connect ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

If the connection was successful.

Błędy/Wyjątki

Throws MongoConnectionException if it fails to connect to the database.

Mongo::close
Mongo::connectUtil
Mongo


Connects with a database server

Mongo::connect
Mongo::__construct
Mongo
PHP Manual

Mongo::connectUtil

(PECL mongo >=0.9.0)

Mongo::connectUtil — Connects with a database server

Opis

protected bool Mongo::connectUtil ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

If the connection was successful.

Błędy/Wyjątki

Throws MongoConnectionException if it fails to connect to the databases.

Mongo::connect
Mongo::__construct
Mongo


Creates a new database connection object

Mongo::connectUtil
Mongo::dropDB
Mongo
PHP Manual

Mongo::__construct

(PECL mongo >=0.9.0)

Mongo::__construct — Creates a new database connection object

Opis

 public  Mongo::__construct
  ([ string $server = "mongodb://localhost:27017"
 [, array $options = array("connect" => TRUE)
]] )

If no parameters are passed, this connects to "localhost:27017" (or whatever was specified in php.ini for mongo.default_host and mongo.default_port).

server should have the form:

mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db

The connection string always starts with mongodb://, to indicate it is a connection string in this form.

If username and password are specified, the constructor will attempt to authenticate the connection with the database before returning. Username and password are optional and must be followed by an @, if specified.

At least one host must be given (port optional, always defaulting to 27017) and as many hosts as desired may be connected to. Host names are comma-separated and the constructor will return successfully if it connected to at least one host. If it could not connect to any of the hosts, it will throw a MongoConnectionException.

Finally, if you specified a username and password, you may specify a database to authenticate with. If db is not specified, "admin" will be used.

Parametry

server

The server name.

options

An array of options for the connection. Currently available options include:

  • "connect"

    If the constructor should connect before returning. Default is TRUE.

  • "timeout"

    For how long the driver should try to connect to the database (in milliseconds).

  • "replicaSet"

    The name of the replica set to connect to. If this is given, the master will be determined by using the ismaster database command on the seeds, so the driver may end up connecting to a server that was not even listed. See the replica set example below for details.

  • "username"

    The username can be specified here, instead of including it in the host list. This is especially useful if a username has a ":" in it. This overrides a username set in the host list.

  • "password"

    The password can be specified here, instead of including it in the host list. This is especially useful if a password has a "@" in it. This overrides a password set in the host list.

  • "db"

    The database to authenticate against can be specified here, instead of including it in the host list. This overrides a database given in the host list.

Zwracane wartości

Returns a new database connection object.

Błędy/Wyjątki

Throws MongoConnectionException if it tries and fails to connect to the database for all hostnames given. It will also throw a MongoConnnectionException if an invalid username or password is given. See MongoConnectionException documentation for common exceptions and their causes.

Rejestr zmian

Wersja | Opis
1.2.0

Removed the persist option, as all connections are now persistent. It can still be used, but it doesn't affect anything.

"persist"

If the connection should be persistent. If set, the connection will be persistent. The string representation of the value is used as an id for the connection, so two instances of Mongo that are initialized with array("persist" => "foobar") will share the same database connection, whereas an instance initialized with array("persist" => "barbaz") will use a different database connection.

The "replicaSet" parameter now takes a string, not a boolean (although boolean is still accepted).

1.0.2 Changed constructor to take an array of options. Pre-1.0.2, the constructor took the following parameters:
server

The server name.

connect

Optional boolean parameter specifying if the constructor should connect to the database before returning. Defaults to TRUE.

persistent

If the connection should be persistent.

paired

If the connection should be paired.

1.0.9 | Added the replicaSet option.
1.2.0 | Added the username and password options.

Przykłady

Przykład #1 Mongo::__construct() replica set example

This example shows how to connect the driver to a replica set. It assumes that there is a set of three servers: sf1.example.com, sf2.example.com, and ny1.example.com. The master could be any one of these servers.

<?php

// pass a comma-separated list of server names to the constructor
$m1 = new Mongo("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));

// you only need to pass a single seed, the driver will derive the full list and
// find the master from this seed
$m2 = new Mongo("mongodb://ny1.example.com", array("replicaSet" => "myReplSet"));

?>

If the current master fails, the driver will figure out which secondary server became the new master and automatically start using that connection. Automatic failover will not work correctly if replicaSet is not specified.

At least one seed in the seed list must be up for the driver to connect to the replica set.

If you include seeds from two separate replica sets, behavior is undefined.

See the » core documentation on replica sets for more information.

Przykład #2 Connecting to a domain socket

In version 1.0.9+, you can use a UNIX domain socket to connect to an instance of MongoDB running locally. This should be slightly faster than using a network connection.

In version 1.5.0, the MongoDB server automatically opens a socket at /tmp/mongodb-<port>.sock. You can connect to this by specifying the path in your connection string:

<?php

// MongoDB server running locally on port 20000
$m = new Mongo("mongodb:///tmp/mongodb-20000.sock");

?>

You can combine this with any other connections you'd like:

<?php

// try to connect to the domain socket, fall back to localhost connection
$m = new MongoDB("mongodb:///tmp/mongodb-27017.sock,localhost:27017");

?>

Przykład #3 Mongo::__construct() authentication example

A user must exist in the admin database before attempting to use authentication. You can create one with the Mongo shell by running:

> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
        "_id" : ObjectId("4b21272fd9ab21611d19095c"),
        "user" : "testUser",
        "pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>

After creating a user with, in this case, username "testUser" and password "testPass", you can create an authenticated connection:

<?php

$m = new Mongo("mongodb://testUser:testPass@localhost");

?>
Mongo::connectUtil
Mongo::dropDB
Mongo


Drops a database [deprecated]

Mongo::__construct
Mongo::__get
Mongo
PHP Manual

Mongo::dropDB

(PECL mongo >=0.9.0)

Mongo::dropDB — Drops a database [deprecated]

Opis

public array Mongo::dropDB ( mixed $db )
Ostrzeżenie

Deprecated

Use MongoDB::drop() instead.

Parametry

db

The database to drop. Can be a MongoDB object or the name of the database.

Zwracane wartości

Returns the database response.

Mongo::__construct
Mongo::__get
Mongo


Gets a database

Mongo::dropDB
Mongo::getHosts
Mongo
PHP Manual

Mongo::__get

(PECL mongo >=1.0.2)

Mongo::__get — Gets a database

Opis

public MongoDB Mongo::__get ( string $dbname )

This is the cleanest way of getting a database. If the database name has any special characters, Mongo::selectDB() will need to be used. However, in most cases, this should be sufficient.

<?php

$mongo = new Mongo();

// the following two lines are equivalent
$db = $mongo->selectDB("foo");
$db = $mongo->foo;

?>

Parametry

dbname

The database name.

Zwracane wartości

Returns a new db object.

Błędy/Wyjątki

Throws a generic exception if the database name is invalid.

Mongo::dropDB
Mongo::getHosts
Mongo


Updates status for all hosts associated with this

Mongo::__get
Mongo::getPoolSize
Mongo
PHP Manual

Mongo::getHosts

(PECL mongo >=1.1.0)

Mongo::getHosts — Updates status for all hosts associated with this

Opis

public array Mongo::getHosts ( void )

This method can only be used with a connection to a replica set. It returns the status of all of the hosts in the set.

See the query section of this manual for information on distributing reads to slaves.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array of information about the hosts in the set. Includes each host's hostname, its health (1 is healthy), its state (1 is primary, 2 is secondary, 0 is anything else), the amount of time it took to ping the server, and when the last ping occurred. For example, on a three-member replica set, it might look something like:

array(2) {
  ["A:27017"]=>
  array(4) {
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(369)
    ["lastPing"]=>
    int(1309470644)
  }
  ["B:27017"]=>
  array(4) {
    ["health"]=>
    int(1)
    ["state"]=>
    int(1)
    ["ping"]=>
    int(139)
    ["lastPing"]=>
    int(1309470644)
  }
  ["C:27017"]=>
  array(4) {
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(1012)
    ["lastPing"]=>
    int(1309470644)
  }
}

In the example above, B and C are secondaries (state 2). B is likely to be selected for queries if slaveOkay is set, as it has a lower ping time (and thus is likely closer or handling less load) than C.

Mongo::__get
Mongo::getPoolSize
Mongo


Get pool size for connection pools

Mongo::getHosts
Mongo::getSlave
Mongo
PHP Manual

Mongo::getPoolSize

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

Mongo::getPoolSize — Get pool size for connection pools

Opis

public static int Mongo::getPoolSize ( void )
Ostrzeżenie

This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::getSize() instead.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current pool size.

Przykłady

Przykład #1 Changing pool size

This returns the default pool size, sets a new pool size, then prints the new pool size and the pool debugging information. Note that changing the pool size only affects new connection pools, it does not change old ones.

<?php

$connection = new Mongo("host1");

// pool size is -1
echo "pool size is: ".Mongo::getPoolSize()."\n";

echo "setting pool size to 200\n";

Mongo::setPoolSize(200);

// pool size is 200
echo "pool size is: ".Mongo::getPoolSize()."\n";

$conn2 = new Mongo("host2");

// remaining for host1 is -2
// remaining for host2 is 199
var_dump(Mongo::poolDebug());

?>

Zobacz też:

  • Mongo::setPoolSize() - Set the size for future connection pools.
  • Mongo::poolDebug() - Returns information about all connection pools.
  • The connection documentation.

Mongo::getHosts
Mongo::getSlave
Mongo


Returns the address being used by this for slaveOkay reads

Mongo::getPoolSize
Mongo::getSlaveOkay
Mongo
PHP Manual

Mongo::getSlave

(PECL mongo >=1.1.0)

Mongo::getSlave — Returns the address being used by this for slaveOkay reads

Opis

public string Mongo::getSlave ( void )

This finds the address of the slave currently being used for reads. It is a read-only method: it does not change anything about the internal state of the object.

When you create a connection to the database, the driver will not immediately decide on a slave to use. Thus, after you connect, this function will return NULL even if there are slaves available. When you first do a query with slaveOkay set, at that point the driver will choose a slave for this connection. At that point, this function will return the chosen slave.

See the query section of this manual for information on distributing reads to slaves.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The address of the slave this connection is using for reads.

This returns NULL if this is not connected to a replica set or not yet initialized.

Mongo::getPoolSize
Mongo::getSlaveOkay
Mongo


Get slaveOkay setting for this connection

Mongo::getSlave
Mongo::listDBs
Mongo
PHP Manual

Mongo::getSlaveOkay

(PECL mongo >=1.1.0)

Mongo::getSlaveOkay — Get slaveOkay setting for this connection

Opis

public bool Mongo::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to slaves.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the value of slaveOkay for this instance.

Mongo::getSlave
Mongo::listDBs
Mongo


Lists all of the databases available.

Mongo::getSlaveOkay
Mongo::poolDebug
Mongo
PHP Manual

Mongo::listDBs

(PECL mongo >=1.0.4)

Mongo::listDBs — Lists all of the databases available.

Opis

public array Mongo::listDBs ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an associative array containing three fields. The first field is databases, which in turn contains an array. Each element of the array is an associative array corresponding to a database, giving the database's name, size, and if it's empty. The other two fields are totalSize (in bytes) and ok, which is 1 if this method ran successfully.

Przykłady

Przykład #1 Mongo::listDBs() example

Example demonstrating how to use listDBs and the returned data structure.

<?php

$mongo = new Mongo();
$dbs = $mongo->listDBs();
print_r($dbs);

?>

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

Array
(
    [databases] => Array
        (
            [0] => Array
                (
                    [name] => doctrine
                    [sizeOnDisk] => 218103808
                    [empty] =>
                )
        )

    [totalSize] => 218103808
    [ok] => 1
)
Mongo::getSlaveOkay
Mongo::poolDebug
Mongo


Returns information about all connection pools.

Mongo::listDBs
Mongo::selectCollection
Mongo
PHP Manual

Mongo::poolDebug

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

Mongo::poolDebug — Returns information about all connection pools.

Opis

public array Mongo::poolDebug ( void )
Ostrzeżenie

This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::info() instead.

Returns an array of information about all connection pools.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Each connection pool has an identifier, which starts with the host. For each pool, this function shows the following fields:

in use

The number of connections currently being used by Mongo instances.

in pool

The number of connections currently in the pool (not being used).

remaining

The number of connections that could be created by this pool. For example, suppose a pool had 5 connections remaining and 3 connections in the pool. We could create 8 new instances of Mongo before we exhausted this pool (assuming no instances of Mongo went out of scope, returning their connections to the pool).

A negative number means that this pool will spawn unlimited connections.

Before a pool is created, you can change the max number of connections by calling Mongo::setPoolSize(). Once a pool is showing up in the output of this function, its size cannot be changed.

timeout

The socket timeout for connections in this pool. This is how long connections in this pool will attempt to connect to a server before giving up.

Mongo::listDBs
Mongo::selectCollection
Mongo


Gets a database collection

Mongo::poolDebug
Mongo::selectDB
Mongo
PHP Manual

Mongo::selectCollection

(PECL mongo >=0.9.0)

Mongo::selectCollection — Gets a database collection

Opis

public MongoCollection Mongo::selectCollection ( string $db , string $collection )

Parametry

db

The database name.

collection

The collection name.

Zwracane wartości

Returns a new collection object.

Błędy/Wyjątki

Throws InvalidArgumentException if the database or collection name is invalid.

Przykłady

Przykład #1 Mongo::selectCollection() example

<?php
$m = new Mongo();

$c1 = $m->selectCollection("foo", "bar.baz");
// which is equivalent to
$c2 = $m->selectDB("foo")->selectCollection("bar.baz");

// $c1 and $c2 now represent the same collection
?>
Mongo::poolDebug
Mongo::selectDB
Mongo


Gets a database

Mongo::selectCollection
Mongo::setPoolSize
Mongo
PHP Manual

Mongo::selectDB

(PECL mongo >=0.9.0)

Mongo::selectDB — Gets a database

Opis

public MongoDB Mongo::selectDB ( string $name )

Parametry

name

The database name.

Zwracane wartości

Returns a new db object.

Błędy/Wyjątki

Throws InvalidArgumentException if the database name is invalid.

Mongo::selectCollection
Mongo::setPoolSize
Mongo


Set the size for future connection pools.

Mongo::selectDB
Mongo::setSlaveOkay
Mongo
PHP Manual

Mongo::setPoolSize

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

Mongo::setPoolSize — Set the size for future connection pools.

Opis

public static bool Mongo::setPoolSize ( int $size )
Ostrzeżenie

This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::setSize() instead.

Sets the max number of connections new pools will be able to create.

Parametry

size

The max number of connections future pools will be able to create. Negative numbers mean that the pool will spawn an infinite number of connections.

Zwracane wartości

Returns the former value of pool size.

Przykłady

Przykład #1 Mongo::setPoolSize() example

If you set the pool size to n and then create n connections, attempting to create an n+1st connection will throw a MongoConnectionException.

<?php

// only allow one connection to a server
Mongo::setPoolSize(1);

// creates one connection to localhost:27017
$m1 = new Mongo();

// attempt to create a second connection to localhost:27017
// only one connection is allowed, so this will throw an exception
$m2 = new Mongo();

?>

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

Fatal error: Uncaught exception 'MongoConnectionException' with message 'no more connections in pool' in /path/to/php/script.php:10
Stack trace:
#0 /path/to/php/script.php(10): Mongo->__construct()
#1 {main}
  thrown in /path/to/php/script.php on line 10

Zobacz też:

  • Mongo::getPoolSize() - Get pool size for connection pools
  • Mongo::poolDebug() - Returns information about all connection pools.
  • The connection documentation.

Mongo::selectDB
Mongo::setSlaveOkay
Mongo


Change slaveOkay setting for this connection

Mongo::setPoolSize
Mongo::switchSlave
Mongo
PHP Manual

Mongo::setSlaveOkay

(PECL mongo >=1.1.0)

Mongo::setSlaveOkay — Change slaveOkay setting for this connection

Opis

public bool Mongo::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to slaves.

Parametry

ok

If reads should be sent to secondary members of a replica set for all possible queries using this Mongo instance.

Zwracane wartości

Returns the former value of slaveOkay for this instance.

Mongo::setPoolSize
Mongo::switchSlave
Mongo


Choose a new slave for slaveOkay reads

Mongo::setSlaveOkay
Mongo::__toString
Mongo
PHP Manual

Mongo::switchSlave

(PECL mongo >=1.1.0)

Mongo::switchSlave — Choose a new slave for slaveOkay reads

Opis

public string Mongo::switchSlave ( void )

This choses a random slave for a connection to read from. It is called automatically by the driver and should not need to be used. It calls Mongo::getHosts() (to refresh the status of hosts) and Mongo::getSlave() (to get the return value).

See the query section of this manual for information on distributing reads to slaves.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The address of the slave this connection is using for reads. This may be the same as the previous address as addresses are randomly chosen. It may return only one address if only one secondary (or only the primary) is available.

For example, if we had a three member replica set with a primary, secondary, and arbiter this method would always return the address of the secondary. If the secondary became unavailable, this method would always return the address of the primary. If the primary also became unavailable, this method would throw an exception, as an arbiter cannot handle reads.

Błędy/Wyjątki

Throws a MongoException (error code 15) if it is called on a non-replica-set connection. It will also throw MongoExceptions if it cannot find anyone (primary or secondary) to read from (error code 16).

Mongo::setSlaveOkay
Mongo::__toString
Mongo


String representation of this connection

Mongo::switchSlave
MongoDB
Mongo
PHP Manual

Mongo::__toString

(PECL mongo >=0.9.0)

Mongo::__toString — String representation of this connection

Opis

public string Mongo::__toString ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns hostname and port for this connection.

Mongo::switchSlave
MongoDB
Mongo


The MongoDB class

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

Wstęp

Instances of this class are used to interact with a database. To get a database:

<?php

$m = new Mongo(); // connect
$db = $m->selectDB("example");

?>
Database names can use almost any character in the ASCII range. However, they cannot contain " ", "." or be the empty string. The name "system" is also reserved.

A few unusual, but valid, database names: "null", "[x,y]", "3", "\"", "/".

Unlike collection names, database names may contain "$".

Krótki opis klasy

MongoDB {
/* Stałe */
const int PROFILING_OFF = 0 ;
const int PROFILING_SLOW = 1 ;
const int PROFILING_ON = 2 ;
/* Fields */
public integer $w = 1 ;
public integer $wtimeout = 10000 ;
/* Metody */
public array authenticate ( string $username , string $password )
public array command ( array $command [, array $options = array() ] )
public __construct ( Mongo $conn , string $name )
public MongoCollection createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )
public array createDBRef ( string $collection , mixed $a )
public array drop ( void )
public array dropCollection ( mixed $coll )
public array execute ( mixed $code [, array $args = array() ] )
public bool forceError ( void )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
public int getProfilingLevel ( void )
public bool getSlaveOkay ( void )
public array lastError ( void )
public array listCollections ( void )
public array prevError ( void )
public array repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] )
public array resetError ( void )
public MongoCollection selectCollection ( string $name )
public int setProfilingLevel ( int $level )
public bool setSlaveOkay ([ bool $ok = true ] )
public string __toString ( void )
}

Stałe predefiniowane

MongoDB Log Levels

MongoDB::PROFILING_OFF
0
Profiling is off.
MongoDB::PROFILING_SLOW
1
Profiling is on for slow operations (>100 ms).
MongoDB::PROFILING_ON
2
Profiling is on for all operations.

Fields

w
1

The number of servers to replicate a change to before returning success. Inherited by instances of MongoCollection derived from this. w functionality is only available in version 1.5.1+ of the MongoDB server and 1.0.8+ of the driver.

w is used whenever you perform a "safe" operation (MongoCollection::insert(), MongoCollection::update(), MongoCollection::remove(), MongoCollection::save(), and MongoCollection::ensureIndex() all support safe options). With the default value (1), a safe operation will return once the database server has the operation. If the server goes down before the operation has been replicated to a slave, it is possible to lose the operation forever. Thus, you can specify w to be higher than one and guarantee that at least one slave has the operation before it is considered successful.

For example, if w is 2, the main server and one slave must have a record of the operation or the driver will throw a MongoCursorException. It is tempting to set w to the total number of slaves + master, but then if one slave is down the op will fail and an exception will be thrown, so usually w=2 is safest (master+1 slave).

wtimeout
10000

The number of milliseconds to wait for MongoDB::$w replications to take place. Inherited by instances of MongoCollection derived from this. w functionality is only available in version 1.5.1+ of the MongoDB server and 1.0.8+ of the driver.

Unless wtimeout is set, the server waits forever for replicating to w servers to finish. The driver defaults to waiting for 10 seconds, you can change this value to alter its behavior.

Zobacz też:

MongoDB core docs on » databases.

Spis treści

  • MongoDB::authenticate — Log in to this database
  • MongoDB::command — Execute a database command
  • MongoDB::__construct — Creates a new database
  • MongoDB::createCollection — Creates a collection
  • MongoDB::createDBRef — Creates a database reference
  • MongoDB::drop — Drops this database
  • MongoDB::dropCollection — Drops a collection [deprecated]
  • MongoDB::execute — Runs JavaScript code on the database server.
  • MongoDB::forceError — Creates a database error
  • MongoDB::__get — Gets a collection
  • MongoDB::getDBRef — Fetches the document pointed to by a database reference
  • MongoDB::getGridFS — Fetches toolkit for dealing with files stored in this database
  • MongoDB::getProfilingLevel — Gets this database's profiling level
  • MongoDB::getSlaveOkay — Get slaveOkay setting for this database
  • MongoDB::lastError — Check if there was an error on the most recent db operation performed
  • MongoDB::listCollections — Get a list of collections in this database
  • MongoDB::prevError — Checks for the last error thrown during a database operation
  • MongoDB::repair — Repairs and compacts this database
  • MongoDB::resetError — Clears any flagged errors on the database
  • MongoDB::selectCollection — Gets a collection
  • MongoDB::setProfilingLevel — Sets this database's profiling level
  • MongoDB::setSlaveOkay — Change slaveOkay setting for this database
  • MongoDB::__toString — The name of this database
Mongo::__toString
MongoDB::authenticate
Core Classes


Log in to this database

MongoDB
MongoDB::command
MongoDB
PHP Manual

MongoDB::authenticate

(PECL mongo >=1.0.1)

MongoDB::authenticate — Log in to this database

Opis

public array MongoDB::authenticate ( string $username , string $password )

This method causes its connection to be authenticated. If authentication is enabled for the database server (it's not, by default), you need to log in before the database will allow you to do anything.

In general, you should use the authenticate built into Mongo::__construct() in preference to this method. If you authenticate on connection and the connection drops and reconnects during your session, you'll be reauthenticated. If you manually authenticated using this method and the connection drops, you'll have to call this method again once you're reconnected.

This method is identical to running:

<?php

$salted = "${username}:mongo:${password}";
$hash = md5($salted);

$nonce = $db->command(array("getnonce" => 1));

$saltedHash = md5($nonce["nonce"]."${username}${hash}");

$result = $db->command(array("authenticate" => 1,
    "user" => $username,
    "nonce" => $nonce["nonce"],
    "key" => $saltedHash
));

?>

Once a connection has been authenticated, it can only be un-authenticated by using the "logout" database command:

<?php

$db->command(array("logout" => 1));

?>

Parametry

username

The username.

password

The password (in plaintext).

Zwracane wartości

Returns database response. If the login was successful, it will return

<?php
array("ok" => 1);
?>
If something went wrong, it will return
<?php
array("ok" => 0, "errmsg" => "auth fails");
?>
("auth fails" could be another message, depending on database version and what when wrong).

Zobacz też:

MongoDB core docs on » authenticate.

MongoDB
MongoDB::command
MongoDB


Execute a database command

MongoDB::authenticate
MongoDB::__construct
MongoDB
PHP Manual

MongoDB::command

(PECL mongo >=0.9.2)

MongoDB::command — Execute a database command

Opis

public array MongoDB::command ( array $command [, array $options = array() ] )

Almost everything that is not a CRUD operation can be done with a database command. Need to know the database version? There's a command for that. Need to do aggregation? There's a command for that. Need to turn up logging? You get the idea.

This method is identical to:

<?php

public function command($data) {
    return $this->selectCollection('$cmd')->findOne($data);
}

?>

Parametry

command

The query to send.

options

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "timeout"

    Integer, defaults to Mongo::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Rejestr zmian

Wersja | Opis
1.2.0 | Added options parameter with a single option: timeout.

Zwracane wartości

Returns database response.

Przykłady

Przykład #1 MongoDB::command() "distinct" example

Finding all of the distinct values for a key.

<?php

$people = $db->people;

$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));

$ages = $db->command(array("distinct" => "people", "key" => "age"));

foreach ($ages['values'] as $age) {
    echo "$age\n";
}

?>

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

4
22
87

Przykład #2 MongoDB::command() "distinct" example

Finding all of the distinct values for a key, where the value is larger than or equal to 18.

<?php

$people = $db->people;

$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));

$ages = $db->command(
    array(
        "distinct" => "people",
        "key" => "age",
        "query" => array("age" => array('$gte' => 18))
    )
);

foreach ($ages['values'] as $age) {
    echo "$age\n";
}

?>

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

22
87

Przykład #3 MongoDB::command() MapReduce example

Get all users with at least on "sale" event, and how many times each of these users has had a sale.

<?php

// sample event document
$events->insert(array("user_id" => $id,
    "type" => $type,
    "time" => new MongoDate(),
    "desc" => $description));

// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
    "var sum = 0;".
    "for (var i in vals) {".
        "sum += vals[i];".
    "}".
    "return sum; }");

$sales = $db->command(array(
    "mapreduce" => "events",
    "map" => $map,
    "reduce" => $reduce,
    "query" => array("type" => "sale"),
    "out" => array("merge" => "eventCounts")));

$users = $db->selectCollection($sales['result'])->find();

foreach ($users as $user) {
    echo "{$user['_id']} had {$user['value']} sale(s).\n";
}

?>

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

User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).

Informacja: Using MongoCode

This example uses MongoCode, which can also take a scope argument. However, at the moment, MongoDB does not support using scopes in MapReduce. If you would like to use client-side variables in the MapReduce functions, you can add them to the global scope by using the optional scope field with the database command. See the » MapReduce documentation for more information.

Informacja: The out argument

Before 1.8.0, the out argument was optional. If you did not use it, MapReduce results would be written to a temporary collection, which would be deleted when your connection was closed. In 1.8.0+, the out argument is required. See the » MapReduce documentation for more information.

If you are going to be using MapReduce, Prajwal Tuladhar created an API for Mongo PHP users which provides a nicer interface than the bare command. You can download it from » Github and there is a » blog post on how to use it.

Zobacz też:

MongoDB core docs on » database commands and on individual commands: » findAndModify, » getLastError, and » repair (dozens more exist, there are merely a few examples).

MongoDB::authenticate
MongoDB::__construct
MongoDB


Creates a new database

MongoDB::command
MongoDB::createCollection
MongoDB
PHP Manual

MongoDB::__construct

(PECL mongo >=0.9.0)

MongoDB::__construct — Creates a new database

Opis

public MongoDB::__construct ( Mongo $conn , string $name )

This method is not meant to be called directly. The preferred way to create an instance of MongoDB is through Mongo::__get() or Mongo::selectDB().

If you're ignoring the previous paragraph and want to call it directly you can do so:

<?php

$m = new Mongo();
$db = new MongoDB($m, 'mydbname');

?>

But don't. Isn't this much nicer:

<?php

$m = new Mongo();
$db = $m->mydbname;

// or, if the name contains weird characters:

$db = $m->selectDB('my,db:name');

?>

Parametry

Mongo conn

Database connection.

name

Database name.

Zwracane wartości

Returns the database.

Błędy/Wyjątki

Throws default exception if the database name is invalid.

MongoDB::command
MongoDB::createCollection
MongoDB


Creates a collection

MongoDB::__construct
MongoDB::createDBRef
MongoDB
PHP Manual

MongoDB::createCollection

(PECL mongo >=0.9.0)

MongoDB::createCollection — Creates a collection

Opis

public MongoCollection MongoDB::createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] )

This method is used to create capped collections and other collections requiring special options. It is identical to running:

<?php

$collection = $db->command(array("create" => $name, "size" => $size, "capped" => $capped, "max" => $max));

?>
See MongoDB::command() for more information about database commands.

Parametry

name

The name of the collection.

capped

If the collection should be a fixed size.

size

If the collection is fixed size, its size in bytes.

max

If the collection is fixed size, the maximum number of elements to store in the collection.

Zwracane wartości

Returns a collection object representing the new collection.

Przykłady

Przykład #1 MongoDB::createCollection() capped collection example

A capped collection is a special type of collection that has either a fixed or a fixed number of elements. Once the collection is "full," the oldest elements will be removed when new elements are added. Capped collections can be very useful for applications like logging, where you may want to reserve a certain amount of space for logs and not worry about them getting too big.

This example creates a very tiny log collection that will keep a maximum of 10 documents.

<?php

$log = $db->createCollection("logger", true, 10*1024, 10);

for ($i = 0; $i < 100; $i++) {
    $log->insert(array("level" => WARN, "msg" => "sample log message #$i", "ts" => new MongoDate()));
}

$msgs = $log->find();

foreach ($msgs as $msg) {
    echo $msg['msg']."\n";
}

?>

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

sample log message #90
sample log message #91
sample log message #92
sample log message #93
sample log message #94
sample log message #95
sample log message #96
sample log message #97
sample log message #98
sample log message #99
MongoDB::__construct
MongoDB::createDBRef
MongoDB


Creates a database reference

MongoDB::createCollection
MongoDB::drop
MongoDB
PHP Manual

MongoDB::createDBRef

(PECL mongo >=0.9.0)

MongoDB::createDBRef — Creates a database reference

Opis

public array MongoDB::createDBRef ( string $collection , mixed $a )

This method is a flexible interface for creating database refrences (see MongoDBRef).

Parametry

collection

The collection to which the database reference will point.

a

Object or _id to which to create a reference. If an object or associative array is given, this will create a reference using the _id field.

Zwracane wartości

Returns a database reference array.

Przykłady

Przykład #1 MongoDB::createDBRef() example

Example demonstrating how to programatically create a DB reference array from a document.

<?php

$articles = $db->articles;

$article = array(
 'title' => 'Test article',
 'description' => 'Test article description'
);

$articles->insert($article);
$ref = $db->createDBRef('articles', $article);

print_r($article);
print_r($ref);
?>

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

     Array
     (
         [title] => Test article
         [description] => Test article description
         [_id] => MongoId Object
             (
             )

     )
     Array
     (
         [$ref] => articles
         [$id] => MongoId Object
             (
             )

     )

Now the $ref can be stored on another document and retrieved later with MongoDB::getDBRef() or MongoCollection::getDBRef().

Przykład #2 MongoDB::createDBRef() example

Example demonstrating how to programatically create a DB reference from just an id.

<?php

$id = new MongoId('47cc67093475061e3d9536d2');
$ref = $db->createDBRef('articles', $id);
?>
MongoDB::createCollection
MongoDB::drop
MongoDB


Drops this database

MongoDB::createDBRef
MongoDB::dropCollection
MongoDB
PHP Manual

MongoDB::drop

(PECL mongo >=0.9.0)

MongoDB::drop — Drops this database

Opis

public array MongoDB::drop ( void )

This drops the database currently being used.

This is identical to running:

<?php

public function drop() {
    $this->command(array("dropDatabase" => 1));
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the database response.

Przykłady

Przykład #1 MongoDB::drop() example

This example demonstrates how to drop a mongo database and the response to expect.

<?php

$db = $mongo->foo;
$response = $db->drop();
print_r($response);

?>

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

Array
(
    [dropped] => foo.$cmd
    [ok] => 1
)
MongoDB::createDBRef
MongoDB::dropCollection
MongoDB


Drops a collection [deprecated]

MongoDB::drop
MongoDB::execute
MongoDB
PHP Manual

MongoDB::dropCollection

(PECL mongo >=0.9.0)

MongoDB::dropCollection — Drops a collection [deprecated]

Opis

public array MongoDB::dropCollection ( mixed $coll )
Ostrzeżenie

Deprecated

Use MongoCollection::drop() instead.

This function leaks memory in version 1.0.7 and earlier!

Parametry

coll

MongoCollection or name of collection to drop.

Zwracane wartości

Returns the database response.

MongoDB::drop
MongoDB::execute
MongoDB


Runs JavaScript code on the database server.

MongoDB::dropCollection
MongoDB::forceError
MongoDB
PHP Manual

MongoDB::execute

(PECL mongo >=0.9.3)

MongoDB::execute — Runs JavaScript code on the database server.

Opis

public array MongoDB::execute ( mixed $code [, array $args = array() ] )

The Mongo database server runs a JavaScript engine. This method allows you to run arbitary JavaScript on the database. This can be useful if you want touch a number of collections lightly, or process some results on the database side to reduce the amount that has to be sent to the client.

Running JavaScript in the database takes a write lock, meaning it blocks other operations. Make sure you consider this before running a long script.

This is a wrapper for a database command. This method is basically:

<?php

public function execute($code, $args) {
    return $this->command(array('$eval' => $code, args => $args));
}

?>

MongoDB implies a return statement if you have a single statement on a single line. This can cause some unintuitive behavior. For example, this returns "foo":

<?php

$db->execute('"foo";');

?>

However, these return NULL:

<?php

$db->execute('"bar"; "foo";'); // more than one statement

$db->execute('db.foo.count(
);'); // more than one line

?>

To avoid surprising behavior, it is best not to depend on MongoDB to decide what to return, but to explicitly state a return value. In the examples above, we can change them to:

<?php

$db->execute('"bar"; return "foo";');

$db->execute('return db.foo.count(
);');

?>

Now the first statement will return "foo" and the second statement will return a count of the "foo" collection.

Parametry

code

MongoCode or string to execute.

args

Arguments to be passed to code.

Zwracane wartości

Returns the result of the evaluation.

Przykłady

Przykład #1 Simple MongoDB::execute() example

<?php

$response = $db->execute("function() { return 'Hello, world!'; }");
echo $response['retval'];

?>

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

Hello, world!

Przykład #2 Parameter MongoDB::execute() example

The optional array of parameters will be passed to the JavaScript function.

<?php

$response = $db->execute("function(greeting, name) { return greeting+', '+name+'!'; }", array("Good bye", "Joe"));
echo $response['retval'];

?>

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

Good bye, Joe!

Przykład #3 Scope example

If a MongoCode object is used instead of a string for the first parameter, a scope can be passed in which the JavaScript will be executed.

<?php

$func =
    "function(greeting, name) { ".
        "return greeting+', '+name+', says '+greeter;".
    "}";
$scope = array("greeter" => "Fred");

$code = new MongoCode($func, $scope);

$response = $db->execute($code, array("Goodbye", "Joe"));
echo $response['retval'];

?>

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

Goodbye, Joe, says Fred
MongoDB::dropCollection
MongoDB::forceError
MongoDB


Creates a database error

MongoDB::execute
MongoDB::__get
MongoDB
PHP Manual

MongoDB::forceError

(PECL mongo >=0.9.5)

MongoDB::forceError — Creates a database error

Opis

public bool MongoDB::forceError ( void )

This method is not very useful for normal MongoDB use. It forces a database error to occur. This means that MongoDB::lastError() will return a generic database error after running this command.

This command is identical to running:

<?php

public function forceError() {
    return $this->command(array('forceerror' => 1));
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the database response.

MongoDB::execute
MongoDB::__get
MongoDB


Gets a collection

MongoDB::forceError
MongoDB::getDBRef
MongoDB
PHP Manual

MongoDB::__get

(PECL mongo >=1.0.2)

MongoDB::__get — Gets a collection

Opis

public MongoCollection MongoDB::__get ( string $name )

This is the easiest way of getting a collection from a database object. If a collection name contains strange characters, you may have to use MongoDB::selectCollection() instead.

<?php

$mongo = new Mongo();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar");
$collection = $mongo->foo->bar;

?>

Parametry

name

The name of the collection.

Zwracane wartości

Returns the collection.

MongoDB::forceError
MongoDB::getDBRef
MongoDB


Fetches the document pointed to by a database reference

MongoDB::__get
MongoDB::getGridFS
MongoDB
PHP Manual

MongoDB::getDBRef

(PECL mongo >=0.9.0)

MongoDB::getDBRef — Fetches the document pointed to by a database reference

Opis

public array MongoDB::getDBRef ( array $ref )

Parametry

ref

A database reference.

Zwracane wartości

Returns the document pointed to by the reference.

Przykłady

Przykład #1 MongoDB::getDBRef() example

Example demonstrating how to get a database reference and what the expected input is.

<?php

 $ref = array(
   '$ref' => 'profiles',
   '$id' => '47cc67093475061e3d9536d2'
 );

 $profile = $db->getDBRef($ref);
 ?>

See MongoDB::createDBRef() for more information about how to programatically create DB references.

MongoDB::__get
MongoDB::getGridFS
MongoDB


Fetches toolkit for dealing with files stored in this database

MongoDB::getDBRef
MongoDB::getProfilingLevel
MongoDB
PHP Manual

MongoDB::getGridFS

(PECL mongo >=0.9.0)

MongoDB::getGridFS — Fetches toolkit for dealing with files stored in this database

Opis

public MongoGridFS MongoDB::getGridFS ([ string $prefix = "fs" ] )

Parametry

prefix

The prefix for the files and chunks collections.

Zwracane wartości

Returns a new gridfs object for this database.

Przykłady

Przykład #1 MongoDB::getGridFS() example

This example demonstrates how get a MongoGridFS instance.

<?php

$db = $mongo->my_db;

$prefix = 'files';
$collection = $db->getGridFS($prefix);

?>

Read more about the MongoGridFS to learn how to store files with MongoDB.

MongoDB::getDBRef
MongoDB::getProfilingLevel
MongoDB


Gets this database's profiling level

MongoDB::getGridFS
MongoDB::getSlaveOkay
MongoDB
PHP Manual

MongoDB::getProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::getProfilingLevel — Gets this database's profiling level

Opis

public int MongoDB::getProfilingLevel ( void )

This returns the current database profiling level.

The database profiler tracks query execution times. If you turn it on (say, using MongoDB::setProfilingLevel() or the shell), you can see how many queries took longer than a given number of milliseconds or the timing for all queries.

Note that profiling slows down queries, so it is better to use in development or testing than in a time-sensitive application.

This function is equivalent to running:

<?php

public function getProfilingLevel() {
    return $this->command(array('profile' => -1));
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the profiling level.

Zobacz też:

MongoDB core docs on » profiling and MongoDB::setProfilingLevel() - Sets this database's profiling level.

MongoDB::getGridFS
MongoDB::getSlaveOkay
MongoDB


Get slaveOkay setting for this database

MongoDB::getProfilingLevel
MongoDB::lastError
MongoDB
PHP Manual

MongoDB::getSlaveOkay

(PECL mongo >=1.1.0)

MongoDB::getSlaveOkay — Get slaveOkay setting for this database

Opis

public bool MongoDB::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to slaves.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the value of slaveOkay for this instance.

MongoDB::getProfilingLevel
MongoDB::lastError
MongoDB


Check if there was an error on the most recent db operation performed

MongoDB::getSlaveOkay
MongoDB::listCollections
MongoDB
PHP Manual

MongoDB::lastError

(PECL mongo >=0.9.5)

MongoDB::lastError — Check if there was an error on the most recent db operation performed

Opis

public array MongoDB::lastError ( void )

This method is equivalent to:

<?php

public function lastError() {
    return $this->command(array('getlasterror' => 1));
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the error, if there was one.

Przykłady

Przykład #1 MongoDB::lastError() NULL error example

<?php
$db->resetError();
var_dump($db->lastError());
?>

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

array(3) {
  ["err"]=>
  NULL
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}

Przykład #2 MongoDB::lastError() duplicate key example

<?php
$c = $db->selectCollection("foo");

// insert two documents with the same _id
$c->insert(array("_id" => 1));
$c->insert(array("_id" => 1));

var_dump($db->lastError());
?>

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

array(3) {
  ["err"]=>
  string(64) "E11000 duplicate key errorindex: foo.foo.$_id_  dup key: { : 1 }"
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}
MongoDB::getSlaveOkay
MongoDB::listCollections
MongoDB


Get a list of collections in this database

MongoDB::lastError
MongoDB::prevError
MongoDB
PHP Manual

MongoDB::listCollections

(PECL mongo >=0.9.0)

MongoDB::listCollections — Get a list of collections in this database

Opis

public array MongoDB::listCollections ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a list of MongoCollections.

Przykłady

Przykład #1 MongoDB::listCollections() example

The following example demonstrates dropping each collection in a database.

<?php

$m = new Mongo();
$db = $m->selectDB("sample");

$list = $db->listCollections();
foreach ($list as $collection) {
    echo "removing $collection... ";
    $collection->drop();
    echo "gone\n";
}

?>

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

removing sample.blog.posts... gone
removing sample.critical.docs... gone
removing sample.taxes... gone
...
MongoDB::lastError
MongoDB::prevError
MongoDB


Checks for the last error thrown during a database operation

MongoDB::listCollections
MongoDB::repair
MongoDB
PHP Manual

MongoDB::prevError

(PECL mongo >=0.9.5)

MongoDB::prevError — Checks for the last error thrown during a database operation

Opis

public array MongoDB::prevError ( void )

MongoDB::lastError() is usually preferred to this. This method returns the last database error that occurred and how many operations ago it occurred. It is mostly deprecated.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the error and the number of operations ago it occurred.

MongoDB::listCollections
MongoDB::repair
MongoDB


Repairs and compacts this database

MongoDB::prevError
MongoDB::resetError
MongoDB
PHP Manual

MongoDB::repair

(PECL mongo >=0.9.0)

MongoDB::repair — Repairs and compacts this database

Opis

public array MongoDB::repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] )

This creates a fresh copy of all database data. It will remove any corrupt data and compact and large stretches of free space it finds. This is a very slow operation on a large database.

This is usually run from the shell or the command line, not the driver.

It is equivalent to the function:

<?php

public function repair() {
    return $this->command(array('repairDatabase' => 1));
}

?>

Parametry

preserve_cloned_files

If cloned files should be kept if the repair fails.

backup_original_files

If original files should be backed up.

Zwracane wartości

Returns db response.

Zobacz też:

MongoDB core docs on » repair.

Przykłady

Przykład #1 MongoDB::repair() example

This example demonstrates how to repare and compact a database.

<?php

$db = $mongo->foo;

$response = $db->repair();
print_r($response);

?>

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

Array
(
    [ok] => 1
)
MongoDB::prevError
MongoDB::resetError
MongoDB


Clears any flagged errors on the database

MongoDB::repair
MongoDB::selectCollection
MongoDB
PHP Manual

MongoDB::resetError

(PECL mongo >=0.9.5)

MongoDB::resetError — Clears any flagged errors on the database

Opis

public array MongoDB::resetError ( void )

This method is not used in normal operations. It resets the database error tracker (which can be incremented with MongoDB::forceError(), also not normally used).

It is equivalent to running:

<?php

public function resetError() {
    return $this->command(array('reseterror' => 1));
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the database response.

MongoDB::repair
MongoDB::selectCollection
MongoDB


Gets a collection

MongoDB::resetError
MongoDB::setProfilingLevel
MongoDB
PHP Manual

MongoDB::selectCollection

(PECL mongo >=0.9.0)

MongoDB::selectCollection — Gets a collection

Opis

public MongoCollection MongoDB::selectCollection ( string $name )

Parametry

name

The name of the collection.

Zwracane wartości

Returns the collection.

MongoDB::resetError
MongoDB::setProfilingLevel
MongoDB


Sets this database's profiling level

MongoDB::selectCollection
MongoDB::setSlaveOkay
MongoDB
PHP Manual

MongoDB::setProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::setProfilingLevel — Sets this database's profiling level

Opis

public int MongoDB::setProfilingLevel ( int $level )

This changes the current database profiling level.

This function is equivalent to running:

<?php

public function setProfilingLevel($level) {
    return $this->command(array('profile' => $level));
}

?>

The options for level are 0 (off), 1 (queries > 100ms), and 2 (all queries). If you would like to profile queries that take longer than another time period, use the database command and pass it a second option, the number of milliseconds. For example, to profile all queries that take longer than one second, run:

<?php

$result = $this->command(array('profile' => 1, 'slowms' => 1000));

?>

Profiled queries will appear in the system.profile collection of this database.

Parametry

level

Profiling level.

Zwracane wartości

Returns the previous profiling level.

MongoDB::selectCollection
MongoDB::setSlaveOkay
MongoDB


Change slaveOkay setting for this database

MongoDB::setProfilingLevel
MongoDB::__toString
MongoDB
PHP Manual

MongoDB::setSlaveOkay

(PECL mongo >=1.1.0)

MongoDB::setSlaveOkay — Change slaveOkay setting for this database

Opis

public bool MongoDB::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to slaves.

Parametry

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoDB instance.

Zwracane wartości

Returns the former value of slaveOkay for this instance.

MongoDB::setProfilingLevel
MongoDB::__toString
MongoDB


The name of this database

MongoDB::setSlaveOkay
MongoCollection
MongoDB
PHP Manual

MongoDB::__toString

(PECL mongo >=0.9.0)

MongoDB::__toString — The name of this database

Opis

public string MongoDB::__toString ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns this database's name.

MongoDB::setSlaveOkay
MongoCollection
MongoDB


The MongoCollection class

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

Wstęp

Representations a database collection.

Collection names can use any character in the ASCII set. Some valid collection names are "", "...", "my collection", and "*&#@".

User-defined collection names cannot contain the $ symbol. There are certain system collections which use a $ in their names (e.g., local.oplog.$main), but it is a reserved character. If you attempt to create and use a collection with a $ in the name, MongoDB will assert.

Krótki opis klasy

MongoCollection {
/* Stałe */
const int ASCENDING = 1 ;
const int DESCENDING = -1 ;
/* Fields */
public MongoDB $db = NULL ;
public integer $w ;
public integer $wtimeout ;
/* Metody */
public mixed batchInsert ( array $a [, array $options = array() ] )
public __construct ( MongoDB $db , string $name )
public int count ([ array $query = array() [, int $limit = 0 [, int $skip = 0 ]]] )
public array createDBRef ( array $a )
public array deleteIndex ( string|array $keys )
public array deleteIndexes ( void )
public array drop ( void )
public bool ensureIndex ( string|array $key|keys [, array $options = array() ] )
public MongoCursor find ([ array $query = array() [, array $fields = array() ]] )
public array findOne ([ array $query = array() [, array $fields = array() ]] )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public array getIndexInfo ( void )
public string getName ( void )
public bool getSlaveOkay ( void )
public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )
public bool|array insert ( array $a [, array $options = array() ] )
public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed save ( array $a [, array $options = array() ] )
public bool setSlaveOkay ([ bool $ok = true ] )
static protected string toIndexString ( mixed $keys )
public string __toString ( void )
public bool|array update ( array $criteria , array $new_object [, array $options = array() ] )
public array validate ([ bool $scan_data = FALSE ] )
}

Stałe predefiniowane

MongoCollection::ASCENDING
1
Ascending direction for sorts and index creation.
MongoCollection::DESCENDING
-1
Descending direction for sorts and index creation.

Fields

db

The "parent" database for this collection.

w

The number of servers to replicate a change to before returning success. Value is inherited from the parent database. The MongoDB class has a more detailed description of how w works.

wtimeout

The number of milliseconds to wait for $this->w replications to take place. Value is inherited from the parent database. The MongoDB class has a more detailed description of how wtimeout works.

Zobacz też:

MongoDB core docs on » collections.

Spis treści

  • MongoCollection::batchInsert — Inserts multiple documents into this collection
  • MongoCollection::__construct — Creates a new collection
  • MongoCollection::count — Counts the number of documents in this collection
  • MongoCollection::createDBRef — Creates a database reference
  • MongoCollection::deleteIndex — Deletes an index from this collection
  • MongoCollection::deleteIndexes — Delete all indices for this collection
  • MongoCollection::drop — Drops this collection
  • MongoCollection::ensureIndex — Creates an index on the given field(s), or does nothing if the index already exists
  • MongoCollection::find — Querys this collection, returning a MongoCursor for the result set
  • MongoCollection::findOne — Querys this collection, returning a single element
  • MongoCollection::__get — Gets a collection
  • MongoCollection::getDBRef — Fetches the document pointed to by a database reference
  • MongoCollection::getIndexInfo — Returns information about indexes on this collection
  • MongoCollection::getName — Returns this collection's name
  • MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection
  • MongoCollection::group — Performs an operation similar to SQL's GROUP BY command
  • MongoCollection::insert — Inserts an array into the collection
  • MongoCollection::remove — Remove records from this collection
  • MongoCollection::save — Saves an object to this collection
  • MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection
  • MongoCollection::toIndexString — Converts keys specifying an index to its identifying string
  • MongoCollection::__toString — String representation of this collection
  • MongoCollection::update — Update records based on a given criteria
  • MongoCollection::validate — Validates this collection
MongoDB::__toString
MongoCollection::batchInsert
Core Classes


Inserts multiple documents into this collection

MongoCollection
MongoCollection::__construct
MongoCollection
PHP Manual

MongoCollection::batchInsert

(PECL mongo >=0.9.0)

MongoCollection::batchInsert — Inserts multiple documents into this collection

Opis

public mixed MongoCollection::batchInsert ( array $a [, array $options = array() ] )

Parametry

a

An array of arrays.

options

Options for the inserts.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the insert did not succeed.

    If safe is an integer, will replicate the insert to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, a safe insert is implied and will override setting safe to FALSE.

Zwracane wartości

If "safe" is set, returns an associative array with the status of the inserts ("ok") and any error that may have occured ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.

Błędy/Wyjątki

Throws MongoCursorException if the "safe" option is set and the insert fails.

Throws MongoCursorTimeoutException if the "safe" option is set to a value greater than one and the database cannot replicate the operation in MongoCollection::$wtimeout milliseconds.

Rejestr zmian

Wersja | Opis
1.0.5 | Added "options" parameter.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.

Przykłady

Przykład #1 MongoCollection::batchInsert() example

Batch insertion is a quick way to add many elements to the database at once

<?php

$users = array();
for ($i = 0; $i<100; $i++) {
  $users[] = array('username' => 'user'.$i, 'i' => $i);
}

$mongo = new Mongo();
$collection = $mongo->my_db->users;
$collection->drop();

$collection->batchInsert($users);

foreach ($users as $user) {
  echo $user['_id']."\n"; // populated with instanceof MongoId
}

$users = $collection->find()->sort(array('i' => 1));
foreach ($users as $user) {
    var_dump($user['username']);
}

?>

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

4bf43ac68ead0e1971000000
4bf43ac68ead0e1971010000
4bf43ac68ead0e1971020000
...
string(5) "user1"
string(5) "user2"
string(5) "user3"
...

Zobacz też:

  • MongoCollection::insert() - Inserts an array into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Querys this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.
MongoCollection
MongoCollection::__construct
MongoCollection


Creates a new collection

MongoCollection::batchInsert
MongoCollection::count
MongoCollection
PHP Manual

MongoCollection::__construct

(PECL mongo >=0.9.0)

MongoCollection::__construct — Creates a new collection

Opis

public MongoCollection::__construct ( MongoDB $db , string $name )

Parametry

MongoDB db

Parent database.

name

Name for this collection.

Zwracane wartości

Returns a new collection object.

Błędy/Wyjątki

Throws default exception if the collection name is invalid.

MongoCollection::batchInsert
MongoCollection::count
MongoCollection


Counts the number of documents in this collection

MongoCollection::__construct
MongoCollection::createDBRef
MongoCollection
PHP Manual

MongoCollection::count

(PECL mongo >=0.9.0)

MongoCollection::count — Counts the number of documents in this collection

Opis

public int MongoCollection::count ([ array $query = array() [, int $limit = 0 [, int $skip = 0 ]]] )

Parametry

query

Associative array or object with fields to match.

limit

Specifies an upper limit to the number returned.

skip

Specifies a number of results to skip before starting the count.

Zwracane wartości

Returns the number of documents matching the query.

Rejestr zmian

Wersja | Opis
1.0.7 | Added limit and skip parameters.

Przykłady

Przykład #1 MongoCollection::count() example

<?php

$collection->insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));

var_dump($collection->count());
var_dump($collection->count(array('x'=>1)));

?>

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

int(3)
int(1)
MongoCollection::__construct
MongoCollection::createDBRef
MongoCollection


Creates a database reference

MongoCollection::count
MongoCollection::deleteIndex
MongoCollection
PHP Manual

MongoCollection::createDBRef

(PECL mongo >=0.9.0)

MongoCollection::createDBRef — Creates a database reference

Opis

public array MongoCollection::createDBRef ( array $a )

Parametry

a

Object to which to create a reference.

Zwracane wartości

Returns a database reference array.

Przykłady

Przykład #1 MongoCollection::createDBRef() example

<?php

$songs = $db->songs;
$playlists = $db->playlists;

// create a reference to a song
$manamana = $songs->findOne(array('title' => 'Ma na ma na'));
$refToSong = $songs->createDBRef($manamana);

// add the reference to my playlist
$playlists->update(array('username' => 'me'), array('$push' => array('songlist' => $refToSong)));

?>

Zobacz też:

  • MongoCollection::getDBRef() - Fetches the document pointed to by a database reference

MongoCollection::count
MongoCollection::deleteIndex
MongoCollection


Deletes an index from this collection

MongoCollection::createDBRef
MongoCollection::deleteIndexes
MongoCollection
PHP Manual

MongoCollection::deleteIndex

(PECL mongo >=0.9.0)

MongoCollection::deleteIndex — Deletes an index from this collection

Opis

public array MongoCollection::deleteIndex ( string|array $keys )

This method is identical to:

<?php

public function deleteIndexes($keys) {
  // toIndexString is a protected method that turns strings, arrays, and objs
  //into index names
  $index = $this->toIndexString($keys);

  return $this->db->command(array("deleteIndexes" => $this->getName(),
    "index" => $index);
}

?>

Each index, when created, is given a unique name. This is generally user-set (with MongoCollection::ensureIndex()'s "name" option) or generated by the driver from a combination of key names and directions. This name is then used by MongoCollection::deleteIndex() to remove the function.

Unfortunately, the MongoCollection::ensureIndex() generates slightly different names than the shell and, due to backwards compatibility issues, MongoCollection::deleteIndex() cannot delete custom-named indexes as well. Thus, the best way to delete indexes created in the shell or with custom names is to directly call the deleteIndexes database command.

Thus, if you named an index "superfast query", you could only delete it with the PHP driver by running:

<?php

$db->command(array("deleteIndexes" => $collection->getName(), "index" => "superfast query");

?>

To find what an index is named, you can query the system.indexes collection of a database and look for the name field.

Parametry

keys

Field or fields from which to delete the index.

Zwracane wartości

Returns the generated name of the key if successful, or NULL otherwise.

Przykłady

Przykład #1 MongoCollection::deleteIndex() example

This example passes the function string and array parameters.

<?php
$m = new Mongo();
$c = $m->example->indices;

// create an index
$c->ensureIndex(array("i"=>1));

// remove a simple index
$c->deleteIndex("i");

// create a multi-key index
$c->ensureIndex(array("j" => 1, "k" => 1));

// remove a multi-key index
$c->deleteIndex(array("j" => 1, "k" => 1));
?>
MongoCollection::createDBRef
MongoCollection::deleteIndexes
MongoCollection


Delete all indices for this collection

MongoCollection::deleteIndex
MongoCollection::drop
MongoCollection
PHP Manual

MongoCollection::deleteIndexes

(PECL mongo >=0.9.0)

MongoCollection::deleteIndexes — Delete all indices for this collection

Opis

public array MongoCollection::deleteIndexes ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the database response.

Przykłady

Przykład #1 MongoCollection::deleteIndexes() example

This example demonstrates how to delete all indexes from a collection and the response to expect.

<?php

$collection = $mongo->my_db->articles;
$response = $collection->deleteIndexes();
print_r($response);

?>

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

Array
(
    [nIndexesWas] => 1
    [msg] => all indexes deleted for collection
    [ok] => 1
)
MongoCollection::deleteIndex
MongoCollection::drop
MongoCollection


Drops this collection

MongoCollection::deleteIndexes
MongoCollection::ensureIndex
MongoCollection
PHP Manual

MongoCollection::drop

(PECL mongo >=0.9.0)

MongoCollection::drop — Drops this collection

Opis

public array MongoCollection::drop ( void )

Drops this collection and deletes its indices.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the database response.

Przykłady

Przykład #1 MongoCollection::drop() example

This example demonstrates how to drop a collection and the response to expect.

<?php

$collection = $mongo->my_db->articles;
$response = $collection->drop();
print_r($response);

?>

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

Array
(
    [nIndexesWas] => 1
    [msg] => all indexes deleted for collection
    [ns] => my_db.articles
    [ok] => 1
)
MongoCollection::deleteIndexes
MongoCollection::ensureIndex
MongoCollection


Creates an index on the given field(s), or does nothing if the index already exists

MongoCollection::drop
MongoCollection::find
MongoCollection
PHP Manual

MongoCollection::ensureIndex

(PECL mongo >=0.9.0)

MongoCollection::ensureIndex — Creates an index on the given field(s), or does nothing if the index already exists

Opis

public bool MongoCollection::ensureIndex ( string|array $key|keys [, array $options = array() ] )

This method creates an index on the collection and the specified fields. The key specification can either be just a single field name as string, or an array containing one or more field names with their sort direction.

Parametry

keys

An array of fields by which to sort the index on. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort.

options

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "unique"

    Create a unique index.

    Ostrzeżenie

    A unique index cannot be created on a field if multiple existing documents do not contain the field. The field is effectively NULL for these documents and thus already non-unique.

  • "dropDups"

    If a unique index is being created and duplicate values exist, drop all but one duplicate value.

  • "background"

    If you are using MongoDB version 1.3.2+, you can create indexes in the background while other operations are taking place. By default, index creation happens synchronously. If you specify TRUE with this option, index creation will be asynchronous.

  • "safe"

    Starting with driver version 1.0.4, you can specify a boolean value for checking if the index creation succeeded. The driver will throw a MongoCursorException if index creation failed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

  • "name"

    Starting with driver version 1.0.5 you can specify an index name. This can be useful if you are indexing many keys and Mongo complains about the index name being too long.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Zwracane wartości

Returns TRUE.

Rejestr zmian

Wersja | Opis
1.0.2 | Changed "options" parameter from boolean to array. Pre-1.0.2, the second parameter was an optional boolean value specifying a unique index.
1.0.11 | "safe" will trigger master failover, if necessary.
1.0.11 | MongoException will be thrown if index name (either generated or set) is longer than 128 bytes.
1.2.0 | Added timeout option.
1.3.0 | The options parameter does no longer accept just a boolean to signify a unique index. Instead, this now has to be done with array('unique' => true).

Błędy/Wyjątki

Throws MongoException if the index name is longer than 128 bytes. (Version 1.0.11+)

Throws MongoCursorException if the "safe" option is set and the index creation fails.

Throws MongoCursorTimeoutException if the "safe" option is set and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout.

Przykłady

Przykład #1 MongoCollection::ensureIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->ensureIndex('x');

// create an index on 'y' ascending
$c->ensureIndex(array('y' => 1));

// create an index on 'z' ascending and 'zz' descending
$c->ensureIndex(array('z' => 1, 'zz' => -1));

// create a unique index on 'x'
$c->ensureIndex(array('x' => 1), array("unique" => true));

?>

Przykład #2 Drop duplicates example

<?php

$collection->insert(array("username" => "joeschmoe"));
$collection->insert(array("username" => "joeschmoe"));

/*
 * index creation fails, you can't create a unique index on a key with
 * non-unique values
 */
$collection->ensureIndex(array("username" => 1), array("unique" => 1));

/*
 * index creation succeeds: one of the documents is removed from the collection
 */
$collection->ensureIndex(array("username" => 1), array("unique" => 1, "dropDups" => 1));

/*
 * now we have a unique index, more inserts with the same username (such as the
 * one below) will fail
 */
$collection->insert(array("username" => "joeschmoe"));

?>

Przykład #3 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. For example, to create a geospatial index on the "loc" field:

<?php

$collection->ensureIndex(array("loc" => "2d"));

?>

Zobacz też:

MongoDB core docs on » vanilla indexes and » geospatial indexes.

MongoCollection::drop
MongoCollection::find
MongoCollection


Querys this collection, returning a MongoCursor for the result set

MongoCollection::ensureIndex
MongoCollection::findOne
MongoCollection
PHP Manual

MongoCollection::find

(PECL mongo >=0.9.0)

MongoCollection::find — Querys this collection, returning a MongoCursor for the result set

Opis

 public MongoCursor MongoCollection::find
  ([ array $query = array()
 [, array $fields = array()
]] )

Parametry

query

The fields for which to search. MongoDB's query language is quite extensive. The PHP driver will in almost all cases pass the query straight through to the server, so reading the MongoDB core docs on » find is a good idea.

Ostrzeżenie

Please make sure that for all special query operaters (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.

fields

Fields of the results to return. The array is in the format array('fieldname' => true, 'fieldname2' => true). The _id field is always returned.

Zwracane wartości

Returns a cursor for the search results.

Przykłady

Przykład #1 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));

$cursor = $collection->find($rangeQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

Powyższy przykład wyświetli:

array(2) {
  ["_id"]=>
  object(MongoId)#10 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000000"
  }
  ["x"]=>
  int(12)
}
array(2) {
  ["_id"]=>
  object(MongoId)#11 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000001"
  }
  ["x"]=>
  int(12)
}

See MongoCursor for more information how to work with cursors.

Przykład #2 MongoCollection::find() example using $where

This example demonstrates how to search a collection using javascript code to reduce the resultset.

<?php

$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$js = "function() {
    return this.name == 'Joe' || this.age == 50;
}";
$cursor = $collection->find(array('$where' => $js));
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

Powyższy przykład wyświetli:

array(3) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000002"
  }
  ["name"]=>
  string(3) "Joe"
  ["age"]=>
  int(20)
}

Przykład #3 MongoCollection::find() example using $in

This example demonstrates how to search a collection using the $in operator.

<?php

$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find(array(
    'name' => array('$in' => array('Joe', 'Wendy'))
));

?>

Powyższy przykład wyświetli:

array(3) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000002"
  }
  ["name"]=>
  string(3) "Joe"
  ["age"]=>
  int(20)
}

Przykład #4 Getting results as an array

This returns a MongoCursor. Often, when people are starting out, they are more comfortable using an array. To turn a cursor into an array, use the iterator_to_array() function.

<?php

$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find();
$array = iterator_to_array($cursor);

?>

Powyższy przykład wyświetli:

array(3) {
  ["4ebc40af10b89f5149000000"]=>
  array(2) {
    ["_id"]=>
    object(MongoId)#6 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000000"
    }
    ["x"]=>
    int(12)
  }
  ["4ebc40af10b89f5149000001"]=>
  array(2) {
    ["_id"]=>
    object(MongoId)#11 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000001"
    }
    ["x"]=>
    int(12)
  }
  ["4ebc40af10b89f5149000002"]=>
  array(3) {
    ["_id"]=>
    object(MongoId)#12 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000002"
    }
    ["name"]=>
    string(3) "Joe"
    ["age"]=>
    int(20)
  }
}

Using iterator_to_array() forces the driver to load all of the results into memory, so do not do this for result sets that are larger than memory!

Also, certain system collections do not have an _id field. If you are dealing with a collection that might have documents without _ids, pass FALSE as the second argument to iterator_to_array() (so that it will not try to use the non-existent _id values as keys).

Zobacz też:

  • MongoCollection::findOne() - Querys this collection, returning a single element
  • MongoCollection::insert() - Inserts an array into the collection
  • MongoDB core docs on » find.
MongoCollection::ensureIndex
MongoCollection::findOne
MongoCollection


Querys this collection, returning a single element

MongoCollection::find
MongoCollection::__get
MongoCollection
PHP Manual

MongoCollection::findOne

(PECL mongo >=0.9.0)

MongoCollection::findOne — Querys this collection, returning a single element

Opis

 public array MongoCollection::findOne
  ([ array $query = array()
 [, array $fields = array()
]] )

As opposed to MongoCollection::find(), this method will return only the first result from the result set, and not a MongoCursor that can be iterated over.

Parametry

query

The fields for which to search. MongoDB's query language is quite extensive. The PHP driver will in almost all cases pass the query straight through to the server, so reading the MongoDB core docs on » find is a good idea.

Ostrzeżenie

Please make sure that for all special query operaters (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.

fields

Fields of the results to return. The array is in the format array('fieldname' => true, 'fieldname2' => true). The _id field is always returned.

Zwracane wartości

Returns record matching the search or NULL.

Błędy/Wyjątki

Throws MongoConnectionException if it cannot reach the database.

Przykłady

Przykład #1 MongoCollection::findOne() document by its id.

This example demonstrates how to find a single document in a collection by its id.

<?php

$articles = $mongo->my_db->articles;

$article = $articles->findOne(array('_id' => new MongoId('47cc67093475061e3d9536d2')));

?>

Przykład #2 MongoCollection::findOne() document by some condition.

This example demonstrates how to find a single document in a collection by some condition and limiting the returned fields.

<?php

$users = $mongo->my_db->users;
$user = $users->findOne(array('username' => 'jwage'), array('password'));
print_r($user);

?>

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

Array
(
    [_id] => MongoId Object
        (
        )

    [password] => test
)

Notice how even though the document does have a username field, we limited the results to only contain the password field.

Zobacz też:

  • MongoCollection::find() - Querys this collection, returning a MongoCursor for the result set
  • MongoCollection::insert() - Inserts an array into the collection
  • MongoDB core docs on » find.
MongoCollection::find
MongoCollection::__get
MongoCollection


Gets a collection

MongoCollection::findOne
MongoCollection::getDBRef
MongoCollection
PHP Manual

MongoCollection::__get

(PECL mongo >=1.0.2)

MongoCollection::__get — Gets a collection

Opis

public MongoCollection MongoCollection::__get ( string $name )

A concise syntax for getting a collection with a dot-separated name. If a collection name contains strange characters, you may have to use MongoDB::selectCollection() instead.

<?php

$mongo = new Mongo();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar.baz");
$collection = $mongo->foo->bar->baz;

?>

Parametry

name

The next string in the collection name.

Zwracane wartości

Returns the collection.

MongoCollection::findOne
MongoCollection::getDBRef
MongoCollection


Fetches the document pointed to by a database reference

MongoCollection::__get
MongoCollection::getIndexInfo
MongoCollection
PHP Manual

MongoCollection::getDBRef

(PECL mongo >=0.9.0)

MongoCollection::getDBRef — Fetches the document pointed to by a database reference

Opis

public array MongoCollection::getDBRef ( array $ref )

Parametry

ref

A database reference.

Zwracane wartości

Returns the database document pointed to by the reference.

Przykłady

Przykład #1 MongoCollection::getDBRef() example

<?php

$playlists = $db->playlists;

$myList = $playlists->findOne(array('username' => 'me'));

// fetch each song in the playlist
foreach ($myList['songlist'] as $songRef) {
    $song = $playlists->getDBRef($songRef);
    echo $song['title'] . "\n";
}

?>

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

Dazed and Confused
Ma na ma na
Bohemian Rhapsody

In the above example each $songRef looks something like the following:
    Array
    (
        [$ref] => songs
        [$id] => 49902cde5162504500b45c2c
    )

Zobacz też:

  • MongoCollection::createDBRef() - Creates a database reference

MongoCollection::__get
MongoCollection::getIndexInfo
MongoCollection


Returns information about indexes on this collection

MongoCollection::getDBRef
MongoCollection::getName
MongoCollection
PHP Manual

MongoCollection::getIndexInfo

(PECL mongo >=0.9.0)

MongoCollection::getIndexInfo — Returns information about indexes on this collection

Opis

public array MongoCollection::getIndexInfo ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This function returns an array in which each elements describes an array. The elements contain the values name for the name of the index, ns for the namespace (the name of the collection), key containing a list of all the keys and their sort order that make up the index and _id containing a MongoID object with the ID of this index.

Przykłady

Przykład #1 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

$m = new Mongo;
$c = $m->selectCollection('project', 'outfits');
var_dump($c->getIndexInfo());

?>

Powyższy przykład wyświetli:

array(8) {
  [0] =>
  array(3) {
    'name' =>
    string(4) '_id_'
    'ns' =>
    string(12) 'project.outfits'
    'key' =>
    array(1) {
      '_id' =>
      int(1)
    }
  }
...
  [7] =>
  array(4) {
    '_id' =>
    class MongoId#12 (1) {
      public $$id =>      string(24) '4d6f7abd44670a1513190000'
    }
    'ns' =>
    string(12) 'project.outfits'
    'key' =>
    array(2) {
      'created' =>
      int(-1)
      'userid' =>
      int(1)
    }
    'name' =>
    string(19) 'created_-1_userid_1'
  }
}

See MongoCursor for more information how to work with cursors.

MongoCollection::getDBRef
MongoCollection::getName
MongoCollection


Returns this collection's name

MongoCollection::getIndexInfo
MongoCollection::getSlaveOkay
MongoCollection
PHP Manual

MongoCollection::getName

(PECL mongo >=0.9.0)

MongoCollection::getName — Returns this collection's name

Opis

public string MongoCollection::getName ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the name of this collection.

Przykłady

Przykład #1 MongoCollection::getName() example

<?php

$m = new Mongo();
$c = $m->foo->bar->baz;

echo "Working with collection " . $c->getName() . ".\n";

// the full namespace is given by the MongoCollection::__toString() method
echo "Working in namespace $c.\n";

?>

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

Working with collection bar.baz.
Working in namespace foo.bar.baz.

MongoCollection::getIndexInfo
MongoCollection::getSlaveOkay
MongoCollection


Get slaveOkay setting for this collection

MongoCollection::getName
MongoCollection::group
MongoCollection
PHP Manual

MongoCollection::getSlaveOkay

(PECL mongo >=1.1.0)

MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection

Opis

public bool MongoCollection::getSlaveOkay ( void )

See the query section of this manual for information on distributing reads to slaves.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the value of slaveOkay for this instance.

MongoCollection::getName
MongoCollection::group
MongoCollection


Performs an operation similar to SQL's GROUP BY command

MongoCollection::getSlaveOkay
MongoCollection::insert
MongoCollection
PHP Manual

MongoCollection::group

(PECL mongo >=0.9.2)

MongoCollection::group — Performs an operation similar to SQL's GROUP BY command

Opis

public array MongoCollection::group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )

Parametry

keys

Fields to group by. If an array or non-code object is passed, it will be the key used to group results.

1.0.4+: If keys is an instance of MongoCode, keys will be treated as a function that returns the key to group by (see the "Passing a keys function" example below).

initial

Initial value of the aggregation counter object.

reduce

A function that takes two arguments (the current document and the aggregation to this point) and does the aggregation.

options

Optional parameters to the group command. Valid options include:

  • "condition"

    Criteria for including a document in the aggregation.

  • "finalize"

    Function called once per unique key that takes the final output of the reduce function.

Zwracane wartości

Returns an array containing the result.

Przykłady

Przykład #1 MongoCollection::group() example

This groups documents by category and creates a list of names within that category.

<?php

$collection->insert(array("category" => "fruit", "name" => "apple"));
$collection->insert(array("category" => "fruit", "name" => "peach"));
$collection->insert(array("category" => "fruit", "name" => "banana"));
$collection->insert(array("category" => "veggie", "name" => "corn"));
$collection->insert(array("category" => "veggie", "name" => "broccoli"));

$keys = array("category" => 1);

$initial = array("items" => array());

$reduce = "function (obj, prev) { prev.items.push(obj.name); }";

$g = $collection->group($keys, $initial, $reduce);

echo json_encode($g['retval']);

?>

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

[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]

Przykład #2 MongoCollection::group() example

This example doesn't use any key, so every document will be its own group. It also uses a condition: only documents that match this condition will be processed by the grouping function.

<?php

$collection->save(array("a" => 2));
$collection->save(array("b" => 5));
$collection->save(array("a" => 1));

// use all fields
$keys = array();

// set intial values
$initial = array("count" => 0);

// JavaScript function to perform
$reduce = "function (obj, prev) { prev.count++; }";

// only use documents where the "a" field is greater than 1
$condition = array("a" => array( '$gt' => 1));

$g = $collection->group($keys, $initial, $reduce, $condition);

var_dump($g);

?>

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

array(4) {
  ["retval"]=>
  array(1) {
    [0]=>
    array(1) {
      ["count"]=>
      float(1)
    }
  }
  ["count"]=>
  float(1)
  ["keys"]=>
  int(1)
  ["ok"]=>
  float(1)
}

Przykład #3 Passing a keys function

If you want to group by something other than a field name, you can pass a function as the first parameter of MongoCollection::group() and it will be run against each document. The return value of the function will be used as its grouping value.

This example demonstrates grouping by the num field modulo 4.

<?php

$c->group(new MongoCode('function(doc) { return {mod : doc.num % 4}; }'),
     array("count" => 0),
     new MongoCode('function(current, total) { total.count++; }'));

?>
MongoCollection::getSlaveOkay
MongoCollection::insert
MongoCollection


Inserts an array into the collection

MongoCollection::group
MongoCollection::remove
MongoCollection
PHP Manual

MongoCollection::insert

(PECL mongo >=0.9.0)

MongoCollection::insert — Inserts an array into the collection

Opis

public bool|array MongoCollection::insert ( array $a [, array $options = array() ] )

All strings sent to the database must be UTF-8. If a string is not UTF-8, a MongoException will be thrown. To insert (or query for) a non-UTF-8 string, use MongoBinData.

Parametry

a

An array.

options

Options for the insert.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the insert did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw an exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the insert to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, a safe insert is implied and will override setting safe to FALSE.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Zwracane wartości

If safe was set, returns an array containing the status of the insert. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).

If an array is returned, the following keys can be present:

ok

This should almost be 1 (unless last_error itself failed).

err

If this field is non-null, an error occurred on the previous operation. If this field is set, it will be a string describing the error that occurred.

code

If a database error occurred, the relevant error code will be passed back to the client.

errmsg

This field is set if something goes wrong with a database command. It is coupled with ok being 0. For example, if w is set and times out, errmsg will be set to "timed out waiting for slaves" and ok will be 0. If this field is set, it will be a string describing the error that occurred.

n

If the last operation was an insert, an update or a remove, the number of objects affected will be returned.

wtimeout

If the previous option timed out waiting for replication.

waiter

How long the operation waited before timing out.

wtime

If w was set and the operation succeeded, how long it took to replicate to w servers.

upserted

If an upsert occured, this field will contain the new record's _id field. For upserts, either this field or updatedExisting will be present (unless an error occurred).

updatedExisting

If an upsert updated an existing element, this field will be true. For upserts, either this field or upserted will be present (unless an error occurred).

Błędy/Wyjątki

Throws MongoCursorException if the "safe" option is set and the insert fails. (Version 1.0.1+)

Throws MongoCursorTimeoutException if the "safe" option is set and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout.

Rejestr zmian

Wersja | Opis
1.0.5 | Changed second parameter to an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.9 | The return type was changed to be an array containing error information if the "safe" option is used, otherwise it is a boolean as before.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.2.0 | Added timeout option.
1.3.0 | The options parameter does no longer accept just a boolean to signify a safe insert. Instead, this now has to be done with array('safe' => true).

Przykłady

Przykład #1 MongoCollection::insert() _id example

Inserting an object will add an _id field to it, unless it is passed by reference.

<?php

$m = new Mongo();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$a = array('x' => 12);
$collection->insert($a);
var_dump($a);

$b = array('x' => 12);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);

?>

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

array(2) {
  ["x"]=>
  int(12)
  ["_id"]=>
  object(MongoId)#4 (0) {
  }
}
array(12) {
  ["x"]=>
  int(1)
}

Przykład #2 MongoCollection::insert() safe example

This example shows inserting two elements with the same _id, which causes a MongoCursorException to be thrown, as safe was set.

<?php

$person = array("name" => "Joe", "age" => 20);
$collection->insert($person, true);

// now $person has an _id field, so if we save it
// again, we will get an exception
try {
    $collection->insert($person, true);
} catch(MongoCursorException $e) {
    echo "Can't save the same person twice!\n";
}

?>

Zobacz też:

  • MongoCollection::batchInsert() - Inserts multiple documents into this collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Querys this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.
MongoCollection::group
MongoCollection::remove
MongoCollection


Remove records from this collection

MongoCollection::insert
MongoCollection::save
MongoCollection
PHP Manual

MongoCollection::remove

(PECL mongo >=0.9.0)

MongoCollection::remove — Remove records from this collection

Opis

 public bool|array MongoCollection::remove
  ([ array $criteria = array()
 [, array $options = array()
]] )

Parametry

criteria

Description of records to remove.

options

Options for remove.

  • "justOne"

    Remove at most one record matching this criteria.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the update did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the update to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the update to be synced to disk before returning success. If TRUE, a safe update is implied and will override setting safe to FALSE.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Zwracane wartości

If safe was set, returns an array containing the status of the remove. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted). The fields in this array are decribed in the documentation for MongoCollection::insert().

Błędy/Wyjątki

Throws MongoCursorException if the "safe" option is set and the remove fails.

Throws MongoCursorTimeoutException if the "safe" option is set and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout.

Rejestr zmian

Wersja | Opis
1.0.5 | Changed second parameter to an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "justOne" option and there was no safe option.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.9 | The return type was changed to be an array containing error information if the "safe" option is used, otherwise it is a boolean as before.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.2.0 | Added timeout option.
1.3.0 | The options parameter does no longer accept just a boolean to signify "justOne". Instead, this now has to be done with array('justOne' => true).

Przykłady

Przykład #1 MongoCollection::remove() with justOne example

<?php

$radioactive = $db->radioactive;

// count how much more plutonium there is
$remaining = $radioactive->count(array('type' => 94));

$halflife = $remaining/2;

// remove half of it
while ($halflife > 0) {
    $radioactive->remove(array('type' => 94), array("justOne" => true));
    $halflife--;
}

?>

Zobacz też:

  • MongoCollection::insert() - Inserts an array into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoDB core docs on » remove.
MongoCollection::insert
MongoCollection::save
MongoCollection


Saves an object to this collection

MongoCollection::remove
MongoCollection::setSlaveOkay
MongoCollection
PHP Manual

MongoCollection::save

(PECL mongo >=0.9.0)

MongoCollection::save — Saves an object to this collection

Opis

public mixed MongoCollection::save ( array $a [, array $options = array() ] )

If the object is from the database, update the existing database object, otherwise insert this object.

Parametry

a

Array to save.

options

Options for the save.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the insert did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the insert to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the insert to be synced to disk before returning success. If TRUE, a safe insert is implied and will override setting safe to FALSE.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Zwracane wartości

If safe was set, returns an array containing the status of the save. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).

Błędy/Wyjątki

Throws MongoCursorException if the "safe" option is set and the save fails.

Throws MongoCursorTimeoutException if the "safe" option is set and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout.

Rejestr zmian

Wersja | Opis
1.0.5 | Added "options" parameter.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.2.0 | Added timeout option.

Przykłady

Przykład #1 MongoCollection::save() example

<?php

$obj = array('x' => 1);

// insert $obj into the db
$collection->save($obj);

// add another field
$obj['foo'] = 'bar';

// $obj cannot be inserted again, causes duplicate _id error
$collection->insert($obj);

// save updates $obj with the new field
$collection->save($obj);

?>
MongoCollection::remove
MongoCollection::setSlaveOkay
MongoCollection


Change slaveOkay setting for this collection

MongoCollection::save
MongoCollection::toIndexString
MongoCollection
PHP Manual

MongoCollection::setSlaveOkay

(PECL mongo >=1.1.0)

MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection

Opis

public bool MongoCollection::setSlaveOkay ([ bool $ok = true ] )

See the query section of this manual for information on distributing reads to slaves.

Parametry

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoCollection instance.

Zwracane wartości

Returns the former value of slaveOkay for this instance.

MongoCollection::save
MongoCollection::toIndexString
MongoCollection


Converts keys specifying an index to its identifying string

MongoCollection::setSlaveOkay
MongoCollection::__toString
MongoCollection
PHP Manual

MongoCollection::toIndexString

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

MongoCollection::toIndexString — Converts keys specifying an index to its identifying string

Opis

static protected string MongoCollection::toIndexString ( mixed $keys )

Parametry

keys

Field or fields to convert to the identifying string

Zwracane wartości

Returns a string that describes the index.

Przykłady

Przykład #1 MongoCollection::toIndexString() example

This example shows how you can create an index name out of of keys. Because this is a protected (static) method, you need to overload it in a child class first.

<?php
// Create inheritec class to make the method "public".
class MyCollection extends MongoCollection
{
    static public function toIndexString($a)
    {
        return parent::toIndexString($a);
    }
}

echo MyCollection::toIndexString("foo")), "\n";
// Outputs: foo_1

echo MyCollection::toIndexString(array('name' => 1, 'age' => -1)), "\n";
// Outputs: name_1_age_-1
?>

Zobacz też:

MongoDB core docs on » indexes.

MongoCollection::setSlaveOkay
MongoCollection::__toString
MongoCollection


String representation of this collection

MongoCollection::toIndexString
MongoCollection::update
MongoCollection
PHP Manual

MongoCollection::__toString

(PECL mongo >=0.9.0)

MongoCollection::__toString — String representation of this collection

Opis

public string MongoCollection::__toString ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the full name of this collection.

Przykłady

Przykład #1 MongoCollection::__toString() example

<?php

$m = new Mongo();

$c1 = $m->foo->bar->baz;
echo "Working with collection $c1.";

$c2 = $m->selectCollection('[]', '&');
echo "Working with collection $c2.";

?>

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

Working with collection foo.bar.baz.
Working with collection [].&.

MongoCollection::toIndexString
MongoCollection::update
MongoCollection


Update records based on a given criteria

MongoCollection::__toString
MongoCollection::validate
MongoCollection
PHP Manual

MongoCollection::update

(PECL mongo >=0.9.0)

MongoCollection::update — Update records based on a given criteria

Opis

public bool|array MongoCollection::update ( array $criteria , array $new_object [, array $options = array() ] )

Parametry

criteria

Description of the objects to update.

new_object

The object with which to update the matching records.

options

This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:

  • "upsert"

    If no document matches $criteria, a new document will be created from $criteria and $new_object (see upsert example below).

  • "multiple"

    All documents matching $criteria will be updated. MongoCollection::update() has exactly the opposite behavior of MongoCollection::remove(): it updates one document by default, not all matching documents. It is recommended that you always specify whether you want to update multiple documents or a single document, as the database may change its default behavior at some point in the future.

  • "safe"

    Can be a boolean or integer, defaults to FALSE. If FALSE, the program continues executing without waiting for a database response. If TRUE, the program will wait for the database response and throw a MongoCursorException if the update did not succeed.

    If you are using replication and the master has changed, using "safe" will make the driver disconnect from the master, throw and exception, and attempt to find a new master on the next operation (your application must decide whether or not to retry the operation on the new master).

    If you do not use "safe" with a replica set and the master changes, there will be no way for the driver to know about the change so it will continuously and silently fail to write.

    If safe is an integer, will replicate the update to that many machines before returning success (or throw an exception if the replication times out, see wtimeout). This overrides the w variable set on the collection.

  • "fsync"

    Boolean, defaults to FALSE. Forces the update to be synced to disk before returning success. If TRUE, a safe update is implied and will override setting safe to FALSE.

  • "timeout"

    Integer, defaults to MongoCursor::$timeout. If "safe" is set, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.

Zwracane wartości

If safe was set, returns an array containing the status of the update. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted). The fields in this array are decribed in the documentation for MongoCollection::insert().

Błędy/Wyjątki

Throws MongoCursorException if the "safe" option is set and the update fails.

Throws MongoCursorTimeoutException if the "safe" option is set and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout.

Rejestr zmian

Wersja | Opis
1.0.1 | Changed "options" parameter from boolean to array. Pre-1.0.1, the second parameter was an optional boolean value specifying an upsert.
1.0.5 | Added "safe" option.
1.0.9 | Added ability to pass integers to "safe" options (only accepted booleans before) and added "fsync" option.
1.0.9 | The return type was changed to be an array containing error information if the "safe" option is used, otherwise it is a boolean as before.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.2.0 | Added timeout option.
1.3.0 | The options parameter does no longer accept just a boolean to signify an upsert. Instead, this now has to be done with array('upsert' => true).

Przykłady

Przykład #1 MongoCollection::update()

Adding an address field to a document.

<?php

$c->insert(array("firstname" => "Bob", "lastname" => "Jones" ));
$newdata = array('$set' => array("address" => "1 Smith Lane"));
$c->update(array("firstname" => "Bob"), $newdata);

var_dump($c->findOne(array("firstname" => "Bob")));

?>

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

array(4) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["firstname"]=>
  string(3) "Bob"
  ["lastname"]=>
  string(5) "Jones"
  ["address"]=>
  string(12) "1 Smith Lane"
}

Przykład #2 MongoCollection::update() upsert example

Upserts can simplify code, as a single line can create the object if it does not exist yet and update it if it does.

<?php

$c->drop();
$c->update(array("uri" => "/summer_pics"), array('$inc' => array("page hits" => 1)), array("upsert" => true));
var_dump($c->findOne());

?>

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

array(3) {
  ["_id"]=>
  object(MongoId)#9 (0) {
  }
  ["uri"]=>
  string(12) "/summer_pics"
  ["page hits"]=>
  int(1)
}

If $new_object does not contain $-operators, an upsert will create a new document from the passed fields only. This matches the behavior of a normal update, where not using $-operators causes the whole document to be overwritten.

<?php

$c->drop();
$c->update(
    array("name" => "joe"),
    array("username" => "joe312", "createdAt" => new MongoDate()),
    array("upsert" => true)
);
var_dump($c->findOne());

?>

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

array(3) {
  ["_id"]=>
  object(MongoId)#10 (0) {
  }
  ["username"]=>
  string(6) "joe312"
  ["createdAt"]=>
  object(MongoDate)#4 (0) {
  }
}

Przykład #3 MongoCollection::update() multiple example

By default, MongoCollection::update() will only update the first document matching $criteria that it finds. Using the "multiple" option can override this behavior, if needed.

This example adds a "gift" field to every person whose birthday is in the next day.

<?php

$today = array('$gt' => new MongoDate(), '$lt' => new MongoDate(strtotime("+1 day")));
$people->update(
    array("birthday" => $today),
    array('$set' => array('gift' => $surprise)),
    array("multiple" => true)
);

?>

Zobacz też:

The PHP documentation on updates and the » MongoDB core docs.

MongoCollection::__toString
MongoCollection::validate
MongoCollection


Validates this collection

MongoCollection::update
MongoCursor
MongoCollection
PHP Manual

MongoCollection::validate

(PECL mongo >=0.9.0)

MongoCollection::validate — Validates this collection

Opis

public array MongoCollection::validate ([ bool $scan_data = FALSE ] )

Parametry

scan_data

Only validate indices, not the base collection.

Zwracane wartości

Returns the database's evaluation of this object.

MongoCollection::update
MongoCursor
MongoCollection


The MongoCursor class

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

Wstęp

A cursor is used to iterate through the results of a database query. For example, to query the database and see all results, you could do:

<?php

$cursor = $collection->find();
var_dump(iterator_to_array($cursor));

?>

You don't generally create cursors using the MongoCursor constructor, you get a new cursor by calling MongoCollection::find() (as shown above).

Suppose that, in the example above, $collection was a 50GB collection. We certainly wouldn't want to load that into memory all at once, which is what a cursor is for: allowing the client to access the collection in dribs and drabs.

If we have a large result set, we can iterate through it, loading a few megabytes of results into memory at a time. For example, we could do:

<?php

$cursor = $collection->find();

foreach ($cursor as $doc) {
    // do something to each document
}

?>
This will go through each document in the collection, loading and garbage collecting documents as needed.

Note that this means that a cursor does not "contain" the database results, it just manages them. Thus, if you print a cursor (with, say, var_dump() or print_r()), you'll just get the cursor object, not your documents. To get the documents themselves, you can use one of the methods shown above.

Cursor Stages

A MongoCursor has two "life stages": pre- and post- query. When a cursor is created, it has not yet contacted the database, so it is in its pre-query state. In this state, the client can further specify what they want the query to do, including adding limits, skips, sorts, and more advanced options.

When the client attempts to get a result (by calling MongoCursor::next(), directly or indirectly), the cursor moves into the post-query stage. At this point, the query has been executed by the database and cannot be modified anymore.

<?php

$cursor = $collection->find()->limit(10);

// database has not yet been queried, so more search options can be added
$cursor = $cursor->sort(array("a" => 1));

var_dump($cursor->getNext());
// now database has been queried and more options cannot be added

// so this will throw an exception:
$cursor->skip(4);
?>

Krótki opis klasy

MongoCursor implements Iterator {
/* Static Fields */
static boolean $slaveOkay = FALSE ;
static integer $timeout = 20000 ;
/* Metody */
public MongoCursor addOption ( string $key , mixed $value )
public MongoCursor batchSize ( int $num )
public __construct ( Mongo $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public int count ([ bool $foundOnly = FALSE ] )
public array current ( void )
public bool dead ( void )
protected void doQuery ( void )
public array explain ( void )
public MongoCursor fields ( array $f )
public array getNext ( void )
public bool hasNext ( void )
public MongoCursor hint ( array $key_pattern )
public MongoCursor immortal ([ bool $liveForever = true ] )
public array info ( void )
public string key ( void )
public MongoCursor limit ( int $num )
public void next ( void )
public MongoCursor partial ([ bool $okay = true ] )
public void reset ( void )
public void rewind ( void )
public MongoCursor skip ( int $num )
public MongoCursor slaveOkay ([ bool $okay = true ] )
public MongoCursor snapshot ( void )
public MongoCursor sort ( array $fields )
public MongoCursor tailable ([ bool $tail = true ] )
public MongoCursor timeout ( int $ms )
public bool valid ( void )
}

Static Variables

slaveOkay

If the query should have the "slaveOkay" flag set, which allows reads on the slave (slaves are, by default, just for backup and unreadable). Can be overridden with MongoCursor::slaveOkay().

timeout

Set timeout in milliseconds for all database responses. To wait forever, use -1. Can be overridden with MongoCursor::timeout(). This does not cause the MongoDB server to cancel the operation, it just causes the driver to stop waiting for a response and throw a MongoCursorTimeoutException.

Zobacz też:

MongoDB core docs on » cursors.

Spis treści

  • MongoCursor::addOption — Adds a top-level key/value pair to a query
  • MongoCursor::batchSize — Sets the number of results returned per result set
  • MongoCursor::__construct — Create a new cursor
  • MongoCursor::count — Counts the number of results for this query
  • MongoCursor::current — Returns the current element
  • MongoCursor::dead — Checks if there are documents that have not been sent yet from the database for this cursor
  • MongoCursor::doQuery — Execute the query.
  • MongoCursor::explain — Return an explanation of the query, often useful for optimization and debugging
  • MongoCursor::fields — Sets the fields for a query
  • MongoCursor::getNext — Return the next object to which this cursor points, and advance the cursor
  • MongoCursor::hasNext — Checks if there are any more elements in this cursor
  • MongoCursor::hint — Gives the database a hint about the query
  • MongoCursor::immortal — Sets whether this cursor will timeout
  • MongoCursor::info — Gets the query, fields, limit, and skip for this cursor
  • MongoCursor::key — Returns the current result's _id
  • MongoCursor::limit — Limits the number of results returned
  • MongoCursor::next — Advances the cursor to the next result
  • MongoCursor::partial — If this query should fetch partial results from mongos if a shard is down
  • MongoCursor::reset — Clears the cursor
  • MongoCursor::rewind — Returns the cursor to the beginning of the result set
  • MongoCursor::skip — Skips a number of results
  • MongoCursor::slaveOkay — Sets whether this query can be done on a slave
  • MongoCursor::snapshot — Use snapshot mode for the query
  • MongoCursor::sort — Sorts the results by given fields
  • MongoCursor::tailable — Sets whether this cursor will be left open after fetching the last results
  • MongoCursor::timeout — Sets a client-side timeout for this query
  • MongoCursor::valid — Checks if the cursor is reading a valid result.
MongoCollection::validate
MongoCursor::addOption
Core Classes


Adds a top-level key/value pair to a query

MongoCursor
MongoCursor::batchSize
MongoCursor
PHP Manual

MongoCursor::addOption

(PECL mongo >=1.0.4)

MongoCursor::addOption — Adds a top-level key/value pair to a query

Opis

public MongoCursor MongoCursor::addOption ( string $key , mixed $value )

This is an advanced function and should not be used unless you know what you're doing.

A query can optionally be nested in a "query" field if other options, such as a sort or hint, are given. For instance, adding a sort causes the query to become a subfield of a bigger query object, like:

<?php

$query = array("query" => $query, "orderby" => $sort);

?>

This method is for adding a top-level field to a query. It makes the query a subobject (if it isn't already) and adds the key/value pair of your chosing to the top level.

Ostrzeżenie

It cannot be used to add extra criteria to a query on the fly. For instance, this will not work:

<?php

// NOT CORRECT
$cursor = $users->find()->addOption("name", "joe")->addOption("age", 20);

?>
This does not query for a user named "joe" with an age of 20.

Parametry

key

Fieldname to add.

value

Value to add.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

Przykłady

Przykład #1 MongoCursor::addOption() example

Using MongoCursor::skip() to skip over millions of results can become slow. One way around this is to use $min or $max options for the query. These can be handy, but they require an index on exactly the fields being searched for. This is an example of how to use $min as an alternative to MongoCursor::skip().

<?php

// make sure we have an index
$c->ensureIndex(array("ts" => 1));

// you may have to modify this to run in a reasonable amount of time on slow
// machines (should take about 30 seconds on a good machine)
for ($i = 0; $i < 30000000; $i++) {
    $c->insert(array("ts" => new MongoDate(), "i" => $i));
}

$now = strtotime("now");

// find documents inserted in the last 2 seconds
$cursor = $c->find()->addOption('$min', array("ts" => $now-2));

?>
MongoCursor
MongoCursor::batchSize
MongoCursor


Sets the number of results returned per result set

MongoCursor::addOption
MongoCursor::__construct
MongoCursor
PHP Manual

MongoCursor::batchSize

(PECL mongo >=1.0.11)

MongoCursor::batchSize — Sets the number of results returned per result set

Opis

public MongoCursor MongoCursor::batchSize ( int $num )

This cannot override MongoDB's limit on the amount of data it will return to the client (i.e., if you set batch size to 1,000,000,000, MongoDB will still only return 4-16MB of results).

To ensure consistent behavior, the rules of batchSize and limit behavior a little complex but work "as expected". The rules are: hard limits override soft limits with preference given to MongoCursor::limit() over MongoCursor::batchSize(). After that, whichever is set and lower than the other will take precedence. Some examples:

<?php

// one batch, at most 20 items
$cursor->limit(-20)->batchSize(10);

// one batch, at most 10 items
$cursor->limit(20)->batchSize(-10);

// first batch: at most 10 items
$cursor->limit(10);

// first batch: at most 10 items
$cursor->limit(10)->batchSize(20);

// first batch: at most 10 items
$cursor->limit(20)->batchSize(10);

$cursor->limit(30)->batchSize(7)
// if we iterate through 28 items, the next call to getNext() will contact the
// database and request a batch of 2 documents

?>

Parametry

num

The number of results to return in the next batch.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating. This will change in 1.0.12, as this should be able to be called at any time.

MongoCursor::addOption
MongoCursor::__construct
MongoCursor


Create a new cursor

MongoCursor::batchSize
MongoCursor::count
MongoCursor
PHP Manual

MongoCursor::__construct

(PECL mongo >=0.9.0)

MongoCursor::__construct — Create a new cursor

Opis

public MongoCursor::__construct ( Mongo $connection , string $ns [, array $query = array() [, array $fields = array() ]] )

Parametry

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Zwracane wartości

Returns the new cursor.

MongoCursor::batchSize
MongoCursor::count
MongoCursor


Counts the number of results for this query

MongoCursor::__construct
MongoCursor::current
MongoCursor
PHP Manual

MongoCursor::count

(PECL mongo >=0.9.2)

MongoCursor::count — Counts the number of results for this query

Opis

public int MongoCursor::count ([ bool $foundOnly = FALSE ] )

This method does not affect the state of the cursor: if you haven't queried yet, you can still apply limits, skips, etc. If you have started iterating through results, it will not move the current position of the cursor. If you have exhasted the cursor, it will not reset it.

Parametry

foundOnly

Send cursor limit and skip information to the count function, if applicable.

Zwracane wartości

The number of documents returned by this cursor's query.

Przykłady

Przykład #1 MongoCursor::count() example

<?php

$collection->insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));

$cursor = $collection->find();

var_dump($cursor->count());
var_dump($cursor->count(true));

$cursor->limit(2);

var_dump($cursor->count());
var_dump($cursor->count(true));

?>

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

int(3)
int(3)
int(3)
int(2)

Błędy/Wyjątki

Throws MongoConnectionException if it cannot reach the database.

MongoCursor::__construct
MongoCursor::current
MongoCursor


Returns the current element

MongoCursor::count
MongoCursor::dead
MongoCursor
PHP Manual

MongoCursor::current

(PECL mongo >=0.9.0)

MongoCursor::current — Returns the current element

Opis

public array MongoCursor::current ( void )

This returns NULL until MongoCursor::next() is called.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current result as an associative array.

MongoCursor::count
MongoCursor::dead
MongoCursor


Checks if there are documents that have not been sent yet from the database for this cursor

MongoCursor::current
MongoCursor::doQuery
MongoCursor
PHP Manual

MongoCursor::dead

(PECL mongo >=0.9.6)

MongoCursor::dead — Checks if there are documents that have not been sent yet from the database for this cursor

Opis

public bool MongoCursor::dead ( void )

The database sends responses in batches of documents, up to 4Mb of documents per response. This method checks if the database has more batches or if the result set has been exhausted.

A cursor being "dead" does not mean that MongoCursor::hasNext() will return FALSE, it only means that the database is done sending results to the client. The client should continue iterating through results until MongoCursor::hasNext() is FALSE.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns if there are more results that have not been sent to the client, yet.

MongoCursor::current
MongoCursor::doQuery
MongoCursor


Execute the query.

MongoCursor::dead
MongoCursor::explain
MongoCursor
PHP Manual

MongoCursor::doQuery

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

MongoCursor::doQuery — Execute the query.

Opis

protected void MongoCursor::doQuery ( void )

This function actually queries the database. All queries and commands go through this function. Thus, this function can be overridden to provide custom query handling.

This handles serializing your query, sending it to the database, receiving a response, and deserializing it. Thus, if you are planning to override this, your code should probably call out to the original to use the existing functionality (see the example below).

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

NULL.

Błędy/Wyjątki

Throws MongoConnectionException if it cannot reach the database.

Przykłady

Przykład #1 MongoCursor::doQuery() example

You could override this function to attempt a query on a slave and, if that fails, try it again on the master.

<?php

class MyCursor extends MongoCursor {

    protected function doQuery() {

        $this->slaveOkay();

        try {
            MongoCursor::doQuery();
        }
        catch(MongoCursorException $e) {
            $this->slaveOkay(false);
            MongoCursor::doQuery();
        }
    }
}

?>

MongoCursor::dead
MongoCursor::explain
MongoCursor


Return an explanation of the query, often useful for optimization and debugging

MongoCursor::doQuery
MongoCursor::fields
MongoCursor
PHP Manual

MongoCursor::explain

(PECL mongo >=0.9.2)

MongoCursor::explain — Return an explanation of the query, often useful for optimization and debugging

Opis

public array MongoCursor::explain ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an explanation of the query.

Przykłady

Przykład #1 MongoCursor::explain() example

<?php

$cursor = $collection->find(array("x"=>1), array("y"));
$cursor->sort(array("z" => 1))->limit(4)->skip(5);

var_dump($cursor->explain());

?>

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

array(8) {
  ["cursor"]=>
  string(15) "BtreeCursor x_1"
  ["startKey"]=>
  array(1) {
    ["x"]=>
    int(1)
  }
  ["endKey"]=>
  array(1) {
    ["x"]=>
    int(1)
  }
  ["nscanned"]=>
  float(4)
  ["n"]=>
  int(4)
  ["scanAndOrder"]=>
  int(1)
  ["millis"]=>
  int(3)
  ["allPlans"]=>
  array(2) {
    [0]=>
    array(3) {
      ["cursor"]=>
      string(15) "BtreeCursor x_1"
      ["startKey"]=>
      array(1) {
        ["x"]=>
        int(1)
      }
      ["endKey"]=>
      array(1) {
        ["x"]=>
        int(1)
      }
    }
    [1]=>
    array(3) {
      ["cursor"]=>
      string(11) "BasicCursor"
      ["startKey"]=>
      array(0) {
      }
      ["endKey"]=>
      array(0) {
      }
    }
  }
}

Błędy/Wyjątki

Throws MongoConnectionException if it cannot reach the database.

Zobacz też:

MongoDB core docs on » explain.

MongoCursor::doQuery
MongoCursor::fields
MongoCursor


Sets the fields for a query

MongoCursor::explain
MongoCursor::getNext
MongoCursor
PHP Manual

MongoCursor::fields

(PECL mongo >=1.0.6)

MongoCursor::fields — Sets the fields for a query

Opis

public MongoCursor MongoCursor::fields ( array $f )

Fields are specified by "fieldname" : bool. TRUE indicates that a field should be returned, FALSE indicates that it should not be returned. You can also use 1 and 0 instead of TRUE and FALSE.

Thus, to return only the "summary" field, one could say:

<?php

$cursor->fields(array("summary" => true));

?>

To return all fields except the "hidden" field:

<?php

$cursor->fields(array("hidden" => false));

?>

Parametry

f

Fields to return (or not return).

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating or a scalar argument is given.

MongoCursor::explain
MongoCursor::getNext
MongoCursor


Return the next object to which this cursor points, and advance the cursor

MongoCursor::fields
MongoCursor::hasNext
MongoCursor
PHP Manual

MongoCursor::getNext

(PECL mongo >=0.9.0)

MongoCursor::getNext — Return the next object to which this cursor points, and advance the cursor

Opis

public array MongoCursor::getNext ( void )

This is identical to the function:

<?php

public function getNext() {
    $this->next();
    return $this->current();
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the next object.

Błędy/Wyjątki

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

MongoCursor::fields
MongoCursor::hasNext
MongoCursor


Checks if there are any more elements in this cursor

MongoCursor::getNext
MongoCursor::hint
MongoCursor
PHP Manual

MongoCursor::hasNext

(PECL mongo >=0.9.0)

MongoCursor::hasNext — Checks if there are any more elements in this cursor

Opis

public bool MongoCursor::hasNext ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns if there is another element.

Błędy/Wyjątki

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

MongoCursor::getNext
MongoCursor::hint
MongoCursor


Gives the database a hint about the query

MongoCursor::hasNext
MongoCursor::immortal
MongoCursor
PHP Manual

MongoCursor::hint

(PECL mongo >=0.9.0)

MongoCursor::hint — Gives the database a hint about the query

Opis

public MongoCursor MongoCursor::hint ( array $key_pattern )

Parametry

key_pattern

Indexes to use for the query.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::hasNext
MongoCursor::immortal
MongoCursor


Sets whether this cursor will timeout

MongoCursor::hint
MongoCursor::info
MongoCursor
PHP Manual

MongoCursor::immortal

(PECL mongo >=1.0.1)

MongoCursor::immortal — Sets whether this cursor will timeout

Opis

public MongoCursor MongoCursor::immortal ([ bool $liveForever = true ] )

After remaining idle for some amount of time, cursor, by default, "die." This is generally the behavior one wants. The database cleans up a cursor once all of its results have been sent to the client, but if the client doesn't request all of the results, the cursor will languish there, taking up resources. Thus, after a few minutes, the cursor "times out" and the database assumes the client has gotten everything it needs and cleans up its the cursor's resources.

If, for some reason, you need a cursor to hang around for a long time, you can prevent the database from cleaning it up by using this method. However, if you make a cursor immortal, you need to iterate through all of its results (or at least until Cursor::dead() returns TRUE) or the cursor will hang around the database forever, taking up resources.

Parametry

liveForever

If the cursor should be immortal.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::hint
MongoCursor::info
MongoCursor


Gets the query, fields, limit, and skip for this cursor

MongoCursor::immortal
MongoCursor::key
MongoCursor
PHP Manual

MongoCursor::info

(PECL mongo >=1.0.5)

MongoCursor::info — Gets the query, fields, limit, and skip for this cursor

Opis

public array MongoCursor::info ( void )

This can be called before or after the query.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the namespace, limit, skip, query, and fields for this cursor.

Rejestr zmian

Wersja | Opis
1.0.10 | Added started_iterating field, a boolean indicating if cursor is pre- or post-query.
1.1.0 | Added a number of other fields, including id (the cursor id), at (the driver's counter of which document is current), numReturned (the number returned by the server in the current batch), and server (which server the query was sent to—useful in conjunction with MongoCursor::slaveOkay()).

Przykłady

Przykład #1 MongoCursor::info() example

<?php

$m = new Mongo();
$cursor = $m->foo->bar->find(array("x" => 4), array("y" => false));
var_dump($cursor->info());

?>

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

array(5) {
  ["ns"]=>
  string(7) "foo.bar"
  ["limit"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["query"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["fields"]=>
  array(1) {
    ["y"]=>
    int(0)
  }
}
MongoCursor::immortal
MongoCursor::key
MongoCursor


Returns the current result's _id

MongoCursor::info
MongoCursor::limit
MongoCursor
PHP Manual

MongoCursor::key

(PECL mongo >=0.9.0)

MongoCursor::key — Returns the current result's _id

Opis

public string MongoCursor::key ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current result's _id as a string.

MongoCursor::info
MongoCursor::limit
MongoCursor


Limits the number of results returned

MongoCursor::key
MongoCursor::next
MongoCursor
PHP Manual

MongoCursor::limit

(PECL mongo >=0.9.0)

MongoCursor::limit — Limits the number of results returned

Opis

public MongoCursor MongoCursor::limit ( int $num )

Parametry

num

The number of results to return.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

Zobacz też:

MongoDB core docs on » limit.

MongoCursor::key
MongoCursor::next
MongoCursor


Advances the cursor to the next result

MongoCursor::limit
MongoCursor::partial
MongoCursor
PHP Manual

MongoCursor::next

(PECL mongo >=0.9.0)

MongoCursor::next — Advances the cursor to the next result

Opis

public void MongoCursor::next ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

NULL.

Błędy/Wyjątki

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

MongoCursor::limit
MongoCursor::partial
MongoCursor


If this query should fetch partial results from mongos if a shard is down

MongoCursor::next
MongoCursor::reset
MongoCursor
PHP Manual

MongoCursor::partial

(PECL mongo >=1.2.0)

MongoCursor::partial — If this query should fetch partial results from mongos if a shard is down

Opis

public MongoCursor MongoCursor::partial ([ bool $okay = true ] )

This option allows mongos to send partial query results if a shard is unreachable. This is only applicable when running a sharded MongoDB cluster and connecting to a mongos.

If a shard goes down and a query needs to be sent to that shard, mongos will return the results (if any) from shards it already contacted, then an error message that it could not reach the shard (a MongoCursorException in PHP). If you would like to get whatever results mongos can provide and no exception, you can use this method. Note that this means that you won't have an indication that a shard is down in your query response.

This has no effect on the query if all shards are reachable. This flag was implemented in MongoDB version 1.7.5, so will only work with that version and higher.

Parametry

okay

If receiving partial results is okay.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::next
MongoCursor::reset
MongoCursor


Clears the cursor

MongoCursor::partial
MongoCursor::rewind
MongoCursor
PHP Manual

MongoCursor::reset

(PECL mongo >=0.9.0)

MongoCursor::reset — Clears the cursor

Opis

public void MongoCursor::reset ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

NULL.

MongoCursor::partial
MongoCursor::rewind
MongoCursor


Returns the cursor to the beginning of the result set

MongoCursor::reset
MongoCursor::skip
MongoCursor
PHP Manual

MongoCursor::rewind

(PECL mongo >=0.9.0)

MongoCursor::rewind — Returns the cursor to the beginning of the result set

Opis

public void MongoCursor::rewind ( void )

This is identical to the function:

<?php

public function rewind() {
    $this->reset();
    $this->next();
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

NULL.

Błędy/Wyjątki

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

MongoCursor::reset
MongoCursor::skip
MongoCursor


Skips a number of results

MongoCursor::rewind
MongoCursor::slaveOkay
MongoCursor
PHP Manual

MongoCursor::skip

(PECL mongo >=0.9.0)

MongoCursor::skip — Skips a number of results

Opis

public MongoCursor MongoCursor::skip ( int $num )

Parametry

num

The number of results to skip.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::rewind
MongoCursor::slaveOkay
MongoCursor


Sets whether this query can be done on a slave

MongoCursor::skip
MongoCursor::snapshot
MongoCursor
PHP Manual

MongoCursor::slaveOkay

(PECL mongo >=0.9.4)

MongoCursor::slaveOkay — Sets whether this query can be done on a slave

Opis

public MongoCursor MongoCursor::slaveOkay ([ bool $okay = true ] )

Calling this will make the driver route reads to slaves if:

  • You are using a replica set and
  • You created a Mongo instance using the option "replicaSet" => true and
  • There is a healthy slave that can be reached by the driver.
You can check which server was used for this query by calling MongoCursor::info() after running the query. It's server field will show which server the query was sent to.

Note that you should use this function even if you do not use the automatic routing to slaves. If you connect directly to a secondary in a replica set, you still need to call this function, which basically tells the database that you are aware that you might be getting older data and you're okay with that. If you do not call this, you'll get "not master" errors when you try to query.

This method will override the static class variable
MongoCursor::slaveOkay.  It will also override
Mongo::setSlaveOkay(),
MongoDB::setSlaveOkay() and
MongoCollection::setSlaveOkay().

Parametry

okay

If it is okay to query the slave.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

Przykłady

Przykład #1 MongoCursor::slaveOkay() example

<?php

MongoCursor::$slaveOkay = false;

// cannot query slave
$cursor = $collection->find();

// can query slave
$cursor = $collection->find()->slaveOkay();

MongoCursor::$slaveOkay = true;

// can query slave
$cursor = $collection->find();

// cannot query slave
$cursor = $collection->find()->slaveOkay(false);

?>
MongoCursor::skip
MongoCursor::snapshot
MongoCursor


Use snapshot mode for the query

MongoCursor::slaveOkay
MongoCursor::sort
MongoCursor
PHP Manual

MongoCursor::snapshot

(PECL mongo >=0.9.4)

MongoCursor::snapshot — Use snapshot mode for the query

Opis

public MongoCursor MongoCursor::snapshot ( void )

Use snapshot mode for the query. Snapshot mode assures no duplicates are returned, or objects missed, which were present at both the start and end of the query's execution (if an object is new during the query, or deleted during the query, it may or may not be returned, even with snapshot mode).

Note that short query responses (less than 1MB) are always effectively snapshotted.

Currently, snapshot mode may not be used with sorting or explicit hints.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

MongoCursor::slaveOkay
MongoCursor::sort
MongoCursor


Sorts the results by given fields

MongoCursor::snapshot
MongoCursor::tailable
MongoCursor
PHP Manual

MongoCursor::sort

(PECL mongo >=0.9.0)

MongoCursor::sort — Sorts the results by given fields

Opis

public MongoCursor MongoCursor::sort ( array $fields )

Parametry

fields

An array of fields by which to sort. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort.

Each result is first sorted on the first field in the array, then (if it exists) on the second field in the array, etc. This means that the order of the fields in the fields array is important. See also the examples section.

Zwracane wartości

Returns the same cursor that this method was called on.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

Przykłady

Przykład #1 MongoCursor::sort() example

<?php
// Sort on field x, ascending
$cursor->sort(array('x' => 1));

// The order in the associative array is important. For instance, these two
// examples will yield different results:

// Sort on date ascending and age descending
$cursor->sort(array('date' => 1, 'age' => -1));

// Sort on age descending and date ascending
$cursor->sort(array('age' => -1, 'date' => 1));
?>
MongoCursor::snapshot
MongoCursor::tailable
MongoCursor


Sets whether this cursor will be left open after fetching the last results

MongoCursor::sort
MongoCursor::timeout
MongoCursor
PHP Manual

MongoCursor::tailable

(PECL mongo >=0.9.4)

MongoCursor::tailable — Sets whether this cursor will be left open after fetching the last results

Opis

public MongoCursor MongoCursor::tailable ([ bool $tail = true ] )

Mongo has a feature known as tailable cursors which are similar to the Unix "tail -f" command.

Tailable means cursor is not closed when the last data is retrieved. Rather, the cursor marks the final object's position. you can resume using the cursor later, from where it was located, if more data were received.

Like any "latent cursor", the cursor may become invalid at some point -- for example if that final object it references were deleted. Thus, you should be prepared to requery if the cursor is MongoCursor::dead().

Parametry

tail

If the cursor should be tailable.

Zwracane wartości

Returns this cursor.

Błędy/Wyjątki

Throws MongoCursorException if this cursor has started iterating.

Przykłady

Przykład #1 MongoCursor::tailable() example

<?php

$cursor = $collection->find()->tailable();

$results = array();

while (1) {
    if (!$cursor->hasNext()) {
        // we've read all the results, exit
        if ($cursor->dead()) {
            break;
        }
        // read all results so far, wait for more
        sleep(10);
    }
    else {
        $results[] = $cursor->getNext();
    }
}

?>
MongoCursor::sort
MongoCursor::timeout
MongoCursor


Sets a client-side timeout for this query

MongoCursor::tailable
MongoCursor::valid
MongoCursor
PHP Manual

MongoCursor::timeout

(PECL mongo >=1.0.3)

MongoCursor::timeout — Sets a client-side timeout for this query

Opis

public MongoCursor MongoCursor::timeout ( int $ms )

A timeout can be set at any time and will affect subsequent queries on the cursor, including fetching more results from the database. For example, to wait forever for an initial response but timeout after 100 ms for subsequent results, one could say:

<?php

$cursor = $collection->find();

// $cursor->hasNext() executes the query.  No timeout has been set, so the
// program will wait as long as necessary for a response.

while ($cursor->hasNext()) {
    $cursor->timeout(100);

    // now the timeout has been set, so if the cursor needs to get more results
    // from the database, it will only wait 100 ms for the database's reply

    try {
        print_r($cursor->getNext());
    }
    catch(MongoCursorTimeoutException $e) {
        echo "query took too long!";
    }
}

?>

A timeout of 0 (or a negative number) will wait forever so it can be used to reset the cursor if a timeout is no longer needed.

Parametry

ms

The number of milliseconds for the cursor to wait for a response. By default, the cursor will wait forever.

Zwracane wartości

This cursor.

Przykłady

Przykład #1 MongoCursor::timeout() example

A query where the cursor waits for one second for a response.

<?php

$cursor = $collection->find()->timeout(1000);

try {
  foreach ($cursor as $value) {
    print_r($value);
  }
}
catch(MongoCursorTimeoutException $e) {
  echo "query took too long!";
}

?>

Błędy/Wyjątki

Causes methods that fetch results to throw MongoCursorTimeoutExceptions if the query takes longer than the number of milliseconds specified.

MongoCursor::tailable
MongoCursor::valid
MongoCursor


Checks if the cursor is reading a valid result.

MongoCursor::timeout
Types
MongoCursor
PHP Manual

MongoCursor::valid

(PECL mongo >=0.9.0)

MongoCursor::valid — Checks if the cursor is reading a valid result.

Opis

public bool MongoCursor::valid ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

If the current result is not null.

MongoCursor::timeout
Types
MongoCursor


Types

Spis treści

  • MongoId
  • MongoCode
  • MongoDate
  • MongoRegex
  • MongoBinData
  • MongoInt32
  • MongoInt64
  • MongoDBRef
  • MongoMinKey
  • MongoMaxKey
  • MongoTimestamp

MongoDB allows programmers to save and query for data expressed in all of the basic PHP types, compound types (arrays, associative arrays, and objects), and a half-dozen classes provided by the MongoDB PHP driver (for regular expressions, dates, and other specialized applications).

Booleans and NULL

TRUE, FALSE, and NULL can be used as-is.

Numbers

Numbers are distinct from strings in MongoDB: "123" does not match 123. Thus, if you want to make sure numbers are sorted and matched correctly, you must make sure that they are actually saved as numbers.

<?php

$doc = array("a" => 123, "b" => "123");
$collection->insert($doc);

$doc->find(array("a" => 123));   // matches
$doc->find(array("a" => "123")); // doesn't match
$doc->find(array("a" => 123.0)); // matches
$doc->find(array("b" => 123));   // doesn't match
$doc->find(array("b" => "123")); // matches

?>

As noted above, floating point numbers do compare with/match integer numbers as one would expect.

Large Numbers

By default, on a 32-bit system, numbers are sent to the database as 32-bit integers. On a 64-bit system, they are sent as 64-bit integers. For backwards compatibility, all systems deserialize 64-bit integers as floating point numbers. Floating point numbers are not exact. If you need exact values, you must tweak your » php.ini settings.

On a 32-bit system, if mongo.long_as_object is set, 64-bit integers will be returns as MongoInt64 objects. The integer will be stored in the value field with perfect precision (as a string). You can also use MongoInt64 to save 64-bit integers on 32-bit machines.

On 64-bit systems, you can either set mongo.long_as_object or set mongo.native_long. mongo.native_long will return 64-bit integers and "normal" PHP integers. You can use MongoInt32 to save 32-bit integers on 64-bit machines.

You should set the mongo.long_as_object and mongo.native_long behavior that you plan to use, even if it is the default behavior (to protect against future changes to the defaults).

See also: » php.ini Options, MongoInt32, MongoInt64.

Strings

Strings must be UTF-8. Non-UTF-8 strings must either be converted to UTF-8 before being sent to the database or saved as binary data.

Regular expressions can be used to match strings, and are expressed using the MongoRegex class.

Binary Data

Non-UTF-8 strings, images, and any other binary data should be sent to the database using the MongoBinData type.

Dates

Dates can be created using the MongoDate class. They are stored as milliseconds since the epoch.

MongoTimestamp is not for saving dates or timestamps, it is used internally by MongoDB. Unless you are creating a tool that interacts with the internals of replication or sharding, you should use MongoDate, not MongoTimestamp.

Unique Ids

The driver will automatically create an _id field before inserting a document (unless one is specified by the user). This field is an instance of MongoId (called "ObjectId" in most other languages).

These ids are 12 bytes long and composed of:

  • 4 bytes of timestamp

    No two records can have the same id if they were inserted at different times.

  • 3 bytes machine id

    No two records can have the same id if they were inserted on different machines

  • 2 bytes thread id

    No two records can have the same id if they were inserted by different threads running on the same machine.

  • 3 bytes incrementing value

    Each time an id is created, a global counter is incremented and used as the increment value of the next id.

Thus, no two records can have the same id unless a single process on a single machine managed to insert 256^3 (over 16 million) documents in one second, overflowing the increment field.

JavaScript

MongoDB comes with a JavaScript engine, so you can embed JavaScript in queries (using a $where clause), send it directly to the database to be executed, and use it to perform aggregations.

For security, use MongoCode's scope field to use PHP variables in JavaScript. Code that does not require external values can either use MongoCode or just be a string. See the » section on security for more information about sending JavaScript to the database.

Arrays and Objects

Arrays and objects can also be saved to the database. An array with ascending numeric keys will be saved as a an array, anything else will be saved as an object.

<?php

// $scores will be saved as an array
$scores = array(98, 100, 73, 85);
$collection->insert(array("scores" => $scores));

// $scores will be saved as an object
$scores = array("quiz1" => 98, "midterm" => 100, "quiz2" => 73, "final" => 85);
$collection->insert(array("scores" => $scores));

?>

If you query for these objects using the database shell, they will look like:

> db.students.find()
{ "_id" : ObjectId("4b06beada9ad6390dab17c43"), "scores" : [ 98, 100, 73, 85 ] }
{ "_id" : ObjectId("4b06bebea9ad6390dab17c44"), "scores" : { "quiz1" : 98, "midterm" : 100, "quiz2" : 73, "final" : 85 } }

The database can also save arbitrary PHP objects (although they will be returned as associative arrays). The fields are used for the key/value pairs. For example, a blog post might look like:

<?php

  // the blog post class
  class Post {

  var $author;
  var $content;
  var $comments = array();
  var $date;

  public function __construct($author, $content) {
  $this->author = $author;
$this->content = $content;
    $this->date = new MongoDate();
  }

  public function setTitle($title) {
    $this->title = $title;
  }
}

// create a simple blog post and insert it into the database
$post1 = new Post("Adam", "This is a blog post");

$blog->insert($post1);

// there is nothing restricting the type of the "author" field, so we can make
// it a nested object
$author = array("name" => "Fred", "karma" => 42);
$post2 = new Post($author, "This is another blog post.");

// we create an extra field by setting the title
$post2->setTitle("Second Post");

$blog->insert($post2);

?>

From the database shell, this will look something like:

> db.blog.find()
{ "_id" : ObjectId("4b06c263edb87a281e09dad8"), "author" : "Adam", "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:22:59 GMT-0500 (EST)" }
{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "author" : { "name" : "Fred", "karma" : 42 }, "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:23:30 GMT-0500 (EST)", "title" : "Second Post" }

The driver will not detect reference loops in arrays and objects. For example, this will give a fatal error:

<?php

$collection->insert($GLOBALS);

?>

Fatal error: Nesting level too deep - recursive dependency?
If you need to insert documents that may have recursive dependency, you have to check for it yourself before passing it to the driver.

MongoCursor::valid
MongoId
Mongo


The MongoId class

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

Wstęp

A unique identifier created for database objects. If an object is inserted into the database without an _id field, an _id field will be added to it with a MongoId instance as its value. If the data has a naturally occuring unique field (say, a username or timestamp) it is fine to use this as the _id field instead, and it will not be replaced with a MongoId.

Instances of the MongoId class fulfill the role that autoincrementing does in a relational database: to provide a unique key if the data does not natually have one. Autoincrementing does not work well with a sharded database, as it is impossible to find what the next number should be quickly. This class fulfills the constraints of quickly generating a value that is unique across shards.

Each MongoId is 12 bytes (making its string form 24 hexidecimal characters). The first four bytes are a timestamp, the next three are a hash of the client machine's hostname, the next two are the two least significant bytes of the process id running the script, and the last three bytes are an incrementing value.

MongoIds are serializable/unserializable. Their serialized form is similar to their string form:

C:7:"MongoId":24:{4af9f23d8ead0e1d32000000}

Krótki opis klasy

MongoId {
public string $id = NULL ;
/* Metody */
public __construct ([ string $id = NULL ] )
public static string getHostname ( void )
public int getInc ( void )
public int getPID ( void )
public int getTimestamp ( void )
public static MongoId __set_state ( array $props )
public string __toString ( void )
}

Fields

id
This field contains the string representation of this object.

Zobacz też:

MongoDB core docs on » ids.

Spis treści

  • MongoId::__construct — Creates a new id
  • MongoId::getHostname — Gets the hostname being used for this machine's ids
  • MongoId::getInc — Gets the incremented value to create this id
  • MongoId::getPID — Gets the process id used to create this
  • MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created
  • MongoId::__set_state — Create a dummy MongoId
  • MongoId::__toString — Returns a hexidecimal representation of this id
Types
MongoId::__construct
Types


Creates a new id

MongoId
MongoId::getHostname
MongoId
PHP Manual

MongoId::__construct

(PECL mongo >= 0.8.0)

MongoId::__construct — Creates a new id

Opis

public MongoId::__construct ([ string $id = NULL ] )

Parametry

id

A string to use as the id. Must be 24 hexidecimal characters. If an invalid string is passed to this constructor, the constructor will ignore it and create a new id value.

Zwracane wartości

Returns a new id.

Przykłady

Przykład #1 MongoId::__construct() example

This example shows how to create a new id. This is seldom necessary, as the driver adds an id to arrays automatically before storing them in the database.

<?php

  $id1 = new MongoId();
  echo "$id1\n";

  $id2 = new MongoId();
  echo "$id2\n";

  ?>

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

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d

Przykład #2 Parameter example

This example shows how to use a string parameter to initialize a MongoId with a given value.

<?php
  $id1 = new MongoId();

  // create a new id from $id1
  $id2 = new MongoId("$id1");

  // show that $id1 and $id2 have the same hexidecimal value
  var_dump($id1 == $id2);
  ?>

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

bool(true)

Zobacz też:

  • MongoId::__toString() - Returns a hexidecimal representation of this id

MongoId
MongoId::getHostname
MongoId


Gets the hostname being used for this machine's ids

MongoId::__construct
MongoId::getInc
MongoId
PHP Manual

MongoId::getHostname

(PECL mongo >= 1.0.8)

MongoId::getHostname — Gets the hostname being used for this machine's ids

Opis

public static string MongoId::getHostname ( void )

This returns the hostname MongoId is using to generate unique ids. This should be the same value gethostname() returns.

It is identical to the function:

<?php

public static function getHostname() {
    return gethostname();
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the hostname.

MongoId::__construct
MongoId::getInc
MongoId


Gets the incremented value to create this id

MongoId::getHostname
MongoId::getPID
MongoId
PHP Manual

MongoId::getInc

(PECL mongo >= 1.0.11)

MongoId::getInc — Gets the incremented value to create this id

Opis

public int MongoId::getInc ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the incremented value used to create this MongoId.

MongoId::getHostname
MongoId::getPID
MongoId


Gets the process id used to create this

MongoId::getInc
MongoId::getTimestamp
MongoId
PHP Manual

MongoId::getPID

(PECL mongo >= 1.0.11)

MongoId::getPID — Gets the process id used to create this

Opis

public int MongoId::getPID ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the PID used to create this MongoId.

MongoId::getInc
MongoId::getTimestamp
MongoId


Gets the number of seconds since the epoch that this id was created

MongoId::getPID
MongoId::__set_state
MongoId
PHP Manual

MongoId::getTimestamp

(PECL mongo >= 1.0.1)

MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created

Opis

public int MongoId::getTimestamp ( void )

This returns the same thing as running time() when the id is created.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the number of seconds since the epoch that this id was created. There are only four bytes of timestamp stored, so MongoDate is a better choice for storing exact or wide-ranging times.

MongoId::getPID
MongoId::__set_state
MongoId


Create a dummy MongoId

MongoId::getTimestamp
MongoId::__toString
MongoId
PHP Manual

MongoId::__set_state

(PECL mongo >= 1.0.8)

MongoId::__set_state — Create a dummy MongoId

Opis

public static MongoId MongoId::__set_state ( array $props )

This function is only used by PHP internally, it shouldn't need to ever be called by the user.

It is identical to the function:

<?php

public static function __set_state($props) {
    return new MongoId("000000000000000000000000");
}

?>

Parametry

props

Theoretically, an array of properties used to create the new id. However, as MongoId instances have no properties, this is not used.

Zwracane wartości

A new id with the value "000000000000000000000000".

MongoId::getTimestamp
MongoId::__toString
MongoId


Returns a hexidecimal representation of this id

MongoId::__set_state
MongoCode
MongoId
PHP Manual

MongoId::__toString

(PECL mongo >= 0.8.0)

MongoId::__toString — Returns a hexidecimal representation of this id

Opis

public string MongoId::__toString ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This id.

Przykłady

Przykład #1 MongoId::__toString() example

<?php

$m = new Mongo();
$collection = $m->selectDB("foo")->selectCollection("bar");

$collection->insert(array( "x" => "y" ));
$collection->insert(array( "x" => "y" ));

$cursor = $collection->find();
$r1 = $cursor->next();
$r2 = $cursor->next();

echo $r1["_id"] . "\n";
echo $r2["_id"] . "\n";

?>

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

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d
MongoId::__set_state
MongoCode
MongoId


The MongoCode class

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

Wstęp

Represents JavaScript code for the database.

MongoCode objects are composed of two parts: a string of code and an optional scope. The string of code must be valid JavaScript. The scope is a associative array of variable name/value pairs.

Krótki opis klasy

MongoCode {
/* Metody */
public __construct ( string $code [, array $scope = array() ] )
public string __toString ( void )
}

Spis treści

  • MongoCode::__construct — Creates a new code object
  • MongoCode::__toString — Returns this code as a string
MongoId::__toString
MongoCode::__construct
Types


Creates a new code object

MongoCode
MongoCode::__toString
MongoCode
PHP Manual

MongoCode::__construct

(PECL mongo >= 0.8.3)

MongoCode::__construct — Creates a new code object

Opis

public MongoCode::__construct ( string $code [, array $scope = array() ] )

Parametry

code

A string of code.

scope

The scope to use for the code.

Zwracane wartości

Returns a new code object.

Przykłady

Przykład #1 MongoCode::__construct() example

<?php

$code = new MongoCode('function() { '.
    'for(i=0;i<10;i++) {'.
        'db.foo.update({z : i}, {z : x});'.
    '}'.
    'return x-1;'.
 '}', array("x" => 4));
var_dump($code);

?>

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

object(MongoCode)#1 (2) {
  ["scope"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["code"]=>
  string(80) "function() { for(i=0;i<10;i++) { db.foo.update({z : i}, {z : x}); } return x-1; }"
}

Przykład #2 Using MongoCode() with $where

This example queries a collection for elements where the 'x' fields is less than $y. Notice that PHP objects can be passed into the JavaScript scope and that the JavaScript function returns a boolean.

<?php

$cursor = $collection->find(array('$where' => new MongoCode('function() { return this.x < y; }', array('y'=>$y))));

?>
MongoCode
MongoCode::__toString
MongoCode


Returns this code as a string

MongoCode::__construct
MongoDate
MongoCode
PHP Manual

MongoCode::__toString

(PECL mongo >= 0.8.3)

MongoCode::__toString — Returns this code as a string

Opis

public string MongoCode::__toString ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This code, the scope is not returned.

Przykłady

Przykład #1 MongoCode::__toString() example

<?php

$code = new MongoCode('return x;', array("x"=>"hi"));
echo "$code\n";

$code = new MongoCode('function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }');
echo "$code\n";

?>

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

return x;
function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }
MongoCode::__construct
MongoDate
MongoCode


The MongoDate class

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

Wstęp

Represent date objects for the database. This class should be used to save dates to the database and to query for dates. For example:

<?php

// save a date to the database
$collection->save(array("ts" => new MongoDate()));

$start = new MongoDate(strtotime("2010-01-15 00:00:00"));
$end = new MongoDate(strtotime("2010-01-30 00:00:00"));

// find dates between 1/15/2010 and 1/30/2010
$collection->find(array("ts" => array('$gt' => $start, '$lte' => $end)));

?>

MongoDB stores dates as milliseconds past the epoch. This means that dates do not contain timezone information. Timezones must be stored in a separate field if needed. Second, this means that any precision beyond milliseconds will be lost when the document is sent to/from the database.

Krótki opis klasy

MongoDate {
/* Fields */
public int $sec ;
public int $usec ;
/* Metody */
public __construct ([ int $sec = time() [, int $usec = 0 ]] )
public string __toString ( void )
}

Spis treści

  • MongoDate::__construct — Creates a new date.
  • MongoDate::__toString — Returns a string representation of this date
MongoCode::__toString
MongoDate::__construct
Types


Creates a new date.

MongoDate
MongoDate::__toString
MongoDate
PHP Manual

MongoDate::__construct

(PECL mongo >= 0.8.1)

MongoDate::__construct — Creates a new date.

Opis

public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )

Creates a new date. If no parameters are given, the current time is used.

Parametry

sec

Number of seconds since January 1st, 1970.

usec

Microseconds.

Zwracane wartości

Returns this new date.

Przykłady

Przykład #1 MongoDate::__construct() example

This example demonstrates creating a new date with the current time and a new date with a given time.

<?php

$d = new MongoDate();
echo "$d\n";
$d = new MongoDate(1234567890);
echo "$d\n";
$d = new MongoDate(strtotime("2009-05-01 00:00:01"));
echo "$d\n";

?>

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

0.23660600 1235685067
0.00000000 1234567890
0.00000000 1241150401

Zobacz też:

  • MongoDate::__toString() - Returns a string representation of this date

MongoDate
MongoDate::__toString
MongoDate


Returns a string representation of this date

MongoDate::__construct
MongoRegex
MongoDate
PHP Manual

MongoDate::__toString

(PECL mongo >= 0.8.1)

MongoDate::__toString — Returns a string representation of this date

Opis

public string MongoDate::__toString ( void )

Returns a string representation of this date, similar to the representation returned by microtime().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This date.

MongoDate::__construct
MongoRegex
MongoDate


The MongoRegex class

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

Wstęp

This class can be used to create regular expressions. Typically, these expressions will be used to query the database and find matching strings. More unusually, they can be saved to the database and retrieved.

Mongo recognizes six regular expression flags:

  • i

    Case insensitive

  • m

    Multiline

  • x

    Can contain comments

  • l

    locale

  • s

    dotall, "." matches everything, including newlines

  • u

    match unicode

Krótki opis klasy

MongoRegex {
/* Fields */
public string $regex ;
public string $flags ;
/* Metody */
public __construct ( string $regex )
public string __toString ( void )
}

Spis treści

  • MongoRegex::__construct — Creates a new regular expression
  • MongoRegex::__toString — A string representation of this regular expression
MongoDate::__toString
MongoRegex::__construct
Types


Creates a new regular expression

MongoRegex
MongoRegex::__toString
MongoRegex
PHP Manual

MongoRegex::__construct

(PECL mongo >= 0.8.1)

MongoRegex::__construct — Creates a new regular expression

Opis

public MongoRegex::__construct ( string $regex )

Creates a new regular expression.

Parametry

regex

Regular expression string of the form /expr/flags.

Zwracane wartości

Returns a new regular expression.

Przykłady

Przykład #1 MongoRegex::__construct() example

This example uses a regular expression to query for all documents with a username field matching a regular expression.

<?php

$joe_search = new MongoRegex("/j[o0]e/i");
$cursor = $collection->find(array("username" => $joe_search));

?>

Zobacz też:

  • MongoRegex::__toString() - A string representation of this regular expression

MongoRegex
MongoRegex::__toString
MongoRegex


A string representation of this regular expression

MongoRegex::__construct
MongoBinData
MongoRegex
PHP Manual

MongoRegex::__toString

(PECL mongo >= 0.8.1)

MongoRegex::__toString — A string representation of this regular expression

Opis

public string MongoRegex::__toString ( void )

Returns a string representation of this regular expression.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This regular expression in the form "/expr/flags".

Przykłady

Przykład #1 MongoRegex::__toString() example

<?php

$r = new MongoRegex( "/[a-fA-F0-9]{16}/g" );
echo $r->regex . "\n";
echo $r->flags . "\n";
echo "$r\n";

?>

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

[a-fA-F0-9]{16}
g
/[a-fA-F0-9]{16}/g

MongoRegex::__construct
MongoBinData
MongoRegex


The MongoBinData class

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

Wstęp

An object that can be used to store or retrieve binary data from the database.

The maximum size of a single object that can be inserted into the database is 4Mb. For data that is larger than this (movies, music, Henry Kissinger's autobiography), use MongoGridFS. For data that is smaller than 4Mb, it's probably be easier to just embed it into the document using MongoBinData.

For example, to embed an image in a document, one could write:

<?php

$profile = array("username" => "foobity",
    "pic" => new MongoBinData(file_get_contents("gravatar.jpg"))
);

$users->save($profile);

?>

This class contains a type field, which currently gives no additional functionality in the driver or the database. There are five predefined types (which are the class constants listed below), and the user can create their own (at the risk of the BSON spec catching up with them). By default, the PHP driver always uses type 2: a byte array.

Krótki opis klasy

MongoBinData {
/* Stałe */
const int FUNC = 1 ;
const int BYTE_ARRAY = 2 ;
const int UUID = 3 ;
const int MD5 = 5 ;
const int CUSTOM = 128 ;
/* Fields */
public string $bin ;
public int $type = 2 ;
/* Metody */
public __construct ( string $data [, int $type = 2 ] )
public string __toString ( void )
}

Stałe predefiniowane

Binary Data Types

MongoBinData::FUNC
0x01
Function.
MongoBinData::BYTE_ARRAY
0x02
Array of bytes.
MongoBinData::UUID
0x03
Universally unique identifier.
MongoBinData::MD5
0x05
MD5.
MongoBinData::CUSTOM
0xf0
User-defined type.

Spis treści

  • MongoBinData::__construct — Creates a new binary data object.
  • MongoBinData::__toString — The string representation of this binary data object.
MongoRegex::__toString
MongoBinData::__construct
Types


Creates a new binary data object.

MongoBinData
MongoBinData::__toString
MongoBinData
PHP Manual

MongoBinData::__construct

(PECL mongo >= 0.8.1)

MongoBinData::__construct — Creates a new binary data object.

Opis

public MongoBinData::__construct ( string $data [, int $type = 2 ] )

Creates a new binary data object.

There are five types of binary data currently recognized by the BSON spec: function (0x01), byte array (0x02), UUID (0x03), MD5 (0x05), and user defined (0x80). The default type is byte array (0x02). There is no particular difference in how the driver or server interpret different types, so by and large they are irrelevant for now. Any number (between 0 and 255) could be used for type, if the user is willing to assume the risk that the database might eventually do something with binary data based on type.

Parametry

data

Binary data.

type

Data type.

Zwracane wartości

Returns a new binary data object.

MongoBinData
MongoBinData::__toString
MongoBinData


The string representation of this binary data object.

MongoBinData::__construct
MongoInt32
MongoBinData
PHP Manual

MongoBinData::__toString

(PECL mongo >= 0.8.1)

MongoBinData::__toString — The string representation of this binary data object.

Opis

public string MongoBinData::__toString ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the string "<Mongo Binary Data>". To access the contents of a MongoBinData, use the bin field.

MongoBinData::__construct
MongoInt32
MongoBinData


The MongoInt32 class

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

Wstęp

The class can be used to save 32-bit integers to the database on a 64-bit system.

Krótki opis klasy

MongoInt32 {
/* Fields */
public string $value ;
/* Metody */
public __construct ( string $value )
public string __toString ( void )
}

Fields

value
This is the string value of the 64-bit number. For instance, 123's value would be "123".

Spis treści

  • MongoInt32::__construct — Creates a new 32-bit integer.
  • MongoInt32::__toString — Returns the string representation of this 32-bit integer.
MongoBinData::__toString
MongoInt32::__construct
Types


Creates a new 32-bit integer.

MongoInt32
MongoInt32::__toString
MongoInt32
PHP Manual

MongoInt32::__construct

(PECL mongo >= 1.0.9)

MongoInt32::__construct — Creates a new 32-bit integer.

Opis

public MongoInt32::__construct ( string $value )

Creates a new 32-bit number with the given value.

Parametry

value

A number.

Zwracane wartości

Returns a new integer.

MongoInt32
MongoInt32::__toString
MongoInt32


Returns the string representation of this 32-bit integer.

MongoInt32::__construct
MongoInt64
MongoInt32
PHP Manual

MongoInt32::__toString

(PECL mongo >= 1.0.9)

MongoInt32::__toString — Returns the string representation of this 32-bit integer.

Opis

public string MongoInt32::__toString ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the string representation of this integer.

MongoInt32::__construct
MongoInt64
MongoInt32


The MongoInt64 class

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

Wstęp

The class can be used to save 64-bit integers to the database on a 32-bit system.

Krótki opis klasy

MongoInt64 {
/* Fields */
public string $value ;
/* Metody */
public __construct ( string $value )
public string __toString ( void )
}

Fields

value
This is the string value of the 64-bit number. For instance, 123's value would be "123".

Spis treści

  • MongoInt64::__construct — Creates a new 64-bit integer.
  • MongoInt64::__toString — Returns the string representation of this 64-bit integer.
MongoInt32::__toString
MongoInt64::__construct
Types


Creates a new 64-bit integer.

MongoInt64
MongoInt64::__toString
MongoInt64
PHP Manual

MongoInt64::__construct

(PECL mongo >= 1.0.9)

MongoInt64::__construct — Creates a new 64-bit integer.

Opis

public MongoInt64::__construct ( string $value )

Creates a new 64-bit number with the given value.

Parametry

value

A number.

Zwracane wartości

Returns a new integer.

MongoInt64
MongoInt64::__toString
MongoInt64


Returns the string representation of this 64-bit integer.

MongoInt64::__construct
MongoDBRef
MongoInt64
PHP Manual

MongoInt64::__toString

(PECL mongo >= 1.0.9)

MongoInt64::__toString — Returns the string representation of this 64-bit integer.

Opis

public string MongoInt64::__toString ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the string representation of this integer.

MongoInt64::__construct
MongoDBRef
MongoInt64


The MongoDBRef class

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

Wstęp

This class can be used to create lightweight links between objects in different collections.

Motivation: Suppose we need to refer to a document in another collection. The easiest way is to create a field in the current document. For example, if we had a "people" collection and an "addresses" collection, we might want to create a link between each person document and an address document:

<?php

$people = $db->people;
$addresses = $db->addresses;

$myAddress = array("line 1" => "123 Main Street",
    "line 2" => null,
    "city" => "Springfield",
    "state" => "Vermont",
    "country" => "USA");

// save the address
$addresses->insert($myAddress);

// save a person with a reference to the address
$me = array("name" => "Fred", "address" => $myAddress['_id']);
$people->insert($me);

?>

Then, later on, we can find the person's address by querying the "addresses" collection with the MongoId we saved in the "people" collection.

Suppose now that we have a more general case, where we don't know which collection (or even which database) contains the referenced document. MongoDBRef is a good choice for this case, as it is a common format that all of the drivers and the database understand.

If each person had a list of things they liked which could come from multiple collections, such as "hobbies", "sports", "books", etc., we could use MongoDBRefs to keep track of what "like" went with what collection:

<?php

$people = $db->selectCollection("people");

// model trains are in the "hobbies" collection
$trainRef = MongoDBRef::create("hobbies", $modelTrains['_id']);
// soccer is in the "sports" collection
$soccerRef = MongoDBRef::create("sports", $soccer['_id']);

// now we'll know what collections the items in the "likes" array came from when
// we retrieve this document
$people->insert(array("name" => "Fred", "likes" => array($trainRef, $soccerRef)));

?>

Database references can be thought of as hyperlinks: they give the unique address of another document, but they do not load it or automatically follow the link/reference.

A database reference is just a normal associative array, not an instance of MongoDBRef, so this class is a little different than the other data type classes. This class contains exclusively static methods for manipulating database references.

Krótki opis klasy

MongoDBRef {
/* Metody */
public static array create ( string $collection , mixed $id [, string $database ] )
public static array get ( MongoDB $db , array $ref )
public static bool isRef ( mixed $ref )
}

Zobacz też:

MongoDB core docs on » databases references.

Spis treści

  • MongoDBRef::create — Creates a new database reference
  • MongoDBRef::get — Fetches the object pointed to by a reference
  • MongoDBRef::isRef — Checks if an array is a database reference
MongoInt64::__toString
MongoDBRef::create
Types


Creates a new database reference

MongoDBRef
MongoDBRef::get
MongoDBRef
PHP Manual

MongoDBRef::create

(PECL mongo >= 0.9.0)

MongoDBRef::create — Creates a new database reference

Opis

public static array MongoDBRef::create ( string $collection , mixed $id [, string $database ] )

If no database is given, the current database is used.

Parametry

collection

Collection name (without the database name).

id

The _id field of the object to which to link.

database

Database name.

Zwracane wartości

Returns the reference.

Przykłady

Przykład #1 MongoDBRef::create() example

This creates a database reference to a document in the addresses collection. The MongoCollection::getName() function returns the name of the collection (not including the database name).

<?php
$addresses = $db->addresses;
$people = $db->people;

// save $address so it has an _id
$addresses->insert($address);

// create a reference
$ref = MongoDBRef::create($addresses->getName(), $address['_id']);

// set the field in $person
$person['address'] = $ref;
$people->save($person);
?>

Zobacz też:

  • MongoDB::createDBRef() - Creates a database reference
  • MongoCollection::createDBRef() - Creates a database reference

MongoDBRef
MongoDBRef::get
MongoDBRef


Fetches the object pointed to by a reference

MongoDBRef::create
MongoDBRef::isRef
MongoDBRef
PHP Manual

MongoDBRef::get

(PECL mongo >= 0.9.0)

MongoDBRef::get — Fetches the object pointed to by a reference

Opis

public static array MongoDBRef::get ( MongoDB $db , array $ref )

Parametry

db

Database to use.

ref

Reference to fetch.

Zwracane wartości

Returns the document to which the reference refers or NULL if the document does not exist (the reference is broken).

Przykłady

Przykład #1 MongoCollection::createDBRef() example

<?php

// get $person out of the db
$person = $people->findOne();

// dereference the address
$address = MongoDBRef::get($people->db, $person['address']);

?>

Zobacz też:

  • MongoDB::getDBRef() - Fetches the document pointed to by a database reference
  • MongoCollection::getDBRef() - Fetches the document pointed to by a database reference

MongoDBRef::create
MongoDBRef::isRef
MongoDBRef


Checks if an array is a database reference

MongoDBRef::get
MongoMinKey
MongoDBRef
PHP Manual

MongoDBRef::isRef

(PECL mongo >= 0.9.0)

MongoDBRef::isRef — Checks if an array is a database reference

Opis

public static bool MongoDBRef::isRef ( mixed $ref )

This not actually follow the reference, so it does not determine if it is broken or not. It merely checks that ref is in valid database reference format (in that it is an object or array with $ref and $id fields).

Parametry

ref

Array or object to check.

Zwracane wartości

Returns if ref is a reference.

MongoDBRef::get
MongoMinKey
MongoDBRef


The MongoMinKey class

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

Wstęp

MongoMinKey is a special type used by the database that evaluates to less than any other type. Thus, if a query is sorted by a given field in ascending order, any document with a MongoMinKey as its value will be returned first.

MongoMinKey has no associated fields, methods, or constants. It is merely the "smallest" thing that can be inserted into the database.

Krótki opis klasy

MongoMinKey {
}

Using MongoMinKey as a value

<?php

$collection->insert(array("task" => "lunch", "do by" => new MongoMinKey));
$collection->insert(array("task" => "staff meeting", "do by" => new MongoDate(strtotime("+4 days"))));

$cursor = $collection->find()->sort(array("do by" => 1));

?>

The cursor will contain the lunch document, then the staff meeting document. The lunch document will always be returned first, regardless of what else is added to the collection (unless other documents are added with MongoMinKey in the "do by" field).

MongoDBRef::isRef
MongoMaxKey
Types


The MongoMaxKey class

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

Wstęp

MongoMaxKey is a special type used by the database that evaluates to greater than any other type. Thus, if a query is sorted by a given field in ascending order, any document with a MongoMaxKey as its value will be returned last.

MongoMaxKey has no associated fields, methods, or constants. It is merely the "largest" thing that can be inserted into the database.

Krótki opis klasy

MongoMaxKey {
}

Using MongoMaxKey as a value

<?php

$collection->insert(array("task" => "dishes", "do by" => new MongoMaxKey));
$collection->insert(array("task" => "staff meeting", "do by" => new MongoDate(strtotime("+4 days"))));

$cursor = $collection->find()->sort(array("do by" => 1));

?>

The cursor will contain the staff meeting document, then the dishes document. The dishes document will always be returned last, regardless of what else is added to the collection (unless other documents are added with MongoMaxKey in the "do by" field).

MongoMinKey
MongoTimestamp
Types


The MongoTimestamp class

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

Wstęp

MongoTimestamp is used by sharding. If you're not looking to write sharding tools, what you probably want is MongoDate.

MongoTimestamp is 4 bytes of timestamp (seconds since the epoch) and 4 bytes of increment.

This class is not for measuring time, creating a timestamp on a document or automatically adding or updating a timestamp on a document. Unless you are writing something that interacts with the sharding internals, stop, go directly to MongoDate, do not pass go, do not collect 200 dollars. This is not the class you are looking for.

If you are writing sharding tools, read on.

Krótki opis klasy

MongoTimestamp {
/* Fields */
public int $sec = 0 ;
public int $inc = 0 ;
/* Metody */
public __construct ([ int $sec = time() [, int $inc ]] )
public string __toString ( void )
}

Spis treści

  • MongoTimestamp::__construct — Creates a new timestamp.
  • MongoTimestamp::__toString — Returns a string representation of this timestamp
MongoMaxKey
MongoTimestamp::__construct
Types


Creates a new timestamp.

MongoTimestamp
MongoTimestamp::__toString
MongoTimestamp
PHP Manual

MongoTimestamp::__construct

(PECL mongo >= 1.0.1)

MongoTimestamp::__construct — Creates a new timestamp.

Opis

public MongoTimestamp::__construct ([ int $sec = time() [, int $inc ]] )

Creates a new timestamp. If no parameters are given, the current time is used and the increment is automatically provided. The increment is set to 0 when the module is loaded and is incremented every time this constructor is called (without the $inc parameter passed in).

Parametry

sec

Number of seconds since January 1st, 1970.

inc

Increment.

Zwracane wartości

Returns this new timestamp.

Zobacz też:

  • MongoTimestamp::__toString() - Returns a string representation of this timestamp

MongoTimestamp
MongoTimestamp::__toString
MongoTimestamp


Returns a string representation of this timestamp

MongoTimestamp::__construct
GridFS Classes
MongoTimestamp
PHP Manual

MongoTimestamp::__toString

(PECL mongo >= 1.0.1)

MongoTimestamp::__toString — Returns a string representation of this timestamp

Opis

public string MongoTimestamp::__toString ( void )

Returns the "sec" field of this timestamp.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The seconds since epoch represented by this timestamp.

MongoTimestamp::__construct
GridFS Classes
MongoTimestamp


GridFS Classes

Spis treści

  • MongoGridFS
  • MongoGridFSFile
  • MongoGridFSCursor
MongoTimestamp::__toString
MongoGridFS
Mongo


The MongoGridFS class

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

Wstęp

Utilities for storing and retrieving files from the database.

GridFS is a storage specification all supported drivers implement. Basically, it defines two collections: files, for file metadata, and chunks, for file content. If the file is large, it will automatically be split into smaller chunks and each chunk will be saved as a document in the chunks collection.

Each document in the files collection contains the filename, upload date, and md5 hash. It also contains a unique _id field, which can be used to query the chunks collection for the file's content. Each document in the chunks collection contains a chunk of binary data, a files_id field that matches its file's _id, and the position of this chunk in the overall file.

For example, the files document is something like:

<?php
array("_id" => 123456789, "filename" => "foo.txt", "chunkSize" => 3, "length" => 12);
?>
and the chunks documents look like:
<?php
array("files_id" => 123456789, "n" => 0, "data" => new MongoBinData("abc"));
array("files_id" => 123456789, "n" => 1, "data" => new MongoBinData("def"));
array("files_id" => 123456789, "n" => 2, "data" => new MongoBinData("ghi"));
array("files_id" => 123456789, "n" => 3, "data" => new MongoBinData("jkl"));
?>
Of course, the default chunk size is thousands of bytes, but that makes an unweildy example.

Inter-Language Compatibility

You should be able to use any files created by MongoGridFS with any other drivers, and visa vera. However, some drivers expect that all metadata associated with a file be in a "metadata" field. If you're going to be using other languages, it's a good idea to wrap info you might want them to see in a "metadata" field. For example, instead of:

<?php

$grid->storeFile("somefile.txt", array("date" => new MongoDate()));

?>

use something like:

<?php

$grid->storeFile("somefile.txt", array("metadata" => array("date" => new MongoDate())));

?>

The MongoGridFS Family

MongoGridFS represents the files and chunks collections. MongoGridFS extends MongoCollection, and an instance of MongoGridFS has access to all of MongoCollection methods, which act on the files collection:

<?php

$grid = $db->getGridFS();
$grid->update(array("filename" => "foo"), $newObj); // update on the files collection

?>

Another example of manipulating metadata:

<?php

// save a file
$id = $grid->storeFile("game.tgz");
$game = $grid->findOne();

// add a downloads counter
$game->file['downloads'] = 0;
$grid->save($game->file);

// increment the counter
$grid->update(array("_id" => $id), array('$inc' => array("downloads" => 1)));

?>

You can also access the chunks collection from an instance of MongoGridFS:

<?php

  $chunks = $grid->chunks; // $chunks is a normal MongoCollection
$chunks->insert(array("x" => 4));

?>

There are some methods for MongoGridFS with the same name as MongoCollection methods, that behave slightly differently. For example, MongoGridFS::remove() will remove any objects that match the criteria from the files collection and their content from the chunks collection.

To store something new in GridFS, there are a couple options. If you have a filename, you can say:

<?php

$grid->storeFile($filename, array("whatever" => "metadata", "you" => "want"));

?>

If you have a string of bytes that isn't a file, you can also store that using MongoGridFS::storeBytes():

<?php

$grid->storeBytes($bytes, array("whatever" => "metadata", "you" => "want"));

?>

Querying a MongoGridFS collection returns a MongoGridFSCursor, which behaves like a normal MongoCursor except that it returns MongoGridFSFiles instead of associative arrays.

MongoGridFSFiles can be written back to disc using MongoGridFSFile::write() or retrieved in memory using MongoGridFSFile::getBytes(). There is currently no method that automatically streams chunks, but it would be fairly easy to write by querying the $grid->chunks collection.

MongoGridFSFile objects contain a field file which contains any file metadata.

Krótki opis klasy

extends MongoCollection {
/* Fields */
public MongoCollection $chunks = NULL ;
protected string $filesName = NULL ;
protected string $chunksName = NULL ;
/* Metody */
public __construct ( MongoDB $db [, string $prefix = "fs" [, mixed $chunks = "fs" ]] )
public bool delete ( mixed $id )
public array drop ( void )
public MongoGridFSCursor find ([ array $query = array() [, array $fields = array() ]] )
public MongoGridFSFile findOne ([ mixed $query = array() [, mixed $fields = array() ]] )
public MongoGridFSFile get ( mixed $id )
public mixed put ( string $filename [, array $extra = array() ] )
public bool remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed storeBytes ( string $bytes [, array $extra = array() [, array $options = array() ]] )
public mixed storeFile ( string $filename [, array $extra = array() [, array $options = array() ]] )
public mixed storeUpload ( string $name [, array $metadata ] )
}

Zobacz też:

MongoDB core docs on » GridFS. There's also a nice intro to » saving user uploads and » adding metadata at LightCubeSolutions.com.

Spis treści

  • MongoGridFS::__construct — Creates new file collections
  • MongoGridFS::delete — Delete a file from the database
  • MongoGridFS::drop — Drops the files and chunks collections
  • MongoGridFS::find — Queries for files
  • MongoGridFS::findOne — Returns a single file matching the criteria
  • MongoGridFS::get — Retrieve a file from the database
  • MongoGridFS::put — Stores a file in the database
  • MongoGridFS::remove — Removes files from the collections
  • MongoGridFS::storeBytes — Chunkifies and stores bytes in the database
  • MongoGridFS::storeFile — Stores a file in the database
  • MongoGridFS::storeUpload — Saves an uploaded file to the database
GridFS Classes
MongoGridFS::__construct
GridFS Classes


Creates new file collections

MongoGridFS
MongoGridFS::delete
MongoGridFS
PHP Manual

MongoGridFS::__construct

(PECL mongo >=0.9.0)

MongoGridFS::__construct — Creates new file collections

Opis

public MongoGridFS::__construct ( MongoDB $db [, string $prefix = "fs" [, mixed $chunks = "fs" ]] )

Files as stored across two collections, the first containing file meta information, the second containing chunks of the actual file. By default, fs.files and fs.chunks are the collection names used.

Use one argument to specify a prefix other than "fs":

$fs = new MongoGridFS($db, "myfiles");
uses myfiles.files and myfiles.chunks collections.

Parametry

db

Database.

files

Optional collection name prefix.

MongoGridFS
MongoGridFS::delete
MongoGridFS


Delete a file from the database

MongoGridFS::__construct
MongoGridFS::drop
MongoGridFS
PHP Manual

MongoGridFS::delete

(PECL mongo >=1.0.8)

MongoGridFS::delete — Delete a file from the database

Opis

public bool MongoGridFS::delete ( mixed $id )

Parametry

id

_id of the file to remove.

Zwracane wartości

Returns if the remove was successfully sent to the database.

MongoGridFS::__construct
MongoGridFS::drop
MongoGridFS


Drops the files and chunks collections

MongoGridFS::delete
MongoGridFS::find
MongoGridFS
PHP Manual

MongoGridFS::drop

(PECL mongo >=0.9.0)

MongoGridFS::drop — Drops the files and chunks collections

Opis

public array MongoGridFS::drop ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The database response.

MongoGridFS::delete
MongoGridFS::find
MongoGridFS


Queries for files

MongoGridFS::drop
MongoGridFS::findOne
MongoGridFS
PHP Manual

MongoGridFS::find

(PECL mongo >=0.9.0)

MongoGridFS::find — Queries for files

Opis

 public MongoGridFSCursor MongoGridFS::find
  ([ array $query = array()
 [, array $fields = array()
]] )

Parametry

query

The query.

fields

Fields to return.

Zwracane wartości

A MongoGridFSCursor.

MongoGridFS::drop
MongoGridFS::findOne
MongoGridFS


Returns a single file matching the criteria

MongoGridFS::find
MongoGridFS::get
MongoGridFS
PHP Manual

MongoGridFS::findOne

(PECL mongo >=0.9.0)

MongoGridFS::findOne — Returns a single file matching the criteria

Opis

 public MongoGridFSFile MongoGridFS::findOne
  ([ mixed $query = array()
 [, mixed $fields = array()
]] )

Parametry

query

The filename or criteria for which to search.

Zwracane wartości

Returns a MongoGridFSFile or NULL.

Przykłady

Przykład #1 MongoGridFS::findOne() example

Example demonstrating how to find a single file from the MongoGridFS.

<?php

$downloads = $mongo->my_db->getGridFS('downloads');

$downloads->storeFile('filename.tgz');

$download = $downloads->findOne('filename.tgz'); // instance of MongoGridFSFile

print_r($download);
?>

See MongoGridFSFile for more information about how to work with files.

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

MongoGridFSFile Object
(
    [file] => Array
        (
            [_id] => MongoId Object
                (
                )

            [filename] => filename.tgz
            [uploadDate] => MongoDate Object
                (
                    [sec] => 1274288014
                    [usec] => 467000
                )

            [chunkSize] => 262144
            [md5] => d41d8cd98f00b204e9800998ecf8427e
        )

    [gridfs:protected] => MongoGridFS Object
        (
            [chunks] => MongoCollection Object
                (
                )

            [filesName:protected] => downloads.files
            [chunksName:protected] => downloads.chunks
        )

)
MongoGridFS::find
MongoGridFS::get
MongoGridFS


Retrieve a file from the database

MongoGridFS::findOne
MongoGridFS::put
MongoGridFS
PHP Manual

MongoGridFS::get

(PECL mongo >=1.0.8)

MongoGridFS::get — Retrieve a file from the database

Opis

public MongoGridFSFile MongoGridFS::get ( mixed $id )

Parametry

id

_id of the file to find.

Zwracane wartości

Returns the file, if found, or NULL.

MongoGridFS::findOne
MongoGridFS::put
MongoGridFS


Stores a file in the database

MongoGridFS::get
MongoGridFS::remove
MongoGridFS
PHP Manual

MongoGridFS::put

(PECL mongo >=1.0.8)

MongoGridFS::put — Stores a file in the database

Opis

public mixed MongoGridFS::put ( string $filename [, array $extra = array() ] )

Parametry

filename

The name of the file.

extra

Other metadata to add to the file saved.

Zwracane wartości

Returns the _id of the saved object.

MongoGridFS::get
MongoGridFS::remove
MongoGridFS


Removes files from the collections

MongoGridFS::put
MongoGridFS::storeBytes
MongoGridFS
PHP Manual

MongoGridFS::remove

(PECL mongo >=0.9.0)

MongoGridFS::remove — Removes files from the collections

Opis

 public bool MongoGridFS::remove
  ([ array $criteria = array()
 [, array $options = array()
]] )

Parametry

query

The filename or criteria for which to search.

options

Options for the remove. Valid options are:

  • "safe"

    Check that the remove succeeded.

Zwracane wartości

Returns if the removal was successfully sent to the database.

MongoGridFS::put
MongoGridFS::storeBytes
MongoGridFS


Chunkifies and stores bytes in the database

MongoGridFS::remove
MongoGridFS::storeFile
MongoGridFS
PHP Manual

MongoGridFS::storeBytes

(PECL mongo >=0.9.2)

MongoGridFS::storeBytes — Chunkifies and stores bytes in the database

Opis

public mixed MongoGridFS::storeBytes ( string $bytes [, array $extra = array() [, array $options = array() ]] )

Parametry

bytes

A string of bytes to store.

extra

Other metadata to add to the file saved.

options

Options for the store.

  • "safe"

    Check that this store succeeded.

Zwracane wartości

The _id of the object saved.

Błędy/Wyjątki

Throws MongoCursorException if the "safe" option is set and the insert fails.

MongoGridFS::remove
MongoGridFS::storeFile
MongoGridFS


Stores a file in the database

MongoGridFS::storeBytes
MongoGridFS::storeUpload
MongoGridFS
PHP Manual

MongoGridFS::storeFile

(PECL mongo >=0.9.0)

MongoGridFS::storeFile — Stores a file in the database

Opis

public mixed MongoGridFS::storeFile ( string $filename [, array $extra = array() [, array $options = array() ]] )

Parametry

filename

The name of the file.

extra

Other metadata to add to the file saved.

options

Options for the store.

  • "safe"

    Check that this store succeeded.

Zwracane wartości

Returns the _id of the saved object.

Błędy/Wyjątki

Throws MongoCursorException if the "safe" option is set and the insert fails.

MongoGridFS::storeBytes
MongoGridFS::storeUpload
MongoGridFS


Saves an uploaded file to the database

MongoGridFS::storeFile
MongoGridFSFile
MongoGridFS
PHP Manual

MongoGridFS::storeUpload

(PECL mongo >=0.9.0)

MongoGridFS::storeUpload — Saves an uploaded file to the database

Opis

public mixed MongoGridFS::storeUpload ( string $name [, array $metadata ] )

Stores files directly from a POST to the database. For example, suppose you had the following HTML form:

<form method="POST" enctype="multipart/form-data">
     Please upload a profile picture: <input type="file" name="pic"/>
     <input type="submit"/>
</form>

If you wanted to store this upload in MongoDB, you could do:

<?php

$grid->storeUpload("pic", array("username" => "joe"));

?>

Note that the "name" field in HTML matches the name parameter.

Parametry

name

The name field of the uploaded file.

metadata

An array of extra fields for the uploaded file.

Zwracane wartości

Returns the _id of the uploaded file.

Rejestr zmian

Wersja | Opis
1.2.5 | Changed second parameter to an array of metadata. Pre-1.2.5, the second parameter was an optional string overriding the filename.

MongoGridFS::storeFile
MongoGridFSFile
MongoGridFS


The MongoGridFSFile class

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

Wstęp

A database file object.

Krótki opis klasy

MongoGridFSFile {
/* Fields */
public array $file = NULL ;
protected MongoGridFS $gridfs = NULL ;
/* Metody */
public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )
public string getBytes ( void )
public string getFilename ( void )
public stream getResource ( void )
public int getSize ( void )
public int write ([ string $filename = NULL ] )
}

Spis treści

  • MongoGridfsFile::__construct — Create a new GridFS file
  • MongoGridFSFile::getBytes — Returns this file's contents as a string of bytes
  • MongoGridFSFile::getFilename — Returns this file's filename
  • MongoGridFSFile::getResource — Returns a resource that can be used to read the stored file
  • MongoGridFSFile::getSize — Returns this file's size
  • MongoGridFSFile::write — Writes this file to the filesystem
MongoGridFS::storeUpload
MongoGridfsFile::__construct
GridFS Classes


Create a new GridFS file

MongoGridFSFile
MongoGridFSFile::getBytes
MongoGridFSFile
PHP Manual

MongoGridfsFile::__construct

(PECL mongo >=0.9.0)

MongoGridfsFile::__construct — Create a new GridFS file

Opis

public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )

Parametry

gridfs

The parent MongoGridFS instance.

file

A file from the database.

Zwracane wartości

Returns a new MongoGridFSFile.

MongoGridFSFile
MongoGridFSFile::getBytes
MongoGridFSFile


Returns this file's contents as a string of bytes

MongoGridfsFile::__construct
MongoGridFSFile::getFilename
MongoGridFSFile
PHP Manual

MongoGridFSFile::getBytes

(PECL mongo >=0.9.0)

MongoGridFSFile::getBytes — Returns this file's contents as a string of bytes

Opis

public string MongoGridFSFile::getBytes ( void )

Warning: this will load the file into memory. If the file is bigger than your memory, this will cause problems!

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string of the bytes in the file.

Przykłady

Przykład #1 MongoGridFSFile::getBytes() example

<?php

$images = $db->my_db->getGridFS('images');

$image = $images->findOne('jwage.png');

header('Content-type: image/png;');
echo $image->getBytes();
?>
MongoGridfsFile::__construct
MongoGridFSFile::getFilename
MongoGridFSFile


Returns this file's filename

MongoGridFSFile::getBytes
MongoGridFSFile::getResource
MongoGridFSFile
PHP Manual

MongoGridFSFile::getFilename

(PECL mongo >=0.9.0)

MongoGridFSFile::getFilename — Returns this file's filename

Opis

public string MongoGridFSFile::getFilename ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the filename.

MongoGridFSFile::getBytes
MongoGridFSFile::getResource
MongoGridFSFile


Returns a resource that can be used to read the stored file

MongoGridFSFile::getFilename
MongoGridFSFile::getSize
MongoGridFSFile
PHP Manual

MongoGridFSFile::getResource

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

MongoGridFSFile::getResource — Returns a resource that can be used to read the stored file

Opis

public stream MongoGridFSFile::getResource ( void )

This method returns a stream resource that can be used with all file functions in PHP. The contents of the file are pulled out of MongoDB on the fly, so that the whole file does not have to be loaded into memory first.

At most two GridFSFile chunks will be loaded in memory.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a resource that can be used to read the file with

Przykłady

Przykład #1 MongoGridFSFile::getResource() example

<?php
$m = new Mongo;
$images = $m->my_db->getGridFS('images');

$image = $images->findOne('mongo.png');

header('Content-type: image/png;');
$stream = $image->getResource();

while (!feof($stream)) {
    echo fread($stream, 8192);
}
?>
MongoGridFSFile::getFilename
MongoGridFSFile::getSize
MongoGridFSFile


Returns this file's size

MongoGridFSFile::getResource
MongoGridFSFile::write
MongoGridFSFile
PHP Manual

MongoGridFSFile::getSize

(PECL mongo >=0.9.0)

MongoGridFSFile::getSize — Returns this file's size

Opis

public int MongoGridFSFile::getSize ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns this file's size

MongoGridFSFile::getResource
MongoGridFSFile::write
MongoGridFSFile


Writes this file to the filesystem

MongoGridFSFile::getSize
MongoGridFSCursor
MongoGridFSFile
PHP Manual

MongoGridFSFile::write

(PECL mongo >=0.9.0)

MongoGridFSFile::write — Writes this file to the filesystem

Opis

public int MongoGridFSFile::write ([ string $filename = NULL ] )

Parametry

filename

The location to which to write the file. If none is given, the stored filename will be used.

Zwracane wartości

Returns the number of bytes written.

Przykłady

Przykład #1 MongoGridFSFile::write() example

<?php

$images = $db->my_db->getGridFS('images');

$image = $images->findOne('jwage.png');
$image->write('/path/to/write/jwage.png');
?>
MongoGridFSFile::getSize
MongoGridFSCursor
MongoGridFSFile


The MongoGridFSCursor class

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

Wstęp

Cursor for database file results.

Krótki opis klasy

extends MongoCursor {
/* Fields */
protected MongoGridFS $gridfs = NULL ;
/* Metody */
public __construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )
public MongoGridFSFile current ( void )
public MongoGridFSFile getNext ( void )
public string key ( void )
}

Spis treści

  • MongoGridFSCursor::__construct — Create a new cursor
  • MongoGridFSCursor::current — Returns the current file
  • MongoGridFSCursor::getNext — Return the next file to which this cursor points, and advance the cursor
  • MongoGridFSCursor::key — Returns the current result's filename
MongoGridFSFile::write
MongoGridFSCursor::__construct
GridFS Classes


Create a new cursor

MongoGridFSCursor
MongoGridFSCursor::current
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::__construct

(PECL mongo >=0.9.0)

MongoGridFSCursor::__construct — Create a new cursor

Opis

public MongoGridFSCursor::__construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )

Parametry

gridfs

Related GridFS collection.

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Zwracane wartości

Returns the new cursor.

MongoGridFSCursor
MongoGridFSCursor::current
MongoGridFSCursor


Returns the current file

MongoGridFSCursor::__construct
MongoGridFSCursor::getNext
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::current

(PECL mongo >=0.9.0)

MongoGridFSCursor::current — Returns the current file

Opis

public MongoGridFSFile MongoGridFSCursor::current ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current file.

MongoGridFSCursor::__construct
MongoGridFSCursor::getNext
MongoGridFSCursor


Return the next file to which this cursor points, and advance the cursor

MongoGridFSCursor::current
MongoGridFSCursor::key
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::getNext

(PECL mongo >=0.9.0)

MongoGridFSCursor::getNext — Return the next file to which this cursor points, and advance the cursor

Opis

public MongoGridFSFile MongoGridFSCursor::getNext ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the next file.

MongoGridFSCursor::current
MongoGridFSCursor::key
MongoGridFSCursor


Returns the current result's filename

MongoGridFSCursor::getNext
Miscellaneous
MongoGridFSCursor
PHP Manual

MongoGridFSCursor::key

(PECL mongo >=0.9.0)

MongoGridFSCursor::key — Returns the current result's filename

Opis

public string MongoGridFSCursor::key ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current result's filename.

MongoGridFSCursor::getNext
Miscellaneous
MongoGridFSCursor


Miscellaneous

Spis treści

  • MongoLog
  • MongoPool
MongoGridFSCursor::key
MongoLog
Mongo


The MongoLog class

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

Wstęp

Logging can be used to get detailed information about what the driver is doing. With PHP-CLI, log output will be printed to stderr. Under an app server, log messages will generally be printed to an error log.

Logging is turned off, by default. This class allows you to turn on specific levels of logging for specific parts of the driver. Some examples:

<?php

// print every log message possible
MongoLog::setLevel(MongoLog::ALL); // all log levels
MongoLog::setModule(MongoLog::ALL); // all parts of the driver

// print significant events about replica set failover
MongoLog::setLevel(MongoLog::INFO);
MongoLog::setModule(MongoLog::RS);

// print info- and server tuning-level events from replica sets and connection pooling
MongoLog::setLevel(MongoLog::INFO|MongoLog::FINE);
MongoLog::setModule(MongoLog::RS|MongoLog::POOL);

?>

Krótki opis klasy

MongoLog {
/* Stałe */
const int NONE ;
const int ALL ;
level constants {
const int WARNING ;
const int INFO ;
const int FINE ;
module constants {
const int RS ;
const int POOL ;
const int IO ;
const int SERVER ;
const int PARSE ;
/* Fields */
public int $level ;
public int $module ;
/* Metody */
public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )
public string MongoDate::__toString ( void )
}

Stałe predefiniowane

MongoLog Constants

These constants can be used by both MongoLog::setLevel() and MongoLog::setModule().

MongoLog::NONE
Constant for turning logging off.
MongoLog::ALL
Constant for logging everything.

MongoLog Level Constants

These constants can be used by MongoLog::setLevel().

MongoLog::WARNING
This will print log messages about somewhat exceptional but not-quite-exception-worthy happenings.
MongoLog::INFO
Logs events that may be of interest to administrators, but are not particularly noteworthy.
MongoLog::FINE
Logs most events that the driver performs. Depending on the module being logged, this can be extremely noisy and is primarily for debugging.

MongoLog Module Constants

These constants can be used by MongoLog::setModule().

MongoLog::IO
Logs traffic to/from the database. Unless your program is trivial, this will create an enormous number of log messages.
MongoLog::PARSE
Log server string parsing.
MongoLog::POOL
Log connection pool activity. Creating new connections, reusing connections, and closing connections.
MongoLog::RS
Log replica set activity. Failovers, pinging, chosing secondaries to read from, etc.
MongoLog::SERVER
Log server status changes. Detecting primary, secondary and duplication detection.

Spis treści

  • MongoLog::getLevel — Gets the log level
  • MongoLog::getModule — Gets the modules currently being logged
  • MongoLog::setLevel — Sets logging level
  • MongoLog::setModule — Sets driver functionality to log
Miscellaneous
MongoLog::getLevel
Miscellaneous


Gets the log level

MongoLog
MongoLog::getModule
MongoLog
PHP Manual

MongoLog::getLevel

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

MongoLog::getLevel — Gets the log level

Opis

public static int MongoLog::getLevel ( void )

This can be used to see the log level. Use the constants described in the MongoLog section with bitwise operators to check the level.

<?php

if (MongoLog::getLevel() & MongoLog::FINE) {
    echo "lots 'o logs\n";
}

if (MongoLog::getLevel() ^ MongoLog::NONE) {
    echo "logging, at least a little\n";
}

if (MongoLog::getLevel() == MongoLog::ALL) {
    echo "logging at the highest levels\n";
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current level.

MongoLog
MongoLog::getModule
MongoLog


Gets the modules currently being logged

MongoLog::getLevel
MongoLog::setLevel
MongoLog
PHP Manual

MongoLog::getModule

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

MongoLog::getModule — Gets the modules currently being logged

Opis

public static int MongoLog::getModule ( void )

This function can be used to see which parts of the driver's functionality are being logged. Use the constants described in the MongoLog section with bitwise operators to check if specific modules are being logged.

<?php

if (MongoLog::getModule() & MongoLog::RS) {
    echo "logging replica sets\n";
}

if (MongoLog::getModule() ^ MongoLog::NONE) {
    echo "logging something\n";
}

if ((MongoLog::getModule() & MongoLog::IO) == 0) {
    echo "not logging io\n";
}

?>

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the modules currently being logged.

MongoLog::getLevel
MongoLog::setLevel
MongoLog


Sets logging level

MongoLog::getModule
MongoLog::setModule
MongoLog
PHP Manual

MongoLog::setLevel

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

MongoLog::setLevel — Sets logging level

Opis

public static void MongoLog::setLevel ( int $level )

This function can be used to set how verbose logging should be and the types of activities that should be logged. Use the constants described in the MongoLog section with bitwise operators to specify levels.

<?php

// first, turning on logging for a module
MongoLog::setModule(MongoLog::POOL);

// log messages of every level
MongoLog::setLevel(MongoLog::ALL);

// log warnings and info
MongoLog::setLevel(MongoLog::WARNING|MongoLog::INFO);

// log everything except fine activity
MongoLog::setLevel(MongoLog::ALL & (~MongoLog::FINE));

?>

Note that you must also call MongoLog::setModule() to choose what part of the driver to log.

Parametry

level

The levels you would like to log.

MongoLog::getModule
MongoLog::setModule
MongoLog


Sets driver functionality to log

MongoLog::setLevel
MongoPool
MongoLog
PHP Manual

MongoLog::setModule

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

MongoLog::setModule — Sets driver functionality to log

Opis

public static void MongoLog::setModule ( int $module )

This function can be used to set which parts of the driver's functionality should be logged. Use the constants described in the MongoLog section with bitwise operators to specify modules.

<?php

// first, turning up the logging level
MongoLog::setLevel(MongoLog::ALL);

// log replica set activity
MongoLog::setModule(MongoLog::RS);

// log replica sets and connection pooling
MongoLog::setModule(MongoLog::RS|MongoLog::ALL);

// log everything except IO activity
MongoLog::setModule(MongoLog::ALL & (~MongoLog::IO));

?>

Note that you must also call MongoLog::setLevel() to turn on logging.

Parametry

module

The module(s) you would like to log.

MongoLog::setLevel
MongoPool
MongoLog


The MongoPool class

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

Wstęp

In version 1.2.0 of the driver, built-in connection pooling was introduced. This class gives you some control and information about pooling.

Informacja:

The functions in this class were originally static members of Mongo. It is highly recommended that you use these functions in the future, as the static Mongo functions are considered deprecated.

Krótki opis klasy

MongoPool {
/* Metody */
public static int getSize ( void )
public array info ( void )
public static bool setSize ( int $size )
}

Spis treści

  • MongoPool::getSize — Get pool size for connection pools
  • MongoPool::info — Returns information about all connection pools.
  • MongoPool::setSize — Set the size for future connection pools.
MongoLog::setModule
MongoPool::getSize
Miscellaneous


Get pool size for connection pools

MongoPool
MongoPool::info
MongoPool
PHP Manual

MongoPool::getSize

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

MongoPool::getSize — Get pool size for connection pools

Opis

public static int MongoPool::getSize ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current pool size.

Przykłady

Przykład #1 Changing pool size

This returns the default pool size, sets a new pool size, then prints the new pool size and the pool debugging information. Note that changing the pool size only affects new connection pools, it does not change old ones.

<?php

$connection = new Mongo("host1");

// pool size is -1
echo "pool size is: ".MongoPool::getSize()."\n";

echo "setting pool size to 200\n";

MongoPool::setSize(200);

// pool size is 200
echo "pool size is: ".MongoPool::getSize()."\n";

$conn2 = new Mongo("host2");

// remaining for host1 is -2
// remaining for host2 is 199
var_dump(Mongo::poolDebug());

?>

Zobacz też:

  • MongoPool::setSize() - Set the size for future connection pools.
  • MongoPool::info() - Returns information about all connection pools.
  • The connection documentation.

MongoPool
MongoPool::info
MongoPool


Returns information about all connection pools.

MongoPool::getSize
MongoPool::setSize
MongoPool
PHP Manual

MongoPool::info

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

MongoPool::info — Returns information about all connection pools.

Opis

public array MongoPool::info ( void )

Returns an array of information about all connection pools.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Each connection pool has an identifier, which starts with the host. For each pool, this function shows the following fields:

in use

The number of connections currently being used by Mongo instances.

in pool

The number of connections currently in the pool (not being used).

remaining

The number of connections that could be created by this pool. For example, suppose a pool had 5 connections remaining and 3 connections in the pool. We could create 8 new instances of Mongo before we exhausted this pool (assuming no instances of Mongo went out of scope, returning their connections to the pool).

A negative number means that this pool will spawn unlimited connections.

Before a pool is created, you can change the max number of connections by calling Mongo::setPoolSize(). Once a pool is showing up in the output of this function, its size cannot be changed.

total

The total number of connections allowed for this pool. This should be greater than or equal to "in use" + "in pool" (or -1).

timeout

The socket timeout for connections in this pool. This is how long connections in this pool will attempt to connect to a server before giving up.

waiting

If you have capped the pool size, workers requesting connections from the pool may block until other workers return their connections. This field shows how many milliseconds workers have blocked for connections to be released. If this number keeps increasing, you may want to use MongoPool::setSize() to add more connections to your pool.

MongoPool::getSize
MongoPool::setSize
MongoPool


Set the size for future connection pools.

MongoPool::info
Functions
MongoPool
PHP Manual

MongoPool::setSize

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

MongoPool::setSize — Set the size for future connection pools.

Opis

public static bool MongoPool::setSize ( int $size )

Sets the max number of connections new pools will be able to create.

Parametry

size

The max number of connections future pools will be able to create. Negative numbers mean that the pool will spawn an infinite number of connections.

Zwracane wartości

Returns the former value of pool size.

Przykłady

Przykład #1 Mongo::setPoolSize() example

If you set the pool size to n and then create n connections, attempting to create an n+1st connection will throw a MongoConnectionException.

<?php

// only allow one connection to a server
MongoPool::setSize(1);

// creates one connection to localhost:27017
$m1 = new Mongo();

// attempt to create a second connection to localhost:27017
// only one connection is allowed, so this will throw an exception
$m2 = new Mongo();

?>

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

Fatal error: Uncaught exception 'MongoConnectionException' with message 'no more connections in pool' in /path/to/php/script.php:10
Stack trace:
#0 /path/to/php/script.php(10): Mongo->__construct()
#1 {main}
  thrown in /path/to/php/script.php on line 10

Zobacz też:

  • MongoPool::getSize() - Get pool size for connection pools
  • MongoPool::info() - Returns information about all connection pools.
  • The connection documentation.

MongoPool::info
Functions
MongoPool


Functions

Spis treści

  • Mongo Funkcje
MongoPool::setSize
Mongo Funkcje
Mongo


Mongo Funkcje

Spis treści

  • bson_decode — Deserializes a BSON object into a PHP array
  • bson_encode — Serializes a PHP variable into a BSON string
Functions
bson_decode
Functions


Deserializes a BSON object into a PHP array

Mongo Funkcje
bson_encode
Mongo Funkcje
PHP Manual

bson_decode

(PECL mongo >=1.0.1)

bson_decode — Deserializes a BSON object into a PHP array

Opis

array bson_decode ( string $bson )

This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver.

Parametry

bson

The BSON to be deserialized.

Zwracane wartości

Returns the deserialized BSON object.

Mongo Funkcje
bson_encode
Mongo Funkcje


Serializes a PHP variable into a BSON string

bson_decode
Exceptions
Mongo Funkcje
PHP Manual

bson_encode

(PECL mongo >=1.0.1)

bson_encode — Serializes a PHP variable into a BSON string

Opis

string bson_encode ( mixed $anything )

This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver.

Parametry

anything

The variable to be serialized.

Zwracane wartości

Returns the serialized string.

bson_decode
Exceptions
Mongo Funkcje


Exceptions

Spis treści

  • MongoException
  • MongoCursorException
  • MongoCursorTimeoutException
  • MongoConnectionException
  • MongoGridFSException

VMWare Oddities

If you are running VMWare on Windows and are using CIFS, pausing the VM will cause CIFS to go out of sync and cause weird errors on un-pausing it ("The Mongo object has not been correctly initialized by its constructor"). Permanently mounting the Windows shares will fix this and you'll be able to pause and unpause at will.

To permanently mount the Windows shares, run:

$ sudo update-rc.d -f umountnfs.sh remove
$ sudo update-rc.d umountnfs.sh stop 15 0 6 .

See » the Ubuntu docs for the most up-to-date instructions.

bson_encode
MongoException
Mongo


The MongoException class

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

Wstęp

Default Mongo exception.

This covers a bunch of different error conditions that may eventually be moved to more specific exceptions, but will always extend MongoException.

  • The MongoSomething object has not been correctly initialized by its constructor

    Code: 0

    Probably your Mongo object is not connected to a database server.

  • zero-length keys are not allowed, did you use $ with double quotes?

    Code: 1

    You tried to save "" as a key. You generally should not do this. "" can mess up subobject access and is used by MongoDB internally. However, if you really want, you can set mongo.allow_empty_keys to true in your php.ini file to override this sanity check. If you override this, it is highly recommended that you set error checking to strict to avoid string interpolation errors.

  • '.' not allowed in key: <key>

    Code: 2

    You attempted to write a key with '.' in it, which is prohibited.

  • insert too large: <size>, max: <max>

    Code: 3

    You're attempting to send too much data to the database at once: the database will only accept inserts up to a certain size (currently 16 MB).

  • no elements in doc

    Code: 4

    You're attempting to save a document with no fields.

  • size of BSON doc is <size> bytes, max <max>MB

    Code: 5

    You're attempting to save a document that is larger than MongoDB can save.

  • no documents given

    Code: 6

    You're attempting to batch insert an empty array of documents.

  • MongoCollection::group takes an array, object, or MongoCode key

    Code: 7

    Wrong type parameter send to MongoCollection::group().

  • field names must be strings

    Code: 8

    You should format field selectors as array("field1" => 1, "field2" => 1, ..., "fieldN" => 1).

  • invalid regex

    Code: 8

    The regex passed to MongoRegex is not of the correct form.

  • MongoDBRef::get: $ref field must be a string

    Code: 10

  • MongoDBRef::get: $db field must be a string

    Code: 11

  • non-utf8 string: <str>

    Code: 12

    This error occurs if you attempt to send a non-utf8 string to the database. All strings going into the database should be UTF8. See php.ini options for the transition option of quieting this exception.

  • mutex error: <err>

    Code: 13

    The driver uses mutexes for synchronizing requests and responses in multithreaded environments. This is a fairly serious error and may not have a stack trace. It's unusual and should be reported to maintainers with any system information and steps to reproduce that you can provide.

  • index name too long: <len>, max <max> characters

    Code: 14

    Indexes with names longer than 128 characters cannot be created. If you get this error, you should use MongoCollection::ensureIndex()'s "name" option to create a shorter name for your index.

Krótki opis klasy

extends Exception {
}
Exceptions
MongoCursorException
Exceptions


The MongoCursorException class

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

Wstęp

Caused by accessing a cursor incorrectly or a error receiving a reply. Note that this can be thrown by any database request that receives a reply, not just queries. Writes, commands, and any other operation that sends information to the database and waits for a response can throw a MongoCursorException. The only exception is new Mongo() (creating a new connection), which will only throw MongoConnectionExceptions.

This returns a specific error message to help diagnose the problem and a numeric error code associated with the cause of the exception.

For example, suppose you tried to insert two documents with the same _id:

<?php

try {
    $collection->insert(array("_id" => 1), array("safe" => true));
    $collection->insert(array("_id" => 1), array("safe" => true));
}
catch (MongoCursorException $e) {
    echo "error message: ".$e->getMessage()."\n";
    echo "error code: ".$e->getCode()."\n";
}

?>
This would produce output like:
error message: E11000 duplicate key error index: foo.bar.$_id_  dup key: { : 1 }
error code: 11000
Note that the MongoDB error code (11000) is used for the PHP error code. The PHP driver uses the "native" error code wherever possible.

The following is a list of common errors, codes, and causes. Exact errors are in italics, errors where the message can vary are described in obliques.

  • cannot modify cursor after beginning iteration

    Code: 0

    You are calling a method that sets up the query after executing the query. Reset the cursor and try again.

    An example:

    <?php

    try {
            $cursor = $collection->find();
            var_dump($cursor->getNext());

            // getNext() queried the database, it's too late to set a limit
            $cursor->limit(1);
    }
    catch (    MongoCursorException $e) {
        echo     "error message: ".$e->getMessage()."\n";
        echo     "error code: ".$e->getCode()."\n";
    }

    // this will work, though:
    $cursor->getNext();
    $cursor->reset();
    $cursor->limit(1);

    ?>

  • Get next batch send errors

    Code: 1

    Could not send the query to the database. Make sure the database is still up and the network is okay.

  • cursor not found

    Code: 2

    The driver was trying to fetch more results from the database, but the database did not have a record of the query. This usually means that the cursor timed out on the server side: after a few minutes of inactivity, the database will kill a cursor (see MongoCursor::immortal() for information on preventing this).

    An example:

    <?php

    try {
            $cursor = $collection->find();
            $cursor->getNext();

            // sleep for 15 minutes
            sleep(60*15);

        while (    $cursor->hasNext()) {
                $cursor->getNext();
        }
    }
    catch (    MongoCursorException $e) {
        echo     "error message: ".$e->getMessage()."\n";
        echo     "error code: ".$e->getCode()."\n";
    }

    ?>

  • cursor->buf.pos is null

    Code: 3

    This may indicate you are out of RAM or some other extraordinary circumstance.

  • couldn't get response header

    Code: 4

    A common error if the database or network goes down. This means that the driver couldn't get a response from the connection.

  • no db response

    Code: 5

    This may not even be an error, for example, the database command "shutdown" returns no response. However, if you were expecting a response, this means the database didn't give one.

  • bad response length: %d, did the db assert?

    Code: 6

    This means that the database said that its response was less than 0. This error probably indicates a network error or database corruption.

  • incomplete header

    Code: 7

    Highly unusual. Occurs if the database response started out correctly, but broke off in the middle. Probably indicates a network problem.

  • incomplete response

    Code: 8

    Highly unusual. Occurs if the database response started out correctly, but broke off in the middle. Probably indicates a network problem.

  • couldn't find a response

    Code: 9

    If the response was cached and now cannot be located.

  • error getting socket

    Code: 10

    The socket was closed or encountered an error. The driver should automatically reconnect (if possible) on the next operation.

  • couldn't find reply, please try again

    Code: 11

    The driver saves any database responses it cannot immediately match with a request. This exception occurs if the driver has already passed your request's response and cannot find your response in its cache.

  • error getting database response: errstr

    WSA error getting database response: errstr

    "errstr" is an io error reported directly from the C socket subsystem. On Windows, the error message is prefixed with "WSA".

  • Timeout error

    Code: 13

    If there was an error while waiting for a query to complete.

  • couldn't send query: <various>

    Code: 14

    C socket error on send.

  • max number of retries exhausted, couldn't send query

    Code: 19

    The driver will automatically retry "plain" queries (not commands) a couple of times if the first attempt failed for certain reasons. This is to cause fewer exceptions during replica set failover (although you will probably still have to deal with some) and gloss over transient network issues.

    This can also be caused by the driver not being able to reconnect at all to the database (if, for example, the database is unreachable).

    Version 1.2.2+.

Errors passed through by the database

Database errors should always trigger MongoCursorExceptions on queries. Error messages and codes are sent directly from the database and you should be able to see matching errors in the database log.

A few common database errors are listed below:

  • E11000 duplicate key error index: foo.bar.$X dup key: { /* ... */ }

    Code: 11000

    Database error for duplicate keys.

  • not master

    Codes: 10107, 13435, and 10058

    Not master errors, piped through by the database. Each of these will cause the driver to disconnect and attempt to find a new master. The actual error you get on failover may not be a "not master" error, depending on when the change in master occurs.

Krótki opis klasy

extends MongoException {
}
MongoException
MongoCursorTimeoutException
Exceptions


The MongoCursorTimeoutException class

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

Wstęp

Caused by a query timing out. You can set the length of time to wait before this exception is thrown by calling MongoCursor::timeout() on the cursor or setting MongoCursor::$timeout. The static variable is useful for queries such as database commands and MongoCollection::findOne(), both of which implicitly use cursors.

Krótki opis klasy

extends MongoCursorException {
}
MongoCursorException
MongoConnectionException
Exceptions


The MongoConnectionException class

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

Wstęp

Thrown when the driver fails to connect to the database.

There are a number of possible error messages to help you diagnose the connection problem. These are:

  • No server name given.

    This error occurs if you pass in "" as the server name, probably because of an typo with string interpolation, e.g., "$servr" instead of "$server".

  • failed to get host [hostname] or port [portnum] from [server].

    This indicated that the server string was malformed. "[hostname]" and "[portnum]" will be as much as the driver could dicipher of it.

  • Operation in progress

    Connecting to the database timed out.

  • Transport endpoint is not connected

    Generally means that the connection string isn't correct, the driver couldn't even find the database server.

  • couldn't determine master

    Neither server in a paired connection appeared to be master.

  • couldn't get host info for [server]

    This indicated that DNS could not resolve the server address you gave. This could easily be caused by a typo, for example, "server" instead of "$server".

  • Invalid Argument

    This can be caused by attempting to connect to a machine that is up but that the database isn't actually running on. Make sure that you've started the database server before connecting.

  • Permission denied

    This means that the socket could not be opened due to permissions issues. On Red Hat variants, this can be caused by a default setting that does not allow Apache to create network connections. You can override this setting by running:

    $ /usr/sbin/setsebool -P httpd_can_network_connect 1
    then restarting Apache.

If the error message is not listed above, it is probably an error from the C socket, and you can search the web for its usual cause.

Krótki opis klasy

extends MongoException {
}
MongoCursorTimeoutException
MongoGridFSException
Exceptions


The MongoGridFSException class

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

Wstęp

Thrown when there are errors reading or writing files to or from the database.

Krótki opis klasy

extends MongoException {
}
MongoConnectionException
mSQL
Exceptions


mSQL

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Podstawowe użycie
  • Funkcje mSQL
    • msql_affected_rows — Returns number of affected rows
    • msql_close — Zamyka połączenie z serwerem mSQL
    • msql_connect — Otwiera połączenie z serwerem mSQL
    • msql_create_db — Tworzy nową bazę danych na serwerze mSQL
    • msql_createdb — Alias dla msql_create_db
    • msql_data_seek — Move internal row pointer
    • msql_db_query — Send mSQL query
    • msql_dbname — Alias dla msql_result
    • msql_drop_db — Usuwa bazę danych z serwera mSQL
    • msql_error — Returns error message of last msql call
    • msql_fetch_array — Fetch row as array
    • msql_fetch_field — Get field information
    • msql_fetch_object — Fetch row as object
    • msql_fetch_row — Get row as enumerated array
    • msql_field_flags — Get field flags
    • msql_field_len — Get field length
    • msql_field_name — Get the name of the specified field in a result
    • msql_field_seek — Set field offset
    • msql_field_table — Get table name for field
    • msql_field_type — Get field type
    • msql_fieldflags — Alias dla msql_field_flags
    • msql_fieldlen — Alias dla msql_field_len
    • msql_fieldname — Alias dla msql_field_name
    • msql_fieldtable — Alias dla msql_field_table
    • msql_fieldtype — Alias dla msql_field_type
    • msql_free_result — Free result memory
    • msql_list_dbs — List mSQL databases on server
    • msql_list_fields — List result fields
    • msql_list_tables — List tables in an mSQL database
    • msql_num_fields — Get number of fields in result
    • msql_num_rows — Get number of rows in result
    • msql_numfields — Alias dla msql_num_fields
    • msql_numrows — Alias dla msql_num_rows
    • msql_pconnect — Otwiera trwałe połączenie do serwera mSQL
    • msql_query — Send mSQL query
    • msql_regcase — Alias dla sql_regcase
    • msql_result — Get result data
    • msql_select_db — Select mSQL database
    • msql_tablename — Alias dla msql_result
    • msql — Alias dla msql_db_query
MongoGridFSException
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Te funkcje pozwalają uzyskać dostęp do serwerów baz danych mSQL. Więcej informacji na temat mSQL można znaleźć na stronie » http://www.hughes.com.au/.

mSQL
Instalacja/Konfiguracja
mSQL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
mSQL


Instalacja

Aby te funkcje były dostępne, musimy skompilować PHP z obsługą msql używając opcji --with-msql[=DIR] . DIR jest katalogiem instalacji mSQL, domyślnie /usr/local/msql3.

Informacja: Informacja dla użytkowników Windows

Aby poprawnie działało rozszerzenie, pliki DLL muszą znajdować się w miejscu wskazanym przez PATH systemu Windows. Aby uzyskać więcej informacji zobacz FAQ zatytułowane "Jak mam dodać mój katalog PHP do PATH w Windows". Chociaż skopiowanie plików DLL z folderu PHP do systemowego katalogu Windows także zadziała (ponieważ katalog systemowy jest domyślnie w PATH systemu), ale nie jest to wymagane. To rozszerzenie wymaga następujących plików znajdujących się w PATH: msql.dll

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracyjne mSQL
Nazwa | Wartość domyślna | Możliwość zmian | Rejestr zmian
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
msql.max_links | "-1" | 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.

msql.allow_persistent boolean

Określa, czy pozwolić na połączenia stałe z serwerem mSQL.

msql.max_persistent integer

Maksymalna liczba połączeń stałych z serwerem mSQL na proces.

msql.max_links integer

Maksymalna liczba połączeń z serwerem mSQL na proces, włączając połączenia stałe.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

Istnieją dwa typy zasobów używane w rozszerzeniu mSQL. Pierwszy z nich to identyfikator połączenia z bazą danych, natomiast drugi to zasób przechowujący wyniki zapytania.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

MSQL_ASSOC (integer)
MSQL_NUM (integer)
MSQL_BOTH (integer)
Typy zasobów
Przykłady
mSQL


Przykłady

Spis treści

  • Podstawowe użycie
Stałe predefiniowane
Podstawowe użycie
mSQL


Podstawowe użycie

Ten prosty przykład pokazuje jak można połączyć się do bazy mSQL, wykonać zapytanie, wyświetlić wiersze z wynikami i zamknąć połączenie.

Przykład #1 Przykład użycia mSQL

<?php
/* Nawiązanie połączenia, wybór bazy danych */
$link = msql_connect('localhost')
    or die('Nie można nawiązać połączenia : ' . msql_error());

msql_select_db('database', $link)
    or die('Nie można wybrać bazy danych');

/* Wykonanie zapytania SQL */
$query = 'SELECT * FROM my_table';
$result = msql_query($query, $link) or die('Wykonanie zapytania nie powiodło się : ' . msql_error());

/* Wyświetlenie wyników w postaci tabeli HTML */
echo "<table>\n";
while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($row as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

/* Zwolnienie pamięci zajmowanej przez wynik */
msql_free_result($result);

/* Zamknięcie połączenia */
msql_close($link);
?>

Przykłady
Funkcje mSQL
Przykłady


Funkcje mSQL

Spis treści

  • msql_affected_rows — Returns number of affected rows
  • msql_close — Zamyka połączenie z serwerem mSQL
  • msql_connect — Otwiera połączenie z serwerem mSQL
  • msql_create_db — Tworzy nową bazę danych na serwerze mSQL
  • msql_createdb — Alias dla msql_create_db
  • msql_data_seek — Move internal row pointer
  • msql_db_query — Send mSQL query
  • msql_dbname — Alias dla msql_result
  • msql_drop_db — Usuwa bazę danych z serwera mSQL
  • msql_error — Returns error message of last msql call
  • msql_fetch_array — Fetch row as array
  • msql_fetch_field — Get field information
  • msql_fetch_object — Fetch row as object
  • msql_fetch_row — Get row as enumerated array
  • msql_field_flags — Get field flags
  • msql_field_len — Get field length
  • msql_field_name — Get the name of the specified field in a result
  • msql_field_seek — Set field offset
  • msql_field_table — Get table name for field
  • msql_field_type — Get field type
  • msql_fieldflags — Alias dla msql_field_flags
  • msql_fieldlen — Alias dla msql_field_len
  • msql_fieldname — Alias dla msql_field_name
  • msql_fieldtable — Alias dla msql_field_table
  • msql_fieldtype — Alias dla msql_field_type
  • msql_free_result — Free result memory
  • msql_list_dbs — List mSQL databases on server
  • msql_list_fields — List result fields
  • msql_list_tables — List tables in an mSQL database
  • msql_num_fields — Get number of fields in result
  • msql_num_rows — Get number of rows in result
  • msql_numfields — Alias dla msql_num_fields
  • msql_numrows — Alias dla msql_num_rows
  • msql_pconnect — Otwiera trwałe połączenie do serwera mSQL
  • msql_query — Send mSQL query
  • msql_regcase — Alias dla sql_regcase
  • msql_result — Get result data
  • msql_select_db — Select mSQL database
  • msql_tablename — Alias dla msql_result
  • msql — Alias dla msql_db_query
Podstawowe użycie
msql_affected_rows
mSQL


Returns number of affected rows

Funkcje mSQL
msql_close
Funkcje mSQL
PHP Manual

msql_affected_rows

(PHP 4, PHP 5)

msql_affected_rows — Returns number of affected rows

Opis

int msql_affected_rows ( resource $result )

Returns number of affected rows by the last SELECT, UPDATE or DELETE query associated with result.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

Zwracane wartości

Returns the number of affected rows on success, or FALSE on error.

Zobacz też:

  • msql_query() - Send mSQL query

Funkcje mSQL
msql_close
Funkcje mSQL


Zamyka połączenie z serwerem mSQL

msql_affected_rows
msql_connect
Funkcje mSQL
PHP Manual

msql_close

(PHP 4, PHP 5)

msql_close — Zamyka połączenie z serwerem mSQL

Opis

bool msql_close ([ resource $identyfikator_połączenia ] )

msql_close() zamyka nietrwałe połączenie do serwera mSQL skojarzone z określonym identyfikatorem połączenia.

Używanie msql_close() zazwyczaj nie jest konieczne, jako że nietrwałe połączenia są automatycznie zamykane po zakończeniu wykonywania skryptu. Patrz także: zwalnianie zasobów.

Parametry

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msql_connect() - Otwiera połączenie z serwerem mSQL
  • msql_pconnect() - Otwiera trwałe połączenie do serwera mSQL

msql_affected_rows
msql_connect
Funkcje mSQL


Otwiera połączenie z serwerem mSQL

msql_close
msql_create_db
Funkcje mSQL
PHP Manual

msql_connect

(PHP 4, PHP 5)

msql_connect — Otwiera połączenie z serwerem mSQL

Opis

resource msql_connect ([ string $nazwa_hosta ] )

msql_connect() nawiązuje połączenie z serwerem mSQL.

W przypadku kolejnego wywołania funkcji msql_connect() z takimi samymi argumentami, nie jest otwierane nowe połączenie, jednak w to miejsce powinien zostać zwrócony identyfikator już otwartego połączenia.

Połączenie z serwerem powinno zostać zamknięte wkrótce po tym, gdy wykonywanie skryptu PHP się zakończy, o ile nie zostanie zamknięte wcześniej przez jawne wywołanie funkcji msql_close().

Parametry

nazwa_hosta

Parametr nazwa_hosta może mieć dołączony numer portu np. hostname,port.

Jeśli go nie określono, to połączenie jest nawiązywane za pomocą gniazd domenowych Uniksa, które są znacznie bardziej wydajne niż połączenia TCP z hostem lokalnym.

Informacja:

Ta funkcja pozwala na stosowanie dwukropka (:) jako separatora hosta/portu, ale bardziej preferowaną metodą jest używanie przecinka (,).

Zwracane wartości

Zwraca identyfikator połączenia do mSQL w przypadku sukcesu lub FALSE w przypadku błędu.

Zobacz też:

  • msql_pconnect() - Otwiera trwałe połączenie do serwera mSQL
  • msql_close() - Zamyka połączenie z serwerem mSQL

msql_close
msql_create_db
Funkcje mSQL


Tworzy nową bazę danych na serwerze mSQL

msql_connect
msql_createdb
Funkcje mSQL
PHP Manual

msql_create_db

(PHP 4, PHP 5)

msql_create_db — Tworzy nową bazę danych na serwerze mSQL

Opis

bool msql_create_db ( string $nazwa_bazy_danych [, resource $identyfikator_połączenia ] )

msql_create_db() próbuje utworzyć nową bazę danych na serwerze mSQL.

Parametry

nazwa_bazy_danych

Nazwa nowej bazy danych mSQL.

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msql_drop_db() - Usuwa bazę danych z serwera mSQL

msql_connect
msql_createdb
Funkcje mSQL


Alias dla msql_create_db

msql_create_db
msql_data_seek
Funkcje mSQL
PHP Manual

msql_createdb

(PHP 4, PHP 5)

msql_createdb — Alias dla msql_create_db()

Opis

Ta funkcja jest aliasem dla: msql_create_db().

msql_create_db
msql_data_seek
Funkcje mSQL


Move internal row pointer

msql_createdb
msql_db_query
Funkcje mSQL
PHP Manual

msql_data_seek

(PHP 4, PHP 5)

msql_data_seek — Move internal row pointer

Opis

bool msql_data_seek ( resource $result , int $row_number )

msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point to the specified row number. The next call to msql_fetch_row() would return that row.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

row_number

The seeked row number.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_object() - Fetch row as object
  • msql_fetch_row() - Get row as enumerated array
  • msql_result() - Get result data

msql_createdb
msql_db_query
Funkcje mSQL


Send mSQL query

msql_data_seek
msql_dbname
Funkcje mSQL
PHP Manual

msql_db_query

(PHP 4, PHP 5)

msql_db_query — Send mSQL query

Opis

resource msql_db_query ( string $database , string $query [, resource $link_identifier ] )

msql_db_query() selects a database and executes a query on it.

Parametry

database

The name of the mSQL database.

query

The SQL query.

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Returns a positive mSQL query identifier to the query result, or FALSE on error.

Zobacz też:

  • msql_query() - Send mSQL query

msql_data_seek
msql_dbname
Funkcje mSQL


Alias dla msql_result

msql_db_query
msql_drop_db
Funkcje mSQL
PHP Manual

msql_dbname

(PHP 4, PHP 5)

msql_dbname — Alias dla msql_result()

Opis

Ta funkcja jest aliasem dla: msql_result().

msql_db_query
msql_drop_db
Funkcje mSQL


Usuwa bazę danych z serwera mSQL

msql_dbname
msql_error
Funkcje mSQL
PHP Manual

msql_drop_db

(PHP 4, PHP 5)

msql_drop_db — Usuwa bazę danych z serwera mSQL

Opis

bool msql_drop_db ( string $nazwa_bazy_danych [, resource $identyfikator_połączenia ] )

msql_drop_db() próbuje usunąć bazę danych z serwera mSQL.

Parametry

nazwa_bazy_danych

Nazwa bazy danych.

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msql_create_db() - Tworzy nową bazę danych na serwerze mSQL

msql_dbname
msql_error
Funkcje mSQL


Returns error message of last msql call

msql_drop_db
msql_fetch_array
Funkcje mSQL
PHP Manual

msql_error

(PHP 4, PHP 5)

msql_error — Returns error message of last msql call

Opis

string msql_error ( void )

msql_error() returns the last issued error by the mSQL server. Note that only the last error message is accessible with msql_error().

Zwracane wartości

The last error message or an empty string if no error was issued.

msql_drop_db
msql_fetch_array
Funkcje mSQL


Fetch row as array

msql_error
msql_fetch_field
Funkcje mSQL
PHP Manual

msql_fetch_array

(PHP 4, PHP 5)

msql_fetch_array — Fetch row as array

Opis

array msql_fetch_array ( resource $result [, int $result_type ] )

msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

result_type

A constant that can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Przykłady

Przykład #1 msql_fetch_array() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo $row['id'] . ': ' . $row['name'] . "\n";
}

msql_free_result($result);
?>

Rejestr zmian

Wersja | Opis
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

Zobacz też:

  • msql_fetch_row() - Get row as enumerated array
  • msql_fetch_object() - Fetch row as object
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

msql_error
msql_fetch_field
Funkcje mSQL


Get field information

msql_fetch_array
msql_fetch_object
Funkcje mSQL
PHP Manual

msql_fetch_field

(PHP 4, PHP 5)

msql_fetch_field — Get field information

Opis

object msql_fetch_field ( resource $result [, int $field_offset = 0 ] )

msql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

field_offset

The field offset. If not specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.

Zwracane wartości

Returns an object containing field information. The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • not_null - 1 if the column cannot be NULL

  • unique - 1 if the column is a unique key

  • type - the type of the column

Zobacz też:

  • msql_field_seek() - Set field offset

msql_fetch_array
msql_fetch_object
Funkcje mSQL


Fetch row as object

msql_fetch_field
msql_fetch_row
Funkcje mSQL
PHP Manual

msql_fetch_object

(PHP 4, PHP 5)

msql_fetch_object — Fetch row as object

Opis

object msql_fetch_object ( resource $result )

msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

Zwracane wartości

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Przykłady

Przykład #1 msql_fetch_object() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_object($result, MSQL_ASSOC)) {
    echo $row->id . ': ' . $row->name . "\n";
}

msql_free_result($result);
?>

Rejestr zmian

Wersja | Opis
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

Zobacz też:

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_row() - Get row as enumerated array
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

msql_fetch_field
msql_fetch_row
Funkcje mSQL


Get row as enumerated array

msql_fetch_object
msql_field_flags
Funkcje mSQL
PHP Manual

msql_fetch_row

(PHP 4, PHP 5)

msql_fetch_row — Get row as enumerated array

Opis

array msql_fetch_row ( resource $result )

msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Przykłady

Przykład #1 msql_fetch_row() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_row($result)) {
    echo $row[0] . ': ' . $row[1] . "\n";
}

msql_free_result($result);
?>

Rejestr zmian

Wersja | Opis
4.3.11 and 5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

Zobacz też:

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_object() - Fetch row as object
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data

msql_fetch_object
msql_field_flags
Funkcje mSQL


Get field flags

msql_fetch_row
msql_field_len
Funkcje mSQL
PHP Manual

msql_field_flags

(PHP 4, PHP 5)

msql_field_flags — Get field flags

Opis

string msql_field_flags ( resource $result , int $field_offset )

msql_field_flags() returns the field flags of the specified field.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

przesunięcie_pola

Liczbowe przesunięcie pola. przesunięcie_pola zaczyna się od wartości 1.

Zwracane wartości

Returns a string containing the field flags of the specified key. This can be: primary key not null, not null, primary key, unique not null or unique.

msql_fetch_row
msql_field_len
Funkcje mSQL


Get field length

msql_field_flags
msql_field_name
Funkcje mSQL
PHP Manual

msql_field_len

(PHP 4, PHP 5)

msql_field_len — Get field length

Opis

int msql_field_len ( resource $result , int $field_offset )

msql_field_len() returns the length of the specified field.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

przesunięcie_pola

Liczbowe przesunięcie pola. przesunięcie_pola zaczyna się od wartości 1.

Zwracane wartości

Returns the length of the specified field or FALSE on error.

msql_field_flags
msql_field_name
Funkcje mSQL


Get the name of the specified field in a result

msql_field_len
msql_field_seek
Funkcje mSQL
PHP Manual

msql_field_name

(PHP 4, PHP 5)

msql_field_name — Get the name of the specified field in a result

Opis

string msql_field_name ( resource $result , int $field_offset )

msql_field_name() gets the name of the specified field index.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

przesunięcie_pola

Liczbowe przesunięcie pola. przesunięcie_pola zaczyna się od wartości 1.

Zwracane wartości

The name of the field lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • msql_field_len() - Get field length

msql_field_len
msql_field_seek
Funkcje mSQL


Set field offset

msql_field_name
msql_field_table
Funkcje mSQL
PHP Manual

msql_field_seek

(PHP 4, PHP 5)

msql_field_seek — Set field offset

Opis

bool msql_field_seek ( resource $result , int $field_offset )

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

przesunięcie_pola

Liczbowe przesunięcie pola. przesunięcie_pola zaczyna się od wartości 1.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msql_fetch_field() - Get field information

msql_field_name
msql_field_table
Funkcje mSQL


Get table name for field

msql_field_seek
msql_field_type
Funkcje mSQL
PHP Manual

msql_field_table

(PHP 4, PHP 5)

msql_field_table — Get table name for field

Opis

int msql_field_table ( resource $result , int $field_offset )

Returns the name of the table that the specified field is in.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

przesunięcie_pola

Liczbowe przesunięcie pola. przesunięcie_pola zaczyna się od wartości 1.

Zwracane wartości

The name of the table on success lub FALSE w przypadku niepowodzenia.

msql_field_seek
msql_field_type
Funkcje mSQL


Get field type

msql_field_table
msql_fieldflags
Funkcje mSQL
PHP Manual

msql_field_type

(PHP 4, PHP 5)

msql_field_type — Get field type

Opis

string msql_field_type ( resource $result , int $field_offset )

msql_field_type() gets the type of the specified field index.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

przesunięcie_pola

Liczbowe przesunięcie pola. przesunięcie_pola zaczyna się od wartości 1.

Zwracane wartości

The type of the field. One of int, char, real, ident, null or unknown. This functions will return FALSE on failure.

msql_field_table
msql_fieldflags
Funkcje mSQL


Alias dla msql_field_flags

msql_field_type
msql_fieldlen
Funkcje mSQL
PHP Manual

msql_fieldflags

(PHP 4, PHP 5)

msql_fieldflags — Alias dla msql_field_flags()

Opis

Ta funkcja jest aliasem dla msql_field_flags().

msql_field_type
msql_fieldlen
Funkcje mSQL


Alias dla msql_field_len

msql_fieldflags
msql_fieldname
Funkcje mSQL
PHP Manual

msql_fieldlen

(PHP 4, PHP 5)

msql_fieldlen — Alias dla msql_field_len()

Opis

Ta funkcja jest aliasem dla msql_field_len().

msql_fieldflags
msql_fieldname
Funkcje mSQL


Alias dla msql_field_name

msql_fieldlen
msql_fieldtable
Funkcje mSQL
PHP Manual

msql_fieldname

(PHP 4, PHP 5)

msql_fieldname — Alias dla msql_field_name()

Opis

Ta funkcja jest aliasem dla msql_field_name().

msql_fieldlen
msql_fieldtable
Funkcje mSQL


Alias dla msql_field_table

msql_fieldname
msql_fieldtype
Funkcje mSQL
PHP Manual

msql_fieldtable

(PHP 4, PHP 5)

msql_fieldtable — Alias dla msql_field_table()

Opis

Ta funkcja jest aliasem dla msql_field_table().

msql_fieldname
msql_fieldtype
Funkcje mSQL


Alias dla msql_field_type

msql_fieldtable
msql_free_result
Funkcje mSQL
PHP Manual

msql_fieldtype

(PHP 4, PHP 5)

msql_fieldtype — Alias dla msql_field_type()

Opis

Ta funkcja jest aliasem dla msql_field_type().

msql_fieldtable
msql_free_result
Funkcje mSQL


Free result memory

msql_fieldtype
msql_list_dbs
Funkcje mSQL
PHP Manual

msql_free_result

(PHP 4, PHP 5)

msql_free_result — Free result memory

Opis

bool msql_free_result ( resource $result )

msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

msql_fieldtype
msql_list_dbs
Funkcje mSQL


List mSQL databases on server

msql_free_result
msql_list_fields
Funkcje mSQL
PHP Manual

msql_list_dbs

(PHP 4, PHP 5)

msql_list_dbs — List mSQL databases on server

Opis

resource msql_list_dbs ([ resource $link_identifier ] )

msql_list_tables() lists the databases available on the specified link_identifier.

Parametry

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

Zobacz też:

  • msql_list_tables() - List tables in an mSQL database
  • msql_list_fields() - List result fields

msql_free_result
msql_list_fields
Funkcje mSQL


List result fields

msql_list_dbs
msql_list_tables
Funkcje mSQL
PHP Manual

msql_list_fields

(PHP 4, PHP 5)

msql_list_fields — List result fields

Opis

resource msql_list_fields ( string $database , string $tablename [, resource $link_identifier ] )

msql_list_fields() returns information about the given table.

Parametry

database

The name of the database.

tablename

The name of the table.

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

Zobacz też:

  • msql_list_tables() - List tables in an mSQL database
  • msql_list_dbs() - List mSQL databases on server

msql_list_dbs
msql_list_tables
Funkcje mSQL


List tables in an mSQL database

msql_list_fields
msql_num_fields
Funkcje mSQL
PHP Manual

msql_list_tables

(PHP 4, PHP 5)

msql_list_tables — List tables in an mSQL database

Opis

resource msql_list_tables ( string $database [, resource $link_identifier ] )

msql_list_tables() lists the tables on the specified database.

Parametry

database

The name of the database.

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

Zobacz też:

  • msql_list_fields() - List result fields
  • msql_list_dbs() - List mSQL databases on server

msql_list_fields
msql_num_fields
Funkcje mSQL


Get number of fields in result

msql_list_tables
msql_num_rows
Funkcje mSQL
PHP Manual

msql_num_fields

(PHP 4, PHP 5)

msql_num_fields — Get number of fields in result

Opis

int msql_num_fields ( resource $result )

msql_num_fields() returns the number of fields in a result set.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

Zwracane wartości

Returns the number of fields in the result set.

Zobacz też:

  • msql_query() - Send mSQL query
  • msql_fetch_field() - Get field information
  • msql_num_rows() - Get number of rows in result

msql_list_tables
msql_num_rows
Funkcje mSQL


Get number of rows in result

msql_num_fields
msql_numfields
Funkcje mSQL
PHP Manual

msql_num_rows

(PHP 4, PHP 5)

msql_num_rows — Get number of rows in result

Opis

int msql_num_rows ( resource $query_identifier )

msql_num_rows() returns the number of rows in a result set.

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

Zwracane wartości

Returns the number of rows in the result set.

Zobacz też:

  • msql_num_fields() - Get number of fields in result

msql_num_fields
msql_numfields
Funkcje mSQL


Alias dla msql_num_fields

msql_num_rows
msql_numrows
Funkcje mSQL
PHP Manual

msql_numfields

(PHP 4, PHP 5)

msql_numfields — Alias dla msql_num_fields()

Opis

Ta funkcja jest aliasem dla msql_num_fields().

msql_num_rows
msql_numrows
Funkcje mSQL


Alias dla msql_num_rows

msql_numfields
msql_pconnect
Funkcje mSQL
PHP Manual

msql_numrows

(PHP 4, PHP 5)

msql_numrows — Alias dla msql_num_rows()

Opis

Ta funkcja jest aliasem dla msql_num_rows().

msql_numfields
msql_pconnect
Funkcje mSQL


Otwiera trwałe połączenie do serwera mSQL

msql_numrows
msql_query
Funkcje mSQL
PHP Manual

msql_pconnect

(PHP 4, PHP 5)

msql_pconnect — Otwiera trwałe połączenie do serwera mSQL

Opis

resource msql_pconnect ([ string $nazwa_hosta ] )

msql_pconnect() zachowuje się prawie jak msql_connect() z dwoma zasadniczymi różnicami:

Pierwsza, podczas łączenia funkcja najpierw spróbuje znaleźć połączenie (trwałe), już otwarte dla tego samego hosta. Jeżeli je znajdzie, to jego identyfikator zostanie zwrócony zamiast otwierania nowego połączenia.

Druga, połączenie do serwera mSQL nie zostanie zamknięte po zakończeniu wykonywania skryptu. Zamiast tego połączenie pozostanie otwarte do późniejszego użycia (msql_close() nie zamyka połączeń nawiązanych za pomocą tej funkcji).

Parametry

nazwa_hosta

Parametr nazwa_hosta może mieć dołączony numer portu np. nazwa_hosta,port.

Jeśli go nie określono, to połączenie jest nawiązywane za pomocą gniazd domenowych Uniksa, które są znacznie bardziej wydajne niż połączenia TCP z hostem lokalnym.

Informacja: Ta funkcja pozwala na stosowanie dwukropka (:) jako separatora hosta/portu, ale bardziej preferowaną metodą jest używanie przecinka (,).

Zwracane wartości

Zwraca identyfikator połączenia do mSQL w przypadku sukcesu lub FALSE w przypadku błędu.

Zobacz też:

  • msql_connect() - Otwiera połączenie z serwerem mSQL
  • msql_close() - Zamyka połączenie z serwerem mSQL

msql_numrows
msql_query
Funkcje mSQL


Send mSQL query

msql_pconnect
msql_regcase
Funkcje mSQL
PHP Manual

msql_query

(PHP 4, PHP 5)

msql_query — Send mSQL query

Opis

resource msql_query ( string $query [, resource $link_identifier ] )

msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parametry

query

The SQL query.

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Returns a positive mSQL query identifier on success, or FALSE on error.

Przykłady

Przykład #1 msql_query() example

<?php
$link = msql_connect("dbserver")
   or die("unable to connect to msql server: " . msql_error());
msql_select_db("db", $link)
   or die("unable to select database 'db': " . msql_error());

$result = msql_query("SELECT * FROM table WHERE id=1", $link);
if (!$result) {
   die("query failed: " . msql_error());
}

while ($row = msql_fetch_array($result)) {
    echo $row["id"];
}
?>

Zobacz też:

  • msql_db_query() - Send mSQL query
  • msql_select_db() - Select mSQL database
  • msql_connect() - Otwiera połączenie z serwerem mSQL

msql_pconnect
msql_regcase
Funkcje mSQL


Alias dla sql_regcase

msql_query
msql_result
Funkcje mSQL
PHP Manual

msql_regcase

(PHP 4, PHP 5)

msql_regcase — Alias dla sql_regcase()

Opis

Ta funkcja jest aliasem dla sql_regcase().

msql_query
msql_result
Funkcje mSQL


Get result data

msql_regcase
msql_select_db
Funkcje mSQL
PHP Manual

msql_result

(PHP 4, PHP 5)

msql_result — Get result data

Opis

string msql_result ( resource $result , int $row [, mixed $field ] )

msql_result() returns the contents of one cell from a mSQL result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they are often much quicker than msql_result().

Recommended high-performance alternatives:
msql_fetch_row(),
msql_fetch_array(), and
msql_fetch_object().

Parametry

wynik

Wynik w postaci zmiennej typu resource, który jest przetwarzany. Wynik pochodzi z wywołania funkcji msql_query().

row

The row offset.

field

Can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname.). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.

Informacja:

Specifying a numeric field offset is much quicker than specifying a fieldname or tablename.fieldname.

Zwracane wartości

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_regcase
msql_select_db
Funkcje mSQL


Select mSQL database

msql_result
msql_tablename
Funkcje mSQL
PHP Manual

msql_select_db

(PHP 4, PHP 5)

msql_select_db — Select mSQL database

Opis

bool msql_select_db ( string $database_name [, resource $link_identifier ] )

msql_select_db() sets the current active database on the server that's associated with the specified link_identifier.

Subsequent calls to msql_query() will be made on the active database.

Parametry

database_name

The database name.

identyfikator_połączenia

Połączenie mSQL. Jeśli nie zostanie podany, używane jest ostatnie połączenie otwarte przez msql_connect(). Jeśli nie zostanie ono znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja msql_connect(), i je użyje.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msql_connect() - Otwiera połączenie z serwerem mSQL
  • msql_pconnect() - Otwiera trwałe połączenie do serwera mSQL
  • msql_query() - Send mSQL query

msql_result
msql_tablename
Funkcje mSQL


Alias dla msql_result

msql_select_db
msql
Funkcje mSQL
PHP Manual

msql_tablename

(PHP 4, PHP 5)

msql_tablename — Alias dla msql_result()

Opis

Ta funkcja jest aliasem dla msql_result().

msql_select_db
msql
Funkcje mSQL


Alias dla msql_db_query

msql_tablename
Mssql
Funkcje mSQL
PHP Manual

msql

(PHP 4, PHP 5)

msql — Alias dla msql_db_query()

Opis

Ta funkcja jest aliasem dla msql_db_query().

msql_tablename
Mssql
Funkcje mSQL


Microsoft SQL Server

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje Mssql
    • mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
    • mssql_close — Zamyka połączenie z MS SQL Server
    • mssql_connect — Otwiera połączenie z serwerem MS SQL
    • mssql_data_seek — Moves internal row pointer
    • mssql_execute — Executes a stored procedure on a MS SQL server database
    • mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • mssql_fetch_assoc — Returns an associative array of the current row in the result
    • mssql_fetch_batch — Returns the next batch of records
    • mssql_fetch_field — Get field information
    • mssql_fetch_object — Fetch row as object
    • mssql_fetch_row — Get row as enumerated array
    • mssql_field_length — Get the length of a field
    • mssql_field_name — Get the name of a field
    • mssql_field_seek — Seeks to the specified field offset
    • mssql_field_type — Gets the type of a field
    • mssql_free_result — Free result memory
    • mssql_free_statement — Free statement memory
    • mssql_get_last_message — Zwraca ostatni komunikat z serwera
    • mssql_guid_string — Converts a 16 byte binary GUID to a string
    • mssql_init — Initializes a stored procedure or a remote stored procedure
    • mssql_min_error_severity — Ustawia poziom ważności zwracanych kodów błędów
    • mssql_min_message_severity — Ustawia poziom ważności zwracanych komunikatów o błędach
    • mssql_next_result — Move the internal result pointer to the next result
    • mssql_num_fields — Zwraca liczbę pól w zbiorze wynikowym
    • mssql_num_rows — Zwraca liczbę wierszy w zbiorze wynikowym
    • mssql_pconnect — Open persistent MS SQL connection
    • mssql_query — Wysyła zapytanie do serwera MS SQL
    • mssql_result — Get result data
    • mssql_rows_affected — Zwraca liczbę rekordów przetworzonych przez ostatnie zapytanie
    • mssql_select_db — Select MS SQL database
msql
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Te funkcje umożliwiają dostęp do serwerów baz danych MS SQL Server.

To rozszerzenie nie jest już dostępne na Windows od PHP 5.3 i nowszych wersji.

SQLSRV - opcjonalny sterownik do MS SQL jest dostępny od Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Mssql
Instalacja/Konfiguracja
Mssql


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Mssql


Wymagania

Wymagania dla platform Win32.

Rozszerzenie wymaga aby w systemie, w którym jest zainstalowany PHP, znajdowały się narzędzia MS SQL Client Tools. Client Tools można zainstalować z płyty instalacyjnej serwera MS SQL Server lub skopiować plik ntwdblib.dll z katalogu \winnt\system32 systemu, na którym jest uruchomiony serwer do katalogu \winnt\system32 systemu, na którym znajduje się PHP. Skopiowanie ntwdblib.dll powinno umożliwić tylko dostęp poprzez potoki nazwane. Pełna konfiguracja klienta wymaga instalacji wszystkich narzędzi Client Tools.

To rozszerzenie nie jest już dostępne na Windows od PHP 5.3 i nowszych wersji.

SqlSrv - opcjonalny sterownik do MS SQL jest dostępny na witrynie firmy Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Wymagania dla platform Unix/Linux.

Aby używać rozszerzenia MSSQL w Unix/Linux, należy najpierw skompilować i zainstalować bibliotekę FreeTDS. Kod źródłowy i instrukcje instalacji są dostępne na witrynie FreeTDS: » http://www.freetds.org/

Informacja:

W Windows jest używana DBLIB Microsoftu. Funkcje, które zwracają nazwy kolumn używają wewnętrznej funkcji DBLIB dbcolname(). DBLIB została zaprojektowana dla SQL Server 6.x gdzie maksymalna długość identyfikatora wynosiła 30. Z tego powodu, maksymalna długość zwracanej nazwy kolumny wynosi 30 znaków. Na platformach gdzie używa się FreeTDS (Linux), nie ma takiego problemu.

Informacja:

W Windows z zainstalowanym serwerem MSSQL 2005 lub nowszym należy skopiować bibliotekę ntwdblib.dll do katalogu w którym jest zainstalowany PHP i w razie potrzeby nadpisać znajdującą się tam bibliotekę. Należy to zrobić, gdyż wersja biblioteki dystrybuowana z PHP jest przestarzała. Innym sposobem nawiązania połączenia z MSSQL są rozszerzenia: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx, ODBC, PDO_DBLIB lub PDO_ODBC.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Rozszerzenie MSSQL włącza się poprzez dodanie linii extension=php_mssql.dll w php.ini.

Aby te funkcje działały, należy skompilować PHP z opcją --with-mssql[=DIR] , gdzie DIR jest ścieżką instalacji FreeTDS. Natomiast FreeTDS powinien być skompilowany z opcją --enable-msdblib .

Ostrzeżenie

Funkcje MS SQL są aliasami funkcji Sybase jeśli PHP został skompilowany z rozszerzeniem Sybase i bez rozszerzenia MS SQL.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracyjne MS SQL Server
Nazwa | Wartość domyślna | Możliwość zmian | Rejestr zmian
mssql.allow_persistent | "1" | PHP_INI_SYSTEM |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM |
mssql.max_links | "-1" | PHP_INI_SYSTEM |
mssql.min_error_severity | "10" | PHP_INI_ALL |
mssql.min_message_severity | "10" | PHP_INI_ALL |
mssql.compatability_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL | Dostępna od PHP 4.1.0.
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.batchsize | "0" | PHP_INI_ALL | Dostępna od PHP 4.0.4.
mssql.datetimeconvert | "1" | PHP_INI_ALL | Dostępna od PHP 4.2.0.
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Dostępna od PHP 4.3.0.
mssql.max_procs | "-1" | PHP_INI_ALL | Dostępna od PHP 4.3.0.
mssql.charset | "" | PHP_INI_ALL | Dostępna od PHP 5.1.2, gdy zostanie zbudowany z obsługą FreeTDS 7.0 lub nowszej.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

identyfikator połączenia mssql

Identyfikator połączenia zwrócony przez mssql_connect() lub mssql_pconnect().

zbiór wynikowy mssql

Zbiór wynikowy zwrócony przez mssql_query() dla zapytań SELECT.

identyfikator instrukcji mssql

Identyfikator instrukcji zwrócony przez mssql_init().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

MSSQL_ASSOC (integer)
Zwraca tablicę asocjacyjną. Używane w funkcji mssql_fetch_array() jako parametr dla result_type.
MSSQL_NUM (integer)
Zwraca tablicę numeryczną. Używane w funkcji mssql_fetch_array() jako parametr result_type.
MSSQL_BOTH (integer)
Zwraca tablicę z kluczami numerycznymi i kluczami jako nazwy pól. Jest to wartość domyślna w funkcji mssql_fetch_array() jako parametr result_type.
SQLTEXT (integer)
Wskazuje typ 'TEXT' w MSSQL używany przez mssql_bind() jako parametr type.
SQLVARCHAR (integer)
Wskazuje typ 'VARCHAR' w MSSQL używany przez mssql_bind() jako parametr type.
SQLCHAR (integer)
Wskazuje typ 'CHAR' w MSSQL używany przez mssql_bind() jako parametr type.
SQLINT1 (integer)
Reprezentuje jeden bajt z zakresem od -128 do 127.
SQLINT2 (integer)
Reprezentuje dwa bajty z zakresem od -32768 do 32767.
SQLINT4 (integer)
Reprezentuje cztery bajty z zakresem od -2147483648 do 2147483647.
SQLBIT (integer)
Wskazuje typ 'BIT' w MSSQL używany przez mssql_bind() jako parametr type.
SQLFLT4 (integer)
Reprezentuje czterobajtową liczbę typu float.
SQLFLT8 (integer)
Reprezentuje ośmiobajtową liczbę typu float.
Typy zasobów
Funkcje Mssql
Mssql


Funkcje Mssql

Spis treści

  • mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_close — Zamyka połączenie z MS SQL Server
  • mssql_connect — Otwiera połączenie z serwerem MS SQL
  • mssql_data_seek — Moves internal row pointer
  • mssql_execute — Executes a stored procedure on a MS SQL server database
  • mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_assoc — Returns an associative array of the current row in the result
  • mssql_fetch_batch — Returns the next batch of records
  • mssql_fetch_field — Get field information
  • mssql_fetch_object — Fetch row as object
  • mssql_fetch_row — Get row as enumerated array
  • mssql_field_length — Get the length of a field
  • mssql_field_name — Get the name of a field
  • mssql_field_seek — Seeks to the specified field offset
  • mssql_field_type — Gets the type of a field
  • mssql_free_result — Free result memory
  • mssql_free_statement — Free statement memory
  • mssql_get_last_message — Zwraca ostatni komunikat z serwera
  • mssql_guid_string — Converts a 16 byte binary GUID to a string
  • mssql_init — Initializes a stored procedure or a remote stored procedure
  • mssql_min_error_severity — Ustawia poziom ważności zwracanych kodów błędów
  • mssql_min_message_severity — Ustawia poziom ważności zwracanych komunikatów o błędach
  • mssql_next_result — Move the internal result pointer to the next result
  • mssql_num_fields — Zwraca liczbę pól w zbiorze wynikowym
  • mssql_num_rows — Zwraca liczbę wierszy w zbiorze wynikowym
  • mssql_pconnect — Open persistent MS SQL connection
  • mssql_query — Wysyła zapytanie do serwera MS SQL
  • mssql_result — Get result data
  • mssql_rows_affected — Zwraca liczbę rekordów przetworzonych przez ostatnie zapytanie
  • mssql_select_db — Select MS SQL database
Stałe predefiniowane
mssql_bind
Mssql


Adds a parameter to a stored procedure or a remote stored procedure

Funkcje Mssql
mssql_close
Funkcje Mssql
PHP Manual

mssql_bind

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure

Opis

bool mssql_bind ( resource $stmt , string $param_name , mixed &$var , int $type [, bool $is_output = false [, bool $is_null = false [, int $maxlen = -1 ]]] )

Binds a parameter to a stored procedure or a remote stored procedure.

Parametry

stmt

Statement resource, obtained with mssql_init().

param_name

The parameter name, as a string.

Informacja:

You have to include the @ character, like in the T-SQL syntax. See the explanation included in mssql_execute().

var

The PHP variable you'll bind the MSSQL parameter to. It is passed by reference, to retrieve OUTPUT and RETVAL values after the procedure execution.

type

One of: SQLTEXT, SQLVARCHAR, SQLCHAR, SQLINT1, SQLINT2, SQLINT4, SQLBIT, SQLFLT4, SQLFLT8, SQLFLTN.

is_output

Whether the value is an OUTPUT parameter or not. If it's an OUTPUT parameter and you don't mention it, it will be treated as a normal input parameter and no error will be thrown.

is_null

Whether the parameter is NULL or not. Passing the NULL value as var will not do the job.

maxlen

Used with char/varchar values. You have to indicate the length of the data so if the parameter is a varchar(50), the type must be SQLVARCHAR and this value 50.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mssql_bind() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Create a new stored prodecure
$stmt = mssql_init('NewUserRecord');

// Bind the field names
mssql_bind($stmt, '@username',  'Kalle',  SQLVARCHAR,  false,  false,  60);
mssql_bind($stmt, '@name',      'Kalle',  SQLVARCHAR,  false,  false,  60);
mssql_bind($stmt, '@age',       19,       SQLINT1,     false,  false,   3);

// Execute
mssql_execute($stmt);

// Free statement
mssql_free_statement($stmt);
?>

Zobacz też:

  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_free_statement() - Free statement memory
  • mssql_init() - Initializes a stored procedure or a remote stored procedure

Funkcje Mssql
mssql_close
Funkcje Mssql


Zamyka połączenie z MS SQL Server

mssql_bind
mssql_connect
Funkcje Mssql
PHP Manual

mssql_close

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_close — Zamyka połączenie z MS SQL Server

Opis

bool mssql_close ([ resource $identyfikator_połączenia ] )

Zamyka połączenie z MS SQL Server skojarzone z podanym identyfikatorem połączenia. Jeśli identyfikator_połączenia nie został podany, przyjmowane jest ostatnio otwarte połączenie.

Stosowanie tej funkcji zazwyczaj nie jest potrzebne, jako że niestałe połączenia są automatycznie zamykane po zakończeniu wykonywania skryptu.

Parametry

identyfikator_połączenia

Identyfikator połączenia MS SQL, zwracany przez mssql_connect().

Ta funkcje nie zamyka stałych połączeń nawiązanych za pomocą mssql_pconnect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład mssql_close()

<?php
// Połączenie do MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Wykonanie operacji na bazie danych

// Zamknięcie połączenia z MSSQL
mssql_close($link);
?>

Zobacz też:

  • mssql_connect() - Otwiera połączenie z serwerem MS SQL
  • mssql_pconnect() - Open persistent MS SQL connection

mssql_bind
mssql_connect
Funkcje Mssql


Otwiera połączenie z serwerem MS SQL

mssql_close
mssql_data_seek
Funkcje Mssql
PHP Manual

mssql_connect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_connect — Otwiera połączenie z serwerem MS SQL

Opis

resource mssql_connect ([ string $nazwa_serwera [, string $nazwa_użytkownika [, string $hasło [, bool $nowy_identyfikator_połączenia = false ]]]] )

mssql_connect() nawiązuje połączenie do serwera MS SQL.

Połączenie do serwera powinno zostać zamknięte automatycznie zaraz po zakończeniu wykonywania skryptu, o ile nie zostanie zamknięte wcześniej poprzez jawne wywołanie mssql_close().

Parametry

nazwa_serwera

Określa MS SQL Server. Może zawierać numer portu np. hostname:port (Linux), lub hostname,port (Windows).

nazwa_użytkownika

Login użytkownika.

hasło

Hasło użytkownika.

nowy_identyfikator_połączenia

Jeśli następuje kolejne wywołanie mssql_connect() z tymi samymi argumentami, nie jest nawiązywanie nowe połączenie, lecz zamiast tego zwracany jest identyfikator już otwartego połączenia. Ten parametr modyfikuje to zachowanie tak, że mssql_connect() zawsze otwiera nowe połączenie, nawet gdy mssql_connect() była wywołana wcześniej z takimi samymi parametrami.

Zwracane wartości

Zwraca identyfikator połączenia do MS SQL w przypadku powodzenia lub FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
4.4.1 i 5.1.0 | Dodano parametr nowy_identyfikator_połączenia

Przykłady

Przykład #1 mssql_connect() example

<?php
// Serwer w następującym formacie: <komputer>\<nazwa instancji> lub
// <serwer>,<port> jeśli używany jest niestandardowy port
$server = 'KALLESPC\SQLEXPRESS';

// Połączenie do MSSQL
$link = mssql_connect($server, 'sa', 'phpfi');

if (!$link) {
    die('Wystąpił błąd podczas połączenia do MSSQL');
}
?>

Zobacz też:

  • mssql_close() - Zamyka połączenie z MS SQL Server
  • mssql_pconnect() - Open persistent MS SQL connection

mssql_close
mssql_data_seek
Funkcje Mssql


Moves internal row pointer

mssql_connect
mssql_execute
Funkcje Mssql
PHP Manual

mssql_data_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_data_seek — Moves internal row pointer

Opis

bool mssql_data_seek ( resource $result_identifier , int $row_number )

mssql_data_seek() moves the internal row pointer of the MS SQL result associated with the specified result identifier to point to the specified row number, first row being number 0. The next call to mssql_fetch_row() would return that row.

Parametry

result_identifier

The result resource that is being evaluated.

row_number

The desired row number of the new result pointer.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mssql_data_seek() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Select all people
$result = mssql_query('SELECT [name], [age] FROM [persons] WHERE [age] >= 13');

if (!$result) {
    die('Query failed.');
}

// Select every 4th student in the results
for ($i = mssql_num_rows($result) - 1; $i % 4; $i++) {
    if (!mssql_data_seek($result, $i)) {
        continue;
    }

    // Fetch the row ...
}

// Free the query result
mssql_free_result($result);
?>

mssql_connect
mssql_execute
Funkcje Mssql


Executes a stored procedure on a MS SQL server database

mssql_data_seek
mssql_fetch_array
Funkcje Mssql
PHP Manual

mssql_execute

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_execute — Executes a stored procedure on a MS SQL server database

Opis

mixed mssql_execute ( resource $stmt [, bool $skip_results = false ] )

Executes a stored procedure on a MS SQL server database

Parametry

stmt

Statement handle obtained with mssql_init().

skip_results

Whenever to skip the results or not.

Przykłady

Przykład #1 mssql_execute() example

<?php
// Create a new statement
$stmt = mssql_init('NewBlogEntry');

// Some data strings
$title = 'Test of blogging system';
$content = 'If you can read this, then the new system is compatible with MSSQL';

// Bind values
mssql_bind($stmt, '@author',    'Felipe Pena',  SQLVARCHAR,     false,  false,   60);
mssql_bind($stmt, '@date',      '08/10/2008',   SQLVARCHAR,     false,  false,   20);
mssql_bind($stmt, '@title',     $title,         SQLVARCHAR,     false,  false,   60);
mssql_bind($stmt, '@content',   $content,       SQLTEXT);

// Execute the statement
mssql_execute($stmt);

// And we can free it like so:
mssql_free_statement($stmt);
?>

Notatki

Informacja:

If the stored procedure returns parameters or a return value these will be available after the call to mssql_execute() unless the stored procedure returns more than one result set. In that case use mssql_next_result() to shift through the results. When the last result has been processed the output parameters and return values will be available.

Zobacz też:

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_free_statement() - Free statement memory
  • mssql_init() - Initializes a stored procedure or a remote stored procedure

mssql_data_seek
mssql_fetch_array
Funkcje Mssql


Fetch a result row as an associative array, a numeric array, or both

mssql_execute
mssql_fetch_assoc
Funkcje Mssql
PHP Manual

mssql_fetch_array

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Opis

array mssql_fetch_array ( resource $result [, int $result_type = MSSQL_BOTH ] )

mssql_fetch_array() is an extended version of mssql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using mssql_fetch_array() is NOT significantly slower than using mssql_fetch_row(), while it provides a significant added value.

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

result_type

The type of array that is to be fetched. It's a constant and can take the following values: MSSQL_ASSOC, MSSQL_NUM, and MSSQL_BOTH.

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Przykłady

Przykład #1 mssql_fetch_array() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    // The following is equal to the code below:
    //
    // while ($row = mssql_fetch_row($query)) {

    while ($row = mssql_fetch_array($query, MSSQL_NUM)) {
        // ...
    }
}

// Free the query result
mssql_free_result($query);
?>

Notatki

Informacja: Nazwy pól zwracane przez tą funkcję rozróżniają wielkość znaków.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Zobacz też:

  • mssql_fetch_row() - Get row as enumerated array

mssql_execute
mssql_fetch_assoc
Funkcje Mssql


Returns an associative array of the current row in the result

mssql_fetch_array
mssql_fetch_batch
Funkcje Mssql
PHP Manual

mssql_fetch_assoc

(PHP 4 >= 4.2.0, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_assoc — Returns an associative array of the current row in the result

Opis

array mssql_fetch_assoc ( resource $result_id )

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mssql_fetch_assoc() is equivalent to calling mssql_fetch_array() with MSSQL_ASSOC for the optional second parameter.

Parametry

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Zwracane wartości

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Przykłady

Przykład #1 mssql_fetch_assoc() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
}
else
{
    // Print a nice list of users in the format of:
    // * name (username)

    echo '<ul>';

    while ($row = mssql_fetch_assoc($query)) {
        echo '<li>' . $row['name'] . ' (' . $row['username'] . ')</li>';
    }

    echo '</ul>';
}

// Free the query result
mssql_free_result($query);
?>

mssql_fetch_array
mssql_fetch_batch
Funkcje Mssql


Returns the next batch of records

mssql_fetch_assoc
mssql_fetch_field
Funkcje Mssql
PHP Manual

mssql_fetch_batch

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_batch — Returns the next batch of records

Opis

int mssql_fetch_batch ( resource $result )

Returns the next batch of records

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Zwracane wartości

Returns the batch number as an integer.

Przykłady

Przykład #1 mssql_fetch_batch() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Send a query
$result = mssql_query('SELECT * FROM [php].[dbo].[people]', $link, 100);
$records = 10;

while ($records >= 0) {
    while ($row = mssql_fetch_assoc($result)) {
        // Do stuff ...
    }

    --$records;
}

if ($batchsize = mssql_fetch_batch($result)) {
    // $batchsize is the number of records left
    // in the result, but not shown above
}
?>

mssql_fetch_assoc
mssql_fetch_field
Funkcje Mssql


Get field information

mssql_fetch_batch
mssql_fetch_object
Funkcje Mssql
PHP Manual

mssql_fetch_field

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_field — Get field information

Opis

object mssql_fetch_field ( resource $result [, int $field_offset = -1 ] )

mssql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

field_offset

The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0.

Zwracane wartości

Returns an object containing field information.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
  • column_source - the table from which the column was taken
  • max_length - maximum length of the column
  • numeric - 1 if the column is numeric
  • type - the column type.

Przykłady

Przykład #1 mssql_fetch_field() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

// Construct table
echo '<h3>Table structure for \'persons\'</h3>';
echo '<table border="1">';

// Table header
echo '<thead>';
echo '<tr>';
echo '<td>Field name</td>';
echo '<td>Data type</td>';
echo '<td>Max length</td>';
echo '</tr>';
echo '</thead>';

// Dump all fields
echo '<tbody>';

for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    // Fetch the field information
    $field = mssql_fetch_field($query, $i);

    // Print the row
    echo '<tr>';
    echo '<td>' . $field->name . '</td>';
    echo '<td>' . strtoupper($field->type) . '</td>';
    echo '<td>' . $field->max_length . '</td>';
    echo '</tr>';
}

echo '</tbody>';
echo '</table>';

// Free the query result
mssql_free_result($query);
?>

Zobacz też:

  • mssql_field_seek() - Seeks to the specified field offset

mssql_fetch_batch
mssql_fetch_object
Funkcje Mssql


Fetch row as object

mssql_fetch_field
mssql_fetch_row
Funkcje Mssql
PHP Manual

mssql_fetch_object

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_object — Fetch row as object

Opis

object mssql_fetch_object ( resource $result )

mssql_fetch_object() is similar to mssql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is insignificant).

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Zwracane wartości

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Przykłady

Przykład #1 mssql_fetch_object() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    // Print a nice list of users in the format of:
    // * name (username)

    echo '<ul>';

    while ($row = mssql_fetch_object($query)) {
        echo '<li>' . $row->name . ' (' . $row->username . ')</li>';
    }

    echo '</ul>';
}

// Free the query result
mssql_free_result($query);
?>

Notatki

Informacja: Nazwy pól zwracane przez tą funkcję rozróżniają wielkość znaków.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Zobacz też:

  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_row() - Get row as enumerated array

mssql_fetch_field
mssql_fetch_row
Funkcje Mssql


Get row as enumerated array

mssql_fetch_object
mssql_field_length
Funkcje Mssql
PHP Manual

mssql_fetch_row

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_row — Get row as enumerated array

Opis

array mssql_fetch_row ( resource $result )

mssql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to mssql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Przykłady

Przykład #1 mssql_fetch_row() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Query to execute
$query = mssql_query('SELECT [id], [quote] FROM [quotes] WHERE [id] = \'42\'', $link);

// Did the query fail?
if (!$query) {
    die('MSSQL error: ' . mssql_get_last_message());
}

// Fetch the row
$row = mssql_fetch_row($query);

// Print the 'quote'
echo 'Quote #' . $row[0] . ': "' . $row[1] . '"';
?>

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

Quote #42: "The answer to everything..."

Notatki

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Zobacz też:

  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_object() - Fetch row as object
  • mssql_data_seek() - Moves internal row pointer
  • mssql_result() - Get result data

mssql_fetch_object
mssql_field_length
Funkcje Mssql


Get the length of a field

mssql_fetch_row
mssql_field_name
Funkcje Mssql
PHP Manual

mssql_field_length

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_length — Get the length of a field

Opis

int mssql_field_length ( resource $result [, int $offset = -1 ] )

Returns the length of field no. offset in result.

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Zwracane wartości

The length of the specified field index on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 mssql_field_length() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Print the field length
echo 'The field \'age\' has a data length of ' . mssql_field_length($query, 1);

// Free the query result
mssql_free_result($query);
?>

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

The field 'age' has a data length of 4

Notatki

Informacja: Note to Windows Users

Due to a limitation in the underlying API used by PHP (MS DBLib C API), the length of VARCHAR fields is limited to 255. If you need to store more data, use a TEXT field instead.

Zobacz też:

  • mssql_field_name() - Get the name of a field
  • mssql_field_type() - Gets the type of a field

mssql_fetch_row
mssql_field_name
Funkcje Mssql


Get the name of a field

mssql_field_length
mssql_field_seek
Funkcje Mssql
PHP Manual

mssql_field_name

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_name — Get the name of a field

Opis

string mssql_field_name ( resource $result [, int $offset = -1 ] )

Returns the name of field no. offset in result.

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Zwracane wartości

The name of the specified field index on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 mssql_field_name() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name], [email] FROM [php].[dbo].[userlist]');

echo 'Result set contains the following field(s):', PHP_EOL;

// Dump all field names in result
for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    echo ' - ' . mssql_field_name($query, $i), PHP_EOL;
}

// Free the query result
mssql_free_result($query);
?>

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

Result set contains the following field(s):
 - username
 - name
 - email

Zobacz też:

  • mssql_field_length() - Get the length of a field
  • mssql_field_type() - Gets the type of a field

mssql_field_length
mssql_field_seek
Funkcje Mssql


Seeks to the specified field offset

mssql_field_name
mssql_field_type
Funkcje Mssql
PHP Manual

mssql_field_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_seek — Seeks to the specified field offset

Opis

bool mssql_field_seek ( resource $result , int $field_offset )

Seeks to the specified field offset. If the next call to mssql_fetch_field() won't include a field offset, this field would be returned.

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

field_offset

The field offset, starts at 0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using mssql_field_seek() on the example for mssql_fetch_field()

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

// Construct table
echo '<h3>Table structure for \'persons\'</h3>';
echo '<table border="1">';

// Table header
echo '<thead>';
echo '<tr>';
echo '<td>Field name</td>';
echo '<td>Data type</td>';
echo '<td>Max length</td>';
echo '</tr>';
echo '</thead>';

// Dump all fields
echo '<tbody>';

for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    // Fetch the field information, notice the
    // field_offset parameter is not set. See
    // the mssql_field_seek call below
    $field = mssql_fetch_field($query);

    // Print the row
    echo '<tr>';
    echo '<td>' . $field->name . '</td>';
    echo '<td>' . strtoupper($field->type) . '</td>';
    echo '<td>' . $field->max_length . '</td>';
    echo '</tr>';

    // Move the internal seek pointer to the next
    // row in the result set
    mssql_field_seek($query, $i + 1);
}

echo '</tbody>';
echo '</table>';

// Free the query result
mssql_free_result($query);
?>

Zobacz też:

  • mssql_fetch_field() - Get field information

mssql_field_name
mssql_field_type
Funkcje Mssql


Gets the type of a field

mssql_field_seek
mssql_free_result
Funkcje Mssql
PHP Manual

mssql_field_type

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_type — Gets the type of a field

Opis

string mssql_field_type ( resource $result [, int $offset = -1 ] )

Returns the type of field no. offset in result.

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Zwracane wartości

The type of the specified field index on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 mssql_field_type() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT [name] FROM [php].[dbo].[persons]');

// Print the field type and length
echo '\'' . mssql_field_name($query, 0) . '\' is a type of ' .
     strtoupper(mssql_field_type($query, 0)) .
     '(' . mssql_field_length($query, 0) . ')';

// Free the query result
mssql_free_result($query);
?>

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

'name' is a type of CHAR(50)

Zobacz też:

  • mssql_field_length() - Get the length of a field
  • mssql_field_name() - Get the name of a field

mssql_field_seek
mssql_free_result
Funkcje Mssql


Free result memory

mssql_field_type
mssql_free_statement
Funkcje Mssql
PHP Manual

mssql_free_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_free_result — Free result memory

Opis

bool mssql_free_result ( resource $result )

mssql_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call mssql_free_result() with the result identifier as an argument and the associated result memory will be freed.

Parametry

result

The result resource that is being freed. This result comes from a call to mssql_query().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mssql_free_result() example

<?php
// Select some data from a table
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]', $link);

// Handle query result here

// When we're done we free the result by calling
// mssql_free_result like so:
mssql_free_result($query);
?>

Zobacz też:

  • mssql_free_statement() - Free statement memory

mssql_field_type
mssql_free_statement
Funkcje Mssql


Free statement memory

mssql_free_result
mssql_get_last_message
Funkcje Mssql
PHP Manual

mssql_free_statement

(PHP 4 >= 4.3.2, PHP 5, PECL odbtp >= 1.1.1)

mssql_free_statement — Free statement memory

Opis

bool mssql_free_statement ( resource $stmt )

mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with the statement identifier as an argument and the associated statement memory will be freed.

Parametry

stmt

Statement resource, obtained with mssql_init().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mssql_free_statement() example

<?php
// Create a new statement
$stmt = mssql_init('test');

// Bind values here and execute the statement

// once we're done, we clear it from the memory
// using mssql_free_statement like so:
mssql_free_statement($stmt);
?>

Zobacz też:

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_init() - Initializes a stored procedure or a remote stored procedure
  • mssql_free_result() - Free result memory

mssql_free_result
mssql_get_last_message
Funkcje Mssql


Zwraca ostatni komunikat z serwera

mssql_free_statement
mssql_guid_string
Funkcje Mssql
PHP Manual

mssql_get_last_message

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_get_last_message — Zwraca ostatni komunikat z serwera

Opis

string mssql_get_last_message ( void )

Pobiera ostatni komunikat z serwera MS-SQL

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca ostatnią informację o błędzie z serwera lub pusty łańcuch znaków, jeśli MSSQL nie zwrócił żadnego błędu.

Przykłady

Przykład #1 Przykład mssql_get_last_message()

<?php
// Połączenie do MSSQL i wybranie bazy danych
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Make a query that will fail
$query = @mssql_query('SELECT * FROM [php].[dbo].[not-found]');

if (!$query) {
    // The query has failed, print a nice error message
    // using mssql_get_last_message()
    die('MSSQL error: ' . mssql_get_last_message());
}
?>

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

MSSQL error: Invalid object name 'php.dbo.not-found'.

Zobacz też:

  • mssql_min_error_severity() - Ustawia poziom ważności zwracanych kodów błędów
  • mssql_min_message_severity() - Ustawia poziom ważności zwracanych komunikatów o błędach

mssql_free_statement
mssql_guid_string
Funkcje Mssql


Converts a 16 byte binary GUID to a string

mssql_get_last_message
mssql_init
Funkcje Mssql
PHP Manual

mssql_guid_string

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_guid_string — Converts a 16 byte binary GUID to a string

Opis

string mssql_guid_string ( string $binary [, bool $short_format = false ] )

Converts a 16 byte binary GUID to a string.

Parametry

binary

A 16 byte binary GUID.

short_format

Whenever to use short format.

Zwracane wartości

Returns the converted string on success.

Przykłady

Przykład #1 mssql_guid_string() example

<?php
$binary = '19555081977808608437941339997619274330352755554827939936';

var_dump(mssql_guid_string($binary));
var_dump(mssql_guid_string($binary, true));
?>

Powyższy przykład wyświetli:

string(36) "35353931-3035-3138-3937-373830383630"
string(32) "31393535353038313937373830383630"

mssql_get_last_message
mssql_init
Funkcje Mssql


Initializes a stored procedure or a remote stored procedure

mssql_guid_string
mssql_min_error_severity
Funkcje Mssql
PHP Manual

mssql_init

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_init — Initializes a stored procedure or a remote stored procedure

Opis

resource mssql_init ( string $sp_name [, resource $link_identifier ] )

Initializes a stored procedure or a remote stored procedure.

Parametry

sp_name

Stored procedure name, like ownew.sp_name or otherdb.owner.sp_name.

link_identifier

A MS SQL link identifier, returned by mssql_connect().

Zwracane wartości

Returns a resource identifier "statement", used in subsequent calls to mssql_bind() and mssql_execute(), or FALSE on errors.

Przykłady

Przykład #1 mssql_init() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Create a new statement
$stmt = mssql_init('StatementTest', $link);

// Bind values here

// Once values are binded we execute our statement
// using mssql_execute:
mssql_execute($stmt);

// And we can free it like so:
mssql_free_statement($stmt);
?>

Zobacz też:

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_free_statement() - Free statement memory

mssql_guid_string
mssql_min_error_severity
Funkcje Mssql


Ustawia poziom ważności zwracanych kodów błędów

mssql_init
mssql_min_message_severity
Funkcje Mssql
PHP Manual

mssql_min_error_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_error_severity — Ustawia poziom ważności zwracanych kodów błędów

Opis

void mssql_min_error_severity ( int $poziom ważności )

Ustawia poziom ważności zwracanych kodów błędów.

Parametry

poziom ważności

Nowy poziom ważności zwracanych kodów błędów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Przykład mssql_min_error_severity()

<?php
// Połączenie do MSSQL i wybór bazy danych
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Set the minimum error severity to not include SQL
// syntax errors by setting it to something greater than
// or equal to 1.
mssql_min_error_severity(1);

// Send a query we know that will cause an syntax error, in
// this case we use the MySQL quote signs instead of wrapping
// square brackets around the field and table names.
$query = mssql_query('SELECT `syntax`, `error` FROM `MSSQL`');

if (!$query) {
    // Custom error handler ...
}
?>

mssql_init
mssql_min_message_severity
Funkcje Mssql


Ustawia poziom ważności zwracanych komunikatów o błędach

mssql_min_error_severity
mssql_next_result
Funkcje Mssql
PHP Manual

mssql_min_message_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_message_severity — Ustawia poziom ważności zwracanych komunikatów o błędach

Opis

void mssql_min_message_severity ( int $poziom ważności )

Ustawia poziom ważności zwracanych komunikatów o błędach

Parametry

poziom ważności

Nowy poziom ważności zwracanych komunikatów o błędach.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Przykład mssql_min_message_severity()

<?php
// Połączenie do MSSQL
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Ustaw poziom ważności zwracanych komunikatów o błędach na 17.
// To nie wywoła żadnego komunikatu o błędzie, gdy przez API
// zostanie wybrana nieistniejąca baza danych
mssql_min_message_severity(17);

// Wybranie nieistniejącej bazy danych
mssql_select_db('THIS_DATABASE_DOES_NOT_EXISTS');
?>

Powyższy przykład wyświetli:

mssql_select_db(): Nie można wybrać bazy danych:  THIS_DATABASE_DOES_NOT_EXISTS

mssql_min_error_severity
mssql_next_result
Funkcje Mssql


Move the internal result pointer to the next result

mssql_min_message_severity
mssql_num_fields
Funkcje Mssql
PHP Manual

mssql_next_result

(PHP 4 >= 4.0.5, PHP 5, PECL odbtp >= 1.1.1)

mssql_next_result — Move the internal result pointer to the next result

Opis

bool mssql_next_result ( resource $result_id )

When sending more than one SQL statement to the server or executing a stored procedure with multiple results, it will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the rows from the new result set.

Parametry

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Zwracane wartości

Returns TRUE if an additional result set was available or FALSE otherwise.

Przykłady

Przykład #1 mssql_next_result() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Send a query to MSSQL
$sql = 'SELECT [name], [age] FROM [php].[dbo].[persons]';
$query = mssql_query($sql, $link);

// Iterate through returned records
do {
    while ($row = mssql_fetch_row($query)) {
        // Handle record ...
    }
} while (mssql_next_result($query));

// Clean up
mssql_free_result($query);
mssql_close($link);
?>

mssql_min_message_severity
mssql_num_fields
Funkcje Mssql


Zwraca liczbę pól w zbiorze wynikowym

mssql_next_result
mssql_num_rows
Funkcje Mssql
PHP Manual

mssql_num_fields

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_num_fields — Zwraca liczbę pól w zbiorze wynikowym

Opis

int mssql_num_fields ( resource $wynik )

mssql_num_fields() zwraca liczbę pól w zbiorze wynikowym.

Parametry

wynik

Obliczane są zasoby zbioru wynikowego. Zbiór wynikowy powstaje w następstwie wywołania mssql_query().

Zwracane wartości

Zwraca liczbę pól, jako integer.

Przykłady

Przykład #1 Przykład mssql_num_fields()

<?php
// Połączenie do MSSQL i wybór bazy danych
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Pobranie danych z bazy danych
$data = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Utworzenie tabeli HTML
echo '<table border="1">';

$header = false;

// Iteracja, dopóki zwracane są wiersze
while ($row = mssql_fetch_array($data)) {
    // Utworzenie nagłówka tabeli HTML
    if (!$header) {
        echo '<thead>';
        echo '<tr>';

        for ($i = 1; ($i + 1) <= mssql_num_fields($data); ++$i) {
            echo '<td>' . ucfirst($row[$i]) . '</td>';
        }

        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';

        $header = true;
    }

    // Utworzenie wiersza HTML
    echo '<tr>';

    foreach($row as $value) {
        echo '<td>' . $value . '</td>';
    }

    echo '</tr>';
}

// Zamknięcie tabeli HTML
echo '</tbody>';
echo '</table>';

// Zwolnienie pamięci zajmowanej przez wynik
mssql_free_result($data);
mssql_close($link);
?>

Zobacz też:

  • mssql_query() - Wysyła zapytanie do serwera MS SQL
  • mssql_fetch_field() - Get field information
  • mssql_num_rows() - Zwraca liczbę wierszy w zbiorze wynikowym

mssql_next_result
mssql_num_rows
Funkcje Mssql


Zwraca liczbę wierszy w zbiorze wynikowym

mssql_num_fields
mssql_pconnect
Funkcje Mssql
PHP Manual

mssql_num_rows

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_num_rows — Zwraca liczbę wierszy w zbiorze wynikowym

Opis

int mssql_num_rows ( resource $wynik )

mssql_num_rows() zwraca liczbę wierszy znajdujących się w zbiorze wynikowym.

Parametry

wynik

Obliczane są zasoby zbioru wynikowego. Zbiór wynikowy powstaje w następstwie wywołania mssql_query().

Zwracane wartości

Zwraca liczbę wierszy, jako integer.

Przykłady

Przykład #1 Przykład mssql_num_rows()

<?php
// Połączenie do MSSQL i wybór bazy danych
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Pobranie wszystkich wierszy z tabeli
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

echo 'Liczba wierszy w tabeli: ' . mssql_num_rows($query);

// Clean up
mssql_free_result($query);
?>

Zobacz też:

  • mssql_query() - Wysyła zapytanie do serwera MS SQL
  • mssql_fetch_row() - Get row as enumerated array

mssql_num_fields
mssql_pconnect
Funkcje Mssql


Open persistent MS SQL connection

mssql_num_rows
mssql_query
Funkcje Mssql
PHP Manual

mssql_pconnect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_pconnect — Open persistent MS SQL connection

Opis

resource mssql_pconnect ([ string $servername [, string $username [, string $password [, bool $new_link = false ]]]] )

mssql_pconnect() acts very much like mssql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mssql_close() will not close links established by mssql_pconnect()).

This type of links is therefore called 'persistent'.

Parametry

servername

The MS SQL server. It can also include a port number. e.g. hostname:port.

username

The username.

password

The password.

new_link

If a second call is made to mssql_pconnect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. This parameter modifies this behavior and makes mssql_pconnect() always open a new link, even if mssql_pconnect() was called before with the same parameters.

Zwracane wartości

Returns a positive MS SQL persistent link identifier on success, or FALSE on error.

Przykłady

Przykład #1 mssql_pconnect() using the new_link parameter

<?php
// Connect to MSSQL and select the database
$link1 = mssql_pconnect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link1);

// Create a new link
$link2 = mssql_pconnect('MANGO\SQLEXPRESS', 'sa', 'phpfi', true);
mssql_select_db('random', $link2);
?>

mssql_num_rows
mssql_query
Funkcje Mssql


Wysyła zapytanie do serwera MS SQL

mssql_pconnect
mssql_result
Funkcje Mssql
PHP Manual

mssql_query

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_query — Wysyła zapytanie do serwera MS SQL

Opis

mixed mssql_query ( string $zapytanie [, resource $identyfikator_połączenia [, int $ograniczenie_liczby_wyników ]] )

mssql_query() wysyła zapytanie do aktywnej bazy danych, na serwerze skojarzonym za pomocą identyfikatora połączenia.

Parametry

zapytanie

Zapytanie SQL.

identyfikator_połączenia

Identyfikator połączenia z MS SQL, zwrócony przez mssql_connect() lub mssql_pconnect().

Jeśli nie podano identyfikatora połączenia, przyjmowane jest ostatnio otwarte połączenie. Jeśli połączenie nie jest otwarte, funkcja próbuje nawiązać nowe i go użyć, tak jakby została wywołana mssql_connect().

ograniczenie_liczby_wyników

Maksymalna liczba rekordów, które mają zostać umieszczone w buforze wynikowym.

Zwracane wartości

Zwraca identyfikator zbioru wynikowego, TRUE jeśli nie zostały zwrócone wiersze lub FALSE kiedy wystąpił błąd.

Przykłady

Przykład #1 Przykład mssql_query()

<?php
// Połączenie do MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

if (!$link || !mssql_select_db('php', $link)) {
    die('Nie można nawiązać połączenia lub wybrać bazy danych!');
}

// Wykonaj proste zapytanie, pobierz wersję
// MSSQL i ją wyświetl.
$version = mssql_query('SELECT @@VERSION');
$row = mssql_fetch_array($version);

echo $row[0];

// Zwolnienie zasobów serwera zajmowanych przez zbiór wynikowy
mssql_free_result($version);
?>

Notatki

Informacja:

Jeśli zapytanie zwraca wiele wyników, wówczas konieczne jest pobranie ich wszystkich za pomocą mssql_next_result() lub też zwolnienie za pomocą mssql_free_result() przed wykonaniem następnego zapytania.

Zobacz też:

  • mssql_select_db() - Select MS SQL database
  • mssql_connect() - Otwiera połączenie z serwerem MS SQL

mssql_pconnect
mssql_result
Funkcje Mssql


Get result data

mssql_query
mssql_rows_affected
Funkcje Mssql
PHP Manual

mssql_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_result — Get result data

Opis

string mssql_result ( resource $result , int $row , mixed $field )

mssql_result() returns the contents of one cell from a MS SQL result set.

Parametry

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

row

The row number.

field

Can be the field's offset, the field's name or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), it uses the alias instead of the column name.

Informacja:

Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Zwracane wartości

Returns the contents of the specified cell.

Przykłady

Przykład #1 mssql_result() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    for ($i = 0; $i < mssql_num_rows($query); ++$i) {
        echo mssql_result($query, $i, 'username'), PHP_EOL;
    }
}

// Free the query result
mssql_free_result($query);
?>

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

Kalle
Felipe
Emil
Ross

Przykład #2 Faster alternative to above example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    while ($row = mssql_fetch_array($query)) {
        echo $row['username'], PHP_EOL;
    }
}

// Free the query result
mssql_free_result($query);
?>

Notatki

Informacja:

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mssql_result().

Zobacz też:

Recommended high-performance alternatives:

  • mssql_fetch_row() - Get row as enumerated array
  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_assoc() - Returns an associative array of the current row in the result
  • mssql_fetch_object() - Fetch row as object

mssql_query
mssql_rows_affected
Funkcje Mssql


Zwraca liczbę rekordów przetworzonych przez ostatnie zapytanie

mssql_result
mssql_select_db
Funkcje Mssql
PHP Manual

mssql_rows_affected

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

mssql_rows_affected — Zwraca liczbę rekordów przetworzonych przez ostatnie zapytanie

Opis

int mssql_rows_affected ( resource $identyfikator_połączenia )

Zwraca liczbę rekordów przetworzonych przez ostatnie zapytanie do obróbki danych.

Parametry

identyfikator_połączenia

Identyfikator połączenia z serwerem MS SQL, zwracany przez mssql_connect() lub mssql_pconnect().

Zwracane wartości

Zwraca liczbę rekordów przetworzonych podczas ostatniej operacji.

Przykłady

Przykład #1 Przykład mssql_rows_affected()

<?php
// Usuń wszystkie rekordy z tabeli
mssql_query('TRUNCATE TABLE [php].[dbo].[persons]');

echo 'Usunięto ' . mssql_rows_affected($link) . ' rekordów';
?>

mssql_result
mssql_select_db
Funkcje Mssql


Select MS SQL database

mssql_rows_affected
MySQL
Funkcje Mssql
PHP Manual

mssql_select_db

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_select_db — Select MS SQL database

Opis

bool mssql_select_db ( string $database_name [, resource $link_identifier ] )

mssql_select_db() sets the current active database on the server that's associated with the specified link identifier.

Every subsequent call to mssql_query() will be made on the active database.

Parametry

database_name

The database name.

To escape the name of a database that contains spaces, hyphens ("-"), or any other exceptional characters, the database name must be enclosed in brackets, as is shown in the example, below. This technique must also be applied when selecting a database name that is also a reserved word (such as primary).

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mssql_connect() was called, and use it.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mssql_select_db() example

<?php
// Create a link to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Select the database 'php'
mssql_select_db('php', $link);
?>

Przykład #2 Escaping the database name with square brackets

<?php
// Create a link to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Select the database 'my.database-name'
mssql_select_db('[my.database-name]', $link);
?>

Zobacz też:

  • mssql_connect() - Otwiera połączenie z serwerem MS SQL
  • mssql_pconnect() - Open persistent MS SQL connection
  • mssql_query() - Wysyła zapytanie do serwera MS SQL

mssql_rows_affected
MySQL
Funkcje Mssql


MySQL Drivers and Plugins

PHP offers several MySQL drivers and plugins for accessing and handling MySQL.

The differences and functionality of the MySQL extensions are described within the overview of this section.

  • Overview of the MySQL PHP drivers
    • Terminology overview
    • Choosing an API
    • Choosing a library
  • Mysql — Oryginalne API MySQL
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • MySQL Funkcje
  • Mysqli — MySQL Improved Extension
    • Wstęp
    • Overview
    • Quickstart
    • Instalacja/Konfiguracja
    • The mysqli Extension and Persistent Connections
    • Stałe predefiniowane
    • Notes
    • The MySQLi Extension Function Summary
    • mysqli — The mysqli class
    • mysqli_stmt — The mysqli_stmt class
    • mysqli_result — The mysqli_result class
    • mysqli_driver — The mysqli_driver class
    • mysqli_warning — The mysqli_warning class
    • Aliases and deprecated Mysqli Funkcje
  • Mysqlnd — MySQL Native Driver
    • Wstęp
    • Overview
    • Installation
    • Konfiguracja wykonawcza
    • Persistent Connections
    • Statistics
    • Notes
    • MySQL Native Driver Plugin API
  • mysqlnd_ms — Mysqlnd replication and load balancing plugin
    • Wstęp
    • Quickstart and Examples
    • Concepts
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Mysqlnd_ms Funkcje
    • Change History
  • mysqlnd_qc — Mysqlnd query result cache plugin
    • Wstęp
    • Quickstart and Examples
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • mysqlnd_qc Funkcje
    • Change History
  • mysqlnd_uh — Mysqlnd user handler plugin
    • Wstęp
    • Quickstart and Examples
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • MysqlndUhConnection — The MysqlndUhConnection class
    • MysqlndUhPreparedStatement — The MysqlndUhPreparedStatement class
    • Mysqlnd_uh Funkcje
    • Change History
mssql_select_db
Overview of the MySQL PHP drivers
Rozszerzenia producentów baz danych


Overview of the MySQL PHP drivers

  • Terminology overview
  • Choosing an API
  • Choosing a library
MySQL
Terminology overview
MySQL


Terminology overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two the latter is usually the preferred interface, as it is more modern and leads to better organized code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term "driver" is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the mysqli extension, and the mysql extension, are implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

Overview of the MySQL PHP drivers
Choosing an API
Overview of the MySQL PHP drivers


Choosing an API

PHP offers three different APIs to connect to MySQL. Below we show the APIs provided by the mysql, mysqli, and PDO extensions. Each code snippet creates a connection to a MySQL server running on "example.com" using the username "user" and the password "password". And a query is run to greet the user.

Przykład #1 Comparing the three MySQL APIs

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['_message']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['_message']);
?>

Recommended API

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

Feature comparison

 | ext/mysqli | PDO_MySQL | ext/mysql
PHP version introduced | 5.0 | 5.1 | 2.0
Included with PHP 5.x | Yes | Yes | Yes
Development status | Active | Active | Maintenance only
Lifecycle | Active | Active | Long term deprecation announced
Recommended for new projects | Yes | Yes | No
OOP Interface | Yes | Yes | No
Procedural Interface | Yes | No | Yes
API supports non-blocking, asynchronous queries with mysqlnd | Yes | No | No
Persistent Connections | Yes | Yes | Yes
API supports Charsets | Yes | Yes | Yes
API supports server-side Prepared Statements | Yes | Yes | No
API supports client-side Prepared Statements | No | Yes | No
API supports Stored Procedures | Yes | Yes | No
API supports Multiple Statements | Yes | Most | No
API supports Transactions | Yes | Yes | No
Transactions can be controlled with SQL | Yes | Yes | Yes
API supports Transactions | Yes | Yes | No
Supports all MySQL 5.1+ functionality | Yes | Most | No
Terminology overview
Choosing a library
Overview of the MySQL PHP drivers


Choosing a library

The mysqli, PDO_MySQL and mysql PHP extensions are lightweight wrappers on top of a C client library. The extensions can either use the mysqlnd library or the libmysql library. Choosing a library is a compile time decision.

The mysqlnd library is part of the PHP distribution since 5.3.0. It offers features like lazy connections and query caching, features that are not available with libmysql, so using the built-in mysqlnd library is highly recommended. See the mysqlnd documentation for additional details, and a listing of features and functionality that it offers.

Przykład #1 Configure commands for using mysqlnd or libmysql

// Recommended, compiles with mysqlnd
$ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-mysql=mysqlnd

// Not recommended, compiles with libmysql
$ ./configure --with-mysqli=/path/to/mysql_config --with-pdo-mysql=/path/to/mysql_config --with-mysql=/path/to/mysql_config

Library feature comparison

It is recommended to use the mysqlnd library instead of the MySQL Client Server library (libmysql). Both libraries are supported and constantly being improved.

 | MySQL native driver (mysqlnd) | MySQL client server library (libmysql)
Part of the PHP distribution | Yes | No
PHP version introduced | 5.3.0 | N/A
License | PHP License 3.01 | Dual-License
Development status | Active | Active
Lifecycle | No end announced | No end announced
PHP 5.4 compile default (for all MySQL extensions) | Yes | No
PHP 5.3 compile default (for all MySQL extensions) | No | Yes
Compression protocol support | Yes (5.3.1+) | yes
SSL support | Yes (5.3.3+) | Yes
Named pipe support | Yes (5.3.4+) | Yes
Non-blocking, asynchronous queries | Yes | No
Performance statistics | Yes | No
LOAD LOCAL INFILE respects the open_basedir directive | Yes | No
PHP memory limits followed | Yes | No
Return numeric column as double (COM_QUERY) | Yes | No
Return numeric column as string (COM_QUERY) | Yes | Yes
Plugin API | Yes | Limited
Read/Write splitting for MySQL Replication | Yes, with plugin | No
Load Balancing | Yes, with plugin | No
Fail over | Yes, with plugin | No
Lazy connections | Yes, with plugin | No
Query caching | Yes, with plugin | No
Transparent query manipulations (E.g., auto-EXPLAIN or monitoring) | Yes, with plugin | No
Choosing an API
Mysql
Overview of the MySQL PHP drivers


Oryginalne API MySQL

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • MySQL extension overview example
  • MySQL Funkcje
    • mysql_affected_rows — Zwraca liczbę wierszy przetworzonych w poprzedniej operacji MySQL
    • mysql_client_encoding — Zwraca nazwę zestawu znaków
    • mysql_close — Zamyka połączenie MySQL
    • mysql_connect — Otwiera połączenie do serwera MySQL
    • mysql_create_db — Tworzy bazę MySQL
    • mysql_data_seek — Przesuwa wewnętrzny wskaźnik wyniku
    • mysql_db_name — Pobiera dane wynikowe
    • mysql_db_query — Wybiera bazę danych MySQL i wykonuje na niej zapytanie
    • mysql_drop_db — Usuwa bazę MySQL
    • mysql_errno — Zwraca liczbową wartość kodu błędu z poprzedniej operacji MySQL
    • mysql_error — Zwraca tekst komunikatu błędu z ostatniej operacji MySQL
    • mysql_escape_string — Dodaje znaki unikowe na użytek mysql_query
    • mysql_fetch_array — Zapisuje wiersz wyniku w tablicy asocjacyjnej, numerycznej lub w obu
    • mysql_fetch_assoc — Zapisuje wiersz wyniku w tablicy asocjacyjnej
    • mysql_fetch_field — Pobiera z wyniku informacje o kolumnie i zwraca jako obiekt
    • mysql_fetch_lengths — Pobiera długość każdego pola w wierszu wyniku
    • mysql_fetch_object — Zapisuje wiersz wyniku jako obiekt
    • mysql_fetch_row — Zapisuje wiersz wyniku w tablicy wyliczeniowej
    • mysql_field_flags — Pobiera flagi dla danego pola w wyniku
    • mysql_field_len — Zwraca długość danego pola
    • mysql_field_name — Podaje nazwę danego pola w wyniku
    • mysql_field_seek — Przesuwa wskaźnik wyniku do wybranego pola
    • mysql_field_table — Pobiera nazwę tabeli w której znajduje się dane pole
    • mysql_field_type — Pobiera typ podanego pola
    • mysql_free_result — Zwalnia pamięć zajmowaną przez wynik
    • mysql_get_client_info — Pobiera informacje o kliencie MySQL
    • mysql_get_host_info — Pobiera informacje o hoście MySQL
    • mysql_get_proto_info — Pobiera informacje o protokole MySQL
    • mysql_get_server_info — Pobiera informacje o serwerze MySQL
    • mysql_info — Pobiera informacje o ostatnim zapytaniu
    • mysql_insert_id — Podaje numer ID wygenerowany podczas ostatniej operacji INSERT
    • mysql_list_dbs — Pobiera nazwy baz dostępnych na serwerze MySQL
    • mysql_list_fields — Pobiera informacje o polach tabeli MySQL
    • mysql_list_processes — Zwraca listę procesów MySQL
    • mysql_list_tables — Pobiera listę tabel z bazy MySQL
    • mysql_num_fields — Zwraca liczbę pól w wyniku
    • mysql_num_rows — Zwraca liczbę wierszy w wyniku
    • mysql_pconnect — Otwiera stałe połączenie z serwerem MySQL
    • mysql_ping — Sprawdza połączenie z serwerem, lub nawiązuje połączenie, jeśli go nie było
    • mysql_query — Wysyła zapytanie do serwera MySQL
    • mysql_real_escape_string — Dodaje znaki unikowe w łańcuchu znaków do użycia w instrukcji SQL
    • mysql_result — Zwraca dane wynikowe
    • mysql_select_db — Wybiera bazę MySQL
    • mysql_set_charset — Sets the client character set
    • mysql_stat — Pobiera aktualny stan systemu
    • mysql_tablename — Zwraca nazwę tabeli
    • mysql_thread_id — Zwraca id bieżącego wątku
    • mysql_unbuffered_query — Wysyła zapytanie do serwera MySQL nie pobierając i nie buforując wyniku
Choosing a library
Wstęp
MySQL


Wstęp

Te funkcje pozwalają na dostęp do serwerów baz danych MySQL. Wiecej informacji o MySQL znajduje się pod adresem » http://www.mysql.com/.

Dokumentacja MySQL znajduje się pod adresem » http://dev.mysql.com/doc/.

Przegląd warunków połączenia do bazy danych MySQL i produktów znajduje się na stronie Overview.

Mysql
Instalacja/Konfiguracja
Mysql


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Mysql


Wymagania

Aby te funkcje były dostępne należy skompilować PHP z obsługą MySQL.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

For compiling, simply use the --with-mysql[=DIR] configuration option where the optional [DIR] points to the MySQL installation directory.

Although this MySQL extension is compatible with MySQL 4.1.0 and greater, it doesn't support the extra functionality that these versions provide. For that, use the MySQLi extension.

If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.

Installation on Linux Systems

Note: [DIR] is the path to the MySQL client library files (headers and libraries), which can be downloaded from » MySQL.

ext/mysql compile time support matrix
PHP Wersja | Domyślnie | Opcje konfiguracyjne: mysqlnd | Opcje konfiguracyjne: libmysql | Rejestr zmian
4.x.x | libmysql | Niedostępne | --without-mysql to disable | MySQL enabled by default, MySQL client libraries are bundled
5.0.x, 5.1.x, 5.2.x | libmysql | Niedostępne | --with-mysql=[DIR] | MySQL is no longer enabled by default, and the MySQL client libraries are no longer bundled
5.3.x | libmysql | --with-mysql=mysqlnd | --with-mysql=[DIR] | mysqlnd is now available
5.4.x | mysqlnd | --with-mysql | --with-mysql=[DIR] | mysqlnd is now the default

Installation on Windows Systems

PHP 4

The PHP MySQL extension is compiled into PHP.

PHP 5.0.x, 5.1.x, 5.2.x

MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying libmysql.dll to the Windows system directory also works (because the system directory is by default in the system's PATH), it's not recommended.

As with enabling any PHP extension (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example extension_dir value for PHP 5 is c:\php\ext

Informacja:

If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysql.dll'", this is because php_mysql.dll and/or libmysql.dll cannot be found by the system.

PHP 5.3.0+

The MySQL Native Driver is enabled by default. Include php_mysql.dll, but libmysql.dll is no longer required or used.

MySQL Installation Notes

Ostrzeżenie

Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode extension. See the recode extension for more information.

Informacja:

If you need charsets other than latin (default), you have to install external (not bundled) libmysql with compiled charset support.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

MySQL Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mysql.allow_local_infile | "1" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Available since PHP 4.0.1.
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.3.2. Available since PHP 4.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.

mysql.allow_local_infile integer

Allow accessing, from PHP's perspective, local files with LOAD DATA statements

mysql.allow_persistent boolean

Whether to allow persistent connections to MySQL.

mysql.max_persistent integer

The maximum number of persistent MySQL connections per process.

mysql.max_links integer

The maximum number of MySQL connections per process, including persistent connections.

mysql.trace_mode boolean

Trace mode. When mysql.trace_mode is enabled, warnings for table/index scans, non free result sets, and SQL-Errors will be displayed. (Introduced in PHP 4.3.0)

mysql.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.

mysql.default_socket string

The default socket name to use when connecting to a local database server if no other socket name is specified.

mysql.default_host string

The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in tryb bezpieczny SQL.

mysql.default_user string

The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in tryb bezpieczny SQL.

mysql.default_password string

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in tryb bezpieczny SQL.

mysql.connect_timeout integer

Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer from the server.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

Istnieją dwa typy zasobów używane w module MySQL. Pierwszy z nich to identyfikator połączenia do bazy danych. Drugi zasób przechowuje wynik zapytania.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

Since PHP 4.3.0 it is possible to specify additional client flags for the mysql_connect() and mysql_pconnect() functions. The following constants are defined:

MySQL client constants
Constant | Description
MYSQL_CLIENT_COMPRESS | Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE | Allow space after function names
MYSQL_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout ) of inactivity before closing the connection.
MYSQL_CLIENT_SSL | Use SSL encryption. This flag is only available with version 4.x of the MySQL client library or newer. Version 3.23.x is bundled both with PHP 4 and Windows binaries of PHP 5.

The function mysql_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:

MySQL fetch constants
Constant | Description
MYSQL_ASSOC | Columns are returned into the array having the fieldname as the array index.
MYSQL_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index.
MYSQL_NUM | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

Typy zasobów
Przykłady
Mysql


Przykłady

Spis treści

  • MySQL extension overview example
Stałe predefiniowane
MySQL extension overview example
Mysql


MySQL extension overview example

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database.

Przykład #1 MySQL extension overview example

<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');

// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?>

Przykłady
MySQL Funkcje
Przykłady


MySQL Funkcje

Notatki

Informacja:

Most MySQL functions accept link_identifier as the last optional parameter. If it is not provided, last opened connection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not successful, functions return FALSE.

Spis treści

  • mysql_affected_rows — Zwraca liczbę wierszy przetworzonych w poprzedniej operacji MySQL
  • mysql_client_encoding — Zwraca nazwę zestawu znaków
  • mysql_close — Zamyka połączenie MySQL
  • mysql_connect — Otwiera połączenie do serwera MySQL
  • mysql_create_db — Tworzy bazę MySQL
  • mysql_data_seek — Przesuwa wewnętrzny wskaźnik wyniku
  • mysql_db_name — Pobiera dane wynikowe
  • mysql_db_query — Wybiera bazę danych MySQL i wykonuje na niej zapytanie
  • mysql_drop_db — Usuwa bazę MySQL
  • mysql_errno — Zwraca liczbową wartość kodu błędu z poprzedniej operacji MySQL
  • mysql_error — Zwraca tekst komunikatu błędu z ostatniej operacji MySQL
  • mysql_escape_string — Dodaje znaki unikowe na użytek mysql_query
  • mysql_fetch_array — Zapisuje wiersz wyniku w tablicy asocjacyjnej, numerycznej lub w obu
  • mysql_fetch_assoc — Zapisuje wiersz wyniku w tablicy asocjacyjnej
  • mysql_fetch_field — Pobiera z wyniku informacje o kolumnie i zwraca jako obiekt
  • mysql_fetch_lengths — Pobiera długość każdego pola w wierszu wyniku
  • mysql_fetch_object — Zapisuje wiersz wyniku jako obiekt
  • mysql_fetch_row — Zapisuje wiersz wyniku w tablicy wyliczeniowej
  • mysql_field_flags — Pobiera flagi dla danego pola w wyniku
  • mysql_field_len — Zwraca długość danego pola
  • mysql_field_name — Podaje nazwę danego pola w wyniku
  • mysql_field_seek — Przesuwa wskaźnik wyniku do wybranego pola
  • mysql_field_table — Pobiera nazwę tabeli w której znajduje się dane pole
  • mysql_field_type — Pobiera typ podanego pola
  • mysql_free_result — Zwalnia pamięć zajmowaną przez wynik
  • mysql_get_client_info — Pobiera informacje o kliencie MySQL
  • mysql_get_host_info — Pobiera informacje o hoście MySQL
  • mysql_get_proto_info — Pobiera informacje o protokole MySQL
  • mysql_get_server_info — Pobiera informacje o serwerze MySQL
  • mysql_info — Pobiera informacje o ostatnim zapytaniu
  • mysql_insert_id — Podaje numer ID wygenerowany podczas ostatniej operacji INSERT
  • mysql_list_dbs — Pobiera nazwy baz dostępnych na serwerze MySQL
  • mysql_list_fields — Pobiera informacje o polach tabeli MySQL
  • mysql_list_processes — Zwraca listę procesów MySQL
  • mysql_list_tables — Pobiera listę tabel z bazy MySQL
  • mysql_num_fields — Zwraca liczbę pól w wyniku
  • mysql_num_rows — Zwraca liczbę wierszy w wyniku
  • mysql_pconnect — Otwiera stałe połączenie z serwerem MySQL
  • mysql_ping — Sprawdza połączenie z serwerem, lub nawiązuje połączenie, jeśli go nie było
  • mysql_query — Wysyła zapytanie do serwera MySQL
  • mysql_real_escape_string — Dodaje znaki unikowe w łańcuchu znaków do użycia w instrukcji SQL
  • mysql_result — Zwraca dane wynikowe
  • mysql_select_db — Wybiera bazę MySQL
  • mysql_set_charset — Sets the client character set
  • mysql_stat — Pobiera aktualny stan systemu
  • mysql_tablename — Zwraca nazwę tabeli
  • mysql_thread_id — Zwraca id bieżącego wątku
  • mysql_unbuffered_query — Wysyła zapytanie do serwera MySQL nie pobierając i nie buforując wyniku
MySQL extension overview example
mysql_affected_rows
Mysql


Zwraca liczbę wierszy przetworzonych w poprzedniej operacji MySQL

MySQL Funkcje
mysql_client_encoding
MySQL Funkcje
PHP Manual

mysql_affected_rows

(PHP 4, PHP 5)

mysql_affected_rows — Zwraca liczbę wierszy przetworzonych w poprzedniej operacji MySQL

Opis

int mysql_affected_rows ([ resource $identyfikator_połączenia ] )

Pobiera liczbę wierszy przetworzonych w ostatnim zapytaniu INSERT, UPDATE, REPLACE lub DELETE skojarzonym z identyfikator_połączenia.

Parametry

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca liczbę przetworzonych wierszy w przypadku sukcesu i -1 jeśli ostatnie zapytanie zawiedzie.

Jeżeli ostatnim zapytaniem było DELETE bez użycia klauzuli WHERE, wszystkie rekordy zostaną usunięte z tabeli, ale funkcja zwróci zero w wersjach MySQL starszych niż 4.1.2.

Podczas operacji UPDATE, MySQL nie aktualizuje kolumn w których nowa wartość jest identyczna z poprzednią. Możliwe jest zatem, że zwrócona przez mysql_affected_rows() liczba nie będzie odpowiadać liczbie wierszy pasujących do zapytania, ale tych, które zostały faktycznie zmienione.

Wyrażenie REPLACE najpierw skasuje rekord z tym samym kluczem głównym następnie wstawi nowy rekord. Ta funkcja zwraca liczbę skasowanych rekordów plus liczbę wstawionych rekordów.

Przykłady

Przykład #1 Przykład mysql_affected_rows()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Nie można się połączyć: ' . mysql_error());
}
mysql_select_db('mydb');

/* to powinno zwrócić prawidłową liczbę usuniętych rekordów */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Usuniętych rekordów: %d\n", mysql_affected_rows());

/* z klauzulą where, która nigdy nie jest prawdziwa, powinno zrwócic 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Usuniętych rekordów: %d\n", mysql_affected_rows());
?>

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

Usuniętych rekordów: 10
Usuniętych rekordów: 0

Przykład #2 Przykład mysql_affected_rows() używający transakcję

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Nie można się połączyć: ' . mysql_error());
}
mysql_select_db('mydb');

/* Uaktualnienie rekordów */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Zaktualizowanych rekordów: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

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

Zaktualizowanych rekordów: 10

Notatki

Informacja: Transakcje

Jeśli używasz transakcji musisz wywołać mysql_affected_rows() po Twoim zapytaniu INSERT, UPDATE lub DELETE, a nie po COMMIT.

Informacja: Instrukcja SELECT

Aby uzyskać liczbę wierszy zwróconych przez SELECT, można użyć use mysql_num_rows().

Informacja: Kaskadowe klucze obce

mysql_affected_rows() nie zwraca liczby wierszy przetworzonych pośrednio przez użycie klauzuli ON DELETE CASCADE i/lub ON UPDATE CASCADE w ograniczeniach kluczy obcych.

Zobacz też:

  • mysql_num_rows() - Zwraca liczbę wierszy w wyniku
  • mysql_info() - Pobiera informacje o ostatnim zapytaniu

MySQL Funkcje
mysql_client_encoding
MySQL Funkcje


Zwraca nazwę zestawu znaków

mysql_affected_rows
mysql_close
MySQL Funkcje
PHP Manual

mysql_client_encoding

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding — Zwraca nazwę zestawu znaków

Opis

string mysql_client_encoding ([ resource $identyfikator_połączenia ] )

Zwraca zmienną character_set z serwera MySQL.

Parametry

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca domyślny zestaw znaków dla bieżącego połączenia.

Przykłady

Przykład #1 Przykład użycia mysql_client_encoding()

<?php
$link    = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);

echo "Obecny zestaw znaków to : $charset\n";
?>

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

Obecny zestaw znaków to: latin2

Zobacz też:

  • mysql_real_escape_string() - Dodaje znaki unikowe w łańcuchu znaków do użycia w instrukcji SQL

mysql_affected_rows
mysql_close
MySQL Funkcje


Zamyka połączenie MySQL

mysql_client_encoding
mysql_connect
MySQL Funkcje
PHP Manual

mysql_close

(PHP 4, PHP 5)

mysql_close — Zamyka połączenie MySQL

Opis

bool mysql_close ([ resource $identyfikator_połączenia ] )

mysql_close() zamyka nie stałe połączenie do serwera MySQL, które zostało skojarzone z podanym identyfikatorem połączenia. Jeśli identyfikator_połączenia nie został określony, zostanie użyte ostatnio używane połączenie.

Używanie mysql_close() nie jest zwykle konieczne, ponieważ nie stałe linki są automatycznie zamykane na końcu wykonywania skryptu. Patrz także zwalnianie zasobów.

Parametry

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no connection is found or established, an E_WARNING level error is generated.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład mysql_close()

<?php
$link = mysql_connect('localhost', 'użytkownik_mysql', 'hasło_mysql');
if (!$link) {
    die('Nie można się połączyć: ' . mysql_error());
}
echo 'Połączono poprawnie';
mysql_close($link);
?>

Powyższy przykład wyświetli:

Połączono poprawnie

Notatki

Informacja:

mysql_close() nie zamknie stałych połączeń stworzonych przez mysql_pconnect().

Zobacz też:

  • mysql_connect() - Otwiera połączenie do serwera MySQL
  • mysql_free_result() - Zwalnia pamięć zajmowaną przez wynik

mysql_client_encoding
mysql_connect
MySQL Funkcje


Otwiera połączenie do serwera MySQL

mysql_close
mysql_create_db
MySQL Funkcje
PHP Manual

mysql_connect

(PHP 4, PHP 5)

mysql_connect — Otwiera połączenie do serwera MySQL

Opis

resource mysql_connect ([ string $serwer = ini_get("mysql.default_host") [, string $nazwa_użytkownika = ini_get("mysql.default_user") [, string $hasło = ini_get("mysql.default_password") [, bool $nowe_połączenie = false [, int $flagi_klienta = 0 ]]]]] )

Otwiera lub ponownie używa połączenie do serwera MySQL.

Parametry

serwer

Serwer MySQL. Może także zawierać numer portu np. "nazwa_serwera:port" lub ścieżkę do lokalnego gniazda np. ":/ścieżka/do/gniazda" dla lokalnego hosta.

Jeśli, dyrektywa PHP mysql.default_host jest nie zdefiniowana (domyślnie), wtedy domyślną wartością jest 'localhost:3306'. W tryb bezpieczny SQL, ten parametr jest ignorowany i zawsze jest używana wartość 'localhost:3306'.

nazwa_użytkownika

Nazwa użytkownika. Domyślna watość jest definiowana przez mysql.default_user. W tryb bezpieczny SQL, parametr ten jest ignorowany i używana jest nazwa użytkownika, który jest właścicielem procesu serwera.

hasło

Hasło. Domyślna wartość jest zdefiniowana przez mysql.default_password. W tryb bezpieczny SQL, ten parametr jest ignorowany i użyte jest puste hasło.

nowe_połączenie

Jeśli, ponownie wywołamy mysql_connect() z tymi samymi argumentami, nie zostanie nawiązane nowe połączenie, lecz zamiast tego, zostanie zwrócony identyfikator obecnie otwartego połączenia. Parametr nowe_połączenie modyfikuje to zachowanie i sprawia, że mysql_connect() zawsze otwiera nowe połączenie, nawet jeśli mysql_connect() zostało wywołane wcześniej z tymi samymi parametrami. W tryb bezpieczny SQL, ten parametr jest ignorowany.

flagi_klienta

Parametr flagi_klienta może być kombinacją następujących stałych: 128 (włącza obsługę LOAD DATA LOCAL), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE lub MYSQL_CLIENT_INTERACTIVE. Przeczytaj sekcję o MySQL client constants w celu dalszych informacji. W tryb bezpieczny SQL, ten parametr jest ignorowany.

Zwracane wartości

Zwraca identyfikator połączenia MySQL w przypadku sukcesu, lub FALSE w przypadku niepowodzenia

Rejestr zmian

Wersja | Opis
4.3.0 | Dodano parametr flagi_klienta.
4.2.0 | Dodano parametr nowe_połączenie.

Przykłady

Przykład #1 Przykład mysql_connect()

<?php
$link = mysql_connect('localhost', 'użytkownik_mysql', 'hasło_mysql');
if (!$link) {
    die('Nie można się połaczyć: ' . mysql_error());
}
echo 'Połączenie nawiązane';
mysql_close($link);
?>

Przykład #2 Przykład mysql_connect() z użyciem składni nazwa_hosta:port

<?php
// połączymy się do example.com i portu 3307
$link = mysql_connect('example.com:3307', 'użytkownik_mysql', 'hasło_mysql');
if (!$link) {
    die('Nie można się połączyć: ' . mysql_error());
}
echo 'Połączenie nawiązane';
mysql_close($link);

// połączymy się do localhost na port 3307
$link = mysql_connect('127.0.0.1:3307', 'użytkownik_mysql', 'hasło_mysql');
if (!$link) {
    die('Nie można się połączyć: ' . mysql_error());
}
echo 'Połączenie nawiązane';
mysql_close($link);
?>

Przykład #3 mysql_connect() przykład użycia składni ":/ścieżka/do/gniazda"

<?php
// połączymy się do lokalhost i gniazda np. /tmp/mysql.sock

//wariant 1: z pominięciem localhost
$link = mysql_connect(':/tmp/mysql', 'użytkownik_mysql', 'hasło_mysql');
if (!$link) {
    die('Nie można się połączyć: ' . mysql_error());
}
echo 'Połączenie nawiązane';
mysql_close($link);

// wariant 2: z localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'użytkownik_mysql', 'hasło_mysql');
if (!$link) {
    die('Nie można się połączyć: ' . mysql_error());
}
echo 'Połączenie nawiązane';
mysql_close($link);
?>

Notatki

Informacja:

Ilekroć określasz serwer jako "localhost" lub "localhost:port", biblioteka kliencka MySQL nadpisze to i spróbuje połączyć się do lokalnego gniazda (nazwanego potokiem w Windows). Jeśli chcesz użyć TCP/IP, użyj "127.0.0.1" zamiast "localhost". Jeśli biblioteka kliencka MySQL próbuje połączyć się do niewłaściwego lokalnego gniazda, powinieneś ustawić prawidłową ścieżkę jako w Twojej konfiguracji PHP i zostawić puste pole serwer.

Informacja:

Połączenie do serwera zostanie zamknięte jak tylko wykonywanie skryptu zakończy się, chyba, że zostanie wcześniej zamknięte poprzez wyraźne wywołanie mysql_close().

Informacja:

Możesz zapobiec informacją o błędach w przypadku niepowodzenia za pomocą poprzedzenia nazwy funkcji @.

Informacja:

Błąd "Can't create TCP/IP socket (10106)" zwykle oznacza, że dyrektywa konfiguracyjna variables_order nie zawiera znaku E. Pod Windows, jeśli środowisko nie jest skopiowane zmienna środowiskowa SYSTEMROOT nie będzie dostępna i PHP będzie mieć problemy aby załadować Winsock.

Zobacz też:

  • mysql_pconnect() - Otwiera stałe połączenie z serwerem MySQL
  • mysql_close() - Zamyka połączenie MySQL

mysql_close
mysql_create_db
MySQL Funkcje


Tworzy bazę MySQL

mysql_connect
mysql_data_seek
MySQL Funkcje
PHP Manual

mysql_create_db

(PHP 4, PHP 5)

mysql_create_db — Tworzy bazę MySQL

Opis

bool mysql_create_db ( string $nazwa_bazy [, resource $identyfikator_połączenia ] )

mysql_create_db()tworzy nową bazę na serwerze skojarzonym z podanym identyfikatorem połączenia.

Parametry

nazwa_bazy

Nazwa tworzonej bazy danych.

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mysql_create_db() przykład alternatywny

Stosowanie funkcji mysql_create_db() jest nie zalecane. Sugerowane jest wydawanie polecenia CREATE DATABASE przy użyciu funkcji mysql_query().

<?php
$link = mysql_connect('localhost', 'uzytkownik', 'haslo');
if (!$link) {
    die('Nie można się połączyć: ' . mysql_error());
}

$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Baza my_db została pomyślnie utworzona\n";
} else {
    echo 'Błąd podczas tworzenia bazy: ' . mysql_error() . "\n";
}
?>

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

Baza my_db została pomyślnie utworzona

Notatki

Informacja:

Dla zachowania zgodności z poprzednimi wersjami PHP możliwe jest używanie aliasów: mysql_createdb()

Informacja:

Funkcja ta nie będzie dostępna jeśli rozszerzenie MySQL zostało skompilowane z wersją 4.x biblioteki klienta MySQL.

Zobacz też:

  • mysql_query() - Wysyła zapytanie do serwera MySQL
  • mysql_select_db() - Wybiera bazę MySQL

mysql_connect
mysql_data_seek
MySQL Funkcje


Przesuwa wewnętrzny wskaźnik wyniku

mysql_create_db
mysql_db_name
MySQL Funkcje
PHP Manual

mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seek — Przesuwa wewnętrzny wskaźnik wyniku

Opis

bool mysql_data_seek ( resource $wynik , int $numer_wiersza )

mysql_data_seek() przesuwa wewnętrzny wskaźnik wiersza wyniku operacji MySQL skojarzony z podanym identyfikatorem wyniku na podany numer wiersza. Następne wywołanie MySQLowej funkcji pobierającej, takiej jak mysql_fetch_assoc() zwróci ten wiersz.

row_number zaczyna się od 0. Parametr row_number powinien być wartością z zakresu od 0 do mysql_num_rows() - 1. Jednakże jeśli zbiór wyników jest pusty (mysql_num_rows() == 0), przesunięcie na pozycję 0 zawiedzie i wygeneruje ostrzeżenie E_WARNING, mysql_data_seek() zwróci FALSE.

Parametry

wynik

Wynik w postaci zmiennej typu resource, które jest przetwarzane. Wynik ten pochodzi z wywołania funkcji mysql_query().

row_number

Pożądany numer wiersza dla nowego wskaźnika wyniku.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład mysql_data_seek()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
  die('Nie można się połączyć: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
  die('Nie można wybrać bazy: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!$result) {
  die('Błędne zapytanie: ' . mysql_error());
}

/* pobieramy wiersze w odwrotnej kolejności */
for ($i = mysql_num_rows($result) - 1; $i >=0; $i--) {
    if (!mysql_data_seek($result, $i)) {
        echo "Nie można przejść do wiersza $i: " . mysql_error() . "\n";
        continue;
    }

    if (!($row = mysql_fetch_assoc($result))) {
       continue;
    }
    echo $row['last_name'] . ' ' . $row['first_name'] . "<br />\n";
}

mysql_free_result($result);
?>

Notatki

Informacja:

Funkcja mysql_data_seek() może być uzyta tylko w połączeniu z mysql_query(), a nie z mysql_unbuffered_query().

Zobacz też:

  • mysql_query() - Wysyła zapytanie do serwera MySQL
  • mysql_num_rows() - Zwraca liczbę wierszy w wyniku
  • mysql_fetch_row() - Zapisuje wiersz wyniku w tablicy wyliczeniowej
  • mysql_fetch_assoc() - Zapisuje wiersz wyniku w tablicy asocjacyjnej
  • mysql_fetch_array() - Zapisuje wiersz wyniku w tablicy asocjacyjnej, numerycznej lub w obu
  • mysql_fetch_object() - Zapisuje wiersz wyniku jako obiekt

mysql_create_db
mysql_db_name
MySQL Funkcje


Pobiera dane wynikowe

mysql_data_seek
mysql_db_query
MySQL Funkcje
PHP Manual

mysql_db_name

(PHP 4, PHP 5)

mysql_db_name — Pobiera dane wynikowe

Opis

string mysql_db_name ( resource $wynik , int $wiersz [, mixed $ pole ] )

mysql_db_name() przyjmuje jako pierwszy parametr wskaźnik wyniku zwrócony przez mysql_list_dbs(). Parametr wiersz działa jako indeks wyniku.

Jeśli wystąpi błąd, zwrócona zostanie wartość FALSE. Użyj mysql_errno() i mysql_error() by poznać przyczynę błędu.

Przykład #1 mysql_db_name

<?php
error_reporting(E_ALL);

mysql_connect('localhost', 'uzytkownik', 'haslo');
$db_list = mysql_list_dbs();

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
    echo mysql_db_name($db_list, $i) . "\n";
    $i++;
}
?>

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_dbname().

mysql_data_seek
mysql_db_query
MySQL Funkcje


Wybiera bazę danych MySQL i wykonuje na niej zapytanie

mysql_db_name
mysql_drop_db
MySQL Funkcje
PHP Manual

mysql_db_query

(PHP 4, PHP 5)

mysql_db_query — Wybiera bazę danych MySQL i wykonuje na niej zapytanie

Opis

resource mysql_db_query ( string $baza , string $zapytanie [, resource $identyfikator_połączenia ] )

mysql_db_query() wybiera bazę i wykonuje na niej zapytanie.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Parametry

baza

Nazwa bazy danych, która zostanie wybrana.

zapytanie

Zapytanie do bazy MySQL.

Dane w zapytaniu powinny być poprzedzone poprawnymi znakami ucieczki.

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca dodatni identyfikator wyniku MySQL wskazujący na wynik zapytania, lub FALSE w przypadku błędu. Wartość TRUE/FALSE jest także zwracana dla zapytań INSERT/UPDATE/DELETE informując o sukcesie lub błędzie.

Rejestr zmian

Wersja | Opis
5.3.0 | Ta funkcja zwraca wyjątek E_DEPRECATED.
4.0.6 | Nie zaleca się używania tej funkcji. W zamian korzystaj z mysql_select_db() lub mysql_query().

Przykłady

Przykład #1 Przykład mysql_db_query()

<?php

if (!$link = mysql_connect('host', 'uzytkownik', 'haslo')) {
    echo 'Nie można nawiązać połączenia z bazą danych';
    exit;
}

if (!mysql_select_db('nazwa_bazy', $link)) {
    echo 'Nie można wybrać bazy danych';
    exit;
}

$sql    = 'SELECT foo FROM bar WHERE id = 42';
$result = mysql_query($sql, $link);

if (!$result) {
    echo "Błąd bazy danych, nie można wykonać zapytania do bazy\n";
    echo 'Błąd MySQL: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row['foo'];
}

mysql_free_result($result);

?>

Notatki

Informacja:

Zwróć uwagę, że ta funkcja NIE wybierze ponownie bazy danych, z którą byłeś połączony wcześniej. Innymi słowy, funkcji tej nie można użyć do wysłania zapytania w tle do innej bazy, w takim przypadku należy ręcznie przełączyć się z powrotem do pierwotnie wybranej bazy. Zamiast tego zaleca się stosowanie składni database.table lub mysql_select_db() w zapytaniach SQL.

Zobacz też:

  • mysql_query() - Wysyła zapytanie do serwera MySQL
  • mysql_select_db() - Wybiera bazę MySQL

mysql_db_name
mysql_drop_db
MySQL Funkcje


Usuwa bazę MySQL

mysql_db_query
mysql_errno
MySQL Funkcje
PHP Manual

mysql_drop_db

(PHP 4, PHP 5)

mysql_drop_db — Usuwa bazę MySQL

Opis

bool mysql_drop_db ( string $nazwa_bazy [, resource $ identyfikator_połączenia ] )

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

mysql_drop_db() usuwa całą bazę z serwera skojarzonego z podanym identyfikatorem połączenia.

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_dropdb(). Jest to jednak niezalecane.

Informacja:

Stosowanie funkcji mysql_drop_db() jest niezalecane. Sugerowane jest wydawanie polecenia DROP DATABASE przy użyciu funkcji mysql_query().

Patrz także: mysql_create_db(), mysql_query().

mysql_db_query
mysql_errno
MySQL Funkcje


Zwraca liczbową wartość kodu błędu z poprzedniej operacji MySQL

mysql_drop_db
mysql_error
MySQL Funkcje
PHP Manual

mysql_errno

(PHP 4, PHP 5)

mysql_errno — Zwraca liczbową wartość kodu błędu z poprzedniej operacji MySQL

Opis

int mysql_errno ([ resource $identyfikator_połączenia ] )

Zwraca numer błędu z ostatniej operacji MySQL.

Błędy, zwracane z serwera MySQL, nie powodują generowania ostrzeżeń. Zamiast tego, należy używać funkcji mysql_errno() do pobrania kodu błędu. Funkcja ta zwraca tylko kod błędu, wygenerowany przez ostatnio wywołaną funkcję MySQL (nie licząc mysql_error() i mysql_errno()), a więc kod błędu należy sprawdzać przed wywołaniem kolejnej funkcji MySQL.

Parametry

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca numer błędu ostatnio wywołanej funkcji MySQL, lub Returns the error number from the last MySQL function, or 0 (zero) jeśli żaden błąd nie wystąpił.

Przykłady

Przykład #1 Przykłady użycia mysql_errno()

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!mysql_select_db("nieistniejacabaza", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}

mysql_select_db("kossu", $link);
if (!mysql_query("SELECT * FROM nieistniejacatabela", $link)) {
    echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
?>

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

1049: Unknown database 'nieistniejacabaza'
1146: Table 'kossu.nieistniejacatabela' doesn't exist

Zobacz też:

  • mysql_error() - Zwraca tekst komunikatu błędu z ostatniej operacji MySQL
  • » Kody błędów MySQL

mysql_drop_db
mysql_error
MySQL Funkcje


Zwraca tekst komunikatu błędu z ostatniej operacji MySQL

mysql_errno
mysql_escape_string
MySQL Funkcje
PHP Manual

mysql_error

(PHP 4, PHP 5)

mysql_error — Zwraca tekst komunikatu błędu z ostatniej operacji MySQL

Opis

string mysql_error ([ resource $ identyfikator_połączenia ] )

Zwraca tekst komunikatu błędu z ostatnio użytej funkcji MySQL, lub '' (pusty łańcuch) jeśli wystąpi błąd.

Błędy pochodzące z klienta bazy MySQL już nie powodują wyświetlania ostrzeżeń. Zamiast tego, użyj mysql_error() by uzyskać komunikat błędu. Weź pod uwagę, że ta funkcja zwraca komunikat błędu z ostatnio użytej funkcji MySQL (wyłączając mysql_error() i mysql_errno()), dlatego jeśli jej używasz, upewnij się, by zrobić to przed użyciem następnej funkcji MySQL.

Przykład #1 Przykład użycia mysql_error

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo');

mysql_select_db('niematakiejbazy');
echo mysql_errno() . ": " . mysql_error(). "\n";

mysql_select_db('takiejbazytezniema');
mysql_query('SELECT * FROM niematakiejtabeli');
echo mysql_errno() . ": " . mysql_error() . "\n";
?>

Powyższy przykład da następujący wynik:

1049: Unknown database 'niematakiejbazy'
1146: Table 'takiejbazytezniema.niematakiejtabeli' doesn't exist

Informacja:

Jeżeli jako opcjonalny argument zostanie podany identyfikator połączenia, to zostanie on wykorzystany do wyciągnięcia numeru błędu. Jeśli nie, wykorzystane zostanie ostatnio otwarte połączenie.

Patrz także: mysql_errno()

mysql_errno
mysql_escape_string
MySQL Funkcje


Dodaje znaki unikowe na użytek mysql_query

mysql_error
mysql_fetch_array
MySQL Funkcje
PHP Manual

mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string — Dodaje znaki unikowe na użytek mysql_query

Opis

string mysql_escape_string ( string $łańcuch_bez_znaków_unikowych )

Ta funkcja wstawi znaki unikowe do łańcuch_bez_znaków_unikowych, aby bezpiecznym było umieszczenie go w mysql_query().

Informacja: mysql_escape_string() nie dotyczy znaków % i _. Funkcja ta działa identycznie jak mysql_real_escape_string(), z tym wyjątkiem, że mysql_real_escape_string() pobiera identyfikator połączenia i wstawia znaki unikowe zgodnie z bieżącym zestawem znaków. mysql_escape_string() nie pobiera identyfikatora połączenia i nie bierze pod uwagę bieżącego zestawu znaków.

Przykład #1 przykład użycia mysql_escape_string()

<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf ("Łańcuch ze znakami unikowymi: %s\n", $escaped_item);
?>

Powyższy przykład da następujący wynik:

Łańcuch ze znakami unikowymi: Zak\'s Laptop

Patrz także: mysql_real_escape_string(), addslashes() oraz dyrektywa magic_quotes_gpc.

mysql_error
mysql_fetch_array
MySQL Funkcje


Zapisuje wiersz wyniku w tablicy asocjacyjnej, numerycznej lub w obu

mysql_escape_string
mysql_fetch_assoc
MySQL Funkcje
PHP Manual

mysql_fetch_array

(PHP 4, PHP 5)

mysql_fetch_array — Zapisuje wiersz wyniku w tablicy asocjacyjnej, numerycznej lub w obu

Opis

array mysql_fetch_array ( resource $wynik [, int $ typ_wyniku ] )

Zwraca tablicę zawierającą pobrany wiersz, lub FALSE jeżeli nie ma więcej wierszy w wynik.

mysql_fetch_array() jest rozszerzoną wersją mysql_fetch_row(). Oprócz zapisywania danych w indeksach numerycznych, zapisuje je też w indeksach przyporządkowujących (asocjacyjnych), używając nazw pól jako kluczy.

Jeżeli dwie lub więcej kolumn wyniku ma te same nazwy, ostatnia kolumna będzie brana pod uwagę. Dostęp do innych kolumn o tej samej nazwie jest możliwy jedynie przez indeksowanie numeryczne lub przez stworzenie aliasa. Po stworzeniu aliasa nie można już odwoływać się do danej kolumny używając jej prawdziwej nazwy (w tym przykładzie używając 'pole').

Przykład #1 Zapytanie z powtarzającymi się nazwami pól

select table1.field as foo table2.field as bar from table1, table2

Godne uwagi jest to, że użycie mysql_fetch_array() nie jest znacząco wolniejsze od użycia mysql_fetch_row(), a jest bardziej funkcjonalne.

Opcjonalny drugi argument result_type w funkcji mysql_fetch_array() jest stałą i może przyjmować następujące wartości: MYSQL_ASSOC, MYSQL_NUM i MYSQL_BOTH. Tę funkcjonalność dodano w PHP 3.0.7. Wartością domyślną jest MYSQL_BOTH.

Używając MYSQL_BOTH otrzymasz tablicę indeksowaną zarówno asocjacyjnie jak i numerycznie. MYSQL_ASSOC dostarczy tablicy indeksowanej tylko asocjacyjnie (jak w mysql_fetch_assoc()), natomiast MYSQL_NUM indeksowanej tylko numerycznie (jak w mysql_fetch_row()).

Przykład #2 mysql_fetch_array z MYSQL_NUM

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo') or
    die('Nie można się połączyć: ' . mysql_error());
mysql_select_db('baza');

$result = mysql_query("SELECT id, nazwa FROM tabela");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    printf ("ID: %s  Nazwa: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>

Przykład #3 mysql_fetch_array z MYSQL_ASSOC

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo') or
    die('Nie można się połączyć: ' . mysql_error());
mysql_select_db('baza');

$result = mysql_query("SELECT id, nazwa FROM tabela");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    printf ("ID: %s  Nazwa: %s", $row["id"], $row["nazwa"]);
}
mysql_free_result($result);
?>

Przykład #4 mysql_fetch_array z MYSQL_BOTH

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo') or
    die('Nie można się połączyć: ' . mysql_error());
mysql_select_db('baza');

$result = mysql_query("SELECT id, nazwa FROM tabela");

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    printf ("ID: %s  Nazwa: %s", $row[0], $row["nazwa"]);
}
mysql_free_result($result);
?>

Patrz także: mysql_fetch_row(), mysql_fetch_assoc().

mysql_escape_string
mysql_fetch_assoc
MySQL Funkcje


Zapisuje wiersz wyniku w tablicy asocjacyjnej

mysql_fetch_array
mysql_fetch_field
MySQL Funkcje
PHP Manual

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — Zapisuje wiersz wyniku w tablicy asocjacyjnej

Opis

array mysql_fetch_assoc ( resource $wynik )

Zwraca tablicę zawierającą pobrany wiersz, lub FALSE jeżeli nie ma więcej wierszy w wynik.

Użycie mysql_fetch_assoc() jest równoznaczne z wywołaniem mysql_fetch_array() podając jako drugi argument MYSQL_ASSOC. Zwraca jedynie tablicę asocjacyjną. Początkowo tak właśnie zachowywała się funkcja mysql_fetch_array(). Jeśli oprócz indeksowania asocjacyjnego potrzebujesz także numeryczne, użyj funkcji mysql_fetch_array().

Jeżeli dwie lub więcej kolumn wyniku ma te same nazwy, ostatnia kolumna będzie brana pod uwagę. Dostęp do innych kolumn o tej samej nazwie jest możliwy przy użyciu funkcji mysql_fetch_array(), która wprowadzi również indeksowanie numeryczne.

Godne uwagi jest to, że użycie mysql_fetch_assoc() nie jest znacząco wolniejsze od użycia mysql_fetch_row(), a jest bardziej funkcjonalne.

Przykład #1 mysql_fetch_assoc()

<?php
mysql_connect('localhost','uzytkownik','haslo');
mysql_select_db('baza');
$result = mysql_query('select * from tabela');
while ($row = mysql_fetch_assoc($result)) {
    echo $row["id_uzytkownika"];
    echo $row["pelna_nazwa"];
}
mysql_free_result($result);
?>

Patrz także:
mysql_fetch_row(),
mysql_fetch_array() i
mysql_query().

mysql_fetch_array
mysql_fetch_field
MySQL Funkcje


Pobiera z wyniku informacje o kolumnie i zwraca jako obiekt

mysql_fetch_assoc
mysql_fetch_lengths
MySQL Funkcje
PHP Manual

mysql_fetch_field

(PHP 4, PHP 5)

mysql_fetch_field — Pobiera z wyniku informacje o kolumnie i zwraca jako obiekt

Opis

object mysql_fetch_field ( resource $wynik [, int $ ofset_pola ] )

Zwraca obiekt zawierający informacje o polu.

mysql_fetch_field() pozwala uzyskać informacje o polach w danym wyniku zapytania. Jeżeli ofset pola nie został podany, zwracane zostanie następne pole nie pobrane jeszcze przez mysql_fetch_field().

Właściwości obiektu:

  • name - nazwa kolumny
  • table - nazwa tabeli do której należy kolumna
  • max_length - maksymalna długość kolumny
  • not_null - 1 jeżeli pole nie może być puste (NULL)
  • primary_key - 1 jeżeli kolumna jest kluczem podstawowym
  • unique_key - 1 jeżeli kolumna jest kluczem unikatowym
  • multiple_key - 1 jeżeli kolumna jest kluczem nieunikatowym
  • numeric - 1 jeżeli kolumna jest liczbowa
  • blob - 1 jeżeli kolumna jest typu BLOOB
  • type - typ kolumny
  • unsigned - 1 jeżeli kolumna jest bez znaku (plus lub minus)
  • zerofill - 1 jeżeli kolumna jest wypełniona zerami

Przykład #1 mysql_fetch_field()

<?php
mysql_connect('localhost','uzytkownik','haslo');
    or die ('Nie można się połączyć');
mysql_select_db('baza');
$result = mysql_query('select * from tabela')
    or die('Zapytanie zakończone niepowodzeniem');
/* pobieramy dane kolumny */
$i = 0;
while ($i < mysql_num_fields($result)) {
    echo "Informacje o kolumnie $i:<br />\n";
    $meta = mysql_fetch_field($result);
    if (!$meta) {
        echo "Informacje niedostępne<br />\n";
    }
    echo "<pre>
blob:         $meta->blob
max_length:   $meta->max_length
multiple_key: $meta->multiple_key
name:         $meta->name
not_null:     $meta->not_null
numeric:      $meta->numeric
primary_key:  $meta->primary_key
table:        $meta->table
type:         $meta->type
unique_key:   $meta->unique_key
unsigned:     $meta->unsigned
zerofill:     $meta->zerofill
</pre>";
    $i++;
}
mysql_free_result($result);
?>

Patrz także: mysql_field_seek().

mysql_fetch_assoc
mysql_fetch_lengths
MySQL Funkcje


Pobiera długość każdego pola w wierszu wyniku

mysql_fetch_field
mysql_fetch_object
MySQL Funkcje
PHP Manual

mysql_fetch_lengths

(PHP 4, PHP 5)

mysql_fetch_lengths — Pobiera długość każdego pola w wierszu wyniku

Opis

array mysql_fetch_lengths ( resource $wynik )

Zwraca tablicę zawierającą długość każdego pola z wiersza ostatnio pobranego przez mysql_fetch_row(), lub FALSE, jeżeli wystąpi błąd.

mysql_fetch_lengths() zapisuje w tablicy
długości wszystkich pól z ostatniego wiersza pobranego przez
funkcje mysql_fetch_row(),
mysql_fetch_array() i
mysql_fetch_object() zaczynając od
ofsetu 0.

Patrz także: mysql_fetch_row().

mysql_fetch_field
mysql_fetch_object
MySQL Funkcje


Zapisuje wiersz wyniku jako obiekt

mysql_fetch_lengths
mysql_fetch_row
MySQL Funkcje
PHP Manual

mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object — Zapisuje wiersz wyniku jako obiekt

Opis

object mysql_fetch_object ( resource $wynik )

Zwraca: obiekt, którego właściwości zawierają pobrany wiersz, lub FALSE, jeżeli nie ma więcej wierszy.

Funkcja mysql_fetch_object() jest podobna do mysql_fetch_array() z jedną różnicą - zamiast tablicy zwracany jest obiekt. Oczywiście oznacza to, że dane dostępne są tylko przez podanie nazw pól, a nie przed podanie ofsetu (liczby nie są dopuszczalne jako nazwy właściwości).

<?php

/* poprawnie */
echo $wiersz->pole;
/* niepoprawnie */
echo $wiersz->0;

?>

Szybkość tej funkcji jest identyczna jak mysql_fetch_array() i prawie taka sama jak mysql_fetch_row() (różnica jest nieznaczna).

Przykład #1 mysql_fetch_object()

<?php
mysql_connect('localhost','uzytkownik','haslo');
mysql_select_db($db);
$result = mysql_query('select * from tabela');
while ($row = mysql_fetch_object($result)) {
    echo $row->id_uzytkownika;
    echo $row->pelna_nazwa;
}
mysql_free_result($result);
?>

Patrz także: mysql_fetch_array() i mysql_fetch_row().

mysql_fetch_lengths
mysql_fetch_row
MySQL Funkcje


Zapisuje wiersz wyniku w tablicy wyliczeniowej

mysql_fetch_object
mysql_field_flags
MySQL Funkcje
PHP Manual

mysql_fetch_row

(PHP 4, PHP 5)

mysql_fetch_row — Zapisuje wiersz wyniku w tablicy wyliczeniowej

Opis

array mysql_fetch_row ( resource $wynik )

Zwraca tablicę numeryczną, która odpowiada pobranemu wierszowi i przesuwa do przodu wewnętrzny wskaźnik danych.

Parametry

wynik

Wynik w postaci zmiennej typu resource, które jest przetwarzane. Wynik ten pochodzi z wywołania funkcji mysql_query().

Zwracane wartości

Zwraca tablicę numeryczną, która odpowiada pobranemu wierszowi, lub FALSE jeśli nie ma więcej wierszy.

mysql_fetch_row() pobiera jeden wiersz danych z wyniku skojarzonego z podanym identyfikatorem wyniku. Wiersz zwracany jest jako tablica. Komórki są umieszczone pod oddzielnymi ofsetami, zaczynając od 0.

Przykłady

Przykład #1 Pobieranie jednego wiersza za pomocą mysql_fetch_row()

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Nie można uruchomić zapytania: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // wartość kolumny email
?>

Notatki

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Zobacz też:

  • mysql_fetch_array() - Zapisuje wiersz wyniku w tablicy asocjacyjnej, numerycznej lub w obu
  • mysql_fetch_assoc() - Zapisuje wiersz wyniku w tablicy asocjacyjnej
  • mysql_fetch_object() - Zapisuje wiersz wyniku jako obiekt
  • mysql_data_seek() - Przesuwa wewnętrzny wskaźnik wyniku
  • mysql_fetch_lengths() - Pobiera długość każdego pola w wierszu wyniku
  • mysql_result() - Zwraca dane wynikowe

mysql_fetch_object
mysql_field_flags
MySQL Funkcje


Pobiera flagi dla danego pola w wyniku

mysql_fetch_row
mysql_field_len
MySQL Funkcje
PHP Manual

mysql_field_flags

(PHP 4, PHP 5)

mysql_field_flags — Pobiera flagi dla danego pola w wyniku

Opis

string mysql_field_flags ( resource $wynik , int $ofset_pola )

mysql_field_flags() zwraca flagi podanego pola. Flagi są przedstawiane jako pojedyncze słowa oddzielone spacją tak, by można było je rodzielić za pomocą funkcji explode().

Następujące flagi są przedstawiane jeżeli wersja MySQLa jest na tyle aktualna by je obsłużyć: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldflags(). Jest to jednak niezalecane.

mysql_fetch_row
mysql_field_len
MySQL Funkcje


Zwraca długość danego pola

mysql_field_flags
mysql_field_name
MySQL Funkcje
PHP Manual

mysql_field_len

(PHP 4, PHP 5)

mysql_field_len — Zwraca długość danego pola

Opis

int mysql_field_len ( resource $wynik , int $ofset_pola )

mysql_field_len() zwraca długość danego pola.

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldlen(). Jest to jednak niezalecane.

mysql_field_flags
mysql_field_name
MySQL Funkcje


Podaje nazwę danego pola w wyniku

mysql_field_len
mysql_field_seek
MySQL Funkcje
PHP Manual

mysql_field_name

(PHP 4, PHP 5)

mysql_field_name — Podaje nazwę danego pola w wyniku

Opis

string mysql_field_name ( resource $wynik , int $indeks_pola )

mysql_field_name() zwraca nazwę danego pola. wynik musi być poprawnym identyfikatorem wyniku, a indeks_pola powinien zawierać liczbowy indeks pola.

Informacja:

indeks_pola liczy się od 0.

Indeksem trzeciego pola będzie liczba 2, czwartego 3 i tak dalej...

Przykład #1 mysql_field_name()

<?php
/* Tabela składa się z trzech pól:
 *   id_uzytkownika
 *   nazwa_uzytkownika
 *   haslo
 */
$link = mysql_connect('localhost', 'uzytkownik', 'haslo');
mysql_select_db($dbname, $link)
    or die("Nie można otworzyć bazy $dbname");
$res = mysql_query("select * from users", $link);
echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);
?>

Powyższy przykład da następujący wynik:

id_uzytkownika
haslo

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldname(). Jest to jednak niezalecane.

mysql_field_len
mysql_field_seek
MySQL Funkcje


Przesuwa wskaźnik wyniku do wybranego pola

mysql_field_name
mysql_field_table
MySQL Funkcje
PHP Manual

mysql_field_seek

(PHP 4, PHP 5)

mysql_field_seek — Przesuwa wskaźnik wyniku do wybranego pola

Opis

int mysql_field_seek ( resource $wynik , int $ofset_pola )

Przesuwa się na wybrane pole. Jeżeli kolejne wywołanie mysql_fetch_field() nie będzie zawierać indeksu pola, wtedy zwrócone zostanie to pole.

Patrz także: mysql_fetch_field().

mysql_field_name
mysql_field_table
MySQL Funkcje


Pobiera nazwę tabeli w której znajduje się dane pole

mysql_field_seek
mysql_field_type
MySQL Funkcje
PHP Manual

mysql_field_table

(PHP 4, PHP 5)

mysql_field_table — Pobiera nazwę tabeli w której znajduje się dane pole

Opis

string mysql_field_table ( resource $wynik , int $ofset_pola )

Zwraca nazwę tabeli w której znajduje się dane pole.

Parametry

wynik

Wynik w postaci zmiennej typu resource, które jest przetwarzane. Wynik ten pochodzi z wywołania funkcji mysql_query().

przesunięcie_pola

Liczbowe przesunięcie pola. przesunięcie_pola zaczyna się od wartości 0. Jeśli przesunięcie_pola nie istnieje, wygenerowane zostanie ostrzeżenie poziomu E_WARNING.

Zwracane wartości

Zwraca nazwę tabeli w przypadku powodzenia.

Przykłady

Przykład #1 Przykład użycia mysql_field_table()

<?php

$query = "SELECT konto.*, panstwo.* FROM konto, panstwo WHERE konto.nazwa = 'Polska' AND konto.panstwo_id = panstwo.id";

// Pobiera wynik z bazy danych
$result = mysql_query($query);

// Wyświetla nazwę tablicy, a następnie nazwę pola
for ($i = 0; $i < mysql_num_fields($result); ++$i) {
    $table = mysql_field_table($result, $i);
    $field = mysql_field_name($result, $i);

    echo  "$table: $field\n";
}

?>

Notatki

Informacja:

Dla zachowania zgodności z poprzednimi wersjami PHP możliwe jest używanie aliasów: mysql_fieldtable()

Zobacz też:

  • mysql_list_tables() - Pobiera listę tabel z bazy MySQL

mysql_field_seek
mysql_field_type
MySQL Funkcje


Pobiera typ podanego pola

mysql_field_table
mysql_free_result
MySQL Funkcje
PHP Manual

mysql_field_type

(PHP 4, PHP 5)

mysql_field_type — Pobiera typ podanego pola

Opis

string mysql_field_type ( resource $wynik , int $ofset_pola )

Funkcja mysql_field_type() jest podobna do mysql_field_name(). Argumenty są identyczne, ale zwracany jest typ pola. Będzie to jeden z "int", "real", "string", "blob" lub innych opisanych w dokumentacji » MySQL.

Przykład #1 Typy pól MySQL

<?php
mysql_connect('localhost','uzytkownik','haslo');
mysql_select_db('baza');
$result = mysql_query('SELECT * FROM tabela');
$fields = mysql_num_fields($result);
$rows   = mysql_num_rows($result);
$table = mysql_field_table($result, 0);
echo "Tabela '".$table."' ma ".$fields." pól i ".$rows." wierszy\n";
echo "Tabela ma następujące pola:\n";
for ($i=0; $i < $fields; $i++) {
    $type  = mysql_field_type($result, $i);
    $name  = mysql_field_name($result, $i);
    $len   = mysql_field_len($result, $i);
    $flags = mysql_field_flags($result, $i);
    echo $type." ".$name." ".$len." ".$flags."\n";
    $i++;
}
mysql_free_result($result);
mysql_close();
?>

Powyższy przykład da następujący wynik:

Tabela 'tabela' ma 4 pól i 1 wierszy
Tabela ma następujące pola:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_fieldtype(). Jest to jednak niezalecane.

mysql_field_table
mysql_free_result
MySQL Funkcje


Zwalnia pamięć zajmowaną przez wynik

mysql_field_type
mysql_get_client_info
MySQL Funkcje
PHP Manual

mysql_free_result

(PHP 4, PHP 5)

mysql_free_result — Zwalnia pamięć zajmowaną przez wynik

Opis

bool mysql_free_result ( resource $wynik )

mysql_free_result() zwolni całą pamięć przydzieloną podanemu wskaźnikowi wyniku.

mysql_free_result() używa się tylko w wypadkach obawy zajęcia zbyt dużej ilości pamięci przez zapytania zwracające duże ilości danych. Cała pamięć przydzielona wynikowi skojarzonemu z podanym identyfikatorem wyniku będzie automatycznie zwolniona.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_freeresult(). Jest to jednak niezalecane.

mysql_field_type
mysql_get_client_info
MySQL Funkcje


Pobiera informacje o kliencie MySQL

mysql_free_result
mysql_get_host_info
MySQL Funkcje
PHP Manual

mysql_get_client_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info — Pobiera informacje o kliencie MySQL

Opis

string mysql_get_client_info ( void )

mysql_get_client_info() zwraca ciąg znaków zawierający wersję bibliotek klienta MySQL.

Przykład #1 mysql_get_client_info

<?php
printf ("MySQL client info: %s\n", mysql_get_client_info());
?>

Powyższy przykład da następujący wynik:

MySQL client info: 3.23.39

Patrz także: mysql_get_host_info(),
mysql_get_proto_info() i
mysql_get_server_info().

mysql_free_result
mysql_get_host_info
MySQL Funkcje


Pobiera informacje o hoście MySQL

mysql_get_client_info
mysql_get_proto_info
MySQL Funkcje
PHP Manual

mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info — Pobiera informacje o hoście MySQL

Opis

string mysql_get_host_info ([ resource $identyfikator_połączenia ] )

mysql_get_host_info() zwraca ciąg znaków opisujący typ połączenia wykorzystywany przez identyfikator_połączenia, włączając to nazwę serwera. Jeżeli identyfikator_połączenia nie zostanie podany, wykorzystane zostanie ostatnio otwarte połączenie.

Przykład #1 mysql_get_host_info

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo') or
    die('Nie można się połączyć');
printf ("MySQL host info: %s\n", mysql_get_host_info());
?>

Powyższy przykład da następujący wynik:

MySQL host info: Localhost via UNIX socket

Patrz także: mysql_get_client_info(),
mysql_get_proto_info() i
mysql_get_server_info().

mysql_get_client_info
mysql_get_proto_info
MySQL Funkcje


Pobiera informacje o protokole MySQL

mysql_get_host_info
mysql_get_server_info
MySQL Funkcje
PHP Manual

mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info — Pobiera informacje o protokole MySQL

Opis

int mysql_get_proto_info ([ resource $identyfikator_połączenia ] )

mysql_get_proto_info() zwraca wersję protokołu, używanego przez identyfikator_połączenia. Jeżeli identyfikator_połączenia nie zostanie podany, wykorzystane zostanie ostatnio otwarte połączenie.

Przykład #1 mysql_get_proto_info

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo') or
    die('Nie można się połączyć');
printf ("MySQL protocol version: %s\n", mysql_get_proto_info());
?>

Powyższy przykład da następujący wynik:

MySQL protocol version : 10

Patrz także: mysql_get_client_info(),
mysql_get_host_info() i
mysql_get_server_info().

mysql_get_host_info
mysql_get_server_info
MySQL Funkcje


Pobiera informacje o serwerze MySQL

mysql_get_proto_info
mysql_info
MySQL Funkcje
PHP Manual

mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info — Pobiera informacje o serwerze MySQL

Opis

string mysql_get_server_info ([ resource $identyfikator_połączenia ] )

mysql_get_server_info() zwraca wersję serwera, używanego przez identyfikator_połączenia. Jeżeli identyfikator_połączenia nie zostanie podany, wykorzystane zostanie ostatnio otwarte połączenie.

mysql_get_server_info() dodano w PHP 4.0.5.

Przykład #1 mysql_get_server_info

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo') or
    die('Nie można się połączyć');
printf ("MySQL server version: %s\n", mysql_get_server_info());
?>

Powyższy przykład da następujący wynik:

MySQL server version: 4.0.1-alpha

Patrz także: mysql_get_client_info(),
mysql_get_host_info() i
mysql_get_proto_info().

mysql_get_proto_info
mysql_info
MySQL Funkcje


Pobiera informacje o ostatnim zapytaniu

mysql_get_server_info
mysql_insert_id
MySQL Funkcje
PHP Manual

mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info — Pobiera informacje o ostatnim zapytaniu

Opis

string mysql_info ([ resource $ identyfikator_połączenia ] )

mysql_info() zwraca szczegółowe informacje o ostatnim zapytaniu wykonanym przy użyciu podanego identyfikatora_połączenia. Jeśli identyfikator_połączenia nie zostanie podany, domyślnie przyjmowane jest ostatnio otwarte połączenie.

mysql_info() zwraca wartość typu string dla poleceń wymienionych poniżej. Dla wszystkich innych zwracana jest wartość FALSE. Format zwracanej wartości zależy od polecenia.

Przykład #1 Formaty zwracanych wartości

INSERT INTO ... SELECT ...
String format: Records: 23 Duplicates: 0 Warnings: 0
INSERT INTO ... VALUES (...),(...),(...)...
String format: Records: 37 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ...
String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE
String format: Records: 60 Duplicates: 0 Warnings: 0
UPDATE
String format: Rows matched: 65 Changed: 65 Warnings: 0
Podane wartości są jedynie przykładowe. Będą one różne, w zależności od zapytania.

Informacja:

Dla poleceń typu INSERT ... VALUES, mysql_info() zwraca wartość różną od FALSE, tylko jeśli w zapytaniu podanych zostało kilka wartości.

Patrz także: mysql_affected_rows()

mysql_get_server_info
mysql_insert_id
MySQL Funkcje


Podaje numer ID wygenerowany podczas ostatniej operacji INSERT

mysql_info
mysql_list_dbs
MySQL Funkcje
PHP Manual

mysql_insert_id

(PHP 4, PHP 5)

mysql_insert_id — Podaje numer ID wygenerowany podczas ostatniej operacji INSERT

Opis

int mysql_insert_id ([ resource $ identyfikator_połączenia ] )

mysql_insert_id() zwraca ID wygenerowane dla pola z własnością AUTO_INCREMENT. Funkcja zwróci ID wygenerowane automatycznie przez ostatnią operację INSERT używającą podanego identyfikatora_połączenia. Jeżeli identyfikator_połączenia nie został podany, wykorzystywane jest ostatnio otwarte połączenie.

mysql_insert_id() zwróci 0 jeśli ostatnie zapytanie nie generowało wartości AUTO_INCREMENT. Jeśli chcesz przechować zwrócony przez tę funkcję wynik, upewnij się, że wywołujesz ją zaraz po zapytaniu generującym nową wartość.

Informacja:

Funkcja MySQL LAST_INSERT_ID() zawsze zawiera ostatnio wygenerowane ID, a zwracana wartośc nie jest czyszczona pomiędzy kolejnymi zapytaniami.

Ostrzeżenie

mysql_insert_id() konwertuje typ wartości otrzymanej od natywnej funkcji MySQL C API mysql_insert_id() na typ long (czyli int w PHP). Jeśli kolumna AUTO_INCREMENT jest typu BIGINT, wartość zwracana przez mysql_insert_id() będzie niepoprawna. Należy w zapytaniu SQL użyć wewnętrznej funkcji MySQL LAST_INSERT_ID().

Przykład #1 Przykład użycia mysql_insert_id

<?php
    mysql_connect('localhost', 'uzytkownik', 'haslo') or
        die('Nie można się połączyć');
    mysql_select_db('baza');

    mysql_query("INSERT INTO mytable (product) values ('kossu')");
    printf ("Ostatnio dodany rekord ma id %d\n", mysql_insert_id());
?>

Patrz także: mysql_query().

mysql_info
mysql_list_dbs
MySQL Funkcje


Pobiera nazwy baz dostępnych na serwerze MySQL

mysql_insert_id
mysql_list_fields
MySQL Funkcje
PHP Manual

mysql_list_dbs

(PHP 4, PHP 5)

mysql_list_dbs — Pobiera nazwy baz dostępnych na serwerze MySQL

Opis

resource mysql_list_dbs ([ resource $ identyfikator_połączenia ] )

mysql_list_dbs() zwróci wynik zawierający nazwy baz dostępnych na serwerze skojarzonym z identyfikatorem połączenia. Żeby uzyskać nazwy za wskaźnika wyniku należy użyć funkcji mysql_tablename() lub innej operującej na tablicach wyników.

Przykład #1 mysql_list_dbs()

<?php
$link = mysql_connect ('localhost','uzytkownik','haslo');
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}
?>

Powyższy przykład da następujący wynik:

baza1
baza2
baza3
...

Informacja:

Powyższy kod będzie równie dobrze działał z funkcją mysql_fetch_row() lub innymi podobnymi.

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_listdbs(). Jest to jednak niezalecane.

Patrz także: mysql_db_name().

mysql_insert_id
mysql_list_fields
MySQL Funkcje


Pobiera informacje o polach tabeli MySQL

mysql_list_dbs
mysql_list_processes
MySQL Funkcje
PHP Manual

mysql_list_fields

(PHP 4, PHP 5)

mysql_list_fields — Pobiera informacje o polach tabeli MySQL

Opis

resource mysql_list_fields ( string $baza , string $tabela [, resource $ identyfikator_połączenia ] )

mysql_list_fields()
pobiera informacje o danej tabeli. Argumentami są nazwa bazy i
nazwa tabeli. Zwracany jest wskaźnik wyniku, który może zostać
użyty z funkcjami mysql_field_flags(),
mysql_field_len(),
mysql_field_name() i
mysql_field_type().

Przykład #1 mysql_list_fields()

<?php
$link = mysql_connect ('localhost','uzytkownik','haslo');

$fields = mysql_list_fields('baza', 'tabela', $link);
$columns = mysql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo mysql_field_name($fields, $i) . "\n";
}
?>

Powyższy przykład da następujący wynik:

pole1
pole2
pole3
...

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_listfields(). Jest to jednak niezalecane.

mysql_list_dbs
mysql_list_processes
MySQL Funkcje


Zwraca listę procesów MySQL

mysql_list_fields
mysql_list_tables
MySQL Funkcje
PHP Manual

mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes — Zwraca listę procesów MySQL

Opis

resource mysql_list_processes ([ resource $ identyfikator_połączenia ] )

mysql_list_processes() zwraca wskaźnik wyniku zawierającego opis aktualnych wątków serwera.

Przykład #1 przykład użycia mysql_list_processes()

<?php
$link = mysql_connect('localhost', 'uzytkownik', 'haslo');

$result = mysql_list_processes($link);
while ($row = mysql_fetch_row($result)){
    printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
       $row["Command"], $row["Time"]);
}
mysql_free_result ($result);
?>

Powyższy przykład da następujący wynik:

1 localhost test Processlist 0
4 localhost mysql sleep 5

Patrz także: mysql_thread_id()

mysql_list_fields
mysql_list_tables
MySQL Funkcje


Pobiera listę tabel z bazy MySQL

mysql_list_processes
mysql_num_fields
MySQL Funkcje
PHP Manual

mysql_list_tables

(PHP 4, PHP 5)

mysql_list_tables — Pobiera listę tabel z bazy MySQL

Opis

resource mysql_list_tables ( string $baza [, resource $ identyfikator_połączenia ] )

mysql_list_tables() przyjmuje jako argument nazwę bazy i zwraca wskaźnik wyniku podobnie jak funkcja mysql_query(). Żeby uzyskać nazwy tabel za wskaźnika wyniku należy użyć funkcji mysql_tablename() lub innej operującej na tablicach wyników.

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_listtables(). Jest to jednak niezalecane.

Przykład #1 Przykład użycia mysql_list_tables

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo') or
    die('Nie można się połączyć');
mysql_select_db('baza');

$result = mysql_list_tables();

while (($row = mysql_fetch_row($result))
    printf ("Tabela: %s\n", $row[0]);

mysql_free_result($result);
?>

Patrz także: mysql_list_dbs(), mysql_tablename().

mysql_list_processes
mysql_num_fields
MySQL Funkcje


Zwraca liczbę pól w wyniku

mysql_list_tables
mysql_num_rows
MySQL Funkcje
PHP Manual

mysql_num_fields

(PHP 4, PHP 5)

mysql_num_fields — Zwraca liczbę pól w wyniku

Opis

int mysql_num_fields ( resource $wynik )

mysql_num_fields() zwraca liczbę pól w wyniku.

Patrz także:
mysql_select_db(),
mysql_query(),
mysql_fetch_field(),
mysql_num_rows().

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_numfields().

mysql_list_tables
mysql_num_rows
MySQL Funkcje


Zwraca liczbę wierszy w wyniku

mysql_num_fields
mysql_pconnect
MySQL Funkcje
PHP Manual

mysql_num_rows

(PHP 4, PHP 5)

mysql_num_rows — Zwraca liczbę wierszy w wyniku

Opis

int mysql_num_rows ( resource $wynik )

mysql_num_rows() zwraca liczbę wierszy w wyniku. Tę funkcję stosuje się tylko do operacji SELECT. Aby pobrać ilość wierszy przetworzonych w operacjach INSERT, UPDATE lub DELETE należy użyć funkcji mysql_affected_rows().

Przykład #1 mysql_num_rows()

<?php
$link = mysql_connect ('serwer','uzytkownik','haslo');
mysql_select_db('baza', $link);

$result = mysql_query('SELECT * FROM tabela', $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows wierszy\n";
?>

Informacja:

Jeśli funkcja mysql_num_rows() jest używana w połączeniu z mysql_unbuffered_query(), poprawna wartość zostanie zwrócona dopiero po odebraniu wszystkich wierszy wyniku.

Patrz także:
mysql_affected_rows(),
mysql_connect(),
mysql_data_seek(),
mysql_select_db() i
mysql_query().

Aby zachować zgodność z poprzednimi wersjami, można użyć również mysql_numrows(). Jest to jednak niezalecane.

mysql_num_fields
mysql_pconnect
MySQL Funkcje


Otwiera stałe połączenie z serwerem MySQL

mysql_num_rows
mysql_ping
MySQL Funkcje
PHP Manual

mysql_pconnect

(PHP 4, PHP 5)

mysql_pconnect — Otwiera stałe połączenie z serwerem MySQL

Opis

resource mysql_pconnect ([ string $ serwer [, string $użytkownik [, string $hasło ]]] )

Zwraca identyfikator połączenia w przypadku powodzenia, lub FALSE jeśli wystąpi błąd.

mysql_connect() nawiązuje połączenie z serwerem MySQL. Jeśli nie podano argumentów, przyjmowane są następujące wartości domyślne: host:port = 'localhost:3306', użytkownik = nazwa użytkownika będącego właścicielem procesu serwera, hasło = puste hasło.

Argument host może również zawierać numer portu, np. "host:port" lub ścieżkę do gniaza np. ":/sciezka/do/gniazda" dla localhosta.

Informacja:

Obsługę ":port" dodano w PHP 3.0B4.

Obsługę ":/sciezka/do/gniazda" dodano w PHP 3.0.10.

mysql_pconnect() zachowuje się prawie jak mysql_connect() z dwoma zasadniczymi różnicami.

Pierwsza, podczas łączenia funkcja najpierw spróbuje znaleźć połączenie (stałe) już otwarte dla tego samego hosta, użytkownika i hasła. Jeżeli je znajdzie, jego identyfikator zostanie zwrócony zamiast otwierania nowego połączenia.

Druga, połączenie z serwerem SQL nie zostanie zamknięte po zakończeniu wykonywania skryptu. Zamiast tego połączenie pozostanie otwarte do późniejszego użycia (mysql_close() nie zamyka połączeń nawiązanych za pomocą mysql_pconnect()).

Dlatego też ten typ połączeń nazywany jest 'stałym'.

Informacja:

Trzeba zaznaczyć, że stałe połączenia działają jedynie z PHP pracującym jako moduł. Przeczytaj rozdział Stałe połączenia z bazami danych by dowiedzieć się więcej.

Ostrzeżenie

Używanie stałych połączeń może wymagać dostrojenia konfiguracji Apache'a i MySQLa, aby nie przekroczyć limitu jednoczesnych połączeń dozwolonych przez MySQL.

mysql_num_rows
mysql_ping
MySQL Funkcje


Sprawdza połączenie z serwerem, lub nawiązuje połączenie, jeśli go nie było

mysql_pconnect
mysql_query
MySQL Funkcje
PHP Manual

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping — Sprawdza połączenie z serwerem, lub nawiązuje połączenie, jeśli go nie było

Opis

bool mysql_ping ([ resource $identyfikator_połączenia ] )

Sprawdza czy połączenie z serwerem działa poprawnie. Jeśli zostało zamknięte, następuje próba ponownego połączenia. Funkcja ta, w skryptach które pozostają długi czas w bezczynności, może służyć do sprawdzenia czy serwer zamknął połączenie i, jeśli zajdzie potrzeba, nawiązania go ponownie.

Informacja:

Od wersji MySQL 5.0.13 automatyczne ponawianie połączenia jest wyłączone.

Parametry

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca TRUE jeśli połączenie z serwerem działa poprawnie, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Przykład użycia mysql_ping()

<?php
set_time_limit(0);

$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db   = mysql_select_db('mydb');

/* Zakładamy, że wykonanie zapytania zajmie dużo czasu */
$result = mysql_query($sql);
if (!$result) {
    echo 'Wykonanie zapytania #1 nie powiodło się, zamykanie.';
    exit;
}

/* Upewniamy się, że połączenie jest aktywne, w przeciwnym wypadku ponawiamy je */
if (!mysql_ping($conn)) {
    echo 'Połączenie zerwane, zamykanie po zapytaniu #1';
    exit;
}
mysql_free_result($result);

/* Jeśli połączenie jest aktywne wykonujemy następne zapytanie */
$result2 = mysql_query($sql2);
?>

Zobacz też:

  • mysql_thread_id() - Zwraca id bieżącego wątku
  • mysql_list_processes() - Zwraca listę procesów MySQL

mysql_pconnect
mysql_query
MySQL Funkcje


Wysyła zapytanie do serwera MySQL

mysql_ping
mysql_real_escape_string
MySQL Funkcje
PHP Manual

mysql_query

(PHP 4, PHP 5)

mysql_query — Wysyła zapytanie do serwera MySQL

Opis

resource mysql_query ( string $zapytanie [, resource $identyfikator_połączenia [, int $typ_wyniku ]] )

mysql_query() wysyła zapytanie do aktywnej bazy na serwerze skojarzonym z podanym identyfikatorem połączenia. Jeżeli identyfikator_połączenia nie został podany, wykorzystywane jest ostatnio otwarte połączenie. Jeżeli żadne połączenie nie jest otwarte, podjęta zostanie próba ustanowienia go, poprzez wywołanie mysql_connect() bez argumentów.

Opcjonalny argument result_mode może przyjmować wartość MYSQL_USE_RESULT lub MYSQL_STORE_RESULT. Domyślnie używana jest wartość MYSQL_STORE_RESULT, zatem wynik jest buforowany. Odpowiednikiem użycia drugiej opcji jest funkcja mysql_unbuffered_query().

Informacja:

Zapytanie nie powinno kończyć się znakiem średnika.

mysql_query() zwraca identyfikator wyniku (lub FALSE w przypadku niepowodzenia) jedynie dla zapytań typu SELECT, SHOW, EXPLAIN i DESCRIBE. Dla innych zapytań SQL mysql_query() zwraca TRUE lub FALSE informując czy zapytanie zakończyło się sukcesem czy też nie. Jeśli nie została zwrócona wartość FALSE to znaczy, że zapytanie było prawidłowe i może być wykonane przez serwer. Nie mówi natomiast nic o liczbie przetworzonych lub zwróconych wierszy. Jest również możliwe, że zapytanie zostanie wykonane poprawnie, nie przetwarzając lub zwracając żadnych wierszy.

Następujące zapytanie jest niepoprawne składniowo, dlatego mysql_query() zwróci FALSE:

Przykład #1 mysql_query()

<?php
$result = mysql_query("SELECT * WHERE 1=1")
    or die("Zapytanie niepoprawne");
?>

Następujące zapytanie jest niepoprawne semantycznie, jeżeli my_col nie jest kolumną w tabeli my_tbl, dlatego mysql_query() zwróci FALSE:

Przykład #2 mysql_query()

<?php
$result = mysql_query("SELECT kolumna FROM tabela")
    or die("Zapytanie niepoprawne");
?>

mysql_query() zwróci FALSE również wtedy, gdy nie będzie praw dostępu do tabel wyszczególnionych w zapytaniu.

Przyjmując, że zapytanie się powiodło, można użyć mysql_num_rows() by uzyskać informację o liczbie wierszy zwróconych w instrukcji SELECT, lub mysql_affected_rows() w celu uzyskania liczby wierszy przetworzonych przez instrukcje DELETE, INSERT, REPLACE i UPDATE.

Jedynie po operacjach SELECT, SHOW, EXPLAIN i DESCRIBE mysql_query() zwróci identyfikator wyniku, który można przekazać do funkcji mysql_fetch_array() lub innych funkcji operujących na tablicach wyników. Po wykonaniu operacji na wyniku, można zwolnić zasoby przez niego wykorzystywane wywołując mysql_free_result(). Po zakończeniu działania skryptu pamięć i tak będzie automatycznie zwolniona.

Patrz także: mysql_num_rows(),
mysql_affected_rows(),
mysql_unbuffered_query(),
mysql_free_result(),
mysql_fetch_array(),
mysql_fetch_row(),
mysql_fetch_assoc(),
mysql_result(),
mysql_select_db() i
mysql_connect().

mysql_ping
mysql_real_escape_string
MySQL Funkcje


Dodaje znaki unikowe w łańcuchu znaków do użycia w instrukcji SQL

mysql_query
mysql_result
MySQL Funkcje
PHP Manual

mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_string — Dodaje znaki unikowe w łańcuchu znaków do użycia w instrukcji SQL

Opis

string mysql_real_escape_string ( string $łańcuch_bez_znaków_unikowych [, resource $identyfikator_połączeniar ] )

Dodaje znaki unikowe do łańcucha_bez_znaków_unikowych, mając na uwadze aktualnie używany w połączeniu zestaw znaków by tak przygotowanego łańcucha można bezpiecznie użyc w funkcji mysql_query(). Jeśli dopisywane dane mają postać binarną wymagane jest użycie tej funkcji.

mysql_real_escape_string() wywołuje funkcję biblioteki MySQL mysql_real_escape_string, która dodaje lewe ukośniki (backslash) do następujących znaków: \x00, \n, \r, \, ', " and \x1a.

Użycie tej funkcji jest wymagane zawsze (poza kilkoma wyjątkami) przed wysłaniem zapytania do bazy danych aby zabezpieczyć dane.

Parametry

łańcuch_bez_znaków_unikowych

Łańcuch, do którego zostaną dodane znaki unikowe.

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca łańcuch ze znakami unikowymi lub FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia mysql_real_escape_string()

<?php
// Connect
$link = mysql_connect('host', 'uzytkownik', 'haslo')
    OR die(mysql_error());

// Zapytanie
$query = sprintf("SELECT * FROM uzytkownicy WHERE uzytkownik='%s' AND haslo='%s'",
            mysql_real_escape_string($uzytkownik),
            mysql_real_escape_string($haslo));
?>

Przykład #2 Przykład ataku SQL Injection

<?php
// Nie sprawdziliśmy zmiennej $_POST['password'], która może zawierać wszystko czego chciał użytkownik! Na przykład:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// Zapytanie pobierające pasujących użytkowników
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// Oznacza to, że zapytanie ma postać:
echo $query;
?>

Zapytanie wysłane do bazy danych:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

Zapytanie to pozwala zalogować się każdemu bez znajomości poprawnego hasła.

Notatki

Informacja:

Przed użyciem mysql_real_escape_string() należy otworzyć połączenie z MySQL, w przeciwnym razie zostanie wygenerowany błąd poziomu E_WARNING i zwrócona zostanie wartość FALSE. Jeśli identyfikator_połączenia nie został zdefiniowany, zostanie użyte ostatnie połączenie do serwera MySQL.

Informacja:

Jeśli opcja magic_quotes_gpc została włączona, najpierw na danych należy użyć stripslashes(). Użycie tej funkcji samej spowoduje, że do danych zostaną dodane podwójne znaki unikowe.

Informacja:

Jeśli funkcja ta nie zostanie użyta na danych, zapytanie będzie podatne na ataki SQL Injection Attacks.

Informacja: mysql_real_escape_string() nie dodaje znaków unikowych do % i _. Te maski są stosowane w zapytaniach MySQL w połączeniu z LIKE, GRANT lub REVOKE.

Zobacz też:

  • mysql_client_encoding() - Zwraca nazwę zestawu znaków
  • addslashes() - Quote string with slashes
  • stripslashes() - Un-quotes a quoted string
  • The magic_quotes_gpc directive
  • The magic_quotes_runtime directive

mysql_query
mysql_result
MySQL Funkcje


Zwraca dane wynikowe

mysql_real_escape_string
mysql_select_db
MySQL Funkcje
PHP Manual

mysql_result

(PHP 4, PHP 5)

mysql_result — Zwraca dane wynikowe

Opis

mixed mysql_result ( resource $wynik , int $wiersz [, mixed $ pole ] )

mysql_result() zwraca zawartość jednej komórki z wyniku. Jako argument pole można podać ofset, nazwę pola lub nazwę tabeli z nazwą pola (tabela.pole). Jeżeli nazwa kolumny została zastąpiona synonimem ('select foo as bar from...'), należy użyć tej nazwy zamiast rzeczywistej.

Przy pracy z dużymi wynikami, powinno się rozważyć użycie jednej z funkcji pobierających cały wiersz (patrz niżej). Jako, że funkcje te zwracają zawartość kilku komórek w jednym wywołaniu, są one ZNACZNIE szybsze niż mysql_result(). Podanie przesunięcia (offset) w argumencie pole jest znacznie szybsze niż podanie nazwy pola lub konstrukcji tabela.pole.

Wywołania mysql_result() nie powinny być mieszane z wywołaniami innych funkcji operujących na wyniku.

Zalecane wydajniejsze alternatywy:
mysql_fetch_row(),
mysql_fetch_array() i
mysql_fetch_object().

mysql_real_escape_string
mysql_select_db
MySQL Funkcje


Wybiera bazę MySQL

mysql_result
mysql_set_charset
MySQL Funkcje
PHP Manual

mysql_select_db

(PHP 4, PHP 5)

mysql_select_db — Wybiera bazę MySQL

Opis

bool mysql_select_db ( string $nazwa_bazy [, resource $identyfikator_połączenia ] )

Ustawia aktywną bazę danych na serwerze określonym przez podany identyfikator połączenia. Kolejne wywołania funkcji mysql_query() będą dotyczyły aktywnej bazy danych.

Parametry

nazwa_bazy

Nazwa wybieranej bazy danych.

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia mysql_select_db()

<?php

$link = mysql_connect('localhost', 'uzytkownik', 'haslo');
if (!$link) {
    die('Nie połączono : ' . mysql_error());
}

// Ustaw foo jako aktualną bazę danych
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Nie można ustawić foo : ' . mysql_error());
}
?>

Notatki

Informacja:

Dla zachowania zgodności z poprzednimi wersjami PHP możliwe jest używanie aliasów: mysql_selectdb()

Zobacz też:

  • mysql_connect() - Otwiera połączenie do serwera MySQL
  • mysql_pconnect() - Otwiera stałe połączenie z serwerem MySQL
  • mysql_query() - Wysyła zapytanie do serwera MySQL

mysql_result
mysql_set_charset
MySQL Funkcje


Sets the client character set

mysql_select_db
mysql_stat
MySQL Funkcje
PHP Manual

mysql_set_charset

(PHP 5 >= 5.2.3)

mysql_set_charset — Sets the client character set

Opis

bool mysql_set_charset ( string $charset [, resource $link_identifier ] )

Sets the default character set for the current connection.

Parametry

charset

A valid character set name.

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

This function requires MySQL 5.0.7 or later.

Informacja:

This is the preferred way to change the charset. Using mysql_query() to execute SET NAMES .. is not recommended.

Zobacz też:

  • mysql_client_encoding() - Zwraca nazwę zestawu znaków
  • » List of character sets that MySQL supports

mysql_select_db
mysql_stat
MySQL Funkcje


Pobiera aktualny stan systemu

mysql_set_charset
mysql_tablename
MySQL Funkcje
PHP Manual

mysql_stat

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat — Pobiera aktualny stan systemu

Opis

string mysql_stat ([ resource $identyfikator_połączenia ] )

mysql_stat() zwraca aktualny stan serwera.

Informacja:

mysql_stat() w chwili obecnej zwraca jedynie czas pracy serwera, liczbę wątków, zapytań, otwartych tabel, oraz liczbę zapytań na sekundę. Pełną listę parametrów opisujących stan można uzyskać wydając komendę SQL: SHOW STATUS.

Przykład #1 przykład użycia mysql_stat()

<?php
$link = mysql_connect('localhost', 'uzytkownik', 'haslo');
printf("%s\n", mysql_stat($link));
?>

Powyższy przykład da następujący wynik:

Uptime: 5380  Threads: 1  Questions: 1321299  Slow queries: 1  Opens: 26 Flush tables: 1  Open tables: 17  Queries per second avg: 245.595

mysql_set_charset
mysql_tablename
MySQL Funkcje


Zwraca nazwę tabeli

mysql_stat
mysql_thread_id
MySQL Funkcje
PHP Manual

mysql_tablename

(PHP 4, PHP 5)

mysql_tablename — Zwraca nazwę tabeli

Opis

string mysql_tablename ( resource $wynik , int $i )

mysql_tablename() przyjmuje jako parametry wskaźnik wyniku zwrócony przez mysql_list_tables() oraz indeks, zwracając nazwę tabeli. Liczbę tabel zwróconych w wyniku można określić używając funkcji mysql_num_rows().

Przykład #1 Przykład użycia mysql_tablename()

<?php
mysql_connect('localhost', 'uzytkownik', 'haslo');
$result = mysql_list_tables('baza');

for ($i = 0; $i < mysql_num_rows($result); $i++)
    printf ("Tabela: %s\n", mysql_tablename($result, $i));

mysql_free_result($result);
?>

Patrz także: mysql_list_tables().

mysql_stat
mysql_thread_id
MySQL Funkcje


Zwraca id bieżącego wątku

mysql_tablename
mysql_unbuffered_query
MySQL Funkcje
PHP Manual

mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id — Zwraca id bieżącego wątku

Opis

int mysql_thread_id ([ resource $identyfikator_połączenia ] )

mysql_thread_id() zwraca id bieżącego wątku. Jeśli połączenie zostało przerwane i nawiązane ponownie przy użyciu funkcji mysql_ping(), to id wątku się zmieni. Oznacza to, że nie powinno się pobierać id wątku i zapisywać do późniejszego użycia, lecz pobierać zawsze, gdy jest potrzebny.

Przykład #1 przykład użycia mysql_list_processes()

<?php
$link = mysql_connect('localhost', 'uzytkownik', 'haslo');
$thread_id = mysql_thread_id($link);
if ($thread_id){
    printf ("id bieżącego wątku: %d\n", $thread_id);
}
?>

Powyższy przykład da następujący wynik:

id bieżącego wątku: 73

Patrz także: mysql_ping(), mysql_list_processes().

mysql_tablename
mysql_unbuffered_query
MySQL Funkcje


Wysyła zapytanie do serwera MySQL nie pobierając i nie buforując wyniku

mysql_thread_id
Mysqli
MySQL Funkcje
PHP Manual

mysql_unbuffered_query

(PHP 4 >= 4.0.6, PHP 5)

mysql_unbuffered_query — Wysyła zapytanie do serwera MySQL nie pobierając i nie buforując wyniku

Opis

resource mysql_unbuffered_query ( string $zapytanie [, resource $identyfikator_połączenia ] )

mysql_unbuffered_query() wysyła zapytanie SQL do serwera MySQL, nie pobierając i nie buforując wyników zapytań, w przeciwieństwie do mysql_query(). To oszczędza znaczną ilość pamięci w zapytaniach SQL, które generują duże zbiory wynikowe. Można pracować na zbiorze wynikowym natychmiast po pobraniu pierwszego rekordu. Nie trzeba czekać, aż zapytanie SQL zostanie w bazie danych wykonane do końca. Aby posługiwać się funkcją mysql_unbuffered_query() z kilkoma połączeniami do baz danych, należy podawać opcjonalny parametr identyfikator_połączenia określający, które połączenie ma zostać wykorzystane.

Parametry

zapytanie

Zapytanie SQL do wykonania

Dane w zapytaniu powinny być poprzedzone poprawnymi znakami ucieczki.

identyfikator_połączenia

Połączenie MySQL. Jeśli identyfikator połączenia nie zostanie podany, użyte zostanie ostatnie połączenie otwarte przez mysql_connect(). Jeśli połączenie takie nie zostanie znalezione, funkcja spróbuje nawiązać połączenie tak, jakby wywołana została funkcja mysql_connect() bez argumentów. Jeśli żadne połączenie nie zostanie znalezione lub nawiązane, wygenerowany zostanie błąd poziomu E_WARNING.

Zwracane wartości

Dla wyrażeń SELECT, SHOW, DESCRIBE lub EXPLAIN, mysql_unbuffered_query() zwraca zasób w przypadku sukcesu lub FALSE gdy nastąpi niepowodzenie.

Dla innych typów wyrażeń SQL, UPDATE, DELETE, DROP, etc, mysql_unbuffered_query() zwróci TRUE w przypadku powodzenia lub FALSE gdy nastąpi błąd.

Notatki

Informacja:

Oprócz korzyści, funkcja mysql_unbuffered_query() wprowadza pewne ograniczenia: nie można użyć funkcji mysql_num_rows() i mysql_data_seek() na zbiorze wynikowym, zwróconym przez mysql_unbuffered_query(). Trzeba także pobrać wszystkie wiersze ze zbioru wynikowego niebuforowanego zapytania SQL przed wysłaniem kolejnego.

Zobacz też:

  • mysql_query() - Wysyła zapytanie do serwera MySQL

mysql_thread_id
Mysqli
MySQL Funkcje


MySQL Improved Extension

  • Wstęp
  • Overview
  • Quickstart
    • Dual procedural and object-oriented interface
    • Connections
    • Executing statements
    • Prepared Statements
    • Stored Procedures
    • Multiple Statements
    • API support for transactions
    • Metadata
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • The mysqli Extension and Persistent Connections
  • Stałe predefiniowane
  • Notes
  • The MySQLi Extension Function Summary
  • mysqli — The mysqli class
    • mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
    • mysqli::autocommit — Turns on or off auto-commiting database modifications
    • mysqli::change_user — Changes the user of the specified database connection
    • mysqli::character_set_name — Returns the default character set for the database connection
    • mysqli::$client_info — Returns the MySQL client version as a string
    • mysqli::$client_version — Get MySQL client info
    • mysqli::close — Closes a previously opened database connection
    • mysqli::commit — Commits the current transaction
    • mysqli::$connect_errno — Returns the error code from last connect call
    • mysqli::$connect_error — Returns a string description of the last connect error
    • mysqli::__construct — Open a new connection to the MySQL server
    • mysqli::debug — Performs debugging operations
    • mysqli::disable_reads_from_master — Disable reads from master
    • mysqli::dump_debug_info — Dump debugging information into the log
    • mysqli::$errno — Returns the error code for the most recent function call
    • mysqli::$error — Returns a string description of the last error
    • mysqli::$field_count — Returns the number of columns for the most recent query
    • mysqli::get_charset — Returns a character set object
    • mysqli::get_client_info — Returns the MySQL client version as a string
    • mysqli_get_client_stats — Returns client per-process statistics
    • mysqli::$client_version — Get MySQL client info
    • mysqli::get_connection_stats — Returns statistics about the client connection
    • mysqli::$host_info — Returns a string representing the type of connection used
    • mysqli::$protocol_version — Returns the version of the MySQL protocol used
    • mysqli::$server_info — Returns the version of the MySQL server
    • mysqli::$server_version — Returns the version of the MySQL server as an integer
    • mysqli::get_warnings — Get result of SHOW WARNINGS
    • mysqli::$info — Retrieves information about the most recently executed query
    • mysqli::init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()
    • mysqli::$insert_id — Returns the auto generated id used in the last query
    • mysqli::kill — Asks the server to kill a MySQL thread
    • mysqli::more_results — Check if there are any more query results from a multi query
    • mysqli::multi_query — Performs a query on the database
    • mysqli::next_result — Prepare next result from multi_query
    • mysqli::options — Set options
    • mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • mysqli::poll — Poll connections
    • mysqli::prepare — Prepare an SQL statement for execution
    • mysqli::query — Performs a query on the database
    • mysqli::real_connect — Opens a connection to a mysql server
    • mysqli::real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • mysqli::real_query — Execute an SQL query
    • mysqli::reap_async_query — Get result from async query
    • mysqli::refresh — Refreshes
    • mysqli::rollback — Rolls back current transaction
    • mysqli::rpl_query_type — Returns RPL query type
    • mysqli::select_db — Selects the default database for database queries
    • mysqli::send_query — Send the query and return
    • mysqli::set_charset — Sets the default client character set
    • mysqli::set_local_infile_default — Unsets user defined handler for load local infile command
    • mysqli::set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command
    • mysqli::$sqlstate — Returns the SQLSTATE error from previous MySQL operation
    • mysqli::ssl_set — Used for establishing secure connections using SSL
    • mysqli::stat — Gets the current system status
    • mysqli::stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
    • mysqli::store_result — Transfers a result set from the last query
    • mysqli::$thread_id — Returns the thread ID for the current connection
    • mysqli::thread_safe — Returns whether thread safety is given or not
    • mysqli::use_result — Initiate a result set retrieval
    • mysqli::$warning_count — Returns the number of warnings from the last query for the given link
  • mysqli_stmt — The mysqli_stmt class
    • mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • mysqli_stmt::attr_get — Used to get the current value of a statement attribute
    • mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
    • mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
    • mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
    • mysqli_stmt::close — Closes a prepared statement
    • mysqli_stmt::data_seek — Seeks to an arbitrary row in statement result set
    • mysqli_stmt::$errno — Returns the error code for the most recent statement call
    • mysqli_stmt::$error — Returns a string description for last statement error
    • mysqli_stmt::execute — Executes a prepared Query
    • mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
    • mysqli_stmt::$field_count — Returns the number of field in the given statement
    • mysqli_stmt::free_result — Frees stored result memory for the given statement handle
    • mysqli_stmt::get_result — Gets a result set from a prepared statement
    • mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
    • mysqli_stmt::$insert_id — Get the ID generated from the previous INSERT operation
    • mysqli_stmt::$num_rows — Return the number of rows in statements result set
    • mysqli_stmt::$param_count — Returns the number of parameter for the given statement
    • mysqli_stmt::prepare — Prepare an SQL statement for execution
    • mysqli_stmt::reset — Resets a prepared statement
    • mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
    • mysqli_stmt::send_long_data — Send data in blocks
    • mysqli_stmt::$sqlstate — Returns SQLSTATE error from previous statement operation
    • mysqli_stmt::store_result — Transfers a result set from a prepared statement
  • mysqli_result — The mysqli_result class
    • mysqli_result::$current_field — Get current field offset of a result pointer
    • mysqli_result::data_seek — Adjusts the result pointer to an arbitary row in the result
    • mysqli_result::fetch_all — Fetches all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array — Fetch a result row as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc — Fetch a result row as an associative array
    • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
    • mysqli_result::fetch_field — Returns the next field in the result set
    • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_object — Returns the current row of a result set as an object
    • mysqli_result::fetch_row — Get a result row as an enumerated array
    • mysqli_result::$field_count — Get the number of fields in a result
    • mysqli_result::field_seek — Set result pointer to a specified field offset
    • mysqli_result::free — Frees the memory associated with a result
    • mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
    • mysqli_result::$num_rows — Gets the number of rows in a result
  • mysqli_driver — The mysqli_driver class
    • mysqli_driver::embedded_server_end — Stop embedded server
    • mysqli_driver::embedded_server_start — Initialize and start embedded server
  • mysqli_warning — The mysqli_warning class
    • mysqli_warning::__construct — The __construct purpose
    • mysqli_warning::next — The next purpose
  • Aliases and deprecated Mysqli Funkcje
    • mysqli_bind_param — Alias for mysqli_stmt_bind_param
    • mysqli_bind_result — Alias for mysqli_stmt_bind_result
    • mysqli_client_encoding — Alias of mysqli_character_set_name
    • mysqli_connect — Alias dla mysqli::__construct
    • mysqli_disable_rpl_parse — Disable RPL parse
    • mysqli_enable_reads_from_master — Enable reads from master
    • mysqli_enable_rpl_parse — Enable RPL parse
    • mysqli_escape_string — Alias dla mysqli_real_escape_string
    • mysqli_execute — Alias for mysqli_stmt_execute
    • mysqli_fetch — Alias for mysqli_stmt_fetch
    • mysqli_get_cache_stats — Returns client Zval cache statistics
    • mysqli_get_metadata — Alias for mysqli_stmt_result_metadata
    • mysqli_master_query — Enforce execution of a query on the master in a master/slave setup
    • mysqli_param_count — Alias for mysqli_stmt_param_count
    • mysqli_report — Enables or disables internal report functions
    • mysqli_rpl_parse_enabled — Check if RPL parse is enabled
    • mysqli_rpl_probe — RPL probe
    • mysqli_send_long_data — Alias for mysqli_stmt_send_long_data
    • mysqli_set_opt — Alias of mysqli_options
    • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup
mysql_unbuffered_query
Wstęp
MySQL


Wstęp

The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above. More information about the MySQL Database server can be found at » http://www.mysql.com/

An overview of software available for using MySQL from PHP can be found at Overview

Documentation for MySQL can be found at » http://dev.mysql.com/doc/.

Parts of this documentation included from MySQL manual with permissions of Oracle Corporation.

Examples

All examples in the mysqli documentation use the world database. The world database can be found at » http://downloads.mysql.com/docs/world.sql.gz

Mysqli
Overview
Mysqli


Overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two the latter is usually the preferred interface, as it is more modern and leads to better organised code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term "driver" is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions, such as the mysqli extension, and the mysql extension, are implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

What are the main PHP API offerings for using MySQL?

There are three main API options when considering connecting to a MySQL database server:

  • PHP's MySQL Extension

  • PHP's mysqli Extension

  • PHP Data Objects (PDO)

Each has its own advantages and disadvantages. The following discussion aims to give a brief introduction to the key aspects of each API.

What is PHP's MySQL Extension?

This is the original extension designed to allow you to develop PHP applications that interact with a MySQL database. The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4.1.3. This extension can be used with versions of MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available.

Informacja:

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead.

The mysql extension source code is located in the PHP extension directory ext/mysql.

For further information on the mysql extension, see Mysql.

What is PHP's mysqli Extension?

The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface

  • Support for Prepared Statements

  • Support for Multiple Statements

  • Support for Transactions

  • Enhanced debugging capabilities

  • Embedded server support

Informacja:

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use this extension.

As well as the object-oriented interface the extension also provides a procedural interface.

The mysqli extension is built using the PHP extension framework, its source code is located in the directory ext/mysqli.

For further information on the mysqli extension, see Mysqli.

What is PDO?

PHP Data Objects, or PDO, is a database abstraction layer specifically for PHP applications. PDO provides a consistent API for your PHP application regardless of the type of database server your application will connect to. In theory, if you are using the PDO API, you could switch the database server you used, from say Firebird to MySQL, and only need to make minor changes to your PHP code.

Other examples of database abstraction layers include JDBC for Java applications and DBI for Perl.

While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements.

PDO is implemented using the PHP extension framework, its source code is located in the directory ext/pdo.

For further information on PDO, see the PDO.

What is the PDO MYSQL driver?

The PDO MYSQL driver is not an API as such, at least from the PHP programmer's perspective. In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific functionality. The programmer still calls the PDO API, but PDO uses the PDO MYSQL driver to carry out communication with the MySQL server.

The PDO MYSQL driver is one of several available PDO drivers. Other PDO drivers available include those for the Firebird and PostgreSQL database servers.

The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is located in the directory ext/pdo_mysql. It does not expose an API to the PHP programmer.

For further information on the PDO MYSQL driver, see MySQL (PDO).

What is PHP's MySQL Native Driver?

In order to communicate with the MySQL database server the mysql extension, mysqli and the PDO MYSQL driver each use a low-level library that implements the required protocol. In the past, the only available library was the MySQL Client Library, otherwise known as libmysql.

However, the interface presented by libmysql was not optimized for communication with PHP applications, as libmysql was originally designed with C applications in mind. For this reason the MySQL Native Driver, mysqlnd, was developed as an alternative to libmysql for PHP applications.

The mysql extension, the mysqli extension and the PDO MySQL driver can each be individually configured to use either libmysql or mysqlnd. As mysqlnd is designed specifically to be utilised in the PHP system it has numerous memory and speed enhancements over libmysql. You are strongly encouraged to take advantage of these improvements.

Informacja:

The MySQL Native Driver can only be used with MySQL server versions 4.1.3 and later.

The MySQL Native Driver is implemented using the PHP extension framework. The source code is located in ext/mysqlnd. It does not expose an API to the PHP programmer.

Comparison of Features

The following table compares the functionality of the three main methods of connecting to MySQL from PHP:

 | PHP's mysqli Extension | PDO (Using PDO MySQL Driver and MySQL Native Driver) | PHP's MySQL Extension
PHP version introduced | 5.0 | 5.0 | Prior to 3.0
Included with PHP 5.x | yes | yes | Yes
MySQL development status | Active development | Active development as of PHP 5.3 | Maintenance only
Recommended by MySQL for new projects | Yes - preferred option | Yes | No
API supports Charsets | Yes | Yes | No
API supports server-side Prepared Statements | Yes | Yes | No
API supports client-side Prepared Statements | No | Yes | No
API supports Stored Procedures | Yes | Yes | No
API supports Multiple Statements | Yes | Most | No
Supports all MySQL 4.1+ functionality | Yes | Most | No
Wstęp
Quickstart
Mysqli


Quickstart

Spis treści

  • Dual procedural and object-oriented interface
  • Connections
  • Executing statements
  • Prepared Statements
  • Stored Procedures
  • Multiple Statements
  • API support for transactions
  • Metadata

This quickstart guide shall help choosing an PHP MYSQL API and help getting familiar with it.

The quickstart gives an overview on the mysqli extension. Code examples are given for all major aspects of the API. Database concepts are explained to the degree needed for presenting MySQL specifics.

Familarity with the PHP programming language, the SQL language and basic knowledge of the MySQL server is assumed.

Overview
Dual procedural and object-oriented interface
Mysqli


Dual procedural and object-oriented interface

The mysqli extension features a dual interface. It supports the procedural and object-oriented programming paradigma.

Users stepping up from the old mysql extension may prefer the procedural interface. The procedural interface is similar to that of the mysql extension. In many cases function names differ only by prefix. Some mysqli functions take a connection handle as their first argument, whereas matching functions in the old mysql interface take it as an optional last argument.

Przykład #1 Easy migration from the old mysql extension

<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT 'Please, do not use ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysql = mysql_connect("localhost", "root", "");
mysql_select_db("test");
$res = mysql_query("SELECT 'the mysql extension for new developments.' AS _msg FROM DUAL", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];
?>

Powyższy przykład wyświetli:

Please, do not use the mysql extension for new developments.

The object-oriented interface

In addition to the classical procedural interface, users can choose to use the object-oriented interface. The documentation is organized using the object-oriented interface. The object-oriented interface shows functions grouped by their purpose, making it easier to get started. The reference section gives examples for both syntax variants.

There are no significant performance differences between the two interfaces. Users can base their choice on personal preference.

Przykład #2 Object-oriented and procedural interface

<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
if (mysqli_connect_errno($mysqli))
 echo "Failed to connect to MySQL: " . mysqli_connect_error();

$res = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: " . $mysqli->connect_error;

$res = $mysqli->query("SELECT 'choices to please everybody,' AS _msg FROM DUAL");
$row = $res->fetch_assoc();
echo $row['_msg'];
?>

Powyższy przykład wyświetli:

A world full of choices to please everybody.

The object oriented interface is used for the quickstart because the reference section is organized that way.

Mixing styles

It is possible to switch between styles at any time. Mixing both styles is not recommended for code clarity and coding style reasons.

Przykład #3 Bad coding style

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: " . $mysqli->connect_error;

$res = mysqli_query($mysqli, "SELECT 'Possible but bad style.' AS _msg FROM DUAL");
if (!$res)
 echo "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error;

if ($row = $res->fetch_assoc())
 echo $row['_msg'];
?>

Powyższy przykład wyświetli:

Possible but bad style.

See also

  • mysqli::__construct()
  • mysqli::query()
  • mysqli_result::fetch_assoc()
  • $mysqli::connect_errno
  • $mysqli::connect_error
  • $mysqli::errno
  • $mysqli::error
  • The MySQLi Extension Function Summary

Quickstart
Connections
Quickstart


Connections

The MySQL server supports the use of different transport layers for connections. Connections use TCP/IP, Unix domain sockets or Windows named pipes.

The hostname localhost has a special meaning. It is bound to the use of Unix domain sockets. It is not possible to open a TCP/IP connection using the hostname localhost you must use 127.0.0.1 instead.

Przykład #1 Special meaning of localhost

<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
?>

Powyższy przykład wyświetli:

Localhost via UNIX socket
127.0.0.1 via TCP/IP

Connection parameter defaults

Depending on the connection function used, assorted parameters can be omitted. If a parameter is not given the extension attempts to use defaults values set in the PHP configuration file.

Przykład #2 Setting defaults

mysqli.default_host=192.168.2.27
mysqli.default_user=root
mysqli.default_pw=""
mysqli.default_port=3306
mysqli.default_socket=/tmp/mysql.sock

The resulting parameter values are then passed to the client library used by the extension. If the client library detects empty or unset parameters, it may default to library built-in values.

Built-in connection library defaults

If the host value is unset or empty, the client library will default to a Unix socket connection on localhost. If socket is unset or empty and a Unix socket connection is requested, a connection to the default socket on /tmp/mysql.sock is attempted.

On Windows systems the host name . is interpreted by the client library as an attempt to open a Windows named pipe based connection. In this case the socket parameter is interpreted as the pipes name. If not given or empty, the socket (here: pipe name) defaults to \\.\pipe\MySQL.

If neither a Unix domain socket based not a Windows named pipe based connection is to be bestablished and the port parameter value is unset, the library will default to port 3306.

The mysqlnd library and the MySQL Client Library (libmysql) implement the same logic for determining defaults.

Connection options

Various connection options are available, for example, to set init commands which are executed upon connect or, for requesting use of a certain charset. Connection options must be set before a network connection is established.

For setting a connection option the connect operation has to be
performed in three steps: creating a connection handle with
mysqli_init(), setting the requested options using
mysqli_options() and establishing the network
connection with mysqli_real_connect().

Connection pooling

The mysqli extension supports persistent database connections, which are a special kind of pooled connections. By default every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. A persistent connection is not. Instead it is put into a pool for later reuse, if a connection to the same server using the same username, password, socket, port and default database is opened. Reuse saves connection overhead.

Every PHP process is using its own mysqli connection pool. Depending on the web server deployment model a PHP process may serve one or multiple requests. Therefore, a pooled connection may be used by one or more scripts subsequently.

Persistent connection

If no unused persistent connection for a given combination of host, username, password, socket, port and default database can be found in the connection pool, mysqli opens a new connection. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links. The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent. Please note, that the web server may spawn many PHP processes.

A common complain about persistent connections is that their state is not reset before reuse. For example, open, unfinished transactions are not automatically rolled back. But also, authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. This may be seen as an unwanted side-effect. On the contrary, the name persistent may be understood as a promise that the state is persisted.

The mysqli extension supports both interpretations of a persistent connection: state persisted and state reset before reuse. The default is reset. Before a persistent connection is reused, the mysqli extension implicitly calls mysqli_change_user() to reset the state. The persistent connection appears to the user as if it was just opened. No artefacts from previous usages are visible.

The mysqli_change_user() function is an expensive operation. For best performance, users may want to recompile the extension with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT being set.

It is left to the user to choose between safe behaviour and best performance. Both are valid optimization goals. For ease of use, the safe behaviour has been made the default at the expense of maximum performance. Please, run your own benchmarks to measure the performance impact for your work load.

See also

  • mysqli::__construct()
  • mysqli::init()
  • mysqli::options()
  • mysqli::real_connect()
  • mysqli::change_user()
  • $mysqli::host_info
  • MySQLi Configuration Options
  • Persistent Database Connections

Dual procedural and object-oriented interface
Executing statements
Quickstart


Executing statements

Statements can be executed by help of the
mysqli_query(), mysqli_real_query()
and mysqli_multi_query() function.
The mysqli_query() function is the most
commonly used one. It combines executing statement and doing a
buffered fetch of its result set, if any, in one call.
Calling mysqli_query() is identical to
calling mysqli_real_query()
followed by mysqli_store_result().

The mysqli_multi_query() function is used with Multiple Statements and is described elsewhere.

Przykład #1 Bad coding style

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
?>

Buffered result sets

After statement execution results can be retrieved at once to be buffered by the client or by read row by row. Client-side result set buffering allows the server to free resources associated with the statement results as early as possible. Generally speaking, clients are slow consuming result sets. Therefore, it is recommended to use buffered result sets. mysqli_query() combines statement execution and result set buffering.

PHP applications can navigate freely through buffered results. Nagivation is fast because the result sets is hold in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.

Przykład #2 Navigation through buffered results

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");

echo "Reverse order...\n";
for ($row_no = $res->num_rows - 1; $row_no >= 0; $row_no--) {
  $res->data_seek($row_no);
  $row = $res->fetch_assoc();
  echo " id = " . $row['id'] . "\n";
}

echo "Result set order...\n";
$res->data_seek(0);
while ($row = $res->fetch_assoc())
 echo " id = " . $row['id'] . "\n";
?>

Powyższy przykład wyświetli:

Reverse order...
 id = 3
 id = 2
 id = 1
Result set order...
 id = 1
 id = 2
 id = 3

Unbuffered result sets

If client memory is a short resource and freeing server resources as early as possible to keep server load low is not needed, unbuffered results can be used. Scrolling through unbuffered results is not possible before all rows have been read.

Przykład #3 Navigation through buffered results

<?php
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();

echo "Result set order...\n";
while ($row = $res->fetch_assoc())
 echo " id = " . $row['id'] . "\n";
?>

Result set values data types

The mysqli_query(), mysqli_real_query() and mysqli_multi_query() functions are used to execute non-prepared statements. At the level of the MySQL Client Server Protocol the command COM_QUERY and the text protocol are used for statement execution. With the text protocol, the MySQL server converts all data of a result sets into strings before sending. This conversion is done regardless of the SQL result set column data type. The mysql client libraries receive all column values as strings. No further client-side casting is done to convert columns back to their native types. Instead, all values are provided as PHP strings.

Przykład #4 Text protocol returns strings by default

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

Powyższy przykład wyświetli:

id = 1 (string)
label = a (string)

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd libary. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

Przykład #5 Native data types with mysqlnd and conneciton option

<?php
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$mysqli->real_connect("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

Powyższy przykład wyświetli:

id = 1 (string)
label = a (string)

See also

  • mysqli::__construct()
  • mysqli::init()
  • mysqli::options()
  • mysqli::real_connect()
  • mysqli::query()
  • mysqli::multi_query()
  • mysqli::use_result()
  • mysqli::store_result()
  • mysqli_result::free()

Connections
Prepared Statements
Quickstart


Prepared Statements

The MySQL database supports prepared statements. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency.

Basic workflow

The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is send to the database server. The server performs a syntax check and initializes server internal resources for later use.

The MySQL server supports using anonymous, positional placeholder with ?.

Przykład #1 First stage: prepare

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)")))
 echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
?>

Prepare is followed by execute. During execute the client binds parameter values and sends them to the server. The server creates a statement from the statement template and the bound values to execute it using the previously created internal resources.

Przykład #2 Second stage: bind and execute

<?php
/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id))
 echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;

if (!$stmt->execute())
 echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
?>

Repeated execution

A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and send to the server. The statement is not parsed again. The statement template is not transferred to the server again.

Przykład #3 INSERT prepared once, executed multiple times

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)")))
 echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;

/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id))
 echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;

if (!$stmt->execute())
 echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;

/* Prepared statement: repeated execution, only data transferred from client to server */
for ($id = 2; $id < 5; $id++)
  if (!$stmt->execute())
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;

/* explicit close recommended */
$stmt->close();

/* Non-prepared statement */
$res = $mysqli->query("SELECT id FROM test");
var_dump($res->fetch_all());
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [3]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

Every prepared statement occupies server resources. Statements should be closed explicitly immediately after use. If not done explicitly, the statement will be closed when the statement handle is freed by PHP.

Using a prepared statement is not always the most efficient way of executing a statement. A prepared statement executed only once causes more client-server round-trips than a non-prepared statement. This is why the SELECT is not run as a prepared statement above.

Also, consider the use of the MySQL multi-INSERT SQL syntax for INSERTs. For the example, belows multi-INSERT requires less round-trips between the server and client than the prepared statement shown above.

Przykład #4 Less round trips using multi-INSERT SQL

<?php
if (!$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3), (4)"))
 echo "Multi-INSERT failed: (" . $mysqli->errno . ") " . $mysqli->error;
?>

Result set values data types

The MySQL Client Server Protocol defines a different data transfer protocol for prepared statements and non-prepared statements. Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. The client libraries do not receive strings only. Instead, they will receive binary data and try to convert the values into appropriate PHP data types. For example, results from an SQL INT column will be provided as PHP integer variables.

Przykład #5 Native datatypes

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

Powyższy przykład wyświetli:

id = 1 (integer)
label = a (string)

This behaviour differes from non-prepared statements. By default, non-prepared statements return all results as strings. This default can be changed using a connection option. If the connection option is used, there are no differences.

Fetching results using bound variables

Results from prepared statements can either be retrieved by binding output variables or by requesting a mysqli_result object.

Output variables must be bound after statement execution. One variable must be bound for every column of the statements result set.

Przykład #6 Output variable binding

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test")))
 echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$stmt->execute())
  echo "Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;

$out_id = NULL;
$out_label = NULL;
if (!$stmt->bind_result($out_id, $out_label))
 echo "Binding output parameters failed: (" . $stmt->errno . ") " . $stmt->error;

while ($stmt->fetch())
 printf("id = %s (%s), label = %s (%s)\n",
   $out_id, gettype($out_id),
   $out_label, gettype($out_label));
?>

Powyższy przykład wyświetli:

id = 1 (integer), label = a (string)

Prepared statements return unbuffered result sets by default. The results of the statement are not implicitly fetched and transferred from the server to the client for client-side buffering. The result set takes server resources until all results have been fetched by the client. Thus it is recommended to consume results timely. If a client fails to fetch all results or the client closes the statement before having fetched all data, the data has to be fetched implicitly by mysqli.

It is also possible to buffer the results of a prepared statement using mysqli_stmt_store_result().

Fetching results using mysqli_result interface

Instead of using bound results, results can also be retrieved through the mysqli_result interface. mysqli_stmt_get_result() returns a buffered result set.

Przykład #7 Using mysqli_result to fetch results

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test ORDER BY id ASC")))
 echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$stmt->execute())
  echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;

if (!($res = $stmt->get_result()))
 echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;

var_dump($res->fetch_all());
?>

Powyższy przykład wyświetli:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    string(1) "a"
  }
}

Using the mysqli_result interface this has the additional benefit of flexible client-side result set navigation.

Przykład #8 Buffered result set for flexible read out

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a'), (2, 'b'), (3, 'c')"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test")))
 echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$stmt->execute())
  echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;

if (!($res = $stmt->get_result()))
 echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;

for ($row_no = ($res->num_rows - 1); $row_no >= 0; $row_no--) {
  $res->data_seek($row_no);
  var_dump($res->fetch_assoc());
}
$res->close();
?>

Powyższy przykład wyświetli:

array(2) {
  ["id"]=>
  int(3)
  ["label"]=>
  string(1) "c"
}
array(2) {
  ["id"]=>
  int(2)
  ["label"]=>
  string(1) "b"
}
array(2) {
  ["id"]=>
  int(1)
  ["label"]=>
  string(1) "a"
}

Escaping and SQL injection

Bound variables will be escaped automatically by the server. The server inserts their escaped values at the appropriate places into the statement template before execution. Users must hint the server about the type of the bound variable for appropriate conversion, see mysqli_stmt_bind_param().

The automatic escaping of values within the server is sometimes considered as a security feature to prevent SQL injection. The same degree of security can be achieved with non-prepared statements, if input values are escaped correctly.

Client-side prepared statement emulation

The API does not include a client-side prepared statement emulation.

Quick prepared - non-prepared statement comparison

The below table gives a quick comparison on server-side prepared and non-prepared statements.

 | Prepared Statement | Non-prepared statement
Client-server round trips, SELECT, single execution | 2 | 1
Statement string transferred from client to server | 1 | 1
Client-server round trips, SELECT, repeated (n) execution | 1 + n | n
Statement string transferred from client to server | 1 template, n times bound parameter, if any | n times together with parameter, if any
Input parameter binding API | yes, automatic input escaping | no, manual input escaping
Output variable binding API | yes | no
Supports use of mysqli_result API | yes, use mysqli_stmt_get_result() | yes
Buffered result sets | yes, use mysqli_stmt_get_result()() or binding with mysqli_stmt_store_result() | yes, default of mysqli_query()
Unbuffered result sets | yes, use output binding API | yes, use mysqli_real_query() with mysqli_use_result()
MySQL Client Server protocol data transfer flavour | binary protocol | text protocol
Result set values SQL data types | preserved when fetching | converted to string or preserved when fetching
Supports all SQL statements | Recent MySQL versions support most but not all | yes

See also

  • mysqli::__construct()
  • mysqli::query()
  • mysqli::prepare()
  • mysqli_stmt::prepare()
  • mysqli_stmt::execute()
  • mysqli_stmt::bind_param()
  • mysqli_stmt::bind_result()

Executing statements
Stored Procedures
Quickstart


Stored Procedures

The MySQL database supports stored procedures. A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The CALL SQL statement is used to execute a stored procedure.

Parameter

Stored procedures can have IN, INOUT and OUT parameters, depending on the MySQL version. The mysqli interface has no special notion for the different kinds of parameters.

IN parameter

Input parameters are provided with the CALL statement. Please, make sure values are escaped correctly.

Przykład #1 Calling a stored procedure

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;"))
   echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$mysqli->query("CALL p(1)"))
 echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!($res = $mysqli->query("SELECT id FROM test")))
 echo "SELECT failed: (" . $mysqli->errno . ") " . $mysqli->error;

var_dump($res->fetch_assoc());
?>

Powyższy przykład wyświetli:

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

INOUT/OUT parameter

The values of INOUT/OUT parameters are accessed using session variables.

Przykład #2 Using session variables

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;'))
   echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$mysqli->query("SET @msg = ''") ||
    !$mysqli->query("CALL p(@msg)"))
 echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!($res = $mysqli->query("SELECT @msg as _p_out")))
 echo "Fetch failed: (" . $mysqli->errno . ") " . $mysqli->error;

$row = $res->fetch_assoc();
echo $row['_p_out'];
?>

Powyższy przykład wyświetli:

Hi!

Application and framework developers may be able to provide a more convenient API using a mix of session variables and databased catalog inspection. However, please note the possible performance impact of a custom solution based on catalog inspection.

Handling result sets

Stored procedures can return result sets. Result sets returned from a stored procedure cannot be fetched correctly using mysqli_query(). The mysqli_query() function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli_query() to fail returning the user expected result sets.

Result sets returned from a stored procedure are fetched using mysqli_real_query() or mysqli_multi_query(). Both functions allow fetching any number of result sets returned by a statement, such as CALL. Failing to fetch all result sets returned by a stored procedure causes an error.

Przykład #3 Fetching results from stored procedures

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;'))
   echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$mysqli->multi_query("CALL p()"))
   echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;

do {
 if ($res = $mysqli->store_result()) {
   printf("---\n");
   var_dump($res->fetch_all());
   $res->free();
 } else {
   if ($mysqli->errno)
     echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error;
 }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

Powyższy przykład wyświetli:

---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
}
---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

Use of prepared statements

No special handling is required when using the prepared statement interface for fetching results from the same stored procedure as above. The prepared statement and non-prepared statement interfaces are similar. Please note, that not every MYSQL server version may support preparing the CALL SQL statement.

Przykład #4 Stored Procedures and Prepared Statements

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;'))
   echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!($stmt = $mysqli->prepare("CALL p()")))
   echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$stmt->execute())
  echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;

do {
 if ($res = $stmt->get_result()) {
   printf("---\n");
   var_dump(mysqli_fetch_all($res));
   mysqli_free_result($res);
 } else {
   if ($stmt->errno)
     echo "Store failed: (" . $stmt->errno . ") " . $stmt->error;
 }
} while ($stmt->more_results() && $stmt->next_result());
?>

Of course, use of the bind API for fetching is supported as well.

Przykład #5 Stored Procedures and Prepared Statements using bind API

<?php
if (!($stmt = $mysqli->prepare("CALL p()")))
   echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;

if (!$stmt->execute())
  echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;

do {

 $id_out = NULL;
 if (!$stmt->bind_result($id_out))
   echo "Bind failed: (" . $stmt->errno . ") " . $stmt->error;

 while ($stmt->fetch())
   echo "id = $id_out\n";
} while ($stmt->more_results() && $stmt->next_result());
?>

See also

  • mysqli::query()
  • mysqli::multi_query()
  • mysqli_result::next-result()
  • mysqli_result::more-results()

Prepared Statements
Multiple Statements
Quickstart


Multiple Statements

MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.

Multiple statements or multi queries must be executed with mysqli_multi_query(). The individual statements of the statement string are seperated by semicolon. Then, all result sets returned by the executed statements must be fetched.

The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.

Przykład #1 Multiple Statements

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)"))
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql))
 echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;

do {
 if ($res = $mysqli->store_result()) {
  var_dump($res->fetch_all(MYSQLI_ASSOC));
  $res->free();
 }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

Powyższy przykład wyświetli:

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

Security considerations

The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.

Przykład #2 SQL ijnection

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$res = $mysqli->query("SELECT 1; DROP TABLE mysql.user");
if (!$res)
  echo "Error executing query: (" . $mysqli->errno . ") " . $mysqli->error;
?>

Powyższy przykład wyświetli:

Error executing query: (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DROP TABLE mysq.user' at line 1

Prepared statements

Use of the multiple statement with prepared statements is not supported.

See also

  • mysqli::query()
  • mysqli::multi_query()
  • mysqli_result::next-result()
  • mysqli_result::more-results()

Stored Procedures
API support for transactions
Quickstart


API support for transactions

The MySQL server supports transactions depending on the storage engine used. Since MySQL [TODO]x.y[TODO] the default storage engine is InnoDB. InnoDB has full ACID transaction support.

Transactions can either be controlled using SQL or API calls. It is recommended to use API calls for enabling and disabling the auto commit mode and for comitting and rolling back transactions.

Przykład #1 Setting auto commit mode with SQL and through the API

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

/* Recommended: using API to control transactional settings */
$mysqli->autocommit(false);

/* Won't be monitored and recognized by the replication and the load balancing plugin */
if (!$mysqli->query('SET AUTOCOMMIT = 0'))
  echo "Query failed: (" . $mysqli->errno . ") " . $mysqli->error;
?>

Optional feature packages, such as the replication and load balancing plugin, can easily monitor API calls. The replication plugin offers transaction aware load balancing, if transactions are controlled with API calls. Transaction aware load balancing is not available if SQL statements are used for setting auto commit mode, committing or rolling back a transaction.

Przykład #2 Commit and rollback

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->autocommit(false);

$mysqli->query("INSERT INTO test(id) VALUES (1)");
$mysqli->rollback();

$mysqli->query("INSERT INTO test(id) VALUES (2)");
$mysqli->commit();
?>

Please note, that the MySQL server cannot roll back all statements. Some statements cause am implicit commit.

See also

  • mysqli::autocommit()
  • mysqli_result::commit()
  • mysqli_result::rollback()

Multiple Statements
Metadata
Quickstart


Metadata

A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata send by MySQL is accessible through the mysqli interface. The extension performs no or negliable changes to the information it receives. Differences between MySQL server versions are not aligned.

Meta data is access through the mysqli_result interface.

Przykład #1 Accessing result set meta data

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno)
 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;

$res = $mysqli->query("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
var_dump($res->fetch_fields());
?>

Powyższy przykład wyświetli:

array(2) {
  [0]=>
  object(stdClass)#3 (13) {
    ["name"]=>
    string(4) "_one"
    ["orgname"]=>
    string(0) ""
    ["table"]=>
    string(0) ""
    ["orgtable"]=>
    string(0) ""
    ["def"]=>
    string(0) ""
    ["db"]=>
    string(0) ""
    ["catalog"]=>
    string(3) "def"
    ["max_length"]=>
    int(1)
    ["length"]=>
    int(1)
    ["charsetnr"]=>
    int(63)
    ["flags"]=>
    int(32897)
    ["type"]=>
    int(8)
    ["decimals"]=>
    int(0)
  }
  [1]=>
  object(stdClass)#4 (13) {
    ["name"]=>
    string(4) "_two"
    ["orgname"]=>
    string(0) ""
    ["table"]=>
    string(0) ""
    ["orgtable"]=>
    string(0) ""
    ["def"]=>
    string(0) ""
    ["db"]=>
    string(0) ""
    ["catalog"]=>
    string(3) "def"
    ["max_length"]=>
    int(5)
    ["length"]=>
    int(5)
    ["charsetnr"]=>
    int(8)
    ["flags"]=>
    int(1)
    ["type"]=>
    int(253)
    ["decimals"]=>
    int(31)
  }
}

Prepared statements

Meta data of result sets created using prepared statements are accessed the same way. A suitable mysqli_result handle is returned by mysqli_stmt_result_metadata().

Przykład #2 Prepared statements metadata

<?php
$stmt = $mysqli->prepare("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
$stmt->execute();
$res = $stmt->result_metadata();
var_dump($res->fetch_fields());
?>

See also

  • mysqli::query()
  • mysqli_result::fetch_fields()

API support for transactions
Instalacja/Konfiguracja
Quickstart


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Metadata
Wymagania
Mysqli


Wymagania

In order to have these functions available, you must compile PHP with support for the mysqli extension.

Informacja:

The mysqli extension is designed to work with MySQL version 4.1.13 or newer, or 5.0.7 or newer. For previous versions, please see the MySQL extension documentation.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

By zainstalować rozszerzenie mysqli dla PHP należy użyć opcji konfiguracyjnej --with-mysqli=mysql_config_path/mysql_config , gdzie mysql_config_path wskazuje na ścieżkę dostępu do programu mysql_config, który występuje w wersjach MySQL powyżej 4.1.

Jeśli chcesz zainstalować rozszerzenie mysql razem z rozszerzeniem mysqli musisz użyć tej samej biblioteki klienckiej w celu uniknięcia konfliktów.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracyjne MySQLi
Nazwa | Wartość domyślna | Możliwość zmian | Rejestr zmian
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | Dostępna od PHP 5.3.0.
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | Dostępna od PHP 5.3.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Dostępna od PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Dostępna od PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Dostępna od PHP 5.0.0.
mysqli.default_host | NULL | PHP_INI_ALL | Dostępna od PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Dostępna od PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Dostępna od PHP 5.0.0.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Dostępna od PHP 4.3.5.
mysqli.allow_local_infile | "1" | PHP_INI_SYSTEM | Dostępna od PHP 5.2.4.
mysqli.cache_size | "2000" | PHP_INI_SYSTEM | Dostępna od PHP 5.3.0.

Aby dowiedzieć się więcej o powyższych definicjach i stałych PHP_INI_*, zobacz rozdział poświęcony zmianom konfiguracji.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

mysqli.allow_persistent integer

Włącza możliwość tworzenia połączeń stałych za pomocą mysqli_connect().

mysqli.max_persistent integer

Maksymalna liczba połączeń stałych, które można utworzyć. Wartość 0 ustawia nieograniczoną liczbę połączeń stałych.

mysqli.max_links integer

Maksymalna liczba połączeń MySQL na proces.

mysqli.default_port string

Domyślny port TCP używany podczas połączenia do serwera bazy danych, jeśli nie podano innego portu. Jeżeli ta wartość nie zostanie ustawiona, numer portu zostanie pobrany ze zmiennej środowiskowej MYSQL_TCP_PORT, wpisu mysql-tcp w pliku /etc/services lub stałej MYSQL_PORT podanej podczas kompilacji (dokładnie w takim porządku). Systemy Windows używają tylko stałej MYSQL_PORT

mysqli.default_socket string

Domyślna nazwa gniazda używanego podczas połączenia do lokalnego serwera bazy danych, jeśli nie została podana inna wartość.

mysqli.default_host string

Domyślna nazwa hosta używana podczas połączenia do serwera bazy danych, jeśli nie została podana inna wartość. Nie działa w trybie bezpiecznym.

mysqli.default_user string

Domyślna nazwa użytkownika używana podczas połączenia do serwera bazy danych, jeśli nie została podana inna nazwa. Nie działa w trybie bezpiecznym.

mysqli.default_pw string

Domyślne hasło używane podczas połączenia do serwera bazy danych, jeśli nie zostało podane inne hasło. Nie działa w trybie bezpiecznym.

mysqli.reconnect integer

Automatycznie ponownie nawiązuje połączenie, jeśli zostanie zerwane.

mysqli.allow_local_infile integer

mysqli.cache_size integer

Dostępna tylko z mysqlnd.

Użytkownicy nie mogą ustawić MYSQL_OPT_READ_TIMEOUT przez wywołanie API, ani w konfiguracji wykonawczej. Proszę zwrócić uwagę na to, że jeśli ustawienie było możliwe, to są różnice w interpretacji przez libmysql i przez potoki wartości MYSQL_OPT_READ_TIMEOUT.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
The mysqli Extension and Persistent Connections
Instalacja/Konfiguracja


The mysqli Extension and Persistent Connections

Persistent connection support was introduced in PHP 5.3 for the mysqli extension. Support was already present in PDO MYSQL and ext/mysql. The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process, rather than being created and destroyed multiple times. This reduces the overhead of creating fresh connections every time one is required, as unused connections are cached and ready to be reused.

Unlike the mysql extension, mysqli does not provide a separate function for opening persistent connections. To open a persistent connection you must prepend p: to the hostname when connecting.

The problem with persistent connections is that they can be left in unpredictable states by clients. For example, a table lock might be activated before a client terminates unexpectedly. A new client process reusing this persistent connection will get the connection "as is". Any cleanup would need to be done by the new client process before it could make good use of the persistent connection, increasing the burden on the programmer.

The persistent connection of the mysqli extension however provides built-in cleanup handling code. The cleanup carried out by mysqli includes:

  • Rollback active transactions

  • Close and drop temporary tables

  • Unlock tables

  • Reset session variables

  • Close prepared statements (always happens with PHP)

  • Close handler

  • Release locks acquired with GET_LOCK()

This ensures that persistent connections are in a clean state on return from the connection pool, before the client process uses them.

The mysqli extension does this cleanup by automatically calling the C-API function mysql_change_user().

The automatic cleanup feature has advantages and disadvantages though. The advantage is that the programmer no longer needs to worry about adding cleanup code, as it is called automatically. However, the disadvantage is that the code could potentially be a little slower, as the code to perform the cleanup needs to run each time a connection is returned from the connection pool.

It is possible to switch off the automatic cleanup code, by compiling PHP with MYSQLI_NO_CHANGE_USER_ON_PCONNECT defined.

Informacja:

The mysqli extension supports persistent connections when using either MySQL Native Driver or MySQL Client Library.

Typy zasobów
Stałe predefiniowane
Mysqli


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.

MYSQLI_READ_DEFAULT_GROUP

Read options from the named group from my.cnf or the file specified with MYSQLI_READ_DEFAULT_FILE

MYSQLI_READ_DEFAULT_FILE

Read options from the named option file instead of from my.cnf

MYSQLI_OPT_CONNECT_TIMEOUT

Connect timeout in seconds

MYSQLI_OPT_LOCAL_INFILE

Enables command LOAD LOCAL INFILE

MYSQLI_INIT_COMMAND

Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.

MYSQLI_CLIENT_SSL

Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library

MYSQLI_CLIENT_COMPRESS

Use compression protocol

MYSQLI_CLIENT_INTERACTIVE

Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable.

MYSQLI_CLIENT_IGNORE_SPACE

Allow spaces after function names. Makes all functions names reserved words.

MYSQLI_CLIENT_NO_SCHEMA

Don't allow the db_name.tbl_name.col_name syntax.

MYSQLI_CLIENT_MULTI_QUERIES

Allows multiple semicolon-delimited queries in a single mysqli_query() call.

MYSQLI_STORE_RESULT

For using buffered resultsets

MYSQLI_USE_RESULT

For using unbuffered resultsets

MYSQLI_ASSOC

Columns are returned into the array having the fieldname as the array index.

MYSQLI_NUM

Columns are returned into the array having an enumerated index.

MYSQLI_BOTH

Columns are returned into the array having both a numerical index and the fieldname as the associative index.

MYSQLI_NOT_NULL_FLAG

Indicates that a field is defined as NOT NULL

MYSQLI_PRI_KEY_FLAG

Field is part of a primary index

MYSQLI_UNIQUE_KEY_FLAG

Field is part of a unique index.

MYSQLI_MULTIPLE_KEY_FLAG

Field is part of an index.

MYSQLI_BLOB_FLAG

Field is defined as BLOB

MYSQLI_UNSIGNED_FLAG

Field is defined as UNSIGNED

MYSQLI_ZEROFILL_FLAG

Field is defined as ZEROFILL

MYSQLI_AUTO_INCREMENT_FLAG

Field is defined as AUTO_INCREMENT

MYSQLI_TIMESTAMP_FLAG

Field is defined as TIMESTAMP

MYSQLI_SET_FLAG

Field is defined as SET

MYSQLI_NUM_FLAG

Field is defined as NUMERIC

MYSQLI_PART_KEY_FLAG

Field is part of an multi-index

MYSQLI_GROUP_FLAG

Field is part of GROUP BY

MYSQLI_TYPE_DECIMAL

Field is defined as DECIMAL

MYSQLI_TYPE_NEWDECIMAL

Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)

MYSQLI_TYPE_BIT

Field is defined as BIT (MySQL 5.0.3 and up)

MYSQLI_TYPE_TINY

Field is defined as TINYINT

MYSQLI_TYPE_SHORT

Field is defined as SMALLINT

MYSQLI_TYPE_LONG

Field is defined as INT

MYSQLI_TYPE_FLOAT

Field is defined as FLOAT

MYSQLI_TYPE_DOUBLE

Field is defined as DOUBLE

MYSQLI_TYPE_NULL

Field is defined as DEFAULT NULL

MYSQLI_TYPE_TIMESTAMP

Field is defined as TIMESTAMP

MYSQLI_TYPE_LONGLONG

Field is defined as BIGINT

MYSQLI_TYPE_INT24

Field is defined as MEDIUMINT

MYSQLI_TYPE_DATE

Field is defined as DATE

MYSQLI_TYPE_TIME

Field is defined as TIME

MYSQLI_TYPE_DATETIME

Field is defined as DATETIME

MYSQLI_TYPE_YEAR

Field is defined as YEAR

MYSQLI_TYPE_NEWDATE

Field is defined as DATE

MYSQLI_TYPE_INTERVAL

Field is defined as INTERVAL

MYSQLI_TYPE_ENUM

Field is defined as ENUM

MYSQLI_TYPE_SET

Field is defined as SET

MYSQLI_TYPE_TINY_BLOB

Field is defined as TINYBLOB

MYSQLI_TYPE_MEDIUM_BLOB

Field is defined as MEDIUMBLOB

MYSQLI_TYPE_LONG_BLOB

Field is defined as LONGBLOB

MYSQLI_TYPE_BLOB

Field is defined as BLOB

MYSQLI_TYPE_VAR_STRING

Field is defined as VARCHAR

MYSQLI_TYPE_STRING

Field is defined as STRING

MYSQLI_TYPE_CHAR

Field is defined as CHAR

MYSQLI_TYPE_GEOMETRY

Field is defined as GEOMETRY

MYSQLI_NEED_DATA

More data available for bind variable

MYSQLI_NO_DATA

No more data available for bind variable

MYSQLI_DATA_TRUNCATED

Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5.

MYSQLI_ENUM_FLAG

Field is defined as ENUM. Available since PHP 5.3.0.

MYSQLI_CURSOR_TYPE_FOR_UPDATE

MYSQLI_CURSOR_TYPE_NO_CURSOR

MYSQLI_CURSOR_TYPE_READ_ONLY

MYSQLI_CURSOR_TYPE_SCROLLABLE

MYSQLI_STMT_ATTR_CURSOR_TYPE

MYSQLI_STMT_ATTR_PREFETCH_ROWS

MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH

MYSQLI_SET_CHARSET_NAME

MYSQLI_REPORT_INDEX

Report if no index or bad index was used in a query.

MYSQLI_REPORT_ERROR

Report errors from mysqli function calls.

MYSQLI_REPORT_STRICT

Throw a mysqli_sql_exception for errors instead of warnings.

MYSQLI_REPORT_ALL

Set all options on (report all).

MYSQLI_REPORT_OFF

Turns reporting off.

MYSQLI_DEBUG_TRACE_ENABLED

Is set to 1 if mysqli_debug() functionality is enabled.

MYSQLI_SERVER_QUERY_NO_GOOD_INDEX_USED

MYSQLI_SERVER_QUERY_NO_INDEX_USED

MYSQLI_REFRESH_GRANT

Refreshes the grant tables.

MYSQLI_REFRESH_LOG

Flushes the logs, like executing the FLUSH LOGS SQL statement.

MYSQLI_REFRESH_TABLES

Flushes the table cache, like executing the FLUSH TABLES SQL statement.

MYSQLI_REFRESH_HOSTS

Flushes the host cache, like executing the FLUSH HOSTS SQL statement.

MYSQLI_REFRESH_STATUS

Reset the status variables, like executing the FLUSH STATUS SQL statement.

MYSQLI_REFRESH_THREADS

Flushes the thread cache.

MYSQLI_REFRESH_SLAVE

On a slave replication server: resets the master server information, and restarts the slave. Like executing the RESET SLAVE SQL statement.

MYSQLI_REFRESH_MASTER

On a master replication server: removes the binary log files listed in the binary log index, and truncates the index file. Like executing the RESET MASTER SQL statement.

The mysqli Extension and Persistent Connections
Notes
Mysqli


Notes

Some implementation notes:

  1. Support was added for MYSQL_TYPE_GEOMETRY to the MySQLi extension in PHP 5.3.

  2. Note there are different internal implementations within libmysql and mysqlnd for handling columns of type MYSQL_TYPE_GEOMETRY. Generally speaking, mysqlnd will allocate significantly less memory. For example, if there is a POINT column in a result set, libmysql may pre-allocate up to 4GB of RAM although less than 50 bytes are needed for holding a POINT column in memory. Memory allocation is much lower, less than 50 bytes, if using mysqlnd.

Stałe predefiniowane
The MySQLi Extension Function Summary
Mysqli


The MySQLi Extension Function Summary

mysqli Class
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli::affected_rows | mysqli_affected_rows() | N/A | Gets the number of affected rows in a previous MySQL operation
$mysqli::client_info | mysqli_get_client_info() | N/A | Returns the MySQL client version as a string
$mysqli::client_version | mysqli_get_client_version() | N/A | Returns MySQL client version info as an integer
$mysqli::connect_errno | mysqli_connect_errno() | N/A | Returns the error code from last connect call
$mysqli::connect_error | mysqli_connect_error() | N/A | Returns a string description of the last connect error
$mysqli::errno | mysqli_errno() | N/A | Returns the error code for the most recent function call
$mysqli::error | mysqli_error() | N/A | Returns a string description of the last error
$mysqli::field_count | mysqli_field_count() | N/A | Returns the number of columns for the most recent query
$mysqli::host_info | mysqli_get_host_info() | N/A | Returns a string representing the type of connection used
$mysqli::protocol_version | mysqli_get_proto_info() | N/A | Returns the version of the MySQL protocol used
$mysqli::server_info | mysqli_get_server_info() | N/A | Returns the version of the MySQL server
$mysqli::server_version | mysqli_get_server_version() | N/A | Returns the version of the MySQL server as an integer
$mysqli::info | mysqli_info() | N/A | Retrieves information about the most recently executed query
$mysqli::insert_id | mysqli_insert_id() | N/A | Returns the auto generated id used in the last query
$mysqli::sqlstate | mysqli_sqlstate() | N/A | Returns the SQLSTATE error from previous MySQL operation
$mysqli::warning_count | mysqli_warning_count() | N/A | Returns the number of warnings from the last query for the given link
Methods
mysqli::autocommit() | mysqli_autocommit() | N/A | Turns on or off auto-commiting database modifications
mysqli::change_user() | mysqli_change_user() | N/A | Changes the user of the specified database connection
mysqli::character_set_name(), mysqli::client_encoding | mysqli_character_set_name() | mysqli_client_encoding() | Returns the default character set for the database connection
mysqli::close() | mysqli_close() | N/A | Closes a previously opened database connection
mysqli::commit() | mysqli_commit() | N/A | Commits the current transaction
mysqli::__construct() | mysqli_connect() | N/A | Open a new connection to the MySQL server [Note: static (i.e. class) method]
mysqli::debug() | mysqli_debug() | N/A | Performs debugging operations
mysqli::dump_debug_info() | mysqli_dump_debug_info() | N/A | Dump debugging information into the log
mysqli::get_charset() | mysqli_get_charset() | N/A | Returns a character set object
mysqli::get_connection_stats() | mysqli_get_connection_stats() | N/A | Returns client connection statistics. Dostępna tylko z mysqlnd.
mysqli::get_client_info() | mysqli_get_client_info() | N/A | Returns the MySQL client version as a string
mysqli::get_client_stats() | mysqli_get_client_stats() | N/A | Returns client per-process statistics. Dostępna tylko z mysqlnd.
mysqli::get_cache_stats() | mysqli_get_cache_stats() | N/A | Returns client Zval cache statistics. Dostępna tylko z mysqlnd.
mysqli::get_server_info() | mysqli_get_server_info() | N/A | NOT DOCUMENTED
mysqli::get_warnings() | mysqli_get_warnings() | N/A | NOT DOCUMENTED
mysqli::init() | mysqli_init() | N/A | Initializes MySQLi and returns a resource for use with mysqli_real_connect. [Not called on an object, as it returns a $mysqli object.]
mysqli::kill() | mysqli_kill() | N/A | Asks the server to kill a MySQL thread
mysqli::more_results() | mysqli_more_results() | N/A | Check if there are any more query results from a multi query
mysqli::multi_query() | mysqli_multi_query() | N/A | Performs a query on the database
mysqli::next_result() | mysqli_next_result() | N/A | Prepare next result from multi_query
mysqli::options() | mysqli_options() | mysqli_set_opt() | Set options
mysqli::ping() | mysqli_ping() | N/A | Pings a server connection, or tries to reconnect if the connection has gone down
mysqli::prepare() | mysqli_prepare() | N/A | Prepare an SQL statement for execution
mysqli::query() | mysqli_query() | N/A | Performs a query on the database
mysqli::real_connect() | mysqli_real_connect() | N/A | Opens a connection to a mysql server
mysqli::real_escape_string(), mysqli::escape_string() | mysqli_real_escape_string() | mysqli_escape_string() | Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
mysqli::real_query() | mysqli_real_query() | N/A | Execute an SQL query
mysqli::refresh() | mysqli_refresh() | N/A | Flushes tables or caches, or resets the replication server information
mysqli::rollback() | mysqli_rollback() | N/A | Rolls back current transaction
mysqli::select_db() | mysqli_select_db() | N/A | Selects the default database for database queries
mysqli::set_charset() | mysqli_set_charset() | N/A | Sets the default client character set
mysqli::set_local_infile_default() | mysqli_set_local_infile_default() | N/A | Unsets user defined handler for load local infile command
mysqli::set_local_infile_handler() | mysqli_set_local_infile_handler() | N/A | Set callback function for LOAD DATA LOCAL INFILE command
mysqli::ssl_set() | mysqli_ssl_set() | N/A | Used for establishing secure connections using SSL
mysqli::stat() | mysqli_stat() | N/A | Gets the current system status
mysqli::stmt_init() | mysqli_stmt_init() | N/A | Initializes a statement and returns an object for use with mysqli_stmt_prepare
mysqli::store_result() | mysqli_store_result() | N/A | Transfers a result set from the last query
mysqli::thread_id() | mysqli_thread_id() | N/A | Returns the thread ID for the current connection
mysqli::thread_safe() | mysqli_thread_safe() | N/A | Returns whether thread safety is given or not
mysqli::use_result() | mysqli_use_result() | N/A | Initiate a result set retrieval
MySQL_STMT
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli_stmt::affected_rows | mysqli_stmt_affected_rows() | N/A | Returns the total number of rows changed, deleted, or inserted by the last executed statement
$mysqli_stmt::errno | mysqli_stmt_errno() | N/A | Returns the error code for the most recent statement call
$mysqli_stmt::error | mysqli_stmt_error() | N/A | Returns a string description for last statement error
$mysqli_stmt::field_count | mysqli_stmt_field_count() | N/A | Returns the number of field in the given statement - not documented
$mysqli_stmt::insert_id | mysqli_stmt_insert_id() | N/A | Get the ID generated from the previous INSERT operation
$mysqli_stmt::num_rows | mysqli_stmt_num_rows() | N/A | Return the number of rows in statements result set
$mysqli_stmt::param_count | mysqli_stmt_param_count() | mysqli_param_count() | Returns the number of parameter for the given statement
$mysqli_stmt::sqlstate | mysqli_stmt_sqlstate() | N/A | Returns SQLSTATE error from previous statement operation
Methods
mysqli_stmt::attr_get() | mysqli_stmt_attr_get() | N/A | Used to get the current value of a statement attribute
mysqli_stmt::attr_set() | mysqli_stmt_attr_set() | N/A | Used to modify the behavior of a prepared statement
mysqli_stmt::bind_param() | mysqli_stmt_bind_param() | mysqli_bind_param() | Binds variables to a prepared statement as parameters
mysqli_stmt::bind_result() | mysqli_stmt_bind_result() | mysqli_bind_result() | Binds variables to a prepared statement for result storage
mysqli_stmt::close() | mysqli_stmt_close() | N/A | Closes a prepared statement
mysqli_stmt::data_seek() | mysqli_stmt_data_seek() | N/A | Seeks to an arbitrary row in statement result set
mysqli_stmt::execute() | mysqli_stmt_execute() | mysqli_execute() | Executes a prepared Query
mysqli_stmt::fetch() | mysqli_stmt_fetch() | mysqli_fetch() | Fetch results from a prepared statement into the bound variables
mysqli_stmt::free_result() | mysqli_stmt_free_result() | N/A | Frees stored result memory for the given statement handle
mysqli_stmt::get_result() | mysqli_stmt_get_result() | N/A | Gets a result set from a prepared statement. Dostępna tylko z mysqlnd.
mysqli_stmt::get_warnings() | mysqli_stmt_get_warnings() | N/A | NOT DOCUMENTED
$mysqli_stmt::more_results() | mysqli_stmt_more_results() | N/A | NOT DOCUMENTED Dostępna tylko z mysqlnd.
$mysqli_stmt::next_result() | mysqli_stmt_next_result() | N/A | NOT DOCUMENTED Dostępna tylko z mysqlnd.
mysqli_stmt::num_rows() | mysqli_stmt_num_rows() | N/A | See also property $mysqli_stmt::num_rows
mysqli_stmt::prepare() | mysqli_stmt_prepare() | N/A | Prepare an SQL statement for execution
mysqli_stmt::reset() | mysqli_stmt_reset() | N/A | Resets a prepared statement
mysqli_stmt::result_metadata() | mysqli_stmt_result_metadata() | mysqli_get_metadata() | Returns result set metadata from a prepared statement
mysqli_stmt::send_long_data() | mysqli_stmt_send_long_data() | mysqli_send_long_data() | Send data in blocks
mysqli_stmt::store_result() | mysqli_stmt_store_result() | N/A | Transfers a result set from a prepared statement
mysqli_result
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
$mysqli_result::current_field | mysqli_field_tell() | N/A | Get current field offset of a result pointer
$mysqli_result::field_count | mysqli_num_fields() | N/A | Get the number of fields in a result
$mysqli_result::lengths | mysqli_fetch_lengths() | N/A | Returns the lengths of the columns of the current row in the result set
$mysqli_result::num_rows | mysqli_num_rows() | N/A | Gets the number of rows in a result
Methods
mysqli_result::data_seek() | mysqli_data_seek() | N/A | Adjusts the result pointer to an arbitary row in the result
mysqli_result::fetch_all() | mysqli_fetch_all() | N/A | Fetches all result rows and returns the result set as an associative array, a numeric array, or both. Dostępna tylko z mysqlnd.
mysqli_result::fetch_array() | mysqli_fetch_array() | N/A | Fetch a result row as an associative, a numeric array, or both
mysqli_result::fetch_assoc() | mysqli_fetch_assoc() | N/A | Fetch a result row as an associative array
mysqli_result::fetch_field_direct() | mysqli_fetch_field_direct() | N/A | Fetch meta-data for a single field
mysqli_result::fetch_field() | mysqli_fetch_field() | N/A | Returns the next field in the result set
mysqli_result::fetch_fields() | mysqli_fetch_fields() | N/A | Returns an array of objects representing the fields in a result set
mysqli_result::fetch_object() | mysqli_fetch_object() | N/A | Returns the current row of a result set as an object
mysqli_result::fetch_row() | mysqli_fetch_row() | N/A | Get a result row as an enumerated array
mysqli_result::field_seek() | mysqli_field_seek() | N/A | Set result pointer to a specified field offset
mysqli_result::free(), mysqli_result::close, mysqli_result::free_result | mysqli_free_result() | N/A | Frees the memory associated with a result
MySQL_Driver
OOP Interface | Procedural Interface | Alias (Do not use) | Description
Properties
N/A
Methods
mysqli_driver::embedded_server_end() | mysqli_embedded_server_end() | N/A | NOT DOCUMENTED
mysqli_driver::embedded_server_start() | mysqli_embedded_server_start() | N/A | NOT DOCUMENTED

Informacja:

Alias functions are provided for backward compatibility purposes only. Do not use them in new projects.

Notes
mysqli
Mysqli


The mysqli class

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

Wstęp

Represents a connection between PHP and a MySQL database.

Krótki opis klasy

mysqli {
/* Właściwości */
int $affected_rows;
string $client_info;
int $client_version;
string $connect_errno;
string $connect_error;
int $errno;
string $error;
int $field_count;
int $client_version;
string $host_info;
string $protocol_version;
string $server_info;
int $server_version;
string $info;
mixed $insert_id;
string $sqlstate;
int $thread_id;
int $warning_count;
/* Metody */
bool autocommit ( bool $mode )
bool change_user ( string $user , string $password , string $database )
string character_set_name ( void )
bool close ( void )
bool commit ( void )
bool debug ( string $message )
void disable_reads_from_master ( void )
bool dump_debug_info ( void )
object get_charset ( void )
string get_client_info ( void )
bool get_connection_stats ( void )
mysqli_warning get_warnings ( void )
mysqli init ( void )
bool kill ( int $processid )
bool more_results ( void )
bool multi_query ( string $query )
bool next_result ( void )
bool options ( int $option , mixed $value )
bool ping ( void )
public int poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )
mysqli_stmt prepare ( string $query )
mixed query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
bool real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )
string escape_string ( string $escapestr )
bool real_query ( string $query )
public mysqli_result reap_async_query ( void )
public bool refresh ( int $options )
bool rollback ( void )
int rpl_query_type ( string $query )
bool select_db ( string $dbname )
bool send_query ( string $query )
bool set_charset ( string $charset )
bool set_local_infile_handler ( mysqli $link , callback $read_func )
bool ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )
string stat ( void )
mysqli_stmt stmt_init ( void )
mysqli_result store_result ( void )
mysqli_result use_result ( void )
}

Spis treści

  • mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
  • mysqli::autocommit — Turns on or off auto-commiting database modifications
  • mysqli::change_user — Changes the user of the specified database connection
  • mysqli::character_set_name — Returns the default character set for the database connection
  • mysqli::$client_info — Returns the MySQL client version as a string
  • mysqli::$client_version — Get MySQL client info
  • mysqli::close — Closes a previously opened database connection
  • mysqli::commit — Commits the current transaction
  • mysqli::$connect_errno — Returns the error code from last connect call
  • mysqli::$connect_error — Returns a string description of the last connect error
  • mysqli::__construct — Open a new connection to the MySQL server
  • mysqli::debug — Performs debugging operations
  • mysqli::disable_reads_from_master — Disable reads from master
  • mysqli::dump_debug_info — Dump debugging information into the log
  • mysqli::$errno — Returns the error code for the most recent function call
  • mysqli::$error — Returns a string description of the last error
  • mysqli::$field_count — Returns the number of columns for the most recent query
  • mysqli::get_charset — Returns a character set object
  • mysqli::get_client_info — Returns the MySQL client version as a string
  • mysqli_get_client_stats — Returns client per-process statistics
  • mysqli::$client_version — Get MySQL client info
  • mysqli::get_connection_stats — Returns statistics about the client connection
  • mysqli::$host_info — Returns a string representing the type of connection used
  • mysqli::$protocol_version — Returns the version of the MySQL protocol used
  • mysqli::$server_info — Returns the version of the MySQL server
  • mysqli::$server_version — Returns the version of the MySQL server as an integer
  • mysqli::get_warnings — Get result of SHOW WARNINGS
  • mysqli::$info — Retrieves information about the most recently executed query
  • mysqli::init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli::$insert_id — Returns the auto generated id used in the last query
  • mysqli::kill — Asks the server to kill a MySQL thread
  • mysqli::more_results — Check if there are any more query results from a multi query
  • mysqli::multi_query — Performs a query on the database
  • mysqli::next_result — Prepare next result from multi_query
  • mysqli::options — Set options
  • mysqli::ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • mysqli::poll — Poll connections
  • mysqli::prepare — Prepare an SQL statement for execution
  • mysqli::query — Performs a query on the database
  • mysqli::real_connect — Opens a connection to a mysql server
  • mysqli::real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • mysqli::real_query — Execute an SQL query
  • mysqli::reap_async_query — Get result from async query
  • mysqli::refresh — Refreshes
  • mysqli::rollback — Rolls back current transaction
  • mysqli::rpl_query_type — Returns RPL query type
  • mysqli::select_db — Selects the default database for database queries
  • mysqli::send_query — Send the query and return
  • mysqli::set_charset — Sets the default client character set
  • mysqli::set_local_infile_default — Unsets user defined handler for load local infile command
  • mysqli::set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command
  • mysqli::$sqlstate — Returns the SQLSTATE error from previous MySQL operation
  • mysqli::ssl_set — Used for establishing secure connections using SSL
  • mysqli::stat — Gets the current system status
  • mysqli::stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • mysqli::store_result — Transfers a result set from the last query
  • mysqli::$thread_id — Returns the thread ID for the current connection
  • mysqli::thread_safe — Returns whether thread safety is given or not
  • mysqli::use_result — Initiate a result set retrieval
  • mysqli::$warning_count — Returns the number of warnings from the last query for the given link
The MySQLi Extension Function Summary
mysqli::$affected_rows
Mysqli


Gets the number of affected rows in a previous MySQL operation

mysqli
mysqli::autocommit
mysqli
PHP Manual

mysqli::$affected_rows

mysqli_affected_rows

(PHP 5)

mysqli::$affected_rows -- mysqli_affected_rows — Gets the number of affected rows in a previous MySQL operation

Opis

Styl obiektowy

int $mysqli->affected_rows;

Styl proceduralny

int mysqli_affected_rows ( mysqli $link )

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.

For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.

Informacja:

If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string.

Przykłady

Przykład #1 $mysqli->affected_rows example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);

/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);

/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);

$result->close();

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));

mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");

/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));

/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));

/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));

mysqli_free_result($result);

/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

Zobacz też:

  • mysqli_num_rows() - Gets the number of rows in a result
  • mysqli_info() - Retrieves information about the most recently executed query

mysqli
mysqli::autocommit
mysqli


Turns on or off auto-commiting database modifications

mysqli::$affected_rows
mysqli::change_user
mysqli
PHP Manual

mysqli::autocommit

mysqli_autocommit

(PHP 5)

mysqli::autocommit -- mysqli_autocommit — Turns on or off auto-commiting database modifications

Opis

Styl obiektowy

bool mysqli::autocommit ( bool $mode )

Styl proceduralny

bool mysqli_autocommit ( mysqli $link , bool $mode )

Turns on or off auto-commit mode on queries for the database connection.

To determine the current state of autocommit use the SQL command SELECT @@autocommit.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

mode

Whether to turn on auto-commit or not.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

This function doesn't work with non transactional table types (like MyISAM or ISAM).

Przykłady

Przykład #1 mysqli::autocommit() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
$mysqli->autocommit(TRUE);

if ($result = $mysqli->query("SELECT @@autocommit")) {
    $row = $result->fetch_row();
    printf("Autocommit is %s\n", $row[0]);
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
mysqli_autocommit($link, TRUE);

if ($result = mysqli_query($link, "SELECT @@autocommit")) {
    $row = mysqli_fetch_row($result);
    printf("Autocommit is %s\n", $row[0]);
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Autocommit is 1

Zobacz też:

  • mysqli_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction

mysqli::$affected_rows
mysqli::change_user
mysqli


Changes the user of the specified database connection

mysqli::autocommit
mysqli::character_set_name
mysqli
PHP Manual

mysqli::change_user

mysqli_change_user

(PHP 5)

mysqli::change_user -- mysqli_change_user — Changes the user of the specified database connection

Opis

Styl obiektowy

bool mysqli::change_user ( string $user , string $password , string $database )

Styl proceduralny

bool mysqli_change_user ( mysqli $link , string $user , string $password , string $database )

Changes the user of the specified database connection and sets the current database.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

user

The MySQL user name.

password

The MySQL password.

database

The database to change to.

If desired, the NULL value may be passed resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

Przykłady

Przykład #1 mysqli::change_user() example

Styl obiektowy

<?php

/* connect database test */
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
$mysqli->query("SET @a:=1");

/* reset all and select a new database */
$mysqli->change_user("my_user", "my_password", "world");

if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database: %s\n", $row[0]);
    $result->close();
}

if ($result = $mysqli->query("SELECT @a")) {
    $row = $result->fetch_row();
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
/* connect database test */
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
mysqli_query($link, "SET @a:=1");

/* reset all and select a new database */
mysqli_change_user($link, "my_user", "my_password", "world");

if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database: %s\n", $row[0]);
    mysqli_free_result($result);
}

if ($result = mysqli_query($link, "SELECT @a")) {
    $row = mysqli_fetch_row($result);
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Default database: world
Value of variable a is NULL

Zobacz też:

  • mysqli_connect() - Alias dla mysqli::__construct
  • mysqli_select_db() - Selects the default database for database queries

mysqli::autocommit
mysqli::character_set_name
mysqli


Returns the default character set for the database connection

mysqli::change_user
mysqli::$client_info
mysqli
PHP Manual

mysqli::character_set_name

mysqli_character_set_name

(PHP 5)

mysqli::character_set_name -- mysqli_character_set_name — Returns the default character set for the database connection

Opis

Styl obiektowy

string mysqli::character_set_name ( void )

Styl proceduralny

string mysqli_character_set_name ( mysqli $link )

Returns the current character set for the database connection.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

The default character set for the current connection

Przykłady

Przykład #1 mysqli::character_set_name() example

Styl obiektowy

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = $mysqli->character_set_name();
printf ("Current character set is %s\n", $charset);

$mysqli->close();
?>

Styl proceduralny

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = mysqli_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Current character set is latin1_swedish_ci

Zobacz też:

  • mysqli_client_encoding() - Alias of mysqli_character_set_name
  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

mysqli::change_user
mysqli::$client_info
mysqli


Returns the MySQL client version as a string

mysqli::character_set_name
mysqli::$client_version
mysqli
PHP Manual

mysqli::$client_info

mysqli_get_client_info

(PHP 5)

mysqli::$client_info -- mysqli_get_client_info — Returns the MySQL client version as a string

Opis

Styl obiektowy

string $mysqli->client_info;

Styl proceduralny

string mysqli_get_client_info ( mysqli $link )

Returns a string that represents the MySQL client library version.

Zwracane wartości

A string that represents the MySQL client library version

Przykłady

Przykład #1 mysqli_get_client_info

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %s\n", mysqli_get_client_info());
?>

Zobacz też:

  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli::character_set_name
mysqli::$client_version
mysqli


Get MySQL client info

mysqli::$client_info
mysqli::close
mysqli
PHP Manual

mysqli::$client_version

mysqli_get_client_version

(PHP 5)

mysqli::$client_version -- mysqli_get_client_version — Get MySQL client info

Opis

Styl obiektowy

int $mysqli->client_version;

Styl proceduralny

int mysqli_get_client_version ( mysqli $link )

Returns client version number as an integer.

Zwracane wartości

A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the client library to know if some capability exists.

Przykłady

Przykład #1 mysqli_get_client_version

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?>

Zobacz też:

  • mysqli_get_client_info() - Returns the MySQL client version as a string
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli::$client_info
mysqli::close
mysqli


Closes a previously opened database connection

mysqli::$client_version
mysqli::commit
mysqli
PHP Manual

mysqli::close

mysqli_close

(PHP 5)

mysqli::close -- mysqli_close — Closes a previously opened database connection

Opis

Styl obiektowy

bool mysqli::close ( void )

Styl proceduralny

bool mysqli_close ( mysqli $link )

Closes a previously opened database connection.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

See mysqli_connect().

Zobacz też:

  • mysqli_connect() - Alias dla mysqli::__construct
  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli::$client_version
mysqli::commit
mysqli


Commits the current transaction

mysqli::close
mysqli::$connect_errno
mysqli
PHP Manual

mysqli::commit

mysqli_commit

(PHP 5)

mysqli::commit -- mysqli_commit — Commits the current transaction

Opis

Styl obiektowy

bool mysqli::commit ( void )

Styl proceduralny

bool mysqli_commit ( mysqli $link )

Commits the current transaction for the database connection.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mysqli::commit() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE Language LIKE CountryLanguage");

/* set autocommit to off */
$mysqli->autocommit(FALSE);

/* Insert some values */
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
$mysqli->commit();

/* drop table */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage");

/* Insert some values */
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
mysqli_commit($link);

/* close connection */
mysqli_close($link);
?>

Zobacz też:

  • mysqli_autocommit() - Turns on or off auto-commiting database modifications
  • mysqli_rollback() - Rolls back current transaction

mysqli::close
mysqli::$connect_errno
mysqli


Returns the error code from last connect call

mysqli::commit
mysqli::$connect_error
mysqli
PHP Manual

mysqli::$connect_errno

mysqli_connect_errno

(PHP 5)

mysqli::$connect_errno -- mysqli_connect_errno — Returns the error code from last connect call

Opis

Styl obiektowy

string $mysqli->connect_errno;

Styl proceduralny

int mysqli_connect_errno ( void )

Returns the last error code number from the last call to mysqli_connect().

Informacja:

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Zwracane wartości

An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.

Przykłady

Przykład #1 $mysqli->connect_errno example

Styl obiektowy

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

if ($mysqli->connect_errno) {
    die('Connect Error: ' . $mysqli->connect_errno);
}
?>

Styl proceduralny

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_errno());
}
?>

Powyższe przykłady wyświetlą:

Connect Error: 1045

Zobacz też:

  • mysqli_connect() - Alias dla mysqli::__construct
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli::commit
mysqli::$connect_error
mysqli


Returns a string description of the last connect error

mysqli::$connect_errno
mysqli::__construct
mysqli
PHP Manual

mysqli::$connect_error

mysqli_connect_error

(PHP 5)

mysqli::$connect_error -- mysqli_connect_error — Returns a string description of the last connect error

Opis

Styl obiektowy

string $mysqli->connect_error;

Styl proceduralny

string mysqli_connect_error ( void )

Returns the last error message string from the last call to mysqli_connect().

Zwracane wartości

A string that describes the error. NULL is returned if no error occurred.

Przykłady

Przykład #1 $mysqli->connect_error example

Styl obiektowy

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
?>

Styl proceduralny

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_error());
}
?>

Powyższe przykłady wyświetlą:

Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES)

Notatki

Ostrzeżenie

The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error() function if compatibility with earlier PHP versions is required.

Zobacz też:

  • mysqli_connect() - Alias dla mysqli::__construct
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli::$connect_errno
mysqli::__construct
mysqli


Open a new connection to the MySQL server

mysqli::$connect_error
mysqli::debug
mysqli
PHP Manual

mysqli::__construct

mysqli_connect

(PHP 5)

mysqli::__construct -- mysqli_connect — Open a new connection to the MySQL server

Opis

Styl obiektowy

  mysqli::__construct()
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )

Styl proceduralny

 mysqli mysqli_connect
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )

Opens a connection to the MySQL Server running on.

Parametry

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

Prepending host by p: opens a persistent connection. mysqli_change_user() is automatically called on connections opened from the connection pool.

username

The MySQL user name.

passwd

If not provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

Informacja:

Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

Zwracane wartości

Returns an object which represents the connection to a MySQL Server.

Rejestr zmian

Wersja | Opis
5.3.0 | Added the ability of persistent connections.

Przykłady

Przykład #1 mysqli::__construct() example

Styl obiektowy

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

Styl obiektowy when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::__construct($host, $user, $pass, $db);

        if (mysqli_connect_error()) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Success... MySQL host info: localhost via TCP/IP

Notatki

Informacja:

MySQLnd zawsze przyjmuje domyślne kodowanie znaków serwera. To kodowanie jest przesyłane podczas połączenia hand-shake/authentication, którego używa mysqlnd.

Libmysql używa domyślnego kodowania znaków ustawionego w pliku my.cnf lub przez jawne wywołanie funkcji mysqli_options() przed wywołaniem mysqli_real_connect(), ale po wywołaniu mysqli_init().

Informacja:

OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.

Informacja:

If it is necessary to set options, such as the connection timeout, mysqli_real_connect() must be used instead.

Informacja:

Calling the constructor with no parameters is the same as calling mysqli_init().

Informacja:

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

Zobacz też:

  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_close() - Closes a previously opened database connection

mysqli::$connect_error
mysqli::debug
mysqli


Performs debugging operations

mysqli::__construct
mysqli::disable_reads_from_master
mysqli
PHP Manual

mysqli::debug

mysqli_debug

(PHP 5)

mysqli::debug -- mysqli_debug — Performs debugging operations

Opis

Styl obiektowy

bool mysqli::debug ( string $message )

Styl proceduralny

bool mysqli_debug ( string $message )

Performs debugging operations using the Fred Fish debugging library.

Parametry

message

A string representing the debugging operation to perform

Zwracane wartości

Returns TRUE.

Notatki

Informacja:

To use the mysqli_debug() function you must compile the MySQL client library to support debugging.

Przykłady

Przykład #1 Generating a Trace File

<?php

/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:o,/tmp/client.trace");

?>

Zobacz też:

  • mysqli_dump_debug_info() - Dump debugging information into the log
  • mysqli_report() - Enables or disables internal report functions

mysqli::__construct
mysqli::disable_reads_from_master
mysqli


Disable reads from master

mysqli::debug
mysqli::dump_debug_info
mysqli
PHP Manual

mysqli::disable_reads_from_master

mysqli_disable_reads_from_master

(PHP 5)

mysqli::disable_reads_from_master -- mysqli_disable_reads_from_master — Disable reads from master

Opis

Styl obiektowy

void mysqli::disable_reads_from_master ( void )

Styl proceduralny

bool mysqli_disable_reads_from_master ( mysqli $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli::debug
mysqli::dump_debug_info
mysqli


Dump debugging information into the log

mysqli::disable_reads_from_master
mysqli::$errno
mysqli
PHP Manual

mysqli::dump_debug_info

mysqli_dump_debug_info

(PHP 5)

mysqli::dump_debug_info -- mysqli_dump_debug_info — Dump debugging information into the log

Opis

Styl obiektowy

bool mysqli::dump_debug_info ( void )

Styl proceduralny

bool mysqli_dump_debug_info ( mysqli $link )

This function is designed to be executed by an user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mysqli_debug() - Performs debugging operations

mysqli::disable_reads_from_master
mysqli::$errno
mysqli


Returns the error code for the most recent function call

mysqli::dump_debug_info
mysqli::$error
mysqli
PHP Manual

mysqli::$errno

mysqli_errno

(PHP 5)

mysqli::$errno -- mysqli_errno — Returns the error code for the most recent function call

Opis

Styl obiektowy

int $mysqli->errno;

Styl proceduralny

int mysqli_errno ( mysqli $link )

Returns the last error code for the most recent MySQLi function call that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

An error code value for the last call, if it failed. zero means no error occurred.

Przykłady

Przykład #1 $mysqli->errno example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errorcode: %d\n", $mysqli->errno);
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errorcode: %d\n", mysqli_errno($link));
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Errorcode: 1193

Zobacz też:

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli::dump_debug_info
mysqli::$error
mysqli


Returns a string description of the last error

mysqli::$errno
mysqli::$field_count
mysqli
PHP Manual

mysqli::$error

mysqli_error

(PHP 5)

mysqli::$error -- mysqli_error — Returns a string description of the last error

Opis

Styl obiektowy

string $mysqli->error;

Styl proceduralny

string mysqli_error ( mysqli $link )

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

A string that describes the error. An empty string if no error occurred.

Przykłady

Przykład #1 $mysqli->error example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("SET a=1")) {
    printf("Errormessage: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errormessage: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Errormessage: Unknown system variable 'a'

Zobacz też:

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli::$errno
mysqli::$field_count
mysqli


Returns the number of columns for the most recent query

mysqli::$error
mysqli::get_charset
mysqli
PHP Manual

mysqli::$field_count

mysqli_field_count

(PHP 5)

mysqli::$field_count -- mysqli_field_count — Returns the number of columns for the most recent query

Opis

Styl obiektowy

int $mysqli->field_count;

Styl proceduralny

int mysqli_field_count ( mysqli $link )

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

An integer representing the number of fields in a result set.

Przykłady

Przykład #1 $mysqli->field_count example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$mysqli->real_query("SELECT * FROM friends");

if ($mysqli->field_count) {
    /* this was a select/show or describe query */
    $result = $mysqli->store_result();

    /* process resultset */
    $row = $result->fetch_row();

    /* free resultset */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

mysqli_real_query($link, "SELECT * FROM friends");

if (mysqli_field_count($link)) {
    /* this was a select/show or describe query */
    $result = mysqli_store_result($link);

    /* process resultset */
    $row = mysqli_fetch_row($result);

    /* free resultset */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>
mysqli::$error
mysqli::get_charset
mysqli


Returns a character set object

mysqli::$field_count
mysqli::get_client_info
mysqli
PHP Manual

mysqli::get_charset

mysqli_get_charset

(PHP 5 >= 5.1.0)

mysqli::get_charset -- mysqli_get_charset — Returns a character set object

Opis

Styl obiektowy

object mysqli::get_charset ( void )

Styl proceduralny

object mysqli_get_charset ( mysqli $link )

Returns a character set object providing several properties of the current active character set.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

The function returns a character set object with the following properties:

charset

Character set name

collation

Collation name

dir

Directory the charset description was fetched from (?) or "" for built-in character sets

min_length

Minimum character length in bytes

max_length

Maximum character length in bytes

number

Internal character set number

state

Character set status (?)

Przykłady

Przykład #1 mysqli::get_charset() example

Styl obiektowy

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");
  var_dump($db->get_charset());
?>

Styl proceduralny

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");
  var_dump($db->get_charset());
?>

Powyższe przykłady wyświetlą:

object(stdClass)#2 (7) {
  ["charset"]=>
  string(6) "latin1"
  ["collation"]=>
  string(17) "latin1_swedish_ci"
  ["dir"]=>
  string(0) ""
  ["min_length"]=>
  int(1)
  ["max_length"]=>
  int(1)
  ["number"]=>
  int(8)
  ["state"]=>
  int(801)
}

Zobacz też:

  • mysqli_character_set_name() - Returns the default character set for the database connection
  • mysqli_set_charset() - Sets the default client character set

mysqli::$field_count
mysqli::get_client_info
mysqli


Returns the MySQL client version as a string

mysqli::get_charset
mysqli_get_client_stats
mysqli
PHP Manual

mysqli::get_client_info

mysqli_get_client_info

(PHP 5)

mysqli::get_client_info -- mysqli_get_client_info — Returns the MySQL client version as a string

Opis

Styl obiektowy

string mysqli::get_client_info ( void )

Styl proceduralny

string mysqli_get_client_info ( mysqli $link )

Returns a string that represents the MySQL client library version.

Zwracane wartości

A string that represents the MySQL client library version

Przykłady

Przykład #1 mysqli_get_client_info

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %s\n", mysqli_get_client_info());
?>

Zobacz też:

  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli::get_charset
mysqli_get_client_stats
mysqli


Returns client per-process statistics

mysqli::get_client_info
mysqli::$client_version
mysqli
PHP Manual

mysqli_get_client_stats

(PHP 5 >= 5.3.0)

mysqli_get_client_stats — Returns client per-process statistics

Opis

array mysqli_get_client_stats ( void )

Returns client per-process statistics. Dostępna tylko z mysqlnd.

Parametry

Zwracane wartości

Returns an array with client stats if success, FALSE otherwise.

Przykłady

Przykład #1 A mysqli_get_client_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_client_stats());
?>

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

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

Zobacz też:

  • Stats description

mysqli::get_client_info
mysqli::$client_version
mysqli


Get MySQL client info

mysqli_get_client_stats
mysqli::get_connection_stats
mysqli
PHP Manual

mysqli::$client_version

mysqli_get_client_version

(PHP 5)

mysqli::$client_version -- mysqli_get_client_version — Get MySQL client info

Opis

Styl obiektowy

int $mysqli->client_version;

Styl proceduralny

int mysqli_get_client_version ( mysqli $link )

Returns client version number as an integer.

Zwracane wartości

A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.

This is useful to quickly determine the version of the client library to know if some capability exits.

Przykłady

Przykład #1 mysqli_get_client_version

<?php

/* We don't need a connection to determine
   the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?>

Zobacz też:

  • mysqli_get_client_info() - Returns the MySQL client version as a string
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli_get_client_stats
mysqli::get_connection_stats
mysqli


Returns statistics about the client connection

mysqli::$client_version
mysqli::$host_info
mysqli
PHP Manual

mysqli::get_connection_stats

mysqli_get_connection_stats

(PHP 5 >= 5.3.0)

mysqli::get_connection_stats -- mysqli_get_connection_stats — Returns statistics about the client connection

Opis

Styl obiektowy

bool mysqli::get_connection_stats ( void )

Styl proceduralny

array mysqli_get_connection_stats ( mysqli $link )

Returns statistics about the client connection. Dostępna tylko z mysqlnd.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Returns an array with connection stats if success, FALSE otherwise.

Przykłady

Przykład #1 A mysqli_get_connection_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_connection_stats($link));
?>

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

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

Zobacz też:

  • Stats description

mysqli::$client_version
mysqli::$host_info
mysqli


Returns a string representing the type of connection used

mysqli::get_connection_stats
mysqli::$protocol_version
mysqli
PHP Manual

mysqli::$host_info

mysqli_get_host_info

(PHP 5)

mysqli::$host_info -- mysqli_get_host_info — Returns a string representing the type of connection used

Opis

Styl obiektowy

string $mysqli->host_info;

Styl proceduralny

string mysqli_get_host_info ( mysqli $link )

Returns a string describing the connection represented by the link parameter (including the server host name).

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

A character string representing the server hostname and the connection type.

Przykłady

Przykład #1 $mysqli->host_info example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", $mysqli->host_info);

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Host info: Localhost via UNIX socket

Zobacz też:

  • mysqli_get_proto_info() - Returns the version of the MySQL protocol used

mysqli::get_connection_stats
mysqli::$protocol_version
mysqli


Returns the version of the MySQL protocol used

mysqli::$host_info
mysqli::$server_info
mysqli
PHP Manual

mysqli::$protocol_version

mysqli_get_proto_info

(PHP 5)

mysqli::$protocol_version -- mysqli_get_proto_info — Returns the version of the MySQL protocol used

Opis

Styl obiektowy

string $mysqli->protocol_version;

Styl proceduralny

int mysqli_get_proto_info ( mysqli $link )

Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Returns an integer representing the protocol version.

Przykłady

Przykład #1 $mysqli->protocol_version example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $mysqli->protocol_version);

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Protocol version: 10

Zobacz też:

  • mysqli_get_host_info() - Returns a string representing the type of connection used

mysqli::$host_info
mysqli::$server_info
mysqli


Returns the version of the MySQL server

mysqli::$protocol_version
mysqli::$server_version
mysqli
PHP Manual

mysqli::$server_info

mysqli_get_server_info

(PHP 5)

mysqli::$server_info -- mysqli_get_server_info — Returns the version of the MySQL server

Opis

Styl obiektowy

string $mysqli->server_info;

Styl proceduralny

string mysqli_get_server_info ( mysqli $link )

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

A character string representing the server version.

Przykłady

Przykład #1 $mysqli->server_info example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", $mysqli->server_info);

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Server version: 4.1.2-alpha-debug

Zobacz też:

  • mysqli_get_client_info() - Returns the MySQL client version as a string
  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer

mysqli::$protocol_version
mysqli::$server_version
mysqli


Returns the version of the MySQL server as an integer

mysqli::$server_info
mysqli::get_warnings
mysqli
PHP Manual

mysqli::$server_version

mysqli_get_server_version

(PHP 5)

mysqli::$server_version -- mysqli_get_server_version — Returns the version of the MySQL server as an integer

Opis

Styl obiektowy

int $mysqli->server_version;

Styl proceduralny

int mysqli_get_server_version ( mysqli $link )

The mysqli_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

An integer representing the server version.

The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100).

Przykłady

Przykład #1 $mysqli->server_version example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", $mysqli->server_version);

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Server version: 40102

Zobacz też:

  • mysqli_get_client_info() - Returns the MySQL client version as a string
  • mysqli_get_client_version() - Get MySQL client info
  • mysqli_get_server_info() - Returns the version of the MySQL server

mysqli::$server_info
mysqli::get_warnings
mysqli


Get result of SHOW WARNINGS

mysqli::$server_version
mysqli::$info
mysqli
PHP Manual

mysqli::get_warnings

mysqli_get_warnings

(PHP 5 >= 5.1.0)

mysqli::get_warnings -- mysqli_get_warnings — Get result of SHOW WARNINGS

Opis

Styl obiektowy

mysqli_warning mysqli::get_warnings ( void )

Styl proceduralny

mysqli_warning mysqli_get_warnings ( mysqli $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

mysqli::$server_version
mysqli::$info
mysqli


Retrieves information about the most recently executed query

mysqli::get_warnings
mysqli::init
mysqli
PHP Manual

mysqli::$info

mysqli_info

(PHP 5)

mysqli::$info -- mysqli_info — Retrieves information about the most recently executed query

Opis

Styl obiektowy

string $mysqli->info;

Styl proceduralny

string mysqli_info ( mysqli $link )

The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Possible mysqli_info return values
Query type | Example result string
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0

Informacja:

Queries which do not fall into one of the preceding formats are not supported. In these situations, mysqli_info() will return an empty string.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

A character string representing additional information about the most recently executed query.

Przykłady

Przykład #1 $mysqli->info example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO .. SELECT */
mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", mysqli_info($link));

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Records: 150  Duplicates: 0  Warnings: 0

Zobacz też:

  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysqli_warning_count() - Returns the number of warnings from the last query for the given link
  • mysqli_num_rows() - Gets the number of rows in a result

mysqli::get_warnings
mysqli::init
mysqli


Initializes MySQLi and returns a resource for use with mysqli_real_connect()

mysqli::$info
mysqli::$insert_id
mysqli
PHP Manual

mysqli::init

mysqli_init

(PHP 5)

mysqli::init -- mysqli_init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()

Opis

Styl obiektowy

mysqli mysqli::init ( void )

Styl proceduralny

mysqli mysqli_init ( void )

Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().

Informacja:

Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.

Zwracane wartości

Returns an object.

Przykłady

See mysqli_real_connect().

Zobacz też:

  • mysqli_options() - Set options
  • mysqli_close() - Closes a previously opened database connection
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_connect() - Alias dla mysqli::__construct

mysqli::$info
mysqli::$insert_id
mysqli


Returns the auto generated id used in the last query

mysqli::init
mysqli::kill
mysqli
PHP Manual

mysqli::$insert_id

mysqli_insert_id

(PHP 5)

mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query

Opis

Styl obiektowy

mixed $mysqli->insert_id;

Styl proceduralny

mixed mysqli_insert_id ( mysqli $link )

The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

Informacja:

Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.

Informacja:

If the number is greater than maximal int value, mysqli_insert_id() will return a string.

Przykłady

Przykład #1 $mysqli->insert_id example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* drop table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);

printf ("New Record has id %d.\n", mysqli_insert_id($link));

/* drop table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

New Record has id 1.
mysqli::init
mysqli::kill
mysqli


Asks the server to kill a MySQL thread

mysqli::$insert_id
mysqli::more_results
mysqli
PHP Manual

mysqli::kill

mysqli_kill

(PHP 5)

mysqli::kill -- mysqli_kill — Asks the server to kill a MySQL thread

Opis

Styl obiektowy

bool mysqli::kill ( int $processid )

Styl proceduralny

bool mysqli_kill ( mysqli $link , int $processid )

This function is used to ask the server to kill a MySQL thread specified by the processid parameter. This value must be retrieved by calling the mysqli_thread_id() function.

To stop a running query you should use the SQL command KILL QUERY processid.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mysqli::kill() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = $mysqli->thread_id;

/* Kill connection */
$mysqli->kill($thread_id);

/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = mysqli_thread_id($link);

/* Kill connection */
mysqli_kill($link, $thread_id);

/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Error: MySQL server has gone away

Zobacz też:

  • mysqli_thread_id() - Returns the thread ID for the current connection

mysqli::$insert_id
mysqli::more_results
mysqli


Check if there are any more query results from a multi query

mysqli::kill
mysqli::multi_query
mysqli
PHP Manual

mysqli::more_results

mysqli_more_results

(PHP 5)

mysqli::more_results -- mysqli_more_results — Check if there are any more query results from a multi query

Opis

Styl obiektowy

bool mysqli::more_results ( void )

Styl proceduralny

bool mysqli_more_results ( mysqli $link )

Indicates if one or more result sets are available from a previous call to mysqli_multi_query().

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

See mysqli_multi_query().

Zobacz też:

  • mysqli_multi_query() - Performs a query on the database
  • mysqli_next_result() - Prepare next result from multi_query
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli::kill
mysqli::multi_query
mysqli


Performs a query on the database

mysqli::more_results
mysqli::next_result
mysqli
PHP Manual

mysqli::multi_query

mysqli_multi_query

(PHP 5)

mysqli::multi_query -- mysqli_multi_query — Performs a query on the database

Opis

Styl obiektowy

bool mysqli::multi_query ( string $query )

Styl proceduralny

bool mysqli_multi_query ( mysqli $link , string $query )

Executes one or multiple queries which are concatenated by a semicolon.

To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

query

The query, as a string.

Data inside the query should be properly escaped.

Zwracane wartości

Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

Przykłady

Przykład #1 mysqli::multi_query() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_store_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą coś podobnego do:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

Zobacz też:

  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_next_result() - Prepare next result from multi_query
  • mysqli_more_results() - Check if there are any more query results from a multi query

mysqli::more_results
mysqli::next_result
mysqli


Prepare next result from multi_query

mysqli::multi_query
mysqli::options
mysqli
PHP Manual

mysqli::next_result

mysqli_next_result

(PHP 5)

mysqli::next_result -- mysqli_next_result — Prepare next result from multi_query

Opis

Styl obiektowy

bool mysqli::next_result ( void )

Styl proceduralny

bool mysqli_next_result ( mysqli $link )

Prepares next result set from a previous call to
mysqli_multi_query() which can be retrieved by
mysqli_store_result() or
mysqli_use_result().

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

See mysqli_multi_query().

Zobacz też:

  • mysqli_multi_query() - Performs a query on the database
  • mysqli_more_results() - Check if there are any more query results from a multi query
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli::multi_query
mysqli::options
mysqli


Set options

mysqli::next_result
mysqli::ping
mysqli
PHP Manual

mysqli::options

mysqli_options

(PHP 5)

mysqli::options -- mysqli_options — Set options

Opis

Styl obiektowy

bool mysqli::options ( int $option , mixed $value )

Styl proceduralny

bool mysqli_options ( mysqli $link , int $option , mixed $value )

Used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

mysqli_options() should be called after
mysqli_init() and before
mysqli_real_connect().

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

option

The option that you want to set. It can be one of the following values:

Valid options
Name | Description
MYSQLI_OPT_CONNECT_TIMEOUT | connection timeout in seconds (supported on Windows with TCP/IP since PHP 5.3.1)
MYSQLI_OPT_LOCAL_INFILE | enable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND | command to execute after when connecting to MySQL server
MYSQLI_READ_DEFAULT_FILE | Read options from named option file instead of my.cnf
MYSQLI_READ_DEFAULT_GROUP | Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE.

value

The value for the option.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

See mysqli_real_connect().

Notatki

Informacja:

MySQLnd zawsze przyjmuje domyślne kodowanie znaków serwera. To kodowanie jest przesyłane podczas połączenia hand-shake/authentication, którego używa mysqlnd.

Libmysql używa domyślnego kodowania znaków ustawionego w pliku my.cnf lub przez jawne wywołanie funkcji mysqli_options() przed wywołaniem mysqli_real_connect(), ale po wywołaniu mysqli_init().

Zobacz też:

  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli::next_result
mysqli::ping
mysqli


Pings a server connection, or tries to reconnect if the connection has gone down

mysqli::options
mysqli::poll
mysqli
PHP Manual

mysqli::ping

mysqli_ping

(PHP 5)

mysqli::ping -- mysqli_ping — Pings a server connection, or tries to reconnect if the connection has gone down

Opis

Styl obiektowy

bool mysqli::ping ( void )

Styl proceduralny

bool mysqli_ping ( mysqli $link )

Checks whether the connection to the server is working. If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mysqli::ping() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* check if server is alive */
if ($mysqli->ping()) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* check if server is alive */
if (mysqli_ping($link)) {
    printf ("Our connection is ok!\n");
} else {
    printf ("Error: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Our connection is ok!
mysqli::options
mysqli::poll
mysqli


Poll connections

mysqli::ping
mysqli::prepare
mysqli
PHP Manual

mysqli::poll

mysqli_poll

(PHP 5 >= 5.3.0)

mysqli::poll -- mysqli_poll — Poll connections

Opis

Styl obiektowy

public int mysqli::poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )

Styl proceduralny

int mysqli_poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Poll connections. Dostępna tylko z mysqlnd.

Parametry

read

error

reject

sec

Number of seconds to wait, must be non-negative.

usec

Number of microseconds to wait, must be non-negative.

Zwracane wartości

Returns number of ready connections in success, FALSE otherwise.

Przykłady

Przykład #1 A mysqli_poll() example

<?php
$link1 = mysqli_connect();
$link1->query("SELECT 'test'", MYSQLI_ASYNC);
$all_links = array($link1);
$processed = 0;
do {
    $links = $errors = $reject = array();
    foreach ($all_links as $link) {
        $links[] = $errors[] = $reject[] = $link;
    }
    if (!mysqli_poll($links, $errors, $reject, 1)) {
        continue;
    }
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            mysqli_free_result($result);
            $processed++;
        }
    }
} while ($processed < count($all_links));
?>

Powyższy przykład wyświetli:

Array
(
    [0] => test
)

Zobacz też:

  • mysqli_query() - Performs a query on the database
  • mysqli_reap_async_query() - Get result from async query

mysqli::ping
mysqli::prepare
mysqli


Prepare an SQL statement for execution

mysqli::poll
mysqli::query
mysqli
PHP Manual

mysqli::prepare

mysqli_prepare

(PHP 5)

mysqli::prepare -- mysqli_prepare — Prepare an SQL statement for execution

Opis

Styl obiektowy

mysqli_stmt mysqli::prepare ( string $query )

Styl proceduralny

mysqli_stmt mysqli_prepare ( mysqli $link , string $query )

Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

query

The query, as a string.

Informacja:

You should not add a terminating semicolon or \g to the statement.

This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Informacja:

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

Zwracane wartości

mysqli_prepare() returns a statement object or FALSE if an error occurred.

Przykłady

Przykład #1 mysqli::prepare() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Amersfoort is in district Utrecht

Zobacz też:

  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_close() - Closes a prepared statement

mysqli::poll
mysqli::query
mysqli


Performs a query on the database

mysqli::prepare
mysqli::real_connect
mysqli
PHP Manual

mysqli::query

mysqli_query

(PHP 5)

mysqli::query -- mysqli_query — Performs a query on the database

Opis

Styl obiektowy

mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Styl proceduralny

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

Performs a query against the database.

Functionally, using this function is identical to calling
mysqli_real_query() followed either by
mysqli_use_result() or
mysqli_store_result().

Informacja:

In the case where you pass a statement to mysqli_query() that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means "got a packet bigger than max_allowed_packet bytes".

  • mysqlnd on Windows returns an error code 2006. This error message means "server has gone away".

  • libmysql on all platforms returns an error code 2006. This error message means "server has gone away".

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

query

The query string.

Data inside the query should be properly escaped.

resultmode

Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result()

With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll() is then used to get results from such queries.

Zwracane wartości

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Rejestr zmian

Wersja | Opis
5.3.0 | Added the ability of async queries.

Przykłady

Przykład #1 mysqli::query() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

    /* free result set */
    mysqli_free_result($result);
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!mysqli_query($link, "SET @a:='this will not work'")) {
        printf("Error: %s\n", mysqli_error($link));
    }
    mysqli_free_result($result);
}

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync;  You can't run this command now

Zobacz też:

  • mysqli_real_query() - Execute an SQL query
  • mysqli_multi_query() - Performs a query on the database
  • mysqli_free_result() - Frees the memory associated with a result

mysqli::prepare
mysqli::real_connect
mysqli


Opens a connection to a mysql server

mysqli::query
mysqli::real_escape_string
mysqli
PHP Manual

mysqli::real_connect

mysqli_real_connect

(PHP 5)

mysqli::real_connect -- mysqli_real_connect — Opens a connection to a mysql server

Opis

Styl obiektowy

bool mysqli::real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

Styl proceduralny

bool mysqli_real_connect ( mysqli $link [, string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] )

Establish a connection to a MySQL database engine.

This function differs from mysqli_connect():

  • mysqli_real_connect() needs a valid object which has to be created by function mysqli_init().

  • With the mysqli_options() function you can set various options for connection.

  • There is a flags parameter.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

username

The MySQL user name.

passwd

If provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

Informacja:

Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.

flags

With the parameter flags you can set different connection options:

Supported flags
Name | Description
MYSQLI_CLIENT_COMPRESS | Use compression protocol
MYSQLI_CLIENT_FOUND_ROWS | return number of matched rows, not the number of affected rows
MYSQLI_CLIENT_IGNORE_SPACE | Allow spaces after function names. Makes all function names reserved words.
MYSQLI_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection
MYSQLI_CLIENT_SSL | Use SSL (encryption)

Informacja:

For security reasons the MULTI_STATEMENT flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query() function.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mysqli::real_connect() example

Styl obiektowy

<?php

$mysqli = mysqli_init();
if (!$mysqli) {
    die('mysqli_init failed');
}

if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

Styl obiektowy when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::init();

        if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
            die('Setting MYSQLI_INIT_COMMAND failed');
        }

        if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
            die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
        }

        if (!parent::real_connect($host, $user, $pass, $db)) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

Styl proceduralny

<?php

$link = mysqli_init();
if (!$link) {
    die('mysqli_init failed');
}

if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Success... MySQL host info: localhost via TCP/IP

Notatki

Informacja:

MySQLnd zawsze przyjmuje domyślne kodowanie znaków serwera. To kodowanie jest przesyłane podczas połączenia hand-shake/authentication, którego używa mysqlnd.

Libmysql używa domyślnego kodowania znaków ustawionego w pliku my.cnf lub przez jawne wywołanie funkcji mysqli_options() przed wywołaniem mysqli_real_connect(), ale po wywołaniu mysqli_init().

Zobacz też:

  • mysqli_connect() - Alias dla mysqli::__construct
  • mysqli_init() - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
  • mysqli_options() - Set options
  • mysqli_ssl_set() - Used for establishing secure connections using SSL
  • mysqli_close() - Closes a previously opened database connection

mysqli::query
mysqli::real_escape_string
mysqli


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

mysqli::real_connect
mysqli::real_query
mysqli
PHP Manual

mysqli::real_escape_string

mysqli_real_escape_string

(PHP 5)

mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

Opis

Styl obiektowy

string mysqli::escape_string ( string $escapestr )
string mysqli::real_escape_string ( string $escapestr )

Styl proceduralny

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

escapestr

The string to be escaped.

Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Zwracane wartości

Returns an escaped string.

Przykłady

Przykład #1 mysqli::real_escape_string() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Error: 42000
1 Row inserted.

Notatki

Informacja:

For those accustomed to using mysql_real_escape_string(),
note that the arguments of mysqli_real_escape_string()
differ from what mysql_real_escape_string() expects.
The link identifier comes first in
mysqli_real_escape_string(), whereas the string to be escaped
comes first in mysql_real_escape_string().

Zobacz też:

  • mysqli_character_set_name() - Returns the default character set for the database connection

mysqli::real_connect
mysqli::real_query
mysqli


Execute an SQL query

mysqli::real_escape_string
mysqli::reap_async_query
mysqli
PHP Manual

mysqli::real_query

mysqli_real_query

(PHP 5)

mysqli::real_query -- mysqli_real_query — Execute an SQL query

Opis

Styl obiektowy

bool mysqli::real_query ( string $query )

Styl proceduralny

bool mysqli_real_query ( mysqli $link , string $query )

Executes a single query against the database whose result can then be retrieved or stored using the mysqli_store_result() or mysqli_use_result() functions.

In order to determine if a given query should return a result set or not, see mysqli_field_count().

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

query

The query, as a string.

Data inside the query should be properly escaped.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mysqli_query() - Performs a query on the database
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli::real_escape_string
mysqli::reap_async_query
mysqli


Get result from async query

mysqli::real_query
mysqli::refresh
mysqli
PHP Manual

mysqli::reap_async_query

mysqli_reap_async_query

(PHP 5 >= 5.3.0)

mysqli::reap_async_query -- mysqli_reap_async_query — Get result from async query

Opis

Styl obiektowy

public mysqli_result mysqli::reap_async_query ( void )

Styl proceduralny

mysqli_result mysqli_reap_async_query ( mysql $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Get result from async query. Dostępna tylko z mysqlnd.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Returns mysqli_result in success, FALSE otherwise.

Zobacz też:

  • mysqli_poll() - Poll connections

mysqli::real_query
mysqli::refresh
mysqli


Refreshes

mysqli::reap_async_query
mysqli::rollback
mysqli
PHP Manual

mysqli::refresh

mysqli_refresh

(PHP 5 <= 5.3.0)

mysqli::refresh -- mysqli_refresh — Refreshes

Opis

Styl obiektowy

public bool mysqli::refresh ( int $options )

Styl proceduralny

int mysqli_refresh ( resource $link , int $options )

Flushes tables or caches, or resets the replication server information.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

options

The options to refresh, using the MYSQLI_REFRESH_* constants as documented within the MySQLi constants documentation.

See also the official » MySQL Refresh documentation.

Zwracane wartości

TRUE if the refresh was a success, otherwise FALSE

Zobacz też:

  • mysqli_poll() - Poll connections

mysqli::reap_async_query
mysqli::rollback
mysqli


Rolls back current transaction

mysqli::refresh
mysqli::rpl_query_type
mysqli
PHP Manual

mysqli::rollback

mysqli_rollback

(PHP 5)

mysqli::rollback -- mysqli_rollback — Rolls back current transaction

Opis

Styl obiektowy

bool mysqli::rollback ( void )

Styl proceduralny

bool mysqli_rollback ( mysqli $link )

Rollbacks the current transaction for the database.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mysqli::rollback() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

$mysqli->query("CREATE TABLE myCity LIKE City");
$mysqli->query("ALTER TABLE myCity Type=InnoDB");
$mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
$mysqli->commit();

/* delete all rows */
$mysqli->query("DELETE FROM myCity");

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Rollback */
$mysqli->rollback();

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Drop table myCity */
$mysqli->query("DROP TABLE myCity");

$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE myCity LIKE City");
mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");
mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
mysqli_commit($link);

/* delete all rows */
mysqli_query($link, "DELETE FROM myCity");

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Rollback */
mysqli_rollback($link);

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Drop table myCity */
mysqli_query($link, "DROP TABLE myCity");

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

0 rows in table myCity.
50 rows in table myCity (after rollback).

Zobacz też:

  • mysqli_commit() - Commits the current transaction
  • mysqli_autocommit() - Turns on or off auto-commiting database modifications

mysqli::refresh
mysqli::rpl_query_type
mysqli


Returns RPL query type

mysqli::rollback
mysqli::select_db
mysqli
PHP Manual

mysqli::rpl_query_type

mysqli_rpl_query_type

(PHP 5)

mysqli::rpl_query_type -- mysqli_rpl_query_type — Returns RPL query type

Opis

Styl obiektowy

int mysqli::rpl_query_type ( string $query )

Styl proceduralny

int mysqli_rpl_query_type ( mysqli $link , string $query )

Returns MYSQLI_RPL_MASTER, MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. INSERT, UPDATE and similar are master queries, SELECT is slave, and FLUSH, REPAIR and similar are admin.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli::rollback
mysqli::select_db
mysqli


Selects the default database for database queries

mysqli::rpl_query_type
mysqli::send_query
mysqli
PHP Manual

mysqli::select_db

mysqli_select_db

(PHP 5)

mysqli::select_db -- mysqli_select_db — Selects the default database for database queries

Opis

Styl obiektowy

bool mysqli::select_db ( string $dbname )

Styl proceduralny

bool mysqli_select_db ( mysqli $link , string $dbname )

Selects the default database to be used when performing queries against the database connection.

Informacja:

This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect().

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

dbname

The database name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mysqli::select_db() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

/* change db to world db */
$mysqli->select_db("world");

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* change db to world db */
mysqli_select_db($link, "world");

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Default database is test.
Default database is world.

Zobacz też:

  • mysqli_connect() - Alias dla mysqli::__construct
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli::rpl_query_type
mysqli::send_query
mysqli


Send the query and return

mysqli::select_db
mysqli::set_charset
mysqli
PHP Manual

mysqli::send_query

mysqli_send_query

(PHP 5)

mysqli::send_query -- mysqli_send_query — Send the query and return

Opis

Styl obiektowy

bool mysqli::send_query ( string $query )

Styl proceduralny

bool mysqli_send_query ( mysqli $link , string $query )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli::select_db
mysqli::set_charset
mysqli


Sets the default client character set

mysqli::send_query
mysqli::set_local_infile_default
mysqli
PHP Manual

mysqli::set_charset

mysqli_set_charset

(PHP 5 >= 5.0.5)

mysqli::set_charset -- mysqli_set_charset — Sets the default client character set

Opis

Styl obiektowy

bool mysqli::set_charset ( string $charset )

Styl proceduralny

bool mysqli_set_charset ( mysqli $link , string $charset )

Sets the default character set to be used when sending data from and to the database server.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

charset

The charset to be set as default.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above).

Informacja:

This is the preferred way to change the charset. Using mysqli::query() to execute SET NAMES .. is not recommended.

Przykłady

Przykład #1 mysqli::set_charset() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* change character set to utf8 */
if (!mysqli_set_charset($link, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Current character set: utf8

Zobacz też:

  • mysqli_character_set_name() - Returns the default character set for the database connection
  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • » List of character sets that MySQL supports

mysqli::send_query
mysqli::set_local_infile_default
mysqli


Unsets user defined handler for load local infile command

mysqli::set_charset
mysqli::set_local_infile_handler
mysqli
PHP Manual

mysqli::set_local_infile_default

mysqli_set_local_infile_default

(PHP 5)

mysqli::set_local_infile_default -- mysqli_set_local_infile_default — Unsets user defined handler for load local infile command

Opis

void mysqli_set_local_infile_default ( mysqli $link )

Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler().

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

See mysqli_set_local_infile_handler() examples

Zobacz też:

  • mysqli_set_local_infile_handler() - Set callback function for LOAD DATA LOCAL INFILE command

mysqli::set_charset
mysqli::set_local_infile_handler
mysqli


Set callback function for LOAD DATA LOCAL INFILE command

mysqli::set_local_infile_default
mysqli::$sqlstate
mysqli
PHP Manual

mysqli::set_local_infile_handler

mysqli_set_local_infile_handler

(PHP 5)

mysqli::set_local_infile_handler -- mysqli_set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command

Opis

Styl obiektowy

bool mysqli::set_local_infile_handler ( mysqli $link , callback $read_func )

Styl proceduralny

bool mysqli_set_local_infile_handler ( mysqli $link , callback $read_func )

Set callback function for LOAD DATA LOCAL INFILE command

The callbacks task is to read input from the file specified in the LOAD DATA LOCAL INFILE and to reformat it into the format understood by LOAD DATA INFILE.

The returned data needs to match the format specified in the LOAD DATA

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

read_func

A callback function or object method taking the following parameters:

stream

A PHP stream associated with the SQL commands INFILE

&buffer

A string buffer to store the rewritten input into

buflen

The maximum number of characters to be stored in the buffer

&errormsg

If an error occurs you can store an error message in here

The callback function should return the number of characters stored in the buffer or a negative value if an error occurred.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mysqli::set_local_infile_handler() example

Styl obiektowy

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // convert to upper case and replace "," delimiter with [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }

  echo "Input:\n";

  $db->set_local_infile_handler("callme");
  $db->query("LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  $db->set_local_infile_default();

  $res = $db->query("SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = $res->fetch_assoc()) {
    echo join(",", $row)."\n";
  }
?>

Styl proceduralny

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // convert to upper case and replace "," delimiter with [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }

  echo "Input:\n";

  mysqli_set_local_infile_handler($db, "callme");
  mysqli_query($db, "LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  mysqli_set_local_infile_default($db);

  $res = mysqli_query($db, "SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = mysqli_fetch_assoc($res)) {
    echo join(",", $row)."\n";
  }
?>

Powyższe przykłady wyświetlą:

Input:
23,foo
42,bar

Output:
23,FOO
42,BAR

Zobacz też:

  • mysqli_set_local_infile_default() - Unsets user defined handler for load local infile command

mysqli::set_local_infile_default
mysqli::$sqlstate
mysqli


Returns the SQLSTATE error from previous MySQL operation

mysqli::set_local_infile_handler
mysqli::ssl_set
mysqli
PHP Manual

mysqli::$sqlstate

mysqli_sqlstate

(PHP 5)

mysqli::$sqlstate -- mysqli_sqlstate — Returns the SQLSTATE error from previous MySQL operation

Opis

Styl obiektowy

string $mysqli->sqlstate;

Styl proceduralny

string mysqli_sqlstate ( mysqli $link )

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

Informacja:

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Przykłady

Przykład #1 $mysqli->sqlstate example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}

$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Error - SQLSTATE 42S01.

Zobacz też:

  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error

mysqli::set_local_infile_handler
mysqli::ssl_set
mysqli


Used for establishing secure connections using SSL

mysqli::$sqlstate
mysqli::stat
mysqli
PHP Manual

mysqli::ssl_set

mysqli_ssl_set

(PHP 5)

mysqli::ssl_set -- mysqli_ssl_set — Used for establishing secure connections using SSL

Opis

Styl obiektowy

bool mysqli::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher )

Styl proceduralny

bool mysqli_ssl_set ( mysqli $link , string $key , string $cert , string $ca , string $capath , string $cipher )

Used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.

Note that MySQL Native Driver does not support SSL before PHP 5.3.3, so calling this function when using MySQL Native Driver will result in an error. MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5.3 onwards.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

key

The path name to the key file.

cert

The path name to the certificate file.

ca

The path name to the certificate authority file.

capath

The pathname to a directory that contains trusted SSL CA certificates in PEM format.

cipher

A list of allowable ciphers to use for SSL encryption.

Any unused SSL parameters may be given as NULL

Zwracane wartości

This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.

Zobacz też:

  • mysqli_options() - Set options
  • mysqli_real_connect() - Opens a connection to a mysql server

mysqli::$sqlstate
mysqli::stat
mysqli


Gets the current system status

mysqli::ssl_set
mysqli::stmt_init
mysqli
PHP Manual

mysqli::stat

mysqli_stat

(PHP 5)

mysqli::stat -- mysqli_stat — Gets the current system status

Opis

Styl obiektowy

string mysqli::stat ( void )

Styl proceduralny

string mysqli_stat ( mysqli $link )

mysqli_stat() returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

A string describing the server status. FALSE if an error occurred.

Przykłady

Przykład #1 mysqli::stat() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("System status: %s\n", $mysqli->stat());

$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("System status: %s\n", mysqli_stat($link));

mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

System status: Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0
Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632
Memory in use: 8496K  Max memory used: 8560K

Zobacz też:

  • mysqli_get_server_info() - Returns the version of the MySQL server

mysqli::ssl_set
mysqli::stmt_init
mysqli


Initializes a statement and returns an object for use with mysqli_stmt_prepare

mysqli::stat
mysqli::store_result
mysqli
PHP Manual

mysqli::stmt_init

mysqli_stmt_init

(PHP 5)

mysqli::stmt_init -- mysqli_stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare

Opis

Styl obiektowy

mysqli_stmt mysqli::stmt_init ( void )

Styl proceduralny

mysqli_stmt mysqli_stmt_init ( mysqli $link )

Allocates and initializes a statement object suitable for mysqli_stmt_prepare().

Informacja:

Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare() was called.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Returns an object.

Zobacz też:

  • mysqli_stmt_prepare() - Prepare an SQL statement for execution

mysqli::stat
mysqli::store_result
mysqli


Transfers a result set from the last query

mysqli::stmt_init
mysqli::$thread_id
mysqli
PHP Manual

mysqli::store_result

mysqli_store_result

(PHP 5)

mysqli::store_result -- mysqli_store_result — Transfers a result set from the last query

Opis

Styl obiektowy

mysqli_result mysqli::store_result ( void )

Styl proceduralny

mysqli_result mysqli_store_result ( mysqli $link )

Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek() function.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Returns a buffered result object or FALSE if an error occurred.

Informacja:

mysqli_store_result() returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error() doesn't return an empty string, if mysqli_errno() returns a non zero value, or if mysqli_field_count() returns a non zero value. Also possible reason for this function returning FALSE after successful call to mysqli_query() can be too large result set (memory for it cannot be allocated). If mysqli_field_count() returns a non-zero value, the statement should have produced a non-empty result set.

Notatki

Informacja:

Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result() function, when transferring large result sets using the mysqli_store_result() this becomes particularly important.

Przykłady

See mysqli_multi_query().

Zobacz też:

  • mysqli_real_query() - Execute an SQL query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli::stmt_init
mysqli::$thread_id
mysqli


Returns the thread ID for the current connection

mysqli::store_result
mysqli::thread_safe
mysqli
PHP Manual

mysqli::$thread_id

mysqli_thread_id

(PHP 5)

mysqli::$thread_id -- mysqli_thread_id — Returns the thread ID for the current connection

Opis

Styl obiektowy

int $mysqli->thread_id;

Styl proceduralny

int mysqli_thread_id ( mysqli $link )

The mysqli_thread_id() function returns the thread ID for the current connection which can then be killed using the mysqli_kill() function. If the connection is lost and you reconnect with mysqli_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.

Informacja:

The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.

To kill a running query you can use the SQL command KILL QUERY processid.

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Returns the Thread ID for the current connection.

Przykłady

Przykład #1 $mysqli->thread_id example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = $mysqli->thread_id;

/* Kill connection */
$mysqli->kill($thread_id);

/* This should produce an error */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", $mysqli->error);
    exit;
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* determine our thread id */
$thread_id = mysqli_thread_id($link);

/* Kill connection */
mysqli_kill($link, $thread_id);

/* This should produce an error */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
    printf("Error: %s\n", mysqli_error($link));
    exit;
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Error: MySQL server has gone away

Zobacz też:

  • mysqli_kill() - Asks the server to kill a MySQL thread

mysqli::store_result
mysqli::thread_safe
mysqli


Returns whether thread safety is given or not

mysqli::$thread_id
mysqli::use_result
mysqli
PHP Manual

mysqli::thread_safe

mysqli_thread_safe

(PHP 5)

mysqli::thread_safe -- mysqli_thread_safe — Returns whether thread safety is given or not

Opis

Styl proceduralny

bool mysqli_thread_safe ( void )

Tells whether the client library is compiled as thread-safe.

Zwracane wartości

TRUE if the client library is thread-safe, otherwise FALSE.

mysqli::$thread_id
mysqli::use_result
mysqli


Initiate a result set retrieval

mysqli::thread_safe
mysqli::$warning_count
mysqli
PHP Manual

mysqli::use_result

mysqli_use_result

(PHP 5)

mysqli::use_result -- mysqli_use_result — Initiate a result set retrieval

Opis

Styl obiektowy

mysqli_result mysqli::use_result ( void )

Styl proceduralny

mysqli_result mysqli_use_result ( mysqli $link )

Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection.

Either this or the mysqli_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.

Informacja:

The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

Zwracane wartości

Returns an unbuffered result object or FALSE if an error occurred.

Przykłady

Przykład #1 mysqli::use_result() example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->use_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->close();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
    do {
        /* store first result set */
        if ($result = mysqli_use_result($link)) {
            while ($row = mysqli_fetch_row($result)) {
                printf("%s\n", $row[0]);
            }
            mysqli_free_result($result);
        }
        /* print divider */
        if (mysqli_more_results($link)) {
            printf("-----------------\n");
        }
    } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

Zobacz też:

  • mysqli_real_query() - Execute an SQL query
  • mysqli_store_result() - Transfers a result set from the last query

mysqli::thread_safe
mysqli::$warning_count
mysqli


Returns the number of warnings from the last query for the given link

mysqli::use_result
mysqli_stmt
mysqli
PHP Manual

mysqli::$warning_count

mysqli_warning_count

(PHP 5)

mysqli::$warning_count -- mysqli_warning_count — Returns the number of warnings from the last query for the given link

Opis

Styl obiektowy

int $mysqli->warning_count;

Styl proceduralny

int mysqli_warning_count ( mysqli $link )

Returns the number of warnings from the last query in the connection.

Informacja:

For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

Parametry

połączenie

Tylko styl proceduralny: Identyfikator połączenia zwrócony przez mysqli_connect() lub mysqli_init()

Zwracane wartości

Number of warnings or zero if there are no warnings.

Przykłady

Przykład #1 $mysqli->warning_count example

Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$mysqli->query($query);

if ($mysqli->warning_count) {
    if ($result = $mysqli->query("SHOW WARNINGS")) {
        $row = $result->fetch_row();
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        $result->close();
    }
}

/* close connection */
$mysqli->close();
?>

Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* a remarkable long city name in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

mysqli_query($link, $query);

if (mysqli_warning_count($link)) {
    if ($result = mysqli_query($link, "SHOW WARNINGS")) {
        $row = mysqli_fetch_row($result);
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        mysqli_free_result($result);
    }
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Warning (1264): Data truncated for column 'Name' at row 1

Zobacz też:

  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation

mysqli::use_result
mysqli_stmt
mysqli


The mysqli_stmt class

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

Wstęp

Represents a prepared statement.

Krótki opis klasy

mysqli_stmt {
/* Właściwości */
int $affected_rows;
int $errno;
string $error;
int $field_count;
int $insert_id;
int $num_rows;
int $param_count;
string $sqlstate;
/* Metody */
int attr_get ( int $attr )
bool attr_set ( int $attr , int $mode )
bool bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
bool bind_result ( mixed &$var1 [, mixed &$... ] )
bool close ( void )
void data_seek ( int $offset )
bool execute ( void )
bool fetch ( void )
void free_result ( void )
mysqli_result get_result ( void )
object get_warnings ( mysqli_stmt $stmt )
mixed prepare ( string $query )
bool reset ( void )
mysqli_result result_metadata ( void )
bool send_long_data ( int $param_nr , string $data )
bool store_result ( void )
}

Spis treści

  • mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • mysqli_stmt::attr_get — Used to get the current value of a statement attribute
  • mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
  • mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
  • mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
  • mysqli_stmt::close — Closes a prepared statement
  • mysqli_stmt::data_seek — Seeks to an arbitrary row in statement result set
  • mysqli_stmt::$errno — Returns the error code for the most recent statement call
  • mysqli_stmt::$error — Returns a string description for last statement error
  • mysqli_stmt::execute — Executes a prepared Query
  • mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
  • mysqli_stmt::$field_count — Returns the number of field in the given statement
  • mysqli_stmt::free_result — Frees stored result memory for the given statement handle
  • mysqli_stmt::get_result — Gets a result set from a prepared statement
  • mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
  • mysqli_stmt::$insert_id — Get the ID generated from the previous INSERT operation
  • mysqli_stmt::$num_rows — Return the number of rows in statements result set
  • mysqli_stmt::$param_count — Returns the number of parameter for the given statement
  • mysqli_stmt::prepare — Prepare an SQL statement for execution
  • mysqli_stmt::reset — Resets a prepared statement
  • mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
  • mysqli_stmt::send_long_data — Send data in blocks
  • mysqli_stmt::$sqlstate — Returns SQLSTATE error from previous statement operation
  • mysqli_stmt::store_result — Transfers a result set from a prepared statement
mysqli::$warning_count
mysqli_stmt::$affected_rows
Mysqli


Returns the total number of rows changed, deleted, or inserted by the last executed statement

mysqli_stmt
mysqli_stmt::attr_get
mysqli_stmt
PHP Manual

mysqli_stmt::$affected_rows

mysqli_stmt_affected_rows

(PHP 5)

mysqli_stmt::$affected_rows -- mysqli_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement

Opis

Styl obiektowy

int $mysqli_stmt->affected_rows;

Styl proceduralny

int mysqli_stmt_affected_rows ( mysqli_stmt $stmt )

Returns the number of rows affected by INSERT, UPDATE, or DELETE query.

This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows() instead.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error. NULL indicates an invalid argument was supplied to the function.

Informacja:

If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    $stmt->bind_param("s", $code);

    /* execute statement */
    $stmt->execute();

    printf("rows inserted: %d\n", $stmt->affected_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($stmt = mysqli_prepare($link, $query)) {

    /* Bind variable for placeholder */
    $code = 'A%';
    mysqli_stmt_bind_param($stmt, "s", $code);

    /* execute statement */
    mysqli_stmt_execute($stmt);

    printf("rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

rows inserted: 17

Zobacz też:

  • mysqli_stmt_num_rows() - Return the number of rows in statements result set
  • mysqli_prepare() - Prepare an SQL statement for execution

mysqli_stmt
mysqli_stmt::attr_get
mysqli_stmt


Used to get the current value of a statement attribute

mysqli_stmt::$affected_rows
mysqli_stmt::attr_set
mysqli_stmt
PHP Manual

mysqli_stmt::attr_get

mysqli_stmt_attr_get

(PHP 5)

mysqli_stmt::attr_get -- mysqli_stmt_attr_get — Used to get the current value of a statement attribute

Opis

Styl obiektowy

int mysqli_stmt::attr_get ( int $attr )

Styl proceduralny

int mysqli_stmt_attr_get ( mysqli_stmt $stmt , int $attr )

Gets the current value of a statement attribute.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

attr

The attribute that you want to get.

Zwracane wartości

Returns FALSE if the attribute is not found, otherwise returns the value of the attribute.

mysqli_stmt::$affected_rows
mysqli_stmt::attr_set
mysqli_stmt


Used to modify the behavior of a prepared statement

mysqli_stmt::attr_get
mysqli_stmt::bind_param
mysqli_stmt
PHP Manual

mysqli_stmt::attr_set

mysqli_stmt_attr_set

(PHP 5)

mysqli_stmt::attr_set -- mysqli_stmt_attr_set — Used to modify the behavior of a prepared statement

Opis

Styl obiektowy

bool mysqli_stmt::attr_set ( int $attr , int $mode )

Styl proceduralny

bool mysqli_stmt_attr_set ( mysqli_stmt $stmt , int $attr , int $mode )

Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

attr

The attribute that you want to set. It can have one of the following values:

Attribute values
Character | Description
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH | If set to 1, causes mysqli_stmt_store_result() to update the metadata MYSQL_FIELD->max_length value.
MYSQLI_STMT_ATTR_CURSOR_TYPE | Type of cursor to open for statement when mysqli_stmt_execute() is invoked. mode can be MYSQLI_CURSOR_TYPE_NO_CURSOR (the default) or MYSQLI_CURSOR_TYPE_READ_ONLY.
MYSQLI_STMT_ATTR_PREFETCH_ROWS | Number of rows to fetch from server at a time when using a cursor. mode can be in the range from 1 to the maximum value of unsigned long. The default is 1.

If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement when you invoke mysqli_stmt_execute(). If there is already an open cursor from a previous mysqli_stmt_execute() call, it closes the cursor before opening a new one. mysqli_stmt_reset() also closes any open cursor before preparing the statement for re-execution. mysqli_stmt_free_result() closes any open cursor.

If you open a cursor for a prepared statement, mysqli_stmt_store_result() is unnecessary.

mode

The value to assign to the attribute.

mysqli_stmt::attr_get
mysqli_stmt::bind_param
mysqli_stmt


Binds variables to a prepared statement as parameters

mysqli_stmt::attr_set
mysqli_stmt::bind_result
mysqli_stmt
PHP Manual

mysqli_stmt::bind_param

mysqli_stmt_bind_param

(PHP 5)

mysqli_stmt::bind_param -- mysqli_stmt_bind_param — Binds variables to a prepared statement as parameters

Opis

Styl obiektowy

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

Styl proceduralny

bool mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed &$var1 [, mixed &$... ] )

Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare().

Informacja:

If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packets.

Informacja:

Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

types

A string that contains one or more characters which specify the types for the corresponding bind variables:

Type specification chars
Character | Description
i | corresponding variable has type integer
d | corresponding variable has type double
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packets

var1

The number of variables and length of string types must match the parameters in the statement.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

1 Row inserted.
1 Row deleted.

Zobacz też:

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_send_long_data() - Send data in blocks
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

mysqli_stmt::attr_set
mysqli_stmt::bind_result
mysqli_stmt


Binds variables to a prepared statement for result storage

mysqli_stmt::bind_param
mysqli_stmt::close
mysqli_stmt
PHP Manual

mysqli_stmt::bind_result

mysqli_stmt_bind_result

(PHP 5)

mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables to a prepared statement for result storage

Opis

Styl obiektowy

bool mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] )

Styl proceduralny

bool mysqli_stmt_bind_result ( mysqli_stmt $stmt , mixed &$var1 [, mixed &$... ] )

Binds columns in the result set to variables.

When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....

Informacja:

Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.

A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

var1

The variable to be bound.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($col1, $col2);

    /* fetch values */
    while ($stmt->fetch()) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();

?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
    mysqli_stmt_execute($stmt);

    /* bind variables to prepared statement */
    mysqli_stmt_bind_result($stmt, $col1, $col2);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf("%s %s\n", $col1, $col2);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra

Zobacz też:

  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

mysqli_stmt::bind_param
mysqli_stmt::close
mysqli_stmt


Closes a prepared statement

mysqli_stmt::bind_result
mysqli_stmt::data_seek
mysqli_stmt
PHP Manual

mysqli_stmt::close

mysqli_stmt_close

(PHP 5)

mysqli_stmt::close -- mysqli_stmt_close — Closes a prepared statement

Opis

Styl obiektowy

bool mysqli_stmt::close ( void )

Styl proceduralny

bool mysqli_stmt_close ( mysqli_stmt $stmt )

Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution

mysqli_stmt::bind_result
mysqli_stmt::data_seek
mysqli_stmt


Seeks to an arbitrary row in statement result set

mysqli_stmt::close
mysqli_stmt::$errno
mysqli_stmt
PHP Manual

mysqli_stmt::data_seek

mysqli_stmt_data_seek

(PHP 5)

mysqli_stmt::data_seek -- mysqli_stmt_data_seek — Seeks to an arbitrary row in statement result set

Opis

Styl obiektowy

void mysqli_stmt::data_seek ( int $offset )

Styl proceduralny

void mysqli_stmt_data_seek ( mysqli_stmt $stmt , int $offset )

Seeks to an arbitrary result pointer in the statement result set.

mysqli_stmt_store_result() must be called prior to mysqli_stmt_data_seek().

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

offset

Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows() - 1).

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* store result */
    $stmt->store_result();

    /* seek to row no. 400 */
    $stmt->data_seek(399);

    /* fetch values */
    $stmt->fetch();

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* store result */
    mysqli_stmt_store_result($stmt);

    /* seek to row no. 400 */
    mysqli_stmt_data_seek($stmt, 399);

    /* fetch values */
    mysqli_stmt_fetch($stmt);

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

City: Benin City  Countrycode: NGA

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution

mysqli_stmt::close
mysqli_stmt::$errno
mysqli_stmt


Returns the error code for the most recent statement call

mysqli_stmt::data_seek
mysqli_stmt::$error
mysqli_stmt
PHP Manual

mysqli_stmt::$errno

mysqli_stmt_errno

(PHP 5)

mysqli_stmt::$errno -- mysqli_stmt_errno — Returns the error code for the most recent statement call

Opis

Styl obiektowy

int $mysqli_stmt->errno;

Styl proceduralny

int mysqli_stmt_errno ( mysqli_stmt $stmt )

Returns the error code for the most recently invoked statement function that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

An error code value. Zero means no error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %d.\n", $stmt->errno);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %d.\n", mysqli_stmt_errno($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Error: 1146.

Zobacz też:

  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

mysqli_stmt::data_seek
mysqli_stmt::$error
mysqli_stmt


Returns a string description for last statement error

mysqli_stmt::$errno
mysqli_stmt::execute
mysqli_stmt
PHP Manual

mysqli_stmt::$error

mysqli_stmt_error

(PHP 5)

mysqli_stmt::$error -- mysqli_stmt_error — Returns a string description for last statement error

Opis

Styl obiektowy

string $mysqli_stmt->error;

Styl proceduralny

string mysqli_stmt_error ( mysqli_stmt $stmt )

Returns a containing the error message for the most recently invoked statement function that can succeed or fail.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

A string that describes the error. An empty string if no error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->error);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_error($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Error: Table 'world.myCountry' doesn't exist.

Zobacz też:

  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

mysqli_stmt::$errno
mysqli_stmt::execute
mysqli_stmt


Executes a prepared Query

mysqli_stmt::$error
mysqli_stmt::fetch
mysqli_stmt
PHP Manual

mysqli_stmt::execute

mysqli_stmt_execute

(PHP 5)

mysqli_stmt::execute -- mysqli_stmt_execute — Executes a prepared Query

Opis

Styl obiektowy

bool mysqli_stmt::execute ( void )

Styl proceduralny

bool mysqli_stmt_execute ( mysqli_stmt $stmt )

Executes a query that has been previously prepared using the mysqli_prepare() function. When executed any parameter markers which exist will automatically be replaced with the appropriate data.

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. Likewise, if the query yields a result set the mysqli_stmt_fetch() function is used.

Informacja:

When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
$stmt->execute();

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    $result->close();
}

/* remove table */
$mysqli->query("DROP TABLE myCity");

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $query);

mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
mysqli_stmt_execute($stmt);

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
mysqli_stmt_execute($stmt);

/* close statement */
mysqli_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_row($result)) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    mysqli_free_result($result);
}

/* remove table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

mysqli_stmt::$error
mysqli_stmt::fetch
mysqli_stmt


Fetch results from a prepared statement into the bound variables

mysqli_stmt::execute
mysqli_stmt::$field_count
mysqli_stmt
PHP Manual

mysqli_stmt::fetch

mysqli_stmt_fetch

(PHP 5)

mysqli_stmt::fetch -- mysqli_stmt_fetch — Fetch results from a prepared statement into the bound variables

Opis

Styl obiektowy

bool mysqli_stmt::fetch ( void )

Styl proceduralny

bool mysqli_stmt_fetch ( mysqli_stmt $stmt )

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().

Informacja:

Note that all columns must be bound by the application before calling mysqli_stmt_fetch().

Informacja:

Data are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Zwracane wartości
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occurred
NULL | No more rows/data exists or data truncation occurred

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

    /* execute statement */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = mysqli_prepare($link, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* fetch values */
    while (mysqli_stmt_fetch($stmt)) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

mysqli_stmt::execute
mysqli_stmt::$field_count
mysqli_stmt


Returns the number of field in the given statement

mysqli_stmt::fetch
mysqli_stmt::free_result
mysqli_stmt
PHP Manual

mysqli_stmt::$field_count

mysqli_stmt_field_count

(PHP 5)

mysqli_stmt::$field_count -- mysqli_stmt_field_count — Returns the number of field in the given statement

Opis

Styl obiektowy

int $mysqli_stmt->field_count;

Styl proceduralny

int mysqli_stmt_field_count ( mysqli_stmt $stmt )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

mysqli_stmt::fetch
mysqli_stmt::free_result
mysqli_stmt


Frees stored result memory for the given statement handle

mysqli_stmt::$field_count
mysqli_stmt::get_result
mysqli_stmt
PHP Manual

mysqli_stmt::free_result

mysqli_stmt_free_result

(PHP 5)

mysqli_stmt::free_result -- mysqli_stmt_free_result — Frees stored result memory for the given statement handle

Opis

Styl obiektowy

void mysqli_stmt::free_result ( void )

Styl proceduralny

void mysqli_stmt_free_result ( mysqli_stmt $stmt )

Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result().

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement

mysqli_stmt::$field_count
mysqli_stmt::get_result
mysqli_stmt


Gets a result set from a prepared statement

mysqli_stmt::free_result
mysqli_stmt::get_warnings
mysqli_stmt
PHP Manual

mysqli_stmt::get_result

mysqli_stmt_get_result

(PHP 5 >= 5.3.0)

mysqli_stmt::get_result -- mysqli_stmt_get_result — Gets a result set from a prepared statement

Opis

Styl obiektowy

mysqli_result mysqli_stmt::get_result ( void )

Styl proceduralny

mysqli_result mysqli_stmt_get_result ( mysqli_stmt $stmt )

Call to return a result set from a prepared statement query.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Returns a resultset lub FALSE w przypadku niepowodzenia.

Wyłączenie w natywnym sterowniku MySQL

Dostępna tylko z mysqlnd.

Przykłady

Przykład #1 Styl obiektowy

<?php

$mysqli = new mysqli("127.0.0.1", "user", "password", "world");

if($mysqli->connect_error)
{
    die("$mysqli->connect_errno: $myslqi->connect_error");
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query))
{
    print "Failed to prepare statement\n";
}
else
{
    $stmt->bind_param("s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array as $continent)
    {
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_array(MYSQLI_NUM))
        {
            foreach ($row as $r)
            {
                print "$r ";
            }
            print "\n";
        }
    }
}

$stmt->close();
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php

$link = mysqli_connect("127.0.0.1", "user", "password", "world");

if (!$link)
{
    $error = mysqli_connect_error();
    $errno = mysqli_connect_errno();
    print "$errno: $error\n";
    exit();
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = mysqli_stmt_init($link);
if(!mysqli_stmt_prepare($stmt, $query))
{
    print "Failed to prepare statement\n";
}
else
{
    mysqli_stmt_bind_param($stmt, "s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array as $continent)
    {
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
        {
            foreach ($row as $r)
            {
                print "$r ";
            }
            print "\n";
        }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Albania 3401200 Europe
Algeria 31471000 Africa
Afghanistan 22720000 Asia
Anguilla 8000 North America

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement

mysqli_stmt::free_result
mysqli_stmt::get_warnings
mysqli_stmt


Get result of SHOW WARNINGS

mysqli_stmt::get_result
mysqli_stmt::$insert_id
mysqli_stmt
PHP Manual

mysqli_stmt::get_warnings

mysqli_stmt_get_warnings

(PHP 5 >= 5.1.0)

mysqli_stmt::get_warnings -- mysqli_stmt_get_warnings — Get result of SHOW WARNINGS

Opis

Styl obiektowy

object mysqli_stmt::get_warnings ( mysqli_stmt $stmt )

Styl proceduralny

object mysqli_stmt_get_warnings ( mysqli_stmt $stmt )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

mysqli_stmt::get_result
mysqli_stmt::$insert_id
mysqli_stmt


Get the ID generated from the previous INSERT operation

mysqli_stmt::get_warnings
mysqli_stmt::$num_rows
mysqli_stmt
PHP Manual

mysqli_stmt::$insert_id

mysqli_stmt_insert_id

(PHP 5)

mysqli_stmt::$insert_id -- mysqli_stmt_insert_id — Get the ID generated from the previous INSERT operation

Opis

Styl obiektowy

int $mysqli_stmt->insert_id;

Styl proceduralny

mixed mysqli_stmt_insert_id ( mysqli_stmt $stmt )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

mysqli_stmt::get_warnings
mysqli_stmt::$num_rows
mysqli_stmt


Return the number of rows in statements result set

mysqli_stmt::$insert_id
mysqli_stmt::$param_count
mysqli_stmt
PHP Manual

mysqli_stmt::$num_rows

mysqli_stmt_num_rows

(PHP 5)

mysqli_stmt::$num_rows -- mysqli_stmt_num_rows — Return the number of rows in statements result set

Opis

Styl obiektowy

int $mysqli_stmt->num_rows;

Styl proceduralny

int mysqli_stmt_num_rows ( mysqli_stmt $stmt )

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

An integer representing the number of rows in result set.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Number of rows: 20.

Zobacz też:

  • mysqli_stmt_affected_rows() - Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement

mysqli_stmt::$insert_id
mysqli_stmt::$param_count
mysqli_stmt


Returns the number of parameter for the given statement

mysqli_stmt::$num_rows
mysqli_stmt::prepare
mysqli_stmt
PHP Manual

mysqli_stmt::$param_count

mysqli_stmt_param_count

(PHP 5)

mysqli_stmt::$param_count -- mysqli_stmt_param_count — Returns the number of parameter for the given statement

Opis

Styl obiektowy

int $mysqli_stmt->param_count;

Styl proceduralny

int mysqli_stmt_param_count ( mysqli_stmt $stmt )

Returns the number of parameter markers present in the prepared statement.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Returns an integer representing the number of parameters.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = $stmt->param_count;
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = mysqli_prepare($link, "SELECT Name FROM Country WHERE Name=? OR Code=?")) {

    $marker = mysqli_stmt_param_count($stmt);
    printf("Statement has %d markers.\n", $marker);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Statement has 2 markers.

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution

mysqli_stmt::$num_rows
mysqli_stmt::prepare
mysqli_stmt


Prepare an SQL statement for execution

mysqli_stmt::$param_count
mysqli_stmt::reset
mysqli_stmt
PHP Manual

mysqli_stmt::prepare

mysqli_stmt_prepare

(PHP 5)

mysqli_stmt::prepare -- mysqli_stmt_prepare — Prepare an SQL statement for execution

Opis

Styl obiektowy

mixed mysqli_stmt::prepare ( string $query )

Styl proceduralny

bool mysqli_stmt_prepare ( mysqli_stmt $stmt , string $query )

Prepares the SQL query pointed to by the null-terminated string query.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

Informacja:

In the case where you pass a statement to mysqli_stmt_prepare() that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysql). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means "got a packet bigger than max_allowed_packet bytes".

  • mysqlnd on Windows returns an error code 2006. This error message means "server has gone away".

  • libmysql on all platforms returns an error code 2006. This error message means "server has gone away".

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

query

The query, as a string. It must consist of a single SQL statement.

You can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Informacja:

You should not add a terminating semicolon or \g to the statement.

Informacja:

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.

However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt =  $mysqli->stmt_init();
if ($stmt->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, 'SELECT District FROM City WHERE Name=?')) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Amersfoort is in district Utrecht

Zobacz też:

  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_close() - Closes a prepared statement

mysqli_stmt::$param_count
mysqli_stmt::reset
mysqli_stmt


Resets a prepared statement

mysqli_stmt::prepare
mysqli_stmt::result_metadata
mysqli_stmt
PHP Manual

mysqli_stmt::reset

mysqli_stmt_reset

(PHP 5)

mysqli_stmt::reset -- mysqli_stmt_reset — Resets a prepared statement

Opis

Styl obiektowy

bool mysqli_stmt::reset ( void )

Styl proceduralny

bool mysqli_stmt_reset ( mysqli_stmt $stmt )

Resets a prepared statement on client and server to state after prepare.

It resets the statement on the server, data sent using mysqli_stmt_send_long_data(), unbuffered result sets and current errors. It does not clear bindings or stored result sets. Stored result sets will be cleared when executing the prepared statement (or closing it).

To prepare a statement with another query use function mysqli_stmt_prepare().

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution

mysqli_stmt::prepare
mysqli_stmt::result_metadata
mysqli_stmt


Returns result set metadata from a prepared statement

mysqli_stmt::reset
mysqli_stmt::send_long_data
mysqli_stmt
PHP Manual

mysqli_stmt::result_metadata

mysqli_stmt_result_metadata

(PHP 5)

mysqli_stmt::result_metadata -- mysqli_stmt_result_metadata — Returns result set metadata from a prepared statement

Opis

Styl obiektowy

mysqli_result mysqli_stmt::result_metadata ( void )

Styl proceduralny

mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt $stmt )

If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object that can be used to process the meta information such as total number of fields and individual field information.

Informacja:

This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • mysqli_num_fields()

  • mysqli_fetch_field()

  • mysqli_fetch_field_direct()

  • mysqli_fetch_fields()

  • mysqli_field_count()

  • mysqli_field_seek()

  • mysqli_field_tell()

  • mysqli_free_result()

The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result()

Informacja:

The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Returns a result object or FALSE if an error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query("DROP TABLE IF EXISTS friends");
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);

/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_free_result() - Frees the memory associated with a result

mysqli_stmt::reset
mysqli_stmt::send_long_data
mysqli_stmt


Send data in blocks

mysqli_stmt::result_metadata
mysqli_stmt::$sqlstate
mysqli_stmt
PHP Manual

mysqli_stmt::send_long_data

mysqli_stmt_send_long_data

(PHP 5)

mysqli_stmt::send_long_data -- mysqli_stmt_send_long_data — Send data in blocks

Opis

Styl obiektowy

bool mysqli_stmt::send_long_data ( int $param_nr , string $data )

Styl proceduralny

bool mysqli_stmt_send_long_data ( mysqli_stmt $stmt , int $param_nr , string $data )

Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

param_nr

Indicates which parameter to associate the data with. Parameters are numbered beginning with 0.

data

A string containing data to be sent.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
    $stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

mysqli_stmt::result_metadata
mysqli_stmt::$sqlstate
mysqli_stmt


Returns SQLSTATE error from previous statement operation

mysqli_stmt::send_long_data
mysqli_stmt::store_result
mysqli_stmt
PHP Manual

mysqli_stmt::$sqlstate

mysqli_stmt_sqlstate

(PHP 5)

mysqli_stmt::$sqlstate -- mysqli_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

Opis

Styl obiektowy

string $mysqli_stmt->sqlstate;

Styl proceduralny

string mysqli_stmt_sqlstate ( mysqli_stmt $stmt )

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

Notatki

Informacja:

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* drop table */
    $mysqli->query("DROP TABLE myCountry");

    /* execute query */
    $stmt->execute();

    printf("Error: %s.\n", $stmt->sqlstate);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* drop table */
    mysqli_query($link, "DROP TABLE myCountry");

    /* execute query */
    mysqli_stmt_execute($stmt);

    printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Error: 42S02.

Zobacz też:

  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

mysqli_stmt::send_long_data
mysqli_stmt::store_result
mysqli_stmt


Transfers a result set from a prepared statement

mysqli_stmt::$sqlstate
mysqli_result
mysqli_stmt
PHP Manual

mysqli_stmt::store_result

mysqli_stmt_store_result

(PHP 5)

mysqli_stmt::store_result -- mysqli_stmt_store_result — Transfers a result set from a prepared statement

Opis

Styl obiektowy

bool mysqli_stmt::store_result ( void )

Styl proceduralny

bool mysqli_stmt_store_result ( mysqli_stmt $stmt )

You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data.

Informacja:

It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns NULL.

Parametry

stmt

Tylko styl proceduralny: Identyfikator stanu zwrócony przez mysqli_stmt_init().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* free result */
    $stmt->free_result();

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* free result */
    mysqli_stmt_free_result($stmt);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Number of rows: 20.

Zobacz też:

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

mysqli_stmt::$sqlstate
mysqli_result
mysqli_stmt


The mysqli_result class

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

Wstęp

Represents the result set obtained from a query against the database.

Rejestr zmian

Rejestr zmian
Wersja | Opis
5.4.0 | Iterator support was added, as mysqli_result now implements Traversable.

Krótki opis klasy

mysqli_result implements Traversable {
/* Właściwości */
int $current_field ;
int $field_count;
array $lengths;
int $num_rows;
/* Metody */
bool data_seek ( int $offset )
mixed fetch_all ([ int $resulttype = MYSQLI_NUM ] )
mixed fetch_array ([ int $resulttype = MYSQLI_BOTH ] )
array fetch_assoc ( void )
object fetch_field_direct ( int $fieldnr )
object fetch_field ( void )
array fetch_fields ( void )
object fetch_object ([ string $class_name [, array $params ]] )
mixed fetch_row ( void )
bool field_seek ( int $fieldnr )
void free ( void )
}

Spis treści

  • mysqli_result::$current_field — Get current field offset of a result pointer
  • mysqli_result::data_seek — Adjusts the result pointer to an arbitary row in the result
  • mysqli_result::fetch_all — Fetches all result rows as an associative array, a numeric array, or both
  • mysqli_result::fetch_array — Fetch a result row as an associative, a numeric array, or both
  • mysqli_result::fetch_assoc — Fetch a result row as an associative array
  • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
  • mysqli_result::fetch_field — Returns the next field in the result set
  • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
  • mysqli_result::fetch_object — Returns the current row of a result set as an object
  • mysqli_result::fetch_row — Get a result row as an enumerated array
  • mysqli_result::$field_count — Get the number of fields in a result
  • mysqli_result::field_seek — Set result pointer to a specified field offset
  • mysqli_result::free — Frees the memory associated with a result
  • mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
  • mysqli_result::$num_rows — Gets the number of rows in a result
mysqli_stmt::store_result
mysqli_result::$current_field
Mysqli


Get current field offset of a result pointer

mysqli_result
mysqli_result::data_seek
mysqli_result
PHP Manual

mysqli_result::$current_field

mysqli_field_tell

(PHP 5)

mysqli_result::$current_field -- mysqli_field_tell — Get current field offset of a result pointer

Opis

Styl obiektowy

int $mysqli_result->current_field ;

Styl proceduralny

int mysqli_field_tell ( mysqli_result $result )

Returns the position of the field cursor used for the last mysqli_fetch_field() call. This value can be used as an argument to mysqli_field_seek().

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

Returns current offset of field cursor.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        /* get fieldpointer offset */
        $currentfield = $result->current_field;

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        /* get fieldpointer offset */
        $currentfield = mysqli_field_tell($result);

        printf("Column %d:\n", $currentfield);
        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Column 1:
Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Column 2:
Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

Zobacz też:

  • mysqli_fetch_field() - Returns the next field in the result set
  • mysqli_field_seek() - Set result pointer to a specified field offset

mysqli_result
mysqli_result::data_seek
mysqli_result


Adjusts the result pointer to an arbitary row in the result

mysqli_result::$current_field
mysqli_result::fetch_all
mysqli_result
PHP Manual

mysqli_result::data_seek

mysqli_data_seek

(PHP 5)

mysqli_result::data_seek -- mysqli_data_seek — Adjusts the result pointer to an arbitary row in the result

Opis

Styl obiektowy

bool mysqli_result::data_seek ( int $offset )

Styl proceduralny

bool mysqli_data_seek ( mysqli_result $result , int $offset )

The mysqli_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

offset

The field offset. Must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

This function can only be used with buffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = $mysqli->query( $query)) {

    /* seek to row no. 400 */
    $result->data_seek(399);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";

if ($result = mysqli_query($link, $query)) {

    /* seek to row no. 400 */
    mysqli_data_seek($result, 399);

    /* fetch row */
    $row = mysqli_fetch_row($result);

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

City: Benin City  Countrycode: NGA

Zobacz też:

  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_num_rows() - Gets the number of rows in a result

mysqli_result::$current_field
mysqli_result::fetch_all
mysqli_result


Fetches all result rows as an associative array, a numeric array, or both

mysqli_result::data_seek
mysqli_result::fetch_array
mysqli_result
PHP Manual

mysqli_result::fetch_all

mysqli_fetch_all

(PHP 5 >= 5.3.0)

mysqli_result::fetch_all -- mysqli_fetch_all — Fetches all result rows as an associative array, a numeric array, or both

Opis

Styl obiektowy

mixed mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] )

Styl proceduralny

mixed mysqli_fetch_all ( mysqli_result $result [, int $resulttype = MYSQLI_NUM ] )

mysqli_fetch_all() fetches all result rows and returns the result set as an associative array, a numeric array, or both.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

resulttype

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

Zwracane wartości

Returns an array of associative or numeric arrays holding result rows.

Wyłączenie w natywnym sterowniku MySQL

Dostępna tylko z mysqlnd.

As mysqli_fetch_all() returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array(), which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all() should only be used in those situations where the fetched result set will be sent to another layer for processing.

Zobacz też:

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_query() - Performs a query on the database

mysqli_result::data_seek
mysqli_result::fetch_array
mysqli_result


Fetch a result row as an associative, a numeric array, or both

mysqli_result::fetch_all
mysqli_result::fetch_assoc
mysqli_result
PHP Manual

mysqli_result::fetch_array

mysqli_fetch_array

(PHP 5)

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both

Opis

Styl obiektowy

mixed mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] )

Styl proceduralny

mixed mysqli_fetch_array ( mysqli_result $result [, int $resulttype = MYSQLI_BOTH ] )

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Informacja: Nazwy pól zwracane przez tą funkcję rozróżniają wielkość znaków.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

resulttype

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

Zwracane wartości

Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = $mysqli->query($query);

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
$result->close();

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);

/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

Zobacz też:

  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitary row in the result

mysqli_result::fetch_all
mysqli_result::fetch_assoc
mysqli_result


Fetch a result row as an associative array

mysqli_result::fetch_array
mysqli_result::fetch_field_direct
mysqli_result
PHP Manual

mysqli_result::fetch_assoc

mysqli_fetch_assoc

(PHP 5)

mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row as an associative array

Opis

Styl obiektowy

array mysqli_result::fetch_assoc ( void )

Styl proceduralny

array mysqli_fetch_assoc ( mysqli_result $result )

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

Informacja: Nazwy pól zwracane przez tą funkcję rozróżniają wielkość znaków.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row() or add alias names.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

Przykład #3 A mysqli_result example comparing iterator usage

<?php
$c = mysqli_connect('127.0.0.1','user', 'pass');

// Using iterators (support was added with PHP 5.4)
foreach ( $c->query('SELECT user,host FROM mysql.user') as $row ) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

echo "\n==================\n";

// Not using iterators
$result = $c->query('SELECT user,host FROM mysql.user');
while ($row = $result->fetch_assoc()) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

?>

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

'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'

==================

'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'

Zobacz też:

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitary row in the result

mysqli_result::fetch_array
mysqli_result::fetch_field_direct
mysqli_result


Fetch meta-data for a single field

mysqli_result::fetch_assoc
mysqli_result::fetch_field
mysqli_result
PHP Manual

mysqli_result::fetch_field_direct

mysqli_fetch_field_direct

(PHP 5)

mysqli_result::fetch_field_direct -- mysqli_fetch_field_direct — Fetch meta-data for a single field

Opis

Styl obiektowy

object mysqli_result::fetch_field_direct ( int $fieldnr )

Styl proceduralny

object mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr )

Returns an object which contains field definition information from the specified result set.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Zwracane wartości

Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available.

Object attributes
Attribute | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = $result->fetch_field_direct(1);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for column 'SurfaceArea' */
    $finfo = mysqli_fetch_field_direct($result, 1);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

Zobacz też:

  • mysqli_num_fields() - Get the number of fields in a result
  • mysqli_fetch_field() - Returns the next field in the result set
  • mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set

mysqli_result::fetch_assoc
mysqli_result::fetch_field
mysqli_result


Returns the next field in the result set

mysqli_result::fetch_field_direct
mysqli_result::fetch_fields
mysqli_result
PHP Manual

mysqli_result::fetch_field

mysqli_fetch_field

(PHP 5)

mysqli_result::fetch_field -- mysqli_fetch_field — Returns the next field in the result set

Opis

Styl obiektowy

object mysqli_result::fetch_field ( void )

Styl proceduralny

object mysqli_fetch_field ( mysqli_result $result )

Returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

Returns an object which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | Reserved for default value, currently always ""
db | Database (since PHP 5.3.6)
catalog | The catalog name, always "def" (since PHP 5.3.6)
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    while ($finfo = $result->fetch_field()) {

        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all fields */
    while ($finfo = mysqli_fetch_field($result)) {

        printf("Name:     %s\n", $finfo->name);
        printf("Table:    %s\n", $finfo->table);
        printf("max. Len: %d\n", $finfo->max_length);
        printf("Flags:    %d\n", $finfo->flags);
        printf("Type:     %d\n\n", $finfo->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

Zobacz też:

  • mysqli_num_fields() - Get the number of fields in a result
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set
  • mysqli_field_seek() - Set result pointer to a specified field offset

mysqli_result::fetch_field_direct
mysqli_result::fetch_fields
mysqli_result


Returns an array of objects representing the fields in a result set

mysqli_result::fetch_field
mysqli_result::fetch_object
mysqli_result
PHP Manual

mysqli_result::fetch_fields

mysqli_fetch_fields

(PHP 5)

mysqli_result::fetch_fields -- mysqli_fetch_fields — Returns an array of objects representing the fields in a result set

Opis

Styl obiektowy

array mysqli_result::fetch_fields ( void )

Styl proceduralny

array mysqli_fetch_fields ( mysqli_result $result )

This function serves an identical purpose to the mysqli_fetch_field() function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

Returns an array of objects which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for all columns */
    $finfo = $result->fetch_fields();

    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val->name);
        printf("Table:    %s\n", $val->table);
        printf("max. Len: %d\n", $val->max_length);
        printf("Flags:    %d\n", $val->flags);
        printf("Type:     %d\n\n", $val->type);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for all columns */
    $finfo = mysqli_fetch_fields($result);

    foreach ($finfo as $val) {
        printf("Name:     %s\n", $val->name);
        printf("Table:    %s\n", $val->table);
        printf("max. Len: %d\n", $val->max_length);
        printf("Flags:    %d\n", $val->flags);
        printf("Type:     %d\n\n", $val->type);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

Zobacz też:

  • mysqli_num_fields() - Get the number of fields in a result
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_field() - Returns the next field in the result set

mysqli_result::fetch_field
mysqli_result::fetch_object
mysqli_result


Returns the current row of a result set as an object

mysqli_result::fetch_fields
mysqli_result::fetch_row
mysqli_result
PHP Manual

mysqli_result::fetch_object

mysqli_fetch_object

(PHP 5)

mysqli_result::fetch_object -- mysqli_fetch_object — Returns the current row of a result set as an object

Opis

Styl obiektowy

object mysqli_result::fetch_object ([ string $class_name [, array $params ]] )

Styl proceduralny

object mysqli_fetch_object ( mysqli_result $result [, string $class_name [, array $params ]] )

The mysqli_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set.

Note that mysqli_fetch_object() sets the properties of the object before calling the object constructor.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

class_name

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

Zwracane wartości

Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset.

Informacja: Nazwy pól zwracane przez tą funkcję rozróżniają wielkość znaków.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Rejestr zmian

Wersja | Opis
5.0.0 | Added the ability to return as a different object.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($obj = $result->fetch_object()) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($obj = mysqli_fetch_object($result)) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

Zobacz też:

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitary row in the result

mysqli_result::fetch_fields
mysqli_result::fetch_row
mysqli_result


Get a result row as an enumerated array

mysqli_result::fetch_object
mysqli_result::$field_count
mysqli_result
PHP Manual

mysqli_result::fetch_row

mysqli_fetch_row

(PHP 5)

mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array

Opis

Styl obiektowy

mixed mysqli_result::fetch_row ( void )

Styl proceduralny

mixed mysqli_fetch_row ( mysqli_result $result )

Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

mysqli_fetch_row() returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in result set.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_row()) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_row($result)) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

Zobacz też:

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_object() - Returns the current row of a result set as an object
  • mysqli_query() - Performs a query on the database
  • mysqli_data_seek() - Adjusts the result pointer to an arbitary row in the result

mysqli_result::fetch_object
mysqli_result::$field_count
mysqli_result


Get the number of fields in a result

mysqli_result::fetch_row
mysqli_result::field_seek
mysqli_result
PHP Manual

mysqli_result::$field_count

mysqli_num_fields

(PHP 5)

mysqli_result::$field_count -- mysqli_num_fields — Get the number of fields in a result

Opis

Styl obiektowy

int $mysqli_result->field_count;

Styl proceduralny

int mysqli_num_fields ( mysqli_result $result )

Returns the number of fields from specified result set.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

The number of fields from a result set.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = $result->field_count;

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = mysqli_num_fields($result);

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Result set has 5 fields.

Zobacz też:

  • mysqli_fetch_field() - Returns the next field in the result set

mysqli_result::fetch_row
mysqli_result::field_seek
mysqli_result


Set result pointer to a specified field offset

mysqli_result::$field_count
mysqli_result::free
mysqli_result
PHP Manual

mysqli_result::field_seek

mysqli_field_seek

(PHP 5)

mysqli_result::field_seek -- mysqli_field_seek — Set result pointer to a specified field offset

Opis

Styl obiektowy

bool mysqli_result::field_seek ( int $fieldnr )

Styl proceduralny

bool mysqli_field_seek ( mysqli_result $result , int $fieldnr )

Sets the field cursor to the given offset. The next call to mysqli_fetch_field() will retrieve the field definition of the column associated with that offset.

Informacja:

To seek to the beginning of a row, pass an offset value of zero.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

    /* Get field information for 2nd column */
    $result->field_seek(1);
    $finfo = $result->fetch_field();

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

    /* Get field information for 2nd column */
    mysqli_field_seek($result, 1);
    $finfo = mysqli_fetch_field($result);

    printf("Name:     %s\n", $finfo->name);
    printf("Table:    %s\n", $finfo->table);
    printf("max. Len: %d\n", $finfo->max_length);
    printf("Flags:    %d\n", $finfo->flags);
    printf("Type:     %d\n\n", $finfo->type);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

Zobacz też:

  • mysqli_fetch_field() - Returns the next field in the result set

mysqli_result::$field_count
mysqli_result::free
mysqli_result


Frees the memory associated with a result

mysqli_result::field_seek
mysqli_result::$lengths
mysqli_result
PHP Manual

mysqli_result::free

mysqli_free_result

(PHP 5)

mysqli_result::free -- mysqli_free_result — Frees the memory associated with a result

Opis

Styl obiektowy

void mysqli_result::free ( void )
void mysqli_result::close ( void )
void mysqli_result::free_result ( void )

Styl proceduralny

void mysqli_free_result ( mysqli_result $result )

Frees the memory associated with the result.

Informacja:

You should always free your result with mysqli_free_result(), when your result object is not needed anymore.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • mysqli_query() - Performs a query on the database
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval

mysqli_result::field_seek
mysqli_result::$lengths
mysqli_result


Returns the lengths of the columns of the current row in the result set

mysqli_result::free
mysqli_result::$num_rows
mysqli_result
PHP Manual

mysqli_result::$lengths

mysqli_fetch_lengths

(PHP 5)

mysqli_result::$lengths -- mysqli_fetch_lengths — Returns the lengths of the columns of the current row in the result set

Opis

Styl obiektowy

array $mysqli_result->lengths;

Styl proceduralny

array mysqli_fetch_lengths ( mysqli_result $result )

The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

mysqli_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = $mysqli->query($query)) {

    $row = $result->fetch_row();

    /* display column lengths */
    foreach ($result->lengths as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = mysqli_query($link, $query)) {

    $row = mysqli_fetch_row($result);

    /* display column lengths */
    foreach (mysqli_fetch_lengths($result) as $i => $val) {
        printf("Field %2d has Length %2d\n", $i+1, $val);
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Field  1 has Length  3
Field  2 has Length  5
Field  3 has Length 13
Field  4 has Length  9
Field  5 has Length  6
Field  6 has Length  1
Field  7 has Length  6
Field  8 has Length  4
Field  9 has Length  6
Field 10 has Length  6
Field 11 has Length  5
Field 12 has Length 44
Field 13 has Length  7
Field 14 has Length  3
Field 15 has Length  2
mysqli_result::free
mysqli_result::$num_rows
mysqli_result


Gets the number of rows in a result

mysqli_result::$lengths
mysqli_driver
mysqli_result
PHP Manual

mysqli_result::$num_rows

mysqli_num_rows

(PHP 5)

mysqli_result::$num_rows -- mysqli_num_rows — Gets the number of rows in a result

Opis

Styl obiektowy

int $mysqli_result->num_rows;

Styl proceduralny

int mysqli_num_rows ( mysqli_result $result )

Returns the number of rows in the result set.

The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved.

Parametry

wynik

Tylko styl proceduralny: Identyfikator zbioru wyników zwróconych przez mysqli_query(), mysqli_store_result() lub mysqli_use_result().

Zwracane wartości

Returns number of rows in the result set.

Informacja:

If the number of rows is greater than MAXINT, the number will be returned as a string.

Przykłady

Przykład #1 Styl obiektowy

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Przykład #2 Styl proceduralny

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = mysqli_num_rows($result);

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Powyższe przykłady wyświetlą:

Result set has 239 rows.

Zobacz też:

  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_query() - Performs a query on the database

mysqli_result::$lengths
mysqli_driver
mysqli_result


The mysqli_driver class

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

Wstęp

MySQLi Driver.

Krótki opis klasy

mysqli_driver {
/* Właściwości */
public readonly string $client_info ;
public readonly string $client_version ;
public readonly string $driver_version ;
public readonly string $embedded ;
public bool $reconnect ;
public int $report_mode ;
/* Metody */
void embedded_server_end ( void )
bool embedded_server_start ( bool $start , array $arguments , array $groups )
}

Właściwości

client_info

The Client API header version

client_version

The Client version

driver_version

The MySQLi Driver version

embedded

Whether MySQLi Embedded support is enabled

reconnect

Allow or prevent reconnect (see the mysqli.reconnect INI directive)

report_mode

Set to MYSQLI_REPORT_OFF, MYSQLI_REPORT_ALL or any combination of MYSQLI_REPORT_STRICT (throw Exceptions for errors), MYSQLI_REPORT_ERROR (report errors) and MYSQLI_REPORT_INDEX (errors regarding indexes). See also mysqli_report().

Spis treści

  • mysqli_driver::embedded_server_end — Stop embedded server
  • mysqli_driver::embedded_server_start — Initialize and start embedded server
mysqli_result::$num_rows
mysqli_driver::embedded_server_end
Mysqli


Stop embedded server

mysqli_driver
mysqli_driver::embedded_server_start
mysqli_driver
PHP Manual

mysqli_driver::embedded_server_end

mysqli_embedded_server_end

(PHP 5)

mysqli_driver::embedded_server_end -- mysqli_embedded_server_end — Stop embedded server

Opis

Styl obiektowy

void mysqli_driver::embedded_server_end ( void )

Styl proceduralny

void mysqli_embedded_server_end ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

mysqli_driver
mysqli_driver::embedded_server_start
mysqli_driver


Initialize and start embedded server

mysqli_driver::embedded_server_end
mysqli_warning
mysqli_driver
PHP Manual

mysqli_driver::embedded_server_start

mysqli_embedded_server_start

(PHP 5)

mysqli_driver::embedded_server_start -- mysqli_embedded_server_start — Initialize and start embedded server

Opis

Styl obiektowy

bool mysqli_driver::embedded_server_start ( bool $start , array $arguments , array $groups )

Styl proceduralny

bool mysqli_embedded_server_start ( bool $start , array $arguments , array $groups )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

mysqli_driver::embedded_server_end
mysqli_warning
mysqli_driver


The mysqli_warning class

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

Wstęp

Represents a MySQL warning.

Krótki opis klasy

mysqli_warning {
/* Właściwości */
public $message ;
public $sqlstate ;
public $errno ;
/* Metody */
public __construct ( void )
public void next ( void )
}

Właściwości

message

Message string

sqlstate

SQL state

errno

Error number

Spis treści

  • mysqli_warning::__construct — The __construct purpose
  • mysqli_warning::next — The next purpose
mysqli_driver::embedded_server_start
mysqli_warning::__construct
Mysqli


The __construct purpose

mysqli_warning
mysqli_warning::next
mysqli_warning
PHP Manual

mysqli_warning::__construct

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

mysqli_warning::__construct — The __construct purpose

Opis

public mysqli_warning::__construct ( 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

mysqli_warning
mysqli_warning::next
mysqli_warning


The next purpose

mysqli_warning::__construct
Aliases and deprecated Mysqli Funkcje
mysqli_warning
PHP Manual

mysqli_warning::next

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

mysqli_warning::next — The next purpose

Opis

public void mysqli_warning::next ( 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

mysqli_warning::__construct
Aliases and deprecated Mysqli Funkcje
mysqli_warning


Aliases and deprecated Mysqli Funkcje

Spis treści

  • mysqli_bind_param — Alias for mysqli_stmt_bind_param
  • mysqli_bind_result — Alias for mysqli_stmt_bind_result
  • mysqli_client_encoding — Alias of mysqli_character_set_name
  • mysqli_connect — Alias dla mysqli::__construct
  • mysqli_disable_rpl_parse — Disable RPL parse
  • mysqli_enable_reads_from_master — Enable reads from master
  • mysqli_enable_rpl_parse — Enable RPL parse
  • mysqli_escape_string — Alias dla mysqli_real_escape_string
  • mysqli_execute — Alias for mysqli_stmt_execute
  • mysqli_fetch — Alias for mysqli_stmt_fetch
  • mysqli_get_cache_stats — Returns client Zval cache statistics
  • mysqli_get_metadata — Alias for mysqli_stmt_result_metadata
  • mysqli_master_query — Enforce execution of a query on the master in a master/slave setup
  • mysqli_param_count — Alias for mysqli_stmt_param_count
  • mysqli_report — Enables or disables internal report functions
  • mysqli_rpl_parse_enabled — Check if RPL parse is enabled
  • mysqli_rpl_probe — RPL probe
  • mysqli_send_long_data — Alias for mysqli_stmt_send_long_data
  • mysqli_set_opt — Alias of mysqli_options
  • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup
mysqli_warning::next
mysqli_bind_param
Mysqli


Alias for mysqli_stmt_bind_param

Aliases and deprecated Mysqli Funkcje
mysqli_bind_result
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_bind_param

(PHP 5)

mysqli_bind_param — Alias for mysqli_stmt_bind_param()

Opis

This function is an alias of mysqli_stmt_bind_param().

Notatki

Informacja:

mysqli_bind_param() is deprecated and will be removed.

Zobacz też:

  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

Aliases and deprecated Mysqli Funkcje
mysqli_bind_result
Aliases and deprecated Mysqli Funkcje


Alias for mysqli_stmt_bind_result

mysqli_bind_param
mysqli_client_encoding
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_bind_result

(PHP 5)

mysqli_bind_result — Alias for mysqli_stmt_bind_result()

Opis

This function is an alias of mysqli_stmt_bind_result().

Notatki

Informacja:

mysqli_bind_result() is deprecated and will be removed.

Zobacz też:

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

mysqli_bind_param
mysqli_client_encoding
Aliases and deprecated Mysqli Funkcje


Alias of mysqli_character_set_name

mysqli_bind_result
mysqli_connect
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_client_encoding

(PHP 5)

mysqli_client_encoding — Alias of mysqli_character_set_name()

Opis

This function is an alias of mysqli_character_set_name().

Zobacz też:

  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

mysqli_bind_result
mysqli_connect
Aliases and deprecated Mysqli Funkcje


Alias dla mysqli::__construct

mysqli_client_encoding
mysqli_disable_rpl_parse
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_connect

(PHP 5)

mysqli_connect — Alias dla mysqli::__construct()

Opis

Ta funkcja jest aliasem dla: mysqli::__construct()

mysqli_client_encoding
mysqli_disable_rpl_parse
Aliases and deprecated Mysqli Funkcje


Disable RPL parse

mysqli_connect
mysqli_enable_reads_from_master
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_disable_rpl_parse

(PHP 5)

mysqli_disable_rpl_parse — Disable RPL parse

Opis

bool mysqli_disable_rpl_parse ( mysqli $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli_connect
mysqli_enable_reads_from_master
Aliases and deprecated Mysqli Funkcje


Enable reads from master

mysqli_disable_rpl_parse
mysqli_enable_rpl_parse
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_enable_reads_from_master

(PHP 5)

mysqli_enable_reads_from_master — Enable reads from master

Opis

bool mysqli_enable_reads_from_master ( mysqli $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli_disable_rpl_parse
mysqli_enable_rpl_parse
Aliases and deprecated Mysqli Funkcje


Enable RPL parse

mysqli_enable_reads_from_master
mysqli_escape_string
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_enable_rpl_parse

(PHP 5)

mysqli_enable_rpl_parse — Enable RPL parse

Opis

bool mysqli_enable_rpl_parse ( mysqli $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli_enable_reads_from_master
mysqli_escape_string
Aliases and deprecated Mysqli Funkcje


Alias dla mysqli_real_escape_string

mysqli_enable_rpl_parse
mysqli_execute
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_escape_string

(PHP 5)

mysqli_escape_string — Alias dla mysqli_real_escape_string()

Opis

Ta funkcja jest aliasem dla: mysqli_real_escape_string().

mysqli_enable_rpl_parse
mysqli_execute
Aliases and deprecated Mysqli Funkcje


Alias for mysqli_stmt_execute

mysqli_escape_string
mysqli_fetch
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_execute

(PHP 5)

mysqli_execute — Alias for mysqli_stmt_execute()

Opis

This function is an alias of mysqli_stmt_execute().

Notatki

Informacja:

mysqli_execute() is deprecated and will be removed.

Zobacz też:

  • mysqli_stmt_execute() - Executes a prepared Query

mysqli_escape_string
mysqli_fetch
Aliases and deprecated Mysqli Funkcje


Alias for mysqli_stmt_fetch

mysqli_execute
mysqli_get_cache_stats
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_fetch

(PHP 5)

mysqli_fetch — Alias for mysqli_stmt_fetch()

Opis

This function is an alias of mysqli_stmt_fetch().

Notatki

Informacja:

mysqli_fetch() is deprecated and will be removed.

Zobacz też:

  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

mysqli_execute
mysqli_get_cache_stats
Aliases and deprecated Mysqli Funkcje


Returns client Zval cache statistics

mysqli_fetch
mysqli_get_metadata
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_get_cache_stats

(PHP 5 >= 5.3.0)

mysqli_get_cache_stats — Returns client Zval cache statistics

Opis

array mysqli_get_cache_stats ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns client Zval cache statistics. Dostępna tylko z mysqlnd.

Parametry

Zwracane wartości

Returns an array with client Zval cache stats if success, FALSE otherwise.

Przykłady

Przykład #1 A mysqli_get_cache_stats() example

<?php
$link = mysqli_connect();
print_r(mysqli_get_cache_stats());
?>

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

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

Zobacz też:

  • Stats description

mysqli_fetch
mysqli_get_metadata
Aliases and deprecated Mysqli Funkcje


Alias for mysqli_stmt_result_metadata

mysqli_get_cache_stats
mysqli_master_query
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_get_metadata

(PHP 5)

mysqli_get_metadata — Alias for mysqli_stmt_result_metadata()

Opis

This function is an alias of mysqli_stmt_result_metadata().

Notatki

Informacja:

mysqli_get_metadata() is deprecated and will be removed.

Zobacz też:

  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement

mysqli_get_cache_stats
mysqli_master_query
Aliases and deprecated Mysqli Funkcje


Enforce execution of a query on the master in a master/slave setup

mysqli_get_metadata
mysqli_param_count
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_master_query

(PHP 5)

mysqli_master_query — Enforce execution of a query on the master in a master/slave setup

Opis

bool mysqli_master_query ( mysqli $link , string $query )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli_get_metadata
mysqli_param_count
Aliases and deprecated Mysqli Funkcje


Alias for mysqli_stmt_param_count

mysqli_master_query
mysqli_report
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_param_count

(PHP 5)

mysqli_param_count — Alias for mysqli_stmt_param_count()

Opis

This function is an alias of mysqli_stmt_param_count().

Notatki

Informacja:

mysqli_param_count() is deprecated and will be removed.

Zobacz też:

  • mysqli_stmt_param_count() - Returns the number of parameter for the given statement

mysqli_master_query
mysqli_report
Aliases and deprecated Mysqli Funkcje


Enables or disables internal report functions

mysqli_param_count
mysqli_rpl_parse_enabled
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_report

(PHP 5)

mysqli_report — Enables or disables internal report functions

Opis

bool mysqli_report ( int $flags )

mysqli_report() is a powerful function to improve your queries and code during development and testing phase. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index).

Parametry

flags

Supported flags
Name | Description
MYSQLI_REPORT_OFF | Turns reporting off
MYSQLI_REPORT_ERROR | Report errors from mysqli function calls
MYSQLI_REPORT_STRICT | Throw mysqli_sql_exception for errors instead of warnings
MYSQLI_REPORT_INDEX | Report if no index or bad index was used in a query
MYSQLI_REPORT_ALL | Set all options (report all)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.2.15 & 5.3.4 | Changing the reporting mode is now be per-request, rather than per-process.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this query should report a bad index */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
$result->close();

$mysqli->close();
?>

Zobacz też:

  • mysqli_driver::$report_mode
  • mysqli_debug() - Performs debugging operations
  • mysqli_dump_debug_info() - Dump debugging information into the log

mysqli_param_count
mysqli_rpl_parse_enabled
Aliases and deprecated Mysqli Funkcje


Check if RPL parse is enabled

mysqli_report
mysqli_rpl_probe
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_rpl_parse_enabled

(PHP 5)

mysqli_rpl_parse_enabled — Check if RPL parse is enabled

Opis

int mysqli_rpl_parse_enabled ( mysqli $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli_report
mysqli_rpl_probe
Aliases and deprecated Mysqli Funkcje


RPL probe

mysqli_rpl_parse_enabled
mysqli_send_long_data
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_rpl_probe

(PHP 5)

mysqli_rpl_probe — RPL probe

Opis

bool mysqli_rpl_probe ( mysqli $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli_rpl_parse_enabled
mysqli_send_long_data
Aliases and deprecated Mysqli Funkcje


Alias for mysqli_stmt_send_long_data

mysqli_rpl_probe
mysqli_set_opt
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_send_long_data

(PHP 5)

mysqli_send_long_data — Alias for mysqli_stmt_send_long_data()

Opis

This function is an alias of mysqli_stmt_send_long_data().

Notatki

Informacja:

mysqli_send_long_data() is deprecated and will be removed.

Zobacz też:

  • mysqli_stmt_send_long_data() - Send data in blocks

mysqli_rpl_probe
mysqli_set_opt
Aliases and deprecated Mysqli Funkcje


Alias of mysqli_options

mysqli_send_long_data
mysqli_slave_query
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_set_opt

(PHP 5)

mysqli_set_opt — Alias of mysqli_options()

Opis

This function is an alias of mysqli_options().

mysqli_send_long_data
mysqli_slave_query
Aliases and deprecated Mysqli Funkcje


Force execution of a query on a slave in a master/slave setup

mysqli_set_opt
Mysqlnd
Aliases and deprecated Mysqli Funkcje
PHP Manual

mysqli_slave_query

(PHP 5)

mysqli_slave_query — Force execution of a query on a slave in a master/slave setup

Opis

bool mysqli_slave_query ( mysqli $link , string $query )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA i zostanie USUNIĘTA od PHP 5.3.0.

mysqli_set_opt
Mysqlnd
Aliases and deprecated Mysqli Funkcje


MySQL Native Driver

  • Wstęp
  • Overview
  • Installation
  • Konfiguracja wykonawcza
  • Persistent Connections
  • Statistics
  • Notes
  • MySQL Native Driver Plugin API
    • A comparison of mysqlnd plugins with MySQL Proxy
    • Obtaining the mysqlnd plugin API
    • MySQL Native Driver Plugin Architecture
    • The mysqlnd plugin API
    • Getting started building a mysqlnd plugin
mysqli_slave_query
Wstęp
MySQL


Wstęp

This section of the manual provides an overview of the MySQL Native Driver.

Mysqlnd
Overview
Mysqlnd


Overview

MySQL Native Driver is a replacement for the MySQL Client Library (libmysql). MySQL Native Driver is part of the official PHP sources as of PHP 5.3.0.

The MySQL database extensions MySQL extension, mysqli and PDO MYSQL all communicate with the MySQL server. In the past, this was done by the extension using the services provided by the MySQL Client Library. The extensions were compiled against the MySQL Client Library in order to use its client-server protocol.

With MySQL Native Driver there is now an alternative, as the MySQL database extensions can be compiled to use MySQL Native Driver instead of the MySQL Client Library.

MySQL Native Driver is written in C as a PHP extension.

What it is not

Although MySQL Native Driver is written as a PHP extension, it is important to note that it does not provide a new API to the PHP programmer. The programmer APIs for MySQL database connectivity are provided by the MySQL extension, mysqli and PDO MYSQL. These extensions can now use the services of MySQL Native Driver to communicate with the MySQL Server. Therefore, you should not think of MySQL Native Driver as an API.

Why use it?

Using the MySQL Native Driver offers a number of advantages over using the MySQL Client Library.

The older MySQL Client Library was written by MySQL AB (now Oracle Corporation) and so was released under the MySQL license. This ultimately led to MySQL support being disabled by default in PHP. However, the MySQL Native Driver has been developed as part of the PHP project, and is therefore released under the PHP license. This removes licensing issues that have been problematic in the past.

Also, in the past, you needed to build the MySQL database extensions against a copy of the MySQL Client Library. This typically meant you needed to have MySQL installed on a machine where you were building the PHP source code. Also, when your PHP application was running, the MySQL database extensions would call down to the MySQL Client library file at run time, so the file needed to be installed on your system. With MySQL Native Driver that is no longer the case as it is included as part of the standard distribution. So you do not need MySQL installed in order to build PHP or run PHP database applications.

Because MySQL Native Driver is written as a PHP extension, it is tightly coupled to the workings of PHP. This leads to gains in efficiency, especially when it comes to memory usage, as the driver uses the PHP memory management system. It also supports the PHP memory limit. Using MySQL Native Driver leads to comparable or better performance than using MySQL Client Library, it always ensures the most efficient use of memory. One example of the memory efficiency is the fact that when using the MySQL Client Library, each row is stored in memory twice, whereas with the MySQL Native Driver each row is only stored once in memory.

Special features

MySQL Native Driver also provides some special features not available when the MySQL database extensions use MySQL Client Library. These special features are listed below:

  • Improved persistent connections

  • The special function mysqli_fetch_all()

  • Performance statistics calls:
mysqli_get_cache_stats(),
mysqli_get_client_stats(),
mysqli_get_connection_stats()

The performance statistics facility can prove to be very useful in identifying performance bottlenecks.

MySQL Native Driver also allows for persistent connections when used with the mysqli extension.

SSL Support

MySQL Native Driver has supported SSL since PHP version 5.3.3

Compressed Protocol Support

As of PHP 5.3.2 MySQL Native Driver supports the compressed client server protocol. MySQL Native Driver did not support this in 5.3.0 and 5.3.1. Extensions such as ext/mysql, ext/mysqli, that are configured to use MySQL Native Driver, can also take advantage of this feature. Note that PDO_MYSQL does NOT support compression when used together with mysqlnd.

Named Pipes Support

Named pipes support for Windows was added in PHP version 5.4.0.

Wstęp
Installation
Mysqlnd


Installation

Rejestr zmian

Rejestr zmian
Wersja | Opis
5.3.0 | The MySQL Native Driver was added, with support for all MySQL extensions (i.e., mysql, mysqli and PDO_MYSQL). Passing in mysqlnd to the appropriate configure switch enables this support.
5.4.0 | The MySQL Native Driver is now the default for all MySQL extensions (i.e., mysql, mysqli and PDO_MYSQL). Passing in mysqlnd to configure is now optional.

Installation on Unix

The MySQL database extensions must be configured to use the MySQL Client Library. In order to use the MySQL Native Driver, PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support. This is done through configuration options prior to building the PHP source code.

For example, to build the MySQL extension, mysqli and PDO MYSQL using the MySQL Native Driver, the following command would be given:

./configure --with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
[other options]

Installation on Windows

In the official PHP Windows distributions from 5.3 onwards, MySQL Native Driver is enabled by default, so no additional configuration is required to use it. All MySQL database extensions will use MySQL Native Driver in this case.

Overview
Konfiguracja wykonawcza
Mysqlnd


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

MySQL Native Driver Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mysqlnd.collect_statistics | "1" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.net_read_timeout | "31536000" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.net_cmd_buffer_size | 5.3.0 - "2048", 5.3.1 - "4096" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_SYSTEM | 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.

mysqlnd.collect_statistics boolean

Enables the collection of various client statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(),
mysqli_get_cache_stats() and are shown in
mysqlnd section of the output of the
phpinfo() function as well.

This configuration setting enables all MySQL Native Driver statistics except those relating to memory management.

mysqlnd.collect_memory_statistics boolean

Enable the collection of various memory statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(),
mysqli_get_cache_stats() and are shown in
mysqlnd section of the output of the
phpinfo() function as well.

This configuration setting enables the memory management statistics within the overall set of MySQL Native Driver statistics.

mysqlnd.debug string

Records communication from all extensions using mysqlnd to the specified log file.

The format of the directive is mysqlnd.debug = "option1[,parameter_option1][:option2[,parameter_option2]]".

The options for the format string are as follows:

  • A[,file] - Appends trace output to specified file. Also ensures that data is written after each write. This is done by closing and reopening the trace file (this is slow). It helps ensure a complete log file should the application crash.

  • a[,file] - Appends trace output to the specified file.

  • d - Enables output from DBUG_<N> macros for the current state. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword. An empty list of keywords implies output for all macros.

  • f[,functions] - Limits debugger actions to the specified list of functions. An empty list of functions implies that all functions are selected.

  • F - Marks each debugger output line with the name of the source file containing the macro causing the output.

  • i - Marks each debugger output line with the PID of the current process.

  • L - Marks each debugger output line with the name of the source file line number of the macro causing the output.

  • n - Marks each debugger output line with the current function nesting depth

  • o[,file] - Similar to a[,file] but overwrites old file, and does not append.

  • O[,file] - Similar to A[,file] but overwrites old file, and does not append.

  • t[,N] - Enables function control flow tracing. The maximum nesting depth is specified by N, and defaults to 200.

  • x - This option activates profiling.

Example:

d:t:x:O,/tmp/mysqlnd.trace

Informacja:

This feature is only available with a debug build of PHP. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above.

mysqlnd.net_read_timeout integer

mysqlnd and the MySQL Client Library, libmysql use different networking APIs. mysqlnd uses PHP streams, whereas libmysql uses its own wrapper around the operating level network calls. PHP, by default, sets a read timeout of 60s for streams. This is set via php.ini, default_socket_timeout. This default applies to all streams that set no other timeout value. mysqlnd does not set any other value and therefore connections of long running queries can be disconnected after default_socket_timeout seconds resulting in an error message "2006 - MySQL Server has gone away". The MySQL Client Library sets a default timeout of 365 * 24 * 3600 seconds (1 year) and waits for other timeouts to occur, such as TCP/IP timeouts. mysqlnd now uses the same very long timeout. The value is configurable through a new php.ini setting: mysqlnd.net_read_timeout. mysqlnd.net_read_timeout gets used by any extension (ext/mysql, ext/mysqli, PDO_MySQL) that uses mysqlnd. mysqlnd tells PHP Streams to use mysqlnd.net_read_timeout. Please note that there may be subtle differences between MYSQL_OPT_READ_TIMEOUT from the MySQL Client Library and PHP Streams, for example MYSQL_OPT_READ_TIMEOUT is documented to work only for TCP/IP connections and, prior to MySQL 5.1.2, only for Windows. PHP streams may not have this limitation. Please check the streams documentation, if in doubt.

mysqlnd.net_cmd_buffer_size long

mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size (in php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY ("normal" query), does not fit into the buffer, mysqlnd will grow the buffer to the size required for sending the command. Whenever the buffer gets extended for one connection, command_buffer_too_small will be incremented by one.

If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size bytes for almost every connection, you should consider increasing the default size to avoid re-allocations.

The default buffer size is 2048 bytes in PHP 5.3.0. In later versions the default is 4096 bytes. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).

It is recommended that the buffer size be set to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence, mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message, or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields() and the meta data come from a string column with a very long default value (>1900 bytes).

As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.

The value can also be set using mysqli_option(link, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, size).

mysqlnd.net_read_buffer_size long

Maximum read chunk size in bytes when reading the body of a MySQL command packet. The MySQL client server protocol encapsulates all its commands in packets. The packets consist of a small header and a body with the actual payload. The size of the body is encoded in the header. mysqlnd reads the body in chunks of MIN(header.size, mysqlnd.net_read_buffer_size) bytes. If a packet body is larger than mysqlnd.net_read_buffer_size bytes, mysqlnd has to call read() multiple times.

The value can also be set using mysqli_optionS(link, MYSQLI_OPT_NET_READ_BUFFER_SIZE, size).

Installation
Persistent Connections
Mysqlnd


Persistent Connections

Using Persistent Connections

If mysqli is used with mysqlnd, when a persistent connection is created it generates a COM_CHANGE_USER (mysql_change_user()) call on the server. This ensures that re-authentication of the connection takes place.

As there is some overhead associated with the COM_CHANGE_USER call, it is possible to switch this off at compile time. Reusing a persistent connection will then generate a COM_PING (mysql_ping) call to simply test the connection is reusable.

Generation of COM_CHANGE_USER can be switched off with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT. For example:

shell# CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" ./configure --with-mysql=/usr/local/mysql/ --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql=/usr/local/mysql/bin/mysql_config --enable-debug && make clean && make -j6

Or alternatively:

shell# export CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT"
shell# configure --whatever-option
shell# make clean
shell# make

Note that only mysqli on mysqlnd uses COM_CHANGE_USER. Other extension-driver combinations use COM_PING on initial use of a persistent connection.

Konfiguracja wykonawcza
Statistics
Mysqlnd


Statistics

Using Statistical Data

MySQL Native Driver contains support for gathering statistics on the communication between the client and the server. The statistics gathered are of three main types:

  • Client statistics

  • Connection statistics

  • Zval cache statistics

If you are using the mysqli extension, these statistics can be obtained through three API calls:

  • mysqli_get_client_stats()

  • mysqli_get_connection_stats()

  • mysqli_get_cache_stats()

Informacja:

Statistics are aggregated among all extensions that use MySQL Native Driver. For example, when compiling both ext/mysql and ext/mysqli against MySQL Native Driver, both function calls of ext/mysql and ext/mysqli will change the statistics. There is no way to find out how much a certain API call of any extension that has been compiled against MySQL Native Driver has impacted a certain statistic. You can configure the PDO MySQL Driver, ext/mysql and ext/mysqli to optionally use the MySQL Native Driver. When doing so, all three extensions will change the statistics.

Accessing Client Statistics

To access client statistics, you need to call mysqli_get_client_stats(). The function call does not require any parameters.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Client statistics can also be accessed by calling the phpinfo() function.

Accessing Connection Statistics

To access connection statistics call mysqli_get_connection_stats(). This takes the database connection handle as the parameter.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Accessing Zval Cache Statistics

The MySQL Native Driver also collects statistics from its internal Zval cache. These statistics can be accessed by calling mysqli_get_cache_stats().

The Zval cache statistics obtained may lead to a tweaking of php.ini settings related to the Zval cache, resulting in better performance.

Buffered and Unbuffered Result Sets

Result sets can be buffered or unbuffered. Using default settings, ext/mysql and ext/mysqli work with buffered result sets for normal (non prepared statement) queries. Buffered result sets are cached on the client. After the query execution all results are fetched from the MySQL Server and stored in a cache on the client. The big advantage of buffered result sets is that they allow the server to free all resources allocated to a result set, once the results have been fetched by the client.

Unbuffered result sets on the other hand are kept much longer on the server. If you want to reduce memory consumption on the client, but increase load on the server, use unbuffered results. If you experience a high server load and the figures for unbuffered result sets are high, you should consider moving the load to the clients. Clients typically scale better than servers. "Load" does not only refer to memory buffers - the server also needs to keep other resources open, for example file handles and threads, before a result set can be freed.

Prepared Statements use unbuffered result sets by default. However, you can use mysqli_stmt_store_result() to enable buffered result sets.

Statistics returned by MySQL Native Driver

The following tables show a list of statistics returned by the
mysqli_get_client_stats(),
mysqli_get_connection_stats() and
mysqli_get_cache_stats() functions.

Network

Statistic | Scope | Description | Notes
bytes_sent | Connection | Number of bytes sent from PHP to the MySQL server | Can be used to check the efficiency of the compression protocol
bytes_received | Connection | Number of bytes received from MySQL server | Can be used to check the efficiency of the compression protocol
packets_sent | Connection | Number of MySQL Client Server protocol packets sent | Used for debugging Client Server protocol implementation
packets_received | Connection | Number of MySQL Client Server protocol packets received | Used for debugging Client Server protocol implementation
protocol_overhead_in | Connection | MySQL Client Server protocol overhead in bytes for incoming traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_in = packets_received * 4 | Used for debugging Client Server protocol implementation
protocol_overhead_out | Connection | MySQL Client Server protocol overhead in bytes for outgoing traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_out = packets_sent * 4 | Used for debugging Client Server protocol implementation
bytes_received_ok_packet | Connection | Total size of bytes of MySQL Client Server protocol OK packets received. OK packets can contain a status message. The length of the status message can vary and thus the size of an OK packet is not fixed. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_ok | Connection | Number of MySQL Client Server protocol OK packets received. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_eof_packet | Connection | Total size in bytes of MySQL Client Server protocol EOF packets received. EOF can vary in size depending on the server version. Also, EOF can transport an error message. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_eof | Connection | Number of MySQL Client Server protocol EOF packets. Like with other packet statistics the number of packets will be increased even if PHP does not receive the expected packet but, for example, an error message. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_header_packet | Connection | Total size in bytes of MySQL Client Server protocol result set header packets. The size of the packets varies depending on the payload (LOAD LOCAL INFILE, INSERT, UPDATE, SELECT, error message). | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_header | Connection | Number of MySQL Client Server protocol result set header packets. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_field_meta_packet | Connection | Total size in bytes of MySQL Client Server protocol result set meta data (field information) packets. Of course the size varies with the fields in the result set. The packet may also transport an error or an EOF packet in case of COM_LIST_FIELDS. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_field_meta | Connection | Number of MySQL Client Server protocol result set meta data (field information) packets. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_row_packet | Connection | Total size in bytes of MySQL Client Server protocol result set row data packets. The packet may also transport an error or an EOF packet. You can reverse engineer the number of error and EOF packets by substracting rows_fetched_from_server_normal and rows_fetched_from_server_ps from bytes_received_rset_row_packet. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_row | Connection | Number of MySQL Client Server protocol result set row data packets and their total size in bytes. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_prepare_response_packet | Connection | Total size in bytes of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). The packet may also transport an error. The packet size depends on the MySQL version: 9 bytes with MySQL 4.1 and 12 bytes from MySQL 5.0 on. There is no safe way to know how many errors happened. You may be able to guess that an error has occurred if, for example, you always connect to MySQL 5.0 or newer and, bytes_received_prepare_response_packet != packets_received_prepare_response * 12. See also ps_prepared_never_executed, ps_prepared_once_executed. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_prepare_response | Connection | Number of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_change_user_packet | Connection | Total size in bytes of MySQL Client Server protocol COM_CHANGE_USER packets. The packet may also transport an error or EOF. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_change_user | Connection | Number of MySQL Client Server protocol COM_CHANGE_USER packets | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_sent_command | Connection | Number of MySQL Client Server protocol commands sent from PHP to MySQL. There is no way to know which specific commands and how many of them have been sent. At its best you can use it to check if PHP has sent any commands to MySQL to know if you can consider to disable MySQL support in your PHP binary. There is also no way to reverse engineer the number of errors that may have occurred while sending data to MySQL. The only error recoded is command_buffer_too_small (see below). | Only useful for debugging CS protocol implementation.
bytes_received_real_data_normal Connection Number of bytes of payload fetched by the PHP client from mysqlnd using the text protocol. This is the size of the actual data contained in result sets that do not originate from prepared statements and which have been fetched by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd, this statistic only counts actual data pulled from mysqlnd by the PHP client. An example of a code sequence that will increase the value is as follows:
$mysqli = new mysqli();
$res = $mysqli->query("SELECT 'abc'");
$res->fetch_assoc();
$res->close();

Every fetch operation will increase the value.

The statistic will not be increased if the result set is only buffered on the client, but not fetched, such as in the following example:

$mysqli = new mysqli();
$res = $mysqli->query("SELECT 'abc'");
$res->close();

This statistic is available as of PHP version 5.3.4.

bytes_received_real_data_ps | Connection | Number of bytes of the payload fetched by the PHP client from mysqlnd using the prepared statement protocol. | This is the size of the actual data contained in result sets that originate from prepared statements and which has been fetched by the PHP client. The value will not be increased if the result set is not subsequently read by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd, this statistic only counts actual data pulled from mysqlnd by the PHP client. See also bytes_received_real_data_normal. This statistic is available as of PHP version 5.3.4.

Result Set

Statistic | Scope | Description | Notes
result_set_queries | Connection | Number of queries that have generated a result set. Examples of queries that generate a result set: SELECT, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. | You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
non_result_set_queries | Connection | Number of queries that did not generate a result set. Examples of queries that do not generate a result set: INSERT, UPDATE, LOAD DATA, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. | You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
no_index_used | Connection | Number of queries that have generated a result set but did not use an index (see also mysqld start option –log-queries-not-using-indexes). If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT).
bad_index_used | Connection | Number of queries that have generated a result set and did not use a good index (see also mysqld start option –log-slow-queries). | If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT)
slow_queries | Connection | SQL statements that took more than long_query_time seconds to execute and required at least min_examined_row_limit rows to be examined. | Not reported through mysqli_report()
buffered_sets | Connection | Number of buffered result sets returned by "normal" queries. "Normal" means "not prepared statement" in the following notes. | Examples of API calls that will buffer result sets on the client: mysql_query(), mysqli_query(), mysqli_store_result(), mysqli_stmt_get_result(). Buffering result sets on the client ensures that server resources are freed as soon as possible and it makes result set scrolling easier. The downside is the additional memory consumption on the client for buffering data. Note that mysqlnd (unlike the MySQL Client Library) respects the PHP memory limit because it uses PHP internal memory management functions to allocate memory. This is also the reason why memory_get_usage() reports a higer memory consumption when using mysqlnd instead of the MySQL Client Library. memory_get_usage() does not measure the memory consumption of the MySQL Client Library at all because the MySQL Client Library does not use PHP internal memory management functions monitored by the function!
unbuffered_sets | Connection | Number of unbuffered result sets returned by normal (non prepared statement) queries. | Examples of API calls that will not buffer result sets on the client: mysqli_use_result()
ps_buffered_sets | Connection | Number of buffered result sets returned by prepared statements. By default prepared statements are unbuffered. | Examples of API calls that will not buffer result sets on the client: mysqli_stmt_store_result
ps_unbuffered_sets | Connection | Number of unbuffered result sets returned by prepared statements. | By default prepared statements are unbuffered.
flushed_normal_sets Connection Number of result sets from normal (non prepared statement) queries with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush:

  • Faulty client application

  • Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed

  • Client application has stopped unexpectedly

flushed_ps_sets Connection Number of result sets from prepared statements with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush:

  • Faulty client application

  • Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed

  • Client application has stopped unexpectedly

ps_prepared_never_executed | Connection | Number of statements prepared but never executed. | Prepared statements occupy server resources. You should not prepare a statement if you do not plan to execute it.
ps_prepared_once_executed | Connection | Number of prepared statements executed only one. | One of the ideas behind prepared statements is that the same query gets executed over and over again (with different parameters) and some parsing and other preparation work can be saved, if statement execution is split up in separate prepare and execute stages. The idea is to prepare once and "cache" results, for example, the parse tree to be reused during multiple statement executions. If you execute a prepared statement only once the two stage processing can be inefficient compared to "normal" queries because all the caching means extra work and it takes (limited) server resources to hold the cached information. Consequently, prepared statements that are executed only once may cause performance hurts.
rows_fetched_from_server_normal, rows_fetched_from_server_ps | Connection | Total number of result set rows successfully fetched from MySQL regardless if the client application has consumed them or not. Some of the rows may not have been fetched by the client application but have been flushed implicitly. | See also packets_received_rset_row
rows_buffered_from_client_normal, rows_buffered_from_client_ps | Connection | Total number of succesfully buffered rows originating from a "normal" query or a prepared statement. This is the number of rows that have been fetched from MySQL and buffered on client. Note that there are two distinct statistics on rows that have been buffered (MySQL to mysqlnd internal buffer) and buffered rows that have been fetched by the client application (mysqlnd internal buffer to client application). If the number of buffered rows is higher than the number of fetched buffered rows it can mean that the client application runs queries that cause larger result sets than needed resulting in rows not read by the client. | Examples of queries that will buffer results: mysqli_query(), mysqli_store_result()
rows_fetched_from_client_normal_buffered, rows_fetched_from_client_ps_buffered | Connection | Total number of rows fetched by the client from a buffered result set created by a normal query or a prepared statement.
rows_fetched_from_client_normal_unbuffered, rows_fetched_from_client_ps_unbuffered | Connection | Total number of rows fetched by the client from a unbuffered result set created by a "normal" query or a prepared statement.
rows_fetched_from_client_ps_cursor | Connection | Total number of rows fetch by the client from a cursor created by a prepared statement.
rows_skipped_normal, rows_skipped_ps | Connection | Reserved for future use (currently not supported)
copy_on_write_saved, copy_on_write_performed | Process | With mysqlnd, variables returned by the extensions point into mysqlnd internal network result buffers. If you do not change the variables, fetched data will be kept only once in memory. If you change the variables, mysqlnd has to perform a copy-on-write to protect the internal network result buffers from being changed. With the MySQL Client Library you always hold fetched data twice in memory. Once in the internal MySQL Client Library buffers and once in the variables returned by the extensions. In theory mysqlnd can save up to 40% memory. However, note that the memory saving cannot be measured using memory_get_usage().
explicit_free_result, implicit_free_result | Connection, Process (only during prepared statement cleanup) | Total number of freed result sets. | The free is always considered explicit but for result sets created by an init command, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...)
proto_text_fetched_null, proto_text_fetched_bit, proto_text_fetched_tinyint proto_text_fetched_short, proto_text_fetched_int24, proto_text_fetched_int proto_text_fetched_bigint, proto_text_fetched_decimal, proto_text_fetched_float proto_text_fetched_double, proto_text_fetched_date, proto_text_fetched_year proto_text_fetched_time, proto_text_fetched_datetime, proto_text_fetched_timestamp proto_text_fetched_string, proto_text_fetched_blob, proto_text_fetched_enum proto_text_fetched_set, proto_text_fetched_geometry, proto_text_fetched_other Connection Total number of columns of a certain type fetched from a normal query (MySQL text protocol). Mapping from C API / MySQL meta data type to statistics name:

  • MYSQL_TYPE_NULL - proto_text_fetched_null

  • MYSQL_TYPE_BIT - proto_text_fetched_bit

  • MYSQL_TYPE_TINY - proto_text_fetched_tinyint

  • MYSQL_TYPE_SHORT - proto_text_fetched_short

  • MYSQL_TYPE_INT24 - proto_text_fetched_int24

  • MYSQL_TYPE_LONG - proto_text_fetched_int

  • MYSQL_TYPE_LONGLONG - proto_text_fetched_bigint

  • MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL - proto_text_fetched_decimal

  • MYSQL_TYPE_FLOAT - proto_text_fetched_float

  • MYSQL_TYPE_DOUBLE - proto_text_fetched_double

  • MYSQL_TYPE_DATE, MYSQL_TYPE_NEWDATE - proto_text_fetched_date

  • MYSQL_TYPE_YEAR - proto_text_fetched_year

  • MYSQL_TYPE_TIME - proto_text_fetched_time

  • MYSQL_TYPE_DATETIME - proto_text_fetched_datetime

  • MYSQL_TYPE_TIMESTAMP - proto_text_fetched_timestamp

  • MYSQL_TYPE_STRING, MYSQL_TYPE_VARSTRING, MYSQL_TYPE_VARCHAR - proto_text_fetched_string

  • MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB - proto_text_fetched_blob

  • MYSQL_TYPE_ENUM - proto_text_fetched_enum

  • MYSQL_TYPE_SET - proto_text_fetched_set

  • MYSQL_TYPE_GEOMETRY - proto_text_fetched_geometry

  • Any MYSQL_TYPE_* not listed before (there should be none) - proto_text_fetched_other

Note that the MYSQL_*-type constants may not be associated with the very same SQL column types in every version of MySQL.

proto_binary_fetched_null, proto_binary_fetched_bit, proto_binary_fetched_tinyint proto_binary_fetched_short, proto_binary_fetched_int24, proto_binary_fetched_int, proto_binary_fetched_bigint, proto_binary_fetched_decimal, proto_binary_fetched_float, proto_binary_fetched_double, proto_binary_fetched_date, proto_binary_fetched_year, proto_binary_fetched_time, proto_binary_fetched_datetime, proto_binary_fetched_timestamp, proto_binary_fetched_string, proto_binary_fetched_blob, proto_binary_fetched_enum, proto_binary_fetched_set, proto_binary_fetched_geometry, proto_binary_fetched_other | Connection | Total number of columns of a certain type fetched from a prepared statement (MySQL binary protocol). | For type mapping see proto_text_* described in the preceding text.

Connection

Statistic | Scope | Description | Notes
connect_success, connect_failure | Connection | Total number of successful / failed connection attempt. | Reused connections and all other kinds of connections are included.
reconnect | Process | Total number of (real_)connect attempts made on an already opened connection handle. | The code sequence $link = new mysqli(...); $link->real_connect(...) will cause a reconnect. But $link = new mysqli(...); $link->connect(...) will not because $link->connect(...) will explicitly close the existing connection before a new connection is established.
pconnect_success | Connection | Total number of successful persistent connection attempts. | Note that connect_success holds the sum of successful persistent and non-persistent connection attempts. The number of successful non-persistent connection attempts is connect_success - pconnect_success.
active_connections | Connection | Total number of active persistent and non-persistent connections.
active_persistent_connections | Connection | Total number of active persistent connections. | The total number of active non-persistent connections is active_connections - active_persistent_connections.
explicit_close Connection Total number of explicitly closed connections (ext/mysqli only). Examples of code snippets that cause an explicit close :
$link = new mysqli(...); $link->close(...)
$link = new mysqli(...); $link->connect(...)
implicit_close Connection Total number of implicitly closed connections (ext/mysqli only). Examples of code snippets that cause an implicit close :

  • $link = new mysqli(...); $link->real_connect(...)

  • unset($link)

  • Persistent connection: pooled connection has been created with real_connect and there may be unknown options set - close implicitly to avoid returning a connection with unknown options

  • Persistent connection: ping/change_user fails and ext/mysqli closes the connection

  • end of script execution: close connections that have not been closed by the user

disconnect_close | Connection | Connection failures indicated by the C API call mysql_real_connect() during an attempt to establish a connection. | It is called disconnect_close because the connection handle passed to the C API call will be closed.
in_middle_of_command_close | Process | A connection has been closed in the middle of a command execution (outstanding result sets not fetched, after sending a query and before retrieving an answer, while fetching data, while transferring data with LOAD DATA). | Unless you use asynchronous queries this should only happen if your script stops unexpectedly and PHP shuts down the connections for you.
init_command_executed_count | Connection | Total number of init command executions, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...). | The number of successful executions is init_command_executed_count - init_command_failed_count.
init_command_failed_count | Connection | Total number of failed init commands.

COM_* Commands

Statistic Scope Description Notes
com_quit, com_init_db, com_query, com_field_list, com_create_db, com_drop_db, com_refresh, com_shutdown, com_statistics, com_process_info, com_connect, com_process_kill, com_debug, com_ping, com_time, com_delayed_insert, com_change_user, com_binlog_dump, com_table_dump, com_connect_out, com_register_slave, com_stmt_prepare, com_stmt_execute, com_stmt_send_long_data, com_stmt_close, com_stmt_reset, com_stmt_set_option, com_stmt_fetch, com_daemon Connection Total number of attempts to send a certain COM_* command from PHP to MySQL.

The statistics are incremented after checking the line and immediately before sending the corresponding MySQL client server protocol packet. If mysqlnd fails to send the packet over the wire the statistics will not be decremented. In case of a failure mysqlnd emits a PHP warning "Error while sending %s packet. PID=%d."

Usage examples:

  • Check if PHP sends certain commands to MySQL, for example, check if a client sends COM_PROCESS_KILL

  • Calculate the average number of prepared statement executions by comparing COM_EXECUTE with COM_PREPARE

  • Check if PHP has run any non-prepared SQL statements by checking if COM_QUERY is zero

  • Identify PHP scripts that run an excessive number of SQL statements by checking COM_QUERY and COM_EXECUTE

Miscellaneous

Statistic | Scope | Description | Notes
explicit_stmt_close, implicit_stmt_close | Process | Total number of close prepared statements. | A close is always considered explicit but for a failed prepare.
mem_emalloc_count, mem_emalloc_ammount, mem_ecalloc_count, mem_ecalloc_ammount, mem_erealloc_count, mem_erealloc_ammount, mem_efree_count, mem_malloc_count, mem_malloc_ammount, mem_calloc_count, mem_calloc_ammount, mem_realloc_count, mem_realloc_ammount, mem_free_count | Process | Memory management calls. | Development only.
command_buffer_too_small Connection Number of network command buffer extensions while sending commands from PHP to MySQL.

mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size (php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (normal query), does not fit into the buffer, mysqlnd will grow the buffer to what is needed for sending the command. Whenever the buffer gets extended for one connection command_buffer_too_small will be incremented by one.

If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size (php.ini) bytes for almost every connection, you should consider to increase the default size to avoid re-allocations.

The default buffer size is 2048 bytes in PHP 5.3.0. In future versions the default will be 4kB or larger. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).

It is recommended to set the buffer size to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields()) and the meta data comes from a string column with a very long default value (>1900 bytes). No bug report on this exists - it should happen rarely.

As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.

connection_reused
Persistent Connections
Notes
Mysqlnd


Notes

This section provides a collection of miscellaneous notes on MySQL Native Driver usage.

  • Using mysqlnd means using PHP streams for underlying connectivity. For mysqlnd, the PHP streams documentation (Streams) should be consulted on such details as timeout settings, not the documentation for the MySQL Client Library.

Statistics
MySQL Native Driver Plugin API
Mysqlnd


MySQL Native Driver Plugin API

Spis treści

  • A comparison of mysqlnd plugins with MySQL Proxy
  • Obtaining the mysqlnd plugin API
  • MySQL Native Driver Plugin Architecture
  • The mysqlnd plugin API
  • Getting started building a mysqlnd plugin

The MySQL Native Driver Plugin API is a feature of MySQL Native Driver, or mysqlnd. Mysqlnd plugins operate in the layer between PHP applications and the MySQL server. This is comparable to MySQL Proxy. MySQL Proxy operates on a layer between any MySQL client application, for example, a PHP application and, the MySQL server. Mysqlnd plugins can undertake typical MySQL Proxy tasks such as load balancing, monitoring and performance optimizations. Due to the different architecture and location, mysqlnd plugins do not have some of MySQL Proxy's disadvantages. For example, with plugins, there is no single point of failure, no dedicated proxy server to deploy, and no new programming language to learn (Lua).

A mysqlnd plugin can be thought of as an extension to mysqlnd. Plugins can intercept the majority of mysqlnd functions. The mysqlnd functions are called by the PHP MySQL extensions such as ext/mysql, ext/mysqli, and PDO_MYSQL. As a result, it is possible for a mysqlnd plugin to intercept all calls made to these extensions from the client application.

Internal mysqlnd function calls can also be intercepted, or replaced. There are no restrictions on manipulating mysqlnd internal function tables. It is possible to set things up so that when certain mysqlnd functions are called by the extensions that use mysqlnd, the call is directed to the appropriate function in the mysqlnd plugin. The ability to manipulate mysqlnd internal function tables in this way allows maximum flexibility for plugins.

Mysqlnd plugins are in fact PHP Extensions, written in C, that use the mysqlnd plugin API (which is built into MySQL Native Driver, mysqlnd). Plugins can be made 100% transparent to PHP applications. No application changes are needed because plugins operate on a different layer. The mysqlnd plugin can be thought of as operating in a layer below mysqlnd.

The following list represents some possible applications of mysqlnd plugins.

  • Load Balancing

    • Read/Write Splitting. An example of this is the PECL/mysqlnd_ms (Master Slave) extension. This extension splits read/write queries for a replication setup.

    • Failover

    • Round-Robin, least loaded

  • Monitoring

    • Query Logging

    • Query Analysis

    • Query Auditing. An example of this is the PECL/mysqlnd_sip (SQL Injection Protection) extension. This extension inspects queries and executes only those that are allowed according to a ruleset.

  • Performance

    • Caching. An example of this is the PECL/mysqlnd_qc (Query Cache) extension.

    • Throttling

    • Sharding. An example of this is the PECL/mysqlnd_mc (Multi Connect) extension. This extension will attempt to split a SELECT statement into n-parts, using SELECT ... LIMIT part_1, SELECT LIMIT part_n. It sends the queries to distinct MySQL servers and merges the result at the client.

MySQL Native Driver Plugins Available

There are a number of mysqlnd plugins already available. These include:

  • PECL/mysqlnd_mc - Multi Connect plugin.

  • PECL/mysqlnd_ms - Master Slave plugin.

  • PECL/mysqlnd_qc - Query Cache plugin.

  • PECL/mysqlnd_pscache - Prepared Statement Handle Cache plugin.

  • PECL/mysqlnd_sip - SQL Injection Protection plugin.

  • PECL/mysqlnd_uh - User Handler plugin.

Notes
A comparison of mysqlnd plugins with MySQL Proxy
Mysqlnd


A comparison of mysqlnd plugins with MySQL Proxy

Mysqlnd plugins and MySQL Proxy are different technologies using different approaches. Both are valid tools for solving a variety of common tasks such as load balancing, monitoring, and performance enhancements. An important difference is that MySQL Proxy works with all MySQL clients, whereas mysqlnd plugins are specific to PHP applications.

As a PHP Extension, a mysqlnd plugin gets installed on the PHP application server, along with the rest of PHP. MySQL Proxy can either be run on the PHP application server or can be installed on a dedicated machine to handle multiple PHP application servers.

Deploying MySQL Proxy on the application server has two advantages:

  1. No single point of failure

  2. Easy to scale out (horizontal scale out, scale by client)

MySQL Proxy (and mysqlnd plugins) can solve problems easily which otherwise would have required changes to existing applications.

However, MySQL Proxy does have some disadvantages:

  • MySQL Proxy is a new component and technology to master and deploy.

  • MySQL Proxy requires knowledge of the Lua scripting language.

MySQL Proxy can be customized with C and Lua programming. Lua is the preferred scripting language of MySQL Proxy. For most PHP experts Lua is a new language to learn. A mysqlnd plugin can be written in C. It is also possible to write plugins in PHP using » PECL/mysqlnd_uh.

MySQL Proxy runs as a daemon - a background process. MySQL Proxy can recall earlier decisions, as all state can be retained. However, a mysqlnd plugin is bound to the request-based lifecycle of PHP. MySQL Proxy can also share one-time computed results among multiple application servers. A mysqlnd plugin would need to store data in a persistent medium to be able to do this. Another daemon would need to be used for this purpose, such as Memcache. This gives MySQL Proxy an advantage in this case.

MySQL Proxy works on top of the wire protocol. With MySQL Proxy you have to parse and reverse engineer the MySQL Client Server Protocol. Actions are limited to those that can be achieved by manipulating the communication protocol. If the wire protocol changes (which happens very rarely) MySQL Proxy scripts would need to be changed as well.

Mysqlnd plugins work on top of the C API, which mirrors the libmysql client and Connector/C APIs. This C API is basically a wrapper around the MySQL Client Server protocol, or wire protocol, as it is sometimes called. You can intercept all C API calls. PHP makes use of the C API, therefore you can hook all PHP calls, without the need to program at the level of the wire protocol.

Mysqlnd implements the wire protocol. Plugins can therefore parse, reverse engineer, manipulate and even replace the communication protocol. However, this is usually not required.

As plugins allow you to create implementations that use two levels (C API and wire protocol), they have greater flexibility than MySQL Proxy. If a mysqlnd plugin is implemented using the C API, any subsequent changes to the wire protocol do not require changes to the plugin itself.

MySQL Native Driver Plugin API
Obtaining the mysqlnd plugin API
MySQL Native Driver Plugin API


Obtaining the mysqlnd plugin API

The mysqlnd plugin API is simply part of the MySQL Native Driver PHP extension, ext/mysqlnd. Development started on the mysqlnd plugin API in December 2009. It is developed as part of the PHP source repository, and as such is available to the public either via SVN, or through source snapshot downloads.

The following table shows PHP versions and the corresponding mysqlnd version contained within.

PHP Version | MySQL Native Driver version
5.3.0 | 5.0.5
5.3.1 | 5.0.5
5.3.2 | 5.0.7
5.3.3 | 5.0.7
5.3.4 | 5.0.7

Plugin developers can determine the mysqlnd version through accessing MYSQLND_VERSION, which is a string of the format "mysqlnd 5.0.7-dev - 091210 - $Revision: 300535", or through MYSQLND_VERSION_ID, which is an integer such as 50007. Developers can calculate the version number as follows:

Version (part) | Example
Major*10000 | 5*10000 = 50000
Minor*100 | 0*100 = 0
Patch | 7 = 7
MYSQLND_VERSION_ID | 50007

During development, developers should refer to the mysqlnd version number for compatibility and version tests, as several iterations of mysqlnd could occur during the lifetime of a PHP development branch with a single PHP version number.

A comparison of mysqlnd plugins with MySQL Proxy
MySQL Native Driver Plugin Architecture
MySQL Native Driver Plugin API


MySQL Native Driver Plugin Architecture

This section provides an overview of the mysqlnd plugin architecture.

MySQL Native Driver Overview

Before developing mysqlnd plugins, it is useful to know a little of how mysqlnd itself is organized. Mysqlnd consists of the following modules:

Modules Statistics | mysqlnd_statistics.c
Connection | mysqlnd.c
Resultset | mysqlnd_result.c
Resultset Metadata | mysqlnd_result_meta.c
Statement | mysqlnd_ps.c
Network | mysqlnd_net.c
Wire protocol | mysqlnd_wireprotocol.c

C Object Oriented Paradigm

At the code level, mysqlnd uses a C pattern for implementing object orientation.

In C you use a struct to represent an object. Members of the struct represent object properties. Struct members pointing to functions represent methods.

Unlike with other languages such as C++ or Java, there are no fixed rules on inheritance in the C object oriented paradigm. However, there are some conventions that need to be followed that will be discussed later.

The PHP Life Cycle

When considering the PHP life cycle there are two basic cycles:

  • PHP engine startup and shutdown cycle

  • Request cycle

When the PHP engine starts up it will call the module initialization (MINIT) function of each registered extension. This allows each module to setup variables and allocate resources that will exist for the lifetime of the PHP engine process. When the PHP engine shuts down it will call the module shutdown (MSHUTDOWN) function of each extension.

During the lifetime of the PHP engine it will receive a number of requests. Each request constitutes another life cycle. On each request the PHP engine will call the request initialization function of each extension. The extension can perform any variable setup and resource allocation required for request processing. As the request cycle ends the engine calls the request shutdown (RSHUTDOWN) function of each extension so the extension can perform any cleanup required.

How a plugin works

A mysqlnd plugin works by intercepting calls made to mysqlnd by extensions that use mysqlnd. This is achieved by obtaining the mysqlnd function table, backing it up, and replacing it by a custom function table, which calls the functions of the plugin as required.

The following code shows how the mysqlnd function table is replaced:

/* a place to store orginal function table */
struct st_mysqlnd_conn_methods org_methods;

void minit_register_hooks(TSRMLS_D) {
  /* active function table */
  struct st_mysqlnd_conn_methods * current_methods
    = mysqlnd_conn_get_methods();

  /* backup original function table */
  memcpy(&org_methods, current_methods,
    sizeof(struct st_mysqlnd_conn_methods);

  /* install new methods */
  current_methods->query = MYSQLND_METHOD(my_conn_class, query);
}

Connection function table manipulations must be done during Module Initialization (MINIT). The function table is a global shared resource. In an multi-threaded environment, with a TSRM build, the manipulation of a global shared resource during the request processing will almost certainly result in conflicts.

Informacja:

Do not use any fixed-size logic when manipulating the mysqlnd function table: new methods may be added at the end of the function table. The function table may change at any time in the future.

Calling parent methods

If the original function table entries are backed up, it is still possible to call the original function table entries - the parent methods.

In some cases, such as for Connection::stmt_init(), it is vital to call the parent method prior to any other activity in the derived method.

MYSQLND_METHOD(my_conn_class, query)(MYSQLND *conn,
  const char *query, unsigned int query_len TSRMLS_DC) {

  php_printf("my_conn_class::query(query = %s)\n", query);

  query = "SELECT 'query rewritten' FROM DUAL";
  query_len = strlen(query);

  return org_methods.query(conn, query, query_len); /* return with call to parent */
}

Extending properties

A mysqlnd object is represented by a C struct. It is not possible to add a member to a C struct at run time. Users of mysqlnd objects cannot simply add properties to the objects.

Arbitrary data (properties) can be added to a mysqlnd objects using an appropriate function of the mysqlnd_plugin_get_plugin_<object>_data() family. When allocating an object mysqlnd reserves space at the end of the object to hold a void * pointer to arbitrary data. mysqlnd reserves space for one void * pointer per plugin.

The following table shows how to calculate the position of the pointer for a specific plugin:

Memory address | Contents
0 | Beginning of the mysqlnd object C struct
n | End of the mysqlnd object C struct
n + (m x sizeof(void*)) | void* to object data of the m-th plugin

If you plan to subclass any of the mysqlnd object constructors, which is allowed, you must keep this in mind!

The following code shows extending properties:

/* any data we want to associate */
typedef struct my_conn_properties {
  unsigned long query_counter;
} MY_CONN_PROPERTIES;

/* plugin id */
unsigned int my_plugin_id;

void minit_register_hooks(TSRMLS_D) {
  /* obtain unique plugin ID */
  my_plugin_id = mysqlnd_plugin_register();
  /* snip - see Extending Connection: methods */
}

static MY_CONN_PROPERTIES** get_conn_properties(const MYSQLND *conn TSRMLS_DC) {
  MY_CONN_PROPERTIES** props;
  props = (MY_CONN_PROPERTIES**)mysqlnd_plugin_get_plugin_connection_data(
    conn, my_plugin_id);
  if (!props || !(*props)) {
    *props = mnd_pecalloc(1, sizeof(MY_CONN_PROPERTIES), conn->persistent);
    (*props)->query_counter = 0;
  }
  return props;
}

The plugin developer is responsible for the management of plugin data memory.

Use of the mysqlnd memory allocator is recommended for plugin data. These functions are named using the convention: mnd_*loc(). The mysqlnd allocator has some useful features, such as the ability to use a debug allocator in a non-debug build.

When and how to subclass

 | When to subclass? | Each instance has its own private function table? | How to subclass?
Connection (MYSQLND) | MINIT | No | mysqlnd_conn_get_methods()
Resultset (MYSQLND_RES) | MINIT or later | Yes | mysqlnd_result_get_methods() or object method function table manipulation
Resultset Meta (MYSQLND_RES_METADATA) | MINIT | No | mysqlnd_result_metadata_get_methods()
Statement (MYSQLND_STMT) | MINIT | No | mysqlnd_stmt_get_methods()
Network (MYSQLND_NET) | MINIT or later | Yes | mysqlnd_net_get_methods() or object method function table manipulation
Wire protocol (MYSQLND_PROTOCOL) | MINIT or later | Yes | mysqlnd_protocol_get_methods() or object method function table manipulation

You must not manipulate function tables at any time later than MINIT if it is not allowed according to the above table.

Some classes contain a pointer to the method function table. All instances of such a class will share the same function table. To avoid chaos, in particular in threaded environments, such function tables must only be manipulated during MINIT.

Other classes use copies of a globally shared function table. The class function table copy is created together with the object. Each object uses its own function table. This gives you two options: you can manipulate the default function table of an object at MINIT, and you can additionally refine methods of an object without impacting other instances of the same class.

The advantage of the shared function table approach is performance. There is no need to copy a function table for each and every object.

Constructors

Allocation, construction, reset | Can be modified? | Caller
Connection (MYSQLND) | mysqlnd_init() | No | mysqlnd_connect()
Resultset(MYSQLND_RES)

Allocation:

  • Connection::result_init()

Reset and re-initialized during:

  • Result::use_result()

  • Result::store_result

Yes, but call parent!

  • Connection::list_fields()

  • Statement::get_result()

  • Statement::prepare() (Metadata only)

  • Statement::resultMetaData()

Resultset Meta (MYSQLND_RES_METADATA) | Connection::result_meta_init() | Yes, but call parent! | Result::read_result_metadata()
Statement (MYSQLND_STMT) | Connection::stmt_init() | Yes, but call parent! | Connection::stmt_init()
Network (MYSQLND_NET) | mysqlnd_net_init() | No | Connection::init()
Wire protocol (MYSQLND_PROTOCOL) | mysqlnd_protocol_init() | No | Connection::init()

It is strongly recommended that you do not entirely replace a constructor. The constructors perform memory allocations. The memory allocations are vital for the mysqlnd plugin API and the object logic of mysqlnd. If you do not care about warnings and insist on hooking the constructors, you should at least call the parent constructor before doing anything in your constructor.

Regardless of all warnings, it can be useful to subclass constructors. Constructors are the perfect place for modifying the function tables of objects with non-shared object tables, such as Resultset, Network, Wire Protocol.

Destruction

 | Derived method must call parent? | Destructor
Connection | yes, after method execution | free_contents(), end_psession()
Resultset | yes, after method execution | free_result()
Resultset Meta | yes, after method execution | free()
Statement | yes, after method execution | dtor(), free_stmt_content()
Network | yes, after method execution | free()
Wire protocol | yes, after method execution | free()

The destructors are the appropriate place to free properties, mysqlnd_plugin_get_plugin_<object>_data().

The listed destructors may not be equivalent to the actual mysqlnd method freeing the object itself. However, they are the best possible place for you to hook in and free your plugin data. As with constructors you may replace the methods entirely but this is not recommended. If multiple methods are listed in the above table you will need to hook all of the listed methods and free your plugin data in whichever method is called first by mysqlnd.

The recommended method for plugins is to simply hook the methods, free your memory and call the parent implementation immediately following this.

Uwaga

Due to a bug in PHP versions 5.3.0 to 5.3.3, plugins do not associate plugin data with a persistent connection. This is because ext/mysql and ext/mysqli do not trigger all the necessary mysqlnd end_psession() method calls and the plugin may therefore leak memory. This has been fixed in PHP 5.3.4.

Obtaining the mysqlnd plugin API
The mysqlnd plugin API
MySQL Native Driver Plugin API


The mysqlnd plugin API

The following is a list of functions provided in the mysqlnd plugin API:

  • mysqlnd_plugin_register()

  • mysqlnd_plugin_count()

  • mysqlnd_plugin_get_plugin_connection_data()

  • mysqlnd_plugin_get_plugin_result_data()

  • mysqlnd_plugin_get_plugin_stmt_data()

  • mysqlnd_plugin_get_plugin_net_data()

  • mysqlnd_plugin_get_plugin_protocol_data()

  • mysqlnd_conn_get_methods()

  • mysqlnd_result_get_methods()

  • mysqlnd_result_meta_get_methods()

  • mysqlnd_stmt_get_methods()

  • mysqlnd_net_get_methods()

  • mysqlnd_protocol_get_methods()

There is no formal definition of what a plugin is and how a plugin mechanism works.

Components often found in plugins mechanisms are:

  • A plugin manager

  • A plugin API

  • Application services (or modules)

  • Application service APIs (or module APIs)

The mysqlnd plugin concept employs these features, and additionally enjoys an open architecture.

No Restrictions

A plugin has full access to the inner workings of mysqlnd. There are no security limits or restrictions. Everything can be overwritten to implement friendly or hostile algorithms. It is recommended you only deploy plugins from a trusted source.

As discussed previously, plugins can use pointers freely. These pointers are not restricted in any way, and can point into another plugin's data. Simple offset arithmetic can be used to read another plugin's data.

It is recommended that you write cooperative plugins, and that you always call the parent method. The plugins should always cooperate with mysqlnd itself.

Issues: an example of chaining and cooperation

Extension | mysqlnd.query() pointer | call stack if calling parent
ext/mysqlnd | mysqlnd.query() | mysqlnd.query
ext/mysqlnd_cache mysqlnd_cache.query()

  1. mysqlnd_cache.query()

  2. mysqlnd.query

ext/mysqlnd_monitor mysqlnd_monitor.query()

  1. mysqlnd_monitor.query()

  2. mysqlnd_cache.query()

  3. mysqlnd.query

In this scenario, a cache (ext/mysqlnd_cache) and a monitor (ext/mysqlnd_monitor) plugin are loaded. Both subclass Connection::query(). Plugin registration happens at MINIT using the logic shown previously. PHP calls extensions in alphabetical order by default. Plugins are not aware of each other and do not set extension dependencies.

By default the plugins call the parent implementation of the query method in their derived version of the method.

PHP Extension Recap

This is a recap of what happens when using an example plugin, ext/mysqlnd_plugin, which exposes the mysqlnd C plugin API to PHP:

  • Any PHP MySQL application tries to establish a connection to 192.168.2.29

  • The PHP application will either use ext/mysql, ext/mysqli or PDO_MYSQL. All three PHP MySQL extensions use mysqlnd to establish the connection to 192.168.2.29.

  • Mysqlnd calls its connect method, which has been subclassed by ext/mysqlnd_plugin.

  • ext/mysqlnd_plugin calls the userspace hook proxy::connect() registered by the user.

  • The userspace hook changes the connection host IP from 192.168.2.29 to 127.0.0.1 and returns the connection established by parent::connect().

  • ext/mysqlnd_plugin performs the equivalent of parent::connect(127.0.0.1) by calling the original mysqlnd method for establishing a connection.

  • ext/mysqlnd establishes a connection and returns to ext/mysqlnd_plugin. ext/mysqlnd_plugin returns as well.

  • Whatever PHP MySQL extension had been used by the application, it receives a connection to 127.0.0.1. The PHP MySQL extension itself returns to the PHP application. The circle is closed.

MySQL Native Driver Plugin Architecture
Getting started building a mysqlnd plugin
MySQL Native Driver Plugin API


Getting started building a mysqlnd plugin

It is important to remember that a mysqlnd plugin is itself a PHP extension.

The following code shows the basic structure of the MINIT function that will be used in the typical mysqlnd plugin:

/* my_php_mysqlnd_plugin.c */

 static PHP_MINIT_FUNCTION(mysqlnd_plugin) {
  /* globals, ini entries, resources, classes */

  /* register mysqlnd plugin */
  mysqlnd_plugin_id = mysqlnd_plugin_register();

  conn_m = mysqlnd_get_conn_methods();
  memcpy(org_conn_m, conn_m,
    sizeof(struct st_mysqlnd_conn_methods));

  conn_m->query = MYSQLND_METHOD(mysqlnd_plugin_conn, query);
  conn_m->connect = MYSQLND_METHOD(mysqlnd_plugin_conn, connect);
}

/* my_mysqlnd_plugin.c */

 enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, query)(/* ... */) {
  /* ... */
}
enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, connect)(/* ... */) {
  /* ... */
}

Task analysis: from C to userspace

 class proxy extends mysqlnd_plugin_connection {
  public function connect($host, ...) { .. }
}
mysqlnd_plugin_set_conn_proxy(new proxy());

Process:

  1. PHP: user registers plugin callback

  2. PHP: user calls any PHP MySQL API to connect to MySQL

  3. C: ext/*mysql* calls mysqlnd method

  4. C: mysqlnd ends up in ext/mysqlnd_plugin

  5. C: ext/mysqlnd_plugin

    1. Calls userspace callback

    2. Or orginal mysqlnd method, if userspace callback not set

You need to carry out the following:

  1. Write a class "mysqlnd_plugin_connection" in C

  2. Accept and register proxy object through "mysqlnd_plugin_set_conn_proxy()"

  3. Call userspace proxy methods from C (optimization - zend_interfaces.h)

Userspace object methods can either be called using call_user_function() or you can operate at a level closer to the Zend Engine and use zend_call_method().

Optimization: calling methods from C using zend_call_method

The following code snippet shows the prototype for the zend_call_method function, taken from zend_interfaces.h.

 ZEND_API zval* zend_call_method(
  zval **object_pp, zend_class_entry *obj_ce,
  zend_function **fn_proxy, char *function_name,
  int function_name_len, zval **retval_ptr_ptr,
  int param_count, zval* arg1, zval* arg2 TSRMLS_DC
);

Zend API supports only two arguments. You may need more, for example:

 enum_func_status (*func_mysqlnd_conn__connect)(
  MYSQLND *conn, const char *host,
  const char * user, const char * passwd,
  unsigned int passwd_len, const char * db,
  unsigned int db_len, unsigned int port,
  const char * socket, unsigned int mysql_flags TSRMLS_DC
);

To get around this problem you will need to make a copy of zend_call_method() and add a facility for additional parameters. You can do this by creating a set of MY_ZEND_CALL_METHOD_WRAPPER macros.

Calling PHP userspace

This code snippet shows the optimized method for calling a userspace function from C:

/* my_mysqlnd_plugin.c */

MYSQLND_METHOD(my_conn_class,connect)(
  MYSQLND *conn, const char *host /* ... */ TSRMLS_DC) {
  enum_func_status ret = FAIL;
  zval * global_user_conn_proxy = fetch_userspace_proxy();
  if (global_user_conn_proxy) {
    /* call userspace proxy */
    ret = MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, host, /*...*/);
  } else {
    /* or original mysqlnd method = do nothing, be transparent */
    ret = org_methods.connect(conn, host, user, passwd,
          passwd_len, db, db_len, port,
          socket, mysql_flags TSRMLS_CC);
  }
  return ret;
}

Calling userspace: simple arguments

/* my_mysqlnd_plugin.c */

 MYSQLND_METHOD(my_conn_class,connect)(
  /* ... */, const char *host, /* ...*/) {
  /* ... */
  if (global_user_conn_proxy) {
    /* ... */
    zval* zv_host;
    MAKE_STD_ZVAL(zv_host);
    ZVAL_STRING(zv_host, host, 1);
    MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_host /*, ...*/);
    zval_ptr_dtor(&zv_host);
    /* ... */
  }
  /* ... */
}

Calling userspace: structs as arguments

/* my_mysqlnd_plugin.c */

MYSQLND_METHOD(my_conn_class, connect)(
  MYSQLND *conn, /* ...*/) {
  /* ... */
  if (global_user_conn_proxy) {
    /* ... */
    zval* zv_conn;
    ZEND_REGISTER_RESOURCE(zv_conn, (void *)conn, le_mysqlnd_plugin_conn);
    MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_conn, zv_host /*, ...*/);
    zval_ptr_dtor(&zv_conn);
    /* ... */
  }
  /* ... */
}

The first argument of many mysqlnd methods is a C "object". For example, the first argument of the connect() method is a pointer to MYSQLND. The struct MYSQLND represents a mysqlnd connection object.

The mysqlnd connection object pointer can be compared to a standard I/O file handle. Like a standard I/O file handle a mysqlnd connection object shall be linked to the userspace using the PHP resource variable type.

From C to userspace and back

 class proxy extends mysqlnd_plugin_connection {
  public function connect($conn, $host, ...) {
    /* "pre" hook */
    printf("Connecting to host = '%s'\n", $host);
    debug_print_backtrace();
    return parent::connect($conn);
  }

  public function query($conn, $query) {
    /* "post" hook */
    $ret = parent::query($conn, $query);
    printf("Query = '%s'\n", $query);
    return $ret;
  }
}
mysqlnd_plugin_set_conn_proxy(new proxy());

PHP users must be able to call the parent implementation of an overwritten method.

As a result of subclassing it is possible to refine only selected methods and you can choose to have "pre" or "post" hooks.

Buildin class: mysqlnd_plugin_connection::connect()

/*  my_mysqlnd_plugin_classes.c */

 PHP_METHOD("mysqlnd_plugin_connection", connect) {
  /* ... simplified! ... */
  zval* mysqlnd_rsrc;
  MYSQLND* conn;
  char* host; int host_len;
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs",
    &mysqlnd_rsrc, &host, &host_len) == FAILURE) {
    RETURN_NULL();
  }
  ZEND_FETCH_RESOURCE(conn, MYSQLND* conn, &mysqlnd_rsrc, -1,
    "Mysqlnd Connection", le_mysqlnd_plugin_conn);
  if (PASS == org_methods.connect(conn, host, /* simplified! */ TSRMLS_CC))
    RETVAL_TRUE;
  else
    RETVAL_FALSE;
}
The mysqlnd plugin API
mysqlnd_ms
MySQL Native Driver Plugin API


Mysqlnd replication and load balancing plugin

  • Wstęp
  • Quickstart and Examples
    • Setup
    • Running statements
    • Connection state
    • SQL Hints
    • Transactions
    • Service level and consistency
    • Global transaction IDs
  • Concepts
    • Architecture
    • Connection pooling and switching
    • Transaction handling
    • Error handling
    • Failover
    • Load balancing
    • Read-write splitting
    • Filter
    • Service level and consistency
    • Global transaction IDs
    • Supported clusters
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Plugin configuration file (>=1.1.x)
    • Plugin configuration file (<= 1.0.x)
    • Testing
    • Debugging and Tracing
    • Monitoring
  • Stałe predefiniowane
  • Mysqlnd_ms Funkcje
    • mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID
    • mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection
    • mysqlnd_ms_get_stats — Returns query distribution and connection statistics
    • mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not
    • mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server
    • mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster
    • mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting
  • Change History
    • PECL/mysqlnd_ms 1.2 series
    • PECL/mysqlnd_ms 1.1 series
    • PECL/mysqlnd_ms 1.0 series
Getting started building a mysqlnd plugin
Wstęp
MySQL


Wstęp

The mysqlnd replication and load balancing plugin (mysqlnd_ms) adds easy to use MySQL replication support to all PHP MySQL extensions that use mysqlnd.

As of version PHP 5.3.3 the MySQL native driver for PHP (mysqlnd) features an internal plugin C API. C plugins, such as the replication and load balancing plugin, can extend the functionality of mysqlnd.

The MySQL native driver for PHP is a C library that ships together with PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL Client Library (libmysql/libmysqlclient). Using mysqlnd has several advantages: no extra downloads are required because it's bundled with PHP, it's under the PHP license, there is lower memory consumption in certain cases, and it contains new functionality such as asynchronous queries.

Mysqlnd plugins like mysqlnd_ms operate, for the most part, transparently from a user perspective. The replication and load balancing plugin supports all PHP applications, and all MySQL PHP extensions. It does not change existing APIs. Therefore, it can easily be used with existing PHP applications.

Informacja:

The mysqlnd replication and load balancing plugin is a beta plugin, and is not feature complete.

Key Features

The key features of PECL/mysqlnd_ms are as follows.

  • Transparent and therefore easy to use.

    • Supports all of the PHP MySQL extensions.

    • SSL support.

    • A consistent API.

    • Little to no application changes required, dependent on the required usage scenario.

    • Lazy connections: connections to master and slave servers are not opened before a SQL statement is executed.

    • Optional: automatic use of master after the first write in a web request, to lower the possible impact of replication lag.

  • Featured read-write split strategies

    • Automatic detection of SELECT.

    • Supports SQL hints to overrule automatism.

    • User-defined.

    • Can be disabled for, for example, when using synchronous clusters such as MySQL Cluster.

  • Featured load balancing strategies

    • Round Robin: choose a different slave in round-robin fashion for every slave request.

    • Random: choose a random slave for every slave request.

    • Random once (sticky): choose a random slave once to run all slave requests for the duration of a web request.

    • User-defined. The application can register callbacks with mysqlnd_ms.

    • PHP 5.4.0 or newer: transaction aware when using API calls only to control transactions.

  • Global transaction ID

    • Client-side emulation. Makes manual master server failover and slave promotion easier with asynchronous clusters, such as MySQL Replication.

    • Supports using transaction ids to identify up-to-date asynchronous slaves for reading when session consistency is required.

  • Service and consistency levels

    • Applications can request eventual, session and strong consistency service levels for connections. Appropriate cluster nodes will be searched automatically.

Limitations

The plugin does not support MySQL replication setups with more than one master server. The experimental configuration setting mysqlnd_ms.multi_master was introduced in version 1.1.0-beta, to help find ways to remove this limitation and to enable the use of synchronous clusters, such as MySQL Cluster.

The built-in read/write-split mechanism is very basic. Every query which starts with SELECT is considered a read request to be sent to a MySQL slave server. All other queries (such as SHOW statements) are considered as write requests that are sent to the MySQL master server. The build-in behavior can be overruled using SQL hints, or a user-defined callback function.

The read/write splitter is not aware of multi-statements. Multi-statements are considered as one statement. The decision of where to run the statement will be based on the beginning of the statement string. For example, if using mysqli_multi_query() to execute the multi-statement SELECT id FROM test ; INSERT INTO test(id) VALUES (1), the statement will be redirected to a slave server because it begins with SELECT. The INSERT statement, which is also part of the multi-statement, will not be redirected to a master server.

Prior to version 1.1.0-beta, the plugin did not support native prepared statements. Please note that PDO_MySQL uses client-side prepared statement emulation by default. Client-side emulated prepared statements are fully supported by any version of the replication and load balancing plugin because the emulation is not using native prepared statements. If you are using PHP based database abstraction, please consult the vendor manual to learn if a client-side prepared statement emulation is used.

Informacja:

Applications must be aware of the consequences of connection switches that are performed for load balancing purposes. Please check the documentation on connection pooling and switching, transaction handling, failover load balancing i read-write splitting.

On the name

The shortcut mysqlnd_ms stands for mysqlnd master slave plugin. The name was chosen for a quick-and-dirty proof-of-concept. In the beginning the developers did not expect to continue using the code base.

mysqlnd_ms
Quickstart and Examples
mysqlnd_ms


Quickstart and Examples

Spis treści

  • Setup
  • Running statements
  • Connection state
  • SQL Hints
  • Transactions
  • Service level and consistency
  • Global transaction IDs

The mysqlnd replication load balancing plugin is easy to use. This quickstart will demo typical use-cases, and provide practical advice on getting started.

It is strongly recommended to read the reference sections in addition to the quickstart. The quickstart tries to avoid discussing theoretical concepts and limitations. Instead, it will link to the reference sections. It is safe to begin with the quickstart. However, before using the plugin in mission critical environments we urge you to read additionally the background information from the reference sections.

The focus is on using PECL mysqlnd_ms for work with an asynchronous MySQL cluster, namelys MySQL replication. Generally speaking an asynchronous cluster is more difficult to use than a synchronous one. Thus, users of, for example, MySQL Cluster will find more information than needed.

Informacja:

The documentation has been updated to show the syntax used as of version 1.1.0-beta. PECL/mysqlnd_ms 1.1.0-beta introduces many changes. Among others, it is using a new JSON based plugin configuration file format.

Wstęp
Setup
mysqlnd_ms


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install the » PECL/mysqlnd_ms extension.

Compile or configure the PHP MySQL extension (API) (mysqli, PDO_MYSQL, mysql) that you plan to use with support for the mysqlnd library. PECL/mysqlnd_ms is a plugin for the mysqlnd library. To use the plugin with any of the PHP MySQL extensions, the extension has to use the mysqlnd library.

Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_ms.enable.

Przykład #1 Enabling the plugin (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.ini_file=/path/to/mysqlnd_ms_plugin.ini

The plugin uses its own configuration file. Use the PHP configuration directive mysqlnd_ms.ini_file to set the full file path to the plugin-specific configuration file. This file must be readable by PHP (e.g., the web server user).

Create a plugin-specific configuration file. Save the file to the path set by the PHP configuration directive mysqlnd_ms.ini_file.

The plugins configuration file is JSON based. It is divided into one or more sections. Each section has a name, for example, myapp. Every section makes its own set of configuration settings.

A section must, at a minimum, list the MySQL replication master server, and set a list of slaves. The plugin supports using only one master server per section. Multi-master MySQL replication setups are not yet fully supported. Use the configuration setting master to set the hostname, and the port or socket of the MySQL master server. MySQL slave servers are configured using the slave keyword.

Przykład #2 Minimal plugin-specific configuration file (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": [

        ]
    }
}

Configuring a MySQL slave server list is required, although it may contain an empty list. It is recommended to always configure at least one slave server.

Server lists can use anonymous or non-anonymous syntax. Non-anonymous lists include alias names for the servers, such as master_0 for the master in the above example. The quickstart uses the more verbose non-anonymous syntax.

Przykład #3 Recommended minimal plugin-specific config (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

If there are at least two servers in total, the plugin can start to load balance and switch connections. Switching connections is not always transparent and can cause issues in certain cases. The reference sections about connection pooling and switching, transaction handling, fail over load balancing and read-write splitting all provide more details. And potential pitfalls are described later in this guide.

It is the responsibility of the application to handle potential issues caused by connection switches, by configuring a master with at least one slave server, which allows switching to work therefore related problems can be found.

The MySQL master and MySQL slave servers, which you configure, do not need to be part of MySQL replication setup. For testing purpose you can use single MySQL server and make it known to the plugin as a master and slave server as shown below. This could help you to detect many potential issues with connection switches. However, such a setup will not be prone to the issues caused by replication lag.

Przykład #4 Using one server as a master and as a slave (testing only!)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

Quickstart and Examples
Running statements
Quickstart and Examples


Running statements

The plugin can be used with any PHP MySQL extension (mysqli, mysql, and PDO_MYSQL) that is compiled to use the mysqlnd library. PECL/mysqlnd_ms plugs into the mysqlnd library. It does not change the API or behavior of those extensions.

Whenever a connection to MySQL is being opened, the plugin compares the host parameter value of the connect call, with the section names from the plugin specific configuration file. If, for example, the plugin specific configuration file has a section myapp then the section should be referenced by opening a MySQL connection to the host myapp

Przykład #1 Plugin specific configuration file (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Przykład #2 Opening a load balanced connection

<?php
/* Load balanced following "myapp" section rules from the plugins config file */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");
?>

The connection examples above will be load balanced. The plugin will send read-only statements to the MySQL slave server with the IP 192.168.2.27 and will listen on port 3306 for the MySQL client connection. All other statements will be directed to the MySQL master server running on the host localhost. If on Unix like operating systems, the master on localhost will be accepting MySQL client connections on the Unix domain socket /tmp/mysql.sock, while TCP/IP is the default port on Windows. The plugin will use the user name username and the password password to connect to any of the MySQL servers listed in the section myapp of the plugins configuration file. Upon connect, the plugin will select database as the current schemata.

The username, password and schema name are taken from the connect API calls and used for all servers. In other words: you must use the same username and password for every MySQL server listed in a plugin configuration file section. The is not a general limitation. As of PECL/mysqlnd_ms 1.1.0, it is possible to set the username and password for any server in the plugins configuration file, to be used instead of the credentials passed to the API call.

The plugin does not change the API for running statements. Read-write splitting works out of the box. The following example assumes that there is no significant replication lag between the master and the slave.

Przykład #3 Executing statements

<?php
/* Load balanced following "myapp" section rules from the plugins config file */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Statements will be run on the master */
if (!$mysqli->query("DROP TABLE IF EXISTS test")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
if (!$mysqli->query("CREATE TABLE test(id INT)")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* read-only: statement will be run on a slave */
if (!($res = $mysqli->query("SELECT id FROM test")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("Slave returns id = '%s'\n", $row['id'];
}
$mysqli->close();
?>

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

Slave returns id = '1'

Setup
Connection state
Quickstart and Examples


Connection state

The plugin changes the semantics of a PHP MySQL connection handle. A new connection handle represents a connection pool, instead of a single MySQL client-server network connection. The connection pool consists of a master connection, and optionally any number of slave connections.

Every connection from the connection pool has its own state. For example, SQL user variables, temporary tables and transactions are part of the state. For a complete list of items that belong to the state of a connection, see the connection pooling and switching concepts documentation. If the plugin decides to switch connections for load balancing, the application could be given a connection which has a different state. Applications must be made aware of this.

Przykład #1 Plugin config with one slave and one master

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Przykład #2 Pitfall: connection state and SQL user variables

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, run on slave because SELECT */
if (!($res = $mysqli->query("SELECT @myrole AS _role"))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

Powyższy przykład wyświetli:

@myrole = ''

The example opens a load balanced connection and executes two statements. The first statement SET @myrole='master' does not begin with the string SELECT. Therefore the plugin does not recognize it as a read-only query which shall be run on a slave. The plugin runs the statement on the connection to the master. The statement sets a SQL user variable which is bound to the master connection. The state of the master connection has been changed.

The next statement is SELECT @myrole AS _role. The plugin does recognize it as a read-only query and sends it to the slave. The statement is run on a connection to the slave. This second connection does not have any SQL user variables bound to it. It has a different state than the first connection to the master. The requested SQL user variable is not set. The example script prints @myrole = ''.

It is the responsibility of the application developer to take care of the connection state. The plugin does not monitor all connection state changing activities. Monitoring all possible cases would be a very CPU intensive task, if it could be done at all.

The pitfalls can easily be worked around using SQL hints.

Running statements
SQL Hints
Quickstart and Examples


SQL Hints

SQL hints can force a query to choose a specific server from the connection pool. It gives the plugin a hint to use a designated server, which can solve issues caused by connection switches and connection state.

SQL hints are standard compliant SQL comments. Because SQL comments are supposed to be ignored by SQL processing systems, they do not interfere with other programs such as the MySQL Server, the MySQL Proxy, or a firewall.

Three SQL hints are supported by the plugin: The MYSQLND_MS_MASTER_SWITCH hint makes the plugin run a statement on the master, MYSQLND_MS_SLAVE_SWITCH enforces the use of the slave, and MYSQLND_MS_MASTER_SWITCH will run a statement on the same server that was used for the previous statement.

The plugin scans the beginning of a statement for the existence of an SQL hint. SQL hints are only recognized if they appear at the beginning of the statement.

Przykład #1 Plugin config with one slave and one master

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Przykład #2 SQL hints to prevent connection switches

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 1, run on master because of SQL hint */
if (!($res = $mysqli->query(sprintf("/*%s*/SELECT @myrole AS _role", MYSQLND_MS_LAST_USED_SWITCH)))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

Powyższy przykład wyświetli:

@myrole = 'master'

In the above example, using MYSQLND_MS_LAST_USED_SWITCH prevents session switching from the master to a slave when running the SELECT statement.

SQL hints can also be used to run SELECT statements on the MySQL master server. This may be desired if the MySQL slave servers are typically behind the master, but you need current data from the cluster.

In version 1.2.0 the concept of a service level has been introduced to address cases when current data is required. Using a service level requires less attention and removes the need of using SQL hints for this use case. Please, find more information below in the service level and consistency section.

Przykład #3 Fighting replication lag

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Force use of master, master has always fresh and current data */
if (!$mysqli->query(sprintf("/*%s*/SELECT critical_data FROM important_table", MYSQLND_MS_MASTER_SWITCH))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
?>

A use case may include the creation of tables on a slave. If an SQL hint is not given, then the plugin will send CREATE and INSERT statements to the master. Use the SQL hint MYSQLND_MS_SLAVE_SWITCH if you want to run any such statement on a slave, for example, to build temporary reporting tables.

Przykład #4 Table creation on a slave

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Force use of slave */
if (!$mysqli->query(sprintf("/*%s*/CREATE TABLE slave_reporting(id INT)", MYSQLND_MS_SLAVE_SWITCH))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Continue using this particular slave connection */
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO slave_reporting(id) VALUES (1), (2), (3)", MYSQLND_MS_LAST_USED_SWITCH))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Don't use MYSQLND_MS_SLAVE_SWITCH which would allow switching to another slave! */
if ($res = $mysqli->query(sprintf("/*%s*/SELECT COUNT(*) AS _num FROM slave_reporting", MYSQLND_MS_LAST_USED_SWITCH))) {
  $row = $res->fetch_assoc();
  $res->close();
  printf("There are %d rows in the table 'slave_reporting'", $row['_num']);
} else {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
$mysqli->close();
?>

The SQL hint MYSQLND_MS_LAST_USED forbids switching a connection, and forces use of the previously used connection.

Connection state
Transactions
Quickstart and Examples


Transactions

The current version of the plugin is not transaction safe by default, because it is not transaction aware. SQL transactions are units of work to be run on a single server. The plugin does not know when the unit of work starts and when it ends. Therefore, the plugin may decide to switch connections in the middle of a transaction.

You can either use SQL hints to work around this limitation. Alternatively, you can activate transaction API call monitoring. In the latter case you must use API calls only to control transactins, see below.

Przykład #1 Plugin config with one slave and one master

[myapp]
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Przykład #2 Using SQL hints for transactions

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Not a SELECT, will use master */
if (!$mysqli->query("START TRANSACTION")) {
 /* Please use better error handling in your code */
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Prevent connection switch! */
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO test(id) VALUES (1)", MYSQLND_MS_LAST_USED_SWITCH)))) {
 /* Please do proper ROLLBACK in your code, don't just die */
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if ($res = $mysqli->query(sprintf("/*%s*/SELECT COUNT(*) AS _num FROM test", MYSQLND_MS_LAST_USED_SWITCH)))) {
  $row = $res->fetch_assoc();
  $res->close();
  if ($row['_num'] > 1000) {
   if (!$mysqli->query(sprintf("/*%s*/INSERT INTO events(task) VALUES ('cleanup')", MYSQLND_MS_LAST_USED_SWITCH)))) {
     die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
   }
  }
} else {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query(sprintf("/*%s*/UPDATE log SET last_update = NOW()", MYSQLND_MS_LAST_USED_SWITCH)))) {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query(sprintf("/*%s*/COMMIT", MYSQLND_MS_LAST_USED_SWITCH)))) {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

$mysqli->close();
?>

Starting with PHP 5.4.0, the mysqlnd library allows the plugin to monitor the status of the autocommit mode, if the mode is set by API calls instead of using SQL statements such as SET AUTOCOMMIT=0. This makes it possible for the plugin to become transaction aware.

If using PHP 5.4.0 or newer, API calls that enable autocommit mode, and when setting the plugin configuration option trx_stickiness=master, the plugin can automatically disable load balancing and connection switches for SQL transactions. In this configuration, the plugin stops load balancing if autocommit is disabled and directs all statements to the master. This prevents connection switches in the middle of a transaction. Once autocommit is re-enabled, the plugin starts to load balance statements again.

Przykład #3 Transaction aware load balancing: trx_stickiness setting

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "trx_stickiness": "master"
    }
}

Przykład #4 Transaction aware

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Disable autocommit, plugin will run all statements on the master */
$mysqli->autocommit(FALSE);

if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
 /* Please do proper ROLLBACK in your code, don't just die */
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if ($res = $mysqli->query("SELECT COUNT(*) AS _num FROM test")) {
  $row = $res->fetch_assoc();
  $res->close();
  if ($row['_num'] > 1000) {
   if (!$mysqli->query("INSERT INTO events(task) VALUES ('cleanup')")) {
     die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
   }
  }
} else {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query("UPDATE log SET last_update = NOW()")) {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->commit()) {
 die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Plugin assumes that the transaction has ended and starts load balancing again */
$mysqli->autocommit(TRUE);
$mysqli->close();
?>

Informacja: Version requirement

The plugin configuration option trx_stickiness=master requires PHP 5.4.0 or newer.

SQL Hints
Service level and consistency
Quickstart and Examples


Service level and consistency

Informacja: Version requirement

Service levels have been introduced in PECL mysqlnd_ms version 1.2.0-alpha. mysqlnd_ms_set_qos() is available with PHP 5.4.0 or newer.

Different types of MySQL cluster solutions offer different service and data consistency levels to their users. An asynchronous MySQL replication cluster offers eventual consistency by default. A read executed on an asynchronous slave may return current, stale or no data at all, depending on whether the slave has replayed all changesets from the master or not.

Applications using an MySQL replication cluster need to be designed to work correctly with eventual consistent data. In some cases, however, stale data is not acceptable. In those cases only certain slaves or even only master accesses are allowed to achieve the required quality of service from the cluster.

As of PECL mysqlnd_ms 1.2.0 the plugin is capable of selecting MySQL replication nodes automatically that deliver session consistency or strong consistency. Session consistency means that one client can read its writes. Other clients may or may not see the clients' write. Strong consistency means that all clients will see all writes from the client.

Przykład #1 Session consistency: read your writes

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

Przykład #2 Requesting session consistency

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* read-write splitting: master used */
if (!$mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')")) {
   /* Please use better error handling in your code */
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Request session consistency: read your writes */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Plugin picks a node which has the changes, here: master */
if (!$res = $mysqli->query("SELECT item FROM orders WHERE order_id = 1"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

var_dump($res->fetch_assoc());

/* Back to eventual consistency: stale data allowed */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Plugin picks any slave, stale data is allowed */
if (!$res = $mysqli->query("SELECT item, price FROM specials"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

Service levels can be set in the plugins configuration file and at runtime using mysqlnd_ms_set_qos(). In the example the function is used to enforce session consistency (read your writes) for all future statements until further notice. The SELECT statement on the orders table is run on the master to ensure the previous write can be seen by the client. Read-write splitting logic has been adapted to fulfill the service level.

After the application has read its changes from the orders table it returns to the default service level, which is eventual consistency. Eventual consistency puts no restrictions on choosing a node for statement execution. Thus, the SELECT statement on the specials table is executed on a slave.

The new functionality supersedes the use of SQL hints and the master_on_write configuration option. In many cases mysqlnd_ms_set_qos() is easier to use, more powerful improves portability.

Przykład #3 Maximum age/slave lag

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "failover" : "master"
    }
}

Przykład #4 Limiting slave lag

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Read from slaves lagging no more than four seconds */
$ret = mysqlnd_ms_set_qos($mysqli,
         MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL,
         MYSQLND_MS_QOS_OPTION_AGE, 4);

if (!$ret)
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Plugin picks any slave, which may or may not have the changes */
if (!$res = $mysqli->query("SELECT item, price FROM daytrade"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Back to default: use of all slaves and masters permitted */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

The eventual consistency service level can be used with an optional parameter to set a maximum slave lag for choosing slaves. If set, the plugin checks SHOW SLAVE STATUS for all configured slaves. In case of the example, only slaves for which Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master <= 4 is true are considered for executing the statement SELECT item, price FROM daytrade.

Checking SHOW SLAVE STATUS is done transparently from an applications perspective. Errors, if any, are reported as warnings. No error will be set on the connection handle. Even if all SHOW SLAVE STATUS SQL statements executed by the plugin fail, the execution of the users statement is not stopped, given that master fail over is enabled. Thus, no application changes are required.

Informacja: Expensive and slow operation

Checking SHOW SLAVE STATUS for all slaves adds overhead to the application. It is an expensive and slow background operation. Try to minimize the use of it. Unfortunately, a MySQL replication cluster does not give clients the possibility to request a list of candidates from a central instance. Thus, a more efficient way of checking the slaves lag is not available.

Please, note the limitations and properties of SHOW SLAVE STATUS as explained in the MySQL reference manual.

To prevent mysqlnd_ms from emitting a warning if no slaves can be found that lag no more than the defined number of seconds behind the master, it is necessary to enable master fail over in the plugins configuration file. If no slaves can be found and fail over is turned on, the plugin picks a master for executing the statement.

If no slave can be found and fail over is turned off, the plugin emits a warning, it does not execute the statement and it sets an error on the connection.

Przykład #5 Fail over not set

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

Przykład #6 No slave within time limit

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Read from slaves lagging no more than four seconds */
$ret = mysqlnd_ms_set_qos($mysqli,
         MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL,
         MYSQLND_MS_QOS_OPTION_AGE, 4);

if (!$ret)
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Plugin picks any slave, which may or may not have the changes */
if (!$res = $mysqli->query("SELECT item, price FROM daytrade"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Back to default: use of all slaves and masters permitted */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

Powyższy przykład wyświetli:

PHP Warning:  mysqli::query(): (mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. Something is wrong in %s on line %d
PHP Warning:  mysqli::query(): (mysqlnd_ms) No connection selected by the last filter in %s on line %d
[2000] (mysqlnd_ms) No connection selected by the last filter

Informacja: Fail over logic is work in progress

The details of the fail over logic may change in future versions.

Transactions
Global transaction IDs
Quickstart and Examples


Global transaction IDs

Informacja: Version requirement

Global transaction ID injection has been introduced in mysqlnd_ms version 1.2.0-alpha. The feature is not required for synchronous clusters, such as MySQL Cluster. Use it with asynchronous clusters such as classical MySQL replication.

In its most basic form a global transaction ID (GTID) is a counter in a table on the master. The counter is incremented whenever a transaction is comitted on the master. Slaves replicate the table. The counter serves two puposes. In case of a master failure, it helps the database administrator to identify the most recent slave for promoting it to the new master. The most recent slave is the one with the highest counter value. Applications can use the global transaction ID to search for slaves which have replicated a certain write (identified by a global transaction ID) already.

PECL/mysqlnd_ms can inject SQL for every comitted transaction to increment a GTID counter. The so created GTID is accessible by the application to identify an applications write operation. This enables the plugin to deliver session consistency (read your writes) service level by not only quering masters but also slaves which have replicated the change already. Read load is taken away from the master.

Client-side global transaction ID emulation has some limitations. Please, read the concepts section carefully to fully understand the principles and ideas behind it, before using in production environments. The background knowledge is not required to continue with the quickstart.

First, create a counter table on your master server and insert a record into it. The plugin does not assist creating the table. Database administrators must make sure it exists. Depending on the error reporting mode, the plugin will silently ignore the lack of the table or bail out.

Przykład #1 Create counter table on master

CREATE TABLE `trx` (
  `trx_id` int(11) DEFAULT NULL,
  `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO `trx`(`trx_id`) VALUES (1);

In the plugins configuration file set the SQL to update the global transaction ID table using on_commit from the global_transaction_id_injection section. Make sure the table name used for the UPDATE statement is fully qualified. In the example, test.trx is used to refer to table trx in the schema (database) test. Use the table that was created in the previous step. It is important to set the fully qualified table name because the connection on which the injection is done may use a different default database. Make sure the user that opens the connection is allowed to execute the UPDATE.

Enable reporting of errors that may occur when mysqlnd_ms does global transaction ID injection.

Przykład #2 Plugin config: SQL for client-side GTID injection

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "report_error":true
        }
    }
}

Przykład #3 Transparent global transaction ID injection

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("INSERT INTO test(id) VALUES (1)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* auto commit mode, read on slave, no increment */
if (!($res = $mysqli->query("SELECT id FROM test")))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

var_dump($res->fetch_assoc());
?>

Powyższy przykład wyświetli:

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

The example runs three statements in auto commit mode on the master, causing three transactions on the master. For every such statement, the plugin will inject the configured UPDATE transparently before executing the users SQL statement. When the script ends the global transaction ID counter on the master has been incremented by three.

The fourth SQL statement executed in the example, a SELECT, does not trigger an increment. Only transactions (writes) executed on a master shall increment the GTID counter.

Informacja: SQL for global transaction ID: efficient solution wanted!

The SQL used for the client-side global transaction ID emulation is inefficient. It is optimized for clearity not for performance. Do not use it for production environments. Please, help finding an efficient solution for inclusion in the manual. We appreciate your input.

Przykład #4 Plugin config: SQL for fetching GTID

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "fetch_last_gtid" : "SELECT MAX(trx_id) FROM test.trx",
            "report_error":true
        }
    }
}

Przykład #5 Obtaining GTID after injection

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));
?>

Powyższy przykład wyświetli:

GTID after transaction 7
GTID after transaction 8

Applications can ask PECL mysqlnd_ms for a global transaction ID which belongs to the last write operation performed by the application. The function mysqlnd_ms_get_last_gtid() returns the GTID obtained when executing the SQL statement from the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file. The function may be called after the GTID has been incremented.

Applications are adviced not to run the SQL statement themselves as this bares the risk of accidently causing an implicit GTID increment. Also, if the function is used, it is easy to migrate an application from one SQL statement for fetching a transaction ID to another, for example, if any MySQL server ever features built-in global transaction ID support.

The quickstart shows a SQL statement which will return a GTID equal or greater to that created for the previous statement. It is exactly the GTID created for the previous statement if no other clients have incremented the GTID in the time span between the statement execution and the SELECT to fetch the GTID. Otherwise, it is greater.

Przykład #6 Plugin config: Checking for a certain GTID

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "fetch_last_gtid" : "SELECT MAX(trx_id) FROM test.trx",
            "check_for_gtid" : "SELECT trx_id FROM test.trx WHERE trx_id >= #GTID",
            "report_error":true
        }
    }
}

Przykład #7 Session consistency service level and GTID combined

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* GTID as an identifier for the last write */
$gtid = mysqlnd_ms_get_last_gtid($mysqli);

/* Session consistency (read your writes): try to read from slaves not only master */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION, MYSQLND_MS_QOS_OPTION_GTID, $gtid)) {
    die(sprintf("[006] [%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Either run on master or a slave which has replicated the INSERT */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

var_dump($res->fetch_assoc());
?>

A GTID returned from mysqlnd_ms_get_last_gtid() can be used as an option for the session consistency service level. Session consistency delivers read your writes. Session consistency can be requested by calling mysqlnd_ms_set_qos(). In the example, the plugin will execute the SELECT statement either on the master or on a slave which has replicated the previous INSERT already.

PECL mysqlnd_ms will transparently check every configured slave if it has replicated the INSERT by checking the slaves GTID table. The check is done running the SQL set with the check_for_gtid option from the global_transaction_id_injection section of the plugins configuration file. Please note, that this is a slow and expensive procedure. Applications should try to use it sparsely and only if read load on the master becomes to high otherwise.

Service level and consistency
Concepts
Quickstart and Examples


Concepts

Spis treści

  • Architecture
  • Connection pooling and switching
  • Transaction handling
  • Error handling
  • Failover
  • Load balancing
  • Read-write splitting
  • Filter
  • Service level and consistency
  • Global transaction IDs
  • Supported clusters

This explains the architecture and related concepts for this plugin, and describes the impact that MySQL replication and this plugin have on developmental tasks while using a database cluster. Reading and understanding these concepts is required, in order to use this plugin with success.

Global transaction IDs
Architecture
mysqlnd_ms


Architecture

The mysqlnd replication and load balancing plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter, in the module init phase of the PHP engine, it gets registered as a mysqlnd plugin to replace selected mysqlnd C methods.

At PHP runtime, it inspects queries sent from mysqlnd (PHP) to the MySQL server. If a query is recognized as read-only, it will be sent to one of the configured slave servers. Statements are considered read-only if they either start with SELECT, the SQL hint /*ms=slave*/ or a slave had been chosen for running the previous query, and the query started with the SQL hint /*ms=last_used*/. In all other cases, the query will be sent to the MySQL replication master server.

For better portability, applications should use the MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH, and MYSQLND_MS_LAST_USED_SWITCH predefined mysqlnd_ms constants, instead of their literal values, such as /*ms=slave*/.

The plugin handles the opening and closing of database connections to both master and slave servers. From an application point of view, there continues to be only one connection handle. However, internally, this one public connection handle represents a pool of network connections that are managed by the plugin. The plugin proxies queries to the master server, and to the slaves using multiple connections.

Database connections have a state consisting of, for example, transaction status, transaction settings, character set settings, and temporary tables. The plugin will try to maintain the same state among all internal connections, whenever this can be done in an automatic and transparent way. In cases where it is not easily possible to maintain state among all connections, such as when using BEGIN TRANSACTION, the plugin leaves it to the user to handle.

Concepts
Connection pooling and switching
Concepts


Connection pooling and switching

The replication and load balancing plugin changes the semantics of a PHP MySQL connection handle. The existing API of the PHP MySQL extensions (mysqli, mysql, and PDO_MYSQL) are not changed in a way that functions are added or removed. But their behaviour changes when using the plugin. Existing applications do not need to be adapted to a new API, but they may need to be modified because of the behaviour changes.

The plugin breaks the one-by-one relationship between a mysqli, mysql, and PDO_MYSQL connection handle and a MySQL network connection. And a mysqli, mysql, and PDO_MYSQL connection handle represents a local pool of connections to the configured MySQL replication master and MySQL replication slave servers. The plugin redirects queries to the master and slave servers. At some point in time one and the same PHP connection handle may point to the MySQL master server. Later on, it may point to one of the slave servers or still the master. Manipulating and replacing the network connection referenced by a PHP MySQL connection handle is not a transparent operation.

Every MySQL connection has a state. The state of the connections in the connection pool of the plugin can differ. Whenever the plugin switches from one wire connection to another, the current state of the user connection may change. The applications must be aware of this.

The following list shows what the connection state consists of. The list may not be complete.

  • Transaction status
  • Temporary tables
  • Table locks
  • Session system variables and session user variables
  • The current database set using USE and other state chaining SQL commands
  • Prepared statements
  • HANDLER variables
  • Locks acquired with GET_LOCK()

Connection switches happen right before queries are executed. The plugin does not switch the current connection until the next statement is executed.

Informacja: Replication issues

See also the MySQL reference manual chapter about » replication features and related issues. Some restrictions may not be related to the PHP plugin, but are properties of the MySQL replication system.

Broadcasted messages

The plugins philosophy is to align the state of connections in the pool only if the state is under full control of the plugin, or if it is necessary for security reasons. Just a few actions that change the state of the connection fall into this category.

The following is a list of connection client library calls that change state, and are broadcasted to all open connections in the connection pool.

If any of the listed calls below are to be executed, the plugin loops over all open master and slave connections. The loop continues until all servers have been contacted, and the loop does not break if a server indicates a failure. If possible, the failure will propagate to the called user API function, which may be detected depending on which underlying library function was triggered.

Library call | Notes | Version
change_user() | Called by the mysqli_change_user() user API call. Also triggered upon reuse of a persistent mysqli connection. | Since 1.0.0.
select_db | Called by the following user API calls: mysql_select_db(), mysql_list_tables(), mysql_db_query(), mysql_list_fields(), mysqli_select_db(). Note, that SQL USE is not monitored. | Since 1.0.0.
set_charset() | Called by the following user API calls: mysql_set_charset(). mysqli_set_charset(). Note, that SQL SET NAMES is not monitored. | Since 1.0.0.
set_server_option() | Called by the following user API calls: mysqli_multi_query(), mysqli_real_query(), mysqli_query(), mysql_query(). | Since 1.0.0.
set_client_option() | Called by the following user API calls: mysqli_options(), mysqli_ssl_set(), mysqli_connect(), mysql_connect(), mysql_pconnect(). | Since 1.0.0.
set_autocommit() | Called by the following user API calls: mysqli_autocommit(), PDO::setAttribute(PDO::ATTR_AUTOCOMMIT). | Since 1.0.0. PHP >= 5.4.0.
ssl_set() | Called by the following user API calls: mysqli_ssl_set(). | Since 1.1.0.

Broadcasting and lazy connections

The plugin does not proxy or "remember" all settings to apply them on connections opened in the future. This is important to remember, if using lazy connections. Lazy connections are connections which are not opened before the client sends the first connection. Use of lazy connections is the default plugin action.

The following connection library calls each changed state, and their execution is recorded for later use when lazy connections are opened. This helps ensure that the connection state of all connections in the connection pool are comparable.

Library call | Notes | Version
change_user() | User, password and database recorded for future use. | Since 1.1.0.
select_db | Database recorded for future use. | Since 1.1.0.
set_charset() | Calls set_client_option(MYSQL_SET_CHARSET_NAME, charset) on lazy connection to ensure charset will be used upon opening the lazy connection. | Since 1.1.0.
set_autocommit() | Adds SET AUTOCOMMIT=0|1 to the list of init commands of a lazy connection using set_client_option(MYSQL_INIT_COMMAND, "SET AUTOCOMMIT=...%quot;). | Since 1.1.0. PHP >= 5.4.0.
Uwaga

Connection state

The connection state is not only changed by API calls. Thus, even if PECL mysqlnd_ms monitors all API calls, the application must still be aware. Ultimately, it is the applications responsibility to maintain the connection state, if needed.

Architecture
Transaction handling
Concepts


Transaction handling

Transaction handling is fundamentally changed. An SQL transaction is a unit of work that is run on one database server. The unit of work consists of one or more SQL statements.

By default the plugin is not aware of SQL transactions. The plugin may switch connections for load balancing at any point in time. Connection switches may happen in the middle of a transaction. This is against the nature of an SQL transaction. By default, the plugin is not transaction safe.

At the time of writing, applications using SQL transactions together with the plugin must use SQL hints to disable connection switches in the middle of a SQL transaction. See also the examples section.

Informacja: Added features as of PHP 5.4.0

The mysqlnd library allows this plugin to subclass the library C API call set_autocommit(), to detect the status of autocommit mode.

Added support for trx_stickiness=master

The PHP MySQL extensions either issue a query (such as SET AUTOCOMMIT=0|1), or use the mysqlnd library call set_autcommit() to control the autocommit setting. If an extension makes use of set_autocommit(), the plugin can be made transaction aware. Transaction awareness cannot be achieved if using SQL to set the autocommit mode. The library function set_autocommit() is called by the mysqli_autocommit() and PDO::setAttribute(PDO::ATTR_AUTOCOMMIT) user API calls.

The plugin configuration option trx_stickiness=master can be used to make the plugin transactional aware. In this mode, the plugin stops load balancing if autocommit becomes disabled, and directs all statements to the master until autocommit gets enabled.

Connection pooling and switching
Error handling
Concepts


Error handling

Applications using PECL/mysqlnd_ms should implement proper error handling for all user API calls. And because the plugin changes the semantics of a connection handle, API calls may return unexpected errors. If using the plugin on a connection handle that no longer represents an individual network connection, but a connection pool, an error code and error message will be set on the connection handle whenever an error occurs on any of the network connections behind.

If using lazy connections, which is the default, connections are not opened until they are needed for query execution. Therefore, an API call for a statement execution may return a connection error. In the example below, an error is provoked when trying to run a statement on a slave. Opening a slave connection fails because the plugin configuration file lists an invalid host name for the slave.

Przykład #1 Provoking a connection error

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "invalid_host_name",
            }
        },
        "lazy_connections": 1
    }
}

The explicit activation of lazy connections is for demonstration purpose only.

Przykład #2 Connection error on query execution

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, run on slave because SELECT, provoke connection error */
if (!($res = $mysqli->query("SELECT @myrole AS _role"))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

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

PHP Warning:  mysqli::query(): php_network_getaddresses: getaddrinfo failed: Name or service not known in %s on line %d
PHP Warning:  mysqli::query(): [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (trying to connect via tcp://invalid_host_name:3306) in %s on line %d
[2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

Applications are expected to handle possible connection errors by implementing proper error handling.

Depending on the use case, applications may want to handle connection errors differently from other errors. Typical connection errors are 2002 (CR_CONNECTION_ERROR) - Can't connect to local MySQL server through socket '%s' (%d), 2003 (CR_CONN_HOST_ERROR) - Can't connect to MySQL server on '%s' (%d) and 2005 (CR_UNKNOWN_HOST) - Unknown MySQL server host '%s' (%d). For example, the application may test for the error codes and manually perform a fail over. The plugins philosophy is not to offer automatic fail over, beyond master fail over, because fail over is not a transparent operation.

Przykład #3 Provoking a connection error

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "invalid_host_name"
            },
            "slave_1": {
                "host": "192.168.78.136"
            }
        },
        "lazy_connections": 1,
        "filters": {
            "roundrobin": [

            ]
        }
    }
}

Explicitly activating lazy connections is done for demonstration purposes, as is round robin load balancing as opposed to the default random once type.

Przykład #4 Most basic failover

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, first slave */
$res = $mysqli->query("SELECT VERSION() AS _version");
/* Hackish manual fail over */
if (2002 == $mysqli->errno || 2003 == $mysqli->errno || 2004 == $mysqli->errno) {
  /* Connection 3, first slave connection failed, trying next slave */
  $res = $mysqli->query("SELECT VERSION() AS _version");
}

if (!$res) {
  printf("ERROR, [%d] '%s'\n", $mysqli->errno, $mysqli->error);
} else {
 /* Error messages are taken from connection 3, thus no error */
 printf("SUCCESS, [%d] '%s'\n", $mysqli->errno, $mysqli->error);
 $row = $res->fetch_assoc();
 $res->close();
 printf("version = %s\n", $row['_version']);
}
$mysqli->close();
?>

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

[1045] Access denied for user 'username'@'localhost' (using password: YES)
PHP Warning:  mysqli::query(): php_network_getaddresses: getaddrinfo failed: Name or service not known in %s on line %d
PHP Warning:  mysqli::query(): [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (trying to connect via tcp://invalid_host_name:3306) in %s on line %d
SUCCESS, [0] ''
version = 5.6.2-m5-log

In some cases, it may not be easily possible to retrieve all errors that occur on all network connections through a connection handle. For example, let's assume a connection handle represents a pool of three open connections. One connection to a master and two connections to the slaves. The application changes the current database using the user API call mysqli_select_db(), which then calls the mysqlnd library function to change the schemata. mysqlnd_ms monitors the function, and tries to change the current database on all connections to harmonize their state. Now, assume the master succeeds in changing the database, and both slaves fail. Upon the initial error from the first slave, the plugin will set an appropriate error on the connection handle. The same is done when the second slave fails to change the database. The error message from the first slave is lost.

Such cases can be debugged by either checking for errors of the type E_WARNING (see above) or, if no other option, investigation of the mysqlnd_ms debug and trace log.

Transaction handling
Failover
Concepts


Failover

Connection failover handling is left to the user. The application is responsible for checking return values of the database functions it calls and reacting to possible errors. If, for example, the plugin recognizes a query as a read-only query to be sent to the slave servers, and the slave server selected by the plugin is not available, the plugin will raise an error after not executing the statement.

It is up to the application to handle the error and, if required, re-issue the query to trigger the selection of another slave server for statement execution. The plugin will make no attempts to failover automatically, because the plugin cannot ensure that an automatic failover will not change the state of the connection. For example, the application may have issued a query which depends on SQL user variables which are bound to a specific connection. Such a query might return incorrect results if the plugin would switch the connection implicitly as part of automatic failover. To ensure correct results, the application must take care of the failover, and rebuild the required connection state. Therefore, by default, no automatic failover is performed by the plugin.

A user that does not change the connection state after opening a connection may activate automatic master failover.

The failover policy is configured in the plugins configuration file, by using the failover configuration directive.

A basic manual failover example is provided within the error handling section.

Error handling
Load balancing
Concepts


Load balancing

Four load balancing strategies are supported to distribute read-only statements over the configured MySQL slave servers:

random

Chooses a random server whenever a statement is executed.

random once (default)

Chooses a random server after the first statement is executed, and uses the decision for the rest of the PHP request.

It is the default, and the lowest impact on the connection state.

round robin

Iterates over the list of configured servers.

user-defined via callback

Is used to implement any other strategy.

The load balancing policy is configured in the plugins configuration file using the random, roundrobin, and user filters.

Failover
Read-write splitting
Concepts


Read-write splitting

The plugin executes read-only statements on the configured MySQL slaves, and all other queries on the MySQL master. Statements are considered read-only if they either start with SELECT, the SQL hint /*ms=slave*/, or if a slave had been chosen for running the previous query and the query starts with the SQL hint /*ms=last_used*/. In all other cases, the query will be sent to the MySQL replication master server. It is recommended to use the constants MYSQLND_MS_SLAVE_SWITCH, MYSQLND_MS_MASTER_SWITCH and MYSQLND_MS_LAST_USED_SWITCH instead of /*ms=slave*/. See also the list of mysqlnd_ms constants.

SQL hints are a special kind of standard compliant SQL comments. The plugin does check every statement for certain SQL hints. The SQL hints are described within the mysqlnd_ms constants documentation, constants that are exported by the extension. Other systems involved with the statement processing, such as the MySQL server, SQL firewalls, and SQL proxies, are unaffected by the SQL hints, because those systems are designed to ignore SQL comments.

The built-in read-write splitter can be replaced by a user-defined filter, see also the user filter documentation.

A user-defined read-write splitter can request the built-in logic to send a statement to a specific location, by invoking mysqlnd_ms_is_select().

Informacja:

The built-in read-write splitter is not aware of multi-statements. Multi-statements are seen as one statement. The splitter will check the beginning of the statement to decide where to run the statement. If, for example, a multi-statement begins with SELECT 1 FROM DUAL; INSERT INTO test(id) VALUES (1); ... the plugin will run it on a slave although the statement is not read-only.

Load balancing
Filter
Concepts


Filter

Informacja: Version requirement

Filters exist as of mysqlnd_ms version 1.1.0-beta.

filters. PHP applications that implement a MySQL replication cluster must first identify a group of servers in the cluster which could execute a statement before the statement is executed by one of the candidates. In other words: a defined list of servers must be filtered until only one server is available.

The process of filtering may include using one or more filters, and filters can be chained. And they are executed in the order they are defined in the plugins configuration file.

Informacja: Explanation: comparing filter chaining to pipes

The concept of chained filters can be compared to using pipes to connect command line utilities on an operating system command shell. For example, an input stream is passed to a processor, filtered, and then transferred to be output. Then, the output is passed as input to the next command, which is connected to the previous using the pipe operator.

Available filters:

  • Load balancing filters: random and roundrobin.
  • Selection filter: user, user_multi, quality_of_service.

The random filter implements the 'random' and 'random once' load balancing policies. The 'round robin' load balancing can be configured through the roundrobin filter. Setting a 'user defined callback' for server selection is possible with the user filter. The quality_of_service filter finds cluster nodes capable of delivering a certain service, for example, read-your-writes or, not lagging more seconds behind the master than allowed.

Filters can accept parameters to change their behaviour. The random filter accepts an optional sticky parameter. If set to true, the filter changes load balancing from random to random once. Random picks a random server every time a statement is to be executed. Random once picks a random server when the first statement is to be executed and uses the same server for the rest of the PHP request.

One of the biggest strength of the filter concept is the possibility to chain filters. This strength does not become immediately visible because tje random, roundrobin and user filters are supposed to output no more than one server. If a filter reduces the list of candidates for running a statement to only one server, it makes little sense to use that one server as input for another filter for further reduction of the list of candidates.

An example filter sequence that will fail:

  • Statement to be executed: SELECT 1 FROM DUAL. Passed to all filters.
  • All configured nodes are passed as input to the first filter. Master nodes: master_0. Slave nodes:slave_0, slave_1
  • Filter: random, argument sticky=1. Picks a random slave once to be used for the rest of the PHP request. Output: slave_0.
  • Output of slave_0 and the statement to be executed is passed as input to the next filter. Here: roundrobin, server list passed to filter is: slave_0.
  • Filter: roundrobin. Server list consists of one server only, round robin will always return the same server.
If trying to use such a filter sequence, the plugin may emit a warning like (mysqlnd_ms) Error while creating filter '%s' . Non-multi filter '%s' already created. Stopping in %s on line %d. Furthermore, an appropriate error on the connection handle may be set.

A second type of filter exists: multi filter. A multi filter emits zero, one or multiple servers after processing. The quality_of_service filter is an example. If the service quality requested sets an upper limit for the slave lag and more than one slave is lagging behind less than the allowed number of seconds, the filter returns more than one cluster node. A multi filter must be followed by other to further reduce the list of candidates for statement execution until a candidate is found.

A filter sequence with the quality_of_service multi filter followed by a load balancing filter.

  • Statement to be executed: SELECT sum(price) FROM orders WHERE order_id = 1. Passed to all filters.
  • All configured nodes are passed as input to the first filter. Master nodes: master_0. Slave nodes: slave_0, slave_1, slave_2, slave_3
  • Filter: quality_of_service, rule set: session_consistency (read-your-writes) Output: master_0
  • Output of master_0 and the statement to be executed is passed as input to the next filter, which is roundrobin.
  • Filter: roundrobin. Server list consists of one server. Round robin selects master_0.

A filter sequence must not end with a multi filter. If trying to use a filter sequence which ends with a multi filter the plugin may emit a warning like (mysqlnd_ms) Error in configuration. Last filter is multi filter. Needs to be non-multi one. Stopping in %s on line %d. Furthermore, an appropriate error on the connection handle may be set.

Informacja: Speculation towards the future: MySQL replication filtering

In future versions, there may be additional multi filters. For example, there may be a table filter to support MySQL replication filtering. This would allow you to define rules for which database or table is to be replicated to which node of a replication cluster. Assume your replication cluster consists of four slaves (slave_0, slave_1, slave_2, slave_3) two of which replicate a database named sales (slave_0, slave_1). If the application queries the database slaves, the hypothetical table filter reduces the list of possible servers to slave_0 and slave_1. Because the output and list of candidates consists of more than one server, it is necessary and possible to add additional filters to the candidate list, for example, using a load balancing filter to identify a server for statement execution.

Read-write splitting
Service level and consistency
Concepts


Service level and consistency

Informacja: Version requirement

Service levels have been introduced in mysqlnd_ms version 1.2.0-alpha. mysqlnd_ms_set_qos() requires PHP 5.4.0 or newer.

The plugin can be used with different kinds of MySQL database clusters. Different clusters can deliver different levels of service to applications. The service levels can be grouped by the data consistency levels that can be achieved. The plugin knows about:

  • eventual consistency
  • session consistency
  • strong consistency

Depending how a cluster is used it may be possible to achieve higher service levels than the default one. For example, a read from an asynchronous MySQL replication slave is eventual consistent. Thus, one may say the default consistency level of a MySQL replication cluster is eventual consistency. However, if the master only is used by a client for reading and writing during a session, session consistency (read your writes) is given. PECL mysqlnd 1.2.0 abstracts the details of choosing an appropriate node for any of the above service levels from the user.

Service levels can be set through the qualify-of-service filter in the plugins configuration file and at runtime using the function mysqlnd_ms_set_qos().

The plugin defines the different service levels as follows.

Eventual consistency is the default service provided by an asynchronous cluster, such as classical MySQL replication. A read operation executed on an arbitrary node may or may not return stale data. The applications view of the data is eventual consistent.

Session consistency is given if a client can always read its own writes. An asynchronous MySQL replication cluster can deliver session consistency if clients always use the master after the first write or never query a slave which has not yet replicated the clients write operation.

The plugins understanding of strong consistency is that all clients always see the comitted writes of all other clients. This is the default when using MySQL Cluster or any other cluster offering synchronous data distribution.

Service level parameters

Eventual consistency and session consistency service level accept parameters.

Eventual consistency is the service provided by classical MySQL replication. By default, all nodes qualify for read requests. An optional age parameter can be given to filter out nodes which lag more than a certain number of seconds behind the master. The plugin is using SHOW SLAVE STATUS to measure the lag. Please, see the MySQL reference manual to learn about accuracy and reliability of the SHOW SLAVE STATUS command.

Session consistency (read your writes) accepts an optional GTID parameter to consider reading not only from the master but also from slaves which already have replicated a certain write described by its transaction identifier. This way, when using asynchronous MySQL replication, read requests may be load balanced over slaves while still ensuring session consistency.

The latter requires the use of client-side global transaction id injection.

Advantages of the new approach

The new approach supersedes the use of SQL hints and the configuration option master_on_write in some respects. If an application running on top of an asynchonous MySQL replication cluster cannot accept stale data for certain reads, it is easier to tell the plugin to choose appropriate nodes than prefixing all read statements in question with the SQL hint to enforce the use of the master. Furthermore, the plugin may be able to use selected slaves for reading.

The master_on_write configuration option makes the plugin use the master after the first write (session consistency, read your writes). In some cases, session consistency may not be needed for the rest of the session but only for some, few read operations. Thus, master_on_write may result in more read load on the master than necessary. In those cases it is better to request a higher than default service level only for those reads that actually need it. Once the reads are done, the application can return to default service level. Switching between service levels is only possible using mysqlnd_ms_set_qos().

Performance considerations

A MySQL replication cluster cannot tell clients which slaves are capable of delivering which level of service. Thus, in some cases, clients need to query the slaves to check their status. PECL mysqlnd_ms transparently runs the necessary SQL in the background. However, this is an expensive and slow operation. SQL statements are run if eventual consistency is combined with an age (slave lag) limit and if session consistency is combined with a global transaction ID.

If eventual consistency is combined with an maximum age (slave lag), the plugin selects candidates for statement execution and load balancing for each statement as follows. If the statement is a write all masters are considered as candidates. Slaves are not checked and not considered as candidates. If the statement is a read, the plugin transparently executes SHOW SLAVE STATUS on every slaves connection. It will loop over all connections, send the statement and then start checking for results. Usually, this is slighly faster than a loop over all connections in which for every connection a query is send and the plugin waits for its results. A slave is considered a candidate if SHOW SLAVE STATUS reports Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master is less or equal than the allowed maximum age. In case of an SQL error, the plugin emits a warning but does not set an error on the connection. The error is not set to make it possible to use the plugin as a drop-in.

If session consistency is combined with a global transaction ID, the plugin executes the SQL statement set with the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file. Further details are identical to those described above.

In version 1.2.0 no additional optimizations are done for executing background queries. Future versions may contain optimizations, depending on user demand.

If no parameters and options are set, no SQL is needed. In that case, the plugin consider all nodes of the type shown below.

  • eventual consistency, no further options set: all masters, all slaves
  • session consistency, no further options set: all masters
  • strong consistency (no options allowed): all masters

Filter
Global transaction IDs
Concepts


Global transaction IDs

Informacja: Version requirement

Client side global transaction ID injection exists as of mysqlnd_ms version 1.2.0-alpha. Transaction boundaries are detected by monitoring API calls. This is possible as of PHP 5.4.0. Please, see also Transaction handling.

PECL/mysqlnd_ms can do client-side transparent global transaction ID injection. In its most basic form, a global transaction identifier is a counter which is incremented for every transaction executed on the master. The counter is held in a table on the master. Slaves replicate the counter table.

In case of a master failure a database administrator can easily identify the most recent slave for promiting it as a new master. The most recent slave has the highest transaction identifier.

Application developers can ask the plugin for the global transaction identifier (GTID) for their last successful write operation. The plugin will return an identifier that refers to an transaction no older than that of the clients last write operation. Then, the GTID can be passed as a parameter to the quality of service (QoS) filter as an option for session consistency. Session consistency ensures read your writes. The filter ensures that all reads are either directed to a master or a slave which has replicated the write referenced by the GTID.

When injection is done

The plugin transparently maintains the GTID table on the master. In autocommit mode the plugin injects an UPDATE statement before executing the users statement for every master use. In manual transaction mode, the injection is done before the application calls commit() to close a transaction. The configuration option report_error of the GTID section in the plugins configuration file is used to control whether a failed injection shall abort the current operation or be ignored silently (default).

Please note, the PHP version requirements for transaction boundary monitoring and their limits.

Limitations

Client-side global transaction ID injection has shortcomings. The potential issues are not specific to PECL/mysqlnd_ms but are rather of general nature.

  • The GTID can have holes. Only PHP clients using the plugin will maintain the table. Other clients will not.
  • Client-side transaction boundary detection is based on API calls only.
  • Client-side transaction boundary detection does not take implicit commit into account. Some MySQL SQL statements cause an implicit commit and cannot be rolled back.

Informacja: Server-side global transaction ID support

The plugin is prepared to support MySQL servers which implement global transaction ID support and which maintain a global transaction ID themselves. Client-side injection would not be necessary with such servers. However, without any server supporting it yet and, in heterogenous environments with old MySQL servers, client-side injection is a valuable, although not perfect, option.

Service level and consistency
Supported clusters
Concepts


Supported clusters

Any application using any kind of MySQL cluster is faced with the same tasks:

  • Identify nodes capable of executing a given statement with the required service level
  • Load balance requests within the list of candidates
  • Automatic fail over within candidates, if needed

The plugin is optimized for fulfilling these tasks in the context of a classical asynchronous MySQL replication cluster consisting of a single master and many slaves. When using classical, asynchronous MySQL replication all of the above listed tasks need to be mastered at the client level.

Other types of MySQL cluster may have lower requirements on the application side. For example, if all nodes in the cluster can answer read and write requests, no read-write splitting needs to be done. If all nodes in the cluster are synchronous, they automatically provide the higest possible quality of service which makes choosing a node easier. In those cases, the plugin may serve the application after some reconfiguration to disable certain features, such as built-in read-write splitting.

Informacja: Documentation focus

The documentation focusses describing the use of the plugin with classical asynchronous MySQL replication clusters. Support for this kind of cluster has been the original development goal. Use of other clusters is briefly described below. Please note, that this is still work in progress.

Using asynchronous clusters with single master

Primary use case of the plugin. Follow the hints given in the descriptions of each feature.

Informacja: Version requirement

The following cluster may require use of settings not available before mysqlnd_ms 1.2.0-alpha.

Using asynchronous clusters with multiple masters

This setup is currently unsupported.

The plugin has no built-in functionality to direct certain writes to certain masters. It is considered to add table filtering to future versions. Table filter would allow restricting both read and writes to certain slaves and masters based on the database/schema and table used by a statement.

A table filtering feature is prepared in the plugins source code. However, it is instable and must not be used. Bug reports on table filtering will be rejected.

Using synchronous clusters such as MySQL Cluster

MySQL Cluster is a synchronous cluster solution. All cluster nodes accept read and write requests. In the context of the plugin, all nodes shall be considered as masters.

Use the load balancing and fail over features only.

  • Disable the plugins built-in read-write splitting.
  • Configure masters only.
  • Consider random once load balancing strategy, which is the plugins default. If random once is used, only masters are configured and no SQL hints are used to force using a certain node, no connection switches will happen for the duration of a web request. Thus, no special handling is required for transactions. The plugin will pick one master at the beginning of the PHP script and use it until the script terminates.
  • Do not set the quality of service. All nodes have all the data. This automatically gives you the highest possible service quality (strong consistency).
  • Do not enable client-side global transaction injection. It is neither required to help with server-side fail over nor to assist the quality of service filter choosing an appropiate node.

Disabling built-in read-write splitting.

  • Set mysqlnd_ms.disable_rw_split=1
  • Do not use SQL hints to enforce the use of slaves

Configure masters only.

  • Set mysqlnd_ms.multi_master=1
  • Do not configure any slaves
  • Set failover=master in the plugins configuration file to avoid warnings about the empty slave list

Global transaction IDs
Instalacja/Konfiguracja
Concepts


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Plugin configuration file (>=1.1.x)
  • Plugin configuration file (<= 1.0.x)
  • Testing
  • Debugging and Tracing
  • Monitoring
Supported clusters
Wymagania
mysqlnd_ms


Wymagania

PHP 5.3.6 or newer. Some advanced functionality requires PHP 5.4.0 or newer.

The mysqlnd_ms replication and load balancing plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in order to be able to use the mysqlnd_ms plugin for mysqlnd.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/mysqlnd_ms

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Mysqlnd_ms Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mysqlnd_ms.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.force_config_usage | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.ini_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.collect_statistics | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.multi_master | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.disable_rw_split | 0 | PHP_INI_SYSTEM |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

mysqlnd_ms.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

mysqlnd_ms.force_config_usage integer

If enabled, the plugin checks if the host (server) parameters value of any MySQL connection attempt, matches a section name from the plugin configuration file. If not, the connection attempt is blocked.

mysqlnd_ms.ini_file string

Plugin specific configuration file.

mysqlnd_ms.collect_statistics integer

Enables or disables the collection of statistics. The collection of statistics is disabled by default for performance reasons. Statistics are returned by the function mysqlnd_ms_get_stats().

mysqlnd_ms.multi_master integer

Enables or disables support of MySQL multi master replication setups. Please, see also supported clusters.

mysqlnd_ms.disable_rw_split integer

Enables or disables built-in read write splitting.

Controls whether load balancing and lazy connection functionality can be used independently of read write splitting. If read write splitting is disabled, only servers from the master list will be used for statement execution. All configured slave servers will be ignored.

The SQL hint MYSQLND_MS_USE_SLAVE will not be recognized. If found, the statement will be redirected to a master.

Disabling read write splitting impacts the return value of mysqlnd_ms_query_is_select(). The function will no longer propose query execution on slave servers.

Informacja: Multiple master servers

Setting mysqlnd_ms.multi_master=1 allows the plugin to use multiple master servers, instead of only the first master server of the master list.

Please, see also supported clusters.

Instalacja
Plugin configuration file (>=1.1.x)
Instalacja/Konfiguracja


Plugin configuration file (>=1.1.x)

Informacja: Changelog: Feature was added in PECL/mysqlnd_ms 1.1.0-beta

The below description applies to PECL/mysqlnd_ms >= 1.1.0-beta. It is not valid for prior versions.

The plugin uses its own configuration file. The configuration file holds information about the MySQL replication master server, the MySQL replication slave servers, the server pick (load balancing) policy, the failover strategy, and the use of lazy connections.

The plugin loads its configuration file at the beginning of a web request. It is then cached in memory and used for the duration of the web request. This way, there is no need to restart PHP after deploying the configuration file. Configuration file changes will become active almost instantly.

The PHP configuration directive mysqlnd_ms.ini_file is used to set the plugins configuration file. Please note, that the PHP configuration directive may not be evaluated for every web request. Therefore, changing the plugins configuration file name or location may require a PHP restart. However, no restart is required to read changes if an already existing plugin configuration file is updated.

Using and parsing JSON is efficient, and using JSON makes it easier to express hierarchical data structures than the standard php.ini format.

Przykład #1 Converting a PHP array (hash) into JSON format

Or alternatively, a developer may be more familiar with the PHP array syntax, and prefer it. This example demonstrates how a developer might convert a PHP array to JSON.

<?php
$config = array(
  "myapp" => array(
    "master" => array(
      "master_0" => array(
        "host"   => "localhost",
        "socket" => "/tmp/mysql.sock",
      ),
    ),
    "slave" => array(),
  ),
);

file_put_contents("mysqlnd_ms.ini", json_encode($config, JSON_PRETTY_PRINT));
printf("mysqlnd_ms.ini file created...\n");
printf("Dumping file contents...\n");
printf("%s\n", str_repeat("-", 80));
echo file_get_contents("mysqlnd_ms.ini");
printf("\n%s\n", str_repeat("-", 80));
?>

Powyższy przykład wyświetli:

mysqlnd_ms.ini file created...
Dumping file contents...
--------------------------------------------------------------------------------
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": [

        ]
    }
}
--------------------------------------------------------------------------------

A plugin configuration file consists of one or more sections. Sections are represented by the top-level object properties of the object encoded in the JSON file. Sections could also be called configuration names.

Applications reference sections by their name. Applications use section names as the host (server) parameter to the various connect methods of the mysqli, mysql and PDO_MYSQL extensions. Upon connect, the mysqlnd plugin compares the hostname with all of the section names from the plugin configuration file. If the hostname and section name match, then the plugin will load the settings for that section.

Przykład #2 Using section names example

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27"
            },
            "slave_1": {
                "host": "192.168.2.27",
                "port": 3306
            }
        }
    },
    "localhost": {
        "master": [
            {
                "host": "localhost",
                "socket": "\/path\/to\/mysql.sock"
            }
        ],
        "slave": [
            {
                "host": "192.168.3.24",
                "port": "3305"
            },
            {
                "host": "192.168.3.65",
                "port": "3309"
            }
        ]
    }
}
<?php
/* All of the following connections will be load balanced */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");

$mysqli = new mysqli("localhost", "username", "password", "database");
?>

Section names are strings. It is valid to use a section name such as 192.168.2.1, 127.0.0.1 or localhost. If, for example, an application connects to localhost and a plugin configuration section localhost exists, the semantics of the connect operation are changed. The application will no longer only use the MySQL server running on the host localhost, but the plugin will start to load balance MySQL queries following the rules from the localhost configuration section. This way you can load balance queries from an application without changing the applications source code. Please keep in mind, that such a configuration may not contribute to overall readability of your applications source code. Using section names that can be mixed up with host names should be seen as a last resort.

Each configuration section contains, at a minimum, a list of master servers and a list of slave servers. The master list is configured with the keyword master, while the slave list is configured with the slave keyword. Failing to provide a slave list will result in a fatal E_ERROR level error, although a slave list may be empty. It is possible to allow no slaves. However, this is only recommended with synchronous clusters, please see also supported clusters. The main part of the documentation focusses on the use of aynchronous MySQL replication clusters.

The master and slave server lists can be optionally indexed by symbolic names for the servers they describe. Alternatively, an array of descriptions for slave and master servers may be used.

Przykład #3 List of anonymous slaves

"slave": [
    {
        "host": "192.168.3.24",
        "port": "3305"
    },
    {
        "host": "192.168.3.65",
        "port": "3309"
    }
]

An anonymous server list is encoded by the JSON array type. Optionally, symbolic names may be used for indexing the slave or master servers of a server list, and done so using the JSON object type.

Przykład #4 Master list using symbolic names

"master": {
    "master_0": {
        "host": "localhost"
    }
}

It is recommended to index the server lists with symbolic server names. The alias names will be shown in error messages.

The order of servers is preserved and taken into account by mysqlnd_ms. If, for example, you configure round robin load balancing strategy, the first SELECT statement will be executed on the slave that appears first in the slave server list.

A configured server can be described with the host, port, socket, db, user, password and connect_flags. It is mandatory to set the database server host using the host keyword. All other settings are optional.

Przykład #5 Keywords to configure a server

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "db_server_host",
                "port": "db_server_port",
                "socket": "db_server_socket",
                "db": "database_resp_schema",
                "user": "user",
                "password": "password",
                "connect_flags": 0
            }
        },
        "slave": {
            "slave_0": {
                "host": "db_server_host",
                "port": "db_server_port",
                "socket": "db_server_socket"
            }
        }
    }
}

If a setting is omitted, the plugin will use the value provided by the user API call used to open a connection. Please, see the using section names example above.

The configuration file format has been changed in version 1.1.0-beta to allow for chained filters. Filters are responsible for filtering the configured list of servers to identify a server for execution of a given statement. Filters are configured with the filter keyword. Filters are executed by mysqlnd_ms in the order of their appearance. Defining filters is optional. A configuration section in the plugins configuration file does not need to have a filters entry.

Filters replace the pick[] setting from prior versions. The new random and roundrobin provide the same functionality.

Przykład #6 New roundrobin filter, old functionality

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.137",
                "port": "3306"
            }
        },
        "filters": {
            "roundrobin": [

            ]
        }
    }
}

The function mysqlnd_ms_set_user_pick_server() has been removed. Setting a callback is now done with the user filter. Some filters accept parameters. The user filter requires and accepts a mandatory callback parameter to set the callback previously set through the function mysqlnd_ms_set_user_pick_server().

Przykład #7 The user filter replaces mysqlnd_ms_set_user_pick_server()

"filters": {
    "user": {
        "callback": "pick_server"
    }
}

Here is a short explanation of the configuration directives that can be used.

master array or object

List of MySQL replication master servers. The list of either of the JSON type array to declare an anonymous list of servers or of the JSON type object. Please, see above for examples.

Setting at least one master server is mandatory. The plugin will issue an error of type E_ERROR if the user has failed to provide a master server list for a configuration section. The fatal error may read (mysqlnd_ms) Section [master] doesn't exist for host [name_of_a_config_section] in %s on line %d.

A server is described with the host, port, socket, db, user, password and connect_flags. It is mandatory to provide at a value for host. If any of the other values is not given, it will be taken from the user API connect call, please, see also: using section names example.

Table of server configuration keywords.

Keyword Description Version
host

Database server host. This is a mandatory setting. Failing to provide, will cause an error of type E_RECOVERABLE_ERROR when the plugin tries to connect to the server. The error message may read (mysqlnd_ms) Cannot find [host] in [%s] section in config in %s on line %d.

Since 1.1.0.
port

Database server TCP/IP port.

Since 1.1.0.
socket

Database server Unix domain socket.

Since 1.1.0.
db

Database (schemata).

Since 1.1.0.
user

MySQL database user.

Since 1.1.0.
password

MySQL database user password.

Since 1.1.0.
connect_flags

Connection flags.

Since 1.1.0.

The plugin supports using only one master server. An experimental setting exists to enable multi-master support. The details are not documented. The setting is meant for development only.

slave array or object

List of one or more MySQL replication slave servers. The syntax is identical to setting master servers, please, see master above for details.

The plugin supports using one or more slave servers.

Setting a list of slave servers is mandatory. The plugin will report an error of the type E_ERROR if slave is not given for a configuration section. The fatal error message may read (mysqlnd_ms) Section [slave] doesn't exist for host [%s] in %s on line %d. Note, that it is valid to use an empty slave server list. The error has been introduced to prevent accidently setting no slaves by forgetting about the slave setting. A master-only setup is still possible using an empty slave server list.

If an empty slave list is configured and an attempt is made to execute a statement on a slave the plugin may emit a warning like mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. upon statement execution. It is possible that another warning follows such as (mysqlnd_ms) No connection selected by the last filter.

filters object

List of filters. A filter is responsible to filter the list of available servers for executing a given statement. Filters can be chained. The random and roundrobin filter replace the pick[] directive used in prior version to select a load balancing policy. The user filter replaces the mysqlnd_ms_set_user_pick_server() function.

Filters may accept parameters to refine their actions.

If no load balancing policy is set, the plugin will default to random_once. The random_once policy picks a random slave server when running the first read-only statement. The slave server will be used for all read-only statements until the PHP script execution ends. No load balancing policy is set and thus, defaulting takes place, if neither the random nor the roundrobin are part of a configuration section.

If a filter chain is configured so that a filter which output no more than once server is used as input for a filter which should be given more than one server as input, the plugin may emit a warning upon opening a connection. The warning may read: (mysqlnd_ms) Error while creating filter '%s' . Non-multi filter '%s' already created. Stopping in %s on line %d. Futhermore an error of the error code 2000, the sql state HY000 and an error message similar to the warning may be set on the connection handle.

Przykład #8 Invalid filter sequence

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": [
            "roundrobin",
            "random"
        ]
    }
}
<?php
$link = new mysqli("myapp", "root", "", "test");
printf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error());
$link->query("SELECT 1 FROM DUAL");
?>

Powyższy przykład wyświetli:

PHP Warning:  mysqli::mysqli(): (HY000/2000): (mysqlnd_ms) Error while creating filter 'random' . Non-multi filter 'roundrobin' already created. Stopping in filter_warning.php on line 1
[2000] (mysqlnd_ms) Error while creating filter 'random' . Non-multi filter 'roundrobin' already created. Stopping
PHP Warning:  mysqli::query(): Couldn't fetch mysqli in filter_warning.php on line 3

Filter: random object

The random filter features the random and random once load balancing policies, set through the pick[] directive in older versions.

The random policy will pick a random server whenever a read-only statement is to be executed. The random once strategy picks a random slave server once and continues using the slave for the rest of the PHP web request. Random once is a default, if load balancing is not configured through a filter.

If the random filter is not given any arguments, it stands for random load balancing policy.

Przykład #9 Random load balancing with random filter

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.137",
                "port": "3306"
            }
        },
        "filters": [
            "random"
        ]
    }
}

Optionally, the sticky argument can be passed to the filter. If the parameter sticky is set to the string 1, the filter follows the random once load balancing strategy.

Przykład #10 Random once load balancing with random filter

{
    "filters": {
        "random": {
            "sticky": "1"
        }
    }
}

Unknown arguments are ignored. No warning or error is given.

Expects one or more servers as input. Outputs one server. A filter sequence such as random, roundrobin may cause a warning and an error message to be set on the connection handle when executing a statement.

Filter: roundrobin object

If using the roundrobin filter, the plugin iterates over the list of configured slave servers to pick a server for statement execution. If the plugin reaches the end of the list, it wraps around to the beginning of the list and picks the first configured slave server.

Przykład #11 roundrobin filter

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": [
            "roundrobin"
        ]
    }
}

Expects one or more servers as input. Outputs one server. A filter sequence such as roundrobin, random may cause a warning and an error message to be set on the connection handle when executing a statement.

Filter: user object

The user replaces mysqlnd_ms_set_user_pick_server() function, which was removed in 1.1.0-beta. The filter sets a callback for user-defined read/write splitting and server selection.

The plugins built-in read/write query split mechanism decisions can be overwritten in two ways. The easiest way is to prepend a query string with the SQL hints MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH or MYSQLND_MS_LAST_USED_SWITCH. Using SQL hints one can control, for example, whether a query shall be send to the MySQL replication master server or one of the slave servers. By help of SQL hints it is not possible to pick a certain slave server for query execution.

Full control on server selection can be gained using a callback function. Use of a callback is recommended to expert users only because the callback has to cover all cases otherwise handled by the plugin.

The plugin will invoke the callback function for selecting a server from the lists of configured master and slave servers. The callback function inspects the query to run and picks a server for query execution by returning the hosts URI, as found in the master and slave list.

If the lazy connections are enabled and the callback choses a slave server for which no connection has been established so far and establishing the connection to the slave fails, the plugin will return an error upon the next action on the failed connection, for example, when running a query. It is the responsibility of the application developer to handle the error. For example, the application can re-run the query to trigger a new server selection and callback invocation. If so, the callback must make sure to select a different slave, or check slave availability, before returning to the plugin to prevent an endless loop.

Przykład #12 Setting a callback

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "user": {
                "callback": "pick_server"
            }
        }
    }
}

The callback is supposed to return a host to run the query on. The host URI is to be taken from the master and slave connection lists passed to the callback function. If callback returns a value neither found in the master nor in the slave connection lists the plugin will emit an error of the type E_RECOVERABLE_ERROR The error may read like (mysqlnd_ms) User filter callback has returned an unknown server. The server 'server that is not in master or slave list' can neither be found in the master list nor in the slave list. If the application catches the error to ignore it, follow up errors may be set on the connection handle, for example, (mysqlnd_ms) No connection selected by the last filter with the error code 2000 and the sqlstate HY000. Furthermore a warning may be emitted.

Referencing a non-existing function as a callback will result in any error of the type E_RECOVERABLE_ERROR whenever the plugin tries to callback function. The error message may reads like: (mysqlnd_ms) Specified callback (pick_server) is not a valid callback. If the application catches the error to ignore it, follow up errors may be set on the connection handle, for example, (mysqlnd_ms) Specified callback (pick_server) is not a valid callback with the error code 2000 and the sqlstate HY000. Furthermore a warning may be emitted.

The following parameters are passed from the plugin to the callback.

Parameter Description Version
connected_host

URI of the currently connected database server.

Since 1.1.0.
query

Query string of the statement for which a server needs to be picked.

Since 1.1.0.
masters

List of master servers to choose from. Note, that the list of master servers may not be identical to the list of configured master servers if the filter is not the first in the filter chain. Previously run filters may have reduced the master list already.

Since 1.1.0.
slaves

List of slave servers to choose from. Note, that the list of master servers may not be identical to the list of configured master servers if the filter is not the first in the filter chain. Previously run filters may have reduced the master list already.

Since 1.1.0.
last_used_connection

URI of the server of the connection used to execute the previous statement on.

Since 1.1.0.
in_transaction

Boolean flag indicating wheter the statement is part of an open transaction. If autocommit mode is turned off, this will be set to TRUE. Otherwise it is set to FALSE.

Transaction detection is based on monitoring the mysqlnd library call set_autocommit. Monitoring is not possible beofre PHP 5.4.0. Please, see connection pooling and switching concepts discussion for further details.

Since 1.1.0.

Przykład #13 Using a callback

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "user": {
                "callback": "pick_server"
            }
        }
    }
}
<?php
function pick_server($connected, $query, $masters, $slaves, $last_used_connection, $in_transaction)
{
 static $slave_idx = 0;
 static $num_slaves = NULL;
 if (is_null($num_slaves))
  $num_slaves = count($slaves);

 /* default: fallback to the plugins build-in logic */
 $ret = NULL;

 printf("User has connected to '%s'...\n", $connected);
 printf("... deciding where to run '%s'\n", $query);

 $where = mysqlnd_ms_query_is_select($query);
 switch ($where)
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("... using master\n");
   $ret = $masters[0];
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   /* SELECT or SQL hint for using slave */
   if (stristr($query, "FROM table_on_slave_a_only"))
   {
    /* a table which is only on the first configured slave  */
    printf("... access to table available only on slave A detected\n");
    $ret = $slaves[0];
   }
   else
   {
    /* round robin */
    printf("... some read-only query for a slave\n");
    $ret = $slaves[$slave_idx++ % $num_slaves];
   }
   break;
  case MYSQLND_MS_QUERY_LAST_USED:
   printf("... using last used server\n");
   $ret = $last_used_connection;
   break;
 }

 printf("... ret = '%s'\n", $ret);
 return $ret;
}

$mysqli = new mysqli("myapp", "root", "", "test");

if (!($res = $mysqli->query("SELECT 1 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT 2 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT * FROM table_on_slave_a_only")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

$mysqli->close();
?>

Powyższy przykład wyświetli:

User has connected to 'myapp'...
... deciding where to run 'SELECT 1 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.2.27:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT 2 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.78.136:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT * FROM table_on_slave_a_only'
... access to table available only on slave A detected
... ret = 'tcp://192.168.2.27:3306'

Filter: user_multi object

The user_multi differs from the user only in one aspect. Otherwise, their syntax is identical. The user filter must pick and return exactly one node for statement execution. A filter chain usually ends with a filter that emits only one node. The filter chain shall reduce the list of candidates for statement execution down to one. This, only one node left, is the case after the user filter has been run.

The user_multi filter is a multi filter. It returns a list of slave and a list of master servers. This list needs further filtering to identify exactly one node for statement execution. A multi filter is typically placed at the top of the filter chain. The quality_of_service filter is another example of a multi filter.

The return value of the callback set for user_multi must be an an array with two elements. The first element holds a list of selected master servers. The second element contains a list of selected slave servers. The lists shall contain the keys of the slave and master servers as found in the slave and master lists passed to the callback. The below example returns random master and slave lists extracted from the functions input.

Przykład #14 Returning random masters and slaves

<?php
function pick_server($connected, $query, $masters, $slaves, $last_used_connection, $in_transaction)
{
  $picked_masters = array()
  foreach ($masters as $key => $value) {
    if (mt_rand(0, 2) > 1)
      $picked_masters[] = $key;
  }
  $picked_slaves = array()
  foreach ($slaves as $key => $value) {
    if (mt_rand(0, 2) > 1)
      $picked_slaves[] = $key;
  }
  return array($picked_masters, $picked_slaves);
}
?>

The plugin will issue an error of type E_RECOVERABLE if the callback fails to return a server list. The error may read (mysqlnd_ms) User multi filter callback has not returned a list of servers to use. The callback must return an array in %s on line %d. In case the server list is not empty but has invalid servers key/ids in it, an error of type E_RECOVERABLE will the thrown with an error message like (mysqlnd_ms) User multi filter callback has returned an invalid list of servers to use. Server id is negative in %s on line %d, or similar.

Whether an error is emitted in case of an empty slave or master list depends on the configuration. If an empty master list is returned for a write operation, it is likely that the plugin will emit a warning that may read (mysqlnd_ms) Couldn't find the appropriate master connection. 0 masters to choose from. Something is wrong in %s on line %d. Typically a follow up error of type E_ERROR will happen. In case of a read operation and an empty slave list the behviour depends on the fail over configuration. If fail over to master is enabled, no error should appear. If fail over to master is deactivated the plugin will emit a warning that may read (mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. Something is wrong in %s on line %d.

Filter: quality_of_service object

The quality_of_service identifies cluster nodes capable of delivering a certain quality of service. It is a multi filter which returns zero, one or multiple of its input servers. Thus, it must be followed by other filters to reduce the number of candidates down to one for statement execution.

The quality_of_service filter has been introduced in 1.2.0-alpha. In the 1.2 series the filters focus is on the consistency aspect of service quality. Different types of clusters offer different default data consistencies. For example, an asynchronous MySQL replication slave offers eventual consistency. The slave may not be able to deliver requested data because it has not replicated the write, it may serve stale database because its lagging behind or it may serve current information. Often, this is acceptable. In some cases higher consistency levels are needed for the application to work correct. In those cases, the quality_of_service can filter out cluster nodes which cannot deliver the necessary quality of service.

The quality_of_service filter can be replaced or created at runtime. A successful call to mysqlnd_ms_set_qos() removes all existing qos filter entries from the filter list and installs a new one at the very beginning. All settings that can be made through mysqlnd_ms_set_qos() can also be in the plugins configuration file. However, use of the function is by far the most common use case. Instead of setting session consistency and strong consistency service levels in the plugins configuration file it is recommended to define only masters and no slaves. Both service levels will force the use of masters only. Using an empty slave list shortens the configuration file, thus improving readability. The only service level for which there is a case of defining in the plugins configuration file is the combination of eventual consistency and maximum slave lag.

Keyword Description Version
eventual_consistency

Request eventual consistency. Allows the use of all master and slave servers. Data returned may or may not be current.

Eventual consistency accepts an optional age parameter. If age is given the plugin considers only slaves for reading for which MySQL replication reports a slave lag less or equal to age. The repliation lag is measure using SHOW SLAVE STATUS. If the plugin fails to fetch the replication lag, the slave tested is skipped. Implementation details and tipps are given in the quality of service concepts section.

Please note, if a filter chain generates an empty slave list and the PHP configuration directive mysqlnd_ms.multi_master=0 is used, the plugin may emit a warning.

Przykład #15 Global limit on slave lag

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "quality_of_service": {
                "eventual_consistency": {
                    "age":123
                }
            }
        }
    }
}

 Since 1.2.0.
session_consistency

Request session consistency (read your writes). Allows use of all masters and all slaves which are in sync with the master. If no further parameters are given slaves are filtered out as there is no reliable way to test if a slave has caugth up to the master or is lagging behind. Please note, if a filter chain generates an empty slave list and the PHP configuration directive mysqlnd_ms.multi_master=0 is used, the plugin may emit a warning.

Session consistency temporarily requested using mysqlnd_ms_set_qos() is a valuable alternative to using master_on_write. master_on_write is likely to send more statements to the master than needed. The application may be able to contiue operation at a lower consistency level after it has done some critial reads.

Since 1.1.0.
strong_consistency

Request strong consistency. Only masters will be used.

Since 1.2.0.
failover string

Failover policy. Supported policies: disabled (default), master.

If no failover policy is set, the plugin will not do any automatic failover (failover=disabled). Whenever the plugin fails to connect a server it will emit a warning and set the connections error code and message. Thereafter it is up to the application to handle the error and, for example, resent the last statement to trigger the selection of another server.

If using failover=master the plugin will implicitly failover to a slave, if available. Please check the concepts documentation to learn about potential pitfalls and risks of using failover=master.

Przykład #16 Optional master failover when failing to connect to slave

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "failover": "master"
    }
}

Setting failover to any other value but disabled or master will not emit any warning or error.

lazy_connections bool

Controls the use of lazy connections. Lazy connections are connections which are not opened before the client sends the first connection. Lazy connections are a default.

It is strongly recommended to use lazy connections. Lazy connections help to keep the number of open connections low. If you disable lazy connections and, for example, configure one MySQL replication master server and two MySQL replication slaves, the plugin will open three connections upon the first call to a connect function although the application might use the master connection only.

Lazy connections bare a risk if you make heavy use of actions which change the state of a connection. The plugin does not dispatch all state changing actions to all connections from the connection pool. The few dispatched actions are applied to already opened connections only. Lazy connections opened in the future are not affected. Only some settings are "remembered" and applied when lazy connections are opened.

Przykład #17 Disabling lazy connection

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "lazy_connections": 0
    }
}

master_on_write bool

If set, the plugin will use the master server only after the first statement has been executed on the master. Applications can still send statements to the slaves using SQL hints to overrule the automatic decision.

The setting may help with replication lag. If an application runs an INSERT the plugin will, by default, use the master to execute all following statements, including SELECT statements. This helps to avoid problems with reads from slaves which have not replicated the INSERT yet.

Przykład #18 Master on write for consistent reads

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "master_on_write": 1
    }
}

Please, note the quality_of_service filter introduced in version 1.2.0-alpha. It gives finer control, for example, for achieving read-your-writes and, it offers additional functionality introducing service levels.

trx_stickiness string

Transaction stickiness policy. Supported policies: disabled (default), master.

The setting requires 5.4.0 or newer. If used with PHP older than 5.4.0, the plugin will emit a warning like (mysqlnd_ms) trx_stickiness strategy is not supported before PHP 5.3.99.

If no transaction stickiness policy is set or, if setting trx_stickiness=disabled, the plugin is not transaction aware. Thus, the plugin may load balance connections and switch connections in the middle of a transaction. The plugin is not transaction safe. SQL hints must be used avoid connection switches during a transaction.

As of PHP 5.4.0 the mysqlnd library allows the plugin to monitor the autocommit mode set by calls to the libraries set_autocommit() function. If setting set_stickiness=master and autocommit gets disabled by a PHP MySQL extension invoking the mysqlnd library internal function call set_autocommit(), the plugin is made aware of the begin of a transaction. Then, the plugin stops load balancing and directs all statements to the master server until autocommit is enabled. Thus, no SQL hints are required.

An example of a PHP MySQL API function calling the mysqlnd library internal function call set_autocommit() is mysqli_autocommit().

Although setting ser_stickiness=master, the plugin cannot be made aware of autocommit mode changes caused by SQL statements such as SET AUTOCOMMIT=0.

Przykład #19 Using master to execute transactions

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "trx_stickiness": "master"
    }
}

Konfiguracja wykonawcza
Plugin configuration file (<= 1.0.x)
Instalacja/Konfiguracja


Plugin configuration file (<= 1.0.x)

Informacja:

The below description applies to PECL/mysqlnd_ms < 1.1.0-beta. It is not valid for later versions.

The plugin is using its own configuration file. The configuration file holds information on the MySQL replication master server, the MySQL replication slave servers, the server pick (load balancing) policy, the failover strategy and the use of lazy connections.

The PHP configuration directive mysqlnd_ms.ini_file is used to set the plugins configuration file.

The configuration file mimics standard the php.ini format. It consists of one or more sections. Every section defines its own unit of settings. There is no global section for setting defaults.

Applications reference sections by their name. Applications use section names as the host (server) parameter to the various connect methods of the mysqli, mysql and PDO_MYSQL extensions. Upon connect the mysqlnd plugin compares the hostname with all section names from the plugin configuration file. If hostname and section name match, the plugin will load the sections settings.

Przykład #1 Using section names example

[myapp]
master[] = localhost
slave[] = 192.168.2.27
slave[] = 192.168.2.28:3306
[localhost]
master[] = localhost:/tmp/mysql/mysql.sock
slave[] = 192.168.3.24:3305
slave[] = 192.168.3.65:3309
<?php
/* All of the following connections will be load balanced */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");

$mysqli = new mysqli("localhost", "username", "password", "database");
?>

Section names are strings. It is valid to use a section name such as 192.168.2.1, 127.0.0.1 or localhost. If, for example, an application connects to localhost and a plugin configuration section [localhost] exists, the semantics of the connect operation are changed. The application will no longer only use the MySQL server running on the host localhost but the plugin will start to load balance MySQL queries following the rules from the [localhost] configuration section. This way you can load balance queries from an application without changing the applications source code.

The master[], slave[] and pick[] configuration directives use a list-like syntax. Configuration directives supporting list-like syntax may appear multiple times in a configuration section. The plugin maintains the order in which entries appear when interpreting them. For example, the below example shows two slave[] configuration directives in the configuration section [myapp]. If doing round-robin load balancing for read-only queries, the plugin will send the first read-only query to the MySQL server mysql_slave_1 because it is the first in the list. The second read-only query will be send to the MySQL server mysql_slave_2 because it is the second in the list. Configuration directives supporting list-like syntax result are ordered from top to bottom in accordance to their appearance within a configuration section.

Przykład #2 List-like syntax

[myapp]
master[] = mysql_master_server
slave[] = mysql_slave_1
slave[] = mysql_slave_2

Here is a short explanation of the configuration directives that can be used.

master[] string

URI of a MySQL replication master server. The URI follows the syntax hostname[:port|unix_domain_socket].

The plugin supports using only one master server.

Setting a master server is mandatory. The plugin will report a warning upon connect if the user has failed to provide a master server for a configuration section. The warning may read (mysqlnd_ms) Cannot find master section in config. Furthermore the plugin may set an error code for the connection handle such as HY000/2000 (CR_UNKNOWN_ERROR). The corresponding error message depends on your language settings.

slave[] string

URI of one or more MySQL replication slave servers. The URI follows the syntax hostname[:port|unix_domain_socket].

The plugin supports using one or more slave servers.

Setting a slave server is mandatory. The plugin will report a warning upon connect if the user has failed to provide at least one slave server for a configuration section. The warning may read (mysqlnd_ms) Cannot find slaves section in config. Furthermore the plugin may set an error code for the connection handle such as HY000/2000 (CR_UNKNOWN_ERROR). The corresponding error message depends on your language settings.

pick[] string

Load balancing (server picking) policy. Supported policies: random, random_once (default), roundrobin, user.

If no load balancing policy is set, the plugin will default to random_once. The random_once policy picks a random slave server when running the first read-only statement. The slave server will be used for all read-only statements until the PHP script execution ends.

The random policy will pick a random server whenever a read-only statement is to be executed.

If using roundrobin the plugin iterates over the list of configured slave servers to pick a server for statement execution. If the plugin reaches the end of the list, it wraps around to the beginning of the list and picks the first configured slave server.

Setting more than one load balancing policy for a configuration section makes only sense in conjunction with user and mysqlnd_ms_set_user_pick_server(). If the user defined callback fails to pick a server, the plugin falls back to the second configured load balancing policy.

failover string

Failover policy. Supported policies: disabled (default), master.

If no failover policy is set, the plugin will not do any automatic failover (failover=disabled). Whenever the plugin fails to connect a server it will emit a warning and set the connections error code and message. Thereafter it is up to the application to handle the error and, for example, resent the last statement to trigger the selection of another server.

If using failover=master the plugin will implicitly failover to a slave, if available. Please check the concepts documentation to learn about potential pitfalls and risks of using failover=master.

lazy_connections bool

Controls the use of lazy connections. Lazy connections are connections which are not opened before the client sends the first connection.

It is strongly recommended to use lazy connections. Lazy connections help to keep the number of open connections low. If you disable lazy connections and, for example, configure one MySQL replication master server and two MySQL replication slaves, the plugin will open three connections upon the first call to a connect function although the application might use the master connection only.

Lazy connections bare a risk if you make heavy use of actions which change the state of a connection. The plugin does not dispatch all state changing actions to all connections from the connection pool. The few dispatched actions are applied to already opened connections only. Lazy connections opened in the future are not affected. If, for example, the connection character set is changed using a PHP MySQL API call, the plugin will change the character set of all currently opened connection. It will not remember the character set change to apply it on lazy connections opened in the future. As a result the internal connection pool would hold connections using different character sets. This is not desired. Remember that character sets are taken into account for escaping.

master_on_write bool

If set, the plugin will use the master server only after the first statement has been executed on the master. Applications can still send statements to the slaves using SQL hints to overrule the automatic decision.

The setting may help with replication lag. If an application runs an INSERT the plugin will, by default, use the master to execute all following statements, including SELECT statements. This helps to avoid problems with reads from slaves which have not replicated the INSERT yet.

trx_stickiness string

Transaction stickiness policy. Supported policies: disabled (default), master.

Experimental feature.

The setting requires 5.4.0 or newer. If used with PHP older than 5.4.0, the plugin will emit a warning like (mysqlnd_ms) trx_stickiness strategy is not supported before PHP 5.3.99.

If no transaction stickiness policy is set or, if setting trx_stickiness=disabled, the plugin is not transaction aware. Thus, the plugin may load balance connections and switch connections in the middle of a transaction. The plugin is not transaction safe. SQL hints must be used avoid connection switches during a transaction.

As of PHP 5.4.0 the mysqlnd library allows the plugin to monitor the autocommit mode set by calls to the libraries trx_autocommit() function. If setting trx_stickiness=master and autocommit gets disabled by a PHP MySQL extension invoking the mysqlnd library internal function call trx_autocommit(), the plugin is made aware of the begin of a transaction. Then, the plugin stops load balancing and directs all statements to the master server until autocommit is enabled. Thus, no SQL hints are required.

An example of a PHP MySQL API function calling the mysqlnd library internal function call trx_autocommit() is mysqli_autocommit().

Although setting trx_stickiness=master, the plugin cannot be made aware of autocommit mode changes caused by SQL statements such as SET AUTOCOMMIT=0.

Plugin configuration file (>=1.1.x)
Testing
Instalacja/Konfiguracja


Testing

Informacja:

The section applies to myslqnd_ms 1.1.0 or newer, not the 1.0 series.

The PECL/mysqlnd_ms test suite is in the tests/ directory of the source distribution. The test suite consists of standard phpt tests, which are described on the PHP Quality Assurance Teams website.

Running the tests requires setting up one to four MySQL servers. Some tests don't connect to MySQL at all. Others require one server for testing. Some require two distict servers. In some cases two servers are used to emulate a replication setup. In other cases a master and a slave of an existing MySQL replication setup are required for testing. The tests will try to detect how many servers and what kind of servers are given. If the required servers are not found, the test will be skipped automatically.

Before running the tests, edit tests/config.inc to configure the MySQL servers to be used for testing.

The most basic configuration is as follows.

 putenv("MYSQL_TEST_HOST=localhost");
 putenv("MYSQL_TEST_PORT=3306");
 putenv("MYSQL_TEST_USER=root");
 putenv("MYSQL_TEST_PASSWD=");
 putenv("MYSQL_TEST_DB=test");
 putenv("MYSQL_TEST_ENGINE=MyISAM");
 putenv("MYSQL_TEST_SOCKET=");

 putenv("MYSQL_TEST_SKIP_CONNECT_FAILURE=1");
 putenv("MYSQL_TEST_CONNECT_FLAGS=0");
 putenv("MYSQL_TEST_EXPERIMENTAL=0");

 /* replication cluster emulation */
 putenv("MYSQL_TEST_EMULATED_MASTER_HOST=". getenv("MYSQL_TEST_HOST"));
 putenv("MYSQL_TEST_EMULATED_SLAVE_HOST=". getenv("MYSQL_TEST_HOST"));

 /* real replication cluster */
 putenv("MYSQL_TEST_MASTER_HOST=". getenv("MYSQL_TEST_EMULATED_MASTER_HOST"));
 putenv("MYSQL_TEST_SLAVE_HOST=". getenv("MYSQL_TEST_EMULATED_SLAVE_HOST"));

MYSQL_TEST_HOST, MYSQL_TEST_PORT and MYSQL_TEST_SOCKET define the hostname, TCP/IP port and Unix domain socket of the default database server. MYSQL_TEST_USER and MYSQL_TEST_PASSWD contain the user and password needed to connect to the database/schema configured with MYSQL_TEST_DB. All configured servers must have the same database user configured to give access to the test database.

Using host, host:port or host:/path/to/socket syntax one can set an alternate host, host and port or host and socket for any of the servers.

putenv("MYSQL_TEST_SLAVE_HOST=192.168.78.136:3307"));
putenv("MYSQL_TEST_MASTER_HOST=myserver_hostname:/path/to/socket"));

Plugin configuration file (<= 1.0.x)
Debugging and Tracing
Instalacja/Konfiguracja


Debugging and Tracing

The mysqlnd debug log can be used to debug and trace the actitivities of PECL/mysqlnd_ms. As a mysqlnd PECL/mysqlnd_ms adds trace information to the mysqlnd library debug file. Please, see the mysqlnd.debug PHP configuration directive documentation for a detailed description on how to configure the debug log.

Configuration setting example to activate the debug log:

mysqlnd.debug=d:t:x:O,/tmp/mysqlnd.trace

Informacja:

This feature is only available with a debug build of PHP. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above.

The debug log shows mysqlnd library and PECL/mysqlnd_ms plugin function calls, similar to a trace log. Mysqlnd library calls are usually prefixed with mysqlnd_. PECL/mysqlnd internal calls begin with mysqlnd_ms.

Example excerpt from the debug log (connect):

[...]
>mysqlnd_connect
| info : host=myapp user=root db=test port=3306 flags=131072
| >mysqlnd_ms::connect
| | >mysqlnd_ms_config_json_section_exists
| | | info : section=[myapp] len=[5]
| | | >mysqlnd_ms_config_json_sub_section_exists
| | | | info : section=[myapp] len=[5]
| | | | info : ret=1
| | | <mysqlnd_ms_config_json_sub_section_exists
| | | info : ret=1
| | <mysqlnd_ms_config_json_section_exists
[...]

The debug log is not only useful for plugin developers but also to find the cause of user errors. For example, if your application does not do proper error handling and fails to record error messages, checking the debug and trace log may help finding the cause. Use of the debug log to debug application issues should be considered only if no other option is available. Writing the debug log to disk is a slow operation and may have negative impact on the application performance.

Example excerpt from the debug log (connection failure):

[...]
| | | | | | | info : adding error [Access denied for user 'root'@'localhost' (using password: YES)] to the list
| | | | | | | info : PACKET_FREE(0)
| | | | | | | info : PACKET_FREE(0x7f3ef6323f50)
| | | | | | | info : PACKET_FREE(0x7f3ef6324080)
| | | | | | <mysqlnd_auth_handshake
| | | | | | info : switch_to_auth_protocol=n/a
| | | | | | info : conn->error_info.error_no = 1045
| | | | | <mysqlnd_connect_run_authentication
| | | | | info : PACKET_FREE(0x7f3ef63236d8)
| | | | | >mysqlnd_conn::free_contents
| | | | | | >mysqlnd_net::free_contents
| | | | | | <mysqlnd_net::free_contents
| | | | | | info : Freeing memory of members
| | | | | | info : scheme=unix:///tmp/mysql.sock
| | | | | | >mysqlnd_error_list_pdtor
| | | | | | <mysqlnd_error_list_pdtor
| | | | | <mysqlnd_conn::free_contents
| | | | <mysqlnd_conn::connect
[...]

The trace log can also be used to verify correct behaviour of PECL/mysqlnd_ms itself, for example, to check which server has been selected for query execution and why.

Example excerpt from the debug log (plugin decision):

[...]
>mysqlnd_ms::query
| info : query=DROP TABLE IF EXISTS test
| >_mysqlnd_plugin_get_plugin_connection_data
| | info : plugin_id=5
| <_mysqlnd_plugin_get_plugin_connection_data
| >mysqlnd_ms_pick_server_ex
| | info : conn_data=0x7fb6a7d3e5a0 *conn_data=0x7fb6a7d410d0
| | >mysqlnd_ms_select_servers_all
| | <mysqlnd_ms_select_servers_all
| | >mysqlnd_ms_choose_connection_rr
| | | >mysqlnd_ms_query_is_select
[...]
| | | <mysqlnd_ms_query_is_select
[...]
| | | info : Init the master context
| | | info : list(0x7fb6a7d3f598) has 1
| | | info : Using master connection
| | | >mysqlnd_ms_advanced_connect
| | | | >mysqlnd_conn::connect
| | | | | info : host=localhost user=root db=test port=3306 flags=131072 persistent=0 state=0

In this case the statement DROP TABLE IF EXISTS test has been executed. Note that the statement string is shown in the log file. You may want to take measures to restrict access to the log for security considerations.

The statement has been load balanced using round robin policy, as you can easily guess from the functions name >mysqlnd_ms_choose_connection_rr. It has been sent to a master server running on host=localhost user=root db=test port=3306 flags=131072 persistent=0 state=0.

Testing
Monitoring
Instalacja/Konfiguracja


Monitoring

Plugin activity can be monitored using the mysqlnd trace log, mysqlnd statistics, mysqlnd_ms plugin statistics and external PHP debugging tools. Use of the trace log should be limited to debugging. It is recommended to use the plugins statistics for monitoring.

Writing a trace log is a slow operation. If using an external PHP debugging tool, please refer to the vendors manual about its perfomance impact and the type of information collected. In many cases, external debugging tools will provide call stacks. Often, a call stack or a trace log is more difficult to interpret than the statistics provided by the plugin.

Plugin statistics tell how often which kind of cluster node has been used (slave or master), why the node was used, if lazy connections have been used and if global transaction ID injection has been performed. The monitoring information provided enables user to verify plugin decisions and to plan their cluster resources based on usage pattern. The function mysqlnd_ms_get_stats() is used to access the statistics. Please, see the functions description for a list of available statistics.

Statistics are collected on a per PHP process basis. Their scope is a PHP process. Depending on the PHP deployment model a process may serve one or multiple web requests. If using CGI model, a PHP process serves one web request. If using FastCGI or pre-fork web server models, a PHP process usually serves multiple web requests. The same is the case with a threaded web server. Please, note that threads running in parallel can update the statistics in parallel. Thus, if using a threaded PHP deployment model, statistics can be changed by more than one script at a time. A script cannot rely on the fact that it sees only its own changes to statistics.

Przykład #1 Verify plugin activity in a non-threaded deployment model

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
<?php
/* Load balanced following "myapp" section rules from the plugins config file (not shown) */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

$stats_before = mysqlnd_ms_get_stats();
if ($res = $mysqli->query("SELECT 'Read request' FROM DUAL")) {
  var_dump($res->fetch_all());
}
$stats_after = mysqlnd_ms_get_stats();
if ($stats_after['use_slave'] <= $stats_before['use_slave']) {
  echo "According to the statistics the read request has not been run on a slave!";
}
?>

Statistics are aggregated for all plugin activities and all connections handled by the plugin. It is not possible to tell how much a certain connection handle has contributed to the overall statistics.

Utilizing PHPs register_shutdown_function() function or the auto_append_file PHP configuration directive it is easily possible to dump statistics into, for example, a log file when a script finishes. Instead of using a log file it is also possible to send the statistics to an external monitoring tool for recording and display.

Przykład #2 Recording statistics during shutdown

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
error_log=/tmp/php_errors.log
<?php
function check_stats() {
  $msg = str_repeat("-", 80) . "\n";
  $msg .= var_export(mysqlnd_ms_get_stats(), true) . "\n";
  $msg .= str_repeat("-", 80) . "\n";
  error_log($msg);
}
register_shutdown_function("check_stats");
?>

Debugging and Tracing
Stałe predefiniowane
Instalacja/Konfiguracja


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.

SQL hint related

The mysqlnd replication and load balancing plugin (mysqlnd_ms) performs read/write splitting. This directs write queries to a MySQL master server, and read-only queries to the MySQL slave servers. The plugin has a built-in read/write split logic. All queries which start with SELECT are considered read-only queries, which are then sent to a MySQL slave server that is listed in the plugin configuration file. All other queries are directed to the MySQL master server that is also specified in the plugin configuration file.

User supplied SQL hints can be used to overrule automatic read/write splitting, to gain full control on the process. SQL hints are standards compliant SQL comments. The plugin will scan the beginning of a query string for an SQL comment for certain commands, which then control query redirection. Other systems involved in the query processing are unaffected by the SQL hints because other systems will ignore the SQL comments.

The plugin supports three SQL hints to direct queries to either the MySQL slave servers, the MySQL master server, or the last used MySQL server. SQL hints must be placed at the beginning of a query to be recognized by the plugin.

For better portability, it is recommended to use the string constants MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH and MYSQLND_MS_LAST_USED_SWITCH instead of their literal values.

<?php
/* Use constants for maximum portability */
$master_query = "/*" . MYSQLND_MS_MASTER_SWITCH . "*/SELECT id FROM test";

/* Valid but less portable: using literal instead of constant */
$slave_query = "/*ms=slave*/SHOW TABLES";

printf("master_query = '%s'\n", $master_query);
printf("slave_query = '%s'\n", $slave_query);
?>

Powyższe przykłady wyświetlą:

master_query = /*ms=master*/SELECT id FROM test
slave_query = /*ms=slave*/SHOW TABLES

MYSQLND_MS_MASTER_SWITCH (string)
SQL hint used to send a query to the MySQL replication master server.
MYSQLND_MS_SLAVE_SWITCH (string)
SQL hint used to send a query to one of the MySQL replication slave servers.
MYSQLND_MS_LAST_USED_SWITCH (string)
SQL hint used to send a query to the last used MySQL server. The last used MySQL server can either be a master or a slave server in a MySQL replication setup.

mysqlnd_ms_query_is_select() related

MYSQLND_MS_QUERY_USE_MASTER (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_MASTER for a given query, the built-in read/write split mechanism recommends sending the query to a MySQL replication master server.
MYSQLND_MS_QUERY_USE_SLAVE (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_SLAVE for a given query, the built-in read/write split mechanism recommends sending the query to a MySQL replication slave server.
MYSQLND_MS_QUERY_USE_LAST_USED (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_LAST_USED for a given query, the built-in read/write split mechanism recommends sending the query to the last used server.

mysqlnd_ms_set_qos(), quality of service filter and service level related

MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL (integer)
Use to request the service level eventual consistency from the mysqlnd_ms_set_qos(). Eventual consistency is the default quality of service when reading from an asynchronous MySQL replication slave. Data returned in this service level may or may not be stale, depending on whether the selected slaves happens to have replicated the lastest changes from the MySQL replication master or not.
MYSQLND_MS_QOS_CONSISTENCY_SESSION (integer)
Use to request the service level session consistency from the mysqlnd_ms_set_qos(). Session consistency is defined as read your writes. The client is guaranteed to see his latest changes.
MYSQLND_MS_QOS_CONSISTENCY_STRONG (integer)
Use to request the service level strong consistency from the mysqlnd_ms_set_qos(). Strong consistency is used to ensure all clients see each others changes.
MYSQLND_MS_QOS_OPTION_GTID (integer)
Used as a service level option with mysqlnd_ms_set_qos() to parameterize session consistency.
MYSQLND_MS_QOS_OPTION_AGE (integer)
Used as a service level option with mysqlnd_ms_set_qos() to parameterize eventual consistency.

Other

The plugins version number can be obtained using MYSQLND_MS_VERSION or MYSQLND_MS_VERSION_ID. MYSQLND_MS_VERSION is the string representation of the numerical version number MYSQLND_MS_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_MS_VERSION_ID | 10000

MYSQLND_MS_VERSION (string)
Plugin version string, for example, "1.0.0-prototype".
MYSQLND_MS_VERSION_ID (integer)
Plugin version number, for example, 10000.

Monitoring
Mysqlnd_ms Funkcje
mysqlnd_ms


Mysqlnd_ms Funkcje

Spis treści

  • mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID
  • mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection
  • mysqlnd_ms_get_stats — Returns query distribution and connection statistics
  • mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not
  • mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server
  • mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster
  • mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting
Stałe predefiniowane
mysqlnd_ms_get_last_gtid
mysqlnd_ms


Returns the latest global transaction ID

Mysqlnd_ms Funkcje
mysqlnd_ms_get_last_used_connection
Mysqlnd_ms Funkcje
PHP Manual

mysqlnd_ms_get_last_gtid

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

mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID

Opis

string mysqlnd_ms_get_last_gtid ( mixed $connection )

Returns a global transaction identifier which belongs to a write operation no older than the last write performed by the client. It is not guaranteed that the global transaction identifier is identical to that one created for the last write transaction performed by the client.

Parametry

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MySQL, mysqli or mysql. The connection handle is obtained when opening a connection with a host name that matches a mysqlnd_ms configuration file entry using any of the three extensions.

Zwracane wartości

Returns a global transaction ID (GTID) on success. Otherwise, returns FALSE.

The function mysqlnd_ms_get_last_gtid() returns the GTID obtained when executing the SQL statement from the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file.

The function may be called after the GTID has been incremented.

Notatki

Informacja:

mysqlnd_ms_get_last_gtid() requires PHP >= 5.4.0 and PECL mysqlnd_ms >= 1.2.0. Internally, it is using a mysqlnd library C functionality not available with PHP 5.3.

Przykłady

Przykład #1 mysqlnd_ms_get_last_gtid() example

<?php
/* Open mysqlnd_ms connection using mysqli, PDO_MySQL or mysql extension */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));
?>

Zobacz też:

  • Global Transaction IDs

Mysqlnd_ms Funkcje
mysqlnd_ms_get_last_used_connection
Mysqlnd_ms Funkcje


Returns an array which describes the last used connection

mysqlnd_ms_get_last_gtid
mysqlnd_ms_get_stats
Mysqlnd_ms Funkcje
PHP Manual

mysqlnd_ms_get_last_used_connection

(PHP >= 5.4.0, PECL mysqlnd_ms >= 1.1.0)

mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection

Opis

array mysqlnd_ms_get_last_used_connection ( mixed $connection )

Returns an array which describes the last used connection from the plugins connection pool currently pointed to by the user connection handle. If using the plugin, a user connection handle represents a pool of database connections. It is not possible to tell from the user connection handles properties to which database server from the pool the user connection handle points.

The function can be used to debug or monitor PECL mysqlnd_ms.

Parametry

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

Zwracane wartości

FALSE on error. Otherwise, an array which describes the connection used to execute the last statement on.

Array which describes the connection.

Property | Description | Version
scheme | Connection scheme. Either tcp://host:port or unix://host:socket. If you want to distinguish connections from each other use a combination of scheme and thread_id as a unique key. Neither scheme nor thread_id alone are sufficient to distinguish two connections from each other. Two servers may assign the same thread_id to two different connections. Thus, connections in the pool may have the same thread_id. Also, do not rely on uniqueness of scheme in a pool. Your QA engineers may use the same MySQL server instance for two distinct logical roles and add it multiple times to the pool. This hack is used, for example, in the test suite. | Since 1.1.0.
host | Database server host used with the connection. The host is only set with TCP/IP connections. It is empty with Unix domain or Windows named pipe connections, | Since 1.1.0.
host_info | A character string representing the server hostname and the connection type. | Since 1.1.2.
port | Database server port used with the connection. | Since 1.1.0.
socket_or_pipe | Unix domain socket or Windows named pipe used with the connection. The value is empty for TCP/IP connections. | Since 1.1.2.
thread_id | Connection thread id. | Since 1.1.0.
last_message | Info message obtained from the MySQL C API function mysql_info(). Please, see mysqli_info() for a description. | Since 1.1.0.
errno | Error code. | Since 1.1.0.
error | Error message. | Since 1.1.0.
sqlstate | Error SQLstate code. | Since 1.1.0.

Notatki

Informacja:

mysqlnd_ms_get_last_used_connection() requires PHP >= 5.4.0 and PECL mysqlnd_ms >> 1.1.0. Internally, it is using a mysqlnd library C call not available with PHP 5.3.

Przykłady

The example assumes that myapp refers to a plugin configuration file section and represents a connection pool.

Przykład #1 mysqlnd_ms_get_last_used_connection() example

<?php
$link = new mysqli("myapp", "user", "password", "database");
$res = $link->query("SELECT 1 FROM DUAL");
var_dump(mysqlnd_ms_get_last_used_connection($link));
?>

Powyższy przykład wyświetli:

array(10) {
  ["scheme"]=>
  string(22) "unix:///tmp/mysql.sock"
  ["host_info"]=>
  string(25) "Localhost via UNIX socket"
  ["host"]=>
  string(0) ""
  ["port"]=>
  int(3306)
  ["socket_or_pipe"]=>
  string(15) "/tmp/mysql.sock"
  ["thread_id"]=>
  int(46253)
  ["last_message"]=>
  string(0) ""
  ["errno"]=>
  int(0)
  ["error"]=>
  string(0) ""
  ["sqlstate"]=>
  string(5) "00000"
}

mysqlnd_ms_get_last_gtid
mysqlnd_ms_get_stats
Mysqlnd_ms Funkcje


Returns query distribution and connection statistics

mysqlnd_ms_get_last_used_connection
mysqlnd_ms_match_wild
Mysqlnd_ms Funkcje
PHP Manual

mysqlnd_ms_get_stats

(PECL mysqlnd_ms >= 1.0.0)

mysqlnd_ms_get_stats — Returns query distribution and connection statistics

Opis

array mysqlnd_ms_get_stats ( void )

Returns an array of statistics collected by the replication and load balancing plugin.

The PHP configuration setting mysqlnd_ms.collect_statistics controls the collection of statistics. The collection of statistics is disabled by default for performance reasons.

The scope of the statistics is the PHP process. Depending on your deployment model a PHP process may handle one or multiple requests.

Statistics are aggregated for all connections and all storage handler. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql API calls have contributed to the aggregated data values.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns NULL if the PHP configuration directive mysqlnd_ms.enable has disabled the plugin. Otherwise, returns array of statistics.

Array of statistics

Statistic | Description | Version
use_slave

The semantics of this statistic has changed between 1.0.1 - 1.1.0.

The meaning for version 1.0.1 is as follows. Number of statements considered as read-only by the built-in query analyzer. Neither statements which begin with a SQL hint to force use of slave nor statements directed to a slave by an user-defined callback are included. The total number of statements sent to the slaves is use_slave + use_slave_sql_hint + use_slave_callback.

PECL/mysqlnd_ms 1.1.0 introduces a new concept of chained filters. The statictics is now set by the internal load balancing filter. With version 1.1.0 the load balancing filter is always the last in the filter chain, if used. In future versions a load balancing filter may be followed by other filters causing another change in the meaning of the statistic. If, in the future, a load balancing filter is followed by another filter it is no longer guaranteed that the satement, whichs increments use_slave, will be executed on the slaves.

The meaning for version 1.1.0 is as follows. Number of statements sent to the slaves. Statements directed to a slave by the user filter (an user-defined callback) are not included. The latter are counted by use_slave_callback.

Since 1.0.0.
use_master

The semantics of this statistic has changed between 1.0.1 - 1.1.0.

The meaning for version 1.0.1 is as follows. Number of statements not considered as read-only by the built-in query analyzer. Neither statements which begin with a SQL hint to force use of master nor statements directed to a master by an user-defined callback are included. The total number of statements sent to the master is use_master + use_master_sql_hint + use_master_callback.

PECL/mysqlnd_ms 1.1.0 introduces a new concept of chained filters. The statictics is now set by the internal load balancing filter. With version 1.1.0 the load balancing filter is always the last in the filter chain, if used. In future versions a load balancing filter may be followed by other filters causing another change in the meaning of the statistic. If, in the future, a load balancing filter is followed by another filter it is no longer guaranteed that the satement, whichs increments use_master, will be executed on the slaves.

The meaning for version 1.1.0 is as follows. Number of statements sent to the masters. Statements directed to a master by the user filter (an user-defined callback) are not included. The latter are counted by use_master_callback.

Since 1.0.0.
use_slave_guess | Number of statements the built-in query analyzer recommends sending to a slave because they contain no SQL hint to force use of a certain server. The recommendation may be overruled in the following. It is not guaranteed whether the statement will be excuted on a slave or not. This is how often the internal is_select function has guessed that a slave shall be used. Please, see also the user space function mysqlnd_ms_query_is_select(). | Since 1.1.0.
use_master_guess | Number of statements the built-in query analyzer recommends sending to a master because they contain no SQL hint to force use of a certain server. The recommendation may be overruled in the following. It is not guaranteed whether the statement will be excuted on a slave or not. This is how often the internal is_select function has guessed that a master shall be used. Please, see also the user space function mysqlnd_ms_query_is_select(). | Since 1.1.0.
use_slave_sql_hint | Number of statements sent to a slave because statement begins with the SQL hint to force use of slave. | Since 1.0.0.
use_master_sql_hint | Number of statements sent to a master because statement begins with the SQL hint to force use of master. | Since 1.0.0.
use_last_used_sql_hint | Number of statements sent to server which has run the previous statement, because statement begins with the SQL hint to force use of previously used server. | Since 1.0.0.
use_slave_callback | Number of statements sent to a slave because an user-defined callback has chosen a slave server for statement execution. | Since 1.0.0.
use_master_callback | Number of statements sent to a master because an user-defined callback has chosen a master server for statement execution. | Since 1.0.0.
non_lazy_connections_slave_success | Number of successfully opened slave connections from configurations not using lazy connections. The total number of successfully opened slave connections is non_lazy_connections_slave_success + lazy_connections_slave_success | Since 1.0.0.
non_lazy_connections_slave_failure | Number of failed slave connection attempts from configurations not using lazy connections. The total number of failed slave connection attempts is non_lazy_connections_slave_failure + lazy_connections_slave_failure | Since 1.0.0.
non_lazy_connections_master_success | Number of successfully opened master connections from configurations not using lazy connections. The total number of successfully opened master connections is non_lazy_connections_master_success + lazy_connections_master_success | Since 1.0.0.
non_lazy_connections_master_failure | Number of failed master connection attempts from configurations not using lazy connections. The total number of failed master connection attempts is non_lazy_connections_master_failure + lazy_connections_master_failure | Since 1.0.0.
lazy_connections_slave_success | Number of successfully opened slave connections from configurations using lazy connections. | Since 1.0.0.
lazy_connections_slave_failure | Number of failed slave connection attempts from configurations using lazy connections. | Since 1.0.0.
lazy_connections_master_success | Number of successfully opened master connections from configurations using lazy connections. | Since 1.0.0.
lazy_connections_master_failure | Number of failed master connection attempts from configurations using lazy connections. | Since 1.0.0.
trx_autocommit_on | Number of autocommit mode activations via API calls. This figure may be used to monitor activity related to the plugin configuration setting trx_stickiness. If, for example, you want to know if a certain API call invokes the mysqlnd library function trx_autocommit(), which is a requirement for trx_stickiness, you may call the user API function in question and check if the statistic has changed. The statistic is modified only by the plugins internal subclassed trx_autocommit() method. | Since 1.0.0.
trx_autocommit_off | Number of autocommit mode deactivations via API calls. | Since 1.0.0.
trx_master_forced | Number of statemens redirected to the master while trx_stickiness=master and autocommit mode is disabled. | Since 1.0.0.
gtid_autocommit_injections_success | Number of successful SQL injections in autocommit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_autocommit_injections_failure | Number of failed SQL injections in autocommit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_commit_injections_success | Number of successful SQL injections in commit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_commit_injections_failure | Number of failed SQL injections in commit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_implicit_commit_injections_success | Number of successful SQL injections when implicit commit is detected as part of the plugins client-side global transaction id emulation. Implicit commit happens, for example, when autocommit has been turned off, a query is executed and autocommit is enabled again. In that case, the statement will be committed by the server and SQL to maintain is injected before the autocommit is re-enabled. | Since 1.2.0.
gtid_implicit_commit_injections_failure | Number of failed SQL injections when implicit commit is detected as part of the plugins client-side global transaction id emulation. Implicit commit happens, for example, when autocommit has been turned off, a query is executed and autocommit is enabled again. In that case, the statement will be committed by the server and SQL to maintain is injected before the autocommit is re-enabled. | Since 1.2.0.

Przykłady

Przykład #1 mysqlnd_ms_get_stats() example

<?php
printf("mysqlnd_ms.enable = %d\n", ini_get("mysqlnd_ms.enable"));
printf("mysqlnd_ms.collect_statistics = %d\n", ini_get("mysqlnd_ms.collect_statistics"));
var_dump(mysqlnd_ms_get_stats());
?>

Powyższy przykład wyświetli:

mysqlnd_ms.enable = 1
mysqlnd_ms.collect_statistics = 1
array(26) {
  ["use_slave"]=>
  string(1) "0"
  ["use_master"]=>
  string(1) "0"
  ["use_slave_guess"]=>
  string(1) "0"
  ["use_master_guess"]=>
  string(1) "0"
  ["use_slave_sql_hint"]=>
  string(1) "0"
  ["use_master_sql_hint"]=>
  string(1) "0"
  ["use_last_used_sql_hint"]=>
  string(1) "0"
  ["use_slave_callback"]=>
  string(1) "0"
  ["use_master_callback"]=>
  string(1) "0"
  ["non_lazy_connections_slave_success"]=>
  string(1) "0"
  ["non_lazy_connections_slave_failure"]=>
  string(1) "0"
  ["non_lazy_connections_master_success"]=>
  string(1) "0"
  ["non_lazy_connections_master_failure"]=>
  string(1) "0"
  ["lazy_connections_slave_success"]=>
  string(1) "0"
  ["lazy_connections_slave_failure"]=>
  string(1) "0"
  ["lazy_connections_master_success"]=>
  string(1) "0"
  ["lazy_connections_master_failure"]=>
  string(1) "0"
  ["trx_autocommit_on"]=>
  string(1) "0"
  ["trx_autocommit_off"]=>
  string(1) "0"
  ["trx_master_forced"]=>
  string(1) "0"
  ["gtid_autocommit_injections_success"]=>
  string(1) "0"
  ["gtid_autocommit_injections_failure"]=>
  string(1) "0"
  ["gtid_commit_injections_success"]=>
  string(1) "0"
  ["gtid_commit_injections_failure"]=>
  string(1) "0"
  ["gtid_implicit_commit_injections_success"]=>
  string(1) "0"
  ["gtid_implicit_commit_injections_failure"]=>
  string(1) "0"
}

Zobacz też:

  • Runtime configuration
  • mysqlnd_ms.collect_statistics
  • mysqlnd_ms.enable
  • Monitoring

mysqlnd_ms_get_last_used_connection
mysqlnd_ms_match_wild
Mysqlnd_ms Funkcje


Finds whether a table name matches a wildcard pattern or not

mysqlnd_ms_get_stats
mysqlnd_ms_query_is_select
Mysqlnd_ms Funkcje
PHP Manual

mysqlnd_ms_match_wild

(PECL mysqlnd_ms >= 1.1.0)

mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not

Opis

bool mysqlnd_ms_match_wild ( string $table_name , string $wildcard )

Finds whether a table name matches a wildcard pattern or not.

This function is not of much practical relevance with PECL mysqlnd_ms 1.1.0 because the plugin does not support MySQL replication table filtering yet.

Parametry

table_name

The table name to check if it is matched by the wildcard.

wildcard

The wildcard pattern to check against the table name. The wildcard pattern supports the same placeholders as MySQL replication filters do.

MySQL replication filters can be configured by using the MySQL Server configuration options --replicate-wild-do-table and --replicate-wild-do-db. Please, consult the MySQL Reference Manual to learn more about this MySQL Server feature.

The supported placeholders are:

  • % - zero or more literals
  • % - one literal

Placeholders can be escaped using \.

Zwracane wartości

Returns TRUE table_name is matched by wildcard. Otherwise, returns FALSE

Przykłady

Przykład #1 mysqlnd_ms_match_wild() example

<?php
var_dump(mysqlnd_ms_match_wild("schema_name.table_name", "schema%"));
var_dump(mysqlnd_ms_match_wild("abc", "_"));
var_dump(mysqlnd_ms_match_wild("table1", "table_"));
var_dump(mysqlnd_ms_match_wild("asia_customers", "%customers"));
var_dump(mysqlnd_ms_match_wild("funny%table","funny\%table"));
var_dump(mysqlnd_ms_match_wild("funnytable", "funny%table"));
?>

Powyższy przykład wyświetli:

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

mysqlnd_ms_get_stats
mysqlnd_ms_query_is_select
Mysqlnd_ms Funkcje


Find whether to send the query to the master, the slave or the last used MySQL server

mysqlnd_ms_match_wild
mysqlnd_ms_set_qos
Mysqlnd_ms Funkcje
PHP Manual

mysqlnd_ms_query_is_select

(PECL mysqlnd_ms >= 1.0.0)

mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server

Opis

int mysqlnd_ms_query_is_select ( string $query )

Finds whether to send the query to the master, the slave or the last used MySQL server.

The plugins built-in read/write split mechanism will be used to analyze the query string to make a recommendation where to send the query. The built-in read/write split mechanism is very basic and simple. The plugin will recommend sending all queries to the MySQL replication master server but those which begin with SELECT, or begin with a SQL hint which enforces sending the query to a slave server. Due to the basic but fast algorithm the plugin may propose to run some read-only statements such as SHOW TABLES on the replication master.

Parametry

query

Query string to test.

Zwracane wartości

A return value of MYSQLND_MS_QUERY_USE_MASTER indicates that the query should be send to the MySQL replication master server. The function returns a value of MYSQLND_MS_QUERY_USE_SLAVE if the query can be run on a slave because it is considered read-only. A value of MYSQLND_MS_QUERY_USE_LAST_USED is returned to recommend running the query on the last used server. This can either be a MySQL replication master server or a MySQL replication slave server.

If read write splitting has been disabled by setting mysqlnd_ms.disable_rw_split, the fucntion will always return MYSQLND_MS_QUERY_USE_MASTER or MYSQLND_MS_QUERY_USE_LAST_USED.

Przykłady

Przykład #1 mysqlnd_ms_query_is_select() example

<?php
function is_select($query)
{
 switch (mysqlnd_ms_query_is_select($query))
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("'%s' should be run on the master.\n", $query);
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   printf("'%s' should be run on a slave.\n", $query);
   break;
  case MYSQLND_MS_QUERY_USE_LAST_USED:
   printf("'%s' should be run on the server that has run the previous query\n", $query);
   break;
  default:
   printf("No suggestion where to run the '%s', fallback to master recommended\n", $query);
   break;
 }
}

is_select("INSERT INTO test(id) VALUES (1)");
is_select("SELECT 1 FROM DUAL");
is_select("/*" . MYSQLND_MS_LAST_USED_SWITCH . "*/SELECT 2 FROM DUAL");
?>

Powyższy przykład wyświetli:

INSERT INTO test(id) VALUES (1) should be run on the master.
SELECT 1 FROM DUAL should be run on a slave.
/*ms=last_used*/SELECT 2 FROM DUAL should be run on the server that has run the previous query

Zobacz też:

  • Predefined Constants
  • user filter
  • Runtime configuration
  • mysqlnd_ms.disable_rw_split
  • mysqlnd_ms.enable

mysqlnd_ms_match_wild
mysqlnd_ms_set_qos
Mysqlnd_ms Funkcje


Sets the quality of service needed from the cluster

mysqlnd_ms_query_is_select
mysqlnd_ms_set_user_pick_server
Mysqlnd_ms Funkcje
PHP Manual

mysqlnd_ms_set_qos

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

mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster

Opis

bool mysqlnd_ms_set_qos ( mixed $connection , int $service_level [, int $service_level_option [, mixed $option_value ]] )

Sets the quality of service needed from the cluster. A database cluster delivers a certain quality of service to the user depending on its architecture. A major aspect of the quality of service is the consistency level the cluster can offer. An asynchronous MySQL replication cluster defaults to eventual consistency for slave reads: a slave may serve stale data, current data or it may have not the requested data at all, because it is not synchronous to the master. In a MySQL replication cluster only master accesses can give strong consistency, which promises that all clients see each others changes.

PECL/mysqlnd_ms hides the complexity of choosing appropriate nodes to achieve a certain level of service from the cluster. The quality of service filter implements the necessary logic. The filter can either be configured in the plugins configuration file or at run time using mysqlnd_ms_set_qos().

Similar results can be achieved with PECL mysqlnd_ms < 1.2.0, if using SQL hints to force the use of a certain type of node or using the master_on_write plugin configuration option. The first requires more code and causes more work on the application side. The latter is coarser than using the quality of service filter. Settings made through the function call can be reversed, as shown in the example below. The example temporarily switches to a higher service level (session consistency, read your writes) and returns back to the clusters default after it has performed all operations that require the better service. This way, read load on the master can be minimized compared to using master_on_write, which would continue using the master after the first write.

Parametry

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MySQL, mysqli or mysql for which a service level is to be set. The connection handle is obtained when opening a connection with a host name that matches a mysqlnd_ms configuration file entry using any of the three extensions.

service_level

The requested service level: MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_CONSISTENCY_SESSION or MYSQLND_MS_QOS_CONSISTENCY_STRONG.

service_level_option

An option to parameterize the requested service level. The option can either be MYSQLND_MS_QOS_OPTION_GTID or MYSQLND_MS_QOS_OPTION_AGE.

The option MYSQLND_MS_QOS_OPTION_GTID can be used to refine the service level MYSQLND_MS_QOS_CONSISTENCY_SESSION. It must be combined with a fourth function parameter, the option_value. The option_value shall be a global transaction ID obtained from mysqlnd_ms_get_last_gtid(). If set, the plugin considers both master servers and asynchronous slaves for session consistency (read your writes). Otherwise, only masters are used to achive session consistency. A slave is considered up-to-date and taken into account if it has already replicated the global transaction ID from option_value. Please note, searching appropriate slaves is an expensive and slow operation. Use the feature sparsely, if the master cannot handle the read load alone.

The option MYSQLND_MS_QOS_OPTION_AGE can be used together with the MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL service level to filter out asynchronous slaves that lag more seconds behind the master than option_value. If set, the plugin will consider only slaves for reading for which SHOW SLAVE STATUS reports Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master <= option_value. Please note, searching appropriate slaves is an expensive and slow operation. Use the feature sparsely in version 1.2.0. Future versions may improve the algorithm used to identify candidates. Please, see the MySQL reference manual about the precision, accuracy and limitations of the MySQL administrative command SHOW SLAVE STATUS.

option_value

Parameter value for the service level option. See also service_level_option.

Zwracane wartości

Returns TRUE if the connections service level has been switched to the requested. Otherwise, returns FALSE

Notatki

Informacja:

mysqlnd_ms_set_qos() requires PHP >= 5.4.0 and PECL mysqlnd_ms >= 1.2.0. Internally, it is using a mysqlnd library C functionality not available with PHP 5.3.

Przykłady

Przykład #1 mysqlnd_ms_set_qos() example

<?php
/* Open mysqlnd_ms connection using mysqli, PDO_MySQL or mysql extension */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Session consistency: read your writes */
$ret = mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION);
if (!$ret)
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Will use master and return fresh data, client can see his last write */
if (!$res = $mysqli->query("SELECT item, price FROM orders WHERE order_id = 1"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Back to default: use of all slaves and masters permitted, stale data can happen */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

Zobacz też:

  • mysqlnd_ms_get_last_gtid() - Returns the latest global transaction ID
  • Service level and consistency concept
  • Filter concept

mysqlnd_ms_query_is_select
mysqlnd_ms_set_user_pick_server
Mysqlnd_ms Funkcje


Sets a callback for user-defined read/write splitting

mysqlnd_ms_set_qos
Change History
Mysqlnd_ms Funkcje
PHP Manual

mysqlnd_ms_set_user_pick_server

(PECL mysqlnd_ms < 1.1.0)

mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting

Opis

bool mysqlnd_ms_set_user_pick_server ( string $function )

Sets a callback for user-defined read/write splitting. The plugin will call the callback only if pick[]=user is the default rule for server picking in the relevant section of the plugins configuration file.

The plugins built-in read/write query split mechanism decisions can be overwritten in two ways. The easiest way is to prepend the query string with the SQL hints MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH or MYSQLND_MS_LAST_USED_SWITCH. Using SQL hints one can control, for example, whether a query shall be send to the MySQL replication master server or one of the slave servers. By help of SQL hints it is not possible to pick a certain slave server for query execution.

Full control on server selection can be gained using a callback function. Use of a callback is recommended to expert users only because the callback has to cover all cases otherwise handled by the plugin.

The plugin will invoke the callback function for selecting a server from the lists of configured master and slave servers. The callback function inspects the query to run and picks a server for query execution by returning the hosts URI, as found in the master and slave list.

If the lazy connections are enabled and the callback choses a slave server for which no connection has been established so far and establishing the connection to the slave fails, the plugin will return an error upon the next action on the failed connection, for example, when running a query. It is the responsibility of the application developer to handle the error. For example, the application can re-run the query to trigger a new server selection and callback invocation. If so, the callback must make sure to select a different slave, or check slave availability, before returning to the plugin to prevent an endless loop.

Parametry

function

The function to be called. Class methods may also be invoked statically using this function by passing array($classname, $methodname) to this parameter. Additionally class methods of an object instance may be called by passing array($objectinstance, $methodname) to this parameter.

Zwracane wartości

Host to run the query on. The host URI is to be taken from the master and slave connection lists passed to the callback function. If callback returns a value neither found in the master nor in the slave connection lists the plugin will fallback to the second pick method configured via the pick[] setting in the plugin configuration file. If not second pick method is given, the plugin falls back to the build-in default pick method for server selection.

Notatki

Informacja:

mysqlnd_ms_set_user_pick_server() is available with PECL mysqlnd_ms < 1.1.0. It has been replaced by the user filter. Please, check the Change History for upgrade notes.

Przykłady

Przykład #1 mysqlnd_ms_set_user_pick_server() example

[myapp]
master[] = localhost
slave[] = 192.168.2.27:3306
slave[] = 192.168.78.136:3306
pick[] = user
<?php

function pick_server($connected, $query, $master, $slaves, $last_used)
{
 static $slave_idx = 0;
 static $num_slaves = NULL;
 if (is_null($num_slaves))
  $num_slaves = count($slaves);

 /* default: fallback to the plugins build-in logic */
 $ret = NULL;

 printf("User has connected to '%s'...\n", $connected);
 printf("... deciding where to run '%s'\n", $query);

 $where = mysqlnd_ms_query_is_select($query);
 switch ($where)
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("... using master\n");
   $ret = $master[0];
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   /* SELECT or SQL hint for using slave */
   if (stristr($query, "FROM table_on_slave_a_only"))
   {
    /* a table which is only on the first configured slave  */
    printf("... access to table available only on slave A detected\n");
    $ret = $slaves[0];
   }
   else
   {
    /* round robin */
    printf("... some read-only query for a slave\n");
    $ret = $slaves[$slave_idx++ % $num_slaves];
   }
   break;
  case MYSQLND_MS_QUERY_LAST_USED:
   printf("... using last used server\n");
   $ret = $last_used;
   break;
 }

 printf("... ret = '%s'\n", $ret);
 return $ret;
}

mysqlnd_ms_set_user_pick_server("pick_server");

$mysqli = new mysqli("myapp", "root", "root", "test");

if (!($res = $mysqli->query("SELECT 1 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT 2 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT * FROM table_on_slave_a_only")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

$mysqli->close();
?>

Powyższy przykład wyświetli:

User has connected to 'myapp'...
... deciding where to run 'SELECT 1 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.2.27:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT 2 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.78.136:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT * FROM table_on_slave_a_only'
... access to table available only on slave A detected
... ret = 'tcp://192.168.2.27:3306'

Zobacz też:

  • mysqlnd_ms_query_is_select() - Find whether to send the query to the master, the slave or the last used MySQL server
  • Filter concept
  • user filter

mysqlnd_ms_set_qos
Change History
Mysqlnd_ms Funkcje


Change History

Spis treści

  • PECL/mysqlnd_ms 1.2 series
  • PECL/mysqlnd_ms 1.1 series
  • PECL/mysqlnd_ms 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.

mysqlnd_ms_set_user_pick_server
PECL/mysqlnd_ms 1.2 series
mysqlnd_ms


PECL/mysqlnd_ms 1.2 series

1.2.1-beta

  • Release dates: 01/2012 (beta)
  • Motto/theme: see 1.2.0-alpha

Minor test changes.

1.2.0-alpha

  • Release dates: 11/2011 (alpha)
  • Motto/theme: Global Transaction ID injection and quality-of-service concept

In version 1.2 the focus continues to be on supporting MySQL database clusters with asynchronous replication. The plugin tries to make using the cluster introducing a quality-of-service filter which applications can use to define what service quality they need from the cluster. Service levels provided are eventual consistency with optional maximum age/slave slag, session consistency and strong consistency.

Additionally the plugin can do client-side global transaction id injection to make manual master failover easier.

Feature changes

  • Introduced quality-of-service (QoS) filter. Service levels provided by QoS filter:

    • eventual consistency, optional option slave lag
    • session consistency, optional option GTID
    • strong consistency

  • Added mysqlnd_ms_set_qos() function to set required connection quality at runtime. New constants related to mysqlnd_ms_set_qos():

    • MYSQLND_MS_QOS_CONSISTENCY_STRONG
    • MYSQLND_MS_QOS_CONSISTENCY_SESSION
    • MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL
    • MYSQLND_MS_QOS_OPTION_GTID
    • MYSQLND_MS_QOS_OPTION_AGE

  • Added client-side global transaction id injection (GTID).

  • New statistics related to GTID:

    • gtid_autocommit_injections_success
    • gtid_autocommit_injections_failure
    • gtid_commit_injections_success
    • gtid_commit_injections_failure
    • gtid_implicit_commit_injections_success
    • gtid_implicit_commit_injections_failure

  • Added mysqlnd_ms_get_last_gtid() to fetch last global transaction id.

  • Enabled support for multi master without slaves.

Change History
PECL/mysqlnd_ms 1.1 series
Change History


PECL/mysqlnd_ms 1.1 series

1.1.0

  • Release date: 09/2011
  • Motto/theme: Cover replication basics with production quality

The 1.1 and 1.0 series expose a similar feature set. Internally, the 1.1 series has been refactored to plan for future feature additions. A new configuration file format has been introduced, and limitations have been lifted. And the code quality and quality assurance has been improved.

Feature changes

  • Added the (chainable) filter concept:

    • BC break: mysqlnd_ms_set_user_pick_server() has been removed. Thehttp://svn.php.net/viewvc/pecl/mysqlnd_ms/trunk/ user filter has been introduced to replace it. The filter offers similar functionality, but see below for an explanation of the differences.

  • New powerful JSON based configuration syntax.
  • Lazy connections improved: security relevant, and state changing commands are covered.
  • Support for (native) prepared statements.

  • New statistics: use_master_guess, use_slave_guess.

    • BC break: Semantics of statistics changed for use_slave, use_master. Future changes are likely. Please see, mysqlnd_ms_get_stats().

  • List of broadcasted messages extended by ssl_set.
  • Library calls now monitored to remember settings for lazy connections: change_user, select_db, set_charset, set_autocommit.
  • Introduced mysqlnd_ms.disable_rw_split. The configuration setting allows using the load balancing and lazy connection functionality independently of read write splitting.

Bug fixes

  • Fixed PECL #22724 - Server switching (mysqlnd_ms_query_is_select() case sensitive)
  • Fixed PECL #22784 - Using mysql_connect and mysql_select_db did not work
  • Fixed PECL #59982 - Unusable extension with --enable-mysqlnd-ms-table-filter. Use of the option is NOT supported. You must not used it. Added note to m4.
  • Fixed Bug #60119 - host="localhost" lost in mysqlnd_ms_get_last_used_connection()

The mysqlnd_ms_set_user_pick_server() function was removed, and replaced in favor of a new user filter. You can no longer set a callback function using mysqlnd_ms_set_user_pick_server() at runtime, but instead have to configure it in the plugins configuration file. The user filter will pass the same arguments to the callback as before. Therefore, you can continue to use the same procedural function as a callback.callback It is no longer possible to use static class methods, or class methods of an object instance, as a callback. Doing so will cause the function executing a statement handled by the plugin to emit an E_RECOVERABLE_ERROR level error, which might look like: "(mysqlnd_ms) Specified callback (picker) is not a valid callback." Note: this may halt your application.

PECL/mysqlnd_ms 1.2 series
PECL/mysqlnd_ms 1.0 series
Change History


PECL/mysqlnd_ms 1.0 series

1.0.1-alpha

  • Release date: 04/2011
  • Motto/theme: bug fix release

1.0.0-alpha

  • Release date: 04/2011
  • Motto/theme: Cover replication basics to test user feedback

The first release of practical use. It features basic automatic read-write splitting, SQL hints to overrule automatic redirection, load balancing of slave requests, lazy connections, and optional, automatic use of the master after the first write.

The public feature set is close to that of the 1.1 release.

1.0.0-pre-alpha

  • Release date: 09/2010
  • Motto/theme: Proof of concept

Initial check-in. Essentially a demo of the mysqlnd plugin API.

PECL/mysqlnd_ms 1.1 series
mysqlnd_qc
Change History


Mysqlnd query result cache plugin

  • Wstęp
  • Quickstart and Examples
    • Architecture and Concepts
    • Setup
    • Caching queries
    • Setting the TTL
    • Pattern based caching
    • Slam defense
    • Finding cache candidates
    • Measuring cache efficiency
    • Beyond TTL: user-defined storage
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
  • Stałe predefiniowane
  • mysqlnd_qc Funkcje
    • mysqlnd_qc_clear_cache — Flush all cache contents
    • mysqlnd_qc_get_available_handlers — Returns a list of available storage handler
    • mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available
    • mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache
    • mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache
    • mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache
    • mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached
    • mysqlnd_qc_set_storage_handler — Change current storage handler
    • mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler
  • Change History
    • PECL/mysqlnd_qc 1.1 series
    • PECL/mysqlnd_qc 1.0 series
PECL/mysqlnd_ms 1.0 series
Wstęp
MySQL


Wstęp

The mysqlnd query result cache plugin adds easy to use client-side query caching to all PHP MySQL extensions using mysqlnd.

As of version PHP 5.3.3 the MySQL native driver for PHP ( mysqlnd) features an internal plugin C API. C plugins, such as the query cache plugin, can extend the functionality of mysqlnd.

Mysqlnd plugins such as the query cache plugin operate transparent from a user perspective. The cache plugin supports all PHP applications and all PHP MySQL extensions ( mysqli, mysql, PDO_MYSQL). It does not change existing APIs.

No significant application changes are required to cache a query. The cache has two operation modes. It will either cache all queries (not recommended) or only those queries marked with a certain SQL hint (recommended).

Key Features

  • Transparent and therefore easy to use

    • supports all PHP MySQL extensions

    • no API changes

    • very little application changes required

  • Flexible invalidation strategy

    • Time-to-Live (TTL)

    • user-defined

  • Storage with different scope and life-span

    • Default (Hash, process memory)

    • APC

    • MEMCACHE

    • sqlite

    • user-defined

Limitations

The current 1.0.1 release of PECL mysqlnd_qc does not support PHP 5.4.

Prepared statements and unbuffered queries are fully supported. Thus, the plugin is capable of caching all statements issued with mysqli or PDO_MySQL, which are the only two PHP MySQL APIs to offer prepared statement support.

On the name

The shortcut mysqlnd_qc stands for mysqlnd query cache plugin. The name was chosen for a quick-and-dirty proof-of-concept. In the beginning the developers did not expect to continue using the code base. Sometimes PECL/mysqlnd_qc has also been called client-side query result set cache.

mysqlnd_qc
Quickstart and Examples
mysqlnd_qc


Quickstart and Examples

Spis treści

  • Architecture and Concepts
  • Setup
  • Caching queries
  • Setting the TTL
  • Pattern based caching
  • Slam defense
  • Finding cache candidates
  • Measuring cache efficiency
  • Beyond TTL: user-defined storage

The mysqlnd query cache plugin is easy to use. This quickstart will demo typical use-cases, and provide practical advice on getting started.

It is strongly recommended to read the reference sections in addition to the quickstart. It is safe to begin with the quickstart. However, before using the plugin in mission critical environments we urge you to read additionally the background information from the reference sections.

Most of the examples use the mysqli extension because it is the most feature complete PHP MySQL extension. However, the plugin can be used with any PHP MySQL extension that is using the mysqlnd library.

Wstęp
Architecture and Concepts
mysqlnd_qc


Architecture and Concepts

The query cache plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter it gets registered as a mysqlnd plugin to replace selected mysqlnd C methods. Hereby, it can change the behaviour of any PHP MySQL extension (mysqli, PDO_MYSQL, mysql) compiled to use the mysqlnd library without changing the extensions API. This makes the plugin compatible with each and every PHP MySQL application. Because existing APIs are not changed, it is almost transparent to use. Please, see the mysqlnd plugin API description for a discussion of the advantages of the plugin architecture and a comparison with proxy based solutions.

Transparent to use

At PHP run time PECL/mysqlnd_qc can proxy queries send from PHP (mysqlnd) to the MySQL server. It then inspects the statement string to find whether it shall cache its results. If so, result set is cached using a storage handler and further executions of the statement are served from the cache for a user-defined period. The Time to Live (TTL) of the cache entry can either be set globally or on a per statement basis.

A statement is either cached if the plugin is instructed to cache all statements globally using a or, if the query string starts with the SQL hint (/*qc=on*/). The plugin is capable of caching any query isssued by calling appropriate API calls of any of the existing PHP MySQL extensions.

Flexible storage: various storage handler

Various storage handler are supported to offer different scopes for cache entries. Different scopes allow for different degrees in sharing cache entries among clients.

  • default (built-in): process memory, scope: process, one or more web requests depending on PHP deployment model used

  • APC: shared memory, scope: single server, multiple web requests

  • SQLite: memory or file, scope: single server, multiple web requests

  • MEMCACHE: main memory, scope: single or multiple server, multiple web requests

  • user (built-in): user-defined - any, scope: user-defined - any

Support for the APC, SQLite and MEMCACHE storage handler has to be enabled at compile time. The default and user handler are built-in. It is possible to switch between compiled-in storage handlers on a per query basis at run time. However, it is recommended to pick one storage handler and use it for all cache entries.

Built-in slam defense to avoid overloading

To avoid overload situations the cache plugin has a built-in slam defense mechanism. If a popular cache entries expires many clients using the cache entries will try to refresh the cache entry. For the duration of the refresh many clients may access the database server concurrently. In the worst case, the database server becomes overloaded and it takes more and more time to refresh the cache entry, which in turn lets more and more clients try to refresh the cache entry. To prevent this from happening the plugin has a slam defense mechanism. If slam defense is enabled and the plugin detects an expired cache entry it extends the life time of the cache entry before it refreshes the cache entry. This way other concurrent accesses to the expired cache entry are still served from the cache for a certain time. The other concurrent accesses to not trigger a concurrent refresh. Ideally, the cache entry gets refreshed by the client which extended the cache entries lifespan before other clients try to refresh the cache and potentially cause an overload situation.

Unique approach to caching

PECL/mysqlnd_qc has a unique approach to caching result sets that is superior to application based cache solutions. Application based solutions first fetch a result set into PHP variables. Then, the PHP variables are serialized for storing in a persistent cache and unserialized when fetching. The mysqlnd query cache stores the raw wire protocol data send from MySQL to PHP in its cache and replayes it, if still valid, on a cache hit. This way, it saves an extra serialization step for a cache put that all application based solutions have to do. It can store the raw wire protocol data in the cache without having to serizalize into a PHP variable first and deserializing the PHP variable for storing in the cache again.

Quickstart and Examples
Setup
Quickstart and Examples


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install the » PECL/mysqlnd_qc extension.

Compile or configure the PHP MySQL extension (mysqli, PDO_MYSQL, mysql) that you plan to use with support for the mysqlnd library. PECL/mysqlnd_qc is a plugin for the mysqlnd library. To use the plugin with any of the existing PHP MySQL extensions (APIs), the extension has to use the mysqlnd library.

Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_qc.enable_qc.

Przykład #1 Enabling the plugin (php.ini)

mysqlnd_qc.enable_qc=1

Architecture and Concepts
Caching queries
Quickstart and Examples


Caching queries

The plugin can either cache all statements by default or, only those that begin with an SQL hint to enable caching. A SQL hint is a SQL standards compliant comment. As a SQL comment it is ignored by the database. A statement is considered eligable for caching if it either begins with the SQL hint enabling caching or it is a SELECT statement.

An individual query which shall be cached must begin with the SQL hint /*qc=on*/. It is recommended to use the PHP constant MYSQLND_QC_ENABLE_SWITCH instead of using the string value.

  • not eliable for caching and not cached: INSERT INTO test(id) VALUES (1)

  • not eliable for caching and not cached: SHOW ENGINES

  • eliable for caching but uncached: SELECT id FROM test

  • eliable for caching and cached: /*qc=on*/SELECT id FROM test

The examples SELECT statement string is prefixed with the MYSQLND_QC_ENABLE_SWITCH SQL hint to enable caching of the statement. The SQL hint must be given at the very beginning of the statement string to enable caching.

mysqlnd_qc.enable_qc=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* Will be cached because of the SQL hint */
$start = microtime(true);
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
printf("Total time uncached query: %.6fs\n", microtime(true) - $start);

/* Cache hit */
$start = microtime(true);
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
printf("Total time cached query: %.6fs\n", microtime(true) - $start);
?>

Powyższe przykłady wyświetlą:

array(1) {
  ["id"]=>
  string(1) "1"
}
Total time uncached query: 0.000740s
array(1) {
  ["id"]=>
  string(1) "1"
}
Total time cached query: 0.000098s

If nothing else is configured, as it is the case in the quickstart example, the plugin will use the built-in default storage handler. The default storage handler uses process memory to hold a cache entry. Depending on the PHP deploymnet model a PHP process may serve one or more web requests. Please, consult the web server manual for details. Details make no difference for the examples given in the quickstart.

The query cache plugin will cache all queries regardless if the query string begins with the SQL hint which enables caching or not, if the PHP configuration directive mysqlnd_qc.cache_by_default is set to 1. The setting mysqlnd_qc.cache_by_default is evaluated by the core of the query cache plugins. Neither the built-in nor user-defined storage handler can overrule the setting.

The SQL hint /*qc=off*/ can be used to disable caching of individual queries if mysqlnd_qc.cache_by_default = 1 It is recommended to use the PHP constant MYSQLND_QC_DISABLE_SWITCH instead of using the string value.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* Will be cached although no SQL hint is present because of mysqlnd_qc.cache_by_default = 1*/
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

$mysqli->query("DELETE FROM test WHERE id = 1");

/* Cache hit - no automatic invalidation and still valid! */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* Cache miss - query must not be cached because of the SQL hint */
$res = $mysqli->query("/*" . MYSQLND_QC_DISABLE_SWITCH . "*/SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>

Powyższe przykłady wyświetlą:

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

PECL/mysqlnd_qc forbids caching of statements for which at least one column from the statements result set shows no table name in its meta data by default. This is usually the case for columns originating from SQL functions such as NOW() or LAST_INSERT_ID(). The policy aims to prevent pitfalls if caching by default is used.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");

for ($i = 0; $i < 3; $i++) {

  $start = microtime(true);

  /* Note: statement will not be cached because of NOW() use */
  $res = $mysqli->query("SELECT id, NOW() AS _time FROM test");
  $row = $res->fetch_assoc();

  /* dump results */
  var_dump($row);

  printf("Total time: %.6fs\n", microtime(true) - $start);

  /* pause one second */
  sleep(1);
}
?>

Powyższe przykłady wyświetlą:

array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:10"
}
Total time: 0.000540s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:11"
}
Total time: 0.000555s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:12"
}
Total time: 0.000549s

It is possible to enable caching for all statements including those which has columns in their result set for which MySQL reports no table, such as the statement from the example. Set mysqlnd_qc.cache_no_table = 1 to enable caching of such statements. Please, note the difference in the measured times for the above and below examples.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
mysqlnd_qc.cache_no_table=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");

for ($i = 0; $i < 3; $i++) {

  $start = microtime(true);

  /* Note: statement will not be cached because of NOW() use */
  $res = $mysqli->query("SELECT id, NOW() AS _time FROM test");
  $row = $res->fetch_assoc();

  /* dump results */
  var_dump($row);

  printf("Total time: %.6fs\n", microtime(true) - $start);

  /* pause one second */
  sleep(1);
}
?>

Powyższe przykłady wyświetlą:

array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000546s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000187s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000167s

Informacja:

Although mysqlnd_qc.cache_no_table = 1 has been created for use with mysqlnd_qc.cache_by_default = 1 it is bound it. The plugin will evaluate the mysqlnd_qc.cache_no_table whenever a query is to be cached, no matter whether caching has been enabled using a SQL hint or any other measure.

Setup
Setting the TTL
Quickstart and Examples


Setting the TTL

The default invalidation strategy of the query cache plugin is Time to Live (TTL). The built-in storage handlers will use the default TTL defined by the PHP configuration value mysqlnd_qc.ttl unless the query string contains a hint for setting a different TTL. The TTL is specified in seconds. By default cache entries expire after 30 seconds

The example sets mysqlnd_qc.ttl=3 to cache statements for three seconds by default. Every second it updates a database table record to hold the current time and executes a SELECT statement to fetch the record from the database. The SELECT statement is cached for three seconds because it is prefixed with the SQL hint enabling caching. The output verifies that the query results are taken from the cache for the duration of three seconds before they are refreshed.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.ttl=3
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id VARCHAR(255))");

for ($i = 0; $i < 7; $i++) {

  /* update DB row  */
  if (!$mysqli->query("DELETE FROM test") ||
      !$mysqli->query("INSERT INTO test(id) VALUES (NOW())"))
    /* Of course, a real-life script should do better error handling */
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

  /* select latest row but cache results */
  $query  = "/*" . MYSQLND_QC_ENABLE_SWITCH . "*/";
  $query .= "SELECT id AS _time FROM test";
  if (!($res = $mysqli->query($query)) ||
      !($row = $res->fetch_assoc()))
  {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
  }
  $res->free();
  printf("Wall time %s - DB row time %s\n", date("H:i:s"), $row['_time']);

  /* pause one second */
  sleep(1);
}
?>

Powyższe przykłady wyświetlą:

Wall time 14:55:59 - DB row time 2012-01-11 14:55:59
Wall time 14:56:00 - DB row time 2012-01-11 14:55:59
Wall time 14:56:01 - DB row time 2012-01-11 14:55:59
Wall time 14:56:02 - DB row time 2012-01-11 14:56:02
Wall time 14:56:03 - DB row time 2012-01-11 14:56:02
Wall time 14:56:04 - DB row time 2012-01-11 14:56:02
Wall time 14:56:05 - DB row time 2012-01-11 14:56:05

As can be seen from the example, any TTL based cache can serve stale data. Cache entries are not automatically invalidated, if underlying data changes. Applications using the default TTL invalidation strategy must be able to work correctly with stale data.

User-defined cache storage handler can implement any invalidation strategy to work around this limitation. Please, find more on this below.

The default TTL can be overruled using the SQL hint /*qc_tt=seconds*/. The SQL hint must be appear immediately after the SQL hint which enables caching. It is recommended to use the PHP constant MYSQLND_QC_TTL_SWITCH instead of using the string value.

<?php
$start = microtime(true);

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

printf("Default TTL\t: %d seconds\n", ini_get("mysqlnd_qc.ttl"));

/* Will be cached for 2 seconds */
$sql = sprintf("/*%s*//*%s%d*/SELECT id FROM test WHERE id = 1",
 MYSQLND_QC_ENABLE_SWITCH,
 MYSQLND_QC_TTL_SWITCH,
 2);
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();

$mysqli->query("DELETE FROM test WHERE id = 1");
sleep(1);

/* Cache hit - no automatic invalidation and still valid! */
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();

sleep(2);

/* Cache miss - cache entry has expired */
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();

printf("Script runtime\t: %d seconds\n", microtime(true) - $start);
?>

Powyższe przykłady wyświetlą:

Default TTL     : 30 seconds
array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "1"
}
NULL
Script runtime  : 3 seconds

Caching queries
Pattern based caching
Quickstart and Examples


Pattern based caching

An application has three options for telling PECL/mysqlnd_qc whether a particular statement shall be used. The most basic approach is to cache all statements by setting mysqlnd_qc.cache_by_default = 1. This apporach is often of little practical value. But it enables users to make a quick estimation about the maximum performance gains from caching. An application designed to use a cache may able to prefix selected statements with the appropriate SQL hints. However, altering an applications source code may not always be possible or desired, for example, to avoid problems with software updates. Therefore, PECL/mysqlnd_qc allows setting a callback which decides if a query is to be cached.

The callback is installed with the mysqlnd_qc_set_is_select() function. The callback is given the statement string of every statement inspected by the plugin. Then, the callback can decide whether to cache the function. The callback is supposed to return FALSE if the statement shall not be cached. A return value of TRUE makes the plugin try to add the statement into the cache. The cache entry will be given the default TTL ( mysqlnd_qc.ttl). If the callback returns a numberical value it is used as the TTL instead of the global default.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_statistics=1
<?php
/* callback which decides if query is cached */
function is_select($query) {
  static $patterns = array(
   /* true - use default from mysqlnd_qc.ttl */
   "@SELECT\s+.*\s+FROM\s+test@ismU" => true,
   /* 3 - use TTL = 3 seconds */
   "@SELECT\s+.*\s+FROM\s+news@ismU" => 3
  );

  /* check if query does match pattern */
  foreach ($patterns as $pattern => $ttl) {
    if (preg_match($pattern, $query)) {
      printf("is_select(%45s): cache\n", $query);
      return $ttl;
    }
  }
  printf("is_select(%45s): do not cache\n", $query);
  return false;
}
/* install callback */
mysqlnd_qc_set_is_select("is_select");

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* cache put */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache hit */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache put */
$mysqli->query("SELECT * FROM test");

$stats = mysqlnd_qc_get_core_stats();
printf("Cache put: %d\n", $stats['cache_put']);
printf("Cache hit: %d\n", $stats['cache_hit']);
?>

Powyższe przykłady wyświetlą:

is_select(                    DROP TABLE IF EXISTS test): do not cache
is_select(                    CREATE TABLE test(id INT)): do not cache
is_select(    INSERT INTO test(id) VALUES (1), (2), (3)): do not cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(                           SELECT * FROM test): cache
Cache put: 2
Cache hit: 1

The examples callback tests if a statement string matches a pattern. If this is the case, it either returns TRUE to cache the statement using the global default TTL or an alternative TTL.

To minimize application changes the callback can put into and registered in an auto prepend file.

Setting the TTL
Slam defense
Quickstart and Examples


Slam defense

A badly designed cache can do more harm than good. In the worst case a cache can increase database server load instead of minimizing it. An overload situation can occur if a highly shared cache entry expires.

Cache entries are shared and reused to a different degree depending on the storage used. The default storage handler stores cache entries in process memory. Thus, a cache entry can be reused for the life-span of a process. Other PHP processes cannot access it. If Memcache is used, a cache entry can be shared among multiple PHP processes and even among multiple machines, depending on the set up being used.

If a highly shared cache entry stored, for example, in Memcache expires, many clients gets a cache miss. Many client requests can no longer be served from the cache but try to run the underlying query on the database server. Until the cache entry is refreshed, more and more clients contact the database server. In the worst case, a total lost of service is the result.

The overload can be avoided using a storage handler which limits the reuse of cache entries to few clients. Then, at the average, its likely that only a limited number of clients will try to refresh a cache entry concurrently.

Additionally, the built-in slam defense mechanism can and should be used. If slam defense is activated an expired cache entry is given an extended life time. The first client getting a cache miss for the expired cache entry tries to refresh the cache entry within the extended life time. All other clients requesting the cache entry are temporarily served from the cache although the original TTL of the cache entry has expired. The other clients will not experience a cache miss before the extended life time is over.

mysqlnd_qc.slam_defense=1
mysqlnd_qc.slam_defense_ttl=1

The slam defense mechanism is enabled with the PHP configuration directive mysqlnd_qc.slam_defense. The extended life time of a cache entry is set with mysqlnd_qc.slam_defense_ttl.

The function mysqlnd_qc_get_core_stats() returns an array of statistics. The statistics slam_stale_refresh and slam_stale_hit are incremented if slam defense takes place.

It is not possible to give a one-fits-all recommendation on the slam defense configuration. Users are advised to monitor and test their setup and derive settings accordingly.

Pattern based caching
Finding cache candidates
Quickstart and Examples


Finding cache candidates

A statement should be considered for caching if it is executed often and has a long run time. Cache candidates are found by creating a list of statements sorted by the product of the number of executions multiplied by the statements run time. The function mysqlnd_qc_get_query_trace_log() returns a query log which help with the task.

Collecting a query trace is a slow operation. Thus, it is disabled by default. The PHP configuration directive mysqlnd_qc.collect_query_trace is used to enable it. The functions trace contains one entry for every query issued before the function is called.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");

/* dummy queries to fill the query trace */
for ($i = 0; $i < 2; $i++) {
  $res = $mysqli->query("SELECT 1 AS _one FROM DUAL");
  $res->free();
}

/* dump trace */
var_dump(mysqlnd_qc_get_query_trace_log());
?>

Powyższe przykłady wyświetlą:

array(2) {
  [0]=>
  array(8) {
    ["query"]=>
    string(26) "SELECT 1 AS _one FROM DUAL"
    ["origin"]=>
    string(102) "#0 qc.php(7): mysqli->query('SELECT 1 AS _on...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(25)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [1]=>
  array(8) {
    ["query"]=>
    string(26) "SELECT 1 AS _one FROM DUAL"
    ["origin"]=>
    string(102) "#0 qc.php(7): mysqli->query('SELECT 1 AS _on...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(8)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
}

Assorted information is given in the trace. Among them timings and the origin of the query call. The origin property holds a code backtrace to identify the source of the query. The depth of the backtrace can be limited with the PHP configuration directive mysqlnd_qc.query_trace_bt_depth. The default depth is 3.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 0; $i < 3; $i++) {
  $res = $mysqli->query("SELECT id FROM test WHERE id = " . $mysqli->real_escape_string($i));
  $res->free();
}

$trace = mysqlnd_qc_get_query_trace_log();
$summary = array();
foreach ($trace as $entry) {
  if (!isset($summary[$entry['query']])) {
    $summary[$entry['query']] = array(
      "executions" => 1,
      "time"       => $entry['run_time'] + $entry['store_time'],
    );
  } else {
    $summary[$entry['query']]['executions']++;
    $summary[$entry['query']]['time'] += $entry['run_time'] + $entry['store_time'];
 }
}
foreach ($summary as $query => $details) {
  printf("%45s: %5dms (%dx)\n",
   $query, $details['time'], $details['executions']);
}
?>

Powyższe przykłady wyświetlą:

                    DROP TABLE IF EXISTS test:     0ms (1x)
                    CREATE TABLE test(id INT):     0ms (1x)
    INSERT INTO test(id) VALUES (1), (2), (3):     0ms (1x)
             SELECT id FROM test WHERE id = 0:    25ms (1x)
             SELECT id FROM test WHERE id = 1:    10ms (1x)
             SELECT id FROM test WHERE id = 2:     9ms (1x)

Slam defense
Measuring cache efficiency
Quickstart and Examples


Measuring cache efficiency

PECL/mysqlnd_qc offers three ways to measure the cache efficiency. The function mysqlnd_qc_get_normalized_query_trace_log() returns statistics aggregated by the normalized query string, mysqlnd_qc_get_cache_info() gives storage handler specific information which includes a list of all cached items, depending on the storage handler. Additionally, the core of PECL/mysqlnd_qc collects high-level summary statistics aggregated per PHP process. The high-level satistics are returned by mysqlnd_qc_get_core_stats().

The functions mysqlnd_qc_get_normalized_query_trace_log() and mysqlnd_qc_get_core_stats() will not collect data unless, data collection has been enabled through their corresponding PHP configuration directives. Please, find the names of the configuration directives in the examples. Data collection is disabled by default for performance considerations. It has been made configurable through mysqlnd_qc.time_statistics whether to collect timing information or not. Collection of time statistics is enabled by default but only performed, if data collection as such has been enabled. Recording time statistics causes extra system calls. In most cases, the benefit of the monitoring outweights any potential performance penalty of the additional system calls.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_statistics=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries */
for ($i = 1; $i <= 4; $i++) {
  $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d",
     MYSQLND_QC_ENABLE_SWITCH,
     $i % 2);
  $res = $mysqli->query($query);
  $res->free();
}

var_dump(mysqlnd_qc_get_core_stats());
?>

Powyższe przykłady wyświetlą:

array(26) {
  ["cache_hit"]=>
  string(1) "2"
  ["cache_miss"]=>
  string(1) "2"
  ["cache_put"]=>
  string(1) "2"
  ["query_should_cache"]=>
  string(1) "4"
  ["query_should_not_cache"]=>
  string(1) "3"
  ["query_not_cached"]=>
  string(1) "3"
  ["query_could_cache"]=>
  string(1) "4"
  ["query_found_in_cache"]=>
  string(1) "2"
  ["query_uncached_other"]=>
  string(1) "0"
  ["query_uncached_no_table"]=>
  string(1) "0"
  ["query_uncached_no_result"]=>
  string(1) "0"
  ["query_uncached_use_result"]=>
  string(1) "0"
  ["query_aggr_run_time_cache_hit"]=>
  string(2) "28"
  ["query_aggr_run_time_cache_put"]=>
  string(3) "900"
  ["query_aggr_run_time_total"]=>
  string(3) "928"
  ["query_aggr_store_time_cache_hit"]=>
  string(2) "14"
  ["query_aggr_store_time_cache_put"]=>
  string(2) "40"
  ["query_aggr_store_time_total"]=>
  string(2) "54"
  ["receive_bytes_recorded"]=>
  string(3) "136"
  ["receive_bytes_replayed"]=>
  string(3) "136"
  ["send_bytes_recorded"]=>
  string(2) "84"
  ["send_bytes_replayed"]=>
  string(2) "84"
  ["slam_stale_refresh"]=>
  string(1) "0"
  ["slam_stale_hit"]=>
  string(1) "0"
  ["request_counter"]=>
  int(1)
  ["process_hash"]=>
  int(1929695233)
}

For a quick overview, call mysqlnd_qc_get_core_stats(). It delivers cache usage, cache timing and traffic related statistics. Values are aggregated on a per process basis for all queries issued by any PHP MySQL API call.

Some storage handler, such as the default handler, can report cache entries, statistics related to the entries and meta data for the underlying query through the mysqlnd_qc_get_cache_info() function. Please note, that the information returned depends on the storage handler. Values are aggregated on a per process basis.

mysqlnd_qc.enable_qc=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 1; $i <= 4; $i++) {
  $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d",
     MYSQLND_QC_ENABLE_SWITCH,
     $i % 2);
  $res = $mysqli->query($query);
  $res->free();
}
var_dump(mysqlnd_qc_get_cache_info());
?>

Powyższe przykłady wyświetlą:

array(4) {
  ["num_entries"]=>
  int(2)
  ["handler"]=>
  string(7) "default"
  ["handler_version"]=>
  string(5) "1.0.0"
  ["data"]=>
  array(2) {
    ["Localhost via UNIX socket
3306
root
test|/*qc=on*/SELECT id FROM test WHERE id = 1"]=>
    array(2) {
      ["statistics"]=>
      array(11) {
        ["rows"]=>
        int(1)
        ["stored_size"]=>
        int(71)
        ["cache_hits"]=>
        int(1)
        ["run_time"]=>
        int(391)
        ["store_time"]=>
        int(27)
        ["min_run_time"]=>
        int(16)
        ["max_run_time"]=>
        int(16)
        ["min_store_time"]=>
        int(8)
        ["max_store_time"]=>
        int(8)
        ["avg_run_time"]=>
        int(8)
        ["avg_store_time"]=>
        int(4)
      }
      ["metadata"]=>
      array(1) {
        [0]=>
        array(8) {
          ["name"]=>
          string(2) "id"
          ["orig_name"]=>
          string(2) "id"
          ["table"]=>
          string(4) "test"
          ["orig_table"]=>
          string(4) "test"
          ["db"]=>
          string(4) "test"
          ["max_length"]=>
          int(1)
          ["length"]=>
          int(11)
          ["type"]=>
          int(3)
        }
      }
    }
    ["Localhost via UNIX socket
3306
root
test|/*qc=on*/SELECT id FROM test WHERE id = 0"]=>
    array(2) {
      ["statistics"]=>
      array(11) {
        ["rows"]=>
        int(0)
        ["stored_size"]=>
        int(65)
        ["cache_hits"]=>
        int(1)
        ["run_time"]=>
        int(299)
        ["store_time"]=>
        int(13)
        ["min_run_time"]=>
        int(11)
        ["max_run_time"]=>
        int(11)
        ["min_store_time"]=>
        int(6)
        ["max_store_time"]=>
        int(6)
        ["avg_run_time"]=>
        int(5)
        ["avg_store_time"]=>
        int(3)
      }
      ["metadata"]=>
      array(1) {
        [0]=>
        array(8) {
          ["name"]=>
          string(2) "id"
          ["orig_name"]=>
          string(2) "id"
          ["table"]=>
          string(4) "test"
          ["orig_table"]=>
          string(4) "test"
          ["db"]=>
          string(4) "test"
          ["max_length"]=>
          int(0)
          ["length"]=>
          int(11)
          ["type"]=>
          int(3)
        }
      }
    }
  }
}

It is possible to further break down the granularity of statistics to the level of the normalized statement string. The normalized statement string is the statements string with all parameters replaced with question marks. For example, the two statements SELECT id FROM test WHERE id = 0 and SELECT id FROM test WHERE id = 1 are normalized into SELECT id FROM test WHERE id = ?. Their both statistics are aggregated into one entry for SELECT id FROM test WHERE id = ?.

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_normalized_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 1; $i <= 4; $i++) {
  $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d",
     MYSQLND_QC_ENABLE_SWITCH,
     $i % 2);
  $res = $mysqli->query($query);
  $res->free();
}
var_dump(mysqlnd_qc_get_normalized_query_trace_log());
?>

Powyższe przykłady wyświetlą:

array(4) {
  [0]=>
  array(9) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [1]=>
  array(9) {
    ["query"]=>
    string(27) "CREATE TABLE test (id INT )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [2]=>
  array(9) {
    ["query"]=>
    string(46) "INSERT INTO test (id ) VALUES (? ), (? ), (? )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [3]=>
  array(9) {
    ["query"]=>
    string(31) "SELECT id FROM test WHERE id =?"
    ["occurences"]=>
    int(4)
    ["eligible_for_caching"]=>
    bool(true)
    ["avg_run_time"]=>
    int(179)
    ["min_run_time"]=>
    int(11)
    ["max_run_time"]=>
    int(393)
    ["avg_store_time"]=>
    int(12)
    ["min_store_time"]=>
    int(7)
    ["max_store_time"]=>
    int(25)
  }
}

The source distribution of PECL/mysqlnd_qc contains a directory web/ in which web based monitoring scripts can be found which give an example how to write a cache monitor. Please, follow the instructions given in the source.

Since PECL/mysqlnd_qc 1.1.0 it is possible to write statistics into a log file. Please, see mysqlnd_qc.collect_statistics_log_file.

Finding cache candidates
Beyond TTL: user-defined storage
Quickstart and Examples


Beyond TTL: user-defined storage

The query cache plugin supports the use of user-defined storage handler. User-defined storage handler can use arbitrarily complex invalidation algorithms and support arbitrary storage media.

All user-defined storage handlers have to provide a certain interface. The functions of the user-defined storage handler will be called by the core of the cache plugin. The necessary interface consists of seven public functions. Both procedural and object oriented user-defined storage handler must implement the same set of functions.

Please check the example for details.

<?php
/* Enable default caching of all statements */
ini_set("mysqlnd_qc.cache_by_default", 1);

/* Procedural user defined storage handler functions */

$__cache = array();

function get_hash($host_info, $port, $user, $db, $query) {
  global $__cache;
  printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

  return md5(sprintf("%s%s%s%s%s", $host_info, $port, $user, $db, $query));
}

function find_query_in_cache($key) {
  global $__cache;
  printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

  if (isset($__cache[$key])) {
    $tmp = $__cache[$key];
    if ($tmp["valid_until"] < time()) {
      unset($__cache[$key]);
      $ret = NULL;
    } else {
      $ret = $__cache[$key]["data"];
    }
  } else {
    $ret = NULL;
  }

  return $ret;
}

function return_to_cache($key) {
  /*
     Called on cache hit after cached data has been processed,
     may be used for reference counting
  */
  printf("\t%s(%d)\n", __FUNCTION__, func_num_args());
}

function add_query_to_cache_if_not_exists($key, $data, $ttl, $run_time, $store_time, $row_count) {
  global $__cache;
  printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

  $__cache[$key] = array(
    "data"               => $data,
    "row_count"          => $row_count,
    "valid_until"        => time() + $ttl,
    "hits"               => 0,
    "run_time"           => $run_time,
    "store_time"         => $store_time,
    "cached_run_times"   => array(),
    "cached_store_times" => array(),
  );

  return TRUE;
}

function query_is_select($query) {
  printf("\t%s('%s'): ", __FUNCTION__, $query);

  $ret = FALSE;
  if (stristr($query, "SELECT") !== FALSE) {
    /* cache for 5 seconds */
    $ret = 5;
  }

  printf("%s\n", (FALSE === $ret) ? "FALSE" : $ret);
  return $ret;
}

function update_query_run_time_stats($key, $run_time, $store_time) {
  global $__cache;
  printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

  if (isset($__cache[$key])) {
    $__cache[$key]['hits']++;
    $__cache[$key]["cached_run_times"][] = $run_time;
    $__cache[$key]["cached_store_times"][] = $store_time;
  }
}

function get_stats($key = NULL) {
  global $__cache;
  printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

  if ($key && isset($__cache[$key])) {
    $stats = $__cache[$key];
  } else {
    $stats = array();
    foreach ($__cache as $key => $details) {
      $stats[$key] = array(
        'hits'              => $details['hits'],
        'bytes'             => strlen($details['data']),
        'uncached_run_time' => $details['run_time'],
        'cached_run_time'   => (count($details['cached_run_times']))
                                  ? array_sum($details['cached_run_times']) / count($details['cached_run_times'])
                                  : 0,
      );
    }
  }

  return $stats;
}

function clear_cache() {
  global $__cache;
  printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

  $__cache = array();
  return TRUE;
}

/* Install procedural user-defined storage handler */
if (!mysqlnd_qc_set_user_handlers("get_hash", "find_query_in_cache",
      "return_to_cache", "add_query_to_cache_if_not_exists",
      "query_is_select", "update_query_run_time_stats",
       "get_stats", "clear_cache")) {
  printf("Failed to install user-defined storage handler\n");
}

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

printf("\nCache put/cache miss\n");

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* Delete record to verify we get our data from the cache */
$mysqli->query("DELETE FROM test WHERE id = 1");

printf("\nCache hit\n");

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

printf("\nDisplay cache statistics\n");
var_dump(mysqlnd_qc_get_cache_info());

printf("\nFlushing cache, cache put/cache miss");
var_dump(mysqlnd_qc_clear_cache());

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>

Powyższe przykłady wyświetlą:

        query_is_select('DROP TABLE IF EXISTS test'): FALSE
        query_is_select('CREATE TABLE test(id INT)'): FALSE
        query_is_select('INSERT INTO test(id) VALUES (1), (2)'): FALSE

Cache put/cache miss
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        add_query_to_cache_if_not_exists(6)
array(1) {
  ["id"]=>
  string(1) "1"
}
        query_is_select('DELETE FROM test WHERE id = 1'): FALSE

Cache hit
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        return_to_cache(1)
        update_query_run_time_stats(3)
array(1) {
  ["id"]=>
  string(1) "1"
}

Display cache statistics
        get_stats(0)
array(4) {
  ["num_entries"]=>
  int(1)
  ["handler"]=>
  string(4) "user"
  ["handler_version"]=>
  string(5) "1.0.0"
  ["data"]=>
  array(1) {
    ["18683c177dc89bb352b29965d112fdaa"]=>
    array(4) {
      ["hits"]=>
      int(1)
      ["bytes"]=>
      int(71)
      ["uncached_run_time"]=>
      int(398)
      ["cached_run_time"]=>
      int(4)
    }
  }
}

Flushing cache, cache put/cache miss    clear_cache(0)
bool(true)
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        add_query_to_cache_if_not_exists(6)
NULL

Measuring cache efficiency
Instalacja/Konfiguracja
Quickstart and Examples


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
Beyond TTL: user-defined storage
Wymagania
mysqlnd_qc


Wymagania

PHP 5.3.3 or a newer version of PHP 5.3. PHP 5.4.0 support is in preparation.

PECL/mysqlnd_qc is a mysqlnd plugin. It plugs into the mysqlnd library. To use you plugin with a PHP MySQL extension (mysqli, mysql, PDO_MYSQL) it is necessary to enable use of the mysqlnd library by the PHP MySQL extension in question. Please refer to the extensions manual sections for details.

For using APC storage handler: APC 3.1.3p1-beta or newer.

For using MEMCACHE storage handler: libmemcache 0.38 or newer.

For using sqlite storage handler: sqlite3 bundled with PHP.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/mysqlnd_qc

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

mysqlnd_qc Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mysqlnd_qc.enable_qc | 1 | PHP_INI_SYSTEM |
mysqlnd_qc.ttl | 30 | PHP_INI_ALL |
mysqlnd_qc.cache_by_default | 0 | PHP_INI_ALL |
mysqlnd_qc.cache_no_table | 0 | PHP_INI_ALL |
mysqlnd_qc.use_request_time | 0 | PHP_INI_ALL |
mysqlnd_qc.time_statistics | 1 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics | 0 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics_log_file | /tmp/mysqlnd_qc.stats | PHP_INI_SYSTEM |
mysqlnd_qc.collect_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.query_trace_bt_depth | 3 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | PHP_INI_SYSTEM |
mysqlnd_qc.collect_normalized_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.std_data_copy | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.apc_prefix | qc_ | PHP_INI_ALL |
mysqlnd_qc.memc_server | 127.0.0.1 | PHP_INI_ALL |
mysqlnd_qc.memc_port | 11211 | PHP_INI_ALL |
mysqlnd_qc.sqlite_data_file | :memory: | PHP_INI_ALL |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

mysqlnd_qc.enable_qc integer

Enables or disables the plugin. If disabled the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

mysqlnd_qc.ttl integer

Default Time-to-Live (TTL) for cache entries in seconds.

mysqlnd_qc.cache_by_default integer

Cache all queries regardless if they begin with the SQL hint that enables caching of a query or not. Storage handler cannot overrule the setting. It is evaluated by the core of the plugin.

mysqlnd_qc.cache_no_table integer

Cache queries with no table name in any of columns meta data of their result set, e.g. SELECT SLEEP(1)?

mysqlnd_qc.use_request_time integer

Use PHP global request time to avoid gettimeofday() system calls? If using APC storage handler it should be set to the value of apc.use_request_time , if not warnings will be generated.

mysqlnd_qc.time_statistics integer

Collect run time and store time statistics using gettimeofday() system call? Data will be collected only if you also set mysqlnd_qc.collect_statistics = 1,

mysqlnd_qc.collect_statistics integer

Collect statistics for mysqlnd_qc_get_core_stats()? Does not influence storage handler statistics! Handler statistics can be an integral part of the handler internal storage format. Thereofore, collection of some handler statistics cannot be disabled.

mysqlnd_qc.collect_statistics-log-file integer

If mysqlnd_qc.collect_statistics and mysqlnd_qc.collect_statistics_log_file are set, the plugin will dump statistics into the specified log file at every 10th web request during PHP request shutdown. The log file needs to be writeable by the web server user.

Since 1.1.0.

mysqlnd_qc.collect_query_trace integer

Collect query back traces?

mysqlnd_qc.query_trace_bt_depth integer

Maximum depth/level of a query code backtrace.

mysqlnd_qc.slam_defense integer

Activates handler based slam defense if available. Supported by Default and APC storage handler

mysqlnd_qc.slam_defense_ttl integer

TTL for stale cache entries which are served while another client updates the entries. Supported by APC storage handler.

mysqlnd_qc.collect_normalized_query_trace integer

Collect aggregated normalized query traces? The setting has no effect by default. You compile the extension using the define NORM_QUERY_TRACE_LOG to make use of the setting.

mysqlnd_qc.std_data_copy integer

Default storage handler: copy cached wire data? EXPERIMENTAL – use default setting!

mysqlnd_qc.apc_prefix string

The APC storage handler stores data in the APC user cache. The setting sets a prefix to be used for cache entries.

mysqlnd_qc.memc_server string

MEMCACHE storage handler: memcache server host.

mysqlnd_qc.memc_port integer

MEMCACHE storage handler: memcached server port.

mysqlnd_qc.sqlite_data_file string

sqlite storage handler: data file. Any setting but :memory: may be of little practical value.

Instalacja
Stałe predefiniowane
Instalacja/Konfiguracja


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.

SQL hint related

The query cache is controled by SQL hints. SQL hints are used to enable and disable caching. SQL hints can be used to set the TTL of a query.

The SQL hints recognized by the query cache can be manually changed at compile time. This makes it possible to use mysqlnd_qc in environments in which the default SQL hints are already taken and interpreted by other systems. Therefore it is recommended to use the SQL hint string constants instead of manually adding the default SQL hints to the query string.

<?php
/* Use constants for maximum portability */
$query = "/*" . MYSQLND_QC_ENABLE_SWITCH . "*/SELECT id FROM test";

/* Valid but less portable: default TTL */
$query = "/*qc=on*/SELECT id FROM test";

/* Valid but less portable: per statement TTL */
$query = "/*qc=on*//*qc_ttl=5*/SELECT id FROM test";

printf("MYSQLND_QC_ENABLE_SWITCH: %s\n", MYSQLND_QC_ENABLE_SWITCH);
printf("MYSQLND_QC_DISABLE_SWITCH: %s\n", MYSQLND_QC_DISABLE_SWITCH);
printf("MYSQLND_QC_TTL_SWITCH: %s\n", MYSQLND_QC_TTL_SWITCH);
?>

Powyższe przykłady wyświetlą:

MYSQLND_QC_ENABLE_SWITCH: qc=on
MYSQLND_QC_DISABLE_SWITCH: qc=off
MYSQLND_QC_TTL_SWITCH: qc_ttl=

MYSQLND_QC_ENABLE_SWITCH ( string)
SQL hint used to enable caching of a query.
MYSQLND_QC_DISABLE_SWITCH ( string)
SQL hint used to disable caching of a query if mysqlnd_qc.cache_by_default = 1.
MYSQLND_QC_TTL_SWITCH ( string)
SQL hint used to set the TTL of a result set.

Konfiguracja wykonawcza
mysqlnd_qc Funkcje
mysqlnd_qc


mysqlnd_qc Funkcje

Spis treści

  • mysqlnd_qc_clear_cache — Flush all cache contents
  • mysqlnd_qc_get_available_handlers — Returns a list of available storage handler
  • mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available
  • mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache
  • mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache
  • mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache
  • mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached
  • mysqlnd_qc_set_storage_handler — Change current storage handler
  • mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler
Stałe predefiniowane
mysqlnd_qc_clear_cache
mysqlnd_qc


Flush all cache contents

mysqlnd_qc Funkcje
mysqlnd_qc_get_available_handlers
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_clear_cache

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

mysqlnd_qc_clear_cache — Flush all cache contents

Opis

bool mysqlnd_qc_clear_cache ( void )

Flush all cache contents.

Flushing the cache is a storage handler responsibility. All built-in storage handler but the memcache storage handler support flushing the cache. The memcache storage handler cannot flush its cache contents.

User-defined storage handler may or may not support the operation.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

A return value of FALSE indicates that flushing all cache contents has failed or the operation is not supported by the active storage handler. Applications must not expect that calling the function will always flush the cache.

mysqlnd_qc Funkcje
mysqlnd_qc_get_available_handlers
mysqlnd_qc Funkcje


Returns a list of available storage handler

mysqlnd_qc_clear_cache
mysqlnd_qc_get_cache_info
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_get_available_handlers

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

mysqlnd_qc_get_available_handlers — Returns a list of available storage handler

Opis

array mysqlnd_qc_get_available_handlers ( void )

Which storage are available depends on the compile time configuration of the query cache plugin. The default storage handler is always available. All other storage handler must be enabled explicitly when building the extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array of available built-in storage handler. For each storage handler the version number and version string is given.

Przykłady

<?php
var_dump(mysqlnd_qc_get_available_handlers());
?>

Powyższe przykłady wyświetlą:

array(5) {
  ["default"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["user"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["APC"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["MEMCACHE"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["sqlite"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
}

Zobacz też:

  • Installation
  • mysqlnd_qc_set_storage_handler() - Change current storage handler

mysqlnd_qc_clear_cache
mysqlnd_qc_get_cache_info
mysqlnd_qc Funkcje


Returns information on the current handler, the number of cache entries and cache entries, if available

mysqlnd_qc_get_available_handlers
mysqlnd_qc_get_core_stats
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_get_cache_info

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

mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available

Opis

array mysqlnd_qc_get_cache_info ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns information on the current handler, the number of cache entries and cache entries, if available. If and what data will be returned for the cache entries is subject to the active storage handler. Storage handler are free to return any data. Storage handler are recommended to return at least the data provided by the default handler, if technically possible.

The scope of the information is the PHP process. Dependng on the PHP deployment model a process may serve one or more web requests.

Values are aggregated for all cache activities on a per storage handler basis. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql.API calls have contributed to the aggregated data values. Use mysqlnd_qc_get_core_stats() to get timing data aggregated for all storage handlers.

Array of cache information

handler string

The active storage handler.

All storage handler. Since 1.0.0.

handler_version string

The version of the active storage handler.

All storage handler. Since 1.0.0.

num_entries int

The number of cache entries. The value depends on the storage handler in use.

The default, APC and SQLite storage handler provide the actual number of cache entries.

The MEMCACHE storage handler always returns 0. MEMCACHE does not support counting the number of cache entries.

If a user defined handler is used, the number of entries of the data property is reported.

Since 1.0.0.

data array

The version of the active storage handler.

Additional storage handler dependent data on the cache entries. Storage handler are requested to provide similar and comparable information. A user defined storage handler is free to return any data.

Since 1.0.0.

The following information is provided by the default storage handler for the data property.

The data property holds a hash. The hash is indexed by the internal cache entry itentifier of the storage handler. The cache entry identifier is human-readable and contains the query string leading to the cache entry. Please, see also the example below. The following data is given for every cache entry.

statistics array

Statistics of the cache entry.

Since 1.0.0.

Property | Description | Version
rows | Number of rows of the cached result set. | Since 1.0.0.
stored_size | The size of the cached result set in bytes. This is the size of the payload. The value is not suited for caclculating the total memory consumption of all cache entries including the administrative overhead of the cache entries. | Since 1.0.0.
cache_hits | How often the cached entry has been returned. | Since 1.0.0.
run_time | Run time of the statement to which the cache entry belongs. This is the run time of the uncached statement. It is the time between sending the statement to MySQL receiving a reply from MySQL. Run time saved by using the query cache plugin can be calculated like this: cache_hits * ((run_time - avg_run_time) + (store_time - avg_store_time)). | Since 1.0.0.
store_time | Store time of the statements result set to which the cache entry belongs. This is the time it took to fetch and store the results of the uncached statement. | Since 1.0.0.
min_run_time | Minimun run time of the cached statement. How long it took to find the statement in the cache. | Since 1.0.0.
min_store_time | Minimun store time of the cached statement. The time taken for fetching the cached result set from the storage medium and decoding | Since 1.0.0.
avg_run_time | Average run time of the cached statement. | Since 1.0.0.
avg_store_time | Average store time of the cached statement. | Since 1.0.0.
max_run_time | Average run time of the cached statement. | Since 1.0.0.
max_store_time | Average store time of the cached statement. | Since 1.0.0.
metadata array

Metadata of the cache entry. This is the metadata provided by MySQL together with the result set of the statement in question. Different versions of the MySQL server may return different metadata. Unlike with some of the PHP MySQL extensions no attempt is made to hide MySQL server version dependencies and version details from the caller. Please, refer to the MySQL C API documentation that belongs to the MySQL server in use for further details.

The metadata list contains one entry for every column.

Since 1.0.0.

Property | Description | Version
name | The field name. Depending on the MySQL version this may be the fields alias name. | Since 1.0.0.
org_name | The field name. | Since 1.0.0.
table | The table name. If an alias name was used for the table, this usually holds the alias name. | Since 1.0.0.
org_table | The table name. | Since 1.0.0.
db | The database/schema name. | Since 1.0.0.
max_length | The maximum width of the field. Details may vary by MySQL server version. | Since 1.0.0.
length | The width of the field. Details may vary by MySQL server version. | Since 1.0.0.
type | The data type of the field. Details may vary by the MySQL server in use. This is the MySQL C API type constants value. It is recommended to use type constants provided by the mysqli extension to test for its meaning. You should not test for certain type values by comparing with certain numbers. | Since 1.0.0.

The APC storage handler returns the same information for the data property but no metadata. The metadata of a cache entry is set to NULL.

The MEMCACHE storage handler does not fill the data property. Statistics are not available on a per cache entry basis with the MEMCACHE storage handler.

A user defined storage handler is free to provide any data.

Przykłady

The example shows the output from the built-in default storage handler. Other storage handler may report different data.

<?php
/* Populate the cache, e.g. using mysqli */
$mysqli = new mysqli("host", "user", "password", "schema");
$mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/SELECT id FROM test");

/* Display cache information */
var_dump(mysqlnd_qc_get_cache_info());
?>

Powyższe przykłady wyświetlą:

array(4) {
 ["num_entries"]=>
 int(1)
 ["handler"]=>
 string(7) "default"
 ["handler_version"]=>
 string(5) "1.0.0"
 ["data"]=>
 array(1) {
   ["Localhost via UNIX socket 3306 user schema|/*qc=on*/SELECT id FROM test"]=>
   array(2) {
     ["statistics"]=>
     array(11) {
       ["rows"]=>
       int(6)
       ["stored_size"]=>
       int(101)
       ["cache_hits"]=>
       int(0)
       ["run_time"]=>
       int(471)
       ["store_time"]=>
       int(27)
       ["min_run_time"]=>
       int(0)
       ["max_run_time"]=>
       int(0)
       ["min_store_time"]=>
       int(0)
       ["max_store_time"]=>
       int(0)
       ["avg_run_time"]=>
       int(0)
       ["avg_store_time"]=>
       int(0)
     }
     ["metadata"]=>
     array(1) {
       [0]=>
       array(8) {
         ["name"]=>
         string(2) "id"
         ["orig_name"]=>
         string(2) "id"
         ["table"]=>
         string(4) "test"
         ["orig_table"]=>
         string(4) "test"
         ["db"]=>
         string(4) "schema"
         ["max_length"]=>
         int(1)
         ["length"]=>
         int(11)
         ["type"]=>
         int(3)
       }
     }
   }
 }
}

Zobacz też:

  • mysqlnd_qc_get_core_stats() - Statistics collected by the core of the query cache

mysqlnd_qc_get_available_handlers
mysqlnd_qc_get_core_stats
mysqlnd_qc Funkcje


Statistics collected by the core of the query cache

mysqlnd_qc_get_cache_info
mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_get_core_stats

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

mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache

Opis

array mysqlnd_qc_get_core_stats ( void )

Returns an array of statistics collected by the core of the cache plugin. The same data fields will be reported for any storage handler because the data is collected by the core.

The PHP configuration setting mysqlnd_qc.collect_statistics controls the collection of statistics. The collection of statistics is disabled by default for performance reasons. Disabling the collection of statistics will also disable the collection of time related statistics.

The PHP configuration setting mysqlnd_qc.collect_time_statistics controls the collection of time related statistics.

The scope of the core statistics is the PHP process. Depending on your deployment model a PHP process may handle one or multiple requests.

Statistics are aggregated for all cache entries and all storage handler. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql API calls have contributed to the aggregated data values.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Array of core statistics

Statistic | Description | Version
cache_hit | Statement is considered cacheable and cached data has been reused. Statement is considered cacheable and a cache miss happened but the statement got cached by someone else while we process it and thus we can fetch the result from the refreshed cache. | Since 1.0.0.
cache_miss Statement is considered cacheable...

  • ... and has been added to the cache

  • ... but the PHP configuration directive setting of mysqlnd_qc.cache_no_table = 1 has prevented caching.

  • ... but an unbuffered result set is requested.

  • ... but a buffered result set was empty.

Since 1.0.0.
cache_put | Statement is considered cacheable and has been added to the cache. Take care when calculating derived statistics. Storage handler with a storage life time beyond process scope may report cache_put = 0 together with cache_hit > 0, if another process has filled the cache. You may want to use num_entries from mysqlnd_qc_get_cache_info() if the handler supports it ( default, APC). | Since 1.0.0.
query_should_cache | Statement is considered cacheable based on query string analysis. The statement may or may not be added to the cache. See also cache_put. | Since 1.0.0.
query_should_not_cache | Statement is considered not cacheable based on query string analysis. | Since 1.0.0.
query_not_cached | Statement is considered not cacheable or it is considered cachable but the storage handler has not returned a hash key for it. | Since 1.0.0.
query_could_cache Statement is considered cacheable...

  • ... and statement has been run without errors

  • ... and meta data shows at least one column in the result set

The statement may or may not be in the cache already. It may or may not be added to the cache later on. 		Since 1.0.0.
query_found_in_cache | Statement is considered cacheable and we have found it in the cache but we have not replayed the cached data yet and we have not send the result set to the client yet. This is not considered a cache hit because the client might not fetch the result or the cached data may be faulty. | Since 1.0.0.
query_uncached_other | Statement is considered cacheable and it may or may not be in the cache already but either replaying cached data has failed, no result set is available or some other error has happened.
query_uncached_no_table | Statement has not been cached because the result set has at least one column which has no table name in its meta data. An example of such a query is SELECT SLEEP(1). To cache those statements you have to change default value of the PHP configuration directive mysqlnd_qc.cache_no_table and set mysqlnd_qc.cache_no_table = 1. Often, it is not desired to cache such statements. | Since 1.0.0.
query_uncached_use_result | Statement would have been cached if a buffered result set had been used. The situation is also consiered as a cache miss and cache_miss will be incremented as well. | Since 1.0.0.
query_aggr_run_time_cache_hit | Aggregated run time (ms) of all cached queries. Cached queries are those which have incremented cache_hit. | Since 1.0.0.
query_aggr_run_time_cache_put | Aggregated run time (ms) of all uncached queries that have been put into the cache. See also cache_put. | Since 1.0.0.
query_aggr_run_time_total | Aggregated run time (ms) of all uncached and cached queries that have been inspected and executed by the query cache. | Since 1.0.0.
query_aggr_store_time_cache_hit | Aggregated store time (ms) of all cached queries. Cached queries are those which have incremented cache_hit. | Since 1.0.0.
query_aggr_store_time_cache_put | Aggregated store time ( ms) of all uncached queries that have been put into the cache. See also cache_put. | Since 1.0.0.
query_aggr_store_time_total | Aggregated store time (ms) of all uncached and cached queries that have been inspected and executed by the query cache. | Since 1.0.0.
receive_bytes_recorded | Recorded incoming network traffic ( bytes) send from MySQL to PHP. The traffic may or may not have been added to the cache. The traffic is the total for all queries regardless if cached or not. | Since 1.0.0.
receive_bytes_replayed | Network traffic replayed during cache. This is the total amount of incoming traffic saved because of the usage of the query cache plugin. | Since 1.0.0.
send_bytes_recorded | Recorded outgoing network traffic ( bytes) send from MySQL to PHP. The traffic may or may not have been added to the cache. The traffic is the total for all queries regardless if cached or not. | Since 1.0.0.
send_bytes_replayed | Network traffic replayed during cache. This is the total amount of outgoing traffic saved because of the usage of the query cache plugin. | Since 1.0.0.
slam_stale_refresh | Number of cache misses which triggered serving stale data until the client causing the cache miss has refreshed the cache entry. | Since 1.0.0.
slam_stale_hit | Number of cache hits while a stale cache entry gets refreshed. | Since 1.0.0.

Przykłady

<?php
/* Enable collection of statistics - default: disabled */
ini_set("mysqlnd_qc.collect_statistics", 1);

/* Enable collection of all timing related statistics -
default: enabled but overruled by mysqlnd_qc.collect_statistics = 0 */
ini_set("mysqlnd_qc.collect_time_statistics", 1);

/* Populate the cache, e.g. using mysqli */
$mysqli = new mysqli('host', 'user', 'password', 'schema');

/* Cache miss and cache put */
$mysqli->query("/*qc=on*/SELECT id FROM test");
/* Cache hit */
$mysqli->query("/*qc=on*/SELECT id FROM test");

/* Display core statstics */
var_dump(mysqlnd_qc_get_core_stats());
?>

Powyższe przykłady wyświetlą:

array(26) {
  ["cache_hit"]=>
  string(1) "1"
  ["cache_miss"]=>
  string(1) "1"
  ["cache_put"]=>
  string(1) "1"
  ["query_should_cache"]=>
  string(1) "2"
  ["query_should_not_cache"]=>
  string(1) "0"
  ["query_not_cached"]=>
  string(1) "0"
  ["query_could_cache"]=>
  string(1) "2"
  ["query_found_in_cache"]=>
  string(1) "1"
  ["query_uncached_other"]=>
  string(1) "0"
  ["query_uncached_no_table"]=>
  string(1) "0"
  ["query_uncached_no_result"]=>
  string(1) "0"
  ["query_uncached_use_result"]=>
  string(1) "0"
  ["query_aggr_run_time_cache_hit"]=>
  string(1) "4"
  ["query_aggr_run_time_cache_put"]=>
  string(3) "395"
  ["query_aggr_run_time_total"]=>
  string(3) "399"
  ["query_aggr_store_time_cache_hit"]=>
  string(1) "2"
  ["query_aggr_store_time_cache_put"]=>
  string(1) "8"
  ["query_aggr_store_time_total"]=>
  string(2) "10"
  ["receive_bytes_recorded"]=>
  string(2) "65"
  ["receive_bytes_replayed"]=>
  string(2) "65"
  ["send_bytes_recorded"]=>
  string(2) "29"
  ["send_bytes_replayed"]=>
  string(2) "29"
  ["slam_stale_refresh"]=>
  string(1) "0"
  ["slam_stale_hit"]=>
  string(1) "0"
  ["request_counter"]=>
  int(1)
  ["process_hash"]=>
  int(3547549858)
}

Zobacz też:

  • Runtime configuration
  • mysqlnd_qc.collect_statistics
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc_get_cache_info() - Returns information on the current handler, the number of cache entries and cache entries, if available

mysqlnd_qc_get_cache_info
mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc Funkcje


Returns a normalized query trace log for each query inspected by the query cache

mysqlnd_qc_get_core_stats
mysqlnd_qc_get_query_trace_log
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_get_normalized_query_trace_log

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

mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache

Opis

array mysqlnd_qc_get_normalized_query_trace_log ( void )

Returns a normalized query trace log for each query inspected by the query cache. The collection of the trace log is disabled by default. To collect the trace log you have to set the PHP configuration directive mysqlnd_qc.collect_normalized_query_trace to 1

Entries in the trace log are grouped by the normalized query statement. The normalized query statement is the query statement with all statement parameter values being replaced with a question mark. For example, the two statements SELECT id FROM test WHERE id = 1 and SELECT id FROM test WHERE id = 2 are normalized as SELECT id FROM test WHERE id = ?. Whenever a statement is inspected by the query cache which matches the normalized statement pattern, its statistics are grouped by the normalized statement string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of query log. Every list entry contains the normalized query stringand further detail information.

Key | Description
query | Normalized statement string.
occurences | How many statements have matched the normalized statement string in addition to the one which has created the log entry. The value is zero if a statement has been normalized, its normalized representation has been added to the log but no further queries inspected by PECL/mysqlnd_qc have the same normalized statement string.
eligible_for_caching | Whether the statement could be cached. An statement eligible for caching has not necessarily been cached. It not possible to tell for sure if or how many cached statement have contributed to the aggregated normalized statement log entry. However, comparing the minimum and average run time one can make an educated guess.
avg_run_time | The average run time of all queries contributing to the query log entry. The run time is the time between sending the query statement to MySQL and receiving an answer from MySQL.
avg_store_time | The average store time of all queries contributing to the query log entry. The store time is the time needed to fetch a statements result set from the server to the client and, storing it on the client.
min_run_time | The minimum run time of all queries contributing to the query log entry.
min_store_time | The minimum store time of all queries contributing to the query log entry.
max_run_time | The maximum run time of all queries contributing to the query log entry.
max_store_time | The maximum store time of all queries contributing to the query log entry.

Przykłady

mysqlnd_qc.collect_normalized_query_trace=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* not cached */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* cache put */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

/* cache hit */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

var_dump(mysqlnd_qc_get_normalized_query_trace_log());
?>

Powyższe przykłady wyświetlą:

array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(4) {
  [0]=>
  array(9) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [1]=>
  array(9) {
    ["query"]=>
    string(27) "CREATE TABLE test (id INT )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [2]=>
  array(9) {
    ["query"]=>
    string(40) "INSERT INTO test (id ) VALUES (? ), (? )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [3]=>
  array(9) {
    ["query"]=>
    string(31) "SELECT id FROM test WHERE id =?"
    ["occurences"]=>
    int(2)
    ["eligible_for_caching"]=>
    bool(true)
    ["avg_run_time"]=>
    int(159)
    ["min_run_time"]=>
    int(12)
    ["max_run_time"]=>
    int(307)
    ["avg_store_time"]=>
    int(10)
    ["min_store_time"]=>
    int(8)
    ["max_store_time"]=>
    int(13)
  }
}

Zobacz też:

  • Runtime configuration
  • mysqlnd_qc.collect_normalized_query_trace
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc_get_query_trace_log() - Returns a backtrace for each query inspected by the query cache

mysqlnd_qc_get_core_stats
mysqlnd_qc_get_query_trace_log
mysqlnd_qc Funkcje


Returns a backtrace for each query inspected by the query cache

mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc_set_is_select
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_get_query_trace_log

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

mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache

Opis

array mysqlnd_qc_get_query_trace_log ( void )

Returns a backtrace for each query inspected by the query cache. The collection of the backtrace is disabled by default. To collect the backtrace you have to set the PHP configuration directive mysqlnd_qc.collect_query_trace to 1

The maximum depth of the backtrace is limited to the depth set with the PHP configuration directive mysqlnd_qc.query_trace_bt_depth.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of query backtrace. Every list entry contains the query string, a backtrace and further detail information.

Key | Description
query | Query string.
origin | Code backtrace.
run_time | Query run time in milliseconds. The collection of all times and the necessary gettimeofday system calls can be disabled by setting the PHP configuration directive mysqlnd_qc.time_statistics to 0
store_time | Query result set store time in milliseconds. The collection of all times and the necessary gettimeofday system calls can be disabled by setting the PHP configuration directive mysqlnd_qc.time_statistics to 0
eligible_for_caching | TRUE if query is cacheble otherwise FALSE.
no_table | TRUE if the query has generated a result set and at least one column from the result set has no table name set in its metadata. This is usually the case with queries which one probably do not want to cache such as SELECT SLEEP(1). By default any such query will not be added to the cache. See also PHP configuration directive mysqlnd_qc.cache_no_table.
was_added | TRUE if the query result has been put into the cache, otherwise FALSE.
was_already_in_cache | TRUE if the query result would have been added to the cache if it was not already in the cache (cache hit). Otherwise FALSE.

Przykłady

mysqlnd_qc.collect_query_trace=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* not cached */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* cache put */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

/* cache hit */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

var_dump(mysqlnd_qc_get_query_trace_log());
?>

Powyższe przykłady wyświetlą:

array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(6) {
  [0]=>
  array(8) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["origin"]=>
    string(102) "#0 qc.php(4): mysqli->query('DROP TABLE IF E...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [1]=>
  array(8) {
    ["query"]=>
    string(25) "CREATE TABLE test(id INT)"
    ["origin"]=>
    string(102) "#0 qc.php(5): mysqli->query('CREATE TABLE te...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [2]=>
  array(8) {
    ["query"]=>
    string(36) "INSERT INTO test(id) VALUES (1), (2)"
    ["origin"]=>
    string(102) "#0 qc.php(6): mysqli->query('INSERT INTO tes...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [3]=>
  array(8) {
    ["query"]=>
    string(32) "SELECT id FROM test WHERE id = 1"
    ["origin"]=>
    string(102) "#0 qc.php(9): mysqli->query('SELECT id FROM ...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(25)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [4]=>
  array(8) {
    ["query"]=>
    string(41) "/*qc=on*/SELECT id FROM test WHERE id = 2"
    ["origin"]=>
    string(103) "#0 qc.php(14): mysqli->query('/*qc=on*/SELECT...')
#1 {main}"
    ["run_time"]=>
    int(311)
    ["store_time"]=>
    int(13)
    ["eligible_for_caching"]=>
    bool(true)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(true)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [5]=>
  array(8) {
    ["query"]=>
    string(41) "/*qc=on*/SELECT id FROM test WHERE id = 2"
    ["origin"]=>
    string(103) "#0 qc.php(19): mysqli->query('/*qc=on*/SELECT...')
#1 {main}"
    ["run_time"]=>
    int(13)
    ["store_time"]=>
    int(8)
    ["eligible_for_caching"]=>
    bool(true)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(true)
  }
}

Zobacz też:

  • Runtime configuration
  • mysqlnd_qc.collect_query_trace
  • mysqlnd_qc.query_trace_bt_depth
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc.cache_no_table
  • mysqlnd_qc_get_normalized_query_trace_log() - Returns a normalized query trace log for each query inspected by the query cache

mysqlnd_qc_get_normalized_query_trace_log
mysqlnd_qc_set_is_select
mysqlnd_qc Funkcje


Installs a callback which decides whether a statement is cached

mysqlnd_qc_get_query_trace_log
mysqlnd_qc_set_storage_handler
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_set_is_select

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

mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached

Opis

mixed mysqlnd_qc_set_is_select ( string $callback )

Installs a callback which decides whether a statement is cached.

There are several ways of hinting PELC/mysqlnd_qc to cache a query. By default, PECL/mysqlnd_qc attempts to cache a if caching of all statements is enabled or the query string begins with a certain SQL hint. The plugin internally calls a function named is_select() to find out. This internal function can be replaced with a user-defined callback. Then, the user-defined callback is responsible to decide whether the plugin attempts to cache a statement. Because the internal function is replaced with the callback, the callback gains full control. The callback is free to ignore the configuration setting mysqlnd_qc.cache_by_default and SQL hints.

The callback is invoked for every statement inspected by the plugin. It is given the statements string as a parameter. The callback returns FALSE if the statement shall not be cached. It returns TRUE to make the plugin attempt to cache the statements result set, if any. A so-created cache entry is given the default TTL set with the PHP configuration directive mysqlnd_qc.ttl. If a different TTL shall be used, the callback returns a numeric value to be used as the TTL.

The internal is_select function is part of the internal cache storage handler interface. Thus, a user-defined storage handler offers the same capabilities.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

<?php
/* callback which decides if query is cached */
function is_select($query) {
  static $patterns = array(
   /* true - use default from mysqlnd_qc.ttl */
   "@SELECT\s+.*\s+FROM\s+test@ismU" => true,
   /* 3 - use TTL = 3 seconds */
   "@SELECT\s+.*\s+FROM\s+news@ismU" => 3
  );
  /* check if query does match pattern */
  foreach ($patterns as $pattern => $ttl) {
    if (preg_match($pattern, $query)) {
      printf("is_select(%45s): cache\n", $query);
      return $ttl;
    }
  }
  printf("is_select(%45s): do not cache\n", $query);
  return false;
}
mysqlnd_qc_set_is_select("is_select");

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* cache put */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache hit */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache put */
$mysqli->query("SELECT * FROM test");
?>

Powyższe przykłady wyświetlą:

is_select(                    DROP TABLE IF EXISTS test): do not cache
is_select(                    CREATE TABLE test(id INT)): do not cache
is_select(    INSERT INTO test(id) VALUES (1), (2), (3)): do not cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(                           SELECT * FROM test): cache

Zobacz też:

  • Runtime configuration
  • mysqlnd_qc.ttl
  • mysqlnd_qc.cache_by_default
  • mysqlnd_qc_set_user_handlers() - Sets the callback functions for a user-defined procedural storage handler

mysqlnd_qc_get_query_trace_log
mysqlnd_qc_set_storage_handler
mysqlnd_qc Funkcje


Change current storage handler

mysqlnd_qc_set_is_select
mysqlnd_qc_set_user_handlers
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_set_storage_handler

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

mysqlnd_qc_set_storage_handler — Change current storage handler

Opis

bool mysqlnd_qc_set_storage_handler ( string $handler )

Sets the storage handler used by the query cache. A list of available storage handler can be obtained from mysqlnd_qc_get_available_handlers(). Which storage are available depends on the compile time configuration of the query cache plugin. The default storage handler is always available. All other storage handler must be enabled explicitly when building the extension.

Parametry

handler

Handler can be of type string representing the name of a built-in storage handler or an object of type mysqlnd_qc_handler_default. The names of the built-in storage handler are default, APC, MEMCACHE, sqlite.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

If changing the storage handler fails a catchable fatal error will be thrown. The query cache cannot operate if the previous storage handler has been shutdown but no new storage handler has been installed.

Przykłady

The example shows the output from the built-in default storage handler. Other storage handler may report different data.

<?php
var_dump(mysqlnd_qc_set_storage_handler("memcache"));

if (true === mysqlnd_qc_set_storage_handler("default"))
  printf("Default storage handler activated");

/* Catchable fatal error */
var_dump(mysqlnd_qc_set_storage_handler("unknown"));
?>

Powyższe przykłady wyświetlą:

bool(true)
Default storage handler activated
Catchable fatal error: mysqlnd_qc_set_storage_handler(): Unknown handler 'unknown' in (file) on line (line)

Zobacz też:

  • Installation
  • mysqlnd_qc_get_available_handlers() - Returns a list of available storage handler

mysqlnd_qc_set_is_select
mysqlnd_qc_set_user_handlers
mysqlnd_qc Funkcje


Sets the callback functions for a user-defined procedural storage handler

mysqlnd_qc_set_storage_handler
Change History
mysqlnd_qc Funkcje
PHP Manual

mysqlnd_qc_set_user_handlers

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

mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler

Opis

bool mysqlnd_qc_set_user_handlers ( string $get_hash , string $find_query_in_cache , string $return_to_cache , string $add_query_to_cache_if_not_exists , string $query_is_select , string $update_query_run_time_stats , string $get_stats , string $clear_cache )

Sets the callback functions for a user-defined procedural storage handler.

Parametry

get_hash

Name of the user function implementing the storage handler get_hash functionality.

find_query_in_cache

Name of the user function implementing the storage handler find_in_cache functionality.

return_to_cache

Name of the user function implementing the storage handler return_to_cache functionality.

add_query_to_cache_if_not_exists

Name of the user function implementing the storage handler add_query_to_cache_if_not_exists functionality.

query_is_select

Name of the user function implementing the storage handler query_is_select functionality.

update_query_run_time_stats

Name of the user function implementing the storage handler update_query_run_time_stats functionality.

get_stats

Name of the user function implementing the storage handler get_stats functionality.

clear_cache

Name of the user function implementing the storage handler clear_cache functionality.

Zwracane wartości

Returns TRUE on success or FALSE on FAILURE.

Zobacz też:

  • Procedural user-defined storage handler example

mysqlnd_qc_set_storage_handler
Change History
mysqlnd_qc Funkcje


Change History

Spis treści

  • PECL/mysqlnd_qc 1.1 series
  • PECL/mysqlnd_qc 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.

mysqlnd_qc_set_user_handlers
PECL/mysqlnd_qc 1.1 series
mysqlnd_qc


PECL/mysqlnd_qc 1.1 series

1.1.0

  • Release date: under development
  • Motto/theme: PHP 5.4 compatbility

Feature changes

  • APC storage handler update

    • Fix build for APC 3.1.9+
    • Note: Use of the APC storage handler is currently not recommended due to stability issues of APC itself.

  • New PHP configuration directive

    • mysqlnd_qc.collect_statistics_log_file

Change History
PECL/mysqlnd_qc 1.0 series
Change History


PECL/mysqlnd_qc 1.0 series

1.0.1-stable

  • Release date: 12/2010
  • Motto/theme: Prepared statement support

Added support for Prepared statements and unbuffered queries.

1.0.0-beta

  • Release date: 07/2010
  • Motto/theme: TTL-based cache with various storage options (Memcache, APC, SQLite, user-defined)

Initial public release of the transparent TTL-based query result cache. Flexible storage of cached results. Various storage media supported.

PECL/mysqlnd_qc 1.1 series
mysqlnd_uh
Change History


Mysqlnd user handler plugin

  • Wstęp
  • Quickstart and Examples
    • Setup
    • How it works
    • Installing a proxy
    • Basic query monitoring
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • MysqlndUhConnection — The MysqlndUhConnection class
    • MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection
    • MysqlndUhConnection::charsetName — Returns the default character set for the database connection
    • MysqlndUhConnection::close — Closes a previously opened database connection
    • MysqlndUhConnection::connect — Open a new connection to the MySQL server
    • MysqlndUhConnection::__construct — The __construct purpose
    • MysqlndUhConnection::endPSession — End a persistent connection
    • MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation
    • MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call
    • MysqlndUhConnection::getErrorString — Returns a string description of the last error
    • MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query
    • MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used
    • MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query.
    • MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query
    • MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used
    • MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server
    • MysqlndUhConnection::getServerStatistics — Gets the current system status
    • MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer
    • MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation
    • MysqlndUhConnection::getStatistics — Returns statistics about the client connection.
    • MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection
    • MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link
    • MysqlndUhConnection::init — Initialize mysqlnd connection
    • MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread
    • MysqlndUhConnection::listFields — List MySQL table fields
    • MysqlndUhConnection::listMethod — Wrapper for assorted list commands
    • MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query
    • MysqlndUhConnection::nextResult — Prepare next result from multi_query
    • MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • MysqlndUhConnection::query — Performs a query on the database
    • MysqlndUhConnection::queryReadResultsetHeader — Read a result set header
    • MysqlndUhConnection::reapQuery — Get result from async query
    • MysqlndUhConnection::refreshServer — Flush or reset tables and caches
    • MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection
    • MysqlndUhConnection::selectDb — Selects the default database for database queries
    • MysqlndUhConnection::sendClose — Sends a close command to MySQL
    • MysqlndUhConnection::sendQuery — Sends a query to MySQL
    • MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server
    • MysqlndUhConnection::setAutocommit — Turns on or off auto-commiting database modifications
    • MysqlndUhConnection::setCharset — Sets the default client character set
    • MysqlndUhConnection::setClientOption — Sets a client option
    • MysqlndUhConnection::setServerOption — Sets a server option
    • MysqlndUhConnection::shutdownServer — The shutdownServer purpose
    • MysqlndUhConnection::simpleCommand — Sends a basic COM_* command
    • MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client
    • MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL
    • MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare
    • MysqlndUhConnection::storeResult — Transfers a result set from the last query
    • MysqlndUhConnection::txCommit — Commits the current transaction
    • MysqlndUhConnection::txRollback — Rolls back current transaction
    • MysqlndUhConnection::useResult — Initiate a result set retrieval
  • MysqlndUhPreparedStatement — The MysqlndUhPreparedStatement class
    • MysqlndUhPreparedStatement::__construct — The __construct purpose
    • MysqlndUhPreparedStatement::execute — Executes a prepared Query
    • MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution
  • Mysqlnd_uh Funkcje
    • mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle
    • mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections
    • mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements
  • Change History
    • PECL/mysqlnd_uh 1.0 series
PECL/mysqlnd_qc 1.0 series
Wstęp
MySQL


Wstęp

The mysqlnd user handler plugin (mysqlnd_uh) allows users to set hooks for most internal calls of the MySQL native driver for PHP (mysqlnd). Mysqlnd and its plugins, including PECL/mysqlnd_uh, operate on a layer beneath the PHP MySQL extensions. A mysqlnd plugin can be considered as a proxy between the PHP MySQL extensions and the MySQL server as part of the PHP executable on the client-side. Because the plugins operates on their own layer below the PHP MySQL extensions, they can monitor and change application actions without requiring application changes. If the PHP MySQL extensions (mysqli, mysql, PDO_MYSQL) are compiled to use mysqlnd this can be used for:

  • Monitoring

    • Queries run by any of the PHP MySQL extensions

    • Prepared statements run by any of the PHP MySQL extensions

  • Auditing

    • Detection of databases uses

    • SQL Injection protection using black-/whitelists

  • Assorted

    • Load Balancing connections

As of version PHP 5.3.3 the MySQL native driver for PHP (mysqlnd) features an internal plugin C API. C plugins, such as the mysqlnd user handler plugin, can extend the functionality of mysqlnd. PECL/mysqlnd_uh makes parts of the internal plugin C API available to the PHP user for plugin development with PHP.

The MySQL native driver for PHP is a C library which ships together with PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL Client Library (AKA libmysql/libmysqlclient). As of PHP 5.4.0, mysqlnd is the compile time default library used by all PHP MySQL extensions.

Security considerations

PECL/mysqlnd_uh gives users access to MySQL user names, MySQL password used by any of the PHP MySQL extensions to connect to MySQL. It allows monitoring of all queries and prepared statements exposing the statement string to the user. Therefore, the extension should be installed with care. The PHP_INI_SYSTEM configuration setting mysqlnd_uh.enable can be used to prevent users from hooking mysqlnd calls.

Code obfuscators and similar technologies are not suitable to prevent monitoring of mysqlnd library activities if PECL/mysqlnd_uh is made available and the user can install a proxy, for example, using auto_prepend_file.

Documentation note

Many of the extensions functions are described very briefly. This is done intentionally to avoid content duplication. The mysqli extension is often only a thin abstraction layer on top of the MySQL C API, which the mysqlnd library provides. Therefore, the corresponding mysqli documentation respectively the MySQL reference manual can be consulted to get more information on a particular function.

On the name

The shortcut mysqlnd_uh stands for mysqlnd user handler. There may be better names. However, this was the initial choice when development started. Meanwhile, non speaking names have almost become a tradition.

Informacja:

The mysqlnd user handler plugin is in alpha status. Take appropriate care before using it in production environments.

mysqlnd_uh
Quickstart and Examples
mysqlnd_uh


Quickstart and Examples

Spis treści

  • Setup
  • How it works
  • Installing a proxy
  • Basic query monitoring

The mysqlnd user handler plugin can be understood as a client-side proxy for all PHP MySQL extensions (mysqli, mysql, PDO_MYSQL), if they are compiled to use the mysqlnd library. The extensions use the mysqlnd library internally, at the C level, to communicate with the MySQL server. PECL/mysqlnd_uh allows it to hook many mysqlnd calls. Therefore, most activities of the PHP MySQL extensions can be monitored.

Because monitoring happens at the level of the library, at a layer below the application, it is possible to monitor applications without changing them.

On the C level, the mysqlnd library is structured in modules or classes. The extension hooks almost all methods of the mysqlnd internal connection class and exposes them through the user space class MysqlndUhConnection. Some few methods of the mysqlnd internal statement class are made available to the PHP user with the class MysqlndUhPreparedStatement. By subclassing the classes MysqlndUhConnection and MysqlndUhPreparedStatement users get access to mysqlnd internal function calls.

Informacja:

None of the mysqlnd internal function calls has been designed to ever by exposed to the PHP user. Manipulating their activities may cause PHP to crash or leak memory. Often, this is not considered a bug. Please, keep in mind that you are accessing C library functions through PHP which are expected to take certain actions, which you may not be able to emulate in user space. Therefore, it is strongly recommended to always call the parent method implementation when subclassing MysqlndUhConnection or MysqlndUhPreparedStatement. To prevent the worst case, the extension performs some sanity checks. Please, see also Mysqlnd_uh Opcje konfiguracyjne.

Wstęp
Setup
mysqlnd_uh


Setup

The plugin is implemented as a PHP extension. Please, follow the installation instructions to install the » PECL/mysqlnd_uh extension. Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_uh.enable. The below example shows the default settings of the extension.

Przykład #1 Enabling the plugin (php.ini)

mysqlnd_uh.enable=1
mysqlnd_uh.report_wrong_types=1

Quickstart and Examples
How it works
Quickstart and Examples


How it works

Informacja:

You can skip the following and move on to the examples for now, if you are not interested in the inner workings. Please, get back to the background information and read it carefully, if you plan to use PECL/mysqlnd_uh intensively in the future.

Two classes are provided by the extension: MysqlndUhConnection and MysqlndUhPreparedStatement. The first one lets you access almost all methods of the mysqlnd internal connection class. The latter exposes some, selected methods of the mysqlnd internal statement class. For example, MysqlndUhConnection::connect() maps to the mysqlnd library C function mysqlnd_conn__connect.

As a mysqlnd plugin, the PECL/mysqlnd_uh extensions replaces mysqlnd library C functions with its own functions. Whenever a PHP MySQL extension compiled to use mysqlnd, calls a mysqlnd function, the functions installed by the plugin are executed instead of the original mysqlnd ones. If, for example, mysqli_connect() invokes mysqlnd_conn__connect, the connect function installed by PECL/mysqlnd_uh will be called. The functions installed by PECL/mysqlnd_uh are the methods of the built-in classes.

The built-in PHP classes and their methods do nothing but call their mysqlnd C library counterparts, to behave exaclty like the original mysqlnd function they replace. The code below illustrates in pseudo-code what the extension does.

Przykład #1 Pseudo-code: what a built-in class does

class MysqlndUhConnection {
  public function connect(($conn, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
    MYSQLND* c_mysqlnd_connection = convert_from_php_to_c($conn);
    ...
    return call_c_function(mysqlnd_conn__connect(c_mysqlnd_connection, ...));
  }
}

The build-in classes behave like a transparent proxy. It is possible for you to replace the proxy with your own. This is done by subclassing MysqlndUhConnection or MysqlndUhPreparedStatement to extend the functionality of the proxy, followed by registering a new proxy object. Proxy objects are installed by mysqlnd_uh_set_connection_proxy() and mysqlnd_uh_set_statement_proxy().

Przykład #2 Installing a proxy

<?php
class proxy extends MysqlndUhConnection {
 public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

Powyższy przykład wyświetli:

proxy::connect(array (
  0 => NULL,
  1 => 'localhost',
  2 => 'root',
  3 => '',
  4 => 'test',
  5 => 3306,
  6 => NULL,
  7 => 131072,
))
proxy::connect returns true

Setup
Installing a proxy
Quickstart and Examples


Installing a proxy

The extension provides two built-in classes: MysqlndUhConnection and MysqlndUhPreparedStatement. The classes are used for hooking mysqlnd library calls. Their methods correspond to mysqlnd internal functions. By default they act like a transparent proxy and do nothing but call their mysqlnd counterparts. By subclassing the classes you can install your own proxy to monitor mysqlnd.

Please, see How it works for details. However, to get started you do not need to look at the details. Copy the patterns shown in the quickstart instead.

Connections proxies are objects of the type MysqlndUhConnection. Connection proxy objects are installed by mysqlnd_uh_set_connection_proxy(). If you install the built-in class MysqlndUhConnection as a proxy, nothing happens. It behaves like a transparent proxy.

Przykład #1 Proxy registration, mysqlnd_uh.enable=1

<?php
mysqlnd_uh_set_connection_proxy(new MysqlndUhConnection());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

The PHP_INI_SYSTEM configuration setting mysqlnd_uh.enable setting controls whether a proxy may be set. If disabled, the extension will throw errors of type E_WARNING

Przykład #2 Proxy installation disabled

mysqlnd_uh.enable=0
<?php
mysqlnd_uh_set_connection_proxy(new MysqlndUhConnection());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

Powyższy przykład wyświetli:

PHP Warning:  MysqlndUhConnection::__construct(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enabled = false.  You must not use any of the base classes in %s on line %d
PHP Warning:  mysqlnd_uh_set_connection_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed  in %s on line %d

To monitor mysqlnd you have to write your own proxy object subclassing MysqlndUhConnection. Please, see the function reference for a the list of methods that can be subclassed. Alternatively, you can use reflection to inspect the built-in MysqlndUhConnection.

Create a new class proxy. Derive it from the built-in class MysqlndUhConnection. Replace the MysqlndUhConnection::connect(). method. Print out the host parameter value passed to the method. Make sure that you call the parent implementation of the connect method. Failing to do so may give unexpected and undesired results, including memory leaks and crashes.

Register your proxy and open three connections using the PHP MySQL extensions mysqli, mysql, PDO_MYSQL. If the extensions have been compiled to use the mysqlnd library, the proxy::connect method will be called three times, once for each connection opened.

Przykład #3 Connection proxy

<?php
class proxy extends MysqlndUhConnection {
  public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("Connection opened to '%s'\n", $host);
   /* Always call the parent implementation! */
   return parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
  }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysql = mysql_connect("localhost", "root", "");
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
?>

Powyższy przykład wyświetli:

Connection opened to 'localhost'
Connection opened to 'localhost'
Connection opened to 'localhost'

The use of prepared statement proxies follows the same pattern: create a proxy object of the type MysqlndUhPreparedStatement and install the proxy using mysqlnd_uh_set_statement_proxy().

Przykład #4 Prepared statement proxy

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  printf("%s(%s)\n", __METHOD__, $query);
  return parent::prepare($res, $query);
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'mysqlnd hacking made easy' AS _msg FROM DUAL");
?>

Powyższy przykład wyświetli:

stmt_proxy::prepare(SELECT 'mysqlnd hacking made easy' AS _msg FROM DUAL)

How it works
Basic query monitoring
Quickstart and Examples


Basic query monitoring

Basic monitoring of a query statement is easy with PECL/mysqlnd_uh. Combined with debug_print_backtrace() it can become a powerful tool, for example, to find the origin of certain statement. This may be desired when searching for slow queries but also after database refactorings to find code still accessing deprecated databases or tables. The latter may be a complicated matter to do otherwise, if the application uses auto-generated queries.

Przykład #1 Basic Monitoring

<?php
class conn_proxy extends MysqlndUhConnection {
 public function query($res, $query) {
  debug_print_backtrace();
  return parent::query($res, $query);
 }
}
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  debug_print_backtrace();
  return parent::prepare($res, $query);
 }
}
mysqlnd_uh_set_connection_proxy(new conn_proxy());
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

printf("Proxies installed...\n");
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
var_dump($pdo->query("SELECT 1 AS _one FROM DUAL")->fetchAll(PDO::FETCH_ASSOC));

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->prepare("SELECT 1 AS _two FROM DUAL");
?>

Powyższy przykład wyświetli:

#0  conn_proxy->query(Resource id #19, SELECT 1 AS _one FROM DUAL)
#1  PDO->query(SELECT 1 AS _one FROM DUAL) called at [example.php:19]
array(1) {
  [0]=>
  array(1) {
    ["_one"]=>
    string(1) "1"
  }
}
#0  stmt_proxy->prepare(Resource id #753, SELECT 1 AS _two FROM DUAL)
#1  mysqli->prepare(SELECT 1 AS _two FROM DUAL) called at [example.php:22]

For basic query monitoring you should install a connection and a prepared statement proxy. The connection proxy should subclass MysqlndUhConnection::query(). All database queries not using native prepared statements will call this method. In the example the query function is invoked by a PDO call. By default, PDO_MySQL is using prepared statement emulation.

All native prepared statements are prepared with the prepare method of mysqlnd exported through MysqlndUhPreparedStatement::prepare(). Subclass MysqlndUhPreparedStatement and overwrite prepare for native prepared statement monitoring.

Installing a proxy
Instalacja/Konfiguracja
Quickstart and Examples


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Basic query monitoring
Wymagania
mysqlnd_uh


Wymagania

PHP 5.3.3 or later. It is recommended to use PHP 5.4.0 or later to get access to the latest mysqlnd features.

The mysqlnd_uh user handler plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in order to be able to use the mysqlnd_uh plugin for mysqlnd.

The alpha versions makes use of some mysqli features. You must enable mysqli to compile the plugin. This requirement may be removed in the future. Note, that this requirement does not restrict you to use the plugin only with mysqli. You can use the plugin to monitor mysql, mysqli and PDO_MYSQL.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/mysqlnd-uh

PECL/mysqlnd_uh is currently not available on Windows. The source code of the extension makes use of C99 constructs not allowed with PHP Windows builds.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Mysqlnd_uh Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mysqlnd_uh.enable | 1 | PHP_INI_SYSTEM |
mysqlnd_uh.report_wrong_types | 1 | PHP_INI_ALL |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

mysqlnd_uh.enable integer

Enables or disables the plugin. If set to disabled, the extension will not allow users to plug into mysqlnd to hook mysqlnd calls.

mysqlnd_uh.report_wrong_types integer

Wheter to report wrong return value types of user hooks as error of the type E_WARNING. It is strongly recommended to use this setting for detecting possible issues.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

Most of the constants refer to details of the MySQL Client Server Protocol. Please, refer to the MySQL reference manual to learn about their meaning. To avoid content duplication, only short descriptions are given.

MysqlndUhConnection::simpleCommand() related

The following constants can be used to detect what command is to be send through MysqlndUhConnection::simpleCommand().

MYSQLND_UH_MYSQLND_COM_SLEEP (integer)
MySQL Client Server protocol command: COM_SLEEP.
MYSQLND_UH_MYSQLND_COM_QUIT (integer)
MySQL Client Server protocol command: COM_QUIT.
MYSQLND_UH_MYSQLND_COM_INIT_DB (integer)
MySQL Client Server protocol command: COM_INIT_DB.
MYSQLND_UH_MYSQLND_COM_QUERY (integer)
MySQL Client Server protocol command: COM_QUERY.
MYSQLND_UH_MYSQLND_COM_FIELD_LIST (integer)
MySQL Client Server protocol command: COM_FIELD_LIST.
MYSQLND_UH_MYSQLND_COM_CREATE_DB (integer)
MySQL Client Server protocol command: COM_CREATE_DB.
MYSQLND_UH_MYSQLND_COM_DROP_DB (integer)
MySQL Client Server protocol command: COM_DROP_DB.
MYSQLND_UH_MYSQLND_COM_REFRESH (integer)
MySQL Client Server protocol command: COM_REFRESH.
MYSQLND_UH_MYSQLND_COM_SHUTDOWN (integer)
MySQL Client Server protocol command: COM_SHUTDOWN.
MYSQLND_UH_MYSQLND_COM_STATISTICS (integer)
MySQL Client Server protocol command: COM_STATISTICS.
MYSQLND_UH_MYSQLND_COM_PROCESS_INFO (integer)
MySQL Client Server protocol command: COM_PROCESS_INFO.
MYSQLND_UH_MYSQLND_COM_CONNECT (integer)
MySQL Client Server protocol command: COM_CONNECT.
MYSQLND_UH_MYSQLND_COM_PROCESS_KILL (integer)
MySQL Client Server protocol command: COM_PROCESS_KILL.
MYSQLND_UH_MYSQLND_COM_DEBUG (integer)
MySQL Client Server protocol command: COM_DEBUG.
MYSQLND_UH_MYSQLND_COM_PING (integer)
MySQL Client Server protocol command: COM_PING.
MYSQLND_UH_MYSQLND_COM_TIME (integer)
MySQL Client Server protocol command: COM_TIME.
MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT (integer)
MySQL Client Server protocol command: COM_DELAYED_INSERT.
MYSQLND_UH_MYSQLND_COM_CHANGE_USER (integer)
MySQL Client Server protocol command: COM_CHANGE_USER.
MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP (integer)
MySQL Client Server protocol command: COM_BINLOG_DUMP.
MYSQLND_UH_MYSQLND_COM_TABLE_DUMP (integer)
MySQL Client Server protocol command: COM_TABLE_DUMP.
MYSQLND_UH_MYSQLND_COM_CONNECT_OUT (integer)
MySQL Client Server protocol command: COM_CONNECT_OUT.
MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED (integer)
MySQL Client Server protocol command: COM_REGISTER_SLAVED.
MYSQLND_UH_MYSQLND_COM_STMT_PREPARE (integer)
MySQL Client Server protocol command: COM_STMT_PREPARE.
MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE (integer)
MySQL Client Server protocol command: COM_STMT_EXECUTE.
MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA (integer)
MySQL Client Server protocol command: COM_STMT_SEND_LONG_DATA.
MYSQLND_UH_MYSQLND_COM_STMT_CLOSE (integer)
MySQL Client Server protocol command: COM_STMT_CLOSE.
MYSQLND_UH_MYSQLND_COM_STMT_RESET (integer)
MySQL Client Server protocol command: COM_STMT_RESET.
MYSQLND_UH_MYSQLND_COM_SET_OPTION (integer)
MySQL Client Server protocol command: COM_SET_OPTION.
MYSQLND_UH_MYSQLND_COM_STMT_FETCH (integer)
MySQL Client Server protocol command: COM_STMT_FETCH.
MYSQLND_UH_MYSQLND_COM_DAEMON (integer)
MySQL Client Server protocol command: COM_DAEMON.
MYSQLND_UH_MYSQLND_COM_END (integer)
MySQL Client Server protocol command: COM_END.

The following constants can be used to analyze the ok_packet argument of MysqlndUhConnection::simpleCommand().

MYSQLND_UH_MYSQLND_PROT_GREET_PACKET (integer)
MySQL Client Server protocol packet: greeting.
MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET (integer)
MySQL Client Server protocol packet: authentification.
MYSQLND_UH_MYSQLND_PROT_OK_PACKET (integer)
MySQL Client Server protocol packet: OK.
MYSQLND_UH_MYSQLND_PROT_EOF_PACKET (integer)
MySQL Client Server protocol packet: EOF.
MYSQLND_UH_MYSQLND_PROT_CMD_PACKET (integer)
MySQL Client Server protocol packet: command.
MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET (integer)
MySQL Client Server protocol packet: result set header.
MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET (integer)
MySQL Client Server protocol packet: resultset field.
MYSQLND_UH_MYSQLND_PROT_ROW_PACKET (integer)
MySQL Client Server protocol packet: row.
MYSQLND_UH_MYSQLND_PROT_STATS_PACKET (integer)
MySQL Client Server protocol packet: stats.
MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET (integer)
MySQL Client Server protocol packet: prepare response.
MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET (integer)
MySQL Client Server protocol packet: change user response.
MYSQLND_UH_MYSQLND_PROT_LAST (integer)
No practical meaning. Last entry marker of internal C data structure list.

MysqlndUhConnection::close() related

The following constants can be used to detect why a connection has been closed through MysqlndUhConnection::close().

MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT (integer)
User has called mysqlnd to close the connection.
MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT (integer)
Implicity close, for example, during garbage connection.
MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED (integer)
Connection error.
MYSQLND_UH_MYSQLND_CLOSE_LAST (integer)
No practical meaning. Last entry marker of internal C data structure list.

MysqlndUhConnection::setServerOption() related

The following constants can be used to detect which option is set through MysqlndUhConnection::setServerOption().

MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON (integer)
Option: enables multi statement support.
MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_OFF (integer)
Option: disables multi statement support.

MysqlndUhConnection::setClientOption() related

The following constants can be used to detect which option is set through MysqlndUhConnection::setClientOption().

MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT (integer)
Option: connection timeout.
MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS (integer)
Option: wheter the MySQL compressed protocol is to be used.
MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE (integer)
Option: named pipe to use for connection (Windows).
MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND (integer)
Option: init command to execute upon connect.
MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE (integer)
Option: MySQL server default file to read upon connect.
MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP (integer)
Option: MySQL server default file group to read upon connect.
MYSQLND_UH_MYSQLND_SET_CHARSET_DIR (integer)
Option: charset description files directory.
MYSQLND_UH_MYSQLND_SET_CHARSET_NAME (integer)
Option: charset name.
MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE (integer)
Option: Wheter to allow LOAD DATA LOCAL INFILE use.
MYSQLND_UH_MYSQLND_OPT_PROTOCOL (integer)
Option: supported protocol version.
MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME (integer)
Option: shared memory base name for shared memory connections.
MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT (integer)
Option: connection read timeout.
MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT (integer)
Option: connection write timeout.
MYSQLND_UH_MYSQLND_OPT_USE_RESULT (integer)
Option: unbuffered result sets.
MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION (integer)
Embedded server related.
MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION (integer)
Embedded server related.
MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION (integer)
TODO
MYSQLND_UH_MYSQLND_SET_CLIENT_IP (integer)
TODO
MYSQLND_UH_MYSQLND_SECURE_AUTH (integer)
TODO
MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION (integer)
Option: Wheter to report data truncation.
MYSQLND_UH_MYSQLND_OPT_RECONNECT (integer)
Option: Wheter to reconnect automatically.
MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT (integer)
Option: TODO
MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE (integer)
Option: mysqlnd network buffer size for commands.
MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE (integer)
Option: mysqlnd network buffer size for reading from the server.
MYSQLND_UH_MYSQLND_OPT_SSL_KEY (integer)
Option: SSL key.
MYSQLND_UH_MYSQLND_OPT_SSL_CERT (integer)
Option: SSL certificate.
MYSQLND_UH_MYSQLND_OPT_SSL_CA (integer)
Option: SSL CA.
MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH (integer)
Option: Path to SSL CA.
MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER (integer)
Option: SSL cipher.
MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE (integer)
Option: SSL passphrase.
MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR (integer)
Option: server plugin directory.
MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH (integer)
Option: default authentification method.
MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP (integer)
TODO
MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET (integer)
Option: maximum allowd packet size. Available as of PHP 5.4.0.
MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL (integer)
Option: TODO. Available as of PHP 5.4.0.
MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE (integer)
Option: make mysqlnd return integer and float columns as long even when using the MySQL Client Server text protocol. Only available with a custom build of mysqlnd.

Other

The plugins version number can be obtained using MYSQLND_UH_VERSION or MYSQLND_UH_VERSION_ID. MYSQLND_UH_VERSION is the string representation of the numerical version number MYSQLND_UH_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_UH_VERSION_ID | 10000

MYSQLND_UH_VERSION (string)
Plugin version string, for example, "1.0.0-alpha".
MYSQLND_UH_VERSION_ID (integer)
Plugin version number, for example, 10000.

Typy zasobów
MysqlndUhConnection
mysqlnd_uh


The MysqlndUhConnection class

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

Wstęp

Krótki opis klasy

MysqlndUhConnection {
/* Metody */
public bool changeUser ( mysqlnd_onnection $connection , string $user , string $password , string $database , bool $silent , int $passwd_len )
public string charsetName ( mysqlnd_connection $connection )
public bool close ( mysqlnd_connection $connection , int $close_type )
public bool connect ( mysqlnd_connection $connection , string $host , string $use" , string $password , string $database , int $port , string $socket , int $mysql_flags )
public __construct ( void )
public bool endPSession ( mysqlnd_connection $connection )
public string escapeString ( mysqlnd_connection $connection , string $escape_string )
public int getAffectedRows ( mysqlnd_connection $connection )
public int getErrorNumber ( mysqlnd_connection $connection )
public string getErrorString ( mysqlnd_connection $connection )
public int getFieldCount ( mysqlnd_connection $connection )
public string getHostInformation ( mysqlnd_connection $connection )
public int getLastInsertId ( mysqlnd_connection $connection )
public void getLastMessage ( mysqlnd_connection $connection )
public string getProtocolInformation ( mysqlnd_connection $connection )
public string getServerInformation ( mysqlnd_connection $connection )
public string getServerStatistics ( mysqlnd_connection $connection )
public int getServerVersion ( mysqlnd_connection $connection )
public string getSqlstate ( mysqlnd_connection $connection )
public array getStatistics ( mysqlnd_connection $connection )
public int getThreadId ( mysqlnd_connection $connection )
public int getWarningCount ( mysqlnd_connection $connection )
public bool init ( mysqlnd_connection $connection )
public bool killConnection ( mysqlnd_connection $connection , int $pid )
public array listFields ( mysqlnd_connection $connection , string $table , string $achtung_wild )
public void listMethod ( mysqlnd_connection $connection , string $query , string $achtung_wild , string $par1 )
public bool moreResults ( mysqlnd_connection $connection )
public bool nextResult ( mysqlnd_connection $connection )
public bool ping ( mysqlnd_connection $connection )
public bool query ( mysqlnd_connection $connection , string $query )
public bool queryReadResultsetHeader ( mysqlnd_connection $connection , mysqlnd_statement $mysqlnd_stmt )
public bool reapQuery ( mysqlnd_connection $connection )
public bool refreshServer ( mysqlnd_connection $connection , int $options )
public bool restartPSession ( mysqlnd_connection $connection )
public bool selectDb ( mysqlnd_connection $connection , string $database )
public bool sendClose ( mysqlnd_connection $connection )
public bool sendQuery ( mysqlnd_connection $connection , string $query )
public bool serverDumpDebugInformation ( mysqlnd_connection $connection )
public bool setAutocommit ( mysqlnd_connection $connection , int $mode )
public bool setCharset ( mysqlnd_connection $connection , string $charset )
public bool setClientOption ( mysqlnd_connection $connection , int $option , int $value )
public void setServerOption ( mysqlnd_connection $connection , int $option )
public void shutdownServer ( string $MYSQLND_UH_RES_MYSQLND_NAME , string $"level" )
public bool simpleCommand ( mysqlnd_connection $connection , int $command , string $arg , int $ok_packet , bool $silent , bool $ignore_upsert_status )
public bool simpleCommandHandleResponse ( mysqlnd_connection $connection , int $ok_packet , bool $silent , int $command , bool $ignore_upsert_status )
public bool sslSet ( mysqlnd_connection $connection , string $key , string $cert , string $ca , string $capath , string $cipher )
public resource stmtInit ( mysqlnd_connection $connection )
public resource storeResult ( mysqlnd_connection $connection )
public bool txCommit ( mysqlnd_connection $connection )
public bool txRollback ( mysqlnd_connection $connection )
public resource useResult ( mysqlnd_connection $connection )
}

Spis treści

  • MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection
  • MysqlndUhConnection::charsetName — Returns the default character set for the database connection
  • MysqlndUhConnection::close — Closes a previously opened database connection
  • MysqlndUhConnection::connect — Open a new connection to the MySQL server
  • MysqlndUhConnection::__construct — The __construct purpose
  • MysqlndUhConnection::endPSession — End a persistent connection
  • MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation
  • MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call
  • MysqlndUhConnection::getErrorString — Returns a string description of the last error
  • MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query
  • MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used
  • MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query.
  • MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query
  • MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used
  • MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server
  • MysqlndUhConnection::getServerStatistics — Gets the current system status
  • MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer
  • MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation
  • MysqlndUhConnection::getStatistics — Returns statistics about the client connection.
  • MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection
  • MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link
  • MysqlndUhConnection::init — Initialize mysqlnd connection
  • MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread
  • MysqlndUhConnection::listFields — List MySQL table fields
  • MysqlndUhConnection::listMethod — Wrapper for assorted list commands
  • MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query
  • MysqlndUhConnection::nextResult — Prepare next result from multi_query
  • MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • MysqlndUhConnection::query — Performs a query on the database
  • MysqlndUhConnection::queryReadResultsetHeader — Read a result set header
  • MysqlndUhConnection::reapQuery — Get result from async query
  • MysqlndUhConnection::refreshServer — Flush or reset tables and caches
  • MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection
  • MysqlndUhConnection::selectDb — Selects the default database for database queries
  • MysqlndUhConnection::sendClose — Sends a close command to MySQL
  • MysqlndUhConnection::sendQuery — Sends a query to MySQL
  • MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server
  • MysqlndUhConnection::setAutocommit — Turns on or off auto-commiting database modifications
  • MysqlndUhConnection::setCharset — Sets the default client character set
  • MysqlndUhConnection::setClientOption — Sets a client option
  • MysqlndUhConnection::setServerOption — Sets a server option
  • MysqlndUhConnection::shutdownServer — The shutdownServer purpose
  • MysqlndUhConnection::simpleCommand — Sends a basic COM_* command
  • MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client
  • MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL
  • MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare
  • MysqlndUhConnection::storeResult — Transfers a result set from the last query
  • MysqlndUhConnection::txCommit — Commits the current transaction
  • MysqlndUhConnection::txRollback — Rolls back current transaction
  • MysqlndUhConnection::useResult — Initiate a result set retrieval
Stałe predefiniowane
MysqlndUhConnection::changeUser
mysqlnd_uh


Changes the user of the specified mysqlnd database connection

MysqlndUhConnection
MysqlndUhConnection::charsetName
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::changeUser

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection

Opis

public bool MysqlndUhConnection::changeUser ( mysqlnd_onnection $connection , string $user , string $password , string $database , bool $silent , int $passwd_len )

Changes the user of the specified mysqlnd database connection

Parametry

connection

Mysqlnd connection handle. Do not modify!

user

The MySQL user name.

password

The MySQL password.

database

The MySQL database to change to.

silent

Controls if mysqlnd is allowed to emit errors or not.

passwd_len

Length of the MySQL password.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::changeUser() example

<?php
class proxy extends MysqlndUhConnection {
 /* Hook mysqlnd's connection::change_user call */
 public function changeUser($res, $user, $passwd, $db, $silent, $passwd_len) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::changeUser($res, $user, $passwd, $db, $silent, $passwd_len);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
/* Install proxy/hooks to be used with all future mysqlnd connection */
mysqlnd_uh_set_connection_proxy(new proxy());

/* Create mysqli connection which is using the mysqlnd library */
$mysqli = new mysqli("localhost", "root", "", "test");

/* Example of a user API call which triggers the hooked mysqlnd call */
var_dump($mysqli->change_user("root", "bar", "test"));
?>

Powyższy przykład wyświetli:

proxy::changeUser(array (
  0 => NULL,
  1 => 'root',
  2 => 'bar',
  3 => 'test',
  4 => false,
  5 => 3,
))
proxy::changeUser returns false
bool(false)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_change_user() - Changes the user of the specified database connection

MysqlndUhConnection
MysqlndUhConnection::charsetName
MysqlndUhConnection


Returns the default character set for the database connection

MysqlndUhConnection::changeUser
MysqlndUhConnection::close
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::charsetName

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::charsetName — Returns the default character set for the database connection

Opis

public string MysqlndUhConnection::charsetName ( mysqlnd_connection $connection )

Returns the default character set for the database connection.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

The default cahracter set.

Przykłady

Przykład #1 MysqlndUhConnection::charsetName() example

<?php
class proxy extends MysqlndUhConnection {
  public function charsetName($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::charsetName($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump(mysqli_character_set_name($mysqli));
?>

Powyższy przykład wyświetli:

proxy::charsetName(array (
  0 => NULL,
))
proxy::charsetName returns 'latin1'
string(6) "latin1"

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_character_set_name() - Returns the default character set for the database connection

MysqlndUhConnection::changeUser
MysqlndUhConnection::close
MysqlndUhConnection


Closes a previously opened database connection

MysqlndUhConnection::charsetName
MysqlndUhConnection::connect
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::close

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::close — Closes a previously opened database connection

Opis

public bool MysqlndUhConnection::close ( mysqlnd_connection $connection , int $close_type )

Closes a previously opened database connection.

Informacja:

Failing to call the parent implementation may cause memory leaks or crash PHP. This is not considered a bug. Please, keep in mind that the mysqlnd library functions have never been designed to be exposed to the user space.

Parametry

connection

The connection to be closed. Do not modify!

close_type

Why the connection is to be closed. The value of close_type is one of MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT, MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT, MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED or MYSQLND_UH_MYSQLND_CLOSE_LAST. The latter should never be seen, unless the default behaviour of the mysqlnd library has been changed by a plugin.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::close() example

<?php
function close_type_to_string($close_type) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED => "MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED",
  MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT => "MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT",
  MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT => "MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT",
  MYSQLND_UH_MYSQLND_CLOSE_LAST => "MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT"
 );
 return (isset($mapping[$close_type])) ? $mapping[$close_type] : 'unknown';
}

class proxy extends MysqlndUhConnection {
  public function close($res, $close_type) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   printf("close_type = %s\n", close_type_to_string($close_type));
   /* WARNING: you must call the parent */
   $ret = parent::close($res, $close_type);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->close();
?>

Powyższy przykład wyświetli:

proxy::close(array (
  0 => NULL,
  1 => 0,
))
close_type = MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT
proxy::close returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_close() - Closes a previously opened database connection
  • mysql_close() - Zamyka połączenie MySQL

MysqlndUhConnection::charsetName
MysqlndUhConnection::connect
MysqlndUhConnection


Open a new connection to the MySQL server

MysqlndUhConnection::close
MysqlndUhConnection::__construct
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::connect

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::connect — Open a new connection to the MySQL server

Opis

public bool MysqlndUhConnection::connect ( mysqlnd_connection $connection , string $host , string $use" , string $password , string $database , int $port , string $socket , int $mysql_flags )

Open a new connection to the MySQL server.

Parametry

connection

Mysqlnd connection handle. Do not modify!

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

user

The MySQL user name.

password

If not provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

database

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used. If NULL, mysqlnd will default to /tmp/mysql.sock.

mysql_flags

Connection options.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::connect() example

<?php
class proxy extends MysqlndUhConnection {
 public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

Powyższy przykład wyświetli:

proxy::connect(array (
  0 => NULL,
  1 => 'localhost',
  2 => 'root',
  3 => '',
  4 => 'test',
  5 => 3306,
  6 => NULL,
  7 => 131072,
))
proxy::connect returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_connect() - Alias dla mysqli::__construct
  • mysql_connect() - Otwiera połączenie do serwera MySQL

MysqlndUhConnection::close
MysqlndUhConnection::__construct
MysqlndUhConnection


The __construct purpose

MysqlndUhConnection::connect
MysqlndUhConnection::endPSession
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::__construct

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::__construct — The __construct purpose

Opis

public MysqlndUhConnection::__construct ( 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

MysqlndUhConnection::connect
MysqlndUhConnection::endPSession
MysqlndUhConnection


End a persistent connection

MysqlndUhConnection::__construct
MysqlndUhConnection::escapeString
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::endPSession

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::endPSession — End a persistent connection

Opis

public bool MysqlndUhConnection::endPSession ( mysqlnd_connection $connection )

End a persistent connection

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::endPSession() example

<?php
class proxy extends MysqlndUhConnection {
 public function endPSession($conn) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::endPSession($conn);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("p:localhost", "root", "", "test");
$mysqli->close();
?>

Powyższy przykład wyświetli:

proxy::endPSession(array (
  0 => NULL,
))
proxy::endPSession returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::__construct
MysqlndUhConnection::escapeString
MysqlndUhConnection


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

MysqlndUhConnection::endPSession
MysqlndUhConnection::getAffectedRows
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::escapeString

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

Opis

public string MysqlndUhConnection::escapeString ( mysqlnd_connection $connection , string $escape_string )

Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection.

Parametry

MYSQLND_UH_RES_MYSQLND_NAME

Mysqlnd connection handle. Do not modify!

escape_string

The string to be escaped.

Zwracane wartości

The escaped string.

Przykłady

Przykład #1 MysqlndUhConnection::escapeString() example

<?php
class proxy extends MysqlndUhConnection {
 public function escapeString($res, $string) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::escapeString($res, $string);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->set_charset("latin1");
$mysqli->real_escape_string("test0'test");
?>

Powyższy przykład wyświetli:

proxy::escapeString(array (
  0 => NULL,
  1 => 'test0\'test',
))
proxy::escapeString returns 'test0\\\'test'

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • mysql_real_escape_string() - Dodaje znaki unikowe w łańcuchu znaków do użycia w instrukcji SQL

MysqlndUhConnection::endPSession
MysqlndUhConnection::getAffectedRows
MysqlndUhConnection


Gets the number of affected rows in a previous MySQL operation

MysqlndUhConnection::escapeString
MysqlndUhConnection::getErrorNumber
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getAffectedRows

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation

Opis

public int MysqlndUhConnection::getAffectedRows ( mysqlnd_connection $connection )

Gets the number of affected rows in a previous MySQL operation.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Number of affected rows.

Przykłady

Przykład #1 MysqlndUhConnection::getAffectedRows() example

<?php
class proxy extends MysqlndUhConnection {
 public function getAffectedRows($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getAffectedRows($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");
var_dump($mysqli->affected_rows);
?>

Powyższy przykład wyświetli:

proxy::getAffectedRows(array (
  0 => NULL,
))
proxy::getAffectedRows returns 1
int(1)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysql_affected_rows() - Zwraca liczbę wierszy przetworzonych w poprzedniej operacji MySQL

MysqlndUhConnection::escapeString
MysqlndUhConnection::getErrorNumber
MysqlndUhConnection


Returns the error code for the most recent function call

MysqlndUhConnection::getAffectedRows
MysqlndUhConnection::getErrorString
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getErrorNumber

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call

Opis

public int MysqlndUhConnection::getErrorNumber ( mysqlnd_connection $connection )

Returns the error code for the most recent function call.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Error code for the most recent function call.

Przykłady

MysqlndUhConnection::getErrorNumber() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Przykład #1 MysqlndUhConnection::getErrorNumber() example

<?php
class proxy extends MysqlndUhConnection {
 public function getErrorNumber($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getErrorNumber($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

printf("connect...\n");
$mysqli = new mysqli("localhost", "root", "", "test");
printf("query...\n");
$mysqli->query("PLEASE_LET_THIS_BE_INVALID_SQL");
printf("errno...\n");
var_dump($mysqli->errno);
printf("close...\n");
$mysqli->close();
?>

Powyższy przykład wyświetli:

connect...
proxy::getErrorNumber(array (
  0 => NULL,
))
proxy::getErrorNumber returns 0
query...
errno...
proxy::getErrorNumber(array (
  0 => NULL,
))
proxy::getErrorNumber returns 1064
int(1064)
close...

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • MysqlndUhConnection::getErrorString() - Returns a string description of the last error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysql_errno() - Zwraca liczbową wartość kodu błędu z poprzedniej operacji MySQL

MysqlndUhConnection::getAffectedRows
MysqlndUhConnection::getErrorString
MysqlndUhConnection


Returns a string description of the last error

MysqlndUhConnection::getErrorNumber
MysqlndUhConnection::getFieldCount
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getErrorString

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getErrorString — Returns a string description of the last error

Opis

public string MysqlndUhConnection::getErrorString ( mysqlnd_connection $connection )

Returns a string description of the last error.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Error string for the most recent function call.

Przykłady

MysqlndUhConnection::getErrorString() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Przykład #1 MysqlndUhConnection::getErrorString() example

<?php
class proxy extends MysqlndUhConnection {
 public function getErrorString($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getErrorString($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

printf("connect...\n");
$mysqli = new mysqli("localhost", "root", "", "test");
printf("query...\n");
$mysqli->query("WILL_I_EVER_LEARN_SQL?");
printf("errno...\n");
var_dump($mysqli->error);
printf("close...\n");
$mysqli->close();
?>

Powyższy przykład wyświetli:

connect...
proxy::getErrorString(array (
  0 => NULL,
))
proxy::getErrorString returns ''
query...
errno...
proxy::getErrorString(array (
  0 => NULL,
))
proxy::getErrorString returns 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'WILL_I_EVER_LEARN_SQL?\' at line 1'
string(168) "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WILL_I_EVER_LEARN_SQL?' at line 1"
close...

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • MysqlndUhConnection::getErrorNumber() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysql_error() - Zwraca tekst komunikatu błędu z ostatniej operacji MySQL

MysqlndUhConnection::getErrorNumber
MysqlndUhConnection::getFieldCount
MysqlndUhConnection


Returns the number of columns for the most recent query

MysqlndUhConnection::getErrorString
MysqlndUhConnection::getHostInformation
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getFieldCount

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query

Opis

public int MysqlndUhConnection::getFieldCount ( mysqlnd_connection $connection )

Returns the number of columns for the most recent query.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Number of columns.

Przykłady

MysqlndUhConnection::getFieldCount() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Przykład #1 MysqlndUhConnection::getFieldCount() example

<?php
class proxy extends MysqlndUhConnection {
 public function getFieldCount($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getFieldCount($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("WILL_I_EVER_LEARN_SQL?");
var_dump($mysqli->field_count);
$mysqli->query("SELECT 1, 2, 3 FROM DUAL");
var_dump($mysqli->field_count);
?>

Powyższy przykład wyświetli:

proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 0
int(0)
proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 3
proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 3
int(3)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_field_count() - Returns the number of columns for the most recent query

MysqlndUhConnection::getErrorString
MysqlndUhConnection::getHostInformation
MysqlndUhConnection


Returns a string representing the type of connection used

MysqlndUhConnection::getFieldCount
MysqlndUhConnection::getLastInsertId
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getHostInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used

Opis

public string MysqlndUhConnection::getHostInformation ( mysqlnd_connection $connection )

Returns a string representing the type of connection used.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Connection description.

Przykłady

Przykład #1 MysqlndUhConnection::getHostInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getHostInformation($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getHostInformation($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->host_info);
?>

Powyższy przykład wyświetli:

proxy::getHostInformation(array (
  0 => NULL,
))
proxy::getHostInformation returns 'Localhost via UNIX socket'
string(25) "Localhost via UNIX socket"

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_host_info() - Returns a string representing the type of connection used
  • mysql_get_host_info() - Pobiera informacje o hoście MySQL

MysqlndUhConnection::getFieldCount
MysqlndUhConnection::getLastInsertId
MysqlndUhConnection


Returns the auto generated id used in the last query.

MysqlndUhConnection::getHostInformation
MysqlndUhConnection::getLastMessage
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getLastInsertId

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query.

Opis

public int MysqlndUhConnection::getLastInsertId ( mysqlnd_connection $connection )

Returns the auto generated id used in the last query.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Last insert id.

Przykłady

Przykład #1 MysqlndUhConnection::getLastInsertId() example

<?php
class proxy extends MysqlndUhConnection {
 public function getLastInsertId($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getLastInsertId($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT AUTO_INCREMENT PRIMARY KEY, col VARCHAR(255))");
$mysqli->query("INSERT INTO test(col) VALUES ('a')");
var_dump($mysqli->insert_id);
?>

Powyższy przykład wyświetli:

proxy::getLastInsertId(array (
  0 => NULL,
))
proxy::getLastInsertId returns 1
int(1)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_insert_id() - Returns the auto generated id used in the last query
  • mysql_insert_id() - Podaje numer ID wygenerowany podczas ostatniej operacji INSERT

MysqlndUhConnection::getHostInformation
MysqlndUhConnection::getLastMessage
MysqlndUhConnection


Retrieves information about the most recently executed query

MysqlndUhConnection::getLastInsertId
MysqlndUhConnection::getProtocolInformation
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getLastMessage

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query

Opis

public void MysqlndUhConnection::getLastMessage ( mysqlnd_connection $connection )

Retrieves information about the most recently executed query.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Last message. Trying to return a string longer than 511 bytes will cause an error of the type E_WARNING and result in the string being truncated.

Przykłady

Przykład #1 MysqlndUhConnection::getLastMessage() example

<?php
class proxy extends MysqlndUhConnection {
 public function getLastMessage($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getLastMessage($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->info);
$mysqli->query("DROP TABLE IF EXISTS test");
var_dump($mysqli->info);
?>

Powyższy przykład wyświetli:

proxy::getLastMessage(array (
  0 => NULL,
))
proxy::getLastMessage returns ''
string(0) ""
proxy::getLastMessage(array (
  0 => NULL,
))
proxy::getLastMessage returns ''
string(0) ""

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_info() - Retrieves information about the most recently executed query
  • mysql_info() - Pobiera informacje o ostatnim zapytaniu

MysqlndUhConnection::getLastInsertId
MysqlndUhConnection::getProtocolInformation
MysqlndUhConnection


Returns the version of the MySQL protocol used

MysqlndUhConnection::getLastMessage
MysqlndUhConnection::getServerInformation
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getProtocolInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used

Opis

public string MysqlndUhConnection::getProtocolInformation ( mysqlnd_connection $connection )

Returns the version of the MySQL protocol used.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

The protocol version.

Przykłady

Przykład #1 MysqlndUhConnection::getProtocolInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getProtocolInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getProtocolInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->protocol_version);
?>

Powyższy przykład wyświetli:

proxy::getProtocolInformation(array (
  0 => NULL,
))
proxy::getProtocolInformation returns 10
int(10)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_proto_info() - Returns the version of the MySQL protocol used
  • mysql_get_proto_info() - Pobiera informacje o protokole MySQL

MysqlndUhConnection::getLastMessage
MysqlndUhConnection::getServerInformation
MysqlndUhConnection


Returns the version of the MySQL server

MysqlndUhConnection::getProtocolInformation
MysqlndUhConnection::getServerStatistics
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getServerInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server

Opis

public string MysqlndUhConnection::getServerInformation ( mysqlnd_connection $connection )

Returns the version of the MySQL server.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

The server version.

Przykłady

Przykład #1 MysqlndUhConnection::getServerInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->server_info);
?>

Powyższy przykład wyświetli:

proxy::getServerInformation(array (
  0 => NULL,
))
proxy::getServerInformation returns '5.1.45-debug-log'
string(16) "5.1.45-debug-log"

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysql_get_server_info() - Pobiera informacje o serwerze MySQL

MysqlndUhConnection::getProtocolInformation
MysqlndUhConnection::getServerStatistics
MysqlndUhConnection


Gets the current system status

MysqlndUhConnection::getServerInformation
MysqlndUhConnection::getServerVersion
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getServerStatistics

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerStatistics — Gets the current system status

Opis

public string MysqlndUhConnection::getServerStatistics ( mysqlnd_connection $connection )

Gets the current system status.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

The system status message.

Przykłady

Przykład #1 MysqlndUhConnection::getServerStatistics() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerStatistics($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerStatistics($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump(mysqli_stat($mysqli));
?>

Powyższy przykład wyświetli:

proxy::getServerStatistics(array (
  0 => NULL,
))
proxy::getServerStatistics returns 'Uptime: 2059995  Threads: 1  Questions: 126157  Slow queries: 0  Opens: 6377  Flush tables: 1  Open tables: 18  Queries per second avg: 0.61'
string(140) "Uptime: 2059995  Threads: 1  Questions: 126157  Slow queries: 0  Opens: 6377  Flush tables: 1  Open tables: 18  Queries per second avg: 0.61"

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_stat() - Gets the current system status
  • mysql_stat() - Pobiera aktualny stan systemu

MysqlndUhConnection::getServerInformation
MysqlndUhConnection::getServerVersion
MysqlndUhConnection


Returns the version of the MySQL server as an integer

MysqlndUhConnection::getServerStatistics
MysqlndUhConnection::getSqlstate
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getServerVersion

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer

Opis

public int MysqlndUhConnection::getServerVersion ( mysqlnd_connection $connection )

Returns the version of the MySQL server as an integer.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

The MySQL version.

Przykłady

Przykład #1 MysqlndUhConnection::getServerVersion() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerVersion($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerVersion($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->server_version);
?>

Powyższy przykład wyświetli:

proxy::getServerVersion(array (
  0 => NULL,
))
proxy::getServerVersion returns 50145
int(50145)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer
  • mysql_get_server_version()

MysqlndUhConnection::getServerStatistics
MysqlndUhConnection::getSqlstate
MysqlndUhConnection


Returns the SQLSTATE error from previous MySQL operation

MysqlndUhConnection::getServerVersion
MysqlndUhConnection::getStatistics
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getSqlstate

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation

Opis

public string MysqlndUhConnection::getSqlstate ( mysqlnd_connection $connection )

Returns the SQLSTATE error from previous MySQL operation.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

The SQLSTATE code.

Przykłady

Przykład #1 MysqlndUhConnection::getSqlstate() example

<?php
class proxy extends MysqlndUhConnection {
 public function getSqlstate($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getSqlstate($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->sqlstate);
$mysqli->query("AN_INVALID_REQUEST_TO_PROVOKE_AN_ERROR");
var_dump($mysqli->sqlstate);
?>

Powyższy przykład wyświetli:

proxy::getSqlstate(array (
  0 => NULL,
))
proxy::getSqlstate returns '00000'
string(5) "00000"
proxy::getSqlstate(array (
  0 => NULL,
))
proxy::getSqlstate returns '42000'
string(5) "42000"

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_sql_state()

MysqlndUhConnection::getServerVersion
MysqlndUhConnection::getStatistics
MysqlndUhConnection


Returns statistics about the client connection.

MysqlndUhConnection::getSqlstate
MysqlndUhConnection::getThreadId
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getStatistics

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getStatistics — Returns statistics about the client connection.

Opis

public array MysqlndUhConnection::getStatistics ( mysqlnd_connection $connection )

Returns statistics about the client connection.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Connection statistics collected by mysqlnd.

Przykłady

Przykład #1 MysqlndUhConnection::getStatistics() example

<?php
class proxy extends MysqlndUhConnection {
 public function getStatistics($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getStatistics($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->get_connection_stats());
?>

Powyższy przykład wyświetli:

proxy::getStatistics(array (
  0 => NULL,
))
proxy::getStatistics returns array (
  'bytes_sent' => '73',
  'bytes_received' => '77',
  'packets_sent' => '2',
  'packets_received' => '2',
  'protocol_overhead_in' => '8',
  'protocol_overhead_out' => '8',
  'bytes_received_ok_packet' => '0',
  'bytes_received_eof_packet' => '0',
  'bytes_received_rset_header_packet' => '0',
  'bytes_received_rset_field_meta_packet' => '0',
  'bytes_received_rset_row_packet' => '0',
  'bytes_received_prepare_response_packet' => '0',
  'bytes_received_change_user_packet' => '0',
  'packets_sent_command' => '0',
  'packets_received_ok' => '0',
  'packets_received_eof' => '0',
  'packets_received_rset_header' => '0',
  'packets_received_rset_field_meta' => '0',
  'packets_received_rset_row' => '0',
  'packets_received_prepare_response' => '0',
  'packets_received_change_user' => '0',
  'result_set_queries' => '0',
  'non_result_set_queries' => '0',
  'no_index_used' => '0',
  'bad_index_used' => '0',
  'slow_queries' => '0',
  'buffered_sets' => '0',
  'unbuffered_sets' => '0',
  'ps_buffered_sets' => '0',
  'ps_unbuffered_sets' => '0',
  'flushed_normal_sets' => '0',
  'flushed_ps_sets' => '0',
  'ps_prepared_never_executed' => '0',
  'ps_prepared_once_executed' => '0',
  'rows_fetched_from_server_normal' => '0',
  'rows_fetched_from_server_ps' => '0',
  'rows_buffered_from_client_normal' => '0',
  'rows_buffered_from_client_ps' => '0',
  'rows_fetched_from_client_normal_buffered' => '0',
  'rows_fetched_from_client_normal_unbuffered' => '0',
  'rows_fetched_from_client_ps_buffered' => '0',
  'rows_fetched_from_client_ps_unbuffered' => '0',
  'rows_fetched_from_client_ps_cursor' => '0',
  'rows_affected_normal' => '0',
  'rows_affected_ps' => '0',
  'rows_skipped_normal' => '0',
  'rows_skipped_ps' => '0',
  'copy_on_write_saved' => '0',
  'copy_on_write_performed' => '0',
  'command_buffer_too_small' => '0',
  'connect_success' => '1',
  'connect_failure' => '0',
  'connection_reused' => '0',
  'reconnect' => '0',
  'pconnect_success' => '0',
  'active_connections' => '1',
  'active_persistent_connections' => '0',
  'explicit_close' => '0',
  'implicit_close' => '0',
  'disconnect_close' => '0',
  'in_middle_of_command_close' => '0',
  'explicit_free_result' => '0',
  'implicit_free_result' => '0',
  'explicit_stmt_close' => '0',
  'implicit_stmt_close' => '0',
  'mem_emalloc_count' => '0',
  'mem_emalloc_amount' => '0',
  'mem_ecalloc_count' => '0',
  'mem_ecalloc_amount' => '0',
  'mem_erealloc_count' => '0',
  'mem_erealloc_amount' => '0',
  'mem_efree_count' => '0',
  'mem_efree_amount' => '0',
  'mem_malloc_count' => '0',
  'mem_malloc_amount' => '0',
  'mem_calloc_count' => '0',
  'mem_calloc_amount' => '0',
  'mem_realloc_count' => '0',
  'mem_realloc_amount' => '0',
  'mem_free_count' => '0',
  'mem_free_amount' => '0',
  'mem_estrndup_count' => '0',
  'mem_strndup_count' => '0',
  'mem_estndup_count' => '0',
  'mem_strdup_count' => '0',
  'proto_text_fetched_null' => '0',
  'proto_text_fetched_bit' => '0',
  'proto_text_fetched_tinyint' => '0',
  'proto_text_fetched_short' => '0',
  'proto_text_fetched_int24' => '0',
  'proto_text_fetched_int' => '0',
  'proto_text_fetched_bigint' => '0',
  'proto_text_fetched_decimal' => '0',
  'proto_text_fetched_float' => '0',
  'proto_text_fetched_double' => '0',
  'proto_text_fetched_date' => '0',
  'proto_text_fetched_year' => '0',
  'proto_text_fetched_time' => '0',
  'proto_text_fetched_datetime' => '0',
  'proto_text_fetched_timestamp' => '0',
  'proto_text_fetched_string' => '0',
  'proto_text_fetched_blob' => '0',
  'proto_text_fetched_enum' => '0',
  'proto_text_fetched_set' => '0',
  'proto_text_fetched_geometry' => '0',
  'proto_text_fetched_other' => '0',
  'proto_binary_fetched_null' => '0',
  'proto_binary_fetched_bit' => '0',
  'proto_binary_fetched_tinyint' => '0',
  'proto_binary_fetched_short' => '0',
  'proto_binary_fetched_int24' => '0',
  'proto_binary_fetched_int' => '0',
  'proto_binary_fetched_bigint' => '0',
  'proto_binary_fetched_decimal' => '0',
  'proto_binary_fetched_float' => '0',
  'proto_binary_fetched_double' => '0',
  'proto_binary_fetched_date' => '0',
  'proto_binary_fetched_year' => '0',
  'proto_binary_fetched_time' => '0',
  'proto_binary_fetched_datetime' => '0',
  'proto_binary_fetched_timestamp' => '0',
  'proto_binary_fetched_string' => '0',
  'proto_binary_fetched_blob' => '0',
  'proto_binary_fetched_enum' => '0',
  'proto_binary_fetched_set' => '0',
  'proto_binary_fetched_geometry' => '0',
  'proto_binary_fetched_other' => '0',
  'init_command_executed_count' => '0',
  'init_command_failed_count' => '0',
  'com_quit' => '0',
  'com_init_db' => '0',
  'com_query' => '0',
  'com_field_list' => '0',
  'com_create_db' => '0',
  'com_drop_db' => '0',
  'com_refresh' => '0',
  'com_shutdown' => '0',
  'com_statistics' => '0',
  'com_process_info' => '0',
  'com_connect' => '0',
  'com_process_kill' => '0',
  'com_debug' => '0',
  'com_ping' => '0',
  'com_time' => '0',
  'com_delayed_insert' => '0',
  'com_change_user' => '0',
  'com_binlog_dump' => '0',
  'com_table_dump' => '0',
  'com_connect_out' => '0',
  'com_register_slave' => '0',
  'com_stmt_prepare' => '0',
  'com_stmt_execute' => '0',
  'com_stmt_send_long_data' => '0',
  'com_stmt_close' => '0',
  'com_stmt_reset' => '0',
  'com_stmt_set_option' => '0',
  'com_stmt_fetch' => '0',
  'com_deamon' => '0',
  'bytes_received_real_data_normal' => '0',
  'bytes_received_real_data_ps' => '0',
)
array(160) {
  ["bytes_sent"]=>
  string(2) "73"
  ["bytes_received"]=>
  string(2) "77"
  ["packets_sent"]=>
  string(1) "2"
  ["packets_received"]=>
  string(1) "2"
  ["protocol_overhead_in"]=>
  string(1) "8"
  ["protocol_overhead_out"]=>
  string(1) "8"
  ["bytes_received_ok_packet"]=>
  string(1) "0"
  ["bytes_received_eof_packet"]=>
  string(1) "0"
  ["bytes_received_rset_header_packet"]=>
  string(1) "0"
  ["bytes_received_rset_field_meta_packet"]=>
  string(1) "0"
  ["bytes_received_rset_row_packet"]=>
  string(1) "0"
  ["bytes_received_prepare_response_packet"]=>
  string(1) "0"
  ["bytes_received_change_user_packet"]=>
  string(1) "0"
  ["packets_sent_command"]=>
  string(1) "0"
  ["packets_received_ok"]=>
  string(1) "0"
  ["packets_received_eof"]=>
  string(1) "0"
  ["packets_received_rset_header"]=>
  string(1) "0"
  ["packets_received_rset_field_meta"]=>
  string(1) "0"
  ["packets_received_rset_row"]=>
  string(1) "0"
  ["packets_received_prepare_response"]=>
  string(1) "0"
  ["packets_received_change_user"]=>
  string(1) "0"
  ["result_set_queries"]=>
  string(1) "0"
  ["non_result_set_queries"]=>
  string(1) "0"
  ["no_index_used"]=>
  string(1) "0"
  ["bad_index_used"]=>
  string(1) "0"
  ["slow_queries"]=>
  string(1) "0"
  ["buffered_sets"]=>
  string(1) "0"
  ["unbuffered_sets"]=>
  string(1) "0"
  ["ps_buffered_sets"]=>
  string(1) "0"
  ["ps_unbuffered_sets"]=>
  string(1) "0"
  ["flushed_normal_sets"]=>
  string(1) "0"
  ["flushed_ps_sets"]=>
  string(1) "0"
  ["ps_prepared_never_executed"]=>
  string(1) "0"
  ["ps_prepared_once_executed"]=>
  string(1) "0"
  ["rows_fetched_from_server_normal"]=>
  string(1) "0"
  ["rows_fetched_from_server_ps"]=>
  string(1) "0"
  ["rows_buffered_from_client_normal"]=>
  string(1) "0"
  ["rows_buffered_from_client_ps"]=>
  string(1) "0"
  ["rows_fetched_from_client_normal_buffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_normal_unbuffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_buffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_unbuffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_cursor"]=>
  string(1) "0"
  ["rows_affected_normal"]=>
  string(1) "0"
  ["rows_affected_ps"]=>
  string(1) "0"
  ["rows_skipped_normal"]=>
  string(1) "0"
  ["rows_skipped_ps"]=>
  string(1) "0"
  ["copy_on_write_saved"]=>
  string(1) "0"
  ["copy_on_write_performed"]=>
  string(1) "0"
  ["command_buffer_too_small"]=>
  string(1) "0"
  ["connect_success"]=>
  string(1) "1"
  ["connect_failure"]=>
  string(1) "0"
  ["connection_reused"]=>
  string(1) "0"
  ["reconnect"]=>
  string(1) "0"
  ["pconnect_success"]=>
  string(1) "0"
  ["active_connections"]=>
  string(1) "1"
  ["active_persistent_connections"]=>
  string(1) "0"
  ["explicit_close"]=>
  string(1) "0"
  ["implicit_close"]=>
  string(1) "0"
  ["disconnect_close"]=>
  string(1) "0"
  ["in_middle_of_command_close"]=>
  string(1) "0"
  ["explicit_free_result"]=>
  string(1) "0"
  ["implicit_free_result"]=>
  string(1) "0"
  ["explicit_stmt_close"]=>
  string(1) "0"
  ["implicit_stmt_close"]=>
  string(1) "0"
  ["mem_emalloc_count"]=>
  string(1) "0"
  ["mem_emalloc_amount"]=>
  string(1) "0"
  ["mem_ecalloc_count"]=>
  string(1) "0"
  ["mem_ecalloc_amount"]=>
  string(1) "0"
  ["mem_erealloc_count"]=>
  string(1) "0"
  ["mem_erealloc_amount"]=>
  string(1) "0"
  ["mem_efree_count"]=>
  string(1) "0"
  ["mem_efree_amount"]=>
  string(1) "0"
  ["mem_malloc_count"]=>
  string(1) "0"
  ["mem_malloc_amount"]=>
  string(1) "0"
  ["mem_calloc_count"]=>
  string(1) "0"
  ["mem_calloc_amount"]=>
  string(1) "0"
  ["mem_realloc_count"]=>
  string(1) "0"
  ["mem_realloc_amount"]=>
  string(1) "0"
  ["mem_free_count"]=>
  string(1) "0"
  ["mem_free_amount"]=>
  string(1) "0"
  ["mem_estrndup_count"]=>
  string(1) "0"
  ["mem_strndup_count"]=>
  string(1) "0"
  ["mem_estndup_count"]=>
  string(1) "0"
  ["mem_strdup_count"]=>
  string(1) "0"
  ["proto_text_fetched_null"]=>
  string(1) "0"
  ["proto_text_fetched_bit"]=>
  string(1) "0"
  ["proto_text_fetched_tinyint"]=>
  string(1) "0"
  ["proto_text_fetched_short"]=>
  string(1) "0"
  ["proto_text_fetched_int24"]=>
  string(1) "0"
  ["proto_text_fetched_int"]=>
  string(1) "0"
  ["proto_text_fetched_bigint"]=>
  string(1) "0"
  ["proto_text_fetched_decimal"]=>
  string(1) "0"
  ["proto_text_fetched_float"]=>
  string(1) "0"
  ["proto_text_fetched_double"]=>
  string(1) "0"
  ["proto_text_fetched_date"]=>
  string(1) "0"
  ["proto_text_fetched_year"]=>
  string(1) "0"
  ["proto_text_fetched_time"]=>
  string(1) "0"
  ["proto_text_fetched_datetime"]=>
  string(1) "0"
  ["proto_text_fetched_timestamp"]=>
  string(1) "0"
  ["proto_text_fetched_string"]=>
  string(1) "0"
  ["proto_text_fetched_blob"]=>
  string(1) "0"
  ["proto_text_fetched_enum"]=>
  string(1) "0"
  ["proto_text_fetched_set"]=>
  string(1) "0"
  ["proto_text_fetched_geometry"]=>
  string(1) "0"
  ["proto_text_fetched_other"]=>
  string(1) "0"
  ["proto_binary_fetched_null"]=>
  string(1) "0"
  ["proto_binary_fetched_bit"]=>
  string(1) "0"
  ["proto_binary_fetched_tinyint"]=>
  string(1) "0"
  ["proto_binary_fetched_short"]=>
  string(1) "0"
  ["proto_binary_fetched_int24"]=>
  string(1) "0"
  ["proto_binary_fetched_int"]=>
  string(1) "0"
  ["proto_binary_fetched_bigint"]=>
  string(1) "0"
  ["proto_binary_fetched_decimal"]=>
  string(1) "0"
  ["proto_binary_fetched_float"]=>
  string(1) "0"
  ["proto_binary_fetched_double"]=>
  string(1) "0"
  ["proto_binary_fetched_date"]=>
  string(1) "0"
  ["proto_binary_fetched_year"]=>
  string(1) "0"
  ["proto_binary_fetched_time"]=>
  string(1) "0"
  ["proto_binary_fetched_datetime"]=>
  string(1) "0"
  ["proto_binary_fetched_timestamp"]=>
  string(1) "0"
  ["proto_binary_fetched_string"]=>
  string(1) "0"
  ["proto_binary_fetched_blob"]=>
  string(1) "0"
  ["proto_binary_fetched_enum"]=>
  string(1) "0"
  ["proto_binary_fetched_set"]=>
  string(1) "0"
  ["proto_binary_fetched_geometry"]=>
  string(1) "0"
  ["proto_binary_fetched_other"]=>
  string(1) "0"
  ["init_command_executed_count"]=>
  string(1) "0"
  ["init_command_failed_count"]=>
  string(1) "0"
  ["com_quit"]=>
  string(1) "0"
  ["com_init_db"]=>
  string(1) "0"
  ["com_query"]=>
  string(1) "0"
  ["com_field_list"]=>
  string(1) "0"
  ["com_create_db"]=>
  string(1) "0"
  ["com_drop_db"]=>
  string(1) "0"
  ["com_refresh"]=>
  string(1) "0"
  ["com_shutdown"]=>
  string(1) "0"
  ["com_statistics"]=>
  string(1) "0"
  ["com_process_info"]=>
  string(1) "0"
  ["com_connect"]=>
  string(1) "0"
  ["com_process_kill"]=>
  string(1) "0"
  ["com_debug"]=>
  string(1) "0"
  ["com_ping"]=>
  string(1) "0"
  ["com_time"]=>
  string(1) "0"
  ["com_delayed_insert"]=>
  string(1) "0"
  ["com_change_user"]=>
  string(1) "0"
  ["com_binlog_dump"]=>
  string(1) "0"
  ["com_table_dump"]=>
  string(1) "0"
  ["com_connect_out"]=>
  string(1) "0"
  ["com_register_slave"]=>
  string(1) "0"
  ["com_stmt_prepare"]=>
  string(1) "0"
  ["com_stmt_execute"]=>
  string(1) "0"
  ["com_stmt_send_long_data"]=>
  string(1) "0"
  ["com_stmt_close"]=>
  string(1) "0"
  ["com_stmt_reset"]=>
  string(1) "0"
  ["com_stmt_set_option"]=>
  string(1) "0"
  ["com_stmt_fetch"]=>
  string(1) "0"
  ["com_deamon"]=>
  string(1) "0"
  ["bytes_received_real_data_normal"]=>
  string(1) "0"
  ["bytes_received_real_data_ps"]=>
  string(1) "0"
}

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_connection_stats() - Returns statistics about the client connection

MysqlndUhConnection::getSqlstate
MysqlndUhConnection::getThreadId
MysqlndUhConnection


Returns the thread ID for the current connection

MysqlndUhConnection::getStatistics
MysqlndUhConnection::getWarningCount
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getThreadId

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection

Opis

public int MysqlndUhConnection::getThreadId ( mysqlnd_connection $connection )

Returns the thread ID for the current connection.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Connection thread id.

Przykłady

Przykład #1 MysqlndUhConnection::getThreadId() example

<?php
class proxy extends MysqlndUhConnection {
 public function getThreadId($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getThreadId($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->thread_id);
?>

Powyższy przykład wyświetli:

proxy::getThreadId(array (
  0 => NULL,
))
proxy::getThreadId returns 27646
int(27646)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_thread_id() - Returns the thread ID for the current connection
  • mysql_thread_id() - Zwraca id bieżącego wątku

MysqlndUhConnection::getStatistics
MysqlndUhConnection::getWarningCount
MysqlndUhConnection


Returns the number of warnings from the last query for the given link

MysqlndUhConnection::getThreadId
MysqlndUhConnection::init
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::getWarningCount

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link

Opis

public int MysqlndUhConnection::getWarningCount ( mysqlnd_connection $connection )

Returns the number of warnings from the last query for the given link.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Number of warnings.

Przykłady

Przykład #1 MysqlndUhConnection::getWarningCount() example

<?php
class proxy extends MysqlndUhConnection {
 public function getWarningCount($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getWarningCount($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->warning_count);
?>

Powyższy przykład wyświetli:

proxy::getWarningCount(array (
  0 => NULL,
))
proxy::getWarningCount returns 0
int(0)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_warning_count() - Returns the number of warnings from the last query for the given link

MysqlndUhConnection::getThreadId
MysqlndUhConnection::init
MysqlndUhConnection


Initialize mysqlnd connection

MysqlndUhConnection::getWarningCount
MysqlndUhConnection::killConnection
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::init

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::init — Initialize mysqlnd connection

Opis

public bool MysqlndUhConnection::init ( mysqlnd_connection $connection )

Initialize mysqlnd connection. This is an mysqlnd internal call to initialize the connection object.

Informacja:

Failing to call the parent implementation may cause memory leaks or crash PHP. This is not considered a bug. Please, keep in mind that the mysqlnd library functions have never been designed to be exposed to the user space.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::init() example

<?php
class proxy extends MysqlndUhConnection {
 public function init($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::init($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

Powyższy przykład wyświetli:

proxy::init(array (
  0 => NULL,
))
proxy::init returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::getWarningCount
MysqlndUhConnection::killConnection
MysqlndUhConnection


Asks the server to kill a MySQL thread

MysqlndUhConnection::init
MysqlndUhConnection::listFields
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::killConnection

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread

Opis

public bool MysqlndUhConnection::killConnection ( mysqlnd_connection $connection , int $pid )

Asks the server to kill a MySQL thread.

Parametry

connection

Mysqlnd connection handle. Do not modify!

pid

Thread Id of the connection to be killed.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::kill() example

<?php
class proxy extends MysqlndUhConnection {
 public function killConnection($res, $pid) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::killConnection($res, $pid);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->kill($mysqli->thread_id);
?>

Powyższy przykład wyświetli:

proxy::killConnection(array (
  0 => NULL,
  1 => 27650,
))
proxy::killConnection returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_kill() - Asks the server to kill a MySQL thread

MysqlndUhConnection::init
MysqlndUhConnection::listFields
MysqlndUhConnection


List MySQL table fields

MysqlndUhConnection::killConnection
MysqlndUhConnection::listMethod
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::listFields

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::listFields — List MySQL table fields

Opis

public array MysqlndUhConnection::listFields ( mysqlnd_connection $connection , string $table , string $achtung_wild )

List MySQL table fields.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

connection

Mysqlnd connection handle. Do not modify!

table

The name of the table that's being queried.

pattern

Name pattern.

Zwracane wartości

Przykłady

Przykład #1 MysqlndUhConnection::listFields() example

<?php
class proxy extends MysqlndUhConnection {
 public function listFields($res, $table, $pattern) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::listFields($res, $table, $pattern);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysql = mysql_connect("localhost", "root", "");
mysql_select_db("test", $mysql);
mysql_query("DROP TABLE IF EXISTS test_a", $mysql);
mysql_query("CREATE TABLE test_a(id INT, col1 VARCHAR(255))", $mysql);
$res = mysql_list_fields("test", "test_a", $mysql);
printf("num_rows = %d\n", mysql_num_rows($res));
while ($row = mysql_fetch_assoc($res))
 var_dump($row);
?>

Powyższy przykład wyświetli:

proxy::listFields(array (
  0 => NULL,
  1 => 'test_a',
  2 => '',
))
proxy::listFields returns NULL
num_rows = 0

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysql_list_fields() - Pobiera informacje o polach tabeli MySQL

MysqlndUhConnection::killConnection
MysqlndUhConnection::listMethod
MysqlndUhConnection


Wrapper for assorted list commands

MysqlndUhConnection::listFields
MysqlndUhConnection::moreResults
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::listMethod

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::listMethod — Wrapper for assorted list commands

Opis

public void MysqlndUhConnection::listMethod ( mysqlnd_connection $connection , string $query , string $achtung_wild , string $par1 )

Wrapper for assorted list commands.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

connection

Mysqlnd connection handle. Do not modify!

query

SHOW command to be executed.

achtung_wild

par1

Zwracane wartości

Zwracane wartości

TODO

Przykłady

Przykład #1 MysqlndUhConnection::listMethod() example

<?php
class proxy extends MysqlndUhConnection {
 public function listMethod($res, $query, $pattern, $par1) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::listMethod($res, $query, $pattern, $par1);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysql = mysql_connect("localhost", "root", "");
$res = mysql_list_dbs($mysql);
printf("num_rows = %d\n", mysql_num_rows($res));
while ($row = mysql_fetch_assoc($res))
 var_dump($row);
?>

Powyższy przykład wyświetli:

proxy::listMethod(array (
  0 => NULL,
  1 => 'SHOW DATABASES',
  2 => '',
  3 => '',
))
proxy::listMethod returns NULL
num_rows = 6
array(1) {
  ["Database"]=>
  string(18) "information_schema"
}
array(1) {
  ["Database"]=>
  string(5) "mysql"
}
array(1) {
  ["Database"]=>
  string(8) "oxid_new"
}
array(1) {
  ["Database"]=>
  string(7) "phptest"
}
array(1) {
  ["Database"]=>
  string(7) "pushphp"
}
array(1) {
  ["Database"]=>
  string(4) "test"
}

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysql_list_dbs() - Pobiera nazwy baz dostępnych na serwerze MySQL

MysqlndUhConnection::listFields
MysqlndUhConnection::moreResults
MysqlndUhConnection


Check if there are any more query results from a multi query

MysqlndUhConnection::listMethod
MysqlndUhConnection::nextResult
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::moreResults

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query

Opis

public bool MysqlndUhConnection::moreResults ( mysqlnd_connection $connection )

Check if there are any more query results from a multi query.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::moreResults() example

<?php
class proxy extends MysqlndUhConnection {
 public function moreResults($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::moreResults($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1 AS _one; SELECT 2 AS _two");
do {
  $res = $mysqli->store_result();
  var_dump($res->fetch_assoc());
  printf("%s\n", str_repeat("-", 40));
} while ($mysqli->more_results() && $mysqli->next_result());
?>

Powyższy przykład wyświetli:

array(1) {
  ["_one"]=>
  string(1) "1"
}
----------------------------------------
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns true
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns true
array(1) {
  ["_two"]=>
  string(1) "2"
}
----------------------------------------
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns false

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_more_results() - Check if there are any more query results from a multi query

MysqlndUhConnection::listMethod
MysqlndUhConnection::nextResult
MysqlndUhConnection


Prepare next result from multi_query

MysqlndUhConnection::moreResults
MysqlndUhConnection::ping
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::nextResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::nextResult — Prepare next result from multi_query

Opis

public bool MysqlndUhConnection::nextResult ( mysqlnd_connection $connection )

Prepare next result from multi_query.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::nextResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function nextResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::nextResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1 AS _one; SELECT 2 AS _two");
do {
  $res = $mysqli->store_result();
  var_dump($res->fetch_assoc());
  printf("%s\n", str_repeat("-", 40));
} while ($mysqli->more_results() && $mysqli->next_result());
?>

Powyższy przykład wyświetli:

array(1) {
  ["_one"]=>
  string(1) "1"
}
----------------------------------------
proxy::nextResult(array (
  0 => NULL,
))
proxy::nextResult returns true
array(1) {
  ["_two"]=>
  string(1) "2"
}
----------------------------------------

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_next_result() - Prepare next result from multi_query

MysqlndUhConnection::moreResults
MysqlndUhConnection::ping
MysqlndUhConnection


Pings a server connection, or tries to reconnect if the connection has gone down

MysqlndUhConnection::nextResult
MysqlndUhConnection::query
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::ping

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down

Opis

public bool MysqlndUhConnection::ping ( mysqlnd_connection $connection )

Pings a server connection, or tries to reconnect if the connection has gone down.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::ping() example

<?php
class proxy extends MysqlndUhConnection {
 public function ping($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::ping($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ping();
?>

Powyższy przykład wyświetli:

proxy::ping(array (
  0 => NULL,
))
proxy::ping returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_ping() - Pings a server connection, or tries to reconnect if the connection has gone down
  • mysql_ping() - Sprawdza połączenie z serwerem, lub nawiązuje połączenie, jeśli go nie było

MysqlndUhConnection::nextResult
MysqlndUhConnection::query
MysqlndUhConnection


Performs a query on the database

MysqlndUhConnection::ping
MysqlndUhConnection::queryReadResultsetHeader
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::query

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::query — Performs a query on the database

Opis

public bool MysqlndUhConnection::query ( mysqlnd_connection $connection , string $query )

Performs a query on the database (COM_QUERY).

Parametry

connection

Mysqlnd connection handle. Do not modify!

query

The query string.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::query() example

<?php
class proxy extends MysqlndUhConnection {
 public function query($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $query = "SELECT 'How about query rewriting?'";
  $ret = parent::query($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Welcome mysqlnd_uh!' FROM DUAL");
var_dump($res->fetch_assoc());
?>

Powyższy przykład wyświetli:

proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Welcome mysqlnd_uh!\' FROM DUAL',
))
proxy::query returns true
array(1) {
  ["How about query rewriting?"]=>
  string(26) "How about query rewriting?"
}

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_query() - Performs a query on the database
  • mysql_query() - Wysyła zapytanie do serwera MySQL

MysqlndUhConnection::ping
MysqlndUhConnection::queryReadResultsetHeader
MysqlndUhConnection


Read a result set header

MysqlndUhConnection::query
MysqlndUhConnection::reapQuery
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::queryReadResultsetHeader

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::queryReadResultsetHeader — Read a result set header

Opis

public bool MysqlndUhConnection::queryReadResultsetHeader ( mysqlnd_connection $connection , mysqlnd_statement $mysqlnd_stmt )

Read a result set header.

Parametry

connection

Mysqlnd connection handle. Do not modify!

mysqlnd_stmt

Mysqlnd statement handle. Do not modify! Set to NULL, if function is not used in the context of a prepared statement.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::queryReadResultsetHeader() example

<?php
class proxy extends MysqlndUhConnection {
 public function queryReadResultsetHeader($res, $stmt) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::queryReadResultsetHeader($res, $stmt);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Welcome mysqlnd_uh!' FROM DUAL");
var_dump($res->fetch_assoc());
?>

Powyższy przykład wyświetli:

proxy::queryReadResultsetHeader(array (
  0 => NULL,
  1 => NULL,
))
proxy::queryReadResultsetHeader returns true
array(1) {
  ["Welcome mysqlnd_uh!"]=>
  string(19) "Welcome mysqlnd_uh!"
}

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::query
MysqlndUhConnection::reapQuery
MysqlndUhConnection


Get result from async query

MysqlndUhConnection::queryReadResultsetHeader
MysqlndUhConnection::refreshServer
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::reapQuery

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::reapQuery — Get result from async query

Opis

public bool MysqlndUhConnection::reapQuery ( mysqlnd_connection $connection )

Get result from async query.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::reapQuery() example

<?php
class proxy extends MysqlndUhConnection {
 public function reapQuery($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::reapQuery($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$conn1 = new mysqli("localhost", "root", "", "test");
$conn2 = new mysqli("localhost", "root", "", "test");

$conn1->query("SELECT 1 as 'one', SLEEP(1) AS _sleep FROM DUAL", MYSQLI_ASYNC |  MYSQLI_USE_RESULT);
$conn2->query("SELECT 1.1 as 'one dot one' FROM DUAL", MYSQLI_ASYNC |  MYSQLI_USE_RESULT);

$links = array(
 $conn1->thread_id => array('link' => $conn1, 'processed' => false),
 $conn2->thread_id => array('link' => $conn2, 'processed' => false)
);

$saved_errors = array();
do {
 $poll_links = $poll_errors = $poll_reject = array();
 foreach ($links as $thread_id => $link) {
  if (!$link['processed']) {
   $poll_links[] = $link['link'];
   $poll_errors[] = $link['link'];
   $poll_reject[] = $link['link'];
  }
 }
 if (0 == count($poll_links))
  break;

 if (0 == ($num_ready = mysqli_poll($poll_links, $poll_errors, $poll_reject, 0, 200000)))
  continue;

 if (!empty($poll_errors)) {
  die(var_dump($poll_errors));
 }

 foreach ($poll_links as $link) {
  $thread_id = mysqli_thread_id($link);
  $links[$thread_id]['processed'] = true;

  if (is_object($res = mysqli_reap_async_query($link))) {
   // result set object
   while ($row = mysqli_fetch_assoc($res)) {
    // eat up all results
    var_dump($row);
   }
   mysqli_free_result($res);
  } else {
   // either there is no result (no SELECT) or there is an error
   if (mysqli_errno($link) > 0) {
    $saved_errors[$thread_id] = mysqli_errno($link);
    printf("'%s' caused %d\n", $links[$thread_id]['query'],     mysqli_errno($link));
   }
  }
 }
} while (true);
?>

Powyższy przykład wyświetli:

proxy::reapQuery(array (
  0 => NULL,
))
proxy::reapQuery returns true
array(1) {
  ["one dot one"]=>
  string(3) "1.1"
}
proxy::reapQuery(array (
  0 => NULL,
))
proxy::reapQuery returns true
array(2) {
  ["one"]=>
  string(1) "1"
  ["_sleep"]=>
  string(1) "0"
}

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_async_query()

MysqlndUhConnection::queryReadResultsetHeader
MysqlndUhConnection::refreshServer
MysqlndUhConnection


Flush or reset tables and caches

MysqlndUhConnection::reapQuery
MysqlndUhConnection::restartPSession
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::refreshServer

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::refreshServer — Flush or reset tables and caches

Opis

public bool MysqlndUhConnection::refreshServer ( mysqlnd_connection $connection , int $options )

Flush or reset tables and caches.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

connection

Mysqlnd connection handle. Do not modify!

options

What to refresh.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::refreshServer() example

<?php
class proxy extends MysqlndUhConnection {
 public function refreshServer($res, $option) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::refreshServer($res, $option);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
mysqli_refresh($mysqli, 1);
?>

Powyższy przykład wyświetli:

proxy::refreshServer(array (
  0 => NULL,
  1 => 1,
))
proxy::refreshServer returns false

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::reapQuery
MysqlndUhConnection::restartPSession
MysqlndUhConnection


Restart a persistent mysqlnd connection

MysqlndUhConnection::refreshServer
MysqlndUhConnection::selectDb
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::restartPSession

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection

Opis

public bool MysqlndUhConnection::restartPSession ( mysqlnd_connection $connection )

Restart a persistent mysqlnd connection.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::restartPSession() example

<?php
class proxy extends MysqlndUhConnection {
 public function ping($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::ping($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ping();
?>

Powyższy przykład wyświetli:

proxy::restartPSession(array (
  0 => NULL,
))
proxy::restartPSession returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::refreshServer
MysqlndUhConnection::selectDb
MysqlndUhConnection


Selects the default database for database queries

MysqlndUhConnection::restartPSession
MysqlndUhConnection::sendClose
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::selectDb

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::selectDb — Selects the default database for database queries

Opis

public bool MysqlndUhConnection::selectDb ( mysqlnd_connection $connection , string $database )

Selects the default database for database queries.

Parametry

connection

Mysqlnd connection handle. Do not modify!

database

The database name.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::selectDb() example

<?php
class proxy extends MysqlndUhConnection {
 public function selectDb($res, $database) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::selectDb($res, $database);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->select_db("mysql");
?>

Powyższy przykład wyświetli:

proxy::selectDb(array (
  0 => NULL,
  1 => 'mysql',
))
proxy::selectDb returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_select_db() - Selects the default database for database queries
  • mysql_select_db() - Wybiera bazę MySQL

MysqlndUhConnection::restartPSession
MysqlndUhConnection::sendClose
MysqlndUhConnection


Sends a close command to MySQL

MysqlndUhConnection::selectDb
MysqlndUhConnection::sendQuery
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::sendClose

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sendClose — Sends a close command to MySQL

Opis

public bool MysqlndUhConnection::sendClose ( mysqlnd_connection $connection )

Sends a close command to MySQL.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::sendClose() example

<?php
class proxy extends MysqlndUhConnection {
 public function sendClose($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sendClose($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->close();
?>

Powyższy przykład wyświetli:

proxy::sendClose(array (
  0 => NULL,
))
proxy::sendClose returns true
proxy::sendClose(array (
  0 => NULL,
))
proxy::sendClose returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::selectDb
MysqlndUhConnection::sendQuery
MysqlndUhConnection


Sends a query to MySQL

MysqlndUhConnection::sendClose
MysqlndUhConnection::serverDumpDebugInformation
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::sendQuery

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sendQuery — Sends a query to MySQL

Opis

public bool MysqlndUhConnection::sendQuery ( mysqlnd_connection $connection , string $query )

Sends a query to MySQL.

Parametry

connection

Mysqlnd connection handle. Do not modify!

query

The query string.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::sendQuery() example

<?php
class proxy extends MysqlndUhConnection {
 public function sendQuery($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sendQuery($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 1");
?>

Powyższy przykład wyświetli:

proxy::sendQuery(array (
  0 => NULL,
  1 => 'SELECT 1',
))
proxy::sendQuery returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::sendClose
MysqlndUhConnection::serverDumpDebugInformation
MysqlndUhConnection


Dump debugging information into the log for the MySQL server

MysqlndUhConnection::sendQuery
MysqlndUhConnection::setAutocommit
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::serverDumpDebugInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server

Opis

public bool MysqlndUhConnection::serverDumpDebugInformation ( mysqlnd_connection $connection )

Dump debugging information into the log for the MySQL server.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::serverDumpDebugInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function serverDumpDebugInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::serverDumpDebugInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->dump_debug_info();
?>

Powyższy przykład wyświetli:

proxy::serverDumpDebugInformation(array (
  0 => NULL,
))
proxy::serverDumpDebugInformation returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_dump_debug_info() - Dump debugging information into the log

MysqlndUhConnection::sendQuery
MysqlndUhConnection::setAutocommit
MysqlndUhConnection


Turns on or off auto-commiting database modifications

MysqlndUhConnection::serverDumpDebugInformation
MysqlndUhConnection::setCharset
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::setAutocommit

(PECL mysqlnd-uh >= 1.0.1-alpha, PHP >= 5.4.0)

MysqlndUhConnection::setAutocommit — Turns on or off auto-commiting database modifications

Opis

public bool MysqlndUhConnection::setAutocommit ( mysqlnd_connection $connection , int $mode )

Turns on or off auto-commiting database modifications

Parametry

connection

Mysqlnd connection handle. Do not modify!

mode

Whether to turn on auto-commit or not.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::setAutocommit() example

<?php
class proxy extends MysqlndUhConnection {
 public function setAutocommit($res, $mode) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::setAutocommit($res, $mode);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->autocommit(false);
$mysqli->autocommit(true);
?>

Powyższy przykład wyświetli:

proxy::setAutocommit(array (
  0 => NULL,
  1 => 0,
))
proxy::setAutocommit returns true
proxy::setAutocommit(array (
  0 => NULL,
  1 => 1,
))
proxy::setAutocommit returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_autocommit() - Turns on or off auto-commiting database modifications

MysqlndUhConnection::serverDumpDebugInformation
MysqlndUhConnection::setCharset
MysqlndUhConnection


Sets the default client character set

MysqlndUhConnection::setAutocommit
MysqlndUhConnection::setClientOption
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::setCharset

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setCharset — Sets the default client character set

Opis

public bool MysqlndUhConnection::setCharset ( mysqlnd_connection $connection , string $charset )

Sets the default client character set.

Parametry

connection

Mysqlnd connection handle. Do not modify!

charset

The charset to be set as default.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::setCharset() example

<?php
class proxy extends MysqlndUhConnection {
 public function setCharset($res, $charset) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::setCharset($res, $charset);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->set_charset("latin1");
?>

Powyższy przykład wyświetli:

proxy::setCharset(array (
  0 => NULL,
  1 => 'latin1',
))
proxy::setCharset returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_set_charset() - Sets the default client character set

MysqlndUhConnection::setAutocommit
MysqlndUhConnection::setClientOption
MysqlndUhConnection


Sets a client option

MysqlndUhConnection::setCharset
MysqlndUhConnection::setServerOption
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::setClientOption

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setClientOption — Sets a client option

Opis

public bool MysqlndUhConnection::setClientOption ( mysqlnd_connection $connection , int $option , int $value )

Sets a client option.

Parametry

connection

Mysqlnd connection handle. Do not modify!

option

The option to be set.

value

Optional option value, if required.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::setClientOption() example

<?php
function client_option_to_string($option) {
 static $mapping = array(
  MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT => "MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS => "MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS",
  MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE => "MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE",
  MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND => "MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND",
  MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE => "MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE",
  MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP => "MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP",
  MYSQLND_UH_MYSQLND_SET_CHARSET_DIR => "MYSQLND_UH_MYSQLND_SET_CHARSET_DIR",
  MYSQLND_UH_MYSQLND_SET_CHARSET_NAME => "MYSQLND_UH_MYSQLND_SET_CHARSET_NAME",
  MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE => "MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE",
  MYSQLND_UH_MYSQLND_OPT_PROTOCOL => "MYSQLND_UH_MYSQLND_OPT_PROTOCOL",
  MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME => "MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME",
  MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT => "MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT => "MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPT_USE_RESULT => "MYSQLND_UH_MYSQLND_OPT_USE_RESULT",
  MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION",
  MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION",
  MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION",
  MYSQLND_UH_MYSQLND_SET_CLIENT_IP => "MYSQLND_UH_MYSQLND_SET_CLIENT_IP",
  MYSQLND_UH_MYSQLND_SECURE_AUTH => "MYSQLND_UH_MYSQLND_SECURE_AUTH",
  MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION => "MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION",
  MYSQLND_UH_MYSQLND_OPT_RECONNECT => "MYSQLND_UH_MYSQLND_OPT_RECONNECT",
  MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT => "MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT",
  MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE => "MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE",
  MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE => "MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE",
  MYSQLND_UH_MYSQLND_OPT_SSL_KEY => "MYSQLND_UH_MYSQLND_OPT_SSL_KEY",
  MYSQLND_UH_MYSQLND_OPT_SSL_CERT => "MYSQLND_UH_MYSQLND_OPT_SSL_CERT",
  MYSQLND_UH_MYSQLND_OPT_SSL_CA => "MYSQLND_UH_MYSQLND_OPT_SSL_CA",
  MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH => "MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH",
  MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER => "MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER",
  MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE => "MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE",
  MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR => "MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR",
  MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH => "MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH",
  MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP => "MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP"
 );
 if (version_compare(PHP_VERSION, '5.3.99-dev', '>')) {
  $mapping[MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET] = "MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET";
  $mapping[MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL] = "MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL";
 }
 if (defined("MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE")) {
  /* special mysqlnd build */
  $mapping["MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE"] = "MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE";
 }
 return (isset($mapping[$option])) ? $mapping[$option] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function setClientOption($res, $option, $value) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Option '%s' set to %s\n", client_option_to_string($option), var_export($value, true));
  $ret = parent::setClientOption($res, $option, $value);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

Powyższy przykład wyświetli:

proxy::setClientOption(array (
  0 => NULL,
  1 => 210,
  2 => 3221225472,
))
Option 'MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET' set to 3221225472
proxy::setClientOption returns true
proxy::setClientOption(array (
  0 => NULL,
  1 => 211,
  2 => 'mysql_native_password',
))
Option 'MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL' set to 'mysql_native_password'
proxy::setClientOption returns true
proxy::setClientOption(array (
  0 => NULL,
  1 => 8,
  2 => 1,
))
Option 'MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE' set to 1
proxy::setClientOption returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options

MysqlndUhConnection::setCharset
MysqlndUhConnection::setServerOption
MysqlndUhConnection


Sets a server option

MysqlndUhConnection::setClientOption
MysqlndUhConnection::shutdownServer
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::setServerOption

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setServerOption — Sets a server option

Opis

public void MysqlndUhConnection::setServerOption ( mysqlnd_connection $connection , int $option )

Sets a server option.

Parametry

connection

Mysqlnd connection handle. Do not modify!

option

The option to be set.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::setServerOption() example

<?php
function server_option_to_string($option) {
 $ret = 'unknown';
 switch ($option) {
  case MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON:
   $ret = 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON';
   break;
  case MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_OFF:
   $ret = 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON';
   break;
 }
 return $ret;
}

class proxy extends MysqlndUhConnection {
 public function setServerOption($res, $option) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Option '%s' set\n", server_option_to_string($option));
  $ret = parent::setServerOption($res, $option);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1; SELECT 2");
?>

Powyższy przykład wyświetli:

proxy::setServerOption(array (
  0 => NULL,
  1 => 0,
))
Option 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON' set
proxy::setServerOption returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options
  • mysqli_multi_query() - Performs a query on the database

MysqlndUhConnection::setClientOption
MysqlndUhConnection::shutdownServer
MysqlndUhConnection


The shutdownServer purpose

MysqlndUhConnection::setServerOption
MysqlndUhConnection::simpleCommand
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::shutdownServer

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::shutdownServer — The shutdownServer purpose

Opis

public void MysqlndUhConnection::shutdownServer ( string $MYSQLND_UH_RES_MYSQLND_NAME , string $"level" )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

MYSQLND_UH_RES_MYSQLND_NAME

"level"

Zwracane wartości

MysqlndUhConnection::setServerOption
MysqlndUhConnection::simpleCommand
MysqlndUhConnection


Sends a basic COM_* command

MysqlndUhConnection::shutdownServer
MysqlndUhConnection::simpleCommandHandleResponse
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::simpleCommand

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::simpleCommand — Sends a basic COM_* command

Opis

public bool MysqlndUhConnection::simpleCommand ( mysqlnd_connection $connection , int $command , string $arg , int $ok_packet , bool $silent , bool $ignore_upsert_status )

Sends a basic COM_* command to MySQL.

Parametry

connection

Mysqlnd connection handle. Do not modify!

command

The COM command to be send.

arg

Optional COM command arguments.

ok_packet

The OK packet type.

silent

Whether mysqlnd may emit errors.

ignore_upsert_status

Whether to ignore UPDATE/INSERT status.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::simpleCommand() example

<?php
function server_cmd_2_string($command) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_COM_SLEEP => "MYSQLND_UH_MYSQLND_COM_SLEEP",
  MYSQLND_UH_MYSQLND_COM_QUIT => "MYSQLND_UH_MYSQLND_COM_QUIT",
  MYSQLND_UH_MYSQLND_COM_INIT_DB => "MYSQLND_UH_MYSQLND_COM_INIT_DB",
  MYSQLND_UH_MYSQLND_COM_QUERY => "MYSQLND_UH_MYSQLND_COM_QUERY",
  MYSQLND_UH_MYSQLND_COM_FIELD_LIST => "MYSQLND_UH_MYSQLND_COM_FIELD_LIST",
  MYSQLND_UH_MYSQLND_COM_CREATE_DB => "MYSQLND_UH_MYSQLND_COM_CREATE_DB",
  MYSQLND_UH_MYSQLND_COM_DROP_DB => "MYSQLND_UH_MYSQLND_COM_DROP_DB",
  MYSQLND_UH_MYSQLND_COM_REFRESH => "MYSQLND_UH_MYSQLND_COM_REFRESH",
  MYSQLND_UH_MYSQLND_COM_SHUTDOWN => "MYSQLND_UH_MYSQLND_COM_SHUTDOWN",
  MYSQLND_UH_MYSQLND_COM_STATISTICS => "MYSQLND_UH_MYSQLND_COM_STATISTICS",
  MYSQLND_UH_MYSQLND_COM_PROCESS_INFO => "MYSQLND_UH_MYSQLND_COM_PROCESS_INFO",
  MYSQLND_UH_MYSQLND_COM_CONNECT => "MYSQLND_UH_MYSQLND_COM_CONNECT",
  MYSQLND_UH_MYSQLND_COM_PROCESS_KILL => "MYSQLND_UH_MYSQLND_COM_PROCESS_KILL",
  MYSQLND_UH_MYSQLND_COM_DEBUG => "MYSQLND_UH_MYSQLND_COM_DEBUG",
  MYSQLND_UH_MYSQLND_COM_PING => "MYSQLND_UH_MYSQLND_COM_PING",
  MYSQLND_UH_MYSQLND_COM_TIME => "MYSQLND_UH_MYSQLND_COM_TIME",
  MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT => "MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT",
  MYSQLND_UH_MYSQLND_COM_CHANGE_USER => "MYSQLND_UH_MYSQLND_COM_CHANGE_USER",
  MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP => "MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP",
  MYSQLND_UH_MYSQLND_COM_TABLE_DUMP => "MYSQLND_UH_MYSQLND_COM_TABLE_DUMP",
  MYSQLND_UH_MYSQLND_COM_CONNECT_OUT => "MYSQLND_UH_MYSQLND_COM_CONNECT_OUT",
  MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED => "MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED",
  MYSQLND_UH_MYSQLND_COM_STMT_PREPARE => "MYSQLND_UH_MYSQLND_COM_STMT_PREPARE",
  MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE => "MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE",
  MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA => "MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA",
  MYSQLND_UH_MYSQLND_COM_STMT_CLOSE => "MYSQLND_UH_MYSQLND_COM_STMT_CLOSE",
  MYSQLND_UH_MYSQLND_COM_STMT_RESET => "MYSQLND_UH_MYSQLND_COM_STMT_RESET",
  MYSQLND_UH_MYSQLND_COM_SET_OPTION => "MYSQLND_UH_MYSQLND_COM_SET_OPTION",
  MYSQLND_UH_MYSQLND_COM_STMT_FETCH => "MYSQLND_UH_MYSQLND_COM_STMT_FETCH",
  MYSQLND_UH_MYSQLND_COM_DAEMON => "MYSQLND_UH_MYSQLND_COM_DAEMON",
  MYSQLND_UH_MYSQLND_COM_END => "MYSQLND_UH_MYSQLND_COM_END",
 );
 return (isset($mapping[$command])) ? $mapping[$command] : 'unknown';
}

function ok_packet_2_string($ok_packet) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_PROT_GREET_PACKET => "MYSQLND_UH_MYSQLND_PROT_GREET_PACKET",
  MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET => "MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET",
  MYSQLND_UH_MYSQLND_PROT_OK_PACKET => "MYSQLND_UH_MYSQLND_PROT_OK_PACKET",
  MYSQLND_UH_MYSQLND_PROT_EOF_PACKET => "MYSQLND_UH_MYSQLND_PROT_EOF_PACKET",
  MYSQLND_UH_MYSQLND_PROT_CMD_PACKET => "MYSQLND_UH_MYSQLND_PROT_CMD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_ROW_PACKET => "MYSQLND_UH_MYSQLND_PROT_ROW_PACKET",
  MYSQLND_UH_MYSQLND_PROT_STATS_PACKET => "MYSQLND_UH_MYSQLND_PROT_STATS_PACKET",
  MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET => "MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET",
  MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET => "MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET",
  MYSQLND_UH_MYSQLND_PROT_LAST => "MYSQLND_UH_MYSQLND_PROT_LAST",
 );
 return (isset($mapping[$ok_packet])) ? $mapping[$ok_packet] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function simpleCommand($conn, $command, $arg, $ok_packet, $silent, $ignore_upsert_status) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Command '%s'\n", server_cmd_2_string($command));
  printf("OK packet '%s'\n",  ok_packet_2_string($ok_packet));
  $ret = parent::simpleCommand($conn, $command, $arg, $ok_packet, $silent, $ignore_upsert_status);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 1");
?>

Powyższy przykład wyświetli:

proxy::simpleCommand(array (
  0 => NULL,
  1 => 3,
  2 => 'SELECT 1',
  3 => 13,
  4 => false,
  5 => false,
))
Command 'MYSQLND_UH_MYSQLND_COM_QUERY'
OK packet 'MYSQLND_UH_MYSQLND_PROT_LAST'
proxy::simpleCommand returns true
:)proxy::simpleCommand(array (
  0 => NULL,
  1 => 1,
  2 => '',
  3 => 13,
  4 => true,
  5 => true,
))
Command 'MYSQLND_UH_MYSQLND_COM_QUIT'
OK packet 'MYSQLND_UH_MYSQLND_PROT_LAST'
proxy::simpleCommand returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::shutdownServer
MysqlndUhConnection::simpleCommandHandleResponse
MysqlndUhConnection


Process a response for a basic COM_* command send to the client

MysqlndUhConnection::simpleCommand
MysqlndUhConnection::sslSet
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::simpleCommandHandleResponse

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client

Opis

public bool MysqlndUhConnection::simpleCommandHandleResponse ( mysqlnd_connection $connection , int $ok_packet , bool $silent , int $command , bool $ignore_upsert_status )

Process a response for a basic COM_* command send to the client.

Parametry

connection

Mysqlnd connection handle. Do not modify!

ok_packet

The OK packet type.

silent

Whether mysqlnd may emit errors.

command

The COM command to process results from.

ignore_upsert_status

Whether to ignore UPDATE/INSERT status.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::simpleCommandHandleResponse() example

<?php
function server_cmd_2_string($command) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_COM_SLEEP => "MYSQLND_UH_MYSQLND_COM_SLEEP",
  MYSQLND_UH_MYSQLND_COM_QUIT => "MYSQLND_UH_MYSQLND_COM_QUIT",
  MYSQLND_UH_MYSQLND_COM_INIT_DB => "MYSQLND_UH_MYSQLND_COM_INIT_DB",
  MYSQLND_UH_MYSQLND_COM_QUERY => "MYSQLND_UH_MYSQLND_COM_QUERY",
  MYSQLND_UH_MYSQLND_COM_FIELD_LIST => "MYSQLND_UH_MYSQLND_COM_FIELD_LIST",
  MYSQLND_UH_MYSQLND_COM_CREATE_DB => "MYSQLND_UH_MYSQLND_COM_CREATE_DB",
  MYSQLND_UH_MYSQLND_COM_DROP_DB => "MYSQLND_UH_MYSQLND_COM_DROP_DB",
  MYSQLND_UH_MYSQLND_COM_REFRESH => "MYSQLND_UH_MYSQLND_COM_REFRESH",
  MYSQLND_UH_MYSQLND_COM_SHUTDOWN => "MYSQLND_UH_MYSQLND_COM_SHUTDOWN",
  MYSQLND_UH_MYSQLND_COM_STATISTICS => "MYSQLND_UH_MYSQLND_COM_STATISTICS",
  MYSQLND_UH_MYSQLND_COM_PROCESS_INFO => "MYSQLND_UH_MYSQLND_COM_PROCESS_INFO",
  MYSQLND_UH_MYSQLND_COM_CONNECT => "MYSQLND_UH_MYSQLND_COM_CONNECT",
  MYSQLND_UH_MYSQLND_COM_PROCESS_KILL => "MYSQLND_UH_MYSQLND_COM_PROCESS_KILL",
  MYSQLND_UH_MYSQLND_COM_DEBUG => "MYSQLND_UH_MYSQLND_COM_DEBUG",
  MYSQLND_UH_MYSQLND_COM_PING => "MYSQLND_UH_MYSQLND_COM_PING",
  MYSQLND_UH_MYSQLND_COM_TIME => "MYSQLND_UH_MYSQLND_COM_TIME",
  MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT => "MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT",
  MYSQLND_UH_MYSQLND_COM_CHANGE_USER => "MYSQLND_UH_MYSQLND_COM_CHANGE_USER",
  MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP => "MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP",
  MYSQLND_UH_MYSQLND_COM_TABLE_DUMP => "MYSQLND_UH_MYSQLND_COM_TABLE_DUMP",
  MYSQLND_UH_MYSQLND_COM_CONNECT_OUT => "MYSQLND_UH_MYSQLND_COM_CONNECT_OUT",
  MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED => "MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED",
  MYSQLND_UH_MYSQLND_COM_STMT_PREPARE => "MYSQLND_UH_MYSQLND_COM_STMT_PREPARE",
  MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE => "MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE",
  MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA => "MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA",
  MYSQLND_UH_MYSQLND_COM_STMT_CLOSE => "MYSQLND_UH_MYSQLND_COM_STMT_CLOSE",
  MYSQLND_UH_MYSQLND_COM_STMT_RESET => "MYSQLND_UH_MYSQLND_COM_STMT_RESET",
  MYSQLND_UH_MYSQLND_COM_SET_OPTION => "MYSQLND_UH_MYSQLND_COM_SET_OPTION",
  MYSQLND_UH_MYSQLND_COM_STMT_FETCH => "MYSQLND_UH_MYSQLND_COM_STMT_FETCH",
  MYSQLND_UH_MYSQLND_COM_DAEMON => "MYSQLND_UH_MYSQLND_COM_DAEMON",
  MYSQLND_UH_MYSQLND_COM_END => "MYSQLND_UH_MYSQLND_COM_END",
 );
 return (isset($mapping[$command])) ? $mapping[$command] : 'unknown';
}

function ok_packet_2_string($ok_packet) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_PROT_GREET_PACKET => "MYSQLND_UH_MYSQLND_PROT_GREET_PACKET",
  MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET => "MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET",
  MYSQLND_UH_MYSQLND_PROT_OK_PACKET => "MYSQLND_UH_MYSQLND_PROT_OK_PACKET",
  MYSQLND_UH_MYSQLND_PROT_EOF_PACKET => "MYSQLND_UH_MYSQLND_PROT_EOF_PACKET",
  MYSQLND_UH_MYSQLND_PROT_CMD_PACKET => "MYSQLND_UH_MYSQLND_PROT_CMD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_ROW_PACKET => "MYSQLND_UH_MYSQLND_PROT_ROW_PACKET",
  MYSQLND_UH_MYSQLND_PROT_STATS_PACKET => "MYSQLND_UH_MYSQLND_PROT_STATS_PACKET",
  MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET => "MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET",
  MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET => "MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET",
  MYSQLND_UH_MYSQLND_PROT_LAST => "MYSQLND_UH_MYSQLND_PROT_LAST",
 );
 return (isset($mapping[$ok_packet])) ? $mapping[$ok_packet] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function simpleCommandHandleResponse($conn, $ok_packet, $silent, $command, $ignore_upsert_status) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Command '%s'\n", server_cmd_2_string($command));
  printf("OK packet '%s'\n",  ok_packet_2_string($ok_packet));
  $ret = parent::simpleCommandHandleResponse($conn, $ok_packet, $silent, $command, $ignore_upsert_status);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysql = mysql_connect("localhost", "root", "");
mysql_query("SELECT 1 FROM DUAL", $mysql);
?>

Powyższy przykład wyświetli:

proxy::simpleCommandHandleResponse(array (
  0 => NULL,
  1 => 5,
  2 => false,
  3 => 27,
  4 => true,
))
Command 'MYSQLND_UH_MYSQLND_COM_SET_OPTION'
OK packet 'MYSQLND_UH_MYSQLND_PROT_EOF_PACKET'
proxy::simpleCommandHandleResponse returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections

MysqlndUhConnection::simpleCommand
MysqlndUhConnection::sslSet
MysqlndUhConnection


Used for establishing secure connections using SSL

MysqlndUhConnection::simpleCommandHandleResponse
MysqlndUhConnection::stmtInit
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::sslSet

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL

Opis

public bool MysqlndUhConnection::sslSet ( mysqlnd_connection $connection , string $key , string $cert , string $ca , string $capath , string $cipher )

Used for establishing secure connections using SSL.

Parametry

connection

Mysqlnd connection handle. Do not modify!

key

The path name to the key file.

cert

The path name to the certificate file.

ca

The path name to the certificate authority file.

capath

The pathname to a directory that contains trusted SSL CA certificates in PEM format.

cipher

A list of allowable ciphers to use for SSL encryption.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::sslSet() example

<?php
class proxy extends MysqlndUhConnection {
 public function sslSet($conn, $key, $cert, $ca, $capth, $cipher) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sslSet($conn, $key, $cert, $ca, $capth, $cipher);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ssl_set("key", "cert", "ca", "capath", "cipher");
?>

Powyższy przykład wyświetli:

proxy::sslSet(array (
  0 => NULL,
  1 => 'key',
  2 => 'cert',
  3 => 'ca',
  4 => 'capath',
  5 => 'cipher',
))
proxy::sslSet returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_ssl_set() - Used for establishing secure connections using SSL

MysqlndUhConnection::simpleCommandHandleResponse
MysqlndUhConnection::stmtInit
MysqlndUhConnection


Initializes a statement and returns a resource for use with mysqli_statement::prepare

MysqlndUhConnection::sslSet
MysqlndUhConnection::storeResult
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::stmtInit

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare

Opis

public resource MysqlndUhConnection::stmtInit ( mysqlnd_connection $connection )

Initializes a statement and returns a resource for use with mysqli_statement::prepare.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_prepared_statement.

Przykłady

Przykład #1 MysqlndUhConnection::stmtInit() example

<?php
class proxy extends MysqlndUhConnection {
 public function stmtInit($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  var_dump($res);
  $ret = parent::stmtInit($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 1 AS _one FROM DUAL");
$stmt->execute();
$one = NULL;
$stmt->bind_result($one);
$stmt->fetch();
var_dump($one);
?>

Powyższy przykład wyświetli:

proxy::stmtInit(array (
  0 => NULL,
))
resource(19) of type (Mysqlnd Connection)
proxy::stmtInit returns NULL
resource(246) of type (Mysqlnd Prepared Statement (internal only - you must not modify it!))
int(1)

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare

MysqlndUhConnection::sslSet
MysqlndUhConnection::storeResult
MysqlndUhConnection


Transfers a result set from the last query

MysqlndUhConnection::stmtInit
MysqlndUhConnection::txCommit
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::storeResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::storeResult — Transfers a result set from the last query

Opis

public resource MysqlndUhConnection::storeResult ( mysqlnd_connection $connection )

Transfers a result set from the last query.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Resource of type Mysqlnd Resultset (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_resultset.

Przykłady

Przykład #1 MysqlndUhConnection::storeResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function storeResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::storeResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Also called buffered result' AS _msg FROM DUAL");
var_dump($res->fetch_assoc());

$mysqli->real_query("SELECT 'Good morning!' AS _msg FROM DUAL");
$res = $mysqli->store_result();
var_dump($res->fetch_assoc());
?>

Powyższy przykład wyświetli:

proxy::storeResult(array (
  0 => NULL,
))
proxy::storeResult returns NULL
resource(475) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(27) "Also called buffered result"
}
proxy::storeResult(array (
  0 => NULL,
))
proxy::storeResult returns NULL
resource(730) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(13) "Good morning!"
}

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_real_query() - Execute an SQL query

MysqlndUhConnection::stmtInit
MysqlndUhConnection::txCommit
MysqlndUhConnection


Commits the current transaction

MysqlndUhConnection::storeResult
MysqlndUhConnection::txRollback
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::txCommit

(PECL mysqlnd-uh >= 1.0.1-alpha, PHP >= 5.4.0)

MysqlndUhConnection::txCommit — Commits the current transaction

Opis

public bool MysqlndUhConnection::txCommit ( mysqlnd_connection $connection )

Commits the current transaction.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::txCommit() example

<?php
class proxy extends MysqlndUhConnection {
 public function txCommit($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::txCommit($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->commit();
?>

Powyższy przykład wyświetli:

proxy::txCommit(array (
  0 => NULL,
))
proxy::txCommit returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_commit() - Commits the current transaction

MysqlndUhConnection::storeResult
MysqlndUhConnection::txRollback
MysqlndUhConnection


Rolls back current transaction

MysqlndUhConnection::txCommit
MysqlndUhConnection::useResult
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::txRollback

(PECL mysqlnd-uh >= 1.0.1-alpha, PHP >= 5.4.0)

MysqlndUhConnection::txRollback — Rolls back current transaction

Opis

public bool MysqlndUhConnection::txRollback ( mysqlnd_connection $connection )

Rolls back current transaction.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhConnection::txRollback() example

<?php
class proxy extends MysqlndUhConnection {
 public function txRollback($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::txRollback($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->rollback();
?>

Powyższy przykład wyświetli:

proxy::txRollback(array (
  0 => NULL,
))
proxy::txRollback returns true

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_commit() - Commits the current transaction

MysqlndUhConnection::txCommit
MysqlndUhConnection::useResult
MysqlndUhConnection


Initiate a result set retrieval

MysqlndUhConnection::txRollback
MysqlndUhPreparedStatement
MysqlndUhConnection
PHP Manual

MysqlndUhConnection::useResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::useResult — Initiate a result set retrieval

Opis

public resource MysqlndUhConnection::useResult ( mysqlnd_connection $connection )

Initiate a result set retrieval.

Parametry

connection

Mysqlnd connection handle. Do not modify!

Zwracane wartości

Resource of type Mysqlnd Resultset (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_resultset.

Przykłady

Przykład #1 MysqlndUhConnection::useResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function useResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::useResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->real_query("SELECT 'Good morning!' AS _msg FROM DUAL");
$res = $mysqli->use_result();
var_dump($res->fetch_assoc());
?>

Powyższy przykład wyświetli:

proxy::useResult(array (
  0 => NULL,
))
proxy::useResult returns NULL
resource(425) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(13) "Good morning!"
}

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_real_query() - Execute an SQL query

MysqlndUhConnection::txRollback
MysqlndUhPreparedStatement
MysqlndUhConnection


The MysqlndUhPreparedStatement class

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

Wstęp

Krótki opis klasy

MysqlndUhPreparedStatement {
/* Metody */
public __construct ( void )
public bool execute ( mysqlnd_prepared_statement $statement )
public bool prepare ( mysqlnd_prepared_statement $statement , string $query )
}

Spis treści

  • MysqlndUhPreparedStatement::__construct — The __construct purpose
  • MysqlndUhPreparedStatement::execute — Executes a prepared Query
  • MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution
MysqlndUhConnection::useResult
MysqlndUhPreparedStatement::__construct
mysqlnd_uh


The __construct purpose

MysqlndUhPreparedStatement
MysqlndUhPreparedStatement::execute
MysqlndUhPreparedStatement
PHP Manual

MysqlndUhPreparedStatement::__construct

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::__construct — The __construct purpose

Opis

public MysqlndUhPreparedStatement::__construct ( 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

MysqlndUhPreparedStatement
MysqlndUhPreparedStatement::execute
MysqlndUhPreparedStatement


Executes a prepared Query

MysqlndUhPreparedStatement::__construct
MysqlndUhPreparedStatement::prepare
MysqlndUhPreparedStatement
PHP Manual

MysqlndUhPreparedStatement::execute

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::execute — Executes a prepared Query

Opis

public bool MysqlndUhPreparedStatement::execute ( mysqlnd_prepared_statement $statement )

Executes a prepared Query.

Parametry

statement

Mysqlnd prepared statement handle. Do not modify! Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!).

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhPreparedStatement::execute() example

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function execute($res) {
  printf("%s(", __METHOD__);
  var_dump($res);
  printf(")\n");
  $ret = parent::execute($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'Labskaus' AS _msg FROM DUAL");
$stmt->execute();
$msg = NULL;
$stmt->bind_result($msg);
$stmt->fetch();
var_dump($msg);
?>

Powyższy przykład wyświetli:

stmt_proxy::execute(resource(256) of type (Mysqlnd Prepared Statement (internal only - you must not modify it!))
)
stmt_proxy::execute returns true
bool(true)
string(8) "Labskaus"

Zobacz też:

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqli_stmt_execute() - Executes a prepared Query

MysqlndUhPreparedStatement::__construct
MysqlndUhPreparedStatement::prepare
MysqlndUhPreparedStatement


Prepare an SQL statement for execution

MysqlndUhPreparedStatement::execute
Mysqlnd_uh Funkcje
MysqlndUhPreparedStatement
PHP Manual

MysqlndUhPreparedStatement::prepare

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution

Opis

public bool MysqlndUhPreparedStatement::prepare ( mysqlnd_prepared_statement $statement , string $query )

Prepare an SQL statement for execution.

Parametry

statement

Mysqlnd prepared statement handle. Do not modify! Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!).

query

The query to be prepared.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 MysqlndUhPreparedStatement::prepare() example

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $query = "SELECT 'No more you-know-what-I-mean for lunch, please' AS _msg FROM DUAL";
  $ret = parent::prepare($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'Labskaus' AS _msg FROM DUAL");
$stmt->execute();
$msg = NULL;
$stmt->bind_result($msg);
$stmt->fetch();
var_dump($msg);
?>

Powyższy przykład wyświetli:

stmt_proxy::prepare(array (
  0 => NULL,
  1 => 'SELECT \'Labskaus\' AS _msg FROM DUAL',
))
stmt_proxy::prepare returns true
bool(true)
string(46) "No more you-know-what-I-mean for lunch, please"

Zobacz też:

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqli_stmt_prepare() - Prepare an SQL statement for execution
  • mysqli_prepare() - Prepare an SQL statement for execution

MysqlndUhPreparedStatement::execute
Mysqlnd_uh Funkcje
MysqlndUhPreparedStatement


Mysqlnd_uh Funkcje

Spis treści

  • mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle
  • mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections
  • mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements
MysqlndUhPreparedStatement::prepare
mysqlnd_uh_convert_to_mysqlnd
mysqlnd_uh


Converts a MySQL connection handle into a mysqlnd connection handle

Mysqlnd_uh Funkcje
mysqlnd_uh_set_connection_proxy
Mysqlnd_uh Funkcje
PHP Manual

mysqlnd_uh_convert_to_mysqlnd

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle

Opis

resource mysqlnd_uh_convert_to_mysqlnd ( mysqli &$mysql_connection )

Converts a MySQL connection handle into a mysqlnd connection handle. After conversion you can execute mysqlnd library calls on the connection handle. This can be used to access mysqlnd functionality not made available through user space API calls.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_convert_to_mysqlnd(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. You are not allowed to call this function [...].

Parametry

MySQL connection handle

A MySQL connection handle of type mysql, mysqli or PDO_MySQL.

Informacja:

The MySQL connection handle can be of no other type but mysqli if using PHP < 5.4.0.

Zwracane wartości

A mysqlnd connection handle.

Przykłady

Przykład #1 mysqlnd_uh_convert_to_mysqlnd() example

<?php
/* PDO user API gives no access to connection thread id */
$mysql_connection = new PDO("mysql:host=localhost;dbname=test", "root", "");

/* Convert PDO MySQL handle to mysqlnd handle */
$mysqlnd = mysqlnd_uh_convert_to_mysqlnd($mysql_connection);

/* Create Proxy to call mysqlnd connection class methods */
$obj = new MySQLndUHConnection();
/* Call mysqlnd_conn::get_thread_id */
var_dump($obj->getThreadId($mysqlnd));

/* Use SQL to fetch connection thread id */
var_dump($mysql_connection->query("SELECT CONNECTION_ID()")->fetchAll());
?>

Powyższy przykład wyświetli:

int(27054)
array(1) {
  [0]=>
  array(2) {
    ["CONNECTION_ID()"]=>
    string(5) "27054"
    [0]=>
    string(5) "27054"
  }
}

Zobacz też:

  • mysqlnd_uh.enable

Mysqlnd_uh Funkcje
mysqlnd_uh_set_connection_proxy
Mysqlnd_uh Funkcje


Installs a proxy for mysqlnd connections

mysqlnd_uh_convert_to_mysqlnd
mysqlnd_uh_set_statement_proxy
Mysqlnd_uh Funkcje
PHP Manual

mysqlnd_uh_set_connection_proxy

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections

Opis

bool mysqlnd_uh_set_connection_proxy ( MysqlndUhConnection &$connection_proxy [, mysqli &$mysqli_connection ] )

Installs a proxy object to hook mysqlnd's connection objects methods. Once installed, the proxy will be used for all MySQL connections opened with mysqli, mysql or PDO_MYSQL, assuming that the listed extensions are compiled to use the mysqlnd library.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_set_connection_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed [...].

Parametry

connection_proxy

A proxy object of type MysqlndUhConnection.

mysqli_connection

Object of type mysqli. If given, the proxy will be set for this particular connection only.

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Przykłady

Przykład #1 mysqlnd_uh_set_connection_proxy() example

<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 'No proxy installed, yet'");

class proxy extends MysqlndUhConnection {
 public function query($res, $query) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::query($res, $query);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli->query("SELECT 'mysqlnd rocks!'");

$mysql = mysql_connect("localhost", "root", "", "test");
mysql_query("SELECT 'Ahoy Andrey!'", $mysql);

$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$pdo->query("SELECT 'Moin Johannes!'");
?>

Powyższy przykład wyświetli:

proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'mysqlnd rocks!\'',
))
proxy::query returns true
proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Ahoy Andrey!\'',
))
proxy::query returns true
proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Moin Johannes!\'',
))
proxy::query returns true

Zobacz też:

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqlnd_uh.enable

mysqlnd_uh_convert_to_mysqlnd
mysqlnd_uh_set_statement_proxy
Mysqlnd_uh Funkcje


Installs a proxy for mysqlnd statements

mysqlnd_uh_set_connection_proxy
Change History
Mysqlnd_uh Funkcje
PHP Manual

mysqlnd_uh_set_statement_proxy

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements

Opis

bool mysqlnd_uh_set_statement_proxy ( MysqlndUhStatement &$statement_proxy )

Installs a proxy for mysqlnd statements. The proxy object will be used for all mysqlnd prepared statement objects, regardless which PHP MySQL extension (mysqli, mysql, PDO_MYSQL) has created them as long as the extension is compiled to use the mysqlnd library.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_set_statement_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed [...].

Parametry

statement_proxy

The mysqlnd statement proxy object of type MysqlndUhStatement

Zwracane wartości

Returns TRUE on success. Otherwise, returns FALSE

Zobacz też:

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqlnd_uh.enable

mysqlnd_uh_set_connection_proxy
Change History
Mysqlnd_uh Funkcje


Change History

Spis treści

  • PECL/mysqlnd_uh 1.0 series

The Change History lists major changes users need to be aware if upgrading from one version to another. It is a high level summary of selected changes that may impact applications or might even break backwards compatibility. Please, consult the CHANGES file contained in the source distribution for a more complete list of changes. If you are eager to learn about all changes, even smaller ones that do not make it into the CHANGES file, you may want to monitor PECL commit messages. To do you, you could, for example, subscribe to the PECL commit message mailing list.

mysqlnd_uh_set_statement_proxy
PECL/mysqlnd_uh 1.0 series
mysqlnd_uh


PECL/mysqlnd_uh 1.0 series

1.0.1-alpha

  • Release date: TBD
  • Motto/theme: bug fix release

Feature changes

  • Support of PHP 5.4.0 or later.
  • BC break: MysqlndUhConnection::changeUser() requires additional passwd_len parameter.
  • BC break: MYSQLND_UH_VERSION_STR renamed to MYSQLND_UH_VERSION. MYSQLND_UH_VERSION renamed to MYSQLND_UH_VERSION_ID.
  • BC break: mysqlnd_uh.enabled configuration setting renamed to mysqlnd_uh.enable.

1.0.0-alpha

  • Release date: 08/2010
  • Motto/theme: Initial release

Change History
OCI8
Change History


Oracle OCI8

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Testing
    • Konfiguracja wykonawcza
  • Stałe predefiniowane
  • Przykłady
  • Connection Handling
  • Supported Datatypes
  • OCI8 Funkcje
    • OCI-Collection::append — Appends element to the collection
    • OCI-Collection::assign — Assigns a value to the collection from another existing collection
    • OCI-Collection::assignElem — Assigns a value to the element of the collection
    • OCI-Collection::free — Frees the resources associated with the collection object
    • OCI-Collection::getElem — Returns value of the element
    • OCI-Collection::max — Returns the maximum number of elements in the collection
    • OCI-Collection::size — Returns size of the collection
    • OCI-Collection::trim — Trims elements from the end of the collection
    • OCI-Lob::append — Appends data from the large object to another large object
    • OCI-Lob::close — Closes LOB descriptor
    • OCI-Lob::eof — Tests for end-of-file on a large object's descriptor
    • OCI-Lob::erase — Erases a specified portion of the internal LOB data
    • OCI-Lob::export — Exports LOB's contents to a file
    • OCI-Lob::flush — Flushes/writes buffer of the LOB to the server
    • OCI-Lob::free — Frees resources associated with the LOB descriptor
    • OCI-Lob::getBuffering — Returns current state of buffering for the large object
    • OCI-Lob::import — Imports file data to the LOB
    • OCI-Lob::load — Returns large object's contents
    • OCI-Lob::read — Reads part of the large object
    • OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object
    • OCI-Lob::save — Saves data to the large object
    • OCI-Lob::saveFile — Alias dla OCI-Lob::import
    • OCI-Lob::seek — Sets the internal pointer of the large object
    • OCI-Lob::setBuffering — Changes current state of buffering for the large object
    • OCI-Lob::size — Returns size of large object
    • OCI-Lob::tell — Returns the current position of internal pointer of large object
    • OCI-Lob::truncate — Truncates large object
    • OCI-Lob::write — Writes data to the large object
    • OCI-Lob::writeTemporary — Writes a temporary large object
    • OCI-Lob::writeToFile — Alias dla OCI-Lob::export
    • oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
    • oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
    • oci_cancel — Anuluje odczytywanie z kursora
    • oci_client_version — Returns the Oracle client library version
    • oci_close — Closes an Oracle connection
    • oci_commit — Commits the outstanding database transaction
    • oci_connect — Connect to an Oracle database
    • oci_define_by_name — Associates a PHP variable with a column for query fetches
    • oci_error — Returns the last error found
    • oci_execute — Executes a statement
    • oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
    • oci_fetch_array — Returns the next row from a query as an associative or numeric array
    • oci_fetch_assoc — Returns the next row from a query as an associative array
    • oci_fetch_object — Returns the next row from a query as an object
    • oci_fetch_row — Returns the next row from a query as a numeric array
    • oci_fetch — Fetches the next row from a query into internal buffers
    • oci_field_is_null — Checks if the field is NULL
    • oci_field_name — Returns the name of a field from the statement
    • oci_field_precision — Tell the precision of a field
    • oci_field_scale — Tell the scale of the field
    • oci_field_size — Returns field's size
    • oci_field_type_raw — Tell the raw Oracle data type of the field
    • oci_field_type — Returns field's data type
    • oci_free_statement — Frees all resources associated with statement or cursor
    • oci_internal_debug — Enables or disables internal debug output
    • oci_lob_copy — Copies large object
    • oci_lob_is_equal — Compares two LOB/FILE locators for equality
    • oci_new_collection — Allocates new collection object
    • oci_new_connect — Connect to the Oracle server using a unique connection
    • oci_new_cursor — Allocates and returns a new cursor (statement handle)
    • oci_new_descriptor — Initializes a new empty LOB or FILE descriptor
    • oci_num_fields — Returns the number of result columns in a statement
    • oci_num_rows — Returns number of rows affected during statement execution
    • oci_parse — Prepares an Oracle statement for execution
    • oci_password_change — Changes password of Oracle's user
    • oci_pconnect — Connect to an Oracle database using a persistent connection
    • oci_result — Returns field's value from the fetched row
    • oci_rollback — Rolls back the outstanding database transaction
    • oci_server_version — Returns the Oracle Database version
    • oci_set_action — Sets the action name
    • oci_set_client_identifier — Sets the client identifier
    • oci_set_client_info — Sets the client information
    • oci_set_edition — Sets the database edition
    • oci_set_module_name — Sets the module name
    • oci_set_prefetch — Sets number of rows to be prefetched by queries
    • oci_statement_type — Returns the type of a statement
  • OCI8 Obsolete Aliases and Functions
    • ocibindbyname — Alias dla oci_bind_by_name
    • ocicancel — Alias dla oci_cancel
    • ocicloselob — Alias dla OCI-Lob::close
    • ocicollappend — Alias dla OCI-Collection::append
    • ocicollassign — Alias dla OCI-Collection::assign
    • ocicollassignelem — Alias dla OCI-Collection::assignElem
    • ocicollgetelem — Alias dla OCI-Collection::getElem
    • ocicollmax — Alias dla OCI-Collection::max
    • ocicollsize — Alias dla OCI-Collection::size
    • ocicolltrim — Alias dla OCI-Collection::trim
    • ocicolumnisnull — Alias dla oci_field_is_null
    • ocicolumnname — Alias dla oci_field_name
    • ocicolumnprecision — Alias dla oci_field_precision
    • ocicolumnscale — Alias dla oci_field_scale
    • ocicolumnsize — Alias dla oci_field_size
    • ocicolumntype — Alias dla oci_field_type
    • ocicolumntyperaw — Alias dla oci_field_type_raw
    • ocicommit — Alias dla oci_commit
    • ocidefinebyname — Alias dla oci_define_by_name
    • ocierror — Alias dla oci_error
    • ociexecute — Alias dla oci_execute
    • ocifetch — Alias dla oci_fetch
    • ocifetchinto — Fetches the next row into an array (deprecated)
    • ocifetchstatement — Alias dla oci_fetch_all
    • ocifreecollection — Alias dla OCI-Collection::free
    • ocifreecursor — Alias dla oci_free_statement
    • ocifreedesc — Alias dla OCI-Lob::free
    • ocifreestatement — Alias dla oci_free_statement
    • ociinternaldebug — Alias dla oci_internal_debug
    • ociloadlob — Alias dla OCI-Lob::load
    • ocilogoff — Alias dla oci_close
    • ocilogon — Alias dla oci_connect
    • ocinewcollection — Alias dla oci_new_collection
    • ocinewcursor — Alias dla oci_new_cursor
    • ocinewdescriptor — Alias dla oci_new_descriptor
    • ocinlogon — Alias dla oci_new_connect
    • ocinumcols — Alias dla oci_num_fields
    • ociparse — Alias dla oci_parse
    • ociplogon — Alias dla oci_pconnect
    • ociresult — Alias dla oci_result
    • ocirollback — Alias dla oci_rollback
    • ocirowcount — Alias dla oci_num_rows
    • ocisavelob — Alias dla OCI-Lob::save
    • ocisavelobfile — Alias dla OCI-Lob::import
    • ociserverversion — Alias dla oci_server_version
    • ocisetprefetch — Alias dla oci_set_prefetch
    • ocistatementtype — Alias dla oci_statement_type
    • ociwritelobtofile — Alias dla OCI-Lob::export
    • ociwritetemporarylob — Alias dla OCI-Lob::writeTemporary
PECL/mysqlnd_uh 1.0 series
Wstęp
Rozszerzenia producentów baz danych


Wstęp

These functions allow you to access Oracle Database 11g, 10g, 9i and 8i. They support SQL and PL/SQL statements. Basic features include transaction control, binding of PHP variables to Oracle placeholders, and support for large object (LOB) types and collections. Oracle's scalability features such as Database Resident Connection Pooling (DRCP) and result caching are also supported.

OCI8
Instalacja/Konfiguracja
OCI8


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Testing
  • Konfiguracja wykonawcza
Wstęp
Wymagania
OCI8


Wymagania

The OCI8 extension requires Oracle 9iR2, 10g or 11g Client libraries. If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries. When PHP is on a different machine, use the free » Oracle Instant Client libraries.

To use Oracle Instant Client, install the basic or basiclite Oracle Instant Client ZIP file or RPM package. When building PHP from source code, also install the sdk ZIP file or devel RPM package.

On Windows, the php_oci8 DLL needs client libraries from version 10gR2 or greater. In PHP 5.3 up to and including PHP 5.3.5, the php_oci8_11g DLL requires Oracle 11gR1 or greater client libraries. From PHP 5.3.6 the php_oci8_11g DLL requires Oracle 11gR2 or greater client libraries. With some versions of Instant Client you may additionally need mfc71.dll and msvcr71.dll libraries.

You should run PHP with the same, or more recent, version of the Oracle libraries that OCI8 was built with.

Informacja:

If OCI8 uses 9iR2 or 10g client libraries, then PHP can connect to Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 11g client libraries, the database can be 9iR2, 10g or 11g.

Informacja:

Full OCI8 feature support is only available when using the most recent versions of the client libraries and database.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Configuring PHP with OCI8

Review the previous Requirements section before configuring OCI8.

To enable the OCI8 extension, configure PHP with the option --with-oci8 .

Before starting the web server, OCI8 typically requires several Oracle environment variables (see below) to locate libraries, point to configuration files, and set some basic properties such as the character set used by Oracle libraries. The variables should be set before any PHP process starts.

PHP should be run with the same, or more recent, major version of Oracle libraries as it was configured with. For example, if you build OCI8 with Oracle 11.2 libraries, then PHP should also be deployed and run with Oracle 11.2 libraries.

Installing OCI8 as a Shared Extension

The configuration shared option builds OCI8 as a shared library that can be dynamically loaded into PHP. Building a shared extension allows OCI8 to be upgraded easily without impacting the rest of PHP.

Configure OCI8 using one of the following configure options.

  • If using Oracle Instant Client, then do:

    ./configure --with-oci8=shared,instantclient,/path/to/instant/client/lib

    If Instant Client is installed from ZIP files, make sure to create the library symbolic link, for example ln -s libclntsh.so.11.1 libclntsh.so.

    If using an RPM-based installation of Oracle Instant Client, the configure line will look like this:

    ./configure --with-oci8=shared,instantclient,/usr/lib/oracle/<version>/client/lib

    For example, --with-oci8=shared,instantclient,/usr/lib/oracle/11.2/client/lib .

    Note that Oracle Instant Client support first appeared in PHP 4.3.11 and 5.0.4 and originally used the option --with-oci8-instant-client to configure PHP.

  • If using an Oracle database or full Oracle Client installation then do:

    ./configure --with-oci8=shared,$ORACLE_HOME

    Make sure the web server user (nobody, www) has access to the libraries, initialization files and tnsnames.ora (if used) under the $ORACLE_HOME directory. With Oracle 10gR2, you may need to run the $ORACLE_HOME/install/changePerm.sh utility to give directory access.

After configuration, follow the usual PHP building procedure, e.g. make install. The OCI8 shared extension oci8.so library will be created. It may need to be manually moved to the PHP extension directory, specified by the extension_dir option in your php.ini file.

To complete installation of OCI8, edit php.ini and add the line:

extension=oci8.so

Installing OCI8 as a Statically Compiled Extension

Configure OCI8 using one of the following configure options.

  • If using Oracle Instant Client, then do:

    ./configure --with-oci8=instantclient,/path/to/instant/client/lib

  • If using an Oracle database or full Oracle Client installation then do:

    ./configure --with-oci8=$ORACLE_HOME

After configuration, follow the usual PHP building procedure, e.g. make install. After successful compilation, you do not need to add oci8.so to php.ini. No additional build steps are required.

Installing OCI8 from PECL

The OCI8 extension can be added to an existing PHP installation either automatically or manually from » http://pecl.php.net/. 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/oci8.

For an automated install follow these steps:

  • If you are behind a firewall, set PEAR's proxy, for example:

    pear config-set http_proxy http://my-proxy.example.com:80/

  • Run

    pecl install oci8

    When prompted, enter either the value of $ORACLE_HOME, or instantclient,/path/to/instant/client/lib.

    Note: Do not enter the variable $ORACLE_HOME because it will not be expanded. Instead, enter the actual path of the Oracle home directory.

For a manual install, download the PECL OCI8 package, e.g. oci8-1.3.5.tgz.

  • Extract the package:

    tar -zxf oci8-1.3.5.tgz
cd oci8-1.3.5

  • Prepare the package:

    phpize

  • Configure the package, either using $ORACLE_HOME or Instant Client

    ./configure -with-oci8=shared,$ORACLE_HOME

    or

    ./configure -with-oci8=shared,instantclient,/path/to/instant/client/lib

  • Install the package:

    make install

After either an automatic or manual install, edit your php.ini file and add the line:

extension=oci8.so

Make sure the php.ini directive extension_dir is set to the directory that oci8.so was installed in.

Installing OCI8 on Windows

On Windows, uncomment the php.ini line extension=php_oci8.dll when using Oracle 10gR2 client libraries. Uncomment extension=php_oci8_11g.dll when using Oracle 11g client libraries. These two DLLs contain equivalent functionality and only one may be enabled at a time. Make sure extension_dir is set to the directory containing the PHP extension DLLs.

If using Instant Client, set the system PATH environment variable to the Oracle library directory.

Setting the Oracle Environment

Before using this extension, make sure that the Oracle environment variables are properly set for the web daemon user. If your web server is automatically started at boot time then make sure that the boot-time environment is also configured correctly.

Informacja:

Do not set Oracle environment variables using putenv() in a PHP script because Oracle libraries may be loaded and initialized before your script runs. Variables set with putenv() may then cause conflicts, crashes, or unpredictable behavior. Some functions may work but others might give subtle errors. The variables should be set up before the web server is started.

On Red Hat Linux and variants, export variables at the end of /etc/sysconfig/httpd. Other systems with Apache 2 may use an envvars script in the Apache bin directory. A third option, the Apache SetEnv directive in httpd.conf, may work in some systems but is known to be insufficient in others.

To check that environment variables are set correctly, use phpinfo() and check the Environment (not the Apache Environment) section contains the expected variables.

The variables that might be needed are included in the following table. Refer to the Oracle documentation for more information on all the variables.

Common Oracle Environment Variables
Name | Purpose
ORACLE_HOME | Contains the directory of the full Oracle Database software. Do not set this when using Oracle Instant Client as it is unnecessary and may cause installation problems.
ORACLE_SID | Contains the name of the database on the local machine to be connected to. There is no need to set this if you using Oracle Instant Client, or always pass the connection parameter to oci_connect().
LD_LIBRARY_PATH | Set this (or its platform equivalent, such as DYLD_LIBRARY_PATH, LIBPATH, or SHLIB_PATH) to the location of the Oracle libraries, for example $ORACLE_HOME/lib or /usr/lib/oracle/11.1/client/lib. This variable is not needed if the libraries are located by a different search mechanism, such as with ldconfig or with LD_PRELOAD.
NLS_LANG | This is the primary variable for setting the character set and globalization information used by the Oracle libraries.
ORA_SDTZ | Sets the Oracle session timezone.
TNS_ADMIN | Contains the directory where the Oracle Net Services configuration files such as tnsnames.ora and sqlnet.ora are kept. Not needed if the oci_connect() connection string uses the Easy Connect naming syntax such as localhost/XE. Not needed if the network configuration files are in one of the default locations such as $ORACLE_HOME/network/admin or /etc.
Less frequently used Oracle environment variables include TWO_TASK, ORA_TZFILE, and the various Oracle globalization settings like NLS* and the ORA_NLS_* variables.

Troubleshooting

The most common problem with installing OCI8 is not having the Oracle environment correctly set. This typically appears as a problem using oci_connect() or oci_pconnect(). The error may be a PHP error such as Call to undefined function oci_connect(), an Oracle error such as ORA-12705, or even an Apache crash. Check the Apache log files for startup errors and see the sections above to resolve this problem.

While network errors like ORA-12154 or ORA-12514 indicate an Oracle network naming or configuration issue, the root cause may be because the PHP environment is incorrectly set up and Oracle libraries are unable to locate the tnsnames.ora configuration file.

On Windows, having multiple versions of Oracle on the one machine can easily cause library clashes unless care is taken to make sure PHP only uses the correct version of Oracle.

A utility to examine what libraries are being looked for and loaded can help resolve missing or clashing library issues, particularly on Windows.

Informacja: If the web server doesn't start or crashes at startup

Check that Apache is linked with the pthread library:

# ldd /www/apache/bin/httpd
  libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000)
  libm.so.6 => /lib/libm.so.6 (0x4002f000)
  libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000)
  libdl.so.2 => /lib/libdl.so.2 (0x4007a000)
  libc.so.6 => /lib/libc.so.6 (0x4007e000)
  /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

If the libpthread is not listed, then reinstall Apache:

# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

Please note that on some systems like UnixWare, it is libthread instead of libpthread. PHP and Apache have to be configured with EXTRA_LIBS=-lthread.

Wymagania
Testing
Instalacja/Konfiguracja


Testing

The OCI8 test suite is in ext/oci8/tests. After OCI8 tests are run this directory will also contain logs of any failures.

Before running PHP's tests, edit details.inc and set $user, $password and the $dbase connection string. The OCI8 test suite has been developed using the SYSTEM account. Some tests will fail if the test user does not have equivalent permissions.

If Oracle 11g Database Resident Connection Pooling is being tested, set $test_drcp to TRUE and ensure the connection string uses an appropriate DRCP pooled server.

An alternative to editing details.inc is the set environment variables, for example:

    $ export PHP_OCI8_TEST_USER=system
    $ export PHP_OCI8_TEST_PASS=oracle
    $ export PHP_OCI8_TEST_DB=localhost/XE
    $ export PHP_OCI8_TEST_DRCP=FALSE
Note in some shells these variables are not propagated correctly to the PHP process and tests will fail to connect if this method is used.

Next, set any necessary environment for the Oracle database. With Oracle 10gR2 XE do:

    $ . /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh

With Oracle 11gR2 XE do:

    $ . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh

For other versions of the Oracle database do:

    $ . /usr/local/bin/oraenv

Some shells require that php.ini has E in the variables_order parameter, for example:

    variables_order = "EGPCS"

Run all the PHP tests with:

    $ cd your_php_src_directory
    $ make test
or run only the OCI8 tests with
    $ cd your_php_src_directory
    $ make test TESTS=ext/oci8

When the tests have completed, review any test failures. On slow systems, some tests may take longer than the default test timeout in run-tests.php. To correct this, set the environment variable TEST_TIMEOUT to a larger number of seconds.

On fast machines with a local database configured for light load (e.g. Oracle 11gR2 XE) some tests might fail with ORA-12516 or ORA-12520 errors. To prevent this, increase the database PROCESSES parameter using the following steps:

Connect as the oracle software owner:

    $ su - oracle

Set the necessary Oracle environment with oracle_env.sh or oraenv, as described above.

Start the SQL*Plus command line tool and increase PROCESSES

    $ sqlplus / as sysdba
    SQL> alter system set processes=100 scope=spfile

Restart the database:

    SQL> startup force

Instalacja
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

OCI8 Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
oci8.connection_class | "" | PHP_INI_ALL | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.default_prefetch | "100" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.events | Off | PHP_INI_SYSTEM | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.privileged_connect | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

oci8.connection_class string

This user defined text is used by Oracle 11g Database Resident Connection Pooling (DRCP) connections to sub-partition the connection pool. It allows OCI8 persistent connections from an application to reuse database sessions from a previous PHP script, giving better scalability. When an application uses a database pooled process previously used with a different connection class, the session settings such as the default Oracle date format are reset. This prevents accidental sharing of information between different applications.

The value can be set at runtime with ini_set() prior to connecting.

To use DRCP, OCI8 must be linked with Oracle 11g libraries and the database must be Oracle 11g. The connection pool must be enabled in the database, the oci8.connection_class should be set to the same string for all web servers running the same application, and the OCI8 connection string must specify to use a pooled server.

oci8.default_prefetch int

This option sets the default number of extra rows that will be fetched and cached automatically whenever a low-level request for data from the database is made. Setting a value of 0 turns off prefetching.

The prefetch value does not alter the number of rows that functions like oci_fetch_array() return to the user; the prefetching and caching of rows is handled internally in OCI8.

The value can be set per-statement with oci_set_prefetch() prior to statement execution.

In PHP 5.3 (PECL OCI8 1.3.4) the default value was increased from 10 to 100.

In PHP 5.3.2 (PECL OCI8 1.4) the minimum value settable was reduced from 1 to 0, allowing prefetching to be turned off.

Informacja: A larger prefetch can result in improved performance, at the cost of some increased memory usage. For queries that return large amounts of data, the performance benefit can be significant.

oci8.events boolean

Using On allows PHP to be notified of database Fast Application Notification (FAN) events.

Without FAN, when a database instance or machine node fails unexpectedly, PHP applications may be blocked waiting for a database response until a TCP timeout expires. With FAN events, PHP applications are quickly notified of failures that affect their established database connections. The OCI8 extension will clean up unusable connections in the persistent connection cache.

When using On, the database must also be configured to post FAN events.

FAN support is available when OCI8 is linked with Oracle 10gR2 (or later) libraries and connected to Oracle Database 10gR2 (or later).

oci8.max_persistent int

The maximum number of persistent OCI8 connections per PHP process. Setting this option to -1 means that there is no limit.

oci8.old_oci_close_semantics boolean

This option controls oci_close() behaviour. Enabling it means that oci_close() will do nothing; the connection will not be closed until the end of the script. This is for backward compatibility only. If you find that you need to enable this setting, you are strongly encouraged to adjust the oci_close() calls in your application instead of enabling this option.

oci8.persistent_timeout int

The maximum number of seconds that a PHP process is allowed to keep an idle persistent connection open. Setting this option to -1 means that idle persistent connections will be retained until the PHP process terminates or the connection is explicitly closed with oci_close().

Informacja: In PHP, the expiry of idle resources is not alarm-based. It occurs when PHP finishes processing a script and checks the last-used timestamp of resources. Hence there is a paradox that idle connections can only be closed when there is some activity (though not necessarily OCI8 related) in the PHP process. The introduction of Database Resident Connection Pooling (DRCP) in Oracle 11g resolves the memory and resource issues that oci8.max_persistent and oci8.persistent_timeout previously attempted to overcome.

Informacja: In PHP 5.3 (PECL OCI8 1.3), persistent connections can be closed with oci_close().

oci8.ping_interval int

The number of seconds that must pass before issuing a ping during oci_pconnect(). A ping ensures that the database connection is valid. When set to 0, persistent connections will be pinged every time oci_pconnect() is called. To disable pings completely, set this option to -1.

Informacja: Disabling pings allows oci_pconnect() to operate at the highest efficiency, but PHP may not be able to detect unusable connections, such as caused by network dropout, or if the Oracle database has gone down since PHP connected, until the connection is used later in the script. Consult the oci_pconnect() documentation for more information.

oci8.privileged_connect boolean

This option allows connections to use the privileged external credentials OCI_SYSOPER or OCI_SYSDBA.

Informacja: Seting this On can allow scripts on web servers running with the appropriate OS user privileges to connect as privileged database users without requiring a database password. This can be a security risk.

oci8.statement_cache_size int

This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.

Statement caching removes the need to transmit the statement text to the database and removes the need to transmit any meta data about the statement back to PHP. This can significantly improve overall system performance in applications which reuse statements during the lifetime of a connection. Some extra database "cursors" may be held open under the assumption that statements will be reused.

Set this value to the size of the working set of statements used by your application. Setting too small a value can cause statements to be flushed from the cache before they are reused.

This option is of most use with persistent connections.

Testing
Stałe predefiniowane
Instalacja/Konfiguracja


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.

OCI8 Function and Method Modes
Constant | Description
OCI_ASSOC | Used with oci_fetch_all() and oci_fetch_array() to get results as an associative array.
OCI_BOTH | Used with oci_fetch_all() and oci_fetch_array() to get results as an array with both associative and number indices.
OCI_COMMIT_ON_SUCCESS | Statement execution mode for oci_execute() call. Automatically commit changes when the statement has succeeded.
OCI_CRED_EXT | Used with oci_connect() for using Oracles' External or OS authentication. Introduced in PHP 5.3 and PECL OCI8 1.3.4.
OCI_DEFAULT | Statement execution mode for oci_execute(). The transaction is not automatically committed when using this mode. From PHP 5.3.2 (PECL OCI8 1.4) onwards, OCI_NO_AUTO_COMMIT is preferred instead of OCI_DEFAULT.
OCI_DESCRIBE_ONLY | Statement execution mode for oci_execute(). Use this mode if you want meta data such as the column names but don't want to fetch rows from the query.
OCI_EXACT_FETCH | Obsolete. Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. The cursor is canceled after the desired rows are fetched which may result in reduced server-side resource usage.
OCI_FETCHSTATEMENT_BY_COLUMN | Default mode of oci_fetch_all().
OCI_FETCHSTATEMENT_BY_ROW | Alternative mode of oci_fetch_all().
OCI_LOB_BUFFER_FREE | Used with OCI-Lob::flush to free buffers used.
OCI_NO_AUTO_COMMIT | Statement execution mode for oci_execute(). The statement is not committed automatically when using this mode. For readability in new code, use this value instead of the obsolete OCI_DEFAULT constant. Introduced in PHP 5.3.2 (PECL OCI8 1.4).
OCI_NUM | Used with oci_fetch_all() and oci_fetch_array() to get results as an enumerated array.
OCI_RETURN_LOBS | Used with oci_fetch_array() to get the data value of the LOB instead of the descriptor.
OCI_RETURN_NULLS | Used with oci_fetch_array() to get empty array elements if the row items value is NULL.
OCI_SEEK_CUR | Used with OCI-Lob::seek to set the seek position.
OCI_SEEK_END | Used with OCI-Lob::seek to set the seek position.
OCI_SEEK_SET | Used with OCI-Lob::seek to set the seek position.
OCI_SYSDATE | Obsolete.
OCI_SYSDBA | Used with oci_connect() to connect with the SYSDBA privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_SYSOPER | Used with oci_connect() to connect with the SYSOPER privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_TEMP_BLOB | Used with OCI-Lob::writeTemporary to indicate that a temporary BLOB should be created.
OCI_TEMP_CLOB | Used with OCI-Lob::writeTemporary to indicate that a temporary CLOB should be created.
OCI8 Bind and Define Types
Constant | Description
OCI_B_BFILE | Used with oci_bind_by_name() when binding BFILEs.
OCI_B_BIN | Used with oci_bind_by_name() to bind RAW values.
OCI_B_BLOB | Used with oci_bind_by_name() when binding BLOBs.
OCI_B_CFILEE | Used with oci_bind_by_name() when binding CFILEs.
OCI_B_CLOB | Used with oci_bind_by_name() when binding CLOBs.
OCI_B_CURSOR | Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().
OCI_B_INT | Used with oci_bind_array_by_name() to bind arrays of INTEGER.
OCI_B_NTY | Used with oci_bind_by_name() when binding named data types. Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.
OCI_B_NUM | Used with oci_bind_array_by_name() to bind arrays of NUMBER.
OCI_B_ROWID | Used with oci_bind_by_name() when binding ROWIDs.
SQLT_AFC | Used with oci_bind_array_by_name() to bind arrays of CHAR.
SQLT_AVC | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2.
SQLT_BDOUBLE | Not supported.
SQLT_BFILEE | The same as OCI_B_BFILE.
SQLT_BFLOAT | Not supported.
SQLT_BIN | The same as OCI_B_BIN.
SQLT_BLOB | The same as OCI_B_BLOB.
SQLT_CFILEE | The same as OCI_B_CFILEE.
SQLT_CHR | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name().
SQLT_CLOB | The same as OCI_B_CLOB.
SQLT_FLT | Used with oci_bind_array_by_name() to bind arrays of FLOAT.
SQLT_INT | The same as OCI_B_INT.
SQLT_LBI | Used with oci_bind_by_name() to bind LONG RAW values.
SQLT_LNG | Used with oci_bind_by_name() to bind LONG values.
SQLT_LVC | Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR.
SQLT_NTY | The same as OCI_B_NTY.
SQLT_NUM | The same as OCI_B_NUM.
SQLT_ODT | Used with oci_bind_array_by_name() to bind arrays of LONG.
SQLT_RDD | The same as OCI_B_ROWID.
SQLT_RSET | The same as OCI_B_CURSOR.
SQLT_STR | Used with oci_bind_array_by_name() to bind arrays of STRING.
SQLT_UIN | Not supported.
SQLT_VCS | Used with oci_bind_array_by_name() to bind arrays of VARCHAR.
OCI8 Descriptor Types
Constant | Description
OCI_DTYPE_FILE | This flag tells oci_new_descriptor() to initialize a new FILE descriptor.
OCI_DTYPE_LOB | This flag tells oci_new_descriptor() to initialize a new LOB descriptor.
OCI_DTYPE_ROWID | This flag tells oci_new_descriptor() to initialize a new ROWID descriptor.
OCI_D_FILE | The same as OCI_DTYPE_FILE.
OCI_D_LOB | The same as OCI_DTYPE_LOB.
OCI_D_ROWID | The same as OCI_DTYPE_ROWID.
Konfiguracja wykonawcza
Przykłady
OCI8


Przykłady

These examples connect as the HR user, which is the sample "Human Resources" schema supplied with the Oracle database. The account may need to be unlocked and the password reset before you can use it.

The examples connect to the XE database on your machine. Change the connect string to your database before running the examples.

Przykład #1 Basic query

This shows querying and displaying results. Statements in OCI8 use a prepare-execute-fetch sequence of steps.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Prepare the statement
$stid = oci_parse($conn, 'SELECT * FROM departments');
if (!$stid) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Fetch the results of the query
print "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    print "<tr>\n";
    foreach ($row as $item) {
        print "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #2 Inserting with bind variables

Bind variables improve performance by allowing reuse of execution contexts and caches. Bind variables improve security by preventing some kinds of SQL Injection problems.

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO MYTABLE (mid, myd) VALUES(:myid, :mydata)');

$id = 60;
$data = 'Some data';

oci_bind_by_name($stid, ':myid', $id);
oci_bind_by_name($stid, ':mydata', $data);

$r = oci_execute($stid);  // executes and commits

if ($r) {
    print "One row inserted";
}

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #3 Inserting data into a CLOB column

For large data use binary long object (BLOB) or character long object (CLOB) types. This example uses CLOB.

<?php

// Before running, create the table:
//     CREATE TABLE MYTABLE (mykey NUMBER, myclob CLOB);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$mykey = 12343;  // arbitrary key for this example;

$sql = "INSERT INTO mytable (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_NO_AUTO_COMMIT); // use OCI_DEFAULT for PHP <= 5.3.1
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytable WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);

print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
    $result = $row['MYCLOB']->load();
    print '<tr><td>'.$result.'</td></tr>';
}
print '</table>';

?>

Przykład #4 Using a PL/SQL stored function

You must bind a variable for the return value and optionally for any PL/SQL function arguments.

<?php

/*
  Before running the PHP program, create a stored function in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
  BEGIN
      RETURN p * 3;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p = 8;

$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);
oci_bind_by_name($stid, ':r', $r, 40);

oci_execute($stid);

print "$r\n";   // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #5 Using a PL/SQL stored procedure

With stored procedures, you should bind variables for any arguments.

<?php

/*
  Before running the PHP program, create a stored procedure in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
  BEGIN
      p2 := p1 * 2;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 = 8;

$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #6 Calling a PL/SQL function that returns a REF CURSOR

Each returned value from the query is a REF CURSOR that can be fetched from.

<?php
/*
  Create the PL/SQL stored function as:

  CREATE OR REPLACE FUNCTION myfunc(p1 IN NUMBER) RETURN SYS_REFCURSOR AS
      rc SYS_REFCURSOR;
  BEGIN
      OPEN rc FOR SELECT city FROM locations WHERE ROWNUM < p1;
      RETURN rc;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT myfunc(5) AS mfrc FROM dual');
oci_execute($stid);

echo "<table border='1'>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
    echo "<tr>\n";
    $rc = $row['MFRC'];
    oci_execute($rc);  // returned column value from the query is a ref cursor
    while (($rc_row = oci_fetch_array($rc, OCI_ASSOC))) {
        echo "    <td>" . $rc_row['CITY'] . "</td>\n";
    }
    oci_free_statement($rc);
    echo "</tr>\n";
}
echo "</table>\n";

// Output is:
//   Beijing
//   Bern
//   Bombay
//   Geneva

oci_free_statement($stid);
oci_close($conn);

?>
Stałe predefiniowane
Connection Handling
OCI8


Connection Handling

Connection Functions

The OCI8 extension provides three different functions for connecting to Oracle. The standard connection function is oci_connect(). This creates a connection to an Oracle database and returns a resource used by subsequent database calls.

Connecting to an Oracle server is a reasonably expensive operation in terms of the time that it takes to complete. The oci_pconnect() function uses a persistent cache of connections that can be re-used across different script requests. This means that the connection overhead will typically only occur once per PHP process (or Apache child).

If the application connects to Oracle using a different set of credentials for each web user, the persistent cache employed by oci_pconnect() will become less useful as the number of concurrent users increases, to the point where it may start to adversely affect the overall performance of the Oracle server due to maintaining too many idle connections. If the application is structured in this way, it is recommended to either tune the application using the oci8.max_persistent and oci8.persistent_timeout configuration settings (these will give control over the persistent connection cache size and lifetime), use Oracle 11g Database Resident Connection Pooling, or use oci_connect() instead.

Both oci_connect() and oci_pconnect() employ a connection cache; if multiple calls to oci_connect() use the same parameters in a given script, the second and subsequent calls return the existing connection handle. The cache used by oci_connect() is cleaned up at the end of the script run, or when the connection handle is explicitly closed. The function oci_pconnect() has similar behavior, although its cache is maintained separately and survives between HTTP requests.

This caching feature means the two handles are not transactionally isolated (they are in fact the same connection handle, so there is no isolation of any kind). If the application needs two separate, transactionally isolated connections, then use oci_new_connect().

The oci_pconnect() cache is cleared and any database connections closed when the PHP process terminates, so effective use of persistent connections requires that PHP be an Apache module or used with FGCI, or similar. Persistent connections will not have any benefits over oci_connect() when PHP is used with CGI or via the command-line.

The function oci_new_connect() always creates a new connection to the Oracle server, regardless of what other connections might already exist. High traffic web applications should avoid using oci_new_connect(), especially in the busiest sections of the application.

DRCP Connection Pooling

PHP 5.3 (PECL OCI8 1.3) supports Oracle 11g Database Resident Connection Pooling (DRCP). DRCP allows more efficient use of database machine memory and provides high scalability. No, or minimal, application changes are needed to use DRCP.

DRCP is suited for applications that connect using few database schemas and hold database connections open for a short period of time. Other applications should use Oracle's default Dedicated database server processes, or use Shared servers.

DRCP benefits all three connection functions, but gives the highest scalability when connections are created with oci_pconnect().

For DRCP to be available in OCI8, Oracle client libraries used by PHP and the version of the Oracle Database must both be 11g.

Documentation on DRCP is found in several Oracle manuals. For example, see » Configuring Database Resident Connection Pooling in the Oracle documentation for usage information. A » DRCP white paper contains background information on DRCP.

To use DRCP, build PHP with the OCI8 1.3 extension and Oracle 11g libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to start the connection pool in the database:

        SQL> execute dbms_connection_pool.start_pool;

  • Optionally use dbms_connection_pool.alter_param() to configure DRCP settings. The current pool settings can be queried from the DBA_CPOOL_INFO view.

  • Update the connection strings used. For PHP applications that currently connect using a Network Connect Name like MYDB:

        $c = oci_pconnect("myuser", "mypassword", "MYDB");

    modify the tnsnames.ora file and add a (SERVER=POOLED) clause, for example:

        MYDB = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost.dom.com)
           (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
           (SERVER=POOLED)))

    Alternatively, modify the Easy Connect syntax in PHP and add :POOLED after the service name:

        $c = oci_pconnect("myuser", "mypassword", "myhost.dom.com:1521/sales:POOLED");

  • Edit php.ini and choose a connection class name. This name indicates a logical division of the connection pool and can be used to isolate pooling for separate applications. Any PHP applications with the same user name and connection class value will be able to share connections in the pool, giving greater scalability.

        oci8.connection_class = "MY_APPLICATION_NAME"

  • Run the application, connecting to the 11g database.

Informacja:

Applications using Oracle 10g that require the performance of persistent connections can reduce the amount of database server memory needed by using Oracle Shared servers (previously known as Multi Threaded Servers). Refer to Oracle documentation for information.

DRCP Recommendations and Known Limitations

Changing a password over DRCP connections will fail with the error ORA-56609: Usage not supported with DRCP. This is a documented restriction of Oracle Database 11g.

With the OCI8 1.3 extension, persistent connections can now be closed by the user, allowing greater control over connection resource usage. Persistent connections will now also be closed automatically when there is no PHP variable referencing them, such as at the end of scope of a PHP user function. This will rollback any uncommitted transaction. These changes to persistent connections make them behave similarly to non-persistent connections, simplifying the interface, allowing for greater application consistency and predictability. Use oci8.old_oci_close_semantics set to On to retain the historical behavior.

If the Oracle Database is version 11.1.0.6, then the Oracle database patch for Oracle bug 6474441 must be applied to use DRCP. Without this patch, errors such as ORA-01000: maximum open cursors exceeded, ORA-01001 invalid cursor or ORA-01002 fetch out of sequence may occur. This bug was fixed in Oracle 11.1.0.7 onwards.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following three workarounds can be used instead:

  • Connect using Oracle Dedicated or Shared servers instead of DRCP.
  • Set PHP's oci8.statement_cache_size to 0.
  • Set an event in the database initialization parameter file: event="56699 trace name context forever, level 128".

Oracle Database 11.1.0.7 and the Oracle Database 11.1.0.6 patch for Oracle bug 6474441 allow PHP applications with DRCP connection to use a database LOGON trigger to set session properties at the time of session creation. Examples of such settings are the NLS language and the date format.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following workarounds can be used instead of using LOGON triggers:

  • After logon, explicitly set the session properties using PHP application code.
  • Connect using Oracle Dedicated or Shared servers instead of DRCP.

The automatic re-establishment of PHP persistent connections after an Apache or FGCI process respawns means LOGON triggers in PHP are only recommended for setting session attributes and not for per-application user connection requests. This is even more so with DRCP due to the automatic pool sizing and with the way LOGON triggers fire with DRCP authentication.

Fast Application Notification (FAN) Support

FAN support gives fast connection failover, a high availability feature. This allows PHP OCI8 scripts to be notified when a database machine or database instance becomes unavailable. Without FAN, OCI8 can hang until a TCP timeout occurs and an error is returned, which might be several minutes. Enabling FAN in OCI8 can allow applications to detect errors and re-connect to an available database instance without the web user being aware of an outage.

FAN support is available when the Oracle client libraries that PHP links with and the Oracle Database are either version 10gR2 or 11g.

FAN benefits users of Oracle's clustering technology (RAC) because connections to surviving database instances can be immediately made. Users of Oracle's Data Guard with a broker will see the FAN events generated when the standby database goes online. Standalone databases will send FAN events when the database restarts.

For active connections, when a machine or database instance becomes unavailable, a connection failure error will be returned by the OCI8 extension function currently being called. On a subsequent PHP script re-connect, a connection to a surviving database instance will be established. The OCI8 extension also transparently cleans up any idle connections affected by a database machine or instance failure so PHP connect calls will establish a fresh connection without the script being aware of any service disruption.

When oci8.events is On, it is suggested to set oci8.ping_interval to -1 to disable pinging, since enabling FAN events provide pro-active connection management of idle connections made invalid by a service disruption.

To enable FAN support in PHP, build PHP with Oracle 10gR2 or 11g libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to enable the database service to post FAN events, for example:

        SQL> execute dbms_service.modify_service(
                   SERVICE_NAME        => 'sales',
                   AQ_HA_NOTIFICATIONS => TRUE);

  • Edit php.ini and add

        oci8.events = On

  • If the application does not already handle OCI8 error conditions, modify it to detect failures and take appropriate action. This may include re-connecting and re-executing statements.
  • Run the application, connecting to an Oracle 10gR2 or 11g database.

Przykłady
Supported Datatypes
OCI8


Supported Datatypes

The driver supports the following types when binding parameters using oci_bind_by_name() function:
Type | Mapping
SQLT_NTY | Maps a native collection type from a PHP collection object, such as those created by oci_new_collection().
SQLT_BFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_BLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_RDD | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_NUM | Converts the PHP parameter to a 'C' long type, and binds to that value.
SQLT_RSET | Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries.
SQLT_CHR and any other type | Converts the PHP parameter to a string type and binds as a string.
The following types are supported when retrieving columns from a result set:
Type | Mapping
SQLT_RSET | Creates an oci statement resource to represent the cursor.
SQLT_RDD | Creates a ROWID object.
SQLT_BLOB | Creates a LOB object.
SQLT_CLOB | Creates a LOB object.
SQLT_BFILE | Creates a LOB object.
SQLT_LNG | Bound as SQLT_CHR, returned as a string
SQLT_LBI | Bound as SQLT_BIN, returned as a string
Any other type | Bound as SQLT_CHR, returned as a string
Connection Handling
OCI8 Funkcje
OCI8


OCI8 Funkcje

Spis treści

  • OCI-Collection::append — Appends element to the collection
  • OCI-Collection::assign — Assigns a value to the collection from another existing collection
  • OCI-Collection::assignElem — Assigns a value to the element of the collection
  • OCI-Collection::free — Frees the resources associated with the collection object
  • OCI-Collection::getElem — Returns value of the element
  • OCI-Collection::max — Returns the maximum number of elements in the collection
  • OCI-Collection::size — Returns size of the collection
  • OCI-Collection::trim — Trims elements from the end of the collection
  • OCI-Lob::append — Appends data from the large object to another large object
  • OCI-Lob::close — Closes LOB descriptor
  • OCI-Lob::eof — Tests for end-of-file on a large object's descriptor
  • OCI-Lob::erase — Erases a specified portion of the internal LOB data
  • OCI-Lob::export — Exports LOB's contents to a file
  • OCI-Lob::flush — Flushes/writes buffer of the LOB to the server
  • OCI-Lob::free — Frees resources associated with the LOB descriptor
  • OCI-Lob::getBuffering — Returns current state of buffering for the large object
  • OCI-Lob::import — Imports file data to the LOB
  • OCI-Lob::load — Returns large object's contents
  • OCI-Lob::read — Reads part of the large object
  • OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object
  • OCI-Lob::save — Saves data to the large object
  • OCI-Lob::saveFile — Alias dla OCI-Lob::import
  • OCI-Lob::seek — Sets the internal pointer of the large object
  • OCI-Lob::setBuffering — Changes current state of buffering for the large object
  • OCI-Lob::size — Returns size of large object
  • OCI-Lob::tell — Returns the current position of internal pointer of large object
  • OCI-Lob::truncate — Truncates large object
  • OCI-Lob::write — Writes data to the large object
  • OCI-Lob::writeTemporary — Writes a temporary large object
  • OCI-Lob::writeToFile — Alias dla OCI-Lob::export
  • oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
  • oci_bind_by_name — Binds a PHP variable to an Oracle placeholder
  • oci_cancel — Anuluje odczytywanie z kursora
  • oci_client_version — Returns the Oracle client library version
  • oci_close — Closes an Oracle connection
  • oci_commit — Commits the outstanding database transaction
  • oci_connect — Connect to an Oracle database
  • oci_define_by_name — Associates a PHP variable with a column for query fetches
  • oci_error — Returns the last error found
  • oci_execute — Executes a statement
  • oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array — Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc — Returns the next row from a query as an associative array
  • oci_fetch_object — Returns the next row from a query as an object
  • oci_fetch_row — Returns the next row from a query as a numeric array
  • oci_fetch — Fetches the next row from a query into internal buffers
  • oci_field_is_null — Checks if the field is NULL
  • oci_field_name — Returns the name of a field from the statement
  • oci_field_precision — Tell the precision of a field
  • oci_field_scale — Tell the scale of the field
  • oci_field_size — Returns field's size
  • oci_field_type_raw — Tell the raw Oracle data type of the field
  • oci_field_type — Returns field's data type
  • oci_free_statement — Frees all resources associated with statement or cursor
  • oci_internal_debug — Enables or disables internal debug output
  • oci_lob_copy — Copies large object
  • oci_lob_is_equal — Compares two LOB/FILE locators for equality
  • oci_new_collection — Allocates new collection object
  • oci_new_connect — Connect to the Oracle server using a unique connection
  • oci_new_cursor — Allocates and returns a new cursor (statement handle)
  • oci_new_descriptor — Initializes a new empty LOB or FILE descriptor
  • oci_num_fields — Returns the number of result columns in a statement
  • oci_num_rows — Returns number of rows affected during statement execution
  • oci_parse — Prepares an Oracle statement for execution
  • oci_password_change — Changes password of Oracle's user
  • oci_pconnect — Connect to an Oracle database using a persistent connection
  • oci_result — Returns field's value from the fetched row
  • oci_rollback — Rolls back the outstanding database transaction
  • oci_server_version — Returns the Oracle Database version
  • oci_set_action — Sets the action name
  • oci_set_client_identifier — Sets the client identifier
  • oci_set_client_info — Sets the client information
  • oci_set_edition — Sets the database edition
  • oci_set_module_name — Sets the module name
  • oci_set_prefetch — Sets number of rows to be prefetched by queries
  • oci_statement_type — Returns the type of a statement
Supported Datatypes
OCI-Collection::append
OCI8


Appends element to the collection

OCI8 Funkcje
OCI-Collection::assign
OCI8 Funkcje
PHP Manual

OCI-Collection::append

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::append — Appends element to the collection

Opis

bool OCI-Collection::append ( mixed $value )

Appends element to the end of the collection.

Parametry

value

The value to be added to the collection. Can be a string or a number.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Collection::assign

OCI8 Funkcje
OCI-Collection::assign
OCI8 Funkcje


Assigns a value to the collection from another existing collection

OCI-Collection::append
OCI-Collection::assignElem
OCI8 Funkcje
PHP Manual

OCI-Collection::assign

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::assign — Assigns a value to the collection from another existing collection

Opis

bool OCI-Collection::assign ( OCI-Collection $from )

Assigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.

Parametry

from

An instance of OCI-Collection.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Collection::append

OCI-Collection::append
OCI-Collection::assignElem
OCI8 Funkcje


Assigns a value to the element of the collection

OCI-Collection::assign
OCI-Collection::free
OCI8 Funkcje
PHP Manual

OCI-Collection::assignElem

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::assignElem — Assigns a value to the element of the collection

Opis

bool OCI-Collection::assignElem ( int $index , mixed $value )

Assigns a value to the element with index index.

Parametry

index

The element index. First index is 1.

value

Can be a string or a number.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Collection::getElem

OCI-Collection::assign
OCI-Collection::free
OCI8 Funkcje


Frees the resources associated with the collection object

OCI-Collection::assignElem
OCI-Collection::getElem
OCI8 Funkcje
PHP Manual

OCI-Collection::free

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::free — Frees the resources associated with the collection object

Opis

bool OCI-Collection::free ( void )

Frees the resources associated with the collection object.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • oci_new_collection

OCI-Collection::assignElem
OCI-Collection::getElem
OCI8 Funkcje


Returns value of the element

OCI-Collection::free
OCI-Collection::max
OCI8 Funkcje
PHP Manual

OCI-Collection::getElem

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::getElem — Returns value of the element

Opis

mixed OCI-Collection::getElem ( int $index )

Returns element's value with the index index (1-based).

Parametry

index

The element index. First index is 1.

Zwracane wartości

Returns FALSE if such element doesn't exist; NULL if element is NULL; string if element is column of a string datatype or number if element is numeric field.

Zobacz też:

  • OCI-Collection::assignElem

OCI-Collection::free
OCI-Collection::max
OCI8 Funkcje


Returns the maximum number of elements in the collection

OCI-Collection::getElem
OCI-Collection::size
OCI8 Funkcje
PHP Manual

OCI-Collection::max

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::max — Returns the maximum number of elements in the collection

Opis

int OCI-Collection::max ( void )

Returns the maximum number of elements in the collection.

Zwracane wartości

Returns the maximum number as an integer, or FALSE on errors.

If the returned value is 0, then the number of elements is not limited.

Zobacz też:

  • OCI-Collection::size

OCI-Collection::getElem
OCI-Collection::size
OCI8 Funkcje


Returns size of the collection

OCI-Collection::max
OCI-Collection::trim
OCI8 Funkcje
PHP Manual

OCI-Collection::size

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::size — Returns size of the collection

Opis

int OCI-Collection::size ( void )

Returns the size of the collection.

Zwracane wartości

Returns the number of elements in the collection or FALSE on error.

Zobacz też:

  • OCI-Collection::max

OCI-Collection::max
OCI-Collection::trim
OCI8 Funkcje


Trims elements from the end of the collection

OCI-Collection::size
OCI-Lob::append
OCI8 Funkcje
PHP Manual

OCI-Collection::trim

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Collection::trim — Trims elements from the end of the collection

Opis

bool OCI-Collection::trim ( int $num )

Trims num of elements from the end of the collection.

Parametry

num

The number of elements to be trimmed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Collection::size

OCI-Collection::size
OCI-Lob::append
OCI8 Funkcje


Appends data from the large object to another large object

OCI-Collection::trim
OCI-Lob::close
OCI8 Funkcje
PHP Manual

OCI-Lob::append

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::append — Appends data from the large object to another large object

Opis

bool OCI-Lob::append ( OCI-Lob $lob_from )

Appends data from the large object to the end of another large object.

Writing to the large object with this method will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCI-Lob::flush before disabling buffering.

Parametry

lob_from

The copied LOB.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::flush
  • OCI-Lob::setBuffering
  • OCI-Lob::getBuffering

OCI-Collection::trim
OCI-Lob::close
OCI8 Funkcje


Closes LOB descriptor

OCI-Lob::append
OCI-Lob::eof
OCI8 Funkcje
PHP Manual

OCI-Lob::close

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::close — Closes LOB descriptor

Opis

bool OCI-Lob::close ( void )

Closes descriptor of LOB or FILE. This function should be used only with OCI-Lob::writeTemporary.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::writeTemporary

OCI-Lob::append
OCI-Lob::eof
OCI8 Funkcje


Tests for end-of-file on a large object's descriptor

OCI-Lob::close
OCI-Lob::erase
OCI8 Funkcje
PHP Manual

OCI-Lob::eof

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::eof — Tests for end-of-file on a large object's descriptor

Opis

bool OCI-Lob::eof ( void )

Tells whether the internal pointer of large object is at the end of LOB.

Zwracane wartości

Returns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.

Zobacz też:

  • OCI-Lob::size

OCI-Lob::close
OCI-Lob::erase
OCI8 Funkcje


Erases a specified portion of the internal LOB data

OCI-Lob::eof
OCI-Lob::export
OCI8 Funkcje
PHP Manual

OCI-Lob::erase

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::erase — Erases a specified portion of the internal LOB data

Opis

int OCI-Lob::erase ([ int $offset [, int $length ]] )

Erases a specified portion of the internal LOB data starting at a specified offset. If called without parameters, it erases all LOB data.

For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.

Parametry

offset

length

Zwracane wartości

Returns the actual number of characters/bytes erased lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • OCI-Lob::truncate

OCI-Lob::eof
OCI-Lob::export
OCI8 Funkcje


Exports LOB's contents to a file

OCI-Lob::erase
OCI-Lob::flush
OCI8 Funkcje
PHP Manual

OCI-Lob::export

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::export — Exports LOB's contents to a file

Opis

bool OCI-Lob::export ( string $filename [, int $start [, int $length ]] )

Exports LOB contents to a file.

Parametry

filename

Path to the file.

start

Indicates from where to start exporting.

length

Indicates the length of data to be exported.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::import

OCI-Lob::erase
OCI-Lob::flush
OCI8 Funkcje


Flushes/writes buffer of the LOB to the server

OCI-Lob::export
OCI-Lob::free
OCI8 Funkcje
PHP Manual

OCI-Lob::flush

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::flush — Flushes/writes buffer of the LOB to the server

Opis

bool OCI-Lob::flush ([ int $flag ] )

OCI-Lob::flush() actually writes data to the server.

Parametry

flag

By default, resources are not freed, but using flag OCI_LOB_BUFFER_FREE you can do it explicitly. Be sure you know what you're doing - next read/write operation to the same part of LOB will involve a round-trip to the server and initialize new buffer resources. It is recommended to use OCI_LOB_BUFFER_FREE flag only when you are not going to work with the LOB anymore.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Returns FALSE if buffering was not enabled or an error occurred.

Zobacz też:

  • OCI-Lob::getBuffering
  • OCI-Lob::setBuffering

OCI-Lob::export
OCI-Lob::free
OCI8 Funkcje


Frees resources associated with the LOB descriptor

OCI-Lob::flush
OCI-Lob::getBuffering
OCI8 Funkcje
PHP Manual

OCI-Lob::free

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::free — Frees resources associated with the LOB descriptor

Opis

bool OCI-Lob::free ( void )

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

OCI-Lob::flush
OCI-Lob::getBuffering
OCI8 Funkcje


Returns current state of buffering for the large object

OCI-Lob::free
OCI-Lob::import
OCI8 Funkcje
PHP Manual

OCI-Lob::getBuffering

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::getBuffering — Returns current state of buffering for the large object

Opis

bool OCI-Lob::getBuffering ( void )

Tells whether the buffering for the large object is on or off.

Zwracane wartości

Returns FALSE if buffering for the large object is off and TRUE if buffering is used.

Zobacz też:

  • OCI-Lob::setBuffering

OCI-Lob::free
OCI-Lob::import
OCI8 Funkcje


Imports file data to the LOB

OCI-Lob::getBuffering
OCI-Lob::load
OCI8 Funkcje
PHP Manual

OCI-Lob::import

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::import — Imports file data to the LOB

Opis

bool OCI-Lob::import ( string $filename )

Writes data from the filename in to the current position of large object.

Parametry

filename

Path to the file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::export
  • OCI-Lob::write

OCI-Lob::getBuffering
OCI-Lob::load
OCI8 Funkcje


Returns large object's contents

OCI-Lob::import
OCI-Lob::read
OCI8 Funkcje
PHP Manual

OCI-Lob::load

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::load — Returns large object's contents

Opis

string OCI-Lob::load ( void )

Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCI-Lob::read instead.

Zwracane wartości

Returns the contents of the object, or FALSE on errors.

Zobacz też:

  • OCI-Lob::read

OCI-Lob::import
OCI-Lob::read
OCI8 Funkcje


Reads part of the large object

OCI-Lob::load
OCI-Lob::rewind
OCI8 Funkcje
PHP Manual

OCI-Lob::read

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::read — Reads part of the large object

Opis

string OCI-Lob::read ( int $length )

Reads length bytes from the current position of LOB's internal pointer.

Reading stops when length bytes have been read or end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes read.

Parametry

length

The length of data to read, in bytes.

Zwracane wartości

Returns the contents as a string, lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • OCI-Lob::load
  • OCI-Lob::write

OCI-Lob::load
OCI-Lob::rewind
OCI8 Funkcje


Moves the internal pointer to the beginning of the large object

OCI-Lob::read
OCI-Lob::save
OCI8 Funkcje
PHP Manual

OCI-Lob::rewind

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object

Opis

bool OCI-Lob::rewind ( void )

Sets the internal pointer to the beginning of the large object.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::seek
  • OCI-Lob::tell

OCI-Lob::read
OCI-Lob::save
OCI8 Funkcje


Saves data to the large object

OCI-Lob::rewind
OCI-Lob::saveFile
OCI8 Funkcje
PHP Manual

OCI-Lob::save

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::save — Saves data to the large object

Opis

bool OCI-Lob::save ( string $data [, int $offset ] )

Saves data to the large object.

Parametry

data

The data to be saved.

offset

Can be used to indicate offset from the beginning of the large object.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::write
  • OCI-Lob::import

OCI-Lob::rewind
OCI-Lob::saveFile
OCI8 Funkcje


Alias dla OCI-Lob::import

OCI-Lob::save
OCI-Lob::seek
OCI8 Funkcje
PHP Manual

OCI-Lob::saveFile

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::saveFile — Alias dla OCI-Lob::import()

Opis

Ta funkcja jest aliasem dla: OCI-Lob::import().

OCI-Lob::save
OCI-Lob::seek
OCI8 Funkcje


Sets the internal pointer of the large object

OCI-Lob::saveFile
OCI-Lob::setBuffering
OCI8 Funkcje
PHP Manual

OCI-Lob::seek

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::seek — Sets the internal pointer of the large object

Opis

bool OCI-Lob::seek ( int $offset [, int $whence = OCI_SEEK_SET ] )

Sets the internal pointer of the large object.

Parametry

offset

Indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by whence.

whence

May be one of:

  • OCI_SEEK_SET - sets the position equal to offset
  • OCI_SEEK_CUR - adds offset bytes to the current position
  • OCI_SEEK_END - adds offset bytes to the end of large object (use negative value to move to a position before the end of large object)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::rewind
  • OCI-Lob::tell
  • OCI-Lob::eof

OCI-Lob::saveFile
OCI-Lob::setBuffering
OCI8 Funkcje


Changes current state of buffering for the large object

OCI-Lob::seek
OCI-Lob::size
OCI8 Funkcje
PHP Manual

OCI-Lob::setBuffering

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::setBuffering — Changes current state of buffering for the large object

Opis

bool OCI-Lob::setBuffering ( bool $on_off )

Sets the buffering for the large object, depending on the value of the on_off parameter.

Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. OCI-Lob::flush() should be used to flush buffers, when you have finished working with the large object.

Parametry

on_off

TRUE for on and FALSE for off.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Repeated calls to this method with the same flag will return TRUE.

Zobacz też:

  • OCI-Lob::getBuffering

OCI-Lob::seek
OCI-Lob::size
OCI8 Funkcje


Returns size of large object

OCI-Lob::setBuffering
OCI-Lob::tell
OCI8 Funkcje
PHP Manual

OCI-Lob::size

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::size — Returns size of large object

Opis

int OCI-Lob::size ( void )

Gets the size of the large object.

Zwracane wartości

Returns length of large object value lub FALSE w przypadku niepowodzenia. Empty objects have zero length.

OCI-Lob::setBuffering
OCI-Lob::tell
OCI8 Funkcje


Returns the current position of internal pointer of large object

OCI-Lob::size
OCI-Lob::truncate
OCI8 Funkcje
PHP Manual

OCI-Lob::tell

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::tell — Returns the current position of internal pointer of large object

Opis

int OCI-Lob::tell ( void )

Gets the current position of a LOB's internal pointer.

Zwracane wartości

Returns current position of a LOB's internal pointer or FALSE if an error occurred.

Zobacz też:

  • OCI-Lob::rewind
  • OCI-Lob::size
  • OCI-Lob::eof

OCI-Lob::size
OCI-Lob::truncate
OCI8 Funkcje


Truncates large object

OCI-Lob::tell
OCI-Lob::write
OCI8 Funkcje
PHP Manual

OCI-Lob::truncate

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::truncate — Truncates large object

Opis

bool OCI-Lob::truncate ([ int $length = 0 ] )

Truncates the LOB.

Parametry

length

If provided, this method will truncate the LOB to length bytes. Otherwise, it will completely purge the LOB.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::erase

OCI-Lob::tell
OCI-Lob::write
OCI8 Funkcje


Writes data to the large object

OCI-Lob::truncate
OCI-Lob::writeTemporary
OCI8 Funkcje
PHP Manual

OCI-Lob::write

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::write — Writes data to the large object

Opis

int OCI-Lob::write ( string $data [, int $length ] )

Writes data from the parameter data into the current position of LOB's internal pointer.

Parametry

data

The data to write in the LOB.

length

If this parameter is given, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

Zwracane wartości

Returns the number of bytes written lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • OCI-Lob::read

OCI-Lob::truncate
OCI-Lob::writeTemporary
OCI8 Funkcje


Writes a temporary large object

OCI-Lob::write
OCI-Lob::writeToFile
OCI8 Funkcje
PHP Manual

OCI-Lob::writeTemporary

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::writeTemporary — Writes a temporary large object

Opis

bool OCI-Lob::writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] )

Creates a temporary large object and writes data to it.

You should use OCI-Lob::close when you are done with this object.

Parametry

data

The data to write.

lob_type

Can be one of the following:

  • OCI_TEMP_BLOB is used to create temporary BLOBs
  • OCI_TEMP_CLOB is used to create temporary CLOBs

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OCI-Lob::close

OCI-Lob::write
OCI-Lob::writeToFile
OCI8 Funkcje


Alias dla OCI-Lob::export

OCI-Lob::writeTemporary
oci_bind_array_by_name
OCI8 Funkcje
PHP Manual

OCI-Lob::writeToFile

(PHP 5, PECL OCI8 >= 1.1.0)

OCI-Lob::writeToFile — Alias dla OCI-Lob::export()

Opis

Ta funkcja jest aliasem dla: OCI-Lob::export().

OCI-Lob::writeTemporary
oci_bind_array_by_name
OCI8 Funkcje


Binds a PHP array to an Oracle PL/SQL array parameter

OCI-Lob::writeToFile
oci_bind_by_name
OCI8 Funkcje
PHP Manual

oci_bind_array_by_name

(PHP 5 >= 5.1.2, PECL OCI8 >= 1.2.0)

oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter

Opis

bool oci_bind_array_by_name ( resource $statement , string $name , array &$var_array , int $max_table_length [, int $max_item_length = -1 [, int $type = SQLT_AFC ]] )

Binds the PHP array var_array to the Oracle placeholder name, which points to an Oracle PL/SQL array. Whether it will be used for input or output will be determined at run-time.

Parametry

statement

A valid OCI statement identifier.

name

The Oracle placeholder.

var_array

An array.

max_table_length

Sets the maximum length both for incoming and result arrays.

max_item_length

Sets maximum length for array items. If not specified or equals to -1, oci_bind_array_by_name() will find the longest element in the incoming array and will use it as the maximum length.

type

Should be used to set the type of PL/SQL array items. See list of available types below:

  • SQLT_NUM - for arrays of NUMBER.

  • SQLT_INT - for arrays of INTEGER (Note: INTEGER it is actually a synonym for NUMBER(38), but SQLT_NUM type won't work in this case even though they are synonyms).

  • SQLT_FLT - for arrays of FLOAT.

  • SQLT_AFC - for arrays of CHAR.

  • SQLT_CHR - for arrays of VARCHAR2.

  • SQLT_VCS - for arrays of VARCHAR.

  • SQLT_AVC - for arrays of CHARZ.

  • SQLT_STR - for arrays of STRING.

  • SQLT_LVC - for arrays of LONG VARCHAR.

  • SQLT_ODT - for arrays of DATE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 oci_bind_array_by_name() example

<?php

$c = oci_connect("scott", "tiger");

$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$statement = oci_parse($c, $create);
oci_execute($statement);

$create_pkg = "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
  TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
  PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;";
$statement = oci_parse($c, $create_pkg);
oci_execute($statement);

$create_pkg_body = "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
  CURSOR CUR IS SELECT name FROM bind_example;
  PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
    BEGIN
    FOR i IN 1..5 LOOP
      INSERT INTO bind_example VALUES (c1(i));
    END LOOP;
    IF NOT CUR%ISOPEN THEN
      OPEN CUR;
    END IF;
    FOR i IN REVERSE 1..5 LOOP
      FETCH CUR INTO c1(i);
      IF CUR%NOTFOUND THEN
        CLOSE CUR;
        EXIT;
      END IF;
    END LOOP;
  END iobind;
END ARRAYBINDPKG1;";
$statement = oci_parse($c, $create_pkg_body);
oci_execute($statement);

$statement = oci_parse($c, "BEGIN ARRAYBINDPKG1.iobind(:c1); END;");

$array = array("one", "two", "three", "four", "five");

oci_bind_array_by_name($statement, ":c1", $array, 5, -1, SQLT_CHR);

oci_execute($statement);

var_dump($array);

?>

OCI-Lob::writeToFile
oci_bind_by_name
OCI8 Funkcje


Binds a PHP variable to an Oracle placeholder

oci_bind_array_by_name
oci_cancel
OCI8 Funkcje
PHP Manual

oci_bind_by_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_bind_by_name — Binds a PHP variable to an Oracle placeholder

Opis

bool oci_bind_by_name ( resource $statement , string $bv_name , mixed &$variable [, int $maxlength = -1 [, int $type = SQLT_CHR ]] )

Binds a PHP variable variable to the Oracle bind variable placeholder bv_name. Binding is important for Oracle database performance and also as a way to avoid SQL Injection security issues.

Binding allows the database to reuse the statement context and caches from previous executions of the statement, even if another user or process originally executed it. Binding reduces SQL Injection concerns because the data associated with a bind variable is never treated as part of the SQL statement. It does not need quoting or escaping.

PHP variables that have been bound can be changed and the statement re-executed without needing to re-parse the statement or re-bind.

In Oracle, bind variables are commonly divided into IN binds for values that are passed into the database, and OUT binds for values that are returned to PHP. A bind variable may be both IN and OUT. Whether a bind variable will be used for input or output is determined at run-time.

You must specify maxlength when using an OUT bind so that PHP allocates enough memory to hold the returned value.

For IN binds it is recommended to set the maxlength length if the statement is re-executed multiple times with different values for the PHP variable. Otherwise Oracle may truncate data to the length of the initial PHP variable value. If you don't know what the maximum length will be, then re-call oci_bind_by_name() with the current data size prior to each oci_execute() call. Binding an unnecessarily large length will have an impact on process memory in the database.

A bind call tells Oracle which memory address to read data from. For IN binds that address needs to contain valid data when oci_execute() is called. This means that the variable bound must remain in scope until execution. If it doesn't, unexpected results or errors such as "ORA-01460: unimplemented or unreasonable conversion requested" may occur. For OUT binds one symptom is no value being set in the PHP variable.

For a statement that is repeatedly executed, binding values that never change may reduce the ability of the Oracle optimizer to choose the best statement execution plan. Long running statements that are rarely re-executed may not benefit from binding. However in both cases, binding might be safer than joining strings into a SQL statement, as this can be a security risk if unfiltered user text is concatenated.

Parametry

statement

A valid OCI8 statement identifer.

bv_name

The colon-prefixed bind variable placeholder used in the statement. The colon is optional in bv_name. Oracle does not use question marks for placeholders.

variable

The PHP variable to be associated with bv_name

maxlength

Sets the maximum length for the data. If you set it to -1, this function will use the current length of variable to set the maximum length. In this case the variable must exist and contain data when oci_bind_by_name() is called.

type

The datatype that Oracle will treat the data as. The default type used is SQLT_CHR. Oracle will convert the data between this type and the database column (or PL/SQL variable type), when possible.

If you need to bind an abstract datatype (LOB/ROWID/BFILE) you need to allocate it first using the oci_new_descriptor() function. The length is not used for abstract datatypes and should be set to -1.

Possible values for type are:

  • SQLT_BFILEE or OCI_B_BFILE - for BFILEs;

  • SQLT_CFILEE or OCI_B_CFILEE - for CFILEs;

  • SQLT_CLOB or OCI_B_CLOB - for CLOBs;

  • SQLT_BLOB or OCI_B_BLOB - for BLOBs;

  • SQLT_RDD or OCI_B_ROWID - for ROWIDs;

  • SQLT_NTY or OCI_B_NTY - for named datatypes;

  • SQLT_INT or OCI_B_INT - for integers;

  • SQLT_CHR - for VARCHARs;

  • SQLT_BIN or OCI_B_BIN - for RAW columns;

  • SQLT_LNG - for LONG columns;

  • SQLT_LBI - for LONG RAW columns;

  • SQLT_RSET - for cursors created with oci_new_cursor().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Inserting data with oci_bind_by_name()

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, text VARCHAR2(40));

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn,"INSERT INTO mytab (id, text) VALUES(:id_bv, :text_bv)");

$id = 1;
$text = "Data to insert     ";
oci_bind_by_name($stid, ":id_bv", $id);
oci_bind_by_name($stid, ":text_bv", $text);
oci_execute($stid);

// Table now contains: 1, 'Data to insert     '

?>

Przykład #2 Binding once for multiple executions

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$a = array(1,3,5,7,11);  // data to insert

$stid = oci_parse($conn, 'INSERT INTO mytab (id) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $v, 20);
foreach ($a as $v) {
    $r = oci_execute($stid, OCI_DEFAULT);  // don't auto commit
}
oci_commit($conn); // commit everything at once

// Table contains five rows: 1, 3, 5, 7, 11

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #3 Binding with a foreach() loop

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT * FROM departments WHERE department_name = :dname AND location_id = :loc';
$stid = oci_parse($conn, $sql);

$ba = array(':dname' => 'IT Support', ':loc' => 1700);

foreach ($ba as $key => $val) {

    // oci_bind_by_name($stid, $key, $val) does not work
    // because it binds each placeholder to the same location: $val
    // instead use the actual location of the data: $ba[$key]
    oci_bind_by_name($stid, $key, $ba[$key]);
}

oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
foreach ($row as $item) {
    print $item."<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #4 Binding in a WHERE clause

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE employee_id = :eidbv';
$stid = oci_parse($conn, $sql);
$myeid = 101;
oci_bind_by_name($stid, ':eidbv', $myeid);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['LAST_NAME'] ."<br>\n";

// Output is
//    Kochhar

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #5 Binding with a LIKE clause

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that begin with 'South'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE city LIKE :bv");
$city = 'South%';  // '%' is a wildcard in SQL
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);

foreach ($res['CITY'] as $c) {
    print $c . "<br>\n";
}
// Output is
//   South Brunswick
//   South San Francisco
//   Southlake

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #6 Binding with REGEXP_LIKE

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that contain 'ing'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE REGEXP_LIKE(city, :bv)");
$city = '.*ing.*';
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);

foreach ($res['CITY'] as $c) {
    print $c . "<br>\n";
}
// Output is
//   Beijing
//   Singapore

oci_free_statement($stid);
oci_close($conn);

?>

For a small, fixed number of IN clause conditions, use individual bind variables. Values unknown at run time can be set to NULL. This allows a single statement to be used by all application users, maximizing Oracle DB cache efficiency.

Przykład #7 Binding Multiple Values in an IN Clause

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE employee_id in (:e1, :e2, :e3)';
$stid = oci_parse($conn, $sql);
$mye1 = 103;
$mye2 = 104;
$mye3 = NULL; // pretend we were not given this value
oci_bind_by_name($stid, ':e1', $mye1);
oci_bind_by_name($stid, ':e2', $mye2);
oci_bind_by_name($stid, ':e3', $mye3);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['LAST_NAME'] as $name) {
    print $name ."<br>\n";
}

// Output is
//   Ernst
//   Hunold

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #8 Binding a ROWID returned by a query

<?php

// Create the table with:
//   CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//   INSERT INTO mytab (id, salary, name) VALUES (1, 100, 'Chris');
//   COMMIT;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT ROWID, name FROM mytab WHERE id = :id_bv FOR UPDATE');
$id = 1;
oci_bind_by_name($stid, ':id_bv', $id);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$rid = $row['ROWID'];
$name = $row['NAME'];

// Change name to upper case & save the changes
$name = strtoupper($name);
$stid = oci_parse($conn, 'UPDATE mytab SET name = :n_bv WHERE ROWID = :r_bv');
oci_bind_by_name($stid, ':n_bv', $name);
oci_bind_by_name($stid, ':r_bv', $rid, -1, OCI_B_ROWID);
oci_execute($stid);

// The table now contains 1, 100, CHRIS

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #9 Binding a ROWID on INSERT

<?php

// This example inserts an id & name, and then updates the salary
// Create the table with:
//   CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//
// Based on original ROWID example by thies at thieso dot net (980221)

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $m = oci_error();
    trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = "INSERT INTO mytab (id, name) VALUES(:id_bv, :name_bv)
        RETURNING ROWID INTO :rid";

$ins_stid = oci_parse($conn, $sql);

$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_bind_by_name($ins_stid, ":id_bv",   $id,    10);
oci_bind_by_name($ins_stid, ":name_bv", $name,  32);
oci_bind_by_name($ins_stid, ":rid",     $rowid, -1, OCI_B_ROWID);

$sql = "UPDATE mytab SET salary = :salary WHERE ROWID = :rid";
$upd_stid = oci_parse($conn, $sql);
oci_bind_by_name($upd_stid, ":rid", $rowid, -1, OCI_B_ROWID);
oci_bind_by_name($upd_stid, ":salary", $salary,   32);

// ids and names to insert
$data = array(1111 => "Larry",
              2222 => "Bill",
              3333 => "Jim");

// Salary of each person
$salary = 10000;

// Insert and immediately update each row
foreach ($data as $id => $name) {
    oci_execute($ins_stid);
    oci_execute($upd_stid);
}

$rowid->free();
oci_free_statement($upd_stid);
oci_free_statement($ins_stid);

// Show the new rows
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    var_dump($row);
}

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #10 Binding for a PL/SQL stored function

<?php

//  Before running the PHP program, create a stored function in
//  SQL*Plus or SQL Developer:
//
//  CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
//  BEGIN
//      RETURN p * 3;
//  END;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p = 8;

$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);

// The return value is an OUT bind. The default type will be a string
// type so binding a length 40 means that at most 40 digits will be
// returned.
oci_bind_by_name($stid, ':r', $r, 40);

oci_execute($stid);

print "$r\n";   // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #11 Binding parameters for a PL/SQL stored procedure

<?php

//  Before running the PHP program, create a stored procedure in
//  SQL*Plus or SQL Developer:
//
//  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
//  BEGIN
//      p2 := p1 * 2;
//  END;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p1 = 8;

$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);

// The second procedure parameter is an OUT bind. The default type
// will be a string type so binding a length 40 means that at most 40
// digits will be returned.
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #12 Binding a CLOB column

<?php

// Before running, create the table:
//     CREATE TABLE mytab (mykey NUMBER, myclob CLOB);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$mykey = 12343;  // arbitrary key for this example;

$sql = "INSERT INTO mytab (mykey, myclob)
        VALUES (:mykey, EMPTY_CLOB())
        RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_DEFAULT);
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytab WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);

print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC)) {
  $result = $row['MYCLOB']->load();
  print '<tr><td>'.$result.'</td></tr>';
}
print '</table>';

?>

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Ostrzeżenie

Do not use magic_quotes_gpc or addslashes() and oci_bind_by_name() simultaneously as no quoting is needed. Any magically applied quotes will be written into your database because oci_bind_by_name() inserts data verbatim and does not remove quotes or escape characters.

Informacja:

If you bind a string to a CHAR column in a WHERE clause, remember that Oracle uses blank-padded comparison semantics for CHAR columns. Your PHP variable should be blank padded to the same width as the column for the WHERE clause to succeed.

Informacja:

The PHP variable argument is a reference. Some forms of loops do not work as expected:

<?php
foreach ($myarray as $key => $value)  {
    oci_bind_by_name($stid, $key, $value);
}
?>

This binds each key to the location of $value, so all bound variables end up pointing to the last loop iteration's value. Instead use the following:

<?php
foreach ($myarray as $key => $value) {
    oci_bind_by_name($stid, $key, $myarray[$key]);
}
?>

Informacja:

In PHP versions before 5.0.0 you must use ocibindbyname() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_bind_array_by_name() - Binds a PHP array to an Oracle PL/SQL array parameter
  • oci_parse() - Prepares an Oracle statement for execution

oci_bind_array_by_name
oci_cancel
OCI8 Funkcje


Anuluje odczytywanie z kursora

oci_bind_by_name
oci_client_version
OCI8 Funkcje
PHP Manual

oci_cancel

(PHP 5, PECL OCI8 >= 1.1.0)

oci_cancel — Anuluje odczytywanie z kursora

Opis

bool oci_cancel ( zasób $instrukcja )

Unieważnia kursor uwalniając wszystkie powiązane z nim zasoby i końcy mozliwość odczytywania z niego.

Parametry

instrukcja

Instrukcja OCI.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

oci_bind_by_name
oci_client_version
OCI8 Funkcje


Returns the Oracle client library version

oci_cancel
oci_close
OCI8 Funkcje
PHP Manual

oci_client_version

(PHP 5.3.7, PECL OCI8 >= 1.4.6)

oci_client_version — Returns the Oracle client library version

Opis

string oci_client_version ( void )

Returns a string containing the version number of the Oracle C client library that PHP is linked with.

Parametry

None

Zwracane wartości

Returns the version number as a string.

Przykłady

Przykład #1 oci_client_version() example

<?php
    echo "Client Version: " . oci_client_version(); // Client version: 11.2.0.2
?>

Notatki

Informacja:

Oracle libraries before 10gR2 do not have the underlying functionality to get the client library version number. The string "Unknown" will be returned in this case.

Zobacz też:

  • oci_server_version() - Returns the Oracle Database version

oci_cancel
oci_close
OCI8 Funkcje


Closes an Oracle connection

oci_client_version
oci_commit
OCI8 Funkcje
PHP Manual

oci_close

(PHP 5, PECL OCI8 >= 1.1.0)

oci_close — Closes an Oracle connection

Opis

bool oci_close ( resource $connection )

Unsets connection. The underlying database connection is closed if no other resources are using it and if it was created with oci_connect() or oci_new_connect().

It is recommended to close connections that are no longer needed because this makes database resources available for other users.

Parametry

connection

An Oracle connection identifier returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Closing a connection

Resources associated with a connection should be closed to ensure the underlying database connection is properly terminated and the database resources are released.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM departments');
$r = oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);

// Free the statement identifier when closing the connection
oci_free_statement($stid);
oci_close($conn);

?>

Przykład #2 Database connections are not closed until all references are closed

The internal refcount of a connection identifier must be zero before the underlying connection to the database is closed.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM departments');  // this increases the refcount on $conn
oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);

oci_close($conn);

// $conn is no long usable in the script but the underlying database
// connection is still held open until $stid is freed.
var_dump($conn);  // prints NULL

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user is still connected.
sleep(10);

// When $stid is freed, the database connection is physically closed
oci_free_statement($stid);

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user has disconnected.
sleep(10);

?>

Przykład #3 Closing a connection opened more than once

When database credentials are reused, both connections must be closed before the underlying database connection is closed.

<?php

$conn1 = oci_connect('hr', 'welcome', 'localhost/XE');

// Using the same credentials reuses the same underlying database connection
// Any uncommitted changes done on $conn1 will be visible in $conn2
$conn2 = oci_connect('hr', 'welcome', 'localhost/XE');

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that only one database user is connected.
sleep(10);

oci_close($conn1); // doesn't close the underlying database connection
var_dump($conn1);  // prints NULL because the variable $conn1 is no longer usable
var_dump($conn2);  // displays that $conn2 is still a valid connection resource

?>

Przykład #4 Connections are closed when variables go out of scope

When all variables referencing a connection go out of scope and are freed by PHP, a rollback occurs (if necessary) and the underlying connection to the database is closed.

<?php

function myfunc() {
    $conn = oci_connect('hr', 'hrpwd', 'localhost/XE');
    if (!$conn) {
        $e = oci_error();
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }

    $stid = oci_parse($conn, 'UPDATE mytab SET id = 100');
    oci_execute($stid, OCI_NO_AUTO_COMMIT);
    return "Finished";
}

$r = myfunc();
// At this point a rollback occurred and the underlying database connection was released.

print $r;  // displays the function return value "Finished"

?>

Notatki

Informacja:

Variables that have a dependency on the connection identifier, such as statement identifiers returned by oci_parse(), must also be freed before the underlying database connection is closed.

Informacja:

Prior to version PHP 5.1.2 (PECL OCI8 1.1) oci_close() was a no-op. In more recent versions it correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behavior of this function.

Informacja:

The oci_close() function does not close the underlying database connections created with oci_pconnect().

Informacja:

In PHP versions before 5.0.0 you must use ocilogoff() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_connect() - Connect to an Oracle database
  • oci_free_statement() - Frees all resources associated with statement or cursor

oci_client_version
oci_commit
OCI8 Funkcje


Commits the outstanding database transaction

oci_close
oci_connect
OCI8 Funkcje
PHP Manual

oci_commit

(PHP 5, PECL OCI8 >= 1.1.0)

oci_commit — Commits the outstanding database transaction

Opis

bool oci_commit ( resource $connection )

Commits the outstanding transaction for the Oracle connection. A commit ends the current transaction and makes permanent all changes. It releases all locks held.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

Parametry

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 oci_commit() example

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    oci_rollback($conn);  // rollback changes to both tables
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

Notatki

Informacja:

Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Informacja:

In PHP versions before 5.0.0 you must use ocicommit() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_execute() - Executes a statement
  • oci_rollback() - Rolls back the outstanding database transaction

oci_close
oci_connect
OCI8 Funkcje


Connect to an Oracle database

oci_commit
oci_define_by_name
OCI8 Funkcje
PHP Manual

oci_connect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_connect — Connect to an Oracle database

Opis

resource oci_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] )

Returns a connection identifier needed for most other OCI8 operations.

See Connection Handling for general information on connection management and connection pooling.

From PHP 5.1.2 (PECL OCI8 1.1) oci_close() can be used to close the connection.

The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that transactions in one handle are also in the other handles, because they use the same underlying database connection. If two handles need to be transactionally isolated from each other, use oci_new_connect() instead.

Parametry

username

The Oracle user name.

password

The password for username.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. With Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce connection time.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Zwracane wartości

Returns a connection identifier or FALSE on error.

Przykłady

Przykład #1 Basic oci_connect() using Easy Connect syntax

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Przykład #2 Basic oci_connect() using a Network Connect name

<?php

// Connects to the MYDB database described in tnsnames.ora file,
// One example tnsnames.ora entry for MYDB could be:
//   MYDB =
//     (DESCRIPTION =
//       (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))
//       (CONNECT_DATA =
//         (SERVER = DEDICATED)
//         (SERVICE_NAME = XE)
//       )
//     )

$conn = oci_connect('hr', 'welcome', 'MYDB');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Przykład #3 oci_connect() with an explicit character set

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE', 'AL32UTF8');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Przykład #4 Using multiple calls to oci_connect()

<?php

$c1 = oci_connect("hr", "welcome", 'localhost/XE');
$c2 = oci_connect("hr", "welcome", 'localhost/XE');

// Both $c1 and $c2 show the same PHP resource id meaning they use the
// same underlying database connection
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";

function create_table($conn)
{
    $stmt = oci_parse($conn, "create table hallo (test varchar2(64))");
    oci_execute($stmt);
    echo "Created table<br>\n";
}

function drop_table($conn)
{
    $stmt = oci_parse($conn, "drop table hallo");
    oci_execute($stmt);
    echo "Dropped table<br>\n";
}

function insert_data($connname, $conn)
{
    $stmt = oci_parse($conn, "insert into hallo
              values(to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
    oci_execute($stmt, OCI_DEFAULT);
    echo "$connname inserted row without committing<br>\n";
}

function rollback($connname, $conn)
{
    oci_rollback($conn);
    echo "$connname rollback<br>\n";
}

function select_data($connname, $conn)
{
    $stmt = oci_parse($conn, "select * from hallo");
    oci_execute($stmt, OCI_DEFAULT);
    echo "$connname ----selecting<br>\n";
    while (oci_fetch($stmt)) {
        echo "    " . oci_result($stmt, "TEST") . "<br>\n";
    }
    echo "$connname ----done<br>\n";
}

create_table($c1);

insert_data('c1', $c1);   // Insert a row using c1
sleep(2);                 // sleep to show a different timestamp for the 2nd row
insert_data('c2', $c2);   // Insert a row using c2

select_data('c1', $c1);   // Results of both inserts are returned
select_data('c2', $c2);   // Results of both inserts are returned

rollback('c1', $c1);      // Rollback using c1

select_data('c1', $c1);   // Both inserts have been rolled back
select_data('c2', $c2);

drop_table($c1);

// Closing one of the connections makes the PHP variable unusable, but
// the other could be used
oci_close($c1);
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";

// Output is:
//    c1 is Resource id #5
//    c2 is Resource id #5
//    Created table
//    c1 inserted row without committing
//    c2 inserted row without committing
//    c1 ----selecting
//        09-DEC-09 12:14:43
//        09-DEC-09 12:14:45
//    c1 ----done
//    c2 ----selecting
//        09-DEC-09 12:14:43
//        09-DEC-09 12:14:45
//    c2 ----done
//    c1 rollback
//    c1 ----selecting
//    c1 ----done
//    c2 ----selecting
//    c2 ----done
//    Dropped table
//    c1 is
//    c2 is Resource id #5

?>

Notatki

Informacja:

An incorrectly installed or configured OCI8 extension will often manifest itself as a connection problem or error. See Installing/Configuring for troubleshooting information.

Informacja:

In PHP versions before 5.0.0 use ocilogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_pconnect() - Connect to an Oracle database using a persistent connection
  • oci_new_connect() - Connect to the Oracle server using a unique connection
  • oci_close() - Closes an Oracle connection

oci_commit
oci_define_by_name
OCI8 Funkcje


Associates a PHP variable with a column for query fetches

oci_connect
oci_error
OCI8 Funkcje
PHP Manual

oci_define_by_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_define_by_name — Associates a PHP variable with a column for query fetches

Opis

bool oci_define_by_name ( resource $statement , string $column_name , mixed &$variable [, int $type = SQLT_CHR ] )

Associates a PHP variable with a column for query fetches using oci_fetch().

The oci_define_by_name() call must occur before executing oci_execute().

Parametry

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

column_name

The column name used in the query.

Use uppercase for Oracle's default, non-case sensitive column names. Use the exact column name case for case-sensitive column names.

variable

The PHP variable that will contain the returned column value.

type

The data type to be returned. Generally not needed. Note that Oracle-style data conversions are not performed. For example, SQLT_INT will be ignored and the returned data type will still be SQLT_CHR.

You can optionally use oci_new_descriptor() to allocate LOB/ROWID/BFILE descriptors.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 oci_define_by_name() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);

// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
    echo "Location id $locid is $city<br>\n";
}

// Displays:
//   Location id 1000 is Roma
//   Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #2 oci_define_by_name() with case sensitive column names

<?php

/*
  Before running, create the table with a case sensitive column name:
    CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
    INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// Use uppercase for non case-sensitive column names
oci_define_by_name($stid, 'ID', $id);

// Use the exact case for case-sensitive column names
oci_define_by_name($stid, 'MyDescription', $mydesc);

oci_execute($stid);

while (oci_fetch($stid)) {
    echo "id $id is $mydesc<br>\n";
}

// Displays:
//   id 1 is Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #3 oci_define_by_name() with LOB columns

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, fruit CLOB);
    INSERT INTO mytab (id, fruit) values (1, 'apple');
    INSERT INTO mytab (id, fruit) values (2, 'orange');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);
oci_define_by_name($stid, 'FRUIT', $fruit);  // $fruit will become a LOB descriptor

oci_execute($stid);

while (oci_fetch($stid)) {
    echo $id . " is " . $fruit->load(100) . "<br>\n";
}

// Displays:
//   1 is apple
//   2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

Przykład #4 oci_define_by_name() with an explicit type

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, fruit CLOB);
    INSERT INTO mytab (id, fruit) values (1, 'apple');
    INSERT INTO mytab (id, fruit) values (2, 'orange');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);

$fruit = oci_new_descriptor($conn, OCI_D_LOB);
oci_define_by_name($stid, 'FRUIT', $fruit, OCI_D_CLOB);

oci_execute($stid);

while (oci_fetch($stid)) {
    echo $id . " is " . $fruit->load(100) . "<br>\n";
}

// Displays:
//   1 is apple
//   2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

Notatki

Informacja:

In PHP versions before 5.0.0 use ocidefinebyname() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_new_descriptor() - Initializes a new empty LOB or FILE descriptor

oci_connect
oci_error
OCI8 Funkcje


Returns the last error found

oci_define_by_name
oci_execute
OCI8 Funkcje
PHP Manual

oci_error

(PHP 5, PECL OCI8 >= 1.1.0)

oci_error — Returns the last error found

Opis

array oci_error ([ resource $resource ] )

Returns the last error found.

The function should be called immediately after an error occurs. Errors are cleared by a successful statement.

Parametry

resource

For most errors, resource is the
resource handle that was passed to the failing function call.
For connection errors with oci_connect(),
oci_new_connect() or
oci_pconnect() do not pass resource.

Zwracane wartości

If no error is found, oci_error() returns FALSE. Otherwise, oci_error() returns the error information as an associative array.

oci_error() Array Description
Array key | Type | Opis
code | integer | The Oracle error number.
message | string | The Oracle error text.
offset | integer | The byte position of an error in the SQL statement. If there was no statement, this is 0
sqltext | string | The SQL statement text. If there was no statement, this is an empty string.

Rejestr zmian

Wersja | Opis
4.3.0 | The offset and sqltext entries were added.

Przykłady

Przykład #1 Displaying the Oracle error message after a connection error

<?php
$conn = oci_connect("hr", "welcome", "localhost/XE");
if (!$conn) {
    $e = oci_error();   // For oci_connect errors do not pass a handle
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>

Przykład #2 Displaying the Oracle error message after a parsing error

<?php
$stid = oci_parse($conn, "select ' from dual");  // note mismatched quote
if (!$stid) {
    $e = oci_error($conn);  // For oci_parse errors pass the connection handle
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>

Przykład #3 Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error

<?php
$stid = oci_parse($conn, "select does_not_exist from dual");
$r = oci_execute($stid);
if (!$r) {
    $e = oci_error($stid);  // For oci_execute errors pass the statement handle
    print htmlentities($e['message']);
    print "\n<pre>\n";
    print htmlentities($e['sqltext']);
    printf("\n%".($e['offset']+1)."s", "^");
    print  "\n</pre>\n";
}
?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocierror() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

oci_define_by_name
oci_execute
OCI8 Funkcje


Executes a statement

oci_error
oci_fetch_all
OCI8 Funkcje
PHP Manual

oci_execute

(PHP 5, PECL OCI8 >= 1.1.0)

oci_execute — Executes a statement

Opis

bool oci_execute ( resource $statement [, int $mode = OCI_COMMIT_ON_SUCCESS ] )

Executes a statement previously returned from oci_parse().

After execution, statements like INSERT will have data committed to the database by default. For statements like SELECT, execution performs the logic of the query. Query results can subsequently be fetched in PHP with functions like oci_fetch_array().

Each parsed statement may be executed multiple times, saving the cost of re-parsing. This is commonly used for INSERT statements when data is bound with oci_bind_by_name().

Parametry

statement

A valid OCI statement identifier.

mode

An optional second parameter can be one of the following constants:

Execution Modes
Constant | Description
OCI_COMMIT_ON_SUCCESS | Automatically commit all outstanding changes for this connection when the statement has succeeded. This is the default.
OCI_DEFAULT | Obsolete as of PHP 5.3.2 (PECL OCI8 1.4) but still available for backward compatibility. Use the equivalent OCI_NO_AUTO_COMMIT in new code.
OCI_DESCRIBE_ONLY | Make query meta data available to functions like oci_field_name() but do not create a result set. Any subsequent fetch call such as oci_fetch_array() will fail.
OCI_NO_AUTO_COMMIT | Do not automatically commit changes. Prior to PHP 5.3.2 (PECL OCI8 1.4) use OCI_DEFAULT which is an alias for OCI_NO_AUTO_COMMIT.

Using OCI_NO_AUTO_COMMIT mode starts a transaction. Transactions are automatically rolled back when the connection is closed, or when the script ends. Explicitly call oci_commit() to commit a transaction, or oci_rollback() to abort it.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

If OCI_NO_AUTO_COMMIT mode is used for any statement including queries, and oci_commit() or oci_rollback() is not subsequently called, then OCI8 will perform a rollback at the end of the script even if no data was changed. To avoid an unnecessary rollback, many scripts do not use OCI_NO_AUTO_COMMIT mode for queries or PL/SQL. Be careful to ensure the appropriate transactional consistency for the application when using oci_execute() with different modes in the same script.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 oci_execute() for queries

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Przykład #2 oci_execute() without specifying a mode example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');

oci_execute($stid); // The row is committed and immediately visible to other users

?>

Przykład #3 oci_execute() with OCI_NO_AUTO_COMMIT example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $i, 10);
for ($i = 1; $i <= 5; ++$i) {
    oci_execute($stid, OCI_NO_AUTO_COMMIT);  // use OCI_DEFAULT for PHP <= 5.3.1
}
oci_commit($conn);  // commits all new values: 1, 2, 3, 4, 5

?>

Przykład #4 oci_execute() with different commit modes example

<?php

// Before running, create the table:
//   CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stid, OCI_NO_AUTO_COMMIT);  // data not committed

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (456)');
oci_execute($stid);  // commits both 123 and 456 values

?>

Przykład #5 oci_execute() with OCI_DESCRIBE_ONLY example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM locations');
oci_execute($s, OCI_DESCRIBE_ONLY);
for ($i = 1; $i <= oci_num_fields($stid); ++$i) {
    echo oci_field_name($stid, $i) . "<br>\n";
}

?>

Notatki

Informacja:

Transactions are automatically rolled back when connections are closed, or when the script ends, whichever is soonest. Explicitly call oci_commit() to commit a transaction.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Informacja:

Because the oci_execute() function generally sends the statement to the database, oci_execute() can identify some statement syntax errors that the lightweight, local oci_parse() function does not.

Informacja:

In PHP versions before 5.0.0 use ociexecute() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_parse() - Prepares an Oracle statement for execution

oci_error
oci_fetch_all
OCI8 Funkcje


Fetches multiple rows from a query into a two-dimensional array

oci_execute
oci_fetch_array
OCI8 Funkcje
PHP Manual

oci_fetch_all

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_all — Fetches multiple rows from a query into a two-dimensional array

Opis

int oci_fetch_all ( resource $statement , array &$output [, int $skip = 0 [, int $maxrows = -1 [, int $flags = OCI_FETCHSTATEMENT_BY_COLUMN + OCI_ASSOC ]]] )

Fetches multiple rows from a query into a two-dimensional array. By default, all rows are returned.

This function can be called only once for each query executed with oci_execute().

Parametry

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

output

The variable to contain the returned rows.

LOB columns are returned as strings, where Oracle supports conversion.

See oci_fetch_array() for more information on how data and types are fetched.

skip

The number of initial rows to discard when fetching the result. The default value is 0, so the first row onwards is returned.

maxrows

The number of rows to return. The default is -1 meaning return all the rows from skip + 1 onwards.

flags

Parameter flags indicates the array structure and whether associative arrays should be used.

oci_fetch_all() Array Structure Modes
Constant | Description
OCI_FETCHSTATEMENT_BY_ROW | The outer array will contain one sub-array per query row.
OCI_FETCHSTATEMENT_BY_COLUMN | The outer array will contain one sub-array per query column. This is the default.

Arrays can be indexed by column heading or numerically.

oci_fetch_all() Array Index Modes
Constant | Description
OCI_NUM | Numeric indexes are used for each column's array.
OCI_ASSOC | Associative indexes are used for each column's array. This is the default.

Use the addition operator "+" to choose a combination of array structure and index modes.

Oracle's default, non-case sensitive column names will have uppercase array keys. Case-sensitive column names will have array keys using the exact column case. Use var_dump() on output to verify the appropriate case to use for each query.

Queries that have more than one column with the same name should use column aliases. Otherwise only one of the columns will appear in an associative array.

Zwracane wartości

Returns the number of rows in output, which may be 0 or more, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 oci_fetch_all() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// var_dump output is:
//    2 rows fetched
//    array(2) {
//      ["POSTAL_CODE"]=>
//      array(2) {
//        [0]=>
//        string(6) "00989x"
//        [1]=>
//        string(6) "10934x"
//      }
//      ["CITY"]=>
//      array(2) {
//        [0]=>
//        string(4) "Roma"
//        [1]=>
//        string(6) "Venice"
//      }
//    }

// Pretty-print the results
echo "<table border='1'>\n";
foreach ($res as $col) {
    echo "<tr>\n";
    foreach ($col as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #2 oci_fetch_all() example with OCI_FETCHSTATEMENT_BY_ROW

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
//    2 rows fetched
//    array(2) {
//      [0]=>
//      array(2) {
//        ["POSTAL_CODE"]=>
//        string(6) "00989x"
//        ["CITY"]=>
//        string(4) "Roma"
//      }
//      [1]=>
//      array(2) {
//        ["POSTAL_CODE"]=>
//        string(6) "10934x"
//        ["CITY"]=>
//        string(6) "Venice"
//      }
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #3 oci_fetch_all() with OCI_NUM

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_NUM);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
//    2 rows fetched
//    array(2) {
//      [0]=>
//      array(2) {
//        [0]=>
//        string(6) "00989x"
//        [1]=>
//        string(4) "Roma"
//      }
//      [1]=>
//      array(2) {
//        [0]=>
//        string(6) "10934x"
//        [1]=>
//        string(6) "Venice"
//      }
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Notatki

Informacja:

Using skip is very inefficient. All the rows to be skipped are included in the result set that is returned from the database to PHP. They are then discarded. It is more efficient to use SQL to restrict the offset and range of rows in the query. See oci_fetch_array() for an example.

Informacja:

Queries that return a large number of rows can be more memory efficient if a single-row fetching function like oci_fetch_array() is used.

Informacja:

For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

Informacja:

In PHP versions before 5.0.0 you must use ocifetchstatement() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_set_prefetch() - Sets number of rows to be prefetched by queries

oci_execute
oci_fetch_array
OCI8 Funkcje


Returns the next row from a query as an associative or numeric array

oci_fetch_all
oci_fetch_assoc
OCI8 Funkcje
PHP Manual

oci_fetch_array

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_array — Returns the next row from a query as an associative or numeric array

Opis

array oci_fetch_array ( resource $statement [, int $mode ] )

Returns an array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parametry

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

mode

An optional second parameter can be any combination of the following constants:

oci_fetch_array() Modes
Constant | Description
OCI_BOTH | Returns an array with both associative and numeric indices. This is the same as OCI_ASSOC + OCI_NUM and is the default behavior.
OCI_ASSOC | Returns an associative array.
OCI_NUM | Returns a numeric array.
OCI_RETURN_NULLS | Creates elements for NULL fields. The element values will be a PHP NULL.
OCI_RETURN_LOBS | Returns the contents of LOBs instead of the LOB descriptors.

The default mode is OCI_BOTH.

Use the addition operator "+" to specify more than one mode at a time.

Zwracane wartości

Returns an array with associative and/or numeric indices. If there are no more rows in the statement then FALSE is returned.

By default, LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase associative indices in the result array. Case-sensitive column names will have array indices using the exact column case. Use var_dump() on the result array to verify the appropriate case to use for each query.

Przykłady

Przykład #1 oci_fetch_array() with OCI_BOTH

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_BOTH))) {
    // Use the uppercase column names for the associative array indices
    echo $row[0] . " and " . $row['DEPARTMENT_ID']   . " are the same<br>\n";
    echo $row[1] . " and " . $row['DEPARTMENT_NAME'] . " are the same<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #2 oci_fetch_array() with OCI_NUM

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_NUM))) {
    echo $row[0] . "<br>\n";
    echo $row[1]->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #3 oci_fetch_array() with OCI_ASSOC

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
    echo $row['ID'] . "<br>\n";
    echo $row['DESCRIPTION']->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #4 oci_fetch_array() with OCI_RETURN_NULLS

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC))) { // Ignore NULLs
    var_dump($row);
}

/*
The above code prints:
  array(1) {
    [1]=>
    string(1) "1"
  }
*/

$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS))) { // Fetch NULLs
    var_dump($row);
}

/*
The above code prints:
  array(2) {
    [1]=>
    string(1) "1"
    ["NULL"]=>
    NULL
  }
*/

?>

Przykład #5 oci_fetch_array() with OCI_RETURN_LOBS

<?php

/*
  Before running, create the table:
      CREATE TABLE mytab (id NUMBER, description CLOB);
      INSERT INTO mytab (id, description) values (1, 'A very long string');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS))) {
    echo $row['ID'] . "<br>\n";
    echo $row['DESCRIPTION'] . "<br>\n"; // this contains all of DESCRIPTION
}

// Output is:
//    1
//    A very long string

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #6 oci_fetch_array() with case sensitive column names

<?php

/*
   Before running, create the table:
      CREATE TABLE mytab ("Name" VARCHAR2(20), city VARCHAR2(20));
      INSERT INTO mytab ("Name", city) values ('Chris', 'Melbourne');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

// Because 'Name' was created as a case-sensitive column, that same
// case is used for the array index.  However uppercase 'CITY' must
// be used for the case-insensitive column index
print $row['Name'] . "<br>\n";   //  prints Chris
print $row['CITY'] . "<br>\n";   //  prints Melbourne

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #7 oci_fetch_array() with columns having duplicate names

<?php

/*
  Before running, create the tables:
      CREATE TABLE mycity (id NUMBER, name VARCHAR2(20));
      INSERT INTO mycity (id, name) values (1, 'Melbourne');
      CREATE TABLE mycountry (id NUMBER, name VARCHAR2(20));
      INSERT INTO mycountry (id, name) values (1, 'Australia');
      COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT mycity.name, mycountry.name
        FROM mycity, mycountry
        WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);

// Output only contains one "NAME" entry:
//    array(1) {
//      ["NAME"]=>
//      string(9) "Australia"
//    }

// To query a repeated column name, use an SQL column alias like "AS ctnm":
$sql = 'SELECT mycity.name AS ctnm, mycountry.name
        FROM mycity, mycountry
        WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);

// Output now contains both columns selected:
//    array(2) {
//      ["CTNM"]=>
//      string(9) "Melbourne"
//      ["NAME"]=>
//      string(9) "Australia"
//    }

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #8 oci_fetch_array() with DATE columns

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Set the date format for this connection.
// For performance reasons, consider changing the format
// in a trigger or with environment variables instead
$stid = oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
oci_execute($stid);

$stid = oci_parse($conn, 'SELECT hire_date FROM employees WHERE employee_id = 188');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['HIRE_DATE'] . "<br>\n";  // prints 1997-06-14

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #9 oci_fetch_array() with REF CURSOR

<?php
/*
  Create the PL/SQL stored procedure as:

  CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
  BEGIN
    OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Execute the returned REF CURSOR and fetch from it like a statement identifier
oci_execute($refcur);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

Przykład #10 oci_fetch_array() with a LIMIT-like query

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// This is the query you want to execute
$sql = 'SELECT city, postal_code FROM locations ORDER BY city';

// This nested query selects a subset of rows from $sql.
// In production environments, be careful to avoid SQL Injection
// issues with concatenated SQL statements
$limit_sql =
   'select *
    from ( select a.*, rownum as rnum
        from (' . $sql . ') a
        where rownum < :FIRST_ROW + :NUM_ROWS )
    where rnum >= :FIRST_ROW';

$first = 1;  // start with the first row
$num   = 5;  // return 5 rows
$stid = oci_parse($conn, $limit_sql);
oci_bind_by_name($stid, ':FIRST_ROW', $first);
oci_bind_by_name($stid, ':NUM_ROWS', $num);
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
    echo $row['CITY'] . " " . $row['POSTAL_CODE'] . "<br>\n";
}

// Output is:
//    Beijing 190518x
//    Bern 3095x
//    Bombay 490231x
//    Geneva 1730x
//    Hiroshima 6823x

oci_free_statement($stid);
oci_close($conn);

?>

Notatki

Informacja:

Associative array indices need to be in uppercase for standard Oracle columns that were created with case insensitive names.

Informacja:

For queries returning a large number of rows, performance can be significantly improved by increasing oci8.default_prefetch or using oci_set_prefetch().

Informacja:

The function oci_fetch_array() is insignificantly slower than oci_fetch_assoc() or oci_fetch_row(), but is more flexible.

Zobacz też:

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_set_prefetch() - Sets number of rows to be prefetched by queries

oci_fetch_all
oci_fetch_assoc
OCI8 Funkcje


Returns the next row from a query as an associative array

oci_fetch_array
oci_fetch_object
OCI8 Funkcje
PHP Manual

oci_fetch_assoc

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_assoc — Returns the next row from a query as an associative array

Opis

array oci_fetch_assoc ( resource $statement )

Returns an associative array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

Calling oci_fetch_assoc() is identical to calling oci_fetch_array() with OCI_ASSOC + OCI_RETURN_NULLS.

Parametry

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Zwracane wartości

Returns an associative array. If there are no more rows in the statement then FALSE is returned.

Notatki

Informacja:

See oci_fetch_array() for examples of fetching rows.

Zobacz też:

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array

oci_fetch_array
oci_fetch_object
OCI8 Funkcje


Returns the next row from a query as an object

oci_fetch_assoc
oci_fetch_row
OCI8 Funkcje
PHP Manual

oci_fetch_object

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_object — Returns the next row from a query as an object

Opis

object oci_fetch_object ( resource $statement )

Returns an object containing the next result-set row of a query. Each attribute of the object corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parametry

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Zwracane wartości

Returns an object. Each attribute of the object corresponds to a column of the row. If there are no more rows in the statement then FALSE is returned.

Any LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase attribute names. Case-sensitive column names will have attribute names using the exact column case. Use var_dump() on the result object to verify the appropriate case to use for each query.

Attribute values will be NULL for any NULL data fields.

Przykłady

Przykład #1 oci_fetch_object() example

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, description VARCHAR2(30));
    INSERT INTO mytab (id, description) values (1, 'Fish and Chips');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid))) {
    // Use upper case attribute names for each standard Oracle column
    echo $row->ID . "<br>\n";
    echo $row->DESCRIPTION . "<br>\n";
}

// Output is:
//    1
//    Fish and Chips

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #2 oci_fetch_object() with case sensitive column names

<?php

/*
  Before running, create the table with a case sensitive column name:
    CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
    INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, "MyDescription" FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid))) {
    // Use upper case attribute names for each standard Oracle column
    echo $row->ID . "<br>\n";
    // Use the exact case for the case sensitive column name
    echo $row->MyDescription . "<br>\n";
}

// Output is:
//    1
//    Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #3 oci_fetch_object() with LOBs

<?php

/*
  Before running, create the table:
    CREATE TABLE mytab (id NUMBER, description CLOB);
    INSERT INTO mytab (id, description) values (1, 'A very long string');
    COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid))) {
    echo $row->ID . "<br>\n";
    // The following will output the first 11 bytes from DESCRIPTION
    echo $row->DESCRIPTION->read(11) . "<br>\n";
}

// Output is:
//    1
//    A very long

oci_free_statement($stid);
oci_close($conn);

?>

Zobacz też:

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_row() - Returns the next row from a query as a numeric array

oci_fetch_assoc
oci_fetch_row
OCI8 Funkcje


Returns the next row from a query as a numeric array

oci_fetch_object
oci_fetch
OCI8 Funkcje
PHP Manual

oci_fetch_row

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch_row — Returns the next row from a query as a numeric array

Opis

array oci_fetch_row ( resource $statement )

Returns a numerically indexed array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns FALSE, indicating no more rows exist.

Calling oci_fetch_row() is identical to calling oci_fetch_array() with OCI_NUM + OCI_RETURN_NULLS.

Parametry

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Zwracane wartości

Returns a numerically indexed array. If there are no more rows in the statement then FALSE is returned.

Notatki

Informacja:

See oci_fetch_array() for examples of fetching rows.

Zobacz też:

  • oci_fetch() - Fetches the next row from a query into internal buffers
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object

oci_fetch_object
oci_fetch
OCI8 Funkcje


Fetches the next row from a query into internal buffers

oci_fetch_row
oci_field_is_null
OCI8 Funkcje
PHP Manual

oci_fetch

(PHP 5, PECL OCI8 >= 1.1.0)

oci_fetch — Fetches the next row from a query into internal buffers

Opis

bool oci_fetch ( resource $statement )

Fetches the next row from a query into internal buffers accessible either with oci_result(), or by using variables previously defined with oci_define_by_name().

See oci_fetch_array() for general information about fetching data.

Parametry

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

Zwracane wartości

Returns TRUE on success or FALSE if there are no more rows in the statement.

Przykłady

Przykład #1 oci_fetch() with defined variables

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);

// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
    echo "Location id $locid is $city<br>\n";
}

// Displays:
//   Location id 1000 is Roma
//   Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #2 oci_fetch() with oci_result()

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (oci_fetch($stid)) {
    echo oci_result($stid, 'LOCATION_ID') . " is ";
    echo oci_result($stid, 'CITY') . "<br>\n";
}

// Displays:
//   1000 is Roma
//   1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Notatki

Informacja:

In PHP versions before 5.0.0 use ocifetch() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_define_by_name() - Associates a PHP variable with a column for query fetches
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_result() - Returns field's value from the fetched row

oci_fetch_row
oci_field_is_null
OCI8 Funkcje


Checks if the field is NULL

oci_fetch
oci_field_name
OCI8 Funkcje
PHP Manual

oci_field_is_null

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_is_null — Checks if the field is NULL

Opis

bool oci_field_is_null ( resource $statement , mixed $field )

Checks if the given field from the statement is NULL.

Parametry

statement

A valid OCI statement identifier.

field

Can be a field's index or a field's name (uppercased).

Zwracane wartości

Returns TRUE if field is NULL, FALSE otherwise.

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.

oci_fetch
oci_field_name
OCI8 Funkcje


Returns the name of a field from the statement

oci_field_is_null
oci_field_precision
OCI8 Funkcje
PHP Manual

oci_field_name

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_name — Returns the name of a field from the statement

Opis

string oci_field_name ( resource $statement , int $field )

Returns the name of the field.

Parametry

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Zwracane wartości

Returns the name as a string, or FALSE on errors.

Przykłady

Przykład #1 oci_field_name() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>\n";
oci_free_statement($stmt);
oci_close($conn);
?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.

Zobacz też:

  • oci_num_fields() - Returns the number of result columns in a statement
  • oci_field_type() - Returns field's data type
  • oci_field_size() - Returns field's size

oci_field_is_null
oci_field_precision
OCI8 Funkcje


Tell the precision of a field

oci_field_name
oci_field_scale
OCI8 Funkcje
PHP Manual

oci_field_precision

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_precision — Tell the precision of a field

Opis

int oci_field_precision ( resource $statement , int $field )

Returns precision of the field.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parametry

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Zwracane wartości

Returns the precision as an integer, or FALSE on errors.

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.

Zobacz też:

  • oci_field_scale() - Tell the scale of the field
  • oci_field_type() - Returns field's data type

oci_field_name
oci_field_scale
OCI8 Funkcje


Tell the scale of the field

oci_field_precision
oci_field_size
OCI8 Funkcje
PHP Manual

oci_field_scale

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_scale — Tell the scale of the field

Opis

int oci_field_scale ( resource $statement , int $field )

Returns the scale of the column with field index.

For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).

Parametry

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Zwracane wartości

Returns the scale as an integer, or FALSE on errors.

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.

Zobacz też:

  • oci_field_precision() - Tell the precision of a field
  • oci_field_type() - Returns field's data type

oci_field_precision
oci_field_size
OCI8 Funkcje


Returns field's size

oci_field_scale
oci_field_type_raw
OCI8 Funkcje
PHP Manual

oci_field_size

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_size — Returns field's size

Opis

int oci_field_size ( resource $statement , mixed $field )

Returns the size of a field.

Parametry

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Zwracane wartości

Returns the size of a field in bytes, or FALSE on errors.

Przykłady

Przykład #1 oci_field_size() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);
    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>";

oci_free_statement($stmt);
oci_close($conn);
?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.

Zobacz też:

  • oci_num_fields() - Returns the number of result columns in a statement
  • oci_field_name() - Returns the name of a field from the statement

oci_field_scale
oci_field_type_raw
OCI8 Funkcje


Tell the raw Oracle data type of the field

oci_field_size
oci_field_type
OCI8 Funkcje
PHP Manual

oci_field_type_raw

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_type_raw — Tell the raw Oracle data type of the field

Opis

int oci_field_type_raw ( resource $statement , int $field )

Returns Oracle's raw data type of the field.

However, if you want to get field's type, then oci_field_type() will suit you better.

Parametry

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Zwracane wartości

Returns Oracle's raw data type as a string, or FALSE on errors.

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.

oci_field_size
oci_field_type
OCI8 Funkcje


Returns field's data type

oci_field_type_raw
oci_free_statement
OCI8 Funkcje
PHP Manual

oci_field_type

(PHP 5, PECL OCI8 >= 1.1.0)

oci_field_type — Returns field's data type

Opis

mixed oci_field_type ( resource $statement , int $field )

Returns a field's data type.

Parametry

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Zwracane wartości

Returns the field data type as a string, or FALSE on errors.

Zwracane wartości

Przykład #1 oci_field_type() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "SELECT * FROM emp");
oci_execute($stmt);

echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>";

$ncols = oci_num_fields($stmt);

for ($i = 1; $i <= $ncols; $i++) {
    $column_name  = oci_field_name($stmt, $i);
    $column_type  = oci_field_type($stmt, $i);
    $column_size  = oci_field_size($stmt, $i);

    echo "<tr>";
    echo "<td>$column_name</td>";
    echo "<td>$column_type</td>";
    echo "<td>$column_size</td>";
    echo "</tr>";
}

echo "</table>\n";

oci_free_statement($stmt);
oci_close($conn);
?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.

Zobacz też:

  • oci_num_fields() - Returns the number of result columns in a statement
  • oci_field_name() - Returns the name of a field from the statement
  • oci_field_size() - Returns field's size

oci_field_type_raw
oci_free_statement
OCI8 Funkcje


Frees all resources associated with statement or cursor

oci_field_type
oci_internal_debug
OCI8 Funkcje
PHP Manual

oci_free_statement

(PHP 5, PECL OCI8 >= 1.1.0)

oci_free_statement — Frees all resources associated with statement or cursor

Opis

bool oci_free_statement ( resource $statement )

Frees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.

Parametry

statement

A valid OCI statement identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

oci_field_type
oci_internal_debug
OCI8 Funkcje


Enables or disables internal debug output

oci_free_statement
oci_lob_copy
OCI8 Funkcje
PHP Manual

oci_internal_debug

(PHP 5, PECL OCI8 >= 1.1.0)

oci_internal_debug — Enables or disables internal debug output

Opis

void oci_internal_debug ( bool $onoff )

Enables or disables internal debug output.

Parametry

onoff

Set this to FALSE to turn debug output off or TRUE to turn it on.

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.

oci_free_statement
oci_lob_copy
OCI8 Funkcje


Copies large object

oci_internal_debug
oci_lob_is_equal
OCI8 Funkcje
PHP Manual

oci_lob_copy

(PHP 5, PECL OCI8 >= 1.1.0)

oci_lob_copy — Copies large object

Opis

bool oci_lob_copy ( OCI-Lob $lob_to , OCI-Lob $lob_from [, int $length = 0 ] )

Copies a large object or a part of a large object to another large object. Old LOB-recipient data will be overwritten.

If you need to copy a particular part of a LOB to a particular position of a LOB, use OCI-Lob::seek() to move LOB internal pointers.

Parametry

lob_to

The destination LOB.

lob_from

The copied LOB.

length

Indicates the length of data to be copied.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

oci_internal_debug
oci_lob_is_equal
OCI8 Funkcje


Compares two LOB/FILE locators for equality

oci_lob_copy
oci_new_collection
OCI8 Funkcje
PHP Manual

oci_lob_is_equal

(PHP 5, PECL OCI8 >= 1.1.0)

oci_lob_is_equal — Compares two LOB/FILE locators for equality

Opis

bool oci_lob_is_equal ( OCI-Lob $lob1 , OCI-Lob $lob2 )

Compares two LOB/FILE locators.

Parametry

lob1

A LOB identifier.

lob2

A LOB identifier.

Zwracane wartości

Returns TRUE if these objects are equal, FALSE otherwise.

oci_lob_copy
oci_new_collection
OCI8 Funkcje


Allocates new collection object

oci_lob_is_equal
oci_new_connect
OCI8 Funkcje
PHP Manual

oci_new_collection

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_collection — Allocates new collection object

Opis

OCI-Collection oci_new_collection ( resource $connection , string $tdo [, string $schema = NULL ] )

Allocates a new collection object.

Parametry

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

tdo

Should be a valid named type (uppercase).

schema

Should point to the scheme, where the named type was created. The name of the current user is the default value.

Zwracane wartości

Returns a new OCICollection object or FALSE on error.

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocinewcollection() instead. This name still can be used, it was left as alias of oci_new_collection() for downwards compatability. This, however, is deprecated and not recommended.

oci_lob_is_equal
oci_new_connect
OCI8 Funkcje


Connect to the Oracle server using a unique connection

oci_new_collection
oci_new_cursor
OCI8 Funkcje
PHP Manual

oci_new_connect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_connect — Connect to the Oracle server using a unique connection

Opis

resource oci_new_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] )

Establishes a new connection to an Oracle server and logs on.

Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache connections and will always return a brand-new freshly opened connection handle. This is useful if your application needs transactional isolation between two sets of queries.

Parametry

username

The Oracle user name.

password

The password for username.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. With Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce connection time.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Zwracane wartości

Returns a connection identifier or FALSE on error.

Przykłady

The following demonstrates how you can separate connections.

Przykład #1 oci_new_connect() example

<?php
echo "<html><pre>";
$db = "";

$c1 = oci_connect("scott", "tiger", $db);
$c2 = oci_new_connect("scott", "tiger", $db);

function create_table($conn)
{
  $stmt = oci_parse($conn, "create table scott.hallo (test
varchar2(64))");
  oci_execute($stmt);
  echo $conn . " created table\n\n";
}

function drop_table($conn)
{
  $stmt = oci_parse($conn, "drop table scott.hallo");
  oci_execute($stmt);
  echo $conn . " dropped table\n\n";
}

function insert_data($conn)
{
  $stmt = oci_parse($conn, "insert into scott.hallo
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " inserted hallo\n\n";
}

function delete_data($conn)
{
  $stmt = oci_parse($conn, "delete from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . " deleted hallo\n\n";
}

function commit($conn)
{
  oci_commit($conn);
  echo $conn . " committed\n\n";
}

function rollback($conn)
{
  oci_rollback($conn);
  echo $conn . " rollback\n\n";
}

function select_data($conn)
{
  $stmt = oci_parse($conn, "select * from scott.hallo");
  oci_execute($stmt, OCI_DEFAULT);
  echo $conn . "----selecting\n\n";
  while (oci_fetch($stmt)) {
    echo $conn . " <" . oci_result($stmt, "TEST") . ">\n\n";
  }
  echo $conn . "----done\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);
select_data($c2);

rollback($c1);

select_data($c1);
select_data($c2);

insert_data($c2);
commit($c2);

select_data($c1);

delete_data($c1);
select_data($c1);
select_data($c2);
commit($c1);

select_data($c1);
select_data($c2);

drop_table($c1);
echo "</pre></html>";
?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocinlogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_connect() - Connect to an Oracle database
  • oci_pconnect() - Connect to an Oracle database using a persistent connection

oci_new_collection
oci_new_cursor
OCI8 Funkcje


Allocates and returns a new cursor (statement handle)

oci_new_connect
oci_new_descriptor
OCI8 Funkcje
PHP Manual

oci_new_cursor

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_cursor — Allocates and returns a new cursor (statement handle)

Opis

resource oci_new_cursor ( resource $connection )

Allocates a new statement handle on the specified connection.

Parametry

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

Zwracane wartości

Returns a new statement handle, or FALSE on error.

Przykłady

Przykład #1 Using REF CURSOR in an Oracle's stored procedure

<?php
// suppose your stored procedure info.output returns a ref cursor in :data

$conn = oci_connect("scott", "tiger");
$curs = oci_new_cursor($conn);
$stmt = oci_parse($conn, "begin info.output(:data); end;");

oci_bind_by_name($stmt, "data", $curs, -1, OCI_B_CURSOR);
oci_execute($stmt);
oci_execute($curs);

while ($data = oci_fetch_row($curs)) {
    var_dump($data);
}

oci_free_statement($stmt);
oci_free_statement($curs);
oci_close($conn);
?>

Przykład #2 Using REF CURSOR in an Oracle's select statement

<?php
echo "<html><body>";
$conn = oci_connect("scott", "tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
                "where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = oci_parse($conn, "select deptno,dname,$count_cursor");

oci_execute($stmt);
echo "<table border=\"1\">";
echo "<tr>";
echo "<th>DEPT NAME</th>";
echo "<th>DEPT #</th>";
echo "<th># EMPLOYEES</th>";
echo "</tr>";

while ($data = oci_fetch_assoc($stmt)) {
    echo "<tr>";
    $dname  = $data["DNAME"];
    $deptno = $data["DEPTNO"];
    echo "<td>$dname</td>";
    echo "<td>$deptno</td>";
    oci_execute($data["EMPCNT"]);
    while ($subdata = oci_fetch_assoc($data["EMPCNT"])) {
        $num_emps = $subdata["NUM_EMPS"];
        echo  "<td>$num_emps</td>";
    }
    echo "</tr>";
}
echo "</table>";
echo "</body></html>";
oci_free_statement($stmt);
oci_close($conn);
?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.

oci_new_connect
oci_new_descriptor
OCI8 Funkcje


Initializes a new empty LOB or FILE descriptor

oci_new_cursor
oci_num_fields
OCI8 Funkcje
PHP Manual

oci_new_descriptor

(PHP 5, PECL OCI8 >= 1.1.0)

oci_new_descriptor — Initializes a new empty LOB or FILE descriptor

Opis

OCI-Lob oci_new_descriptor ( resource $connection [, int $type = OCI_DTYPE_LOB ] )

Allocates resources to hold descriptor or LOB locator.

Parametry

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

type

Valid values for type are: OCI_DTYPE_FILE, OCI_DTYPE_LOB and OCI_DTYPE_ROWID.

Zwracane wartości

Returns a new LOB or FILE descriptor on success, FALSE on error.

Przykłady

Przykład #1 oci_new_descriptor() example

<?php
/* This script is designed to be called from a HTML form.
 * It expects $user, $password, $table, $where, and $commitsize
 * to be passed in from the form.  The script then deletes
 * the selected rows using the ROWID and commits after each
 * set of $commitsize rows. (Use with care, there is no rollback)
 */
$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "select rowid from $table $where");
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_define_by_name($stmt, "ROWID", $rowid);
oci_execute($stmt);
while (oci_fetch($stmt)) {
    $nrows = oci_num_rows($stmt);
    $delete = oci_parse($conn, "delete from $table where ROWID = :rid");
    oci_bind_by_name($delete, ":rid", $rowid, -1, OCI_B_ROWID);
    oci_execute($delete);
    echo "$nrows\n";
    if (($nrows % $commitsize) == 0) {
        oci_commit($conn);
    }
}
$nrows = oci_num_rows($stmt);
echo "$nrows deleted...\n";
oci_free_statement($stmt);
oci_close($conn);
?>
<?php
    /* This script demonstrates file upload to LOB columns
     * The formfield used for this example looks like this
     * <form action="upload.php" method="post" enctype="multipart/form-data">
     * <input type="file" name="lob_upload" />
     * ...
     */
  if (!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload" /><br />
<input type="submit" value="Upload" /> - <input type="reset" value="Reset" />
</form>
<?php
  } else {

     // $lob_upload contains the temporary filename of the uploaded file

     // see also the features section on file upload,
     // if you would like to use secure uploads

     $conn = oci_connect($user, $password);
     $lob = oci_new_descriptor($conn, OCI_D_LOB);
     $stmt = oci_parse($conn, "insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
     oci_bind_by_name($stmt, ':the_blob', $lob, -1, OCI_B_BLOB);
     oci_execute($stmt, OCI_DEFAULT);
     if ($lob->savefile($lob_upload)){
        oci_commit($conn);
        echo "Blob successfully uploaded\n";
     }else{
        echo "Couldn't upload Blob\n";
     }
     oci_free_descriptor($lob);
     oci_free_statement($stmt);
     oci_close($conn);
  }
?>

Przykład #2 oci_new_descriptor() example

<?php
/* Calling PL/SQL stored procedures which contain clobs as input
 * parameters (PHP 4 >= 4.0.6).
 * Example PL/SQL stored procedure signature is:
 *
 * PROCEDURE save_data
 *   Argument Name                  Type                    In/Out Default?
 *   ------------------------------ ----------------------- ------ --------
 *   KEY                            NUMBER(38)              IN
 *   DATA                           CLOB                    IN
 *
 */

$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':key', $key);
oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
$clob->write($data);
oci_execute($stmt, OCI_DEFAULT);
oci_commit($conn);
$clob->free();
oci_free_statement($stmt);
?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.

Zobacz też:

  • oci_bind_by_name() - Binds a PHP variable to an Oracle placeholder

oci_new_cursor
oci_num_fields
OCI8 Funkcje


Returns the number of result columns in a statement

oci_new_descriptor
oci_num_rows
OCI8 Funkcje
PHP Manual

oci_num_fields

(PHP 5, PECL OCI8 >= 1.1.0)

oci_num_fields — Returns the number of result columns in a statement

Opis

int oci_num_fields ( resource $statement )

Gets the number of columns in the given statement.

Parametry

statement

A valid OCI statement identifier.

Zwracane wartości

Returns the number of columns as an integer, or FALSE on errors.

Przykłady

Przykład #1 oci_num_fields() example

<?php
$conn = oci_connect("scott", "tiger");
$stmt = oci_parse($conn, "select * from emp");

oci_execute($stmt);

while (oci_fetch($stmt)) {
    echo "\n";
    $ncols = oci_num_fields($stmt);
    for ($i = 1; $i <= $ncols; $i++) {
        $column_name  = oci_field_name($stmt, $i);
        $column_value = oci_result($stmt, $i);
        echo $column_name . ': ' . $column_value . "\n";
    }
    echo "\n";
}

oci_free_statement($stmt);
oci_close($conn);
?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.

oci_new_descriptor
oci_num_rows
OCI8 Funkcje


Returns number of rows affected during statement execution

oci_num_fields
oci_parse
OCI8 Funkcje
PHP Manual

oci_num_rows

(PHP 5, PECL OCI8 >= 1.1.0)

oci_num_rows — Returns number of rows affected during statement execution

Opis

int oci_num_rows ( resource $statement )

Gets the number of rows affected during statement execution.

Parametry

statement

A valid OCI statement identifier.

Zwracane wartości

Returns the number of rows affected as an integer, or FALSE on errors.

Przykłady

Przykład #1 oci_num_rows() example

<?php
$conn = oci_connect("scott", "tiger");

$stmt = oci_parse($conn, "create table emp2 as select * from emp");
oci_execute($stmt);
echo oci_num_rows($stmt) . " rows inserted.<br />";
oci_free_statement($stmt);

$stmt = oci_parse($conn, "delete from emp2");
oci_execute($stmt, OCI_DEFAULT);
echo oci_num_rows($stmt) . " rows deleted.<br />";
oci_commit($conn);
oci_free_statement($stmt);

$stmt = oci_parse($conn, "drop table emp2");
oci_execute($stmt);
oci_free_statement($stmt);

oci_close($conn);
?>

Notatki

Informacja:

This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.

Informacja:

In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.

oci_num_fields
oci_parse
OCI8 Funkcje


Prepares an Oracle statement for execution

oci_num_rows
oci_password_change
OCI8 Funkcje
PHP Manual

oci_parse

(PHP 5, PECL OCI8 >= 1.1.0)

oci_parse — Prepares an Oracle statement for execution

Opis

resource oci_parse ( resource $connection , string $sql_text )

Prepares sql_text using connection and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.

Statement identifiers can be freed with oci_free_statement() or by setting the variable to NULL.

Parametry

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

sql_text

The SQL or PL/SQL statement.

SQL statements should not end with a semi-colon (";"). PL/SQL statements should end with a semi-colon (";").

Zwracane wartości

Returns a statement handle on success, or FALSE on error.

Przykłady

Przykład #1 oci_parse() example for SQL statements

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

// Parse the statement. Note there is no final semi-colon in the SQL statement
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Przykład #2 oci_parse() example for PL/SQL statements

<?php

/*
  Before running the PHP program, create a stored procedure in
  SQL*Plus or SQL Developer:

  CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
  BEGIN
      p2 := p1 * 2;
  END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 = 8;

// When parsing PL/SQL programs, there should be a final semi-colon in the string
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n";   // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Notatki

Informacja:

This function does not validate sql_text. The only way to find out if sql_text is a valid SQL or PL/SQL statement is to execute it.

Informacja:

In PHP versions before 5.0.0 use ociparse() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_execute() - Executes a statement
  • oci_free_statement() - Frees all resources associated with statement or cursor

oci_num_rows
oci_password_change
OCI8 Funkcje


Changes password of Oracle's user

oci_parse
oci_pconnect
OCI8 Funkcje
PHP Manual

oci_password_change

(PHP 5, PECL OCI8 >= 1.1.0)

oci_password_change — Changes password of Oracle's user

Opis

bool oci_password_change ( resource $connection , string $username , string $old_password , string $new_password )
resource oci_password_change ( string $dbname , string $username , string $old_password , string $new_password )

Changes password for user with username.

The oci_password_change() function is most useful for PHP command-line scripts, or when non-persistent connections are used throughout the PHP application.

Parametry

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

username

The Oracle user name.

old_password

The old password.

new_password

The new password to be set.

dbname

The database name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

Changing the password either with this function or directly in Oracle should be done carefully. This is because PHP applications may continue to successfully reuse persistent connections by authenticating with the old password. The best practice is to restart all web servers whenever the user password is changed.

Informacja:

If upgrading the Oracle client libraries or the database from a release prior to 11.2.0.3 to version 11.2.0.3 or higher, oci_password_change() may give the error "ORA-1017: invalid username/password" unless both client and server versions are upgraded at the same time.

Informacja: The second oci_password_change() syntax is available since OCI8 version 1.1.

Informacja:

In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.

oci_parse
oci_pconnect
OCI8 Funkcje


Connect to an Oracle database using a persistent connection

oci_password_change
oci_result
OCI8 Funkcje
PHP Manual

oci_pconnect

(PHP 5, PECL OCI8 >= 1.1.0)

oci_pconnect — Connect to an Oracle database using a persistent connection

Opis

resource oci_pconnect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] )

Creates a persistent connection to an Oracle server and logs on.

Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FastCGI/CGI process). See the Persistent Database Connections section for more information.

Parametry

username

The Oracle user name.

password

The password for username.

connection_string

Contains the Oracle instance to connect to. It can be an » Easy Connect string, or a Connect Name from the tnsnames.ora file, or the name of a local Oracle instance.

If not specified, PHP uses environment variables such as TWO_TASK (on Linux) or LOCAL (on Windows) and ORACLE_SID to determine the Oracle instance to connect to.

To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. With Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.

The tnsnames.ora file can be in the Oracle Net search path, which includes $ORACLE_HOME/network/admin and /etc. Alternatively set TNS_ADMIN so that $TNS_ADMIN/tnsnames.ora is read. Make sure the web daemon has read access to the file.

character_set

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce connection time.

session_mode

This parameter is available since version PHP 5 (PECL OCI8 1.1) and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, this function will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.

PHP 5.3 (PECL OCI8 1.3.4) introduced the OCI_CRED_EXT mode value. This tells Oracle to use External or OS authentication, which must be configured in the database. The OCI_CRED_EXT flag can only be used with username of "/" and a empty password. oci8.privileged_connect may be On or Off.

OCI_CRED_EXT may be combined with the OCI_SYSOPER or OCI_SYSDBA modes.

OCI_CRED_EXT is not supported on Windows for security reasons.

Zwracane wartości

Returns a connection identifier or FALSE on error.

Notatki

Informacja: Starting with PHP 5.1.2 and PECL oci8 1.1, the lifetime and maximum number of persistent Oracle connections can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.

Informacja:

In PHP versions before 5.0.0 you must use ociplogon() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_connect() - Connect to an Oracle database
  • oci_new_connect() - Connect to the Oracle server using a unique connection

oci_password_change
oci_result
OCI8 Funkcje


Returns field's value from the fetched row

oci_pconnect
oci_rollback
OCI8 Funkcje
PHP Manual

oci_result

(PHP 5, PECL OCI8 >= 1.1.0)

oci_result — Returns field's value from the fetched row

Opis

mixed oci_result ( resource $statement , mixed $field )

Returns the data from field in the current row, fetched by oci_fetch().

For details on the data type mapping performed by the OCI8 extension, see the datatypes supported by the driver

Parametry

statement

field

Can be either use the column number (1-based) or the column name (in uppercase).

Zwracane wartości

Returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). Returns FALSE on error.

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.

Zobacz też:

  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_fetch_all() - Fetches multiple rows from a query into a two-dimensional array

oci_pconnect
oci_rollback
OCI8 Funkcje


Rolls back the outstanding database transaction

oci_result
oci_server_version
OCI8 Funkcje
PHP Manual

oci_rollback

(PHP 5, PECL OCI8 >= 1.1.0)

oci_rollback — Rolls back the outstanding database transaction

Opis

bool oci_rollback ( resource $connection )

Reverts all uncommitted changes for the Oracle connection and ends the transaction. It releases all locks held. All Oracle SAVEPOINTS are erased.

A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag. Further data changes made by other statements become part of the same transaction. Data changes made in a transaction are temporary until the transaction is committed or rolled back. Other users of the database will not see the changes until they are committed.

When inserting or updating data, using transactions is recommended for relational data consistency and for performance reasons.

Parametry

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect() or oci_new_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 oci_rollback() example

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
    $e = oci_error($stid);
    oci_rollback($conn);  // rollback changes to both tables
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
    $e = oci_error($conn);
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

Przykład #2 Rolling back to a SAVEPOINT example

<?php
$stid = oci_parse($conn, 'UPDATE mytab SET id = 1111');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

// Create the savepoint
$stid = oci_parse($conn, 'SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

$stid = oci_parse($conn, 'UPDATE mytab SET id = 2222');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

// Use an explicit SQL statement to rollback to the savepoint
$stid = oci_parse($conn, 'ROLLBACK TO SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

oci_commit($conn);  // mytab now has id of 1111
?>

Notatki

Informacja:

Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Informacja:

In PHP versions before 5.0.0 you must use ocirollback() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci_commit() - Commits the outstanding database transaction
  • oci_execute() - Executes a statement

oci_result
oci_server_version
OCI8 Funkcje


Returns the Oracle Database version

oci_rollback
oci_set_action
OCI8 Funkcje
PHP Manual

oci_server_version

(PHP 5, PECL OCI8 >= 1.1.0)

oci_server_version — Returns the Oracle Database version

Opis

string oci_server_version ( resource $connection )

Returns a string with the Oracle Database version and available options

Parametry

connection

Zwracane wartości

Returns the version information as a string or FALSE on error.

Przykłady

Przykład #1 oci_server_version() example

<?php
    $conn = oci_connect("scott", "tiger");
    echo "Server Version: " . oci_server_version($conn);

    // Displays:
    // Server Version: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    // With the Partitioning, OLAP, Data Mining and Real Application Testing option

    oci_close($conn);

?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ociserverversion() instead. This old name still can be used. However it is deprecated and not recommended.

Zobacz też:

  • oci_client_version() - Returns the Oracle client library version

oci_rollback
oci_set_action
OCI8 Funkcje


Sets the action name

oci_server_version
oci_set_client_identifier
OCI8 Funkcje
PHP Manual

oci_set_action

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_action — Sets the action name

Opis

bool oci_set_action ( resource $connection , string $action_name )

Sets the action name for Oracle tracing.

The action name is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when an SQL statement is executed.

The action name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

Parametry

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

action_name

User chosen string up to 32 bytes long.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Setting the action

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the action
oci_set_action($c, 'Friend Lookup');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the actions
// being performed:

sqlplus system/welcome
SQL> select action from v$session;

Notatki

Informacja: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Wskazówka

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Uwaga

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

Zobacz też:

  • oci_set_module_name() - Sets the module name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier

oci_server_version
oci_set_client_identifier
OCI8 Funkcje


Sets the client identifier

oci_set_action
oci_set_client_info
OCI8 Funkcje
PHP Manual

oci_set_client_identifier

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_client_identifier — Sets the client identifier

Opis

bool oci_set_client_identifier ( resource $connection , string $client_identifier )

Sets the client identifier used by various database components to identify lightweight application users who authenticate as the same database user.

The client identifier is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when an SQL statement is executed.

The identifier can subsequently be queried from database administration views such as V$SESSION. It can be used with DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE for tracing. It can be used for auditing.

The value may be retained across persistent connections.

Parametry

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

client_identifier

User chosen string up to 64 bytes long.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Setting the client identifier to the application user

<?php

// Find the application user's login name
session_start();
$un = my_validate_session($_SESSION['username']);
$c = oci_connect('myschema', 'welcome', 'localhost/XE');

// Tell Oracle who that user is
oci_set_client_identifier($c, $un);

// The next roundtrip to the database will piggyback the identifier
$s = oci_parse($c, 'select mydata from mytable');
oci_execute($s);

// ...

?>

Notatki

Uwaga

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

Zobacz też:

  • oci_set_module_name() - Sets the module name
  • oci_set_action() - Sets the action name
  • oci_set_client_info() - Sets the client information

oci_set_action
oci_set_client_info
OCI8 Funkcje


Sets the client information

oci_set_client_identifier
oci_set_edition
OCI8 Funkcje
PHP Manual

oci_set_client_info

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_client_info — Sets the client information

Opis

bool oci_set_client_info ( resource $connection , string $client_info )

Sets the client information for Oracle tracing.

The client information is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when an SQL statement is executed.

The client information can subsequently be queried from database administration views such as V$SESSION.

The value may be retained across persistent connections.

Parametry

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

User chosen string up to 64 bytes long.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Setting the client information

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the client information
oci_set_client_info($c, 'My Application Version 2');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the client
// information:

sqlplus system/welcome
SQL> select client_info from v$session;

Notatki

Informacja: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Wskazówka

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Uwaga

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

Zobacz też:

  • oci_set_module_name() - Sets the module name
  • oci_set_action() - Sets the action name
  • oci_set_client_identifier() - Sets the client identifier

oci_set_client_identifier
oci_set_edition
OCI8 Funkcje


Sets the database edition

oci_set_client_info
oci_set_module_name
OCI8 Funkcje
PHP Manual

oci_set_edition

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_edition — Sets the database edition

Opis

bool oci_set_edition ( string $edition )

Sets the database "edition" of objects to be used by a subsequent connections.

Oracle Editions allow concurrent versions of applications to run using the same schema and object names. This is useful for upgrading live systems.

Call oci_set_edition() before calling
oci_connect(), oci_pconnect()
or oci_new_connect().

If an edition is set that is not valid in the database, connection will fail even if oci_set_edition() returns success.

When using persistent connections, if a connection with the requested edition setting already exists, it is reused. Otherwise, a different persistent connection is created

Parametry

edition

Oracle Database edition name previously created with the SQL "CREATE EDITION" command.

Notatki

Informacja: Oracle version requirement

This function is available from Oracle 11gR2 onwards.

Uwaga

Persistent connections

To avoid inconsistencies and unexpected errors, do not use ALTER SESSION SET EDITION to change the edition on persistent connections.

Uwaga

DRCP Connection Pooling

To avoid inconsistencies and unexpected errors when using editions and DRCP with Oracle 11.2.0.1, keep a one-to-one correspondence between the oci8.connection_class and the edition name used by applications. Each pooled server of a given connection class should only be used with one edition. This restriction has been removed with Oracle 11.2.0.2.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Two scripts can use different versions of myfunc() at the same time

<?php

// File 1

echo "Version 1 of application\n";

oci_set_edition('ORA$BASE');
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";

?>
<?php

// File 2

echo "Version 2 of application\n";

oci_set_edition('E1');
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";

?>

oci_set_client_info
oci_set_module_name
OCI8 Funkcje


Sets the module name

oci_set_edition
oci_set_prefetch
OCI8 Funkcje
PHP Manual

oci_set_module_name

(PHP 5.3.2, PECL OCI8 >= 1.4.0)

oci_set_module_name — Sets the module name

Opis

bool oci_set_module_name ( resource $connection , string $module_name )

Sets the module name for Oracle tracing.

The module name is registered with the database when the next 'roundtrip' from PHP to the database occurs, typically when an SQL statement is executed.

The name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

Parametry

connection

An Oracle connection identifier, returned by oci_connect(), oci_pconnect(), or oci_new_connect().

module_name

User chosen string up to 48 bytes long.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Oracle version requirement

This function is available when PHP is linked with Oracle Database libraries from version 10g onwards.

Wskazówka

Performance

With older versions of OCI8 or the Oracle Database, the client information can be set using the Oracle DBMS_APPLICATION_INFO package. This is less efficient than using oci_set_client_info().

Uwaga

Roundtrip Gotcha

Some but not all OCI8 functions cause roundtrips. Roundtrips to the database may not occur with queries when result caching is enabled.

Przykłady

Przykład #1 Setting the module name

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the module
oci_set_module_name($c, 'Home Page');

// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);
?>
// While the script is running, the administrator can see the
// modules in use:

sqlplus system/welcome
SQL> select module from v$session;

Zobacz też:

  • oci_set_action() - Sets the action name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier

oci_set_edition
oci_set_prefetch
OCI8 Funkcje


Sets number of rows to be prefetched by queries

oci_set_module_name
oci_statement_type
OCI8 Funkcje
PHP Manual

oci_set_prefetch

(PHP 5, PECL OCI8 >= 1.1.0)

oci_set_prefetch — Sets number of rows to be prefetched by queries

Opis

bool oci_set_prefetch ( resource $statement , int $rows )

Sets the number of rows to be buffered by the Oracle Client libraries after a successful query call to oci_execute() and for each subsequent internal fetch request to the database. For queries returning a large number of rows, performance can be significantly improved by increasing the prefetch count above the default oci8.default_prefetch value.

Prefetching is Oracle's efficient way of returning more than one data row from the database in each network request. This can result in better network and CPU utilization. The buffering of rows is internal to OCI8 and the behavior of OCI8 fetching functions is unchanged regardless of the prefetch count. For example, oci_fetch_row() will always return one row. The prefetch buffer is per-statement and is not used by re-executed statements or by other connections.

Call oci_set_prefetch() before calling oci_execute().

A tuning goal is to set the prefetch value to a reasonable size for the network and database to handle. For queries returning a very large number of rows, overall system efficiency might be better if rows are retrieved from the database in several chunks (i.e set the prefetch value smaller than the number of rows). This allows the database to handle other users' statements while the PHP script is processing the current set of rows.

Query prefetching was introduced in Oracle 8i. REF CURSOR prefetching was introduced in Oracle 11gR2 and occurs when PHP is linked with Oracle 11gR2 Client libraries and connected to 11gR2 or previous versions of the database. Nested cursor prefetching was introduced in Oracle 11gR2 and requires both the Oracle Client libraries and the database to be version 11gR2.

Prefetching is not supported when queries contain LONG or LOB columns. The prefetch value is ignored and single-row fetches will be used in all the situations when prefetching is not supported.

Parametry

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(), or a REF CURSOR statement identifier.

rows

The number of rows to be prefetched, >= 0

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
PHP 5.3.2 (PECL OCI8 1.4) | Before this release, rows must be >= 1.
PHP 5.3 (PECL OCI8 1.3.4) | Before this release, prefetching was limited to the lesser of rows rows and 1024 * rows bytes. The byte size restriction has now been removed.

Przykłady

Przykład #1 Changing the default prefetch value for a query

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM myverybigtable');
oci_set_prefetch($stid, 300);  // Set before calling oci_execute()
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Przykład #2 Changing the default prefetch for a REF CURSOR fetch

<?php
/*
  Create the PL/SQL stored procedure as:

  CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
  BEGIN
    OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
  END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Change the prefetch before executing the cursor.
// REF CURSOR prefetching works when PHP is linked with Oracle 11gR2 Client libraries
oci_set_prefetch($refcur, 200);
oci_execute($refcur);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
    echo "<tr>\n";
    foreach ($row as $item) {
        echo "    <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

If PHP OCI8 fetches from a REF CURSOR and then passes the REF CURSOR back to a second PL/SQL procedure for further processing, then set the REF CURSOR prefetch count to 0 to avoid rows being "lost" from the result set. The prefetch value is the number of extra rows fetched in each OCI8 internal request to the database, so setting it to 0 means only fetch one row at a time.

Przykład #3 Setting the prefetch value when passing a REF CURSOR back to Oracle

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/orcl');

// get the REF CURSOR
$stid = oci_parse($conn, 'BEGIN myproc(:rc_out); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc_out', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Display two rows, but don't prefetch any extra rows otherwise
// those extra rows would not be passed back to myproc_use_rc().
// A prefetch value of 0 is allowed in PHP 5.3.2 and PECL OCI8 1.4
oci_set_prefetch($refcur, 0);
oci_execute($refcur);
$row = oci_fetch_array($refcur);
var_dump($row);
$row = oci_fetch_array($refcur);
var_dump($row);

// pass the REF CURSOR to myproc_use_rc() to do more data processing
// with the result set
$stid = oci_parse($conn, 'begin myproc_use_rc(:rc_in); end;');
oci_bind_by_name($stid, ':rc_in', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

?>

Notatki

Informacja:

In PHP versions before 5.0.0 use ocisetprefetch() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

Zobacz też:

  • oci8.default_prefetch ini option

oci_set_module_name
oci_statement_type
OCI8 Funkcje


Returns the type of a statement

oci_set_prefetch
OCI8 Obsolete Aliases and Functions
OCI8 Funkcje
PHP Manual

oci_statement_type

(PHP 5, PECL OCI8 >= 1.1.0)

oci_statement_type — Returns the type of a statement

Opis

string oci_statement_type ( resource $statement )

Returns a keyword identifying the type of the OCI8 statement.

Parametry

statement

A valid OCI8 statement identifier from oci_parse().

Zwracane wartości

Returns the type of statement as one of the following strings.

Statement type
Return String | Notes
ALTER |
BEGIN |
CALL | Introduced in PHP 5.2.1 (PECL OCI8 1.2.3)
CREATE |
DECLARE |
DELETE |
DROP |
INSERT |
SELECT |
UPDATE |
UNKNOWN |

Returns FALSE on error.

Przykłady

Przykład #1 oci_statement_type() example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'DELETE FROM departments WHERE department_id = 130;');
if (oci_statement_type($stid) == "DELETE") {
    trigger_error('You are not allowed to delete from this table', E_USER_ERROR);
}
else {
    oci_execute($stid);  // delete the row
}

oci_free_statement($stid);
oci_close($conn);

?>

Notatki

Informacja:

In PHP versions before 5.0.0 you must use ocistatementtype() instead. The old function name can still be used in current versions, however it is deprecated and not recommended.

oci_set_prefetch
OCI8 Obsolete Aliases and Functions
OCI8 Funkcje


OCI8 Obsolete Aliases and Functions

Spis treści

  • ocibindbyname — Alias dla oci_bind_by_name
  • ocicancel — Alias dla oci_cancel
  • ocicloselob — Alias dla OCI-Lob::close
  • ocicollappend — Alias dla OCI-Collection::append
  • ocicollassign — Alias dla OCI-Collection::assign
  • ocicollassignelem — Alias dla OCI-Collection::assignElem
  • ocicollgetelem — Alias dla OCI-Collection::getElem
  • ocicollmax — Alias dla OCI-Collection::max
  • ocicollsize — Alias dla OCI-Collection::size
  • ocicolltrim — Alias dla OCI-Collection::trim
  • ocicolumnisnull — Alias dla oci_field_is_null
  • ocicolumnname — Alias dla oci_field_name
  • ocicolumnprecision — Alias dla oci_field_precision
  • ocicolumnscale — Alias dla oci_field_scale
  • ocicolumnsize — Alias dla oci_field_size
  • ocicolumntype — Alias dla oci_field_type
  • ocicolumntyperaw — Alias dla oci_field_type_raw
  • ocicommit — Alias dla oci_commit
  • ocidefinebyname — Alias dla oci_define_by_name
  • ocierror — Alias dla oci_error
  • ociexecute — Alias dla oci_execute
  • ocifetch — Alias dla oci_fetch
  • ocifetchinto — Fetches the next row into an array (deprecated)
  • ocifetchstatement — Alias dla oci_fetch_all
  • ocifreecollection — Alias dla OCI-Collection::free
  • ocifreecursor — Alias dla oci_free_statement
  • ocifreedesc — Alias dla OCI-Lob::free
  • ocifreestatement — Alias dla oci_free_statement
  • ociinternaldebug — Alias dla oci_internal_debug
  • ociloadlob — Alias dla OCI-Lob::load
  • ocilogoff — Alias dla oci_close
  • ocilogon — Alias dla oci_connect
  • ocinewcollection — Alias dla oci_new_collection
  • ocinewcursor — Alias dla oci_new_cursor
  • ocinewdescriptor — Alias dla oci_new_descriptor
  • ocinlogon — Alias dla oci_new_connect
  • ocinumcols — Alias dla oci_num_fields
  • ociparse — Alias dla oci_parse
  • ociplogon — Alias dla oci_pconnect
  • ociresult — Alias dla oci_result
  • ocirollback — Alias dla oci_rollback
  • ocirowcount — Alias dla oci_num_rows
  • ocisavelob — Alias dla OCI-Lob::save
  • ocisavelobfile — Alias dla OCI-Lob::import
  • ociserverversion — Alias dla oci_server_version
  • ocisetprefetch — Alias dla oci_set_prefetch
  • ocistatementtype — Alias dla oci_statement_type
  • ociwritelobtofile — Alias dla OCI-Lob::export
  • ociwritetemporarylob — Alias dla OCI-Lob::writeTemporary
oci_statement_type
ocibindbyname
OCI8


Alias dla oci_bind_by_name

OCI8 Obsolete Aliases and Functions
ocicancel
OCI8 Obsolete Aliases and Functions
PHP Manual

ocibindbyname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocibindbyname — Alias dla oci_bind_by_name()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

OCI8 Obsolete Aliases and Functions
ocicancel
OCI8 Obsolete Aliases and Functions


Alias dla oci_cancel

ocibindbyname
ocicloselob
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicancel

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicancel — Alias dla oci_cancel()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocibindbyname
ocicloselob
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Lob::close

ocicancel
ocicollappend
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicloselob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicloselob — Alias dla OCI-Lob::close()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicancel
ocicollappend
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Collection::append

ocicloselob
ocicollassign
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollappend — Alias dla OCI-Collection::append()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicloselob
ocicollassign
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Collection::assign

ocicollappend
ocicollassignelem
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollassign

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicollassign — Alias dla OCI-Collection::assign()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicollappend
ocicollassignelem
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Collection::assignElem

ocicollassign
ocicollgetelem
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollassignelem — Alias dla OCI-Collection::assignElem()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicollassign
ocicollgetelem
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Collection::getElem

ocicollassignelem
ocicollmax
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollgetelem — Alias dla OCI-Collection::getElem()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicollassignelem
ocicollmax
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Collection::max

ocicollgetelem
ocicollsize
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollmax — Alias dla OCI-Collection::max()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicollgetelem
ocicollsize
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Collection::size

ocicollmax
ocicolltrim
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicollsize — Alias dla OCI-Collection::size()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicollmax
ocicolltrim
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Collection::trim

ocicollsize
ocicolumnisnull
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocicolltrim — Alias dla OCI-Collection::trim()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicollsize
ocicolumnisnull
OCI8 Obsolete Aliases and Functions


Alias dla oci_field_is_null

ocicolltrim
ocicolumnname
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnisnull

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnisnull — Alias dla oci_field_is_null()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicolltrim
ocicolumnname
OCI8 Obsolete Aliases and Functions


Alias dla oci_field_name

ocicolumnisnull
ocicolumnprecision
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnname — Alias dla oci_field_name()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicolumnisnull
ocicolumnprecision
OCI8 Obsolete Aliases and Functions


Alias dla oci_field_precision

ocicolumnname
ocicolumnscale
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnprecision

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnprecision — Alias dla oci_field_precision()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicolumnname
ocicolumnscale
OCI8 Obsolete Aliases and Functions


Alias dla oci_field_scale

ocicolumnprecision
ocicolumnsize
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnscale

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnscale — Alias dla oci_field_scale()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicolumnprecision
ocicolumnsize
OCI8 Obsolete Aliases and Functions


Alias dla oci_field_size

ocicolumnscale
ocicolumntype
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumnsize

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumnsize — Alias dla oci_field_size()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicolumnscale
ocicolumntype
OCI8 Obsolete Aliases and Functions


Alias dla oci_field_type

ocicolumnsize
ocicolumntyperaw
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumntype

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumntype — Alias dla oci_field_type()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicolumnsize
ocicolumntyperaw
OCI8 Obsolete Aliases and Functions


Alias dla oci_field_type_raw

ocicolumntype
ocicommit
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicolumntyperaw

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicolumntyperaw — Alias dla oci_field_type_raw()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicolumntype
ocicommit
OCI8 Obsolete Aliases and Functions


Alias dla oci_commit

ocicolumntyperaw
ocidefinebyname
OCI8 Obsolete Aliases and Functions
PHP Manual

ocicommit

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocicommit — Alias dla oci_commit()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicolumntyperaw
ocidefinebyname
OCI8 Obsolete Aliases and Functions


Alias dla oci_define_by_name

ocicommit
ocierror
OCI8 Obsolete Aliases and Functions
PHP Manual

ocidefinebyname

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocidefinebyname — Alias dla oci_define_by_name()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocicommit
ocierror
OCI8 Obsolete Aliases and Functions


Alias dla oci_error

ocidefinebyname
ociexecute
OCI8 Obsolete Aliases and Functions
PHP Manual

ocierror

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocierror — Alias dla oci_error()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocidefinebyname
ociexecute
OCI8 Obsolete Aliases and Functions


Alias dla oci_execute

ocierror
ocifetch
OCI8 Obsolete Aliases and Functions
PHP Manual

ociexecute

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociexecute — Alias dla oci_execute()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocierror
ocifetch
OCI8 Obsolete Aliases and Functions


Alias dla oci_fetch

ociexecute
ocifetchinto
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetch

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetch — Alias dla oci_fetch()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ociexecute
ocifetchinto
OCI8 Obsolete Aliases and Functions


Fetches the next row into an array (deprecated)

ocifetch
ocifetchstatement
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetchinto

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetchinto — Fetches the next row into an array (deprecated)

Opis

int ocifetchinto ( resource $statement , array &$result [, int $mode = OCI_ASSOC + OCI_NUM ] )

This function is deprecated. Recommended alternatives:
oci_fetch_array(), oci_fetch_object(),
oci_fetch_assoc() and
oci_fetch_row().

Ostrzeżenie

This function has been DEPRECATED as of PHP 5.4.0. Relying on this function is highly discouraged.

ocifetch
ocifetchstatement
OCI8 Obsolete Aliases and Functions


Alias dla oci_fetch_all

ocifetchinto
ocifreecollection
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifetchstatement

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifetchstatement — Alias dla oci_fetch_all()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocifetchinto
ocifreecollection
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Collection::free

ocifetchstatement
ocifreecursor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PECL OCI8 >= 1.0.0)

ocifreecollection — Alias dla OCI-Collection::free()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocifetchstatement
ocifreecursor
OCI8 Obsolete Aliases and Functions


Alias dla oci_free_statement

ocifreecollection
ocifreedesc
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreecursor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreecursor — Alias dla oci_free_statement()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocifreecollection
ocifreedesc
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Lob::free

ocifreecursor
ocifreestatement
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreedesc

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreedesc — Alias dla OCI-Lob::free()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocifreecursor
ocifreestatement
OCI8 Obsolete Aliases and Functions


Alias dla oci_free_statement

ocifreedesc
ociinternaldebug
OCI8 Obsolete Aliases and Functions
PHP Manual

ocifreestatement

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocifreestatement — Alias dla oci_free_statement()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocifreedesc
ociinternaldebug
OCI8 Obsolete Aliases and Functions


Alias dla oci_internal_debug

ocifreestatement
ociloadlob
OCI8 Obsolete Aliases and Functions
PHP Manual

ociinternaldebug

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociinternaldebug — Alias dla oci_internal_debug()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocifreestatement
ociloadlob
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Lob::load

ociinternaldebug
ocilogoff
OCI8 Obsolete Aliases and Functions
PHP Manual

ociloadlob

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociloadlob — Alias dla OCI-Lob::load()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ociinternaldebug
ocilogoff
OCI8 Obsolete Aliases and Functions


Alias dla oci_close

ociloadlob
ocilogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ocilogoff

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocilogoff — Alias dla oci_close()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ociloadlob
ocilogon
OCI8 Obsolete Aliases and Functions


Alias dla oci_connect

ocilogoff
ocinewcollection
OCI8 Obsolete Aliases and Functions
PHP Manual

ocilogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocilogon — Alias dla oci_connect()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocilogoff
ocinewcollection
OCI8 Obsolete Aliases and Functions


Alias dla oci_new_collection

ocilogon
ocinewcursor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PECL OCI8 >= 1.0.0)

ocinewcollection — Alias dla oci_new_collection()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocilogon
ocinewcursor
OCI8 Obsolete Aliases and Functions


Alias dla oci_new_cursor

ocinewcollection
ocinewdescriptor
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewcursor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinewcursor — Alias dla oci_new_cursor()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocinewcollection
ocinewdescriptor
OCI8 Obsolete Aliases and Functions


Alias dla oci_new_descriptor

ocinewcursor
ocinlogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinewdescriptor

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinewdescriptor — Alias dla oci_new_descriptor()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocinewcursor
ocinlogon
OCI8 Obsolete Aliases and Functions


Alias dla oci_new_connect

ocinewdescriptor
ocinumcols
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinlogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinlogon — Alias dla oci_new_connect()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocinewdescriptor
ocinumcols
OCI8 Obsolete Aliases and Functions


Alias dla oci_num_fields

ocinlogon
ociparse
OCI8 Obsolete Aliases and Functions
PHP Manual

ocinumcols

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocinumcols — Alias dla oci_num_fields()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocinlogon
ociparse
OCI8 Obsolete Aliases and Functions


Alias dla oci_parse

ocinumcols
ociplogon
OCI8 Obsolete Aliases and Functions
PHP Manual

ociparse

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociparse — Alias dla oci_parse()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocinumcols
ociplogon
OCI8 Obsolete Aliases and Functions


Alias dla oci_pconnect

ociparse
ociresult
OCI8 Obsolete Aliases and Functions
PHP Manual

ociplogon

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociplogon — Alias dla oci_pconnect()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ociparse
ociresult
OCI8 Obsolete Aliases and Functions


Alias dla oci_result

ociplogon
ocirollback
OCI8 Obsolete Aliases and Functions
PHP Manual

ociresult

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociresult — Alias dla oci_result()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ociplogon
ocirollback
OCI8 Obsolete Aliases and Functions


Alias dla oci_rollback

ociresult
ocirowcount
OCI8 Obsolete Aliases and Functions
PHP Manual

ocirollback

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocirollback — Alias dla oci_rollback()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ociresult
ocirowcount
OCI8 Obsolete Aliases and Functions


Alias dla oci_num_rows

ocirollback
ocisavelob
OCI8 Obsolete Aliases and Functions
PHP Manual

ocirowcount

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocirowcount — Alias dla oci_num_rows()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocirollback
ocisavelob
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Lob::save

ocirowcount
ocisavelobfile
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisavelob

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisavelob — Alias dla OCI-Lob::save()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocirowcount
ocisavelobfile
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Lob::import

ocisavelob
ociserverversion
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisavelobfile

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisavelobfile — Alias dla OCI-Lob::import()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocisavelob
ociserverversion
OCI8 Obsolete Aliases and Functions


Alias dla oci_server_version

ocisavelobfile
ocisetprefetch
OCI8 Obsolete Aliases and Functions
PHP Manual

ociserverversion

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociserverversion — Alias dla oci_server_version()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocisavelobfile
ocisetprefetch
OCI8 Obsolete Aliases and Functions


Alias dla oci_set_prefetch

ociserverversion
ocistatementtype
OCI8 Obsolete Aliases and Functions
PHP Manual

ocisetprefetch

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocisetprefetch — Alias dla oci_set_prefetch()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ociserverversion
ocistatementtype
OCI8 Obsolete Aliases and Functions


Alias dla oci_statement_type

ocisetprefetch
ociwritelobtofile
OCI8 Obsolete Aliases and Functions
PHP Manual

ocistatementtype

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ocistatementtype — Alias dla oci_statement_type()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocisetprefetch
ociwritelobtofile
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Lob::export

ocistatementtype
ociwritetemporarylob
OCI8 Obsolete Aliases and Functions
PHP Manual

ociwritelobtofile

(PHP 4, PHP 5, PECL OCI8 >= 1.0.0)

ociwritelobtofile — Alias dla OCI-Lob::export()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ocistatementtype
ociwritetemporarylob
OCI8 Obsolete Aliases and Functions


Alias dla OCI-Lob::writeTemporary

ociwritelobtofile
Ovrimos SQL
OCI8 Obsolete Aliases and Functions
PHP Manual

ociwritetemporarylob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ociwritetemporarylob — Alias dla OCI-Lob::writeTemporary()

Opis

Ostrzeżenie

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.

ociwritelobtofile
Ovrimos SQL
OCI8 Obsolete Aliases and Functions


Ovrimos SQL

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Podstawowe użycie
  • Funkcje Ovrimos SQL
    • ovrimos_close — Zamyka połączenie z serwerem Ovrimos
    • ovrimos_commit — Potwierdza transakcję
    • ovrimos_connect — Otwiera połączenie z określoną bazą danych
    • ovrimos_cursor — Zwraca nazwę kursora
    • ovrimos_exec — Wykonuje instrukcję SQL
    • ovrimos_execute — Wykonuje przygotowaną instrukcję SQL
    • ovrimos_fetch_into — Pobiera wiersz ze zbioru wyniku
    • ovrimos_fetch_row — Pobiera wiersz ze zbioru wyniku
    • ovrimos_field_len — Zwraca długość kolumny
    • ovrimos_field_name — Zwraca nazwę kolumny
    • ovrimos_field_num — Zwraca numer kolumny
    • ovrimos_field_type — Zwraca typ kolumny
    • ovrimos_free_result — Zwalnia pamięć zajmowaną przez określony wynik
    • ovrimos_longreadlen — Określa ile bajtów zostanie odczytanych z dużych typów danych
    • ovrimos_num_fields — Zwraca liczbę kolumn
    • ovrimos_num_rows — Pobiera liczbę wierszy użytych przez operacje aktualizacji
    • ovrimos_prepare — Przygotowuje instrukcję SQL
    • ovrimos_result_all — Wyświetla cały zbiór wyniku w postaci tabeli HTML
    • ovrimos_result — Odczytuje wartość kolumny
    • ovrimos_rollback — Wycofuje transakcję
ociwritetemporarylob
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Ovrimos SQL Server to klient/serwer, system zarządzania relacyjnymi bazami danych łączący możliwości sieci i szybkie transakcje.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 4.4.5 i PHP 5.1.0.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

Ovrimos SQL
Instalacja/Konfiguracja
Ovrimos SQL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Ovrimos SQL


Wymagania

Należy zainstalować bibliotekę sqlcli znajdującą się w dystrybucji Ovrimos SQL Server.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Aby włączyć obsługę Ovrimos w PHP, należy skompilować PHP z parametrem --with-ovrimos[=DIR] , gdzie DIR jest katalogiem instalacji biblioteki libsqlcli.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Ovrimos SQL


Przykłady

Spis treści

  • Podstawowe użycie
Stałe predefiniowane
Podstawowe użycie
Ovrimos SQL


Podstawowe użycie

Przykład #1 Połączenie do Ovrimos SQL Server i pobranie danych z tabeli systemowej

<?php
$conn = ovrimos_connect("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Połączenie zostało nawiązane.";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Instrukcja została wykonana prawidłowo.";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

Przykłady
Funkcje Ovrimos SQL
Przykłady


Funkcje Ovrimos SQL

Spis treści

  • ovrimos_close — Zamyka połączenie z serwerem Ovrimos
  • ovrimos_commit — Potwierdza transakcję
  • ovrimos_connect — Otwiera połączenie z określoną bazą danych
  • ovrimos_cursor — Zwraca nazwę kursora
  • ovrimos_exec — Wykonuje instrukcję SQL
  • ovrimos_execute — Wykonuje przygotowaną instrukcję SQL
  • ovrimos_fetch_into — Pobiera wiersz ze zbioru wyniku
  • ovrimos_fetch_row — Pobiera wiersz ze zbioru wyniku
  • ovrimos_field_len — Zwraca długość kolumny
  • ovrimos_field_name — Zwraca nazwę kolumny
  • ovrimos_field_num — Zwraca numer kolumny
  • ovrimos_field_type — Zwraca typ kolumny
  • ovrimos_free_result — Zwalnia pamięć zajmowaną przez określony wynik
  • ovrimos_longreadlen — Określa ile bajtów zostanie odczytanych z dużych typów danych
  • ovrimos_num_fields — Zwraca liczbę kolumn
  • ovrimos_num_rows — Pobiera liczbę wierszy użytych przez operacje aktualizacji
  • ovrimos_prepare — Przygotowuje instrukcję SQL
  • ovrimos_result_all — Wyświetla cały zbiór wyniku w postaci tabeli HTML
  • ovrimos_result — Odczytuje wartość kolumny
  • ovrimos_rollback — Wycofuje transakcję
Podstawowe użycie
ovrimos_close
Ovrimos SQL


Zamyka połączenie z serwerem Ovrimos

Funkcje Ovrimos SQL
ovrimos_commit
Funkcje Ovrimos SQL
PHP Manual

ovrimos_close

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_close — Zamyka połączenie z serwerem Ovrimos

Opis

void ovrimos_close ( int $identyfikator_połączenia )

Zamyka połączenie z serwerem Ovrimos, określone parametrem connection. W efekcie wszystkie niezatwierdzone transakcje w danej sesji zostaną wycofane.

Parametry

identyfikator_połączenia

Identyfikator połączenia z serwerem Ovrimos, zwrócony przez ovrimos_connect().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ovrimos_connect() - Otwiera połączenie z określoną bazą danych

Funkcje Ovrimos SQL
ovrimos_commit
Funkcje Ovrimos SQL


Potwierdza transakcję

ovrimos_close
ovrimos_connect
Funkcje Ovrimos SQL
PHP Manual

ovrimos_commit

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_commit — Potwierdza transakcję

Opis

bool ovrimos_commit ( int $identyfikator_połączenia )

Potwierdza transakcję.

Parametry

identyfikator_połączenia

Identyfikator połączenia z serwerem Ovrimos, zwrócony przez ovrimos_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_rollback() - Wycofuje transakcję

ovrimos_close
ovrimos_connect
Funkcje Ovrimos SQL


Otwiera połączenie z określoną bazą danych

ovrimos_commit
ovrimos_cursor
Funkcje Ovrimos SQL
PHP Manual

ovrimos_connect

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_connect — Otwiera połączenie z określoną bazą danych

Opis

int ovrimos_connect ( string $host , string $nazwabazy_lub_port , string $użytkownik , string $hasło )

Otwiera połączenie do określonej bazy danych.

Parametry

host

Nazwa hosta lub adres IP.

nazwabazy_lub_port

Nazwa bazy danych lub numer portu.

użytkownik

Nazwa użytkownika.

hasło

Hasło użytkownika.

Zwracane wartości

Zwraca identyfikator połączenia (wartość większa od 0) w przypadku powodzenia, lub 0 w przypadku błędu.

Przykłady

Przykład #1 Przykład ovrimos_connect()

<?php
$conn = ovrimos_connect("server.example.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Połączenie zostało nawiązane.";
    $res = ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Instrukcja została wykonana prawidłowo.";
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

Zobacz też:

  • ovrimos_close() - Zamyka połączenie z serwerem Ovrimos

ovrimos_commit
ovrimos_cursor
Funkcje Ovrimos SQL


Zwraca nazwę kursora

ovrimos_connect
ovrimos_exec
Funkcje Ovrimos SQL
PHP Manual

ovrimos_cursor

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_cursor — Zwraca nazwę kursora

Opis

string ovrimos_cursor ( int $identyfikator_wyniku )

Pobiera nazwę kursora. Przydatne podczas wykonywania określanych zapytań aktualizacji lub usuwania.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

Zwracane wartości

Zwraca nazwę jako string, lub FALSE w przypadku błędu.

ovrimos_connect
ovrimos_exec
Funkcje Ovrimos SQL


Wykonuje instrukcję SQL

ovrimos_cursor
ovrimos_execute
Funkcje Ovrimos SQL
PHP Manual

ovrimos_exec

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_exec — Wykonuje instrukcję SQL

Opis

int ovrimos_exec ( int $identyfikator_połączenia , string $zapytanie )

Wykonuje instrukcję SQL i zwraca identyfikator wyniku.

Parametry

identyfikator_połączenia

Identyfikator połączenia z serwerem Ovrimos, zwrócony przez ovrimos_connect().

zapytanie

Instrukcja SQL. Oczywiście nie może zawierać parametrów. Do przygotowania instrukcji SQL należy używać ovrimos_prepare().

Zwracane wartości

Zwraca indentyfikator wyniku jako integer, lub FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_execute() - Wykonuje przygotowaną instrukcję SQL
  • ovrimos_prepare() - Przygotowuje instrukcję SQL

ovrimos_cursor
ovrimos_execute
Funkcje Ovrimos SQL


Wykonuje przygotowaną instrukcję SQL

ovrimos_exec
ovrimos_fetch_into
Funkcje Ovrimos SQL
PHP Manual

ovrimos_execute

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_execute — Wykonuje przygotowaną instrukcję SQL

Opis

bool ovrimos_execute ( int $identyfikator_wyniku [, array $tablica_parametrów ] )

Wykonuje przygotowaną instrukcję SQL.

Parametry

identyfikator_wyniku

Identyfikator wyniku Ovrimos, przygotowany za pomocą ovrimos_prepare().

tablica_parametrów

Jeśli przygotowana instrukcja zawiera parametry (znaki zapytania), to powinna zostać do funkcji przekazana tablica zawierająca odpowiednią liczbę wartości dla nich.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_prepare() - Przygotowuje instrukcję SQL

ovrimos_exec
ovrimos_fetch_into
Funkcje Ovrimos SQL


Pobiera wiersz ze zbioru wyniku

ovrimos_execute
ovrimos_fetch_row
Funkcje Ovrimos SQL
PHP Manual

ovrimos_fetch_into

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_fetch_into — Pobiera wiersz ze zbioru wyniku

Opis

bool ovrimos_fetch_into ( int $identyfikator_wyniku , array &$tablica_wyniku [, string $sposób [, int $numer_wiersza ]] )

Pobiera wiersz z podanego zbioru wyniku do tablicy_wyniku.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

tablica_wyniku

Należy dostarczyć tablicę przez referencję. Zostanie ona wypełniona pobranymi wartościami.

sposób

Określa w jaki sposób będą pobierane wiersze. Może przyjmować jedną z następujących wartości (wielkość liter nie ma znaczenia):

Opcja | Informacja
Next | Następny z bieżącej pozycji. To jest wartość domyślna.
Prev | Poprzedni z bieżącej pozycji.
First | Pierwszy.
Last | Ostatni.
Absolute | Wskazany numer, liczony od początku zbioru. Wymaga podania numer_wiersza.

numer_wiersza

Numer wiersza liczony od 0. Wymagany tylko, gdy sposób ma wartość Absolute.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład ovrimos_fetch_into

<?php
$conn=ovrimos_connect("neptune", "8001", "admin", "password");
if ($conn!=0) {
    echo "Połączenie zostało nawiązane.";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Instrukcja została wykonana prawidłowo.";
        if (ovrimos_fetch_into($res, $row)) {
            list($table_id, $table_name) = $row;
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_into($res, $row)) {
                list($table_id, $table_name) = $row;
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Następny: błąd\n";
            }
        } else {
            echo "Pierwszy: błąd\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

Zobacz też:

  • ovrimos_fetch_row() - Pobiera wiersz ze zbioru wyniku

ovrimos_execute
ovrimos_fetch_row
Funkcje Ovrimos SQL


Pobiera wiersz ze zbioru wyniku

ovrimos_fetch_into
ovrimos_field_len
Funkcje Ovrimos SQL
PHP Manual

ovrimos_fetch_row

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_fetch_row — Pobiera wiersz ze zbioru wyniku

Opis

bool ovrimos_fetch_row ( int $identyfikator_wyniku [, int $sposób [, int $numer_wiersza ]] )

Pobiera wiersz ze zbioru wyniku. Wartości kolumn powinny być odczytywane przez wywołania innej funkcji.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

sposób

Określa w jaki sposób będą pobierane wiersze. Może przyjmować jedną z następujących wartości (wielkość liter nie ma znaczenia):

Opcja | Informacja
Next | Następny z bieżącej pozycji. To jest wartość domyślna.
Prev | Poprzedni z bieżącej pozycji.
First | Pierwszy.
Last | Ostatni.
Absolute | Wskazany numer, liczony od początku zbioru. Wymaga podania numer_wiersza.

numer_wiersza

Numer wiersza liczony od 0. Wymagany tylko, gdy sposób ma wartość Absolute.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład ovrimos_fetch_row

<?php
$conn = ovrimos_connect("remote.host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Połączenie zostało nawiązane.";
    $res=ovrimos_exec($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Instrukcja została wykonana prawidłowo.";
        if (ovrimos_fetch_row($res, "First")) {
            $table_id = ovrimos_result($res, 1);
            $table_name = ovrimos_result($res, 2);
            echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            if (ovrimos_fetch_row($res, "Next")) {
                $table_id = ovrimos_result($res, "table_id");
                $table_name = ovrimos_result($res, "table_name");
                echo "table_id=" . $table_id . ", table_name=" . $table_name . "\n";
            } else {
                echo "Następny: błąd\n";
            }
        } else {
            echo "Pierwszy: błąd\n";
        }
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>
Pobranie wiersza i wyświetlenie wyniku.

Zobacz też:

  • ovrimos_fetch_into() - Pobiera wiersz ze zbioru wyniku

ovrimos_fetch_into
ovrimos_field_len
Funkcje Ovrimos SQL


Zwraca długość kolumny

ovrimos_fetch_row
ovrimos_field_name
Funkcje Ovrimos SQL
PHP Manual

ovrimos_field_len

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_len — Zwraca długość kolumny

Opis

int ovrimos_field_len ( int $identyfikator_wyniku , int $numer_pola )

Zwraca długość określonej kolumny.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

numer_pola

Numer pola. Numeracja zaczyna się od 1.

Zwracane wartości

Zwraca długość jako integer, lub FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_field_name() - Zwraca nazwę kolumny
  • ovrimos_field_num() - Zwraca numer kolumny
  • ovrimos_field_type() - Zwraca typ kolumny

ovrimos_fetch_row
ovrimos_field_name
Funkcje Ovrimos SQL


Zwraca nazwę kolumny

ovrimos_field_len
ovrimos_field_num
Funkcje Ovrimos SQL
PHP Manual

ovrimos_field_name

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_name — Zwraca nazwę kolumny

Opis

string ovrimos_field_name ( int $identyfikator_wyniku , int $numer_pola )

Zwraca nazwę kolumny dla określonego numeru pola.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

numer_pola

Numer pola. Numeracja zaczyna się od 1.

Zwracane wartości

Zwraca nazwę pola jako string, lub FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_field_len() - Zwraca długość kolumny
  • ovrimos_field_num() - Zwraca numer kolumny
  • ovrimos_field_type() - Zwraca typ kolumny

ovrimos_field_len
ovrimos_field_num
Funkcje Ovrimos SQL


Zwraca numer kolumny

ovrimos_field_name
ovrimos_field_type
Funkcje Ovrimos SQL
PHP Manual

ovrimos_field_num

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_num — Zwraca numer kolumny

Opis

int ovrimos_field_num ( int $identyfikator_wyniku , string $nazwa_pola )

Zwraca numer określonej kolumny. Numeracja zaczyna się od 1.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

nazwa_pola

Nazwa pola.

Zwracane wartości

Zwraca indeks rozpoczynający się od 1, lub FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_field_len() - Zwraca długość kolumny
  • ovrimos_field_name() - Zwraca nazwę kolumny
  • ovrimos_field_type() - Zwraca typ kolumny

ovrimos_field_name
ovrimos_field_type
Funkcje Ovrimos SQL


Zwraca typ kolumny

ovrimos_field_num
ovrimos_free_result
Funkcje Ovrimos SQL
PHP Manual

ovrimos_field_type

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_field_type — Zwraca typ kolumny

Opis

int ovrimos_field_type ( int $identyfikator_wyniku , int $numer_pola )

Zwraca typ kolumny.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

numer_pola

Indeks zaczynający się od 1.

Zwracane wartości

Zwraca typ pola jako integer, lub FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_field_len() - Zwraca długość kolumny
  • ovrimos_field_name() - Zwraca nazwę kolumny
  • ovrimos_field_num() - Zwraca numer kolumny

ovrimos_field_num
ovrimos_free_result
Funkcje Ovrimos SQL


Zwalnia pamięć zajmowaną przez określony wynik

ovrimos_field_type
ovrimos_longreadlen
Funkcje Ovrimos SQL
PHP Manual

ovrimos_free_result

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_free_result — Zwalnia pamięć zajmowaną przez określony wynik

Opis

bool ovrimos_free_result ( int $identyfikator_wyniku )

Zwalnia pamięć zajmowaną przez określony wynik.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

Zwracane wartości

Zwraca TRUE.

ovrimos_field_type
ovrimos_longreadlen
Funkcje Ovrimos SQL


Określa ile bajtów zostanie odczytanych z dużych typów danych

ovrimos_free_result
ovrimos_num_fields
Funkcje Ovrimos SQL
PHP Manual

ovrimos_longreadlen

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_longreadlen — Określa ile bajtów zostanie odczytanych z dużych typów danych

Opis

bool ovrimos_longreadlen ( int $identyfikator_wyniku , int $długość )

Określa ile bajtów zostanie odczytanych z dużych typów danych (long varchar i long varbinary).

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

długość

Liczba bajtów do odczytu. Domyślnie zero.

Zwracane wartości

Zwraca TRUE.

ovrimos_free_result
ovrimos_num_fields
Funkcje Ovrimos SQL


Zwraca liczbę kolumn

ovrimos_longreadlen
ovrimos_num_rows
Funkcje Ovrimos SQL
PHP Manual

ovrimos_num_fields

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_num_fields — Zwraca liczbę kolumn

Opis

int ovrimos_num_fields ( int $identyfikator_wyniku )

Zwraca liczbę kolumn w określonym zbiorze wyniku.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

Zwracane wartości

Zwraca liczbę kolumn jako integer, lub FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_num_rows() - Pobiera liczbę wierszy użytych przez operacje aktualizacji

ovrimos_longreadlen
ovrimos_num_rows
Funkcje Ovrimos SQL


Pobiera liczbę wierszy użytych przez operacje aktualizacji

ovrimos_num_fields
ovrimos_prepare
Funkcje Ovrimos SQL
PHP Manual

ovrimos_num_rows

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_num_rows — Pobiera liczbę wierszy użytych przez operacje aktualizacji

Opis

int ovrimos_num_rows ( int $identyfikator_wyniku )

Pobiera liczbę zaktualizowanych wierszy.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

Zwracane wartości

Zwraca liczbę wierszy jako integer, lub FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_num_fields() - Zwraca liczbę kolumn

ovrimos_num_fields
ovrimos_prepare
Funkcje Ovrimos SQL


Przygotowuje instrukcję SQL

ovrimos_num_rows
ovrimos_result_all
Funkcje Ovrimos SQL
PHP Manual

ovrimos_prepare

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_prepare — Przygotowuje instrukcję SQL

Opis

int ovrimos_prepare ( int $identyfikator_połączenia , string $zapytanie )

Przygotowuje instrukcję SQL.

Parametry

identyfikator_połączenia

Identyfikator połączenia z serwerem Ovrimos, zwrócony przez ovrimos_connect().

zapytanie

Instrukcja SQL.

Zwracane wartości

Zwraca identyfikator wyniku, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład ovrimos_prepare()

<?php
$conn=ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn!=0) {
    echo "Połączenie zostało nawiązane.";

    // Przygotowanie instrukcji
    $res=ovrimos_prepare($conn, "select table_id, table_name
                                  from sys.tables where table_id=1");
    if ($res != 0) {
        echo "Przygotowanie instrukcji powiodło się";
        // Wykonanie przygotowanej instrukcji
        if (ovrimos_execute($res)) {
            echo "Wykonanie instrukcji powiodło się\n";
            ovrimos_result_all($res);
        } else {
            echo "Wykonanie instrukcji nie powiodło się";
        }
        ovrimos_free_result($res);
    } else {
        echo "Przygotowanie instrukcji nie powiodło się\n";
    }
    ovrimos_close($conn);
}
?>

ovrimos_num_rows
ovrimos_result_all
Funkcje Ovrimos SQL


Wyświetla cały zbiór wyniku w postaci tabeli HTML

ovrimos_prepare
ovrimos_result
Funkcje Ovrimos SQL
PHP Manual

ovrimos_result_all

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_result_all — Wyświetla cały zbiór wyniku w postaci tabeli HTML

Opis

int ovrimos_result_all ( int $identyfikator_wyniku [, string $format ] )

Wyświetla cały zbiór wyniku w postaci tabeli HTML.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

format

Opcjonalne atrybuty HTML używane podczas generowania tabeli.

Zwracane wartości

Zwraca liczbę wierszy w wygenerowanej tabeli.

Przykłady

Wykonanie instrukcji SQL i wyświetlenie wyniku w postaci tabeli HTML.

Przykład #1 Przygotowanie instrukcji, wykonanie, i wyświetlenie wyniku

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Połączenie zostało nawiązane.";
    $res = ovrimos_prepare($conn, "select table_id, table_name
                                    from sys.tables where table_id = 7");
    if ($res != 0) {
        echo "Instrukcja została przygotowana prawidłowo";
        if (ovrimos_execute($res, array(3))) {
            echo "Wykonanie instrukcji powiodło się\n";
            ovrimos_result_all($res);
        } else {
            echo "Wykonanie instrukcji nie powiodło się";
        }
        ovrimos_free_result($res);
    } else {
        echo "Przygotowanie instrukcji nie powiodło się\n";
    }
    ovrimos_close($conn);
}
?>

Przykład #2 Przykład ovrimos_result_all() z metadanymi

<?php
$conn = ovrimos_connect("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Połączenie zostało nawiązane.";
    $res = ovrimos_exec($conn, "select table_id, table_name
                                 from sys.tables where table_id = 1");
    if ($res != 0) {
        echo "Instrukcja została wykonana prawidłowo; cursor=" . ovrimos_cursor($res) . "\n";
        $colnb = ovrimos_num_fields($res);
        echo "Liczba kolumn=" . $colnb . "\n";
        for ($i=1; $i <= $colnb; $i++) {
            $name = ovrimos_field_name($res, $i);
            $type = ovrimos_field_type($res, $i);
            $len = ovrimos_field_len($res, $i);
            echo "Kolumna " . $i . " nazwa=" . $name . " typ=" . $type . " długość=" . $len . "\n";
        }
        ovrimos_result_all($res);
        ovrimos_free_result($res);
    }
    ovrimos_close($conn);
}
?>

ovrimos_prepare
ovrimos_result
Funkcje Ovrimos SQL


Odczytuje wartość kolumny

ovrimos_result_all
ovrimos_rollback
Funkcje Ovrimos SQL
PHP Manual

ovrimos_result

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_result — Odczytuje wartość kolumny

Opis

string ovrimos_result ( int $identyfikator_wyniku , mixed $pole )

Odczytuje wartość kolumny określoną przez pole.

Parametry

identyfikator_wyniku

Indetyfikator wyniku zwrócony przez ovrimos_execute() lub ovrimos_exec().

pole

Nazwa kolumny jako string lub indeks zaczynający się od 1.

Zwracane wartości

Zwraca kolumnę jako string, lub FALSE w przypadku błędu.

ovrimos_result_all
ovrimos_rollback
Funkcje Ovrimos SQL


Wycofuje transakcję

ovrimos_result
Paradox
Funkcje Ovrimos SQL
PHP Manual

ovrimos_rollback

(PHP 4 >= 4.0.3, PHP 5 <= 5.0.5)

ovrimos_rollback — Wycofuje transakcję

Opis

bool ovrimos_rollback ( int $identyfikator_połączenia )

Wycofuje transakcję.

Parametry

identyfikator_połączenia

Identyfikator połączenia z serwerem Ovrimos, zwrócony przez ovrimos_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ovrimos_commit() - Potwierdza transakcję

ovrimos_result
Paradox
Funkcje Ovrimos SQL


Paradox File Access

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Paradox Funkcje
    • px_close — Closes a paradox database
    • px_create_fp — Create a new paradox database
    • px_date2string — Converts a date into a string.
    • px_delete_record — Deletes record from paradox database
    • px_delete — Deletes resource of paradox database
    • px_get_field — Returns the specification of a single field
    • px_get_info — Return lots of information about a paradox file
    • px_get_parameter — Gets a parameter
    • px_get_record — Returns record of paradox database
    • px_get_schema — Returns the database schema
    • px_get_value — Gets a value
    • px_insert_record — Inserts record into paradox database
    • px_new — Create a new paradox object
    • px_numfields — Returns number of fields in a database
    • px_numrecords — Returns number of records in a database
    • px_open_fp — Open paradox database
    • px_put_record — Stores record into paradox database
    • px_retrieve_record — Returns record of paradox database
    • px_set_blob_file — Sets the file where blobs are read from
    • px_set_parameter — Sets a parameter
    • px_set_tablename — Sets the name of a table (deprecated)
    • px_set_targetencoding — Sets the encoding for character fields (deprecated)
    • px_set_value — Sets a value
    • px_timestamp2string — Converts the timestamp into a string.
    • px_update_record — Updates record in paradox database
ovrimos_rollback
Wstęp
Rozszerzenia producentów baz danych


Wstęp

This module allows to read and write Paradox databases, primary index files and blob files. Write support has been proven to be quite reliable, though due to lack of documentation the produced files may not in any case be readable by other applications. Encrypted databases can be read without specifying a password if pxlib >= 0.5.0 is used.

Informacja:

This module is also in development and may change, though major changes to the API are not expected.

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.

Paradox
Instalacja/Konfiguracja
Paradox


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Paradox


Wymagania

You need at least PHP 5.0.0 and pxlib >= 0.4.4 for the basic set of functions. Some newer functions are only available with pxlib >= 0.6.0. Reading and writing of encrypted databases requires at least pxlib >= 0.5.0. The paradox library (pxlib) is available at » http://pxlib.sourceforge.net.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/paradox

Make sure you have pxlib installed before. If you install pxlib from an rpm or debian package, do not forget to install the development package as well.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

px_new() creates a new Paradox object required by all Paradox functions.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

The following two tables lists all constants defined by the paradox extension.

Contants for field types
Name | Meaning
PX_FIELD_ALPHA | Character data with fixed length
PX_FIELD_DATE | Date, number of days since 1.1.0000
PX_FIELD_SHORT | Short integer (2 Bytes)
PX_FIELD_LONG | Long integer (4 Bytes)
PX_FIELD_CURRENCY | same as PX_FIELD_NUMBER
PX_FIELD_NUMBER | Double
PX_FIELD_LOGICAL | Boolean
PX_FIELD_MEMOBLOB | Binary large object
PX_FIELD_BLOB | Binary large object (not supported)
PX_FIELD_FMTMEMOBLOB | Binary large object
PX_FIELD_OLE | OLE object (basically a blob, not supported)
PX_FIELD_GRAPHIC | Graphic (basically a blob, not supported)
PX_FIELD_TIME | time, number of milli seconds since midnight
PX_FIELD_TIMESTAMP | timestamp, number of milli seconds since 1.1.0000
PX_FIELD_AUTOINC | Auto incrementing interger (like PX_FIELD_LONG)
PX_FIELD_BCD | Decimal number stored in bcd format (not supported)
PX_FIELD_BYTES | Array of Bytes with not more than 255 bytes (not supported)
PX_KEYTOLOWER | Turn all field names into lower case
PX_KEYTOUPPER | Turn all field names into upper case
Contants for file types
Name | Meaning
PX_FILE_INDEX_DB | Indexed database
PX_FILE_PRIM_INDEX | Primary index
PX_FILE_NON_INDEX_DB | None indexed database
PX_FILE_NON_INC_SEC_INDEX | None incremental secondary index
PX_FILE_SEC_INDEX | Secondary index
PX_FILE_INC_SEC_INDEX | Incremental secondary index
PX_FILE_NON_INC_SEC_INDEX_G | Non incremental secondary index
PX_FILE_SEC_INDEX_G | Secondary index
PX_FILE_INC_SEC_INDEX_G | Non incremental secondary index

Typy zasobów
Paradox Funkcje
Paradox


Paradox Funkcje

Object oriented API

The paradox extension provides also an object oriented API. It consists of only one class called paradox_db. Its methods only differ from the functions in its name and of course the missing first parameter. The following table will list all methods and its equivalent functions.

Methods of class paradox_db
Name of method | Equivalent function
Constructor | px_new()
Destructor | px_delete()
open_fp() | px_open_fp()
create_fp() | px_create_fp()
close() | px_close()
numrecords() | px_numrecords()
numfields() | px_numfields()
get_record() | px_get_record()
put_record() | px_put_record()
retrieve_record() | px_retrieve_record()
delete_record() | px_delete_record()
insert_record() | px_insert_record()
update_record() | px_update_record()
get_field() | px_get_field()
get_schema() | px_get_schema()
get_info() | px_get_info()
set_parameter() | px_set_parameter()
get_parameter() | px_get_parameter()
set_value() | px_set_value()
get_value() | px_get_value()
get_info() | px_get_info()
set_targetencoding() | px_set_targetencoding()
set_tablename() | px_set_tablename()
set_blob_file() | px_set_blob_file()
date2string() | px_date2string()
timestamp2string() | px_timestamp2string()

Spis treści

  • px_close — Closes a paradox database
  • px_create_fp — Create a new paradox database
  • px_date2string — Converts a date into a string.
  • px_delete_record — Deletes record from paradox database
  • px_delete — Deletes resource of paradox database
  • px_get_field — Returns the specification of a single field
  • px_get_info — Return lots of information about a paradox file
  • px_get_parameter — Gets a parameter
  • px_get_record — Returns record of paradox database
  • px_get_schema — Returns the database schema
  • px_get_value — Gets a value
  • px_insert_record — Inserts record into paradox database
  • px_new — Create a new paradox object
  • px_numfields — Returns number of fields in a database
  • px_numrecords — Returns number of records in a database
  • px_open_fp — Open paradox database
  • px_put_record — Stores record into paradox database
  • px_retrieve_record — Returns record of paradox database
  • px_set_blob_file — Sets the file where blobs are read from
  • px_set_parameter — Sets a parameter
  • px_set_tablename — Sets the name of a table (deprecated)
  • px_set_targetencoding — Sets the encoding for character fields (deprecated)
  • px_set_value — Sets a value
  • px_timestamp2string — Converts the timestamp into a string.
  • px_update_record — Updates record in paradox database
Stałe predefiniowane
px_close
Paradox


Closes a paradox database

Paradox Funkcje
px_create_fp
Paradox Funkcje
PHP Manual

px_close

(PECL paradox >= 1.0.0)

px_close — Closes a paradox database

Opis

bool px_close ( resource $pxdoc )

Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • px_open_fp() - Open paradox database
  • The example at px_new() - Create a new paradox object

Paradox Funkcje
px_create_fp
Paradox Funkcje


Create a new paradox database

px_close
px_date2string
Paradox Funkcje
PHP Manual

px_create_fp

(PECL paradox >= 1.0.0)

px_create_fp — Create a new paradox database

Opis

bool px_create_fp ( resource $pxdoc , resource $file , array $fielddesc )

Create a new paradox database file. The actual file has to be opened before with fopen(). Make sure the file is writable.

Informacja:

Calling this functions issues a warning about an empty tablename which can be safely ignored. Just set the tablename afterwards with px_set_parameter().

Informacja:

This function is highly experimental, due to insufficient documentation of the paradox file format. Database files created with this function can be opened by px_open_fp() and has been successfully opened by the Paradox software, but your milage may vary.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

File handle as returned by fopen().

fielddesc

fielddesc is an array containing one element for each field specification. A field specification is an array itself with either two or three elements.The first element is always a string value used as the name of the field. It may not be larger than ten characters. The second element contains the field type which is one of the constants listed in the table Constants for field types. In the case of a character field or bcd field, you will have to provide a third element specifying the length respectively the precesion of the field. If your field specification contains blob fields, you will have to make sure to either make the field large enough for all field values to fit or specify a blob file with px_set_blob_file() for storing the blobs. If this is not done the field data is truncated.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Creating a Paradox database with two fields

<?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "w+");
$fields = array(array("col1", "S"), array("col2", "I"));
if(!px_create_fp($pxdoc, $fp, $fields)) {
  /* Error handling */
}
px_set_parameter($pxdoc, "tablename", "testtable");
for($i=-50; $i<50; $i++) {
  $rec = array($i, -$i);
  px_put_record($pxdoc, $rec);
}
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

Zobacz też:

  • px_new() - Create a new paradox object
  • px_put_record() - Stores record into paradox database
  • fopen() - Otwiera plik lub URL

px_close
px_date2string
Paradox Funkcje


Converts a date into a string.

px_create_fp
px_delete_record
Paradox Funkcje
PHP Manual

px_date2string

(PECL paradox >= 1.4.0)

px_date2string — Converts a date into a string.

Opis

string px_date2string ( resource $pxdoc , int $value , string $format )

Turns a date as it stored in the paradox file into human readable format. Paradox dates are the number of days since 1.1.0000. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the example below.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

value

Value as stored in paradox database field of type PX_FIELD_DATE.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, L).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Turn a paradox date into a human readable form

<?php
$px = px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";
/* px_date2string() outputs the same */
echo px_date2string($px, $days, "n/d/Y")."\n";

px_delete($px);
?>

Powyższy przykład wyświetli:

7/15/1917
7/15/1917

Zobacz też:

  • px_timestamp2string() - Converts the timestamp into a string.
  • jdtogregorian() - Converts Julian Day Count to Gregorian date

px_create_fp
px_delete_record
Paradox Funkcje


Deletes record from paradox database

px_date2string
px_delete
Paradox Funkcje
PHP Manual

px_delete_record

(PECL paradox >= 1.4.0)

px_delete_record — Deletes record from paradox database

Opis

bool px_delete_record ( resource $pxdoc , int $num )

This function deletes a record from the database. It does not free the space in the database file but just marks it as deleted. Inserting a new record afterwards will reuse the space.

Informacja:

This function is only available if pxlib >= 0.6.0 is used.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

px_date2string
px_delete
Paradox Funkcje


Deletes resource of paradox database

px_delete_record
px_get_field
Paradox Funkcje
PHP Manual

px_delete

(PECL paradox >= 1.0.0)

px_delete — Deletes resource of paradox database

Opis

bool px_delete ( resource $pxdoc )

Deletes the resource of the paradox file and frees all memory.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

px_delete_record
px_get_field
Paradox Funkcje


Returns the specification of a single field

px_delete
px_get_info
Paradox Funkcje
PHP Manual

px_get_field

(PECL paradox >= 1.0.0)

px_get_field — Returns the specification of a single field

Opis

array px_get_field ( resource $pxdoc , int $fieldno )

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

fieldno

Number of the field. The first field has number 0. Specifying a field number less than 0 and greater or equal the number of fields will trigger an error.

Zwracane wartości

Returns the specification of the fieldno 'th database field as an associated array. The array contains three fields named name, type, and size.

px_delete
px_get_info
Paradox Funkcje


Return lots of information about a paradox file

px_get_field
px_get_parameter
Paradox Funkcje
PHP Manual

px_get_info

(PECL paradox >= 1.0.0)

px_get_info — Return lots of information about a paradox file

Opis

array px_get_info ( resource $pxdoc )

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

Zwracane wartości

Returns an associated array with lots of information about a paradox file. This array is likely to be extended in the future.

fileversion

Version of file multiplied by 10, e.g. 70.

tablename

Name of table as stored in the file. If the database was created by pxlib, then this will be the name of the file without the extension.

numrecords

Number of records in this table.

numfields

Number of fields in this table.

headersize

Number of bytes used for the header. This is usually 0x800.

recordsize

Number of bytes used for each record. This is the sum of all field sizes (available since version 1.4.2).

maxtablesize

This value multiplied by 0x400 is the size of a data block in bytes. The maximum number of records in a datablock is the integer part of (maxtablesize * 0x400 - 8) / recordsize.

numdatablocks

The number of data blocks in the file. Each data block contains a certain number of records which depends on the record size and the data block size (maxtablesize). Data blocks may not necessarily be completely filled.

numindexfields

Number of fields used for the primary index. The fields do always start with field number 1.

codepage

The DOS codepage which was used for encoding fields with character data. If the target encoding is not set with px_set_targetencoding() this will be the encoding for character fields when records are being accessed with px_get_record() or px_retrieve_record().

Zobacz też:

  • px_numfields() - Returns number of fields in a database
  • px_numrecords() - Returns number of records in a database

px_get_field
px_get_parameter
Paradox Funkcje


Gets a parameter

px_get_info
px_get_record
Paradox Funkcje
PHP Manual

px_get_parameter

(PECL paradox >= 1.1.0)

px_get_parameter — Gets a parameter

Opis

string px_get_parameter ( resource $pxdoc , string $name )

Gets various parameters.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

The name can be one of the following:

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields with px_get_record() or px_retrieve_record() is recoded into the targetencoding. If it is not set, then the data will be delivered as stored in the database file.

inputencoding

The encoding of the input data which is to be stored into the database. When storing data of character fields in the database, the data is expected to be delivered in this encoding.

Zwracane wartości

Returns the value of the parameter lub FALSE w przypadku niepowodzenia.

px_get_info
px_get_record
Paradox Funkcje


Returns record of paradox database

px_get_parameter
px_get_schema
Paradox Funkcje
PHP Manual

px_get_record

(PECL paradox >= 1.0.0)

px_get_record — Returns record of paradox database

Opis

array px_get_record ( resource $pxdoc , int $num [, int $mode = 0 ] )

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys of the returned array into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp (PX_FIELD_TIMESTAMP) and date (PX_FIELD_DATE) are floating point respectively int values counting milliseconds respectively days starting at the beginning of julian calendar. Use the functions px-timestamp2string() and px-date2string() to convert them into a character representation.

Zwracane wartości

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

Zobacz też:

  • px_retrieve_record() - Returns record of paradox database

px_get_parameter
px_get_schema
Paradox Funkcje


Returns the database schema

px_get_record
px_get_value
Paradox Funkcje
PHP Manual

px_get_schema

(PECL paradox >= 1.0.0)

px_get_schema — Returns the database schema

Opis

array px_get_schema ( resource $pxdoc [, int $mode = 0 ] )

px_get_schema() returns the database schema.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

mode

If the optional mode is PX_KEYTOLOWER or PX_KEYTOUPPER the keys of the returned array will be converted to lower or upper case. If mode is 0 or not passed at all, then the key name will be identical to the field name.

Zwracane wartości

Returns the schema of a database file as an associated array. The key name is equal to the field name. Each array element is itself an associated array containing the two fields type and size. type is one of the constants in table Constants for field types. size is the number of bytes this field consumes in the record. The total of all field sizes is equal to the record size as it can be retrieved with px-get-info().

px_get_record
px_get_value
Paradox Funkcje


Gets a value

px_get_schema
px_insert_record
Paradox Funkcje
PHP Manual

px_get_value

(PECL paradox >= 1.1.0)

px_get_value — Gets a value

Opis

float px_get_value ( resource $pxdoc , string $name )

Gets various values.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

Zwracane wartości

Returns the value of the parameter lub FALSE w przypadku niepowodzenia.

px_get_schema
px_insert_record
Paradox Funkcje


Inserts record into paradox database

px_get_value
px_new
Paradox Funkcje
PHP Manual

px_insert_record

(PECL paradox >= 1.4.0)

px_insert_record — Inserts record into paradox database

Opis

int px_insert_record ( resource $pxdoc , array $data )

Inserts a new record into the database. The record is not necessarily inserted at the end of the database, but may be inserted at any position depending on where the first free slot is found.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Most field values can be passed as its equivalent php type e.g. a long value is used for fields of type PX_FIELD_LONG, PX_FIELD_SHORT and PX_FIELD_AUTOINC, a double values is used for fields of type PX_FIELD_CURRENCY and PX_FIELD_NUMBER. Field values for blob and alpha fields are passed as strings.

Fields of type PX_FIELD_TIME and PX_FIELD_DATE both require a long value. In the first case this is the number of milliseconds since midnight. In the second case this is the number of days since 1.1.0000. Below there are two examples to convert the current date or timestamp into a value suitable for one of paradox's date/time fields.

Informacja:

This function is only available if pxlib >= 0.6.0 is used.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

Zwracane wartości

Returns FALSE on failure or the record number in case of success.

Przykłady

Przykład #1 Set the date/time fields in a paradox database to the current date/time

<?php
$px = px_new();
$fp = fopen("test.db", "w+");
px_create_fp($px, $fp, array(array("timestamp", "@"), array("time", "T"), array("date", "D")));

$curdate = getdate();
$jd = gregoriantojd($curdate["mon"], $curdate["mday"], $curdate["year"]);
$days = $jd - 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
$secs = $curdate["hours"]*3600 + $curdate["minutes"]*60 + $curdate["seconds"];
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));

$curtimestamp = microtime(true);
$days = (int) ($curtimestamp/86400);
$secs = $curtimestamp - ($days * 86400.0);
$days += 2440588; /* Number of days between 1.1.4714 b.c. and 1.1.1970 */
$days -= 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));
for($i=0; $i<2; $i++) {
    $rec = px_retrieve_record($px, $i);
    echo px_timestamp2string($px, $rec["timestamp"], "n/d/Y H:i:s")."\n";
    echo px_date2string($px, $rec["date"], "n/d/Y")."\n";
}
px_close($px);
px_delete($px);
?>

Powyższy przykład wyświetli:

2/21/2006 21:42:30
2/21/2006
2/21/2006 20:42:30
2/21/2006

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain milli seconds.

Zobacz też:

px_update_record() - Updates record in paradox database

px_get_value
px_new
Paradox Funkcje


Create a new paradox object

px_insert_record
px_numfields
Paradox Funkcje
PHP Manual

px_new

(PECL paradox >= 1.0.0)

px_new — Create a new paradox object

Opis

resource px_new ( void )

Create a new paradox object. You will have to call this function before any further functions. px_new() does not create any file on the disk, it just creates an instance of a paradox object. This function must not be called if the object oriented interface is used. Use new paradox_db() instead.

Zwracane wartości

Returns FALSE on failure.

Przykłady

Przykład #1 Opening a Paradox database

<?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "r");
if(!px_open_fp($pxdoc, $fp)) {
  /* Error handling */
}
// ...
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

If you prefer the object oriented API, then the above example will look like the following.

Przykład #2 Opening a Paradox database

<?php
$fp = fopen("test.db", "r");
$pxdoc = new paradox_db();
if(!$pxdoc->open_fp($fp)) {
  /* Error handling */
}
// ...
$pxdoc->close();
fclose($fp);
?>

Zobacz też:

  • px_delete() - Deletes resource of paradox database
  • px_open_fp() - Open paradox database

px_insert_record
px_numfields
Paradox Funkcje


Returns number of fields in a database

px_new
px_numrecords
Paradox Funkcje
PHP Manual

px_numfields

(PECL paradox >= 1.0.0)

px_numfields — Returns number of fields in a database

Opis

int px_numfields ( resource $pxdoc )

Get the number of fields in a database file.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

Zwracane wartości

Returns the number of fields in a database file. The return value of this function is identical to the element numfields in the array returned by px_get_info().

px_new
px_numrecords
Paradox Funkcje


Returns number of records in a database

px_numfields
px_open_fp
Paradox Funkcje
PHP Manual

px_numrecords

(PECL paradox >= 1.0.0)

px_numrecords — Returns number of records in a database

Opis

int px_numrecords ( resource $pxdoc )

Get the number of records in a database file.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

Zwracane wartości

Returns the number of records in a database file. The return value of this function is identical to the element numrecords in the array returned by px_get_info().

px_numfields
px_open_fp
Paradox Funkcje


Open paradox database

px_numrecords
px_put_record
Paradox Funkcje
PHP Manual

px_open_fp

(PECL paradox >= 1.0.0)

px_open_fp — Open paradox database

Opis

bool px_open_fp ( resource $pxdoc , resource $file )

Open an existing paradox database file. The actual file has to be opened before with fopen(). This function can also be used to open primary index files and tread them like a paradox database. This is supported for those who would like to investigate a primary index. It cannot be used to accelerate access to a database file.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

file is the return value from fopen() with the actual database file as parameter. Make sure the database is writable if you plan to update or insert records.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fopen() - Otwiera plik lub URL
  • The example at px_new() - Create a new paradox object

px_numrecords
px_put_record
Paradox Funkcje


Stores record into paradox database

px_open_fp
px_retrieve_record
Paradox Funkcje
PHP Manual

px_put_record

(PECL paradox >= 1.0.0)

px_put_record — Stores record into paradox database

Opis

bool px_put_record ( resource $pxdoc , array $record [, int $recpos = -1 ] )

Stores a record into a paradox database. The record is always added at the end of the database, regardless of any free slots. Use px_insert_record() to add a new record into the first free slot found in the database.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

record

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

recpos

This optional parameter may be used to specify a record number greater than the current number of records in the database. The function will add as many empty records as needed. There is hardly any need for this parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

px_open_fp
px_retrieve_record
Paradox Funkcje


Returns record of paradox database

px_put_record
px_set_blob_file
Paradox Funkcje
PHP Manual

px_retrieve_record

(PECL paradox >= 1.4.0)

px_retrieve_record — Returns record of paradox database

Opis

array px_retrieve_record ( resource $pxdoc , int $num [, int $mode = 0 ] )

This function is very similar to px_get_record() but uses internally a different approach to retrieve the data. It relies on pxlib for reading each single field value, which usually results in support for more field types.

Informacja:

This function is only available if pxlib >= 0.6.0 is used.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp is a floating point value also counting milliseconds starting at the beginning of julian calendar.

Zwracane wartości

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

Zobacz też:

  • px_get_record() - Returns record of paradox database

px_put_record
px_set_blob_file
Paradox Funkcje


Sets the file where blobs are read from

px_retrieve_record
px_set_parameter
Paradox Funkcje
PHP Manual

px_set_blob_file

(PECL paradox >= 1.3.0)

px_set_blob_file — Sets the file where blobs are read from

Opis

bool px_set_blob_file ( resource $pxdoc , string $filename )

Sets the name of the file where blobs are going to be read from or written into. Without calling this function, px_get_record() or px_retrieve_record() will only return data in blob fields if the data is part of the record and not stored in the blob file. Blob data is stored in the record if it is small enough to fit in the size of the blob field.

Calling px_put_record(),
px_insert_record(), or
px_update_record() without calling
px_set_blob_file() will result in truncated blob fields
unless the data fits into the database file.

Calling this function twice will close the first blob file and open the new one.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

filename

The name of the file. Its extension should be .MB.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

px_retrieve_record
px_set_parameter
Paradox Funkcje


Sets a parameter

px_set_blob_file
px_set_tablename
Paradox Funkcje
PHP Manual

px_set_parameter

(PECL paradox >= 1.1.0)

px_set_parameter — Sets a parameter

Opis

bool px_set_parameter ( resource $pxdoc , string $name , string $value )

Sets various parameters.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

Depending on the parameter you want to set, name can be one of the following.

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

inputencoding

The encoding of the input data which is to be stored into the database.

value

The value of parameter to set. For inputencoding and targetencoding this must be the name of the encoding as understood by iconv or recode, e.g. iso-8859-1, utf-8, cp850.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • px_get_info() - Return lots of information about a paradox file to determine the DOS code page.

px_set_blob_file
px_set_tablename
Paradox Funkcje


Sets the name of a table (deprecated)

px_set_parameter
px_set_targetencoding
Paradox Funkcje
PHP Manual

px_set_tablename

(PECL paradox >= 1.0.0)

px_set_tablename — Sets the name of a table (deprecated)

Opis

void px_set_tablename ( resource $pxdoc , string $name )

Sets the table name of a paradox database, which was created with px_create_fp(). This function is deprecated use px_set_parameter() instead.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

tablename

The name of the table. If it is not set explicitly it will be set to the name of the database file.

Zwracane wartości

Returns NULL on success lub FALSE w przypadku niepowodzenia.

Zobacz też:

px_set_parameter() - Sets a parameter

px_set_parameter
px_set_targetencoding
Paradox Funkcje


Sets the encoding for character fields (deprecated)

px_set_tablename
px_set_value
Paradox Funkcje
PHP Manual

px_set_targetencoding

(PECL paradox >= 1.0.0)

px_set_targetencoding — Sets the encoding for character fields (deprecated)

Opis

bool px_set_targetencoding ( resource $pxdoc , string $encoding )

Set the encoding for data retrieved from a character field. All character fields will be recoded to the encoding set by this function. If the encoding is not set, the character data will be returned in the DOS code page encoding as specified in the database file. The encoding can be any string identifier known to iconv or recode. On Unix systems run iconv -l for a list of available encodings.

This function is deprecated and should be replaced by calling px_set_parameter().

See also px_get_info() to determine the DOS code page as stored in the database file.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

encoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

Zwracane wartości

Returns FALSE if the encoding could not be set, e.g. the encoding is unknown, or pxlib does not support recoding at all. In the second case a warning will be issued.

Zobacz też:

px_set_parameter() - Sets a parameter

px_set_tablename
px_set_value
Paradox Funkcje


Sets a value

px_set_targetencoding
px_timestamp2string
Paradox Funkcje
PHP Manual

px_set_value

(PECL paradox >= 1.1.0)

px_set_value — Sets a value

Opis

bool px_set_value ( resource $pxdoc , string $name , float $value )

Sets various values.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

value

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

px_set_parameter() - Sets a parameter

px_set_targetencoding
px_timestamp2string
Paradox Funkcje


Converts the timestamp into a string.

px_set_value
px_update_record
Paradox Funkcje
PHP Manual

px_timestamp2string

(PECL paradox >= 1.4.0)

px_timestamp2string — Converts the timestamp into a string.

Opis

string px_timestamp2string ( resource $pxdoc , float $value , string $format )

Turns a timestamp as it stored in the paradox file into human readable format. Paradox timestamps are the number of miliseconds since 0001-01-02. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the following example.

Parametry

pxdoc

Resource identifier of the paradox database.

value

Value as stored in paradox database field of type PX_FIELD_TIME, or PX_FIELD_TIMESTAMP.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, H, h, G, g, i, s, A, a, L).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Turn a paradox timestamp into a human readable form

<?php
$px = px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";

/* Turn it into a timestamp as it stored in a paradox database */
/* Timestamps are stored in miliseconds since 0001-01-02 */
$stamp = $days * 86400.0 * 1000.0;
/* Add one hour */
$stamp += 3600000.0;
/* The following will output '7/15/1917 01:00:00'. */
echo px_timestamp2string($px, $stamp, "n/d/Y H:i:s")."\n";

px_delete($px);
?>

Powyższy przykład wyświetli:

7/15/1917
7/15/1917 01:00:00

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain miliseconds.

Zobacz też:

  • px_date2string() - Converts a date into a string.
  • jdtogregorian() - Converts Julian Day Count to Gregorian date

px_set_value
px_update_record
Paradox Funkcje


Updates record in paradox database

px_timestamp2string
PostgreSQL
Paradox Funkcje
PHP Manual

px_update_record

(PECL paradox >= 1.4.0)

px_update_record — Updates record in paradox database

Opis

bool px_update_record ( resource $pxdoc , array $data , int $num )

Updates an exiting record in the database. The record starts at 0.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Informacja:

This function is only available if pxlib >= 0.6.0 is used.

Parametry

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated array containing the field values as returned by px_retrieve_record().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

px_insert_record() - Inserts record into paradox database

px_timestamp2string
PostgreSQL
Paradox Funkcje


PostgreSQL

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Podstawowe użycie
  • Funkcje PostgreSQL
    • pg_affected_rows — Zwraca liczbę zmodyfikowanych wierszy
    • pg_cancel_query — Przerywa zapytanie asynchroniczne
    • pg_client_encoding — Zwraca stronę kodową klienta
    • pg_close — Zamyka połączenie z PostgreSQL
    • pg_connect — Otwiera tymczasowe połączenie do PostgreSQL-a
    • pg_connection_busy — Sprawdza czy połączenie jest zajęte czy wolne
    • pg_connection_reset — Restartuje połączenie
    • pg_connection_status — Zwraca stan połączenia
    • pg_convert — Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.
    • pg_copy_from — Wstawia wiersze do tabeli z tablicy
    • pg_copy_to — Kopiuje tabelę do tablicy
    • pg_dbname — Podaje nazwę bazy danych
    • pg_delete — Usuwa rekordy
    • pg_end_copy — Synchronizuje klienta z serwerem PostgreSQL.
    • pg_escape_bytea — Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea
    • pg_escape_identifier — Escape a identifier for insertion into a text field
    • pg_escape_literal — Escape a literal for insertion into a text field
    • pg_escape_string — Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape
    • pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result.
    • pg_fetch_all_columns — Fetches all rows in a particular result column as an array
    • pg_fetch_all — Fetches all rows from a result as an array
    • pg_fetch_array — Pobiera wiersz jako tablicę
    • pg_fetch_assoc — Fetch a row as an associative array
    • pg_fetch_object — Pobiera wiersz jako obiekt
    • pg_fetch_result — Pobiera dane z wyniku
    • pg_fetch_row — Pobiera wiersz jako tablicę z indeksami numerycznymi
    • pg_field_is_null — Sprawdza czy pole SQL zawiera NULL
    • pg_field_name — Zwraca nazwę kolumny
    • pg_field_num — Zwraza numer kolumny o podanej nazwie
    • pg_field_prtlen — Zwraca drukowalną długość
    • pg_field_size — Zwraca wewnętrzny rozmiar kolumny
    • pg_field_table — Returns the name or oid of the tables field
    • pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
    • pg_field_type — Zwraca typ wskazanej kolumny
    • pg_free_result — Zwalnia pamięć wyniku
    • pg_get_notify — Gets SQL NOTIFY message
    • pg_get_pid — Gets the backend's process ID
    • pg_get_result — Pobiera wynik zapytania asynchroniczego
    • pg_host — Zwraca nazwę komputera związanego z połączeniem
    • pg_insert — Wstawia tablicę do tabeli
    • pg_last_error — Zwraca łańcuch ostatniego komunikatu błędu dla połączenia
    • pg_last_notice — Zwraca komunikaty informacyjne serwera PostgreSQL
    • pg_last_oid — Zwraca identyfikator OID ostatniego wiersza
    • pg_lo_close — Zamyka wielki obiekt (LO)
    • pg_lo_create — Tworzy wielki obiekt (Large Object - LO)
    • pg_lo_export — Eksportuje wielki obiekt (Large Object - LO) do pliku
    • pg_lo_import — Importuje wielki obiekt (Large Object - LO) z pliku
    • pg_lo_open — Otwiera wielki obiekt (Large Object - LO)
    • pg_lo_read_all — Odczytuje wielki obiekt (Large Object - LO) i wysła go do przeglądarki
    • pg_lo_read — Odczytuje wielki obiekt (Large Object - LO)
    • pg_lo_seek — Przemieszcza wskaźnik położenia w wielkim obiekcie (Large Object - LO)
    • pg_lo_tell — Zwraca wskaźnik położenia w wielkim obiekcie (Large Object - LO)
    • pg_lo_unlink — Usuwa wielki obiekt (Large Object - LO)
    • pg_lo_write — Zapisuje do wielkiego obiektu (Large Object - LO)
    • pg_meta_data — Pobiera informacje o tabeli
    • pg_num_fields — Zwraca liczbę kolumn
    • pg_num_rows — Zwraca liczbę wierszy
    • pg_options — Podaje opcje powiązane z połączenim
    • pg_parameter_status — Looks up a current parameter setting of the server.
    • pg_pconnect — Otwiera trwałe połączenie z serwerem PostgreSQL
    • pg_ping — Ping database connection
    • pg_port — Zwraca numer portu związany z połączeniem
    • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.
    • pg_put_line — Wysyła łańcuch zakończony znakiem NULL do serwera PostgreSQL
    • pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
    • pg_query — Realizujezapytanie do bazy danych
    • pg_result_error_field — Returns an individual field of an error report.
    • pg_result_error — Zwraca błąd związany z identyfikatorem wyniku
    • pg_result_seek — Set internal row offset in result resource
    • pg_result_status — Zwraca stan wyniku zapytania
    • pg_select — Wybiera wiersze
    • pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
    • pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.
    • pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).
    • pg_send_query — Wysyła zapytanie asynchroniczne
    • pg_set_client_encoding — Ustawia stronę kodową klienta PostgreSQL-a
    • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error.
    • pg_trace — Uruchamia śledzenie połączeń z PostgreSQL
    • pg_transaction_status — Returns the current in-transaction status of the server.
    • pg_tty — Zwraca nazwę konsoli tty związanej z połączeniem
    • pg_unescape_bytea — Unescape binary for bytea type
    • pg_untrace — Wyłącza śledzenie połączeń PostgreSQL-a
    • pg_update — Aktualizuje tabelę
    • pg_version — Returns an array with client, protocol and server version (when available)
px_update_record
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Baza danych PostgreSQL jest otwartym oprogramowaniem, dostępnym bez ponoszenia opłat. Postgres, tworzony początkowo na Wydziale Nauk Komputerowych Uniwersytetu Berkeley, był pionierem wielu koncepcji obiektowo-relacyjnych, obecnie dostępnych w niektórych komercyjnych bazach danych. Jest zgodny ze standardami języków SQL92/SQL99, obsługuje transakcje, integralność referencji, procedury składowane, i pozwala definiować własne typy danych. PostgreSQL jest wolnodostępnym spadkobiercą oryginalnego kodu Berkeley.

PostgreSQL
Instalacja/Konfiguracja
PostgreSQL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
PostgreSQL


Wymagania

PHP obsługuje PostgreSQL w wersji 6.5 lub nowszej. Aby używać wszystkich właściwości rozszerzenia wymagana jest baza danych PostgreSQL 8.0 lub nowsza. PostgreSQL obsługuje wiele kodowań znaków, włącznie z wielobajtowym. Bieżące wydanie, oraz więcej informacji na temat PostgreSQL jest dostępnych na witrynach: » http://www.postgresql.org/ i » Dokumentacja PostgreSQL.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

W celu uruchomienia obsługi bazy danych PostgreSQL, należy w czasie kompilacji PHP użyć opcji konfiguracyjnej --with-pgsql[=DIR] , gdzie DIR jest katalogiem instalacji PostgreSQL, domyślnie /usr/local/pgsql. Jeśli jest dostępny moduł współdzielony, rozszerzenie PostgreSQL może być załadowane przez wpisanie dyrektywy extension w pliku php.ini lub za pomocą funkcji dl().

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracyjne PostgreSQL
Nazwa | Wartość domyślna | Możliwość zmian | Rejestr zmian
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Dostępna od PHP 4.2.0.
pgsql.ignore_notice | "0" | PHP_INI_ALL | Dostępna od PHP 4.3.0.
pgsql.log_notice | "0" | PHP_INI_ALL | Dostępna od PHP 4.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.

pgsql.allow_persistent boolean

Określa czy pozwolić bazie PostgreSQL na połączenia stałe.

pgsql.max_persistent integer

Definiuje maksymalną liczbę połączeń stałych PostgreSQL na proces serwera.

pgsql.max_links integer

Definiuje maksymalną liczbę połączeń PostgreSQL na proces serwera, włączając w to połączenia stałe.

pgsql.auto_reset_persistent integer

Wykrywa błędne identyfikatory połączeń utworzone za pomocą pg_pconnect(). Potrzebuje niewielkiego kosztu obciążenia.

pgsql.ignore_notice integer

Określa czy ignorować powiadomienia o uwagach zwracane przez PostgreSQL.

pgsql.log_notice integer

Określa czy logować powiadomienia o uwagach zwracane przez PostgreSQL. Dyrektywa PHP pgsql.ignore_notice musi być wyłączona, żeby możliwe było logowanie powiadomień o uwagach.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

Istnieją dwa typy zasobów używanych przez rozszerzenie PostgreSQL. Pierwszy to identyfikator połączenia z bazą danych. Natomiast drugi przechowuje wynik zapytania.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

PGSQL_ASSOC (integer)
Passed to pg_fetch_array(). Return an associative array of field names and values.
PGSQL_NUM (integer)
Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.
PGSQL_BOTH (integer)
Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).
PGSQL_CONNECT_FORCE_NEW (integer)
Passed to pg_connect() to force the creation of a new connection, rather than re-using an existing identical connection.
PGSQL_CONNECTION_BAD (integer)
Returned by pg_connection_status() indicating that the database connection is in an invalid state.
PGSQL_CONNECTION_OK (integer)
Returned by pg_connection_status() indicating that the database connection is in a valid state.
PGSQL_SEEK_SET (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.
PGSQL_SEEK_CUR (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the current position.
PGSQL_SEEK_END (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.
PGSQL_EMPTY_QUERY (integer)
Returned by pg_result_status(). The string sent to the server was empty.
PGSQL_COMMAND_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning no data.
PGSQL_TUPLES_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).
PGSQL_COPY_OUT (integer)
Returned by pg_result_status(). Copy Out (from server) data transfer started.
PGSQL_COPY_IN (integer)
Returned by pg_result_status(). Copy In (to server) data transfer started.
PGSQL_BAD_RESPONSE (integer)
Returned by pg_result_status(). The server's response was not understood.
PGSQL_NONFATAL_ERROR (integer)
Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.
PGSQL_FATAL_ERROR (integer)
Returned by pg_result_status(). A fatal error occurred.
PGSQL_TRANSACTION_IDLE (integer)
Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.
PGSQL_TRANSACTION_ACTIVE (integer)
Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.
PGSQL_TRANSACTION_INTRANS (integer)
Returned by pg_transaction_status(). The connection is idle, in a transaction block.
PGSQL_TRANSACTION_INERROR (integer)
Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.
PGSQL_TRANSACTION_UNKNOWN (integer)
Returned by pg_transaction_status(). The connection is bad.
PGSQL_DIAG_SEVERITY (integer)
Passed to pg_result_error_field(). The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.
PGSQL_DIAG_SQLSTATE (integer)
Passed to pg_result_error_field(). The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. This field is not localizable, and is always present.
PGSQL_DIAG_MESSAGE_PRIMARY (integer)
Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.
PGSQL_DIAG_MESSAGE_DETAIL (integer)
Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.
PGSQL_DIAG_MESSAGE_HINT (integer)
Passed to pg_result_error_field(). Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.
PGSQL_DIAG_STATEMENT_POSITION (integer)
Passed to pg_result_error_field(). A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
PGSQL_DIAG_INTERNAL_POSITION (integer)
Passed to pg_result_error_field(). This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.
PGSQL_DIAG_INTERNAL_QUERY (integer)
Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
PGSQL_DIAG_CONTEXT (integer)
Passed to pg_result_error_field(). An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
PGSQL_DIAG_SOURCE_FILE (integer)
Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_LINE (integer)
Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_FUNCTION (integer)
Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.
PGSQL_ERRORS_TERSE (integer)
Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.
PGSQL_ERRORS_DEFAULT (integer)
Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).
PGSQL_ERRORS_VERBOSE (integer)
Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.
PGSQL_STATUS_LONG (integer)
Passed to pg_result_status(). Indicates that numerical result code is desired.
PGSQL_STATUS_STRING (integer)
Passed to pg_result_status(). Indicates that textual result command tag is desired.
PGSQL_CONV_IGNORE_DEFAULT (integer)
Passed to pg_convert(). Ignore default values in the table during conversion.
PGSQL_CONV_FORCE_NULL (integer)
Passed to pg_convert(). Use SQL NULL in place of an empty string.
PGSQL_CONV_IGNORE_NOT_NULL (integer)
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.
Typy zasobów
Przykłady
PostgreSQL


Przykłady

Spis treści

  • Podstawowe użycie
Stałe predefiniowane
Podstawowe użycie
PostgreSQL


Podstawowe użycie

Ten nieskomplikowany przykład pokazuje jak można nawiązać połączenie, wykonać zapytanie, wyświetlić wyniki i rozłączyć się z bazą danych PostgreSQL.

Przykład #1 Przykład działania rozszerzenia PostgreSQL

<?php
// Nawiązanie połączenia, wybór bazy danych
$dbconn = pg_connect("host=localhost dbname=publikacje user=www password=tajne")
    or die('Nie można nawiązać połączenia: ' . pg_last_error());

// Wykonanie zapytania SQL
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Nieprawidłowe zapytanie: ' . pg_last_error());

// Wyświetlenie wyników w postaci HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

// Zwolnienie zasobów wyniku zapytania
pg_free_result($result);

// Zamknięcie połączenia
pg_close($dbconn);
?>

Przykłady
Funkcje PostgreSQL
Przykłady


Funkcje PostgreSQL

Notatki

Informacja:

Nie wszystkie funkcje są obsługiwane w każdym wydaniu. To zależy od wersji libpq ( Interfejs C klienta PostgreSQL ) oraz sposobu w jaki został on skompilowany. Jeśli brakuje niektórych właściwości, to bardzo możliwe, że libpq ich nie obsługuje.

Informacja:

Większość funkcji PostgreSQL posiada connection jako pierwszy, opcjonalny parametr. Jeśli nie jest on podawany, to używane jest ostatnio otwarte połączenie. Jeśli ono nie istnieje, to funkcje zwracają FALSE.

Informacja:

Podczas tworzenia obiektów oraz wykonywania zapytań PostgreSQL zamienia automatycznie na małe litery wszystkie identyfikatory (np. nazwy tabel, kolumn). Aby wymusić używanie dużych i małych liter w nazwach identyfikatorów należy umieszczać je w znakach unikowych - podwójnych cudzysłowach ("").

Informacja:

PostgreSQL nie posiada specjalnych poleceń do pobierania informacji o schemacie bazy danych (np. wszystkich tabelach w bieżącej bazie danych). Zamiast tego istnieje niestandardowy schemat nazwany information_schema. W PostgreSQL 7.4 i nowszych można pobierać z niego za pomocą zapytań SQL widoki systemowe i inne niezbędne informacje. Szczegółowe informacje na ten temat znajdują się w » Dokumentacja PostgreSQL

Spis treści

  • pg_affected_rows — Zwraca liczbę zmodyfikowanych wierszy
  • pg_cancel_query — Przerywa zapytanie asynchroniczne
  • pg_client_encoding — Zwraca stronę kodową klienta
  • pg_close — Zamyka połączenie z PostgreSQL
  • pg_connect — Otwiera tymczasowe połączenie do PostgreSQL-a
  • pg_connection_busy — Sprawdza czy połączenie jest zajęte czy wolne
  • pg_connection_reset — Restartuje połączenie
  • pg_connection_status — Zwraca stan połączenia
  • pg_convert — Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.
  • pg_copy_from — Wstawia wiersze do tabeli z tablicy
  • pg_copy_to — Kopiuje tabelę do tablicy
  • pg_dbname — Podaje nazwę bazy danych
  • pg_delete — Usuwa rekordy
  • pg_end_copy — Synchronizuje klienta z serwerem PostgreSQL.
  • pg_escape_bytea — Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea
  • pg_escape_identifier — Escape a identifier for insertion into a text field
  • pg_escape_literal — Escape a literal for insertion into a text field
  • pg_escape_string — Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape
  • pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_fetch_all_columns — Fetches all rows in a particular result column as an array
  • pg_fetch_all — Fetches all rows from a result as an array
  • pg_fetch_array — Pobiera wiersz jako tablicę
  • pg_fetch_assoc — Fetch a row as an associative array
  • pg_fetch_object — Pobiera wiersz jako obiekt
  • pg_fetch_result — Pobiera dane z wyniku
  • pg_fetch_row — Pobiera wiersz jako tablicę z indeksami numerycznymi
  • pg_field_is_null — Sprawdza czy pole SQL zawiera NULL
  • pg_field_name — Zwraca nazwę kolumny
  • pg_field_num — Zwraza numer kolumny o podanej nazwie
  • pg_field_prtlen — Zwraca drukowalną długość
  • pg_field_size — Zwraca wewnętrzny rozmiar kolumny
  • pg_field_table — Returns the name or oid of the tables field
  • pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
  • pg_field_type — Zwraca typ wskazanej kolumny
  • pg_free_result — Zwalnia pamięć wyniku
  • pg_get_notify — Gets SQL NOTIFY message
  • pg_get_pid — Gets the backend's process ID
  • pg_get_result — Pobiera wynik zapytania asynchroniczego
  • pg_host — Zwraca nazwę komputera związanego z połączeniem
  • pg_insert — Wstawia tablicę do tabeli
  • pg_last_error — Zwraca łańcuch ostatniego komunikatu błędu dla połączenia
  • pg_last_notice — Zwraca komunikaty informacyjne serwera PostgreSQL
  • pg_last_oid — Zwraca identyfikator OID ostatniego wiersza
  • pg_lo_close — Zamyka wielki obiekt (LO)
  • pg_lo_create — Tworzy wielki obiekt (Large Object - LO)
  • pg_lo_export — Eksportuje wielki obiekt (Large Object - LO) do pliku
  • pg_lo_import — Importuje wielki obiekt (Large Object - LO) z pliku
  • pg_lo_open — Otwiera wielki obiekt (Large Object - LO)
  • pg_lo_read_all — Odczytuje wielki obiekt (Large Object - LO) i wysła go do przeglądarki
  • pg_lo_read — Odczytuje wielki obiekt (Large Object - LO)
  • pg_lo_seek — Przemieszcza wskaźnik położenia w wielkim obiekcie (Large Object - LO)
  • pg_lo_tell — Zwraca wskaźnik położenia w wielkim obiekcie (Large Object - LO)
  • pg_lo_unlink — Usuwa wielki obiekt (Large Object - LO)
  • pg_lo_write — Zapisuje do wielkiego obiektu (Large Object - LO)
  • pg_meta_data — Pobiera informacje o tabeli
  • pg_num_fields — Zwraca liczbę kolumn
  • pg_num_rows — Zwraca liczbę wierszy
  • pg_options — Podaje opcje powiązane z połączenim
  • pg_parameter_status — Looks up a current parameter setting of the server.
  • pg_pconnect — Otwiera trwałe połączenie z serwerem PostgreSQL
  • pg_ping — Ping database connection
  • pg_port — Zwraca numer portu związany z połączeniem
  • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_put_line — Wysyła łańcuch zakończony znakiem NULL do serwera PostgreSQL
  • pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_query — Realizujezapytanie do bazy danych
  • pg_result_error_field — Returns an individual field of an error report.
  • pg_result_error — Zwraca błąd związany z identyfikatorem wyniku
  • pg_result_seek — Set internal row offset in result resource
  • pg_result_status — Zwraca stan wyniku zapytania
  • pg_select — Wybiera wiersze
  • pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
  • pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).
  • pg_send_query — Wysyła zapytanie asynchroniczne
  • pg_set_client_encoding — Ustawia stronę kodową klienta PostgreSQL-a
  • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error.
  • pg_trace — Uruchamia śledzenie połączeń z PostgreSQL
  • pg_transaction_status — Returns the current in-transaction status of the server.
  • pg_tty — Zwraca nazwę konsoli tty związanej z połączeniem
  • pg_unescape_bytea — Unescape binary for bytea type
  • pg_untrace — Wyłącza śledzenie połączeń PostgreSQL-a
  • pg_update — Aktualizuje tabelę
  • pg_version — Returns an array with client, protocol and server version (when available)
Podstawowe użycie
pg_affected_rows
PostgreSQL


Zwraca liczbę zmodyfikowanych wierszy

Funkcje PostgreSQL
pg_cancel_query
Funkcje PostgreSQL
PHP Manual

pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_affected_rows — Zwraca liczbę zmodyfikowanych wierszy

Opis

int pg_affected_rows ( resource $result )

pg_affected_rows() zwraca liczbę wierszy dodanych, zmodyfikowanych lub usuniętych przez zapytania INSERT, UPDATE i DELETE.

Informacja:

Ta funkcja była nazwana pg_cmdtuples().

Parametry

result

Zasób, wynik zapytania PostgreSQL, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (wśród innych).

Zwracane wartości

Liczba wierszy na które wpływ ma zapytanie. Jeśli nie wystąpił taki wiersz, zostanie zwrócone 0.

Przykłady

Przykład #1 pg_affected_rows() przykład

<?php
     $result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");
     $cmdtuples = pg_affected_rows ($result);
     echo $cmdtuples . " wiersz(e), na które miało wpływ zapytanie.\n";
?>

Powyższy przykład wyświetli:

1 wiersz(e), na które miało wpływ zapytanie.

Zobacz też:

  • pg_query() - Realizujezapytanie do bazy danych
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_num_rows() - Zwraca liczbę wierszy

Funkcje PostgreSQL
pg_cancel_query
Funkcje PostgreSQL


Przerywa zapytanie asynchroniczne

pg_affected_rows
pg_client_encoding
Funkcje PostgreSQL
PHP Manual

pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5)

pg_cancel_query — Przerywa zapytanie asynchroniczne

Opis

bool pg_cancel_query ( resource $połączenie )

pg_cancel_query() przerywa zapytanie asynchroniczne wysłane przez pg_send_query(), pg_send_query_params() lub pg_send_execute(). Nie można przerwać zapytania uruchomionego przez pg_query().

Parametry

połączenie

Zasób, połączenie do bazy PostgreSQL.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_cancel_query() przykład

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Nie można połączyć się");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
  }

  $res1 = pg_get_result($dbconn);
  echo "Pierwsze wywołanie pg_get_result(): $res1\n";
  $rows1 = pg_num_rows($res1);
  echo "$res1 ma $rows1 rekordów\n\n";

  // Anuluj obecnie działające zapytanie.  Będzie to drugie zapytanie, jeśli się
  // jeszcze wykonuje.
  pg_cancel_query($dbconn);
?>

Powyższy przykład wyświetli:

Pierwsze wywołanie pg_get_result(): Resource id #3
Resource id #3 ma 3 rekordów

Zobacz też:

  • pg_send_query() - Wysyła zapytanie asynchroniczne
  • pg_connection_busy() - Sprawdza czy połączenie jest zajęte czy wolne

pg_affected_rows
pg_client_encoding
Funkcje PostgreSQL


Zwraca stronę kodową klienta

pg_cancel_query
pg_close
Funkcje PostgreSQL
PHP Manual

pg_client_encoding

(PHP 4 >= 4.0.3, PHP 5)

pg_client_encoding — Zwraca stronę kodową klienta

Opis

string pg_client_encoding ([ resource $połączenie ] )

PostgreSQL wspiera automatyczną konwersję zestawu znaków pomiędzy serwerem, a klientem dla pewnych systemów kodowania. pg_client_encoding() zwraca stronę kodową klienta jako łańcuch. Zwracany łańcuch będzie jednym ze standardowych identyfikatorów kodowania PostgreSQL.

Informacja:

Ta funkcja wymaga PHP 4.0.3 lub nowszego i PostgreSQL 7.0 lub nowszego. Jeśli libpq jest skompilowane bez wsparcia dla kodowania wielobajtowego, pg_client_encoding() zawsze zwraca SQL_ASCII. Wspierane strony kodowe zależą od wersji PostgreSQL. Sprawdź dokumentację PostgreSQL o wspieranych kodowaniach.

Ta funkcja była poprzednio nazywana pg_clientencoding().

Parametry

połączenie

Zasób, połączenie do bazy PostgreSQL. Kiedy parametr połączenie nie jest podany, użyte zostanie domyślne połączenie. Domyślne połączenie to ostatnie połączenie utworzone przez pg_connect() lub pg_pconnect().

Zwracane wartości

Kodowanie klienta, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_client_encoding() przykład

<?php
// Zakładamy, że $conn jest połączeniem do bazy w ISO-8859-1
$encoding = pg_client_encoding($conn);

echo "Kodowanie klienta to: ", $encoding, "\n";
?>

Powyższy przykład wyświetli:

Kodowanie klienta to: ISO-8859-1

Zobacz też:

  • pg_set_client_encoding() - Ustawia stronę kodową klienta PostgreSQL-a

pg_cancel_query
pg_close
Funkcje PostgreSQL


Zamyka połączenie z PostgreSQL

pg_client_encoding
pg_connect
Funkcje PostgreSQL
PHP Manual

pg_close

(PHP 4, PHP 5)

pg_close — Zamyka połączenie z PostgreSQL

Opis

bool pg_close ([ resource $połączenie ] )

pg_close() zamyka tymczasowe połączenie z serwerem PostgreSQL związane z podanym parametrem połączenie.

Informacja:

Używanie pg_close() jest z reguły niepotrzebne, jako że połączenia tymczasowe są zamykane automatycznie po zakończeniu wykonywania skryptu.

Nie wolno zamykać połączenia jeśli jest otwarty wielki obiekt. W pierwszej kolejności należy zamknąć wszystkie wielkie obiekty.

Parametry

połączenie

Zasób, połączenie do bazy PostgreSQL. Kiedy parametr połączenie nie jest podany, użyte zostanie domyślne połączenie. Domyślne połączenie to ostatnie połączenie utworzone przez pg_connect() lub pg_pconnect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_close() przykład

<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
   or die("Nie można się połączyć");
echo "Poprawnie połączono";
pg_close($dbconn);
?>

Powyższy przykład wyświetli:

Poprawnie połączono

Zobacz też:

  • pg_connect() - Otwiera tymczasowe połączenie do PostgreSQL-a

pg_client_encoding
pg_connect
Funkcje PostgreSQL


Otwiera tymczasowe połączenie do PostgreSQL-a

pg_close
pg_connection_busy
Funkcje PostgreSQL
PHP Manual

pg_connect

(PHP 4, PHP 5)

pg_connect — Otwiera tymczasowe połączenie do PostgreSQL-a

Opis

resource pg_connect ( string $łąńcuch_połączenia [, int $typ_połączenia ] )

pg_connect() Otwiera tymczasowe połączenie do serwera PostgreSQL określonego przez łąńcuch_połączenia.

Jeśli funkcja pg_connect() zostanie wywołana drugi raz z tym samym łąńcuchem_połączenia jak istniejące połączenie, zostanie zwrócony identyfikator istniejącego połączenia chyba, że podasz PGSQL_CONNECT_FORCE_NEW jako typ_połączenia.

Stara składnia z wieloma parametrami $conn = pg_connect("host", "port", "opcje", "tty", "nazwa_bazy") jest przestarzała.

Parametry

łąńcuch_połączenia

łąńcuch_połączenia może być pusty, użyte zostaą wszystkie domyślne parametry lub może zawierać jeden lub więcej parametrów ustawień oddzielonych przez biały znak. Każdy parametr ustawień jest w postaci słowo_kluczowe = wartość. Odstępy wokół znaku równości są opcjonalne. Aby zapisać pustą wartość lub wartość zawierającą spacje, należy otoczyć ją przez pojedynczy cudzysłów, np. słowo_kluczowe = 'ta wartość'. Pojedyncze cudzysłowy i lewe ukośniki w wartości musza być poprzedzone znakiem unikowym (lewym ukośnikiem) tj. \' i \\

Obecnie rozpoznwane parametry słów kluczowych to: host, hostaddr, port, dbname, user, password, connect_timeout, options, tty (ignorowany), sslmode, requiressl (przestarzały na rzecz sslmode) i service. Które z tych parametrów istnieją zależy od Twojej wersji PostgreSQL.

typ_połączenia

Jeśli jest podany PGSQL_CONNECT_FORCE_NEW, wtedy nowe połączenie jest tworzone, nawet jeśli łąńcuch_połączenia jest identyczny z istniejącym połączeniem.

Zwracane wartości

Zasób, połączenie do bazy PostgreSQL w przypadku powodzenia, lub FALSE gdy zawiedzie.

Przykłady

Przykład #1 Używanie pg_connect

<?php
$dbconn = pg_connect ("dbname=mary");
//Otwiera połączenie z bazą "mary"

$dbconn2 = pg_connect ("host=localhost port=5432 dbname=mary");
//Otwiera połączenie z bazą "mary" na komputerze "localhost" przez port "5432"

$dbconn3 = pg_connect ("host=sheep port=5432 dbname=mary user=lamb password=foo");
//Otwiera połączenie z bazą "mary" na komputerze "sheep" z użyciem nazwy użytkownika i hasła

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect ($conn_string);
//Otwiera połączenie z bazą "test" na komputerze "sheep" z użyciem nazwy użytkownika i hasła
?>

Zobacz też:

  • pg_pconnect() - Otwiera trwałe połączenie z serwerem PostgreSQL
  • pg_close() - Zamyka połączenie z PostgreSQL
  • pg_host() - Zwraca nazwę komputera związanego z połączeniem
  • pg_port() - Zwraca numer portu związany z połączeniem
  • pg_tty() - Zwraca nazwę konsoli tty związanej z połączeniem
  • pg_options() - Podaje opcje powiązane z połączenim
  • pg_dbname() - Podaje nazwę bazy danych

pg_close
pg_connection_busy
Funkcje PostgreSQL


Sprawdza czy połączenie jest zajęte czy wolne

pg_connect
pg_connection_reset
Funkcje PostgreSQL
PHP Manual

pg_connection_busy

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_busy — Sprawdza czy połączenie jest zajęte czy wolne

Opis

bool pg_connection_busy ( resource $połączenie )

pg_connection_busy() sprawdza czy połączenie jest zajęte. Jeśli jest zajęte, poprzednie zapytanie jest wciąż wykonywane. Jeśli pg_get_result() jest użyte na połączeniu, zostanie ono zablokowane.

Parametry

połączenie

Zasób, połączenie do bazy PostgreSQL.

Zwracane wartości

Zwraca TRUE jeśli połączenie jest zajęte, FALSE w przeciwnym wypadku.

Przykłady

Przykład #1 pg_connection_busy() przykład

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Nie można się połączyć");
  $bs = pg_connection_busy($dbconn);
  if ($bs) {
      echo 'połączenie jest zajęte';
  } else {
     echo 'połączenie jest wolne';
  }
?>

Zobacz też:

  • pg_connection_status() - Zwraca stan połączenia
  • pg_get_result() - Pobiera wynik zapytania asynchroniczego

pg_connect
pg_connection_reset
Funkcje PostgreSQL


Restartuje połączenie

pg_connection_busy
pg_connection_status
Funkcje PostgreSQL
PHP Manual

pg_connection_reset

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_reset — Restartuje połączenie

Opis

bool pg_connection_reset ( resource $połączenie )

pg_connection_reset() restartuje połączenie. Jest użyteczne w sytuacja awaryjnych.

Parametry

połączenie

Zasób, połączenie do bazy PostgreSQL.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_connection_reset() przykład

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Nie można się połączyć");
  $dbconn2 = pg_connection_reset($dbconn);
  if ($dbconn2) {
      echo "restart poprawny\n";
  } else {
      echo "restart nie powiódł się\n";
  }
?>

Zobacz też:

  • pg_connect() - Otwiera tymczasowe połączenie do PostgreSQL-a
  • pg_pconnect() - Otwiera trwałe połączenie z serwerem PostgreSQL
  • pg_connection_status() - Zwraca stan połączenia

pg_connection_busy
pg_connection_status
Funkcje PostgreSQL


Zwraca stan połączenia

pg_connection_reset
pg_convert
Funkcje PostgreSQL
PHP Manual

pg_connection_status

(PHP 4 >= 4.2.0, PHP 5)

pg_connection_status — Zwraca stan połączenia

Opis

int pg_connection_status ( resource $połączenie )

pg_connection_status() zwraca status podanego połączenia.

Parametry

połączenie

Zasób, połączenie do bazy PostgreSQL.

Zwracane wartości

PGSQL_CONNECTION_OK lub PGSQL_CONNECTION_BAD.

Przykłady

Przykład #1 pg_connection_status() przykład

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Nie można się połączyć");
  $stat = pg_connection_status($dbconn);
  if ($stat === PGSQL_CONNECTION_OK) {
      echo 'Status połączenia ok';
  } else {
      echo 'Status połączenia bad';
  }
?>

Zobacz też:

  • pg_connection_busy() - Sprawdza czy połączenie jest zajęte czy wolne

pg_connection_reset
pg_convert
Funkcje PostgreSQL


Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.

pg_connection_status
pg_copy_from
Funkcje PostgreSQL
PHP Manual

pg_convert

(PHP 4 >= 4.3.0, PHP 5)

pg_convert — Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.

Opis

array pg_convert ( resource $połączenie , string $nazwa_tabeli , array $tablica_asocjacyjna [, int $opcje ] )

pg_convert() sprawdza i konwertuje wartości w tablica_asocjacyjna na postać użyteczną dla zapytania SQL. Warunkiem koniecznym dla pg_convert() jest istnienie tabeli nazwa_tabeli, ktora ma przynajmniej tyle kolumn, ile tablica_asocjacyjna ma elementów. Nazwy pól w nazwa_tabeli muszą pasować do indeksów w parametrze tablica_asocjacyjna i odpowiednie typy danych muszą być zgodne. Zwraca tabelę z przekonwertowanymi wartościami w razie sukcesu, FALSE w przeciwnym wypadku.

Informacja:

Jeśli istnieją pola typu boolean w nazwa_tabeli, nie używaj stałej wartości TRUE w parametrze tablica_asocjacyjna. Zostanie on przekonwertowany do łańcucha 'TRUE', który nie jest poprawnym wpisem dla pól typu boolean w PostgreSQL. W zamian użyj jednej z propozycji: t, true, 1, y, yes.

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

połączenie

Źródło połączenia do bazy PostgreSQL.

nazwa_tabeli

Nazwa tabeli, w stosunku do której będą konwertowane typy.

tablica_asocjacyjna

Dane do konwersji.

options

Kombinacja dowolnej ilości poniższych stałych: PGSQL_CONV_IGNORE_DEFAULT, PGSQL_CONV_FORCE_NULL lub PGSQL_CONV_IGNORE_NOT_NULL.

Zwracane wartości

Typ tablicowy (ang. array) z przekonwertowanymi wartościami, lub FALSE w razie błędu.

Przykłady

Przykład #1 pg_convert() - przykład

<?php
  $polaczenie = pg_connect('dbname=foo');

  $tmp = array(
      'autor' => 'Jan Hakreski',
      'rok' => 2005,
      'tytuł' => 'Życie Jana Hakerskiego'
  );

  $wartosci = pg_convert($polaczenie, 'autorzy', $tmp);
?>

Zobacz też:

  • pg_meta_data() - Pobiera informacje o tabeli

pg_connection_status
pg_copy_from
Funkcje PostgreSQL


Wstawia wiersze do tabeli z tablicy

pg_convert
pg_copy_to
Funkcje PostgreSQL
PHP Manual

pg_copy_from

(PHP 4 >= 4.2.0, PHP 5)

pg_copy_from — Wstawia wiersze do tabeli z tablicy

Opis

bool pg_copy_from ( resource $połączenie , string $nazwa_tabeli , array $wiersze [, string $delimiter [, string $null_jako ]] )

pg_copy_from() wstawia wiersze do tabeli z tablicy wiersze. Wywołuje wewnętrznie polecenie SQL COPY FROM aby wstawić wiersze. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Parametry

połączenie

Zasób, połączenie do bazy danych PostgreSQL.

nazwa_tabeli

Nazwa tabeli do której będą kopiowane wiersze.

wiersze

Tablica danych, które będą skopiowane do nazwa_tabeli. Każda wartość w wiersze stanie się wierszem w nazwa_tabeli. Każda wartość w wiersze powinna być łańcuchem znaków rozdzielonych wartości do wstawienia w każde pole. Wartości powinny być zakończone przejściem do nowej linii.

delimiter

Symbol jaki rozdziela wartości dla każdego pola w każdym elemencie wiersza. Domyślnie jest to TAB.

null_jako

Jak wartość SQL NULL jest reprezentowana w wierszu. Domyślnie jest to \N ("\\N").

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_copy_from() przykład

<?php
   $db = pg_connect("dbname=publisher") or die("Nie można się połączyć");

   $rows = pg_copy_to($db, $table_name);

   pg_query($db, "DELETE FROM $table_name");

   pg_copy_from($db, $table_name, $rows);
?>

Zobacz też:

  • pg_copy_to() - Kopiuje tabelę do tablicy

pg_convert
pg_copy_to
Funkcje PostgreSQL


Kopiuje tabelę do tablicy

pg_copy_from
pg_dbname
Funkcje PostgreSQL
PHP Manual

pg_copy_to

(PHP 4 >= 4.2.0, PHP 5)

pg_copy_to — Kopiuje tabelę do tablicy

Opis

array pg_copy_to ( resource $polaczenie , string $nazwa_tabeli [, string $separator [, string $null_jako ]] )

pg_copy_to() kopiuje tabelę do tablicy. Wywołuje to wewnętrzne polecenie SQL COPY TO na wydobywane rekordy.

Parametry

polaczenie

Identyfikator połączenia do serwera PostgreSQL.

nazwa_tabeli

Nazwa tabeli, z której zostaną skopiowane dane do zmiennej wiersze.

separator

Znak oddzielający wartości dla każdego pola każdego elementu zmiennej wiersze. Domyślnie jest to TAB.

null_jako

Jak wartości NULL z SQL są przedstawiane w zmiennej wiersze. Domyślnie jest to \N ("\\N").

Zwracane wartości

Tablica (ang. array) z jednym elementem dla każdej linii kopiowanych (COPY) danych. Zwraca FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_copy_to() - przykład

<?php
   $baza = pg_connect("dbname=wydawca") or die("Nie można się połączyć");

   $wiersze = pg_copy_to($baza, $nazwa_tabeli);

   pg_query($baza, "DELETE FROM $nazwa_tabeli");

   pg_copy_from($baza, $nazwa_tabeli, $wiersze);
?>

Zobacz też:

  • pg_copy_from() - Wstawia wiersze do tabeli z tablicy

pg_copy_from
pg_dbname
Funkcje PostgreSQL


Podaje nazwę bazy danych

pg_copy_to
pg_delete
Funkcje PostgreSQL
PHP Manual

pg_dbname

(PHP 4, PHP 5)

pg_dbname — Podaje nazwę bazy danych

Opis

string pg_dbname ([ resource $polaczenie ] )

pg_dbname() zwraca nazwę bazy danych dla podanego identyfikatora połączenia (polaczenie).

Parametry

polaczenie

Identyfikator połączenia do bazy PostgreSQL. Gdy nie podano parametru polaczenie, domyślne połączenie jest użyte. Domyślnym połączeniem jest ostatnie połączenie stworzone przez pg_connect() lub pg_pconnect().

Zwracane wartości

Łańcuch (ang. string) zawierający nazwę bazy danych, do której polaczenie jest nawiązane, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_dbname() - przykład

<?php
  error_reporting(E_ALL);

  pg_connect("host=localhost port=5432 dbname=mary");
  echo pg_dbname(); // mary
?>

pg_copy_to
pg_delete
Funkcje PostgreSQL


Usuwa rekordy

pg_dbname
pg_end_copy
Funkcje PostgreSQL
PHP Manual

pg_delete

(PHP 4 >= 4.3.0, PHP 5)

pg_delete — Usuwa rekordy

Opis

mixed pg_delete ( resource $identyfikator_połączenia , string $nazwa_tabeli , array $tablica_asocjacyjna [, int $opcje ] )

pg_delete() usuwa wiersze z tabeli określonej przez klucze i wartości w parametrze tablica_asocjacyjna. Jeśli opcje zostały określone, to funkcja pg_convert() stosuje do parametru tablica_asocjacyjna podane opcje.

Parametry

identyfikator_połączenia

Identyfikator połączenia do bazy PostgreSQL.

nazwa_tabeli

Nazwa tabeli, z której będą usuwane wiersze.

tablica_asocjacyjna

Tablica (ang. array), której klucze są nazwami pól w określonej parametrem nazwa_tabeli tabeli, oraz której wartościami, są wartości tych pól, które mają zostać usunięte.

opcje

Dowolna kombinacja, dowolnej ilości parametrów: PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC oraz PGSQL_DML_STRING. Jeśli PGSQL_DML_STRING jest jedną z podanych w parametrze opcje opcji, zostanie zwrócony łańcuch zapytania z URL (ang. query string).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Zwraca łańcuch (ang. string) gdy podano PGSQL_DML_STRING poprzez opcje.

Przykłady

Przykład #1 pg_delete() - przykład

<?php
  $polaczenie_do_bazy = pg_connect ('dbname=foo');
  // To jest bezpieczne, odkąd $_POST jest konwertowane automatycznie
  $res = pg_delete($polaczenie_do_bazy, 'kopia_post', $_POST);
  if ($res) {
      echo "Dane określone przez POST zostały usunięte: $res\n";
  } else {
      echo "Użytkownik wprowadził błędne dane\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.

Zobacz też:

  • pg_convert() - Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.

pg_dbname
pg_end_copy
Funkcje PostgreSQL


Synchronizuje klienta z serwerem PostgreSQL.

pg_delete
pg_escape_bytea
Funkcje PostgreSQL
PHP Manual

pg_end_copy

(PHP 4 >= 4.0.3, PHP 5)

pg_end_copy — Synchronizuje klienta z serwerem PostgreSQL.

Opis

bool pg_end_copy ([ resource $polaczenie ] )

pg_end_copy() synchronizuje klienta PostgreSQL z serwerem po wykonaniu operacji kopiowania przez funkcję pg_put_line(). Funkcja pg_end_copy() musi być wywołana, inaczej serwer PostgreSQL-a może być niezsychronizowany z klientem i może wystąpić błąd.

Parametry

polaczenie

Identyfikator połączenia do bazy danych PostgreSQL. Gdy polaczenie nie zostało podane, domyślne połączenie jest użyte. Domyślnym połączeniem jest ostatnie połączenie stworzone przez pg_connect() lub pg_pconnect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_end_copy() - przykład

<?php
  $polaczenie = pg_pconnect("dbname=foo");
  pg_query($polaczenie, "create table bar (a int4, b char(16), d float8)");
  pg_query($polaczenie, "copy bar from stdin");
  pg_put_line($polaczenie, "3\twitaj świecie\t4.5\n");
  pg_put_line($polaczenie, "4\tżegnaj świecie\t7.11\n");
  pg_put_line($polaczenie, "\\.\n");
  pg_end_copy($polaczenie);
?>

Zobacz też:

  • pg_put_line() - Wysyła łańcuch zakończony znakiem NULL do serwera PostgreSQL

pg_delete
pg_escape_bytea
Funkcje PostgreSQL


Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea

pg_end_copy
pg_escape_identifier
Funkcje PostgreSQL
PHP Manual

pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_bytea — Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea

Opis

string pg_escape_bytea ([ resource $połączenie ], string $dane )

pg_escape_bytea() konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea. Zwraca łańcuch z sekwencjami Escape.

Informacja:

Przy wywołaniu SELECT dla typu bytea, PostgrSQL zwraca łańcuchy zawierające wartości ósemkowe poprzedzone znakiem "\" (np. \032). Użytkownicy muszą samodzielnie odkodować te dane.

Ta funkcja wymaga PostgreSQL 7.2 lub nowszego. Dla PostgreSQL 7.2.0 i 7.2.1, wartości bytea muszą być wskazane jeśli uruchomisz wsparcie dla kodowania wielobajtowego np. INSERT INTO tabela_testowa (obraz) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 i nowszy nie potrzebuje wskazania typu. Wyjątkiem jest przypadek kiedy klient i serwer posługują się różnymi stronami kodowymi. W takim przypadku może wystąpić błąd (ang. multi-byte stream error). Użytkownik musi wtedy wskazać typ bytea, by uniknąć tego błędu.

Parametry

połączenie

Identyfikator połączenia do bazy danych PostgreSQL. Kiedy połączenie nie został podany, domyślne połączenie zostaje użyte. Domyślnym połączeniem jest ostatnie połączenie stworzone przez pg_connect() lub pg_pconnect().

dane

Łańcuch (ang. string) zawierający tekst lub binarne dane wstawiane do kolumny bytea.

Zwracane wartości

Łańcuch (ang. string) zawierający dane z sekwencjami Escape..

Rejestr zmian

Wersja | Opis
5.2.0 | Parametr połączenie został dodany

Przykłady

Przykład #1 pg_escape_bytea() - przykład

<?php
  // Połącz z bazą
  $połączenie = pg_connect('dbname=foo');

  // Przeczytaj z binarnego pliku
  $dane = file_get_contents('obrazek1.jpg');

  // Poprzedź sekwencjami Escape dane binarne
  $escaped = pg_escape_bytea($dane);

  // Wpisz to do bazy danych
  pg_query("INSERT INTO galeria (nazwa, dane) VALUES ('Drzewa sosnowe', '{$escaped}')");
?>

Zobacz też:

  • pg_unescape_bytea() - Unescape binary for bytea type
  • pg_escape_string() - Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape

pg_end_copy
pg_escape_identifier
Funkcje PostgreSQL


Escape a identifier for insertion into a text field

pg_escape_bytea
pg_escape_literal
Funkcje PostgreSQL
PHP Manual

pg_escape_identifier

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

pg_escape_identifier — Escape a identifier for insertion into a text field

Opis

string pg_escape_identifier ([ resource $connection ], string $data )

pg_escape_identifier() escapes a identifier (e.g. table, field names) for quering the database. It returns an escaped identifier string for PostgreSQL server. pg_escape_identifier() adds double quotes before and after data. Users should not add double quotes. Use of this function is recommended for identifier parameters in query. For SQL literals (i.e. parameters except bytea), pg_escape_literal() or pg_escape_string() muse be used. For bytea type fields, pg_escape_bytea() must be used instead.

Informacja:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text to be escaped.

Zwracane wartości

A string containing the escaped data.

Przykłady

Przykład #1 pg_escape_identifier() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Escape the table name data
  $escaped = pg_escape_identifier($table_name);

  // Select rows from $table_name
  pg_query("SELECT * FROM {$escaped};");
?>

Zobacz też:

  • pg_escape_literal() - Escape a literal for insertion into a text field
  • pg_escape_bytea() - Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea
  • pg_escape_string() - Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape

pg_escape_bytea
pg_escape_literal
Funkcje PostgreSQL


Escape a literal for insertion into a text field

pg_escape_identifier
pg_escape_string
Funkcje PostgreSQL
PHP Manual

pg_escape_literal

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

pg_escape_literal — Escape a literal for insertion into a text field

Opis

string pg_escape_literal ([ resource $connection ], string $data )

pg_escape_literal() escapes a literal for querying the PostgreSQL database. It returns an escaped literal in the PostgreSQL format. pg_escape_literal() adds quotes before and after data. Users should not add quotes. Use of this function is recommended instead of pg_escape_string(). If the type of the column is bytea, pg_escape_bytea() must be used instead. For escaping identifiers (e.g. table, field names), pg_escape_identifier() must be used.

Informacja:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text to be escaped.

Zwracane wartości

A string containing the escaped data.

Przykłady

Przykład #1 pg_escape_literal() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Read in a text file (containing apostrophes and backslashes)
  $data = file_get_contents('letter.txt');

  // Escape the text data
  $escaped = pg_escape_literal($data);

  // Insert it into the database. Note that no quotes around {$escaped}
  pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', {$escaped})");
?>

Zobacz też:

  • pg_escape_identifier() - Escape a identifier for insertion into a text field
  • pg_escape_bytea() - Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea
  • pg_escape_string() - Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape

pg_escape_identifier
pg_escape_string
Funkcje PostgreSQL


Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape

pg_escape_literal
pg_execute
Funkcje PostgreSQL
PHP Manual

pg_escape_string

(PHP 4 >= 4.2.0, PHP 5)

pg_escape_string — Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape

Opis

string pg_escape_string ([ resource $polaczenie ], string $dane )

pg_escape_string() konwertuje łańcuch wstawiając sekwencje Escape przy wpisywaniu do bazy danych. Zwraca łańcuch z sekwencjami Escape w formacie PostgreSQL-a. Zalecane jest używanie tej funkcji w miejsce addslashes(). Jeśli typem kolumny jest bytea, trzeba użyć funkcji pg_escape_bytea() zamiast tej.

Informacja:

Funkcja wymaga PostgreSQL 7.2 lub nowszego.

Parametry

polaczenie

Identyfikator połączenia do bazy danych. Gdy polaczenie nie zostało podane, domyślne połączenie jest użyte. Domyślnym połączeniem jest ostatnie połączenie stworzone przez pg_connect() lub pg_pconnect().

dane

Łańcuch (ang. string) zawierający tekst bez sekwencji Escape.

Zwracane wartości

Łańcuch (ang. string) zawierający dane z sekwencjami Escape.

Rejestr zmian

Wersja | Opis
5.2.0 | Parametr polaczenie został dodany

Przykłady

Przykład #1 pg_escape_string() - przykład

<?php
  // Połączenie do bazy danych
  $polaczenie = pg_connect('dbname=foo');

  // Przeczytaj plik tekstowy (zawierający apostrofy i ukośniki wsteczne)
  $dane = file_get_contents('list.txt');

  // Dodaj sekwencje Escape do danych
  $z_escape = pg_escape_string($dane);

  // Wpisz to do bazy danych
  pg_query("INSERT INTO korespondencja (nazwa, dane) VALUES ('Moj list', '{$z_escape}')");
?>

Zobacz też:

  • pg_escape_bytea() - Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea

pg_escape_literal
pg_execute
Funkcje PostgreSQL


Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_escape_string
pg_fetch_all_columns
Funkcje PostgreSQL
PHP Manual

pg_execute

(PHP 5 >= 5.1.0)

pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result.

Opis

resource pg_execute ([ resource $connection ], string $stmtname , array $params )

Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Ostrzeżenie

Elements are converted to strings by calling this function.

Zwracane wartości

A query result resource on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Using pg_execute()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

Zobacz też:

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_escape_string
pg_fetch_all_columns
Funkcje PostgreSQL


Fetches all rows in a particular result column as an array

pg_execute
pg_fetch_all
Funkcje PostgreSQL
PHP Manual

pg_fetch_all_columns

(PHP 5 >= 5.1.0)

pg_fetch_all_columns — Fetches all rows in a particular result column as an array

Opis

array pg_fetch_all_columns ( resource $result [, int $column = 0 ] )

pg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the result resource.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Parametry

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

column

Column number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.

Zwracane wartości

An array with all values in the result column.

FALSE is returned if column is larger than the number of columns in the result, or on any other error.

Przykłady

Przykład #1 pg_fetch_all_columns() example

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);

var_dump($arr);

?>

Zobacz też:

  • pg_fetch_all() - Fetches all rows from a result as an array

pg_execute
pg_fetch_all
Funkcje PostgreSQL


Fetches all rows from a result as an array

pg_fetch_all_columns
pg_fetch_array
Funkcje PostgreSQL
PHP Manual

pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5)

pg_fetch_all — Fetches all rows from a result as an array

Opis

array pg_fetch_all ( resource $result )

pg_fetch_all() returns an array that contains all rows (records) in the result resource.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Parametry

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Zwracane wartości

An array with all rows in the result. Each row is an array of field values indexed by field name.

FALSE is returned if there are no rows in the result, or on any other error.

Przykłady

Przykład #1 PostgreSQL fetch all

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
    echo "An error occured.\n";
    exit;
}

$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
    echo "An error occured.\n";
    exit;
}

$arr = pg_fetch_all($result);

print_r($arr);

?>

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

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Fred
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
        )

)

Zobacz też:

  • pg_fetch_row() - Pobiera wiersz jako tablicę z indeksami numerycznymi
  • pg_fetch_array() - Pobiera wiersz jako tablicę
  • pg_fetch_object() - Pobiera wiersz jako obiekt
  • pg_fetch_result() - Pobiera dane z wyniku

pg_fetch_all_columns
pg_fetch_array
Funkcje PostgreSQL


Pobiera wiersz jako tablicę

pg_fetch_all
pg_fetch_assoc
Funkcje PostgreSQL
PHP Manual

pg_fetch_array

(PHP 4, PHP 5)

pg_fetch_array — Pobiera wiersz jako tablicę

Opis

array pg_fetch_array ( resource $wynik [, int $wiersz [, int $typ_wyniku = PGSQL_BOTH ]] )

pg_fetch_array() zwraca tablicę zawierającą dane z pobranego wiersza (rekordu).

pg_fetch_array() jest rozszerzeną wersją pg_fetch_row(). Oprócz zapisywania danych w tablicy wyników indeksowanej numerycznie, zapisuje je też używając indeksów przyporządkowujących (asocjacyjnych) tej tablicy, nazwy kolumn traktując jako klucze. Domyślnie zapisywane są oba rodzaje indeksów.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

pg_fetch_array() NIE jest znacznie wolniejsze, niż używanie pg_fetch_row(), oraz jest zdecydowanie łatwiejsze do użycia.

Parametry

wynik

Identyfikator wyniku zapytania PostgreSQL, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

wiersz

Numer wiersza w wyniku do pobrania. Wiersze są numerowane od zera w górę. Jeśli jest pominięty albo wynosi NULL, pobrany zostanie kolejny wiersz.

typ_wyniku

Opcjonalny parametr kontrolujący w jaki sposób zwrócona tablica (ang. array) jest indeksowana. typ_wyniku jest stałą i może przyjąć następujące wartości: PGSQL_ASSOC, PGSQL_NUM oraz PGSQL_BOTH. Używając PGSQL_NUM, pg_fetch_array() zwróci tablicę z indeksami numerycznymi, użycie PGSQL_ASSOC zwróci wyłącznie indeksy asocjacyjne podczas, gdy PGSQL_BOTH, wartość domyślna, zwróci oba rodzaje indeksów - numeryczne i asocjacyjne.

Zwracane wartości

Tablica (ang. array) indeksowana numerycznie (zaczynając od zera) lub asocjacyjnie (indeksowana przez nazwy kolumn), lub tak i tak. Każda wartość w tablicy (ang. array) jest przedstawiona jako łańcuch (ang. string). Wartości NULL z bazy danych są zwracane jako NULL.

FALSE zostanie zwrócone jeśli wiersz przekracza ilość wierszy w całym zbiorze, nie ma więcej wierszy, lub dowolnym innym błędzie.

Rejestr zmian

Wersja | Opis
4.1.0 | Parametr wiersz stał się opcjonalnym.

Przykłady

Przykład #1 pg_fetch_array() - przykład

<?php

$polaczenie_z_baza = pg_pconnect("dbname=wydawca");
if (!$polaczenie_z_baza) {
  echo "Wystąpił błąd.\n";
  exit;
}

$wynik = pg_query($polaczenie_z_baza, "SELECT autor, email FROM autorzy");
if (!$wynik) {
  echo "Wystąpił błąd.\n";
  exit;
}

$tab = pg_fetch_array($wynik, 0, PGSQL_NUM);
echo $tab[0] . " <- Wiersz 1 Autor\n";
echo $tab[1] . " <- Wiersz 1 E-mail\n";

// Jako, że w PHP 4.1.0, parametr wiersz jest opcjonalny; można podać w zamian NULL,
// by podać typ_wyniku.  Kolejne wywołanie funkcji pg_fetch_array zwróci
// następny wiersz.
$tab = pg_fetch_array ($wynik, 1, PGSQL_ASSOC);
echo $tab["autor"] . " <- Wiersz 2 Autor\n";
echo $tab["email"] . " <- Wiersz 2 E-mail\n";

$tab = pg_fetch_array($wynik);
echo $tab["autor"] . " <- Wiersz 3 Autor\n";
echo $tab[1] . " <- Wiersz 3 E-mail\n";

?>

Zobacz też:

  • pg_fetch_row() - Pobiera wiersz jako tablicę z indeksami numerycznymi
  • pg_fetch_object() - Pobiera wiersz jako obiekt
  • pg_fetch_result() - Pobiera dane z wyniku

pg_fetch_all
pg_fetch_assoc
Funkcje PostgreSQL


Fetch a row as an associative array

pg_fetch_array
pg_fetch_object
Funkcje PostgreSQL
PHP Manual

pg_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

pg_fetch_assoc — Fetch a row as an associative array

Opis

array pg_fetch_assoc ( resource $result [, int $row ] )

pg_fetch_assoc() returns an associative array that corresponds to the fetched row (records).

pg_fetch_assoc() is equivalent to calling pg_fetch_array() with PGSQL_ASSOC as the optional third parameter. It only returns an associative array. If you need the numeric indices, use pg_fetch_row().

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), and is significantly easier to use.

Parametry

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

row

Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or NULL, the next row is fetched.

Zwracane wartości

An array indexed associatively (by field name). Each value in the array is represented as a string. Database NULL values are returned as NULL.

FALSE is returned if row exceeds the number of rows in the set, there are no more rows, or on any other error.

Rejestr zmian

Wersja | Opis
4.1.0 | The parameter row became optional.

Przykłady

Przykład #1 pg_fetch_assoc() example

<?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

while ($row = pg_fetch_assoc($result)) {
  echo $row['id'];
  echo $row['author'];
  echo $row['email'];
}
?>

Zobacz też:

  • pg_fetch_row() - Pobiera wiersz jako tablicę z indeksami numerycznymi
  • pg_fetch_array() - Pobiera wiersz jako tablicę
  • pg_fetch_object() - Pobiera wiersz jako obiekt
  • pg_fetch_result() - Pobiera dane z wyniku

pg_fetch_array
pg_fetch_object
Funkcje PostgreSQL


Pobiera wiersz jako obiekt

pg_fetch_assoc
pg_fetch_result
Funkcje PostgreSQL
PHP Manual

pg_fetch_object

(PHP 4, PHP 5)

pg_fetch_object — Pobiera wiersz jako obiekt

Opis

object pg_fetch_object ( resource $wynik [, int $wiersz [, int $typ_wyniku = PGSQL_ASSOC ]] )
object pg_fetch_object ( resource $wynik [, int $wiersz [, string $nazwa_klasy [, array $parametry ]]] )

pg_fetch_object() zwraca obiekt którego atrybutami są nazwy pól pobranego wiersza. Może dodatkowo tworzyć pewien obiekt określonej klasy, oraz wstawić parametry do konstruktora tej klasy.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Pod względem szybkości funkcja ta jest identyczna jak pg_fetch_array(), i prawie tak szybka jak pg_fetch_row() (różnica jest znikoma).

Parametry

wynik

Identyfikator wyniku zapytania PostgreSQL, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

wiersz

Numer wiersza w wyniku do pobrania. Wiersze są numerowane od zera w górę. Jeśli jest pominięty albo wynosi NULL, pobrany zostanie kolejny wiersz.

typ_wyniku

Pomijany i przestarzały.

nazwa_klasy

Nazwa klasy do wytworzenia, określenie zwracanych parametrów. Jeśli nie podano, zwrócony zostanie obiekt stdClass.

parametry

Opcjonalna tablica (ang. array) parametrów podawanych do konstruktora obiektów klasy nazwa_klasy.

Zwracane wartości

Obiekt (ang. object) z atrybutem dla każdej nazwy kolumny w wyniku. Wartości NULL z bazy danych są zwracane jako NULL.

FALSE jest zwracne, gdy parametr wiersz przekracza całkowitą liczbę wierszy, gdy kolejny wiersz nie istnieje, lub w przypadku każdego innego błędu.

Rejestr zmian

Wersja | Opis
5.0.0 | Parametry nazwa_klasy oraz parametry zostały dodane. Stara wersja z typ_wyniku wciąż istnieje, w celu zachowania wstecznej kompatybilności.
4.3.0 | Domyślną wartość parametru typ_wyniku zmieniono z PGSQL_BOTH na PGSQL_ASSOC, gdyż indeks numeryczny był niepoprawny.
4.1.0 | Parametr wiersz stał się opcjonalnym.

Przykłady

Przykład #1 pg_fetch_object() - przykład

<?php

$baza = "magazyn";

$polaczenie = pg_connect("host=localhost port=5432 dbname=$baza");
if (!$polaczenie) {
  echo "Błąd połączenia do bazy PostgreSQL $baza\n";
  exit;
}

$zap = pg_query($polaczenie, "SELECT * FROM ksiazki ORDER BY autor");

while ($dane = pg_fetch_object($zap)) {
  echo $dane->autor . " (";
  echo $dane->rok . "): ";
  echo $dane->tytul . "<br />";
}

pg_free_result($zap);
pg_close($polaczenie);

?>

Zobacz też:

  • pg_query() - Realizujezapytanie do bazy danych
  • pg_fetch_array() - Pobiera wiersz jako tablicę
  • pg_fetch_assoc() - Fetch a row as an associative array
  • pg_fetch_row() - Pobiera wiersz jako tablicę z indeksami numerycznymi
  • pg_fetch_result() - Pobiera dane z wyniku

pg_fetch_assoc
pg_fetch_result
Funkcje PostgreSQL


Pobiera dane z wyniku

pg_fetch_object
pg_fetch_row
Funkcje PostgreSQL
PHP Manual

pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5)

pg_fetch_result — Pobiera dane z wyniku

Opis

mixed pg_fetch_result ( resource $wynik , int $wiersz , mixed $kolumna )
string pg_fetch_result ( resource $wynik , mixed $kolumna )

pg_fetch_result() zwraca wartość określonego wiersza i pola (kolumny) w identyfikatorze wyniku PostgreSQL.

Informacja:

Funkcja ta nazywana była wcześniej pg_result().

Parametry

wynik

Identyfikator wyniku zapytania, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

wiersz

Numer wiersza wyniku do zwrócenia. Wiersze są numerowane od zera w górę. Jeśli nie podano, zwracany jest kolejny wiersz.

kolumna

Łańcuch (ang. string) reprezentujący nazwę pola (kolumny) do pobrania, w innym wypadku, kolumnę do pobrania reprezentuje jej numer (int). Pola są numerowane od zera w górę.

Zwracane wartości

Typ boolean jest zwracany jako "t" lub "f" (true lub false z j. ang.). Wszystkie inne typy, włączając tablice są zwracane jako łańcuchy sformatowane domyślnie, do takiego samego typu PostgreSQL, jaki powinieneś zobaczyć w programie psql. Wartości NULL z bazy danych są zwracane jako NULL.

FALSE jest zwracane jeśli wiersz przekracza liczbę wszystkich dostępnych wierszy, lub w przypadku każdego innego błędu.

Przykłady

Przykład #1 pg_fetch_result() - przykład

<?php
$baza_danych = pg_connect("dbname=uzytkownicy uzytkownik=ja") || die();

$id = pg_query($baza_danych, "SELECT 1 UNION ALL SELECT 2");

$war = pg_fetch_result($id, 1, 0);

echo "Pierwsze pole w drugim wierszu to: ", $war, "\n";
?>

Powyższy przykład wyświetli:

Pierwsze pole w drugim wierszu to: 2

Zobacz też:

  • pg_query() - Realizujezapytanie do bazy danych
  • pg_fetch_array() - Pobiera wiersz jako tablicę

pg_fetch_object
pg_fetch_row
Funkcje PostgreSQL


Pobiera wiersz jako tablicę z indeksami numerycznymi

pg_fetch_result
pg_field_is_null
Funkcje PostgreSQL
PHP Manual

pg_fetch_row

(PHP 4, PHP 5)

pg_fetch_row — Pobiera wiersz jako tablicę z indeksami numerycznymi

Opis

array pg_fetch_row ( resource $wynik , int $wiersz )

pg_fetch_row() pobiera jeden wiersz z wyniku wskazanego przez określony identyfikator wyniku wynik.

Informacja: Ta funkcja ustala wartość pól NULL na NULL.

Parametry

wynik

Identyfikator wyniku zapytania bazy PostgreSQL, zwrócony przez jedną z funkcji pg_query(), pg_query_params() lub pg_execute() (między innymi).

wiersz

Numer wiersza w wyniku do pobrania. Wiersze numerowane są od zera w górę. Jeśli jest pominięty albo wynosi NULL, pobrany zostanie kolejny wiersz.

Zwracane wartości

Tablica (ang. array), indeksowana od zera w górę, z reprezentowaną każdą wartością jako łańcuch (ang. string). Wartości NULL z bazy danych są zwracane jako NULL.

FALSE jest zwracane, jeśli wiersz przekracza liczbę wszystkich wierszy, nie ma więcej wierszy, lub w przypadku każdego innego błędu.

Rejestr zmian

Wersja | Opis
4.1.0 | Parametr wiersz stał się opcjonalny.

Przykłady

Przykład #1 pg_fetch_row() - przykład

<?php

$polaczenie = pg_pconnect("dbname=wydawca");
if (!$polaczenie) {
  echo "Wystąpił błąd.\n";
  exit;
}

$wynik = pg_query($polaczenie, "SELECT autor, email FROM autorzy");
if (!$wynik) {
  echo "Wystąpił błąd.\n";
  exit;
}

while ($wiersz = pg_fetch_row($wynik)) {
  echo "Autor: $wiersz[0]  E-mail: $wiersz[1]";
  echo "<br />\n";
}

?>

Zobacz też:

  • pg_query() - Realizujezapytanie do bazy danych
  • pg_fetch_array() - Pobiera wiersz jako tablicę
  • pg_fetch_object() - Pobiera wiersz jako obiekt
  • pg_fetch_result() - Pobiera dane z wyniku

pg_fetch_result
pg_field_is_null
Funkcje PostgreSQL


Sprawdza czy pole SQL zawiera NULL

pg_fetch_row
pg_field_name
Funkcje PostgreSQL
PHP Manual

pg_field_is_null

(PHP 4 >= 4.2.0, PHP 5)

pg_field_is_null — Sprawdza czy pole SQL zawiera NULL

Opis

int pg_field_is_null ( resource $wynik , int $wiersz , mixed $pole )
int pg_field_is_null ( resource $wynik , mixed $pole )

pg_field_is_null() sprawdza, czy pole identyfikatora wyniku PostgreSQL jest wartością NULL SQL-a czy nie.

Informacja:

Ta funkcja była poprzednio nazwana pg_fieldisnull().

Parametry

wynik

Identyfikator wyniku PostgreSQL-q, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

wiersz

Numer wiersza w wyniku do pobrania. Wiersze są numerowane od zera, w górę. Jeśli nie podano, aktualny wiersz jest pobierany.

pole

Numer pola (zaczynając od zera) jako typ całkowity (ang. integer) lub nazwa pola jako łańcuch (ang. string).

Zwracane wartości

Zwraca 1 jeśli pole w zadanym wierszu w bazie SQL jest wartością NULL, 0 jeśli nią nie jest. FALSE jest zwracane, gdy podany wiersz jest poza przedziałem, lub przez każdy inny błąd.

Przykłady

Przykład #1 pg_field_is_null() - przykład

<?php
  $polaczenie = pg_connect("dbname=wydawca") or die ("Nie można się połączyć");
  $wyn = pg_query($polaczenie, "select * from autorzy where autor = 'Orwell'"
  if ($wyn) {
      if (pg_field_is_null($wyn, 0, "rok") == 1) {
          echo "Wartość pola roku jest null.\n";
      }
      if (pg_field_is_null($wyn, 0, "rok") == 0) {
          echo "Wartość pola roku nie jest null.\n";
    }
 }
?>

pg_fetch_row
pg_field_name
Funkcje PostgreSQL


Zwraca nazwę kolumny

pg_field_is_null
pg_field_num
Funkcje PostgreSQL
PHP Manual

pg_field_name

(PHP 4 >= 4.2.0, PHP 5)

pg_field_name — Zwraca nazwę kolumny

Opis

string pg_field_name ( resource $wynik , int $numer_pola )

pg_field_name() zwraca nazwę kolumny znajdującej się na pozycji numer_pola w identyfikatorze wyniku wynik PostgreSQL-a. Kolumny są numerowane od zera.

Informacja:

Ta funkcja była poprzednio nazwana pg_fieldname().

Parametry

wynik

Identyfikator wyniku zapytania PostgreSQL-a, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

numer_pola

Numer kolumny, rozpoczynając od zera.

Zwracane wartości

Nazwa kolumny, lub FALSE w razie błędu.

Przykłady

Przykład #1 Pobieranie informacji o kolumnach

<?php
  $polaczenie = pg_connect("dbname=wydawca") or die("Nie można się połączyć");

  $wyn = pg_query($polaczenie, "select * from autorzy where autor = 'Orwell'");
  $i = pg_num_fields($wyn);
  for ($j = 0; $j < $i; $j++) {
      echo "kolumna $j\n";
      $nazwa_pola = pg_field_name($wyn, $j);
      echo "nazwa pola: $nazwa_pola\n";
      echo "drukowalna długość: " . pg_field_prtlen($wyn, $nazwa_pola) . " znak(ów)\n";
      echo "rzeczywista długość: " . pg_field_size($wyn, $j) . " bajt(ów)\n";
      echo "typ pola: " . pg_field_type($wyn, $j) . " \n\n";
  }
?>

Powyższy przykład wyświetli:

kolumna 0
nazwa pola: autor
drukowalna długość: 6 znak(ów)
rzeczywista długość: -1 bajt(ów)
typ pola: varchar

kolumna 1
nazwa pola: rok
drukowalna długość: 4 znak(ów)
rzeczywista długość: 2 bajt(ów)
typ pola: int2

kolumna 2
nazwa pola: tytul
drukowalna długość: 24 znak(ów)
rzeczywista długość: -1 bajt(ów)
typ pola: varchar

Zobacz też:

  • pg_field_num() - Zwraza numer kolumny o podanej nazwie

pg_field_is_null
pg_field_num
Funkcje PostgreSQL


Zwraza numer kolumny o podanej nazwie

pg_field_name
pg_field_prtlen
Funkcje PostgreSQL
PHP Manual

pg_field_num

(PHP 4 >= 4.2.0, PHP 5)

pg_field_num — Zwraza numer kolumny o podanej nazwie

Opis

int pg_field_num ( resource $wynik , string $nazwa_pola )

pg_field_num() zwraca indeks numeru pola o podanej nazwie nazwa_pola w podanym identyfikatorze wyniku wynik.

Informacja:

Ta funkcja była poprzednio nazwana pg_fieldnum().

Parametry

wynik

Identyfikator wyniku zapytania PostgreSQL-a, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

nazwa_pola

Nazwa kolumny.

Zwracane wartości

Numer pola (numerowanie od zera), lub -1 w razie błędu.

Przykłady

Przykład #1 Pobieranie informacji o polach

<?php
  $polaczenie = pg_connect("dbname=wydawca") or die("Nie można się połączyć");

  $wyn = pg_query($polaczenie, "select autor, rok, tytul from autorzy where autor = 'Orwell'");

  echo "Kolumna 'tytul' to pole numer: ", pg_field_num($wyn, 'tytul');
?>

Powyższy przykład wyświetli:

Kolumna 'tytul' to pole numer: 2

Zobacz też:

  • pg_field_name() - Zwraca nazwę kolumny

pg_field_name
pg_field_prtlen
Funkcje PostgreSQL


Zwraca drukowalną długość

pg_field_num
pg_field_size
Funkcje PostgreSQL
PHP Manual

pg_field_prtlen

(PHP 4 >= 4.2.0, PHP 5)

pg_field_prtlen — Zwraca drukowalną długość

Opis

int pg_field_prtlen ( resource $wynik , int $numer_wiersza , string $nazwa_pola_lub_numer )
int pg_field_prtlen ( resource $wynik , mixed $nazwa_pola_lub_numer )

pg_field_prtlen() zwraca aktualną drukowalną długość (liczbę znaków) wskazanej danej wyniku parametru wynik PostgreSQL-a. Wiersze są numerowane od zera. Funkcja zwraca -1 w razie błędu.

Parametr nazwa_pola_lub_numer przyjmie wartości zarówno liczbowe (integer), jak również łańcuchowe (ang. string). Jeśli podano liczbę całkowitą (integer), PHP rozpozna to jako numer pola, w przeciwnym wypadku jako nazwę pola.

Proszę spojrzeć na przykład zawarty na stronie opisującej funkcję pg_field_name().

Informacja:

Ta funkcja była poprzednio nazwana pg_fieldprtlen().

Parametry

wynik

Identyfikator wyniku zapytania do PostgreSQL, zwrócony przez pg_guery(), pg_query_params() lub pg_execute() (między innymi).

wiersz

Numer wiersza w wyniku. Wiersze są numerowane od zera w górę. Jeśli pominięto, pobierany jest aktualny wiersz.

Zwracane wartości

Długość drukowailna pola, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 Pobieranie informacji na temat pól

<?php
  $polaczenie_z_baza = pg_connect("dbname=wydawca") or die("Nie można się połączyć.");

  $wyn = pg_query($polaczenie_z_baza, "select * from autorzy where autor = 'Orwell'");
  $i = pg_num_fields($wyn);
  for ($j = 0; $j < $i; $j++) {
      echo "kolumna $j\n";
      $nazwa_pola = pg_field_name($wyn, $j);
      echo "nazwa pola: $nazwa_pola\n";
      echo "długość drukowalna: " . pg_field_prtlen($wyn, $nazwa_pola) . " znaki(ów)\n";
      echo "realna długość: " . pg_field_size($wyn, $j) . " bajty(ów)\n";
      echo "typ pola: " . pg_field_type($wyn, $j) . " \n\n";
  }
?>

Powyższy przykład wyświetli:

kolumna 0
nazwa pola: autor
długość drukowalna: 6 znaki(ów)
realna długość: -1 bajt(ów)
typ pola: varchar

kolumna 1
nazwa pola: rok
długość drukowalna: 4 znaki(ów)
realna długość: 2 bajt(ów)
typ pola: int2

kolumna 2
nazwa pola: tytuł
długość drukowalna: 24 znaki(ów)
realna długość: -1 bajt(ów)
typ pola: varchar

Zobacz też:

  • pg_field_size() - Zwraca wewnętrzny rozmiar kolumny

pg_field_num
pg_field_size
Funkcje PostgreSQL


Zwraca wewnętrzny rozmiar kolumny

pg_field_prtlen
pg_field_table
Funkcje PostgreSQL
PHP Manual

pg_field_size

(PHP 4 >= 4.2.0, PHP 5)

pg_field_size — Zwraca wewnętrzny rozmiar kolumny

Opis

int pg_field_size ( resource $wynik , int $numer_pola )

pg_field_size() zwraca wewnętrzny rozmiar (w bajtach) wskazanej numerem kolumny w podanym wyniku wynik PostgreSQL-a.

Informacja:

Ta funkcja była poprzednio nazwana pg_fieldsize().

Parametry

wynik

Identyfikator wyniku zapytania PostgreSQL, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

numer_pola

Numer pola, zaczynając od zera.

Zwracane wartości

Wewnętrzny rozmiar danego pola (w bajtach). -1 oznacza niestałą wielkość pola. FALSE zwracane jest w przypadku błędu.

Przykłady

Przykład #1 Pobieranie informacji o polach

<?php
  $polaczenie = pg_connect("dbname=wydawca") or die("Nie można się połączyć");

  $wyn = pg_query($polaczenie, "select * from autorzy where autor = 'Orwell'");
  $i = pg_num_fields($wyn);
  for ($j = 0; $j < $i; $j++) {
      echo "kolumna $j\n";
      $nazwa_pola = pg_field_name($wyn, $j);
      echo "nazwa pola: $nazwa_pola\n";
      echo "drukowalna długość: " . pg_field_prtlen($wyn, $nazwa_pola) . " znak(ów)\n";
      echo "rzeczywista długość: " . pg_field_size($wyn, $j) . " bajt(ów)\n";
      echo "typ pola: " . pg_field_type($wyn, $j) . " \n\n";
  }
?>

Powyższy przykład wyświetli:

kolumna 0
nazwa pola: autor
drukowalna długość: 6 znak(ów)
rzeczywista długość: -1 bajt(ów)
typ pola: varchar

kolumna 1
nazwa pola: rok
drukowalna długość: 4 znak(ów)
rzeczywista długość: 2 bajt(ów)
typ pola: int2

kolumna 2
nazwa pola: tytul
drukowalna długość: 24 znak(ów)
rzeczywista długość: -1 bajt(ów)
typ pola: varchar

Zobacz też:

  • pg_field_prtlen() - Zwraca drukowalną długość
  • pg_field_type() - Zwraca typ wskazanej kolumny

pg_field_prtlen
pg_field_table
Funkcje PostgreSQL


Returns the name or oid of the tables field

pg_field_size
pg_field_type_oid
Funkcje PostgreSQL
PHP Manual

pg_field_table

(PHP 5 >= 5.2.0)

pg_field_table — Returns the name or oid of the tables field

Opis

mixed pg_field_table ( resource $result , int $field_number [, bool $oid_only = false ] )

pg_field_table() returns the name of the table that field belongs to, or the table's oid if oid_only is TRUE.

Parametry

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

oid_only

By default the tables name that field belongs to is returned but if oid_only is set to TRUE, then the oid will instead be returned.

Zwracane wartości

On success either the fields table name or oid. Or, FALSE on failure.

Przykłady

Przykład #1 Getting table information about a field

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$res = pg_query($dbconn, "SELECT bar FROM foo");

echo pg_field_table($res, 0);
echo pg_field_table($res, 0, true);

$res = pg_query($dbconn, "SELECT version()");
var_dump(pg_field_table($res, 0));
?>

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

foo
14379580

bool(false)

Notatki

Informacja:

Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table.

Zobacz też:

  • pg_field_name() - Zwraca nazwę kolumny
  • pg_field_type() - Zwraca typ wskazanej kolumny

pg_field_size
pg_field_type_oid
Funkcje PostgreSQL


Returns the type ID (OID) for the corresponding field number

pg_field_table
pg_field_type
Funkcje PostgreSQL
PHP Manual

pg_field_type_oid

(PHP 5 >= 5.1.0)

pg_field_type_oid — Returns the type ID (OID) for the corresponding field number

Opis

int pg_field_type_oid ( resource $result , int $field_number )

pg_field_type_oid() returns an integer containing the OID of the base type of the given field_number in the given PostgreSQL result resource.

You can get more information about the field type by querying PostgreSQL's pg_type system table using the OID obtained with this function. The PostgreSQL format_type() function will convert a type OID into an SQL standard type name.

Informacja:

If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.

Parametry

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Zwracane wartości

The OID of the field's base type. FALSE is returned on error.

Przykłady

Przykład #1 Getting information about fields

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Assume 'title' is a varchar type
  $res = pg_query($dbconn, "select title from authors where author = 'Orwell'");

  echo "Title field type OID: ", pg_field_type_oid($res, 0);
?>

Powyższy przykład wyświetli:

Title field type OID: 1043

Zobacz też:

  • pg_field_type() - Zwraca typ wskazanej kolumny
  • pg_field_prtlen() - Zwraca drukowalną długość
  • pg_field_name() - Zwraca nazwę kolumny

pg_field_table
pg_field_type
Funkcje PostgreSQL


Zwraca typ wskazanej kolumny

pg_field_type_oid
pg_free_result
Funkcje PostgreSQL
PHP Manual

pg_field_type

(PHP 4 >= 4.2.0, PHP 5)

pg_field_type — Zwraca typ wskazanej kolumny

Opis

string pg_field_type ( resource $wynik , int $numer_kolumny )

pg_field_type() zwraca łańcuch zawierający typ podstawowy kolumny wskazanej przez numer_kolumny w wyniku wynik PostgreSQL-a.

Informacja:

Jeśli kolumna używa domeny PostgreSQL (zamiast typu podstawowego), jest to nazwa podstawowego typu domeny, który jest zwrócony, zamiast nazwy samej domeny.

Informacja:

Ta funkcja dawniej nazywała się pg_fieldtype().

Parametry

wynik

Identyfikator wyniku zapytania do bazy PostgreSQL, zwrócony przez funkcję pg_query(), pg_query_params() lub pg_execute() (między innymi).

numer_pola

Numer pola, zaczynając od zera.

Zwracane wartości

Łańcuch (ang. string) zawierający podstawową nazwę typu pola, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 Pobieranie informacji o kolumnach

<?php
  $polaczenie_do_bazy = pg_connect("dbname=publisher") or die("Nie można się połączyć");

  // Załóżmy, że 'tytul' jest typu varchar
  $res = pg_query($polaczenie_do_bazy, "select tytul from autorzy where autor = 'Orwell'");

  echo "Typ pola tytułu: ", pg_field_type($res, 0);
?>

Powyższy przykład wyświetli:

Typ pola tytułu: varchar

Zobacz też:

  • pg_field_prtlen() - Zwraca drukowalną długość
  • pg_field_name() - Zwraca nazwę kolumny
  • pg_field_type_oid() - Returns the type ID (OID) for the corresponding field number

pg_field_type_oid
pg_free_result
Funkcje PostgreSQL


Zwalnia pamięć wyniku

pg_field_type
pg_get_notify
Funkcje PostgreSQL
PHP Manual

pg_free_result

(PHP 4 >= 4.2.0, PHP 5)

pg_free_result — Zwalnia pamięć wyniku

Opis

bool pg_free_result ( resource $wynik )

pg_free_result() zwalnia pamięć i danych związanych z określonym identyfikatorem wyniku PostgreSQL (ang. typ resource).

Tę funkcję trzeba wywołać jeśli zużywanie pamięci podczas wykonywania skryptu stanowi problem. W przeciwnym wypadku, cała pamięć przeznaczona dla wyniku zostanie automatycznie zwolniona, gdy skrypt zakończy się.

Informacja:

Ta funkcja była poprzednio nazwana pg_freeresult().

Parametry

wynik

Identyfikator wyniku PostgreSQL, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_free_result() - przykład

<?php
$baza_danych = pg_connect("dbname=uzytkownicy uzytkownik=ja") || die();

$wyn = pg_query($baza_danych, "SELECT 1 UNION ALL SELECT 2");

$wartosc = pg_fetch_result($wyn, 1, 0);

echo "Pierwsze pole w drugim wierszu to: ", $wartosc, "\n";

pg_free_result($wyn);
?>

Powyższy przykład wyświetli:

Pierwsze pole w drugim wierszu to: 2

Zobacz też:

  • pg_query() - Realizujezapytanie do bazy danych
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_field_type
pg_get_notify
Funkcje PostgreSQL


Gets SQL NOTIFY message

pg_free_result
pg_get_pid
Funkcje PostgreSQL
PHP Manual

pg_get_notify

(PHP 4 >= 4.3.0, PHP 5)

pg_get_notify — Gets SQL NOTIFY message

Opis

array pg_get_notify ( resource $connection [, int $result_type ] )

pg_get_notify() gets notifications generated by a NOTIFY SQL command. To receive notifications, the LISTEN SQL command must be issued.

Parametry

connection

PostgreSQL database connection resource.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_get_notify() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, will return both numerical and associative indices.

Zwracane wartości

An array containing the NOTIFY message name and backend PID. Otherwise if no NOTIFY is waiting, then FALSE is returned.

Przykłady

Przykład #1 PostgreSQL NOTIFY message

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

// Listen 'author_updated' message from other processes
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
  echo "No messages\n";
} else {
  print_r($notify);
}
?>

Zobacz też:

  • pg_get_pid() - Gets the backend's process ID

pg_free_result
pg_get_pid
Funkcje PostgreSQL


Gets the backend's process ID

pg_get_notify
pg_get_result
Funkcje PostgreSQL
PHP Manual

pg_get_pid

(PHP 4 >= 4.3.0, PHP 5)

pg_get_pid — Gets the backend's process ID

Opis

int pg_get_pid ( resource $connection )

pg_get_pid() gets the backend's (database server process) PID. The PID is useful to determine whether or not a NOTIFY message received via pg_get_notify() is sent from another process or not.

Parametry

connection

PostgreSQL database connection resource.

Zwracane wartości

The backend database process ID.

Przykłady

Przykład #1 PostgreSQL backend PID

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>

Zobacz też:

  • pg_get_notify() - Gets SQL NOTIFY message

pg_get_notify
pg_get_result
Funkcje PostgreSQL


Pobiera wynik zapytania asynchroniczego

pg_get_pid
pg_host
Funkcje PostgreSQL
PHP Manual

pg_get_result

(PHP 4 >= 4.2.0, PHP 5)

pg_get_result — Pobiera wynik zapytania asynchroniczego

Opis

resource pg_get_result ([ resource $polaczenie ] )

pg_get_result() zwraca wynik zapytania asynchronicznego uruchomionego przez pg_send_query(), pg_send_query_params() lub pg_send_execute().

pg_send_query() oraz inne funkcje zapytań asynchronicznych może wysyłać wiele zapytań do serwera PostgreSQL, natomiast pg_get_result() jest używana do pobierania wyników każdego zapytania po kolei.

Parametry

polaczenie

Identyfikator połączenia z bazą PostgreSQL.

Zwracane wartości

Identyfikator wyniku (ang. resource), lub FALSE gdy brak więcej dostępnych wyników.

Przykłady

Przykład #1 pg_get_result() - przykład

<?php
  $polaczenie = pg_connect("dbname=wydawca") or die("Nie można się połączyć");

  if (!pg_connection_busy($polaczenie)) {
      pg_send_query($polaczenie, "select * from autorzy; select count(*) from autorzy;");
  }

  $wyn1 = pg_get_result($polaczenie);
  echo "Pierwsze wywołanie pg_get_result(): $wyn1\n";
  $wiersze1 = pg_num_rows($wyn1);
  echo "$wyn1 ma $wiersze1 rekordy(ów)\n\n";

  $wyn2 = pg_get_result($polaczenie);
  echo "Drugie wywołanie pg_get_result(): $wyn2\n";
  $wiersze2 = pg_num_rows($wyn2);
  echo "$wyn2 ma $wiersze2 rekordy(ów)\n";
?>

Powyższy przykład wyświetli:

Pierwsze wywołanie pg_get_result(): Resource id #3
Resource id #3 ma 3 rekordy(ów)

Drugie wywołanie pg_get_result(): Resource id #4
Resource id #4 ma 1 rekordy(ów)

Zobacz też:

  • pg_send_query() - Wysyła zapytanie asynchroniczne

pg_get_pid
pg_host
Funkcje PostgreSQL


Zwraca nazwę komputera związanego z połączeniem

pg_get_result
pg_insert
Funkcje PostgreSQL
PHP Manual

pg_host

(PHP 4, PHP 5)

pg_host — Zwraca nazwę komputera związanego z połączeniem

Opis

string pg_host ([ resource $polaczenie ] )

pg_host() zwraca nazwę komputera, dla danego identyfikatora polaczenie, z którym połączony jest PostgreSQL.

Parametry

polaczenie

Identyfikator połączenia do bazy PostgreSQL. Gdy parametr polaczenie nie został podany, domyślne połączenie jest używane. Domyślnym połączeniem jest ostatnie połączenie stworzone przez pg_connect() lub pg_pconnect().

Zwracane wartości

Łańcuch (ang. string) zawierający nazwę komputera, do którego polaczenie jest nawiązane, lub FALSE w razie błędu.

Przykłady

Przykład #1 pg_host() - przykład

<?php
$pgsql_polacz = pg_connect("dbname=marek host=localhost");

if ($pgsql_polacz) {
   print "Nawiązano połączenie do: " . pg_host($pgsql_polacz) . "<br/>\n";
} else {
   print pg_last_error($pgsql_polacz);
   exit;
}
?>

Zobacz też:

  • pg_connect() - Otwiera tymczasowe połączenie do PostgreSQL-a
  • pg_pconnect() - Otwiera trwałe połączenie z serwerem PostgreSQL

pg_get_result
pg_insert
Funkcje PostgreSQL


Wstawia tablicę do tabeli

pg_host
pg_last_error
Funkcje PostgreSQL
PHP Manual

pg_insert

(PHP 4 >= 4.3.0, PHP 5)

pg_insert — Wstawia tablicę do tabeli

Opis

mixed pg_insert ( resource $identyfikator_połączenia , string $nazwa_tabeli , array $tablica_asocjacyjna [, int $opcje ] )

pg_insert() wstawia wartości parametru tablica_asocjacyjna do tabeli określonej przez parametr nazwa_tabeli. Jeśli określono jakieś opcje, funkcja pg_convert() stosuje do parametru tablica_asocjacyjna określone opcje.

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

identyfikator_połączenia

Identyfikator połączenia do bazy PostgreSQL.

nazwa_tabeli

Nazwa tabeli, do której mają zostać dodane wiersze. Tabela nazwa_tabeli musi mieć przynajmniej tyle kolumn, ile elementów ma tablica_asocjacyjna.

tablica_asocjacyjna

Tablica (ang. array), której klucze to nazwy pól w tabeli nazwa_tabeli, oraz której wartościami są wartości tych pól, które mają zostać wpisane.

opcje

Dowolna kombinacja dowolnej ilości parametrów: PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DML_ASYNC oraz PGSQL_DML_STRING. Gdy PGSQL_DML_STRING jest zawarty w parametrze opcje, zwrócony zostanie łańcuch zapytania z URL (ang. query string).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Zwraca łańcuch (ang. string) jeśli PGSQL_DML_STRING zostało wprowadzone poprzez parametr opcje.

Przykłady

Przykład #1 pg_insert() - przykład

<?php
  $polaczenie_do_bazy = pg_connect ('dbname=foo');
  // To wywołanie jest bezpieczne, odkąd $_POST jest konwertowane automatycznie
  $res = pg_insert($polaczenie_do_bazy, 'kopia_post', $_POST);
  if ($res) {
      echo "Dane z tablicy POST zapisane pomyślnie\n";
  } else {
      echo "Użytkownik musiał wysłać złe dane\n";
  }
?>

Zobacz też:

  • pg_convert() - Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.

pg_host
pg_last_error
Funkcje PostgreSQL


Zwraca łańcuch ostatniego komunikatu błędu dla połączenia

pg_insert
pg_last_notice
Funkcje PostgreSQL
PHP Manual

pg_last_error

(PHP 4 >= 4.2.0, PHP 5)

pg_last_error — Zwraca łańcuch ostatniego komunikatu błędu dla połączenia

Opis

string pg_last_error ([ resource $polaczenie ] )

pg_last_error() zwraca ostatni komunikat błędu dla połączenia danego parametrem polaczenie.

Komunikaty błędów mogą być zamazane przez wewnętrzne wywołania funkcji PostgreSQL(libpq). Funkcja może nie zwrócić właściwego komunikatu, jeśli wewnątrz modułu PostgreSQL wystąpiło wiele błędów.

Stosuj pg_result_error(), pg_result_error_field(),
pg_result_status() i
pg_connection_status() dla lepszej obsługi błędów.

Informacja:

Ta funkcja była poprzednio nazwana pg_errormessage().

Parametry

polaczenie

Identyfikator połączenia do bazy danych PostgreSQL. Gdy polaczenie nie został podany, domyślne połączenie jest użyte. Domyślnym połączeniem jest ostatnie, stworzone przez pg_connect() lub pg_pconnect().

Zwracane wartości

Łańcuch (ang. string) zawierający ostatni komunikat błędu dla danego poprzez parametr polaczenie połączenia, lub FALSE w razie niepowodzenia.

Przykłady

Przykład #1 pg_last_error() - przykład

<?php
  $polaczenie = pg_connect("dbname=wydawca") or die("Nie można się połączyć");

  // Zapytanie, które nie zostało wykonane
  $wyn = pg_query($polaczenie, "select * from nie_istniejaca_tabela");

  echo pg_last_error($polaczenie);
?>

Zobacz też:

  • pg_result_error() - Zwraca błąd związany z identyfikatorem wyniku
  • pg_result_error_field() - Returns an individual field of an error report.

pg_insert
pg_last_notice
Funkcje PostgreSQL


Zwraca komunikaty informacyjne serwera PostgreSQL

pg_last_error
pg_last_oid
Funkcje PostgreSQL
PHP Manual

pg_last_notice

(PHP 4 >= 4.0.6, PHP 5)

pg_last_notice — Zwraca komunikaty informacyjne serwera PostgreSQL

Opis

string pg_last_notice ( resource $connection )

pg_last_notice() zwraca ostatni komunikat informacyjny serwera PostgreSQL związanego z połączeniem connection. Serwer PostgreSQL wysyła komunikaty informacyjne w pewnych przypadkach, np. gdy trasakcja nie może być kontynuowana. Przy użyciu pg_last_notice(), możesz uniknąć wywoływania bezużytecznych zapytań, sprawdzając czy komunikat jest związany z transakcją czy nie.

Ostrzeżenie

Ta funkcja jest EKSPERYMENTALNA i nie jest jeszcze w pełni zaimplementowana. pg_last_notice() została dodana w PHP 4.0.6. Niestety PHP 4.0.6 ma błąd w obsłudze tych komunikatów. Używanie modułu PostgreSQL z PHP 4.0.6 nie jest zalecane, nawet jeśli nie używasz funkcji pg_last_notice().

Ta funkcja jest w pełni zaimplementowana w PHP 4.3.0. Wcześniejsze niż 4.3.0 wersje PHP ignorują parametr connection.

Śledzenie komunikatów informacyjnych może być ustawtione jako opcjonalne przez ustawienie parametru ini pgsql.ignore_notice na 1 od wersji PHP 4.3.0.

Logowanie komunikatów informacyjnych może być ustawtione jako opcjonalne przez ustawienie parametru ini pgsql.log_notice na 0 od wersji PHP 4.3.0. Dopuki pgsql.ignore_notice jest ustawione na 0, komunikaty informacyjne nie mogą być logowane.

Zobacz także pg_query() i pg_last_error().

pg_last_error
pg_last_oid
Funkcje PostgreSQL


Zwraca identyfikator OID ostatniego wiersza

pg_last_notice
pg_lo_close
Funkcje PostgreSQL
PHP Manual

pg_last_oid

(PHP 4 >= 4.2.0, PHP 5)

pg_last_oid — Zwraca identyfikator OID ostatniego wiersza

Opis

string pg_last_oid ( resource $wynik )

pg_last_oid() służy do pobrania OID przypisanego do dopisanego wiersza.

OID jest polem opcjonalnym od wersji PostgreSQL 7.2 i nie pojawi się domyślnie w PostgreSQL 8.1. Gdy pole OID nie pojawia się w tabeli, programista musi użyć pg_result_status() aby sprawdzić czy rekord został dopisany czy nie.

Aby pobrać wartość pola SERIAL we wstawionym wierszu, niezbędnym jest użycie funkcji PostgreSQL CURRVAL, przekazując sekwencję, której wymagana jest ostatnia wartość. Jeśli nazwa sekwencji nie jest znana, konieczne jest użycie funkcji pg_get_serial_sequence PostgreSQL-a 8.0.

PostgreSQL 8.1 ma funkcję LASTVAL, która zwraca wartość ostatnio użytej sekwencji w sesji. To uchyla potrzebę powoływania razem sekwencji, tabeli lub kolumny.

Informacja:

Ta funkcja była poprzednio nazwana pg_getlastoid().

Parametry

wynik

Identyfikator wyniku zapytania PostgreSQL-a, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

Zwracane wartości

Łańcuch (ang. string) zawierający OID przydzielony do ostatnio wstawionego wiersza w określonym parametrem polaczenie połączeniem, lub FALSE w przypadku błędu lub gdy OID nie jest dostępny.

Przykłady

Przykład #1 pg_last_oid() - przykład

<?php
  $pgsql_polaczenie = pg_connect("dbname=ocena host=localhost");

  $wyn1 = pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");

  $wyn2 = pg_query("INSERT INTO test VALUES (1)");

  $oid = pg_last_oid($wyn2);
?>

Zobacz też:

  • pg_query() - Realizujezapytanie do bazy danych
  • pg_result_status() - Zwraca stan wyniku zapytania

pg_last_notice
pg_lo_close
Funkcje PostgreSQL


Zamyka wielki obiekt (LO)

pg_last_oid
pg_lo_create
Funkcje PostgreSQL
PHP Manual

pg_lo_close

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_close — Zamyka wielki obiekt (LO)

Opis

bool pg_lo_close ( resource $uchwyt )

pg_lo_close() zamyka wielki obiekt (z ang. Large Object - LO). uchwyt jest identyfikatorem wielkiego obiektu (LO) wywołanego funkcją pg_lo_open().

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja:

Ta funkcja była poprzednio nazwana pg_loclose().

Parametry

uchwyt

Identyfikator wielkiego obiektu (LO) PostgreSQL-a, zwrócony przez pg_lo_open().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_lo_close() - przykład

<?php
   $baza_danych = pg_connect("dbname=jacarta");
   pg_query($baza_danych, "begin");
   $oid = pg_lo_create($baza_danych);
   echo "$oid\n";
   $uchwyt = pg_lo_open($baza_danych, $oid, "w");
   echo "$uchwyt\n";
   pg_lo_write($uchwyt, "large object data");
   pg_lo_close($uchwyt);
   pg_query($baza_danych, "commit");
?>

Zobacz też:

  • pg_lo_open() - Otwiera wielki obiekt (Large Object - LO)
  • pg_lo_create() - Tworzy wielki obiekt (Large Object - LO)
  • pg_lo_import() - Importuje wielki obiekt (Large Object - LO) z pliku

pg_last_oid
pg_lo_create
Funkcje PostgreSQL


Tworzy wielki obiekt (Large Object - LO)

pg_lo_close
pg_lo_export
Funkcje PostgreSQL
PHP Manual

pg_lo_create

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_create — Tworzy wielki obiekt (Large Object - LO)

Opis

int pg_lo_create ( resource $connection )

pg_lo_create() tworzy wielki obiekt (LO) i zwraca jego oid. Parametr connection wskazuje istniejące połączenie do bazy. Tryby dostępu PostgreSQL-a: INV_READ, INV_WRITE i INV_ARCHIVE nie są wspierane, obiekt jest tworzony zawsze z dostępem do odczytu i zapisu. Tryb INV_ARCHIVE został usunięty z PostgreSQL-a (wersja 6.3 i nowsze). Funkcja zwraca oid lub FALSE jeśli wystąpił błąd.

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja:

Ta funkcja była poprzednio nazwana pg_locreate().

pg_lo_close
pg_lo_export
Funkcje PostgreSQL


Eksportuje wielki obiekt (Large Object - LO) do pliku

pg_lo_create
pg_lo_import
Funkcje PostgreSQL
PHP Manual

pg_lo_export

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_export — Eksportuje wielki obiekt (Large Object - LO) do pliku

Opis

bool pg_lo_export ( resource $polaczenie , int $oid , string $sciezka )
bool pg_lo_export ( int $oid , string $sciezka )

pg_lo_export() pobiera wielki obiekt w bazie PostgreSQL i zapisuje jego zawartość do lokalnego systemu plików.

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja:

Ta funkcja była poprzednio nazwana pg_loexport().

Parametry

polaczenie

Identyfikator połączenia do bazy PostgreSQL. Gdy polaczenie nie zostało podane, domyślne połączenie zostaje użyte. Domyślnym połączeniem jest ostatnie stworzone przez pg_connect() lub pg_pconnect().

oid

OID wielkiego obiektu w bazie danych.

sciezka

Pełna ścieżka i nazwa pliku, do którego zostanie zapisana zawartość wielkiego obiektu w systemie plików klienta.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_lo_export() - przykład

<?php
   $baza_danych = pg_connect("dbname=jacarta");
   pg_query($baza_danych, "begin");
   $oid = pg_lo_create($baza_danych);
   $uchwyt = pg_lo_open($baza_danych, $oid, "w");
   pg_lo_write($uchwyt, "large object data");
   pg_lo_close($uchwyt);
   pg_lo_export($baza_danych, $oid, '/tmp/lob.dat');
   pg_query($baza_danych, "commit");
?>

Zobacz też:

  • pg_lo_import() - Importuje wielki obiekt (Large Object - LO) z pliku

pg_lo_create
pg_lo_import
Funkcje PostgreSQL


Importuje wielki obiekt (Large Object - LO) z pliku

pg_lo_export
pg_lo_open
Funkcje PostgreSQL
PHP Manual

pg_lo_import

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_import — Importuje wielki obiekt (Large Object - LO) z pliku

Opis

int pg_lo_import ( resource $polaczenie , string $sciezka , mixed $id_objektu )
int pg_lo_import ( string $sciezka , mixed $id_objektu )

pg_lo_import() kreuje nowy Wielki Obiekt (LO) w bazie danych, używając pliku w systemie plików jako jego danych źródłowych.

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Informacja:

Ta funkcja była poprzednio nazwana pg_loimport().

Parametry

polaczenie

Identyfikator połączenia do bazy PostgreSQL. Gdy parametr polaczenie nie został podany, zostanie użyte domyślne połączenie. Domyślnym połączeniem jest ostatnie połączenie stworzone przez pg_connect() lub pg_pconnect().

sciezka

Pełna ścieżka z nazwą pliku znajdującego się w systemie plików klienta, z którego zostanie przeczytany LO.

id_obiektu

Jeśli id_obiektu został podany, funkcja spróbuje stworzyć wielki obiekt o podanym unikalnym identyfikatorze, w przeciwnym razie serwer przydzieli dowolne id. Parametr został dodany w PHP 5.3 i jest uzależniony od mechanizmów działania, które jako pierwsze pojawiły się w PostgreSQL 8.1.

Zwracane wartości

Identyfikator OID nowo stworzonego LO, lub FALSE w przypadku błędów.

Rejestr zmian

Wersja | Opis
4.2.0 | Składnia tej funkcji uległa zmianie. Wcześniej wyglądała tak: int pg_lo_import ( string $sciezka [, resource $polaczenie ] )

Przykłady

Przykład #1 pg_lo_import() - przykład

<?php
   $baza_danych = pg_connect("dbname=warszawa");
   pg_query($baza_danych, "begin");
   $oid = pg_lo_import($baza_danych, '/tmp/lob.dat');
   pg_query($baza_danych, "commit");
?>

Zobacz też:

  • pg_lo_export() - Eksportuje wielki obiekt (Large Object - LO) do pliku
  • pg_lo_open() - Otwiera wielki obiekt (Large Object - LO)

pg_lo_export
pg_lo_open
Funkcje PostgreSQL


Otwiera wielki obiekt (Large Object - LO)

pg_lo_import
pg_lo_read_all
Funkcje PostgreSQL
PHP Manual

pg_lo_open

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_open — Otwiera wielki obiekt (Large Object - LO)

Opis

resource pg_lo_open ( resource $connection , int $oid , string $mode )

pg_lo_open() otwiera wielki obiekt (LO) i zwraca identyfikator połączenia do niego. oid wskazuje poprawny identyfikator wielkiego obiektu (LO), mode może przyjmować wartości "r" - odczyt, "w" - zapis, lub "rw" odczyt/zapis. Funkcja zwraca FALSE w razie błędu.

Ostrzeżenie

Nie wolno zamykać połączenia z serwerem przed zamknięciem wszystkich wielkich obiektów.

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja:

Ta funkcja była poprzednio nazwana pg_loopen().

Zobacz także pg_lo_close() i pg_lo_create().

pg_lo_import
pg_lo_read_all
Funkcje PostgreSQL


Odczytuje wielki obiekt (Large Object - LO) i wysła go do przeglądarki

pg_lo_open
pg_lo_read
Funkcje PostgreSQL
PHP Manual

pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_read_all — Odczytuje wielki obiekt (Large Object - LO) i wysła go do przeglądarki

Opis

int pg_lo_read_all ( resource $large_object )

pg_lo_read_all() odczytuje wielki obiekt (LO) i przekazuje go wprost do przeglądarki, po wysłaniu wszystkich nagłówków. Przeznaczony głównie do wysyłania danych binarnych, jak obrazy i dźwięk. Zwraca ilość odczytanych danych. Funkcja zwraca FALSE w razie błędu.

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja:

Ta funkcja była poprzednio nazwana pg_loreadall().

Zobacz także pg_lo_read().

pg_lo_open
pg_lo_read
Funkcje PostgreSQL


Odczytuje wielki obiekt (Large Object - LO)

pg_lo_read_all
pg_lo_seek
Funkcje PostgreSQL
PHP Manual

pg_lo_read

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_read — Odczytuje wielki obiekt (Large Object - LO)

Opis

string pg_lo_read ( resource $large_object , int $len )

pg_lo_read() odczytuje co najwyżej len bajtów z wielkiego obiektu (LO) i zwraca je jako łańcuch. large_object wskazuje identyfikator połączenia z pg_lo_open(), len wskazuje maksymalną dopuszczalną wielkość segmentu wielkiego obiektu. Funkcja zwraca FALSE w razie błędu.

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja:

Ta funkcja była poprzednio nazwana pg_loread().

Zobacz także pg_lo_read_all().

pg_lo_read_all
pg_lo_seek
Funkcje PostgreSQL


Przemieszcza wskaźnik położenia w wielkim obiekcie (Large Object - LO)

pg_lo_read
pg_lo_tell
Funkcje PostgreSQL
PHP Manual

pg_lo_seek

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_seek — Przemieszcza wskaźnik położenia w wielkim obiekcie (Large Object - LO)

Opis

bool pg_lo_seek ( resource $large_object , int $offset [, int $whence ] )

pg_lo_seek() przemieszcza wskaźnik położenia w wielkim obiekcie (LO). Parametr whence może przyjmować wartości PGSQL_SEEK_SET, PGSQL_SEEK_CUR lub PGSQL_SEEK_END.

Zobacz także pg_lo_tell().

pg_lo_read
pg_lo_tell
Funkcje PostgreSQL


Zwraca wskaźnik położenia w wielkim obiekcie (Large Object - LO)

pg_lo_seek
pg_lo_unlink
Funkcje PostgreSQL
PHP Manual

pg_lo_tell

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_tell — Zwraca wskaźnik położenia w wielkim obiekcie (Large Object - LO)

Opis

int pg_lo_tell ( resource $large_object )

pg_lo_tell() zwraca aktualną pozycję wskaźnika położenia w wielkim obiekcie (LO) liczoną od jego początku.

Zobacz także pg_lo_seek().

pg_lo_seek
pg_lo_unlink
Funkcje PostgreSQL


Usuwa wielki obiekt (Large Object - LO)

pg_lo_tell
pg_lo_write
Funkcje PostgreSQL
PHP Manual

pg_lo_unlink

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_unlink — Usuwa wielki obiekt (Large Object - LO)

Opis

bool pg_lo_unlink ( resource $connection , int $oid )

pg_lo_unlink() usuwa wielki obiekt (LO) określony przez oid. Zwraca TRUE jeśli operacja się powiedzie lub FALSE jeśli wystąpi błąd.

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja:

Ta funkcja była poprzednio nazwana pg_lounlink().

Zobacz także pg_lo_create() i pg_lo_import().

pg_lo_tell
pg_lo_write
Funkcje PostgreSQL


Zapisuje do wielkiego obiektu (Large Object - LO)

pg_lo_unlink
pg_meta_data
Funkcje PostgreSQL
PHP Manual

pg_lo_write

(PHP 4 >= 4.2.0, PHP 5)

pg_lo_write — Zapisuje do wielkiego obiektu (Large Object - LO)

Opis

int pg_lo_write ( resource $large_object , string $data )

pg_lo_write() zapisuje jak najwięcej do wielkiego obiektu ze zmiennej data i zwraca liczbę bajtów zapisanych, lub FALSE jeśli wystąpił błąd. Paramter large_object jest identyfikatorem polączenia z pg_lo_open().

Użycie interfejsu wielkich obiektów (LO) wymaga zamknięcia wszystkich operacji z nim związanych wewnątrz transakcji.

Informacja:

Ta funkcja była poprzednio nazwana pg_lowrite().

Zobacz także pg_lo_create() i pg_lo_open().

pg_lo_unlink
pg_meta_data
Funkcje PostgreSQL


Pobiera informacje o tabeli

pg_lo_write
pg_num_fields
Funkcje PostgreSQL
PHP Manual

pg_meta_data

(PHP 4 >= 4.3.0, PHP 5)

pg_meta_data — Pobiera informacje o tabeli

Opis

array pg_meta_data ( resource $connection , string $table_name )

pg_meta_data() zwraca definicje tabeli dla argumentu table_name jako tablicę.

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

connection

Identyfikator połączenia do bazy danych PostgreSQL.

table_name

Nazwa tabeli.

Zwracane wartości

Tablica array z definicją tabeli, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 Pobranie informacji o tabeli

<?php
  $dbconn = pg_connect("dbname=publikacje") or die("Nie można się połączyć.");

  $meta = pg_meta_data($dbconn, 'autorzy');
  if (is_array($meta)) {
      echo '<pre>';
      var_dump($meta);
      echo '</pre>';
  }
?>

Powyższy przykład wyświetli:

array(3) {
["autor"]=>
array(5) {
  ["num"]=>
  int(1)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["rok"]=>
array(5) {
  ["num"]=>
  int(2)
  ["type"]=>
  string(4) "int2"
  ["len"]=>
  int(2)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["tytul"]=>
array(5) {
  ["num"]=>
  int(3)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
}

Zobacz też:

  • pg_convert() - Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.

pg_lo_write
pg_num_fields
Funkcje PostgreSQL


Zwraca liczbę kolumn

pg_meta_data
pg_num_rows
Funkcje PostgreSQL
PHP Manual

pg_num_fields

(PHP 4 >= 4.2.0, PHP 5)

pg_num_fields — Zwraca liczbę kolumn

Opis

int pg_num_fields ( resource $result )

pg_num_fields() zwraca liczbę kolumn w wyniku PostgreSQL. Argumentem jest właściwy identyfikator wyniku zwrócony przez pg_query(). Funkcja zwraca -1 w razie błędu.

Informacja:

Ta funkcja była poprzednio nazwana pg_numfields().

Zobacz także pg_num_rows() i pg_affected_rows().

pg_meta_data
pg_num_rows
Funkcje PostgreSQL


Zwraca liczbę wierszy

pg_num_fields
pg_options
Funkcje PostgreSQL
PHP Manual

pg_num_rows

(PHP 4 >= 4.2.0, PHP 5)

pg_num_rows — Zwraca liczbę wierszy

Opis

int pg_num_rows ( resource $result )

pg_num_rows() zwraca liczbę wierszy w wyniku result zwróconym przez pg_query(). Funkcja zwraca -1 w razie błędu.

Informacja:

Użyj pg_affected_rows() aby otrzymać liczbę wierszy zmodyfikowanych przez INSERT, UPDATE lub DELETE.

Informacja:

Ta funkcja była poprzednio nazwana pg_numrows().

Zobacz także pg_num_fields() i pg_affected_rows().

pg_num_fields
pg_options
Funkcje PostgreSQL


Podaje opcje powiązane z połączenim

pg_num_rows
pg_parameter_status
Funkcje PostgreSQL
PHP Manual

pg_options

(PHP 4, PHP 5)

pg_options — Podaje opcje powiązane z połączenim

Opis

string pg_options ( resource $connection )

pg_options() zwraca łańcuch zawierający opcje związane połączeniem wskazanym przez parametr connection.

pg_num_rows
pg_parameter_status
Funkcje PostgreSQL


Looks up a current parameter setting of the server.

pg_options
pg_pconnect
Funkcje PostgreSQL
PHP Manual

pg_parameter_status

(PHP 5)

pg_parameter_status — Looks up a current parameter setting of the server.

Opis

string pg_parameter_status ([ resource $connection ], string $param_name )

Looks up a current parameter setting of the server.

Certain parameter values are reported by the server automatically at connection startup or whenever their values change. pg_parameter_status() can be used to interrogate these settings. It returns the current value of a parameter if known, or FALSE if the parameter is not known.

Parameters reported as of PostgreSQL 8.0 include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0.) Note that server_version, server_encoding and integer_datetimes cannot change after PostgreSQL startup.

PostgreSQL 7.3 or lower servers do not report parameter settings, pg_parameter_status() includes logic to obtain values for server_version and client_encoding anyway. Applications are encouraged to use pg_parameter_status() rather than ad hoc code to determine these values.

Uwaga

On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status().

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

param_name

Possible param_name values include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes.

Zwracane wartości

A string containing the value of the parameter, FALSE on failure or invalid param_name.

Przykłady

Przykład #1 pg_parameter_status() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?>

Powyższy przykład wyświetli:

Server encoding: SQL_ASCII

pg_options
pg_pconnect
Funkcje PostgreSQL


Otwiera trwałe połączenie z serwerem PostgreSQL

pg_parameter_status
pg_ping
Funkcje PostgreSQL
PHP Manual

pg_pconnect

(PHP 4, PHP 5)

pg_pconnect — Otwiera trwałe połączenie z serwerem PostgreSQL

Opis

resource pg_pconnect ( string $łańcuch_połączenia [, int $typ_połączenia ] )

pg_pconnect() otwiera trwałe połączenie z serwerem PostgreSQL. Zwraca identyfikator połączenia używany przez inne funkcje PostgreSQL-a.

Ponowne wywołanie funkcji pg_pconnect() z identycznym parametrem łańcuch_połączenia, jak w połączeniu już istniejącym, zwróci identyfikator istniejącego połączenia, chyba, że podasz PGSQL_CONNECT_FORCE_NEW jako parametr typ_połączenia.

Aby zezwolić na używanie stałych połączeń, należy ustawić dyrektywę pgsql.allow_persistent w php.ini na "On" (jest to ustawienie domyślne). Maksymalna liczba jednoczesnych trwałych połączeń może być zdefiniowana przez dyrektywę pgsql.max_persistent w php.ini (domyślnia wartość to -1 oznacza brak ograniczeń). Maksymalna liczba wszystkich połączeń może być ustawiona przez dyrektywę pgsql.max_links w php.ini.

pg_close() nie zamyka trwałych połączeń otwartych przez pg_pconnect().

Parametry

connection_string

Parametr łańcuch_połączenia może zostać pusty w celu użycia domyślnych parametrów, lub może zawierać jedno, lub więcej ustawień oddzielonych spacją. Każde ustawienie ma format klucz = wartość. Spacje po obu stronach znaku równości są opcjonalne. Aby stworzyć wartość pustą, lub zawierającą spacje, otocz ją pojedynczymi znakami cudzysłowia, np. klucz = 'wartość'. Pojedyncze cudzysłowy, oraz backslashe wewnątrz wartości muszą być poprzedzone znakiem ucieczki "\", np., \' oraz \\.

Aktualnie rozpoznawanymi parametrami są: host, hostaddr, port dbname, user, password, connect_timeout, options, tty (ignorowany), sslmode requiressl (zdeprecjonowany na korzyść sslmode), oraz service. Niektóre z tych argumentów są zależne od używanej wersji PostgreSQL.

connect_type

Jeśli podano PGSQL_CONNECT_FORCE_NEW, zostanie stworzone nowe połączenie, nawet gdy łańcuch_połączenia jest identyczny, jak w jakimś istniejącym połączeniu.

Zwracane wartości

Nawiązanie połączenie z serwerem PostgreSQL w przypadku powodzenia, FALSE w razie błędu.

Przykłady

Przykład #1 Używanie pg_pconnect()

<?php
$polaczenie = pg_pconnect("dbname=mary");
//Połączenie z bazą o nazwie "mary"

$polaczenie2 = pg_pconnect("host=localhost port=5432 dbname=mary");
//Połączenie z bazą o nazwie "mary" na "localhost" portem "5432"

$polaczenie3 = pg_pconnect("host=owca port=5432 dbname=mary user=jagnie password=foo");
//Połączenie z bazą o nazwie "mary" na hoście "owca" z nazwą użytkownika i hasłem

$lancuch_polaczenia = "host=owca port=5432 dbname=test user=jagnie password=bar";
$polaczenie4 = pg_pconnect($lancuch_polaczenia);
//Połączenie z bazą o nazwie "test" na hoście "owca" z nazwą użytkownika i hasłem
?>

Zobacz też:

  • pg_connect() - Otwiera tymczasowe połączenie do PostgreSQL-a
  • Trwałe połączenia z serwerem baz danych

pg_parameter_status
pg_ping
Funkcje PostgreSQL


Ping database connection

pg_pconnect
pg_port
Funkcje PostgreSQL
PHP Manual

pg_ping

(PHP 4 >= 4.3.0, PHP 5)

pg_ping — Ping database connection

Opis

bool pg_ping ([ resource $connection ] )

pg_ping() pings a database connection and tries to reconnect it if it is broken.

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_ping() example

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

if (!pg_ping($conn))
  die("Connection is broken\n");
?>

Zobacz też:

  • pg_connection_status() - Zwraca stan połączenia
  • pg_connection_reset() - Restartuje połączenie

pg_pconnect
pg_port
Funkcje PostgreSQL


Zwraca numer portu związany z połączeniem

pg_ping
pg_prepare
Funkcje PostgreSQL
PHP Manual

pg_port

(PHP 4, PHP 5)

pg_port — Zwraca numer portu związany z połączeniem

Opis

int pg_port ( resource $connection )

pg_port() zwraca numer portu dla połączenia wskazanego przez connection.

pg_ping
pg_prepare
Funkcje PostgreSQL


Submits a request to create a prepared statement with the given parameters, and waits for completion.

pg_port
pg_put_line
Funkcje PostgreSQL
PHP Manual

pg_prepare

(PHP 5 >= 5.1.0)

pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion.

Opis

resource pg_prepare ([ resource $connection ], string $stmtname , string $query )

pg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The function creates a prepared statement named stmtname from the query string, which must contain a single SQL command. stmtname may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc.

Prepared statements for use with pg_prepare() can also be created by executing SQL PREPARE statements. (But pg_prepare() is more flexible since it does not require parameter types to be pre-specified.) Also, although there is no PHP function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Zwracane wartości

A query result resource on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Using pg_prepare()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query.  Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

Zobacz też:

  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

pg_port
pg_put_line
Funkcje PostgreSQL


Wysyła łańcuch zakończony znakiem NULL do serwera PostgreSQL

pg_prepare
pg_query_params
Funkcje PostgreSQL
PHP Manual

pg_put_line

(PHP 4 >= 4.0.3, PHP 5)

pg_put_line — Wysyła łańcuch zakończony znakiem NULL do serwera PostgreSQL

Opis

bool pg_put_line ([ resource $connection ], string $data )

pg_put_line() wysyła łańcuch zakończony przez NULL do serwera PostgreSQL. Funkcja jest użyteczna do bardzo szybkiego wstawiania danych to tabel, inicjowanych przez operację copy PostgreSQL-a. Końcowy znak NULL jest wstawiany automatycznie. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja:

Aplikacja musi jawnie wysłać dwa znaki: "\." w końcowej linii, aby poinformować serwer że zakończyła wysyłać dane.

Zobacz także pg_end_copy().

Przykład #1 Szybkie wstawianie danych do tebeli

<?php
    $conn = pg_pconnect ("dbname=foo");
    pg_query($conn, "create table bar (a int4, b char(16), d float8)");
    pg_query($conn, "copy bar from stdin");
    pg_put_line($conn, "3\thello world\t4.5\n");
    pg_put_line($conn, "4\tgoodbye world\t7.11\n");
    pg_put_line($conn, "\\.\n");
    pg_end_copy($conn);
?>

pg_prepare
pg_query_params
Funkcje PostgreSQL


Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_put_line
pg_query
Funkcje PostgreSQL
PHP Manual

pg_query_params

(PHP 5 >= 5.1.0)

pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

Opis

resource pg_query_params ([ resource $connection ], string $query , array $params )

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

If parameters are used, they are referred to in the query string as $1, $2, etc. params specifies the actual values of the parameters. A NULL value in this array means the corresponding parameter is SQL NULL.

The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the query string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Zwracane wartości

A query result resource on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Using pg_query_params()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Find all shops named Joe's Widgets.  Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));

// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");

?>

Zobacz też:

  • pg_query() - Realizujezapytanie do bazy danych

pg_put_line
pg_query
Funkcje PostgreSQL


Realizujezapytanie do bazy danych

pg_query_params
pg_result_error_field
Funkcje PostgreSQL
PHP Manual

pg_query

(PHP 4 >= 4.2.0, PHP 5)

pg_query — Realizujezapytanie do bazy danych

Opis

resource pg_query ( string $zapytanie )
resource pg_query ( resource $identyfikator_połączenia , string $zapytanie )

pg_query() wykonuje zapytanie na określonej parametrem identyfikator_połączenia bazie danych.

Jeśli nadarzy się błąd, oraz zwracane jest FALSE, jego szczegóły mogą zostać wydobyte dzięki użyciu funkcji pg_last_error(), jeśli połączenie jest poprawne.

Informacja: Chociaż identyfikator_połączenia można pominąć, nie jest to zalecane, gdyż może to powodować trudne do znalezienia błędy w skrypcie.

Informacja:

Ta funkcja była poprzednio nazwana pg_exec(). pg_exec() jest wciąż dostępna w celu zachowania kompatybilności, ale zalecane jest używanie nowej nazwy.

Parametry

identyfikator_połączenia

Identyfikator połączenia do bazy PostgreSQL. Jeśli identyfikator_połączenia nie został podany, zostanie użyte domyślne połączenie. Domyślnym połączeniem jest to, które jako ostatnie zostało stworzone przez jedną z funkcji: pg_connect() lub pg_pconnect().

zapytanie

Polecenie lub polecenia SQL, do wykonania. Kiedy do funkcji podane zostanie więcej jak jedno zapytanie, wykonają się one automatycznie jako jedna operacja, chyba, że komendy BEGIN/COMMIT są zawarte w zapytaniu. Niemniej jednak, używanie wielu operacji w jednym wywołaniu funkcji nie jest zalecane.

Zwracane wartości

Identyfikator wyniku zapytania w przypadku sukcesu, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 pg_query() - przykład

<?php

$polaczenie = pg_pconnect("dbname=publisher");
if (!$polaczenie) {
  echo "Wystąpił błąd.\n";
  exit;
}

$wynik = pg_query($polaczenie, "SELECT autor, email FROM autorzy");
if (!$wynik) {
  echo "Wystąpił błąd.\n";
  exit;
}

while ($wiersz = pg_fetch_row($wynik)) {
  echo "Autor: $wiersz[0]  E-mail: $wiersz[1]";
  echo "<br />\n";
}

?>

Przykład #2 Używanie pg_query() z wieloma zapytaniami

<?php

$polaczenie = pg_pconnect("dbname=wydawca");

// te polecenia wykonają się jako jedna operacja

$zapytanie = "UPDATE autorzy SET autor=UPPER(autor) WHERE id=1;";
$zapytanie .= "UPDATE autorzy SET autor=LOWER(autor) WHERE id=2;";
$zapytanie .= "UPDATE autorzy SET autor=NULL WHERE id=3;";

pg_query($polaczenie, $zapytanie);

?>

Zobacz też:

  • pg_connect() - Otwiera tymczasowe połączenie do PostgreSQL-a
  • pg_pconnect() - Otwiera trwałe połączenie z serwerem PostgreSQL
  • pg_fetch_array() - Pobiera wiersz jako tablicę
  • pg_fetch_object() - Pobiera wiersz jako obiekt
  • pg_num_rows() - Zwraca liczbę wierszy
  • pg_affected_rows() - Zwraca liczbę zmodyfikowanych wierszy

pg_query_params
pg_result_error_field
Funkcje PostgreSQL


Returns an individual field of an error report.

pg_query
pg_result_error
Funkcje PostgreSQL
PHP Manual

pg_result_error_field

(PHP 5 >= 5.1.0)

pg_result_error_field — Returns an individual field of an error report.

Opis

string pg_result_error_field ( resource $result , int $fieldcode )

pg_result_error_field() returns one of the detailed error message fields associated with result resource. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the fieldcode.

Because pg_query() and pg_query_params() return FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.

Parametry

result

A PostgreSQL query result resource from a previously executed statement.

fieldcode

Possible fieldcode values are: PGSQL_DIAG_SEVERITY, PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY, PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_MESSAGE_HINT, PGSQL_DIAG_STATEMENT_POSITION, PGSQL_DIAG_INTERNAL_POSITION (PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only), PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE, PGSQL_DIAG_SOURCE_LINE or PGSQL_DIAG_SOURCE_FUNCTION.

Zwracane wartości

A string containing the contents of the error field, NULL if the field does not exist or FALSE on failure.

Przykłady

Przykład #1 pg_result_error_field() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  $res1 = pg_get_result($dbconn);
  echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE);
?>

Zobacz też:

  • pg_result_error() - Zwraca błąd związany z identyfikatorem wyniku

pg_query
pg_result_error
Funkcje PostgreSQL


Zwraca błąd związany z identyfikatorem wyniku

pg_result_error_field
pg_result_seek
Funkcje PostgreSQL
PHP Manual

pg_result_error

(PHP 4 >= 4.2.0, PHP 5)

pg_result_error — Zwraca błąd związany z identyfikatorem wyniku

Opis

string pg_result_error ( resource $result )

pg_result_error() zwraca komunikat błędu związany z identyfikatorem wyniku result. Dzięki temu użytkownik ma większą szanse aby otrzymać właściwy komunikat niż przy użyciu pg_last_error().

Zobacz także pg_query(),
pg_send_query(),
pg_get_result(),
pg_last_error() i
pg_last_notice()

pg_result_error_field
pg_result_seek
Funkcje PostgreSQL


Set internal row offset in result resource

pg_result_error
pg_result_status
Funkcje PostgreSQL
PHP Manual

pg_result_seek

(PHP 4 >= 4.3.0, PHP 5)

pg_result_seek — Set internal row offset in result resource

Opis

bool pg_result_seek ( resource $result , int $offset )

pg_result_seek() sets the internal row offset in a result resource.

Parametry

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

offset

Row to move the internal offset to in the result resource. Rows are numbered starting from zero.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pg_result_seek() example

<?php

// Connect to the database
$conn = pg_pconnect("dbname=publisher");

// Execute a query
$result = pg_query($conn, "SELECT author, email FROM authors");

// Seek to the 3rd row (assuming there are 3 rows)
pg_result_seek($result, 2);

// Fetch the 3rd row
$row = pg_fetch_row($result);

?>

Zobacz też:

  • pg_fetch_row() - Pobiera wiersz jako tablicę z indeksami numerycznymi
  • pg_fetch_assoc() - Fetch a row as an associative array
  • pg_fetch_array() - Pobiera wiersz jako tablicę
  • pg_fetch_object() - Pobiera wiersz jako obiekt
  • pg_fetch_result() - Pobiera dane z wyniku

pg_result_error
pg_result_status
Funkcje PostgreSQL


Zwraca stan wyniku zapytania

pg_result_seek
pg_select
Funkcje PostgreSQL
PHP Manual

pg_result_status

(PHP 4 >= 4.2.0, PHP 5)

pg_result_status — Zwraca stan wyniku zapytania

Opis

mixed pg_result_status ( resource $wynik [, int $typ = PGSQL_STATUS_LONG ] )

pg_result_status() zwraca stan identyfikatora wyniku, lub oznaczenie dopełnienia komendy, związane z wynikiem

Parametry

wynik

Identyfikator wyniku zapytania PostgreSQL-a, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).

typ

Zarówno PGSQL_STATUS_LONG aby zwrócić liczbowy stan parametru wynik, jak i PGSQL_STATUS_STRING aby zwrócić oznaczenie parametru wynik. Jeśli nie podano, PGSQL_STATUS_LONG zostanie domyślnie użyte.

Zwracane wartości

Możliwe zwracane wartości to: PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR oraz PGSQL_FATAL_ERROR gdy określono PGSQL_STATUS_LONG. W przeciwnym wypadku łańcuch (ang. string) zawierający oznaczenie komendy PostgreSQL-a jest zwracany.

Rejestr zmian

Wersja | Opis
4.3.0 | Parametr typ został dodany.

Przykłady

Przykład #1 pg_result_status() - przykład

<?php

// Połącz się z bazą
$polaczenie = pg_pconnect("dbname=wydawca");

// Wykonaj COPY
$wynik = pg_query($polaczenie, "COPY autorzy FROM STDIN;");

// Pobierz stan wyniku
$stan = pg_result_status($wynik);

// Ustal stan
if ($stan == PGSQL_COPY_IN)
   echo "Kopiowanie rozpoczęło się.";
else
   echo "Kopiowanie nie powiodło się.";

?>

Powyższy przykład wyświetli:

Kopiowanie rozpoczęło się.

Zobacz też:

  • pg_connection_status() - Zwraca stan połączenia

pg_result_seek
pg_select
Funkcje PostgreSQL


Wybiera wiersze

pg_result_status
pg_send_execute
Funkcje PostgreSQL
PHP Manual

pg_select

(PHP 4 >= 4.3.0, PHP 5)

pg_select — Wybiera wiersze

Opis

mixed pg_select ( resource $identyfikator_połączenia , string $nazwa_tabeli , array $tablica_asocjacyjna [, int $opcje ] )

pg_select() wybiera wiersze określone przez tablicę tablica_asocjacyjna która zawiera dane w postaci: kolumna=>wartość. Jeśli zapytanie się powiedzie, zwraca tablicę zawierającą wszystkie wiersze i kolumny spełniające warunek określony przez tablica_asocjacyjna

Jeśli określono parametr opcje to funkcja, pg_convert() stosuje do tablicy tablica_asocjacyjna określone flagi.

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

identyfikator_połączenia

Identyfikator połączenia do bazy PostgreSQL.

nazwa_tabeli

Nazwa tabeli, z której będą wybrane wiersze.

tablica_asocjacyjna

Tablica (ang. array), której kluczami są nazwy pól w tabeli nazwa_tabeli, oraz której wartości są warunkami, które muszą spełniać wyszukiwane wiersze.

opcje

Dowolna kombinacja dowolnej ilości parametrów: PGSQL_CONV_FORCE_NULL, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DML_ASYNC oraz PGSQL_DML_STRING. Jeśli PGSQL_DML_STRING jest częścią podanego parametru opcje, zostanie zwrócony łańcuch zapytania.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Returns string if PGSQL_DML_STRING is passed via options.

Przykłady

Przykład #1 pg_select() example

<?php
  $db = pg_connect('dbname=foo');
  // This is safe, since $_POST is converted automatically
  $rec = pg_select($db, 'post_log', $_POST);
  if ($rec) {
      echo "Records selected\n";
      var_dump($rec);
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

Zobacz też:

  • pg_convert() - Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.

pg_result_status
pg_send_execute
Funkcje PostgreSQL


Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

pg_select
pg_send_prepare
Funkcje PostgreSQL
PHP Manual

pg_send_execute

(PHP 5 >= 5.1.0)

pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

Opis

bool pg_send_execute ( resource $connection , string $stmtname , array $params )

Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Zwracane wartości

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Przykłady

Przykład #1 Using pg_send_execute()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Prepare a query for execution
  if (!pg_connection_busy($dbconn)) {
    pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
    $res1 = pg_get_result($dbconn);
  }

  // Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
    $res2 = pg_get_result($dbconn);
  }

  // Execute the same prepared query, this time with a different parameter
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
    $res3 = pg_get_result($dbconn);
  }

?>

Zobacz też:

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion.
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion.
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_select
pg_send_prepare
Funkcje PostgreSQL


Sends a request to create a prepared statement with the given parameters, without waiting for completion.

pg_send_execute
pg_send_query_params
Funkcje PostgreSQL
PHP Manual

pg_send_prepare

(PHP 5 >= 5.1.0)

pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion.

Opis

bool pg_send_prepare ( resource $connection , string $stmtname , string $query )

Sends a request to create a prepared statement with the given parameters, without waiting for completion.

This is an asynchronous version of pg_prepare(): it returns TRUE if it was able to dispatch the request, and FALSE if not. After a successful call, call pg_get_result() to determine whether the server successfully created the prepared statement. The function's parameters are handled identically to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions of PostgreSQL.

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

Zwracane wartości

Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.

Przykłady

Przykład #1 Using pg_send_prepare()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Prepare a query for execution
  if (!pg_connection_busy($dbconn)) {
    pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
    $res1 = pg_get_result($dbconn);
  }

  // Execute the prepared query.  Note that it is not necessary to escape
  // the string "Joe's Widgets" in any way
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
    $res2 = pg_get_result($dbconn);
  }

  // Execute the same prepared query, this time with a different parameter
  if (!pg_connection_busy($dbconn)) {
    pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
    $res3 = pg_get_result($dbconn);
  }

?>

Zobacz też:

  • pg_connect() - Otwiera tymczasowe połączenie do PostgreSQL-a
  • pg_pconnect() - Otwiera trwałe połączenie z serwerem PostgreSQL
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result.
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
  • pg_send_query_params() - Submits a command and separate parameters to the server without waiting for the result(s).

pg_send_execute
pg_send_query_params
Funkcje PostgreSQL


Submits a command and separate parameters to the server without waiting for the result(s).

pg_send_prepare
pg_send_query
Funkcje PostgreSQL
PHP Manual

pg_send_query_params

(PHP 5 >= 5.1.0)

pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s).

Opis

bool pg_send_query_params ( resource $connection , string $query , array $params )

Submits a command and separate parameters to the server without waiting for the result(s).

This is equivalent to pg_send_query() except that query parameters can be specified separately from the query string. The function's parameters are handled identically to pg_query_params(). Like pg_query_params(), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string.

Parametry

connection

PostgreSQL database connection resource.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Use pg_get_result() to determine the query result.

Przykłady

Przykład #1 Using pg_send_query_params()

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  // Using parameters.  Note that it is not necessary to quote or escape
  // the parameter.
  pg_send_query_params($dbconn, 'select count(*) from authors where city = $1', array('Perth'));

  // Compare against basic pg_send_query usage
  $str = pg_escape_string('Perth');
  pg_send_query($dbconn, "select count(*) from authors where city = '${str}'");
?>

Zobacz też:

  • pg_send_query() - Wysyła zapytanie asynchroniczne

pg_send_prepare
pg_send_query
Funkcje PostgreSQL


Wysyła zapytanie asynchroniczne

pg_send_query_params
pg_set_client_encoding
Funkcje PostgreSQL
PHP Manual

pg_send_query

(PHP 4 >= 4.2.0, PHP 5)

pg_send_query — Wysyła zapytanie asynchroniczne

Opis

bool pg_send_query ( resource $identyfikator_połączenia , string $zapytanie )

pg_send_query() wysyła asynchroniczne zapytanie lub zapytania do połączenia określonego przez identyfikator_połączenia. W przeciwieństwie do pg_query(), pozwala wysłać jednorazowo wiele zapytań do PostgreSQL-a, na następnie pobrać wyniki jeden po drugim używając funkcji pg_get_result().

Wykonywanie skryptu nie jest blokowane w czasie wykonywania zapytań. Możesz użyć pg_connection_busy() aby sprawdzić czy połączenie jest nie jest zajęte (np. wykonuje się inne zapytanie). Zapytania mogą zostać przerwane przez użycie funkcji pg_cancel_query().

Tak więc użytkownik może wysłać wiele zapytań jednocześnie, ale nie może ich wysyłać jeśli połączenie jest zajęte. Jeśli zapytanie będzie wysłane gdy połączenie jest zajęte, będzie oczekiwało aż wykona się poprzednie zapytanie i utracone zostaną wszystkie wyniki.

Parametry

identyfikator_połączenia

Identyfikator połączenia do bazy PostgreSQL.

zapytanie

Instrukcja lub instrukcje SQL do wykonania.

Dane w zapytaniu powinny posiadać znaki unikowe.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Użyj pg_get_result(), aby ustalić wynik zapytania.

Przykłady

Przykład #1 Przykład pg_send_query()

<?php
  $polaczenie_z_baza = pg_connect("dbname=wydawca") or die("Nie można było się połączyć");

  if (!pg_connection_busy($polaczenie_z_baza)) {
      pg_send_query($polaczenie_z_baza, "select * from autorzy; select count(*) from autorzy;");
  }

  $wynik1 = pg_get_result($polaczenie_z_baza);
  echo "Pierwsze wywołanie pg_get_result(): $wynik1\n";
  $wiersze1 = pg_num_rows($wynik1);
  echo "$wynik1 ma $wiersze1 wpisów\n\n";

  $wynik2 = pg_get_result($polaczenie_z_baza);
  echo "Drugie wywołanie pg_get_result(): $wynik2\n";
  $wiersze2 = pg_num_rows($wynik2);
  echo "$wynik2 ma $wiersze2 wpisów\n";
?>

Powyższy przykład wyświetli:

Pierwsze wywołanie pg_get_result(): Resource id #3
Resource id #3 ma 8 wpisów

Drugie wywołanie pg_get_result(): Resource id #4
Resource id #4 ma 5 wpisów

Zobacz też:

  • pg_query() - Realizujezapytanie do bazy danych
  • pg_cancel_query() - Przerywa zapytanie asynchroniczne
  • pg_get_result() - Pobiera wynik zapytania asynchroniczego
  • pg_connection_busy() - Sprawdza czy połączenie jest zajęte czy wolne

pg_send_query_params
pg_set_client_encoding
Funkcje PostgreSQL


Ustawia stronę kodową klienta PostgreSQL-a

pg_send_query
pg_set_error_verbosity
Funkcje PostgreSQL
PHP Manual

pg_set_client_encoding

(PHP 4 >= 4.0.3, PHP 5)

pg_set_client_encoding — Ustawia stronę kodową klienta PostgreSQL-a

Opis

int pg_set_client_encoding ([ resource $connection ], string $encoding )

pg_set_client_encoding() ustawia stronę kodową klienta i zwraca 0 w razie powodzenia lub -1 w razie błedu.

encoding jest stroną kodową klienta i może przyjmować następujace wartości: SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250. Dostępne strony kodowe zależą od PostgreSQL-a i wersji libpq. Sprawdź w podręczniku PostgreSQL jakie są dostępne strony kodowe dla twojego PostgreSQL-a.

Informacja:

Ta funkcja wymaga PHP-4.0.3 lub nowszego i PostgreSQL-7.0 lub nowszego. Dostępne strony kodowe zależą od wersji PostgreSQL.

Ta funkcja była poprzednio nazwana pg_setclientencoding().

Zobacz także pg_client_encoding().

pg_send_query
pg_set_error_verbosity
Funkcje PostgreSQL


Determines the verbosity of messages returned by pg_last_error and pg_result_error.

pg_set_client_encoding
pg_trace
Funkcje PostgreSQL
PHP Manual

pg_set_error_verbosity

(PHP 5 >= 5.1.0)

pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

Opis

int pg_set_error_verbosity ([ resource $connection ], int $verbosity )

Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous setting. In PGSQL_ERRORS_TERSE mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

verbosity

The required verbosity: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Zwracane wartości

The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

Przykłady

Przykład #1 pg_set_error_verbosity() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");

  if (!pg_connection_busy($dbconn)) {
      pg_send_query($dbconn, "select * from doesnotexist;");
  }

  pg_set_error_verbosity($dbconn, PGSQL_ERRORS_VERBOSE);
  $res1 = pg_get_result($dbconn);
  echo pg_result_error($res1);
?>

Zobacz też:

  • pg_last_error() - Zwraca łańcuch ostatniego komunikatu błędu dla połączenia
  • pg_result_error() - Zwraca błąd związany z identyfikatorem wyniku

pg_set_client_encoding
pg_trace
Funkcje PostgreSQL


Uruchamia śledzenie połączeń z PostgreSQL

pg_set_error_verbosity
pg_transaction_status
Funkcje PostgreSQL
PHP Manual

pg_trace

(PHP 4 >= 4.0.1, PHP 5)

pg_trace — Uruchamia śledzenie połączeń z PostgreSQL

Opis

bool pg_trace ( string $pathname [, string $mode [, resource $connection ]] )

pg_trace() uruchamia śledzenie połączeń między klientem a serwerem PostgreSQL-a. Wynik śledzenia jest zapisywany do pliku wskazanego przez pathname. Aby w pełni zrozumieć wyniki śledzenia potrzebna jest wiedza o szczegółach wewnętrznej komunikacji PostgreSQL-a. Nieobeznani z tymi szczegółami, mogą jednak wykorzystać tą funkcję do śledzenia błędów w zapytaniach wysyłanych do serwera. Przykładowo, wykonując grep '^To backend' trace.log można zobaczyć zapytania które były wysłane do serwera. Więcej szczegółow można dowiedzieć się z podręcznika PostgreSQL-a.

Parametry pathname i mode są takie same jak dla funkcji fopen() (domyślną wartością mode jest 'w'), connection wskazuje identyfikator połączenia które ma być śledzone. Domyślnie przyjmowane jest ostatnio otwarte.

Funkcja zwraca TRUE jeśli pathname został pomyslnie otwarty do logowania lub FALSE w przeciwnym wypadku.

Zobacz także fopen() i pg_untrace().

pg_set_error_verbosity
pg_transaction_status
Funkcje PostgreSQL


Returns the current in-transaction status of the server.

pg_trace
pg_tty
Funkcje PostgreSQL
PHP Manual

pg_transaction_status

(PHP 5 >= 5.1.0)

pg_transaction_status — Returns the current in-transaction status of the server.

Opis

int pg_transaction_status ( resource $connection )

Returns the current in-transaction status of the server.

Uwaga

pg_transaction_status() will give incorrect results when using a PostgreSQL 7.3 server that has the parameter autocommit set to off. The server-side autocommit feature has been deprecated and does not exist in later server versions.

Parametry

connection

PostgreSQL database connection resource.

Zwracane wartości

The status can be PGSQL_TRANSACTION_IDLE (currently idle), PGSQL_TRANSACTION_ACTIVE (a command is in progress), PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block), or PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block). PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad. PGSQL_TRANSACTION_ACTIVE is reported only when a query has been sent to the server and not yet completed.

Przykłady

Przykład #1 pg_transaction_status() example

<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_transaction_status($dbconn);
  if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
      echo 'Connection is bad';
  } else if ($stat === PGSQL_TRANSACTION_IDLE) {
      echo 'Connection is currently idle';
  } else {
      echo 'Connection is in a transaction state';
  }
?>

pg_trace
pg_tty
Funkcje PostgreSQL


Zwraca nazwę konsoli tty związanej z połączeniem

pg_transaction_status
pg_unescape_bytea
Funkcje PostgreSQL
PHP Manual

pg_tty

(PHP 4, PHP 5)

pg_tty — Zwraca nazwę konsoli tty związanej z połączeniem

Opis

string pg_tty ( resource $connection )

pg_tty() zwraca nazwę konsoli tty którą serwer PostgreSQL wykorzystuje do debugowania połączenia wskazanego przez connection.

pg_transaction_status
pg_unescape_bytea
Funkcje PostgreSQL


Unescape binary for bytea type

pg_tty
pg_untrace
Funkcje PostgreSQL
PHP Manual

pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5)

pg_unescape_bytea — Unescape binary for bytea type

Opis

string pg_unescape_bytea ( string $data )

pg_unescape_bytea() unescapes PostgreSQL bytea data values. It returns the unescaped string, possibly containing binary data.

Informacja:

When you SELECT a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually.

This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. INSERT INTO test_table (image) VALUES ('$image_escaped'::bytea); PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error.

Parametry

data

A string containing PostgreSQL bytea data to be converted into a PHP binary string.

Zwracane wartości

A string containing the unescaped data.

Przykłady

Przykład #1 pg_unescape_bytea() example

<?php
  // Connect to the database
  $dbconn = pg_connect('dbname=foo');

  // Get the bytea data
  $res = pg_query("SELECT data FROM gallery WHERE name='Pine trees'");
  $raw = pg_fetch_result($res, 'data');

  // Convert to binary and send to the browser
  header('Content-type: image/jpeg');
  echo pg_unescape_bytea($raw);
?>

Zobacz też:

  • pg_escape_bytea() - Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea
  • pg_escape_string() - Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape

pg_tty
pg_untrace
Funkcje PostgreSQL


Wyłącza śledzenie połączeń PostgreSQL-a

pg_unescape_bytea
pg_update
Funkcje PostgreSQL
PHP Manual

pg_untrace

(PHP 4 >= 4.0.1, PHP 5)

pg_untrace — Wyłącza śledzenie połączeń PostgreSQL-a

Opis

bool pg_untrace ([ resource $connection ] )

Wyłącza śledzenie połączeń uruchomione przez pg_trace(). connection wskazuje połączenie które było śledzone, domyślnie przyjmowane jest ostatnio otwarte.

Zawsze zwraca TRUE.

Zobacz także pg_trace().

pg_unescape_bytea
pg_update
Funkcje PostgreSQL


Aktualizuje tabelę

pg_untrace
pg_version
Funkcje PostgreSQL
PHP Manual

pg_update

(PHP 4 >= 4.3.0, PHP 5)

pg_update — Aktualizuje tabelę

Opis

mixed pg_update ( resource $identyfikator_połączenia , string $nazwa_tabeli , array $dane , array $warunek [, int $opcje ] )

pg_update() aktualizuje wiersze spełniające warunki zawarte w parametrze warunek używając danych z parametru dane. Jeśli jest użyty parametr opcje, jest on przekazywany do wywołania pg_convert() z opcjami w parametrze dane.

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

identyfikator_połączenia

Identyfikator połączenia do bazy PostgreSQL.

nazwa_tabeli

Nazwa tabeli, w której będą aktualizowane wiersze.

dane

Tablica (ang. array), której klucze są nazwami kolumn w tabeli nazwa_tabeli, oraz której wartości są nową zawartością pasujących do warunków wierszy.

warunek

Tablica (ang. array), której klucze są nazwami kolumn w tabeli nazwa_tabeli, oraz której wartości są warunkami, jakie muszą spełnić uaktualniane wiersze.

opcje

Dowolna kombinacja dowolnej ilości parametrów: PGSQL_CONV_OPTS, PGSQL_DML_NO_CONV, PGSQL_DML_EXEC oraz PGSQL_DML_STRING. Jeśli PGSQL_DML_STRING został podany w parametrze opcje, zostanie zwrócony łańcuch zapytania.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Zwraca łańcuch (ang. string) gdy PGSQL_DML_STRING został podany poprzez opcje.

Przykłady

Przykład #1 pg_update() - przykład

<?php
  $polaczenie = pg_connect ('dbname=foo');
  $dane = array('kolumna1'=>'AA', 'kolumna2'=>'BB');

  // To jest bezpieczne, gdyż $_POST jest konwertowane automatycznie
  $res = pg_update($polaczenie, 'kopia_post', $_POST, $dane);
  if ($res) {
      echo "Dane zostały zaktualizowane: $res\n";
  } else {
      echo "Użytkownik wprowadził błędne dane\n";
  }
?>

Zobacz też:

  • pg_convert() - Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.

pg_untrace
pg_version
Funkcje PostgreSQL


Returns an array with client, protocol and server version (when available)

pg_update
SQLite
Funkcje PostgreSQL
PHP Manual

pg_version

(PHP 5)

pg_version — Returns an array with client, protocol and server version (when available)

Opis

array pg_version ([ resource $connection ] )

pg_version() returns an array with the client, protocol and server version. Protocol and server versions are only available if PHP was compiled with PostgreSQL 7.4 or later.

For more detailed server information, use pg_parameter_status().

Parametry

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Zwracane wartości

Returns an array with client, protocol and server keys and values (if available). Returns FALSE on error or invalid connection.

Przykłady

Przykład #1 pg_version() example

<?php
  $dbconn = pg_connect("host=localhost port=5432 dbname=mary")
     or die("Could not connect");

  $v = pg_version($dbconn);

  echo $v['client'];
?>

Powyższy przykład wyświetli:

7.4

Zobacz też:

  • pg_parameter_status() - Looks up a current parameter setting of the server.

pg_update
SQLite
Funkcje PostgreSQL


SQLite

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • SQLite Funkcje
    • sqlite_array_query — Execute a query against a given database and returns an array
    • sqlite_busy_timeout — Set busy timeout duration, or disable busy handlers
    • sqlite_changes — Returns the number of rows that were changed by the most recent SQL statement
    • sqlite_close — Closes an open SQLite database
    • sqlite_column — Fetches a column from the current row of a result set
    • sqlite_create_aggregate — Register an aggregating UDF for use in SQL statements
    • sqlite_create_function — Registers a "regular" User Defined Function for use in SQL statements
    • sqlite_current — Fetches the current row from a result set as an array
    • sqlite_error_string — Returns the textual description of an error code
    • sqlite_escape_string — Escapes a string for use as a query parameter
    • sqlite_exec — Executes a result-less query against a given database
    • sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object
    • sqlite_fetch_all — Fetches all rows from a result set as an array of arrays
    • sqlite_fetch_array — Fetches the next row from a result set as an array
    • sqlite_fetch_column_types — Return an array of column types from a particular table
    • sqlite_fetch_object — Fetches the next row from a result set as an object
    • sqlite_fetch_single — Fetches the first column of a result set as a string
    • sqlite_fetch_string — Alias dla sqlite_fetch_single
    • sqlite_field_name — Returns the name of a particular field
    • sqlite_has_more — Finds whether or not more rows are available
    • sqlite_has_prev — Returns whether or not a previous row is available
    • sqlite_key — Returns the current row index
    • sqlite_last_error — Returns the error code of the last error for a database
    • sqlite_last_insert_rowid — Returns the rowid of the most recently inserted row
    • sqlite_libencoding — Returns the encoding of the linked SQLite library
    • sqlite_libversion — Returns the version of the linked SQLite library
    • sqlite_next — Seek to the next row number
    • sqlite_num_fields — Returns the number of fields in a result set
    • sqlite_num_rows — Returns the number of rows in a buffered result set
    • sqlite_open — Opens an SQLite database and create the database if it does not exist
    • sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist
    • sqlite_prev — Seek to the previous row number of a result set
    • sqlite_query — Executes a query against a given database and returns a result handle
    • sqlite_rewind — Seek to the first row number
    • sqlite_seek — Seek to a particular row number of a buffered result set
    • sqlite_single_query — Executes a query and returns either an array for one single column or the value of the first row
    • sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF
    • sqlite_udf_encode_binary — Encode binary data before returning it from an UDF
    • sqlite_unbuffered_query — Execute a query that does not prefetch and buffer all data
    • sqlite_valid — Returns whether more rows are available
pg_version
Wstęp
Rozszerzenia producentów baz danych


Wstęp

This is an extension for the SQLite Embeddable SQL Database Engine. SQLite is a C library that implements an embeddable SQL database engine. Programs that link with the SQLite library can have SQL database access without running a separate RDBMS process.

SQLite is not a client library used to connect to a big database server. SQLite is the server. The SQLite library reads and writes directly to and from the database files on disk.

Informacja:

For further information see the SQLite Website (» http://sqlite.org/).

SQLite
Instalacja/Konfiguracja
SQLite


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SQLite


Wymagania

The SQLite extension is enabled by default as of PHP 5.0. Beginning with PHP 5.4, the SQLite extension is available only via PECL.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Since PHP 5.0 this extension was bundled with PHP. Beginning with PHP 5.4, this extension is available only via PECL.

Windows users must enable php_sqlite.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/

Windows builds must also enable PDO because as of PHP 5.1.0 it depends on it. So, php.ini will end up with something like this:

extension=php_pdo.dll
extension=php_sqlite.dll
On Linux or Unix operating systems, if you build PDO as a shared extension, you must build SQLite as a shared extension using the --with-sqlite=shared configure option.

The PHP 5.0.x series of Windows builds enabled this extension by default, where no DLL file is necessary.

SQLite 3 is supported through PDO SQLite.

Informacja: Windows installation for unprivileged accounts

On Windows operating systems, unprivileged accounts don't have the TMP environment variable set by default. This will make sqlite create temporary files in the windows directory, which is not desirable. So, you should set the TMP environment variable for the web server or the user account the web server is running under. If Apache is your web server, you can accomplish this via a SetEnv directive in your httpd.conf file. For example:

SetEnv TMP c:/temp
If you are unable to establish this setting at the server level, you can implement the setting in your script:
<?php
putenv('TMP=C:/temp');
?>
The setting must refer to a directory that the web server has permission to create files in and subsequently write to and delete the files it created. Otherwise, you may receive the following error message: malformed database schema - unable to open a temporary database file for storing temporary tables

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

SQLite Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Changelog
sqlite.assoc_case | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

sqlite.assoc_case int

Whether to use mixed case (0), upper case (1) or lower case (2) hash indexes.

This option is primarily useful when you need compatibility with other database systems, where the names of the columns are always returned as uppercase or lowercase, regardless of the case of the actual field names in the database schema.

The SQLite library returns the column names in their natural case (that matches the case you used in your schema). When sqlite.assoc_case is set to 0 the natural case will be preserved. When it is set to 1 or 2, PHP will apply case folding on the hash keys to upper- or lower-case the keys, respectively.

Use of this option incurs a slight performance penalty, but is MUCH faster than performing the case folding yourself using PHP script.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

There are two resources used in the SQLite Interface. The first one is the database connection, the second one the result set.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

The functions sqlite_fetch_array() and sqlite_current() use a constant for the different types of result arrays. The following constants are defined:

SQLite result type constants
SQLITE_ASSOC (int)
Columns are returned into the array having the field name as the array index.
SQLITE_BOTH (int)
Columns are returned into the array having both a numerical index and the field name as the array index.
SQLITE_NUM (int)
Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

A number of functions may return status codes. The following constants are defined:

SQLite status code constants
SQLITE_OK (int)
Successful result.
SQLITE_ERROR (int)
SQL error or missing database.
SQLITE_INTERNAL (int)
An internal logic error in SQLite.
SQLITE_PERM (int)
Access permission denied.
SQLITE_ABORT (int)
Callback routine requested an abort.
SQLITE_BUSY (int)
The database file is locked.
SQLITE_LOCKED (int)
A table in the database is locked.
SQLITE_NOMEM (int)
Memory allocation failed.
SQLITE_READONLY (int)
Attempt to write a readonly database.
SQLITE_INTERRUPT (int)
Operation terminated internally.
SQLITE_IOERR (int)
Disk I/O error occurred.
SQLITE_NOTADB (int)
File opened that is not a database file.
SQLITE_CORRUPT (int)
The database disk image is malformed.
SQLITE_FORMAT (int)
Auxiliary database format error.
SQLITE_NOTFOUND (int)
(Internal) Table or record not found.
SQLITE_FULL (int)
Insertion failed because database is full.
SQLITE_CANTOPEN (int)
Unable to open the database file.
SQLITE_PROTOCOL (int)
Database lock protocol error.
SQLITE_EMPTY (int)
(Internal) Database table is empty.
SQLITE_SCHEMA (int)
The database schema changed.
SQLITE_TOOBIG (int)
Too much data for one row of a table.
SQLITE_CONSTRAINT (int)
Abort due to constraint violation.
SQLITE_MISMATCH (int)
Data type mismatch.
SQLITE_MISUSE (int)
Library used incorrectly.
SQLITE_NOLFS (int)
Uses of OS features not supported on host.
SQLITE_AUTH (int)
Authorized failed.
SQLITE_ROW (int)
Internal process has another row ready.
SQLITE_DONE (int)
Internal process has finished executing.
Typy zasobów
SQLite Funkcje
SQLite


SQLite Funkcje

Klasy predefiniowane

SQLiteDatabase

Represents an opened SQLite database.

Konstruktor

  • __construct - construct a new SQLiteDatabase object

Metody

  • query - Execute a query
  • queryExec - Execute a result-less query
  • arrayQuery - Execute a query and return the result as an array
  • singleQuery - Execute a query and return either an array for one single column or the value of the first row
  • unbufferedQuery - Execute an unbuffered query
  • lastInsertRowid - Returns the rowid of the most recently inserted row
  • changes - Returns the number of rows changed by the most recent statement
  • createAggregate - Register an aggregating UDF for use in SQL statements
  • createFunction - Register a UDF for use in SQL statements
  • busyTimeout - Sets or disables busy timeout duration
  • lastError - Returns the last error code of the most recently encountered error
  • fetchColumnTypes - Return an array of column types from a particular table

SQLiteResult

Represents a buffered SQLite result set.

Metody

  • fetch - Fetches the next row from the result set as an array
  • fetchObject - Fetches the next row from the result set as an object
  • fetchSingle - Fetches the first column from the result set as a string
  • fetchAll - Fetches all rows from the result set as an array of arrays
  • column - Fetches a column from the current row of the result set
  • numFields - Returns the number of fields in the result set
  • fieldName - Returns the name of a particular field in the result set
  • current - Fetches the current row from the result set as an array
  • key - Return the current row index
  • next - Seek to the next row number
  • valid - Returns whether more rows are available
  • rewind - Seek to the first row number of the result set
  • prev - Seek to the previous row number of the result set
  • hasPrev - Returns whether or not a previous row is available
  • numRows - Returns the number of rows in the result set
  • seek - Seek to a particular row number

SQLiteUnbuffered

Represents an unbuffered SQLite result set. Unbuffered results sets are sequential, forward-seeking only.

Metody

  • fetch - Fetches the next row from the result set as an array
  • fetchObject - Fetches the next row from the result set as an object
  • fetchSingle - Fetches the first column from the result set as a string
  • fetchAll - Fetches all rows from the result set as an array of arrays
  • column - Fetches a column from the current row of the result set
  • numFields - Returns the number of fields in the result set
  • fieldName - Returns the name of a particular field in the result set
  • current - Fetches the current row from the result set as an array
  • next - Seek to the next row number
  • valid - Returns whether more rows are available

Spis treści

  • sqlite_array_query — Execute a query against a given database and returns an array
  • sqlite_busy_timeout — Set busy timeout duration, or disable busy handlers
  • sqlite_changes — Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_close — Closes an open SQLite database
  • sqlite_column — Fetches a column from the current row of a result set
  • sqlite_create_aggregate — Register an aggregating UDF for use in SQL statements
  • sqlite_create_function — Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_current — Fetches the current row from a result set as an array
  • sqlite_error_string — Returns the textual description of an error code
  • sqlite_escape_string — Escapes a string for use as a query parameter
  • sqlite_exec — Executes a result-less query against a given database
  • sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object
  • sqlite_fetch_all — Fetches all rows from a result set as an array of arrays
  • sqlite_fetch_array — Fetches the next row from a result set as an array
  • sqlite_fetch_column_types — Return an array of column types from a particular table
  • sqlite_fetch_object — Fetches the next row from a result set as an object
  • sqlite_fetch_single — Fetches the first column of a result set as a string
  • sqlite_fetch_string — Alias dla sqlite_fetch_single
  • sqlite_field_name — Returns the name of a particular field
  • sqlite_has_more — Finds whether or not more rows are available
  • sqlite_has_prev — Returns whether or not a previous row is available
  • sqlite_key — Returns the current row index
  • sqlite_last_error — Returns the error code of the last error for a database
  • sqlite_last_insert_rowid — Returns the rowid of the most recently inserted row
  • sqlite_libencoding — Returns the encoding of the linked SQLite library
  • sqlite_libversion — Returns the version of the linked SQLite library
  • sqlite_next — Seek to the next row number
  • sqlite_num_fields — Returns the number of fields in a result set
  • sqlite_num_rows — Returns the number of rows in a buffered result set
  • sqlite_open — Opens an SQLite database and create the database if it does not exist
  • sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist
  • sqlite_prev — Seek to the previous row number of a result set
  • sqlite_query — Executes a query against a given database and returns a result handle
  • sqlite_rewind — Seek to the first row number
  • sqlite_seek — Seek to a particular row number of a buffered result set
  • sqlite_single_query — Executes a query and returns either an array for one single column or the value of the first row
  • sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF
  • sqlite_udf_encode_binary — Encode binary data before returning it from an UDF
  • sqlite_unbuffered_query — Execute a query that does not prefetch and buffer all data
  • sqlite_valid — Returns whether more rows are available
Stałe predefiniowane
sqlite_array_query
SQLite


Execute a query against a given database and returns an array

SQLite Funkcje
sqlite_busy_timeout
SQLite Funkcje
PHP Manual

sqlite_array_query

SQLiteDatabase::arrayQuery

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_array_query -- SQLiteDatabase::arrayQuery — Execute a query against a given database and returns an array

Opis

array sqlite_array_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
array sqlite_array_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Styl obiektowy (method):

array SQLiteDatabase::arrayQuery ( string $query [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

sqlite_array_query() executes the given query and returns an array of the entire result set. It is similar to calling sqlite_query() and then sqlite_fetch_array() for each row in the result set. sqlite_array_query() is significantly faster than the aforementioned.

Wskazówka

sqlite_array_query() is best suited to queries returning 45 rows or less. If you have more data than that, it is recommended that you write your scripts to use sqlite_unbuffered_query() instead for more optimal performance.

Parametry

query

The query to be executed.

Data inside the query should be properly escaped.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

Opcjonalny parametr result_type przyjmuje wartości stałych i określa jak indeksowane będą zwracane wartości. Używając SQLITE_ASSOC zwrócone zostaną tylko indeksy asocjacyjne (nazwy pól), podczas gdy SQLITE_NUM zwróci tylko indeksy numeryczne (numery pól). SQLITE_BOTH zwróci i indeksy asocjacyjne i numeryczne. SQLITE_BOTH jest domyślną wartością dla tej funkcji.

decode_binary

Gdy parametr decode_binary zostanie ustawiony na TRUE (domyślnie), PHP zdekoduje kodowanie binarne, któremu zostały poddane dane, jeśli były kodowane przy użyciu funkcji sqlite_escape_string(). Zazwyczaj należy pozostawić domyślną wartość tego parametru, chyba że baza jest współużytkowana przez różne aplikacje.

Informacja: Obsługiwane są dwie alternatywne składnie, dla zachowania kompatybilności z rozszerzeniami dla innych baz danych (takich jak MySQL). Preferowana jest pierwsza, gdzie dbhandle jest pierwszym parametrem funkcji.

Zwracane wartości

Returns an array of the entire result set; FALSE otherwise.

Wielkość liter w nazwach kolumn zwróconych przez SQLITE_ASSOC i SQLITE_BOTH zostaną przetworzone zależnie od ustawienia opcji konfiguracji sqlite.assoc_case.

Przykłady

Przykład #1 Styl proceduralny

<?php
$dbhandle = sqlite_open('sqlitedb');
$result = sqlite_array_query($dbhandle, 'SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Przykład #2 Object-oriented style

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$result = $dbhandle->arrayQuery('SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Zobacz też:

  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_fetch_array() - Fetches the next row from a result set as an array
  • sqlite_fetch_string() - Alias dla sqlite_fetch_single

SQLite Funkcje
sqlite_busy_timeout
SQLite Funkcje


Set busy timeout duration, or disable busy handlers

sqlite_array_query
sqlite_changes
SQLite Funkcje
PHP Manual

sqlite_busy_timeout

SQLiteDatabase::busyTimeout

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_busy_timeout -- SQLiteDatabase::busyTimeout — Set busy timeout duration, or disable busy handlers

Opis

void sqlite_busy_timeout ( resource $dbhandle , int $milliseconds )

Styl obiektowy (method):

void SQLiteDatabase::busyTimeout ( int $milliseconds )

Set the maximum time, in milliseconds, that SQLite will wait for a dbhandle to become ready for use.

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

milliseconds

The number of milliseconds. When set to 0, busy handlers will be disabled and SQLite will return immediately with a SQLITE_BUSY status code if another process/thread has the database locked for an update.

PHP sets the default busy timeout to be 60 seconds when the database is opened.

Informacja:

There are one thousand (1000) milliseconds in one second.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl proceduralny

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle, 10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle, 0); // disable busy handler
?>

Przykład #2 Styl obiektowy

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>

Zobacz też:

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist

sqlite_array_query
sqlite_changes
SQLite Funkcje


Returns the number of rows that were changed by the most recent SQL statement

sqlite_busy_timeout
sqlite_close
SQLite Funkcje
PHP Manual

sqlite_changes

SQLiteDatabase::changes

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_changes -- SQLiteDatabase::changes — Returns the number of rows that were changed by the most recent SQL statement

Opis

int sqlite_changes ( resource $dbhandle )

Styl obiektowy (method):

int SQLiteDatabase::changes ( void )

Returns the numbers of rows that were changed by the most recent SQL statement executed against the dbhandle database handle.

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Zwracane wartości

Returns the number of changed rows.

Przykłady

Przykład #1 Styl proceduralny

<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_query($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>

Przykład #2 Styl obiektowy

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

Zobacz też:

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist

sqlite_busy_timeout
sqlite_close
SQLite Funkcje


Closes an open SQLite database

sqlite_changes
sqlite_column
SQLite Funkcje
PHP Manual

sqlite_close

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_close — Closes an open SQLite database

Opis

void sqlite_close ( resource $dbhandle )

Closes the given db_handle database handle. If the database was persistent, it will be closed and removed from the persistent list.

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 sqlite_close() example

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?>

Zobacz też:

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_changes
sqlite_column
SQLite Funkcje


Fetches a column from the current row of a result set

sqlite_close
sqlite_create_aggregate
SQLite Funkcje
PHP Manual

sqlite_column

SQLiteResult::column

SQLiteUnbuffered::column

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_column -- SQLiteResult::column -- SQLiteUnbuffered::column — Fetches a column from the current row of a result set

Opis

mixed sqlite_column ( resource $result , mixed $index_or_name [, bool $decode_binary = true ] )
mixed SQLiteResult::column ( mixed $index_or_name [, bool $decode_binary = true ] )
mixed SQLiteUnbuffered::column ( mixed $index_or_name [, bool $decode_binary = true ] )

Fetches the value of a column named index_or_name (if it is a string), or of the ordinal column numbered index_or_name (if it is an integer) from the current row of the query result handle result.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

index_or_name

The column index or name to fetch.

decode_binary

Gdy parametr decode_binary zostanie ustawiony na TRUE (domyślnie), PHP zdekoduje kodowanie binarne, któremu zostały poddane dane, jeśli były kodowane przy użyciu funkcji sqlite_escape_string(). Zazwyczaj należy pozostawić domyślną wartość tego parametru, chyba że baza jest współużytkowana przez różne aplikacje.

Zwracane wartości

Returns the column value.

Notatki

Informacja:

Use this function when you are iterating a large result set with many columns, or with columns that contain large amounts of data.

Zobacz też:

  • sqlite_fetch_string() - Alias dla sqlite_fetch_single

sqlite_close
sqlite_create_aggregate
SQLite Funkcje


Register an aggregating UDF for use in SQL statements

sqlite_column
sqlite_create_function
SQLite Funkcje
PHP Manual

sqlite_create_aggregate

SQLiteDatabase::createAggregate

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_create_aggregate -- SQLiteDatabase::createAggregate — Register an aggregating UDF for use in SQL statements

Opis

void sqlite_create_aggregate ( resource $dbhandle , string $function_name , callback $step_func , callback $finalize_func [, int $num_args = -1 ] )

Styl obiektowy (method):

void SQLiteDatabase::createAggregate ( string $function_name , callback $step_func , callback $finalize_func [, int $num_args = -1 ] )

sqlite_create_aggregate() is similar to sqlite_create_function() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this function and sqlite_create_function() is that two functions are required to manage the aggregate; step_func is called for each row of the result set. Your PHP function should accumulate the result and store it into the aggregation context. Once all the rows have been processed, finalize_func will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set. Function parameters are &$context, $value, ....

finalize_func

Callback function to aggregate the "stepped" data from each row. Function parameter is &$context and the function should return the final result of aggregation.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$dbhandle = sqlite_open(':memory:');
sqlite_query($dbhandle, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($dbhandle, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string)
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context)
{
    return $context;
}

sqlite_create_aggregate($dbhandle, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($dbhandle, 'SELECT max_len(a) from strings'));

?>

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Informacja:

The example above will not work correctly if the column contains binary data. Take a look at the manual page for sqlite_udf_decode_binary() for an explanation of why this is so, and an example of how to make it respect the binary encoding.

Wskazówka

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Wskazówka

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

Zobacz też:

  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF
  • sqlite_udf_decode_binary() - Decode binary data passed as parameters to an UDF

sqlite_column
sqlite_create_function
SQLite Funkcje


Registers a "regular" User Defined Function for use in SQL statements

sqlite_create_aggregate
sqlite_current
SQLite Funkcje
PHP Manual

sqlite_create_function

SQLiteDatabase::createFunction

(PHP 5, sqlite >= 1.0.0)

sqlite_create_function -- SQLiteDatabase::createFunction — Registers a "regular" User Defined Function for use in SQL statements

Opis

void sqlite_create_function ( resource $dbhandle , string $function_name , callback $callback [, int $num_args = -1 ] )

Styl obiektowy (method):

void SQLiteDatabase::createFunction ( string $function_name , callback $callback [, int $num_args = -1 ] )

sqlite_create_function() allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Informacja: Callback functions should return a type understood by SQLite (i.e. scalar type).

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Informacja: Obsługiwane są dwie alternatywne składnie, dla zachowania kompatybilności z rozszerzeniami dla innych baz danych (takich jak MySQL). Preferowana jest pierwsza, gdzie dbhandle jest pierwszym parametrem funkcji.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 sqlite_create_function() example

<?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    sqlite_create_function($dbhandle, 'md5rev', 'md5_and_reverse', 1);

    $sql  = 'SELECT md5rev(filename) FROM files';
    $rows = sqlite_array_query($dbhandle, $sql);
} else {
    echo 'Error opening sqlite db: ' . $sqliteerror;
    exit;
}
?>

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach loop after you have queried for the data.

PHP registers a special function named php when the database is first opened. The php function can be used to call any PHP function without having to register it first.

Przykład #2 Example of using the PHP function

<?php
$rows = sqlite_array_query($dbhandle, "SELECT php('md5', filename) from files");
?>

This example will call the md5() on each filename column in the database and return the result into $rows

Informacja:

For performance reasons, PHP will not automatically encode/decode binary data passed to and from your UDF's. You need to manually encode/decode the parameters and return values if you need to process binary data in this way. Take a look at sqlite_udf_encode_binary() and sqlite_udf_decode_binary() for more details.

Wskazówka

It is not recommended to use UDF's to handle processing of binary data, unless high performance is not a key requirement of your application.

Wskazówka

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

Zobacz też:

  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

sqlite_create_aggregate
sqlite_current
SQLite Funkcje


Fetches the current row from a result set as an array

sqlite_create_function
sqlite_error_string
SQLite Funkcje
PHP Manual

sqlite_current

SQLiteResult::current

SQLiteUnbuffered::current

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_current -- SQLiteResult::current -- SQLiteUnbuffered::current — Fetches the current row from a result set as an array

Opis

array sqlite_current ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Styl obiektowy (method):

array SQLiteResult::current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
array SQLiteUnbuffered::current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

sqlite_current() is identical to sqlite_fetch_array() except that it does not advance to the next row prior to returning the data; it returns the data from the current position only.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

Opcjonalny parametr result_type przyjmuje wartości stałych i określa jak indeksowane będą zwracane wartości. Używając SQLITE_ASSOC zwrócone zostaną tylko indeksy asocjacyjne (nazwy pól), podczas gdy SQLITE_NUM zwróci tylko indeksy numeryczne (numery pól). SQLITE_BOTH zwróci i indeksy asocjacyjne i numeryczne. SQLITE_BOTH jest domyślną wartością dla tej funkcji.

decode_binary

Gdy parametr decode_binary zostanie ustawiony na TRUE (domyślnie), PHP zdekoduje kodowanie binarne, któremu zostały poddane dane, jeśli były kodowane przy użyciu funkcji sqlite_escape_string(). Zazwyczaj należy pozostawić domyślną wartość tego parametru, chyba że baza jest współużytkowana przez różne aplikacje.

Zwracane wartości

Returns an array of the current row from a result set; FALSE if the current position is beyond the final row.

Wielkość liter w nazwach kolumn zwróconych przez SQLITE_ASSOC i SQLITE_BOTH zostaną przetworzone zależnie od ustawienia opcji konfiguracji sqlite.assoc_case.

Zobacz też:

  • sqlite_seek() - Seek to a particular row number of a buffered result set
  • sqlite_next() - Seek to the next row number
  • sqlite_fetch_array() - Fetches the next row from a result set as an array

sqlite_create_function
sqlite_error_string
SQLite Funkcje


Returns the textual description of an error code

sqlite_current
sqlite_escape_string
SQLite Funkcje
PHP Manual

sqlite_error_string

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_error_string — Returns the textual description of an error code

Opis

string sqlite_error_string ( int $error_code )

Returns a human readable description of the error_code returned from sqlite_last_error().

Parametry

error_code

The error code being used, which might be passed in from sqlite_last_error().

Zwracane wartości

Returns a human readable description of the error_code, as a string.

Zobacz też:

  • sqlite_last_error() - Returns the error code of the last error for a database

sqlite_current
sqlite_escape_string
SQLite Funkcje


Escapes a string for use as a query parameter

sqlite_error_string
sqlite_exec
SQLite Funkcje
PHP Manual

sqlite_escape_string

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_escape_string — Escapes a string for use as a query parameter

Opis

string sqlite_escape_string ( string $item )

sqlite_escape_string() will correctly quote the string specified by item for use in an SQLite SQL statement. This includes doubling up single-quote characters (') and checking for binary-unsafe characters in the query string.

Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data. In practice, this shouldn't be a problem, as your schema should be such that you don't use such things on binary columns (in fact, it might be better to store binary data using other means, such as in files).

Parametry

item

The string being quoted.

If the item contains a NUL character, or if it begins with a character whose ordinal value is 0x01, PHP will apply a binary encoding scheme so that you can safely store and retrieve binary data.

Zwracane wartości

Returns an escaped string for use in an SQLite SQL statement.

Notatki

Informacja:

    Do not use this function to encode the return values from UDF's created
    using sqlite_create_function() or
    sqlite_create_aggregate() - use
    sqlite_udf_encode_binary() instead.

Ostrzeżenie

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

Zobacz też:

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF

sqlite_error_string
sqlite_exec
SQLite Funkcje


Executes a result-less query against a given database

sqlite_escape_string
sqlite_factory
SQLite Funkcje
PHP Manual

sqlite_exec

SQLiteDatabase::exec

(PHP 5, PECL sqlite >= 1.0.3)

sqlite_exec -- SQLiteDatabase::exec — Executes a result-less query against a given database

Opis

bool sqlite_exec ( resource $dbhandle , string $query [, string &$error_msg ] )
bool sqlite_exec ( string $query , resource $dbhandle )

Styl obiektowy (method):

bool SQLiteDatabase::queryExec ( string $query [, string &$error_msg ] )

Executes an SQL statement given by the query against a given database handle (specified by the dbhandle parameter).

Ostrzeżenie

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script.

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Informacja: Obsługiwane są dwie alternatywne składnie, dla zachowania kompatybilności z rozszerzeniami dla innych baz danych (takich jak MySQL). Preferowana jest pierwsza, gdzie dbhandle jest pierwszym parametrem funkcji.

Zwracane wartości

This function will return a boolean result; TRUE for success or FALSE for failure. If you need to run a query that returns rows, see sqlite_query().

Wielkość liter w nazwach kolumn zwróconych przez SQLITE_ASSOC i SQLITE_BOTH zostaną przetworzone zależnie od ustawienia opcji konfiguracji sqlite.assoc_case.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the error_msg parameter

Przykłady

Przykład #1 Procedural example

<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_exec($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
    exit("Error in query: '$error'");
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>

Przykład #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->queryExec("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
    exit("Error in query: '$error'");
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

Zobacz też:

  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_unbuffered_query() - Execute a query that does not prefetch and buffer all data
  • sqlite_array_query() - Execute a query against a given database and returns an array

sqlite_escape_string
sqlite_factory
SQLite Funkcje


Opens an SQLite database and returns an SQLiteDatabase object

sqlite_exec
sqlite_fetch_all
SQLite Funkcje
PHP Manual

sqlite_factory

(PHP 5)

sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object

Opis

SQLiteDatabase sqlite_factory ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

sqlite_factory() behaves similarly to sqlite_open() in that it opens an SQLite database or attempts to create it if it does not exist. However, a SQLiteDatabase object is returned rather than a resource. Please see the sqlite_open() reference page for further usage and caveats.

Parametry

filename

The filename of the SQLite database.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Zwracane wartości

Returns an SQLiteDatabase object on success, NULL on error.

Przykłady

Przykład #1 sqlite_factory() example

<?php
$dbhandle = sqlite_factory('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

/* functionally equivalent to: */

$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

?>

Zobacz też:

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_exec
sqlite_fetch_all
SQLite Funkcje


Fetches all rows from a result set as an array of arrays

sqlite_factory
sqlite_fetch_array
SQLite Funkcje
PHP Manual

sqlite_fetch_all

SQLiteResult::fetchAll

SQLiteUnbuffered::fetchAll

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_fetch_all -- SQLiteResult::fetchAll -- SQLiteUnbuffered::fetchAll — Fetches all rows from a result set as an array of arrays

Opis

array sqlite_fetch_all ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Styl obiektowy (method):

array SQLiteResult::fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
array SQLiteUnbuffered::fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

sqlite_fetch_all() returns an array of the entire result set from the result resource. It is similar to calling sqlite_query() (or sqlite_unbuffered_query()) and then sqlite_fetch_array() for each row in the result set.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

Opcjonalny parametr result_type przyjmuje wartości stałych i określa jak indeksowane będą zwracane wartości. Używając SQLITE_ASSOC zwrócone zostaną tylko indeksy asocjacyjne (nazwy pól), podczas gdy SQLITE_NUM zwróci tylko indeksy numeryczne (numery pól). SQLITE_BOTH zwróci i indeksy asocjacyjne i numeryczne. SQLITE_BOTH jest domyślną wartością dla tej funkcji.

decode_binary

Gdy parametr decode_binary zostanie ustawiony na TRUE (domyślnie), PHP zdekoduje kodowanie binarne, któremu zostały poddane dane, jeśli były kodowane przy użyciu funkcji sqlite_escape_string(). Zazwyczaj należy pozostawić domyślną wartość tego parametru, chyba że baza jest współużytkowana przez różne aplikacje.

Zwracane wartości

Returns an array of the remaining rows in a result set. If called right after sqlite_query(), it returns all rows. If called after sqlite_fetch_array(), it returns the rest. If there are no rows in a result set, it returns an empty array.

Wielkość liter w nazwach kolumn zwróconych przez SQLITE_ASSOC i SQLITE_BOTH zostaną przetworzone zależnie od ustawienia opcji konfiguracji sqlite.assoc_case.

Przykłady

Przykład #1 Procedural example

<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Przykład #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

$result = $query->fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Zobacz też:

  • sqlite_fetch_array() - Fetches the next row from a result set as an array

sqlite_factory
sqlite_fetch_array
SQLite Funkcje


Fetches the next row from a result set as an array

sqlite_fetch_all
sqlite_fetch_column_types
SQLite Funkcje
PHP Manual

sqlite_fetch_array

SQLiteResult::fetch

SQLiteUnbuffered::fetch

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_fetch_array -- SQLiteResult::fetch -- SQLiteUnbuffered::fetch — Fetches the next row from a result set as an array

Opis

array sqlite_fetch_array ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Styl obiektowy (method):

array SQLiteResult::fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )
array SQLiteUnbuffered::fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = true ]] )

Fetches the next row from the given result handle. If there are no more rows, returns FALSE, otherwise returns an associative array representing the row data.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

Opcjonalny parametr result_type przyjmuje wartości stałych i określa jak indeksowane będą zwracane wartości. Używając SQLITE_ASSOC zwrócone zostaną tylko indeksy asocjacyjne (nazwy pól), podczas gdy SQLITE_NUM zwróci tylko indeksy numeryczne (numery pól). SQLITE_BOTH zwróci i indeksy asocjacyjne i numeryczne. SQLITE_BOTH jest domyślną wartością dla tej funkcji.

decode_binary

Gdy parametr decode_binary zostanie ustawiony na TRUE (domyślnie), PHP zdekoduje kodowanie binarne, któremu zostały poddane dane, jeśli były kodowane przy użyciu funkcji sqlite_escape_string(). Zazwyczaj należy pozostawić domyślną wartość tego parametru, chyba że baza jest współużytkowana przez różne aplikacje.

Zwracane wartości

Returns an array of the next row from a result set; FALSE if the next position is beyond the final row.

Wielkość liter w nazwach kolumn zwróconych przez SQLITE_ASSOC i SQLITE_BOTH zostaną przetworzone zależnie od ustawienia opcji konfiguracji sqlite.assoc_case.

Przykłady

Przykład #1 Procedural example

<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
while ($entry = sqlite_fetch_array($query, SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Przykład #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

while ($entry = $query->fetch(SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Zobacz też:

  • sqlite_array_query() - Execute a query against a given database and returns an array
  • sqlite_fetch_string() - Alias dla sqlite_fetch_single

sqlite_fetch_all
sqlite_fetch_column_types
SQLite Funkcje


Return an array of column types from a particular table

sqlite_fetch_array
sqlite_fetch_object
SQLite Funkcje
PHP Manual

sqlite_fetch_column_types

SQLiteDatabase::fetchColumnTypes

(PHP 5)

sqlite_fetch_column_types -- SQLiteDatabase::fetchColumnTypes — Return an array of column types from a particular table

Opis

array sqlite_fetch_column_types ( string $table_name , resource $dbhandle [, int $result_type = SQLITE_ASSOC ] )

Styl obiektowy (method):

array SQLiteDatabase::fetchColumnTypes ( string $table_name [, int $result_type = SQLITE_ASSOC ] )

sqlite_fetch_column_types() returns an array of column data types from the specified table_name table.

Parametry

table_name

The table name to query.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_ASSOC is the default for this function.

Zwracane wartości

Returns an array of column data types; FALSE on error.

Wielkość liter w nazwach kolumn zwróconych przez SQLITE_ASSOC i SQLITE_BOTH zostaną przetworzone zależnie od ustawienia opcji konfiguracji sqlite.assoc_case.

Rejestr zmian

Wersja | Opis
5.1.0 | Added result_type

Przykłady

Przykład #1 Procedural example

<?php
$db = sqlite_open('mysqlitedb');
sqlite_query($db, 'CREATE TABLE foo (bar varchar(10), arf text)');
$cols = sqlite_fetch_column_types('foo', $db, SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type\n";
}
?>

Przykład #2 Object-oriented example

<?php
$db = new SQLiteDatabase('mysqlitedb');
$db->query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols = $db->fetchColumnTypes('foo', SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type\n";
}
?>

Powyższy przykład wyświetli:

Column: bar  Type: VARCHAR
Column: arf  Type: TEXT

sqlite_fetch_array
sqlite_fetch_object
SQLite Funkcje


Fetches the next row from a result set as an object

sqlite_fetch_column_types
sqlite_fetch_single
SQLite Funkcje
PHP Manual

sqlite_fetch_object

SQLiteResult::fetchObject

SQLiteUnbuffered::fetchObject

(PHP 5)

sqlite_fetch_object -- SQLiteResult::fetchObject -- SQLiteUnbuffered::fetchObject — Fetches the next row from a result set as an object

Opis

object sqlite_fetch_object ( resource $result [, string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )

Styl obiektowy (method):

object SQLiteResult::fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )
object SQLiteUnbuffered::fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = true ]]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

sqlite_fetch_column_types
sqlite_fetch_single
SQLite Funkcje


Fetches the first column of a result set as a string

sqlite_fetch_object
sqlite_fetch_string
SQLite Funkcje
PHP Manual

sqlite_fetch_single

SQLiteResult::fetchSingle

SQLiteUnbuffered::fetchSingle

(PHP 5, PECL sqlite >= 1.0.1)

sqlite_fetch_single -- SQLiteResult::fetchSingle -- SQLiteUnbuffered::fetchSingle — Fetches the first column of a result set as a string

Opis

string sqlite_fetch_single ( resource $result [, bool $decode_binary = true ] )

Styl obiektowy (method):

string SQLiteResult::fetchSingle ([ bool $decode_binary = true ] )
string SQLiteUnbuffered::fetchSingle ([ bool $decode_binary = true ] )

sqlite_fetch_single() is identical to sqlite_fetch_array() except that it returns the value of the first column of the rowset.

This is the most optimal way to retrieve data when you are only interested in the values from a single column of data.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

decode_binary

Gdy parametr decode_binary zostanie ustawiony na TRUE (domyślnie), PHP zdekoduje kodowanie binarne, któremu zostały poddane dane, jeśli były kodowane przy użyciu funkcji sqlite_escape_string(). Zazwyczaj należy pozostawić domyślną wartość tego parametru, chyba że baza jest współużytkowana przez różne aplikacje.

Zwracane wartości

Returns the first column value, as a string.

Przykłady

Przykład #1 A sqlite_fetch_single() example

<?php
if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    $sql = "SELECT id FROM sometable WHERE id = 42";
    $res = sqlite_query($dbhandle, $sql);

    if (sqlite_num_rows($res) > 0) {
        echo sqlite_fetch_single($res); // 42
    }

    sqlite_close($dbhandle);
}
?>

Zobacz też:

  • sqlite_fetch_array() - Fetches the next row from a result set as an array

sqlite_fetch_object
sqlite_fetch_string
SQLite Funkcje


Alias dla sqlite_fetch_single

sqlite_fetch_single
sqlite_field_name
SQLite Funkcje
PHP Manual

sqlite_fetch_string

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_fetch_string — Alias dla sqlite_fetch_single()

Opis

Ta funkcja jest aliasem dla: sqlite_fetch_single().

sqlite_fetch_single
sqlite_field_name
SQLite Funkcje


Returns the name of a particular field

sqlite_fetch_string
sqlite_has_more
SQLite Funkcje
PHP Manual

sqlite_field_name

SQLiteResult::fieldName

SQLiteUnbuffered::fieldName

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_field_name -- SQLiteResult::fieldName -- SQLiteUnbuffered::fieldName — Returns the name of a particular field

Opis

string sqlite_field_name ( resource $result , int $field_index )

Styl obiektowy (method):

string SQLiteResult::fieldName ( int $field_index )
string SQLiteUnbuffered::fieldName ( int $field_index )

Given the ordinal column number, field_index, sqlite_field_name() returns the name of that field in the result set result.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

field_index

The ordinal column number in the result set.

Zwracane wartości

Returns the name of a field in an SQLite result set, given the ordinal column number; FALSE on error.

Wielkość liter w nazwach kolumn zwróconych przez SQLITE_ASSOC i SQLITE_BOTH zostaną przetworzone zależnie od ustawienia opcji konfiguracji sqlite.assoc_case.

sqlite_fetch_string
sqlite_has_more
SQLite Funkcje


Finds whether or not more rows are available

sqlite_field_name
sqlite_has_prev
SQLite Funkcje
PHP Manual

sqlite_has_more

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_has_more — Finds whether or not more rows are available

Opis

bool sqlite_has_more ( resource $result )

Finds whether more rows are available from the given result set.

Parametry

result

The SQLite result resource.

Zwracane wartości

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

Zobacz też:

  • sqlite_num_rows() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement

sqlite_field_name
sqlite_has_prev
SQLite Funkcje


Returns whether or not a previous row is available

sqlite_has_more
sqlite_key
SQLite Funkcje
PHP Manual

sqlite_has_prev

SQLiteResult::hasPrev

(PHP 5)

sqlite_has_prev -- SQLiteResult::hasPrev — Returns whether or not a previous row is available

Opis

bool sqlite_has_prev ( resource $result )

Styl obiektowy (method):

bool SQLiteResult::hasPrev ( void )

Find whether there are more previous rows from the given result handle.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Informacja:

Ta funkcja nie może być używana z niebuforowanymi wynikami.

Zwracane wartości

Returns TRUE if there are more previous rows available from the result handle, or FALSE otherwise.

Zobacz też:

  • sqlite_prev() - Seek to the previous row number of a result set
  • sqlite_has_more() - Finds whether or not more rows are available
  • sqlite_num_rows() - Returns the number of rows in a buffered result set

sqlite_has_more
sqlite_key
SQLite Funkcje


Returns the current row index

sqlite_has_prev
sqlite_last_error
SQLite Funkcje
PHP Manual

sqlite_key

SQLiteResult::key

(PHP 5 >= 5.1.0)

sqlite_key -- SQLiteResult::key — Returns the current row index

Opis

int sqlite_key ( resource $result )

Styl obiektowy (method):

int SQLiteResult::key ( void )

sqlite_key() returns the current row index of the buffered result set result.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Informacja:

Ta funkcja nie może być używana z niebuforowanymi wynikami.

Zwracane wartości

Returns the current row index of the buffered result set result.

Rejestr zmian

Wersja | Opis
5.0.4 | Prior to PHP 5.0.4, sqlite_key() was only able to be called as a method on a SQLiteResult object, not procedurally.

Zobacz też:

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

sqlite_has_prev
sqlite_last_error
SQLite Funkcje


Returns the error code of the last error for a database

sqlite_key
sqlite_last_insert_rowid
SQLite Funkcje
PHP Manual

sqlite_last_error

SQLiteDatabase::lastError

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_last_error -- SQLiteDatabase::lastError — Returns the error code of the last error for a database

Opis

int sqlite_last_error ( resource $dbhandle )

Styl obiektowy (method):

int SQLiteDatabase::lastError ( void )

Returns the error code from the last operation performed on dbhandle (the database handle), or 0 when no error occurred. A human readable description of the error code can be retrieved using sqlite_error_string().

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Zwracane wartości

Returns an error code, or 0 if no error occurred.

Zobacz też:

  • sqlite_error_string() - Returns the textual description of an error code

sqlite_key
sqlite_last_insert_rowid
SQLite Funkcje


Returns the rowid of the most recently inserted row

sqlite_last_error
sqlite_libencoding
SQLite Funkcje
PHP Manual

sqlite_last_insert_rowid

SQLiteDatabase::lastInsertRowid

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_last_insert_rowid -- SQLiteDatabase::lastInsertRowid — Returns the rowid of the most recently inserted row

Opis

int sqlite_last_insert_rowid ( resource $dbhandle )

Styl obiektowy (method):

int SQLiteDatabase::lastInsertRowid ( void )

Returns the rowid of the row that was most recently inserted into the database dbhandle, if it was created as an auto-increment field.

Wskazówka

You can create auto-increment fields in SQLite by declaring them as INTEGER PRIMARY KEY in your table schema.

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Zwracane wartości

Returns the row id, as an integer.

sqlite_last_error
sqlite_libencoding
SQLite Funkcje


Returns the encoding of the linked SQLite library

sqlite_last_insert_rowid
sqlite_libversion
SQLite Funkcje
PHP Manual

sqlite_libencoding

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_libencoding — Returns the encoding of the linked SQLite library

Opis

string sqlite_libencoding ( void )

The SQLite library may be compiled in either ISO-8859-1 or UTF-8 compatible modes. This function allows you to determine which encoding scheme is used by your version of the library.

Ostrzeżenie

The default PHP distribution builds libsqlite in ISO-8859-1 encoding mode. However, this is a misnomer; rather than handling ISO-8859-1, it operates according to your current locale settings for string comparisons and sort ordering. So, rather than ISO-8859-1, you should think of it as being '8-bit' instead.

When compiled with UTF-8 support, sqlite handles encoding and decoding of UTF-8 multi-byte character sequences, but does not yet do a complete job when working with the data (no normalization is performed for example), and some comparison operations may still not be carried out correctly.

Ostrzeżenie

It is not recommended that you use PHP in a web-server configuration with a version of the SQLite library compiled with UTF-8 support, since libsqlite will abort the process if it detects a problem with the UTF-8 encoding.

Zwracane wartości

Returns the library encoding.

Zobacz też:

  • sqlite_lib_version()

sqlite_last_insert_rowid
sqlite_libversion
SQLite Funkcje


Returns the version of the linked SQLite library

sqlite_libencoding
sqlite_next
SQLite Funkcje
PHP Manual

sqlite_libversion

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_libversion — Returns the version of the linked SQLite library

Opis

string sqlite_libversion ( void )

Returns the version of the linked SQLite library.

Zwracane wartości

Returns the library version, as a string.

Zobacz też:

  • sqlite_libencoding() - Returns the encoding of the linked SQLite library

sqlite_libencoding
sqlite_next
SQLite Funkcje


Seek to the next row number

sqlite_libversion
sqlite_num_fields
SQLite Funkcje
PHP Manual

sqlite_next

SQLiteResult::next

SQLiteUnbuffered::next

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_next -- SQLiteResult::next -- SQLiteUnbuffered::next — Seek to the next row number

Opis

bool sqlite_next ( resource $result )

Styl obiektowy (method):

bool SQLiteResult::next ( void )
bool SQLiteUnbuffered::next ( void )

sqlite_next() advances the result handle result to the next row.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Zwracane wartości

Returns TRUE on success, or FALSE if there are no more rows.

Zobacz też:

  • sqlite_seek() - Seek to a particular row number of a buffered result set
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

sqlite_libversion
sqlite_num_fields
SQLite Funkcje


Returns the number of fields in a result set

sqlite_next
sqlite_num_rows
SQLite Funkcje
PHP Manual

sqlite_num_fields

SQLiteResult::numFields

SQLiteUnbuffered::numFields

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_num_fields -- SQLiteResult::numFields -- SQLiteUnbuffered::numFields — Returns the number of fields in a result set

Opis

int sqlite_num_fields ( resource $result )

Styl obiektowy (method):

int SQLiteResult::numFields ( void )
int SQLiteUnbuffered::numFields ( void )

Returns the number of fields in the result set.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Zwracane wartości

Returns the number of fields, as an integer.

Zobacz też:

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_num_rows() - Returns the number of rows in a buffered result set

sqlite_next
sqlite_num_rows
SQLite Funkcje


Returns the number of rows in a buffered result set

sqlite_num_fields
sqlite_open
SQLite Funkcje
PHP Manual

sqlite_num_rows

SQLiteResult::numRows

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_num_rows -- SQLiteResult::numRows — Returns the number of rows in a buffered result set

Opis

int sqlite_num_rows ( resource $result )

Styl obiektowy (method):

int SQLiteResult::numRows ( void )

Returns the number of rows in the buffered result set.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Informacja:

Ta funkcja nie może być używana z niebuforowanymi wynikami.

Zwracane wartości

Returns the number of rows, as an integer.

Przykłady

Przykład #1 Procedural example

<?php
$db = sqlite_open('mysqlitedb');
$result = sqlite_query($db, "SELECT * FROM mytable WHERE name='John Doe'");
$rows = sqlite_num_rows($result);

echo "Number of rows: $rows";
?>

Przykład #2 Object-oriented example

<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();

echo "Number of rows: $rows";
?>

Zobacz też:

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_num_fields() - Returns the number of fields in a result set

sqlite_num_fields
sqlite_open
SQLite Funkcje


Opens an SQLite database and create the database if it does not exist

sqlite_num_rows
sqlite_popen
SQLite Funkcje
PHP Manual

sqlite_open

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_open — Opens an SQLite database and create the database if it does not exist

Opis

resource sqlite_open ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Styl obiektowy (constructor):

SQLiteDatabase::__construct() ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Opens an SQLite database or creates the database if it does not exist.

Parametry

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Zwracane wartości

Returns a resource (database handle) on success, FALSE on error.

Przykłady

Przykład #1 sqlite_open() example

<?php
if ($db = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
    sqlite_query($db, 'CREATE TABLE foo (bar varchar(10))');
    sqlite_query($db, "INSERT INTO foo VALUES ('fnord')");
    $result = sqlite_query($db, 'select bar from foo');
    var_dump(sqlite_fetch_array($result));
} else {
    die($sqliteerror);
}
?>

Notatki

Wskazówka

On Unix platforms, SQLite is sensitive to scripts that use the fork() system call. If you do have such a script, it is recommended that you close the handle prior to forking and then re-open it in the child and/or parent. For more information on this issue, see » The C language interface to the SQLite library in the section entitled Multi-Threading And SQLite.

Wskazówka

It is not recommended to work with SQLite databases mounted on NFS partitions. Since NFS is notoriously bad when it comes to locking you may find that you cannot even open the database at all, and if it succeeds, the locking behaviour may be undefined.

Informacja: Starting with SQLite library version 2.8.2, you can specify :memory: as the filename to create a database that lives only in the memory of the computer. This is useful mostly for temporary processing, as the in-memory database will be destroyed when the process ends. It can also be useful when coupled with the ATTACH DATABASE SQL statement to load other databases and move and query data between them.

Informacja: SQLite is tryb bezpieczny and open_basedir aware.

Zobacz też:

  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens an SQLite database and returns an SQLiteDatabase object

sqlite_num_rows
sqlite_popen
SQLite Funkcje


Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_open
sqlite_prev
SQLite Funkcje
PHP Manual

sqlite_popen

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist

Opis

resource sqlite_popen ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

This function behaves identically to sqlite_open() except that is uses the persistent resource mechanism of PHP. For information about the meaning of the parameters, read the sqlite_open() manual page.

sqlite_popen() will first check to see if a persistent handle has already been opened for the given filename. If it finds one, it returns that handle to your script, otherwise it opens a fresh handle to the database.

The benefit of this approach is that you don't incur the performance cost of re-reading the database and index schema on each page hit served by persistent web server SAPI's (any SAPI except for regular CGI or CLI).

Informacja: If you use persistent handles and have the database updated by a background process (perhaps via a crontab), and that process re-creates the database by overwriting it (either by unlinking and rebuilding, or moving the updated version to replace the current version), you may experience undefined behaviour when a persistent handle on the old version of the database is recycled. To avoid this situation, have your background processes open the same database file and perform their updates in a transaction.

Parametry

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Zwracane wartości

Returns a resource (database handle) on success, FALSE on error.

Zobacz też:

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens an SQLite database and returns an SQLiteDatabase object

sqlite_open
sqlite_prev
SQLite Funkcje


Seek to the previous row number of a result set

sqlite_popen
sqlite_query
SQLite Funkcje
PHP Manual

sqlite_prev

SQLiteResult::prev

(PHP 5)

sqlite_prev -- SQLiteResult::prev — Seek to the previous row number of a result set

Opis

bool sqlite_prev ( resource $result )

Styl obiektowy (method):

bool SQLiteResult::prev ( void )

sqlite_prev() seeks back the result handle to the previous row.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Informacja:

Ta funkcja nie może być używana z niebuforowanymi wynikami.

Zwracane wartości

Returns TRUE on success, or FALSE if there are no more previous rows.

Zobacz też:

  • sqlite_has_prev() - Returns whether or not a previous row is available
  • sqlite_rewind() - Seek to the first row number
  • sqlite_next() - Seek to the next row number

sqlite_popen
sqlite_query
SQLite Funkcje


Executes a query against a given database and returns a result handle

sqlite_prev
sqlite_rewind
SQLite Funkcje
PHP Manual

sqlite_query

SQLiteDatabase::query

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_query -- SQLiteDatabase::query — Executes a query against a given database and returns a result handle

Opis

resource sqlite_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] )
resource sqlite_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] )

Styl obiektowy (method):

SQLiteResult SQLiteDatabase::query ( string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] )

Executes an SQL statement given by the query against a given database handle.

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

result_type

Opcjonalny parametr result_type przyjmuje wartości stałych i określa jak indeksowane będą zwracane wartości. Używając SQLITE_ASSOC zwrócone zostaną tylko indeksy asocjacyjne (nazwy pól), podczas gdy SQLITE_NUM zwróci tylko indeksy numeryczne (numery pól). SQLITE_BOTH zwróci i indeksy asocjacyjne i numeryczne. SQLITE_BOTH jest domyślną wartością dla tej funkcji.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Informacja: Obsługiwane są dwie alternatywne składnie, dla zachowania kompatybilności z rozszerzeniami dla innych baz danych (takich jak MySQL). Preferowana jest pierwsza, gdzie dbhandle jest pierwszym parametrem funkcji.

Zwracane wartości

This function will return a result handle lub FALSE w przypadku niepowodzenia. For queries that return rows, the result handle can then be used with functions such as sqlite_fetch_array() and sqlite_seek().

Regardless of the query type, this function will return FALSE if the query failed.

sqlite_query() returns a buffered, seekable result handle. This is useful for reasonably small queries where you need to be able to randomly access the rows. Buffered result handles will allocate memory to hold the entire result and will not return until it has been fetched. If you only need sequential access to the data, it is recommended that you use the much higher performance sqlite_unbuffered_query() instead.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the error_msg parameter

Notatki

Ostrzeżenie

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script. However, this works only when the result of the function is not used - if it is used, only the first SQL statement would be executed. Function sqlite_exec() will always execute multiple SQL statements.

When executing multiple queries, the return value of this function will be FALSE if there was an error, but undefined otherwise (it might be TRUE for success or it might return a result handle).

Zobacz też:

  • sqlite_unbuffered_query() - Execute a query that does not prefetch and buffer all data
  • sqlite_array_query() - Execute a query against a given database and returns an array

sqlite_prev
sqlite_rewind
SQLite Funkcje


Seek to the first row number

sqlite_query
sqlite_seek
SQLite Funkcje
PHP Manual

sqlite_rewind

SQLiteResult::rewind

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_rewind -- SQLiteResult::rewind — Seek to the first row number

Opis

bool sqlite_rewind ( resource $result )

Styl obiektowy (method):

bool SQLiteResult::rewind ( void )

sqlite_rewind() seeks back to the first row in the given result set.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Informacja:

Ta funkcja nie może być używana z niebuforowanymi wynikami.

Zwracane wartości

Returns FALSE if there are no rows in the result set, TRUE otherwise.

Zobacz też:

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_seek() - Seek to a particular row number of a buffered result set

sqlite_query
sqlite_seek
SQLite Funkcje


Seek to a particular row number of a buffered result set

sqlite_rewind
sqlite_single_query
SQLite Funkcje
PHP Manual

sqlite_seek

SQLiteResult::seek

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_seek -- SQLiteResult::seek — Seek to a particular row number of a buffered result set

Opis

bool sqlite_seek ( resource $result , int $rownum )

Styl obiektowy (method):

bool SQLiteResult::seek ( int $rownum )

sqlite_seek() seeks to the row given by the parameter rownum.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Informacja:

Ta funkcja nie może być używana z niebuforowanymi wynikami.

rownum

The ordinal row number to seek to. The row number is zero-based (0 is the first row).

Informacja:

Ta funkcja nie może być używana z niebuforowanymi wynikami.

Zwracane wartości

Returns FALSE if the row does not exist, TRUE otherwise.

Zobacz też:

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number

sqlite_rewind
sqlite_single_query
SQLite Funkcje


Executes a query and returns either an array for one single column or the value of the first row

sqlite_seek
sqlite_udf_decode_binary
SQLite Funkcje
PHP Manual

sqlite_single_query

SQLiteDatabase::singleQuery

(PHP 5, PECL sqlite >= 1.0.1)

sqlite_single_query -- SQLiteDatabase::singleQuery — Executes a query and returns either an array for one single column or the value of the first row

Opis

array sqlite_single_query ( resource $db , string $query [, bool $first_row_only [, bool $decode_binary ]] )

Styl obiektowy (method):

array SQLiteDatabase::singleQuery ( string $query [, bool $first_row_only [, bool $decode_binary ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

sqlite_seek
sqlite_udf_decode_binary
SQLite Funkcje


Decode binary data passed as parameters to an UDF

sqlite_single_query
sqlite_udf_encode_binary
SQLite Funkcje
PHP Manual

sqlite_udf_decode_binary

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF

Opis

string sqlite_udf_decode_binary ( string $data )

Decodes binary data passed as parameters to a UDF.

You must call this function on parameters passed to your UDF if you need them to handle binary data, as the binary encoding employed by PHP will obscure the content and of the parameter in its natural, non-coded form.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Parametry

data

The encoded data that will be decoded, data that was applied by either sqlite_udf_encode_binary() or sqlite_escape_string().

Zwracane wartości

The decoded string.

Przykłady

Przykład #1 binary-safe max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = sqlite_open(':memory:');
sqlite_query($db, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($db, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string)
{
    $string = sqlite_udf_decode_binary($string);
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context)
{
    return $context;
}

sqlite_create_aggregate($db, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($db, 'SELECT max_len(a) from strings'));

?>

Zobacz też:

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

sqlite_single_query
sqlite_udf_encode_binary
SQLite Funkcje


Encode binary data before returning it from an UDF

sqlite_udf_decode_binary
sqlite_unbuffered_query
SQLite Funkcje
PHP Manual

sqlite_udf_encode_binary

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_udf_encode_binary — Encode binary data before returning it from an UDF

Opis

string sqlite_udf_encode_binary ( string $data )

sqlite_udf_encode_binary() applies a binary encoding to the data so that it can be safely returned from queries (since the underlying libsqlite API is not binary safe).

If there is a chance that your data might be binary unsafe (e.g.: it contains a NUL byte in the middle rather than at the end, or if it has and 0x01 byte as the first character) then you must call this function to encode the return value from your UDF.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Informacja:

Do not use sqlite_escape_string() to quote strings returned from UDF's as it will lead to double-quoting of the data. Use sqlite_udf_encode_binary() instead!

Parametry

data

The string being encoded.

Zwracane wartości

The encoded string.

Zobacz też:

  • sqlite_udf_decode_binary() - Decode binary data passed as parameters to an UDF
  • sqlite_escape_string() - Escapes a string for use as a query parameter
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements

sqlite_udf_decode_binary
sqlite_unbuffered_query
SQLite Funkcje


Execute a query that does not prefetch and buffer all data

sqlite_udf_encode_binary
sqlite_valid
SQLite Funkcje
PHP Manual

sqlite_unbuffered_query

SQLiteDatabase::unbufferedQuery

(PHP 5, PECL sqlite >= 1.0.0)

sqlite_unbuffered_query -- SQLiteDatabase::unbufferedQuery — Execute a query that does not prefetch and buffer all data

Opis

resource sqlite_unbuffered_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] )
resource sqlite_unbuffered_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] )

Styl obiektowy (method):

SQLiteUnbuffered SQLiteDatabase::unbufferedQuery ( string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] )

sqlite_unbuffered_query() is identical to sqlite_query() except that the result that is returned is a sequential forward-only result set that can only be used to read each row, one after the other.

This function is ideal for generating things such as HTML tables where you only need to process one row at a time and don't need to randomly access the row data.

Informacja:

Functions such as sqlite_seek(),
sqlite_rewind(), sqlite_next(),
sqlite_current(), and
sqlite_num_rows() do not work on result handles
returned from sqlite_unbuffered_query().

Parametry

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

result_type

Opcjonalny parametr result_type przyjmuje wartości stałych i określa jak indeksowane będą zwracane wartości. Używając SQLITE_ASSOC zwrócone zostaną tylko indeksy asocjacyjne (nazwy pól), podczas gdy SQLITE_NUM zwróci tylko indeksy numeryczne (numery pól). SQLITE_BOTH zwróci i indeksy asocjacyjne i numeryczne. SQLITE_BOTH jest domyślną wartością dla tej funkcji.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Informacja: Obsługiwane są dwie alternatywne składnie, dla zachowania kompatybilności z rozszerzeniami dla innych baz danych (takich jak MySQL). Preferowana jest pierwsza, gdzie dbhandle jest pierwszym parametrem funkcji.

Zwracane wartości

Returns a result handle lub FALSE w przypadku niepowodzenia.

sqlite_unbuffered_query() returns a sequential forward-only result set that can only be used to read each row, one after the other.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the error_msg parameter

Zobacz też:

  • sqlite_query() - Executes a query against a given database and returns a result handle

sqlite_udf_encode_binary
sqlite_valid
SQLite Funkcje


Returns whether more rows are available

sqlite_unbuffered_query
SQLite3
SQLite Funkcje
PHP Manual

sqlite_valid

SQLiteResult::valid

SQLiteUnbuffered::valid

(PHP 5)

sqlite_valid -- SQLiteResult::valid -- SQLiteUnbuffered::valid — Returns whether more rows are available

Opis

bool sqlite_valid ( resource $result )

Styl obiektowy (method):

bool SQLiteResult::valid ( void )
bool SQLiteUnbuffered::valid ( void )

Finds whether more rows are available from the given result handle.

Parametry

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Informacja:

Ta funkcja nie może być używana z niebuforowanymi wynikami.

Zwracane wartości

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

Zobacz też:

  • sqlite_num_rows() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement

sqlite_unbuffered_query
SQLite3
SQLite Funkcje


SQLite3

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • SQLite3 — The SQLite3 class
    • SQLite3::busyTimeout — Sets the busy connection handler
    • SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close — Closes the database connection
    • SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
    • SQLite3::escapeString — Returns a string that has been properly escaped
    • SQLite3::exec — Executes a result-less query against a given database
    • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension — Attempts to load an SQLite extension library
    • SQLite3::open — Opens an SQLite database
    • SQLite3::prepare — Prepares an SQL statement for execution
    • SQLite3::query — Executes an SQL query
    • SQLite3::querySingle — Executes a query and returns a single result
    • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
  • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear — Clears all current bound parameters
    • SQLite3Stmt::close — Closes the prepared statement
    • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
    • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
    • SQLite3Stmt::reset — Resets the prepared statement
  • SQLite3Result — The SQLite3Result class
    • SQLite3Result::columnName — Returns the name of the nth column
    • SQLite3Result::columnType — Returns the type of the nth column
    • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize — Closes the result set
    • SQLite3Result::numColumns — Returns the number of columns in the result set
    • SQLite3Result::reset — Resets the result set back to the first row
sqlite_valid
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Obsługa baz danych SQLite 3.

SQLite3
Instalacja/Konfiguracja
SQLite3


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SQLite3


Instalacja

The SQLite3 extension is enabled by default as of PHP 5.3.0. It's possible to disable it by using --without-sqlite3 at compile time.

Windows users must enable php_sqlite3.dll in order to use this extension. This DLL is included with Windows distributions of PHP as of PHP 5.3.0.

Informacja:

This extension was briefly a PECL extension but that version is only recommended for experimental use.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

SQLite3 Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Changelog
sqlite3.extension_dir | NULL | PHP_INI_SYSTEM |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

sqlite3.extension_dir string

Path to the directory where the loadable extensions for SQLite reside.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

SQLITE3_ASSOC (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column name as returned in the corresponding result set.
SQLITE3_NUM (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column number as returned in the corresponding result set, starting at column 0.
SQLITE3_BOTH (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
SQLITE3_INTEGER (integer)
Represents the SQLite3 INTEGER storage class.
SQLITE3_FLOAT (integer)
Represents the SQLite3 REAL (FLOAT) storage class.
SQLITE3_TEXT (integer)
Represents the SQLite3 TEXT storage class.
SQLITE3_BLOB (integer)
Represents the SQLite3 BLOB storage class.
SQLITE3_NULL (integer)
Represents the SQLite3 NULL storage class.
SQLITE3_OPEN_READONLY (integer)
Specifies that the SQLite3 database be opened for reading only.
SQLITE3_OPEN_READWRITE (integer)
Specifies that the SQLite3 database be opened for reading and writing.
SQLITE3_OPEN_CREATE (integer)
Specifies that the SQLite3 database be created if it does not already exist.

Typy zasobów
SQLite3
SQLite3


The SQLite3 class

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

Wstęp

A class that interfaces SQLite 3 databases.

Krótki opis klasy

SQLite3 {
/* Metody */
public bool busyTimeout ( int $msecs )
public int changes ( void )
public bool close ( void )
public __construct ( string $filename [, int $flags [, string $encryption_key ]] )
public bool createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] )
public bool createFunction ( string $name , mixed $callback [, int $argument_count = -1 ] )
public string escapeString ( string $value )
public bool exec ( string $query )
public int lastErrorCode ( void )
public string lastErrorMsg ( void )
public int lastInsertRowID ( void )
public bool loadExtension ( string $shared_library )
public void open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key ]] )
public SQLite3Stmt prepare ( string $query )
public SQLite3Result query ( string $query )
public mixed querySingle ( string $query [, bool $entire_row = false ] )
public array version ( void )
}

Spis treści

  • SQLite3::busyTimeout — Sets the busy connection handler
  • SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
  • SQLite3::close — Closes the database connection
  • SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database
  • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
  • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
  • SQLite3::escapeString — Returns a string that has been properly escaped
  • SQLite3::exec — Executes a result-less query against a given database
  • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
  • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
  • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
  • SQLite3::loadExtension — Attempts to load an SQLite extension library
  • SQLite3::open — Opens an SQLite database
  • SQLite3::prepare — Prepares an SQL statement for execution
  • SQLite3::query — Executes an SQL query
  • SQLite3::querySingle — Executes a query and returns a single result
  • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
Stałe predefiniowane
SQLite3::busyTimeout
SQLite3


Sets the busy connection handler

SQLite3
SQLite3::changes
SQLite3
PHP Manual

SQLite3::busyTimeout

(PHP 5 >= 5.3.3)

SQLite3::busyTimeout — Sets the busy connection handler

Opis

public bool SQLite3::busyTimeout ( int $msecs )

Sets a busy handler that will sleep until the database is not locked or the timeout is reached.

Parametry

msecs

The milliseconds to sleep. Setting this value to a value less than or equal to zero, will turn off an already set timeout handler.

Zwracane wartości

Returns TRUE on success, FALSE on failure.

SQLite3
SQLite3::changes
SQLite3


Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

SQLite3::busyTimeout
SQLite3::close
SQLite3
PHP Manual

SQLite3::changes

(PHP 5 >= 5.3.0)

SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

Opis

public int SQLite3::changes ( void )

Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement.

Przykłady

Przykład #1 SQLite3::changes() example

<?php
$db = new SQLite3('mysqlitedb.db');

$query = $db->exec('UPDATE counter SET views=0 WHERE page="test"');
if ($query) {
    echo 'Number of rows modified: ', $db->changes();
}
?>

SQLite3::busyTimeout
SQLite3::close
SQLite3


Closes the database connection

SQLite3::changes
SQLite3::__construct
SQLite3
PHP Manual

SQLite3::close

(PHP 5 >= 5.3.0)

SQLite3::close — Closes the database connection

Opis

public bool SQLite3::close ( void )

Closes the database connection.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success, FALSE on failure.

Przykłady

Przykład #1 SQLite3::close() example

<?php
$db = new SQLite3('mysqlitedb.db');
$db->close();
?>

SQLite3::changes
SQLite3::__construct
SQLite3


Instantiates an SQLite3 object and opens an SQLite 3 database

SQLite3::close
SQLite3::createAggregate
SQLite3
PHP Manual

SQLite3::__construct

(PHP 5 >= 5.3.0)

SQLite3::__construct — Instantiates an SQLite3 object and opens an SQLite 3 database

Opis

public SQLite3::__construct ( string $filename [, int $flags [, string $encryption_key ]] )

Instantiates an SQLite3 object and opens a connection to an SQLite 3 database. If the build includes encryption, then it will attempt to use the key.

Parametry

filename

Path to the SQLite database, or :memory: to use in-memory database.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryption_key

An optional encryption key used when encrypting and decrypting an SQLite database.

Zwracane wartości

Returns an SQLite3 object on success.

Przykłady

Przykład #1 SQLite3::__construct() example

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

SQLite3::close
SQLite3::createAggregate
SQLite3


Registers a PHP function for use as an SQL aggregate function

SQLite3::__construct
SQLite3::createFunction
SQLite3
PHP Manual

SQLite3::createAggregate

(PHP 5 >= 5.3.0)

SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function

Opis

public bool SQLite3::createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] )

Registers a PHP function or user-defined function for use as an SQL aggregate function for use within SQL statements.

Parametry

name

Name of the SQL aggregate to be created or redefined.

step_callback

The name of a PHP function or user-defined function to apply as a callback for every item in the aggregate.

final_callback

The name of a PHP function or user-defined function to apply as a callback at the end of the aggregate data.

argument_count

The number of arguments that the SQL aggregate takes. If this parameter is negative, then the SQL aggregate may take any number of arguments.

Zwracane wartości

Returns TRUE upon successful creation of the aggregate, FALSE on failure.

SQLite3::__construct
SQLite3::createFunction
SQLite3


Registers a PHP function for use as an SQL scalar function

SQLite3::createAggregate
SQLite3::escapeString
SQLite3
PHP Manual

SQLite3::createFunction

(PHP 5 >= 5.3.0)

SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function

Opis

public bool SQLite3::createFunction ( string $name , mixed $callback [, int $argument_count = -1 ] )

Registers a PHP function or user-defined function for use as an SQL scalar function for use within SQL statements.

Parametry

name

Name of the SQL function to be created or redefined.

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the SQL function.

argument_count

The number of arguments that the SQL function takes. If this parameter is negative, then the SQL function may take any number of arguments.

Zwracane wartości

Returns TRUE upon successful creation of the function, FALSE on failure.

Przykłady

Przykład #1 SQLite3::createFunction() example

<?php
function my_udf_md5($string) {
    return md5($string);
}

$db = new SQLite3('mysqlitedb.db');
$db->createFunction('my_udf_md5', 'my_udf_md5');

var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>

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

string(32) "098f6bcd4621d373cade4e832627b4f6"

SQLite3::createAggregate
SQLite3::escapeString
SQLite3


Returns a string that has been properly escaped

SQLite3::createFunction
SQLite3::exec
SQLite3
PHP Manual

SQLite3::escapeString

(PHP 5 >= 5.3.0)

SQLite3::escapeString — Returns a string that has been properly escaped

Opis

public string SQLite3::escapeString ( string $value )

Returns a string that has been properly escaped for safe inclusion in an SQL statement.

Parametry

value

The string to be escaped.

Zwracane wartości

Returns a properly escaped string that may be used safely in an SQL statement.

Notatki

Ostrzeżenie

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

SQLite3::createFunction
SQLite3::exec
SQLite3


Executes a result-less query against a given database

SQLite3::escapeString
SQLite3::lastErrorCode
SQLite3
PHP Manual

SQLite3::exec

(PHP 5 >= 5.3.0)

SQLite3::exec — Executes a result-less query against a given database

Opis

public bool SQLite3::exec ( string $query )

Executes a result-less query against a given database.

Parametry

query

The SQL query to execute (typically an INSERT, UPDATE, or DELETE query).

Zwracane wartości

Returns TRUE if the query succeeded, FALSE on failure.

Przykłady

Przykład #1 SQLite3::exec() example

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE bar (bar STRING)');
?>

SQLite3::escapeString
SQLite3::lastErrorCode
SQLite3


Returns the numeric result code of the most recent failed SQLite request

SQLite3::exec
SQLite3::lastErrorMsg
SQLite3
PHP Manual

SQLite3::lastErrorCode

(PHP 5 >= 5.3.0)

SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request

Opis

public int SQLite3::lastErrorCode ( void )

Returns the numeric result code of the most recent failed SQLite request.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer value representing the numeric result code of the most recent failed SQLite request.

SQLite3::exec
SQLite3::lastErrorMsg
SQLite3


Returns English text describing the most recent failed SQLite request

SQLite3::lastErrorCode
SQLite3::lastInsertRowID
SQLite3
PHP Manual

SQLite3::lastErrorMsg

(PHP 5 >= 5.3.0)

SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request

Opis

public string SQLite3::lastErrorMsg ( void )

Returns English text describing the most recent failed SQLite request.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an English string describing the most recent failed SQLite request.

SQLite3::lastErrorCode
SQLite3::lastInsertRowID
SQLite3


Returns the row ID of the most recent INSERT into the database

SQLite3::lastErrorMsg
SQLite3::loadExtension
SQLite3
PHP Manual

SQLite3::lastInsertRowID

(PHP 5 >= 5.3.0)

SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database

Opis

public int SQLite3::lastInsertRowID ( void )

Returns the row ID of the most recent INSERT into the database.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the row ID of the most recent INSERT into the database

SQLite3::lastErrorMsg
SQLite3::loadExtension
SQLite3


Attempts to load an SQLite extension library

SQLite3::lastInsertRowID
SQLite3::open
SQLite3
PHP Manual

SQLite3::loadExtension

(PHP 5 >= 5.3.0)

SQLite3::loadExtension — Attempts to load an SQLite extension library

Opis

public bool SQLite3::loadExtension ( string $shared_library )

Attempts to load an SQLite extension library.

Parametry

shared_library

The name of the library to load. The library must be located in the directory specified in the configure option sqlite3.extension_dir.

Zwracane wartości

Returns TRUE if the extension is successfully loaded, FALSE on failure.

Przykłady

Przykład #1 SQLite3::loadExtension() example

<?php
$db = new SQLite3('mysqlitedb.db');
$db->loadExtension('libagg.so');
?>

SQLite3::lastInsertRowID
SQLite3::open
SQLite3


Opens an SQLite database

SQLite3::loadExtension
SQLite3::prepare
SQLite3
PHP Manual

SQLite3::open

(PHP 5 >= 5.3.0)

SQLite3::open — Opens an SQLite database

Opis

public void SQLite3::open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key ]] )

Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.

Parametry

filename

Path to the SQLite database, or :memory: to use in-memory database.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryption_key

An optional encryption key used when encrypting and decrypting an SQLite database.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SQLite3::open() example

<?php
/**
 * Simple example of extending the SQLite3 class and changing the __construct
 * parameters, then using the open method to initialize the DB.
 */
class MyDB extends SQLite3
{
    function __construct()
    {
        $this->open('mysqlitedb.db');
    }
}

$db = new MyDB();

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

SQLite3::loadExtension
SQLite3::prepare
SQLite3


Prepares an SQL statement for execution

SQLite3::open
SQLite3::query
SQLite3
PHP Manual

SQLite3::prepare

(PHP 5 >= 5.3.0)

SQLite3::prepare — Prepares an SQL statement for execution

Opis

public SQLite3Stmt SQLite3::prepare ( string $query )

Prepares an SQL statement for execution and returns an SQLite3Stmt object.

Parametry

query

The SQL query to prepare.

Zwracane wartości

Returns an SQLite3Stmt object on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 SQLite3::prepare() example

<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray());
?>

SQLite3::open
SQLite3::query
SQLite3


Executes an SQL query

SQLite3::prepare
SQLite3::querySingle
SQLite3
PHP Manual

SQLite3::query

(PHP 5 >= 5.3.0)

SQLite3::query — Executes an SQL query

Opis

public SQLite3Result SQLite3::query ( string $query )

Executes an SQL query, returning an SQLite3Result object if the query returns results.

Parametry

query

The SQL query to execute.

Zwracane wartości

Returns an SQLite3Result object if the query returns results. Otherwise, returns TRUE if the query succeeded, FALSE on failure.

Przykłady

Przykład #1 SQLite3::query() example

<?php
$db = new SQLite3('mysqlitedb.db');

$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
    var_dump($row);
}
?>

SQLite3::prepare
SQLite3::querySingle
SQLite3


Executes a query and returns a single result

SQLite3::query
SQLite3::version
SQLite3
PHP Manual

SQLite3::querySingle

(PHP 5 >= 5.3.0)

SQLite3::querySingle — Executes a query and returns a single result

Opis

public mixed SQLite3::querySingle ( string $query [, bool $entire_row = false ] )

Executes a query and returns a single result.

Parametry

query

The SQL query to execute.

entire_row

By default, querySingle() returns the value of the first column returned by the query. If entire_row is TRUE, then it returns an array of the entire first row.

Zwracane wartości

Returns the value of the first column of results or an array of the entire first row (if entire_row is TRUE).

If the query is valid but no results are returned, then NULL will be returned if entire_row is FALSE, otherwise an empty array is returned.

Invalid or failing queries will return FALSE.

Przykłady

Przykład #1 SQLite3::querySingle() example

<?php
$db = new SQLite3('mysqlitedb.db');

var_dump($db->querySingle('SELECT username FROM user WHERE userid=1'));
print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1', true));
?>

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

string(5) "Scott"
Array
(
    [username] => Scott
    [email] => scott@example.com
)

SQLite3::query
SQLite3::version
SQLite3


Returns the SQLite3 library version as a string constant and as a number

SQLite3::querySingle
SQLite3Stmt
SQLite3
PHP Manual

SQLite3::version

(PHP 5 >= 5.3.0)

SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

Opis

public array SQLite3::version ( void )

Returns the SQLite3 library version as a string constant and as a number.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an associative array with the keys "versionString" and "versionNumber".

Przykłady

Przykład #1 SQLite3::version() example

<?php
print_r(SQLite3::version());
?>

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

Array
(
    [versionString] => 3.5.9
    [versionNumber] => 3005009
)

SQLite3::querySingle
SQLite3Stmt
SQLite3


The SQLite3Stmt class

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

Wstęp

A class that handles prepared statements for the SQLite 3 extension.

Krótki opis klasy

SQLite3Stmt {
/* Metody */
public bool bindParam ( string $sql_param , mixed &$param [, int $type ] )
public bool bindValue ( string $sql_param , mixed $value [, int $type ] )
public bool clear ( void )
public bool close ( void )
public SQLite3Result execute ( void )
public int paramCount ( void )
public bool reset ( void )
}

Spis treści

  • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
  • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
  • SQLite3Stmt::clear — Clears all current bound parameters
  • SQLite3Stmt::close — Closes the prepared statement
  • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
  • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
  • SQLite3Stmt::reset — Resets the prepared statement
SQLite3::version
SQLite3Stmt::bindParam
SQLite3


Binds a parameter to a statement variable

SQLite3Stmt
SQLite3Stmt::bindValue
SQLite3Stmt
PHP Manual

SQLite3Stmt::bindParam

(PHP 5 >= 5.3.0)

SQLite3Stmt::bindParam — Binds a parameter to a statement variable

Opis

public bool SQLite3Stmt::bindParam ( string $sql_param , mixed &$param [, int $type ] )

Binds a parameter to a statement variable.

Parametry

sql_param

An string identifying the statement variable to which the parameter should be bound.

param

The parameter to bind to a statement variable.

type

The data type of the parameter to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

Zwracane wartości

Returns TRUE if the parameter is bound to the statement variable, FALSE on failure.

SQLite3Stmt
SQLite3Stmt::bindValue
SQLite3Stmt


Binds the value of a parameter to a statement variable

SQLite3Stmt::bindParam
SQLite3Stmt::clear
SQLite3Stmt
PHP Manual

SQLite3Stmt::bindValue

(PHP 5 >= 5.3.0)

SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable

Opis

public bool SQLite3Stmt::bindValue ( string $sql_param , mixed $value [, int $type ] )

Binds the value of a parameter to a statement variable.

Parametry

sql_param

An string identifying the statement variable to which the value should be bound.

value

The value to bind to a statement variable.

type

The data type of the value to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

Zwracane wartości

Returns TRUE if the value is bound to the statement variable, FALSE on failure.

Przykłady

Przykład #1 SQLite3Stmt::bindValue() example

<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray());
?>

SQLite3Stmt::bindParam
SQLite3Stmt::clear
SQLite3Stmt


Clears all current bound parameters

SQLite3Stmt::bindValue
SQLite3Stmt::close
SQLite3Stmt
PHP Manual

SQLite3Stmt::clear

(PHP 5 >= 5.3.0)

SQLite3Stmt::clear — Clears all current bound parameters

Opis

public bool SQLite3Stmt::clear ( void )

Clears all current bound parameters.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on successful clearing of bound parameters, FALSE on failure.

SQLite3Stmt::bindValue
SQLite3Stmt::close
SQLite3Stmt


Closes the prepared statement

SQLite3Stmt::clear
SQLite3Stmt::execute
SQLite3Stmt
PHP Manual

SQLite3Stmt::close

(PHP 5 >= 5.3.0)

SQLite3Stmt::close — Closes the prepared statement

Opis

public bool SQLite3Stmt::close ( void )

Closes the prepared statement.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE

SQLite3Stmt::clear
SQLite3Stmt::execute
SQLite3Stmt


Executes a prepared statement and returns a result set object

SQLite3Stmt::close
SQLite3Stmt::paramCount
SQLite3Stmt
PHP Manual

SQLite3Stmt::execute

(PHP 5 >= 5.3.0)

SQLite3Stmt::execute — Executes a prepared statement and returns a result set object

Opis

public SQLite3Result SQLite3Stmt::execute ( void )

Executes a prepared statement and returns a result set object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an SQLite3Result object on successful execution of the prepared statement, FALSE on failure.

SQLite3Stmt::close
SQLite3Stmt::paramCount
SQLite3Stmt


Returns the number of parameters within the prepared statement

SQLite3Stmt::execute
SQLite3Stmt::reset
SQLite3Stmt
PHP Manual

SQLite3Stmt::paramCount

(PHP 5 >= 5.3.0)

SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement

Opis

public int SQLite3Stmt::paramCount ( void )

Returns the number of parameters within the prepared statement.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the number of parameters within the prepared statement.

SQLite3Stmt::execute
SQLite3Stmt::reset
SQLite3Stmt


Resets the prepared statement

SQLite3Stmt::paramCount
SQLite3Result
SQLite3Stmt
PHP Manual

SQLite3Stmt::reset

(PHP 5 >= 5.3.0)

SQLite3Stmt::reset — Resets the prepared statement

Opis

public bool SQLite3Stmt::reset ( void )

Resets the prepared statement to its state prior to execution. All bindings remain intact after reset.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the statement is successfully reset, FALSE on failure.

SQLite3Stmt::paramCount
SQLite3Result
SQLite3Stmt


The SQLite3Result class

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

Wstęp

A class that handles result sets for the SQLite 3 extension.

Krótki opis klasy

SQLite3Result {
/* Metody */
public string columnName ( int $column_number )
public int columnType ( int $column_number )
public array fetchArray ([ int $mode = SQLITE3_BOTH ] )
public bool finalize ( void )
public int numColumns ( void )
public bool reset ( void )
}

Spis treści

  • SQLite3Result::columnName — Returns the name of the nth column
  • SQLite3Result::columnType — Returns the type of the nth column
  • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
  • SQLite3Result::finalize — Closes the result set
  • SQLite3Result::numColumns — Returns the number of columns in the result set
  • SQLite3Result::reset — Resets the result set back to the first row
SQLite3Stmt::reset
SQLite3Result::columnName
SQLite3


Returns the name of the nth column

SQLite3Result
SQLite3Result::columnType
SQLite3Result
PHP Manual

SQLite3Result::columnName

(PHP 5 >= 5.3.0)

SQLite3Result::columnName — Returns the name of the nth column

Opis

public string SQLite3Result::columnName ( int $column_number )

Returns the name of the column specified by the column_number.

Parametry

column_number

The numeric zero-based index of the column.

Zwracane wartości

Returns the string name of the column identified by column_number.

SQLite3Result
SQLite3Result::columnType
SQLite3Result


Returns the type of the nth column

SQLite3Result::columnName
SQLite3Result::fetchArray
SQLite3Result
PHP Manual

SQLite3Result::columnType

(PHP 5 >= 5.3.0)

SQLite3Result::columnType — Returns the type of the nth column

Opis

public int SQLite3Result::columnType ( int $column_number )

Returns the type of the column identified by column_number.

Parametry

column_number

The numeric zero-based index of the column.

Zwracane wartości

Returns the data type index of the column identified by column_number (one of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, or SQLITE3_NULL).

SQLite3Result::columnName
SQLite3Result::fetchArray
SQLite3Result


Fetches a result row as an associative or numerically indexed array or both

SQLite3Result::columnType
SQLite3Result::finalize
SQLite3Result
PHP Manual

SQLite3Result::fetchArray

(PHP 5 >= 5.3.0)

SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both

Opis

public array SQLite3Result::fetchArray ([ int $mode = SQLITE3_BOTH ] )

Fetches a result row as an associative or numerically indexed array or both. By default, fetches as both.

Parametry

mode

Controls how the next row will be returned to the caller. This value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH.

  • SQLITE3_ASSOC: returns an array indexed by column name as returned in the corresponding result set

  • SQLITE3_NUM: returns an array indexed by column number as returned in the corresponding result set, starting at column 0

  • SQLITE3_BOTH: returns an array indexed by both column name and number as returned in the corresponding result set, starting at column 0

Zwracane wartości

Returns a result row as an associatively or numerically indexed array or both.

SQLite3Result::columnType
SQLite3Result::finalize
SQLite3Result


Closes the result set

SQLite3Result::fetchArray
SQLite3Result::numColumns
SQLite3Result
PHP Manual

SQLite3Result::finalize

(PHP 5 >= 5.3.0)

SQLite3Result::finalize — Closes the result set

Opis

public bool SQLite3Result::finalize ( void )

Closes the result set.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE.

SQLite3Result::fetchArray
SQLite3Result::numColumns
SQLite3Result


Returns the number of columns in the result set

SQLite3Result::finalize
SQLite3Result::reset
SQLite3Result
PHP Manual

SQLite3Result::numColumns

(PHP 5 >= 5.3.0)

SQLite3Result::numColumns — Returns the number of columns in the result set

Opis

public int SQLite3Result::numColumns ( void )

Returns the number of columns in the result set.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the number of columns in the result set.

SQLite3Result::finalize
SQLite3Result::reset
SQLite3Result


Resets the result set back to the first row

SQLite3Result::numColumns
SQLSRV
SQLite3Result
PHP Manual

SQLite3Result::reset

(PHP 5 >= 5.3.0)

SQLite3Result::reset — Resets the result set back to the first row

Opis

public bool SQLite3Result::reset ( void )

Resets the result set back to the first row.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the result set is successfully reset back to the first row, FALSE on failure.

SQLite3Result::numColumns
SQLSRV
SQLite3Result


Microsoft SQL Server Driver for PHP

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • SQLSRV Funkcje
    • sqlsrv_begin_transaction — Begins a database transaction
    • sqlsrv_cancel — Cancels a statement
    • sqlsrv_client_info — Returns information about the client and specified connection
    • sqlsrv_close — Closes an open connection and releases resourses associated with the connection
    • sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_configure — Changes the driver error handling and logging configurations
    • sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
    • sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
    • sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare
    • sqlsrv_fetch_array — Returns a row as an array
    • sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
    • sqlsrv_fetch — Makes the next row in a result set available for reading
    • sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
    • sqlsrv_free_stmt — Frees all resources for the specified statement
    • sqlsrv_get_config — Returns the value of the specified configuration setting
    • sqlsrv_get_field — Gets field data from the currently selected row
    • sqlsrv_has_rows — Indicates whether the specified statement has rows
    • sqlsrv_next_result — Makes the next result of the specified statement active
    • sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows — Retrieves the number of rows in a result set
    • sqlsrv_prepare — Prepares a query for execution
    • sqlsrv_query — Prepares and executes a query.
    • sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data — Sends data from parameter streams to the server
    • sqlsrv_server_info — Returns information about the server
SQLite3Result::reset
Wstęp
Rozszerzenia producentów baz danych


Wstęp

The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases when running PHP on Windows.

The SQLSRV extension is supported by Microsoft and available for download here: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

SQLSRV
Instalacja/Konfiguracja
SQLSRV


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SQLSRV


Wymagania

The SQLSRV extension can be used on the following operating systems:

  • Windows Server 2003 Service Pack 1
  • Windows XP Service Pack 3
  • Windows Vista Service Pack 1 or later
  • Windows Server 2008
  • Windows Server 2008 R2
  • Windows 7

The SQLSRV extension requires that the Microsoft SQL Server 2008 R2 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2008 R2 is not already installed, click the appropriate link below to download it:

  • » Download the x86 package
  • » Download the x64 package

The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

The SQLSRV extension is only compatible with PHP running on Windows.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

The following table lists the configuration options available in the SQLSRV extension. For more information about these options, see » Handling SQLSRV Warnings and Errors.

SQLSRV Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Changelog
sqlsrv.WarningsReturnAsErrors | 1 (TRUE) | PHP_INI_ALL | Available since SQLSRV 1.0
sqlsrv.LogSubsystems | 0 | PHP_INI_ALL | Available since SQLSRV 1.0
sqlsrv.LogSeverity | 1 | PHP_INI_ALL | Available since SQLSRV 1.0

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

Connection resource

A connection resource returned by sqlsrv_connect().

Statement resource

A statement resource returned by sqlsrv_query() or by sqlsrv_prepare().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

SQLSRV_FETCH_ASSOC (integer)
Forces sqlsrv_fetch_array() to return an associative array when passed as a parameter.
SQLSRV_FETCH_NUMERIC (integer)
Forces sqlsrv_fetch_array() to return an array with numeric when passed as a parameter.
SQLSRV_FETCH_BOTH (integer)
Forces sqlsrv_fetch_array() to return an array with both associative and numeric keys when passed as a parameter (the default behavior).
SQLSRV_ERR_ALL (integer)
Forces sqlsrv_errors() to return both errors and warings when passed as a parameter (the default behavior).
SQLSRV_ERR_ERRORS (integer)
Forces sqlsrv_errors() to return errors only (no warnings) when passed as a parameter.
SQLSRV_ERR_WARNINGS (integer)
Forces sqlsrv_errors() to return warnings only (no errors) when passed as a parameter.
SQLSRV_LOG_SYSTEM_ALL (integer)
Turns on logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_CONN (integer)
Turns on logging of connection activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_INIT (integer)
Turns on logging of initialization activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_OFF (integer)
Turns off logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_STMT (integer)
Turns on logging of statement activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_UTIL (integer)
Turns on logging of error function activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ALL (integer)
Specifies that errors, warnings, and notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ERROR (integer)
Specifies that errors will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_NOTICE (integer)
Specifies that notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_WARNING (integer)
Specifies that warnings will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_NULLABLE_YES (integer)
Indicates that a column is nullable.
SQLSRV_NULLABLE_NO (integer)
Indicates that a column is not nullable.
SQLSRV_NULLABLE_UNKNOWN (integer)
Indicates that it is not known if a column is nullable.
SQLSRV_PARAM_IN (integer)
Indicates an input parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_INOUT (integer)
Indicates a bidirectional parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_OUT (integer)
Indicates an output parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PHPTYPE_INT (integer)
Specifies an integer PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_DATETIME (integer)
Specifies a datetime PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_FLOAT (integer)
Specifies a float PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STREAM (integer)
Specifies a PHP stream. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STRING (integer)
Specifies a string PHP data type. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
SQLSRV_ENC_BINARY (integer)
Specifies that data is returned as a raw byte stream from the server without performing encoding or translation. For usage information, see » How to: Specify PHP Types.
SQLSRV_ENC_CHAR (integer)
Data is returned in 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This is the default encoding. For usage information, see » How to: Specify PHP Types.
UTF-8 (integer)
Specifies that data is returned with UTF-8 encoding. For usage information, see » How to: Specify PHP Types.
SQLSRV_SQLTYPE_BIGINT (integer)
Describes the bigint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BINARY (integer)
Describes the binary SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BIT (integer)
Describes the bit SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_CHAR (integer)
Describes the char SQL Server data type. This constant works like a function and accepts a parameter indicating the number characters. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATE (integer)
Describes the date SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME (integer)
Describes the datetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME2 (integer)
Describes the datetime2 SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIMEOFFSET (integer)
Describes the datetimeoffset SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DECIMAL (integer)
Describes the decimal SQL Server data type. This constant works like a function and accepts two parameters indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_FLOAT (integer)
Describes the float SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_IMAGE (integer)
Describes the image SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_INT (integer)
Describes the int SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_MONEY (integer)
Describes the money SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NCHAR (integer)
Describes the nchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NUMERIC (integer)
Describes the numeric SQL Server data type. This constant works like a function and accepts two parameter indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NVARCHAR (integer)
Describes the nvarchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NVARCHAR('max') (integer)
Describes the nvarchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NTEXT (integer)
Describes the ntext SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_REAL (integer)
Describes the real SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLDATETIME (integer)
Describes the smalldatetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLINT (integer)
Describes the smallint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLMONEY (integer)
Describes the smallmoney SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TEXT (integer)
Describes the text SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIME (integer)
Describes the time SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIMESTAMP (integer)
Describes the timestamp SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TINYINT (integer)
Describes the tinyint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UNIQUEIDENTIFIER (integer)
Describes the uniqueidentifier SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UDT (integer)
Describes the UDT SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY (integer)
Describes the varbinary SQL Server data type. This constant works like a function and accepts a single parameter indicating the byte count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY('max') (integer)
Describes the varbinary(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR (integer)
Describes the varchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR('max') (integer)
Describes the varchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_XML (integer)
Describes the XML SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_TXN_READ_UNCOMMITTED (integer)
Inidicates a transaction isolation level of READ UNCOMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_READ_COMMITTED (integer)
Inidicates a transaction isolation level of READ COMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_REPEATABLE_READ (integer)
Inidicates a transaction isolation level of REPEATABLE READ. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_SNAPSHOT (integer)
Inidicates a transaction isolation level of SNAPSHOT. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_TXN_READ_SERIALIZABLE (integer)
Inidicates a transaction isolation level of SERIALIZABLE. This value is used to set the TransactionIsolation level in the $connectionOptions arrary passed to sqlsrv_connect().
SQLSRV_CURSOR_FORWARD (integer)
Inidicates a forward-only cursor. For usage information, see » How to: Specify a Cursor Type.
SQLSRV_CURSOR_STATIC (integer)
Inidicates a static cursor. For usage information, see » How to: Specify a Cursor Type.
SQLSRV_DYNAMIC (integer)
Inidicates a dynamic cursor. For usage information, see » How to: Specify a Cursor Type.
SQLSRV_CURSOR_KEYSET (integer)
Inidicates a keyset cursor. For usage information, see » How to: Specify a Cursor Type.
SQLSRV_SCROLL_NEXT (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_PRIOR (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_FIRST (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_LAST (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_ABSOLUTE (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.
SQLSRV_SCROLL_RELATIVE (integer)
Specifies which row to select in a result set. For usage information, see » How to: Specify a Cursor Type and Select Rows.

Typy zasobów
SQLSRV Funkcje
SQLSRV


SQLSRV Funkcje

Spis treści

  • sqlsrv_begin_transaction — Begins a database transaction
  • sqlsrv_cancel — Cancels a statement
  • sqlsrv_client_info — Returns information about the client and specified connection
  • sqlsrv_close — Closes an open connection and releases resourses associated with the connection
  • sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_configure — Changes the driver error handling and logging configurations
  • sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
  • sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare
  • sqlsrv_fetch_array — Returns a row as an array
  • sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
  • sqlsrv_fetch — Makes the next row in a result set available for reading
  • sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
  • sqlsrv_free_stmt — Frees all resources for the specified statement
  • sqlsrv_get_config — Returns the value of the specified configuration setting
  • sqlsrv_get_field — Gets field data from the currently selected row
  • sqlsrv_has_rows — Indicates whether the specified statement has rows
  • sqlsrv_next_result — Makes the next result of the specified statement active
  • sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
  • sqlsrv_num_rows — Retrieves the number of rows in a result set
  • sqlsrv_prepare — Prepares a query for execution
  • sqlsrv_query — Prepares and executes a query.
  • sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
  • sqlsrv_send_stream_data — Sends data from parameter streams to the server
  • sqlsrv_server_info — Returns information about the server
Stałe predefiniowane
sqlsrv_begin_transaction
SQLSRV


Begins a database transaction

SQLSRV Funkcje
sqlsrv_cancel
SQLSRV Funkcje
PHP Manual

sqlsrv_begin_transaction

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

sqlsrv_begin_transaction — Begins a database transaction

Opis

bool sqlsrv_begin_transaction ( resource $conn )

The transaction begun by sqlsrv_begin_transaction() includes all statements that were executed after the call to sqlsrv_begin_transaction() and before calls to sqlsrv_rollback() or sqlsrv_commit(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and committ/roll back transactions. For more information, see » SQLSRV Transactions.

Parametry

conn

The connection resource returned by a call to sqlsrv_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 sqlsrv_begin_transaction() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
          VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
          SET Quantity = (Quantity - ?)
          WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     sqlsrv_commit( $conn );
     echo "Transaction committed.<br />";
} else {
     sqlsrv_rollback( $conn );
     echo "Transaction rolled back.<br />";
}
?>

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

Zobacz też:

  • sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

SQLSRV Funkcje
sqlsrv_cancel
SQLSRV Funkcje


Cancels a statement

sqlsrv_begin_transaction
sqlsrv_client_info
SQLSRV Funkcje
PHP Manual

sqlsrv_cancel

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

sqlsrv_cancel — Cancels a statement

Opis

bool sqlsrv_cancel ( resource $stmt )

Cancels a statement. Any results associated with the statement that have not been consumed are deleted. After sqlsrv_cancel() has been called, the specified statement can be re-executed if it was created with sqlsrv_prepare(). Calling sqlsrv_cancel() is not necessary if all the results associated with the statement have been consumed.

Parametry

stmt

The statement resource to be cancelled.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 sqlsrv_cancel() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Sales FROM Table_1";

$stmt = sqlsrv_prepare( $conn, $sql);

if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

if( sqlsrv_execute( $stmt ) === false) {
     die( print_r( sqlsrv_errors(), true));
}

$salesTotal = 0;
$count = 0;

while( ($row = sqlsrv_fetch_array( $stmt)) && $salesTotal <=100000)
{
     $qty = $row[0];
     $price = $row[1];
     $salesTotal += ( $price * $qty);
     $count++;
}

echo "$count sales accounted for the first $$salesTotal in revenue.<br />";

// Cancel the pending results. The statement can be reused.
sqlsrv_cancel( $stmt);
?>

Notatki

The main difference between sqlsrv_cancel() and sqlsrv_free_stmt() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

Zobacz też:

  • sqlsrv_free_stmt() - Frees all resources for the specified statement
  • sqlsrv_prepare() - Prepares a query for execution

sqlsrv_begin_transaction
sqlsrv_client_info
SQLSRV Funkcje


Returns information about the client and specified connection

sqlsrv_cancel
sqlsrv_close
SQLSRV Funkcje
PHP Manual

sqlsrv_client_info

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

sqlsrv_client_info — Returns information about the client and specified connection

Opis

array sqlsrv_client_info ( resource $conn )

Returns information about the client and specified connection

Parametry

conn

The connection about which information is returned.

Zwracane wartości

Returns an associative array with keys described in the table below. Returns FALSE otherwise.

Array returned by sqlsrv_client_info
Key | Description
DriverDllName | SQLNCLI10.DLL
DriverODBCVer | ODBC version (xx.yy)
DriverVer | SQL Server Native Client DLL version (10.5.xxx)
ExtensionVer | php_sqlsrv.dll version (2.0.xxx.x)

Przykłady

Przykład #1 sqlsrv_client_info() example

<?php
$serverName = "serverName\sqlexpress";
$connOptions = array("UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connOptions );

if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

if( $client_info = sqlsrv_client_info( $conn)) {
    foreach( $client_info as $key => $value) {
        echo $key.": ".$value."<br />";
    }
} else {
    echo "Error in retrieving client info.<br />";
}
?>

Zobacz też:

  • sqlsrv_server_info() - Returns information about the server

sqlsrv_cancel
sqlsrv_close
SQLSRV Funkcje


Closes an open connection and releases resourses associated with the connection

sqlsrv_client_info
sqlsrv_commit
SQLSRV Funkcje
PHP Manual

sqlsrv_close

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

sqlsrv_close — Closes an open connection and releases resourses associated with the connection

Opis

bool sqlsrv_close ( resource $conn )

Closes an open connection and releases resourses associated with the connection.

Parametry

conn

The connection to be closed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 sqlsrv_close() example

<?php
$serverName = "serverName\sqlexpres";
$connOptions = array("UID"=>"username", "PWD"=>"password", "Database"=>"dbname");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

//-------------------------------------
// Perform database operations here.
//-------------------------------------

// Close the connection.
sqlsrv_close( $conn );
?>

Zobacz też:

  • sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database

sqlsrv_client_info
sqlsrv_commit
SQLSRV Funkcje


Commits a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_close
sqlsrv_configure
SQLSRV Funkcje
PHP Manual

sqlsrv_commit

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

sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction()

Opis

bool sqlsrv_commit ( resource $conn )

Commits a transaction that was begun with sqlsrv_begin_transaction(). The connection is returned to auto-commit mode after sqlsrv_commit() is called. The transaction that is committed includes all statements that were executed after the call to sqlsrv_begin_transaction(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and committ/roll back transactions. For more information, see » SQLSRV Transactions.

Parametry

conn

The connection on which the transaction is to be committed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 sqlsrv_commit() example

The following example demonstrates how to use sqlsrv_commit() together with sqlsrv_begin_transaction() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
         VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
         SET Quantity = (Quantity - ?)
         WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     sqlsrv_commit( $conn );
     echo "Transaction committed.<br />";
} else {
     sqlsrv_rollback( $conn );
     echo "Transaction rolled back.<br />";
}
?>

Zobacz też:

  • sqlsrv_begin_transaction() - Begins a database transaction
  • sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_close
sqlsrv_configure
SQLSRV Funkcje


Changes the driver error handling and logging configurations

sqlsrv_commit
sqlsrv_connect
SQLSRV Funkcje
PHP Manual

sqlsrv_configure

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

sqlsrv_configure — Changes the driver error handling and logging configurations

Opis

bool sqlsrv_configure ( string $setting , mixed $value )

Changes the driver error handling and logging configurations.

Parametry

setting

The name of the setting to set. The possible values are "WarningsReturnAsErrors", "LogSubsystems", and "LogSeverity".

value

The value of the specified setting. The following table shows possible values:

Error and Logging Setting Options
Setting | Options
WarningsReturnAsErrors | 1 (TRUE) or 0 (FALSE)
LogSubsystems | SQLSRV_LOG_SYSTEM_ALL (-1) SQLSRV_LOG_SYSTEM_CONN (2) SQLSRV_LOG_SYSTEM_INIT (1) SQLSRV_LOG_SYSTEM_OFF (0) SQLSRV_LOG_SYSTEM_STMT (4) SQLSRV_LOG_SYSTEM_UTIL (8)
LogSeverity | SQLSRV_LOG_SEVERITY_ALL (-1) SQLSRV_LOG_SEVERITY_ERROR (1) SQLSRV_LOG_SEVERITY_NOTICE (4) SQLSRV_LOG_SEVERITY_WARNING (2)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • » SQLSRV Error Handling.
  • » Logging SQLSRV Activity.

sqlsrv_commit
sqlsrv_connect
SQLSRV Funkcje


Opens a connection to a Microsoft SQL Server database

sqlsrv_configure
sqlsrv_errors
SQLSRV Funkcje
PHP Manual

sqlsrv_connect

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

sqlsrv_connect — Opens a connection to a Microsoft SQL Server database

Opis

resource sqlsrv_connect ( string $serverName [, array $connectionInfo ] )

Opens a connection to a Microsoft SQL Server database. By default, the connection is attempted using Windows Authentication. To connect using SQL Server Authentication, include "UID" and "PWD" in the connection options array.

Parametry

serverName

The name of the server to which a connection is established. To connect to a specific instance, follow the server name with a forward slash and the instance name (e.g. serverName\sqlexpress).

connectionInfo

An associative array that specifies options for connecting to the server. If values for the UID and PWD keys are not specified, the connection will be attempted using Windows Authentication. For a complete list of supported keys, see » SQLSRV Connection Options.

Zwracane wartości

A connection resource. If a connection cannot be successfully opened, FALSE is returned.

Przykłady

Przykład #1 Connect using Windows Authentication.

<?php
$serverName = "serverName\sqlexpress"; //serverName\instanceName

// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Przykład #2 Connect by specifying a user name and password.

<?php
$serverName = "serverName\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Przykład #3 Connect on a specifed port.

<?php
$serverName = "serverName\sqlexpress, 1542"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Notatki

By default, the sqlsrv_connect() uses connection pooling to improve connection performance. To turn off connection pooling (i.e. force a new connection on each call), set the "ConnectionPooling" option in the $connectionOptions array to 0 (or FALSE). For more information, see » SQLSRV Connection Pooling.

The SQLSRV extension does not have a dedicated function for changing which database is connected to. The target database is specified in the $connectionOptions array that is passed to sqlsrv_connect. To change the database on an open connection, execute the following query "USE dbName" (e.g. sqlsrv_query($conn, "USE dbName")).

Zobacz też:

  • sqlsrv_close() - Closes an open connection and releases resourses associated with the connection
  • sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_query() - Prepares and executes a query.

sqlsrv_configure
sqlsrv_errors
SQLSRV Funkcje


Returns error and warning information about the last SQLSRV operation performed

sqlsrv_connect
sqlsrv_execute
SQLSRV Funkcje
PHP Manual

sqlsrv_errors

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

sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed

Opis

mixed sqlsrv_errors ([ int $errorsOrWarnings ] )

Returns error and warning information about the last SQLSRV operation performed.

Parametry

errorsOrWarnings

Determines whether error information, warning information, or both are returned. If this parameter is not supplied, both error information and warning information are returned. The following are the supported values for this parameter: SQLSRV_ERR_ALL, SQLSRV_ERR_ERRORS, SQLSRV_ERR_WARNINGS.

Zwracane wartości

If errors and/or warnings occured on the last sqlsrv operation, and array of arrays containing error information is returned. If no errors and/or warnings occured on the last sqlsrv operation, NULL is returned. The following table describes the structure of the returned arrays:

Array returned by sqlsrv_errors
Key | Description
SQLSTATE | For errors that originate from the ODBC driver, the SQLSTATE returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of IMSSP. For warnings that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of 01SSP.
code | For errors that originate from SQL Server, the native SQL Server error code. For errors that originate from the ODBC driver, the error code returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, the Microsoft Drivers for PHP for SQL Server error code.
message | A description of the error.

Przykłady

Przykład #1 functionname() example

<?php
$serverName = "serverName/sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

/* Set up a query to select an invalid column name. */
$sql = "SELECT BadColumnName FROM Table_1";

/* Execution of the query will fail because of the bad column name. */
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
    if( ($errors = sqlsrv_errors() ) != null) {
        foreach( $errors as $error ) {
            echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
            echo "code: ".$error[ 'code']."<br />";
            echo "message: ".$error[ 'message']."<br />";
        }
    }
}
?>

Notatki

By default, warnings generated on a call to any SQLSRV function are treated as errors. This means that if a warning occurs on a call to a SQLSRV function, the function returns FALSE. However, warnings that correspond to SQLSTATE values 01000, 01001, 01003, and 01S02 are never treated as errors. For information about changing this behavior, see sqlsrv_configure() and the WarningsReturnAsErrors setting.

Zobacz też:

  • sqlsrv_configure() - Changes the driver error handling and logging configurations

sqlsrv_connect
sqlsrv_execute
SQLSRV Funkcje


Executes a statement prepared with sqlsrv_prepare

sqlsrv_errors
sqlsrv_fetch_array
SQLSRV Funkcje
PHP Manual

sqlsrv_execute

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

sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare()

Opis

bool sqlsrv_execute ( resource $stmt )

Executes a statement prepared with sqlsrv_prepare(). This function is ideal for executing a prepared statement multiple times with different parameter values.

Parametry

stmt

A statement resource returned by sqlsrv_prepare().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 sqlsrv_execute() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1
        SET OrderQty = ?
        WHERE SalesOrderID = ?";

// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
    die( print_r( sqlsrv_errors(), true));
}

// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);

// Execute the statement for each order.
foreach( $orders as $id => $qty) {
    // Because $id and $qty are bound to $stmt1, their updated
    // values are used with each execution of the statement.
    if( sqlsrv_execute( $stmt ) === false ) {
          die( print_r( sqlsrv_errors(), true));
    }
}
?>

Notatki

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

Zobacz też:

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_query() - Prepares and executes a query.

sqlsrv_errors
sqlsrv_fetch_array
SQLSRV Funkcje


Returns a row as an array

sqlsrv_execute
sqlsrv_fetch_object
SQLSRV Funkcje
PHP Manual

sqlsrv_fetch_array

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

sqlsrv_fetch_array — Returns a row as an array

Opis

array sqlsrv_fetch_array ( resource $stmt [, int $fetchType [, int $row [, int $offset ]]] )

Returns the next available row of data as an associative array, a numeric array, or both (the default).

Parametry

stmt

A statement resource returned by sqlsrv_query or sqlsrv_execute.

fetchType

A predefined constant specifying the type of array to return. Possible values are SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC, and SQLSRV_FETCH_BOTH (the default).

A fetch type of SQLSRV_FETCH_ASSOC should not be used when consuming a result set with multiple columns of the same name.

row

Specifies the row to access in a result set that uses a scrollable cursor. Possible values are SQLSRV_SCROLL_NEXT, SQLSRV_SCROLL_PRIOR, SQLSRV_SCROLL_FIRST, SQLSRV_SCROLL_LAST, SQLSRV_SCROLL_ABSOLUTE and, SQLSRV_SCROLL_RELATIVE (the default). When this parameter is specified, the fetchType must be explicitly defined.

Zwracane wartości

Returns an array on success, NULL if there are no more rows to return, and FALSE if an error occurs.

Przykłady

Przykład #1 Retrieving an associative array.

<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
      echo $row['LastName'].", ".$row['FirstName']."<br />";
}

sqlsrv_free_stmt( $stmt);
?>

Przykład #2 Retrieving a numeric array.

<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
      echo $row[0].", ".$row[1]."<br />";
}

sqlsrv_free_stmt( $stmt);
?>

Notatki

Not specifying the fetchType or explicity using the SQLSRV_FETCH_TYPE constant in the examples above will return an array that has both associative and numeric keys.

If more than one column is returned with the same name, the last column will take precedence. To avoid field name collisions, use aliases.

If a column with no name is returned, the associative key for the array element will be an empty string ("").

Zobacz też:

  • sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database
  • sqlsrv_query() - Prepares and executes a query.
  • sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_fetch() - Makes the next row in a result set available for reading

sqlsrv_execute
sqlsrv_fetch_object
SQLSRV Funkcje


Retrieves the next row of data in a result set as an object

sqlsrv_fetch_array
sqlsrv_fetch
SQLSRV Funkcje
PHP Manual

sqlsrv_fetch_object

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

sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object

Opis

mixed sqlsrv_fetch_object ( resource $stmt [, string $className [, array $ctorParams [, int $row [, int $offset ]]]] )

Retrieves the next row of data in a result set as an instance of the specified class with properties that match the row field names and values that correspond to the row field values.

Parametry

stmt

A statement resource created by sqlsrv_query() or sqlsrv_execute().

className

The name of the class to instantiate. If no class name is specified, stdClass is instantiated.

ctorParams

Values passed to the constructor of the specified class. If the constructor of the specified class takes parameters, the ctorParams array must be supplied.

row

The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

Zwracane wartości

Returns an object on success, NULL if there are no more rows to return, and FALSE if an error occurs or if the specified class does not exist.

Przykłady

Przykład #1 sqlsrv_fetch_object() example

The following example demonstrates how to retrieve a row as a stdClass object.

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT fName, lName FROM Table_1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

// Retrieve each row as an object.
// Because no class is specified, each row will be retrieved as a stdClass object.
// Property names correspond to field names.
while( $obj = sqlsrv_fetch_object( $stmt)) {
      echo $obj->fName.", ".$obj->lName."<br />";
}
?>

Notatki

If a class name is specified with the optional $className parameter and the class has properties whose names match the result set field names, the corresponding result set values are applied to the properties. If a result set field name does not match a class property, a property with the result set field name is added to the object and the result set value is applied to the property. The following rules apply when using the $className parameter:

  • Field-property name matching is case-sensitive.
  • Field-property matching occurs regardless of access modifiers.
  • Class property data types are ignored when applying a field value to a property.
  • If the class does not exist, the function returns FALSE and adds an error to the error collection.
Regardless of whether the $className parameter is supplied, if a field with no name is returned, the field value will be ignored and a warning will be added to the error collection.

When consuming a result set that has multiple columns with the same name, it may be better to use sqlsrv_fetch_array() or the combination of sqlsrv_fetch() and sqlsrv_get_field().

Zobacz też:

  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_fetch_array() - Returns a row as an array

sqlsrv_fetch_array
sqlsrv_fetch
SQLSRV Funkcje


Makes the next row in a result set available for reading

sqlsrv_fetch_object
sqlsrv_field_metadata
SQLSRV Funkcje
PHP Manual

sqlsrv_fetch

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

sqlsrv_fetch — Makes the next row in a result set available for reading

Opis

mixed sqlsrv_fetch ( resource $stmt [, int $row [, int $offset ]] )

Makes the next row in a result set available for reading. Use sqlsrv_get_field() to read the fields of the row.

Parametry

stmt

A statement resource created by executing sqlsrv_query() or sqlsrv_execute().

row

The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

Zwracane wartości

Returns TRUE if the next row of a result set was successfully retrieved, FALSE if an error occurs, and NULL if there are no more rows in the result set.

Przykłady

Przykład #1 sqlsrv_fetch() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Name, Comment
        FROM Table_1
        WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
     die( print_r( sqlsrv_errors(), true));
}

// Get the row fields. Field indeces start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";

$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>

Zobacz też:

  • sqlsrv_get_field() - Gets field data from the currently selected row
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_fetch_object() - Retrieves the next row of data in a result set as an object

sqlsrv_fetch_object
sqlsrv_field_metadata
SQLSRV Funkcje


Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

sqlsrv_fetch
sqlsrv_free_stmt
SQLSRV Funkcje
PHP Manual

sqlsrv_field_metadata

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

sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query()

Opis

mixed sqlsrv_field_metadata ( resource $stmt )

Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query(). sqlsrv_field_metadata() can be called on a statement before or after statement execution.

Parametry

stmt

The statment resource for which metadata is returned.

Zwracane wartości

Returns an array of arrays is returned on success. Otherwise, FALSE is returned. Each returned array is described by the following table:

Array returned by sqlsrv_field_metadata
Key | Description
Name | The name of the field.
Type | The numeric value for the SQL type.
Size | The number of characters for fields of character type, the number of bytes for fields of binary type, or NULL for other types.
Precision | The precision for types of variable precision, NULL for other types.
Scale | The scale for types of variable scale, NULL for other types.
Nullable | An enumeration indicating whether the column is nullable, not nullable, or if it is not known.
For more information, see » sqlsrv_field_metadata in the Microsoft SQLSRV documentation.

Przykłady

Przykład #1 sqlsrv_field_metadata() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"AdventureWorks", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
   die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql );

foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) {
    foreach( $fieldMetadata as $name => $value) {
       echo "$name: $value<br />";
    }
      echo "<br />";
}
?>

Zobacz też:

  • sqlsrv_client_info() - Returns information about the client and specified connection

sqlsrv_fetch
sqlsrv_free_stmt
SQLSRV Funkcje


Frees all resources for the specified statement

sqlsrv_field_metadata
sqlsrv_get_config
SQLSRV Funkcje
PHP Manual

sqlsrv_free_stmt

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

sqlsrv_free_stmt — Frees all resources for the specified statement

Opis

bool sqlsrv_free_stmt ( resource $stmt )

Frees all resources for the specified statement. The statement cannot be used after sqlsrv_free_stmt() has been called on it. If sqlsrv_free_stmt() is called on an in-progress statement that alters server state, statement execution is terminated and the statement is rolled back.

Parametry

stmt

The statment for which resources are freed. Note that NULL is a valid parameter value. This allows the function to be called multiple times in a script.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 sqlsrv_free_stmt() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

/*-------------------------------
     Process query results here.
-------------------------------*/

/* Free the statement resources. */
sqlsrv_free_stmt( $stmt);

?>

Notatki

The main difference between sqlsrv_free_stmt() and sqlsrv_cancel() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

Zobacz też:

  • sqlsrv_cancel() - Cancels a statement

sqlsrv_field_metadata
sqlsrv_get_config
SQLSRV Funkcje


Returns the value of the specified configuration setting

sqlsrv_free_stmt
sqlsrv_get_field
SQLSRV Funkcje
PHP Manual

sqlsrv_get_config

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

sqlsrv_get_config — Returns the value of the specified configuration setting

Opis

mixed sqlsrv_get_config ( string $setting )

Returns the value of the specified configuration setting.

Parametry

setting

The name of the setting for which the value is returned. For a list of configurable settings, see sqlsrv_configure().

Zwracane wartości

Returns the value of the specified setting. If an invalid setting is specified, FALSE is returned.

Zobacz też:

  • sqlsrv_configure() - Changes the driver error handling and logging configurations

sqlsrv_free_stmt
sqlsrv_get_field
SQLSRV Funkcje


Gets field data from the currently selected row

sqlsrv_get_config
sqlsrv_has_rows
SQLSRV Funkcje
PHP Manual

sqlsrv_get_field

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

sqlsrv_get_field — Gets field data from the currently selected row

Opis

mixed sqlsrv_get_field ( resource $stmt , int $fieldIndex [, int $getAsType ] )

Gets field data from the currently selected row. Fields must be accessed in order. Field indices start at 0.

Parametry

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

fieldIndex

The index of the field to be retrieved. Field indices start at 0. Fields must be accessed in order. i.e. If you access field index 1, then field index 0 will not be available.

getAsType

The PHP data type for the returned field data. If this parameter is not set, the field data will be returned as its default PHP data type. For information about default PHP data types, see » Default PHP Data Types in the Microsoft SQLSRV documentation.

Zwracane wartości

Returns data from the specified field on success. Returns FALSE otherwise.

Przykłady

Przykład #1 sqlsrv_get_field() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Name, Comment
        FROM Table_1
        WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
     die( print_r( sqlsrv_errors(), true));
}

// Get the row fields. Field indeces start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";

$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>

Zobacz też:

  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_fetch_object() - Retrieves the next row of data in a result set as an object

sqlsrv_get_config
sqlsrv_has_rows
SQLSRV Funkcje


Indicates whether the specified statement has rows

sqlsrv_get_field
sqlsrv_next_result
SQLSRV Funkcje
PHP Manual

sqlsrv_has_rows

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

sqlsrv_has_rows — Indicates whether the specified statement has rows

Opis

bool sqlsrv_has_rows ( resource $stmt )

Indicates whether the specified statement has rows.

Parametry

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

Zwracane wartości

Returns TRUE if the specified statement has rows and FALSE if the statement does not have rows or if an error occured.

Przykłady

Przykład #1 sqlsrv_has_rows() example

<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" )
$conn = sqlsrv_connect( $server, $connectionInfo );

$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");

if ($stmt) {
   $rows = sqlsrv_has_rows( $stmt );
   if ($rows === true)
      echo "There are rows. <br />";
   else
      echo "There are no rows. <br />";
}
?>

Zobacz też:

  • sqlsrv_num_rows() - Retrieves the number of rows in a result set
  • sqlsrv_query() - Prepares and executes a query.

sqlsrv_get_field
sqlsrv_next_result
SQLSRV Funkcje


Makes the next result of the specified statement active

sqlsrv_has_rows
sqlsrv_num_fields
SQLSRV Funkcje
PHP Manual

sqlsrv_next_result

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

sqlsrv_next_result — Makes the next result of the specified statement active

Opis

mixed sqlsrv_next_result ( resource $stmt )

Makes the next result of the specified statement active. Results include result sets, row counts, and output parameters.

Parametry

stmt

The statment on which the next result is being called.

Zwracane wartości

Returns TRUE if the next result was successfully retrieved, FALSE if an error occurred, and NULL if there are no more results to retrieve.

Przykłady

Przykład #1 sqlsrv_next_result() example

The following example executes a batch query that inserts into a table and then selects from the table. This produces two results on the statement: one for the rows affected by the INSERT and one for the rows returned by the SELECT. To get to the rows returned by the SELECT, sqlsrv_next_result() must be called to move past the first result.

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array("Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

$query = "INSERT INTO Table_1 (id, data) VALUES (?,?); SELECT * FROM TABLE_1;";
$params = array(1, "some data");
$stmt = sqlsrv_query($conn, $query, $params);

// Consume the first result (rows affected by INSERT) without calling sqlsrv_next_result.
echo "Rows affected: ".sqlsrv_rows_affected($stmt)."<br />";

// Move to the next result and display results.
$next_result = sqlsrv_next_result($stmt);
if( $next_result ) {
   while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
      echo $row['id'].": ".$row['data']."<br />";
   }
} elseif( is_null($next_result)) {
     echo "No more results.<br />";
} else {
     die(print_r(sqlsrv_errors(), true));
}
?>

Zobacz też:

  • sqlsrv_query() - Prepares and executes a query.
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_rows_affected() - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

sqlsrv_has_rows
sqlsrv_num_fields
SQLSRV Funkcje


Retrieves the number of fields (columns) on a statement

sqlsrv_next_result
sqlsrv_num_rows
SQLSRV Funkcje
PHP Manual

sqlsrv_num_fields

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

sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement

Opis

mixed sqlsrv_num_fields ( resource $stmt )

Retrieves the number of fields (columns) on a statement.

Parametry

stmt

The statment for which the number of fields is returned. sqlsrv_num_fields() can be called on a statement before or after statement execution.

Zwracane wartości

Returns the number of fields on success. Returns FALSE otherwise.

Przykłady

Przykład #1 sqlsrv_num_fields() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
   die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
   die( print_r( sqlsrv_errors(), true));
}

$numFields = sqlsrv_num_fields( $stmt );

while( sqlsrv_fetch( $stmt )) {
   // Iterate through the fields of each row.
   for($i = 0; $i < $numFields; $i++) {
   {
      echo sqlsrv_get_field($stmt, $i)." ";
     }
     echo "<br />";
}
?>

Zobacz też:

  • sqlsrv_field_metadata() - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_get_field() - Gets field data from the currently selected row

sqlsrv_next_result
sqlsrv_num_rows
SQLSRV Funkcje


Retrieves the number of rows in a result set

sqlsrv_num_fields
sqlsrv_prepare
SQLSRV Funkcje
PHP Manual

sqlsrv_num_rows

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

sqlsrv_num_rows — Retrieves the number of rows in a result set

Opis

mixed sqlsrv_num_rows ( resource $stmt )

Retrieves the number of rows in a result set. This function requires that the statment resource be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Parametry

stmt

The statement for which the row count is returned. The statment resource must be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Zwracane wartości

Returns the number of rows retrieved on success and FALSE if an error occured. If a forward cursor (the default) or dynamic cursor is used, FALSE is returned.

Przykłady

Przykład #1 sqlsrv_num_rows() example

<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );

$sql = "SELECT * FROM Table_1";
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );

$row_count = sqlsrv_num_rows( $stmt );

if ($row_count === false)
   echo "Error in retrieveing row count.";
else
   echo $row_count;
?>

Zobacz też:

  • sqlsrv_has_rows() - Indicates whether the specified statement has rows
  • sqlsrv_rows_affected() - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

sqlsrv_num_fields
sqlsrv_prepare
SQLSRV Funkcje


Prepares a query for execution

sqlsrv_num_rows
sqlsrv_query
SQLSRV Funkcje
PHP Manual

sqlsrv_prepare

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

sqlsrv_prepare — Prepares a query for execution

Opis

mixed sqlsrv_prepare ( resource $conn , string $sql [, array $params [, array $options ]] )

Prepares a query for execution. This function is ideal for preparing a query that will be executed multiple times with different parameter values.

Parametry

conn

A connection resource returned by sqlsrv_connect().

sql

The string that defines the query to be prepared and executed.

params

An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  • A literal value
  • A PHP variable
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
The following table describes the elements in the array structure above:

Array structure
Element | Description
$value | A literal value, a PHP variable, or a PHP by-reference variable.
$direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
$phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
$sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.
options

An array specifing query property options. The supported keys are described in the following table:

Query Options
Key | Values | Description
QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
SendStreamParamsAtExec | TRUE or FALSE (the default is TRUE) | Configures the driver to send all stream data at execution (TRUE), or to send stream data in chunks (FALSE). By default, the value is set to TRUE. For more information, see sqlsrv_send_stream_data().
Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Zwracane wartości

Returns a statement resource on success and FALSE if an error occurred.

Przykłady

Przykład #1 sqlsrv_prepare() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1
        SET OrderQty = ?
        WHERE SalesOrderID = ?";

// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
    die( print_r( sqlsrv_errors(), true));
}

// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);

// Execute the statement for each order.
foreach( $orders as $id => $qty) {
    // Because $id and $qty are bound to $stmt1, their updated
    // values are used with each execution of the statement.
    if( sqlsrv_execute( $stmt ) === false ) {
          die( print_r( sqlsrv_errors(), true));
    }
}
?>

Notatki

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

Zobacz też:

  • sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare
  • sqlsrv_query() - Prepares and executes a query.

sqlsrv_num_rows
sqlsrv_query
SQLSRV Funkcje


Prepares and executes a query.

sqlsrv_prepare
sqlsrv_rollback
SQLSRV Funkcje
PHP Manual

sqlsrv_query

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

sqlsrv_query — Prepares and executes a query.

Opis

mixed sqlsrv_query ( resource $conn , string $sql [, array $params [, array $options ]] )

Prepares and executes a query.

Parametry

conn

A connection resource returned by sqlsrv_connect().

sql

The string that defines the query to be prepared and executed.

params

An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  • A literal value
  • A PHP variable
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
The following table describes the elements in the array structure above:

Array structure
Element | Description
$value | A literal value, a PHP variable, or a PHP by-reference variable.
$direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
$phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
$sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.
options

An array specifing query property options. The supported keys are described in the following table:

Query Options
Key | Values | Description
QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
SendStreamParamsAtExec | TRUE or FALSE (the default is TRUE) | Configures the driver to send all stream data at execution (TRUE), or to send stream data in chunks (FALSE). By default, the value is set to TRUE. For more information, see sqlsrv_send_stream_data().
Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

Zwracane wartości

Returns a statement resource on success and FALSE if an error occurred.

Przykłady

Przykład #1 sqlsrv_query() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");

$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}
?>

Notatki

For statements that you plan to execute only once, use sqlsrv_query(). If you intend to re-execute a statement with different parameter values, use the combination of sqlsrv_prepare() and sqlsrv_execute().

Zobacz też:

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare

sqlsrv_prepare
sqlsrv_rollback
SQLSRV Funkcje


Rolls back a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_query
sqlsrv_rows_affected
SQLSRV Funkcje
PHP Manual

sqlsrv_rollback

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

sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction()

Opis

bool sqlsrv_rollback ( resource $conn )

Rolls back a transaction that was begun with sqlsrv_begin_transaction() and returns the connection to auto-commit mode.

Parametry

conn

The connection resource returned by a call to sqlsrv_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 sqlsrv_rollback() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
         VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
         SET Quantity = (Quantity - ?)
         WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     sqlsrv_commit( $conn );
     echo "Transaction committed.<br />";
} else {
     sqlsrv_rollback( $conn );
     echo "Transaction rolled back.<br />";
}
?>

Zobacz też:

  • sqlsrv_begin_transaction() - Begins a database transaction
  • sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_query
sqlsrv_rows_affected
SQLSRV Funkcje


Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

sqlsrv_rollback
sqlsrv_send_stream_data
SQLSRV Funkcje
PHP Manual

sqlsrv_rows_affected

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

sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

Opis

int sqlsrv_rows_affected ( resource $stmt )

Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed. For information about the number of rows returned by a SELECT query, see sqlsrv_num_rows().

Parametry

stmt

The executed statement resource for which the number of affected rows is returned.

Zwracane wartości

Returns the number of rows affected by the last INSERT, UPDATE, or DELETE query. If no rows were affected, 0 is returned. If the number of affected rows cannot be determined, -1 is returned. If an error occured, FALSE is returned.

Przykłady

Przykład #1 sqlsrv_rows_affected() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1 SET data = ? WHERE id = ?";

$params = array("updated data", 1);

$stmt = sqlsrv_query( $conn, $sql, $params);

$rows_affected = sqlsrv_rows_affected( $stmt);
if( $rows_affected === false) {
     die( print_r( sqlsrv_errors(), true));
} elseif( $rows_affected == -1) {
      echo "No information available.<br />";
} else {
      echo $rows_affected." rows were updated.<br />";
}
?>

Zobacz też:

  • sqlsrv_num_rows() - Retrieves the number of rows in a result set

sqlsrv_rollback
sqlsrv_send_stream_data
SQLSRV Funkcje


Sends data from parameter streams to the server

sqlsrv_rows_affected
sqlsrv_server_info
SQLSRV Funkcje
PHP Manual

sqlsrv_send_stream_data

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

sqlsrv_send_stream_data — Sends data from parameter streams to the server

Opis

bool sqlsrv_send_stream_data ( resource $stmt )

Send data from parameter streams to the server. Up to 8 KB of data is sent with each call.

Parametry

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

Zwracane wartości

Returns TRUE if there is more data to send and FALSE if there is not.

Przykłady

Przykład #1 sqlsrv_send_stream_data() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1 SET data = ( ?) WHERE id = 100";

// Open parameter data as a stream and put it in the $params array.
$data = fopen( "data://text/plain,[ Lengthy content here. ]", "r");
$params = array( &$data);

// Prepare the statement. Use the $options array to turn off the
// default behavior, which is to send all stream data at the time of query
// execution.
$options = array("SendStreamParamsAtExec"=>0);
$stmt = sqlsrv_prepare( $conn, $sql, $params, $options);

sqlsrv_execute( $stmt);

// Send up to 8K of parameter data to the server
// with each call to sqlsrv_send_stream_data.
$i = 1;
while( sqlsrv_send_stream_data( $stmt)) {
      $i++;
}
echo "$i calls were made.";
?>

Zobacz też:

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_query() - Prepares and executes a query.

sqlsrv_rows_affected
sqlsrv_server_info
SQLSRV Funkcje


Returns information about the server

sqlsrv_send_stream_data
Sybase
SQLSRV Funkcje
PHP Manual

sqlsrv_server_info

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

sqlsrv_server_info — Returns information about the server

Opis

array sqlsrv_server_info ( resource $conn )

Returns information about the server.

Parametry

conn

The connection resource that connects the client and the server.

Zwracane wartości

Returns an array as described in the following table:

Returned Array
CurrentDatabase | The connected-to database.
SQLServerVersion | The SQL Server version.
SQLServerName | The name of the server.

Przykłady

Przykład #1 sqlsrv_server_info() example

<?php
$serverName = "serverName\sqlexpress";
$conn = sqlsrv_connect( $serverName);
if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
}

$server_info = sqlsrv_server_info( $conn);
if( $server_info )
{
    foreach( $server_info as $key => $value) {
       echo $key.": ".$value."<br />";
    }
} else {
      die( print_r( sqlsrv_errors(), true));
}
?>

Zobacz też:

  • sqlsrv_client_info() - Returns information about the client and specified connection

sqlsrv_send_stream_data
Sybase
SQLSRV Funkcje


Sybase

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Sybase Funkcje
    • sybase_affected_rows — Gets number of affected rows in last query
    • sybase_close — Closes a Sybase connection
    • sybase_connect — Opens a Sybase server connection
    • sybase_data_seek — Moves internal row pointer
    • sybase_deadlock_retry_count — Sets the deadlock retry count
    • sybase_fetch_array — Fetch row as array
    • sybase_fetch_assoc — Fetch a result row as an associative array
    • sybase_fetch_field — Get field information from a result
    • sybase_fetch_object — Fetch a row as an object
    • sybase_fetch_row — Get a result row as an enumerated array
    • sybase_field_seek — Sets field offset
    • sybase_free_result — Frees result memory
    • sybase_get_last_message — Returns the last message from the server
    • sybase_min_client_severity — Sets minimum client severity
    • sybase_min_error_severity — Sets minimum error severity
    • sybase_min_message_severity — Sets minimum message severity
    • sybase_min_server_severity — Sets minimum server severity
    • sybase_num_fields — Gets the number of fields in a result set
    • sybase_num_rows — Get number of rows in a result set
    • sybase_pconnect — Open persistent Sybase connection
    • sybase_query — Sends a Sybase query
    • sybase_result — Get result data
    • sybase_select_db — Selects a Sybase database
    • sybase_set_message_handler — Sets the handler called when a server message is raised
    • sybase_unbuffered_query — Send a Sybase query and do not block
sqlsrv_server_info
Wstęp
Rozszerzenia producentów baz danych


Wstęp

Sybase
Instalacja/Konfiguracja
Sybase


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Sybase


Instalacja

To enable Sybase-DB support configure PHP --with-sybase[=DIR] . DIR is the Sybase home directory, defaults to /home/sybase. To enable Sybase-CT support configure PHP --with-sybase-ct[=DIR] . DIR is the Sybase home directory, defaults to /home/sybase.

Informacja:

As of PHP 5.3.0, the Sybase extension has been superseded by the sybase_ct extension and is no longer maintained. To continue using sybase you must use the sybase_ct extension.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Sybase configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.interface_file | "/usr/sybase/interfaces" | PHP_INI_SYSTEM |
sybase.min_error_severity | "10" | PHP_INI_ALL |
sybase.min_message_severity | "10" | PHP_INI_ALL |
sybase.compatability_mode | "0" | PHP_INI_ALL |
magic_quotes_sybase | "0" | PHP_INI_ALL | Deprecated in PHP 5.3.0. Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

sybase.allow_persistent boolean

Whether to allow persistent Sybase connections.

sybase.max_persistent integer

The maximum number of persistent Sybase connections per process. -1 means no limit.

sybase.max_links integer

The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.

sybase.min_error_severity integer

Minimum error severity to display.

sybase.min_message_severity integer

Minimum message severity to display.

magic_quotes_sybase boolean

If magic_quotes_sybase is on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime are enabled. This setting is also respected by addslashes() and stripslashes().

Informacja:

Note that when magic_quotes_sybase is ON it completely overrides magic_quotes_gpc . In this case even when magic_quotes_gpc is enabled neither double quotes, backslashes or NUL's will be escaped.

Ostrzeżenie

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

Sybase-CT configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
sybct.allow_persistent | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.max_links | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.min_server_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.min_client_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.hostname | NULL | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

sybct.allow_persistent boolean

Whether to allow persistent Sybase-CT connections. The default is on.

sybct.max_persistent integer

The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.

sybct.max_links integer

The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.

sybct.min_server_severity integer

Server messages with severity greater than or equal to sybct.min_server_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_server_severity(). The default is 10 which reports errors of information severity or greater.

sybct.min_client_severity integer

Client library messages with severity greater than or equal to sybct.min_client_severity will be reported as warnings. This value can also be set from a script by calling sybase_min_client_severity(). The default is 10 which effectively disables reporting.

sybct.login_timeout integer

The maximum time in seconds to wait for a connection attempt to succeed before returning failure. Note that if max_execution_time has been exceeded when a connection attempt times out, your script will be terminated before it can take action on failure. The default is one minute.

sybct.timeout integer

The maximum time in seconds to wait for a select_db or query operation to succeed before returning failure. Note that if max_execution_time has been exceeded when an operation times out, your script will be terminated before it can take action on failure. The default is no limit.

sybct.hostname string

The name of the host you claim to be connecting from, for display by sp_who. The default is none.

sybct.deadlock_retry_count int

Allows you to define how often deadlocks are to be retried. The default is 0, value -1 means "forever".

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Sybase Funkcje
Sybase


Sybase Funkcje

Spis treści

  • sybase_affected_rows — Gets number of affected rows in last query
  • sybase_close — Closes a Sybase connection
  • sybase_connect — Opens a Sybase server connection
  • sybase_data_seek — Moves internal row pointer
  • sybase_deadlock_retry_count — Sets the deadlock retry count
  • sybase_fetch_array — Fetch row as array
  • sybase_fetch_assoc — Fetch a result row as an associative array
  • sybase_fetch_field — Get field information from a result
  • sybase_fetch_object — Fetch a row as an object
  • sybase_fetch_row — Get a result row as an enumerated array
  • sybase_field_seek — Sets field offset
  • sybase_free_result — Frees result memory
  • sybase_get_last_message — Returns the last message from the server
  • sybase_min_client_severity — Sets minimum client severity
  • sybase_min_error_severity — Sets minimum error severity
  • sybase_min_message_severity — Sets minimum message severity
  • sybase_min_server_severity — Sets minimum server severity
  • sybase_num_fields — Gets the number of fields in a result set
  • sybase_num_rows — Get number of rows in a result set
  • sybase_pconnect — Open persistent Sybase connection
  • sybase_query — Sends a Sybase query
  • sybase_result — Get result data
  • sybase_select_db — Selects a Sybase database
  • sybase_set_message_handler — Sets the handler called when a server message is raised
  • sybase_unbuffered_query — Send a Sybase query and do not block
Stałe predefiniowane
sybase_affected_rows
Sybase


Gets number of affected rows in last query

Sybase Funkcje
sybase_close
Sybase Funkcje
PHP Manual

sybase_affected_rows

(PHP 4, PHP 5)

sybase_affected_rows — Gets number of affected rows in last query

Opis

int sybase_affected_rows ([ resource $link_identifier ] )

sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier.

This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().

Parametry

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Zwracane wartości

Returns the number of affected rows, as an integer.

Przykłady

Przykład #1 Delete-Query

<?php
/* connect to database */
sybase_connect('SYBASE', '', '') or
die("Could not connect");
sybase_select_db("db");

sybase_query("DELETE FROM sometable WHERE id < 10");
printf("Records deleted: %d\n", sybase_affected_rows());
?>

Powyższy przykład wyświetli:

Records deleted: 10

Zobacz też:

  • sybase_num_rows() - Get number of rows in a result set

Sybase Funkcje
sybase_close
Sybase Funkcje


Closes a Sybase connection

sybase_affected_rows
sybase_connect
Sybase Funkcje
PHP Manual

sybase_close

(PHP 4, PHP 5)

sybase_close — Closes a Sybase connection

Opis

bool sybase_close ([ resource $link_identifier ] )

sybase_close() closes the link to a Sybase database that's associated with the specified link link_identifier.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

sybase_close() will not close persistent links generated by sybase_pconnect().

Parametry

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection

sybase_affected_rows
sybase_connect
Sybase Funkcje


Opens a Sybase server connection

sybase_close
sybase_data_seek
Sybase Funkcje
PHP Manual

sybase_connect

(PHP 4, PHP 5)

sybase_connect — Opens a Sybase server connection

Opis

resource sybase_connect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname [, bool $new = false ]]]]]] )

sybase_connect() establishes a connection to a Sybase server.

In case a second call is made to sybase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling sybase_close().

Parametry

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username.

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

new

Whether to open a new connection or use the existing one.

Zwracane wartości

Returns a positive Sybase link identifier on success, or FALSE on failure.

Rejestr zmian

Wersja | Opis
5.3.0 | The new parameter was added.
4.2.0 | The appname parameter was added.
4.0.2 | The charset parameter was added.

Przykłady

Przykład #1 sybase_connect() example

<?php
$link = sybase_connect('SYBASE', '', '')
        or die("Could not connect !");
echo "Connected successfully";
sybase_close($link);
?>

Zobacz też:

  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_close() - Closes a Sybase connection

sybase_close
sybase_data_seek
Sybase Funkcje


Moves internal row pointer

sybase_connect
sybase_deadlock_retry_count
Sybase Funkcje
PHP Manual

sybase_data_seek

(PHP 4, PHP 5)

sybase_data_seek — Moves internal row pointer

Opis

bool sybase_data_seek ( resource $result_identifier , int $row_number )

sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specified row number. The next call to sybase_fetch_row() would return that row.

Parametry

result_identifier

row_number

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • sybase_fetch_row() - Get a result row as an enumerated array

sybase_connect
sybase_deadlock_retry_count
Sybase Funkcje


Sets the deadlock retry count

sybase_data_seek
sybase_fetch_array
Sybase Funkcje
PHP Manual

sybase_deadlock_retry_count

(PHP 4 >= 4.3.0, PHP 5)

sybase_deadlock_retry_count — Sets the deadlock retry count

Opis

void sybase_deadlock_retry_count ( int $retry_count )

Using sybase_deadlock_retry_count(), the number of retries can be defined in cases of deadlocks. By default, every deadlock is retried an infinite number of times or until the process is killed by Sybase, the executing script is killed (for instance, by set_time_limit()) or the query succeeds.

Parametry

retry_count

Values for retry_count
-1 | Retry forever (default)
0 | Do not retry
n | Retry n times

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli za interfejs do Sybase służy biblioteka CT, a nie DB.

sybase_data_seek
sybase_fetch_array
Sybase Funkcje


Fetch row as array

sybase_deadlock_retry_count
sybase_fetch_assoc
Sybase Funkcje
PHP Manual

sybase_fetch_array

(PHP 4, PHP 5)

sybase_fetch_array — Fetch row as array

Opis

array sybase_fetch_array ( resource $result )

sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Parametry

result

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Informacja:

When selecting fields with identical names (for instance, in a join), the associative indices will have a sequential number prepended. See the example for details.

Przykłady

Przykład #1 Identical fieldnames

<?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_query('SELECT * FROM p, a WHERE p.person_id= a.person_id');
var_dump(sybase_fetch_array($q));
sybase_close($dbh);
?>

The above example would produce the following output (assuming the two tables only have each one column called "person_id"):

array(4) {
  [0]=>
  int(1)
  ["person_id"]=>
  int(1)
  [1]=>
  int(1)
  ["person_id1"]=>
  int(1)
}

Zobacz też:

  • sybase_fetch_row() - Get a result row as an enumerated array
  • sybase_fetch_assoc() - Fetch a result row as an associative array
  • sybase_fetch_object() - Fetch a row as an object

sybase_deadlock_retry_count
sybase_fetch_assoc
Sybase Funkcje


Fetch a result row as an associative array

sybase_fetch_array
sybase_fetch_field
Sybase Funkcje
PHP Manual

sybase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

sybase_fetch_assoc — Fetch a result row as an associative array

Opis

array sybase_fetch_assoc ( resource $result )

sybase_fetch_assoc() is a version of sybase_fetch_row() that uses column names instead of integers for indices in the result array. Columns from different tables with the same names are returned as name, name1, name2, ..., nameN.

An important thing to note is that using sybase_fetch_assoc() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Parametry

result

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli za interfejs do Sybase służy biblioteka CT, a nie DB.

Zobacz też:

  • sybase_fetch_row() - Get a result row as an enumerated array
  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_object() - Fetch a row as an object

sybase_fetch_array
sybase_fetch_field
Sybase Funkcje


Get field information from a result

sybase_fetch_assoc
sybase_fetch_object
Sybase Funkcje
PHP Manual

sybase_fetch_field

(PHP 4, PHP 5)

sybase_fetch_field — Get field information from a result

Opis

object sybase_fetch_field ( resource $result [, int $field_offset = -1 ] )

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parametry

result

field_offset

If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

Zwracane wartości

Returns an object containing field information.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
  • column_source - the table from which the column was taken
  • max_length - maximum length of the column
  • numeric - 1 if the column is numeric
  • type - datatype of the column

Zobacz też:

  • sybase_field_seek() - Sets field offset

sybase_fetch_assoc
sybase_fetch_object
Sybase Funkcje


Fetch a row as an object

sybase_fetch_field
sybase_fetch_row
Sybase Funkcje
PHP Manual

sybase_fetch_object

(PHP 4, PHP 5)

sybase_fetch_object — Fetch a row as an object

Opis

object sybase_fetch_object ( resource $result [, mixed $object ] )

sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

Parametry

result

object

Use the second object to specify the type of object you want to return. If this parameter is omitted, the object will be of type stdClass.

Zwracane wartości

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Rejestr zmian

Wersja Opis
4.3.0

This function will no longer return numeric object members. Old behaviour:

object(stdclass)(3) {
  [0]=>
  string(3) "foo"
  ["foo"]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "bar"
}
New behaviour:
object(stdclass)(3) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}

Przykłady

Przykład #1 sybase_fetch_object() return as Foo

<?php
    class Foo {
        var $foo, $bar, $baz;
    }

    // {...]
    $qrh= sybase_query('SELECT foo, bar, baz FROM example');
    $foo= sybase_fetch_object($qrh, 'Foo');
    $bar= sybase_fetch_object($qrh, new Foo());
    // {...]
?>

Zobacz też:

  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_row() - Get a result row as an enumerated array

sybase_fetch_field
sybase_fetch_row
Sybase Funkcje


Get a result row as an enumerated array

sybase_fetch_object
sybase_field_seek
Sybase Funkcje
PHP Manual

sybase_fetch_row

(PHP 4, PHP 5)

sybase_fetch_row — Get a result row as an enumerated array

Opis

array sybase_fetch_row ( resource $result )

sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parametry

result

Zwracane wartości

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 0.

Data types
PHP | Sybase
string | VARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME
int | NUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT
float | NUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY
NULL | NULL

Zobacz też:

  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_assoc() - Fetch a result row as an associative array
  • sybase_fetch_object() - Fetch a row as an object
  • sybase_data_seek() - Moves internal row pointer
  • sybase_result() - Get result data

sybase_fetch_object
sybase_field_seek
Sybase Funkcje


Sets field offset

sybase_fetch_row
sybase_free_result
Sybase Funkcje
PHP Manual

sybase_field_seek

(PHP 4, PHP 5)

sybase_field_seek — Sets field offset

Opis

bool sybase_field_seek ( resource $result , int $field_offset )

Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.

Parametry

result

field_offset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • sybase_fetch_field() - Get field information from a result

sybase_fetch_row
sybase_free_result
Sybase Funkcje


Frees result memory

sybase_field_seek
sybase_get_last_message
Sybase Funkcje
PHP Manual

sybase_free_result

(PHP 4, PHP 5)

sybase_free_result — Frees result memory

Opis

bool sybase_free_result ( resource $result )

sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.

Parametry

result

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

sybase_field_seek
sybase_get_last_message
Sybase Funkcje


Returns the last message from the server

sybase_free_result
sybase_min_client_severity
Sybase Funkcje
PHP Manual

sybase_get_last_message

(PHP 4, PHP 5)

sybase_get_last_message — Returns the last message from the server

Opis

string sybase_get_last_message ( void )

sybase_get_last_message() returns the last message reported by the server.

Zwracane wartości

Returns the message as a string.

Zobacz też:

  • sybase_min_message_severity() - Sets minimum message severity

sybase_free_result
sybase_min_client_severity
Sybase Funkcje


Sets minimum client severity

sybase_get_last_message
sybase_min_error_severity
Sybase Funkcje
PHP Manual

sybase_min_client_severity

(PHP 4, PHP 5)

sybase_min_client_severity — Sets minimum client severity

Opis

void sybase_min_client_severity ( int $severity )

sybase_min_client_severity() sets the minimum client severity level.

Parametry

severity

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli za interfejs do Sybase służy biblioteka CT, a nie DB.

Zobacz też:

  • sybase_min_server_severity() - Sets minimum server severity

sybase_get_last_message
sybase_min_error_severity
Sybase Funkcje


Sets minimum error severity

sybase_min_client_severity
sybase_min_message_severity
Sybase Funkcje
PHP Manual

sybase_min_error_severity

(PHP 4, PHP 5)

sybase_min_error_severity — Sets minimum error severity

Opis

void sybase_min_error_severity ( int $severity )

sybase_min_error_severity() sets the minimum error severity level.

Parametry

severity

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli za interfejs do Sybase służy biblioteka CT, a nie DB.

Zobacz też:

  • sybase_min_message_severity() - Sets minimum message severity

sybase_min_client_severity
sybase_min_message_severity
Sybase Funkcje


Sets minimum message severity

sybase_min_error_severity
sybase_min_server_severity
Sybase Funkcje
PHP Manual

sybase_min_message_severity

(PHP 4, PHP 5)

sybase_min_message_severity — Sets minimum message severity

Opis

void sybase_min_message_severity ( int $severity )

sybase_min_message_severity() sets the minimum message severity level.

Parametry

severity

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli za interfejs do Sybase służy biblioteka DB, a nie CT.

Zobacz też:

  • sybase_min_error_severity() - Sets minimum error severity

sybase_min_error_severity
sybase_min_server_severity
Sybase Funkcje


Sets minimum server severity

sybase_min_message_severity
sybase_num_fields
Sybase Funkcje
PHP Manual

sybase_min_server_severity

(PHP 4, PHP 5)

sybase_min_server_severity — Sets minimum server severity

Opis

void sybase_min_server_severity ( int $severity )

sybase_min_server_severity() sets the minimum server severity level.

Parametry

severity

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli za interfejs do Sybase służy biblioteka CT, a nie DB.

Zobacz też:

  • sybase_min_client_severity() - Sets minimum client severity

sybase_min_message_severity
sybase_num_fields
Sybase Funkcje


Gets the number of fields in a result set

sybase_min_server_severity
sybase_num_rows
Sybase Funkcje
PHP Manual

sybase_num_fields

(PHP 4, PHP 5)

sybase_num_fields — Gets the number of fields in a result set

Opis

int sybase_num_fields ( resource $result )

sybase_num_fields() returns the number of fields in a result set.

Parametry

result

Zwracane wartości

Returns the number of fields as an integer.

Zobacz też:

  • sybase_query() - Sends a Sybase query
  • sybase_fetch_field() - Get field information from a result
  • sybase_num_rows() - Get number of rows in a result set

sybase_min_server_severity
sybase_num_rows
Sybase Funkcje


Get number of rows in a result set

sybase_num_fields
sybase_pconnect
Sybase Funkcje
PHP Manual

sybase_num_rows

(PHP 4, PHP 5)

sybase_num_rows — Get number of rows in a result set

Opis

int sybase_num_rows ( resource $result )

sybase_num_rows() returns the number of rows in a result set.

Parametry

result

Zwracane wartości

Returns the number of rows as an integer.

Zobacz też:

  • sybase_num_fields() - Gets the number of fields in a result set
  • sybase_query() - Sends a Sybase query
  • sybase_fetch_row() - Get a result row as an enumerated array

sybase_num_fields
sybase_pconnect
Sybase Funkcje


Open persistent Sybase connection

sybase_num_rows
sybase_query
Sybase Funkcje
PHP Manual

sybase_pconnect

(PHP 4, PHP 5)

sybase_pconnect — Open persistent Sybase connection

Opis

resource sybase_pconnect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname ]]]]] )

sybase_pconnect() acts very much like sybase_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()).

This type of links is therefore called 'persistent'.

Parametry

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username.

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

Zwracane wartości

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

Rejestr zmian

Wersja | Opis
4.2.0 | The appname parameter was added.
4.0.2 | The charset parameter was added.

Zobacz też:

  • sybase_connect() - Opens a Sybase server connection

sybase_num_rows
sybase_query
Sybase Funkcje


Sends a Sybase query

sybase_pconnect
sybase_result
Sybase Funkcje
PHP Manual

sybase_query

(PHP 4, PHP 5)

sybase_query — Sends a Sybase query

Opis

mixed sybase_query ( string $query [, resource $link_identifier ] )

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parametry

query

link_identifier

If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Zwracane wartości

Returns a positive Sybase result identifier on success, FALSE on error, or TRUE if the query was successful but didn't return any columns.

Zobacz też:

  • sybase_select_db() - Selects a Sybase database
  • sybase_connect() - Opens a Sybase server connection

sybase_pconnect
sybase_result
Sybase Funkcje


Get result data

sybase_query
sybase_select_db
Sybase Funkcje
PHP Manual

sybase_result

(PHP 4, PHP 5)

sybase_result — Get result data

Opis

string sybase_result ( resource $result , int $row , mixed $field )

Returns the contents of the cell at the row and offset in the specified Sybase result set.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives:
sybase_fetch_row(),
sybase_fetch_array() and
sybase_fetch_object().

Parametry

result

row

field

The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Zwracane wartości

sybase_result() returns the contents of one cell from a Sybase result set.

sybase_query
sybase_select_db
Sybase Funkcje


Selects a Sybase database

sybase_result
sybase_set_message_handler
Sybase Funkcje
PHP Manual

sybase_select_db

(PHP 4, PHP 5)

sybase_select_db — Selects a Sybase database

Opis

bool sybase_select_db ( string $database_name [, resource $link_identifier ] )

sybase_select_db() sets the current active database on the server that's associated with the specified link identifier.

Every subsequent call to sybase_query() will be made on the active database.

Parametry

database_name

link_identifier

If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_query() - Sends a Sybase query

sybase_result
sybase_set_message_handler
Sybase Funkcje


Sets the handler called when a server message is raised

sybase_select_db
sybase_unbuffered_query
Sybase Funkcje
PHP Manual

sybase_set_message_handler

(PHP 4 >= 4.3.0, PHP 5)

sybase_set_message_handler — Sets the handler called when a server message is raised

Opis

bool sybase_set_message_handler ( callback $handler [, resource $link_identifier ] )

sybase_set_message_handler() sets a user function to handle messages generated by the server. You may specify the name of a global function, or use an array to specify an object reference and a method name.

Parametry

handler

The handler expects five arguments in the following order: message number, severity, state, line number and description. The first four are integers. The last is a string. If the function returns FALSE, PHP generates an ordinary error message.

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
4.3.5 | The link_identifier parameter was added.

Przykłady

Przykład #1 sybase_set_message_handler() callback function

<?php
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?>

Przykład #2 sybase_set_message_handler() callback to a class

<?php
    class Sybase {
        function handler($msgnumber, $severity, $state, $line, $text)
        {
            var_dump($msgnumber, $severity, $state, $line, $text);
        }
    }

    $sybase= new Sybase();
    sybase_set_message_handler(array($sybase, 'handler'));
?>

Przykład #3 sybase_set_message_handler() unhandled messages

<?php
    // Return FALSE from this function to indicate you can't handle
    // this. The error is printed out as a warning, the way you're used
    // to it if there is no handler installed.
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        if (257 == $msgnumber) {
            return false;
        }
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli za interfejs do Sybase służy biblioteka CT, a nie DB.

sybase_select_db
sybase_unbuffered_query
Sybase Funkcje


Send a Sybase query and do not block

sybase_set_message_handler
tokyo_tyrant
Sybase Funkcje
PHP Manual

sybase_unbuffered_query

(PHP 4 >= 4.3.0, PHP 5)

sybase_unbuffered_query — Send a Sybase query and do not block

Opis

resource sybase_unbuffered_query ( string $query , resource $link_identifier [, bool $store_result ] )

sybase_unbuffered_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Unlike sybase_query(), sybase_unbuffered_query() reads only the first row of the result set. sybase_fetch_array() and similar function read more rows as needed. sybase_data_seek() reads up to the target row. The behavior may produce better performance for large result sets.

sybase_num_rows() will only return the correct number of rows if all result sets have been read. To Sybase, the number of rows is not known and is therefore computed by the client implementation.

Informacja:

If you don't read all of the resultsets prior to executing the next query, PHP will raise a warning and cancel all of the pending results. To get rid of this, use sybase_free_result() which will cancel pending results of an unbuffered query.

Parametry

query

link_identifier

store_result

The optional store_result can be FALSE to indicate the resultsets shouldn't be fetched into memory, thus minimizing memory usage which is particularly interesting with very large resultsets.

Zwracane wartości

Returns a positive Sybase result identifier on success, or FALSE on error.

Przykłady

Przykład #1 sybase_unbuffered_query() example

<?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_unbuffered_query('select firstname, lastname from huge_table', $dbh, false);
sybase_data_seek($q, 10000);
$i = 0;

while ($row = sybase_fetch_row($q)) {
    echo $row[0], ' ', $row[1], '<br />';
    if ($i++ > 40000) {
        break;
    }
}

sybase_free_result($q);
sybase_close($dbh);

?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli za interfejs do Sybase służy biblioteka CT, a nie DB.

Zobacz też:

  • sybase_query() - Sends a Sybase query

sybase_set_message_handler
tokyo_tyrant
Sybase Funkcje


tokyo_tyrant

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • TokyoTyrant — The TokyoTyrant class
    • TokyoTyrant::add — Adds to a numeric key
    • TokyoTyrant::connect — Connect to a database
    • TokyoTyrant::connectUri — Connects to a database
    • TokyoTyrant::__construct — Construct a new TokyoTyrant object
    • TokyoTyrant::copy — Copies the database
    • TokyoTyrant::ext — Execute a remote script
    • TokyoTyrant::fwmKeys — Returns the forward matching keys
    • TokyoTyrant::get — The get purpose
    • TokyoTyrant::getIterator — Get an iterator
    • TokyoTyrant::num — Number of records in the database
    • TokyoTyrant::out — Removes records
    • TokyoTyrant::put — Puts values
    • TokyoTyrant::putCat — Concatenates to a record
    • TokyoTyrant::putKeep — Puts a record
    • TokyoTyrant::putNr — Puts value
    • TokyoTyrant::putShl — Concatenates to a record
    • TokyoTyrant::restore — Restore the database
    • TokyoTyrant::setMaster — Set the replication master
    • TokyoTyrant::size — Returns the size of the value
    • TokyoTyrant::stat — Get statistics
    • TokyoTyrant::sync — Synchronize the database
    • TokyoTyrant::tune — Tunes connection values
    • TokyoTyrant::vanish — Empties the database
  • TokyoTyrantTable — The TokyoTyrantTable class
    • TokyoTyrantTable::add — Adds a record
    • TokyoTyrantTable::genUid — Generate unique id
    • TokyoTyrantTable::get — Get a row
    • TokyoTyrantTable::getIterator — Get an iterator
    • TokyoTyrantTable::getQuery — Get a query object
    • TokyoTyrantTable::out — Remove records
    • TokyoTyrantTable::put — Store a row
    • TokyoTyrantTable::putCat — Concatenates to a row
    • TokyoTyrantTable::putKeep — Put a new record
    • TokyoTyrantTable::putNr — Puts value
    • TokyoTyrantTable::putShl — Concatenates to a record
    • TokyoTyrantTable::setIndex — Sets index
  • TokyoTyrantQuery — The TokyoTyrantQuery class
    • TokyoTyrantQuery::addCond — Adds a condition to the query
    • TokyoTyrantQuery::__construct — Construct a new query
    • TokyoTyrantQuery::count — Counts records
    • TokyoTyrantQuery::current — Returns the current element
    • TokyoTyrantQuery::hint — Get the hint string of the query
    • TokyoTyrantQuery::key — Returns the current key
    • TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
    • TokyoTyrantQuery::next — Moves the iterator to next entry
    • TokyoTyrantQuery::out — Removes records based on query
    • TokyoTyrantQuery::rewind — Rewinds the iterator
    • TokyoTyrantQuery::search — Searches records
    • TokyoTyrantQuery::setLimit — Limit results
    • TokyoTyrantQuery::setOrder — Orders results
    • TokyoTyrantQuery::valid — Checks the validity of current item
  • TokyoTyrantIterator — The TokyoTyrantIterator class
    • TokyoTyrantIterator::__construct — Construct an iterator
    • TokyoTyrantIterator::current — Get the current value
    • TokyoTyrantIterator::key — Returns the current key
    • TokyoTyrantIterator::next — Move to next key
    • TokyoTyrantIterator::rewind — Rewinds the iterator
    • TokyoTyrantIterator::valid — Rewinds the iterator
  • TokyoTyrantException — The TokyoTyrantException class
sybase_unbuffered_query
Wstęp
Rozszerzenia producentów baz danych


Wstęp

tokyo_tyrant extension provides a wrapper for Tokyo Tyrant client libraries. The extension contains the normal key-value API and the table API.

"Tokyo Tyrant is a package of network interface to the DBM called Tokyo Cabinet. Though the DBM has high performance, you might bother in case that multiple processes share the same database, or remote processes access the database. Thus, Tokyo Tyrant is provided for concurrent and remote connections to Tokyo Cabinet. It is composed of the server process managing a database and its access library for client applications." --Tokyo Tyrant documentation

Tokyo Tyrant is written by Mikio Hirabayashi and is licensed under GNU Lesser General Public License.

tokyo_tyrant
Instalacja/Konfiguracja
tokyo_tyrant


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
tokyo_tyrant


Wymagania

Before using this extension Tokyo Cabinet and Tokyo Tyrant must be installed.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/tokyo_tyrant

Configure options

  • --with-tokyo-tyrant[=DIR] DIR is the prefix to the Tokyo Tyrant installation
  • --with-tokyo-cabinet-dir[=DIR] DIR is the prefix to the Tokyo Cabinet installation
  • --disable-tokyo-tyrant-session Disable Tokyo Tyrant session handler support

Enabling the extension

The extension can be enabled by adding extension=tokyo_tyrant.so to the INI-configuration

Running Tokyo Tyrant for the session handler

ttserver -port 2000 -ext /path/to/expire.lua -extpc expire 30.0 '/tmp/sessions.tct#idx=ts:dec'

Informacja: expire.lua is included in the tokyo_tyrant extension source distribution

Configuring session handler

  • tokyo_tyrant.session_salt="randomlongstring"
  • session.save_handler=tokyo_tyrant
  • session.save_path="tcp://hostname1:2000,tcp://hostname2:2000"

Informacja: It is important to make sure that tokyo_tyrant.session_salt matches on all servers.

How it works?

The session handler creates a session id like the following: 8b0e27a823fa4a6cf7246945b82c1d51-a5eadbbed1f2075952900628456bfd6830541629-0-5460

The parts from left to right:

  • Session id - Generated session id
  • Checksum - Checksum of session salt, session id, node id and primary key
  • Node id - The id of the node where the session maps to
  • Primary key - The primary key of the row where the session is stored

The checksum contains SHA1 sum of the node id, primary key, session id and the salt which is known only on the server side. This allows quick mapping of session id to node and primary key since there is no need to do an additional search. During session id regeneration only the parts 1 and 2 change but the mapping to the node and primary key stays constant.

In case some of the nodes fail tokyo_tyrant.allow_failover, tokyo_tyrant.fail_threshold and tokyo_tyrant.health_check_divisor INI-settings control the behavior during failover. If failover is allowed the session handler will map the session to a healthy node and creates a new empty session.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

tokyo_tyrant Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
tokyo_tyrant.default_timeout | 2.0 | PHP_INI_ALL |
tokyo_tyrant.session_salt | NULL | PHP_INI_ALL |
tokyo_tyrant.key_prefix | NULL | PHP_INI_ALL |
tokyo_tyrant.allow_failover | 1 | PHP_INI_ALL |
tokyo_tyrant.fail_threshold | 5 | PHP_INI_ALL |
tokyo_tyrant.health_check_divisor | 1000 | PHP_INI_ALL |
tokyo_tyrant.php_expiration | 0 | PHP_INI_ALL |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

tokyo_tyrant.default_timeout integer

Default timeout when connecting to databases

tokyo_tyrant.session_salt string

The secret that is used to salt session id

tokyo_tyrant.key_prefix string

Prefix all keys with this string. The prefix is transparent to the developer but helps making sure that keys won't collide if multiple applications are using the same database.

tokyo_tyrant.allow_failover integer

Whether to allow session failover in case a server dies.

tokyo_tyrant.fail_threshold integer

How many read/write or connection failures is allowed before server is marked as failed.

tokyo_tyrant.health_check_divisor integer

Defines the divisor for the health check probability. If there are failed servers and the probability matches, the servers are health checked and in case the server seems healthy, it will be added back to the pool.

tokyo_tyrant.php_expiration integer

Whether to use built in session expiration mechanism or delegate the expiration to a lua-script on the server-side.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

TokyoTyrant constants

Typy zasobów
Przykłady
tokyo_tyrant


Przykłady

Basic usage

Przykład #1 Putting and getting a key-value pair

<?php
$tt = new TokyoTyrant("localhost");
$tt->put("key", "value");
echo $tt->get("key");
?>

Powyższy przykład wyświetli:

value
Stałe predefiniowane
TokyoTyrant
tokyo_tyrant


The TokyoTyrant class

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

Wstęp

The main Tokyo Tyrant class

Krótki opis klasy

TokyoTyrant {
/* Stałe */
const integer RDBDEF_PORT = 1978 ;
const integer RDBQC_STREQ = 0 ;
const integer RDBQC_STRINC = 1 ;
const integer RDBQC_STRBW = 2 ;
const integer RDBQC_STREW = 3 ;
const integer RDBQC_STRAND = 4 ;
const integer RDBQC_STROR = 5 ;
const integer RDBQC_STROREQ = 6 ;
const integer RDBQC_STRRX = 7 ;
const integer RDBQC_NUMEQ = 8 ;
const integer RDBQC_NUMGT = 9 ;
const integer RDBQC_NUMGE = 10 ;
const integer RDBQC_NUMLT = 11 ;
const integer RDBQC_NUMLE = 12 ;
const integer RDBQC_NUMBT = 13 ;
const integer RDBQC_NUMOREQ = 14 ;
const integer RDBQC_NEGATE = 16777216 ;
const integer RDBQC_NOIDX = 33554432 ;
const integer RDBQO_STRASC = 0 ;
const integer RDBQO_STRDESC = 1 ;
const integer RDBQO_NUMASC = 2 ;
const integer RDBQO_NUMDESC = 3 ;
const integer RDBIT_LEXICAL = 0 ;
const integer RDBIT_DECIMAL = 1 ;
const integer RDBIT_TOKEN = 2 ;
const integer RDBIT_QGRAM = 3 ;
const integer RDBIT_OPT = 9998 ;
const integer RDBIT_VOID = 9999 ;
const integer RDBIT_KEEP = 16777216 ;
const integer RDBQCFTS_PH = 15 ;
const integer RDBQCFTS_AND = 16 ;
const integer RDBQCFTS_OR = 17 ;
const integer RDBQCFTS_EX = 18 ;
const integer RDBXO_LCKREC = 1 ;
const integer RDBXOLCK_GLB = 2 ;
const integer RDBREC_INT = 1 ;
const integer RDBREC_DBL = 2 ;
const integer RDBMS_UNION = 0 ;
const integer RDBMS_ISECT = 1 ;
const integer RDBMS_DIFF = 2 ;
const integer RDBT_RECON = 1 ;
/* Metody */
public number add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant connectUri ( string $uri )
public __construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant copy ( string $path )
public string ext ( string $name , int $options , string $key , string $value )
public array fwmKeys ( string $prefix , int $max_recs )
public mixed get ( mixed $keys )
public TokyoTyrantIterator getIterator ( void )
public int num ( void )
public TokyoTyrant out ( mixed $keys )
public TokyoTyrant put ( mixed $keys [, string $value = NULL ] )
public TokyoTyrant putCat ( mixed $keys [, string $value ] )
public TokyoTyrant putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant putNr ( mixed $keys [, string $value = NULL ] )
public mixed putShl ( string $key , string $value , int $width )
public mixed restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )
public mixed setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )
public int size ( string $key )
public array stat ( void )
public mixed sync ( void )
public TokyoTyrant tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )
public mixed vanish ( void )
}

Stałe predefiniowane

TokyoTyrant Constants

TokyoTyrant::RDBDEF_PORT

The default port of the Tokyo Tyrant database

TokyoTyrant::RDBQC_STREQ

string is equal to

TokyoTyrant::RDBQC_STRINC

string is included in

TokyoTyrant::RDBQC_STRBW

string begins with

TokyoTyrant::RDBQC_STREW

string ends with

TokyoTyrant::RDBQC_STRAND

string includes all tokens in

TokyoTyrant::RDBQC_STROR

string includes at least one token in

TokyoTyrant::RDBQC_STROREQ

string is equal to at least one token in

TokyoTyrant::RDBQC_STRRX

string matches regular expressions of

TokyoTyrant::RDBQC_NUMEQ

number is equal to

TokyoTyrant::RDBQC_NUMGT

number is greater than

TokyoTyrant::RDBQC_NUMGE

number is greater than or equal to

TokyoTyrant::RDBQC_NUMLT

number is less than

TokyoTyrant::RDBQC_NUMLE

number is less than or equal to

TokyoTyrant::RDBQC_NUMBT

number is between two tokens of

TokyoTyrant::RDBQC_NUMOREQ

number is equal to at least one token in

TokyoTyrant::RDBQC_NEGATE

negation flag

TokyoTyrant::RDBQC_NOIDX

no index flag

TokyoTyrant::RDBQO_STRASC

string ascending

TokyoTyrant::RDBQO_STRDESC

string descending

TokyoTyrant::RDBQO_NUMASC

number ascending

TokyoTyrant::RDBQO_NUMDESC

number descending

TokyoTyrant::RDBIT_LEXICAL

lexical string

TokyoTyrant::RDBIT_DECIMAL

decimal string

TokyoTyrant::RDBIT_TOKEN

token inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_QGRAM

QGRAM inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_OPT

optimize

TokyoTyrant::RDBIT_VOID

void

TokyoTyrant::RDBIT_KEEP

keep existing index

TokyoTyrant::RDBQCFTS_PH

full-text search with the phrase of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

full-text search with all tokens in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_OR

full-text search with at least one token in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_EX

full-text search with the compound expression of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

Metasearch union between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_OR

Metasearch intersection between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_EX

Metasearch difference between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBT_RECON

Whether to reconnect on connection failure. It is recommended to have this parameter on for persistent connections

TokyoTyrant::RDBXOLCK_REC

record locking

TokyoTyrant::RDBXOLCK_GLB

global locking

TokyoTyrant::RDBREC_INT

record type int

TokyoTyrant::RDBREC_DBL

record type float (double)

TokyoTyrant::TTE_SUCCESS

success

TokyoTyrant::TTE_INVALID

invalid operation

TokyoTyrant::TTE_NOHOST

host not found

TokyoTyrant::TTE_REFUSED

connection refused

TokyoTyrant::TTE_SEND

send error

TokyoTyrant::TTE_RECV

recv error

TokyoTyrant::TTE_KEEP

record exist

TokyoTyrant::TTE_NOREC

no record found

TokyoTyrant::TTE_MISC

miscellaneous error

Spis treści

  • TokyoTyrant::add — Adds to a numeric key
  • TokyoTyrant::connect — Connect to a database
  • TokyoTyrant::connectUri — Connects to a database
  • TokyoTyrant::__construct — Construct a new TokyoTyrant object
  • TokyoTyrant::copy — Copies the database
  • TokyoTyrant::ext — Execute a remote script
  • TokyoTyrant::fwmKeys — Returns the forward matching keys
  • TokyoTyrant::get — The get purpose
  • TokyoTyrant::getIterator — Get an iterator
  • TokyoTyrant::num — Number of records in the database
  • TokyoTyrant::out — Removes records
  • TokyoTyrant::put — Puts values
  • TokyoTyrant::putCat — Concatenates to a record
  • TokyoTyrant::putKeep — Puts a record
  • TokyoTyrant::putNr — Puts value
  • TokyoTyrant::putShl — Concatenates to a record
  • TokyoTyrant::restore — Restore the database
  • TokyoTyrant::setMaster — Set the replication master
  • TokyoTyrant::size — Returns the size of the value
  • TokyoTyrant::stat — Get statistics
  • TokyoTyrant::sync — Synchronize the database
  • TokyoTyrant::tune — Tunes connection values
  • TokyoTyrant::vanish — Empties the database
Przykłady
TokyoTyrant::add
tokyo_tyrant


Adds to a numeric key

TokyoTyrant
TokyoTyrant::connect
TokyoTyrant
PHP Manual

TokyoTyrant::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::add — Adds to a numeric key

Opis

public number TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] )

Adds to an int or double value. This increments the value by the given amount and returns the new value. If the key does not exist a new key is created with initial value of the increment parameter.

Parametry

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDBREC_INT or TokyoTyrant::RDBREC_DBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Zwracane wartości

Returns the new value on success

Przykłady

Przykład #1 TokyoTyrant::add() example

<?php
$tt = new TokyoTyrant("localhost", TokyoTyrant::RDBDEF_PORT);
/* Adds integer 3 to key and creates a new key */
$tt->add("test", 3);

/* String value is converted to double */
echo $tt->add("test", "3.5", TokyoTyrant::RDBREC_DBL);
?>

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

6.5

Zobacz też:

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putcat() - Concatenates to a record
  • TokyoTyrant::putkeep() - Puts a record

TokyoTyrant
TokyoTyrant::connect
TokyoTyrant


Connect to a database

TokyoTyrant::add
TokyoTyrant::connectUri
TokyoTyrant
PHP Manual

TokyoTyrant::connect

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connect — Connect to a database

Opis

public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )

Connects to a remote database

Parametry

host

The hostname

port

The port. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::connect() example

<?php
$tt = new TokyoTyrant();
$tt->connect("localhost", TokyoTyrant::RDBDEF_PORT)->put("test", "value");
?>

Zobacz też:

  • TokyoTyrant::connectUri() - Connects to a database

TokyoTyrant::add
TokyoTyrant::connectUri
TokyoTyrant


Connects to a database

TokyoTyrant::connect
TokyoTyrant::__construct
TokyoTyrant
PHP Manual

TokyoTyrant::connectUri

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connectUri — Connects to a database

Opis

public TokyoTyrant TokyoTyrant::connectUri ( string $uri )

Connects to a database using an uri

Parametry

uri

An URI to the database. For example tcp://localhost:1979/

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::connectUri() example

<?php
$tt = new TokyoTyrant();
$tt->connectUri("tcp://localhost:1978/")->put("test", "hi");
?>

Zobacz też:

  • TokyoTyrant::connect() - Connect to a database

TokyoTyrant::connect
TokyoTyrant::__construct
TokyoTyrant


Construct a new TokyoTyrant object

TokyoTyrant::connectUri
TokyoTyrant::copy
TokyoTyrant
PHP Manual

TokyoTyrant::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::__construct — Construct a new TokyoTyrant object

Opis

public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )

Constructs a new TokyoTyrant object and optionally connects to the database

Parametry

host

The hostname. Default: NULL

port

port number. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Zwracane wartości

Throws TokyoTyrantException if connection to database fails

Zobacz też:

  • TokyoTyrant::connect() - Connect to a database
  • TokyoTyrant::connectUri() - Connects to a database

TokyoTyrant::connectUri
TokyoTyrant::copy
TokyoTyrant


Copies the database

TokyoTyrant::__construct
TokyoTyrant::ext
TokyoTyrant
PHP Manual

TokyoTyrant::copy

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::copy — Copies the database

Opis

public TokyoTyrant TokyoTyrant::copy ( string $path )

Makes a copy of the current database

Parametry

path

Path to where to copy the database. The user running the remote database must have a write access to the directory.

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::copy() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->copy("/tmp/foobar.tct");
?>

Zobacz też:

  • TokyoTyrant::restore() - Restore the database

TokyoTyrant::__construct
TokyoTyrant::ext
TokyoTyrant


Execute a remote script

TokyoTyrant::copy
TokyoTyrant::fwmKeys
TokyoTyrant
PHP Manual

TokyoTyrant::ext

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::ext — Execute a remote script

Opis

public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )

Executes a remote script extension.

Parametry

name

Name of the function to execute

options

Either TokyoTyrant::RDBXO_LCKREC for record locking and TokyoTyrant::RDBXO_LCKGLB for global locking.

key

The key to pass to the function

value

The value to pass to the function

Zwracane wartości

Returns the result of the script function

Przykłady

Przykład #1 TokyoTyrant::ext() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
echo $tt->ext("somefunc", TokyoTyrant::RDBXO_LCKREC, "some_key", "some_value");
?>

TokyoTyrant::copy
TokyoTyrant::fwmKeys
TokyoTyrant


Returns the forward matching keys

TokyoTyrant::ext
TokyoTyrant::get
TokyoTyrant
PHP Manual

TokyoTyrant::fwmKeys

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::fwmKeys — Returns the forward matching keys

Opis

public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )

Returns the forward matching keys from the database

Parametry

prefix

Prefix of the keys

max_recs

Maximum records to return

Zwracane wartości

Returns an array of matching keys. The values are not returned

Przykłady

Przykład #1 TokyoTyrant::fwmKeys() example

<?php

$tt = new TokyoTyrant("localhost");

/* Create 20 macthing keys */
for ($i = 0; $i < 20; $i++) {
    $tt->put("key_" . $i, "value_" . $i);
}

/* Create 20 non-macthing keys */
for ($i = 0; $i < 20; $i++) {
    $tt->put("something_" . $i, "data_" . $i);
}

/* Get five matching keys */
var_dump($tt->fwmKeys("key_", 5));
?>

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

array(5) {
  [0]=>
  string(5) "key_5"
  [1]=>
  string(6) "key_14"
  [2]=>
  string(5) "key_6"
  [3]=>
  string(6) "key_15"
  [4]=>
  string(5) "key_7"
}

TokyoTyrant::ext
TokyoTyrant::get
TokyoTyrant


The get purpose

TokyoTyrant::fwmKeys
TokyoTyrant::getIterator
TokyoTyrant
PHP Manual

TokyoTyrant::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::get — The get purpose

Opis

public mixed TokyoTyrant::get ( mixed $keys )

This method is used to return a value or multiple values. This method accepts a string or an array as a value.

Parametry

keys

A string key or an array of string keys

Zwracane wartości

Returns a string or an array based on the given parameters. Throws a TokyoTyrantException on error. If string is passed null is returned if the key is not found. In case an array is given as an parameter only existing keys will be returned. It is not an error to pass a key that does not exist.

Przykłady

Przykład #1 TokyoTyrant::get() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->put("key1", "value1");
$tt->put("key2", "value2");
var_dump($tt->get(array("key1", "key2")));
var_dump($tt->get("key1"));
?>

Powyższy przykład wyświetli:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
}
string(6) "value1"

Zobacz też:

  • TokyoTyrant::put() - Puts values

TokyoTyrant::fwmKeys
TokyoTyrant::getIterator
TokyoTyrant


Get an iterator

TokyoTyrant::get
TokyoTyrant::num
TokyoTyrant
PHP Manual

TokyoTyrant::getIterator

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

TokyoTyrant::getIterator — Get an iterator

Opis

public TokyoTyrantIterator TokyoTyrant::getIterator ( void )

Gets an iterator for iterating all keys / values in the database.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::getIterator() example

<?php
$tt = new TokyoTyrant("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {

}
?>

Zobacz też:

  • TokyoTyrantTable::getQuery() - Get a query object
  • TokyoTyrantTable::getIterator() - Get an iterator

TokyoTyrant::get
TokyoTyrant::num
TokyoTyrant


Number of records in the database

TokyoTyrant::getIterator
TokyoTyrant::out
TokyoTyrant
PHP Manual

TokyoTyrant::num

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::num — Number of records in the database

Opis

public int TokyoTyrant::num ( void )

Returns the number of records in the database

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns number of records in the database

Przykłady

Przykład #1 TokyoTyrant::num() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Echo the number of records */
echo $tt->num();
?>

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

1234

Zobacz też:

  • TokyoTyrant::stat() - Get statistics

TokyoTyrant::getIterator
TokyoTyrant::out
TokyoTyrant


Removes records

TokyoTyrant::num
TokyoTyrant::put
TokyoTyrant
PHP Manual

TokyoTyrant::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::out — Removes records

Opis

public TokyoTyrant TokyoTyrant::out ( mixed $keys )

Removes a record or multiple records. This method accepts a string for a single key or an array of keys for multiple records.

Parametry

keys

A string key or an array of string keys

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::out() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

$tt->put("test1", "value1");
$tt->put("test2", "value2");

$tt->out(array("test1", "test2"));
?>

Zobacz też:

  • TokyoTyrant::put() - Puts values

TokyoTyrant::num
TokyoTyrant::put
TokyoTyrant


Puts values

TokyoTyrant::out
TokyoTyrant::putCat
TokyoTyrant
PHP Manual

TokyoTyrant::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::put — Puts values

Opis

public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value = NULL ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key exists the value will be replaced with new value.

Parametry

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Zwracane wartości

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::put() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->put("key", "value");

/* Put key-value pairs, new value overwrites the old */
$tt->put(array("key1" => "value1", "key" => "value2"));

/* Get back one key */
echo $tt->get("key");
?>

Powyższy przykład wyświetli:

value2

Zobacz też:

  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record

TokyoTyrant::out
TokyoTyrant::putCat
TokyoTyrant


Concatenates to a record

TokyoTyrant::put
TokyoTyrant::putKeep
TokyoTyrant
PHP Manual

TokyoTyrant::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putCat — Concatenates to a record

Opis

public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )

Appends a value into existing key or multiple values if keys is an array. The second parameter is mandatory if keys is a string. If the record does not exist a new record is created.

Parametry

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Zwracane wartości

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::putCat() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "value");

/* Concatenate single key-value pair */
$tt->putCat("key", " has more data");

/* Echo the key */
echo $tt->get("key");
?>

Powyższy przykład wyświetli:

value has more data

Zobacz też:

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record

TokyoTyrant::put
TokyoTyrant::putKeep
TokyoTyrant


Puts a record

TokyoTyrant::putCat
TokyoTyrant::putNr
TokyoTyrant
PHP Manual

TokyoTyrant::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putKeep — Puts a record

Opis

public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key already exists this method throws an exception indicating that the records exists.

Parametry

keys

A string key or an array of key-value pairs

value

The string value

Zwracane wartości

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 tokyotyrant::putKeep() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "value");

try {
    $tt->putKeep("key", "new value");
} catch (TokyoTyrantException $e) {
    if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo "Existing record! Not modified\n";
    } else {
        echo "Error: " , $e->getMessage() , "\n";
    }
}
echo $tt->get("key");
?>

Powyższy przykład wyświetli:

Existing record! Not modified
value

Zobacz też:

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putCat() - Concatenates to a record

TokyoTyrant::putCat
TokyoTyrant::putNr
TokyoTyrant


Puts value

TokyoTyrant::putKeep
TokyoTyrant::putShl
TokyoTyrant
PHP Manual

TokyoTyrant::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putNr — Puts value

Opis

public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] )

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. This method does not wait for the response from the server.

Parametry

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Zwracane wartości

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::putNr() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->putNr("key", "value");

/* Put key-value pairs */
$tt->putNr(array("key1" => "value1", "key2" => "value2"));

/* Get back one key */
echo $tt->get("key1");
?>

Powyższy przykład wyświetli:

value1

Zobacz też:

  • TokyoTyrant::putNr()
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record

TokyoTyrant::putKeep
TokyoTyrant::putShl
TokyoTyrant


Concatenates to a record

TokyoTyrant::putNr
TokyoTyrant::restore
TokyoTyrant
PHP Manual

TokyoTyrant::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putShl — Concatenates to a record

Opis

public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )

Concatenate to a record and shift to left.

Parametry

key

A string key

value

The value to concatenate

width

The width of the record

Zwracane wartości

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::putShl() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "just a long piece of data");

/* Concatenate and shift to left */
$tt->putShl("key", " and string", 15);

/* Echo the key */
echo $tt->get("key");
?>

Powyższy przykład wyświetli:

data and string

Zobacz też:

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record

TokyoTyrant::putNr
TokyoTyrant::restore
TokyoTyrant


Restore the database

TokyoTyrant::putShl
TokyoTyrant::setMaster
TokyoTyrant
PHP Manual

TokyoTyrant::restore

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::restore — Restore the database

Opis

public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )

Restore the database from the update log.

Ostrzeżenie

This method is not supported on 32bit platforms.

Parametry

log_dir

Directory where the log is

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency: Default: TRUE

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrant::putShl
TokyoTyrant::setMaster
TokyoTyrant


Set the replication master

TokyoTyrant::restore
TokyoTyrant::size
TokyoTyrant
PHP Manual

TokyoTyrant::setMaster

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::setMaster — Set the replication master

Opis

public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )

Sets the replication master of the database

Ostrzeżenie

This method is not supported on 32bit platforms.

Parametry

host

Hostname of the replication master. If NULL the replication is disabled.

port

Port of the replication master

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency.

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::setMaster() example

<?php
/* Connect to a database */
$tt = new TokyoTyrant("tokyotyrant.example.com");

/* Disable the replication */
$tt->setMaster(NULL, 0, 0);
?>

Zobacz też:

  • Classname::Method()

TokyoTyrant::restore
TokyoTyrant::size
TokyoTyrant


Returns the size of the value

TokyoTyrant::setMaster
TokyoTyrant::stat
TokyoTyrant
PHP Manual

TokyoTyrant::size

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::size — Returns the size of the value

Opis

public int TokyoTyrant::size ( string $key )

Returns the size of a value by key

Parametry

key

The key of which size to fetch

Zwracane wartości

Returns the size of the key or throw TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrant::size() example

<?php
$tt = new TokyoTyrant("localhost");

$tt->put("test_key", "12345");

echo $tt->size("test_key");
?>

Powyższy przykład wyświetli:

5

TokyoTyrant::setMaster
TokyoTyrant::stat
TokyoTyrant


Get statistics

TokyoTyrant::size
TokyoTyrant::sync
TokyoTyrant
PHP Manual

TokyoTyrant::stat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::stat — Get statistics

Opis

public array TokyoTyrant::stat ( void )

Returns statistics of the remote database

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array of key value pairs describing the statistics

Przykłady

Przykład #1 TokyoTyrant::stat() example

<?php
$tt = new TokyoTyrant("localhost");

var_dump($tt->stat());
?>

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

array(19) {
  ["version"]=>
  string(6) "1.1.28"
  ["libver"]=>
  string(3) "311"
  ["protver"]=>
  string(4) "0.91"
  ["os"]=>
  string(5) "Linux"
  ["time"]=>
  string(17) "1247358357.665630"
  ["pid"]=>
  string(5) "14348"
  ["sid"]=>
  string(8) "59025947"
  ["type"]=>
  string(9) "on-memory"
  ["path"]=>
  string(1) "*"
  ["rnum"]=>
  string(1) "4"
  ["size"]=>
  string(6) "262856"
  ["bigend"]=>
  string(1) "0"
  ["fd"]=>
  string(1) "5"
  ["loadavg"]=>
  string(8) "0.000000"
  ["memsize"]=>
  string(8) "77328384"
  ["memrss"]=>
  string(7) "1183744"
  ["ru_real"]=>
  string(13) "162776.042152"
  ["ru_user"]=>
  string(8) "0.476029"
  ["ru_sys"]=>
  string(8) "8.652540"
}

Zobacz też:

  • Classname::Method()

TokyoTyrant::size
TokyoTyrant::sync
TokyoTyrant


Synchronize the database

TokyoTyrant::stat
TokyoTyrant::tune
TokyoTyrant
PHP Manual

TokyoTyrant::sync

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::sync — Synchronize the database

Opis

public mixed TokyoTyrant::sync ( void )

Synchronizes the database on to the physical device

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrant::stat
TokyoTyrant::tune
TokyoTyrant


Tunes connection values

TokyoTyrant::sync
TokyoTyrant::vanish
TokyoTyrant
PHP Manual

TokyoTyrant::tune

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrant::tune — Tunes connection values

Opis

public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )

Tunes database connection options.

Parametry

timeout

The objects timeout value (default: 5.0)

options

Bitmask of options to tune. This can be either 0 or TokyoTyrant::RDBT_RECON. It is recommended not to change the second parameter.

Zwracane wartości

This method returns a reference to the current object and throws TokyoTyrantException on failure.

TokyoTyrant::sync
TokyoTyrant::vanish
TokyoTyrant


Empties the database

TokyoTyrant::tune
TokyoTyrantTable
TokyoTyrant
PHP Manual

TokyoTyrant::vanish

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::vanish — Empties the database

Opis

public mixed TokyoTyrant::vanish ( void )

Empties a remote database

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrant::vanish() example

<?php
$tt = new TokyoTyrant("localhost");
$tt->vanish();
?>

Zobacz też:

  • TokyoTyrant::out() - Removes records

TokyoTyrant::tune
TokyoTyrantTable
TokyoTyrant


The TokyoTyrantTable class

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

Wstęp

Provides an API to the table databases. A table database can be create using the following command: ttserver -port 1979 /tmp/tt_table.tct. In Tokyo Tyrant the table API is a schemaless database which can store arbitrary amount of key-value pairs under a single primary key.

Krótki opis klasy

TokyoTyrantTable extends TokyoTyrant {
/* Metody */
public void add ( string $key , mixed $increment [, string $type ] )
public int genUid ( void )
public void get ( mixed $keys )
public TokyoTyrantIterator getIterator ( void )
public TokyoTyrantQuery getQuery ( void )
public void out ( mixed $keys )
public int put ( string $key , array $columns )
public void putCat ( string $key , array $columns )
public void putKeep ( string $key , array $columns )
public void putNr ( mixed $keys [, string $value ] )
public void putShl ( string $key , string $value , int $width )
public mixed setIndex ( string $column , int $type )
/* Metody dziedziczone */
public number TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant TokyoTyrant::connectUri ( string $uri )
public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant TokyoTyrant::copy ( string $path )
public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )
public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )
public mixed TokyoTyrant::get ( mixed $keys )
public TokyoTyrantIterator TokyoTyrant::getIterator ( void )
public int TokyoTyrant::num ( void )
public TokyoTyrant TokyoTyrant::out ( mixed $keys )
public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value = NULL ] )
public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] )
public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )
public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )
public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )
public int TokyoTyrant::size ( string $key )
public array TokyoTyrant::stat ( void )
public mixed TokyoTyrant::sync ( void )
public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )
public mixed TokyoTyrant::vanish ( void )
}

Spis treści

  • TokyoTyrantTable::add — Adds a record
  • TokyoTyrantTable::genUid — Generate unique id
  • TokyoTyrantTable::get — Get a row
  • TokyoTyrantTable::getIterator — Get an iterator
  • TokyoTyrantTable::getQuery — Get a query object
  • TokyoTyrantTable::out — Remove records
  • TokyoTyrantTable::put — Store a row
  • TokyoTyrantTable::putCat — Concatenates to a row
  • TokyoTyrantTable::putKeep — Put a new record
  • TokyoTyrantTable::putNr — Puts value
  • TokyoTyrantTable::putShl — Concatenates to a record
  • TokyoTyrantTable::setIndex — Sets index
TokyoTyrant::vanish
TokyoTyrantTable::add
tokyo_tyrant


Adds a record

TokyoTyrantTable
TokyoTyrantTable::genUid
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::add — Adds a record

Opis

public void TokyoTyrantTable::add ( string $key , mixed $increment [, string $type ] )

This method is not supported with table databases.

Parametry

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDB_RECINT or TokyoTyrant::RDB_RECDBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Zwracane wartości

This method throws an TokyoTyrantException if used through this class.

Zobacz też:

  • TokyoTyrant::add() - Adds to a numeric key

TokyoTyrantTable
TokyoTyrantTable::genUid
TokyoTyrantTable


Generate unique id

TokyoTyrantTable::add
TokyoTyrantTable::get
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::genUid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::genUid — Generate unique id

Opis

public int TokyoTyrantTable::genUid ( void )

Generates an unique id inside the table database. In table databases rows are referenced using a numeric primary key.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an unique id or throws TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrantTable::genUid() example

<?php
$tt = new TokyoTyrantTable("localhost", 1122);

echo $tt->genUid();
?>

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

4

Zobacz też:

  • TokyoTyrantTable::put() - Store a row

TokyoTyrantTable::add
TokyoTyrantTable::get
TokyoTyrantTable


Get a row

TokyoTyrantTable::genUid
TokyoTyrantTable::getIterator
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::get — Get a row

Opis

public void TokyoTyrantTable::get ( mixed $keys )

Gets a row from table database. keys is a single integer for the primary key of the row or an array of integers for multiple rows.

Parametry

keys

The primary key, can be a string or an integer

Zwracane wartości

Returns the row as an array

Przykłady

Przykład #1 TokyoTyrantTable::get() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));
?>

Powyższy przykład wyświetli:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

Notatki

Informacja:

Starting from version 0.3.0 this method accepts array as parameter. Please note that multi-get on tables is not binary-safe.

Zobacz też:

  • TokyoTyrantTable::put() - Store a row

TokyoTyrantTable::genUid
TokyoTyrantTable::getIterator
TokyoTyrantTable


Get an iterator

TokyoTyrantTable::get
TokyoTyrantTable::getQuery
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::getIterator

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

TokyoTyrantTable::getIterator — Get an iterator

Opis

public TokyoTyrantIterator TokyoTyrantTable::getIterator ( void )

Gets an iterator for iterating all keys / values in the database.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrantTable::getIterator() example

<?php
$tt = new TokyoTyrantTable("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {
  var_dump($k, $v);
}
?>

Zobacz też:

  • TokyoTyrantTable::getQuery() - Get a query object
  • TokyoTyrant::getIterator() - Get an iterator

TokyoTyrantTable::get
TokyoTyrantTable::getQuery
TokyoTyrantTable


Get a query object

TokyoTyrantTable::getIterator
TokyoTyrantTable::out
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::getQuery

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::getQuery — Get a query object

Opis

public TokyoTyrantQuery TokyoTyrantTable::getQuery ( void )

Get a query object to execute searches on the database

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TokyoTyrantQuery on success and throws TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrantTable::getQuery() example

<?php
/* Connect to a table database */
$table = new TokyoTyrantTable("localhost", 1979);

/* Put a few rows */
$table->put(null, array("column1" => "some data", "column2" => "more data"));
$table->put(null, array("something" => "value", "data" => "good data"));

/* Get query object */
$query = $table->getQuery();

/* Add condition to query */
$query->addCond('data', TokyoTyrant::RDBQC_STREQ, 'good data');

/* Get matching rows */
var_dump($query->search());
?>

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

array(1) {
  [11]=>
  array(2) {
    ["something"]=>
    string(5) "value"
    ["data"]=>
    string(9) "good data"
  }
}

Zobacz też:

  • TokyoTyrantQuery::search() - Searches records
  • TokyoTyrantQuery::out() - Removes records based on query

TokyoTyrantTable::getIterator
TokyoTyrantTable::out
TokyoTyrantTable


Remove records

TokyoTyrantTable::getQuery
TokyoTyrantTable::put
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::out — Remove records

Opis

public void TokyoTyrantTable::out ( mixed $keys )

Removes records from a table database.

Parametry

keys

A single integer key or an array of integers

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrantTable::out() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Delete the row */
$tt->out($index);
?>

Zobacz też:

  • TokyoTyrantTable::put() - Store a row

TokyoTyrantTable::getQuery
TokyoTyrantTable::put
TokyoTyrantTable


Store a row

TokyoTyrantTable::out
TokyoTyrantTable::putCat
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::put — Store a row

Opis

public int TokyoTyrantTable::put ( string $key , array $columns )

Puts a new row into the database. This method parameters are key which is the primary key of the row, passing NULL will generate a new unique id. value is an array containing the row contents which is usually key value pairs.

Parametry

key

The primary key of the row

columns

The row contents

Zwracane wartości

Returns the primary key on success and throws TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrantTable::put() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->put($index, array("column1" => "other data", "column2" => "better data"));

/* Get the row back */
var_dump($tt->get($index));
?>

Powyższy przykład wyświetli:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(2) {
  ["column1"]=>
  string(10) "other data"
  ["column2"]=>
  string(11) "better data"
}

Zobacz też:

  • TokyoTyrantTable::get() - Get a row

TokyoTyrantTable::out
TokyoTyrantTable::putCat
TokyoTyrantTable


Concatenates to a row

TokyoTyrantTable::put
TokyoTyrantTable::putKeep
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putCat — Concatenates to a row

Opis

public void TokyoTyrantTable::putCat ( string $key , array $columns )

This method can be used to add new columns to existing records. Existing keys will be left unmodified but any new columns will be appended to the row. Passing null as key will generate a new row.

Parametry

key

The primary key of the row or NULL

columns

Array of row contents

Zwracane wartości

Returns the primary key and throws TokyoTyrantException on error.

Przykłady

Przykład #1 TokyoTyrantTable::putCat() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->putcat($index, array("column1" => "something new", "new_column" => "other data"));

/* Get the row back */
var_dump($tt->get($index));
?>

Powyższy przykład wyświetli:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(3) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
  ["new_column"]=>
  string(10) "other data"
}

Zobacz też:

  • TokyoTyrantTable::put() - Store a row

TokyoTyrantTable::put
TokyoTyrantTable::putKeep
TokyoTyrantTable


Put a new record

TokyoTyrantTable::putCat
TokyoTyrantTable::putNr
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putKeep — Put a new record

Opis

public void TokyoTyrantTable::putKeep ( string $key , array $columns )

Puts a new record into the database. If the key already exists this method throws an exception indicating that the records exists.

Parametry

key

The primary key of the row or NULL

columns

Array of the row contents

Zwracane wartości

Returns the primary key and throws TokyoTyrantException on error.

Przykłady

Przykład #1 TokyoTyrantTable::putKeep() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

try {
    $tt->putKeep($index, array("column1" => "something new", "new_column" => "other data"));
} catch (TokyoTyrantException $e) {
    if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo "Existing record! Not modified\n";
    } else {
        echo "Error: " , $e->getMessage() , "\n";
    }
}

/* Get the row back */
var_dump($tt->get($index));
?>

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

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
Existing record! Not modified
array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

Zobacz też:

  • TokyoTyrantTable::put() - Store a row

TokyoTyrantTable::putCat
TokyoTyrantTable::putNr
TokyoTyrantTable


Puts value

TokyoTyrantTable::putKeep
TokyoTyrantTable::putShl
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putNr — Puts value

Opis

public void TokyoTyrantTable::putNr ( mixed $keys [, string $value ] )

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parametry

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Zwracane wartości

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Zobacz też:

  • TokyoTyrant::putNr() - Puts value
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record

TokyoTyrantTable::putKeep
TokyoTyrantTable::putShl
TokyoTyrantTable


Concatenates to a record

TokyoTyrantTable::putNr
TokyoTyrantTable::setIndex
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putShl — Concatenates to a record

Opis

public void TokyoTyrantTable::putShl ( string $key , string $value , int $width )

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parametry

key

A string key

value

The value to concatenate

width

The width of the record

Zwracane wartości

This method is not supported on table databases.

Zobacz też:

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record
  • TokyoTyrantTable::put() - Store a row
  • TokyoTyrantTable::putKeep() - Put a new record
  • TokyoTyrantTable::putCat() - Concatenates to a row

TokyoTyrantTable::putNr
TokyoTyrantTable::setIndex
TokyoTyrantTable


Sets index

TokyoTyrantTable::putShl
TokyoTyrantQuery
TokyoTyrantTable
PHP Manual

TokyoTyrantTable::setIndex

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::setIndex — Sets index

Opis

public mixed TokyoTyrantTable::setIndex ( string $column , int $type )

Sets an index on a specified column. The index type is one of the TokyoTyrant::RDBIT_* constants. Passing TokyoTyrant::RDBIT_VOID removes the index.

Parametry

column

The name of the column

type

The index type

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrantTable::putShl
TokyoTyrantQuery
TokyoTyrantTable


The TokyoTyrantQuery class

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

Wstęp

This class is used to query the table databases

Krótki opis klasy

TokyoTyrantQuery implements Iterator , Traversable {
/* Metody */
public mixed addCond ( string $name , int $op , string $expr )
public __construct ( TokyoTyrantTable $table )
public int count ( void )
public array current ( void )
public string hint ( void )
public string key ( void )
public array metaSearch ( array $queries , int $type )
public array next ( void )
public TokyoTyrantQuery out ( void )
public bool rewind ( void )
public array search ( void )
public mixed setLimit ([ int $max [, int $skip ]] )
public mixed setOrder ( string $name , int $type )
public bool valid ( void )
}

Spis treści

  • TokyoTyrantQuery::addCond — Adds a condition to the query
  • TokyoTyrantQuery::__construct — Construct a new query
  • TokyoTyrantQuery::count — Counts records
  • TokyoTyrantQuery::current — Returns the current element
  • TokyoTyrantQuery::hint — Get the hint string of the query
  • TokyoTyrantQuery::key — Returns the current key
  • TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
  • TokyoTyrantQuery::next — Moves the iterator to next entry
  • TokyoTyrantQuery::out — Removes records based on query
  • TokyoTyrantQuery::rewind — Rewinds the iterator
  • TokyoTyrantQuery::search — Searches records
  • TokyoTyrantQuery::setLimit — Limit results
  • TokyoTyrantQuery::setOrder — Orders results
  • TokyoTyrantQuery::valid — Checks the validity of current item
TokyoTyrantTable::setIndex
TokyoTyrantQuery::addCond
tokyo_tyrant


Adds a condition to the query

TokyoTyrantQuery
TokyoTyrantQuery::__construct
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::addCond

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::addCond — Adds a condition to the query

Opis

public mixed TokyoTyrantQuery::addCond ( string $name , int $op , string $expr )

Adds a condition to the query. Condition can be something like: get all keys which value matches expr.

Parametry

name

Name of the column in the condition

op

The operator. One of the TokyoTyrant::RDBQC_* constants

expr

The expression

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrantQuery::addCond() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Dump the search results */
var_dump($query->search());
?>

Powyższy przykład wyświetli:

array(2) {
  [1]=>
  array(2) {
    ["column1"]=>
    string(9) "some data"
    ["column2"]=>
    string(14) "something here"
  }
  [4]=>
  array(2) {
    ["column45"]=>
    string(11) "random data"
    ["column2"]=>
    string(25) "something along the lines"
  }
}

Zobacz też:

  • Classname::Method()

TokyoTyrantQuery
TokyoTyrantQuery::__construct
TokyoTyrantQuery


Construct a new query

TokyoTyrantQuery::addCond
TokyoTyrantQuery::count
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::__construct — Construct a new query

Opis

public TokyoTyrantQuery::__construct ( TokyoTyrantTable $table )

Construct a new query object

Parametry

table

TokyoTyrantTable object with active database connection

Zwracane wartości

Returns a new TokyoTyrantQuery object and throws TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrantQuery::__construct() example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);

$query = new TokyoTyrantQuery($tt);

/* Work with $query */
?>

Zobacz też:

  • TokyoTyrantTable::getQuery() - Get a query object

TokyoTyrantQuery::addCond
TokyoTyrantQuery::count
TokyoTyrantQuery


Counts records

TokyoTyrantQuery::__construct
TokyoTyrantQuery::current
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::count

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

TokyoTyrantQuery::count — Counts records

Opis

public int TokyoTyrantQuery::count ( void )

Returns a count of how many records a query returns.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a count of matching rows and throws TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrantQuery::count() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Count the results */
var_dump($query->count());
?>

Powyższy przykład wyświetli:

int(2)

Zobacz też:

  • TokyoTyrantQuery::out() - Removes records based on query
  • TokyoTyrantQuery::search() - Searches records
  • TokyoTyrantQuery::metaSearch() - Retrieve records with multiple queries

TokyoTyrantQuery::__construct
TokyoTyrantQuery::current
TokyoTyrantQuery


Returns the current element

TokyoTyrantQuery::count
TokyoTyrantQuery::hint
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::current

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::current — Returns the current element

Opis

public array TokyoTyrantQuery::current ( void )

Returns the current element. Part of Iterator interface

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current row

Przykłady

Przykład #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

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

pk: 1, columns: 2
pk: 4, columns: 2

Zobacz też:

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

TokyoTyrantQuery::count
TokyoTyrantQuery::hint
TokyoTyrantQuery


Get the hint string of the query

TokyoTyrantQuery::current
TokyoTyrantQuery::key
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::hint

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

TokyoTyrantQuery::hint — Get the hint string of the query

Opis

public string TokyoTyrantQuery::hint ( void )

Get the hint string of the query. The hint string contains information about an executed query and it could be compared to for example MySQL EXPLAIN statement.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method always returns a string

Przykłady

Przykład #1 TokyoTyrantQuery::hint example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);
$tt->vanish();

for ($i = 0; $i < 11; $i++) {
     $tt->put(null, array('a_col' => 'a' . $i, 'b_col' => 'b' . $i));
}

$query = $tt->getQuery();
$query->addCond('a_col', TokyoTyrant::RDBQC_STRBW, 'a');

$query->search();
var_dump($query->hint());
?>

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

string(72) "
scanning the whole table
result set size: 11
leaving the natural order
"

Zobacz też:

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

TokyoTyrantQuery::current
TokyoTyrantQuery::key
TokyoTyrantQuery


Returns the current key

TokyoTyrantQuery::hint
TokyoTyrantQuery::metaSearch
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::key

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::key — Returns the current key

Opis

public string TokyoTyrantQuery::key ( void )

Returns the current key. Part of the Iterator interface

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current key and throws TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

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

pk: 1, columns: 2
pk: 4, columns: 2

Zobacz też:

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

TokyoTyrantQuery::hint
TokyoTyrantQuery::metaSearch
TokyoTyrantQuery


Retrieve records with multiple queries

TokyoTyrantQuery::key
TokyoTyrantQuery::next
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::metaSearch

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

TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries

Opis

public array TokyoTyrantQuery::metaSearch ( array $queries , int $type )

Executes multiple queries on a database and returns matching records. The current object is always the left most object in the search.

Parametry

queries

Array of TokyoTyrantQuery objects

type

One of the TokyoTyrant::RDBMS_* constants

Zwracane wartości

Returns the matching rows and throws TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrantQuery::metaSearch() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add test data */
$tt->put('cherry',     array('color' => 'red'));
$tt->put('strawberry', array('color' => 'red'));
$tt->put('apple',      array('color' => 'green'));
$tt->put('lemon',      array('color' => 'yellow'));

/* First query */
$query = $tt->getQuery();
$query->addCond('color', TokyoTyrant::RDBQC_STREQ, 'red')->setOrder('color', TokyoTyrant::RDBQO_STRASC);

/* Second query */
$query1 = $tt->getQuery();
$query1->addCond('color', TokyoTyrant::RDBQC_STREQ, 'yellow');

/* Get union between the queries */
var_dump($query->metaSearch(array($query1), TokyoTyrant::RDBMS_UNION));
?>

Powyższy przykład wyświetli:

array(3) {
  ["cherry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["strawberry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["lemon"]=>
  array(1) {
    ["color"]=>
    string(6) "yellow"
  }
}

Zobacz też:

  • TokyoTyrantQuery::search() - Searches records

TokyoTyrantQuery::key
TokyoTyrantQuery::next
TokyoTyrantQuery


Moves the iterator to next entry

TokyoTyrantQuery::metaSearch
TokyoTyrantQuery::out
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::next

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::next — Moves the iterator to next entry

Opis

public array TokyoTyrantQuery::next ( void )

Returns the next result in the resultset. Part of the Iterator interface.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the next row and throws TokyoTyrantException on error.

Przykłady

Przykład #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

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

pk: 1, columns: 2
pk: 4, columns: 2

Zobacz też:

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

TokyoTyrantQuery::metaSearch
TokyoTyrantQuery::out
TokyoTyrantQuery


Removes records based on query

TokyoTyrantQuery::next
TokyoTyrantQuery::rewind
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::out — Removes records based on query

Opis

public TokyoTyrantQuery TokyoTyrantQuery::out ( void )

Removes all records that match the query. Works exactly like search but removes the records instead of returning them.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

Przykłady

Przykład #1 TokyoTyrantQuery::out() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Remove matching records */
$query->out();
?>

Zobacz też:

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

TokyoTyrantQuery::next
TokyoTyrantQuery::rewind
TokyoTyrantQuery


Rewinds the iterator

TokyoTyrantQuery::out
TokyoTyrantQuery::search
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::rewind

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::rewind — Rewinds the iterator

Opis

public bool TokyoTyrantQuery::rewind ( void )

Rewind the resultset and executes the query if it has not been executed. Part of the Iterator interface.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE

Przykłady

Przykład #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

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

pk: 1, columns: 2
pk: 4, columns: 2

Zobacz też:

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

TokyoTyrantQuery::out
TokyoTyrantQuery::search
TokyoTyrantQuery


Searches records

TokyoTyrantQuery::rewind
TokyoTyrantQuery::setLimit
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::search

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::search — Searches records

Opis

public array TokyoTyrantQuery::search ( void )

Executes a search on the table database. Returns an array of arrays containing the matching records. In the returned array the first level is the primary key of the data and the second level is the row data.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the matching rows and throws TokyoTyrantException on error

Przykłady

Przykład #1 TokyoTyrantQuery::search() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Dump the search results */
var_dump($query->search());
?>

Powyższy przykład wyświetli:

array(2) {
  [1]=>
  array(2) {
    ["column1"]=>
    string(9) "some data"
    ["column2"]=>
    string(14) "something here"
  }
  [4]=>
  array(2) {
    ["column45"]=>
    string(11) "random data"
    ["column2"]=>
    string(25) "something along the lines"
  }
}

Zobacz też:

  • TokyoTyrantQuery::out() - Removes records based on query
  • TokyoTyrantQuery::metaSearch() - Retrieve records with multiple queries

TokyoTyrantQuery::rewind
TokyoTyrantQuery::setLimit
TokyoTyrantQuery


Limit results

TokyoTyrantQuery::search
TokyoTyrantQuery::setOrder
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::setLimit

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setLimit — Limit results

Opis

public mixed TokyoTyrantQuery::setLimit ([ int $max [, int $skip ]] )

Set the maximum amount of records to return on a query.

Parametry

max

Maximum amount of records. Default: -1

skip

How many records to skip from the start. Default: -1

Zwracane wartości

This method returns the current object and throws TokyoTyrantException on failure.

TokyoTyrantQuery::search
TokyoTyrantQuery::setOrder
TokyoTyrantQuery


Orders results

TokyoTyrantQuery::setLimit
TokyoTyrantQuery::valid
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::setOrder

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setOrder — Orders results

Opis

public mixed TokyoTyrantQuery::setOrder ( string $name , int $type )

Sets the order of a query

Parametry

name

The column name to apply the ordering on.

type

The type can be one of the following constants:

  • TokyoTyrant::RDBQO_STRASC - String ascending
  • TokyoTyrant::RDBQO_STRDESC - String descending
  • TokyoTyrant::RDBQO_NUMASC - Numberic ascending
  • TokyoTyrant::RDBQO_NUMDESC - String descending

Zwracane wartości

This method returns the current object.

TokyoTyrantQuery::setLimit
TokyoTyrantQuery::valid
TokyoTyrantQuery


Checks the validity of current item

TokyoTyrantQuery::setOrder
TokyoTyrantIterator
TokyoTyrantQuery
PHP Manual

TokyoTyrantQuery::valid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::valid — Checks the validity of current item

Opis

public bool TokyoTyrantQuery::valid ( void )

Checks if the current item is valid. Part of the Iterator interface

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the current item is valid and FALSE if not.

Przykłady

Przykład #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

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

pk: 1, columns: 2
pk: 4, columns: 2

Zobacz też:

  • TokyoTyrantQuery::addCond() - Adds a condition to the query

TokyoTyrantQuery::setOrder
TokyoTyrantIterator
TokyoTyrantQuery


The TokyoTyrantIterator class

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

Wstęp

Provides an iterator for TokyoTyrant and TokyoTyrantTable objects. The iterator iterates over all keys and values in the database. TokyoTyrantIterator was added in version 0.2.0.

Krótki opis klasy

TokyoTyrantIterator implements Iterator {
/* Methods */
public __construct ( mixed $object )
public mixed current ( void )
public mixed key ( void )
public mixed next ( void )
public void rewind ( void )
public bool valid ( void )
/* Inherited methods */
public number TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] )
public TokyoTyrant TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] )
public TokyoTyrant TokyoTyrant::connectUri ( string $uri )
public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant TokyoTyrant::copy ( string $path )
public string TokyoTyrant::ext ( string $name , int $options , string $key , string $value )
public array TokyoTyrant::fwmKeys ( string $prefix , int $max_recs )
public mixed TokyoTyrant::get ( mixed $keys )
public TokyoTyrantIterator TokyoTyrant::getIterator ( void )
public int TokyoTyrant::num ( void )
public TokyoTyrant TokyoTyrant::out ( mixed $keys )
public TokyoTyrant TokyoTyrant::put ( mixed $keys [, string $value = NULL ] )
public TokyoTyrant TokyoTyrant::putCat ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putKeep ( mixed $keys [, string $value ] )
public TokyoTyrant TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] )
public mixed TokyoTyrant::putShl ( string $key , string $value , int $width )
public mixed TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = true ] )
public mixed TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = true ] )
public int TokyoTyrant::size ( string $key )
public array TokyoTyrant::stat ( void )
public mixed TokyoTyrant::sync ( void )
public TokyoTyrant TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] )
public mixed TokyoTyrant::vanish ( void )
}

Spis treści

  • TokyoTyrantIterator::__construct — Construct an iterator
  • TokyoTyrantIterator::current — Get the current value
  • TokyoTyrantIterator::key — Returns the current key
  • TokyoTyrantIterator::next — Move to next key
  • TokyoTyrantIterator::rewind — Rewinds the iterator
  • TokyoTyrantIterator::valid — Rewinds the iterator
TokyoTyrantQuery::valid
TokyoTyrantIterator::__construct
tokyo_tyrant


Construct an iterator

TokyoTyrantIterator
TokyoTyrantIterator::current
TokyoTyrantIterator
PHP Manual

TokyoTyrantIterator::__construct

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::__construct — Construct an iterator

Opis

public TokyoTyrantIterator::__construct ( mixed $object )

Construct a new TokyoTyrantIterator object. One connection can have multiple iterators but it is not quaranteed that all items are traversed in that case. object parameter can be either an of instance TokyoTyrant or TokyoTyrantTable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Throws an exception if iterator initialization fails.

Przykłady

Przykład #1 TokyoTyrantIterator::__construct() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Construct an iterator */
$it = new TokyoTyrantIterator($tt);

foreach ($it as $value) {
    var_dump($value);
}
?>

Powyższy przykład wyświetli:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

Zobacz też:

  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key

TokyoTyrantIterator
TokyoTyrantIterator::current
TokyoTyrantIterator


Get the current value

TokyoTyrantIterator::__construct
TokyoTyrantIterator::key
TokyoTyrantIterator
PHP Manual

TokyoTyrantIterator::current

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::current — Get the current value

Opis

public mixed TokyoTyrantIterator::current ( void )

Returns the current value during iteration.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current value on success and false on failure.

Zobacz też:

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator

TokyoTyrantIterator::__construct
TokyoTyrantIterator::key
TokyoTyrantIterator


Returns the current key

TokyoTyrantIterator::current
TokyoTyrantIterator::next
TokyoTyrantIterator
PHP Manual

TokyoTyrantIterator::key

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::key — Returns the current key

Opis

public mixed TokyoTyrantIterator::key ( void )

Returns the current key.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current key on success and false on failure.

Zobacz też:

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator

TokyoTyrantIterator::current
TokyoTyrantIterator::next
TokyoTyrantIterator


Move to next key

TokyoTyrantIterator::key
TokyoTyrantIterator::rewind
TokyoTyrantIterator
PHP Manual

TokyoTyrantIterator::next

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::next — Move to next key

Opis

public mixed TokyoTyrantIterator::next ( void )

Move to next key during iteration and return it's value.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the next value on success and false on failure.

Zobacz też:

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::rewind() - Rewinds the iterator

TokyoTyrantIterator::key
TokyoTyrantIterator::rewind
TokyoTyrantIterator


Rewinds the iterator

TokyoTyrantIterator::next
TokyoTyrantIterator::valid
TokyoTyrantIterator
PHP Manual

TokyoTyrantIterator::rewind

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::rewind — Rewinds the iterator

Opis

public void TokyoTyrantIterator::rewind ( void )

Rewinds the iterator for new iteration. Called automatically at the beginning of foreach.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Throws TokyoTyrantException if iterator initialization fails.

Zobacz też:

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind()

TokyoTyrantIterator::next
TokyoTyrantIterator::valid
TokyoTyrantIterator


Rewinds the iterator

TokyoTyrantIterator::rewind
TokyoTyrantException
TokyoTyrantIterator
PHP Manual

TokyoTyrantIterator::valid

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::valid — Rewinds the iterator

Opis

public bool TokyoTyrantIterator::valid ( void )

Checks whether the internal pointer points to valid element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the current item is valid and FALSE if not.

Zobacz też:

  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator

TokyoTyrantIterator::rewind
TokyoTyrantException
TokyoTyrantIterator


The TokyoTyrantException class

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

Wstęp

TokyoTyrantException

Krótki opis klasy

tokyotyrantexception extends Exception {
/* Właściwości */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 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

code

The exception code. This can be compared to TokyoTyrant::TTE_* constants

TokyoTyrantIterator::valid
Rozszerzenia powiązane z systemem plików
tokyo_tyrant


Rozszerzenia powiązane z systemem plików

  • Direct IO
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Direct IO Funkcje
  • Directories
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Directory — The Directory class
    • Funkcje katalogów
  • Fileinfo — File Information
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Fileinfo Funkcje
  • Filesystem
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje Systemu plików
  • Inotify
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Inotify Funkcje
  • Mimetype
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
  • Proctitle
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Proctitle Funkcje
  • xattr
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • xattr Funkcje
  • xdiff
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • xdiff Funkcje
TokyoTyrantException
Direct IO
Opis funkcji


Direct IO

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Direct IO Funkcje
    • dio_close — Closes the file descriptor given by fd
    • dio_fcntl — Performs a c library fcntl on fd
    • dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.
    • dio_read — Reads bytes from a file descriptor
    • dio_seek — Seeks to pos on fd from whence
    • dio_stat — Gets stat information about the file descriptor fd
    • dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
    • dio_truncate — Truncates file descriptor fd to offset bytes
    • dio_write — Writes data to fd with optional truncation at length
Rozszerzenia powiązane z systemem plików
Wstęp
Rozszerzenia powiązane z systemem plików


Wstęp

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0.

This extension is only available on Windows Platforms as of PHP 5.0.0

Direct IO
Instalacja/Konfiguracja
Direct IO


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Direct IO


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/dio.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

One resource type is defined by this extension: a file descriptor returned by dio_open().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

F_DUPFD (integer)

F_GETFD (integer)

F_GETFL (integer)

F_GETLK (integer)

F_GETOWN (integer)

F_RDLCK (integer)

F_SETFL (integer)

F_SETLK (integer)

F_SETLKW (integer)

F_SETOWN (integer)

F_UNLCK (integer)

F_WRLCK (integer)

O_APPEND (integer)

O_ASYNC (integer)

O_CREAT (integer)

O_EXCL (integer)

O_NDELAY (integer)

O_NOCTTY (integer)

O_NONBLOCK (integer)

O_RDONLY (integer)

O_RDWR (integer)

O_SYNC (integer)

O_TRUNC (integer)

O_WRONLY (integer)

S_IRGRP (integer)

S_IROTH (integer)

S_IRUSR (integer)

S_IRWXG (integer)

S_IRWXO (integer)

S_IRWXU (integer)

S_IWGRP (integer)

S_IWOTH (integer)

S_IWUSR (integer)

S_IXGRP (integer)

S_IXOTH (integer)

S_IXUSR (integer)

Typy zasobów
Direct IO Funkcje
Direct IO


Direct IO Funkcje

Spis treści

  • dio_close — Closes the file descriptor given by fd
  • dio_fcntl — Performs a c library fcntl on fd
  • dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.
  • dio_read — Reads bytes from a file descriptor
  • dio_seek — Seeks to pos on fd from whence
  • dio_stat — Gets stat information about the file descriptor fd
  • dio_tcsetattr — Sets terminal attributes and baud rate for a serial port
  • dio_truncate — Truncates file descriptor fd to offset bytes
  • dio_write — Writes data to fd with optional truncation at length
Stałe predefiniowane
dio_close
Direct IO


Closes the file descriptor given by fd

Direct IO Funkcje
dio_fcntl
Direct IO Funkcje
PHP Manual

dio_close

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_close — Closes the file descriptor given by fd

Opis

void dio_close ( resource $fd )

The function dio_close() closes the file descriptor fd.

Parametry

fd

The file descriptor returned by dio_open().

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Closing an open file descriptor

<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_close($fd);
?>

Zobacz też:

  • dio_open() - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

Direct IO Funkcje
dio_fcntl
Direct IO Funkcje


Performs a c library fcntl on fd

dio_close
dio_open
Direct IO Funkcje
PHP Manual

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_fcntl — Performs a c library fcntl on fd

Opis

mixed dio_fcntl ( resource $fd , int $cmd [, mixed $args ] )

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied.

Parametry

fd

The file descriptor returned by dio_open().

cmd

Can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater than or equal to args and returns them.

  • F_SETFL - Sets the file descriptors flags to the value specified by args, which can be O_APPEND, O_NONBLOCK or O_ASYNC. To use O_ASYNC you will need to use the PCNTL extension.

args

args is an associative array, when cmd is F_SETLK or F_SETLLW, with the following keys:

  • "start" - offset where lock begins

  • "length" - size of locked area. zero means to end of file

  • "wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

Zwracane wartości

Returns the result of the C call.

Przykłady

Przykład #1 Setting and clearing a lock

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
   // the file descriptor appears locked
   echo "The lock can not be cleared. It is held by someone else.";
} else {
   echo "Lock succesfully set/cleared";
}

dio_close($fd);
?>

Notatki

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

dio_close
dio_open
Direct IO Funkcje


Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

dio_fcntl
dio_read
Direct IO Funkcje
PHP Manual

dio_open

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_open — Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.

Opis

resource dio_open ( string $filename , int $flags [, int $mode = 0 ] )

dio_open() opens a file and returns a new file descriptor for it.

Parametry

filename

The pathname of the file to open.

flags

The flags parameter is a bitwise-ORed value comprising flags from the following list. This value must include one of O_RDONLY, O_WRONLY, or O_RDWR. Additionally, it may include any combination of the other flags from this list.

  • O_RDONLY - opens the file for read access.

  • O_WRONLY - opens the file for write access.

  • O_RDWR - opens the file for both reading and writing.

  • O_CREAT - creates the file, if it doesn't already exist.

  • O_EXCL - if both O_CREAT and O_EXCL are set and the file already exists, causes dio_open() to fail.

  • O_TRUNC - if the file exists and is opened for write access, the file will be truncated to zero length.

  • O_APPEND - write operations write data at the end of the file.

  • O_NONBLOCK - sets non blocking mode.

  • O_NOCTTY - prevent the OS from assigning the opened file as the process's controlling terminal when opening a TTY device file.

mode

If flags contains O_CREAT, mode will set the permissions of the file (creation permissions). Mode is required for correct operation when O_CREAT is specified in mode and is ignored otherwise.

The actual permissions assigned to the created file will be affected by the process's umask setting as per usual.

Zwracane wartości

A file descriptor or FALSE on error.

Przykłady

Przykład #1 Opening a file descriptor

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?>

Zobacz też:

  • dio_close() - Closes the file descriptor given by fd

dio_fcntl
dio_read
Direct IO Funkcje


Reads bytes from a file descriptor

dio_open
dio_seek
Direct IO Funkcje
PHP Manual

dio_read

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_read — Reads bytes from a file descriptor

Opis

string dio_read ( resource $fd [, int $len = 1024 ] )

The function dio_read() reads and returns len bytes from file with descriptor fd.

Parametry

fd

The file descriptor returned by dio_open().

len

The number of bytes to read. If not specified, dio_read() reads 1K sized block.

Zwracane wartości

The bytes read from fd.

Zobacz też:

  • dio_write() - Writes data to fd with optional truncation at length

dio_open
dio_seek
Direct IO Funkcje


Seeks to pos on fd from whence

dio_read
dio_stat
Direct IO Funkcje
PHP Manual

dio_seek

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_seek — Seeks to pos on fd from whence

Opis

int dio_seek ( resource $fd , int $pos [, int $whence = SEEK_SET ] )

The function dio_seek() is used to change the file position of the given file descriptor.

Parametry

fd

The file descriptor returned by dio_open().

pos

The new position.

whence

Specifies how the position pos should be interpreted:

  • SEEK_SET (default) - specifies that pos is specified from the beginning of the file.

  • SEEK_CUR - Specifies that pos is a count of characters from the current file position. This count may be positive or negative.

  • SEEK_END - Specifies that pos is a count of characters from the end of the file. A negative count specifies a position within the current extent of the file; a positive count specifies a position past the current end. If you set the position past the current end, and actually write data, you will extend the file with zeros up to that position.

Zwracane wartości

Przykłady

Przykład #1 Positioning in a file

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_seek($fd, 10, SEEK_SET);
// position is now at 10 characters from the start of the file

dio_seek($fd, -2, SEEK_CUR);
// position is now at 8 characters from the start of the file

dio_seek($fd, -5, SEEK_END);
// position is now at 5 characters from the end of the file

dio_seek($fd, 10, SEEK_END);
// position is now at 10 characters past the end of the file.
// The 10 characters between the end of the file and the current
// position are filled with zeros.

dio_close($fd);
?>

dio_read
dio_stat
Direct IO Funkcje


Gets stat information about the file descriptor fd

dio_seek
dio_tcsetattr
Direct IO Funkcje
PHP Manual

dio_stat

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_stat — Gets stat information about the file descriptor fd

Opis

array dio_stat ( resource $fd )

dio_stat() returns information about the given file descriptor.

Parametry

fd

The file descriptor returned by dio_open().

Zwracane wartości

Returns an associative array with the following keys:

  • "device" - device

  • "inode" - inode

  • "mode" - mode

  • "nlink" - number of hard links

  • "uid" - user id

  • "gid" - group id

  • "device_type" - device type (if inode device)

  • "size" - total size in bytes

  • "blocksize" - blocksize

  • "blocks" - number of blocks allocated

  • "atime" - time of last access

  • "mtime" - time of last modification

  • "ctime" - time of last change

On error dio_stat() returns NULL.

dio_seek
dio_tcsetattr
Direct IO Funkcje


Sets terminal attributes and baud rate for a serial port

dio_stat
dio_truncate
Direct IO Funkcje
PHP Manual

dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 <= 5.0.5)

dio_tcsetattr — Sets terminal attributes and baud rate for a serial port

Opis

bool dio_tcsetattr ( resource $fd , array $options )

dio_tcsetattr() sets the terminal attributes and baud rate of the open fd.

Parametry

fd

The file descriptor returned by dio_open().

options

The currently available options are:

  • 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800, 1200,600,300,200,150,134,110,75 or 50, default value is 9600.

  • 'bits' - data bits - can be 8,7,6 or 5. Default value is 8.

  • 'stop' - stop bits - can be 1 or 2. Default value is 1.

  • 'parity' - can be 0,1 or 2. Default value is 0.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Setting the baud rate on a serial port

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd, F_SETFL, O_SYNC);

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  => 1,
  'parity' => 0
));

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
      echo $data;
  }
}

?>

Notatki

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

dio_stat
dio_truncate
Direct IO Funkcje


Truncates file descriptor fd to offset bytes

dio_tcsetattr
dio_write
Direct IO Funkcje
PHP Manual

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_truncate — Truncates file descriptor fd to offset bytes

Opis

bool dio_truncate ( resource $fd , int $offset )

dio_truncate() truncates a file to at most offset bytes in size.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes.

Parametry

fd

The file descriptor returned by dio_open().

offset

The offset in bytes.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

dio_tcsetattr
dio_write
Direct IO Funkcje


Writes data to fd with optional truncation at length

dio_truncate
Directories
Direct IO Funkcje
PHP Manual

dio_write

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_write — Writes data to fd with optional truncation at length

Opis

int dio_write ( resource $fd , string $data [, int $len = 0 ] )

dio_write() writes up to len bytes from data to file fd.

Parametry

fd

The file descriptor returned by dio_open().

data

The written data.

len

The length of data to write in bytes. If not specified, the function writes all the data to the specified file.

Zwracane wartości

Returns the number of bytes written to fd.

Zobacz też:

  • dio_read() - Reads bytes from a file descriptor

dio_truncate
Directories
Direct IO Funkcje


Directories

  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Directory — The Directory class
    • Directory::close — Close directory handle
    • Directory::read — Read entry from directory handle
    • Directory::rewind — Rewind directory handle
  • Funkcje katalogów
    • chdir — Zmienia bieżący katalog
    • chroot — Zmienia główny katalog
    • closedir — Zamyka wskaźnik katalogu
    • dir — Return an instance of the Directory class
    • getcwd — Wskazuje bieżący katalog roboczy
    • opendir — Otwiera katalog
    • readdir — Czyta zawartość katalogu
    • rewinddir — Ustawia wskaźnik katalogu na początek
    • scandir — Wypisze wszystkie pliki i katalogi z określonej lokalizacji
dio_write
Instalacja/Konfiguracja
Rozszerzenia powiązane z systemem plików


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Directories
Wymagania
Directories


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.

DIRECTORY_SEPARATOR (string)
PATH_SEPARATOR (string)
Available since PHP 4.3.0. Semicolon on Windows, colon otherwise.
SCANDIR_SORT_ASCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_DESCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_NONE (integer)
Available since PHP 5.4.0.
Typy zasobów
Directory
Directories


The Directory class

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

Wstęp

Instances of Directory are created by calling the dir() function, not by the new operator.

Krótki opis klasy

Directory {
/* Właściwości */
public string $path ;
public resource $handle ;
/* Metody */
public void close ([ resource $dir_handle ] )
public string read ([ resource $dir_handle ] )
public void rewind ([ resource $dir_handle ] )
}

Właściwości

path

The directory that was opened.

handle

Can be used with other directory functions such as readdir(), rewinddir() and closedir().

Spis treści

  • Directory::close — Close directory handle
  • Directory::read — Read entry from directory handle
  • Directory::rewind — Rewind directory handle
Stałe predefiniowane
Directory::close
Directories


Close directory handle

Directory
Directory::read
Directory
PHP Manual

Directory::close

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

Directory::close — Close directory handle

Opis

public void Directory::close ([ resource $dir_handle ] )

Same as closedir(), only dir_handle defaults to $this.

Directory
Directory::read
Directory


Read entry from directory handle

Directory::close
Directory::rewind
Directory
PHP Manual

Directory::read

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

Directory::read — Read entry from directory handle

Opis

public string Directory::read ([ resource $dir_handle ] )

Same as readdir(), only dir_handle defaults to $this.

Directory::close
Directory::rewind
Directory


Rewind directory handle

Directory::read
Funkcje katalogów
Directory
PHP Manual

Directory::rewind

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

Directory::rewind — Rewind directory handle

Opis

public void Directory::rewind ([ resource $dir_handle ] )

Same as rewinddir(), only dir_handle defaults to $this.

Directory::read
Funkcje katalogów
Directory


Funkcje katalogów

Zobacz też:

Dla funkcji pokrewnych takich jak dirname(),
is_dir(), mkdir(), oraz
rmdir(), zobacz rozdział
System plików.

Spis treści

  • chdir — Zmienia bieżący katalog
  • chroot — Zmienia główny katalog
  • closedir — Zamyka wskaźnik katalogu
  • dir — Return an instance of the Directory class
  • getcwd — Wskazuje bieżący katalog roboczy
  • opendir — Otwiera katalog
  • readdir — Czyta zawartość katalogu
  • rewinddir — Ustawia wskaźnik katalogu na początek
  • scandir — Wypisze wszystkie pliki i katalogi z określonej lokalizacji
Directory::rewind
chdir
Directories


Zmienia bieżący katalog

Funkcje katalogów
chroot
Funkcje katalogów
PHP Manual

chdir

(PHP 4, PHP 5)

chdir — Zmienia bieżący katalog

Opis

bool chdir ( string $katalog )

Zmienia bieżący katalog roboczy na katalog

Parametry

katalog

Nowy bieżący katalog

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia chdir()

<?php

// bieżący katalog
echo getcwd() . "\n";

chdir('public_html');

// nowy bieżący katalog
echo getcwd() . "\n";

?>

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

/home/vincent
/home/vincent/public_html

Notatki

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza czy katalog, na którym zostaną wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Zobacz też:

  • getcwd() - Wskazuje bieżący katalog roboczy

Funkcje katalogów
chroot
Funkcje katalogów


Zmienia główny katalog

chdir
closedir
Funkcje katalogów
PHP Manual

chroot

(PHP 4 >= 4.0.5, PHP 5)

chroot — Zmienia główny katalog

Opis

bool chroot ( string $katalog )

Zmienia główny katalog wykonywanego procesu na katalog

Ta funkcja jest dostępna tylko gdy system ją obsługuje i jest używany CLI, CGI lub Embed SAPI. Również, ta funkcja wymaga praw superużytkownika.

Parametry

katalog

Nowy katalog

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

chdir
closedir
Funkcje katalogów


Zamyka wskaźnik katalogu

chroot
dir
Funkcje katalogów
PHP Manual

closedir

(PHP 4, PHP 5)

closedir — Zamyka wskaźnik katalogu

Opis

void closedir ([ zasób $uchwyt_katalogu ] )

Zamyka wskaźnik katalogu identyfikowany przez uchwyt_katalogu. Wskaźnik katalogu musi być wcześniej otwarty przez opendir().

Parametry

uchwyt_katalogu

Uchwyt katalogu (zasób) otwarty wcześniej za pomocą opendir(). Jeśli uchwyt katalogu nie jest podany, przyjmowany jest ostatni wskaźnik katalogu utworzony przez opendir().

Przykłady

Przykład #1 Przykład closedir()

<?php
$dir = "/etc/php5/";

// Otworzenie podanego katalogu, przeczytanie katalogu do zmiennej i zamknięcie
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $directory = readdir($dh);
        closedir($dh);
    }
}
?>

chroot
dir
Funkcje katalogów


Return an instance of the Directory class

closedir
getcwd
Funkcje katalogów
PHP Manual

dir

(PHP 4, PHP 5)

dir — Return an instance of the Directory class

Opis

Directory dir ( string $directory [, resource $context ] )

A pseudo-object oriented mechanism for reading a directory. The given directory is opened.

Parametry

directory

Directory to open

context

Informacja: Obsługa kontekstów została dodana w PHP 5.0.0. Opis kontekstów znajduje się w rozdziale Stream Funkcje.

Zwracane wartości

Returns an instance of Directory, or NULL with wrong parameters, or FALSE in case of another error.

Przykłady

Przykład #1 dir() example

Please note the fashion in which Directory::read()'s return value is checked in the example below. We are explicitly testing whether the return value is identical to (equal to and of the same type as - see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop.

<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
   echo $entry."\n";
}
$d->close();
?>

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

Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli

Notatki

Informacja:

The order in which directory entries are returned by the read method is system-dependent.

closedir
getcwd
Funkcje katalogów


Wskazuje bieżący katalog roboczy

dir
opendir
Funkcje katalogów
PHP Manual

getcwd

(PHP 4, PHP 5)

getcwd — Wskazuje bieżący katalog roboczy

Opis

string getcwd ( void )

Pobiera aktualny katalog roboczy.

Zwracane wartości

Zwraca aktualny katalog roboczy, lub FALSE w przypadku błędu.

W niektórych przypadkach w systemie Uniksowym, getcwd() zwróci FALSE jeśli którykolwiek z katalogów w ścieżce nie posiada praw do odczytu lub wykonywania, nawet jeśli bieżący katalog roboczy posiada takie prawa. Więcej informacji na temat praw można przeczytać w opisie funckji chmod().

Przykłady

Przykład #1 Przykład użycia getcwd()

<?php

// bieżący katalog roboczy
echo getcwd() . "\n";

chdir('cvs');

// nowy bieżący katalog roboczy
echo getcwd() . "\n";

?>

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

/home/didou
/home/didou/cvs

Zobacz też:

  • chdir() - Zmienia bieżący katalog
  • chmod() - Zmienia prawa dostępu do pliku

dir
opendir
Funkcje katalogów


Otwiera katalog

getcwd
readdir
Funkcje katalogów
PHP Manual

opendir

(PHP 4, PHP 5)

opendir — Otwiera katalog

Opis

resource opendir ( string $path [, resource $context ] )

Zwraca wskaźnik do otwartego katalogu, który może być następnie wykorzystany przez closedir(), readdir(), and rewinddir() calls.

Parametry

path

Ścieżka do katalogu który ma zostać otwarty

context

Po opis parametru context, sięgnij do the streams section

Zwracane wartości

W przypadku sukcesu zwraca wskaźnik do katalogu resource, w przypadku niepowodzenia zwraca FALSE.

Jeśli path nie jest katalogiem lub jeśli katalog nie posiada odpowiednich praw dostępu, lub gdy system plików zawiódł opendir() zwróci FALSE i wygeneruje błąd PHP E_WARNING. Można wyłączyć wyświetlanie błędów opendir() poprzez postawienie znaku '@' przed wywołaniem funkcji.

Rejestr zmian

Wersja | Opis
5.0.0 | path wspiera ftp:// URL wrapper.
4.3.0 | path może być również URL-em odnoszącym się do katalogu, jednak tylko file:// URL wrapper jest wspierany w wersji PHP 4.3.

Przykłady

Przykład #1 opendir() example

<?php
$dir = "/etc/php5/";

// Otwarcie prawidłowego katalogu i pobranie jego zawartości
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}
?>

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

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

Zobacz też:

  • is_dir() - Mówi czy nazwa_pliku jest katalogiem
  • readdir() - Czyta zawartość katalogu
  • dir() - Return an instance of the Directory class

getcwd
readdir
Funkcje katalogów


Czyta zawartość katalogu

opendir
rewinddir
Funkcje katalogów
PHP Manual

readdir

(PHP 4, PHP 5)

readdir — Czyta zawartość katalogu

Opis

string readdir ([ zasób $uchwyt_katalogu ] )

Zwraca nazwę kolejnego pliku z katalogu. Nazwy plików są zwracane w kolejności posortowanej przez system plików.

Parametry

uchwyt_katalogu

Uchwyt katalogu (zasób) otwarty wcześniej za pomocą opendir(). Jeśli uchwyt katalogu nie jest podany, przyjmowany jest ostatni wskaźnik katalogu utworzony przez opendir().

Zwracane wartości

Zwraca nazwę pliku w przypadku powodzenia lub FALSE w przypadku niepowodzenia.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 Lista wszystkich plików w katalogu

Sposób w jaki zwrócona przez readdir() wartość powinna być sprawdzona, obrazuje poniższy przykład. Należy sprawdzić czy zwrócona wartość jest równa (jest tego samego typu -- zobacz również Comparison Operators) FALSE. W przeciwnym razie plik o nazwie FALSE (jak również "0") znajdujący się w czytanym katalogu zatrzymałby pętle.

<?php
//  !== nie istniał w wersji wcześniejszej niż 4.0.0-RC2

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Files:\n";

    /* To jest poprawna metoda  */
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }

    /* To jest ZŁA metoda */
    while ($file = readdir($handle)) {
        echo "$file\n";
    }

    closedir($handle);
}
?>

Przykład #2 Lista wszystkich plików w wskazanym katalogu oprócz . i ..

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

Zobacz też:

  • is_dir() - Mówi czy nazwa_pliku jest katalogiem
  • glob() - Find pathnames matching a pattern
  • opendir() - Otwiera katalog
  • scandir() - Wypisze wszystkie pliki i katalogi z określonej lokalizacji

opendir
rewinddir
Funkcje katalogów


Ustawia wskaźnik katalogu na początek

readdir
scandir
Funkcje katalogów
PHP Manual

rewinddir

(PHP 4, PHP 5)

rewinddir — Ustawia wskaźnik katalogu na początek

Opis

void rewinddir ([ zasób $uchwyt_katalogu ] )

Ustawia wskaźnik strumienia katalogu uchwyt_katalogu na początek katalogu.

Parametry

uchwyt_katalogu

Uchwyt katalogu (zasób) otwarty wcześniej za pomocą opendir(). Jeśli uchwyt katalogu nie jest podany, przyjmowany jest ostatni wskaźnik katalogu utworzony przez opendir().

readdir
scandir
Funkcje katalogów


Wypisze wszystkie pliki i katalogi z określonej lokalizacji

rewinddir
Fileinfo
Funkcje katalogów
PHP Manual

scandir

(PHP 5)

scandir — Wypisze wszystkie pliki i katalogi z określonej lokalizacji

Opis

array scandir ( string $katalog [, int $sorting_order = 0 [, resource $context ]] )

Zwraca tablicę z wszystkimi plikami i katalogami znajdującymi się w katalog.

Parametry

katalog

Katalog, który ma być przeskanowany.

sorting_order

Domyślnie, kolejność w zwróconej tablicy jest alfabetyczna w porządku rosnącym. Jeżeli opcjonalny parametr sorting_order jest ustawiony (nie na wartość 0), wówczas kolejność jest alfabetyczna w porządku malejącym.

context

Po opis parametru context , odsyłamy do sekcji strumienii podręcznika PHP.

Zwracane wartości

Zwraca tablicę z nazwami plików w przypadku powodzenia lub FALSE w przypadku błędu. Jeżeli katalog nie jest w rzeczywistości katalogiem, wtedy zwracany jest FALSE, oraz generowane jest ostrzeżenie E_WARNING.

Przykłady

Przykład #1 Przykład użycia scandir()e

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

print_r($files1);
print_r($files2);
?>

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

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => jakiśkatalog
)
Array
(
    [0] => jakiśkatalog
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Przykład #2 Alternatywa dla scandir() w PHP 4

<?php
$dir = "/tmp";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

sort($files);

print_r($files);

rsort($files);

print_r($files);

?>

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

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => jakiśkatalog
)
Array
(
    [0] => jakiśkatalog
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

Notatki

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Zobacz też:

  • opendir() - Otwiera katalog
  • readdir() - Czyta zawartość katalogu
  • glob() - Find pathnames matching a pattern
  • is_dir() - Mówi czy nazwa_pliku jest katalogiem
  • sort() - Sortuje tablicę

rewinddir
Fileinfo
Funkcje katalogów


File Information

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Fileinfo Funkcje
    • finfo_buffer — Return information about a string buffer
    • finfo_close — Close fileinfo resource
    • finfo_file — Return information about a file
    • finfo_open — Create a new fileinfo resource
    • finfo_set_flags — Set libmagic configuration options
    • mime_content_type — Detect MIME Content-type for a file (deprecated)
scandir
Wstęp
Rozszerzenia powiązane z systemem plików


Wstęp

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

Fileinfo
Instalacja/Konfiguracja
Fileinfo


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Fileinfo


Wymagania

Before PHP 5.3.0, the magic_open library is needed to build this extension.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

This extension is enabled by default as of PHP 5.3.0. Before this time, fileinfo was a PECL extension but is no longer maintained there. However, versions prior to 5.3+ may use the » discontinued PECL extension.

Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.

The libmagic library is bundled with PHP, but includes PHP specific changes. A patch against libmagic named libmagic.patch is maintained and may be found within the PHP fileinfo extensions source.

Upgrade history of the bundled libmagic library
PHP Wersja | Updated libmagic Wersja | Notes
5.3.2 | 5.03 |
5.3.0 | 5.02 |

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

There is one resource used in Fileinfo extension: a magic database descriptor returned by finfo_open().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

FILEINFO_NONE (integer)
No special handling.
FILEINFO_SYMLINK (integer)
Follow symlinks.
FILEINFO_MIME_TYPE (integer)
Return the mime type. Available since PHP 5.3.0.
FILEINFO_MIME_ENCODING (integer)
Return the mime encoding of the file. Available since PHP 5.3.0.
FILEINFO_MIME (integer)
Return the mime type and mime encoding as defined by RFC 2045.
FILEINFO_COMPRESS (integer)
Decompress compressed files. Disabled since PHP 5.3.0 due to thread safety issues.
FILEINFO_DEVICES (integer)
Look at the contents of blocks or character special devices.
FILEINFO_CONTINUE (integer)
Return all matches, not just the first.
FILEINFO_PRESERVE_ATIME (integer)
If possible preserve the original access time.
FILEINFO_RAW (integer)
Don't translate unprintable characters to a \ooo octal representation.
Typy zasobów
Fileinfo Funkcje
Fileinfo


Fileinfo Funkcje

Spis treści

  • finfo_buffer — Return information about a string buffer
  • finfo_close — Close fileinfo resource
  • finfo_file — Return information about a file
  • finfo_open — Create a new fileinfo resource
  • finfo_set_flags — Set libmagic configuration options
  • mime_content_type — Detect MIME Content-type for a file (deprecated)
Stałe predefiniowane
finfo_buffer
Fileinfo


Return information about a string buffer

Fileinfo Funkcje
finfo_close
Fileinfo Funkcje
PHP Manual

finfo_buffer

finfo::buffer

(PHP 5 >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_buffer -- finfo::buffer — Return information about a string buffer

Opis

Styl proceduralny

string finfo_buffer ( resource $finfo , string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Styl obiektowy

string finfo::buffer ( string $string = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

This function is used to get information about binary data in a string.

Parametry

finfo

Fileinfo resource returned by finfo_open().

string

Content of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

Zwracane wartości

Returns a textual description of the string argument, or FALSE if an error occurred.

Przykłady

Przykład #1 A finfo_buffer() example

<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($_POST["script"]) . "\n";
?>

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

application/x-sh; charset=us-ascii

Zobacz też:

  • finfo_file() - Return information about a file

Fileinfo Funkcje
finfo_close
Fileinfo Funkcje


Close fileinfo resource

finfo_buffer
finfo_file
Fileinfo Funkcje
PHP Manual

finfo_close

finfo::__destruct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_close -- finfo::__destruct — Close fileinfo resource

Opis

Styl proceduralny

bool finfo_close ( resource $finfo )

Styl obiektowy

finfo::__destruct() ( void )

This function closes the resource opened by finfo_open().

Parametry

finfo

Fileinfo resource returned by finfo_open().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

finfo_buffer
finfo_file
Fileinfo Funkcje


Return information about a file

finfo_close
finfo_open
Fileinfo Funkcje
PHP Manual

finfo_file

finfo::file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_file -- finfo::file — Return information about a file

Opis

Styl proceduralny

string finfo_file ( resource $finfo , string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

Styl obiektowy

string finfo::file ( string $file_name = NULL [, int $options = FILEINFO_NONE [, resource $context = NULL ]] )

This function is used to get information about a file.

Parametry

finfo

Fileinfo resource returned by finfo_open().

file_name

Name of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

For a description of contexts, refer to Stream Funkcje.

Zwracane wartości

Returns a textual description of the contents of the filename argument, or FALSE if an error occurred.

Przykłady

Przykład #1 A finfo_file() example

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>

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

text/html
image/gif
application/vnd.ms-excel

Zobacz też:

  • finfo_buffer() - Return information about a string buffer

finfo_close
finfo_open
Fileinfo Funkcje


Create a new fileinfo resource

finfo_file
finfo_set_flags
Fileinfo Funkcje
PHP Manual

finfo_open

finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_open -- finfo::__construct — Create a new fileinfo resource

Opis

Styl proceduralny

resource finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

Styl obiektowy (constructor):

finfo::__construct() ([ int $options = FILEINFO_NONE [, string $magic_file = NULL ]] )

This function opens a magic database and returns its resource.

Parametry

options

One or disjunction of more Fileinfo constants.

magic_file

Name of a magic database file, usually something like /path/to/magic.mime. If not specified, the MAGIC environment variable is used. If this variable is not set either, /usr/share/misc/magic is used by default. A .mime and/or .mgc suffix is added if needed.

Passing NULL or an empty string will be equivalent to the default value.

Zwracane wartości

Returns a magic database resource on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Styl obiektowy

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>

Przykład #2 Styl proceduralny

<?php
$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); // return mime type ala mimetype extension

if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo finfo_file($finfo, $filename);

/* close connection */
finfo_close($finfo);
?>

Powyższy przykład wyświetli:

text/plain; charset=us-ascii

Zobacz też:

  • finfo_close() - Close fileinfo resource

finfo_file
finfo_set_flags
Fileinfo Funkcje


Set libmagic configuration options

finfo_open
mime_content_type
Fileinfo Funkcje
PHP Manual

finfo_set_flags

finfo::set_flags

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_set_flags -- finfo::set_flags — Set libmagic configuration options

Opis

Styl proceduralny

bool finfo_set_flags ( resource $finfo , int $options )

Styl obiektowy

bool finfo::set_flags ( int $options )

This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.

Parametry

finfo

Fileinfo resource returned by finfo_open().

options

One or disjunction of more Fileinfo constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

finfo_open
mime_content_type
Fileinfo Funkcje


Detect MIME Content-type for a file (deprecated)

finfo_set_flags
Filesystem
Fileinfo Funkcje
PHP Manual

mime_content_type

(PHP 4 >= 4.3.0, PHP 5)

mime_content_type — Detect MIME Content-type for a file (deprecated)

Opis

string mime_content_type ( string $filename )

Returns the MIME content type for a file as determined by using information from the magic.mime file.

Parametry

filename

Path to the tested file.

Zwracane wartości

Returns the content type in MIME format, like text/plain or application/octet-stream.

Notatki

Ostrzeżenie

This function has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.

Przykłady

Przykład #1 mime_content_type() Example

<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>

Powyższy przykład wyświetli:

image/gif
text/plain

Zobacz też:

  • Fileinfo for a replacement

finfo_set_flags
Filesystem
Fileinfo Funkcje


Filesystem

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje Systemu plików
    • basename — Zwraca nazwę pliku, będącego składową ścieżki
    • chgrp — Zmienia grupę pliku
    • chmod — Zmienia prawa dostępu do pliku
    • chown — Zmienia właściciela pliku
    • clearstatcache — Czyści bufor statusu pliku
    • copy — Kopiuje plik
    • delete — Zobacz unlink lub unset
    • dirname — Zwraca nazwę katalogu, będącego składową ścieżki
    • disk_free_space — Zwraca ilość wolnego miejsca w systemie plików lub partycji dysku
    • disk_total_space — Zwraca całkowity rozmiar systemu plików lub partycji dysku
    • diskfreespace — Alias dla disk_free_space
    • fclose — Zamyka otwarty wskaźnik pliku
    • feof — Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
    • fflush — Przekierowuje wyjście do pliku
    • fgetc — Pobiera znak ze wskaźnika pliku
    • fgetcsv — Pobiera linię ze wskanika pliku i przetwarza na pola CSV
    • fgets — Pobiera linię ze wskaźnika pliku
    • fgetss — Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
    • file_exists — Sprawdza czy plik lub katalog istnieje
    • file_get_contents — Reads entire file into a string
    • file_put_contents — Write a string to a file
    • file — Czyta całą zawartość pliku do tablicy
    • fileatime — Pobiera ostatni czas dostępu do pliku
    • filectime — Pobiera i-węzłowy czas zmiany pliku
    • filegroup — Pobiera grupę pliku
    • fileinode — Pobiera i-węzeł pliku
    • filemtime — Pobiera czas ostatniej modyfikacji pliku
    • fileowner — Pobiera właściciela pliku
    • fileperms — Pobiera prawa dostępu pliku
    • filesize — Pobiera rozmiar pliku
    • filetype — Pobiera typ pliku
    • flock — Portable advisory file locking
    • fnmatch — Match filename against a pattern
    • fopen — Otwiera plik lub URL
    • fpassthru — Output all remaining data on a file pointer
    • fputcsv — Format line as CSV and write to file pointer
    • fputs — Alias dla fwrite
    • fread — Odczyt pliku binarnie bezpieczy
    • fscanf — Przetwarza dane z pliku według formatu
    • fseek — Seeks on a file pointer
    • fstat — Pobiera informacje o pliku używając otwartego wskaźnika pliku
    • ftell — Mówi o pozycji odczyt/zapis wskaźnika pliku
    • ftruncate — Przycina plik do podanej długości
    • fwrite — Zapis pliku binarnie bezpieczny
    • glob — Find pathnames matching a pattern
    • is_dir — Mówi czy nazwa_pliku jest katalogiem
    • is_executable — Mówi czy plik jest wykonywalny
    • is_file — Mówi czy nazwa_pliku jest zwykłym plikiem
    • is_link — Mówi czy nazwa_pliku jest dowiązaniem symbolicznym
    • is_readable — Tells whether a file exists and is readable
    • is_uploaded_file — Mówi czy plik został przysłany przez HTTP POST.
    • is_writable — Tells whether the filename is writable
    • is_writeable — Alias dla is_writable
    • lchgrp — Changes group ownership of symlink
    • lchown — Changes user ownership of symlink
    • link — Tworzy dowiązanie twarde
    • linkinfo — Pobiera informacje o linku
    • lstat — Podaje informacje o pliku lub dowiązaniu symbolicznym
    • mkdir — Tworzy katalog
    • move_uploaded_file — Przenieś uploadowany plik do innej lokalizacji
    • parse_ini_file — Parse a configuration file
    • parse_ini_string — Parse a configuration string
    • pathinfo — Zwraca informacje o ścieżce do pliku
    • pclose — Zamyka wskaźnik pliku do procesu
    • popen — Otwiera wskaźnik pliku do procesu
    • readfile — Wyświetla plik
    • readlink — Zwraca cel linku symbolicznego
    • realpath_cache_get — Get realpath cache entries
    • realpath_cache_size — Get realpath cache size
    • realpath — Returns canonicalized absolute pathname
    • rename — Renames a file or directory
    • rewind — Rewind the position of a file pointer
    • rmdir — Usuwanie katalogów
    • set_file_buffer — Alias dla stream_set_write_buffer
    • stat — Gives information about a file
    • symlink — Tworzy dowiązanie symboliczne
    • tempnam — Create file with unique file name
    • tmpfile — Tworzy plik tymczasowy
    • touch — Ustawia czas modyfikacji pliku
    • umask — Changes the current umask
    • unlink — Kasowanie pliku
mime_content_type
Wstęp
Rozszerzenia powiązane z systemem plików


Wstęp

No external libraries are needed to build this extension, but if you want PHP to support LFS (large files) on Linux, then you need to have a recent glibc and you need compile PHP with the following compiler flags: -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.

Filesystem
Instalacja/Konfiguracja
Filesystem


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Filesystem


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
allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.3.4. Available since PHP 4.0.4.
allow_url_include | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 5. Available since PHP 5.2.0.
user_agent | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
default_socket_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.0.
from | "" | PHP_INI_ALL |
auto_detect_line_endings | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

allow_url_fopen boolean

This option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.

Informacja:

This option was introduced immediately after the release of version 4.0.3. For versions up to and including 4.0.3 you can only disable this feature at compile time by using the configuration switch --disable-url-fopen-wrapper.

Ostrzeżenie

On Windows versions prior to PHP 4.3.0, the following functions do not
support remote file accessing: include(),
include_once(), require(),
require_once() and the imagecreatefromXXX
functions in the GD and Image Funkcje extension.

allow_url_include boolean

This option allows the use of URL-aware fopen wrappers with the following functions: include(), include_once(), require(), require_once().

Informacja:

This setting requires allow_url_fopen to be on.

user_agent string

Define the user agent for PHP to send.

default_socket_timeout integer

Default timeout (in seconds) for socket based streams.

Informacja: This configuration option was introduced in PHP 4.3.0

from string

The email address to be used on unauthenticated FTP connections and as the value of From header for HTTP connections, when using the ftp and http wrappers, respectively.

auto_detect_line_endings boolean

When turned on, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Macintosh line-ending conventions.

This enables PHP to interoperate with Macintosh systems, but defaults to Off, as there is a very small performance penalty when detecting the EOL conventions for the first line, and also because people using carriage-returns as item separators under Unix systems would experience non-backwards-compatible behaviour.

Informacja: This configuration option was introduced in PHP 4.3.0

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

The file system uses streams as their resource type. Streams are documented in its own reference chapter, Streams.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

GLOB_BRACE (integer)
GLOB_ONLYDIR (integer)
GLOB_MARK (integer)
GLOB_NOSORT (integer)
GLOB_NOCHECK (integer)
GLOB_NOESCAPE (integer)
GLOB_AVAILABLE_FLAGS (integer)
PATHINFO_DIRNAME (integer)
PATHINFO_BASENAME (integer)
PATHINFO_EXTENSION (integer)
PATHINFO_FILENAME (integer)
Od PHP 5.2.0.
FILE_USE_INCLUDE_PATH (integer)
Poszukuje nazwy_pliku w include_path (od PHP 5).
FILE_NO_DEFAULT_CONTEXT (integer)
FILE_APPEND (integer)
Dodaje treść do istniejącego pliku.
FILE_IGNORE_NEW_LINES (integer)
Usuwa znaki końca lini (EOL) (od PHP 5).
FILE_SKIP_EMPTY_LINES (integer)
Pomija puste linie (od PHP 5).
FILE_BINARY (integer)

Tryb binarny (od PHP 5.2.7).

Informacja:

Ta stała niczego nie zmienia. Jest ona dostępna tylko w celu zgodności z poprzednimi wersjami.

FILE_TEXT (integer)

Tryb tekstowy (od PHP 5.2.7).

Informacja:

Ta stała niczego nie zmienia. Jest ona dostępna tylko w celu zgodności z poprzednimi wersjami.

INI_SCANNER_NORMAL (integer)
Standardowy tryb skanowania INI (od PHP 5.3).
INI_SCANNER_RAW (integer)
Surowy tryb skanowania INI (od PHP 5.3).
FNM_NOESCAPE (integer)
Wyłączenie sekwencji unikowych odwrotnym ukośnikiem.
FNM_PATHNAME (integer)
Ukośnik w łańcuchu znaków jedynie pasuje do ukośnika z podanego wzorca.
FNM_PERIOD (integer)
Poprzedzająca kropka w łańcuchu znaków musi dokładnie pasować do kropki w podanym wzorcu.
FNM_CASEFOLD (integer)
Dopasowanie bez rozróżniania znaków. Część rozszeżenia GNU.
Typy zasobów
Funkcje Systemu plików
Filesystem


Funkcje Systemu plików

Zobacz też:

Związane z tym działem funkcje, znajdziesz w rozdziale Katalog i Wykonywanie programów.

Listę wraz z opisem różnych wrapperów URL, które mogą zostać użyte jako zdalne pliki, znajdziesz tu Supported Protocols and Wrappers.

Spis treści

  • basename — Zwraca nazwę pliku, będącego składową ścieżki
  • chgrp — Zmienia grupę pliku
  • chmod — Zmienia prawa dostępu do pliku
  • chown — Zmienia właściciela pliku
  • clearstatcache — Czyści bufor statusu pliku
  • copy — Kopiuje plik
  • delete — Zobacz unlink lub unset
  • dirname — Zwraca nazwę katalogu, będącego składową ścieżki
  • disk_free_space — Zwraca ilość wolnego miejsca w systemie plików lub partycji dysku
  • disk_total_space — Zwraca całkowity rozmiar systemu plików lub partycji dysku
  • diskfreespace — Alias dla disk_free_space
  • fclose — Zamyka otwarty wskaźnik pliku
  • feof — Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
  • fflush — Przekierowuje wyjście do pliku
  • fgetc — Pobiera znak ze wskaźnika pliku
  • fgetcsv — Pobiera linię ze wskanika pliku i przetwarza na pola CSV
  • fgets — Pobiera linię ze wskaźnika pliku
  • fgetss — Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
  • file_exists — Sprawdza czy plik lub katalog istnieje
  • file_get_contents — Reads entire file into a string
  • file_put_contents — Write a string to a file
  • file — Czyta całą zawartość pliku do tablicy
  • fileatime — Pobiera ostatni czas dostępu do pliku
  • filectime — Pobiera i-węzłowy czas zmiany pliku
  • filegroup — Pobiera grupę pliku
  • fileinode — Pobiera i-węzeł pliku
  • filemtime — Pobiera czas ostatniej modyfikacji pliku
  • fileowner — Pobiera właściciela pliku
  • fileperms — Pobiera prawa dostępu pliku
  • filesize — Pobiera rozmiar pliku
  • filetype — Pobiera typ pliku
  • flock — Portable advisory file locking
  • fnmatch — Match filename against a pattern
  • fopen — Otwiera plik lub URL
  • fpassthru — Output all remaining data on a file pointer
  • fputcsv — Format line as CSV and write to file pointer
  • fputs — Alias dla fwrite
  • fread — Odczyt pliku binarnie bezpieczy
  • fscanf — Przetwarza dane z pliku według formatu
  • fseek — Seeks on a file pointer
  • fstat — Pobiera informacje o pliku używając otwartego wskaźnika pliku
  • ftell — Mówi o pozycji odczyt/zapis wskaźnika pliku
  • ftruncate — Przycina plik do podanej długości
  • fwrite — Zapis pliku binarnie bezpieczny
  • glob — Find pathnames matching a pattern
  • is_dir — Mówi czy nazwa_pliku jest katalogiem
  • is_executable — Mówi czy plik jest wykonywalny
  • is_file — Mówi czy nazwa_pliku jest zwykłym plikiem
  • is_link — Mówi czy nazwa_pliku jest dowiązaniem symbolicznym
  • is_readable — Tells whether a file exists and is readable
  • is_uploaded_file — Mówi czy plik został przysłany przez HTTP POST.
  • is_writable — Tells whether the filename is writable
  • is_writeable — Alias dla is_writable
  • lchgrp — Changes group ownership of symlink
  • lchown — Changes user ownership of symlink
  • link — Tworzy dowiązanie twarde
  • linkinfo — Pobiera informacje o linku
  • lstat — Podaje informacje o pliku lub dowiązaniu symbolicznym
  • mkdir — Tworzy katalog
  • move_uploaded_file — Przenieś uploadowany plik do innej lokalizacji
  • parse_ini_file — Parse a configuration file
  • parse_ini_string — Parse a configuration string
  • pathinfo — Zwraca informacje o ścieżce do pliku
  • pclose — Zamyka wskaźnik pliku do procesu
  • popen — Otwiera wskaźnik pliku do procesu
  • readfile — Wyświetla plik
  • readlink — Zwraca cel linku symbolicznego
  • realpath_cache_get — Get realpath cache entries
  • realpath_cache_size — Get realpath cache size
  • realpath — Returns canonicalized absolute pathname
  • rename — Renames a file or directory
  • rewind — Rewind the position of a file pointer
  • rmdir — Usuwanie katalogów
  • set_file_buffer — Alias dla stream_set_write_buffer
  • stat — Gives information about a file
  • symlink — Tworzy dowiązanie symboliczne
  • tempnam — Create file with unique file name
  • tmpfile — Tworzy plik tymczasowy
  • touch — Ustawia czas modyfikacji pliku
  • umask — Changes the current umask
  • unlink — Kasowanie pliku
Stałe predefiniowane
basename
Filesystem


Zwraca nazwę pliku, będącego składową ścieżki

Funkcje Systemu plików
chgrp
Funkcje Systemu plików
PHP Manual

basename

(PHP 4, PHP 5)

basename — Zwraca nazwę pliku, będącego składową ścieżki

Opis

string basename ( string $ścieżka [, string $przyrostek ] )

Z podanego łańcucha zawierającego ścieżkę do pliku, funkcja zwraca samą nazwę pliku.

Parametry

ścieżka

Ścieżka

W Windows jako separator katalogów używany jest znak slash (/) i backslash (\). W innych środowiskach jest to slash (/).

przyrostek

Jeśli plik kończy się przyrostkiem to także zostanie on obcięty.

Zwracane wartości

Zwraca nazwę pliku z podanej ścieżki.

Rejestr zmian

Wersja | Opis
4.1.0 | Został dodany Parametr przyrostek

Przykłady

Przykład #1 Przykład basename()

<?php
echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL;
echo "2) ".basename("/etc/passwd").PHP_EOL;
echo "3) ".basename("/etc/").PHP_EOL;
echo "4) ".basename(".").PHP_EOL;
echo "5) ".basename("/");
?>

Powyższy przykład wyświetli:

1) sudoers
2) passwd
3) etc
4) .
5)

Notatki

Informacja:

basename() działa naiwnie na wejściowym łańcuchu znaków i nie jest świadoma bieżącego systemu plików lub składników ścieżki takich jak "..".

Informacja:

basename() jest świadoma locale, aby widzieć prawidłowe basename ze ścieżek z wielobajtowymi znakami, musi zostać ustawione pasujące locale za pomocą funkcji setlocale().

Zobacz też:

  • dirname() - Zwraca nazwę katalogu, będącego składową ścieżki
  • pathinfo() - Zwraca informacje o ścieżce do pliku

Funkcje Systemu plików
chgrp
Funkcje Systemu plików


Zmienia grupę pliku

basename
chmod
Funkcje Systemu plików
PHP Manual

chgrp

(PHP 4, PHP 5)

chgrp — Zmienia grupę pliku

Opis

bool chgrp ( string $nazwa_pliku , mixed $grupa )

Próbuje zmienić grupę pliku podanego w parametrze nazwa_pliku na wybraną parametrem grupa

Tylko super użytkownik może zmienić dowolnie grupę pliku; inni użytkownicy mogą zmienić grupę pliku na dowolną grupę, której członkiem jest ten użytkownik.

Parametry

nazwa_pliku

Ścieżka do pliku.

grupa

Numer lub nazwa grupy.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Zmiana grupy pliku

<?php
$nazwa_pliku = 'wspoldzielony_plik.txt';
$format = "%s's Identyfikator grupy @ %s: %d\n";
printf($format, $nazwa_pliku, date('r'), filegroup($nazwa_pliku));
chgrp($filename, 8);
clearstatcache(); // nie buforuj wyników filegroup()
printf($format, $nazwa_pliku, date('r'), filegroup($nazwa_pliku));
?>

Notatki

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Zobacz też:

  • chown() - Zmienia właściciela pliku
  • chmod() - Zmienia prawa dostępu do pliku

basename
chmod
Funkcje Systemu plików


Zmienia prawa dostępu do pliku

chgrp
chown
Funkcje Systemu plików
PHP Manual

chmod

(PHP 4, PHP 5)

chmod — Zmienia prawa dostępu do pliku

Opis

bool chmod ( string $nazwa_pliku , int $prawa )

Próbuje dokonać zmiany praw pliku na podane w prawa.

Parametry

nazwa_pliku

Ścieżka do pliku.

prawa

Pamiętaj, że parametr prawa nie jest automatycznie zastępowany wartością oktalną (ósemkową), więc łańcuchy (takie jak "g+w") nie będą poprawnie interpretowane. Aby, zapewnić poprawność operacji musisz parametr prawa poprzedzić prefixem zero (0):

<?php
chmod("/somedir/somefile", 755);   // dziesiętnie; prawdopodobnie nieprawidłowo
chmod("/somedir/somefile", "u+rwx,go+rx"); // łańcuch; nieprawidłowo
chmod("/somedir/somefile", 0755);  // ósemkowo; poprawna wartość dla praw
?>

Parametr prawa zawiera trzy cyfry w systemie ósemkowym określające prawa dostępu dla właściciela, grupy do której on należy oraz wszystkich innych. Jedna cyfra może zostać obliczona poprzez dodanie do siebie potrzebnych uprawnień. Cyfra 1 oznacza nadanie praw do wykonania, cyfra 2 oznacza, że plik będzie zapisywalny, cyfra 4 oznacza, że plik będzie można odczytać. Dodając te cyfry określamy potrzebne uprawnienia. Więcej o prawach w systemie Unix można przeczytać w 'man 1 chmod' i 'man 2 chmod'.

<?php
// Odczyt i zapis dla właściciela, żadnych praw dla innych
chmod("/katalog/plik", 0600);

// Odczyt i zapis dla właściciela, odczyt dla wszystkich
chmod("/katalog/plik", 0644);

// Wszystkie prawa dla właściciela, odczyt i wykonanie dla innych
chmod("/katalog/plik", 0755);

// Wszystkie prawa dla właściciela, odczyt i wykonanie dla grupy właściciela
chmod("/katalog/plik", 0750);
?>

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

Bieżący użytkownik to użytkownik pod którym działa PHP. Prawdpodobnie nie jest to ten sam użytkownik, którego używasz normalnie przy dostępie do shell'a lub FTP. W większości systemów, prawa mogą być zmienione jedynie przez właściciela pliku.

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Informacja:

Kiedy włączony jest tryb bezpieczny, PHP sprawdza czy pliki lub katalogi na których mają zostać wykonane operacje posiadają taki sam UID (właściciela) jak skrypt, który jest wykonywany. W dodatku, nie możesz ustawić SUI, SGID i bitów lepkości (sticky bits).

Zobacz też:

  • chown() - Zmienia właściciela pliku
  • chgrp() - Zmienia grupę pliku
  • fileperms() - Pobiera prawa dostępu pliku
  • stat() - Gives information about a file

chgrp
chown
Funkcje Systemu plików


Zmienia właściciela pliku

chmod
clearstatcache
Funkcje Systemu plików
PHP Manual

chown

(PHP 4, PHP 5)

chown — Zmienia właściciela pliku

Opis

bool chown ( string $nazwa_pliku , mixed $użytkownik )

Próbuje dokonać zmiany właściciela pliku nazwa_pliku na użytkownika podanego w parametrze użytkownik. Tylko superużytkownik może zmienić właściciela pliku.

Parametry

nazwa_pliku

Ścieżka do pliku.

użytkownik

Numer ID lub nazwa użytkownika.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Proste użycie chown()

<?php

// Nazwa pliku i użytkownika
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "root";

// Ustaw właściciela pliku
chown($path, $user_name);

// Check the result
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));

?>

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

Array
(
     [name] => root
     [passwd] => x
     [uid] => 0
     [gid] => 0
     [gecos] => root
     [dir] => /root
     [shell] => /bin/bash
)

Notatki

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Zobacz też:

  • chmod() - Zmienia prawa dostępu do pliku

chmod
clearstatcache
Funkcje Systemu plików


Czyści bufor statusu pliku

chown
copy
Funkcje Systemu plików
PHP Manual

clearstatcache

(PHP 4, PHP 5)

clearstatcache — Czyści bufor statusu pliku

Opis

void clearstatcache ([ bool $clear_realpath_cache = false [, string $nazwa_pliku ]] )

Kiedy używasz stat(), lstat() lub dowolnej z funkcji wymienionej niżej, PHP buforuje informacje, zwrócone przez te funkcje w celu zapewnienia większej wydajności. Jednakże, w kilku przypadkach, możesz chcieć wyczyścić zbuforowane informacje. W przypadku, gdy ten sam plik jest sprawdzany wiele razy w tym samym skrypcie i istnieje obawa, że plik ten zostanie zmieniony lub usunięty podczas pracy skryptu, możesz wywołać czyszczenie bufora stanu. W takim przypadku, możesz użyć funkcji clearstatcache() do wyczyszczenia informacji o pliku zbuforowanej przez PHP.

Weź pod uwagę, że PHP nie buforuje informacji o nie istniejących plikach. Jeśli wywołasz file_exists() na pliku, który nie istnieje zostanie zwrócone FALSE dopóki nie stworzysz tego pliku. Jeśli go utworzysz funkcja zwróci TRUE nawet jeśli go później skasujesz. Jednakże unlink() czyści automatycznie bufor.

Informacja:

Ta funkcja buforuje informacje o podanych nazwach plików, więc potrzebujesz wywoływać clearstatcache() jeśli wykonujesz wiele operacji na tym samym pliku i potrzebujesz, aby informacje o tym pliku nie były buforowane.

Dotyczy funkcji stat(),
lstat(),
file_exists(),
is_writable(),
is_readable(),
is_executable(),
is_file(),
is_dir(),
is_link(),
filectime(),
fileatime(),
filemtime(),
fileinode(),
filegroup(),
fileowner(),
filesize(),
filetype() i
fileperms().

Parametry

clear_realpath_cache

Czy czyścić bufor o prawdziej ścieżce, czy nie.

nazwa_pliku

Czyści bufor o prawdziwej ścieżce dla podanego pliku; tylko jeśli clear_realpath_cache jest TRUE.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
5.3.0 | Dodano opcjonalne parametry clear_realpath_cache i filename.

Przykłady

Przykład #1 Przykład clearstatcache()

<?php
$file = 'output_log.txt';

function get_owner($file)
{
    $stat = stat($file);
    $user = posix_getpwuid($stat['uid']);
    return $user['name'];
}

$format = "UID @ %s: %s\n";

printf($format, date('r'), get_owner($file));

chown($file, 'ross');
printf($format, date('r'), get_owner($file));

clearstatcache();
printf($format, date('r'), get_owner($file));
?>

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

UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross

chown
copy
Funkcje Systemu plików


Kopiuje plik

clearstatcache
delete
Funkcje Systemu plików
PHP Manual

copy

(PHP 4, PHP 5)

copy — Kopiuje plik

Opis

bool copy ( string $źródło , string $przeznaczenie [, resource $kontekst ] )

Kopiuje plik z źródło do przeznaczenie.

Jeśli chcesz przenieść plik, użyj funkcji rename().

Parametry

źródło

Ścieżka do pliku źródłowego.

przeznaczenie

Ścieżka docelowa. Jeśli przeznaczenie jest URLem, operacja kopiowania może się niepowieść, jeśli wrapper nie obsługuje nadpisywania istniejących plików.

Ostrzeżenie

Jeśli, docelowy plik istnieje to zostanie nadpisany.

kontekst

Prawidłowo utworzony zasób kontekstowy za pomocą stream_context_create().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.0 | Dodano obsługę kontekstu.
4.3.0 | Zarówno źródło i przeznaczenie mogą być URLami jeśli "wrappery fopen" zostały włączone. Zobacz fopen() w celu poznania więcej szczegółów.

Przykłady

Przykład #1 copy() przykład

<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
      echo "kopiowanie pliku $file, nie powiodło się\n";
}
?>

Zobacz też:

  • move_uploaded_file() - Przenieś uploadowany plik do innej lokalizacji
  • rename() - Renames a file or directory
  • Rozdział podręcznika dotyczącyobsługi wgrywania plików

clearstatcache
delete
Funkcje Systemu plików


Zobacz unlink lub unset

copy
dirname
Funkcje Systemu plików
PHP Manual

delete

delete — Zobacz unlink() lub unset()

Opis

void delete ( void )

To jest ślepy wpis aby zadowolić ludzi którzy szukają unlink() lub unset() w nie właściwym miejscu.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • unlink() - Kasowanie pliku
  • unset() - Unset a given variable

copy
dirname
Funkcje Systemu plików


Zwraca nazwę katalogu, będącego składową ścieżki

delete
disk_free_space
Funkcje Systemu plików
PHP Manual

dirname

(PHP 4, PHP 5)

dirname — Zwraca nazwę katalogu, będącego składową ścieżki

Opis

string dirname ( string $ścieżka )

Z podanego łańcucha zawierającego ścieżkę do pliku, funkcja ta zwróci nazwę nadrzędnego katalogu.

Parametry

path

A path.

W Windows jako separator katalogu używany jest znak slash (/) i backslash (\). W innych środowiskach jest to slash (/).

Zwracane wartości

Zwraca nazwę katalogu. Jeśli, w ścieżce nie znajdują się ukośniki to zwracana jest kropka ('.'), oznaczająca bieżący katalog. W innym przypadku, zwracany jest łańcuch znaków ścieżka z usuniętymi wszystkimi koncowymi /komponentami.

Rejestr zmian

Wersja | Opis
5.0.0 | dirname() od teraz jest binarnie bezpieczna
4.0.3 | dirname() poprawiono kompatybilność z POSIX.

Przykłady

Przykład #1 Przykład dirname()

<?php
echo "1) " . dirname("/etc/passwd") . PHP_EOL; // 1) /etc
echo "2) " . dirname("/etc/") . PHP_EOL; // 2) / (lub \ pod Windows)
echo "3) " . dirname("."); // 3) .
?>

Notatki

Informacja:

dirname() działa naiwnie na wejściowym łańcuchu znaków i nie jest świadoma bieżącego systemu plików lub składników ścieżki takich jak "..".

Informacja:

dirname() jest świadoma locale, aby widzieć prawidłową nazwę katalogu z ścieżek z wielobajtowymi znakami, musi zostać ustawione pasujące locale za pomocą funkcji setlocale().

Informacja:

Od PHP 4.3.0, często otrzymasz ukośnik lub kropkę z dirname() w sytuacjach gdzie starsza funkcjonalność mogła dać pusty łańcuch znaków.

Sprawdź poniższy przykład zmian:

<?php

//przed PHP 4.3.0
dirname('c:/'); // zwraca '.'

//po PHP 4.3.0
dirname('c:/x'); // zwraca 'c:\'
dirname('c:/Temp/x'); // zwraca 'c:/Temp'
dirname('/x'); // zwraca '\'

?>

Zobacz też:

  • basename() - Zwraca nazwę pliku, będącego składową ścieżki
  • pathinfo() - Zwraca informacje o ścieżce do pliku
  • realpath() - Returns canonicalized absolute pathname

delete
disk_free_space
Funkcje Systemu plików


Zwraca ilość wolnego miejsca w systemie plików lub partycji dysku

dirname
disk_total_space
Funkcje Systemu plików
PHP Manual

disk_free_space

(PHP 4 >= 4.1.0, PHP 5)

disk_free_space — Zwraca ilość wolnego miejsca w systemie plików lub partycji dysku

Opis

float disk_free_space ( string $katalog )

Podając łańcuch zawierający katalog, funkcja zwróci liczbę dostępnych bajtów w odpowiadającym mu systemie plików lub partycji dysku.

Parametry

katalog

Katalog w systemie plików lub partycji dysku.

Informacja:

Po podaniu nazwy pliku zamiast katalogu zachowanie funkcji jest nieprzewidywalne i może się różnić w zależności od systemu operacyjnego i wersji PHP.

Zwracane wartości

Zwraca liczbę dostępnych bajtów jako liczbę zmiennoprzecinkową. lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Przykład disk_free_space()

<?php
// $df zawiera liczbę dostępnych bajtów w "/"
$df = disk_free_space("/");

// Pod Windows:
$df_c = disk_free_space("C:");
$df_d = disk_free_space("D:");
?>

Notatki

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Zobacz też:

  • disk_total_space() - Zwraca całkowity rozmiar systemu plików lub partycji dysku

dirname
disk_total_space
Funkcje Systemu plików


Zwraca całkowity rozmiar systemu plików lub partycji dysku

disk_free_space
diskfreespace
Funkcje Systemu plików
PHP Manual

disk_total_space

(PHP 4 >= 4.1.0, PHP 5)

disk_total_space — Zwraca całkowity rozmiar systemu plików lub partycji dysku

Opis

float disk_total_space ( string $katalog )

Podając łańcuch zawierający katalog, funkcja ta zwróci całkowitą liczbę bajtów w odpowiadającym mu systemie plików lub partycji dysku.

Parametry

katalog

Katalog w systemie plików lub partycji dysku.

Zwracane wartości

Zwraca całkowitą liczbę bajtów jako liczbę zmiennoprzecinkową lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Przykład disk_total_space()

<?php
// $ds zawiera całkowita liczbę dostepnych bajtów on "/"
$ds = disk_total_space("/");

// Pod Windows:
$ds = disk_total_space("C:");
$ds = disk_total_space("D:");
?>

Notatki

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Zobacz też:

  • disk_free_space() - Zwraca ilość wolnego miejsca w systemie plików lub partycji dysku

disk_free_space
diskfreespace
Funkcje Systemu plików


Alias dla disk_free_space

disk_total_space
fclose
Funkcje Systemu plików
PHP Manual

diskfreespace

(PHP 4, PHP 5)

diskfreespace — Alias dla disk_free_space()

Opis

Ta funkcja jest aliasem dla: disk_free_space().

disk_total_space
fclose
Funkcje Systemu plików


Zamyka otwarty wskaźnik pliku

diskfreespace
feof
Funkcje Systemu plików
PHP Manual

fclose

(PHP 4, PHP 5)

fclose — Zamyka otwarty wskaźnik pliku

Opis

bool fclose ( resource $uchwyt )

Zamyka wskaźnik pliku uchwyt.

Parametry

uchwyt

Wskaźnik pliku musi byc prawidłowy i musi wskazywać na plik poprawnie otworzony przez fopen() lub fsockopen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Prosty przykład fclose()

<?php

$uchwyt = fopen('jakis_plik.txt', 'r');

fclose($uchwyt);

?>

Zobacz też:

  • fopen() - Otwiera plik lub URL
  • fsockopen() - Open Internet or Unix domain socket connection

diskfreespace
feof
Funkcje Systemu plików


Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)

fclose
fflush
Funkcje Systemu plików
PHP Manual

feof

(PHP 4, PHP 5)

feof — Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)

Opis

bool feof ( resource $uchwyt )

Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF).

Parametry

uchwyt

Wskaźnik na plik musi być poprawny i musi wskazywać na plik pomyślnie otwarty przez funkcję fopen() lub fsockopen() (a jednocześnie nie zamknięty jeszcze przez fclose()).

Zwracane wartości

Zwraca TRUE jeśli wskaźnik pliku jest na EOF lub gdy zdarzy się błąd (także timeout połączenia socket'owego); w przeciwnym wypadku zwraca FALSE.

Notatki

Ostrzeżenie

Jeśli połączenie otworzone za pomocą fsockopen() nie zostanie zamknięte przez serwer, feof() zawiesi się. Aby to obejść zobacz poniższy przykład:

Przykład #1 Obsługa limitu czasu w feof()

<?php
function safe_feof($fp, &$start = NULL) {
 $start = microtime(true);

 return feof($fp);
}

/* Zakładając, że $fp jest wcześniej otworzone przez fsockopen() */

$start = NULL;
$timeout = ini_get('default_socket_timeout');

while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
 /* Uchwyt */
}
?>

Ostrzeżenie

Jeśli podano nieprawidłowy wskaźnik pliku to możesz uzyskać nieskończoną pętle, ponieważ feof() w przypadku błędu zwraca TRUE..

Przykład #2 feof() przykład z nieprawidłowym wskaźnikiem pliku

<?php
// jeśli plik nie może zostać odczytany lub nie istnieje funkcja fopen zwróci FALSE
$file = @fopen("nie_isniejacy_plik", "r");

// FALSE z fopen spowoduje ostrzeżenie oraz wystąpi tu nieskończona pętla
while (!feof($file)) {
}

fclose($file);
?>

fclose
fflush
Funkcje Systemu plików


Przekierowuje wyjście do pliku

feof
fgetc
Funkcje Systemu plików
PHP Manual

fflush

(PHP 4 >= 4.0.1, PHP 5)

fflush — Przekierowuje wyjście do pliku

Opis

bool fflush ( resource $uchwyt )

Ta funkcja wymusza zapis całego zbuforowanego wyjścia do zasobu wskazywanego przez plik uchwyt.

Parametry

uchwyt

Wskaźnik na plik musi być poprawny i musi wskazywać na plik pomyślnie otwarty przez funkcję fopen() lub fsockopen() (a jednocześnie nie zamknięty jeszcze przez fclose()).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład zapisu do pliku używając fflush()

<?php
$nazwa_pliku = 'bar.txt';

$plik = fopen($nazwa_pliku, 'r+');
rewind($plik);
fwrite($plik, 'Foo');
fflush($plik);
ftruncate($plik, ftell($plik));
fclose($plik);
?>

Zobacz też:

  • clearstatcache() - Czyści bufor statusu pliku
  • fwrite() - Zapis pliku binarnie bezpieczny

feof
fgetc
Funkcje Systemu plików


Pobiera znak ze wskaźnika pliku

fflush
fgetcsv
Funkcje Systemu plików
PHP Manual

fgetc

(PHP 4, PHP 5)

fgetc — Pobiera znak ze wskaźnika pliku

Opis

string fgetc ( resource $uchwyt )

Pobiera znak ze wskaźnika pliku.

Parametry

uchwyt

Wskaźnik na plik musi być poprawny i musi wskazywać na plik pomyślnie otwarty przez funkcję fopen() lub fsockopen() (a jednocześnie nie zamknięty jeszcze przez fclose()).

Zwracane wartości

Zwraca łańcuch znaków zawierający pojedynczy znak odczytany z pliku wskazanego przez uchwyt. Zwraca FALSE lub EOF.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 Przykład fgetc()

<?php
$fp = fopen('plik.txt', 'r');
if (!$fp) {
    echo 'Nie można otworzyć plik.txt';
}
while (false !== ($char = fgetc($fp))) {
    echo "$char\n";
}
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • fread() - Odczyt pliku binarnie bezpieczy
  • fopen() - Otwiera plik lub URL
  • popen() - Otwiera wskaźnik pliku do procesu
  • fsockopen() - Open Internet or Unix domain socket connection
  • fgets() - Pobiera linię ze wskaźnika pliku

fflush
fgetcsv
Funkcje Systemu plików


Pobiera linię ze wskanika pliku i przetwarza na pola CSV

fgetc
fgets
Funkcje Systemu plików
PHP Manual

fgetcsv

(PHP 4, PHP 5)

fgetcsv — Pobiera linię ze wskanika pliku i przetwarza na pola CSV

Opis

array fgetcsv ( resource $uchwyt [, int $długość = 0 [, string $delimiter = ',' [, string $ogranicznik = '"' [, string $ucieczka = '\\' ]]]] )

Działa podobnie do fgets() tylko, że fgetcsv() przetwarza odczytaną linię na pola w formacie CSV i zwraca tablicę zawierającą odczytane pola.

Parametry

uchwyt

Ważny uchwyt pliku, poprawnie otwartego za pomocą fopen(), popen() lub fsockopen().

długość

Musi być większy niż najdłuższa linia (w znakach), która znajduje się w pliku CSV (wliczając znaki końca lini). Stał się opcjonalny w PHP 5. Opuszczenie tego parametru (lub ustawienie go na 0 w PHP 5.0.4 lub późniejszym) spowoduje, że maksymalna długość lini nie jest limitowana, co jest nieznacznie wolniejsze.

delimiter

Ustawia delimeter (tylko jeden znak) pól.

ogranicznik

Ustawia znak ograniczający pole.

ucieczka

Ustawia znak ucieczki (tylko jeden znak). Domyślnie jest to odwrotny ukośnik.

Zwracane wartości

Zwraca indeksowaną tablicę zawierającą odczytane pola.

Informacja:

Pusta linia w pliku CSV zostanie zwrócona jako tablica składająca się z pojedynczego pola null i nie zostanie potraktowana jako błąd.

Informacja: Jeśli PHP niewłaściwie rozpoznaje znaki końca linii podczas odczytu plików stworzonych lub znajdujących się na komputerach Macintosh, problem może rozwiązać włączenie dyrektywy konfiguracyjnej auto_detect_line_endings .

fgetcsv() zwraca NULL jeśli dostarczono niewłaściwy uchwyt lub FALSE w przypadku innego błędu, włączając w to koniec pliku.

Rejestr zmian

Wersja | Opis
5.3.0 | Dodano parametr ucieczka
4.3.5 | fgetcsv() stał się bezpiecznym dla danych binarnych
4.3.0 | Dodano parametr ogranicznik

Przykłady

Przykład #1 fgetcsv() przykład - Odczyt i wyświetlenie całej zawartości pliku CSV

<?php
$row = 1;
if (($uchwyt = fopen ("test.csv","r")) !== FALSE) {
while (($data = fgetcsv($uchwyt, 1000, ",")) !== FALSE)  {
    $num = count($data);
    echo "<p> $num pól w lini $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
    echo $data[$c] . "<br />\n";
    }
}
fclose ($uchwyt);
}
?>

Notatki

Informacja:

Ustawienia lokale są brane pod uwagę przez tę funkcję. Jeśli LANG jest ustawione na np. en_US.UTF-8, pliki z jedno bajtowym kodowaniem zostaną nieprawidłowo odczytane przez funkcję.

Zobacz też:

  • str_getcsv() - Parse a CSV string into an array
  • explode() - Split a string by string
  • file() - Czyta całą zawartość pliku do tablicy
  • pack() - Pack data into binary string
  • fputcsv() - Format line as CSV and write to file pointer

fgetc
fgets
Funkcje Systemu plików


Pobiera linię ze wskaźnika pliku

fgetcsv
fgetss
Funkcje Systemu plików
PHP Manual

fgets

(PHP 4, PHP 5)

fgets — Pobiera linię ze wskaźnika pliku

Opis

string fgets ( resource $uchwyt [, int $długość ] )

Pobiera linię ze wskaźnika pliku.

Parametry

uchwyt

Wskaźnik na plik musi być poprawny i musi wskazywać na plik pomyślnie otwarty przez funkcję fopen() lub fsockopen() (a jednocześnie nie zamknięty jeszcze przez fclose()).

długość

Kończy czytanie gdy przeczytano długość - 1 bajtów, na znaku nowej linii (który jest dołączony do zwracanej wartości), lub na końcu pliku (EOF) (cokolwiek wystąpi wcześniej). Jeśli, nie określono długości, czytanie ze strumienia będzie kontynuowane do czasu osiągnięcia końca linii.

Informacja:

Do wersji PHP 4.3.0, pominięcie powodowało ustawienie długości na 1024. Jeśli większość linii w pliku jest dłuższa od 8KB, dużo efektywniejsze jest podanie maksymalnej długości linii.

Zwracane wartości

Zwraca łańcuch znaków o długości - 1 bajtów odczytanych ze wskaźnika pliku wskazanego przez uchwyt. Jeśli nie ma więcej danych do przeczytania ze wskaźnika pliku to zwraca FALSE

W przypadku błędu zwraca FALSE.

Rejestr zmian

Wersja | Opis
4.3.0 | fgets() stał się bezpieczny dla danych binarnych
4.2.0 | Parametr długość stał się opcjonalny.

Przykłady

Przykład #1 Oczyt pliku linia po linii

<?php
$uchwyt = @fopen("/tmp/plik_wejsciowy.txt", "r");
if ($uchwyt) {
    while (($bufor = fgets($uchwyt, 4096)) !== false) {
        echo $bufor;
    }
    if (!feof($uchwyt)) {
        echo "Błąd: niespodziewany błąd fgets()\n";
    }
    fclose($uchwyt);
}
?>

Notatki

Informacja: Jeśli PHP niewłaściwie rozpoznaje znaki końca linii podczas odczytu plików stworzonych lub znajdujących się na komputerach Macintosh, problem może rozwiązać włączenie dyrektywy konfiguracyjnej auto_detect_line_endings .

Informacja:

Osoby przyzwyczajone do semantyki 'C' powinny zauważyć różnicę w sposobie zwracania EOF przez fgets().

Zobacz też:

  • fgetss() - Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
  • fread() - Odczyt pliku binarnie bezpieczy
  • fgetc() - Pobiera znak ze wskaźnika pliku
  • stream_get_line() - Gets line from stream resource up to a given delimiter
  • fopen() - Otwiera plik lub URL
  • popen() - Otwiera wskaźnik pliku do procesu
  • fsockopen() - Open Internet or Unix domain socket connection
  • stream_set_timeout() - Set timeout period on a stream

fgetcsv
fgetss
Funkcje Systemu plików


Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML

fgets
file_exists
Funkcje Systemu plików
PHP Manual

fgetss

(PHP 4, PHP 5)

fgetss — Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML

Opis

string fgetss ( resource $uchwyt [, int $długość [, string $dozwolone_tagi ]] )

Działa identycznie jak fgets(), oprócz tego że fgetss() próbuje usunąć wszystkie bajty NUL, znaczniki HTML i PHP z tekstu, który przeczyta.

Parametry

uchwyt

Wskaźnik na plik musi być poprawny i musi wskazywać na plik pomyślnie otwarty przez funkcję fopen() lub fsockopen() (a jednocześnie nie zamknięty jeszcze przez fclose()).

długość

Długość danych do pobrania.

dozwolone_tagi

Możesz użyć opcjonalnego trzeciego parametru do określenia które znaczniki nie powinny być usunięte.

Zwracane wartości

Zwraca łańcuch znaków o długości - 1 bajtów odczytanych ze wskaźnika pliku wskazanego przez uchwyt, pozbawionego całego kodu HTML i PHP.

W przypadku błędu zwraca FALSE.

Rejestr zmian

Wersja | Opis
5.0.0 | Parametr długość jest opcjonalny.

Przykład #1 Czytanie pliku PHP linia po linii

<?php
$str = <<<EOD
<html><body>
 <p>Witaj! Dziś jest <?php echo(date('jS')); ?> z <?= date('F'); ?>.</p>
</body></html>
Tekst po za blokiem HTML.
EOD;
file_put_contents('przyklad.php', $str);

$uchwyt = @fopen("przyklad.php", "r");
if ($uchwyt) {
    while (!feof($uchwyt)) {
        $bufor = fgetss($uchwyt, 4096);
        echo $bufor;
    }
    fclose($uchwyt);
}
?>

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

 Witaj! Dziś jest  z .

Tekst po za blokiem HTML.

Notatki

Informacja: Jeśli PHP niewłaściwie rozpoznaje znaki końca linii podczas odczytu plików stworzonych lub znajdujących się na komputerach Macintosh, problem może rozwiązać włączenie dyrektywy konfiguracyjnej auto_detect_line_endings .

Zobacz też:

  • fgets() - Pobiera linię ze wskaźnika pliku
  • fopen() - Otwiera plik lub URL
  • popen() - Otwiera wskaźnik pliku do procesu
  • fsockopen() - Open Internet or Unix domain socket connection
  • strip_tags() - Strip HTML and PHP tags from a string

fgets
file_exists
Funkcje Systemu plików


Sprawdza czy plik lub katalog istnieje

fgetss
file_get_contents
Funkcje Systemu plików
PHP Manual

file_exists

(PHP 4, PHP 5)

file_exists — Sprawdza czy plik lub katalog istnieje

Opis

bool file_exists ( string $nazwa_pliku )

Sprawdza czy plik lub katalog istnieje.

Parametry

nazwa_pliku

Ścieżka do pliku lub katalogu.

Pod Windows, użyj //nazwa_komputera/udział/nazwa_pliku lub \\nazwa_komputera\udział\nazwa_pliku aby sprawdzić pliki dla sieciowych udziałów.

Zwracane wartości

Zwraca TRUE jeśli plik lub katalog określony w nazwa_pliku istnieje; FALSE w przeciwnym wypadku.

Informacja:

Ta funkcja zwróci FALSE dla linków symbolicznych wskazujących na nie istniejące pliki.

Ostrzeżenie

Funkcja zwraca FALSE dla plików niedostępnych z powodu restrykcji trybu bezpiecznego. Jednak te pliki ciągle mogą być inkludowane jeśli znajdują się w safe_mode_include_dir.

Informacja:

Sprawdzanie dokonywane jest na prawdziwych UID/GID, a nie efektywnych.

Informacja: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Przykłady

Przykład #1 Sprawdzanie czy plik istnieje

<?php
$nazwa_pliku = '/sciezka/do/pliku.txt';

if (file_exists($nazwa_pliku)) {
    echo "Plik $nazwa_pliku istnieje";
} else {
    echo "Plik $nazwa_pliku nie istnieje";
}
?>

Błędy/Wyjątki

W przypadku niepowodzenia jest emitowany E_WARNING.

Notatki

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Zobacz też:

  • is_readable() - Tells whether a file exists and is readable
  • is_writable() - Tells whether the filename is writable
  • is_file() - Mówi czy nazwa_pliku jest zwykłym plikiem
  • file() - Czyta całą zawartość pliku do tablicy

fgetss
file_get_contents
Funkcje Systemu plików


Reads entire file into a string

file_exists
file_put_contents
Funkcje Systemu plików
PHP Manual

file_get_contents

(PHP 4 >= 4.3.0, PHP 5)

file_get_contents — Reads entire file into a string

Opis

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Informacja:

If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().

Parametry

filename

Name of the file to read.

use_include_path

Informacja:

As of PHP 5 the FILE_USE_INCLUDE_PATH can be used to trigger include path search.

context

A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL.

offset

The offset where the reading starts on the original stream.

Seeking (offset) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.

maxlen

Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.

Zwracane wartości

The function returns the read data lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

An E_WARNING level error is generated if either maxlength is less than zero, or if offset exceeds the length of the stream.

Przykłady

Przykład #1 Get and output the source of the homepage of a website

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

Przykład #2 Searching within the include_path

<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

Przykład #3 Reading a section of a file

<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>

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

string(14) "lle Bjori Ro"

Przykład #4 Using stream contexts

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>

Rejestr zmian

Wersja | Opis
5.1.0 | Added the offset and maxlen parameters.
5.0.0 | Added context support.

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Ostrzeżenie

Nawiązując połączenie przez SSL, serwer Microsoft IIS narusza reguły protokołu przez zamknięcie połączenia bez wysłania wskaźnika close_notify. Po przesłaniu całości danych PHP zgłosi to jako "SSL: Fatal Protocol Error". Aby obejść ten błąd, wystarczy obniżyć poziom raportowania błędów error_reporting, tak aby nie były wyświetlane ostrzeżenia. PHP 4.3.7 i nowsze wersje same wykrywają błąd serwera IIS przy otwieraniu strumienia https:// i za pomocą nakładki i pomijają ostrzeżenia. Używając funkcji fsockopen() do otwarcia gniazda ssl:// programista sam musi zadbać o wyłączenie ostrzeżeń.

Zobacz też:

  • file() - Czyta całą zawartość pliku do tablicy
  • fgets() - Pobiera linię ze wskaźnika pliku
  • fread() - Odczyt pliku binarnie bezpieczy
  • readfile() - Wyświetla plik
  • file_put_contents() - Write a string to a file
  • stream_get_contents() - Reads remainder of a stream into a string
  • stream_context_create() - Create a streams context
  • $http_response_header

file_exists
file_put_contents
Funkcje Systemu plików


Write a string to a file

file_get_contents
file
Funkcje Systemu plików
PHP Manual

file_put_contents

(PHP 5)

file_put_contents — Write a string to a file

Opis

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

Parametry

filename

Path to the file where to write the data.

data

The data to write. Can be either a string, an array or a stream resource.

If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

You can also specify the data parameter as a single dimension array. This is equivalent to file_put_contents($filename, implode('', $array)).

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Available flags
Flag | Description
FILE_USE_INCLUDE_PATH | Search for filename in the include directory. See include_path for more information.
FILE_APPEND | If file filename already exists, append the data to the file instead of overwriting it.
LOCK_EX | Acquire an exclusive lock on the file while proceeding to the writing.

context

A valid context resource created with stream_context_create().

Zwracane wartości

The function returns the number of bytes that were written to the file, or FALSE on failure.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 Simple usage example

<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>

Przykład #2 Using flags

<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

Rejestr zmian

Wersja | Opis
5.0.0 | Added context support
5.1.0 | Added support for LOCK_EX and the ability to pass a stream resource to the data parameter

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Zobacz też:

  • fopen() - Otwiera plik lub URL
  • fwrite() - Zapis pliku binarnie bezpieczny
  • file_get_contents() - Reads entire file into a string
  • stream_context_create() - Create a streams context

file_get_contents
file
Funkcje Systemu plików


Czyta całą zawartość pliku do tablicy

file_put_contents
fileatime
Funkcje Systemu plików
PHP Manual

file

(PHP 4, PHP 5)

file — Czyta całą zawartość pliku do tablicy

Opis

array file ( string $nazwa_pliku [, int $flagi [, resource $kontekst ]] )

Działa podobnie do file_get_contents(), tylko że file() zwraca plik w tablicy. Każdy element tablicy odpowiada linii w pliku. Elementy tablicy zawierają znak nowej linii. W przypadku błędu, file() zwraca FALSE.

Opcjonalny parametr flagi może być jedną lub więcej, z następujących stałych:

FILE_USE_INCLUDE_PATH
Poszukuj pliku w include_path.
FILE_IGNORE_NEW_LINES
Nie dodawaj nowej lini na na końcu każdego elementu tablicy.
FILE_SKIP_EMPTY_LINES
Pomiń puste linie.

Informacja:

Przed PHP 5.0.0 parametr flagi jedynie ukrywał include_path i był włączany przez 1.

<?php
// Pobierz plik do tablicy. W tym przykładzie poprzez HTTP pobierzemy
// źródło HTML z URL
$lines = file('http://www.example.com/');
// Za pomocą pętli przeglądamy naszą tablicę i pokazujemy źródło strony w postaci
// źródła HTML oraz numery linii.
  foreach ($lines as $line_num => $line) {
      echo "Linia #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Kolejny przyklad pozwala pobrać stronę i umieścić ją w łańcuchu znaków  Zobacz także file_get_contents().
$html = implode ('', file ('http://www.example.com/'));
?>

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Informacja:

Każda linia w wynikowej tabeli będzie zawierać znak(i) końca linii chyba, że jest użyte FILE_IGNORE_NEW_LINES, jeśli nie chcesz ich musisz uzyć rtrim().

Informacja: Jeśli PHP niewłaściwie rozpoznaje znaki końca linii podczas odczytu plików stworzonych lub znajdujących się na komputerach Macintosh, problem może rozwiązać włączenie dyrektywy konfiguracyjnej auto_detect_line_endings .

Informacja:

W PHP 4.3.0 możesz użyć file_get_contents() aby zwrócić zawartość pliku do łańcucha.

W PHP 4.3.0 file() stał się binarnie bezpieczny.

Informacja: Obsługa kontekstów została dodana w PHP 5.0.0. Opis kontekstów znajduje się w rozdziale Stream Funkcje.

Ostrzeżenie

Nawiązując połączenie przez SSL, serwer Microsoft IIS narusza reguły protokołu przez zamknięcie połączenia bez wysłania wskaźnika close_notify. Po przesłaniu całości danych PHP zgłosi to jako "SSL: Fatal Protocol Error". Aby obejść ten błąd, wystarczy obniżyć poziom raportowania błędów error_reporting, tak aby nie były wyświetlane ostrzeżenia. PHP 4.3.7 i nowsze wersje same wykrywają błąd serwera IIS przy otwieraniu strumienia https:// i za pomocą nakładki i pomijają ostrzeżenia. Używając funkcji fsockopen() do otwarcia gniazda ssl:// programista sam musi zadbać o wyłączenie ostrzeżeń.

Patrz także: readfile(),
fopen(), fsockopen(),
popen(), file_get_contents(),
include() i
stream_context_create().

file_put_contents
fileatime
Funkcje Systemu plików


Pobiera ostatni czas dostępu do pliku

file
filectime
Funkcje Systemu plików
PHP Manual

fileatime

(PHP 4, PHP 5)

fileatime — Pobiera ostatni czas dostępu do pliku

Opis

int fileatime ( string $nazwa_pliku )

Zwraca czas, kiedy nastąpił ostatni dostęp do pliku lub FALSE w przypadku błędu. Czas jest zwracany w postaci unix'owego znacznika czasu.

Notka: Czas dostępu do pliku przypuszczalnie zmienia się zawsze kiedy bloki danych pliku są odczytywane. To może kosztować utratę wydajności aplikacji, które regularnie korzystają z wielu plików lub katalogów. Niektóre unix'owe systemy plików mogą być montowane z wyłączonym uaktualnianiem czasu dostępu, aby podnieść wydajność takich aplikacji; USENETowy katalog roboczy wiadomości jest dobrym przykładem. Na takich systemach plików ta funkcja będzie bezużyteczna.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Przykład #1 fileatime() przykład

<?php

// przykładowy wynik: ostatni dostep do pliku: jakisplik.txt December 29 2002 22:16:23.

$filename = 'jakisplik.txt';
if (file_exists($filename)) {
   echo "ostatni dostep do pliku: $filename " . date("F d Y H:i:s.", fileatime($filename));
}

?>

Ta funkcja nie działa na zdalnych plikach; sprawdzany plik musi być dostępny przez system plików serwera.

file
filectime
Funkcje Systemu plików


Pobiera i-węzłowy czas zmiany pliku

fileatime
filegroup
Funkcje Systemu plików
PHP Manual

filectime

(PHP 4, PHP 5)

filectime — Pobiera i-węzłowy czas zmiany pliku

Opis

int filectime ( string $nazwa_pliku )

Zwraca czas, ostatniej zmiany pliku lub FALSE w przypadku błędu. Czas jest zwracany w postaci unix'owego znacznika czasu.

Uwaga: W większości Unixowych systemów plików, plik ulega zmianie wtedy kiedy dane jego i-węzła zmieniają się; tj. kiedy prawa dostępu, właściciel, grupa lub inne metadane z i-węzłą są nadpisywane. Patrz także: filemtime() (którą powinnieneś użyć, gdy chcesz stworzyć stopkę strony "Ostatnia Modyfikacja") i fileatime().

Zauważ także, że w niektórych tekstach Unixowych ctime pliku jest określany jako będący czasem stworzenia pliku. To jest nieprawidłowe. Nie ma pojęcia czasu stworzenia dla plików Unixowych większości Unixowych systemów plików.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Przykład #1 filectime() przykład

<?php

// wyświetli np. jakisplik.txt został ostatnio zmieniony : December 29 2002 22:16:23.

$filename = 'jakisplik.txt';
if (file_exists($filename)) {
  echo "$filename został ostatnio zmieniony : " . date("F d Y H:i:s.", filectime($filename));
}
?>

Patrz także: filemtime()

fileatime
filegroup
Funkcje Systemu plików


Pobiera grupę pliku

filectime
fileinode
Funkcje Systemu plików
PHP Manual

filegroup

(PHP 4, PHP 5)

filegroup — Pobiera grupę pliku

Opis

int filegroup ( string $nazwa_pliku )

Zwraca identyfikator grupy pliku lub FALSE w przypadku błędu. Identyfikator grupy zwracany jest w postaci numerycznej, użyj posix_getgrgid() aby rozwinąć go w nazwę grupy. W przypadku niepowodzenia zwracany jest FALSE przy ustawionym poziomie błędów na E_WARNING.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Informacja: Patrz także fileowner() i safe_mode_gid.

filectime
fileinode
Funkcje Systemu plików


Pobiera i-węzeł pliku

filegroup
filemtime
Funkcje Systemu plików
PHP Manual

fileinode

(PHP 4, PHP 5)

fileinode — Pobiera i-węzeł pliku

Opis

int fileinode ( string $nazwa_pliku )

Zwraca numer i-węzła pliku lub FALSE w przypadku błędu.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Patrz także: stat().

filegroup
filemtime
Funkcje Systemu plików


Pobiera czas ostatniej modyfikacji pliku

fileinode
fileowner
Funkcje Systemu plików
PHP Manual

filemtime

(PHP 4, PHP 5)

filemtime — Pobiera czas ostatniej modyfikacji pliku

Opis

int filemtime ( string $nazwa_pliku )

Ta funkcja zwraca czas kiedy bloki danych pliku zostały zapisane, to jest, czas kiedy zawartość pliku została zmieniona.

Parametry

nazwa_pliku

Ścieżka do pliku.

Zwracane wartości

Zwraca czas, kiedy plik był ostatnio modyfikowany lub FALSE w przypadku niepowodzenia. Czas jest zwracany w postaci unix'owego znacznika czasu, który jest odpowiedni dla funkcji date().

Przykłady

Przykład #1 filemtime() przykład

<?php
// wyświetli np. jakisplik.txt został ostatnio zmodyfikowny : December 29 2002 22:16:23.

$filename = 'jakisplik.txt';
if (file_exists($filename)) {
  echo "$filename został ostatnio zmodyfikowny : " . date ("F d Y H:i:s.", filemtime($filename));
}
?>

Błędy/Wyjątki

W przypadku niepowodzenia jest emitowany E_WARNING.

Notatki

Informacja:

Proszę zauważyć, że informacja o czasie dostępu może się różnić w zależności od systemu plików.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Zobacz też:

  • filectime() - Pobiera i-węzłowy czas zmiany pliku
  • stat() - Gives information about a file
  • touch() - Ustawia czas modyfikacji pliku
  • getlastmod() - Gets time of last page modification

fileinode
fileowner
Funkcje Systemu plików


Pobiera właściciela pliku

filemtime
fileperms
Funkcje Systemu plików
PHP Manual

fileowner

(PHP 4, PHP 5)

fileowner — Pobiera właściciela pliku

Opis

int fileowner ( string $nazwa_pliku )

Zwraca identyfikator użytkownika, który jest właścicielem pliku, lub FALSE w przypadku błędu. Identyfikator użytkownika zwracany jest w postaci numerycznej, użyj posix_getpwuid() aby rozwinąć go w nazwę użytkownika.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Patrz także: stat()

filemtime
fileperms
Funkcje Systemu plików


Pobiera prawa dostępu pliku

fileowner
filesize
Funkcje Systemu plików
PHP Manual

fileperms

(PHP 4, PHP 5)

fileperms — Pobiera prawa dostępu pliku

Opis

int fileperms ( string $nazwa_pliku )

Zwraca prawa dostępu pliku, lub FALSE w przypadku błędu.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Przykład #1 Wyświetlanie uprawnień w postaci ósemkowej

<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>

To powino wyświetlić:

1777
0644

Przykład #2 Wyświetlanie wszystkich uprawnień

<?php
$perms = fileperms('/etc/passwd');

if (($perms & 0xC000) == 0xC000) {
  // Gniazdo (socket)
  $info = 's';
} elseif (($perms & 0xA000) == 0xA000) {
  // Link symboliczny
  $info = 'l';
} elseif (($perms & 0x8000) == 0x8000) {
  // Zwykły plik
  $info = '-';
} elseif (($perms & 0x6000) == 0x6000) {
  // Urządzenie blokowe
  $info = 'b';
} elseif (($perms & 0x4000) == 0x4000) {
  // Katalog
  $info = 'd';
} elseif (($perms & 0x2000) == 0x2000) {
  // Urządzenie znakowe
  $info = 'c';
} elseif (($perms & 0x1000) == 0x1000) {
  // Potok (FIFO)
  $info = 'p';
} else {
  // Nieznane
   $info = 'u';
}

// Właściciel
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
         (($perms & 0x0800) ? 's' : 'x' ) :
         (($perms & 0x0800) ? 'S' : '-'));

// Grupa
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
         (($perms & 0x0400) ? 's' : 'x' ) :
         (($perms & 0x0400) ? 'S' : '-'));

// Świat
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
         (($perms & 0x0200) ? 't' : 'x' ) :
         (($perms & 0x0200) ? 'T' : '-'));

echo $info;
?>

To powino wyświetlić:

-rw-r--r--

Patrz także: is_readable(), i stat()

fileowner
filesize
Funkcje Systemu plików


Pobiera rozmiar pliku

fileperms
filetype
Funkcje Systemu plików
PHP Manual

filesize

(PHP 4, PHP 5)

filesize — Pobiera rozmiar pliku

Opis

int filesize ( string $nazwa_pliku )

Zwraca rozmiar pliku w bajtach, lub FALSE (oraz zostanie wygenerowany błąd na poziomie E_WARNING) w przypadku błędu.

Informacja: Ponieważ PHPowy typ integer jest oznaczony (ang. signed, dopuszcza liczby ujemne i dodatnie) i wiele platform używa 32 bitowego integera, filesize() może zwrócić nieoczekiwane wyniki dla plików większych od 2 GB. Dla plików o rozmiarze pomiędzy 2 GB, a 4 GB można zwykle przezwyciężyć to używając sprintf("%u", filesize($plik)).

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Przykład #1 filesize() przykład

<?php

// wyświetli np. jakisplik.txt: 1024 bajtów

$filename = 'jakisplik.txt';
echo $filename . ': ' . filesize($filename) . ' bajtów';

?>

Patrz także: file_exists()

fileperms
filetype
Funkcje Systemu plików


Pobiera typ pliku

filesize
flock
Funkcje Systemu plików
PHP Manual

filetype

(PHP 4, PHP 5)

filetype — Pobiera typ pliku

Opis

string filetype ( string $nazwa_pliku )

Zwraca typ pliku. Możliwe wartości to fifo, char, dir, block, link, file i unknown.

Zwraca FALSE jeśli wystąpił błąd. filetype() również utworzy wiadomość E_NOTICE jeśli wywołanie stat się nie powiedzie lub gdy plik ma tym nieznany (unknown).

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Przykład #1 filetype() przykład

<?php

echo filetype('/etc/passwd');  // plik
echo filetype('/etc/');        // katalog

?>

Patrz także: is_dir(), is_file(),
is_link(), file_exists(),
stat() i mime_content_type().

filesize
flock
Funkcje Systemu plików


Portable advisory file locking

filetype
fnmatch
Funkcje Systemu plików
PHP Manual

flock

(PHP 4, PHP 5)

flock — Portable advisory file locking

Opis

bool flock ( resource $handle , int $operation [, int &$wouldblock ] )

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished).

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled (on non-Windows platforms) with the LOCK_NB option documented below.

Parametry

handle

Wskaźnik do systemu plików typu resource jest zazwyczaj tworzony poprzez funkcję fopen().

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).

It is also possible to add LOCK_NB as a bitmask to one of the above operations if you don't want flock() to block while locking. (not supported on Windows)

wouldblock

The optional third argument is set to TRUE if the lock would block (EWOULDBLOCK errno condition). (not supported on Windows)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.2 | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.
4.0.1 | The LOCK_XXX constants were added. Prior to that you must use 1 for LOCK_SH, 2 for LOCK_EX, 3 for LOCK_UN and 4 for LOCK_NB

Przykłady

Przykład #1 flock() example

<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
    ftruncate($fp, 0); // truncate file
    fwrite($fp, "Write something here\n");
    flock($fp, LOCK_UN); // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?>

Przykład #2 flock() using the LOCK_NB option

<?php
$fp = fopen('/tmp/lock.txt', 'r+');

/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
    echo 'Unable to obtain lock';
    exit(-1);
}

/* ... */

fclose($fp);
?>

Notatki

Informacja:

flock() uses mandatory locking instead of advisory locking on Windows. Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is, if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux, the file system will also need to be mounted with the mand option for this to work.

Informacja:

Because flock() requires a file pointer, you may have to use a special lock file to protect access to a file that you intend to truncate by opening it in write mode (with a "w" or "w+" argument to fopen()).

Informacja:

May only be used on file pointers returned by fopen() for local files, or file pointers pointing to userspace streams that implement the streamWrapper::stream_lock() method.

Ostrzeżenie

Assigning another value to handle argument in subsequent code will release the lock.

Ostrzeżenie

On some operating systems flock() is implemented at the process level. When using a multithreaded server API like ISAPI you may not be able to rely on flock() to protect files against other PHP scripts running in parallel threads of the same server instance!

flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under this environments (this is especially true for Windows 98 users).

filetype
fnmatch
Funkcje Systemu plików


Match filename against a pattern

flock
fopen
Funkcje Systemu plików
PHP Manual

fnmatch

(PHP 4 >= 4.3.0, PHP 5)

fnmatch — Match filename against a pattern

Opis

bool fnmatch ( string $pattern , string $string [, int $flags = 0 ] )

fnmatch() checks if the passed string would match the given shell wildcard pattern.

Parametry

pattern

The shell wildcard pattern.

string

The tested string. This function is especially useful for filenames, but may also be used on regular strings.

The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of preg_match() for frontend search expression input may be way more convenient for non-programming users.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

A list of possible flags for fnmatch()
Flag | Description
FNM_NOESCAPE | Disable backslash escaping.
FNM_PATHNAME | Slash in string only matches slash in the given pattern.
FNM_PERIOD | Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD | Caseless match. Part of the GNU extension.

Zwracane wartości

Returns TRUE if there is a match, FALSE otherwise.

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.

Przykłady

Przykład #1 Checking a color name against a shell wildcard pattern

<?php
if (fnmatch("*gr[ae]y", $color)) {
  echo "some form of gray ...";
}
?>

Notatki

Ostrzeżenie

For now this function is not available on non-POSIX compliant systems.

Zobacz też:

  • glob() - Find pathnames matching a pattern
  • preg_match() - Perform a regular expression match
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

flock
fopen
Funkcje Systemu plików


Otwiera plik lub URL

fnmatch
fpassthru
Funkcje Systemu plików
PHP Manual

fopen

(PHP 4, PHP 5)

fopen — Otwiera plik lub URL

Opis

resource fopen ( string $nazwa_pliku , string $tryb [, bool $użyj_include_path [, resource $kontekst ]] )

fopen() wiąże nazwany zasób, określony przez nazwa_pliku, do strumienia.

Parametry

nazwa_pliku

Jeśli nazwa_pliku jest w postaci "schemat://...", to przypuszczalnie jest to URL i PHP szuka protokołu obsługi (także zwanego wrapper'em) dla tego schematu. Jeśli nie zarejestrowano żadnego wrapper'a dla tego protokołu, PHP wyemituje notatkę, aby pomóc Tobie w wyśledzeniu potencajalnego problemu w Twoim skrypcie następnie będzie kontynuować z podanym nazwa_pliku traktując go jako zwykły plik.

Jeśli PHP zdecyduje, że nazwa_pliku określa lokalny plik, wtedy spróbuje otworzyć strumień na tym pliku. Plik musi być dostępny dla PHP, więc musisz zapewnić prawa dostępu do pliku pozwalające na taką operację. Jeśli masz włączone tryb bezpieczny lub open_basedir mogą mieć zastosowanie dodatkowe restrykcje.

Jeśli PHP zdecyduje, że nazwa_pliku określa zarejestrowany protokół i ten protokół jest zarejestowany jako sieciowy URL, PHP sprawdzi allow_url_fopen czy jest włączone. Jeśli jest wyłączone (off), PHP wyświetli ostrzeżenie i wywołanie fopen zakończy się niepowodzeniem.

Informacja:

Listę obsługiwanych protokołów możesz znaleźć w Supported Protocols and Wrappers. Niektóre protokoły (również określane przez wrappery obsługują kontekst lub/i opcje php.ini. Odwołaj się do konkretnej strony protokołu aby uzyskać listę opcji jakie mogą zostać ustawione (np. php.ini wartość user_agent używana przez wrapper http).

Na platformie Windows, dbaj aby wstawiać znaki ucieczki (escape) przed wszystkimi lewymi ukośnikami (backslash) użytymi w ścieżce do pliku lub używać ukośników (slash).

<?php
     $handle = fopen("c:\\data\\info.txt", "r");
     ?>

tryb

Parametr tryb określa rodzaj dostępu jaki wymagasz do strumienia. Może być dowolny z następujących:

Lista możliwych trybów dla fopen() używając tryb
tryb | Opis
'r' | Otwiera tylko do odczytu; umieszcza wskaźnik pliku na jego początku.
'r+' | Otwiera do odczytu i zapisu; umieszcza wskaźnik pliku na jego początku.
'w' | Otwiera tylko do zapisu; umieszcza wskaźnik pliku na jego początku i obcina plik do zerowej długości. Jeśli plik nie istnieje to próbuje go utworzyć.
'w+' | Otwiera do odczytu i zapisu; umieszcza wskaźnik pliku na jego początku i obcina plik do zerowej długości. Jeśli plik nie istnieje to próbuje go utworzyć.
'a' | Otwiera tylko do zapisu; umieszcza wskaźnik pliku na jego końcu. Jeśli plik nie istnieje to próbuje go utworzyć.
'a+' | Otwiera do odczytu i zapisu; umieszcza wskaźnik pliku na jego końcu. Jeśli plik nie istnieje to próbuje go utworzyć.
'x' | Tworzy i otwiera plik tylko do zapisu; umieszcza wskaźnik pliku na jego początku. Jeśli plik juz istnieje, wywołanie fopen() nie powiedzie się, zwróci FALSE i wygeneruje błąd na poziomie E_WARNING. Jeśli plik nie istnieje, spróbuje go utworzyć. To jest równoważne z określeniem flag O_EXCL|O_CREAT stosowanym w wywołaniu systemowym open(2).
'x+' | Tworzy i otwiera plik odczytu i zapisu; umieszcza wskaźnik pliku na jego początku. Jeśli plik juz istnieje, wywołanie fopen() nie powiedzie się, zwróci FALSE i wygeneruje błąd na poziomie E_WARNING. Jeśli plik nie istnieje, spróbuje go utworzyć. To jest równoważne z okresleniem flag O_EXCL|O_CREAT stosowanym w wywołaniu systemowym open(2).

Informacja:

Różne rodziny systemów operacyjnych stosuja rózne konwencje końca lini. Kiedy zapisujesz plik tekstowy i chcesz wstawić łamanie lini, musisz użyć poprawnych dla twojego systemu operacyjnego znak(ów) końca lini. Systemy bazujące na Uniksie używają \n jako znaku końca lini, systemy bazujące na Windowsie używają \r\n jako znaków końca lini, a systemy Macintosh używają \r jako znak końca lini.

Jeśli użyjesz nieprawidłowego końca lini do zapisu pliku, możesz zaobserwować, w innych aplikacjach otwierając ten plik, że "wygląda on zabawnie".

Windows oferuje flagę ('t') konwertującą tryb tekstowy, która przezroczyście przekłada \n na \r\n kiedy pracujesz z plikiem. Dla kontrastu, możesz także uzyć 'b' aby wymusić tryb binarny, wtedy nie będzie konwertować twoich danych. Aby użyć tych flag, wstaw 'b' lub 't' jako ostatni znak w parametrze tryb.

Domyślnie tryb konwersji zależy od SAPI i wersji PHP jakiej używasz, więc namawiamy aby zawsze podawać stosowną flage w celu przenośności. Powinieneś użyć trybu 't' jeśli pracujesz ze zwykłymi plikami tekstowymi (plain-text)i używasz \n do ograniczenia konców lini w twoim skrypcie, ale wymagasz aby twój plik był czytelny w aplikacjach takich jak notatnik. Powinieneś uzyć 'b' w każdym innym przypadku.

Jeśli nie podasz flagi 'b' kiedy pracujesz na binarnych plikach, możesz doświadczyć dziwnych problemów z twoimi danymi, włączając uszkodzone pliki graficzne i dziwne problemy ze znakami \r\n.

Informacja:

Dla przenośności, bardzo zalecane jest użycie zawsze flagi 'b' kiedy otwierasz pliki za pomocą fopen().

Informacja:

Ponownie, dla przenośności, jest również bardzo zalecane abyś, przepisał swój kod, który używa lub polega na trybie 't' tak aby używał poprawnego końca lini oraz trybu 'b'.

użyj_include_path

Opcjonalny trzeci parametr użyj_include_path może być ustawiony na '1' lub TRUE jeśli chcesz szukać pliku także w include_path.

kontekst

Informacja: Obsługa kontekstów została dodana w PHP 5.0.0. Opis kontekstów znajduje się w rozdziale Stream Funkcje.

Zwracane wartości

Zwraca wskaźnik pliku do zasobu w przypadku sukcesu lub FALSE przy błędzie.

Błędy/Wyjątki

Jeśli otwieranie się nie powiedzie, funkcja wygeneruje błąd na poziomie E_WARNING. Możesz użyć @ aby zatuszować to ostrzeżenie.

Rejestr zmian

Wersja | Opis
4.3.2 | Od PHP 4.3.2 domyślny tryb ustawiany jest na binarny, dla wszystkich platform, które rozróżniają tryby binarne i tekstowe. Jeśli masz problemy ze skryptem po aktualizacji, spróbuj użyć flagi 't' jako obejście dopóki nie uczynisz Twojego skryptu bardziej przenośnym jak opisano niżej.
4.3.2 | Dodano opcje 'x' i 'x+'

Przykłady

Przykład #1 fopen() przykłady

<?php
$handle = fopen("/home/rasmus/plik.txt", "r");
$handle = fopen("/home/rasmus/plik.gif", "wb");
$handle = fopen("http://www.przyklad.com/", "r");
$handle = fopen("ftp://uzytkownik:haslo@przyklad.com/jakisplik.txt", "w");
?>

Notatki

Ostrzeżenie

Nawiązując połączenie przez SSL, serwer Microsoft IIS narusza reguły protokołu przez zamknięcie połączenia bez wysłania wskaźnika close_notify. Po przesłaniu całości danych PHP zgłosi to jako "SSL: Fatal Protocol Error". Aby obejść ten błąd, wystarczy obniżyć poziom raportowania błędów error_reporting, tak aby nie były wyświetlane ostrzeżenia. PHP 4.3.7 i nowsze wersje same wykrywają błąd serwera IIS przy otwieraniu strumienia https:// i za pomocą nakładki i pomijają ostrzeżenia. Używając funkcji fsockopen() do otwarcia gniazda ssl:// programista sam musi zadbać o wyłączenie ostrzeżeń.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza czy katalog, na którym zostaną wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Jeśli doświadczasz problemów z odczytem lub zapisywaniem do plików i używasz PHP w postaci modułu serwera, pamiętaj, żeby się upewnić, że pliki i katalogi, których używasz są dostępne dla procesu serwera.

Zobacz też:

  • Supported Protocols and Wrappers
  • fclose() - Zamyka otwarty wskaźnik pliku
  • fgets() - Pobiera linię ze wskaźnika pliku
  • fread() - Odczyt pliku binarnie bezpieczy
  • fwrite() - Zapis pliku binarnie bezpieczny
  • fsockopen() - Open Internet or Unix domain socket connection
  • file() - Czyta całą zawartość pliku do tablicy
  • file_exists() - Sprawdza czy plik lub katalog istnieje
  • is_readable() - Tells whether a file exists and is readable
  • stream_set_timeout() - Set timeout period on a stream
  • popen() - Otwiera wskaźnik pliku do procesu
  • stream_context_create() - Create a streams context

fnmatch
fpassthru
Funkcje Systemu plików


Output all remaining data on a file pointer

fopen
fputcsv
Funkcje Systemu plików
PHP Manual

fpassthru

(PHP 4, PHP 5)

fpassthru — Output all remaining data on a file pointer

Opis

int fpassthru ( resource $handle )

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readfile(), which saves you the fopen() call.

Parametry

handle

Wskaźnik na plik musi być poprawny i musi wskazywać na plik pomyślnie otwarty przez funkcję fopen() lub fsockopen() (a jednocześnie nie zamknięty jeszcze przez fclose()).

Zwracane wartości

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle and passed through to the output.

Przykłady

Przykład #1 Using fpassthru() with binary files

<?php

// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;

?>

Notatki

Informacja:

When using fpassthru() on a binary file on Windows systems, you should make sure to open the file in binary mode by appending a b to the mode used in the call to fopen().

You are encouraged to use the b flag when dealing with binary files, even if your system does not require it, so that your scripts will be more portable.

Zobacz też:

  • readfile() - Wyświetla plik
  • fopen() - Otwiera plik lub URL
  • popen() - Otwiera wskaźnik pliku do procesu
  • fsockopen() - Open Internet or Unix domain socket connection

fopen
fputcsv
Funkcje Systemu plików


Format line as CSV and write to file pointer

fpassthru
fputs
Funkcje Systemu plików
PHP Manual

fputcsv

(PHP 5 >= 5.1.0)

fputcsv — Format line as CSV and write to file pointer

Opis

int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] )

fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle.

Parametry

handle

Wskaźnik na plik musi być poprawny i musi wskazywać na plik pomyślnie otwarty przez funkcję fopen() lub fsockopen() (a jednocześnie nie zamknięty jeszcze przez fclose()).

fields

An array of values.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

Zwracane wartości

Returns the length of the written string lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 fputcsv() example

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

Notatki

Informacja: Jeśli PHP niewłaściwie rozpoznaje znaki końca linii podczas odczytu plików stworzonych lub znajdujących się na komputerach Macintosh, problem może rozwiązać włączenie dyrektywy konfiguracyjnej auto_detect_line_endings .

Zobacz też:

  • fgetcsv() - Pobiera linię ze wskanika pliku i przetwarza na pola CSV

fpassthru
fputs
Funkcje Systemu plików


Alias dla fwrite

fputcsv
fread
Funkcje Systemu plików
PHP Manual

fputs

(PHP 4, PHP 5)

fputs — Alias dla fwrite()

Opis

Ta funkcja jest aliasem dla: fwrite().

fputcsv
fread
Funkcje Systemu plików


Odczyt pliku binarnie bezpieczy

fputs
fscanf
Funkcje Systemu plików
PHP Manual

fread

(PHP 4, PHP 5)

fread — Odczyt pliku binarnie bezpieczy

Opis

string fread ( resource $uchwyt , int $długość )

fread() odczytuje do długość bajtów ze wskaźnika pliku określonego przez uchwyt. Czytanie kończy się gdy odczytano długość bajtów, osiągnięty został koniec pliku (EOF), (dla sieciowych strumieni), kiedy pakiet stanie się dostępny lub (po otwarciu strumienia z przestrzeni użytkownika) kiedy 8192 bajtów zostanie odczytanych, cokolwiek nastąpi pierwsze.

Zwraca łańcuch znaków lub FALSE w przypadku błędu.

<?php
// pobierz zawartość pliku do łańcucha
$nazwa_pliku = "/usr/local/jakis.txt";
$uchwyt = fopen($nazwa_pliku, "r");
$tresc = fread($uchwyt, filesize($nazwa_pliku));
fclose($uchwyt);
?>

Ostrzeżenie

W systemach, które rozróżniają pliki binarne i tekstowe (np. Windows) plik musi zostać otworzony z 'b' dołączonym do parametru tryb fopen().

<?php
$nazwa_pliku = "c:\\pliki\\jakisobrazek.gif";
$uchwyt = fopen($nazwa_pliku, "rb");
$tresc = fread($uchwyt, filesize($nazwa_pliku));
fclose($uchwyt);
?>

Ostrzeżenie

Kiedy następuje odczyt z czegokolwiek innego niż zwykłe lokalne pliki, takich jak strumienie zwrócone gdy odczytujesz zdalne pliki lub z popen() i fsockopen(), odczyt zakończy się po tym jak pakiet jest dostępny. To znaczy, że powinieneś gromadzić dane razem z kawałków jak pokazano na poniższych przykładach.

<?php
// dla PHP 5 i nowszych
$uchwyt = fopen("http://www.example.com/", "rb");
$tresc = stream_get_contents($uchwyt);
fclose($uchwyt);
?>

<?php
$uchwyt = fopen("http://www.przykladowy.com/", "rb");
$tresc = '';
while (!feof($uchwyt)) {
  $tresc .= fread($uchwyt, 8192);
}
fclose($uchwyt);
?>

Informacja:

Jeśli po prostu chcesz otrzymać treść pliku w stringu, użyj file_get_contents() dlatego, że ma to dużo lepszą wydajność niż kod powyżej.

Patrz także: fwrite(), fopen(),
fsockopen(), popen(),
fgets(), fgetss(),
fscanf(), file() i
fpassthru().

fputs
fscanf
Funkcje Systemu plików


Przetwarza dane z pliku według formatu

fread
fseek
Funkcje Systemu plików
PHP Manual

fscanf

(PHP 4 >= 4.0.1, PHP 5)

fscanf — Przetwarza dane z pliku według formatu

Opis

mixed fscanf ( resource $uchwyt , string $format [, mixed &$... ] )

Funkcja fscanf() jest podobna do sscanf(), ale pobiera dane wejściowe z pliku skojarzonego z uchwytem i interpretuje je zgodnie z podanym formatem, który opisany jest w dokumentacji do sprintf(). Jeśli tylko dwa parametry zostaną podane do funkcji, przetworzone wartości zostaną zwrócone w tablicy. W przeciwnym razie, jeśli opcjonalne parametry zostaną podane, funkcja zwróci numer przypisany do wartości. Opcjonalny parametr musi być podawany przez referencje.

Dowolny biały znak w łańcuchu formatującym pasuje do dowolnego białego znaku w strumieniu wejściowym. To znaczy, że nawet tabulacja \t w łańcuchu formatującym może być dopasowana do pojedynczego znaku spacji w strumieniu wejściowym.

Przykład #1 fscanf() Przykład

<?php
$uchwyt = fopen("users.txt", "r");
while ($userinfo = fscanf($uchwyt, "%s\t%s\t%s\n")) {
    list ($name, $profession, $countrycode) = $userinfo;
     //... zrób coś z wartościami
}
fclose($uchwyt);
?>

Przykład #2 Zawartość pliku users.txt

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

Informacja: Przed PHP 4.3.0, maksymalną liczbą znaków czytanych z pliku było 512 (lub do pierwszego wystąpienia \n, cokolwiek nastąpiło pierwsze). Od PHP 4.3.0 dowolnie długie linie są czytane i skanowane.

Patrz także: fread(), fgets(),
fgetss(), sscanf(),
printf() i sprintf().

fread
fseek
Funkcje Systemu plików


Seeks on a file pointer

fscanf
fstat
Funkcje Systemu plików
PHP Manual

fseek

(PHP 4, PHP 5)

fseek — Seeks on a file pointer

Opis

int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )

Sets the file position indicator for the file referenced by handle. The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence.

In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage.

Parametry

handle

Wskaźnik do systemu plików typu resource jest zazwyczaj tworzony poprzez funkcję fopen().

offset

The offset.

To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

Zwracane wartości

Upon success, returns 0; otherwise, returns -1.

Przykłady

Przykład #1 fseek() example

<?php

$fp = fopen('somefile.txt', 'r');

// read some data
$data = fgets($fp, 4096);

// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);

?>

Notatki

Informacja:

If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

Informacja:

Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.

Zobacz też:

  • ftell() - Mówi o pozycji odczyt/zapis wskaźnika pliku
  • rewind() - Rewind the position of a file pointer

fscanf
fstat
Funkcje Systemu plików


Pobiera informacje o pliku używając otwartego wskaźnika pliku

fseek
ftell
Funkcje Systemu plików
PHP Manual

fstat

(PHP 4, PHP 5)

fstat — Pobiera informacje o pliku używając otwartego wskaźnika pliku

Opis

array fstat ( resource $uchwyt )

Zbiera statystyki otwartego pliku przez wskaźnik pliku uchwyt. Ta funkcja jest podobna do funkcji stat() z wyjątkiem tego, że operuje na otwartym wskaźniku pliku zamiast na nazwię pliku.

Zwraca tablicę ze statystykami pliku; format tablicy szczegółowo jest opisany na stronie stat() podręcznika.

Przykład #1 fstat() przykład

<?php

// otwarcie pliku
$fp = fopen("/etc/passwd", "r");

// zebranie statystyk
$fstat = fstat($fp);

// zamknięcie pliku
fclose($fp);

// wyświetlenie tylko części asocjacyjnej
print_r(array_slice($fstat, 13));

?>

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

Array
(
  [dev] => 771
  [ino] => 488704
  [mode] => 33188
  [nlink] => 1
  [uid] => 0
  [gid] => 0
  [rdev] => 0
  [size] => 1114
  [atime] => 1061067181
  [mtime] => 1056136526
  [ctime] => 1056136526
  [blksize] => 4096
  [blocks] => 8
)

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

fseek
ftell
Funkcje Systemu plików


Mówi o pozycji odczyt/zapis wskaźnika pliku

fstat
ftruncate
Funkcje Systemu plików
PHP Manual

ftell

(PHP 4, PHP 5)

ftell — Mówi o pozycji odczyt/zapis wskaźnika pliku

Opis

int ftell ( resource $uchwyt )

Zwraca pozycję wskaźnika pliku wskazywanego przez uchwyt; np. jego ofset w strumieniu pliku.

W przypadku błędu, zwraca FALSE.

Wskaźnik pliku musi być prawidłowy i musi wskazywać na
poprawnie otworzony plik przez fopen() lub
popen().
ftell() zwraca niezdefiniowane wyniki dla
strumieni tylko do dopisywania (otwartych z flagą "a").

Przykład #1 ftell() przykład

<?php

// otwarcie pliku i odczytanie jakiś danych
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);

// gdzie jesteśmy ?
echo ftell($fp); // 11

fclose($fp);

?>

Patrz także: fopen(), popen(), fseek() i rewind().

fstat
ftruncate
Funkcje Systemu plików


Przycina plik do podanej długości

ftell
fwrite
Funkcje Systemu plików
PHP Manual

ftruncate

(PHP 4, PHP 5)

ftruncate — Przycina plik do podanej długości

Opis

bool ftruncate ( resource $uchwyt , int $rozmiar )

Pobiera wskaźnik pliku, uchwyt i przycina plik do długości, rozmiar.

Parametry

uchwyt

Wskaźnik pliku

Informacja:

uchwyt musi by otworzony do zapisu.

rozmiar

Rozmiar do którego przycinamy.

Informacja:

Jeśli rozmiar jest większy niż rozmiar pliku to jest on rozszerzany bajtami null.

Jeśli rozmiar jest mniejszy niż rozmiar pliku to dalsze dane zostaną stracone.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
PHP 4.3.3 | Przed tym wydaniem ftruncate() zwracała integer o wartości 1 w przypadku sukcesu, zamiast boolean TRUE.

Notatki

Informacja:

Wskaźnik pliku jest nie modyfikowany.

Zobacz też:

  • fopen() - Otwiera plik lub URL
  • fseek() - Seeks on a file pointer

ftell
fwrite
Funkcje Systemu plików


Zapis pliku binarnie bezpieczny

ftruncate
glob
Funkcje Systemu plików
PHP Manual

fwrite

(PHP 4, PHP 5)

fwrite — Zapis pliku binarnie bezpieczny

Opis

int fwrite ( resource $uchwyt , string $łańcuch [, int $długość ] )

fwrite() zapisuje treść łańcuch do strumienia pliku wskazanego przez uchwyt.

Parametry

uchwyt

Wskaźnik do systemu plików typu resource jest zazwyczaj tworzony poprzez funkcję fopen().

łańcuch

Łańcuch znaków, który ma być zapisany.

długość

Jeśli podany jest argument długość, zapisywanie zakończy się po zapisaniu długości bajtów lub gdy osiagnięty zostanie koniec łańcucha, cokolwiek zdarzy się pierwsze.

Zauważ, że jeśli argument długość zosta podany, to konfiguracja magic_quotes_runtime zostaje zignorowana i żadne slashe nie zostaną usunięte z łańcucha.

Zwracane wartości

fwrite() zwraca liczbę zapisanych bajtów lub FALSE w przypadku błędu.

Notatki

Informacja:

W systemach, które rozróżniają pliki na binarne i tekstowe (np. Windows) plik musi zostać otworzony z 'b' włączonym do parametru tryb funkcji fopen().

Informacja:

Jeśli uchwyt został utworzony za pomocą fopen() w trybie dopisywania, zapis do pliku jest niepodzielny (chyba, że rozmiar łańcucha przekracza blok systemu plików, na niektórych platformach, przy założeniu, że plik jest na lokalnym systemie plików). Jeśli tak, to nie ma potrzeby flock()owanie zasobu przed wywołaniem fwrite(); wszystkie dane zostaną zapisane bez przerywania.

Informacja:

Jeśli, zapiszemy dwukrotnie do wskaźnika pliku, dane zostaną dołączone na koncu treści pliku, oznacza to, że poniższy przykład nie zadziała jak się tego spodziewamy.

<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

// plik 'data.txt' ma treść 123, a nie 23!
?>

Przykłady

Przykład #1 Prosty przykład fwrite()

<?php
$nazwapliku = 'test.txt';
$trochetresci = "Dodaj to do pliku\n";

// Najpierw przekonaj się czy plik istnieje i jest zapisywalny.
if (is_writable($nazwapliku)) {

// W naszym przykładzie otwieramy $nazwapliku w trybie dopisywania.
// Wskaźnik pliku jest ustawiony na końcu pliku gdzie znajdzie
// się zawartość $trochetresci po wykonaniu fwrite().
if (!$uchwyt = fopen($nazwapliku, 'a')) {
   echo "Nie mogę otworzyć pliku ($nazwapliku)";
   exit;
 }

// Zapis $trochetresci do naszego otwartego pliku.
if (fwrite($uchwyt, $trochetresci) === FALSE) {
   echo "Nie mogę zapisać do pliku ($nazwapliku)";
   exit;
 }

echo "Sukces, zapisano ($trochetresci) do pliku ($nazwapliku)";

fclose($uchwyt);

} else {
  echo "Plik $nazwapliku nie jest zapisywalny";
}
?>

Zobacz też:

  • fread() - Odczyt pliku binarnie bezpieczy
  • fopen() - Otwiera plik lub URL
  • fsockopen() - Open Internet or Unix domain socket connection
  • popen() - Otwiera wskaźnik pliku do procesu
  • file_get_contents() - Reads entire file into a string

ftruncate
glob
Funkcje Systemu plików


Find pathnames matching a pattern

fwrite
is_dir
Funkcje Systemu plików
PHP Manual

glob

(PHP 4 >= 4.3.0, PHP 5)

glob — Find pathnames matching a pattern

Opis

array glob ( string $pattern [, int $flags = 0 ] )

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

Parametry

pattern

The pattern. No tilde expansion or parameter substitution is done.

flags

Valid flags:

  • GLOB_MARK - Adds a slash to each directory returned
  • GLOB_NOSORT - Return files as they appear in the directory (no sorting)
  • GLOB_NOCHECK - Return the search pattern if no files matching it were found
  • GLOB_NOESCAPE - Backslashes do not quote metacharacters
  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
  • GLOB_ONLYDIR - Return only directory entries which match the pattern
  • GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored.

Zwracane wartości

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Informacja:

On some systems it is impossible to distinguish between empty match and an error.

Rejestr zmian

Wersja | Opis
5.1.0 | GLOB_ERR was added
4.3.3 | GLOB_ONLYDIR became available on Windows and other systems not using the GNU C library

Przykłady

Przykład #1 Convenient way how glob() can replace opendir() and friends.

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

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

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Notatki

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Informacja: This function isn't available on some systems (e.g. old Sun OS).

Informacja: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

Zobacz też:

  • opendir() - Otwiera katalog
  • readdir() - Czyta zawartość katalogu
  • closedir() - Zamyka wskaźnik katalogu
  • fnmatch() - Match filename against a pattern

fwrite
is_dir
Funkcje Systemu plików


Mówi czy nazwa_pliku jest katalogiem

glob
is_executable
Funkcje Systemu plików
PHP Manual

is_dir

(PHP 4, PHP 5)

is_dir — Mówi czy nazwa_pliku jest katalogiem

Opis

bool is_dir ( string $nazwa_pliku )

Mówi czy nazwa_pliku jest katalogiem.

Parametry

nazwa_pliku

Ścieżka do pliku. Jeśli nazwa_pliku jest względną nazwą pliku, to zostanie sprawdzona względnie do bieżącego katalogu roboczego. Jeśli nazwa_pliku jest symbolicznym lub twardym dowiązaniem wtedy link zostanie rozwiązany i sprawdzony. Jeśli masz włączone tryb bezpieczny lub open_basedir dodatkowe ograniczenia mogą mieć zastosowanie.

Zwracane wartości

Zwraca TRUE jeśli nazwa pliku istnieje i jest katalogiem, w przeciwnym razie FALSE

Przykłady

Przykład #1 is_dir() przykład

<?php
var_dump(is_dir('plik.txt'));
var_dump(is_dir('nieistniejacy_katalog/abc'));

var_dump(is_dir('..')); //jeden katalog wyżej
?>

Powyższy przykład wyświetli:

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

Błędy/Wyjątki

W przypadku niepowodzenia jest emitowany E_WARNING.

Notatki

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Zobacz też:

  • chdir() - Zmienia bieżący katalog
  • dir() - Return an instance of the Directory class
  • opendir() - Otwiera katalog
  • is_file() - Mówi czy nazwa_pliku jest zwykłym plikiem
  • is_link() - Mówi czy nazwa_pliku jest dowiązaniem symbolicznym

glob
is_executable
Funkcje Systemu plików


Mówi czy plik jest wykonywalny

is_dir
is_file
Funkcje Systemu plików
PHP Manual

is_executable

(PHP 4, PHP 5)

is_executable — Mówi czy plik jest wykonywalny

Opis

bool is_executable ( string $nazwa_pliku )

Zwraca TRUE jeśli plik istnieje i jest wykonywalny.

is_executable() w Windows jest dostępna w wersji PHP 5.0.0.

Przykład #1 is_executable() przykład

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
  echo $file.' jest wykonywalny';
} else {
  echo $file.' nie jest wykonywalny';
}

?>

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Patrz także: is_file() i is_link().

is_dir
is_file
Funkcje Systemu plików


Mówi czy nazwa_pliku jest zwykłym plikiem

is_executable
is_link
Funkcje Systemu plików
PHP Manual

is_file

(PHP 4, PHP 5)

is_file — Mówi czy nazwa_pliku jest zwykłym plikiem

Opis

bool is_file ( string $nazwa_pliku )

Zwraca TRUE jesli nazwa_pliku istnieje i jest zwykłym plikiem.

Przykład #1 is_file() przykład

<?php
var_dump(is_file('plik.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Patrz także: is_dir() i is_link().

is_executable
is_link
Funkcje Systemu plików


Mówi czy nazwa_pliku jest dowiązaniem symbolicznym

is_file
is_readable
Funkcje Systemu plików
PHP Manual

is_link

(PHP 4, PHP 5)

is_link — Mówi czy nazwa_pliku jest dowiązaniem symbolicznym

Opis

bool is_link ( string $nazwa_pliku )

Zwraca TRUE jeśli nazwa_pliku istnieje i jest dowiązaniem symbolicznym.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Patrz także: is_dir(), is_file() i readlink().

is_file
is_readable
Funkcje Systemu plików


Tells whether a file exists and is readable

is_link
is_uploaded_file
Funkcje Systemu plików
PHP Manual

is_readable

(PHP 4, PHP 5)

is_readable — Tells whether a file exists and is readable

Opis

bool is_readable ( string $filename )

Tells whether a file exists and is readable.

Parametry

filename

Path to the file.

Zwracane wartości

Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise.

Przykłady

Przykład #1 is_readable() example

<?php
$filename = 'test.txt';
if (is_readable($filename)) {
    echo 'The file is readable';
} else {
    echo 'The file is not readable';
}
?>

Błędy/Wyjątki

W przypadku niepowodzenia jest emitowany E_WARNING.

Notatki

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account before PHP 5.1.5.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Informacja:

The check is done using the real UID/GID instead of the effective one.

Zobacz też:

  • is_writable() - Tells whether the filename is writable
  • file_exists() - Sprawdza czy plik lub katalog istnieje
  • fgets() - Pobiera linię ze wskaźnika pliku

is_link
is_uploaded_file
Funkcje Systemu plików


Mówi czy plik został przysłany przez HTTP POST.

is_readable
is_writable
Funkcje Systemu plików
PHP Manual

is_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

is_uploaded_file — Mówi czy plik został przysłany przez HTTP POST.

Opis

bool is_uploaded_file ( string $nazwa_pliku )

Zwraca TRUE jeśli plik o nazwie nazwa_pliku został przysłany (upload) przez HTTP POST. To pomaga upewnić się, czy złośliwy użytkownik nie próbuje oszukać skryptu pracującego na plikach, tak aby działał on na plikach na których nie powinien -- na przykład /etc/passwd.

Ten rodzaj testów jest szczególnie ważny jeśli istnieje szansa, że cokolwiek robimy z przysłanymi plikami może zdradzić ich treść użytkownikowi lub nawet innym użytkownikom tego samego systemu.

Do prawidłowego działania, funkcja is_uploaded_file() wymaga argumentu jak $_FILES['userfile']['tmp_name'], - nazwa przysyłanego pliku na maszynie klienta $_FILES['userfile']['name'] nie zadziała.

Przykład #1 is_uploaded_file() przykład

<?php

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
  echo "File ". $_FILES['userfile']['name'] ." upload prawidłowy.\n";
  echo "Wyświetlam treść\n";
  readfile($_FILES['userfile']['tmp_name']);
 } else {
  echo "Możliwy atak przez uploadowanie pliku: ";
  echo "Plik '". $_FILES['userfile']['tmp_name'] . "'.";
 }

?>

is_uploaded_file() jest dostępna tylko w wersjach PHP 3 późniejszych od PHP 3.0.16, i wersjach PHP 4 późniejszych od 4.0.2. Jeśli utknołeś przy używaniu wcześniejszej wersji, możesz użyć poniższej funkcji w celu pomocy w zabezpieczeniu siebie:

Informacja:

Poniższy przykład nie zadziała w wersjach PHP 4 późniejszych od 4.0.2. To jest spowodowane zmianą wewnętrznej funkcjonalności PHP po tej wersji.

Przykład #2 is_uploaded_file() przykład dla PHP 4 < 4.0.3

<?php
/* Test po stronie użytkownika na uploadowany plik */
function is_uploaded_file_4_0_2($filename)
{
if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
    $tmp_file = dirname(tempnam('', ''));
}
$tmp_file .= '/' . basename($filename);
  /* Użytkownik może mieć zamykający ukośnik w php.ini... */
return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

/* Jak użyć tej funkcji, w starych wersjach nie masz także
 * move_uploaded_file(): */
if (is_uploaded_file_4_0_2($HTTP_POST_FILES['userfile'])) {
    copy($HTTP_POST_FILES['userfile'], "/place/to/put/uploaded/file");
} else {
    echo "Prawdopodobny atak przez uploadowanie pliku: '$HTTP_POST_FILES[userfile]'.";
}
?>

Patrz także: move_uploaded_file() i rozdział Obsługa uploadowanych plików w celu uzyskania prostych przykładów użycia tej funkcji.

is_readable
is_writable
Funkcje Systemu plików


Tells whether the filename is writable

is_uploaded_file
is_writeable
Funkcje Systemu plików
PHP Manual

is_writable

(PHP 4, PHP 5)

is_writable — Tells whether the filename is writable

Opis

bool is_writable ( string $filename )

Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.

Parametry

filename

The filename being checked.

Zwracane wartości

Returns TRUE if the filename exists and is writable.

Przykłady

Przykład #1 is_writable() example

<?php
$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?>

Błędy/Wyjątki

W przypadku niepowodzenia jest emitowany E_WARNING.

Notatki

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Zobacz też:

  • is_readable() - Tells whether a file exists and is readable
  • file_exists() - Sprawdza czy plik lub katalog istnieje
  • fwrite() - Zapis pliku binarnie bezpieczny

is_uploaded_file
is_writeable
Funkcje Systemu plików


Alias dla is_writable

is_writable
lchgrp
Funkcje Systemu plików
PHP Manual

is_writeable

(PHP 4, PHP 5)

is_writeable — Alias dla is_writable()

Opis

Ta funkcja jest aliasem dla: is_writable().

is_writable
lchgrp
Funkcje Systemu plików


Changes group ownership of symlink

is_writeable
lchown
Funkcje Systemu plików
PHP Manual

lchgrp

(PHP 5 >= 5.1.2)

lchgrp — Changes group ownership of symlink

Opis

bool lchgrp ( string $filename , mixed $group )

Attempts to change the group of the symlink filename to group.

Only the superuser may change the group of a symlink arbitrarily; other users may change the group of a symlink to any group of which that user is a member.

Parametry

filename

Path to the symlink.

group

The group specified by name or number.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Changing the group of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchgrp($link, 8);
?>

Notatki

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Zobacz też:

  • chgrp() - Zmienia grupę pliku
  • lchown() - Changes user ownership of symlink
  • chown() - Zmienia właściciela pliku
  • chmod() - Zmienia prawa dostępu do pliku

is_writeable
lchown
Funkcje Systemu plików


Changes user ownership of symlink

lchgrp
link
Funkcje Systemu plików
PHP Manual

lchown

(PHP 5 >= 5.1.2)

lchown — Changes user ownership of symlink

Opis

bool lchown ( string $filename , mixed $user )

Attempts to change the owner of the symlink filename to user user.

Only the superuser may change the owner of a symlink.

Parametry

filename

Path to the file.

user

User name or number.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Changing the owner of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchown($link, 8);
?>

Notatki

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Zobacz też:

  • chown() - Zmienia właściciela pliku
  • lchgrp() - Changes group ownership of symlink
  • chgrp() - Zmienia grupę pliku
  • chmod() - Zmienia prawa dostępu do pliku

lchgrp
link
Funkcje Systemu plików


Tworzy dowiązanie twarde

lchown
linkinfo
Funkcje Systemu plików
PHP Manual

link

(PHP 4, PHP 5)

link — Tworzy dowiązanie twarde

Opis

bool link ( string $cel , string $link )

link() tworzy dowiązanie twarde. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja: Ta funkcja nie będzie działać na zdalnych plikach, ponieważ przetwarzany plik musi być dostępny w systemie plików serwera.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Patrz także: symlink() do tworzenia dowiązań symbolicznych, i readlink() w powiązaniu z linkinfo().

lchown
linkinfo
Funkcje Systemu plików


Pobiera informacje o linku

link
lstat
Funkcje Systemu plików
PHP Manual

linkinfo

(PHP 4, PHP 5)

linkinfo — Pobiera informacje o linku

Opis

int linkinfo ( string $ścieżka )

linkinfo() zwraca pole st_dev o strukturze unix'owej funkcji (języka C) stat, pole zwracane jest poprzez wywołanie systemowe lstat. Ta funkcja używana jest do weryfikacji czy link (wskazywany przez ścieżkę) naprawdę istnieje (używana jest ta sama metoda co w makrze S_ISLNK zdefiniowanym w stat.h). Zwraca 0 lub FALSE w przypadku błędu.

Przykład #1 przykład linkinfo()

<?php

echo linkinfo('/vmlinuz'); // 835

?>

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Patrz także: symlink(), link() i readlink().

link
lstat
Funkcje Systemu plików


Podaje informacje o pliku lub dowiązaniu symbolicznym

linkinfo
mkdir
Funkcje Systemu plików
PHP Manual

lstat

(PHP 4, PHP 5)

lstat — Podaje informacje o pliku lub dowiązaniu symbolicznym

Opis

array lstat ( string $nazwa_pliku )

Zbiera statystyki pliku lub dowiązania symbolicznego nazwanego przez nazwę_pliku. Ta funkcja jest identyczna do funkcji stat() z wyjątkiem tego, że jeśli parametr nazwa_pliku jest dowiązaniem symbolicznym, zwracany jest status dowiązania symbolicznego, a nie status pliku na które ono wskazuje.

Zobacz stronę podręcznika dla stat() w którym znajdują się informacje na temat struktury tablicy jaką lstat() zwraca.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Patrz także: stat().

linkinfo
mkdir
Funkcje Systemu plików


Tworzy katalog

lstat
move_uploaded_file
Funkcje Systemu plików
PHP Manual

mkdir

(PHP 4, PHP 5)

mkdir — Tworzy katalog

Opis

bool mkdir ( string $nazwa_ścieżki [, int $prawa dostępu [, bool $rekursywność [, resource $kontekst ]]] )

Tworzy katalog podany w nazwa_ścieżki.

Uwaga: Prawdopodobnie chciałbyś podać prawa dostępu jako wartość oktalną (ósemkową), co oznacza że powinieneś poprzedzić je zerem. Prawa dostępu mogą być także modyfikowane przez bieżący umask, który możesz zmienić używając umask().

Informacja:

Prawa dostępu sa ignorowane w Windows, i stały się opcjonalne w PHP 4.2.0.

Domyslnie prawa dostępu to 0777, co oznacza najbardziej otwarty dostęp. Po więcej informacji na temat praw dostępu, przeczytaj na stronie chmod().

Przykład #1 mkdir() przykład

<?php
mkdir ("/path/to/my/dir", 0700);
?>

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja: Od PHP 5.0.0 mkdir() może być użyta z niektórymi wrapperami URL. Zajrzyj do Supported Protocols and Wrappers aby uzyskać listę wrapperów, które wspierają mkdir().

Informacja: Obsługa kontekstów została dodana w PHP 5.0.0. Opis kontekstów znajduje się w rozdziale Stream Funkcje.

Informacja: Parametr rekursywność został dodany w PHP 5.0.0.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza czy katalog, na którym zostaną wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Patrz także: rmdir().

lstat
move_uploaded_file
Funkcje Systemu plików


Przenieś uploadowany plik do innej lokalizacji

mkdir
parse_ini_file
Funkcje Systemu plików
PHP Manual

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5)

move_uploaded_file — Przenieś uploadowany plik do innej lokalizacji

Opis

bool move_uploaded_file ( string $nazwa_pliku , string $przeznaczenie )

Funkcja ta sprawdza czy na pewno plik określony przez nazwa_pliku jest prawidło uploadowanym plikiem (to znaczy, że został uploadowany przez PHPowy mechanizm uploadowania HTTP POST). Jeśli plik jest prawidłowy, to zostanie przeniesiony do nazwy pliku wskazanej przez przeznaczenie.

Ten rodzaj testów jest szczególnie ważny jeśli istnieje szansa, że cokolwiek robimy z przysłanymi plikami może zdradzić ich treść użytkownikowi lub nawet innym użytkownikom tego samego systemu.

Parametry

nazwa_pliku

Nazwa wgrywanego pliku.

przeznaczenie

Miejsce docelowe przenoszonego pliku.

Zwracane wartości

Jeśli nazwa_pliku nie jest prawidło uploadowanym plikiem, to żadna akcja nie zostanie wykonana i move_uploaded_file() zwróci FALSE.

Jeśli nazwa_pliku jest prawidłowo uploadowanym plikiem, ale nie może zostać przeniesiony z jakiś powodów, żadna akcja nie zostanie wykonana i move_uploaded_file() zwróci FALSE. Dodatkowo, zostanie pokazane ostrzeżenie.

Notatki

Informacja:

Funkcja move_uploaded_file() jest świadoma tryb bezpieczny oraz open_basedir. Jednak, ograniczenia nałożone są tylko na ścieżkę przeznaczenie, ponieważ pozwala na przenoszenie uploadowanych plików w których nazwa_pliku może kolidować z takimi ograniczeniami. move_uploaded_file() zapewnia bezpieczeństwo tej operacji poprzez zezwolenie na przeniesienie tylko tych plików, które były uploadowane przez PHP.

Ostrzeżenie

Jeśli już istnieje plik docelowy, to zostanie on nadpisany.

Zobacz też:

  • is_uploaded_file() - Mówi czy plik został przysłany przez HTTP POST.
  • Zobacz Obsługa uploadowanych plików w celu uzyskania prostych przykładów użycia tej funkcji.

mkdir
parse_ini_file
Funkcje Systemu plików


Parse a configuration file

move_uploaded_file
parse_ini_string
Funkcje Systemu plików
PHP Manual

parse_ini_file

(PHP 4, PHP 5)

parse_ini_file — Parse a configuration file

Opis

array parse_ini_file ( string $filename [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )

parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array.

The structure of the ini file is the same as the php.ini's.

Parametry

filename

The filename of the ini file being parsed.

process_sections

By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

scanner_mode

Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.

Zwracane wartości

The settings are returned as an associative array on success, and FALSE on failure.

Rejestr zmian

Wersja | Opis
5.3.0 | Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) may no longer be used as comments and will throw a deprecation warning if used.
5.2.7 | On syntax error this function will return FALSE rather than an empty array.
5.2.4 | Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals.
5.0.0 | Values enclosed in double quotes can contain new lines.
4.2.1 | This function is now affected by tryb bezpieczny and open_basedir.

Przykłady

Przykład #1 Contents of sample.ini

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

Przykład #2 parse_ini_file() example

Constants may also be parsed in the ini file so if you define a constant as an ini value before running parse_ini_file(), it will be integrated into the results. Only ini values are evaluated. For example:

<?php

define('BIRD', 'Dodo bird');

// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Parse with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);

?>

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

Array
(
    [one] => 1
    [five] => 5
    [animal] => Dodo bird
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
    [phpversion] => Array
        (
            [0] => 5.0
            [1] => 5.1
            [2] => 5.2
            [3] => 5.3
        )

)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
            [animal] => Dodo bird
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

    [third_section] => Array
        (
            [phpversion] => Array
                (
                    [0] => 5.0
                    [1] => 5.1
                    [2] => 5.2
                    [3] => 5.3
                )

        )

)

Przykład #3 parse_ini_file() parsing a php.ini file

<?php
// A simple function used for comparing the results below
function yesno($expression)
{
    return($expression ? 'Yes' : 'No');
}

// Get the path to php.ini using the php_ini_loaded_file()
// function available as of PHP 5.2.4
$ini_path = php_ini_loaded_file();

// Parse php.ini
$ini = parse_ini_file($ini_path);

// Print and compare the values, note that using get_cfg_var()
// will give the same results for parsed and loaded here
echo '(parsed) magic_quotes_gpc = ' . yesno($ini['magic_quotes_gpc']) . PHP_EOL;
echo '(loaded) magic_quotes_gpc = ' . yesno(get_cfg_var('magic_quotes_gpc')) . PHP_EOL;
?>

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

(parsed) magic_quotes_gpc = Yes
(loaded) magic_quotes_gpc = Yes

Notatki

Informacja:

This function has nothing to do with the php.ini file. It is already processed by the time you run your script. This function can be used to read in your own application's configuration files.

Informacja:

If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes (").

Informacja: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, no and false results in "", yes and true results in "1". Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

Zobacz też:

  • parse_ini_string() - Parse a configuration string

move_uploaded_file
parse_ini_string
Funkcje Systemu plików


Parse a configuration string

parse_ini_file
pathinfo
Funkcje Systemu plików
PHP Manual

parse_ini_string

(PHP 5 >= 5.3.0)

parse_ini_string — Parse a configuration string

Opis

array parse_ini_string ( string $ini [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )

parse_ini_string() returns the settings in string ini in an associative array.

The structure of the ini string is the same as the php.ini's.

Parametry

ini

The contents of the ini file being parsed.

process_sections

By setting the process_sections parameter to TRUE, you get a multidimensional array, with the section names and settings included. The default for process_sections is FALSE

scanner_mode

Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.

Zwracane wartości

The settings are returned as an associative array on success, and FALSE on failure.

Notatki

Informacja: There are reserved words which must not be used as keys for ini files. These include: null, yes, no, true, false, on, off, none. Values null, no and false results in "", yes and true results in "1". Characters ?{}|&~![()^" must not be used anywhere in the key and have a special meaning in the value.

Zobacz też:

  • parse_ini_file() - Parse a configuration file

parse_ini_file
pathinfo
Funkcje Systemu plików


Zwraca informacje o ścieżce do pliku

parse_ini_string
pclose
Funkcje Systemu plików
PHP Manual

pathinfo

(PHP 4 >= 4.0.3, PHP 5)

pathinfo — Zwraca informacje o ścieżce do pliku

Opis

mixed pathinfo ( string $ścieżka [, int $opcje = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )

pathinfo() zwraca asocjacyjną tablicę zawierającą informacje o ścieżce.

Parametry

ścieżka

Ścieżka która jest sprawdzana

opcje

Możesz określić, który element zostanie zwrócony, za pomocą opcjonalnego parametru opcje. Składajego się z PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION i PATHINFO_FILENAME. Domyślnie zwracane są wszystkie elementy.

Zwracane wartości

Zwracane są następujące elementy asocjacyjnej tablicy array: dirname, basename, extension (jeśli wystąpi) i filename.

Jeśli parametr opcje zostanie użyty, funkcja zwróci string w przypadku gdy nie zarządano wszystkich elementów.

Rejestr zmian

Wersja | Opis
5.2.0 | Została dodana stała PATHINFO_FILENAME.

Przykłady

Przykład #1 Przykład pathinfo()

<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // od PHP 5.2.0
?>

Powyższy przykład wyświetli:

/www/htdocs/inc
lib.inc.php
php
lib.inc

Notatki

Informacja:

W celu uzyskania informacji jak pobrać bieżącą ścieżkę, przeczytaj rozdział predefiniowane zarezerwowane zmienne.

Zobacz też:

  • dirname() - Zwraca nazwę katalogu, będącego składową ścieżki
  • basename() - Zwraca nazwę pliku, będącego składową ścieżki
  • parse_url() - Przetwarza adres URL i zwraca jego składowe
  • realpath() - Returns canonicalized absolute pathname

parse_ini_string
pclose
Funkcje Systemu plików


Zamyka wskaźnik pliku do procesu

pathinfo
popen
Funkcje Systemu plików
PHP Manual

pclose

(PHP 4, PHP 5)

pclose — Zamyka wskaźnik pliku do procesu

Opis

int pclose ( resource $uchwyt )

Zamyka wskaźnik pliku do potoku otwartego przez popen().

Wskaźnik pliku musi być ważny, i musi być zwrócony przez pomyślne wywołanie popen().

Zwraca status zakończenia procesu który był uruchamiany.

Patrz także popen().

pathinfo
popen
Funkcje Systemu plików


Otwiera wskaźnik pliku do procesu

pclose
readfile
Funkcje Systemu plików
PHP Manual

popen

(PHP 4, PHP 5)

popen — Otwiera wskaźnik pliku do procesu

Opis

resource popen ( string $polecenie , string $tryb )

Otwiera potok do procesu uruchomionego przez rozwidlenie polecenia (ang. forking) podanego w parametrze polecenie.

Zwraca wskaźnik pliku identyczny do tego zwracanego przez fopen() z wyjątkiem tego, że jest on jednokierunkowy (może być tylko użyty do odczytu lub zapisu) i musi być zamknięty za pomocą pclose(). Wskaźnik ten może być użyty z fgets(), fgetss() i fwrite().

W przypadku błędu, zwraca FALSE.

Informacja:

Jeśli szukasz dwukierunkowej obsługi (w obie strony), użyj proc_open().

Przykład #1 popen() przykład

<?php
$uchwyt = popen("/bin/ls", "r");
?>

Jeśli polecenie uruchamiane nie może zostać znalezione, poprawny zasób jest zwracany. To może wydawać się dziwne, ale ma sens; pozwala tobie na dostęp do wszystkich informacji o błędach zwracanych przez powłokę.

<?php
error_reporting(E_ALL);

/* Dodanie przekierowania, aby móc dostać stderr. */
$uchwyt = popen('/sciezka/do/czegos 2>&1', 'r');
echo "'$uchwyt'; " . gettype($uchwyt) . "\n";
$czytaj = fread($uchwyt, 2096);
echo $czytaj;
pclose($uchwyt);
?>

Informacja: Jeśli tryb bezpieczny został włączony, możliwe jest wykonywanie programów tylko z katalogu określonego przez safe_mode_exec_dir. Ze względów praktycznych, nie można podawać elementów .. w ścieżce do pliku wykonywalnego.

Ostrzeżenie

Jeśli włączony jest tryb bezpieczny, ciągi zawierające polecenia są filtrowane przez funkcję escapeshellcmd(). W związku z tym, echo y | echo x staje się echo y \| echo x.

Patrz także pclose(), fopen() i proc_open().

pclose
readfile
Funkcje Systemu plików


Wyświetla plik

popen
readlink
Funkcje Systemu plików
PHP Manual

readfile

(PHP 4, PHP 5)

readfile — Wyświetla plik

Opis

int readfile ( string $nazwapliku [, bool $użyj_include_path [, resource $context ]] )

Odczytuje plik i zapisuje go do bufora wyjściowego.

Zwraca liczbę odczytanych bajtów z pliku, Jeśli nastąpił błą, zwraca FALSE oraz wyświetlany jest komunikat błędu, chyba, żę funkcja została wywołana jako @readfile().

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Można ustawić opcjonalny drugi parametr na TRUE jeśli plik ma być poszukiwany także w include_path.

Informacja: Obsługa kontekstów została dodana w PHP 5.0.0. Opis kontekstów znajduje się w rozdziale Stream Funkcje.

Patrz także: fpassthru(),
file(), fopen(),
include(), require(),
virtual(), file_get_contents()
i Supported Protocols and Wrappers.

popen
readlink
Funkcje Systemu plików


Zwraca cel linku symbolicznego

readfile
realpath_cache_get
Funkcje Systemu plików
PHP Manual

readlink

(PHP 4, PHP 5)

readlink — Zwraca cel linku symbolicznego

Opis

string readlink ( string $ścieżka )

readlink() jest tym samym co funkcja języka C readlink i zwraca ścieżkę linku symbolicznego lub FALSE w przypadku błędu.

Przykład #1 readlink() przykład

<?php

// wynik np. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Patrz takżę: is_link(),
symlink() i
linkinfo().

readfile
realpath_cache_get
Funkcje Systemu plików


Get realpath cache entries

readlink
realpath_cache_size
Funkcje Systemu plików
PHP Manual

realpath_cache_get

(PHP 5 >= 5.3.2)

realpath_cache_get — Get realpath cache entries

Opis

array realpath_cache_get ( void )

Get the contents of the realpath cache.

Zwracane wartości

Returns an array of realpath cache entries. The keys are original path entries, and the values are arrays of data items, containing the resolved path, expiration date, and other options kept in the cache.

Przykłady

Przykład #1 realpath_cache_get() example

<?php
var_dump(realpath_cache_get());
?>

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

array(2) {
  ["/test"]=>
  array(4) {
    ["key"]=>
    int(123456789)
    ["is_dir"]=>
    bool(true)
    ["realpath"]=>
    string(5) "/test"
    ["expires"]=>
    int(1260318939)
  }
  ["/test/test.php"]=>
  array(4) {
    ["key"]=>
    int(987654321)
    ["is_dir"]=>
    bool(false)
    ["realpath"]=>
    string(12) "/root/test.php"
    ["expires"]=>
    int(1260318939)
  }
}

Zobacz też:

  • realpath_cache_size() - Get realpath cache size

readlink
realpath_cache_size
Funkcje Systemu plików


Get realpath cache size

realpath_cache_get
realpath
Funkcje Systemu plików
PHP Manual

realpath_cache_size

(PHP 5 >= 5.3.2)

realpath_cache_size — Get realpath cache size

Opis

int realpath_cache_size ( void )

Get the amount of memory used by the realpath cache.

Zwracane wartości

Returns how much memory realpath cache is using.

Przykłady

Przykład #1 realpath_cache_size() example

<?php
var_dump(realpath_cache_size());
?>

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

int(412)

Zobacz też:

  • realpath_cache_get() - Get realpath cache entries

realpath_cache_get
realpath
Funkcje Systemu plików


Returns canonicalized absolute pathname

realpath_cache_size
rename
Funkcje Systemu plików
PHP Manual

realpath

(PHP 4, PHP 5)

realpath — Returns canonicalized absolute pathname

Opis

string realpath ( string $path )

realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname.

Parametry

path

The path being checked.

Informacja:

Whilst a path must be supplied, the value can be blank or NULL In these cases, the value is interpreted as the current directory.

Zwracane wartości

Returns the canonicalized absolute pathname on success. The resulting path will have no symbolic link, '/./' or '/../' components.

realpath() returns FALSE on failure, e.g. if the file does not exist.

Informacja:

The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.

Informacja: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Rejestr zmian

Wersja | Opis
5.3.0 | Prior to this release, if only the last path component did not exist, realpath() would not fail on *BSD systems. realpath() now fails in this case.
5.0.0 | Prior to this release, a blank or NULL path would cause realpath() to return the directory name of the script.

Przykłady

Przykład #1 realpath() example

<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd');
?>

Powyższy przykład wyświetli:

/etc/passwd

Przykład #2 realpath() on Windows

On windows realpath() will change unix style paths to windows style.

<?php
echo realpath('/windows/system32');
?>

Powyższy przykład wyświetli:

C:\WINDOWS\System32

Zobacz też:

  • basename() - Zwraca nazwę pliku, będącego składową ścieżki
  • dirname() - Zwraca nazwę katalogu, będącego składową ścieżki
  • pathinfo() - Zwraca informacje o ścieżce do pliku

realpath_cache_size
rename
Funkcje Systemu plików


Renames a file or directory

realpath
rewind
Funkcje Systemu plików
PHP Manual

rename

(PHP 4, PHP 5)

rename — Renames a file or directory

Opis

bool rename ( string $oldname , string $newname [, resource $context ] )

Attempts to rename oldname to newname.

Parametry

oldname

Informacja:

The old name. The wrapper used in oldname must match the wrapper used in newname.

newname

The new name.

context

Informacja: Obsługa kontekstów została dodana w PHP 5.0.0. Opis kontekstów znajduje się w rozdziale Stream Funkcje.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.1 | rename() can now rename files across drives in Windows.
5.0.0 | rename() can now also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support rename().
4.3.3 | rename() may now be able to rename files across partitions on *nix based systems, provided the appropriate permissions are held. Warnings may be generated if the destination filesystem doesn't permit chown() or chmod() system calls to be made on files — for example, if the destination filesystem is a FAT filesystem.

Przykłady

Przykład #1 Example with rename()

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

Zobacz też:

  • copy() - Kopiuje plik
  • unlink() - Kasowanie pliku
  • move_uploaded_file() - Przenieś uploadowany plik do innej lokalizacji

realpath
rewind
Funkcje Systemu plików


Rewind the position of a file pointer

rename
rmdir
Funkcje Systemu plików
PHP Manual

rewind

(PHP 4, PHP 5)

rewind — Rewind the position of a file pointer

Opis

bool rewind ( resource $handle )

Sets the file position indicator for handle to the beginning of the file stream.

Informacja:

If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.

Parametry

handle

The file pointer must be valid, and must point to a file successfully opened by fopen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 rewind() overwriting example

<?php
$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);

echo fread($handle, filesize('output.txt'));

fclose($handle);
?>

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

Foolly long sentence.

Zobacz też:

  • fread() - Odczyt pliku binarnie bezpieczy
  • fseek() - Seeks on a file pointer
  • ftell() - Mówi o pozycji odczyt/zapis wskaźnika pliku
  • fwrite() - Zapis pliku binarnie bezpieczny

rename
rmdir
Funkcje Systemu plików


Usuwanie katalogów

rewind
set_file_buffer
Funkcje Systemu plików
PHP Manual

rmdir

(PHP 4, PHP 5)

rmdir — Usuwanie katalogów

Opis

bool rmdir ( string $nazwa_katalogu [, resource $kontekst ] )

Próbuje usunąć katalog podany przez nazwa_katalogu. Katalog musi byc pusty, i stosowne uprawnienia muszą na to pozwalać. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja: Od PHP 5.0.0 rmdir() może być również użyta z niektórymi wrapperami URL. Odwołaj się do Supported Protocols and Wrappers listy wrapperów, które wspierają rmdir().

Informacja: Obsługa kontekstów została dodana w PHP 5.0.0. Opis kontekstów znajduje się w rozdziale Stream Funkcje.

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza czy katalog, na którym zostaną wykonane operacje, ma takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Patrz także mkdir() i unlink().

rewind
set_file_buffer
Funkcje Systemu plików


Alias dla stream_set_write_buffer

rmdir
stat
Funkcje Systemu plików
PHP Manual

set_file_buffer

(PHP 4, PHP 5)

set_file_buffer — Alias dla stream_set_write_buffer()

Opis

Ta funkcja jest aliasem dla: stream_set_write_buffer().

rmdir
stat
Funkcje Systemu plików


Gives information about a file

set_file_buffer
symlink
Funkcje Systemu plików
PHP Manual

stat

(PHP 4, PHP 5)

stat — Gives information about a file

Opis

array stat ( string $filename )

Gathers the statistics of the file named by filename. If filename is a symbolic link, statistics are from the file itself, not the symlink.

lstat() is identical to stat() except it would instead be based off the symlinks status.

Parametry

filename

Path to the file.

Zwracane wartości

stat() and fstat() result format
Numeric | Associative (since PHP 4.0.6) | Description
0 | dev | device number
1 | ino | inode number *
2 | mode | inode protection mode
3 | nlink | number of links
4 | uid | userid of owner *
5 | gid | groupid of owner *
6 | rdev | device type, if inode device
7 | size | size in bytes
8 | atime | time of last access (Unix timestamp)
9 | mtime | time of last modification (Unix timestamp)
10 | ctime | time of last inode change (Unix timestamp)
11 | blksize | blocksize of filesystem IO **
12 | blocks | number of 512-byte blocks allocated **
* On Windows this will always be 0.

** Only valid on systems supporting the st_blksize type - other systems (e.g. Windows) return -1.

In case of error, stat() returns FALSE.

Informacja: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Błędy/Wyjątki

Upon failure, an E_WARNING is emitted.

Rejestr zmian

Wersja | Opis
4.0.6 | In addition to returning these attributes in a numeric array, they can be accessed with associative indices, as noted next to each parameter

Przykłady

Przykład #1 stat() example

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/*
 * Print file access time, this is the same
 * as calling fileatime()
 */
echo 'Access time: ' . $stat['atime'];

/*
 * Print file modification time, this is the
 * same as calling filemtime()
 */
echo 'Modification time: ' . $stat['mtime'];

/* Print the device number */
echo 'Device number: ' . $stat['dev'];
?>

Przykład #2 Using stat() information together with touch()

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/* Did we failed to get stat information? */
if (!$stat) {
    echo 'stat() call failed...';
} else {
    /*
     * We want the access time to be 1 week
     * after the current access time.
     */
    $atime = $stat['atime'] + 604800;

    /* Touch the file */
    if (!touch('some_file.txt', time(), $atime)) {
        echo 'Failed to touch file...';
    } else {
        echo 'touch() returned success...';
    }
}
?>

Notatki

Informacja:

Proszę zauważyć, że informacja o czasie dostępu może się różnić w zależności od systemu plików.

Informacja: Wyniki działania tej funkcji są buforowane. Zobacz opis funkcji clearstatcache() aby uzyskać więcej informacji.

Wskazówka

Od PHP 5.0.0 ta funkcja może być użyta także z niektórymi nakładkami URL. Zobacz Supported Protocols and Wrappers aby uzyskać listę nakładek, które obsługują funkcjonalność z rodziny stat().

Zobacz też:

  • lstat() - Podaje informacje o pliku lub dowiązaniu symbolicznym
  • fstat() - Pobiera informacje o pliku używając otwartego wskaźnika pliku
  • filemtime() - Pobiera czas ostatniej modyfikacji pliku
  • filegroup() - Pobiera grupę pliku

set_file_buffer
symlink
Funkcje Systemu plików


Tworzy dowiązanie symboliczne

stat
tempnam
Funkcje Systemu plików
PHP Manual

symlink

(PHP 4, PHP 5)

symlink — Tworzy dowiązanie symboliczne

Opis

bool symlink ( string $cel , string $dowiązanie )

symlink() tworzy dowiązanie symboliczne do istniejącego celu z podaną nazwą dowiązanie.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Patrz także link() aby stworzyć twarde dowiązanie, i readlink() w powiązaniu z linkinfo().

stat
tempnam
Funkcje Systemu plików


Create file with unique file name

symlink
tmpfile
Funkcje Systemu plików
PHP Manual

tempnam

(PHP 4, PHP 5)

tempnam — Create file with unique file name

Opis

string tempnam ( string $dir , string $prefix )

Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.

Parametry

dir

The directory where the temporary filename will be created.

prefix

The prefix of the generated temporary filename.

Informacja: Windows uses only the first three characters of prefix.

Zwracane wartości

Returns the new temporary filename, or FALSE on failure.

Rejestr zmian

Wersja | Opis
4.0.6 | Prior to PHP 4.0.6, the behaviour of the tempnam() function was system dependent. On Windows the TMP environment variable will override the dir parameter, on Linux the TMPDIR environment variable has precedence, while SVR4 will always use your dir parameter if the directory it points to exists. Consult your system documentation on the tempnam(3) function if in doubt.
4.0.3 | This function's behavior changed in 4.0.3. The temporary file is also created to avoid a race condition where the file might appear in the filesystem between the time the string was generated and before the script gets around to creating the file. Note, that you need to remove the file in case you need it no more, it is not done automatically.

Przykłady

Przykład #1 tempnam() example

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?>

Notatki

Informacja: If PHP cannot create a file in the specified dir parameter, it falls back on the system default. On NTFS this also happens if the specified dir contains more than 65534 files.

Zobacz też:

  • tmpfile() - Tworzy plik tymczasowy
  • sys_get_temp_dir() - Returns directory path used for temporary files
  • unlink() - Kasowanie pliku

symlink
tmpfile
Funkcje Systemu plików


Tworzy plik tymczasowy

tempnam
touch
Funkcje Systemu plików
PHP Manual

tmpfile

(PHP 4, PHP 5)

tmpfile — Tworzy plik tymczasowy

Opis

resource tmpfile ( void )

Tworzy plik tymczasowy o unikalnej nazwie i otwiera go w trybie do odczytu i zapisu (w+), zwraca uchwyt pliku, podobnie jak fopen(). Plik jest automatycznie kasowany przy zamykaniu (po użyciu fclose()), lub gdy skrypt się zakończy.

Jeśli chcesz uzyskać więcej szczegółów, zajrzyj do dokumentacji twojego systemu dotyczącej funkcji tmpfile(3), albo do pliku nagłówkowego stdio.h.

Przykład #1 tmpfile() przykład

<?php
$temp = tmpfile();
fwrite($temp, "zapisywanie do pliku tymczasowego");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // to kasuje plik
?>

Powyższy przykład wyświetli:

zapisywanie do pliku tymczasowego

Patrz także: tempnam(), sys_get_temp_dir().

tempnam
touch
Funkcje Systemu plików


Ustawia czas modyfikacji pliku

tmpfile
umask
Funkcje Systemu plików
PHP Manual

touch

(PHP 4, PHP 5)

touch — Ustawia czas modyfikacji pliku

Opis

bool touch ( string $nazwa_pliku [, int $czas = time() [, int $dczas ]] )

Próbuje ustawić czas dostępu i modyfikacji pliku o nazwie nazwa_pliku na wartość podaną przez czas. Zauważ, że czas dostępu jest zawsze modyfikowany, niezależnie od ilości parametrów.

Jeśli plik nie istnieje, to zostanie utworzony.

Parametry

nazwa_pliku

Nazwa pliku, który ma być zmodyfikowany.

czas

Czas modyfikacji. Jeśli czas nie został podany, zostanie użyty bieżący czas systemowy.

dczas

Jeśli podano, to czas dostępu do podanego pliku zostanie ustawiony na wartość dczas. W przeciwnym wypadku zostanie ustawiony na wartość przekazaną w parametrze time. Jeśli, żaden nie występuje, zostanie użyty bieżący czas.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.0 | Możliwa jest zmiana czasu modyfikacji katalogu pod Windows.

Przykłady

Przykład #1 touch() przykład

<?php
if (touch($filename)) {
    echo $filename . ' czas modyfikacji został zmieniony na bieżący czas';
} else {
    echo 'Przykro mi ale Nie Mogę zmienić czasu modyfikacji pliku ' . $filename;
}
?>

Przykład #2 touch() użycie parametru czas

<?php
// To jest czas modyfikacji, ustawimy go na jedną godzinę wstecz.
$time = time() - 3600;

// Modyfikujemy czas pliku
if (!touch('jakis_plik.txt', $time)) {
    echo 'Coś się nie udało...';
} else {
    echo 'Czas modyfikacji pliku ustawiony';
}
?>

Notatki

Informacja:

Proszę zauważyć, że informacja o czasie dostępu może się różnić w zależności od systemu plików.

Ostrzeżenie

Przed wersją PHP 5.3.0 nie istniała mozliwość zmiany czasu modyfikacji katalogu za pomocą tej funkcji pod systemem Windows.

tmpfile
umask
Funkcje Systemu plików


Changes the current umask

touch
unlink
Funkcje Systemu plików
PHP Manual

umask

(PHP 4, PHP 5)

umask — Changes the current umask

Opis

int umask ([ int $mask ] )

umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.

Parametry

mask

The new umask.

Zwracane wartości

umask() without arguments simply returns the current umask otherwise the old umask is returned.

Przykłady

Przykład #1 umask() example

<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);

// Checking
if ($old != umask()) {
    die('An error occured while changing back the umask');
}
?>

Notatki

Informacja:

Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file. Using umask() can lead to unexpected behavior of concurrently running scripts and the webserver itself because they all use the same umask.

touch
unlink
Funkcje Systemu plików


Kasowanie pliku

umask
Inotify
Funkcje Systemu plików
PHP Manual

unlink

(PHP 4, PHP 5)

unlink — Kasowanie pliku

Opis

bool unlink ( string $nazwa_pliku [, resource $kontekst ] )

Kasuje nazwa_pliku. Podobnie do uniksowej funkcji C unlink(). W przypadku porażki zostanie wygenerowany błąd na poziomie E_WARNING.

Parametry

nazwa_pliku

Ścieżka do pliku.

context

Informacja: Obsługa kontekstów została dodana w PHP 5.0.0. Opis kontekstów znajduje się w rozdziale Stream Funkcje.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.0.0 | Od PHP 5.0.0 unlink() może być również użyty z niektórymi osłonami (wrapperami) URL. Zajrzyj do Supported Protocols and Wrappers aby uzyskać listę wrapperów, które obsługuje unlink().

Przykłady

Przykład #1 Podstawowe użycie unlink()

<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Witaj Świecie!</h1>');
fclose($fh);

unlink('test.html');
?>

Zobacz też:

  • rmdir() - Usuwanie katalogów

umask
Inotify
Funkcje Systemu plików


Inotify

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja/Konfiguracja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Inotify Funkcje
    • inotify_add_watch — Add a watch to an initialized inotify instance
    • inotify_init — Initialize an inotify instance
    • inotify_queue_len — Return a number upper than zero if there are pending events
    • inotify_read — Read events from an inotify instance
    • inotify_rm_watch — Remove an existing watch from an inotify instance
unlink
Wstęp
Rozszerzenia powiązane z systemem plików


Wstęp

The inotify extension exposes the inotify functions inotify_init(), inotify_add_watch() and inotify_rm_watch().

As the C inotify_init() function returns a file descriptor, PHP's inotify_init() returns a stream resource, usable with standard stream functions, like stream_select(), stream_set_blocking() and fclose(). inotify_read() replaces the C way of reading inotify events.

Inotify
Instalacja/Konfiguracja
Inotify


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja/Konfiguracja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Inotify


Wymagania

This extension requires Linux 2.6.13 or newer, and a recent libC.

Instalacja/Konfiguracja
Instalacja/Konfiguracja
Instalacja/Konfiguracja


Instalacja/Konfiguracja
PHP Manual

Instalacja/Konfiguracja

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/inotify.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja
PHP Manual


Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.

Instalacja/Konfiguracja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines a stream resource returned by inotify_init().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

Inotify constants usable with inotify_add_watch() and/or returned by inotify_read()
IN_ACCESS (integer)
File was accessed (read) (*)
IN_MODIFY (integer)
File was modified (*)
IN_ATTRIB (integer)
Metadata changed (e.g. permissions, mtime, etc.) (*)
IN_CLOSE_WRITE (integer)
File opened for writing was closed (*)
IN_CLOSE_NOWRITE (integer)
File not opened for writing was closed (*)
IN_OPEN (integer)
File was opened (*)
IN_MOVED_TO (integer)
File moved into watched directory (*)
IN_MOVED_FROM (integer)
File moved out of watched directory (*)
IN_CREATE (integer)
File or directory created in watched directory (*)
IN_DELETE (integer)
File or directory deleted in watched directory (*)
IN_DELETE_SELF (integer)
Watched file or directory was deleted
IN_MOVE_SELF (integer)
Watch file or directory was moved
IN_CLOSE (integer)
Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
IN_MOVE (integer)
Equals to IN_MOVED_FROM | IN_MOVED_TO
IN_ALL_EVENTS (integer)
Bitmask of all the above constants
IN_UNMOUNT (integer)
File system containing watched object was unmounted
IN_Q_OVERFLOW (integer)
Event queue overflowed (wd is -1 for this event)
IN_IGNORED (integer)
Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted
IN_ISDIR (integer)
Subject of this event is a directory
IN_ONLYDIR (integer)
Only watch pathname if it is a directory (Since Linux 2.6.15)
IN_DONT_FOLLOW (integer)
Do not dereference pathname if it is a symlink (Since Linux 2.6.15)
IN_MASK_ADD (integer)
Add events to watch mask for this pathname if it already exists (instead of replacing mask).
IN_ONESHOT (integer)
Monitor pathname for one event, then remove from watch list.

Informacja: The events marked with an asterisk (*) above can occur for files in watched directories.

Typy zasobów
Inotify Funkcje
Inotify


Inotify Funkcje

Spis treści

  • inotify_add_watch — Add a watch to an initialized inotify instance
  • inotify_init — Initialize an inotify instance
  • inotify_queue_len — Return a number upper than zero if there are pending events
  • inotify_read — Read events from an inotify instance
  • inotify_rm_watch — Remove an existing watch from an inotify instance
Stałe predefiniowane
inotify_add_watch
Inotify


Add a watch to an initialized inotify instance

Inotify Funkcje
inotify_init
Inotify Funkcje
PHP Manual

inotify_add_watch

(PECL inotify >= 0.1.2)

inotify_add_watch — Add a watch to an initialized inotify instance

Opis

int inotify_add_watch ( resource $inotify_instance , string $pathname , int $mask )

inotify_add_watch() adds a new watch or modify an existing watch for the file or directory specified in pathname.

Using inotify_add_watch() on a watched object replaces the existing watch. Using the IN_MASK_ADD constant adds (OR) events to the existing watch.

Parametry

inotify_instance

Zasób zwracany przez inotify_init()

pathname

File or directory to watch

mask

Events to watch for. See Predefiniowane stałe.

Zwracane wartości

The return value is a unique (inotify instance wide) watch descriptor.

Zobacz też:

  • inotify_init() - Initialize an inotify instance

Inotify Funkcje
inotify_init
Inotify Funkcje


Initialize an inotify instance

inotify_add_watch
inotify_queue_len
Inotify Funkcje
PHP Manual

inotify_init

(PECL inotify >= 0.1.2)

inotify_init — Initialize an inotify instance

Opis

resource inotify_init ( void )

Initialize an inotify instance for use with inotify_add_watch()

Zwracane wartości

A stream resource or FALSE on error.

Przykłady

Przykład #1 Example usage of inotify

<?php
// Open an inotify instance
$fd = inotify_init();

// Watch __FILE__ for metadata changes (e.g. mtime)
$watch_descriptor = inotify_add_watch($fd, __FILE__, IN_ATTRIB);

// generate an event
touch(__FILE__);

// Read events
$events = inotify_read($fd);
print_r($events);

// The following methods allows to use inotify functions without blocking on inotify_read():

// - Using stream_select() on $fd:
$read = array($fd);
$write = null;
$except = null;
stream_select($read,$write,$except,0);

// - Using stream_set_blocking() on $fd
stream_set_blocking($fd, 0);
inotify_read($fd); // Does no block, and return false if no events are pending

// - Using inotify_queue_len() to check if event queue is not empty
$queue_len = inotify_queue_len($fd); // If > 0, inotify_read() will not block

// Stop watching __FILE__ for metadata changes
inotify_rm_watch($fd, $watch_descriptor);

// Close the inotify instance
// This may have closed all watches if this was not already done
fclose($fd);

?>

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

array(
  array(
    'wd' => 1,     // Equals $watch_descriptor
    'mask' => 4,   // IN_ATTRIB bit is set
    'cookie' => 0, // unique id to connect related events (e.g.
                   // IN_MOVE_FROM and IN_MOVE_TO events)
    'name' => '',  // the name of a file (e.g. if we monitored changes
                   // in a directory)
  ),
);

Zobacz też:

  • inotify_add_watch() - Add a watch to an initialized inotify instance
  • inotify_rm_watch() - Remove an existing watch from an inotify instance
  • inotify_queue_len() - Return a number upper than zero if there are pending events
  • inotify_read() - Read events from an inotify instance
  • fclose() - Zamyka otwarty wskaźnik pliku

inotify_add_watch
inotify_queue_len
Inotify Funkcje


Return a number upper than zero if there are pending events

inotify_init
inotify_read
Inotify Funkcje
PHP Manual

inotify_queue_len

(PECL inotify >= 0.1.2)

inotify_queue_len — Return a number upper than zero if there are pending events

Opis

int inotify_queue_len ( resource $inotify_instance )

This function allows to know if inotify_read() will block or not. If a number upper than zero is returned, there are pending events and inotify_read() will not block.

Parametry

inotify_instance

Zasób zwracany przez inotify_init()

Zwracane wartości

Returns a number upper than zero if there are pending events.

Zobacz też:

  • inotify_init() - Initialize an inotify instance
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream

inotify_init
inotify_read
Inotify Funkcje


Read events from an inotify instance

inotify_queue_len
inotify_rm_watch
Inotify Funkcje
PHP Manual

inotify_read

(PECL inotify >= 0.1.2)

inotify_read — Read events from an inotify instance

Opis

array inotify_read ( resource $inotify_instance )

Read inotify events from an inotify instance.

Parametry

inotify_instance

Zasób zwracany przez inotify_init()

Zwracane wartości

An array of inotify events or FALSE if no events was pending and inotify_instance is non-blocking. Each event is an array with the following keys:

  • wd is a watch descriptor returned by inotify_add_watch()
  • mask is a bit mask of events
  • cookie is a unique id to connect related events (e.g. IN_MOVE_FROM and IN_MOVE_TO)
  • name is the name of a file (e.g. if a file was modified in a watched directory)

Zobacz też:

  • inotify_init() - Initialize an inotify instance
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • inotify_queue_len() - Return a number upper than zero if there are pending events

inotify_queue_len
inotify_rm_watch
Inotify Funkcje


Remove an existing watch from an inotify instance

inotify_read
Mimetype
Inotify Funkcje
PHP Manual

inotify_rm_watch

(PECL inotify >= 0.1.2)

inotify_rm_watch — Remove an existing watch from an inotify instance

Opis

bool inotify_rm_watch ( resource $inotify_instance , int $watch_descriptor )

inotify_rm_watch() removes the watch watch_descriptor from the inotify instance inotify_instance.

Parametry

inotify_instance

Zasób zwracany przez inotify_init()

watch_descriptor

Watch to remove from the instance

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • inotify_init() - Initialize an inotify instance

inotify_read
Mimetype
Inotify Funkcje


Mimetype

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
inotify_rm_watch
Wstęp
Rozszerzenia powiązane z systemem plików


Wstęp

Ostrzeżenie

This extension has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

This extension is derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.

Mimetype
Instalacja/Konfiguracja
Mimetype


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Mimetype


Instalacja

Ostrzeżenie

Mimetype extensions has been removed from PHP 5.3.0 in favor of Fileinfo.

You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.

Informacja:

The configure option has been changed from --enable-mime-magic to --with-mime-magic since PHP 4.3.2

Informacja:

This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.

Informacja: Note to Win32 Users

In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.

Przykład #1 Setting the path to magic.mime

mime_magic.magicfile = "$PHP_INSTALL_DIR\magic.mime"

Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Mimetype configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.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.

mime_magic.debug bool

Enable/disable debugging.

mime_magic.magicfile string

The path to the magic.mime file.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Proctitle
Mimetype


Proctitle

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Proctitle Funkcje
    • setproctitle — Set the process title
    • setthreadtitle — Set the thread title
Stałe predefiniowane
Wstęp
Rozszerzenia powiązane z systemem plików


Wstęp

This extension allows changing the current process', and thread, name on Linux and *BSD systems. This is useful when using pcntl_fork() to identify running processes in process list

Proctitle
Instalacja/Konfiguracja
Proctitle


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Proctitle


Wymagania

Nothing special.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/proctitle.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Proctitle Funkcje
Proctitle


Proctitle Funkcje

Spis treści

  • setproctitle — Set the process title
  • setthreadtitle — Set the thread title
Stałe predefiniowane
setproctitle
Proctitle


Set the process title

Proctitle Funkcje
setthreadtitle
Proctitle Funkcje
PHP Manual

setproctitle

(PECL proctitle >= 0.1.0)

setproctitle — Set the process title

Opis

void setproctitle ( string $title )

Sets the process title of the current process.

Parametry

title

The title to use as the process title.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 setproctitle() example

Running the example below will change the process title (visible with ps a for example).

<?php
setproctitle("myscript");
?>

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

$ ps a
  PID TTY      STAT   TIME COMMAND
 1168 pts/3    S      0:00 myscript

Zobacz też:

  • pcntl_fork() - Forks the currently running process
  • setthreadtitle() - Set the thread title
Proctitle Funkcje
setthreadtitle
Proctitle Funkcje


Set the thread title

setproctitle
xattr
Proctitle Funkcje
PHP Manual

setthreadtitle

(PECL proctitle >= 0.1.2)

setthreadtitle — Set the thread title

Opis

bool setthreadtitle ( string $title )

Sets the thread title.

Parametry

title

The title to use as the thread title.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 setthreadtitle() example

Running the example below will change the thread title (visible with ps c for example).

<?php
setthreadtitle("myscript");
?>

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

$ ps c
  PID TTY      STAT   TIME COMMAND
 1178 pts/3    S      0:00 myscript

Zobacz też:

  • pcntl_fork() - Forks the currently running process
  • setproctitle() - Set the process title
setproctitle
xattr
Proctitle Funkcje


xattr

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • xattr Funkcje
    • xattr_get — Get an extended attribute
    • xattr_list — Get a list of extended attributes
    • xattr_remove — Remove an extended attribute
    • xattr_set — Set an extended attribute
    • xattr_supported — Check if filesystem supports extended attributes
setthreadtitle
Wstęp
Rozszerzenia powiązane z systemem plików


Wstęp

The xattr extension allows for the manipulation of extended attributes on a filesystem.

xattr
Instalacja/Konfiguracja
xattr


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
xattr


Wymagania

To use xattr, you will need libattr installed. It is available at » http://oss.sgi.com/projects/xfs/.

Informacja:

These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are ext2, ext3, reiserfs, jfs, and xfs.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/xattr.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

XATTR_ROOT (integer)
Set attribute in root (trusted) namespace. Requires root privileges.
XATTR_DONTFOLLOW (integer)
Do not follow the symbolic link but operate on symbolic link itself.
XATTR_CREATE (integer)
Function will fail if extended attribute already exists.
XATTR_REPLACE (integer)
Function will fail if extended attribute doesn't exist.
Typy zasobów
xattr Funkcje
xattr


xattr Funkcje

Spis treści

  • xattr_get — Get an extended attribute
  • xattr_list — Get a list of extended attributes
  • xattr_remove — Remove an extended attribute
  • xattr_set — Set an extended attribute
  • xattr_supported — Check if filesystem supports extended attributes
Stałe predefiniowane
xattr_get
xattr


Get an extended attribute

xattr Funkcje
xattr_list
xattr Funkcje
PHP Manual

xattr_get

(PECL xattr >= 0.9.0)

xattr_get — Get an extended attribute

Opis

string xattr_get ( string $filename , string $name [, int $flags = 0 ] )

This function gets the value of an extended attribute of a file.

Rozszerzone atrybuty mają dwie różne przestrzenie nazw: przestrzeń użytkownika i roota. Przestrzeń użytkownika dostępna jest dla wszystkich użytkowników, podczas gdy przestrzeń roota dostępna jest tylko dla użytkownika z uprawnieniami superużytkownika. xattr domyślne działa w przestrzeni użytkownika, ale można to zmienić używając argumentu flags.

Parametry

filename

The file from which we get the attribute.

name

The name of the attribute.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Zwracane wartości

Returns a string containing the value or FALSE if the attribute doesn't exist.

Przykłady

Przykład #1 Checks if system administrator has signed the file

<?php
$file = '/usr/local/sbin/some_binary';
$signature = xattr_get($file, 'Root signature', XATTR_ROOT);

/* ... check if $signature is valid ... */

?>

Zobacz też:

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_remove() - Remove an extended attribute

xattr Funkcje
xattr_list
xattr Funkcje


Get a list of extended attributes

xattr_get
xattr_remove
xattr Funkcje
PHP Manual

xattr_list

(PECL xattr >= 0.9.0)

xattr_list — Get a list of extended attributes

Opis

array xattr_list ( string $filename [, int $flags = 0 ] )

This functions gets a list of names of extended attributes of a file.

Rozszerzone atrybuty mają dwie różne przestrzenie nazw: przestrzeń użytkownika i roota. Przestrzeń użytkownika dostępna jest dla wszystkich użytkowników, podczas gdy przestrzeń roota dostępna jest tylko dla użytkownika z uprawnieniami superużytkownika. xattr domyślne działa w przestrzeni użytkownika, ale można to zmienić używając argumentu flags.

Parametry

filename

The path of the file.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Zwracane wartości

This function returns an array with names of extended attributes.

Przykłady

Przykład #1 Prints names of all extended attributes of file

<?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);

echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
    printf("%s\n", $attr_name);
}

?>

Zobacz też:

  • xattr_get() - Get an extended attribute

xattr_get
xattr_remove
xattr Funkcje


Remove an extended attribute

xattr_list
xattr_set
xattr Funkcje
PHP Manual

xattr_remove

(PECL xattr >= 0.9.0)

xattr_remove — Remove an extended attribute

Opis

bool xattr_remove ( string $filename , string $name [, int $flags = 0 ] )

This function removes an extended attribute of a file.

Rozszerzone atrybuty mają dwie różne przestrzenie nazw: przestrzeń użytkownika i roota. Przestrzeń użytkownika dostępna jest dla wszystkich użytkowników, podczas gdy przestrzeń roota dostępna jest tylko dla użytkownika z uprawnieniami superużytkownika. xattr domyślne działa w przestrzeni użytkownika, ale można to zmienić używając argumentu flags.

Parametry

filename

The file from which we remove the attribute.

name

The name of the attribute to remove.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Removes all extended attributes of a file

<?php
$file = 'some_file';
$attributes = xattr_list($file);

foreach ($attributes as $attr_name) {
    xattr_remove($file, $attr_name);
}
?>

Zobacz też:

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_get() - Get an extended attribute

xattr_list
xattr_set
xattr Funkcje


Set an extended attribute

xattr_remove
xattr_supported
xattr Funkcje
PHP Manual

xattr_set

(PECL xattr >= 0.9.0)

xattr_set — Set an extended attribute

Opis

bool xattr_set ( string $filename , string $name , string $value [, int $flags = 0 ] )

This function sets the value of an extended attribute of a file.

Rozszerzone atrybuty mają dwie różne przestrzenie nazw: przestrzeń użytkownika i roota. Przestrzeń użytkownika dostępna jest dla wszystkich użytkowników, podczas gdy przestrzeń roota dostępna jest tylko dla użytkownika z uprawnieniami superużytkownika. xattr domyślne działa w przestrzeni użytkownika, ale można to zmienić używając argumentu flags.

Parametry

filename

The file in which we set the attribute.

name

The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the flags parameter.

value

The value of the attribute.

flags

Supported xattr flags
XATTR_CREATE | Function will fail if extended attribute already exists.
XATTR_REPLACE | Function will fail if extended attribute doesn't exist.
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Sets extended attributes on .wav file

<?php
$file = 'my_favourite_song.wav';
xattr_set($file, 'Artist', 'Someone');
xattr_set($file, 'My ranking', 'Good');
xattr_set($file, 'Listen count', '34');

/* ... other code ... */

printf("You've played this song %d times", xattr_get($file, 'Listen count'));
?>

Zobacz też:

  • xattr_get() - Get an extended attribute
  • xattr_remove() - Remove an extended attribute

xattr_remove
xattr_supported
xattr Funkcje


Check if filesystem supports extended attributes

xattr_set
xdiff
xattr Funkcje
PHP Manual

xattr_supported

(PECL xattr >= 1.0.0)

xattr_supported — Check if filesystem supports extended attributes

Opis

bool xattr_supported ( string $filename [, int $flags = 0 ] )

This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.

Parametry

filename

The path of the tested file.

flags

Supported xattr flags
XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.

Zwracane wartości

This function returns TRUE if filesystem supports extended attributes, FALSE if it doesn't and NULL if it can't be determined (for example wrong path or lack of permissions to file).

Przykłady

Przykład #1 xattr_supported() example

The following code checks if we can use extended attributes.

<?php
$file = 'some_file';

if (xattr_supported($file)) {
    /* ... make use of some xattr_* functions ... */
}

?>

Zobacz też:

  • xattr_get() - Get an extended attribute
  • xattr_list() - Get a list of extended attributes

xattr_set
xdiff
xattr Funkcje


xdiff

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • xdiff Funkcje
    • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_file_bdiff — Make binary diff of two files
    • xdiff_file_bpatch — Patch a file with a binary diff
    • xdiff_file_diff_binary — Alias of xdiff_file_bdiff
    • xdiff_file_diff — Make unified diff of two files
    • xdiff_file_merge3 — Merge 3 files into one
    • xdiff_file_patch_binary — Alias of xdiff_file_bpatch
    • xdiff_file_patch — Patch a file with an unified diff
    • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_string_bdiff — Make binary diff of two strings
    • xdiff_string_bpatch — Patch a string with a binary diff
    • xdiff_string_diff_binary — Alias of xdiff_string_bdiff
    • xdiff_string_diff — Make unified diff of two strings
    • xdiff_string_merge3 — Merge 3 strings into one
    • xdiff_string_patch_binary — Alias of xdiff_string_bpatch
    • xdiff_string_patch — Patch a string with an unified diff
    • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
xattr_supported
Wstęp
Rozszerzenia powiązane z systemem plików


Wstęp

xdiff extension enables you to create and apply patch files containing differences between different revisions of files.

This extension supports two modes of operation - on strings and on files, as well as two different patch formats - unified and binary. Unified patches are excellent for text files as they are human-readable and easy to review. For binary files like archives or images, binary patches will be adequate choice as they are binary safe and handle non-printable characters well.

Starting from version 1.5.0 there are two different sets of functions for generating binary patches. New functions - xdiff_string_rabdiff() and xdiff_file_rabdiff() generate output compatible with older functions but are typically faster and generate smaller results. For more details about methods of generating binary patches and differences between them, please check » libxdiff website.

This extension uses libxdiff to implement these functions. Please see » http://www.xmailserver.org/xdiff-lib.html for more information.

xdiff
Instalacja/Konfiguracja
xdiff


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
xdiff


Wymagania

To use xdiff, you will need libxdiff installed, available on the libxdiff homepage » http://www.xmailserver.org/xdiff-lib.html.

Informacja:

You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/xdiff.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

XDIFF_PATCH_NORMAL (integer)
This flag indicates that xdiff_string_patch() and xdiff_file_patch() functions should create result by applying patch to original content thus creating newer version of file. This is the default mode of operation.
XDIFF_PATCH_REVERSE (integer)
This flag indicated that xdiff_string_patch() and xdiff_file_patch() functions should create result by reversing patch changed from newer content thus creating original version.
Typy zasobów
xdiff Funkcje
xdiff


xdiff Funkcje

Spis treści

  • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_file_bdiff — Make binary diff of two files
  • xdiff_file_bpatch — Patch a file with a binary diff
  • xdiff_file_diff_binary — Alias of xdiff_file_bdiff
  • xdiff_file_diff — Make unified diff of two files
  • xdiff_file_merge3 — Merge 3 files into one
  • xdiff_file_patch_binary — Alias of xdiff_file_bpatch
  • xdiff_file_patch — Patch a file with an unified diff
  • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_string_bdiff — Make binary diff of two strings
  • xdiff_string_bpatch — Patch a string with a binary diff
  • xdiff_string_diff_binary — Alias of xdiff_string_bdiff
  • xdiff_string_diff — Make unified diff of two strings
  • xdiff_string_merge3 — Merge 3 strings into one
  • xdiff_string_patch_binary — Alias of xdiff_string_bpatch
  • xdiff_string_patch — Patch a string with an unified diff
  • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
Stałe predefiniowane
xdiff_file_bdiff_size
xdiff


Read a size of file created by applying a binary diff

xdiff Funkcje
xdiff_file_bdiff
xdiff Funkcje
PHP Manual

xdiff_file_bdiff_size

(PECL xdiff >= 0.2.0)

xdiff_file_bdiff_size — Read a size of file created by applying a binary diff

Opis

int xdiff_file_bdiff_size ( string $file )

Returns a size of a result file that would be created after applying binary patch from file file to the original file.

Parametry

file

The path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Zwracane wartości

Returns the size of file that would be created.

Przykłady

Przykład #1 xdiff_file_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$length = xdiff_string_bdiff_size('file.bdiff');
echo "Resulting file will be $length bytes long";
?>

Zobacz też:

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff Funkcje
xdiff_file_bdiff
xdiff Funkcje


Make binary diff of two files

xdiff_file_bdiff_size
xdiff_file_bpatch
xdiff Funkcje
PHP Manual

xdiff_file_bdiff

(PECL xdiff >= 0.2.0)

xdiff_file_bdiff — Make binary diff of two files

Opis

bool xdiff_file_bdiff ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

Parametry

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 xdiff_file_bdiff() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_bdiff($old_version, $new_version, 'my_script.bdiff');
?>

Notatki

Informacja:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

Zobacz też:

  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff_file_bdiff_size
xdiff_file_bpatch
xdiff Funkcje


Patch a file with a binary diff

xdiff_file_bdiff
xdiff_file_diff_binary
xdiff Funkcje
PHP Manual

xdiff_file_bpatch

(PECL xdiff >= 0.2.0)

xdiff_file_bpatch — Patch a file with a binary diff

Opis

bool xdiff_file_bpatch ( string $file , string $patch , string $dest )

Patches a file with a binary patch and stores the result in a file dest. This function accepts patches created both via xdiff_file_bdiff() and xdiff_file_rabdiff() functions or their string counterparts.

Parametry

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 xdiff_file_bpatch() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_bpatch($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
   echo "File patched";
} else {
   echo "File couldn't be patched";
}

?>

Notatki

Informacja:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

Zobacz też:

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_bdiff
xdiff_file_diff_binary
xdiff Funkcje


Alias of xdiff_file_bdiff

xdiff_file_bpatch
xdiff_file_diff
xdiff Funkcje
PHP Manual

xdiff_file_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_file_diff_binary — Alias of xdiff_file_bdiff

Opis

bool xdiff_file_diff_binary ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_file_bdiff().

Parametry

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 xdiff_file_diff_binary() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?>

Notatki

Informacja:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

Zobacz też:

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff_file_bpatch
xdiff_file_diff
xdiff Funkcje


Make unified diff of two files

xdiff_file_diff_binary
xdiff_file_merge3
xdiff Funkcje
PHP Manual

xdiff_file_diff

(PECL xdiff >= 0.2.0)

xdiff_file_diff — Make unified diff of two files

Opis

bool xdiff_file_diff ( string $old_file , string $new_file , string $dest [, int $context = 3 [, bool $minimal = false ]] )

Makes an unified diff containing differences between old_file and new_file and stores it in dest file. The resulting file is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

Parametry

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file.

context

Indicates how many lines of context you want to include in diff result.

minimal

Set this parameter to TRUE if you want to minimalize size of the result (can take a long time).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 xdiff_file_diff() example

The following code makes unified diff of two php files with context length of 2.

<?php
$old_version = 'my_script.php';
$new_version = 'my_new_script.php';

xdiff_file_diff($old_version, $new_version, 'my_script.diff', 2);
?>

Notatki

Informacja:

This function doesn't work well with binary files. To make diff of binary files use xdiff_file_bdiff()/xdiff_file_rabdiff() function.

Zobacz też:

  • xdiff_file_patch() - Patch a file with an unified diff

xdiff_file_diff_binary
xdiff_file_merge3
xdiff Funkcje


Merge 3 files into one

xdiff_file_diff
xdiff_file_patch_binary
xdiff Funkcje
PHP Manual

xdiff_file_merge3

(PECL xdiff >= 0.2.0)

xdiff_file_merge3 — Merge 3 files into one

Opis

mixed xdiff_file_merge3 ( string $old_file , string $new_file1 , string $new_file2 , string $dest )

Merges three files into one and stores the result in a file dest. The old_file is an original version while new_file1 and new_file2 are modified versions of an original.

Parametry

old_file

Path to the first file. It acts as "old" file.

new_file1

Path to the second file. It acts as modified version of old_file.

new_file2

Path to the third file. It acts as modified version of old_file.

dest

Path of the resulting file, containing merged changed from both new_file1 and new_file2.

Zwracane wartości

Returns TRUE if merge was successful, string with rejected chunks if it was not or FALSE if an internal error happened.

Przykłady

Przykład #1 xdiff_file_merge3() example

The following code merges three files into one.

<?php
$old_version = 'original_script.php';
$fix1 = 'script_with_fix1.php';
$fix2 = 'script_with_fix2.php';

$errors = xdiff_file_merge3($old_version, $fix1, $fix2, 'fixed_script.php');
if (is_string($errors)) {
    echo "Rejects:\n";
    echo $errors;
}
?>

Zobacz też:

  • xdiff_string_merge3() - Merge 3 strings into one

xdiff_file_diff
xdiff_file_patch_binary
xdiff Funkcje


Alias of xdiff_file_bpatch

xdiff_file_merge3
xdiff_file_patch
xdiff Funkcje
PHP Manual

xdiff_file_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_file_patch_binary — Alias of xdiff_file_bpatch

Opis

bool xdiff_file_patch_binary ( string $file , string $patch , string $dest )

Patches a file with a binary patch and stores the result in a file dest. This function accepts patches created both via xdiff_file_bdiff() or xdiff_file_rabdiff() functions or their string counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_file_bpatch().

Parametry

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 xdiff_file_patch_binary() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
   echo "File patched";
} else {
   echo "File couldn't be patched";
}

?>

Notatki

Informacja:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

Zobacz też:

  • xdiff_string_patch_binary() - Alias of xdiff_string_bpatch

xdiff_file_merge3
xdiff_file_patch
xdiff Funkcje


Patch a file with an unified diff

xdiff_file_patch_binary
xdiff_file_rabdiff
xdiff Funkcje
PHP Manual

xdiff_file_patch

(PECL xdiff >= 0.2.0)

xdiff_file_patch — Patch a file with an unified diff

Opis

mixed xdiff_file_patch ( string $file , string $patch , string $dest [, int $flags = DIFF_PATCH_NORMAL ] )

Patches a file with a patch and stores the result in a file. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation.

Parametry

file

The original file.

patch

The unified patch file. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

dest

Path of the resulting file.

flags

Can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

Zwracane wartości

Returns FALSE if an internal error happened, string with rejected chunks if patch couldn't be applied or TRUE if patch has been successfully applied.

Przykłady

Przykład #1 xdiff_file_patch() example

The following code applies unified diff to a file.

<?php
$old_version = 'my_script-1.0.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($old_version, $patch, 'my_script-1.1.php');
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?>

Przykład #2 Patch reversing example

The following code reverses a patch.

<?php
$new_version = 'my_script-1.1.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($new_version, $patch, 'my_script-1.0.php', XDIFF_PATCH_REVERSE);
if (is_string($errors)) {
   echo "Rejects:\n";
   echo $errors;
}

?>

Zobacz też:

  • xdiff_file_diff() - Make unified diff of two files

xdiff_file_patch_binary
xdiff_file_rabdiff
xdiff Funkcje


Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_patch
xdiff_string_bdiff_size
xdiff Funkcje
PHP Manual

xdiff_file_rabdiff

(PECL xdiff >= 0.2.0)

xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

Opis

bool xdiff_file_rabdiff ( string $old_file , string $new_file , string $dest )

Makes a binary diff of two files and stores the result in a patch file. The difference between this function and xdiff_file_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

Parametry

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 xdiff_file_rabdiff() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_rabdiff($old_version, $new_version, 'my_script.bdiff');
?>

Notatki

Informacja:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

Zobacz też:

  • xdiff_file_bpatch() - Patch a file with a binary diff

xdiff_file_patch
xdiff_string_bdiff_size
xdiff Funkcje


Read a size of file created by applying a binary diff

xdiff_file_rabdiff
xdiff_string_bdiff
xdiff Funkcje
PHP Manual

xdiff_string_bdiff_size

(PECL xdiff >= 0.2.0)

xdiff_string_bdiff_size — Read a size of file created by applying a binary diff

Opis

int xdiff_string_bdiff_size ( string $patch )

Returns a size of a result file that would be created after applying binary patch to the original file.

Parametry

patch

The binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

Zwracane wartości

Returns the size of file that would be created.

Przykłady

Przykład #1 xdiff_string_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$binary_patch = file_get_contents('file.bdiff');
$length = xdiff_string_bdiff_size($binary_patch);
echo "Resulting file will be $length bytes long";
?>

Zobacz też:

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_file_rabdiff
xdiff_string_bdiff
xdiff Funkcje


Make binary diff of two strings

xdiff_string_bdiff_size
xdiff_string_bpatch
xdiff Funkcje
PHP Manual

xdiff_string_bdiff

(PECL xdiff >= 0.2.0)

xdiff_string_bdiff — Make binary diff of two strings

Opis

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Parametry

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Zwracane wartości

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

Zobacz też:

  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_string_bdiff_size
xdiff_string_bpatch
xdiff Funkcje


Patch a string with a binary diff

xdiff_string_bdiff
xdiff_string_diff_binary
xdiff Funkcje
PHP Manual

xdiff_string_bpatch

(PECL xdiff >= 0.2.0)

xdiff_string_bpatch — Patch a string with a binary diff

Opis

string xdiff_string_bpatch ( string $str , string $patch )

Patches a string str with a binary patch. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Parametry

str

The original binary string.

patch

The binary patch string.

Zwracane wartości

Returns the patched string, or FALSE on error.

Zobacz też:

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_bdiff
xdiff_string_diff_binary
xdiff Funkcje


Alias of xdiff_string_bdiff

xdiff_string_bpatch
xdiff_string_diff
xdiff Funkcje
PHP Manual

xdiff_string_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_string_diff_binary — Alias of xdiff_string_bdiff

Opis

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_string_bdiff().

Parametry

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Zwracane wartości

Returns string with result or FALSE if an internal error happened.

Zobacz też:

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_string_bpatch
xdiff_string_diff
xdiff Funkcje


Make unified diff of two strings

xdiff_string_diff_binary
xdiff_string_merge3
xdiff Funkcje
PHP Manual

xdiff_string_diff

(PECL xdiff >= 0.2.0)

xdiff_string_diff — Make unified diff of two strings

Opis

string xdiff_string_diff ( string $old_data , string $new_data [, int $context = 3 [, bool $minimal = false ]] )

Makes an unified diff containing differences between old_data string and new_data string and returns it. The resulting diff is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

Parametry

old_data

First string with data. It acts as "old" data.

new_data

Second string with data. It acts as "new" data.

context

Indicates how many lines of context you want to include in the diff result.

minimal

Set this parameter to TRUE if you want to minimalize the size of the result (can take a long time).

Zwracane wartości

Returns string with resulting diff or FALSE if an internal error happened.

Przykłady

Przykład #1 xdiff_string_diff() example

The following code makes unified diff of two articles.

<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */

$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
    echo "Differences between two articles:\n";
    echo $diff;
}

?>

Notatki

Informacja:

This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().

Zobacz też:

  • xdiff_string_patch() - Patch a string with an unified diff

xdiff_string_diff_binary
xdiff_string_merge3
xdiff Funkcje


Merge 3 strings into one

xdiff_string_diff
xdiff_string_patch_binary
xdiff Funkcje
PHP Manual

xdiff_string_merge3

(PECL xdiff >= 0.2.0)

xdiff_string_merge3 — Merge 3 strings into one

Opis

mixed xdiff_string_merge3 ( string $old_data , string $new_data1 , string $new_data2 [, string &$error ] )

Merges three strings into one and returns the result. The old_data is an original version of data while new_file1 and new_file2 are modified versions of an original. An optional error is used to pass any rejected parts during merging process.

Parametry

old_data

First string with data. It acts as "old" data.

new_data1

Second string with data. It acts as modified version of old_data.

new_data2

Third string with data. It acts as modified version of old_data.

error

If provided then rejected parts are stored inside this variable.

Zwracane wartości

Returns the merged string, FALSE if an internal error happened, or TRUE if merged string is empty.

Zobacz też:

  • xdiff_file_merge3() - Merge 3 files into one

xdiff_string_diff
xdiff_string_patch_binary
xdiff Funkcje


Alias of xdiff_string_bpatch

xdiff_string_merge3
xdiff_string_patch
xdiff Funkcje
PHP Manual

xdiff_string_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_string_patch_binary — Alias of xdiff_string_bpatch

Opis

string xdiff_string_patch_binary ( string $str , string $patch )

Patches a string str with a binary patch. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_string_bpatch().

Parametry

str

The original binary string.

patch

The binary patch string.

Zwracane wartości

Returns the patched string, or FALSE on error.

Zobacz też:

  • xdiff_string_bpatch() - Patch a string with a binary diff
  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_merge3
xdiff_string_patch
xdiff Funkcje


Patch a string with an unified diff

xdiff_string_patch_binary
xdiff_string_rabdiff
xdiff Funkcje
PHP Manual

xdiff_string_patch

(PECL xdiff >= 0.2.0)

xdiff_string_patch — Patch a string with an unified diff

Opis

string xdiff_string_patch ( string $str , string $patch [, int $flags [, string &$error ]] )

Patches a str string with an unified patch in patch parameter and returns the result. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation. Any rejected parts of the patch will be stored inside error variable if it is provided.

Parametry

str

The original string.

patch

The unified patch string. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

flags

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

error

If provided then rejected parts are stored inside this variable.

Zwracane wartości

Returns the patched string, or FALSE on error.

Przykłady

Przykład #1 xdiff_string_patch() example

The following code applies changes to some article.

<?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */

$errors = '';

$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
    echo "New article:\n";
    echo $new_article;
}

if (strlen($errors)) {
    echo "Rejects: \n";
    echo $errors;
}

?>

Zobacz też:

  • xdiff_string_diff() - Make unified diff of two strings

xdiff_string_patch_binary
xdiff_string_rabdiff
xdiff Funkcje


Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_patch
Język naturalny i obsługa kodowania znaków
xdiff Funkcje
PHP Manual

xdiff_string_rabdiff

(PECL xdiff >= 0.2.0)

xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

Opis

string xdiff_string_bdiff ( string $old_data , string $new_data )

Makes a binary diff of two strings and returns the result. The difference between this function and xdiff_string_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

Parametry

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

Zwracane wartości

Returns string with binary diff containing differences between "old" and "new" data or FALSE if an internal error occurred.

Zobacz też:

  • xdiff_string_bpatch() - Patch a string with a binary diff

xdiff_string_patch
Język naturalny i obsługa kodowania znaków
xdiff Funkcje


Język naturalny i obsługa kodowania znaków

  • Enchant — Enchant spelling library
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Enchant Funkcje
  • FriBiDi
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • FriBiDi Funkcje
  • Gettext
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Gettext Funkcje
  • iconv
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • iconv Funkcje
  • intl — Internationalization Functions
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Collator — The Collator class
    • NumberFormatter — The NumberFormatter class
    • Locale — The Locale class
    • Normalizer — The Normalizer class
    • MessageFormatter — The MessageFormatter class
    • IntlDateFormatter — The IntlDateFormatter class
    • ResourceBundle — The ResourceBundle class
    • Spoofchecker — The Spoofchecker class
    • Transliterator — The Transliterator class
    • Grapheme Funkcje
    • IDN Funkcje
    • intl Funkcje
  • Multibyte String
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Summaries of supported encodings
    • Basics of Japanese multi-byte encodings
    • HTTP Input and Output
    • Supported Character Encodings
    • Function Overloading Feature
    • PHP Character Encoding Requirements
    • Multibyte String Funkcje
  • Pspell
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Pspell Funkcje
  • Recode — GNU Recode
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Recode Funkcje
xdiff_string_rabdiff
Enchant
Opis funkcji


Enchant spelling library

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Enchant Funkcje
    • enchant_broker_describe — Enumerates the Enchant providers
    • enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free_dict — Free a dictionary resource
    • enchant_broker_free — Free the broker resource and its dictionnaries
    • enchant_broker_get_error — Returns the last error of the broker
    • enchant_broker_init — create a new broker object capable of requesting
    • enchant_broker_list_dicts — Returns a list of available dictionaries
    • enchant_broker_request_dict — create a new dictionary using a tag
    • enchant_broker_request_pwl_dict — creates a dictionary using a PWL file
    • enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
    • enchant_dict_add_to_personal — add a word to personal word list
    • enchant_dict_add_to_session — add 'word' to this spell-checking session
    • enchant_dict_check — Check whether a word is correctly spelled or not
    • enchant_dict_describe — Describes an individual dictionary
    • enchant_dict_get_error — Returns the last error of the current spelling-session
    • enchant_dict_is_in_session — whether or not 'word' exists in this spelling-session
    • enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
    • enchant_dict_store_replacement — Add a correction for a word
    • enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met
Język naturalny i obsługa kodowania znaków
Wstęp
Język naturalny i obsługa kodowania znaków


Wstęp

Enchant is the PHP binding for the » Enchant library. Enchant steps in to provide uniformity and conformity on top of all spelling libraries, and implement certain features that may be lacking in any individual provider library. Everything should "just work" for any and every definition of "just working."

Enchat supports the following backends:

  • Aspell/Pspell (intends to replace Ispell)

  • Ispell (old as sin, could be interpreted as a defacto standard)

  • MySpell/Hunspell (an OOo projects, also used by Mozilla)

  • Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")

  • Hspell (Hebrew)

  • AppleSpell (Mac OSX)

Enchant
Instalacja/Konfiguracja
Enchant


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Enchant


Wymagania

This version uses the functions of the » Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later.

Enchant also requires » Glib 2.6 or greater. Pre-compiled Windows libraries are available from » http://ftp.gnome.org/pub/gnome/binaries/win32/glib/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

This extension is bundled with PHP as of PHP 5.3.0. Before this time, enchant was a PECL extension. Users of versions prior to 5.3.0 may use the » PECL extension.

Provided the required libraries are installed, users of PHP 5.3.0 or later may enable enchant by adding the --with-enchant[=dir] option when compiling PHP.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

There are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Enchant


Przykłady

Przykład #1 Enchant Usage Example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);
    $dprovides = enchant_dict_describe($d);
    echo "dictionary $tag provides:\n";
    $wordcorrect = enchant_dict_check($d, "soong");
    print_r($dprovides);
    if (!$wordcorrect) {
        $suggs = enchant_dict_suggest($d, "soong");
        echo "Suggestions for 'soong':";
        print_r($suggs);
    }
    enchant_broker_free_dict($d);
} else {
}
enchant_broker_free($r);
?>
Stałe predefiniowane
Enchant Funkcje
Enchant


Enchant Funkcje

Spis treści

  • enchant_broker_describe — Enumerates the Enchant providers
  • enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict — Free a dictionary resource
  • enchant_broker_free — Free the broker resource and its dictionnaries
  • enchant_broker_get_error — Returns the last error of the broker
  • enchant_broker_init — create a new broker object capable of requesting
  • enchant_broker_list_dicts — Returns a list of available dictionaries
  • enchant_broker_request_dict — create a new dictionary using a tag
  • enchant_broker_request_pwl_dict — creates a dictionary using a PWL file
  • enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
  • enchant_dict_add_to_personal — add a word to personal word list
  • enchant_dict_add_to_session — add 'word' to this spell-checking session
  • enchant_dict_check — Check whether a word is correctly spelled or not
  • enchant_dict_describe — Describes an individual dictionary
  • enchant_dict_get_error — Returns the last error of the current spelling-session
  • enchant_dict_is_in_session — whether or not 'word' exists in this spelling-session
  • enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
  • enchant_dict_store_replacement — Add a correction for a word
  • enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met
Przykłady
enchant_broker_describe
Enchant


Enumerates the Enchant providers

Enchant Funkcje
enchant_broker_dict_exists
Enchant Funkcje
PHP Manual

enchant_broker_describe

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0)

enchant_broker_describe — Enumerates the Enchant providers

Opis

array enchant_broker_describe ( resource $broker )

Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().

Parametry

broker

Broker resource

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 List the backends provided by the given broker

<?php
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

?>

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

Current broker provides the following backend(s):
Array
(
    [0] => Array
        (
            [name] => aspell
            [desc] => Aspell Provider
            [file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [1] => Array
        (
            [name] => hspell
            [desc] => Hspell Provider
            [file] => /usr/lib/enchant/libenchant_hspell.so
        )

    [2] => Array
        (
            [name] => ispell
            [desc] => Ispell Provider
            [file] => /usr/lib/enchant/libenchant_ispell.so
        )

    [3] => Array
        (
            [name] => myspell
            [desc] => Myspell Provider
            [file] => /usr/lib/enchant/libenchant_myspell.so
        )

)

Enchant Funkcje
enchant_broker_dict_exists
Enchant Funkcje


Whether a dictionary exists or not. Using non-empty tag

enchant_broker_describe
enchant_broker_free_dict
Enchant Funkcje
PHP Manual

enchant_broker_dict_exists

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag

Opis

bool enchant_broker_dict_exists ( resource $broker , string $tag )

Tells if a dictionary exists or not, using a non-empty tags

Parametry

broker

Broker resource

tag

non-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.

Zwracane wartości

Returns TRUE when the tag exist or FALSE when not.

Przykłady

Przykład #1 A enchant_broker_dict_exists() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
    echo $tag . " dictionary found.\n";
}
?>

Zobacz też:

  • enchant_broker_describe() - Enumerates the Enchant providers

enchant_broker_describe
enchant_broker_free_dict
Enchant Funkcje


Free a dictionary resource

enchant_broker_dict_exists
enchant_broker_free
Enchant Funkcje
PHP Manual

enchant_broker_free_dict

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_free_dict — Free a dictionary resource

Opis

bool enchant_broker_free_dict ( resource $dict )

Free a dictionary resource.

Parametry

dict

Dictionary resource.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • enchant_broker_request_dict() - create a new dictionary using a tag
  • enchant_broker_request_pwl_dict() - creates a dictionary using a PWL file

enchant_broker_dict_exists
enchant_broker_free
Enchant Funkcje


Free the broker resource and its dictionnaries

enchant_broker_free_dict
enchant_broker_get_error
Enchant Funkcje
PHP Manual

enchant_broker_free

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_free — Free the broker resource and its dictionnaries

Opis

bool enchant_broker_free ( resource $broker )

Free a broker resource with all its dictionaries.

Parametry

broker

Broker resource

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • enchant_broker_init() - create a new broker object capable of requesting

enchant_broker_free_dict
enchant_broker_get_error
Enchant Funkcje


Returns the last error of the broker

enchant_broker_free
enchant_broker_init
Enchant Funkcje
PHP Manual

enchant_broker_get_error

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_get_error — Returns the last error of the broker

Opis

string enchant_broker_get_error ( resource $broker )

Returns the last error which occurred in this broker.

Parametry

broker

Broker resource.

Zwracane wartości

Return the msg string if an error was found or FALSE

enchant_broker_free
enchant_broker_init
Enchant Funkcje


create a new broker object capable of requesting

enchant_broker_get_error
enchant_broker_list_dicts
Enchant Funkcje
PHP Manual

enchant_broker_init

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_init — create a new broker object capable of requesting

Opis

resource enchant_broker_init ( void )

Parametry

Zwracane wartości

Returns a broker resource on success or FALSE.

Zobacz też:

  • enchant_broker_free() - Free the broker resource and its dictionnaries

enchant_broker_get_error
enchant_broker_list_dicts
Enchant Funkcje


Returns a list of available dictionaries

enchant_broker_init
enchant_broker_request_dict
Enchant Funkcje
PHP Manual

enchant_broker_list_dicts

(PHP 5 >= 5.3.0, PECL enchant >= 1.0.1)

enchant_broker_list_dicts — Returns a list of available dictionaries

Opis

mixed enchant_broker_list_dicts ( resource $broker )

Returns a list of available dictionaries with their details.

Parametry

broker

Broker resource

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 List all available dictionaries for one broker

<?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?>

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

Array
(
    [0] => Array
        (
            [lang_tag] => de
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [1] => Array
        (
            [lang_tag] => de_DE
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [3] => Array
        (
            [lang_tag] => en
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [4] => Array
        (
            [lang_tag] => en_GB
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [5] => Array
        (
            [lang_tag] => en_US
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [6] => Array
        (
            [lang_tag] => hi_IN
            [provider_name] => myspell
            [provider_desc] => Myspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_myspell.so
        )

)

Zobacz też:

  • enchant_broker_describe() - Enumerates the Enchant providers

enchant_broker_init
enchant_broker_request_dict
Enchant Funkcje


create a new dictionary using a tag

enchant_broker_list_dicts
enchant_broker_request_pwl_dict
Enchant Funkcje
PHP Manual

enchant_broker_request_dict

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_request_dict — create a new dictionary using a tag

Opis

resource enchant_broker_request_dict ( resource $broker , string $tag )

create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)

Parametry

broker

Broker resource

tag

A tag describing the locale, for example en_US, de_DE

Zwracane wartości

Returns a dictionary resource on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 A enchant_broker_request_dict() example

Check if a dictionary exists using enchant_broker_dict_exists() and request it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
    $dict = enchant_broker_request_dict($r, $tag);
}
?>

Zobacz też:

  • enchant_dict_describe() - Describes an individual dictionary
  • enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict() - Free a dictionary resource

enchant_broker_list_dicts
enchant_broker_request_pwl_dict
Enchant Funkcje


creates a dictionary using a PWL file

enchant_broker_request_dict
enchant_broker_set_ordering
Enchant Funkcje
PHP Manual

enchant_broker_request_pwl_dict

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_request_pwl_dict — creates a dictionary using a PWL file

Opis

resource enchant_broker_request_pwl_dict ( resource $broker , string $filename )

Creates a dictionary using a PWL file. A PWL file is personal word file one word per line.

Parametry

broker

Broker resource

filename

Path to the PWL file.

Zwracane wartości

Returns a dictionary resource on success lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • enchant_dict_describe() - Describes an individual dictionary
  • enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict() - Free a dictionary resource

enchant_broker_request_dict
enchant_broker_set_ordering
Enchant Funkcje


Declares a preference of dictionaries to use for the language

enchant_broker_request_pwl_dict
enchant_dict_add_to_personal
Enchant Funkcje
PHP Manual

enchant_broker_set_ordering

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language

Opis

bool enchant_broker_set_ordering ( resource $broker , string $tag , string $ordering )

Declares a preference of dictionaries to use for the language described/referred to by 'tag'. The ordering is a comma delimited list of provider names. As a special exception, the "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

Parametry

broker

Broker resource

tag

Language tag. The special "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

ordering

Comma delimited list of provider names

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

enchant_broker_request_pwl_dict
enchant_dict_add_to_personal
Enchant Funkcje


add a word to personal word list

enchant_broker_set_ordering
enchant_dict_add_to_session
Enchant Funkcje
PHP Manual

enchant_dict_add_to_personal

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_add_to_personal — add a word to personal word list

Opis

void enchant_dict_add_to_personal ( resource $dict , string $word )

Add a word to personal word list of the given dictionary.

Parametry

dict

Dictionary resource

word

The word to add

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • enchant_broker_request_pwl_dict() - creates a dictionary using a PWL file
  • enchant_broker_request_dict() - create a new dictionary using a tag

enchant_broker_set_ordering
enchant_dict_add_to_session
Enchant Funkcje


add 'word' to this spell-checking session

enchant_dict_add_to_personal
enchant_dict_check
Enchant Funkcje
PHP Manual

enchant_dict_add_to_session

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_add_to_session — add 'word' to this spell-checking session

Opis

void enchant_dict_add_to_session ( resource $dict , string $word )

Add a word to the given dictionary. It will be added only for the active spell-checking session.

Parametry

dict

Dictionary resource

word

The word to add

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • enchant_broker_request_dict() - create a new dictionary using a tag

enchant_dict_add_to_personal
enchant_dict_check
Enchant Funkcje


Check whether a word is correctly spelled or not

enchant_dict_add_to_session
enchant_dict_describe
Enchant Funkcje
PHP Manual

enchant_dict_check

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_check — Check whether a word is correctly spelled or not

Opis

bool enchant_dict_check ( resource $dict , string $word )

If the word is correctly spelled return TRUE, otherwise return FALSE

Parametry

dict

Dictionary resource

word

The word to check

Zwracane wartości

Returns TRUE if the word is spelled correctly, FALSE if not.

enchant_dict_add_to_session
enchant_dict_describe
Enchant Funkcje


Describes an individual dictionary

enchant_dict_check
enchant_dict_get_error
Enchant Funkcje
PHP Manual

enchant_dict_describe

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_describe — Describes an individual dictionary

Opis

mixed enchant_dict_describe ( resource $dict )

Returns the details of the dictionary.

Parametry

dict

Dictinaray resource

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A enchant_dict_describe() example

Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
    $dict = enchant_broker_request_dict($r, $tag);
    $dict_details = enchant_dict_describe($dict);
    print_r($dict_details);
}
?>

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

Array
(
    [lang] => en_US
    [name] => aspell
    [desc] => Aspell Provider
    [file] => /usr/lib/enchant/libenchant_aspell.so
)

enchant_dict_check
enchant_dict_get_error
Enchant Funkcje


Returns the last error of the current spelling-session

enchant_dict_describe
enchant_dict_is_in_session
Enchant Funkcje
PHP Manual

enchant_dict_get_error

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_get_error — Returns the last error of the current spelling-session

Opis

string enchant_dict_get_error ( resource $dict )

Returns the last error of the current spelling-session

Parametry

dict

Dictinaray resource

Zwracane wartości

Returns the error message as string or FALSE if no error occurred.

enchant_dict_describe
enchant_dict_is_in_session
Enchant Funkcje


whether or not 'word' exists in this spelling-session

enchant_dict_get_error
enchant_dict_quick_check
Enchant Funkcje
PHP Manual

enchant_dict_is_in_session

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_is_in_session — whether or not 'word' exists in this spelling-session

Opis

bool enchant_dict_is_in_session ( resource $dict , string $word )

Tells whether or not a word already exists in the current session.

Parametry

dict

Dictionary resource

word

The word to lookup

Zwracane wartości

Returns TRUE if the word exists or FALSE

Zobacz też:

  • enchant_dict_add_to_session() - add 'word' to this spell-checking session

enchant_dict_get_error
enchant_dict_quick_check
Enchant Funkcje


Check the word is correctly spelled and provide suggestions

enchant_dict_is_in_session
enchant_dict_store_replacement
Enchant Funkcje
PHP Manual

enchant_dict_quick_check

(PHP 5 >= 5.3.0, PECL enchant:0.2.0-1.0.1)

enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions

Opis

bool enchant_dict_quick_check ( resource $dict , string $word [, array &$suggestions ] )

If the word is correctly spelled return TRUE, otherwise return FALSE, if suggestions variable is provided, fill it with spelling alternatives.

Parametry

dict

Dictionary resource

word

The word to check

suggestions

If the word is not correctly spelled, this variable will contain an array of suggestions.

Zwracane wartości

Returns TRUE if the word is correctly spelled or FALSE

Przykłady

Przykład #1 A enchant_dict_quick_check() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();

if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);
    enchant_dict_quick_check($d, 'soong', $suggs);
    print_r($suggs);
}
?>

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

Array
(
    [0] => song
    [1] => snog
    [2] => soon
    [3] => Sang
    [4] => Sung
    [5] => sang
    [6] => sung
    [7] => sponge
    [8] => spongy
    [9] => snag
    [10] => snug
    [11] => sonic
    [12] => sing
    [13] => songs
    [14] => Son
    [15] => Sonja
    [16] => Synge
    [17] => son
    [18] => Sejong
    [19] => sarong
    [20] => sooner
    [21] => Sony
    [22] => sown
    [23] => scone
    [24] => song's
)

Zobacz też:

  • enchant_dict_check() - Check whether a word is correctly spelled or not
  • enchant_dict_suggest() - Will return a list of values if any of those pre-conditions are not met

enchant_dict_is_in_session
enchant_dict_store_replacement
Enchant Funkcje


Add a correction for a word

enchant_dict_quick_check
enchant_dict_suggest
Enchant Funkcje
PHP Manual

enchant_dict_store_replacement

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_store_replacement — Add a correction for a word

Opis

void enchant_dict_store_replacement ( resource $dict , string $mis , string $cor )

Add a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list.

Parametry

dict

Dictionary resource

mis

The work to fix

cor

The correct word

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

enchant_dict_quick_check
enchant_dict_suggest
Enchant Funkcje


Will return a list of values if any of those pre-conditions are not met

enchant_dict_store_replacement
FriBiDi
Enchant Funkcje
PHP Manual

enchant_dict_suggest

(PHP 5 >= 5.3.0, PECL enchant >= 0.1.0 )

enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met

Opis

array enchant_dict_suggest ( resource $dict , string $word )

Parametry

dict

Dictionary resource

word

Word to use for the suggestions.

Zwracane wartości

Will returns an array of suggestions if the word is bad spelled.

Przykłady

Przykład #1 A enchant_dict_suggest() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
    $d = enchant_broker_request_dict($r, $tag);

    $wordcorrect = enchant_dict_check($d, "soong");
    if (!$wordcorrect) {
        $suggs = enchant_dict_suggest($d, "soong");
        echo "Suggestions for 'soong':";
        print_r($suggs);
    }
    enchant_broker_free_dict($d);
}
enchant_broker_free($r);
?>

Zobacz też:

  • enchant_dict_check() - Check whether a word is correctly spelled or not
  • enchant_dict_quick_check() - Check the word is correctly spelled and provide suggestions

enchant_dict_store_replacement
FriBiDi
Enchant Funkcje


FriBiDi

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • FriBiDi Funkcje
    • fribidi_log2vis — Convert a logical string to a visual one
enchant_dict_suggest
Wstęp
Język naturalny i obsługa kodowania znaków


Wstęp

FriBiDi is a free implementation of the » Unicode Bidirectional Algorithm.

FriBiDi
Instalacja/Konfiguracja
FriBiDi


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
FriBiDi


Wymagania

You must download and install the » FriBiDi package.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/fribidi.

In order to use these functions you must compile PHP with Fribidi support by using the --with-fribidi[=DIR] configure option.

Windows users will enable php_fribidi.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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

FRIBIDI_CHARSET_UTF8 (integer)
Unicode
FRIBIDI_CHARSET_8859_6 (integer)
Arabic
FRIBIDI_CHARSET_8859_8 (integer)
Hebrew
FRIBIDI_CHARSET_CP1255 (integer)
Hebrew/Yiddish
FRIBIDI_CHARSET_CP1256 (integer)
Arabic
FRIBIDI_CHARSET_ISIRI_3342 (integer)
Persian
FRIBIDI_CHARSET_CAP_RTL (integer)
Used for test purposes, will treat CAPS as non-English letters
FRIBIDI_RTL (integer)
Right to left
FRIBIDI_LTR (integer)
Left to right
FRIBIDI_AUTO (integer)
Autodetect the base direction
Typy zasobów
FriBiDi Funkcje
FriBiDi


FriBiDi Funkcje

Spis treści

  • fribidi_log2vis — Convert a logical string to a visual one
Stałe predefiniowane
fribidi_log2vis
FriBiDi


Convert a logical string to a visual one

FriBiDi Funkcje
Gettext
FriBiDi Funkcje
PHP Manual

fribidi_log2vis

(PHP 4 >= 4.0.4 and PHP 4 <= 4.1.0, PECL fribidi >= 1.0)

fribidi_log2vis — Convert a logical string to a visual one

Opis

string fribidi_log2vis ( string $str , string $direction , int $charset )

Converts a logical string to a visual one.

Parametry

str

The logical string.

direction

One of FRIBIDI_RTL, FRIBIDI_LTR or FRIBIDI_AUTO.

charset

One of the FRIBIDI_CHARSET_XXX constants.

Zwracane wartości

Returns the visual string on success lub FALSE w przypadku niepowodzenia.

FriBiDi Funkcje
Gettext
FriBiDi Funkcje


Gettext

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Gettext Funkcje
    • bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
    • bindtextdomain — Sets the path for a domain
    • dcgettext — Overrides the domain for a single lookup
    • dcngettext — Plural version of dcgettext
    • dgettext — Override the current domain
    • dngettext — Plural version of dgettext
    • gettext — Lookup a message in the current domain
    • ngettext — Plural version of gettext
    • textdomain — Sets the default domain
fribidi_log2vis
Wstęp
Język naturalny i obsługa kodowania znaków


Wstęp

The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at » http://www.gnu.org/software/gettext/manual/gettext.html.

Gettext
Instalacja/Konfiguracja
Gettext


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Gettext


Wymagania

To use these functions you must download and install the GNU gettext package from » http://www.gnu.org/software/gettext/gettext.html

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Gettext Funkcje
Gettext


Gettext Funkcje

Spis treści

  • bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
  • bindtextdomain — Sets the path for a domain
  • dcgettext — Overrides the domain for a single lookup
  • dcngettext — Plural version of dcgettext
  • dgettext — Override the current domain
  • dngettext — Plural version of dgettext
  • gettext — Lookup a message in the current domain
  • ngettext — Plural version of gettext
  • textdomain — Sets the default domain
Stałe predefiniowane
bind_textdomain_codeset
Gettext


Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Gettext Funkcje
bindtextdomain
Gettext Funkcje
PHP Manual

bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5)

bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Opis

string bind_textdomain_codeset ( string $domain , string $codeset )

With bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.

Parametry

domain

The domain

codeset

The code set

Zwracane wartości

A string on success.

Gettext Funkcje
bindtextdomain
Gettext Funkcje


Sets the path for a domain

bind_textdomain_codeset
dcgettext
Gettext Funkcje
PHP Manual

bindtextdomain

(PHP 4, PHP 5)

bindtextdomain — Sets the path for a domain

Opis

string bindtextdomain ( string $domain , string $directory )

The bindtextdomain() function sets the path for a domain.

Parametry

domain

The domain

directory

The directory path

Zwracane wartości

The full pathname for the domain currently being set.

Przykłady

Przykład #1 bindtextdomain() example

<?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');

?>

Powyższy przykład wyświetli:

/usr/share/myapp/locale

bind_textdomain_codeset
dcgettext
Gettext Funkcje


Overrides the domain for a single lookup

bindtextdomain
dcngettext
Gettext Funkcje
PHP Manual

dcgettext

(PHP 4, PHP 5)

dcgettext — Overrides the domain for a single lookup

Opis

string dcgettext ( string $domain , string $message , int $category )

This function allows you to override the current domain for a single message lookup.

Parametry

domain

The domain

message

The message

category

The category

Zwracane wartości

A string on success.

Zobacz też:

  • gettext() - Lookup a message in the current domain

bindtextdomain
dcngettext
Gettext Funkcje


Plural version of dcgettext

dcgettext
dgettext
Gettext Funkcje
PHP Manual

dcngettext

(PHP 4 >= 4.2.0, PHP 5)

dcngettext — Plural version of dcgettext

Opis

string dcngettext ( string $domain , string $msgid1 , string $msgid2 , int $n , int $category )

This function allows you to override the current domain for a single plural message lookup.

Parametry

domain

The domain

msgid1

msgid2

n

category

Zwracane wartości

A string on success.

Zobacz też:

  • ngettext() - Plural version of gettext

dcgettext
dgettext
Gettext Funkcje


Override the current domain

dcngettext
dngettext
Gettext Funkcje
PHP Manual

dgettext

(PHP 4, PHP 5)

dgettext — Override the current domain

Opis

string dgettext ( string $domain , string $message )

The dgettext() function allows you to override the current domain for a single message lookup.

Parametry

domain

The domain

message

The message

Zwracane wartości

A string on success.

Zobacz też:

  • gettext() - Lookup a message in the current domain

dcngettext
dngettext
Gettext Funkcje


Plural version of dgettext

dgettext
gettext
Gettext Funkcje
PHP Manual

dngettext

(PHP 4 >= 4.2.0, PHP 5)

dngettext — Plural version of dgettext

Opis

string dngettext ( string $domain , string $msgid1 , string $msgid2 , int $n )

The dngettext() function allows you to override the current domain for a single plural message lookup.

Parametry

domain

The domain

msgid1

msgid2

n

Zwracane wartości

A string on success.

Zobacz też:

  • ngettext() - Plural version of gettext

dgettext
gettext
Gettext Funkcje


Lookup a message in the current domain

dngettext
ngettext
Gettext Funkcje
PHP Manual

gettext

(PHP 4, PHP 5)

gettext — Lookup a message in the current domain

Opis

string gettext ( string $message )

Looks up a message in the current domain.

Parametry

message

The message being translated.

Zwracane wartości

Returns a translated string if one is found in the translation table, or the submitted message if not found.

Przykłady

Przykład #1 gettext()-check

<?php
// Set language to German
putenv('LC_ALL=de_DE');
setlocale(LC_ALL, 'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");
?>

Notatki

Informacja:

You may use the underscore character '_' as an alias to this function.

Informacja:

Setting a language isn't enough for some systems and the putenv() should be used to define the current locale.

Zobacz też:

  • setlocale() - Set locale information

dngettext
ngettext
Gettext Funkcje


Plural version of gettext

gettext
textdomain
Gettext Funkcje
PHP Manual

ngettext

(PHP 4 >= 4.2.0, PHP 5)

ngettext — Plural version of gettext

Opis

string ngettext ( string $msgid1 , string $msgid2 , int $n )

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

Parametry

msgid1

msgid2

n

Zwracane wartości

Returns correct plural form of message identified by msgid1 and msgid2 for count n.

Przykłady

Przykład #1 ngettext() example

<?php

setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken

?>

gettext
textdomain
Gettext Funkcje


Sets the default domain

ngettext
iconv
Gettext Funkcje
PHP Manual

textdomain

(PHP 4, PHP 5)

textdomain — Sets the default domain

Opis

string textdomain ( string $text_domain )

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

Parametry

text_domain

The new message domain, or NULL to get the current setting without changing it

Zwracane wartości

If successful, this function returns the current message domain, after possibly changing it.

ngettext
iconv
Gettext Funkcje


iconv

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • iconv Funkcje
    • iconv_get_encoding — Pobiera aktualne ustawienia dla konwersji zestawu znaków
    • iconv_mime_decode_headers — Decodes multiple MIME header fields at once
    • iconv_mime_decode — Decodes a MIME header field
    • iconv_mime_encode — Composes a MIME header field
    • iconv_set_encoding — Ustawia aktualne ustawienia dla konwersji zestawu znaków
    • iconv_strlen — Returns the character count of string
    • iconv_strpos — Finds position of first occurrence of a needle within a haystack
    • iconv_strrpos — Finds the last occurrence of a needle within a haystack
    • iconv_substr — Cut out part of a string
    • iconv — Konwertuje łańcuch znaków do innego zestawu znaków
    • ob_iconv_handler — Konwersja kodowania znaków jako uchwyt buforu wyjścia
textdomain
Wstęp
Język naturalny i obsługa kodowania znaków


Wstęp

This module contains an interface to iconv character set conversion facility. With this module, you can turn a string represented by a local character set into the one represented by another character set, which may be the Unicode character set. Supported character sets depend on the iconv implementation of your system. Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the » GNU libiconv library. It will most likely end up with more consistent results.

Since PHP 5.0.0, this extension comes with various utility functions that help you to write multilingual scripts. Let's have a look at the following sections to explore the new features.

iconv
Instalacja/Konfiguracja
iconv


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
iconv


Wymagania

You will need nothing if the system you are using is one of the recent POSIX-compliant systems because standard C libraries that are supplied in them must provide iconv facility. Otherwise, you have to get the » libiconv library installed in your system.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

This extension is enabled by default, although it may be disabled by compiling with --without-iconv .

The optional --with-iconv-dir directive is used to specify the location of iconv on the system that PHP is being compiled on, otherwise only the default locations are scanned.

Informacja: Note to PHP 4 users
Enabling this extension requires building with --with-iconv=[DIR] , or Windows users may enable by having iconv.dll available in the systems PATH, and php_iconv.dll enabled in php.ini.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Iconv Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

Ostrzeżenie

Some systems (like IBM AIX) use "ISO8859-1" instead of "ISO-8859-1" so this value has to be used in configuration options and function parameters.

iconv.input_encoding string

Currently this option is not used.

iconv.output_encoding string

iconv.internal_encoding string

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

Since PHP 4.3.0 it is possible to identify at runtime which iconv implementation is adopted by this extension.

iconv constants
Name | Type | Description
ICONV_IMPL | string | The implementation name
ICONV_VERSION | string | The implementation version

Informacja:

Writing implementation-dependent scripts with these constants is strongly discouraged.

Since PHP 5.0.0, the following constants are also available:

iconv constants available since PHP 5.0.0
Name | Type | Description
ICONV_MIME_DECODE_STRICT | integer | A bitmask used for iconv_mime_decode()
ICONV_MIME_DECODE_CONTINUE_ON_ERROR | integer | A bitmask used for iconv_mime_decode()

Typy zasobów
iconv Funkcje
iconv


iconv Funkcje

Zobacz też:

See also GNU Recode functions.

Spis treści

  • iconv_get_encoding — Pobiera aktualne ustawienia dla konwersji zestawu znaków
  • iconv_mime_decode_headers — Decodes multiple MIME header fields at once
  • iconv_mime_decode — Decodes a MIME header field
  • iconv_mime_encode — Composes a MIME header field
  • iconv_set_encoding — Ustawia aktualne ustawienia dla konwersji zestawu znaków
  • iconv_strlen — Returns the character count of string
  • iconv_strpos — Finds position of first occurrence of a needle within a haystack
  • iconv_strrpos — Finds the last occurrence of a needle within a haystack
  • iconv_substr — Cut out part of a string
  • iconv — Konwertuje łańcuch znaków do innego zestawu znaków
  • ob_iconv_handler — Konwersja kodowania znaków jako uchwyt buforu wyjścia
Stałe predefiniowane
iconv_get_encoding
iconv


Pobiera aktualne ustawienia dla konwersji zestawu znaków

iconv Funkcje
iconv_mime_decode_headers
iconv Funkcje
PHP Manual

iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_get_encoding — Pobiera aktualne ustawienia dla konwersji zestawu znaków

Opis

array iconv_get_encoding ([ string $typ ] )

Zwraca aktualne ustawienia funkcji ob_iconv_handler() jako tablicę, lub FALSE jeśli się nie uda.

Patrz także: iconv_set_encoding() i ob_iconv_handler().

iconv Funkcje
iconv_mime_decode_headers
iconv Funkcje


Decodes multiple MIME header fields at once

iconv_get_encoding
iconv_mime_decode
iconv Funkcje
PHP Manual

iconv_mime_decode_headers

(PHP 5)

iconv_mime_decode_headers — Decodes multiple MIME header fields at once

Opis

array iconv_mime_decode_headers ( string $encoded_headers [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] )

Decodes multiple MIME header fields at once.

Parametry

encoded_headers

The encoded headers, as a string.

mode

mode determines the behaviour in the event iconv_mime_decode_headers() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.

Bitmasks acceptable to iconv_mime_decode_headers()
Value | Constant | Description
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in » RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers.
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_encoding will be used.

Zwracane wartości

Returns an associative array that holds a whole set of MIME header fields specified by encoded_headers on success, or FALSE if an error occurs during the decoding.

Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence.

Przykłady

Przykład #1 iconv_mime_decode_headers() example

<?php
$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for <example@example.com>;
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");
print_r($headers);
?>

Powyższy przykład wyświetli:

Array
(
    [Subject] => Prüfung Prüfung
    [To] => example@example.com
    [Date] => Thu, 1 Jan 1970 00:00:00 +0000
    [Message-Id] => <example@example.com>
    [Received] => Array
        (
            [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id example for <example@example.com>; Thu, 1 Jan 1970 00:00:00 +0000 (UTC) (envelope-from example-return-0000-example=example.com@example.com)
            [1] => (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
        )

)

Zobacz też:

  • iconv_mime_decode() - Decodes a MIME header field
  • mb_decode_mimeheader() - Decode string in MIME header field
  • imap_mime_header_decode() - Decode MIME header elements
  • imap_base64() - Decode BASE64 encoded text
  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

iconv_get_encoding
iconv_mime_decode
iconv Funkcje


Decodes a MIME header field

iconv_mime_decode_headers
iconv_mime_encode
iconv Funkcje
PHP Manual

iconv_mime_decode

(PHP 5)

iconv_mime_decode — Decodes a MIME header field

Opis

string iconv_mime_decode ( string $encoded_header [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] )

Decodes a MIME header field.

Parametry

encoded_header

The encoded header, as a string.

mode

mode determines the behaviour in the event iconv_mime_decode() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.

Bitmasks acceptable to iconv_mime_decode()
Value | Constant | Description
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in » RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers.
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_encoding will be used.

Zwracane wartości

Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.

Przykłady

Przykład #1 iconv_mime_decode() example

<?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       0, "ISO-8859-1");
?>

Zobacz też:

  • iconv_mime_decode_headers() - Decodes multiple MIME header fields at once
  • mb_decode_mimeheader() - Decode string in MIME header field
  • imap_mime_header_decode() - Decode MIME header elements
  • imap_base64() - Decode BASE64 encoded text
  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

iconv_mime_decode_headers
iconv_mime_encode
iconv Funkcje


Composes a MIME header field

iconv_mime_decode
iconv_set_encoding
iconv Funkcje
PHP Manual

iconv_mime_encode

(PHP 5)

iconv_mime_encode — Composes a MIME header field

Opis

string iconv_mime_encode ( string $field_name , string $field_value [, array $preferences = NULL ] )

Composes and returns a string that represents a valid MIME header field, which looks like the following:

Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile
In the above example, "Subject" is the field name and the portion that begins with "=?ISO-8859-1?..." is the field value.

Parametry

field_name

The field name.

field_value

The field value.

preferences

You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter preferences. The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.

Configuration items supported by iconv_mime_encode()
Item | Type | Description | Default value | Example
scheme | string | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. | B | B
input-charset | string | Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_encoding ini setting. | iconv.internal_encoding | ISO-8859-1
output-charset | string | Specifies the character set to use to compose the MIME header. | iconv.internal_encoding | UTF-8
line-length | integer | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to » RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996
line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (CR LF). Note that this parameter is always treated as an ASCII string regardless of the value of input-charset. | \r\n | \n

Zwracane wartości

Returns an encoded MIME field on success, or FALSE if an error occurs during the encoding.

Przykłady

Przykład #1 iconv_mime_encode() example

<?php
$preferences = array(
    "input-charset" => "ISO-8859-1",
    "output-charset" => "UTF-8",
    "line-length" => 76,
    "line-break-chars" => "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung=20Pr=C3=BCfung?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);

$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
?>

Zobacz też:

  • imap_binary() - Convert an 8bit string to a base64 string
  • mb_encode_mimeheader() - Encode string for MIME header
  • imap_8bit() - Convert an 8bit string to a quoted-printable string
  • quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string

iconv_mime_decode
iconv_set_encoding
iconv Funkcje


Ustawia aktualne ustawienia dla konwersji zestawu znaków

iconv_mime_encode
iconv_strlen
iconv Funkcje
PHP Manual

iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5)

iconv_set_encoding — Ustawia aktualne ustawienia dla konwersji zestawu znaków

Opis

bool iconv_set_encoding ( string $typ , string $zestaw_znaków )

Zmienia wartość zmiennej typ na zestaw_znaków. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Argument typ może przyjmować następujące wartości:

  • input_encoding
  • output_encoding
  • internal_encoding

Przykład #1 przykład iconv_set_encoding():

iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");

Patrz także: iconv_get_encoding() i ob_iconv_handler().

iconv_mime_encode
iconv_strlen
iconv Funkcje


Returns the character count of string

iconv_set_encoding
iconv_strpos
iconv Funkcje
PHP Manual

iconv_strlen

(PHP 5)

iconv_strlen — Returns the character count of string

Opis

int iconv_strlen ( string $str [, string $charset = ini_get("iconv.internal_encoding") ] )

In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence str on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte.

Parametry

str

The string.

charset

If charset parameter is omitted, str is assumed to be encoded in iconv.internal_encoding.

Zwracane wartości

Returns the character count of str, as an integer.

Zobacz też:

  • strlen() - Get string length
  • mb_strlen() - Get string length

iconv_set_encoding
iconv_strpos
iconv Funkcje


Finds position of first occurrence of a needle within a haystack

iconv_strlen
iconv_strrpos
iconv Funkcje
PHP Manual

iconv_strpos

(PHP 5)

iconv_strpos — Finds position of first occurrence of a needle within a haystack

Opis

int iconv_strpos ( string $haystack , string $needle [, int $offset = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] )

Finds position of first occurrence of a needle within a haystack.

In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.

Parametry

haystack

The entire string.

needle

The searched substring.

offset

The optional offset parameter specifies the position from which the search should be performed.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Zwracane wartości

Returns the numeric position of the first occurrence of needle in haystack.

If needle is not found, iconv_strpos() will return FALSE.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Zobacz też:

  • strpos() - Find the position of the first occurrence of a substring in a string
  • iconv_strrpos() - Finds the last occurrence of a needle within a haystack
  • mb_strpos() - Find position of first occurrence of string in a string

iconv_strlen
iconv_strrpos
iconv Funkcje


Finds the last occurrence of a needle within a haystack

iconv_strpos
iconv_substr
iconv Funkcje
PHP Manual

iconv_strrpos

(PHP 5)

iconv_strrpos — Finds the last occurrence of a needle within a haystack

Opis

int iconv_strrpos ( string $haystack , string $needle [, string $charset = ini_get("iconv.internal_encoding") ] )

Finds the last occurrence of a needle within a haystack.

In contrast to strrpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.

Parametry

haystack

The entire string.

needle

The searched substring.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

Zwracane wartości

Returns the numeric position of the last occurrence of needle in haystack.

If needle is not found, iconv_strrpos() will return FALSE.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Zobacz też:

  • strrpos() - Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków
  • iconv_strpos() - Finds position of first occurrence of a needle within a haystack
  • mb_strrpos() - Find position of last occurrence of a string in a string

iconv_strpos
iconv_substr
iconv Funkcje


Cut out part of a string

iconv_strrpos
iconv
iconv Funkcje
PHP Manual

iconv_substr

(PHP 5)

iconv_substr — Cut out part of a string

Opis

string iconv_substr ( string $str , int $offset [, int $length = iconv_strlen($str, $charset) [, string $charset = ini_get("iconv.internal_encoding") ]] )

Cuts a portion of str specified by the offset and length parameters.

Parametry

str

The original string.

offset

If offset is non-negative, iconv_substr() cuts the portion out of str beginning at offset'th character, counting from zero.

If offset is negative, iconv_substr() cuts out the portion beginning at the position, offset characters away from the end of str.

length

If length is given and is positive, the return value will contain at most length characters of the portion that begins at offset (depending on the length of string).

If negative length is passed, iconv_substr() cuts the portion out of str from the offset'th character up to the character that is length characters away from the end of the string. In case offset is also negative, the start position is calculated beforehand according to the rule explained above.

charset

If charset parameter is omitted, string are assumed to be encoded in iconv.internal_encoding.

Note that offset and length parameters are always deemed to represent offsets that are calculated on the basis of the character set determined by charset, whilst the counterpart substr() always takes these for byte offsets.

Zwracane wartości

Returns the portion of str specified by the offset and length parameters.

If str is shorter than offset characters long, FALSE will be returned.

Zobacz też:

  • substr() - Return part of a string
  • mb_substr() - Get part of string
  • mb_strcut() - Get part of string

iconv_strrpos
iconv
iconv Funkcje


Konwertuje łańcuch znaków do innego zestawu znaków

iconv_substr
ob_iconv_handler
iconv Funkcje
PHP Manual

iconv

(PHP 4 >= 4.0.5, PHP 5)

iconv — Konwertuje łańcuch znaków do innego zestawu znaków

Opis

string iconv ( string $zestaw_wejściowy , string $zestaw_docelowy , string $łańcuch )

Konwertuje łańcuch znaków łańcuch, zakodowany w zestaw_wejściowy na łańcuch znaków zakodowany w zestaw_docelowy. Zwraca skonwertowany łańcuch lub FALSE, jeśli konwersja się nie uda.

Przykład #1 przykład iconv():

echo iconv("ISO-8859-1","UTF-8","To jest test.");
echo iconv("ISO-8859-2","UTF-8","Zażółć gęślą jaźń");

iconv_substr
ob_iconv_handler
iconv Funkcje


Konwersja kodowania znaków jako uchwyt buforu wyjścia

iconv
intl
iconv Funkcje
PHP Manual

ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5)

ob_iconv_handler — Konwersja kodowania znaków jako uchwyt buforu wyjścia

Opis

string ob_iconv_handler ( string $zawartość , int $status )

Konwertuje string zapisany w internal_encoding do output_encoding.

internal_encoding i output_encoding powinny zostać zdefiniowane przez iconv_set_encoding() lub w pliku konfiguracyjnym php.ini.

Przykład #1 przykład ob_iconv_handler():

<?php
ob_start("ob_iconv_handler"); // rozpocznij buforowanie wyjścia
?>

Patrz także: iconv_get_encoding(), iconv_set_encoding() i funkcje output-control.

iconv
intl
iconv Funkcje


Internationalization Functions

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage of this extension
  • Collator — The Collator class
    • Collator::asort — Sort array maintaining index association
    • Collator::compare — Compare two Unicode strings
    • Collator::__construct — Create a collator
    • Collator::create — Create a collator
    • Collator::getAttribute — Get collation attribute value
    • Collator::getErrorCode — Get collator's last error code
    • Collator::getErrorMessage — Get text for collator's last error code
    • Collator::getLocale — Get the locale name of the collator
    • Collator::getSortKey — Get sorting key for a string
    • Collator::getStrength — Get current collation strength
    • Collator::setAttribute — Set collation attribute
    • Collator::setStrength — Set collation strength
    • Collator::sortWithSortKeys — Sort array using specified collator and sort keys
    • Collator::sort — Sort array using specified collator
  • NumberFormatter — The NumberFormatter class
    • NumberFormatter::create — Create a number formatter
    • NumberFormatter::formatCurrency — Format a currency value
    • NumberFormatter::format — Format a number
    • NumberFormatter::getAttribute — Get an attribute
    • NumberFormatter::getErrorCode — Get formatter's last error code.
    • NumberFormatter::getErrorMessage — Get formatter's last error message.
    • NumberFormatter::getLocale — Get formatter locale
    • NumberFormatter::getPattern — Get formatter pattern
    • NumberFormatter::getSymbol — Get a symbol value
    • NumberFormatter::getTextAttribute — Get a text attribute
    • NumberFormatter::parseCurrency — Parse a currency number
    • NumberFormatter::parse — Parse a number
    • NumberFormatter::setAttribute — Set an attribute
    • NumberFormatter::setPattern — Set formatter pattern
    • NumberFormatter::setSymbol — Set a symbol value
    • NumberFormatter::setTextAttribute — Set a text attribute
  • Locale — The Locale class
    • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::composeLocale — Returns a correctly ordered and delimited locale ID
    • Locale::filterMatches — Checks if a language tag filter matches with locale
    • Locale::getAllVariants — Gets the variants for the input locale
    • Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
    • Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
    • Locale::getDisplayName — Returns an appropriately localized display name for the input locale
    • Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
    • Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
    • Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
    • Locale::getKeywords — Gets the keywords for the input locale
    • Locale::getPrimaryLanguage — Gets the primary language for the input locale
    • Locale::getRegion — Gets the region for the input locale
    • Locale::getScript — Gets the script for the input locale
    • Locale::lookup — Searches the language tag list for the best match to the language
    • Locale::parseLocale — Returns a key-value array of locale ID subtag elements.
    • Locale::setDefault — sets the default runtime locale
  • Normalizer — The Normalizer class
    • Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form.
    • Normalizer::normalize — Normalizes the input provided and returns the normalized string
  • MessageFormatter — The MessageFormatter class
    • MessageFormatter::create — Constructs a new Message Formatter
    • MessageFormatter::formatMessage — Quick format message
    • MessageFormatter::format — Format the message
    • MessageFormatter::getErrorCode — Get the error code from last operation
    • MessageFormatter::getErrorMessage — Get the error text from the last operation
    • MessageFormatter::getLocale — Get the locale for which the formatter was created.
    • MessageFormatter::getPattern — Get the pattern used by the formatter
    • MessageFormatter::parseMessage — Quick parse input string
    • MessageFormatter::parse — Parse input string according to pattern
    • MessageFormatter::setPattern — Set the pattern used by the formatter
  • IntlDateFormatter — The IntlDateFormatter class
    • IntlDateFormatter::create — Create a date formatter
    • IntlDateFormatter::format — Format the date/time value as a string
    • IntlDateFormatter::getCalendar — Get the calendar used for the IntlDateFormatter
    • IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode — Get the error code from last operation
    • IntlDateFormatter::getErrorMessage — Get the error text from the last operation.
    • IntlDateFormatter::getLocale — Get the locale used by formatter
    • IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime — Parse string to a field-based time value
    • IntlDateFormatter::parse — Parse string to a timestamp value
    • IntlDateFormatter::setCalendar — sets the calendar used to the appropriate calendar, which must be
    • IntlDateFormatter::setLenient — Set the leniency of the parser
    • IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZoneId — Sets the time zone to use
  • ResourceBundle — The ResourceBundle class
    • ResourceBundle::count — Get number of elements in the bundle
    • ResourceBundle::create — Create a resource bundle
    • ResourceBundle::getErrorCode — Get bundle's last error code.
    • ResourceBundle::getErrorMessage — Get bundle's last error message.
    • ResourceBundle::get — Get data from the bundle
    • ResourceBundle::getLocales — Get supported locales
  • Spoofchecker — The Spoofchecker class
    • Spoofchecker::areConfusable — Checks if a given text contains any confusable characters
    • Spoofchecker::__construct — Constructor
    • Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters
    • Spoofchecker::setAllowedLocales — Locales to use when running checks
    • Spoofchecker::setChecks — Set the checks to run
  • Transliterator — The Transliterator class
    • Transliterator::__construct — Construct a Transliterator object
    • Transliterator::create — Create a transliterator
    • Transliterator::createFromRules — Create transliterator from rules
    • Transliterator::createInverse — Create an inverse transliterator
    • Transliterator::getErrorCode — Get last error code
    • Transliterator::getErrorMessage — Get last error message
    • Transliterator::listIDs — Get transliterator IDs
    • Transliterator::transliterate — Transliterate a string
  • Grapheme Funkcje
    • grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
    • grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
    • grapheme_strlen — Get string length in grapheme units
    • grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.
    • grapheme_substr — Return part of a string
  • IDN Funkcje
    • idn_to_ascii — Convert domain name to IDNA ASCII form.
    • idn_to_unicode — Alias dla idn_to_utf8
    • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.
  • intl Funkcje
    • intl_error_name — Get symbolic name for a given error code
    • intl_get_error_code — Get the last error code
    • intl_get_error_message — Get description of the last error
    • intl_is_failure — Check whether the given error code indicates failure
ob_iconv_handler
Wstęp
Język naturalny i obsługa kodowania znaków


Wstęp

Internationalization extension (further is referred as Intl) is a wrapper for » ICU library, enabling PHP programmers to perform » UCA-conformant collation and date/time/number/currency formatting in their scripts.

It tends to closely follow ICU APIs, so that people having experience working with ICU in either C/C++ or Java could easily use the PHP API. Also, this way ICU documentation would be useful to understand various ICU functions.

Intl consists of several modules, each of them exposes the corresponding ICU API:

  • Collator: provides string comparison capability with support for appropriate locale-sensitive sort orderings.
  • Number Formatter: allows to display number according to the localized format or given pattern or set of rules, and to parse strings into numbers.
  • Message Formatter: allows to create messages incorporating data (such as numbers or dates) formatted according to given pattern and locale rules, and parse messages extracting data from them.
  • Normalizer: provides a function to transform text into one of the Unicode normalization forms, and provides a routine to test if a given string is already normalized.
  • Locale: provides interaction with locale identifiers in the form of functions to get subtags from locale identifier; parse, compose, match(lookup and filter) locale identifiers.

Links

  • » Miscellaneous ICU docs

  • » ICU User Guide

  • » Unicode Collation Algorithm

intl
Instalacja/Konfiguracja
intl


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
intl


Wymagania

To build the extension you need to install the » ICU library of version 3.6+.

This extension is bundled with PHP as of PHP version 5.3.0. Alternatively, the PECL version of this extension may be used with all PHP versions greater than 5.2.0 (5.2.4+ recommended).

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

This extension may be installed using the bundled version as of PHP 5.3.0, or as a PECL extension as of PHP 5.2.0. In other words, there are two methods to install the intl extension.

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/intl.

Alternatively, --enable-intl will enable the bundled version while compiling PHP.

If your ICU is installed to a non-standard directory then you might want to specify its location in LD_LIBRARY_PATH environment variable so that dynamic linker can find it:

$ export LD_LIBRARY_PATH=/opt/icu/lib

Otherwise, if PHP and ICU are installed to their default locations, then the additional options to `configure' are not needed.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Intl Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
intl.default_locale |  | 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.

intl.default_locale string

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

INTL_MAX_LOCALE_LEN (integer)
Limit on locale length, set to 80 in PHP code. Locale names longer than this limit will not be accepted.
IDNA_DEFAULT (integer)
Prohibit processing of unassigned codepoints in the input for IDN functions and do not check if the input conforms to domain name ASCII rules.
IDNA_ALLOW_UNASSIGNED (integer)
Allow processing of unassigned codepoints in the input for IDN functions.
IDNA_USE_STD3_RULES (integer)
Check if the input for IDN functions conforms to domain name ASCII rules.
IDNA_CHECK_BIDI (integer)
Check whether the input conforms to the BiDi rules. Ignored by the IDNA2003 implementation, which always performs this check.
IDNA_CHECK_CONTEXTJ (integer)
Check whether the input conforms to the CONTEXTJ rules. Ignored by the IDNA2003 implementation, as this check is new in IDNA2008.
IDNA_NONTRANSITIONAL_TO_ASCII (integer)
Option for nontransitional processing in idn_to_ascii(). Transitional processing is activated by default. This option is ignored by the IDNA2003 implementation.
IDNA_NONTRANSITIONAL_TO_UNICODE (integer)
Option for nontransitional processing in idn_to_utf8(). Transitional processing is activated by default. This option is ignored by the IDNA2003 implementation.
INTL_IDNA_VARIANT_2003 (integer)
Use IDNA 2003 algorithm in idn_to_utf8() and idn_to_ascii(). This is the default.
INTL_IDNA_VARIANT_UTS46 (integer)
Use UTS #46 algorithm in idn_to_utf8() and idn_to_ascii().
IDNA_ERROR_EMPTY_LABEL (integer)
IDNA_ERROR_LABEL_TOO_LONG (integer)
IDNA_ERROR_DOMAIN_NAME_TOO_LONG (integer)
IDNA_ERROR_LEADING_HYPHEN (integer)
IDNA_ERROR_TRAILING_HYPHEN (integer)
IDNA_ERROR_HYPHEN_3_4 (integer)
IDNA_ERROR_LEADING_COMBINING_MARK (integer)
IDNA_ERROR_DISALLOWED (integer)
IDNA_ERROR_PUNYCODE (integer)
IDNA_ERROR_LABEL_HAS_DOT (integer)
IDNA_ERROR_INVALID_ACE_LABEL (integer)
IDNA_ERROR_BIDI (integer)
IDNA_ERROR_CONTEXTJ (integer)
Errors reported in a bitset returned by the UTS #46 algorithm in idn_to_utf8() and idn_to_ascii().

Typy zasobów
Przykłady
intl


Przykłady

Spis treści

  • Basic usage of this extension
Stałe predefiniowane
Basic usage of this extension
intl


Basic usage of this extension

Each module provides two kind of APIs: a procedural one and an object oriented one. Both are actually identical and described in the corresponding document.

Informacja:

All input strings must be in UTF-8 encoding. All output strings are also in UTF-8.

Przykład #1 Example of using the procedural API

<?php
$coll  = collator_create('en_US');
$result = collator_compare($coll, "string#1", "string#2");
?>

Przykład #2 Example of using the object-oriented API

<?php
$coll = new Collator('en_US');
$al   = $coll->getLocale(Locale::ACTUAL_LOCALE);
echo "Actual locale: $al\n";

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->format(1234567);
?>
Przykłady
Collator
Przykłady


The Collator class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Wstęp

Provides string comparison capability with support for appropriate locale-sensitive sort orderings.

Krótki opis klasy

Collator {
/* Metody */
__construct ( string $locale )
bool asort ( array &$arr [, int $sort_flag ] )
int compare ( string $str1 , string $str2 )
static Collator create ( string $locale )
int getAttribute ( int $attr )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $type ] )
string getSortKey ( string $str )
int getStrength ( void )
bool setAttribute ( int $attr , int $val )
bool setStrength ( int $strength )
bool sortWithSortKeys ( array &$arr )
bool sort ( array &$arr [, int $sort_flag ] )
}

Stałe predefiniowane

Collator::FRENCH_COLLATION (integer)

Sort strings with different accents from the back of the string. This attribute is automatically set to On for the French locales and a few others. Users normally would not need to explicitly set this attribute. There is a string comparison performance cost when it is set On, but sort key length is unaffected. Possible values are:

  • Collator::ON
  • Collator::OFF(default)
  • Collator::DEFAULT_VALUE

Przykład #1 FRENCH_COLLATION rules

  • F=OFF cote < coté < côte < côté
  • F=ON cote < côte < coté < côté

Collator::ALTERNATE_HANDLING (integer)

The Alternate attribute is used to control the handling of the so called variable characters in the UCA: whitespace, punctuation and symbols. If Alternate is set to NonIgnorable (N), then differences among these characters are of the same importance as differences among letters. If Alternate is set to Shifted (S), then these characters are of only minor importance. The Shifted value is often used in combination with Strength set to Quaternary. In such a case, whitespace, punctuation, and symbols are considered when comparing strings, but only if all other aspects of the strings (base letters, accents, and case) are identical. If Alternate is not set to Shifted, then there is no difference between a Strength of 3 and a Strength of 4. For more information and examples, see Variable_Weighting in the » UCA. The reason the Alternate values are not simply On and Off is that additional Alternate values may be added in the future. The UCA option Blanked is expressed with Strength set to 3, and Alternate set to Shifted. The default for most locales is NonIgnorable. If Shifted is selected, it may be slower if there are many strings that are the same except for punctuation; sort key length will not be affected unless the strength level is also increased.

Possible values are:

  • Collator::NON_IGNORABLE(default)
  • Collator::SHIFTED
  • Collator::DEFAULT_VALUE

Przykład #2 ALTERNATE_HANDLING rules

  • S=3, A=N di Silva < Di Silva < diSilva < U.S.A. < USA
  • S=3, A=S di Silva = diSilva < Di Silva < U.S.A. = USA
  • S=4, A=S di Silva < diSilva < Di Silva < U.S.A. < USA

Collator::CASE_FIRST (integer)

The Case_First attribute is used to control whether uppercase letters come before lowercase letters or vice versa, in the absence of other differences in the strings. The possible values are Uppercase_First (U) and Lowercase_First (L), plus the standard Default and Off. There is almost no difference between the Off and Lowercase_First options in terms of results, so typically users will not use Lowercase_First: only Off or Uppercase_First. (People interested in the detailed differences between X and L should consult the Collation Customization). Specifying either L or U won't affect string comparison performance, but will affect the sort key length.

Possible values are:

  • Collator::OFF(default)
  • Collator::LOWER_FIRST
  • Collator::UPPER_FIRST
  • Collator:DEFAULT

Przykład #3 CASE_FIRST rules

  • C=X or C=L "china" < "China" < "denmark" < "Denmark"
  • C=U "China" < "china" < "Denmark" < "denmark"

Collator::CASE_LEVEL (integer)

The Case_Level attribute is used when ignoring accents but not case. In such a situation, set Strength to be Primary, and Case_Level to be On. In most locales, this setting is Off by default. There is a small string comparison performance and sort key impact if this attribute is set to be On.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Przykład #4 CASE_LEVEL rules

  • S=1, E=X role = Role = rôle
  • S=1, E=O role = rôle < Role

Collator::NORMALIZATION_MODE (integer)

The Normalization setting determines whether text is thoroughly normalized or not in comparison. Even if the setting is off (which is the default for many locales), text as represented in common usage will compare correctly (for details, see UTN #5). Only if the accent marks are in noncanonical order will there be a problem. If the setting is On, then the best results are guaranteed for all possible text input. There is a medium string comparison performance cost if this attribute is On, depending on the frequency of sequences that require normalization. There is no significant effect on sort key length. If the input text is known to be in NFD or NFKD normalization forms, there is no need to enable this Normalization option.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::STRENGTH (integer)

The ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions. For more detailed information, see collator_set_strength() chapter.

Possible values are:

  • Collator::PRIMARY
  • Collator::SECONDARY
  • Collator::TERTIARY(default)
  • Collator::QUATERNARY
  • Collator::IDENTICAL
  • Collator::DEFAULT_VALUE

Collator::HIRAGANA_QUATERNARY_MODE (integer)

Compatibility with JIS x 4061 requires the introduction of an additional level to distinguish Hiragana and Katakana characters. If compatibility with that standard is required, then this attribute should be set On, and the strength set to Quaternary. This will affect sort key length and string comparison string comparison performance.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::NUMERIC_COLLATION (integer)

When turned on, this attribute generates a collation key for the numeric value of substrings of digits. This is a way to get '100' to sort AFTER '2'.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::DEFAULT_VALUE (integer)
Collator::PRIMARY (integer)
Collator::SECONDARY (integer)
Collator::TERTIARY (integer)
Collator::DEFAULT_STRENGTH (integer)
Collator::QUATERNARY (integer)
Collator::IDENTICAL (integer)
Collator::OFF (integer)
Collator::ON (integer)
Collator::SHIFTED (integer)
Collator::NON_IGNORABLE (integer)
Collator::LOWER_FIRST (integer)
Collator::UPPER_FIRST (integer)

Spis treści

  • Collator::asort — Sort array maintaining index association
  • Collator::compare — Compare two Unicode strings
  • Collator::__construct — Create a collator
  • Collator::create — Create a collator
  • Collator::getAttribute — Get collation attribute value
  • Collator::getErrorCode — Get collator's last error code
  • Collator::getErrorMessage — Get text for collator's last error code
  • Collator::getLocale — Get the locale name of the collator
  • Collator::getSortKey — Get sorting key for a string
  • Collator::getStrength — Get current collation strength
  • Collator::setAttribute — Set collation attribute
  • Collator::setStrength — Set collation strength
  • Collator::sortWithSortKeys — Sort array using specified collator and sort keys
  • Collator::sort — Sort array using specified collator
Basic usage of this extension
Collator::asort
intl


Sort array maintaining index association

Collator
Collator::compare
Collator
PHP Manual

Collator::asort

collator_asort

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::asort -- collator_asort — Sort array maintaining index association

Opis

Styl obiektowy

bool Collator::asort ( array &$arr [, int $sort_flag ] )

Styl proceduralny

bool collator_asort ( Collator $coll , array &$arr [, int $sort_flag ] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. Array elements will have sort order according to current locale rules.

Equivalent to standard PHP asort().

Parametry

coll

Collator object.

arr

Array of strings to sort.

sort_flag

Optional sorting type, one of the following:

  • Collator::SORT_REGULAR - compare items normally (don't change types)

  • Collator::SORT_NUMERIC - compare items numerically

  • Collator::SORT_STRING - compare items as strings

Default $sort_flag value is Collator::SORT_REGULAR. It is also used if an invalid $sort_flag value has been specified.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 collator_asort()example

<?php
$coll = collator_create( 'en_US' );
$arr = array(
     'a' => '100',
     'b' => '50',
     'c' => '7'
);
collator_asort( $coll, $arr, Collator::SORT_NUMERIC );
var_export( $arr );

collator_asort( $coll, $arr, Collator::SORT_STRING );
var_export( $arr );
?>

Powyższy przykład wyświetli:

array (
  'c' => '7',
  'b' => '50',
  'a' => '100',
)array (
  'a' => '100',
  'b' => '50',
  'c' => '7',
)

Zobacz też:

  • Collator constants
  • collator_sort() - Sort array using specified collator
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

Collator
Collator::compare
Collator


Compare two Unicode strings

Collator::asort
Collator::__construct
Collator
PHP Manual

Collator::compare

collator_compare

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::compare -- collator_compare — Compare two Unicode strings

Opis

Styl obiektowy

int Collator::compare ( string $str1 , string $str2 )

Styl proceduralny

int collator_compare ( Collator $coll , string $str1 , string $str2 )

Compare two Unicode strings according to collation rules.

Parametry

coll

Collator object.

str1

The first string to compare.

str2

The second string to compare.

Zwracane wartości

Return comparison result:

  • 1 if str1 is greater than str2 ;

  • 0 if str1 is equal to str2;

  • -1 if str1 is less than str2 .

On error boolean FALSE is returned.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 collator_compare()example

<?php
$s1 = 'Hello';
$s2 = 'hello';

$coll = collator_create( 'en_US' );
$res  = collator_compare( $coll, $s1, $s2 );

if ($res === false) {
    echo collator_get_error_message( $coll );
} else if( $res > 0 ) {
    echo "s1 is greater than s2\n";
} else if( $res < 0 ) {
    echo "s1 is less than s2\n";
} else {
    echo "s1 is equal to s2\n";
}
?>

Powyższy przykład wyświetli:

s1 is greater than s2

Zobacz też:

  • collator_sort() - Sort array using specified collator

Collator::asort
Collator::__construct
Collator


Create a collator

Collator::compare
Collator::create
Collator
PHP Manual

Collator::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::__construct — Create a collator

Opis

Collator::__construct() ( string $locale )

Creates a new instance of Collator.

Parametry

locale

The locale whose collation rules should be used. Special values for locales can be passed in - if null is passed for the locale, the default locale collation rules will be used. If empty string ("") or "root" are passed, UCA rules will be used.

The Locale attribute is typically the most important attribute for correct sorting and matching, according to the user expectations in different countries and regions. The default » UCA ordering will only sort a few languages such as Dutch and Portuguese correctly ("correctly" meaning according to the normal expectations for users of the languages). Otherwise, you need to supply the locale to UCA in order to properly collate text for a given language. Thus a locale needs to be supplied so as to choose a collator that is correctly tailored for that locale. The choice of a locale will automatically preset the values for all of the attributes to something that is reasonable for that locale. Thus most of the time the other attributes do not need to be explicitly set. In some cases, the choice of locale will make a difference in string comparison performance and/or sort key length.

Zwracane wartości

Returns Collator instance.

Błędy/Wyjątki

Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened.

Przykłady

Przykład #1 Collator::__construct() example

<?php
$coll = new Collator( 'en_CA' );
?>

Zobacz też:

  • Collator::create() - Create a collator
  • collator_create() - Create a collator

Collator::compare
Collator::create
Collator


Create a collator

Collator::__construct
Collator::getAttribute
Collator
PHP Manual

Collator::create

collator_create

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::create -- collator_create — Create a collator

Opis

Styl obiektowy

static Collator Collator::create ( string $locale )

Styl proceduralny

Collator collator_create ( string $locale )

The strings will be compared using the options already specified.

Parametry

locale

The locale containing the required collation rules. Special values for locales can be passed in - if null is passed for the locale, the default locale collation rules will be used. If empty string ("") or "root" are passed, » UCA rules will be used.

Zwracane wartości

Return new instance of Collator object, or NULL on error.

Przykłady

Przykład #1 collator_create() example

<?php
$coll = collator_create( 'en_US' );

if( !isset( $coll ) ) {
    printf( "Collator creation failed: %s\n", intl_get_error_message() );
    exit( 1 );
}
?>

Zobacz też:

  • Collator::__construct() - Create a collator

Collator::__construct
Collator::getAttribute
Collator


Get collation attribute value

Collator::create
Collator::getErrorCode
Collator
PHP Manual

Collator::getAttribute

collator_get_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getAttribute -- collator_get_attribute — Get collation attribute value

Opis

Styl obiektowy

int Collator::getAttribute ( int $attr )

Styl proceduralny

int collator_get_attribute ( Collator $coll , int $attr )

Get a value of an integer collator attribute.

Parametry

coll

Collator object.

attr

Attribute to get value for.

Zwracane wartości

Attribute value, or boolean FALSE on error.

Przykłady

Przykład #1 collator_get_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if( $val === false )
{
    // Handle error.
}
?>

Zobacz też:

  • Collator constants
  • collator_set_attribute() - Set collation attribute
  • collator_get_strength() - Get current collation strength

Collator::create
Collator::getErrorCode
Collator


Get collator's last error code

Collator::getAttribute
Collator::getErrorMessage
Collator
PHP Manual

Collator::getErrorCode

collator_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getErrorCode -- collator_get_error_code — Get collator's last error code

Opis

Styl obiektowy

int Collator::getErrorCode ( void )

Styl proceduralny

int collator_get_error_code ( Collator $coll )

Parametry

coll

Collator object.

Zwracane wartości

Error code returned by the last Collator API function call.

Przykłady

Przykład #1 collator_get_error_code() example

<?php
$coll = collator_create( 'en_US' );
if( collator_get_attribute( $coll, Collator::FRENCH_COLLATION ) === false )
        handle_error( collator_get_error_code() );
?>

Zobacz też:

  • collator_get_error_message() - Get text for collator's last error code

Collator::getAttribute
Collator::getErrorMessage
Collator


Get text for collator's last error code

Collator::getErrorCode
Collator::getLocale
Collator
PHP Manual

Collator::getErrorMessage

collator_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getErrorMessage -- collator_get_error_message — Get text for collator's last error code

Opis

Styl obiektowy

string Collator::getErrorMessage ( void )

Styl proceduralny

string collator_get_error_message ( Collator $coll )

Retrieves the message for the last error.

Parametry

coll

Collator object.

Zwracane wartości

Description of an error occurred in the last Collator API function call.

Przykłady

Przykład #1 collator_get_error_message() example

<?php
$coll = collator_create( 'lt' );
if( collator_compare( $coll, 'y', 'k' ) === false ) {
    echo collator_get_error_message( $coll );
}
?>

Zobacz też:

  • collator_get_error_code() - Get collator's last error code

Collator::getErrorCode
Collator::getLocale
Collator


Get the locale name of the collator

Collator::getErrorMessage
Collator::getSortKey
Collator
PHP Manual

Collator::getLocale

collator_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getLocale -- collator_get_locale — Get the locale name of the collator

Opis

Styl obiektowy

string Collator::getLocale ([ int $type ] )

Styl proceduralny

string collator_get_locale ( Collator $coll , int $type )

Get collector locale name.

Parametry

coll

Collator object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE and Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

Zwracane wartości

Real locale name from which the collation data comes. If the collator was instantiated from rules or an error occurred, returns boolean FALSE.

Przykłady

Przykład #1 collator_get_locale() example

<?php
$coll    = collator_create( 'en_US_California' );
$res_val = collator_get_locale( $coll, Locale::VALID_LOCALE );
$res_act = collator_get_locale( $coll, Locale::ACTUAL_LOCALE );
printf( "Valid locale name: %s\nActual locale name: %s\n",
         $res_req, $res_val, $res_act );
?>

Powyższy przykład wyświetli:

Requested locale name: en_US_California
Valid locale name: en_US
Actual locale name: en

Zobacz też:

  • collator_create() - Create a collator

Collator::getErrorMessage
Collator::getSortKey
Collator


Get sorting key for a string

Collator::getLocale
Collator::getStrength
Collator
PHP Manual

Collator::getSortKey

collator_get_sort_key

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

Collator::getSortKey -- collator_get_sort_key — Get sorting key for a string

Opis

Styl obiektowy

string Collator::getSortKey ( string $str )

Styl proceduralny

string collator_get_sort_key ( Collator $coll , string $str )

Return collation key for a string.

Parametry

coll

Collator object.

str

The string to produce the key from.

Zwracane wartości

Returns the collation key for the string. Collation keys can be compared directly instead of strings.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 collator_get_sort_key()example

<?php
$s1 = 'Hello';

$coll = collator_create( 'en_US' );
$res  = collator_get_sort_key( $coll, $s1);

echo urlencode($res);
?>

Powyższy przykład wyświetli:

71%3F%3FE%01%09%01%8F%08%00

Zobacz też:

  • collator_sort() - Sort array using specified collator
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

Collator::getLocale
Collator::getStrength
Collator


Get current collation strength

Collator::getSortKey
Collator::setAttribute
Collator
PHP Manual

Collator::getStrength

collator_get_strength

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::getStrength -- collator_get_strength — Get current collation strength

Opis

Styl obiektowy

int Collator::getStrength ( void )

Styl proceduralny

int collator_get_strength ( Collator $coll )

Parametry

coll

Collator object.

Zwracane wartości

Returns current collation strength, or boolean FALSE on error.

Przykłady

Przykład #1 collator_get_strength() example

<?php
$coll     = collator_create( 'en_US' );
$strength = collator_get_strength( $coll );
?>

Zobacz też:

  • Collator constants
  • collator_set_strength() - Set collation strength
  • collator_get_attribute() - Get collation attribute value

Collator::getSortKey
Collator::setAttribute
Collator


Set collation attribute

Collator::getStrength
Collator::setStrength
Collator
PHP Manual

Collator::setAttribute

collator_set_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::setAttribute -- collator_set_attribute — Set collation attribute

Opis

Styl obiektowy

bool Collator::setAttribute ( int $attr , int $val )

Styl proceduralny

bool collator_set_attribute ( Collator $coll , int $attr , int $val )

Parametry

coll

Collator object.

attr

Attribute.

val

Attribute value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 collator_set_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val  = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if ($val === false) {
    // Handle error.
} elseif ($val === Collator::ON) {
    // Do something useful.
}
?>

Zobacz też:

  • Collator constants
  • collator_get_attribute() - Get collation attribute value
  • collator_set_strength() - Set collation strength

Collator::getStrength
Collator::setStrength
Collator


Set collation strength

Collator::setAttribute
Collator::sortWithSortKeys
Collator
PHP Manual

Collator::setStrength

collator_set_strength

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::setStrength -- collator_set_strength — Set collation strength

Opis

Styl obiektowy

bool Collator::setStrength ( int $strength )

Styl proceduralny

bool collator_set_strength ( Collator $coll , int $strength )

The » ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions.

  1. Primary Level: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character. This is also called the level1 strength.

  2. Secondary Level: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. This is also called the level2 strength.

    Informacja:

    Note: In some languages (such as Danish), certain accented letters are considered to be separate base characters. In most languages, however, an accented letter only has a secondary difference from the unaccented version of that letter.

  3. Tertiary Level: Upper and lower case differences in characters are distinguished at the tertiary level (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary level (such as "A" and " "). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings. This is also called the level3 strength.

  4. Quaternary Level: When punctuation is ignored (see Ignoring Punctuations ) at level 13, an additional level can be used to distinguish words with and without punctuation (for example, "ab" < "a-b" < "aB"). This difference is ignored when there is a primary, secondary or tertiary difference. This is also known as the level4 strength. The quaternary level should only be used if ignoring punctuation is required or when processing Japanese text (see Hiragana processing).

  5. Identical Level: When all other levels are equal, the identical level is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared at this level, just in case there is no difference at levels 14. For example, Hebrew cantillation marks are only distinguished at this level. This level should be used sparingly, as only code point values differences between two strings is an extremely rare occurrence. Using this level substantially decreases the performance for both incremental comparison and sort key generation (as well as increasing the sort key length). It is also known as level 5 strength.

For example, people may choose to ignore accents or ignore accents and case when searching for text. Almost all characters are distinguished by the first three levels, and in most locales the default value is thus Tertiary. However, if Alternate is set to be Shifted, then the Quaternary strength can be used to break ties among whitespace, punctuation, and symbols that would otherwise be ignored. If very fine distinctions among characters are required, then the Identical strength can be used (for example, Identical Strength distinguishes between the Mathematical Bold Small A and the Mathematical Italic Small A.). However, using levels higher than Tertiary the Identical strength result in significantly longer sort keys, and slower string comparison performance for equal strings.

Parametry

coll

Collator object.

strength

Strength to set.

Possible values are:

  • Collator::PRIMARY

  • Collator::SECONDARY

  • Collator::TERTIARY

  • Collator::QUATERNARY

  • Collator::IDENTICAL

  • Collator::DEFAULT

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 collator_set_strength() example

<?php
$arr  = array( 'aò', 'Ao', 'ao' );
$coll = collator_create( 'en_US' );

// Sort array using default strength.
collator_sort( $coll, $arr );
var_export( $arr );

// Sort array using primary strength.
collator_set_strength( $coll, Collator::PRIMARY );
collator_sort( $coll, $arr );
var_export( $arr );
?>

Powyższy przykład wyświetli:

array (
  0 => 'ao',
  1 => 'Ao',
  2 => 'aò',
)
array (
  0 => 'aò',
  1 => 'Ao',
  2 => 'ao',
)

Zobacz też:

  • Collator constants
  • collator_get_strength() - Get current collation strength

Collator::setAttribute
Collator::sortWithSortKeys
Collator


Sort array using specified collator and sort keys

Collator::setStrength
Collator::sort
Collator
PHP Manual

Collator::sortWithSortKeys

collator_sort_with_sort_keys

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::sortWithSortKeys -- collator_sort_with_sort_keys — Sort array using specified collator and sort keys

Opis

Styl obiektowy

bool Collator::sortWithSortKeys ( array &$arr )

Styl proceduralny

bool collator_sort_with_sort_keys ( Collator $coll , array &$arr )

Similar to collator_sort() but uses ICU sorting keys produced by ucol_getSortKey() to gain more speed on large arrays.

Parametry

coll

Collator object.

arr

Array of strings to sort

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 collator_sort_with_sort_keys() example

<?php
$arr  = array( 'Köpfe', 'Kypper', 'Kopfe' );
$coll = collator_create( 'sv' );

collator_sort_with_sort_keys( $coll, $arr );
var_export( $arr );
?>

Powyższy przykład wyświetli:

array (
  0 => 'Kopfe',
  1 => 'Kypper',
  2 => 'Köpfe',
)

Zobacz też:

  • Collator constants
  • collator_sort() - Sort array using specified collator
  • collator_asort() - Sort array maintaining index association

Collator::setStrength
Collator::sort
Collator


Sort array using specified collator

Collator::sortWithSortKeys
NumberFormatter
Collator
PHP Manual

Collator::sort

collator_sort

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Collator::sort -- collator_sort — Sort array using specified collator

Opis

Styl obiektowy

bool Collator::sort ( array &$arr [, int $sort_flag ] )

Styl proceduralny

bool collator_sort ( Collator $coll , array &$arr [, int $sort_flag ] )

This function sorts an array according to current locale rules.

Equivalent to standard PHP sort() .

Parametry

coll

Collator object.

arr

Array of strings to sort.

sort_flag

Optional sorting type, one of the following:

  • Collator::SORT_REGULAR - compare items normally (don't change types)

  • Collator::SORT_NUMERIC - compare items numerically

  • Collator::SORT_STRING - compare items as strings

Default sorting type is Collator::SORT_REGULAR. It is also used if an invalid sort_flag value has been specified.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 collator_sort() example

<?php
$coll = collator_create( 'en_US' );
$arr  = array( 'at', 'às', 'as' );

var_export( $arr );
collator_sort( $coll, $arr );
var_export( $arr );
?>

Powyższy przykład wyświetli:

array (
  0 => 'at',
  1 => 'às',
  2 => 'as',
)array (
  0 => 'as',
  1 => 'às',
  2 => 'at',
)

Zobacz też:

  • Collator constants
  • collator_asort() - Sort array maintaining index association
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

Collator::sortWithSortKeys
NumberFormatter
Collator


The NumberFormatter class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Wstęp

Programs store and operate on numbers using a locale-independent binary representation. When displaying or printing a number it is converted to a locale-specific string. For example, the number 12345.67 is "12,345.67" in the US, "12 345,67" in France and "12.345,67" in Germany.

By invoking the methods provided by the NumberFormatter class, you can format numbers, currencies, and percentages according to the specified or default locale. NumberFormatter is locale-sensitive so you need to create a new NumberFormatter for each locale. NumberFormatter methods format primitive-type numbers, such as double and output the number as a locale-specific string.

For currencies you can use currency format type to create a formatter that returns a string with the formatted number and the appropriate currency sign. Of course, the NumberFormatter class is unaware of exchange rates so, the number output is the same regardless of the specified currency. This means that the same number has different monetary values depending on the currency locale. If the number is 9988776.65 the results will be:

  • 9 988 776,65 € in France
  • 9.988.776,65 € in Germany
  • $9,988,776.65 in the United States

In order to format percentages, create a locale-specific formatter with percentage format type. With this formatter, a decimal fraction such as 0.75 is displayed as 75%.

For more complex formatting, like spelled-out numbers, the rule-based number formatters are used.

Krótki opis klasy

NumberFormatter {
/* Metody */
__construct ( string $locale , int $style [, string $pattern ] )
static NumberFormatter create ( string $locale , int $style [, string $pattern ] )
string formatCurrency ( float $value , string $currency )
string format ( number $value [, int $type ] )
int getAttribute ( int $attr )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $type ] )
string getPattern ( void )
string getSymbol ( int $attr )
string getTextAttribute ( int $attr )
float parseCurrency ( string $value , string &$currency [, int &$position ] )
mixed parse ( string $value [, int $type [, int &$position ]] )
bool setAttribute ( int $attr , int $value )
bool setPattern ( string $pattern )
bool setSymbol ( int $attr , string $value )
bool setTextAttribute ( int $attr , string $value )
}

Stałe predefiniowane

These styles are used by the numfmt_create() to define the type of the formatter.

NumberFormatter::PATTERN_DECIMAL (integer)
Decimal format defined by pattern
NumberFormatter::DECIMAL (integer)
Decimal format
NumberFormatter::CURRENCY (integer)
Currency format
NumberFormatter::PERCENT (integer)
Percent format
NumberFormatter::SCIENTIFIC (integer)
Scientific format
NumberFormatter::SPELLOUT (integer)
Spellout rule-based format
NumberFormatter::ORDINAL (integer)
Ordinal rule-based format
NumberFormatter::DURATION (integer)
Duration rule-based format
NumberFormatter::PATTERN_RULEBASED (integer)
Rule-based format defined by pattern
NumberFormatter::DEFAULT_STYLE (integer)
Default format for the locale
NumberFormatter::IGNORE (integer)
Alias for PATTERN_DECIMAL

These constants define how the numbers are parsed or formatted. They should be used as arguments to numfmt_format() and numfmt_parse().

NumberFormatter::TYPE_DEFAULT (integer)
Derive the type from variable type
NumberFormatter::TYPE_INT32 (integer)
Format/parse as 32-bit integer
NumberFormatter::TYPE_INT64 (integer)
Format/parse as 64-bit integer
NumberFormatter::TYPE_DOUBLE (integer)
Format/parse as floating point value
NumberFormatter::TYPE_CURRENCY (integer)
Format/parse as currency value

Number format attribute used by numfmt_get_attribute() and numfmt_set_attribute().

NumberFormatter::PARSE_INT_ONLY (integer)
Parse integers only.
NumberFormatter::GROUPING_USED (integer)
Use grouping separator.
NumberFormatter::DECIMAL_ALWAYS_SHOWN (integer)
Always show decimal point.
NumberFormatter::MAX_INTEGER_DIGITS (integer)
Maximum integer digits.
NumberFormatter::MIN_INTEGER_DIGITS (integer)
Minimum integer digits.
NumberFormatter::INTEGER_DIGITS (integer)
Integer digits.
NumberFormatter::MAX_FRACTION_DIGITS (integer)
Maximum fraction digits.
NumberFormatter::MIN_FRACTION_DIGITS (integer)
Minimum fraction digits.
NumberFormatter::FRACTION_DIGITS (integer)
Fraction digits.
NumberFormatter::MULTIPLIER (integer)
Multiplier.
NumberFormatter::GROUPING_SIZE (integer)
Grouping size.
NumberFormatter::ROUNDING_MODE (integer)
Rounding Mode.
NumberFormatter::ROUNDING_INCREMENT (integer)
Rounding increment.
NumberFormatter::FORMAT_WIDTH (integer)
The width to which the output of format() is padded.
NumberFormatter::PADDING_POSITION (integer)
The position at which padding will take place. See pad position constants for possible argument values.
NumberFormatter::SECONDARY_GROUPING_SIZE (integer)
Secondary grouping size.
NumberFormatter::SIGNIFICANT_DIGITS_USED (integer)
Use significant digits.
NumberFormatter::MIN_SIGNIFICANT_DIGITS (integer)
Minimum significant digits.
NumberFormatter::MAX_SIGNIFICANT_DIGITS (integer)
Maximum significant digits.
NumberFormatter::LENIENT_PARSE (integer)
Lenient parse mode used by rule-based formats.

Number format text attribute used by numfmt_get_text_attribute() and numfmt_set_text_attribute().

NumberFormatter::POSITIVE_PREFIX (integer)
Positive prefix.
NumberFormatter::POSITIVE_SUFFIX (integer)
Positive suffix.
NumberFormatter::NEGATIVE_PREFIX (integer)
Negative prefix.
NumberFormatter::NEGATIVE_SUFFIX (integer)
Negative suffix.
NumberFormatter::PADDING_CHARACTER (integer)
The character used to pad to the format width.
NumberFormatter::CURRENCY_CODE (integer)
The ISO currency code.
NumberFormatter::DEFAULT_RULESET (integer)
The default rule set. This is only available with rule-based formatters.
NumberFormatter::PUBLIC_RULESETS (integer)
The public rule sets. This is only available with rule-based formatters. This is a read-only attribute. The public rulesets are returned as a single string, with each ruleset name delimited by ';' (semicolon).

Number format symbols used by numfmt_get_symbol() and numfmt_set_symbol().

NumberFormatter::DECIMAL_SEPARATOR_SYMBOL (integer)
The decimal separator.
NumberFormatter::GROUPING_SEPARATOR_SYMBOL (integer)
The grouping separator.
NumberFormatter::PATTERN_SEPARATOR_SYMBOL (integer)
The pattern separator.
NumberFormatter::PERCENT_SYMBOL (integer)
The percent sign.
NumberFormatter::ZERO_DIGIT_SYMBOL (integer)
Zero.
NumberFormatter::DIGIT_SYMBOL (integer)
Character representing a digit in the pattern.
NumberFormatter::MINUS_SIGN_SYMBOL (integer)
The minus sign.
NumberFormatter::PLUS_SIGN_SYMBOL (integer)
The plus sign.
NumberFormatter::CURRENCY_SYMBOL (integer)
The currency symbol.
NumberFormatter::INTL_CURRENCY_SYMBOL (integer)
The international currency symbol.
NumberFormatter::MONETARY_SEPARATOR_SYMBOL (integer)
The monetary separator.
NumberFormatter::EXPONENTIAL_SYMBOL (integer)
The exponential symbol.
NumberFormatter::PERMILL_SYMBOL (integer)
Per mill symbol.
NumberFormatter::PAD_ESCAPE_SYMBOL (integer)
Escape padding character.
NumberFormatter::INFINITY_SYMBOL (integer)
Infinity symbol.
NumberFormatter::NAN_SYMBOL (integer)
Not-a-number symbol.
NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL (integer)
Significant digit symbol.
NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL (integer)
The monetary grouping separator.

Rounding mode values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::ROUNDING_MODE attribute.

NumberFormatter::ROUND_CEILING (integer)
Rounding mode to round towards positive infinity.
NumberFormatter::ROUND_DOWN (integer)
Rounding mode to round towards zero.
NumberFormatter::ROUND_FLOOR (integer)
Rounding mode to round towards negative infinity.
NumberFormatter::ROUND_HALFDOWN (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
NumberFormatter::ROUND_HALFEVEN (integer)
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
NumberFormatter::ROUND_HALFUP (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
NumberFormatter::ROUND_UP (integer)
Rounding mode to round away from zero.

Pad position values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::PADDING_POSITION attribute.

NumberFormatter::PAD_AFTER_PREFIX (integer)
Pad characters inserted after the prefix.
NumberFormatter::PAD_AFTER_SUFFIX (integer)
Pad characters inserted after the suffix.
NumberFormatter::PAD_BEFORE_PREFIX (integer)
Pad characters inserted before the prefix.
NumberFormatter::PAD_BEFORE_SUFFIX (integer)
Pad characters inserted before the suffix.

Zobacz też:

  • » ICU formatting documentation
  • » ICU number formatters
  • » ICU decimal formatters
  • » ICU rule-based number formatters

Spis treści

  • NumberFormatter::create — Create a number formatter
  • NumberFormatter::formatCurrency — Format a currency value
  • NumberFormatter::format — Format a number
  • NumberFormatter::getAttribute — Get an attribute
  • NumberFormatter::getErrorCode — Get formatter's last error code.
  • NumberFormatter::getErrorMessage — Get formatter's last error message.
  • NumberFormatter::getLocale — Get formatter locale
  • NumberFormatter::getPattern — Get formatter pattern
  • NumberFormatter::getSymbol — Get a symbol value
  • NumberFormatter::getTextAttribute — Get a text attribute
  • NumberFormatter::parseCurrency — Parse a currency number
  • NumberFormatter::parse — Parse a number
  • NumberFormatter::setAttribute — Set an attribute
  • NumberFormatter::setPattern — Set formatter pattern
  • NumberFormatter::setSymbol — Set a symbol value
  • NumberFormatter::setTextAttribute — Set a text attribute
Collator::sort
NumberFormatter::create
intl


Create a number formatter

NumberFormatter
NumberFormatter::formatCurrency
NumberFormatter
PHP Manual

NumberFormatter::create

numfmt_create

NumberFormatter::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::create -- numfmt_create -- NumberFormatter::__construct — Create a number formatter

Opis

Styl obiektowy (method)

static NumberFormatter NumberFormatter::create ( string $locale , int $style [, string $pattern ] )

Styl proceduralny

NumberFormatter numfmt_create ( string $locale , int $style [, string $pattern ] )

Styl obiektowy (constructor):

NumberFormatter::__construct() ( string $locale , int $style [, string $pattern ] )

Creates a number formatter.

Parametry

locale

Locale in which the number would be formatted (locale name, e.g. en_CA).

style

Style of the formatting, one of the format style constants. If NumberFormatter::PATTERN_DECIMAL or NumberFormatter::PATTERN_RULEBASED is passed then the number format is opened using the given pattern, which must conform to the syntax described in » ICU DecimalFormat documentation or » ICU RuleBasedNumberFormat documentation, respectively.

pattern

Pattern string if the chosen style requires a pattern.

Zwracane wartości

Returns NumberFormatter object or FALSE on error.

Przykłady

Przykład #1 numfmt_create() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
$fmt = numfmt_create( 'it', NumberFormatter::SPELLOUT );
echo numfmt_format($fmt, 1142)."\n";
?>

Przykład #2 NumberFormatter::create() example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo $fmt->format(1234567.891234567890000)."\n";
$fmt = new NumberFormatter( 'it', NumberFormatter::SPELLOUT );
echo $fmt->format(1142)."\n";
?>

Powyższy przykład wyświetli:

1.234.567,891
millicentoquarantadue

Zobacz też:

  • numfmt_format() - Format a number
  • numfmt_parse() - Parse a number

NumberFormatter
NumberFormatter::formatCurrency
NumberFormatter


Format a currency value

NumberFormatter::create
NumberFormatter::format
NumberFormatter
PHP Manual

NumberFormatter::formatCurrency

numfmt_format_currency

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::formatCurrency -- numfmt_format_currency — Format a currency value

Opis

Styl obiektowy

string NumberFormatter::formatCurrency ( float $value , string $currency )

Styl proceduralny

string numfmt_format_currency ( NumberFormatter $fmt , float $value , string $currency )

Format the currency value according to the formatter rules.

Parametry

fmt

NumberFormatter object.

value

The numeric currency value.

currency

The 3-letter ISO 4217 currency code indicating the currency to use.

Zwracane wartości

String representing the formatted currency value.

Przykłady

Przykład #1 numfmt_format_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
$fmt = numfmt_create( 'ru_RU', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
$fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
?>

Powyższy przykład wyświetli:

1.234.567,89 €
1.234.567,89 RUR
1 234 567,89€
1 234 567,89р.

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number

NumberFormatter::create
NumberFormatter::format
NumberFormatter


Format a number

NumberFormatter::formatCurrency
NumberFormatter::getAttribute
NumberFormatter
PHP Manual

NumberFormatter::format

numfmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::format -- numfmt_format — Format a number

Opis

Styl obiektowy

string NumberFormatter::format ( number $value [, int $type ] )

Styl proceduralny

string numfmt_format ( NumberFormatter $fmt , number $value [, int $type ] )

Format a numeric value according to the formatter rules.

Parametry

fmt

NumberFormatter object.

value

The value to format. Can be integer or float, other values will be converted to a numeric value.

type

The formatting type to use.

Zwracane wartości

Returns the string containing formatted value, or FALSE on error.

Przykłady

Przykład #1 numfmt_format() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_format($fmt))) {
    report_error("Formatter error");
}
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

Powyższy przykład wyświetli:

1.234.567,891

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format_currency() - Format a currency value
  • numfmt_parse() - Parse a number

NumberFormatter::formatCurrency
NumberFormatter::getAttribute
NumberFormatter


Get an attribute

NumberFormatter::format
NumberFormatter::getErrorCode
NumberFormatter
PHP Manual

NumberFormatter::getAttribute

numfmt_get_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getAttribute -- numfmt_get_attribute — Get an attribute

Opis

Styl obiektowy

int NumberFormatter::getAttribute ( int $attr )

Styl proceduralny

int numfmt_get_attribute ( NumberFormatter $fmt , int $attr )

Get a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

Parametry

fmt

NumberFormatter object.

attr

Attribute specifier - one of the numeric attribute constants.

Zwracane wartości

Return attribute value on success, or FALSE on error.

Przykłady

Przykład #1 numfmt_get_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

Powyższy przykład wyświetli:

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_text_attribute() - Get a text attribute
  • numfmt_set_attribute() - Set an attribute

NumberFormatter::format
NumberFormatter::getErrorCode
NumberFormatter


Get formatter's last error code.

NumberFormatter::getAttribute
NumberFormatter::getErrorMessage
NumberFormatter
PHP Manual

NumberFormatter::getErrorCode

numfmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getErrorCode -- numfmt_get_error_code — Get formatter's last error code.

Opis

Styl obiektowy

int NumberFormatter::getErrorCode ( void )

Styl proceduralny

int numfmt_get_error_code ( NumberFormatter $fmt )

Get error code from the last function performed by the formatter.

Parametry

fmt

NumberFormatter object.

Zwracane wartości

Returns error code from last formatter call.

Przykłady

Przykład #1 numfmt_get_error_code() example

<?php
$fmt  = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_get_error_code($fmt))) {
    report_error("Formatter error");
}
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

Zobacz też:

  • numfmt_get_error_message() - Get formatter's last error message.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

NumberFormatter::getAttribute
NumberFormatter::getErrorMessage
NumberFormatter


Get formatter's last error message.

NumberFormatter::getErrorCode
NumberFormatter::getLocale
NumberFormatter
PHP Manual

NumberFormatter::getErrorMessage

numfmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getErrorMessage -- numfmt_get_error_message — Get formatter's last error message.

Opis

Styl obiektowy

string NumberFormatter::getErrorMessage ( void )

Styl proceduralny

string numfmt_get_error_message ( NumberFormatter $fmt )

Get error message from the last function performed by the formatter.

Parametry

fmt

NumberFormatter object.

Zwracane wartości

Returns error message from last formatter call.

Przykłady

Przykład #1 numfmt_get_error_message() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_get_error_code($fmt))) {
    report_error("Formatter error");
}
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

NumberFormatter::getErrorCode
NumberFormatter::getLocale
NumberFormatter


Get formatter locale

NumberFormatter::getErrorMessage
NumberFormatter::getPattern
NumberFormatter
PHP Manual

NumberFormatter::getLocale

numfmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getLocale -- numfmt_get_locale — Get formatter locale

Opis

Styl obiektowy

string NumberFormatter::getLocale ([ int $type ] )

Styl proceduralny

string numfmt_get_locale ( NumberFormatter $fmt [, int $type ] )

Get formatter locale name.

Parametry

fmt

NumberFormatter object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE, Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

Zwracane wartości

The locale name used to create the formatter.

Przykłady

Przykład #1 numfmt_get_locale() example

<?php
$req     = 'fr_FR_PARIS';
$fmt     = numfmt_create( $req,  NumberFormatter::DECIMAL);
$res_val = numfmt_get_locale( $fmt, Locale::VALID_LOCALE );
$res_act = numfmt_get_locale( $fmt, Locale::ACTUAL_LOCALE );
printf( "Requested locale name: %s\nValid locale name: %s\nActual locale name: %s\n",
         $req, $res_val, $res_act );
?>

Powyższy przykład wyświetli:

Requested locale name: fr_FR_PARIS
Valid locale name: fr_FR
Actual locale name: fr

Zobacz też:

  • numfmt_create() - Create a number formatter
  • numfmt_get_error_code() - Get formatter's last error code.

NumberFormatter::getErrorMessage
NumberFormatter::getPattern
NumberFormatter


Get formatter pattern

NumberFormatter::getLocale
NumberFormatter::getSymbol
NumberFormatter
PHP Manual

NumberFormatter::getPattern

numfmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getPattern -- numfmt_get_pattern — Get formatter pattern

Opis

Styl obiektowy

string NumberFormatter::getPattern ( void )

Styl proceduralny

string numfmt_get_pattern ( NumberFormatter $fmt )

Extract pattern used by the formatter.

Parametry

fmt

NumberFormatter object.

Zwracane wartości

Pattern string that is used by the formatter, or FALSE if an error happens.

Przykłady

Przykład #1 numfmt_get_pattern() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

Powyższy przykład wyświetli:

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_set_pattern() - Set formatter pattern
  • numfmt_create() - Create a number formatter

NumberFormatter::getLocale
NumberFormatter::getSymbol
NumberFormatter


Get a symbol value

NumberFormatter::getPattern
NumberFormatter::getTextAttribute
NumberFormatter
PHP Manual

NumberFormatter::getSymbol

numfmt_get_symbol

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getSymbol -- numfmt_get_symbol — Get a symbol value

Opis

Styl obiektowy

string NumberFormatter::getSymbol ( int $attr )

Styl proceduralny

string numfmt_get_symbol ( NumberFormatter $fmt , int $attr )

Get a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

Parametry

fmt

NumberFormatter object.

attr

Symbol specifier, one of the format symbol constants.

Zwracane wartości

The symbol string or FALSE on error.

Przykłady

Przykład #1 numfmt_get_symbol() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

Powyższy przykład wyświetli:

Sep: .
1.234.567,891
Sep: *
1*234*567,891

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_set_symbol() - Set a symbol value

NumberFormatter::getPattern
NumberFormatter::getTextAttribute
NumberFormatter


Get a text attribute

NumberFormatter::getSymbol
NumberFormatter::parseCurrency
NumberFormatter
PHP Manual

NumberFormatter::getTextAttribute

numfmt_get_text_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::getTextAttribute -- numfmt_get_text_attribute — Get a text attribute

Opis

Styl obiektowy

string NumberFormatter::getTextAttribute ( int $attr )

Styl proceduralny

string numfmt_get_text_attribute ( NumberFormatter $fmt , int $attr )

Get a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, U_UNSUPPORTED_ERROR error is produced. Rule-based formatters only understand NumberFormatter::DEFAULT_RULESET and NumberFormatter::PUBLIC_RULESETS.

Parametry

fmt

NumberFormatter object.

attr

Attribute specifier - one of the text attribute constants.

Zwracane wartości

Return attribute value on success, or FALSE on error.

Przykłady

Przykład #1 numfmt_get_text_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>

Powyższy przykład wyświetli:

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_attribute() - Get an attribute
  • numfmt_set_text_attribute() - Set a text attribute

NumberFormatter::getSymbol
NumberFormatter::parseCurrency
NumberFormatter


Parse a currency number

NumberFormatter::getTextAttribute
NumberFormatter::parse
NumberFormatter
PHP Manual

NumberFormatter::parseCurrency

numfmt_parse_currency

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::parseCurrency -- numfmt_parse_currency — Parse a currency number

Opis

Styl obiektowy

float NumberFormatter::parseCurrency ( string $value , string &$currency [, int &$position ] )

Styl proceduralny

float numfmt_parse_currency ( NumberFormatter $fmt , string $value , string &$currency [, int &$position ] )

Parse a string into a double and a currency using the current formatter.

Parametry

fmt

NumberFormatter object.

currency

Parameter to receive the currency name (3-letter ISO 4217 currency code).

position

Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

Zwracane wartości

The parsed numeric value or FALSE on error.

Przykłady

Przykład #1 numfmt_parse_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".numfmt_parse_currency($fmt, $num, $curr)." in $curr\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
?>

Powyższy przykład wyświetli:

We have 1234567.89 in USD

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_parse() - Parse a number
  • numfmt_format_currency() - Format a currency value

NumberFormatter::getTextAttribute
NumberFormatter::parse
NumberFormatter


Parse a number

NumberFormatter::parseCurrency
NumberFormatter::setAttribute
NumberFormatter
PHP Manual

NumberFormatter::parse

numfmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::parse -- numfmt_parse — Parse a number

Opis

Styl obiektowy

mixed NumberFormatter::parse ( string $value [, int $type [, int &$position ]] )

Styl proceduralny

mixed numfmt_parse ( NumberFormatter $fmt , string $value [, int $type [, int &$position ]] )

Parse a string into a number using the current formatter rules.

Parametry

fmt

NumberFormatter object.

type

The formatting type to use. By default, NumberFormatter::TYPE_DOUBLE is used.

position

Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

Zwracane wartości

The value of the parsed number or FALSE on error.

Przykłady

Przykład #1 numfmt_parse() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo numfmt_parse($fmt, $num)."\n";
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."\n";
echo $fmt->parse($num, NumberFormatter::TYPE_INT32)."\n";
?>

Powyższy przykład wyświetli:

1234567.891
1234567

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number

NumberFormatter::parseCurrency
NumberFormatter::setAttribute
NumberFormatter


Set an attribute

NumberFormatter::parse
NumberFormatter::setPattern
NumberFormatter
PHP Manual

NumberFormatter::setAttribute

numfmt_set_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setAttribute -- numfmt_set_attribute — Set an attribute

Opis

Styl obiektowy

bool NumberFormatter::setAttribute ( int $attr , int $value )

Styl proceduralny

bool numfmt_set_attribute ( NumberFormatter $fmt , int $attr , int $value )

Set a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

Parametry

fmt

NumberFormatter object.

attr

Attribute specifier - one of the numeric attribute constants.

value

The attribute value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 numfmt_set_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

Powyższy przykład wyświetli:

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_attribute() - Get an attribute
  • numfmt_set_text_attribute() - Set a text attribute

NumberFormatter::parse
NumberFormatter::setPattern
NumberFormatter


Set formatter pattern

NumberFormatter::setAttribute
NumberFormatter::setSymbol
NumberFormatter
PHP Manual

NumberFormatter::setPattern

numfmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setPattern -- numfmt_set_pattern — Set formatter pattern

Opis

Styl obiektowy

bool NumberFormatter::setPattern ( string $pattern )

Styl proceduralny

bool numfmt_set_pattern ( NumberFormatter $fmt , string $pattern )

Set the pattern used by the formatter. Can not be used on a rule-based formatter.

Parametry

fmt

NumberFormatter object.

pattern

Pattern in syntax described in » ICU DecimalFormat documentation.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 numfmt_set_pattern() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

Powyższy przykład wyświetli:

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_create() - Create a number formatter
  • numfmt_get_pattern() - Get formatter pattern

NumberFormatter::setAttribute
NumberFormatter::setSymbol
NumberFormatter


Set a symbol value

NumberFormatter::setPattern
NumberFormatter::setTextAttribute
NumberFormatter
PHP Manual

NumberFormatter::setSymbol

numfmt_set_symbol

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setSymbol -- numfmt_set_symbol — Set a symbol value

Opis

Styl obiektowy

bool NumberFormatter::setSymbol ( int $attr , string $value )

Styl proceduralny

bool numfmt_set_symbol ( NumberFormatter $fmt , int $attr , string $value )

Set a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

Parametry

fmt

NumberFormatter object.

attr

Symbol specifier, one of the format symbol constants.

value

Text for the symbol.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 numfmt_set_symbol() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

Powyższy przykład wyświetli:

Sep: .
1.234.567,891
Sep: *
1*234*567,891

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_symbol() - Get a symbol value

NumberFormatter::setPattern
NumberFormatter::setTextAttribute
NumberFormatter


Set a text attribute

NumberFormatter::setSymbol
Locale
NumberFormatter
PHP Manual

NumberFormatter::setTextAttribute

numfmt_set_text_attribute

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

NumberFormatter::setTextAttribute -- numfmt_set_text_attribute — Set a text attribute

Opis

Styl obiektowy

bool NumberFormatter::setTextAttribute ( int $attr , string $value )

Styl proceduralny

bool numfmt_set_text_attribute ( NumberFormatter $fmt , int $attr , string $value )

Set a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, U_UNSUPPORTED_ERROR error is produced. Rule-based formatters only understand NumberFormatter::DEFAULT_RULESET and NumberFormatter::PUBLIC_RULESETS.

Parametry

fmt

NumberFormatter object.

attr

Attribute specifier - one of the text attribute constants.

value

Text for the attribute value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 numfmt_set_text_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>

Przykład #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>

Powyższy przykład wyświetli:

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

Zobacz też:

  • numfmt_get_error_code() - Get formatter's last error code.
  • numfmt_get_text_attribute() - Get a text attribute
  • numfmt_set_attribute() - Set an attribute

NumberFormatter::setSymbol
Locale
NumberFormatter


The Locale class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Wstęp

A "Locale" is an identifier used to get language, culture, or regionally-specific behavior from an API. PHP locales are organized and identified the same way that the CLDR locales used by ICU (and many vendors of Unix-like operating systems, the Mac, Java, and so forth) use. Locales are identified using RFC 4646 language tags (which use hyphen, not underscore) in addition to the more traditional underscore-using identifiers. Unless otherwise noted the functions in this class are tolerant of both formats.

Examples of identifiers include:

  • en-US (English, United States)
  • zh-Hant-TW (Chinese, Traditional Script, Taiwan)
  • fr-CA, fr-FR (French for Canada and France respectively)

The Locale class (and related procedural functions) are used to interact with locale identifiers--to verify that an ID is well-formed, valid, etc. The extensions used by CLDR in UAX #35 (and inherited by ICU) are valid and used wherever they would be in ICU normally.

Locales cannot be instantiated as objects. All of the functions/methods provided are static.

The null or empty string obtains the "root" locale. The "root" locale is equivalent to "en_US_POSIX" in CLDR. Language tags (and thus locale identifiers) are case insensitive. There exists a canonicalization function to make case match the specification.

Krótki opis klasy

Locale {
/* Metody */
static string acceptFromHttp ( string $header )
static string composeLocale ( array $subtags )
static bool filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )
static array getAllVariants ( string $locale )
static string getDefault ( void )
static string getDisplayLanguage ( string $locale [, string $in_locale ] )
static string getDisplayName ( string $locale [, string $in_locale ] )
static string getDisplayRegion ( string $locale [, string $in_locale ] )
static string getDisplayScript ( string $locale [, string $in_locale ] )
static string getDisplayVariant ( string $locale [, string $in_locale ] )
static array getKeywords ( string $locale )
static string getPrimaryLanguage ( string $locale )
static string getRegion ( string $locale )
static string getScript ( string $locale )
static string lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )
static array parseLocale ( string $locale )
static bool setDefault ( string $locale )
}

Stałe predefiniowane

Locale::DEFAULT_LOCALE (null)
Used as locale parameter with the methods of the various locale affected classes, such as NumberFormatter. This constant would make the methods to use default locale.

These constants describe the choice of the locale for getLocalte method of different classes.

Locale::ACTUAL_LOCALE (string)
This is locale the data actually comes from.
Locale::VALID_LOCALE (string)
This is the most specific locale supported by ICU.

These constants define how the Locales are parsed or composed. They should be used as keys in the argument array to locale_compose() and are returned from locale_parse() as keys of the returned associative array.

Locale::LANG_TAG (string)
Language subtag
Locale::EXTLANG_TAG (string)
Extended language subtag
Locale::SCRIPT_TAG (string)
Script subtag
Locale::REGION_TAG (string)
Region subtag
Locale::VARIANT_TAG (string)
Variant subtag
Locale::GRANDFATHERED_LANG_TAG (string)
Grandfathered Language subtag
Locale::PRIVATE_TAG (string)
Private subtag

Zobacz też:

  • » RFC 4646 - Tags for Identifying Languages
  • » RFC 4647 - Matching of Language Tags
  • » Unicode CLDR Project:Common Locale Data Repository
  • » IANA Language Subtags Registry
  • » ICU User Guide - Locale
  • » ICU Locale api

Spis treści

  • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
  • Locale::composeLocale — Returns a correctly ordered and delimited locale ID
  • Locale::filterMatches — Checks if a language tag filter matches with locale
  • Locale::getAllVariants — Gets the variants for the input locale
  • Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
  • Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
  • Locale::getDisplayName — Returns an appropriately localized display name for the input locale
  • Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
  • Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
  • Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
  • Locale::getKeywords — Gets the keywords for the input locale
  • Locale::getPrimaryLanguage — Gets the primary language for the input locale
  • Locale::getRegion — Gets the region for the input locale
  • Locale::getScript — Gets the script for the input locale
  • Locale::lookup — Searches the language tag list for the best match to the language
  • Locale::parseLocale — Returns a key-value array of locale ID subtag elements.
  • Locale::setDefault — sets the default runtime locale
NumberFormatter::setTextAttribute
Locale::acceptFromHttp
intl


Tries to find out best available locale based on HTTP "Accept-Language" header

Locale
Locale::composeLocale
Locale
PHP Manual

Locale::acceptFromHttp

locale_accept_from_http

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::acceptFromHttp -- locale_accept_from_http — Tries to find out best available locale based on HTTP "Accept-Language" header

Opis

Styl obiektowy

static string Locale::acceptFromHttp ( string $header )

Styl proceduralny

string locale_accept_from_http ( string $header )

Tries to find locale that can satisfy the language list that is requested by the HTTP "Accept-Language" header.

Parametry

header

The string containing the "Accept-Language" header according to format in RFC 2616.

Zwracane wartości

The corresponding locale identifier.

Przykłady

Przykład #1 locale_accept_from_http() example

<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

Przykład #2 OO example

<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

Powyższy przykład wyświetli:

en_US

Zobacz też:

  • locale_lookup() - Searches the language tag list for the best match to the language

Locale
Locale::composeLocale
Locale


Returns a correctly ordered and delimited locale ID

Locale::acceptFromHttp
Locale::filterMatches
Locale
PHP Manual

Locale::composeLocale

locale_compose

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::composeLocale -- locale_compose — Returns a correctly ordered and delimited locale ID

Opis

Styl obiektowy

static string Locale::composeLocale ( array $subtags )

Styl proceduralny

string locale_compose ( array $subtags )

Returns a correctly ordered and delimited locale ID the keys identify the particular locale ID subtags, and the values are the associated subtag values.

Parametry

subtags

an array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values.

Informacja:

The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values.e.g. Variants are allowed with the suffix ranging from 0-14. Hence the keys for the input array can be variant0, variant1, ...,variant14. In the returned locale id, the subtag is ordered by suffix resulting in variant0 followed by variant1 followed by variant2 and so on.

The 'variant', 'private' and 'extlang' multiple values can be specified both as array under specific key (e.g. 'variant') and as multiple numbered keys (e.g. 'variant0', 'variant1', etc.).

Zwracane wartości

The corresponding locale identifier.

Przykłady

Przykład #1 locale_compose() example

<?php
$arr = array(
    'language'=>'en' ,
    'script'  =>'Hans' ,
    'region'  =>'CN',
    'variant2'=>'rozaj' ,
    'variant1'=>'nedis' ,
    'private1'=>'prv1' ,
    'private2'=>'prv2'
);
echo locale_compose( $arr );
?>

Przykład #2 OO example

<?php
$arr = array(
    'language'=>'en' ,
    'script'  =>'Hans' ,
    'region'  =>'CN',
    'variant2'=>'rozaj' ,
    'variant1'=>'nedis' ,
    'private1'=>'prv1' ,
    'private2'=>'prv2'
);
echo Locale::composeLocale( $arr );
?>

Powyższy przykład wyświetli:

Locale: en_Hans_CN_nedis_rozaj_x_prv1_prv2

Zobacz też:

  • locale_parse() - Returns a key-value array of locale ID subtag elements.

Locale::acceptFromHttp
Locale::filterMatches
Locale


Checks if a language tag filter matches with locale

Locale::composeLocale
Locale::getAllVariants
Locale
PHP Manual

Locale::filterMatches

locale_filter_matches

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::filterMatches -- locale_filter_matches — Checks if a language tag filter matches with locale

Opis

Styl obiektowy

static bool Locale::filterMatches ( string $langtag , string $locale [, bool $canonicalize = false ] )

Styl proceduralny

bool locale_filter_matches ( string $langtag , string $locale [, bool $canonicalize = false ] )

Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm

Parametry

langtag

The language tag to check

locale

The language range to check against

canonicalize

If true, the arguments will be converted to canonical form before matching.

Zwracane wartości

TRUE if $locale matches $langtag FALSE otherwise.

Przykłady

Przykład #1 locale_filter_matches() example

<?php
echo (locale_filter_matches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (locale_filter_matches('de-DE_1996','de-DE', false)) ? "Matches" : "Does not match";
?>

Przykład #2 OO example

<?php
echo (Locale::filterMatches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (Locale::filterMatches('de-DE-1996','de-DE', false)) ? "Matches" : "Does not match";
?>

Powyższy przykład wyświetli:

Does not match; Matches

Zobacz też:

  • locale_lookup() - Searches the language tag list for the best match to the language

Locale::composeLocale
Locale::getAllVariants
Locale


Gets the variants for the input locale

Locale::filterMatches
Locale::getDefault
Locale
PHP Manual

Locale::getAllVariants

locale_get_all_variants

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getAllVariants -- locale_get_all_variants — Gets the variants for the input locale

Opis

Styl obiektowy

static array Locale::getAllVariants ( string $locale )

Styl proceduralny

array locale_get_all_variants ( string $locale )

Gets the variants for the input locale

Parametry

locale

The locale to extract the variants from

Zwracane wartości

The array containing the list of all variants subtag for the locale or NULL if not present

Przykłady

Przykład #1 locale_get_all_variants() example

<?php
$arr = locale_get_all_variants('sl_IT_NEDIS_ROJAZ_1901');
var_export( $arr );
?>

Przykład #2 OO example

<?php
 $arr = Locale::getAllVariants('sl_IT_NEDIS_ROJAZ_1901');
 var_export( $arr );
?>

Powyższy przykład wyświetli:

array (
    0 => 'NEDIS',
    1 => 'ROJAZ',
    2 => '1901',
)

Zobacz też:

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_script() - Gets the script for the input locale
  • locale_get_region() - Gets the region for the input locale

Locale::filterMatches
Locale::getDefault
Locale


Gets the default locale value from the INTL global 'default_locale'

Locale::getAllVariants
Locale::getDisplayLanguage
Locale
PHP Manual

Locale::getDefault

locale_get_default

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDefault -- locale_get_default — Gets the default locale value from the INTL global 'default_locale'

Opis

Styl obiektowy

static string Locale::getDefault ( void )

Styl proceduralny

string locale_get_default ( void )

Gets the default locale value. At the PHP initialization this value is set to 'intl.default_locale' value from php.ini if that value exists or from ICU's function uloc_getDefault().

Parametry

Zwracane wartości

The current runtime locale

Przykłady

Przykład #1 locale_get_default() example

<?php
ini_set('intl.default_locale', 'de-DE');
echo locale_get_default();
echo '; ';
locale_set_default('fr');
echo locale_get_default();
?>

Przykład #2 OO example

<?php
ini_set('intl.default_locale', 'de-DE');
echo Locale::getDefault();
echo '; ';
Locale::setDefault('fr');
echo Locale::getDefault();
?>

Powyższy przykład wyświetli:

de-DE; fr

Zobacz też:

  • locale_set_default() - sets the default runtime locale

Locale::getAllVariants
Locale::getDisplayLanguage
Locale


Returns an appropriately localized display name for language of the inputlocale

Locale::getDefault
Locale::getDisplayName
Locale
PHP Manual

Locale::getDisplayLanguage

locale_get_display_language

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayLanguage -- locale_get_display_language — Returns an appropriately localized display name for language of the inputlocale

Opis

Styl obiektowy

static string Locale::getDisplayLanguage ( string $locale [, string $in_locale ] )

Styl proceduralny

string locale_get_display_language ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for language of the input locale. If is NULL then the default locale is used.

Parametry

locale

The locale to return a display language for

in_locale

Optional format locale to use to display the language name

Zwracane wartości

display name of the language for the $locale in the format appropriate for $in_locale.

Przykłady

Przykład #1 locale_get_display_language() example

<?php
echo locale_get_display_language('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'de');
?>

Przykład #2 OO example

<?php
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'de');
?>

Powyższy przykład wyświetli:

Slovenian;
slov\xc3\xa8ne;
Slowenisch

Zobacz też:

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

Locale::getDefault
Locale::getDisplayName
Locale


Returns an appropriately localized display name for the input locale

Locale::getDisplayLanguage
Locale::getDisplayRegion
Locale
PHP Manual

Locale::getDisplayName

locale_get_display_name

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayName -- locale_get_display_name — Returns an appropriately localized display name for the input locale

Opis

Styl obiektowy

static string Locale::getDisplayName ( string $locale [, string $in_locale ] )

Styl proceduralny

string locale_get_display_name ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for the input locale. If is NULL then the default locale is used.

Parametry

locale

The locale to return a display name for.

in_locale

optional format locale

Zwracane wartości

Display name of the locale in the format appropriate for $in_locale.

Przykłady

Przykład #1 locale_get_display_name() example

<?php
echo locale_get_display_name('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'de');
?>

Przykład #2 OO example

<?php
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'de');
?>

Powyższy przykład wyświetli:

Slovenian (Latin, Italy, Natisone dialect);
slov\xc3\xa8ne (latin, Italie, dialecte de Natisone;
Slowenisch (Lateinisch, Italien, NEDIS)

Zobacz też:

  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayLanguage
Locale::getDisplayRegion
Locale


Returns an appropriately localized display name for region of the input locale

Locale::getDisplayName
Locale::getDisplayScript
Locale
PHP Manual

Locale::getDisplayRegion

locale_get_display_region

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayRegion -- locale_get_display_region — Returns an appropriately localized display name for region of the input locale

Opis

Styl obiektowy

static string Locale::getDisplayRegion ( string $locale [, string $in_locale ] )

Styl proceduralny

string locale_get_display_region ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for region of the input locale. If is NULL then the default locale is used.

Parametry

locale

The locale to return a display region for.

in_locale

Optional format locale to use to display the region name

Zwracane wartości

display name of the region for the $locale in the format appropriate for $in_locale.

Przykłady

Przykład #1 locale_get_display_region() example

<?php
echo locale_get_display_region('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'de');
?>

Przykład #2 OO example

<?php
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'de');
?>

Powyższy przykład wyświetli:

Italy;
Italie;
Italien

Zobacz też:

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayName
Locale::getDisplayScript
Locale


Returns an appropriately localized display name for script of the input locale

Locale::getDisplayRegion
Locale::getDisplayVariant
Locale
PHP Manual

Locale::getDisplayScript

locale_get_display_script

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayScript -- locale_get_display_script — Returns an appropriately localized display name for script of the input locale

Opis

Styl obiektowy

static string Locale::getDisplayScript ( string $locale [, string $in_locale ] )

Styl proceduralny

string locale_get_display_script ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for script of the input locale. If is NULL then the default locale is used.

Parametry

locale

The locale to return a display script for

in_locale

Optional format locale to use to display the script name

Zwracane wartości

Display name of the script for the $locale in the format appropriate for $in_locale.

Przykłady

Przykład #1 locale_get_display_script() example

<?php
echo locale_get_display_script('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'de');
?>

Przykład #2 OO example

<?php
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'de');
?>

Powyższy przykład wyświetli:

Latin;
latin;
Lateinisch

Zobacz też:

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayRegion
Locale::getDisplayVariant
Locale


Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayScript
Locale::getKeywords
Locale
PHP Manual

Locale::getDisplayVariant

locale_get_display_variant

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getDisplayVariant -- locale_get_display_variant — Returns an appropriately localized display name for variants of the input locale

Opis

Styl obiektowy

static string Locale::getDisplayVariant ( string $locale [, string $in_locale ] )

Styl proceduralny

string locale_get_display_variant ( string $locale [, string $in_locale ] )

Returns an appropriately localized display name for variants of the input locale. If is NULL then the default locale is used.

Parametry

locale

The locale to return a display variant for

in_locale

Optional format locale to use to display the variant name

Zwracane wartości

Display name of the variant for the $locale in the format appropriate for $in_locale.

Przykłady

Przykład #1 locale_get_display_variant() example

<?php
echo locale_get_display_variant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'de');
?>

Przykład #2 OO example

<?php
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'de');
?>

Powyższy przykład wyświetli:

Natisone dialect;
dialecte de Natisone;
NEDIS

Zobacz też:

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale

Locale::getDisplayScript
Locale::getKeywords
Locale


Gets the keywords for the input locale

Locale::getDisplayVariant
Locale::getPrimaryLanguage
Locale
PHP Manual

Locale::getKeywords

locale_get_keywords

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getKeywords -- locale_get_keywords — Gets the keywords for the input locale

Opis

Styl obiektowy

static array Locale::getKeywords ( string $locale )

Styl proceduralny

array locale_get_keywords ( string $locale )

Gets the keywords for the input locale.

Parametry

locale

The locale to extract the keywords from

Zwracane wartości

Associative array containing the keyword-value pairs for this locale

Przykłady

Przykład #1 locale_get_keywords() example

<?php
$keywords_arr = locale_get_keywords( 'de_DE@currency=EUR;collation=PHONEBOOK' );
if ($keywords_arr) {
    foreach ($keywords_arr as $key => $value) {
        echo "$key = $value\n";
    }
}
?>

Przykład #2 OO example

<?php
$keywords_arr = Locale::getKeywords( 'de_DE@currency=EUR;collation=PHONEBOOK' );
if ($keywords_arr) {
    foreach( $keywords_arr as $key => $value){
        echo "$key = $value\n";
    }
}
?>

Powyższy przykład wyświetli:

collation = PHONEBOOK
currency = EUR

Zobacz też:

  • locale_get_all_variants() - Gets the variants for the input locale

Locale::getDisplayVariant
Locale::getPrimaryLanguage
Locale


Gets the primary language for the input locale

Locale::getKeywords
Locale::getRegion
Locale
PHP Manual

Locale::getPrimaryLanguage

locale_get_primary_language

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getPrimaryLanguage -- locale_get_primary_language — Gets the primary language for the input locale

Opis

Styl obiektowy

static string Locale::getPrimaryLanguage ( string $locale )

Styl proceduralny

string locale_get_primary_language ( string $locale )

Gets the primary language for the input locale

Parametry

locale

The locale to extract the primary language code from

Zwracane wartości

The language code associated with the language or NULL in case of error.

Przykłady

Przykład #1 locale_get_primary_language() example

<?php
echo locale_get_primary_language('zh-Hant');
?>

Przykład #2 OO example

<?php
echo Locale::getPrimaryLanguage('zh-Hant');
?>

Powyższy przykład wyświetli:

zh

Zobacz też:

  • locale_get_script() - Gets the script for the input locale
  • locale_get_region() - Gets the region for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

Locale::getKeywords
Locale::getRegion
Locale


Gets the region for the input locale

Locale::getPrimaryLanguage
Locale::getScript
Locale
PHP Manual

Locale::getRegion

locale_get_region

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getRegion -- locale_get_region — Gets the region for the input locale

Opis

Styl obiektowy

static string Locale::getRegion ( string $locale )

Styl proceduralny

string locale_get_region ( string $locale )

Gets the region for the input locale.

Parametry

locale

The locale to extract the region code from

Zwracane wartości

The region subtag for the locale or NULL if not present

Przykłady

Przykład #1 locale_get_region() example

<?php
echo locale_get_region('de-CH-1901');
?>

Przykład #2 OO example

<?php
echo Locale::getRegion('de-CH-1901');
?>

Powyższy przykład wyświetli:

CH

Zobacz też:

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_script() - Gets the script for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

Locale::getPrimaryLanguage
Locale::getScript
Locale


Gets the script for the input locale

Locale::getRegion
Locale::lookup
Locale
PHP Manual

Locale::getScript

locale_get_script

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::getScript -- locale_get_script — Gets the script for the input locale

Opis

Styl obiektowy

static string Locale::getScript ( string $locale )

Styl proceduralny

string locale_get_script ( string $locale )

Gets the script for the input locale.

Parametry

locale

The locale to extract the script code from

Zwracane wartości

The script subtag for the locale or NULL if not present

Przykłady

Przykład #1 locale_get_script() example

<?php
echo locale_get_script('sr-Cyrl');
?>

Przykład #2 OO example

<?php
echo Locale::getScript('sr-Cyrl');
?>

Powyższy przykład wyświetli:

Cyrl

Zobacz też:

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_region() - Gets the region for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

Locale::getRegion
Locale::lookup
Locale


Searches the language tag list for the best match to the language

Locale::getScript
Locale::parseLocale
Locale
PHP Manual

Locale::lookup

locale_lookup

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::lookup -- locale_lookup — Searches the language tag list for the best match to the language

Opis

Styl obiektowy

static string Locale::lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )

Styl proceduralny

string locale_lookup ( array $langtag , string $locale [, bool $canonicalize = false [, string $default ]] )

Searches the items in langtag for the best match to the language range specified in locale according to RFC 4647's lookup algorithm.

Parametry

langtag

An array containing a list of language tags to compare to locale. Maximum 100 items allowed.

locale

The locale to use as the language range when matching.

canonicalize

If true, the arguments will be converted to canonical form before matching.

default

The locale to use if no match is found.

Zwracane wartości

The closest matching language tag or default value.

Przykłady

Przykład #1 locale_lookup() example

<?php
$arr = array(
    'de-DEVA',
    'de-DE-1996',
    'de',
    'de-De'
);
echo locale_lookup($arr, 'de-DE-1996-x-prv1-prv2', 'en_US');
?>

Przykład #2 OO example

<?php
$arr = array(
    'de-DEVA',
    'de-DE-1996',
    'de',
    'de-De'
);
echo Locale::lookup($arr, 'de-DE-1996-x-prv1-prv2', 'en_US');
?>

Powyższy przykład wyświetli:

de_de_1996

Zobacz też:

  • locale_filter_matches() - Checks if a language tag filter matches with locale

Locale::getScript
Locale::parseLocale
Locale


Returns a key-value array of locale ID subtag elements.

Locale::lookup
Locale::setDefault
Locale
PHP Manual

Locale::parseLocale

locale_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::parseLocale -- locale_parse — Returns a key-value array of locale ID subtag elements.

Opis

Styl obiektowy

static array Locale::parseLocale ( string $locale )

Styl proceduralny

array locale_parse ( string $locale )

Returns a key-value array of locale ID subtag elements.

Parametry

locale

The locale to extract the subtag array from. Note: The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values.

Zwracane wartości

Returns an array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values. The array will be ordered as the locale id subtags e.g. in the locale id if variants are '-varX-varY-varZ' then the returned array will have variant0=>varX , variant1=>varY , variant2=>varZ

Przykłady

Przykład #1 locale_parse() example

<?php
$arr = locale_parse('sl-Latn-IT-nedis');
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}
?>

Przykład #2 OO example

<?php
$arr = Locale::parseLocale('sl-Latn-IT-nedis');
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}
?>

Powyższy przykład wyświetli:

language : sl , script : Latn , region : IT , variant0 : NEDIS ,

Zobacz też:

  • locale_compose() - Returns a correctly ordered and delimited locale ID

Locale::lookup
Locale::setDefault
Locale


sets the default runtime locale

Locale::parseLocale
Normalizer
Locale
PHP Manual

Locale::setDefault

locale_set_default

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Locale::setDefault -- locale_set_default — sets the default runtime locale

Opis

Styl obiektowy

static bool Locale::setDefault ( string $locale )

Styl proceduralny

bool locale_set_default ( string $locale )

Sets the default runtime locale to $locale. This changes the value of INTL global 'default_locale' locale identifier. UAX #35 extensions are accepted.

Parametry

locale

Is a BCP 47 compliant language tag containing the

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 locale_set_default() example

<?php
locale_set_default('de-DE');
echo locale_get_default();
?>

Przykład #2 OO example

<?php
Locale::setDefault('de-DE');
echo Locale::getDefault();
?>

Powyższy przykład wyświetli:

de-DE

Zobacz też:

  • locale_get_default() - Gets the default locale value from the INTL global 'default_locale'

Locale::parseLocale
Normalizer
Locale


The Normalizer class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Wstęp

Normalization is a process that involves transforming characters and sequences of characters into a formally-defined underlying representation. This process is most important when text needs to be compared for sorting and searching, but it is also used when storing text to ensure that the text is stored in a consistent representation.

The Unicode Consortium has defined a number of normalization forms reflecting the various needs of applications:

  • Normalization Form D (NFD) - Canonical Decomposition
  • Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
  • Normalization Form KD (NFKD) - Compatibility Decomposition
  • Normalization Form KC (NFKC) - Compatibility Decomposition followed by Canonical Composition
The different forms are defined in terms of a set of transformations on the text, transformations that are expressed by both an algorithm and a set of data files.

Krótki opis klasy

Normalizer {
/* Metody */
static bool isNormalized ( string $input [, string $form = Normalizer::FORM_C ] )
static string normalize ( string $input [, string $form = Normalizer::FORM_C ] )
}

Stałe predefiniowane

The following constants define the normalization form used by the normalizer:

Normalizer::FORM_C (string)
Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
Normalizer::FORM_D (string)
Normalization Form D (NFD) - Canonical Decomposition
Normalizer::FORM_KC (string)
Normalization Form KC (NFKC) - Compatibility Decomposition, followed by Canonical Composition
Normalizer::FORM_KD (string)
Normalization Form KD (NFKD) - Compatibility Decomposition
Normalizer::NONE (string)
No decomposition/composition
Normalizer::OPTION_DEFAULT (string)
Default normalization options

Zobacz też:

  • » Unicode Normalization
  • » Unicode Normalization FAQ
  • » ICU User Guide - Normalization
  • » ICU API Reference - Normalization

Spis treści

  • Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form.
  • Normalizer::normalize — Normalizes the input provided and returns the normalized string
Locale::setDefault
Normalizer::isNormalized
intl


Checks if the provided string is already in the specified normalization form.

Normalizer
Normalizer::normalize
Normalizer
PHP Manual

Normalizer::isNormalized

normalizer_is_normalized

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Normalizer::isNormalized -- normalizer_is_normalized — Checks if the provided string is already in the specified normalization form.

Opis

Styl obiektowy

static bool Normalizer::isNormalized ( string $input [, string $form = Normalizer::FORM_C ] )

Styl proceduralny

bool normalizer_is_normalized ( string $input [, string $form = Normalizer::FORM_C ] )

Checks if the provided string is already in the specified normalization form.

Parametry

input

The input string to normalize

form

One of the normalization forms.

Zwracane wartości

TRUE if normalized, FALSE otherwise or if there an error

Przykłady

Przykład #1 normalizer_is_normalized() example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_orig = 'A' . $char_combining_ring_above;
$char_norm = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo ( normalizer_is_normalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( normalizer_is_normalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>

Przykład #2 OO example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_orig = 'A' . $char_combining_ring_above;
$char_norm = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo ( Normalizer::isNormalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( Normalizer::isNormalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>

Powyższy przykład wyświetli:

not normalized; normalized

Zobacz też:

  • normalizer_normalize() - Normalizes the input provided and returns the normalized string

Normalizer
Normalizer::normalize
Normalizer


Normalizes the input provided and returns the normalized string

Normalizer::isNormalized
MessageFormatter
Normalizer
PHP Manual

Normalizer::normalize

normalizer_normalize

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Normalizer::normalize -- normalizer_normalize — Normalizes the input provided and returns the normalized string

Opis

Styl obiektowy

static string Normalizer::normalize ( string $input [, string $form = Normalizer::FORM_C ] )

Styl proceduralny

string normalizer_normalize ( string $input [, string $form = Normalizer::FORM_C ] )

Normalizes the input provided and returns the normalized string

Parametry

input

The input string to normalize

form

One of the normalization forms.

Zwracane wartości

The normalized string or NULL if an error occurred.

Przykłady

Przykład #1 normalizer_normalize() example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_1 = normalizer_normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>

Przykład #2 OO example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A";  // 'COMBINING RING ABOVE' (U+030A)

$char_1 = Normalizer::normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>

Powyższy przykład wyświetli:

%C3%85 %C3%85

Zobacz też:

  • normalizer_is_normalized() - Checks if the provided string is already in the specified normalization form.

Normalizer::isNormalized
MessageFormatter
Normalizer


The MessageFormatter class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Wstęp

MessageFormatter is a concrete class that enables users to produce concatenated, language-neutral messages. The methods supplied in this class are used to build all the messages that are seen by end users.

The MessageFormatter class assembles messages from various fragments (such as text fragments, numbers, and dates) supplied by the program. Because of the MessageFormatter class, the program does not need to know the order of the fragments. The class uses the formatting specifications for the fragments to assemble them into a message that is contained in a single string within a resource bundle. For example, MessageFormatter enables you to print the phrase "Finished printing x out of y files..." in a manner that still allows for flexibility in translation.

Previously, an end user message was created as a sentence and handled as a string. This procedure created problems for localizers because the sentence structure, word order, number format and so on are very different from language to language. The language-neutral way to create messages keeps each part of the message separate and provides keys to the data. Using these keys, the MessageFormatter class can concatenate the parts of the message, localize them, and display a well-formed string to the end user.

MessageFormatter takes a set of objects, formats them, and then inserts the formatted strings into the pattern at the appropriate places. Choice formats can be used in conjunction with MessageFormatter to handle plurals, match numbers, and select from an array of items. Typically, the message format will come from resources and the arguments will be dynamically set at runtime.

Krótki opis klasy

MessageFormatter {
/* Metody */
__construct ( string $locale , string $pattern )
MessageFormatter create ( string $locale , string $pattern )
static string formatMessage ( string $locale , string $pattern , array $args )
string format ( array $args )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ( void )
string getPattern ( void )
static array parseMessage ( string $locale , string $pattern , string $source )
array parse ( string $value )
bool setPattern ( string $pattern )
}

Zobacz też:

  • » ICU formatting documentation
  • » ICU message formatting description
  • » ICU message formatters
  • » ICU choice formatters

Spis treści

  • MessageFormatter::create — Constructs a new Message Formatter
  • MessageFormatter::formatMessage — Quick format message
  • MessageFormatter::format — Format the message
  • MessageFormatter::getErrorCode — Get the error code from last operation
  • MessageFormatter::getErrorMessage — Get the error text from the last operation
  • MessageFormatter::getLocale — Get the locale for which the formatter was created.
  • MessageFormatter::getPattern — Get the pattern used by the formatter
  • MessageFormatter::parseMessage — Quick parse input string
  • MessageFormatter::parse — Parse input string according to pattern
  • MessageFormatter::setPattern — Set the pattern used by the formatter
Normalizer::normalize
MessageFormatter::create
intl


Constructs a new Message Formatter

MessageFormatter
MessageFormatter::formatMessage
MessageFormatter
PHP Manual

MessageFormatter::create

MessageFormatter::__construct

msgfmt_create

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::create -- MessageFormatter::__construct -- msgfmt_create — Constructs a new Message Formatter

Opis

Styl obiektowy (method)

MessageFormatter MessageFormatter::create ( string $locale , string $pattern )

Styl obiektowy (constructor):

MessageFormatter::__construct() ( string $locale , string $pattern )

Styl proceduralny

MessageFormatter msgfmt_create ( string $locale , string $pattern )

Constructs a new Message Formatter

Parametry

locale

The locale to use when formatting arguments

pattern

The pattern string to stick arguments into. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

Zwracane wartości

The formatter object

Przykłady

Przykład #1 msgfmt_create() example

<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>

Przykład #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>

Powyższy przykład wyświetli:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

Zobacz też:

  • msgfmt_format() - Format the message
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

MessageFormatter
MessageFormatter::formatMessage
MessageFormatter


Quick format message

MessageFormatter::create
MessageFormatter::format
MessageFormatter
PHP Manual

MessageFormatter::formatMessage

msgfmt_format_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::formatMessage -- msgfmt_format_message — Quick format message

Opis

Styl obiektowy

static string MessageFormatter::formatMessage ( string $locale , string $pattern , array $args )

Styl proceduralny

string msgfmt_format_message ( string $locale , string $pattern , array $args )

Quick formatting function that formats the string without having to explicitly create the formatter object. Use this function when the format operation is done only once and does not need and parameters or state to be kept.

Parametry

locale

The locale to use for formatting locale-dependent parts

pattern

The pattern string to insert things into. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

args

The array of values to insert into the format string

Zwracane wartości

The formatted pattern string or FALSE if an error occurred

Przykłady

Przykład #1 msgfmt_format_message() example

<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", array(4560, 123, 4560/123));
echo msgfmt_format_message("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum", array(4560, 123, 4560/123));
?>

Przykład #2 OO example

<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", array(4560, 123, 4560/123));
echo msgfmt_format_message("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum", array(4560, 123, 4560/123));
?>

Powyższy przykład wyświetli:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

Zobacz też:

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

MessageFormatter::create
MessageFormatter::format
MessageFormatter


Format the message

MessageFormatter::formatMessage
MessageFormatter::getErrorCode
MessageFormatter
PHP Manual

MessageFormatter::format

msgfmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::format -- msgfmt_format — Format the message

Opis

Styl obiektowy

string MessageFormatter::format ( array $args )

Styl proceduralny

string msgfmt_format ( MessageFormatter $fmt , array $args )

Format the message by substituting the data into the format string according to the locale rules

Parametry

fmt

The message formatter

args

Arguments to insert into the format string

Zwracane wartości

The formatted string, or FALSE if an error occurred

Przykłady

Przykład #1 msgfmt_format() example

<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>

Przykład #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>

Powyższy przykład wyświetli:

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum

Zobacz też:

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_format_message() - Quick format message
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

MessageFormatter::formatMessage
MessageFormatter::getErrorCode
MessageFormatter


Get the error code from last operation

MessageFormatter::format
MessageFormatter::getErrorMessage
MessageFormatter
PHP Manual

MessageFormatter::getErrorCode

msgfmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getErrorCode -- msgfmt_get_error_code — Get the error code from last operation

Opis

Styl obiektowy

int MessageFormatter::getErrorCode ( void )

Styl proceduralny

int msgfmt_get_error_code ( MessageFormatter $fmt )

Get the error code from last operation.

Parametry

fmt

The message formatter

Zwracane wartości

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

Przykłady

Przykład #1 msgfmt_get_error_code() example

<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
    echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>

Przykład #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

Powyższy przykład wyświetli:

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

Zobacz też:

  • msgfmt_get_error_message() - Get the error text from the last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

MessageFormatter::format
MessageFormatter::getErrorMessage
MessageFormatter


Get the error text from the last operation

MessageFormatter::getErrorCode
MessageFormatter::getLocale
MessageFormatter
PHP Manual

MessageFormatter::getErrorMessage

msgfmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getErrorMessage -- msgfmt_get_error_message — Get the error text from the last operation

Opis

Styl obiektowy

string MessageFormatter::getErrorMessage ( void )

Styl proceduralny

string msgfmt_get_error_message ( MessageFormatter $fmt )

Get the error text from the last operation.

Parametry

fmt

The message formatter

Zwracane wartości

Description of the last error.

Przykłady

Przykład #1 msgfmt_get_error_message() example

<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
    echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>

Przykład #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

Powyższy przykład wyświetli:

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

Zobacz też:

  • msgfmt_get_error_code() - Get the error code from last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

MessageFormatter::getErrorCode
MessageFormatter::getLocale
MessageFormatter


Get the locale for which the formatter was created.

MessageFormatter::getErrorMessage
MessageFormatter::getPattern
MessageFormatter
PHP Manual

MessageFormatter::getLocale

msgfmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getLocale -- msgfmt_get_locale — Get the locale for which the formatter was created.

Opis

Styl obiektowy

string MessageFormatter::getLocale ( void )

Styl proceduralny

string msgfmt_get_locale ( NumberFormatter $formatter )

Get the locale for which the formatter was created.

Parametry

formatter

The formatter resource

Zwracane wartości

The locale name

Przykłady

Przykład #1 msgfmt_get_locale() example

<?php
$fmt = msgfmt_create('en_US', "Number {0,number}");
echo msgfmt_get_locale($fmt);
?>

Przykład #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "Number {0,number}");
echo $fmt->getLocale();
?>

Powyższy przykład wyświetli:

en_US

Zobacz też:

  • msgfmt_create() - Constructs a new Message Formatter

MessageFormatter::getErrorMessage
MessageFormatter::getPattern
MessageFormatter


Get the pattern used by the formatter

MessageFormatter::getLocale
MessageFormatter::parseMessage
MessageFormatter
PHP Manual

MessageFormatter::getPattern

msgfmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::getPattern -- msgfmt_get_pattern — Get the pattern used by the formatter

Opis

Styl obiektowy

string MessageFormatter::getPattern ( void )

Styl proceduralny

string msgfmt_get_pattern ( MessageFormatter $fmt )

Get the pattern used by the formatter

Parametry

fmt

The message formatter

Zwracane wartości

The pattern string for this message formatter

Przykłady

Przykład #1 msgfmt_get_pattern() example

<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";

msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>

Przykład #2 OO example

<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";

$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>

Powyższy przykład wyświetli:

Default pattern: '{0,number} monkeys on {1,number} trees'
Formatting result: 123 monkeys on 456 trees
New pattern: '{0,number} trees hosting {1,number} monkeys'
Formatted number: 123 trees hosting 456 monkeys

Zobacz też:

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_set_pattern() - Set the pattern used by the formatter

MessageFormatter::getLocale
MessageFormatter::parseMessage
MessageFormatter


Quick parse input string

MessageFormatter::getPattern
MessageFormatter::parse
MessageFormatter
PHP Manual

MessageFormatter::parseMessage

msgfmt_parse_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::parseMessage -- msgfmt_parse_message — Quick parse input string

Opis

Styl obiektowy

static array MessageFormatter::parseMessage ( string $locale , string $pattern , string $source )

Styl proceduralny

array msgfmt_parse_message ( string $locale , string $pattern , string $value )

Parses input string without explicitly creating the formatter object. Use this function when the format operation is done only once and does not need and parameters or state to be kept.

Parametry

locale

The locale to use for parsing locale-dependent parts

pattern

The pattern with which to parse the value.

source

The string to parse, conforming to the pattern.

Zwracane wartości

An array containing items extracted, or FALSE on error

Przykłady

Przykład #1 msgfmt_parse_message() example

<?php
$fmt = msgfmt_parse_message('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
                            "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);

$fmt = msgfmt_parse_message('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",
                            "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($fmt);
?>

Przykład #2 OO example

<?php
$fmt = MessageFormatter::parseMessage('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
                            "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);

$fmt = MessageFormatter::parseMessage('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",
                            "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($fmt);
?>

Powyższy przykład wyświetli:

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

Zobacz też:

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_format_message() - Quick format message
  • msgfmt_parse() - Parse input string according to pattern

MessageFormatter::getPattern
MessageFormatter::parse
MessageFormatter


Parse input string according to pattern

MessageFormatter::parseMessage
MessageFormatter::setPattern
MessageFormatter
PHP Manual

MessageFormatter::parse

msgfmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::parse -- msgfmt_parse — Parse input string according to pattern

Opis

Styl obiektowy

array MessageFormatter::parse ( string $value )

Styl proceduralny

array msgfmt_parse ( MessageFormatter $fmt , string $value )

Parses input string and return any extracted items as an array.

Parametry

fmt

The message formatter

value

The string to parse

Zwracane wartości

An array containing the items extracted, or FALSE on error

Przykłady

Przykład #1 msgfmt_parse() example

<?php
$fmt = msgfmt_create('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = msgfmt_parse($fmt, "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);

$fmt = msgfmt_create('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
$res = msgfmt_parse($fmt, "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($res);
?>

Przykład #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = $fmt->parse("4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);

$fmt = new MessageFormatter('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum");
$res = $fmt->parse("4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum");
var_export($res);
?>

Powyższy przykład wyświetli:

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

Zobacz też:

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_format() - Format the message
  • msgfmt_parse_message() - Quick parse input string

MessageFormatter::parseMessage
MessageFormatter::setPattern
MessageFormatter


Set the pattern used by the formatter

MessageFormatter::parse
IntlDateFormatter
MessageFormatter
PHP Manual

MessageFormatter::setPattern

msgfmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

MessageFormatter::setPattern -- msgfmt_set_pattern — Set the pattern used by the formatter

Opis

Styl obiektowy

bool MessageFormatter::setPattern ( string $pattern )

Styl proceduralny

bool msgfmt_set_pattern ( MessageFormatter $fmt , string $pattern )

Set the pattern used by the formatter

Parametry

fmt

The message formatter

pattern

The pattern string to use in this message formatter. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 msgfmt_set_pattern() example

<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";

msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>

Przykład #2 OO example

<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";

$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>

Powyższy przykład wyświetli:

Default pattern: '{0,number} monkeys on {1,number} trees'
Formatting result: 123 monkeys on 456 trees
New pattern: '{0,number} trees hosting {1,number} monkeys'
Formatted number: 123 trees hosting 456 monkeys

Zobacz też:

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_get_pattern() - Get the pattern used by the formatter

MessageFormatter::parse
IntlDateFormatter
MessageFormatter


The IntlDateFormatter class

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

Wstęp

Date Formatter is a concrete class that enables locale-dependent formatting/parsing of dates using pattern strings and/or canned patterns.

This class represents the ICU date formatting functionality. It allows users to display dates in a localized format or to parse strings into PHP date values using pattern strings and/or canned patterns.

Class synopsis

IntlDateFormatter {
/* Metody */
__construct ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )
static IntlDateFormatter create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )
string format ( mixed $value )
int getCalendar ( void )
int getDateType ( void )
int getErrorCode ( void )
string getErrorMessage ( void )
string getLocale ([ int $which ] )
string getPattern ( void )
int getTimeType ( void )
string getTimeZoneId ( void )
bool isLenient ( void )
array localtime ( string $value [, int &$position ] )
int parse ( string $value [, int &$position ] )
bool setCalendar ( int $which )
bool setLenient ( bool $lenient )
bool setPattern ( string $pattern )
bool setTimeZoneId ( string $zone )
}

Zobacz też:

  • » ICU Date formatter
  • » ICU Date formats

Stałe predefiniowane

These constants are used to specify different formats in the constructor for DateType and TimeType.

IntlDateFormatter::NONE (integer)
Do not include this element
IntlDateFormatter::FULL (integer)
Completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST)
IntlDateFormatter::LONG (integer)
Long style (January 12, 1952 or 3:30:32pm)
IntlDateFormatter::MEDIUM (integer)
Medium style (Jan 12, 1952)
IntlDateFormatter::SHORT (integer)
Most abbreviated style, only essential data (12/13/52 or 3:30pm)

The following int constants are used to specify the calendar. These calendars are all based directly on the Gregorian calendar. Non-Gregorian calendars need to be specified in locale. Examples might include locale="hi@calendar=BUDDHIST".

IntlDateFormatter::TRADITIONAL (integer)
Non-Gregorian Calendar
IntlDateFormatter::GREGORIAN (integer)
Gregorian Calendar

Spis treści

  • IntlDateFormatter::create — Create a date formatter
  • IntlDateFormatter::format — Format the date/time value as a string
  • IntlDateFormatter::getCalendar — Get the calendar used for the IntlDateFormatter
  • IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
  • IntlDateFormatter::getErrorCode — Get the error code from last operation
  • IntlDateFormatter::getErrorMessage — Get the error text from the last operation.
  • IntlDateFormatter::getLocale — Get the locale used by formatter
  • IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
  • IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
  • IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
  • IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
  • IntlDateFormatter::localtime — Parse string to a field-based time value
  • IntlDateFormatter::parse — Parse string to a timestamp value
  • IntlDateFormatter::setCalendar — sets the calendar used to the appropriate calendar, which must be
  • IntlDateFormatter::setLenient — Set the leniency of the parser
  • IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
  • IntlDateFormatter::setTimeZoneId — Sets the time zone to use
MessageFormatter::setPattern
IntlDateFormatter::create
intl


Create a date formatter

IntlDateFormatter
IntlDateFormatter::format
IntlDateFormatter
PHP Manual

IntlDateFormatter::create

datefmt_create

IntlDateFormatter::__construct

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::create -- datefmt_create -- IntlDateFormatter::__construct — Create a date formatter

Opis

Styl obiektowy

static IntlDateFormatter IntlDateFormatter::create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Styl obiektowy (constructor)

IntlDateFormatter::__construct() ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Styl proceduralny

IntlDateFormatter datefmt_create ( string $locale , int $datetype , int $timetype [, string $timezone [, int $calendar [, string $pattern ]]] )

Create a date formatter

Parametry

locale

Locale to use when formatting or parsing.

datetype

Date type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants.

timetype

Time type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants.

timezone

Time zone ID, default is system default.

calendar

Calendar to use for formatting or parsing; default is Gregorian. This is one of the IntlDateFormatter calendar constants.

pattern

Optional pattern to use when formatting or parsing. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Zwracane wartości

Przykłady

Przykład #1 datefmt_create() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles', IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);
?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".$fmt->format(0);

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
     'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
      'America/Los_Angeles',IntlDateFormatter::GREGORIAN , "MM/dd/yyyy");
echo "Second Formatted output with pattern is ".$fmt->format(0);
?>

Powyższy przykład wyświetli:

First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
First Formatted output with pattern is 12/31/1969
Second Formatted output with pattern is 12/31/1969

Zobacz też:

  • datefmt_format() - Format the date/time value as a string
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

IntlDateFormatter
IntlDateFormatter::format
IntlDateFormatter


Format the date/time value as a string

IntlDateFormatter::create
IntlDateFormatter::getCalendar
IntlDateFormatter
PHP Manual

IntlDateFormatter::format

datefmt_format

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::format -- datefmt_format — Format the date/time value as a string

Opis

Styl obiektowy

string IntlDateFormatter::format ( mixed $value )

Styl proceduralny

string datefmt_format ( IntlDateFormatter $fmt , mixed $value )

Formats the time value as a string.

Parametry

fmt

The date formatter resource.

value

Value to format. This may be a DateTime object, an integer representing a Unix timestamp value (seconds since epoch, UTC) or an array in the format output by localtime().

Zwracane wartości

The formatted string or, if an error occurred, FALSE.

Rejestr zmian

Wersja | Opis
5.3.4 | Support for providing DateTime objects to the value parameter was added.

Przykłady

Przykład #1 datefmt_format() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);
?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second Formatted output is ".$fmt->format(0);

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN , "MM/dd/yyyy");
echo "Second Formatted output with pattern is ".$fmt->format(0);
?>

Powyższy przykład wyświetli:

First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
First Formatted output with pattern is 12/31/1969
Second Formatted output with pattern is 12/31/1969

Zobacz też:

  • datefmt_create() - Create a date formatter
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

IntlDateFormatter::create
IntlDateFormatter::getCalendar
IntlDateFormatter


Get the calendar used for the IntlDateFormatter

IntlDateFormatter::format
IntlDateFormatter::getDateType
IntlDateFormatter
PHP Manual

IntlDateFormatter::getCalendar

datefmt_get_calendar

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getCalendar -- datefmt_get_calendar — Get the calendar used for the IntlDateFormatter

Opis

Styl obiektowy

int IntlDateFormatter::getCalendar ( void )

Styl proceduralny

int datefmt_get_calendar ( IntlDateFormatter $fmt )

Parametry

fmt

The formatter resource

Zwracane wartości

The calendar being used by the formatter.

Przykłady

Przykład #1 datefmt_get_calendar() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "calendar of the formatter is : ".datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt,IntlDateFormatter::TRADITIONAL);
echo "Now calendar of the formatter is : ".datefmt_get_calendar($fmt);
?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "calendar of the formatter is : ".$fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo "Now calendar of the formatter is : ".$fmt->getCalendar();

?>

Powyższy przykład wyświetli:

calendar of the formatter is : 1
Now calendar of the formatter is : 0

Zobacz też:

  • datefmt_set_calendar() - sets the calendar used to the appropriate calendar, which must be
  • datefmt_create() - Create a date formatter

IntlDateFormatter::format
IntlDateFormatter::getDateType
IntlDateFormatter


Get the datetype used for the IntlDateFormatter

IntlDateFormatter::getCalendar
IntlDateFormatter::getErrorCode
IntlDateFormatter
PHP Manual

IntlDateFormatter::getDateType

datefmt_get_datetype

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getDateType -- datefmt_get_datetype — Get the datetype used for the IntlDateFormatter

Opis

Styl obiektowy

int IntlDateFormatter::getDateType ( void )

Styl proceduralny

int datefmt_get_datetype ( IntlDateFormatter $fmt )

Returns date type used by the formatter.

Parametry

fmt

The formatter resource.

Zwracane wartości

The current date type value of the formatter.

Przykłady

Przykład #1 datefmt_get_datetype() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "datetype of the formatter is : ".datefmt_get_datetype($fmt);
echo "First Formatted output with datetype is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::SHORT,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Now datetype of the formatter is : ".datefmt_get_datetype($fmt);
echo "Second Formatted output with datetype is ".datefmt_format( $fmt , 0);

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN);
echo "datetype of the formatter is : ".$fmt->getDateType();
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::SHORT,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN);
echo "Now datetype of the formatter is : ".$fmt->getDateType();
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

?>

Powyższy przykład wyświetli:

datetype of the formatter is : 0
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Now datetype of the formatter is : 2
Second Formatted output is 12/31/69 4:00:00 PM PT

Zobacz też:

  • datefmt_get_timetype() - Get the timetype used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getCalendar
IntlDateFormatter::getErrorCode
IntlDateFormatter


Get the error code from last operation

IntlDateFormatter::getDateType
IntlDateFormatter::getErrorMessage
IntlDateFormatter
PHP Manual

IntlDateFormatter::getErrorCode

datefmt_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorCode -- datefmt_get_error_code — Get the error code from last operation

Opis

Styl obiektowy

int IntlDateFormatter::getErrorCode ( void )

Styl proceduralny

int datefmt_get_error_code ( IntlDateFormatter $fmt )

Get the error code from last operation. Returns error code from the last number formatting operation.

Parametry

fmt

The formatter resource.

Zwracane wartości

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

Przykłady

Przykład #1 datefmt_get_error_code() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = datefmt_format($fmt);
if(!$str) {
    echo "ERROR: ".datefmt_get_error_message($fmt) . " (" . datefmt_get_error_code($fmt) . ")\n";
}
?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = $fmt->format();
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

Powyższy przykład wyświetli:

ERROR: U_ZERO_ERROR (0)

Zobacz też:

  • datefmt_get_error_message() - Get the error text from the last operation.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

IntlDateFormatter::getDateType
IntlDateFormatter::getErrorMessage
IntlDateFormatter


Get the error text from the last operation.

IntlDateFormatter::getErrorCode
IntlDateFormatter::getLocale
IntlDateFormatter
PHP Manual

IntlDateFormatter::getErrorMessage

datefmt_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorMessage -- datefmt_get_error_message — Get the error text from the last operation.

Opis

Styl obiektowy

string IntlDateFormatter::getErrorMessage ( void )

Styl proceduralny

string datefmt_get_error_message ( IntlDateFormatter $fmt )

Get the error text from the last operation.

Parametry

fmt

The formatter resource.

Zwracane wartości

Description of the last error.

Przykłady

Przykład #1 datefmt_get_error_message() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = datefmt_format($fmt);
if(!$str) {
    echo "ERROR: ".datefmt_get_error_message($fmt) . " (" . datefmt_get_error_code($fmt) . ")\n";
}
?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$str = $fmt->format();
if(!$str) {
    echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}

?>

Powyższy przykład wyświetli:

ERROR: U_ZERO_ERROR (0)

Zobacz też:

  • datefmt_get_error_code() - Get the error code from last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

IntlDateFormatter::getErrorCode
IntlDateFormatter::getLocale
IntlDateFormatter


Get the locale used by formatter

IntlDateFormatter::getErrorMessage
IntlDateFormatter::getPattern
IntlDateFormatter
PHP Manual

IntlDateFormatter::getLocale

datefmt_get_locale

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getLocale -- datefmt_get_locale — Get the locale used by formatter

Opis

Styl obiektowy

string IntlDateFormatter::getLocale ([ int $which ] )

Styl proceduralny

string datefmt_get_locale ( IntlDateFormatter $fmt [, int $which ] )

Get locale used by the formatter.

Parametry

fmt

The formatter resource

hich

You can choose between valid and actual locale ( Locale::VALID_LOCALE, Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

Zwracane wartości

the locale of this formatter or 'false' if error

Przykłady

Przykład #1 datefmt_get_locale() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "locale of the formatter is : ".datefmt_get_locale($fmt);
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "locale of the formatter is : ".datefmt_get_locale($fmt);
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "locale of the formatter is : ".$fmt->getLocale();
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "locale of the formatter is : ".$fmt->getLocale();
echo "Second Formatted output is ".$fmt->format(0);

?>

Powyższy przykład wyświetli:

locale of the formatter is : en
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
locale of the formatter is : de
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00

Zobacz też:

  • datefmt_create() - Create a date formatter

IntlDateFormatter::getErrorMessage
IntlDateFormatter::getPattern
IntlDateFormatter


Get the pattern used for the IntlDateFormatter

IntlDateFormatter::getLocale
IntlDateFormatter::getTimeType
IntlDateFormatter
PHP Manual

IntlDateFormatter::getPattern

datefmt_get_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getPattern -- datefmt_get_pattern — Get the pattern used for the IntlDateFormatter

Opis

Styl obiektowy

string IntlDateFormatter::getPattern ( void )

Styl proceduralny

string datefmt_get_pattern ( IntlDateFormatter $fmt )

Get pattern used by the formatter.

Parametry

fmt

The formatter resource.

Zwracane wartości

The pattern string being used to format/parse.

Przykłady

Przykład #1 datefmt_get_pattern() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "pattern of the formatter is : ".datefmt_get_pattern($fmt);
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
datefmt_set_pattern($fmt,'yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".datefmt_get_pattern($fmt);
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN,"MM/dd/yyyy"  );
echo "pattern of the formatter is : ".$fmt->getPattern();
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".$fmt->getPattern();
echo "Second Formatted output is ".datefmt_format( $fmt , 0);
?>

Powyższy przykład wyświetli:

pattern of the formatter is : MM/dd/yyyy
First Formatted output is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output is 19690031 04:00:00 PST

Zobacz też:

  • datefmt_set_pattern() - Set the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getLocale
IntlDateFormatter::getTimeType
IntlDateFormatter


Get the timetype used for the IntlDateFormatter

IntlDateFormatter::getPattern
IntlDateFormatter::getTimeZoneId
IntlDateFormatter
PHP Manual

IntlDateFormatter::getTimeType

datefmt_get_timetype

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeType -- datefmt_get_timetype — Get the timetype used for the IntlDateFormatter

Opis

Styl obiektowy

int IntlDateFormatter::getTimeType ( void )

Styl proceduralny

int datefmt_get_timetype ( IntlDateFormatter $fmt )

Return time type used by the formatter.

Parametry

fmt

The formatter resource.

Zwracane wartości

The current date type value of the formatter.

Przykłady

Przykład #1 datefmt_get_timetype() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timetype of the formatter is : ".datefmt_get_timetype($fmt);
echo "First Formatted output with timetype is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::SHORT,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Now timetype of the formatter is : ".datefmt_get_timetype($fmt);
echo "Second Formatted output with timetype is ".datefmt_format( $fmt , 0);

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN);
echo "timetype of the formatter is : ".$fmt->getTimeType();
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::SHORT,'America/Los_Angeles',IntlDateFormatter::GREGORIAN);
echo "Now timetype of the formatter is : ".$fmt->getTimeType();
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

?>

Powyższy przykład wyświetli:

timetype of the formatter is : 0
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Now timetype of the formatter is : 3
Second Formatted output is Wednesday, December 31, 1969 4:00 PM

Zobacz też:

  • datefmt_get_datetype() - Get the datetype used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getPattern
IntlDateFormatter::getTimeZoneId
IntlDateFormatter


Get the timezone-id used for the IntlDateFormatter

IntlDateFormatter::getTimeType
IntlDateFormatter::isLenient
IntlDateFormatter
PHP Manual

IntlDateFormatter::getTimeZoneId

datefmt_get_timezone_id

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeZoneId -- datefmt_get_timezone_id — Get the timezone-id used for the IntlDateFormatter

Opis

Styl obiektowy

string IntlDateFormatter::getTimeZoneId ( void )

Styl proceduralny

string datefmt_get_timezone_id ( IntlDateFormatter $fmt )

Get the timezone-id used for the IntlDateFormatter.

Parametry

fmt

The formatter resource.

Zwracane wartości

ID string for the time zone used by this formatter.

Przykłady

Przykład #1 datefmt_get_timezone_id() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timezone_id of the formatter is : ".datefmt_get_timezone_id($fmt);
datefmt_set_timezone_id($fmt,'CN');
echo "Now timezone_id of the formatter is : ".datefmt_get_timezone_id($fmt);

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timezone_id of the formatter is : ".$fmt->getTimezoneId();
$fmt->setTimezoneId('CN');
echo "Now timezone_id of the formatter is : ".$fmt->getTimezoneId();

?>

Powyższy przykład wyświetli:

timezone_id of the formatter is : America/Los_Angeles
Now timezone_id of the formatter is : CN

Zobacz też:

  • datefmt_set_timezone_id() - Sets the time zone to use
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getTimeType
IntlDateFormatter::isLenient
IntlDateFormatter


Get the lenient used for the IntlDateFormatter

IntlDateFormatter::getTimeZoneId
IntlDateFormatter::localtime
IntlDateFormatter
PHP Manual

IntlDateFormatter::isLenient

datefmt_is_lenient

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::isLenient -- datefmt_is_lenient — Get the lenient used for the IntlDateFormatter

Opis

Styl obiektowy

bool IntlDateFormatter::isLenient ( void )

Styl proceduralny

bool datefmt_is_lenient ( IntlDateFormatter $fmt )

Check if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly.

Parametry

fmt

The formatter resource.

Zwracane wartości

TRUE if parser is lenient, FALSE if parser is strict. By default the parser is strict.

Przykłady

Przykład #1 datefmt_is_lenient() example

<?php
$fmt = datefmt_create( "en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, "dd/mm/yyyy");
echo "lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
datefmt_parse($fmt,"35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}
datefmt_set_lenient($fmt,false);
echo "Now lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
datefmt_parse($fmt,"35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter("en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, "dd/mm/yyyy"  );
echo "lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
$fmt->parse("35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo "Now lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
$fmt->parse("35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

?>

Powyższy przykład wyświetli:

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : -2147483
Now lenient of the formatter is : FALSE
Trying to do parse('35/13/1971').
Result is : Error_msg is : Date parsing failed: U_PARSE_ERROR Error_code is : 9

Zobacz też:

  • datefmt_set_lenient() - Set the leniency of the parser
  • datefmt_create() - Create a date formatter

IntlDateFormatter::getTimeZoneId
IntlDateFormatter::localtime
IntlDateFormatter


Parse string to a field-based time value

IntlDateFormatter::isLenient
IntlDateFormatter::parse
IntlDateFormatter
PHP Manual

IntlDateFormatter::localtime

datefmt_localtime

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::localtime -- datefmt_localtime — Parse string to a field-based time value

Opis

Styl obiektowy

array IntlDateFormatter::localtime ( string $value [, int &$position ] )

Styl proceduralny

array datefmt_localtime ( IntlDateFormatter $fmt , string $value [, int &$position ] )

Converts string $value to a field-based time value ( an array of various fields), starting at $parse_pos and consuming as much of the input value as possible.

Parametry

fmt

The formatter resource

value

string to convert to a time

position

Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse_pos will contain -1 otherwise it will contain the position at which parsing ended . If $parse_pos > strlen($value), the parse fails immediately.

Zwracane wartości

Localtime compatible array of integers : contains 24 hour clock value in tm_hour field

Przykłady

Przykład #1 datefmt_localtime() example

<?php

$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$arr = datefmt_localtime( $fmt, "Wednesday, December 31, 1969 4:00:00 PM PT",0);
echo "First parsed output is ";
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$arr = $fmt->localtime( "Wednesday, December 31, 1969 4:00:00 PM PT",0);
echo "First parsed output is ";
if ($arr) {
    foreach ($arr as $key => $value) {
        echo "$key : $value , ";
    }
}

?>

Powyższy przykład wyświetli:

First parsed output is tm_sec : 0 , tm_min : 0 , tm_hour : 16 , tm_year : 1969 ,
tm_mday : 31 , tm_wday : 4 , tm_yday : 365 , tm_mon : 11 , tm_isdst : 0 ,

Zobacz też:

  • datefmt_create() - Create a date formatter
  • datefmt_format() - Format the date/time value as a string
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

IntlDateFormatter::isLenient
IntlDateFormatter::parse
IntlDateFormatter


Parse string to a timestamp value

IntlDateFormatter::localtime
IntlDateFormatter::setCalendar
IntlDateFormatter
PHP Manual

IntlDateFormatter::parse

datefmt_parse

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::parse -- datefmt_parse — Parse string to a timestamp value

Opis

Styl obiektowy

int IntlDateFormatter::parse ( string $value [, int &$position ] )

Styl proceduralny

int datefmt_parse ( IntlDateFormatter $fmt , string $value [, int &$position ] )

Converts string $value to an incremental time value, starting at $parse_pos and consuming as much of the input value as possible.

Parametry

fmt

The formatter resource

value

string to convert to a time

position

Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse_pos will contain -1 otherwise it will contain the position at which parsing ended (and the error occurred). This variable will contain the end position if the parse fails. If $parse_pos > strlen($value), the parse fails immediately.

Zwracane wartości

timestamp parsed value

Przykłady

Przykład #1 datefmt_parse() example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First parsed output is ".$fmt->parse("Wednesday, December 20, 1989 4:00:00 PM PT");
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second parsed output is ".$fmt->parse("Mittwoch, 20. Dezember 1989 16:00 Uhr GMT-08:00");
?>

Przykład #2 OO example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "First parsed output is ".datefmt_parse( $fmt ,  "Wednesday, December 20, 1989 4:00:00 PM PT");
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "Second parsed output is ".datefmt_parse( $fmt , "Mittwoch, 20. Dezember 1989 16:00 Uhr GMT-08:00");
?>

Powyższy przykład wyświetli:

First parsed output is 630201600
Second parsed output is 630201600

Zobacz też:

  • datefmt_create() - Create a date formatter
  • datefmt_format() - Format the date/time value as a string
  • datefmt_localtime() - Parse string to a field-based time value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation.

IntlDateFormatter::localtime
IntlDateFormatter::setCalendar
IntlDateFormatter


sets the calendar used to the appropriate calendar, which must be

IntlDateFormatter::parse
IntlDateFormatter::setLenient
IntlDateFormatter
PHP Manual

IntlDateFormatter::setCalendar

datefmt_set_calendar

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setCalendar -- datefmt_set_calendar — sets the calendar used to the appropriate calendar, which must be

Opis

Styl obiektowy

bool IntlDateFormatter::setCalendar ( int $which )

Styl proceduralny

bool datefmt_set_calendar ( IntlDateFormatter $fmt , int $which )

Sets the calendar used by the formatter.

Parametry

fmt

The formatter resource.

which

The calendar to use. Default is IntlDateFormatter::GREGORIAN.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 datefmt_set_calendar() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "calendar of the formatter is : ".datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt,IntlDateFormatter::TRADITIONAL);
echo "Now calendar of the formatter is : ".datefmt_get_calendar($fmt);
?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "calendar of the formatter is : ".$fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo "Now calendar of the formatter is : ".$fmt->getCalendar();
?>

Powyższy przykład wyświetli:

calendar of the formatter is : 1
Now calendar of the formatter is : 0

Zobacz też:

  • datefmt_get_calendar() - Get the calendar used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::parse
IntlDateFormatter::setLenient
IntlDateFormatter


Set the leniency of the parser

IntlDateFormatter::setCalendar
IntlDateFormatter::setPattern
IntlDateFormatter
PHP Manual

IntlDateFormatter::setLenient

datefmt_set_lenient

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setLenient -- datefmt_set_lenient — Set the leniency of the parser

Opis

Styl obiektowy

bool IntlDateFormatter::setLenient ( bool $lenient )

Styl proceduralny

bool datefmt_set_lenient ( IntlDateFormatter $fmt , bool $lenient )

Define if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly. Enabling lenient parsing allows the parser to accept otherwise flawed date or time patterns, parsing as much as possible to obtain a value. Extra space, unrecognized tokens, or invalid values ("February 30th") are not accepted.

Parametry

fmt

The formatter resource

lenient

Sets whether the parser is lenient or not, default is FALSE (strict).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 datefmt_set_lenient() example

<?php
$fmt = datefmt_create("en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, "dd/mm/yyyy");
echo "lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
datefmt_parse($fmt,"35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}
datefmt_set_lenient($fmt,false);
echo "Now lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
datefmt_parse($fmt,"35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .datefmt_parse($fmt,"35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter("en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, "dd/mm/yyyy");
echo "lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
$fmt->parse("35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo "Now lenient of the formatter is : ";
if( $fmt->isLenient() ){
        echo('TRUE');
}else{
        echo('FALSE');
}
$fmt->parse("35/13/1971");
echo "\n Trying to do parse('35/13/1971').Result is : " .$fmt->parse("35/13/1971");
if( intl_get_error_code() !=0 ){
        echo "Error_msg is : ".intl_get_error_message();
        echo "Error_code is : ".intl_get_error_code();
}

?>

Powyższy przykład wyświetli:

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : -2147483
Now lenient of the formatter is : FALSE
Trying to do parse('35/13/1971').
Result is : Error_msg is : Date parsing failed: U_PARSE_ERROR Error_code is : 9

Zobacz też:

  • datefmt_is_lenient() - Get the lenient used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::setCalendar
IntlDateFormatter::setPattern
IntlDateFormatter


Set the pattern used for the IntlDateFormatter

IntlDateFormatter::setLenient
IntlDateFormatter::setTimeZoneId
IntlDateFormatter
PHP Manual

IntlDateFormatter::setPattern

datefmt_set_pattern

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setPattern -- datefmt_set_pattern — Set the pattern used for the IntlDateFormatter

Opis

Styl obiektowy

bool IntlDateFormatter::setPattern ( string $pattern )

Styl proceduralny

bool datefmt_set_pattern ( IntlDateFormatter $fmt , string $pattern )

Set the pattern used for the IntlDateFormatter.

Parametry

fmt

The formatter resource.

pattern

New pattern string to use. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/datetime.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Bad formatstrings are usually the cause of the failure.

Przykłady

Przykład #1 datefmt_set_pattern() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  ,"MM/dd/yyyy");
echo "pattern of the formatter is : ".datefmt_get_pattern($fmt);
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
datefmt_set_pattern($fmt,'yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".datefmt_get_pattern($fmt);
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);

?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN,"MM/dd/yyyy"  );
echo "pattern of the formatter is : ".$fmt->getPattern();
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo "Now pattern of the formatter is : ".$fmt->getPattern();
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

?>

Powyższy przykład wyświetli:

pattern of the formatter is : MM/dd/yyyy
First Formatted output with pattern is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output with pattern is 19690031 04:00:00 PST

Zobacz też:

  • datefmt_get_pattern() - Get the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::setLenient
IntlDateFormatter::setTimeZoneId
IntlDateFormatter


Sets the time zone to use

IntlDateFormatter::setPattern
ResourceBundle
IntlDateFormatter
PHP Manual

IntlDateFormatter::setTimeZoneId

datefmt_set_timezone_id

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setTimeZoneId -- datefmt_set_timezone_id — Sets the time zone to use

Opis

Styl obiektowy

bool IntlDateFormatter::setTimeZoneId ( string $zone )

Styl proceduralny

bool datefmt_set_timezone_id ( IntlDateFormatter $fmt , string $zone )

Sets the time zone to use.

Parametry

fmt

The formatter resource.

zone

The time zone ID string of the time zone to use. If NULL or the empty string, the default time zone for the runtime is used.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 datefmt_set_timezone_id() example

<?php
$fmt = datefmt_create(  "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timezone_id of the formatter is : ".datefmt_get_timezone_id($fmt);
datefmt_set_timezone_id($fmt,'CN');
echo "Now timezone_id of the formatter is : ".datefmt_get_timezone_id($fmt);
?>

Przykład #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL,IntlDateFormatter::FULL,'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
echo "timezone_id of the formatter is : ".$fmt->getTimezoneId();
$fmt->setTimezoneId('CN');
echo "Now timezone_id of the formatter is : ".$fmt->getTimezoneId();

?>

Powyższy przykład wyświetli:

timezone_id of the formatter is : America/Los_Angeles
Now timezone_id of the formatter is : CN

Zobacz też:

  • datefmt_get_timezone_id() - Get the timezone-id used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

IntlDateFormatter::setPattern
ResourceBundle
IntlDateFormatter


The ResourceBundle class

(PHP > 5.4.0)

Wstęp

Localized software products often require sets of data that are to be customized depending on current locale, e.g.: messages, labels, formatting patterns. ICU resource mechanism allows to define sets of resources that the application can load on locale basis, while accessing them in unified locale-independent fashion.

This class implements access to ICU resource data files. These files are binary data arrays which ICU uses to store the localized data.

ICU resource bundle can hold simple resources and complex resources. Complex resources are containers which can be either integer-indexed or string-indexed (just like PHP arrays). Simple resources can be of the following typos: string, integer, binary data field or integer array.

ResourceBundle supports direct access to the data through array access pattern and iteration via foreach, as well as access via class methods. The result will be PHP value for simple resources and ResourceBundle object for complex ones. All resources are read-only.

Krótki opis klasy

ResourceBundle {
/* Methods */
__construct ( string $locale , string $bundlename [, bool $fallback ] )
int count ( void )
static ResourceBundle create ( string $locale , string $bundlename [, bool $fallback ] )
int getErrorCode ( void )
string getErrorMessage ( void )
mixed get ( string|int $index )
array getLocales ( string $bundlename )
}

Zobacz też:

  • » ICU Resource Management
  • » ICU Data

Spis treści

  • ResourceBundle::count — Get number of elements in the bundle
  • ResourceBundle::create — Create a resource bundle
  • ResourceBundle::getErrorCode — Get bundle's last error code.
  • ResourceBundle::getErrorMessage — Get bundle's last error message.
  • ResourceBundle::get — Get data from the bundle
  • ResourceBundle::getLocales — Get supported locales
IntlDateFormatter::setTimeZoneId
ResourceBundle::count
intl


Get number of elements in the bundle

ResourceBundle
ResourceBundle::create
ResourceBundle
PHP Manual

ResourceBundle::count

resourcebundle_count

(PHP > 5.4.0)

ResourceBundle::count -- resourcebundle_count — Get number of elements in the bundle

Opis

Styl obiektowy

int ResourceBundle::count ( void )

Styl proceduralny

int resourcebundle_count ( ResourceBundle $r )

Get the number of elements in the bundle.

Parametry

r

ResourceBundle object.

Zwracane wartości

Returns number of elements in the bundle.

Przykłady

Przykład #1 resourcebundle_count() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_count($r);
?>

Przykład #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->count();
?>

Powyższy przykład wyświetli:

42

Zobacz też:

  • resourcebundle_get() - Get data from the bundle

ResourceBundle
ResourceBundle::create
ResourceBundle


Create a resource bundle

ResourceBundle::count
ResourceBundle::getErrorCode
ResourceBundle
PHP Manual

ResourceBundle::create

resourcebundle_create

ResourceBundle::__construct

(PHP > 5.4.0)

ResourceBundle::create -- resourcebundle_create -- ResourceBundle::__construct — Create a resource bundle

Opis

Styl obiektowy (method)

static ResourceBundle ResourceBundle::create ( string $locale , string $bundlename [, bool $fallback ] )

Styl proceduralny

ResourceBundle resourcebundle_create ( string $locale , string $bundlename [, bool $fallback ] )

Styl obiektowy (constructor):

ResourceBundle::__construct() ( string $locale , string $bundlename [, bool $fallback ] )

Creates a resource bundle.

Parametry

locale

Locale for which the resources should be loaded (locale name, e.g. en_CA).

bundlename

The directory where the data is stored or the name of the .dat file.

fallback

Whether locale should match exactly or fallback to parent locale is allowed.

Zwracane wartości

Returns ResourceBundle object or FALSE on error.

Przykłady

Przykład #1 resourcebundle_create() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

Przykład #2 ResourceBundle::create() example

<?php
$r = ResourceBundle::create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

Powyższy przykład wyświetli:

¡Hola, mundo!

Zobacz też:

  • resourcebundle_get() - Get data from the bundle

ResourceBundle::count
ResourceBundle::getErrorCode
ResourceBundle


Get bundle's last error code.

ResourceBundle::create
ResourceBundle::getErrorMessage
ResourceBundle
PHP Manual

ResourceBundle::getErrorCode

resourcebundle_get_error_code

(PHP > 5.4.0)

ResourceBundle::getErrorCode -- resourcebundle_get_error_code — Get bundle's last error code.

Opis

Styl obiektowy

int ResourceBundle::getErrorCode ( void )

Styl proceduralny

int resourcebundle_get_error_code ( ResourceBundle $r )

Get error code from the last function performed by the bundle object.

Parametry

r

ResourceBundle object.

Zwracane wartości

Returns error code from last bundle object call.

Przykłady

Przykład #1 resourcebundle_get_error_code() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
    report_error("Bundle error");
}
?>

Przykład #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
    report_error("Bundle error");
}
?>

Zobacz też:

  • resourcebundle_get_error_message() - Get bundle's last error message.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

ResourceBundle::create
ResourceBundle::getErrorMessage
ResourceBundle


Get bundle's last error message.

ResourceBundle::getErrorCode
ResourceBundle::get
ResourceBundle
PHP Manual

ResourceBundle::getErrorMessage

resourcebundle_get_error_message

(PHP > 5.4.0)

ResourceBundle::getErrorMessage -- resourcebundle_get_error_message — Get bundle's last error message.

Opis

Styl obiektowy

string ResourceBundle::getErrorMessage ( void )

Styl proceduralny

string resourcebundle_get_error_message ( ResourceBundle $r )

Get error message from the last function performed by the bundle object.

Parametry

r

ResourceBundle object.

Zwracane wartości

Returns error message from last bundle object's call.

Przykłady

Przykład #1 resourcebundle_get_error_message() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
    report_error("Bundle error: ".resourcebundle_get_error_message($r));
}
?>

Przykład #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
    report_error("Bundle error: ".ResourceBundle::getErrorMessage($r));
}
?>

Zobacz też:

  • resourcebundle_get_error_code() - Get bundle's last error code.
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

ResourceBundle::getErrorCode
ResourceBundle::get
ResourceBundle


Get data from the bundle

ResourceBundle::getErrorMessage
ResourceBundle::getLocales
ResourceBundle
PHP Manual

ResourceBundle::get

resourcebundle_get

(PHP > 5.4.0)

ResourceBundle::get -- resourcebundle_get — Get data from the bundle

Opis

Styl obiektowy

mixed ResourceBundle::get ( string|int $index )

Styl proceduralny

mixed resourcebundle_get ( ResourceBundle $r , string|int $index )

Get the data from the bundle by index or string key.

Parametry

r

ResourceBundle object.

index

Data index, must be string or integer.

Zwracane wartości

Returns the data located at the index or NULL on error. Strings, integers and binary data strings are returned as corresponding PHP types, integer array is returned as PHP array. Complex types are returned as ResourceBundle object.

Przykłady

Przykład #1 resourcebundle_get() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_get($r, 'somestring');
?>

Przykład #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->get('somestring');
?>

Powyższy przykład wyświetli:

?Hola, mundo!

Zobacz też:

  • resourcebundle_count() - Get number of elements in the bundle

ResourceBundle::getErrorMessage
ResourceBundle::getLocales
ResourceBundle


Get supported locales

ResourceBundle::get
Spoofchecker
ResourceBundle
PHP Manual

ResourceBundle::getLocales

resourcebundle_locales

(PHP > 5.4.0)

ResourceBundle::getLocales -- resourcebundle_locales — Get supported locales

Opis

Styl obiektowy

array ResourceBundle::getLocales ( string $bundlename )

Styl proceduralny

array resourcebundle_locales ( string $bundlename )

Get available locales from ResourceBundle name.

Parametry

bundlename

Path of ResourceBundle for which to get available locales, or empty string for default locales list.

Zwracane wartości

Returns the list of locales supported by the bundle.

Przykłady

Przykład #1 resourcebundle_locales() example

<?php
$bundle = "/user/share/data/myapp";
echo join(PHP_EOL, resourcebundle_locales($bundle);
?>

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

es
root

Przykład #2 OO example

<?php
$bundle = "/usr/share/data/myapp";
$r = new ResourceBundle( 'es', $bundle);
echo join("\n", $r->getLocales($bundle));
?>

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

es
root

Zobacz też:

  • resourcebundle_get() - Get data from the bundle

ResourceBundle::get
Spoofchecker
ResourceBundle


The Spoofchecker class

(PHP > 5.4.0)

Wstęp

Krótki opis klasy

Spoofchecker {
/* Constants */
const integer SINGLE_SCRIPT_CONFUSABLE = 1 ;
const integer MIXED_SCRIPT_CONFUSABLE = 2 ;
const integer WHOLE_SCRIPT_CONFUSABLE = 4 ;
const integer ANY_CASE = 8 ;
const integer SINGLE_SCRIPT = 16 ;
const integer INVISIBLE = 32 ;
const integer CHAR_LIMIT = 64 ;
/* Metody */
public bool areConfusable ( string $s1 , string $s2 [, string &$error ] )
public __construct ( void )
public bool isSuspicious ( string $text [, string &$error ] )
public void setAllowedLocales ( string $locale_list )
public void setChecks ( string $checks )
}

Stałe predefiniowane

Spoofchecker::SINGLE_SCRIPT_CONFUSABLE

Spoofchecker::MIXED_SCRIPT_CONFUSABLE

Spoofchecker::WHOLE_SCRIPT_CONFUSABLE

Spoofchecker::ANY_CASE

Spoofchecker::SINGLE_SCRIPT

Spoofchecker::INVISIBLE

Spoofchecker::CHAR_LIMIT

Spis treści

  • Spoofchecker::areConfusable — Checks if a given text contains any confusable characters
  • Spoofchecker::__construct — Constructor
  • Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters
  • Spoofchecker::setAllowedLocales — Locales to use when running checks
  • Spoofchecker::setChecks — Set the checks to run
ResourceBundle::getLocales
Spoofchecker::areConfusable
intl


Checks if a given text contains any confusable characters

Spoofchecker
Spoofchecker::__construct
Spoofchecker
PHP Manual

Spoofchecker::areConfusable

(PHP > 5.4.0)

Spoofchecker::areConfusable — Checks if a given text contains any confusable characters

Opis

public bool Spoofchecker::areConfusable ( string $s1 , string $s2 [, string &$error ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

s1

s2

error

Zwracane wartości

Spoofchecker
Spoofchecker::__construct
Spoofchecker


Constructor

Spoofchecker::areConfusable
Spoofchecker::isSuspicious
Spoofchecker
PHP Manual

Spoofchecker::__construct

(PHP > 5.4.0)

Spoofchecker::__construct — Constructor

Opis

public Spoofchecker::__construct ( 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

Spoofchecker::areConfusable
Spoofchecker::isSuspicious
Spoofchecker


Checks if a given text contains any suspicious characters

Spoofchecker::__construct
Spoofchecker::setAllowedLocales
Spoofchecker
PHP Manual

Spoofchecker::isSuspicious

(PHP > 5.4.0)

Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters

Opis

public bool Spoofchecker::isSuspicious ( string $text [, string &$error ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

text

error

Zwracane wartości

Spoofchecker::__construct
Spoofchecker::setAllowedLocales
Spoofchecker


Locales to use when running checks

Spoofchecker::isSuspicious
Spoofchecker::setChecks
Spoofchecker
PHP Manual

Spoofchecker::setAllowedLocales

(PHP > 5.4.0)

Spoofchecker::setAllowedLocales — Locales to use when running checks

Opis

public void Spoofchecker::setAllowedLocales ( string $locale_list )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

locale_list

Zwracane wartości

Spoofchecker::isSuspicious
Spoofchecker::setChecks
Spoofchecker


Set the checks to run

Spoofchecker::setAllowedLocales
Transliterator
Spoofchecker
PHP Manual

Spoofchecker::setChecks

(PHP > 5.4.0)

Spoofchecker::setChecks — Set the checks to run

Opis

public void Spoofchecker::setChecks ( string $checks )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

checks

Zwracane wartości

Spoofchecker::setAllowedLocales
Transliterator
Spoofchecker


The Transliterator class

(PHP > 5.4.0)

Wstęp

Transliterator provides transliteration of strings.

Krótki opis klasy

Transliterator {
/* Stałe */
const integer FORWARD = 0 ;
const integer REVERSE = 1 ;
/* Właściwości */
public $id ;
/* Metody */
__construct ( void )
public static Transliterator create ( string $id [, int $direction ] )
public static Transliterator createFromRules ( string $rules [, string $direction ] )
public Transliterator createInverse ( void )
public int getErrorCode ( void )
public string getErrorMessage ( void )
public static array listIDs ( void )
public string transliterate ( string $subject [, int $start [, int $end ]] )
}

Właściwości

id

Stałe predefiniowane

Transliterator::FORWARD

Transliterator::REVERSE

Spis treści

  • Transliterator::__construct — Construct a Transliterator object
  • Transliterator::create — Create a transliterator
  • Transliterator::createFromRules — Create transliterator from rules
  • Transliterator::createInverse — Create an inverse transliterator
  • Transliterator::getErrorCode — Get last error code
  • Transliterator::getErrorMessage — Get last error message
  • Transliterator::listIDs — Get transliterator IDs
  • Transliterator::transliterate — Transliterate a string
Spoofchecker::setChecks
Transliterator::__construct
intl


Construct a Transliterator object

Transliterator
Transliterator::create
Transliterator
PHP Manual

Transliterator::__construct

(PHP > 5.4.0)

Transliterator::__construct — Construct a Transliterator object

Opis

Transliterator::__construct() ( void )

Constructs a transliterator object.

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

A transliterator object.

Zobacz też:

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::create() - Create a transliterator

Transliterator
Transliterator::create
Transliterator


Create a transliterator

Transliterator::__construct
Transliterator::createFromRules
Transliterator
PHP Manual

Transliterator::create

transliterator_create

(PHP > 5.4.0)

Transliterator::create -- transliterator_create — Create a transliterator

Opis

Styl obiektowy

public static Transliterator Transliterator::create ( string $id [, int $direction ] )

Styl proceduralny

Transliterator transliterator_create ( string $id [, int $direction ] )

Opens a Transliterator by id.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

id

The id.

direction

The direction, defaults to >Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

Zwracane wartości

Returns a Transliterator object on success, or NULL on failure.

Zobacz też:

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::__construct() - Construct a Transliterator object

Transliterator::__construct
Transliterator::createFromRules
Transliterator


Create transliterator from rules

Transliterator::create
Transliterator::createInverse
Transliterator
PHP Manual

Transliterator::createFromRules

transliterator_create_from_rules

(PHP > 5.4.0)

Transliterator::createFromRules -- transliterator_create_from_rules — Create transliterator from rules

Opis

Styl obiektowy

public static Transliterator Transliterator::createFromRules ( string $rules [, string $direction ] )

Styl proceduralny

Transliterator transliterator_create_from_rules ( string $id [, int $direction ] )

Creates a Transliterator from rules.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

rules

The rules.

direction

The direction, defaults to >Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

Zwracane wartości

Returns a Transliterator object on success, or NULL on failure.

Zobacz też:

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::create() - Create a transliterator

Transliterator::create
Transliterator::createInverse
Transliterator


Create an inverse transliterator

Transliterator::createFromRules
Transliterator::getErrorCode
Transliterator
PHP Manual

Transliterator::createInverse

transliterator_create_inverse

(PHP > 5.4.0)

Transliterator::createInverse -- transliterator_create_inverse — Create an inverse transliterator

Opis

Styl obiektowy

public Transliterator Transliterator::createInverse ( void )

Styl proceduralny

Transliterator transliterator_create_inverse ( void )

Opens the inverse transliterator transliterator.

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

Returns a Transliterator object on success, or NULL on failure

Zobacz też:

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::create() - Create a transliterator

Transliterator::createFromRules
Transliterator::getErrorCode
Transliterator


Get last error code

Transliterator::createInverse
Transliterator::getErrorMessage
Transliterator
PHP Manual

Transliterator::getErrorCode

transliterator_get_error_code

(PHP > 5.4.0)

Transliterator::getErrorCode -- transliterator_get_error_code — Get last error code

Opis

Styl obiektowy

public int Transliterator::getErrorCode ( void )

Styl proceduralny

int transliterator_get_error_code ( void )

Gets the last error code for this transliterator.

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 error code on success, or FALSE if none exists, or on failure.

Zobacz też:

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::listIDs() - Get transliterator IDs

Transliterator::createInverse
Transliterator::getErrorMessage
Transliterator


Get last error message

Transliterator::getErrorCode
Transliterator::listIDs
Transliterator
PHP Manual

Transliterator::getErrorMessage

transliterator_get_error_message

(PHP > 5.4.0)

Transliterator::getErrorMessage -- transliterator_get_error_message — Get last error message

Opis

Styl obiektowy

public string Transliterator::getErrorMessage ( void )

Styl proceduralny

string transliterator_get_error_message ( void )

Gets the last error message for this transliterator.

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 error code on success, or FALSE if none exists, or on failure.

Zobacz też:

  • Transliterator::getErrorCode() - Get last error code
  • Transliterator::listIDs() - Get transliterator IDs

Transliterator::getErrorCode
Transliterator::listIDs
Transliterator


Get transliterator IDs

Transliterator::getErrorMessage
Transliterator::transliterate
Transliterator
PHP Manual

Transliterator::listIDs

transliterator_list_ids

(PHP > 5.4.0)

Transliterator::listIDs -- transliterator_list_ids — Get transliterator IDs

Opis

Styl obiektowy

public static array Transliterator::listIDs ( void )

Styl proceduralny

array transliterator_list_ids ( void )

Returns an array with the registered transliterator IDs.

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 registered transliterator IDs on success, lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::transliterate() - Transliterate a string

Transliterator::getErrorMessage
Transliterator::transliterate
Transliterator


Transliterate a string

Transliterator::listIDs
Grapheme Funkcje
Transliterator
PHP Manual

Transliterator::transliterate

transliterator_transliterate

(PHP > 5.4.0)

Transliterator::transliterate -- transliterator_transliterate — Transliterate a string

Opis

Styl obiektowy

public string Transliterator::transliterate ( string $subject [, int $start [, int $end ]] )

Styl proceduralny

transliterator_transliterate ( mixed $transliterator , string $subject [, int $start [, int $end ]] )

Transforms a string or part thereof using an ICU transliterator.

Parametry

transliterator

In the procedural version, either a Transliterator or a string from which a Transliterator can be built.

subject

The string to be transformed.

start

The start index (in UTF-16 code units) from which the string will start to be transformed, inclusive. Indexing starts at 0. The text before will be left as is.

end

The end index (in UTF-16 code units) until which the string will be transformed, exclusive. Indexing starts at 0. The text after will be left as is.

Zwracane wartości

The transfomed string on success, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Converting escaped UTF-16 code units

<?php
$s = "\u304A\u65E9\u3046\u3054\u3056\u3044\u307E\u3059";
echo transliterator_transliterate("Hex-Any/Java", $s), "\n";

//now the reverse operation with a supplementary character
$supplChar = html_entity_decode('&#x1D11E;');
echo mb_strlen($supplChar, "UTF-8"), "\n";
$encSupplChar = transliterator_transliterate("Any-Hex/Java", $supplChar);
//echoes two encoded UTF-16 code units
echo $encSupplChar, "\n";
//and back
echo transliterator_transliterate("Hex-Any/Java", $encSupplChar), "\n";
?>

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

お早うございます
1
\uD834\uDD1E
𝄞

Zobacz też:

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::__construct() - Construct a Transliterator object

Transliterator::listIDs
Grapheme Funkcje
Transliterator


Grapheme Funkcje

Spis treści

  • grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
  • grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strlen — Get string length in grapheme units
  • grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • grapheme_substr — Return part of a string
Transliterator::transliterate
grapheme_extract
intl


Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Grapheme Funkcje
grapheme_stripos
Grapheme Funkcje
PHP Manual

grapheme_extract

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Opis

Styl proceduralny

string grapheme_extract ( string $haystack , int $size [, int $extract_type [, int $start = 0 [, int &$next ]]] )

Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

Parametry

haystack

String to search.

size

Maximum number items - based on the $extract_type - to return.

extract_type

Defines the type of units referred to by the $size parameter:

  • GRAPHEME_EXTR_COUNT (default) - $size is the number of default grapheme clusters to extract.
  • GRAPHEME_EXTR_MAXBYTES - $size is the maximum number of bytes returned.
  • GRAPHEME_EXTR_MAXCHARS - $size is the maximum number of UTF-8 characters returned.

start

Starting position in $haystack in bytes - if given, it must be zero or a positive value that is less than or equal to the length of $haystack in bytes. If $start does not point to the first byte of a UTF-8 character, the start position is moved to the next character boundary.

next

Reference to a value that will be set to the next starting position. When the call returns, this may point to the first byte position past the end of the string.

Zwracane wartości

A string starting at offset $start and ending on a default grapheme cluster boundary that conforms to the $size and $extract_type specified.

Przykłady

Przykład #1 grapheme_extract() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_extract( $char_a_ring_nfd . $char_o_diaeresis_nfd, 1, GRAPHEME_EXTR_COUNT, 2));

?>

Powyższy przykład wyświetli:

o%CC%88

Zobacz też:

  • grapheme_substr() - Return part of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

Grapheme Funkcje
grapheme_stripos
Grapheme Funkcje


Find position (in grapheme units) of first occurrence of a case-insensitive string

grapheme_extract
grapheme_stristr
Grapheme Funkcje
PHP Manual

grapheme_stripos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string

Opis

Styl proceduralny

int grapheme_stripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of first occurrence of a case-insensitive string

Parametry

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Zwracane wartości

Returns the position as an integer. If needle is not found, grapheme_stripos() will return boolean FALSE.

Przykłady

Przykład #1 grapheme_stripos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print grapheme_stripos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);

?>

Powyższy przykład wyświetli:

2

Zobacz też:

  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_extract
grapheme_stristr
Grapheme Funkcje


Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

grapheme_stripos
grapheme_strlen
Grapheme Funkcje
PHP Manual

grapheme_stristr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

Opis

Styl proceduralny

string grapheme_stristr ( string $haystack , string $needle [, bool $before_needle = false ] )

Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.

Parametry

haystack

The input string. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

before_needle

If TRUE, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle.

Zwracane wartości

Returns the portion of $haystack, or FALSE if $needle is not found.

Przykłady

Przykład #1 grapheme_stristr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_O_diaeresis_nfd));

?>

Powyższy przykład wyświetli:

o%CC%88a%CC%8A

Zobacz też:

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_stripos
grapheme_strlen
Grapheme Funkcje


Get string length in grapheme units

grapheme_stristr
grapheme_strpos
Grapheme Funkcje
PHP Manual

grapheme_strlen

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strlen — Get string length in grapheme units

Opis

Styl proceduralny

int grapheme_strlen ( string $input )

Get string length in grapheme units (not bytes or characters)

Parametry

input

The string being measured for length. It must be a valid UTF-8 string.

Zwracane wartości

The length of the string on success, and 0 if the string is empty.

Przykłady

Przykład #1 grapheme_strlen() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strlen( 'abc' . $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd);

?>

Powyższy przykład wyświetli:

6

Zobacz też:

  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_stristr
grapheme_strpos
Grapheme Funkcje


Find position (in grapheme units) of first occurrence of a string

grapheme_strlen
grapheme_strripos
Grapheme Funkcje
PHP Manual

grapheme_strpos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strpos — Find position (in grapheme units) of first occurrence of a string

Opis

Styl proceduralny

int grapheme_strpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of first occurrence of a string

Parametry

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Zwracane wartości

Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE.

Przykłady

Przykład #1 grapheme_strpos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strpos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);

?>

Powyższy przykład wyświetli:

2

Zobacz też:

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strlen
grapheme_strripos
Grapheme Funkcje


Find position (in grapheme units) of last occurrence of a case-insensitive string

grapheme_strpos
grapheme_strrpos
Grapheme Funkcje
PHP Manual

grapheme_strripos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string

Opis

Styl proceduralny

int grapheme_strripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of last occurrence of a case-insensitive string

Parametry

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Zwracane wartości

Returns the position as an integer. If needle is not found, grapheme_strripos() will return boolean FALSE.

Przykłady

Przykład #1 grapheme_strripos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print grapheme_strripos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);

?>

Powyższy przykład wyświetli:

2

Zobacz też:

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strpos
grapheme_strrpos
Grapheme Funkcje


Find position (in grapheme units) of last occurrence of a string

grapheme_strripos
grapheme_strstr
Grapheme Funkcje
PHP Manual

grapheme_strrpos

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string

Opis

Styl proceduralny

int grapheme_strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find position (in grapheme units) of last occurrence of a string

Parametry

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional $offset parameter allows you to specify where in $haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of $offset.

Zwracane wartości

Returns the position as an integer. If needle is not found, grapheme_strrpos() will return boolean FALSE.

Przykłady

Przykład #1 grapheme_strrpos() example

<?php
$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strrpos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);
?>

Powyższy przykład wyświetli:

2

Zobacz też:

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strripos
grapheme_strstr
Grapheme Funkcje


Returns part of haystack string from the first occurrence of needle to the end of haystack.

grapheme_strrpos
grapheme_substr
Grapheme Funkcje
PHP Manual

grapheme_strstr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack.

Opis

Styl proceduralny

string grapheme_strstr ( string $haystack , string $needle [, bool $before_needle = false ] )

Returns part of haystack string from the first occurrence of needle to the end of haystack.

Parametry

haystack

The input string. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

before_needle

If TRUE, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle.

Zwracane wartości

Returns the portion of string, or FALSE if needle is not found.

Przykłady

Przykład #1 grapheme_strstr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_o_diaeresis_nfd));

?>

Powyższy przykład wyświetli:

o%CC%88a%CC%8A

Zobacz też:

  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strrpos
grapheme_substr
Grapheme Funkcje


Return part of a string

grapheme_strstr
IDN Funkcje
Grapheme Funkcje
PHP Manual

grapheme_substr

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

grapheme_substr — Return part of a string

Opis

Styl proceduralny

int grapheme_substr ( string $string , int $start [, int $length ] )

Return part of a string

Parametry

string

The input string. Must be valid UTF-8.

start

Start position in default grapheme units. If $start is non-negative, the returned string will start at the $start'th position in $string, counting from zero. If $start is negative, the returned string will start at the $start'th grapheme unit from the end of string.

length

Length in grapheme units. If $length is given and is positive, the string returned will contain at most $length grapheme units beginning from $start (depending on the length of string). If $length is given and is negative, then that many grapheme units will be omitted from the end of string (after the start position has been calculated when a start is negative). If $start denotes a position beyond this truncation, FALSE will be returned.

Zwracane wartości

Returns the extracted part of $string.

Rejestr zmian

Wersja | Opis
5.4 | If length is given and positive and the argument string is shorter than the specified length, all the rest of the string according to start parameter is returned. Previously, FALSE was returned.

Przykłady

Przykład #1 grapheme_substr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_substr( "ao" . $char_a_ring_nfd . "bc" . $char_o_diaeresis_nfd . "O", 2, -1 ));
?>

Powyższy przykład wyświetli:

a%CC%8Abco%CC%88

Zobacz też:

  • grapheme_extract() - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

grapheme_strstr
IDN Funkcje
Grapheme Funkcje


IDN Funkcje

Spis treści

  • idn_to_ascii — Convert domain name to IDNA ASCII form.
  • idn_to_unicode — Alias dla idn_to_utf8
  • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.
grapheme_substr
idn_to_ascii
intl


Convert domain name to IDNA ASCII form.

IDN Funkcje
idn_to_unicode
IDN Funkcje
PHP Manual

idn_to_ascii

(PHP 5 >= 5.3.0, PECL intl >= 1.0.2, PECL idn >= 0.1)

idn_to_ascii — Convert domain name to IDNA ASCII form.

Opis

Styl proceduralny

string idn_to_ascii ( string $domain [, int $options = 0 [, int $variant = INTL_IDNA_VARIANT_2003 [, array &$idna_info ]]] )

This function converts Unicode domain name to IDNA ASCII-compatible format.

Parametry

domain

Domain to convert. In PHP 5 must be UTF-8 encoded.

options

Conversion options - combination of IDNA_* constants (except IDNA_ERROR_* constants).

variant

Either INTL_IDNA_VARIANT_2003 for IDNA 2003 or INTL_IDNA_VARIANT_UTS46 for UTS #46.

idna_info

This parameter can be used only if INTL_IDNA_VARIANT_UTS46 was used for variant. In that case, it will be filled with an array with the keys 'result', the possibly illegal result of the transformation, 'isTransitionalDifferent', a boolean indicating whether the usage of the transitional mechanisms of UTS #46 either has or would have changed the result and 'errors', which is an int representing a bitset of the error constants IDNA_ERROR_*.

Zwracane wartości

Domain name encoded in ASCII-compatible form. lub FALSE w przypadku niepowodzenia

Rejestr zmian

Wersja | Opis
5.4.0/PECL 2.0.0b1 | Added the parameters variant and idna_info; UTS #46 support.

Przykłady

Przykład #1 idn_to_ascii() example

<?php

echo idn_to_ascii('täst.de');

?>

Powyższy przykład wyświetli:

xn--tst-qla.de

Zobacz też:

  • idn_to_unicode() - Alias dla idn_to_utf8

IDN Funkcje
idn_to_unicode
IDN Funkcje


Alias dla idn_to_utf8

idn_to_ascii
idn_to_utf8
IDN Funkcje
PHP Manual

idn_to_unicode

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

idn_to_unicode — Alias dla idn_to_utf8()

Opis

Ta funkcja jest aliasem dla: idn_to_utf8().

idn_to_ascii
idn_to_utf8
IDN Funkcje


Convert domain name from IDNA ASCII to Unicode.

idn_to_unicode
intl Funkcje
IDN Funkcje
PHP Manual

idn_to_utf8

(PHP 5 >= 5.3.0, PECL intl >= 1.0.2, PECL idn >= 0.1)

idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode.

Opis

Styl proceduralny

string idn_to_utf8 ( string $domain [, int $options = 0 [, int $variant = INTL_IDNA_VARIANT_2003 [, array &$idna_info ]]] )

This function converts Unicode domain name from IDNA ASCII-compatible format to plain Unicode, encoded in UTF-8.

Parametry

domain

Domain to convert in IDNA ASCII-compatible format.

options

Conversion options - combination of IDNA_* constants (except IDNA_ERROR_* constants).

variant

Either INTL_IDNA_VARIANT_2003 for IDNA 2003 or INTL_IDNA_VARIANT_UTS46 for UTS #46.

idna_info

This parameter can be used only if INTL_IDNA_VARIANT_UTS46 was used for variant. In that case, it will be filled with an array with the keys 'result', the possibly illegal result of the transformation, 'isTransitionalDifferent', a boolean indicating whether the usage of the transitional mechanisms of UTS #46 either has or would have changed the result and 'errors', which is an int representing a bitset of the error constants IDNA_ERROR_*.

Zwracane wartości

Domain name in Unicode, encoded in UTF-8. lub FALSE w przypadku niepowodzenia

Rejestr zmian

Wersja | Opis
5.4.0/PECL 2.0.0b1 | Added the parameters variant and idna_info; UTS #46 support.

Przykłady

Przykład #1 idn_to_utf8() example

<?php

echo idn_to_utf8('xn--tst-qla.de');

?>

Powyższy przykład wyświetli:

täst.de

Zobacz też:

  • idn_to_unicode() - Alias dla idn_to_utf8

idn_to_unicode
intl Funkcje
IDN Funkcje


intl Funkcje

Spis treści

  • intl_error_name — Get symbolic name for a given error code
  • intl_get_error_code — Get the last error code
  • intl_get_error_message — Get description of the last error
  • intl_is_failure — Check whether the given error code indicates failure
idn_to_utf8
intl_error_name
intl


Get symbolic name for a given error code

intl Funkcje
intl_get_error_code
intl Funkcje
PHP Manual

intl_error_name

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_error_name — Get symbolic name for a given error code

Opis

string intl_error_name ( int $error_code )

Return ICU error code name.

Parametry

error_code

ICU error code.

Zwracane wartości

The returned string will be the same as the name of the error code constant.

Przykłady

Przykład #1 intl_error_name() example

<?php
$coll     = collator_create( 'en_RU' );
$err_code = collator_get_error_code( $coll );

printf( "Symbolic name for %d is %s\n.", $err_code, intl_error_name( $err_code ) );
?>

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

Symbolic name for -128 is U_USING_FALLBACK_WARNING.

Zobacz też:

  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_get_error_code() - Get the last error code
  • intl_get_error_message() - Get description of the last error

intl Funkcje
intl_get_error_code
intl Funkcje


Get the last error code

intl_error_name
intl_get_error_message
intl Funkcje
PHP Manual

intl_get_error_code

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_get_error_code — Get the last error code

Opis

int intl_get_error_code ( void )

Useful to handle errors occurred in static methods when there's no object to get error code from.

Zwracane wartości

Error code returned by the last API function call.

Przykłady

Przykład #1 intl_get_error_code() example

<?php
$coll = collator_create( '<bad_param>' );
if( !$coll ) {
    handle_error( intl_get_error_code() );
}
?>

Zobacz też:

  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_message() - Get description of the last error
  • collator_get_error_code() - Get collator's last error code
  • numfmt_get_error_code() - Get formatter's last error code.

intl_error_name
intl_get_error_message
intl Funkcje


Get description of the last error

intl_get_error_code
intl_is_failure
intl Funkcje
PHP Manual

intl_get_error_message

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_get_error_message — Get description of the last error

Opis

string intl_get_error_message ( void )

Get error message from last internationalization function called.

Zwracane wartości

Description of an error occurred in the last API function call.

Przykłady

Przykład #1 intl_get_error_message() example

<?php
if( Collator::getAvailableLocales() === false ) {
    show_error( intl_get_error_message() );
}
?>

Zobacz też:

  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure
  • collator_get_error_message() - Get text for collator's last error code
  • numfmt_get_error_message() - Get formatter's last error message.

intl_get_error_code
intl_is_failure
intl Funkcje


Check whether the given error code indicates failure

intl_get_error_message
Multibyte String
intl Funkcje
PHP Manual

intl_is_failure

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

intl_is_failure — Check whether the given error code indicates failure

Opis

bool intl_is_failure ( int $error_code )

Parametry

error_code

is a value that returned by functions: intl_get_error_code(), collator_get_error_code() .

Zwracane wartości

TRUE if it the code indicates some failure, and FALSE in case of success or a warning.

Przykłady

Przykład #1 intl_is_failure() example

<?php
function check( $err_code )
{
    var_export( intl_is_failure( $err_code ) );
    echo "\n";
}

check( U_ZERO_ERROR );
check( U_USING_FALLBACK_WARNING );
check( U_ILLEGAL_ARGUMENT_ERROR );
?>

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

false
false
true

Zobacz też:

  • intl_get_error_code() - Get the last error code
  • collator_get_error_code() - Get collator's last error code
  • Collator-getErrorCode() - Get collator's last error code

intl_get_error_message
Multibyte String
intl Funkcje


Multibyte String

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Summaries of supported encodings
  • Basics of Japanese multi-byte encodings
  • HTTP Input and Output
  • Supported Character Encodings
  • Function Overloading Feature
  • PHP Character Encoding Requirements
  • Multibyte String Funkcje
    • mb_check_encoding — Check if the string is valid for the specified encoding
    • mb_convert_case — Perform case folding on a string
    • mb_convert_encoding — Convert character encoding
    • mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
    • mb_convert_variables — Convert character code in variable(s)
    • mb_decode_mimeheader — Decode string in MIME header field
    • mb_decode_numericentity — Decode HTML numeric string reference to character
    • mb_detect_encoding — Detect character encoding
    • mb_detect_order — Set/Get character encoding detection order
    • mb_encode_mimeheader — Encode string for MIME header
    • mb_encode_numericentity — Encode character to HTML numeric string reference
    • mb_encoding_aliases — Get aliases of a known encoding type
    • mb_ereg_match — Regular expression match for multibyte string
    • mb_ereg_replace — Replace regular expression with multibyte support
    • mb_ereg_search_getpos — Returns start point for next regular expression match
    • mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match
    • mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
    • mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
    • mb_ereg_search_regs — Returns the matched part of a multibyte regular expression
    • mb_ereg_search_setpos — Set start point of next regular expression match
    • mb_ereg_search — Multibyte regular expression match for predefined multibyte string
    • mb_ereg — Regular expression match with multibyte support
    • mb_eregi_replace — Replace regular expression with multibyte support ignoring case
    • mb_eregi — Regular expression match ignoring case with multibyte support
    • mb_get_info — Get internal settings of mbstring
    • mb_http_input — Detect HTTP input character encoding
    • mb_http_output — Set/Get HTTP output character encoding
    • mb_internal_encoding — Set/Get internal character encoding
    • mb_language — Set/Get current language
    • mb_list_encodings — Returns an array of all supported encodings
    • mb_output_handler — Callback function converts character encoding in output buffer
    • mb_parse_str — Parse GET/POST/COOKIE data and set global variable
    • mb_preferred_mime_name — Get MIME charset string
    • mb_regex_encoding — Returns current encoding for multibyte regex as string
    • mb_regex_set_options — Set/Get the default options for mbregex functions
    • mb_send_mail — Send encoded mail
    • mb_split — Split multibyte string using regular expression
    • mb_strcut — Get part of string
    • mb_strimwidth — Get truncated string with specified width
    • mb_stripos — Finds position of first occurrence of a string within another, case insensitive
    • mb_stristr — Finds first occurrence of a string within another, case insensitive
    • mb_strlen — Get string length
    • mb_strpos — Find position of first occurrence of string in a string
    • mb_strrchr — Finds the last occurrence of a character in a string within another
    • mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive
    • mb_strripos — Finds position of last occurrence of a string within another, case insensitive
    • mb_strrpos — Find position of last occurrence of a string in a string
    • mb_strstr — Finds first occurrence of a string within another
    • mb_strtolower — Make a string lowercase
    • mb_strtoupper — Make a string uppercase
    • mb_strwidth — Return width of string
    • mb_substitute_character — Set/Get substitution character
    • mb_substr_count — Count the number of substring occurrences
    • mb_substr — Get part of string
intl_is_failure
Wstęp
Język naturalny i obsługa kodowania znaków


Wstęp

While there are many languages in which every necessary character can be represented by a one-to-one mapping to an 8-bit value, there are also several languages which require so many characters for written communication that they cannot be contained within the range a mere byte can code (A byte is made up of eight bits. Each bit can contain only two distinct values, one or zero. Because of this, a byte can only represent 256 unique values (two to the power of eight)). Multibyte character encoding schemes were developed to express more than 256 characters in the regular bytewise coding system.

When you manipulate (trim, split, splice, etc.) strings encoded in a multibyte encoding, you need to use special functions since two or more consecutive bytes may represent a single character in such encoding schemes. Otherwise, if you apply a non-multibyte-aware string function to the string, it probably fails to detect the beginning or ending of the multibyte character and ends up with a corrupted garbage string that most likely loses its original meaning.

mbstring provides multibyte specific string functions that help you deal with multibyte encodings in PHP. In addition to that, mbstring handles character encoding conversion between the possible encoding pairs. mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience (listed below).

Multibyte String
Instalacja/Konfiguracja
Multibyte String


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Multibyte String


Instalacja

mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details.

The following configure options are related to the mbstring module.

  • --enable-mbstring : Enable mbstring functions. This option is required to use mbstring functions.

    libmbfl is necesarry for mbstring. libmbfl is bundled with mbstring. If libmbfl is already installed on the system, --with-libmbfl[=DIR] can be specified to use the installed library.

    As of PHP 4.3.0, mbstring extension provides enhanced support for Simplified Chinese, Traditional Chinese, Korean, and Russian in addition to Japanese.

    For PHP 4.3.3 or before, To enable that feature, you will have to supply either one of the following options to the LANG parameter of --enable-mbstring=LANG ; --enable-mbstring=cn for Simplified Chinese support, --enable-mbstring=tw for Traditional Chinese support, --enable-mbstring=kr for Korean support, --enable-mbstring=ru for Russian support, and --enable-mbstring=ja for Japanese support (default). To enable all supported encoding, use --enable-mbstring=all .

    Informacja:

    As of PHP 4.3.4, all supported encoding by libmbfl is enabled with --enable-mbstring .

  • --enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.

    Informacja:

    As of PHP 4.3.0, the option --enable-mbstr-enc-trans was eliminated and replaced with the runtime setting mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On (the default is Off).

  • --disable-mbregex : Disable regular expression functions with multibyte character support.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

mbstring configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mbstring.language | "neutral" | PHP_INI_ALL | Available since PHP 4.3.0.; PHP_INI_PERDIR in PHP <= 5.2.6
mbstring.detect_order | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.http_input | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP <= 4.2.3; PHP_INI_SYSTEM | PHP_INI_PERDIR from PHP 4.3 through 5.2.6. Available since PHP 4.2.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Available since PHP 5.1.2.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

mbstring.language string

The default national language setting (NLS) used in mbstring. Note that this option automagically defines mbstring.internal_encoding and mbstring.internal_encoding should be placed after mbstring.language in php.ini

mbstring.encoding_translation boolean

Enables the transparent character encoding filter for the incoming HTTP queries, which performs detection and conversion of the input encoding to the internal character encoding.

mbstring.internal_encoding string

Defines the default internal character encoding.

mbstring.http_input string

Defines the default HTTP input character encoding.

mbstring.http_output string

Defines the default HTTP output character encoding.

mbstring.detect_order string

Defines default character code detection order. See also mb_detect_order().

mbstring.substitute_character string

Defines character to substitute for invalid character encoding.

mbstring.func_overload string

Overloads a set of single byte functions by the mbstring counterparts. See Function overloading for more information.

mbstring.strict_detection boolean

Enables the strict encoding detection.

According to the » HTML 4.01 specification, Web browsers are allowed to encode a form being submitted with a character encoding different from the one used for the page. See mb_http_input() to detect character encoding used by browsers.

Although popular browsers are capable of giving a reasonably accurate guess to the character encoding of a given HTML document, it would be better to set the charset parameter in the Content-Type HTTP header to the appropriate value by header() or default_charset ini setting.

Przykład #1 php.ini setting examples

; Set default language
mbstring.language        = Neutral; Set default language to Neutral(UTF-8) (default)
mbstring.language        = English; Set default language to English
mbstring.language        = Japanese; Set default language to Japanese

;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input           = pass    ; No conversion.
mbstring.http_input           = auto    ; Set HTTP input to auto
                                ; "auto" is expanded according to mbstring.language
mbstring.http_input           = SJIS    ; Set HTTP input to SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specify order

;; Set default HTTP output character encoding
mbstring.http_output          = pass    ; No conversion
mbstring.http_output          = UTF-8   ; Set HTTP output encoding to UTF-8

;; Set default character encoding detection order
mbstring.detect_order         = auto    ; Set detect order to auto
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

;; Set default substitute character
mbstring.substitute_character = 12307   ; Specify Unicode value
mbstring.substitute_character = none    ; Do not print character
mbstring.substitute_character = long    ; Long Example: U+3000,JIS+7E7E

Przykład #2 php.ini setting for EUC-JP users

;; Disable Output Buffering
output_buffering      = Off

;; Set HTTP header charset
default_charset       = EUC-JP

;; Set default language to Japanese
mbstring.language = Japanese

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set HTTP input encoding conversion to auto
mbstring.http_input   = auto

;; Convert HTTP output to EUC-JP
mbstring.http_output  = EUC-JP

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP

;; Do not print invalid characters
mbstring.substitute_character = none

Przykład #3 php.ini setting for SJIS users

;; Enable Output Buffering
output_buffering     = On

;; Set mb_output_handler to enable output conversion
output_handler       = mb_output_handler

;; Set HTTP header charset
default_charset      = Shift_JIS

;; Set default language to Japanese
mbstring.language = Japanese

;; Set http input encoding conversion to auto
mbstring.http_input  = auto

;; Convert to SJIS
mbstring.http_output = SJIS

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP

;; Do not print invalid characters
mbstring.substitute_character = none

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

MB_OVERLOAD_MAIL (integer)
MB_OVERLOAD_STRING (integer)
MB_OVERLOAD_REGEX (integer)
MB_CASE_UPPER (integer)
MB_CASE_LOWER (integer)
MB_CASE_TITLE (integer)
Typy zasobów
Summaries of supported encodings
Multibyte String


Summaries of supported encodings

Summaries of supported encodings
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:ISO 10646
Description: The Universal Character Set with 31-bit code space, standardized as UCS-4 by ISO/IEC 10646. It is kept synchronized with the latest version of the Unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in big endian form.
Name in the IANA character set registry:ISO-10646-UCS-4
Underlying character set:UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in little endian form.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: The Universal Character Set with 16-bit code space, standardized as UCS-2 by ISO/IEC 10646. It is kept synchronized with the latest version of the unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in big endian form.
Name in the IANA character set registry:ISO-10646-UCS-2
Underlying character set:UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-32
Underlying character set:Unicode
Description: Unicode Transformation Format of 32-bit unit width, whose encoding space refers to the Unicode's codeset standard. This encoding scheme wasn't identical to UCS-4 because the code space of Unicode were limited to a 21-bit value.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:UTF-32BE
Underlying character set:Unicode
Description:See above
Additional note: In contrast to UTF-32, strings are always assumed to be in big endian form.
Name in the IANA character set registry:UTF-32LE
Underlying character set:Unicode
Description:See above
Additional note: In contrast to UTF-32, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-16
Underlying character set:Unicode
Description: Unicode Transformation Format of 16-bit unit width. It's worth a note that UTF-16 is no longer the same specification as UCS-2 because the surrogate mechanism has been introduced since Unicode 2.0 and UTF-16 now refers to a 21-bit code space.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry:UTF-16BE
Underlying character set:Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry:UTF-16LE
Underlying character set:Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in little endian form.
Name in the IANA character set registry:UTF-8
Underlying character set:Unicode / UCS
Description: Unicode Transformation Format of 8-bit unit width.
Additional note:none
Name in the IANA character set registry:UTF-7
Underlying character set:Unicode
Description: A mail-safe transformation format of Unicode, specified in » RFC2152.
Additional note:none
Name in the IANA character set registry:(none)
Underlying character set:Unicode
Description: A variant of UTF-7 which is specialized for use in the » IMAP protocol.
Additional note:none
Name in the IANA character set registry: US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII
Underlying character set:ASCII / ISO 646
Description: American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646.
Additional note:(none)
Name in the IANA character set registry: EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese
Underlying character set: Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990
Description: As you see the name is derived from an abbreviation of Extended UNIX Code Packed Format for Japanese, this encoding is mostly used on UNIX or alike platforms. The original encoding scheme, Extended UNIX Code, is designed on the basis of ISO 2022.
Additional note: The character set referred to by EUC-JP is different to IBM932 / CP932, which are used by OS/2® and Microsoft® Windows®. For information interchange with those platforms, use EUCJP-WIN instead.
Name in the IANA character set registry:Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS
Underlying character set:Compound of JIS X0201:1997 / JIS X0208:1997
Description: Shift_JIS was developed in early 80's, at the time personal Japanese word processors were brought into the market, in order to maintain compatiblities with the legacy encoding scheme JIS X 0201:1976. According to the IANA definition the codeset of Shift_JIS is slightly different to IBM932 / CP932. However, the names "SJIS" / "Shift_JIS" are often wrongly used to refer to these codesets.
Additional note:For the CP932 codemap, use SJIS-WIN instead.
Name in the IANA character set registry:(none)
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as EUC-JP, the underlying character set is different. That is, some code points map to different characters than EUC-JP.
Additional note:none
Name in the IANA character set registry:Windows-31J / csWindows31J
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as Shift_JIS, the underlying character set is different. That means some code points map to different characters than Shift_JIS.
Additional note:(none)
Name in the IANA character set registry:ISO-2022-JP (preferred MIME name) / csISO2022JP
Underlying character set: US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983
Description: » RFC1468
Additional note:(none)
Name in the IANA character set registry:JIS
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-1
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-2
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-3
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-4
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-6
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-7
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-8
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-9
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-10
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-13
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-14
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-8859-15
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte2be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte2le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte4be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:byte4le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:BASE64
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:HTML-ENTITIES
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:7bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:8bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-CN
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP936
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:HZ
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-TW
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP950
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:BIG-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:EUC-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:UHC (CP949)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:ISO-2022-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:Windows-1251 (CP1251)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:Windows-1252 (CP1252)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:CP866 (IBM866)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry:KOI8-R
Underlying character set:
Description:
Additional note:
Stałe predefiniowane
Basics of Japanese multi-byte encodings
Multibyte String


Basics of Japanese multi-byte encodings

Japanese characters can only be represented by multibyte encodings, and multiple encoding standards are used depending on platform and text purpose. To make matters worse, these encoding standards differ slightly from one another. In order to create a web application which would be usable in a Japanese environment, a developer has to keep these complexities in mind to ensure that the proper character encodings are used.

  • Storage for a character can be up to six bytes
  • Most Japanese multibyte characters appear twice as wide as single-byte characters. These characters are called "zen-kaku" in Japanese, which means "full width". Other, narrower, characters are called "han-kaku", which means "half width". The graphical properties of the characters, however, depends upon the type faces used to display them.
  • Some character encodings use shift(escape) sequences defined in ISO-2022 to switch the code map of the specific code area (00h to 7fh).
  • ISO-2022-JP should be used in SMTP/NNTP, and headers and entities should be reencoded as per RFC requirements. Although those are not requisites, it's still a good idea because several popular user agents cannot recognize any other encoding methods.
  • Web pages created for mobile phone services such as » i-mode or » EZweb are supposed to use Shift_JIS.
  • As of PHP 5.4.0, the pictogram characters used for mobile phone service such as » i-mode or » EZweb are supported.

Summaries of supported encodings
HTTP Input and Output
Multibyte String


HTTP Input and Output

HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.

Informacja:

In PHP 4.3.2 or earlier versions, there was a limitation in this functionality that mbstring does not perform character encoding conversion in POST data if the enctype attribute in the form element is set to multipart/form-data. So you have to convert the incoming data by yourself in this case if necessary.

Beginning with PHP 4.3.3, if enctype for HTML form is set to multipart/form-data and mbstring.encoding_translation is set to On in php.ini the POST'ed variables and the names of uploaded files will be converted to the internal character encoding as well. However, the conversion isn't applied to the query keys.

  • HTTP Input

    There is no way to control HTTP input character conversion from a PHP script. To disable HTTP input character conversion, it has to be done in php.ini.

    Przykład #1 Disable HTTP input conversion in php.ini

    ;; Disable HTTP Input conversion
mbstring.http_input = pass
;; Disable HTTP Input conversion (PHP 4.3.0 or higher)
mbstring.encoding_translation = Off

    When using PHP as an Apache module, it is possible to override those settings in each Virtual Host directive in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.

  • HTTP Output

    There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as the ob_start callback function.

Przykład #2 php.ini setting example

;; Enable output character encoding conversion for all PHP pages

;; Enable Output Buffering
output_buffering    = On

;; Set mb_output_handler to enable output conversion
output_handler      = mb_output_handler

Przykład #3 Script example

<?php

// Enable output character encoding conversion only for this page

// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');

// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');

?>

Basics of Japanese multi-byte encodings
Supported Character Encodings
Multibyte String


Supported Character Encodings

Currently the following character encodings are supported by the mbstring module. Any of those Character encodings can be specified in the encoding parameter of mbstring functions.

The following character encodings are supported in this PHP extension:

  • UCS-4*
  • UCS-4BE
  • UCS-4LE*
  • UCS-2
  • UCS-2BE
  • UCS-2LE
  • UTF-32*
  • UTF-32BE*
  • UTF-32LE*
  • UTF-16*
  • UTF-16BE*
  • UTF-16LE*
  • UTF-7
  • UTF7-IMAP
  • UTF-8*
  • ASCII*
  • EUC-JP*
  • SJIS*
  • eucJP-win*
  • SJIS-win*
  • ISO-2022-JP
  • ISO-2022-JP-MS
  • CP932
  • CP51932
  • SJIS-mac** (alias: MacJapanese)
  • SJIS-Mobile#DOCOMO** (alias: SJIS-DOCOMO)
  • SJIS-Mobile#KDDI** (alias: SJIS-KDDI)
  • SJIS-Mobile#SOFTBANK** (alias: SJIS-SOFTBANK)
  • UTF-8-Mobile#DOCOMO** (alias: UTF-8-DOCOMO)
  • UTF-8-Mobile#KDDI-A**
  • UTF-8-Mobile#KDDI-B** (alias: UTF-8-KDDI)
  • UTF-8-Mobile#SOFTBANK** (alias: UTF-8-SOFTBANK)
  • ISO-2022-JP-MOBILE#KDDI** (alias: ISO-2022-JP-KDDI)
  • JIS
  • JIS-ms
  • CP50220
  • CP50220raw
  • CP50221
  • CP50222
  • ISO-8859-1*
  • ISO-8859-2*
  • ISO-8859-3*
  • ISO-8859-4*
  • ISO-8859-5*
  • ISO-8859-6*
  • ISO-8859-7*
  • ISO-8859-8*
  • ISO-8859-9*
  • ISO-8859-10*
  • ISO-8859-13*
  • ISO-8859-14*
  • ISO-8859-15*
  • byte2be
  • byte2le
  • byte4be
  • byte4le
  • BASE64
  • HTML-ENTITIES
  • 7bit
  • 8bit
  • EUC-CN*
  • CP936
  • GB18030**
  • HZ
  • EUC-TW*
  • CP950
  • BIG-5*
  • EUC-KR*
  • UHC (CP949)
  • ISO-2022-KR
  • Windows-1251 (CP1251)
  • Windows-1252 (CP1252)
  • CP866 (IBM866)
  • KOI8-R*

* denotes encodings usable also in regular expressions.

** denotes encodings available since PHP 5.4.0.

Any php.ini entry which accepts an encoding name can also use the values "auto" and "pass". mbstring functions which accept an encoding name can also use the value "auto".

If "pass" is set, no character encoding conversion is performed.

If "auto" is set, it is expanded to the list of encodings defined per the NLS. For instance, if the NLS is set to Japanese, the value is assumed to be "ASCII,JIS,UTF-8,EUC-JP,SJIS".

See also mb_detect_order()

HTTP Input and Output
Function Overloading Feature
Multibyte String


Function Overloading Feature

You might often find it difficult to get an existing PHP application to work in a given multibyte environment. This happens because most PHP applications out there are written with the standard string functions such as substr(), which are known to not properly handle multibyte-encoded strings.

mbstring supports a 'function overloading' feature which enables you to add multibyte awareness to such an application without code modification by overloading multibyte counterparts on the standard string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. This feature makes it easy to port applications that only support single-byte encodings to a multibyte environment in many cases.

To use function overloading, set mbstring.func_overload in php.ini to a positive value that represents a combination of bitmasks specifying the categories of functions to be overloaded. It should be set to 1 to overload the mail() function. 2 for string functions, 4 for regular expression functions. For example, if it is set to 7, mail, strings and regular expression functions will be overloaded. The list of overloaded functions are shown below.

Functions to be overloaded
value of mbstring.func_overload | original function | overloaded function
1 | mail() | mb_send_mail()
2 | strlen() | mb_strlen()
2 | strpos() | mb_strpos()
2 | strrpos() | mb_strrpos()
2 | substr() | mb_substr()
2 | strtolower() | mb_strtolower()
2 | strtoupper() | mb_strtoupper()
2 | stripos() | mb_stripos()
2 | strripos() | mb_strripos()
2 | strstr() | mb_strstr()
2 | stristr() | mb_stristr()
2 | strrchr() | mb_strrchr()
2 | substr_count() | mb_substr_count()
4 | ereg() | mb_ereg()
4 | eregi() | mb_eregi()
4 | ereg_replace() | mb_ereg_replace()
4 | eregi_replace() | mb_eregi_replace()
4 | split() | mb_split()

Informacja:

It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour.

Supported Character Encodings
PHP Character Encoding Requirements
Multibyte String


PHP Character Encoding Requirements

Encodings of the following types are safely used with PHP.

  • A singlebyte encoding,

    • which has ASCII-compatible (ISO646 compatible) mappings for the characters in range of 00h to 7fh.

  • A multibyte encoding,

    • which has ASCII-compatible mappings for the characters in range of 00h to 7fh.
    • which don't use ISO2022 escape sequences.
    • which don't use a value from 00h to 7fh in any of the compounded bytes that represents a single character.

These are examples of character encodings that are unlikely to work with PHP.

JIS, SJIS, ISO-2022-JP, BIG-5

Although PHP scripts written in any of those encodings might not work, especially in the case where encoded strings appear as identifiers or literals in the script, you can almost avoid using these encodings by setting up the mbstring's transparent encoding filter function for incoming HTTP queries.

Informacja:

It's highly discouraged to use SJIS, BIG5, CP936, CP949 and GB18030 for the internal encoding unless you are familiar with the parser, the scanner and the character encoding.

Informacja:

If you are connecting to a database with PHP, it is recommended that you use the same character encoding for both the database and the internal encoding for ease of use and better performance.

If you are using PostgreSQL, the character encoding used in the database and the one used in PHP may differ as it supports automatic character set conversion between the backend and the frontend.

Function Overloading Feature
Multibyte String Funkcje
Multibyte String


Multibyte String Funkcje

References

Multibyte character encoding schemes and their related issues are fairly complicated, and are beyond the scope of this documentation. Please refer to the following URLs and other resources for further information regarding these topics.

  • Unicode materials

    » http://www.unicode.org/

  • Japanese/Korean/Chinese character information

    » http://examples.oreilly.com/cjkvinfo/doc/cjk.inf

Spis treści

  • mb_check_encoding — Check if the string is valid for the specified encoding
  • mb_convert_case — Perform case folding on a string
  • mb_convert_encoding — Convert character encoding
  • mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
  • mb_convert_variables — Convert character code in variable(s)
  • mb_decode_mimeheader — Decode string in MIME header field
  • mb_decode_numericentity — Decode HTML numeric string reference to character
  • mb_detect_encoding — Detect character encoding
  • mb_detect_order — Set/Get character encoding detection order
  • mb_encode_mimeheader — Encode string for MIME header
  • mb_encode_numericentity — Encode character to HTML numeric string reference
  • mb_encoding_aliases — Get aliases of a known encoding type
  • mb_ereg_match — Regular expression match for multibyte string
  • mb_ereg_replace — Replace regular expression with multibyte support
  • mb_ereg_search_getpos — Returns start point for next regular expression match
  • mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match
  • mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
  • mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
  • mb_ereg_search_regs — Returns the matched part of a multibyte regular expression
  • mb_ereg_search_setpos — Set start point of next regular expression match
  • mb_ereg_search — Multibyte regular expression match for predefined multibyte string
  • mb_ereg — Regular expression match with multibyte support
  • mb_eregi_replace — Replace regular expression with multibyte support ignoring case
  • mb_eregi — Regular expression match ignoring case with multibyte support
  • mb_get_info — Get internal settings of mbstring
  • mb_http_input — Detect HTTP input character encoding
  • mb_http_output — Set/Get HTTP output character encoding
  • mb_internal_encoding — Set/Get internal character encoding
  • mb_language — Set/Get current language
  • mb_list_encodings — Returns an array of all supported encodings
  • mb_output_handler — Callback function converts character encoding in output buffer
  • mb_parse_str — Parse GET/POST/COOKIE data and set global variable
  • mb_preferred_mime_name — Get MIME charset string
  • mb_regex_encoding — Returns current encoding for multibyte regex as string
  • mb_regex_set_options — Set/Get the default options for mbregex functions
  • mb_send_mail — Send encoded mail
  • mb_split — Split multibyte string using regular expression
  • mb_strcut — Get part of string
  • mb_strimwidth — Get truncated string with specified width
  • mb_stripos — Finds position of first occurrence of a string within another, case insensitive
  • mb_stristr — Finds first occurrence of a string within another, case insensitive
  • mb_strlen — Get string length
  • mb_strpos — Find position of first occurrence of string in a string
  • mb_strrchr — Finds the last occurrence of a character in a string within another
  • mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive
  • mb_strripos — Finds position of last occurrence of a string within another, case insensitive
  • mb_strrpos — Find position of last occurrence of a string in a string
  • mb_strstr — Finds first occurrence of a string within another
  • mb_strtolower — Make a string lowercase
  • mb_strtoupper — Make a string uppercase
  • mb_strwidth — Return width of string
  • mb_substitute_character — Set/Get substitution character
  • mb_substr_count — Count the number of substring occurrences
  • mb_substr — Get part of string
PHP Character Encoding Requirements
mb_check_encoding
Multibyte String


Check if the string is valid for the specified encoding

Multibyte String Funkcje
mb_convert_case
Multibyte String Funkcje
PHP Manual

mb_check_encoding

(PHP 4 >= 4.4.3, PHP 5 >= 5.1.3)

mb_check_encoding — Check if the string is valid for the specified encoding

Opis

bool mb_check_encoding ([ string $var = NULL [, string $encoding = mb_internal_encoding() ]] )

Checks if the specified byte stream is valid for the specified encoding. It is useful to prevent so-called "Invalid Encoding Attack".

Parametry

var

The byte stream to check. If it is omitted, this function checks all the input from the beginning of the request.

encoding

The expected encoding.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Multibyte String Funkcje
mb_convert_case
Multibyte String Funkcje


Perform case folding on a string

mb_check_encoding
mb_convert_encoding
Multibyte String Funkcje
PHP Manual

mb_convert_case

(PHP 4 >= 4.3.0, PHP 5)

mb_convert_case — Perform case folding on a string

Opis

string mb_convert_case ( string $str , int $mode = MB_CASE_UPPER [, string $encoding = mb_internal_encoding() ] )

Performs case folding on a string, converted in the way specified by mode.

Parametry

str

The string being converted.

mode

The mode of the conversion. It can be one of MB_CASE_UPPER, MB_CASE_LOWER, or MB_CASE_TITLE.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

A case folded version of string converted in the way specified by mode.

Kodowanie Unicode

By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

Przykłady

Przykład #1 mb_convert_case() example

<?php
$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints Mary Had A Little Lamb And She Loved It So
?>

Przykład #2 mb_convert_case() example with non-Latin UTF-8 text

<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints Τάχιστη Αλώπηξ Βαφήσ Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνόσ
?>

Zobacz też:

  • mb_strtolower() - Make a string lowercase
  • mb_strtoupper() - Make a string uppercase
  • strtolower() - Zmienia wszystkie litery w łańcuchu na małe
  • strtoupper() - Zmienia wszystkie litery w łańcuchu na duże
  • ucfirst() - Make a string's first character uppercase
  • ucwords() - Uppercase the first character of each word in a string

mb_check_encoding
mb_convert_encoding
Multibyte String Funkcje


Convert character encoding

mb_convert_case
mb_convert_kana
Multibyte String Funkcje
PHP Manual

mb_convert_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_encoding — Convert character encoding

Opis

string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding ] )

Converts the character encoding of string str to to_encoding from optionally from_encoding.

Parametry

str

The string being encoded.

to_encoding

The type of encoding that str is being converted to.

from_encoding

Is specified by character code names before conversion. It is either an array, or a comma separated enumerated list. If from_encoding is not specified, the internal encoding will be used.

See supported encodings.

Zwracane wartości

The encoded string.

Przykłady

Przykład #1 mb_convert_encoding() example

<?php
/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");

/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");

/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
?>

Zobacz też:

  • mb_detect_order() - Set/Get character encoding detection order

mb_convert_case
mb_convert_kana
Multibyte String Funkcje


Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

mb_convert_encoding
mb_convert_variables
Multibyte String Funkcje
PHP Manual

mb_convert_kana

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

Opis

string mb_convert_kana ( string $str [, string $option = "KV" [, string $encoding ]] )

Performs a "han-kaku" - "zen-kaku" conversion for string str. This function is only useful for Japanese.

Parametry

str

The string being converted.

option

The conversion option.

Specify with a combination of following options.

Applicable Conversion Options
Option | Meaning
r | Convert "zen-kaku" alphabets to "han-kaku"
R | Convert "han-kaku" alphabets to "zen-kaku"
n | Convert "zen-kaku" numbers to "han-kaku"
N | Convert "han-kaku" numbers to "zen-kaku"
a | Convert "zen-kaku" alphabets and numbers to "han-kaku"
A | Convert "han-kaku" alphabets and numbers to "zen-kaku" (Characters included in "a", "A" options are U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E)
s | Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020)
S | Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000)
k | Convert "zen-kaku kata-kana" to "han-kaku kata-kana"
K | Convert "han-kaku kata-kana" to "zen-kaku kata-kana"
h | Convert "zen-kaku hira-gana" to "han-kaku kata-kana"
H | Convert "han-kaku kata-kana" to "zen-kaku hira-gana"
c | Convert "zen-kaku kata-kana" to "zen-kaku hira-gana"
C | Convert "zen-kaku hira-gana" to "zen-kaku kata-kana"
V | Collapse voiced sound notation and convert them into a character. Use with "K","H"

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

The converted string.

Przykłady

Przykład #1 mb_convert_kana() example

<?php
/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");

/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
   and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");
?>

mb_convert_encoding
mb_convert_variables
Multibyte String Funkcje


Convert character code in variable(s)

mb_convert_kana
mb_decode_mimeheader
Multibyte String Funkcje
PHP Manual

mb_convert_variables

(PHP 4 >= 4.0.6, PHP 5)

mb_convert_variables — Convert character code in variable(s)

Opis

string mb_convert_variables ( string $to_encoding , mixed $from_encoding , mixed &$vars [, mixed &$... ] )

Converts character encoding of variables vars in encoding from_encoding to encoding to_encoding.

mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.

Parametry

to_encoding

The encoding that the string is being converted to.

from_encoding

from_encoding is specified as an array or comma separated string, it tries to detect encoding from from-coding. When from_encoding is omitted, detect_order is used.

vars

vars is the reference to the variable being converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

...

Additional vars.

Zwracane wartości

The character encoding before conversion for success, or FALSE for failure.

Przykłady

Przykład #1 mb_convert_variables() example

<?php
/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
?>

mb_convert_kana
mb_decode_mimeheader
Multibyte String Funkcje


Decode string in MIME header field

mb_convert_variables
mb_decode_numericentity
Multibyte String Funkcje
PHP Manual

mb_decode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_mimeheader — Decode string in MIME header field

Opis

string mb_decode_mimeheader ( string $str )

Decodes encoded-word string str in MIME header.

Parametry

str

The string being decoded.

Zwracane wartości

The decoded string in internal character encoding.

Zobacz też:

  • mb_encode_mimeheader() - Encode string for MIME header

mb_convert_variables
mb_decode_numericentity
Multibyte String Funkcje


Decode HTML numeric string reference to character

mb_decode_mimeheader
mb_detect_encoding
Multibyte String Funkcje
PHP Manual

mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5)

mb_decode_numericentity — Decode HTML numeric string reference to character

Opis

string mb_decode_numericentity ( string $str , array $convmap , string $encoding )

Convert numeric string reference of string str in a specified block to character.

Parametry

str

The string being decoded.

convmap

convmap is an array that specifies the code area to convert.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

The converted string.

Przykłady

Przykład #1 convmap example

<?php
$convmap = array (
   int start_code1, int end_code1, int offset1, int mask1,
   int start_code2, int end_code2, int offset2, int mask2,
   ........
   int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN,
// then convert value to numeric string reference.
?>

Zobacz też:

  • mb_encode_numericentity() - Encode character to HTML numeric string reference

mb_decode_mimeheader
mb_detect_encoding
Multibyte String Funkcje


Detect character encoding

mb_decode_numericentity
mb_detect_order
Multibyte String Funkcje
PHP Manual

mb_detect_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_detect_encoding — Detect character encoding

Opis

string mb_detect_encoding ( string $str [, mixed $encoding_list = mb_detect_order() [, bool $strict = false ]] )

Detects character encoding in string str.

Parametry

str

The string being detected.

encoding_list

encoding_list is list of character encoding. Encoding order may be specified by array or comma separated list string.

If encoding_list is omitted, detect_order is used.

strict

strict specifies whether to use the strict encoding detection or not. Default is FALSE.

Zwracane wartości

The detected character encoding or FALSE if the encoding cannot be detected from the given string.

Przykłady

Przykład #1 mb_detect_encoding() example

<?php
/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded according to mbstring.language */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list  */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);
?>

Zobacz też:

  • mb_detect_order() - Set/Get character encoding detection order

mb_decode_numericentity
mb_detect_order
Multibyte String Funkcje


Set/Get character encoding detection order

mb_detect_encoding
mb_encode_mimeheader
Multibyte String Funkcje
PHP Manual

mb_detect_order

(PHP 4 >= 4.0.6, PHP 5)

mb_detect_order — Set/Get character encoding detection order

Opis

mixed mb_detect_order ([ mixed $encoding_list ] )

Sets the automatic character encoding detection order to encoding_list.

Parametry

encoding_list

encoding_list is an array or comma separated list of character encoding. See supported encodings.

If encoding_list is omitted, it returns the current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

mbstring currently implements the following encoding detection filters. If there is an invalid byte sequence for the following encodings, encoding detection will fail.

UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP

For ISO-8859-*, mbstring always detects as ISO-8859-*.

For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.

Przykład #1 Useless detect order example

; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; Always detect as UTF-8, since ASCII/UTF-7 values are
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #2 mb_detect_order() examples

<?php
/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");

/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);

/* Display current detection order */
echo implode(", ", mb_detect_order());
?>

Zobacz też:

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_input() - Detect HTTP input character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_send_mail() - Send encoded mail

mb_detect_encoding
mb_encode_mimeheader
Multibyte String Funkcje


Encode string for MIME header

mb_detect_order
mb_encode_numericentity
Multibyte String Funkcje
PHP Manual

mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_mimeheader — Encode string for MIME header

Opis

string mb_encode_mimeheader ( string $str [, string $charset [, string $transfer_encoding [, string $linefeed = "\r\n" [, int $indent = 0 ]]]] )

Encodes a given string str by the MIME header encoding scheme.

Parametry

str

The string being encoded.

charset

charset specifies the name of the character set in which str is represented in. The default value is determined by the current NLS setting (mbstring.language). mb_internal_encoding() should be set to same encoding.

transfer_encoding

transfer_encoding specifies the scheme of MIME encoding. It should be either "B" (Base64) or "Q" (Quoted-Printable). Falls back to "B" if not given.

linefeed

linefeed specifies the EOL (end-of-line) marker with which mb_encode_mimeheader() performs line-folding (a » RFC term, the act of breaking a line longer than a certain length into multiple lines. The length is currently hard-coded to 74 characters). Falls back to "\r\n" (CRLF) if not given.

indent

Indentation of the first line (number of characters in the header before str).

Zwracane wartości

A converted version of the string represented in ASCII.

Rejestr zmian

Wersja | Opis
5.0.0 | The indent parameter was added.

Przykłady

Przykład #1 mb_encode_mimeheader() example

<?php
$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " <" . $mbox . "@" . $doma . ">";
echo $addr;
?>

Notatki

Informacja:

This function isn't designed to break lines at higher-level contextual break points (word boundaries, etc.). This behaviour may clutter up the original string with unexpected spaces.

Zobacz też:

  • mb_decode_mimeheader() - Decode string in MIME header field

mb_detect_order
mb_encode_numericentity
Multibyte String Funkcje


Encode character to HTML numeric string reference

mb_encode_mimeheader
mb_encoding_aliases
Multibyte String Funkcje
PHP Manual

mb_encode_numericentity

(PHP 4 >= 4.0.6, PHP 5)

mb_encode_numericentity — Encode character to HTML numeric string reference

Opis

string mb_encode_numericentity ( string $str , array $convmap , string $encoding )

Converts specified character codes in string str from HTML numeric character reference to character code.

Parametry

str

The string being encoded.

convmap

convmap is array specifies code area to convert.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

The converted string.

Przykłady

Przykład #1 convmap example

<?php
$convmap = array (
 int start_code1, int end_code1, int offset1, int mask1,
 int start_code2, int end_code2, int offset2, int mask2,
 ........
 int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.
?>

Przykłady

Przykład #2 mb_encode_numericentity() example

<?php
/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");

/* Convert user defined SJIS-win code in block 95-104 to numeric
   string reference */
$convmap = array(
       0xe000, 0xe03e, 0x1040, 0xffff,
       0xe03f, 0xe0bb, 0x1041, 0xffff,
       0xe0bc, 0xe0fa, 0x1084, 0xffff,
       0xe0fb, 0xe177, 0x1085, 0xffff,
       0xe178, 0xe1b6, 0x10c8, 0xffff,
       0xe1b7, 0xe233, 0x10c9, 0xffff,
       0xe234, 0xe272, 0x110c, 0xffff,
       0xe273, 0xe2ef, 0x110d, 0xffff,
       0xe2f0, 0xe32e, 0x1150, 0xffff,
       0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");
?>

Zobacz też:

  • mb_decode_numericentity() - Decode HTML numeric string reference to character

mb_encode_mimeheader
mb_encoding_aliases
Multibyte String Funkcje


Get aliases of a known encoding type

mb_encode_numericentity
mb_ereg_match
Multibyte String Funkcje
PHP Manual

mb_encoding_aliases

(PHP 5 >= 5.3.0)

mb_encoding_aliases — Get aliases of a known encoding type

Opis

array mb_encoding_aliases ( string $encoding )

Returns an array of aliases for a known encoding type.

Parametry

encoding

The encoding type being checked, for aliases.

Zwracane wartości

Returns a numerically indexed array of encoding aliases on success, lub FALSE w przypadku niepowodzenia

Błędy/Wyjątki

Emits an E_WARNING level error if encoding is unknown.

Przykłady

Przykład #1 mb_encoding_aliases() example

<?php
$encoding        = 'ASCII';
$known_encodings = mb_list_encodings();

if (in_array($encoding, $known_encodings)) {

    $aliases = mb_encoding_aliases($encoding);
    print_r($aliases);

} else {

    echo "Unknown ($encoding) encoding.\n";

}
?>

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

Array
(
    [0] => ANSI_X3.4-1968
    [1] => iso-ir-6
    [2] => ANSI_X3.4-1986
    [3] => ISO_646.irv:1991
    [4] => US-ASCII
    [5] => ISO646-US
    [6] => us
    [7] => IBM367
    [8] => cp367
    [9] => csASCII
)

Zobacz też:

  • mb_list_encodings() - Returns an array of all supported encodings

mb_encode_numericentity
mb_ereg_match
Multibyte String Funkcje


Regular expression match for multibyte string

mb_encoding_aliases
mb_ereg_replace
Multibyte String Funkcje
PHP Manual

mb_ereg_match

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_match — Regular expression match for multibyte string

Opis

bool mb_ereg_match ( string $pattern , string $string [, string $option = "msr" ] )

A regular expression match for a multibyte string

Parametry

pattern

The regular expression pattern.

string

The string being evaluated.

option

Zwracane wartości

Returns TRUE if string matches the regular expression pattern, FALSE if not.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

mb_encoding_aliases
mb_ereg_replace
Multibyte String Funkcje


Replace regular expression with multibyte support

mb_ereg_match
mb_ereg_search_getpos
Multibyte String Funkcje
PHP Manual

mb_ereg_replace

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_replace — Replace regular expression with multibyte support

Opis

string mb_ereg_replace ( string $pattern , string $replacement , string $string [, string $option = "msr" ] )

Scans string for matches to pattern, then replaces the matched text with replacement

Parametry

pattern

The regular expression pattern.

Multibyte characters may be used in pattern.

replacement

The replacement text.

string

The string being checked.

option
Matching condition can be set by option parameter. If i is specified for this parameter, the case will be ignored. If x is specified, white space will be ignored. If m is specified, match will be executed in multiline mode and line break will be included in '.'. If p is specified, match will be executed in POSIX mode, line break will be considered as normal character. If e is specified, replacement string will be evaluated as PHP expression.

Zwracane wartości

The resultant string on success, or FALSE on error.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Ostrzeżenie

Nigdy nie należy używać modyfikatora e na niesprawdzonych danych wejściowych. Znaki unikowe nie są dodawane automatycznie (podobnie jak w preg_replace()). Nie zwracanie uwagi na to często powoduje, że aplikacje są podatne na zdalne wywoływania szkodliwego kodu.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_eregi_replace() - Replace regular expression with multibyte support ignoring case

mb_ereg_match
mb_ereg_search_getpos
Multibyte String Funkcje


Returns start point for next regular expression match

mb_ereg_replace
mb_ereg_search_getregs
Multibyte String Funkcje
PHP Manual

mb_ereg_search_getpos

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_getpos — Returns start point for next regular expression match

Opis

int mb_ereg_search_getpos ( void )

Returns the start point for the next regular expression match.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

mb_ereg_search_getpos() returns
the point to start regular expression match for
mb_ereg_search(),
mb_ereg_search_pos(),
mb_ereg_search_regs(). The position is
represented by bytes from the head of string.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_setpos() - Set start point of next regular expression match

mb_ereg_replace
mb_ereg_search_getregs
Multibyte String Funkcje


Retrieve the result from the last multibyte regular expression match

mb_ereg_search_getpos
mb_ereg_search_init
Multibyte String Funkcje
PHP Manual

mb_ereg_search_getregs

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match

Opis

array mb_ereg_search_getregs ( void )

Retrieve the result from the last multibyte regular expression match

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some matches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns FALSE on error;

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_getpos
mb_ereg_search_init
Multibyte String Funkcje


Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_getregs
mb_ereg_search_pos
Multibyte String Funkcje
PHP Manual

mb_ereg_search_init

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match

Opis

bool mb_ereg_search_init ( string $string [, string $pattern [, string $option = "msr" ]] )

mb_ereg_search_init() sets
string and pattern
for a multibyte regular expression. These values are used for
mb_ereg_search(),
mb_ereg_search_pos(), and
mb_ereg_search_regs().

Parametry

string

The search string.

pattern

The search pattern.

option

The search option.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_regs() - Returns the matched part of a multibyte regular expression

mb_ereg_search_getregs
mb_ereg_search_pos
Multibyte String Funkcje


Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

mb_ereg_search_init
mb_ereg_search_regs
Multibyte String Funkcje
PHP Manual

mb_ereg_search_pos

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

Opis

array mb_ereg_search_pos ([ string $pattern [, string $option = "ms" ]] )

Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

The string for match is specified by mb_ereg_search_init(). If it is not specified, the previous one will be used.

Parametry

pattern

The search pattern.

option

The search option.

Zwracane wartości

An array including the position of a matched part for a multibyte regular expression. The first element of the array will be the beginning of matched part, the second element will be length (bytes) of matched part. It returns FALSE on error.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_init
mb_ereg_search_regs
Multibyte String Funkcje


Returns the matched part of a multibyte regular expression

mb_ereg_search_pos
mb_ereg_search_setpos
Multibyte String Funkcje
PHP Manual

mb_ereg_search_regs

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_regs — Returns the matched part of a multibyte regular expression

Opis

array mb_ereg_search_regs ([ string $pattern [, string $option = "ms" ]] )

Returns the matched part of a multibyte regular expression.

Parametry

pattern

The search pattern.

option

The search option.

Zwracane wartości

mb_ereg_search_regs() executes the multibyte regular expression match, and if there are some matched part, it returns an array including substring of matched part as first element, the first grouped part with brackets as second element, the second grouped part as third element, and so on. It returns FALSE on error.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_pos
mb_ereg_search_setpos
Multibyte String Funkcje


Set start point of next regular expression match

mb_ereg_search_regs
mb_ereg_search
Multibyte String Funkcje
PHP Manual

mb_ereg_search_setpos

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search_setpos — Set start point of next regular expression match

Opis

bool mb_ereg_search_setpos ( int $position )

mb_ereg_search_setpos() sets the starting point of a match for mb_ereg_search().

Parametry

position

The position to set.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_regs
mb_ereg_search
Multibyte String Funkcje


Multibyte regular expression match for predefined multibyte string

mb_ereg_search_setpos
mb_ereg
Multibyte String Funkcje
PHP Manual

mb_ereg_search

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg_search — Multibyte regular expression match for predefined multibyte string

Opis

bool mb_ereg_search ([ string $pattern [, string $option = "ms" ]] )

Performs a multibyte regular expression match for a predefined multibyte string.

Parametry

pattern

The search pattern.

option

The search option.

Zwracane wartości

mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, or FALSE otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_setpos
mb_ereg
Multibyte String Funkcje


Regular expression match with multibyte support

mb_ereg_search
mb_eregi_replace
Multibyte String Funkcje
PHP Manual

mb_ereg

(PHP 4 >= 4.2.0, PHP 5)

mb_ereg — Regular expression match with multibyte support

Opis

int mb_ereg ( string $pattern , string $string [, array $regs ] )

Executes the regular expression match with multibyte support.

Parametry

pattern

The search pattern.

string

The search string.

regs

Contains a substring of the matched string.

Zwracane wartości

Executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional regs parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The function returns 1 if it matches with the empty string. If no matches are found or an error happens, FALSE will be returned.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_eregi() - Regular expression match ignoring case with multibyte support

mb_ereg_search
mb_eregi_replace
Multibyte String Funkcje


Replace regular expression with multibyte support ignoring case

mb_ereg
mb_eregi
Multibyte String Funkcje
PHP Manual

mb_eregi_replace

(PHP 4 >= 4.2.0, PHP 5)

mb_eregi_replace — Replace regular expression with multibyte support ignoring case

Opis

string mb_eregi_replace ( string $pattern , string $replace , string $string [, string $option = "msri" ] )

Scans string for matches to pattern, then replaces the matched text with replacement.

Parametry

pattern

The regular expression pattern. Multibyte characters may be used. The case will be ignored.

replace

The replacement text.

string

The searched string.

option
option has the same meaning as in mb_ereg_replace().

Zwracane wartości

The resultant string or FALSE on error.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Ostrzeżenie

Nigdy nie należy używać modyfikatora e na niesprawdzonych danych wejściowych. Znaki unikowe nie są dodawane automatycznie (podobnie jak w preg_replace()). Nie zwracanie uwagi na to często powoduje, że aplikacje są podatne na zdalne wywoływania szkodliwego kodu.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg_replace() - Replace regular expression with multibyte support

mb_ereg
mb_eregi
Multibyte String Funkcje


Regular expression match ignoring case with multibyte support

mb_eregi_replace
mb_get_info
Multibyte String Funkcje
PHP Manual

mb_eregi

(PHP 4 >= 4.2.0, PHP 5)

mb_eregi — Regular expression match ignoring case with multibyte support

Opis

int mb_eregi ( string $pattern , string $string [, array $regs ] )

Executes the case insensitive regular expression match with multibyte support.

Parametry

pattern

The regular expression pattern.

string

The string being searched.

regs

Contains a substring of the matched string.

Zwracane wartości

Executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional regs parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The function returns 1 if it matches with the empty string. If no matches are found or an error happens, FALSE will be returned.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

mb_eregi_replace
mb_get_info
Multibyte String Funkcje


Get internal settings of mbstring

mb_eregi
mb_http_input
Multibyte String Funkcje
PHP Manual

mb_get_info

(PHP 4 >= 4.2.0, PHP 5)

mb_get_info — Get internal settings of mbstring

Opis

mixed mb_get_info ([ string $type = "all" ] )

mb_get_info() returns the internal setting parameters of mbstring.

Parametry

type

If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload", "mail_charset", "mail_header_encoding", "mail_body_encoding" will be returned.

If type is specified as "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

Zwracane wartości

An array of type information if type is not specified, otherwise a specific type.

Rejestr zmian

Wersja | Opis
5.1.3 | The entries "mail_charset", "mail_header_encoding", and "mail_body_encoding" were made available.
5.3.0 | The entry "http_output_conv_mimetypes" was made available.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_http_output() - Set/Get HTTP output character encoding

mb_eregi
mb_http_input
Multibyte String Funkcje


Detect HTTP input character encoding

mb_get_info
mb_http_output
Multibyte String Funkcje
PHP Manual

mb_http_input

(PHP 4 >= 4.0.6, PHP 5)

mb_http_input — Detect HTTP input character encoding

Opis

mixed mb_http_input ([ string $type = "" ] )

Detects the HTTP input character encoding.

Parametry

type

Input string specifies the input type. "G" for GET, "P" for POST, "C" for COOKIE, "S" for string, "L" for list, and "I" for the whole list (will return array). If type is omitted, it returns the last input type processed.

Zwracane wartości

The character encoding name, as per the type. If mb_http_input() does not process specified HTTP input, it returns FALSE.

Zobacz też:

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_detect_order() - Set/Get character encoding detection order

mb_get_info
mb_http_output
Multibyte String Funkcje


Set/Get HTTP output character encoding

mb_http_input
mb_internal_encoding
Multibyte String Funkcje
PHP Manual

mb_http_output

(PHP 4 >= 4.0.6, PHP 5)

mb_http_output — Set/Get HTTP output character encoding

Opis

mixed mb_http_output ([ string $encoding ] )

Set/Get the HTTP output character encoding. Output after this function is converted to encoding.

Parametry

encoding

If encoding is set, mb_http_output() sets the HTTP output character encoding to encoding.

If encoding is omitted, mb_http_output() returns the current HTTP output character encoding.

Zwracane wartości

If encoding is omitted, mb_http_output() returns the current HTTP output character encoding. Otherwise, Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_http_input() - Detect HTTP input character encoding
  • mb_detect_order() - Set/Get character encoding detection order

mb_http_input
mb_internal_encoding
Multibyte String Funkcje


Set/Get internal character encoding

mb_http_output
mb_language
Multibyte String Funkcje
PHP Manual

mb_internal_encoding

(PHP 4 >= 4.0.6, PHP 5)

mb_internal_encoding — Set/Get internal character encoding

Opis

mixed mb_internal_encoding ([ string $encoding = mb_internal_encoding() ] )

Set/Get the internal character encoding

Parametry

encoding

encoding is the character encoding name used for the HTTP input character encoding conversion, HTTP output character encoding conversion, and the default character encoding for string functions defined by the mbstring module.

Zwracane wartości

If encoding is set, then Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If encoding is omitted, then the current character encoding name is returned.

Przykłady

Przykład #1 mb_internal_encoding() example

<?php
/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");

/* Display current internal character encoding */
echo mb_internal_encoding();
?>

Zobacz też:

  • mb_http_input() - Detect HTTP input character encoding
  • mb_http_output() - Set/Get HTTP output character encoding
  • mb_detect_order() - Set/Get character encoding detection order

mb_http_output
mb_language
Multibyte String Funkcje


Set/Get current language

mb_internal_encoding
mb_list_encodings
Multibyte String Funkcje
PHP Manual

mb_language

(PHP 4 >= 4.0.6, PHP 5)

mb_language — Set/Get current language

Opis

mixed mb_language ([ string $language ] )

Set/Get the current language.

Parametry

language

Used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.

Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.

Zwracane wartości

If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns the language name as a string. If no language is set previously, it then returns FALSE.

Zobacz też:

  • mb_send_mail() - Send encoded mail

mb_internal_encoding
mb_list_encodings
Multibyte String Funkcje


Returns an array of all supported encodings

mb_language
mb_output_handler
Multibyte String Funkcje
PHP Manual

mb_list_encodings

(PHP 5)

mb_list_encodings — Returns an array of all supported encodings

Opis

array mb_list_encodings ( void )

Returns an array containing all supported encodings.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a numerically indexed array.

Błędy/Wyjątki

This function does not emit any errors.

Przykłady

Przykład #1 mb_list_encodings() example

<?php

print_r(mb_list_encodings());

?>

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

Array
(
    [0] => pass
    [1] => auto
    [2] => wchar
    [3] => byte2be
    [4] => byte2le
    [5] => byte4be
    [6] => byte4le
    [7] => BASE64
    [8] => UUENCODE
    [9] => HTML-ENTITIES
    [10] => Quoted-Printable
    [11] => 7bit
    [12] => 8bit
    [13] => UCS-4
    [14] => UCS-4BE
    [15] => UCS-4LE
    [16] => UCS-2
    [17] => UCS-2BE
    [18] => UCS-2LE
    [19] => UTF-32
    [20] => UTF-32BE
    [21] => UTF-32LE
    [22] => UTF-16
    [23] => UTF-16BE
    [24] => UTF-16LE
    [25] => UTF-8
    [26] => UTF-7
    [27] => UTF7-IMAP
    [28] => ASCII
    [29] => EUC-JP
    [30] => SJIS
    [31] => eucJP-win
    [32] => SJIS-win
    [33] => JIS
    [34] => ISO-2022-JP
    [35] => Windows-1252
    [36] => ISO-8859-1
    [37] => ISO-8859-2
    [38] => ISO-8859-3
    [39] => ISO-8859-4
    [40] => ISO-8859-5
    [41] => ISO-8859-6
    [42] => ISO-8859-7
    [43] => ISO-8859-8
    [44] => ISO-8859-9
    [45] => ISO-8859-10
    [46] => ISO-8859-13
    [47] => ISO-8859-14
    [48] => ISO-8859-15
    [49] => EUC-CN
    [50] => CP936
    [51] => HZ
    [52] => EUC-TW
    [53] => BIG-5
    [54] => EUC-KR
    [55] => UHC
    [56] => ISO-2022-KR
    [57] => Windows-1251
    [58] => CP866
    [59] => KOI8-R
)

mb_language
mb_output_handler
Multibyte String Funkcje


Callback function converts character encoding in output buffer

mb_list_encodings
mb_parse_str
Multibyte String Funkcje
PHP Manual

mb_output_handler

(PHP 4 >= 4.0.6, PHP 5)

mb_output_handler — Callback function converts character encoding in output buffer

Opis

string mb_output_handler ( string $contents , int $status )

mb_output_handler() is
ob_start() callback
function. mb_output_handler() converts
characters in the output buffer from internal character encoding to
HTTP output character encoding.

Parametry

contents

The contents of the output buffer.

status

The status of the output buffer.

Zwracane wartości

The converted string.

Rejestr zmian

Wersja Opis
4.1.0

This handler now adds the charset HTTP header when the following conditions are met:

  • Does not set Content-Type, using header().
  • The default MIME type begins with text/.
  • The mbstring.http_input setting is something other than pass.

Przykłady

Przykład #1 mb_output_handler() example

<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>

Notatki

Informacja:

If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.

Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.

If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().

Zobacz też:

  • ob_start() - Turn on output buffering

mb_list_encodings
mb_parse_str
Multibyte String Funkcje


Parse GET/POST/COOKIE data and set global variable

mb_output_handler
mb_preferred_mime_name
Multibyte String Funkcje
PHP Manual

mb_parse_str

(PHP 4 >= 4.0.6, PHP 5)

mb_parse_str — Parse GET/POST/COOKIE data and set global variable

Opis

bool mb_parse_str ( string $encoded_string [, array &$result ] )

Parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only be used for GET data for now. It parses URL encoded data, detects encoding, converts coding to internal encoding and set values to the result array or global variables.

Parametry

encoded_string

The URL encoded data.

result

An array containing decoded and character encoded converted values.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mb_detect_order() - Set/Get character encoding detection order
  • mb_internal_encoding() - Set/Get internal character encoding

mb_output_handler
mb_preferred_mime_name
Multibyte String Funkcje


Get MIME charset string

mb_parse_str
mb_regex_encoding
Multibyte String Funkcje
PHP Manual

mb_preferred_mime_name

(PHP 4 >= 4.0.6, PHP 5)

mb_preferred_mime_name — Get MIME charset string

Opis

string mb_preferred_mime_name ( string $encoding )

Get a MIME charset string for a specific encoding.

Parametry

encoding

The encoding being checked.

Zwracane wartości

The MIME charset string for character encoding encoding.

Przykłady

Przykład #1 mb_preferred_mime_name() example

<?php
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
?>

mb_parse_str
mb_regex_encoding
Multibyte String Funkcje


Returns current encoding for multibyte regex as string

mb_preferred_mime_name
mb_regex_set_options
Multibyte String Funkcje
PHP Manual

mb_regex_encoding

(PHP 4 >= 4.2.0, PHP 5)

mb_regex_encoding — Returns current encoding for multibyte regex as string

Opis

mixed mb_regex_encoding ([ string $encoding ] )

Returns the current encoding for a multibyte regex as a string.

Parametry

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

Returns the character encoding used by multibyte regex functions.

Zobacz też:

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_ereg() - Regular expression match with multibyte support

mb_preferred_mime_name
mb_regex_set_options
Multibyte String Funkcje


Set/Get the default options for mbregex functions

mb_regex_encoding
mb_send_mail
Multibyte String Funkcje
PHP Manual

mb_regex_set_options

(PHP 4 >= 4.3.0, PHP 5)

mb_regex_set_options — Set/Get the default options for mbregex functions

Opis

string mb_regex_set_options ([ string $options = "msr" ] )

Sets the default options described by options for multibyte regex functions.

Parametry

options

The options to set. This is a a string where each character is an option. To set a mode, the mode character must be the last one set, however there can only be set one mode but multiple options.

Regex options
Option | Meaning
i | Ambiguity match on
x | Enables extended pattern form
m | '.' matches with newlines
s | '^' -> '\A', '$' -> '\Z'
p | Same as both the m and s options
l | Finds longest matches
n | Ignores empty matches
e | eval() resulting code
Regex syntax modes
Mode | Meaning
j | Java (Sun java.util.regex)
u | GNU regex
g | grep
c | Emacs
r | Ruby
z | Perl
b | POSIX Basic regex
d | POSIX Extended regex

Zwracane wartości

The previous options. If options is omitted, it returns the string that describes the current options.

Zobacz też:

  • mb_split() - Split multibyte string using regular expression
  • mb_ereg() - Regular expression match with multibyte support
  • mb_eregi() - Regular expression match ignoring case with multibyte support

mb_regex_encoding
mb_send_mail
Multibyte String Funkcje


Send encoded mail

mb_regex_set_options
mb_split
Multibyte String Funkcje
PHP Manual

mb_send_mail

(PHP 4 >= 4.0.6, PHP 5)

mb_send_mail — Send encoded mail

Opis

bool mb_send_mail ( string $to , string $subject , string $message [, string $additional_headers = NULL [, string $additional_parameter = NULL ]] )

Sends email. Headers and messages are converted and encoded according to the mb_language() setting. It's a wrapper function for mail(), so see also mail() for details.

Parametry

to

The mail addresses being sent to. Multiple recipients may be specified by putting a comma between each address in to. This parameter is not automatically encoded.

subject

The subject of the mail.

message

The message of the mail.

additional_headers

additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").

additional_parameter

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.0.0 | The Content-Type and Content-Transfer-Encoding headers may be redefined as of PHP 5.0.0. Before this time, the values defined by mb_language() are always used.

Zobacz też:

  • mail() - Wysyłanie poczty elektronicznej
  • mb_encode_mimeheader() - Encode string for MIME header
  • mb_language() - Set/Get current language

mb_regex_set_options
mb_split
Multibyte String Funkcje


Split multibyte string using regular expression

mb_send_mail
mb_strcut
Multibyte String Funkcje
PHP Manual

mb_split

(PHP 4 >= 4.2.0, PHP 5)

mb_split — Split multibyte string using regular expression

Opis

array mb_split ( string $pattern , string $string [, int $limit = -1 ] )

Split a multibyte string using regular expression pattern and returns the result as an array.

Parametry

pattern

The regular expression pattern.

string

The string being split.

limit
If optional parameter limit is specified, it will be split in limit elements as maximum.

Zwracane wartości

The result as an array.

Notatki

Informacja:

Wewnętrzne kodowanie lub kodowanie znaków określone przez mb_regex_encoding() zostanie użyte jako kodowanie znaków dla tej funkcji.

Zobacz też:

  • mb_regex_encoding() - Returns current encoding for multibyte regex as string
  • mb_ereg() - Regular expression match with multibyte support

mb_send_mail
mb_strcut
Multibyte String Funkcje


Get part of string

mb_split
mb_strimwidth
Multibyte String Funkcje
PHP Manual

mb_strcut

(PHP 4 >= 4.0.6, PHP 5)

mb_strcut — Get part of string

Opis

string mb_strcut ( string $str , int $start [, int $length [, string $encoding ]] )

mb_strcut() extracts a substring from a string similarly to mb_substr(), but operates on bytes instead of characters. If the cut position happens to be between two bytes of a multi-byte character, the cut is performed starting from the first byte of that character. This is also the difference to the substr() function, which would simply cut the string between the bytes and thus result in a malformed byte sequence.

Parametry

str

The string being cut.

start

Starting position in bytes.

length

Length in bytes.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

mb_strcut() returns the portion of str specified by the start and length parameters.

Zobacz też:

  • mb_substr() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_split
mb_strimwidth
Multibyte String Funkcje


Get truncated string with specified width

mb_strcut
mb_stripos
Multibyte String Funkcje
PHP Manual

mb_strimwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strimwidth — Get truncated string with specified width

Opis

string mb_strimwidth ( string $str , int $start , int $width [, string $trimmarker [, string $encoding ]] )

Truncates string str to specified width.

Parametry

str

The string being decoded.

start

The start position offset. Number of characters from the beginning of string. (First character is 0)

width

The width of the desired trim.

trimmarker

A string that is added to the end of string when string is truncated.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

The truncated string. If trimmarker is set, trimmarker is appended to the return value.

Przykłady

Przykład #1 mb_strimwidth() example

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
// outputs Hello W...
?>

Zobacz też:

  • mb_strwidth() - Return width of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_strcut
mb_stripos
Multibyte String Funkcje


Finds position of first occurrence of a string within another, case insensitive

mb_strimwidth
mb_stristr
Multibyte String Funkcje
PHP Manual

mb_stripos

(PHP 5 >= 5.2.0)

mb_stripos — Finds position of first occurrence of a string within another, case insensitive

Opis

int mb_stripos ( string $haystack , string $needle [, int $offset [, string $encoding ]] )

mb_stripos() returns the numeric position of the first occurrence of needle in the haystack string. Unlike mb_strpos(), mb_stripos() is case-insensitive. If needle is not found, it returns FALSE.

Parametry

haystack

The string from which to get the position of the first occurrence of needle

needle

The string to find in haystack

offset

The position in haystack to start searching

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Zwracane wartości

Return the numeric position of the first occurrence of needle in the haystack string, or FALSE if needle is not found.

Zobacz też:

  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strpos() - Find the position of the first occurrence of a substring in a string
  • mb_strpos() - Find position of first occurrence of string in a string

mb_strimwidth
mb_stristr
Multibyte String Funkcje


Finds first occurrence of a string within another, case insensitive

mb_stripos
mb_strlen
Multibyte String Funkcje
PHP Manual

mb_stristr

(PHP 5 >= 5.2.0)

mb_stristr — Finds first occurrence of a string within another, case insensitive

Opis

string mb_stristr ( string $haystack , string $needle [, bool $part = false [, string $encoding ]] )

mb_stristr() finds the first occurrence of needle in haystack and returns the portion of haystack. Unlike mb_strstr(), mb_stristr() is case-insensitive. If needle is not found, it returns FALSE.

Parametry

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle. If set to FALSE, it returns all of haystack from the first occurrence of needle to the end,

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Zwracane wartości

Returns the portion of haystack, or FALSE if needle is not found.

Zobacz też:

  • stristr() - Case-insensitive strstr
  • strstr() - Find the first occurrence of a string
  • mb_strstr() - Finds first occurrence of a string within another

mb_stripos
mb_strlen
Multibyte String Funkcje


Get string length

mb_stristr
mb_strpos
Multibyte String Funkcje
PHP Manual

mb_strlen

(PHP 4 >= 4.0.6, PHP 5)

mb_strlen — Get string length

Opis

int mb_strlen ( string $str [, string $encoding ] )

Gets the length of a string.

Parametry

str

The string being checked for length.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

Returns the number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

Zobacz też:

  • mb_internal_encoding() - Set/Get internal character encoding
  • strlen() - Get string length

mb_stristr
mb_strpos
Multibyte String Funkcje


Find position of first occurrence of string in a string

mb_strlen
mb_strrchr
Multibyte String Funkcje
PHP Manual

mb_strpos

(PHP 4 >= 4.0.6, PHP 5)

mb_strpos — Find position of first occurrence of string in a string

Opis

int mb_strpos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding ]] )

Finds position of the first occurrence of a string in a string.

Performs a multi-byte safe strpos() operation based on number of characters. The first character's position is 0, the second character position is 1, and so on.

Parametry

haystack

The string being checked.

needle

The string to find in haystack. In contrast with strpos(), numeric values are not applied as the ordinal value of a character.

offset

The search offset. If it is not specified, 0 is used.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

Returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

Zobacz też:

  • mb_internal_encoding() - Set/Get internal character encoding
  • strpos() - Find the position of the first occurrence of a substring in a string

mb_strlen
mb_strrchr
Multibyte String Funkcje


Finds the last occurrence of a character in a string within another

mb_strpos
mb_strrichr
Multibyte String Funkcje
PHP Manual

mb_strrchr

(PHP 5 >= 5.2.0)

mb_strrchr — Finds the last occurrence of a character in a string within another

Opis

string mb_strrchr ( string $haystack , string $needle [, bool $part = false [, string $encoding ]] )

mb_strrchr() finds the last occurrence of needle in haystack and returns the portion of haystack. If needle is not found, it returns FALSE.

Parametry

haystack

The string from which to get the last occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the last occurrence of needle. If set to FALSE, it returns all of haystack from the last occurrence of needle to the end,

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Zwracane wartości

Returns the portion of haystack. or FALSE if needle is not found.

Zobacz też:

  • strrchr() - Znajduje ostatnie występowanie znaku w łańcuchu znaków
  • mb_strstr() - Finds first occurrence of a string within another
  • mb_strrichr() - Finds the last occurrence of a character in a string within another, case insensitive

mb_strpos
mb_strrichr
Multibyte String Funkcje


Finds the last occurrence of a character in a string within another, case insensitive

mb_strrchr
mb_strripos
Multibyte String Funkcje
PHP Manual

mb_strrichr

(PHP 5 >= 5.2.0)

mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive

Opis

string mb_strrichr ( string $haystack , string $needle [, bool $part = false [, string $encoding ]] )

mb_strrichr() finds the last occurrence of needle in haystack and returns the portion of haystack. Unlike mb_strrchr(), mb_strrichr() is case-insensitive. If needle is not found, it returns FALSE.

Parametry

haystack

The string from which to get the last occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the last occurrence of needle. If set to FALSE, it returns all of haystack from the last occurrence of needle to the end,

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Zwracane wartości

Returns the portion of haystack. or FALSE if needle is not found.

Zobacz też:

  • mb_stristr() - Finds first occurrence of a string within another, case insensitive
  • mb_strrchr() - Finds the last occurrence of a character in a string within another

mb_strrchr
mb_strripos
Multibyte String Funkcje


Finds position of last occurrence of a string within another, case insensitive

mb_strrichr
mb_strrpos
Multibyte String Funkcje
PHP Manual

mb_strripos

(PHP 5 >= 5.2.0)

mb_strripos — Finds position of last occurrence of a string within another, case insensitive

Opis

int mb_strripos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding ]] )

mb_strripos() performs multi-byte safe strripos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1. Unlike mb_strrpos(), mb_strripos() is case-insensitive.

Parametry

haystack

The string from which to get the position of the last occurrence of needle

needle

The string to find in haystack

offset

The position in haystack to start searching

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Zwracane wartości

Return the numeric position of the last occurrence of needle in the haystack string, or FALSE if needle is not found.

Zobacz też:

  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strrpos() - Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków
  • mb_strrpos() - Find position of last occurrence of a string in a string

mb_strrichr
mb_strrpos
Multibyte String Funkcje


Find position of last occurrence of a string in a string

mb_strripos
mb_strstr
Multibyte String Funkcje
PHP Manual

mb_strrpos

(PHP 4 >= 4.0.6, PHP 5)

mb_strrpos — Find position of last occurrence of a string in a string

Opis

int mb_strrpos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding ]] )

Performs a multibyte safe strrpos() operation based on the number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.

Parametry

haystack

The string being checked, for the last occurrence of needle

needle

The string to find in haystack.

offset
May be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string.
encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

Returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

Rejestr zmian

Wersja | Opis
5.2.0 | Added the optional parameter offset.

Notatki

Informacja: The encoding parameter was moved from the third position to the fourth in PHP 5.2.0. For backward compatibility, encoding can be specified as the third parameter, but doing so is deprecated and will be removed in the future.

Zobacz też:

  • mb_strpos() - Find position of first occurrence of string in a string
  • mb_internal_encoding() - Set/Get internal character encoding
  • strrpos() - Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków

mb_strripos
mb_strstr
Multibyte String Funkcje


Finds first occurrence of a string within another

mb_strrpos
mb_strtolower
Multibyte String Funkcje
PHP Manual

mb_strstr

(PHP 5 >= 5.2.0)

mb_strstr — Finds first occurrence of a string within another

Opis

string mb_strstr ( string $haystack , string $needle [, bool $part = false [, string $encoding ]] )

mb_strstr() finds the first occurrence of needle in haystack and returns the portion of haystack. If needle is not found, it returns FALSE.

Parametry

haystack

The string from which to get the first occurrence of needle

needle

The string to find in haystack

part

Determines which portion of haystack this function returns. If set to TRUE, it returns all of haystack from the beginning to the first occurrence of needle. If set to FALSE, it returns all of haystack from the first occurrence of needle to the end,

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Zwracane wartości

Returns the portion of haystack, or FALSE if needle is not found.

Zobacz też:

  • stristr() - Case-insensitive strstr
  • strstr() - Find the first occurrence of a string
  • mb_stristr() - Finds first occurrence of a string within another, case insensitive

mb_strrpos
mb_strtolower
Multibyte String Funkcje


Make a string lowercase

mb_strstr
mb_strtoupper
Multibyte String Funkcje
PHP Manual

mb_strtolower

(PHP 4 >= 4.3.0, PHP 5)

mb_strtolower — Make a string lowercase

Opis

string mb_strtolower ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns str with all alphabetic characters converted to lowercase.

Parametry

str

The string being lowercased.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

str with all alphabetic characters converted to lowercase.

Kodowanie Unicode

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

Przykłady

Przykład #1 mb_strtolower() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>

Przykład #2 mb_strtolower() example with non-Latin UTF-8 text

<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtolower($str, 'UTF-8');
echo $str; // Prints τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός
?>

Zobacz też:

  • mb_strtoupper() - Make a string uppercase
  • mb_convert_case() - Perform case folding on a string
  • strtolower() - Zmienia wszystkie litery w łańcuchu na małe

mb_strstr
mb_strtoupper
Multibyte String Funkcje


Make a string uppercase

mb_strtolower
mb_strwidth
Multibyte String Funkcje
PHP Manual

mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5)

mb_strtoupper — Make a string uppercase

Opis

string mb_strtoupper ( string $str [, string $encoding = mb_internal_encoding() ] )

Returns str with all alphabetic characters converted to uppercase.

Parametry

str

The string being uppercased.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

str with all alphabetic characters converted to uppercase.

Kodowanie Unicode

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).

Przykłady

Przykład #1 mb_strtoupper() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

Przykład #2 mb_strtoupper() example with non-Latin UTF-8 text

<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtoupper($str, 'UTF-8');
echo $str; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
?>

Zobacz też:

  • mb_strtolower() - Make a string lowercase
  • mb_convert_case() - Perform case folding on a string
  • strtoupper() - Zmienia wszystkie litery w łańcuchu na duże

mb_strtolower
mb_strwidth
Multibyte String Funkcje


Return width of string

mb_strtoupper
mb_substitute_character
Multibyte String Funkcje
PHP Manual

mb_strwidth

(PHP 4 >= 4.0.6, PHP 5)

mb_strwidth — Return width of string

Opis

int mb_strwidth ( string $str [, string $encoding ] )

Returns the width of string str.

Multi-byte characters are usually twice the width of single byte characters.

Characters width
Chars | Width
U+0000 - U+0019 | 0
U+0020 - U+1FFF | 1
U+2000 - U+FF60 | 2
U+FF61 - U+FF9F | 1
U+FFA0 - | 2

Parametry

str

The string being decoded.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

The width of string str.

Zobacz też:

  • mb_strimwidth() - Get truncated string with specified width
  • mb_internal_encoding() - Set/Get internal character encoding

mb_strtoupper
mb_substitute_character
Multibyte String Funkcje


Set/Get substitution character

mb_strwidth
mb_substr_count
Multibyte String Funkcje
PHP Manual

mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5)

mb_substitute_character — Set/Get substitution character

Opis

mixed mb_substitute_character ([ mixed $substrchar ] )

Specifies a substitution character when input character encoding is invalid or character code does not exist in output character encoding. Invalid characters may be substituted NULL (no output), string or integer value (Unicode character code value).

This setting affects mb_convert_encoding(),
mb_convert_variables(),
mb_output_handler(),
and mb_send_mail().

Parametry

substrchar

Specify the Unicode value as an integer, or as one of the following strings:

  • "none" : no output
  • "long" : Output character code value (Example: U+3000, JIS+7E7E)
  • "entity" : Output character entity (Example: Ȁ)

Zwracane wartości

If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns the Unicode value, or "none" or "long".

Przykłady

Przykład #1 mb_substitute_character() example

<?php
/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);

/* Set hex format */
mb_substitute_character("long");

/* Display current setting */
echo mb_substitute_character();
?>

mb_strwidth
mb_substr_count
Multibyte String Funkcje


Count the number of substring occurrences

mb_substitute_character
mb_substr
Multibyte String Funkcje
PHP Manual

mb_substr_count

(PHP 4 >= 4.3.0, PHP 5)

mb_substr_count — Count the number of substring occurrences

Opis

int mb_substr_count ( string $haystack , string $needle [, string $encoding ] )

Counts the number of times the needle substring occurs in the haystack string.

Parametry

haystack

The string being checked.

needle

The string being found.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

The number of times the needle substring occurs in the haystack string.

Przykłady

Przykład #1 mb_substr_count() example

<?php
echo mb_substr_count("This is a test", "is"); // prints out 2
?>

Zobacz też:

  • mb_strpos() - Find position of first occurrence of string in a string
  • mb_substr() - Get part of string
  • substr_count() - Count the number of substring occurrences

mb_substitute_character
mb_substr
Multibyte String Funkcje


Get part of string

mb_substr_count
Pspell
Multibyte String Funkcje
PHP Manual

mb_substr

(PHP 4 >= 4.0.6, PHP 5)

mb_substr — Get part of string

Opis

string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )

Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.

Parametry

str

The string to extract the substring from.

start

Position of first character to use from str.

length

Maximum number of characters to use from str.

encoding

Parametr encoding określa kodowanie znaków. Jeśli nie jest podany, to zostanie użyta wewnętrzna wartość kodowania zanków.

Zwracane wartości

mb_substr() returns the portion of str specified by the start and length parameters.

Zobacz też:

  • mb_strcut() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding

mb_substr_count
Pspell
Multibyte String Funkcje


Pspell

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Pspell Funkcje
    • pspell_add_to_personal — Add the word to a personal wordlist
    • pspell_add_to_session — Add the word to the wordlist in the current session
    • pspell_check — Check a word
    • pspell_clear_session — Clear the current session
    • pspell_config_create — Create a config used to open a dictionary
    • pspell_config_data_dir — location of language data files
    • pspell_config_dict_dir — Location of the main word list
    • pspell_config_ignore — Ignore words less than N characters long
    • pspell_config_mode — Change the mode number of suggestions returned
    • pspell_config_personal — Set a file that contains personal wordlist
    • pspell_config_repl — Set a file that contains replacement pairs
    • pspell_config_runtogether — Consider run-together words as valid compounds
    • pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
    • pspell_new_config — Load a new dictionary with settings based on a given config
    • pspell_new_personal — Load a new dictionary with personal wordlist
    • pspell_new — Load a new dictionary
    • pspell_save_wordlist — Save the personal wordlist to a file
    • pspell_store_replacement — Store a replacement pair for a word
    • pspell_suggest — Suggest spellings of a word
mb_substr
Wstęp
Język naturalny i obsługa kodowania znaków


Wstęp

These functions allow you to check the spelling of a word and offer suggestions.

Pspell
Instalacja/Konfiguracja
Pspell


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Pspell


Wymagania

To compile PHP with pspell support, you need the aspell library, available from » http://aspell.net/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

Informacja: Note to Win32 Users

Aby poprawnie działało rozszerzenie, pliki DLL muszą znajdować się w miejscu wskazanym przez PATH systemu Windows. Aby uzyskać więcej informacji zobacz FAQ zatytułowane "Jak mam dodać mój katalog PHP do PATH w Windows". Chociaż skopiowanie plików DLL z folderu PHP do systemowego katalogu Windows także zadziała (ponieważ katalog systemowy jest domyślnie w PATH systemu), ale nie jest to wymagane. To rozszerzenie wymaga następujących plików znajdujących się w PATH: aspell-15.dll from the bin folder of the aspell installation.

Win32 support is available only in PHP 4.3.3 and later versions. Also, at least aspell version 0.50 is required.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

PSPELL_FAST (integer)
PSPELL_NORMAL (integer)
PSPELL_BAD_SPELLERS (integer)
PSPELL_RUN_TOGETHER (integer)
Typy zasobów
Pspell Funkcje
Pspell


Pspell Funkcje

Spis treści

  • pspell_add_to_personal — Add the word to a personal wordlist
  • pspell_add_to_session — Add the word to the wordlist in the current session
  • pspell_check — Check a word
  • pspell_clear_session — Clear the current session
  • pspell_config_create — Create a config used to open a dictionary
  • pspell_config_data_dir — location of language data files
  • pspell_config_dict_dir — Location of the main word list
  • pspell_config_ignore — Ignore words less than N characters long
  • pspell_config_mode — Change the mode number of suggestions returned
  • pspell_config_personal — Set a file that contains personal wordlist
  • pspell_config_repl — Set a file that contains replacement pairs
  • pspell_config_runtogether — Consider run-together words as valid compounds
  • pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist
  • pspell_new_config — Load a new dictionary with settings based on a given config
  • pspell_new_personal — Load a new dictionary with personal wordlist
  • pspell_new — Load a new dictionary
  • pspell_save_wordlist — Save the personal wordlist to a file
  • pspell_store_replacement — Store a replacement pair for a word
  • pspell_suggest — Suggest spellings of a word
Stałe predefiniowane
pspell_add_to_personal
Pspell


Add the word to a personal wordlist

Pspell Funkcje
pspell_add_to_session
Pspell Funkcje
PHP Manual

pspell_add_to_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_add_to_personal — Add the word to a personal wordlist

Opis

bool pspell_add_to_personal ( int $dictionary_link , string $word )

pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist().

Parametry

dictionary_link

word

The added word.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?>

Notatki

Informacja:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Pspell Funkcje
pspell_add_to_session
Pspell Funkcje


Add the word to the wordlist in the current session

pspell_add_to_personal
pspell_check
Pspell Funkcje
PHP Manual

pspell_add_to_session

(PHP 4 >= 4.0.2, PHP 5)

pspell_add_to_session — Add the word to the wordlist in the current session

Opis

bool pspell_add_to_session ( int $dictionary_link , string $word )

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

Parametry

dictionary_link

word

The added word.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

pspell_add_to_personal
pspell_check
Pspell Funkcje


Check a word

pspell_add_to_session
pspell_clear_session
Pspell Funkcje
PHP Manual

pspell_check

(PHP 4 >= 4.0.2, PHP 5)

pspell_check — Check a word

Opis

bool pspell_check ( int $dictionary_link , string $word )

pspell_check() checks the spelling of a word.

Parametry

dictionary_link

word

The tested word.

Zwracane wartości

Returns TRUE if the spelling is correct, FALSE if not.

Przykłady

Przykład #1 pspell_check() Example

<?php
$pspell_link = pspell_new("en");

if (pspell_check($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}
?>

pspell_add_to_session
pspell_clear_session
Pspell Funkcje


Clear the current session

pspell_check
pspell_config_create
Pspell Funkcje
PHP Manual

pspell_clear_session

(PHP 4 >= 4.0.2, PHP 5)

pspell_clear_session — Clear the current session

Opis

bool pspell_clear_session ( int $dictionary_link )

pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.

Parametry

dictionary_link

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_add_to_personal() Example

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_clear_session($pspell_link);
pspell_save_wordlist($pspell_link);    //"Vlad" will not be saved
?>

pspell_check
pspell_config_create
Pspell Funkcje


Create a config used to open a dictionary

pspell_clear_session
pspell_config_data_dir
Pspell Funkcje
PHP Manual

pspell_config_create

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_create — Create a config used to open a dictionary

Opis

int pspell_config_create ( string $language [, string $spelling [, string $jargon [, string $encoding ]]] )

Create a config used to open a dictionary.

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediately followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parametry

language

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

Zwracane wartości

Retuns a pspell config identifier, or FALSE on error.

Przykłady

Przykład #1 pspell_config_create()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_personal($pspell_config, "en");
?>

pspell_clear_session
pspell_config_data_dir
Pspell Funkcje


location of language data files

pspell_config_create
pspell_config_dict_dir
Pspell Funkcje
PHP Manual

pspell_config_data_dir

(PHP 5)

pspell_config_data_dir — location of language data files

Opis

bool pspell_config_data_dir ( int $conf , string $directory )

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.

pspell_config_create
pspell_config_dict_dir
Pspell Funkcje


Location of the main word list

pspell_config_data_dir
pspell_config_ignore
Pspell Funkcje
PHP Manual

pspell_config_dict_dir

(PHP 5)

pspell_config_dict_dir — Location of the main word list

Opis

bool pspell_config_dict_dir ( int $conf , string $directory )

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.

pspell_config_data_dir
pspell_config_ignore
Pspell Funkcje


Ignore words less than N characters long

pspell_config_dict_dir
pspell_config_mode
Pspell Funkcje
PHP Manual

pspell_config_ignore

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_ignore — Ignore words less than N characters long

Opis

bool pspell_config_ignore ( int $dictionary_link , int $n )

pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spell checker.

Parametry

dictionary_link

n

Words less than n characters will be skipped.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_config_ignore()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_ignore($pspell_config, 5);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "abcd");    //will not result in an error
?>

pspell_config_dict_dir
pspell_config_mode
Pspell Funkcje


Change the mode number of suggestions returned

pspell_config_ignore
pspell_config_personal
Pspell Funkcje
PHP Manual

pspell_config_mode

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_mode — Change the mode number of suggestions returned

Opis

bool pspell_config_mode ( int $dictionary_link , int $mode )

pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().

Parametry

dictionary_link

mode

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_config_mode() Example

<?php
$pspell_config = pspell_config_create("en");
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

pspell_config_ignore
pspell_config_personal
Pspell Funkcje


Set a file that contains personal wordlist

pspell_config_mode
pspell_config_repl
Pspell Funkcje
PHP Manual

pspell_config_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_personal — Set a file that contains personal wordlist

Opis

bool pspell_config_personal ( int $dictionary_link , string $file )

Set a file that contains personal wordlist. The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). The file is also the file where pspell_save_wordlist() will save personal wordlist to.

pspell_config_personal() should be used on a config before calling pspell_new_config().

Parametry

dictionary_link

file

The personal wordlist. If the file does not exist, it will be created. The file should be writable by whoever PHP runs as (e.g. nobody).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_config_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

Notatki

Informacja:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_mode
pspell_config_repl
Pspell Funkcje


Set a file that contains replacement pairs

pspell_config_personal
pspell_config_runtogether
Pspell Funkcje
PHP Manual

pspell_config_repl

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_repl — Set a file that contains replacement pairs

Opis

bool pspell_config_repl ( int $dictionary_link , string $file )

Set a file that contains replacement pairs.

The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs.

pspell_config_repl() should be used on a config before calling pspell_new_config().

Parametry

dictionary_link

file

The file should be writable by whoever PHP runs as (e.g. nobody).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_config_repl()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

Notatki

Informacja:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_personal
pspell_config_runtogether
Pspell Funkcje


Consider run-together words as valid compounds

pspell_config_repl
pspell_config_save_repl
Pspell Funkcje
PHP Manual

pspell_config_runtogether

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_runtogether — Consider run-together words as valid compounds

Opis

bool pspell_config_runtogether ( int $dictionary_link , bool $flag )

This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

pspell_config_runtogether() should be used on a config before calling pspell_new_config().

Parametry

dictionary_link

flag

TRUE if run-together words should be treated as legal compounds, FALSE otherwise.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_config_runtogether()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_runtogether($pspell_config, true);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

pspell_config_repl
pspell_config_save_repl
Pspell Funkcje


Determine whether to save a replacement pairs list along with the wordlist

pspell_config_runtogether
pspell_new_config
Pspell Funkcje
PHP Manual

pspell_config_save_repl

(PHP 4 >= 4.0.2, PHP 5)

pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist

Opis

bool pspell_config_save_repl ( int $dictionary_link , bool $flag )

pspell_config_save_repl() determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved.

pspell_config_save_repl() should be used on a config before calling pspell_new_config().

Parametry

dictionary_link

flag

TRUE if replacement pairs should be saved, FALSE otherwise.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_config_runtogether
pspell_new_config
Pspell Funkcje


Load a new dictionary with settings based on a given config

pspell_config_save_repl
pspell_new_personal
Pspell Funkcje
PHP Manual

pspell_new_config

(PHP 4 >= 4.0.2, PHP 5)

pspell_new_config — Load a new dictionary with settings based on a given config

Opis

int pspell_new_config ( int $config )

pspell_new_config() opens up a new dictionary with settings specified in a config, created with pspell_config_create() and modified with pspell_config_*() functions. This method provides you with the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().

Parametry

config

The config parameter is the one returned by pspell_config_create() when the config was created.

Zwracane wartości

Returns a dictionary link identifier on success.

Przykłady

Przykład #1 pspell_new_config()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);
?>

pspell_config_save_repl
pspell_new_personal
Pspell Funkcje


Load a new dictionary with personal wordlist

pspell_new_config
pspell_new
Pspell Funkcje
PHP Manual

pspell_new_personal

(PHP 4 >= 4.0.2, PHP 5)

pspell_new_personal — Load a new dictionary with personal wordlist

Opis

int pspell_new_personal ( string $personal , string $language [, string $spelling [, string $jargon [, string $encoding [, int $mode = 0 ]]]] )

pspell_new_personal() opens up a new dictionary with a personal wordlist. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parametry

personal

The file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.

language

The language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

Extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding that words are expected to be in. Valid values are utf-8, iso8859-*, koi8-r, viscii, cp1252, machine unsigned 16, machine unsigned 32.

mode

The mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

Zwracane wartości

Returns the dictionary link identifier for use in other pspell functions.

Przykłady

Przykład #1 pspell_new_personal()

<?php
$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws",
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?>

pspell_new_config
pspell_new
Pspell Funkcje


Load a new dictionary

pspell_new_personal
pspell_save_wordlist
Pspell Funkcje
PHP Manual

pspell_new

(PHP 4 >= 4.0.2, PHP 5)

pspell_new — Load a new dictionary

Opis

int pspell_new ( string $language [, string $spelling [, string $jargon [, string $encoding [, int $mode = 0 ]]]] )

pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

Parametry

language

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

spelling

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

mode

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)
  • PSPELL_NORMAL - Normal mode (more suggestions)
  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.
Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

Zwracane wartości

Returns the dictionary link identifier on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 pspell_new()

<?php
$pspell_link = pspell_new("en", "", "", "",
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>

pspell_new_personal
pspell_save_wordlist
Pspell Funkcje


Save the personal wordlist to a file

pspell_new
pspell_store_replacement
Pspell Funkcje
PHP Manual

pspell_save_wordlist

(PHP 4 >= 4.0.2, PHP 5)

pspell_save_wordlist — Save the personal wordlist to a file

Opis

bool pspell_save_wordlist ( int $dictionary_link )

pspell_save_wordlist() saves the personal wordlist from the current session. The location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl().

Parametry

dictionary_link

A dictionary link identifier opened with pspell_new_personal().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/tmp/dicts/newdict");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?>

Notatki

Informacja:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_new
pspell_store_replacement
Pspell Funkcje


Store a replacement pair for a word

pspell_save_wordlist
pspell_suggest
Pspell Funkcje
PHP Manual

pspell_store_replacement

(PHP 4 >= 4.0.2, PHP 5)

pspell_store_replacement — Store a replacement pair for a word

Opis

bool pspell_store_replacement ( int $dictionary_link , string $misspelled , string $correct )

pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk.

Parametry

dictionary_link

A dictionary link identifier, opened with pspell_new_personal()

misspelled

The misspelled word.

correct

The fixed spelling for the misspelled word.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pspell_store_replacement()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl");
$pspell_link = pspell_new_config($pspell_config);

pspell_store_replacement($pspell_link, $misspelled, $correct);
pspell_save_wordlist($pspell_link);
?>

Notatki

Informacja:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

pspell_save_wordlist
pspell_suggest
Pspell Funkcje


Suggest spellings of a word

pspell_store_replacement
Recode
Pspell Funkcje
PHP Manual

pspell_suggest

(PHP 4 >= 4.0.2, PHP 5)

pspell_suggest — Suggest spellings of a word

Opis

array pspell_suggest ( int $dictionary_link , string $word )

pspell_suggest() returns an array of possible spellings for the given word.

Parametry

dictionary_link

word

The tested word.

Zwracane wartości

Returns an array of possible spellings.

Przykłady

Przykład #1 pspell_suggest() example

<?php
$pspell_link = pspell_new("en");

if (!pspell_check($pspell_link, "testt")) {
    $suggestions = pspell_suggest($pspell_link, "testt");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br />";
    }
}
?>

pspell_store_replacement
Recode
Pspell Funkcje


GNU Recode

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Recode Funkcje
    • recode_file — Recode from file to file according to recode request
    • recode_string — Recode a string according to a recode request
    • recode — Alias dla recode_string
pspell_suggest
Wstęp
Język naturalny i obsługa kodowania znaków


Wstęp

This module contains an interface to the GNU Recode library. The GNU Recode library converts files between various coded character sets and surface encodings. When this cannot be achieved exactly, it may get rid of the offending characters or fall back on approximations. The library recognises or produces nearly 150 different character sets and is able to convert files between almost any pair. Most » RFC 1345 character sets are supported.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

Recode
Instalacja/Konfiguracja
Recode


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Recode


Wymagania

You must have GNU Recode 3.5 or higher installed on your system. You can download the package from » http://directory.fsf.org/All_GNU_Packages/recode.html.

Ostrzeżenie

The Recode library version 3.6 adds weird characters behind converted strings under certain circumstances. Thus it's safer to use Recode v3.5 or one of the available alternatives like the iconv or mbstring extension.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

Ostrzeżenie

Crashes and startup problems of PHP may be encountered when loading the recode as extension after loading any extension of mysql or imap. Loading the recode before those extension has proved to fix the problem. This is due a technical problem that both the c-client library used by imap and recode have their own hash_lookup() function and both mysql and recode have their own hash_insert function.

Ostrzeżenie

Rozszerzenia IMAP, recode, YAZ i Cyrus nie mogą być używane razem. Dzieje się tak z powodu współdzielenia tych samych oznaczeń wewnętrznych. Notatka: problem nie dotyczy Yaz 2.0 i nowszych wersji.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Recode Funkcje
Recode


Recode Funkcje

Spis treści

  • recode_file — Recode from file to file according to recode request
  • recode_string — Recode a string according to a recode request
  • recode — Alias dla recode_string
Stałe predefiniowane
recode_file
Recode


Recode from file to file according to recode request

Recode Funkcje
recode_string
Recode Funkcje
PHP Manual

recode_file

(PHP 4, PHP 5)

recode_file — Recode from file to file according to recode request

Opis

bool recode_file ( string $request , resource $input , resource $output )

Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request.

Parametry

request

The desired recode request type

input

A local file handle resource for the input

output

A local file handle resource for the output

Zwracane wartości

Returns FALSE, if unable to comply, TRUE otherwise.

Przykłady

Przykład #1 Basic recode_file() example

<?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?>

Notatki

This function does not currently process file handles referencing remote files (URLs). Both file handles must refer to local files.

Zobacz też:

  • fopen() - Otwiera plik lub URL

Recode Funkcje
recode_string
Recode Funkcje


Recode a string according to a recode request

recode_file
recode
Recode Funkcje
PHP Manual

recode_string

(PHP 4, PHP 5)

recode_string — Recode a string according to a recode request

Opis

string recode_string ( string $request , string $string )

Recode the string string according to the recode request request.

Parametry

request

The desired recode request type

string

The string to be recoded

Zwracane wartości

Returns the recoded string or FALSE, if unable to perform the recode request.

Przykłady

Przykład #1 Basic recode_string() example

<?php
echo recode_string("us..flat", "The following character has a diacritical mark: á");
?>

Notatki

A simple recode request may be "lat1..iso646-de".

Zobacz też:

  • The GNU Recode documentation of your installation for detailed instructions about recode requests.

recode_file
recode
Recode Funkcje


Alias dla recode_string

recode_string
Przetwarzanie i generowanie obrazów
Recode Funkcje
PHP Manual

recode

(PHP 4, PHP 5)

recode — Alias dla recode_string()

Opis

Ta funkcja jest aliasem dla: recode_string().

recode_string
Przetwarzanie i generowanie obrazów
Recode Funkcje


Przetwarzanie i generowanie obrazów

  • Cairo
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Cairo Funkcje
    • Cairo — The Cairo class
    • CairoContext — The CairoContext class
    • CairoException — The CairoException class
    • CairoStatus — The CairoStatus class
    • CairoSurface — The CairoSurface class
    • CairoSvgSurface — Svg Surface Backend
    • CairoImageSurface — The CairoImageSurface class
    • CairoPdfSurface — The CairoPdfSurface class
    • CairoPsSurface — The CairoPsSurface class
    • CairoSurfaceType — The CairoSurfaceType class
    • CairoFontFace — The CairoFontFace class
    • CairoFontOptions — The CairoFontOptions class
    • CairoFontSlant — The CairoFontSlant class
    • CairoFontType — The CairoFontType class
    • CairoFontWeight — The CairoFontWeight class
    • CairoScaledFont — The CairoScaledFont class
    • CairoToyFontFace — The CairoToyFontFace class
    • CairoPatternType — The CairoPatternType class
    • CairoPattern — The CairoPattern class
    • CairoGradientPattern — The CairoGradientPattern class
    • CairoSolidPattern — The CairoSolidPattern class
    • CairoSurfacePattern — The CairoSurfacePattern class
    • CairoLinearGradient — The CairoLinearGradient class
    • CairoRadialGradient — The CairoRadialGradient class
    • CairoAntialias — The CairoAntialias class
    • CairoContent — The CairoContent class
    • CairoExtend — The CairoExtend class
    • CairoFormat — The CairoFormat class
    • CairoFillRule — The CairoFillRule class
    • CairoFilter — The CairoFilter class
    • CairoHintMetrics — The CairoHintMetrics class
    • CairoHintStyle — The CairoHintStyle class
    • CairoLineCap — The CairoLineCap class
    • CairoLineJoin — The CairoLineJoin class
    • CairoMatrix — The CairoMatrix class
    • CairoOperator — The CairoOperator class
    • CairoPath — The CairoPath class
    • CairoPsLevel — The CairoPsLevel class
    • CairoSubpixelOrder — The CairoSubpixelOrder class
    • CairoSvgVersion — The CairoSvgVersion class
  • Exif — Exchangeable image information
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje Exif
  • GD — Image Processing and GD
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • GD and Image Funkcje
  • Gmagick
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Gmagick — The Gmagick class
    • GmagickDraw — The GmagickDraw class
    • GmagickPixel — The GmagickPixel class
  • ImageMagick — Image Processing (ImageMagick)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Imagick — The Imagick class
    • ImagickDraw — The ImagickDraw class
    • ImagickPixel — The ImagickPixel class
    • ImagickPixelIterator — The ImagickPixelIterator class
recode
Cairo
Opis funkcji


Cairo

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Cairo Funkcje
    • cairo_create — Returns a new CairoContext object on the requested surface.
    • cairo_font_face_get_type — Description
    • cairo_font_face_status — Description
    • cairo_font_options_create — Description
    • cairo_font_options_equal — Description
    • cairo_font_options_get_antialias — Description
    • cairo_font_options_get_hint_metrics — Description
    • cairo_font_options_get_hint_style — Description
    • cairo_font_options_get_subpixel_order — Description
    • cairo_font_options_hash — Description
    • cairo_font_options_merge — Description
    • cairo_font_options_set_antialias — Description
    • cairo_font_options_set_hint_metrics — Description
    • cairo_font_options_set_hint_style — Description
    • cairo_font_options_set_subpixel_order — Description
    • cairo_font_options_status — Description
    • cairo_format_stride_for_width — Description
    • cairo_image_surface_create_for_data — Description
    • cairo_image_surface_create_from_png — Description
    • cairo_image_surface_create — Description
    • cairo_image_surface_get_data — Description
    • cairo_image_surface_get_format — Description
    • cairo_image_surface_get_height — Description
    • cairo_image_surface_get_stride — Description
    • cairo_image_surface_get_width — Description
    • cairo_matrix_create_scale — Alias dla CairoMatrix::initScale
    • cairo_matrix_create_translate — Alias dla CairoMatrix::initTranslate
    • cairo_matrix_invert — Description
    • cairo_matrix_multiply — Description
    • cairo_matrix_rotate — Description
    • cairo_matrix_transform_distance — Description
    • cairo_matrix_transform_point — Description
    • cairo_matrix_translate — Description
    • cairo_pattern_add_color_stop_rgb — Description
    • cairo_pattern_add_color_stop_rgba — Description
    • cairo_pattern_create_for_surface — Description
    • cairo_pattern_create_linear — Description
    • cairo_pattern_create_radial — Description
    • cairo_pattern_create_rgb — Description
    • cairo_pattern_create_rgba — Description
    • cairo_pattern_get_color_stop_count — Description
    • cairo_pattern_get_color_stop_rgba — Description
    • cairo_pattern_get_extend — Description
    • cairo_pattern_get_filter — Description
    • cairo_pattern_get_linear_points — Description
    • cairo_pattern_get_matrix — Description
    • cairo_pattern_get_radial_circles — Description
    • cairo_pattern_get_rgba — Description
    • cairo_pattern_get_surface — Description
    • cairo_pattern_get_type — Description
    • cairo_pattern_set_extend — Description
    • cairo_pattern_set_filter — Description
    • cairo_pattern_set_matrix — Description
    • cairo_pattern_status — Description
    • cairo_pdf_surface_create — Description
    • cairo_pdf_surface_set_size — Description
    • cairo_ps_get_levels — Description
    • cairo_ps_level_to_string — Description
    • cairo_ps_surface_create — Description
    • cairo_ps_surface_dsc_begin_page_setup — Description
    • cairo_ps_surface_dsc_begin_setup — Description
    • cairo_ps_surface_dsc_comment — Description
    • cairo_ps_surface_get_eps — Description
    • cairo_ps_surface_restrict_to_level — Description
    • cairo_ps_surface_set_eps — Description
    • cairo_ps_surface_set_size — Description
    • cairo_scaled_font_create — Description
    • cairo_scaled_font_extents — Description
    • cairo_scaled_font_get_ctm — Description
    • cairo_scaled_font_get_font_face — Description
    • cairo_scaled_font_get_font_matrix — Description
    • cairo_scaled_font_get_font_options — Description
    • cairo_scaled_font_get_scale_matrix — Description
    • cairo_scaled_font_get_type — Description
    • cairo_scaled_font_glyph_extents — Description
    • cairo_scaled_font_status — Description
    • cairo_scaled_font_text_extents — Description
    • cairo_surface_copy_page — Description
    • cairo_surface_create_similar — Description
    • cairo_surface_finish — Description
    • cairo_surface_flush — Description
    • cairo_surface_get_content — Description
    • cairo_surface_get_device_offset — Description
    • cairo_surface_get_font_options — Description
    • cairo_surface_get_type — Description
    • cairo_surface_mark_dirty_rectangle — Description
    • cairo_surface_mark_dirty — Description
    • cairo_surface_set_device_offset — Description
    • cairo_surface_set_fallback_resolution — Description
    • cairo_surface_show_page — Description
    • cairo_surface_status — Description
    • cairo_surface_write_to_png — Description
    • cairo_svg_surface_create — Description
    • cairo_svg_surface_restrict_to_version — Description
    • cairo_svg_version_to_string — Description
  • Cairo — The Cairo class
    • Cairo::availableFonts — Retrieves the availables font types
    • Cairo::availableSurfaces — Retrieves all available surfaces
    • Cairo::statusToString — Retrieves the current status as string
    • Cairo::version — Retrives cairo's library version
    • Cairo::versionString — Retrieves cairo version as string
  • CairoContext — The CairoContext class
    • CairoContext::appendPath — Appends a path to current path
    • CairoContext::arc — Adds a circular arc
    • CairoContext::arcNegative — Adds a negative arc
    • CairoContext::clip — Establishes a new clip region
    • CairoContext::clipExtents — Computes the area inside the current clip
    • CairoContext::clipPreserve — Establishes a new clip region from the current clip
    • CairoContext::clipRectangleList — Retrieves the current clip as a list of rectangles
    • CairoContext::closePath — Closes the current path
    • CairoContext::__construct — Creates a new CairoContext
    • CairoContext::copyPage — Emits the current page
    • CairoContext::copyPath — Creates a copy of the current path
    • CairoContext::copyPathFlat — Gets a flattened copy of the current path
    • CairoContext::curveTo — Adds a curve
    • CairoContext::deviceToUser — Transform a coordinate
    • CairoContext::deviceToUserDistance — Transform a distance
    • CairoContext::fill — Fills the current path
    • CairoContext::fillExtents — Computes the filled area
    • CairoContext::fillPreserve — Fills and preserve the current path
    • CairoContext::fontExtents — Get the font extents
    • CairoContext::getAntialias — Retrives the current antialias mode
    • CairoContext::getCurrentPoint — The getCurrentPoint purpose
    • CairoContext::getDash — The getDash purpose
    • CairoContext::getDashCount — The getDashCount purpose
    • CairoContext::getFillRule — The getFillRule purpose
    • CairoContext::getFontFace — The getFontFace purpose
    • CairoContext::getFontMatrix — The getFontMatrix purpose
    • CairoContext::getFontOptions — The getFontOptions purpose
    • CairoContext::getGroupTarget — The getGroupTarget purpose
    • CairoContext::getLineCap — The getLineCap purpose
    • CairoContext::getLineJoin — The getLineJoin purpose
    • CairoContext::getLineWidth — The getLineWidth purpose
    • CairoContext::getMatrix — The getMatrix purpose
    • CairoContext::getMiterLimit — The getMiterLimit purpose
    • CairoContext::getOperator — The getOperator purpose
    • CairoContext::getScaledFont — The getScaledFont purpose
    • CairoContext::getSource — The getSource purpose
    • CairoContext::getTarget — The getTarget purpose
    • CairoContext::getTolerance — The getTolerance purpose
    • CairoContext::glyphPath — The glyphPath purpose
    • CairoContext::hasCurrentPoint — The hasCurrentPoint purpose
    • CairoContext::identityMatrix — The identityMatrix purpose
    • CairoContext::inFill — The inFill purpose
    • CairoContext::inStroke — The inStroke purpose
    • CairoContext::lineTo — The lineTo purpose
    • CairoContext::mask — The mask purpose
    • CairoContext::maskSurface — The maskSurface purpose
    • CairoContext::moveTo — The moveTo purpose
    • CairoContext::newPath — The newPath purpose
    • CairoContext::newSubPath — The newSubPath purpose
    • CairoContext::paint — The paint purpose
    • CairoContext::paintWithAlpha — The paintWithAlpha purpose
    • CairoContext::pathExtents — The pathExtents purpose
    • CairoContext::popGroup — The popGroup purpose
    • CairoContext::popGroupToSource — The popGroupToSource purpose
    • CairoContext::pushGroup — The pushGroup purpose
    • CairoContext::pushGroupWithContent — The pushGroupWithContent purpose
    • CairoContext::rectangle — The rectangle purpose
    • CairoContext::relCurveTo — The relCurveTo purpose
    • CairoContext::relLineTo — The relLineTo purpose
    • CairoContext::relMoveTo — The relMoveTo purpose
    • CairoContext::resetClip — The resetClip purpose
    • CairoContext::restore — The restore purpose
    • CairoContext::rotate — The rotate purpose
    • CairoContext::save — The save purpose
    • CairoContext::scale — The scale purpose
    • CairoContext::selectFontFace — The selectFontFace purpose
    • CairoContext::setAntialias — The setAntialias purpose
    • CairoContext::setDash — The setDash purpose
    • CairoContext::setFillRule — The setFillRule purpose
    • CairoContext::setFontFace — The setFontFace purpose
    • CairoContext::setFontMatrix — The setFontMatrix purpose
    • CairoContext::setFontOptions — The setFontOptions purpose
    • CairoContext::setFontSize — The setFontSize purpose
    • CairoContext::setLineCap — The setLineCap purpose
    • CairoContext::setLineJoin — The setLineJoin purpose
    • CairoContext::setLineWidth — The setLineWidth purpose
    • CairoContext::setMatrix — The setMatrix purpose
    • CairoContext::setMiterLimit — The setMiterLimit purpose
    • CairoContext::setOperator — The setOperator purpose
    • CairoContext::setScaledFont — The setScaledFont purpose
    • CairoContext::setSource — The setSource purpose
    • CairoContext::setSourceRGB — The setSourceRGB purpose
    • CairoContext::setSourceRGBA — The setSourceRGBA purpose
    • CairoContext::setSourceSurface — The setSourceSurface purpose
    • CairoContext::setTolerance — The setTolerance purpose
    • CairoContext::showPage — The showPage purpose
    • CairoContext::showText — The showText purpose
    • CairoContext::status — The status purpose
    • CairoContext::stroke — The stroke purpose
    • CairoContext::strokeExtents — The strokeExtents purpose
    • CairoContext::strokePreserve — The strokePreserve purpose
    • CairoContext::textExtents — The textExtents purpose
    • CairoContext::textPath — The textPath purpose
    • CairoContext::transform — The transform purpose
    • CairoContext::translate — The translate purpose
    • CairoContext::userToDevice — The userToDevice purpose
    • CairoContext::userToDeviceDistance — The userToDeviceDistance purpose
  • CairoException — The CairoException class
  • CairoStatus — The CairoStatus class
  • CairoSurface — The CairoSurface class
    • CairoSurface::__construct — The __construct purpose
    • CairoSurface::copyPage — The copyPage purpose
    • CairoSurface::createSimilar — The createSimilar purpose
    • CairoSurface::finish — The finish purpose
    • CairoSurface::flush — The flush purpose
    • CairoSurface::getContent — The getContent purpose
    • CairoSurface::getDeviceOffset — The getDeviceOffset purpose
    • CairoSurface::getFontOptions — The getFontOptions purpose
    • CairoSurface::getType — The getType purpose
    • CairoSurface::markDirty — The markDirty purpose
    • CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose
    • CairoSurface::setDeviceOffset — The setDeviceOffset purpose
    • CairoSurface::setFallbackResolution — The setFallbackResolution purpose
    • CairoSurface::showPage — The showPage purpose
    • CairoSurface::status — The status purpose
    • CairoSurface::writeToPng — The writeToPng purpose
  • CairoSvgSurface — Svg Surface Backend
    • CairoSvgSurface::__construct — The __construct purpose
    • CairoSvgSurface::getVersions — Used to retrieve a list of supported SVG versions
    • CairoSvgSurface::restrictToVersion — The restrictToVersion purpose
    • CairoSvgSurface::versionToString — The versionToString purpose
  • CairoImageSurface — The CairoImageSurface class
    • CairoImageSurface::__construct — Creates a new CairoImageSurface
    • CairoImageSurface::createForData — The createForData purpose
    • CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file
    • CairoImageSurface::getData — Gets the image data as string
    • CairoImageSurface::getFormat — Get the image format
    • CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface
    • CairoImageSurface::getStride — The getStride purpose
    • CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface
  • CairoPdfSurface — The CairoPdfSurface class
    • CairoPdfSurface::__construct — The __construct purpose
    • CairoPdfSurface::setSize — The setSize purpose
  • CairoPsSurface — The CairoPsSurface class
    • CairoPsSurface::__construct — The __construct purpose
    • CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose
    • CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose
    • CairoPsSurface::dscComment — The dscComment purpose
    • CairoPsSurface::getEps — The getEps purpose
    • CairoPsSurface::getLevels — The getLevels purpose
    • CairoPsSurface::levelToString — The levelToString purpose
    • CairoPsSurface::restrictToLevel — The restrictToLevel purpose
    • CairoPsSurface::setEps — The setEps purpose
    • CairoPsSurface::setSize — The setSize purpose
  • CairoSurfaceType — The CairoSurfaceType class
  • CairoFontFace — The CairoFontFace class
    • CairoFontFace::__construct — Creates a new CairoFontFace object
    • CairoFontFace::getType — Retrieves the font face type
    • CairoFontFace::status — Check for CairoFontFace errors
  • CairoFontOptions — The CairoFontOptions class
    • CairoFontOptions::__construct — The __construct purpose
    • CairoFontOptions::equal — The equal purpose
    • CairoFontOptions::getAntialias — The getAntialias purpose
    • CairoFontOptions::getHintMetrics — The getHintMetrics purpose
    • CairoFontOptions::getHintStyle — The getHintStyle purpose
    • CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose
    • CairoFontOptions::hash — The hash purpose
    • CairoFontOptions::merge — The merge purpose
    • CairoFontOptions::setAntialias — The setAntialias purpose
    • CairoFontOptions::setHintMetrics — The setHintMetrics purpose
    • CairoFontOptions::setHintStyle — The setHintStyle purpose
    • CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose
    • CairoFontOptions::status — The status purpose
  • CairoFontSlant — The CairoFontSlant class
  • CairoFontType — The CairoFontType class
  • CairoFontWeight — The CairoFontWeight class
  • CairoScaledFont — The CairoScaledFont class
    • CairoScaledFont::__construct — The __construct purpose
    • CairoScaledFont::extents — The extents purpose
    • CairoScaledFont::getCtm — The getCtm purpose
    • CairoScaledFont::getFontFace — The getFontFace purpose
    • CairoScaledFont::getFontMatrix — The getFontMatrix purpose
    • CairoScaledFont::getFontOptions — The getFontOptions purpose
    • CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose
    • CairoScaledFont::getType — The getType purpose
    • CairoScaledFont::glyphExtents — The glyphExtents purpose
    • CairoScaledFont::status — The status purpose
    • CairoScaledFont::textExtents — The textExtents purpose
  • CairoToyFontFace — The CairoToyFontFace class
  • CairoPatternType — The CairoPatternType class
  • CairoPattern — The CairoPattern class
    • CairoPattern::__construct — The __construct purpose
    • CairoPattern::getMatrix — The getMatrix purpose
    • CairoPattern::getType — The getType purpose
    • CairoPattern::setMatrix — The setMatrix purpose
    • CairoPattern::status — The status purpose
  • CairoGradientPattern — The CairoGradientPattern class
    • CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose
    • CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose
    • CairoGradientPattern::getColorStopCount — The getColorStopCount purpose
    • CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose
    • CairoGradientPattern::getExtend — The getExtend purpose
    • CairoGradientPattern::setExtend — The setExtend purpose
  • CairoSolidPattern — The CairoSolidPattern class
    • CairoSolidPattern::__construct — The __construct purpose
    • CairoSolidPattern::getRgba — The getRgba purpose
  • CairoSurfacePattern — The CairoSurfacePattern class
    • CairoSurfacePattern::__construct — The __construct purpose
    • CairoSurfacePattern::getExtend — The getExtend purpose
    • CairoSurfacePattern::getFilter — The getFilter purpose
    • CairoSurfacePattern::getSurface — The getSurface purpose
    • CairoSurfacePattern::setExtend — The setExtend purpose
    • CairoSurfacePattern::setFilter — The setFilter purpose
  • CairoLinearGradient — The CairoLinearGradient class
    • CairoLinearGradient::__construct — The __construct purpose
    • CairoLinearGradient::getPoints — The getPoints purpose
  • CairoRadialGradient — The CairoRadialGradient class
    • CairoRadialGradient::__construct — The __construct purpose
    • CairoRadialGradient::getCircles — The getCircles purpose
  • CairoAntialias — The CairoAntialias class
  • CairoContent — The CairoContent class
  • CairoExtend — The CairoExtend class
  • CairoFormat — The CairoFormat class
    • CairoFormat::strideForWidth — Provides an appropiate stride to use
  • CairoFillRule — The CairoFillRule class
  • CairoFilter — The CairoFilter class
  • CairoHintMetrics — The CairoHintMetrics class
  • CairoHintStyle — The CairoHintStyle class
  • CairoLineCap — The CairoLineCap class
  • CairoLineJoin — The CairoLineJoin class
  • CairoMatrix — The CairoMatrix class
    • CairoMatrix::__construct — Creates a new CairoMatrix object
    • CairoMatrix::initIdentity — Creates a new identity matrix
    • CairoMatrix::initRotate — Creates a new rotated matrix
    • CairoMatrix::initScale — Creates a new scaling matrix
    • CairoMatrix::initTranslate — Creates a new translation matrix
    • CairoMatrix::invert — The invert purpose
    • CairoMatrix::multiply — The multiply purpose
    • CairoMatrix::rotate — The rotate purpose
    • CairoMatrix::scale — Applies scaling to a matrix
    • CairoMatrix::transformDistance — The transformDistance purpose
    • CairoMatrix::transformPoint — The transformPoint purpose
    • CairoMatrix::translate — The translate purpose
  • CairoOperator — The CairoOperator class
  • CairoPath — The CairoPath class
  • CairoPsLevel — The CairoPsLevel class
  • CairoSubpixelOrder — The CairoSubpixelOrder class
  • CairoSvgVersion — The CairoSvgVersion class
Przetwarzanie i generowanie obrazów
Wstęp
Przetwarzanie i generowanie obrazów


Wstęp

Cairo is a native PHP extension to create and modify graphics using the Cairo Graphics Library.

The Cairo Graphics Library is a 2D library written in C with support for multiple output devices. Currently supported output targets include the X Window System, Quartz, Win32, image buffers, PostScript, PDF, and SVG file output. Experimental backends include OpenGL (through glitz), XCB, BeOS, OS/2, and DirectFB. The library also has support for two types of text manipulation and layout. The "toy" API provides demo quality support, and the glyphs API, although full-featured, works best with a helper library such as pango. Font backend support includes FreeType, Quartz, Win32, and User fonts.

There are two types of computer graphics, vector and raster. Raster graphics are the representation of images as an array of pixels. Vector graphics use geometrical primitives such as points, lines, curves or polygons to represent images. The primitives are created using mathematical equations. The Cairo Graphics Library takes a vector approach to graphics, allowing smaller size, infinite zooming, and moving, scaling and rotating without degrading image quality.

Operations in the cairo graphics library including stroking and filling cubic Bézier splines, transforming and compositing translucent images, and antialiased text rendering. All drawing operations can be transformed by any affine transformation (scale, rotation, shear, and others) This is very similiar to drawing operations for PostScript and PDF drawing.

The Cairo PHP Extension aims to provide support for all officially supported font backends and surface backends, as well as expose all available functionality in cairo to PHP users.

Cairo
Instalacja/Konfiguracja
Cairo


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Cairo


Wymagania

Cairo is only available for PHP 5.2+ and PHP 5.3+ The extension also requires the cairo graphics library version 1.4 or higher. The cairo graphics library uses an even and odd numbering scheme to denote stable and unstable library versions. Both unstable and stable versions can be used with the extension, but conditional support for new features is determined by the stable version below the unstable version in use. The latest cairo release can be found at » http://cairographics.org/.

The binary files used for the windows compiles can be found at » http://cairographics.org/download/ along with the project files used to create them.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/cairo.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Notes specific to installation on Windows

Binary builds of the extension can be found at » http://cairographics.org/download/. Download the correct zip file, place php_cairo.dll in the extensions directory, and enable it via the php.ini file in use. Please be sure the PHP minor version (5.2, 5.3) match, the thread safety (Thread Safe TS or Non-Thread Safe NTS), the architecture (x86 or x64), and the compiler version (VC6 or VC9) match or the extension will not load.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

CAIRO_STATUS_SUCCESS (integer)
CAIRO_STATUS_NO_MEMORY (integer)
CAIRO_STATUS_INVALID_RESTORE (integer)
CAIRO_STATUS_INVALID_POP_GROUP (integer)
CAIRO_STATUS_NO_CURRENT_POINT (integer)
CAIRO_STATUS_INVALID_MATRIX (integer)
CAIRO_STATUS_INVALID_STATUS (integer)
CAIRO_STATUS_NULL_POINTER (integer)
CAIRO_STATUS_INVALID_STRING (integer)
CAIRO_STATUS_INVALID_PATH_DATA (integer)
CAIRO_STATUS_READ_ERROR (integer)
CAIRO_STATUS_WRITE_ERROR (integer)
CAIRO_STATUS_SURFACE_FINISHED (integer)
CAIRO_STATUS_SURFACE_TYPE_MISMATCH (integer)
CAIRO_STATUS_PATTERN_TYPE_MISMATCH (integer)
CAIRO_STATUS_INVALID_CONTENT (integer)
CAIRO_STATUS_INVALID_FORMAT (integer)
CAIRO_STATUS_INVALID_VISUAL (integer)
CAIRO_STATUS_FILE_NOT_FOUND (integer)
CAIRO_STATUS_INVALID_DASH (integer)
CAIRO_STATUS_INVALID_DSC_COMMENT (integer)
CAIRO_STATUS_INVALID_INDEX (integer)
CAIRO_STATUS_CLIP_NOT_REPRESENTABLE (integer)
CAIRO_STATUS_TEMP_FILE_ERROR (integer)
CAIRO_STATUS_INVALID_STRIDE (integer)
CAIRO_ANTIALIAS_DEFAULT (integer)
CAIRO_ANTIALIAS_NONE (integer)
CAIRO_ANTIALIAS_GRAY (integer)
CAIRO_ANTIALIAS_SUBPIXEL (integer)
CAIRO_SUBPIXEL_ORDER_DEFAULT (integer)
CAIRO_SUBPIXEL_ORDER_RGB (integer)
CAIRO_SUBPIXEL_ORDER_BGR (integer)
CAIRO_SUBPIXEL_ORDER_VRGB (integer)
CAIRO_SUBPIXEL_ORDER_VBGR (integer)
CAIRO_FILL_RULE_WINDING (integer)
CAIRO_FILL_RULE_EVEN_ODD (integer)
CAIRO_LINE_CAP_BUTT (integer)
CAIRO_LINE_CAP_ROUND (integer)
CAIRO_LINE_CAP_SQUARE (integer)
CAIRO_LINE_JOIN_MITER (integer)
CAIRO_LINE_JOIN_ROUND (integer)
CAIRO_LINE_JOIN_BEVEL (integer)
CAIRO_OPERATOR_CLEAR (integer)
CAIRO_OPERATOR_SOURCE (integer)
CAIRO_OPERATOR_OVER (integer)
CAIRO_OPERATOR_IN (integer)
CAIRO_OPERATOR_OUT (integer)
CAIRO_OPERATOR_ATOP (integer)
CAIRO_OPERATOR_DEST (integer)
CAIRO_OPERATOR_DEST_OVER (integer)
CAIRO_OPERATOR_DEST_IN (integer)
CAIRO_OPERATOR_DEST_OUT (integer)
CAIRO_OPERATOR_DEST_ATOP (integer)
CAIRO_OPERATOR_XOR (integer)
CAIRO_OPERATOR_ADD (integer)
CAIRO_OPERATOR_SATURATE (integer)
CAIRO_PATTERN_TYPE_SOLID (integer)
CAIRO_PATTERN_TYPE_SURFACE (integer)
CAIRO_PATTERN_TYPE_LINEAR (integer)
CAIRO_PATTERN_TYPE_RADIAL (integer)
CAIRO_EXTEND_NONE (integer)
CAIRO_EXTEND_REPEAT (integer)
CAIRO_EXTEND_REFLECT (integer)
CAIRO_EXTEND_PAD (integer)
CAIRO_FILTER_FAST (integer)
CAIRO_FILTER_GOOD (integer)
CAIRO_FILTER_BEST (integer)
CAIRO_FILTER_NEAREST (integer)
CAIRO_FILTER_BILINEAR (integer)
CAIRO_FILTER_GAUSSIAN (integer)
CAIRO_HINT_STYLE_DEFAULT (integer)
CAIRO_HINT_STYLE_NONE (integer)
CAIRO_HINT_STYLE_SLIGHT (integer)
CAIRO_HINT_STYLE_MEDIUM (integer)
CAIRO_HINT_STYLE_FULL (integer)
CAIRO_HINT_METRICS_DEFAULT (integer)
CAIRO_HINT_METRICS_OFF (integer)
CAIRO_HINT_METRICS_ON (integer)
CAIRO_FONT_TYPE_TOY (integer)
CAIRO_FONT_TYPE_FT (integer)
CAIRO_FONT_TYPE_WIN32 (integer)
CAIRO_FONT_TYPE_QUARTZ (integer)
CAIRO_FONT_SLANT_NORMAL (integer)
CAIRO_FONT_SLANT_ITALIC (integer)
CAIRO_FONT_SLANT_OBLIQUE (integer)
CAIRO_FONT_WEIGHT_NORMAL (integer)
CAIRO_FONT_WEIGHT_BOLD (integer)
CAIRO_CONTENT_COLOR (integer)
CAIRO_CONTENT_ALPHA (integer)
CAIRO_CONTENT_COLOR_ALPHA (integer)
CAIRO_SURFACE_TYPE_IMAGE (integer)
CAIRO_SURFACE_TYPE_PDF (integer)
CAIRO_SURFACE_TYPE_PS (integer)
CAIRO_SURFACE_TYPE_XLIB (integer)
CAIRO_SURFACE_TYPE_XCB (integer)
CAIRO_SURFACE_TYPE_GLITZ (integer)
CAIRO_SURFACE_TYPE_QUARTZ (integer)
CAIRO_SURFACE_TYPE_WIN32 (integer)
CAIRO_SURFACE_TYPE_BEOS (integer)
CAIRO_SURFACE_TYPE_DIRECTFB (integer)
CAIRO_SURFACE_TYPE_SVG (integer)
CAIRO_SURFACE_TYPE_OS2 (integer)
CAIRO_SURFACE_TYPE_WIN32_PRINTING (integer)
CAIRO_SURFACE_TYPE_QUARTZ_IMAGE (integer)
CAIRO_FORMAT_ARGB32 (integer)
CAIRO_FORMAT_RGB24 (integer)
CAIRO_FORMAT_A8 (integer)
CAIRO_FORMAT_A1 (integer)
CAIRO_PS_LEVEL_2 (integer)
CAIRO_PS_LEVEL_3 (integer)
CAIRO_SVG_VERSION_1_1 (integer)
CAIRO_SVG_VERSION_1_2 (integer)

Typy zasobów
Przykłady
Cairo


Przykłady

Description here...

Przykład #1 Cairo Example

<?php

/* ... */

?>

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

...
Stałe predefiniowane
Cairo Funkcje
Cairo


Cairo Funkcje

Spis treści

  • cairo_create — Returns a new CairoContext object on the requested surface.
  • cairo_font_face_get_type — Description
  • cairo_font_face_status — Description
  • cairo_font_options_create — Description
  • cairo_font_options_equal — Description
  • cairo_font_options_get_antialias — Description
  • cairo_font_options_get_hint_metrics — Description
  • cairo_font_options_get_hint_style — Description
  • cairo_font_options_get_subpixel_order — Description
  • cairo_font_options_hash — Description
  • cairo_font_options_merge — Description
  • cairo_font_options_set_antialias — Description
  • cairo_font_options_set_hint_metrics — Description
  • cairo_font_options_set_hint_style — Description
  • cairo_font_options_set_subpixel_order — Description
  • cairo_font_options_status — Description
  • cairo_format_stride_for_width — Description
  • cairo_image_surface_create_for_data — Description
  • cairo_image_surface_create_from_png — Description
  • cairo_image_surface_create — Description
  • cairo_image_surface_get_data — Description
  • cairo_image_surface_get_format — Description
  • cairo_image_surface_get_height — Description
  • cairo_image_surface_get_stride — Description
  • cairo_image_surface_get_width — Description
  • cairo_matrix_create_scale — Alias dla CairoMatrix::initScale
  • cairo_matrix_create_translate — Alias dla CairoMatrix::initTranslate
  • cairo_matrix_invert — Description
  • cairo_matrix_multiply — Description
  • cairo_matrix_rotate — Description
  • cairo_matrix_transform_distance — Description
  • cairo_matrix_transform_point — Description
  • cairo_matrix_translate — Description
  • cairo_pattern_add_color_stop_rgb — Description
  • cairo_pattern_add_color_stop_rgba — Description
  • cairo_pattern_create_for_surface — Description
  • cairo_pattern_create_linear — Description
  • cairo_pattern_create_radial — Description
  • cairo_pattern_create_rgb — Description
  • cairo_pattern_create_rgba — Description
  • cairo_pattern_get_color_stop_count — Description
  • cairo_pattern_get_color_stop_rgba — Description
  • cairo_pattern_get_extend — Description
  • cairo_pattern_get_filter — Description
  • cairo_pattern_get_linear_points — Description
  • cairo_pattern_get_matrix — Description
  • cairo_pattern_get_radial_circles — Description
  • cairo_pattern_get_rgba — Description
  • cairo_pattern_get_surface — Description
  • cairo_pattern_get_type — Description
  • cairo_pattern_set_extend — Description
  • cairo_pattern_set_filter — Description
  • cairo_pattern_set_matrix — Description
  • cairo_pattern_status — Description
  • cairo_pdf_surface_create — Description
  • cairo_pdf_surface_set_size — Description
  • cairo_ps_get_levels — Description
  • cairo_ps_level_to_string — Description
  • cairo_ps_surface_create — Description
  • cairo_ps_surface_dsc_begin_page_setup — Description
  • cairo_ps_surface_dsc_begin_setup — Description
  • cairo_ps_surface_dsc_comment — Description
  • cairo_ps_surface_get_eps — Description
  • cairo_ps_surface_restrict_to_level — Description
  • cairo_ps_surface_set_eps — Description
  • cairo_ps_surface_set_size — Description
  • cairo_scaled_font_create — Description
  • cairo_scaled_font_extents — Description
  • cairo_scaled_font_get_ctm — Description
  • cairo_scaled_font_get_font_face — Description
  • cairo_scaled_font_get_font_matrix — Description
  • cairo_scaled_font_get_font_options — Description
  • cairo_scaled_font_get_scale_matrix — Description
  • cairo_scaled_font_get_type — Description
  • cairo_scaled_font_glyph_extents — Description
  • cairo_scaled_font_status — Description
  • cairo_scaled_font_text_extents — Description
  • cairo_surface_copy_page — Description
  • cairo_surface_create_similar — Description
  • cairo_surface_finish — Description
  • cairo_surface_flush — Description
  • cairo_surface_get_content — Description
  • cairo_surface_get_device_offset — Description
  • cairo_surface_get_font_options — Description
  • cairo_surface_get_type — Description
  • cairo_surface_mark_dirty_rectangle — Description
  • cairo_surface_mark_dirty — Description
  • cairo_surface_set_device_offset — Description
  • cairo_surface_set_fallback_resolution — Description
  • cairo_surface_show_page — Description
  • cairo_surface_status — Description
  • cairo_surface_write_to_png — Description
  • cairo_svg_surface_create — Description
  • cairo_svg_surface_restrict_to_version — Description
  • cairo_svg_version_to_string — Description
Przykłady
cairo_create
Cairo


Returns a new CairoContext object on the requested surface.

Cairo Funkcje
cairo_font_face_get_type
Cairo Funkcje
PHP Manual

cairo_create

(PECL cairo >= 0.1.0)

cairo_create — Returns a new CairoContext object on the requested surface.

Opis

CairoContext cairo_create ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

Cairo Funkcje
cairo_font_face_get_type
Cairo Funkcje


Description

cairo_create
cairo_font_face_status
Cairo Funkcje
PHP Manual

cairo_font_face_get_type

(PECL cairo >= 0.1.0)

cairo_font_face_get_type — Description

Opis

int cairo_font_face_get_type ( CairoFontFace $fontface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

fontface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_face_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_create
cairo_font_face_status
Cairo Funkcje


Description

cairo_font_face_get_type
cairo_font_options_create
Cairo Funkcje
PHP Manual

cairo_font_face_status

(PECL cairo >= 0.1.0)

cairo_font_face_status — Description

Opis

int cairo_font_face_status ( CairoFontFace $fontface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

fontface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_face_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_face_get_type
cairo_font_options_create
Cairo Funkcje


Description

cairo_font_face_status
cairo_font_options_equal
Cairo Funkcje
PHP Manual

cairo_font_options_create

(PECL cairo >= 0.1.0)

cairo_font_options_create — Description

Opis

CairoFontOptions cairo_font_options_create ( void )

The function description goes here.

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

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_face_status
cairo_font_options_equal
Cairo Funkcje


Description

cairo_font_options_create
cairo_font_options_get_antialias
Cairo Funkcje
PHP Manual

cairo_font_options_equal

(PECL cairo >= 0.1.0)

cairo_font_options_equal — Description

Opis

bool cairo_font_options_equal ( CairoFontOptions $options , CairoFontOptions $other )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

other

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_equal() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_create
cairo_font_options_get_antialias
Cairo Funkcje


Description

cairo_font_options_equal
cairo_font_options_get_hint_metrics
Cairo Funkcje
PHP Manual

cairo_font_options_get_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_get_antialias — Description

Opis

int cairo_font_options_get_antialias ( CairoFontOptions $options )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_get_antialias() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_equal
cairo_font_options_get_hint_metrics
Cairo Funkcje


Description

cairo_font_options_get_antialias
cairo_font_options_get_hint_style
Cairo Funkcje
PHP Manual

cairo_font_options_get_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_metrics — Description

Opis

int cairo_font_options_get_hint_metrics ( CairoFontOptions $options )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_get_hint_metrics() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_get_antialias
cairo_font_options_get_hint_style
Cairo Funkcje


Description

cairo_font_options_get_hint_metrics
cairo_font_options_get_subpixel_order
Cairo Funkcje
PHP Manual

cairo_font_options_get_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_style — Description

Opis

int cairo_font_options_get_hint_style ( CairoFontOptions $options )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_get_hint_style() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_get_hint_metrics
cairo_font_options_get_subpixel_order
Cairo Funkcje


Description

cairo_font_options_get_hint_style
cairo_font_options_hash
Cairo Funkcje
PHP Manual

cairo_font_options_get_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_get_subpixel_order — Description

Opis

int cairo_font_options_get_subpixel_order ( CairoFontOptions $options )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_get_subpixel_order() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_get_hint_style
cairo_font_options_hash
Cairo Funkcje


Description

cairo_font_options_get_subpixel_order
cairo_font_options_merge
Cairo Funkcje
PHP Manual

cairo_font_options_hash

(PECL cairo >= 0.1.0)

cairo_font_options_hash — Description

Opis

int cairo_font_options_hash ( CairoFontOptions $options )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_hash() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_get_subpixel_order
cairo_font_options_merge
Cairo Funkcje


Description

cairo_font_options_hash
cairo_font_options_set_antialias
Cairo Funkcje
PHP Manual

cairo_font_options_merge

(PECL cairo >= 0.1.0)

cairo_font_options_merge — Description

Opis

void cairo_font_options_merge ( CairoFontOptions $options , CairoFontOptions $other )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

other

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_merge() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_hash
cairo_font_options_set_antialias
Cairo Funkcje


Description

cairo_font_options_merge
cairo_font_options_set_hint_metrics
Cairo Funkcje
PHP Manual

cairo_font_options_set_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_set_antialias — Description

Opis

void cairo_font_options_set_antialias ( CairoFontOptions $options , int $antialias )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

antialias

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_set_antialias() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_merge
cairo_font_options_set_hint_metrics
Cairo Funkcje


Description

cairo_font_options_set_antialias
cairo_font_options_set_hint_style
Cairo Funkcje
PHP Manual

cairo_font_options_set_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_metrics — Description

Opis

void cairo_font_options_set_hint_metrics ( CairoFontOptions $options , int $hint_metrics )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

hint_metrics

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_set_hint_metrics() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_set_antialias
cairo_font_options_set_hint_style
Cairo Funkcje


Description

cairo_font_options_set_hint_metrics
cairo_font_options_set_subpixel_order
Cairo Funkcje
PHP Manual

cairo_font_options_set_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_style — Description

Opis

void cairo_font_options_set_hint_style ( CairoFontOptions $options , int $hint_style )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

hint_style

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_set_hint_style() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_set_hint_metrics
cairo_font_options_set_subpixel_order
Cairo Funkcje


Description

cairo_font_options_set_hint_style
cairo_font_options_status
Cairo Funkcje
PHP Manual

cairo_font_options_set_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_set_subpixel_order — Description

Opis

void cairo_font_options_set_subpixel_order ( CairoFontOptions $options , int $subpixel_order )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

subpixel_order

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_set_subpixel_order() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_set_hint_style
cairo_font_options_status
Cairo Funkcje


Description

cairo_font_options_set_subpixel_order
cairo_format_stride_for_width
Cairo Funkcje
PHP Manual

cairo_font_options_status

(PECL cairo >= 0.1.0)

cairo_font_options_status — Description

Opis

int cairo_font_options_status ( CairoFontOptions $options )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_font_options_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_set_subpixel_order
cairo_format_stride_for_width
Cairo Funkcje


Description

cairo_font_options_status
cairo_image_surface_create_for_data
Cairo Funkcje
PHP Manual

cairo_format_stride_for_width

(PECL cairo >= 0.1.0)

cairo_format_stride_for_width — Description

Opis

int cairo_format_stride_for_width ( int $format , int $width )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

format

Description...

width

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_format_stride_for_width() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_font_options_status
cairo_image_surface_create_for_data
Cairo Funkcje


Description

cairo_format_stride_for_width
cairo_image_surface_create_from_png
Cairo Funkcje
PHP Manual

cairo_image_surface_create_for_data

(PECL cairo >= 0.1.0)

cairo_image_surface_create_for_data — Description

Opis

CairoImageSurface cairo_image_surface_create_for_data ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_image_surface_create_for_data() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_format_stride_for_width
cairo_image_surface_create_from_png
Cairo Funkcje


Description

cairo_image_surface_create_for_data
cairo_image_surface_create
Cairo Funkcje
PHP Manual

cairo_image_surface_create_from_png

(PECL cairo >= 0.1.0)

cairo_image_surface_create_from_png — Description

Opis

CairoImageSurface cairo_image_surface_create_from_png ( string $file )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_image_surface_create_from_png() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_image_surface_create_for_data
cairo_image_surface_create
Cairo Funkcje


Description

cairo_image_surface_create_from_png
cairo_image_surface_get_data
Cairo Funkcje
PHP Manual

cairo_image_surface_create

(PECL cairo >= 0.1.0)

cairo_image_surface_create — Description

Opis

CairoImageSurface cairo_image_surface_create ( int $format , int $width , int $height )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

format

Description...

width

Description...

height

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_image_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_image_surface_create_from_png
cairo_image_surface_get_data
Cairo Funkcje


Description

cairo_image_surface_create
cairo_image_surface_get_format
Cairo Funkcje
PHP Manual

cairo_image_surface_get_data

(PECL cairo >= 0.1.0)

cairo_image_surface_get_data — Description

Opis

string cairo_image_surface_get_data ( CairoImageSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_image_surface_get_data() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_image_surface_create
cairo_image_surface_get_format
Cairo Funkcje


Description

cairo_image_surface_get_data
cairo_image_surface_get_height
Cairo Funkcje
PHP Manual

cairo_image_surface_get_format

(PECL cairo >= 0.1.0)

cairo_image_surface_get_format — Description

Opis

int cairo_image_surface_get_format ( CairoImageSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_image_surface_get_format() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_image_surface_get_data
cairo_image_surface_get_height
Cairo Funkcje


Description

cairo_image_surface_get_format
cairo_image_surface_get_stride
Cairo Funkcje
PHP Manual

cairo_image_surface_get_height

(PECL cairo >= 0.1.0)

cairo_image_surface_get_height — Description

Opis

int cairo_image_surface_get_height ( CairoImageSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_image_surface_get_height() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_image_surface_get_format
cairo_image_surface_get_stride
Cairo Funkcje


Description

cairo_image_surface_get_height
cairo_image_surface_get_width
Cairo Funkcje
PHP Manual

cairo_image_surface_get_stride

(PECL cairo >= 0.1.0)

cairo_image_surface_get_stride — Description

Opis

int cairo_image_surface_get_stride ( CairoImageSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_image_surface_get_stride() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_image_surface_get_height
cairo_image_surface_get_width
Cairo Funkcje


Description

cairo_image_surface_get_stride
cairo_matrix_create_scale
Cairo Funkcje
PHP Manual

cairo_image_surface_get_width

(PECL cairo >= 0.1.0)

cairo_image_surface_get_width — Description

Opis

int cairo_image_surface_get_width ( CairoImageSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_image_surface_get_width() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_image_surface_get_stride
cairo_matrix_create_scale
Cairo Funkcje


Alias dla CairoMatrix::initScale

cairo_image_surface_get_width
cairo_matrix_create_translate
Cairo Funkcje
PHP Manual

cairo_matrix_create_scale

(PECL cairo >= 0.1.0)

cairo_matrix_create_scale — Alias dla CairoMatrix::initScale()

Opis

Ta funkcja jest aliasem dla: CairoMatrix::initScale().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

cairo_image_surface_get_width
cairo_matrix_create_translate
Cairo Funkcje


Alias dla CairoMatrix::initTranslate

cairo_matrix_create_scale
cairo_matrix_invert
Cairo Funkcje
PHP Manual

cairo_matrix_create_translate

(PECL cairo >= 0.1.0)

cairo_matrix_create_translate — Alias dla CairoMatrix::initTranslate()

Opis

Ta funkcja jest aliasem dla: CairoMatrix::initTranslate().

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

cairo_matrix_create_scale
cairo_matrix_invert
Cairo Funkcje


Description

cairo_matrix_create_translate
cairo_matrix_multiply
Cairo Funkcje
PHP Manual

cairo_matrix_invert

(PECL cairo >= 0.1.0)

cairo_matrix_invert — Description

Opis

void cairo_matrix_invert ( CairoMatrix $matrix )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

matrix

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_matrix_invert() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_matrix_create_translate
cairo_matrix_multiply
Cairo Funkcje


Description

cairo_matrix_invert
cairo_matrix_rotate
Cairo Funkcje
PHP Manual

cairo_matrix_multiply

(PECL cairo >= 0.1.0)

cairo_matrix_multiply — Description

Opis

CairoMatrix cairo_matrix_multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

matrix1

Description...

matrix2

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_matrix_multiply() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_matrix_invert
cairo_matrix_rotate
Cairo Funkcje


Description

cairo_matrix_multiply
cairo_matrix_transform_distance
Cairo Funkcje
PHP Manual

cairo_matrix_rotate

(PECL cairo >= 0.1.0)

cairo_matrix_rotate — Description

Opis

void cairo_matrix_rotate ( CairoMatrix $matrix , float $radians )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

matrix

Description...

radians

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_matrix_rotate() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_matrix_multiply
cairo_matrix_transform_distance
Cairo Funkcje


Description

cairo_matrix_rotate
cairo_matrix_transform_point
Cairo Funkcje
PHP Manual

cairo_matrix_transform_distance

(PECL cairo >= 0.1.0)

cairo_matrix_transform_distance — Description

Opis

array cairo_matrix_transform_distance ( CairoMatrix $matrix , float $dx , float $dy )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

matrix

Description...

dx

Description...

dy

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_matrix_transform_distance() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_matrix_rotate
cairo_matrix_transform_point
Cairo Funkcje


Description

cairo_matrix_transform_distance
cairo_matrix_translate
Cairo Funkcje
PHP Manual

cairo_matrix_transform_point

(PECL cairo >= 0.1.0)

cairo_matrix_transform_point — Description

Opis

array cairo_matrix_transform_point ( CairoMatrix $matrix , float $dx , float $dy )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

matrix

Description...

dx

Description...

dy

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_matrix_transform_point() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_matrix_transform_distance
cairo_matrix_translate
Cairo Funkcje


Description

cairo_matrix_transform_point
cairo_pattern_add_color_stop_rgb
Cairo Funkcje
PHP Manual

cairo_matrix_translate

(PECL cairo >= 0.1.0)

cairo_matrix_translate — Description

Opis

void cairo_matrix_translate ( CairoMatrix $matrix , float $tx , float $ty )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

matrix

Description...

tx

Description...

ty

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_matrix_translate() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_matrix_transform_point
cairo_pattern_add_color_stop_rgb
Cairo Funkcje


Description

cairo_matrix_translate
cairo_pattern_add_color_stop_rgba
Cairo Funkcje
PHP Manual

cairo_pattern_add_color_stop_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgb — Description

Opis

void cairo_pattern_add_color_stop_rgb ( CairoGradientPattern $pattern , float $offset , float $red , float $green , float $blue )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_add_color_stop_rgb() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_matrix_translate
cairo_pattern_add_color_stop_rgba
Cairo Funkcje


Description

cairo_pattern_add_color_stop_rgb
cairo_pattern_create_for_surface
Cairo Funkcje
PHP Manual

cairo_pattern_add_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgba — Description

Opis

void cairo_pattern_add_color_stop_rgba ( CairoGradientPattern $pattern , float $offset , float $red , float $green , float $blue , float $alpha )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_add_color_stop_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_add_color_stop_rgb
cairo_pattern_create_for_surface
Cairo Funkcje


Description

cairo_pattern_add_color_stop_rgba
cairo_pattern_create_linear
Cairo Funkcje
PHP Manual

cairo_pattern_create_for_surface

(PECL cairo >= 0.1.0)

cairo_pattern_create_for_surface — Description

Opis

CairoPattern cairo_pattern_create_for_surface ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_create_for_surface() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_add_color_stop_rgba
cairo_pattern_create_linear
Cairo Funkcje


Description

cairo_pattern_create_for_surface
cairo_pattern_create_radial
Cairo Funkcje
PHP Manual

cairo_pattern_create_linear

(PECL cairo >= 0.1.0)

cairo_pattern_create_linear — Description

Opis

CairoPattern cairo_pattern_create_linear ( float $x0 , float $y0 , float $x1 , float $y1 )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_create_linear() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_create_for_surface
cairo_pattern_create_radial
Cairo Funkcje


Description

cairo_pattern_create_linear
cairo_pattern_create_rgb
Cairo Funkcje
PHP Manual

cairo_pattern_create_radial

(PECL cairo >= 0.1.0)

cairo_pattern_create_radial — Description

Opis

CairoPattern cairo_pattern_create_radial ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x0

Description...

y0

Description...

r0

Description...

x1

Description...

y1

Description...

r1

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_create_radial() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_create_linear
cairo_pattern_create_rgb
Cairo Funkcje


Description

cairo_pattern_create_radial
cairo_pattern_create_rgba
Cairo Funkcje
PHP Manual

cairo_pattern_create_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgb — Description

Opis

CairoPattern cairo_pattern_create_rgb ( float $red , float $green , float $blue )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

red

Description...

green

Description...

blue

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_create_rgb() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_create_radial
cairo_pattern_create_rgba
Cairo Funkcje


Description

cairo_pattern_create_rgb
cairo_pattern_get_color_stop_count
Cairo Funkcje
PHP Manual

cairo_pattern_create_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgba — Description

Opis

CairoPattern cairo_pattern_create_rgba ( float $red , float $green , float $blue , float $alpha )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

red

Description...

green

Description...

blue

Description...

alpha

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_create_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_create_rgb
cairo_pattern_get_color_stop_count
Cairo Funkcje


Description

cairo_pattern_create_rgba
cairo_pattern_get_color_stop_rgba
Cairo Funkcje
PHP Manual

cairo_pattern_get_color_stop_count

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_count — Description

Opis

int cairo_pattern_get_color_stop_count ( CairoGradientPattern $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_color_stop_count() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_create_rgba
cairo_pattern_get_color_stop_rgba
Cairo Funkcje


Description

cairo_pattern_get_color_stop_count
cairo_pattern_get_extend
Cairo Funkcje
PHP Manual

cairo_pattern_get_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_rgba — Description

Opis

array cairo_pattern_get_color_stop_rgba ( CairoGradientPattern $pattern , int $index )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

index

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_color_stop_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_color_stop_count
cairo_pattern_get_extend
Cairo Funkcje


Description

cairo_pattern_get_color_stop_rgba
cairo_pattern_get_filter
Cairo Funkcje
PHP Manual

cairo_pattern_get_extend

(PECL cairo >= 0.1.0)

cairo_pattern_get_extend — Description

Opis

int cairo_pattern_get_extend ( string $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_extend() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_color_stop_rgba
cairo_pattern_get_filter
Cairo Funkcje


Description

cairo_pattern_get_extend
cairo_pattern_get_linear_points
Cairo Funkcje
PHP Manual

cairo_pattern_get_filter

(PECL cairo >= 0.1.0)

cairo_pattern_get_filter — Description

Opis

int cairo_pattern_get_filter ( CairoSurfacePattern $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_filter() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_extend
cairo_pattern_get_linear_points
Cairo Funkcje


Description

cairo_pattern_get_filter
cairo_pattern_get_matrix
Cairo Funkcje
PHP Manual

cairo_pattern_get_linear_points

(PECL cairo >= 0.1.0)

cairo_pattern_get_linear_points — Description

Opis

array cairo_pattern_get_linear_points ( CairoLinearGradient $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_linear_points() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_filter
cairo_pattern_get_matrix
Cairo Funkcje


Description

cairo_pattern_get_linear_points
cairo_pattern_get_radial_circles
Cairo Funkcje
PHP Manual

cairo_pattern_get_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_get_matrix — Description

Opis

CairoMatrix cairo_pattern_get_matrix ( CairoPattern $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_linear_points
cairo_pattern_get_radial_circles
Cairo Funkcje


Description

cairo_pattern_get_matrix
cairo_pattern_get_rgba
Cairo Funkcje
PHP Manual

cairo_pattern_get_radial_circles

(PECL cairo >= 0.1.0)

cairo_pattern_get_radial_circles — Description

Opis

array cairo_pattern_get_radial_circles ( CairoRadialGradient $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_radial_circles() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_matrix
cairo_pattern_get_rgba
Cairo Funkcje


Description

cairo_pattern_get_radial_circles
cairo_pattern_get_surface
Cairo Funkcje
PHP Manual

cairo_pattern_get_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_rgba — Description

Opis

array cairo_pattern_get_rgba ( CairoSolidPattern $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_radial_circles
cairo_pattern_get_surface
Cairo Funkcje


Description

cairo_pattern_get_rgba
cairo_pattern_get_type
Cairo Funkcje
PHP Manual

cairo_pattern_get_surface

(PECL cairo >= 0.1.0)

cairo_pattern_get_surface — Description

Opis

CairoSurface cairo_pattern_get_surface ( CairoSurfacePattern $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_surface() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_rgba
cairo_pattern_get_type
Cairo Funkcje


Description

cairo_pattern_get_surface
cairo_pattern_set_extend
Cairo Funkcje
PHP Manual

cairo_pattern_get_type

(PECL cairo >= 0.1.0)

cairo_pattern_get_type — Description

Opis

int cairo_pattern_get_type ( CairoPattern $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_surface
cairo_pattern_set_extend
Cairo Funkcje


Description

cairo_pattern_get_type
cairo_pattern_set_filter
Cairo Funkcje
PHP Manual

cairo_pattern_set_extend

(PECL cairo >= 0.1.0)

cairo_pattern_set_extend — Description

Opis

void cairo_pattern_set_extend ( string $pattern , string $extend )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

extend

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_set_extend() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_get_type
cairo_pattern_set_filter
Cairo Funkcje


Description

cairo_pattern_set_extend
cairo_pattern_set_matrix
Cairo Funkcje
PHP Manual

cairo_pattern_set_filter

(PECL cairo >= 0.1.0)

cairo_pattern_set_filter — Description

Opis

void cairo_pattern_set_filter ( CairoSurfacePattern $pattern , int $filter )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

filter

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_set_filter() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_set_extend
cairo_pattern_set_matrix
Cairo Funkcje


Description

cairo_pattern_set_filter
cairo_pattern_status
Cairo Funkcje
PHP Manual

cairo_pattern_set_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_set_matrix — Description

Opis

void cairo_pattern_set_matrix ( CairoPattern $pattern , CairoMatrix $matrix )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

matrix

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_set_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_set_filter
cairo_pattern_status
Cairo Funkcje


Description

cairo_pattern_set_matrix
cairo_pdf_surface_create
Cairo Funkcje
PHP Manual

cairo_pattern_status

(PECL cairo >= 0.1.0)

cairo_pattern_status — Description

Opis

int cairo_pattern_status ( CairoPattern $pattern )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pattern

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pattern_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_set_matrix
cairo_pdf_surface_create
Cairo Funkcje


Description

cairo_pattern_status
cairo_pdf_surface_set_size
Cairo Funkcje
PHP Manual

cairo_pdf_surface_create

(PECL cairo >= 0.1.0)

cairo_pdf_surface_create — Description

Opis

CairoPdfSurface cairo_pdf_surface_create ( string $file , float $width , float $height )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Description...

width

Description...

height

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pdf_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pattern_status
cairo_pdf_surface_set_size
Cairo Funkcje


Description

cairo_pdf_surface_create
cairo_ps_get_levels
Cairo Funkcje
PHP Manual

cairo_pdf_surface_set_size

(PECL cairo >= 0.1.0)

cairo_pdf_surface_set_size — Description

Opis

void cairo_pdf_surface_set_size ( CairoPdfSurface $surface , float $width , float $height )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

width

Description...

height

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_pdf_surface_set_size() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pdf_surface_create
cairo_ps_get_levels
Cairo Funkcje


Description

cairo_pdf_surface_set_size
cairo_ps_level_to_string
Cairo Funkcje
PHP Manual

cairo_ps_get_levels

(PECL cairo >= 0.1.0)

cairo_ps_get_levels — Description

Opis

array cairo_ps_get_levels ( void )

The function description goes here.

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

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_get_levels() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_pdf_surface_set_size
cairo_ps_level_to_string
Cairo Funkcje


Description

cairo_ps_get_levels
cairo_ps_surface_create
Cairo Funkcje
PHP Manual

cairo_ps_level_to_string

(PECL cairo >= 0.1.0)

cairo_ps_level_to_string — Description

Opis

string cairo_ps_level_to_string ( int $level )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

level

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_level_to_string() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_get_levels
cairo_ps_surface_create
Cairo Funkcje


Description

cairo_ps_level_to_string
cairo_ps_surface_dsc_begin_page_setup
Cairo Funkcje
PHP Manual

cairo_ps_surface_create

(PECL cairo >= 0.1.0)

cairo_ps_surface_create — Description

Opis

CairoPsSurface cairo_ps_surface_create ( string $file , float $width , float $height )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Description...

width

Description...

height

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_level_to_string
cairo_ps_surface_dsc_begin_page_setup
Cairo Funkcje


Description

cairo_ps_surface_create
cairo_ps_surface_dsc_begin_setup
Cairo Funkcje
PHP Manual

cairo_ps_surface_dsc_begin_page_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_page_setup — Description

Opis

void cairo_ps_surface_dsc_begin_page_setup ( CairoPsSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_surface_dsc_begin_page_setup() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_surface_create
cairo_ps_surface_dsc_begin_setup
Cairo Funkcje


Description

cairo_ps_surface_dsc_begin_page_setup
cairo_ps_surface_dsc_comment
Cairo Funkcje
PHP Manual

cairo_ps_surface_dsc_begin_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_setup — Description

Opis

void cairo_ps_surface_dsc_begin_setup ( CairoPsSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_surface_dsc_begin_setup() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_surface_dsc_begin_page_setup
cairo_ps_surface_dsc_comment
Cairo Funkcje


Description

cairo_ps_surface_dsc_begin_setup
cairo_ps_surface_get_eps
Cairo Funkcje
PHP Manual

cairo_ps_surface_dsc_comment

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_comment — Description

Opis

void cairo_ps_surface_dsc_comment ( CairoPsSurface $surface , string $comment )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

comment

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_surface_dsc_comment() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_surface_dsc_begin_setup
cairo_ps_surface_get_eps
Cairo Funkcje


Description

cairo_ps_surface_dsc_comment
cairo_ps_surface_restrict_to_level
Cairo Funkcje
PHP Manual

cairo_ps_surface_get_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_get_eps — Description

Opis

bool cairo_ps_surface_get_eps ( CairoPsSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_surface_get_eps() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_surface_dsc_comment
cairo_ps_surface_restrict_to_level
Cairo Funkcje


Description

cairo_ps_surface_get_eps
cairo_ps_surface_set_eps
Cairo Funkcje
PHP Manual

cairo_ps_surface_restrict_to_level

(PECL cairo >= 0.1.0)

cairo_ps_surface_restrict_to_level — Description

Opis

void cairo_ps_surface_restrict_to_level ( CairoPsSurface $surface , int $level )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

level

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_surface_restrict_to_level() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_surface_get_eps
cairo_ps_surface_set_eps
Cairo Funkcje


Description

cairo_ps_surface_restrict_to_level
cairo_ps_surface_set_size
Cairo Funkcje
PHP Manual

cairo_ps_surface_set_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_eps — Description

Opis

void cairo_ps_surface_set_eps ( CairoPsSurface $surface , bool $level )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

level

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_surface_set_eps() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_surface_restrict_to_level
cairo_ps_surface_set_size
Cairo Funkcje


Description

cairo_ps_surface_set_eps
cairo_scaled_font_create
Cairo Funkcje
PHP Manual

cairo_ps_surface_set_size

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_size — Description

Opis

void cairo_ps_surface_set_size ( CairoPsSurface $surface , float $width , float $height )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

width

Description...

height

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_ps_surface_set_size() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_surface_set_eps
cairo_scaled_font_create
Cairo Funkcje


Description

cairo_ps_surface_set_size
cairo_scaled_font_extents
Cairo Funkcje
PHP Manual

cairo_scaled_font_create

(PECL cairo >= 0.1.0)

cairo_scaled_font_create — Description

Opis

CairoScaledFont cairo_scaled_font_create ( CairoFontFace $fontface , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $fontoptions )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

fontface

Description...

matrix

Description...

ctm

Description...

fontoptions

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_ps_surface_set_size
cairo_scaled_font_extents
Cairo Funkcje


Description

cairo_scaled_font_create
cairo_scaled_font_get_ctm
Cairo Funkcje
PHP Manual

cairo_scaled_font_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_extents — Description

Opis

array cairo_scaled_font_extents ( CairoScaledFont $scaledfont )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_create
cairo_scaled_font_get_ctm
Cairo Funkcje


Description

cairo_scaled_font_extents
cairo_scaled_font_get_font_face
Cairo Funkcje
PHP Manual

cairo_scaled_font_get_ctm

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_ctm — Description

Opis

CairoMatrix cairo_scaled_font_get_ctm ( CairoScaledFont $scaledfont )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_get_ctm() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_extents
cairo_scaled_font_get_font_face
Cairo Funkcje


Description

cairo_scaled_font_get_ctm
cairo_scaled_font_get_font_matrix
Cairo Funkcje
PHP Manual

cairo_scaled_font_get_font_face

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_face — Description

Opis

CairoFontFace cairo_scaled_font_get_font_face ( CairoScaledFont $scaledfont )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_get_font_face() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_get_ctm
cairo_scaled_font_get_font_matrix
Cairo Funkcje


Description

cairo_scaled_font_get_font_face
cairo_scaled_font_get_font_options
Cairo Funkcje
PHP Manual

cairo_scaled_font_get_font_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_matrix — Description

Opis

CairoFontOptions cairo_scaled_font_get_font_matrix ( CairoScaledFont $scaledfont )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_get_font_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_get_font_face
cairo_scaled_font_get_font_options
Cairo Funkcje


Description

cairo_scaled_font_get_font_matrix
cairo_scaled_font_get_scale_matrix
Cairo Funkcje
PHP Manual

cairo_scaled_font_get_font_options

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_options — Description

Opis

CairoFontOptions cairo_scaled_font_get_font_options ( CairoScaledFont $scaledfont )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_get_font_options() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_get_font_matrix
cairo_scaled_font_get_scale_matrix
Cairo Funkcje


Description

cairo_scaled_font_get_font_options
cairo_scaled_font_get_type
Cairo Funkcje
PHP Manual

cairo_scaled_font_get_scale_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_scale_matrix — Description

Opis

CairoMatrix cairo_scaled_font_get_scale_matrix ( CairoScaledFont $scaledfont )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_get_scale_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_get_font_options
cairo_scaled_font_get_type
Cairo Funkcje


Description

cairo_scaled_font_get_scale_matrix
cairo_scaled_font_glyph_extents
Cairo Funkcje
PHP Manual

cairo_scaled_font_get_type

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_type — Description

Opis

int cairo_scaled_font_get_type ( CairoScaledFont $scaledfont )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_get_scale_matrix
cairo_scaled_font_glyph_extents
Cairo Funkcje


Description

cairo_scaled_font_get_type
cairo_scaled_font_status
Cairo Funkcje
PHP Manual

cairo_scaled_font_glyph_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_glyph_extents — Description

Opis

array cairo_scaled_font_glyph_extents ( CairoScaledFont $scaledfont , array $glyphs )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

glyphs

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_glyph_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_get_type
cairo_scaled_font_status
Cairo Funkcje


Description

cairo_scaled_font_glyph_extents
cairo_scaled_font_text_extents
Cairo Funkcje
PHP Manual

cairo_scaled_font_status

(PECL cairo >= 0.1.0)

cairo_scaled_font_status — Description

Opis

int cairo_scaled_font_status ( CairoScaledFont $scaledfont )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_glyph_extents
cairo_scaled_font_text_extents
Cairo Funkcje


Description

cairo_scaled_font_status
cairo_surface_copy_page
Cairo Funkcje
PHP Manual

cairo_scaled_font_text_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_text_extents — Description

Opis

array cairo_scaled_font_text_extents ( CairoScaledFont $scaledfont , string $text )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

scaledfont

Description...

text

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_scaled_font_text_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_status
cairo_surface_copy_page
Cairo Funkcje


Description

cairo_scaled_font_text_extents
cairo_surface_create_similar
Cairo Funkcje
PHP Manual

cairo_surface_copy_page

(PECL cairo >= 0.1.0)

cairo_surface_copy_page — Description

Opis

void cairo_surface_copy_page ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_copy_page() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_scaled_font_text_extents
cairo_surface_create_similar
Cairo Funkcje


Description

cairo_surface_copy_page
cairo_surface_finish
Cairo Funkcje
PHP Manual

cairo_surface_create_similar

(PECL cairo >= 0.1.0)

cairo_surface_create_similar — Description

Opis

CairoSurface cairo_surface_create_similar ( CairoSurface $surface , int $content , float $width , float $height )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

content

Description...

width

Description...

height

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_create_similar() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_copy_page
cairo_surface_finish
Cairo Funkcje


Description

cairo_surface_create_similar
cairo_surface_flush
Cairo Funkcje
PHP Manual

cairo_surface_finish

(PECL cairo >= 0.1.0)

cairo_surface_finish — Description

Opis

void cairo_surface_finish ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_finish() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_create_similar
cairo_surface_flush
Cairo Funkcje


Description

cairo_surface_finish
cairo_surface_get_content
Cairo Funkcje
PHP Manual

cairo_surface_flush

(PECL cairo >= 0.1.0)

cairo_surface_flush — Description

Opis

void cairo_surface_flush ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_flush() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_finish
cairo_surface_get_content
Cairo Funkcje


Description

cairo_surface_flush
cairo_surface_get_device_offset
Cairo Funkcje
PHP Manual

cairo_surface_get_content

(PECL cairo >= 0.1.0)

cairo_surface_get_content — Description

Opis

int cairo_surface_get_content ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_get_content() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_flush
cairo_surface_get_device_offset
Cairo Funkcje


Description

cairo_surface_get_content
cairo_surface_get_font_options
Cairo Funkcje
PHP Manual

cairo_surface_get_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_get_device_offset — Description

Opis

array cairo_surface_get_device_offset ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_get_device_offset() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_get_content
cairo_surface_get_font_options
Cairo Funkcje


Description

cairo_surface_get_device_offset
cairo_surface_get_type
Cairo Funkcje
PHP Manual

cairo_surface_get_font_options

(PECL cairo >= 0.1.0)

cairo_surface_get_font_options — Description

Opis

CairoFontOptions cairo_surface_get_font_options ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_get_font_options() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_get_device_offset
cairo_surface_get_type
Cairo Funkcje


Description

cairo_surface_get_font_options
cairo_surface_mark_dirty_rectangle
Cairo Funkcje
PHP Manual

cairo_surface_get_type

(PECL cairo >= 0.1.0)

cairo_surface_get_type — Description

Opis

int cairo_surface_get_type ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_get_font_options
cairo_surface_mark_dirty_rectangle
Cairo Funkcje


Description

cairo_surface_get_type
cairo_surface_mark_dirty
Cairo Funkcje
PHP Manual

cairo_surface_mark_dirty_rectangle

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty_rectangle — Description

Opis

void cairo_surface_mark_dirty_rectangle ( CairoSurface $surface , float $x , float $y , float $width , float $height )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_mark_dirty_rectangle() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_get_type
cairo_surface_mark_dirty
Cairo Funkcje


Description

cairo_surface_mark_dirty_rectangle
cairo_surface_set_device_offset
Cairo Funkcje
PHP Manual

cairo_surface_mark_dirty

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty — Description

Opis

void cairo_surface_mark_dirty ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_mark_dirty() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_mark_dirty_rectangle
cairo_surface_set_device_offset
Cairo Funkcje


Description

cairo_surface_mark_dirty
cairo_surface_set_fallback_resolution
Cairo Funkcje
PHP Manual

cairo_surface_set_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_set_device_offset — Description

Opis

void cairo_surface_set_device_offset ( CairoSurface $surface , float $x , float $y )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

x

Description...

y

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_set_device_offset() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_mark_dirty
cairo_surface_set_fallback_resolution
Cairo Funkcje


Description

cairo_surface_set_device_offset
cairo_surface_show_page
Cairo Funkcje
PHP Manual

cairo_surface_set_fallback_resolution

(PECL cairo >= 0.1.0)

cairo_surface_set_fallback_resolution — Description

Opis

void cairo_surface_set_fallback_resolution ( CairoSurface $surface , float $x , float $y )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

x

Description...

y

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_set_fallback_resolution() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_set_device_offset
cairo_surface_show_page
Cairo Funkcje


Description

cairo_surface_set_fallback_resolution
cairo_surface_status
Cairo Funkcje
PHP Manual

cairo_surface_show_page

(PECL cairo >= 0.1.0)

cairo_surface_show_page — Description

Opis

void cairo_surface_show_page ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_show_page() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_set_fallback_resolution
cairo_surface_status
Cairo Funkcje


Description

cairo_surface_show_page
cairo_surface_write_to_png
Cairo Funkcje
PHP Manual

cairo_surface_status

(PECL cairo >= 0.1.0)

cairo_surface_status — Description

Opis

int cairo_surface_status ( CairoSurface $surface )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_show_page
cairo_surface_write_to_png
Cairo Funkcje


Description

cairo_surface_status
cairo_svg_surface_create
Cairo Funkcje
PHP Manual

cairo_surface_write_to_png

(PECL cairo >= 0.1.0)

cairo_surface_write_to_png — Description

Opis

void cairo_surface_write_to_png ( CairoSurface $surface , resource $stream )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

stream

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_surface_write_to_png() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_status
cairo_svg_surface_create
Cairo Funkcje


Description

cairo_surface_write_to_png
cairo_svg_surface_restrict_to_version
Cairo Funkcje
PHP Manual

cairo_svg_surface_create

(PECL cairo >= 0.1.0)

cairo_svg_surface_create — Description

Opis

CairoSvgSurface cairo_svg_surface_create ( string $file , float $width , float $height )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Description...

width

Description...

height

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_svg_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_surface_write_to_png
cairo_svg_surface_restrict_to_version
Cairo Funkcje


Description

cairo_svg_surface_create
cairo_svg_version_to_string
Cairo Funkcje
PHP Manual

cairo_svg_surface_restrict_to_version

(PECL cairo >= 0.1.0)

cairo_svg_surface_restrict_to_version — Description

Opis

void cairo_svg_surface_restrict_to_version ( CairoSvgSurface $surface , int $version )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

version

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_svg_surface_restrict_to_version() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_svg_surface_create
cairo_svg_version_to_string
Cairo Funkcje


Description

cairo_svg_surface_restrict_to_version
Cairo
Cairo Funkcje
PHP Manual

cairo_svg_version_to_string

(PECL cairo >= 0.1.0)

cairo_svg_version_to_string — Description

Opis

string cairo_svg_version_to_string ( int $version )

The function description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

version

Description...

Zwracane wartości

What is returned on success and failure

Błędy/Wyjątki

When does this function issue E_* level errors, and/or throw exceptions.

Przykłady

Przykład #1 cairo_svg_version_to_string() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

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

...

Zobacz też:

  • related function name here()

cairo_svg_surface_restrict_to_version
Cairo
Cairo Funkcje


The Cairo class

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

Wstęp

Simple class with some static helper methods.

Krótki opis klasy

Cairo {
/* Metody */
public static array availableFonts ( void )
public static array availableSurfaces ( void )
public static string statusToString ( int $status )
public static int version ( void )
public static string versionString ( void )
}

Spis treści

  • Cairo::availableFonts — Retrieves the availables font types
  • Cairo::availableSurfaces — Retrieves all available surfaces
  • Cairo::statusToString — Retrieves the current status as string
  • Cairo::version — Retrives cairo's library version
  • Cairo::versionString — Retrieves cairo version as string
cairo_svg_version_to_string
Cairo::availableFonts
Cairo


Retrieves the availables font types

Cairo
Cairo::availableSurfaces
Cairo
PHP Manual

Cairo::availableFonts

cairo_available_fonts

(PECL cairo >= 0.1.0)

Cairo::availableFonts -- cairo_available_fonts — Retrieves the availables font types

Opis

Styl obiektowy:

public static array Cairo::availableFonts ( void )

Styl proceduralny:

array cairo_available_fonts ( void )

Returns an array with the available font backends

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A list-type array with all available font backends.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* Object Oriented Style */
var_dump(Cairo::availableFonts());

?>

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

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

Przykład #2 Styl proceduralny

<?php

/* Procedural style */
var_dump(cairo_available_fonts());

?>

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

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

Zobacz też:

  • Cairo::availableSurfaces() - Retrieves all available surfaces

Cairo
Cairo::availableSurfaces
Cairo


Retrieves all available surfaces

Cairo::availableFonts
Cairo::statusToString
Cairo
PHP Manual

Cairo::availableSurfaces

cairo_available_surfaces

(PECL cairo >= 0.1.0)

Cairo::availableSurfaces -- cairo_available_surfaces — Retrieves all available surfaces

Opis

Styl obiektowy (method):

public static array Cairo::availableSurfaces ( void )

Styl proceduralny:

array cairo_available_surfaces ( void )

Returns an array with the available surface backends

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A list-type array with all available surface backends.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* Object Oriented style */
var_dump(Cairo::availableSurfaces());

?>

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

array(6) {
  [0]=>
  string(5) "IMAGE"
  [1]=>
  string(3) "PNG"
  [2]=>
  string(3) "PDF"
  [3]=>
  string(2) "PS"
  [4]=>
  string(3) "SVG"
  [5]=>
  string(5) "WIN32"
}

Przykład #2 Styl proceduralny

<?php

/* Procedural style */
var_dump(cairo_available_surfaces());

?>

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

array(6) {
  [0]=>
  string(5) "IMAGE"
  [1]=>
  string(3) "PNG"
  [2]=>
  string(3) "PDF"
  [3]=>
  string(2) "PS"
  [4]=>
  string(3) "SVG"
  [5]=>
  string(5) "WIN32"
}

Zobacz też:

  • Cairo::availableFonts() - Retrieves the availables font types

Cairo::availableFonts
Cairo::statusToString
Cairo


Retrieves the current status as string

Cairo::availableSurfaces
Cairo::version
Cairo
PHP Manual

Cairo::statusToString

cairo_status_to_string

(PECL cairo >= 0.1.0)

Cairo::statusToString -- cairo_status_to_string — Retrieves the current status as string

Opis

Styl obiektowy (method):

public static string Cairo::statusToString ( int $status )

Styl proceduralny:

string cairo_status_to_string ( int $status )

Retrieves the current status as a readable string

Parametry

status

A valid status code given by cairo_status() or CairoContext::status()

Zwracane wartości

A string containing the current status of a CairoContext object

Przykłady

Przykład #1 Styl obiektowy

<?php
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

var_dump(Cairo::statusToString($context->status()));
?>

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

string(7) "success"

Przykład #2 Styl proceduralny

<?php
$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$context = cairo_create($surface);

var_dump(cairo_status_to_string(cairo_status($context)));
?>

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

string(7) "success"

Zobacz też:

  • CairoContext::status() - The status purpose

Cairo::availableSurfaces
Cairo::version
Cairo


Retrives cairo's library version

Cairo::statusToString
Cairo::versionString
Cairo
PHP Manual

Cairo::version

cairo_version

(PECL cairo >= 0.1.0)

Cairo::version -- cairo_version — Retrives cairo's library version

Opis

Styl obiektowy (method):

public static int Cairo::version ( void )

Styl proceduralny:

int cairo_version ( void )

Retrieves the current version of the cairo library as an integer value

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Current Cairo library version integer

Przykłady

Przykład #1 Styl obiektowy

<?php
var_dump(Cairo::version());
?>

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

int(10808)

Przykład #2 Styl proceduralny

<?php
var_dump(cairo_version());
?>

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

int(10808)

Zobacz też:

  • Cairo::versionString() - Retrieves cairo version as string

Cairo::statusToString
Cairo::versionString
Cairo


Retrieves cairo version as string

Cairo::version
CairoContext
Cairo
PHP Manual

Cairo::versionString

cairo_version_string

(PECL cairo >= 0.1.0)

Cairo::versionString -- cairo_version_string — Retrieves cairo version as string

Opis

Styl obiektowy (method):

public static string Cairo::versionString ( void )

Styl proceduralny:

string cairo_version_string ( void )

Retrieves the current cairo library version as a string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Current Cairo library version string

Przykłady

Przykład #1 Styl obiektowy

<?php

var_dump(Cairo::versionString());

?>

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

string(5) "1.8.8"

Przykład #2 Styl proceduralny

<?php

var_dump(cairo_version_string());

?>

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

string(5) "1.8.8"

Zobacz też:

  • Cairo::version() - Retrives cairo's library version

Cairo::version
CairoContext
Cairo


The CairoContext class

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

Wstęp

Context is the main object used when drawing with cairo. To draw with cairo, you create a CairoContext, set the target CairoSurface, and drawing options for the CairoContext, create shapes with functions . like CairoContext::moveTo() and CairoContext::lineTo(), and then draw shapes with CairoContext::stroke() or CairoContext::fill(). Contexts can be pushed to a stack via CairoContext::save(). They may then safely be changed, without loosing the current state. Use CairoContext::restore() to restore to the saved state.

Krótki opis klasy

CairoContext {
/* Metody */
public void appendPath ( CairoPath $path )
public void arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 )
public void arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 )
public void clip ( void )
public array clipExtents ( void )
public void clipPreserve ( void )
public array clipRectangleList ( void )
public void closePath ( void )
public __construct ( CairoSurface $surface )
public void copyPage ( void )
public CairoPath copyPath ( void )
public CairoPath copyPathFlat ( void )
public void curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )
public array deviceToUser ( float $x , float $y )
public array deviceToUserDistance ( float $x , float $y )
public void fill ( void )
public array fillExtents ( void )
public void fillPreserve ( void )
public array fontExtents ( void )
public int getAntialias ( void )
public array getCurrentPoint ( void )
public array getDash ( void )
public int getDashCount ( void )
public int getFillRule ( void )
public void getFontFace ( void )
public void getFontMatrix ( void )
public void getFontOptions ( void )
public void getGroupTarget ( void )
public int getLineCap ( void )
public int getLineJoin ( void )
public float getLineWidth ( void )
public void getMatrix ( void )
public float getMiterLimit ( void )
public int getOperator ( void )
public void getScaledFont ( void )
public void getSource ( void )
public void getTarget ( void )
public float getTolerance ( void )
public void glyphPath ( array $glyphs )
public bool hasCurrentPoint ( void )
public void identityMatrix ( void )
public bool inFill ( string $x , string $y )
public bool inStroke ( string $x , string $y )
public void lineTo ( string $x , string $y )
public void mask ( string $pattern )
public void maskSurface ( string $surface [, string $x [, string $y ]] )
public void moveTo ( string $x , string $y )
public void newPath ( void )
public void newSubPath ( void )
public void paint ( void )
public void paintWithAlpha ( string $alpha )
public array pathExtents ( void )
public void popGroup ( void )
public void popGroupToSource ( void )
public void pushGroup ( void )
public void pushGroupWithContent ( string $content )
public void rectangle ( string $x , string $y , string $width , string $height )
public void relCurveTo ( string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )
public void relLineTo ( string $x , string $y )
public void relMoveTo ( string $x , string $y )
public void resetClip ( void )
public void restore ( void )
public void rotate ( string $angle )
public void save ( void )
public void scale ( string $x , string $y )
public void selectFontFace ( string $family [, string $slant [, string $weight ]] )
public void setAntialias ([ string $antialias ] )
public void setDash ( string $dashes [, string $offset ] )
public void setFillRule ( string $setting )
public void setFontFace ( CairoFontFace $fontface )
public void setFontMatrix ( string $matrix )
public void setFontOptions ( string $fontoptions )
public void setFontSize ( string $size )
public void setLineCap ( string $setting )
public void setLineJoin ( string $setting )
public void setLineWidth ( string $width )
public void setMatrix ( string $matrix )
public void setMiterLimit ( string $limit )
public void setOperator ( string $setting )
public void setScaledFont ( string $scaledfont )
public void setSource ( string $pattern )
public void setSourceRGB ( string $red , string $green , string $blue )
public void setSourceRGBA ( string $red , string $green , string $blue , string $alpha )
public void setSourceSurface ( string $surface [, string $x [, string $y ]] )
public void setTolerance ( string $tolerance )
public void showPage ( void )
public void showText ( string $text )
public int status ( void )
public void stroke ( void )
public array strokeExtents ( void )
public void strokePreserve ( void )
public array textExtents ( string $text )
public void textPath ( string $string )
public void transform ( string $matrix )
public void translate ( string $x , string $y )
public array userToDevice ( string $x , string $y )
public array userToDeviceDistance ( string $x , string $y )
}

Spis treści

  • CairoContext::appendPath — Appends a path to current path
  • CairoContext::arc — Adds a circular arc
  • CairoContext::arcNegative — Adds a negative arc
  • CairoContext::clip — Establishes a new clip region
  • CairoContext::clipExtents — Computes the area inside the current clip
  • CairoContext::clipPreserve — Establishes a new clip region from the current clip
  • CairoContext::clipRectangleList — Retrieves the current clip as a list of rectangles
  • CairoContext::closePath — Closes the current path
  • CairoContext::__construct — Creates a new CairoContext
  • CairoContext::copyPage — Emits the current page
  • CairoContext::copyPath — Creates a copy of the current path
  • CairoContext::copyPathFlat — Gets a flattened copy of the current path
  • CairoContext::curveTo — Adds a curve
  • CairoContext::deviceToUser — Transform a coordinate
  • CairoContext::deviceToUserDistance — Transform a distance
  • CairoContext::fill — Fills the current path
  • CairoContext::fillExtents — Computes the filled area
  • CairoContext::fillPreserve — Fills and preserve the current path
  • CairoContext::fontExtents — Get the font extents
  • CairoContext::getAntialias — Retrives the current antialias mode
  • CairoContext::getCurrentPoint — The getCurrentPoint purpose
  • CairoContext::getDash — The getDash purpose
  • CairoContext::getDashCount — The getDashCount purpose
  • CairoContext::getFillRule — The getFillRule purpose
  • CairoContext::getFontFace — The getFontFace purpose
  • CairoContext::getFontMatrix — The getFontMatrix purpose
  • CairoContext::getFontOptions — The getFontOptions purpose
  • CairoContext::getGroupTarget — The getGroupTarget purpose
  • CairoContext::getLineCap — The getLineCap purpose
  • CairoContext::getLineJoin — The getLineJoin purpose
  • CairoContext::getLineWidth — The getLineWidth purpose
  • CairoContext::getMatrix — The getMatrix purpose
  • CairoContext::getMiterLimit — The getMiterLimit purpose
  • CairoContext::getOperator — The getOperator purpose
  • CairoContext::getScaledFont — The getScaledFont purpose
  • CairoContext::getSource — The getSource purpose
  • CairoContext::getTarget — The getTarget purpose
  • CairoContext::getTolerance — The getTolerance purpose
  • CairoContext::glyphPath — The glyphPath purpose
  • CairoContext::hasCurrentPoint — The hasCurrentPoint purpose
  • CairoContext::identityMatrix — The identityMatrix purpose
  • CairoContext::inFill — The inFill purpose
  • CairoContext::inStroke — The inStroke purpose
  • CairoContext::lineTo — The lineTo purpose
  • CairoContext::mask — The mask purpose
  • CairoContext::maskSurface — The maskSurface purpose
  • CairoContext::moveTo — The moveTo purpose
  • CairoContext::newPath — The newPath purpose
  • CairoContext::newSubPath — The newSubPath purpose
  • CairoContext::paint — The paint purpose
  • CairoContext::paintWithAlpha — The paintWithAlpha purpose
  • CairoContext::pathExtents — The pathExtents purpose
  • CairoContext::popGroup — The popGroup purpose
  • CairoContext::popGroupToSource — The popGroupToSource purpose
  • CairoContext::pushGroup — The pushGroup purpose
  • CairoContext::pushGroupWithContent — The pushGroupWithContent purpose
  • CairoContext::rectangle — The rectangle purpose
  • CairoContext::relCurveTo — The relCurveTo purpose
  • CairoContext::relLineTo — The relLineTo purpose
  • CairoContext::relMoveTo — The relMoveTo purpose
  • CairoContext::resetClip — The resetClip purpose
  • CairoContext::restore — The restore purpose
  • CairoContext::rotate — The rotate purpose
  • CairoContext::save — The save purpose
  • CairoContext::scale — The scale purpose
  • CairoContext::selectFontFace — The selectFontFace purpose
  • CairoContext::setAntialias — The setAntialias purpose
  • CairoContext::setDash — The setDash purpose
  • CairoContext::setFillRule — The setFillRule purpose
  • CairoContext::setFontFace — The setFontFace purpose
  • CairoContext::setFontMatrix — The setFontMatrix purpose
  • CairoContext::setFontOptions — The setFontOptions purpose
  • CairoContext::setFontSize — The setFontSize purpose
  • CairoContext::setLineCap — The setLineCap purpose
  • CairoContext::setLineJoin — The setLineJoin purpose
  • CairoContext::setLineWidth — The setLineWidth purpose
  • CairoContext::setMatrix — The setMatrix purpose
  • CairoContext::setMiterLimit — The setMiterLimit purpose
  • CairoContext::setOperator — The setOperator purpose
  • CairoContext::setScaledFont — The setScaledFont purpose
  • CairoContext::setSource — The setSource purpose
  • CairoContext::setSourceRGB — The setSourceRGB purpose
  • CairoContext::setSourceRGBA — The setSourceRGBA purpose
  • CairoContext::setSourceSurface — The setSourceSurface purpose
  • CairoContext::setTolerance — The setTolerance purpose
  • CairoContext::showPage — The showPage purpose
  • CairoContext::showText — The showText purpose
  • CairoContext::status — The status purpose
  • CairoContext::stroke — The stroke purpose
  • CairoContext::strokeExtents — The strokeExtents purpose
  • CairoContext::strokePreserve — The strokePreserve purpose
  • CairoContext::textExtents — The textExtents purpose
  • CairoContext::textPath — The textPath purpose
  • CairoContext::transform — The transform purpose
  • CairoContext::translate — The translate purpose
  • CairoContext::userToDevice — The userToDevice purpose
  • CairoContext::userToDeviceDistance — The userToDeviceDistance purpose
Cairo::versionString
CairoContext::appendPath
Cairo


Appends a path to current path

CairoContext
CairoContext::arc
CairoContext
PHP Manual

CairoContext::appendPath

cairo_append_path

(PECL cairo >= 0.1.0)

CairoContext::appendPath -- cairo_append_path — Appends a path to current path

Opis

Styl obiektowy (method):

public void CairoContext::appendPath ( CairoPath $path )

Styl proceduralny:

void cairo_append_path ( CairoContext $context , CairoPath $path )

Appends the path onto the current path. The path may be either the return value from one of CairoContext::copyPath() or CairoContext::copyPathFlat();

if path is not a valid CairoPath instance a CairoException will be thrown

Parametry

context

CairoContext object

path

CairoPath object

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$path = $context->copyPath();

$context->appendPath($path);

?>

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

$path = cairo_copy_path($context);

cairo_append_path($context, $path);

?>

Zobacz też:

  • CairoPath
  • CairoContext::copyPath() - Creates a copy of the current path
  • CairoContext::copyPathFlat() - Gets a flattened copy of the current path

CairoContext
CairoContext::arc
CairoContext


Adds a circular arc

CairoContext::appendPath
CairoContext::arcNegative
CairoContext
PHP Manual

CairoContext::arc

cairo_arc

(PECL cairo >= 0.1.0)

CairoContext::arc -- cairo_arc — Adds a circular arc

Opis

Styl obiektowy (method):

public void CairoContext::arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 )

Styl proceduralny:

void cairo_arc ( CairoContext $context , float $x , float $y , float $radius , float $angle1 , float $angle2 )

Adds a circular arc of the given radius to the current path. The arc is centered at (x, y), begins at angle1 and proceeds in the direction of increasing angles to end at angle2. If angle2 is less than angle1 it will be progressively increased by 2*M_PI until it is greater than angle1. If there is a current point, an initial line segment will be added to the path to connect the current point to the beginning of the arc. If this initial line is undesired, it can be avoided by calling CairoContext::newSubPath() or procedural cairo_new_sub_path() before calling CairoContext::arc() or cairo_arc(). Angles are measured in radians. An angle of 0.0 is in the direction of the positive X axis (in user space). An angle of M_PI/2.0 radians (90 degrees) is in the direction of the positive Y axis (in user space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction. (To convert from degrees to radians, use degrees * (M_PI / 180.).) This function gives the arc in the direction of increasing angles; see CairoContext::arcNegative() or cairo_arc_negative() to get the arc in the direction of decreasing angles.

Parametry

context

A valid CairoContext object

x

x position

y

y position

radius

Radius of the arc

angle1

start angle

angle2

end angle

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setLineWidth(1);
$c->setSourceRgb(1, 1, 1);

for ($r = 50; $r > 0; $r -= 10) {
 $c->arc(50, 50, $r, 0, 2 * M_PI);
 $c->stroke();
 $c->fill();
}

$s->writeToPng(dirname(__FILE__) . '/CairoContext__arc.png');
?>

Przykład #2 Styl proceduralny

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_set_line_width($c, 1);

for ($r = 50; $r > 0; $r -= 10) {
 cairo_arc($c, 50, 50, $r, 0, 2 * M_PI);
 cairo_stroke($c);
 cairo_fill($c);
}

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_arc.png');
?>

Zobacz też:

  • CairoContext::arcNegative() - Adds a negative arc

CairoContext::appendPath
CairoContext::arcNegative
CairoContext


Adds a negative arc

CairoContext::arc
CairoContext::clip
CairoContext
PHP Manual

CairoContext::arcNegative

cairo_arc_negative

(PECL cairo >= 0.1.0)

CairoContext::arcNegative -- cairo_arc_negative — Adds a negative arc

Opis

Styl obiektowy (method):

public void CairoContext::arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 )

Styl proceduralny:

void cairo_arc_negative ( CairoContext $context , float $x , float $y , float $radius , float $angle1 , float $angle2 )

Adds a circular arc of the given radius to the current path. The arc is centered at (x, y), begins at angle1 and proceeds in the direction of decreasing angles to end at angle2. If angle2 is greater than angle1 it will be progressively decreased by 2*M_PI until it is less than angle1. See CairoContext::arc() or cairo_arc() for more details. This function differs only in the direction of the arc between the two angles.

Parametry

context

A valid CairoContext object

x

double x position

y

double y position

radius

The radius of the desired negative arc

angle1

Start angle of the arc

angle2

End angle of the arc

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setLineWidth(1);
$c->setSourceRgb(1, 1, 1);

for ($r = 50; $r > 0; $r -= 10) {
 $c->arcNegative(50, 50, $r, 2 * M_PI, 0);
 $c->stroke();
 $c->fill();
}

$s->writeToPng(dirname(__FILE__) . '/CairoContext__arcNegative.png');
?>

Przykład #2 Styl proceduralny

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_set_line_width($c, 1);

for ($r = 50; $r > 0; $r -= 10) {
 cairo_arc_negative($c, 50, 50, $r, 2 * M_PI, 0);
 cairo_stroke($c);
 cairo_fill($c);
}

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_arc_negative.png');
?>

Zobacz też:

  • CairoContext::arc() - Adds a circular arc

CairoContext::arc
CairoContext::clip
CairoContext


Establishes a new clip region

CairoContext::arcNegative
CairoContext::clipExtents
CairoContext
PHP Manual

CairoContext::clip

cairo_clip

(PECL cairo >= 0.1.0)

CairoContext::clip -- cairo_clip — Establishes a new clip region

Opis

Styl obiektowy (method):

public void CairoContext::clip ( void )

Styl proceduralny:

void cairo_clip ( CairoContext $context )

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by CairoContext::fill() or cairo_fill() and according to the current fill rule (see CairoContext::setFillRule() or cairo_set_fill_rule()).

After CairoContext::clip() or cairo_clip(), the current path will be cleared from the cairo context.

The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling  CairoContext::clip() or cairo_clip()
can only make the clip region smaller, never larger. But the current clip is part of the
graphics state, so a temporary restriction of the clip region can be achieved by calling
 CairoContext::clip() or cairo_clip() within a
 CairoContext::save()/ CairoContext::restore() or
cairo_save()/cairo_restore() pair.
The only other means of increasing the size of the clip region is
 CairoContext::resetClip() or procedural cairo_reset_clip().

Parametry

context

A valid CairoContext object

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clip();

?>

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip($context);

?>

Zobacz też:

  • CairoContext::resetClip() - The resetClip purpose
  • cairo_reset_clip() - The resetClip purpose

CairoContext::arcNegative
CairoContext::clipExtents
CairoContext


Computes the area inside the current clip

CairoContext::clip
CairoContext::clipPreserve
CairoContext
PHP Manual

CairoContext::clipExtents

cairo_clip_extents

(PECL cairo >= 0.1.0)

CairoContext::clipExtents -- cairo_clip_extents — Computes the area inside the current clip

Opis

Styl obiektowy (method):

public array CairoContext::clipExtents ( void )

Styl proceduralny:

array cairo_clip_extents ( CairoContext $context )

Computes a bounding box in user coordinates covering the area inside the current clip.

Parametry

context

A valid CairoContext object

Zwracane wartości

An array containing the (float)x1, (float)y1, (float)x2, (float)y2, coordinates covering the area inside the current clip

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipExtents());
?>

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

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_extents($context));

?>

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

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

Zobacz też:

  • CairoContext::clip() - Establishes a new clip region

CairoContext::clip
CairoContext::clipPreserve
CairoContext


Establishes a new clip region from the current clip

CairoContext::clipExtents
CairoContext::clipRectangleList
CairoContext
PHP Manual

CairoContext::clipPreserve

cairo_clip_preserve

(PECL cairo >= 0.1.0)

CairoContext::clipPreserve -- cairo_clip_preserve — Establishes a new clip region from the current clip

Opis

Styl obiektowy (method):

public void CairoContext::clipPreserve ( void )

Styl proceduralny:

void cairo_clip_preserve ( CairoContext $context )

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by Context.fill() and according to the current FILL RULE (see CairoContext::setFillRule() or cairo_set_fill_rule()).

Unlike CairoContext::clip(), CairoContext::clipPreserve() preserves the path within the Context. The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling CairoContext::clipPreserve() can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling CairoContext::clipPreserve() within a CairoContext::save()/ CairoContext::restore() pair. The only other means of increasing the size of the clip region is CairoContext::resetClip().

Parametry

context

A valid CairoContext object

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clipPreserve();

?>

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip_preserve($context);

?>

Zobacz też:

  • CairoContext::save() - The save purpose
  • CairoContext::restore() - The restore purpose
  • CairoContext::resetClip() - The resetClip purpose

CairoContext::clipExtents
CairoContext::clipRectangleList
CairoContext


Retrieves the current clip as a list of rectangles

CairoContext::clipPreserve
CairoContext::closePath
CairoContext
PHP Manual

CairoContext::clipRectangleList

cairo_clip_rectangle_list

(PECL cairo >= 0.1.0)

CairoContext::clipRectangleList -- cairo_clip_rectangle_list — Retrieves the current clip as a list of rectangles

Opis

Styl obiektowy (method):

public array CairoContext::clipRectangleList ( void )

Styl proceduralny:

array cairo_clip_rectangle_list ( CairoContext $context )

Returns a list-type array with the current clip region as a list of rectangles in user coordinates

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Zwracane wartości

An array of user-space represented rectangles for the current clip

(The status in the list may be CAIRO_STATUS_CLIP_NOT_REPRESENTABLE to indicate that the clip region cannot be represented as a list of user-space rectangles. The status may have other values to indicate other errors.)

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipRectangleList());

?>

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

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_rectangle_list($context));

?>

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

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

Zobacz też:

  • Classname::Method()

CairoContext::clipPreserve
CairoContext::closePath
CairoContext


Closes the current path

CairoContext::clipRectangleList
CairoContext::__construct
CairoContext
PHP Manual

CairoContext::closePath

cairo_close_path

(PECL cairo >= 0.1.0)

CairoContext::closePath -- cairo_close_path — Closes the current path

Opis

Styl obiektowy (method):

public void CairoContext::closePath ( void )

Styl proceduralny:

void cairo_close_path ( CairoContext $context )

Adds a line segment to the path from the current point to the beginning of the current sub-path, (the most recent point passed to CairoContext::moveTo()), and closes this sub-path. After this call the current point will be at the joined endpoint of the sub-path.

The behavior of close_path() is distinct from simply calling CairoContext::lineTo() with the equivalent coordinate in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, there is a line join connecting the final and initial segments of the sub-path.

If there is no current point before the call to CairoContext::closePath(), this function will have no effect.

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->closePath();

?>

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_close_path($context);

?>

Zobacz też:

  • CairoContext::copyPath() - Creates a copy of the current path

CairoContext::clipRectangleList
CairoContext::__construct
CairoContext


Creates a new CairoContext

CairoContext::closePath
CairoContext::copyPage
CairoContext
PHP Manual

CairoContext::__construct

(PECL cairo >= 0.1.0)

CairoContext::__construct — Creates a new CairoContext

Opis

public CairoContext::__construct ( CairoSurface $surface )

Creates a new CairoContext object to draw

Parametry

surface

A valid CairoSurface like CairoImageSurface or CairoPdfSurface

Zwracane wartości

A CairoContext

Przykłady

Przykład #1 CairoContext::__construct() example

<?php
// The surface to work on
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

// Create a new CairoContext for the CairoSurface
$context = new CairoContext($surface);

?>

Zobacz też:

  • Cairo::Method()

CairoContext::closePath
CairoContext::copyPage
CairoContext


Emits the current page

CairoContext::__construct
CairoContext::copyPath
CairoContext
PHP Manual

CairoContext::copyPage

cairo_copy_page

(PECL cairo >= 0.1.0)

CairoContext::copyPage -- cairo_copy_page — Emits the current page

Opis

Styl obiektowy (method):

public void CairoContext::copyPage ( void )

Styl proceduralny:

void cairo_copy_page ( CairoContext $context )

Emits the current page for backends that support multiple pages, but doesn’t clear it, so, the contents of the current page will be retained for the next page too. Use CairoContext::showPage() if you want to get an empty page after the emission.

This is a convenience function that simply calls CairoSurface::copyPage() on CairoContext’s target.

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->copyPage();

?>

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_copy_page($context);

?>

Zobacz też:

  • CairoContext::showPage() - The showPage purpose
  • CairoSurface::copyPage() - The copyPage purpose

CairoContext::__construct
CairoContext::copyPath
CairoContext


Creates a copy of the current path

CairoContext::copyPage
CairoContext::copyPathFlat
CairoContext
PHP Manual

CairoContext::copyPath

cairo_copy_path

(PECL cairo >= 0.1.0)

CairoContext::copyPath -- cairo_copy_path — Creates a copy of the current path

Opis

Styl obiektowy (method):

public CairoPath CairoContext::copyPath ( void )

Styl proceduralny:

CairoPath cairo_copy_path ( CairoContext $context )

Creates a copy of the current path and returns it to the user as a CairoPath. See CairoPath for hints on how to iterate over the returned data structure.

This function will always return a valid CairoPath object, but the result will have no data, if either of the following conditions hold:

  • 1. If there is insufficient memory to copy the path. In this case CairoPath->status will be set to CAIRO_STATUS_NO_MEMORY.
  • 2. If context is already in an error state. In this case CairoPath->status will contain the same status that would be returned by cairo_status().
In either case, CairoPath->status will be set to CAIRO_STATUS_NO_MEMORY (regardless of what the error status in cr might have been).

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Zwracane wartości

A copy of the current CairoPath in the context

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPath())

?>

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

object(CairoPath)#3 (0) {
}

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path($context));

?>

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

object(CairoPath)#3 (0) {
}

Zobacz też:

  • CairoContext::closePath() - Closes the current path

CairoContext::copyPage
CairoContext::copyPathFlat
CairoContext


Gets a flattened copy of the current path

CairoContext::copyPath
CairoContext::curveTo
CairoContext
PHP Manual

CairoContext::copyPathFlat

cairo_copy_path_flat

(PECL cairo >= 0.1.0)

CairoContext::copyPathFlat -- cairo_copy_path_flat — Gets a flattened copy of the current path

Opis

Styl obiektowy (method):

public CairoPath CairoContext::copyPathFlat ( void )

Styl proceduralny:

CairoPath cairo_copy_path_flat ( CairoContext $context )

Gets a flattened copy of the current path and returns it to the user as a CairoPath.

This function is like CairoContext::copyPath() except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value). That is, the result is guaranteed to not have any elements of type CAIRO_PATH_CURVE_TO which will instead be replaced by a series of CAIRO_PATH_LINE_TO elements.

Parametry

context

A CairoContext object

Zwracane wartości

A copy of the current path

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPathFlat());

?>

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

object(CairoPath)#3 (0) {
}

Przykład #2 Styl proceduralny

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path_flat($context));

?>

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

object(CairoPath)#3 (0) {
}

Zobacz też:

  • CairoContext::copyPath() - Creates a copy of the current path
  • CairoContext::closePath() - Closes the current path

CairoContext::copyPath
CairoContext::curveTo
CairoContext


Adds a curve

CairoContext::copyPathFlat
CairoContext::deviceToUser
CairoContext
PHP Manual

CairoContext::curveTo

cairo_curve_to

(PECL cairo >= 0.1.0)

CairoContext::curveTo -- cairo_curve_to — Adds a curve

Opis

Styl obiektowy (method):

public void CairoContext::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Styl proceduralny:

void cairo_curve_to ( CairoContext $context , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Adds a cubic Bezier spline to the path from the current point to position x3 ,y3 in user-space coordinates, using x1, y1 and x2, y2 as the control points. After this call the current point will be x3, y3.

If there is no current point before the call to CairoContext::curveTo() this function will behave as if preceded by a call to CairoContext::moveTo() (x1, y1).

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x1

First control point in the x axis for the curve

y1

First control point in the y axis for the curve

x2

Second control point in x axis for the curve

y2

Second control point in y axis for the curve

x3

Final point in the x axis for the curve

y3

Final point in the y axis for the curve

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php
$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);

$c->paint();

$c->moveTo(10, 50);
$c->setLineWidth(5);
$c->setSourceRgb(.1, 0, 1);
$c->curveTo(20, 80, 80, 20, 90, 50);
$c->stroke();

$s->writeToPng(dirname(__FILE__) . '/curveTo.png');
?>

Przykład #2 Styl proceduralny

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);

cairo_paint($c);

cairo_move_to($c, 10, 50);
cairo_set_line_width($c, 5);
cairo_set_source_rgb($c, .1, 0, 1);
cairo_curve_to($c, 20, 80, 80, 20, 90, 50);
cairo_stroke($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/curve_to.png');
?>

Zobacz też:

  • CairoContext::moveTo() - The moveTo purpose

CairoContext::copyPathFlat
CairoContext::deviceToUser
CairoContext


Transform a coordinate

CairoContext::curveTo
CairoContext::deviceToUserDistance
CairoContext
PHP Manual

CairoContext::deviceToUser

cairo_device_to_user

(PECL cairo >= 0.1.0)

CairoContext::deviceToUser -- cairo_device_to_user — Transform a coordinate

Opis

Styl obiektowy (method):

public array CairoContext::deviceToUser ( float $x , float $y )

Styl proceduralny:

array cairo_device_to_user ( CairoContext $context , float $x , float $y )

Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM).

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x

x value of the coordinate

y

y value of the coordinate

Zwracane wartości

An array containing the x and y coordinates in the user-space

Zobacz też:

  • CairoContext::deviceToUserDistance() - Transform a distance

CairoContext::curveTo
CairoContext::deviceToUserDistance
CairoContext


Transform a distance

CairoContext::deviceToUser
CairoContext::fill
CairoContext
PHP Manual

CairoContext::deviceToUserDistance

cairo_device_to_user_distance

(PECL cairo >= 0.1.0)

CairoContext::deviceToUserDistance -- cairo_device_to_user_distance — Transform a distance

Opis

Styl obiektowy (method):

public array CairoContext::deviceToUserDistance ( float $x , float $y )

Styl proceduralny:

array cairo_device_to_user_distance ( CairoContext $context , float $x , float $y )

Transform a distance vector from device space to user space. This function is similar to CairoContext::deviceToUser() or cairo_device_to_user() except that the translation components of the inverse Cairo Transformation Matrix will be ignored when transforming (x,y).

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x

X component of a distance vector

y

Y component of a distance vector

Zwracane wartości

Returns an array with the x and y values of a distance vector in the user-space

Zobacz też:

  • CairoContext::deviceToUser() - Transform a coordinate

CairoContext::deviceToUser
CairoContext::fill
CairoContext


Fills the current path

CairoContext::deviceToUserDistance
CairoContext::fillExtents
CairoContext
PHP Manual

CairoContext::fill

cairo_fill

(PECL cairo >= 0.1.0)

CairoContext::fill -- cairo_fill — Fills the current path

Opis

Styl obiektowy (method):

public void CairoContext::fill ( void )

Styl proceduralny:

void cairo_fill ( CairoContext $context )

A drawing operator that fills the current path according to the current CairoFillRule, (each sub-path is implicitly closed before being filled). After CairoContext::fill() or cairo_fill(), the current path will be cleared from the CairoContext.

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setSourceRgb(1, 1, 1);
$c->rectangle(0, 0, 50, 50);
$c->fill();
$c->setSourceRgb(0, 1, 0);
$c->rectangle(50, 50, 50, 50);
$c->fill();

$s->writeToPng(dirname(__FILE__) . '/CairoContext_fill.png');

?>

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

...

Przykład #2 Styl proceduralny

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_rectangle($c, 0, 0, 50, 50);
cairo_fill($c);
cairo_set_source_rgb($c, 0, 1, 0);
cairo_rectangle($c, 50, 50, 50, 50);
cairo_fill($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_fill.png');

?>

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

...

Zobacz też:

  • CairoContext::setFillRule() - The setFillRule purpose
  • ContextContext::fillPreserve()
  • CairoFillRule

CairoContext::deviceToUserDistance
CairoContext::fillExtents
CairoContext


Computes the filled area

CairoContext::fill
CairoContext::fillPreserve
CairoContext
PHP Manual

CairoContext::fillExtents

cairo_fill_extents

(PECL cairo >= 0.1.0)

CairoContext::fillExtents -- cairo_fill_extents — Computes the filled area

Opis

Styl obiektowy (method):

public array CairoContext::fillExtents ( void )

Styl proceduralny:

array cairo_fill_extents ( CairoContext $context )

Computes a bounding box in user coordinates covering the area that would be affected, (the “inked” area), by a CairoContext::fill() operation given the current path and fill parameters. If the current path is empty, returns an empty rectangle (0,0,0,0). Surface dimensions and clipping are not taken into account.

Contrast with CairoContext::pathExtents(), which is similar, but returns non-zero extents for some paths with no inked area, (such as a simple line segment).

Note that CairoContext::fillExtents() must necessarily do more work to compute the precise inked areas in light of the fill rule, so CairoContext::pathExtents() may be more desirable for sake of performance if the non-inked path extents are desired.

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Zwracane wartości

An array with the coordinates of the afected area

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • CairoContext::fill() - Fills the current path
  • CairoContext::setFillRule() - The setFillRule purpose
  • CairoContext::fillPreserve() - Fills and preserve the current path

CairoContext::fill
CairoContext::fillPreserve
CairoContext


Fills and preserve the current path

CairoContext::fillExtents
CairoContext::fontExtents
CairoContext
PHP Manual

CairoContext::fillPreserve

cairo_fill_preserve

(PECL cairo >= 0.1.0)

CairoContext::fillPreserve -- cairo_fill_preserve — Fills and preserve the current path

Opis

Styl obiektowy (method):

public void CairoContext::fillPreserve ( void )

Styl proceduralny:

void cairo_fill_preserve ( CairoContext $context )

A drawing operator that fills the current path according to the current CairoFillRule, (each sub-path is implicitly closed before being filled). Unlike CairoContext::fill(), CairoContext::fillPreserve() (Procedural cairo_fill(), cairo_fill_preserve(), respectively) preserves the path within the Context.

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • CairoContext::setFillRule() - The setFillRule purpose
  • CairoContext::fill() - Fills the current path

CairoContext::fillExtents
CairoContext::fontExtents
CairoContext


Get the font extents

CairoContext::fillPreserve
CairoContext::getAntialias
CairoContext
PHP Manual

CairoContext::fontExtents

cairo_font_extents

(PECL cairo >= 0.1.0)

CairoContext::fontExtents -- cairo_font_extents — Get the font extents

Opis

Styl obiektowy (method):

public array CairoContext::fontExtents ( void )

Styl proceduralny:

array cairo_font_extents ( CairoContext $context )

Gets the font extents for the currently selected font.

Parametry

context

Description...

Zwracane wartości

An array containing the font extents for the current font.

Przykłady

Przykład #1 Styl obiektowy

<?php

$sur = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$con = new CairoContext($sur);

var_dump($con->fontExtents());

?>

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

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

Przykład #2 Styl proceduralny

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

var_dump(cairo_font_extents($con));

?>

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

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

Zobacz też:

  • Classname::Method()

CairoContext::fillPreserve
CairoContext::getAntialias
CairoContext


Retrives the current antialias mode

CairoContext::fontExtents
CairoContext::getCurrentPoint
CairoContext
PHP Manual

CairoContext::getAntialias

cairo_get_antialias

(PECL cairo >= 0.1.0)

CairoContext::getAntialias -- cairo_get_antialias — Retrives the current antialias mode

Opis

Styl obiektowy (method):

public int CairoContext::getAntialias ( void )

Styl proceduralny:

int cairo_get_antialias ( CairoContext $context )

Returns the current CairoAntialias mode, as set by CairoContext::setAntialias().

Parametry

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Zwracane wartości

The current CairoAntialias mode.

Przykłady

Przykład #1 Styl obiektowy

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

$context->setAntialias(CairoAntialias::MODE_SUBPIXEL);

var_dump($context->getAntialias());

?>

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

int(3)

Przykład #2 Styl proceduralny

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

cairo_set_antialias($con, CAIRO_ANTIALIAS_SUBPIXEL);

var_dump(cairo_get_antialias($con));

?>

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

int(3)

Zobacz też:

  • CairoContext::setAntialias() - The setAntialias purpose
  • CairoAntialias

CairoContext::fontExtents
CairoContext::getCurrentPoint
CairoContext


The getCurrentPoint purpose

CairoContext::getAntialias
CairoContext::getDash
CairoContext
PHP Manual

CairoContext::getCurrentPoint

cairo_get_current_point

(PECL cairo >= 0.1.0)

CairoContext::getCurrentPoint -- cairo_get_current_point — The getCurrentPoint purpose

Opis

Styl obiektowy

public array CairoContext::getCurrentPoint ( void )

Styl proceduralny

array cairo_get_current_point ( CairoContext $context )

Gets the current point of the current path, which is conceptually the final point reached by the path so far.

The current point is returned in the user-space coordinate system. If there is no defined current point or if cr is in an error status, x and y will both be set to 0.0. It is possible to check this in advance with CairoContext::hasCurrentPoint().

Most path construction functions alter the current point. See the following for details on how they affect the current point:  CairoContext::newPath(),
 CairoContext::newSubPath(),  CairoContext::appendPath(),  CairoContext::closePath(),  CairoContext::moveTo(),
 CairoContext::lineTo(),  CairoContext::curveTo(),  CairoContext::relMoveTo(),
 CairoContext::relLineTo(),  CairoContext::relCurveTo(),
 CairoContext::arc(),  CairoContext::arcNegative(),  CairoContext::rectangle(),
 CairoContext::textPath(),  CairoContext::glyphPath().

Some functions use and alter the current point but do not otherwise change current path: CairoContext::showText().

Some functions unset the current path and as a result, current point: CairoContext::fill(), CairoContext::stroke().

Parametry

context

A valid CairoContext object.

Zwracane wartości

An array containing the x (index 0) and y (index 1) coordinates of the current point.

Przykłady

Przykład #1 Styl obiektowy

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->moveTo(10, 10);

var_dump($c->getCurrentPoint());

?>

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

array(2) {
  [0]=>
  float(10)
  [1]=>
  float(10)
}

Przykład #2 Styl proceduralny

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_move_to($c, 10, 10);

var_dump(cairo_get_current_point($c));

?>

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

array(2) {
  [0]=>
  float(10)
  [1]=>
  float(10)
}

Zobacz też:

  • CairoContext::moveTo() - The moveTo purpose
  • CairoContext::hasCurrentPoint() - The hasCurrentPoint purpose

CairoContext::getAntialias
CairoContext::getDash
CairoContext


The getDash purpose

CairoContext::getCurrentPoint
CairoContext::getDashCount
CairoContext
PHP Manual

CairoContext::getDash

cairo_get_dash

(PECL cairo >= 0.1.0)

CairoContext::getDash -- cairo_get_dash — The getDash purpose

Opis

Styl obiektowy (method):

public array CairoContext::getDash ( void )

Styl proceduralny:

array cairo_get_dash ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getCurrentPoint
CairoContext::getDashCount
CairoContext


The getDashCount purpose

CairoContext::getDash
CairoContext::getFillRule
CairoContext
PHP Manual

CairoContext::getDashCount

cairo_get_dash_count

(PECL cairo >= 0.1.0)

CairoContext::getDashCount -- cairo_get_dash_count — The getDashCount purpose

Opis

Styl obiektowy (method):

public int CairoContext::getDashCount ( void )

Styl proceduralny:

int cairo_get_dash_count ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getDash
CairoContext::getFillRule
CairoContext


The getFillRule purpose

CairoContext::getDashCount
CairoContext::getFontFace
CairoContext
PHP Manual

CairoContext::getFillRule

cairo_get_fill_rule

(PECL cairo >= 0.1.0)

CairoContext::getFillRule -- cairo_get_fill_rule — The getFillRule purpose

Opis

Styl obiektowy (method):

public int CairoContext::getFillRule ( void )

Styl proceduralny:

int cairo_get_fill_rule ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getDashCount
CairoContext::getFontFace
CairoContext


The getFontFace purpose

CairoContext::getFillRule
CairoContext::getFontMatrix
CairoContext
PHP Manual

CairoContext::getFontFace

cairo_get_font_face

(PECL cairo >= 0.1.0)

CairoContext::getFontFace -- cairo_get_font_face — The getFontFace purpose

Opis

Styl obiektowy (method):

public void CairoContext::getFontFace ( void )

Styl proceduralny:

void cairo_get_font_face ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getFillRule
CairoContext::getFontMatrix
CairoContext


The getFontMatrix purpose

CairoContext::getFontFace
CairoContext::getFontOptions
CairoContext
PHP Manual

CairoContext::getFontMatrix

cairo_get_font_matrix

(PECL cairo >= 0.1.0)

CairoContext::getFontMatrix -- cairo_get_font_matrix — The getFontMatrix purpose

Opis

Styl obiektowy (method):

public void CairoContext::getFontMatrix ( void )

Styl proceduralny:

void cairo_get_font_matrix ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getFontFace
CairoContext::getFontOptions
CairoContext


The getFontOptions purpose

CairoContext::getFontMatrix
CairoContext::getGroupTarget
CairoContext
PHP Manual

CairoContext::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoContext::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Opis

Styl obiektowy (method):

public void CairoContext::getFontOptions ( void )

Styl proceduralny:

void cairo_get_font_options ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getFontMatrix
CairoContext::getGroupTarget
CairoContext


The getGroupTarget purpose

CairoContext::getFontOptions
CairoContext::getLineCap
CairoContext
PHP Manual

CairoContext::getGroupTarget

cairo_get_group_target

(PECL cairo >= 0.1.0)

CairoContext::getGroupTarget -- cairo_get_group_target — The getGroupTarget purpose

Opis

Styl obiektowy (method):

public void CairoContext::getGroupTarget ( void )

Styl proceduralny:

void cairo_get_group_target ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getFontOptions
CairoContext::getLineCap
CairoContext


The getLineCap purpose

CairoContext::getGroupTarget
CairoContext::getLineJoin
CairoContext
PHP Manual

CairoContext::getLineCap

cairo_get_line_cap

(PECL cairo >= 0.1.0)

CairoContext::getLineCap -- cairo_get_line_cap — The getLineCap purpose

Opis

Styl obiektowy (method):

public int CairoContext::getLineCap ( void )

Styl proceduralny:

int cairo_get_line_cap ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getGroupTarget
CairoContext::getLineJoin
CairoContext


The getLineJoin purpose

CairoContext::getLineCap
CairoContext::getLineWidth
CairoContext
PHP Manual

CairoContext::getLineJoin

cairo_get_line_join

(PECL cairo >= 0.1.0)

CairoContext::getLineJoin -- cairo_get_line_join — The getLineJoin purpose

Opis

Styl obiektowy (method):

public int CairoContext::getLineJoin ( void )

Styl proceduralny:

int cairo_get_line_join ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getLineCap
CairoContext::getLineWidth
CairoContext


The getLineWidth purpose

CairoContext::getLineJoin
CairoContext::getMatrix
CairoContext
PHP Manual

CairoContext::getLineWidth

cairo_get_line_width

(PECL cairo >= 0.1.0)

CairoContext::getLineWidth -- cairo_get_line_width — The getLineWidth purpose

Opis

Styl obiektowy (method):

public float CairoContext::getLineWidth ( void )

Styl proceduralny:

float cairo_get_line_width ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getLineJoin
CairoContext::getMatrix
CairoContext


The getMatrix purpose

CairoContext::getLineWidth
CairoContext::getMiterLimit
CairoContext
PHP Manual

CairoContext::getMatrix

cairo_get_matrix

(PECL cairo >= 0.1.0)

CairoContext::getMatrix -- cairo_get_matrix — The getMatrix purpose

Opis

Styl obiektowy (method):

public void CairoContext::getMatrix ( void )

Styl proceduralny:

void cairo_get_matrix ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getLineWidth
CairoContext::getMiterLimit
CairoContext


The getMiterLimit purpose

CairoContext::getMatrix
CairoContext::getOperator
CairoContext
PHP Manual

CairoContext::getMiterLimit

cairo_get_miter_limit

(PECL cairo >= 0.1.0)

CairoContext::getMiterLimit -- cairo_get_miter_limit — The getMiterLimit purpose

Opis

Styl obiektowy (method):

public float CairoContext::getMiterLimit ( void )

Styl proceduralny:

float cairo_get_miter_limit ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getMatrix
CairoContext::getOperator
CairoContext


The getOperator purpose

CairoContext::getMiterLimit
CairoContext::getScaledFont
CairoContext
PHP Manual

CairoContext::getOperator

cairo_get_operator

(PECL cairo >= 0.1.0)

CairoContext::getOperator -- cairo_get_operator — The getOperator purpose

Opis

Styl obiektowy (method):

public int CairoContext::getOperator ( void )

Styl proceduralny:

int cairo_get_operator ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getMiterLimit
CairoContext::getScaledFont
CairoContext


The getScaledFont purpose

CairoContext::getOperator
CairoContext::getSource
CairoContext
PHP Manual

CairoContext::getScaledFont

cairo_get_scaled_font

(PECL cairo >= 0.1.0)

CairoContext::getScaledFont -- cairo_get_scaled_font — The getScaledFont purpose

Opis

Styl obiektowy (method):

public void CairoContext::getScaledFont ( void )

Styl proceduralny:

void cairo_get_scaled_font ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getOperator
CairoContext::getSource
CairoContext


The getSource purpose

CairoContext::getScaledFont
CairoContext::getTarget
CairoContext
PHP Manual

CairoContext::getSource

cairo_get_source

(PECL cairo >= 0.1.0)

CairoContext::getSource -- cairo_get_source — The getSource purpose

Opis

Styl obiektowy (method):

public void CairoContext::getSource ( void )

Styl proceduralny:

void cairo_get_source ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getScaledFont
CairoContext::getTarget
CairoContext


The getTarget purpose

CairoContext::getSource
CairoContext::getTolerance
CairoContext
PHP Manual

CairoContext::getTarget

cairo_get_target

(PECL cairo >= 0.1.0)

CairoContext::getTarget -- cairo_get_target — The getTarget purpose

Opis

Styl obiektowy (method):

public void CairoContext::getTarget ( void )

Styl proceduralny:

void cairo_get_target ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getSource
CairoContext::getTolerance
CairoContext


The getTolerance purpose

CairoContext::getTarget
CairoContext::glyphPath
CairoContext
PHP Manual

CairoContext::getTolerance

cairo_get_tolerance

(PECL cairo >= 0.1.0)

CairoContext::getTolerance -- cairo_get_tolerance — The getTolerance purpose

Opis

Styl obiektowy (method):

public float CairoContext::getTolerance ( void )

Styl proceduralny:

float cairo_get_tolerance ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::getTarget
CairoContext::glyphPath
CairoContext


The glyphPath purpose

CairoContext::getTolerance
CairoContext::hasCurrentPoint
CairoContext
PHP Manual

CairoContext::glyphPath

cairo_glyph_path

(PECL cairo >= 0.1.0)

CairoContext::glyphPath -- cairo_glyph_path — The glyphPath purpose

Opis

Styl obiektowy

public void CairoContext::glyphPath ( array $glyphs )

Styl proceduralny

void cairo_glyph_path ( CairoContext $context , array $glyphs )

Adds closed paths for the glyphs to the current path. The generated path if filled, achieves an effect similar to that of CairoContext::showGlyphs().

Parametry

context

A CairoContext object

glyphs

Array of glyphs

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

CairoContext::getTolerance
CairoContext::hasCurrentPoint
CairoContext


The hasCurrentPoint purpose

CairoContext::glyphPath
CairoContext::identityMatrix
CairoContext
PHP Manual

CairoContext::hasCurrentPoint

cairo_has_current_point

(PECL cairo >= 0.1.0)

CairoContext::hasCurrentPoint -- cairo_has_current_point — The hasCurrentPoint purpose

Opis

Styl obiektowy (method):

public bool CairoContext::hasCurrentPoint ( void )

Styl proceduralny:

bool cairo_has_current_point ( CairoContext $context )

Returns whether a current point is defined on the current path. See CairoContext::getCurrentPoint() for details on the current point.

Parametry

context

A valid CairoContext object.

Zwracane wartości

Whether a current point is defined

Przykłady

Przykład #1 Styl obiektowy

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

var_dump($c->hasCurrentPoint());

$c->moveTo(10, 10);

var_dump($c->hasCurrentPoint());

?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Przykład #2 Styl proceduralny

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

var_dump(cairo_has_current_point($c));

cairo_move_to($c, 10, 10);

var_dump(cairo_has_current_point($c));

?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:

  • CairoContext::getCurrentPoint() - The getCurrentPoint purpose

CairoContext::glyphPath
CairoContext::identityMatrix
CairoContext


The identityMatrix purpose

CairoContext::hasCurrentPoint
CairoContext::inFill
CairoContext
PHP Manual

CairoContext::identityMatrix

cairo_identity_matrix

(PECL cairo >= 0.1.0)

CairoContext::identityMatrix -- cairo_identity_matrix — The identityMatrix purpose

Opis

Styl obiektowy (method):

public void CairoContext::identityMatrix ( void )

Styl proceduralny:

void cairo_identity_matrix ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::hasCurrentPoint
CairoContext::inFill
CairoContext


The inFill purpose

CairoContext::identityMatrix
CairoContext::inStroke
CairoContext
PHP Manual

CairoContext::inFill

cairo_in_fill

(PECL cairo >= 0.1.0)

CairoContext::inFill -- cairo_in_fill — The inFill purpose

Opis

Styl obiektowy (method):

public bool CairoContext::inFill ( string $x , string $y )

Styl proceduralny:

bool cairo_in_fill ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::identityMatrix
CairoContext::inStroke
CairoContext


The inStroke purpose

CairoContext::inFill
CairoContext::lineTo
CairoContext
PHP Manual

CairoContext::inStroke

cairo_in_stroke

(PECL cairo >= 0.1.0)

CairoContext::inStroke -- cairo_in_stroke — The inStroke purpose

Opis

Styl obiektowy (method):

public bool CairoContext::inStroke ( string $x , string $y )

Styl proceduralny:

bool cairo_in_stroke ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::inFill
CairoContext::lineTo
CairoContext


The lineTo purpose

CairoContext::inStroke
CairoContext::mask
CairoContext
PHP Manual

CairoContext::lineTo

cairo_line_to

(PECL cairo >= 0.1.0)

CairoContext::lineTo -- cairo_line_to — The lineTo purpose

Opis

Styl obiektowy (method):

public void CairoContext::lineTo ( string $x , string $y )

Styl proceduralny:

void cairo_line_to ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::inStroke
CairoContext::mask
CairoContext


The mask purpose

CairoContext::lineTo
CairoContext::maskSurface
CairoContext
PHP Manual

CairoContext::mask

cairo_mask

(PECL cairo >= 0.1.0)

CairoContext::mask -- cairo_mask — The mask purpose

Opis

Styl obiektowy (method):

public void CairoContext::mask ( string $pattern )

Styl proceduralny:

void cairo_mask ( CairoContext $context , CairoPattern $pattern )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

pattern

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::lineTo
CairoContext::maskSurface
CairoContext


The maskSurface purpose

CairoContext::mask
CairoContext::moveTo
CairoContext
PHP Manual

CairoContext::maskSurface

cairo_mask_surface

(PECL cairo >= 0.1.0)

CairoContext::maskSurface -- cairo_mask_surface — The maskSurface purpose

Opis

Styl obiektowy (method):

public void CairoContext::maskSurface ( string $surface [, string $x [, string $y ]] )

Styl proceduralny:

void cairo_mask_surface ( CairoContext $context , CairoSurface $surface [, string $x [, string $y ]] )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

surface

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::mask
CairoContext::moveTo
CairoContext


The moveTo purpose

CairoContext::maskSurface
CairoContext::newPath
CairoContext
PHP Manual

CairoContext::moveTo

cairo_move_to

(PECL cairo >= 0.1.0)

CairoContext::moveTo -- cairo_move_to — The moveTo purpose

Opis

Styl obiektowy (method):

public void CairoContext::moveTo ( string $x , string $y )

Styl proceduralny:

void cairo_move_to ( CairoContext $context , string $x , string $y )

Begin a new sub-path. After this call the current point will be (x, y).

Parametry

context

A valid CairoContext object.

x

The x coordinate of the new position.

y

The y coordinate of the new position

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

// Move 10 pixels across, and 10 pixels down
$c->moveTo(10, 10);
$c->lineTo(90, 90);
$c->setLineWidth(2);
$c->setSourceRgb(1, 1, 1);
$c->stroke();

// Move 90 pixels across, and 10 pixels down
$c->moveTo(90, 10);
$c->lineTo(10, 90);
$c->setLineWidth(2);
$c->setSourceRgb(1, 1, 1);
$c->stroke();

$s->writeToPng(dirname(__FILE__) . '/CairoContext_moveTo.png');
?>

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

...

Przykład #2 Styl proceduralny

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

// Move 10 pixels across, and 10 pixels down
cairo_move_to($c, 10, 10);
cairo_line_to($c, 90, 90);
cairo_set_line_width($c, 2);
cairo_set_source_rgb($c, 1, 1, 1);
cairo_stroke($c);

// Move 90 pixels across, and 10 pixels down
cairo_move_to($c, 90, 10);
cairo_line_to($c, 10, 90);
cairo_set_line_width($c, 2);
cairo_set_source_rgb($c, 1, 1, 1);
cairo_stroke($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_move_to.png');
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::maskSurface
CairoContext::newPath
CairoContext


The newPath purpose

CairoContext::moveTo
CairoContext::newSubPath
CairoContext
PHP Manual

CairoContext::newPath

cairo_new_path

(PECL cairo >= 0.1.0)

CairoContext::newPath -- cairo_new_path — The newPath purpose

Opis

Styl obiektowy (method):

public void CairoContext::newPath ( void )

Styl proceduralny:

void cairo_new_path ( CairoContext $context )

Clears the current path. After this call there will be no path and no current point.

Parametry

context

A valid CairoContext object.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Styl obiektowy

<?php
// [...]
CairoContext::newPath();
?>

Przykład #2 Styl proceduralny

<?php
// [...]
cairo_new_path($context);
?>

Zobacz też:

  • CairoContext::appendPath() - Appends a path to current path
  • CairoContext::closePath() - Closes the current path

CairoContext::moveTo
CairoContext::newSubPath
CairoContext


The newSubPath purpose

CairoContext::newPath
CairoContext::paint
CairoContext
PHP Manual

CairoContext::newSubPath

cairo_new_sub_path

(PECL cairo >= 0.1.0)

CairoContext::newSubPath -- cairo_new_sub_path — The newSubPath purpose

Opis

Styl obiektowy (method):

public void CairoContext::newSubPath ( void )

Styl proceduralny:

void cairo_new_sub_path ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::newPath
CairoContext::paint
CairoContext


The paint purpose

CairoContext::newSubPath
CairoContext::paintWithAlpha
CairoContext
PHP Manual

CairoContext::paint

cairo_paint

(PECL cairo >= 0.1.0)

CairoContext::paint -- cairo_paint — The paint purpose

Opis

Styl obiektowy (method):

public void CairoContext::paint ( void )

Styl proceduralny:

void cairo_paint ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::newSubPath
CairoContext::paintWithAlpha
CairoContext


The paintWithAlpha purpose

CairoContext::paint
CairoContext::pathExtents
CairoContext
PHP Manual

CairoContext::paintWithAlpha

cairo_paint_with_alpha

(PECL cairo >= 0.1.0)

CairoContext::paintWithAlpha -- cairo_paint_with_alpha — The paintWithAlpha purpose

Opis

Styl obiektowy (method):

public void CairoContext::paintWithAlpha ( string $alpha )

Styl proceduralny:

void cairo_paint_with_alpha ( CairoContext $context , string $alpha )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

alpha

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::paint
CairoContext::pathExtents
CairoContext


The pathExtents purpose

CairoContext::paintWithAlpha
CairoContext::popGroup
CairoContext
PHP Manual

CairoContext::pathExtents

cairo_path_extents

(PECL cairo >= 0.1.0)

CairoContext::pathExtents -- cairo_path_extents — The pathExtents purpose

Opis

Styl obiektowy (method):

public array CairoContext::pathExtents ( void )

Styl proceduralny:

array cairo_path_extents ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::paintWithAlpha
CairoContext::popGroup
CairoContext


The popGroup purpose

CairoContext::pathExtents
CairoContext::popGroupToSource
CairoContext
PHP Manual

CairoContext::popGroup

cairo_pop_group

(PECL cairo >= 0.1.0)

CairoContext::popGroup -- cairo_pop_group — The popGroup purpose

Opis

Styl obiektowy (method):

public void CairoContext::popGroup ( void )

Styl proceduralny:

void cairo_pop_group ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::pathExtents
CairoContext::popGroupToSource
CairoContext


The popGroupToSource purpose

CairoContext::popGroup
CairoContext::pushGroup
CairoContext
PHP Manual

CairoContext::popGroupToSource

cairo_pop_group_to_source

(PECL cairo >= 0.1.0)

CairoContext::popGroupToSource -- cairo_pop_group_to_source — The popGroupToSource purpose

Opis

Styl obiektowy (method):

public void CairoContext::popGroupToSource ( void )

Styl proceduralny:

void cairo_pop_group_to_source ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::popGroup
CairoContext::pushGroup
CairoContext


The pushGroup purpose

CairoContext::popGroupToSource
CairoContext::pushGroupWithContent
CairoContext
PHP Manual

CairoContext::pushGroup

cairo_push_group

(PECL cairo >= 0.1.0)

CairoContext::pushGroup -- cairo_push_group — The pushGroup purpose

Opis

Styl obiektowy (method):

public void CairoContext::pushGroup ( void )

Styl proceduralny:

void cairo_push_group ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::popGroupToSource
CairoContext::pushGroupWithContent
CairoContext


The pushGroupWithContent purpose

CairoContext::pushGroup
CairoContext::rectangle
CairoContext
PHP Manual

CairoContext::pushGroupWithContent

cairo_push_group_with_content

(PECL cairo >= 0.1.0)

CairoContext::pushGroupWithContent -- cairo_push_group_with_content — The pushGroupWithContent purpose

Opis

Styl obiektowy (method):

public void CairoContext::pushGroupWithContent ( string $content )

Styl proceduralny:

void cairo_push_group_with_content ( CairoContext $context , string $content )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

content

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::pushGroup
CairoContext::rectangle
CairoContext


The rectangle purpose

CairoContext::pushGroupWithContent
CairoContext::relCurveTo
CairoContext
PHP Manual

CairoContext::rectangle

cairo_rectangle

(PECL cairo >= 0.1.0)

CairoContext::rectangle -- cairo_rectangle — The rectangle purpose

Opis

Styl obiektowy (method):

public void CairoContext::rectangle ( string $x , string $y , string $width , string $height )

Styl proceduralny:

void cairo_rectangle ( CairoContext $context , string $x , string $y , string $width , string $height )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::pushGroupWithContent
CairoContext::relCurveTo
CairoContext


The relCurveTo purpose

CairoContext::rectangle
CairoContext::relLineTo
CairoContext
PHP Manual

CairoContext::relCurveTo

cairo_rel_curve_to

(PECL cairo >= 0.1.0)

CairoContext::relCurveTo -- cairo_rel_curve_to — The relCurveTo purpose

Opis

Styl obiektowy (method):

public void CairoContext::relCurveTo ( string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )

Styl proceduralny:

void cairo_rel_curve_to ( CairoContext $context , string $x1 , string $y1 , string $x2 , string $y2 , string $x3 , string $y3 )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x1

Description...

y1

Description...

x2

Description...

y2

Description...

x3

Description...

y3

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::rectangle
CairoContext::relLineTo
CairoContext


The relLineTo purpose

CairoContext::relCurveTo
CairoContext::relMoveTo
CairoContext
PHP Manual

CairoContext::relLineTo

cairo_rel_line_to

(PECL cairo >= 0.1.0)

CairoContext::relLineTo -- cairo_rel_line_to — The relLineTo purpose

Opis

Styl obiektowy (method):

public void CairoContext::relLineTo ( string $x , string $y )

Styl proceduralny:

void cairo_rel_line_to ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::relCurveTo
CairoContext::relMoveTo
CairoContext


The relMoveTo purpose

CairoContext::relLineTo
CairoContext::resetClip
CairoContext
PHP Manual

CairoContext::relMoveTo

cairo_rel_move_to

(PECL cairo >= 0.1.0)

CairoContext::relMoveTo -- cairo_rel_move_to — The relMoveTo purpose

Opis

Styl obiektowy (method):

public void CairoContext::relMoveTo ( string $x , string $y )

Styl proceduralny:

void cairo_rel_move_to ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::relLineTo
CairoContext::resetClip
CairoContext


The resetClip purpose

CairoContext::relMoveTo
CairoContext::restore
CairoContext
PHP Manual

CairoContext::resetClip

cairo_reset_clip

(PECL cairo >= 0.1.0)

CairoContext::resetClip -- cairo_reset_clip — The resetClip purpose

Opis

Styl obiektowy (method):

public void CairoContext::resetClip ( void )

Styl proceduralny:

void cairo_reset_clip ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::relMoveTo
CairoContext::restore
CairoContext


The restore purpose

CairoContext::resetClip
CairoContext::rotate
CairoContext
PHP Manual

CairoContext::restore

cairo_restore

(PECL cairo >= 0.1.0)

CairoContext::restore -- cairo_restore — The restore purpose

Opis

Styl obiektowy (method):

public void CairoContext::restore ( void )

Styl proceduralny:

void cairo_restore ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::resetClip
CairoContext::rotate
CairoContext


The rotate purpose

CairoContext::restore
CairoContext::save
CairoContext
PHP Manual

CairoContext::rotate

cairo_rotate

(PECL cairo >= 0.1.0)

CairoContext::rotate -- cairo_rotate — The rotate purpose

Opis

Styl obiektowy (method):

public void CairoContext::rotate ( string $angle )

Styl proceduralny:

void cairo_rotate ( CairoContext $context , string $angle )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

angle

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::restore
CairoContext::save
CairoContext


The save purpose

CairoContext::rotate
CairoContext::scale
CairoContext
PHP Manual

CairoContext::save

cairo_save

(PECL cairo >= 0.1.0)

CairoContext::save -- cairo_save — The save purpose

Opis

Styl obiektowy (method):

public void CairoContext::save ( void )

Styl proceduralny:

void cairo_save ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::rotate
CairoContext::scale
CairoContext


The scale purpose

CairoContext::save
CairoContext::selectFontFace
CairoContext
PHP Manual

CairoContext::scale

cairo_scale

(PECL cairo >= 0.1.0)

CairoContext::scale -- cairo_scale — The scale purpose

Opis

Styl obiektowy (method):

public void CairoContext::scale ( string $x , string $y )

Styl proceduralny:

void cairo_scale ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::save
CairoContext::selectFontFace
CairoContext


The selectFontFace purpose

CairoContext::scale
CairoContext::setAntialias
CairoContext
PHP Manual

CairoContext::selectFontFace

cairo_select_font_face

(PECL cairo >= 0.1.0)

CairoContext::selectFontFace -- cairo_select_font_face — The selectFontFace purpose

Opis

Styl obiektowy (method):

public void CairoContext::selectFontFace ( string $family [, string $slant [, string $weight ]] )

Styl proceduralny:

void cairo_select_font_face ( CairoContext $context , string $family [, string $slant [, string $weight ]] )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

family

Description...

slant

Description...

weight

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::scale
CairoContext::setAntialias
CairoContext


The setAntialias purpose

CairoContext::selectFontFace
CairoContext::setDash
CairoContext
PHP Manual

CairoContext::setAntialias

cairo_set_antialias

(PECL cairo >= 0.1.0)

CairoContext::setAntialias -- cairo_set_antialias — The setAntialias purpose

Opis

Styl obiektowy (method):

public void CairoContext::setAntialias ([ string $antialias ] )

Styl proceduralny:

void cairo_set_antialias ( CairoContext $context [, string $antialias ] )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

antialias

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::selectFontFace
CairoContext::setDash
CairoContext


The setDash purpose

CairoContext::setAntialias
CairoContext::setFillRule
CairoContext
PHP Manual

CairoContext::setDash

cairo_set_dash

(PECL cairo >= 0.1.0)

CairoContext::setDash -- cairo_set_dash — The setDash purpose

Opis

Styl obiektowy (method):

public void CairoContext::setDash ( string $dashes [, string $offset ] )

Styl proceduralny:

void cairo_set_dash ( CairoContext $context , array $dashes [, string $offset ] )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

dashes

Description...

offset

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setAntialias
CairoContext::setFillRule
CairoContext


The setFillRule purpose

CairoContext::setDash
CairoContext::setFontFace
CairoContext
PHP Manual

CairoContext::setFillRule

cairo_set_fill_rule

(PECL cairo >= 0.1.0)

CairoContext::setFillRule -- cairo_set_fill_rule — The setFillRule purpose

Opis

Styl obiektowy (method):

public void CairoContext::setFillRule ( string $setting )

Styl proceduralny:

void cairo_set_fill_rule ( CairoContext $context , string $setting )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

setting

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setDash
CairoContext::setFontFace
CairoContext


The setFontFace purpose

CairoContext::setFillRule
CairoContext::setFontMatrix
CairoContext
PHP Manual

CairoContext::setFontFace

cairo_set_font_face

(PECL cairo >= 0.1.0)

CairoContext::setFontFace -- cairo_set_font_face — The setFontFace purpose

Opis

Styl obiektowy (method):

public void CairoContext::setFontFace ( CairoFontFace $fontface )

Styl proceduralny:

void cairo_set_font_face ( CairoContext $context , CairoFontFace $fontface )

Sets the font-face for a given context.

Parametry

context

A CairoContext object to change the font-face for.

fontface

A CairoFontFace object

Zwracane wartości

No value is returned

Przykłady

Przykład #1 Styl obiektowy

<?php
// New surface with white background
$s = new CairoImageSurface(CairoFormat::ARGB32, 300, 100);
$c = new CairoContext($s);
$c->setSourceRgb(1, 1, 1);
$c->paint();

// Draw some text
$c->setSourceRgb(0, 0, 0);
$c->moveTo(10, 60);
// Create a new font face
$f = new CairoToyFontFace("sans-serif", CairoFontSlant::NORMAL, CairoFontWeight::NORMAL);
$c->setFontFace($f);
$c->setFontSize(30);
$c->showText('Hello, World!');
$s->writeToPng(dirname(__FILE__) . '/setFontFace.png');
?>

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Zobacz też:

  • CairoContext::setFontSize() - The setFontSize purpose
  • CairoContext::showText() - The showText purpose

CairoContext::setFillRule
CairoContext::setFontMatrix
CairoContext


The setFontMatrix purpose

CairoContext::setFontFace
CairoContext::setFontOptions
CairoContext
PHP Manual

CairoContext::setFontMatrix

cairo_set_font_matrix

(PECL cairo >= 0.1.0)

CairoContext::setFontMatrix -- cairo_set_font_matrix — The setFontMatrix purpose

Opis

Styl obiektowy (method):

public void CairoContext::setFontMatrix ( string $matrix )

Styl proceduralny:

void cairo_set_font_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

matrix

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setFontFace
CairoContext::setFontOptions
CairoContext


The setFontOptions purpose

CairoContext::setFontMatrix
CairoContext::setFontSize
CairoContext
PHP Manual

CairoContext::setFontOptions

cairo_set_font_options

(PECL cairo >= 0.1.0)

CairoContext::setFontOptions -- cairo_set_font_options — The setFontOptions purpose

Opis

Styl obiektowy (method):

public void CairoContext::setFontOptions ( string $fontoptions )

Styl proceduralny:

void cairo_set_font_options ( CairoContext $context , CairoFontOptions $fontoptions )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

fontoptions

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setFontMatrix
CairoContext::setFontSize
CairoContext


The setFontSize purpose

CairoContext::setFontOptions
CairoContext::setLineCap
CairoContext
PHP Manual

CairoContext::setFontSize

cairo_set_font_size

(PECL cairo >= 0.1.0)

CairoContext::setFontSize -- cairo_set_font_size — The setFontSize purpose

Opis

Styl obiektowy (method):

public void CairoContext::setFontSize ( string $size )

Styl proceduralny:

void cairo_set_font_size ( CairoContext $context , string $size )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

size

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setFontOptions
CairoContext::setLineCap
CairoContext


The setLineCap purpose

CairoContext::setFontSize
CairoContext::setLineJoin
CairoContext
PHP Manual

CairoContext::setLineCap

cairo_set_line_cap

(PECL cairo >= 0.1.0)

CairoContext::setLineCap -- cairo_set_line_cap — The setLineCap purpose

Opis

Styl obiektowy (method):

public void CairoContext::setLineCap ( string $setting )

Styl proceduralny:

void cairo_set_line_cap ( CairoContext $context , string $setting )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

setting

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setFontSize
CairoContext::setLineJoin
CairoContext


The setLineJoin purpose

CairoContext::setLineCap
CairoContext::setLineWidth
CairoContext
PHP Manual

CairoContext::setLineJoin

cairo_set_line_join

(PECL cairo >= 0.1.0)

CairoContext::setLineJoin -- cairo_set_line_join — The setLineJoin purpose

Opis

Styl obiektowy (method):

public void CairoContext::setLineJoin ( string $setting )

Styl proceduralny:

void cairo_set_line_join ( CairoContext $context , string $setting )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

setting

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setLineCap
CairoContext::setLineWidth
CairoContext


The setLineWidth purpose

CairoContext::setLineJoin
CairoContext::setMatrix
CairoContext
PHP Manual

CairoContext::setLineWidth

cairo_set_line_width

(PECL cairo >= 0.1.0)

CairoContext::setLineWidth -- cairo_set_line_width — The setLineWidth purpose

Opis

Styl obiektowy (method):

public void CairoContext::setLineWidth ( string $width )

Styl proceduralny:

void cairo_set_line_width ( CairoContext $context , string $width )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

width

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setLineJoin
CairoContext::setMatrix
CairoContext


The setMatrix purpose

CairoContext::setLineWidth
CairoContext::setMiterLimit
CairoContext
PHP Manual

CairoContext::setMatrix

cairo_set_matrix

(PECL cairo >= 0.1.0)

CairoContext::setMatrix -- cairo_set_matrix — The setMatrix purpose

Opis

Styl obiektowy (method):

public void CairoContext::setMatrix ( string $matrix )

Styl proceduralny:

void cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

matrix

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setLineWidth
CairoContext::setMiterLimit
CairoContext


The setMiterLimit purpose

CairoContext::setMatrix
CairoContext::setOperator
CairoContext
PHP Manual

CairoContext::setMiterLimit

cairo_set_miter_limit

(PECL cairo >= 0.1.0)

CairoContext::setMiterLimit -- cairo_set_miter_limit — The setMiterLimit purpose

Opis

Styl obiektowy (method):

public void CairoContext::setMiterLimit ( string $limit )

Styl proceduralny:

void cairo_set_miter_limit ( CairoContext $context , string $limit )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

limit

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setMatrix
CairoContext::setOperator
CairoContext


The setOperator purpose

CairoContext::setMiterLimit
CairoContext::setScaledFont
CairoContext
PHP Manual

CairoContext::setOperator

cairo_set_operator

(PECL cairo >= 0.1.0)

CairoContext::setOperator -- cairo_set_operator — The setOperator purpose

Opis

Styl obiektowy (method):

public void CairoContext::setOperator ( string $setting )

Styl proceduralny:

void cairo_set_operator ( CairoContext $context , string $setting )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

setting

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setMiterLimit
CairoContext::setScaledFont
CairoContext


The setScaledFont purpose

CairoContext::setOperator
CairoContext::setSource
CairoContext
PHP Manual

CairoContext::setScaledFont

cairo_set_scaled_font

(PECL cairo >= 0.1.0)

CairoContext::setScaledFont -- cairo_set_scaled_font — The setScaledFont purpose

Opis

Styl obiektowy (method):

public void CairoContext::setScaledFont ( string $scaledfont )

Styl proceduralny:

void cairo_set_scaled_font ( CairoContext $context , CairoScaledFont $scaledfont )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

scaledfont

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setOperator
CairoContext::setSource
CairoContext


The setSource purpose

CairoContext::setScaledFont
CairoContext::setSourceRGB
CairoContext
PHP Manual

CairoContext::setSource

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSource -- cairo_set_source — The setSource purpose

Opis

Styl obiektowy (method):

public void CairoContext::setSource ( string $pattern )

Styl proceduralny:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

pattern

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setScaledFont
CairoContext::setSourceRGB
CairoContext


The setSourceRGB purpose

CairoContext::setSource
CairoContext::setSourceRGBA
CairoContext
PHP Manual

CairoContext::setSourceRGB

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSourceRGB -- cairo_set_source — The setSourceRGB purpose

Opis

Styl obiektowy (method):

public void CairoContext::setSourceRGB ( string $red , string $green , string $blue )

Styl proceduralny:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

pattern

Description...

red

Description...

green

Description...

blue

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setSource
CairoContext::setSourceRGBA
CairoContext


The setSourceRGBA purpose

CairoContext::setSourceRGB
CairoContext::setSourceSurface
CairoContext
PHP Manual

CairoContext::setSourceRGBA

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSourceRGBA -- cairo_set_source — The setSourceRGBA purpose

Opis

Styl obiektowy (method):

public void CairoContext::setSourceRGBA ( string $red , string $green , string $blue , string $alpha )

Styl proceduralny:

void cairo_set_source ( CairoContext $context , CairoPattern $pattern )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

pattern

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setSourceRGB
CairoContext::setSourceSurface
CairoContext


The setSourceSurface purpose

CairoContext::setSourceRGBA
CairoContext::setTolerance
CairoContext
PHP Manual

CairoContext::setSourceSurface

cairo_set_source_surface

(PECL cairo >= 0.1.0)

CairoContext::setSourceSurface -- cairo_set_source_surface — The setSourceSurface purpose

Opis

Styl obiektowy (method):

public void CairoContext::setSourceSurface ( string $surface [, string $x [, string $y ]] )

Styl proceduralny:

void cairo_set_source_surface ( CairoContext $context , CairoSurface $surface [, string $x [, string $y ]] )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

surface

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setSourceRGBA
CairoContext::setTolerance
CairoContext


The setTolerance purpose

CairoContext::setSourceSurface
CairoContext::showPage
CairoContext
PHP Manual

CairoContext::setTolerance

cairo_set_tolerance

(PECL cairo >= 0.1.0)

CairoContext::setTolerance -- cairo_set_tolerance — The setTolerance purpose

Opis

Styl obiektowy (method):

public void CairoContext::setTolerance ( string $tolerance )

Styl proceduralny:

void cairo_set_tolerance ( CairoContext $context , string $tolerance )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

tolerance

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setSourceSurface
CairoContext::showPage
CairoContext


The showPage purpose

CairoContext::setTolerance
CairoContext::showText
CairoContext
PHP Manual

CairoContext::showPage

cairo_show_page

(PECL cairo >= 0.1.0)

CairoContext::showPage -- cairo_show_page — The showPage purpose

Opis

Styl obiektowy (method):

public void CairoContext::showPage ( void )

Styl proceduralny:

void cairo_show_page ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::setTolerance
CairoContext::showText
CairoContext


The showText purpose

CairoContext::showPage
CairoContext::status
CairoContext
PHP Manual

CairoContext::showText

cairo_show_text

(PECL cairo >= 0.1.0)

CairoContext::showText -- cairo_show_text — The showText purpose

Opis

Styl obiektowy (method):

public void CairoContext::showText ( string $text )

Styl proceduralny:

void cairo_show_text ( CairoContext $context , string $text )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

text

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::showPage
CairoContext::status
CairoContext


The status purpose

CairoContext::showText
CairoContext::stroke
CairoContext
PHP Manual

CairoContext::status

cairo_status

(PECL cairo >= 0.1.0)

CairoContext::status -- cairo_status — The status purpose

Opis

Styl obiektowy (method):

public int CairoContext::status ( void )

Styl proceduralny:

int cairo_status ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::showText
CairoContext::stroke
CairoContext


The stroke purpose

CairoContext::status
CairoContext::strokeExtents
CairoContext
PHP Manual

CairoContext::stroke

cairo_stroke

(PECL cairo >= 0.1.0)

CairoContext::stroke -- cairo_stroke — The stroke purpose

Opis

Styl obiektowy (method):

public void CairoContext::stroke ( void )

Styl proceduralny:

void cairo_stroke ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::status
CairoContext::strokeExtents
CairoContext


The strokeExtents purpose

CairoContext::stroke
CairoContext::strokePreserve
CairoContext
PHP Manual

CairoContext::strokeExtents

cairo_stroke_extents

(PECL cairo >= 0.1.0)

CairoContext::strokeExtents -- cairo_stroke_extents — The strokeExtents purpose

Opis

Styl obiektowy (method):

public array CairoContext::strokeExtents ( void )

Styl proceduralny:

array cairo_stroke_extents ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::stroke
CairoContext::strokePreserve
CairoContext


The strokePreserve purpose

CairoContext::strokeExtents
CairoContext::textExtents
CairoContext
PHP Manual

CairoContext::strokePreserve

cairo_stroke_preserve

(PECL cairo >= 0.1.0)

CairoContext::strokePreserve -- cairo_stroke_preserve — The strokePreserve purpose

Opis

Styl obiektowy (method):

public void CairoContext::strokePreserve ( void )

Styl proceduralny:

void cairo_stroke_preserve ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::strokeExtents
CairoContext::textExtents
CairoContext


The textExtents purpose

CairoContext::strokePreserve
CairoContext::textPath
CairoContext
PHP Manual

CairoContext::textExtents

cairo_text_extents

(PECL cairo >= 0.1.0)

CairoContext::textExtents -- cairo_text_extents — The textExtents purpose

Opis

Styl obiektowy (method):

public array CairoContext::textExtents ( string $text )

Styl proceduralny:

array cairo_text_extents ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

text

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::strokePreserve
CairoContext::textPath
CairoContext


The textPath purpose

CairoContext::textExtents
CairoContext::transform
CairoContext
PHP Manual

CairoContext::textPath

cairo_text_path

(PECL cairo >= 0.1.0)

CairoContext::textPath -- cairo_text_path — The textPath purpose

Opis

Styl obiektowy

public void CairoContext::textPath ( string $string )

Styl proceduralny

void cairo_text_path ( CairoContext $context , string $text )

Adds closed paths for text to the current path. The generated path, if filled, achieves an effect similar to that of CairoContext::showText().

Text conversion and positioning is done similar to CairoContext::showText().

Like CairoContext::showText(), after this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for chaining multiple calls to CairoContext::showText() without having to set current point in between.

Note: The CairoContext::textPath() function call is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See CairoContext::glyphPath() for the "real" text path API in cairo.

Parametry

context

A CairoContext object

text

Description...

string

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::textExtents
CairoContext::transform
CairoContext


The transform purpose

CairoContext::textPath
CairoContext::translate
CairoContext
PHP Manual

CairoContext::transform

cairo_transform

(PECL cairo >= 0.1.0)

CairoContext::transform -- cairo_transform — The transform purpose

Opis

Styl obiektowy (method):

public void CairoContext::transform ( string $matrix )

Styl proceduralny:

void cairo_transform ( CairoContext $context , CairoMatrix $matrix )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

matrix

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::textPath
CairoContext::translate
CairoContext


The translate purpose

CairoContext::transform
CairoContext::userToDevice
CairoContext
PHP Manual

CairoContext::translate

cairo_translate

(PECL cairo >= 0.1.0)

CairoContext::translate -- cairo_translate — The translate purpose

Opis

Styl obiektowy (method):

public void CairoContext::translate ( string $x , string $y )

Styl proceduralny:

void cairo_translate ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::transform
CairoContext::userToDevice
CairoContext


The userToDevice purpose

CairoContext::translate
CairoContext::userToDeviceDistance
CairoContext
PHP Manual

CairoContext::userToDevice

cairo_user_to_device

(PECL cairo >= 0.1.0)

CairoContext::userToDevice -- cairo_user_to_device — The userToDevice purpose

Opis

Styl obiektowy (method):

public array CairoContext::userToDevice ( string $x , string $y )

Styl proceduralny:

array cairo_user_to_device ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::translate
CairoContext::userToDeviceDistance
CairoContext


The userToDeviceDistance purpose

CairoContext::userToDevice
CairoException
CairoContext
PHP Manual

CairoContext::userToDeviceDistance

cairo_user_to_device_distance

(PECL cairo >= 0.1.0)

CairoContext::userToDeviceDistance -- cairo_user_to_device_distance — The userToDeviceDistance purpose

Opis

Styl obiektowy (method):

public array CairoContext::userToDeviceDistance ( string $x , string $y )

Styl proceduralny:

array cairo_user_to_device_distance ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoContext::userToDevice
CairoException
CairoContext


The CairoException class

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

Wstęp

Exception class throwed by Cairo functions and methods

Krótki opis klasy

CairoException extends Exception {
/* Właściwości */
/* Metody dziedziczone */
}

Właściwości

message

Prop description

code

Prop description

file

Prop description

line

Prop description

CairoContext::userToDeviceDistance
CairoStatus
Cairo


The CairoStatus class

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

Wstęp

CairoStatus is used to indicate errors that can occur when using Cairo. In some cases it is returned directly by functions. but when using CairoContext, the last error, if any, is stored in the object and can be retrieved with CairoContext::status() or cairo_status(). New entries may be added in future versions.

Use Cairo::statusToString() or cairo_status_to_string() to get a human-readable representation of an error message.

Krótki opis klasy

CairoStatus {
/* Stałe */
const integer SUCCESS = 0 ;
const integer NO_MEMORY = 1 ;
const integer INVALID_RESTORE = 2 ;
const integer INVALID_POP_GROUP = 3 ;
const integer NO_CURRENT_POINT = 4 ;
const integer INVALID_MATRIX = 5 ;
const integer INVALID_STATUS = 6 ;
const integer NULL_POINTER = 7 ;
const integer INVALID_STRING = 8 ;
const integer INVALID_PATH_DATA = 9 ;
const integer READ_ERROR = 10 ;
const integer WRITE_ERROR = 11 ;
const integer SURFACE_FINISHED = 12 ;
const integer SURFACE_TYPE_MISMATCH = 13 ;
const integer PATTERN_TYPE_MISMATCH = 14 ;
const integer INVALID_CONTENT = 15 ;
const integer INVALID_FORMAT = 16 ;
const integer INVALID_VISUAL = 17 ;
const integer FILE_NOT_FOUND = 18 ;
const integer INVALID_DASH = 19 ;
const integer INVALID_DSC_COMMENT = 20 ;
const integer INVALID_INDEX = 21 ;
const integer CLIP_NOT_REPRESENTABLE = 22 ;
const integer TEMP_FILE_ERROR = 23 ;
const integer INVALID_STRIDE = 24 ;
}

Stałe predefiniowane

CairoStatus::SUCCESS

No error has occurred

CairoStatus::NO_MEMORY

Out of memory

CairoStatus::INVALID_RESTORE

cairo_restore() called without matching cairo_save()

CairoStatus::INVALID_POP_GROUP

No saved group to pop

CairoStatus::NO_CURRENT_POINT

No current point defined

CairoStatus::INVALID_MATRIX

Invalid matrix (not invertible)

CairoStatus::INVALID_STATUS

Invalid value for an input CairoStatus>

CairoStatus::NULL_POINTER

Null pointer

CairoStatus::INVALID_STRING

Input string not valid UTF-8 string

CairoStatus::INVALID_PATH_DATA

Input path data not valid

CairoStatus::READ_ERROR

Error while reading from input stream

CairoStatus::WRITE_ERROR

Error while writing to output stream

CairoStatus::SURFACE_FINISHED

Target surface has been finished

CairoStatus::SURFACE_TYPE_MISMATCH

The surface type is not appropriate for the operation

CairoStatus::PATTERN_TYPE_MISMATCH

The pattern type is not appropriate for the operation

CairoStatus::INVALID_CONTENT

Invalid value for an input CairoContent

CairoStatus::INVALID_FORMAT

Invalid value for an input CairoFormat

CairoStatus::INVALID_VISUAL

Invalid value for an input Visual

CairoStatus::FILE_NOT_FOUND

File not found

CairoStatus::INVALID_DASH

Invalid value for a dash setting

CairoStatus::INVALID_DSC_COMMENT

Invalid value for a DSC comment

CairoStatus::INVALID_INDEX

Invalid index passed to getter

CairoStatus::CLIP_NOT_REPRESENTABLE

Clip region not representable in desired format

CairoStatus::TEMP_FILE_ERROR

Error creating or writing to a temporary file

CairoStatus::INVALID_STRIDE

Invalid value for CairoStride

CairoException
CairoSurface
Cairo


The CairoSurface class

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

Wstęp

This is the base-class for all other Surface types. CairoSurface is the abstract type representing all different drawing targets that cairo can render to. The actual drawings are performed using a CairoContext.

Krótki opis klasy

CairoSurface {
/* Metody */
public __construct ( void )
public void copyPage ( void )
public void createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void finish ( void )
public void flush ( void )
public int getContent ( void )
public array getDeviceOffset ( void )
public void getFontOptions ( void )
public int getType ( void )
public void markDirty ( void )
public void markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void setDeviceOffset ( string $x , string $y )
public void setFallbackResolution ( string $x , string $y )
public void showPage ( void )
public int status ( void )
public void writeToPng ( string $file )
}

Spis treści

  • CairoSurface::__construct — The __construct purpose
  • CairoSurface::copyPage — The copyPage purpose
  • CairoSurface::createSimilar — The createSimilar purpose
  • CairoSurface::finish — The finish purpose
  • CairoSurface::flush — The flush purpose
  • CairoSurface::getContent — The getContent purpose
  • CairoSurface::getDeviceOffset — The getDeviceOffset purpose
  • CairoSurface::getFontOptions — The getFontOptions purpose
  • CairoSurface::getType — The getType purpose
  • CairoSurface::markDirty — The markDirty purpose
  • CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose
  • CairoSurface::setDeviceOffset — The setDeviceOffset purpose
  • CairoSurface::setFallbackResolution — The setFallbackResolution purpose
  • CairoSurface::showPage — The showPage purpose
  • CairoSurface::status — The status purpose
  • CairoSurface::writeToPng — The writeToPng purpose
CairoStatus
CairoSurface::__construct
Cairo


The __construct purpose

CairoSurface
CairoSurface::copyPage
CairoSurface
PHP Manual

CairoSurface::__construct

(PECL cairo >= 0.1.0)

CairoSurface::__construct — The __construct purpose

Opis

public CairoSurface::__construct ( void )

CairoSurface is an abstract type and, as such, should not be instantiated in your PHP scripts.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

No return value

Notatki

Informacja:

If you're using a PHP version before 5.3, you must destroy the CairoContext associated with a CairoSurface after you destroy the CairoSurface. Otherwise, you're left with a Circular-reference memory leak.

Zobacz też:

  • CairoImageSurface::__construct() - Creates a new CairoImageSurface

CairoSurface
CairoSurface::copyPage
CairoSurface


The copyPage purpose

CairoSurface::__construct
CairoSurface::createSimilar
CairoSurface
PHP Manual

CairoSurface::copyPage

cairo_copy_page

(PECL cairo >= 0.1.0)

CairoSurface::copyPage -- cairo_copy_page — The copyPage purpose

Opis

Styl obiektowy (method):

public void CairoSurface::copyPage ( void )

Styl proceduralny:

void cairo_copy_page ( CairoContext $context )

Emits the current page for backends that support multiple pages, but doesn't clear it, so that the contents of the current page will be retained for the next page. Use CairoSurface::showPage() if you want to get an empty page after the emission.

Parametry

context

A CairoContext object

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoSurface::__construct
CairoSurface::createSimilar
CairoSurface


The createSimilar purpose

CairoSurface::copyPage
CairoSurface::finish
CairoSurface
PHP Manual

CairoSurface::createSimilar

(PECL cairo >= 0.1.0)

CairoSurface::createSimilar — The createSimilar purpose

Opis

public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )

Create a new surface that is as compatible as possible with an existing surface. For example the new surface will have the same fallback resolution and font options as other. Generally, the new surface will also use the same backend as other, unless that is not possible for some reason. The type of the returned surface may be examined with CairoSurface::getType(). Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)

Parametry

other

An existing surface used to select the backend of the new surface

content

The content for the new surface. See the CairoContent class for possible values.

width

Width of the new surface, (in device-space units).

height

Height of the new surface, (in device-space units).

Zwracane wartości

A new CairoSurface

Przykłady

Przykład #1 CairoSurface::createSimilar() example

<?php
/* ... */
?>

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

...

Zobacz też:

  • CairoContent()

CairoSurface::copyPage
CairoSurface::finish
CairoSurface


The finish purpose

CairoSurface::createSimilar
CairoSurface::flush
CairoSurface
PHP Manual

CairoSurface::finish

(PECL cairo >= 0.1.0)

CairoSurface::finish — The finish purpose

Opis

public void CairoSurface::finish ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurface::finish() example

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoSurface::createSimilar
CairoSurface::flush
CairoSurface


The flush purpose

CairoSurface::finish
CairoSurface::getContent
CairoSurface
PHP Manual

CairoSurface::flush

(PECL cairo >= 0.1.0)

CairoSurface::flush — The flush purpose

Opis

public void CairoSurface::flush ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurface::flush() example

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoSurface::finish
CairoSurface::getContent
CairoSurface


The getContent purpose

CairoSurface::flush
CairoSurface::getDeviceOffset
CairoSurface
PHP Manual

CairoSurface::getContent

(PECL cairo >= 0.1.0)

CairoSurface::getContent — The getContent purpose

Opis

public int CairoSurface::getContent ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurface::getContent() example

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoSurface::flush
CairoSurface::getDeviceOffset
CairoSurface


The getDeviceOffset purpose

CairoSurface::getContent
CairoSurface::getFontOptions
CairoSurface
PHP Manual

CairoSurface::getDeviceOffset

(PECL cairo >= 0.1.0)

CairoSurface::getDeviceOffset — The getDeviceOffset purpose

Opis

public array CairoSurface::getDeviceOffset ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurface::getDeviceOffset() example

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoSurface::getContent
CairoSurface::getFontOptions
CairoSurface


The getFontOptions purpose

CairoSurface::getDeviceOffset
CairoSurface::getType
CairoSurface
PHP Manual

CairoSurface::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoSurface::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Opis

Styl obiektowy (method):

public void CairoSurface::getFontOptions ( void )

Styl proceduralny:

void cairo_get_font_options ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

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

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoSurface::getDeviceOffset
CairoSurface::getType
CairoSurface


The getType purpose

CairoSurface::getFontOptions
CairoSurface::markDirty
CairoSurface
PHP Manual

CairoSurface::getType

(PECL cairo >= 0.1.0)

CairoSurface::getType — The getType purpose

Opis

public int CairoSurface::getType ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurface::getType() example

<?php
/* ... */
?>

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

...

Zobacz też:

  • Classname::Method()

CairoSurface::getFontOptions
CairoSurface::markDirty
CairoSurface


The markDirty purpose

CairoSurface::getType
CairoSurface::markDirtyRectangle
CairoSurface
PHP Manual

CairoSurface::markDirty

(PECL cairo >= 0.1.0)

CairoSurface::markDirty — The markDirty purpose

Opis

public void CairoSurface::markDirty ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurface::markDirty() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurface::getType
CairoSurface::markDirtyRectangle
CairoSurface


The markDirtyRectangle purpose

CairoSurface::markDirty
CairoSurface::setDeviceOffset
CairoSurface
PHP Manual

CairoSurface::markDirtyRectangle

(PECL cairo >= 0.1.0)

CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose

Opis

public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

Description...

y

Description...

width

Description...

height

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSurface::markDirtyRectangle() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurface::markDirty
CairoSurface::setDeviceOffset
CairoSurface


The setDeviceOffset purpose

CairoSurface::markDirtyRectangle
CairoSurface::setFallbackResolution
CairoSurface
PHP Manual

CairoSurface::setDeviceOffset

(PECL cairo >= 0.1.0)

CairoSurface::setDeviceOffset — The setDeviceOffset purpose

Opis

public void CairoSurface::setDeviceOffset ( string $x , string $y )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSurface::setDeviceOffset() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurface::markDirtyRectangle
CairoSurface::setFallbackResolution
CairoSurface


The setFallbackResolution purpose

CairoSurface::setDeviceOffset
CairoSurface::showPage
CairoSurface
PHP Manual

CairoSurface::setFallbackResolution

(PECL cairo >= 0.1.0)

CairoSurface::setFallbackResolution — The setFallbackResolution purpose

Opis

public void CairoSurface::setFallbackResolution ( string $x , string $y )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

Description...

y

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSurface::setFallbackResolution() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurface::setDeviceOffset
CairoSurface::showPage
CairoSurface


The showPage purpose

CairoSurface::setFallbackResolution
CairoSurface::status
CairoSurface
PHP Manual

CairoSurface::showPage

cairo_show_page

(PECL cairo >= 0.1.0)

CairoSurface::showPage -- cairo_show_page — The showPage purpose

Opis

Styl obiektowy (method):

public void CairoSurface::showPage ( void )

Styl proceduralny:

void cairo_show_page ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurface::setFallbackResolution
CairoSurface::status
CairoSurface


The status purpose

CairoSurface::showPage
CairoSurface::writeToPng
CairoSurface
PHP Manual

CairoSurface::status

cairo_status

(PECL cairo >= 0.1.0)

CairoSurface::status -- cairo_status — The status purpose

Opis

Styl obiektowy (method):

public int CairoSurface::status ( void )

Styl proceduralny:

int cairo_status ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurface::showPage
CairoSurface::writeToPng
CairoSurface


The writeToPng purpose

CairoSurface::status
CairoSvgSurface
CairoSurface
PHP Manual

CairoSurface::writeToPng

(PECL cairo >= 0.1.0)

CairoSurface::writeToPng — The writeToPng purpose

Opis

public void CairoSurface::writeToPng ( string $file )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSurface::writeToPng() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurface::status
CairoSvgSurface
CairoSurface


Svg Surface Backend

(No version information available, might only be in SVN)

Wstęp

Svg specific surface class, uses the SVG (standard vector graphics) surface backend.

Krótki opis klasy

CairoSvgSurface extends CairoSurface {
/* Metody */
public __construct ( string $file , float $width , float $height )
public static array getVersions ( void )
public void restrictToVersion ( string $version )
public static string versionToString ( int $version )
/* Metody dziedziczone */
public CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Spis treści

  • CairoSvgSurface::__construct — The __construct purpose
  • CairoSvgSurface::getVersions — Used to retrieve a list of supported SVG versions
  • CairoSvgSurface::restrictToVersion — The restrictToVersion purpose
  • CairoSvgSurface::versionToString — The versionToString purpose
CairoSurface::writeToPng
CairoSvgSurface::__construct
Cairo


The __construct purpose

CairoSvgSurface
CairoSvgSurface::getVersions
CairoSvgSurface
PHP Manual

CairoSvgSurface::__construct

(PECL cairo >= 0.1.0)

CairoSvgSurface::__construct — The __construct purpose

Opis

public CairoSvgSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Description...

width

Description...

height

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSvgSurface::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSvgSurface
CairoSvgSurface::getVersions
CairoSvgSurface


Used to retrieve a list of supported SVG versions

CairoSvgSurface::__construct
CairoSvgSurface::restrictToVersion
CairoSvgSurface
PHP Manual

CairoSvgSurface::getVersions

cairo_svg_surface_get_versions

(PECL cairo >= 0.1.0)

CairoSvgSurface::getVersions -- cairo_svg_surface_get_versions — Used to retrieve a list of supported SVG versions

Opis

Styl obiektowy (method):

public static array CairoSvgSurface::getVersions ( void )

Styl proceduralny:

array cairo_svg_get_versions ( void )

Returns a numerically indexed array of currently available CairoSvgVersion constants. In order to retreive the string values for each item, use CairoSvgSurface::versionToString().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a numerically indexed array of integer values.

Przykłady

Przykład #1 CairoSvgSurface::getVersions() example

<?php
/* Grab our list of versions */
$versions = CairoSvgSurface::getVersions();
var_dump($versions);

/* echo the string name of each version */
foreach($versions as $id) {
    echo CairoSvgSurface::versionToString($id), PHP_EOL;
}
?>

Powyższy przykład wyświetli coś podobnego do:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

Przykład #2 Styl proceduralny

<?php
/* Grab our list of versions */
$versions = cairo_svg_surface_get_versions();
var_dump($versions);

/* echo the string name of each version */
foreach($versions as $id) {
    echo cairo_svg_surface_version_to_string($id), PHP_EOL;
}
?>

Powyższy przykład wyświetli coś podobnego do:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

Zobacz też:

  • CairoSvgSurface::versionToString() - The versionToString purpose

CairoSvgSurface::__construct
CairoSvgSurface::restrictToVersion
CairoSvgSurface


The restrictToVersion purpose

CairoSvgSurface::getVersions
CairoSvgSurface::versionToString
CairoSvgSurface
PHP Manual

CairoSvgSurface::restrictToVersion

(PECL cairo >= 0.1.0)

CairoSvgSurface::restrictToVersion — The restrictToVersion purpose

Opis

public void CairoSvgSurface::restrictToVersion ( string $version )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

version

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSvgSurface::restrictToVersion() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSvgSurface::getVersions
CairoSvgSurface::versionToString
CairoSvgSurface


The versionToString purpose

CairoSvgSurface::restrictToVersion
CairoImageSurface
CairoSvgSurface
PHP Manual

CairoSvgSurface::versionToString

(PECL cairo >= 0.1.0)

CairoSvgSurface::versionToString — The versionToString purpose

Opis

public static string CairoSvgSurface::versionToString ( int $version )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

version

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSvgSurface::versionToString() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSvgSurface::restrictToVersion
CairoImageSurface
CairoSvgSurface


The CairoImageSurface class

(No version information available, might only be in SVN)

Wstęp

CairoImageSurface provide the ability to render to memory buffers either allocated by cairo or by the calling code. The supported image formats are those defined in CairoFormat.

Krótki opis klasy

CairoImageSurface extends CairoSurface {
/* Metody */
public __construct ( int $format , int $width , int $height )
public static void createForData ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )
public static CairoImageSurface createFromPng ( string $file )
public string getData ( void )
public int getFormat ( void )
public int getHeight ( void )
public int getStride ( void )
public int getWidth ( void )
/* Metody dziedziczone */
public CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Spis treści

  • CairoImageSurface::__construct — Creates a new CairoImageSurface
  • CairoImageSurface::createForData — The createForData purpose
  • CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file
  • CairoImageSurface::getData — Gets the image data as string
  • CairoImageSurface::getFormat — Get the image format
  • CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface
  • CairoImageSurface::getStride — The getStride purpose
  • CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface
CairoSvgSurface::versionToString
CairoImageSurface::__construct
Cairo


Creates a new CairoImageSurface

CairoImageSurface
CairoImageSurface::createForData
CairoImageSurface
PHP Manual

CairoImageSurface::__construct

(PECL cairo >= 0.1.0)

CairoImageSurface::__construct — Creates a new CairoImageSurface

Opis

public CairoImageSurface::__construct ( int $format , int $width , int $height )

Creates a new CairoImageSuface object of type format

Parametry

format

Can be any defined in CairoFormat

width

The width of the image surface

height

The height of the image surface

Zwracane wartości

A new CairoImageSurface

Przykłady

Przykład #1 CairoImageSurface::__construct() example

<?php

// Creates a image with ARGB32 format of 50 width and 50 height
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50,50);

?>

Zobacz też:

  • CairoContext::__construct() - Creates a new CairoContext

CairoImageSurface
CairoImageSurface::createForData
CairoImageSurface


The createForData purpose

CairoImageSurface::__construct
CairoImageSurface::createFromPng
CairoImageSurface
PHP Manual

CairoImageSurface::createForData

(PECL cairo >= 0.1.0)

CairoImageSurface::createForData — The createForData purpose

Opis

public static void CairoImageSurface::createForData ( string $data , int $format , int $width , int $height [, int $stride = -1 ] )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoImageSurface::createForData() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoImageSurface::__construct
CairoImageSurface::createFromPng
CairoImageSurface


Creates a new CairoImageSurface form a png image file

CairoImageSurface::createForData
CairoImageSurface::getData
CairoImageSurface
PHP Manual

CairoImageSurface::createFromPng

(PECL cairo >= 0.1.0)

CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file

Opis

public static CairoImageSurface CairoImageSurface::createFromPng ( string $file )

Creates a new CairoImageSurface form a png image file

This method should be called static

Parametry

file

Path to PNG image file

Zwracane wartości

CairoImageSurface object

Przykłady

Przykład #1 CairoImageSurface::createFromPng() example

<?php

$surface = CairoImageSurface::createFromPng('/path/to/image/file.png');

?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • CairoImageSurface::__construct() - Creates a new CairoImageSurface

CairoImageSurface::createForData
CairoImageSurface::getData
CairoImageSurface


Gets the image data as string

CairoImageSurface::createFromPng
CairoImageSurface::getFormat
CairoImageSurface
PHP Manual

CairoImageSurface::getData

(PECL cairo >= 0.1.0)

CairoImageSurface::getData — Gets the image data as string

Opis

public string CairoImageSurface::getData ( void )

Returns the image data of this surface or NULL if surface is not an image surface, or if CairoContext::finish(), procedural : cairo_surface_finish(), has been called.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The image data as string

Przykłady

Przykład #1 CairoImageSurface::getData() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • CairoImageSurface::getStride() - The getStride purpose

CairoImageSurface::createFromPng
CairoImageSurface::getFormat
CairoImageSurface


Get the image format

CairoImageSurface::getData
CairoImageSurface::getHeight
CairoImageSurface
PHP Manual

CairoImageSurface::getFormat

(PECL cairo >= 0.1.0)

CairoImageSurface::getFormat — Get the image format

Opis

public int CairoImageSurface::getFormat ( void )

Retrieves the image format, as one of the CairoFormat defined

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

One of the CairoFormat enums

Przykłady

Przykład #1 CairoImageSurface::getFormat() example

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

var_dump($surface->getFormat()); // 0

$surface2 = new CairoImageSurface(CairoFormat::A8, 50, 50);

var_dump($surface2->getFormat()); // 2

?>

Powyższy przykład wyświetli coś podobnego do:

int(0)
int(2)

Zobacz też:

  • CairoImageSurface::getHeight() - Retrieves the height of the CairoImageSurface
  • CairoImageSurface::getWidth() - Retrieves the width of the CairoImageSurface

CairoImageSurface::getData
CairoImageSurface::getHeight
CairoImageSurface


Retrieves the height of the CairoImageSurface

CairoImageSurface::getFormat
CairoImageSurface::getStride
CairoImageSurface
PHP Manual

CairoImageSurface::getHeight

(PECL cairo >= 0.1.0)

CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface

Opis

public int CairoImageSurface::getHeight ( void )

This methods returns the CairoImageSurface height.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

CairoImageSurface object height

Przykłady

Przykład #1 CairoImageSurface::getHeight() example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the height
var_dump($surface->getHeight());

?>

Powyższy przykład wyświetli coś podobnego do:

int(50)

Zobacz też:

  • CairoImageSurface::getWidth() - Retrieves the width of the CairoImageSurface

CairoImageSurface::getFormat
CairoImageSurface::getStride
CairoImageSurface


The getStride purpose

CairoImageSurface::getHeight
CairoImageSurface::getWidth
CairoImageSurface
PHP Manual

CairoImageSurface::getStride

(PECL cairo >= 0.1.0)

CairoImageSurface::getStride — The getStride purpose

Opis

public int CairoImageSurface::getStride ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoImageSurface::getStride() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoImageSurface::getHeight
CairoImageSurface::getWidth
CairoImageSurface


Retrieves the width of the CairoImageSurface

CairoImageSurface::getStride
CairoPdfSurface
CairoImageSurface
PHP Manual

CairoImageSurface::getWidth

(PECL cairo >= 0.1.0)

CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface

Opis

public int CairoImageSurface::getWidth ( void )

Gets the width of the CairoImageSurface

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the width of the CairoImageSurface object

Przykłady

Przykład #1 CairoImageSurface::getWidth() example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the width
var_dump($surface->getWidth());

?>

Powyższy przykład wyświetli coś podobnego do:

int(80)

Zobacz też:

  • CairoImageSurface::getHeight() - Retrieves the height of the CairoImageSurface

CairoImageSurface::getStride
CairoPdfSurface
CairoImageSurface


The CairoPdfSurface class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoPdfSurface extends CairoSurface {
/* Metody */
public __construct ( string $file , float $width , float $height )
public void setSize ( string $width , string $height )
/* Metody dziedziczone */
public CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Spis treści

  • CairoPdfSurface::__construct — The __construct purpose
  • CairoPdfSurface::setSize — The setSize purpose
CairoImageSurface::getWidth
CairoPdfSurface::__construct
Cairo


The __construct purpose

CairoPdfSurface
CairoPdfSurface::setSize
CairoPdfSurface
PHP Manual

CairoPdfSurface::__construct

(PECL cairo >= 0.1.0)

CairoPdfSurface::__construct — The __construct purpose

Opis

public CairoPdfSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Description...

width

Description...

height

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoPdfSurface::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPdfSurface
CairoPdfSurface::setSize
CairoPdfSurface


The setSize purpose

CairoPdfSurface::__construct
CairoPsSurface
CairoPdfSurface
PHP Manual

CairoPdfSurface::setSize

(PECL cairo >= 0.1.0)

CairoPdfSurface::setSize — The setSize purpose

Opis

public void CairoPdfSurface::setSize ( string $width , string $height )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

width

Description...

height

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoPdfSurface::setSize() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPdfSurface::__construct
CairoPsSurface
CairoPdfSurface


The CairoPsSurface class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoPsSurface extends CairoSurface {
/* Metody */
public __construct ( string $file , float $width , float $height )
public void dscBeginPageSetup ( void )
public void dscBeginSetup ( void )
public void dscComment ( string $comment )
public bool getEps ( void )
public static array getLevels ( void )
public static string levelToString ( int $level )
public void restrictToLevel ( string $level )
public void setEps ( string $level )
public void setSize ( string $width , string $height )
/* Metody dziedziczone */
public CairoSurface::__construct ( void )
public void CairoSurface::copyPage ( void )
public void CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height )
public void CairoSurface::finish ( void )
public void CairoSurface::flush ( void )
public int CairoSurface::getContent ( void )
public array CairoSurface::getDeviceOffset ( void )
public void CairoSurface::getFontOptions ( void )
public int CairoSurface::getType ( void )
public void CairoSurface::markDirty ( void )
public void CairoSurface::markDirtyRectangle ( string $x , string $y , string $width , string $height )
public void CairoSurface::setDeviceOffset ( string $x , string $y )
public void CairoSurface::setFallbackResolution ( string $x , string $y )
public void CairoSurface::showPage ( void )
public int CairoSurface::status ( void )
public void CairoSurface::writeToPng ( string $file )
}

Spis treści

  • CairoPsSurface::__construct — The __construct purpose
  • CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose
  • CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose
  • CairoPsSurface::dscComment — The dscComment purpose
  • CairoPsSurface::getEps — The getEps purpose
  • CairoPsSurface::getLevels — The getLevels purpose
  • CairoPsSurface::levelToString — The levelToString purpose
  • CairoPsSurface::restrictToLevel — The restrictToLevel purpose
  • CairoPsSurface::setEps — The setEps purpose
  • CairoPsSurface::setSize — The setSize purpose
CairoPdfSurface::setSize
CairoPsSurface::__construct
Cairo


The __construct purpose

CairoPsSurface
CairoPsSurface::dscBeginPageSetup
CairoPsSurface
PHP Manual

CairoPsSurface::__construct

(PECL cairo >= 0.1.0)

CairoPsSurface::__construct — The __construct purpose

Opis

public CairoPsSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Description...

width

Description...

height

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoPsSurface::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface
CairoPsSurface::dscBeginPageSetup
CairoPsSurface


The dscBeginPageSetup purpose

CairoPsSurface::__construct
CairoPsSurface::dscBeginSetup
CairoPsSurface
PHP Manual

CairoPsSurface::dscBeginPageSetup

(PECL cairo >= 0.1.0)

CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose

Opis

public void CairoPsSurface::dscBeginPageSetup ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoPsSurface::dscBeginPageSetup() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::__construct
CairoPsSurface::dscBeginSetup
CairoPsSurface


The dscBeginSetup purpose

CairoPsSurface::dscBeginPageSetup
CairoPsSurface::dscComment
CairoPsSurface
PHP Manual

CairoPsSurface::dscBeginSetup

(PECL cairo >= 0.1.0)

CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose

Opis

public void CairoPsSurface::dscBeginSetup ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoPsSurface::dscBeginSetup() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::dscBeginPageSetup
CairoPsSurface::dscComment
CairoPsSurface


The dscComment purpose

CairoPsSurface::dscBeginSetup
CairoPsSurface::getEps
CairoPsSurface
PHP Manual

CairoPsSurface::dscComment

(PECL cairo >= 0.1.0)

CairoPsSurface::dscComment — The dscComment purpose

Opis

public void CairoPsSurface::dscComment ( string $comment )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

comment

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoPsSurface::dscComment() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::dscBeginSetup
CairoPsSurface::getEps
CairoPsSurface


The getEps purpose

CairoPsSurface::dscComment
CairoPsSurface::getLevels
CairoPsSurface
PHP Manual

CairoPsSurface::getEps

(PECL cairo >= 0.1.0)

CairoPsSurface::getEps — The getEps purpose

Opis

public bool CairoPsSurface::getEps ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoPsSurface::getEps() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::dscComment
CairoPsSurface::getLevels
CairoPsSurface


The getLevels purpose

CairoPsSurface::getEps
CairoPsSurface::levelToString
CairoPsSurface
PHP Manual

CairoPsSurface::getLevels

(PECL cairo >= 0.1.0)

CairoPsSurface::getLevels — The getLevels purpose

Opis

public static array CairoPsSurface::getLevels ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoPsSurface::getLevels() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::getEps
CairoPsSurface::levelToString
CairoPsSurface


The levelToString purpose

CairoPsSurface::getLevels
CairoPsSurface::restrictToLevel
CairoPsSurface
PHP Manual

CairoPsSurface::levelToString

(PECL cairo >= 0.1.0)

CairoPsSurface::levelToString — The levelToString purpose

Opis

public static string CairoPsSurface::levelToString ( int $level )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

level

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoPsSurface::levelToString() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::getLevels
CairoPsSurface::restrictToLevel
CairoPsSurface


The restrictToLevel purpose

CairoPsSurface::levelToString
CairoPsSurface::setEps
CairoPsSurface
PHP Manual

CairoPsSurface::restrictToLevel

(PECL cairo >= 0.1.0)

CairoPsSurface::restrictToLevel — The restrictToLevel purpose

Opis

public void CairoPsSurface::restrictToLevel ( string $level )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

level

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoPsSurface::restrictToLevel() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::levelToString
CairoPsSurface::setEps
CairoPsSurface


The setEps purpose

CairoPsSurface::restrictToLevel
CairoPsSurface::setSize
CairoPsSurface
PHP Manual

CairoPsSurface::setEps

(PECL cairo >= 0.1.0)

CairoPsSurface::setEps — The setEps purpose

Opis

public void CairoPsSurface::setEps ( string $level )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

level

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoPsSurface::setEps() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::restrictToLevel
CairoPsSurface::setSize
CairoPsSurface


The setSize purpose

CairoPsSurface::setEps
CairoSurfaceType
CairoPsSurface
PHP Manual

CairoPsSurface::setSize

(PECL cairo >= 0.1.0)

CairoPsSurface::setSize — The setSize purpose

Opis

public void CairoPsSurface::setSize ( string $width , string $height )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

width

Description...

height

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoPsSurface::setSize() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPsSurface::setEps
CairoSurfaceType
CairoPsSurface


The CairoSurfaceType class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoSurfaceType {
/* Stałe */
const integer IMAGE = 0 ;
const integer PDF = 1 ;
const integer PS = 2 ;
const integer XLIB = 3 ;
const integer XCB = 4 ;
const integer GLITZ = 5 ;
const integer QUARTZ = 6 ;
const integer WIN32 = 7 ;
const integer BEOS = 8 ;
const integer DIRECTFB = 9 ;
const integer SVG = 10 ;
const integer OS2 = 11 ;
const integer WIN32_PRINTING = 12 ;
const integer QUARTZ_IMAGE = 13 ;
}

Stałe predefiniowane

CairoSurfaceType::IMAGE

Description here...

CairoSurfaceType::PDF

Description here...

CairoSurfaceType::PS

Description here...

CairoSurfaceType::XLIB

Description here...

CairoSurfaceType::XCB

Description here...

CairoSurfaceType::GLITZ

Description here...

CairoSurfaceType::QUARTZ

Description here...

CairoSurfaceType::WIN32

Description here...

CairoSurfaceType::BEOS

Description here...

CairoSurfaceType::DIRECTFB

Description here...

CairoSurfaceType::SVG

Description here...

CairoSurfaceType::OS2

Description here...

CairoSurfaceType::WIN32_PRINTING

Description here...

CairoSurfaceType::QUARTZ_IMAGE

Description here...

CairoPsSurface::setSize
CairoFontFace
Cairo


The CairoFontFace class

(No version information available, might only be in SVN)

Wstęp

CairoFontFace abstract class represents a particular font at a particular weight, slant, and other characteristic but no transformation or size.

Note: This class can not be instantiated directly, it is created by CairoContext::getFontFace() or cairo_scaled_font_get_font_face().

Krótki opis klasy

CairoFontFace {
/* Metody */
public __construct ( void )
public int getType ( void )
public int status ( void )
}

Spis treści

  • CairoFontFace::__construct — Creates a new CairoFontFace object
  • CairoFontFace::getType — Retrieves the font face type
  • CairoFontFace::status — Check for CairoFontFace errors
CairoSurfaceType
CairoFontFace::__construct
Cairo


Creates a new CairoFontFace object

CairoFontFace
CairoFontFace::getType
CairoFontFace
PHP Manual

CairoFontFace::__construct

(PECL cairo >= 0.1.0)

CairoFontFace::__construct — Creates a new CairoFontFace object

Opis

public CairoFontFace::__construct ( void )

CairoFontFace class represents a particular font at a particular weight, slant, and other characteristic but no transformation or size.

Note: This class can't be instantiated directly it is created by CairoContext::getFontFace() or cairo_scaled_font_get_font_face()

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

CairoFontFace

Przykłady

Przykład #1 CairoFontFace::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Class::Method()

CairoFontFace
CairoFontFace::getType
CairoFontFace


Retrieves the font face type

CairoFontFace::__construct
CairoFontFace::status
CairoFontFace
PHP Manual

CairoFontFace::getType

(PECL cairo >= 0.1.0)

CairoFontFace::getType — Retrieves the font face type

Opis

public int CairoFontFace::getType ( void )

This function returns the type of the backend used to create a font face. See CairoFontType class constants for available types.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A font type that can be any one defined in CairoFontType

Przykłady

Przykład #1 CairoFontFace::getType() example

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face type
var_dump($fontface->getType());

?>

Powyższy przykład wyświetli coś podobnego do:

int(0)

Zobacz też:

  • Classname::Method()

CairoFontFace::__construct
CairoFontFace::status
CairoFontFace


Check for CairoFontFace errors

CairoFontFace::getType
CairoFontOptions
CairoFontFace
PHP Manual

CairoFontFace::status

cairo_font_face_status

(PECL cairo >= 0.1.0)

CairoFontFace::status -- cairo_font_face_status — Check for CairoFontFace errors

Opis

Styl obiektowy (method):

public int CairoFontFace::status ( void )

Styl proceduralny:

int cairo_font_face_status ( CairoFontFace $fontface )

Checks whether an error has previously occurred for this font face

Parametry

fontface

A valid CairoFontFace object

Zwracane wartości

CAIRO_STATUS_SUCCESS or another error such as CAIRO_STATUS_NO_MEMORY.

Przykłady

Przykład #1 Styl obiektowy

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face status
var_dump($fontface->status()); // should be the value of CAIRO_STATUS_SUCCESS

?>

Powyższy przykład wyświetli coś podobnego do:

int(0)

Przykład #2 Styl proceduralny

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face status
var_dump(cairo_font_face_status($fontface)); // should be the value of CAIRO_STATUS_SUCCESS

?>

Powyższy przykład wyświetli coś podobnego do:

int(0)

Zobacz też:

  • Classname::Method()

CairoFontFace::getType
CairoFontOptions
CairoFontFace


The CairoFontOptions class

(No version information available, might only be in SVN)

Wstęp

An opaque structure holding all options that are used when rendering fonts.

Individual features of a cairo_font_options_t can be set or accessed using functions named cairo_font_options_set_feature_name and cairo_font_options_get_feature_name, like cairo_font_options_set_antialias() and cairo_font_options_get_antialias().

New features may be added to CairoFontOptions in the future. For this reason CairoFontOptions::copy(), CairoFontOptions::equal(), CairoFontOptions::merge(), CairoFontOptions::hash() (cairo_font_options_copy(), cairo_font_options_equal(), cairo_font_options_merge(), and cairo_font_options_hash() in procedural way) should be used to copy, check for equality, merge, or compute a hash value of CairoFontOptions objects.

Krótki opis klasy

CairoFontOptions {
/* Metody */
public __construct ( void )
public bool equal ( string $other )
public int getAntialias ( void )
public int getHintMetrics ( void )
public int getHintStyle ( void )
public int getSubpixelOrder ( void )
public int hash ( void )
public void merge ( string $other )
public void setAntialias ( string $antialias )
public void setHintMetrics ( string $hint_metrics )
public void setHintStyle ( string $hint_style )
public void setSubpixelOrder ( string $subpixel_order )
public int status ( void )
}

Spis treści

  • CairoFontOptions::__construct — The __construct purpose
  • CairoFontOptions::equal — The equal purpose
  • CairoFontOptions::getAntialias — The getAntialias purpose
  • CairoFontOptions::getHintMetrics — The getHintMetrics purpose
  • CairoFontOptions::getHintStyle — The getHintStyle purpose
  • CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose
  • CairoFontOptions::hash — The hash purpose
  • CairoFontOptions::merge — The merge purpose
  • CairoFontOptions::setAntialias — The setAntialias purpose
  • CairoFontOptions::setHintMetrics — The setHintMetrics purpose
  • CairoFontOptions::setHintStyle — The setHintStyle purpose
  • CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose
  • CairoFontOptions::status — The status purpose
CairoFontFace::status
CairoFontOptions::__construct
Cairo


The __construct purpose

CairoFontOptions
CairoFontOptions::equal
CairoFontOptions
PHP Manual

CairoFontOptions::__construct

(PECL cairo >= 0.1.0)

CairoFontOptions::__construct — The __construct purpose

Opis

public CairoFontOptions::__construct ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoFontOptions::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions
CairoFontOptions::equal
CairoFontOptions


The equal purpose

CairoFontOptions::__construct
CairoFontOptions::getAntialias
CairoFontOptions
PHP Manual

CairoFontOptions::equal

(PECL cairo >= 0.1.0)

CairoFontOptions::equal — The equal purpose

Opis

public bool CairoFontOptions::equal ( string $other )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

other

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoFontOptions::equal() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::__construct
CairoFontOptions::getAntialias
CairoFontOptions


The getAntialias purpose

CairoFontOptions::equal
CairoFontOptions::getHintMetrics
CairoFontOptions
PHP Manual

CairoFontOptions::getAntialias

cairo_get_antialias

(PECL cairo >= 0.1.0)

CairoFontOptions::getAntialias -- cairo_get_antialias — The getAntialias purpose

Opis

Styl obiektowy (method):

public int CairoFontOptions::getAntialias ( void )

Styl proceduralny:

int cairo_get_antialias ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::equal
CairoFontOptions::getHintMetrics
CairoFontOptions


The getHintMetrics purpose

CairoFontOptions::getAntialias
CairoFontOptions::getHintStyle
CairoFontOptions
PHP Manual

CairoFontOptions::getHintMetrics

(PECL cairo >= 0.1.0)

CairoFontOptions::getHintMetrics — The getHintMetrics purpose

Opis

public int CairoFontOptions::getHintMetrics ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoFontOptions::getHintMetrics() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::getAntialias
CairoFontOptions::getHintStyle
CairoFontOptions


The getHintStyle purpose

CairoFontOptions::getHintMetrics
CairoFontOptions::getSubpixelOrder
CairoFontOptions
PHP Manual

CairoFontOptions::getHintStyle

(PECL cairo >= 0.1.0)

CairoFontOptions::getHintStyle — The getHintStyle purpose

Opis

public int CairoFontOptions::getHintStyle ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoFontOptions::getHintStyle() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::getHintMetrics
CairoFontOptions::getSubpixelOrder
CairoFontOptions


The getSubpixelOrder purpose

CairoFontOptions::getHintStyle
CairoFontOptions::hash
CairoFontOptions
PHP Manual

CairoFontOptions::getSubpixelOrder

(PECL cairo >= 0.1.0)

CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose

Opis

public int CairoFontOptions::getSubpixelOrder ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoFontOptions::getSubpixelOrder() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::getHintStyle
CairoFontOptions::hash
CairoFontOptions


The hash purpose

CairoFontOptions::getSubpixelOrder
CairoFontOptions::merge
CairoFontOptions
PHP Manual

CairoFontOptions::hash

(PECL cairo >= 0.1.0)

CairoFontOptions::hash — The hash purpose

Opis

public int CairoFontOptions::hash ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoFontOptions::hash() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::getSubpixelOrder
CairoFontOptions::merge
CairoFontOptions


The merge purpose

CairoFontOptions::hash
CairoFontOptions::setAntialias
CairoFontOptions
PHP Manual

CairoFontOptions::merge

(PECL cairo >= 0.1.0)

CairoFontOptions::merge — The merge purpose

Opis

public void CairoFontOptions::merge ( string $other )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

other

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoFontOptions::merge() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::hash
CairoFontOptions::setAntialias
CairoFontOptions


The setAntialias purpose

CairoFontOptions::merge
CairoFontOptions::setHintMetrics
CairoFontOptions
PHP Manual

CairoFontOptions::setAntialias

cairo_set_antialias

(PECL cairo >= 0.1.0)

CairoFontOptions::setAntialias -- cairo_set_antialias — The setAntialias purpose

Opis

Styl obiektowy (method):

public void CairoFontOptions::setAntialias ( string $antialias )

Styl proceduralny:

void cairo_set_antialias ( CairoContext $context [, string $antialias ] )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

antialias

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::merge
CairoFontOptions::setHintMetrics
CairoFontOptions


The setHintMetrics purpose

CairoFontOptions::setAntialias
CairoFontOptions::setHintStyle
CairoFontOptions
PHP Manual

CairoFontOptions::setHintMetrics

(PECL cairo >= 0.1.0)

CairoFontOptions::setHintMetrics — The setHintMetrics purpose

Opis

public void CairoFontOptions::setHintMetrics ( string $hint_metrics )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

hint_metrics

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoFontOptions::setHintMetrics() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::setAntialias
CairoFontOptions::setHintStyle
CairoFontOptions


The setHintStyle purpose

CairoFontOptions::setHintMetrics
CairoFontOptions::setSubpixelOrder
CairoFontOptions
PHP Manual

CairoFontOptions::setHintStyle

(PECL cairo >= 0.1.0)

CairoFontOptions::setHintStyle — The setHintStyle purpose

Opis

public void CairoFontOptions::setHintStyle ( string $hint_style )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

hint_style

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoFontOptions::setHintStyle() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::setHintMetrics
CairoFontOptions::setSubpixelOrder
CairoFontOptions


The setSubpixelOrder purpose

CairoFontOptions::setHintStyle
CairoFontOptions::status
CairoFontOptions
PHP Manual

CairoFontOptions::setSubpixelOrder

(PECL cairo >= 0.1.0)

CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose

Opis

public void CairoFontOptions::setSubpixelOrder ( string $subpixel_order )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

subpixel_order

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoFontOptions::setSubpixelOrder() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::setHintStyle
CairoFontOptions::status
CairoFontOptions


The status purpose

CairoFontOptions::setSubpixelOrder
CairoFontSlant
CairoFontOptions
PHP Manual

CairoFontOptions::status

cairo_status

(PECL cairo >= 0.1.0)

CairoFontOptions::status -- cairo_status — The status purpose

Opis

Styl obiektowy (method):

public int CairoFontOptions::status ( void )

Styl proceduralny:

int cairo_status ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFontOptions::setSubpixelOrder
CairoFontSlant
CairoFontOptions


The CairoFontSlant class

(No version information available, might only be in SVN)

Wstęp

Specifies variants of a font face based on their slant.

Krótki opis klasy

CairoFontSlant {
/* Stałe */
const integer NORMAL = 0 ;
const integer ITALIC = 1 ;
const integer OBLIQUE = 2 ;
}

Stałe predefiniowane

CairoFontSlant::NORMAL

Upright font style

CairoFontSlant::ITALIC

Italic font style

CairoFontSlant::OBLIQUE

Oblique font style

CairoFontOptions::status
CairoFontType
Cairo


The CairoFontType class

(No version information available, might only be in SVN)

Wstęp

CairoFontType class is an abstract final class that contains constants used to describe the type of a given CairoFontFace or CairoScaledFont. The font types are also known as "font backends" within cairo.

The type of a CairoFontFace is determined by the how it is created, an example would be the CairoToyFontFace::__construct(). The CairoFontFace type can be queried with CairoFontFace::getType() or cairo_font_face_get_type()

The various CairoFontFace functions can be used with a font face of any type.

The type of a CairoScaledFont is determined by the type of the CairoFontFace passed to CairoScaledFont::__construct() or cairo_scaled_font_create(). The scaled font type can be queried with CairoScaledFont::getType() or cairo_scaled_font_get_type().

Krótki opis klasy

CairoFontType {
/* Stałe */
const integer TOY = 0 ;
const integer FT = 1 ;
const integer WIN32 = 2 ;
const integer QUARTZ = 3 ;
}

Stałe predefiniowane

CairoFontType::TOY

The font was created using CairoToyFont api

CairoFontType::FT

The font is of type CairoFreeType

CairoFontType::WIN32

The font is of type Win32

CairoFontType::QUARTZ

The font is of type Quartz

CairoFontType::USER

The font was create using cairo's user font api

CairoFontSlant
CairoFontWeight
Cairo


The CairoFontWeight class

(No version information available, might only be in SVN)

Wstęp

Specifies variants of a font face based on their weight.

Krótki opis klasy

CairoFontWeight {
/* Stałe */
const integer NORMAL = 0 ;
const integer BOLD = 1 ;
}

Stałe predefiniowane

CairoFontWeight::NORMAL

Normal font weight

CairoFontWeight::BOLD

Bold font weight

CairoFontType
CairoScaledFont
Cairo


The CairoScaledFont class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoScaledFont {
/* Metody */
public __construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )
public array extents ( void )
public CairoMatrix getCtm ( void )
public void getFontFace ( void )
public void getFontMatrix ( void )
public void getFontOptions ( void )
public void getScaleMatrix ( void )
public int getType ( void )
public array glyphExtents ( string $glyphs )
public int status ( void )
public array textExtents ( string $text )
}

Spis treści

  • CairoScaledFont::__construct — The __construct purpose
  • CairoScaledFont::extents — The extents purpose
  • CairoScaledFont::getCtm — The getCtm purpose
  • CairoScaledFont::getFontFace — The getFontFace purpose
  • CairoScaledFont::getFontMatrix — The getFontMatrix purpose
  • CairoScaledFont::getFontOptions — The getFontOptions purpose
  • CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose
  • CairoScaledFont::getType — The getType purpose
  • CairoScaledFont::glyphExtents — The glyphExtents purpose
  • CairoScaledFont::status — The status purpose
  • CairoScaledFont::textExtents — The textExtents purpose
CairoFontWeight
CairoScaledFont::__construct
Cairo


The __construct purpose

CairoScaledFont
CairoScaledFont::extents
CairoScaledFont
PHP Manual

CairoScaledFont::__construct

(PECL cairo >= 0.1.0)

CairoScaledFont::__construct — The __construct purpose

Opis

public CairoScaledFont::__construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

font_face

Description...

matrix

Description...

ctm

Description...

options

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoScaledFont::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont
CairoScaledFont::extents
CairoScaledFont


The extents purpose

CairoScaledFont::__construct
CairoScaledFont::getCtm
CairoScaledFont
PHP Manual

CairoScaledFont::extents

(PECL cairo >= 0.1.0)

CairoScaledFont::extents — The extents purpose

Opis

public array CairoScaledFont::extents ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoScaledFont::extents() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::__construct
CairoScaledFont::getCtm
CairoScaledFont


The getCtm purpose

CairoScaledFont::extents
CairoScaledFont::getFontFace
CairoScaledFont
PHP Manual

CairoScaledFont::getCtm

(PECL cairo >= 0.1.0)

CairoScaledFont::getCtm — The getCtm purpose

Opis

public CairoMatrix CairoScaledFont::getCtm ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoScaledFont::getCtm() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::extents
CairoScaledFont::getFontFace
CairoScaledFont


The getFontFace purpose

CairoScaledFont::getCtm
CairoScaledFont::getFontMatrix
CairoScaledFont
PHP Manual

CairoScaledFont::getFontFace

cairo_get_font_face

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontFace -- cairo_get_font_face — The getFontFace purpose

Opis

Styl obiektowy (method):

public void CairoScaledFont::getFontFace ( void )

Styl proceduralny:

void cairo_get_font_face ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::getCtm
CairoScaledFont::getFontMatrix
CairoScaledFont


The getFontMatrix purpose

CairoScaledFont::getFontFace
CairoScaledFont::getFontOptions
CairoScaledFont
PHP Manual

CairoScaledFont::getFontMatrix

cairo_get_font_matrix

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontMatrix -- cairo_get_font_matrix — The getFontMatrix purpose

Opis

Styl obiektowy (method):

public void CairoScaledFont::getFontMatrix ( void )

Styl proceduralny:

void cairo_get_font_matrix ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::getFontFace
CairoScaledFont::getFontOptions
CairoScaledFont


The getFontOptions purpose

CairoScaledFont::getFontMatrix
CairoScaledFont::getScaleMatrix
CairoScaledFont
PHP Manual

CairoScaledFont::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Opis

Styl obiektowy (method):

public void CairoScaledFont::getFontOptions ( void )

Styl proceduralny:

void cairo_get_font_options ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::getFontMatrix
CairoScaledFont::getScaleMatrix
CairoScaledFont


The getScaleMatrix purpose

CairoScaledFont::getFontOptions
CairoScaledFont::getType
CairoScaledFont
PHP Manual

CairoScaledFont::getScaleMatrix

(PECL cairo >= 0.1.0)

CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose

Opis

public void CairoScaledFont::getScaleMatrix ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoScaledFont::getScaleMatrix() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::getFontOptions
CairoScaledFont::getType
CairoScaledFont


The getType purpose

CairoScaledFont::getScaleMatrix
CairoScaledFont::glyphExtents
CairoScaledFont
PHP Manual

CairoScaledFont::getType

(PECL cairo >= 0.1.0)

CairoScaledFont::getType — The getType purpose

Opis

public int CairoScaledFont::getType ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoScaledFont::getType() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::getScaleMatrix
CairoScaledFont::glyphExtents
CairoScaledFont


The glyphExtents purpose

CairoScaledFont::getType
CairoScaledFont::status
CairoScaledFont
PHP Manual

CairoScaledFont::glyphExtents

(PECL cairo >= 0.1.0)

CairoScaledFont::glyphExtents — The glyphExtents purpose

Opis

public array CairoScaledFont::glyphExtents ( string $glyphs )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

glyphs

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoScaledFont::glyphExtents() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::getType
CairoScaledFont::status
CairoScaledFont


The status purpose

CairoScaledFont::glyphExtents
CairoScaledFont::textExtents
CairoScaledFont
PHP Manual

CairoScaledFont::status

cairo_status

(PECL cairo >= 0.1.0)

CairoScaledFont::status -- cairo_status — The status purpose

Opis

Styl obiektowy (method):

public int CairoScaledFont::status ( void )

Styl proceduralny:

int cairo_status ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::glyphExtents
CairoScaledFont::textExtents
CairoScaledFont


The textExtents purpose

CairoScaledFont::status
CairoToyFontFace
CairoScaledFont
PHP Manual

CairoScaledFont::textExtents

cairo_text_extents

(PECL cairo >= 0.1.0)

CairoScaledFont::textExtents -- cairo_text_extents — The textExtents purpose

Opis

Styl obiektowy (method):

public array CairoScaledFont::textExtents ( string $text )

Styl proceduralny:

array cairo_text_extents ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

text

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoScaledFont::status
CairoToyFontFace
CairoScaledFont


The CairoToyFontFace class

(No version information available, might only be in SVN)

Wstęp

The CairoToyFontFace class can be used instead of CairoContext::selectFontFace() to create a toy font independently of a context.

Krótki opis klasy

CairoToyFontFace extends CairoFontFace {
/* Metody dziedziczone */
}
CairoScaledFont::textExtents
CairoPatternType
Cairo


The CairoPatternType class

(No version information available, might only be in SVN)

Wstęp

CairoPatternType is used to describe the type of a given pattern.

The type of a pattern is determined by the function used to create it. The cairo_pattern_create_rgb() and cairo_pattern_create_rgba() functions create CairoPatternType::SOLID patterns. The remaining cairo_pattern_create_* functions map to pattern types in obvious ways.

Krótki opis klasy

CairoPatternType {
/* Stałe */
const integer SOLID = 0 ;
const integer SURFACE = 1 ;
const integer LINEAR = 2 ;
const integer RADIAL = 3 ;
}

Stałe predefiniowane

CairoPatternType::SOLID

The pattern is a solid (uniform) color. It may be opaque or translucent.

CairoPatternType::SURFACE

The pattern is a based on a surface (an image).

CairoPatternType::LINEAR

The pattern is a linear gradient.

CairoPatternType::RADIAL

The pattern is a radial gradient.

CairoToyFontFace
CairoPattern
Cairo


The CairoPattern class

(No version information available, might only be in SVN)

Wstęp

CairoPattern is the abstract base class from which all the other pattern classes derive. It cannot be instantiated directly

Krótki opis klasy

CairoPattern {
/* Metody */
public __construct ( void )
public void getMatrix ( void )
public int getType ( void )
public void setMatrix ( string $matrix )
public int status ( void )
}

Spis treści

  • CairoPattern::__construct — The __construct purpose
  • CairoPattern::getMatrix — The getMatrix purpose
  • CairoPattern::getType — The getType purpose
  • CairoPattern::setMatrix — The setMatrix purpose
  • CairoPattern::status — The status purpose
CairoPatternType
CairoPattern::__construct
Cairo


The __construct purpose

CairoPattern
CairoPattern::getMatrix
CairoPattern
PHP Manual

CairoPattern::__construct

(PECL cairo >= 0.1.0)

CairoPattern::__construct — The __construct purpose

Opis

public CairoPattern::__construct ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoPattern::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPattern
CairoPattern::getMatrix
CairoPattern


The getMatrix purpose

CairoPattern::__construct
CairoPattern::getType
CairoPattern
PHP Manual

CairoPattern::getMatrix

cairo_get_matrix

(PECL cairo >= 0.1.0)

CairoPattern::getMatrix -- cairo_get_matrix — The getMatrix purpose

Opis

Styl obiektowy (method):

public void CairoPattern::getMatrix ( void )

Styl proceduralny:

void cairo_get_matrix ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPattern::__construct
CairoPattern::getType
CairoPattern


The getType purpose

CairoPattern::getMatrix
CairoPattern::setMatrix
CairoPattern
PHP Manual

CairoPattern::getType

(PECL cairo >= 0.1.0)

CairoPattern::getType — The getType purpose

Opis

public int CairoPattern::getType ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoPattern::getType() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPattern::getMatrix
CairoPattern::setMatrix
CairoPattern


The setMatrix purpose

CairoPattern::getType
CairoPattern::status
CairoPattern
PHP Manual

CairoPattern::setMatrix

cairo_set_matrix

(PECL cairo >= 0.1.0)

CairoPattern::setMatrix -- cairo_set_matrix — The setMatrix purpose

Opis

Styl obiektowy (method):

public void CairoPattern::setMatrix ( string $matrix )

Styl proceduralny:

void cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

matrix

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPattern::getType
CairoPattern::status
CairoPattern


The status purpose

CairoPattern::setMatrix
CairoGradientPattern
CairoPattern
PHP Manual

CairoPattern::status

cairo_status

(PECL cairo >= 0.1.0)

CairoPattern::status -- cairo_status — The status purpose

Opis

Styl obiektowy (method):

public int CairoPattern::status ( void )

Styl proceduralny:

int cairo_status ( CairoContext $context )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoPattern::setMatrix
CairoGradientPattern
CairoPattern


The CairoGradientPattern class

(No version information available, might only be in SVN)

Wstęp

CairoGradientPattern is an abstract base class from which other Pattern classes derive. It cannot be instantiated directly.

Krótki opis klasy

CairoGradientPattern extends CairoPattern {
/* Metody */
public void addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int getColorStopCount ( void )
public array getColorStopRgba ( string $index )
public int getExtend ( void )
public void setExtend ( int $extend )
/* Metody dziedziczone */
public CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Spis treści

  • CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose
  • CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose
  • CairoGradientPattern::getColorStopCount — The getColorStopCount purpose
  • CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose
  • CairoGradientPattern::getExtend — The getExtend purpose
  • CairoGradientPattern::setExtend — The setExtend purpose
CairoPattern::status
CairoGradientPattern::addColorStopRgb
Cairo


The addColorStopRgb purpose

CairoGradientPattern
CairoGradientPattern::addColorStopRgba
CairoGradientPattern
PHP Manual

CairoGradientPattern::addColorStopRgb

(PECL cairo >= 0.1.0)

CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose

Opis

public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

offset

Description...

red

Description...

green

Description...

blue

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoGradientPattern::addColorStopRgb() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoGradientPattern
CairoGradientPattern::addColorStopRgba
CairoGradientPattern


The addColorStopRgba purpose

CairoGradientPattern::addColorStopRgb
CairoGradientPattern::getColorStopCount
CairoGradientPattern
PHP Manual

CairoGradientPattern::addColorStopRgba

(PECL cairo >= 0.1.0)

CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose

Opis

public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoGradientPattern::addColorStopRgba() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoGradientPattern::addColorStopRgb
CairoGradientPattern::getColorStopCount
CairoGradientPattern


The getColorStopCount purpose

CairoGradientPattern::addColorStopRgba
CairoGradientPattern::getColorStopRgba
CairoGradientPattern
PHP Manual

CairoGradientPattern::getColorStopCount

(PECL cairo >= 0.1.0)

CairoGradientPattern::getColorStopCount — The getColorStopCount purpose

Opis

public int CairoGradientPattern::getColorStopCount ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoGradientPattern::getColorStopCount() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoGradientPattern::addColorStopRgba
CairoGradientPattern::getColorStopRgba
CairoGradientPattern


The getColorStopRgba purpose

CairoGradientPattern::getColorStopCount
CairoGradientPattern::getExtend
CairoGradientPattern
PHP Manual

CairoGradientPattern::getColorStopRgba

(PECL cairo >= 0.1.0)

CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose

Opis

public array CairoGradientPattern::getColorStopRgba ( string $index )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoGradientPattern::getColorStopRgba() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoGradientPattern::getColorStopCount
CairoGradientPattern::getExtend
CairoGradientPattern


The getExtend purpose

CairoGradientPattern::getColorStopRgba
CairoGradientPattern::setExtend
CairoGradientPattern
PHP Manual

CairoGradientPattern::getExtend

(PECL cairo >= 0.1.0)

CairoGradientPattern::getExtend — The getExtend purpose

Opis

public int CairoGradientPattern::getExtend ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoGradientPattern::getExtend() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoGradientPattern::getColorStopRgba
CairoGradientPattern::setExtend
CairoGradientPattern


The setExtend purpose

CairoGradientPattern::getExtend
CairoSolidPattern
CairoGradientPattern
PHP Manual

CairoGradientPattern::setExtend

(PECL cairo >= 0.1.0)

CairoGradientPattern::setExtend — The setExtend purpose

Opis

public void CairoGradientPattern::setExtend ( int $extend )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

extend

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoGradientPattern::setExtend() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoGradientPattern::getExtend
CairoSolidPattern
CairoGradientPattern


The CairoSolidPattern class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoSolidPattern extends CairoPattern {
/* Metody */
public __construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )
public array getRgba ( void )
/* Metody dziedziczone */
public CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Spis treści

  • CairoSolidPattern::__construct — The __construct purpose
  • CairoSolidPattern::getRgba — The getRgba purpose
CairoGradientPattern::setExtend
CairoSolidPattern::__construct
Cairo


The __construct purpose

CairoSolidPattern
CairoSolidPattern::getRgba
CairoSolidPattern
PHP Manual

CairoSolidPattern::__construct

(PECL cairo >= 0.1.0)

CairoSolidPattern::__construct — The __construct purpose

Opis

public CairoSolidPattern::__construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

red

Description...

green

Description...

blue

Description...

alpha

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSolidPattern::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSolidPattern
CairoSolidPattern::getRgba
CairoSolidPattern


The getRgba purpose

CairoSolidPattern::__construct
CairoSurfacePattern
CairoSolidPattern
PHP Manual

CairoSolidPattern::getRgba

(PECL cairo >= 0.1.0)

CairoSolidPattern::getRgba — The getRgba purpose

Opis

public array CairoSolidPattern::getRgba ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSolidPattern::getRgba() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSolidPattern::__construct
CairoSurfacePattern
CairoSolidPattern


The CairoSurfacePattern class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoSurfacePattern extends CairoPattern {
/* Metody */
public __construct ( CairoSurface $surface )
public int getExtend ( void )
public int getFilter ( void )
public void getSurface ( void )
public void setExtend ( int $extend )
public void setFilter ( string $filter )
/* Metody dziedziczone */
public CairoPattern::__construct ( void )
public void CairoPattern::getMatrix ( void )
public int CairoPattern::getType ( void )
public void CairoPattern::setMatrix ( string $matrix )
public int CairoPattern::status ( void )
}

Spis treści

  • CairoSurfacePattern::__construct — The __construct purpose
  • CairoSurfacePattern::getExtend — The getExtend purpose
  • CairoSurfacePattern::getFilter — The getFilter purpose
  • CairoSurfacePattern::getSurface — The getSurface purpose
  • CairoSurfacePattern::setExtend — The setExtend purpose
  • CairoSurfacePattern::setFilter — The setFilter purpose
CairoSolidPattern::getRgba
CairoSurfacePattern::__construct
Cairo


The __construct purpose

CairoSurfacePattern
CairoSurfacePattern::getExtend
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::__construct

(PECL cairo >= 0.1.0)

CairoSurfacePattern::__construct — The __construct purpose

Opis

public CairoSurfacePattern::__construct ( CairoSurface $surface )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

surface

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSurfacePattern::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurfacePattern
CairoSurfacePattern::getExtend
CairoSurfacePattern


The getExtend purpose

CairoSurfacePattern::__construct
CairoSurfacePattern::getFilter
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::getExtend

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getExtend — The getExtend purpose

Opis

public int CairoSurfacePattern::getExtend ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurfacePattern::getExtend() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurfacePattern::__construct
CairoSurfacePattern::getFilter
CairoSurfacePattern


The getFilter purpose

CairoSurfacePattern::getExtend
CairoSurfacePattern::getSurface
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::getFilter

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getFilter — The getFilter purpose

Opis

public int CairoSurfacePattern::getFilter ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurfacePattern::getFilter() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurfacePattern::getExtend
CairoSurfacePattern::getSurface
CairoSurfacePattern


The getSurface purpose

CairoSurfacePattern::getFilter
CairoSurfacePattern::setExtend
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::getSurface

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getSurface — The getSurface purpose

Opis

public void CairoSurfacePattern::getSurface ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoSurfacePattern::getSurface() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurfacePattern::getFilter
CairoSurfacePattern::setExtend
CairoSurfacePattern


The setExtend purpose

CairoSurfacePattern::getSurface
CairoSurfacePattern::setFilter
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::setExtend

(PECL cairo >= 0.1.0)

CairoSurfacePattern::setExtend — The setExtend purpose

Opis

public void CairoSurfacePattern::setExtend ( int $extend )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

extend

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSurfacePattern::setExtend() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurfacePattern::getSurface
CairoSurfacePattern::setFilter
CairoSurfacePattern


The setFilter purpose

CairoSurfacePattern::setExtend
CairoLinearGradient
CairoSurfacePattern
PHP Manual

CairoSurfacePattern::setFilter

(PECL cairo >= 0.1.0)

CairoSurfacePattern::setFilter — The setFilter purpose

Opis

public void CairoSurfacePattern::setFilter ( string $filter )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

filter

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoSurfacePattern::setFilter() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoSurfacePattern::setExtend
CairoLinearGradient
CairoSurfacePattern


The CairoLinearGradient class

(No version information available, might only be in SVN)

Wstęp

Create a new CairoLinearGradient along the line defined

Krótki opis klasy

CairoLinearGradient extends CairoGradientPattern {
/* Metody */
public __construct ( float $x0 , float $y0 , float $x1 , float $y1 )
public array getPoints ( void )
/* Metody dziedziczone */
public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int CairoGradientPattern::getColorStopCount ( void )
public array CairoGradientPattern::getColorStopRgba ( string $index )
public int CairoGradientPattern::getExtend ( void )
public void CairoGradientPattern::setExtend ( int $extend )
}

Spis treści

  • CairoLinearGradient::__construct — The __construct purpose
  • CairoLinearGradient::getPoints — The getPoints purpose
CairoSurfacePattern::setFilter
CairoLinearGradient::__construct
Cairo


The __construct purpose

CairoLinearGradient
CairoLinearGradient::getPoints
CairoLinearGradient
PHP Manual

CairoLinearGradient::__construct

(PECL cairo >= 0.1.0)

CairoLinearGradient::__construct — The __construct purpose

Opis

public CairoLinearGradient::__construct ( float $x0 , float $y0 , float $x1 , float $y1 )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoLinearGradient::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoLinearGradient
CairoLinearGradient::getPoints
CairoLinearGradient


The getPoints purpose

CairoLinearGradient::__construct
CairoRadialGradient
CairoLinearGradient
PHP Manual

CairoLinearGradient::getPoints

(PECL cairo >= 0.1.0)

CairoLinearGradient::getPoints — The getPoints purpose

Opis

public array CairoLinearGradient::getPoints ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoLinearGradient::getPoints() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoLinearGradient::__construct
CairoRadialGradient
CairoLinearGradient


The CairoRadialGradient class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoRadialGradient extends CairoGradientPattern {
/* Metody */
public __construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )
public array getCircles ( void )
/* Metody dziedziczone */
public void CairoGradientPattern::addColorStopRgb ( string $offset , string $red , string $green , string $blue )
public void CairoGradientPattern::addColorStopRgba ( string $offset , string $red , string $green , string $blue , string $alpha )
public int CairoGradientPattern::getColorStopCount ( void )
public array CairoGradientPattern::getColorStopRgba ( string $index )
public int CairoGradientPattern::getExtend ( void )
public void CairoGradientPattern::setExtend ( int $extend )
}

Spis treści

  • CairoRadialGradient::__construct — The __construct purpose
  • CairoRadialGradient::getCircles — The getCircles purpose
CairoLinearGradient::getPoints
CairoRadialGradient::__construct
Cairo


The __construct purpose

CairoRadialGradient
CairoRadialGradient::getCircles
CairoRadialGradient
PHP Manual

CairoRadialGradient::__construct

(PECL cairo >= 0.1.0)

CairoRadialGradient::__construct — The __construct purpose

Opis

Styl obiektowy:

public CairoRadialGradient::__construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

Styl proceduralny:

Creates a new radial gradient CairoPattern between the two circles defined by (x0, y0, r0) and (x1, y1, r1). Before using the gradient pattern, a number of color stops should be defined using CairoRadialGradient::addColorStopRgb() or CairoRadialGradient::addColorStopRgba().

Note: The coordinates here are in pattern space. For a new pattern, pattern space is identical to user space, but the relationship between the spaces can be changed with CairoRadialGradient::setMatrix().

Parametry

x0

x coordinate for the center of the start circle.

y0

y coordinate for the center of the start circle.

r0

radius of the start circle.

x1

x coordinate for the center of the end circle.

y1

y coordinate for the center of the end circle.

r1

radius of the end circle.

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoRadialGradient::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoRadialGradient
CairoRadialGradient::getCircles
CairoRadialGradient


The getCircles purpose

CairoRadialGradient::__construct
CairoAntialias
CairoRadialGradient
PHP Manual

CairoRadialGradient::getCircles

(PECL cairo >= 0.1.0)

CairoRadialGradient::getCircles — The getCircles purpose

Opis

public array CairoRadialGradient::getCircles ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoRadialGradient::getCircles() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoRadialGradient::__construct
CairoAntialias
CairoRadialGradient


The CairoAntialias class

(No version information available, might only be in SVN)

Wstęp

Enum class that specifies the type of antialiasing to do when rendering text or shapes.

Krótki opis klasy

CairoAntialias {
/* Stałe */
const integer MODE_DEFAULT = 0 ;
const integer MODE_NONE = 1 ;
const integer MODE_GRAY = 2 ;
const integer MODE_SUBPIXEL = 3 ;
}

Stałe predefiniowane

CairoAntialias::MODE_DEFAULT

Use the default antialiasing for the subsystem and target device

CairoAntialias::MODE_NONE

Use a bilevel alpha mask

CairoAntialias::MODE_GRAY

Perform single-color antialiasing (using shades of gray for black text on a white background, for example).

CairoAntialias::MODE_SUBPIXEL

Perform antialiasing by taking advantage of the order of subpixel elements on devices such as LCD panels.

CairoRadialGradient::getCircles
CairoContent
Cairo


The CairoContent class

(No version information available, might only be in SVN)

Wstęp

CairoContent is used to describe the content that a surface will contain, whether color information, alpha information (translucence vs. opacity), or both.

Note: The large values here are designed to keep CairoContent values distinct from CairoContent values so that the implementation can detect the error if users confuse the two types.

Krótki opis klasy

CairoContent {
/* Stałe */
const integer COLOR = 4096 ;
const integer ALPHA = 8192 ;
const integer COLOR_ALPHA = 12288 ;
}

Stałe predefiniowane

CairoContent::COLOR

The surface will hold color content only.

CairoContent::ALPHA

The surface will hold alpha content only.

CairoContent::COLOR_ALPHA

The surface will hold color and alpha content.

CairoAntialias
CairoExtend
Cairo


The CairoExtend class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoExtend {
/* Stałe */
const integer NONE = 0 ;
const integer REPEAT = 1 ;
const integer REFLECT = 2 ;
const integer PAD = 3 ;
}

Stałe predefiniowane

CairoExtend::NONE

Description here...

CairoExtend::REPEAT

Description here...

CairoExtend::REFLECT

Description here...

CairoExtend::PAD

Description here...

CairoContent
CairoFormat
Cairo


The CairoFormat class

(No version information available, might only be in SVN)

Wstęp

CairoFormat enums are used to identify the memory format of the image data.

Krótki opis klasy

CairoFormat {
/* Stałe */
const integer ARGB32 = 0 ;
const integer RGB24 = 1 ;
const integer A8 = 2 ;
const integer A1 = 3 ;
/* Metody */
public static int strideForWidth ( int $format , int $width )
}

Stałe predefiniowane

CairoFormat::ARGB32

Each pixel is a 32-bit quantity, with alpha in the upper 8 bits, then red, then green, then blue. The 32-bit quantities are stored native-endian. Pre-multiplied alpha is used. (That is, 50% transparent red is 0x80800000, not 0x80ff0000.)

CairoFormat::RGB24

Each pixel is a 32-bit quantity, with the upper 8 bits unused. Red, Green, and Blue are stored in the remaining 24 bits in that order.

CairoFormat::A8

Each pixel is a 8-bit quantity holding an alpha value.

CairoFormat::A1

Each pixel is a 1-bit quantity holding an alpha value. Pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianess of the platform. On a big-endian machine, the first pixel is in the uppermost bit, on a little-endian machine the first pixel is in the least-significant bit.

Spis treści

  • CairoFormat::strideForWidth — Provides an appropiate stride to use
CairoExtend
CairoFormat::strideForWidth
Cairo


Provides an appropiate stride to use

CairoFormat
CairoFillRule
CairoFormat
PHP Manual

CairoFormat::strideForWidth

(PECL cairo >= 0.1.0)

CairoFormat::strideForWidth — Provides an appropiate stride to use

Opis

public static int CairoFormat::strideForWidth ( int $format , int $width )

This method provides a stride value that will respect all alignment requirements of the accelerated image-rendering code within cairo.

Parametry

format

The desired CairoFormat to use

width

The width of the image

Zwracane wartości

The appropriate stride to use given the desired format and width, or -1 if either the format is invalid or the width too large.

Przykłady

Przykład #1 CairoFormat::strideForWidth() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoFormat
CairoFillRule
CairoFormat


The CairoFillRule class

(No version information available, might only be in SVN)

Wstęp

A CairoFillRule is used to select how paths are filled. For both fill rules, whether or not a point is included in the fill is determined by taking a ray from that point to infinity and looking at intersections with the path. The ray can be in any direction, as long as it doesn't pass through the end point of a segment or have a tricky intersection such as intersecting tangent to the path. (Note that filling is not actually implemented in this way. This is just a description of the rule that is applied.)

The default fill rule is CairoFillRule::WINDING.

Krótki opis klasy

CairoFillRule {
/* Stałe */
const integer WINDING = 0 ;
const integer EVEN_ODD = 1 ;
}

Stałe predefiniowane

CairoFillRule::WINDING

If the path crosses the ray from left-to-right, counts +1. If the path crosses the ray from right to left, counts -1. (Left and right are determined from the perspective of looking along the ray from the starting point.) If the total count is non-zero, the point will be filled.

CairoFillRule::EVEN_ODD

Counts the total number of intersections, without regard to the orientation of the contour. If the total number of intersections is odd, the point will be filled.

CairoFormat::strideForWidth
CairoFilter
Cairo


The CairoFilter class

(No version information available, might only be in SVN)

Wstęp

A CairoFilter is used to indicate what filtering should be applied when reading pixel values from patterns. See CairoPattern::setSource() or cairo_pattern_set_source() for indicating the desired filter to be used with a particular pattern.

Krótki opis klasy

CairoFilter {
/* Stałe */
const integer FAST = 0 ;
const integer GOOD = 1 ;
const integer BEST = 2 ;
const integer NEAREST = 3 ;
const integer BILINEAR = 4 ;
const integer GAUSSIAN = 5 ;
}

Stałe predefiniowane

CairoFilter::FAST

A high-performance filter, with quality similar to CairoFilter::NEAREST

CairoFilter::GOOD

A reasonable-performance filter, with quality similar to CairoFilter::BILINEAR

CairoFilter::BEST

The highest-quality available, performance may not be suitable for interactive use.

CairoFilter::NEAREST

Nearest-neighbor filtering

CairoFilter::BILINEAR

Linear interpolation in two dimensions

CairoFilter::GAUSSIAN

This filter value is currently unimplemented, and should not be used in current code.

CairoFillRule
CairoHintMetrics
Cairo


The CairoHintMetrics class

(No version information available, might only be in SVN)

Wstęp

Specifies whether to hint font metrics; hinting font metrics means quantizing them so that they are integer values in device space. Doing this improves the consistency of letter and line spacing, however it also means that text will be laid out differently at different zoom factors.

Krótki opis klasy

CairoHintMetrics {
/* Stałe */
const integer METRICS_DEFAULT = 0 ;
const integer METRICS_OFF = 1 ;
const integer METRICS_ON = 2 ;
}

Stałe predefiniowane

CairoHintMetrics::METRICS_DEFAULT

Hint metrics in the default manner for the font backend and target device

CairoHintMetrics::METRICS_OFF

Do not hint font metrics

CairoHintMetrics::METRICS_ON

Hint font metrics

CairoFilter
CairoHintStyle
Cairo


The CairoHintStyle class

(No version information available, might only be in SVN)

Wstęp

Specifies the type of hinting to do on font outlines. Hinting is the process of fitting outlines to the pixel grid in order to improve the appearance of the result. Since hinting outlines involves distorting them, it also reduces the faithfulness to the original outline shapes. Not all of the outline hinting styles are supported by all font backends.

Krótki opis klasy

CairoHintStyle {
/* Stałe */
const integer STYLE_DEFAULT = 0 ;
const integer STYLE_NONE = 1 ;
const integer STYLE_SLIGHT = 2 ;
const integer STYLE_MEDIUM = 3 ;
const integer STYLE_FULL = 4 ;
}

Stałe predefiniowane

CairoHintStyle::STYLE_DEFAULT

Use the default hint style for font backend and target device

CairoHintStyle::STYLE_NONE

Do not hint outlines

CairoHintStyle::STYLE_SLIGHT

Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes.

CairoHintStyle::STYLE_MEDIUM

Hint outlines with medium strength giving a compromise between fidelity to the original shapes and contrast

CairoHintStyle::STYLE_FULL

Hint outlines to maximize contrast

CairoHintMetrics
CairoLineCap
Cairo


The CairoLineCap class

(No version information available, might only be in SVN)

Wstęp

Specifies how to render the endpoints of the path when stroking.

The default line cap style is CairoLineCap::BUTT.

Krótki opis klasy

CairoLineCap {
/* Stałe */
const integer BUTT = 0 ;
const integer ROUND = 1 ;
const integer SQUARE = 2 ;
}

Stałe predefiniowane

CairoLineCap::BUTT

Start(stop) the line exactly at the start(end) point

CairoLineCap::ROUND

Use a round ending, the center of the circle is the end point

CairoLineCap::SQUARE

Use squared ending, the center of the square is the end point

CairoHintStyle
CairoLineJoin
Cairo


The CairoLineJoin class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoLineJoin {
/* Stałe */
const integer MITER = 0 ;
const integer ROUND = 1 ;
const integer BEVEL = 2 ;
}

Stałe predefiniowane

CairoLineJoin::MITER

Description here...

CairoLineJoin::ROUND

Description here...

CairoLineJoin::BEVEL

Description here...

CairoLineCap
CairoMatrix
Cairo


The CairoMatrix class

(No version information available, might only be in SVN)

Wstęp

Matrices are used throughout cairo to convert between different coordinate spaces.

Krótki opis klasy

CairoMatrix {
/* Metody */
public __construct ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )
public static void initIdentity ( void )
public static void initRotate ( float $radians )
public static void initScale ( float $sx , float $sy )
public static void initTranslate ( float $tx , float $ty )
public void invert ( void )
public static CairoMatrix multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )
public void rotate ( string $sx , string $sy )
public void scale ( float $sx , float $sy )
public array transformDistance ( string $dx , string $dy )
public array transformPoint ( string $dx , string $dy )
public void translate ( string $tx , string $ty )
}

Spis treści

  • CairoMatrix::__construct — Creates a new CairoMatrix object
  • CairoMatrix::initIdentity — Creates a new identity matrix
  • CairoMatrix::initRotate — Creates a new rotated matrix
  • CairoMatrix::initScale — Creates a new scaling matrix
  • CairoMatrix::initTranslate — Creates a new translation matrix
  • CairoMatrix::invert — The invert purpose
  • CairoMatrix::multiply — The multiply purpose
  • CairoMatrix::rotate — The rotate purpose
  • CairoMatrix::scale — Applies scaling to a matrix
  • CairoMatrix::transformDistance — The transformDistance purpose
  • CairoMatrix::transformPoint — The transformPoint purpose
  • CairoMatrix::translate — The translate purpose
CairoLineJoin
CairoMatrix::__construct
Cairo


Creates a new CairoMatrix object

CairoMatrix
CairoMatrix::initIdentity
CairoMatrix
PHP Manual

CairoMatrix::__construct

cairo_matrix_init

(PECL cairo >= 0.1.0)

CairoMatrix::__construct -- cairo_matrix_init — Creates a new CairoMatrix object

Opis

Styl obiektowy (method):

public CairoMatrix::__construct ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )

Styl proceduralny:

object cairo_matrix_init ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )

Returns new CairoMatrix object. Matrices are used throughout cairo to convert between different coordinate spaces. Sets matrix to be the affine transformation given by xx, yx, xy, yy, x0, y0. The transformation is given by: x_new = xx * x + xy * y + x0; and y_new = yx * x + yy * y + y0;

Parametry

xx

xx component of the affine transformation

yx

yx component of the affine transformation

xy

xy component of the affine transformation

yy

yy component of the affine transformation

x0

X translation component of the affine transformation

y0

Y translation component of the affine transformation

Zwracane wartości

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Create a new Matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

Przykład #2 Styl proceduralny

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

Zobacz też:

  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix

CairoMatrix
CairoMatrix::initIdentity
CairoMatrix


Creates a new identity matrix

CairoMatrix::__construct
CairoMatrix::initRotate
CairoMatrix
PHP Manual

CairoMatrix::initIdentity

cairo_matrix_init_identity

(PECL cairo >= 0.1.0)

CairoMatrix::initIdentity -- cairo_matrix_init_identity — Creates a new identity matrix

Opis

Styl obiektowy (method):

public static void CairoMatrix::initIdentity ( void )

Styl proceduralny:

object cairo_matrix_init_identity ( void )

Creates a new matrix that is an identity transformation. An identity transformation means the source data is copied into the destination data without change

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initIdentity();
?>

Przykład #2 Styl proceduralny

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_identity();
?>

Zobacz też:

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix

CairoMatrix::__construct
CairoMatrix::initRotate
CairoMatrix


Creates a new rotated matrix

CairoMatrix::initIdentity
CairoMatrix::initScale
CairoMatrix
PHP Manual

CairoMatrix::initRotate

cairo_matrix_init_rotate

(PECL cairo >= 0.1.0)

CairoMatrix::initRotate -- cairo_matrix_init_rotate — Creates a new rotated matrix

Opis

Styl obiektowy (method):

public static void CairoMatrix::initRotate ( float $radians )

Styl proceduralny:

object cairo_matrix_init_rotate ( float $radians )

Creats a new matrix to a transformation that rotates by radians provided

Parametry

radians

angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction.

Zwracane wartości

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initRotate(0.3);
?>

Przykład #2 Styl proceduralny

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_rotate(0.3);
?>

Zobacz też:

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix

CairoMatrix::initIdentity
CairoMatrix::initScale
CairoMatrix


Creates a new scaling matrix

CairoMatrix::initRotate
CairoMatrix::initTranslate
CairoMatrix
PHP Manual

CairoMatrix::initScale

cairo_matrix_init_scale

cairo_matrix_create_scale

(PECL cairo >= 0.1.0)

CairoMatrix::initScale -- cairo_matrix_init_scale -- cairo_matrix_create_scale — Creates a new scaling matrix

Opis

Styl obiektowy (method):

public static void CairoMatrix::initScale ( float $sx , float $sy )

Styl proceduralny:

object cairo_matrix_init_scale ( float $sx , float $sy )

Creates a new matrix to a transformation that scales by sx and sy in the X and Y dimensions, respectively.

Parametry

sx

scale factor in the X direction

sy

scale factor in the Y direction

Zwracane wartości

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initScale(1.0, 2.0);
?>

Przykład #2 Styl proceduralny

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_scale(1.0, 2.0);
?>

Zobacz też:

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix

CairoMatrix::initRotate
CairoMatrix::initTranslate
CairoMatrix


Creates a new translation matrix

CairoMatrix::initScale
CairoMatrix::invert
CairoMatrix
PHP Manual

CairoMatrix::initTranslate

cairo_matrix_init_translate

(PECL cairo >= 0.1.0)

CairoMatrix::initTranslate -- cairo_matrix_init_translate — Creates a new translation matrix

Opis

Styl obiektowy (method):

public static void CairoMatrix::initTranslate ( float $tx , float $ty )

Styl proceduralny:

object cairo_matrix_init_translate ( float $tx , float $ty )

Creates a new matrix to a transformation that translates by tx and ty in the X and Y dimensions, respectively.

Parametry

tx

amount to translate in the X direction

ty

amount to translate in the Y direction

Zwracane wartości

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initTranslate(1.0, 2.0);
?>

Przykład #2 Styl proceduralny

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_translate(1.0, 2.0);
?>

Zobacz też:

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix

CairoMatrix::initScale
CairoMatrix::invert
CairoMatrix


The invert purpose

CairoMatrix::initTranslate
CairoMatrix::multiply
CairoMatrix
PHP Manual

CairoMatrix::invert

(PECL cairo >= 0.1.0)

CairoMatrix::invert — The invert purpose

Opis

public void CairoMatrix::invert ( void )

The method description goes here.

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

Description...

Przykłady

Przykład #1 CairoMatrix::invert() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoMatrix::initTranslate
CairoMatrix::multiply
CairoMatrix


The multiply purpose

CairoMatrix::invert
CairoMatrix::rotate
CairoMatrix
PHP Manual

CairoMatrix::multiply

(PECL cairo >= 0.1.0)

CairoMatrix::multiply — The multiply purpose

Opis

public static CairoMatrix CairoMatrix::multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

matrix1

Description...

matrix2

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoMatrix::multiply() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoMatrix::invert
CairoMatrix::rotate
CairoMatrix


The rotate purpose

CairoMatrix::multiply
CairoMatrix::scale
CairoMatrix
PHP Manual

CairoMatrix::rotate

cairo_rotate

(PECL cairo >= 0.1.0)

CairoMatrix::rotate -- cairo_rotate — The rotate purpose

Opis

Styl obiektowy (method):

public void CairoMatrix::rotate ( string $sx , string $sy )

Styl proceduralny:

void cairo_rotate ( CairoContext $context , string $angle )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

angle

Description...

sx

Description...

sy

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoMatrix::multiply
CairoMatrix::scale
CairoMatrix


Applies scaling to a matrix

CairoMatrix::rotate
CairoMatrix::transformDistance
CairoMatrix
PHP Manual

CairoMatrix::scale

cairo_matrix_scale

(PECL cairo >= 0.1.0)

CairoMatrix::scale -- cairo_matrix_scale — Applies scaling to a matrix

Opis

Styl obiektowy (method):

public void CairoMatrix::scale ( float $sx , float $sy )

Styl proceduralny:

void cairo_matrix_scale ( CairoContext $context , float $sx , float $sy )

Applies scaling by sx, sy to the transformation in the matrix. The effect of the new transformation is to first scale the coordinates by sx and sy, then apply the original transformation to the coordinates.

Parametry

matrix

Procedural only - CairoMatrix instance

sx

scale factor in the X direction

sy

scale factor in the Y direction

Przykłady

Przykład #1 Styl obiektowy

<?php
/* Apply scaling to a matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
$matrix->scale(0.2, 2.0);
?>

Przykład #2 Styl proceduralny

<?php
/* Apply scaling to a matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
cairo_matrix_scale($matrix, 0.2, 2.0);
?>

Zobacz też:

  • CairoMatrix::initScale() - Creates a new scaling matrix

CairoMatrix::rotate
CairoMatrix::transformDistance
CairoMatrix


The transformDistance purpose

CairoMatrix::scale
CairoMatrix::transformPoint
CairoMatrix
PHP Manual

CairoMatrix::transformDistance

(PECL cairo >= 0.1.0)

CairoMatrix::transformDistance — The transformDistance purpose

Opis

public array CairoMatrix::transformDistance ( string $dx , string $dy )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

dx

Description...

dy

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoMatrix::transformDistance() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoMatrix::scale
CairoMatrix::transformPoint
CairoMatrix


The transformPoint purpose

CairoMatrix::transformDistance
CairoMatrix::translate
CairoMatrix
PHP Manual

CairoMatrix::transformPoint

(PECL cairo >= 0.1.0)

CairoMatrix::transformPoint — The transformPoint purpose

Opis

public array CairoMatrix::transformPoint ( string $dx , string $dy )

The method description goes here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

dx

Description...

dy

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 CairoMatrix::transformPoint() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoMatrix::transformDistance
CairoMatrix::translate
CairoMatrix


The translate purpose

CairoMatrix::transformPoint
CairoOperator
CairoMatrix
PHP Manual

CairoMatrix::translate

cairo_translate

(PECL cairo >= 0.1.0)

CairoMatrix::translate -- cairo_translate — The translate purpose

Opis

Styl obiektowy (method):

public void CairoMatrix::translate ( string $tx , string $ty )

Styl proceduralny:

void cairo_translate ( CairoContext $context , string $x , string $y )

Description here.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

context

Description...

x

Description...

y

Description...

tx

Description...

ty

Description...

Zwracane wartości

Description...

Przykłady

Przykład #1 Styl obiektowy

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Przykład #2 Styl proceduralny

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

CairoMatrix::transformPoint
CairoOperator
CairoMatrix


The CairoOperator class

(No version information available, might only be in SVN)

Wstęp

This is used to set the compositing operator for all cairo drawing operations.

The default operator is CairoOperator::OVER

The operators marked as unbounded modify their destination even outside of the mask layer (that is, their effect is not bound by the mask layer). However, their effect can still be limited by way of clipping.

To keep things simple, the operator descriptions here document the behavior for when both source and destination are either fully transparent or fully opaque. The actual implementation works for translucent layers too. For a more detailed explanation of the effects of each operator, including the mathematical definitions, see http://cairographics.org/operators/.

Krótki opis klasy

CairoOperator {
/* Stałe */
const integer CLEAR = 0 ;
const integer SOURCE = 1 ;
const integer OVER = 2 ;
const integer IN = 3 ;
const integer OUT = 4 ;
const integer ATOP = 5 ;
const integer DEST = 6 ;
const integer DEST_OVER = 7 ;
const integer DEST_IN = 8 ;
const integer DEST_OUT = 9 ;
const integer DEST_ATOP = 10 ;
const integer XOR = 11 ;
const integer ADD = 12 ;
const integer SATURATE = 13 ;
}

Stałe predefiniowane

CairoOperator::CLEAR

Clear destination layer (bounded)

CairoOperator::SOURCE

Replace destination layer (bounded)

CairoOperator::OVER

Draw source layer on top of destination layer (bounded)

CairoOperator::IN

Draw source where there was destination content (unbounded)

CairoOperator::OUT

Draw source where there was no destination content (unbounded)

CairoOperator::ATOP

Draw source on top of destination content and only there

CairoOperator::DEST

Ignore the source

CairoOperator::DEST_OVER

Draw destination on top of source

CairoOperator::DEST_IN

Leave destination only where there was source content (unbounded)

CairoOperator::DEST_OUT

Leave destination only where there was no source content

CairoOperator::DEST_ATOP

Leave destination on top of source content and only there (unbounded)

CairoOperator::XOR

Source and destination are shown where there is only one of them

CairoOperator::ADD

Source and destination layers are accumulated

CairoOperator::SATURATE

Like CairoOperator::OVER, but assuming source and dest are disjoint geometries

CairoMatrix::translate
CairoPath
Cairo


The CairoPath class

(No version information available, might only be in SVN)

Wstęp

Note: CairoPath class cannot be instantiated directly, doing so will result in Fatal Error if used or passed

Krótki opis klasy

CairoPath {
}
CairoOperator
CairoPsLevel
Cairo


The CairoPsLevel class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoPsLevel {
/* Stałe */
const integer LEVEL_2 = 0 ;
const integer LEVEL_3 = 1 ;
}

Stałe predefiniowane

CairoPsLevel::LEVEL_2

Description here...

CairoPsLevel::LEVEL_3

Description here...

CairoPath
CairoSubpixelOrder
Cairo


The CairoSubpixelOrder class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoSubpixelOrder {
/* Stałe */
const integer ORDER_DEFAULT = 0 ;
const integer ORDER_RGB = 1 ;
const integer ORDER_BGR = 2 ;
const integer ORDER_VRGB = 3 ;
const integer ORDER_VBGR = 4 ;
}

Stałe predefiniowane

CairoSubpixelOrder::ORDER_DEFAULT

Description here...

CairoSubpixelOrder::ORDER_RGB

Description here...

CairoSubpixelOrder::ORDER_BGR

Description here...

CairoSubpixelOrder::ORDER_VRGB

Description here...

CairoSubpixelOrder::ORDER_VBGR

Description here...

CairoPsLevel
CairoSvgVersion
Cairo


The CairoSvgVersion class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

CairoSvgVersion {
/* Stałe */
const integer VERSION_1_1 = 0 ;
const integer VERSION_1_2 = 1 ;
}

Stałe predefiniowane

CairoSvgVersion::VERSION_1_1

Description here...

CairoSvgVersion::VERSION_1_2

Description here...

CairoSubpixelOrder
Exif
Cairo


Exchangeable image information

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje Exif
    • exif_imagetype — Determine the type of an image
    • exif_read_data — Reads the EXIF headers from JPEG or TIFF
    • exif_tagname — Get the header name for an index
    • exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image
    • read_exif_data — Alias dla exif_read_data
CairoSvgVersion
Wstęp
Przetwarzanie i generowanie obrazów


Wstęp

Rozszerzenie Exif umożliwia pracę z metadanymi obrazów. Można przykładowo używać funkcji Exif do odczytywania informacji przechowywanych w nagłówkach zdjęć JPEG i TIFF pobranych z aparatu cyfrowego.

Exif
Instalacja/Konfiguracja
Exif


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Exif


Wymagania

PHP musi być skompilowany z opcją --enable-exif. Do prawidłowego działania rozszerzenia Exif, PHP nie wymaga dodatkowych bibliotek. Użytkownicy Windows muszą mieć także włączone rozszerzenie mbstring.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Aby włączyć obsługę Exif, należy skonfigurować PHP z opcją --enable-exif

Użytkownicy Windows muszą włączyć w php.ini biblioteki php_mbstring.dll i php_exif.dll. Biblioteka php_mbstring.dll musi zostać załadowana przed php_exif.dll, a więc powinniśmy odpowiednio dostosować nasz php.ini.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your HTTP output.

Exif configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.encode_jis | "" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Available since PHP 4.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.

exif.encode_unicode string

exif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non Asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.

exif.decode_unicode_motorola string

exif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.

exif.decode_unicode_intel string

exif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.

exif.encode_jis string

exif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.

exif.decode_jis_motorola string

exif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

exif.decode_jis_intel string

exif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

EXIF_USE_MBSTRING (integer)

The exif_imagetype() lists several related built-in constants.

Typy zasobów
Funkcje Exif
Exif


Funkcje Exif

Spis treści

  • exif_imagetype — Determine the type of an image
  • exif_read_data — Reads the EXIF headers from JPEG or TIFF
  • exif_tagname — Get the header name for an index
  • exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image
  • read_exif_data — Alias dla exif_read_data
Stałe predefiniowane
exif_imagetype
Exif


Determine the type of an image

Funkcje Exif
exif_read_data
Funkcje Exif
PHP Manual

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5)

exif_imagetype — Determine the type of an image

Opis

int exif_imagetype ( string $filename )

exif_imagetype() reads the first bytes of an image and checks its signature.

exif_imagetype() can be used to avoid calls to other exif functions with unsupported file types or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in the browser.

Parametry

filename
The image being checked.

Zwracane wartości

When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.

Rejestr zmian

Wersja | Opis
5.3.0 | Added icon support.
4.3.2 | Support for JPC, JP2, JPX, JB2, XBM, and WBMP
4.3.0 | Support for SWC

Stałe predefiniowane

The following constants are defined, and represent possible exif_imagetype() return values:

Imagetype Constants
Value | Constant
1 | IMAGETYPE_GIF
2 | IMAGETYPE_JPEG
3 | IMAGETYPE_PNG
4 | IMAGETYPE_SWF
5 | IMAGETYPE_PSD
6 | IMAGETYPE_BMP
7 | IMAGETYPE_TIFF_II (intel byte order)
8 | IMAGETYPE_TIFF_MM (motorola byte order)
9 | IMAGETYPE_JPC
10 | IMAGETYPE_JP2
11 | IMAGETYPE_JPX
12 | IMAGETYPE_JB2
13 | IMAGETYPE_SWC
14 | IMAGETYPE_IFF
15 | IMAGETYPE_WBMP
16 | IMAGETYPE_XBM
17 | IMAGETYPE_ICO

Przykłady

Przykład #1 exif_imagetype() example

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>

Zobacz też:

  • image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • getimagesize() - Get the size of an image

Funkcje Exif
exif_read_data
Funkcje Exif


Reads the EXIF headers from JPEG or TIFF

exif_imagetype
exif_tagname
Funkcje Exif
PHP Manual

exif_read_data

(PHP 4 >= 4.2.0, PHP 5)

exif_read_data — Reads the EXIF headers from JPEG or TIFF

Opis

array exif_read_data ( string $filename [, string $sections = NULL [, bool $arrays = false [, bool $thumbnail = false ]]] )

exif_read_data() reads the EXIF headers from a JPEG or TIFF image file. This way you can read meta data generated by digital cameras.

EXIF headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.

Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML.

When an Exif header contains a Copyright note, this itself can contain two values. As the solution is inconsistent in the Exif 2.10 standard, the COMPUTED section will return both entries Copyright.Photographer and Copyright.Editor while the IFD0 sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The COMPUTED will also contain the entry Copyright which is either the original copyright string, or a comma separated list of the photo and editor copyright.

The tag UserComment has the same problem as the Copyright tag. It can store two values. First the encoding used, and second the value itself. If so the IFD section only contains the encoding or a byte array. The COMPUTED section will store both in the entries UserCommentEncoding and UserComment. The entry UserComment is available in both cases so it should be used in preference to the value in IFD0 section.

exif_read_data() also validates EXIF data tags according to the EXIF specification (» http://exif.org/Exif2-2.PDF, page 20).

Informacja:

Windows Me/XP can both wipe the Exif headers when connecting to a camera.

Parametry

filename

The name of the image file being read. This cannot be an URL.

sections

Is a comma separated list of sections that need to be present in file to produce a result array. If none of the requested sections could be found the return value is FALSE.

FILE | FileName, FileSize, FileDateTime, SectionsFound
COMPUTED | html, Width, Height, IsColor, and more if available. Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML.
ANY_TAG | Any information that has a Tag e.g. IFD0, EXIF, ...
IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
THUMBNAIL | A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section.
COMMENT | Comment headers of JPEG images.
EXIF | The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related.

arrays

Specifies whether or not each section becomes an array. The sections COMPUTED, THUMBNAIL, and COMMENT always become arrays as they may contain values whose names conflict with other sections.

thumbnail

When set to TRUE the thumbnail itself is read. Otherwise, only the tagged data is read.

Zwracane wartości

It returns an associative array where the array indexes are the header names and the array values are the values associated with those headers. If no data can be returned, exif_read_data() will return FALSE.

Rejestr zmian

Wersja | Opis
4.3.0 | Can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in a THUMBNAIL subarray, and can return thumbnails in TIFF format. Also, there is no longer a maximum length for returned values (not until the memory limit has been reached)
4.3.0 | If PHP has mbstring support, the user comment can automatically change encoding. Also, if the user comment uses Unicode or JIS encoding this encoding will automatically be changed according to the exif ini settings in php.ini
4.3.0 | If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. Also, COMPUTED and UserComment no longer only contain the first copyright entry if the datatype was wrong.

Przykłady

Przykład #1 exif_read_data() example

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
    foreach ($section as $name => $val) {
        echo "$key.$name: $val<br />\n";
    }
}
?>

The first call fails because the image has no header information.

Powyższy przykład wyświetli coś podobnego do:

test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

Zobacz też:

  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image
  • getimagesize() - Get the size of an image

exif_imagetype
exif_tagname
Funkcje Exif


Get the header name for an index

exif_read_data
exif_thumbnail
Funkcje Exif
PHP Manual

exif_tagname

(PHP 4 >= 4.2.0, PHP 5)

exif_tagname — Get the header name for an index

Opis

string exif_tagname ( int $index )

Parametry

index

The Tag ID for which a Tag Name will be looked up.

Zwracane wartości

Returns the header name, or FALSE if index is not a defined EXIF tag id.

Przykłady

Przykład #1 exif_tagname() example

<?php
echo "256: ".exif_tagname(256).PHP_EOL;
echo "257: ".exif_tagname(257).PHP_EOL;
?>

Powyższy przykład wyświetli:

256: ImageWidth
257: ImageLength

Zobacz też:

  • exif_imagetype() - Determine the type of an image
  • » EXIF Specification
  • » EXIF Tags

exif_read_data
exif_thumbnail
Funkcje Exif


Retrieve the embedded thumbnail of a TIFF or JPEG image

exif_tagname
read_exif_data
Funkcje Exif
PHP Manual

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5)

exif_thumbnail — Retrieve the embedded thumbnail of a TIFF or JPEG image

Opis

string exif_thumbnail ( string $filename [, int &$width [, int &$height [, int &$imagetype ]]] )

exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image.

If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.

It is possible that exif_thumbnail() cannot create an image but can determine its size. In this case, the return value is FALSE but width and height are set.

Parametry

filename

The name of the image file being read. This image contains an embedded thumbnail.

width

The return width of the returned thumbnail.

height

The returned height of the returned thumbnail.

imagetype

The returned image type of the returned thumbnail. This is either TIFF or JPEG.

Zwracane wartości

Returns the embedded thumbnail, or FALSE if the image contains no thumbnail.

Rejestr zmian

Wersja | Opis
4.3.0 | The optional parameters width, height, and imagetype all became available.
4.3.0 | May return thumbnails in the TIFF format.

Przykłady

Przykład #1 exif_thumbnail() example

<?php
if (array_key_exists('file', $_REQUEST)) {
    $image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
    $image = false;
}
if ($image!==false) {
    header('Content-type: ' .image_type_to_mime_type($type));
    echo $image;
    exit;
} else {
    // no thumbnail available, handle the error here
    echo 'No thumbnail available';
}
?>

Zobacz też:

  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

exif_tagname
read_exif_data
Funkcje Exif


Alias dla exif_read_data

exif_thumbnail
GD
Funkcje Exif
PHP Manual

read_exif_data

(PHP 4 >= 4.0.1, PHP 5)

read_exif_data — Alias dla exif_read_data()

Opis

Ta funkcja jest aliasem dla: exif_read_data().

exif_thumbnail
GD
Funkcje Exif


Image Processing and GD

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • PNG creation with PHP
    • Adding watermarks to images using alpha channels
    • Using imagecopymerge to create a translucent watermark
  • GD and Image Funkcje
    • gd_info — Retrieve information about the currently installed GD library
    • getimagesize — Get the size of an image
    • image_type_to_extension — Get file extension for image type
    • image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
    • image2wbmp — Wysłanie obrazu do przeglądarki lub zapis do pliku
    • imagealphablending — Set the blending mode for an image
    • imageantialias — Should antialias functions be used or not
    • imagearc — Draws an arc
    • imagechar — Draw a character horizontally
    • imagecharup — Draw a character vertically
    • imagecolorallocate — Allocate a color for an image
    • imagecolorallocatealpha — Allocate a color for an image
    • imagecolorat — Get the index of the color of a pixel
    • imagecolorclosest — Get the index of the closest color to the specified color
    • imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
    • imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
    • imagecolordeallocate — De-allocate a color for an image
    • imagecolorexact — Get the index of the specified color
    • imagecolorexactalpha — Get the index of the specified color + alpha
    • imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version
    • imagecolorresolve — Get the index of the specified color or its closest possible alternative
    • imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
    • imagecolorset — Set the color for the specified palette index
    • imagecolorsforindex — Get the colors for an index
    • imagecolorstotal — Find out the number of colors in an image's palette
    • imagecolortransparent — Define a color as transparent
    • imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
    • imagecopy — Copy part of an image
    • imagecopymerge — Copy and merge part of an image
    • imagecopymergegray — Copy and merge part of an image with gray scale
    • imagecopyresampled — Copy and resize part of an image with resampling
    • imagecopyresized — Copy and resize part of an image
    • imagecreate — Create a new palette based image
    • imagecreatefromgd2 — Create a new image from GD2 file or URL
    • imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
    • imagecreatefromgd — Create a new image from GD file or URL
    • imagecreatefromgif — Tworzy nowy obraz z pliku lub URL
    • imagecreatefromjpeg — Tworzy nowy obraz z pliku lub URL
    • imagecreatefrompng — Tworzy nowy obraz z pliku lub URL
    • imagecreatefromstring — Create a new image from the image stream in the string
    • imagecreatefromwbmp — Tworzy nowy obraz z pliku lub URL
    • imagecreatefromxbm — Tworzy nowy obraz z pliku lub URL
    • imagecreatefromxpm — Tworzy nowy obraz z pliku lub URL
    • imagecreatetruecolor — Create a new true color image
    • imagedashedline — Draw a dashed line
    • imagedestroy — Destroy an image
    • imageellipse — Draw an ellipse
    • imagefill — Flood fill
    • imagefilledarc — Draw a partial arc and fill it
    • imagefilledellipse — Draw a filled ellipse
    • imagefilledpolygon — Draw a filled polygon
    • imagefilledrectangle — Draw a filled rectangle
    • imagefilltoborder — Flood fill to specific color
    • imagefilter — Applies a filter to an image
    • imagefontheight — Get font height
    • imagefontwidth — Get font width
    • imageftbbox — Give the bounding box of a text using fonts via freetype2
    • imagefttext — Write text to the image using fonts using FreeType 2
    • imagegammacorrect — Apply a gamma correction to a GD image
    • imagegd2 — Output GD2 image to browser or file
    • imagegd — Output GD image to browser or file
    • imagegif — Wysłanie obrazu do przeglądarki lub zapis do pliku
    • imagegrabscreen — Captures the whole screen
    • imagegrabwindow — Captures a window
    • imageinterlace — Enable or disable interlace
    • imageistruecolor — Finds whether an image is a truecolor image
    • imagejpeg — Wysłanie obrazu do przeglądarki lub zapis do pliku
    • imagelayereffect — Set the alpha blending flag to use the bundled libgd layering effects
    • imageline — Draw a line
    • imageloadfont — Load a new font
    • imagepalettecopy — Copy the palette from one image to another
    • imagepng — Output a PNG image to either the browser or a file
    • imagepolygon — Draws a polygon
    • imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
    • imagepsencodefont — Change the character encoding vector of a font
    • imagepsextendfont — Extend or condense a font
    • imagepsfreefont — Free memory used by a PostScript Type 1 font
    • imagepsloadfont — Load a PostScript Type 1 font from file
    • imagepsslantfont — Slant a font
    • imagepstext — Draws a text over an image using PostScript Type1 fonts
    • imagerectangle — Draw a rectangle
    • imagerotate — Rotate an image with a given angle
    • imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
    • imagesetbrush — Set the brush image for line drawing
    • imagesetpixel — Set a single pixel
    • imagesetstyle — Set the style for line drawing
    • imagesetthickness — Set the thickness for line drawing
    • imagesettile — Set the tile image for filling
    • imagestring — Draw a string horizontally
    • imagestringup — Draw a string vertically
    • imagesx — Get image width
    • imagesy — Get image height
    • imagetruecolortopalette — Convert a true color image to a palette image
    • imagettfbbox — Give the bounding box of a text using TrueType fonts
    • imagettftext — Write text to the image using TrueType fonts
    • imagetypes — Return the image types supported by this PHP build
    • imagewbmp — Wysłanie obrazu do przeglądarki lub zapis do pliku
    • imagexbm — Output XBM image to browser or file
    • iptcembed — Embeds binary IPTC data into a JPEG image
    • iptcparse — Parse a binary IPTC block into single tags.
    • jpeg2wbmp — Convert JPEG image file to WBMP image file
    • png2wbmp — Convert PNG image file to WBMP image file
read_exif_data
Wstęp
Przetwarzanie i generowanie obrazów


Wstęp

PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

With the exif extension, you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras. The exif functions do not require the GD library.

Informacja: Read the requirements section about how to expand image capabilities to read, write and modify images. To read meta data of pictures taken by digital cameras you need the above mentioned exif extension.

Informacja: The getimagesize() function does not require the GD extension.

GD
Instalacja/Konfiguracja
GD


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
GD


Wymagania

If you have the GD library (available at » http://www.libgd.org/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. Versions of GD older than gd-1.6 support GIF format images, and do not support PNG, where versions greater than gd-1.6 and less than gd-2.0.28 support PNG, not GIF. GIF support was re-enabled in gd-2.0.28.

Informacja: Since PHP 4.3 there is a bundled version of the GD lib. This bundled version has some additional features like alpha blending, and should be used in preference to the external library since its codebase is better maintained and more stable.

You may wish to enhance GD to handle more image formats.

Supported image formats
Image format | Library to download | Notes
gif |  | Only supported in GD versions older than gd-1.6 and newer than gd-2.0.28. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library. Write support is available since PHP 4.3.9 and PHP 5.0.1.
jpeg | » http://www.ijg.org/ | When building the jpeg library (prior to building PHP) you must use the --enable-shared option in the configure step. If you do not, you will receive an error saying libjpeg.(a|so) not found when you get to the configure step of building PHP.
png | » http://www.libpng.org/pub/png/libpng.html | Only supported in GD versions greater than gd-1.6.
xpm | » ftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html | It's likely you have this library already available, if your system has an installed X-Environment.

You may wish to enhance GD to deal with different fonts. The following font libraries are supported:

Supported font libraries
Font library | Download | Notes
FreeType 1.x | » http://www.freetype.org/ | Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
FreeType 2 | » http://www.freetype.org/ |
T1lib | » ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) | Support for Postscript Type 1 fonts.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To enable GD-support configure PHP --with-gd[=DIR] , where DIR is the GD base install directory. To use the recommended bundled version of the GD library (which was first bundled in PHP 4.3.0), use the configure option --with-gd . GD library requires libpng and libjpeg to compile.

In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.

Enhance the capabilities of GD to handle more image formats by specifying the --with-XXXX configure switch to your PHP configure line.

Supported image formats
Image Format | Configure Switch
jpeg | To enable support for jpeg add --with-jpeg-dir=DIR . Jpeg 6b, 7 or 8 are supported.
png | To enable support for png add --with-png-dir=DIR . Note, libpng requires the zlib library, therefore add --with-zlib-dir[=DIR] to your configure line.
xpm | To enable support for xpm add --with-xpm-dir=DIR . If configure is not able to find the required libraries, you may add the path to your X11 libraries.

Informacja: When compiling PHP with libpng, you must use the same version that was linked with the GD library.

Enhance the capabilities of GD to deal with different fonts by specifying the --with-XXXX configure switch to your PHP configure line.

Supported font libraries
Font library | Configure Switch
FreeType 1.x | To enable support for FreeType 1.x add --with-ttf[=DIR] .
FreeType 2 | To enable support for FreeType 2 add --with-freetype-dir=DIR .
T1lib | To enable support for T1lib (Postscript Type 1 fonts) add --with-t1lib[=DIR] .
Native TrueType string function | To enable support for native TrueType string function add --enable-gd-native-ttf .

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Image Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Changelog
gd.jpeg_ignore_warning | "0" | PHP_INI_ALL | Available since PHP 5.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.

gd.jpeg_ignore_warning bool

Ignore warnings created by jpeg2wbmp() and imagecreatefromjpeg()

See also the exif configuration directives.

Ostrzeżenie

Image functions are very memory intensive. Be sure to set memory_limit high enough.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines two resource types: an image identifier and a font identifier.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

GD_VERSION (string)
The GD version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MAJOR_VERSION (integer)
The GD major version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MINOR_VERSION (integer)
The GD minor version PHP was compiled against. (Available as of PHP 5.2.4)
GD_RELEASE_VERSION (integer)
The GD release version PHP was compiled against. (Available as of PHP 5.2.4)
GD_EXTRA_VERSION (string)
The GD "extra" version (beta/rc..) PHP was compiled against. (Available as of PHP 5.2.4)
GD_BUNDLED (integer)
When the bundled version of GD is used this is 1 otherwise its set to 0.
IMG_GIF (integer)
Used as a return value by imagetypes()
IMG_JPG (integer)
Used as a return value by imagetypes()
IMG_JPEG (integer)
Used as a return value by imagetypes()

Informacja:

This constant has the same value as IMG_JPG

IMG_PNG (integer)
Used as a return value by imagetypes()
IMG_WBMP (integer)
Used as a return value by imagetypes()
IMG_XPM (integer)
Used as a return value by imagetypes()
IMG_COLOR_TILED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_STYLED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_BRUSHED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_STYLEDBRUSHED (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_COLOR_TRANSPARENT (integer)
Special color option which can be used in stead of color allocated with imagecolorallocate() or imagecolorallocatealpha()
IMG_ARC_ROUNDED (integer)
A style constant used by the imagefilledarc() function.

Informacja:

This constant has the same value as IMG_ARC_PIE

IMG_ARC_PIE (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_CHORD (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_NOFILL (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_EDGED (integer)
A style constant used by the imagefilledarc() function.
IMG_GD2_RAW (integer)
A type constant used by the imagegd2() function.
IMG_GD2_COMPRESSED (integer)
A type constant used by the imagegd2() function.
IMG_EFFECT_REPLACE (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_ALPHABLEND (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_NORMAL (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_OVERLAY (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_FILTER_NEGATE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GRAYSCALE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_BRIGHTNESS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_CONTRAST (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_COLORIZE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EDGEDETECT (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GAUSSIAN_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SELECTIVE_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EMBOSS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_MEAN_REMOVAL (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SMOOTH (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_PIXELATE (integer)
Special GD filter used by the imagefilter() function. (Available as of PHP 5.3.0)
IMAGETYPE_GIF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG2000 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PNG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PSD (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_BMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_WBMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_XBM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_II (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_MM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_IFF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JB2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JP2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPX (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_ICO (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 5.3.0)
PNG_NO_FILTER (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_NONE (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_SUB (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_UP (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_AVG (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_PAETH (integer)
A special PNG filter, used by the imagepng() function.
PNG_ALL_FILTERS (integer)
A special PNG filter, used by the imagepng() function.
Typy zasobów
Przykłady
GD


Przykłady

Spis treści

  • PNG creation with PHP
  • Adding watermarks to images using alpha channels
  • Using imagecopymerge to create a translucent watermark
Stałe predefiniowane
PNG creation with PHP
GD


PNG creation with PHP

Przykład #1 PNG creation with PHP

<?php

header("Content-type: image/png");
$string = $_GET['text'];
$im     = imagecreatefrompng("images/button1.png");
$orange = imagecolorallocate($im, 220, 210, 60);
$px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $orange);
imagepng($im);
imagedestroy($im);

?>
This example would be called from a page with a tag like: <img src="button.php?text=text">. The above button.php script then takes this "text" string and overlays it on top of a base image which in this case is "images/button1.png" and outputs the resulting image. This is a very convenient way to avoid having to draw new button images every time you want to change the text of a button. With this method they are dynamically generated.

Przykłady
Adding watermarks to images using alpha channels
Przykłady


Adding watermarks to images using alpha channels

Przykład #1 Adding watermarks to images using alpha channels

<?php
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo
// width to calculate positioning of the stamp.
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Adding watermarks to images using alpha channels
This example is a common way to add watermarks and stamps to photos and copyrighted images. Note that the presence of an alpha channel in the stamp image as the text is anti-aliased. This is preserved during copying.

PNG creation with PHP
Using imagecopymerge to create a translucent watermark
Przykłady


Using imagecopymerge to create a translucent watermark

Adding watermarks to images using alpha channels
GD and Image Funkcje
Przykłady
PHP Manual

Using imagecopymerge() to create a translucent watermark

Przykład #1 Using imagecopymerge() to create a translucent watermark

<?php
// Load the stamp and the photo to apply the watermark to
$im = imagecreatefromjpeg('photo.jpeg');

// First we create our stamp image manually from GD
$stamp = imagecreatetruecolor(100, 70);
imagefilledrectangle($stamp, 0, 0, 99, 69, 0x0000FF);
imagefilledrectangle($stamp, 9, 9, 90, 60, 0xFFFFFF);
$im = imagecreatefromjpeg('photo.jpeg');
imagestring($stamp, 5, 20, 20, 'libGD', 0x0000FF);
imagestring($stamp, 3, 20, 40, '(c) 2007-9', 0x0000FF);

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Merge the stamp onto our photo with an opacity (transparency) of 50%
imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);

// Save the image to file and free memory
imagepng($im, 'photo_stamp.png');
imagedestroy($im);

?>
Using imagecopymerge() to create a translucent watermark
This example uses imagecopymerge() to merge the stamp with our original image. Using this we can set the opacity of our stamp - in our example we've set it to 50% opacity (another term for transparency). In practice this would be useful in copyright protection as semi-transparent watermarks are hard to remove yet allow viewers to see the image.

Adding watermarks to images using alpha channels
GD and Image Funkcje
Przykłady


GD and Image Funkcje

Spis treści

  • gd_info — Retrieve information about the currently installed GD library
  • getimagesize — Get the size of an image
  • image_type_to_extension — Get file extension for image type
  • image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • image2wbmp — Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagealphablending — Set the blending mode for an image
  • imageantialias — Should antialias functions be used or not
  • imagearc — Draws an arc
  • imagechar — Draw a character horizontally
  • imagecharup — Draw a character vertically
  • imagecolorallocate — Allocate a color for an image
  • imagecolorallocatealpha — Allocate a color for an image
  • imagecolorat — Get the index of the color of a pixel
  • imagecolorclosest — Get the index of the closest color to the specified color
  • imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha
  • imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
  • imagecolordeallocate — De-allocate a color for an image
  • imagecolorexact — Get the index of the specified color
  • imagecolorexactalpha — Get the index of the specified color + alpha
  • imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version
  • imagecolorresolve — Get the index of the specified color or its closest possible alternative
  • imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative
  • imagecolorset — Set the color for the specified palette index
  • imagecolorsforindex — Get the colors for an index
  • imagecolorstotal — Find out the number of colors in an image's palette
  • imagecolortransparent — Define a color as transparent
  • imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
  • imagecopy — Copy part of an image
  • imagecopymerge — Copy and merge part of an image
  • imagecopymergegray — Copy and merge part of an image with gray scale
  • imagecopyresampled — Copy and resize part of an image with resampling
  • imagecopyresized — Copy and resize part of an image
  • imagecreate — Create a new palette based image
  • imagecreatefromgd2 — Create a new image from GD2 file or URL
  • imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL
  • imagecreatefromgd — Create a new image from GD file or URL
  • imagecreatefromgif — Tworzy nowy obraz z pliku lub URL
  • imagecreatefromjpeg — Tworzy nowy obraz z pliku lub URL
  • imagecreatefrompng — Tworzy nowy obraz z pliku lub URL
  • imagecreatefromstring — Create a new image from the image stream in the string
  • imagecreatefromwbmp — Tworzy nowy obraz z pliku lub URL
  • imagecreatefromxbm — Tworzy nowy obraz z pliku lub URL
  • imagecreatefromxpm — Tworzy nowy obraz z pliku lub URL
  • imagecreatetruecolor — Create a new true color image
  • imagedashedline — Draw a dashed line
  • imagedestroy — Destroy an image
  • imageellipse — Draw an ellipse
  • imagefill — Flood fill
  • imagefilledarc — Draw a partial arc and fill it
  • imagefilledellipse — Draw a filled ellipse
  • imagefilledpolygon — Draw a filled polygon
  • imagefilledrectangle — Draw a filled rectangle
  • imagefilltoborder — Flood fill to specific color
  • imagefilter — Applies a filter to an image
  • imagefontheight — Get font height
  • imagefontwidth — Get font width
  • imageftbbox — Give the bounding box of a text using fonts via freetype2
  • imagefttext — Write text to the image using fonts using FreeType 2
  • imagegammacorrect — Apply a gamma correction to a GD image
  • imagegd2 — Output GD2 image to browser or file
  • imagegd — Output GD image to browser or file
  • imagegif — Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagegrabscreen — Captures the whole screen
  • imagegrabwindow — Captures a window
  • imageinterlace — Enable or disable interlace
  • imageistruecolor — Finds whether an image is a truecolor image
  • imagejpeg — Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagelayereffect — Set the alpha blending flag to use the bundled libgd layering effects
  • imageline — Draw a line
  • imageloadfont — Load a new font
  • imagepalettecopy — Copy the palette from one image to another
  • imagepng — Output a PNG image to either the browser or a file
  • imagepolygon — Draws a polygon
  • imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
  • imagepsencodefont — Change the character encoding vector of a font
  • imagepsextendfont — Extend or condense a font
  • imagepsfreefont — Free memory used by a PostScript Type 1 font
  • imagepsloadfont — Load a PostScript Type 1 font from file
  • imagepsslantfont — Slant a font
  • imagepstext — Draws a text over an image using PostScript Type1 fonts
  • imagerectangle — Draw a rectangle
  • imagerotate — Rotate an image with a given angle
  • imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
  • imagesetbrush — Set the brush image for line drawing
  • imagesetpixel — Set a single pixel
  • imagesetstyle — Set the style for line drawing
  • imagesetthickness — Set the thickness for line drawing
  • imagesettile — Set the tile image for filling
  • imagestring — Draw a string horizontally
  • imagestringup — Draw a string vertically
  • imagesx — Get image width
  • imagesy — Get image height
  • imagetruecolortopalette — Convert a true color image to a palette image
  • imagettfbbox — Give the bounding box of a text using TrueType fonts
  • imagettftext — Write text to the image using TrueType fonts
  • imagetypes — Return the image types supported by this PHP build
  • imagewbmp — Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagexbm — Output XBM image to browser or file
  • iptcembed — Embeds binary IPTC data into a JPEG image
  • iptcparse — Parse a binary IPTC block into single tags.
  • jpeg2wbmp — Convert JPEG image file to WBMP image file
  • png2wbmp — Convert PNG image file to WBMP image file
Using imagecopymerge to create a translucent watermark
gd_info
GD


Retrieve information about the currently installed GD library

GD and Image Funkcje
getimagesize
GD and Image Funkcje
PHP Manual

gd_info

(PHP 4 >= 4.3.0, PHP 5)

gd_info — Retrieve information about the currently installed GD library

Opis

array gd_info ( void )

Gets information about the version and capabilities of the installed GD library.

Zwracane wartości

Returns an associative array.

Elements of array returned by gd_info()
Attribute | Meaning
GD Version | string value describing the installed libgd version.
Freetype Support | boolean value. TRUE if Freetype Support is installed.
Freetype Linkage | string value describing the way in which Freetype was linked. Expected values are: 'with freetype', 'with TTF library', and 'with unknown library'. This element will only be defined if Freetype Support evaluated to TRUE.
T1Lib Support | boolean value. TRUE if T1Lib support is included.
GIF Read Support | boolean value. TRUE if support for reading GIF images is included.
GIF Create Support | boolean value. TRUE if support for creating GIF images is included.
JPEG Support | boolean value. TRUE if JPEG support is included.
PNG Support | boolean value. TRUE if PNG support is included.
WBMP Support | boolean value. TRUE if WBMP support is included.
XBM Support | boolean value. TRUE if XBM support is included.

Informacja:

Previous to PHP 5.3.0, the JPEG Support attribute was named JPG Support.

Przykłady

Przykład #1 Using gd_info()

<?php
var_dump(gd_info());
?>

Powyższy przykład wyświetli coś podobnego do:

array(9) {
  ["GD Version"]=>
  string(24) "bundled (2.0 compatible)"
  ["FreeType Support"]=>
  bool(false)
  ["T1Lib Support"]=>
  bool(false)
  ["GIF Read Support"]=>
  bool(true)
  ["GIF Create Support"]=>
  bool(false)
  ["JPEG Support"]=>
  bool(false)
  ["PNG Support"]=>
  bool(true)
  ["WBMP Support"]=>
  bool(true)
  ["XBM Support"]=>
  bool(false)
}

Rejestr zmian

Wersja | Opis
5.3.0 | JPG Support attribute renamed to JPEG Support.

Zobacz też:

  • imagepng() - Output a PNG image to either the browser or a file
  • imagejpeg() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagegif() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagewbmp() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagetypes() - Return the image types supported by this PHP build

GD and Image Funkcje
getimagesize
GD and Image Funkcje


Get the size of an image

gd_info
image_type_to_extension
GD and Image Funkcje
PHP Manual

getimagesize

(PHP 4, PHP 5)

getimagesize — Get the size of an image

Opis

array getimagesize ( string $filename [, array &$imageinfo ] )

The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondant HTTP content type.

getimagesize() can also return some more information in imageinfo parameter.

Informacja: Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain multiple JPEG 2000 codestreams. In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.

Informacja: The information about icons are retrieved from the icon with the highest bitrate.

Parametry

filename

This parameter specifies the file you wish to retrieve information about. It can reference a local file or (configuration permitting) a remote file using one of the supported streams.

imageinfo

This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

Zwracane wartości

Returns an array with 7 elements.

Index 0 and 1 contains respectively the width and the height of the image.

Informacja:

Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.

Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.

mime is the correspondant MIME type of the image. This information can be used to deliver images with the correct HTTP Content-type header:

Przykład #1 getimagesize() and MIME types

<?php
$size = getimagesize($filename);
$fp = fopen($filename, "rb");
if ($size && $fp) {
    header("Content-type: {$size['mime']}");
    fpassthru($fp);
    exit;
} else {
    // error
}
?>

channels will be 3 for RGB pictures and 4 for CMYK pictures.

bits is the number of bits for each color.

For some image types, the presence of channels and bits values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.

On failure, FALSE is returned.

Błędy/Wyjątki

If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE.

Rejestr zmian

Wersja | Opis
5.3.0 | Added icon support.
5.2.3 | Read errors generated by this function downgraded to E_NOTICE from E_WARNING.
4.3.2 | Support for JPC, JP2, JPX, JB2, XBM, and WBMP became available.
4.3.2 | JPEG 2000 support was added for the imageinfo parameter.
4.3.0 | bits and channels are present for other image types, too.
4.3.0 | mime was added.
4.3.0 | Support for SWC and IFF was added.
4.2.0 | Support for TIFF was added.
4.0.6 | Support for BMP and PSD was added.
4.0.5 | URL support was added.

Przykłady

Przykład #2 getimagesize() example

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>

Przykład #3 getimagesize (URL)

<?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");

// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");

?>

Przykład #4 getimagesize() returning IPTC

<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]);
    var_dump($iptc);
}
?>

Notatki

Informacja:

Ta funkcja nie wymaga dostępu do biblioteki GD.

Zobacz też:

  • image_type_to_mime_type() - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
  • exif_imagetype() - Determine the type of an image
  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image

gd_info
image_type_to_extension
GD and Image Funkcje


Get file extension for image type

getimagesize
image_type_to_mime_type
GD and Image Funkcje
PHP Manual

image_type_to_extension

(PHP 5)

image_type_to_extension — Get file extension for image type

Opis

string image_type_to_extension ( int $imagetype [, bool $include_dot = TRUE ] )

Returns the extension for the given IMAGETYPE_XXX constant.

Parametry

imagetype

One of the IMAGETYPE_XXX constant.

include_dot

Whether to prepend a dot to the extension or not. Default to TRUE.

Zwracane wartości

A string with the extension corresponding to the given image type.

Przykłady

Przykład #1 image_type_to_extension() example

<?php
// Create image instance
$im = imagecreatetruecolor(100, 100);

// Save image
imagepng($im, './test' . image_type_to_extension(IMAGETYPE_PNG));
imagedestroy($im);
?>

Notatki

Informacja:

Ta funkcja nie wymaga dostępu do biblioteki GD.

getimagesize
image_type_to_mime_type
GD and Image Funkcje


Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

image_type_to_extension
image2wbmp
GD and Image Funkcje
PHP Manual

image_type_to_mime_type

(PHP 4 >= 4.3.0, PHP 5)

image_type_to_mime_type — Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

Opis

string image_type_to_mime_type ( int $imagetype )

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

Parametry

imagetype

One of the IMAGETYPE_XXX constants.

Zwracane wartości

The returned values are as follows

Returned values Constants
imagetype | Returned value
IMAGETYPE_GIF | image/gif
IMAGETYPE_JPEG | image/jpeg
IMAGETYPE_PNG | image/png
IMAGETYPE_SWF | application/x-shockwave-flash
IMAGETYPE_PSD | image/psd
IMAGETYPE_BMP | image/bmp
IMAGETYPE_TIFF_II (intel byte order) | image/tiff
IMAGETYPE_TIFF_MM (motorola byte order) | image/tiff
IMAGETYPE_JPC | application/octet-stream
IMAGETYPE_JP2 | image/jp2
IMAGETYPE_JPX | application/octet-stream
IMAGETYPE_JB2 | application/octet-stream
IMAGETYPE_SWC | application/x-shockwave-flash
IMAGETYPE_IFF | image/iff
IMAGETYPE_WBMP | image/vnd.wap.wbmp
IMAGETYPE_XBM | image/xbm
IMAGETYPE_ICO | image/vnd.microsoft.icon

Przykłady

Przykład #1 image_type_to_mime_type() example

<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>

Notatki

Informacja:

Ta funkcja nie wymaga dostępu do biblioteki GD.

Zobacz też:

  • getimagesize() - Get the size of an image
  • exif_imagetype() - Determine the type of an image
  • exif_read_data() - Reads the EXIF headers from JPEG or TIFF
  • exif_thumbnail() - Retrieve the embedded thumbnail of a TIFF or JPEG image

image_type_to_extension
image2wbmp
GD and Image Funkcje


Wysłanie obrazu do przeglądarki lub zapis do pliku

image_type_to_mime_type
imagealphablending
GD and Image Funkcje
PHP Manual

image2wbmp

(PHP 4 >= 4.0.5, PHP 5)

image2wbmp — Wysłanie obrazu do przeglądarki lub zapis do pliku

Opis

bool image2wbmp ( resource $image [, string $filename [, int $threshold ]] )

image2wbmp() outputs or save a WBMP version of the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filename

Path to the saved file. If not given, the raw image stream will be outputted directly.

threshold

Threshold value, between 0 and 255 (inclusive).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 image2wbmp() example

<?php
$file = 'php.png';
$image = imagecreatefrompng($file);

header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_WBMP));
image2wbmp($image); // output the stream directly
imagedestroy($image);
?>

Notatki

Informacja:

WBMP support is only available if PHP was compiled against GD-1.8 or later.

Zobacz też:

  • imagewbmp() - Wysłanie obrazu do przeglądarki lub zapis do pliku

image_type_to_mime_type
imagealphablending
GD and Image Funkcje


Set the blending mode for an image

image2wbmp
imageantialias
GD and Image Funkcje
PHP Manual

imagealphablending

(PHP 4 >= 4.0.6, PHP 5)

imagealphablending — Set the blending mode for an image

Opis

bool imagealphablending ( resource $image , bool $blendmode )

imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

blendmode

Whether to enable the blending mode or not. On true color images the default value is TRUE otherwise the default value is FALSE

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagealphablending() usage example

<?php
// Create image
$im = imagecreatetruecolor(100, 100);

// Set alphablending to on
imagealphablending($im, true);

// Draw a square
imagefilledrectangle($im, 30, 30, 70, 70, imagecolorallocate($im, 255, 0, 0));

// Output
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

image2wbmp
imageantialias
GD and Image Funkcje


Should antialias functions be used or not

imagealphablending
imagearc
GD and Image Funkcje
PHP Manual

imageantialias

(PHP 4 >= 4.3.2, PHP 5)

imageantialias — Should antialias functions be used or not

Opis

bool imageantialias ( resource $image , bool $enabled )

Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images.

Thickness and styled are not supported.

Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

enabled

Whether to enable antialiasing or not.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A comparison of two lines, one with anti-aliasing switched on

<?php
// Setup an anti-aliased image and a normal image
$aa = imagecreatetruecolor(400, 100);
$normal = imagecreatetruecolor(200, 100);

// Switch antialiasing on for one image
imageantialias($aa, true);

// Allocate colors
$red = imagecolorallocate($normal, 255, 0, 0);
$red_aa = imagecolorallocate($aa, 255, 0, 0);

// Draw two lines, one with AA enabled
imageline($normal, 0, 0, 200, 100, $red);
imageline($aa, 0, 0, 200, 100, $red_aa);

// Merge the two images side by side for output (AA: left, Normal: Right)
imagecopymerge($aa, $normal, 200, 0, 0, 0, 200, 100, 100);

// Output image
header('Content-type: image/png');

imagepng($aa);
imagedestroy($aa);
imagedestroy($normal);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : A comparison of two lines, one with anti-aliasing switched on

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dołączoną wersją biblioteki GD.

Zobacz też:

  • imagecreatetruecolor() - Create a new true color image

imagealphablending
imagearc
GD and Image Funkcje


Draws an arc

imageantialias
imagechar
GD and Image Funkcje
PHP Manual

imagearc

(PHP 4, PHP 5)

imagearc — Draws an arc

Opis

bool imagearc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , int $end , int $color )

imagearc() draws an arc of circle centered at the given coordinates.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The arc width.

height

The arc height.

start

The arc start angle, in degrees.

end

The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise.

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Drawing a circle with imagearc()

<?php

// create a 200*200 image
$img = imagecreatetruecolor(200, 200);

// allocate some colors
$white = imagecolorallocate($img, 255, 255, 255);
$red   = imagecolorallocate($img, 255,   0,   0);
$green = imagecolorallocate($img,   0, 255,   0);
$blue  = imagecolorallocate($img,   0,   0, 255);

// draw the head
imagearc($img, 100, 100, 200, 200,  0, 360, $white);
// mouth
imagearc($img, 100, 100, 150, 150, 25, 155, $red);
// left and then the right eye
imagearc($img,  60,  75,  50,  50,  0, 360, $green);
imagearc($img, 140,  75,  50,  50,  0, 360, $blue);

// output image in the browser
header("Content-type: image/png");
imagepng($img);

// free memory
imagedestroy($img);

?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Drawing a circle with imagearc()

Zobacz też:

  • imagefilledarc() - Draw a partial arc and fill it
  • imageellipse() - Draw an ellipse
  • imagefilledellipse() - Draw a filled ellipse

imageantialias
imagechar
GD and Image Funkcje


Draw a character horizontally

imagearc
imagecharup
GD and Image Funkcje
PHP Manual

imagechar

(PHP 4, PHP 5)

imagechar — Draw a character horizontally

Opis

bool imagechar ( resource $image , int $font , int $x , int $y , string $c , int $color )

imagechar() draws the first character of c in the image identified by image with its upper-left at x,y (top left is 0, 0) with the color color.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

czcionka

Może przyjąć 1, 2, 3, 4, 5 dla wbudowanych czcionek w kodowaniu latin2 (gdzie większy numer odpowiada większej czcionce) lub własny dowolny identyfikator czcionki zarejestrowany przez imageloadfont().

x

x-coordinate of the start.

y

y-coordinate of the start.

c

The character to draw.

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagechar() example

<?php

$im = imagecreate(100, 100);

$string = 'PHP';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// prints a black "P" in the top left corner
imagechar($im, 1, 0, 0, $string, $black);

header('Content-type: image/png');
imagepng($im);

?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagechar()

Zobacz też:

  • imagecharup() - Draw a character vertically
  • imageloadfont() - Load a new font

imagearc
imagecharup
GD and Image Funkcje


Draw a character vertically

imagechar
imagecolorallocate
GD and Image Funkcje
PHP Manual

imagecharup

(PHP 4, PHP 5)

imagecharup — Draw a character vertically

Opis

bool imagecharup ( resource $image , int $font , int $x , int $y , string $c , int $color )

Draws the character c vertically at the specified coordinate on the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

czcionka

Może przyjąć 1, 2, 3, 4, 5 dla wbudowanych czcionek w kodowaniu latin2 (gdzie większy numer odpowiada większej czcionce) lub własny dowolny identyfikator czcionki zarejestrowany przez imageloadfont().

x

x-coordinate of the start.

y

y-coordinate of the start.

c

The character to draw.

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagecharup() example

<?php

$im = imagecreate(100, 100);

$string = 'Note that the first letter is a N';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// prints a black "Z" on a white background
imagecharup($im, 3, 10, 10, $string, $black);

header('Content-type: image/png');
imagepng($im);

?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagecharup()

Zobacz też:

  • imagechar() - Draw a character horizontally
  • imageloadfont() - Load a new font

imagechar
imagecolorallocate
GD and Image Funkcje


Allocate a color for an image

imagecharup
imagecolorallocatealpha
GD and Image Funkcje
PHP Manual

imagecolorallocate

(PHP 4, PHP 5)

imagecolorallocate — Allocate a color for an image

Opis

int imagecolorallocate ( resource $image , int $red , int $green , int $blue )

Returns a color identifier representing the color composed of the given RGB components.

imagecolorallocate() must be called to create each color that is to be used in the image represented by image.

Informacja:

The first call to imagecolorallocate() fills the background color in palette-based images - images created using imagecreate().

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Zwracane wartości

A color identifier or FALSE if the allocation failed.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Rejestr zmian

Wersja | Opis
Prior to 5.1.3 | Returns -1 if the allocation failed.

Przykłady

Przykład #1 imagecolorallocate() example

<?php

$im = imagecreate(100, 100);

// sets background to red
$background = imagecolorallocate($im, 255, 0, 0);

// sets some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// hexadecimal way
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

?>

Zobacz też:

  • imagecolorallocatealpha() - Allocate a color for an image
  • imagecolordeallocate() - De-allocate a color for an image

imagecharup
imagecolorallocatealpha
GD and Image Funkcje


Allocate a color for an image

imagecolorallocate
imagecolorat
GD and Image Funkcje
PHP Manual

imagecolorallocatealpha

(PHP 4 >= 4.3.2, PHP 5)

imagecolorallocatealpha — Allocate a color for an image

Opis

int imagecolorallocatealpha ( resource $image , int $red , int $green , int $blue , int $alpha )

imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Zwracane wartości

A color identifier or FALSE if the allocation failed.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Rejestr zmian

Wersja | Opis
Prior to 5.1.3 | Returns -1 if the allocation failed.

Przykłady

Przykład #1 Example of using imagecolorallocatealpha()

<?php
$size = 300;
$image=imagecreatetruecolor($size, $size);

// something to get a white background with black border
$back = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $size - 1, $size - 1, $back);
imagerectangle($image, 0, 0, $size - 1, $size - 1, $border);

$yellow_x = 100;
$yellow_y = 75;
$red_x    = 120;
$red_y    = 165;
$blue_x   = 187;
$blue_y   = 125;
$radius   = 150;

// allocate colors with alpha values
$yellow = imagecolorallocatealpha($image, 255, 255, 0, 75);
$red    = imagecolorallocatealpha($image, 255, 0, 0, 75);
$blue   = imagecolorallocatealpha($image, 0, 0, 255, 75);

// drawing 3 overlapped circle
imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow);
imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red);
imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue);

// don't forget to output a correct header!
header('Content-Type: image/png');

// and finally, output the result
imagepng($image);
imagedestroy($image);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Example of using imagecolorallocatealpha()

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imagecolorallocate() - Allocate a color for an image
  • imagecolordeallocate() - De-allocate a color for an image

imagecolorallocate
imagecolorat
GD and Image Funkcje


Get the index of the color of a pixel

imagecolorallocatealpha
imagecolorclosest
GD and Image Funkcje
PHP Manual

imagecolorat

(PHP 4, PHP 5)

imagecolorat — Get the index of the color of a pixel

Opis

int imagecolorat ( resource $image , int $x , int $y )

Returns the index of the color of the pixel at the specified location in the image specified by image.

If PHP is compiled against GD library 2.0 or higher and the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

x

x-coordinate of the point.

y

y-coordinate of the point.

Zwracane wartości

Returns the index of the color.

Przykłady

Przykład #1 Access distinct RGB values

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;

var_dump($r, $g, $b);
?>

Powyższy przykład wyświetli coś podobnego do:

int(119)
int(123)
int(180)

Przykład #2 Human-readable RGB values using imagecolorsforindex()

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);

$colors = imagecolorsforindex($im, $rgb);

var_dump($colors);
?>

Powyższy przykład wyświetli coś podobnego do:

array(4) {
  ["red"]=>
  int(119)
  ["green"]=>
  int(123)
  ["blue"]=>
  int(180)
  ["alpha"]=>
  int(127)
}

Zobacz też:

  • imagecolorset() - Set the color for the specified palette index
  • imagecolorsforindex() - Get the colors for an index

imagecolorallocatealpha
imagecolorclosest
GD and Image Funkcje


Get the index of the closest color to the specified color

imagecolorat
imagecolorclosestalpha
GD and Image Funkcje
PHP Manual

imagecolorclosest

(PHP 4, PHP 5)

imagecolorclosest — Get the index of the closest color to the specified color

Opis

int imagecolorclosest ( resource $image , int $red , int $green , int $blue )

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.

The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.

Jeśli tworzony jest obraz z pliku, zwracane są indeksy kolorów użyte tylko w obrazie. Kolory będące tylko w palecie nie są zwracane.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Zwracane wartości

Returns the index of the closest color, in the palette of the image, to the specified one

Przykłady

Przykład #1 Search for a set of colors in an image

<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Search colors (RGB)
$colors = array(
    array(254, 145, 154),
    array(153, 145, 188),
    array(153, 90, 145),
    array(255, 137, 92)
);

// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
    $result = imagecolorclosest($im, $rgb[0], $rgb[1], $rgb[2]);
    $result = imagecolorsforindex($im, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']})";

    echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2]); Closest match: $result.\n";
}

imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

#0: Search (254, 145, 154); Closest match: (252, 150, 148).
#1: Search (153, 145, 188); Closest match: (148, 150, 196).
#2: Search (153, 90, 145); Closest match: (148, 90, 156).
#3: Search (255, 137, 92); Closest match: (252, 150, 92).

Zobacz też:

  • imagecolorexact() - Get the index of the specified color
  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha
  • imagecolorclosesthwb() - Get the index of the color which has the hue, white and blackness

imagecolorat
imagecolorclosestalpha
GD and Image Funkcje


Get the index of the closest color to the specified color + alpha

imagecolorclosest
imagecolorclosesthwb
GD and Image Funkcje
PHP Manual

imagecolorclosestalpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha

Opis

int imagecolorclosestalpha ( resource $image , int $red , int $green , int $blue , int $alpha )

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Zwracane wartości

Returns the index of the closest color in the palette.

Przykłady

Przykład #1 Search for a set of colors in an image

<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Search colors (RGB)
$colors = array(
    array(254, 145, 154, 50),
    array(153, 145, 188, 127),
    array(153, 90, 145, 0),
    array(255, 137, 92, 84)
);

// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
    $result = imagecolorclosestalpha($im, $rgb[0], $rgb[1], $rgb[2], $rgb[3]);
    $result = imagecolorsforindex($im, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']}, {$result['alpha']})";

    echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2], $rgb[3]); Closest match: $result.\n";
}

imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

#0: Search (254, 145, 154, 50); Closest match: (252, 150, 148, 0).
#1: Search (153, 145, 188, 127); Closest match: (148, 150, 196, 0).
#2: Search (153, 90, 145, 0); Closest match: (148, 90, 156, 0).
#3: Search (255, 137, 92, 84); Closest match: (252, 150, 92, 0).

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imagecolorexactalpha() - Get the index of the specified color + alpha
  • imagecolorclosest() - Get the index of the closest color to the specified color
  • imagecolorclosesthwb() - Get the index of the color which has the hue, white and blackness

imagecolorclosest
imagecolorclosesthwb
GD and Image Funkcje


Get the index of the color which has the hue, white and blackness

imagecolorclosestalpha
imagecolordeallocate
GD and Image Funkcje
PHP Manual

imagecolorclosesthwb

(PHP 4 >= 4.0.1, PHP 5)

imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness

Opis

int imagecolorclosesthwb ( resource $image , int $red , int $green , int $blue )

Get the index of the color which has the hue, white and blackness nearest the given color.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

Zwracane wartości

Returns an integer with the index of the color which has the hue, white and blackness nearest the given color.

Przykłady

Przykład #1 Example of using imagecolorclosesthwb()

<?php
$im = imagecreatefromgif('php.gif');

echo 'HWB: ' . imagecolorclosesthwb($im, 116, 115, 152);

imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

HWB: 33

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows

Zobacz też:

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolorclosestalpha
imagecolordeallocate
GD and Image Funkcje


De-allocate a color for an image

imagecolorclosesthwb
imagecolorexact
GD and Image Funkcje
PHP Manual

imagecolordeallocate

(PHP 4, PHP 5)

imagecolordeallocate — De-allocate a color for an image

Opis

bool imagecolordeallocate ( resource $image , int $color )

De-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

color

The color identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using imagecolordeallocate()

<?php
$white = imagecolorallocate($im, 255, 255, 255);
imagecolordeallocate($im, $white);
?>

Zobacz też:

  • imagecolorallocate() - Allocate a color for an image
  • imagecolorallocatealpha() - Allocate a color for an image

imagecolorclosesthwb
imagecolorexact
GD and Image Funkcje


Get the index of the specified color

imagecolordeallocate
imagecolorexactalpha
GD and Image Funkcje
PHP Manual

imagecolorexact

(PHP 4, PHP 5)

imagecolorexact — Get the index of the specified color

Opis

int imagecolorexact ( resource $image , int $red , int $green , int $blue )

Returns the index of the specified color in the palette of the image.

Jeśli tworzony jest obraz z pliku, zwracane są indeksy kolorów użyte tylko w obrazie. Kolory będące tylko w palecie nie są zwracane.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

Zwracane wartości

Returns the index of the specified color in the palette, or -1 if the color does not exist.

Przykłady

Przykład #1 Get colors from the GD logo

<?php
// Setup an image
$im = imagecreatefrompng('./gdlogo.png');

$colors   = Array();
$colors[] = imagecolorexact($im, 255, 0, 0);
$colors[] = imagecolorexact($im, 0, 0, 0);
$colors[] = imagecolorexact($im, 255, 255, 255);
$colors[] = imagecolorexact($im, 100, 255, 52);

print_r($colors);

// Free from memory
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => 16711680
    [1] => 0
    [2] => 16777215
    [3] => 6618932
)

Zobacz też:

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolordeallocate
imagecolorexactalpha
GD and Image Funkcje


Get the index of the specified color + alpha

imagecolorexact
imagecolormatch
GD and Image Funkcje
PHP Manual

imagecolorexactalpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorexactalpha — Get the index of the specified color + alpha

Opis

int imagecolorexactalpha ( resource $image , int $red , int $green , int $blue , int $alpha )

Returns the index of the specified color+alpha in the palette of the image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Zwracane wartości

Returns the index of the specified color+alpha in the palette of the image, or -1 if the color does not exist in the image's palette.

Przykłady

Przykład #1 Get colors from the GD logo

<?php

// Setup an image
$im = imagecreatefrompng('./gdlogo.png');

$colors   = Array();
$colors[] = imagecolorexactalpha($im, 255, 0, 0, 0);
$colors[] = imagecolorexactalpha($im, 0, 0, 0, 127);
$colors[] = imagecolorexactalpha($im, 255, 255, 255, 55);
$colors[] = imagecolorexactalpha($im, 100, 255, 52, 20);

print_r($colors);

// Free from memory
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => 16711680
    [1] => 2130706432
    [2] => 939524095
    [3] => 342163252
)

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

imagecolorexact
imagecolormatch
GD and Image Funkcje


Makes the colors of the palette version of an image more closely match the true color version

imagecolorexactalpha
imagecolorresolve
GD and Image Funkcje
PHP Manual

imagecolormatch

(PHP 4 >= 4.3.0, PHP 5)

imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version

Opis

bool imagecolormatch ( resource $image1 , resource $image2 )

Makes the colors of the palette version of an image more closely match the true color version.

Parametry

image1

A truecolor image link resource.

image2

A palette image link resource pointing to an image that has the same size as image1.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagecolormatch() example

<?php
// Setup the true color and palette images
$im1 = imagecreatefrompng('./gdlogo.png');
$im2 = imagecreate(imagesx($im1), imagesy($im1));

// Add some colors to $im2
$colors   = Array();
$colors[] = imagecolorallocate($im2, 255, 36, 74);
$colors[] = imagecolorallocate($im2, 40, 0, 240);
$colors[] = imagecolorallocate($im2, 82, 100, 255);
$colors[] = imagecolorallocate($im2, 84, 63, 44);

// Match these colors with the true color image
imagecolormatch($im1, $im2);

// Free from memory
imagedestroy($im1);
imagedestroy($im2);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dołączoną wersją biblioteki GD.

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imagecreatetruecolor() - Create a new true color image

imagecolorexactalpha
imagecolorresolve
GD and Image Funkcje


Get the index of the specified color or its closest possible alternative

imagecolormatch
imagecolorresolvealpha
GD and Image Funkcje
PHP Manual

imagecolorresolve

(PHP 4, PHP 5)

imagecolorresolve — Get the index of the specified color or its closest possible alternative

Opis

int imagecolorresolve ( resource $image , int $red , int $green , int $blue )

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

Jeśli tworzony jest obraz z pliku, zwracane są indeksy kolorów użyte tylko w obrazie. Kolory będące tylko w palecie nie są zwracane.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

Zwracane wartości

Returns a color index.

Przykłady

Przykład #1 Using imagecoloresolve() to get colors from an image

<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');

// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolve($im, 255, 255, 255);
$colors[] = imagecolorresolve($im, 0, 0, 200);

// Output
print_r($colors);

imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => 89
    [1] => 85
)

Zobacz też:

  • imagecolorclosest() - Get the index of the closest color to the specified color

imagecolormatch
imagecolorresolvealpha
GD and Image Funkcje


Get the index of the specified color + alpha or its closest possible alternative

imagecolorresolve
imagecolorset
GD and Image Funkcje
PHP Manual

imagecolorresolvealpha

(PHP 4 >= 4.0.6, PHP 5)

imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative

Opis

int imagecolorresolvealpha ( resource $image , int $red , int $green , int $blue , int $alpha )

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

alpha

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

The colors parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF.

Zwracane wartości

Returns a color index.

Przykłady

Przykład #1 Using imagecoloresolvealpha() to get colors from an image

<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');

// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolvealpha($im, 255, 255, 255, 0);
$colors[] = imagecolorresolvealpha($im, 0, 0, 200, 127);

// Output
print_r($colors);

imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => 89
    [1] => 85
)

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imagecolorclosestalpha() - Get the index of the closest color to the specified color + alpha

imagecolorresolve
imagecolorset
GD and Image Funkcje


Set the color for the specified palette index

imagecolorresolvealpha
imagecolorsforindex
GD and Image Funkcje
PHP Manual

imagecolorset

(PHP 4, PHP 5)

imagecolorset — Set the color for the specified palette index

Opis

void imagecolorset ( resource $image , int $index , int $red , int $green , int $blue [, int $alpha = 0 ] )

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

index

An index in the palette.

red

Wartość składowa czerwonego.

green

Wartość składowa zielonego.

blue

Wartość składowa niebieskiego.

alpha

Value of alpha component.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
5.4.0 | The alpha parameter was added.

Przykłady

Przykład #1 imagecolorset() example

<?php
// Create a 300x100 image
$im = imagecreate(300, 100);

// Set the background to be red
imagecolorallocate($im, 255, 0, 0);

// Get the color index for the background
$bg = imagecolorat($im, 0, 0);

// Set the backgrund to be blue
imagecolorset($im, $bg, 0, 0, 255);

// Output the image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

Zobacz też:

  • imagecolorat() - Get the index of the color of a pixel

imagecolorresolvealpha
imagecolorsforindex
GD and Image Funkcje


Get the colors for an index

imagecolorset
imagecolorstotal
GD and Image Funkcje
PHP Manual

imagecolorsforindex

(PHP 4, PHP 5)

imagecolorsforindex — Get the colors for an index

Opis

array imagecolorsforindex ( resource $image , int $index )

Gets the color for a specified index.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

index

The color index.

Zwracane wartości

Returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.

Przykłady

Przykład #1 imagecolorsforindex() example

<?php

// open an image
$im = imagecreatefrompng('nexen.png');

// get a color
$start_x = 40;
$start_y = 50;
$color_index = imagecolorat($im, $start_x, $start_y);

// make it human readable
$color_tran = imagecolorsforindex($im, $color_index);

// what is it ?
print_r($color_tran);

?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
   [red] => 226
   [green] => 222
   [blue] => 252
   [alpha] => 0
)

Zobacz też:

  • imagecolorat() - Get the index of the color of a pixel
  • imagecolorexact() - Get the index of the specified color

imagecolorset
imagecolorstotal
GD and Image Funkcje


Find out the number of colors in an image's palette

imagecolorsforindex
imagecolortransparent
GD and Image Funkcje
PHP Manual

imagecolorstotal

(PHP 4, PHP 5)

imagecolorstotal — Find out the number of colors in an image's palette

Opis

int imagecolorstotal ( resource $image )

Returns the number of colors in an image palette.

Parametry

image

An image resource, returned by one of the image creation functions, such as imagecreatefromgif().

Zwracane wartości

Returns the number of colors in the specified image's palette or 0 for truecolor images.

Przykłady

Przykład #1 Getting total number of colors in an image using imagecolorstotal()

<?php
// Create image instance
$im = imagecreatefromgif('php.gif');

echo 'Total colors in image: ' . imagecolorstotal($im);

// Free image
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Total colors in image: 128

Zobacz też:

  • imagecolorat() - Get the index of the color of a pixel
  • imagecolorsforindex() - Get the colors for an index
  • imageistruecolor() - Finds whether an image is a truecolor image

imagecolorsforindex
imagecolortransparent
GD and Image Funkcje


Define a color as transparent

imagecolorstotal
imageconvolution
GD and Image Funkcje
PHP Manual

imagecolortransparent

(PHP 4, PHP 5)

imagecolortransparent — Define a color as transparent

Opis

int imagecolortransparent ( resource $image [, int $color ] )

Sets the transparent color in the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

color

A color identifier created with imagecolorallocate().

Zwracane wartości

The identifier of the new (or current, if none is specified) transparent color is returned.

Przykłady

Przykład #1 imagecolortransparent() example

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);

// Make the background transparent
imagecolortransparent($im, $black);

// Draw a red rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $red);

// Save the image
imagepng($im, './imagecolortransparent.png');
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagecolortransparent()

Notatki

Informacja:

Transparency is copied only with imagecopymerge() and true color images, not with imagecopy() or pallete images.

Informacja:

The transparent color is a property of the image, transparency is not a property of the color. Once you have set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.

imagecolorstotal
imageconvolution
GD and Image Funkcje


Apply a 3x3 convolution matrix, using coefficient and offset

imagecolortransparent
imagecopy
GD and Image Funkcje
PHP Manual

imageconvolution

(PHP 5 >= 5.1.0)

imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset

Opis

bool imageconvolution ( resource $image , array $matrix , float $div , float $offset )

Applies a convolution matrix on the image, using the given coefficient and offset.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

matrix

A 3x3 matrix: an array of three arrays of three floats.

div

The divisor of the result of the convolution, used for normalization.

offset

Color offset.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Embossing the PHP.net logo

<?php
$image = imagecreatefromgif('http://www.php.net/images/php.gif');

$emboss = array(array(2, 0, 0), array(0, -1, 0), array(0, 0, -1));
imageconvolution($image, $emboss, 1, 127);

header('Content-Type: image/png');
imagepng($image, null, 9);
?>

Powyższy przykład wyświetli:

Output of example : Embossing the PHP.net logo

Przykład #2 Gaussian blur

<?php
$image = imagecreatetruecolor(180,40);

// Writes the text and apply a gaussian blur on the image
imagestring($image, 5, 10, 8, 'Gaussian Blur Text', 0x00ff00);
$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 4.0, 2.0), array(1.0, 2.0, 1.0));
imageconvolution($image, $gaussian, 16, 0);

// Rewrites the text for comparison
imagestring($image, 5, 10, 18, 'Gaussian Blur Text', 0x00ff00);

header('Content-Type: image/png');
imagepng($image, null, 9);
?>

Powyższy przykład wyświetli:

Output of example : Gaussian blur

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dołączoną wersją biblioteki GD.

Zobacz też:

  • imagefilter() - Applies a filter to an image

imagecolortransparent
imagecopy
GD and Image Funkcje


Copy part of an image

imageconvolution
imagecopymerge
GD and Image Funkcje
PHP Manual

imagecopy

(PHP 4, PHP 5)

imagecopy — Copy part of an image

Opis

bool imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

Parametry

dst_im

Zasób obrazu wynikowego.

src_im

Zasób obrazu źródłowego.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

src_w

Szerokość źródła.

src_h

Wysokość źródła.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Cropping the PHP.net logo

<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);

// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Cropping the PHP.net logo

imageconvolution
imagecopymerge
GD and Image Funkcje


Copy and merge part of an image

imagecopy
imagecopymergegray
GD and Image Funkcje
PHP Manual

imagecopymerge

(PHP 4 >= 4.0.1, PHP 5)

imagecopymerge — Copy and merge part of an image

Opis

bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

Parametry

dst_im

Zasób obrazu wynikowego.

src_im

Zasób obrazu źródłowego.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

src_w

Szerokość źródła.

src_h

Wysokość źródła.

pct

The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Merging two copies of the PHP.net logo with 75% transparency

<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');

// Copy and merge
imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

imagecopy
imagecopymergegray
GD and Image Funkcje


Copy and merge part of an image with gray scale

imagecopymerge
imagecopyresampled
GD and Image Funkcje
PHP Manual

imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5)

imagecopymergegray — Copy and merge part of an image with gray scale

Opis

bool imagecopymergegray ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )

imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

This function is identical to imagecopymerge() except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation.

Parametry

dst_im

Zasób obrazu wynikowego.

src_im

Zasób obrazu źródłowego.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

src_w

Szerokość źródła.

src_h

Wysokość źródła.

pct

The src_im will be changed to grayscale according to pct where 0 is fully grayscale and 100 is unchanged. When pct = 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagecopymergegray() usage

<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');

// Copy and merge - Gray = 20%
imagecopymergegray($dest, $src, 10, 10, 0, 0, 100, 47, 20);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

imagecopymerge
imagecopyresampled
GD and Image Funkcje


Copy and resize part of an image with resampling

imagecopymergegray
imagecopyresized
GD and Image Funkcje
PHP Manual

imagecopyresampled

(PHP 4 >= 4.0.6, PHP 5)

imagecopyresampled — Copy and resize part of an image with resampling

Opis

bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

In other words, imagecopyresampled() will take an rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be unpredictable.

Parametry

dst_image

Zasób obrazu wynikowego.

src_image

Zasób obrazu źródłowego.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

dst_w

Destination width.

dst_h

Destination height.

src_w

Szerokość źródła.

src_h

Wysokość źródła.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Simple example

This example will resample an image to half its original size.

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Simple example

Przykład #2 Resampling an image proportionally

This example will display an image with the maximum width, or height, of 200 pixels.

<?php
// The file
$filename = 'test.jpg';

// Set a maximum height and width
$width = 200;
$height = 200;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Resampling an image proportionally

Notatki

Informacja:

There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

Zobacz też:

imagecopyresized() - Copy and resize part of an image

imagecopymergegray
imagecopyresized
GD and Image Funkcje


Copy and resize part of an image

imagecopyresampled
imagecreate
GD and Image Funkcje
PHP Manual

imagecopyresized

(PHP 4, PHP 5)

imagecopyresized — Copy and resize part of an image

Opis

bool imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )

imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the destination image, src_image is the source image identifier.

In other words, imagecopyresized() will take an rectangular area from src_image of width src_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be unpredictable.

Parametry

dst_image

Zasób obrazu wynikowego.

src_image

Zasób obrazu źródłowego.

dst_x

x-coordinate of destination point.

dst_y

y-coordinate of destination point.

src_x

x-coordinate of source point.

src_y

y-coordinate of source point.

dst_w

Destination width.

dst_h

Destination height.

src_w

Szerokość źródła.

src_h

Wysokość źródła.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Resizing an image

This example will display the image at half size.

<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Resizing an image

The image will be output at half size, though better quality could be obtained using imagecopyresampled().

Notatki

Informacja:

There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

Zobacz też:

imagecopyresampled() - Copy and resize part of an image with resampling

imagecopyresampled
imagecreate
GD and Image Funkcje


Create a new palette based image

imagecopyresized
imagecreatefromgd2
GD and Image Funkcje
PHP Manual

imagecreate

(PHP 4, PHP 5)

imagecreate — Create a new palette based image

Opis

resource imagecreate ( int $width , int $height )

imagecreate() returns an image identifier representing a blank image of specified size.

We recommend the use of imagecreatetruecolor().

Parametry

width

The image width.

height

The image height.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Creating a new GD image stream and outputting an image.

<?php
header("Content-Type: image/png");
$im = @imagecreate(110, 20)
    or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Creating a new GD image stream and outputting an image.

Zobacz też:

  • imagedestroy() - Destroy an image
  • imagecreatetruecolor() - Create a new true color image

imagecopyresized
imagecreatefromgd2
GD and Image Funkcje


Create a new image from GD2 file or URL

imagecreate
imagecreatefromgd2part
GD and Image Funkcje
PHP Manual

imagecreatefromgd2

(PHP 4 >= 4.0.7, PHP 5)

imagecreatefromgd2 — Create a new image from GD2 file or URL

Opis

resource imagecreatefromgd2 ( string $filename )

Create a new image from GD2 file or URL.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the GD2 image.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 imagecreatefromgd2() example

<?php
// Load the gd2 image
$im = imagecreatefromgd2('./test.gd2');

// Apply an effect on the image, in this
// case negate the image if PHP 5+
if(function_exists('imagefilter'))
{
    imagefilter($im, IMG_FILTER_NEGATE);
}

// Save the image
imagegd2($im, './test_updated.gd2');
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

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.

imagecreate
imagecreatefromgd2part
GD and Image Funkcje


Create a new image from a given part of GD2 file or URL

imagecreatefromgd2
imagecreatefromgd
GD and Image Funkcje
PHP Manual

imagecreatefromgd2part

(PHP 4 >= 4.0.7, PHP 5)

imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL

Opis

resource imagecreatefromgd2part ( string $filename , int $srcX , int $srcY , int $width , int $height )

Create a new image from a given part of GD2 file or URL.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the GD2 image.

srcX

x-coordinate of source point.

srcY

y-coordinate of source point.

width

Szerokość źródła.

height

Wysokość źródła.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 imagecreatefromgd2part() example

<?php
// For this example we need the image size before
$image = getimagesize('./test.gd2');

// Create the image instance now we got the image
// sizes
$im = imagecreatefromgd2part('./test.gd2', 4, 4, ($image[0] / 2) - 6, ($image[1] / 2) - 6);

// Do an image operation, in this case we emboss the
// image if PHP 5+
if(function_exists('imagefilter'))
{
    imagefilter($im, IMG_FILTER_EMBOSS);
}

// Save optimized image
imagegd2($im, './test_emboss.gd2');
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

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.

imagecreatefromgd2
imagecreatefromgd
GD and Image Funkcje


Create a new image from GD file or URL

imagecreatefromgd2part
imagecreatefromgif
GD and Image Funkcje
PHP Manual

imagecreatefromgd

(PHP 4 >= 4.0.7, PHP 5)

imagecreatefromgd — Create a new image from GD file or URL

Opis

resource imagecreatefromgd ( string $filename )

Create a new image from GD file or URL.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the GD file.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 imagecreatefromgd() example

<?php
// Load the gd image
$im = @imagecreatefromgd('./test.gd');

// Test if the image was loaded
if(!is_resource($im))
{
     die('Unable to load gd image!');
}

// Do image operations here

// Save the image
imagegd($im, './test_updated.gd');
imagedestroy($im);
?>

Notatki

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.

imagecreatefromgd2part
imagecreatefromgif
GD and Image Funkcje


Tworzy nowy obraz z pliku lub URL

imagecreatefromgd
imagecreatefromjpeg
GD and Image Funkcje
PHP Manual

imagecreatefromgif

(PHP 4, PHP 5)

imagecreatefromgif — Tworzy nowy obraz z pliku lub URL

Opis

resource imagecreatefromgif ( string $filename )

imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the GIF image.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Example to handle an error during loading of a GIF

<?php
function LoadGif($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromgif($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im = imagecreatetruecolor (150, 30);
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc = imagecolorallocate ($im, 0, 0, 0);

        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring ($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/gif');

$img = LoadGif('bogus.image');

imagegif($img);
imagedestroy($img);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Example to handle an error during loading of a GIF

Notatki

Informacja:

GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions.

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.

imagecreatefromgd
imagecreatefromjpeg
GD and Image Funkcje


Tworzy nowy obraz z pliku lub URL

imagecreatefromgif
imagecreatefrompng
GD and Image Funkcje
PHP Manual

imagecreatefromjpeg

(PHP 4, PHP 5)

imagecreatefromjpeg — Tworzy nowy obraz z pliku lub URL

Opis

resource imagecreatefromjpeg ( string $filename )

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the JPEG image.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Example to handle an error during loading of a JPEG

<?php
function LoadJpeg($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromjpeg($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a black image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/jpeg');

$img = LoadJpeg('bogus.image');

imagejpeg($img);
imagedestroy($img);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Example to handle an error during loading of a JPEG

Notatki

Informacja: Obsługa JPEG jest dostępna tylko jeśli PHP zostało skompilowane z GD-1.8 lub nowszym.

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.

imagecreatefromgif
imagecreatefrompng
GD and Image Funkcje


Tworzy nowy obraz z pliku lub URL

imagecreatefromjpeg
imagecreatefromstring
GD and Image Funkcje
PHP Manual

imagecreatefrompng

(PHP 4, PHP 5)

imagecreatefrompng — Tworzy nowy obraz z pliku lub URL

Opis

resource imagecreatefrompng ( string $filename )

imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the PNG image.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Example to handle an error during loading of a PNG

<?php
function LoadPNG($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefrompng($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/png');

$img = LoadPNG('bogus.image');

imagepng($img);
imagedestroy($img);
?>

Powyższy przykład wyświetli coś podobnego do:

Notatki

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.

imagecreatefromjpeg
imagecreatefromstring
GD and Image Funkcje


Create a new image from the image stream in the string

imagecreatefrompng
imagecreatefromwbmp
GD and Image Funkcje
PHP Manual

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5)

imagecreatefromstring — Create a new image from the image stream in the string

Opis

resource imagecreatefromstring ( string $data )

imagecreatefromstring() returns an image identifier representing the image obtained from the given data. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

Parametry

image

A string containing the image data.

Zwracane wartości

An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.

Przykłady

Przykład #1 imagecreatefromstring() example

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
       . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
       . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
       . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
}
else {
    echo 'An error occurred.';
}
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagecreatefromstring()

Zobacz też:

  • imagecreatefromjpeg() - Tworzy nowy obraz z pliku lub URL
  • imagecreatefrompng() - Tworzy nowy obraz z pliku lub URL
  • imagecreatefromgif() - Tworzy nowy obraz z pliku lub URL
  • imagecreatetruecolor() - Create a new true color image

imagecreatefrompng
imagecreatefromwbmp
GD and Image Funkcje


Tworzy nowy obraz z pliku lub URL

imagecreatefromstring
imagecreatefromxbm
GD and Image Funkcje
PHP Manual

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromwbmp — Tworzy nowy obraz z pliku lub URL

Opis

resource imagecreatefromwbmp ( string $filename )

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the WBMP image.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Example to handle an error during loading of a WBMP

<?php
function LoadWBMP($imgname)
{
    /* Attempt to open */
    $im = @imagecreatefromwbmp($imgname);

    /* See if it failed */
    if(!$im)
    {
        /* Create a blank image */
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);

        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

        /* Output an error message */
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    return $im;
}

header('Content-Type: image/vnd.wap.wbmp');

$img = LoadWBMP('bogus.image');

imagewbmp($img);
imagedestroy($img);
?>

Notatki

Informacja: Obsługa WBMP jest dostępna tylko jeśli PHP zostało skompilowane z GD-1.8 lub nowszym.

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.

imagecreatefromstring
imagecreatefromxbm
GD and Image Funkcje


Tworzy nowy obraz z pliku lub URL

imagecreatefromwbmp
imagecreatefromxpm
GD and Image Funkcje
PHP Manual

imagecreatefromxbm

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromxbm — Tworzy nowy obraz z pliku lub URL

Opis

resource imagecreatefromxbm ( string $filename )

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the XBM image.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Convert an XBM image to a png image using imagecreatefromxbm()

<?php
// Load the xbm file
$xbm = imagecreatefromxbm('./example.xbm');

// Convert it to a png file
imagepng($xbm, './example.png');
imagedestroy($xbm);
?>

Notatki

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.

imagecreatefromwbmp
imagecreatefromxpm
GD and Image Funkcje


Tworzy nowy obraz z pliku lub URL

imagecreatefromxbm
imagecreatetruecolor
GD and Image Funkcje
PHP Manual

imagecreatefromxpm

(PHP 4 >= 4.0.1, PHP 5)

imagecreatefromxpm — Tworzy nowy obraz z pliku lub URL

Opis

resource imagecreatefromxpm ( string $filename )

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

Parametry

filename

Path to the XPM image.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Creating an image instance using imagecreatefromxpm()

<?php
// Check for XPM support
if(!(imagetypes() & IMG_XPM))
{
    die('Support for xpm was not found!');
}

// Create the image instance
$xpm = imagecreatefromxpm('./example.xpm');

// Do image operations here

// PHP has no support for writing xpm images
// so in this case we save the image as a
// jpeg file with 100% quality
imagejpeg($xpm, './example.jpg', 100);
imagedestroy($xpm);
?>

Zwracane wartości

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dołączoną wersją biblioteki GD.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

imagecreatefromxbm
imagecreatetruecolor
GD and Image Funkcje


Create a new true color image

imagecreatefromxpm
imagedashedline
GD and Image Funkcje
PHP Manual

imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5)

imagecreatetruecolor — Create a new true color image

Opis

resource imagecreatetruecolor ( int $width , int $height )

imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

Depending on your PHP and GD versions this function is defined or not. With PHP 4.0.6 through 4.1.x this function always exists if the GD module is loaded, but calling it without GD2 being installed PHP will issue a fatal error and exit. With PHP 4.2.x this behaviour is different in issuing a warning instead of an error. Other versions only define this function, if the correct GD version is installed.

Parametry

width

Image width.

height

Image height.

Zwracane wartości

Zwraca identyfikator zasobu obrazu w przypadku powodzenia lub FALSE w przypadku błędów.

Przykłady

Przykład #1 Creating a new GD image stream and outputting an image.

<?php
header ('Content-Type: image/png');
$im = @imagecreatetruecolor(120, 20)
      or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);
imagepng($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Creating a new GD image stream and outputting an image.

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imagedestroy() - Destroy an image
  • imagecreate() - Create a new palette based image

imagecreatefromxpm
imagedashedline
GD and Image Funkcje


Draw a dashed line

imagecreatetruecolor
imagedestroy
GD and Image Funkcje
PHP Manual

imagedashedline

(PHP 4, PHP 5)

imagedashedline — Draw a dashed line

Opis

bool imagedashedline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

This function is deprecated. Use combination of imagesetstyle() and imageline() instead.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

x1

Upper left x coordinate.

y1

Upper left y coordinate 0, 0 is the top left corner of the image.

x2

Bottom right x coordinate.

y2

Bottom right y coordinate.

color

The fill color. A color identifier created with imagecolorallocate().

Zwracane wartości

Always returns true

Przykłady

Przykład #1 imagedashedline() example

<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

// Draw a vertical dashed line
imagedashedline($im, 50, 25, 50, 75, $white);

// Save the image
imagepng($im, './dashedline.png');
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagedashedline()

Przykład #2 Alternative to imagedashedline()

<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

// Define our style: First 4 pixels is white and the
// next 4 is transparent. This creates the dashed line effect
$style = Array(
                $white,
                $white,
                $white,
                $white,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT,
                IMG_COLOR_TRANSPARENT
                );

imagesetstyle($im, $style);

// Draw the dashed line
imageline($im, 50, 25, 50, 75, IMG_COLOR_STYLED);

// Save the image
imagepng($im, './imageline.png');
imagedestroy($im);
?>

Zobacz też:

  • imagesetstyle() - Set the style for line drawing
  • imageline() - Draw a line

imagecreatetruecolor
imagedestroy
GD and Image Funkcje


Destroy an image

imagedashedline
imageellipse
GD and Image Funkcje
PHP Manual

imagedestroy

(PHP 4, PHP 5)

imagedestroy — Destroy an image

Opis

bool imagedestroy ( resource $image )

imagedestroy() frees any memory associated with image image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using imagedestroy() example

<?php
// create a 100 x 100 image
$im = imagecreatetruecolor(100, 100);

// alter or save the image

// frees image from memory
imagedestroy($im);
?>

imagedashedline
imageellipse
GD and Image Funkcje


Draw an ellipse

imagedestroy
imagefill
GD and Image Funkcje
PHP Manual

imageellipse

(PHP 4 >= 4.0.6, PHP 5)

imageellipse — Draw an ellipse

Opis

bool imageellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color )

Draws an ellipse centered at the specified coordinates.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The ellipse width.

height

The ellipse height.

color

The color of the ellipse. A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imageellipse() example

<?php

// Create a blank image.
$image = imagecreatetruecolor(400, 300);

// Select the background color.
$bg = imagecolorallocate($image, 0, 0, 0);

// Fill the background with the color selected above.
imagefill($image, 0, 0, $bg);

// Choose a color for the ellipse.
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// Draw the ellipse.
imageellipse($image, 200, 150, 300, 200, $col_ellipse);

// Output the image.
header("Content-type: image/png");
imagepng($image);

?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imageellipse()

Notatki

Informacja:

This function requires GD 2.0.2 or later.

Zobacz też:

  • imagefilledellipse() - Draw a filled ellipse
  • imagearc() - Draws an arc

imagedestroy
imagefill
GD and Image Funkcje


Flood fill

imageellipse
imagefilledarc
GD and Image Funkcje
PHP Manual

imagefill

(PHP 4, PHP 5)

imagefill — Flood fill

Opis

bool imagefill ( resource $image , int $x , int $y , int $color )

Performs a flood fill starting at the given coordinate (top left is 0, 0) with the given color in the image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

x

x-coordinate of start point.

y

y-coordinate of start point.

color

The fill color. A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagefill() example

<?php

$im = imagecreatetruecolor(100, 100);

// sets background to red
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagefill()

Zobacz też:

  • imagecolorallocate() - Allocate a color for an image

imageellipse
imagefilledarc
GD and Image Funkcje


Draw a partial arc and fill it

imagefill
imagefilledellipse
GD and Image Funkcje
PHP Manual

imagefilledarc

(PHP 4 >= 4.0.6, PHP 5)

imagefilledarc — Draw a partial arc and fill it

Opis

bool imagefilledarc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , int $end , int $color , int $style )

Draws a partial arc centered at the specified coordinate in the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The arc width.

height

The arc height.

start

The arc start angle, in degrees.

end

The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise.

color

A color identifier created with imagecolorallocate().

style

A bitwise OR of the following possibilities:

  1. IMG_ARC_PIE
  2. IMG_ARC_CHORD
  3. IMG_ARC_NOFILL
  4. IMG_ARC_EDGED
IMG_ARC_PIE and IMG_ARC_CHORD are mutually exclusive; IMG_ARC_CHORD just connects the starting and ending angles with a straight line, while IMG_ARC_PIE produces a rounded edge. IMG_ARC_NOFILL indicates that the arc or chord should be outlined, not filled. IMG_ARC_EDGED, used together with IMG_ARC_NOFILL, indicates that the beginning and ending angles should be connected to the center - this is a good way to outline (rather than fill) a 'pie slice'.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Creating a 3D looking pie

<?php

// create image
$image = imagecreatetruecolor(100, 100);

// allocate some colors
$white    = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy     = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red      = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred  = imagecolorallocate($image, 0x90, 0x00, 0x00);

// make the 3D effect
for ($i = 60; $i > 50; $i--) {
   imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
   imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
   imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);
}

imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Creating a 3D looking pie

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

imagefill
imagefilledellipse
GD and Image Funkcje


Draw a filled ellipse

imagefilledarc
imagefilledpolygon
GD and Image Funkcje
PHP Manual

imagefilledellipse

(PHP 4 >= 4.0.6, PHP 5)

imagefilledellipse — Draw a filled ellipse

Opis

bool imagefilledellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color )

Draws an ellipse centered at the specified coordinate on the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The ellipse width.

height

The ellipse height.

color

The fill color. A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagefilledellipse() example

<?php

// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// draw the white ellipse
imagefilledellipse($image, 200, 150, 300, 200, $col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image);

?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagefilledellipse()

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imageellipse() - Draw an ellipse
  • imagefilledarc() - Draw a partial arc and fill it

imagefilledarc
imagefilledpolygon
GD and Image Funkcje


Draw a filled polygon

imagefilledellipse
imagefilledrectangle
GD and Image Funkcje
PHP Manual

imagefilledpolygon

(PHP 4, PHP 5)

imagefilledpolygon — Draw a filled polygon

Opis

bool imagefilledpolygon ( resource $image , array $points , int $num_points , int $color )

imagefilledpolygon() creates a filled polygon in the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

points

An array containing the x and y coordinates of the polygons vertices consecutively.

num_points

Total number of vertices, which must be at least 3.

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagefilledpolygon() example

<?php
// set up array of points for polygon
$values = array(
            40,  50,  // Point 1 (x, y)
            20,  240, // Point 2 (x, y)
            60,  60,  // Point 3 (x, y)
            240, 20,  // Point 4 (x, y)
            50,  40,  // Point 5 (x, y)
            10,  10   // Point 6 (x, y)
            );

// create image
$image = imagecreatetruecolor(250, 250);

// allocate colors
$bg   = imagecolorallocate($image, 0, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);

// fill the background
imagefilledrectangle($image, 0, 0, 249, 249, $bg);

// draw a polygon
imagefilledpolygon($image, $values, 6, $blue);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagefilledpolygon()

imagefilledellipse
imagefilledrectangle
GD and Image Funkcje


Draw a filled rectangle

imagefilledpolygon
imagefilltoborder
GD and Image Funkcje
PHP Manual

imagefilledrectangle

(PHP 4, PHP 5)

imagefilledrectangle — Draw a filled rectangle

Opis

bool imagefilledrectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

Creates a rectangle filled with color in the given image starting at point 1 and ending at point 2. 0, 0 is the top left corner of the image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

x1

x-coordinate for point 1.

y1

y-coordinate for point 1.

x2

x-coordinate for point 2.

y2

y-coordinate for point 2.

color

The fill color. A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagefilledrectangle() usage

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$white = imagecolorallocate($im, 255, 255, 255);

// Draw a white rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $white);

// Save the image
imagepng($im, './imagefilledrectangle.png');
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagefilledrectangle()

imagefilledpolygon
imagefilltoborder
GD and Image Funkcje


Flood fill to specific color

imagefilledrectangle
imagefilter
GD and Image Funkcje
PHP Manual

imagefilltoborder

(PHP 4, PHP 5)

imagefilltoborder — Flood fill to specific color

Opis

bool imagefilltoborder ( resource $image , int $x , int $y , int $border , int $color )

imagefilltoborder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color color.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

x

x-coordinate of start.

y

y-coordinate of start.

border

The border color. A color identifier created with imagecolorallocate().

color

The fill color. A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Filling an ellipse with a color

<?php
// Create the image handle, set the background to white
$im = imagecreatetruecolor(100, 100);
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 255, 255, 255));

// Draw an ellipse to fill with a black border
imageellipse($im, 50, 50, 50, 50, imagecolorallocate($im, 0, 0, 0));

// Set the border and fill colors
$border = imagecolorallocate($im, 0, 0, 0);
$fill = imagecolorallocate($im, 255, 0, 0);

// Fill the selection
imagefilltoborder($im, 50, 50, $border, $fill);

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Filling an ellipse with a color

imagefilledrectangle
imagefilter
GD and Image Funkcje


Applies a filter to an image

imagefilltoborder
imagefontheight
GD and Image Funkcje
PHP Manual

imagefilter

(PHP 5)

imagefilter — Applies a filter to an image

Opis

bool imagefilter ( resource $image , int $filtertype [, int $arg1 [, int $arg2 [, int $arg3 [, int $arg4 ]]]] )

imagefilter() applies the given filter filtertype on the image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filtertype

filtertype can be one of the following:

  • IMG_FILTER_NEGATE: Reverses all colors of the image.
  • IMG_FILTER_GRAYSCALE: Converts the image into grayscale.
  • IMG_FILTER_BRIGHTNESS: Changes the brightness of the image. Use arg1 to set the level of brightness.
  • IMG_FILTER_CONTRAST: Changes the contrast of the image. Use arg1 to set the level of contrast.
  • IMG_FILTER_COLORIZE: Like IMG_FILTER_GRAYSCALE, except you can specify the color. Use arg1, arg2 and arg3 in the form of red, blue, green and arg4 for the alpha channel. The range for each color is 0 to 255.
  • IMG_FILTER_EDGEDETECT: Uses edge detection to highlight the edges in the image.
  • IMG_FILTER_EMBOSS: Embosses the image.
  • IMG_FILTER_GAUSSIAN_BLUR: Blurs the image using the Gaussian method.
  • IMG_FILTER_SELECTIVE_BLUR: Blurs the image.
  • IMG_FILTER_MEAN_REMOVAL: Uses mean removal to achieve a "sketchy" effect.
  • IMG_FILTER_SMOOTH: Makes the image smoother. Use arg1 to set the level of smoothness.
  • IMG_FILTER_PIXELATE: Applies pixelation effect to the image, use arg1 to set the block size and arg2 to set the pixelation effect mode.

arg1

  • IMG_FILTER_BRIGHTNESS: Brightness level.
  • IMG_FILTER_CONTRAST: Contrast level.
  • IMG_FILTER_COLORIZE: Wartość składowa czerwonego.
  • IMG_FILTER_SMOOTH: Smoothness level.
  • IMG_FILTER_PIXELATE: Block size in pixels.

arg2

  • IMG_FILTER_COLORIZE: Wartość składowa zielonego.
  • IMG_FILTER_PIXELATE: Whether to use advanced pixelation effect or not (defaults to FALSE).

arg3

  • IMG_FILTER_COLORIZE: Wartość składowa niebieskiego.

arg4

  • IMG_FILTER_COLORIZE: Alpha channel, A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.0 | Pixelation support (IMG_FILTER_PIXELATE) was added.
5.2.5 | Alpha support for IMG_FILTER_COLORIZE was added.

Przykłady

Przykład #1 imagefilter() grayscale example

<?php
$im = imagecreatefrompng('dave.png');

if($im && imagefilter($im, IMG_FILTER_GRAYSCALE))
{
    echo 'Image converted to grayscale.';

    imagepng($im, 'dave.png');
}
else
{
    echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?>

Przykład #2 imagefilter() brightness example

<?php
$im = imagecreatefrompng('sean.png');

if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20))
{
    echo 'Image brightness changed.';

    imagepng($im, 'sean.png');
    imagedestroy($im);
}
else
{
    echo 'Image brightness change failed.';
}
?>

Przykład #3 imagefilter() colorize example

<?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0))
{
    echo 'Image successfully shaded green.';

    imagepng($im, 'philip.png');
    imagedestroy($im);
}
else
{
    echo 'Green shading failed.';
}
?>

Przykład #4 imagefilter() negate example

<?php
// Define our negate function so its portable for
// php versions without imagefilter()
function negate($im)
{
    if(function_exists('imagefilter'))
    {
        return imagefilter($im, IMG_FILTER_NEGATE);
    }

    for($x = 0; $x < imagesx($im); ++$x)
    {
        for($y = 0; $y < imagesy($im); ++$y)
        {
            $index = imagecolorat($im, $x, $y);
            $rgb = imagecolorsforindex($index);
            $color = imagecolorallocate($im, 255 - $rgb['red'], 255 - $rgb['green'], 255 - $rgb['blue']);

            imagesetpixel($im, $x, $y, $color);
        }
    }

    return(true);
}

$im = imagecreatefromjpeg('kalle.jpg');

if($im && negate($im))
{
    echo 'Image successfully converted to negative colors.';

    imagejpeg($im, 'kalle.jpg', 100);
    imagedestroy($im);
}
else
{
    echo 'Converting to negative colors failed.';
}
?>

Przykład #5 imagefilter() pixelate example

<?php
// Load the PHP logo, we need to create two instances
// to show the differences
$logo1 = imagecreatefrompng('./php.png');
$logo2 = imagecreatefrompng('./php.png');

// Create the image instance we want to show the
// differences on
$output = imagecreatetruecolor(imagesx($logo1) * 2, imagesy($logo1));

// Apply pixelation to each instance, with a block
// size of 3
imagefilter($logo1, IMG_FILTER_PIXELATE, 3);
imagefilter($logo2, IMG_FILTER_PIXELATE, 3, true);

// Merge the differences onto the output image
imagecopy($output, $logo1, 0, 0, 0, 0, imagesx($logo1) - 1, imagesy($logo1) - 1);
imagecopy($output, $logo2, imagesx($logo2), 0, 0, 0, imagesx($logo2) - 1, imagesy($logo2) - 1);
imagedestroy($logo1);
imagedestroy($logo2);

// Output the differences
header('Content-Type: image/png');
imagepng($output);
imagedestroy($output);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagefilter() pixelate

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dołączoną wersją biblioteki GD.

Zobacz też:

  • imageconvolution() - Apply a 3x3 convolution matrix, using coefficient and offset

imagefilltoborder
imagefontheight
GD and Image Funkcje


Get font height

imagefilter
imagefontwidth
GD and Image Funkcje
PHP Manual

imagefontheight

(PHP 4, PHP 5)

imagefontheight — Get font height

Opis

int imagefontheight ( int $font )

Returns the pixel height of a character in the specified font.

Parametry

czcionka

Może przyjąć 1, 2, 3, 4, 5 dla wbudowanych czcionek w kodowaniu latin2 (gdzie większy numer odpowiada większej czcionce) lub własny dowolny identyfikator czcionki zarejestrowany przez imageloadfont().

Zwracane wartości

Returns the height of the pixel.

Przykłady

Przykład #1 Using imagefontheight() on built-in fonts

<?php
echo 'Font height: ' . imagefontheight(4);
?>

Powyższy przykład wyświetli coś podobnego do:

Font height: 16

Przykład #2 Using imagefontheight() together with imageloadfont()

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font height: ' . imagefontheight($font);
?>

Powyższy przykład wyświetli coś podobnego do:

Font height: 43

Zobacz też:

  • imagefontwidth() - Get font width
  • imageloadfont() - Load a new font

imagefilter
imagefontwidth
GD and Image Funkcje


Get font width

imagefontheight
imageftbbox
GD and Image Funkcje
PHP Manual

imagefontwidth

(PHP 4, PHP 5)

imagefontwidth — Get font width

Opis

int imagefontwidth ( int $font )

Returns the pixel width of a character in font.

Parametry

czcionka

Może przyjąć 1, 2, 3, 4, 5 dla wbudowanych czcionek w kodowaniu latin2 (gdzie większy numer odpowiada większej czcionce) lub własny dowolny identyfikator czcionki zarejestrowany przez imageloadfont().

Zwracane wartości

Returns the width of the pixel

Przykłady

Przykład #1 Using imagefontwidth() on built-in fonts

<?php
echo 'Font width: ' . imagefontwidth(4);
?>

Powyższy przykład wyświetli coś podobnego do:

Font width: 8

Przykład #2 Using imagefontwidth() together with imageloadfont()

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font width: ' . imagefontwidth($font);
?>

Powyższy przykład wyświetli coś podobnego do:

Font width: 23

Zobacz też:

  • imagefontheight() - Get font height
  • imageloadfont() - Load a new font

imagefontheight
imageftbbox
GD and Image Funkcje


Give the bounding box of a text using fonts via freetype2

imagefontwidth
imagefttext
GD and Image Funkcje
PHP Manual

imageftbbox

(PHP 4 >= 4.0.7, PHP 5)

imageftbbox — Give the bounding box of a text using fonts via freetype2

Opis

array imageftbbox ( float $size , float $angle , string $fontfile , string $text [, array $extrainfo ] )

This function calculates and returns the bounding box in pixels for a FreeType text.

Parametry

size

Rozmiar czcionki. W zależności od wersji GD rozmiar jest określony albo w pikselach (GD1), albo w punktach (GD2).

angle

Angle in degrees in which text will be measured.

fontfile

The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.

text

The string to be measured.

extrainfo

Possible array indexes for extrainfo
Key | Type | Meaning
linespacing | float | Defines drawing linespacing

Zwracane wartości

imageftbbox() returns an array with 8 elements representing four points making the bounding box of the text:

0 | lower left corner, X position
1 | lower left corner, Y position
2 | lower right corner, X position
3 | lower right corner, Y position
4 | upper right corner, X position
5 | upper right corner, Y position
6 | upper left corner, X position
7 | upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontally.

Przykłady

Przykład #1 imageftbbox() example

<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// Path to our font file
$font = './arial.ttf';

// First we create our bounding box
$bbox = imageftbbox(10, 0, $font, 'The PHP Documentation Group');

// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 5;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

imagefttext($im, 10, 0, $x, $y, $black, $font, 'The PHP Documentation Group');

// Output to browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z obsługą FreeType (--with-freetype-dir=DIR )

Rejestr zmian

Wersja | Opis
4.3.5 | extrainfo was made optional.

imagefontwidth
imagefttext
GD and Image Funkcje


Write text to the image using fonts using FreeType 2

imageftbbox
imagegammacorrect
GD and Image Funkcje
PHP Manual

imagefttext

(PHP 4 >= 4.0.7, PHP 5)

imagefttext — Write text to the image using fonts using FreeType 2

Opis

array imagefttext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text [, array $extrainfo ] )

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

size

The font size to use in points.

angle

The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

x

The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.

y

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The index of the desired color for the text, see imagecolorexact().

fontfile

The path to the TrueType font you wish to use.

Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

text

Text to be inserted into image.

extrainfo

Possible array indexes for extrainfo
Key | Type | Meaning
linespacing | float | Defines drawing linespacing

Zwracane wartości

This function returns an array defining the four points of the box, starting in the lower left and moving counter-clockwise:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | lower right x-coordinate
3 | lower right y-coordinate
4 | upper right x-coordinate
5 | upper right y-coordinate
6 | upper left x-coordinate
7 | upper left y-coordinate

Przykłady

Przykład #1 imagefttext() example

<?php
// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);

// Path to our ttf font file
$font_file = './arial.ttf';

// Draw the text 'PHP Manual' using font size 13
imagefttext($im, 13, 0, 105, 55, $black, $font_file, 'PHP Manual');

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z obsługą FreeType (--with-freetype-dir=DIR )

Rejestr zmian

Wersja | Opis
4.3.5 | extrainfo was made optional.

imageftbbox
imagegammacorrect
GD and Image Funkcje


Apply a gamma correction to a GD image

imagefttext
imagegd2
GD and Image Funkcje
PHP Manual

imagegammacorrect

(PHP 4, PHP 5)

imagegammacorrect — Apply a gamma correction to a GD image

Opis

bool imagegammacorrect ( resource $image , float $inputgamma , float $outputgamma )

Applies gamma correction to the given gd image given an input and an output gamma.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

inputgamma

The input gamma.

outputgamma

The output gamma.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagegammacorrect() usage

<?php
// Create image instance
$im = imagecreatefromgif('php.gif');

// Correct gamma, out = 1.537
imagegammacorrect($im, 1.0, 1.537);

// Save and free image
imagegif($im, './php_gamma_corrected.gif');
imagedestroy($im);
?>

imagefttext
imagegd2
GD and Image Funkcje


Output GD2 image to browser or file

imagegammacorrect
imagegd
GD and Image Funkcje
PHP Manual

imagegd2

(PHP 4 >= 4.0.7, PHP 5)

imagegd2 — Output GD2 image to browser or file

Opis

bool imagegd2 ( resource $image [, string $filename [, int $chunk_size [, int $type = IMG_GD2_RAW ]]] )

Outputs a GD2 image to the given filename.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filename

Ścieżka do zapisu pliku. Jeśli nie jest ustawiona lub ma wartość NULL, obraz zostanie przesłany bezpośrednio na wyjście.

chunk_size

Chunk size.

type

Either IMG_GD2_RAW or IMG_GD2_COMPRESSED. Default is IMG_GD2_RAW.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Outputting a GD2 image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Output the image
imagegd2($im);

// Free up memory
imagedestroy($im);
?>

Przykład #2 Saving a GD2 image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Save the gd2 image
// The file format for GD2 images is .gd2, see http://www.libgd.org/GdFileFormats
imagegd2($im, 'simple.gd2');

// Free up memory
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Informacja:

The GD2 format is commonly used to allow fast loading of parts of images. Note that the GD2 format is only usable in GD2-compatible applications.

Rejestr zmian

Wersja | Opis
4.3.2 | chunk_size and type were added.

Zobacz też:

  • imagegd() - Output GD image to browser or file

imagegammacorrect
imagegd
GD and Image Funkcje


Output GD image to browser or file

imagegd2
imagegif
GD and Image Funkcje
PHP Manual

imagegd

(PHP 4 >= 4.0.7, PHP 5)

imagegd — Output GD image to browser or file

Opis

bool imagegd ( resource $image [, string $filename ] )

Outputs a GD image to the given filename.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filename

Ścieżka do zapisu pliku. Jeśli nie jest ustawiona lub ma wartość NULL, obraz zostanie przesłany bezpośrednio na wyjście.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Outputting a GD image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Output the image
imagegd($im);

// Free up memory
imagedestroy($im);
?>

Przykład #2 Saving a GD image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);

// Save the gd image
// The file format for GD images is .gd, see http://www.libgd.org/GdFileFormats
imagegd($im, 'simple.gd');

// Free up memory
imagedestroy($im);
?>

Notatki

Informacja:

The GD format is commonly used to allow fast loading of parts of images. Note that the GD format is only usable in GD-compatible applications.

Zobacz też:

  • imagegd2() - Output GD2 image to browser or file

imagegd2
imagegif
GD and Image Funkcje


Wysłanie obrazu do przeglądarki lub zapis do pliku

imagegd
imagegrabscreen
GD and Image Funkcje
PHP Manual

imagegif

(PHP 4, PHP 5)

imagegif — Wysłanie obrazu do przeglądarki lub zapis do pliku

Opis

bool imagegif ( resource $image [, string $filename ] )

imagegif() creates the GIF file in filename from the image image. The image argument is the return from the imagecreate() or imagecreatefrom* function.

The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filename

Ścieżka do zapisu pliku. Jeśli nie jest ustawiona lub ma wartość NULL, obraz zostanie przesłany bezpośrednio na wyjście.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Outputting an image using imagegif()

<?php
// Create a new image instance
$im = imagecreatetruecolor(100, 100);

// Make the background white
imagefilledrectangle($im, 0, 0, 99, 99, 0xFFFFFF);

// Draw a text string on the image
imagestring($im, 3, 40, 20, 'GD Library', 0xFFBA00);

// Output the image to browser
header('Content-Type: image/gif');

imagegif($im);
imagedestroy($im);
?>

Przykład #2 Converting a PNG image to GIF using imagegif()

<?php

// Load the PNG
$png = imagecreatefrompng('./php.png');

// Save the image as a GIF
imagegif($png, './php.gif');

// Free from memory
imagedestroy($png);

// We're done
echo 'Converted PNG image to GIF with success!';
?>

Notatki

Informacja:

GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions. For more information, see the » GD Project site.

The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence header ("Content-Type: image/gif"); imagegif ($im); by the more flexible sequence:

<?php
// Create a new image instance
$im = imagecreatetruecolor(100, 100);

// Do some image operations here

// Handle output
if(function_exists('imagegif'))
{
    // For GIF
    header('Content-Type: image/gif');

    imagegif($im);
}
elseif(function_exists('imagejpeg'))
{
    // For JPEG
    header('Content-Type: image/jpeg');

    imagejpeg($im, NULL, 100);
}
elseif(function_exists('imagepng'))
{
    // For PNG
    header('Content-Type: image/png');

    imagepng($im);
}
elseif(function_exists('imagewbmp'))
{
    // For WBMP
    header('Content-Type: image/vnd.wap.wbmp');

    imagewbmp($im);
}
else
{
    imagedestroy($im);

    die('No image support in this PHP server');
}

// If image support was found for one of these
// formats, then free it from memory
if($im)
{
    imagedestroy($im);
}
?>

Informacja:

As of PHP 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:

<?php
if(imagetypes() & IMG_GIF)
{
    header('Content-Type: image/gif');
    imagegif($im);
}
elseif(imagetypes() & IMG_JPG)
{
    /* ... etc. */
}
?>

Zobacz też:

  • imagepng() - Output a PNG image to either the browser or a file
  • imagewbmp() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagejpeg() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagetypes() - Return the image types supported by this PHP build

imagegd
imagegrabscreen
GD and Image Funkcje


Captures the whole screen

imagegif
imagegrabwindow
GD and Image Funkcje
PHP Manual

imagegrabscreen

(PHP 5 >= 5.2.2)

imagegrabscreen — Captures the whole screen

Opis

resource imagegrabscreen ( void )

Grabs a screenshot of the whole screen.

Zwracane wartości

Returns an image resource identifier on success, FALSE on failure.

Przykłady

Przykład #1 imagegrabscreen() example

This example demonstrates how to take a screenshot of the current screen and save it as a png image.

<?php
$im = imagegrabscreen();
imagepng($im, "myscreenshot.png");
imagedestroy($im);
?>

Notatki

Informacja:

This function is only available on Windows.

Zobacz też:

  • imagegrabwindow() - Captures a window

imagegif
imagegrabwindow
GD and Image Funkcje


Captures a window

imagegrabscreen
imageinterlace
GD and Image Funkcje
PHP Manual

imagegrabwindow

(PHP 5 >= 5.2.2)

imagegrabwindow — Captures a window

Opis

resource imagegrabwindow ( int $window_handle [, int $client_area = 0 ] )

Grabs a window or its client area using a windows handle (HWND property in COM instance)

Parametry

window_handle

The HWND window ID.

client_area

Include the client area of the application window.

Zwracane wartości

Returns an image resource identifier on success, FALSE on failure.

Błędy/Wyjątki

E_NOTICE is issued if window_handle is invalid window handle. E_WARNING is issued if the Windows API is too old.

Przykłady

Przykład #1 imagegrabwindow() example

Capture a window (IE for example)

<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$im = imagegrabwindow($handle);
$browser->Quit();
imagepng($im, "iesnap.png");
imagedestroy($im);
?>

Capture a window (IE for example) but with its content

<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$browser->Navigate("http://www.libgd.org");

/* Still working? */
while ($browser->Busy) {
    com_message_pump(4000);
}
$im = imagegrabwindow($handle, 0);
$browser->Quit();
imagepng($im, "iesnap.png");
imagedestroy($im);
?>

Notatki

Informacja:

This function is only available on Windows.

Zobacz też:

  • imagegrabscreen() - Captures the whole screen

imagegrabscreen
imageinterlace
GD and Image Funkcje


Enable or disable interlace

imagegrabwindow
imageistruecolor
GD and Image Funkcje
PHP Manual

imageinterlace

(PHP 4, PHP 5)

imageinterlace — Enable or disable interlace

Opis

int imageinterlace ( resource $image [, int $interlace = 0 ] )

imageinterlace() turns the interlace bit on or off.

If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

interlace

If non-zero, the image will be interlaced, else the interlace bit is turned off.

Zwracane wartości

Returns 1 if the interlace bit is set for the image, 0 otherwise.

Przykłady

Przykład #1 Turn on interlacing using imageinterlace()

<?php
// Create an image instance
$im = imagecreatefromgif('php.gif');

// Enable interlancing
imageinterlace($im, true);

// Save the interlaced image
imagegif($im, './php_interlaced.gif');
imagedestroy($im);
?>

imagegrabwindow
imageistruecolor
GD and Image Funkcje


Finds whether an image is a truecolor image

imageinterlace
imagejpeg
GD and Image Funkcje
PHP Manual

imageistruecolor

(PHP 4 >= 4.3.2, PHP 5)

imageistruecolor — Finds whether an image is a truecolor image

Opis

bool imageistruecolor ( resource $image )

imageistruecolor() finds whether the image image is a truecolor image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

Zwracane wartości

Returns TRUE if the image is truecolor, FALSE otherwise.

Przykłady

Przykład #1 Simple detection of true color image instances using imageistruecolor()

<?php
// $im is an image instance

// Check if image is a true color image or not
if(!imageistruecolor($im))
{
    // Create a new true color image instance
    $tc = imagecreatetruecolor(imagesx($im), imagesy($im));

    imagecopy($tc, $im, 0, 0, 0, 0, imagesx($im), imagesy($im));
    imagedestroy($im);

    $im = $tc;
    $tc = NULL;
}

// Continue working with image instance
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imagecreatetruecolor() - Create a new true color image

imageinterlace
imagejpeg
GD and Image Funkcje


Wysłanie obrazu do przeglądarki lub zapis do pliku

imageistruecolor
imagelayereffect
GD and Image Funkcje
PHP Manual

imagejpeg

(PHP 4, PHP 5)

imagejpeg — Wysłanie obrazu do przeglądarki lub zapis do pliku

Opis

bool imagejpeg ( resource $image [, string $filename [, int $quality ]] )

imagejpeg() creates a JPEG file from the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filename

Ścieżka do zapisu pliku. Jeśli nie jest ustawiona lub ma wartość NULL, obraz zostanie przesłany bezpośrednio na wyjście.

To skip this argument in order to provide the quality parameter, use NULL.

quality

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Outputting a JPEG image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Outputting a JPEG image

Przykład #2 Saving a JPEG image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');

// Free up memory
imagedestroy($im);
?>

Przykład #3 Outputting the image at 75% quality

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Skip the filename parameter using NULL, then set the quality to 75%
imagejpeg($im, NULL, 75);

// Free up memory
imagedestroy($im);
?>

Notatki

Informacja: Obsługa JPEG jest dostępna tylko jeśli PHP zostało skompilowane z GD-1.8 lub nowszym.

Informacja:

If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

Zobacz też:

  • imagepng() - Output a PNG image to either the browser or a file
  • imagegif() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagewbmp() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imageinterlace() - Enable or disable interlace
  • imagetypes() - Return the image types supported by this PHP build

imageistruecolor
imagelayereffect
GD and Image Funkcje


Set the alpha blending flag to use the bundled libgd layering effects

imagejpeg
imageline
GD and Image Funkcje
PHP Manual

imagelayereffect

(PHP 4 >= 4.3.0, PHP 5)

imagelayereffect — Set the alpha blending flag to use the bundled libgd layering effects

Opis

bool imagelayereffect ( resource $image , int $effect )

Set the alpha blending flag to use the bundled libgd layering effects.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

effect

One of the following constants:

IMG_EFFECT_REPLACE
Use pixel replacement (equivalent of passing TRUE to imagealphablending())
IMG_EFFECT_ALPHABLEND
Use normal pixel blending (equivalent of passing FALSE to imagealphablending())
IMG_EFFECT_NORMAL
Same as IMG_EFFECT_ALPHABLEND.
IMG_EFFECT_OVERLAY
Overlay has the effect that black background pixels will remain black, white background pixels will remain white, but grey background pixels will take the colour of the foreground pixel.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagelayereffect() example

<?php
// Setup an image
$im = imagecreatetruecolor(100, 100);

// Set a background
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 220, 220, 220));

// Apply the overlay alpha blending flag
imagelayereffect($im, IMG_EFFECT_OVERLAY);

// Draw two grey ellipses
imagefilledellipse($im, 50, 50, 40, 40, imagecolorallocate($im, 100, 255, 100));
imagefilledellipse($im, 50, 50, 50, 80, imagecolorallocate($im, 100, 100, 255));
imagefilledellipse($im, 50, 50, 80, 50, imagecolorallocate($im, 255, 100, 100));

// Output
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagelayereffect()

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dołączoną wersją biblioteki GD.

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

imagejpeg
imageline
GD and Image Funkcje


Draw a line

imagelayereffect
imageloadfont
GD and Image Funkcje
PHP Manual

imageline

(PHP 4, PHP 5)

imageline — Draw a line

Opis

bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

Draws a line between the two given points.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

x1

x-coordinate for first point.

y1

y-coordinate for first point.

x2

x-coordinate for second point.

y2

y-coordinate for second point.

color

The line color. A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Drawing a thick line

<?php

function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
{
    /* this way it works well only for orthogonal lines
    imagesetthickness($image, $thick);
    return imageline($image, $x1, $y1, $x2, $y2, $color);
    */
    if ($thick == 1) {
        return imageline($image, $x1, $y1, $x2, $y2, $color);
    }
    $t = $thick / 2 - 0.5;
    if ($x1 == $x2 || $y1 == $y2) {
        return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
    }
    $k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q
    $a = $t / sqrt(1 + pow($k, 2));
    $points = array(
        round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
        round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
        round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
        round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
    );
    imagefilledpolygon($image, $points, 4, $color);
    return imagepolygon($image, $points, 4, $color);
}

?>

Zobacz też:

  • imagecreatetruecolor() - Create a new true color image
  • imagecolorallocate() - Allocate a color for an image

imagelayereffect
imageloadfont
GD and Image Funkcje


Load a new font

imageline
imagepalettecopy
GD and Image Funkcje
PHP Manual

imageloadfont

(PHP 4, PHP 5)

imageloadfont — Load a new font

Opis

int imageloadfont ( string $file )

imageloadfont() loads a user-defined bitmap and returns its identifier.

Parametry

file

The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.

Font file format
byte position | C data type | description
byte 0-3 | int | number of characters in the font
byte 4-7 | int | value of first character in the font (often 32 for space)
byte 8-11 | int | pixel width of each character
byte 12-15 | int | pixel height of each character
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes.

Zwracane wartości

The font identifier which is always bigger than 5 to avoid conflicts with built-in fonts or FALSE on errors.

Przykłady

Przykład #1 imageloadfont() usage example

<?php
// Create a new image instance
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Make the background white
imagefilledrectangle($im, 0, 0, 49, 19, $white);

// Load the gd font and write 'Hello'
$font = imageloadfont('./04b.gdf');
imagestring($im, $font, 0, 0, 'Hello', $black);

// Output to browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Zobacz też:

  • imagefontwidth() - Get font width
  • imagefontheight() - Get font height

imageline
imagepalettecopy
GD and Image Funkcje


Copy the palette from one image to another

imageloadfont
imagepng
GD and Image Funkcje
PHP Manual

imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5)

imagepalettecopy — Copy the palette from one image to another

Opis

void imagepalettecopy ( resource $destination , resource $source )

imagepalettecopy() copies the palette from the source image to the destination image.

Parametry

destination

The destination image resource.

source

The source image resource.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 imagepalettecopy() example

<?php
// Create two palette images
$palette1 = imagecreate(100, 100);
$palette2 = imagecreate(100, 100);

// Allocate the background to be
// green in the first palette image
$green = imagecolorallocate($palette1, 0, 255, 0);

// Copy the palette from image 1 to image 2
imagepalettecopy($palette2, $palette1);

// Since the palette is now copied we can use the
// green color allocated to image 1 without using
// imagecolorallocate() twice
imagefilledrectangle($palette2, 0, 0, 99, 99, $green);

// Output image to the browser
header('Content-type: image/png');

imagepng($palette2);
imagedestroy($palette1);
imagedestroy($palette2);
?>

imageloadfont
imagepng
GD and Image Funkcje


Output a PNG image to either the browser or a file

imagepalettecopy
imagepolygon
GD and Image Funkcje
PHP Manual

imagepng

(PHP 4, PHP 5)

imagepng — Output a PNG image to either the browser or a file

Opis

bool imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] )

Outputs or saves a PNG image from the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filename

Ścieżka do zapisu pliku. Jeśli nie jest ustawiona lub ma wartość NULL, obraz zostanie przesłany bezpośrednio na wyjście.

Informacja:

NULL is invalid if the quality and filters arguments are not used.

quality

Compression level: from 0 (no compression) to 9.

filters

Allows reducing the PNG file size. It is a bitmask field which may be set to any combination of the PNG_FILTER_XXX constants. PNG_NO_FILTER or PNG_ALL_FILTERS may also be used to respectively disable or activate all filters.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.1.3 | Added the filters parameter.
5.1.2 | Added the quality parameter.

Przykłady

<?php
$im = imagecreatefrompng("test.png");

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

Zobacz też:

  • imagegif() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagewbmp() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagejpeg() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagetypes() - Return the image types supported by this PHP build
  • imagesavealpha() - Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

imagepalettecopy
imagepolygon
GD and Image Funkcje


Draws a polygon

imagepng
imagepsbbox
GD and Image Funkcje
PHP Manual

imagepolygon

(PHP 4, PHP 5)

imagepolygon — Draws a polygon

Opis

bool imagepolygon ( resource $image , array $points , int $num_points , int $color )

imagepolygon() creates a polygon in the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

points

An array containing the polygon's vertices, e.g.:

points[0] | = x0
points[1] | = y0
points[2] | = x1
points[3] | = y1

num_points

Total number of points (vertices).

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagepolygon() example

<?php
// Create a blank image
$image = imagecreatetruecolor(400, 300);

// Allocate a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);

// Draw the polygon
imagepolygon($image, array(
        0,   0,
        100, 200,
        300, 200
    ),
    3,
    $col_poly);

// Output the picture to the browser
header('Content-type: image/png');

imagepng($image);
imagedestroy($image);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagepolygon()

Zobacz też:

  • imagecreate() - Create a new palette based image
  • imagecreatetruecolor() - Create a new true color image

imagepng
imagepsbbox
GD and Image Funkcje


Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepolygon
imagepsencodefont
GD and Image Funkcje
PHP Manual

imagepsbbox

(PHP 4, PHP 5)

imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts

Opis

array imagepsbbox ( string $text , resource $font , int $size )
array imagepsbbox ( string $text , resource $font , int $size , int $space , int $tightness , float $angle )

Gives the bounding box of a text rectangle using PostScript Type1 fonts.

The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.

Parametry

text

The text to be written.

font_index

A font resource, returned by imagepsloadfont().

size

size is expressed in pixels.

space

Allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

tightness

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

angle

angle is in degrees.

Zwracane wartości

Returns an array containing the following elements:

0 | left x-coordinate
1 | upper y-coordinate
2 | right x-coordinate
3 | lower y-coordinate

Przykłady

Przykład #1 imagepsbbox() usage

<?php
// Create image handle
$im = imagecreatetruecolor(200, 200);

// Allocate colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Load the PostScript Font
$font = imagepsloadfont('font.pfm');

// Make a bounding box for the font
$bbox = imagepsbbox('Sample text is simple', $font, 12);

// Define our X and Y cordinates
$x = ($bbox[2] / 2) - 10;
$y = ($bbox[3] / 2) - 10;

// Write the font to the image
imagepstext($im, 'Sample text is simple', $font, 12, $black, $white, $x, $y);

// Output and free memory
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dyrektywą --enable-t1lib .

Zobacz też:

  • imagepstext() - Draws a text over an image using PostScript Type1 fonts

imagepolygon
imagepsencodefont
GD and Image Funkcje


Change the character encoding vector of a font

imagepsbbox
imagepsextendfont
GD and Image Funkcje
PHP Manual

imagepsencodefont

(PHP 4, PHP 5)

imagepsencodefont — Change the character encoding vector of a font

Opis

bool imagepsencodefont ( resource $font_index , string $encodingfile )

Loads a character encoding vector from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than English.

If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.

Parametry

font_index

A font resource, returned by imagepsloadfont().

encodingfile

The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagepsencodefont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Tell T1lib to use ISO Latin 1 encoding
imagepsencode($font, './IsoLatin1.enc');

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dyrektywą --enable-t1lib .

imagepsbbox
imagepsextendfont
GD and Image Funkcje


Extend or condense a font

imagepsencodefont
imagepsfreefont
GD and Image Funkcje
PHP Manual

imagepsextendfont

(PHP 4, PHP 5)

imagepsextendfont — Extend or condense a font

Opis

bool imagepsextendfont ( resource $font_index , float $extend )

Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.

Parametry

font_index

A font resource, returned by imagepsloadfont().

extend

Extension value, must be greater than 0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagepsextendfont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Extend the font by 2.5
imagepsextendfont($font, 2.5);

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dyrektywą --enable-t1lib .

imagepsencodefont
imagepsfreefont
GD and Image Funkcje


Free memory used by a PostScript Type 1 font

imagepsextendfont
imagepsloadfont
GD and Image Funkcje
PHP Manual

imagepsfreefont

(PHP 4, PHP 5)

imagepsfreefont — Free memory used by a PostScript Type 1 font

Opis

bool imagepsfreefont ( resource $font_index )

imagepsfreefont() frees memory used by a PostScript Type 1 font.

Parametry

font_index

A font resource, returned by imagepsloadfont().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagepsfreefont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./bchbi.pfb');

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dyrektywą --enable-t1lib .

Zobacz też:

  • imagepsloadfont() - Load a PostScript Type 1 font from file

imagepsextendfont
imagepsloadfont
GD and Image Funkcje


Load a PostScript Type 1 font from file

imagepsfreefont
imagepsslantfont
GD and Image Funkcje
PHP Manual

imagepsloadfont

(PHP 4, PHP 5)

imagepsloadfont — Load a PostScript Type 1 font from file

Opis

resource imagepsloadfont ( string $filename )

Load a PostScript Type 1 font from the given filename.

Parametry

filename

Path to the Postscript font file.

Zwracane wartości

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE.

Przykłady

Przykład #1 imagepsloadfont() example

<?php
// Create a new image instance
$im = imagecreatetruecolor(350, 45);

// Allocate colors and fill the background
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 349, 44, $white);

// Load a font, write to the image and free the font from memory
$font = imagepsloadfont("bchbi.pfb");
imagepstext($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont($font);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dyrektywą --enable-t1lib .

Zobacz też:

  • imagepsfreefont() - Free memory used by a PostScript Type 1 font

imagepsfreefont
imagepsslantfont
GD and Image Funkcje


Slant a font

imagepsloadfont
imagepstext
GD and Image Funkcje
PHP Manual

imagepsslantfont

(PHP 4, PHP 5)

imagepsslantfont — Slant a font

Opis

bool imagepsslantfont ( resource $font_index , float $slant )

Slant a given font given.

Parametry

font_index

A font resource, returned by imagepsloadfont().

slant

Slant level.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagepsslantfont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Slant the font by 22.5
imagepsslantfont($font, 22.5);

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dyrektywą --enable-t1lib .

imagepsloadfont
imagepstext
GD and Image Funkcje


Draws a text over an image using PostScript Type1 fonts

imagepsslantfont
imagerectangle
GD and Image Funkcje
PHP Manual

imagepstext

(PHP 4, PHP 5)

imagepstext — Draws a text over an image using PostScript Type1 fonts

Opis

array imagepstext ( resource $image , string $text , resource $font_index , int $size , int $foreground , int $background , int $x , int $y [, int $space = 0 [, int $tightness = 0 [, float $angle = 0.0 [, int $antialias_steps = 4 ]]]] )

Draws a text on an image using PostScript Type1 fonts.

Refer to PostScript documentation about fonts and their measuring system if you have trouble understanding how this works.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

text

The text to be written.

font_index

A font resource, returned by imagepsloadfont().

size

size is expressed in pixels.

foreground

The color in which the text will be painted.

background

The color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.

x

x-coordinate for the lower-left corner of the first character.

y

y-coordinate for the lower-left corner of the first character.

space

Allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

tightness

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

angle

angle is in degrees.

antialias_steps

Allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.

Zwracane wartości

This function returns an array containing the following elements:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | upper right x-coordinate
3 | upper right y-coordinate

Przykłady

Przykład #1 imagepstext() usage

<?php
// Create image handle
$im = imagecreatetruecolor(200, 200);

// Allocate colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Load the PostScript Font
$font = imagepsloadfont('font.pfm');

// Write the font to the image
imagepstext($im, 'Sample text is simple', $font, 12, $black, $white, 50, 50);

// Output and free memory
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dyrektywą --enable-t1lib .

Zobacz też:

  • imagepsbbox() - Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepsslantfont
imagerectangle
GD and Image Funkcje


Draw a rectangle

imagepstext
imagerotate
GD and Image Funkcje
PHP Manual

imagerectangle

(PHP 4, PHP 5)

imagerectangle — Draw a rectangle

Opis

bool imagerectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

imagerectangle() creates a rectangle starting at the specified coordinates.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

x1

Upper left x coordinate.

y1

Upper left y coordinate 0, 0 is the top left corner of the image.

x2

Bottom right x coordinate.

y2

Bottom right y coordinate.

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Simple imagerectangle() example

<?php
// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);

// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);

// Draw three rectangles each with its own color
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);

// Output and free from memory
header('Content-Type: image/jpeg');

imagejpeg($canvas);
imagedestroy($canvas);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Simple imagerectangle() example

imagepstext
imagerotate
GD and Image Funkcje


Rotate an image with a given angle

imagerectangle
imagesavealpha
GD and Image Funkcje
PHP Manual

imagerotate

(PHP 4 >= 4.3.0, PHP 5)

imagerotate — Rotate an image with a given angle

Opis

resource imagerotate ( resource $image , float $angle , int $bgd_color [, int $ignore_transparent = 0 ] )

Rotates the image image using the given angle in degrees.

The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

angle

Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image anticlockwise.

bgd_color

Specifies the color of the uncovered zone after the rotation

ignore_transparent

If set and non-zero, transparent colors are ignored (otherwise kept).

Zwracane wartości

Returns an image resource for the rotated image, lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja | Opis
5.1.0 | ignore_transparent was added.

Przykłady

Przykład #1 Rotate an image 180 degrees

This example rotates an image 180 degrees - upside down.

<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Rotate an image 180 degrees

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dołączoną wersją biblioteki GD.

imagerectangle
imagesavealpha
GD and Image Funkcje


Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

imagerotate
imagesetbrush
GD and Image Funkcje
PHP Manual

imagesavealpha

(PHP 4 >= 4.3.2, PHP 5)

imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

Opis

bool imagesavealpha ( resource $image , bool $saveflag )

imagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.

You have to unset alphablending (imagealphablending($im, false)), to use it.

Alpha channel is not supported by all browsers, if you have problem with your browser, try to load your script with an alpha channel compliant browser, e.g. latest Mozilla.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

saveflag

Whether to save the alpha channel or not. Default to FALSE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagesavealpha() example

<?php
// Load a png image with alpha channels
$png = imagecreatefrompng('./alphachannel_example.png');

// Do required operations

// Turn off alpha blending and set alpha flag
imagealphablending($png, false);
imagesavealpha($png, true);

// Output image to browser
header('Content-Type: image/png');

imagepng($png);
imagedestroy($png);
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

Zobacz też:

  • imagealphablending() - Set the blending mode for an image

imagerotate
imagesetbrush
GD and Image Funkcje


Set the brush image for line drawing

imagesavealpha
imagesetpixel
GD and Image Funkcje
PHP Manual

imagesetbrush

(PHP 4 >= 4.0.6, PHP 5)

imagesetbrush — Set the brush image for line drawing

Opis

bool imagesetbrush ( resource $image , resource $brush )

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

brush

An image resource.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagesetbrush() example

<?php
// Load a mini php logo
$php = imagecreatefrompng('./php.png');

// Create the main image, 100x100
$im = imagecreatetruecolor(100, 100);

// Fill the background with white
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 299, 99, $white);

// Set the brush
imagesetbrush($im, $php);

// Draw a couple of brushes, each overlaying each
imageline($im, 50, 50, 50, 60, IMG_COLOR_BRUSHED);

// Output image to the browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
imagedestroy($php);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagesetbrush()

Notatki

Informacja:

You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!

imagesavealpha
imagesetpixel
GD and Image Funkcje


Set a single pixel

imagesetbrush
imagesetstyle
GD and Image Funkcje
PHP Manual

imagesetpixel

(PHP 4, PHP 5)

imagesetpixel — Set a single pixel

Opis

bool imagesetpixel ( resource $image , int $x , int $y , int $color )

imagesetpixel() draws a pixel at the specified coordinate.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

x

x-coordinate.

y

y-coordinate.

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagesetpixel() example

A random drawing that ends with a regular picture.

<?php

$x = 200;
$y = 200;

$gd = imagecreatetruecolor($x, $y);

$corners[0] = array('x' => 100, 'y' =>  10);
$corners[1] = array('x' =>   0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);

$red = imagecolorallocate($gd, 255, 0, 0);

for ($i = 0; $i < 100000; $i++) {
  imagesetpixel($gd, round($x),round($y), $red);
  $a = rand(0, 2);
  $x = ($x + $corners[$a]['x']) / 2;
  $y = ($y + $corners[$a]['y']) / 2;
}

header('Content-Type: image/png');
imagepng($gd);

?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagesetpixel()

Zobacz też:

  • imagecreatetruecolor() - Create a new true color image
  • imagecolorallocate() - Allocate a color for an image

imagesetbrush
imagesetstyle
GD and Image Funkcje


Set the style for line drawing

imagesetpixel
imagesetthickness
GD and Image Funkcje
PHP Manual

imagesetstyle

(PHP 4 >= 4.0.6, PHP 5)

imagesetstyle — Set the style for line drawing

Opis

bool imagesetstyle ( resource $image , array $style )

imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

style

An array of pixel colors. You can use the IMG_COLOR_TRANSPARENT constant to add a transparent pixel.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Following example script draws a dashed line from upper left to lower right corner of the canvas:

Przykład #1 imagesetstyle() example

<?php
header("Content-type: image/jpeg");
$im  = imagecreatetruecolor(100, 100);
$w   = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);

/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style = array($red, $red, $red, $red, $red, $w, $w, $w, $w, $w);
imagesetstyle($im, $style);
imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using imagesetbrush() with imagesetstyle */
$style = array($w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $red);
imagesetstyle($im, $style);

$brush = imagecreatefrompng("http://www.libpng.org/pub/png/images/smile.happy.png");
$w2 = imagecolorallocate($brush, 255, 255, 255);
imagecolortransparent($brush, $w2);
imagesetbrush($im, $brush);
imageline($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

imagejpeg($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagesetstyle()

Zobacz też:

  • imagesetbrush() - Set the brush image for line drawing
  • imageline() - Draw a line

imagesetpixel
imagesetthickness
GD and Image Funkcje


Set the thickness for line drawing

imagesetstyle
imagesettile
GD and Image Funkcje
PHP Manual

imagesetthickness

(PHP 4 >= 4.0.6, PHP 5)

imagesetthickness — Set the thickness for line drawing

Opis

bool imagesetthickness ( resource $image , int $thickness )

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

thickness

Thickness, in pixels.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagesetthickness() example

<?php
// Create a 200x100 image
$im = imagecreatetruecolor(200, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 99, $white);

// Set the line thickness to 5
imagesetthickness($im, 5);

// Draw the rectangle
imagerectangle($im, 14, 14, 185, 85, $black);

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagesetthickness()

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

imagesetstyle
imagesettile
GD and Image Funkcje


Set the tile image for filling

imagesetthickness
imagestring
GD and Image Funkcje
PHP Manual

imagesettile

(PHP 4 >= 4.0.6, PHP 5)

imagesettile — Set the tile image for filling

Opis

bool imagesettile ( resource $image , resource $tile )

imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.

Informacja:

You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

tile

The image resource to be used as a tile.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagesettile() example

<?php
// Load an external image
$zend = imagecreatefromgif('./zend.gif');

// Create a 200x200 image
$im = imagecreatetruecolor(200, 200);

// Set the tile
imagesettile($im, $zend);

// Make the image repeat
imagefilledrectangle($im, 0, 0, 199, 199, IMG_COLOR_TILED);

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
imagedestroy($zend);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagesettile()

imagesetthickness
imagestring
GD and Image Funkcje


Draw a string horizontally

imagesettile
imagestringup
GD and Image Funkcje
PHP Manual

imagestring

(PHP 4, PHP 5)

imagestring — Draw a string horizontally

Opis

bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color )

Draws a string at the given coordinates.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

czcionka

Może przyjąć 1, 2, 3, 4, 5 dla wbudowanych czcionek w kodowaniu latin2 (gdzie większy numer odpowiada większej czcionce) lub własny dowolny identyfikator czcionki zarejestrowany przez imageloadfont().

x

x-coordinate of the upper left corner.

y

y-coordinate of the upper left corner.

string

The string to be written.

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagestring() example

<?php
// Create a 100*30 image
$im = imagecreate(100, 30);

// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// Write the string at the top left
imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagestring()

Zobacz też:

  • imageloadfont() - Load a new font
  • imagettftext() - Write text to the image using TrueType fonts

imagesettile
imagestringup
GD and Image Funkcje


Draw a string vertically

imagestring
imagesx
GD and Image Funkcje
PHP Manual

imagestringup

(PHP 4, PHP 5)

imagestringup — Draw a string vertically

Opis

bool imagestringup ( resource $image , int $font , int $x , int $y , string $string , int $color )

Draws a string vertically at the given coordinates.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

czcionka

Może przyjąć 1, 2, 3, 4, 5 dla wbudowanych czcionek w kodowaniu latin2 (gdzie większy numer odpowiada większej czcionce) lub własny dowolny identyfikator czcionki zarejestrowany przez imageloadfont().

x

x-coordinate of the bottom left corner.

y

y-coordinate of the bottom left corner.

string

The string to be written.

color

A color identifier created with imagecolorallocate().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imagestringup() example

<?php
// create a 100*100 image
$im = imagecreatetruecolor(100, 100);

// Write the text
$textcolor = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
imagestringup($im, 3, 40, 80, 'gd library', $textcolor);

// Save the image
imagepng($im, './stringup.png');
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagestringup()

Zobacz też:

  • imageloadfont() - Load a new font

imagestring
imagesx
GD and Image Funkcje


Get image width

imagestringup
imagesy
GD and Image Funkcje
PHP Manual

imagesx

(PHP 4, PHP 5)

imagesx — Get image width

Opis

int imagesx ( resource $image )

Returns the width of the given image resource.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

Zwracane wartości

Return the width of the image or FALSE on errors.

Przykłady

Przykład #1 Using imagesx()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesx($img); // 300

?>

Zobacz też:

  • imagecreatetruecolor() - Create a new true color image
  • getimagesize() - Get the size of an image
  • imagesy() - Get image height

imagestringup
imagesy
GD and Image Funkcje


Get image height

imagesx
imagetruecolortopalette
GD and Image Funkcje
PHP Manual

imagesy

(PHP 4, PHP 5)

imagesy — Get image height

Opis

int imagesy ( resource $image )

Returns the height of the given image resource.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

Zwracane wartości

Return the height of the image or FALSE on errors.

Przykłady

Przykład #1 Using imagesy()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesy($img); // 200

?>

Zobacz też:

  • imagecreatetruecolor() - Create a new true color image
  • getimagesize() - Get the size of an image
  • imagesx() - Get image width

imagesx
imagetruecolortopalette
GD and Image Funkcje


Convert a true color image to a palette image

imagesy
imagettfbbox
GD and Image Funkcje
PHP Manual

imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5)

imagetruecolortopalette — Convert a true color image to a palette image

Opis

bool imagetruecolortopalette ( resource $image , bool $dither , int $ncolors )

imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

dither

Indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.

ncolors

Sets the maximum number of colors that should be retained in the palette.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Converting a true color image to a palette-based image

<?php
// Create a new true color image
$im = imagecreatetruecolor(100, 100);

// Convert to palette-based with no dithering and 255 colors
imagetruecolortopalette($im, false, 255);

// Save the image
imagepng($im, './paletteimage.png');
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja wymaga GD 2.0.1 lub nowszej (2.0.28 lub nowsza jest zalecana).

imagesy
imagettfbbox
GD and Image Funkcje


Give the bounding box of a text using TrueType fonts

imagetruecolortopalette
imagettftext
GD and Image Funkcje
PHP Manual

imagettfbbox

(PHP 4, PHP 5)

imagettfbbox — Give the bounding box of a text using TrueType fonts

Opis

array imagettfbbox ( float $size , float $angle , string $fontfile , string $text )

This function calculates and returns the bounding box in pixels for a TrueType text.

Parametry

size

The font size.

Informacja: In GD 1, this is measured in pixels. In GD 2, this is measured in points.

angle

Angle in degrees in which text will be measured.

fontfile

The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.

text

The string to be measured.

Zwracane wartości

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text on success and FALSE on error.

key | contents
0 | lower left corner, X position
1 | lower left corner, Y position
2 | lower right corner, X position
3 | lower right corner, Y position
4 | upper right corner, X position
5 | upper right corner, Y position
6 | upper left corner, X position
7 | upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontally.

Przykłady

Przykład #1 imagettfbbox() example

<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// Path to our font file
$font = './arial.ttf';

// First we create our bounding box for the first text
$bbox = imagettfbbox(10, 45, $font, 'Powered by PHP ' . phpversion());

// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 25;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'Powered by PHP ' . phpversion());

// Create the next bounding box for the second text
$bbox = imagettfbbox(10, 45, $font, 'and Zend Engine ' . zend_version());

// Set the cordinates so its next to the first text
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) + 10;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'and Zend Engine ' . zend_version());

// Output to browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notatki

Informacja:

This function requires both the GD library and the » FreeType library.

Zobacz też:

  • imagettftext() - Write text to the image using TrueType fonts

imagetruecolortopalette
imagettftext
GD and Image Funkcje


Write text to the image using TrueType fonts

imagettfbbox
imagetypes
GD and Image Funkcje
PHP Manual

imagettftext

(PHP 4, PHP 5)

imagettftext — Write text to the image using TrueType fonts

Opis

array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )

Writes the given text into the image using TrueType fonts.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

size

Rozmiar czcionki. W zależności od wersji GD rozmiar jest określony albo w pikselach (GD1), albo w punktach (GD2).

angle

The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.

x

The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.

y

The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.

color

The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().

fontfile

The path to the TrueType font you wish to use.

Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.

In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.

<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

text

The text string in UTF-8 encoding.

May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127. The hexadecimal format (like &#xA9;) is supported. Strings in UTF-8 encoding can be passed directly.

Named entities, such as &copy;, are not supported. Consider using html_entity_decode() to decode these named entities into UTF-8 strings (html_entity_decode() supports this as of PHP 5.0.0).

If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.

Zwracane wartości

Returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally. Returns FALSE on error.

Rejestr zmian

Wersja | Opis
5.2.0 | It is now possible to specify an hexadecimal entity in text.

Przykłady

Przykład #1 imagettftext() example

This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial.

<?php
// Set the content-type
header('Content-Type: image/png');

// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : imagettftext()

Notatki

Informacja:

This function requires both the GD library and the » FreeType library.

Zobacz też:

  • imagettfbbox() - Give the bounding box of a text using TrueType fonts

imagettfbbox
imagetypes
GD and Image Funkcje


Return the image types supported by this PHP build

imagettftext
imagewbmp
GD and Image Funkcje
PHP Manual

imagetypes

(PHP 4 >= 4.0.2, PHP 5)

imagetypes — Return the image types supported by this PHP build

Opis

int imagetypes ( void )

Returns the image types supported by the current PHP installation.

Zwracane wartości

Returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM.

Przykłady

Przykład #1 Checking for PNG support

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

imagettftext
imagewbmp
GD and Image Funkcje


Wysłanie obrazu do przeglądarki lub zapis do pliku

imagetypes
imagexbm
GD and Image Funkcje
PHP Manual

imagewbmp

(PHP 4 >= 4.0.1, PHP 5)

imagewbmp — Wysłanie obrazu do przeglądarki lub zapis do pliku

Opis

bool imagewbmp ( resource $image [, string $filename [, int $foreground ]] )

imagewbmp() outputs or save a WBMP version of the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filename

Ścieżka do zapisu pliku. Jeśli nie jest ustawiona lub ma wartość NULL, obraz zostanie przesłany bezpośrednio na wyjście.

foreground

You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Outputting a WBMP image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/vnd.wap.wbmp
// Hint: see image_type_to_mime_type() for content-types
header('Content-Type: image/vnd.wap.wbmp');

// Output the image
imagewbmp($im);

// Free up memory
imagedestroy($im);
?>

Przykład #2 Saving the WBMP image

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image
imagewbmp($im, 'simpletext.wbmp');

// Free up memory
imagedestroy($im);
?>

Przykład #3 Outputting the image with a different foreground

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/vnd.wap.wbmp
// Hint: see image_type_to_mime_type() for content-types
header('Content-Type: image/vnd.wap.wbmp');

// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);

imagewbmp($im, NULL, $foreground_color);

// Free up memory
imagedestroy($im);
?>

Notatki

Informacja:

WBMP support is only available if PHP was compiled against GD-1.8 or later.

Zobacz też:

  • image2wbmp() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagepng() - Output a PNG image to either the browser or a file
  • imagegif() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagejpeg() - Wysłanie obrazu do przeglądarki lub zapis do pliku
  • imagetypes() - Return the image types supported by this PHP build

imagetypes
imagexbm
GD and Image Funkcje


Output XBM image to browser or file

imagewbmp
iptcembed
GD and Image Funkcje
PHP Manual

imagexbm

(PHP 5)

imagexbm — Output XBM image to browser or file

Opis

bool imagexbm ( resource $image , string $filename [, int $foreground ] )

Outputs or save an XBM version of the given image.

Parametry

obraz

Zasób obrazu, zwrócony przez jedną z funkcji tworzących obrazy, taką jak imagecreatetruecolor().

filename

Ścieżka do zapisu pliku. Jeśli nie jest ustawiona lub ma wartość NULL, obraz zostanie przesłany bezpośrednio na wyjście.

foreground

You can set the foreground color with this parameter by setting an identifier obtained from imagecolorallocate(). The default foreground color is black.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Saving an XBM file

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Save the image
imagexbm($im, 'simpletext.xbm');

// Free up memory
imagedestroy($im);
?>

Przykład #2 Saving an XBM file with a different foreground color

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);

// Save the image
imagexbm($im, NULL, $foreground_color);

// Free up memory
imagedestroy($im);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko jeśli PHP zostało skompilowane z dołączoną wersją biblioteki GD.

imagewbmp
iptcembed
GD and Image Funkcje


Embeds binary IPTC data into a JPEG image

imagexbm
iptcparse
GD and Image Funkcje
PHP Manual

iptcembed

(PHP 4, PHP 5)

iptcembed — Embeds binary IPTC data into a JPEG image

Opis

mixed iptcembed ( string $iptcdata , string $jpeg_file_name [, int $spool ] )

Embeds binary IPTC data into a JPEG image.

Parametry

iptcdata

The data to be written.

jpeg_file_name

Path to the JPEG image.

spool

Spool flag. If the spool flag is over 2 then the JPEG will be returned as a string.

Zwracane wartości

If success and spool flag is lower than 2 then the JPEG will not be returned as a string, FALSE on errors.

Przykłady

Przykład #1 Embedding IPTC data into a JPEG

<?php

// iptc_make_tag() function by Thies C. Arntzen
function iptc_make_tag($rec, $data, $value)
{
    $length = strlen($value);
    $retval = chr(0x1C) . chr($rec) . chr($data);

    if($length < 0x8000)
    {
        $retval .= chr($length >> 8) .  chr($length & 0xFF);
    }
    else
    {
        $retval .= chr(0x80) .
                   chr(0x04) .
                   chr(($length >> 24) & 0xFF) .
                   chr(($length >> 16) & 0xFF) .
                   chr(($length >> 8) & 0xFF) .
                   chr($length & 0xFF);
    }

    return $retval . $value;
}

// Path to jpeg file
$path = './phplogo.jpg';

// We need to check if theres any IPTC data in the jpeg image. If there is then
// bail out because we cannot embed any image that already has some IPTC data!
$image = getimagesize($path, $info);

if(isset($info['APP13']))
{
    die('Error: IPTC data found in source image, cannot continue');
}

// Set the IPTC tags
$iptc = array(
    '2#120' => 'Test image',
    '2#116' => 'Copyright 2008-2009, The PHP Group'
);

// Convert the IPTC tags into binary code
$data = '';

foreach($iptc as $tag => $string)
{
    $tag = substr($tag, 2);
    $data .= iptc_make_tag(2, $tag, $string);
}

// Embed the IPTC data
$content = iptcembed($data, $path);

// Write the new image data out to the file.
$fp = fopen($path, "wb");
fwrite($fp, $content);
fclose($fp);
?>

Notatki

Informacja:

Ta funkcja nie wymaga dostępu do biblioteki GD.

imagexbm
iptcparse
GD and Image Funkcje


Parse a binary IPTC block into single tags.

iptcembed
jpeg2wbmp
GD and Image Funkcje
PHP Manual

iptcparse

(PHP 4, PHP 5)

iptcparse — Parse a binary IPTC block into single tags.

Opis

array iptcparse ( string $iptcblock )

Parses an » IPTC block into its single tags.

Parametry

iptcblock

A binary IPTC block.

Zwracane wartości

Returns an array using the tagmarker as an index and the value as the value. It returns FALSE on error or if no IPTC data was found.

Przykłady

Przykład #1 iptcparse() used together with getimagesize()

<?php
$size = getimagesize('./test.jpg', $info);
if(isset($info['APP13']))
{
    $iptc = iptcparse($info['APP13']);
    var_dump($iptc);
}
?>

Notatki

Informacja:

Ta funkcja nie wymaga dostępu do biblioteki GD.

iptcembed
jpeg2wbmp
GD and Image Funkcje


Convert JPEG image file to WBMP image file

iptcparse
png2wbmp
GD and Image Funkcje
PHP Manual

jpeg2wbmp

(PHP 4 >= 4.0.5, PHP 5)

jpeg2wbmp — Convert JPEG image file to WBMP image file

Opis

bool jpeg2wbmp ( string $jpegname , string $wbmpname , int $dest_height , int $dest_width , int $threshold )

Converts a JPEG file into a WBMP file.

Parametry

jpegname

Path to JPEG file.

wbmpname

Path to destination WBMP file.

dest_height

Destination image height.

dest_width

Destination image width.

threshold

Threshold value, between 0 and 8 (inclusive).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 jpeg2wbmp() example

<?php
// Path to the target jpeg
$path = './test.jpg';

// Get the image sizes
$image = getimagesize($path);

// Convert image
jpeg2wbmp($path, './test.wbmp', $image[1], $image[0], 5);
?>

Notatki

Informacja: Obsługa WBMP jest dostępna tylko jeśli PHP zostało skompilowane z GD-1.8 lub nowszym.

Informacja: Obsługa JPEG jest dostępna tylko jeśli PHP zostało skompilowane z GD-1.8 lub nowszym.

Zobacz też:

  • png2wbmp() - Convert PNG image file to WBMP image file

iptcparse
png2wbmp
GD and Image Funkcje


Convert PNG image file to WBMP image file

jpeg2wbmp
Gmagick
GD and Image Funkcje
PHP Manual

png2wbmp

(PHP 4 >= 4.0.5, PHP 5)

png2wbmp — Convert PNG image file to WBMP image file

Opis

bool png2wbmp ( string $pngname , string $wbmpname , int $dest_height , int $dest_width , int $threshold )

Converts a PNG file into a WBMP file.

Parametry

pngname

Path to PNG file.

wbmpname

Path to destination WBMP file.

dest_height

Destination image height.

dest_width

Destination image width.

threshold

Threshold value, between 0 and 8 (inclusive).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 png2wbmp() example

<?php
// Path to the target png
$path = './test.png';

// Get the image sizes
$image = getimagesize($path);

// Convert image
png2wbmp($path, './test.wbmp', $image[1], $image[0], 7);
?>

Notatki

Informacja: Obsługa WBMP jest dostępna tylko jeśli PHP zostało skompilowane z GD-1.8 lub nowszym.

Zobacz też:

  • jpeg2wbmp() - Convert JPEG image file to WBMP image file

jpeg2wbmp
Gmagick
GD and Image Funkcje


Gmagick

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
  • Stałe predefiniowane
  • Przykłady
  • Gmagick — The Gmagick class
    • Gmagick::addimage — Adds new image to Gmagick object image list
    • Gmagick::addnoiseimage — Adds random noise to the image
    • Gmagick::annotateimage — Annotates an image with text
    • Gmagick::blurimage — Adds blur filter to image
    • Gmagick::borderimage — Surrounds the image with a border
    • Gmagick::charcoalimage — Simulates a charcoal drawing
    • Gmagick::chopimage — Removes a region of an image and trims
    • Gmagick::clear — Clears all resources associated to Gmagick object
    • Gmagick::commentimage — Adds a comment to your image
    • Gmagick::compositeimage — Composite one image onto another
    • Gmagick::__construct — The Gmagick constructor
    • Gmagick::cropimage — Extracts a region of the image
    • Gmagick::cropthumbnailimage — Creates a crop thumbnail
    • Gmagick::current — The current purpose
    • Gmagick::cyclecolormapimage — Displaces an image's colormap
    • Gmagick::deconstructimages — Returns certain pixel differences between images
    • Gmagick::despeckleimage — The despeckleimage purpose
    • Gmagick::destroy — The destroy purpose
    • Gmagick::drawimage — Renders the GmagickDraw object on the current image
    • Gmagick::edgeimage — Enhance edges within the image
    • Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
    • Gmagick::enhanceimage — Improves the quality of a noisy image
    • Gmagick::equalizeimage — Equalizes the image histogram
    • Gmagick::flipimage — Creates a vertical mirror image
    • Gmagick::flopimage — The flopimage purpose
    • Gmagick::frameimage — Adds a simulated three-dimensional border
    • Gmagick::gammaimage — Gamma-corrects an image
    • Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
    • Gmagick::getfilename — The filename associated with an image sequence
    • Gmagick::getimagebackgroundcolor — Returns the image background color
    • Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
    • Gmagick::getimagebordercolor — Returns the image border color
    • Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
    • Gmagick::getimagecolors — Returns the color of the specified colormap index
    • Gmagick::getimagecolorspace — Gets the image colorspace
    • Gmagick::getimagecompose — Returns the composite operator associated with the image
    • Gmagick::getimagedelay — Gets the image delay
    • Gmagick::getimagedepth — Gets the depth of the image
    • Gmagick::getimagedispose — Gets the image disposal method
    • Gmagick::getimageextrema — Gets the extrema for the image
    • Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
    • Gmagick::getimageformat — Returns the format of a particular image in a sequence
    • Gmagick::getimagegamma — Gets the image gamma
    • Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
    • Gmagick::getimageheight — Returns the image height
    • Gmagick::getimagehistogram — Gets the image histogram
    • Gmagick::getimageindex — Gets the index of the current active image
    • Gmagick::getimageinterlacescheme — Gets the image interlace scheme
    • Gmagick::getimageiterations — Gets the image iterations
    • Gmagick::getimagematte — Return if the image has a matte channel
    • Gmagick::getimagemattecolor — Returns the image matte color
    • Gmagick::getimageprofile — Returns the named image profile.
    • Gmagick::getimageredprimary — Returns the chromaticity red primary point
    • Gmagick::getimagerenderingintent — Gets the image rendering intent
    • Gmagick::getimageresolution — Gets the image X and Y resolution
    • Gmagick::getimagescene — Gets the image scene
    • Gmagick::getimagesignature — Generates an SHA-256 message digest
    • Gmagick::getimagetype — Gets the potential image type.
    • Gmagick::getimageunits — Gets the image units of resolution
    • Gmagick::getimagewhitepoint — Returns the chromaticity white point
    • Gmagick::getimagewidth — Returns the width of the image
    • Gmagick::getpackagename — Returns the GraphicsMagick package name.
    • Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.
    • Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.
    • Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.
    • Gmagick::getsize — Returns the size associated with the Gmagick object
    • Gmagick::getversion — Returns the GraphicsMagick API version
    • Gmagick::hasnextimage — Checks if the object has more images
    • Gmagick::haspreviousimage — Checks if the object has a previous image
    • Gmagick::implodeimage — Creates a new image as a copy
    • Gmagick::labelimage — Adds a label to an image.
    • Gmagick::levelimage — Adjusts the levels of an image
    • Gmagick::magnifyimage — Scales an image proportionally 2x
    • Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.
    • Gmagick::medianfilterimage — Applies a digital filter
    • Gmagick::minifyimage — Scales an image proportionally to half its size
    • Gmagick::modulateimage — Control the brightness, saturation, and hue
    • Gmagick::motionblurimage — Simulates motion blur
    • Gmagick::newimage — Creates a new image
    • Gmagick::nextimage — Moves to the next image
    • Gmagick::normalizeimage — Enhances the contrast of a color image
    • Gmagick::oilpaintimage — Simulates an oil painting
    • Gmagick::previousimage — Move to the previous image in the object
    • Gmagick::profileimage — Adds or removes a profile from an image
    • Gmagick::quantizeimage — Analyzes the colors within a reference image
    • Gmagick::quantizeimages — The quantizeimages purpose
    • Gmagick::queryfontmetrics — Returns an array representing the font metrics
    • Gmagick::queryfonts — Returns the configured fonts
    • Gmagick::queryformats — Returns formats supported by Gmagick.
    • Gmagick::radialblurimage — Radial blurs an image
    • Gmagick::raiseimage — Creates a simulated 3d button-like effect
    • Gmagick::read — Reads image from filename
    • Gmagick::readimage — Reads image from filename
    • Gmagick::readimageblob — Reads image from a binary string
    • Gmagick::readimagefile — The readimagefile purpose
    • Gmagick::reducenoiseimage — Smooths the contours of an image
    • Gmagick::removeimage — Removes an image from the image list
    • Gmagick::removeimageprofile — Removes the named image profile and returns it
    • Gmagick::resampleimage — Resample image to desired resolution
    • Gmagick::resizeimage — Scales an image
    • Gmagick::rollimage — Offsets an image
    • Gmagick::rotateimage — Rotates an image
    • Gmagick::scaleimage — Scales the size of an image
    • Gmagick::separateimagechannel — Separates a channel from the image
    • Gmagick::setfilename — Sets the filename before you read or write the image
    • Gmagick::setimagebackgroundcolor — Sets the image background color.
    • Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.
    • Gmagick::setimagebordercolor — Sets the image border color.
    • Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
    • Gmagick::setimagecolorspace — Sets the image colorspace
    • Gmagick::setimagecompose — Sets the image composite operator
    • Gmagick::setimagedelay — Sets the image delay
    • Gmagick::setimagedepth — Sets the image depth
    • Gmagick::setimagedispose — Sets the image disposal method
    • Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
    • Gmagick::setimageformat — Sets the format of a particular image
    • Gmagick::setimagegamma — Sets the image gamma
    • Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.
    • Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
    • Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.
    • Gmagick::setimageiterations — Sets the image iterations.
    • Gmagick::setimageprofile — Adds a named profile to the Gmagick object
    • Gmagick::setimageredprimary — Sets the image chromaticity red primary point.
    • Gmagick::setimagerenderingintent — Sets the image rendering intent
    • Gmagick::setimageresolution — Sets the image resolution
    • Gmagick::setimagescene — Sets the image scene
    • Gmagick::setimagetype — Sets the image type
    • Gmagick::setimageunits — Sets the image units of resolution.
    • Gmagick::setimagewhitepoint — Sets the image chromaticity white point.
    • Gmagick::setsamplingfactors — Sets the image sampling factors.
    • Gmagick::setsize — Sets the size of the Gmagick object
    • Gmagick::shearimage — Creating a parallelogram
    • Gmagick::solarizeimage — Applies a solarizing effect to the image
    • Gmagick::spreadimage — Randomly displaces each pixel in a block
    • Gmagick::stripimage — Strips an image of all profiles and comments
    • Gmagick::swirlimage — Swirls the pixels about the center of the image
    • Gmagick::thumbnailimage — Changes the size of an image
    • Gmagick::trimimage — Remove edges from the image
    • Gmagick::write — Writes an image to the specified filename
    • Gmagick::writeimage — Writes an image to the specified filename
  • GmagickDraw — The GmagickDraw class
    • GmagickDraw::annotate — Draws text on the image
    • GmagickDraw::arc — Draws an arc
    • GmagickDraw::bezier — Draws a bezier curve
    • GmagickDraw::ellipse — Draws an ellipse on the image
    • GmagickDraw::getfillcolor — Returns the fill color
    • GmagickDraw::getfillopacity — Returns the opacity used when drawing
    • GmagickDraw::getfont — Returns the font
    • GmagickDraw::getfontsize — Returns the font pointsize
    • GmagickDraw::getfontstyle — Returns the font style
    • GmagickDraw::getfontweight — Returns the font weight
    • GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration — Returns the text decoration
    • GmagickDraw::gettextencoding — Returns the code set used for text annotations
    • GmagickDraw::line — The line purpose
    • GmagickDraw::point — Draws a point
    • GmagickDraw::polygon — Draws a polygon
    • GmagickDraw::polyline — Draws a polyline
    • GmagickDraw::rectangle — Draws a rectangle
    • GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle — Draws a rounded rectangle
    • GmagickDraw::scale — Adjusts the scaling factor
    • GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.
    • GmagickDraw::setfillopacity — The setfillopacity purpose
    • GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.
    • GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.
    • GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight — Sets the font weight
    • GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.
    • GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.
    • GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.
    • GmagickDraw::settextdecoration — Specifies a decoration
    • GmagickDraw::settextencoding — Specifies specifies the text code set
  • GmagickPixel — The GmagickPixel class
    • GmagickPixel::__construct — The GmagickPixel constructor
    • GmagickPixel::getcolor — Returns the color
    • GmagickPixel::getcolorcount — Returns the color count associated with this color
    • GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor — Sets the color
    • GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels
png2wbmp
Wstęp
Przetwarzanie i generowanie obrazów


Wstęp

Gmagick is a php extension to create, modify and obtain meta information of images using the GraphicsMagick API.

GraphicsMagick prides itself as the swiss army knife of image processing. It works with over 88 major formats including important formats like DPX, GIF, JPEG, JPEG-2000, PNG, PDF, PNM, and TIFF.

Gmagick consists of a main Gmagick class, a GmagickDraw class which is in effect a drawing wand and a GmagickPixel class of which instances represent a single pixel of an image (color, opacity).

Gmagick
Instalacja/Konfiguracja
Gmagick


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
Wstęp
Wymagania
Gmagick


Wymagania

This extension works best with GraphicsMagick version 1.4+ and PHP 5.1.3+. Gmagick should work with earlier versions up to GraphicsMagick 1.2.6 but some features and formats are not supported for these versions. Windows version of GraphicsMagick is available from the GraphicsMagick website. To read about the difference between ImageMagick and GraphicsMagick, check this out: » FAQ .

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/gmagick.

Informacja: The official name of this extension is gmagick.

For Windows, the build of the Gmagick extension is available » here

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.

Instalacja
Stałe predefiniowane
Instalacja/Konfiguracja


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.

Colortype constants
Gmagick::COLOR_BLACK (integer)
Black
Gmagick::COLOR_BLUE (integer)
Blue
Gmagick::COLOR_CYAN (integer)
Cyan
Gmagick::COLOR_GREEN (integer)
Green
Gmagick::COLOR_RED (integer)
Red
Gmagick::COLOR_YELLOW (integer)
Yellow
Gmagick::COLOR_MAGENTA (integer)
Magenta
Gmagick::COLOR_OPACITY (integer)
Opacity
Gmagick::COLOR_ALPHA (integer)
Alpha
Gmagick::COLOR_FUZZ (integer)
Fuzz
Composite Operator Constants
Gmagick::COMPOSITE_DEFAULT (integer)
The default composite operator
Gmagick::COMPOSITE_UNDEFINED (integer)
Undefined composite operator
Gmagick::COMPOSITE_NO (integer)
No composite operator defined
Gmagick::COMPOSITE_ADD (integer)
The result of image + image
Gmagick::COMPOSITE_ATOP (integer)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
Gmagick::COMPOSITE_BLEND (integer)
Blends the image
Gmagick::COMPOSITE_BUMPMAP (integer)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
Gmagick::COMPOSITE_CLEAR (integer)
Makes the target image transparent
Gmagick::COMPOSITE_COLORBURN (integer)
Darkens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORDODGE (integer)
Brightens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORIZE (integer)
Colorizes the target image using the composite image
Gmagick::COMPOSITE_COPYBLACK (integer)
Copies black from the source to target
Gmagick::COMPOSITE_COPYBLUE (integer)
Copies blue from the source to target
Gmagick::COMPOSITE_COPY (integer)
Copies the source image on the target image
Gmagick::COMPOSITE_COPYCYAN (integer)
Copies cyan from the source to target
Gmagick::COMPOSITE_COPYGREEN (integer)
Copies green from the source to target
Gmagick::COMPOSITE_COPYMAGENTA (integer)
Copies magenta from the source to target
Gmagick::COMPOSITE_COPYOPACITY (integer)
Copies opacity from the source to target
Gmagick::COMPOSITE_COPYRED (integer)
Copies red from the source to target
Gmagick::COMPOSITE_COPYYELLOW (integer)
Copies yellow from the source to target
Gmagick::COMPOSITE_DARKEN (integer)
Darkens the target image
Gmagick::COMPOSITE_DSTATOP (integer)
The part of the destination lying inside of the source is composited over the source and replaces the destination
Gmagick::COMPOSITE_DST (integer)
The target is left untouched
Gmagick::COMPOSITE_DSTIN (integer)
The parts inside the source replace the target
Gmagick::COMPOSITE_DSTOUT (integer)
The parts outside the source replace the target
Gmagick::COMPOSITE_DSTOVER (integer)
Target replaces the source
Gmagick::COMPOSITE_DIFFERENCE (integer)
Subtracts the darker of the two constituent colors from the lighter
Gmagick::COMPOSITE_DISPLACE (integer)
Shifts target image pixels as defined by the source
Gmagick::COMPOSITE_DISSOLVE (integer)
Dissolves the source in to the target
Gmagick::COMPOSITE_EXCLUSION (integer)
Produces an effect similar to that of Gmagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
Gmagick::COMPOSITE_HARDLIGHT (integer)
Multiplies or screens the colors, dependent on the source color value
Gmagick::COMPOSITE_HUE (integer)
Modifies the hue of the target as defined by source
Gmagick::COMPOSITE_IN (integer)
Composites source into the target
Gmagick::COMPOSITE_LIGHTEN (integer)
Lightens the target as defined by source
Gmagick::COMPOSITE_LUMINIZE (integer)
Luminizes the target as defined by source
Gmagick::COMPOSITE_MINUS (integer)
Substracts the source from the target
Gmagick::COMPOSITE_MODULATE (integer)
Modulates the target brightness, saturation and hue as defined by source
Gmagick::COMPOSITE_MULTIPLY (integer)
Multiplies the target to the source
Gmagick::COMPOSITE_OUT (integer)
Composites outer parts of the source on the target
Gmagick::COMPOSITE_OVER (integer)
Composites source over the target
Gmagick::COMPOSITE_OVERLAY (integer)
Overlays the source on the target
Gmagick::COMPOSITE_PLUS (integer)
Adds the source to the target
Gmagick::COMPOSITE_REPLACE (integer)
Replaces the target with the source
Gmagick::COMPOSITE_SATURATE (integer)
Saturates the target as defined by the source
Gmagick::COMPOSITE_SCREEN (integer)
The source and destination are complemented and then multiplied and then replace the destination
Gmagick::COMPOSITE_SOFTLIGHT (integer)
Darkens or lightens the colors, dependent on the source
Gmagick::COMPOSITE_SRCATOP (integer)
The part of the source lying inside of the destination is composited onto the destination
Gmagick::COMPOSITE_SRC (integer)
The source is copied to the destination
Gmagick::COMPOSITE_SRCIN (integer)
The part of the source lying inside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOUT (integer)
The part of the source lying outside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOVER (integer)
The source replaces the destination
Gmagick::COMPOSITE_SUBTRACT (integer)
Subtract the colors in the source image from the destination image
Gmagick::COMPOSITE_THRESHOLD (integer)
The source is composited on the target as defined by source threshold
Gmagick::COMPOSITE_XOR (integer)
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source
Montage Mode constants
Gmagick::MONTAGEMODE_FRAME (integer)
Gmagick::MONTAGEMODE_UNFRAME (integer)
Gmagick::MONTAGEMODE_CONCATENATE (integer)
Style constants
Gmagick::STYLE_NORMAL (integer)
Gmagick::STYLE_ITALIC (integer)
Gmagick::STYLE_OBLIQUE (integer)
Gmagick::STYLE_ANY (integer)
Filter constants
Gmagick::FILTER_UNDEFINED (integer)
Gmagick::FILTER_POINT (integer)
Gmagick::FILTER_BOX (integer)
Gmagick::FILTER_TRIANGLE (integer)
Gmagick::FILTER_HERMITE (integer)
Gmagick::FILTER_HANNING (integer)
Gmagick::FILTER_HAMMING (integer)
Gmagick::FILTER_BLACKMAN (integer)
Gmagick::FILTER_GAUSSIAN (integer)
Gmagick::FILTER_QUADRATIC (integer)
Gmagick::FILTER_CUBIC (integer)
Gmagick::FILTER_CATROM (integer)
Gmagick::FILTER_MITCHELL (integer)
Gmagick::FILTER_LANCZOS (integer)
Gmagick::FILTER_BESSEL (integer)
Gmagick::FILTER_SINC (integer)
Image type constants
Gmagick::IMGTYPE_UNDEFINED (integer)
Gmagick::IMGTYPE_BILEVEL (integer)
Gmagick::IMGTYPE_GRAYSCALE (integer)
Gmagick::IMGTYPE_GRAYSCALEMATTE (integer)
Gmagick::IMGTYPE_PALETTE (integer)
Gmagick::IMGTYPE_PALETTEMATTE (integer)
Gmagick::IMGTYPE_TRUECOLOR (integer)
Gmagick::IMGTYPE_TRUECOLORMATTE (integer)
Gmagick::IMGTYPE_COLORSEPARATION (integer)
Gmagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
Gmagick::IMGTYPE_OPTIMIZE (integer)
Resolution constants
Gmagick::RESOLUTION_UNDEFINED (integer)
Gmagick::RESOLUTION_PIXELSPERINCH (integer)
Gmagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
Compression constants
Gmagick::COMPRESSION_UNDEFINED (integer)
Gmagick::COMPRESSION_NO (integer)
Gmagick::COMPRESSION_BZIP (integer)
Gmagick::COMPRESSION_FAX (integer)
Gmagick::COMPRESSION_GROUP4 (integer)
Gmagick::COMPRESSION_JPEG (integer)
Gmagick::COMPRESSION_JPEG2000 (integer)
Gmagick::COMPRESSION_LOSSLESSJPEG (integer)
Gmagick::COMPRESSION_LZW (integer)
Gmagick::COMPRESSION_RLE (integer)
Gmagick::COMPRESSION_ZIP (integer)
Paint constants
Gmagick::PAINT_POINT (integer)
Gmagick::PAINT_REPLACE (integer)
Gmagick::PAINT_FLOODFILL (integer)
Gmagick::PAINT_FILLTOBORDER (integer)
Gmagick::PAINT_RESET (integer)
Gravity constants
Gmagick::GRAVITY_NORTHWEST (integer)
Gmagick::GRAVITY_NORTH (integer)
Gmagick::GRAVITY_NORTHEAST (integer)
Gmagick::GRAVITY_WEST (integer)
Gmagick::GRAVITY_CENTER (integer)
Gmagick::GRAVITY_EAST (integer)
Gmagick::GRAVITY_SOUTHWEST (integer)
Gmagick::GRAVITY_SOUTH (integer)
Gmagick::GRAVITY_SOUTHEAST (integer)
Stretch constants
Gmagick::STRETCH_NORMAL (integer)
Gmagick::STRETCH_ULTRACONDENSED (integer)
Gmagick::STRETCH_CONDENSED (integer)
Gmagick::STRETCH_SEMICONDENSED (integer)
Gmagick::STRETCH_SEMIEXPANDED (integer)
Gmagick::STRETCH_EXPANDED (integer)
Gmagick::STRETCH_EXTRAEXPANDED (integer)
Gmagick::STRETCH_ULTRAEXPANDED (integer)
Gmagick::STRETCH_ANY (integer)
Align constants
Gmagick::ALIGN_UNDEFINED (integer)
Gmagick::ALIGN_LEFT (integer)
Gmagick::ALIGN_CENTER (integer)
Gmagick::ALIGN_RIGHT (integer)
Decoration constants
Gmagick::DECORATION_NO (integer)
Gmagick::DECORATION_UNDERLINE (integer)
Gmagick::DECORATION_OVERLINE (integer)
Gmagick::DECORATION_LINETROUGH (integer)
Noise constants
Gmagick::NOISE_UNIFORM (integer)
Gmagick::NOISE_GAUSSIAN (integer)
Gmagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer)
Gmagick::NOISE_IMPULSE (integer)
Gmagick::NOISE_LAPLACIAN (integer)
Gmagick::NOISE_POISSON (integer)
Channel constants
Gmagick::CHANNEL_UNDEFINED (integer)
Gmagick::CHANNEL_RED (integer)
Gmagick::CHANNEL_GRAY (integer)
Gmagick::CHANNEL_CYAN (integer)
Gmagick::CHANNEL_GREEN (integer)
Gmagick::CHANNEL_MAGENTA (integer)
Gmagick::CHANNEL_BLUE (integer)
Gmagick::CHANNEL_YELLOW (integer)
Gmagick::CHANNEL_ALPHA (integer)
Gmagick::CHANNEL_OPACITY (integer)
Gmagick::CHANNEL_MATTE (integer)
Gmagick::CHANNEL_BLACK (integer)
Gmagick::CHANNEL_INDEX (integer)
Gmagick::CHANNEL_ALL (integer)
Metric constants
Gmagick::METRIC_UNDEFINED (integer)
Gmagick::METRIC_MEANABSOLUTEERROR (integer)
Gmagick::METRIC_MEANSQUAREERROR (integer)
Gmagick::METRIC_PEAKABSOLUTEERROR (integer)
Gmagick::METRIC_PEAKSIGNALTONOISERATIO (integer)
Gmagick::METRIC_ROOTMEANSQUAREDERROR (integer)
Pixel constants
Gmagick::PIXEL_CHAR (integer)
Gmagick::PIXEL_DOUBLE (integer)
Gmagick::PIXEL_FLOAT (integer)
Gmagick::PIXEL_INTEGER (integer)
Gmagick::PIXEL_LONG (integer)
Gmagick::PIXEL_QUANTUM (integer)
Gmagick::PIXEL_SHORT (integer)
Colorspace constants
Gmagick::COLORSPACE_UNDEFINED (integer)
Gmagick::COLORSPACE_RGB (integer)
Gmagick::COLORSPACE_GRAY (integer)
Gmagick::COLORSPACE_TRANSPARENT (integer)
Gmagick::COLORSPACE_OHTA (integer)
Gmagick::COLORSPACE_LAB (integer)
Gmagick::COLORSPACE_XYZ (integer)
Gmagick::COLORSPACE_YCBCR (integer)
Gmagick::COLORSPACE_YCC (integer)
Gmagick::COLORSPACE_YIQ (integer)
Gmagick::COLORSPACE_YPBPR (integer)
Gmagick::COLORSPACE_YUV (integer)
Gmagick::COLORSPACE_CMYK (integer)
Gmagick::COLORSPACE_SRGB (integer)
Gmagick::COLORSPACE_HSB (integer)
Gmagick::COLORSPACE_HSL (integer)
Gmagick::COLORSPACE_HWB (integer)
Gmagick::COLORSPACE_REC601LUMA (integer)
Gmagick::COLORSPACE_REC709LUMA (integer)
Gmagick::COLORSPACE_LOG (integer)
Virtual Pixel Method constants
Gmagick::VIRTUALPIXELMETHOD_UNDEFINED (integer)
Gmagick::VIRTUALPIXELMETHOD_BACKGROUND (integer)
Gmagick::VIRTUALPIXELMETHOD_CONSTANT (integer)
Gmagick::VIRTUALPIXELMETHOD_EDGE (integer)
Gmagick::VIRTUALPIXELMETHOD_MIRROR (integer)
Gmagick::VIRTUALPIXELMETHOD_TILE (integer)
Gmagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer)
Preview constants
Gmagick::PREVIEW_UNDEFINED (integer)
Gmagick::PREVIEW_ROTATE (integer)
Gmagick::PREVIEW_SHEAR (integer)
Gmagick::PREVIEW_ROLL (integer)
Gmagick::PREVIEW_HUE (integer)
Gmagick::PREVIEW_SATURATION (integer)
Gmagick::PREVIEW_BRIGHTNESS (integer)
Gmagick::PREVIEW_GAMMA (integer)
Gmagick::PREVIEW_SPIFF (integer)
Gmagick::PREVIEW_DULL (integer)
Gmagick::PREVIEW_GRAYSCALE (integer)
Gmagick::PREVIEW_QUANTIZE (integer)
Gmagick::PREVIEW_DESPECKLE (integer)
Gmagick::PREVIEW_REDUCENOISE (integer)
Gmagick::PREVIEW_ADDNOISE (integer)
Gmagick::PREVIEW_SHARPEN (integer)
Gmagick::PREVIEW_BLUR (integer)
Gmagick::PREVIEW_THRESHOLD (integer)
Gmagick::PREVIEW_EDGEDETECT (integer)
Gmagick::PREVIEW_SPREAD (integer)
Gmagick::PREVIEW_SOLARIZE (integer)
Gmagick::PREVIEW_SHADE (integer)
Gmagick::PREVIEW_RAISE (integer)
Gmagick::PREVIEW_SEGMENT (integer)
Gmagick::PREVIEW_SWIRL (integer)
Gmagick::PREVIEW_IMPLODE (integer)
Gmagick::PREVIEW_WAVE (integer)
Gmagick::PREVIEW_OILPAINT (integer)
Gmagick::PREVIEW_CHARCOALDRAWING (integer)
Gmagick::PREVIEW_JPEG (integer)
Rendering Intent constants
Gmagick::RENDERINGINTENT_UNDEFINED (integer)
Gmagick::RENDERINGINTENT_SATURATION (integer)
Gmagick::RENDERINGINTENT_PERCEPTUAL (integer)
Gmagick::RENDERINGINTENT_ABSOLUTE (integer)
Gmagick::RENDERINGINTENT_RELATIVE (integer)
Fillrule constants
Gmagick::FILLRULE_UNDEFINED (integer)
Gmagick::FILLRULE_EVENODD (integer)
Gmagick::FILLRULE_NONZERO (integer)
Pathunit constants
Gmagick::PATHUNITS_UNDEFINED (integer)
Gmagick::PATHUNITS_USERSPACE (integer)
Gmagick::PATHUNITS_USERSPACEONUSE (integer)
Gmagick::PATHUNITS_OBJECTBOUNDINGBOX (integer)
Linecap constants
Gmagick::LINECAP_UNDEFINED (integer)
Gmagick::LINECAP_BUTT (integer)
Gmagick::LINECAP_ROUND (integer)
Gmagick::LINECAP_SQUARE (integer)
Line Join constants
Gmagick::LINEJOIN_UNDEFINED (integer)
Gmagick::LINEJOIN_MITER (integer)
Gmagick::LINEJOIN_ROUND (integer)
Gmagick::LINEJOIN_BEVEL (integer)
Resourcetype constants
Gmagick::RESOURCETYPE_UNDEFINED (integer)
Gmagick::RESOURCETYPE_AREA (integer)
Gmagick::RESOURCETYPE_DISK (integer)
Gmagick::RESOURCETYPE_FILE (integer)
Gmagick::RESOURCETYPE_MAP (integer)
Gmagick::RESOURCETYPE_MEMORY (integer)
Orientation constants
Gmagick::ORIENTATION_UNDEFINED (integer)
Gmagick::ORIENTATION_TOPLEFT (integer)
Gmagick::ORIENTATION_TOPRIGHT (integer)
Gmagick::ORIENTATION_BOTTOMRIGHT (integer)
Gmagick::ORIENTATION_BOTTOMLEFT (integer)
Gmagick::ORIENTATION_LEFTTOP (integer)
Gmagick::ORIENTATION_RIGHTTOP (integer)
Gmagick::ORIENTATION_RIGHTBOTTOM (integer)
Gmagick::ORIENTATION_LEFTBOTTOM (integer)
Konfiguracja wykonawcza
Przykłady
Gmagick


Przykłady

The following shows some common Gmagick image operations.

Przykład #1 Gmagick Example

<?php
//Instantiate a new Gmagick object
$image = new Gmagick('example.jpg');

//Make thumbnail from image loaded. 0 for either axes preserves aspect ratio
$image->thumbnailImage(100, 0);

//Create a border around the image, then simulate how the image will look like as an oil painting
//Notice the chaining of mutator methods which is supported in gmagick
$image->borderImage("yellow", 8, 8)->oilPaintImage(0.3);

//Write the current image at the current state to a file
$image->write('example_thumbnail.jpg');
?>
Stałe predefiniowane
Gmagick
Gmagick


The Gmagick class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Gmagick {
/* Metody */
public Gmagick addimage ( Gmagick $Gmagick )
public Gmagick addnoiseimage ( int $NOISE )
public Gmagick annotateimage ( GmagickDraw $GmagickDraw , float $x , float $y , float $angle , string $text )
public Gmagick blurimage ( float $radius , float $sigma [, int $channel ] )
public Gmagick borderimage ( GmagickPixel $color , int $width , int $height )
public Gmagick charcoalimage ( float $radius , float $sigma )
public Gmagick chopimage ( int $width , int $height , int $x , int $y )
public Gmagick clear ( void )
public Gmagick commentimage ( string $comment )
public Gmagick compositeimage ( Gmagick $source , int $COMPOSE , int $x , int $y )
public __construct ([ string $filename ] )
public Gmagick cropimage ( int $width , int $height , int $x , int $y )
public Gmagick cropthumbnailimage ( int $width , int $height )
public Gmagick current ( void )
public Gmagick cyclecolormapimage ( int $displace )
public void deconstructimages ( void )
public Gmagick despeckleimage ( void )
public Gmagick destroy ( void )
public Gmagick drawimage ( GmagickDraw $GmagickDraw )
public Gmagick edgeimage ( float $radius )
public Gmagick embossimage ( float $radius , float $sigma )
public Gmagick enhanceimage ( void )
public Gmagick equalizeimage ( void )
public Gmagick flipimage ( void )
public Gmagick flopimage ( void )
public Gmagick frameimage ( GmagickPixel $color , int $width , int $height , int $inner_bevel , int $outer_bevel )
public Gmagick gammaimage ( float $gamma )
public string getcopyright ( void )
public string getfilename ( void )
public void getimagebackgroundcolor ( void )
public array getimageblueprimary ( void )
public void getimagebordercolor ( void )
public int getimagechanneldepth ( int $channel_type )
public int getimagecolors ( void )
public int getimagecolorspace ( void )
public int getimagecompose ( void )
public int getimagedelay ( void )
public int getimagedepth ( void )
public int getimagedispose ( void )
public array getimageextrema ( void )
public string getimagefilename ( void )
public string getimageformat ( void )
public float getimagegamma ( void )
public array getimagegreenprimary ( void )
public int getimageheight ( void )
public array getimagehistogram ( void )
public int getimageindex ( void )
public int getimageinterlacescheme ( void )
public int getimageiterations ( void )
public int getimagematte ( void )
public void getimagemattecolor ( void )
public string getimageprofile ( string $name )
public array getimageredprimary ( void )
public int getimagerenderingintent ( void )
public array getimageresolution ( void )
public int getimagescene ( void )
public string getimagesignature ( void )
public int getimagetype ( void )
public int getimageunits ( void )
public array getimagewhitepoint ( void )
public int getimagewidth ( void )
public string getpackagename ( void )
public array getquantumdepth ( void )
public string getreleasedate ( void )
public array getsamplingfactors ( void )
public array getsize ( void )
public array getversion ( void )
public mixed hasnextimage ( void )
public mixed haspreviousimage ( void )
public mixed implodeimage ( float $radius )
public mixed labelimage ( string $label )
public mixed levelimage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Gmagick::CHANNEL_DEFAULT ] )
public mixed magnifyimage ( void )
public Gmagick mapimage ( gmagick $gmagick , bool $dither )
public void medianfilterimage ( float $radius )
public void minifyimage ( void )
public void modulateimage ( float $brightness , float $saturation , float $hue )
public void motionblurimage ( float $radius , float $sigma , float $angle )
public void newimage ( int $width , int $height , string $background [, string $format ] )
public bool nextimage ( void )
public void normalizeimage ([ int $channel ] )
public void oilpaintimage ( float $radius )
public bool previousimage ( void )
public void profileimage ( string $name , string $profile )
public void quantizeimage ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )
public void quantizeimages ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )
public array queryfontmetrics ( GmagickDraw $draw , string $text )
public array queryfonts ([ string $pattern = "*" ] )
public array queryformats ([ string $pattern = "*" ] )
public void radialblurimage ( float $angle [, int $channel = Gmagick::CHANNEL_DEFAULT ] )
public void raiseimage ( int $width , int $height , int $x , int $y , bool $raise )
public void read ( string $filename )
public void readimage ( string $filename )
public void readimageblob ( string $imageContents [, string $filename ] )
public void readimagefile ( resource $fp [, string $filename ] )
public void reducenoiseimage ( float $radius )
public void removeimage ( void )
public string removeimageprofile ( string $name )
public void resampleimage ( float $xResolution , float $yResolution , int $filter , float $blur )
public void resizeimage ( int $width , int $height , int $filter , float $blur [, bool $fit = false ] )
public void rollimage ( int $x , int $y )
public Gmagick rotateimage ( mixed $color , float $degrees )
public Gmagick scaleimage ( int $width , int $height [, bool $fit = false ] )
public Gmagick separateimagechannel ( int $channel )
public Gmagick setfilename ( string $filename )
public Gmagick setimagebackgroundcolor ( GmagickPixel $color )
public Gmagick setimageblueprimary ( float $x , float $y )
public Gmagick setimagebordercolor ( GmagickPixel $color )
public Gmagick setimagechanneldepth ( int $channel , int $depth )
public Gmagick setimagecolorspace ( int $colorspace )
public Gmagick setimagecompose ( int $composite )
public Gmagick setimagedelay ( int $delay )
public Gmagick setimagedepth ( int $depth )
public Gmagick setimagedispose ( int $disposeType )
public Gmagick setimagefilename ( string $filename )
public Gmagick setimageformat ( string $imageFormat )
public Gmagick setimagegamma ( float $gamma )
public Gmagick setimagegreenprimary ( float $x , float $y )
public Gmagick setimageindex ( int $index )
public Gmagick setimageinterlacescheme ( int $interlace )
public Gmagick setimageiterations ( int $iterations )
public Gmagick setimageprofile ( string $name , string $profile )
public Gmagick setimageredprimary ( float $x , float $y )
public Gmagick setimagerenderingintent ( int $rendering_intent )
public Gmagick setimageresolution ( float $xResolution , float $yResolution )
public Gmagick setimagescene ( int $scene )
public Gmagick setimagetype ( int $imgType )
public Gmagick setimageunits ( int $resolution )
public Gmagick setimagewhitepoint ( float $x , float $y )
public Gmagick setsamplingfactors ( array $factors )
public Gmagick setsize ( int $columns , int $rows )
public Gmagick shearimage ( mixed $color , float $xShear , float $yShear )
public Gmagick solarizeimage ( int $threshold )
public Gmagick spreadimage ( float $radius )
public Gmagick stripimage ( void )
public Gmagick swirlimage ( float $degrees )
public Gmagick thumbnailimage ( int $width , int $height [, bool $fit = false ] )
public Gmagick trimimage ( float $fuzz )
public void write ( string $filename )
public Gmagick writeimage ( string $filename [, bool $all_frames = false ] )
}

Spis treści

  • Gmagick::addimage — Adds new image to Gmagick object image list
  • Gmagick::addnoiseimage — Adds random noise to the image
  • Gmagick::annotateimage — Annotates an image with text
  • Gmagick::blurimage — Adds blur filter to image
  • Gmagick::borderimage — Surrounds the image with a border
  • Gmagick::charcoalimage — Simulates a charcoal drawing
  • Gmagick::chopimage — Removes a region of an image and trims
  • Gmagick::clear — Clears all resources associated to Gmagick object
  • Gmagick::commentimage — Adds a comment to your image
  • Gmagick::compositeimage — Composite one image onto another
  • Gmagick::__construct — The Gmagick constructor
  • Gmagick::cropimage — Extracts a region of the image
  • Gmagick::cropthumbnailimage — Creates a crop thumbnail
  • Gmagick::current — The current purpose
  • Gmagick::cyclecolormapimage — Displaces an image's colormap
  • Gmagick::deconstructimages — Returns certain pixel differences between images
  • Gmagick::despeckleimage — The despeckleimage purpose
  • Gmagick::destroy — The destroy purpose
  • Gmagick::drawimage — Renders the GmagickDraw object on the current image
  • Gmagick::edgeimage — Enhance edges within the image
  • Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
  • Gmagick::enhanceimage — Improves the quality of a noisy image
  • Gmagick::equalizeimage — Equalizes the image histogram
  • Gmagick::flipimage — Creates a vertical mirror image
  • Gmagick::flopimage — The flopimage purpose
  • Gmagick::frameimage — Adds a simulated three-dimensional border
  • Gmagick::gammaimage — Gamma-corrects an image
  • Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
  • Gmagick::getfilename — The filename associated with an image sequence
  • Gmagick::getimagebackgroundcolor — Returns the image background color
  • Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
  • Gmagick::getimagebordercolor — Returns the image border color
  • Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
  • Gmagick::getimagecolors — Returns the color of the specified colormap index
  • Gmagick::getimagecolorspace — Gets the image colorspace
  • Gmagick::getimagecompose — Returns the composite operator associated with the image
  • Gmagick::getimagedelay — Gets the image delay
  • Gmagick::getimagedepth — Gets the depth of the image
  • Gmagick::getimagedispose — Gets the image disposal method
  • Gmagick::getimageextrema — Gets the extrema for the image
  • Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
  • Gmagick::getimageformat — Returns the format of a particular image in a sequence
  • Gmagick::getimagegamma — Gets the image gamma
  • Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
  • Gmagick::getimageheight — Returns the image height
  • Gmagick::getimagehistogram — Gets the image histogram
  • Gmagick::getimageindex — Gets the index of the current active image
  • Gmagick::getimageinterlacescheme — Gets the image interlace scheme
  • Gmagick::getimageiterations — Gets the image iterations
  • Gmagick::getimagematte — Return if the image has a matte channel
  • Gmagick::getimagemattecolor — Returns the image matte color
  • Gmagick::getimageprofile — Returns the named image profile.
  • Gmagick::getimageredprimary — Returns the chromaticity red primary point
  • Gmagick::getimagerenderingintent — Gets the image rendering intent
  • Gmagick::getimageresolution — Gets the image X and Y resolution
  • Gmagick::getimagescene — Gets the image scene
  • Gmagick::getimagesignature — Generates an SHA-256 message digest
  • Gmagick::getimagetype — Gets the potential image type.
  • Gmagick::getimageunits — Gets the image units of resolution
  • Gmagick::getimagewhitepoint — Returns the chromaticity white point
  • Gmagick::getimagewidth — Returns the width of the image
  • Gmagick::getpackagename — Returns the GraphicsMagick package name.
  • Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.
  • Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.
  • Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.
  • Gmagick::getsize — Returns the size associated with the Gmagick object
  • Gmagick::getversion — Returns the GraphicsMagick API version
  • Gmagick::hasnextimage — Checks if the object has more images
  • Gmagick::haspreviousimage — Checks if the object has a previous image
  • Gmagick::implodeimage — Creates a new image as a copy
  • Gmagick::labelimage — Adds a label to an image.
  • Gmagick::levelimage — Adjusts the levels of an image
  • Gmagick::magnifyimage — Scales an image proportionally 2x
  • Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.
  • Gmagick::medianfilterimage — Applies a digital filter
  • Gmagick::minifyimage — Scales an image proportionally to half its size
  • Gmagick::modulateimage — Control the brightness, saturation, and hue
  • Gmagick::motionblurimage — Simulates motion blur
  • Gmagick::newimage — Creates a new image
  • Gmagick::nextimage — Moves to the next image
  • Gmagick::normalizeimage — Enhances the contrast of a color image
  • Gmagick::oilpaintimage — Simulates an oil painting
  • Gmagick::previousimage — Move to the previous image in the object
  • Gmagick::profileimage — Adds or removes a profile from an image
  • Gmagick::quantizeimage — Analyzes the colors within a reference image
  • Gmagick::quantizeimages — The quantizeimages purpose
  • Gmagick::queryfontmetrics — Returns an array representing the font metrics
  • Gmagick::queryfonts — Returns the configured fonts
  • Gmagick::queryformats — Returns formats supported by Gmagick.
  • Gmagick::radialblurimage — Radial blurs an image
  • Gmagick::raiseimage — Creates a simulated 3d button-like effect
  • Gmagick::read — Reads image from filename
  • Gmagick::readimage — Reads image from filename
  • Gmagick::readimageblob — Reads image from a binary string
  • Gmagick::readimagefile — The readimagefile purpose
  • Gmagick::reducenoiseimage — Smooths the contours of an image
  • Gmagick::removeimage — Removes an image from the image list
  • Gmagick::removeimageprofile — Removes the named image profile and returns it
  • Gmagick::resampleimage — Resample image to desired resolution
  • Gmagick::resizeimage — Scales an image
  • Gmagick::rollimage — Offsets an image
  • Gmagick::rotateimage — Rotates an image
  • Gmagick::scaleimage — Scales the size of an image
  • Gmagick::separateimagechannel — Separates a channel from the image
  • Gmagick::setfilename — Sets the filename before you read or write the image
  • Gmagick::setimagebackgroundcolor — Sets the image background color.
  • Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.
  • Gmagick::setimagebordercolor — Sets the image border color.
  • Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
  • Gmagick::setimagecolorspace — Sets the image colorspace
  • Gmagick::setimagecompose — Sets the image composite operator
  • Gmagick::setimagedelay — Sets the image delay
  • Gmagick::setimagedepth — Sets the image depth
  • Gmagick::setimagedispose — Sets the image disposal method
  • Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
  • Gmagick::setimageformat — Sets the format of a particular image
  • Gmagick::setimagegamma — Sets the image gamma
  • Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.
  • Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
  • Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.
  • Gmagick::setimageiterations — Sets the image iterations.
  • Gmagick::setimageprofile — Adds a named profile to the Gmagick object
  • Gmagick::setimageredprimary — Sets the image chromaticity red primary point.
  • Gmagick::setimagerenderingintent — Sets the image rendering intent
  • Gmagick::setimageresolution — Sets the image resolution
  • Gmagick::setimagescene — Sets the image scene
  • Gmagick::setimagetype — Sets the image type
  • Gmagick::setimageunits — Sets the image units of resolution.
  • Gmagick::setimagewhitepoint — Sets the image chromaticity white point.
  • Gmagick::setsamplingfactors — Sets the image sampling factors.
  • Gmagick::setsize — Sets the size of the Gmagick object
  • Gmagick::shearimage — Creating a parallelogram
  • Gmagick::solarizeimage — Applies a solarizing effect to the image
  • Gmagick::spreadimage — Randomly displaces each pixel in a block
  • Gmagick::stripimage — Strips an image of all profiles and comments
  • Gmagick::swirlimage — Swirls the pixels about the center of the image
  • Gmagick::thumbnailimage — Changes the size of an image
  • Gmagick::trimimage — Remove edges from the image
  • Gmagick::write — Writes an image to the specified filename
  • Gmagick::writeimage — Writes an image to the specified filename
Przykłady
Gmagick::addimage
Gmagick


Adds new image to Gmagick object image list

Gmagick
Gmagick::addnoiseimage
Gmagick
PHP Manual

Gmagick::addimage

(PECL gmagick >= Unknown)

Gmagick::addimage — Adds new image to Gmagick object image list

Opis

public Gmagick Gmagick::addimage ( Gmagick $Gmagick )

Adds new image to Gmagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

Parametry

source

The source Gmagick object

Zwracane wartości

The Gmagick object with image added

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick
Gmagick::addnoiseimage
Gmagick


Adds random noise to the image

Gmagick::addimage
Gmagick::annotateimage
Gmagick
PHP Manual

Gmagick::addnoiseimage

(PECL gmagick >= Unknown)

Gmagick::addnoiseimage — Adds random noise to the image

Opis

public Gmagick Gmagick::addnoiseimage ( int $NOISE )

Adds random noise to the image.

Parametry

noise_type

The type of the noise. Refer to this list of noise constants.

Zwracane wartości

The Gmagick object with noise added.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::addimage
Gmagick::annotateimage
Gmagick


Annotates an image with text

Gmagick::addnoiseimage
Gmagick::blurimage
Gmagick
PHP Manual

Gmagick::annotateimage

(PECL gmagick >= Unknown)

Gmagick::annotateimage — Annotates an image with text

Opis

public Gmagick Gmagick::annotateimage ( GmagickDraw $GmagickDraw , float $x , float $y , float $angle , string $text )

Annotates an image with text.

Parametry

GmagickDraw

The GmagickDraw object that contains settings for drawing the text

x

Horizontal offset in pixels to the left of text

y

Vertical offset in pixels to the baseline of text

angle

The angle at which to write the text

text

The string to draw

Zwracane wartości

The Gmagick object with annotation made.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::addnoiseimage
Gmagick::blurimage
Gmagick


Adds blur filter to image

Gmagick::annotateimage
Gmagick::borderimage
Gmagick
PHP Manual

Gmagick::blurimage

(PECL gmagick >= Unknown)

Gmagick::blurimage — Adds blur filter to image

Opis

public Gmagick Gmagick::blurimage ( float $radius , float $sigma [, int $channel ] )

Adds blur filter to image.

Parametry

radius

Blur radius

sigma

Standard deviation

Zwracane wartości

The blurred Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::annotateimage
Gmagick::borderimage
Gmagick


Surrounds the image with a border

Gmagick::blurimage
Gmagick::charcoalimage
Gmagick
PHP Manual

Gmagick::borderimage

(PECL gmagick >= Unknown)

Gmagick::borderimage — Surrounds the image with a border

Opis

public Gmagick Gmagick::borderimage ( GmagickPixel $color , int $width , int $height )

Surrounds the image with a border of the color defined by the bordercolor GmagickPixel object or a color string.

Parametry

color

GmagickPixel object or a string containing the border color

width

Border width

height

Border height

Zwracane wartości

The Gmagick object with border defined

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::blurimage
Gmagick::charcoalimage
Gmagick


Simulates a charcoal drawing

Gmagick::borderimage
Gmagick::chopimage
Gmagick
PHP Manual

Gmagick::charcoalimage

(PECL gmagick >= Unknown)

Gmagick::charcoalimage — Simulates a charcoal drawing

Opis

public Gmagick Gmagick::charcoalimage ( float $radius , float $sigma )

Simulates a charcoal drawing.

Parametry

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

Zwracane wartości

The Gmagick object with charcoal simulation

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::borderimage
Gmagick::chopimage
Gmagick


Removes a region of an image and trims

Gmagick::charcoalimage
Gmagick::clear
Gmagick
PHP Manual

Gmagick::chopimage

(PECL gmagick >= Unknown)

Gmagick::chopimage — Removes a region of an image and trims

Opis

public Gmagick Gmagick::chopimage ( int $width , int $height , int $x , int $y )

Removes a region of an image and collapses the image to occupy the removed portion.

Parametry

width

Width of the chopped area

height

Height of the chopped area

x

X origo of the chopped area

y

Y origo of the chopped area

Zwracane wartości

The chopped Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::charcoalimage
Gmagick::clear
Gmagick


Clears all resources associated to Gmagick object

Gmagick::chopimage
Gmagick::commentimage
Gmagick
PHP Manual

Gmagick::clear

(PECL gmagick >= Unknown)

Gmagick::clear — Clears all resources associated to Gmagick object

Opis

public Gmagick Gmagick::clear ( void )

Clears all resources associated to Gmagick object

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The cleared Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::chopimage
Gmagick::commentimage
Gmagick


Adds a comment to your image

Gmagick::clear
Gmagick::compositeimage
Gmagick
PHP Manual

Gmagick::commentimage

(PECL gmagick >= Unknown)

Gmagick::commentimage — Adds a comment to your image

Opis

public Gmagick Gmagick::commentimage ( string $comment )

Adds a comment to your image.

Parametry

comment

The comment to add

Zwracane wartości

The Gmagick object with comment added.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::clear
Gmagick::compositeimage
Gmagick


Composite one image onto another

Gmagick::commentimage
Gmagick::__construct
Gmagick
PHP Manual

Gmagick::compositeimage

(PECL gmagick >= Unknown)

Gmagick::compositeimage — Composite one image onto another

Opis

public Gmagick Gmagick::compositeimage ( Gmagick $source , int $COMPOSE , int $x , int $y )

Composite one image onto another at the specified offset.

Parametry

source

Gmagick object which holds the composite image

compose

Composite operator.

x

The column offset of the composited image

y

The row offset of the composited image

Zwracane wartości

The Gmagick object with compositions.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::commentimage
Gmagick::__construct
Gmagick


The Gmagick constructor

Gmagick::compositeimage
Gmagick::cropimage
Gmagick
PHP Manual

Gmagick::__construct

(PECL gmagick >= Unknown)

Gmagick::__construct — The Gmagick constructor

Opis

public Gmagick::__construct ([ string $filename ] )

The Gmagick constructor.

Parametry

filename

The path to an image to load or array of paths

Zwracane wartości

Returns a new Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::compositeimage
Gmagick::cropimage
Gmagick


Extracts a region of the image

Gmagick::__construct
Gmagick::cropthumbnailimage
Gmagick
PHP Manual

Gmagick::cropimage

(PECL gmagick >= Unknown)

Gmagick::cropimage — Extracts a region of the image

Opis

public Gmagick Gmagick::cropimage ( int $width , int $height , int $x , int $y )

Extracts a region of the image.

Parametry

width

The width of the crop

height

The height of the crop

x

The X coordinate of the cropped region's top left corner

y

The Y coordinate of the cropped region's top left corner

Zwracane wartości

The cropped Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::__construct
Gmagick::cropthumbnailimage
Gmagick


Creates a crop thumbnail

Gmagick::cropimage
Gmagick::current
Gmagick
PHP Manual

Gmagick::cropthumbnailimage

(PECL gmagick >= Unknown)

Gmagick::cropthumbnailimage — Creates a crop thumbnail

Opis

public Gmagick Gmagick::cropthumbnailimage ( int $width , int $height )

Creates a fixed size thumbnail by first scaling the image down and cropping a specified area from the center.

Parametry

width

The width of the thumbnail

height

The Height of the thumbnail

Zwracane wartości

The cropped Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::cropimage
Gmagick::current
Gmagick


The current purpose

Gmagick::cropthumbnailimage
Gmagick::cyclecolormapimage
Gmagick
PHP Manual

Gmagick::current

(PECL gmagick >= Unknown)

Gmagick::current — The current purpose

Opis

public Gmagick Gmagick::current ( void )

Returns reference to the current gmagick object with image pointer at the correct sequence.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns self on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::cropthumbnailimage
Gmagick::cyclecolormapimage
Gmagick


Displaces an image's colormap

Gmagick::current
Gmagick::deconstructimages
Gmagick
PHP Manual

Gmagick::cyclecolormapimage

(PECL gmagick >= Unknown)

Gmagick::cyclecolormapimage — Displaces an image's colormap

Opis

public Gmagick Gmagick::cyclecolormapimage ( int $displace )

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

Parametry

displace

The amount to displace the colormap.

Zwracane wartości

Returns self on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::current
Gmagick::deconstructimages
Gmagick


Returns certain pixel differences between images

Gmagick::cyclecolormapimage
Gmagick::despeckleimage
Gmagick
PHP Manual

Gmagick::deconstructimages

(PECL gmagick >= Unknown)

Gmagick::deconstructimages — Returns certain pixel differences between images

Opis

public void Gmagick::deconstructimages ( void )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns self on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::cyclecolormapimage
Gmagick::despeckleimage
Gmagick


The despeckleimage purpose

Gmagick::deconstructimages
Gmagick::destroy
Gmagick
PHP Manual

Gmagick::despeckleimage

(PECL gmagick >= Unknown)

Gmagick::despeckleimage — The despeckleimage purpose

Opis

public Gmagick Gmagick::despeckleimage ( void )

Reduces the speckle noise in an image while preserving the edges of the original image.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The despeckled Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Przykłady

Przykład #1 Gmagick::despeckleimage() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

Gmagick::deconstructimages
Gmagick::destroy
Gmagick


The destroy purpose

Gmagick::despeckleimage
Gmagick::drawimage
Gmagick
PHP Manual

Gmagick::destroy

(PECL gmagick >= Unknown)

Gmagick::destroy — The destroy purpose

Opis

public Gmagick Gmagick::destroy ( void )

Destroys the Gmagick object and frees all resources associated with it

Zwracane wartości

Zwraca TRUE w przypadku powodzenia.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::despeckleimage
Gmagick::drawimage
Gmagick


Renders the GmagickDraw object on the current image

Gmagick::destroy
Gmagick::edgeimage
Gmagick
PHP Manual

Gmagick::drawimage

(PECL gmagick >= Unknown)

Gmagick::drawimage — Renders the GmagickDraw object on the current image

Opis

public Gmagick Gmagick::drawimage ( GmagickDraw $GmagickDraw )

Renders the GmagickDraw object on the current image

Parametry

GmagickDraw

The drawing operations to render on the image.

Zwracane wartości

The drawn Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::destroy
Gmagick::edgeimage
Gmagick


Enhance edges within the image

Gmagick::drawimage
Gmagick::embossimage
Gmagick
PHP Manual

Gmagick::edgeimage

(PECL gmagick >= Unknown)

Gmagick::edgeimage — Enhance edges within the image

Opis

public Gmagick Gmagick::edgeimage ( float $radius )

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

Parametry

radius

The radius of the operation.

Zwracane wartości

The Gmagick object with edges enhanced.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::drawimage
Gmagick::embossimage
Gmagick


Returns a grayscale image with a three-dimensional effect

Gmagick::edgeimage
Gmagick::enhanceimage
Gmagick
PHP Manual

Gmagick::embossimage

(PECL gmagick >= Unknown)

Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect

Opis

public Gmagick Gmagick::embossimage ( float $radius , float $sigma )

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

Parametry

radius

The radius of the effect

sigma

The sigma of the effect

Zwracane wartości

The embossed Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::edgeimage
Gmagick::enhanceimage
Gmagick


Improves the quality of a noisy image

Gmagick::embossimage
Gmagick::equalizeimage
Gmagick
PHP Manual

Gmagick::enhanceimage

(PECL gmagick >= Unknown)

Gmagick::enhanceimage — Improves the quality of a noisy image

Opis

public Gmagick Gmagick::enhanceimage ( void )

Applies a digital filter that improves the quality of a noisy image.

Zwracane wartości

The enhanced Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::embossimage
Gmagick::equalizeimage
Gmagick


Equalizes the image histogram

Gmagick::enhanceimage
Gmagick::flipimage
Gmagick
PHP Manual

Gmagick::equalizeimage

(PECL gmagick >= Unknown)

Gmagick::equalizeimage — Equalizes the image histogram

Opis

public Gmagick Gmagick::equalizeimage ( void )

Equalizes the image histogram.

Zwracane wartości

The equalized Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::enhanceimage
Gmagick::flipimage
Gmagick


Creates a vertical mirror image

Gmagick::equalizeimage
Gmagick::flopimage
Gmagick
PHP Manual

Gmagick::flipimage

(PECL gmagick >= Unknown)

Gmagick::flipimage — Creates a vertical mirror image

Opis

public Gmagick Gmagick::flipimage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Zwracane wartości

The flipped Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::equalizeimage
Gmagick::flopimage
Gmagick


The flopimage purpose

Gmagick::flipimage
Gmagick::frameimage
Gmagick
PHP Manual

Gmagick::flopimage

(PECL gmagick >= Unknown)

Gmagick::flopimage — The flopimage purpose

Opis

public Gmagick Gmagick::flopimage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Zwracane wartości

The flopped Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::flipimage
Gmagick::frameimage
Gmagick


Adds a simulated three-dimensional border

Gmagick::flopimage
Gmagick::gammaimage
Gmagick
PHP Manual

Gmagick::frameimage

(PECL gmagick >= Unknown)

Gmagick::frameimage — Adds a simulated three-dimensional border

Opis

public Gmagick Gmagick::frameimage ( GmagickPixel $color , int $width , int $height , int $inner_bevel , int $outer_bevel )

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

Parametry

color

GmagickPixel object or a float representing the matte color

width

The width of the border

height

The height of the border

inner_bevel

The inner bevel width

outer_bevel

The outer bevel width

Zwracane wartości

The framed Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::flopimage
Gmagick::gammaimage
Gmagick


Gamma-corrects an image

Gmagick::frameimage
Gmagick::getcopyright
Gmagick
PHP Manual

Gmagick::gammaimage

(PECL gmagick >= Unknown)

Gmagick::gammaimage — Gamma-corrects an image

Opis

public Gmagick Gmagick::gammaimage ( float $gamma )

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

Parametry

gamma

The amount of gamma-correction.

Zwracane wartości

The gamma corrected Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::frameimage
Gmagick::getcopyright
Gmagick


Returns the GraphicsMagick API copyright as a string

Gmagick::gammaimage
Gmagick::getfilename
Gmagick
PHP Manual

Gmagick::getcopyright

(PECL gmagick >= Unknown)

Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string

Opis

public string Gmagick::getcopyright ( void )

Returns the GraphicsMagick API copyright as a string.

Zwracane wartości

Returns a string containing the copyright notice of GraphicsMagick and Magickwand C API.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::gammaimage
Gmagick::getfilename
Gmagick


The filename associated with an image sequence

Gmagick::getcopyright
Gmagick::getimagebackgroundcolor
Gmagick
PHP Manual

Gmagick::getfilename

(PECL gmagick >= Unknown)

Gmagick::getfilename — The filename associated with an image sequence

Opis

public string Gmagick::getfilename ( void )

Returns the filename associated with an image sequence.

Zwracane wartości

Returns a string on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getcopyright
Gmagick::getimagebackgroundcolor
Gmagick


Returns the image background color

Gmagick::getfilename
Gmagick::getimageblueprimary
Gmagick
PHP Manual

Gmagick::getimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::getimagebackgroundcolor — Returns the image background color

Opis

public void Gmagick::getimagebackgroundcolor ( void )

Returns the image background color.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an GmagickPixel set to the background color of the image.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getfilename
Gmagick::getimageblueprimary
Gmagick


Returns the chromaticy blue primary point

Gmagick::getimagebackgroundcolor
Gmagick::getimagebordercolor
Gmagick
PHP Manual

Gmagick::getimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::getimageblueprimary — Returns the chromaticy blue primary point

Opis

public array Gmagick::getimageblueprimary ( void )

Returns the chromaticity blue primary point for the image.

Parametry

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

Zwracane wartości

Array consisting of "x" and "y" coordinates of point.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagebackgroundcolor
Gmagick::getimagebordercolor
Gmagick


Returns the image border color

Gmagick::getimageblueprimary
Gmagick::getimagechanneldepth
Gmagick
PHP Manual

Gmagick::getimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::getimagebordercolor — Returns the image border color

Opis

public void Gmagick::getimagebordercolor ( void )

Returns the image border color.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

GmagickPixel object representing the color of the border

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageblueprimary
Gmagick::getimagechanneldepth
Gmagick


Gets the depth for a particular image channel

Gmagick::getimagebordercolor
Gmagick::getimagecolors
Gmagick
PHP Manual

Gmagick::getimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::getimagechanneldepth — Gets the depth for a particular image channel

Opis

public int Gmagick::getimagechanneldepth ( int $channel_type )

Gets the depth for a particular image channel.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Depth of image channel

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagebordercolor
Gmagick::getimagecolors
Gmagick


Returns the color of the specified colormap index

Gmagick::getimagechanneldepth
Gmagick::getimagecolorspace
Gmagick
PHP Manual

Gmagick::getimagecolors

(PECL gmagick >= Unknown)

Gmagick::getimagecolors — Returns the color of the specified colormap index

Opis

public int Gmagick::getimagecolors ( void )

Returns the color of the specified colormap index.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The number of colors in image.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagechanneldepth
Gmagick::getimagecolorspace
Gmagick


Gets the image colorspace

Gmagick::getimagecolors
Gmagick::getimagecompose
Gmagick
PHP Manual

Gmagick::getimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::getimagecolorspace — Gets the image colorspace

Opis

public int Gmagick::getimagecolorspace ( void )

Gets the image colorspace.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Colorspace

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagecolors
Gmagick::getimagecompose
Gmagick


Returns the composite operator associated with the image

Gmagick::getimagecolorspace
Gmagick::getimagedelay
Gmagick
PHP Manual

Gmagick::getimagecompose

(PECL gmagick >= Unknown)

Gmagick::getimagecompose — Returns the composite operator associated with the image

Opis

public int Gmagick::getimagecompose ( void )

Returns the composite operator associated with the image.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the composite operator associated with the image.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagecolorspace
Gmagick::getimagedelay
Gmagick


Gets the image delay

Gmagick::getimagecompose
Gmagick::getimagedepth
Gmagick
PHP Manual

Gmagick::getimagedelay

(PECL gmagick >= Unknown)

Gmagick::getimagedelay — Gets the image delay

Opis

public int Gmagick::getimagedelay ( void )

Gets the image delay

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the composite operator associated with the image.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagecompose
Gmagick::getimagedepth
Gmagick


Gets the depth of the image

Gmagick::getimagedelay
Gmagick::getimagedispose
Gmagick
PHP Manual

Gmagick::getimagedepth

(PECL gmagick >= Unknown)

Gmagick::getimagedepth — Gets the depth of the image

Opis

public int Gmagick::getimagedepth ( void )

Gets the depth of the image.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Image depth

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagedelay
Gmagick::getimagedispose
Gmagick


Gets the image disposal method

Gmagick::getimagedepth
Gmagick::getimageextrema
Gmagick
PHP Manual

Gmagick::getimagedispose

(PECL gmagick >= Unknown)

Gmagick::getimagedispose — Gets the image disposal method

Opis

public int Gmagick::getimagedispose ( void )

Gets the image disposal method

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the dispose method on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagedepth
Gmagick::getimageextrema
Gmagick


Gets the extrema for the image

Gmagick::getimagedispose
Gmagick::getimagefilename
Gmagick
PHP Manual

Gmagick::getimageextrema

(PECL gmagick >= Unknown)

Gmagick::getimageextrema — Gets the extrema for the image

Opis

public array Gmagick::getimageextrema ( void )

Returns an associative array with the keys "min" and "max". Wywołuje wyjątek GmagickException w przypadku błędu.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an associative array with the keys "min" and "max".

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagedispose
Gmagick::getimagefilename
Gmagick


Returns the filename of a particular image in a sequence

Gmagick::getimageextrema
Gmagick::getimageformat
Gmagick
PHP Manual

Gmagick::getimagefilename

(PECL gmagick >= Unknown)

Gmagick::getimagefilename — Returns the filename of a particular image in a sequence

Opis

public string Gmagick::getimagefilename ( void )

Returns the filename of a particular image in a sequence

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string with the filename of the image

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageextrema
Gmagick::getimageformat
Gmagick


Returns the format of a particular image in a sequence

Gmagick::getimagefilename
Gmagick::getimagegamma
Gmagick
PHP Manual

Gmagick::getimageformat

(PECL gmagick >= Unknown)

Gmagick::getimageformat — Returns the format of a particular image in a sequence

Opis

public string Gmagick::getimageformat ( void )

Returns the format of a particular image in a sequence.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string containing the image format on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagefilename
Gmagick::getimagegamma
Gmagick


Gets the image gamma

Gmagick::getimageformat
Gmagick::getimagegreenprimary
Gmagick
PHP Manual

Gmagick::getimagegamma

(PECL gmagick >= Unknown)

Gmagick::getimagegamma — Gets the image gamma

Opis

public float Gmagick::getimagegamma ( void )

Gets the image gamma

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the image gamma on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageformat
Gmagick::getimagegreenprimary
Gmagick


Returns the chromaticy green primary point

Gmagick::getimagegamma
Gmagick::getimageheight
Gmagick
PHP Manual

Gmagick::getimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::getimagegreenprimary — Returns the chromaticy green primary point

Opis

public array Gmagick::getimagegreenprimary ( void )

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array with the keys "x" and "y" on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagegamma
Gmagick::getimageheight
Gmagick


Returns the image height

Gmagick::getimagegreenprimary
Gmagick::getimagehistogram
Gmagick
PHP Manual

Gmagick::getimageheight

(PECL gmagick >= Unknown)

Gmagick::getimageheight — Returns the image height

Opis

public int Gmagick::getimageheight ( void )

Returns the image height

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the image height in pixels.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagegreenprimary
Gmagick::getimagehistogram
Gmagick


Gets the image histogram

Gmagick::getimageheight
Gmagick::getimageindex
Gmagick
PHP Manual

Gmagick::getimagehistogram

(PECL gmagick >= Unknown)

Gmagick::getimagehistogram — Gets the image histogram

Opis

public array Gmagick::getimagehistogram ( void )

Returns the image histogram as an array of GmagickPixel objects. Throw an GmagickException on error.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the image histogram as an array of GmagickPixel objects.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageheight
Gmagick::getimageindex
Gmagick


Gets the index of the current active image

Gmagick::getimagehistogram
Gmagick::getimageinterlacescheme
Gmagick
PHP Manual

Gmagick::getimageindex

(PECL gmagick >= Unknown)

Gmagick::getimageindex — Gets the index of the current active image

Opis

public int Gmagick::getimageindex ( void )

Returns the index of the current active image within the Gmagick object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Index of current active image

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagehistogram
Gmagick::getimageinterlacescheme
Gmagick


Gets the image interlace scheme

Gmagick::getimageindex
Gmagick::getimageiterations
Gmagick
PHP Manual

Gmagick::getimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::getimageinterlacescheme — Gets the image interlace scheme

Opis

public int Gmagick::getimageinterlacescheme ( void )

Gets the image interlace scheme.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the interlace scheme as an integer on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageindex
Gmagick::getimageiterations
Gmagick


Gets the image iterations

Gmagick::getimageinterlacescheme
Gmagick::getimagematte
Gmagick
PHP Manual

Gmagick::getimageiterations

(PECL gmagick >= Unknown)

Gmagick::getimageiterations — Gets the image iterations

Opis

public int Gmagick::getimageiterations ( void )

Gets the image iterations.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the image iterations as an integer.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageinterlacescheme
Gmagick::getimagematte
Gmagick


Return if the image has a matte channel

Gmagick::getimageiterations
Gmagick::getimagemattecolor
Gmagick
PHP Manual

Gmagick::getimagematte

(PECL gmagick >= Unknown)

Gmagick::getimagematte — Return if the image has a matte channel

Opis

public int Gmagick::getimagematte ( void )

Returns TRUE if the image has a matte channel otherwise false.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the image has a matte channel otherwise false.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageiterations
Gmagick::getimagemattecolor
Gmagick


Returns the image matte color

Gmagick::getimagematte
Gmagick::getimageprofile
Gmagick
PHP Manual

Gmagick::getimagemattecolor

(PECL gmagick >= Unknown)

Gmagick::getimagemattecolor — Returns the image matte color

Opis

public void Gmagick::getimagemattecolor ( void )

Returns GmagickPixel object on success. Throw an GmagickException on error.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns GmagickPixel object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagematte
Gmagick::getimageprofile
Gmagick


Returns the named image profile.

Gmagick::getimagemattecolor
Gmagick::getimageredprimary
Gmagick
PHP Manual

Gmagick::getimageprofile

(PECL gmagick >= Unknown)

Gmagick::getimageprofile — Returns the named image profile.

Opis

public string Gmagick::getimageprofile ( string $name )

Returns the named image profile.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string containing the image profile.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagemattecolor
Gmagick::getimageredprimary
Gmagick


Returns the chromaticity red primary point

Gmagick::getimageprofile
Gmagick::getimagerenderingintent
Gmagick
PHP Manual

Gmagick::getimageredprimary

(PECL gmagick >= Unknown)

Gmagick::getimageredprimary — Returns the chromaticity red primary point

Opis

public array Gmagick::getimageredprimary ( void )

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageprofile
Gmagick::getimagerenderingintent
Gmagick


Gets the image rendering intent

Gmagick::getimageredprimary
Gmagick::getimageresolution
Gmagick
PHP Manual

Gmagick::getimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::getimagerenderingintent — Gets the image rendering intent

Opis

public int Gmagick::getimagerenderingintent ( void )

Gets the image rendering intent

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Extracts a region of the image and returns it as a a new wand

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageredprimary
Gmagick::getimageresolution
Gmagick


Gets the image X and Y resolution

Gmagick::getimagerenderingintent
Gmagick::getimagescene
Gmagick
PHP Manual

Gmagick::getimageresolution

(PECL gmagick >= Unknown)

Gmagick::getimageresolution — Gets the image X and Y resolution

Opis

public array Gmagick::getimageresolution ( void )

Returns the resolution as an array.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the resolution as an array.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagerenderingintent
Gmagick::getimagescene
Gmagick


Gets the image scene

Gmagick::getimageresolution
Gmagick::getimagesignature
Gmagick
PHP Manual

Gmagick::getimagescene

(PECL gmagick >= Unknown)

Gmagick::getimagescene — Gets the image scene

Opis

public int Gmagick::getimagescene ( void )

Gets the image scene.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the image scene.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageresolution
Gmagick::getimagesignature
Gmagick


Generates an SHA-256 message digest

Gmagick::getimagescene
Gmagick::getimagetype
Gmagick
PHP Manual

Gmagick::getimagesignature

(PECL gmagick >= Unknown)

Gmagick::getimagesignature — Generates an SHA-256 message digest

Opis

public string Gmagick::getimagesignature ( void )

Generates an SHA-256 message digest for the image pixel stream.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string containing the SHA-256 hash of the file.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagescene
Gmagick::getimagetype
Gmagick


Gets the potential image type.

Gmagick::getimagesignature
Gmagick::getimageunits
Gmagick
PHP Manual

Gmagick::getimagetype

(PECL gmagick >= Unknown)

Gmagick::getimagetype — Gets the potential image type.

Opis

public int Gmagick::getimagetype ( void )

Gets the potential image type.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the potential image type.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagesignature
Gmagick::getimageunits
Gmagick


Gets the image units of resolution

Gmagick::getimagetype
Gmagick::getimagewhitepoint
Gmagick
PHP Manual

Gmagick::getimageunits

(PECL gmagick >= Unknown)

Gmagick::getimageunits — Gets the image units of resolution

Opis

public int Gmagick::getimageunits ( void )

Gets the image units of resolution.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the image units of resolution.

Gmagick::getimagetype
Gmagick::getimagewhitepoint
Gmagick


Returns the chromaticity white point

Gmagick::getimageunits
Gmagick::getimagewidth
Gmagick
PHP Manual

Gmagick::getimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::getimagewhitepoint — Returns the chromaticity white point

Opis

public array Gmagick::getimagewhitepoint ( void )

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimageunits
Gmagick::getimagewidth
Gmagick


Returns the width of the image

Gmagick::getimagewhitepoint
Gmagick::getpackagename
Gmagick
PHP Manual

Gmagick::getimagewidth

(PECL gmagick >= Unknown)

Gmagick::getimagewidth — Returns the width of the image

Opis

public int Gmagick::getimagewidth ( void )

Returns the width of the image.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the image width.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagewhitepoint
Gmagick::getpackagename
Gmagick


Returns the GraphicsMagick package name.

Gmagick::getimagewidth
Gmagick::getquantumdepth
Gmagick
PHP Manual

Gmagick::getpackagename

(PECL gmagick >= Unknown)

Gmagick::getpackagename — Returns the GraphicsMagick package name.

Opis

public string Gmagick::getpackagename ( void )

Returns the GraphicsMagick package name.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the GraphicsMagick package name as a string.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getimagewidth
Gmagick::getquantumdepth
Gmagick


Returns the Gmagick quantum depth as a string.

Gmagick::getpackagename
Gmagick::getreleasedate
Gmagick
PHP Manual

Gmagick::getquantumdepth

(PECL gmagick >= Unknown)

Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string.

Opis

public array Gmagick::getquantumdepth ( void )

Returns the Gmagick quantum depth as a string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the Gmagick quantum depth as a string.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getpackagename
Gmagick::getreleasedate
Gmagick


Returns the GraphicsMagick release date as a string.

Gmagick::getquantumdepth
Gmagick::getsamplingfactors
Gmagick
PHP Manual

Gmagick::getreleasedate

(PECL gmagick >= Unknown)

Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string.

Opis

public string Gmagick::getreleasedate ( void )

Returns the GraphicsMagick release date as a string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the GraphicsMagick release date as a string.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getquantumdepth
Gmagick::getsamplingfactors
Gmagick


Gets the horizontal and vertical sampling factor.

Gmagick::getreleasedate
Gmagick::getsize
Gmagick
PHP Manual

Gmagick::getsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor.

Opis

public array Gmagick::getsamplingfactors ( void )

Gets the horizontal and vertical sampling factor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an associative array with the horizontal and vertical sampling factors of the image.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getreleasedate
Gmagick::getsize
Gmagick


Returns the size associated with the Gmagick object

Gmagick::getsamplingfactors
Gmagick::getversion
Gmagick
PHP Manual

Gmagick::getsize

(PECL gmagick >= Unknown)

Gmagick::getsize — Returns the size associated with the Gmagick object

Opis

public array Gmagick::getsize ( void )

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getsamplingfactors
Gmagick::getversion
Gmagick


Returns the GraphicsMagick API version

Gmagick::getsize
Gmagick::hasnextimage
Gmagick
PHP Manual

Gmagick::getversion

(PECL gmagick >= Unknown)

Gmagick::getversion — Returns the GraphicsMagick API version

Opis

public array Gmagick::getversion ( void )

Returns the GraphicsMagick API version as a string and as a number.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the GraphicsMagick API version as a string and as a number.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getsize
Gmagick::hasnextimage
Gmagick


Checks if the object has more images

Gmagick::getversion
Gmagick::haspreviousimage
Gmagick
PHP Manual

Gmagick::hasnextimage

(PECL gmagick >= Unknown)

Gmagick::hasnextimage — Checks if the object has more images

Opis

public mixed Gmagick::hasnextimage ( void )

Returns TRUE if the object has more images when traversing the list in the forward direction.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the object has more images when traversing the list in the forward direction, returns FALSE if there are none.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::getversion
Gmagick::haspreviousimage
Gmagick


Checks if the object has a previous image

Gmagick::hasnextimage
Gmagick::implodeimage
Gmagick
PHP Manual

Gmagick::haspreviousimage

(PECL gmagick >= Unknown)

Gmagick::haspreviousimage — Checks if the object has a previous image

Opis

public mixed Gmagick::haspreviousimage ( void )

Returns TRUE if the object has more images when traversing the list in the reverse direction

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the object has more images when traversing the list in the reverse direction, returns FALSE if there are none.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::hasnextimage
Gmagick::implodeimage
Gmagick


Creates a new image as a copy

Gmagick::haspreviousimage
Gmagick::labelimage
Gmagick
PHP Manual

Gmagick::implodeimage

(PECL gmagick >= Unknown)

Gmagick::implodeimage — Creates a new image as a copy

Opis

public mixed Gmagick::implodeimage ( float $radius )

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

Parametry

radius

The radius of the implode

Zwracane wartości

Returns imploded Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::haspreviousimage
Gmagick::labelimage
Gmagick


Adds a label to an image.

Gmagick::implodeimage
Gmagick::levelimage
Gmagick
PHP Manual

Gmagick::labelimage

(PECL gmagick >= Unknown)

Gmagick::labelimage — Adds a label to an image.

Opis

public mixed Gmagick::labelimage ( string $label )

Adds a label to an image.

Parametry

label

The label to add

Zwracane wartości

Gmagick with label.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::implodeimage
Gmagick::levelimage
Gmagick


Adjusts the levels of an image

Gmagick::labelimage
Gmagick::magnifyimage
Gmagick
PHP Manual

Gmagick::levelimage

(PECL gmagick >= Unknown)

Gmagick::levelimage — Adjusts the levels of an image

Opis

public mixed Gmagick::levelimage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Gmagick::CHANNEL_DEFAULT ] )

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

Parametry

blackPoint

The image black point

gamma

The gamma value

whitePoint

The image white point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Gmagick object with image levelled.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::labelimage
Gmagick::magnifyimage
Gmagick


Scales an image proportionally 2x

Gmagick::levelimage
Gmagick::mapimage
Gmagick
PHP Manual

Gmagick::magnifyimage

(PECL gmagick >= Unknown)

Gmagick::magnifyimage — Scales an image proportionally 2x

Opis

public mixed Gmagick::magnifyimage ( void )

Conveniently scales an image proportionally to twice its original size.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Magnified Gmagick object.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::levelimage
Gmagick::mapimage
Gmagick


Replaces the colors of an image with the closest color from a reference image.

Gmagick::magnifyimage
Gmagick::medianfilterimage
Gmagick
PHP Manual

Gmagick::mapimage

(PECL gmagick >= Unknown)

Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image.

Opis

public Gmagick Gmagick::mapimage ( gmagick $gmagick , bool $dither )

Replaces the colors of an image with the closest color from a reference image.

Parametry

gmagick

The reference image

dither

Set this integer value to something other than zero to dither the mapped image

Zwracane wartości

Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::magnifyimage
Gmagick::medianfilterimage
Gmagick


Applies a digital filter

Gmagick::mapimage
Gmagick::minifyimage
Gmagick
PHP Manual

Gmagick::medianfilterimage

(PECL gmagick >= Unknown)

Gmagick::medianfilterimage — Applies a digital filter

Opis

public void Gmagick::medianfilterimage ( float $radius )

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

Parametry

radius

The radius of the pixel neighborhood.

Zwracane wartości

Gmagick object with median filter applied.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::mapimage
Gmagick::minifyimage
Gmagick


Scales an image proportionally to half its size

Gmagick::medianfilterimage
Gmagick::modulateimage
Gmagick
PHP Manual

Gmagick::minifyimage

(PECL gmagick >= Unknown)

Gmagick::minifyimage — Scales an image proportionally to half its size

Opis

public void Gmagick::minifyimage ( void )

A convenient method that scales an image proportionally to one-half its original size

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::medianfilterimage
Gmagick::modulateimage
Gmagick


Control the brightness, saturation, and hue

Gmagick::minifyimage
Gmagick::motionblurimage
Gmagick
PHP Manual

Gmagick::modulateimage

(PECL gmagick >= Unknown)

Gmagick::modulateimage — Control the brightness, saturation, and hue

Opis

public void Gmagick::modulateimage ( float $brightness , float $saturation , float $hue )

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

Parametry

brightness

The percent change in brighness (-100 thru +100).

saturation

The percent change in saturation (-100 thru +100)

hue

The percent change in hue (-100 thru +100)

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::minifyimage
Gmagick::motionblurimage
Gmagick


Simulates motion blur

Gmagick::modulateimage
Gmagick::newimage
Gmagick
PHP Manual

Gmagick::motionblurimage

(PECL gmagick >= Unknown)

Gmagick::motionblurimage — Simulates motion blur

Opis

public void Gmagick::motionblurimage ( float $radius , float $sigma , float $angle )

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

Parametry

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::modulateimage
Gmagick::newimage
Gmagick


Creates a new image

Gmagick::motionblurimage
Gmagick::nextimage
Gmagick
PHP Manual

Gmagick::newimage

(PECL gmagick >= Unknown)

Gmagick::newimage — Creates a new image

Opis

public void Gmagick::newimage ( int $width , int $height , string $background [, string $format ] )

Creates a new image with the specified background color

Parametry

width

Width of the new image

height

Height of the new image

background

The background color used for this image (as float)

format

Image format.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::motionblurimage
Gmagick::nextimage
Gmagick


Moves to the next image

Gmagick::newimage
Gmagick::normalizeimage
Gmagick
PHP Manual

Gmagick::nextimage

(PECL gmagick >= Unknown)

Gmagick::nextimage — Moves to the next image

Opis

public bool Gmagick::nextimage ( void )

Associates the next image in the image list with an Gmagick object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::newimage
Gmagick::normalizeimage
Gmagick


Enhances the contrast of a color image

Gmagick::nextimage
Gmagick::oilpaintimage
Gmagick
PHP Manual

Gmagick::normalizeimage

(PECL gmagick >= Unknown)

Gmagick::normalizeimage — Enhances the contrast of a color image

Opis

public void Gmagick::normalizeimage ([ int $channel ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

Parametry

channel

Identify which channel to normalize

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::nextimage
Gmagick::oilpaintimage
Gmagick


Simulates an oil painting

Gmagick::normalizeimage
Gmagick::previousimage
Gmagick
PHP Manual

Gmagick::oilpaintimage

(PECL gmagick >= Unknown)

Gmagick::oilpaintimage — Simulates an oil painting

Opis

public void Gmagick::oilpaintimage ( float $radius )

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

Parametry

radius

The radius of the circular neighborhood.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::normalizeimage
Gmagick::previousimage
Gmagick


Move to the previous image in the object

Gmagick::oilpaintimage
Gmagick::profileimage
Gmagick
PHP Manual

Gmagick::previousimage

(PECL gmagick >= Unknown)

Gmagick::previousimage — Move to the previous image in the object

Opis

public bool Gmagick::previousimage ( void )

Assocates the previous image in an image list with the Gmagick object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::oilpaintimage
Gmagick::profileimage
Gmagick


Adds or removes a profile from an image

Gmagick::previousimage
Gmagick::quantizeimage
Gmagick
PHP Manual

Gmagick::profileimage

(PECL gmagick >= Unknown)

Gmagick::profileimage — Adds or removes a profile from an image

Opis

public void Gmagick::profileimage ( string $name , string $profile )

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.

Parametry

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::previousimage
Gmagick::quantizeimage
Gmagick


Analyzes the colors within a reference image

Gmagick::profileimage
Gmagick::quantizeimages
Gmagick
PHP Manual

Gmagick::quantizeimage

(PECL gmagick >= Unknown)

Gmagick::quantizeimage — Analyzes the colors within a reference image

Opis

public void Gmagick::quantizeimage ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )

Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

Parametry

numColors

The number of colors.

colorspace

Perform color reduction in this colorspace, typically RGBColorspace.

treeDepth

Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.

dither

A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.

measureError

A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::profileimage
Gmagick::quantizeimages
Gmagick


The quantizeimages purpose

Gmagick::quantizeimage
Gmagick::queryfontmetrics
Gmagick
PHP Manual

Gmagick::quantizeimages

(PECL gmagick >= Unknown)

Gmagick::quantizeimages — The quantizeimages purpose

Opis

public void Gmagick::quantizeimages ( int $numColors , int $colorspace , int $treeDepth , bool $dither , bool $measureError )

Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

Parametry

numColors

The number of colors.

colorspace

Perform color reduction in this colorspace, typically RGBColorspace.

treeDepth

Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.

dither

A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.

measureError

A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::quantizeimage
Gmagick::queryfontmetrics
Gmagick


Returns an array representing the font metrics

Gmagick::quantizeimages
Gmagick::queryfonts
Gmagick
PHP Manual

Gmagick::queryfontmetrics

(PECL gmagick >= Unknown)

Gmagick::queryfontmetrics — Returns an array representing the font metrics

Opis

public array Gmagick::queryfontmetrics ( GmagickDraw $draw , string $text )

MagickQueryFontMetrics() returns an array representing the font metrics.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::quantizeimages
Gmagick::queryfonts
Gmagick


Returns the configured fonts

Gmagick::queryfontmetrics
Gmagick::queryformats
Gmagick
PHP Manual

Gmagick::queryfonts

(PECL gmagick >= Unknown)

Gmagick::queryfonts — Returns the configured fonts

Opis

public array Gmagick::queryfonts ([ string $pattern = "*" ] )

Returns fonts supported by Gmagick.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::queryfontmetrics
Gmagick::queryformats
Gmagick


Returns formats supported by Gmagick.

Gmagick::queryfonts
Gmagick::radialblurimage
Gmagick
PHP Manual

Gmagick::queryformats

(PECL gmagick >= Unknown)

Gmagick::queryformats — Returns formats supported by Gmagick.

Opis

public array Gmagick::queryformats ([ string $pattern = "*" ] )

Returns formats supported by Gmagick.

Parametry

pattern

Specifies a pointer to a text string containing a pattern.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::queryfonts
Gmagick::radialblurimage
Gmagick


Radial blurs an image

Gmagick::queryformats
Gmagick::raiseimage
Gmagick
PHP Manual

Gmagick::radialblurimage

(PECL gmagick >= Unknown)

Gmagick::radialblurimage — Radial blurs an image

Opis

public void Gmagick::radialblurimage ( float $angle [, int $channel = Gmagick::CHANNEL_DEFAULT ] )

Radial blurs an image.

Parametry

angle

The angle of the blur in degrees.

channel

Related channel

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::queryformats
Gmagick::raiseimage
Gmagick


Creates a simulated 3d button-like effect

Gmagick::radialblurimage
Gmagick::read
Gmagick
PHP Manual

Gmagick::raiseimage

(PECL gmagick >= Unknown)

Gmagick::raiseimage — Creates a simulated 3d button-like effect

Opis

public void Gmagick::raiseimage ( int $width , int $height , int $x , int $y , bool $raise )

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

Parametry

width

Width of the area to raise.

height

Height of the area to raise.

x

X coordinate

y

Y coordinate

raise

A value other than zero creates a 3-D raise effect, otherwise it has a lowered effect.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::radialblurimage
Gmagick::read
Gmagick


Reads image from filename

Gmagick::raiseimage
Gmagick::readimage
Gmagick
PHP Manual

Gmagick::read

(PECL gmagick >= Unknown)

Gmagick::read — Reads image from filename

Opis

public void Gmagick::read ( string $filename )

Reads image from filename.

Parametry

filename

The image filename.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::raiseimage
Gmagick::readimage
Gmagick


Reads image from filename

Gmagick::read
Gmagick::readimageblob
Gmagick
PHP Manual

Gmagick::readimage

(PECL gmagick >= Unknown)

Gmagick::readimage — Reads image from filename

Opis

public void Gmagick::readimage ( string $filename )

Reads image from filename.

Parametry

filename

The image filename.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::read
Gmagick::readimageblob
Gmagick


Reads image from a binary string

Gmagick::readimage
Gmagick::readimagefile
Gmagick
PHP Manual

Gmagick::readimageblob

(PECL gmagick >= Unknown)

Gmagick::readimageblob — Reads image from a binary string

Opis

public void Gmagick::readimageblob ( string $imageContents [, string $filename ] )

Reads image from a binary string.

Parametry

imageContents

Content of image

filename

The image filename.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::readimage
Gmagick::readimagefile
Gmagick


The readimagefile purpose

Gmagick::readimageblob
Gmagick::reducenoiseimage
Gmagick
PHP Manual

Gmagick::readimagefile

(PECL gmagick >= Unknown)

Gmagick::readimagefile — The readimagefile purpose

Opis

public void Gmagick::readimagefile ( resource $fp [, string $filename ] )

Reads an image or image sequence from an open file descriptor.

Parametry

fp

The file descriptor.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::readimageblob
Gmagick::reducenoiseimage
Gmagick


Smooths the contours of an image

Gmagick::readimagefile
Gmagick::removeimage
Gmagick
PHP Manual

Gmagick::reducenoiseimage

(PECL gmagick >= Unknown)

Gmagick::reducenoiseimage — Smooths the contours of an image

Opis

public void Gmagick::reducenoiseimage ( float $radius )

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Gmagick::reduceNoiseImage() selects a suitable radius for you.

Parametry

radius

The radius of the pixel neighborhood.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::readimagefile
Gmagick::removeimage
Gmagick


Removes an image from the image list

Gmagick::reducenoiseimage
Gmagick::removeimageprofile
Gmagick
PHP Manual

Gmagick::removeimage

(PECL gmagick >= Unknown)

Gmagick::removeimage — Removes an image from the image list

Opis

public void Gmagick::removeimage ( void )

Removes an image from the image list.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::reducenoiseimage
Gmagick::removeimageprofile
Gmagick


Removes the named image profile and returns it

Gmagick::removeimage
Gmagick::resampleimage
Gmagick
PHP Manual

Gmagick::removeimageprofile

(PECL gmagick >= Unknown)

Gmagick::removeimageprofile — Removes the named image profile and returns it

Opis

public string Gmagick::removeimageprofile ( string $name )

Removes the named image profile and returns it.

Parametry

name

Name of profile to return: ICC, IPTC, or generic profile.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::removeimage
Gmagick::resampleimage
Gmagick


Resample image to desired resolution

Gmagick::removeimageprofile
Gmagick::resizeimage
Gmagick
PHP Manual

Gmagick::resampleimage

(PECL gmagick >= Unknown)

Gmagick::resampleimage — Resample image to desired resolution

Opis

public void Gmagick::resampleimage ( float $xResolution , float $yResolution , int $filter , float $blur )

Resample image to desired resolution.

Parametry

xResolution

The new image x resolution.

yResolution

The new image y resolution.

filter

Image filter to use.

blur

The blur factor where larger than 1 is blurry, smaller than 1 is sharp.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::removeimageprofile
Gmagick::resizeimage
Gmagick


Scales an image

Gmagick::resampleimage
Gmagick::rollimage
Gmagick
PHP Manual

Gmagick::resizeimage

(PECL gmagick >= Unknown)

Gmagick::resizeimage — Scales an image

Opis

public void Gmagick::resizeimage ( int $width , int $height , int $filter , float $blur [, bool $fit = false ] )

Scales an image to the desired dimensions with a filter.

Parametry

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

filter

Image filter to use.

blur

The blur factor where larger than 1 is blurry, lesser than 1 is sharp.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::resampleimage
Gmagick::rollimage
Gmagick


Offsets an image

Gmagick::resizeimage
Gmagick::rotateimage
Gmagick
PHP Manual

Gmagick::rollimage

(PECL gmagick >= Unknown)

Gmagick::rollimage — Offsets an image

Opis

public void Gmagick::rollimage ( int $x , int $y )

Offsets an image as defined by x and y.

Parametry

x

The x offset.

y

The y offset.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::resizeimage
Gmagick::rotateimage
Gmagick


Rotates an image

Gmagick::rollimage
Gmagick::scaleimage
Gmagick
PHP Manual

Gmagick::rotateimage

(PECL gmagick >= Unknown)

Gmagick::rotateimage — Rotates an image

Opis

public Gmagick Gmagick::rotateimage ( mixed $color , float $degrees )

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

Parametry

color

The background pixel.

degrees

The number of degrees to rotate the image.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::rollimage
Gmagick::scaleimage
Gmagick


Scales the size of an image

Gmagick::rotateimage
Gmagick::separateimagechannel
Gmagick
PHP Manual

Gmagick::scaleimage

(PECL gmagick >= Unknown)

Gmagick::scaleimage — Scales the size of an image

Opis

public Gmagick Gmagick::scaleimage ( int $width , int $height [, bool $fit = false ] )

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

Parametry

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::rotateimage
Gmagick::separateimagechannel
Gmagick


Separates a channel from the image

Gmagick::scaleimage
Gmagick::setfilename
Gmagick
PHP Manual

Gmagick::separateimagechannel

(PECL gmagick >= Unknown)

Gmagick::separateimagechannel — Separates a channel from the image

Opis

public Gmagick Gmagick::separateimagechannel ( int $channel )

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

Parametry

channel

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::scaleimage
Gmagick::setfilename
Gmagick


Sets the filename before you read or write the image

Gmagick::separateimagechannel
Gmagick::setimagebackgroundcolor
Gmagick
PHP Manual

Gmagick::setfilename

(PECL gmagick >= Unknown)

Gmagick::setfilename — Sets the filename before you read or write the image

Opis

public Gmagick Gmagick::setfilename ( string $filename )

Sets the filename before you read or write an image file.

Parametry

filename

The image filename.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::separateimagechannel
Gmagick::setimagebackgroundcolor
Gmagick


Sets the image background color.

Gmagick::setfilename
Gmagick::setimageblueprimary
Gmagick
PHP Manual

Gmagick::setimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::setimagebackgroundcolor — Sets the image background color.

Opis

public Gmagick Gmagick::setimagebackgroundcolor ( GmagickPixel $color )

Sets the image background color.

Parametry

color

The background pixel wand.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setfilename
Gmagick::setimageblueprimary
Gmagick


Sets the image chromaticity blue primary point.

Gmagick::setimagebackgroundcolor
Gmagick::setimagebordercolor
Gmagick
PHP Manual

Gmagick::setimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point.

Opis

public Gmagick Gmagick::setimageblueprimary ( float $x , float $y )

Sets the image chromaticity blue primary point.

Parametry

x

The blue primary x-point.

y

The blue primary y-point.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagebackgroundcolor
Gmagick::setimagebordercolor
Gmagick


Sets the image border color.

Gmagick::setimageblueprimary
Gmagick::setimagechanneldepth
Gmagick
PHP Manual

Gmagick::setimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::setimagebordercolor — Sets the image border color.

Opis

public Gmagick Gmagick::setimagebordercolor ( GmagickPixel $color )

Sets the image border color.

Parametry

color

The border pixel wand.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageblueprimary
Gmagick::setimagechanneldepth
Gmagick


Sets the depth of a particular image channel

Gmagick::setimagebordercolor
Gmagick::setimagecolorspace
Gmagick
PHP Manual

Gmagick::setimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::setimagechanneldepth — Sets the depth of a particular image channel

Opis

public Gmagick Gmagick::setimagechanneldepth ( int $channel , int $depth )

Sets the depth of a particular image channel.

Parametry

channel

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

depth

The image depth in bits.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagebordercolor
Gmagick::setimagecolorspace
Gmagick


Sets the image colorspace

Gmagick::setimagechanneldepth
Gmagick::setimagecompose
Gmagick
PHP Manual

Gmagick::setimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::setimagecolorspace — Sets the image colorspace

Opis

public Gmagick Gmagick::setimagecolorspace ( int $colorspace )

Sets the image colorspace.

Parametry

colorspace

The image colorspace: UndefinedColorspace, RGBColorspace, GRAYColorspace, TransparentColorspace, OHTAColorspace, XYZColorspace, YCbCrColorspace, YCCColorspace, YIQColorspace, YPbPrColorspace, YPbPrColorspace, YUVColorspace, CMYKColorspace, sRGBColorspace, HSLColorspace, or HWBColorspace.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagechanneldepth
Gmagick::setimagecompose
Gmagick


Sets the image composite operator

Gmagick::setimagecolorspace
Gmagick::setimagedelay
Gmagick
PHP Manual

Gmagick::setimagecompose

(PECL gmagick >= Unknown)

Gmagick::setimagecompose — Sets the image composite operator

Opis

public Gmagick Gmagick::setimagecompose ( int $composite )

Sets the image composite operator.

Parametry

composite

The image composite operator.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagecolorspace
Gmagick::setimagedelay
Gmagick


Sets the image delay

Gmagick::setimagecompose
Gmagick::setimagedepth
Gmagick
PHP Manual

Gmagick::setimagedelay

(PECL gmagick >= Unknown)

Gmagick::setimagedelay — Sets the image delay

Opis

public Gmagick Gmagick::setimagedelay ( int $delay )

Sets the image delay

Parametry

delay

The image delay in 1/100th of a second.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagecompose
Gmagick::setimagedepth
Gmagick


Sets the image depth

Gmagick::setimagedelay
Gmagick::setimagedispose
Gmagick
PHP Manual

Gmagick::setimagedepth

(PECL gmagick >= Unknown)

Gmagick::setimagedepth — Sets the image depth

Opis

public Gmagick Gmagick::setimagedepth ( int $depth )

Sets the image depth

Parametry

depth

The image depth in bits: 8, 16, or 32.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagedelay
Gmagick::setimagedispose
Gmagick


Sets the image disposal method

Gmagick::setimagedepth
Gmagick::setimagefilename
Gmagick
PHP Manual

Gmagick::setimagedispose

(PECL gmagick >= Unknown)

Gmagick::setimagedispose — Sets the image disposal method

Opis

public Gmagick Gmagick::setimagedispose ( int $disposeType )

Sets the image disposal method.

Parametry

disposeType

The image disposal type.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagedepth
Gmagick::setimagefilename
Gmagick


Sets the filename of a particular image in a sequence

Gmagick::setimagedispose
Gmagick::setimageformat
Gmagick
PHP Manual

Gmagick::setimagefilename

(PECL gmagick >= Unknown)

Gmagick::setimagefilename — Sets the filename of a particular image in a sequence

Opis

public Gmagick Gmagick::setimagefilename ( string $filename )

Sets the filename of a particular image in a sequence.

Parametry

filename

The image filename.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagedispose
Gmagick::setimageformat
Gmagick


Sets the format of a particular image

Gmagick::setimagefilename
Gmagick::setimagegamma
Gmagick
PHP Manual

Gmagick::setimageformat

(PECL gmagick >= Unknown)

Gmagick::setimageformat — Sets the format of a particular image

Opis

public Gmagick Gmagick::setimageformat ( string $imageFormat )

Sets the format of a particular image in a sequence.

Parametry

imageFormat

The image format.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagefilename
Gmagick::setimagegamma
Gmagick


Sets the image gamma

Gmagick::setimageformat
Gmagick::setimagegreenprimary
Gmagick
PHP Manual

Gmagick::setimagegamma

(PECL gmagick >= Unknown)

Gmagick::setimagegamma — Sets the image gamma

Opis

public Gmagick Gmagick::setimagegamma ( float $gamma )

Sets the image gamma.

Parametry

gamma

The image gamma.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageformat
Gmagick::setimagegreenprimary
Gmagick


TSets the image chromaticity green primary point.

Gmagick::setimagegamma
Gmagick::setimageindex
Gmagick
PHP Manual

Gmagick::setimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::setimagegreenprimary — TSets the image chromaticity green primary point.

Opis

public Gmagick Gmagick::setimagegreenprimary ( float $x , float $y )

Sets the image chromaticity green primary point.

Parametry

x

The chromaticity green primary x-point.

y

The chromaticity green primary y-point.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagegamma
Gmagick::setimageindex
Gmagick


Set the iterator to the position in the image list specified with the index parameter

Gmagick::setimagegreenprimary
Gmagick::setimageinterlacescheme
Gmagick
PHP Manual

Gmagick::setimageindex

(PECL gmagick >= Unknown)

Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter

Opis

public Gmagick Gmagick::setimageindex ( int $index )

Set the iterator to the position in the image list specified with the index parameter.

Parametry

index

The scene number.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagegreenprimary
Gmagick::setimageinterlacescheme
Gmagick


Sets the interlace scheme of the image.

Gmagick::setimageindex
Gmagick::setimageiterations
Gmagick
PHP Manual

Gmagick::setimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image.

Opis

public Gmagick Gmagick::setimageinterlacescheme ( int $interlace )

Sets the interlace scheme of the image.

Parametry

interlace

The image interlace scheme: NoInterlace, LineInterlace, PlaneInterlace, PartitionInterlace.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageindex
Gmagick::setimageiterations
Gmagick


Sets the image iterations.

Gmagick::setimageinterlacescheme
Gmagick::setimageprofile
Gmagick
PHP Manual

Gmagick::setimageiterations

(PECL gmagick >= Unknown)

Gmagick::setimageiterations — Sets the image iterations.

Opis

public Gmagick Gmagick::setimageiterations ( int $iterations )

Sets the image iterations.

Parametry

iterations

The image delay in 1/100th of a second.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageinterlacescheme
Gmagick::setimageprofile
Gmagick


Adds a named profile to the Gmagick object

Gmagick::setimageiterations
Gmagick::setimageredprimary
Gmagick
PHP Manual

Gmagick::setimageprofile

(PECL gmagick >= Unknown)

Gmagick::setimageprofile — Adds a named profile to the Gmagick object

Opis

public Gmagick Gmagick::setimageprofile ( string $name , string $profile )

Adds a named profile to the Gmagick object. If a profile with the same name already exists, it is replaced. This method differs from the Gmagick::ProfileImage() method in that it does not apply any CMS color profiles.

Parametry

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageiterations
Gmagick::setimageredprimary
Gmagick


Sets the image chromaticity red primary point.

Gmagick::setimageprofile
Gmagick::setimagerenderingintent
Gmagick
PHP Manual

Gmagick::setimageredprimary

(PECL gmagick >= Unknown)

Gmagick::setimageredprimary — Sets the image chromaticity red primary point.

Opis

public Gmagick Gmagick::setimageredprimary ( float $x , float $y )

Sets the image chromaticity red primary point.

Parametry

x

The red primary x-point.

y

The red primary y-point.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageprofile
Gmagick::setimagerenderingintent
Gmagick


Sets the image rendering intent

Gmagick::setimageredprimary
Gmagick::setimageresolution
Gmagick
PHP Manual

Gmagick::setimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::setimagerenderingintent — Sets the image rendering intent

Opis

public Gmagick Gmagick::setimagerenderingintent ( int $rendering_intent )

Sets the image rendering intent.

Parametry

rendering_intent

The image rendering intent: UndefinedIntent, SaturationIntent, PerceptualIntent, AbsoluteIntent, or RelativeIntent.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageredprimary
Gmagick::setimageresolution
Gmagick


Sets the image resolution

Gmagick::setimagerenderingintent
Gmagick::setimagescene
Gmagick
PHP Manual

Gmagick::setimageresolution

(PECL gmagick >= Unknown)

Gmagick::setimageresolution — Sets the image resolution

Opis

public Gmagick Gmagick::setimageresolution ( float $xResolution , float $yResolution )

Sets the image resolution.

Parametry

xResolution

The image x resolution.

yResolution

The image y resolution.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagerenderingintent
Gmagick::setimagescene
Gmagick


Sets the image scene

Gmagick::setimageresolution
Gmagick::setimagetype
Gmagick
PHP Manual

Gmagick::setimagescene

(PECL gmagick >= Unknown)

Gmagick::setimagescene — Sets the image scene

Opis

public Gmagick Gmagick::setimagescene ( int $scene )

Sets the image scene.

Parametry

scene

The image scene number.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageresolution
Gmagick::setimagetype
Gmagick


Sets the image type

Gmagick::setimagescene
Gmagick::setimageunits
Gmagick
PHP Manual

Gmagick::setimagetype

(PECL gmagick >= Unknown)

Gmagick::setimagetype — Sets the image type

Opis

public Gmagick Gmagick::setimagetype ( int $imgType )

Sets the image type.

Parametry

imgType

The image type: UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, or OptimizeType.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagescene
Gmagick::setimageunits
Gmagick


Sets the image units of resolution.

Gmagick::setimagetype
Gmagick::setimagewhitepoint
Gmagick
PHP Manual

Gmagick::setimageunits

(PECL gmagick >= Unknown)

Gmagick::setimageunits — Sets the image units of resolution.

Opis

public Gmagick Gmagick::setimageunits ( int $resolution )

Sets the image units of resolution.

Parametry

resolution

The image units of resolution : Undefinedresolution, PixelsPerInchResolution, or PixelsPerCentimeterResolution.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagetype
Gmagick::setimagewhitepoint
Gmagick


Sets the image chromaticity white point.

Gmagick::setimageunits
Gmagick::setsamplingfactors
Gmagick
PHP Manual

Gmagick::setimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::setimagewhitepoint — Sets the image chromaticity white point.

Opis

public Gmagick Gmagick::setimagewhitepoint ( float $x , float $y )

Sets the image chromaticity white point.

Parametry

x

The white x-point.

y

The white y-point.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimageunits
Gmagick::setsamplingfactors
Gmagick


Sets the image sampling factors.

Gmagick::setimagewhitepoint
Gmagick::setsize
Gmagick
PHP Manual

Gmagick::setsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::setsamplingfactors — Sets the image sampling factors.

Opis

public Gmagick Gmagick::setsamplingfactors ( array $factors )

Sets the image sampling factors.

Parametry

factors

An array of doubles representing the sampling factor for each color component (in RGB order).

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setimagewhitepoint
Gmagick::setsize
Gmagick


Sets the size of the Gmagick object

Gmagick::setsamplingfactors
Gmagick::shearimage
Gmagick
PHP Manual

Gmagick::setsize

(PECL gmagick >= Unknown)

Gmagick::setsize — Sets the size of the Gmagick object

Opis

public Gmagick Gmagick::setsize ( int $columns , int $rows )

Sets the size of the Gmagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.

Parametry

columns

The width in pixels.

rows

The height in pixels.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setsamplingfactors
Gmagick::shearimage
Gmagick


Creating a parallelogram

Gmagick::setsize
Gmagick::solarizeimage
Gmagick
PHP Manual

Gmagick::shearimage

(PECL gmagick >= Unknown)

Gmagick::shearimage — Creating a parallelogram

Opis

public Gmagick Gmagick::shearimage ( mixed $color , float $xShear , float $yShear )

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

Parametry

color

The background pixel wand.

xShear

The number of degrees to shear the image.

yShear

The number of degrees to shear the image.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::setsize
Gmagick::solarizeimage
Gmagick


Applies a solarizing effect to the image

Gmagick::shearimage
Gmagick::spreadimage
Gmagick
PHP Manual

Gmagick::solarizeimage

(PECL gmagick >= Unknown)

Gmagick::solarizeimage — Applies a solarizing effect to the image

Opis

public Gmagick Gmagick::solarizeimage ( int $threshold )

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

Parametry

threshold

Define the extent of the solarization.

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::shearimage
Gmagick::spreadimage
Gmagick


Randomly displaces each pixel in a block

Gmagick::solarizeimage
Gmagick::stripimage
Gmagick
PHP Manual

Gmagick::spreadimage

(PECL gmagick >= Unknown)

Gmagick::spreadimage — Randomly displaces each pixel in a block

Opis

public Gmagick Gmagick::spreadimage ( float $radius )

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

Parametry

radius

Choose a random pixel in a neighborhood of this extent.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::solarizeimage
Gmagick::stripimage
Gmagick


Strips an image of all profiles and comments

Gmagick::spreadimage
Gmagick::swirlimage
Gmagick
PHP Manual

Gmagick::stripimage

(PECL gmagick >= Unknown)

Gmagick::stripimage — Strips an image of all profiles and comments

Opis

public Gmagick Gmagick::stripimage ( void )

Strips an image of all profiles and comments.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::spreadimage
Gmagick::swirlimage
Gmagick


Swirls the pixels about the center of the image

Gmagick::stripimage
Gmagick::thumbnailimage
Gmagick
PHP Manual

Gmagick::swirlimage

(PECL gmagick >= Unknown)

Gmagick::swirlimage — Swirls the pixels about the center of the image

Opis

public Gmagick Gmagick::swirlimage ( float $degrees )

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

Parametry

degrees

Define the tightness of the swirling effect.

Zwracane wartości

The Gmagick object on success

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::stripimage
Gmagick::thumbnailimage
Gmagick


Changes the size of an image

Gmagick::swirlimage
Gmagick::trimimage
Gmagick
PHP Manual

Gmagick::thumbnailimage

(PECL gmagick >= Unknown)

Gmagick::thumbnailimage — Changes the size of an image

Opis

public Gmagick Gmagick::thumbnailimage ( int $width , int $height [, bool $fit = false ] )

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small low cost thumbnail images suited for display on the Web. If TRUE is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until the match or are smaller than the parameter given for the side.

Parametry

width

Image width

height

Image height

Zwracane wartości

The Gmagick object on success.

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::swirlimage
Gmagick::trimimage
Gmagick


Remove edges from the image

Gmagick::thumbnailimage
Gmagick::write
Gmagick
PHP Manual

Gmagick::trimimage

(PECL gmagick >= Unknown)

Gmagick::trimimage — Remove edges from the image

Opis

public Gmagick Gmagick::trimimage ( float $fuzz )

Remove edges that are the background color from the image.

Parametry

fuzz

By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

Zwracane wartości

The Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::thumbnailimage
Gmagick::write
Gmagick


Writes an image to the specified filename

Gmagick::trimimage
Gmagick::writeimage
Gmagick
PHP Manual

Gmagick::write

(PECL gmagick >= Unknown)

Gmagick::write — Writes an image to the specified filename

Opis

public void Gmagick::write ( string $filename )

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Gmagick::ReadImage() or Gmagick::SetImageFilename().

Parametry

filename

The image filename.

Zwracane wartości

The Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::trimimage
Gmagick::writeimage
Gmagick


Writes an image to the specified filename

Gmagick::write
GmagickDraw
Gmagick
PHP Manual

Gmagick::writeimage

(PECL gmagick >= Unknown)

Gmagick::writeimage — Writes an image to the specified filename

Opis

public Gmagick Gmagick::writeimage ( string $filename [, bool $all_frames = false ] )

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Gmagick::ReadImage() or Gmagick::SetImageFilename().

Parametry

filename

The image filename.

Zwracane wartości

The Gmagick object

Błędy/Wyjątki

Wywołuje wyjątek GmagickException w przypadku błędu.

Gmagick::write
GmagickDraw
Gmagick


The GmagickDraw class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

GmagickDraw {
/* Metody */
public GmagickDraw annotate ( float $x , float $y , string $text )
public GmagickDraw arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
public GmagickDraw bezier ( array $coordinate_array )
public GmagickDraw ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
public void getfillcolor ( void )
public float getfillopacity ( void )
public string getfont ( void )
public float getfontsize ( void )
public int getfontstyle ( void )
public int getfontweight ( void )
public void getstrokecolor ( void )
public float getstrokeopacity ( void )
public float getstrokewidth ( void )
public int gettextdecoration ( void )
public string gettextencoding ( void )
public GmagickDraw line ( float $sx , float $sy , float $ex , float $ey )
public GmagickDraw point ( float $x , float $y )
public GmagickDraw polygon ( array $coordinates )
public GmagickDraw polyline ( array $coordinate_array )
public GmagickDraw rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
public GmagickDraw rotate ( float $degrees )
public GmagickDraw roundrectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
public GmagickDraw scale ( float $x , float $y )
public GmagickDraw setfillcolor ( string $color )
public GmagickDraw setfillopacity ( float $fill_opacity )
public GmagickDraw setfont ( string $font )
public GmagickDraw setfontsize ( float $pointsize )
public GmagickDraw setfontstyle ( int $style )
public GmagickDraw setfontweight ( int $weight )
public GmagickDraw setstrokecolor ( GmagickPixel $color )
public GmagickDraw setstrokeopacity ( float $stroke_opacity )
public GmagickDraw setstrokewidth ( float $width )
public GmagickDraw settextdecoration ( int $decoration )
public GmagickDraw settextencoding ( string $encoding )
}

Spis treści

  • GmagickDraw::annotate — Draws text on the image
  • GmagickDraw::arc — Draws an arc
  • GmagickDraw::bezier — Draws a bezier curve
  • GmagickDraw::ellipse — Draws an ellipse on the image
  • GmagickDraw::getfillcolor — Returns the fill color
  • GmagickDraw::getfillopacity — Returns the opacity used when drawing
  • GmagickDraw::getfont — Returns the font
  • GmagickDraw::getfontsize — Returns the font pointsize
  • GmagickDraw::getfontstyle — Returns the font style
  • GmagickDraw::getfontweight — Returns the font weight
  • GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
  • GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
  • GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
  • GmagickDraw::gettextdecoration — Returns the text decoration
  • GmagickDraw::gettextencoding — Returns the code set used for text annotations
  • GmagickDraw::line — The line purpose
  • GmagickDraw::point — Draws a point
  • GmagickDraw::polygon — Draws a polygon
  • GmagickDraw::polyline — Draws a polyline
  • GmagickDraw::rectangle — Draws a rectangle
  • GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
  • GmagickDraw::roundrectangle — Draws a rounded rectangle
  • GmagickDraw::scale — Adjusts the scaling factor
  • GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.
  • GmagickDraw::setfillopacity — The setfillopacity purpose
  • GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.
  • GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.
  • GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
  • GmagickDraw::setfontweight — Sets the font weight
  • GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.
  • GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.
  • GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.
  • GmagickDraw::settextdecoration — Specifies a decoration
  • GmagickDraw::settextencoding — Specifies specifies the text code set
Gmagick::writeimage
GmagickDraw::annotate
Gmagick


Draws text on the image

GmagickDraw
GmagickDraw::arc
GmagickDraw
PHP Manual

GmagickDraw::annotate

(PECL gmagick >= Unknown)

GmagickDraw::annotate — Draws text on the image

Opis

public GmagickDraw GmagickDraw::annotate ( float $x , float $y , string $text )

Draws text on the image.

Parametry

x

x ordinate to left of text

y

y ordinate to text baseline

text

text to draw

Zwracane wartości

The GmagickDraw object on success.

GmagickDraw
GmagickDraw::arc
GmagickDraw


Draws an arc

GmagickDraw::annotate
GmagickDraw::bezier
GmagickDraw
PHP Manual

GmagickDraw::arc

(PECL gmagick >= Unknown)

GmagickDraw::arc — Draws an arc

Opis

public GmagickDraw GmagickDraw::arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )

Draws an arc falling within a specified bounding rectangle on the image.

Parametry

sx

starting x ordinate of bounding rectangle

sy

starting y ordinate of bounding rectangle

ex

ending x ordinate of bounding rectangle

ey

ending y ordinate of bounding rectangle

sd

starting degrees of rotation

ed

ending degrees of rotation

Zwracane wartości

The GmagickDraw object on success.

GmagickDraw::annotate
GmagickDraw::bezier
GmagickDraw


Draws a bezier curve

GmagickDraw::arc
GmagickDraw::ellipse
GmagickDraw
PHP Manual

GmagickDraw::bezier

(PECL gmagick >= Unknown)

GmagickDraw::bezier — Draws a bezier curve

Opis

public GmagickDraw GmagickDraw::bezier ( array $coordinate_array )

Draws a bezier curve through a set of points on the image.

Parametry

coordinate_array

Coordinates array

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::arc
GmagickDraw::ellipse
GmagickDraw


Draws an ellipse on the image

GmagickDraw::bezier
GmagickDraw::getfillcolor
GmagickDraw
PHP Manual

GmagickDraw::ellipse

(PECL gmagick >= Unknown)

GmagickDraw::ellipse — Draws an ellipse on the image

Opis

public GmagickDraw GmagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )

Draws an ellipse on the image.

Parametry

ox

origin x ordinate

oy

origin y ordinate

rx

radius in x

ry

radius in y

start

starting rotation in degrees

end

ending rotation in degrees

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::bezier
GmagickDraw::getfillcolor
GmagickDraw


Returns the fill color

GmagickDraw::ellipse
GmagickDraw::getfillopacity
GmagickDraw
PHP Manual

GmagickDraw::getfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::getfillcolor — Returns the fill color

Opis

public void GmagickDraw::getfillcolor ( void )

Returns the fill color used for drawing filled objects.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The GmagickPixel fill color used for drawing filled objects.

GmagickDraw::ellipse
GmagickDraw::getfillopacity
GmagickDraw


Returns the opacity used when drawing

GmagickDraw::getfillcolor
GmagickDraw::getfont
GmagickDraw
PHP Manual

GmagickDraw::getfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::getfillopacity — Returns the opacity used when drawing

Opis

public float GmagickDraw::getfillopacity ( void )

Returns the opacity used when drawing

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

GmagickDraw::getfillcolor
GmagickDraw::getfont
GmagickDraw


Returns the font

GmagickDraw::getfillopacity
GmagickDraw::getfontsize
GmagickDraw
PHP Manual

GmagickDraw::getfont

(PECL gmagick >= Unknown)

GmagickDraw::getfont — Returns the font

Opis

public string GmagickDraw::getfont ( void )

Returns a string specifying the font used when annotating with text.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string on success and false if no font is set.

GmagickDraw::getfillopacity
GmagickDraw::getfontsize
GmagickDraw


Returns the font pointsize

GmagickDraw::getfont
GmagickDraw::getfontstyle
GmagickDraw
PHP Manual

GmagickDraw::getfontsize

(PECL gmagick >= Unknown)

GmagickDraw::getfontsize — Returns the font pointsize

Opis

public float GmagickDraw::getfontsize ( void )

Returns the font pointsize used when annotating with text.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the font size associated with the current GmagickDraw object.

GmagickDraw::getfont
GmagickDraw::getfontstyle
GmagickDraw


Returns the font style

GmagickDraw::getfontsize
GmagickDraw::getfontweight
GmagickDraw
PHP Manual

GmagickDraw::getfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::getfontstyle — Returns the font style

Opis

public int GmagickDraw::getfontstyle ( void )

Returns the font style used when annotating with text.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the font style constant (STYLE_) associated with the GmagickDraw object or 0 if no style is set.

GmagickDraw::getfontsize
GmagickDraw::getfontweight
GmagickDraw


Returns the font weight

GmagickDraw::getfontstyle
GmagickDraw::getstrokecolor
GmagickDraw
PHP Manual

GmagickDraw::getfontweight

(PECL gmagick >= Unknown)

GmagickDraw::getfontweight — Returns the font weight

Opis

public int GmagickDraw::getfontweight ( void )

Returns the font weight used when annotating with text.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an int on success and 0 if no weight is set.

GmagickDraw::getfontstyle
GmagickDraw::getstrokecolor
GmagickDraw


Returns the color used for stroking object outlines

GmagickDraw::getfontweight
GmagickDraw::getstrokeopacity
GmagickDraw
PHP Manual

GmagickDraw::getstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines

Opis

public void GmagickDraw::getstrokecolor ( void )

Returns the color used for stroking object outlines.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an GmagickPixel object which describes the color

GmagickDraw::getfontweight
GmagickDraw::getstrokeopacity
GmagickDraw


Returns the opacity of stroked object outlines

GmagickDraw::getstrokecolor
GmagickDraw::getstrokewidth
GmagickDraw
PHP Manual

GmagickDraw::getstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines

Opis

public float GmagickDraw::getstrokeopacity ( void )

Returns the opacity of stroked object outlines.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a double describing the opacity.

GmagickDraw::getstrokecolor
GmagickDraw::getstrokewidth
GmagickDraw


Returns the width of the stroke used to draw object outlines

GmagickDraw::getstrokeopacity
GmagickDraw::gettextdecoration
GmagickDraw
PHP Manual

GmagickDraw::getstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines

Opis

public float GmagickDraw::getstrokewidth ( void )

Returns the width of the stroke used to draw object outlines.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a double describing the stroke width.

GmagickDraw::getstrokeopacity
GmagickDraw::gettextdecoration
GmagickDraw


Returns the text decoration

GmagickDraw::getstrokewidth
GmagickDraw::gettextencoding
GmagickDraw
PHP Manual

GmagickDraw::gettextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::gettextdecoration — Returns the text decoration

Opis

public int GmagickDraw::gettextdecoration ( void )

Returns the decoration applied when annotating with text.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns one of the DECORATION_ constants and 0 if no decoration is set.

GmagickDraw::getstrokewidth
GmagickDraw::gettextencoding
GmagickDraw


Returns the code set used for text annotations

GmagickDraw::gettextdecoration
GmagickDraw::line
GmagickDraw
PHP Manual

GmagickDraw::gettextencoding

(PECL gmagick >= Unknown)

GmagickDraw::gettextencoding — Returns the code set used for text annotations

Opis

public string GmagickDraw::gettextencoding ( void )

Returns a string which specifies the code set used for text annotations.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string specifying the code set or false if text encoding is not set.

GmagickDraw::gettextdecoration
GmagickDraw::line
GmagickDraw


The line purpose

GmagickDraw::gettextencoding
GmagickDraw::point
GmagickDraw
PHP Manual

GmagickDraw::line

(PECL gmagick >= Unknown)

GmagickDraw::line — The line purpose

Opis

public GmagickDraw GmagickDraw::line ( float $sx , float $sy , float $ex , float $ey )

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

Parametry

sx

starting x ordinate

sy

starting y ordinate

ex

ending x ordinate

ey

ending y ordinate

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::gettextencoding
GmagickDraw::point
GmagickDraw


Draws a point

GmagickDraw::line
GmagickDraw::polygon
GmagickDraw
PHP Manual

GmagickDraw::point

(PECL gmagick >= Unknown)

GmagickDraw::point — Draws a point

Opis

public GmagickDraw GmagickDraw::point ( float $x , float $y )

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

Parametry

x

target x coordinate

y

target y coordinate

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::line
GmagickDraw::polygon
GmagickDraw


Draws a polygon

GmagickDraw::point
GmagickDraw::polyline
GmagickDraw
PHP Manual

GmagickDraw::polygon

(PECL gmagick >= Unknown)

GmagickDraw::polygon — Draws a polygon

Opis

public GmagickDraw GmagickDraw::polygon ( array $coordinates )

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parametry

coordinates

coordinate array

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::point
GmagickDraw::polyline
GmagickDraw


Draws a polyline

GmagickDraw::polygon
GmagickDraw::rectangle
GmagickDraw
PHP Manual

GmagickDraw::polyline

(PECL gmagick >= Unknown)

GmagickDraw::polyline — Draws a polyline

Opis

public GmagickDraw GmagickDraw::polyline ( array $coordinate_array )

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parametry

coordinate_array

The array of coordinates

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::polygon
GmagickDraw::rectangle
GmagickDraw


Draws a rectangle

GmagickDraw::polyline
GmagickDraw::rotate
GmagickDraw
PHP Manual

GmagickDraw::rectangle

(PECL gmagick >= Unknown)

GmagickDraw::rectangle — Draws a rectangle

Opis

public GmagickDraw GmagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

Parametry

x1

x ordinate of first coordinate

y1

y ordinate of first coordinate

x2

x ordinate of second coordinate

y2

y ordinate of second coordinate

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::polyline
GmagickDraw::rotate
GmagickDraw


Applies the specified rotation to the current coordinate space

GmagickDraw::rectangle
GmagickDraw::roundrectangle
GmagickDraw
PHP Manual

GmagickDraw::rotate

(PECL gmagick >= Unknown)

GmagickDraw::rotate — Applies the specified rotation to the current coordinate space

Opis

public GmagickDraw GmagickDraw::rotate ( float $degrees )

Applies the specified rotation to the current coordinate space.

Parametry

degrees

degrees of rotation

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::rectangle
GmagickDraw::roundrectangle
GmagickDraw


Draws a rounded rectangle

GmagickDraw::rotate
GmagickDraw::scale
GmagickDraw
PHP Manual

GmagickDraw::roundrectangle

(PECL gmagick >= Unknown)

GmagickDraw::roundrectangle — Draws a rounded rectangle

Opis

public GmagickDraw GmagickDraw::roundrectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )

Draws a rounded rectangle given two coordinates, x and y corner radiuses and using the current stroke, stroke width, and fill settings.

Parametry

x1

x ordinate of first coordinate

y1

y ordinate of first coordinate

x2

x ordinate of second coordinate

y2

y ordinate of second coordinate

rx

radius of corner in horizontal direction

ry

radius of corner in vertical direction

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::rotate
GmagickDraw::scale
GmagickDraw


Adjusts the scaling factor

GmagickDraw::roundrectangle
GmagickDraw::setfillcolor
GmagickDraw
PHP Manual

GmagickDraw::scale

(PECL gmagick >= Unknown)

GmagickDraw::scale — Adjusts the scaling factor

Opis

public GmagickDraw GmagickDraw::scale ( float $x , float $y )

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

Parametry

x

horizontal scale factor

y

vertical scale factor

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::roundrectangle
GmagickDraw::setfillcolor
GmagickDraw


Sets the fill color to be used for drawing filled objects.

GmagickDraw::scale
GmagickDraw::setfillopacity
GmagickDraw
PHP Manual

GmagickDraw::setfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects.

Opis

public GmagickDraw GmagickDraw::setfillcolor ( string $color )

Sets the fill color to be used for drawing filled objects.

Parametry

color

GmagickPixel indicating color to use for filling.

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::scale
GmagickDraw::setfillopacity
GmagickDraw


The setfillopacity purpose

GmagickDraw::setfillcolor
GmagickDraw::setfont
GmagickDraw
PHP Manual

GmagickDraw::setfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::setfillopacity — The setfillopacity purpose

Opis

public GmagickDraw GmagickDraw::setfillopacity ( float $fill_opacity )

Sets the opacity to use when drawing using the fill color or fill texture. Setting it to 1.0 will make fill full opaque.

Parametry

fill_opacity

Fill opacity

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setfillcolor
GmagickDraw::setfont
GmagickDraw


Sets the fully-specified font to use when annotating with text.

GmagickDraw::setfillopacity
GmagickDraw::setfontsize
GmagickDraw
PHP Manual

GmagickDraw::setfont

(PECL gmagick >= Unknown)

GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text.

Opis

public GmagickDraw GmagickDraw::setfont ( string $font )

Sets the fully-specified font to use when annotating with text

Parametry

font

font name

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setfillopacity
GmagickDraw::setfontsize
GmagickDraw


Sets the font pointsize to use when annotating with text.

GmagickDraw::setfont
GmagickDraw::setfontstyle
GmagickDraw
PHP Manual

GmagickDraw::setfontsize

(PECL gmagick >= Unknown)

GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text.

Opis

public GmagickDraw GmagickDraw::setfontsize ( float $pointsize )

Sets the font pointsize to use when annotating with text.

Parametry

pointsize

Text pointsize

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setfont
GmagickDraw::setfontstyle
GmagickDraw


Sets the font style to use when annotating with text

GmagickDraw::setfontsize
GmagickDraw::setfontweight
GmagickDraw
PHP Manual

GmagickDraw::setfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::setfontstyle — Sets the font style to use when annotating with text

Opis

public GmagickDraw GmagickDraw::setfontstyle ( int $style )

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

Parametry

style

Font style (NormalStyle, ItalicStyle, ObliqueStyle, AnyStyle)

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setfontsize
GmagickDraw::setfontweight
GmagickDraw


Sets the font weight

GmagickDraw::setfontstyle
GmagickDraw::setstrokecolor
GmagickDraw
PHP Manual

GmagickDraw::setfontweight

(PECL gmagick >= Unknown)

GmagickDraw::setfontweight — Sets the font weight

Opis

public GmagickDraw GmagickDraw::setfontweight ( int $weight )

Sets the font weight to use when annotating with text.

Parametry

weight

Font weight (valid range 100-900)

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setfontstyle
GmagickDraw::setstrokecolor
GmagickDraw


Sets the color used for stroking object outlines.

GmagickDraw::setfontweight
GmagickDraw::setstrokeopacity
GmagickDraw
PHP Manual

GmagickDraw::setstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines.

Opis

public GmagickDraw GmagickDraw::setstrokecolor ( GmagickPixel $color )

Sets the color used for stroking object outlines.

Parametry

color

GmagickPixel representing the color for the stroke.

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setfontweight
GmagickDraw::setstrokeopacity
GmagickDraw


Specifies the opacity of stroked object outlines.

GmagickDraw::setstrokecolor
GmagickDraw::setstrokewidth
GmagickDraw
PHP Manual

GmagickDraw::setstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines.

Opis

public GmagickDraw GmagickDraw::setstrokeopacity ( float $stroke_opacity )

Specifies the opacity of stroked object outlines.

Parametry

stroke_opacity

Stroke opacity. The value 1.0 is opaque.

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setstrokecolor
GmagickDraw::setstrokewidth
GmagickDraw


Sets the width of the stroke used to draw object outlines.

GmagickDraw::setstrokeopacity
GmagickDraw::settextdecoration
GmagickDraw
PHP Manual

GmagickDraw::setstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines.

Opis

public GmagickDraw GmagickDraw::setstrokewidth ( float $width )

Sets the width of the stroke used to draw object outlines

Parametry

width

Stroke width

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setstrokeopacity
GmagickDraw::settextdecoration
GmagickDraw


Specifies a decoration

GmagickDraw::setstrokewidth
GmagickDraw::settextencoding
GmagickDraw
PHP Manual

GmagickDraw::settextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::settextdecoration — Specifies a decoration

Opis

public GmagickDraw GmagickDraw::settextdecoration ( int $decoration )

Specifies a decoration to be applied when annotating with text.

Parametry

int

Text decoration. One of NoDecoration, UnderlineDecoration, OverlineDecoration, or LineThroughDecoration

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::setstrokewidth
GmagickDraw::settextencoding
GmagickDraw


Specifies specifies the text code set

GmagickDraw::settextdecoration
GmagickPixel
GmagickDraw
PHP Manual

GmagickDraw::settextencoding

(PECL gmagick >= Unknown)

GmagickDraw::settextencoding — Specifies specifies the text code set

Opis

public GmagickDraw GmagickDraw::settextencoding ( string $encoding )

Specifies specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

Parametry

encoding

Character string specifying text encoding

Zwracane wartości

The GmagickDraw object on success

GmagickDraw::settextdecoration
GmagickPixel
GmagickDraw


The GmagickPixel class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

GmagickPixel {
/* Metody */
public __construct ([ string $color ] )
public mixed getcolor ([ bool $as_array [, bool $normalize_array ]] )
public int getcolorcount ( void )
public float getcolorvalue ( int $color )
public GmagickPixel setcolor ( string $color )
public GmagickPixel setcolorvalue ( int $color , float $value )
}

Spis treści

  • GmagickPixel::__construct — The GmagickPixel constructor
  • GmagickPixel::getcolor — Returns the color
  • GmagickPixel::getcolorcount — Returns the color count associated with this color
  • GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
  • GmagickPixel::setcolor — Sets the color
  • GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels
GmagickDraw::settextencoding
GmagickPixel::__construct
Gmagick


The GmagickPixel constructor

GmagickPixel
GmagickPixel::getcolor
GmagickPixel
PHP Manual

GmagickPixel::__construct

(PECL gmagick >= Unknown)

GmagickPixel::__construct — The GmagickPixel constructor

Opis

public GmagickPixel::__construct ([ string $color ] )

Constructs an GmagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

Parametry

color

The optional color string to use as the initial value of this object.

Zwracane wartości

The GmagickPixel object on success.

GmagickPixel
GmagickPixel::getcolor
GmagickPixel


Returns the color

GmagickPixel::__construct
GmagickPixel::getcolorcount
GmagickPixel
PHP Manual

GmagickPixel::getcolor

(PECL gmagick >= Unknown)

GmagickPixel::getcolor — Returns the color

Opis

public mixed GmagickPixel::getcolor ([ bool $as_array [, bool $normalize_array ]] )

Returns the color described by the GmagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

Parametry

as_array

True to indicate return of array instead of string

normalize_array

Normalize the color values

Zwracane wartości

An array of channel values, each normalized if TRUE is given as param. Throws GmagickPixelException on error.

GmagickPixel::__construct
GmagickPixel::getcolorcount
GmagickPixel


Returns the color count associated with this color

GmagickPixel::getcolor
GmagickPixel::getcolorvalue
GmagickPixel
PHP Manual

GmagickPixel::getcolorcount

(PECL gmagick >= Unknown)

GmagickPixel::getcolorcount — Returns the color count associated with this color

Opis

public int GmagickPixel::getcolorcount ( void )

Returns the color count associated with this color

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the color count as an integer on success, throws GmagickPixelException on failure.

GmagickPixel::getcolor
GmagickPixel::getcolorvalue
GmagickPixel


Gets the normalized value of the provided color channel

GmagickPixel::getcolorcount
GmagickPixel::setcolor
GmagickPixel
PHP Manual

GmagickPixel::getcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel

Opis

public float GmagickPixel::getcolorvalue ( int $color )

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

Parametry

color

The channel to check, specified as one of the Gmagick channel constants.

Zwracane wartości

The value of the channel, as a normalized floating-point number, throwing GmagickPixelException on error.

GmagickPixel::getcolorcount
GmagickPixel::setcolor
GmagickPixel


Sets the color

GmagickPixel::getcolorvalue
GmagickPixel::setcolorvalue
GmagickPixel
PHP Manual

GmagickPixel::setcolor

(PECL gmagick >= Unknown)

GmagickPixel::setcolor — Sets the color

Opis

public GmagickPixel GmagickPixel::setcolor ( string $color )

Sets the color described by the GmagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

Parametry

color

The color definition to use in order to initialise the GmagickPixel object.

Zwracane wartości

The GmagickPixel object on success.

GmagickPixel::getcolorvalue
GmagickPixel::setcolorvalue
GmagickPixel


Sets the normalized value of one of the channels

GmagickPixel::setcolor
ImageMagick
GmagickPixel
PHP Manual

GmagickPixel::setcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

Opis

public GmagickPixel GmagickPixel::setcolorvalue ( int $color , float $value )

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to a GmagickPixel object.

Parametry

color

One of the Gmagick channel color constants.

value

The value to set this channel to, ranging from 0 to 1.

Zwracane wartości

The GmagickPixel object on success.

GmagickPixel::setcolor
ImageMagick
GmagickPixel


Image Processing (ImageMagick)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • Imagick — The Imagick class
    • Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
    • Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
    • Imagick::adaptiveSharpenImage — Adaptively sharpen the image
    • Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
    • Imagick::addImage — Adds new image to Imagick object image list
    • Imagick::addNoiseImage — Adds random noise to the image
    • Imagick::affineTransformImage — Transforms an image
    • Imagick::animateImages — Animates an image or images
    • Imagick::annotateImage — Annotates an image with text
    • Imagick::appendImages — Append a set of images
    • Imagick::averageImages — Average a set of images
    • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
    • Imagick::blurImage — Adds blur filter to image
    • Imagick::borderImage — Surrounds the image with a border
    • Imagick::charcoalImage — Simulates a charcoal drawing
    • Imagick::chopImage — Removes a region of an image and trims
    • Imagick::clear — Clears all resources associated to Imagick object
    • Imagick::clipImage — Clips along the first path from the 8BIM profile
    • Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
    • Imagick::clone — Makes an exact copy of the Imagick object
    • Imagick::clutImage — Replaces colors in the image
    • Imagick::coalesceImages — Composites a set of images
    • Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
    • Imagick::colorizeImage — Blends the fill color with the image
    • Imagick::combineImages — Combines one or more images into a single image
    • Imagick::commentImage — Adds a comment to your image
    • Imagick::compareImageChannels — Returns the difference in one or more images
    • Imagick::compareImageLayers — Returns the maximum bounding region between images
    • Imagick::compareImages — Compares an image to a reconstructed image
    • Imagick::compositeImage — Composite one image onto another
    • Imagick::__construct — The Imagick constructor
    • Imagick::contrastImage — Change the contrast of the image
    • Imagick::contrastStretchImage — Enhances the contrast of a color image
    • Imagick::convolveImage — Applies a custom convolution kernel to the image
    • Imagick::cropImage — Extracts a region of the image
    • Imagick::cropThumbnailImage — Creates a crop thumbnail
    • Imagick::current — Returns a reference to the current Imagick object
    • Imagick::cycleColormapImage — Displaces an image's colormap
    • Imagick::decipherImage — Deciphers an image
    • Imagick::deconstructImages — Returns certain pixel differences between images
    • Imagick::deleteImageArtifact — Delete image artifact
    • Imagick::deskewImage — Removes skew from the image
    • Imagick::despeckleImage — Reduces the speckle noise in an image
    • Imagick::destroy — Destroys the Imagick object
    • Imagick::displayImage — Displays an image
    • Imagick::displayImages — Displays an image or image sequence
    • Imagick::distortImage — Distorts an image using various distortion methods
    • Imagick::drawImage — Renders the ImagickDraw object on the current image
    • Imagick::edgeImage — Enhance edges within the image
    • Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage — Enciphers an image
    • Imagick::enhanceImage — Improves the quality of a noisy image
    • Imagick::equalizeImage — Equalizes the image histogram
    • Imagick::evaluateImage — Applies an expression to an image
    • Imagick::exportImagePixels — Exports raw image pixels
    • Imagick::extentImage — Set image size
    • Imagick::flattenImages — Merges a sequence of images
    • Imagick::flipImage — Creates a vertical mirror image
    • Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
    • Imagick::flopImage — Creates a horizontal mirror image
    • Imagick::frameImage — Adds a simulated three-dimensional border
    • Imagick::functionImage — Applies a function on the image
    • Imagick::fxImage — Evaluate expression for each pixel in the image
    • Imagick::gammaImage — Gamma-corrects an image
    • Imagick::gaussianBlurImage — Blurs an image
    • Imagick::getColorspace — Gets the colorspace
    • Imagick::getCompression — Gets the object compression type
    • Imagick::getCompressionQuality — Gets the object compression quality
    • Imagick::getCopyright — Returns the ImageMagick API copyright as a string
    • Imagick::getFilename — The filename associated with an image sequence
    • Imagick::getFont — Gets font
    • Imagick::getFormat — Returns the format of the Imagick object
    • Imagick::getGravity — Gets the gravity
    • Imagick::getHomeURL — Returns the ImageMagick home URL
    • Imagick::getImage — Returns a new Imagick object
    • Imagick::getImageAlphaChannel — Gets the image alpha channel
    • Imagick::getImageArtifact — Get image artifact
    • Imagick::getImageBackgroundColor — Returns the image background color
    • Imagick::getImageBlob — Returns the image sequence as a blob
    • Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor — Returns the image border color
    • Imagick::getImageChannelDepth — Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions — Gets channel distortions
    • Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean — Gets the mean and standard deviation
    • Imagick::getImageChannelRange — Gets channel range
    • Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
    • Imagick::getImageClipMask — Gets image clip mask
    • Imagick::getImageColormapColor — Returns the color of the specified colormap index
    • Imagick::getImageColors — Gets the number of unique colors in the image
    • Imagick::getImageColorspace — Gets the image colorspace
    • Imagick::getImageCompose — Returns the composite operator associated with the image
    • Imagick::getImageCompression — Gets the current image's compression type
    • Imagick::getImageCompressionQuality — Gets the current image's compression quality
    • Imagick::getImageDelay — Gets the image delay
    • Imagick::getImageDepth — Gets the image depth
    • Imagick::getImageDispose — Gets the image disposal method
    • Imagick::getImageDistortion — Compares an image to a reconstructed image
    • Imagick::getImageExtrema — Gets the extrema for the image
    • Imagick::getImageFilename — Returns the filename of a particular image in a sequence
    • Imagick::getImageFormat — Returns the format of a particular image in a sequence
    • Imagick::getImageGamma — Gets the image gamma
    • Imagick::getImageGeometry — Gets the width and height as an associative array
    • Imagick::getImageGravity — Gets the image gravity
    • Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
    • Imagick::getImageHeight — Returns the image height
    • Imagick::getImageHistogram — Gets the image histogram
    • Imagick::getImageIndex — Gets the index of the current active image
    • Imagick::getImageInterlaceScheme — Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod — Returns the interpolation method
    • Imagick::getImageIterations — Gets the image iterations
    • Imagick::getImageLength — Returns the image length in bytes
    • Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license
    • Imagick::getImageMatte — Return if the image has a matte channel
    • Imagick::getImageMatteColor — Returns the image matte color
    • Imagick::getImageOrientation — Gets the image orientation
    • Imagick::getImagePage — Returns the page geometry
    • Imagick::getImagePixelColor — Returns the color of the specified pixel
    • Imagick::getImageProfile — Returns the named image profile
    • Imagick::getImageProfiles — Returns the image profiles
    • Imagick::getImageProperties — Returns the image properties
    • Imagick::getImageProperty — Returns the named image property
    • Imagick::getImageRedPrimary — Returns the chromaticity red primary point
    • Imagick::getImageRegion — Extracts a region of the image
    • Imagick::getImageRenderingIntent — Gets the image rendering intent
    • Imagick::getImageResolution — Gets the image X and Y resolution
    • Imagick::getImagesBlob — Returns all image sequences as a blob
    • Imagick::getImageScene — Gets the image scene
    • Imagick::getImageSignature — Generates an SHA-256 message digest
    • Imagick::getImageSize — Returns the image length in bytes
    • Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity — Gets the image total ink density
    • Imagick::getImageType — Gets the potential image type
    • Imagick::getImageUnits — Gets the image units of resolution
    • Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
    • Imagick::getImageWhitePoint — Returns the chromaticity white point
    • Imagick::getImageWidth — Returns the image width
    • Imagick::getInterlaceScheme — Gets the object interlace scheme
    • Imagick::getIteratorIndex — Gets the index of the current active image
    • Imagick::getNumberImages — Returns the number of images in the object
    • Imagick::getOption — Returns a value associated with the specified key
    • Imagick::getPackageName — Returns the ImageMagick package name
    • Imagick::getPage — Returns the page geometry
    • Imagick::getPixelIterator — Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
    • Imagick::getPointSize — Gets point size
    • Imagick::getQuantumDepth — Gets the quantum depth
    • Imagick::getQuantumRange — Returns the Imagick quantum range
    • Imagick::getReleaseDate — Returns the ImageMagick release date
    • Imagick::getResource — Returns the specified resource's memory usage
    • Imagick::getResourceLimit — Returns the specified resource limit
    • Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
    • Imagick::getSize — Returns the size associated with the Imagick object
    • Imagick::getSizeOffset — Returns the size offset
    • Imagick::getVersion — Returns the ImageMagick API version
    • Imagick::haldClutImage — Replaces colors in the image
    • Imagick::hasNextImage — Checks if the object has more images
    • Imagick::hasPreviousImage — Checks if the object has a previous image
    • Imagick::identifyImage — Identifies an image and fetches attributes
    • Imagick::implodeImage — Creates a new image as a copy
    • Imagick::importImagePixels — Imports image pixels
    • Imagick::labelImage — Adds a label to an image
    • Imagick::levelImage — Adjusts the levels of an image
    • Imagick::linearStretchImage — Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage — Animates an image or images
    • Imagick::magnifyImage — Scales an image proportionally 2x
    • Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.
    • Imagick::matteFloodfillImage — Changes the transparency value of a color
    • Imagick::medianFilterImage — Applies a digital filter
    • Imagick::mergeImageLayers — Merges image layers
    • Imagick::minifyImage — Scales an image proportionally to half its size
    • Imagick::modulateImage — Control the brightness, saturation, and hue
    • Imagick::montageImage — Creates a composite image
    • Imagick::morphImages — Method morphs a set of images
    • Imagick::mosaicImages — Forms a mosaic from images
    • Imagick::motionBlurImage — Simulates motion blur
    • Imagick::negateImage — Negates the colors in the reference image
    • Imagick::newImage — Creates a new image
    • Imagick::newPseudoImage — Creates a new image
    • Imagick::nextImage — Moves to the next image
    • Imagick::normalizeImage — Enhances the contrast of a color image
    • Imagick::oilPaintImage — Simulates an oil painting
    • Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage — Performs an ordered dither
    • Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage — Change any pixel that matches color
    • Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage — Fetch basic attributes about the image
    • Imagick::pingImageBlob — Quickly fetch attributes
    • Imagick::pingImageFile — Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage — Simulates a Polaroid picture
    • Imagick::posterizeImage — Reduces the image to a limited number of color level
    • Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage — Move to the previous image in the object
    • Imagick::profileImage — Adds or removes a profile from an image
    • Imagick::quantizeImage — Analyzes the colors within a reference image
    • Imagick::quantizeImages — Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics — Returns an array representing the font metrics
    • Imagick::queryFonts — Returns the configured fonts
    • Imagick::queryFormats — Returns formats supported by Imagick
    • Imagick::radialBlurImage — Radial blurs an image
    • Imagick::raiseImage — Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage — Creates a high-contrast, two-color image
    • Imagick::readImage — Reads image from filename
    • Imagick::readImageBlob — Reads image from a binary string
    • Imagick::readImageFile — Reads image from open filehandle
    • Imagick::recolorImage — Recolors image
    • Imagick::reduceNoiseImage — Smooths the contours of an image
    • Imagick::remapImage — Remaps image colors
    • Imagick::removeImage — Removes an image from the image list
    • Imagick::removeImageProfile — Removes the named image profile and returns it
    • Imagick::render — Renders all preceding drawing commands
    • Imagick::resampleImage — Resample image to desired resolution
    • Imagick::resetImagePage — Reset image page
    • Imagick::resizeImage — Scales an image
    • Imagick::rollImage — Offsets an image
    • Imagick::rotateImage — Rotates an image
    • Imagick::roundCorners — Rounds image corners
    • Imagick::sampleImage — Scales an image with pixel sampling
    • Imagick::scaleImage — Scales the size of an image
    • Imagick::segmentImage — Segments an image
    • Imagick::separateImageChannel — Separates a channel from the image
    • Imagick::sepiaToneImage — Sepia tones an image
    • Imagick::setBackgroundColor — Sets the object's default background color
    • Imagick::setColorspace — Set colorspace
    • Imagick::setCompression — Sets the object's default compression type
    • Imagick::setCompressionQuality — Sets the object's default compression quality
    • Imagick::setFilename — Sets the filename before you read or write the image
    • Imagick::setFirstIterator — Sets the Imagick iterator to the first image
    • Imagick::setFont — Sets font
    • Imagick::setFormat — Sets the format of the Imagick object
    • Imagick::setGravity — Sets the gravity
    • Imagick::setImage — Replaces image in the object
    • Imagick::setImageAlphaChannel — Sets image alpha channel
    • Imagick::setImageArtifact — Set image artifact
    • Imagick::setImageBackgroundColor — Sets the image background color
    • Imagick::setImageBias — Sets the image bias for any method that convolves an image
    • Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor — Sets the image border color
    • Imagick::setImageChannelDepth — Sets the depth of a particular image channel
    • Imagick::setImageClipMask — Sets image clip mask
    • Imagick::setImageColormapColor — Sets the color of the specified colormap index
    • Imagick::setImageColorspace — Sets the image colorspace
    • Imagick::setImageCompose — Sets the image composite operator
    • Imagick::setImageCompression — Sets the image compression
    • Imagick::setImageCompressionQuality — Sets the image compression quality
    • Imagick::setImageDelay — Sets the image delay
    • Imagick::setImageDepth — Sets the image depth
    • Imagick::setImageDispose — Sets the image disposal method
    • Imagick::setImageExtent — Sets the image size
    • Imagick::setImageFilename — Sets the filename of a particular image
    • Imagick::setImageFormat — Sets the format of a particular image
    • Imagick::setImageGamma — Sets the image gamma
    • Imagick::setImageGravity — Sets the image gravity
    • Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
    • Imagick::setImageIndex — Set the iterator position
    • Imagick::setImageInterlaceScheme — Sets the image compression
    • Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
    • Imagick::setImageIterations — Sets the image iterations
    • Imagick::setImageMatte — Sets the image matte channel
    • Imagick::setImageMatteColor — Sets the image matte color
    • Imagick::setImageOpacity — Sets the image opacity level
    • Imagick::setImageOrientation — Sets the image orientation
    • Imagick::setImagePage — Sets the page geometry of the image
    • Imagick::setImageProfile — Adds a named profile to the Imagick object
    • Imagick::setImageProperty — Sets an image property
    • Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent — Sets the image rendering intent
    • Imagick::setImageResolution — Sets the image resolution
    • Imagick::setImageScene — Sets the image scene
    • Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
    • Imagick::setImageType — Sets the image type
    • Imagick::setImageUnits — Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
    • Imagick::setImageWhitePoint — Sets the image chromaticity white point
    • Imagick::setInterlaceScheme — Sets the image compression
    • Imagick::setIteratorIndex — Set the iterator position
    • Imagick::setLastIterator — Sets the Imagick iterator to the last image
    • Imagick::setOption — Set an option
    • Imagick::setPage — Sets the page geometry of the Imagick object
    • Imagick::setPointSize — Sets point size
    • Imagick::setResolution — Sets the image resolution
    • Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes
    • Imagick::setSamplingFactors — Sets the image sampling factors
    • Imagick::setSize — Sets the size of the Imagick object
    • Imagick::setSizeOffset — Sets the size and offset of the Imagick object
    • Imagick::setType — Sets the image type attribute
    • Imagick::shadeImage — Creates a 3D effect
    • Imagick::shadowImage — Simulates an image shadow
    • Imagick::sharpenImage — Sharpens an image
    • Imagick::shaveImage — Shaves pixels from the image edges
    • Imagick::shearImage — Creating a parallelogram
    • Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
    • Imagick::sketchImage — Simulates a pencil sketch
    • Imagick::solarizeImage — Applies a solarizing effect to the image
    • Imagick::sparseColorImage — Interpolates colors
    • Imagick::spliceImage — Splices a solid color into the image
    • Imagick::spreadImage — Randomly displaces each pixel in a block
    • Imagick::steganoImage — Hides a digital watermark within the image
    • Imagick::stereoImage — Composites two images
    • Imagick::stripImage — Strips an image of all profiles and comments
    • Imagick::swirlImage — Swirls the pixels about the center of the image
    • Imagick::textureImage — Repeatedly tiles the texture image
    • Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
    • Imagick::thumbnailImage — Changes the size of an image
    • Imagick::tintImage — Applies a color vector to each pixel in the image
    • Imagick::transformImage — Convenience method for setting crop size and the image geometry
    • Imagick::transparentPaintImage — Paints pixels transparent
    • Imagick::transposeImage — Creates a vertical mirror image
    • Imagick::transverseImage — Creates a horizontal mirror image
    • Imagick::trimImage — Remove edges from the image
    • Imagick::uniqueImageColors — Discards all but one of any pixel color
    • Imagick::unsharpMaskImage — Sharpens an image
    • Imagick::valid — Checks if the current item is valid
    • Imagick::vignetteImage — Adds vignette filter to the image
    • Imagick::waveImage — Applies wave filter to the image
    • Imagick::whiteThresholdImage — Force all pixels above the threshold into white
    • Imagick::writeImage — Writes an image to the specified filename
    • Imagick::writeImageFile — Writes an image to a filehandle
    • Imagick::writeImages — Writes an image or image sequence
    • Imagick::writeImagesFile — Writes frames to a filehandle
  • ImagickDraw — The ImagickDraw class
    • ImagickDraw::affine — Adjusts the current affine transformation matrix
    • ImagickDraw::annotation — Draws text on the image
    • ImagickDraw::arc — Draws an arc
    • ImagickDraw::bezier — Draws a bezier curve
    • ImagickDraw::circle — Draws a circle
    • ImagickDraw::clear — Clears the ImagickDraw
    • ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color — Draws color on image
    • ImagickDraw::comment — Adds a comment
    • ImagickDraw::composite — Composites an image onto the current image
    • ImagickDraw::__construct — The ImagickDraw constructor
    • ImagickDraw::destroy — Frees all associated resources
    • ImagickDraw::ellipse — Draws an ellipse on the image
    • ImagickDraw::getClipPath — Obtains the current clipping path ID
    • ImagickDraw::getClipRule — Returns the current polygon fill rule
    • ImagickDraw::getClipUnits — Returns the interpretation of clip path units
    • ImagickDraw::getFillColor — Returns the fill color
    • ImagickDraw::getFillOpacity — Returns the opacity used when drawing
    • ImagickDraw::getFillRule — Returns the fill rule
    • ImagickDraw::getFont — Returns the font
    • ImagickDraw::getFontFamily — Returns the font family
    • ImagickDraw::getFontSize — Returns the font pointsize
    • ImagickDraw::getFontStyle — Returns the font style
    • ImagickDraw::getFontWeight — Returns the font weight
    • ImagickDraw::getGravity — Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment — Returns the text alignment
    • ImagickDraw::getTextAntialias — Returns the current text antialias setting
    • ImagickDraw::getTextDecoration — Returns the text decoration
    • ImagickDraw::getTextEncoding — Returns the code set used for text annotations
    • ImagickDraw::getTextUnderColor — Returns the text under color
    • ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
    • ImagickDraw::line — Draws a line
    • ImagickDraw::matte — Paints on the image's opacity channel
    • ImagickDraw::pathClose — Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
    • ImagickDraw::pathFinish — Terminates the current path
    • ImagickDraw::pathLineToAbsolute — Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
    • ImagickDraw::pathLineToRelative — Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
    • ImagickDraw::pathMoveToRelative — Starts a new sub-path
    • ImagickDraw::pathStart — Declares the start of a path drawing list
    • ImagickDraw::point — Draws a point
    • ImagickDraw::polygon — Draws a polygon
    • ImagickDraw::polyline — Draws a polyline
    • ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath — Terminates a clip path definition
    • ImagickDraw::popDefs — Terminates a definition list
    • ImagickDraw::popPattern — Terminates a pattern definition
    • ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath — Starts a clip path definition
    • ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle — Draws a rectangle
    • ImagickDraw::render — Renders all preceding drawing commands onto the image
    • ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle — Draws a rounded rectangle
    • ImagickDraw::scale — Adjusts the scaling factor
    • ImagickDraw::setClipPath — Associates a named clipping path with the image
    • ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits — Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight — Sets the font weight
    • ImagickDraw::setGravity — Sets the text placement gravity
    • ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
    • ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment — Specifies a text alignment
    • ImagickDraw::setTextAntialias — Controls whether text is antialiased
    • ImagickDraw::setTextDecoration — Specifies a decoration
    • ImagickDraw::setTextEncoding — Specifies specifies the text code set
    • ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics — Sets the vector graphics
    • ImagickDraw::setViewbox — Sets the overall canvas size
    • ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate — Applies a translation to the current coordinate system
  • ImagickPixel — The ImagickPixel class
    • ImagickPixel::clear — Clears resources associated with this object
    • ImagickPixel::__construct — The ImagickPixel constructor
    • ImagickPixel::destroy — Deallocates resources associated with this object
    • ImagickPixel::getColor — Returns the color
    • ImagickPixel::getColorAsString — Returns the color as a string
    • ImagickPixel::getColorCount — Returns the color count associated with this color
    • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
    • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::isSimilar — Check the distance between this color and another
    • ImagickPixel::setColor — Sets the color
    • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
    • ImagickPixel::setHSL — Sets the normalized HSL color
  • ImagickPixelIterator — The ImagickPixelIterator class
    • ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
    • ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
    • ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
    • ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
    • ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
    • ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
    • ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
    • ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
    • ImagickPixelIterator::resetIterator — Resets the pixel iterator
    • ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
    • ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
    • ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
    • ImagickPixelIterator::syncIterator — Syncs the pixel iterator
GmagickPixel::setcolorvalue
Wstęp
Przetwarzanie i generowanie obrazów


Wstęp

Imagick is a native php extension to create and modify images using the ImageMagick API.

ImageMagick® is a software suite to create, edit, and compose bitmap images.. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF.

Copyright 1999-2007 ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available.

ImageMagick
Instalacja/Konfiguracja
ImageMagick


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
ImageMagick


Wymagania

Installation requirements on Windows

Version information does not differ from that above. There are binaries available from http://www.imagemagick.org/ so that you can load this extension on Windows without need for a compiler.

Installation requirements on other platforms

PHP >= 5.1.3 and ImageMagick >= 6.2.4 is required. The amount of formats supported is by Imagick is entirely dependent upon the amount of formats supported by your ImageMagick installation. For example, Imagemagick requires ghostscript to conduct PDF operations.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/imagick.

Informacja: The official name of this extension is imagick.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Imagick configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
imagick.locale_fix | FALSE | PHP_INI_ALL | Available since Imagick 2.1.0
imagick.progress_monitor | FALSE | PHP_INI_SYSTEM | Available since Imagick 2.2.2
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

imagick.locale_fix boolean

Fixes a drawing bug with locales that use ',' as float separators.

imagick.progress_monitor boolean

Used to enable the image progress monitor.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

COLOR_* constants

Colortype constants. These constants are mainly used with ImagickPixel.

imagick::COLOR_BLACK (integer)
Black color
imagick::COLOR_BLUE (integer)
Blue color
imagick::COLOR_CYAN (integer)
Cyan color
imagick::COLOR_GREEN (integer)
Green color
imagick::COLOR_RED (integer)
Red color
imagick::COLOR_YELLOW (integer)
Yellow color
imagick::COLOR_MAGENTA (integer)
Magenta color
imagick::COLOR_OPACITY (integer)
Color's opacity
imagick::COLOR_ALPHA (integer)
Color's alpha
imagick::COLOR_FUZZ (integer)
Color's fuzz
DISPOSE constants

Dispose type constants

imagick::DISPOSE_UNRECOGNIZED (integer)
Unrecognized dispose type
imagick::DISPOSE_UNDEFINED (integer)
Undefined dispose type
imagick::DISPOSE_NONE (integer)
No dispose type defined
imagick::DISPOSE_BACKGROUND (integer)
Dispose background
imagick::DISPOSE_PREVIOUS (integer)
Dispose previous
Composite Operator Constants
imagick::COMPOSITE_DEFAULT (integer)
The default composite operator
imagick::COMPOSITE_UNDEFINED (integer)
Undefined composite operator
imagick::COMPOSITE_NO (integer)
No composite operator defined
imagick::COMPOSITE_ADD (integer)
The result of image + image
imagick::COMPOSITE_ATOP (integer)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
imagick::COMPOSITE_BLEND (integer)
Blends the image
imagick::COMPOSITE_BUMPMAP (integer)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
imagick::COMPOSITE_CLEAR (integer)
Makes the target image transparent
imagick::COMPOSITE_COLORBURN (integer)
Darkens the destination image to reflect the source image
imagick::COMPOSITE_COLORDODGE (integer)
Brightens the destination image to reflect the source image
imagick::COMPOSITE_COLORIZE (integer)
Colorizes the target image using the composite image
imagick::COMPOSITE_COPYBLACK (integer)
Copies black from the source to target
imagick::COMPOSITE_COPYBLUE (integer)
Copies blue from the source to target
imagick::COMPOSITE_COPY (integer)
Copies the source image on the target image
imagick::COMPOSITE_COPYCYAN (integer)
Copies cyan from the source to target
imagick::COMPOSITE_COPYGREEN (integer)
Copies green from the source to target
imagick::COMPOSITE_COPYMAGENTA (integer)
Copies magenta from the source to target
imagick::COMPOSITE_COPYOPACITY (integer)
Copies opacity from the source to target
imagick::COMPOSITE_COPYRED (integer)
Copies red from the source to target
imagick::COMPOSITE_COPYYELLOW (integer)
Copies yellow from the source to target
imagick::COMPOSITE_DARKEN (integer)
Darkens the target image
imagick::COMPOSITE_DSTATOP (integer)
The part of the destination lying inside of the source is composited over the source and replaces the destination
imagick::COMPOSITE_DST (integer)
The target is left untouched
imagick::COMPOSITE_DSTIN (integer)
The parts inside the source replace the target
imagick::COMPOSITE_DSTOUT (integer)
The parts outside the source replace the target
imagick::COMPOSITE_DSTOVER (integer)
Target replaces the source
imagick::COMPOSITE_DIFFERENCE (integer)
Subtracts the darker of the two constituent colors from the lighter
imagick::COMPOSITE_DISPLACE (integer)
Shifts target image pixels as defined by the source
imagick::COMPOSITE_DISSOLVE (integer)
Dissolves the source in to the target
imagick::COMPOSITE_EXCLUSION (integer)
Produces an effect similar to that of imagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
imagick::COMPOSITE_HARDLIGHT (integer)
Multiplies or screens the colors, dependent on the source color value
imagick::COMPOSITE_HUE (integer)
Modifies the hue of the target as defined by source
imagick::COMPOSITE_IN (integer)
Composites source into the target
imagick::COMPOSITE_LIGHTEN (integer)
Lightens the target as defined by source
imagick::COMPOSITE_LUMINIZE (integer)
Luminizes the target as defined by source
imagick::COMPOSITE_MINUS (integer)
Substracts the source from the target
imagick::COMPOSITE_MODULATE (integer)
Modulates the target brightness, saturation and hue as defined by source
imagick::COMPOSITE_MULTIPLY (integer)
Multiplies the target to the source
imagick::COMPOSITE_OUT (integer)
Composites outer parts of the source on the target
imagick::COMPOSITE_OVER (integer)
Composites source over the target
imagick::COMPOSITE_OVERLAY (integer)
Overlays the source on the target
imagick::COMPOSITE_PLUS (integer)
Adds the source to the target
imagick::COMPOSITE_REPLACE (integer)
Replaces the target with the source
imagick::COMPOSITE_SATURATE (integer)
Saturates the target as defined by the source
imagick::COMPOSITE_SCREEN (integer)
The source and destination are complemented and then multiplied and then replace the destination
imagick::COMPOSITE_SOFTLIGHT (integer)
Darkens or lightens the colors, dependent on the source
imagick::COMPOSITE_SRCATOP (integer)
The part of the source lying inside of the destination is composited onto the destination
imagick::COMPOSITE_SRC (integer)
The source is copied to the destination
imagick::COMPOSITE_SRCIN (integer)
The part of the source lying inside of the destination replaces the destination
imagick::COMPOSITE_SRCOUT (integer)
The part of the source lying outside of the destination replaces the destination
imagick::COMPOSITE_SRCOVER (integer)
The source replaces the destination
imagick::COMPOSITE_SUBTRACT (integer)
Subtract the colors in the source image from the destination image
imagick::COMPOSITE_THRESHOLD (integer)
The source is composited on the target as defined by source threshold
imagick::COMPOSITE_XOR (integer)
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source
MONTAGEMODE constants

imagick::MONTAGEMODE_FRAME (integer)
imagick::MONTAGEMODE_UNFRAME (integer)
imagick::MONTAGEMODE_CONCATENATE (integer)
STYLE constants

imagick::STYLE_NORMAL (integer)
imagick::STYLE_ITALIC (integer)
imagick::STYLE_OBLIQUE (integer)
imagick::STYLE_ANY (integer)
FILTER constants

imagick::FILTER_UNDEFINED (integer)
imagick::FILTER_POINT (integer)
imagick::FILTER_BOX (integer)
imagick::FILTER_TRIANGLE (integer)
imagick::FILTER_HERMITE (integer)
imagick::FILTER_HANNING (integer)
imagick::FILTER_HAMMING (integer)
imagick::FILTER_BLACKMAN (integer)
imagick::FILTER_GAUSSIAN (integer)
imagick::FILTER_QUADRATIC (integer)
imagick::FILTER_CUBIC (integer)
imagick::FILTER_CATROM (integer)
imagick::FILTER_MITCHELL (integer)
imagick::FILTER_LANCZOS (integer)
imagick::FILTER_BESSEL (integer)
imagick::FILTER_SINC (integer)
IMGTYPE constants

imagick::IMGTYPE_UNDEFINED (integer)
imagick::IMGTYPE_BILEVEL (integer)
imagick::IMGTYPE_GRAYSCALE (integer)
imagick::IMGTYPE_GRAYSCALEMATTE (integer)
imagick::IMGTYPE_PALETTE (integer)
imagick::IMGTYPE_PALETTEMATTE (integer)
imagick::IMGTYPE_TRUECOLOR (integer)
imagick::IMGTYPE_TRUECOLORMATTE (integer)
imagick::IMGTYPE_COLORSEPARATION (integer)
imagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
imagick::IMGTYPE_OPTIMIZE (integer)
RESOLUTION constants

imagick::RESOLUTION_UNDEFINED (integer)
imagick::RESOLUTION_PIXELSPERINCH (integer)
imagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
COMPRESSION constants

imagick::COMPRESSION_UNDEFINED (integer)
imagick::COMPRESSION_NO (integer)
imagick::COMPRESSION_BZIP (integer)
imagick::COMPRESSION_FAX (integer)
imagick::COMPRESSION_GROUP4 (integer)
imagick::COMPRESSION_JPEG (integer)
imagick::COMPRESSION_JPEG2000 (integer)
imagick::COMPRESSION_LOSSLESSJPEG (integer)
imagick::COMPRESSION_LZW (integer)
imagick::COMPRESSION_RLE (integer)
imagick::COMPRESSION_ZIP (integer)
imagick::COMPRESSION_DXT1 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
imagick::COMPRESSION_DXT3 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
imagick::COMPRESSION_DXT5 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
PAINT constants

imagick::PAINT_POINT (integer)
imagick::PAINT_REPLACE (integer)
imagick::PAINT_FLOODFILL (integer)
imagick::PAINT_FILLTOBORDER (integer)
imagick::PAINT_RESET (integer)
GRAVITY constants

imagick::GRAVITY_NORTHWEST (integer)
imagick::GRAVITY_NORTH (integer)
imagick::GRAVITY_NORTHEAST (integer)
imagick::GRAVITY_WEST (integer)
imagick::GRAVITY_CENTER (integer)
imagick::GRAVITY_EAST (integer)
imagick::GRAVITY_SOUTHWEST (integer)
imagick::GRAVITY_SOUTH (integer)
imagick::GRAVITY_SOUTHEAST (integer)
STRETCH constants

imagick::STRETCH_NORMAL (integer)
imagick::STRETCH_ULTRACONDENSED (integer)
imagick::STRETCH_CONDENSED (integer)
imagick::STRETCH_SEMICONDENSED (integer)
imagick::STRETCH_SEMIEXPANDED (integer)
imagick::STRETCH_EXPANDED (integer)
imagick::STRETCH_EXTRAEXPANDED (integer)
imagick::STRETCH_ULTRAEXPANDED (integer)
imagick::STRETCH_ANY (integer)
ALIGN constants

imagick::ALIGN_UNDEFINED (integer)
imagick::ALIGN_LEFT (integer)
imagick::ALIGN_CENTER (integer)
imagick::ALIGN_RIGHT (integer)
DECORATION constants

imagick::DECORATION_NO (integer)
imagick::DECORATION_UNDERLINE (integer)
imagick::DECORATION_OVERLINE (integer)
imagick::DECORATION_LINETROUGH (integer)
NOISE constants

imagick::NOISE_UNIFORM (integer)
imagick::NOISE_GAUSSIAN (integer)
imagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer)
imagick::NOISE_IMPULSE (integer)
imagick::NOISE_LAPLACIAN (integer)
imagick::NOISE_POISSON (integer)
imagick::NOISE_RANDOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
CHANNEL constants

imagick::CHANNEL_UNDEFINED (integer)
imagick::CHANNEL_RED (integer)
imagick::CHANNEL_GRAY (integer)
imagick::CHANNEL_CYAN (integer)
imagick::CHANNEL_GREEN (integer)
imagick::CHANNEL_MAGENTA (integer)
imagick::CHANNEL_BLUE (integer)
imagick::CHANNEL_YELLOW (integer)
imagick::CHANNEL_ALPHA (integer)
imagick::CHANNEL_OPACITY (integer)
imagick::CHANNEL_MATTE (integer)
imagick::CHANNEL_BLACK (integer)
imagick::CHANNEL_INDEX (integer)
imagick::CHANNEL_ALL (integer)
imagick::CHANNEL_DEFAULT (integer)
METRIC constants

imagick::METRIC_UNDEFINED (integer)
imagick::METRIC_MEANABSOLUTEERROR (integer)
imagick::METRIC_MEANSQUAREERROR (integer)
imagick::METRIC_PEAKABSOLUTEERROR (integer)
imagick::METRIC_PEAKSIGNALTONOISERATIO (integer)
imagick::METRIC_ROOTMEANSQUAREDERROR (integer)
PIXEL constants

imagick::PIXEL_CHAR (integer)
imagick::PIXEL_DOUBLE (integer)
imagick::PIXEL_FLOAT (integer)
imagick::PIXEL_INTEGER (integer)
imagick::PIXEL_LONG (integer)
imagick::PIXEL_QUANTUM (integer)
imagick::PIXEL_SHORT (integer)
EVALUATE constants

imagick::EVALUATE_UNDEFINED (integer)
imagick::EVALUATE_ADD (integer)
imagick::EVALUATE_AND (integer)
imagick::EVALUATE_DIVIDE (integer)
imagick::EVALUATE_LEFTSHIFT (integer)
imagick::EVALUATE_MAX (integer)
imagick::EVALUATE_MIN (integer)
imagick::EVALUATE_MULTIPLY (integer)
imagick::EVALUATE_OR (integer)
imagick::EVALUATE_RIGHTSHIFT (integer)
imagick::EVALUATE_SET (integer)
imagick::EVALUATE_SUBTRACT (integer)
imagick::EVALUATE_XOR (integer)
imagick::EVALUATE_POW (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_LOG (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLD (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDBLACK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDWHITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_GAUSSIANNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_IMPULSENOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_LAPLACIANNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_MULTIPLICATIVENOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_POISSONNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_UNIFORMNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_COSINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_SINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_ADDMODULUS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
COLORSPACE constants

imagick::COLORSPACE_UNDEFINED (integer)
imagick::COLORSPACE_RGB (integer)
imagick::COLORSPACE_GRAY (integer)
imagick::COLORSPACE_TRANSPARENT (integer)
imagick::COLORSPACE_OHTA (integer)
imagick::COLORSPACE_LAB (integer)
imagick::COLORSPACE_XYZ (integer)
imagick::COLORSPACE_YCBCR (integer)
imagick::COLORSPACE_YCC (integer)
imagick::COLORSPACE_YIQ (integer)
imagick::COLORSPACE_YPBPR (integer)
imagick::COLORSPACE_YUV (integer)
imagick::COLORSPACE_CMYK (integer)
imagick::COLORSPACE_SRGB (integer)
imagick::COLORSPACE_HSB (integer)
imagick::COLORSPACE_HSL (integer)
imagick::COLORSPACE_HWB (integer)
imagick::COLORSPACE_REC601LUMA (integer)
imagick::COLORSPACE_REC709LUMA (integer)
imagick::COLORSPACE_LOG (integer)
imagick::COLORSPACE_CMY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
VIRTUALPIXELMETHOD constants

imagick::VIRTUALPIXELMETHOD_UNDEFINED (integer)
imagick::VIRTUALPIXELMETHOD_BACKGROUND (integer)
imagick::VIRTUALPIXELMETHOD_CONSTANT (integer)
imagick::VIRTUALPIXELMETHOD_EDGE (integer)
imagick::VIRTUALPIXELMETHOD_MIRROR (integer)
imagick::VIRTUALPIXELMETHOD_TILE (integer)
imagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer)
imagick::VIRTUALPIXELMETHOD_MASK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_BLACK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_GRAY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_WHITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_HORIZONTALTILE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
imagick::VIRTUALPIXELMETHOD_VERTICALTILE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
PREVIEW constants

imagick::PREVIEW_UNDEFINED (integer)
imagick::PREVIEW_ROTATE (integer)
imagick::PREVIEW_SHEAR (integer)
imagick::PREVIEW_ROLL (integer)
imagick::PREVIEW_HUE (integer)
imagick::PREVIEW_SATURATION (integer)
imagick::PREVIEW_BRIGHTNESS (integer)
imagick::PREVIEW_GAMMA (integer)
imagick::PREVIEW_SPIFF (integer)
imagick::PREVIEW_DULL (integer)
imagick::PREVIEW_GRAYSCALE (integer)
imagick::PREVIEW_QUANTIZE (integer)
imagick::PREVIEW_DESPECKLE (integer)
imagick::PREVIEW_REDUCENOISE (integer)
imagick::PREVIEW_ADDNOISE (integer)
imagick::PREVIEW_SHARPEN (integer)
imagick::PREVIEW_BLUR (integer)
imagick::PREVIEW_THRESHOLD (integer)
imagick::PREVIEW_EDGEDETECT (integer)
imagick::PREVIEW_SPREAD (integer)
imagick::PREVIEW_SOLARIZE (integer)
imagick::PREVIEW_SHADE (integer)
imagick::PREVIEW_RAISE (integer)
imagick::PREVIEW_SEGMENT (integer)
imagick::PREVIEW_SWIRL (integer)
imagick::PREVIEW_IMPLODE (integer)
imagick::PREVIEW_WAVE (integer)
imagick::PREVIEW_OILPAINT (integer)
imagick::PREVIEW_CHARCOALDRAWING (integer)
imagick::PREVIEW_JPEG (integer)
RENDERINGINTENT constants

imagick::RENDERINGINTENT_UNDEFINED (integer)
imagick::RENDERINGINTENT_SATURATION (integer)
imagick::RENDERINGINTENT_PERCEPTUAL (integer)
imagick::RENDERINGINTENT_ABSOLUTE (integer)
imagick::RENDERINGINTENT_RELATIVE (integer)
INTERLACE constants

imagick::INTERLACE_UNDEFINED (integer)
imagick::INTERLACE_NO (integer)
imagick::INTERLACE_LINE (integer)
imagick::INTERLACE_PLANE (integer)
imagick::INTERLACE_PARTITION (integer)
imagick::INTERLACE_GIF (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
imagick::INTERLACE_JPEG (integer)
imagick::INTERLACE_PNG (integer)
FILLRULE constants

imagick::FILLRULE_UNDEFINED (integer)
imagick::FILLRULE_EVENODD (integer)
imagick::FILLRULE_NONZERO (integer)
PATHUNITS constants

imagick::PATHUNITS_UNDEFINED (integer)
imagick::PATHUNITS_USERSPACE (integer)
imagick::PATHUNITS_USERSPACEONUSE (integer)
imagick::PATHUNITS_OBJECTBOUNDINGBOX (integer)
LINECAP constants

imagick::LINECAP_UNDEFINED (integer)
imagick::LINECAP_BUTT (integer)
imagick::LINECAP_ROUND (integer)
imagick::LINECAP_SQUARE (integer)
LINEJOIN constants

imagick::LINEJOIN_UNDEFINED (integer)
imagick::LINEJOIN_MITER (integer)
imagick::LINEJOIN_ROUND (integer)
imagick::LINEJOIN_BEVEL (integer)
RESOURCETYPE constants

imagick::RESOURCETYPE_UNDEFINED (integer)
imagick::RESOURCETYPE_AREA (integer)
imagick::RESOURCETYPE_DISK (integer)
imagick::RESOURCETYPE_FILE (integer)
imagick::RESOURCETYPE_MAP (integer)
imagick::RESOURCETYPE_MEMORY (integer)
LAYERMETHOD constants

imagick::LAYERMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COALESCE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREANY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPARECLEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREOVERLAY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_DISPOSE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEPLUS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEIMAGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_OPTIMIZETRANS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEDUPS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEZERO (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_COMPOSITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_MERGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
imagick::LAYERMETHOD_FLATTEN (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
imagick::LAYERMETHOD_MOSAIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
ORIENTATION constants

imagick::ORIENTATION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_TOPLEFT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_TOPRIGHT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMRIGHT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMLEFT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_LEFTTOP (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_RIGHTTOP (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_RIGHTBOTTOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_LEFTBOTTOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
DISTORTION constants

imagick::DISTORTION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_AFFINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_AFFINEPROJECTION (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_ARC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVEPROJECTION (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_SCALEROTATETRANSLATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_POLAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_DEPOLAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_BARREL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_BARRELINVERSE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_SHEPARDS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_SENTINEL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
ALPHACHANNEL constants

imagick::ALPHACHANNEL_ACTIVATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_DEACTIVATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_RESET (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_SET (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_COPY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_EXTRACT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_OPAQUE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_SHAPE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_TRANSPARENT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
SPARSECOLORMETHOD constants

imagick::SPARSECOLORMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BARYCENTRIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_SPEPARDS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_VORONOI (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
FUNCTION constants

imagick::FUNCTION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
imagick::FUNCTION_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
imagick::FUNCTION_SINUSOID (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
INTERPOLATE constants

imagick::INTERPOLATE_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_AVERAGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_BICUBIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_FILTER (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_INTEGER (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_MESH (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_NEARESTNEIGHBOR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_SPLINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
DITHERMETHOD constants

imagick::DITHERMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_NO (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_RIEMERSMA (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_FLOYDSTEINBERG (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
Typy zasobów
Przykłady
ImageMagick


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
ImageMagick


Basic usage

Imagick makes image manipulation in PHP extremely easy through an OO interface. Here is a quick example on how to make a thumbnail:

Przykład #1 Creating a thumbnail in Imagick

<?php

header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');

// If 0 is provided as a width or height parameter,
// aspect ratio is maintained
$image->thumbnailImage(100, 0);

echo $image;

?>

Using SPL and other OO features supported in Imagick, it can be simple to resize all files in a directory (useful for batch resizing large digital camera images to be web viewable). Here we use resize, as we might want to retain certain meta-data:

Przykład #2 Make a thumbnail of all JPG files in a directory

<?php

$images = new Imagick(glob('images/*.JPG'));

foreach($images as $image) {

    // Providing 0 forces thumbnailImage to maintain aspect ratio
    $image->thumbnailImage(1024,0);

}

$images->writeImages();

?>

This is an example of creating a reflection of an image. The reflection is created by flipping the image and overlaying a gradient on it. Then both, the original image and the reflection is overlayed on a canvas.

Przykład #3 Creating a reflection of an image

<?php
/* Read the image */
$im = new Imagick("test.png");

/* Thumbnail the image */
$im->thumbnailImage(200, null);

/* Create a border for the image */
$im->borderImage(new ImagickPixel("white"), 5, 5);

/* Clone the image and flip it */
$reflection = $im->clone();
$reflection->flipImage();

/* Create gradient. It will be overlayed on the reflection */
$gradient = new Imagick();

/* Gradient needs to be large enough for the image and the borders */
$gradient->newPseudoImage($reflection->getImageWidth() + 10, $reflection->getImageHeight() + 10, "gradient:transparent-black");

/* Composite the gradient on the reflection */
$reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0);

/* Add some opacity. Requires ImageMagick 6.2.9 or later */
$reflection->setImageOpacity( 0.3 );

/* Create an empty canvas */
$canvas = new Imagick();

/* Canvas needs to be large enough to hold the both images */
$width = $im->getImageWidth() + 40;
$height = ($im->getImageHeight() * 2) + 30;
$canvas->newImage($width, $height, new ImagickPixel("black"));
$canvas->setImageFormat("png");

/* Composite the original image and the reflection on the canvas */
$canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10);
$canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10);

/* Output the image*/
header("Content-Type: image/png");
echo $canvas;
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Creating a reflection of an image

This example illustrates how to use fill patterns during drawing.

Przykład #4 Filling text with gradient

<?php

/* Create a new imagick object */
$im = new Imagick();

/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");

/* Create imagickdraw object */
$draw = new ImagickDraw();

/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);

/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);

/* Close the pattern */
$draw->popPattern();

/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');

/* Set font size to 52 */
$draw->setFontSize(52);

/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");

/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");

/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);

/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);

/* Set the format to PNG */
$canvas->setImageFormat('png');

/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Filling text with gradient

Working with animated GIF images

Przykład #5 Read in GIF image and resize all frames

<?php

/* Create a new imagick object and read in GIF */
$im = new Imagick("example.gif");

/* Resize all frames */
foreach ($im as $frame) {
    /* 50x50 frames */
    $frame->thumbnailImage(50, 50);

    /* Set the virtual canvas to correct size */
    $frame->setImagePage(50, 50, 0, 0);
}

/* Notice writeImages instead of writeImage */
$im->writeImages("example_small.gif", true);
?>

Przykłady
Imagick
Przykłady


The Imagick class

(No version information available, might only be in SVN)

Krótki opis klasy

Imagick implements Iterator , Traversable {
bool adaptiveBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool adaptiveResizeImage ( int $columns , int $rows [, bool $bestfit = false ] )
bool adaptiveSharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool adaptiveThresholdImage ( int $width , int $height , int $offset )
bool addImage ( Imagick $source )
bool addNoiseImage ( int $noise_type [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool affineTransformImage ( ImagickDraw $matrix )
bool animateImages ( string $x_server )
bool annotateImage ( ImagickDraw $draw_settings , float $x , float $y , float $angle , string $text )
Imagick appendImages ( bool $stack = false )
Imagick averageImages ( void )
bool blackThresholdImage ( mixed $threshold )
bool blurImage ( float $radius , float $sigma [, int $channel ] )
bool borderImage ( mixed $bordercolor , int $width , int $height )
bool charcoalImage ( float $radius , float $sigma )
bool chopImage ( int $width , int $height , int $x , int $y )
bool clear ( void )
bool clipImage ( void )
bool clipPathImage ( string $pathname , bool $inside )
Imagick clone ( void )
bool clutImage ( Imagick $lookup_table [, float $channel = Imagick::CHANNEL_DEFAULT ] )
Imagick coalesceImages ( void )
bool colorFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y )
bool colorizeImage ( mixed $colorize , mixed $opacity )
Imagick combineImages ( int $channelType )
bool commentImage ( string $comment )
array compareImageChannels ( Imagick $image , int $channelType , int $metricType )
Imagick compareImageLayers ( int $method )
array compareImages ( Imagick $compare , int $metric )
bool compositeImage ( Imagick $composite_object , int $composite , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )
__construct ( mixed $files )
bool contrastImage ( bool $sharpen )
bool contrastStretchImage ( float $black_point , float $white_point [, int $channel = Imagick::CHANNEL_ALL ] )
bool convolveImage ( array $kernel [, int $channel = Imagick::CHANNEL_ALL ] )
bool cropImage ( int $width , int $height , int $x , int $y )
bool cropThumbnailImage ( int $width , int $height )
Imagick current ( void )
bool cycleColormapImage ( int $displace )
bool decipherImage ( string $passphrase )
Imagick deconstructImages ( void )
bool deleteImageArtifact ( string $artifact )
public bool deskewImage ( float $threshold )
bool despeckleImage ( void )
bool destroy ( void )
bool displayImage ( string $servername )
bool displayImages ( string $servername )
bool distortImage ( int $method , array $arguments , bool $bestfit )
bool drawImage ( ImagickDraw $draw )
bool edgeImage ( float $radius )
bool embossImage ( float $radius , float $sigma )
bool encipherImage ( string $passphrase )
bool enhanceImage ( void )
bool equalizeImage ( void )
bool evaluateImage ( int $op , float $constant [, int $channel = Imagick::CHANNEL_ALL ] )
public array exportImagePixels ( int $x , int $y , int $width , int $height , string $map , int $STORAGE )
bool extentImage ( int $width , int $height , int $x , int $y )
Imagick flattenImages ( void )
bool flipImage ( void )
bool floodFillPaintImage ( mixed $fill , float $fuzz , mixed $target , int $x , int $y , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool flopImage ( void )
bool frameImage ( mixed $matte_color , int $width , int $height , int $inner_bevel , int $outer_bevel )
public bool functionImage ( int $function , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )
Imagick fxImage ( string $expression [, int $channel = Imagick::CHANNEL_ALL ] )
bool gammaImage ( float $gamma [, int $channel = Imagick::CHANNEL_ALL ] )
bool gaussianBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )
int getColorspace ( void )
int getCompression ( void )
int getCompressionQuality ( void )
string getCopyright ( void )
string getFilename ( void )
string getFont ( void )
string getFormat ( void )
int getGravity ( void )
string getHomeURL ( void )
Imagick getImage ( void )
int getImageAlphaChannel ( void )
string getImageArtifact ( string $artifact )
ImagickPixel getImageBackgroundColor ( void )
string getImageBlob ( void )
array getImageBluePrimary ( void )
ImagickPixel getImageBorderColor ( void )
int getImageChannelDepth ( int $channel )
float getImageChannelDistortion ( Imagick $reference , int $channel , int $metric )
float getImageChannelDistortions ( Imagick $reference , int $metric [, int $channel = Imagick::CHANNEL_DEFAULT ] )
array getImageChannelExtrema ( int $channel )
public array getImageChannelKurtosis ([ int $channel = Imagick::CHANNEL_DEFAULT ] )
array getImageChannelMean ( int $channel )
array getImageChannelRange ( int $channel )
array getImageChannelStatistics ( void )
Imagick getImageClipMask ( void )
ImagickPixel getImageColormapColor ( int $index )
int getImageColors ( void )
int getImageColorspace ( void )
int getImageCompose ( void )
int getImageCompression ( void )
int getCompressionQuality ( void )
int getImageDelay ( void )
int getImageDepth ( void )
int getImageDispose ( void )
float getImageDistortion ( MagickWand $reference , int $metric )
array getImageExtrema ( void )
string getImageFilename ( void )
string getImageFormat ( void )
float getImageGamma ( void )
array getImageGeometry ( void )
int getImageGravity ( void )
array getImageGreenPrimary ( void )
int getImageHeight ( void )
array getImageHistogram ( void )
int getImageIndex ( void )
int getImageInterlaceScheme ( void )
int getImageInterpolateMethod ( void )
int getImageIterations ( void )
int getImageLength ( void )
string getImageMagickLicense ( void )
bool getImageMatte ( void )
ImagickPixel getImageMatteColor ( void )
int getImageOrientation ( void )
array getImagePage ( void )
ImagickPixel getImagePixelColor ( int $x , int $y )
string getImageProfile ( string $name )
array getImageProfiles ([ string $pattern = "*" [, bool $only_names = true ]] )
array getImageProperties ([ string $pattern = "*" [, bool $only_names = true ]] )
string getImageProperty ( string $name )
array getImageRedPrimary ( void )
Imagick getImageRegion ( int $width , int $height , int $x , int $y )
int getImageRenderingIntent ( void )
array getImageResolution ( void )
string getImagesBlob ( void )
int getImageScene ( void )
string getImageSignature ( void )
int getImageSize ( void )
int getImageTicksPerSecond ( void )
float getImageTotalInkDensity ( void )
int getImageType ( void )
int getImageUnits ( void )
int getImageVirtualPixelMethod ( void )
array getImageWhitePoint ( void )
int getImageWidth ( void )
int getInterlaceScheme ( void )
int getIteratorIndex ( void )
int getNumberImages ( void )
string getOption ( string $key )
string getPackageName ( void )
array getPage ( void )
ImagickPixelIterator getPixelIterator ( void )
ImagickPixelIterator getPixelRegionIterator ( int $x , int $y , int $columns , int $rows )
float getPointSize ( void )
array getQuantumDepth ( void )
array getQuantumRange ( void )
string getReleaseDate ( void )
int getResource ( int $type )
int getResourceLimit ( int $type )
array getSamplingFactors ( void )
array getSize ( void )
int getSizeOffset ( void )
array getVersion ( void )
public bool haldClutImage ( Imagick $clut [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool hasNextImage ( void )
bool hasPreviousImage ( void )
array identifyImage ([ bool $appendRawOutput = false ] )
bool implodeImage ( float $radius )
public bool importImagePixels ( int $x , int $y , int $width , int $height , string $map , int $storage , array $pixels )
bool labelImage ( string $label )
bool levelImage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Imagick::CHANNEL_ALL ] )
bool linearStretchImage ( float $blackPoint , float $whitePoint )
bool liquidRescaleImage ( int $width , int $height , float $delta_x , float $rigidity )
bool magnifyImage ( void )
bool mapImage ( Imagick $map , bool $dither )
bool matteFloodfillImage ( float $alpha , float $fuzz , mixed $bordercolor , int $x , int $y )
bool medianFilterImage ( float $radius )
bool mergeImageLayers ( int $layer_method )
bool minifyImage ( void )
bool modulateImage ( float $brightness , float $saturation , float $hue )
Imagick montageImage ( ImagickDraw $draw , string $tile_geometry , string $thumbnail_geometry , int $mode , string $frame )
Imagick morphImages ( int $number_frames )
Imagick mosaicImages ( void )
bool motionBlurImage ( float $radius , float $sigma , float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool negateImage ( bool $gray [, int $channel = Imagick::CHANNEL_ALL ] )
bool newImage ( int $cols , int $rows , mixed $background [, string $format ] )
bool newPseudoImage ( int $columns , int $rows , string $pseudoString )
bool nextImage ( void )
bool normalizeImage ([ int $channel = Imagick::CHANNEL_ALL ] )
bool oilPaintImage ( float $radius )
bool opaquePaintImage ( mixed $target , mixed $fill , float $fuzz , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool optimizeImageLayers ( void )
bool orderedPosterizeImage ( string $threshold_map [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintOpaqueImage ( mixed $target , mixed $fill , float $fuzz [, int $channel = Imagick::CHANNEL_ALL ] )
bool paintTransparentImage ( mixed $target , float $alpha , float $fuzz )
bool pingImage ( string $filename )
bool pingImageBlob ( string $image )
bool pingImageFile ( resource $filehandle [, string $fileName ] )
bool polaroidImage ( ImagickDraw $properties , float $angle )
bool posterizeImage ( int $levels , bool $dither )
bool previewImages ( int $preview )
bool previousImage ( void )
bool profileImage ( string $name , string $profile )
bool quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )
bool quantizeImages ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )
array queryFontMetrics ( ImagickDraw $properties , string $text [, bool $multiline ] )
array queryFonts ([ string $pattern = "*" ] )
array queryFormats ([ string $pattern = "*" ] )
bool radialBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_ALL ] )
bool raiseImage ( int $width , int $height , int $x , int $y , bool $raise )
bool randomThresholdImage ( float $low , float $high [, int $channel = Imagick::CHANNEL_ALL ] )
bool readImage ( string $filename )
bool readImageBlob ( string $image [, string $filename ] )
bool readImageFile ( resource $filehandle [, string $fileName = null ] )
bool recolorImage ( array $matrix )
bool reduceNoiseImage ( float $radius )
public bool remapImage ( Imagick $replacement , int $DITHER )
bool removeImage ( void )
string removeImageProfile ( string $name )
bool render ( void )
bool resampleImage ( float $x_resolution , float $y_resolution , int $filter , float $blur )
bool resetImagePage ( string $page )
bool resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )
bool rollImage ( int $x , int $y )
bool rotateImage ( mixed $background , float $degrees )
bool roundCorners ( float $x_rounding , float $y_rounding [, float $stroke_width = 10 [, float $displace = 5 [, float $size_correction = -6 ]]] )
bool sampleImage ( int $columns , int $rows )
bool scaleImage ( int $cols , int $rows [, bool $bestfit = false ] )
public bool segmentImage ( int $COLORSPACE , float $cluster_threshold , float $smooth_threshold [, bool $verbose = false ] )
bool separateImageChannel ( int $channel )
bool sepiaToneImage ( float $threshold )
bool setBackgroundColor ( mixed $background )
bool setColorspace ( int $COLORSPACE )
bool setCompression ( int $compression )
bool setCompressionQuality ( int $quality )
bool setFilename ( string $filename )
bool setFirstIterator ( void )
bool setFont ( string $font )
bool setFormat ( string $format )
bool setGravity ( int $gravity )
bool setImage ( Imagick $replace )
bool setImageAlphaChannel ( int $mode )
bool setImageArtifact ( string $artifact , string $value )
bool setImageBackgroundColor ( mixed $background )
bool setImageBias ( float $bias )
bool setImageBluePrimary ( float $x , float $y )
bool setImageBorderColor ( mixed $border )
bool setImageChannelDepth ( int $channel , int $depth )
bool setImageClipMask ( Imagick $clip_mask )
bool setImageColormapColor ( int $index , ImagickPixel $color )
bool setImageColorspace ( int $colorspace )
bool setImageCompose ( int $compose )
bool setImageCompression ( int $compression )
bool setImageCompressionQuality ( int $quality )
bool setImageDelay ( int $delay )
bool setImageDepth ( int $depth )
bool setImageDispose ( int $dispose )
bool setImageExtent ( int $columns , int $rows )
bool setImageFilename ( string $filename )
bool setImageFormat ( string $format )
bool setImageGamma ( float $gamma )
bool setImageGravity ( int $gravity )
bool setImageGreenPrimary ( float $x , float $y )
bool setImageIndex ( int $index )
bool setImageInterlaceScheme ( int $interlace_scheme )
bool setImageInterpolateMethod ( int $method )
bool setImageIterations ( int $iterations )
bool setImageMatte ( bool $matte )
bool setImageMatteColor ( mixed $matte )
bool setImageOpacity ( float $opacity )
bool setImageOrientation ( int $orientation )
bool setImagePage ( int $width , int $height , int $x , int $y )
bool setImageProfile ( string $name , string $profile )
bool setImageProperty ( string $name , string $value )
bool setImageRedPrimary ( float $x , float $y )
bool setImageRenderingIntent ( int $rendering_intent )
bool setImageResolution ( float $x_resolution , float $y_resolution )
bool setImageScene ( int $scene )
bool setImageTicksPerSecond ( int $ticks_per-second )
bool setImageType ( int $image_type )
bool setImageUnits ( int $units )
bool setImageVirtualPixelMethod ( int $method )
bool setImageWhitePoint ( float $x , float $y )
bool setInterlaceScheme ( int $interlace_scheme )
bool setIteratorIndex ( int $index )
bool setLastIterator ( void )
bool setOption ( string $key , string $value )
bool setPage ( int $width , int $height , int $x , int $y )
bool setPointSize ( float $point_size )
bool setResolution ( float $x_resolution , float $y_resolution )
bool setResourceLimit ( int $type , int $limit )
bool setSamplingFactors ( array $factors )
bool setSize ( int $columns , int $rows )
bool setSizeOffset ( int $columns , int $rows , int $offset )
bool setType ( int $image_type )
bool shadeImage ( bool $gray , float $azimuth , float $elevation )
bool shadowImage ( float $opacity , float $sigma , int $x , int $y )
bool sharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )
bool shaveImage ( int $columns , int $rows )
bool shearImage ( mixed $background , float $x_shear , float $y_shear )
bool sigmoidalContrastImage ( bool $sharpen , float $alpha , float $beta [, int $channel = Imagick::CHANNEL_ALL ] )
bool sketchImage ( float $radius , float $sigma , float $angle )
bool solarizeImage ( int $threshold )
public bool sparseColorImage ( int $SPARSE_METHOD , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )
bool spliceImage ( int $width , int $height , int $x , int $y )
bool spreadImage ( float $radius )
Imagick steganoImage ( Imagick $watermark_wand , int $offset )
bool stereoImage ( Imagick $offset_wand )
bool stripImage ( void )
bool swirlImage ( float $degrees )
bool textureImage ( Imagick $texture_wand )
bool thresholdImage ( float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )
bool thumbnailImage ( int $columns , int $rows [, bool $bestfit = false [, bool $fill = false ]] )
bool tintImage ( mixed $tint , mixed $opacity )
Imagick transformImage ( string $crop , string $geometry )
bool transparentPaintImage ( mixed $target , float $alpha , float $fuzz , bool $invert )
bool transposeImage ( void )
bool transverseImage ( void )
bool trimImage ( float $fuzz )
bool uniqueImageColors ( void )
bool unsharpMaskImage ( float $radius , float $sigma , float $amount , float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )
bool valid ( void )
bool vignetteImage ( float $blackPoint , float $whitePoint , int $x , int $y )
bool waveImage ( float $amplitude , float $length )
bool whiteThresholdImage ( mixed $threshold )
bool writeImage ([ string $filename ] )
bool writeImageFile ( resource $filehandle )
bool writeImages ( string $filename , bool $adjoin )
bool writeImagesFile ( resource $filehandle )
}

Image methods and global methods

The Imagick class has the ability to hold and operate on multiple images simultaneously. This is achieved through an internal stack. There is always an internal pointer that points at the current image. Some functions operate on all images in the Imagick class, but most operate only on the current image in the internal stack. As a convention, method names can contain the word Image to denote they affect only the current image in the stack.

Class Methods

Because there are so many methods, here is a handy list of methods, somewhat reduced to their general purpose:

Class methods by purpose
Image effects | Get methods | Set methods | Read/write images | Other
Imagick::adaptiveBlurImage() | Imagick::getCompression() | Imagick::setBackgroundColor() | Imagick::__construct() | Imagick::clear()
Imagick::adaptiveResizeImage() | Imagick::getFilename() | Imagick::setCompressionQuality() | Imagick::addImage() | Imagick::clone()
Imagick::adaptiveSharpenImage() | Imagick::getFormat() | Imagick::setCompression() | Imagick::appendImages() | Imagick::current()
Imagick::adaptiveThresholdImage() | Imagick::getImageBackgroundColor() | Imagick::setFilename() | Imagick::getFilename() | Imagick::destroy()
Imagick::addNoiseImage() | Imagick::getImageBlob() | Imagick::getImagesBlob() | Imagick::setFormat() | Imagick::getFormat()
Imagick::affinetransformimage() | Imagick::getImageBluePrimary() | Imagick::setImageBackgroundColor() | Imagick::getImageFilename() | Imagick::getHomeURL()
Imagick::annotateImage() | Imagick::getImageBorderColor() | Imagick::setFirstIterator() | Imagick::getImageFormat() | Imagick::commentImage()
Imagick::averageImages() | Imagick::getImageChannelDepth() | Imagick::setImageBias() | Imagick::getImage() | Imagick::getNumberImages()
Imagick::blackThresholdImage() | Imagick::getImageChannelDistortion() | Imagick::setImageBluePrimary() | Imagick::setImageFilename() | Imagick::getReleaseDate()
Imagick::blurImage() | Imagick::getImageChannelExtrema() | Imagick::setImageBorderColor() | Imagick::setImageFormat() | Imagick::getVersion()
Imagick::borderImage() | Imagick::getImageChannelMean() | Imagick::setImageChannelDepth() | Imagick::readImageFile() | Imagick::hasNextImage()
Imagick::charcoalImage() | Imagick::getImageChannelStatistics() | Imagick::setImageColormapColor() | Imagick::readImage() | Imagick::hasPreviousImage()
Imagick::chopImage() | Imagick::getImageColormapColor() | Imagick::setImageColorSpace() | Imagick::writeImages() | Imagick::labelImage()
Imagick::clipImage() | Imagick::getImageColorspace() | Imagick::setImageCompose() | Imagick::writeImage() | Imagick::newImage()
Imagick::clipPathImage() | Imagick::getImageColors() | Imagick::setImageCompression() |  | Imagick::newPseudoImage()
Imagick::coalesceImages() | Imagick::getImageCompose() | Imagick::setImageDelay() |  | Imagick::nextImage()
Imagick::colorFloodFillImage() | Imagick::getImageDelay() | Imagick::setImageDepth() |  | Imagick::pingImageBlob()
Imagick::colorizeImage() | Imagick::getImageDepth() | Imagick::setImageDispose() |  | Imagick::pingImageFile()
Imagick::combineImages() | Imagick::getImageDispose() | Imagick::setImageDispose() |  | Imagick::pingImage()
Imagick::compareImageChannels() | Imagick::getImageDistortion() | Imagick::setImageExtent() |  | Imagick::previousImage()
Imagick::compareImageLayers() | Imagick::getImageExtrema() | Imagick::setImageFilename() |  | Imagick::profileImage()
Imagick::compositeImage() | Imagick::getImageFilename() | Imagick::setImageFormat() |  | Imagick::queryFormats()
Imagick::contrastImage() | Imagick::getImageFormat() | Imagick::setImageGamma() |  | Imagick::removeImageProfile()
Imagick::contrastStretchImage() | Imagick::getImageGamma() | Imagick::setImageGreenPrimary() |  | Imagick::removeImage()
Imagick::convolveImage() | Imagick::getImageGeometry() | Imagick::setImageIndex() |  | Imagick::setFirstIterator()
Imagick::cropImage() | Imagick::getImageGreenPrimary() | Imagick::setImageInterpolateMethod() |  | Imagick::setImageIndex()
Imagick::cycleColormapImage() | Imagick::getImageHeight() | Imagick::setImageIterations() |  | Imagick::valid()
Imagick::deconstructImages() | Imagick::getImageHistogram() | Imagick::setImageMatteColor() |  | Imagick::getCopyright()
Imagick::drawImage() | Imagick::getImageIndex() | Imagick::setImageMatte() |  |
Imagick::edgeImage() | Imagick::getImageInterlaceScheme() | Imagick::setImagePage() |  |
Imagick::embossImage() | Imagick::getImageInterpolateMethod() | Imagick::setImageProfile() |  |
Imagick::enhanceImage() | Imagick::getImageIterations() | Imagick::setImageProperty() |  |
Imagick::equalizeImage() | Imagick::getImageMatteColor() | Imagick::setImageRedPrimary() |  |
Imagick::evaluateImage() | Imagick::getImageMatte() | Imagick::setImageRenderingIntent() |  |
Imagick::flattenImages() | Imagick::getImagePage() | Imagick::setImageResolution() |  |
Imagick::flipImage() | Imagick::getImagePixelColor() | Imagick::setImageScene() |  |
Imagick::flopImage() | Imagick::getImageProfile() | Imagick::setImageTicksPerSecond() |  |
 | Imagick::getImageProperty() | Imagick::setImageType() |  |
Imagick::fxImage() | Imagick::getImageRedPrimary() | Imagick::setImageUnits() |  |
Imagick::gammaImage() | Imagick::getImageRegion() | Imagick::setImageVirtualPixelMethod() |  |
Imagick::gaussianBlurImage() | Imagick::getImageRenderingIntent() | Imagick::setImageWhitepoint() |  |
Imagick::implodeImage() | Imagick::getImageResolution() | Imagick::setInterlaceScheme() |  |
Imagick::levelImage() | Imagick::getImageScene() | Imagick::setOption() |  |
Imagick::linearStretchImage() | Imagick::getImageSignature() | Imagick::setPage() |  |
Imagick::magnifyImage() | Imagick::getImageTicksPerSecond() | Imagick::setResolution() |  |
Imagick::matteFloodFillImage() | Imagick::getImageTotalInkDensity() | Imagick::setResourceLimit() |  |
Imagick::medianFilterImage() | Imagick::getImageType() | Imagick::setSamplingFactors() |  |
Imagick::minifyImage() | Imagick::getImageUnits() | Imagick::setSizeOffset() |  |
Imagick::modulateImage() | Imagick::getImageVirtualPixelMethod() | Imagick::setSize() |  |
Imagick::montageImage() | Imagick::getImageWhitepoint() | Imagick::setType() |  |
Imagick::morphImages() | Imagick::getImageWidth() |  |  |
Imagick::mosaicImages() | Imagick::getImage() |  |  |
Imagick::motionBlurImage() | Imagick::getInterlaceScheme() |  |  |
Imagick::negateImage() | Imagick::getNumberImages() |  |  |
Imagick::normalizeImage() | Imagick::getOption() |  |  |
Imagick::oilPaintImage() | Imagick::getPackageName() |  |  |
Imagick::optimizeImageLayers() | Imagick::getPage() |  |  |
Imagick::paintOpaqueImage() | Imagick::getPixelIterator() |  |  |
Imagick::paintTransparentImage() | Imagick::getPixelRegionIterator() |  |  |
Imagick::posterizeImage() | Imagick::getQuantumDepth() |  |  |
Imagick::radialBlurImage() | Imagick::getQuantumRange() |  |  |
Imagick::raiseImage() | Imagick::getResourceLimit() |  |  |
Imagick::randomThresholdImage() | Imagick::getResource() |  |  |
Imagick::reduceNoiseImage() | Imagick::getSamplingFactors() |  |  |
Imagick::render() | Imagick::getSizeOffset() |  |  |
Imagick::resampleImage() | Imagick::getSize() |  |  |
Imagick::resizeImage() | Imagick::identifyImage() |  |  |
Imagick::rollImage() | Imagick::getImageSize() |  |  |
Imagick::rotateImage() |  |  |  |
Imagick::sampleImage() |  |  |  |
Imagick::scaleImage() |  |  |  |
Imagick::separateImageChannel() |  |  |  |
Imagick::sepiaToneImage() |  |  |  |
Imagick::shadeImage() |  |  |  |
Imagick::shadowImage() |  |  |  |
Imagick::sharpenImage() |  |  |  |
Imagick::shaveImage() |  |  |  |
Imagick::shearImage() |  |  |  |
Imagick::sigmoidalContrastImage() |  |  |  |
Imagick::sketchImage() |  |  |  |
Imagick::solarizeImage() |  |  |  |
Imagick::spliceImage() |  |  |  |
Imagick::spreadImage() |  |  |  |
Imagick::steganoImage() |  |  |  |
Imagick::stereoImage() |  |  |  |
Imagick::stripImage() |  |  |  |
Imagick::swirlImage() |  |  |  |
Imagick::textureImage() |  |  |  |
Imagick::thresholdImage() |  |  |  |
Imagick::thumbnailImage() |  |  |  |
Imagick::tintImage() |  |  |  |
Imagick::transverseImage() |  |  |  |
Imagick::trimImage() |  |  |  |
Imagick::uniqueImageColors() |  |  |  |
Imagick::unsharpMaskImage() |  |  |  |
Imagick::vignetteImage() |  |  |  |
Imagick::waveImage() |  |  |  |
Imagick::whiteThresholdImage() |  |  |  |

Spis treści

  • Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
  • Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
  • Imagick::adaptiveSharpenImage — Adaptively sharpen the image
  • Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
  • Imagick::addImage — Adds new image to Imagick object image list
  • Imagick::addNoiseImage — Adds random noise to the image
  • Imagick::affineTransformImage — Transforms an image
  • Imagick::animateImages — Animates an image or images
  • Imagick::annotateImage — Annotates an image with text
  • Imagick::appendImages — Append a set of images
  • Imagick::averageImages — Average a set of images
  • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
  • Imagick::blurImage — Adds blur filter to image
  • Imagick::borderImage — Surrounds the image with a border
  • Imagick::charcoalImage — Simulates a charcoal drawing
  • Imagick::chopImage — Removes a region of an image and trims
  • Imagick::clear — Clears all resources associated to Imagick object
  • Imagick::clipImage — Clips along the first path from the 8BIM profile
  • Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
  • Imagick::clone — Makes an exact copy of the Imagick object
  • Imagick::clutImage — Replaces colors in the image
  • Imagick::coalesceImages — Composites a set of images
  • Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
  • Imagick::colorizeImage — Blends the fill color with the image
  • Imagick::combineImages — Combines one or more images into a single image
  • Imagick::commentImage — Adds a comment to your image
  • Imagick::compareImageChannels — Returns the difference in one or more images
  • Imagick::compareImageLayers — Returns the maximum bounding region between images
  • Imagick::compareImages — Compares an image to a reconstructed image
  • Imagick::compositeImage — Composite one image onto another
  • Imagick::__construct — The Imagick constructor
  • Imagick::contrastImage — Change the contrast of the image
  • Imagick::contrastStretchImage — Enhances the contrast of a color image
  • Imagick::convolveImage — Applies a custom convolution kernel to the image
  • Imagick::cropImage — Extracts a region of the image
  • Imagick::cropThumbnailImage — Creates a crop thumbnail
  • Imagick::current — Returns a reference to the current Imagick object
  • Imagick::cycleColormapImage — Displaces an image's colormap
  • Imagick::decipherImage — Deciphers an image
  • Imagick::deconstructImages — Returns certain pixel differences between images
  • Imagick::deleteImageArtifact — Delete image artifact
  • Imagick::deskewImage — Removes skew from the image
  • Imagick::despeckleImage — Reduces the speckle noise in an image
  • Imagick::destroy — Destroys the Imagick object
  • Imagick::displayImage — Displays an image
  • Imagick::displayImages — Displays an image or image sequence
  • Imagick::distortImage — Distorts an image using various distortion methods
  • Imagick::drawImage — Renders the ImagickDraw object on the current image
  • Imagick::edgeImage — Enhance edges within the image
  • Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
  • Imagick::encipherImage — Enciphers an image
  • Imagick::enhanceImage — Improves the quality of a noisy image
  • Imagick::equalizeImage — Equalizes the image histogram
  • Imagick::evaluateImage — Applies an expression to an image
  • Imagick::exportImagePixels — Exports raw image pixels
  • Imagick::extentImage — Set image size
  • Imagick::flattenImages — Merges a sequence of images
  • Imagick::flipImage — Creates a vertical mirror image
  • Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
  • Imagick::flopImage — Creates a horizontal mirror image
  • Imagick::frameImage — Adds a simulated three-dimensional border
  • Imagick::functionImage — Applies a function on the image
  • Imagick::fxImage — Evaluate expression for each pixel in the image
  • Imagick::gammaImage — Gamma-corrects an image
  • Imagick::gaussianBlurImage — Blurs an image
  • Imagick::getColorspace — Gets the colorspace
  • Imagick::getCompression — Gets the object compression type
  • Imagick::getCompressionQuality — Gets the object compression quality
  • Imagick::getCopyright — Returns the ImageMagick API copyright as a string
  • Imagick::getFilename — The filename associated with an image sequence
  • Imagick::getFont — Gets font
  • Imagick::getFormat — Returns the format of the Imagick object
  • Imagick::getGravity — Gets the gravity
  • Imagick::getHomeURL — Returns the ImageMagick home URL
  • Imagick::getImage — Returns a new Imagick object
  • Imagick::getImageAlphaChannel — Gets the image alpha channel
  • Imagick::getImageArtifact — Get image artifact
  • Imagick::getImageBackgroundColor — Returns the image background color
  • Imagick::getImageBlob — Returns the image sequence as a blob
  • Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
  • Imagick::getImageBorderColor — Returns the image border color
  • Imagick::getImageChannelDepth — Gets the depth for a particular image channel
  • Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
  • Imagick::getImageChannelDistortions — Gets channel distortions
  • Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
  • Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
  • Imagick::getImageChannelMean — Gets the mean and standard deviation
  • Imagick::getImageChannelRange — Gets channel range
  • Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
  • Imagick::getImageClipMask — Gets image clip mask
  • Imagick::getImageColormapColor — Returns the color of the specified colormap index
  • Imagick::getImageColors — Gets the number of unique colors in the image
  • Imagick::getImageColorspace — Gets the image colorspace
  • Imagick::getImageCompose — Returns the composite operator associated with the image
  • Imagick::getImageCompression — Gets the current image's compression type
  • Imagick::getImageCompressionQuality — Gets the current image's compression quality
  • Imagick::getImageDelay — Gets the image delay
  • Imagick::getImageDepth — Gets the image depth
  • Imagick::getImageDispose — Gets the image disposal method
  • Imagick::getImageDistortion — Compares an image to a reconstructed image
  • Imagick::getImageExtrema — Gets the extrema for the image
  • Imagick::getImageFilename — Returns the filename of a particular image in a sequence
  • Imagick::getImageFormat — Returns the format of a particular image in a sequence
  • Imagick::getImageGamma — Gets the image gamma
  • Imagick::getImageGeometry — Gets the width and height as an associative array
  • Imagick::getImageGravity — Gets the image gravity
  • Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
  • Imagick::getImageHeight — Returns the image height
  • Imagick::getImageHistogram — Gets the image histogram
  • Imagick::getImageIndex — Gets the index of the current active image
  • Imagick::getImageInterlaceScheme — Gets the image interlace scheme
  • Imagick::getImageInterpolateMethod — Returns the interpolation method
  • Imagick::getImageIterations — Gets the image iterations
  • Imagick::getImageLength — Returns the image length in bytes
  • Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license
  • Imagick::getImageMatte — Return if the image has a matte channel
  • Imagick::getImageMatteColor — Returns the image matte color
  • Imagick::getImageOrientation — Gets the image orientation
  • Imagick::getImagePage — Returns the page geometry
  • Imagick::getImagePixelColor — Returns the color of the specified pixel
  • Imagick::getImageProfile — Returns the named image profile
  • Imagick::getImageProfiles — Returns the image profiles
  • Imagick::getImageProperties — Returns the image properties
  • Imagick::getImageProperty — Returns the named image property
  • Imagick::getImageRedPrimary — Returns the chromaticity red primary point
  • Imagick::getImageRegion — Extracts a region of the image
  • Imagick::getImageRenderingIntent — Gets the image rendering intent
  • Imagick::getImageResolution — Gets the image X and Y resolution
  • Imagick::getImagesBlob — Returns all image sequences as a blob
  • Imagick::getImageScene — Gets the image scene
  • Imagick::getImageSignature — Generates an SHA-256 message digest
  • Imagick::getImageSize — Returns the image length in bytes
  • Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
  • Imagick::getImageTotalInkDensity — Gets the image total ink density
  • Imagick::getImageType — Gets the potential image type
  • Imagick::getImageUnits — Gets the image units of resolution
  • Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
  • Imagick::getImageWhitePoint — Returns the chromaticity white point
  • Imagick::getImageWidth — Returns the image width
  • Imagick::getInterlaceScheme — Gets the object interlace scheme
  • Imagick::getIteratorIndex — Gets the index of the current active image
  • Imagick::getNumberImages — Returns the number of images in the object
  • Imagick::getOption — Returns a value associated with the specified key
  • Imagick::getPackageName — Returns the ImageMagick package name
  • Imagick::getPage — Returns the page geometry
  • Imagick::getPixelIterator — Returns a MagickPixelIterator
  • Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
  • Imagick::getPointSize — Gets point size
  • Imagick::getQuantumDepth — Gets the quantum depth
  • Imagick::getQuantumRange — Returns the Imagick quantum range
  • Imagick::getReleaseDate — Returns the ImageMagick release date
  • Imagick::getResource — Returns the specified resource's memory usage
  • Imagick::getResourceLimit — Returns the specified resource limit
  • Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
  • Imagick::getSize — Returns the size associated with the Imagick object
  • Imagick::getSizeOffset — Returns the size offset
  • Imagick::getVersion — Returns the ImageMagick API version
  • Imagick::haldClutImage — Replaces colors in the image
  • Imagick::hasNextImage — Checks if the object has more images
  • Imagick::hasPreviousImage — Checks if the object has a previous image
  • Imagick::identifyImage — Identifies an image and fetches attributes
  • Imagick::implodeImage — Creates a new image as a copy
  • Imagick::importImagePixels — Imports image pixels
  • Imagick::labelImage — Adds a label to an image
  • Imagick::levelImage — Adjusts the levels of an image
  • Imagick::linearStretchImage — Stretches with saturation the image intensity
  • Imagick::liquidRescaleImage — Animates an image or images
  • Imagick::magnifyImage — Scales an image proportionally 2x
  • Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.
  • Imagick::matteFloodfillImage — Changes the transparency value of a color
  • Imagick::medianFilterImage — Applies a digital filter
  • Imagick::mergeImageLayers — Merges image layers
  • Imagick::minifyImage — Scales an image proportionally to half its size
  • Imagick::modulateImage — Control the brightness, saturation, and hue
  • Imagick::montageImage — Creates a composite image
  • Imagick::morphImages — Method morphs a set of images
  • Imagick::mosaicImages — Forms a mosaic from images
  • Imagick::motionBlurImage — Simulates motion blur
  • Imagick::negateImage — Negates the colors in the reference image
  • Imagick::newImage — Creates a new image
  • Imagick::newPseudoImage — Creates a new image
  • Imagick::nextImage — Moves to the next image
  • Imagick::normalizeImage — Enhances the contrast of a color image
  • Imagick::oilPaintImage — Simulates an oil painting
  • Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
  • Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
  • Imagick::orderedPosterizeImage — Performs an ordered dither
  • Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
  • Imagick::paintOpaqueImage — Change any pixel that matches color
  • Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
  • Imagick::pingImage — Fetch basic attributes about the image
  • Imagick::pingImageBlob — Quickly fetch attributes
  • Imagick::pingImageFile — Get basic image attributes in a lightweight manner
  • Imagick::polaroidImage — Simulates a Polaroid picture
  • Imagick::posterizeImage — Reduces the image to a limited number of color level
  • Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
  • Imagick::previousImage — Move to the previous image in the object
  • Imagick::profileImage — Adds or removes a profile from an image
  • Imagick::quantizeImage — Analyzes the colors within a reference image
  • Imagick::quantizeImages — Analyzes the colors within a sequence of images
  • Imagick::queryFontMetrics — Returns an array representing the font metrics
  • Imagick::queryFonts — Returns the configured fonts
  • Imagick::queryFormats — Returns formats supported by Imagick
  • Imagick::radialBlurImage — Radial blurs an image
  • Imagick::raiseImage — Creates a simulated 3d button-like effect
  • Imagick::randomThresholdImage — Creates a high-contrast, two-color image
  • Imagick::readImage — Reads image from filename
  • Imagick::readImageBlob — Reads image from a binary string
  • Imagick::readImageFile — Reads image from open filehandle
  • Imagick::recolorImage — Recolors image
  • Imagick::reduceNoiseImage — Smooths the contours of an image
  • Imagick::remapImage — Remaps image colors
  • Imagick::removeImage — Removes an image from the image list
  • Imagick::removeImageProfile — Removes the named image profile and returns it
  • Imagick::render — Renders all preceding drawing commands
  • Imagick::resampleImage — Resample image to desired resolution
  • Imagick::resetImagePage — Reset image page
  • Imagick::resizeImage — Scales an image
  • Imagick::rollImage — Offsets an image
  • Imagick::rotateImage — Rotates an image
  • Imagick::roundCorners — Rounds image corners
  • Imagick::sampleImage — Scales an image with pixel sampling
  • Imagick::scaleImage — Scales the size of an image
  • Imagick::segmentImage — Segments an image
  • Imagick::separateImageChannel — Separates a channel from the image
  • Imagick::sepiaToneImage — Sepia tones an image
  • Imagick::setBackgroundColor — Sets the object's default background color
  • Imagick::setColorspace — Set colorspace
  • Imagick::setCompression — Sets the object's default compression type
  • Imagick::setCompressionQuality — Sets the object's default compression quality
  • Imagick::setFilename — Sets the filename before you read or write the image
  • Imagick::setFirstIterator — Sets the Imagick iterator to the first image
  • Imagick::setFont — Sets font
  • Imagick::setFormat — Sets the format of the Imagick object
  • Imagick::setGravity — Sets the gravity
  • Imagick::setImage — Replaces image in the object
  • Imagick::setImageAlphaChannel — Sets image alpha channel
  • Imagick::setImageArtifact — Set image artifact
  • Imagick::setImageBackgroundColor — Sets the image background color
  • Imagick::setImageBias — Sets the image bias for any method that convolves an image
  • Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
  • Imagick::setImageBorderColor — Sets the image border color
  • Imagick::setImageChannelDepth — Sets the depth of a particular image channel
  • Imagick::setImageClipMask — Sets image clip mask
  • Imagick::setImageColormapColor — Sets the color of the specified colormap index
  • Imagick::setImageColorspace — Sets the image colorspace
  • Imagick::setImageCompose — Sets the image composite operator
  • Imagick::setImageCompression — Sets the image compression
  • Imagick::setImageCompressionQuality — Sets the image compression quality
  • Imagick::setImageDelay — Sets the image delay
  • Imagick::setImageDepth — Sets the image depth
  • Imagick::setImageDispose — Sets the image disposal method
  • Imagick::setImageExtent — Sets the image size
  • Imagick::setImageFilename — Sets the filename of a particular image
  • Imagick::setImageFormat — Sets the format of a particular image
  • Imagick::setImageGamma — Sets the image gamma
  • Imagick::setImageGravity — Sets the image gravity
  • Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
  • Imagick::setImageIndex — Set the iterator position
  • Imagick::setImageInterlaceScheme — Sets the image compression
  • Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
  • Imagick::setImageIterations — Sets the image iterations
  • Imagick::setImageMatte — Sets the image matte channel
  • Imagick::setImageMatteColor — Sets the image matte color
  • Imagick::setImageOpacity — Sets the image opacity level
  • Imagick::setImageOrientation — Sets the image orientation
  • Imagick::setImagePage — Sets the page geometry of the image
  • Imagick::setImageProfile — Adds a named profile to the Imagick object
  • Imagick::setImageProperty — Sets an image property
  • Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
  • Imagick::setImageRenderingIntent — Sets the image rendering intent
  • Imagick::setImageResolution — Sets the image resolution
  • Imagick::setImageScene — Sets the image scene
  • Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
  • Imagick::setImageType — Sets the image type
  • Imagick::setImageUnits — Sets the image units of resolution
  • Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
  • Imagick::setImageWhitePoint — Sets the image chromaticity white point
  • Imagick::setInterlaceScheme — Sets the image compression
  • Imagick::setIteratorIndex — Set the iterator position
  • Imagick::setLastIterator — Sets the Imagick iterator to the last image
  • Imagick::setOption — Set an option
  • Imagick::setPage — Sets the page geometry of the Imagick object
  • Imagick::setPointSize — Sets point size
  • Imagick::setResolution — Sets the image resolution
  • Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes
  • Imagick::setSamplingFactors — Sets the image sampling factors
  • Imagick::setSize — Sets the size of the Imagick object
  • Imagick::setSizeOffset — Sets the size and offset of the Imagick object
  • Imagick::setType — Sets the image type attribute
  • Imagick::shadeImage — Creates a 3D effect
  • Imagick::shadowImage — Simulates an image shadow
  • Imagick::sharpenImage — Sharpens an image
  • Imagick::shaveImage — Shaves pixels from the image edges
  • Imagick::shearImage — Creating a parallelogram
  • Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
  • Imagick::sketchImage — Simulates a pencil sketch
  • Imagick::solarizeImage — Applies a solarizing effect to the image
  • Imagick::sparseColorImage — Interpolates colors
  • Imagick::spliceImage — Splices a solid color into the image
  • Imagick::spreadImage — Randomly displaces each pixel in a block
  • Imagick::steganoImage — Hides a digital watermark within the image
  • Imagick::stereoImage — Composites two images
  • Imagick::stripImage — Strips an image of all profiles and comments
  • Imagick::swirlImage — Swirls the pixels about the center of the image
  • Imagick::textureImage — Repeatedly tiles the texture image
  • Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
  • Imagick::thumbnailImage — Changes the size of an image
  • Imagick::tintImage — Applies a color vector to each pixel in the image
  • Imagick::transformImage — Convenience method for setting crop size and the image geometry
  • Imagick::transparentPaintImage — Paints pixels transparent
  • Imagick::transposeImage — Creates a vertical mirror image
  • Imagick::transverseImage — Creates a horizontal mirror image
  • Imagick::trimImage — Remove edges from the image
  • Imagick::uniqueImageColors — Discards all but one of any pixel color
  • Imagick::unsharpMaskImage — Sharpens an image
  • Imagick::valid — Checks if the current item is valid
  • Imagick::vignetteImage — Adds vignette filter to the image
  • Imagick::waveImage — Applies wave filter to the image
  • Imagick::whiteThresholdImage — Force all pixels above the threshold into white
  • Imagick::writeImage — Writes an image to the specified filename
  • Imagick::writeImageFile — Writes an image to a filehandle
  • Imagick::writeImages — Writes an image or image sequence
  • Imagick::writeImagesFile — Writes frames to a filehandle
Basic usage
Imagick::adaptiveBlurImage
ImageMagick


Adds adaptive blur filter to image

Imagick
Imagick::adaptiveResizeImage
Imagick
PHP Manual

Imagick::adaptiveBlurImage

(PECL imagick 2.0.0)

Imagick::adaptiveBlurImage — Adds adaptive blur filter to image

Opis

bool Imagick::adaptiveBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adds an adaptive blur filter to image. The intensity of an adaptive blur depends is dramatically decreased at edge of the image, whereas a standard blur is uniform across the image. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

radius

The radius of the Gaussian, in pixels, not counting the center pixel. Provide a value of 0 and the radius will be chosen automagically.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::adaptiveBlurImage():

Adaptively blur an image, then display to the browser.

<?php

header('Content-type: image/jpeg');

$image = new Imagick('test.jpg');

$image->adaptiveBlurImage(5,3);
echo $image;

?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Using Imagick::adaptiveBlurImage()

Zobacz też:

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

Imagick
Imagick::adaptiveResizeImage
Imagick


Adaptively resize image with data dependent triangulation

Imagick::adaptiveBlurImage
Imagick::adaptiveSharpenImage
Imagick
PHP Manual

Imagick::adaptiveResizeImage

(PECL imagick 2.0.0)

Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation

Opis

bool Imagick::adaptiveResizeImage ( int $columns , int $rows [, bool $bestfit = false ] )

Adaptively resize image with data-dependent triangulation. Avoids blurring across sharp color changes. Most useful when used to shrink images slightly to a slightly smaller "web size"; may not look good when a full-sized image is adaptively resized to a thumbnail. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Informacja: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parametry

columns

The number of columns in the scaled image.

rows

The number of rows in the scaled image.

bestfit

Whether to fit the image inside a bounding box.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Added optional fit parameter.
2.1.0 | This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Przykłady

Przykład #1 Using Imagick::adaptiveResizeImage()

Resize an image to a standard size for the web. This method works best when resizing to a size only slightly smaller than the previous image size.

<?php
header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');
$image->adaptiveResizeImage(1024,768);

echo $image;
?>

Zobacz też:

  • Imagick::chopImage() - Removes a region of an image and trims
  • Imagick::cropImage() - Extracts a region of the image
  • Imagick::magnifyImage() - Scales an image proportionally 2x
  • Imagick::minifyImage() - Scales an image proportionally to half its size
  • Imagick::resizeImage() - Scales an image
  • Imagick::scaleImage() - Scales the size of an image
  • Imagick::shaveImage() - Shaves pixels from the image edges
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::trimImage() - Remove edges from the image

Imagick::adaptiveBlurImage
Imagick::adaptiveSharpenImage
Imagick


Adaptively sharpen the image

Imagick::adaptiveResizeImage
Imagick::adaptiveThresholdImage
Imagick
PHP Manual

Imagick::adaptiveSharpenImage

(PECL imagick 2.0.0)

Imagick::adaptiveSharpenImage — Adaptively sharpen the image

Opis

bool Imagick::adaptiveSharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adaptively sharpen the image by sharpening more intensely near image edges and less intensely far from edges. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

radius

The radius of the Gaussian, in pixels, not counting the center pixel. Use 0 for auto-select.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 A Imagick::adaptiveSharpenImage() example

Adaptively sharpen the image with radius 2 and sigma 1.

<?php
try {
    $image = new Imagick('image.png');
    $image->adaptiveSharpenImage(2,1);
} catch(ImagickException $e) {
    echo 'Error: ' , $e->getMessage();
    die();
}
header('Content-type: image/png');
echo $image;
?>

Zobacz też:

  • Imagick::sharpenImage() - Sharpens an image

Imagick::adaptiveResizeImage
Imagick::adaptiveThresholdImage
Imagick


Selects a threshold for each pixel based on a range of intensity

Imagick::adaptiveSharpenImage
Imagick::addImage
Imagick
PHP Manual

Imagick::adaptiveThresholdImage

(PECL imagick 2.0.0)

Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity

Opis

bool Imagick::adaptiveThresholdImage ( int $width , int $height , int $offset )

Selects an individual threshold for each pixel based on the range of intensity values in its local neighborhood. This allows for thresholding of an image whose global intensity histogram doesn't contain distinctive peaks.

Parametry

width

Width of the local neighborhood.

height

Height of the local neighborhood.

offset

The mean offset

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::adaptiveSharpenImage
Imagick::addImage
Imagick


Adds new image to Imagick object image list

Imagick::adaptiveThresholdImage
Imagick::addNoiseImage
Imagick
PHP Manual

Imagick::addImage

(PECL imagick 2.0.0)

Imagick::addImage — Adds new image to Imagick object image list

Opis

bool Imagick::addImage ( Imagick $source )

Adds new image to Imagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

Parametry

source

The source Imagick object

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::adaptiveThresholdImage
Imagick::addNoiseImage
Imagick


Adds random noise to the image

Imagick::addImage
Imagick::affineTransformImage
Imagick
PHP Manual

Imagick::addNoiseImage

(PECL imagick 2.0.0)

Imagick::addNoiseImage — Adds random noise to the image

Opis

bool Imagick::addNoiseImage ( int $noise_type [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Adds random noise to the image.

Parametry

noise_type

The type of the noise. Refer to this list of noise constants.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::addImage
Imagick::affineTransformImage
Imagick


Transforms an image

Imagick::addNoiseImage
Imagick::animateImages
Imagick
PHP Manual

Imagick::affineTransformImage

(PECL imagick 2.0.0)

Imagick::affineTransformImage — Transforms an image

Opis

bool Imagick::affineTransformImage ( ImagickDraw $matrix )

Transforms an image as dictated by the affine matrix.

Parametry

matrix

The affine matrix

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::addNoiseImage
Imagick::animateImages
Imagick


Animates an image or images

Imagick::affineTransformImage
Imagick::annotateImage
Imagick
PHP Manual

Imagick::animateImages

(No version information available, might only be in SVN)

Imagick::animateImages — Animates an image or images

Opis

bool Imagick::animateImages ( string $x_server )

This method animates the image onto a local or remote X server. This method is not available on Windows. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

x_server

X server address

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::displayImage() - Displays an image

Imagick::affineTransformImage
Imagick::annotateImage
Imagick


Annotates an image with text

Imagick::animateImages
Imagick::appendImages
Imagick
PHP Manual

Imagick::annotateImage

(PECL imagick 2.0.0)

Imagick::annotateImage — Annotates an image with text

Opis

bool Imagick::annotateImage ( ImagickDraw $draw_settings , float $x , float $y , float $angle , string $text )

Annotates an image with text.

Parametry

draw_settings

The ImagickDraw object that contains settings for drawing the text

x

Horizontal offset in pixels to the left of text

y

Vertical offset in pixels to the baseline of text

angle

The angle at which to write the text

text

The string to draw

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 Using Imagick::annotateImage():

Annotate text on an empty image

<?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(800, 75, $pixel);

/* Black text */
$draw->setFillColor('black');

/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );

/* Create text */
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog');

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;

?>

Zobacz też:

  • ImagickDraw::annotation() - Draws text on the image
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text

Imagick::animateImages
Imagick::appendImages
Imagick


Append a set of images

Imagick::annotateImage
Imagick::averageImages
Imagick
PHP Manual

Imagick::appendImages

(PECL imagick 2.0.0)

Imagick::appendImages — Append a set of images

Opis

Imagick Imagick::appendImages ( bool $stack = false )

Append a set of images into one larger image.

Parametry

stack

Whether to stack the images vertically. By default (or if FALSE is specified) images are stacked left-to-right. If stack is TRUE, images are stacked top-to-bottom.

Zwracane wartości

Returns Imagick instance on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Imagick::appendImages() example

<?php

/* Create new imagick object */
$im = new Imagick();

/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");

/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);

/* Output the image */
$combined->setImageFormat("png");
header("Content-Type: image/png");
echo $combined;
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Imagick::appendImages()

Imagick::annotateImage
Imagick::averageImages
Imagick


Average a set of images

Imagick::appendImages
Imagick::blackThresholdImage
Imagick
PHP Manual

Imagick::averageImages

(PECL imagick 2.0.0)

Imagick::averageImages — Average a set of images

Opis

Imagick Imagick::averageImages ( void )

Average a set of images.

Zwracane wartości

Returns a new Imagick object on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::appendImages
Imagick::blackThresholdImage
Imagick


Forces all pixels below the threshold into black

Imagick::averageImages
Imagick::blurImage
Imagick
PHP Manual

Imagick::blackThresholdImage

(PECL imagick 2.0.0)

Imagick::blackThresholdImage — Forces all pixels below the threshold into black

Opis

bool Imagick::blackThresholdImage ( mixed $threshold )

Is like Imagick::thresholdImage() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.

Parametry

threshold

The threshold below which everything turns black

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Imagick::averageImages
Imagick::blurImage
Imagick


Adds blur filter to image

Imagick::blackThresholdImage
Imagick::borderImage
Imagick
PHP Manual

Imagick::blurImage

(PECL imagick 2.0.0)

Imagick::blurImage — Adds blur filter to image

Opis

bool Imagick::blurImage ( float $radius , float $sigma [, int $channel ] )

Adds blur filter to image. Optional third parameter to blur a specific channel.

Parametry

radius

Blur radius

sigma

Standard deviation

channel

The Channeltype constant. When not supplied, all channels are blurred.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::blurImage():

Blur an image, then display to the browser.

<?php

header('Content-type: image/jpeg');

$image = new Imagick('test.jpg');

$image->blurImage(5,3);
echo $image;

?>

Zobacz też:

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

Imagick::blackThresholdImage
Imagick::borderImage
Imagick


Surrounds the image with a border

Imagick::blurImage
Imagick::charcoalImage
Imagick
PHP Manual

Imagick::borderImage

(PECL imagick 2.0.0)

Imagick::borderImage — Surrounds the image with a border

Opis

bool Imagick::borderImage ( mixed $bordercolor , int $width , int $height )

Surrounds the image with a border of the color defined by the bordercolor ImagickPixel object.

Parametry

bordercolor

ImagickPixel object or a string containing the border color

width

Border width

height

Border height

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::blurImage
Imagick::charcoalImage
Imagick


Simulates a charcoal drawing

Imagick::borderImage
Imagick::chopImage
Imagick
PHP Manual

Imagick::charcoalImage

(PECL imagick 2.0.0)

Imagick::charcoalImage — Simulates a charcoal drawing

Opis

bool Imagick::charcoalImage ( float $radius , float $sigma )

Simulates a charcoal drawing.

Parametry

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::borderImage
Imagick::chopImage
Imagick


Removes a region of an image and trims

Imagick::charcoalImage
Imagick::clear
Imagick
PHP Manual

Imagick::chopImage

(PECL imagick 2.0.0)

Imagick::chopImage — Removes a region of an image and trims

Opis

bool Imagick::chopImage ( int $width , int $height , int $x , int $y )

Removes a region of an image and collapses the image to occupy the removed portion.

Parametry

width

Width of the chopped area

height

Height of the chopped area

x

X origo of the chopped area

y

Y origo of the chopped area

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::chopImage():

Example of using Imagick::chopImage

<?php
/* Create some objects */
$image = new Imagick();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(400, 200, $pixel);

/* Chop image */
$image->chopImage(200, 200, 0, 0);

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;

?>

Zobacz też:

  • Imagick::cropImage() - Extracts a region of the image

Imagick::charcoalImage
Imagick::clear
Imagick


Clears all resources associated to Imagick object

Imagick::chopImage
Imagick::clipImage
Imagick
PHP Manual

Imagick::clear

(PECL imagick 2.0.0)

Imagick::clear — Clears all resources associated to Imagick object

Opis

bool Imagick::clear ( void )

Clears all resources associated to Imagick object

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::chopImage
Imagick::clipImage
Imagick


Clips along the first path from the 8BIM profile

Imagick::clear
Imagick::clipPathImage
Imagick
PHP Manual

Imagick::clipImage

(PECL imagick 2.0.0)

Imagick::clipImage — Clips along the first path from the 8BIM profile

Opis

bool Imagick::clipImage ( void )

Clips along the first path from the 8BIM profile, if present.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::clear
Imagick::clipPathImage
Imagick


Clips along the named paths from the 8BIM profile

Imagick::clipImage
Imagick::clone
Imagick
PHP Manual

Imagick::clipPathImage

(PECL imagick 2.0.0)

Imagick::clipPathImage — Clips along the named paths from the 8BIM profile

Opis

bool Imagick::clipPathImage ( string $pathname , bool $inside )

Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. It may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path.

Parametry

pathname

The name of the path

inside

If TRUE later operations take effect inside clipping path. Otherwise later operations take effect outside clipping path.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::clipImage
Imagick::clone
Imagick


Makes an exact copy of the Imagick object

Imagick::clipPathImage
Imagick::clutImage
Imagick
PHP Manual

Imagick::clone

(PECL imagick 2.0.0)

Imagick::clone — Makes an exact copy of the Imagick object

Opis

Imagick Imagick::clone ( void )

Makes an exact copy of the Imagick object.

Zwracane wartości

Nie jest zwracana żadna wartość.

Imagick::clipPathImage
Imagick::clutImage
Imagick


Replaces colors in the image

Imagick::clone
Imagick::coalesceImages
Imagick
PHP Manual

Imagick::clutImage

(PECL imagick 2.0.0)

Imagick::clutImage — Replaces colors in the image

Opis

bool Imagick::clutImage ( Imagick $lookup_table [, float $channel = Imagick::CHANNEL_DEFAULT ] )

Replaces colors in the image from a color lookup table. Optional second parameter to replace colors in a specific channel. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

lookup_table

Imagick object containing the color lookup table

channel

The Channeltype constant. When not supplied, default channels are replaced.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 Using Imagick::clutImage():

Replace colors in the image from a color lookup table.

<?php
$image = new Imagick('test.jpg');
$clut = new Imagick();
$clut->newImage(1, 1, new ImagickPixel('black'));
$image->clutImage($clut);
$image->writeImage('test_out.jpg');
?>

Zobacz też:

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

Imagick::clone
Imagick::coalesceImages
Imagick


Composites a set of images

Imagick::clutImage
Imagick::colorFloodfillImage
Imagick
PHP Manual

Imagick::coalesceImages

(PECL imagick 2.0.0)

Imagick::coalesceImages — Composites a set of images

Opis

Imagick Imagick::coalesceImages ( void )

Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. Returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence.

Zwracane wartości

Returns a new Imagick object on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::clutImage
Imagick::colorFloodfillImage
Imagick


Changes the color value of any pixel that matches target

Imagick::coalesceImages
Imagick::colorizeImage
Imagick
PHP Manual

Imagick::colorFloodfillImage

(PECL imagick 2.0.0)

Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target

Opis

bool Imagick::colorFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y )

Changes the color value of any pixel that matches target and is an immediate neighbor.

Parametry

fill

ImagickPixel object containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

bordercolor

ImagickPixel object containing the border color

x

X start position of the floodfill

y

Y start position of the floodfill

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as first and third parameter. Previous versions allow only an ImagickPixel object.

Imagick::coalesceImages
Imagick::colorizeImage
Imagick


Blends the fill color with the image

Imagick::colorFloodfillImage
Imagick::combineImages
Imagick
PHP Manual

Imagick::colorizeImage

(PECL imagick 2.0.0)

Imagick::colorizeImage — Blends the fill color with the image

Opis

bool Imagick::colorizeImage ( mixed $colorize , mixed $opacity )

Blends the fill color with each pixel in the image.

Parametry

colorize

ImagickPixel object or a string containing the colorize color

opacity

ImagickPixel object or an float containing the opacity value. 1.0 is fully opaque and 0.0 is fully transparent.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

Imagick::colorFloodfillImage
Imagick::combineImages
Imagick


Combines one or more images into a single image

Imagick::colorizeImage
Imagick::commentImage
Imagick
PHP Manual

Imagick::combineImages

(PECL imagick 2.0.0)

Imagick::combineImages — Combines one or more images into a single image

Opis

Imagick Imagick::combineImages ( int $channelType )

Combines one or more images into a single image. The grayscale value of the pixels of each image in the sequence is assigned in order to the specified channels of the combined image. The typical ordering would be image 1 => Red, 2 => Green, 3 => Blue, etc.

Parametry

channelType

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::colorizeImage
Imagick::commentImage
Imagick


Adds a comment to your image

Imagick::combineImages
Imagick::compareImageChannels
Imagick
PHP Manual

Imagick::commentImage

(PECL imagick 2.0.0)

Imagick::commentImage — Adds a comment to your image

Opis

bool Imagick::commentImage ( string $comment )

Adds a comment to your image.

Parametry

comment

The comment to add

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::commentImage():

Commenting an image and retrieving the comment:

<?php

/* Create new Imagick object */
$im = new imagick();

/* Create an empty image */
$im->newImage(100, 100, new ImagickPixel("red"));

/* Add comment to the image */
$im->commentImage("Hello World!");

/* Display the comment */
echo $im->getImageProperty("comment");

?>

Imagick::combineImages
Imagick::compareImageChannels
Imagick


Returns the difference in one or more images

Imagick::commentImage
Imagick::compareImageLayers
Imagick
PHP Manual

Imagick::compareImageChannels

(PECL imagick 2.0.0)

Imagick::compareImageChannels — Returns the difference in one or more images

Opis

array Imagick::compareImageChannels ( Imagick $image , int $channelType , int $metricType )

Compares one or more images and returns the difference image.

Parametry

image

Imagick object containing the image to compare.

channelType

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

metricType

One of the metric type constants.

Zwracane wartości

Array consisting of new_wand and distortion.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::commentImage
Imagick::compareImageLayers
Imagick


Returns the maximum bounding region between images

Imagick::compareImageChannels
Imagick::compareImages
Imagick
PHP Manual

Imagick::compareImageLayers

(PECL imagick 2.0.0)

Imagick::compareImageLayers — Returns the maximum bounding region between images

Opis

Imagick Imagick::compareImageLayers ( int $method )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

method

One of the layer method constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::compareImageLayers()

Comparing image layers

<?php
/* create new imagick object */
$im = new Imagick("test.gif");

/* optimize the image layers */
$result = $im->compareImageLayers(imagick::LAYERMETHOD_COALESCE);

/* work on the $result */
?>

Zobacz też:

  • Imagick::optimizeImageLayers() - Removes repeated portions of images to optimize
  • Imagick::writeImages() - Writes an image or image sequence
  • Imagick::writeImage() - Writes an image to the specified filename

Imagick::compareImageChannels
Imagick::compareImages
Imagick


Compares an image to a reconstructed image

Imagick::compareImageLayers
Imagick::compositeImage
Imagick
PHP Manual

Imagick::compareImages

(PECL imagick 2.0.0)

Imagick::compareImages — Compares an image to a reconstructed image

Opis

array Imagick::compareImages ( Imagick $compare , int $metric )

Returns an array containing a reconstructed image and the difference between images.

Parametry

compare

An image to compare to.

metric

Provide a valid metric type constant. Refer to this list of metric constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::compareImages():

Compare images and display the reconstructed image

<?php

$image1 = new imagick("image1.png");
$image2 = new imagick("image2.png");

$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");

header("Content-Type: image/png");
echo $result[0];

?>

Imagick::compareImageLayers
Imagick::compositeImage
Imagick


Composite one image onto another

Imagick::compareImages
Imagick::__construct
Imagick
PHP Manual

Imagick::compositeImage

(PECL imagick 2.0.0)

Imagick::compositeImage — Composite one image onto another

Opis

bool Imagick::compositeImage ( Imagick $composite_object , int $composite , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )

Composite one image onto another at the specified offset.

Parametry

composite_object

Imagick object which holds the composite image

compose

Composite operator. See Composite Operator Constants

x

The column offset of the composited image

y

The row offset of the composited image

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::compareImages
Imagick::__construct
Imagick


The Imagick constructor

Imagick::compositeImage
Imagick::contrastImage
Imagick
PHP Manual

Imagick::__construct

(PECL imagick 2.0.0)

Imagick::__construct — The Imagick constructor

Opis

Imagick::__construct ( mixed $files )

Creates an Imagick instance for a specified image or set of images.

Parametry

files

The path to an image to load or an array of paths. Paths can include wildcards for file names, or can be URLs.

Zwracane wartości

Returns a new Imagick object on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::compositeImage
Imagick::contrastImage
Imagick


Change the contrast of the image

Imagick::__construct
Imagick::contrastStretchImage
Imagick
PHP Manual

Imagick::contrastImage

(PECL imagick 2.0.0)

Imagick::contrastImage — Change the contrast of the image

Opis

bool Imagick::contrastImage ( bool $sharpen )

Enhances the intensity differences between the lighter and darker elements of the image. Set sharpen to a value other than 0 to increase the image contrast otherwise the contrast is reduced.

Parametry

sharpen

The sharpen value

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::__construct
Imagick::contrastStretchImage
Imagick


Enhances the contrast of a color image

Imagick::contrastImage
Imagick::convolveImage
Imagick
PHP Manual

Imagick::contrastStretchImage

(PECL imagick 2.0.0)

Imagick::contrastStretchImage — Enhances the contrast of a color image

Opis

bool Imagick::contrastStretchImage ( float $black_point , float $white_point [, int $channel = Imagick::CHANNEL_ALL ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

black_point

The black point.

white_point

The white point.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Imagick::CHANNEL_ALL. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::contrastImage
Imagick::convolveImage
Imagick


Applies a custom convolution kernel to the image

Imagick::contrastStretchImage
Imagick::cropImage
Imagick
PHP Manual

Imagick::convolveImage

(PECL imagick 2.0.0)

Imagick::convolveImage — Applies a custom convolution kernel to the image

Opis

bool Imagick::convolveImage ( array $kernel [, int $channel = Imagick::CHANNEL_ALL ] )

Applies a custom convolution kernel to the image.

Parametry

kernel

The convolution kernel

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::contrastStretchImage
Imagick::cropImage
Imagick


Extracts a region of the image

Imagick::convolveImage
Imagick::cropThumbnailImage
Imagick
PHP Manual

Imagick::cropImage

(PECL imagick 2.0.0)

Imagick::cropImage — Extracts a region of the image

Opis

bool Imagick::cropImage ( int $width , int $height , int $x , int $y )

Extracts a region of the image.

Parametry

width

The width of the crop

height

The height of the crop

x

The X coordinate of the cropped region's top left corner

y

The Y coordinate of the cropped region's top left corner

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::convolveImage
Imagick::cropThumbnailImage
Imagick


Creates a crop thumbnail

Imagick::cropImage
Imagick::current
Imagick
PHP Manual

Imagick::cropThumbnailImage

(PECL imagick 2.0.0)

Imagick::cropThumbnailImage — Creates a crop thumbnail

Opis

bool Imagick::cropThumbnailImage ( int $width , int $height )

Creates a fixed size thumbnail by first scaling the image up or down and cropping a specified area from the center.

Parametry

width

The width of the thumbnail

height

The Height of the thumbnail

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::cropImage
Imagick::current
Imagick


Returns a reference to the current Imagick object

Imagick::cropThumbnailImage
Imagick::cycleColormapImage
Imagick
PHP Manual

Imagick::current

(PECL imagick 2.0.0)

Imagick::current — Returns a reference to the current Imagick object

Opis

Imagick Imagick::current ( void )

Returns reference to the current imagick object with image pointer at the correct sequence.

Zwracane wartości

Returns self on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::cropThumbnailImage
Imagick::cycleColormapImage
Imagick


Displaces an image's colormap

Imagick::current
Imagick::decipherImage
Imagick
PHP Manual

Imagick::cycleColormapImage

(PECL imagick 2.0.0)

Imagick::cycleColormapImage — Displaces an image's colormap

Opis

bool Imagick::cycleColormapImage ( int $displace )

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

Parametry

displace

The amount to displace the colormap.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::current
Imagick::decipherImage
Imagick


Deciphers an image

Imagick::cycleColormapImage
Imagick::deconstructImages
Imagick
PHP Manual

Imagick::decipherImage

(No version information available, might only be in SVN)

Imagick::decipherImage — Deciphers an image

Opis

bool Imagick::decipherImage ( string $passphrase )

Deciphers image that has been enciphered before. The image must be enciphered using Imagick::encipherImage(). Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.9 lub nowszej.

Parametry

passphrase

The passphrase

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::encipherImage() - Enciphers an image

Imagick::cycleColormapImage
Imagick::deconstructImages
Imagick


Returns certain pixel differences between images

Imagick::decipherImage
Imagick::deleteImageArtifact
Imagick
PHP Manual

Imagick::deconstructImages

(PECL imagick 2.0.0)

Imagick::deconstructImages — Returns certain pixel differences between images

Opis

Imagick Imagick::deconstructImages ( void )

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

Zwracane wartości

Returns a new Imagick object on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::decipherImage
Imagick::deleteImageArtifact
Imagick


Delete image artifact

Imagick::deconstructImages
Imagick::deskewImage
Imagick
PHP Manual

Imagick::deleteImageArtifact

(No version information available, might only be in SVN)

Imagick::deleteImageArtifact — Delete image artifact

Opis

bool Imagick::deleteImageArtifact ( string $artifact )

Deletes an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.5.7 lub nowszej.

Parametry

artifact

The name of the artifact

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Zobacz też:

  • Imagick::setImageArtifact() - Set image artifact
  • Imagick::getImageArtifact() - Get image artifact

Imagick::deconstructImages
Imagick::deskewImage
Imagick


Removes skew from the image

Imagick::deleteImageArtifact
Imagick::despeckleImage
Imagick
PHP Manual

Imagick::deskewImage

(No version information available, might only be in SVN)

Imagick::deskewImage — Removes skew from the image

Opis

public bool Imagick::deskewImage ( float $threshold )

This method can be used to remove skew from for example scanned images where the paper was not properly placed on the scanning surface. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.5 lub nowszej.

Parametry

threshold

Deskew threshold

Zwracane wartości

Imagick::deleteImageArtifact
Imagick::despeckleImage
Imagick


Reduces the speckle noise in an image

Imagick::deskewImage
Imagick::destroy
Imagick
PHP Manual

Imagick::despeckleImage

(PECL imagick 2.0.0)

Imagick::despeckleImage — Reduces the speckle noise in an image

Opis

bool Imagick::despeckleImage ( void )

Reduces the speckle noise in an image while preserving the edges of the original image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::deskewImage
Imagick::destroy
Imagick


Destroys the Imagick object

Imagick::despeckleImage
Imagick::displayImage
Imagick
PHP Manual

Imagick::destroy

(PECL imagick 2.0.0)

Imagick::destroy — Destroys the Imagick object

Opis

bool Imagick::destroy ( void )

Destroys the Imagick object and frees all resources associated with it.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::despeckleImage
Imagick::displayImage
Imagick


Displays an image

Imagick::destroy
Imagick::displayImages
Imagick
PHP Manual

Imagick::displayImage

(PECL imagick 2.0.0)

Imagick::displayImage — Displays an image

Opis

bool Imagick::displayImage ( string $servername )

This method displays an image on a X server.

Parametry

servername

The X server name

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::destroy
Imagick::displayImages
Imagick


Displays an image or image sequence

Imagick::displayImage
Imagick::distortImage
Imagick
PHP Manual

Imagick::displayImages

(PECL imagick 2.0.0)

Imagick::displayImages — Displays an image or image sequence

Opis

bool Imagick::displayImages ( string $servername )

Displays an image or image sequence on a X server.

Parametry

servername

The X server name

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::displayImage
Imagick::distortImage
Imagick


Distorts an image using various distortion methods

Imagick::displayImages
Imagick::drawImage
Imagick
PHP Manual

Imagick::distortImage

(PECL imagick 2.0.1)

Imagick::distortImage — Distorts an image using various distortion methods

Opis

bool Imagick::distortImage ( int $method , array $arguments , bool $bestfit )

Distorts an image using various distortion methods, by mapping color lookups of the source image to a new destination image usually of the same size as the source image, unless 'bestfit' is set to TRUE.

If 'bestfit' is enabled, and distortion allows it, the destination image is adjusted to ensure the whole source 'image' will just fit within the final destination image, which will be sized and offset accordingly. Also in many cases the virtual offset of the source image will be taken into account in the mapping.

Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

method

The method of image distortion. See distortion constants

arguments

The arguments for this distortion method

bestfit

Attempt to resize destination to fit distorted source

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::distortImage():

Distort an image and display to the browser.

<?php
/* Create new object */
$im = new Imagick();

/* Create new checkerboard pattern */
$im->newPseudoImage(100, 100, "pattern:checkerboard");

/* Set the image format to png */
$im->setImageFormat('png');

/* Fill new visible areas with transparent */
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);

/* Activate matte */
$im->setImageMatte(true);

/* Control points for the distortion */
$controlPoints = array( 10, 10,
                        10, 5,

                        10, $im->getImageHeight() - 20,
                        10, $im->getImageHeight() - 5,

                        $im->getImageWidth() - 10, 10,
                        $im->getImageWidth() - 10, 20,

                        $im->getImageWidth() - 10, $im->getImageHeight() - 10,
                        $im->getImageWidth() - 10, $im->getImageHeight() - 30);

/* Perform the distortion */
$im->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true);

/* Ouput the image */
header("Content-Type: image/png");
echo $im;
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Using Imagick::distortImage()

Zobacz też:

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

Imagick::displayImages
Imagick::drawImage
Imagick


Renders the ImagickDraw object on the current image

Imagick::distortImage
Imagick::edgeImage
Imagick
PHP Manual

Imagick::drawImage

(PECL imagick 2.0.0)

Imagick::drawImage — Renders the ImagickDraw object on the current image

Opis

bool Imagick::drawImage ( ImagickDraw $draw )

Renders the ImagickDraw object on the current image.

Parametry

draw

The drawing operations to render on the image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::distortImage
Imagick::edgeImage
Imagick


Enhance edges within the image

Imagick::drawImage
Imagick::embossImage
Imagick
PHP Manual

Imagick::edgeImage

(PECL imagick 2.0.0)

Imagick::edgeImage — Enhance edges within the image

Opis

bool Imagick::edgeImage ( float $radius )

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

Parametry

radius

The radius of the operation.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::drawImage
Imagick::embossImage
Imagick


Returns a grayscale image with a three-dimensional effect

Imagick::edgeImage
Imagick::encipherImage
Imagick
PHP Manual

Imagick::embossImage

(PECL imagick 2.0.0)

Imagick::embossImage — Returns a grayscale image with a three-dimensional effect

Opis

bool Imagick::embossImage ( float $radius , float $sigma )

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

Parametry

radius

The radius of the effect

sigma

The sigma of the effect

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::edgeImage
Imagick::encipherImage
Imagick


Enciphers an image

Imagick::embossImage
Imagick::enhanceImage
Imagick
PHP Manual

Imagick::encipherImage

(No version information available, might only be in SVN)

Imagick::encipherImage — Enciphers an image

Opis

bool Imagick::encipherImage ( string $passphrase )

Converts plain pixels to enciphered pixels. The image is not readable until it has been deciphered using Imagick::decipherImage() Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.9 lub nowszej.

Parametry

passphrase

The passphrase

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::decipherImage() - Deciphers an image

Imagick::embossImage
Imagick::enhanceImage
Imagick


Improves the quality of a noisy image

Imagick::encipherImage
Imagick::equalizeImage
Imagick
PHP Manual

Imagick::enhanceImage

(PECL imagick 2.0.0)

Imagick::enhanceImage — Improves the quality of a noisy image

Opis

bool Imagick::enhanceImage ( void )

Applies a digital filter that improves the quality of a noisy image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::encipherImage
Imagick::equalizeImage
Imagick


Equalizes the image histogram

Imagick::enhanceImage
Imagick::evaluateImage
Imagick
PHP Manual

Imagick::equalizeImage

(PECL imagick 2.0.0)

Imagick::equalizeImage — Equalizes the image histogram

Opis

bool Imagick::equalizeImage ( void )

Equalizes the image histogram.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::enhanceImage
Imagick::evaluateImage
Imagick


Applies an expression to an image

Imagick::equalizeImage
Imagick::exportImagePixels
Imagick
PHP Manual

Imagick::evaluateImage

(PECL imagick 2.0.0)

Imagick::evaluateImage — Applies an expression to an image

Opis

bool Imagick::evaluateImage ( int $op , float $constant [, int $channel = Imagick::CHANNEL_ALL ] )

Applys an arithmetic, relational, or logical expression to an image. Use these operators to lighten or darken an image, to increase or decrease contrast in an image, or to produce the "negative" of an image.

Parametry

op

The evaluation operator

constant

The value of the operator

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Przykłady

Przykład #1 Using Imagick::evaluateImage()

Using evaluateImage to reduce opacity in an image.

<?php
// Create new object with the image
$im = new Imagick('example-alpha.png');

// Reduce the alpha by 50%
$im->evaluateImage(Imagick::EVALUATE_DIVIDE, 2, Imagick::CHANNEL_ALPHA);

// Output the image
header("Content-Type: image/png");
echo $im;
?>

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::equalizeImage
Imagick::exportImagePixels
Imagick


Exports raw image pixels

Imagick::evaluateImage
Imagick::extentImage
Imagick
PHP Manual

Imagick::exportImagePixels

(No version information available, might only be in SVN)

Imagick::exportImagePixels — Exports raw image pixels

Opis

public array Imagick::exportImagePixels ( int $x , int $y , int $width , int $height , string $map , int $STORAGE )

Exports image pixels into an array. The map defines the ordering of the exported pixels. The size of the returned array is width * height * strlen(map). Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.7 lub nowszej.

Parametry

x

X-coordinate of the exported area

y

Y-coordinate of the exported area

width

Width of the exported aread

height

Height of the exported area

map

Ordering of the exported pixels. For example "RGB". Valid characters for the map are R, G, B, A, O, C, Y, M, K, I and P.

STORAGE

Refer to this list of pixel type constants

Przykłady

Przykład #1 Using Imagick::exportImagePixels()

Export image pixels into an array

<?php

/* Create new object */
$im = new Imagick();

/* Create new image */
$im->newPseudoImage(0, 0, "magick:rose");

/* Export the image pixels */
$pixels = $im->exportImagePixels(10, 10, 2, 2, "RGB", Imagick::PIXEL_CHAR);

/* Output */
var_dump($pixels);
?>

Powyższy przykład wyświetli:

array(12) {
  [0]=>
  int(72)
  [1]=>
  int(64)
  [2]=>
  int(57)
  [3]=>
  int(69)
  [4]=>
  int(59)
  [5]=>
  int(43)
  [6]=>
  int(124)
  [7]=>
  int(120)
  [8]=>
  int(-96)
  [9]=>
  int(91)
  [10]=>
  int(84)
  [11]=>
  int(111)
}

Zwracane wartości

Returns an array containing the pixels values.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::evaluateImage
Imagick::extentImage
Imagick


Set image size

Imagick::exportImagePixels
Imagick::flattenImages
Imagick
PHP Manual

Imagick::extentImage

(No version information available, might only be in SVN)

Imagick::extentImage — Set image size

Opis

bool Imagick::extentImage ( int $width , int $height , int $x , int $y )

Comfortability method for setting image size. The method sets the image size and allows setting x,y coordinates where the new area begins. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.1 lub nowszej.

Parametry

width

The new width

height

The new height

x

X position for the new size

y

Y position for the new size

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::cropImage() - Extracts a region of the image

Imagick::exportImagePixels
Imagick::flattenImages
Imagick


Merges a sequence of images

Imagick::extentImage
Imagick::flipImage
Imagick
PHP Manual

Imagick::flattenImages

(PECL imagick 2.0.0)

Imagick::flattenImages — Merges a sequence of images

Opis

Imagick Imagick::flattenImages ( void )

Merges a sequence of images. This is useful for combining Photoshop layers into a single image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::extentImage
Imagick::flipImage
Imagick


Creates a vertical mirror image

Imagick::flattenImages
Imagick::floodFillPaintImage
Imagick
PHP Manual

Imagick::flipImage

(PECL imagick 2.0.0)

Imagick::flipImage — Creates a vertical mirror image

Opis

bool Imagick::flipImage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::flattenImages
Imagick::floodFillPaintImage
Imagick


Changes the color value of any pixel that matches target

Imagick::flipImage
Imagick::flopImage
Imagick
PHP Manual

Imagick::floodFillPaintImage

(No version information available, might only be in SVN)

Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target

Opis

bool Imagick::floodFillPaintImage ( mixed $fill , float $fuzz , mixed $target , int $x , int $y , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Changes the color value of any pixel that matches target and is an immediate neighbor. This method is a replacement for deprecated Imagick::paintFloodFillImage(). Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.8 lub nowszej.

Parametry

fill

ImagickPixel object or a string containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

target

ImagickPixel object or a string containing the target color to paint

x

X start position of the floodfill

y

Y start position of the floodfill

invert

If TRUE paints any pixel that does not match the target color.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 Imagick::floodfillPaintImage() example

<?php

/* Create new imagick object */
$im = new Imagick();

/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");

/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);

/* Save the intermediate image for comparison */
$combined->writeImage("floodfillpaint_intermediate.png");

/* The target pixel to paint */
$x = 1;
$y = 1;

/* Get the color we are painting */
$target = $combined->getImagePixelColor($x, $y);

/* Paints pixel in position 1,1 black and all neighboring
   pixels that match the target color */
$combined->floodfillPaintImage("black", 1, $target, $x, $y, false);

/* Save the result */
$combined->writeImage("floodfillpaint_result.png");
?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Imagick::floodfillPaintImage()
Output of example : Imagick::floodfillPaintImage()

Imagick::flipImage
Imagick::flopImage
Imagick


Creates a horizontal mirror image

Imagick::floodFillPaintImage
Imagick::frameImage
Imagick
PHP Manual

Imagick::flopImage

(PECL imagick 2.0.0)

Imagick::flopImage — Creates a horizontal mirror image

Opis

bool Imagick::flopImage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::floodFillPaintImage
Imagick::frameImage
Imagick


Adds a simulated three-dimensional border

Imagick::flopImage
Imagick::functionImage
Imagick
PHP Manual

Imagick::frameImage

(PECL imagick 2.0.0)

Imagick::frameImage — Adds a simulated three-dimensional border

Opis

bool Imagick::frameImage ( mixed $matte_color , int $width , int $height , int $inner_bevel , int $outer_bevel )

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

Parametry

matte_color

ImagickPixel object or a string representing the matte color

width

The width of the border

height

The height of the border

inner_bevel

The inner bevel width

outer_bevel

The outer bevel width

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::flopImage
Imagick::functionImage
Imagick


Applies a function on the image

Imagick::frameImage
Imagick::fxImage
Imagick
PHP Manual

Imagick::functionImage

(No version information available, might only be in SVN)

Imagick::functionImage — Applies a function on the image

Opis

public bool Imagick::functionImage ( int $function , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Applies an arithmetic, relational, or logical expression to an image. Use these operators to create lighter or darker versions of an image, to increase or decrease contrast in an image, or to negate the image colors. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.9 lub nowszej.

Parametry

function

Refer to this list of function constants

arguments

Array of arguments to pass to this function.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::frameImage
Imagick::fxImage
Imagick


Evaluate expression for each pixel in the image

Imagick::functionImage
Imagick::gammaImage
Imagick
PHP Manual

Imagick::fxImage

(PECL imagick 2.0.0)

Imagick::fxImage — Evaluate expression for each pixel in the image

Opis

Imagick Imagick::fxImage ( string $expression [, int $channel = Imagick::CHANNEL_ALL ] )

Evaluate expression for each pixel in the image. Consult » The Fx Special Effects Image Operator for more information.

Parametry

expression

The expression.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::functionImage
Imagick::gammaImage
Imagick


Gamma-corrects an image

Imagick::fxImage
Imagick::gaussianBlurImage
Imagick
PHP Manual

Imagick::gammaImage

(PECL imagick 2.0.0)

Imagick::gammaImage — Gamma-corrects an image

Opis

bool Imagick::gammaImage ( float $gamma [, int $channel = Imagick::CHANNEL_ALL ] )

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

Parametry

gamma

The amount of gamma-correction.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::fxImage
Imagick::gaussianBlurImage
Imagick


Blurs an image

Imagick::gammaImage
Imagick::getColorspace
Imagick
PHP Manual

Imagick::gaussianBlurImage

(PECL imagick 2.0.0)

Imagick::gaussianBlurImage — Blurs an image

Opis

bool Imagick::gaussianBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )

Blurs an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and selects a suitable radius for you.

Parametry

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::gammaImage
Imagick::getColorspace
Imagick


Gets the colorspace

Imagick::gaussianBlurImage
Imagick::getCompression
Imagick
PHP Manual

Imagick::getColorspace

(PECL imagick 0.9.10-0.9.9)

Imagick::getColorspace — Gets the colorspace

Opis

int Imagick::getColorspace ( void )

Gets the global colorspace value. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.5.7 lub nowszej.

Zwracane wartości

Returns an integer which can be compared against COLORSPACE constants.

Imagick::gaussianBlurImage
Imagick::getCompression
Imagick


Gets the object compression type

Imagick::getColorspace
Imagick::getCompressionQuality
Imagick
PHP Manual

Imagick::getCompression

(PECL imagick 2.0.0)

Imagick::getCompression — Gets the object compression type

Opis

int Imagick::getCompression ( void )

Gets the object compression type.

Zwracane wartości

Returns the compression constant

Imagick::getColorspace
Imagick::getCompressionQuality
Imagick


Gets the object compression quality

Imagick::getCompression
Imagick::getCopyright
Imagick
PHP Manual

Imagick::getCompressionQuality

(PECL imagick 2.0.0)

Imagick::getCompressionQuality — Gets the object compression quality

Opis

int Imagick::getCompressionQuality ( void )

Gets the object compression quality.

Zwracane wartości

Returns integer describing the compression quality

Imagick::getCompression
Imagick::getCopyright
Imagick


Returns the ImageMagick API copyright as a string

Imagick::getCompressionQuality
Imagick::getFilename
Imagick
PHP Manual

Imagick::getCopyright

(PECL imagick 2.0.0)

Imagick::getCopyright — Returns the ImageMagick API copyright as a string

Opis

string Imagick::getCopyright ( void )

Returns the ImageMagick API copyright as a string.

Zwracane wartości

Returns a string containing the copyright notice of Imagemagick and Magickwand C API.

Imagick::getCompressionQuality
Imagick::getFilename
Imagick


The filename associated with an image sequence

Imagick::getCopyright
Imagick::getFont
Imagick
PHP Manual

Imagick::getFilename

(PECL imagick 2.0.0)

Imagick::getFilename — The filename associated with an image sequence

Opis

string Imagick::getFilename ( void )

Returns the filename associated with an image sequence.

Zwracane wartości

Returns a string on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getCopyright
Imagick::getFont
Imagick


Gets font

Imagick::getFilename
Imagick::getFormat
Imagick
PHP Manual

Imagick::getFont

(PECL imagick 2.1.0)

Imagick::getFont — Gets font

Opis

string Imagick::getFont ( void )

Returns the objects font property. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.7 lub nowszej.

Zwracane wartości

Returns the string containing the font name or FALSE if not font is set.

Zobacz też:

  • Imagick::setFont() - Sets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

Imagick::getFilename
Imagick::getFormat
Imagick


Returns the format of the Imagick object

Imagick::getFont
Imagick::getGravity
Imagick
PHP Manual

Imagick::getFormat

(PECL imagick 2.0.0)

Imagick::getFormat — Returns the format of the Imagick object

Opis

string Imagick::getFormat ( void )

Returns the format of the Imagick object.

Zwracane wartości

Returns the format of the image.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getFont
Imagick::getGravity
Imagick


Gets the gravity

Imagick::getFormat
Imagick::getHomeURL
Imagick
PHP Manual

Imagick::getGravity

(No version information available, might only be in SVN)

Imagick::getGravity — Gets the gravity

Opis

int Imagick::getGravity ( void )

Gets the global gravity property for the Imagick object. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.0 lub nowszej.

Zwracane wartości

Returns the gravity property. Refer to the list of gravity constants.

Imagick::getFormat
Imagick::getHomeURL
Imagick


Returns the ImageMagick home URL

Imagick::getGravity
Imagick::getImage
Imagick
PHP Manual

Imagick::getHomeURL

(PECL imagick 2.0.0)

Imagick::getHomeURL — Returns the ImageMagick home URL

Opis

string Imagick::getHomeURL ( void )

Returns the ImageMagick home URL.

Zwracane wartości

Returns a link to the imagemagick homepage.

Imagick::getGravity
Imagick::getImage
Imagick


Returns a new Imagick object

Imagick::getHomeURL
Imagick::getImageAlphaChannel
Imagick
PHP Manual

Imagick::getImage

(PECL imagick 2.0.0)

Imagick::getImage — Returns a new Imagick object

Opis

Imagick Imagick::getImage ( void )

Returns a new Imagick object with the current image sequence.

Zwracane wartości

Returns a new Imagick object with the current image sequence.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getHomeURL
Imagick::getImageAlphaChannel
Imagick


Gets the image alpha channel

Imagick::getImage
Imagick::getImageArtifact
Imagick
PHP Manual

Imagick::getImageAlphaChannel

(No version information available, might only be in SVN)

Imagick::getImageAlphaChannel — Gets the image alpha channel

Opis

int Imagick::getImageAlphaChannel ( void )

Gets the image alpha channel value. The returned value is one of the alpha channel constants. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.0 lub nowszej.

Zwracane wartości

Returns a constant defining the current alpha channel value. Refer to this list of alpha channel constants.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImage
Imagick::getImageArtifact
Imagick


Get image artifact

Imagick::getImageAlphaChannel
Imagick::getImageBackgroundColor
Imagick
PHP Manual

Imagick::getImageArtifact

(No version information available, might only be in SVN)

Imagick::getImageArtifact — Get image artifact

Opis

string Imagick::getImageArtifact ( string $artifact )

Gets an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.5.7 lub nowszej.

Parametry

artifact

The name of the artifact

Zwracane wartości

Returns the artifact value on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Zobacz też:

  • Imagick::setImageArtifact() - Set image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

Imagick::getImageAlphaChannel
Imagick::getImageBackgroundColor
Imagick


Returns the image background color

Imagick::getImageArtifact
Imagick::getImageBlob
Imagick
PHP Manual

Imagick::getImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::getImageBackgroundColor — Returns the image background color

Opis

ImagickPixel Imagick::getImageBackgroundColor ( void )

Returns the image background color.

Zwracane wartości

Returns an ImagickPixel set to the background color of the image.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageArtifact
Imagick::getImageBlob
Imagick


Returns the image sequence as a blob

Imagick::getImageBackgroundColor
Imagick::getImageBluePrimary
Imagick
PHP Manual

Imagick::getImageBlob

(PECL imagick 2.0.0)

Imagick::getImageBlob — Returns the image sequence as a blob

Opis

string Imagick::getImageBlob ( void )

Implements direct to memory image formats. It returns the image sequence as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

Zwracane wartości

Returns a string containing the image.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageBackgroundColor
Imagick::getImageBluePrimary
Imagick


Returns the chromaticy blue primary point

Imagick::getImageBlob
Imagick::getImageBorderColor
Imagick
PHP Manual

Imagick::getImageBluePrimary

(PECL imagick 2.0.0)

Imagick::getImageBluePrimary — Returns the chromaticy blue primary point

Opis

array Imagick::getImageBluePrimary ( void )

Returns the chromaticity blue primary point for the image.

Parametry

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

Zwracane wartości

Array consisting of "x" and "y" coordinates of point.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageBlob
Imagick::getImageBorderColor
Imagick


Returns the image border color

Imagick::getImageBluePrimary
Imagick::getImageChannelDepth
Imagick
PHP Manual

Imagick::getImageBorderColor

(PECL imagick 2.0.0)

Imagick::getImageBorderColor — Returns the image border color

Opis

ImagickPixel Imagick::getImageBorderColor ( void )

Returns the image border color.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageBluePrimary
Imagick::getImageChannelDepth
Imagick


Gets the depth for a particular image channel

Imagick::getImageBorderColor
Imagick::getImageChannelDistortion
Imagick
PHP Manual

Imagick::getImageChannelDepth

(PECL imagick 2.0.0)

Imagick::getImageChannelDepth — Gets the depth for a particular image channel

Opis

int Imagick::getImageChannelDepth ( int $channel )

Gets the depth for a particular image channel.

Parametry

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::getImageBorderColor
Imagick::getImageChannelDistortion
Imagick


Compares image channels of an image to a reconstructed image

Imagick::getImageChannelDepth
Imagick::getImageChannelDistortions
Imagick
PHP Manual

Imagick::getImageChannelDistortion

(PECL imagick 2.0.0)

Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image

Opis

float Imagick::getImageChannelDistortion ( Imagick $reference , int $channel , int $metric )

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metric.

Parametry

reference

Imagick object to compare to.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

metric

One of the metric type constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageChannelDepth
Imagick::getImageChannelDistortions
Imagick


Gets channel distortions

Imagick::getImageChannelDistortion
Imagick::getImageChannelExtrema
Imagick
PHP Manual

Imagick::getImageChannelDistortions

(No version information available, might only be in SVN)

Imagick::getImageChannelDistortions — Gets channel distortions

Opis

float Imagick::getImageChannelDistortions ( Imagick $reference , int $metric [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metrics Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.4 lub nowszej.

Parametry

reference

Imagick object containing the reference image

metric

Refer to this list of metric type constants.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Returns a double describing the channel distortion.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageChannelDistortion
Imagick::getImageChannelExtrema
Imagick


Gets the extrema for one or more image channels

Imagick::getImageChannelDistortions
Imagick::getImageChannelKurtosis
Imagick
PHP Manual

Imagick::getImageChannelExtrema

(PECL imagick 2.0.0)

Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels

Opis

array Imagick::getImageChannelExtrema ( int $channel )

Gets the extrema for one or more image channels. Return value is an associative array with the keys "minima" and "maxima".

Parametry

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageChannelDistortions
Imagick::getImageChannelKurtosis
Imagick


The getImageChannelKurtosis purpose

Imagick::getImageChannelExtrema
Imagick::getImageChannelMean
Imagick
PHP Manual

Imagick::getImageChannelKurtosis

(No version information available, might only be in SVN)

Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose

Opis

public array Imagick::getImageChannelKurtosis ([ int $channel = Imagick::CHANNEL_DEFAULT ] )

Get the kurtosis and skewness of a specific channel. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.9 lub nowszej.

Parametry

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Returns an array with kurtosis and skewness members.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageChannelExtrema
Imagick::getImageChannelMean
Imagick


Gets the mean and standard deviation

Imagick::getImageChannelKurtosis
Imagick::getImageChannelRange
Imagick
PHP Manual

Imagick::getImageChannelMean

(PECL imagick 2.0.0)

Imagick::getImageChannelMean — Gets the mean and standard deviation

Opis

array Imagick::getImageChannelMean ( int $channel )

Gets the mean and standard deviation of one or more image channels. Return value is an associative array with the keys "mean" and "standardDeviation".

Parametry

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageChannelKurtosis
Imagick::getImageChannelRange
Imagick


Gets channel range

Imagick::getImageChannelMean
Imagick::getImageChannelStatistics
Imagick
PHP Manual

Imagick::getImageChannelRange

(PECL imagick 2.2.1)

Imagick::getImageChannelRange — Gets channel range

Opis

array Imagick::getImageChannelRange ( int $channel )

Gets the range for one or more image channels. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.0 lub nowszej.

Parametry

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Returns an array containing minima and maxima values of the channel(s).

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageChannelMean
Imagick::getImageChannelStatistics
Imagick


Returns statistics for each channel in the image

Imagick::getImageChannelRange
Imagick::getImageClipMask
Imagick
PHP Manual

Imagick::getImageChannelStatistics

(PECL imagick 2.0.0)

Imagick::getImageChannelStatistics — Returns statistics for each channel in the image

Opis

array Imagick::getImageChannelStatistics ( void )

Returns statistics for each channel in the image. The statistics include the channel depth, its minima and maxima, the mean, and the standard deviation. You can access the red channel mean, for example, like this:

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::getImageChannelRange
Imagick::getImageClipMask
Imagick


Gets image clip mask

Imagick::getImageChannelStatistics
Imagick::getImageColormapColor
Imagick
PHP Manual

Imagick::getImageClipMask

(No version information available, might only be in SVN)

Imagick::getImageClipMask — Gets image clip mask

Opis

Imagick Imagick::getImageClipMask ( void )

Returns the image clip mask. The clip mask is an Imagick object containing the clip mask. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Zwracane wartości

Returns an Imagick object containing the clip mask.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageChannelStatistics
Imagick::getImageColormapColor
Imagick


Returns the color of the specified colormap index

Imagick::getImageClipMask
Imagick::getImageColors
Imagick
PHP Manual

Imagick::getImageColormapColor

(PECL imagick 2.0.0)

Imagick::getImageColormapColor — Returns the color of the specified colormap index

Opis

ImagickPixel Imagick::getImageColormapColor ( int $index )

Returns the color of the specified colormap index.

Parametry

index

The offset into the image colormap.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageClipMask
Imagick::getImageColors
Imagick


Gets the number of unique colors in the image

Imagick::getImageColormapColor
Imagick::getImageColorspace
Imagick
PHP Manual

Imagick::getImageColors

(PECL imagick 2.0.0)

Imagick::getImageColors — Gets the number of unique colors in the image

Opis

int Imagick::getImageColors ( void )

Gets the number of unique colors in the image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::getImageColormapColor
Imagick::getImageColorspace
Imagick


Gets the image colorspace

Imagick::getImageColors
Imagick::getImageCompose
Imagick
PHP Manual

Imagick::getImageColorspace

(PECL imagick 2.0.0)

Imagick::getImageColorspace — Gets the image colorspace

Opis

int Imagick::getImageColorspace ( void )

Gets the image colorspace.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::getImageColors
Imagick::getImageCompose
Imagick


Returns the composite operator associated with the image

Imagick::getImageColorspace
Imagick::getImageCompression
Imagick
PHP Manual

Imagick::getImageCompose

(PECL imagick 2.0.0)

Imagick::getImageCompose — Returns the composite operator associated with the image

Opis

int Imagick::getImageCompose ( void )

Returns the composite operator associated with the image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::getImageColorspace
Imagick::getImageCompression
Imagick


Gets the current image's compression type

Imagick::getImageCompose
Imagick::getImageCompressionQuality
Imagick
PHP Manual

Imagick::getImageCompression

(PECL imagick 2.2.2)

Imagick::getImageCompression — Gets the current image's compression type

Opis

int Imagick::getImageCompression ( void )

Gets the current image's compression type.

Zwracane wartości

Returns the compression constant

Imagick::getImageCompose
Imagick::getImageCompressionQuality
Imagick


Gets the current image's compression quality

Imagick::getImageCompression
Imagick::getImageDelay
Imagick
PHP Manual

Imagick::getImageCompressionQuality

(PECL imagick 2.2.2)

Imagick::getImageCompressionQuality — Gets the current image's compression quality

Opis

int Imagick::getCompressionQuality ( void )

Gets the current image's compression quality

Zwracane wartości

Returns integer describing the images compression quality

Imagick::getImageCompression
Imagick::getImageDelay
Imagick


Gets the image delay

Imagick::getImageCompressionQuality
Imagick::getImageDepth
Imagick
PHP Manual

Imagick::getImageDelay

(PECL imagick 2.0.0)

Imagick::getImageDelay — Gets the image delay

Opis

int Imagick::getImageDelay ( void )

Gets the image delay.

Zwracane wartości

Returns the image delay.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageCompressionQuality
Imagick::getImageDepth
Imagick


Gets the image depth

Imagick::getImageDelay
Imagick::getImageDispose
Imagick
PHP Manual

Imagick::getImageDepth

(PECL imagick 0.9.1-0.9.9)

Imagick::getImageDepth — Gets the image depth

Opis

int Imagick::getImageDepth ( void )

Gets the image depth.

Zwracane wartości

The image depth.

Imagick::getImageDelay
Imagick::getImageDispose
Imagick


Gets the image disposal method

Imagick::getImageDepth
Imagick::getImageDistortion
Imagick
PHP Manual

Imagick::getImageDispose

(PECL imagick 2.0.0)

Imagick::getImageDispose — Gets the image disposal method

Opis

int Imagick::getImageDispose ( void )

Gets the image disposal method.

Zwracane wartości

Returns the dispose method on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageDepth
Imagick::getImageDistortion
Imagick


Compares an image to a reconstructed image

Imagick::getImageDispose
Imagick::getImageExtrema
Imagick
PHP Manual

Imagick::getImageDistortion

(PECL imagick 2.0.0)

Imagick::getImageDistortion — Compares an image to a reconstructed image

Opis

float Imagick::getImageDistortion ( MagickWand $reference , int $metric )

Compares an image to a reconstructed image and returns the specified distortion metric.

Parametry

reference

Imagick object to compare to.

metric

One of the metric type constants.

Zwracane wartości

Returns the distortion metric used on the image (or the best guess thereof).

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageDispose
Imagick::getImageExtrema
Imagick


Gets the extrema for the image

Imagick::getImageDistortion
Imagick::getImageFilename
Imagick
PHP Manual

Imagick::getImageExtrema

(PECL imagick 2.0.0)

Imagick::getImageExtrema — Gets the extrema for the image

Opis

array Imagick::getImageExtrema ( void )

Gets the extrema for the image. Returns an associative array with the keys "min" and "max".

Zwracane wartości

Returns an associative array with the keys "min" and "max".

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageDistortion
Imagick::getImageFilename
Imagick


Returns the filename of a particular image in a sequence

Imagick::getImageExtrema
Imagick::getImageFormat
Imagick
PHP Manual

Imagick::getImageFilename

(PECL imagick 2.0.0)

Imagick::getImageFilename — Returns the filename of a particular image in a sequence

Opis

string Imagick::getImageFilename ( void )

Returns the filename of a particular image in a sequence.

Zwracane wartości

Returns a string with the filename of the image.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageExtrema
Imagick::getImageFormat
Imagick


Returns the format of a particular image in a sequence

Imagick::getImageFilename
Imagick::getImageGamma
Imagick
PHP Manual

Imagick::getImageFormat

(PECL imagick 2.0.0)

Imagick::getImageFormat — Returns the format of a particular image in a sequence

Opis

string Imagick::getImageFormat ( void )

Returns the format of a particular image in a sequence.

Zwracane wartości

Returns a string containing the image format on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageFilename
Imagick::getImageGamma
Imagick


Gets the image gamma

Imagick::getImageFormat
Imagick::getImageGeometry
Imagick
PHP Manual

Imagick::getImageGamma

(PECL imagick 2.0.0)

Imagick::getImageGamma — Gets the image gamma

Opis

float Imagick::getImageGamma ( void )

Gets the image gamma.

Zwracane wartości

Returns the image gamma on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageFormat
Imagick::getImageGeometry
Imagick


Gets the width and height as an associative array

Imagick::getImageGamma
Imagick::getImageGravity
Imagick
PHP Manual

Imagick::getImageGeometry

(PECL imagick 2.0.0)

Imagick::getImageGeometry — Gets the width and height as an associative array

Opis

array Imagick::getImageGeometry ( void )

Returns the width and height as an associative array.

Zwracane wartości

Returns an array with the width/height of the image.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageGamma
Imagick::getImageGravity
Imagick


Gets the image gravity

Imagick::getImageGeometry
Imagick::getImageGreenPrimary
Imagick
PHP Manual

Imagick::getImageGravity

(No version information available, might only be in SVN)

Imagick::getImageGravity — Gets the image gravity

Opis

int Imagick::getImageGravity ( void )

Gets the current gravity value of the image. Unlike Imagick::getGravity(), this method returns the gravity defined for the current image sequence. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.4 lub nowszej.

Zwracane wartości

Returns the images gravity property. Refer to the list of gravity constants.

Imagick::getImageGeometry
Imagick::getImageGreenPrimary
Imagick


Returns the chromaticy green primary point

Imagick::getImageGravity
Imagick::getImageHeight
Imagick
PHP Manual

Imagick::getImageGreenPrimary

(PECL imagick 2.0.0)

Imagick::getImageGreenPrimary — Returns the chromaticy green primary point

Opis

array Imagick::getImageGreenPrimary ( void )

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Zwracane wartości

Returns an array with the keys "x" and "y" on success, throws an ImagickException on failure.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageGravity
Imagick::getImageHeight
Imagick


Returns the image height

Imagick::getImageGreenPrimary
Imagick::getImageHistogram
Imagick
PHP Manual

Imagick::getImageHeight

(PECL imagick 2.0.0)

Imagick::getImageHeight — Returns the image height

Opis

int Imagick::getImageHeight ( void )

Returns the image height.

Zwracane wartości

Returns the image height in pixels.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageGreenPrimary
Imagick::getImageHistogram
Imagick


Gets the image histogram

Imagick::getImageHeight
Imagick::getImageIndex
Imagick
PHP Manual

Imagick::getImageHistogram

(PECL imagick 2.0.0)

Imagick::getImageHistogram — Gets the image histogram

Opis

array Imagick::getImageHistogram ( void )

Returns the image histogram as an array of ImagickPixel objects.

Zwracane wartości

Returns the image histogram as an array of ImagickPixel objects.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageHeight
Imagick::getImageIndex
Imagick


Gets the index of the current active image

Imagick::getImageHistogram
Imagick::getImageInterlaceScheme
Imagick
PHP Manual

Imagick::getImageIndex

(PECL imagick 2.0.0)

Imagick::getImageIndex — Gets the index of the current active image

Opis

int Imagick::getImageIndex ( void )

Returns the index of the current active image within the Imagick object. This method has been deprecated. See Imagick::getIteratorIndex().

Zwracane wartości

Returns an integer containing the index of the image in the stack.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageHistogram
Imagick::getImageInterlaceScheme
Imagick


Gets the image interlace scheme

Imagick::getImageIndex
Imagick::getImageInterpolateMethod
Imagick
PHP Manual

Imagick::getImageInterlaceScheme

(PECL imagick 2.0.0)

Imagick::getImageInterlaceScheme — Gets the image interlace scheme

Opis

int Imagick::getImageInterlaceScheme ( void )

Gets the image interlace scheme.

Zwracane wartości

Returns the interlace scheme as an integer on success. Zgłasza wyjątek ImagickException gdy wystąpi błąd.

Imagick::getImageIndex
Imagick::getImageInterpolateMethod
Imagick


Returns the interpolation method

Imagick::getImageInterlaceScheme
Imagick::getImageIterations
Imagick
PHP Manual

Imagick::getImageInterpolateMethod

(PECL imagick 2.0.0)

Imagick::getImageInterpolateMethod — Returns the interpolation method

Opis

int Imagick::getImageInterpolateMethod ( void )

Returns the interpolation method for the specified image. The method is one of the Imagick::INTERPOLATE_* constants.

Zwracane wartości

Returns the interpolate method on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageInterlaceScheme
Imagick::getImageIterations
Imagick


Gets the image iterations

Imagick::getImageInterpolateMethod
Imagick::getImageLength
Imagick
PHP Manual

Imagick::getImageIterations

(PECL imagick 2.0.0)

Imagick::getImageIterations — Gets the image iterations

Opis

int Imagick::getImageIterations ( void )

Gets the image iterations.

Zwracane wartości

Returns the image iterations as an integer.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageInterpolateMethod
Imagick::getImageLength
Imagick


Returns the image length in bytes

Imagick::getImageIterations
Imagick::getImageMagickLicense
Imagick
PHP Manual

Imagick::getImageLength

(PECL imagick 2.0.0)

Imagick::getImageLength — Returns the image length in bytes

Opis

int Imagick::getImageLength ( void )

Returns the image length in bytes

Zwracane wartości

Returns an int containing the current image size.

Przykłady

Przykład #1 Using Imagick::getImageLength():

Getting image length in bytes

<?php
$image = new Imagick('test.jpg');
echo $image->getImageLength() . ' bytes';
?>

Imagick::getImageIterations
Imagick::getImageMagickLicense
Imagick


Returns a string containing the ImageMagick license

Imagick::getImageLength
Imagick::getImageMatte
Imagick
PHP Manual

Imagick::getImageMagickLicense

(PECL imagick 2.0.0)

Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license

Opis

string Imagick::getImageMagickLicense ( void )

Returns a string containing the ImageMagick license

Zwracane wartości

Returns a string containing the ImageMagick license.

Imagick::getImageLength
Imagick::getImageMatte
Imagick


Return if the image has a matte channel

Imagick::getImageMagickLicense
Imagick::getImageMatteColor
Imagick
PHP Manual

Imagick::getImageMatte

(PECL imagick 2.0.0)

Imagick::getImageMatte — Return if the image has a matte channel

Opis

bool Imagick::getImageMatte ( void )

Returns TRUE if the image has a matte channel otherwise false. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Imagick::getImageMagickLicense
Imagick::getImageMatteColor
Imagick


Returns the image matte color

Imagick::getImageMatte
Imagick::getImageOrientation
Imagick
PHP Manual

Imagick::getImageMatteColor

(PECL imagick 2.0.0)

Imagick::getImageMatteColor — Returns the image matte color

Opis

ImagickPixel Imagick::getImageMatteColor ( void )

Returns the image matte color.

Zwracane wartości

Returns ImagickPixel object on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageMatte
Imagick::getImageOrientation
Imagick


Gets the image orientation

Imagick::getImageMatteColor
Imagick::getImagePage
Imagick
PHP Manual

Imagick::getImageOrientation

(PECL imagick 2.0.0)

Imagick::getImageOrientation — Gets the image orientation

Opis

int Imagick::getImageOrientation ( void )

Gets the image orientation. The return value is one of the orientation constants.

Zwracane wartości

Returns an int on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageMatteColor
Imagick::getImagePage
Imagick


Returns the page geometry

Imagick::getImageOrientation
Imagick::getImagePixelColor
Imagick
PHP Manual

Imagick::getImagePage

(PECL imagick 2.0.0)

Imagick::getImagePage — Returns the page geometry

Opis

array Imagick::getImagePage ( void )

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

Zwracane wartości

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageOrientation
Imagick::getImagePixelColor
Imagick


Returns the color of the specified pixel

Imagick::getImagePage
Imagick::getImageProfile
Imagick
PHP Manual

Imagick::getImagePixelColor

(PECL imagick 2.0.0)

Imagick::getImagePixelColor — Returns the color of the specified pixel

Opis

ImagickPixel Imagick::getImagePixelColor ( int $x , int $y )

Returns the color of the specified pixel.

Parametry

x

The x-coordinate of the pixel

y

The y-coordinate of the pixel

Zwracane wartości

Returns an ImagickPixel instance for the color at the coordinates given.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImagePage
Imagick::getImageProfile
Imagick


Returns the named image profile

Imagick::getImagePixelColor
Imagick::getImageProfiles
Imagick
PHP Manual

Imagick::getImageProfile

(PECL imagick 2.0.0)

Imagick::getImageProfile — Returns the named image profile

Opis

string Imagick::getImageProfile ( string $name )

Returns the named image profile.

Parametry

name

The name of the profile to return.

Zwracane wartości

Returns a string containing the image profile.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImagePixelColor
Imagick::getImageProfiles
Imagick


Returns the image profiles

Imagick::getImageProfile
Imagick::getImageProperties
Imagick
PHP Manual

Imagick::getImageProfiles

(PECL imagick 2.0.0)

Imagick::getImageProfiles — Returns the image profiles

Opis

array Imagick::getImageProfiles ([ string $pattern = "*" [, bool $only_names = true ]] )

Returns all associated profiles that match the pattern. If TRUE is passed as second parameter only the profile names are returned. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

pattern

The pattern for profile names.

only_names

Whether to return only profile names. If FALSE then values are returned as well

Zwracane wartości

Returns an array containing the image profiles or profile names.

Imagick::getImageProfile
Imagick::getImageProperties
Imagick


Returns the image properties

Imagick::getImageProfiles
Imagick::getImageProperty
Imagick
PHP Manual

Imagick::getImageProperties

(PECL imagick 2.0.0)

Imagick::getImageProperties — Returns the image properties

Opis

array Imagick::getImageProperties ([ string $pattern = "*" [, bool $only_names = true ]] )

Returns all associated properties that match the pattern. If TRUE is passed as second parameter only the property names are returned. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

pattern

The pattern for property names.

only_names

Whether to return only property names. If FALSE then also the values are returned

Zwracane wartości

Returns an array containing the image properties or property names.

Przykłady

Przykład #1 Using Imagick::getImageProperties():

An example of extracting EXIF information.

<?php

/* Create the object */
$im = new imagick("/path/to/example.jpg");

/* Get the EXIF information */
$exifArray = $im->getImageProperties("exif:*");

/* Loop trough the EXIF properties */
foreach ($exifArray as $name => $property)
{
    echo "{$name} => {$property}<br />\n";
}

?>

Imagick::getImageProfiles
Imagick::getImageProperty
Imagick


Returns the named image property

Imagick::getImageProperties
Imagick::getImageRedPrimary
Imagick
PHP Manual

Imagick::getImageProperty

(PECL imagick 2.0.0)

Imagick::getImageProperty — Returns the named image property

Opis

string Imagick::getImageProperty ( string $name )

Returns the named image property. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.2 lub nowszej.

Parametry

name

name of the property (for example Exif:DateTime)

Przykłady

Przykład #1 Using Imagick::getImageProperty():

Setting and getting image property

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>

Zobacz też:

  • Imagick::setImageProperty() - Sets an image property

Zwracane wartości

Returns a string containing the image property, false if a property with the given name does not exist.

Imagick::getImageProperties
Imagick::getImageRedPrimary
Imagick


Returns the chromaticity red primary point

Imagick::getImageProperty
Imagick::getImageRegion
Imagick
PHP Manual

Imagick::getImageRedPrimary

(PECL imagick 2.0.0)

Imagick::getImageRedPrimary — Returns the chromaticity red primary point

Opis

array Imagick::getImageRedPrimary ( void )

Returns the chromaticity red primary point as an array with the keys "x" and "y".

Zwracane wartości

Returns the chromaticity red primary point as an array with the keys "x" and "y". Zgłasza wyjątek ImagickException gdy wystąpi błąd.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageProperty
Imagick::getImageRegion
Imagick


Extracts a region of the image

Imagick::getImageRedPrimary
Imagick::getImageRenderingIntent
Imagick
PHP Manual

Imagick::getImageRegion

(PECL imagick 2.0.0)

Imagick::getImageRegion — Extracts a region of the image

Opis

Imagick Imagick::getImageRegion ( int $width , int $height , int $x , int $y )

Extracts a region of the image and returns it as a new Imagick object.

Parametry

width

The width of the extracted region.

height

The height of the extracted region.

x

X-coordinate of the top-left corner of the extracted region.

y

Y-coordinate of the top-left corner of the extracted region.

Zwracane wartości

Extracts a region of the image and returns it as a new wand.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageRedPrimary
Imagick::getImageRenderingIntent
Imagick


Gets the image rendering intent

Imagick::getImageRegion
Imagick::getImageResolution
Imagick
PHP Manual

Imagick::getImageRenderingIntent

(PECL imagick 2.0.0)

Imagick::getImageRenderingIntent — Gets the image rendering intent

Opis

int Imagick::getImageRenderingIntent ( void )

Gets the image rendering intent.

Zwracane wartości

Returns the image rendering intent.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageRegion
Imagick::getImageResolution
Imagick


Gets the image X and Y resolution

Imagick::getImageRenderingIntent
Imagick::getImagesBlob
Imagick
PHP Manual

Imagick::getImageResolution

(PECL imagick 2.0.0)

Imagick::getImageResolution — Gets the image X and Y resolution

Opis

array Imagick::getImageResolution ( void )

Gets the image X and Y resolution.

Zwracane wartości

Returns the resolution as an array.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageRenderingIntent
Imagick::getImagesBlob
Imagick


Returns all image sequences as a blob

Imagick::getImageResolution
Imagick::getImageScene
Imagick
PHP Manual

Imagick::getImagesBlob

(PECL imagick 2.0.0)

Imagick::getImagesBlob — Returns all image sequences as a blob

Opis

string Imagick::getImagesBlob ( void )

Implements direct to memory image formats. It returns all image sequences as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

Zwracane wartości

Returns a string containing the images. On failure, throws ImagickException.

Imagick::getImageResolution
Imagick::getImageScene
Imagick


Gets the image scene

Imagick::getImagesBlob
Imagick::getImageSignature
Imagick
PHP Manual

Imagick::getImageScene

(PECL imagick 2.0.0)

Imagick::getImageScene — Gets the image scene

Opis

int Imagick::getImageScene ( void )

Gets the image scene.

Zwracane wartości

Returns the image scene.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImagesBlob
Imagick::getImageSignature
Imagick


Generates an SHA-256 message digest

Imagick::getImageScene
Imagick::getImageSize
Imagick
PHP Manual

Imagick::getImageSignature

(PECL imagick 2.0.0)

Imagick::getImageSignature — Generates an SHA-256 message digest

Opis

string Imagick::getImageSignature ( void )

Generates an SHA-256 message digest for the image pixel stream.

Zwracane wartości

Returns a string containing the SHA-256 hash of the file.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageScene
Imagick::getImageSize
Imagick


Returns the image length in bytes

Imagick::getImageSignature
Imagick::getImageTicksPerSecond
Imagick
PHP Manual

Imagick::getImageSize

(PECL imagick 2.0.0)

Imagick::getImageSize — Returns the image length in bytes

Opis

int Imagick::getImageSize ( void )

Returns the image length in bytes

Zwracane wartości

Returns an int containing the current image size.

Imagick::getImageSignature
Imagick::getImageTicksPerSecond
Imagick


Gets the image ticks-per-second

Imagick::getImageSize
Imagick::getImageTotalInkDensity
Imagick
PHP Manual

Imagick::getImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::getImageTicksPerSecond — Gets the image ticks-per-second

Opis

int Imagick::getImageTicksPerSecond ( void )

Gets the image ticks-per-second.

Zwracane wartości

Returns the image ticks-per-second.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageSize
Imagick::getImageTotalInkDensity
Imagick


Gets the image total ink density

Imagick::getImageTicksPerSecond
Imagick::getImageType
Imagick
PHP Manual

Imagick::getImageTotalInkDensity

(PECL imagick 2.0.0)

Imagick::getImageTotalInkDensity — Gets the image total ink density

Opis

float Imagick::getImageTotalInkDensity ( void )

Gets the image total ink density.

Zwracane wartości

Returns the image total ink density of the image. Zgłasza wyjątek ImagickException gdy wystąpi błąd.

Imagick::getImageTicksPerSecond
Imagick::getImageType
Imagick


Gets the potential image type

Imagick::getImageTotalInkDensity
Imagick::getImageUnits
Imagick
PHP Manual

Imagick::getImageType

(PECL imagick 0.9.10-0.9.9)

Imagick::getImageType — Gets the potential image type

Opis

int Imagick::getImageType ( void )

Gets the potential image type.

Zwracane wartości

Returns the potential image type.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageTotalInkDensity
Imagick::getImageUnits
Imagick


Gets the image units of resolution

Imagick::getImageType
Imagick::getImageVirtualPixelMethod
Imagick
PHP Manual

Imagick::getImageUnits

(PECL imagick 2.0.0)

Imagick::getImageUnits — Gets the image units of resolution

Opis

int Imagick::getImageUnits ( void )

Gets the image units of resolution.

Zwracane wartości

Returns the image units of resolution.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageType
Imagick::getImageVirtualPixelMethod
Imagick


Returns the virtual pixel method

Imagick::getImageUnits
Imagick::getImageWhitePoint
Imagick
PHP Manual

Imagick::getImageVirtualPixelMethod

(PECL imagick 2.0.0)

Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method

Opis

int Imagick::getImageVirtualPixelMethod ( void )

Returns the virtual pixel method for the specified image.

Zwracane wartości

Returns the virtual pixel method on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageUnits
Imagick::getImageWhitePoint
Imagick


Returns the chromaticity white point

Imagick::getImageVirtualPixelMethod
Imagick::getImageWidth
Imagick
PHP Manual

Imagick::getImageWhitePoint

(PECL imagick 2.0.0)

Imagick::getImageWhitePoint — Returns the chromaticity white point

Opis

array Imagick::getImageWhitePoint ( void )

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Zwracane wartości

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageVirtualPixelMethod
Imagick::getImageWidth
Imagick


Returns the image width

Imagick::getImageWhitePoint
Imagick::getInterlaceScheme
Imagick
PHP Manual

Imagick::getImageWidth

(PECL imagick 2.0.0)

Imagick::getImageWidth — Returns the image width

Opis

int Imagick::getImageWidth ( void )

Returns the image width.

Zwracane wartości

Returns the image width.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageWhitePoint
Imagick::getInterlaceScheme
Imagick


Gets the object interlace scheme

Imagick::getImageWidth
Imagick::getIteratorIndex
Imagick
PHP Manual

Imagick::getInterlaceScheme

(PECL imagick 2.0.0)

Imagick::getInterlaceScheme — Gets the object interlace scheme

Opis

int Imagick::getInterlaceScheme ( void )

Gets the object interlace scheme.

Zwracane wartości

Gets the wand interlace scheme.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getImageWidth
Imagick::getIteratorIndex
Imagick


Gets the index of the current active image

Imagick::getInterlaceScheme
Imagick::getNumberImages
Imagick
PHP Manual

Imagick::getIteratorIndex

(PECL imagick 2.0.0)

Imagick::getIteratorIndex — Gets the index of the current active image

Opis

int Imagick::getIteratorIndex ( void )

Returns the index of the current active image within the Imagick object. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Zwracane wartości

Returns an integer containing the index of the image in the stack.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::getIteratorIndex():

Create images, set and get the iterator index

<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));

$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>

Zobacz też:

  • Imagick::setIteratorIndex() - Set the iterator position
  • Imagick::getImageIndex() - Gets the index of the current active image
  • Imagick::setImageIndex() - Set the iterator position

Imagick::getInterlaceScheme
Imagick::getNumberImages
Imagick


Returns the number of images in the object

Imagick::getIteratorIndex
Imagick::getOption
Imagick
PHP Manual

Imagick::getNumberImages

(PECL imagick 2.0.0)

Imagick::getNumberImages — Returns the number of images in the object

Opis

int Imagick::getNumberImages ( void )

Returns the number of images associated with Imagick object.

Zwracane wartości

Returns the number of images associated with Imagick object.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getIteratorIndex
Imagick::getOption
Imagick


Returns a value associated with the specified key

Imagick::getNumberImages
Imagick::getPackageName
Imagick
PHP Manual

Imagick::getOption

(PECL imagick 2.0.0)

Imagick::getOption — Returns a value associated with the specified key

Opis

string Imagick::getOption ( string $key )

Returns a value associated within the object for the specified key.

Parametry

key

The name of the option

Zwracane wartości

Returns a value associated with a wand and the specified key.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getNumberImages
Imagick::getPackageName
Imagick


Returns the ImageMagick package name

Imagick::getOption
Imagick::getPage
Imagick
PHP Manual

Imagick::getPackageName

(PECL imagick 2.0.0)

Imagick::getPackageName — Returns the ImageMagick package name

Opis

string Imagick::getPackageName ( void )

Returns the ImageMagick package name.

Zwracane wartości

Returns the ImageMagick package name as a string.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getOption
Imagick::getPage
Imagick


Returns the page geometry

Imagick::getPackageName
Imagick::getPixelIterator
Imagick
PHP Manual

Imagick::getPage

(PECL imagick 2.0.0)

Imagick::getPage — Returns the page geometry

Opis

array Imagick::getPage ( void )

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y".

Zwracane wartości

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y", throwing ImagickException on error.

Imagick::getPackageName
Imagick::getPixelIterator
Imagick


Returns a MagickPixelIterator

Imagick::getPage
Imagick::getPixelRegionIterator
Imagick
PHP Manual

Imagick::getPixelIterator

(PECL imagick 2.0.0)

Imagick::getPixelIterator — Returns a MagickPixelIterator

Opis

ImagickPixelIterator Imagick::getPixelIterator ( void )

Returns a MagickPixelIterator.

Zwracane wartości

Returns an ImagickPixelIterator on success.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getPage
Imagick::getPixelRegionIterator
Imagick


Get an ImagickPixelIterator for an image section

Imagick::getPixelIterator
Imagick::getPointSize
Imagick
PHP Manual

Imagick::getPixelRegionIterator

(PECL imagick 2.0.0)

Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section

Opis

ImagickPixelIterator Imagick::getPixelRegionIterator ( int $x , int $y , int $columns , int $rows )

Get an ImagickPixelIterator for an image section.

Parametry

x

The x-coordinate of the region.

y

The y-coordinate of the region.

columns

The width of the region.

rows

The height of the region.

Zwracane wartości

Returns an ImagickPixelIterator for an image section.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getPixelIterator
Imagick::getPointSize
Imagick


Gets point size

Imagick::getPixelRegionIterator
Imagick::getQuantumDepth
Imagick
PHP Manual

Imagick::getPointSize

(No version information available, might only be in SVN)

Imagick::getPointSize — Gets point size

Opis

float Imagick::getPointSize ( void )

Returns the objects point size property. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.7 lub nowszej.

Zwracane wartości

Returns a float containing the point size.

Zobacz też:

  • Imagick::setPointSize() - Sets point size

Imagick::getPixelRegionIterator
Imagick::getQuantumDepth
Imagick


Gets the quantum depth

Imagick::getPointSize
Imagick::getQuantumRange
Imagick
PHP Manual

Imagick::getQuantumDepth

(PECL imagick 2.0.0)

Imagick::getQuantumDepth — Gets the quantum depth

Opis

array Imagick::getQuantumDepth ( void )

Returns the Imagick quantum depth as a string.

Zwracane wartości

Returns the Imagick quantum depth as a string.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getPointSize
Imagick::getQuantumRange
Imagick


Returns the Imagick quantum range

Imagick::getQuantumDepth
Imagick::getReleaseDate
Imagick
PHP Manual

Imagick::getQuantumRange

(PECL imagick 2.0.0)

Imagick::getQuantumRange — Returns the Imagick quantum range

Opis

array Imagick::getQuantumRange ( void )

Returns the Imagick quantum range as a string.

Zwracane wartości

Returns the Imagick quantum range as a string.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getQuantumDepth
Imagick::getReleaseDate
Imagick


Returns the ImageMagick release date

Imagick::getQuantumRange
Imagick::getResource
Imagick
PHP Manual

Imagick::getReleaseDate

(PECL imagick 2.0.0)

Imagick::getReleaseDate — Returns the ImageMagick release date

Opis

string Imagick::getReleaseDate ( void )

Returns the ImageMagick release date as a string.

Zwracane wartości

Returns the ImageMagick release date as a string.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getQuantumRange
Imagick::getResource
Imagick


Returns the specified resource's memory usage

Imagick::getReleaseDate
Imagick::getResourceLimit
Imagick
PHP Manual

Imagick::getResource

(PECL imagick 2.0.0)

Imagick::getResource — Returns the specified resource's memory usage

Opis

int Imagick::getResource ( int $type )

Returns the specified resource's memory usage in megabytes.

Parametry

type

Refer to the list of resourcetype constants.

Zwracane wartości

Returns the specified resource's memory usage in megabytes.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getReleaseDate
Imagick::getResourceLimit
Imagick


Returns the specified resource limit

Imagick::getResource
Imagick::getSamplingFactors
Imagick
PHP Manual

Imagick::getResourceLimit

(PECL imagick 2.0.0)

Imagick::getResourceLimit — Returns the specified resource limit

Opis

int Imagick::getResourceLimit ( int $type )

Returns the specified resource limit in megabytes.

Parametry

type

Refer to the list of resourcetype constants.

Zwracane wartości

Returns the specified resource limit in megabytes.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getResource
Imagick::getSamplingFactors
Imagick


Gets the horizontal and vertical sampling factor

Imagick::getResourceLimit
Imagick::getSize
Imagick
PHP Manual

Imagick::getSamplingFactors

(PECL imagick 2.0.0)

Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor

Opis

array Imagick::getSamplingFactors ( void )

Gets the horizontal and vertical sampling factor.

Zwracane wartości

Returns an associative array with the horizontal and vertical sampling factors of the image.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getResourceLimit
Imagick::getSize
Imagick


Returns the size associated with the Imagick object

Imagick::getSamplingFactors
Imagick::getSizeOffset
Imagick
PHP Manual

Imagick::getSize

(PECL imagick 2.0.0)

Imagick::getSize — Returns the size associated with the Imagick object

Opis

array Imagick::getSize ( void )

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

Zwracane wartości

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

Imagick::getSamplingFactors
Imagick::getSizeOffset
Imagick


Returns the size offset

Imagick::getSize
Imagick::getVersion
Imagick
PHP Manual

Imagick::getSizeOffset

(PECL imagick 2.0.0)

Imagick::getSizeOffset — Returns the size offset

Opis

int Imagick::getSizeOffset ( void )

Returns the size offset associated with the Imagick object. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Zwracane wartości

Returns the size offset associated with the Imagick object.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getSize
Imagick::getVersion
Imagick


Returns the ImageMagick API version

Imagick::getSizeOffset
Imagick::haldClutImage
Imagick
PHP Manual

Imagick::getVersion

(PECL imagick 2.0.0)

Imagick::getVersion — Returns the ImageMagick API version

Opis

array Imagick::getVersion ( void )

Returns the ImageMagick API version as a string and as a number.

Zwracane wartości

Returns the ImageMagick API version as a string and as a number.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getSizeOffset
Imagick::haldClutImage
Imagick


Replaces colors in the image

Imagick::getVersion
Imagick::hasNextImage
Imagick
PHP Manual

Imagick::haldClutImage

(No version information available, might only be in SVN)

Imagick::haldClutImage — Replaces colors in the image

Opis

public bool Imagick::haldClutImage ( Imagick $clut [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Replaces colors in the image using a Hald lookup table. Hald images can be created using HALD color coder.

Parametry

clut

Imagick object containing the Hald lookup image.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::getVersion
Imagick::hasNextImage
Imagick


Checks if the object has more images

Imagick::haldClutImage
Imagick::hasPreviousImage
Imagick
PHP Manual

Imagick::hasNextImage

(PECL imagick 2.0.0)

Imagick::hasNextImage — Checks if the object has more images

Opis

bool Imagick::hasNextImage ( void )

Returns TRUE if the object has more images when traversing the list in the forward direction.

Zwracane wartości

Returns TRUE if the object has more images when traversing the list in the forward direction, returns FALSE if there are none.

Imagick::haldClutImage
Imagick::hasPreviousImage
Imagick


Checks if the object has a previous image

Imagick::hasNextImage
Imagick::identifyImage
Imagick
PHP Manual

Imagick::hasPreviousImage

(PECL imagick 2.0.0)

Imagick::hasPreviousImage — Checks if the object has a previous image

Opis

bool Imagick::hasPreviousImage ( void )

Returns TRUE if the object has more images when traversing the list in the reverse direction

Zwracane wartości

Returns TRUE if the object has more images when traversing the list in the reverse direction, returns FALSE if there are none.

Imagick::hasNextImage
Imagick::identifyImage
Imagick


Identifies an image and fetches attributes

Imagick::hasPreviousImage
Imagick::implodeImage
Imagick
PHP Manual

Imagick::identifyImage

(PECL imagick 2.0.0)

Imagick::identifyImage — Identifies an image and fetches attributes

Opis

array Imagick::identifyImage ([ bool $appendRawOutput = false ] )

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

Parametry

appendRawOutput

Zwracane wartości

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::hasPreviousImage
Imagick::implodeImage
Imagick


Creates a new image as a copy

Imagick::identifyImage
Imagick::importImagePixels
Imagick
PHP Manual

Imagick::implodeImage

(PECL imagick 2.0.0)

Imagick::implodeImage — Creates a new image as a copy

Opis

bool Imagick::implodeImage ( float $radius )

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

Parametry

radius

The radius of the implode

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::identifyImage
Imagick::importImagePixels
Imagick


Imports image pixels

Imagick::implodeImage
Imagick::labelImage
Imagick
PHP Manual

Imagick::importImagePixels

(No version information available, might only be in SVN)

Imagick::importImagePixels — Imports image pixels

Opis

public bool Imagick::importImagePixels ( int $x , int $y , int $width , int $height , string $map , int $storage , array $pixels )

Imports pixels from an array into an image. The map is usually 'RGB'. This method imposes the following constraints for the parameters: amount of pixels in the array must match width x height x length of the map. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.5 lub nowszej.

Parametry

x

The image x position

y

The image y position

width

The image width

height

The image height

map

Map of pixel ordering as a string. This can be for example RGB. The value can be any combination or order of R = red, G = green, B = blue, A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, M = magenta, K = black, I = intensity (for grayscale), P = pad.

storage

The pixel storage method. Refer to this list of pixel constants.

pixels

The array of pixels

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Imagick::importImagePixels() example

<?php

/* Generate array of pixels. 2000 pixels per color stripe */
$count = 2000 * 3;

$pixels =
   array_merge(array_pad(array(), $count, 0),
               array_pad(array(), $count, 255),
               array_pad(array(), $count, 0),
               array_pad(array(), $count, 255),
               array_pad(array(), $count, 0));

/* Width and height. The area is amount of pixels divided
   by three. Three comes from 'RGB', three values per pixel */
$width = $height = pow((count($pixels) / 3), 0.5);

/* Create empty image */
$im = new Imagick();
$im->newImage($width, $height, 'gray');

/* Import the pixels into image.
   width * height * strlen("RGB") must match count($pixels) */
$im->importImagePixels(0, 0, $width, $height, "RGB", Imagick::PIXEL_CHAR, $pixels);

/* output as jpeg image */
$im->setImageFormat('jpg');
header("Content-Type: image/jpg");
echo $im;

?>

Powyższy przykład wyświetli coś podobnego do:

Output of example : Imagick::importImagePixels()

Imagick::implodeImage
Imagick::labelImage
Imagick


Adds a label to an image

Imagick::importImagePixels
Imagick::levelImage
Imagick
PHP Manual

Imagick::labelImage

(PECL imagick 2.0.0)

Imagick::labelImage — Adds a label to an image

Opis

bool Imagick::labelImage ( string $label )

Adds a label to an image.

Parametry

label

The label to add

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::importImagePixels
Imagick::levelImage
Imagick


Adjusts the levels of an image

Imagick::labelImage
Imagick::linearStretchImage
Imagick
PHP Manual

Imagick::levelImage

(PECL imagick 2.0.0)

Imagick::levelImage — Adjusts the levels of an image

Opis

bool Imagick::levelImage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Imagick::CHANNEL_ALL ] )

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

Parametry

blackPoint

The image black point

gamma

The gamma value

whitePoint

The image white point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::labelImage
Imagick::linearStretchImage
Imagick


Stretches with saturation the image intensity

Imagick::levelImage
Imagick::liquidRescaleImage
Imagick
PHP Manual

Imagick::linearStretchImage

(PECL imagick 2.0.0)

Imagick::linearStretchImage — Stretches with saturation the image intensity

Opis

bool Imagick::linearStretchImage ( float $blackPoint , float $whitePoint )

Stretches with saturation the image intensity.

Parametry

blackPoint

The image black point

whitePoint

The image white point

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::levelImage
Imagick::liquidRescaleImage
Imagick


Animates an image or images

Imagick::linearStretchImage
Imagick::magnifyImage
Imagick
PHP Manual

Imagick::liquidRescaleImage

(No version information available, might only be in SVN)

Imagick::liquidRescaleImage — Animates an image or images

Opis

bool Imagick::liquidRescaleImage ( int $width , int $height , float $delta_x , float $rigidity )

This method scales the images using liquid rescaling method. This method is an implementation of a technique called seam carving. In order for this method to work as expected ImageMagick must be compiled with liblqr support. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.9 lub nowszej.

Parametry

width

The width of the target size

height

The height of the target size

delta_x

How much the seam can traverse on x-axis. Passing 0 causes the seams to be straight.

rigidity

Introduces a bias for non-straight seams. This parameter is typically 0.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::resizeImage() - Scales an image

Imagick::linearStretchImage
Imagick::magnifyImage
Imagick


Scales an image proportionally 2x

Imagick::liquidRescaleImage
Imagick::mapImage
Imagick
PHP Manual

Imagick::magnifyImage

(PECL imagick 2.0.0)

Imagick::magnifyImage — Scales an image proportionally 2x

Opis

bool Imagick::magnifyImage ( void )

Is a convenience method that scales an image proportionally to twice its original size.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::liquidRescaleImage
Imagick::mapImage
Imagick


Replaces the colors of an image with the closest color from a reference image.

Imagick::magnifyImage
Imagick::matteFloodfillImage
Imagick
PHP Manual

Imagick::mapImage

(PECL imagick 2.0.0)

Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image.

Opis

bool Imagick::mapImage ( Imagick $map , bool $dither )

Parametry

map

dither

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::magnifyImage
Imagick::matteFloodfillImage
Imagick


Changes the transparency value of a color

Imagick::mapImage
Imagick::medianFilterImage
Imagick
PHP Manual

Imagick::matteFloodfillImage

(PECL imagick 2.0.0)

Imagick::matteFloodfillImage — Changes the transparency value of a color

Opis

bool Imagick::matteFloodfillImage ( float $alpha , float $fuzz , mixed $bordercolor , int $x , int $y )

Changes the transparency value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the transparency value is changed for any neighbor pixel that does not match the bordercolor member of image.

Parametry

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

bordercolor

An ImagickPixel object or string representing the border color.

x

The starting x coordinate of the operation.

y

The starting y coordinate of the operation.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

Imagick::mapImage
Imagick::medianFilterImage
Imagick


Applies a digital filter

Imagick::matteFloodfillImage
Imagick::mergeImageLayers
Imagick
PHP Manual

Imagick::medianFilterImage

(PECL imagick 2.0.0)

Imagick::medianFilterImage — Applies a digital filter

Opis

bool Imagick::medianFilterImage ( float $radius )

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

Parametry

radius

The radius of the pixel neighborhood.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::matteFloodfillImage
Imagick::mergeImageLayers
Imagick


Merges image layers

Imagick::medianFilterImage
Imagick::minifyImage
Imagick
PHP Manual

Imagick::mergeImageLayers

(PECL imagick 2.1.0)

Imagick::mergeImageLayers — Merges image layers

Opis

bool Imagick::mergeImageLayers ( int $layer_method )

Merges image layers into one. This method is useful when working with image formats that use multiple layers such as PSD. The merging is controlled using the layer_method which defines how the layers are merged. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.7 lub nowszej.

Parametry

layer_method

One of the Imagick::LAYERMETHOD_* constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Zobacz też:

  • Imagick::flattenImages() - Merges a sequence of images

Imagick::medianFilterImage
Imagick::minifyImage
Imagick


Scales an image proportionally to half its size

Imagick::mergeImageLayers
Imagick::modulateImage
Imagick
PHP Manual

Imagick::minifyImage

(PECL imagick 2.0.0)

Imagick::minifyImage — Scales an image proportionally to half its size

Opis

bool Imagick::minifyImage ( void )

Is a convenience method that scales an image proportionally to one-half its original size

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::mergeImageLayers
Imagick::modulateImage
Imagick


Control the brightness, saturation, and hue

Imagick::minifyImage
Imagick::montageImage
Imagick
PHP Manual

Imagick::modulateImage

(PECL imagick 2.0.0)

Imagick::modulateImage — Control the brightness, saturation, and hue

Opis

bool Imagick::modulateImage ( float $brightness , float $saturation , float $hue )

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

Parametry

brightness

saturation

hue

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::minifyImage
Imagick::montageImage
Imagick


Creates a composite image

Imagick::modulateImage
Imagick::morphImages
Imagick
PHP Manual

Imagick::montageImage

(PECL imagick 2.0.0)

Imagick::montageImage — Creates a composite image

Opis

Imagick Imagick::montageImage ( ImagickDraw $draw , string $tile_geometry , string $thumbnail_geometry , int $mode , string $frame )

Creates a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.

Parametry

draw

The font name, size, and color are obtained from this object.

tile_geometry

The number of tiles per row and page (e.g. 6x4+0+0).

thumbnail_geometry

Preferred image size and border size of each thumbnail (e.g. 120x120+4+3>).

mode

Thumbnail framing mode, see Montage Mode constants.

frame

Surround the image with an ornamental border (e.g. 15x15+3+3). The frame color is that of the thumbnail's matte color.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::modulateImage
Imagick::morphImages
Imagick


Method morphs a set of images

Imagick::montageImage
Imagick::mosaicImages
Imagick
PHP Manual

Imagick::morphImages

(PECL imagick 2.0.0)

Imagick::morphImages — Method morphs a set of images

Opis

Imagick Imagick::morphImages ( int $number_frames )

Method morphs a set of images. Both the image pixels and size are linearly interpolated to give the appearance of a meta-morphosis from one image to the next.

Parametry

number_frames

The number of in-between images to generate.

Zwracane wartości

This method returns a new Imagick object on success. Zgłasza wyjątek ImagickException gdy wystąpi błąd.

Imagick::montageImage
Imagick::mosaicImages
Imagick


Forms a mosaic from images

Imagick::morphImages
Imagick::motionBlurImage
Imagick
PHP Manual

Imagick::mosaicImages

(PECL imagick 2.0.0)

Imagick::mosaicImages — Forms a mosaic from images

Opis

Imagick Imagick::mosaicImages ( void )

Inlays an image sequence to form a single coherent picture. It returns a wand with each image in the sequence composited at the location defined by the page offset of the image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::morphImages
Imagick::motionBlurImage
Imagick


Simulates motion blur

Imagick::mosaicImages
Imagick::negateImage
Imagick
PHP Manual

Imagick::motionBlurImage

(PECL imagick 2.0.0)

Imagick::motionBlurImage — Simulates motion blur

Opis

bool Imagick::motionBlurImage ( float $radius , float $sigma , float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

Parametry

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants. The channel argument affects only if Imagick is compiled against ImageMagick version 6.4.4 or greater.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::mosaicImages
Imagick::negateImage
Imagick


Negates the colors in the reference image

Imagick::motionBlurImage
Imagick::newImage
Imagick
PHP Manual

Imagick::negateImage

(PECL imagick 2.0.0)

Imagick::negateImage — Negates the colors in the reference image

Opis

bool Imagick::negateImage ( bool $gray [, int $channel = Imagick::CHANNEL_ALL ] )

Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.

Parametry

gray

Whether to only negate grayscale pixels within the image.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::motionBlurImage
Imagick::newImage
Imagick


Creates a new image

Imagick::negateImage
Imagick::newPseudoImage
Imagick
PHP Manual

Imagick::newImage

(PECL imagick 2.0.0)

Imagick::newImage — Creates a new image

Opis

bool Imagick::newImage ( int $cols , int $rows , mixed $background [, string $format ] )

Creates a new image and associates ImagickPixel value as background color

Parametry

cols

Columns in the new image

rows

Rows in the new image

background

The background color used for this image

format

Image format. This parameter was added in Imagick version 2.0.1.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

Przykłady

Przykład #1 Using Imagick::newImage():

Create a new image and display it.

<?php

$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

header('Content-type: image/png');
echo $image;

?>

Imagick::negateImage
Imagick::newPseudoImage
Imagick


Creates a new image

Imagick::newImage
Imagick::nextImage
Imagick
PHP Manual

Imagick::newPseudoImage

(PECL imagick 2.0.0)

Imagick::newPseudoImage — Creates a new image

Opis

bool Imagick::newPseudoImage ( int $columns , int $rows , string $pseudoString )

Creates a new image using ImageMagick pseudo-formats.

Parametry

columns

columns in the new image

rows

rows in the new image

pseudoString

string containing pseudo image definition.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::newImage
Imagick::nextImage
Imagick


Moves to the next image

Imagick::newPseudoImage
Imagick::normalizeImage
Imagick
PHP Manual

Imagick::nextImage

(PECL imagick 2.0.0)

Imagick::nextImage — Moves to the next image

Opis

bool Imagick::nextImage ( void )

Associates the next image in the image list with an Imagick object.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::newPseudoImage
Imagick::normalizeImage
Imagick


Enhances the contrast of a color image

Imagick::nextImage
Imagick::oilPaintImage
Imagick
PHP Manual

Imagick::normalizeImage

(PECL imagick 2.0.0)

Imagick::normalizeImage — Enhances the contrast of a color image

Opis

bool Imagick::normalizeImage ([ int $channel = Imagick::CHANNEL_ALL ] )

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

Parametry

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::nextImage
Imagick::oilPaintImage
Imagick


Simulates an oil painting

Imagick::normalizeImage
Imagick::opaquePaintImage
Imagick
PHP Manual

Imagick::oilPaintImage

(PECL imagick 2.0.0)

Imagick::oilPaintImage — Simulates an oil painting

Opis

bool Imagick::oilPaintImage ( float $radius )

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

Parametry

radius

The radius of the circular neighborhood.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::normalizeImage
Imagick::opaquePaintImage
Imagick


Changes the color value of any pixel that matches target

Imagick::oilPaintImage
Imagick::optimizeImageLayers
Imagick
PHP Manual

Imagick::opaquePaintImage

(No version information available, might only be in SVN)

Imagick::opaquePaintImage — Changes the color value of any pixel that matches target

Opis

bool Imagick::opaquePaintImage ( mixed $target , mixed $fill , float $fuzz , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Changes any pixel that matches color with the color defined by fill. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.8 lub nowszej.

Parametry

target

ImagickPixel object or a string containing the color to change

fill

The replacement color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

invert

If TRUE paints any pixel that does not match the target color.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::oilPaintImage
Imagick::optimizeImageLayers
Imagick


Removes repeated portions of images to optimize

Imagick::opaquePaintImage
Imagick::orderedPosterizeImage
Imagick
PHP Manual

Imagick::optimizeImageLayers

(PECL imagick 2.0.0)

Imagick::optimizeImageLayers — Removes repeated portions of images to optimize

Opis

bool Imagick::optimizeImageLayers ( void )

Compares each image the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace each frame, while preserving the results of the animation. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::optimizeImageLayers()

Reading, optimizing and writing a GIF image

<?php
/* create new imagick object */
$im = new Imagick("test.gif");

/* optimize the image layers */
$im->optimizeImageLayers();

/* write the image back */
$im->writeImages("test_optimized.gif", true);
?>

Zobacz też:

  • Imagick::compareImageLayers() - Returns the maximum bounding region between images
  • Imagick::writeImages() - Writes an image or image sequence
  • Imagick::writeImage() - Writes an image to the specified filename

Imagick::opaquePaintImage
Imagick::orderedPosterizeImage
Imagick


Performs an ordered dither

Imagick::optimizeImageLayers
Imagick::paintFloodfillImage
Imagick
PHP Manual

Imagick::orderedPosterizeImage

(PECL imagick 2.2.2)

Imagick::orderedPosterizeImage — Performs an ordered dither

Opis

bool Imagick::orderedPosterizeImage ( string $threshold_map [, int $channel = Imagick::CHANNEL_ALL ] )

Performs an ordered dither based on a number of pre-defined dithering threshold maps, but over multiple intensity levels, which can be different for different channels, according to the input arguments. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.1 lub nowszej.

Parametry

threshold_map

A string containing the name of the threshold dither map to use

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::optimizeImageLayers
Imagick::paintFloodfillImage
Imagick


Changes the color value of any pixel that matches target

Imagick::orderedPosterizeImage
Imagick::paintOpaqueImage
Imagick
PHP Manual

Imagick::paintFloodfillImage

(PECL imagick 2.1.0)

Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target

Opis

bool Imagick::paintFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] )

Changes the color value of any pixel that matches target and is an immediate neighbor. As of ImageMagick 6.3.8 this method has been deprecated and Imagick::floodfillPaintImage() should be used instead.

Parametry

fill

ImagickPixel object or a string containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

bordercolor

ImagickPixel object or a string containing the border color

x

X start position of the floodfill

y

Y start position of the floodfill

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::orderedPosterizeImage
Imagick::paintOpaqueImage
Imagick


Change any pixel that matches color

Imagick::paintFloodfillImage
Imagick::paintTransparentImage
Imagick
PHP Manual

Imagick::paintOpaqueImage

(PECL imagick 2.0.0)

Imagick::paintOpaqueImage — Change any pixel that matches color

Opis

bool Imagick::paintOpaqueImage ( mixed $target , mixed $fill , float $fuzz [, int $channel = Imagick::CHANNEL_ALL ] )

Changes any pixel that matches color with the color defined by fill.

Parametry

target

Change this target color to the fill color within the image. An ImagickPixel object or a string representing the target color.

fill

An ImagickPixel object or a string representing the fill color.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as first and second parameter. Previous versions allow only an ImagickPixel object.

Imagick::paintFloodfillImage
Imagick::paintTransparentImage
Imagick


Changes any pixel that matches color with the color defined by fill

Imagick::paintOpaqueImage
Imagick::pingImage
Imagick
PHP Manual

Imagick::paintTransparentImage

(PECL imagick 2.0.0)

Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill

Opis

bool Imagick::paintTransparentImage ( mixed $target , float $alpha , float $fuzz )

Changes any pixel that matches color with the color defined by fill.

Parametry

target

Change this target color to specified opacity value within the image.

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::paintOpaqueImage
Imagick::pingImage
Imagick


Fetch basic attributes about the image

Imagick::paintTransparentImage
Imagick::pingImageBlob
Imagick
PHP Manual

Imagick::pingImage

(PECL imagick 2.0.0)

Imagick::pingImage — Fetch basic attributes about the image

Opis

bool Imagick::pingImage ( string $filename )

This method can be used to query image width, height, size, and format without reading the whole image in to memory.

Parametry

filename

The filename to read the information from.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::paintTransparentImage
Imagick::pingImageBlob
Imagick


Quickly fetch attributes

Imagick::pingImage
Imagick::pingImageFile
Imagick
PHP Manual

Imagick::pingImageBlob

(PECL imagick 2.0.0)

Imagick::pingImageBlob — Quickly fetch attributes

Opis

bool Imagick::pingImageBlob ( string $image )

This method can be used to query image width, height, size, and format without reading the whole image to memory. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

image

A string containing the image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 Using Imagick::pingImageBlob()

Pinging an image from a string

<?php
/* read image contents */
$image = file_get_contents("test.jpg");

/* create new imagick object */
$im = new Imagick();

/* pass the string to the imagick object */
$im->pingImageBlob($image);

/* output image width and height */
echo $im->getImageWidth() . 'x' . $im->getImageHeight();
?>

Zobacz też:

  • Imagick::pingImage() - Fetch basic attributes about the image
  • Imagick::pingImageFile() - Get basic image attributes in a lightweight manner
  • Imagick::readImage() - Reads image from filename
  • Imagick::readImageBlob() - Reads image from a binary string
  • Imagick::readImageFile() - Reads image from open filehandle

Imagick::pingImage
Imagick::pingImageFile
Imagick


Get basic image attributes in a lightweight manner

Imagick::pingImageBlob
Imagick::polaroidImage
Imagick
PHP Manual

Imagick::pingImageFile

(PECL imagick 2.0.0)

Imagick::pingImageFile — Get basic image attributes in a lightweight manner

Opis

bool Imagick::pingImageFile ( resource $filehandle [, string $fileName ] )

This method can be used to query image width, height, size, and format without reading the whole image to memory. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

filehandle

An open filehandle to the image.

fileName

Optional filename for this image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 Using Imagick::pingImageFile()

Opening a remote location

<?php
/* fopen a remote location */
$fp = fopen("http://example.com/test.jpg");

/* create new imagick object */
$im = new Imagick();

/* pass the handle to imagick */
$im->pingImageFile($fp);
?>

Zobacz też:

  • Imagick::pingImage() - Fetch basic attributes about the image
  • Imagick::pingImageBlob() - Quickly fetch attributes
  • Imagick::readImage() - Reads image from filename
  • Imagick::readImageBlob() - Reads image from a binary string
  • Imagick::readImageFile() - Reads image from open filehandle

Imagick::pingImageBlob
Imagick::polaroidImage
Imagick


Simulates a Polaroid picture

Imagick::pingImageFile
Imagick::posterizeImage
Imagick
PHP Manual

Imagick::polaroidImage

(PECL imagick 2.0.0)

Imagick::polaroidImage — Simulates a Polaroid picture

Opis

bool Imagick::polaroidImage ( ImagickDraw $properties , float $angle )

Simulates a Polaroid picture. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.2 lub nowszej.

Parametry

properties

The polaroid properties

angle

The polaroid angle

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 A Imagick::polaroidImage() example

An example of using Imagick::polaroidImage()

<?php
/* Create the object */
$image = new Imagick('source.png');

/* Set the opacity */
$image->polaroidImage(new ImagickDraw(), 25);

/* output the image */
header('Content-type: image/png');
echo $image;

?>

Imagick::pingImageFile
Imagick::posterizeImage
Imagick


Reduces the image to a limited number of color level

Imagick::polaroidImage
Imagick::previewImages
Imagick
PHP Manual

Imagick::posterizeImage

(PECL imagick 2.0.0)

Imagick::posterizeImage — Reduces the image to a limited number of color level

Opis

bool Imagick::posterizeImage ( int $levels , bool $dither )

Reduces the image to a limited number of color level.

Parametry

levels

dither

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::polaroidImage
Imagick::previewImages
Imagick


Quickly pin-point appropriate parameters for image processing

Imagick::posterizeImage
Imagick::previousImage
Imagick
PHP Manual

Imagick::previewImages

(PECL imagick 2.0.0)

Imagick::previewImages — Quickly pin-point appropriate parameters for image processing

Opis

bool Imagick::previewImages ( int $preview )

Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation.

Parametry

preview

Preview type. See Preview type constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::posterizeImage
Imagick::previousImage
Imagick


Move to the previous image in the object

Imagick::previewImages
Imagick::profileImage
Imagick
PHP Manual

Imagick::previousImage

(PECL imagick 2.0.0)

Imagick::previousImage — Move to the previous image in the object

Opis

bool Imagick::previousImage ( void )

Assocates the previous image in an image list with the Imagick object.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::previewImages
Imagick::profileImage
Imagick


Adds or removes a profile from an image

Imagick::previousImage
Imagick::quantizeImage
Imagick
PHP Manual

Imagick::profileImage

(PECL imagick 2.0.0)

Imagick::profileImage — Adds or removes a profile from an image

Opis

bool Imagick::profileImage ( string $name , string $profile )

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.

Parametry

name

profile

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::previousImage
Imagick::quantizeImage
Imagick


Analyzes the colors within a reference image

Imagick::profileImage
Imagick::quantizeImages
Imagick
PHP Manual

Imagick::quantizeImage

(PECL imagick 2.0.0)

Imagick::quantizeImage — Analyzes the colors within a reference image

Opis

bool Imagick::quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )

Parametry

numberColors

colorspace

treedepth

dither

measureError

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::profileImage
Imagick::quantizeImages
Imagick


Analyzes the colors within a sequence of images

Imagick::quantizeImage
Imagick::queryFontMetrics
Imagick
PHP Manual

Imagick::quantizeImages

(PECL imagick 2.0.0)

Imagick::quantizeImages — Analyzes the colors within a sequence of images

Opis

bool Imagick::quantizeImages ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError )

Parametry

numberColors

colorspace

treedepth

dither

measureError

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::quantizeImage
Imagick::queryFontMetrics
Imagick


Returns an array representing the font metrics

Imagick::quantizeImages
Imagick::queryFonts
Imagick
PHP Manual

Imagick::queryFontMetrics

(PECL imagick 2.0.0)

Imagick::queryFontMetrics — Returns an array representing the font metrics

Opis

array Imagick::queryFontMetrics ( ImagickDraw $properties , string $text [, bool $multiline ] )

Returns a multi-dimensional array representing the font metrics.

Parametry

properties

ImagickDraw object containing font properties

text

The text

multiline

Multiline parameter. If left empty it is autodetected

Zwracane wartości

Returns a multi-dimensional array representing the font metrics.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::queryFontMetrics():

Query the metrics for the text and dump the results on the screen.

<?php
/* Create a new Imagick object */
$im = new Imagick();

/* Create an ImagickDraw object */
$draw = new ImagickDraw();

/* Set the font */
$draw->setFont('/path/to/font.ttf');

/* Dump the font metrics, autodetect multiline */
var_dump($im->queryFontMetrics($draw, "Hello World!"));
?>

Imagick::quantizeImages
Imagick::queryFonts
Imagick


Returns the configured fonts

Imagick::queryFontMetrics
Imagick::queryFormats
Imagick
PHP Manual

Imagick::queryFonts

(PECL imagick 2.0.0)

Imagick::queryFonts — Returns the configured fonts

Opis

array Imagick::queryFonts ([ string $pattern = "*" ] )

Returns the configured fonts.

Parametry

pattern

The query pattern

Zwracane wartości

Returns an array containing the configured fonts.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::queryFontMetrics
Imagick::queryFormats
Imagick


Returns formats supported by Imagick

Imagick::queryFonts
Imagick::radialBlurImage
Imagick
PHP Manual

Imagick::queryFormats

(PECL imagick 2.0.0)

Imagick::queryFormats — Returns formats supported by Imagick

Opis

array Imagick::queryFormats ([ string $pattern = "*" ] )

Returns formats supported by Imagick.

Parametry

pattern

Zwracane wartości

Returns an array containing the formats supported by Imagick.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::queryFonts
Imagick::radialBlurImage
Imagick


Radial blurs an image

Imagick::queryFormats
Imagick::raiseImage
Imagick
PHP Manual

Imagick::radialBlurImage

(PECL imagick 2.0.0)

Imagick::radialBlurImage — Radial blurs an image

Opis

bool Imagick::radialBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_ALL ] )

Radial blurs an image.

Parametry

angle

channel

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::queryFormats
Imagick::raiseImage
Imagick


Creates a simulated 3d button-like effect

Imagick::radialBlurImage
Imagick::randomThresholdImage
Imagick
PHP Manual

Imagick::raiseImage

(PECL imagick 2.0.0)

Imagick::raiseImage — Creates a simulated 3d button-like effect

Opis

bool Imagick::raiseImage ( int $width , int $height , int $x , int $y , bool $raise )

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

Parametry

width

height

x

y

raise

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::radialBlurImage
Imagick::randomThresholdImage
Imagick


Creates a high-contrast, two-color image

Imagick::raiseImage
Imagick::readImage
Imagick
PHP Manual

Imagick::randomThresholdImage

(PECL imagick 2.0.0)

Imagick::randomThresholdImage — Creates a high-contrast, two-color image

Opis

bool Imagick::randomThresholdImage ( float $low , float $high [, int $channel = Imagick::CHANNEL_ALL ] )

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

low

The low point

high

The high point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::raiseImage
Imagick::readImage
Imagick


Reads image from filename

Imagick::randomThresholdImage
Imagick::readImageBlob
Imagick
PHP Manual

Imagick::readImage

(PECL imagick 0.9.0-0.9.9)

Imagick::readImage — Reads image from filename

Opis

bool Imagick::readImage ( string $filename )

Reads image from filename

Parametry

filename

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::randomThresholdImage
Imagick::readImageBlob
Imagick


Reads image from a binary string

Imagick::readImage
Imagick::readImageFile
Imagick
PHP Manual

Imagick::readImageBlob

(PECL imagick 2.0.0)

Imagick::readImageBlob — Reads image from a binary string

Opis

bool Imagick::readImageBlob ( string $image [, string $filename ] )

Reads image from a binary string

Parametry

image

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::readImage
Imagick::readImageFile
Imagick


Reads image from open filehandle

Imagick::readImageBlob
Imagick::recolorImage
Imagick
PHP Manual

Imagick::readImageFile

(PECL imagick 2.0.0)

Imagick::readImageFile — Reads image from open filehandle

Opis

bool Imagick::readImageFile ( resource $filehandle [, string $fileName = null ] )

Reads image from open filehandle

Parametry

filehandle

fileName

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::readImageBlob
Imagick::recolorImage
Imagick


Recolors image

Imagick::readImageFile
Imagick::reduceNoiseImage
Imagick
PHP Manual

Imagick::recolorImage

(No version information available, might only be in SVN)

Imagick::recolorImage — Recolors image

Opis

bool Imagick::recolorImage ( array $matrix )

Translate, scale, shear, or rotate image colors. This method supports variable sized matrices but normally 5x5 matrix is used for RGBA and 6x6 is used for CMYK. The last row should contain the normalized values. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

matrix

The matrix containing the color values

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::displayImage() - Displays an image

Imagick::readImageFile
Imagick::reduceNoiseImage
Imagick


Smooths the contours of an image

Imagick::recolorImage
Imagick::remapImage
Imagick
PHP Manual

Imagick::reduceNoiseImage

(PECL imagick 2.0.0)

Imagick::reduceNoiseImage — Smooths the contours of an image

Opis

bool Imagick::reduceNoiseImage ( float $radius )

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Imagick::reduceNoiseImage() selects a suitable radius for you.

Parametry

radius

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::recolorImage
Imagick::remapImage
Imagick


Remaps image colors

Imagick::reduceNoiseImage
Imagick::removeImage
Imagick
PHP Manual

Imagick::remapImage

(No version information available, might only be in SVN)

Imagick::remapImage — Remaps image colors

Opis

public bool Imagick::remapImage ( Imagick $replacement , int $DITHER )

Replaces colors an image with those defined by replacement. The colors are replaced with the closest possible color. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.5 lub nowszej.

Parametry

replacement

An Imagick object containing the replacement colors

DITHER

Refer to this list of dither method constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::reduceNoiseImage
Imagick::removeImage
Imagick


Removes an image from the image list

Imagick::remapImage
Imagick::removeImageProfile
Imagick
PHP Manual

Imagick::removeImage

(PECL imagick 2.0.0)

Imagick::removeImage — Removes an image from the image list

Opis

bool Imagick::removeImage ( void )

Removes an image from the image list.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::remapImage
Imagick::removeImageProfile
Imagick


Removes the named image profile and returns it

Imagick::removeImage
Imagick::render
Imagick
PHP Manual

Imagick::removeImageProfile

(PECL imagick 2.0.0)

Imagick::removeImageProfile — Removes the named image profile and returns it

Opis

string Imagick::removeImageProfile ( string $name )

Removes the named image profile and returns it.

Parametry

name

Zwracane wartości

Returns a string containing the profile of the image.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::removeImage
Imagick::render
Imagick


Renders all preceding drawing commands

Imagick::removeImageProfile
Imagick::resampleImage
Imagick
PHP Manual

Imagick::render

(PECL imagick 2.0.0)

Imagick::render — Renders all preceding drawing commands

Opis

bool Imagick::render ( void )

Renders all preceding drawing commands.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::removeImageProfile
Imagick::resampleImage
Imagick


Resample image to desired resolution

Imagick::render
Imagick::resetImagePage
Imagick
PHP Manual

Imagick::resampleImage

(PECL imagick 2.0.0)

Imagick::resampleImage — Resample image to desired resolution

Opis

bool Imagick::resampleImage ( float $x_resolution , float $y_resolution , int $filter , float $blur )

Resample image to desired resolution.

Parametry

x_resolution

y_resolution

filter

blur

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::render
Imagick::resetImagePage
Imagick


Reset image page

Imagick::resampleImage
Imagick::resizeImage
Imagick
PHP Manual

Imagick::resetImagePage

(No version information available, might only be in SVN)

Imagick::resetImagePage — Reset image page

Opis

bool Imagick::resetImagePage ( string $page )

The page definition as a string. The string is in format WxH+x+y. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

page

The page definition. For example 7168x5147+0+0

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::resampleImage
Imagick::resizeImage
Imagick


Scales an image

Imagick::resetImagePage
Imagick::rollImage
Imagick
PHP Manual

Imagick::resizeImage

(PECL imagick 2.0.0)

Imagick::resizeImage — Scales an image

Opis

bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] )

Scales an image to the desired dimensions with a filter.

Informacja: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parametry

columns

Width of the image

rows

Height of the image

filter

Refer to the list of filter constants.

blur

The blur factor where > 1 is blurry, < 1 is sharp.

bestfit

Optional fit parameter.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Rejestr zmian

Wersja | Opis
2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Imagick::resetImagePage
Imagick::rollImage
Imagick


Offsets an image

Imagick::resizeImage
Imagick::rotateImage
Imagick
PHP Manual

Imagick::rollImage

(PECL imagick 2.0.0)

Imagick::rollImage — Offsets an image

Opis

bool Imagick::rollImage ( int $x , int $y )

Offsets an image as defined by x and y.

Parametry

x

The X offset.

y

The Y offset.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::resizeImage
Imagick::rotateImage
Imagick


Rotates an image

Imagick::rollImage
Imagick::roundCorners
Imagick
PHP Manual

Imagick::rotateImage

(PECL imagick 2.0.0)

Imagick::rotateImage — Rotates an image

Opis

bool Imagick::rotateImage ( mixed $background , float $degrees )

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

Parametry

background

The background color

degrees

The number of degrees to rotate the image

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::rollImage
Imagick::roundCorners
Imagick


Rounds image corners

Imagick::rotateImage
Imagick::sampleImage
Imagick
PHP Manual

Imagick::roundCorners

(PECL imagick 2.0.0)

Imagick::roundCorners — Rounds image corners

Opis

bool Imagick::roundCorners ( float $x_rounding , float $y_rounding [, float $stroke_width = 10 [, float $displace = 5 [, float $size_correction = -6 ]]] )

Rounds image corners. The first two parameters control the amount of rounding and the three last parameters can be used to fine-tune the rounding process. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

x_rounding

x rounding

y_rounding

y rounding

stroke_width

stroke width

displace

image displace

size_correction

size correction

Przykłady

Przykład #1 Using Imagick::roundCorners():

Rounds the image corners

<?php

$image = new Imagick();
$image->newPseudoImage(100, 100, "magick:rose");
$image->setImageFormat("png");

$image->roundCorners(5,3);
$image->writeImage("rounded.png");
?>

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::rotateImage
Imagick::sampleImage
Imagick


Scales an image with pixel sampling

Imagick::roundCorners
Imagick::scaleImage
Imagick
PHP Manual

Imagick::sampleImage

(PECL imagick 2.0.0)

Imagick::sampleImage — Scales an image with pixel sampling

Opis

bool Imagick::sampleImage ( int $columns , int $rows )

Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.

Parametry

columns

rows

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::roundCorners
Imagick::scaleImage
Imagick


Scales the size of an image

Imagick::sampleImage
Imagick::segmentImage
Imagick
PHP Manual

Imagick::scaleImage

(PECL imagick 2.0.0)

Imagick::scaleImage — Scales the size of an image

Opis

bool Imagick::scaleImage ( int $cols , int $rows [, bool $bestfit = false ] )

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

Informacja: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parametry

cols

rows

bestfit

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

Imagick::sampleImage
Imagick::segmentImage
Imagick


Segments an image

Imagick::scaleImage
Imagick::separateImageChannel
Imagick
PHP Manual

Imagick::segmentImage

(No version information available, might only be in SVN)

Imagick::segmentImage — Segments an image

Opis

public bool Imagick::segmentImage ( int $COLORSPACE , float $cluster_threshold , float $smooth_threshold [, bool $verbose = false ] )

Analyses the image and identifies units that are similar. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.5 lub nowszej.

Parametry

COLORSPACE

One of the COLORSPACE constants.

cluster_threshold

A percentage describing minimum number of pixels contained in hexedra before it is considered valid.

smooth_threshold

Eliminates noise from the histogram.

verbose

Whether to output detailed information about recognised classes.

Zwracane wartości

Imagick::scaleImage
Imagick::separateImageChannel
Imagick


Separates a channel from the image

Imagick::segmentImage
Imagick::sepiaToneImage
Imagick
PHP Manual

Imagick::separateImageChannel

(PECL imagick 2.0.0)

Imagick::separateImageChannel — Separates a channel from the image

Opis

bool Imagick::separateImageChannel ( int $channel )

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

Parametry

channel

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::segmentImage
Imagick::sepiaToneImage
Imagick


Sepia tones an image

Imagick::separateImageChannel
Imagick::setBackgroundColor
Imagick
PHP Manual

Imagick::sepiaToneImage

(PECL imagick 2.0.0)

Imagick::sepiaToneImage — Sepia tones an image

Opis

bool Imagick::sepiaToneImage ( float $threshold )

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by sepia toning. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the sepia toning. A threshold of 80 is a good starting point for a reasonable tone.

Parametry

threshold

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::separateImageChannel
Imagick::setBackgroundColor
Imagick


Sets the object's default background color

Imagick::sepiaToneImage
Imagick::setColorspace
Imagick
PHP Manual

Imagick::setBackgroundColor

(PECL imagick 2.0.0)

Imagick::setBackgroundColor — Sets the object's default background color

Opis

bool Imagick::setBackgroundColor ( mixed $background )

Sets the object's default background color.

Parametry

background

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Imagick::sepiaToneImage
Imagick::setColorspace
Imagick


Set colorspace

Imagick::setBackgroundColor
Imagick::setCompression
Imagick
PHP Manual

Imagick::setColorspace

(No version information available, might only be in SVN)

Imagick::setColorspace — Set colorspace

Opis

bool Imagick::setColorspace ( int $COLORSPACE )

Sets the global colorspace value for the object. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.5.7 lub nowszej.

Parametry

COLORSPACE

One of the COLORSPACE constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setBackgroundColor
Imagick::setCompression
Imagick


Sets the object's default compression type

Imagick::setColorspace
Imagick::setCompressionQuality
Imagick
PHP Manual

Imagick::setCompression

(PECL imagick 2.0.0)

Imagick::setCompression — Sets the object's default compression type

Opis

bool Imagick::setCompression ( int $compression )

Sets the object's default compression type

Parametry

compression

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setColorspace
Imagick::setCompressionQuality
Imagick


Sets the object's default compression quality

Imagick::setCompression
Imagick::setFilename
Imagick
PHP Manual

Imagick::setCompressionQuality

(PECL imagick 0.9.10-0.9.9)

Imagick::setCompressionQuality — Sets the object's default compression quality

Opis

bool Imagick::setCompressionQuality ( int $quality )

Sets the object's default compression quality.

Parametry

quality

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setCompression
Imagick::setFilename
Imagick


Sets the filename before you read or write the image

Imagick::setCompressionQuality
Imagick::setFirstIterator
Imagick
PHP Manual

Imagick::setFilename

(PECL imagick 2.0.0)

Imagick::setFilename — Sets the filename before you read or write the image

Opis

bool Imagick::setFilename ( string $filename )

Sets the filename before you read or write an image file.

Parametry

filename

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setCompressionQuality
Imagick::setFirstIterator
Imagick


Sets the Imagick iterator to the first image

Imagick::setFilename
Imagick::setFont
Imagick
PHP Manual

Imagick::setFirstIterator

(PECL imagick 2.0.0)

Imagick::setFirstIterator — Sets the Imagick iterator to the first image

Opis

bool Imagick::setFirstIterator ( void )

Sets the Imagick iterator to the first image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setFilename
Imagick::setFont
Imagick


Sets font

Imagick::setFirstIterator
Imagick::setFormat
Imagick
PHP Manual

Imagick::setFont

(PECL imagick 2.1.0)

Imagick::setFont — Sets font

Opis

bool Imagick::setFont ( string $font )

Sets object's font property. This method can be used for example to set font for caption: pseudo-format. The font needs to be configured in ImageMagick confiration or a file by the name of font must exist. This method should not be confused with ImagickDraw::setFont() which sets the font for a specific ImagickDraw object. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.7 lub nowszej.

Parametry

font

Font name or a filename

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::getFont() - Gets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

Przykłady

Przykład #1 A Imagick::setFont() example

Example of using Imagick::setFont

<?php
/* Create new imagick object */
$im = new Imagick();

/* Set the font for the object */
$im->setFont("example.ttf");

/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");

/* Do something with the image */
?>

Imagick::setFirstIterator
Imagick::setFormat
Imagick


Sets the format of the Imagick object

Imagick::setFont
Imagick::setGravity
Imagick
PHP Manual

Imagick::setFormat

(PECL imagick 2.0.0)

Imagick::setFormat — Sets the format of the Imagick object

Opis

bool Imagick::setFormat ( string $format )

Sets the format of the Imagick object.

Parametry

format

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setFont
Imagick::setGravity
Imagick


Sets the gravity

Imagick::setFormat
Imagick::setImage
Imagick
PHP Manual

Imagick::setGravity

(No version information available, might only be in SVN)

Imagick::setGravity — Sets the gravity

Opis

bool Imagick::setGravity ( int $gravity )

Sets the global gravity property for the Imagick object. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.0 lub nowszej.

Parametry

gravity

The gravity property. Refer to the list of gravity constants.

Zwracane wartości

Nie jest zwracana żadna wartość.

Imagick::setFormat
Imagick::setImage
Imagick


Replaces image in the object

Imagick::setGravity
Imagick::setImageAlphaChannel
Imagick
PHP Manual

Imagick::setImage

(PECL imagick 2.0.0)

Imagick::setImage — Replaces image in the object

Opis

bool Imagick::setImage ( Imagick $replace )

Replaces the current image sequence with the image from replace object.

Parametry

replace

The replace Imagick object

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 A Imagick::setImage() example

An example of using Imagick::setImage()

<?php
/* Create the objects */
$image = new Imagick('source.jpg');
$replace = new Imagick('replace.jpg');

/* source.jpg is replaced with replace.jpg */
$image->setImage($replace);

/* output the image */
header('Content-type: image/jpeg');
echo $image;

?>

Imagick::setGravity
Imagick::setImageAlphaChannel
Imagick


Sets image alpha channel

Imagick::setImage
Imagick::setImageArtifact
Imagick
PHP Manual

Imagick::setImageAlphaChannel

(No version information available, might only be in SVN)

Imagick::setImageAlphaChannel — Sets image alpha channel

Opis

bool Imagick::setImageAlphaChannel ( int $mode )

Activate or deactivate image alpha channel. The mode is one of the Imagick::ALPHACHANNEL_* constants. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.8 lub nowszej.

Parametry

mode

One of the Imagick::ALPHACHANNEL_* constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Zobacz też:

  • Imagick::setImageMatte() - Sets the image matte channel

Imagick::setImage
Imagick::setImageArtifact
Imagick


Set image artifact

Imagick::setImageAlphaChannel
Imagick::setImageBackgroundColor
Imagick
PHP Manual

Imagick::setImageArtifact

(No version information available, might only be in SVN)

Imagick::setImageArtifact — Set image artifact

Opis

bool Imagick::setImageArtifact ( string $artifact , string $value )

Associates an artifact with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.5.7 lub nowszej.

Parametry

artifact

The name of the artifact

value

The value of the artifact

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Zobacz też:

  • Imagick::getImageArtifact() - Get image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

Imagick::setImageAlphaChannel
Imagick::setImageBackgroundColor
Imagick


Sets the image background color

Imagick::setImageArtifact
Imagick::setImageBias
Imagick
PHP Manual

Imagick::setImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::setImageBackgroundColor — Sets the image background color

Opis

bool Imagick::setImageBackgroundColor ( mixed $background )

Sets the image background color.

Parametry

background

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

Imagick::setImageArtifact
Imagick::setImageBias
Imagick


Sets the image bias for any method that convolves an image

Imagick::setImageBackgroundColor
Imagick::setImageBluePrimary
Imagick
PHP Manual

Imagick::setImageBias

(PECL imagick 2.0.0)

Imagick::setImageBias — Sets the image bias for any method that convolves an image

Opis

bool Imagick::setImageBias ( float $bias )

Sets the image bias for any method that convolves an image (e.g. Imagick::ConvolveImage()).

Parametry

bias

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageBackgroundColor
Imagick::setImageBluePrimary
Imagick


Sets the image chromaticity blue primary point

Imagick::setImageBias
Imagick::setImageBorderColor
Imagick
PHP Manual

Imagick::setImageBluePrimary

(PECL imagick 2.0.0)

Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point

Opis

bool Imagick::setImageBluePrimary ( float $x , float $y )

Sets the image chromaticity blue primary point.

Parametry

x

y

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageBias
Imagick::setImageBorderColor
Imagick


Sets the image border color

Imagick::setImageBluePrimary
Imagick::setImageChannelDepth
Imagick
PHP Manual

Imagick::setImageBorderColor

(PECL imagick 2.0.0)

Imagick::setImageBorderColor — Sets the image border color

Opis

bool Imagick::setImageBorderColor ( mixed $border )

Sets the image border color.

Parametry

border

The border color

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Imagick::setImageBluePrimary
Imagick::setImageChannelDepth
Imagick


Sets the depth of a particular image channel

Imagick::setImageBorderColor
Imagick::setImageClipMask
Imagick
PHP Manual

Imagick::setImageChannelDepth

(PECL imagick 2.0.0)

Imagick::setImageChannelDepth — Sets the depth of a particular image channel

Opis

bool Imagick::setImageChannelDepth ( int $channel , int $depth )

Sets the depth of a particular image channel.

Parametry

channel

depth

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageBorderColor
Imagick::setImageClipMask
Imagick


Sets image clip mask

Imagick::setImageChannelDepth
Imagick::setImageColormapColor
Imagick
PHP Manual

Imagick::setImageClipMask

(No version information available, might only be in SVN)

Imagick::setImageClipMask — Sets image clip mask

Opis

bool Imagick::setImageClipMask ( Imagick $clip_mask )

Sets image clip mask from another Imagick object. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

clip_mask

The Imagick object containing the clip mask

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageChannelDepth
Imagick::setImageColormapColor
Imagick


Sets the color of the specified colormap index

Imagick::setImageClipMask
Imagick::setImageColorspace
Imagick
PHP Manual

Imagick::setImageColormapColor

(PECL imagick 2.0.0)

Imagick::setImageColormapColor — Sets the color of the specified colormap index

Opis

bool Imagick::setImageColormapColor ( int $index , ImagickPixel $color )

Sets the color of the specified colormap index.

Parametry

index

color

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageClipMask
Imagick::setImageColorspace
Imagick


Sets the image colorspace

Imagick::setImageColormapColor
Imagick::setImageCompose
Imagick
PHP Manual

Imagick::setImageColorspace

(PECL imagick 2.0.0)

Imagick::setImageColorspace — Sets the image colorspace

Opis

bool Imagick::setImageColorspace ( int $colorspace )

Sets the image colorspace.

Parametry

colorspace

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageColormapColor
Imagick::setImageCompose
Imagick


Sets the image composite operator

Imagick::setImageColorspace
Imagick::setImageCompression
Imagick
PHP Manual

Imagick::setImageCompose

(PECL imagick 2.0.0)

Imagick::setImageCompose — Sets the image composite operator

Opis

bool Imagick::setImageCompose ( int $compose )

Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the Imagick::montageImage() method.

Parametry

compose

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageColorspace
Imagick::setImageCompression
Imagick


Sets the image compression

Imagick::setImageCompose
Imagick::setImageCompressionQuality
Imagick
PHP Manual

Imagick::setImageCompression

(PECL imagick 2.0.0)

Imagick::setImageCompression — Sets the image compression

Opis

bool Imagick::setImageCompression ( int $compression )

Parametry

compression

One of the COMPRESSION constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageCompose
Imagick::setImageCompressionQuality
Imagick


Sets the image compression quality

Imagick::setImageCompression
Imagick::setImageDelay
Imagick
PHP Manual

Imagick::setImageCompressionQuality

(No version information available, might only be in SVN)

Imagick::setImageCompressionQuality — Sets the image compression quality

Opis

bool Imagick::setImageCompressionQuality ( int $quality )

Sets the image compression quality.

Parametry

quality

The image compression quality as an integer

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageCompression
Imagick::setImageDelay
Imagick


Sets the image delay

Imagick::setImageCompressionQuality
Imagick::setImageDepth
Imagick
PHP Manual

Imagick::setImageDelay

(PECL imagick 2.0.0)

Imagick::setImageDelay — Sets the image delay

Opis

bool Imagick::setImageDelay ( int $delay )

Sets the image delay.

Parametry

delay

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageCompressionQuality
Imagick::setImageDepth
Imagick


Sets the image depth

Imagick::setImageDelay
Imagick::setImageDispose
Imagick
PHP Manual

Imagick::setImageDepth

(PECL imagick 2.0.0)

Imagick::setImageDepth — Sets the image depth

Opis

bool Imagick::setImageDepth ( int $depth )

Sets the image depth.

Parametry

depth

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageDelay
Imagick::setImageDispose
Imagick


Sets the image disposal method

Imagick::setImageDepth
Imagick::setImageExtent
Imagick
PHP Manual

Imagick::setImageDispose

(PECL imagick 2.0.0)

Imagick::setImageDispose — Sets the image disposal method

Opis

bool Imagick::setImageDispose ( int $dispose )

Sets the image disposal method.

Parametry

dispose

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageDepth
Imagick::setImageExtent
Imagick


Sets the image size

Imagick::setImageDispose
Imagick::setImageFilename
Imagick
PHP Manual

Imagick::setImageExtent

(PECL imagick 2.0.0)

Imagick::setImageExtent — Sets the image size

Opis

bool Imagick::setImageExtent ( int $columns , int $rows )

Sets the image size (i.e. columns & rows).

Parametry

columns

rows

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageDispose
Imagick::setImageFilename
Imagick


Sets the filename of a particular image

Imagick::setImageExtent
Imagick::setImageFormat
Imagick
PHP Manual

Imagick::setImageFilename

(PECL imagick 2.0.0)

Imagick::setImageFilename — Sets the filename of a particular image

Opis

bool Imagick::setImageFilename ( string $filename )

Sets the filename of a particular image in a sequence.

Parametry

filename

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageExtent
Imagick::setImageFormat
Imagick


Sets the format of a particular image

Imagick::setImageFilename
Imagick::setImageGamma
Imagick
PHP Manual

Imagick::setImageFormat

(PECL imagick 2.0.0)

Imagick::setImageFormat — Sets the format of a particular image

Opis

bool Imagick::setImageFormat ( string $format )

Sets the format of a particular image in a sequence.

Parametry

format

String presentation of the image format. Format support depends on the ImageMagick installation.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageFilename
Imagick::setImageGamma
Imagick


Sets the image gamma

Imagick::setImageFormat
Imagick::setImageGravity
Imagick
PHP Manual

Imagick::setImageGamma

(PECL imagick 2.0.0)

Imagick::setImageGamma — Sets the image gamma

Opis

bool Imagick::setImageGamma ( float $gamma )

Sets the image gamma.

Parametry

gamma

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageFormat
Imagick::setImageGravity
Imagick


Sets the image gravity

Imagick::setImageGamma
Imagick::setImageGreenPrimary
Imagick
PHP Manual

Imagick::setImageGravity

(No version information available, might only be in SVN)

Imagick::setImageGravity — Sets the image gravity

Opis

bool Imagick::setImageGravity ( int $gravity )

Sets the gravity property for the current image. This method can be used to set the gravity property for a single image sequence. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.4 lub nowszej.

Parametry

gravity

The gravity property. Refer to the list of gravity constants.

Zwracane wartości

Nie jest zwracana żadna wartość.

Imagick::setImageGamma
Imagick::setImageGreenPrimary
Imagick


Sets the image chromaticity green primary point

Imagick::setImageGravity
Imagick::setImageIndex
Imagick
PHP Manual

Imagick::setImageGreenPrimary

(PECL imagick 2.0.0)

Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point

Opis

bool Imagick::setImageGreenPrimary ( float $x , float $y )

Sets the image chromaticity green primary point.

Parametry

x

y

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageGravity
Imagick::setImageIndex
Imagick


Set the iterator position

Imagick::setImageGreenPrimary
Imagick::setImageInterlaceScheme
Imagick
PHP Manual

Imagick::setImageIndex

(PECL imagick 2.0.0)

Imagick::setImageIndex — Set the iterator position

Opis

bool Imagick::setImageIndex ( int $index )

Set the iterator to the position in the image list specified with the index parameter.

This method has been deprecated. See Imagick::setIteratorIndex().

Parametry

index

The position to set the iterator to

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageGreenPrimary
Imagick::setImageInterlaceScheme
Imagick


Sets the image compression

Imagick::setImageIndex
Imagick::setImageInterpolateMethod
Imagick
PHP Manual

Imagick::setImageInterlaceScheme

(PECL imagick 2.0.0)

Imagick::setImageInterlaceScheme — Sets the image compression

Opis

bool Imagick::setImageInterlaceScheme ( int $interlace_scheme )

Sets the image compression.

Parametry

interlace_scheme

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageIndex
Imagick::setImageInterpolateMethod
Imagick


Sets the image interpolate pixel method

Imagick::setImageInterlaceScheme
Imagick::setImageIterations
Imagick
PHP Manual

Imagick::setImageInterpolateMethod

(PECL imagick 2.0.0)

Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method

Opis

bool Imagick::setImageInterpolateMethod ( int $method )

Sets the image interpolate pixel method.

Parametry

method

The method is one of the Imagick::INTERPOLATE_* constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageInterlaceScheme
Imagick::setImageIterations
Imagick


Sets the image iterations

Imagick::setImageInterpolateMethod
Imagick::setImageMatte
Imagick
PHP Manual

Imagick::setImageIterations

(PECL imagick 2.0.0)

Imagick::setImageIterations — Sets the image iterations

Opis

bool Imagick::setImageIterations ( int $iterations )

Sets the image iterations.

Parametry

iterations

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageInterpolateMethod
Imagick::setImageMatte
Imagick


Sets the image matte channel

Imagick::setImageIterations
Imagick::setImageMatteColor
Imagick
PHP Manual

Imagick::setImageMatte

(PECL imagick 2.0.0)

Imagick::setImageMatte — Sets the image matte channel

Opis

bool Imagick::setImageMatte ( bool $matte )

Sets the image matte channel. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

matte

True activates the matte channel and false disables it.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageIterations
Imagick::setImageMatteColor
Imagick


Sets the image matte color

Imagick::setImageMatte
Imagick::setImageOpacity
Imagick
PHP Manual

Imagick::setImageMatteColor

(PECL imagick 2.0.0)

Imagick::setImageMatteColor — Sets the image matte color

Opis

bool Imagick::setImageMatteColor ( mixed $matte )

Sets the image matte color.

Parametry

matte

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

Imagick::setImageMatte
Imagick::setImageOpacity
Imagick


Sets the image opacity level

Imagick::setImageMatteColor
Imagick::setImageOrientation
Imagick
PHP Manual

Imagick::setImageOpacity

(PECL imagick 2.0.0)

Imagick::setImageOpacity — Sets the image opacity level

Opis

bool Imagick::setImageOpacity ( float $opacity )

Sets the image to the specified opacity level. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.1 lub nowszej.

Parametry

opacity

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 A Imagick::setImageOpacity() example

An example of using Imagick::setImageOpacity()

<?php
/* Create the object */
$image = new Imagick('source.png');

/* Set the opacity */
$image->setImageOpacity(0.7);

/* output the image */
header('Content-type: image/png');
echo $image;

?>

Imagick::setImageMatteColor
Imagick::setImageOrientation
Imagick


Sets the image orientation

Imagick::setImageOpacity
Imagick::setImagePage
Imagick
PHP Manual

Imagick::setImageOrientation

(PECL imagick 2.0.0)

Imagick::setImageOrientation — Sets the image orientation

Opis

bool Imagick::setImageOrientation ( int $orientation )

Sets the image orientation.

Parametry

orientation

One of the orientation constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageOpacity
Imagick::setImagePage
Imagick


Sets the page geometry of the image

Imagick::setImageOrientation
Imagick::setImageProfile
Imagick
PHP Manual

Imagick::setImagePage

(PECL imagick 2.0.0)

Imagick::setImagePage — Sets the page geometry of the image

Opis

bool Imagick::setImagePage ( int $width , int $height , int $x , int $y )

Sets the page geometry of the image.

Parametry

width

height

x

y

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageOrientation
Imagick::setImageProfile
Imagick


Adds a named profile to the Imagick object

Imagick::setImagePage
Imagick::setImageProperty
Imagick
PHP Manual

Imagick::setImageProfile

(PECL imagick 2.0.0)

Imagick::setImageProfile — Adds a named profile to the Imagick object

Opis

bool Imagick::setImageProfile ( string $name , string $profile )

Adds a named profile to the Imagick object. If a profile with the same name already exists, it is replaced. This method differs from the Imagick::ProfileImage() method in that it does not apply any CMS color profiles.

Parametry

name

profile

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImagePage
Imagick::setImageProperty
Imagick


Sets an image property

Imagick::setImageProfile
Imagick::setImageRedPrimary
Imagick
PHP Manual

Imagick::setImageProperty

(PECL imagick 2.0.0)

Imagick::setImageProperty — Sets an image property

Opis

bool Imagick::setImageProperty ( string $name , string $value )

Sets a named property to the image. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.2 lub nowszej.

Parametry

name

value

Przykłady

Przykład #1 Using Imagick::setImageProperty():

Setting and getting image properties

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>

Zobacz też:

  • Imagick::getImageProperty() - Returns the named image property

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageProfile
Imagick::setImageRedPrimary
Imagick


Sets the image chromaticity red primary point

Imagick::setImageProperty
Imagick::setImageRenderingIntent
Imagick
PHP Manual

Imagick::setImageRedPrimary

(PECL imagick 2.0.0)

Imagick::setImageRedPrimary — Sets the image chromaticity red primary point

Opis

bool Imagick::setImageRedPrimary ( float $x , float $y )

Sets the image chromaticity red primary point.

Parametry

x

y

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageProperty
Imagick::setImageRenderingIntent
Imagick


Sets the image rendering intent

Imagick::setImageRedPrimary
Imagick::setImageResolution
Imagick
PHP Manual

Imagick::setImageRenderingIntent

(PECL imagick 2.0.0)

Imagick::setImageRenderingIntent — Sets the image rendering intent

Opis

bool Imagick::setImageRenderingIntent ( int $rendering_intent )

Sets the image rendering intent.

Parametry

rendering_intent

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageRedPrimary
Imagick::setImageResolution
Imagick


Sets the image resolution

Imagick::setImageRenderingIntent
Imagick::setImageScene
Imagick
PHP Manual

Imagick::setImageResolution

(PECL imagick 2.0.0)

Imagick::setImageResolution — Sets the image resolution

Opis

bool Imagick::setImageResolution ( float $x_resolution , float $y_resolution )

Sets the image resolution.

Parametry

x_resolution

y_resolution

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageRenderingIntent
Imagick::setImageScene
Imagick


Sets the image scene

Imagick::setImageResolution
Imagick::setImageTicksPerSecond
Imagick
PHP Manual

Imagick::setImageScene

(PECL imagick 2.0.0)

Imagick::setImageScene — Sets the image scene

Opis

bool Imagick::setImageScene ( int $scene )

Sets the image scene.

Parametry

scene

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageResolution
Imagick::setImageTicksPerSecond
Imagick


Sets the image ticks-per-second

Imagick::setImageScene
Imagick::setImageType
Imagick
PHP Manual

Imagick::setImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::setImageTicksPerSecond — Sets the image ticks-per-second

Opis

bool Imagick::setImageTicksPerSecond ( int $ticks_per-second )

Sets the image ticks-per-second.

Parametry

ticks_per-second

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageScene
Imagick::setImageType
Imagick


Sets the image type

Imagick::setImageTicksPerSecond
Imagick::setImageUnits
Imagick
PHP Manual

Imagick::setImageType

(PECL imagick 2.0.0)

Imagick::setImageType — Sets the image type

Opis

bool Imagick::setImageType ( int $image_type )

Sets the image type.

Parametry

image_type

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageTicksPerSecond
Imagick::setImageUnits
Imagick


Sets the image units of resolution

Imagick::setImageType
Imagick::setImageVirtualPixelMethod
Imagick
PHP Manual

Imagick::setImageUnits

(PECL imagick 2.0.0)

Imagick::setImageUnits — Sets the image units of resolution

Opis

bool Imagick::setImageUnits ( int $units )

Sets the image units of resolution.

Parametry

units

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageType
Imagick::setImageVirtualPixelMethod
Imagick


Sets the image virtual pixel method

Imagick::setImageUnits
Imagick::setImageWhitePoint
Imagick
PHP Manual

Imagick::setImageVirtualPixelMethod

(PECL imagick 2.0.0)

Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method

Opis

bool Imagick::setImageVirtualPixelMethod ( int $method )

Sets the image virtual pixel method.

Parametry

method

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageUnits
Imagick::setImageWhitePoint
Imagick


Sets the image chromaticity white point

Imagick::setImageVirtualPixelMethod
Imagick::setInterlaceScheme
Imagick
PHP Manual

Imagick::setImageWhitePoint

(PECL imagick 2.0.0)

Imagick::setImageWhitePoint — Sets the image chromaticity white point

Opis

bool Imagick::setImageWhitePoint ( float $x , float $y )

Sets the image chromaticity white point.

Parametry

x

y

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::setImageVirtualPixelMethod
Imagick::setInterlaceScheme
Imagick


Sets the image compression

Imagick::setImageWhitePoint
Imagick::setIteratorIndex
Imagick
PHP Manual

Imagick::setInterlaceScheme

(PECL imagick 2.0.0)

Imagick::setInterlaceScheme — Sets the image compression

Opis

bool Imagick::setInterlaceScheme ( int $interlace_scheme )

Sets the image compression.

Parametry

interlace_scheme

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setImageWhitePoint
Imagick::setIteratorIndex
Imagick


Set the iterator position

Imagick::setInterlaceScheme
Imagick::setLastIterator
Imagick
PHP Manual

Imagick::setIteratorIndex

(PECL imagick 2.0.0)

Imagick::setIteratorIndex — Set the iterator position

Opis

bool Imagick::setIteratorIndex ( int $index )

Set the iterator to the position in the image list specified with the index parameter. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

index

The position to set the iterator to

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 Using Imagick::setIteratorIndex():

Create images, set and get the iterator index

<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));

$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>

Zobacz też:

  • Imagick::getIteratorIndex() - Gets the index of the current active image
  • Imagick::getImageIndex() - Gets the index of the current active image
  • Imagick::setImageIndex() - Set the iterator position

Imagick::setInterlaceScheme
Imagick::setLastIterator
Imagick


Sets the Imagick iterator to the last image

Imagick::setIteratorIndex
Imagick::setOption
Imagick
PHP Manual

Imagick::setLastIterator

(PECL imagick 2.0.1)

Imagick::setLastIterator — Sets the Imagick iterator to the last image

Opis

bool Imagick::setLastIterator ( void )

Sets the Imagick iterator to the last image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setIteratorIndex
Imagick::setOption
Imagick


Set an option

Imagick::setLastIterator
Imagick::setPage
Imagick
PHP Manual

Imagick::setOption

(PECL imagick 2.0.0)

Imagick::setOption — Set an option

Opis

bool Imagick::setOption ( string $key , string $value )

Associates one or more options with the wand.

Parametry

key

value

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setLastIterator
Imagick::setPage
Imagick


Sets the page geometry of the Imagick object

Imagick::setOption
Imagick::setPointSize
Imagick
PHP Manual

Imagick::setPage

(PECL imagick 2.0.0)

Imagick::setPage — Sets the page geometry of the Imagick object

Opis

bool Imagick::setPage ( int $width , int $height , int $x , int $y )

Sets the page geometry of the Imagick object.

Parametry

width

height

x

y

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setOption
Imagick::setPointSize
Imagick


Sets point size

Imagick::setPage
Imagick::setResolution
Imagick
PHP Manual

Imagick::setPointSize

(PECL imagick 2.1.0)

Imagick::setPointSize — Sets point size

Opis

bool Imagick::setPointSize ( float $point_size )

Sets object's point size property. This method can be used for example to set font size for caption: pseudo-format. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.7 lub nowszej.

Parametry

point_size

Point size

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::getPointSize() - Gets point size

Przykłady

Przykład #1 A Imagick::setPointSize() example

Example of using Imagick::setPointSize

<?php
/* Create new imagick object */
$im = new Imagick();

/* Set the font for the object */
$im->setFont("example.ttf");

/* Set the point size */
$im->setPointSize(12);

/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");

/* Do something with the image */
?>

Imagick::setPage
Imagick::setResolution
Imagick


Sets the image resolution

Imagick::setPointSize
Imagick::setResourceLimit
Imagick
PHP Manual

Imagick::setResolution

(PECL imagick 2.0.0)

Imagick::setResolution — Sets the image resolution

Opis

bool Imagick::setResolution ( float $x_resolution , float $y_resolution )

Sets the image resolution.

Parametry

x_resolution

y_resolution

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setPointSize
Imagick::setResourceLimit
Imagick


Sets the limit for a particular resource in megabytes

Imagick::setResolution
Imagick::setSamplingFactors
Imagick
PHP Manual

Imagick::setResourceLimit

(PECL imagick 2.0.0)

Imagick::setResourceLimit — Sets the limit for a particular resource in megabytes

Opis

bool Imagick::setResourceLimit ( int $type , int $limit )

Sets the limit for a particular resource in megabytes.

Parametry

type

limit

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setResolution
Imagick::setSamplingFactors
Imagick


Sets the image sampling factors

Imagick::setResourceLimit
Imagick::setSize
Imagick
PHP Manual

Imagick::setSamplingFactors

(PECL imagick 2.0.0)

Imagick::setSamplingFactors — Sets the image sampling factors

Opis

bool Imagick::setSamplingFactors ( array $factors )

Sets the image sampling factors.

Parametry

factors

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setResourceLimit
Imagick::setSize
Imagick


Sets the size of the Imagick object

Imagick::setSamplingFactors
Imagick::setSizeOffset
Imagick
PHP Manual

Imagick::setSize

(PECL imagick 2.0.0)

Imagick::setSize — Sets the size of the Imagick object

Opis

bool Imagick::setSize ( int $columns , int $rows )

Sets the size of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.

Parametry

columns

rows

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setSamplingFactors
Imagick::setSizeOffset
Imagick


Sets the size and offset of the Imagick object

Imagick::setSize
Imagick::setType
Imagick
PHP Manual

Imagick::setSizeOffset

(PECL imagick 2.0.0)

Imagick::setSizeOffset — Sets the size and offset of the Imagick object

Opis

bool Imagick::setSizeOffset ( int $columns , int $rows , int $offset )

Sets the size and offset of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

columns

The width in pixels.

rows

The height in pixels.

offset

The image offset.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setSize
Imagick::setType
Imagick


Sets the image type attribute

Imagick::setSizeOffset
Imagick::shadeImage
Imagick
PHP Manual

Imagick::setType

(PECL imagick 2.0.0)

Imagick::setType — Sets the image type attribute

Opis

bool Imagick::setType ( int $image_type )

Sets the image type attribute.

Parametry

image_type

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setSizeOffset
Imagick::shadeImage
Imagick


Creates a 3D effect

Imagick::setType
Imagick::shadowImage
Imagick
PHP Manual

Imagick::shadeImage

(PECL imagick 2.0.0)

Imagick::shadeImage — Creates a 3D effect

Opis

bool Imagick::shadeImage ( bool $gray , float $azimuth , float $elevation )

Shines a distant light on an image to create a three-dimensional effect. You control the positioning of the light with azimuth and elevation; azimuth is measured in degrees off the x axis and elevation is measured in pixels above the Z axis. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

gray

A value other than zero shades the intensity of each pixel.

azimuth

Defines the light source direction.

elevation

Defines the light source direction.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::setType
Imagick::shadowImage
Imagick


Simulates an image shadow

Imagick::shadeImage
Imagick::sharpenImage
Imagick
PHP Manual

Imagick::shadowImage

(PECL imagick 2.0.0)

Imagick::shadowImage — Simulates an image shadow

Opis

bool Imagick::shadowImage ( float $opacity , float $sigma , int $x , int $y )

Simulates an image shadow.

Parametry

opacity

sigma

x

y

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::shadeImage
Imagick::sharpenImage
Imagick


Sharpens an image

Imagick::shadowImage
Imagick::shaveImage
Imagick
PHP Manual

Imagick::sharpenImage

(PECL imagick 2.0.0)

Imagick::sharpenImage — Sharpens an image

Opis

bool Imagick::sharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_ALL ] )

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and selects a suitable radius for you.

Parametry

radius

sigma

channel

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::shadowImage
Imagick::shaveImage
Imagick


Shaves pixels from the image edges

Imagick::sharpenImage
Imagick::shearImage
Imagick
PHP Manual

Imagick::shaveImage

(PECL imagick 2.0.0)

Imagick::shaveImage — Shaves pixels from the image edges

Opis

bool Imagick::shaveImage ( int $columns , int $rows )

Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.

Parametry

columns

rows

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::sharpenImage
Imagick::shearImage
Imagick


Creating a parallelogram

Imagick::shaveImage
Imagick::sigmoidalContrastImage
Imagick
PHP Manual

Imagick::shearImage

(PECL imagick 2.0.0)

Imagick::shearImage — Creating a parallelogram

Opis

bool Imagick::shearImage ( mixed $background , float $x_shear , float $y_shear )

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

Parametry

background

The background color

x_shear

The number of degrees to shear on the x axis

y_shear

The number of degrees to shear on the y axis

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

Imagick::shaveImage
Imagick::sigmoidalContrastImage
Imagick


Adjusts the contrast of an image

Imagick::shearImage
Imagick::sketchImage
Imagick
PHP Manual

Imagick::sigmoidalContrastImage

(PECL imagick 2.0.0)

Imagick::sigmoidalContrastImage — Adjusts the contrast of an image

Opis

bool Imagick::sigmoidalContrastImage ( bool $sharpen , float $alpha , float $beta [, int $channel = Imagick::CHANNEL_ALL ] )

Adjusts the contrast of an image with a non-linear sigmoidal contrast algorithm. Increase the contrast of the image using a sigmoidal transfer function without saturating highlights or shadows. Contrast indicates how much to increase the contrast (0 is none; 3 is typical; 20 is pushing it); mid-point indicates where midtones fall in the resultant image (0 is white; 50 is middle-gray; 100 is black). Set sharpen to TRUE to increase the image contrast otherwise the contrast is reduced.

Parametry

sharpen

alpha

beta

channel

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::shearImage
Imagick::sketchImage
Imagick


Simulates a pencil sketch

Imagick::sigmoidalContrastImage
Imagick::solarizeImage
Imagick
PHP Manual

Imagick::sketchImage

(PECL imagick 2.0.0)

Imagick::sketchImage — Simulates a pencil sketch

Opis

bool Imagick::sketchImage ( float $radius , float $sigma , float $angle )

Simulates a pencil sketch. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::sketchImage() selects a suitable radius for you. Angle gives the angle of the blurring motion. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::sigmoidalContrastImage
Imagick::solarizeImage
Imagick


Applies a solarizing effect to the image

Imagick::sketchImage
Imagick::sparseColorImage
Imagick
PHP Manual

Imagick::solarizeImage

(PECL imagick 2.0.0)

Imagick::solarizeImage — Applies a solarizing effect to the image

Opis

bool Imagick::solarizeImage ( int $threshold )

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

Parametry

threshold

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::sketchImage
Imagick::sparseColorImage
Imagick


Interpolates colors

Imagick::solarizeImage
Imagick::spliceImage
Imagick
PHP Manual

Imagick::sparseColorImage

(No version information available, might only be in SVN)

Imagick::sparseColorImage — Interpolates colors

Opis

public bool Imagick::sparseColorImage ( int $SPARSE_METHOD , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] )

Given the arguments array containing numeric values this method interpolates the colors found at those coordinates across the whole image using sparse_method. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.4.5 lub nowszej.

Parametry

SPARSE_METHOD

Refer to this list of sparse method constants

arguments

An array containing the coordinates. The array is in format array(1,1, 2,45)

CHANNEL

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. Defaults to Imagick::CHANNEL_DEFAULT. Refer to this list of channel constants

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::solarizeImage
Imagick::spliceImage
Imagick


Splices a solid color into the image

Imagick::sparseColorImage
Imagick::spreadImage
Imagick
PHP Manual

Imagick::spliceImage

(PECL imagick 2.0.0)

Imagick::spliceImage — Splices a solid color into the image

Opis

bool Imagick::spliceImage ( int $width , int $height , int $x , int $y )

Splices a solid color into the image.

Parametry

width

height

x

y

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::sparseColorImage
Imagick::spreadImage
Imagick


Randomly displaces each pixel in a block

Imagick::spliceImage
Imagick::steganoImage
Imagick
PHP Manual

Imagick::spreadImage

(PECL imagick 2.0.0)

Imagick::spreadImage — Randomly displaces each pixel in a block

Opis

bool Imagick::spreadImage ( float $radius )

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

Parametry

radius

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::spliceImage
Imagick::steganoImage
Imagick


Hides a digital watermark within the image

Imagick::spreadImage
Imagick::stereoImage
Imagick
PHP Manual

Imagick::steganoImage

(PECL imagick 2.0.0)

Imagick::steganoImage — Hides a digital watermark within the image

Opis

Imagick Imagick::steganoImage ( Imagick $watermark_wand , int $offset )

Hides a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark.

Parametry

watermark_wand

offset

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::spreadImage
Imagick::stereoImage
Imagick


Composites two images

Imagick::steganoImage
Imagick::stripImage
Imagick
PHP Manual

Imagick::stereoImage

(PECL imagick 2.0.0)

Imagick::stereoImage — Composites two images

Opis

bool Imagick::stereoImage ( Imagick $offset_wand )

Composites two images and produces a single image that is the composite of a left and right image of a stereo pair.

Parametry

offset_wand

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::steganoImage
Imagick::stripImage
Imagick


Strips an image of all profiles and comments

Imagick::stereoImage
Imagick::swirlImage
Imagick
PHP Manual

Imagick::stripImage

(PECL imagick 2.0.0)

Imagick::stripImage — Strips an image of all profiles and comments

Opis

bool Imagick::stripImage ( void )

Strips an image of all profiles and comments.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::stereoImage
Imagick::swirlImage
Imagick


Swirls the pixels about the center of the image

Imagick::stripImage
Imagick::textureImage
Imagick
PHP Manual

Imagick::swirlImage

(PECL imagick 2.0.0)

Imagick::swirlImage — Swirls the pixels about the center of the image

Opis

bool Imagick::swirlImage ( float $degrees )

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

Parametry

degrees

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::stripImage
Imagick::textureImage
Imagick


Repeatedly tiles the texture image

Imagick::swirlImage
Imagick::thresholdImage
Imagick
PHP Manual

Imagick::textureImage

(PECL imagick 2.0.0)

Imagick::textureImage — Repeatedly tiles the texture image

Opis

bool Imagick::textureImage ( Imagick $texture_wand )

Repeatedly tiles the texture image across and down the image canvas.

Parametry

texture_wand

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::swirlImage
Imagick::thresholdImage
Imagick


Changes the value of individual pixels based on a threshold

Imagick::textureImage
Imagick::thumbnailImage
Imagick
PHP Manual

Imagick::thresholdImage

(PECL imagick 2.0.0)

Imagick::thresholdImage — Changes the value of individual pixels based on a threshold

Opis

bool Imagick::thresholdImage ( float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.

Parametry

threshold

channel

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::textureImage
Imagick::thumbnailImage
Imagick


Changes the size of an image

Imagick::thresholdImage
Imagick::tintImage
Imagick
PHP Manual

Imagick::thumbnailImage

(PECL imagick 2.0.0)

Imagick::thumbnailImage — Changes the size of an image

Opis

bool Imagick::thumbnailImage ( int $columns , int $rows [, bool $bestfit = false [, bool $fill = false ]] )

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small low cost thumbnail images suited for display on the Web. If TRUE is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until the match or are smaller than the parameter given for the side.

Informacja: The behavior of the parameter bestfit changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If bestfit parameter is used both width and height must be given.

Parametry

columns

Image width

rows

Image height

bestfit

Whether to force maximum values

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::thresholdImage
Imagick::tintImage
Imagick


Applies a color vector to each pixel in the image

Imagick::thumbnailImage
Imagick::transformImage
Imagick
PHP Manual

Imagick::tintImage

(PECL imagick 2.0.0)

Imagick::tintImage — Applies a color vector to each pixel in the image

Opis

bool Imagick::tintImage ( mixed $tint , mixed $opacity )

Applies a color vector to each pixel in the image. The length of the vector is 0 for black and white and at its maximum for the midtones. The vector weighing function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))).

Parametry

tint

opacity

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

Imagick::thumbnailImage
Imagick::transformImage
Imagick


Convenience method for setting crop size and the image geometry

Imagick::tintImage
Imagick::transparentPaintImage
Imagick
PHP Manual

Imagick::transformImage

(PECL imagick 2.0.0)

Imagick::transformImage — Convenience method for setting crop size and the image geometry

Opis

Imagick Imagick::transformImage ( string $crop , string $geometry )

A convenience method for setting crop size and the image geometry from strings. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

crop

A crop geometry string. This geometry defines a subregion of the image to crop.

geometry

An image geometry string. This geometry defines the final size of the image.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Przykłady

Przykład #1 Using Imagick::transformImage():

The example creates a 100x100 black image.

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");
$new_image = $image->transformImage("100x100", "100x100");
$new_image->writeImage('test_out.jpg');
?>

Zobacz też:

  • Imagick::cropImage() - Extracts a region of the image
  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image

Imagick::tintImage
Imagick::transparentPaintImage
Imagick


Paints pixels transparent

Imagick::transformImage
Imagick::transposeImage
Imagick
PHP Manual

Imagick::transparentPaintImage

(No version information available, might only be in SVN)

Imagick::transparentPaintImage — Paints pixels transparent

Opis

bool Imagick::transparentPaintImage ( mixed $target , float $alpha , float $fuzz , bool $invert )

Paints pixels matching the target color transparent. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.8 lub nowszej.

Parametry

target

The target color to paint

alpha

Poziom przezroczystości: 1.0 - w pełni nieprzezroczysty, 0.0 - w pełni przezroczysty.

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

invert

If TRUE paints any pixel that does not match the target color.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::transformImage
Imagick::transposeImage
Imagick


Creates a vertical mirror image

Imagick::transparentPaintImage
Imagick::transverseImage
Imagick
PHP Manual

Imagick::transposeImage

(PECL imagick 2.0.0)

Imagick::transposeImage — Creates a vertical mirror image

Opis

bool Imagick::transposeImage ( void )

Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating them 90-degrees. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::transverseImage() - Creates a horizontal mirror image

Imagick::transparentPaintImage
Imagick::transverseImage
Imagick


Creates a horizontal mirror image

Imagick::transposeImage
Imagick::trimImage
Imagick
PHP Manual

Imagick::transverseImage

(PECL imagick 2.0.0)

Imagick::transverseImage — Creates a horizontal mirror image

Opis

bool Imagick::transverseImage ( void )

Creates a horizontal mirror image by reflecting the pixels around the central y-axis while rotating them 270-degrees. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::transposeImage() - Creates a vertical mirror image

Imagick::transposeImage
Imagick::trimImage
Imagick


Remove edges from the image

Imagick::transverseImage
Imagick::uniqueImageColors
Imagick
PHP Manual

Imagick::trimImage

(PECL imagick 2.0.0)

Imagick::trimImage — Remove edges from the image

Opis

bool Imagick::trimImage ( float $fuzz )

Remove edges that are the background color from the image. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

fuzz

By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Przykłady

Przykład #1 Using Imagick::trimImage():

Trim an image, then display to the browser.

<?php
/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image. */
$im->trimImage(0);

/* Ouput the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>

Zobacz też:

  • Imagick::getQuantumDepth() - Gets the quantum depth
  • Imagick::getQuantumRange() - Returns the Imagick quantum range

Imagick::transverseImage
Imagick::uniqueImageColors
Imagick


Discards all but one of any pixel color

Imagick::trimImage
Imagick::unsharpMaskImage
Imagick
PHP Manual

Imagick::uniqueImageColors

(PECL imagick 2.0.0)

Imagick::uniqueImageColors — Discards all but one of any pixel color

Opis

bool Imagick::uniqueImageColors ( void )

Discards all but one of any pixel color. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::trimImage
Imagick::unsharpMaskImage
Imagick


Sharpens an image

Imagick::uniqueImageColors
Imagick::valid
Imagick
PHP Manual

Imagick::unsharpMaskImage

(PECL imagick 2.0.0)

Imagick::unsharpMaskImage — Sharpens an image

Opis

bool Imagick::unsharpMaskImage ( float $radius , float $sigma , float $amount , float $threshold [, int $channel = Imagick::CHANNEL_ALL ] )

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::UnsharpMaskImage() selects a suitable radius for you.

Parametry

radius

sigma

amount

threshold

channel

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Imagick::uniqueImageColors
Imagick::valid
Imagick


Checks if the current item is valid

Imagick::unsharpMaskImage
Imagick::vignetteImage
Imagick
PHP Manual

Imagick::valid

(PECL imagick 2.0.0)

Imagick::valid — Checks if the current item is valid

Opis

bool Imagick::valid ( void )

Checks if the current item is valid.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::unsharpMaskImage
Imagick::vignetteImage
Imagick


Adds vignette filter to the image

Imagick::valid
Imagick::waveImage
Imagick
PHP Manual

Imagick::vignetteImage

(PECL imagick 2.0.0)

Imagick::vignetteImage — Adds vignette filter to the image

Opis

bool Imagick::vignetteImage ( float $blackPoint , float $whitePoint , int $x , int $y )

Softens the edges of the image in vignette style. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

blackPoint

The black point.

whitePoint

The white point

x

X offset of the ellipse

y

Y offset of the ellipse

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Zobacz też:

  • Imagick::waveImage() - Applies wave filter to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

Imagick::valid
Imagick::waveImage
Imagick


Applies wave filter to the image

Imagick::vignetteImage
Imagick::whiteThresholdImage
Imagick
PHP Manual

Imagick::waveImage

(PECL imagick 2.0.0)

Imagick::waveImage — Applies wave filter to the image

Opis

bool Imagick::waveImage ( float $amplitude , float $length )

Applies a wave filter to the image. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.2.9 lub nowszej.

Parametry

amplitude

The amplitude of the wave.

length

The length of the wave.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Błędy/Wyjątki

Zgłasza wyjątek ImagickException w przypadku błędu.

Zobacz też:

  • Imagick::solarizeImage() - Applies a solarizing effect to the image
  • Imagick::oilpaintImage() - Simulates an oil painting
  • Imagick::embossImage() - Returns a grayscale image with a three-dimensional effect
  • Imagick::addNoiseImage() - Adds random noise to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

Imagick::vignetteImage
Imagick::whiteThresholdImage
Imagick


Force all pixels above the threshold into white

Imagick::waveImage
Imagick::writeImage
Imagick
PHP Manual

Imagick::whiteThresholdImage

(PECL imagick 2.0.0)

Imagick::whiteThresholdImage — Force all pixels above the threshold into white

Opis

bool Imagick::whiteThresholdImage ( mixed $threshold )

Is like Imagick::ThresholdImage() but force all pixels above the threshold into white while leaving all pixels below the threshold unchanged.

Parametry

threshold

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Rejestr zmian

Wersja | Opis
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

Imagick::waveImage
Imagick::writeImage
Imagick


Writes an image to the specified filename

Imagick::whiteThresholdImage
Imagick::writeImageFile
Imagick
PHP Manual

Imagick::writeImage

(PECL imagick 0.9.0-0.9.9)

Imagick::writeImage — Writes an image to the specified filename

Opis

bool Imagick::writeImage ([ string $filename ] )

Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Imagick::ReadImage() or Imagick::SetImageFilename().

Parametry

filename

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::whiteThresholdImage
Imagick::writeImageFile
Imagick


Writes an image to a filehandle

Imagick::writeImage
Imagick::writeImages
Imagick
PHP Manual

Imagick::writeImageFile

(No version information available, might only be in SVN)

Imagick::writeImageFile — Writes an image to a filehandle

Opis

bool Imagick::writeImageFile ( resource $filehandle )

Writes the image sequence to an open filehandle. The handle must be opened with for example fopen. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

filehandle

Filehandle where to write the image

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::writeImage
Imagick::writeImages
Imagick


Writes an image or image sequence

Imagick::writeImageFile
Imagick::writeImagesFile
Imagick
PHP Manual

Imagick::writeImages

(PECL imagick 0.9.0-0.9.9)

Imagick::writeImages — Writes an image or image sequence

Opis

bool Imagick::writeImages ( string $filename , bool $adjoin )

Writes an image or image sequence.

Parametry

filename

adjoin

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::writeImageFile
Imagick::writeImagesFile
Imagick


Writes frames to a filehandle

Imagick::writeImages
ImagickDraw
Imagick
PHP Manual

Imagick::writeImagesFile

(No version information available, might only be in SVN)

Imagick::writeImagesFile — Writes frames to a filehandle

Opis

bool Imagick::writeImagesFile ( resource $filehandle )

Writes all image frames into an open filehandle. This method can be used to write animated gifs or other multiframe images into open filehandle. Ta metoda jest dostępna, jeśli rozszerzenie Imagick zostało skompilowane z ImageMagick w wersji 6.3.6 lub nowszej.

Parametry

filehandle

Filehandle where to write the images

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Imagick::writeImages
ImagickDraw
Imagick


The ImagickDraw class

(No version information available, might only be in SVN)

Krótki opis klasy

ImagickDraw {
bool affine ( array $affine )
bool annotation ( float $x , float $y , string $text )
bool arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
bool bezier ( array $coordinates )
bool circle ( float $ox , float $oy , float $px , float $py )
bool clear ( void )
ImagickDraw clone ( void )
bool color ( float $x , float $y , int $paintMethod )
bool comment ( string $comment )
bool composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand )
__construct ( void )
bool destroy ( void )
bool ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
string getClipPath ( void )
int getClipRule ( void )
int getClipUnits ( void )
ImagickPixel getFillColor ( void )
float getFillOpacity ( void )
int getFillRule ( void )
string getFont ( void )
string getFontFamily ( void )
float getFontSize ( void )
int getFontStyle ( void )
int getFontWeight ( void )
int getGravity ( void )
bool getStrokeAntialias ( void )
ImagickPixel getStrokeColor ( void )
array getStrokeDashArray ( void )
float getStrokeDashOffset ( void )
int getStrokeLineCap ( void )
int getStrokeLineJoin ( void )
int getStrokeMiterLimit ( void )
float getStrokeOpacity ( void )
float getStrokeWidth ( void )
int getTextAlignment ( void )
bool getTextAntialias ( void )
int getTextDecoration ( void )
string getTextEncoding ( void )
ImagickPixel getTextUnderColor ( void )
string getVectorGraphics ( void )
bool line ( float $sx , float $sy , float $ex , float $ey )
bool matte ( float $x , float $y , int $paintMethod )
bool pathClose ( void )
bool pathCurveToAbsolute ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
bool pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , float $y )
bool pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , float $y )
bool pathCurveToQuadraticBezierSmoothAbsolute ( float $x , float $y )
bool pathCurveToQuadraticBezierSmoothRelative ( float $x , float $y )
bool pathCurveToRelative ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
bool pathCurveToSmoothAbsolute ( float $x2 , float $y2 , float $x , float $y )
bool pathCurveToSmoothRelative ( float $x2 , float $y2 , float $x , float $y )
bool pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
bool pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
bool pathFinish ( void )
bool pathLineToAbsolute ( float $x , float $y )
bool pathLineToHorizontalAbsolute ( float $x )
bool pathLineToHorizontalRelative ( float $x )
bool pathLineToRelative ( float $x , float $y )
bool pathLineToVerticalAbsolute ( float $y )
bool pathLineToVerticalRelative ( float $y )
bool pathMoveToAbsolute ( float $x , float $y )
bool pathMoveToRelative ( float $x , float $y )
bool pathStart ( void )
bool point ( float $x , float $y )
bool polygon ( array $coordinates )
bool polyline ( array $coordinates )
bool pop ( void )
bool popClipPath ( void )
bool popDefs ( void )
bool popPattern ( void )
bool push ( void )
bool pushClipPath ( string $clip_mask_id )
bool pushDefs ( void )
bool pushPattern ( string $pattern_id , float $x , float $y , float $width , float $height )
bool rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
bool render ( void )
bool rotate ( float $degrees )
bool roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
bool scale ( float $x , float $y )
bool setClipPath ( string $clip_mask )
bool setClipRule ( int $fill_rule )
bool setClipUnits ( int $clip_units )
bool setFillAlpha ( float $opacity )
bool setFillColor ( ImagickPixel $fill_pixel )
bool setFillOpacity ( float $fillOpacity )
bool setFillPatternURL ( string $fill_url )
bool setFillRule ( int $fill_rule )
bool setFont ( string $font_name )
bool setFontFamily ( string $font_family )
bool setFontSize ( float $pointsize )
bool setFontStretch ( int $fontStretch )
bool setFontStyle ( int $style )
bool setFontWeight ( int $font_weight )
bool setGravity ( int $gravity )
bool setStrokeAlpha ( float $opacity )
bool setStrokeAntialias ( bool $stroke_antialias )
bool setStrokeColor ( ImagickPixel $stroke_pixel )
bool setStrokeDashArray ( array $dashArray )
bool setStrokeDashOffset ( float $dash_offset )
bool setStrokeLineCap ( int $linecap )
bool setStrokeLineJoin ( int $linejoin )
bool setStrokeMiterLimit ( int $miterlimit )
bool setStrokeOpacity ( float $stroke_opacity )
bool setStrokePatternURL ( string $stroke_url )
bool setStrokeWidth ( float $stroke_width )
bool setTextAlignment ( int $alignment )
bool setTextAntialias ( bool $antiAlias )
bool setTextDecoration ( int $decoration )
bool setTextEncoding ( string $encoding )
bool setTextUnderColor ( ImagickPixel $under_color )
bool setVectorGraphics ( string $xml )
bool setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 )
bool skewX ( float $degrees )
bool skewY ( float $degrees )
bool translate ( float $x , float $y )
}

Spis treści

  • ImagickDraw::affine — Adjusts the current affine transformation matrix
  • ImagickDraw::annotation — Draws text on the image
  • ImagickDraw::arc — Draws an arc
  • ImagickDraw::bezier — Draws a bezier curve
  • ImagickDraw::circle — Draws a circle
  • ImagickDraw::clear — Clears the ImagickDraw
  • ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
  • ImagickDraw::color — Draws color on image
  • ImagickDraw::comment — Adds a comment
  • ImagickDraw::composite — Composites an image onto the current image
  • ImagickDraw::__construct — The ImagickDraw constructor
  • ImagickDraw::destroy — Frees all associated resources
  • ImagickDraw::ellipse — Draws an ellipse on the image
  • ImagickDraw::getClipPath — Obtains the current clipping path ID
  • ImagickDraw::getClipRule — Returns the current polygon fill rule
  • ImagickDraw::getClipUnits — Returns the interpretation of clip path units
  • ImagickDraw::getFillColor — Returns the fill color
  • ImagickDraw::getFillOpacity — Returns the opacity used when drawing
  • ImagickDraw::getFillRule — Returns the fill rule
  • ImagickDraw::getFont — Returns the font
  • ImagickDraw::getFontFamily — Returns the font family
  • ImagickDraw::getFontSize — Returns the font pointsize
  • ImagickDraw::getFontStyle — Returns the font style
  • ImagickDraw::getFontWeight — Returns the font weight
  • ImagickDraw::getGravity — Returns the text placement gravity
  • ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
  • ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
  • ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
  • ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
  • ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
  • ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
  • ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
  • ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
  • ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
  • ImagickDraw::getTextAlignment — Returns the text alignment
  • ImagickDraw::getTextAntialias — Returns the current text antialias setting
  • ImagickDraw::getTextDecoration — Returns the text decoration
  • ImagickDraw::getTextEncoding — Returns the code set used for text annotations
  • ImagickDraw::getTextUnderColor — Returns the text under color
  • ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
  • ImagickDraw::line — Draws a line
  • ImagickDraw::matte — Paints on the image's opacity channel
  • ImagickDraw::pathClose — Adds a path element to the current path
  • ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
  • ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
  • ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
  • ImagickDraw::pathFinish — Terminates the current path
  • ImagickDraw::pathLineToAbsolute — Draws a line path
  • ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
  • ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
  • ImagickDraw::pathLineToRelative — Draws a line path
  • ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
  • ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
  • ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
  • ImagickDraw::pathMoveToRelative — Starts a new sub-path
  • ImagickDraw::pathStart — Declares the start of a path drawing list
  • ImagickDraw::point — Draws a point
  • ImagickDraw::polygon — Draws a polygon
  • ImagickDraw::polyline — Draws a polyline
  • ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
  • ImagickDraw::popClipPath — Terminates a clip path definition
  • ImagickDraw::popDefs — Terminates a definition list
  • ImagickDraw::popPattern — Terminates a pattern definition
  • ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
  • ImagickDraw::pushClipPath — Starts a clip path definition
  • ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
  • ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
  • ImagickDraw::rectangle — Draws a rectangle
  • ImagickDraw::render — Renders all preceding drawing commands onto the image
  • ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
  • ImagickDraw::roundRectangle — Draws a rounded rectangle
  • ImagickDraw::scale — Adjusts the scaling factor
  • ImagickDraw::setClipPath — Associates a named clipping path with the image
  • ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
  • ImagickDraw::setClipUnits — Sets the interpretation of clip path units
  • ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
  • ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
  • ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
  • ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
  • ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
  • ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
  • ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
  • ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
  • ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
  • ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
  • ImagickDraw::setFontWeight — Sets the font weight
  • ImagickDraw::setGravity — Sets the text placement gravity
  • ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
  • ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
  • ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
  • ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
  • ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
  • ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
  • ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
  • ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
  • ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
  • ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
  • ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
  • ImagickDraw::setTextAlignment — Specifies a text alignment
  • ImagickDraw::setTextAntialias — Controls whether text is antialiased
  • ImagickDraw::setTextDecoration — Specifies a decoration
  • ImagickDraw::setTextEncoding — Specifies specifies the text code set
  • ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
  • ImagickDraw::setVectorGraphics — Sets the vector graphics
  • ImagickDraw::setViewbox — Sets the overall canvas size
  • ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
  • ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
  • ImagickDraw::translate — Applies a translation to the current coordinate system
Imagick::writeImagesFile
ImagickDraw::affine
ImageMagick


Adjusts the current affine transformation matrix

ImagickDraw
ImagickDraw::annotation
ImagickDraw
PHP Manual

ImagickDraw::affine

(PECL imagick 2.0.0)

ImagickDraw::affine — Adjusts the current affine transformation matrix

Opis

bool ImagickDraw::affine ( array $affine )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Adjusts the current affine transformation matrix with the specified affine transformation matrix.

Parametry

affine

Affine matrix parameters

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw
ImagickDraw::annotation
ImagickDraw


Draws text on the image

ImagickDraw::affine
ImagickDraw::arc
ImagickDraw
PHP Manual

ImagickDraw::annotation

(PECL imagick 2.0.0)

ImagickDraw::annotation — Draws text on the image

Opis

bool ImagickDraw::annotation ( float $x , float $y , string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws text on the image.

Parametry

x

The x coordinate where text is drawn

y

The y coordinate where text is drawn

text

The text to draw on the image

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::affine
ImagickDraw::arc
ImagickDraw


Draws an arc

ImagickDraw::annotation
ImagickDraw::bezier
ImagickDraw
PHP Manual

ImagickDraw::arc

(PECL imagick 2.0.0)

ImagickDraw::arc — Draws an arc

Opis

bool ImagickDraw::arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws an arc falling within a specified bounding rectangle on the image.

Parametry

sx

Starting x ordinate of bounding rectangle

sy

starting y ordinate of bounding rectangle

ex

ending x ordinate of bounding rectangle

ey

ending y ordinate of bounding rectangle

sd

starting degrees of rotation

ed

ending degrees of rotation

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::annotation
ImagickDraw::bezier
ImagickDraw


Draws a bezier curve

ImagickDraw::arc
ImagickDraw::circle
ImagickDraw
PHP Manual

ImagickDraw::bezier

(PECL imagick 2.0.0)

ImagickDraw::bezier — Draws a bezier curve

Opis

bool ImagickDraw::bezier ( array $coordinates )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a bezier curve through a set of points on the image.

Parametry

coordinates

Multidimensional array like array( array( 'x' => 1, 'y' => 2 ), array( 'x' => 3, 'y' => 4 ) )

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::arc
ImagickDraw::circle
ImagickDraw


Draws a circle

ImagickDraw::bezier
ImagickDraw::clear
ImagickDraw
PHP Manual

ImagickDraw::circle

(PECL imagick 2.0.0)

ImagickDraw::circle — Draws a circle

Opis

bool ImagickDraw::circle ( float $ox , float $oy , float $px , float $py )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a circle on the image.

Parametry

ox

origin x coordinate

oy

origin y coordinate

px

perimeter x coordinate

py

perimeter y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::bezier
ImagickDraw::clear
ImagickDraw


Clears the ImagickDraw

ImagickDraw::circle
ImagickDraw::clone
ImagickDraw
PHP Manual

ImagickDraw::clear

(PECL imagick 2.0.0)

ImagickDraw::clear — Clears the ImagickDraw

Opis

bool ImagickDraw::clear ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Clears the ImagickDraw object of any accumulated commands, and resets the settings it contains to their defaults.

Zwracane wartości

Returns an ImagickDraw object.

ImagickDraw::circle
ImagickDraw::clone
ImagickDraw


Makes an exact copy of the specified ImagickDraw object

ImagickDraw::clear
ImagickDraw::color
ImagickDraw
PHP Manual

ImagickDraw::clone

(PECL imagick 2.0.0)

ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object

Opis

ImagickDraw ImagickDraw::clone ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Makes an exact copy of the specified ImagickDraw object.

Zwracane wartości

What the function returns, first on success, then on failure. See also the &return.success; entity

ImagickDraw::clear
ImagickDraw::color
ImagickDraw


Draws color on image

ImagickDraw::clone
ImagickDraw::comment
ImagickDraw
PHP Manual

ImagickDraw::color

(PECL imagick 2.0.0)

ImagickDraw::color — Draws color on image

Opis

bool ImagickDraw::color ( float $x , float $y , int $paintMethod )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws color on image using the current fill color, starting at specified position, and using specified paint method.

Parametry

x

x coordinate of the paint

y

y coordinate of the paint

paintMethod

one of the PAINT_ constants

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::clone
ImagickDraw::comment
ImagickDraw


Adds a comment

ImagickDraw::color
ImagickDraw::composite
ImagickDraw
PHP Manual

ImagickDraw::comment

(PECL imagick 2.0.0)

ImagickDraw::comment — Adds a comment

Opis

bool ImagickDraw::comment ( string $comment )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Adds a comment to a vector output stream.

Parametry

comment

The comment string to add to vector output stream

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::color
ImagickDraw::composite
ImagickDraw


Composites an image onto the current image

ImagickDraw::comment
ImagickDraw::__construct
ImagickDraw
PHP Manual

ImagickDraw::composite

(PECL imagick 2.0.0)

ImagickDraw::composite — Composites an image onto the current image

Opis

bool ImagickDraw::composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Composites an image onto the current image, using the specified composition operator, specified position, and at the specified size.

Parametry

compose

composition operator. One of COMPOSITE_ constants

x

x coordinate of the top left corner

y

y coordinate of the top left corner

width

width of the composition image

height

height of the composition image

compositeWand

the Imagick object where composition image is taken from

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickDraw::comment
ImagickDraw::__construct
ImagickDraw


The ImagickDraw constructor

ImagickDraw::composite
ImagickDraw::destroy
ImagickDraw
PHP Manual

ImagickDraw::__construct

(PECL imagick 2.0.0)

ImagickDraw::__construct — The ImagickDraw constructor

Opis

ImagickDraw::__construct ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

The ImagickDraw constructor

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::composite
ImagickDraw::destroy
ImagickDraw


Frees all associated resources

ImagickDraw::__construct
ImagickDraw::ellipse
ImagickDraw
PHP Manual

ImagickDraw::destroy

(PECL imagick 2.0.0)

ImagickDraw::destroy — Frees all associated resources

Opis

bool ImagickDraw::destroy ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Frees all resources associated with the ImagickDraw object.

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::__construct
ImagickDraw::ellipse
ImagickDraw


Draws an ellipse on the image

ImagickDraw::destroy
ImagickDraw::getClipPath
ImagickDraw
PHP Manual

ImagickDraw::ellipse

(PECL imagick 2.0.0)

ImagickDraw::ellipse — Draws an ellipse on the image

Opis

bool ImagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws an ellipse on the image.

Parametry

ox

oy

rx

ry

start

end

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::destroy
ImagickDraw::getClipPath
ImagickDraw


Obtains the current clipping path ID

ImagickDraw::ellipse
ImagickDraw::getClipRule
ImagickDraw
PHP Manual

ImagickDraw::getClipPath

(PECL imagick 2.0.0)

ImagickDraw::getClipPath — Obtains the current clipping path ID

Opis

string ImagickDraw::getClipPath ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Obtains the current clipping path ID.

Zwracane wartości

Returns a string containing the clip path ID or false if no clip path exists.

ImagickDraw::ellipse
ImagickDraw::getClipRule
ImagickDraw


Returns the current polygon fill rule

ImagickDraw::getClipPath
ImagickDraw::getClipUnits
ImagickDraw
PHP Manual

ImagickDraw::getClipRule

(PECL imagick 2.0.0)

ImagickDraw::getClipRule — Returns the current polygon fill rule

Opis

int ImagickDraw::getClipRule ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the current polygon fill rule to be used by the clipping path.

Zwracane wartości

Returns one of the FILLRULE_ constants.

ImagickDraw::getClipPath
ImagickDraw::getClipUnits
ImagickDraw


Returns the interpretation of clip path units

ImagickDraw::getClipRule
ImagickDraw::getFillColor
ImagickDraw
PHP Manual

ImagickDraw::getClipUnits

(PECL imagick 2.0.0)

ImagickDraw::getClipUnits — Returns the interpretation of clip path units

Opis

int ImagickDraw::getClipUnits ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the interpretation of clip path units.

Zwracane wartości

Returns an int on success.

ImagickDraw::getClipRule
ImagickDraw::getFillColor
ImagickDraw


Returns the fill color

ImagickDraw::getClipUnits
ImagickDraw::getFillOpacity
ImagickDraw
PHP Manual

ImagickDraw::getFillColor

(PECL imagick 2.0.0)

ImagickDraw::getFillColor — Returns the fill color

Opis

ImagickPixel ImagickDraw::getFillColor ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the fill color used for drawing filled objects.

Zwracane wartości

Returns an ImagickPixel object.

ImagickDraw::getClipUnits
ImagickDraw::getFillOpacity
ImagickDraw


Returns the opacity used when drawing

ImagickDraw::getFillColor
ImagickDraw::getFillRule
ImagickDraw
PHP Manual

ImagickDraw::getFillOpacity

(PECL imagick 2.0.0)

ImagickDraw::getFillOpacity — Returns the opacity used when drawing

Opis

float ImagickDraw::getFillOpacity ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

Zwracane wartości

The opacity.

ImagickDraw::getFillColor
ImagickDraw::getFillRule
ImagickDraw


Returns the fill rule

ImagickDraw::getFillOpacity
ImagickDraw::getFont
ImagickDraw
PHP Manual

ImagickDraw::getFillRule

(PECL imagick 2.0.0)

ImagickDraw::getFillRule — Returns the fill rule

Opis

int ImagickDraw::getFillRule ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the fill rule used while drawing polygons.

Zwracane wartości

Returns a FILLRULE_ constant

ImagickDraw::getFillOpacity
ImagickDraw::getFont
ImagickDraw


Returns the font

ImagickDraw::getFillRule
ImagickDraw::getFontFamily
ImagickDraw
PHP Manual

ImagickDraw::getFont

(PECL imagick 2.0.0)

ImagickDraw::getFont — Returns the font

Opis

string ImagickDraw::getFont ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns a string specifying the font used when annotating with text.

Zwracane wartości

Returns a string on success and false if no font is set.

ImagickDraw::getFillRule
ImagickDraw::getFontFamily
ImagickDraw


Returns the font family

ImagickDraw::getFont
ImagickDraw::getFontSize
ImagickDraw
PHP Manual

ImagickDraw::getFontFamily

(PECL imagick 2.0.0)

ImagickDraw::getFontFamily — Returns the font family

Opis

string ImagickDraw::getFontFamily ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the font family to use when annotating with text.

Zwracane wartości

Returns the font family currently selected or false if font family is not set.

ImagickDraw::getFont
ImagickDraw::getFontSize
ImagickDraw


Returns the font pointsize

ImagickDraw::getFontFamily
ImagickDraw::getFontStyle
ImagickDraw
PHP Manual

ImagickDraw::getFontSize

(PECL imagick 2.0.0)

ImagickDraw::getFontSize — Returns the font pointsize

Opis

float ImagickDraw::getFontSize ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the font pointsize used when annotating with text.

Zwracane wartości

Returns the font size associated with the current ImagickDraw object.

ImagickDraw::getFontFamily
ImagickDraw::getFontStyle
ImagickDraw


Returns the font style

ImagickDraw::getFontSize
ImagickDraw::getFontWeight
ImagickDraw
PHP Manual

ImagickDraw::getFontStyle

(PECL imagick 2.0.0)

ImagickDraw::getFontStyle — Returns the font style

Opis

int ImagickDraw::getFontStyle ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the font style used when annotating with text.

Zwracane wartości

Returns the font style constant (STYLE_) associated with the ImagickDraw object or 0 if no style is set.

ImagickDraw::getFontSize
ImagickDraw::getFontWeight
ImagickDraw


Returns the font weight

ImagickDraw::getFontStyle
ImagickDraw::getGravity
ImagickDraw
PHP Manual

ImagickDraw::getFontWeight

(PECL imagick 2.0.0)

ImagickDraw::getFontWeight — Returns the font weight

Opis

int ImagickDraw::getFontWeight ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the font weight used when annotating with text.

Zwracane wartości

Returns an int on success and 0 if no weight is set.

ImagickDraw::getFontStyle
ImagickDraw::getGravity
ImagickDraw


Returns the text placement gravity

ImagickDraw::getFontWeight
ImagickDraw::getStrokeAntialias
ImagickDraw
PHP Manual

ImagickDraw::getGravity

(PECL imagick 2.0.0)

ImagickDraw::getGravity — Returns the text placement gravity

Opis

int ImagickDraw::getGravity ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the text placement gravity used when annotating with text.

Zwracane wartości

Returns a GRAVITY_ constant on success and 0 if no gravity is set.

ImagickDraw::getFontWeight
ImagickDraw::getStrokeAntialias
ImagickDraw


Returns the current stroke antialias setting

ImagickDraw::getGravity
ImagickDraw::getStrokeColor
ImagickDraw
PHP Manual

ImagickDraw::getStrokeAntialias

(PECL imagick 2.0.0)

ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting

Opis

bool ImagickDraw::getStrokeAntialias ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the current stroke antialias setting. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

Zwracane wartości

Returns TRUE if antialiasing is on and false if it is off.

ImagickDraw::getGravity
ImagickDraw::getStrokeColor
ImagickDraw


Returns the color used for stroking object outlines

ImagickDraw::getStrokeAntialias
ImagickDraw::getStrokeDashArray
ImagickDraw
PHP Manual

ImagickDraw::getStrokeColor

(PECL imagick 2.0.0)

ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines

Opis

ImagickPixel ImagickDraw::getStrokeColor ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the color used for stroking object outlines.

Parametry

stroke_color

Zwracane wartości

Returns an ImagickPixel object which describes the color.

ImagickDraw::getStrokeAntialias
ImagickDraw::getStrokeDashArray
ImagickDraw


Returns an array representing the pattern of dashes and gaps used to stroke paths

ImagickDraw::getStrokeColor
ImagickDraw::getStrokeDashOffset
ImagickDraw
PHP Manual

ImagickDraw::getStrokeDashArray

(PECL imagick 2.0.0)

ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths

Opis

array ImagickDraw::getStrokeDashArray ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns an array representing the pattern of dashes and gaps used to stroke paths.

Zwracane wartości

Returns an array on success and empty array if not set.

ImagickDraw::getStrokeColor
ImagickDraw::getStrokeDashOffset
ImagickDraw


Returns the offset into the dash pattern to start the dash

ImagickDraw::getStrokeDashArray
ImagickDraw::getStrokeLineCap
ImagickDraw
PHP Manual

ImagickDraw::getStrokeDashOffset

(PECL imagick 2.0.0)

ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash

Opis

float ImagickDraw::getStrokeDashOffset ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the offset into the dash pattern to start the dash.

Zwracane wartości

Returns a float representing the offset and 0 if it's not set.

ImagickDraw::getStrokeDashArray
ImagickDraw::getStrokeLineCap
ImagickDraw


Returns the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::getStrokeDashOffset
ImagickDraw::getStrokeLineJoin
ImagickDraw
PHP Manual

ImagickDraw::getStrokeLineCap

(PECL imagick 2.0.0)

ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked

Opis

int ImagickDraw::getStrokeLineCap ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the shape to be used at the end of open subpaths when they are stroked.

Zwracane wartości

Returns one of the LINECAP_ constants or 0 if stroke linecap is not set.

ImagickDraw::getStrokeDashOffset
ImagickDraw::getStrokeLineJoin
ImagickDraw


Returns the shape to be used at the corners of paths when they are stroked

ImagickDraw::getStrokeLineCap
ImagickDraw::getStrokeMiterLimit
ImagickDraw
PHP Manual

ImagickDraw::getStrokeLineJoin

(PECL imagick 2.0.0)

ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked

Opis

int ImagickDraw::getStrokeLineJoin ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

Zwracane wartości

Returns one of the LINEJOIN_ constants or 0 if stroke line join is not set.

ImagickDraw::getStrokeLineCap
ImagickDraw::getStrokeMiterLimit
ImagickDraw


Returns the stroke miter limit

ImagickDraw::getStrokeLineJoin
ImagickDraw::getStrokeOpacity
ImagickDraw
PHP Manual

ImagickDraw::getStrokeMiterLimit

(PECL imagick 2.0.0)

ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit

Opis

int ImagickDraw::getStrokeMiterLimit ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The 'miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

Zwracane wartości

Returns an int describing the miter limit and 0 if no miter limit is set.

ImagickDraw::getStrokeLineJoin
ImagickDraw::getStrokeOpacity
ImagickDraw


Returns the opacity of stroked object outlines

ImagickDraw::getStrokeMiterLimit
ImagickDraw::getStrokeWidth
ImagickDraw
PHP Manual

ImagickDraw::getStrokeOpacity

(PECL imagick 2.0.0)

ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines

Opis

float ImagickDraw::getStrokeOpacity ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the opacity of stroked object outlines.

Zwracane wartości

Returns a double describing the opacity.

ImagickDraw::getStrokeMiterLimit
ImagickDraw::getStrokeWidth
ImagickDraw


Returns the width of the stroke used to draw object outlines

ImagickDraw::getStrokeOpacity
ImagickDraw::getTextAlignment
ImagickDraw
PHP Manual

ImagickDraw::getStrokeWidth

(PECL imagick 2.0.0)

ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines

Opis

float ImagickDraw::getStrokeWidth ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the width of the stroke used to draw object outlines.

Zwracane wartości

Returns a double describing the stroke width.

ImagickDraw::getStrokeOpacity
ImagickDraw::getTextAlignment
ImagickDraw


Returns the text alignment

ImagickDraw::getStrokeWidth
ImagickDraw::getTextAntialias
ImagickDraw
PHP Manual

ImagickDraw::getTextAlignment

(PECL imagick 2.0.0)

ImagickDraw::getTextAlignment — Returns the text alignment

Opis

int ImagickDraw::getTextAlignment ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the alignment applied when annotating with text.

Zwracane wartości

Returns one of the ALIGN_ constants and 0 if no align is set.

ImagickDraw::getStrokeWidth
ImagickDraw::getTextAntialias
ImagickDraw


Returns the current text antialias setting

ImagickDraw::getTextAlignment
ImagickDraw::getTextDecoration
ImagickDraw
PHP Manual

ImagickDraw::getTextAntialias

(PECL imagick 2.0.0)

ImagickDraw::getTextAntialias — Returns the current text antialias setting

Opis

bool ImagickDraw::getTextAntialias ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the current text antialias setting, which determines whether text is antialiased. Text is antialiased by default.

Zwracane wartości

Returns TRUE if text is antialiased and false if not.

ImagickDraw::getTextAlignment
ImagickDraw::getTextDecoration
ImagickDraw


Returns the text decoration

ImagickDraw::getTextAntialias
ImagickDraw::getTextEncoding
ImagickDraw
PHP Manual

ImagickDraw::getTextDecoration

(PECL imagick 2.0.0)

ImagickDraw::getTextDecoration — Returns the text decoration

Opis

int ImagickDraw::getTextDecoration ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the decoration applied when annotating with text.

Zwracane wartości

Returns one of the DECORATION_ constants and 0 if no decoration is set.

ImagickDraw::getTextAntialias
ImagickDraw::getTextEncoding
ImagickDraw


Returns the code set used for text annotations

ImagickDraw::getTextDecoration
ImagickDraw::getTextUnderColor
ImagickDraw
PHP Manual

ImagickDraw::getTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::getTextEncoding — Returns the code set used for text annotations

Opis

string ImagickDraw::getTextEncoding ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns a string which specifies the code set used for text annotations.

Zwracane wartości

Returns a string specifying the code set or false if text encoding is not set.

ImagickDraw::getTextDecoration
ImagickDraw::getTextUnderColor
ImagickDraw


Returns the text under color

ImagickDraw::getTextEncoding
ImagickDraw::getVectorGraphics
ImagickDraw
PHP Manual

ImagickDraw::getTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::getTextUnderColor — Returns the text under color

Opis

ImagickPixel ImagickDraw::getTextUnderColor ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the color of a background rectangle to place under text annotations.

Zwracane wartości

Returns an ImagickPixel object describing the color.

ImagickDraw::getTextEncoding
ImagickDraw::getVectorGraphics
ImagickDraw


Returns a string containing vector graphics

ImagickDraw::getTextUnderColor
ImagickDraw::line
ImagickDraw
PHP Manual

ImagickDraw::getVectorGraphics

(PECL imagick 2.0.0)

ImagickDraw::getVectorGraphics — Returns a string containing vector graphics

Opis

string ImagickDraw::getVectorGraphics ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns a string which specifies the vector graphics generated by any graphics calls made since the ImagickDraw object was instantiated.

Zwracane wartości

Returns a string containing the vector graphics.

ImagickDraw::getTextUnderColor
ImagickDraw::line
ImagickDraw


Draws a line

ImagickDraw::getVectorGraphics
ImagickDraw::matte
ImagickDraw
PHP Manual

ImagickDraw::line

(PECL imagick 2.0.0)

ImagickDraw::line — Draws a line

Opis

bool ImagickDraw::line ( float $sx , float $sy , float $ex , float $ey )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

Parametry

sx

starting x coordinate

sy

starting y coordinate

ex

ending x coordinate

ey

ending y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::getVectorGraphics
ImagickDraw::matte
ImagickDraw


Paints on the image's opacity channel

ImagickDraw::line
ImagickDraw::pathClose
ImagickDraw
PHP Manual

ImagickDraw::matte

(PECL imagick 2.0.0)

ImagickDraw::matte — Paints on the image's opacity channel

Opis

bool ImagickDraw::matte ( float $x , float $y , int $paintMethod )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Paints on the image's opacity channel in order to set effected pixels to transparent, to influence the opacity of pixels.

Parametry

x

x coordinate of the matte

y

y coordinate of the matte

paintMethod

PAINT_ constant

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ImagickDraw::line
ImagickDraw::pathClose
ImagickDraw


Adds a path element to the current path

ImagickDraw::matte
ImagickDraw::pathCurveToAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathClose

(PECL imagick 2.0.0)

ImagickDraw::pathClose — Adds a path element to the current path

Opis

bool ImagickDraw::pathClose ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Adds a path element to the current path which closes the current subpath by drawing a straight line from the current point to the current subpath's most recent starting point (usually, the most recent moveto point).

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::matte
ImagickDraw::pathCurveToAbsolute
ImagickDraw


Draws a cubic Bezier curve

ImagickDraw::pathClose
ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathCurveToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve

Opis

bool ImagickDraw::pathCurveToAbsolute ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parametry

x1

x coordinate of the first control point

y1

y coordinate of the first control point

x2

x coordinate of the second control point

y2

y coordinate of the first control point

x

x coordinate of the curve end

y

y coordinate of the curve end

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathClose
ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToAbsolute
ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw
PHP Manual

ImagickDraw::pathCurveToQuadraticBezierAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve

Opis

bool ImagickDraw::pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parametry

x1

x coordinate of the control point

y1

y coordinate of the control point

x

x coordinate of the end point

y

y coordinate of the end point

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathCurveToAbsolute
ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathCurveToQuadraticBezierRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve

Opis

bool ImagickDraw::pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parametry

x1

starting x coordinate

y1

starting y coordinate

x

ending x coordinate

y

ending y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathCurveToQuadraticBezierAbsolute
ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw
PHP Manual

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve

Opis

bool ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a quadratic Bezier curve (using absolute coordinates) from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point.). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parametry

x

ending x coordinate

y

ending y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathCurveToQuadraticBezierRelative
ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw


Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw::pathCurveToRelative
ImagickDraw
PHP Manual

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve

Opis

bool ImagickDraw::pathCurveToQuadraticBezierSmoothRelative ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a quadratic Bezier curve (using relative coordinates) from the current point to (x, y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point). At the end of the command, the new current point becomes the final (x, y) coordinate pair used in the polybezier.

Parametry

x

ending x coordinate

y

ending y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
ImagickDraw::pathCurveToRelative
ImagickDraw


Draws a cubic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathCurveToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve

Opis

bool ImagickDraw::pathCurveToRelative ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parametry

x1

x coordinate of starting control point

y1

y coordinate of starting control point

x2

x coordinate of ending control point

y2

y coordinate of ending control point

x

ending x coordinate

y

ending y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw


Draws a cubic Bezier curve

ImagickDraw::pathCurveToRelative
ImagickDraw::pathCurveToSmoothRelative
ImagickDraw
PHP Manual

ImagickDraw::pathCurveToSmoothAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve

Opis

bool ImagickDraw::pathCurveToSmoothAbsolute ( float $x2 , float $y2 , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a cubic Bezier curve from the current point to (x,y) using absolute coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parametry

x2

x coordinate of the second control point

y2

y coordinate of the second control point

x

x coordinate of the ending point

y

y coordinate of the ending point

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathCurveToRelative
ImagickDraw::pathCurveToSmoothRelative
ImagickDraw


Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw::pathEllipticArcAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathCurveToSmoothRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve

Opis

bool ImagickDraw::pathCurveToSmoothRelative ( float $x2 , float $y2 , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a cubic Bezier curve from the current point to (x,y) using relative coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

Parametry

x2

x coordinate of the second control point

y2

y coordinate of the second control point

x

x coordinate of the ending point

y

y coordinate of the ending point

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathCurveToSmoothAbsolute
ImagickDraw::pathEllipticArcAbsolute
ImagickDraw


Draws an elliptical arc

ImagickDraw::pathCurveToSmoothRelative
ImagickDraw::pathEllipticArcRelative
ImagickDraw
PHP Manual

ImagickDraw::pathEllipticArcAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc

Opis

bool ImagickDraw::pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws an elliptical arc from the current point to (x, y) using absolute coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If largeArcFlag is TRUE then draw the larger of the available arcs. If sweepFlag is true, then draw the arc matching a clock-wise rotation.

Parametry

rx

x radius

ry

y radius

x_axis_rotation

x axis rotation

large_arc_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathCurveToSmoothRelative
ImagickDraw::pathEllipticArcRelative
ImagickDraw


Draws an elliptical arc

ImagickDraw::pathEllipticArcAbsolute
ImagickDraw::pathFinish
ImagickDraw
PHP Manual

ImagickDraw::pathEllipticArcRelative

(PECL imagick 2.0.0)

ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc

Opis

bool ImagickDraw::pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws an elliptical arc from the current point to (x, y) using relative coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If largeArcFlag is TRUE then draw the larger of the available arcs. If sweepFlag is true, then draw the arc matching a clock-wise rotation.

Parametry

rx

x radius

ry

y radius

x_axis_rotation

x axis rotation

large_arc_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathEllipticArcAbsolute
ImagickDraw::pathFinish
ImagickDraw


Terminates the current path

ImagickDraw::pathEllipticArcRelative
ImagickDraw::pathLineToAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathFinish

(PECL imagick 2.0.0)

ImagickDraw::pathFinish — Terminates the current path

Opis

bool ImagickDraw::pathFinish ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Terminates the current path.

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathEllipticArcRelative
ImagickDraw::pathLineToAbsolute
ImagickDraw


Draws a line path

ImagickDraw::pathFinish
ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathLineToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToAbsolute — Draws a line path

Opis

bool ImagickDraw::pathLineToAbsolute ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a line path from the current point to the given coordinate using absolute coordinates. The coordinate then becomes the new current point.

Parametry

x

starting x coordinate

y

ending x coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathFinish
ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw


Draws a horizontal line path

ImagickDraw::pathLineToAbsolute
ImagickDraw::pathLineToHorizontalRelative
ImagickDraw
PHP Manual

ImagickDraw::pathLineToHorizontalAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path

Opis

bool ImagickDraw::pathLineToHorizontalAbsolute ( float $x )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a horizontal line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

Parametry

x

x coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathLineToAbsolute
ImagickDraw::pathLineToHorizontalRelative
ImagickDraw


Draws a horizontal line

ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw::pathLineToRelative
ImagickDraw
PHP Manual

ImagickDraw::pathLineToHorizontalRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line

Opis

bool ImagickDraw::pathLineToHorizontalRelative ( float $x )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a horizontal line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

Parametry

x

x coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathLineToHorizontalAbsolute
ImagickDraw::pathLineToRelative
ImagickDraw


Draws a line path

ImagickDraw::pathLineToHorizontalRelative
ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathLineToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToRelative — Draws a line path

Opis

bool ImagickDraw::pathLineToRelative ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a line path from the current point to the given coordinate using relative coordinates. The coordinate then becomes the new current point.

Parametry

x

starting x coordinate

y

starting y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathLineToHorizontalRelative
ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw


Draws a vertical line

ImagickDraw::pathLineToRelative
ImagickDraw::pathLineToVerticalRelative
ImagickDraw
PHP Manual

ImagickDraw::pathLineToVerticalAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line

Opis

bool ImagickDraw::pathLineToVerticalAbsolute ( float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a vertical line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

Parametry

y

y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathLineToRelative
ImagickDraw::pathLineToVerticalRelative
ImagickDraw


Draws a vertical line path

ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw::pathMoveToAbsolute
ImagickDraw
PHP Manual

ImagickDraw::pathLineToVerticalRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path

Opis

bool ImagickDraw::pathLineToVerticalRelative ( float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a vertical line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

Parametry

y

y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathLineToVerticalAbsolute
ImagickDraw::pathMoveToAbsolute
ImagickDraw


Starts a new sub-path

ImagickDraw::pathLineToVerticalRelative
ImagickDraw::pathMoveToRelative
ImagickDraw
PHP Manual

ImagickDraw::pathMoveToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathMoveToAbsolute — Starts a new sub-path

Opis

bool ImagickDraw::pathMoveToAbsolute ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Starts a new sub-path at the given coordinate using absolute coordinates. The current point then becomes the specified coordinate.

Parametry

x

x coordinate of the starting point

y

y coordinate of the starting point

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathLineToVerticalRelative
ImagickDraw::pathMoveToRelative
ImagickDraw


Starts a new sub-path

ImagickDraw::pathMoveToAbsolute
ImagickDraw::pathStart
ImagickDraw
PHP Manual

ImagickDraw::pathMoveToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathMoveToRelative — Starts a new sub-path

Opis

bool ImagickDraw::pathMoveToRelative ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Starts a new sub-path at the given coordinate using relative coordinates. The current point then becomes the specified coordinate.

Parametry

x

target x coordinate

y

target y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathMoveToAbsolute
ImagickDraw::pathStart
ImagickDraw


Declares the start of a path drawing list

ImagickDraw::pathMoveToRelative
ImagickDraw::point
ImagickDraw
PHP Manual

ImagickDraw::pathStart

(PECL imagick 2.0.0)

ImagickDraw::pathStart — Declares the start of a path drawing list

Opis

bool ImagickDraw::pathStart ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Declares the start of a path drawing list which is terminated by a matching DrawPathFinish() command. All other DrawPath commands must be enclosed between a and a DrawPathFinish() command. This is because path drawing commands are subordinate commands and they do not function by themselves.

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathMoveToRelative
ImagickDraw::point
ImagickDraw


Draws a point

ImagickDraw::pathStart
ImagickDraw::polygon
ImagickDraw
PHP Manual

ImagickDraw::point

(PECL imagick 2.0.0)

ImagickDraw::point — Draws a point

Opis

bool ImagickDraw::point ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

Parametry

x

point's x coordinate

y

point's y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pathStart
ImagickDraw::polygon
ImagickDraw


Draws a polygon

ImagickDraw::point
ImagickDraw::polyline
ImagickDraw
PHP Manual

ImagickDraw::polygon

(PECL imagick 2.0.0)

ImagickDraw::polygon — Draws a polygon

Opis

bool ImagickDraw::polygon ( array $coordinates )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parametry

coordinates

multidimensional array like array( array( 'x' => 3, 'y' => 4 ), array( 'x' => 2, 'y' => 6 ) );

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickDraw::point
ImagickDraw::polyline
ImagickDraw


Draws a polyline

ImagickDraw::polygon
ImagickDraw::pop
ImagickDraw
PHP Manual

ImagickDraw::polyline

(PECL imagick 2.0.0)

ImagickDraw::polyline — Draws a polyline

Opis

bool ImagickDraw::polyline ( array $coordinates )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

Parametry

coordinates

array of x and y coordinates: array( array( 'x' => 4, 'y' => 6 ), array( 'x' => 8, 'y' => 10 ) )

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickDraw::polygon
ImagickDraw::pop
ImagickDraw


Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

ImagickDraw::polyline
ImagickDraw::popClipPath
ImagickDraw
PHP Manual

ImagickDraw::pop

(PECL imagick 2.0.0)

ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

Opis

bool ImagickDraw::pop ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw. Multiple ImagickDraws may exist. It is an error to attempt to pop more ImagickDraws than have been pushed, and it is proper form to pop all ImagickDraws which have been pushed.

Zwracane wartości

Returns TRUE on success and false on failure.

ImagickDraw::polyline
ImagickDraw::popClipPath
ImagickDraw


Terminates a clip path definition

ImagickDraw::pop
ImagickDraw::popDefs
ImagickDraw
PHP Manual

ImagickDraw::popClipPath

(PECL imagick 2.0.0)

ImagickDraw::popClipPath — Terminates a clip path definition

Opis

bool ImagickDraw::popClipPath ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Terminates a clip path definition.

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pop
ImagickDraw::popDefs
ImagickDraw


Terminates a definition list

ImagickDraw::popClipPath
ImagickDraw::popPattern
ImagickDraw
PHP Manual

ImagickDraw::popDefs

(PECL imagick 2.0.0)

ImagickDraw::popDefs — Terminates a definition list

Opis

bool ImagickDraw::popDefs ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Terminates a definition list.

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::popClipPath
ImagickDraw::popPattern
ImagickDraw


Terminates a pattern definition

ImagickDraw::popDefs
ImagickDraw::push
ImagickDraw
PHP Manual

ImagickDraw::popPattern

(PECL imagick 2.0.0)

ImagickDraw::popPattern — Terminates a pattern definition

Opis

bool ImagickDraw::popPattern ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Terminates a pattern definition.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ImagickDraw::popDefs
ImagickDraw::push
ImagickDraw


Clones the current ImagickDraw and pushes it to the stack

ImagickDraw::popPattern
ImagickDraw::pushClipPath
ImagickDraw
PHP Manual

ImagickDraw::push

(PECL imagick 2.0.0)

ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack

Opis

bool ImagickDraw::push ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Clones the current ImagickDraw to create a new ImagickDraw, which is then added to the ImagickDraw stack. The original drawing ImagickDraw(s) may be returned to by invoking pop(). The ImagickDraws are stored on a ImagickDraw stack. For every Pop there must have already been an equivalent Push.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ImagickDraw::popPattern
ImagickDraw::pushClipPath
ImagickDraw


Starts a clip path definition

ImagickDraw::push
ImagickDraw::pushDefs
ImagickDraw
PHP Manual

ImagickDraw::pushClipPath

(PECL imagick 2.0.0)

ImagickDraw::pushClipPath — Starts a clip path definition

Opis

bool ImagickDraw::pushClipPath ( string $clip_mask_id )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Starts a clip path definition which is comprised of any number of drawing commands and terminated by a ImagickDraw::popClipPath() command.

Parametry

clip_mask_id

Clip mask Id

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::push
ImagickDraw::pushDefs
ImagickDraw


Indicates that following commands create named elements for early processing

ImagickDraw::pushClipPath
ImagickDraw::pushPattern
ImagickDraw
PHP Manual

ImagickDraw::pushDefs

(PECL imagick 2.0.0)

ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing

Opis

bool ImagickDraw::pushDefs ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Indicates that commands up to a terminating ImagickDraw::popDefs() command create named elements (e.g. clip-paths, textures, etc.) which may safely be processed earlier for the sake of efficiency.

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pushClipPath
ImagickDraw::pushPattern
ImagickDraw


Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

ImagickDraw::pushDefs
ImagickDraw::rectangle
ImagickDraw
PHP Manual

ImagickDraw::pushPattern

(PECL imagick 2.0.0)

ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

Opis

bool ImagickDraw::pushPattern ( string $pattern_id , float $x , float $y , float $width , float $height )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Indicates that subsequent commands up to a DrawPopPattern() command comprise the definition of a named pattern. The pattern space is assigned top left corner coordinates, a width and height, and becomes its own drawing space. Anything which can be drawn may be used in a pattern definition. Named patterns may be used as stroke or brush definitions.

Parametry

pattern_id

the pattern Id

x

x coordinate of the top-left corner

y

y coordinate of the top-left corner

width

width of the pattern

height

height of the pattern

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ImagickDraw::pushDefs
ImagickDraw::rectangle
ImagickDraw


Draws a rectangle

ImagickDraw::pushPattern
ImagickDraw::render
ImagickDraw
PHP Manual

ImagickDraw::rectangle

(PECL imagick 2.0.0)

ImagickDraw::rectangle — Draws a rectangle

Opis

bool ImagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

Parametry

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right corner

y2

y coordinate of the bottom right corner

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::pushPattern
ImagickDraw::render
ImagickDraw


Renders all preceding drawing commands onto the image

ImagickDraw::rectangle
ImagickDraw::rotate
ImagickDraw
PHP Manual

ImagickDraw::render

(PECL imagick 2.0.0)

ImagickDraw::render — Renders all preceding drawing commands onto the image

Opis

bool ImagickDraw::render ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Renders all preceding drawing commands onto the image.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ImagickDraw::rectangle
ImagickDraw::rotate
ImagickDraw


Applies the specified rotation to the current coordinate space

ImagickDraw::render
ImagickDraw::roundRectangle
ImagickDraw
PHP Manual

ImagickDraw::rotate

(PECL imagick 2.0.0)

ImagickDraw::rotate — Applies the specified rotation to the current coordinate space

Opis

bool ImagickDraw::rotate ( float $degrees )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Applies the specified rotation to the current coordinate space.

Parametry

degrees

degrees to rotate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::render
ImagickDraw::roundRectangle
ImagickDraw


Draws a rounded rectangle

ImagickDraw::rotate
ImagickDraw::scale
ImagickDraw
PHP Manual

ImagickDraw::roundRectangle

(PECL imagick 2.0.0)

ImagickDraw::roundRectangle — Draws a rounded rectangle

Opis

bool ImagickDraw::roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Draws a rounded rectangle given two coordinates, x & y corner radiuses and using the current stroke, stroke width, and fill settings.

Parametry

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right

y2

y coordinate of the bottom right

rx

x rounding

ry

y rounding

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::rotate
ImagickDraw::scale
ImagickDraw


Adjusts the scaling factor

ImagickDraw::roundRectangle
ImagickDraw::setClipPath
ImagickDraw
PHP Manual

ImagickDraw::scale

(PECL imagick 2.0.0)

ImagickDraw::scale — Adjusts the scaling factor

Opis

bool ImagickDraw::scale ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

Parametry

x

horizontal factor

y

vertical factor

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::roundRectangle
ImagickDraw::setClipPath
ImagickDraw


Associates a named clipping path with the image

ImagickDraw::scale
ImagickDraw::setClipRule
ImagickDraw
PHP Manual

ImagickDraw::setClipPath

(PECL imagick 2.0.0)

ImagickDraw::setClipPath — Associates a named clipping path with the image

Opis

bool ImagickDraw::setClipPath ( string $clip_mask )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Associates a named clipping path with the image. Only the areas drawn on by the clipping path will be modified as long as it remains in effect.

Parametry

clip_mask

the clipping path name

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::scale
ImagickDraw::setClipRule
ImagickDraw


Set the polygon fill rule to be used by the clipping path

ImagickDraw::setClipPath
ImagickDraw::setClipUnits
ImagickDraw
PHP Manual

ImagickDraw::setClipRule

(PECL imagick 2.0.0)

ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path

Opis

bool ImagickDraw::setClipRule ( int $fill_rule )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Set the polygon fill rule to be used by the clipping path.

Parametry

fill_rule

FILLRULE_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setClipPath
ImagickDraw::setClipUnits
ImagickDraw


Sets the interpretation of clip path units

ImagickDraw::setClipRule
ImagickDraw::setFillAlpha
ImagickDraw
PHP Manual

ImagickDraw::setClipUnits

(PECL imagick 2.0.0)

ImagickDraw::setClipUnits — Sets the interpretation of clip path units

Opis

bool ImagickDraw::setClipUnits ( int $clip_units )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the interpretation of clip path units.

Parametry

clip_units

the number of clip units

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setClipRule
ImagickDraw::setFillAlpha
ImagickDraw


Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setClipUnits
ImagickDraw::setFillColor
ImagickDraw
PHP Manual

ImagickDraw::setFillAlpha

(PECL imagick 2.0.0)

ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture

Opis

bool ImagickDraw::setFillAlpha ( float $opacity )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

Parametry

opacity

fill alpha

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setClipUnits
ImagickDraw::setFillColor
ImagickDraw


Sets the fill color to be used for drawing filled objects

ImagickDraw::setFillAlpha
ImagickDraw::setFillOpacity
ImagickDraw
PHP Manual

ImagickDraw::setFillColor

(PECL imagick 2.0.0)

ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects

Opis

bool ImagickDraw::setFillColor ( ImagickPixel $fill_pixel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the fill color to be used for drawing filled objects.

Parametry

fill_pixel

ImagickPixel to use to set the color

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setFillAlpha
ImagickDraw::setFillOpacity
ImagickDraw


Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillColor
ImagickDraw::setFillPatternURL
ImagickDraw
PHP Manual

ImagickDraw::setFillOpacity

(PECL imagick 2.0.0)

ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture

Opis

bool ImagickDraw::setFillOpacity ( float $fillOpacity )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

Parametry

fillOpacity

the fill opacity

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setFillColor
ImagickDraw::setFillPatternURL
ImagickDraw


Sets the URL to use as a fill pattern for filling objects

ImagickDraw::setFillOpacity
ImagickDraw::setFillRule
ImagickDraw
PHP Manual

ImagickDraw::setFillPatternURL

(PECL imagick 2.0.0)

ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects

Opis

bool ImagickDraw::setFillPatternURL ( string $fill_url )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the URL to use as a fill pattern for filling objects. Only local URLs ("#identifier") are supported at this time. These local URLs are normally created by defining a named fill pattern with DrawPushPattern/DrawPopPattern.

Parametry

fill_url

URL to use to obtain fill pattern.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ImagickDraw::setFillOpacity
ImagickDraw::setFillRule
ImagickDraw


Sets the fill rule to use while drawing polygons

ImagickDraw::setFillPatternURL
ImagickDraw::setFont
ImagickDraw
PHP Manual

ImagickDraw::setFillRule

(PECL imagick 2.0.0)

ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons

Opis

bool ImagickDraw::setFillRule ( int $fill_rule )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the fill rule to use while drawing polygons.

Parametry

fill_rule

FILLRULE_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setFillPatternURL
ImagickDraw::setFont
ImagickDraw


Sets the fully-specified font to use when annotating with text

ImagickDraw::setFillRule
ImagickDraw::setFontFamily
ImagickDraw
PHP Manual

ImagickDraw::setFont

(PECL imagick 2.0.0)

ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text

Opis

bool ImagickDraw::setFont ( string $font_name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the fully-specified font to use when annotating with text.

Parametry

font_name

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickDraw::setFillRule
ImagickDraw::setFontFamily
ImagickDraw


Sets the font family to use when annotating with text

ImagickDraw::setFont
ImagickDraw::setFontSize
ImagickDraw
PHP Manual

ImagickDraw::setFontFamily

(PECL imagick 2.0.0)

ImagickDraw::setFontFamily — Sets the font family to use when annotating with text

Opis

bool ImagickDraw::setFontFamily ( string $font_family )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the font family to use when annotating with text.

Parametry

font_family

the font family

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickDraw::setFont
ImagickDraw::setFontSize
ImagickDraw


Sets the font pointsize to use when annotating with text

ImagickDraw::setFontFamily
ImagickDraw::setFontStretch
ImagickDraw
PHP Manual

ImagickDraw::setFontSize

(PECL imagick 2.0.0)

ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text

Opis

bool ImagickDraw::setFontSize ( float $pointsize )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the font pointsize to use when annotating with text.

Parametry

pointsize

the point size

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setFontFamily
ImagickDraw::setFontStretch
ImagickDraw


Sets the font stretch to use when annotating with text

ImagickDraw::setFontSize
ImagickDraw::setFontStyle
ImagickDraw
PHP Manual

ImagickDraw::setFontStretch

(PECL imagick 2.0.0)

ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text

Opis

bool ImagickDraw::setFontStretch ( int $fontStretch )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the font stretch to use when annotating with text. The AnyStretch enumeration acts as a wild-card "don't care" option.

Parametry

fontStretch

STRETCH_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setFontSize
ImagickDraw::setFontStyle
ImagickDraw


Sets the font style to use when annotating with text

ImagickDraw::setFontStretch
ImagickDraw::setFontWeight
ImagickDraw
PHP Manual

ImagickDraw::setFontStyle

(PECL imagick 2.0.0)

ImagickDraw::setFontStyle — Sets the font style to use when annotating with text

Opis

bool ImagickDraw::setFontStyle ( int $style )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

Parametry

style

STYLETYPE_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setFontStretch
ImagickDraw::setFontWeight
ImagickDraw


Sets the font weight

ImagickDraw::setFontStyle
ImagickDraw::setGravity
ImagickDraw
PHP Manual

ImagickDraw::setFontWeight

(PECL imagick 2.0.0)

ImagickDraw::setFontWeight — Sets the font weight

Opis

bool ImagickDraw::setFontWeight ( int $font_weight )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the font weight to use when annotating with text.

Parametry

font_weight

Zwracane wartości

ImagickDraw::setFontStyle
ImagickDraw::setGravity
ImagickDraw


Sets the text placement gravity

ImagickDraw::setFontWeight
ImagickDraw::setStrokeAlpha
ImagickDraw
PHP Manual

ImagickDraw::setGravity

(PECL imagick 2.0.0)

ImagickDraw::setGravity — Sets the text placement gravity

Opis

bool ImagickDraw::setGravity ( int $gravity )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the text placement gravity to use when annotating with text.

Parametry

gravity

GRAVITY_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setFontWeight
ImagickDraw::setStrokeAlpha
ImagickDraw


Specifies the opacity of stroked object outlines

ImagickDraw::setGravity
ImagickDraw::setStrokeAntialias
ImagickDraw
PHP Manual

ImagickDraw::setStrokeAlpha

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines

Opis

bool ImagickDraw::setStrokeAlpha ( float $opacity )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies the opacity of stroked object outlines.

Parametry

opacity

opacity

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setGravity
ImagickDraw::setStrokeAntialias
ImagickDraw


Controls whether stroked outlines are antialiased

ImagickDraw::setStrokeAlpha
ImagickDraw::setStrokeColor
ImagickDraw
PHP Manual

ImagickDraw::setStrokeAntialias

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased

Opis

bool ImagickDraw::setStrokeAntialias ( bool $stroke_antialias )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Controls whether stroked outlines are antialiased. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

Parametry

stroke_antialias

the antialias setting

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokeAlpha
ImagickDraw::setStrokeColor
ImagickDraw


Sets the color used for stroking object outlines

ImagickDraw::setStrokeAntialias
ImagickDraw::setStrokeDashArray
ImagickDraw
PHP Manual

ImagickDraw::setStrokeColor

(PECL imagick 2.0.0)

ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines

Opis

bool ImagickDraw::setStrokeColor ( ImagickPixel $stroke_pixel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the color used for stroking object outlines.

Parametry

stroke_pixel

the stroke color

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokeAntialias
ImagickDraw::setStrokeDashArray
ImagickDraw


Specifies the pattern of dashes and gaps used to stroke paths

ImagickDraw::setStrokeColor
ImagickDraw::setStrokeDashOffset
ImagickDraw
PHP Manual

ImagickDraw::setStrokeDashArray

(PECL imagick 2.0.0)

ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths

Opis

bool ImagickDraw::setStrokeDashArray ( array $dashArray )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies the pattern of dashes and gaps used to stroke paths. The strokeDashArray represents an array of numbers that specify the lengths of alternating dashes and gaps in pixels. If an odd number of values is provided, then the list of values is repeated to yield an even number of values. To remove an existing dash array, pass a zero number_elements argument and null dash_array. A typical strokeDashArray_ array might contain the members 5 3 2.

Parametry

dashArray

array of floats

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickDraw::setStrokeColor
ImagickDraw::setStrokeDashOffset
ImagickDraw


Specifies the offset into the dash pattern to start the dash

ImagickDraw::setStrokeDashArray
ImagickDraw::setStrokeLineCap
ImagickDraw
PHP Manual

ImagickDraw::setStrokeDashOffset

(PECL imagick 2.0.0)

ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash

Opis

bool ImagickDraw::setStrokeDashOffset ( float $dash_offset )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies the offset into the dash pattern to start the dash.

Parametry

dash_offset

dash offset

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokeDashArray
ImagickDraw::setStrokeLineCap
ImagickDraw


Specifies the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::setStrokeDashOffset
ImagickDraw::setStrokeLineJoin
ImagickDraw
PHP Manual

ImagickDraw::setStrokeLineCap

(PECL imagick 2.0.0)

ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked

Opis

bool ImagickDraw::setStrokeLineCap ( int $linecap )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies the shape to be used at the end of open subpaths when they are stroked.

Parametry

linecap

LINECAP_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokeDashOffset
ImagickDraw::setStrokeLineJoin
ImagickDraw


Specifies the shape to be used at the corners of paths when they are stroked

ImagickDraw::setStrokeLineCap
ImagickDraw::setStrokeMiterLimit
ImagickDraw
PHP Manual

ImagickDraw::setStrokeLineJoin

(PECL imagick 2.0.0)

ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked

Opis

bool ImagickDraw::setStrokeLineJoin ( int $linejoin )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

Parametry

linejoin

LINEJOIN_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokeLineCap
ImagickDraw::setStrokeMiterLimit
ImagickDraw


Specifies the miter limit

ImagickDraw::setStrokeLineJoin
ImagickDraw::setStrokeOpacity
ImagickDraw
PHP Manual

ImagickDraw::setStrokeMiterLimit

(PECL imagick 2.0.0)

ImagickDraw::setStrokeMiterLimit — Specifies the miter limit

Opis

bool ImagickDraw::setStrokeMiterLimit ( int $miterlimit )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

Parametry

miterlimit

the miter limit

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokeLineJoin
ImagickDraw::setStrokeOpacity
ImagickDraw


Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeMiterLimit
ImagickDraw::setStrokePatternURL
ImagickDraw
PHP Manual

ImagickDraw::setStrokeOpacity

(PECL imagick 2.0.0)

ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines

Opis

bool ImagickDraw::setStrokeOpacity ( float $stroke_opacity )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies the opacity of stroked object outlines.

Parametry

stroke_opacity

stroke opacity. 1.0 is fully opaque

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokeMiterLimit
ImagickDraw::setStrokePatternURL
ImagickDraw


Sets the pattern used for stroking object outlines

ImagickDraw::setStrokeOpacity
ImagickDraw::setStrokeWidth
ImagickDraw
PHP Manual

ImagickDraw::setStrokePatternURL

(PECL imagick 2.0.0)

ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines

Opis

bool ImagickDraw::setStrokePatternURL ( string $stroke_url )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the pattern used for stroking object outlines.

Parametry

stroke_url

stroke URL

Zwracane wartości

imagick.imagickdraw.return.success;

ImagickDraw::setStrokeOpacity
ImagickDraw::setStrokeWidth
ImagickDraw


Sets the width of the stroke used to draw object outlines

ImagickDraw::setStrokePatternURL
ImagickDraw::setTextAlignment
ImagickDraw
PHP Manual

ImagickDraw::setStrokeWidth

(PECL imagick 2.0.0)

ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines

Opis

bool ImagickDraw::setStrokeWidth ( float $stroke_width )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the width of the stroke used to draw object outlines.

Parametry

stroke_width

stroke width

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokePatternURL
ImagickDraw::setTextAlignment
ImagickDraw


Specifies a text alignment

ImagickDraw::setStrokeWidth
ImagickDraw::setTextAntialias
ImagickDraw
PHP Manual

ImagickDraw::setTextAlignment

(PECL imagick 2.0.0)

ImagickDraw::setTextAlignment — Specifies a text alignment

Opis

bool ImagickDraw::setTextAlignment ( int $alignment )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies a text alignment to be applied when annotating with text.

Parametry

alignment

ALIGN_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setStrokeWidth
ImagickDraw::setTextAntialias
ImagickDraw


Controls whether text is antialiased

ImagickDraw::setTextAlignment
ImagickDraw::setTextDecoration
ImagickDraw
PHP Manual

ImagickDraw::setTextAntialias

(PECL imagick 2.0.0)

ImagickDraw::setTextAntialias — Controls whether text is antialiased

Opis

bool ImagickDraw::setTextAntialias ( bool $antiAlias )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Controls whether text is antialiased. Text is antialiased by default.

Parametry

antiAlias

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setTextAlignment
ImagickDraw::setTextDecoration
ImagickDraw


Specifies a decoration

ImagickDraw::setTextAntialias
ImagickDraw::setTextEncoding
ImagickDraw
PHP Manual

ImagickDraw::setTextDecoration

(PECL imagick 2.0.0)

ImagickDraw::setTextDecoration — Specifies a decoration

Opis

bool ImagickDraw::setTextDecoration ( int $decoration )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies a decoration to be applied when annotating with text.

Parametry

decoration

DECORATION_ constant

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setTextAntialias
ImagickDraw::setTextEncoding
ImagickDraw


Specifies specifies the text code set

ImagickDraw::setTextDecoration
ImagickDraw::setTextUnderColor
ImagickDraw
PHP Manual

ImagickDraw::setTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::setTextEncoding — Specifies specifies the text code set

Opis

bool ImagickDraw::setTextEncoding ( string $encoding )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

Parametry

encoding

the encoding name

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setTextDecoration
ImagickDraw::setTextUnderColor
ImagickDraw


Specifies the color of a background rectangle

ImagickDraw::setTextEncoding
ImagickDraw::setVectorGraphics
ImagickDraw
PHP Manual

ImagickDraw::setTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle

Opis

bool ImagickDraw::setTextUnderColor ( ImagickPixel $under_color )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Specifies the color of a background rectangle to place under text annotations.

Parametry

under_color

the under color

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setTextEncoding
ImagickDraw::setVectorGraphics
ImagickDraw


Sets the vector graphics

ImagickDraw::setTextUnderColor
ImagickDraw::setViewbox
ImagickDraw
PHP Manual

ImagickDraw::setVectorGraphics

(PECL imagick 2.0.0)

ImagickDraw::setVectorGraphics — Sets the vector graphics

Opis

bool ImagickDraw::setVectorGraphics ( string $xml )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the vector graphics associated with the specified ImagickDraw object. Use this method with ImagickDraw::getVectorGraphics() as a method to persist the vector graphics state.

Parametry

xml

xml containing the vector graphics

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ImagickDraw::setTextUnderColor
ImagickDraw::setViewbox
ImagickDraw


Sets the overall canvas size

ImagickDraw::setVectorGraphics
ImagickDraw::skewX
ImagickDraw
PHP Manual

ImagickDraw::setViewbox

(PECL imagick 2.0.0)

ImagickDraw::setViewbox — Sets the overall canvas size

Opis

bool ImagickDraw::setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the overall canvas size to be recorded with the drawing vector data. Usually this will be specified using the same size as the canvas image. When the vector data is saved to SVG or MVG formats, the viewbox is use to specify the size of the canvas image that a viewer will render the vector data on.

Parametry

x1

left x coordinate

y1

left y coordinate

x2

right x coordinate

y2

right y coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setVectorGraphics
ImagickDraw::skewX
ImagickDraw


Skews the current coordinate system in the horizontal direction

ImagickDraw::setViewbox
ImagickDraw::skewY
ImagickDraw
PHP Manual

ImagickDraw::skewX

(PECL imagick 2.0.0)

ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction

Opis

bool ImagickDraw::skewX ( float $degrees )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Skews the current coordinate system in the horizontal direction.

Parametry

degrees

degrees to skew

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::setViewbox
ImagickDraw::skewY
ImagickDraw


Skews the current coordinate system in the vertical direction

ImagickDraw::skewX
ImagickDraw::translate
ImagickDraw
PHP Manual

ImagickDraw::skewY

(PECL imagick 2.0.0)

ImagickDraw::skewY — Skews the current coordinate system in the vertical direction

Opis

bool ImagickDraw::skewY ( float $degrees )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Skews the current coordinate system in the vertical direction.

Parametry

degrees

degrees to skew

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::skewX
ImagickDraw::translate
ImagickDraw


Applies a translation to the current coordinate system

ImagickDraw::skewY
ImagickPixel
ImagickDraw
PHP Manual

ImagickDraw::translate

(PECL imagick 2.0.0)

ImagickDraw::translate — Applies a translation to the current coordinate system

Opis

bool ImagickDraw::translate ( float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Applies a translation to the current coordinate system which moves the coordinate system origin to the specified coordinate.

Parametry

x

horizontal translation

y

vertical translation

Zwracane wartości

Nie jest zwracana żadna wartość.

ImagickDraw::skewY
ImagickPixel
ImagickDraw


The ImagickPixel class

(No version information available, might only be in SVN)

Krótki opis klasy

ImagickPixel {
bool clear ( void )
__construct ([ string $color ] )
bool destroy ( void )
array getColor ([ bool $normalized = false ] )
string getColorAsString ( void )
int getColorCount ( void )
float getColorValue ( int $color )
array getHSL ( void )
bool isSimilar ( ImagickPixel $color , float $fuzz )
bool setColor ( string $color )
bool setColorValue ( int $color , float $value )
bool setHSL ( float $hue , float $saturation , float $luminosity )
}

Spis treści

  • ImagickPixel::clear — Clears resources associated with this object
  • ImagickPixel::__construct — The ImagickPixel constructor
  • ImagickPixel::destroy — Deallocates resources associated with this object
  • ImagickPixel::getColor — Returns the color
  • ImagickPixel::getColorAsString — Returns the color as a string
  • ImagickPixel::getColorCount — Returns the color count associated with this color
  • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
  • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
  • ImagickPixel::isSimilar — Check the distance between this color and another
  • ImagickPixel::setColor — Sets the color
  • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
  • ImagickPixel::setHSL — Sets the normalized HSL color
ImagickDraw::translate
ImagickPixel::clear
ImageMagick


Clears resources associated with this object

ImagickPixel
ImagickPixel::__construct
ImagickPixel
PHP Manual

ImagickPixel::clear

(PECL imagick 2.0.0)

ImagickPixel::clear — Clears resources associated with this object

Opis

bool ImagickPixel::clear ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Clears the ImagickPixel object, leaving it in a fresh state. This also unsets any color associated with the object.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixel
ImagickPixel::__construct
ImagickPixel


The ImagickPixel constructor

ImagickPixel::clear
ImagickPixel::destroy
ImagickPixel
PHP Manual

ImagickPixel::__construct

(PECL imagick 2.0.0)

ImagickPixel::__construct — The ImagickPixel constructor

Opis

ImagickPixel::__construct ([ string $color ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Constructs an ImagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

Parametry

color

The optional color string to use as the initial value of this object.

Zwracane wartości

Returns an ImagickPixel object on success, throwing ImagickPixelException on failure.

ImagickPixel::clear
ImagickPixel::destroy
ImagickPixel


Deallocates resources associated with this object

ImagickPixel::__construct
ImagickPixel::getColor
ImagickPixel
PHP Manual

ImagickPixel::destroy

(PECL imagick 2.0.0)

ImagickPixel::destroy — Deallocates resources associated with this object

Opis

bool ImagickPixel::destroy ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Deallocates any resources used by the ImagickPixel object, and unsets any associated color. The object should not be used after the destroy function has been called.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixel::__construct
ImagickPixel::getColor
ImagickPixel


Returns the color

ImagickPixel::destroy
ImagickPixel::getColorAsString
ImagickPixel
PHP Manual

ImagickPixel::getColor

(PECL imagick 2.0.0)

ImagickPixel::getColor — Returns the color

Opis

array ImagickPixel::getColor ([ bool $normalized = false ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the color described by the ImagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

Parametry

normalized

Normalize the color values

Zwracane wartości

An array of channel values, each normalized if TRUE is given as param. Throws ImagickPixelException on error.

ImagickPixel::destroy
ImagickPixel::getColorAsString
ImagickPixel


Returns the color as a string

ImagickPixel::getColor
ImagickPixel::getColorCount
ImagickPixel
PHP Manual

ImagickPixel::getColorAsString

(PECL imagick 2.1.0)

ImagickPixel::getColorAsString — Returns the color as a string

Opis

string ImagickPixel::getColorAsString ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the color of the ImagickPixel object as a string.

Parametry

Zwracane wartości

Returns the color of the ImagickPixel object as a string.

ImagickPixel::getColor
ImagickPixel::getColorCount
ImagickPixel


Returns the color count associated with this color

ImagickPixel::getColorAsString
ImagickPixel::getColorValue
ImagickPixel
PHP Manual

ImagickPixel::getColorCount

(PECL imagick 2.0.0)

ImagickPixel::getColorCount — Returns the color count associated with this color

Opis

int ImagickPixel::getColorCount ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the color count associated with this color.

Zwracane wartości

Returns the color count as an integer on success, throws ImagickPixelException on failure.

ImagickPixel::getColorAsString
ImagickPixel::getColorValue
ImagickPixel


Gets the normalized value of the provided color channel

ImagickPixel::getColorCount
ImagickPixel::getHSL
ImagickPixel
PHP Manual

ImagickPixel::getColorValue

(PECL imagick 2.0.0)

ImagickPixel::getColorValue — Gets the normalized value of the provided color channel

Opis

float ImagickPixel::getColorValue ( int $color )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

Parametry

color

The channel to check, specified as one of the Imagick channel constants.

Zwracane wartości

The value of the channel, as a normalized floating-point number, throwing ImagickPixelException on error.

ImagickPixel::getColorCount
ImagickPixel::getHSL
ImagickPixel


Returns the normalized HSL color of the ImagickPixel object

ImagickPixel::getColorValue
ImagickPixel::isSimilar
ImagickPixel
PHP Manual

ImagickPixel::getHSL

(PECL imagick 2.0.0)

ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object

Opis

array ImagickPixel::getHSL ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the normalized HSL color described by the ImagickPixel object, with each of the three values as floating point numbers between 0.0 and 1.0.

Zwracane wartości

Returns the HSL value in an array with the keys "hue", "saturation", and "luminosity". Throws ImagickPixelException on failure.

Notatki

Informacja:

Available with ImageMagick library version 6.2.9 and higher.

ImagickPixel::getColorValue
ImagickPixel::isSimilar
ImagickPixel


Check the distance between this color and another

ImagickPixel::getHSL
ImagickPixel::setColor
ImagickPixel
PHP Manual

ImagickPixel::isSimilar

(PECL imagick 2.0.0)

ImagickPixel::isSimilar — Check the distance between this color and another

Opis

bool ImagickPixel::isSimilar ( ImagickPixel $color , float $fuzz )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar.

Parametry

color

The ImagickPixel object to compare this object against.

fuzz

The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732).

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixel::getHSL
ImagickPixel::setColor
ImagickPixel


Sets the color

ImagickPixel::isSimilar
ImagickPixel::setColorValue
ImagickPixel
PHP Manual

ImagickPixel::setColor

(PECL imagick 2.0.0)

ImagickPixel::setColor — Sets the color

Opis

bool ImagickPixel::setColor ( string $color )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the color described by the ImagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

Parametry

color

The color definition to use in order to initialise the ImagickPixel object.

Zwracane wartości

Returns TRUE if the specified color was set, FALSE otherwise.

ImagickPixel::isSimilar
ImagickPixel::setColorValue
ImagickPixel


Sets the normalized value of one of the channels

ImagickPixel::setColor
ImagickPixel::setHSL
ImagickPixel
PHP Manual

ImagickPixel::setColorValue

(PECL imagick 2.0.0)

ImagickPixel::setColorValue — Sets the normalized value of one of the channels

Opis

bool ImagickPixel::setColorValue ( int $color , float $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to an ImagickPixel object.

Parametry

color

One of the Imagick channel color constants.

value

The value to set this channel to, ranging from 0 to 1.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixel::setColor
ImagickPixel::setHSL
ImagickPixel


Sets the normalized HSL color

ImagickPixel::setColorValue
ImagickPixelIterator
ImagickPixel
PHP Manual

ImagickPixel::setHSL

(PECL imagick 2.0.0)

ImagickPixel::setHSL — Sets the normalized HSL color

Opis

bool ImagickPixel::setHSL ( float $hue , float $saturation , float $luminosity )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the color described by the ImagickPixel object using normalized values for hue, saturation and luminosity.

Parametry

hue

The normalized value for hue, described as a fractional arc (between 0 and 1) of the hue circle, where the zero value is red.

saturation

The normalized value for saturation, with 1 as full saturation.

luminosity

The normalized value for luminosity, on a scale from black at 0 to white at 1, with the full HS value at 0.5 luminosity.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

Notatki

Informacja:

Available with ImageMagick library version 6.2.9 and higher.

ImagickPixel::setColorValue
ImagickPixelIterator
ImagickPixel


The ImagickPixelIterator class

(No version information available, might only be in SVN)

Krótki opis klasy

ImagickPixelIterator {
bool clear ( void )
__construct ( Imagick $wand )
bool destroy ( void )
array getCurrentIteratorRow ( void )
int getIteratorRow ( void )
array getNextIteratorRow ( void )
array getPreviousIteratorRow ( void )
bool newPixelIterator ( Imagick $wand )
bool newPixelRegionIterator ( Imagick $wand , int $x , int $y , int $columns , int $rows )
bool resetIterator ( void )
bool setIteratorFirstRow ( void )
bool setIteratorLastRow ( void )
bool setIteratorRow ( int $row )
bool syncIterator ( void )
}

Spis treści

  • ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
  • ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
  • ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
  • ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
  • ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
  • ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
  • ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
  • ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
  • ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
  • ImagickPixelIterator::resetIterator — Resets the pixel iterator
  • ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
  • ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
  • ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
  • ImagickPixelIterator::syncIterator — Syncs the pixel iterator
ImagickPixel::setHSL
ImagickPixelIterator::clear
ImageMagick


Clear resources associated with a PixelIterator

ImagickPixelIterator
ImagickPixelIterator::__construct
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::clear

(PECL imagick 2.0.0)

ImagickPixelIterator::clear — Clear resources associated with a PixelIterator

Opis

bool ImagickPixelIterator::clear ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Clear resources associated with a PixelIterator.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixelIterator
ImagickPixelIterator::__construct
ImagickPixelIterator


The ImagickPixelIterator constructor

ImagickPixelIterator::clear
ImagickPixelIterator::destroy
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::__construct

(PECL imagick 2.0.0)

ImagickPixelIterator::__construct — The ImagickPixelIterator constructor

Opis

ImagickPixelIterator::__construct ( Imagick $wand )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

The ImagickPixelIterator constructor

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixelIterator::clear
ImagickPixelIterator::destroy
ImagickPixelIterator


Deallocates resources associated with a PixelIterator

ImagickPixelIterator::__construct
ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::destroy

(PECL imagick 2.0.0)

ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator

Opis

bool ImagickPixelIterator::destroy ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Deallocates resources associated with a PixelIterator.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixelIterator::__construct
ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator


Returns the current row of ImagickPixel objects

ImagickPixelIterator::destroy
ImagickPixelIterator::getIteratorRow
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::getCurrentIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects

Opis

array ImagickPixelIterator::getCurrentIteratorRow ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the current row as an array of ImagickPixel objects from the pixel iterator.

Zwracane wartości

Returns a row as an array of ImagickPixel objects that can themselves be iterated.

ImagickPixelIterator::destroy
ImagickPixelIterator::getIteratorRow
ImagickPixelIterator


Returns the current pixel iterator row

ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::getIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row

Opis

int ImagickPixelIterator::getIteratorRow ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the current pixel iterator row.

Zwracane wartości

Returns the integer offset of the row, throwing ImagickPixelIteratorException on error.

ImagickPixelIterator::getCurrentIteratorRow
ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator


Returns the next row of the pixel iterator

ImagickPixelIterator::getIteratorRow
ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::getNextIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator

Opis

array ImagickPixelIterator::getNextIteratorRow ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the next row as an array of pixel wands from the pixel iterator.

Zwracane wartości

Returns the next row as an array of ImagickPixel objects, throwing ImagickPixelIteratorException on error.

ImagickPixelIterator::getIteratorRow
ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator


Returns the previous row

ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator::newPixelIterator
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::getPreviousIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row

Opis

array ImagickPixelIterator::getPreviousIteratorRow ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the previous row as an array of pixel wands from the pixel iterator.

Zwracane wartości

Returns the previous row as an array of ImagickPixelWand objects from the ImagickPixelIterator, throwing ImagickPixelIteratorException on error.

ImagickPixelIterator::getNextIteratorRow
ImagickPixelIterator::newPixelIterator
ImagickPixelIterator


Returns a new pixel iterator

ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::newPixelIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator

Opis

bool ImagickPixelIterator::newPixelIterator ( Imagick $wand )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns a new pixel iterator.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu. Throwing ImagickPixelIteratorException.

ImagickPixelIterator::getPreviousIteratorRow
ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator


Returns a new pixel iterator

ImagickPixelIterator::newPixelIterator
ImagickPixelIterator::resetIterator
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::newPixelRegionIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator

Opis

bool ImagickPixelIterator::newPixelRegionIterator ( Imagick $wand , int $x , int $y , int $columns , int $rows )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns a new pixel iterator.

Parametry

wand

x

y

columns

rows

Zwracane wartości

Returns a new ImagickPixelIterator on success; on failure, throws ImagickPixelIteratorException.

ImagickPixelIterator::newPixelIterator
ImagickPixelIterator::resetIterator
ImagickPixelIterator


Resets the pixel iterator

ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::resetIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::resetIterator — Resets the pixel iterator

Opis

bool ImagickPixelIterator::resetIterator ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Resets the pixel iterator. Use it in conjunction with ImagickPixelIterator::getNextIteratorRow() to iterate over all the pixels in a pixel container.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixelIterator::newPixelRegionIterator
ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator


Sets the pixel iterator to the first pixel row

ImagickPixelIterator::resetIterator
ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::setIteratorFirstRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row

Opis

bool ImagickPixelIterator::setIteratorFirstRow ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the pixel iterator to the first pixel row.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixelIterator::resetIterator
ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator


Sets the pixel iterator to the last pixel row

ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator::setIteratorRow
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::setIteratorLastRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row

Opis

bool ImagickPixelIterator::setIteratorLastRow ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Sets the pixel iterator to the last pixel row.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixelIterator::setIteratorFirstRow
ImagickPixelIterator::setIteratorRow
ImagickPixelIterator


Set the pixel iterator row

ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator::syncIterator
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::setIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorRow — Set the pixel iterator row

Opis

bool ImagickPixelIterator::setIteratorRow ( int $row )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Set the pixel iterator row.

Parametry

row

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixelIterator::setIteratorLastRow
ImagickPixelIterator::syncIterator
ImagickPixelIterator


Syncs the pixel iterator

ImagickPixelIterator::setIteratorRow
Rozszerzenia powiązane z pocztą elektroniczną
ImagickPixelIterator
PHP Manual

ImagickPixelIterator::syncIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::syncIterator — Syncs the pixel iterator

Opis

bool ImagickPixelIterator::syncIterator ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Syncs the pixel iterator.

Zwracane wartości

Zwraca TRUE w przypadku sukcesu.

ImagickPixelIterator::setIteratorRow
Rozszerzenia powiązane z pocztą elektroniczną
ImagickPixelIterator


Rozszerzenia powiązane z pocztą elektroniczną

  • Cyrus — Cyrus IMAP administration
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Cyrus Funkcje
  • IMAP — IMAP, POP3 and NNTP
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • IMAP Funkcje
  • Mail
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Mail Funkcje
  • Mailparse
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Mailparse Funkcje
  • vpopmail
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje vpopmail
ImagickPixelIterator::syncIterator
Cyrus
Opis funkcji


Cyrus IMAP administration

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Cyrus Funkcje
    • cyrus_authenticate — Authenticate against a Cyrus IMAP server
    • cyrus_bind — Bind callbacks to a Cyrus IMAP connection
    • cyrus_close — Close connection to a Cyrus IMAP server
    • cyrus_connect — Connect to a Cyrus IMAP server
    • cyrus_query — Send a query to a Cyrus IMAP server
    • cyrus_unbind — Unbind ...
Rozszerzenia powiązane z pocztą elektroniczną
Wstęp
Rozszerzenia powiązane z pocztą elektroniczną


Wstęp

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0.

Cyrus
Instalacja/Konfiguracja
Cyrus


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Cyrus


Instalacja

To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.

Ostrzeżenie

Rozszerzenia IMAP, recode, YAZ i Cyrus nie mogą być używane razem. Dzieje się tak z powodu współdzielenia tych samych oznaczeń wewnętrznych. Notatka: problem nie dotyczy Yaz 2.0 i nowszych wersji.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines a Cyrus IMAP connection identifier returned by cyrus_connect().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

CYRUS_CONN_NONSYNCLITERAL (integer)
CYRUS_CONN_INITIALRESPONSE (integer)
CYRUS_CALLBACK_NUMBERED (integer)
CYRUS_CALLBACK_NOLITERAL (integer)
Typy zasobów
Cyrus Funkcje
Cyrus


Cyrus Funkcje

Spis treści

  • cyrus_authenticate — Authenticate against a Cyrus IMAP server
  • cyrus_bind — Bind callbacks to a Cyrus IMAP connection
  • cyrus_close — Close connection to a Cyrus IMAP server
  • cyrus_connect — Connect to a Cyrus IMAP server
  • cyrus_query — Send a query to a Cyrus IMAP server
  • cyrus_unbind — Unbind ...
Stałe predefiniowane
cyrus_authenticate
Cyrus


Authenticate against a Cyrus IMAP server

Cyrus Funkcje
cyrus_bind
Cyrus Funkcje
PHP Manual

cyrus_authenticate

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_authenticate — Authenticate against a Cyrus IMAP server

Opis

void cyrus_authenticate ( resource $connection [, string $mechlist [, string $service [, string $user [, int $minssf [, int $maxssf [, string $authname [, string $password ]]]]]]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Cyrus Funkcje
cyrus_bind
Cyrus Funkcje


Bind callbacks to a Cyrus IMAP connection

cyrus_authenticate
cyrus_close
Cyrus Funkcje
PHP Manual

cyrus_bind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_bind — Bind callbacks to a Cyrus IMAP connection

Opis

bool cyrus_bind ( resource $connection , array $callbacks )

Binds callbacks to a Cyrus IMAP connection.

Parametry

connection

The connection handle.

callbacks

An array of callbacks.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

cyrus_authenticate
cyrus_close
Cyrus Funkcje


Close connection to a Cyrus IMAP server

cyrus_bind
cyrus_connect
Cyrus Funkcje
PHP Manual

cyrus_close

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_close — Close connection to a Cyrus IMAP server

Opis

bool cyrus_close ( resource $connection )

Closes the connection to a Cyrus IMAP server.

Parametry

connection

The connection handle.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

cyrus_bind
cyrus_connect
Cyrus Funkcje


Connect to a Cyrus IMAP server

cyrus_close
cyrus_query
Cyrus Funkcje
PHP Manual

cyrus_connect

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_connect — Connect to a Cyrus IMAP server

Opis

resource cyrus_connect ([ string $host [, string $port [, int $flags ]]] )

Connects to a Cyrus IMAP server.

Parametry

host

The Cyrus IMAP host name.

port

The port number.

flags

Zwracane wartości

Returns a connection handler on success lub FALSE w przypadku niepowodzenia.

cyrus_close
cyrus_query
Cyrus Funkcje


Send a query to a Cyrus IMAP server

cyrus_connect
cyrus_unbind
Cyrus Funkcje
PHP Manual

cyrus_query

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_query — Send a query to a Cyrus IMAP server

Opis

array cyrus_query ( resource $connection , string $query )

Sends a query to a Cyrus IMAP server.

Parametry

connection

The connection handle.

query

The query string.

Zwracane wartości

Returns an associative array with the following keys: text, msgno, and keyword.

cyrus_connect
cyrus_unbind
Cyrus Funkcje


Unbind ...

cyrus_query
IMAP
Cyrus Funkcje
PHP Manual

cyrus_unbind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_unbind — Unbind ...

Opis

bool cyrus_unbind ( resource $connection , string $trigger_name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

connection

The connection handle.

trigger_name

The trigger name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

cyrus_query
IMAP
Cyrus Funkcje


IMAP, POP3 and NNTP

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • IMAP Funkcje
    • imap_8bit — Convert an 8bit string to a quoted-printable string
    • imap_alerts — Returns all IMAP alert messages that have occurred
    • imap_append — Append a string message to a specified mailbox
    • imap_base64 — Decode BASE64 encoded text
    • imap_binary — Convert an 8bit string to a base64 string
    • imap_body — Read the message body
    • imap_bodystruct — Read the structure of a specified body section of a specific message
    • imap_check — Check current mailbox
    • imap_clearflag_full — Clears flags on messages
    • imap_close — Close an IMAP stream
    • imap_create — Alias dla imap_createmailbox
    • imap_createmailbox — Create a new mailbox
    • imap_delete — Mark a message for deletion from current mailbox
    • imap_deletemailbox — Delete a mailbox
    • imap_errors — Returns all of the IMAP errors that have occured
    • imap_expunge — Delete all messages marked for deletion
    • imap_fetch_overview — Read an overview of the information in the headers of the given message
    • imap_fetchbody — Fetch a particular section of the body of the message
    • imap_fetchheader — Returns header for a message
    • imap_fetchmime — Fetch MIME headers for a particular section of the message
    • imap_fetchstructure — Read the structure of a particular message
    • imap_fetchtext — Alias dla imap_body
    • imap_gc — Clears IMAP cache
    • imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot — Retrieve the quota settings per user
    • imap_getacl — Gets the ACL for a given mailbox
    • imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed — List all the subscribed mailboxes
    • imap_header — Alias dla imap_headerinfo
    • imap_headerinfo — Read the header of the message
    • imap_headers — Returns headers for all messages in a mailbox
    • imap_last_error — Gets the last IMAP error that occurred during this page request
    • imap_list — Read the list of mailboxes
    • imap_listmailbox — Alias dla imap_list
    • imap_listscan — Returns the list of mailboxes that matches the given text
    • imap_listsubscribed — Alias dla imap_lsub
    • imap_lsub — List all the subscribed mailboxes
    • imap_mail_compose — Create a MIME message based on given envelope and body sections
    • imap_mail_copy — Copy specified messages to a mailbox
    • imap_mail_move — Move specified messages to a mailbox
    • imap_mail — Send an email message
    • imap_mailboxmsginfo — Get information about the current mailbox
    • imap_mime_header_decode — Decode MIME header elements
    • imap_msgno — Gets the message sequence number for the given UID
    • imap_num_msg — Gets the number of messages in the current mailbox
    • imap_num_recent — Gets the number of recent messages in current mailbox
    • imap_open — Open an IMAP stream to a mailbox
    • imap_ping — Check if the IMAP stream is still active
    • imap_qprint — Convert a quoted-printable string to an 8 bit string
    • imap_rename — Alias dla imap_renamemailbox
    • imap_renamemailbox — Rename an old mailbox to new mailbox
    • imap_reopen — Reopen IMAP stream to new mailbox
    • imap_rfc822_parse_adrlist — Parses an address string
    • imap_rfc822_parse_headers — Parse mail headers from a string
    • imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info
    • imap_savebody — Save a specific body section to a file
    • imap_scan — Alias dla imap_listscan
    • imap_scanmailbox — Alias dla imap_listscan
    • imap_search — This function returns an array of messages matching the given search criteria
    • imap_set_quota — Sets a quota for a given mailbox
    • imap_setacl — Sets the ACL for a giving mailbox
    • imap_setflag_full — Sets flags on messages
    • imap_sort — Gets and sort messages
    • imap_status — Returns status information on a mailbox
    • imap_subscribe — Subscribe to a mailbox
    • imap_thread — Returns a tree of threaded message
    • imap_timeout — Set or fetch imap timeout
    • imap_uid — This function returns the UID for the given message sequence number
    • imap_undelete — Unmark the message which is marked deleted
    • imap_unsubscribe — Unsubscribe from a mailbox
    • imap_utf7_decode — Decodes a modified UTF-7 encoded string
    • imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 — Converts MIME-encoded text to UTF-8
cyrus_unbind
Wstęp
Rozszerzenia powiązane z pocztą elektroniczną


Wstęp

These functions enable you to operate with the IMAP protocol, as well as the NNTP, POP3 and local mailbox access methods.

Be warned, however, that some IMAP functions will not work correctly with the POP protocol.

IMAP
Instalacja/Konfiguracja
IMAP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
IMAP


Wymagania

This extension requires the c-client library to be installed. Grab the latest version from » ftp://ftp.cac.washington.edu/imap/ and compile it.

It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client.a was created. Also put this in the lib/ directory but rename it as libc-client.a.

Informacja:

To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.

Informacja: In Mandrake Linux, the IMAP library (libc-client.a) is compiled without Kerberos support. A separate version with SSL (client-PHP4.a) is installed. The library must be recompiled in order to add Kerberos support.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To get these functions to work, you have to compile PHP with --with-imap[=DIR] , where DIR is the c-client install prefix. From our example above, you would use --with-imap=/usr/local/imap-2000b . This location depends on where you created this directory according to the description above. Windows users may include the php_imap.dll DLL in php.ini.

IMAP is not supported on systems earlier than Windows 2000. This is because it uses encryption functions in order to enable SSL connections to the mail servers.

Informacja: Depending on how the c-client was configured, you might also need to add --with-imap-ssl=/path/to/openssl/ and/or --with-kerberos=/path/to/kerberos to the PHP configure line.

Ostrzeżenie

Rozszerzenia IMAP, recode, YAZ i Cyrus nie mogą być używane razem. Dzieje się tak z powodu współdzielenia tych samych oznaczeń wewnętrznych. Notatka: problem nie dotyczy Yaz 2.0 i nowszych wersji.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

NIL (integer)
OP_DEBUG (integer)
OP_READONLY (integer)
Open mailbox read-only
OP_ANONYMOUS (integer)
Don't use or update a .newsrc for news (NNTP only)
OP_SHORTCACHE (integer)
OP_SILENT (integer)
OP_PROTOTYPE (integer)
OP_HALFOPEN (integer)
For IMAP and NNTP names, open a connection but don't open a mailbox.
OP_EXPUNGE (integer)
OP_SECURE (integer)
CL_EXPUNGE (integer)
silently expunge the mailbox before closing when calling imap_close()
FT_UID (integer)
The parameter is a UID
FT_PEEK (integer)
Do not set the \Seen flag if not already set
FT_NOT (integer)
FT_INTERNAL (integer)
The return string is in internal format, will not canonicalize to CRLF.
FT_PREFETCHTEXT (integer)
ST_UID (integer)
The sequence argument contains UIDs instead of sequence numbers
ST_SILENT (integer)
ST_SET (integer)
CP_UID (integer)
the sequence numbers contain UIDS
CP_MOVE (integer)
Delete the messages from the current mailbox after copying with imap_mail_copy()
SE_UID (integer)
Return UIDs instead of sequence numbers
SE_FREE (integer)
SE_NOPREFETCH (integer)
Don't prefetch searched messages
SO_FREE (integer)
SO_NOSERVER (integer)
SA_MESSAGES (integer)
SA_RECENT (integer)
SA_UNSEEN (integer)
SA_UIDNEXT (integer)
SA_UIDVALIDITY (integer)
SA_ALL (integer)
LATT_NOINFERIORS (integer)
This mailbox has no "children" (there are no mailboxes below this one).
LATT_NOSELECT (integer)
This is only a container, not a mailbox - you cannot open it.
LATT_MARKED (integer)
This mailbox is marked. Only used by UW-IMAPD.
LATT_UNMARKED (integer)
This mailbox is not marked. Only used by UW-IMAPD.
SORTDATE (integer)
Sort criteria for imap_sort(): message Date
SORTARRIVAL (integer)
Sort criteria for imap_sort(): arrival date
SORTFROM (integer)
Sort criteria for imap_sort(): mailbox in first From address
SORTSUBJECT (integer)
Sort criteria for imap_sort(): message subject
SORTTO (integer)
Sort criteria for imap_sort(): mailbox in first To address
SORTCC (integer)
Sort criteria for imap_sort(): mailbox in first cc address
SORTSIZE (integer)
Sort criteria for imap_sort(): size of message in octets
TYPETEXT (integer)
TYPEMULTIPART (integer)
TYPEMESSAGE (integer)
TYPEAPPLICATION (integer)
TYPEAUDIO (integer)
TYPEIMAGE (integer)
TYPEVIDEO (integer)
TYPEOTHER (integer)
ENC7BIT (integer)
ENC8BIT (integer)
ENCBINARY (integer)
ENCBASE64 (integer)
ENCQUOTEDPRINTABLE (integer)
ENCOTHER (integer)
IMAP_OPENTIMEOUT (integer)
IMAP_READTIMEOUT (integer)
IMAP_WRITETIMEOUT (integer)
IMAP_CLOSETIMEOUT (integer)
LATT_REFERRAL (integer)
LATT_HASCHILDREN (integer)
LATT_HASNOCHILDREN (integer)
TYPEMODEL (integer)
IMAP_GC_ELT (integer)
Garbage collector, clear message cache elements.
IMAP_GC_ENV (integer)
Garbage collector, clear envelopes and bodies.
IMAP_GC_TEXTS (integer)
Garbage collector, clear texts.
Typy zasobów
IMAP Funkcje
IMAP


IMAP Funkcje

Zobacz też:

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

  • » RFC2821: Simple Mail Transfer Protocol (SMTP).
  • » RFC2822: Standard for ARPA internet text messages.
  • » RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.
  • » RFC1939: Post Office Protocol Version 3 (POP3).
  • » RFC977: Network News Transfer Protocol (NNTP).
  • » RFC2076: Common Internet Message Headers.
  • » RFC2045 , » RFC2046 , » RFC2047 , » RFC2048 & » RFC2049: Multipurpose Internet Mail Extensions (MIME).
A detailed overview is also available in the books » Programming Internet Email by David Wood and » Managing IMAP by Dianna Mullet & Kevin Mullet.

Spis treści

  • imap_8bit — Convert an 8bit string to a quoted-printable string
  • imap_alerts — Returns all IMAP alert messages that have occurred
  • imap_append — Append a string message to a specified mailbox
  • imap_base64 — Decode BASE64 encoded text
  • imap_binary — Convert an 8bit string to a base64 string
  • imap_body — Read the message body
  • imap_bodystruct — Read the structure of a specified body section of a specific message
  • imap_check — Check current mailbox
  • imap_clearflag_full — Clears flags on messages
  • imap_close — Close an IMAP stream
  • imap_create — Alias dla imap_createmailbox
  • imap_createmailbox — Create a new mailbox
  • imap_delete — Mark a message for deletion from current mailbox
  • imap_deletemailbox — Delete a mailbox
  • imap_errors — Returns all of the IMAP errors that have occured
  • imap_expunge — Delete all messages marked for deletion
  • imap_fetch_overview — Read an overview of the information in the headers of the given message
  • imap_fetchbody — Fetch a particular section of the body of the message
  • imap_fetchheader — Returns header for a message
  • imap_fetchmime — Fetch MIME headers for a particular section of the message
  • imap_fetchstructure — Read the structure of a particular message
  • imap_fetchtext — Alias dla imap_body
  • imap_gc — Clears IMAP cache
  • imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
  • imap_get_quotaroot — Retrieve the quota settings per user
  • imap_getacl — Gets the ACL for a given mailbox
  • imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
  • imap_getsubscribed — List all the subscribed mailboxes
  • imap_header — Alias dla imap_headerinfo
  • imap_headerinfo — Read the header of the message
  • imap_headers — Returns headers for all messages in a mailbox
  • imap_last_error — Gets the last IMAP error that occurred during this page request
  • imap_list — Read the list of mailboxes
  • imap_listmailbox — Alias dla imap_list
  • imap_listscan — Returns the list of mailboxes that matches the given text
  • imap_listsubscribed — Alias dla imap_lsub
  • imap_lsub — List all the subscribed mailboxes
  • imap_mail_compose — Create a MIME message based on given envelope and body sections
  • imap_mail_copy — Copy specified messages to a mailbox
  • imap_mail_move — Move specified messages to a mailbox
  • imap_mail — Send an email message
  • imap_mailboxmsginfo — Get information about the current mailbox
  • imap_mime_header_decode — Decode MIME header elements
  • imap_msgno — Gets the message sequence number for the given UID
  • imap_num_msg — Gets the number of messages in the current mailbox
  • imap_num_recent — Gets the number of recent messages in current mailbox
  • imap_open — Open an IMAP stream to a mailbox
  • imap_ping — Check if the IMAP stream is still active
  • imap_qprint — Convert a quoted-printable string to an 8 bit string
  • imap_rename — Alias dla imap_renamemailbox
  • imap_renamemailbox — Rename an old mailbox to new mailbox
  • imap_reopen — Reopen IMAP stream to new mailbox
  • imap_rfc822_parse_adrlist — Parses an address string
  • imap_rfc822_parse_headers — Parse mail headers from a string
  • imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info
  • imap_savebody — Save a specific body section to a file
  • imap_scan — Alias dla imap_listscan
  • imap_scanmailbox — Alias dla imap_listscan
  • imap_search — This function returns an array of messages matching the given search criteria
  • imap_set_quota — Sets a quota for a given mailbox
  • imap_setacl — Sets the ACL for a giving mailbox
  • imap_setflag_full — Sets flags on messages
  • imap_sort — Gets and sort messages
  • imap_status — Returns status information on a mailbox
  • imap_subscribe — Subscribe to a mailbox
  • imap_thread — Returns a tree of threaded message
  • imap_timeout — Set or fetch imap timeout
  • imap_uid — This function returns the UID for the given message sequence number
  • imap_undelete — Unmark the message which is marked deleted
  • imap_unsubscribe — Unsubscribe from a mailbox
  • imap_utf7_decode — Decodes a modified UTF-7 encoded string
  • imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text
  • imap_utf8 — Converts MIME-encoded text to UTF-8
Stałe predefiniowane
imap_8bit
IMAP


Convert an 8bit string to a quoted-printable string

IMAP Funkcje
imap_alerts
IMAP Funkcje
PHP Manual

imap_8bit

(PHP 4, PHP 5)

imap_8bit — Convert an 8bit string to a quoted-printable string

Opis

string imap_8bit ( string $string )

Convert an 8bit string to a quoted-printable string (according to » RFC2045, section 6.7).

Parametry

string

The 8bit string to convert

Zwracane wartości

Returns a quoted-printable string.

Zobacz też:

  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

IMAP Funkcje
imap_alerts
IMAP Funkcje


Returns all IMAP alert messages that have occurred

imap_8bit
imap_append
IMAP Funkcje
PHP Manual

imap_alerts

(PHP 4, PHP 5)

imap_alerts — Returns all IMAP alert messages that have occurred

Opis

array imap_alerts ( void )

Returns all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page.

When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

Zwracane wartości

Returns an array of all of the IMAP alert messages generated or FALSE if no alert messages are available.

Zobacz też:

  • imap_errors() - Returns all of the IMAP errors that have occured

imap_8bit
imap_append
IMAP Funkcje


Append a string message to a specified mailbox

imap_alerts
imap_base64
IMAP Funkcje
PHP Manual

imap_append

(PHP 4, PHP 5)

imap_append — Append a string message to a specified mailbox

Opis

bool imap_append ( resource $imap_stream , string $mailbox , string $message [, string $options = NULL [, string $internal_date = NULL ]] )

Appends a string message to the specified mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information

message

The message to be append, as a string

When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail

options

If provided, the options will also be written to the mailbox

internal_date

If this parameter is set, it will set the INTERNALDATE on the appended message. The parameter should be a date string that conforms to the rfc2060 specifications for a date_time value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.2 | Added INTERNALDATE support to imap_append.

Przykłady

Przykład #1 imap_append() example

<?php
$stream = imap_open("{imap.example.org}INBOX.Drafts", "username", "password");

$check = imap_check($stream);
echo "Msg Count before append: ". $check->Nmsgs . "\n";

imap_append($stream, "{imap.example.org}INBOX.Drafts"
                   , "From: me@example.com\r\n"
                   . "To: you@example.com\r\n"
                   . "Subject: test\r\n"
                   . "\r\n"
                   . "this is a test message, please ignore\r\n"
                   );

$check = imap_check($stream);
echo "Msg Count after append : ". $check->Nmsgs . "\n";

imap_close($stream);
?>

imap_alerts
imap_base64
IMAP Funkcje


Decode BASE64 encoded text

imap_append
imap_binary
IMAP Funkcje
PHP Manual

imap_base64

(PHP 4, PHP 5)

imap_base64 — Decode BASE64 encoded text

Opis

string imap_base64 ( string $text )

Decodes the given BASE-64 encoded text.

Parametry

text

The encoded text

Zwracane wartości

Returns the decoded message as a string.

Zobacz też:

  • imap_binary() - Convert an 8bit string to a base64 string
  • base64_encode() - Koduje dane za pomocą algorytmu MIME base64
  • base64_decode() - Dekoduje dane zakodowane algorytmem MIME base64
  • » RFC2045, Section 6.8

imap_append
imap_binary
IMAP Funkcje


Convert an 8bit string to a base64 string

imap_base64
imap_body
IMAP Funkcje
PHP Manual

imap_binary

(PHP 4, PHP 5)

imap_binary — Convert an 8bit string to a base64 string

Opis

string imap_binary ( string $string )

Convert an 8bit string to a base64 string according to » RFC2045, Section 6.8.

Parametry

string

The 8bit string

Zwracane wartości

Returns a base64 encoded string.

Zobacz też:

  • imap_base64() - Decode BASE64 encoded text

imap_base64
imap_body
IMAP Funkcje


Read the message body

imap_binary
imap_bodystruct
IMAP Funkcje
PHP Manual

imap_body

(PHP 4, PHP 5)

imap_body — Read the message body

Opis

string imap_body ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

imap_body() returns the body of the message, numbered msg_number in the current mailbox.

imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

options

The optional options are a bit mask with one or more of the following:

  • FT_UID - The msg_number is a UID
  • FT_PEEK - Do not set the \Seen flag if not already set
  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Zwracane wartości

Returns the body of the specified message, as a string.

imap_binary
imap_bodystruct
IMAP Funkcje


Read the structure of a specified body section of a specific message

imap_body
imap_check
IMAP Funkcje
PHP Manual

imap_bodystruct

(PHP 4, PHP 5)

imap_bodystruct — Read the structure of a specified body section of a specific message

Opis

object imap_bodystruct ( resource $imap_stream , int $msg_number , string $section )

Read the structure of a specified body section of a specific message.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

section

The body section to read

Zwracane wartości

Returns the information in an object, for a detailed description of the object structure and properties see imap_fetchstructure().

Zobacz też:

  • imap_fetchstructure() - Read the structure of a particular message

imap_body
imap_check
IMAP Funkcje


Check current mailbox

imap_bodystruct
imap_clearflag_full
IMAP Funkcje
PHP Manual

imap_check

(PHP 4, PHP 5)

imap_check — Check current mailbox

Opis

object imap_check ( resource $imap_stream )

Checks information about the current mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

Zwracane wartości

Returns the information in an object with following properties:

  • Date - current system time formatted according to » RFC2822
  • Driver - protocol used to access this mailbox: POP3, IMAP, NNTP
  • Mailbox - the mailbox name
  • Nmsgs - number of messages in the mailbox
  • Recent - number of recent messages in the mailbox

Returns FALSE on failure.

Przykłady

Przykład #1 imap_check() example

<?php

$imap_obj = imap_check($imap_stream);
var_dump($imap_obj);

?>

Powyższy przykład wyświetli coś podobnego do:

object(stdClass)(5) {
  ["Date"]=>
  string(37) "Wed, 10 Dec 2003 17:56:54 +0100 (CET)"
  ["Driver"]=>
  string(4) "imap"
  ["Mailbox"]=>
  string(54)
  "{www.example.com:143/imap/user="foo@example.com"}INBOX"
  ["Nmsgs"]=>
  int(1)
  ["Recent"]=>
  int(0)
}

imap_bodystruct
imap_clearflag_full
IMAP Funkcje


Clears flags on messages

imap_check
imap_close
IMAP Funkcje
PHP Manual

imap_clearflag_full

(PHP 4, PHP 5)

imap_clearflag_full — Clears flags on messages

Opis

bool imap_clearflag_full ( resource $imap_stream , string $sequence , string $flag [, int $options = 0 ] )

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

sequence

A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flag

The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by » RFC2060)

options

options are a bit mask and may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_setflag_full() - Sets flags on messages

imap_check
imap_close
IMAP Funkcje


Close an IMAP stream

imap_clearflag_full
imap_create
IMAP Funkcje
PHP Manual

imap_close

(PHP 4, PHP 5)

imap_close — Close an IMAP stream

Opis

bool imap_close ( resource $imap_stream [, int $flag = 0 ] )

Closes the imap stream.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

flag

If set to CL_EXPUNGE, the function will silently expunge the mailbox before closing, removing all messages marked for deletion. You can achieve the same thing by using imap_expunge()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_open() - Open an IMAP stream to a mailbox

imap_clearflag_full
imap_create
IMAP Funkcje


Alias dla imap_createmailbox

imap_close
imap_createmailbox
IMAP Funkcje
PHP Manual

imap_create

(PHP 4, PHP 5)

imap_create — Alias dla imap_createmailbox()

Opis

Ta funkcja jest aliasem dla: imap_createmailbox().

imap_close
imap_createmailbox
IMAP Funkcje


Create a new mailbox

imap_create
imap_delete
IMAP Funkcje
PHP Manual

imap_createmailbox

(PHP 4, PHP 5)

imap_createmailbox — Create a new mailbox

Opis

bool imap_createmailbox ( resource $imap_stream , string $mailbox )

Creates a new mailbox specified by mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information. Names containing international characters should be encoded by imap_utf7_encode()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imap_createmailbox() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
     or die("can't connect: " . imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewböx"); // phpnewb&w7Y-x

$newname = $name1;

echo "Newname will be '$name1'<br />\n";

// we will now create a new mailbox "phptestbox" in your inbox folder,
// check its status after creation and finaly remove it to restore
// your inbox to its initial state

if (@imap_createmailbox($mbox, imap_utf7_encode("{imap.example.org}INBOX.$newname"))) {
    $status = @imap_status($mbox, "{imap.example.org}INBOX.$newname", SA_ALL);
    if ($status) {
        echo "your new mailbox '$name1' has the following status:<br />\n";
        echo "Messages:   " . $status->messages    . "<br />\n";
        echo "Recent:     " . $status->recent      . "<br />\n";
        echo "Unseen:     " . $status->unseen      . "<br />\n";
        echo "UIDnext:    " . $status->uidnext     . "<br />\n";
        echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";

        if (imap_renamemailbox($mbox, "{imap.example.org}INBOX.$newname", "{imap.example.org}INBOX.$name2")) {
            echo "renamed new mailbox from '$name1' to '$name2'<br />\n";
            $newname = $name2;
        } else {
            echo "imap_renamemailbox on new mailbox failed: " . imap_last_error() . "<br />\n";
        }
    } else {
        echo "imap_status on new mailbox failed: " . imap_last_error() . "<br />\n";
    }

    if (@imap_deletemailbox($mbox, "{imap.example.org}INBOX.$newname")) {
        echo "new mailbox removed to restore initial state<br />\n";
    } else {
        echo "imap_deletemailbox on new mailbox failed: " . implode("<br />\n", imap_errors()) . "<br />\n";
    }

} else {
    echo "could not create new mailbox: " . implode("<br />\n", imap_errors()) . "<br />\n";
}

imap_close($mbox);
?>

Zobacz też:

  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_deletemailbox() - Delete a mailbox

imap_create
imap_delete
IMAP Funkcje


Mark a message for deletion from current mailbox

imap_createmailbox
imap_deletemailbox
IMAP Funkcje
PHP Manual

imap_delete

(PHP 4, PHP 5)

imap_delete — Mark a message for deletion from current mailbox

Opis

bool imap_delete ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

Marks messages listed in msg_number for deletion. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

options

You can set the FT_UID which tells the function to treat the msg_number argument as an UID.

Zwracane wartości

Returns TRUE.

Przykłady

Przykład #1 imap_delete() example

<?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
    or die("Can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);
echo "Messages before delete: " . $check->Nmsgs . "<br />\n";

imap_delete($mbox, 1);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";

imap_expunge($mbox);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";

imap_close($mbox);
?>

Notatki

Informacja:

IMAP mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

Zobacz też:

  • imap_undelete() - Unmark the message which is marked deleted
  • imap_expunge() - Delete all messages marked for deletion
  • imap_close() - Close an IMAP stream

imap_createmailbox
imap_deletemailbox
IMAP Funkcje


Delete a mailbox

imap_delete
imap_errors
IMAP Funkcje
PHP Manual

imap_deletemailbox

(PHP 4, PHP 5)

imap_deletemailbox — Delete a mailbox

Opis

bool imap_deletemailbox ( resource $imap_stream , string $mailbox )

Deletes the specified mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_createmailbox() - Create a new mailbox
  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_open() - Open an IMAP stream to a mailbox for the format of mbox

imap_delete
imap_errors
IMAP Funkcje


Returns all of the IMAP errors that have occured

imap_deletemailbox
imap_expunge
IMAP Funkcje
PHP Manual

imap_errors

(PHP 4, PHP 5)

imap_errors — Returns all of the IMAP errors that have occured

Opis

array imap_errors ( void )

Gets all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

When imap_errors() is called, the error stack is subsequently cleared.

Zwracane wartości

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. Returns FALSE if no error messages are available.

Zobacz też:

  • imap_last_error() - Gets the last IMAP error that occurred during this page request
  • imap_alerts() - Returns all IMAP alert messages that have occurred

imap_deletemailbox
imap_expunge
IMAP Funkcje


Delete all messages marked for deletion

imap_errors
imap_fetch_overview
IMAP Funkcje
PHP Manual

imap_expunge

(PHP 4, PHP 5)

imap_expunge — Delete all messages marked for deletion

Opis

bool imap_expunge ( resource $imap_stream )

Deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

Zwracane wartości

Returns TRUE.

imap_errors
imap_fetch_overview
IMAP Funkcje


Read an overview of the information in the headers of the given message

imap_expunge
imap_fetchbody
IMAP Funkcje
PHP Manual

imap_fetch_overview

(PHP 4, PHP 5)

imap_fetch_overview — Read an overview of the information in the headers of the given message

Opis

array imap_fetch_overview ( resource $imap_stream , string $sequence [, int $options = 0 ] )

This function fetches mail headers for the given sequence and returns an overview of their contents.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

sequence

A message sequence description. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

options

sequence will contain a sequence of message indices or UIDs, if this parameter is set to FT_UID.

Zwracane wartości

Returns an array of objects describing one message header each. The object will only define a property if it exists. The possible properties are:

  • subject - the messages subject
  • from - who sent it
  • to - recipient
  • date - when was it sent
  • message_id - Message-ID
  • references - is a reference to this message id
  • in_reply_to - is a reply to this message id
  • size - size in bytes
  • uid - UID the message has in the mailbox
  • msgno - message sequence number in the mailbox
  • recent - this message is flagged as recent
  • flagged - this message is flagged
  • answered - this message is flagged as answered
  • deleted - this message is flagged for deletion
  • seen - this message is flagged as already read
  • draft - this message is flagged as being a draft

Przykłady

Przykład #1 imap_fetch_overview() example

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password")
     or die("can't connect: " . imap_last_error());

$MC = imap_check($mbox);

// Fetch an overview for all messages in INBOX
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
foreach ($result as $overview) {
    echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from}
    {$overview->subject}\n";
}
imap_close($mbox);
?>

Zobacz też:

  • imap_fetchheader() - Returns header for a message

imap_expunge
imap_fetchbody
IMAP Funkcje


Fetch a particular section of the body of the message

imap_fetch_overview
imap_fetchheader
IMAP Funkcje
PHP Manual

imap_fetchbody

(PHP 4, PHP 5)

imap_fetchbody — Fetch a particular section of the body of the message

Opis

string imap_fetchbody ( resource $imap_stream , int $msg_number , string $section [, int $options = 0 ] )

Fetch of a particular section of the body of the specified messages. Body parts are not decoded by this function.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

section

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID
  • FT_PEEK - Do not set the \Seen flag if not already set
  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Zwracane wartości

Returns a particular section of the body of the specified messages as a text string.

Zobacz też:

  • imap_savebody() - Save a specific body section to a file
  • imap_fetchstructure() - Read the structure of a particular message

imap_fetch_overview
imap_fetchheader
IMAP Funkcje


Returns header for a message

imap_fetchbody
imap_fetchmime
IMAP Funkcje
PHP Manual

imap_fetchheader

(PHP 4, PHP 5)

imap_fetchheader — Returns header for a message

Opis

string imap_fetchheader ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

This function causes a fetch of the complete, unfiltered » RFC2822 format header of the specified message.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

options

The possible options are:

  • FT_UID - The msgno argument is a UID
  • FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize to CRLF newlines
  • FT_PREFETCHTEXT - The RFC822.TEXT should be pre-fetched at the same time. This avoids an extra RTT on an IMAP connection if a full message text is desired (e.g. in a "save to local file" operation)

Zwracane wartości

Returns the header of the specified message as a text string.

Zobacz też:

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

imap_fetchbody
imap_fetchmime
IMAP Funkcje


Fetch MIME headers for a particular section of the message

imap_fetchheader
imap_fetchstructure
IMAP Funkcje
PHP Manual

imap_fetchmime

(PHP 5 >= 5.3.6)

imap_fetchmime — Fetch MIME headers for a particular section of the message

Opis

string imap_fetchmime ( resource $imap_stream , int $msg_number , string $section [, int $options = 0 ] )

Fetch the MIME headers of a particular section of the body of the specified messages.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

section

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID
  • FT_PEEK - Do not set the \Seen flag if not already set
  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Zwracane wartości

Returns the MIME headers of a particular section of the body of the specified messages as a text string.

Zobacz też:

  • imap_fetchbody() - Fetch a particular section of the body of the message
  • imap_fetchstructure() - Read the structure of a particular message
  • imap_fetchheader() - Returns header for a message

imap_fetchheader
imap_fetchstructure
IMAP Funkcje


Read the structure of a particular message

imap_fetchmime
imap_fetchtext
IMAP Funkcje
PHP Manual

imap_fetchstructure

(PHP 4, PHP 5)

imap_fetchstructure — Read the structure of a particular message

Opis

object imap_fetchstructure ( resource $imap_stream , int $msg_number [, int $options = 0 ] )

Fetches all the structured information for a given message.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

options

This optional parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID.

Zwracane wartości

Returns an object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachment. The structure of the returned objects is as follows:

Returned Objects for imap_fetchstructure()
type | Primary body type
encoding | Body transfer encoding
ifsubtype | TRUE if there is a subtype string
subtype | MIME subtype
ifdescription | TRUE if there is a description string
description | Content description string
ifid | TRUE if there is an identification string
id | Identification string
lines | Number of lines
bytes | Number of bytes
ifdisposition | TRUE if there is a disposition string
disposition | Disposition string
ifdparameters | TRUE if the dparameters array exists
dparameters | An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIME header.
ifparameters | TRUE if the parameters array exists
parameters | An array of objects where each object has an "attribute" and a "value" property.
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Primary body type (may vary with used library)
0 | text
1 | multipart
2 | message
3 | application
4 | audio
5 | image
6 | video
7 | other

Transfer encodings (may vary with used library)
0 | 7BIT
1 | 8BIT
2 | BINARY
3 | BASE64
4 | QUOTED-PRINTABLE
5 | OTHER

Zobacz też:

  • imap_fetchbody() - Fetch a particular section of the body of the message
  • imap_bodystruct() - Read the structure of a specified body section of a specific message

imap_fetchmime
imap_fetchtext
IMAP Funkcje


Alias dla imap_body

imap_fetchstructure
imap_gc
IMAP Funkcje
PHP Manual

imap_fetchtext

(PHP 4, PHP 5)

imap_fetchtext — Alias dla imap_body()

Opis

Ta funkcja jest aliasem dla: imap_body().

imap_fetchstructure
imap_gc
IMAP Funkcje


Clears IMAP cache

imap_fetchtext
imap_get_quota
IMAP Funkcje
PHP Manual

imap_gc

(PHP 5 >= 5.3.0)

imap_gc — Clears IMAP cache

Opis

bool imap_gc ( resource $imap_stream , int $caches )

Purges the cache of entries of a specific type.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

caches

Specifies the cache to purge. It may one or a combination of the following constants: IMAP_GC_ELT (message cache elements), IMAP_GC_ENV (enveloppe and bodies), IMAP_GC_TEXTS (texts).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imap_gc() example

<?php

$mbox = imap_open("{imap.example.org:143}", "username", "password");

imap_gc($mbox, IMAP_GC_ELT);

?>

imap_fetchtext
imap_get_quota
IMAP Funkcje


Retrieve the quota level settings, and usage statics per mailbox

imap_gc
imap_get_quotaroot
IMAP Funkcje
PHP Manual

imap_get_quota

(PHP 4 >= 4.0.5, PHP 5)

imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox

Opis

array imap_get_quota ( resource $imap_stream , string $quota_root )

Retrieve the quota level settings, and usage statics per mailbox.

For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

quota_root

quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.

Zwracane wartości

Returns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.

As of PHP 4.3, the function more properly reflects the functionality as dictated by the » RFC2087. The array return value has changed to support an unlimited number of returned resources (i.e. messages, or sub-folders) with each named resource receiving an individual array key. Each key value then contains an another array with the usage and limit values within it.

For backwards compatibility reasons, the original access methods are still available for use, although it is suggested to update.

Przykłady

Przykład #1 imap_get_quota() example

<?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota_value = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_value)) {
    echo "Usage level is: " . $quota_value['usage'];
    echo "Limit level is: " . $quota_value['limit'];
}

imap_close($mbox);
?>

Przykład #2 imap_get_quota() 4.3 or greater example

<?php
$mbox = imap_open("{imap.example.org}", "mailadmin", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota_values = imap_get_quota($mbox, "user.kalowsky");
if (is_array($quota_values)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit is: " .  $message['limit'];

   /* ...  */
}

imap_close($mbox);
?>

Notatki

This function is currently only available to users of the c-client2000 or greater library.

The given imap_stream must be opened as the mail administrator, otherwise this function will fail.

Zobacz też:

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_set_quota() - Sets a quota for a given mailbox
  • imap_get_quotaroot() - Retrieve the quota settings per user

imap_gc
imap_get_quotaroot
IMAP Funkcje


Retrieve the quota settings per user

imap_get_quota
imap_getacl
IMAP Funkcje
PHP Manual

imap_get_quotaroot

(PHP 4 >= 4.3.0, PHP 5)

imap_get_quotaroot — Retrieve the quota settings per user

Opis

array imap_get_quotaroot ( resource $imap_stream , string $quota_root )

Retrieve the quota settings per user. The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

quota_root

quota_root should normally be in the form of which mailbox (i.e. INBOX).

Zwracane wartości

Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.

This function will return FALSE in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.

Przykłady

Przykład #1 imap_get_quotaroot() example

<?php
$mbox = imap_open("{imap.example.org}", "kalowsky", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
   $storage = $quota_values['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE limit level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?>

Notatki

This function is currently only available to users of the c-client2000 or greater library.

The imap_stream should be opened as the user whose mailbox you wish to check.

Zobacz też:

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_set_quota() - Sets a quota for a given mailbox
  • imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

imap_get_quota
imap_getacl
IMAP Funkcje


Gets the ACL for a given mailbox

imap_get_quotaroot
imap_getmailboxes
IMAP Funkcje
PHP Manual

imap_getacl

(PHP 5)

imap_getacl — Gets the ACL for a given mailbox

Opis

array imap_getacl ( resource $imap_stream , string $mailbox )

Gets the ACL for a given mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information

Zwracane wartości

Returns an associative array of "folder" => "acl" pairs.

Przykłady

Przykład #1 imap_getacl() example

<?php

print_r(imap_getacl($conn_id, 'user.joecool'));

?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [asubfolder] => lrswipcda
    [anothersubfolder] => lrswipcda
)

Notatki

This function is currently only available to users of the c-client2000 or greater library.

Zobacz też:

  • imap_setacl() - Sets the ACL for a giving mailbox

imap_get_quotaroot
imap_getmailboxes
IMAP Funkcje


Read the list of mailboxes, returning detailed information on each one

imap_getacl
imap_getsubscribed
IMAP Funkcje
PHP Manual

imap_getmailboxes

(PHP 4, PHP 5)

imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one

Opis

array imap_getmailboxes ( resource $imap_stream , string $ref , string $pattern )

Gets information on the mailboxes.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Zwracane wartości

Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox contains, and may not contain any "children" (there are no mailboxes below this one). Calling imap_createmailbox() will not work on this mailbox.

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. This means that it may contain new messages since the last time it was checked. Not provided by all IMAP servers.

  • LATT_UNMARKED - This mailbox is not marked, does not contain new messages. If either MARKED or UNMARKED is provided, you can assume the IMAP server supports this feature for this mailbox.

Przykłady

Przykład #1 imap_getmailboxes() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$list = imap_getmailboxes($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
    foreach ($list as $key => $val) {
        echo "($key) ";
        echo imap_utf7_decode($val->name) . ",";
        echo "'" . $val->delimiter . "',";
        echo $val->attributes . "<br />\n";
    }
} else {
    echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

Zobacz też:

  • imap_getsubscribed() - List all the subscribed mailboxes

imap_getacl
imap_getsubscribed
IMAP Funkcje


List all the subscribed mailboxes

imap_getmailboxes
imap_header
IMAP Funkcje
PHP Manual

imap_getsubscribed

(PHP 4, PHP 5)

imap_getsubscribed — List all the subscribed mailboxes

Opis

array imap_getsubscribed ( resource $imap_stream , string $ref , string $pattern )

Gets information about the subscribed mailboxes.

Identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Zwracane wartości

Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).
  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.
  • LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.
  • LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.

imap_getmailboxes
imap_header
IMAP Funkcje


Alias dla imap_headerinfo

imap_getsubscribed
imap_headerinfo
IMAP Funkcje
PHP Manual

imap_header

(PHP 4, PHP 5)

imap_header — Alias dla imap_headerinfo()

Opis

Ta funkcja jest aliasem dla: imap_headerinfo().

imap_getsubscribed
imap_headerinfo
IMAP Funkcje


Read the header of the message

imap_header
imap_headers
IMAP Funkcje
PHP Manual

imap_headerinfo

(PHP 4, PHP 5)

imap_headerinfo — Read the header of the message

Opis

object imap_headerinfo ( resource $imap_stream , int $msg_number [, int $fromlength = 0 [, int $subjectlength = 0 [, string $defaulthost = NULL ]]] )

Gets information about the given message number by reading its headers.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

fromlength

Number of characters for the fetchfrom property. Must be greater than or equal to zero.

subjectlength

Number of characters for the fetchsubject property Must be greater than or equal to zero.

defaulthost

Zwracane wartości

Returns the information in an object with following properties:

  • toaddress - full to: line, up to 1024 characters
  • to - an array of objects from the To: line, with the following properties: personal, adl, mailbox, and host
  • fromaddress - full from: line, up to 1024 characters
  • from - an array of objects from the From: line, with the following properties: personal, adl, mailbox, and host
  • ccaddress - full cc: line, up to 1024 characters
  • cc - an array of objects from the Cc: line, with the following properties: personal, adl, mailbox, and host
  • bccaddress - full bcc: line, up to 1024 characters
  • bcc - an array of objects from the Bcc: line, with the following properties: personal, adl, mailbox, and host
  • reply_toaddress - full Reply-To: line, up to 1024 characters
  • reply_to - an array of objects from the Reply-To: line, with the following properties: personal, adl, mailbox, and host
  • senderaddress - full sender: line, up to 1024 characters
  • sender - an array of objects from the Sender: line, with the following properties: personal, adl, mailbox, and host
  • return_pathaddress - full Return-Path: line, up to 1024 characters
  • return_path - an array of objects from the Return-Path: line, with the following properties: personal, adl, mailbox, and host
  • remail -
  • date - The message date as found in its headers
  • Date - Same as date
  • subject - The message subject
  • Subject - Same a subject
  • in_reply_to -
  • message_id -
  • newsgroups -
  • followup_to -
  • references -
  • Recent - R if recent and seen, N if recent and not seen, ' ' if not recent.
  • Unseen - U if not seen AND not recent, ' ' if seen OR not seen and recent
  • Flagged - F if flagged, ' ' if not flagged
  • Answered - A if answered, ' ' if unanswered
  • Deleted - D if deleted, ' ' if not deleted
  • Draft - X if draft, ' ' if not draft
  • Msgno - The message number
  • MailDate -
  • Size - The message size
  • udate - mail message date in Unix time
  • fetchfrom - from line formatted to fit fromlength characters
  • fetchsubject - subject line formatted to fit subjectlength characters

Zobacz też:

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

imap_header
imap_headers
IMAP Funkcje


Returns headers for all messages in a mailbox

imap_headerinfo
imap_last_error
IMAP Funkcje
PHP Manual

imap_headers

(PHP 4, PHP 5)

imap_headers — Returns headers for all messages in a mailbox

Opis

array imap_headers ( resource $imap_stream )

Returns headers for all messages in a mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

Zwracane wartości

Returns an array of string formatted with header info. One element per mail message.

imap_headerinfo
imap_last_error
IMAP Funkcje


Gets the last IMAP error that occurred during this page request

imap_headers
imap_list
IMAP Funkcje
PHP Manual

imap_last_error

(PHP 4, PHP 5)

imap_last_error — Gets the last IMAP error that occurred during this page request

Opis

string imap_last_error ( void )

Gets the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.

Zwracane wartości

Returns the full text of the last IMAP error message that occurred on the current page. Returns FALSE if no error messages are available.

Zobacz też:

  • imap_errors() - Returns all of the IMAP errors that have occured

imap_headers
imap_list
IMAP Funkcje


Read the list of mailboxes

imap_last_error
imap_listmailbox
IMAP Funkcje
PHP Manual

imap_list

(PHP 4, PHP 5)

imap_list — Read the list of mailboxes

Opis

array imap_list ( resource $imap_stream , string $ref , string $pattern )

Read the list of mailboxes.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

ref

ref should normally be just the server specification as described in imap_open().

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Zwracane wartości

Returns an array containing the names of the mailboxes.

Przykłady

Przykład #1 imap_list() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$list = imap_list($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
    foreach ($list as $val) {
        echo imap_utf7_decode($val) . "\n";
    }
} else {
    echo "imap_list failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

Zobacz też:

  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one
  • imap_lsub() - List all the subscribed mailboxes

imap_last_error
imap_listmailbox
IMAP Funkcje


Alias dla imap_list

imap_list
imap_listscan
IMAP Funkcje
PHP Manual

imap_listmailbox

(PHP 4, PHP 5)

imap_listmailbox — Alias dla imap_list()

Opis

Ta funkcja jest aliasem dla: imap_list().

imap_list
imap_listscan
IMAP Funkcje


Returns the list of mailboxes that matches the given text

imap_listmailbox
imap_listsubscribed
IMAP Funkcje
PHP Manual

imap_listscan

(PHP 4, PHP 5)

imap_listscan — Returns the list of mailboxes that matches the given text

Opis

array imap_listscan ( resource $imap_stream , string $ref , string $pattern , string $content )

Returns an array containing the names of the mailboxes that have content in the text of the mailbox.

This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

content

The searched string

Zwracane wartości

Returns an array containing the names of the mailboxes that have content in the text of the mailbox.

Zobacz też:

  • imap_listmailbox() - Alias dla imap_list
  • imap_search() - This function returns an array of messages matching the given search criteria

imap_listmailbox
imap_listsubscribed
IMAP Funkcje


Alias dla imap_lsub

imap_listscan
imap_lsub
IMAP Funkcje
PHP Manual

imap_listsubscribed

(PHP 4, PHP 5)

imap_listsubscribed — Alias dla imap_lsub()

Opis

Ta funkcja jest aliasem dla: imap_lsub().

imap_listscan
imap_lsub
IMAP Funkcje


List all the subscribed mailboxes

imap_listsubscribed
imap_mail_compose
IMAP Funkcje
PHP Manual

imap_lsub

(PHP 4, PHP 5)

imap_lsub — List all the subscribed mailboxes

Opis

array imap_lsub ( resource $imap_stream , string $ref , string $pattern )

Gets an array of all the mailboxes that you have subscribed.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

ref

ref should normally be just the server specification as described in imap_open()

pattern

Specifies where in the mailbox hierarchy to start searching.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Zwracane wartości

Returns an array of all the subscribed mailboxes.

Zobacz też:

  • imap_list() - Read the list of mailboxes
  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one

imap_listsubscribed
imap_mail_compose
IMAP Funkcje


Create a MIME message based on given envelope and body sections

imap_lsub
imap_mail_copy
IMAP Funkcje
PHP Manual

imap_mail_compose

(PHP 4, PHP 5)

imap_mail_compose — Create a MIME message based on given envelope and body sections

Opis

string imap_mail_compose ( array $envelope , array $body )

Create a MIME message based on the given envelope and body sections.

Parametry

envelope

An associative array of headers fields. Valid keys are: "remail", "return_path", "date", "from", "reply_to", "in_reply_to", "subject", "to", "cc", "bcc", "message_id" and "custom_headers" (which contains associative array of other headers).

body

An indexed array of bodies

A body is an associative array which can consist of the following keys: "type", "encoding", "charset", "type.parameters", "subtype", "id", "description", "disposition.type", "disposition", "contents.data", "lines", "bytes" and "md5".

Zwracane wartości

Returns the MIME message.

Przykłady

Przykład #1 imap_mail_compose() example

<?php

$envelope["from"]= "joe@example.com";
$envelope["to"]  = "foo@example.com";
$envelope["cc"]  = "bar@example.com";

$part1["type"] = TYPEMULTIPART;
$part1["subtype"] = "mixed";

$filename = "/tmp/imap.c.gz";
$fp = fopen($filename, "r");
$contents = fread($fp, filesize($filename));
fclose($fp);

$part2["type"] = TYPEAPPLICATION;
$part2["encoding"] = ENCBINARY;
$part2["subtype"] = "octet-stream";
$part2["description"] = basename($filename);
$part2["contents.data"] = $contents;

$part3["type"] = TYPETEXT;
$part3["subtype"] = "plain";
$part3["description"] = "description3";
$part3["contents.data"] = "contents.data3\n\n\n\t";

$body[1] = $part1;
$body[2] = $part2;
$body[3] = $part3;

echo nl2br(imap_mail_compose($envelope, $body));

?>

imap_lsub
imap_mail_copy
IMAP Funkcje


Copy specified messages to a mailbox

imap_mail_compose
imap_mail_move
IMAP Funkcje
PHP Manual

imap_mail_copy

(PHP 4, PHP 5)

imap_mail_copy — Copy specified messages to a mailbox

Opis

bool imap_mail_copy ( resource $imap_stream , string $msglist , string $mailbox [, int $options = 0 ] )

Copies mail messages specified by msglist to specified mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msglist

msglist is a range not just message numbers (as described in » RFC2060).

mailbox

The mailbox name, see imap_open() for more information

options

options is a bitmask of one or more of

  • CP_UID - the sequence numbers contain UIDS
  • CP_MOVE - Delete the messages from the current mailbox after copying

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_mail_move() - Move specified messages to a mailbox

imap_mail_compose
imap_mail_move
IMAP Funkcje


Move specified messages to a mailbox

imap_mail_copy
imap_mail
IMAP Funkcje
PHP Manual

imap_mail_move

(PHP 4, PHP 5)

imap_mail_move — Move specified messages to a mailbox

Opis

bool imap_mail_move ( resource $imap_stream , string $msglist , string $mailbox [, int $options = 0 ] )

Moves mail messages specified by msglist to the specified mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msglist

msglist is a range not just message numbers (as described in » RFC2060).

mailbox

The mailbox name, see imap_open() for more information

options

options is a bitmask and may contain the single option:

  • CP_UID - the sequence numbers contain UIDS

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

imap_mail_move() will flag the original mail with a delete flag, to successfully delete it a call to the imap_expunge() function must be made.

Zobacz też:

  • imap_mail_copy() - Copy specified messages to a mailbox

imap_mail_copy
imap_mail
IMAP Funkcje


Send an email message

imap_mail_move
imap_mailboxmsginfo
IMAP Funkcje
PHP Manual

imap_mail

(PHP 4, PHP 5)

imap_mail — Send an email message

Opis

bool imap_mail ( string $to , string $subject , string $message [, string $additional_headers = NULL [, string $cc = NULL [, string $bcc = NULL [, string $rpath = NULL ]]]] )

This function allows sending of emails with correct handling of Cc and Bcc receivers.

The parameters to, cc and bcc are all strings and are all parsed as » RFC822 address lists.

Parametry

to

The receiver

subject

The mail subject

message

The mail body

additional_headers

As string with additional headers to be set on the mail

cc

bcc

The receivers specified in bcc will get the mail, but are excluded from the headers.

rpath

Use this parameter to specify return path upon mail delivery failure. This is useful when using PHP as a mail client for multiple users.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mail() - Wysyłanie poczty elektronicznej

imap_mail_move
imap_mailboxmsginfo
IMAP Funkcje


Get information about the current mailbox

imap_mail
imap_mime_header_decode
IMAP Funkcje
PHP Manual

imap_mailboxmsginfo

(PHP 4, PHP 5)

imap_mailboxmsginfo — Get information about the current mailbox

Opis

object imap_mailboxmsginfo ( resource $imap_stream )

Checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

Zwracane wartości

Returns the information in an object with following properties:

Mailbox properties
Date | date of last change (current datetime)
Driver | driver
Mailbox | name of the mailbox
Nmsgs | number of messages
Recent | number of recent messages
Unread | number of unread messages
Deleted | number of deleted messages
Size | mailbox size

Returns FALSE on failure.

Przykłady

Przykład #1 imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
      or die("can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);

if ($check) {
    echo "Date: "     . $check->Date    . "<br />\n" ;
    echo "Driver: "   . $check->Driver  . "<br />\n" ;
    echo "Mailbox: "  . $check->Mailbox . "<br />\n" ;
    echo "Messages: " . $check->Nmsgs   . "<br />\n" ;
    echo "Recent: "   . $check->Recent  . "<br />\n" ;
    echo "Unread: "   . $check->Unread  . "<br />\n" ;
    echo "Deleted: "  . $check->Deleted . "<br />\n" ;
    echo "Size: "     . $check->Size    . "<br />\n" ;
} else {
    echo "imap_check() failed: " . imap_last_error() . "<br />\n";
}

imap_close($mbox);

?>

imap_mail
imap_mime_header_decode
IMAP Funkcje


Decode MIME header elements

imap_mailboxmsginfo
imap_msgno
IMAP Funkcje
PHP Manual

imap_mime_header_decode

(PHP 4, PHP 5)

imap_mime_header_decode — Decode MIME header elements

Opis

array imap_mime_header_decode ( string $text )

Decodes MIME message header extensions that are non ASCII text (see » RFC2047).

Parametry

text

The MIME text

Zwracane wartości

The decoded elements are returned in an array of objects, where each object has two properties, charset and text.

If the element hasn't been encoded, and in other words is in plain US-ASCII, the charset property of that element is set to default.

Przykłady

Przykład #1 imap_mime_header_decode() example

<?php
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@example.com>";

$elements = imap_mime_header_decode($text);
for ($i=0; $i<count($elements); $i++) {
    echo "Charset: {$elements[$i]->charset}\n";
    echo "Text: {$elements[$i]->text}\n\n";
}
?>

Powyższy przykład wyświetli:

Charset: ISO-8859-1
Text: Keld Jørn Simonsen

Charset: default
Text:  <keld@example.com>

In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.

Zobacz też:

  • imap_utf8() - Converts MIME-encoded text to UTF-8

imap_mailboxmsginfo
imap_msgno
IMAP Funkcje


Gets the message sequence number for the given UID

imap_mime_header_decode
imap_num_msg
IMAP Funkcje
PHP Manual

imap_msgno

(PHP 4, PHP 5)

imap_msgno — Gets the message sequence number for the given UID

Opis

int imap_msgno ( resource $imap_stream , int $uid )

Returns the message sequence number for the given uid.

This function is the inverse of imap_uid().

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

uid

The message UID

Zwracane wartości

Returns the message sequence number for the given uid.

Zobacz też:

  • imap_uid() - This function returns the UID for the given message sequence number

imap_mime_header_decode
imap_num_msg
IMAP Funkcje


Gets the number of messages in the current mailbox

imap_msgno
imap_num_recent
IMAP Funkcje
PHP Manual

imap_num_msg

(PHP 4, PHP 5)

imap_num_msg — Gets the number of messages in the current mailbox

Opis

int imap_num_msg ( resource $imap_stream )

Gets the number of messages in the current mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

Zwracane wartości

Return the number of messages in the current mailbox, as an integer.

Zobacz też:

  • imap_num_recent() - Gets the number of recent messages in current mailbox
  • imap_status() - Returns status information on a mailbox

imap_msgno
imap_num_recent
IMAP Funkcje


Gets the number of recent messages in current mailbox

imap_num_msg
imap_open
IMAP Funkcje
PHP Manual

imap_num_recent

(PHP 4, PHP 5)

imap_num_recent — Gets the number of recent messages in current mailbox

Opis

int imap_num_recent ( resource $imap_stream )

Gets the number of recent messages in the current mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

Zwracane wartości

Returns the number of recent messages in the current mailbox, as an integer.

Zobacz też:

  • imap_num_msg() - Gets the number of messages in the current mailbox
  • imap_status() - Returns status information on a mailbox

imap_num_msg
imap_open
IMAP Funkcje


Open an IMAP stream to a mailbox

imap_num_recent
imap_ping
IMAP Funkcje
PHP Manual

imap_open

(PHP 4, PHP 5)

imap_open — Open an IMAP stream to a mailbox

Opis

resource imap_open ( string $mailbox , string $username , string $password [, int $options = NIL [, int $n_retries = 0 [, array $params = NULL ]]] )

Opens an IMAP stream to a mailbox.

This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

Parametry

mailbox

A mailbox name consists of a server and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded width imap_utf7_encode().

The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/').

The server part is mandatory in all mailbox parameters.

All names which start with { are remote names, and are in the form "{" remote_system_name [":" port] [flags] "}" [mailbox_name] where:

  • remote_system_name - Internet domain name or bracketed IP address of server.
  • port - optional TCP port number, default is the default port for that service
  • flags - optional flags, see following table.
  • mailbox_name - remote mailbox name, default is INBOX

Optional flags for names
Flag | Description
/service=service | mailbox access service, default is "imap"
/user=user | remote user name for login on the server
/authuser=user | remote authentication user; if specified this is the user name whose password is used (e.g. administrator)
/anonymous | remote access as anonymous user
/debug | record protocol telemetry in application's debug log
/secure | do not transmit a plaintext password over the network
/imap, /imap2, /imap2bis, /imap4, /imap4rev1 | equivalent to /service=imap
/pop3 | equivalent to /service=pop3
/nntp | equivalent to /service=nntp
/norsh | do not use rsh or ssh to establish a preauthenticated IMAP session
/ssl | use the Secure Socket Layer to encrypt the session
/validate-cert | validate certificates from TLS/SSL server (this is the default behavior)
/novalidate-cert | do not validate certificates from TLS/SSL server, needed if server uses self-signed certificates
/tls | force use of start-TLS to encrypt the session, and reject connection to servers that do not support it
/notls | do not do start-TLS to encrypt the session, even with servers that support it
/readonly | request read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3)

username

The user name

password

The password associated with the username

options

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only
  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
  • OP_DEBUG - Debug protocol negotiations
  • OP_SHORTCACHE - Short (elt-only) caching
  • OP_SILENT - Don't pass up events (internal use)
  • OP_PROTOTYPE - Return driver prototype
  • OP_SECURE - Don't do non-secure authentication

n_retries

Number of maximum connect attempts

params

Connection parameters, the following (string) keys maybe used to set one or more connection parameters:

  • DISABLE_AUTHENTICATOR - Disable authentication properties

Zwracane wartości

Returns an IMAP stream on success or FALSE on error.

Rejestr zmian

Wersja | Opis
5.3.2 | params added
5.2.0 | n_retries added

Przykłady

Przykład #1 Different use of imap_open()

<?php
// To connect to an IMAP server running on port 143 on the local machine,
// do the following:
$mbox = imap_open("{localhost:143}INBOX", "user_id", "password");

// To connect to a POP3 server on port 110 on the local server, use:
$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server, add /ssl after the protocol
// specification:
$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

// To connect to an SSL IMAP or POP3 server with a self-signed certificate,
// add /ssl/novalidate-cert after the protocol specification:
$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

// To connect to an NNTP server on port 119 on the local server, use:
$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");
// To connect to a remote server replace "localhost" with the name or the
// IP address of the server you want to connect to.
?>

Przykład #2 imap_open() example

<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password");

echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");

if ($folders == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($folders as $val) {
        echo $val . "<br />\n";
    }
}

echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed<br />\n";
} else {
    foreach ($headers as $val) {
        echo $val . "<br />\n";
    }
}

imap_close($mbox);
?>

Zobacz też:

  • imap_close() - Close an IMAP stream

imap_num_recent
imap_ping
IMAP Funkcje


Check if the IMAP stream is still active

imap_open
imap_qprint
IMAP Funkcje
PHP Manual

imap_ping

(PHP 4, PHP 5)

imap_ping — Check if the IMAP stream is still active

Opis

bool imap_ping ( resource $imap_stream )

imap_ping() pings the stream to see if it's still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

Zwracane wartości

Returns TRUE if the stream is still alive, FALSE otherwise.

Przykłady

Przykład #1 imap_ping() Example

<?php

$imap = imap_open("{imap.example.org}", "mailadmin", "password");

// after some sleeping
if (!imap_ping($imap)) {
    // do some stuff to reconnect
}

?>

imap_open
imap_qprint
IMAP Funkcje


Convert a quoted-printable string to an 8 bit string

imap_ping
imap_rename
IMAP Funkcje
PHP Manual

imap_qprint

(PHP 4, PHP 5)

imap_qprint — Convert a quoted-printable string to an 8 bit string

Opis

string imap_qprint ( string $string )

Convert a quoted-printable string to an 8 bit string according to » RFC2045, section 6.7.

Parametry

string

A quoted-printable string

Zwracane wartości

Returns an 8 bits string.

Zobacz też:

  • imap_8bit() - Convert an 8bit string to a quoted-printable string

imap_ping
imap_rename
IMAP Funkcje


Alias dla imap_renamemailbox

imap_qprint
imap_renamemailbox
IMAP Funkcje
PHP Manual

imap_rename

(PHP 4, PHP 5)

imap_rename — Alias dla imap_renamemailbox()

Opis

Ta funkcja jest aliasem dla: imap_renamemailbox().

imap_qprint
imap_renamemailbox
IMAP Funkcje


Rename an old mailbox to new mailbox

imap_rename
imap_reopen
IMAP Funkcje
PHP Manual

imap_renamemailbox

(PHP 4, PHP 5)

imap_renamemailbox — Rename an old mailbox to new mailbox

Opis

bool imap_renamemailbox ( resource $imap_stream , string $old_mbox , string $new_mbox )

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

old_mbox

The old mailbox name, see imap_open() for more information

new_mbox

The new mailbox name, see imap_open() for more information

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_createmailbox() - Create a new mailbox
  • imap_deletemailbox() - Delete a mailbox

imap_rename
imap_reopen
IMAP Funkcje


Reopen IMAP stream to new mailbox

imap_renamemailbox
imap_rfc822_parse_adrlist
IMAP Funkcje
PHP Manual

imap_reopen

(PHP 4, PHP 5)

imap_reopen — Reopen IMAP stream to new mailbox

Opis

bool imap_reopen ( resource $imap_stream , string $mailbox [, int $options = 0 [, int $n_retries = 0 ]] )

Reopens the specified stream to a new mailbox on an IMAP or NNTP server.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information

options

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only
  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
  • OP_EXPUNGE - Silently expunge recycle stream
  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

n_retries

Number of maximum connect attempts

Zwracane wartości

Returns TRUE if the stream is reopened, FALSE otherwise.

Rejestr zmian

Wersja | Opis
5.2.0 | n_retries added

Przykłady

Przykład #1 imap_reopen() example

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors()));
// ...
imap_reopen($mbox, "{imap.example.org:143}INBOX.Sent") or die(implode(", ", imap_errors()));
// ..
?>

imap_renamemailbox
imap_rfc822_parse_adrlist
IMAP Funkcje


Parses an address string

imap_reopen
imap_rfc822_parse_headers
IMAP Funkcje
PHP Manual

imap_rfc822_parse_adrlist

(PHP 4, PHP 5)

imap_rfc822_parse_adrlist — Parses an address string

Opis

array imap_rfc822_parse_adrlist ( string $address , string $default_host )

Parses the address string as defined in » RFC2822 and for each address.

Parametry

address

A string containing addresses

default_host

The default host name

Zwracane wartości

Returns an array of objects. The objects properties are:

  • mailbox - the mailbox name (username)
  • host - the host name
  • personal - the personal name
  • adl - at domain source route

Przykłady

Przykład #1 imap_rfc822_parse_adrlist() example

<?php

$address_string = "Joe Doe <doe@example.com>, postmaster@example.com, root";
$address_array  = imap_rfc822_parse_adrlist($address_string, "example.com");
if (!is_array($address_array) || count($address_array) < 1) {
    die("something is wrong\n");
}

foreach ($address_array as $id => $val) {
    echo "# $id\n";
    echo "  mailbox : " . $val->mailbox . "\n";
    echo "  host    : " . $val->host . "\n";
    echo "  personal: " . $val->personal . "\n";
    echo "  adl     : " . $val->adl . "\n";
}
?>

Powyższy przykład wyświetli:

# 0
  mailbox : doe
  host    : example.com
  personal: Joe Doe
  adl     :
# 1
  mailbox : postmaster
  host    : example.com
  personal:
  adl     :
# 2
  mailbox : root
  host    : example.com
  personal:
  adl     :

Zobacz też:

  • imap_rfc822_parse_headers() - Parse mail headers from a string

imap_reopen
imap_rfc822_parse_headers
IMAP Funkcje


Parse mail headers from a string

imap_rfc822_parse_adrlist
imap_rfc822_write_address
IMAP Funkcje
PHP Manual

imap_rfc822_parse_headers

(PHP 4, PHP 5)

imap_rfc822_parse_headers — Parse mail headers from a string

Opis

object imap_rfc822_parse_headers ( string $headers [, string $defaulthost = "UNKNOWN" ] )

Gets an object of various header elements, similar to imap_header().

Parametry

headers

The parsed headers data

defaulthost

The default host name

Zwracane wartości

Returns an object similar to the one returned by imap_header(), except for the flags and other properties that come from the IMAP server.

Zobacz też:

  • imap_rfc822_parse_adrlist() - Parses an address string

imap_rfc822_parse_adrlist
imap_rfc822_write_address
IMAP Funkcje


Returns a properly formatted email address given the mailbox, host, and personal info

imap_rfc822_parse_headers
imap_savebody
IMAP Funkcje
PHP Manual

imap_rfc822_write_address

(PHP 4, PHP 5)

imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info

Opis

string imap_rfc822_write_address ( string $mailbox , string $host , string $personal )

Returns a properly formatted email address as defined in » RFC2822 given the needed information.

Parametry

mailbox

The mailbox name, see imap_open() for more information

host

The email host part

personal

The name of the account owner

Zwracane wartości

Returns a string properly formatted email address as defined in » RFC2822.

Przykłady

Przykład #1 imap_rfc822_write_address() example

<?php
echo imap_rfc822_write_address("hartmut", "example.com", "Hartmut Holzgraefe");
?>

Powyższy przykład wyświetli:

Hartmut Holzgraefe <hartmut@example.com>

imap_rfc822_parse_headers
imap_savebody
IMAP Funkcje


Save a specific body section to a file

imap_rfc822_write_address
imap_scan
IMAP Funkcje
PHP Manual

imap_savebody

(PHP 5 >= 5.1.3)

imap_savebody — Save a specific body section to a file

Opis

bool imap_savebody ( resource $imap_stream , mixed $file , int $msg_number [, string $part_number = "" [, int $options = 0 ]] )

Saves a part or the whole body of the specified message.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

file

The path to the saved file as a string, or a valid file descriptor returned by fopen().

msg_number

The message number

part_number

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID
  • FT_PEEK - Do not set the \Seen flag if not already set
  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_fetchbody() - Fetch a particular section of the body of the message

imap_rfc822_write_address
imap_scan
IMAP Funkcje


Alias dla imap_listscan

imap_savebody
imap_scanmailbox
IMAP Funkcje
PHP Manual

imap_scan

(PHP 4, PHP 5)

imap_scan — Alias dla imap_listscan()

Opis

Ta funkcja jest aliasem dla: imap_listscan().

imap_savebody
imap_scanmailbox
IMAP Funkcje


Alias dla imap_listscan

imap_scan
imap_search
IMAP Funkcje
PHP Manual

imap_scanmailbox

(PHP 4, PHP 5)

imap_scanmailbox — Alias dla imap_listscan()

Opis

Ta funkcja jest aliasem dla: imap_listscan().

imap_scan
imap_search
IMAP Funkcje


This function returns an array of messages matching the given search criteria

imap_scanmailbox
imap_set_quota
IMAP Funkcje
PHP Manual

imap_search

(PHP 4, PHP 5)

imap_search — This function returns an array of messages matching the given search criteria

Opis

array imap_search ( resource $imap_stream , string $criteria [, int $options = SE_FREE [, string $charset = NIL ]] )

This function performs a search on the mailbox currently opened in the given IMAP stream.

For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be incomplete or inaccurate (see also » RFC2060, section 6.4.4).

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

criteria

A string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted. Results will match all criteria entries.

  • ALL - return all messages matching the rest of the criteria
  • ANSWERED - match messages with the \\ANSWERED flag set
  • BCC "string" - match messages with "string" in the Bcc: field
  • BEFORE "date" - match messages with Date: before "date"
  • BODY "string" - match messages with "string" in the body of the message
  • CC "string" - match messages with "string" in the Cc: field
  • DELETED - match deleted messages
  • FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
  • FROM "string" - match messages with "string" in the From: field
  • KEYWORD "string" - match messages with "string" as a keyword
  • NEW - match new messages
  • OLD - match old messages
  • ON "date" - match messages with Date: matching "date"
  • RECENT - match messages with the \\RECENT flag set
  • SEEN - match messages that have been read (the \\SEEN flag is set)
  • SINCE "date" - match messages with Date: after "date"
  • SUBJECT "string" - match messages with "string" in the Subject:
  • TEXT "string" - match messages with text "string"
  • TO "string" - match messages with "string" in the To:
  • UNANSWERED - match messages that have not been answered
  • UNDELETED - match messages that are not deleted
  • UNFLAGGED - match messages that are not flagged
  • UNKEYWORD "string" - match messages that do not have the keyword "string"
  • UNSEEN - match messages which have not been read yet

options

Valid values for options are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.

charset

Zwracane wartości

Returns an array of message numbers or UIDs.

Return FALSE if it does not understand the search criteria or no messages have been found.

Rejestr zmian

Wersja | Opis
4.3.3 | The charset parameter was added

Przykłady

Przykład #1 imap_search() example

<?php
$conn   = imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);

$some   = imap_search($conn, 'SUBJECT "HOWTO be Awesome" SINCE "8 August 2008"', SE_UID);
$msgnos = imap_search($conn, 'ALL');
$uids   = imap_search($conn, 'ALL', SE_UID);

print_r($some);
print_r($msgnos);
print_r($uids);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => 4
    [1] => 6
    [2] => 11
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Array
(
    [0] => 1
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 11
    [5] => 12
)

Zobacz też:

  • imap_listscan() - Returns the list of mailboxes that matches the given text

imap_scanmailbox
imap_set_quota
IMAP Funkcje


Sets a quota for a given mailbox

imap_search
imap_setacl
IMAP Funkcje
PHP Manual

imap_set_quota

(PHP 4 >= 4.0.5, PHP 5)

imap_set_quota — Sets a quota for a given mailbox

Opis

bool imap_set_quota ( resource $imap_stream , string $quota_root , int $quota_limit )

Sets an upper limit quota on a per mailbox basis.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

quota_root

The mailbox to have a quota set. This should follow the IMAP standard format for a mailbox: user.name.

quota_limit

The maximum size (in KB) for the quota_root

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imap_set_quota() example

<?php
$mbox = imap_open("{imap.example.org:143}", "mailadmin", "password");

if (!imap_set_quota($mbox, "user.kalowsky", 3000)) {
    echo "Error in setting quota\n";
    return;
}

imap_close($mbox);
?>

Notatki

This function is currently only available to users of the c-client2000 or greater library.

The given imap_stream must be opened as the mail administrator, other wise this function will fail.

Zobacz też:

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

imap_search
imap_setacl
IMAP Funkcje


Sets the ACL for a giving mailbox

imap_set_quota
imap_setflag_full
IMAP Funkcje
PHP Manual

imap_setacl

(PHP 4 >= 4.0.7, PHP 5)

imap_setacl — Sets the ACL for a giving mailbox

Opis

bool imap_setacl ( resource $imap_stream , string $mailbox , string $id , string $rights )

Sets the ACL for a giving mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information

id

The user to give the rights to.

rights

The rights to give to the user. Passing an empty string will delete acl.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

This function is currently only available to users of the c-client2000 or greater library.

Zobacz też:

  • imap_getacl() - Gets the ACL for a given mailbox

imap_set_quota
imap_setflag_full
IMAP Funkcje


Sets flags on messages

imap_setacl
imap_sort
IMAP Funkcje
PHP Manual

imap_setflag_full

(PHP 4, PHP 5)

imap_setflag_full — Sets flags on messages

Opis

bool imap_setflag_full ( resource $imap_stream , string $sequence , string $flag [, int $options = NIL ] )

Causes a store to add the specified flag to the flags set for the messages in the specified sequence.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

sequence

A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flag

The flags which you can set are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by » RFC2060.

options

A bit mask that may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 imap_setflag_full() example

<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password")
     or die("can't connect: " . imap_last_error());

$status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged");

echo gettype($status) . "\n";
echo $status . "\n";

imap_close($mbox);
?>

Zobacz też:

  • imap_clearflag_full() - Clears flags on messages

imap_setacl
imap_sort
IMAP Funkcje


Gets and sort messages

imap_setflag_full
imap_status
IMAP Funkcje
PHP Manual

imap_sort

(PHP 4, PHP 5)

imap_sort — Gets and sort messages

Opis

array imap_sort ( resource $imap_stream , int $criteria , int $reverse [, int $options = 0 [, string $search_criteria = NULL [, string $charset = NIL ]]] )

Gets and sorts message numbers by the given parameters.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

criteria

Criteria can be one (and only one) of the following:

  • SORTDATE - message Date
  • SORTARRIVAL - arrival date
  • SORTFROM - mailbox in first From address
  • SORTSUBJECT - message subject
  • SORTTO - mailbox in first To address
  • SORTCC - mailbox in first cc address
  • SORTSIZE - size of message in octets

reverse

Set this to 1 for reverse sorting

options

The options are a bitmask of one or more of the following:

  • SE_UID - Return UIDs instead of sequence numbers
  • SE_NOPREFETCH - Don't prefetch searched messages

search_criteria

charset

Zwracane wartości

Returns an array of message numbers sorted by the given parameters.

Rejestr zmian

Wersja | Opis
4.3.3 | The charset parameter was added

imap_setflag_full
imap_status
IMAP Funkcje


Returns status information on a mailbox

imap_sort
imap_subscribe
IMAP Funkcje
PHP Manual

imap_status

(PHP 4, PHP 5)

imap_status — Returns status information on a mailbox

Opis

object imap_status ( resource $imap_stream , string $mailbox , int $options )

Gets status information about the given mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information

options

Valid flags are:

  • SA_MESSAGES - set $status->messages to the number of messages in the mailbox
  • SA_RECENT - set $status->recent to the number of recent messages in the mailbox
  • SA_UNSEEN - set $status->unseen to the number of unseen (new) messages in the mailbox
  • SA_UIDNEXT - set $status->uidnext to the next uid to be used in the mailbox
  • SA_UIDVALIDITY - set $status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid
  • SA_ALL - set all of the above

Zwracane wartości

This function returns an object containing status information. The object has the following properties: messages, recent, unseen, uidnext, and uidvalidity.

flags is also set, which contains a bitmask which can be checked against any of the above constants.

Przykłady

Przykład #1 imap_status() example

<?php
$mbox = imap_open("{imap.example.com}", "username", "password", OP_HALFOPEN)
      or die("can't connect: " . imap_last_error());

$status = imap_status($mbox, "{imap.example.org}INBOX", SA_ALL);
if ($status) {
  echo "Messages:   " . $status->messages    . "<br />\n";
  echo "Recent:     " . $status->recent      . "<br />\n";
  echo "Unseen:     " . $status->unseen      . "<br />\n";
  echo "UIDnext:    " . $status->uidnext     . "<br />\n";
  echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";
} else {
  echo "imap_status failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

imap_sort
imap_subscribe
IMAP Funkcje


Subscribe to a mailbox

imap_status
imap_thread
IMAP Funkcje
PHP Manual

imap_subscribe

(PHP 4, PHP 5)

imap_subscribe — Subscribe to a mailbox

Opis

bool imap_subscribe ( resource $imap_stream , string $mailbox )

Subscribe to a new mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_unsubscribe() - Unsubscribe from a mailbox

imap_status
imap_thread
IMAP Funkcje


Returns a tree of threaded message

imap_subscribe
imap_timeout
IMAP Funkcje
PHP Manual

imap_thread

(PHP 4 >= 4.0.7, PHP 5)

imap_thread — Returns a tree of threaded message

Opis

array imap_thread ( resource $imap_stream [, int $options = SE_FREE ] )

Gets a tree of a threaded message.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

options

Zwracane wartości

imap_thread() returns an associative array containing a tree of messages threaded by REFERENCES, or FALSE on error.

Every message in the current mailbox will be represented by three entries in the resulting array:

  • $thread["XX.num"] - current message number

  • $thread["XX.next"]

  • $thread["XX.branch"]

Przykłady

Przykład #1 imap_thread() Example

<?php

// Here we're outputting the threads of a newsgroup, in HTML

$nntp = imap_open('{news.example.com:119/nntp}some.newsgroup', '', '');
$threads = imap_thread($nntp);

foreach ($threads as $key => $val) {
  $tree = explode('.', $key);
  if ($tree[1] == 'num') {
    $header = imap_headerinfo($nntp, $val);
    echo "<ul>\n\t<li>" . $header->fromaddress . "\n";
  } elseif ($tree[1] == 'branch') {
    echo "\t</li>\n</ul>\n";
  }
}

imap_close($nntp);

?>

imap_subscribe
imap_timeout
IMAP Funkcje


Set or fetch imap timeout

imap_thread
imap_uid
IMAP Funkcje
PHP Manual

imap_timeout

(PHP 4 >= 4.3.3, PHP 5)

imap_timeout — Set or fetch imap timeout

Opis

mixed imap_timeout ( int $timeout_type [, int $timeout = -1 ] )

Sets or fetches the imap timeout.

Parametry

timeout_type

One of the following: IMAP_OPENTIMEOUT, IMAP_READTIMEOUT, IMAP_WRITETIMEOUT, or IMAP_CLOSETIMEOUT.

timeout

The timeout, in seconds.

Zwracane wartości

If the timeout parameter is set, this function returns TRUE on success and FALSE on failure.

If timeout is not provided or evaluates to -1, the current timeout value of timeout_type is returned as an integer.

Przykłady

Przykład #1 imap_timeout() example

<?php

echo "The current read timeout is " . imap_timeout(IMAP_READTIMEOUT) . "\n";

?>

imap_thread
imap_uid
IMAP Funkcje


This function returns the UID for the given message sequence number

imap_timeout
imap_undelete
IMAP Funkcje
PHP Manual

imap_uid

(PHP 4, PHP 5)

imap_uid — This function returns the UID for the given message sequence number

Opis

int imap_uid ( resource $imap_stream , int $msg_number )

This function returns the UID for the given message sequence number. An UID is a unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes.

This function is the inverse of imap_msgno().

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number.

Zwracane wartości

The UID of the given message.

Notatki

Informacja:

This function is not supported by POP3 mailboxes.

Zobacz też:

  • imap_msgno() - Gets the message sequence number for the given UID

imap_timeout
imap_undelete
IMAP Funkcje


Unmark the message which is marked deleted

imap_uid
imap_unsubscribe
IMAP Funkcje
PHP Manual

imap_undelete

(PHP 4, PHP 5)

imap_undelete — Unmark the message which is marked deleted

Opis

bool imap_undelete ( resource $imap_stream , int $msg_number [, int $flags = 0 ] )

Removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

msg_number

The message number

flags

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_delete() - Mark a message for deletion from current mailbox
  • imap_mail_move() - Move specified messages to a mailbox

imap_uid
imap_unsubscribe
IMAP Funkcje


Unsubscribe from a mailbox

imap_undelete
imap_utf7_decode
IMAP Funkcje
PHP Manual

imap_unsubscribe

(PHP 4, PHP 5)

imap_unsubscribe — Unsubscribe from a mailbox

Opis

bool imap_unsubscribe ( resource $imap_stream , string $mailbox )

Unsubscribe from the specified mailbox.

Parametry

imap_stream

Strumień IMAP zwrócony przez imap_open().

mailbox

The mailbox name, see imap_open() for more information

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • imap_subscribe() - Subscribe to a mailbox

imap_undelete
imap_utf7_decode
IMAP Funkcje


Decodes a modified UTF-7 encoded string

imap_unsubscribe
imap_utf7_encode
IMAP Funkcje
PHP Manual

imap_utf7_decode

(PHP 4, PHP 5)

imap_utf7_decode — Decodes a modified UTF-7 encoded string

Opis

string imap_utf7_decode ( string $text )

Decodes modified UTF-7 text into ISO-8859-1 string.

This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters.

Parametry

text

A modified UTF-7 encoding string, as defined in » RFC 2060, section 5.1.3 (original UTF-7 was defined in » RFC1642).

Zwracane wartości

Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in text, or FALSE if text contains invalid modified UTF-7 sequence or text contains a character that is not part of ISO-8859-1 character set.

Zobacz też:

  • imap_utf7_encode() - Converts ISO-8859-1 string to modified UTF-7 text

imap_unsubscribe
imap_utf7_encode
IMAP Funkcje


Converts ISO-8859-1 string to modified UTF-7 text

imap_utf7_decode
imap_utf8
IMAP Funkcje
PHP Manual

imap_utf7_encode

(PHP 4, PHP 5)

imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text

Opis

string imap_utf7_encode ( string $data )

Converts data to modified UTF-7 text.

This is needed to encode mailbox names that contain certain characters which are not in range of printable ASCII characters.

Parametry

data

An ISO-8859-1 string.

Zwracane wartości

Returns data encoded with the modified UTF-7 encoding as defined in » RFC 2060, section 5.1.3 (original UTF-7 was defined in » RFC1642).

Zobacz też:

  • imap_utf7_decode() - Decodes a modified UTF-7 encoded string

imap_utf7_decode
imap_utf8
IMAP Funkcje


Converts MIME-encoded text to UTF-8

imap_utf7_encode
Mail
IMAP Funkcje
PHP Manual

imap_utf8

(PHP 4, PHP 5)

imap_utf8 — Converts MIME-encoded text to UTF-8

Opis

string imap_utf8 ( string $mime_encoded_text )

Converts the given mime_encoded_text to UTF-8.

Parametry

mime_encoded_text

A MIME encoded string. MIME encoding method and the UTF-8 specification are described in » RFC2047 and » RFC2044 respectively.

Zwracane wartości

Returns an UTF-8 encoded string.

Zobacz też:

  • imap_mime_header_decode() - Decode MIME header elements

imap_utf7_encode
Mail
IMAP Funkcje


Mail

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Mail Funkcje
    • ezmlm_hash — Oblicza wartość hash potrzebną dla EZMLM
    • mail — Wysyłanie poczty elektronicznej
imap_utf8
Wstęp
Rozszerzenia powiązane z pocztą elektroniczną


Wstęp

The mail() function allows you to send mail.

Mail
Instalacja/Konfiguracja
Mail


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Mail


Wymagania

For the Mail functions to be available, PHP must have access to the sendmail binary on your system during compile time. If you use another mail program, such as qmail or postfix, be sure to use the appropriate sendmail wrappers that come with them. PHP will first look for sendmail in your PATH, and then in the following: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. It's highly recommended to have sendmail available from your PATH. Also, the user that compiled PHP must have permission to access the sendmail binary.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Mail configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mail.add_x_header | "0" | PHP_INI_PERDIR | Available since PHP 5.3.0.
mail.log | NULL | PHP_INI_PERDIR | Available since PHP 5.3.0.
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL | Available since PHP 4.3.0.
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | 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.

mail.add_x_header bool

Add X-PHP-Originating-Script that will include UID of the script followed by the filename.

mail.log string

The path to a log file that will log all mail() calls. Log entries include the full path of the script, line number, To address and headers.

SMTP string

Used under Windows only: host name or IP address of the SMTP server PHP should use for mail sent with the mail() function.

smtp_port int

Used under Windows only: Number of the port to connect to the server specified with the SMTP setting when sending mail with mail(); defaults to 25. Only available since PHP 4.3.0.

sendmail_from string

Which "From:" mail address should be used in mail sent from PHP under Windows. This directive also sets the "Return-Path:" header.

sendmail_path string

Where the sendmail program can be found, usually /usr/sbin/sendmail or /usr/lib/sendmail. configure does an honest attempt of locating this one for you and set a default, but if it fails, you can set it here.

Systems not using sendmail should set this directive to the sendmail wrapper/replacement their mail system offers, if any. For example, » Qmail users can normally set it to /var/qmail/bin/sendmail or /var/qmail/bin/qmail-inject.

qmail-inject does not require any option to process mail correctly.

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Mail Funkcje
Mail


Mail Funkcje

Spis treści

  • ezmlm_hash — Oblicza wartość hash potrzebną dla EZMLM
  • mail — Wysyłanie poczty elektronicznej
Stałe predefiniowane
ezmlm_hash
Mail


Oblicza wartość hash potrzebną dla EZMLM

Mail Funkcje
mail
Mail Funkcje
PHP Manual

ezmlm_hash

(PHP 4 >= 4.0.2, PHP 5)

ezmlm_hash — Oblicza wartość hash potrzebną dla EZMLM

Opis

int ezmlm_hash ( string $adres_e-mail )

ezmlm_hash() oblicza wartość hash potrzebną przy przechowywaniu list adresatów programu EZMLM w bazie danych MySQL.

Parametry

adres_e-mail

Adres email, który zostanie shaszowany.

Zwracane wartości

Wartość hash'a dla adres_e-mail.

Przykłady

Przykład #1 Obliczenie wartości hash i dodanie nowego użytkownika

<?php

$user = "joecool@example.com";
$hash = ezmlm_hash ($user);
$query = sprintf ("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db->query($query); // wykorzystanie interfejsu PHPLIB db

?>

Mail Funkcje
mail
Mail Funkcje


Wysyłanie poczty elektronicznej

ezmlm_hash
Mailparse
Mail Funkcje
PHP Manual

mail

(PHP 4, PHP 5)

mail — Wysyłanie poczty elektronicznej

Opis

bool mail ( string $do , string $temat , string $treść [, string $dodatkowe_nagłówki [, string $dodatkowe_parametry ]] )

Wysyła e-mail.

Parametry

do

Odbiorca lub odbiorcy e-maila.

Format tego łańcucha musi być zgodny z » RFC 2822. Oto kilka przykładów:

  • osoba@example.com
  • osoba@example.com, imie.nazwisko@example.com
  • Osoba <osoba@example.com>
  • Osoba <osoba@example.com>, Inna osoba <ktokolwiek@example.com>

temat

Temat e-maila.

Uwaga

Temat musi spełniać » RFC 2047.

treść

Treść wiadomości.

Każdy wiersz tekstu powinien być zakończony znakiem końca linii LF (\n). Wiersze nie powinny zawierać więcej niż 70 znaków.

Uwaga

(Tylko dla Windows) Kiedy PHP łaczy się bezpośrednio do serwera SMTP i zostaną znalezione znaki wskazujące na koniec wiadomości (\n.) to zostaną one usunięte, co spowoduje że wiadomość będzie mało czytelna. Aby temu zapobiec, należy dodać dodatkową kropkę.

<?php
$text = str_replace("\n.", "\n..", $text);
?>

dodatkowe_nagłówki (opcjonalnie)

Łańcuchy znaków dodane na końcu nagłówka e-maila.

Parametr jest zazwyczaj wykorzystywany do wstawienia dodatkowych nagłówków (From, Cc, oraz Bcc). Dodatkowe nagłówki rozdziela się za pomocą znaku powrotu karetki i nowego wiersza - CRLF (\r\n).

Informacja:

Każdy e-mail musi zawierać nagłówek From. Można go podawać jako parametr dodatkowe_nagłówki albo ustawić w pliku php.ini.

Wynikiem pominięcia tego nagłówka będzie informacja o błędzie, podobna do tej: Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. W Windows nagłówek From ustawia także Return-Path.

Informacja:

Jeśli wiadomości nie są dostarczane, można spróbować używać tylko znaku LF (\n). Niektóre, gorzej napisane MTA na systemy Unix zamieniają automatycznie LF na CRLF (co powoduje podwojenie CR jeśli zostało użyte CRLF). Powinno się to zrobić w ostateczności, jako że nie jest to zgodne z dokumentem » RFC 2822.

dodatkowe_parametry (opcjonalne)

Parametr dodatkowe_parametry może być użyty do przekazania dodatkowych opcji do programu wysyłającego e-maile. Zostaną one użyte przy wysyłaniu e-maila w ścieżce sendmaila jako ustawienia konfiguracyjne. Mogą one być użyte na przykład do wprowadzenia adresu e-mail nadawcy, tak jakbyśmy użyli polecenia sendmail z opcją -f.

Użytkownik z którego prawami jest uruchomiony serwer WWW powinien być dodany jako zaufany użytkownik w konfiguracji programu sendmail, aby zapobiec dodawania nagłówka 'X-Warning' do wiadomości, kiedy ustawiany jest adres nadawcy (-f). Dla użytkowników programu sendmail jest to plik /etc/mail/trusted-users.

Zwracane wartości

Zwraca TRUE jeśli e-mail został zaakceptowany do wysłania, w przeciwnym przypadku zwraca FALSE.

Ważną informacją jest to, że pomimo iż e-mail został zaakceptowany do wysłania, to NIE oznacza, że będzie on już w tej chwili wysyłany do odbiorców.

Rejestr zmian

Wersja | Opis
4.3.0 (tylko Windows) | Obsługiwane są wszystkie dodatkowe nagłówki (takie jak From, Cc, Bcc i Date) i nie są w nich rozróżniane małe i duże litery. (dodatkowe nagłówki nie były przetwarzane bezpośrednio przez MTA, tylko wcześniej parsowane za pomocą PHP, a PHP < 4.3 obsługiwał tylko nagłówek Cc i rozróżniał małe i duże litery).
4.2.3 | Parametr dodatkowe_parametry jest wyłączony w trybie safe_mode, a funkcja mail() wywołuje stosowny komunikat i zwraca FALSE w czasie próby jego użycia.
4.0.5 | Dodano parametr dodatkowe_parametry.

Przykłady

Przykład #1 Wysłanie e-maila.

Użycie funkcji mail() do wysłania prostej wiadomości:

<?php
// Wiadomość
$message = "Linia 1\nLinia 2\nLinia 3";

// W przypadku każdej linii dłuższej niż 70 znaków powinniśmy użyć funkcji wordwrap()
$message = wordwrap($message, 70);

// Wyślij
mail('osoba@example.com', 'Temat wiadomości', $message);
?>

Przykład #2 Wysłanie e-maila z dodatkowymi nagłówkami.

Dodatkowe, podstawowe nagłówki informują program klienta poczty (MUA) o adresach From i Reply-To:

<?php
$to      = 'osoba@example.com';
$subject = 'temat';
$message = 'witam';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Przykład #3 Wysłanie e-maila z dodatkowym parametrem wiersza poleceń.

Parametr dodatkowe_parametry może być użyty do przekazania dodatkowych opcji do programu wysyłającego e-maile. Zostaną one użyte przy wysyłaniu e-maila w ścieżce sendmaila.

<?php
mail('osoba@example.com', 'temat', 'wiadomość', null,
   '-fwebmaster@example.com');
?>

Przykład #4 Wysłanie e-maila w formacie HTML

Za pomocą mail() możliwe jest wysłanie maila z treścią w formacie HTML.

<?php
// kilku odbiorców
$to  = 'aidan@example.com' . ', '; // zwróćmy uwagę na przecinek
$to .= 'wez@example.com';

// temat
$subject = 'Birthday Reminders for August';

// wiadomość
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';

// Aby wysłać e-mail HTML, musi być ustawiony nagłówek Content-type
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Dodatkowe nagłówki
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";

// Wysłanie e-maila
mail($to, $subject, $message, $headers);
?>

Informacja:

Jeśli mamy zamiar wysyłać HTML albo e-maile o złożonej zawartości, zaleca się użyć pakietu PEAR » PEAR::Mail_Mime.

Notatki

Informacja:

Implementacja funkcji mail() w systemach Windows różni się pod wieloma względami od implementacji na platformach Unix. Po pierwsze, do tworzenia wiadomości funkcja nie używa lokalnych poleceń systemowych, tylko operuje bezpośrednio na gniazdach. To oznacza, że wymagana jest dodatkowa usługa MTA, nasłuchująca na porcie (która może działać na localhost lub maszynie zdalnej).

Po drugie, dodatkowe nagłówki, takie jak From:, Cc:, Bcc: i Date: nie są przetwarzane przez MTA, tylko parsowane za pomocą PHP.

Parametr do nie powinien być adresem w postaci "Osoba <ktokolwiek@example.com>". Polecenie mail może nie parsować tego właściwie, podczas komunikowania się z MTA.

Informacja:

Nie warto używać funkcji mail() do wysyłania dużej ilości e-maili stosując pętle. Ta funkcja otwiera i zamyka gniazdo SMTP dla każdego wysyłanego e-maila, a to jest mało wydajne.

Do wysyłania dużej ilości e-maili można stosować pakiety » PEAR::Mail, i » PEAR::Mail_Queue.

Informacja:

Poniższe dokumenty RFC mogą być pomocne: » RFC 1896, » RFC 2045, » RFC 2046, » RFC 2047, » RFC 2048, » RFC 2049, i » RFC 2822.

Zobacz też:

  • imap_mail() - Send an email message
  • » PEAR::Mail
  • » PEAR::Mail_Mime

ezmlm_hash
Mailparse
Mail Funkcje


Mailparse

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Mailparse Funkcje
    • mailparse_determine_best_xfer_encoding — Gets the best way of encoding
    • mailparse_msg_create — Create a mime mail resource
    • mailparse_msg_extract_part_file — Extracts/decodes a message section
    • mailparse_msg_extract_part — Extracts/decodes a message section
    • mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
    • mailparse_msg_free — Frees a MIME resource
    • mailparse_msg_get_part_data — Returns an associative array of info about the message
    • mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
    • mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
    • mailparse_msg_parse_file — Parses a file
    • mailparse_msg_parse — Incrementally parse data into buffer
    • mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
    • mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
    • mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file
mail
Wstęp
Rozszerzenia powiązane z pocztą elektroniczną


Wstęp

Mailparse is an extension for parsing and working with email messages. It can deal with » RFC 822 and » RFC 2045 (MIME) compliant messages.

Mailparse is stream based, which means that it does not keep in-memory copies of the files it processes - so it is very resource efficient when dealing with large messages.

Informacja:

Mailparse requires the mbstring extension, and mbstring must be loaded before mailparse.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 4.2.0.

Mailparse
Instalacja/Konfiguracja
Mailparse


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Mailparse


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/mailparse.

In order to use these functions you must compile PHP with mailparse support by using the --enable-mailparse configure option.

Windows users will enable php_mailparse.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/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Mailparse configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
mailparse.def_charset | "us-ascii" | PHP_INI_ALL | Available since PHP 4.1.0. Removed in PHP 4.2.0.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

MAILPARSE_EXTRACT_OUTPUT (integer)
MAILPARSE_EXTRACT_STREAM (integer)
MAILPARSE_EXTRACT_RETURN (integer)
Typy zasobów
Mailparse Funkcje
Mailparse


Mailparse Funkcje

Spis treści

  • mailparse_determine_best_xfer_encoding — Gets the best way of encoding
  • mailparse_msg_create — Create a mime mail resource
  • mailparse_msg_extract_part_file — Extracts/decodes a message section
  • mailparse_msg_extract_part — Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
  • mailparse_msg_free — Frees a MIME resource
  • mailparse_msg_get_part_data — Returns an associative array of info about the message
  • mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
  • mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
  • mailparse_msg_parse_file — Parses a file
  • mailparse_msg_parse — Incrementally parse data into buffer
  • mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
  • mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp
  • mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file
Stałe predefiniowane
mailparse_determine_best_xfer_encoding
Mailparse


Gets the best way of encoding

Mailparse Funkcje
mailparse_msg_create
Mailparse Funkcje
PHP Manual

mailparse_determine_best_xfer_encoding

(PECL mailparse >= 0.9.0)

mailparse_determine_best_xfer_encoding — Gets the best way of encoding

Opis

string mailparse_determine_best_xfer_encoding ( resource $fp )

Figures out the best way of encoding the content read from the given file pointer.

Parametry

fp

A valid file pointer, which must be seek-able.

Zwracane wartości

Returns one of the character encodings supported by the mbstring module.

Przykłady

Przykład #1 mailparse_determine_best_xfer_encoding() example

<?php

$fp = fopen('somemail.eml', 'r');
echo 'Best encoding: ' . mailparse_determine_best_xfer_encoding($fp);

?>

Powyższy przykład wyświetli coś podobnego do:

Best encoding: 7bit

Mailparse Funkcje
mailparse_msg_create
Mailparse Funkcje


Create a mime mail resource

mailparse_determine_best_xfer_encoding
mailparse_msg_extract_part_file
Mailparse Funkcje
PHP Manual

mailparse_msg_create

(PECL mailparse >= 0.9.0)

mailparse_msg_create — Create a mime mail resource

Opis

resource mailparse_msg_create ( void )

Create a MIME mail resource.

Zwracane wartości

Returns a handle that can be used to parse a message.

Zobacz też:

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_parse_file() - Parses a file

mailparse_determine_best_xfer_encoding
mailparse_msg_extract_part_file
Mailparse Funkcje


Extracts/decodes a message section

mailparse_msg_create
mailparse_msg_extract_part
Mailparse Funkcje
PHP Manual

mailparse_msg_extract_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part_file — Extracts/decodes a message section

Opis

string mailparse_msg_extract_part_file ( resource $mimemail , mixed $filename [, callback $callbackfunc ] )

Extracts/decodes a message section from the supplied filename.

The contents of the section will be decoded according to their transfer encoding - base64, quoted-printable and uuencoded text are supported.

Parametry

mimemail

A valid MIME resource, created with mailparse_msg_create().

filename

Can be a file name or a valid stream resource.

callbackfunc

If set, this must be either a valid callback that will be passed the extracted section, or NULL to make this function return the extracted section.

If not specified, the contents will be sent to "stdout".

Zwracane wartości

If callbackfunc is not NULL returns TRUE on success.

If callbackfunc is set to NULL, returns the extracted section as a string.

Returns FALSE on error.

Zobacz też:

  • mailparse_msg_extract_part() - Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_create
mailparse_msg_extract_part
Mailparse Funkcje


Extracts/decodes a message section

mailparse_msg_extract_part_file
mailparse_msg_extract_whole_part_file
Mailparse Funkcje
PHP Manual

mailparse_msg_extract_part

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part — Extracts/decodes a message section

Opis

void mailparse_msg_extract_part ( resource $mimemail , string $msgbody [, callback $callbackfunc ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

mimemail

A valid MIME resource.

msgbody

callbackfunc

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • mailparse_msg_extract_part_file() - Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_extract_part_file
mailparse_msg_extract_whole_part_file
Mailparse Funkcje


Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_extract_part
mailparse_msg_free
Mailparse Funkcje
PHP Manual

mailparse_msg_extract_whole_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding

Opis

string mailparse_msg_extract_whole_part_file ( resource $mimemail , string $filename [, callback $callbackfunc ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

mimemail

A valid MIME resource.

filename

callbackfunc

Zwracane wartości

Zobacz też:

  • mailparse_msg_extract_part() - Extracts/decodes a message section
  • mailparse_msg_extract_part_file() - Extracts/decodes a message section

mailparse_msg_extract_part
mailparse_msg_free
Mailparse Funkcje


Frees a MIME resource

mailparse_msg_extract_whole_part_file
mailparse_msg_get_part_data
Mailparse Funkcje
PHP Manual

mailparse_msg_free

(PECL mailparse >= 0.9.0)

mailparse_msg_free — Frees a MIME resource

Opis

bool mailparse_msg_free ( resource $mimemail )

Frees a MIME resource.

Parametry

mimemail

A valid MIME resource allocated by mailparse_msg_create() or mailparse_msg_parse_file().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • mailparse_msg_create() - Create a mime mail resource
  • mailparse_msg_parse_file() - Parses a file

mailparse_msg_extract_whole_part_file
mailparse_msg_get_part_data
Mailparse Funkcje


Returns an associative array of info about the message

mailparse_msg_free
mailparse_msg_get_part
Mailparse Funkcje
PHP Manual

mailparse_msg_get_part_data

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part_data — Returns an associative array of info about the message

Opis

array mailparse_msg_get_part_data ( resource $mimemail )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

mimemail

A valid MIME resource.

mailparse_msg_free
mailparse_msg_get_part
Mailparse Funkcje


Returns a handle on a given section in a mimemessage

mailparse_msg_get_part_data
mailparse_msg_get_structure
Mailparse Funkcje
PHP Manual

mailparse_msg_get_part

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part — Returns a handle on a given section in a mimemessage

Opis

resource mailparse_msg_get_part ( resource $mimemail , string $mimesection )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

mimemail

A valid MIME resource.

mimesection

mailparse_msg_get_part_data
mailparse_msg_get_structure
Mailparse Funkcje


Returns an array of mime section names in the supplied message

mailparse_msg_get_part
mailparse_msg_parse_file
Mailparse Funkcje
PHP Manual

mailparse_msg_get_structure

(PECL mailparse >= 0.9.0)

mailparse_msg_get_structure — Returns an array of mime section names in the supplied message

Opis

array mailparse_msg_get_structure ( resource $mimemail )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

mimemail

A valid MIME resource.

mailparse_msg_get_part
mailparse_msg_parse_file
Mailparse Funkcje


Parses a file

mailparse_msg_get_structure
mailparse_msg_parse
Mailparse Funkcje
PHP Manual

mailparse_msg_parse_file

(PECL mailparse >= 0.9.0)

mailparse_msg_parse_file — Parses a file

Opis

resource mailparse_msg_parse_file ( string $filename )

Parses a file. This is the optimal way of parsing a mail file that you have on disk.

Parametry

filename

Path to the file holding the message. The file is opened and streamed through the parser.

Zwracane wartości

Returns a MIME resource representing the structure, or FALSE on error.

Zobacz też:

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_create() - Create a mime mail resource

mailparse_msg_get_structure
mailparse_msg_parse
Mailparse Funkcje


Incrementally parse data into buffer

mailparse_msg_parse_file
mailparse_rfc822_parse_addresses
Mailparse Funkcje
PHP Manual

mailparse_msg_parse

(PECL mailparse >= 0.9.0)

mailparse_msg_parse — Incrementally parse data into buffer

Opis

bool mailparse_msg_parse ( resource $mimemail , string $data )

Incrementally parse data into the supplied mime mail resource.

This function allow you to stream portions of a file at a time, rather than read and parse the whole thing.

Parametry

mimemail

A valid MIME resource.

data

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

mailparse_msg_parse_file
mailparse_rfc822_parse_addresses
Mailparse Funkcje


Parse RFC 822 compliant addresses

mailparse_msg_parse
mailparse_stream_encode
Mailparse Funkcje
PHP Manual

mailparse_rfc822_parse_addresses

(PECL mailparse >= 0.9.0)

mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses

Opis

array mailparse_rfc822_parse_addresses ( string $addresses )

Parses a » RFC 822 compliant recipient list, such as that found in the To: header.

Parametry

addresses

A string containing addresses, like in: Wez Furlong <wez@example.com>, doe@example.com

Informacja:

This string must not include the header name.

Zwracane wartości

Returns an array of associative arrays with the following keys for each recipient:

display | The recipient name, for display purpose. If this part is not set for a recipient, this key will hold the same value as address.
address | The email address
is_group | TRUE if the recipient is a newsgroup, FALSE otherwise.

Przykłady

Przykład #1 mailparse_rfc822_parse_addresses() example

<?php

$to = 'Wez Furlong <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));

?>

Powyższy przykład wyświetli:

array(2) {
  [0]=>
  array(3) {
    ["display"]=>
    string(11) "Wez Furlong"
    ["address"]=>
    string(15) "wez@example.com"
    ["is_group"]=>
    bool(false)
  }
  [1]=>
  array(3) {
    ["display"]=>
    string(15) "doe@example.com"
    ["address"]=>
    string(15) "doe@example.com"
    ["is_group"]=>
    bool(false)
  }
}

mailparse_msg_parse
mailparse_stream_encode
Mailparse Funkcje


Streams data from source file pointer, apply encoding and write to destfp

mailparse_rfc822_parse_addresses
mailparse_uudecode_all
Mailparse Funkcje
PHP Manual

mailparse_stream_encode

(PECL mailparse >= 0.9.0)

mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp

Opis

bool mailparse_stream_encode ( resource $sourcefp , resource $destfp , string $encoding )

Streams data from the source file pointer, apply encoding and write to the destination file pointer.

Parametry

sourcefp

A valid file handle. The file is streamed through the parser.

destfp

The destination file handle in which the encoded data will be written.

encoding

One of the character encodings supported by the mbstring module.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 mailparse_stream_encode() example

<?php

// email.eml contents: hello, this is some text=hello.
$fp = fopen('email.eml', 'r');

$dest = tmpfile();

mailparse_stream_encode($fp, $dest, "quoted-printable");

rewind($dest);

// Display new file contents
fpassthru($dest);

?>

Powyższy przykład wyświetli:

hello, this is some text=3Dhello.

mailparse_rfc822_parse_addresses
mailparse_uudecode_all
Mailparse Funkcje


Scans the data from fp and extract each embedded uuencoded file

mailparse_stream_encode
vpopmail
Mailparse Funkcje
PHP Manual

mailparse_uudecode_all

(PECL mailparse >= 0.9.0)

mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

Opis

array mailparse_uudecode_all ( resource $fp )

Scans the data from the given file pointer and extract each embedded uuencoded file into a temporary file.

Parametry

fp

A valid file pointer.

Zwracane wartości

Returns an array of associative arrays listing filename information.

filename | Path to the temporary file name created
origfilename | The original filename, for uuencoded parts only
The first filename entry is the message body. The next entries are the decoded uuencoded files.

Przykłady

Przykład #1 mailparse_uudecode_all() example

<?php

$text = <<<EOD
To: fred@example.com

hello, this is some text hello.
blah blah blah.

begin 644 test.txt
/=&AI<R!I<R!A('1E<W0*
`
end

EOD;

$fp = tmpfile();
fwrite($fp, $text);

$data = mailparse_uudecode_all($fp);

echo "BODY\n";
readfile($data[0]["filename"]);
echo "UUE ({$data[1]['origfilename']})\n";
readfile($data[1]["filename"]);

// Clean up
unlink($data[0]["filename"]);
unlink($data[1]["filename"]);

?>

Powyższy przykład wyświetli:

BODY
To: fred@example.com

hello, this is some text hello.
blah blah blah.

UUE (test.txt)
this is a test

mailparse_stream_encode
vpopmail
Mailparse Funkcje


vpopmail

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje vpopmail
    • vpopmail_add_alias_domain_ex — Dodaje alias do rzeczywistej domeny wirtualnej
    • vpopmail_add_alias_domain — Dodaje alias do domeny wirtualnej
    • vpopmail_add_domain_ex — Dodaje nową rzeczywistą domenę wirtualną
    • vpopmail_add_domain — Dodaje nową domenę wirtualną
    • vpopmail_add_user — Dodaje nowego użytkownika do podanej domeny wirtualnej
    • vpopmail_alias_add — Dodaje nowy alias do konta użytkownika
    • vpopmail_alias_del_domain — Usuwa wszystkie wirtualne aliasy domeny
    • vpopmail_alias_del — Usuwa wszystkie wirtualne aliasy użytkownika
    • vpopmail_alias_get_all — Zwraca tablicę z informacjami o aliasach dla domeny
    • vpopmail_alias_get — Zwraca tablicę z informacjami o aliasie dla domeny
    • vpopmail_auth_user — Sprawdza poprawność danych użytkownik/domena/hasło
    • vpopmail_del_domain_ex — Usuwa rzeczywistą domenę wirtualną
    • vpopmail_del_domain — Usuwa domenę wirtualną
    • vpopmail_del_user — Usuwa użytkownika z domeny wirtualnej
    • vpopmail_error — Pobiera komunikat tekstowy o ostatnim błędzie vpopmail
    • vpopmail_passwd — Zmienia hasło wirtualnego użytkownika
    • vpopmail_set_user_quota — Ustawia udział dyskowy dla wirtualnego użytkownika
mailparse_uudecode_all
Wstęp
Rozszerzenia powiązane z pocztą elektroniczną


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.

Od wersji PHP 4.3.0 rozszerzenie vpopmail znajduje się w repozytorium » PECL.

vpopmail
Instalacja/Konfiguracja
vpopmail


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
vpopmail


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/vpopmail.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Funkcje vpopmail
vpopmail


Funkcje vpopmail

Spis treści

  • vpopmail_add_alias_domain_ex — Dodaje alias do rzeczywistej domeny wirtualnej
  • vpopmail_add_alias_domain — Dodaje alias do domeny wirtualnej
  • vpopmail_add_domain_ex — Dodaje nową rzeczywistą domenę wirtualną
  • vpopmail_add_domain — Dodaje nową domenę wirtualną
  • vpopmail_add_user — Dodaje nowego użytkownika do podanej domeny wirtualnej
  • vpopmail_alias_add — Dodaje nowy alias do konta użytkownika
  • vpopmail_alias_del_domain — Usuwa wszystkie wirtualne aliasy domeny
  • vpopmail_alias_del — Usuwa wszystkie wirtualne aliasy użytkownika
  • vpopmail_alias_get_all — Zwraca tablicę z informacjami o aliasach dla domeny
  • vpopmail_alias_get — Zwraca tablicę z informacjami o aliasie dla domeny
  • vpopmail_auth_user — Sprawdza poprawność danych użytkownik/domena/hasło
  • vpopmail_del_domain_ex — Usuwa rzeczywistą domenę wirtualną
  • vpopmail_del_domain — Usuwa domenę wirtualną
  • vpopmail_del_user — Usuwa użytkownika z domeny wirtualnej
  • vpopmail_error — Pobiera komunikat tekstowy o ostatnim błędzie vpopmail
  • vpopmail_passwd — Zmienia hasło wirtualnego użytkownika
  • vpopmail_set_user_quota — Ustawia udział dyskowy dla wirtualnego użytkownika
Stałe predefiniowane
vpopmail_add_alias_domain_ex
vpopmail


Dodaje alias do rzeczywistej domeny wirtualnej

Funkcje vpopmail
vpopmail_add_alias_domain
Funkcje vpopmail
PHP Manual

vpopmail_add_alias_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_alias_domain_ex — Dodaje alias do rzeczywistej domeny wirtualnej

Opis

bool vpopmail_add_alias_domain_ex ( string $istniejąca_domena , string $nowa_domena )
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.

Funkcje vpopmail
vpopmail_add_alias_domain
Funkcje vpopmail


Dodaje alias do domeny wirtualnej

vpopmail_add_alias_domain_ex
vpopmail_add_domain_ex
Funkcje vpopmail
PHP Manual

vpopmail_add_alias_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_alias_domain — Dodaje alias do domeny wirtualnej

Opis

bool vpopmail_add_alias_domain ( string $domena , string $alias_domeny )
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.

vpopmail_add_alias_domain_ex
vpopmail_add_domain_ex
Funkcje vpopmail


Dodaje nową rzeczywistą domenę wirtualną

vpopmail_add_alias_domain
vpopmail_add_domain
Funkcje vpopmail
PHP Manual

vpopmail_add_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_domain_ex — Dodaje nową rzeczywistą domenę wirtualną

Opis

bool vpopmail_add_domain_ex ( string $domena , string $hasło [, string $udział_dyskowy [, string $odbijanie_nieprawidłowej_poczty_do_nadawcy [, bool $apop ]]] )
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.

vpopmail_add_alias_domain
vpopmail_add_domain
Funkcje vpopmail


Dodaje nową domenę wirtualną

vpopmail_add_domain_ex
vpopmail_add_user
Funkcje vpopmail
PHP Manual

vpopmail_add_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_domain — Dodaje nową domenę wirtualną

Opis

bool vpopmail_add_domain ( string $domena , string $katalog , int $id_użytkownika , int $id_grupy )
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.

vpopmail_add_domain_ex
vpopmail_add_user
Funkcje vpopmail


Dodaje nowego użytkownika do podanej domeny wirtualnej

vpopmail_add_domain
vpopmail_alias_add
Funkcje vpopmail
PHP Manual

vpopmail_add_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_user — Dodaje nowego użytkownika do podanej domeny wirtualnej

Opis

bool vpopmail_add_user ( string $użytkownik , string $domena , string $hasło [, string $komentarz [, bool $apop ]] )
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.

vpopmail_add_domain
vpopmail_alias_add
Funkcje vpopmail


Dodaje nowy alias do konta użytkownika

vpopmail_add_user
vpopmail_alias_del_domain
Funkcje vpopmail
PHP Manual

vpopmail_alias_add

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_add — Dodaje nowy alias do konta użytkownika

Opis

bool vpopmail_alias_add ( string $użytkownik , string $domena , string $alias )
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.

vpopmail_add_user
vpopmail_alias_del_domain
Funkcje vpopmail


Usuwa wszystkie wirtualne aliasy domeny

vpopmail_alias_add
vpopmail_alias_del
Funkcje vpopmail
PHP Manual

vpopmail_alias_del_domain

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_del_domain — Usuwa wszystkie wirtualne aliasy domeny

Opis

bool vpopmail_alias_del_domain ( string $domena )
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.

vpopmail_alias_add
vpopmail_alias_del
Funkcje vpopmail


Usuwa wszystkie wirtualne aliasy użytkownika

vpopmail_alias_del_domain
vpopmail_alias_get_all
Funkcje vpopmail
PHP Manual

vpopmail_alias_del

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_del — Usuwa wszystkie wirtualne aliasy użytkownika

Opis

bool vpopmail_alias_del ( string $użytkownik , string $domena )
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.

vpopmail_alias_del_domain
vpopmail_alias_get_all
Funkcje vpopmail


Zwraca tablicę z informacjami o aliasach dla domeny

vpopmail_alias_del
vpopmail_alias_get
Funkcje vpopmail
PHP Manual

vpopmail_alias_get_all

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_get_all — Zwraca tablicę z informacjami o aliasach dla domeny

Opis

array vpopmail_alias_get_all ( string $domena )
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.

vpopmail_alias_del
vpopmail_alias_get
Funkcje vpopmail


Zwraca tablicę z informacjami o aliasie dla domeny

vpopmail_alias_get_all
vpopmail_auth_user
Funkcje vpopmail
PHP Manual

vpopmail_alias_get

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_get — Zwraca tablicę z informacjami o aliasie dla domeny

Opis

array vpopmail_alias_get ( string $alias , string $domena )
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.

vpopmail_alias_get_all
vpopmail_auth_user
Funkcje vpopmail


Sprawdza poprawność danych użytkownik/domena/hasło

vpopmail_alias_get
vpopmail_del_domain_ex
Funkcje vpopmail
PHP Manual

vpopmail_auth_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_auth_user — Sprawdza poprawność danych użytkownik/domena/hasło

Opis

bool vpopmail_auth_user ( string $użytkownik , string $domena , string $hasło [, string $apop ] )
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.

vpopmail_alias_get
vpopmail_del_domain_ex
Funkcje vpopmail


Usuwa rzeczywistą domenę wirtualną

vpopmail_auth_user
vpopmail_del_domain
Funkcje vpopmail
PHP Manual

vpopmail_del_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain_ex — Usuwa rzeczywistą domenę wirtualną

Opis

bool vpopmail_del_domain_ex ( string $domena )
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.

vpopmail_auth_user
vpopmail_del_domain
Funkcje vpopmail


Usuwa domenę wirtualną

vpopmail_del_domain_ex
vpopmail_del_user
Funkcje vpopmail
PHP Manual

vpopmail_del_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain — Usuwa domenę wirtualną

Opis

bool vpopmail_del_domain ( string $domena )
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.

vpopmail_del_domain_ex
vpopmail_del_user
Funkcje vpopmail


Usuwa użytkownika z domeny wirtualnej

vpopmail_del_domain
vpopmail_error
Funkcje vpopmail
PHP Manual

vpopmail_del_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_user — Usuwa użytkownika z domeny wirtualnej

Opis

bool vpopmail_del_user ( string $użytkownik , string $domena )
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.

vpopmail_del_domain
vpopmail_error
Funkcje vpopmail


Pobiera komunikat tekstowy o ostatnim błędzie vpopmail

vpopmail_del_user
vpopmail_passwd
Funkcje vpopmail
PHP Manual

vpopmail_error

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_error — Pobiera komunikat tekstowy o ostatnim błędzie vpopmail

Opis

string vpopmail_error ( 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.

vpopmail_del_user
vpopmail_passwd
Funkcje vpopmail


Zmienia hasło wirtualnego użytkownika

vpopmail_error
vpopmail_set_user_quota
Funkcje vpopmail
PHP Manual

vpopmail_passwd

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_passwd — Zmienia hasło wirtualnego użytkownika

Opis

bool vpopmail_passwd ( string $użytkownik , string $domena , string $hasło [, bool $apop ] )
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.

vpopmail_error
vpopmail_set_user_quota
Funkcje vpopmail


Ustawia udział dyskowy dla wirtualnego użytkownika

vpopmail_passwd
Rozszerzenia matematyczne
Funkcje vpopmail
PHP Manual

vpopmail_set_user_quota

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_set_user_quota — Ustawia udział dyskowy dla wirtualnego użytkownika

Opis

bool vpopmail_set_user_quota ( string $użytkownik , string $domena , string $udział_dyskowy )
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.

vpopmail_passwd
Rozszerzenia matematyczne
Funkcje vpopmail


Rozszerzenia matematyczne

  • BC Math — BCMath - arytmetyka liczb dużej precyzji
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje BC Math
  • GMP — GNU Multiple Precision
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • GMP Funkcje
  • Math — Mathematical Functions
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Math Funkcje
  • Statistics
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Statistic Funkcje
vpopmail_set_user_quota
BC Math
Opis funkcji


BCMath - arytmetyka liczb dużej precyzji

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje BC Math
    • bcadd — Dodaje dwie liczby o dużej precyzji
    • bccomp — Porównuje dwie liczby o dużej precyzji
    • bcdiv — Dzieli dwie liczby o dużej precyzji
    • bcmod — Dzieli w module liczbę o dużej precyzji
    • bcmul — Mnoży dwie liczby o dużej precyzji
    • bcpow — Podnosi liczbę o dużej precyzji do potęgi
    • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale — Ustala domyślną precyzję obliczeń BCMath
    • bcsqrt — Wyciąga pierwiastek kwadratowy z liczby o dużej precyzji
    • bcsub — Odejmuje jedną liczbę o dużej precyzji od drugiej
Rozszerzenia matematyczne
Wstęp
Rozszerzenia matematyczne


Wstęp

Dla potrzeb obliczeń arytmetycznych o dużej precyzji, PHP oferuje Kalkulator Binarny, który operuje na liczbach dowolnej wielkości i precyzji, zapisanych jako typ string.

BC Math
Instalacja/Konfiguracja
BC Math


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
BC Math


Wymagania

Począwszy od PHP 4.0.4, biblioteka libbcmath jest dostarczana razem z PHP. To rozszerzenie nie wymaga zatem żadnych zewnętrznych bibliotek.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Te funkcje są dostępne, jeśli PHP został skompilowany z opcją --enable-bcmath .

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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracyjne BC math
Nazwa | Domyślna wartość | Możliwość zmian | Rejestr zmian
bcmath.scale | "0" | 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.

bcmath.scale integer

Liczba miejsc po przecinku określana dla wszystkich funkcji bcmath. Patrz także: bcscale().

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Funkcje BC Math
BC Math


Funkcje BC Math

Spis treści

  • bcadd — Dodaje dwie liczby o dużej precyzji
  • bccomp — Porównuje dwie liczby o dużej precyzji
  • bcdiv — Dzieli dwie liczby o dużej precyzji
  • bcmod — Dzieli w module liczbę o dużej precyzji
  • bcmul — Mnoży dwie liczby o dużej precyzji
  • bcpow — Podnosi liczbę o dużej precyzji do potęgi
  • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcscale — Ustala domyślną precyzję obliczeń BCMath
  • bcsqrt — Wyciąga pierwiastek kwadratowy z liczby o dużej precyzji
  • bcsub — Odejmuje jedną liczbę o dużej precyzji od drugiej
Stałe predefiniowane
bcadd
BC Math


Dodaje dwie liczby o dużej precyzji

Funkcje BC Math
bccomp
Funkcje BC Math
PHP Manual

bcadd

(PHP 4, PHP 5)

bcadd — Dodaje dwie liczby o dużej precyzji

Opis

string bcadd ( string $lewy_operand , string $prawy_operand [, int $precyzja ] )

Dodaje lewy_operand do prawy_operand i zwraca ich sumę jako ciąg znaków. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Przykłady

Przykład #1 bcadd() przykład

<?php

$a = '1.234';
$b = '5';

echo bcadd($a, $b);     // 6
echo bcadd($a, $b, 4);  // 6.2340

?>

Zobacz też:

bcsub().

Funkcje BC Math
bccomp
Funkcje BC Math


Porównuje dwie liczby o dużej precyzji

bcadd
bcdiv
Funkcje BC Math
PHP Manual

bccomp

(PHP 4, PHP 5)

bccomp — Porównuje dwie liczby o dużej precyzji

Opis

int bccomp ( string $lewy_operand , string $prawy_operand [, int $precyzja ] )

Porównuje lewy_operand z prawy_operand i zwraca rezultat w postaci liczby całkowitej. Opcjonalnego argumentu precyzja używa się do ustalenia ilości cyfr po przecinku, które będą wzięte pod uwagę przy porównywaniu. Funkcja zwraca wartość 0, jeśli operandy są sobie równe. Jeśli lewy_operand jest większy niż prawy_operand, to funkcja zwraca +1, zaś jeśli lewy_operand jest mniejszy niż prawy_operand, to funkcja zwraca -1.

Przykłady

Przykład #1 bccomp() przykład

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>
bcadd
bcdiv
Funkcje BC Math


Dzieli dwie liczby o dużej precyzji

bccomp
bcmod
Funkcje BC Math
PHP Manual

bcdiv

(PHP 4, PHP 5)

bcdiv — Dzieli dwie liczby o dużej precyzji

Opis

string bcdiv ( string $lewy_operand , string $prawy_operand [, int $precyzja ] )

Dzieli lewy_operand przez prawy_operand i zwraca wynik. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku, które domyślnie wynosi 0.

Przykłady

Przykład #1 bcdiv() przykład

<?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?>

Zobacz też:

bcmul().

bccomp
bcmod
Funkcje BC Math


Dzieli w module liczbę o dużej precyzji

bcdiv
bcmul
Funkcje BC Math
PHP Manual

bcmod

(PHP 4, PHP 5)

bcmod — Dzieli w module liczbę o dużej precyzji

Opis

string bcmod ( string $lewy_operand , string $moduł )

Zwraca moduł (resztę z dzielenia) z liczby lewy_operand dzielonej przez moduł.

Przykłady

Przykład #1 bcmod() przykład

<?php
echo bcmod('4', '2'); // 0
echo bcmod('2', '4'); // 2
?>

Zobacz też:

bcdiv().

bcdiv
bcmul
Funkcje BC Math


Mnoży dwie liczby o dużej precyzji

bcmod
bcpow
Funkcje BC Math
PHP Manual

bcmul

(PHP 4, PHP 5)

bcmul — Mnoży dwie liczby o dużej precyzji

Opis

string bcmul ( string $lewy_operand , string $prawy_operand [, int $precyzja ] )

Mnoży lewy_operand przez prawy_operand i zwraca wynik. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku (poprzez ucięcie).

Przykłady

Przykład #1 bcmul() przykład

<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>

Zobacz też:

bcdiv().

bcmod
bcpow
Funkcje BC Math


Podnosi liczbę o dużej precyzji do potęgi

bcmul
bcpowmod
Funkcje BC Math
PHP Manual

bcpow

(PHP 4, PHP 5)

bcpow — Podnosi liczbę o dużej precyzji do potęgi

Opis

string bcpow ( string $x , string $y [, int $precyzja ] )

Podnosi liczbę x do potęgi y. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Przykłady

Przykład #1 bcpow() przykład

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

Zobacz też:

bcpowmod() i bcsqrt().

bcmul
bcpowmod
Funkcje BC Math


Raise an arbitrary precision number to another, reduced by a specified modulus

bcpow
bcscale
Funkcje BC Math
PHP Manual

bcpowmod

(PHP 5)

bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus

Opis

string bcpowmod ( string $left_operand , string $right_operand , string $modulus [, int $scale ] )

Use the fast-exponentiation method to raise left_operand to the power right_operand with respect to the modulus modulus.

Parametry

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

modulus

The modulus, as a string.

skala

Ten opcjonalny parametr służy do ustawienia liczby cyfr po kropce w wyniku. Możesz także ustawić globalnie domyślną skalę dla wszystkich funkcji używając bcscale().

Zwracane wartości

Returns the result as a string, or NULL if modulus is 0.

Notatki

Informacja:

Because this method uses the modulus operation, numbers which are not positive integers may give unexpected results.

Przykłady

The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.

<?php
$a = bcpowmod($x, $y, $mod);

$b = bcmod(bcpow($x, $y), $mod);

// $a and $b are equal to each other.

?>

Zobacz też:

  • bcpow() - Podnosi liczbę o dużej precyzji do potęgi
  • bcmod() - Dzieli w module liczbę o dużej precyzji

bcpow
bcscale
Funkcje BC Math


Ustala domyślną precyzję obliczeń BCMath

bcpowmod
bcsqrt
Funkcje BC Math
PHP Manual

bcscale

(PHP 4, PHP 5)

bcscale — Ustala domyślną precyzję obliczeń BCMath

Opis

bool bcscale ( int $precyzja )

Za pomocą tej funkcji ustala się domyślną wartość argumentu precyzja dla wszystkich wywołań funkcji BCMath, w których argument ten nie jest jawnie podany. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bcscale() przykład

<?php

// domyślna precyzja : 3
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007

// to jest to samo bez bcscale()
echo bcdiv('105', '6.55957', 3); // 16.007

?>
bcpowmod
bcsqrt
Funkcje BC Math


Wyciąga pierwiastek kwadratowy z liczby o dużej precyzji

bcscale
bcsub
Funkcje BC Math
PHP Manual

bcsqrt

(PHP 4, PHP 5)

bcsqrt — Wyciąga pierwiastek kwadratowy z liczby o dużej precyzji

Opis

string bcsqrt ( string $operand [, int $precyzja ] )

Zwraca pierwiastek kwadratowy z liczby operand. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Przykłady

Przykład #1 bcsqrt() przykład

<?php

echo bcsqrt('2', 3); // 1.414

?>

Zobacz też:

bcpow().

bcscale
bcsub
Funkcje BC Math


Odejmuje jedną liczbę o dużej precyzji od drugiej

bcsqrt
GMP
Funkcje BC Math
PHP Manual

bcsub

(PHP 4, PHP 5)

bcsub — Odejmuje jedną liczbę o dużej precyzji od drugiej

Opis

string bcsub ( string $lewy_operand , string $prawy_operand [, int $precyzja ] )

Odejmuje prawy_operand od lewy_operand i zwraca wynik jako ciąg znaków. Opcjonalnego argumentu precyzja używa się do określenia ilości miejsc po przecinku dziesiętnym w wyniku.

Przykłady

Przykład #1 bcsub() przykład

<?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>

Zobacz też:

bcadd().

bcsqrt
GMP
Funkcje BC Math


GNU Multiple Precision

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • GMP Funkcje
    • gmp_abs — Absolute value
    • gmp_add — Add numbers
    • gmp_and — Bitwise AND
    • gmp_clrbit — Clear bit
    • gmp_cmp — Compare numbers
    • gmp_com — Calculates one's complement
    • gmp_div_q — Divide numbers
    • gmp_div_qr — Divide numbers and get quotient and remainder
    • gmp_div_r — Remainder of the division of numbers
    • gmp_div — Alias dla gmp_div_q
    • gmp_divexact — Exact division of numbers
    • gmp_fact — Factorial
    • gmp_gcd — Calculate GCD
    • gmp_gcdext — Calculate GCD and multipliers
    • gmp_hamdist — Hamming distance
    • gmp_init — Create GMP number
    • gmp_intval — Convert GMP number to integer
    • gmp_invert — Inverse by modulo
    • gmp_jacobi — Jacobi symbol
    • gmp_legendre — Legendre symbol
    • gmp_mod — Modulo operation
    • gmp_mul — Multiply numbers
    • gmp_neg — Negate number
    • gmp_nextprime — Find next prime number
    • gmp_or — Bitwise OR
    • gmp_perfect_square — Perfect square check
    • gmp_popcount — Population count
    • gmp_pow — Raise number into power
    • gmp_powm — Raise number into power with modulo
    • gmp_prob_prime — Check if number is "probably prime"
    • gmp_random — Random number
    • gmp_scan0 — Scan for 0
    • gmp_scan1 — Scan for 1
    • gmp_setbit — Set bit
    • gmp_sign — Sign of number
    • gmp_sqrt — Calculate square root
    • gmp_sqrtrem — Square root with remainder
    • gmp_strval — Convert GMP number to string
    • gmp_sub — Subtract numbers
    • gmp_testbit — Tests if a bit is set
    • gmp_xor — Bitwise XOR
bcsub
Wstęp
Rozszerzenia matematyczne


Wstęp

These functions allow you to work with arbitrary-length integers using the GNU MP library.

These functions have been added in PHP 4.0.4.

Informacja:

Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.

Ostrzeżenie

If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.

Informacja: This extension is available on Windows platforms since PHP 5.1.0.

GMP
Instalacja/Konfiguracja
GMP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
GMP


Wymagania

You can download the GMP library from » http://gmplib.org/#DOWNLOAD. This site also has the GMP manual available.

You will need GMP version 2 or better to use these functions. Some functions may require more recent version of the GMP library.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

Most GPM functions operate on or return GMP number resources.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

GMP_ROUND_ZERO (integer)
GMP_ROUND_PLUSINF (integer)
GMP_ROUND_MINUSINF (integer)
GMP_VERSION (string)
The GMP library version
Typy zasobów
Przykłady
GMP


Przykłady

Przykład #1 Factorial function using GMP

<?php
function fact($x)
{
    $return = 1;
    for ($i=2; $i < $x; $i++) {
        $return = gmp_mul($return, $i);
    }
    return $return;
}

echo gmp_strval(fact(1000)) . "\n";
?>

This will calculate factorial of 1000 (pretty big number) very fast.

Stałe predefiniowane
GMP Funkcje
GMP


GMP Funkcje

Zobacz też:

More mathematical functions can be found in the Rozszerzenia matematyczne section

Spis treści

  • gmp_abs — Absolute value
  • gmp_add — Add numbers
  • gmp_and — Bitwise AND
  • gmp_clrbit — Clear bit
  • gmp_cmp — Compare numbers
  • gmp_com — Calculates one's complement
  • gmp_div_q — Divide numbers
  • gmp_div_qr — Divide numbers and get quotient and remainder
  • gmp_div_r — Remainder of the division of numbers
  • gmp_div — Alias dla gmp_div_q
  • gmp_divexact — Exact division of numbers
  • gmp_fact — Factorial
  • gmp_gcd — Calculate GCD
  • gmp_gcdext — Calculate GCD and multipliers
  • gmp_hamdist — Hamming distance
  • gmp_init — Create GMP number
  • gmp_intval — Convert GMP number to integer
  • gmp_invert — Inverse by modulo
  • gmp_jacobi — Jacobi symbol
  • gmp_legendre — Legendre symbol
  • gmp_mod — Modulo operation
  • gmp_mul — Multiply numbers
  • gmp_neg — Negate number
  • gmp_nextprime — Find next prime number
  • gmp_or — Bitwise OR
  • gmp_perfect_square — Perfect square check
  • gmp_popcount — Population count
  • gmp_pow — Raise number into power
  • gmp_powm — Raise number into power with modulo
  • gmp_prob_prime — Check if number is "probably prime"
  • gmp_random — Random number
  • gmp_scan0 — Scan for 0
  • gmp_scan1 — Scan for 1
  • gmp_setbit — Set bit
  • gmp_sign — Sign of number
  • gmp_sqrt — Calculate square root
  • gmp_sqrtrem — Square root with remainder
  • gmp_strval — Convert GMP number to string
  • gmp_sub — Subtract numbers
  • gmp_testbit — Tests if a bit is set
  • gmp_xor — Bitwise XOR
Przykłady
gmp_abs
GMP


Absolute value

GMP Funkcje
gmp_add
GMP Funkcje
PHP Manual

gmp_abs

(PHP 4 >= 4.0.4, PHP 5)

gmp_abs — Absolute value

Opis

resource gmp_abs ( resource $a )

Get the absolute value of a number.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Returns the absolute value of a, as a GMP number.

Przykłady

Przykład #1 gmp_abs() example

<?php
$abs1 = gmp_abs("274982683358");
$abs2 = gmp_abs("-274982683358");

echo gmp_strval($abs1) . "\n";
echo gmp_strval($abs2) . "\n";
?>

Powyższy przykład wyświetli:

274982683358
274982683358

GMP Funkcje
gmp_add
GMP Funkcje


Add numbers

gmp_abs
gmp_and
GMP Funkcje
PHP Manual

gmp_add

(PHP 4 >= 4.0.4, PHP 5)

gmp_add — Add numbers

Opis

resource gmp_add ( resource $a , resource $b )

Add two numbers.

Parametry

a

A number that will be added.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

A number that will be added.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

A GMP number representing the sum of the arguments.

Przykłady

Przykład #1 gmp_add() example

<?php
$sum = gmp_add("123456789012345", "76543210987655");
echo gmp_strval($sum) . "\n";
?>

Powyższy przykład wyświetli:

200000000000000

gmp_abs
gmp_and
GMP Funkcje


Bitwise AND

gmp_add
gmp_clrbit
GMP Funkcje
PHP Manual

gmp_and

(PHP 4 >= 4.0.4, PHP 5)

gmp_and — Bitwise AND

Opis

resource gmp_and ( resource $a , resource $b )

Calculates bitwise AND of two GMP numbers.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

A GMP number representing the bitwise AND comparison.

Przykłady

Przykład #1 gmp_and() example

<?php
$and1 = gmp_and("0xfffffffff4", "0x4");
$and2 = gmp_and("0xfffffffff4", "0x8");
echo gmp_strval($and1) . "\n";
echo gmp_strval($and2) . "\n";
?>

Powyższy przykład wyświetli:

4
0
gmp_add
gmp_clrbit
GMP Funkcje


Clear bit

gmp_and
gmp_cmp
GMP Funkcje
PHP Manual

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_clrbit — Clear bit

Opis

void gmp_clrbit ( resource $a , int $index )

Clears (sets to 0) bit index in a. The index starts at 0.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

index

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_clrbit() example

<?php
$a = gmp_init("0xff");
gmp_clrbit($a, 0); // index starts at 0, least significant bit
echo gmp_strval($a) . "\n";
?>

Powyższy przykład wyświetli:

254

Notatki

Informacja:

Unlike most of the other GMP functions, gmp_clrbit() must be called with a GMP resource that already exists (using gmp_init() for example). One will not be automatically created.

Zobacz też:

  • gmp_setbit() - Set bit
  • gmp_testbit() - Tests if a bit is set

gmp_and
gmp_cmp
GMP Funkcje


Compare numbers

gmp_clrbit
gmp_com
GMP Funkcje
PHP Manual

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5)

gmp_cmp — Compare numbers

Opis

int gmp_cmp ( resource $a , resource $b )

Compares two numbers.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Returns a positive value if a > b, zero if a = b and a negative value if a < b.

Przykłady

Przykład #1 gmp_cmp() example

<?php
$cmp1 = gmp_cmp("1234", "1000"); // greater than
$cmp2 = gmp_cmp("1000", "1234"); // less than
$cmp3 = gmp_cmp("1234", "1234"); // equal to

echo "$cmp1 $cmp2 $cmp3\n";
?>

Powyższy przykład wyświetli:

1 -1 0
gmp_clrbit
gmp_com
GMP Funkcje


Calculates one's complement

gmp_cmp
gmp_div_q
GMP Funkcje
PHP Manual

gmp_com

(PHP 4 >= 4.0.4, PHP 5)

gmp_com — Calculates one's complement

Opis

resource gmp_com ( resource $a )

Returns the one's complement of a.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Returns the one's complement of a, as a GMP number.

Przykłady

Przykład #1 gmp_com() example

<?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?>

Powyższy przykład wyświetli:

-1235
gmp_cmp
gmp_div_q
GMP Funkcje


Divide numbers

gmp_com
gmp_div_qr
GMP Funkcje
PHP Manual

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_q — Divide numbers

Opis

resource gmp_div_q ( resource $a , resource $b [, int $round = GMP_ROUND_ZERO ] )

Divides a by b and returns the integer result.

Parametry

a

The number being divided.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

The number that a is being divided by.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

round

The result rounding is defined by the round, which can have the following values:

  • GMP_ROUND_ZERO: The result is truncated towards 0.
  • GMP_ROUND_PLUSINF: The result is rounded towards +infinity.
  • GMP_ROUND_MINUSINF: The result is rounded towards -infinity.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_div_q() example

<?php
$div1 = gmp_div_q("100", "5");
echo gmp_strval($div1) . "\n";

$div2 = gmp_div_q("1", "3");
echo gmp_strval($div2) . "\n";

$div3 = gmp_div_q("1", "3", GMP_ROUND_PLUSINF);
echo gmp_strval($div3) . "\n";

$div4 = gmp_div_q("-1", "4", GMP_ROUND_PLUSINF);
echo gmp_strval($div4) . "\n";

$div5 = gmp_div_q("-1", "4", GMP_ROUND_MINUSINF);
echo gmp_strval($div5) . "\n";
?>

Powyższy przykład wyświetli:

20
0
1
0
-1

Notatki

Informacja:

This function can also be called as gmp_div().

Zobacz też:

  • gmp_div_r() - Remainder of the division of numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

gmp_com
gmp_div_qr
GMP Funkcje


Divide numbers and get quotient and remainder

gmp_div_q
gmp_div_r
GMP Funkcje
PHP Manual

gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_qr — Divide numbers and get quotient and remainder

Opis

array gmp_div_qr ( resource $n , resource $d [, int $round = GMP_ROUND_ZERO ] )

The function divides n by d.

Parametry

n

The number being divided.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

d

The number that n is being divided by.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

round

See the gmp_div_q() function for description of the round argument.

Zwracane wartości

Returns an array, with the first element being [n/d] (the integer result of the division) and the second being (n - [n/d] * d) (the remainder of the division).

Przykłady

Przykład #1 Division of GMP numbers

<?php
$a = gmp_init("0x41682179fbf5");
$res = gmp_div_qr($a, "0xDEFE75");
printf("Result is: q - %s, r - %s",
       gmp_strval($res[0]), gmp_strval($res[1]));
?>

Zobacz też:

  • gmp_div_q() - Divide numbers
  • gmp_div_r() - Remainder of the division of numbers

gmp_div_q
gmp_div_r
GMP Funkcje


Remainder of the division of numbers

gmp_div_qr
gmp_div
GMP Funkcje
PHP Manual

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5)

gmp_div_r — Remainder of the division of numbers

Opis

resource gmp_div_r ( resource $n , resource $d [, int $round = GMP_ROUND_ZERO ] )

Calculates remainder of the integer division of n by d. The remainder has the sign of the n argument, if not zero.

Parametry

n

The number being divided.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

d

The number that n is being divided by.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

round

See the gmp_div_q() function for description of the round argument.

Zwracane wartości

The remainder, as a GMP number.

Przykłady

Przykład #1 gmp_div_r() example

<?php
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
?>

Powyższy przykład wyświetli:

5

Zobacz też:

  • gmp_div_q() - Divide numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

gmp_div_qr
gmp_div
GMP Funkcje


Alias dla gmp_div_q

gmp_div_r
gmp_divexact
GMP Funkcje
PHP Manual

gmp_div

(PHP 4 >= 4.0.4, PHP 5)

gmp_div — Alias dla gmp_div_q()

Opis

Ta funkcja jest aliasem dla: gmp_div_q().

gmp_div_r
gmp_divexact
GMP Funkcje


Exact division of numbers

gmp_div
gmp_fact
GMP Funkcje
PHP Manual

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5)

gmp_divexact — Exact division of numbers

Opis

resource gmp_divexact ( resource $n , resource $d )

Divides n by d, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n.

Parametry

n

The number being divided.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

d

The number that a is being divided by.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_divexact() example

<?php
$div1 = gmp_divexact("10", "2");
echo gmp_strval($div1) . "\n";

$div2 = gmp_divexact("10", "3"); // bogus result
echo gmp_strval($div2) . "\n";
?>

Powyższy przykład wyświetli:

5
2863311534

gmp_div
gmp_fact
GMP Funkcje


Factorial

gmp_divexact
gmp_gcd
GMP Funkcje
PHP Manual

gmp_fact

(PHP 4 >= 4.0.4, PHP 5)

gmp_fact — Factorial

Opis

resource gmp_fact ( mixed $a )

Calculates factorial (a!) of a.

Parametry

a

The factorial number.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_fact() example

<?php
$fact1 = gmp_fact(5); // 5 * 4 * 3 * 2 * 1
echo gmp_strval($fact1) . "\n";

$fact2 = gmp_fact(50); // 50 * 49 * 48, ... etc
echo gmp_strval($fact2) . "\n";
?>

Powyższy przykład wyświetli:

120
30414093201713378043612608166064768844377641568960512000000000000

gmp_divexact
gmp_gcd
GMP Funkcje


Calculate GCD

gmp_fact
gmp_gcdext
GMP Funkcje
PHP Manual

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcd — Calculate GCD

Opis

resource gmp_gcd ( resource $a , resource $b )

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

A positive GMP number that divides into both a and b.

Przykłady

Przykład #1 gmp_gcd() example

<?php
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
?>

Powyższy przykład wyświetli:

3

gmp_fact
gmp_gcdext
GMP Funkcje


Calculate GCD and multipliers

gmp_gcd
gmp_hamdist
GMP Funkcje
PHP Manual

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5)

gmp_gcdext — Calculate GCD and multipliers

Opis

array gmp_gcdext ( resource $a , resource $b )

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

This function can be used to solve linear Diophantine equations in two variables. These are equations that allow only integer solutions and have the form: a*x + b*y = c. For more information, go to the » "Diophantine Equation" page at MathWorld

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

An array of GMP numbers.

Przykłady

Przykład #1 Solving a linear Diophantine equation

<?php
// Solve the equation a*s + b*t = g
// where a = 12, b = 21, g = gcd(12, 21) = 3
$a = gmp_init(12);
$b = gmp_init(21);
$g = gmp_gcd($a, $b);
$r = gmp_gcdext($a, $b);

$check_gcd = (gmp_strval($g) == gmp_strval($r['g']));
$eq_res = gmp_add(gmp_mul($a, $r['s']), gmp_mul($b, $r['t']));
$check_res = (gmp_strval($g) == gmp_strval($eq_res));

if ($check_gcd && $check_res) {
    $fmt = "Solution: %d*%d + %d*%d = %d\n";
    printf($fmt, gmp_strval($a), gmp_strval($r['s']), gmp_strval($b),
    gmp_strval($r['t']), gmp_strval($r['g']));
} else {
    echo "Error while solving the equation\n";
}

// output: Solution: 12*2 + 21*-1 = 3
?>

gmp_gcd
gmp_hamdist
GMP Funkcje


Hamming distance

gmp_gcdext
gmp_init
GMP Funkcje
PHP Manual

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5)

gmp_hamdist — Hamming distance

Opis

int gmp_hamdist ( resource $a , resource $b )

Returns the hamming distance between a and b. Both operands should be non-negative.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

It should be positive.

b

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

It should be positive.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_hamdist() example

<?php
$ham1 = gmp_init("1001010011", 2);
$ham2 = gmp_init("1011111100", 2);
echo gmp_hamdist($ham1, $ham2) . "\n";

/* hamdist is equivilent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
?>

Powyższy przykład wyświetli:

6
6

Zobacz też:

  • gmp_popcount() - Population count
  • gmp_xor() - Bitwise XOR

gmp_gcdext
gmp_init
GMP Funkcje


Create GMP number

gmp_hamdist
gmp_intval
GMP Funkcje
PHP Manual

gmp_init

(PHP 4 >= 4.0.4, PHP 5)

gmp_init — Create GMP number

Opis

resource gmp_init ( mixed $number [, int $base = 0 ] )

Creates a GMP number from an integer or string.

Parametry

number

An integer or a string. The string representation can be decimal, hexadecimal or octal.

base

The base.

The base may vary from 2 to 36. If base is 0 (default value), the actual base is determined from the leading characters: if the first two characters are 0x or 0X, hexadecimal is assumed, otherwise if the first character is "0", octal is assumed, otherwise decimal is assumed.

Zwracane wartości

Numer GMP zasób.

Rejestr zmian

Wersja | Opis
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.
4.1.0 | The optional base parameter was added.

Notatki

Informacja:

To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

Przykłady

Przykład #1 Creating GMP number

<?php
$a = gmp_init(123456);
$b = gmp_init("0xFFFFDEBACDFEDF7200");
?>

Notatki

Informacja:

It is not necessary to call this function if you want to use integer or string in place of GMP number in GMP functions, like gmp_add(). Function arguments are automatically converted to GMP numbers, if such conversion is possible and needed, using the same rules as gmp_init().

gmp_hamdist
gmp_intval
GMP Funkcje


Convert GMP number to integer

gmp_init
gmp_invert
GMP Funkcje
PHP Manual

gmp_intval

(PHP 4 >= 4.0.4, PHP 5)

gmp_intval — Convert GMP number to integer

Opis

int gmp_intval ( resource $gmpnumber )

This function allows to convert GMP number to integer.

Parametry

gmpnumber

A GMP number.

Zwracane wartości

An integer value of gmpnumber.

Przykłady

Przykład #1 gmp_intval() example

<?php
// displays correct result
echo gmp_intval("2147483647") . "\n";

// displays wrong result, above PHP integer limit
echo gmp_intval("2147483648") . "\n";

// displays correct result
echo gmp_strval("2147483648") . "\n";
?>

Powyższy przykład wyświetli:

2147483647
2147483647
2147483648

Notatki

Ostrzeżenie

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). If you want just to print the GMP number, use gmp_strval().

gmp_init
gmp_invert
GMP Funkcje


Inverse by modulo

gmp_intval
gmp_jacobi
GMP Funkcje
PHP Manual

gmp_invert

(PHP 4 >= 4.0.4, PHP 5)

gmp_invert — Inverse by modulo

Opis

resource gmp_invert ( resource $a , resource $b )

Computes the inverse of a modulo b.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

A GMP number on success or FALSE if an inverse does not exist.

Przykłady

Przykład #1 gmp_invert() example

<?php
echo gmp_invert("5", "10"); // no inverse, outputs nothing, result is FALSE
$invert = gmp_invert("5", "11");
echo gmp_strval($invert) . "\n";
?>

Powyższy przykład wyświetli:

9

gmp_intval
gmp_jacobi
GMP Funkcje


Jacobi symbol

gmp_invert
gmp_legendre
GMP Funkcje
PHP Manual

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5)

gmp_jacobi — Jacobi symbol

Opis

int gmp_jacobi ( resource $a , resource $p )

Computes » Jacobi symbol of a and p. p should be odd and must be positive.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

p

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Should be odd and must be positive.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_jacobi() example

<?php
echo gmp_jacobi("1", "3") . "\n";
echo gmp_jacobi("2", "3") . "\n";
?>

Powyższy przykład wyświetli:

1
0

gmp_invert
gmp_legendre
GMP Funkcje


Legendre symbol

gmp_jacobi
gmp_mod
GMP Funkcje
PHP Manual

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5)

gmp_legendre — Legendre symbol

Opis

int gmp_legendre ( resource $a , resource $p )

Compute the » Legendre symbol of a and p. p should be odd and must be positive.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

p

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Should be odd and must be positive.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_legendre() example

<?php
echo gmp_legendre("1", "3") . "\n";
echo gmp_legendre("2", "3") . "\n";
?>

Powyższy przykład wyświetli:

1
0

gmp_jacobi
gmp_mod
GMP Funkcje


Modulo operation

gmp_legendre
gmp_mul
GMP Funkcje
PHP Manual

gmp_mod

(PHP 4 >= 4.0.4, PHP 5)

gmp_mod — Modulo operation

Opis

resource gmp_mod ( resource $n , resource $d )

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

Parametry

n

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

d

The modulo that is being evaluated.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_mod() example

<?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?>

Powyższy przykład wyświetli:

2

gmp_legendre
gmp_mul
GMP Funkcje


Multiply numbers

gmp_mod
gmp_neg
GMP Funkcje
PHP Manual

gmp_mul

(PHP 4 >= 4.0.4, PHP 5)

gmp_mul — Multiply numbers

Opis

resource gmp_mul ( resource $a , resource $b )

Multiplies a by b and returns the result.

Parametry

a

A number that will be multiplied by b.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

A number that will be multiplied by a.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_mul() example

<?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?>

Powyższy przykład wyświetli:

24691356000

gmp_mod
gmp_neg
GMP Funkcje


Negate number

gmp_mul
gmp_nextprime
GMP Funkcje
PHP Manual

gmp_neg

(PHP 4 >= 4.0.4, PHP 5)

gmp_neg — Negate number

Opis

resource gmp_neg ( resource $a )

Returns the negative value of a number.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Returns -a, as a GMP number.

Przykłady

Przykład #1 gmp_neg() example

<?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>

Powyższy przykład wyświetli:

-1
1

gmp_mul
gmp_nextprime
GMP Funkcje


Find next prime number

gmp_neg
gmp_or
GMP Funkcje
PHP Manual

gmp_nextprime

(PHP 5 >= 5.2.0)

gmp_nextprime — Find next prime number

Opis

resource gmp_nextprime ( int $a )

Find next prime number

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Return the next prime number greater than a, as a GMP number.

Przykłady

Przykład #1 gmp_nextprime() example

<?php
$prime1 = gmp_nextprime(10); // next prime number greater than 10
$prime2 = gmp_nextprime(-1000); // next prime number greater than -1000

echo gmp_strval($prime1) . "\n";
echo gmp_strval($prime2) . "\n";
?>

Powyższy przykład wyświetli:

11
-997

Notatki

Informacja:

This function uses a probabilistic algorithm to identify primes and chances to get a composite number are extremely small.

gmp_neg
gmp_or
GMP Funkcje


Bitwise OR

gmp_nextprime
gmp_perfect_square
GMP Funkcje
PHP Manual

gmp_or

(PHP 4 >= 4.0.4, PHP 5)

gmp_or — Bitwise OR

Opis

resource gmp_or ( resource $a , resource $b )

Calculates bitwise inclusive OR of two GMP numbers.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_or() example

<?php
$or1 = gmp_or("0xfffffff2", "4");
echo gmp_strval($or1, 16) . "\n";
$or2 = gmp_or("0xfffffff2", "2");
echo gmp_strval($or2, 16) . "\n";
?>

Powyższy przykład wyświetli:

fffffff6
fffffff2

gmp_nextprime
gmp_perfect_square
GMP Funkcje


Perfect square check

gmp_or
gmp_popcount
GMP Funkcje
PHP Manual

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5)

gmp_perfect_square — Perfect square check

Opis

bool gmp_perfect_square ( resource $a )

Check if a number is a perfect square.

Parametry

a

The number being checked as a perfect square.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Returns TRUE if a is a perfect square, FALSE otherwise.

Przykłady

Przykład #1 gmp_perfect_square() example

<?php
// 3 * 3, perfect square
var_dump(gmp_perfect_square("9"));

// not a perfect square
var_dump(gmp_perfect_square("7"));

// 1234567890 * 1234567890, perfect square
var_dump(gmp_perfect_square("1524157875019052100"));
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)
bool(true)

Zobacz też:

  • gmp_sqrt() - Calculate square root
  • gmp_sqrtrem() - Square root with remainder

gmp_or
gmp_popcount
GMP Funkcje


Population count

gmp_perfect_square
gmp_pow
GMP Funkcje
PHP Manual

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5)

gmp_popcount — Population count

Opis

int gmp_popcount ( resource $a )

Get the population count.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

The population count of a, as an integer.

Przykłady

Przykład #1 gmp_popcount() example

<?php
$pop1 = gmp_init("10000101", 2); // 3 1's
echo gmp_popcount($pop1) . "\n";
$pop2 = gmp_init("11111110", 2); // 7 1's
echo gmp_popcount($pop2) . "\n";
?>

Powyższy przykład wyświetli:

3
7

gmp_perfect_square
gmp_pow
GMP Funkcje


Raise number into power

gmp_popcount
gmp_powm
GMP Funkcje
PHP Manual

gmp_pow

(PHP 4 >= 4.0.4, PHP 5)

gmp_pow — Raise number into power

Opis

resource gmp_pow ( resource $base , int $exp )

Raise base into power exp.

Parametry

base

The base number.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

exp

The positive power to raise the base.

Zwracane wartości

The new (raised) number, as a GMP number. The case of 0^0 yields 1.

Przykłady

Przykład #1 gmp_pow() example

<?php
$pow1 = gmp_pow("2", 31);
echo gmp_strval($pow1) . "\n";
$pow2 = gmp_pow("0", 0);
echo gmp_strval($pow2) . "\n";
$pow3 = gmp_pow("2", -1); // Negative exp, generates warning
echo gmp_strval($pow3) . "\n";
?>

Powyższy przykład wyświetli:

2147483648
1

gmp_popcount
gmp_powm
GMP Funkcje


Raise number into power with modulo

gmp_pow
gmp_prob_prime
GMP Funkcje
PHP Manual

gmp_powm

(PHP 4 >= 4.0.4, PHP 5)

gmp_powm — Raise number into power with modulo

Opis

resource gmp_powm ( resource $base , resource $exp , resource $mod )

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

Parametry

base

The base number.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

exp

The positive power to raise the base.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

mod

The modulo.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

The new (raised) number, as a GMP number.

Przykłady

Przykład #1 gmp_powm() example

<?php
$pow1 = gmp_powm("2", "31", "2147483649");
echo gmp_strval($pow1) . "\n";
?>

Powyższy przykład wyświetli:

2147483648

gmp_pow
gmp_prob_prime
GMP Funkcje


Check if number is "probably prime"

gmp_powm
gmp_random
GMP Funkcje
PHP Manual

gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5)

gmp_prob_prime — Check if number is "probably prime"

Opis

int gmp_prob_prime ( resource $a [, int $reps = 10 ] )

The function uses Miller-Rabin's probabilistic test to check if a number is a prime.

Parametry

a

The number being checked as a prime.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

reps

Reasonable values of reps vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

If this function returns 0, a is definitely not prime. If it returns 1, then a is "probably" prime. If it returns 2, then a is surely prime.

Przykłady

Przykład #1 gmp_prob_prime() example

<?php
// definitely not a prime
echo gmp_prob_prime("6") . "\n";

// probably a prime
echo gmp_prob_prime("1111111111111111111") . "\n";

// definitely a prime
echo gmp_prob_prime("11") . "\n";
?>

Powyższy przykład wyświetli:

0
1
2

gmp_powm
gmp_random
GMP Funkcje


Random number

gmp_prob_prime
gmp_scan0
GMP Funkcje
PHP Manual

gmp_random

(PHP 4 >= 4.0.4, PHP 5)

gmp_random — Random number

Opis

resource gmp_random ([ int $limiter = 20 ] )

Generate a random number. The number will be between zero and the number of bits per limb multiplied by limiter. If limiter is negative, negative numbers are generated.

A limb is an internal GMP mechanism. The number of bits in a limb is not static, and can vary from system to system. Generally, the number of bits in a limb is either 16 or 32, but this is not guaranteed.

Parametry

limiter

The limiter.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

A random GMP number.

Przykłady

Przykład #1 gmp_random() example

<?php
$rand1 = gmp_random(1); // random number from 0 to 1 * bits per limb
$rand2 = gmp_random(2); // random number from 0 to 2 * bits per limb

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

Powyższy przykład wyświetli:

1915834968
8642564075890328087

gmp_prob_prime
gmp_scan0
GMP Funkcje


Scan for 0

gmp_random
gmp_scan1
GMP Funkcje
PHP Manual

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan0 — Scan for 0

Opis

int gmp_scan0 ( resource $a , int $start )

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found.

Parametry

a

The number to scan.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

start

The starting bit.

Zwracane wartości

Returns the index of the found bit, as an integer. The index starts from 0.

Przykłady

Przykład #1 gmp_scan0() example

<?php
// "0" bit is found at position 3. index starts at 0
$s1 = gmp_init("10111", 2);
echo gmp_scan0($s1, 0) . "\n";

// "0" bit is found at position 7. index starts at 5
$s2 = gmp_init("101110000", 2);
echo gmp_scan0($s2, 5) . "\n";
?>

Powyższy przykład wyświetli:

3
7

gmp_random
gmp_scan1
GMP Funkcje


Scan for 1

gmp_scan0
gmp_setbit
GMP Funkcje
PHP Manual

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5)

gmp_scan1 — Scan for 1

Opis

int gmp_scan1 ( resource $a , int $start )

Scans a, starting with bit start, towards more significant bits, until the first set bit is found.

Parametry

a

The number to scan.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

start

The starting bit.

Zwracane wartości

Returns the index of the found bit, as an integer. If no set bit is found, -1 is returned.

Przykłady

Przykład #1 gmp_scan1() example

<?php
// "1" bit is found at position 3. index starts at 0
$s1 = gmp_init("01000", 2);
echo gmp_scan1($s1, 0) . "\n";

// "1" bit is found at position 9. index starts at 5
$s2 = gmp_init("01000001111", 2);
echo gmp_scan1($s2, 5) . "\n";
?>

Powyższy przykład wyświetli:

3
9

gmp_scan0
gmp_setbit
GMP Funkcje


Set bit

gmp_scan1
gmp_sign
GMP Funkcje
PHP Manual

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5)

gmp_setbit — Set bit

Opis

void gmp_setbit ( resource $a , int $index [, bool $set_clear = true ] )

Sets bit index in a.

Parametry

a

The number being set to.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

index

The set bit.

set_clear

Defines if the bit is set to 0 or 1. By default the bit is set to 1. Index starts at 0.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_setbit() example

<?php
$a = gmp_init("0xfd");
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a) . "\n";
?>

Powyższy przykład wyświetli:

255

Notatki

Informacja:

Unlike most of the other GMP functions, gmp_setbit() must be called with a GMP resource that already exists (using gmp_init() for example). One will not be automatically created.

Zobacz też:

  • gmp_clrbit() - Clear bit
  • gmp_testbit() - Tests if a bit is set

gmp_scan1
gmp_sign
GMP Funkcje


Sign of number

gmp_setbit
gmp_sqrt
GMP Funkcje
PHP Manual

gmp_sign

(PHP 4 >= 4.0.4, PHP 5)

gmp_sign — Sign of number

Opis

int gmp_sign ( resource $a )

Checks the sign of a number.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Returns 1 if a is positive, -1 if a is negative, and 0 if a is zero.

Przykłady

Przykład #1 gmp_sign() example

<?php
// positive
echo gmp_sign("500") . "\n";

// negative
echo gmp_sign("-500") . "\n";

// zero
echo gmp_sign("0") . "\n";
?>

Powyższy przykład wyświetli:

1
-1
0

Zobacz też:

  • gmp_abs() - Absolute value
  • abs() - Wartość bezwględna (moduł z liczby)

gmp_setbit
gmp_sqrt
GMP Funkcje


Calculate square root

gmp_sign
gmp_sqrtrem
GMP Funkcje
PHP Manual

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrt — Calculate square root

Opis

resource gmp_sqrt ( resource $a )

Calculates square root of a.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

The integer portion of the square root, as a GMP number.

Przykłady

Przykład #1 gmp_sqrt() example

<?php
$sqrt1 = gmp_sqrt("9");
$sqrt2 = gmp_sqrt("7");
$sqrt3 = gmp_sqrt("1524157875019052100");

echo gmp_strval($sqrt1) . "\n";
echo gmp_strval($sqrt2) . "\n";
echo gmp_strval($sqrt3) . "\n";
?>

Powyższy przykład wyświetli:

3
2
1234567890

gmp_sign
gmp_sqrtrem
GMP Funkcje


Square root with remainder

gmp_sqrt
gmp_strval
GMP Funkcje
PHP Manual

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5)

gmp_sqrtrem — Square root with remainder

Opis

array gmp_sqrtrem ( resource $a )

Calculate the square root of a number, with remainder.

Parametry

a

The number being square rooted.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Returns array where first element is the integer square root of a and the second is the remainder (i.e., the difference between a and the first element squared).

Przykłady

Przykład #1 gmp_sqrtrem() example

<?php
list($sqrt1, $sqrt1rem) = gmp_sqrtrem("9");
list($sqrt2, $sqrt2rem) = gmp_sqrtrem("7");
list($sqrt3, $sqrt3rem) = gmp_sqrtrem("1048576");

echo gmp_strval($sqrt1) . ", " . gmp_strval($sqrt1rem) . "\n";
echo gmp_strval($sqrt2) . ", " . gmp_strval($sqrt2rem) . "\n";
echo gmp_strval($sqrt3) . ", " . gmp_strval($sqrt3rem) . "\n";
?>

Powyższy przykład wyświetli:

3, 0
2, 3
1024, 0

gmp_sqrt
gmp_strval
GMP Funkcje


Convert GMP number to string

gmp_sqrtrem
gmp_sub
GMP Funkcje
PHP Manual

gmp_strval

(PHP 4 >= 4.0.4, PHP 5)

gmp_strval — Convert GMP number to string

Opis

string gmp_strval ( resource $gmpnumber [, int $base = 10 ] )

Convert GMP number to string representation in base base. The default base is 10.

Parametry

gmpnumber

The GMP number that will be converted to a string.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

base

The base of the returned number. The default base is 10. Allowed values for the base are from 2 to 62 and -2 to -36.

Zwracane wartości

The number, as a string.

Rejestr zmian

Wersja | Opis
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.

Notatki

Informacja:

To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

Przykłady

Przykład #1 Converting a GMP number to a string

<?php
$a = gmp_init("0x41682179fbf5");
printf("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?>

gmp_sqrtrem
gmp_sub
GMP Funkcje


Subtract numbers

gmp_strval
gmp_testbit
GMP Funkcje
PHP Manual

gmp_sub

(PHP 4 >= 4.0.4, PHP 5)

gmp_sub — Subtract numbers

Opis

resource gmp_sub ( resource $a , resource $b )

Subtracts b from a and returns the result.

Parametry

a

The number being subtracted from.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

The number subtracted from a.

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_sub() example

<?php
$sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32
echo gmp_strval($sub) . "\n";
?>

Powyższy przykład wyświetli:

281470681743360

gmp_strval
gmp_testbit
GMP Funkcje


Tests if a bit is set

gmp_sub
gmp_xor
GMP Funkcje
PHP Manual

gmp_testbit

(PHP 5 >= 5.3.0)

gmp_testbit — Tests if a bit is set

Opis

bool gmp_testbit ( resource $a , int $index )

Tests if the specified bit is set.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

index

The bit to test

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

E_WARNING is issued when index is less than zero.

Przykłady

Przykład #1 gmp_testbit() example

<?php
$n = gmp_init("1000000");
var_dump(gmp_testbit($n, 1));
gmp_setbit($n, 1);
var_dump(gmp_testbit($n, 1));
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:

  • gmp_setbit() - Set bit
  • gmp_clrbit() - Clear bit

gmp_sub
gmp_xor
GMP Funkcje


Bitwise XOR

gmp_testbit
Math
GMP Funkcje
PHP Manual

gmp_xor

(PHP 4 >= 4.0.4, PHP 5)

gmp_xor — Bitwise XOR

Opis

resource gmp_xor ( resource $a , resource $b )

Calculates bitwise exclusive OR (XOR) of two GMP numbers.

Parametry

a

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

b

Może być zarówno numerem GMP zasób, lub numerycznym łańcuchem znaków, który można skonwertować z liter do liczb.

Zwracane wartości

Numer GMP zasób.

Przykłady

Przykład #1 gmp_xor() example

<?php
$xor1 = gmp_init("1101101110011101", 2);
$xor2 = gmp_init("0110011001011001", 2);

$xor3 = gmp_xor($xor1, $xor2);

echo gmp_strval($xor3, 2) . "\n";
?>

Powyższy przykład wyświetli:

1011110111000100

gmp_testbit
Math
GMP Funkcje


Mathematical Functions

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Math Funkcje
    • abs — Wartość bezwględna (moduł z liczby)
    • acos — Oblicza arcus cosinus liczby
    • acosh — Area cosinus hiperboliczny
    • asin — Oblicza arcus sinus liczby
    • asinh — Area sinus hiperboliczny
    • atan2 — Arcus tangens dwóch zmiennych
    • atan — Oblicza arcus tangens liczby
    • atanh — Area tangens hiperboliczny
    • base_convert — Konwertuje liczbę pomiędzy różnymi systemami liczbowymi
    • bindec — Konwertuje liczbę dwójkową na dziesiętną
    • ceil — Zaokrągla ułamki w górę
    • cos — Oblicza cosinus kąta
    • cosh — Cosinus hiperboliczny
    • decbin — Konwertuje liczbę dziesiętną do dwójkowej
    • dechex — Konwersja liczby dziesiętnej do szesnastkowej
    • decoct — Konwersja liczby dziesiętnej do ósemkowej
    • deg2rad — Przelicza stopnie na radiany
    • exp — Oblicza eksponentę liczby e
    • expm1 — Zwraca exp(liczba) - 1, obliczoną w taki sposób, że wartość jest dokładna, nawet jeśli liczba jest bliska zeru
    • floor — Zaokrągla ułamki w dół
    • fmod — Returns the floating point remainder (modulo) of the division of the arguments
    • getrandmax — Największa możliwa liczba losowa
    • hexdec — Konwersja liczby szesnastkowej do dziesiętnej
    • hypot — Oblicza długość przeciwprostokątnej trójkąta prostokątnego
    • is_finite — Sprawdza czy wartość jest prawidłową skończoną liczbą
    • is_infinite — Sprawdza czy wartość jest nieskończona
    • is_nan — Sprawdza, czy wartość nie jest liczbą
    • lcg_value — Złożony przystający generator liniowy
    • log10 — Logarytm dziesiętny
    • log1p — Zwraca log(1 + liczba), obliczony w taki sposób, że wartości są dokładne, nawet, jeśli liczba jest bliska zeru
    • log — Logarytm naturalny
    • max — Znajduje największą liczbę
    • min — Znajduje najmniejszą wartość
    • mt_getrandmax — Największa możliwa liczba losowa
    • mt_rand — Wygeneruj lepszą liczbę losową
    • mt_srand — Inicjuje generator Mersenne Twister
    • octdec — Konwersja liczby ósemkowej do dziesiętnej
    • pi — Wartość liczby Pi
    • pow — Potęgowanie
    • rad2deg — Przelicza radiany na stopnie.
    • rand — Generuje losową liczbę stałoprzecinkową
    • round — Zaokrągla liczbę zmiennoprzecinkową
    • sin — Oblicza sinus kąta
    • sinh — Sinus hiperboliczny
    • sqrt — Pierwiastek kwadratowy
    • srand — Inicjuje generator liczb losowych
    • tan — Oblicza tangens kąta
    • tanh — Tangens hiperboliczny
gmp_xor
Wstęp
Rozszerzenia matematyczne


Wstęp

These math functions will only handle values within the range of the integer and float types on your computer (this corresponds currently to the C types long resp. double). If you need to handle bigger numbers, take a look at the arbitrary precision math functions.

See also the manual page on arithmetic operators.

Math
Instalacja/Konfiguracja
Math


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Math


Stałe predefiniowane

Poniższe stałe są częścią jądra PHP a więc są zawsze widoczne.

Stałe Matematyczne
Nazwa Stałej | Wartość | Opis | Dostępność
M_PI | 3.14159265358979323846 | Pi |
M_E | 2.7182818284590452354 | e |
M_LOG2E | 1.4426950408889634074 | log_2 e |
M_LOG10E | 0.43429448190325182765 | log_10 e |
M_LN2 | 0.69314718055994530942 | log_e 2 |
M_LN10 | 2.30258509299404568402 | log_e 10 |
M_PI_2 | 1.57079632679489661923 | pi/2 |
M_PI_4 | 0.78539816339744830962 | pi/4 |
M_1_PI | 0.31830988618379067154 | 1/pi |
M_2_PI | 0.63661977236758134308 | 2/pi |
M_SQRTPI | 1.77245385090551602729 | sqrt(pi) | PHP 5.2.0
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) | PHP 5.2.0
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) | PHP 5.2.0
M_EULER | 0.57721566490153286061 | Stała Eulera | PHP 5.2.0
PHP_ROUND_HALF_UP | 1 | Zaokrągla w górę | PHP 5.3.0
PHP_ROUND_HALF_DOWN | 2 | Zaokrągla w dół | PHP 5.3.0
PHP_ROUND_HALF_EVEN | 3 | Zaokrągla do liczb parzystych | PHP 5.3.0
PHP_ROUND_HALF_ODD | 4 | Zaokrągla do liczb nieparzystych | PHP 5.3.0
NAN | NAN (jako float) | Nie liczba |
INF | INF (jako float) | Nieskończoność |

Wszystkie stałe, poza oznaczonymi wersją PHP, są dostępne począwszy od PHP 4.0.0.

Typy zasobów
Math Funkcje
Math


Math Funkcje

Spis treści

  • abs — Wartość bezwględna (moduł z liczby)
  • acos — Oblicza arcus cosinus liczby
  • acosh — Area cosinus hiperboliczny
  • asin — Oblicza arcus sinus liczby
  • asinh — Area sinus hiperboliczny
  • atan2 — Arcus tangens dwóch zmiennych
  • atan — Oblicza arcus tangens liczby
  • atanh — Area tangens hiperboliczny
  • base_convert — Konwertuje liczbę pomiędzy różnymi systemami liczbowymi
  • bindec — Konwertuje liczbę dwójkową na dziesiętną
  • ceil — Zaokrągla ułamki w górę
  • cos — Oblicza cosinus kąta
  • cosh — Cosinus hiperboliczny
  • decbin — Konwertuje liczbę dziesiętną do dwójkowej
  • dechex — Konwersja liczby dziesiętnej do szesnastkowej
  • decoct — Konwersja liczby dziesiętnej do ósemkowej
  • deg2rad — Przelicza stopnie na radiany
  • exp — Oblicza eksponentę liczby e
  • expm1 — Zwraca exp(liczba) - 1, obliczoną w taki sposób, że wartość jest dokładna, nawet jeśli liczba jest bliska zeru
  • floor — Zaokrągla ułamki w dół
  • fmod — Returns the floating point remainder (modulo) of the division of the arguments
  • getrandmax — Największa możliwa liczba losowa
  • hexdec — Konwersja liczby szesnastkowej do dziesiętnej
  • hypot — Oblicza długość przeciwprostokątnej trójkąta prostokątnego
  • is_finite — Sprawdza czy wartość jest prawidłową skończoną liczbą
  • is_infinite — Sprawdza czy wartość jest nieskończona
  • is_nan — Sprawdza, czy wartość nie jest liczbą
  • lcg_value — Złożony przystający generator liniowy
  • log10 — Logarytm dziesiętny
  • log1p — Zwraca log(1 + liczba), obliczony w taki sposób, że wartości są dokładne, nawet, jeśli liczba jest bliska zeru
  • log — Logarytm naturalny
  • max — Znajduje największą liczbę
  • min — Znajduje najmniejszą wartość
  • mt_getrandmax — Największa możliwa liczba losowa
  • mt_rand — Wygeneruj lepszą liczbę losową
  • mt_srand — Inicjuje generator Mersenne Twister
  • octdec — Konwersja liczby ósemkowej do dziesiętnej
  • pi — Wartość liczby Pi
  • pow — Potęgowanie
  • rad2deg — Przelicza radiany na stopnie.
  • rand — Generuje losową liczbę stałoprzecinkową
  • round — Zaokrągla liczbę zmiennoprzecinkową
  • sin — Oblicza sinus kąta
  • sinh — Sinus hiperboliczny
  • sqrt — Pierwiastek kwadratowy
  • srand — Inicjuje generator liczb losowych
  • tan — Oblicza tangens kąta
  • tanh — Tangens hiperboliczny
Stałe predefiniowane
abs
Math


Wartość bezwględna (moduł z liczby)

Math Funkcje
acos
Math Funkcje
PHP Manual

abs

(PHP 4, PHP 5)

abs — Wartość bezwględna (moduł z liczby)

Opis

number abs ( mixed $liczba )

Zwraca wartość bezwględna liczby.

Parametry

liczba

Liczba do przetworzenia

Zwracane wartości

Wartość bezwzględną (moduł) podanego argumentu liczba. Jeśli argument liczba jest typu float, zwracana jest także wartość float. W innych przypadkach zwracana jest wartość integer (float ma zwykle szerszy zakres niż integer).

Przykłady

Przykład #1 Przykład abs()

<?php
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);   // $abs2 = 5; (integer)
$abs3 = abs(-5);  // $abs3 = 5; (integer)
?>

Zobacz też:

  • gmp_abs() - Absolute value
  • gmp_sign() - Sign of number

Math Funkcje
acos
Math Funkcje


Oblicza arcus cosinus liczby

abs
acosh
Math Funkcje
PHP Manual

acos

(PHP 4, PHP 5)

acos — Oblicza arcus cosinus liczby

Opis

float acos ( float $argument )

Zwraca w radianach arcus cosinus argumentu. Funkcja acos() jest dopełniającą do funkcji cos(), co oznacza, że a==cos(acos(a)) dla każdej wartości z dziedziny funkcji acos().

Parametry

argument

Argument do przetworzenia

Zwracane wartości

Arcus cosinus argumentu w radianach.

Zobacz też:

  • cos() - Oblicza cosinus kąta
  • acosh() - Area cosinus hiperboliczny
  • asin() - Oblicza arcus sinus liczby
  • atan() - Oblicza arcus tangens liczby

abs
acosh
Math Funkcje


Area cosinus hiperboliczny

acos
asin
Math Funkcje
PHP Manual

acosh

(PHP 4 >= 4.1.0, PHP 5)

acosh — Area cosinus hiperboliczny

Opis

float acosh ( float $arg )

Zwraca area cosinus hiperboliczny z liczby arg, tzn. taką wartość, której cosinus hiperboliczny jest równy arg.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

   Patrz także:
acos(),
asinh() i
atanh().

acos
asin
Math Funkcje


Oblicza arcus sinus liczby

acosh
asinh
Math Funkcje
PHP Manual

asin

(PHP 4, PHP 5)

asin — Oblicza arcus sinus liczby

Opis

float asin ( float $argument )

Zwraca w radianach arcus sinus argumentu argument. asin() jest funkcją komplementarną do sin(), co oznacza, że a == sin(asin(a)) dla każdej wartości z dziedziny funkcji asin().

   Patrz także:
asinh(),
acos() i
atan().

acosh
asinh
Math Funkcje


Area sinus hiperboliczny

asin
atan2
Math Funkcje
PHP Manual

asinh

(PHP 4 >= 4.1.0, PHP 5)

asinh — Area sinus hiperboliczny

Opis

float asinh ( float $arg )

Zwraca area sinus hiperboliczny z liczby arg, tzn. taką wartość, której sinus hiperboliczny jest równy arg.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

   Patrz także:
asin(),
acosh() i
atanh().

asin
atan2
Math Funkcje


Arcus tangens dwóch zmiennych

asinh
atan
Math Funkcje
PHP Manual

atan2

(PHP 4, PHP 5)

atan2 — Arcus tangens dwóch zmiennych

Opis

float atan2 ( float $y , float $x )

Ta funkcja oblicza arcus tangens dwóch zmiennych x i y. Jej działanie przypomina obliczanie arcus tangens z y / x, a do tego, znaki obydwu argumentów wykorzystywane są do określenia ćwiartki (kwadrantu) układu współrzędnych.

Funkcja zwraca wartość w radianach, zawierającą się między -PI a PI włącznie.

Parametry

y

Dzielna

x

Dzielnik

Zwracane wartości

Arcus tangens y/x w radianach.

Zobacz też:

  • atan() - Oblicza arcus tangens liczby

asinh
atan
Math Funkcje


Oblicza arcus tangens liczby

atan2
atanh
Math Funkcje
PHP Manual

atan

(PHP 4, PHP 5)

atan — Oblicza arcus tangens liczby

Opis

float atan ( float $argument )

Funkcja atan() zwraca w radianach arcus tangens argumentu argument. atan() jest funkcją komplementarną do tan(), co oznacza, że a == tan(atan(a)) dla każdej wartości z dziedziny funkcji atan().

   Patrz także:
atanh(),
   asin() i
acos().

atan2
atanh
Math Funkcje


Area tangens hiperboliczny

atan
base_convert
Math Funkcje
PHP Manual

atanh

(PHP 4 >= 4.1.0, PHP 5)

atanh — Area tangens hiperboliczny

Opis

float atanh ( float $arg )

Zwraca area tangens hiperboliczny z liczby arg, tzn. taką wartość, dla której tangens hiperboliczny jest równy arg.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

   Patrz także:
atan(),
asinh() i
acosh().

atan
base_convert
Math Funkcje


Konwertuje liczbę pomiędzy różnymi systemami liczbowymi

atanh
bindec
Math Funkcje
PHP Manual

base_convert

(PHP 4, PHP 5)

base_convert — Konwertuje liczbę pomiędzy różnymi systemami liczbowymi

Opis

string base_convert ( string $liczba , int $system_bazowy , int $system_docelowy )

Zwraca łańcuch znaków zawierający liczbę w reprezentacji w system_docelowy. System w którym podajemy liczbę jest określony w system_bazowy. Parametry system_bazowy i system_docelowy muszą zawierać się pomiędzy 2 a 36 włącznie. Cyfry w liczbach o bazie większej niż 10 są reprezentowane za pomocą liter a-z, gdzie a oznacza 10, b oznacza 11, a z oznacza 35.

Przykład #1 base_convert() przykład

<?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2);
?>

Wyświetli:

101000110111001100110100

Ostrzeżenie

base_convert() może tracić precyzję przy dużych liczbach z powodu odwoływania się do wewnętrznych typów "double" lub "float". Proszę zajrzeć do sekcji Liczby zmiennoprzecinkowe podręcznika po szczegółowe informacje i ograniczenia.

Patrz także: intval().

atanh
bindec
Math Funkcje


Konwertuje liczbę dwójkową na dziesiętną

base_convert
ceil
Math Funkcje
PHP Manual

bindec

(PHP 4, PHP 5)

bindec — Konwertuje liczbę dwójkową na dziesiętną

Opis

number bindec ( string $liczba_dwójkowa )

Zwraca liczbę dziesiętną odpowiadającą liczbie dwójkowej podanej w argumencie liczba_dwójkowa.

bindec() konwertuje liczby dwójkowe do liczb całkowitych. Największą konwertowaną liczbą jest 31 bitów jedynek, czyli 2 147 483 647 dziesiętnie. Od PHP 4.1.0, funkcja ta potrafi konwertować większe liczby. W takim przypadku zwraca float.

Przykład #1 bindec() przykład

<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";

echo bindec('111');
?>

Powyższy przykład wyświetli:

51
51
7

Patrz także: decbin(),
octdec(),
hexdec() i
base_convert().

base_convert
ceil
Math Funkcje


Zaokrągla ułamki w górę

bindec
cos
Math Funkcje
PHP Manual

ceil

(PHP 4, PHP 5)

ceil — Zaokrągla ułamki w górę

Opis

float ceil ( float $liczba )

Zwraca nabliższą liczbę całkowitą, większą lub równą podanemu argumentowi liczba. Zwracana przez funkcję ceil() wartość jest nadal typu float gdyż zakres tego typu jest zwykle większy niż zakres typu integer.

Przykład #1 przykład ceil()

<?php
echo ceil(4.3);       // 5;
echo ceil(9.999);     // 10;
echo ceil(-3.14);  // -3
?>

Patrz także: floor() i round().

bindec
cos
Math Funkcje


Oblicza cosinus kąta

ceil
cosh
Math Funkcje
PHP Manual

cos

(PHP 4, PHP 5)

cos — Oblicza cosinus kąta

Opis

float cos ( float $argument )

Funkcja cos() zwraca cosinus kąta argument podanego w radianach.

Przykład #1 cos() przykład

<?php

echo cos(M_PI); // -1

?>

Patrz także:
acos(),
sin(),
tan() i
deg2rad().

ceil
cosh
Math Funkcje


Cosinus hiperboliczny

cos
decbin
Math Funkcje
PHP Manual

cosh

(PHP 4 >= 4.1.0, PHP 5)

cosh — Cosinus hiperboliczny

Opis

float cosh ( float $arg )

Zwraca cosinus hiperboliczny z liczby arg, definiowany jako (exp(arg) + exp(-arg))/2.

   Patrz także:
cos(),
acosh(),
   sin() i
tan().

cos
decbin
Math Funkcje


Konwertuje liczbę dziesiętną do dwójkowej

cosh
dechex
Math Funkcje
PHP Manual

decbin

(PHP 4, PHP 5)

decbin — Konwertuje liczbę dziesiętną do dwójkowej

Opis

string decbin ( int $liczba )

Zwraca łańcuch znaków stanowiący dwójkową reprezentację liczby dziesiętnej liczba. Największą liczbą możliwą do skonwertowania jest 4 294 967 295 dziesiętnie, co równe jest 32 bitom jedynek.

Przykład #1 decbin() przykład

<?php
echo decbin(12) . "\n";
echo decbin(26);
?>

Powyższy przykład wyświetli:

1100
11010

Patrz także: bindec(),
decoct(),
dechex() i
base_convert().

cosh
dechex
Math Funkcje


Konwersja liczby dziesiętnej do szesnastkowej

decbin
decoct
Math Funkcje
PHP Manual

dechex

(PHP 4, PHP 5)

dechex — Konwersja liczby dziesiętnej do szesnastkowej

Opis

string dechex ( int $liczba )

Zwraca łańcuch znaków stanowiący szesnastkową reprezentację liczby dziesiętnej liczba. Największą liczbą, która może być skonwertowana jest 4 294 967 295 dziesiętnie, co odpowiada "ffffffff" szesnastkowo.

Przykład #1 dechex() przykład

<?php
echo dechex(10) . "\n";
echo dechex(47);
?>

Powyższy przykład wyświetli:

a
2f

Patrz także: hexdec(),
decbin(),
decoct() i
base_convert().

decbin
decoct
Math Funkcje


Konwersja liczby dziesiętnej do ósemkowej

dechex
deg2rad
Math Funkcje
PHP Manual

decoct

(PHP 4, PHP 5)

decoct — Konwersja liczby dziesiętnej do ósemkowej

Opis

string decoct ( int $liczba )

Zwraca łańcuch znaków zawierający ósemkową reprezentację liczby dziesiętnej liczba. Największą liczbą, która może być skonwertowana jest 4 294 967 295 dziesiętnie, co odpowiada "37777777777" ósemkowo.

Przykład #1 decoct() przykład

<?php
echo decoct(15) . "\n";
echo decoct(264);
?>

Powyższy przykład wyświetli:

17
410

Patrz także octdec(),
decbin(),
dechex() i
base_convert().

dechex
deg2rad
Math Funkcje


Przelicza stopnie na radiany

decoct
exp
Math Funkcje
PHP Manual

deg2rad

(PHP 4, PHP 5)

deg2rad — Przelicza stopnie na radiany

Opis

float deg2rad ( float $liczba )

deg2rad() przelicza stopnie podane w liczba na radiany.

Przykład #1 deg2rad() przykład

<?php

echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)

?>

Patrz także: rad2deg().

decoct
exp
Math Funkcje


Oblicza eksponentę liczby e

deg2rad
expm1
Math Funkcje
PHP Manual

exp

(PHP 4, PHP 5)

exp — Oblicza eksponentę liczby e

Opis

float exp ( float $argument )

Zwraca e podniesione do potęgi argument.

Informacja:

Liczba 'e' jest podstawą logarytmu naturalnego. Wynosi około 2.718282.

Przykład #1 Przykład użycia exp()

<?php
echo exp(12) . "\n";
echo exp(5.7);
?>

Powyższy przykład wyświetli:

1.6275E+005
298.87

Patrz także: log() i pow().

deg2rad
expm1
Math Funkcje


Zwraca exp(liczba) - 1, obliczoną w taki sposób, że wartość jest dokładna, nawet jeśli liczba jest bliska zeru

exp
floor
Math Funkcje
PHP Manual

expm1

(PHP 4 >= 4.1.0, PHP 5)

expm1 — Zwraca exp(liczba) - 1, obliczoną w taki sposób, że wartość jest dokładna, nawet jeśli liczba jest bliska zeru

Opis

float expm1 ( float $liczba )
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.

expm1() zwraca równoważnik 'exp(number) - 1' obliczony w taki sposób, że jest poprawny nawet dla wartości liczby bliskuch zeru, który to przypadek dla operacji 'exp (number) - 1' może być niepoprawny, ze względu na operację odejmowania dwóch liczb, które są prawie równe sobie.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Patrz także: log1p() i exp().

exp
floor
Math Funkcje


Zaokrągla ułamki w dół

expm1
fmod
Math Funkcje
PHP Manual

floor

(PHP 4, PHP 5)

floor — Zaokrągla ułamki w dół

Opis

float floor ( float $liczba )

Zwraca najbliższą liczbę całkowitą, mniejszą lub równą podanemu arumentowi liczba. Zwracana przez funkcję floor() wartość jest nadal typu float ponieważ zakres tego typu jest zwykle większy niż zakres typu integer.

Przykład #1 przykład zastosowania floor()

<?php
echo floor(4.3);   // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

Patrz także: ceil() i round().

expm1
fmod
Math Funkcje


Returns the floating point remainder (modulo) of the division of the arguments

floor
getrandmax
Math Funkcje
PHP Manual

fmod

(PHP 4 >= 4.2.0, PHP 5)

fmod — Returns the floating point remainder (modulo) of the division of the arguments

Opis

float fmod ( float $x , float $y )

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

Parametry

x

The dividend

y

The divisor

Zwracane wartości

The floating point remainder of x/y

Przykłady

Przykład #1 Using fmod()

<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>

floor
getrandmax
Math Funkcje


Największa możliwa liczba losowa

fmod
hexdec
Math Funkcje
PHP Manual

getrandmax

(PHP 4, PHP 5)

getrandmax — Największa możliwa liczba losowa

Opis

int getrandmax ( void )

Zwraca największą liczbę, jaka może być zwrócona przez funkcję rand().

Patrz także: rand(), srand(), i mt_getrandmax().

fmod
hexdec
Math Funkcje


Konwersja liczby szesnastkowej do dziesiętnej

getrandmax
hypot
Math Funkcje
PHP Manual

hexdec

(PHP 4, PHP 5)

hexdec — Konwersja liczby szesnastkowej do dziesiętnej

Opis

number hexdec ( string $hex_string )

Zwraca dziesiętny odpowiednik liczby szesnastkowej podanej w argumencie hex_string. hexdec() konwertuje szesnastkowy łańcuch znaków do postaci liczby dziesiętnej. Największą liczbą, która może być skonwertowana jest 7fffffff, czyli 2147483647 dziesiętnie. Od PHP 4.1.0, funkcja potrafi konwertować także większe liczby. W takim przypadku zwraca float

hexdec() zignoruje wszelkie nie szesnastkowe znaki, które napotka.

Przykład #1 Przykład zastosowania hexdec()

<?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// obydwa zwracają "int(238)"

var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?>

   Patrz także: dechex(),
bindec(),
   octdec() i
   base_convert().

getrandmax
hypot
Math Funkcje


Oblicza długość przeciwprostokątnej trójkąta prostokątnego

hexdec
is_finite
Math Funkcje
PHP Manual

hypot

(PHP 4 >= 4.1.0, PHP 5)

hypot — Oblicza długość przeciwprostokątnej trójkąta prostokątnego

Opis

float hypot ( float $x , float $y )

hypot() zwraca długość przeciwprostokątnej trójkąta prostokątnego, o długościach przyprostokątnych x i y, lub odległość punktu o współrzędnych (x, y) od początku układu współrzędnych. Jest to równoważne wyrażeniu sqrt(x*x + y*y).

hexdec
is_finite
Math Funkcje


Sprawdza czy wartość jest prawidłową skończoną liczbą

hypot
is_infinite
Math Funkcje
PHP Manual

is_finite

(PHP 4 >= 4.2.0, PHP 5)

is_finite — Sprawdza czy wartość jest prawidłową skończoną liczbą

Opis

bool is_finite ( float $wartość )

Zwraca TRUE, jeśli argument wartość jest skończoną liczbą, zawierającą się w zakresie liczb zmiennoprzecinkowych (float) dla tej platformy.

Patrz także is_infinite() i is_nan().

hypot
is_infinite
Math Funkcje


Sprawdza czy wartość jest nieskończona

is_finite
is_nan
Math Funkcje
PHP Manual

is_infinite

(PHP 4 >= 4.2.0, PHP 5)

is_infinite — Sprawdza czy wartość jest nieskończona

Opis

bool is_infinite ( float $wartość )

Zwraca TRUE, jeśli argument wartość jest nieskończonością (dodatnią lub ujemną), tak jak wynik operacji log(0), lub cokolwiek innego, co wykracza poza typ zmiennoprzecinkowy (float) dla tej platformy.

Patrz także is_finite() i is_nan().

is_finite
is_nan
Math Funkcje


Sprawdza, czy wartość nie jest liczbą

is_infinite
lcg_value
Math Funkcje
PHP Manual

is_nan

(PHP 4 >= 4.2.0, PHP 5)

is_nan — Sprawdza, czy wartość nie jest liczbą

Opis

bool is_nan ( float $wartość )

Zwraca TRUE, jeśli wartość jest określana jako 'not a number' (symbol nieoznaczony), czyli nie jest liczbą, tak jak wartość funkcji acos(1.01).

Patrz także is_finite() i is_infinite().

is_infinite
lcg_value
Math Funkcje


Złożony przystający generator liniowy

is_nan
log10
Math Funkcje
PHP Manual

lcg_value

(PHP 4, PHP 5)

lcg_value — Złożony przystający generator liniowy

Opis

float lcg_value ( void )

lcg_value() zwraca liczbę pseudolosową z przedziału (0, 1). Funkcja łączy dwa CG o okresach 2^31 - 85 i 2^31 - 249. Okres tej funkcji jest równy wartości obydwu składowych.

is_nan
log10
Math Funkcje


Logarytm dziesiętny

lcg_value
log1p
Math Funkcje
PHP Manual

log10

(PHP 4, PHP 5)

log10 — Logarytm dziesiętny

Opis

float log10 ( float $argument )

Zwraca logarytm dziesiętny z argument.

Patrz także: log().

lcg_value
log1p
Math Funkcje


Zwraca log(1 + liczba), obliczony w taki sposób, że wartości są dokładne, nawet, jeśli liczba jest bliska zeru

log10
log
Math Funkcje
PHP Manual

log1p

(PHP 4 >= 4.1.0, PHP 5)

log1p — Zwraca log(1 + liczba), obliczony w taki sposób, że wartości są dokładne, nawet, jeśli liczba jest bliska zeru

Opis

float log1p ( float $liczba )
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.

log1p() zwraca log(1 + liczba) obliczone w sposób dokładny, nawet, jeśli wartość argumentu liczba jest bliska zeru.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Patrz także: expm1() i log().

log10
log
Math Funkcje


Logarytm naturalny

log1p
max
Math Funkcje
PHP Manual

log

(PHP 4, PHP 5)

log — Logarytm naturalny

Opis

float log ( float $argument [, float $podstawa ] )

Jeśli opcjonalny argument podstawa został podany, log() zwraca logpodstawa argument, w przeciwnym przypadku log() zwraca logarytm naturalny z argument.

Informacja:

Argument podstawa został dodany w PHP 4.3.0

Zawsze logarytm o podstawie b z liczby n można policzyć korzystając z wzoru logb(n) = log(n)/log(b), gdzie log jest logarytmem naturalnym.

Patrz także: exp().

log1p
max
Math Funkcje


Znajduje największą liczbę

log
min
Math Funkcje
PHP Manual

max

(PHP 4, PHP 5)

max — Znajduje największą liczbę

Opis

mixed max ( number $arg1 , number $arg2 [, number $... ] )
mixed max ( array $numbers )

max() zwraca największą liczbę spośród podanych argumentów.

Jeśli pierwszym i jedynym argumentem jest tablica, max() zwróci największą liczbę z tej tablicy. Jeśli pierwszy argument jest liczbą całkowitą, zmiennoprzecinkową czy łańcuchem znaków, musisz mieć conajmniej dwa argumenty, spomiędzy których funkcja max() zwróci największą wartość. Za pomocą tej funkcji można porównywać nieograniczoną ilość liczb.

Informacja:

PHP będzie uznawał nieliczbowe wartości typu string jako 0, jednakże zwracany będzie ciąg znakowy, jesli zostanie on oznany numerycznie za najmniejszą wartość. Jeśli wiele argumentów zostanie uznanych za wartość 0, to min() zwróci wartość najmniejszą alfanumerycznie, jeśli zostały podane jakiekolwiek ciągi znakowe. W przeciwnym przypadku zwrócona zostanie wartość 0.

Przykład #1 Przykłady użycia max()

<?php
echo max(1, 3, 5, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello
echo max(-1, 'hello');    // hello

// W przypadku podania wielu tablic, min porównuje je od lewej do prawej,
// A więc w poniższym przykładzie 2 == 2, ale 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

// Jeśli podane zostaną tablice i nie-tablice, zawsze zwracana jest
// tablica, jako że zawsze jest uznawana za element największy
$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)
?>

Patrz także: min() i count().

log
min
Math Funkcje


Znajduje najmniejszą wartość

max
mt_getrandmax
Math Funkcje
PHP Manual

min

(PHP 4, PHP 5)

min — Znajduje najmniejszą wartość

Opis

mixed min ( number $arg1 , number $arg2 [, number $... ] )
mixed min ( array $liczby )

min() zwraca najmniejszą liczbę spośród podanych argumentów.

Jeśli pierwszym i jedynym argumentem funkcji jest tablica, zwrócona zostanie najmniejsza wartość z tej tablicy. Jeśli pierwszym argumentem jest liczba stałoprzecinkowa, ciąg znakowy lub liczba zmiennoprzecinkowa, należy podać przynajmniej dwa argumenty, a min() zwróci najmniejszy z nich. Można porównywać nieograniczoną ilość wartości.

Informacja:

PHP będzie uznawał nieliczbowe wartości typu string jako 0, jednakże zwracany będzie ciąg znakowy, jesli zostanie on oznany numerycznie za najmniejszą wartość. Jeśli wiele argumentów zostanie uznanych za wartość 0, to min() zwróci wartość najmniejszą alfanumerycznie, jeśli zostały podane jakiekolwiek ciągi znakowe. W przeciwnym przypadku zwrócona zostanie wartość 0.

Przykład #1 Przykłady użycia min()

<?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2
echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello
echo min('hello', -1);    // -1

// W przypadku podania wielu tablic, min porównuje je od lewej do prawej,
// A więc w poniższym przykładzie 2 == 2, ale 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// Jeśli podane zostaną tablice i nie-tablice, nigdy nie jest zwracana
// tablica, jako że zawsze jest uznawana za element największy
$val = min('string', array(2, 5, 7), 42);   // string

?>

Patrz także: max() i count().

max
mt_getrandmax
Math Funkcje


Największa możliwa liczba losowa

min
mt_rand
Math Funkcje
PHP Manual

mt_getrandmax

(PHP 4, PHP 5)

mt_getrandmax — Największa możliwa liczba losowa

Opis

int mt_getrandmax ( void )

Zwraca największą liczbę losową, jaką może zwrócić funkcja mt_rand().

   Patrz także:
mt_rand(),
   mt_srand() i
   getrandmax().

min
mt_rand
Math Funkcje


Wygeneruj lepszą liczbę losową

mt_getrandmax
mt_srand
Math Funkcje
PHP Manual

mt_rand

(PHP 4, PHP 5)

mt_rand — Wygeneruj lepszą liczbę losową

Opis

int mt_rand ([ int $min ], int $max )

Wiele generatorów liczb losowych w starych libc ma niepewne albo nieznane charakterystyki i są powolne. Domyślnie PHP używa generatora liczb losowych z libc w funkcji rand(). Funkcja mt_rand() jest jej zamiennikiem. Używa ona generatora liczb losowych o znanej charakterystyce używając » Mersenne Twistera, który generuje liczby losowe czterokrotnie szybciej niż średnio funkcja rand() z glibc.

Jeśli funkcja zostanie wywołana bez opcjonalnych argumentów min i max, funkcja mt_rand() zwróci liczbę pseudolosową z przedziału pomiędzy 0 a RAND_MAX. Jeśli na przykład potrzebujesz liczby losowej z przedziału od 5 do 15 włącznie, użyj mt_rand (5, 15).

Przykład #1 Przykład mt_rand()

<?php
echo mt_rand() . "\n";
echo mt_rand() . "\n";

echo mt_rand(5, 15);
?>

Powyższy przykład wyświetli coś podobnego do:

1604716014
1478613278
6

Informacja: Od PHP 4.2.0 nie ma potrzeby inicjalizować generatora liczb losowych funkcją srand() lub mt_srand(), ponieważ dzieje się to automatycznie.

Informacja:

W wersjach przed 3.0.7 argument max znaczył zakres. Aby otrzymać takie same wyniki w tychże wersjach, należy użyć mt_rand (5, 11) aby otrzymać liczbę losową z przedziału od 5 do 15.

Patrz także: mt_srand(), mt_getrandmax() i rand().

mt_getrandmax
mt_srand
Math Funkcje


Inicjuje generator Mersenne Twister

mt_rand
octdec
Math Funkcje
PHP Manual

mt_srand

(PHP 4, PHP 5)

mt_srand — Inicjuje generator Mersenne Twister

Opis

void mt_srand ([ int $ziarno ] )

Inicjuje generator liczb losowych za pomocą ziarna ziarno. Począwszy od PHP 4.2.0, parametr ziarno stał się opcjnalny i nie bierze udziału przy losowaniu wartości, jeśli go pominięto.

Przykład #1 mt_srand() przykład

<?php
// naziarnij mikrosekundami
function make_seed()
{
    list($usec,$sec) = explode(" ", microtime());
    return ((float)$sec+(float)$usec) * 100000;
}
mt_srand(make_seed());
$randval = mt_rand();
?>

Informacja: Od PHP 4.2.0 nie ma potrzeby inicjalizować generatora liczb losowych funkcją srand() lub mt_srand(), ponieważ dzieje się to automatycznie.

   Patrz także:
mt_rand(),
   mt_getrandmax() i
srand().

mt_rand
octdec
Math Funkcje


Konwersja liczby ósemkowej do dziesiętnej

mt_srand
pi
Math Funkcje
PHP Manual

octdec

(PHP 4, PHP 5)

octdec — Konwersja liczby ósemkowej do dziesiętnej

Opis

number octdec ( string $liczba_ósemkowa )

Zwraca dziesiętny odpowiednik liczby ósemkowej podanej jako argument liczba_ósemkowa. Największą liczbą, jaka może być skonwertowana jest 17777777777 ósemkowo, czyli 2147483647 dziesiętnie. Od PHP 4.1.0, funkcja potrafi skonwertować większe liczby. Wtedy zwracana jest wartość typu float.

Przykład #1 octdec() przykład

<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>

Powyższy przykład wyświetli:

63
45

Patrz także:
decoct(),
bindec(),
hexdec() i
base_convert().

mt_srand
pi
Math Funkcje


Wartość liczby Pi

octdec
pow
Math Funkcje
PHP Manual

pi

(PHP 4, PHP 5)

pi — Wartość liczby Pi

Opis

float pi ( void )

Zwraca przybliżoną wartość liczby pi. Zwracana wartość typu float ma precyzję określoną w dyrektywie precision w pliku php.ini, domyślnie równą 14. Można także użyć stałej M_PI, która daje taki sam wynik jak funkcja pi().

Przykład #1 pi() przykład

<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>

octdec
pow
Math Funkcje


Potęgowanie

pi
rad2deg
Math Funkcje
PHP Manual

pow

(PHP 4, PHP 5)

pow — Potęgowanie

Opis

number pow ( number $podstawa , number $wykładnik )

Zwraca argument podstawa podniesiony do potęgi wykładnik. Jeśli możliwe, funkcja zwróci typ integer.

Jeśli nie da się obliczyć potęgi, zostanie wyświetlone ostrzeżenie a funkcja pow() zwróci FALSE. Począwszy od PHP 4.2.0 pow() nie emituje żadnych ostrzeżeń.

Informacja:

PHP nie może cannot operować na ujemnej podstawies.

Przykład #1 Parę przykładów z pow()

<?php

var_dump( pow(2,8) ); // int(256)
echo pow(-1,20); // 1
echo pow(0, 0); // 1

echo pow(-1, 5.5); // błąd

?>
Ostrzeżenie

W PHP 4.0.6 i wcześniejszych funkcja pow() zawsze zwracała typ float i nie wyświetlała ostrzeżeń.

   Patrz także:
exp()
sqrt(),
bcpow() i
gmp_pow(),

pi
rad2deg
Math Funkcje


Przelicza radiany na stopnie.

pow
rand
Math Funkcje
PHP Manual

rad2deg

(PHP 4, PHP 5)

rad2deg — Przelicza radiany na stopnie.

Opis

float rad2deg ( float $liczba )

rad2deg() przelicza kąt liczba podany w radianach na jego odpowiednik w stopniach.

Przykład #1 Przykład użycia rad2deg()

<?php

echo rad2deg(M_PI_4); // 45

?>

Patrz także: deg2rad().

pow
rand
Math Funkcje


Generuje losową liczbę stałoprzecinkową

rad2deg
round
Math Funkcje
PHP Manual

rand

(PHP 4, PHP 5)

rand — Generuje losową liczbę stałoprzecinkową

Opis

int rand ([ int $min [, int $max ]] )

Jeśli wywołana bez opcjonalnych argumentów min i max, funkcja rand() zwraca pseudolosową liczbę stałoprzecinkową z przedziału pomiędzy 0 a RAND_MAX. Dla uzyskania liczby losowej z przedziału np. od 5 do 15 (włącznie), należy wywołać rand (5,15).

Przykład #1 Przykład użycia rand()

<?php
echo rand() . "\n";
echo rand() . "\n";

echo rand(5, 15);
?>

Powyższy przykład wyświetli coś podobnego do:

7771
22264
11

Informacja: Na niektórych platformach (jak na przykład Windows) RAND_MAX to tylko 32768. Aby uzyskać wartości większe niż 32768, należy podać odpowiednie wartości argumentów min and max, co pozwoli na wygenerowanie wartości większych niż RAND_MAX. Można też użyć funkcji mt_rand().

Informacja: Od PHP 4.2.0 nie ma potrzeby inicjalizować generatora liczb losowych funkcją srand() lub mt_srand(), ponieważ dzieje się to automatycznie.

Informacja:

W wersjach przed 3.0.7 argument max znaczył zakres. Aby otrzymać takie same wyniki w tychże wersjach, należy użyć rand (5, 11) aby otrzymać liczbę losową z przedziału od 5 do 15.

Patrz także:
srand(),
getrandmax() i
mt_rand().

rad2deg
round
Math Funkcje


Zaokrągla liczbę zmiennoprzecinkową

rand
sin
Math Funkcje
PHP Manual

round

(PHP 4, PHP 5)

round — Zaokrągla liczbę zmiennoprzecinkową

Opis

float round ( float $wartość [, int $dokładność ] )

Zwraca zaokrągloną wartość argumentu wartość do miejsca po przecinku określonego w dokładność. Argument dokładność może być także ujemny lub równy zero (domyślnie).

Przykład #1 Przykłady użycia round()

<?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?>

Informacja: PHP domyślnie nie obsługuje poprawnie łańcuchów znaków takich jak "12,300.2". Zobacz konwersje z łańcuchów znaków .

Informacja: Argument dokładność został dodany w PHP 4.

Patrz także:
ceil(),
floor() i
number_format().

rand
sin
Math Funkcje


Oblicza sinus kąta

round
sinh
Math Funkcje
PHP Manual

sin

(PHP 4, PHP 5)

sin — Oblicza sinus kąta

Opis

float sin ( void )

Funkcja sin() zwraca sinus kąta argument podanego w radianach.

Przykład #1 Przykład użycia sin()

<?php

// Dokładność jest zależna od dyrektyw konfiguracyjnych
echo sin(deg2rad(60)); //  0.866025403 ...
echo sin(60);          // -0.304810621 ...

?>

Patrz także:
asin(),
cos(),
tan() i
deg2rad().

round
sinh
Math Funkcje


Sinus hiperboliczny

sin
sqrt
Math Funkcje
PHP Manual

sinh

(PHP 4 >= 4.1.0, PHP 5)

sinh — Sinus hiperboliczny

Opis

float sinh ( float $arg )

Zwraca sinus hiperboliczny z liczby arg, definiowany jako (exp(arg) - exp(-arg))/2.

Patrz także:
sin(),
asinh(),
cos() i
tan().

sin
sqrt
Math Funkcje


Pierwiastek kwadratowy

sinh
srand
Math Funkcje
PHP Manual

sqrt

(PHP 4, PHP 5)

sqrt — Pierwiastek kwadratowy

Opis

float sqrt ( float $argument )

Zwraca pierwiastek kwadratowy z argumentu.

Przykład #1 Przykład użycia sqrt()

<?php
// Precyzja jest zależna od aktualnych dyrektyw konfiguracyjnych
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

sinh
srand
Math Funkcje


Inicjuje generator liczb losowych

sqrt
tan
Math Funkcje
PHP Manual

srand

(PHP 4, PHP 5)

srand — Inicjuje generator liczb losowych

Opis

void srand ([ int $ziarno ] )

Inicjuje generator liczb losowych za pomocą argumentu ziarno. W PHP 4.2.0 i nowszych, argument ziarno jest opcjonalny - domyślnie generator inicjowany jest wartością losową.

Przykład #1 Przykład użycia srand()

<?php
// zainicjalizuj mikrosekundami
function make_seed()
{
    list($usec,$sec) = explode(" ", microtime());
    return ((float)$sec+(float)$usec) * 100000;
}
srand(make_seed());
$randval = rand();
?>

Informacja: Od PHP 4.2.0 nie ma potrzeby inicjalizować generatora liczb losowych funkcją srand() lub mt_srand(), ponieważ dzieje się to automatycznie.

Patrz także:
rand(),
getrandmax() i
mt_srand().

sqrt
tan
Math Funkcje


Oblicza tangens kąta

srand
tanh
Math Funkcje
PHP Manual

tan

(PHP 4, PHP 5)

tan — Oblicza tangens kąta

Opis

float tan ( float $argument )

Funkcja tan() zwraca tangens kąta argument podanego w radianach.

Przykład #1 Przykład użycia tan()

<?php

echo tan(M_PI_4); // 1

?>

Patrz także:
atan(),
sin(),
cos() i
deg2rad().

srand
tanh
Math Funkcje


Tangens hiperboliczny

tan
Statistics
Math Funkcje
PHP Manual

tanh

(PHP 4 >= 4.1.0, PHP 5)

tanh — Tangens hiperboliczny

Opis

float tanh ( float $arg )

Zwraca tangens hiperboliczny z liczby arg, definiowanej jako sinh(arg)/cosh(arg).

Patrz także:
tan(),
atanh(),
sin() i
cos().

tan
Statistics
Math Funkcje


Statistics

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Statistic Funkcje
    • stats_absolute_deviation — Returns the absolute deviation of an array of values
    • stats_cdf_beta — CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.
    • stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others.
    • stats_cdf_cauchy — Not documented
    • stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others.
    • stats_cdf_exponential — Not documented
    • stats_cdf_f — Calculates any one parameter of the F distribution given values for the others.
    • stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others.
    • stats_cdf_laplace — Not documented
    • stats_cdf_logistic — Not documented
    • stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others.
    • stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others.
    • stats_cdf_noncentral_f — Calculates any one parameter of the Non-central F distribution given values for the others.
    • stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others.
    • stats_cdf_t — Calculates any one parameter of the T distribution given values for the others.
    • stats_cdf_uniform — Not documented
    • stats_cdf_weibull — Not documented
    • stats_covariance — Computes the covariance of two data sets
    • stats_den_uniform — Not documented
    • stats_dens_beta — Not documented
    • stats_dens_cauchy — Not documented
    • stats_dens_chisquare — Not documented
    • stats_dens_exponential — Not documented
    • stats_dens_f — Opis
    • stats_dens_gamma — Not documented
    • stats_dens_laplace — Not documented
    • stats_dens_logistic — Not documented
    • stats_dens_negative_binomial — Not documented
    • stats_dens_normal — Not documented
    • stats_dens_pmf_binomial — Not documented
    • stats_dens_pmf_hypergeometric — Opis
    • stats_dens_pmf_poisson — Not documented
    • stats_dens_t — Not documented
    • stats_dens_weibull — Not documented
    • stats_harmonic_mean — Returns the harmonic mean of an array of values
    • stats_kurtosis — Computes the kurtosis of the data in the array
    • stats_rand_gen_beta — Generates beta random deviate
    • stats_rand_gen_chisquare — Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.
    • stats_rand_gen_exponential — Generates a single random deviate from an exponential distribution with mean "av"
    • stats_rand_gen_f — Generates a random deviate
    • stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma — Generates random deviates from a gamma distribution
    • stats_rand_gen_ibinomial_negative — Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).
    • stats_rand_gen_ibinomial — Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE
    • stats_rand_gen_int — Generates random integer between 1 and 2147483562
    • stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).
    • stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncenral_chisquare — Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0
    • stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.
    • stats_rand_gen_noncentral_t — Generates a single random deviate from a noncentral T distribution
    • stats_rand_gen_normal — Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.
    • stats_rand_gen_t — Generates a single random deviate from a T distribution
    • stats_rand_get_seeds — Not documented
    • stats_rand_phrase_to_seeds — generate two seeds for the RGN random number generator
    • stats_rand_ranf — Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator
    • stats_rand_setall — Not documented
    • stats_skew — Computes the skewness of the data in the array
    • stats_standard_deviation — Returns the standard deviation
    • stats_stat_binomial_coef — Not documented
    • stats_stat_correlation — Not documented
    • stats_stat_gennch — Not documented
    • stats_stat_independent_t — Not documented
    • stats_stat_innerproduct — Opis
    • stats_stat_noncentral_t — Calculates any one parameter of the noncentral t distribution give values for the others.
    • stats_stat_paired_t — Not documented
    • stats_stat_percentile — Not documented
    • stats_stat_powersum — Not documented
    • stats_variance — Returns the population variance
tanh
Wstęp
Rozszerzenia matematyczne


Wstęp

This is the statistics extension. It contains few dozens of functions useful for statistical computations. It is a wrapper around 2 scientific libraries, namely DCDFLIB (Library of C routines for Cumulative Distributions Functions, Inverses, and Other parameters) by B. Brown & J. Lavato and RANDLIB by Barry Brown, James Lavato & Kathy Russell. Includes CD and PD functions.

Statistics
Instalacja/Konfiguracja
Statistics


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Statistics


Wymagania

No external libraries are needed. The extension comes bundled with the libraries used.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/stats.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Statistic Funkcje
Statistics


Statistic Funkcje

Spis treści

  • stats_absolute_deviation — Returns the absolute deviation of an array of values
  • stats_cdf_beta — CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.
  • stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others.
  • stats_cdf_cauchy — Not documented
  • stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others.
  • stats_cdf_exponential — Not documented
  • stats_cdf_f — Calculates any one parameter of the F distribution given values for the others.
  • stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others.
  • stats_cdf_laplace — Not documented
  • stats_cdf_logistic — Not documented
  • stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others.
  • stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others.
  • stats_cdf_noncentral_f — Calculates any one parameter of the Non-central F distribution given values for the others.
  • stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others.
  • stats_cdf_t — Calculates any one parameter of the T distribution given values for the others.
  • stats_cdf_uniform — Not documented
  • stats_cdf_weibull — Not documented
  • stats_covariance — Computes the covariance of two data sets
  • stats_den_uniform — Not documented
  • stats_dens_beta — Not documented
  • stats_dens_cauchy — Not documented
  • stats_dens_chisquare — Not documented
  • stats_dens_exponential — Not documented
  • stats_dens_f — Opis
  • stats_dens_gamma — Not documented
  • stats_dens_laplace — Not documented
  • stats_dens_logistic — Not documented
  • stats_dens_negative_binomial — Not documented
  • stats_dens_normal — Not documented
  • stats_dens_pmf_binomial — Not documented
  • stats_dens_pmf_hypergeometric — Opis
  • stats_dens_pmf_poisson — Not documented
  • stats_dens_t — Not documented
  • stats_dens_weibull — Not documented
  • stats_harmonic_mean — Returns the harmonic mean of an array of values
  • stats_kurtosis — Computes the kurtosis of the data in the array
  • stats_rand_gen_beta — Generates beta random deviate
  • stats_rand_gen_chisquare — Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.
  • stats_rand_gen_exponential — Generates a single random deviate from an exponential distribution with mean "av"
  • stats_rand_gen_f — Generates a random deviate
  • stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)
  • stats_rand_gen_gamma — Generates random deviates from a gamma distribution
  • stats_rand_gen_ibinomial_negative — Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).
  • stats_rand_gen_ibinomial — Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE
  • stats_rand_gen_int — Generates random integer between 1 and 2147483562
  • stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).
  • stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
  • stats_rand_gen_noncenral_chisquare — Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0
  • stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.
  • stats_rand_gen_noncentral_t — Generates a single random deviate from a noncentral T distribution
  • stats_rand_gen_normal — Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.
  • stats_rand_gen_t — Generates a single random deviate from a T distribution
  • stats_rand_get_seeds — Not documented
  • stats_rand_phrase_to_seeds — generate two seeds for the RGN random number generator
  • stats_rand_ranf — Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator
  • stats_rand_setall — Not documented
  • stats_skew — Computes the skewness of the data in the array
  • stats_standard_deviation — Returns the standard deviation
  • stats_stat_binomial_coef — Not documented
  • stats_stat_correlation — Not documented
  • stats_stat_gennch — Not documented
  • stats_stat_independent_t — Not documented
  • stats_stat_innerproduct — Opis
  • stats_stat_noncentral_t — Calculates any one parameter of the noncentral t distribution give values for the others.
  • stats_stat_paired_t — Not documented
  • stats_stat_percentile — Not documented
  • stats_stat_powersum — Not documented
  • stats_variance — Returns the population variance
Stałe predefiniowane
stats_absolute_deviation
Statistics


Returns the absolute deviation of an array of values

Statistic Funkcje
stats_cdf_beta
Statistic Funkcje
PHP Manual

stats_absolute_deviation

(PECL stats >= 1.0.0)

stats_absolute_deviation — Returns the absolute deviation of an array of values

Opis

float stats_absolute_deviation ( array $a )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

a

Zwracane wartości

Statistic Funkcje
stats_cdf_beta
Statistic Funkcje


CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

stats_absolute_deviation
stats_cdf_binomial
Statistic Funkcje
PHP Manual

stats_cdf_beta

(PECL stats >= 1.0.0)

stats_cdf_beta — CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.

Opis

float stats_cdf_beta ( float $par1 , float $par2 , float $par3 , int $which )

Method Cumulative distribution function (P) is calculated directly by code associated with the following reference. DiDinato, A. R. and Morris, A. H. Algorithm 708: Significant Digit Computation of the Incomplete Beta Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373. Computation of other parameters involve a search for a value that produces the desired value of P. The search relies on the monotonicity of P with the other parameter. Note The beta density is proportional to t^(A-1) * (1-t)^(B-1) Arguments P -- The integral from 0 to X of the chi-square distribution. Input range: [0, 1]. Q -- 1-P. Input range: [0, 1]. P + Q = 1.0. X -- Upper limit of integration of beta density. Input range: [0,1]. Search range: [0,1] Y -- 1-X. Input range: [0,1]. Search range: [0,1] X + Y = 1.0. A -- The first parameter of the beta density. Input range: (0, +infinity). Search range: [1D-100,1D100] B -- The second parameter of the beta density. Input range: (0, +infinity). Search range: [1D-100,1D100] STATUS -- 0 if calculation completed correctly -I if input parameter number I is out of range 1 if answer appears to be lower than lowest search bound 2 if answer appears to be higher than greatest search bound 3 if P + Q .ne. 1 4 if X + Y .ne. 1 BOUND -- Undefined if STATUS is 0 Bound exceeded by parameter number I if STATUS is negative. Lower search bound if STATUS is 1. Upper search bound if STATUS is 2.

Parametry

par1

par2

par3

which

Integer indicating which of the next four argument values is to be calculated from the others. Legal range: 1..4 which = 1 : Calculate P and Q from X,Y,A and B which = 2 : Calculate X and Y from P,Q,A and B which = 3 : Calculate A from P,Q,X,Y and B which = 4 : Calculate B from P,Q,X,Y and A

Zwracane wartości

STATUS -- 0 if calculation completed correctly -I if input parameter number I is out of range 1 if answer appears to be lower than lowest search bound 2 if answer appears to be higher than greatest search bound 3 if P + Q .ne. 1 4 if X + Y .ne. 1

stats_absolute_deviation
stats_cdf_binomial
Statistic Funkcje


Calculates any one parameter of the binomial distribution given values for the others.

stats_cdf_beta
stats_cdf_cauchy
Statistic Funkcje
PHP Manual

stats_cdf_binomial

(PECL stats >= 1.0.0)

stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others.

Opis

float stats_cdf_binomial ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_beta
stats_cdf_cauchy
Statistic Funkcje


Not documented

stats_cdf_binomial
stats_cdf_chisquare
Statistic Funkcje
PHP Manual

stats_cdf_cauchy

(PECL stats >= 1.0.0)

stats_cdf_cauchy — Not documented

Opis

float stats_cdf_cauchy ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_binomial
stats_cdf_chisquare
Statistic Funkcje


Calculates any one parameter of the chi-square distribution given values for the others.

stats_cdf_cauchy
stats_cdf_exponential
Statistic Funkcje
PHP Manual

stats_cdf_chisquare

(PECL stats >= 1.0.0)

stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others.

Opis

float stats_cdf_chisquare ( float $par1 , float $par2 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

which

Zwracane wartości

stats_cdf_cauchy
stats_cdf_exponential
Statistic Funkcje


Not documented

stats_cdf_chisquare
stats_cdf_f
Statistic Funkcje
PHP Manual

stats_cdf_exponential

(PECL stats >= 1.0.0)

stats_cdf_exponential — Not documented

Opis

float stats_cdf_exponential ( float $par1 , float $par2 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

which

Zwracane wartości

stats_cdf_chisquare
stats_cdf_f
Statistic Funkcje


Calculates any one parameter of the F distribution given values for the others.

stats_cdf_exponential
stats_cdf_gamma
Statistic Funkcje
PHP Manual

stats_cdf_f

(PECL stats >= 1.0.0)

stats_cdf_f — Calculates any one parameter of the F distribution given values for the others.

Opis

float stats_cdf_f ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_exponential
stats_cdf_gamma
Statistic Funkcje


Calculates any one parameter of the gamma distribution given values for the others.

stats_cdf_f
stats_cdf_laplace
Statistic Funkcje
PHP Manual

stats_cdf_gamma

(PECL stats >= 1.0.0)

stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others.

Opis

float stats_cdf_gamma ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_f
stats_cdf_laplace
Statistic Funkcje


Not documented

stats_cdf_gamma
stats_cdf_logistic
Statistic Funkcje
PHP Manual

stats_cdf_laplace

(PECL stats >= 1.0.0)

stats_cdf_laplace — Not documented

Opis

float stats_cdf_laplace ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_gamma
stats_cdf_logistic
Statistic Funkcje


Not documented

stats_cdf_laplace
stats_cdf_negative_binomial
Statistic Funkcje
PHP Manual

stats_cdf_logistic

(PECL stats >= 1.0.0)

stats_cdf_logistic — Not documented

Opis

float stats_cdf_logistic ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_laplace
stats_cdf_negative_binomial
Statistic Funkcje


Calculates any one parameter of the negative binomial distribution given values for the others.

stats_cdf_logistic
stats_cdf_noncentral_chisquare
Statistic Funkcje
PHP Manual

stats_cdf_negative_binomial

(PECL stats >= 1.0.0)

stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others.

Opis

float stats_cdf_negative_binomial ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_logistic
stats_cdf_noncentral_chisquare
Statistic Funkcje


Calculates any one parameter of the non-central chi-square distribution given values for the others.

stats_cdf_negative_binomial
stats_cdf_noncentral_f
Statistic Funkcje
PHP Manual

stats_cdf_noncentral_chisquare

(PECL stats >= 1.0.0)

stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others.

Opis

float stats_cdf_noncentral_chisquare ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_negative_binomial
stats_cdf_noncentral_f
Statistic Funkcje


Calculates any one parameter of the Non-central F distribution given values for the others.

stats_cdf_noncentral_chisquare
stats_cdf_poisson
Statistic Funkcje
PHP Manual

stats_cdf_noncentral_f

(PECL stats >= 1.0.0)

stats_cdf_noncentral_f — Calculates any one parameter of the Non-central F distribution given values for the others.

Opis

float stats_cdf_noncentral_f ( float $par1 , float $par2 , float $par3 , float $par4 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

par4

which

Zwracane wartości

stats_cdf_noncentral_chisquare
stats_cdf_poisson
Statistic Funkcje


Calculates any one parameter of the Poisson distribution given values for the others.

stats_cdf_noncentral_f
stats_cdf_t
Statistic Funkcje
PHP Manual

stats_cdf_poisson

(PECL stats >= 1.0.0)

stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others.

Opis

float stats_cdf_poisson ( float $par1 , float $par2 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

which

Zwracane wartości

stats_cdf_noncentral_f
stats_cdf_t
Statistic Funkcje


Calculates any one parameter of the T distribution given values for the others.

stats_cdf_poisson
stats_cdf_uniform
Statistic Funkcje
PHP Manual

stats_cdf_t

(PECL stats >= 1.0.0)

stats_cdf_t — Calculates any one parameter of the T distribution given values for the others.

Opis

float stats_cdf_t ( float $par1 , float $par2 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

which

Zwracane wartości

stats_cdf_poisson
stats_cdf_uniform
Statistic Funkcje


Not documented

stats_cdf_t
stats_cdf_weibull
Statistic Funkcje
PHP Manual

stats_cdf_uniform

(PECL stats >= 1.0.0)

stats_cdf_uniform — Not documented

Opis

float stats_cdf_uniform ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_t
stats_cdf_weibull
Statistic Funkcje


Not documented

stats_cdf_uniform
stats_covariance
Statistic Funkcje
PHP Manual

stats_cdf_weibull

(PECL stats >= 1.0.0)

stats_cdf_weibull — Not documented

Opis

float stats_cdf_weibull ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_cdf_uniform
stats_covariance
Statistic Funkcje


Computes the covariance of two data sets

stats_cdf_weibull
stats_den_uniform
Statistic Funkcje
PHP Manual

stats_covariance

(PECL stats >= 1.0.0)

stats_covariance — Computes the covariance of two data sets

Opis

float stats_covariance ( array $a , array $b )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

a

b

Zwracane wartości

stats_cdf_weibull
stats_den_uniform
Statistic Funkcje


Not documented

stats_covariance
stats_dens_beta
Statistic Funkcje
PHP Manual

stats_den_uniform

(PECL stats >= 1.0.0)

stats_den_uniform — Not documented

Opis

float stats_den_uniform ( float $x , float $a , float $b )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

a

b

Zwracane wartości

stats_covariance
stats_dens_beta
Statistic Funkcje


Not documented

stats_den_uniform
stats_dens_cauchy
Statistic Funkcje
PHP Manual

stats_dens_beta

(PECL stats >= 1.0.0)

stats_dens_beta — Not documented

Opis

float stats_dens_beta ( float $x , float $a , float $b )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

a

b

Zwracane wartości

stats_den_uniform
stats_dens_cauchy
Statistic Funkcje


Not documented

stats_dens_beta
stats_dens_chisquare
Statistic Funkcje
PHP Manual

stats_dens_cauchy

(PECL stats >= 1.0.0)

stats_dens_cauchy — Not documented

Opis

float stats_dens_cauchy ( float $x , float $ave , float $stdev )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

ave

stdev

Zwracane wartości

stats_dens_beta
stats_dens_chisquare
Statistic Funkcje


Not documented

stats_dens_cauchy
stats_dens_exponential
Statistic Funkcje
PHP Manual

stats_dens_chisquare

(PECL stats >= 1.0.0)

stats_dens_chisquare — Not documented

Opis

float stats_dens_chisquare ( float $x , float $dfr )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

dfr

Zwracane wartości

stats_dens_cauchy
stats_dens_exponential
Statistic Funkcje


Not documented

stats_dens_chisquare
stats_dens_f
Statistic Funkcje
PHP Manual

stats_dens_exponential

(PECL stats >= 1.0.0)

stats_dens_exponential — Not documented

Opis

float stats_dens_exponential ( float $x , float $scale )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

scale

Zwracane wartości

stats_dens_chisquare
stats_dens_f
Statistic Funkcje


stats_dens_exponential
stats_dens_gamma
Statistic Funkcje
PHP Manual

stats_dens_f

(PECL stats >= 1.0.0)

stats_dens_f —

Opis

float stats_dens_f ( float $x , float $dfr1 , float $dfr2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

dfr1

dfr2

Zwracane wartości

stats_dens_exponential
stats_dens_gamma
Statistic Funkcje


Not documented

stats_dens_f
stats_dens_laplace
Statistic Funkcje
PHP Manual

stats_dens_gamma

(PECL stats >= 1.0.0)

stats_dens_gamma — Not documented

Opis

float stats_dens_gamma ( float $x , float $shape , float $scale )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

shape

scale

Zwracane wartości

stats_dens_f
stats_dens_laplace
Statistic Funkcje


Not documented

stats_dens_gamma
stats_dens_logistic
Statistic Funkcje
PHP Manual

stats_dens_laplace

(PECL stats >= 1.0.0)

stats_dens_laplace — Not documented

Opis

float stats_dens_laplace ( float $x , float $ave , float $stdev )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

ave

stdev

Zwracane wartości

stats_dens_gamma
stats_dens_logistic
Statistic Funkcje


Not documented

stats_dens_laplace
stats_dens_negative_binomial
Statistic Funkcje
PHP Manual

stats_dens_logistic

(PECL stats >= 1.0.0)

stats_dens_logistic — Not documented

Opis

float stats_dens_logistic ( float $x , float $ave , float $stdev )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

ave

stdev

Zwracane wartości

stats_dens_laplace
stats_dens_negative_binomial
Statistic Funkcje


Not documented

stats_dens_logistic
stats_dens_normal
Statistic Funkcje
PHP Manual

stats_dens_negative_binomial

(PECL stats >= 1.0.0)

stats_dens_negative_binomial — Not documented

Opis

float stats_dens_negative_binomial ( float $x , float $n , float $pi )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

n

pi

Zwracane wartości

stats_dens_logistic
stats_dens_normal
Statistic Funkcje


Not documented

stats_dens_negative_binomial
stats_dens_pmf_binomial
Statistic Funkcje
PHP Manual

stats_dens_normal

(PECL stats >= 1.0.0)

stats_dens_normal — Not documented

Opis

float stats_dens_normal ( float $x , float $ave , float $stdev )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

ave

stdev

Zwracane wartości

stats_dens_negative_binomial
stats_dens_pmf_binomial
Statistic Funkcje


Not documented

stats_dens_normal
stats_dens_pmf_hypergeometric
Statistic Funkcje
PHP Manual

stats_dens_pmf_binomial

(PECL stats >= 1.0.0)

stats_dens_pmf_binomial — Not documented

Opis

float stats_dens_pmf_binomial ( float $x , float $n , float $pi )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

n

pi

Zwracane wartości

stats_dens_normal
stats_dens_pmf_hypergeometric
Statistic Funkcje


stats_dens_pmf_binomial
stats_dens_pmf_poisson
Statistic Funkcje
PHP Manual

stats_dens_pmf_hypergeometric

(PECL stats >= 1.0.0)

stats_dens_pmf_hypergeometric —

Opis

float stats_dens_pmf_hypergeometric ( float $n1 , float $n2 , float $N1 , float $N2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

n1

n2

N1

N2

Zwracane wartości

stats_dens_pmf_binomial
stats_dens_pmf_poisson
Statistic Funkcje


Not documented

stats_dens_pmf_hypergeometric
stats_dens_t
Statistic Funkcje
PHP Manual

stats_dens_pmf_poisson

(PECL stats >= 1.0.0)

stats_dens_pmf_poisson — Not documented

Opis

float stats_dens_pmf_poisson ( float $x , float $lb )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

lb

Zwracane wartości

stats_dens_pmf_hypergeometric
stats_dens_t
Statistic Funkcje


Not documented

stats_dens_pmf_poisson
stats_dens_weibull
Statistic Funkcje
PHP Manual

stats_dens_t

(PECL stats >= 1.0.0)

stats_dens_t — Not documented

Opis

float stats_dens_t ( float $x , float $dfr )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

dfr

Zwracane wartości

stats_dens_pmf_poisson
stats_dens_weibull
Statistic Funkcje


Not documented

stats_dens_t
stats_harmonic_mean
Statistic Funkcje
PHP Manual

stats_dens_weibull

(PECL stats >= 1.0.0)

stats_dens_weibull — Not documented

Opis

float stats_dens_weibull ( float $x , float $a , float $b )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

a

b

Zwracane wartości

stats_dens_t
stats_harmonic_mean
Statistic Funkcje


Returns the harmonic mean of an array of values

stats_dens_weibull
stats_kurtosis
Statistic Funkcje
PHP Manual

stats_harmonic_mean

(PECL stats >= 1.0.0)

stats_harmonic_mean — Returns the harmonic mean of an array of values

Opis

number stats_harmonic_mean ( array $a )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

a

Zwracane wartości

stats_dens_weibull
stats_kurtosis
Statistic Funkcje


Computes the kurtosis of the data in the array

stats_harmonic_mean
stats_rand_gen_beta
Statistic Funkcje
PHP Manual

stats_kurtosis

(PECL stats >= 1.0.0)

stats_kurtosis — Computes the kurtosis of the data in the array

Opis

float stats_kurtosis ( array $a )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

a

Zwracane wartości

stats_harmonic_mean
stats_rand_gen_beta
Statistic Funkcje


Generates beta random deviate

stats_kurtosis
stats_rand_gen_chisquare
Statistic Funkcje
PHP Manual

stats_rand_gen_beta

(PECL stats >= 1.0.0)

stats_rand_gen_beta — Generates beta random deviate

Opis

float stats_rand_gen_beta ( float $a , float $b )

Returns a random deviate from the beta distribution with parameters A and B. The density of the beta is x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x <. Method R. C. H. Cheng.

Parametry

a

b

Zwracane wartości

stats_kurtosis
stats_rand_gen_chisquare
Statistic Funkcje


Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

stats_rand_gen_beta
stats_rand_gen_exponential
Statistic Funkcje
PHP Manual

stats_rand_gen_chisquare

(PECL stats >= 1.0.0)

stats_rand_gen_chisquare — Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.

Opis

float stats_rand_gen_chisquare ( float $df )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

df

Zwracane wartości

stats_rand_gen_beta
stats_rand_gen_exponential
Statistic Funkcje


Generates a single random deviate from an exponential distribution with mean "av"

stats_rand_gen_chisquare
stats_rand_gen_f
Statistic Funkcje
PHP Manual

stats_rand_gen_exponential

(PECL stats >= 1.0.0)

stats_rand_gen_exponential — Generates a single random deviate from an exponential distribution with mean "av"

Opis

float stats_rand_gen_exponential ( float $av )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

av

Zwracane wartości

stats_rand_gen_chisquare
stats_rand_gen_f
Statistic Funkcje


Generates a random deviate

stats_rand_gen_exponential
stats_rand_gen_funiform
Statistic Funkcje
PHP Manual

stats_rand_gen_f

(PECL stats >= 1.0.0)

stats_rand_gen_f — Generates a random deviate

Opis

float stats_rand_gen_f ( float $dfn , float $dfd )

Generates a random deviate from the F (variance ratio) distribution with "dfn" degrees of freedom in the numerator and "dfd" degrees of freedom in the denominator. Method : directly generates ratio of chisquare variates.

Parametry

dfn

dfd

Zwracane wartości

stats_rand_gen_exponential
stats_rand_gen_funiform
Statistic Funkcje


Generates uniform float between low (exclusive) and high (exclusive)

stats_rand_gen_f
stats_rand_gen_gamma
Statistic Funkcje
PHP Manual

stats_rand_gen_funiform

(PECL stats >= 1.0.0)

stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)

Opis

float stats_rand_gen_funiform ( float $low , float $high )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

low

high

Zwracane wartości

stats_rand_gen_f
stats_rand_gen_gamma
Statistic Funkcje


Generates random deviates from a gamma distribution

stats_rand_gen_funiform
stats_rand_gen_ibinomial_negative
Statistic Funkcje
PHP Manual

stats_rand_gen_gamma

(PECL stats >= 1.0.0)

stats_rand_gen_gamma — Generates random deviates from a gamma distribution

Opis

float stats_rand_gen_gamma ( float $a , float $r )

Generates random deviates from the gamma distribution whose density is (A**R)/Gamma(R) * X**(R-1) * Exp(-A*X).

Parametry

a

location parameter of Gamma distribution (a > 0).

r

shape parameter of Gamma distribution (r > 0).

Zwracane wartości

stats_rand_gen_funiform
stats_rand_gen_ibinomial_negative
Statistic Funkcje


Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).

stats_rand_gen_gamma
stats_rand_gen_ibinomial
Statistic Funkcje
PHP Manual

stats_rand_gen_ibinomial_negative

(PECL stats >= 1.0.0)

stats_rand_gen_ibinomial_negative — Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).

Opis

int stats_rand_gen_ibinomial_negative ( int $n , float $p )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

n

p

Zwracane wartości

stats_rand_gen_gamma
stats_rand_gen_ibinomial
Statistic Funkcje


Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE

stats_rand_gen_ibinomial_negative
stats_rand_gen_int
Statistic Funkcje
PHP Manual

stats_rand_gen_ibinomial

(PECL stats >= 1.0.0)

stats_rand_gen_ibinomial — Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE

Opis

int stats_rand_gen_ibinomial ( int $n , float $pp )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

n

pp

Zwracane wartości

stats_rand_gen_ibinomial_negative
stats_rand_gen_int
Statistic Funkcje


Generates random integer between 1 and 2147483562

stats_rand_gen_ibinomial
stats_rand_gen_ipoisson
Statistic Funkcje
PHP Manual

stats_rand_gen_int

(PECL stats >= 1.0.0)

stats_rand_gen_int — Generates random integer between 1 and 2147483562

Opis

int stats_rand_gen_int ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Zwracane wartości

stats_rand_gen_ibinomial
stats_rand_gen_ipoisson
Statistic Funkcje


Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

stats_rand_gen_int
stats_rand_gen_iuniform
Statistic Funkcje
PHP Manual

stats_rand_gen_ipoisson

(PECL stats >= 1.0.0)

stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).

Opis

int stats_rand_gen_ipoisson ( float $mu )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

mu

Zwracane wartości

stats_rand_gen_int
stats_rand_gen_iuniform
Statistic Funkcje


Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

stats_rand_gen_ipoisson
stats_rand_gen_noncenral_chisquare
Statistic Funkcje
PHP Manual

stats_rand_gen_iuniform

(PECL stats >= 1.0.0)

stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

Opis

int stats_rand_gen_iuniform ( int $low , int $high )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

low

high

Zwracane wartości

stats_rand_gen_ipoisson
stats_rand_gen_noncenral_chisquare
Statistic Funkcje


Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0

stats_rand_gen_iuniform
stats_rand_gen_noncentral_f
Statistic Funkcje
PHP Manual

stats_rand_gen_noncenral_chisquare

(PECL stats >= 1.0.0)

stats_rand_gen_noncenral_chisquare — Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0

Opis

float stats_rand_gen_noncenral_chisquare ( float $df , float $xnonc )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

df

xnonc

Zwracane wartości

stats_rand_gen_iuniform
stats_rand_gen_noncentral_f
Statistic Funkcje


Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central 

stats_rand_gen_noncenral_chisquare
stats_rand_gen_noncentral_t
Statistic Funkcje
PHP Manual

stats_rand_gen_noncentral_f

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.

Opis

float stats_rand_gen_noncentral_f ( float $dfn , float $dfd , float $xnonc )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

dfn

dfd

xnonc

Zwracane wartości

stats_rand_gen_noncenral_chisquare
stats_rand_gen_noncentral_t
Statistic Funkcje


Generates a single random deviate from a noncentral T distribution

stats_rand_gen_noncentral_f
stats_rand_gen_normal
Statistic Funkcje
PHP Manual

stats_rand_gen_noncentral_t

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_t — Generates a single random deviate from a noncentral T distribution

Opis

float stats_rand_gen_noncentral_t ( float $df , float $xnonc )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

df

xnonc

Zwracane wartości

stats_rand_gen_noncentral_f
stats_rand_gen_normal
Statistic Funkcje


Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.

stats_rand_gen_noncentral_t
stats_rand_gen_t
Statistic Funkcje
PHP Manual

stats_rand_gen_normal

(PECL stats >= 1.0.0)

stats_rand_gen_normal — Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.

Opis

float stats_rand_gen_normal ( float $av , float $sd )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

av

sd

Zwracane wartości

stats_rand_gen_noncentral_t
stats_rand_gen_t
Statistic Funkcje


Generates a single random deviate from a T distribution

stats_rand_gen_normal
stats_rand_get_seeds
Statistic Funkcje
PHP Manual

stats_rand_gen_t

(PECL stats >= 1.0.0)

stats_rand_gen_t — Generates a single random deviate from a T distribution

Opis

float stats_rand_gen_t ( float $df )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

df

Zwracane wartości

stats_rand_gen_normal
stats_rand_get_seeds
Statistic Funkcje


Not documented

stats_rand_gen_t
stats_rand_phrase_to_seeds
Statistic Funkcje
PHP Manual

stats_rand_get_seeds

(PECL stats >= 1.0.0)

stats_rand_get_seeds — Not documented

Opis

array stats_rand_get_seeds ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Zwracane wartości

stats_rand_gen_t
stats_rand_phrase_to_seeds
Statistic Funkcje


generate two seeds for the RGN random number generator

stats_rand_get_seeds
stats_rand_ranf
Statistic Funkcje
PHP Manual

stats_rand_phrase_to_seeds

(PECL stats >= 1.0.0)

stats_rand_phrase_to_seeds — generate two seeds for the RGN random number generator

Opis

array stats_rand_phrase_to_seeds ( string $phrase )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

phrase

Zwracane wartości

stats_rand_get_seeds
stats_rand_ranf
Statistic Funkcje


Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator

stats_rand_phrase_to_seeds
stats_rand_setall
Statistic Funkcje
PHP Manual

stats_rand_ranf

(PECL stats >= 1.0.0)

stats_rand_ranf — Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator

Opis

float stats_rand_ranf ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Zwracane wartości

stats_rand_phrase_to_seeds
stats_rand_setall
Statistic Funkcje


Not documented

stats_rand_ranf
stats_skew
Statistic Funkcje
PHP Manual

stats_rand_setall

(PECL stats >= 1.0.0)

stats_rand_setall — Not documented

Opis

void stats_rand_setall ( int $iseed1 , int $iseed2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iseed1

iseed2

Zwracane wartości

stats_rand_ranf
stats_skew
Statistic Funkcje


Computes the skewness of the data in the array

stats_rand_setall
stats_standard_deviation
Statistic Funkcje
PHP Manual

stats_skew

(PECL stats >= 1.0.0)

stats_skew — Computes the skewness of the data in the array

Opis

float stats_skew ( array $a )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

a

Zwracane wartości

stats_rand_setall
stats_standard_deviation
Statistic Funkcje


Returns the standard deviation

stats_skew
stats_stat_binomial_coef
Statistic Funkcje
PHP Manual

stats_standard_deviation

(PECL stats >= 1.0.0)

stats_standard_deviation — Returns the standard deviation

Opis

float stats_standard_deviation ( array $a [, bool $sample = false ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

a

sample

Zwracane wartości

stats_skew
stats_stat_binomial_coef
Statistic Funkcje


Not documented

stats_standard_deviation
stats_stat_correlation
Statistic Funkcje
PHP Manual

stats_stat_binomial_coef

(PECL stats >= 1.0.0)

stats_stat_binomial_coef — Not documented

Opis

float stats_stat_binomial_coef ( int $x , int $n )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

x

n

Zwracane wartości

stats_standard_deviation
stats_stat_correlation
Statistic Funkcje


Not documented

stats_stat_binomial_coef
stats_stat_gennch
Statistic Funkcje
PHP Manual

stats_stat_correlation

(PECL stats >= 1.0.0)

stats_stat_correlation — Not documented

Opis

float stats_stat_correlation ( array $arr1 , array $arr2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

arr1

arr2

Zwracane wartości

stats_stat_binomial_coef
stats_stat_gennch
Statistic Funkcje


Not documented

stats_stat_correlation
stats_stat_independent_t
Statistic Funkcje
PHP Manual

stats_stat_gennch

(PECL stats >= 1.0.0)

stats_stat_gennch — Not documented

Opis

float stats_stat_gennch ( int $n )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

n

Zwracane wartości

stats_stat_correlation
stats_stat_independent_t
Statistic Funkcje


Not documented

stats_stat_gennch
stats_stat_innerproduct
Statistic Funkcje
PHP Manual

stats_stat_independent_t

(PECL stats >= 1.0.0)

stats_stat_independent_t — Not documented

Opis

float stats_stat_independent_t ( array $arr1 , array $arr2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

arr1

arr2

Zwracane wartości

stats_stat_gennch
stats_stat_innerproduct
Statistic Funkcje


stats_stat_independent_t
stats_stat_noncentral_t
Statistic Funkcje
PHP Manual

stats_stat_innerproduct

(PECL stats >= 1.0.0)

stats_stat_innerproduct —

Opis

float stats_stat_innerproduct ( array $arr1 , array $arr2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

arr1

arr2

Zwracane wartości

stats_stat_independent_t
stats_stat_noncentral_t
Statistic Funkcje


Calculates any one parameter of the noncentral t distribution give values for the others.

stats_stat_innerproduct
stats_stat_paired_t
Statistic Funkcje
PHP Manual

stats_stat_noncentral_t

(PECL stats >= 1.0.0)

stats_stat_noncentral_t — Calculates any one parameter of the noncentral t distribution give values for the others.

Opis

float stats_stat_noncentral_t ( float $par1 , float $par2 , float $par3 , int $which )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

par1

par2

par3

which

Zwracane wartości

stats_stat_innerproduct
stats_stat_paired_t
Statistic Funkcje


Not documented

stats_stat_noncentral_t
stats_stat_percentile
Statistic Funkcje
PHP Manual

stats_stat_paired_t

(PECL stats >= 1.0.0)

stats_stat_paired_t — Not documented

Opis

float stats_stat_paired_t ( array $arr1 , array $arr2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

arr1

arr2

Zwracane wartości

stats_stat_noncentral_t
stats_stat_percentile
Statistic Funkcje


Not documented

stats_stat_paired_t
stats_stat_powersum
Statistic Funkcje
PHP Manual

stats_stat_percentile

(PECL stats >= 1.0.0)

stats_stat_percentile — Not documented

Opis

float stats_stat_percentile ( float $df , float $xnonc )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

df

xnonc

Zwracane wartości

stats_stat_paired_t
stats_stat_powersum
Statistic Funkcje


Not documented

stats_stat_percentile
stats_variance
Statistic Funkcje
PHP Manual

stats_stat_powersum

(PECL stats >= 1.0.0)

stats_stat_powersum — Not documented

Opis

float stats_stat_powersum ( array $arr , float $power )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

arr

power

Zwracane wartości

stats_stat_percentile
stats_variance
Statistic Funkcje


Returns the population variance

stats_stat_powersum
Generowanie nietekstowych formatów danych
Statistic Funkcje
PHP Manual

stats_variance

(PECL stats >= 1.0.0)

stats_variance — Returns the population variance

Opis

float stats_variance ( array $a [, bool $sample = false ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

a

sample

Zwracane wartości

stats_stat_powersum
Generowanie nietekstowych formatów danych
Statistic Funkcje


Generowanie nietekstowych formatów danych

  • FDF — Forms Data Format
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • FDF Funkcje
  • GnuPG — GNU Privacy Guard
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • GnuPG Funkcje
  • haru — Haru PDF
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Builtin Fonts And Encodings
    • HaruException — The HaruException class
    • HaruDoc — The HaruDoc class
    • HaruPage — The HaruPage class
    • HaruFont — The HaruFont class
    • HaruImage — The HaruImage class
    • HaruEncoder — The HaruEncoder class
    • HaruOutline — The HaruOutline class
    • HaruAnnotation — The HaruAnnotation class
    • HaruDestination — The HaruDestination class
  • Ming — Ming (flash)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Ming Funkcje
    • SWFAction — The SWFAction class
    • SWFBitmap — The SWFBitmap class
    • SWFButton — The SWFButton class
    • SWFDisplayItem — The SWFDisplayItem class
    • SWFFill — The SWFFill class
    • SWFFont — The SWFFont class
    • SWFFontChar — The SWFFontChar class
    • SWFGradient — The SWFGradient class
    • SWFMorph — The SWFMorph class
    • SWFMovie — The SWFMovie class
    • SWFPrebuiltClip — The SWFPrebuiltClip class
    • SWFShape — The SWFShape class
    • SWFSound — The SWFSound class
    • SWFSoundInstance — The SWFSoundInstance class
    • SWFSprite — The SWFSprite class
    • SWFText — The SWFText class
    • SWFTextField — The SWFTextField class
    • SWFVideoStream — The SWFVideoStream class
  • PDF
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • PDF Funkcje
  • PS — PostScript document creation
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • PS Funkcje
  • RPM Reader — RPM Header Reading
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • RPM Reader Funkcje
  • SWF — Shockwave Flash
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • SWF Funkcje
stats_variance
FDF
Opis funkcji


Forms Data Format

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • FDF Funkcje
    • fdf_add_doc_javascript — Adds javascript code to the FDF document
    • fdf_add_template — Adds a template into the FDF document
    • fdf_close — Close an FDF document
    • fdf_create — Create a new FDF document
    • fdf_enum_values — Call a user defined function for each document value
    • fdf_errno — Return error code for last fdf operation
    • fdf_error — Return error description for FDF error code
    • fdf_get_ap — Get the appearance of a field
    • fdf_get_attachment — Extracts uploaded file embedded in the FDF
    • fdf_get_encoding — Get the value of the /Encoding key
    • fdf_get_file — Get the value of the /F key
    • fdf_get_flags — Gets the flags of a field
    • fdf_get_opt — Gets a value from the opt array of a field
    • fdf_get_status — Get the value of the /STATUS key
    • fdf_get_value — Get the value of a field
    • fdf_get_version — Gets version number for FDF API or file
    • fdf_header — Sets FDF-specific output headers
    • fdf_next_field_name — Get the next field name
    • fdf_open_string — Read a FDF document from a string
    • fdf_open — Open a FDF document
    • fdf_remove_item — Sets target frame for form
    • fdf_save_string — Returns the FDF document as a string
    • fdf_save — Save a FDF document
    • fdf_set_ap — Set the appearance of a field
    • fdf_set_encoding — Sets FDF character encoding
    • fdf_set_file — Set PDF document to display FDF data in
    • fdf_set_flags — Sets a flag of a field
    • fdf_set_javascript_action — Sets an javascript action of a field
    • fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt — Sets an option of a field
    • fdf_set_status — Set the value of the /STATUS key
    • fdf_set_submit_form_action — Sets a submit form action of a field
    • fdf_set_target_frame — Set target frame for form display
    • fdf_set_value — Set the value of a field
    • fdf_set_version — Sets version number for a FDF file
Generowanie nietekstowych formatów danych
Wstęp
Generowanie nietekstowych formatów danych


Wstęp

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at » http://www.adobe.com/devnet/acrobat/fdftoolkit.html for more information on what FDF is and how it is used in general.

The general idea of FDF is similar to HTML forms. The difference is basically the format how data is transmitted to the server when the submit button is pressed (this is actually the Form Data Format) and the format of the form itself (which is the Portable Document Format, PDF). Processing the FDF data is one of the features provided by the fdf functions. But there is more. One may as well take an existing PDF form and populated the input fields with data without modifying the form itself. In such a case one would create a FDF document (fdf_create()) set the values of each input field (fdf_set_value()) and associate it with a PDF form (fdf_set_file()). Finally it has to be sent to the browser with MimeType application/vnd.fdf. The Acrobat reader plugin of your browser recognizes the MimeType, reads the associated PDF form and fills in the data from the FDF document.

If you look at an FDF-document with a text editor you will find a catalogue object with the name FDF. Such an object may contain a number of entries like Fields, F, Status etc.. The most commonly used entries are Fields which points to a list of input fields, and F which contains the filename of the PDF-document this data belongs to. Those entries are referred to in the FDF documentation as /F-Key or /Status-Key. Modifying this entries is done by functions like fdf_set_file() and fdf_set_status(). Fields are modified with fdf_set_value(), fdf_set_opt() etc..

FDF
Instalacja/Konfiguracja
FDF


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
FDF


Wymagania

You need the FDF toolkit SDK available from » http://www.adobe.com/devnet/acrobat/fdftoolkit.html. As of PHP 4.3.0 you need at least SDK version 5.0. The FDF toolkit library is available in binary form only, platforms supported by Adobe are Win32, Linux, Solaris and AIX.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/fdf.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.3.0

Informacja: If you run into problems configuring PHP with fdftk support, check whether the header file fdftk.h and the library libfdftk.so are at the right place. The configure script supports both the directory structure of the FDF SDK distribution and the usual DIR/include / DIR/lib layout, so you can point it either directly to the unpacked distribution directory or put the header file and the appropriate library for your platform into e.g. /usr/local/include and /usr/local/lib and configure with --with-fdftk=/usr/local .

Informacja: Note to Win32 Users

Aby poprawnie działało rozszerzenie, pliki DLL muszą znajdować się w miejscu wskazanym przez PATH systemu Windows. Aby uzyskać więcej informacji zobacz FAQ zatytułowane "Jak mam dodać mój katalog PHP do PATH w Windows". Chociaż skopiowanie plików DLL z folderu PHP do systemowego katalogu Windows także zadziała (ponieważ katalog systemowy jest domyślnie w PATH systemu), ale nie jest to wymagane. To rozszerzenie wymaga następujących plików znajdujących się w PATH: fdftk.dll

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

Most fdf functions require a fdf resource as their first parameter. A fdf resource is a handle to an opened fdf file. fdf resources may be obtained using fdf_create(), fdf_open() and fdf_open_string().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

FDFValue (integer)
FDFStatus (integer)
FDFFile (integer)
FDFID (integer)
FDFFf (integer)
FDFSetFf (integer)
FDFClearFf (integer)
FDFFlags (integer)
FDFSetF (integer)
FDFClrF (integer)
FDFAP (integer)
FDFAS (integer)
FDFAction (integer)
FDFAA (integer)
FDFAPRef (integer)
FDFIF (integer)
FDFEnter (integer)
FDFExit (integer)
FDFDown (integer)
FDFUp (integer)
FDFFormat (integer)
FDFValidate (integer)
FDFKeystroke (integer)
FDFCalculate (integer)
FDFNormalAP (integer)
FDFRolloverAP (integer)
FDFDownAP (integer)
Typy zasobów
Przykłady
FDF


Przykłady

The following examples shows just the evaluation of form data.

Przykład #1 Evaluating a FDF document

<?php
// Open fdf from input string provided by the extension
// The pdf form contained several input text fields with the names
// volume, date, comment, publisher, preparer, and two checkboxes
// show_publisher and show_preparer.
$fdf = fdf_open_string($HTTP_FDF_DATA);
$volume = fdf_get_value($fdf, "volume");
echo "The volume field has the value '<b>$volume</b>'<br />";

$date = fdf_get_value($fdf, "date");
echo "The date field has the value '<b>$date</b>'<br />";

$comment = fdf_get_value($fdf, "comment");
echo "The comment field has the value '<b>$comment</b>'<br />";

if (fdf_get_value($fdf, "show_publisher") == "On") {
  $publisher = fdf_get_value($fdf, "publisher");
  echo "The publisher field has the value '<b>$publisher</b>'<br />";
} else
  echo "Publisher shall not be shown.<br />";

if (fdf_get_value($fdf, "show_preparer") == "On") {
  $preparer = fdf_get_value($fdf, "preparer");
  echo "The preparer field has the value '<b>$preparer</b>'<br />";
} else
  echo "Preparer shall not be shown.<br />";
fdf_close($fdf);
?>

Stałe predefiniowane
FDF Funkcje
FDF


FDF Funkcje

Spis treści

  • fdf_add_doc_javascript — Adds javascript code to the FDF document
  • fdf_add_template — Adds a template into the FDF document
  • fdf_close — Close an FDF document
  • fdf_create — Create a new FDF document
  • fdf_enum_values — Call a user defined function for each document value
  • fdf_errno — Return error code for last fdf operation
  • fdf_error — Return error description for FDF error code
  • fdf_get_ap — Get the appearance of a field
  • fdf_get_attachment — Extracts uploaded file embedded in the FDF
  • fdf_get_encoding — Get the value of the /Encoding key
  • fdf_get_file — Get the value of the /F key
  • fdf_get_flags — Gets the flags of a field
  • fdf_get_opt — Gets a value from the opt array of a field
  • fdf_get_status — Get the value of the /STATUS key
  • fdf_get_value — Get the value of a field
  • fdf_get_version — Gets version number for FDF API or file
  • fdf_header — Sets FDF-specific output headers
  • fdf_next_field_name — Get the next field name
  • fdf_open_string — Read a FDF document from a string
  • fdf_open — Open a FDF document
  • fdf_remove_item — Sets target frame for form
  • fdf_save_string — Returns the FDF document as a string
  • fdf_save — Save a FDF document
  • fdf_set_ap — Set the appearance of a field
  • fdf_set_encoding — Sets FDF character encoding
  • fdf_set_file — Set PDF document to display FDF data in
  • fdf_set_flags — Sets a flag of a field
  • fdf_set_javascript_action — Sets an javascript action of a field
  • fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
  • fdf_set_opt — Sets an option of a field
  • fdf_set_status — Set the value of the /STATUS key
  • fdf_set_submit_form_action — Sets a submit form action of a field
  • fdf_set_target_frame — Set target frame for form display
  • fdf_set_value — Set the value of a field
  • fdf_set_version — Sets version number for a FDF file
Przykłady
fdf_add_doc_javascript
FDF


Adds javascript code to the FDF document

FDF Funkcje
fdf_add_template
FDF Funkcje
PHP Manual

fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_add_doc_javascript — Adds javascript code to the FDF document

Opis

bool fdf_add_doc_javascript ( resource $fdf_document , string $script_name , string $script_code )

Adds a script to the FDF, which Acrobat then adds to the doc-level scripts of a document, once the FDF is imported into it.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

script_name

The script name.

script_code

The script code. It is strongly suggested to use \r for linebreaks within the script code.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Adding JavaScript code to a FDF

<?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r  return x+1;\r}\r");
fdf_save($fdf);
?>

will create a FDF like this:

%FDF-1.2
%âãÏÓ
1 0 obj
<<
/FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

FDF Funkcje
fdf_add_template
FDF Funkcje


Adds a template into the FDF document

fdf_add_doc_javascript
fdf_close
FDF Funkcje
PHP Manual

fdf_add_template

(PHP 4, PHP 5)

fdf_add_template — Adds a template into the FDF document

Opis

bool fdf_add_template ( resource $fdf_document , int $newpage , string $filename , string $template , int $rename )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fdf_add_doc_javascript
fdf_close
FDF Funkcje


Close an FDF document

fdf_add_template
fdf_create
FDF Funkcje
PHP Manual

fdf_close

(PHP 4, PHP 5)

fdf_close — Close an FDF document

Opis

void fdf_close ( resource $fdf_document )

Closes the FDF document.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • fdf_open() - Open a FDF document

fdf_add_template
fdf_create
FDF Funkcje


Create a new FDF document

fdf_close
fdf_enum_values
FDF Funkcje
PHP Manual

fdf_create

(PHP 4, PHP 5)

fdf_create — Create a new FDF document

Opis

resource fdf_create ( void )

Creates a new FDF document.

This function is needed if one would like to populate input fields in a PDF document with data.

Zwracane wartości

Returns a FDF document handle, or FALSE on error.

Przykłady

Przykład #1 Populating a PDF document

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

Zobacz też:

  • fdf_close() - Close an FDF document
  • fdf_save() - Save a FDF document
  • fdf_open() - Open a FDF document

fdf_close
fdf_enum_values
FDF Funkcje


Call a user defined function for each document value

fdf_create
fdf_errno
FDF Funkcje
PHP Manual

fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5)

fdf_enum_values — Call a user defined function for each document value

Opis

bool fdf_enum_values ( resource $fdf_document , callback $function [, mixed $userdata ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fdf_create
fdf_errno
FDF Funkcje


Return error code for last fdf operation

fdf_enum_values
fdf_error
FDF Funkcje
PHP Manual

fdf_errno

(PHP 4 >= 4.3.0, PHP 5)

fdf_errno — Return error code for last fdf operation

Opis

int fdf_errno ( void )

Gets the error code set by the last FDF function call.

A textual description of the error may be obtained using with fdf_error().

Zwracane wartości

Returns the error code as an integer, or zero if there was no errors.

Zobacz też:

  • fdf_error() - Return error description for FDF error code

fdf_enum_values
fdf_error
FDF Funkcje


Return error description for FDF error code

fdf_errno
fdf_get_ap
FDF Funkcje
PHP Manual

fdf_error

(PHP 4 >= 4.3.0, PHP 5)

fdf_error — Return error description for FDF error code

Opis

string fdf_error ([ int $error_code = -1 ] )

Gets a textual description for the FDF error code given in error_code.

Parametry

error_code

An error code obtained with fdf_errno(). If not provided, this function uses the internal error code set by the last operation.

Zwracane wartości

Returns the error message as a string, or the string no error if nothing went wrong.

Zobacz też:

  • fdf_errno() - Return error code for last fdf operation

fdf_errno
fdf_get_ap
FDF Funkcje


Get the appearance of a field

fdf_error
fdf_get_attachment
FDF Funkcje
PHP Manual

fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_ap — Get the appearance of a field

Opis

bool fdf_get_ap ( resource $fdf_document , string $field , int $face , string $filename )

Gets the appearance of a field (i.e. the value of the /AP key) and stores it in a file.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

field

face

The possible values are FDFNormalAP, FDFRolloverAP and FDFDownAP.

filename

The appearance will be stored in this parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

fdf_error
fdf_get_attachment
FDF Funkcje


Extracts uploaded file embedded in the FDF

fdf_get_ap
fdf_get_encoding
FDF Funkcje
PHP Manual

fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_attachment — Extracts uploaded file embedded in the FDF

Opis

array fdf_get_attachment ( resource $fdf_document , string $fieldname , string $savepath )

Extracts a file uploaded by means of the "file selection" field fieldname and stores it under savepath.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

savepath

May be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten.

Informacja:

There seems to be no other way to find out the original filename but to store the file using a directory as savepath and check for the basename it was stored under.

Zwracane wartości

The returned array contains the following fields:

  • path - path were the file got stored
  • size - size of the stored file in bytes
  • type - mimetype if given in the FDF

Przykłady

Przykład #1 Storing an uploaded file

<?php
  $fdf = fdf_open_string($HTTP_FDF_DATA);
  $data = fdf_get_attachment($fdf, "filename", "/tmpdir");
  echo "The uploaded file is stored in $data[path]";
?>

fdf_get_ap
fdf_get_encoding
FDF Funkcje


Get the value of the /Encoding key

fdf_get_attachment
fdf_get_file
FDF Funkcje
PHP Manual

fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_encoding — Get the value of the /Encoding key

Opis

string fdf_get_encoding ( resource $fdf_document )

Gets the value of the /Encoding key.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Zwracane wartości

Returns the encoding as a string. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

Zobacz też:

  • fdf_set_encoding() - Sets FDF character encoding

fdf_get_attachment
fdf_get_file
FDF Funkcje


Get the value of the /F key

fdf_get_encoding
fdf_get_flags
FDF Funkcje
PHP Manual

fdf_get_file

(PHP 4, PHP 5)

fdf_get_file — Get the value of the /F key

Opis

string fdf_get_file ( resource $fdf_document )

Gets the value of the /F key.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Zwracane wartości

Returns the key value, as a string.

Zobacz też:

  • fdf_set_file() - Set PDF document to display FDF data in

fdf_get_encoding
fdf_get_flags
FDF Funkcje


Gets the flags of a field

fdf_get_file
fdf_get_opt
FDF Funkcje
PHP Manual

fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_flags — Gets the flags of a field

Opis

int fdf_get_flags ( resource $fdf_document , string $fieldname , int $whichflags )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fdf_get_file
fdf_get_opt
FDF Funkcje


Gets a value from the opt array of a field

fdf_get_flags
fdf_get_status
FDF Funkcje
PHP Manual

fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_opt — Gets a value from the opt array of a field

Opis

mixed fdf_get_opt ( resource $fdf_document , string $fieldname [, int $element = -1 ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fdf_get_flags
fdf_get_status
FDF Funkcje


Get the value of the /STATUS key

fdf_get_opt
fdf_get_value
FDF Funkcje
PHP Manual

fdf_get_status

(PHP 4, PHP 5)

fdf_get_status — Get the value of the /STATUS key

Opis

string fdf_get_status ( resource $fdf_document )

Gets the value of the /STATUS key.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Zwracane wartości

Returns the key value, as a string.

Zobacz też:

  • fdf_set_status() - Set the value of the /STATUS key

fdf_get_opt
fdf_get_value
FDF Funkcje


Get the value of a field

fdf_get_status
fdf_get_version
FDF Funkcje
PHP Manual

fdf_get_value

(PHP 4, PHP 5)

fdf_get_value — Get the value of a field

Opis

mixed fdf_get_value ( resource $fdf_document , string $fieldname [, int $which = -1 ] )

Gets the value for the requested field.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

which

Elements of an array field can be retrieved by passing this optional parameter, starting at zero. For non-array fields, this parameter will be ignored.

Zwracane wartości

Returns the field value.

Rejestr zmian

Wersja | Opis
4.3.0 | Support for arrays and the which parameter were added.

Zobacz też:

  • fdf_set_value() - Set the value of a field

fdf_get_status
fdf_get_version
FDF Funkcje


Gets version number for FDF API or file

fdf_get_value
fdf_header
FDF Funkcje
PHP Manual

fdf_get_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_get_version — Gets version number for FDF API or file

Opis

string fdf_get_version ([ resource $fdf_document ] )

Return the FDF version for the given document, or the toolkit API version number if no parameter is given.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Zwracane wartości

Returns the version as a string. For the current FDF toolkit 5.0 the API version number is 5.0 and the document version number is either 1.2, 1.3 or 1.4.

Zobacz też:

  • fdf_set_version() - Sets version number for a FDF file

fdf_get_value
fdf_header
FDF Funkcje


Sets FDF-specific output headers

fdf_get_version
fdf_next_field_name
FDF Funkcje
PHP Manual

fdf_header

(PHP 4 >= 4.3.0, PHP 5)

fdf_header — Sets FDF-specific output headers

Opis

void fdf_header ( void )

This is a convenience function to set appropriate HTTP headers for FDF output. It sets the Content-type: to application/vnd.fdf.

Zwracane wartości

Nie jest zwracana żadna wartość.

fdf_get_version
fdf_next_field_name
FDF Funkcje


Get the next field name

fdf_header
fdf_open_string
FDF Funkcje
PHP Manual

fdf_next_field_name

(PHP 4, PHP 5)

fdf_next_field_name — Get the next field name

Opis

string fdf_next_field_name ( resource $fdf_document [, string $fieldname ] )

Gets the name of the field after the given field. This name can be used with several functions.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string. If not given, the first field will be assumed.

Zwracane wartości

Returns the field name as a string.

Przykłady

Przykład #1 Detecting all fieldnames in a FDF

<?php
$fdf = fdf_open($HTTP_FDF_DATA);
for ($field = fdf_next_field_name($fdf);
    $field != "";
    $field = fdf_next_field_name($fdf, $field)) {
    echo "field: $field\n";
}
?>

Zobacz też:

  • fdf_get_value() - Get the value of a field

fdf_header
fdf_open_string
FDF Funkcje


Read a FDF document from a string

fdf_next_field_name
fdf_open
FDF Funkcje
PHP Manual

fdf_open_string

(PHP 4 >= 4.3.0, PHP 5)

fdf_open_string — Read a FDF document from a string

Opis

resource fdf_open_string ( string $fdf_data )

Reads form data from a string.

You can use fdf_open_string() together with $HTTP_FDF_DATA to process FDF form input from a remote client.

Parametry

fdf_data

The data as returned from a PDF form or created using fdf_create() and fdf_save_string().

Zwracane wartości

Returns a FDF document handle, or FALSE on error.

Przykłady

Przykład #1 Accessing the form data

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>

Zobacz też:

  • fdf_open() - Open a FDF document
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save_string() - Returns the FDF document as a string

fdf_next_field_name
fdf_open
FDF Funkcje


Open a FDF document

fdf_open_string
fdf_remove_item
FDF Funkcje
PHP Manual

fdf_open

(PHP 4, PHP 5)

fdf_open — Open a FDF document

Opis

resource fdf_open ( string $filename )

Opens a file with form data.

You can also use fdf_open_string() to process the results of a PDF form POST request.

Parametry

filename

Path to the FDF file. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().

Zwracane wartości

Returns a FDF document handle, or FALSE on error.

Przykłady

Przykład #1 Accessing the form data

<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Open temp file and evaluate data
$fdf = fdf_open("test.fdf");
/* ... */
fdf_close($fdf);
?>

Zobacz też:

  • fdf_open_string() - Read a FDF document from a string
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save() - Save a FDF document

fdf_open_string
fdf_remove_item
FDF Funkcje


Sets target frame for form

fdf_open
fdf_save_string
FDF Funkcje
PHP Manual

fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5)

fdf_remove_item — Sets target frame for form

Opis

bool fdf_remove_item ( resource $fdf_document , string $fieldname , int $item )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

fdf_open
fdf_save_string
FDF Funkcje


Returns the FDF document as a string

fdf_remove_item
fdf_save
FDF Funkcje
PHP Manual

fdf_save_string

(PHP 4 >= 4.3.0, PHP 5)

fdf_save_string — Returns the FDF document as a string

Opis

string fdf_save_string ( resource $fdf_document )

Returns the FDF document as a string.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

Zwracane wartości

Returns the document as a string, or FALSE on error.

Przykłady

Przykład #1 Retrieving FDF as a string

<?php
$fdf = fdf_create();
fdf_set_value($fdf, "foo", "bar");
$str = fdf_save_string($fdf);
fdf_close($fdf);
echo $str;
?>

Powyższy przykład wyświetli:

%FDF-1.2
%âãÏÓ
1 0 obj
<<
/FDF << /Fields 2 0 R >>
>>
endobj
2 0 obj
[
<< /T (foo)/V (bar)>>
]
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

Zobacz też:

  • fdf_open_string() - Read a FDF document from a string
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save() - Save a FDF document

fdf_remove_item
fdf_save
FDF Funkcje


Save a FDF document

fdf_save_string
fdf_set_ap
FDF Funkcje
PHP Manual

fdf_save

(PHP 4, PHP 5)

fdf_save — Save a FDF document

Opis

bool fdf_save ( resource $fdf_document [, string $filename ] )

Saves a FDF document.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

filename

If provided, the resulting FDF will be written in this parameter. Otherwise, this function will write the FDF to the default PHP output stream.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save_string() - Returns the FDF document as a string

fdf_save_string
fdf_set_ap
FDF Funkcje


Set the appearance of a field

fdf_save
fdf_set_encoding
FDF Funkcje
PHP Manual

fdf_set_ap

(PHP 4, PHP 5)

fdf_set_ap — Set the appearance of a field

Opis

bool fdf_set_ap ( resource $fdf_document , string $field_name , int $face , string $filename , int $page_number )

Sets the appearance of a field (i.e. the value of the /AP key).

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

field_name

face

The possible values FDFNormalAP, FDFRolloverAP and FDFDownAP.

filename

page_number

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

fdf_save
fdf_set_encoding
FDF Funkcje


Sets FDF character encoding

fdf_set_ap
fdf_set_file
FDF Funkcje
PHP Manual

fdf_set_encoding

(PHP 4 >= 4.0.7, PHP 5)

fdf_set_encoding — Sets FDF character encoding

Opis

bool fdf_set_encoding ( resource $fdf_document , string $encoding )

Sets the character encoding for the FDF document.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

encoding

The encoding name. The following values are supported: "Shift-JIS", "UHC", "GBK" and "BigFive".

An empty string resets the encoding to the default PDFDocEncoding/Unicode scheme.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

fdf_set_ap
fdf_set_file
FDF Funkcje


Set PDF document to display FDF data in

fdf_set_encoding
fdf_set_flags
FDF Funkcje
PHP Manual

fdf_set_file

(PHP 4, PHP 5)

fdf_set_file — Set PDF document to display FDF data in

Opis

bool fdf_set_file ( resource $fdf_document , string $url [, string $target_frame ] )

Selects a different PDF document to display the form results in then the form it originated from.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

url

Should be given as an absolute URL.

target_frame

Use this parameter to specify the frame in which the document will be displayed. You can also set the default value for this parameter using fdf_set_target_frame().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Passing FDF data to a second form

<?php
  /* set content type for Adobe FDF */
  fdf_header();

  /* start new fdf */
  $fdf = fdf_create();

  /* set field "foo" to value "bar" */
  fdf_set_value($fdf, "foo", "bar");

  /* tell client to display FDF data using "fdf_form.pdf" */
  fdf_set_file($fdf, "http://www.example.com/fdf_form.pdf");

  /* output fdf */
  fdf_save($fdf);

  /* clean up */
  fdf_close($fdf);
?>

Zobacz też:

  • fdf_get_file() - Get the value of the /F key
  • fdf_set_target_frame() - Set target frame for form display

fdf_set_encoding
fdf_set_flags
FDF Funkcje


Sets a flag of a field

fdf_set_file
fdf_set_javascript_action
FDF Funkcje
PHP Manual

fdf_set_flags

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_flags — Sets a flag of a field

Opis

bool fdf_set_flags ( resource $fdf_document , string $fieldname , int $whichFlags , int $newFlags )

Sets certain flags of the given field.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

whichFlags

newFlags

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fdf_set_opt() - Sets an option of a field

fdf_set_file
fdf_set_javascript_action
FDF Funkcje


Sets an javascript action of a field

fdf_set_flags
fdf_set_on_import_javascript
FDF Funkcje
PHP Manual

fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_javascript_action — Sets an javascript action of a field

Opis

bool fdf_set_javascript_action ( resource $fdf_document , string $fieldname , int $trigger , string $script )

Sets a javascript action for the given field.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

trigger

script

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fdf_set_submit_form_action() - Sets a submit form action of a field

fdf_set_flags
fdf_set_on_import_javascript
FDF Funkcje


Adds javascript code to be executed when Acrobat opens the FDF

fdf_set_javascript_action
fdf_set_opt
FDF Funkcje
PHP Manual

fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF

Opis

bool fdf_set_on_import_javascript ( resource $fdf_document , string $script , bool $before_data_import )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • fdf_add_doc_javascript() - Adds javascript code to the FDF document
  • fdf_set_javascript_action() - Sets an javascript action of a field

fdf_set_javascript_action
fdf_set_opt
FDF Funkcje


Sets an option of a field

fdf_set_on_import_javascript
fdf_set_status
FDF Funkcje
PHP Manual

fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_opt — Sets an option of a field

Opis

bool fdf_set_opt ( resource $fdf_document , string $fieldname , int $element , string $str1 , string $str2 )

Sets options of the given field.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

element

str1

str2

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fdf_set_flags() - Sets a flag of a field

fdf_set_on_import_javascript
fdf_set_status
FDF Funkcje


Set the value of the /STATUS key

fdf_set_opt
fdf_set_submit_form_action
FDF Funkcje
PHP Manual

fdf_set_status

(PHP 4, PHP 5)

fdf_set_status — Set the value of the /STATUS key

Opis

bool fdf_set_status ( resource $fdf_document , string $status )

Sets the value of the /STATUS key. When a client receives a FDF with a status set it will present the value in an alert box.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

status

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fdf_get_status() - Get the value of the /STATUS key

fdf_set_opt
fdf_set_submit_form_action
FDF Funkcje


Sets a submit form action of a field

fdf_set_status
fdf_set_target_frame
FDF Funkcje
PHP Manual

fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5)

fdf_set_submit_form_action — Sets a submit form action of a field

Opis

bool fdf_set_submit_form_action ( resource $fdf_document , string $fieldname , int $trigger , string $script , int $flags )

Sets a submit form action for the given field.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

trigger

script

flags

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fdf_set_javascript_action() - Sets an javascript action of a field

fdf_set_status
fdf_set_target_frame
FDF Funkcje


Set target frame for form display

fdf_set_submit_form_action
fdf_set_value
FDF Funkcje
PHP Manual

fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_target_frame — Set target frame for form display

Opis

bool fdf_set_target_frame ( resource $fdf_document , string $frame_name )

Sets the target frame to display a result PDF defined with fdf_save_file() in.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

frame_name

The frame name, as a string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fdf_save_file()

fdf_set_submit_form_action
fdf_set_value
FDF Funkcje


Set the value of a field

fdf_set_target_frame
fdf_set_version
FDF Funkcje
PHP Manual

fdf_set_value

(PHP 4, PHP 5)

fdf_set_value — Set the value of a field

Opis

bool fdf_set_value ( resource $fdf_document , string $fieldname , mixed $value [, int $isName ] )

Sets the value for the given field.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

value

This parameter will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.

isName

Informacja:

In older versions of the FDF toolkit last parameter determined if the field value was to be converted to a PDF Name (= 1) or set to a PDF String (= 0).

The value is no longer used in the current toolkit version 5.0. For compatibility reasons it is still supported as an optional parameter beginning with PHP 4.3, but ignored internally.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
4.3.0 | Support for arrays in the value parameter was added.

Zobacz też:

  • fdf_get_value() - Get the value of a field
  • fdf_remove_item() - Sets target frame for form

fdf_set_target_frame
fdf_set_version
FDF Funkcje


Sets version number for a FDF file

fdf_set_value
GnuPG
FDF Funkcje
PHP Manual

fdf_set_version

(PHP 4 >= 4.3.0, PHP 5)

fdf_set_version — Sets version number for a FDF file

Opis

bool fdf_set_version ( resource $fdf_document , string $version )

Sets the FDF version for the given document.

Some features supported by this extension are only available in newer FDF versions.

Parametry

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

version

The version number. For the current FDF toolkit 5.0, this may be either 1.2, 1.3 or 1.4.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fdf_get_version() - Gets version number for FDF API or file

fdf_set_value
GnuPG
FDF Funkcje


GNU Privacy Guard

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Clearsign text
  • GnuPG Funkcje
    • gnupg_adddecryptkey — Add a key for decryption
    • gnupg_addencryptkey — Add a key for encryption
    • gnupg_addsignkey — Add a key for signing
    • gnupg_cleardecryptkeys — Removes all keys which were set for decryption before
    • gnupg_clearencryptkeys — Removes all keys which were set for encryption before
    • gnupg_clearsignkeys — Removes all keys which were set for signing before
    • gnupg_decrypt — Decrypts a given text
    • gnupg_decryptverify — Decrypts and verifies a given text
    • gnupg_encrypt — Encrypts a given text
    • gnupg_encryptsign — Encrypts and signs a given text
    • gnupg_export — Exports a key
    • gnupg_geterror — Returns the errortext, if a function fails
    • gnupg_getprotocol — Returns the currently active protocol for all operations
    • gnupg_import — Imports a key
    • gnupg_init — Initialize a connection
    • gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern
    • gnupg_setarmor — Toggle armored output
    • gnupg_seterrormode — Sets the mode for error_reporting
    • gnupg_setsignmode — Sets the mode for signing
    • gnupg_sign — Signs a given text
    • gnupg_verify — Verifies a signed text
fdf_set_version
Wstęp
Generowanie nietekstowych formatów danych


Wstęp

This module allows you to interact with » gnupg.

GnuPG
Instalacja/Konfiguracja
GnuPG


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
GnuPG


Wymagania

The gnupg extension requires PHP 4.3. To use this extension in an OO style, PHP 5 is required.

This extension requires the » gpgme library

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/gnupg.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

GNUPG_SIG_MODE_NORMAL (integer)
GNUPG_SIG_MODE_DETACH (integer)
GNUPG_SIG_MODE_CLEAR (integer)
GNUPG_VALIDITY_UNKNOWN (integer)
GNUPG_VALIDITY_UNDEFINED (integer)
GNUPG_VALIDITY_NEVER (integer)
GNUPG_VALIDITY_MARGINAL (integer)
GNUPG_VALIDITY_FULL (integer)
GNUPG_VALIDITY_ULTIMATE (integer)
GNUPG_PROTOCOL_OpenPGP (integer)
GNUPG_PROTOCOL_CMS (integer)
GNUPG_SIGSUM_VALID (integer)
GNUPG_SIGSUM_GREEN (integer)
GNUPG_SIGSUM_RED (integer)
GNUPG_SIGSUM_KEY_REVOKED (integer)
GNUPG_SIGSUM_KEY_EXPIRED (integer)
GNUPG_SIGSUM_KEY_MISSING (integer)
GNUPG_SIGSUM_SIG_EXPIRED (integer)
GNUPG_SIGSUM_CRL_MISSING (integer)
GNUPG_SIGSUM_CRL_TOO_OLD (integer)
GNUPG_SIGSUM_BAD_POLICY (integer)
GNUPG_SIGSUM_SYS_ERROR (integer)
GNUPG_ERROR_WARNING (integer)
GNUPG_ERROR_EXCEPTION (integer)
GNUPG_ERROR_SILENT (integer)
Typy zasobów
Przykłady
GnuPG


Przykłady

Spis treści

  • Clearsign text
Stałe predefiniowane
Clearsign text
GnuPG


Clearsign text

This example will clearsign a given text.

Przykład #1 gnupg clearsign example (procedural)

<?php
// init gnupg
$res = gnupg_init();
// not really needed. Clearsign is default
gnupg_setsignmode($res,GNUPG_SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = gnupg_sign($res,"just a test");
echo $signed;
?>

Przykład #2 gnupg clearsign example (OO)

<?php
// new class
$gnupg = new gnupg();
// not really needed. Clearsign is default
$gnupg->setsignmode(gnupg::SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
$gnupg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = $gnupg->sign("just a test");
echo $signed;
?>

Przykład #3 keylistiterator

This extension also comes with an Iterator for your keyring.

<?php
// create a new iterator for listing all public keys that matches 'example'
$iterator = new gnupg_keylistiterator("example");
foreach($iterator as $fingerprint => $userid){
    echo $fingerprint." -> ".$userid."\n";
}
?>
Przykłady
GnuPG Funkcje
Przykłady


GnuPG Funkcje

Notatki

This extension makes use of the keyring of the current user. This keyring is normally located in ~./.gnupg/. To specify a custom location, store the path to the keyring in the environment variable GNUPGHOME. See putenv for more information how to do this.

Some functions require the specification of a key. This specification can be anything that refers to a unique key (userid, key-id, fingerprint, ...). This documentation uses the fingerprint in all examples.

Spis treści

  • gnupg_adddecryptkey — Add a key for decryption
  • gnupg_addencryptkey — Add a key for encryption
  • gnupg_addsignkey — Add a key for signing
  • gnupg_cleardecryptkeys — Removes all keys which were set for decryption before
  • gnupg_clearencryptkeys — Removes all keys which were set for encryption before
  • gnupg_clearsignkeys — Removes all keys which were set for signing before
  • gnupg_decrypt — Decrypts a given text
  • gnupg_decryptverify — Decrypts and verifies a given text
  • gnupg_encrypt — Encrypts a given text
  • gnupg_encryptsign — Encrypts and signs a given text
  • gnupg_export — Exports a key
  • gnupg_geterror — Returns the errortext, if a function fails
  • gnupg_getprotocol — Returns the currently active protocol for all operations
  • gnupg_import — Imports a key
  • gnupg_init — Initialize a connection
  • gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern
  • gnupg_setarmor — Toggle armored output
  • gnupg_seterrormode — Sets the mode for error_reporting
  • gnupg_setsignmode — Sets the mode for signing
  • gnupg_sign — Signs a given text
  • gnupg_verify — Verifies a signed text
Clearsign text
gnupg_adddecryptkey
GnuPG


Add a key for decryption

GnuPG Funkcje
gnupg_addencryptkey
GnuPG Funkcje
PHP Manual

gnupg_adddecryptkey

(PECL gnupg >= 0.5)

gnupg_adddecryptkey — Add a key for decryption

Opis

bool gnupg_adddecryptkey ( resource $identifier , string $fingerprint , string $passphrase )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

fingerprint

Odcisk klucza.

passphrase

The pass phrase.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Procedural gnupg_adddecryptkey() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Przykład #2 OO gnupg_adddecryptkey() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

GnuPG Funkcje
gnupg_addencryptkey
GnuPG Funkcje


Add a key for encryption

gnupg_adddecryptkey
gnupg_addsignkey
GnuPG Funkcje
PHP Manual

gnupg_addencryptkey

(PECL gnupg >= 0.5)

gnupg_addencryptkey — Add a key for encryption

Opis

bool gnupg_addencryptkey ( resource $identifier , string $fingerprint )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

fingerprint

Odcisk klucza.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Procedural gnupg_addencryptkey() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>

Przykład #2 OO gnupg_addencryptkey() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
?>

gnupg_adddecryptkey
gnupg_addsignkey
GnuPG Funkcje


Add a key for signing

gnupg_addencryptkey
gnupg_cleardecryptkeys
GnuPG Funkcje
PHP Manual

gnupg_addsignkey

(PECL gnupg >= 0.5)

gnupg_addsignkey — Add a key for signing

Opis

bool gnupg_addsignkey ( resource $identifier , string $fingerprint [, string $passphrase ] )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

fingerprint

Odcisk klucza.

passphrase

The pass phrase.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Procedural gnupg_addsignkey() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Przykład #2 OO gnupg_addsignkey() example

<?php
$gpg = new gnupg();
$gpg -> addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

gnupg_addencryptkey
gnupg_cleardecryptkeys
GnuPG Funkcje


Removes all keys which were set for decryption before

gnupg_addsignkey
gnupg_clearencryptkeys
GnuPG Funkcje
PHP Manual

gnupg_cleardecryptkeys

(PECL gnupg >= 0.5)

gnupg_cleardecryptkeys — Removes all keys which were set for decryption before

Opis

bool gnupg_cleardecryptkeys ( resource $identifier )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Procedural gnupg_cleardecryptkeys() example

<?php
$res = gnupg_init();
gnupg_cleardecryptkeys($res);
?>

Przykład #2 OO gnupg_cleardecryptkeys() example

<?php
$gpg = new gnupg();
$gpg -> cleardecryptkeys();
?>

gnupg_addsignkey
gnupg_clearencryptkeys
GnuPG Funkcje


Removes all keys which were set for encryption before

gnupg_cleardecryptkeys
gnupg_clearsignkeys
GnuPG Funkcje
PHP Manual

gnupg_clearencryptkeys

(PECL gnupg >= 0.5)

gnupg_clearencryptkeys — Removes all keys which were set for encryption before

Opis

bool gnupg_clearencryptkeys ( resource $identifier )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Procedural gnupg_clearencryptkeys() example

<?php
$res = gnupg_init();
gnupg_clearencryptkeys($res);
?>

Przykład #2 OO gnupg_clearencryptkeys() example

<?php
$gpg = new gnupg();
$gpg -> clearencryptkeys();
?>

gnupg_cleardecryptkeys
gnupg_clearsignkeys
GnuPG Funkcje


Removes all keys which were set for signing before

gnupg_clearencryptkeys
gnupg_decrypt
GnuPG Funkcje
PHP Manual

gnupg_clearsignkeys

(PECL gnupg >= 0.5)

gnupg_clearsignkeys — Removes all keys which were set for signing before

Opis

bool gnupg_clearsignkeys ( resource $identifier )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Procedural gnupg_clearsignkeys() example

<?php
$res = gnupg_init();
gnupg_clearsignkeys($res);
?>

Przykład #2 OO gnupg_clearsignkeys() example

<?php
$gpg = new gnupg();
$gpg -> clearsignkeys();
?>

gnupg_clearencryptkeys
gnupg_decrypt
GnuPG Funkcje


Decrypts a given text

gnupg_clearsignkeys
gnupg_decryptverify
GnuPG Funkcje
PHP Manual

gnupg_decrypt

(PECL gnupg >= 0.1)

gnupg_decrypt — Decrypts a given text

Opis

string gnupg_decrypt ( resource $identifier , string $text )

Decrypts the given text with the keys, which were set with gnupg_adddecryptkey before.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

text

The text being decrypted.

Zwracane wartości

On success, this function returns the decrypted text. On failure, this function returns FALSE.

Przykłady

Przykład #1 Procedural gnupg_decrypt() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = gnupg_decrypt($res,$encrypted_text);
echo $plain;
?>

Przykład #2 OO gnupg_encrypt() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = $gpg -> decrypt($encrypted_text);
echo $plain;
?>

gnupg_clearsignkeys
gnupg_decryptverify
GnuPG Funkcje


Decrypts and verifies a given text

gnupg_decrypt
gnupg_encrypt
GnuPG Funkcje
PHP Manual

gnupg_decryptverify

(PECL gnupg >= 0.2)

gnupg_decryptverify — Decrypts and verifies a given text

Opis

array gnupg_decryptverify ( resource $identifier , string $text , string &$plaintext )

Decrypts and verifies a given text and returns information about the signature.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

text

The text being decrypted.

plaintext

The parameter plaintext gets filled with the decrypted text.

Zwracane wartości

On success, this function returns information about the signature and fills the plaintext parameter with the decrypted text. On failure, this function returns FALSE.

Przykłady

Przykład #1 Procedural gnupg_decryptverify() example

<?php
$plaintext = "";
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = gnupg_decryptverify($res,$text,$plaintext);
print_r($info);
?>

Przykład #2 OO gnupg_decryptverify() example

<?php
$plaintext = "";
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = $gpg -> decryptverify($text,$plaintext);
print_r($info);
?>

gnupg_decrypt
gnupg_encrypt
GnuPG Funkcje


Encrypts a given text

gnupg_decryptverify
gnupg_encryptsign
GnuPG Funkcje
PHP Manual

gnupg_encrypt

(PECL gnupg >= 0.1)

gnupg_encrypt — Encrypts a given text

Opis

string gnupg_encrypt ( resource $identifier , string $plaintext )

Encrypts the given plaintext with the keys, which were set with gnupg_addencryptkey before and returns the encrypted text.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

plaintext

The text being encrypted.

Zwracane wartości

On success, this function returns the encrypted text. On failure, this function returns FALSE.

Przykłady

Przykład #1 Procedural gnupg_encrypt() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "just a test");
echo $enc;
?>

Przykład #2 OO gnupg_encrypt() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$enc = $gpg -> encrypt("just a test");
echo $enc;
?>

gnupg_decryptverify
gnupg_encryptsign
GnuPG Funkcje


Encrypts and signs a given text

gnupg_encrypt
gnupg_export
GnuPG Funkcje
PHP Manual

gnupg_encryptsign

(PECL gnupg >= 0.2)

gnupg_encryptsign — Encrypts and signs a given text

Opis

string gnupg_encryptsign ( resource $identifier , string $plaintext )

Encrypts and signs the given plaintext with the keys, which were set with gnupg_addsignkey and gnupg_addencryptkey before and returns the encrypted and signed text.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

plaintext

The text being encrypted.

Zwracane wartości

On success, this function returns the encrypted and signed text. On failure, this function returns FALSE.

Przykłady

Przykład #1 Procedural gnupg_encryptsign() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = gnupg_encryptsign($res, "just a test");
echo $enc;
?>

Przykład #2 OO gnupg_encryptsign() example

<?php
$gpg = new gnupg();
$gpg -> addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$gpg -> addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = $gpg -> encryptsign("just a test");
echo $enc;
?>

gnupg_encrypt
gnupg_export
GnuPG Funkcje


Exports a key

gnupg_encryptsign
gnupg_geterror
GnuPG Funkcje
PHP Manual

gnupg_export

(PECL gnupg >= 0.1)

gnupg_export — Exports a key

Opis

string gnupg_export ( resource $identifier , string $fingerprint )

Exports the key fingerprint.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

fingerprint

Odcisk klucza.

Zwracane wartości

On success, this function returns the keydata. On failure, this function returns FALSE.

Przykłady

Przykład #1 Procedural gnupg_export() example

<?php
$res = gnupg_init();
$export = gnupg_export($res,"8660281B6051D071D94B5B230549F9DC851566DC");
echo $export;
?>

Przykład #2 OO gnupg_export() example

<?php
$gpg = new gnupg();
$export = $gpg -> export("8660281B6051D071D94B5B230549F9DC851566DC");
?>

gnupg_encryptsign
gnupg_geterror
GnuPG Funkcje


Returns the errortext, if a function fails

gnupg_export
gnupg_getprotocol
GnuPG Funkcje
PHP Manual

gnupg_geterror

(PECL gnupg >= 0.1)

gnupg_geterror — Returns the errortext, if a function fails

Opis

string gnupg_geterror ( resource $identifier )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

Zwracane wartości

Returns an errortext, if an error has occurred, otherwise FALSE.

Przykłady

Przykład #1 Procedural gnupg_geterror() example

<?php
$res = gnupg_init();
echo gnupg_geterror($res);
?>

Przykład #2 OO gnupg_geterror() example

<?php
$gpg = new gnupg();
echo $gpg -> geterror();
?>

gnupg_export
gnupg_getprotocol
GnuPG Funkcje


Returns the currently active protocol for all operations

gnupg_geterror
gnupg_import
GnuPG Funkcje
PHP Manual

gnupg_getprotocol

(PECL gnupg >= 0.1)

gnupg_getprotocol — Returns the currently active protocol for all operations

Opis

int gnupg_getprotocol ( resource $identifier )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

Zwracane wartości

Returns the currently active protocol, which can be one of GNUPG_PROTOCOL_OpenPGP or GNUPG_PROTOCOL_CMS.

Przykłady

Przykład #1 Procedural gnupg_getprotocol() example

<?php
$res = gnupg_init();
echo gnupg_getprotocol($res);
?>

Przykład #2 OO gnupg_getprotocol() example

<?php
$gpg = new gnupg();
echo $gpg -> getprotocol();
?>

gnupg_geterror
gnupg_import
GnuPG Funkcje


Imports a key

gnupg_getprotocol
gnupg_init
GnuPG Funkcje
PHP Manual

gnupg_import

(PECL gnupg >= 0.3)

gnupg_import — Imports a key

Opis

array gnupg_import ( resource $identifier , string $keydata )

Imports the key keydata and returns an array with information about the importprocess.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

keydata

The data key that is being imported.

Zwracane wartości

On success, this function returns and info-array about the importprocess. On failure, this function returns FALSE.

Przykłady

Przykład #1 Procedural gnupg_import() example

<?php
$res = gnupg_init();
$info = gnupg_import($res,$keydata);
print_r($info);
?>

Przykład #2 OO gnupg_import() example

<?php
$gpg = new gnupg();
$info = $gpg -> import($keydata);
print_r($info);
?>

gnupg_getprotocol
gnupg_init
GnuPG Funkcje


Initialize a connection

gnupg_import
gnupg_keyinfo
GnuPG Funkcje
PHP Manual

gnupg_init

(PECL gnupg >= 0.4)

gnupg_init — Initialize a connection

Opis

resource gnupg_init ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A GnuPG resource connection used by other GnuPG functions.

Przykłady

Przykład #1 Procedural gnupg_init() example

<?php
$res = gnupg_init();
?>

Przykład #2 OO gnupg initializer example

<?php
$gpg = new gnupg();
?>

gnupg_import
gnupg_keyinfo
GnuPG Funkcje


Returns an array with information about all keys that matches the given pattern

gnupg_init
gnupg_setarmor
GnuPG Funkcje
PHP Manual

gnupg_keyinfo

(PECL gnupg >= 0.1)

gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern

Opis

array gnupg_keyinfo ( resource $identifier , string $pattern )

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

pattern

The pattern being checked against the keys.

Zwracane wartości

Returns an array with information about all keys that matches the given pattern or FALSE, if an error has occurred.

Przykłady

Przykład #1 Procedural gnupg_keyinfo() example

<?php
$res = gnupg_init();
$info = gnupg_keyinfo($res, 'test');
print_r($info);
?>

Przykład #2 OO gnupg_keyinfo() example

<?php
$gpg = new gnupg();
$info = $gpg -> keyinfo("test");
print_r($info);
?>

gnupg_init
gnupg_setarmor
GnuPG Funkcje


Toggle armored output

gnupg_keyinfo
gnupg_seterrormode
GnuPG Funkcje
PHP Manual

gnupg_setarmor

(PECL gnupg >= 0.1)

gnupg_setarmor — Toggle armored output

Opis

bool gnupg_setarmor ( resource $identifier , int $armor )

Toggle the armored output.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

armor

Pass a non-zero integer-value to this function to enable armored-output (default). Pass 0 to disable armored output.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Procedural gnupg_setarmor() example

<?php
$res = gnupg_init();
gnupg_setarmor($res,1); // enable armored output;
gnupg_setarmor($res,0); // disable armored output;
?>

Przykład #2 OO gnupg_setarmor() example

<?php
$gpg = new gnupg();
$gpg -> setarmor(1); // enable armored output;
$gpg -> setarmor(0); // disable armored output;
?>

gnupg_keyinfo
gnupg_seterrormode
GnuPG Funkcje


Sets the mode for error_reporting

gnupg_setarmor
gnupg_setsignmode
GnuPG Funkcje
PHP Manual

gnupg_seterrormode

(PECL gnupg >= 0.6)

gnupg_seterrormode — Sets the mode for error_reporting

Opis

void gnupg_seterrormode ( resource $identifier , int $errormode )

Sets the mode for error_reporting.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

errormode

The error mode.

errormode takes a constant indicating what type of error_reporting should be used. The possible values are GNUPG_ERROR_WARNING, GNUPG_ERROR_EXCEPTION and GNUPG_ERROR_SILENT. By default GNUPG_ERROR_SILENT is used.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Procedural gnupg_seterrormode() example

<?php
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING); // raise a PHP-Warning in case of an error
?>

Przykład #2 OO gnupg_seterrormode() example

<?php
$gpg = new gnupg();
$gpg -> seterrormode(gnupg::ERROR_EXCEPTION); // throw an exception in case of an error
?>

gnupg_setarmor
gnupg_setsignmode
GnuPG Funkcje


Sets the mode for signing

gnupg_seterrormode
gnupg_sign
GnuPG Funkcje
PHP Manual

gnupg_setsignmode

(PECL gnupg >= 0.1)

gnupg_setsignmode — Sets the mode for signing

Opis

bool gnupg_setsignmode ( resource $identifier , int $signmode )

Sets the mode for signing.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

sigmode

The mode for signing.

signmode takes a constant indicating what type of signature should be produced. The possible values are GNUPG_SIG_MODE_NORMAL, GNUPG_SIG_MODE_DETACH and GNUPG_SIG_MODE_CLEAR. By default GNUPG_SIG_MODE_CLEAR is used.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Procedural gnupg_setsignmode() example

<?php
$res = gnupg_init();
gnupg_setsignmode($res,GNUPG_SIG_MODE_DETACH); // produce a detached signature
?>

Przykład #2 OO gnupg_setsignmode() example

<?php
$gpg = new gnupg();
$gpg -> setsignmode(gnupg::SIG_MODE_DETACH); // produce a detached signature
?>

gnupg_seterrormode
gnupg_sign
GnuPG Funkcje


Signs a given text

gnupg_setsignmode
gnupg_verify
GnuPG Funkcje
PHP Manual

gnupg_sign

(PECL gnupg >= 0.1)

gnupg_sign — Signs a given text

Opis

string gnupg_sign ( resource $identifier , string $plaintext )

Signs the given plaintext with the keys, which were set with gnupg_addsignkey before and returns the signed text or the signature, depending on what was set with gnupg_setsignmode.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

plaintext

The plain text being signed.

Zwracane wartości

On success, this function returns the signed text or the signature. On failure, this function returns FALSE.

Przykłady

Przykład #1 Procedural gnupg_sign() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = gnupg_sign($res, "just a test");
echo $signed;
?>

Przykład #2 OO gnupg_sign() example

<?php
$gpg = new gnupg();
$gpg -> setsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = $gpg -> sign("just a test");
echo $signed;
?>

gnupg_setsignmode
gnupg_verify
GnuPG Funkcje


Verifies a signed text

gnupg_sign
haru
GnuPG Funkcje
PHP Manual

gnupg_verify

(PECL gnupg >= 0.1)

gnupg_verify — Verifies a signed text

Opis

array gnupg_verify ( resource $identifier , string $signed_text , string $signature [, string &$plaintext ] )

Verifies the given signed_text and returns information about the signature.

Parametry

identifier

Identyfikator gnupg, do wywołania funkcji gnupg_init() lub gnupg.

signed_text

The signed text.

signature

The signature. To verify a clearsigned text, set signature to FALSE.

plaintext

The plain text. If this optional parameter is passed, it is filled with the plain text.

Zwracane wartości

On success, this function returns information about the signature. On failure, this function returns FALSE.

Przykłady

Przykład #1 Procedural gnupg_verify() example

<?php
$plaintext = "";
$res = gnupg_init();
// clearsigned
$info = gnupg_verify($res,$signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = gnupg_verify($res,$signed_text,$signature);
print_r($info);
?>

Przykład #2 OO gnupg_verify() example

<?php
$plaintext = "";
$gpg = new gnupg();
// clearsigned
$info = $gpg -> verify($signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = $gpg -> verify($signed_text,$signature);
print_r($info);
?>

gnupg_sign
haru
GnuPG Funkcje


Haru PDF

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic PECL/haru example
  • Builtin Fonts And Encodings
    • Builtin Fonts
    • Builtin Encodings
  • HaruException — The HaruException class
  • HaruDoc — The HaruDoc class
    • HaruDoc::addPage — Add new page to the document
    • HaruDoc::addPageLabel — Set the numbering style for the specified range of pages
    • HaruDoc::__construct — Construct new HaruDoc instance
    • HaruDoc::createOutline — Create a HaruOutline instance
    • HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document
    • HaruDoc::getCurrentPage — Return current page of the document
    • HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding
    • HaruDoc::getFont — Get HaruFont instance
    • HaruDoc::getInfoAttr — Get current value of the specified document attribute
    • HaruDoc::getPageLayout — Get current page layout
    • HaruDoc::getPageMode — Get current page mode
    • HaruDoc::getStreamSize — Get the size of the temporary stream
    • HaruDoc::insertPage — Insert new page just before the specified page
    • HaruDoc::loadJPEG — Load a JPEG image
    • HaruDoc::loadPNG — Load PNG image and return HaruImage instance
    • HaruDoc::loadRaw — Load a RAW image
    • HaruDoc::loadTTC — Load the font with the specified index from TTC file
    • HaruDoc::loadTTF — Load TTF font file
    • HaruDoc::loadType1 — Load Type1 font
    • HaruDoc::output — Write the document data to the output buffer
    • HaruDoc::readFromStream — Read data from the temporary stream
    • HaruDoc::resetError — Reset error state of the document handle
    • HaruDoc::resetStream — Rewind the temporary stream
    • HaruDoc::save — Save the document into the specified file
    • HaruDoc::saveToStream — Save the document into a temporary stream
    • HaruDoc::setCompressionMode — Set compression mode for the document
    • HaruDoc::setCurrentEncoder — Set the current encoder for the document
    • HaruDoc::setEncryptionMode — Set encryption mode for the document
    • HaruDoc::setInfoAttr — Set the info attribute of the document
    • HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document
    • HaruDoc::setOpenAction — Define which page is shown when the document is opened
    • HaruDoc::setPageLayout — Set how pages should be displayed
    • HaruDoc::setPageMode — Set how the document should be displayed
    • HaruDoc::setPagesConfiguration — Set the number of pages per set of pages
    • HaruDoc::setPassword — Set owner and user passwords for the document
    • HaruDoc::setPermission — Set permissions for the document
    • HaruDoc::useCNSEncodings — Enable Chinese simplified encodings
    • HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts
    • HaruDoc::useCNTEncodings — Enable Chinese traditional encodings
    • HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts
    • HaruDoc::useJPEncodings — Enable Japanese encodings
    • HaruDoc::useJPFonts — Enable builtin Japanese fonts
    • HaruDoc::useKREncodings — Enable Korean encodings
    • HaruDoc::useKRFonts — Enable builtin Korean fonts
  • HaruPage — The HaruPage class
    • HaruPage::arc — Append an arc to the current path
    • HaruPage::beginText — Begin a text object and set the current text position to (0,0)
    • HaruPage::circle — Append a circle to the current path
    • HaruPage::closePath — Append a straight line from the current point to the start point of the path
    • HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix
    • HaruPage::createDestination — Create new HaruDestination instance
    • HaruPage::createLinkAnnotation — Create new HaruAnnotation instance
    • HaruPage::createTextAnnotation — Create new HaruAnnotation instance
    • HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance
    • HaruPage::curveTo2 — Append a Bezier curve to the current path
    • HaruPage::curveTo3 — Append a Bezier curve to the current path
    • HaruPage::curveTo — Append a Bezier curve to the current path
    • HaruPage::drawImage — Show image at the page
    • HaruPage::ellipse — Append an ellipse to the current path
    • HaruPage::endPath — End current path object without filling and painting operations
    • HaruPage::endText — End current text object
    • HaruPage::eofill — Fill current path using even-odd rule
    • HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path
    • HaruPage::fill — Fill current path using nonzero winding number rule
    • HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path
    • HaruPage::getCharSpace — Get the current value of character spacing
    • HaruPage::getCMYKFill — Get the current filling color
    • HaruPage::getCMYKStroke — Get the current stroking color
    • HaruPage::getCurrentFont — Get the currently used font
    • HaruPage::getCurrentFontSize — Get the current font size
    • HaruPage::getCurrentPos — Get the current position for path painting
    • HaruPage::getCurrentTextPos — Get the current position for text printing
    • HaruPage::getDash — Get the current dash pattern
    • HaruPage::getFillingColorSpace — Get the current filling color space
    • HaruPage::getFlatness — Get the flatness of the page
    • HaruPage::getGMode — Get the current graphics mode
    • HaruPage::getGrayFill — Get the current filling color
    • HaruPage::getGrayStroke — Get the current stroking color
    • HaruPage::getHeight — Get the height of the page
    • HaruPage::getHorizontalScaling — Get the current value of horizontal scaling
    • HaruPage::getLineCap — Get the current line cap style
    • HaruPage::getLineJoin — Get the current line join style
    • HaruPage::getLineWidth — Get the current line width
    • HaruPage::getMiterLimit — Get the value of miter limit
    • HaruPage::getRGBFill — Get the current filling color
    • HaruPage::getRGBStroke — Get the current stroking color
    • HaruPage::getStrokingColorSpace — Get the current stroking color space
    • HaruPage::getTextLeading — Get the current value of line spacing
    • HaruPage::getTextMatrix — Get the current text transformation matrix of the page
    • HaruPage::getTextRenderingMode — Get the current text rendering mode
    • HaruPage::getTextRise — Get the current value of text rising
    • HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing
    • HaruPage::getTransMatrix — Get the current transformation matrix of the page
    • HaruPage::getWidth — Get the width of the page
    • HaruPage::getWordSpace — Get the current value of word spacing
    • HaruPage::lineTo — Draw a line from the current point to the specified point
    • HaruPage::measureText — Calculate the number of characters which can be included within the specified width
    • HaruPage::moveTextPos — Move text position to the specified offset
    • HaruPage::moveTo — Set starting point for new drawing path
    • HaruPage::moveToNextLine — Move text position to the start of the next line
    • HaruPage::rectangle — Append a rectangle to the current path
    • HaruPage::setCharSpace — Set character spacing for the page
    • HaruPage::setCMYKFill — Set filling color for the page
    • HaruPage::setCMYKStroke — Set stroking color for the page
    • HaruPage::setDash — Set the dash pattern for the page
    • HaruPage::setFlatness — Set flatness for the page
    • HaruPage::setFontAndSize — Set font and fontsize for the page
    • HaruPage::setGrayFill — Set filling color for the page
    • HaruPage::setGrayStroke — Sets stroking color for the page
    • HaruPage::setHeight — Set height of the page
    • HaruPage::setHorizontalScaling — Set horizontal scaling for the page
    • HaruPage::setLineCap — Set the shape to be used at the ends of lines
    • HaruPage::setLineJoin — Set line join style for the page
    • HaruPage::setLineWidth — Set line width for the page
    • HaruPage::setMiterLimit — Set the current value of the miter limit of the page
    • HaruPage::setRGBFill — Set filling color for the page
    • HaruPage::setRGBStroke — Set stroking color for the page
    • HaruPage::setRotate — Set rotation angle of the page
    • HaruPage::setSize — Set size and direction of the page
    • HaruPage::setSlideShow — Set transition style for the page
    • HaruPage::setTextLeading — Set text leading (line spacing) for the page
    • HaruPage::setTextMatrix — Set the current text transformation matrix of the page
    • HaruPage::setTextRenderingMode — Set text rendering mode for the page
    • HaruPage::setTextRise — Set the current value of text rising
    • HaruPage::setWidth — Set width of the page
    • HaruPage::setWordSpace — Set word spacing for the page
    • HaruPage::showText — Print text at the current position of the page
    • HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text
    • HaruPage::stroke — Paint current path
    • HaruPage::textOut — Print the text on the specified position
    • HaruPage::textRect — Print the text inside the specified region
  • HaruFont — The HaruFont class
    • HaruFont::getAscent — Get the vertical ascent of the font
    • HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters
    • HaruFont::getDescent — Get the vertical descent of the font
    • HaruFont::getEncodingName — Get the name of the encoding
    • HaruFont::getFontName — Get the name of the font
    • HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces
    • HaruFont::getUnicodeWidth — Get the width of the character in the font
    • HaruFont::getXHeight — Get the distance from the baseline of lowercase letters
    • HaruFont::measureText — Calculate the number of characters which can be included within the specified width
  • HaruImage — The HaruImage class
    • HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image
    • HaruImage::getColorSpace — Get the name of the color space
    • HaruImage::getHeight — Get the height of the image
    • HaruImage::getSize — Get size of the image
    • HaruImage::getWidth — Get the width of the image
    • HaruImage::setColorMask — Set the color mask of the image
    • HaruImage::setMaskImage — Set the image mask
  • HaruEncoder — The HaruEncoder class
    • HaruEncoder::getByteType — Get the type of the byte in the text
    • HaruEncoder::getType — Get the type of the encoder
    • HaruEncoder::getUnicode — Convert the specified character to unicode
    • HaruEncoder::getWritingMode — Get the writing mode of the encoder
  • HaruOutline — The HaruOutline class
    • HaruOutline::setDestination — Set the destination for the outline
    • HaruOutline::setOpened — Set the initial state of the outline
  • HaruAnnotation — The HaruAnnotation class
    • HaruAnnotation::setBorderStyle — Set the border style of the annotation
    • HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation
    • HaruAnnotation::setIcon — Set the icon style of the annotation
    • HaruAnnotation::setOpened — Set the initial state of the annotation
  • HaruDestination — The HaruDestination class
    • HaruDestination::setFit — Set the appearance of the page to fit the window
    • HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window
    • HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box
    • HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box
    • HaruDestination::setFitH — Set the appearance of the page to fit the window width
    • HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle
    • HaruDestination::setFitV — Set the appearance of the page to fit the window height
    • HaruDestination::setXYZ — Set the appearance of the page
gnupg_verify
Wstęp
Generowanie nietekstowych formatów danych


Wstęp

The PECL/haru extension provides bindings to the libHaru library. libHaru is a free, cross platform, and Open Source library for generating PDF files.

The Haru library (libHaru) may be found here: » http://libharu.org.

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.

haru
Instalacja/Konfiguracja
haru


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
haru


Wymagania

You need to install libharu first to be able to use PECL/haru. PECL/haru is tested with libharu 2.0.8, older versions might or might not work for you. PECL/haru also requires PHP 5.1.3 or newer.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/haru.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
haru


Przykłady

Spis treści

  • Basic PECL/haru example
Stałe predefiniowane
Basic PECL/haru example
haru


Basic PECL/haru example

Przykład #1 Fancy "Hello world"

<?php

$doc = new HaruDoc;

$doc->setPageMode(HaruDoc::PAGE_MODE_USE_THUMBS); /* show thumbnails */

$page = $doc->addPage(); /* add page to the document */
$page->setSize(HaruPage::SIZE_A4, HaruPage::LANDSCAPE); /* set the page to use A4 landscape format */

$courier = $doc->getFont("Courier-Bold"); /* we'll use the bundled font a few lines below */

$page->setRGBStroke(0, 0, 0); /* set colors */
$page->setRGBFill(0.7, 0.8, 0.9);
$page->rectangle(150, 150, 550, 250); /* draw a rectangle */

$page->fillStroke(); /* fill and stroke it */

$page->setDash(array(3, 3), 0); /* set dash style for lines at this page */
$page->setFontAndSize($courier, 60); /* set font and size */

$page->setRGBStroke(0.5, 0.5, 0.1); /* set line color */
$page->setRGBFill(1, 1, 1); /* set filling color */

$page->setTextRenderingMode(HaruPage::FILL_THEN_STROKE); /* fill and stroke text */

/* print the text */
$page->beginText();
$page->textOut(210, 270, "Hello World!");
$page->endText();

$doc->save("/tmp/test.pdf"); /* save the document into a file */

?>

Open the result document in your favourite PDF viewer and you should see a light-blue rectangle and white "Hello World!" on it.

Przykłady
Builtin Fonts And Encodings
Przykłady


Builtin Fonts And Encodings

Spis treści

  • Builtin Fonts
  • Builtin Encodings
Basic PECL/haru example
Builtin Fonts
haru


Builtin Fonts

These Base14 fonts are built-in into PDF and all viewers can display them. Using these fonts may decrease the size of the result file and make the processing faster, avoiding loading external fonts. However the fonts support only latin1 character set and you have to load external fonts if you need to use an other character set.

The Base14 fonts:

  • Courier

  • Courier-Bold

  • Courier-Oblique

  • Courier-BoldOblique

  • Helvetica

  • Helvetica-Bold

  • Helvetica-Oblique

  • Helvetica-BoldOblique

  • Times-Roman

  • Times-Bold

  • Times-Italic

  • Times-BoldItalic

  • Symbol

  • ZapfDingbats

Builtin Fonts And Encodings
Builtin Encodings
Builtin Fonts And Encodings


Builtin Encodings

Single-byte character set encodings
Name | Description
StandardEncoding | The default encoding of PDF.
MacRomanEncoding | The standard encoding of Mac OS.
WinAnsiEncoding | The standard encoding of Windows.
FontSpecific | The font built-in encoding.
ISO8859-2 | Latin2 (East European)
ISO8859-3 | Latin3 (South European)
ISO8859-4 | Latin4 (North European)
ISO8859-5 | Cyrillic
ISO8859-6 | Arabic
ISO8859-7 | Greek
ISO8859-8 | Hebrew
ISO8859-9 | Latin5 (Turkish)
ISO8859-10 | Latin6 (Nordic)
ISO8859-11 | Thai
ISO8859-13 | Latin7 (Baltic Rim)
ISO8859-14 | Latin8 (Celtic)
ISO8859-15 | Latin9
ISO8859-16 | Latin10
CP1250 | MS Windows Codepage 1250.
CP1251 | MS Windows Codepage 1251.
CP1252 | MS Windows Codepage 1252.
CP1253 | MS Windows Codepage 1253.
CP1254 | MS Windows Codepage 1254.
CP1255 | MS Windows Codepage 1255.
CP1256 | MS Windows Codepage 1256.
CP1257 | MS Windows Codepage 1257.
CP1258 | MS Windows Codepage 1258.
KOI8-R | Cyrillic character set.
Multi-byte character set encodings
Name | Description
GB-EUC-H | EUC-CN encoding.
GB-EUC-V | Vertical writing version of GB-EUC-H.
GBK-EUC-H | Microsoft Code Page 936 (lfCharSet 0x86) GBK encoding.
GBK-EUC-V | Vertical writing version of GBK-EUC-H.
ETen-B5-H | Microsoft Code Page 950 (lfCharSet 0x88) Big Five character set with ETen extensions.
ETen-B5-V | Vertical writing version of ETen-B5-H.
90ms-RKSJ-H | Microsoft Code Page 932, JIS X 0208 character.
90ms-RKSJ-V | Vertical writing version of 90ms-RKSJ-V.
90msp-RKSJ-H | Microsoft Code Page 932, JIS X 0208 character (proportional).
EUC-H | JIS X 0208 character set, EUC-JP encoding.
EUC-V | Vertical writing version of EUC-H.
KSC-EUC-H | KS X 1001:1992 character set, EUC-KR encoding.
KSC-EUC-V | Vertical writing version of KSC-EUC-V.
KSCms-UHC-H | Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (proportional).
KSCms-UHC-HW-H | Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (fixed width).
KSCms-UHC-HW-V | Vertical writing version of KSCms-UHC-HW-H.
Builtin Fonts
HaruException
Builtin Fonts And Encodings


The HaruException class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Exception Class.

Krótki opis klasy

HaruException extends Exception {
/* Inherits */
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 )
}
Builtin Encodings
HaruDoc
haru


The HaruDoc class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Document Class.

Krótki opis klasy

HaruDoc {
/* Metody */
object addPage ( void )
bool addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] )
__construct ( void )
object createOutline ( string $title [, object $parent_outline [, object $encoder ]] )
object getCurrentEncoder ( void )
object getCurrentPage ( void )
object getEncoder ( string $encoding )
object getFont ( string $fontname [, string $encoding ] )
string getInfoAttr ( int $type )
int getPageLayout ( void )
int getPageMode ( void )
int getStreamSize ( void )
object insertPage ( object $page )
object loadJPEG ( string $filename )
object loadPNG ( string $filename [, bool $deferred = false ] )
object loadRaw ( string $filename , int $width , int $height , int $color_space )
string loadTTC ( string $fontfile , int $index [, bool $embed = false ] )
string loadTTF ( string $fontfile [, bool $embed = false ] )
string loadType1 ( string $afmfile [, string $pfmfile ] )
bool output ( void )
string readFromStream ( int $bytes )
bool resetError ( void )
bool resetStream ( void )
bool save ( string $file )
bool saveToStream ( void )
bool setCompressionMode ( int $mode )
bool setCurrentEncoder ( string $encoding )
bool setEncryptionMode ( int $mode [, int $key_len = 5 ] )
bool setInfoAttr ( int $type , string $info )
bool setInfoDateAttr ( int $type , int $year , int $month , int $day , int $hour , int $min , int $sec , string $ind , int $off_hour , int $off_min )
bool setOpenAction ( object $destination )
bool setPageLayout ( int $layout )
bool setPageMode ( int $mode )
bool setPagesConfiguration ( int $page_per_pages )
bool setPassword ( string $owner_password , string $user_password )
bool setPermission ( int $permission )
bool useCNSEncodings ( void )
bool useCNSFonts ( void )
bool useCNTEncodings ( void )
bool useCNTFonts ( void )
bool useJPEncodings ( void )
bool useJPFonts ( void )
bool useKREncodings ( void )
bool useKRFonts ( void )
}

Stałe predefiniowane

Type | Name | Description
int | HaruDoc::CS_DEVICE_GRAY |
int | HaruDoc::CS_DEVICE_RGB |
int | HaruDoc::CS_DEVICE_CMYK |
int | HaruDoc::CS_CAL_GRAY |
int | HaruDoc::CS_CAL_RGB |
int | HaruDoc::CS_LAB |
int | HaruDoc::CS_ICC_BASED |
int | HaruDoc::CS_SEPARATION |
int | HaruDoc::CS_DEVICE_N |
int | HaruDoc::CS_INDEXED |
int | HaruDoc::CS_PATTERN |
int | HaruDoc::ENABLE_READ |
int | HaruDoc::ENABLE_PRINT |
int | HaruDoc::ENABLE_EDIT_ALL |
int | HaruDoc::ENABLE_COPY |
int | HaruDoc::ENABLE_EDIT |
int | HaruDoc::ENCRYPT_R2 |
int | HaruDoc::ENCRYPT_R3 |
int | HaruDoc::INFO_AUTHOR |
int | HaruDoc::INFO_CREATOR |
int | HaruDoc::INFO_TITLE |
int | HaruDoc::INFO_SUBJECT |
int | HaruDoc::INFO_KEYWORDS |
int | HaruDoc::INFO_CREATION_DATE |
int | HaruDoc::INFO_MOD_DATE |
int | HaruDoc::COMP_NONE |
int | HaruDoc::COMP_TEXT |
int | HaruDoc::COMP_IMAGE |
int | HaruDoc::COMP_METADATA |
int | HaruDoc::COMP_ALL |
int | HaruDoc::PAGE_LAYOUT_SINGLE |
int | HaruDoc::PAGE_LAYOUT_ONE_COLUMN |
int | HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT |
int | HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT |
int | HaruDoc::PAGE_MODE_USE_NONE |
int | HaruDoc::PAGE_MODE_USE_OUTLINE |
int | HaruDoc::PAGE_MODE_USE_THUMBS |
int | HaruDoc::PAGE_MODE_FULL_SCREEN |

Spis treści

  • HaruDoc::addPage — Add new page to the document
  • HaruDoc::addPageLabel — Set the numbering style for the specified range of pages
  • HaruDoc::__construct — Construct new HaruDoc instance
  • HaruDoc::createOutline — Create a HaruOutline instance
  • HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document
  • HaruDoc::getCurrentPage — Return current page of the document
  • HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding
  • HaruDoc::getFont — Get HaruFont instance
  • HaruDoc::getInfoAttr — Get current value of the specified document attribute
  • HaruDoc::getPageLayout — Get current page layout
  • HaruDoc::getPageMode — Get current page mode
  • HaruDoc::getStreamSize — Get the size of the temporary stream
  • HaruDoc::insertPage — Insert new page just before the specified page
  • HaruDoc::loadJPEG — Load a JPEG image
  • HaruDoc::loadPNG — Load PNG image and return HaruImage instance
  • HaruDoc::loadRaw — Load a RAW image
  • HaruDoc::loadTTC — Load the font with the specified index from TTC file
  • HaruDoc::loadTTF — Load TTF font file
  • HaruDoc::loadType1 — Load Type1 font
  • HaruDoc::output — Write the document data to the output buffer
  • HaruDoc::readFromStream — Read data from the temporary stream
  • HaruDoc::resetError — Reset error state of the document handle
  • HaruDoc::resetStream — Rewind the temporary stream
  • HaruDoc::save — Save the document into the specified file
  • HaruDoc::saveToStream — Save the document into a temporary stream
  • HaruDoc::setCompressionMode — Set compression mode for the document
  • HaruDoc::setCurrentEncoder — Set the current encoder for the document
  • HaruDoc::setEncryptionMode — Set encryption mode for the document
  • HaruDoc::setInfoAttr — Set the info attribute of the document
  • HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document
  • HaruDoc::setOpenAction — Define which page is shown when the document is opened
  • HaruDoc::setPageLayout — Set how pages should be displayed
  • HaruDoc::setPageMode — Set how the document should be displayed
  • HaruDoc::setPagesConfiguration — Set the number of pages per set of pages
  • HaruDoc::setPassword — Set owner and user passwords for the document
  • HaruDoc::setPermission — Set permissions for the document
  • HaruDoc::useCNSEncodings — Enable Chinese simplified encodings
  • HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts
  • HaruDoc::useCNTEncodings — Enable Chinese traditional encodings
  • HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts
  • HaruDoc::useJPEncodings — Enable Japanese encodings
  • HaruDoc::useJPFonts — Enable builtin Japanese fonts
  • HaruDoc::useKREncodings — Enable Korean encodings
  • HaruDoc::useKRFonts — Enable builtin Korean fonts
HaruException
HaruDoc::addPage
haru


Add new page to the document

HaruDoc
HaruDoc::addPageLabel
HaruDoc
PHP Manual

HaruDoc::addPage

(PECL haru >= 0.0.1)

HaruDoc::addPage — Add new page to the document

Opis

object HaruDoc::addPage ( void )

Adds a new page to the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a new HaruPage instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::insertPage() - Insert new page just before the specified page

HaruDoc
HaruDoc::addPageLabel
HaruDoc


Set the numbering style for the specified range of pages

HaruDoc::addPage
HaruDoc::__construct
HaruDoc
PHP Manual

HaruDoc::addPageLabel

(PECL haru >= 0.0.1)

HaruDoc::addPageLabel — Set the numbering style for the specified range of pages

Opis

bool HaruDoc::addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] )

Set the numbering style for the specified range of pages.

Parametry

first_page

The first page included into the labeling range.

style

The numbering style. The following values are allowed:

  • HaruPage::NUM_STYLE_DECIMAL - page label is displayed using decimal numerals.
  • HaruPage::NUM_STYLE_UPPER_ROMAN - page label is displayed using uppercase Roman numerals.
  • HaruPage::NUM_STYLE_LOWER_ROMAN - page label is displayed using lowercase Roman numerals.
  • HaruPage::NUM_STYLE_UPPER_LETTER - page label is displayed using uppercase letters (from A to Z).
  • HaruPage::NUM_STYLE_LOWER_LETTERS - page label is displayed using lowercase letters (from a to z).

first_num

The first page number in this range.

prefix

The prefix for the page label.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDoc::addPage
HaruDoc::__construct
HaruDoc


Construct new HaruDoc instance

HaruDoc::addPageLabel
HaruDoc::createOutline
HaruDoc
PHP Manual

HaruDoc::__construct

(PECL haru >= 0.0.1)

HaruDoc::__construct — Construct new HaruDoc instance

Opis

HaruDoc::__construct ( void )

Constructs new HaruDoc instance.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDoc::addPageLabel
HaruDoc::createOutline
HaruDoc


Create a HaruOutline instance

HaruDoc::__construct
HaruDoc::getCurrentEncoder
HaruDoc
PHP Manual

HaruDoc::createOutline

(PECL haru >= 0.0.1)

HaruDoc::createOutline — Create a HaruOutline instance

Opis

object HaruDoc::createOutline ( string $title [, object $parent_outline [, object $encoder ]] )

Create a HaruOutline instance.

Parametry

title

The caption of new outline object.

parent_outline

A valid HaruOutline instance or NULL.

encoder

A valid HaruEncoder instance or NULL.

Zwracane wartości

Returns a new HaruOutline instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDoc::__construct
HaruDoc::getCurrentEncoder
HaruDoc


Get HaruEncoder currently used in the document

HaruDoc::createOutline
HaruDoc::getCurrentPage
HaruDoc
PHP Manual

HaruDoc::getCurrentEncoder

(PECL haru >= 0.0.1)

HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document

Opis

object HaruDoc::getCurrentEncoder ( void )

Get the HaruEncoder currently used in the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns HaruEncoder currently used in the document or FALSE if encoder is not set.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setCurrentEncoder() - Set the current encoder for the document

HaruDoc::createOutline
HaruDoc::getCurrentPage
HaruDoc


Return current page of the document

HaruDoc::getCurrentEncoder
HaruDoc::getEncoder
HaruDoc
PHP Manual

HaruDoc::getCurrentPage

(PECL haru >= 0.0.1)

HaruDoc::getCurrentPage — Return current page of the document

Opis

object HaruDoc::getCurrentPage ( void )

Get current page of the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns HaruPage instance on success or FALSE if there is no current page at the moment.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDoc::getCurrentEncoder
HaruDoc::getEncoder
HaruDoc


Get HaruEncoder instance for the specified encoding

HaruDoc::getCurrentPage
HaruDoc::getFont
HaruDoc
PHP Manual

HaruDoc::getEncoder

(PECL haru >= 0.0.1)

HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding

Opis

object HaruDoc::getEncoder ( string $encoding )

Get the HaruEncoder instance for the specified encoding.

Parametry

encoding

The encoding name. See Builtin Encodings for the list of allowed values.

Zwracane wartości

Returns a HaruEncoder instance for the specified encoding.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setCurrentEncoder() - Set the current encoder for the document
  • HaruDoc::getCurrentEncoder() - Get HaruEncoder currently used in the document

HaruDoc::getCurrentPage
HaruDoc::getFont
HaruDoc


Get HaruFont instance

HaruDoc::getEncoder
HaruDoc::getInfoAttr
HaruDoc
PHP Manual

HaruDoc::getFont

(PECL haru >= 0.0.1)

HaruDoc::getFont — Get HaruFont instance

Opis

object HaruDoc::getFont ( string $fontname [, string $encoding ] )

Get a HaruFont instance.

Parametry

fontname

The name of the font. See Builtin Fonts for the list of builtin fonts. You can also use the name of a font loaded via HaruDoc::loadTTF(), HaruDoc::loadTTC() and HaruDoc::loadType1().

encoding

The encoding to use. See Builtin Encodings for the list of supported encodings.

Zwracane wartości

Returns a HaruFont instance with the specified fontname and encoding.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setFontAndSize() - Set font and fontsize for the page
  • HaruPage::setCurrentFont()

HaruDoc::getEncoder
HaruDoc::getInfoAttr
HaruDoc


Get current value of the specified document attribute

HaruDoc::getFont
HaruDoc::getPageLayout
HaruDoc
PHP Manual

HaruDoc::getInfoAttr

(PECL haru >= 0.0.1)

HaruDoc::getInfoAttr — Get current value of the specified document attribute

Opis

string HaruDoc::getInfoAttr ( int $type )

Get the current value of the specified document attribute.

Parametry

type

The type of the attribute. The following values are available:

  • HaruDoc::INFO_AUTHOR
  • HaruDoc::INFO_CREATOR
  • HaruDoc::INFO_TITLE
  • HaruDoc::INFO_SUBJECT
  • HaruDoc::INFO_KEYWORDS
  • HaruDoc::INFO_CREATION_DATE
  • HaruDoc::INFO_MOD_DATE

Zwracane wartości

Returns the string value of the specified document attribute.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setInfoAttr() - Set the info attribute of the document
  • HaruDoc::setInfoDateAttr() - Set the datetime info attributes of the document

HaruDoc::getFont
HaruDoc::getPageLayout
HaruDoc


Get current page layout

HaruDoc::getInfoAttr
HaruDoc::getPageMode
HaruDoc
PHP Manual

HaruDoc::getPageLayout

(PECL haru >= 0.0.1)

HaruDoc::getPageLayout — Get current page layout

Opis

int HaruDoc::getPageLayout ( void )

Get the current page layout. See HaruDoc::setPageLayout() for the list of possible values.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the page layout currently set in the document or FALSE if page layout was not set. See HaruDoc::setPageLayout() for the list of possible values.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setPageLayout() - Set how pages should be displayed

HaruDoc::getInfoAttr
HaruDoc::getPageMode
HaruDoc


Get current page mode

HaruDoc::getPageLayout
HaruDoc::getStreamSize
HaruDoc
PHP Manual

HaruDoc::getPageMode

(PECL haru >= 0.0.1)

HaruDoc::getPageMode — Get current page mode

Opis

int HaruDoc::getPageMode ( void )

Get the current page mode. See HaruDoc::setPageMode() for the list of possible values.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the page mode currently set in the document. See HaruDoc::setPageMode() for the list of possible values.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setPageMode() - Set how the document should be displayed

HaruDoc::getPageLayout
HaruDoc::getStreamSize
HaruDoc


Get the size of the temporary stream

HaruDoc::getPageMode
HaruDoc::insertPage
HaruDoc
PHP Manual

HaruDoc::getStreamSize

(PECL haru >= 0.0.1)

HaruDoc::getStreamSize — Get the size of the temporary stream

Opis

int HaruDoc::getStreamSize ( void )

Get the size of the temporary stream.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the size of the data in the temporary stream of the document. The size is zero if the document was not saved to the temporary stream.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream

HaruDoc::getPageMode
HaruDoc::insertPage
HaruDoc


Insert new page just before the specified page

HaruDoc::getStreamSize
HaruDoc::loadJPEG
HaruDoc
PHP Manual

HaruDoc::insertPage

(PECL haru >= 0.0.1)

HaruDoc::insertPage — Insert new page just before the specified page

Opis

object HaruDoc::insertPage ( object $page )

Creates a new page and inserts just before the specified page.

Parametry

page

A valid HaruPage instance.

Zwracane wartości

Returns a new HaruPage instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::addPage() - Add new page to the document

HaruDoc::getStreamSize
HaruDoc::loadJPEG
HaruDoc


Load a JPEG image

HaruDoc::insertPage
HaruDoc::loadPNG
HaruDoc
PHP Manual

HaruDoc::loadJPEG

(PECL haru >= 0.0.1)

HaruDoc::loadJPEG — Load a JPEG image

Opis

object HaruDoc::loadJPEG ( string $filename )

Loads the specified JPEG image.

Parametry

filename

A valid JPEG image file.

Zwracane wartości

Returns a new HaruImage instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::loadPNG() - Load PNG image and return HaruImage instance
  • HaruDoc::loadRAW() - Load a RAW image

HaruDoc::insertPage
HaruDoc::loadPNG
HaruDoc


Load PNG image and return HaruImage instance

HaruDoc::loadJPEG
HaruDoc::loadRaw
HaruDoc
PHP Manual

HaruDoc::loadPNG

(PECL haru >= 0.0.1)

HaruDoc::loadPNG — Load PNG image and return HaruImage instance

Opis

object HaruDoc::loadPNG ( string $filename [, bool $deferred = false ] )

Loads a PNG image.

Libharu might be built without libpng support, in this case each call to this function would result in exception.

Parametry

filename

The name of a PNG image file.

deferred

Do not load data immediately. You can set deferred parameter to TRUE for deferred data loading, in this case only size and color are loaded immediately.

Zwracane wartości

Returns a HaruImage instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::loadJPEG() - Load a JPEG image
  • HaruDoc::loadRAW() - Load a RAW image

HaruDoc::loadJPEG
HaruDoc::loadRaw
HaruDoc


Load a RAW image

HaruDoc::loadPNG
HaruDoc::loadTTC
HaruDoc
PHP Manual

HaruDoc::loadRaw

(PECL haru >= 0.0.1)

HaruDoc::loadRaw — Load a RAW image

Opis

object HaruDoc::loadRaw ( string $filename , int $width , int $height , int $color_space )

Loads a RAW image.

Parametry

filename

The name of a RAW image file.

width

The width of the image.

height

The height of the image.

color_space

The color space of the image. Can be one of the following values:

  • HaruDoc::CS_DEVICE_GRAY
  • HaruDoc::CS_DEVICE_RGB
  • HaruDoc::CS_DEVICE_CMYK

Zwracane wartości

Returns a HaruImage instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::loadJPEG() - Load a JPEG image
  • HaruDoc::loadPNG() - Load PNG image and return HaruImage instance

HaruDoc::loadPNG
HaruDoc::loadTTC
HaruDoc


Load the font with the specified index from TTC file

HaruDoc::loadRaw
HaruDoc::loadTTF
HaruDoc
PHP Manual

HaruDoc::loadTTC

(PECL haru >= 0.0.1)

HaruDoc::loadTTC — Load the font with the specified index from TTC file

Opis

string HaruDoc::loadTTC ( string $fontfile , int $index [, bool $embed = false ] )

Loads the TrueType font with the specified index from a TrueType collection file.

Parametry

fontfile

The TrueType collection file.

index

The index of the font in the collection file.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included.

Zwracane wartości

Returns the name of the loaded font on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::loadTTF() - Load TTF font file
  • HaruDoc::loadType1() - Load Type1 font

HaruDoc::loadRaw
HaruDoc::loadTTF
HaruDoc


Load TTF font file

HaruDoc::loadTTC
HaruDoc::loadType1
HaruDoc
PHP Manual

HaruDoc::loadTTF

(PECL haru >= 0.0.1)

HaruDoc::loadTTF — Load TTF font file

Opis

string HaruDoc::loadTTF ( string $fontfile [, bool $embed = false ] )

Loads the given TTF file and (optionally) embed its data into the document.

Parametry

fontfile

The TTF file to load.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included.

Zwracane wartości

Returns the name of the loaded font on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::loadTTC() - Load the font with the specified index from TTC file
  • HaruDoc::loadType1() - Load Type1 font

HaruDoc::loadTTC
HaruDoc::loadType1
HaruDoc


Load Type1 font

HaruDoc::loadTTF
HaruDoc::output
HaruDoc
PHP Manual

HaruDoc::loadType1

(PECL haru >= 0.0.1)

HaruDoc::loadType1 — Load Type1 font

Opis

string HaruDoc::loadType1 ( string $afmfile [, string $pfmfile ] )

Loads Type1 font from the given file and registers it in the PDF document.

Parametry

afmfile

Path to an AFM file.

pfmfile

Path to a PFA/PFB file, optional. If it's not set only the glyph data of the font is embedded into the PDF document.

Zwracane wartości

Returns the name of the loaded font on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::loadTTC() - Load the font with the specified index from TTC file
  • HaruDoc::loadTTF() - Load TTF font file

HaruDoc::loadTTF
HaruDoc::output
HaruDoc


Write the document data to the output buffer

HaruDoc::loadType1
HaruDoc::readFromStream
HaruDoc
PHP Manual

HaruDoc::output

(PECL haru >= 0.0.1)

HaruDoc::output — Write the document data to the output buffer

Opis

bool HaruDoc::output ( void )

Writes the document data into standard output.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::save() - Save the document into the specified file

HaruDoc::loadType1
HaruDoc::readFromStream
HaruDoc


Read data from the temporary stream

HaruDoc::output
HaruDoc::resetError
HaruDoc
PHP Manual

HaruDoc::readFromStream

(PECL haru >= 0.0.1)

HaruDoc::readFromStream — Read data from the temporary stream

Opis

string HaruDoc::readFromStream ( int $bytes )

Read data from the temporary stream.

Parametry

bytes

The bytes parameter specifies how many bytes to read, though the stream may contain less bytes than requested.

Zwracane wartości

Returns data from the temporary stream.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream

HaruDoc::output
HaruDoc::resetError
HaruDoc


Reset error state of the document handle

HaruDoc::readFromStream
HaruDoc::resetStream
HaruDoc
PHP Manual

HaruDoc::resetError

(PECL haru >= 0.0.1)

HaruDoc::resetError — Reset error state of the document handle

Opis

bool HaruDoc::resetError ( void )

Once an error code is set, most of the operations, including I/O processing functions cannot be performed. In case if you want to continue after the cause of the error has been fixed, you have to invoke this function in order to reset the document error state.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Always succeeds and returns TRUE.

HaruDoc::readFromStream
HaruDoc::resetStream
HaruDoc


Rewind the temporary stream

HaruDoc::resetError
HaruDoc::save
HaruDoc
PHP Manual

HaruDoc::resetStream

(PECL haru >= 0.0.1)

HaruDoc::resetStream — Rewind the temporary stream

Opis

bool HaruDoc::resetStream ( void )

Rewinds the temporary stream of the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream

HaruDoc::resetError
HaruDoc::save
HaruDoc


Save the document into the specified file

HaruDoc::resetStream
HaruDoc::saveToStream
HaruDoc
PHP Manual

HaruDoc::save

(PECL haru >= 0.0.1)

HaruDoc::save — Save the document into the specified file

Opis

bool HaruDoc::save ( string $file )

Saves the document into the specified file.

Parametry

file

The file to save the document to.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::output() - Write the document data to the output buffer

HaruDoc::resetStream
HaruDoc::saveToStream
HaruDoc


Save the document into a temporary stream

HaruDoc::save
HaruDoc::setCompressionMode
HaruDoc
PHP Manual

HaruDoc::saveToStream

(PECL haru >= 0.0.1)

HaruDoc::saveToStream — Save the document into a temporary stream

Opis

bool HaruDoc::saveToStream ( void )

Saves the document data into a temporary stream.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream

HaruDoc::save
HaruDoc::setCompressionMode
HaruDoc


Set compression mode for the document

HaruDoc::saveToStream
HaruDoc::setCurrentEncoder
HaruDoc
PHP Manual

HaruDoc::setCompressionMode

(PECL haru >= 0.0.1)

HaruDoc::setCompressionMode — Set compression mode for the document

Opis

bool HaruDoc::setCompressionMode ( int $mode )

Defines compression mode for the document. In case when libharu was compiled without Zlib support this function will always throw HaruException.

Parametry

mode

The compression mode to use. The value is a combination of the following flags:

  • HaruDoc::COMP_NONE - all contents is not compressed.
  • HaruDoc::COMP_TEXT - compress the text data.
  • HaruDoc::COMP_IMAGE - compress the image data.
  • HaruDoc::COMP_METADATA - compress other data (fonts, cmaps).
  • HaruDoc::COMP_ALL - compress all data.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDoc::saveToStream
HaruDoc::setCurrentEncoder
HaruDoc


Set the current encoder for the document

HaruDoc::setCompressionMode
HaruDoc::setEncryptionMode
HaruDoc
PHP Manual

HaruDoc::setCurrentEncoder

(PECL haru >= 0.0.1)

HaruDoc::setCurrentEncoder — Set the current encoder for the document

Opis

bool HaruDoc::setCurrentEncoder ( string $encoding )

Defines the encoder currently used in the document.

Parametry

encoding

The name of the encoding to use. See Builtin Encodings for the list of allowed values.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDoc::setCompressionMode
HaruDoc::setEncryptionMode
HaruDoc


Set encryption mode for the document

HaruDoc::setCurrentEncoder
HaruDoc::setInfoAttr
HaruDoc
PHP Manual

HaruDoc::setEncryptionMode

(PECL haru >= 0.0.1)

HaruDoc::setEncryptionMode — Set encryption mode for the document

Opis

bool HaruDoc::setEncryptionMode ( int $mode [, int $key_len = 5 ] )

Defines encryption mode for the document. The encryption mode cannot be set before setting the password.

Parametry

mode

The encryption mode to use. Can be one of the following:

  • HaruDoc::ENCRYPT_R2 - use "revision2" algorithm.
  • HaruDoc::ENCRYPT_R3 - use "revision3" algorithm. Using this value bumps the version of PDF to 1.4.

key_len

The encryption key length in bytes. This parameter is optional and used only when mode is HaruDoc::ENCRYPT_R3. The default value is 5 (40bit).

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setPassword() - Set owner and user passwords for the document
  • HaruDoc::setPermission() - Set permissions for the document

HaruDoc::setCurrentEncoder
HaruDoc::setInfoAttr
HaruDoc


Set the info attribute of the document

HaruDoc::setEncryptionMode
HaruDoc::setInfoDateAttr
HaruDoc
PHP Manual

HaruDoc::setInfoAttr

(PECL haru >= 0.0.1)

HaruDoc::setInfoAttr — Set the info attribute of the document

Opis

bool HaruDoc::setInfoAttr ( int $type , string $info )

Defines an info attribute. Uses the current encoding of the document.

Parametry

type

The type of the attribute. Can be one of the following:

  • HaruDoc::INFO_AUTHOR
  • HaruDoc::INFO_CREATOR
  • HaruDoc::INFO_TITLE
  • HaruDoc::INFO_SUBJECT
  • HaruDoc::INFO_KEYWORDS

info

The value of the attribute.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setInfoDateAttr() - Set the datetime info attributes of the document

HaruDoc::setEncryptionMode
HaruDoc::setInfoDateAttr
HaruDoc


Set the datetime info attributes of the document

HaruDoc::setInfoAttr
HaruDoc::setOpenAction
HaruDoc
PHP Manual

HaruDoc::setInfoDateAttr

(PECL haru >= 0.0.1)

HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document

Opis

bool HaruDoc::setInfoDateAttr ( int $type , int $year , int $month , int $day , int $hour , int $min , int $sec , string $ind , int $off_hour , int $off_min )

Sets the datetime info attributes of the document.

Parametry

type

The type of the attribute. Can be one of the following:

  • HaruDoc::INFO_CREATION_DATE
  • HaruDoc::INFO_MOD_DATE

year

month

Between 1 and 12.

day

Between 1 and 31, 30, 29 or 28 (different for each month).

hour

Between 0 and 23.

min

Between 0 and 59.

sec

Between 0 and 59.

ind

The timezone relation to UTC, can be "", " ", "+", "-" and "Z".

off_hour

If ind is not " " or "", values between 0 and 23 are valid. Otherwise, this parameter is ignored.

off_min

If ind is not " " or "", values between 0 and 59 are valid. Otherwise, this parameter is ignored.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setInfoAttr() - Set the info attribute of the document

HaruDoc::setInfoAttr
HaruDoc::setOpenAction
HaruDoc


Define which page is shown when the document is opened

HaruDoc::setInfoDateAttr
HaruDoc::setPageLayout
HaruDoc
PHP Manual

HaruDoc::setOpenAction

(PECL haru >= 0.0.1)

HaruDoc::setOpenAction — Define which page is shown when the document is opened

Opis

bool HaruDoc::setOpenAction ( object $destination )

Defines which page should be shown when the document is opened.

Parametry

destination

A valid HaruDestination instance.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDoc::setInfoDateAttr
HaruDoc::setPageLayout
HaruDoc


Set how pages should be displayed

HaruDoc::setOpenAction
HaruDoc::setPageMode
HaruDoc
PHP Manual

HaruDoc::setPageLayout

(PECL haru >= 0.0.1)

HaruDoc::setPageLayout — Set how pages should be displayed

Opis

bool HaruDoc::setPageLayout ( int $layout )

Defines how pages should be displayed.

Parametry

layout

The following values are accepted:

  • HaruDoc::PAGE_LAYOUT_SINGLE - only one page is displayed.
  • HaruDoc::PAGE_LAYOUT_ONE_COLUMN - display the pages in one column.
  • HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT - display pages in two columns, first page left.
  • HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT - display pages in two columns, first page right.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::getPageLayout() - Get current page layout

HaruDoc::setOpenAction
HaruDoc::setPageMode
HaruDoc


Set how the document should be displayed

HaruDoc::setPageLayout
HaruDoc::setPagesConfiguration
HaruDoc
PHP Manual

HaruDoc::setPageMode

(PECL haru >= 0.0.1)

HaruDoc::setPageMode — Set how the document should be displayed

Opis

bool HaruDoc::setPageMode ( int $mode )

Defines how the document should be displayed.

Parametry

mode

The following values are accepted:

  • HaruDoc::PAGE_MODE_USE_NONE - display the document with neither outline nor thumbnail.
  • HaruDoc::PAGE_MODE_USE_OUTLINE - display the document with outline pane.
  • HaruDoc::PAGE_MODE_USE_THUMBS - display the document with thumbnail pane.
  • HaruDoc::PAGE_MODE_FULL_SCREEN - display the document with full screen mode.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::getPageMode() - Get current page mode

HaruDoc::setPageLayout
HaruDoc::setPagesConfiguration
HaruDoc


Set the number of pages per set of pages

HaruDoc::setPageMode
HaruDoc::setPassword
HaruDoc
PHP Manual

HaruDoc::setPagesConfiguration

(PECL haru >= 0.0.1)

HaruDoc::setPagesConfiguration — Set the number of pages per set of pages

Opis

bool HaruDoc::setPagesConfiguration ( int $page_per_pages )

By default the document has one pages object as a root for all pages. All page objects are create as branches of this object. One pages object can contain only 8191, therefore the maximum number of pages per document is 8191. But you can change that fact by setting page_per_pages parameter, so that the root pages object contains 8191 more pages (not page) objects, which in turn contain 8191 pages each. So the maximum number of pages in the document becomes 8191*page_per_pages.

Parametry

page_per_pages

The numbers of pages that a pages object can contain.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDoc::setPageMode
HaruDoc::setPassword
HaruDoc


Set owner and user passwords for the document

HaruDoc::setPagesConfiguration
HaruDoc::setPermission
HaruDoc
PHP Manual

HaruDoc::setPassword

(PECL haru >= 0.0.1)

HaruDoc::setPassword — Set owner and user passwords for the document

Opis

bool HaruDoc::setPassword ( string $owner_password , string $user_password )

Defines owner and user passwords for the document. Setting the passwords makes the document contents encrypted.

Parametry

owner_password

The password of the owner, which can change permissions of the document. Empty password is not accepted. Owner's password cannot be the same as the user's password.

user_password

The password of the user. Can be empty.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setEncryptionMode() - Set encryption mode for the document
  • HaruDoc::setPermission() - Set permissions for the document

HaruDoc::setPagesConfiguration
HaruDoc::setPermission
HaruDoc


Set permissions for the document

HaruDoc::setPassword
HaruDoc::useCNSEncodings
HaruDoc
PHP Manual

HaruDoc::setPermission

(PECL haru >= 0.0.1)

HaruDoc::setPermission — Set permissions for the document

Opis

bool HaruDoc::setPermission ( int $permission )

Defines permissions for the document.

Parametry

permission

The values is a combination of these flags:

  • HaruDoc::ENABLE_READ - user can read the document.
  • HaruDoc::ENABLE_PRINT - user can print the document.
  • HaruDoc::ENABLE_EDIT_ALL - user can edit the contents of the document other than annotations and form fields.
  • HaruDoc::ENABLE_COPY - user can copy the text and the graphics of the document.
  • HaruDoc::ENABLE_EDIT - user can add or modify the annotations and form fields of the document.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::setPassword() - Set owner and user passwords for the document
  • HaruDoc::setEncryptionMode() - Set encryption mode for the document

HaruDoc::setPassword
HaruDoc::useCNSEncodings
HaruDoc


Enable Chinese simplified encodings

HaruDoc::setPermission
HaruDoc::useCNSFonts
HaruDoc
PHP Manual

HaruDoc::useCNSEncodings

(PECL haru >= 0.0.1)

HaruDoc::useCNSEncodings — Enable Chinese simplified encodings

Opis

bool HaruDoc::useCNSEncodings ( void )

Enables Chinese simplified encodings.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::useCNSFonts() - Enable builtin Chinese simplified fonts

HaruDoc::setPermission
HaruDoc::useCNSFonts
HaruDoc


Enable builtin Chinese simplified fonts

HaruDoc::useCNSEncodings
HaruDoc::useCNTEncodings
HaruDoc
PHP Manual

HaruDoc::useCNSFonts

(PECL haru >= 0.0.1)

HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts

Opis

bool HaruDoc::useCNSFonts ( void )

Enables builtin Chinese simplified fonts.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::useCNSEncodings() - Enable Chinese simplified encodings

HaruDoc::useCNSEncodings
HaruDoc::useCNTEncodings
HaruDoc


Enable Chinese traditional encodings

HaruDoc::useCNSFonts
HaruDoc::useCNTFonts
HaruDoc
PHP Manual

HaruDoc::useCNTEncodings

(PECL haru >= 0.0.1)

HaruDoc::useCNTEncodings — Enable Chinese traditional encodings

Opis

bool HaruDoc::useCNTEncodings ( void )

Enables Chinese traditional encodings.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::useCNTFonts() - Enable builtin Chinese traditional fonts

HaruDoc::useCNSFonts
HaruDoc::useCNTFonts
HaruDoc


Enable builtin Chinese traditional fonts

HaruDoc::useCNTEncodings
HaruDoc::useJPEncodings
HaruDoc
PHP Manual

HaruDoc::useCNTFonts

(PECL haru >= 0.0.1)

HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts

Opis

bool HaruDoc::useCNTFonts ( void )

Enables builtin Chinese traditional fonts.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::useCNTEncodings() - Enable Chinese traditional encodings

HaruDoc::useCNTEncodings
HaruDoc::useJPEncodings
HaruDoc


Enable Japanese encodings

HaruDoc::useCNTFonts
HaruDoc::useJPFonts
HaruDoc
PHP Manual

HaruDoc::useJPEncodings

(PECL haru >= 0.0.1)

HaruDoc::useJPEncodings — Enable Japanese encodings

Opis

bool HaruDoc::useJPEncodings ( void )

Enables Japanese encodings.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::useJPFonts() - Enable builtin Japanese fonts

HaruDoc::useCNTFonts
HaruDoc::useJPFonts
HaruDoc


Enable builtin Japanese fonts

HaruDoc::useJPEncodings
HaruDoc::useKREncodings
HaruDoc
PHP Manual

HaruDoc::useJPFonts

(PECL haru >= 0.0.1)

HaruDoc::useJPFonts — Enable builtin Japanese fonts

Opis

bool HaruDoc::useJPFonts ( void )

Enables builtin Japanese fonts.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::useJPEncodings() - Enable Japanese encodings

HaruDoc::useJPEncodings
HaruDoc::useKREncodings
HaruDoc


Enable Korean encodings

HaruDoc::useJPFonts
HaruDoc::useKRFonts
HaruDoc
PHP Manual

HaruDoc::useKREncodings

(PECL haru >= 0.0.1)

HaruDoc::useKREncodings — Enable Korean encodings

Opis

bool HaruDoc::useKREncodings ( void )

Enables Korean encodings.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::useKRFonts() - Enable builtin Korean fonts

HaruDoc::useJPFonts
HaruDoc::useKRFonts
HaruDoc


Enable builtin Korean fonts

HaruDoc::useKREncodings
HaruPage
HaruDoc
PHP Manual

HaruDoc::useKRFonts

(PECL haru >= 0.0.1)

HaruDoc::useKRFonts — Enable builtin Korean fonts

Opis

bool HaruDoc::useKRFonts ( void )

Enables builtin Korean fonts.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::useKREncodings() - Enable Korean encodings

HaruDoc::useKREncodings
HaruPage
HaruDoc


The HaruPage class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Page Class.

Krótki opis klasy

HaruPage {
/* Metody */
bool arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 )
bool beginText ( void )
bool circle ( float $x , float $y , float $ray )
bool closePath ( void )
bool concat ( float $a , float $b , float $c , float $d , float $x , float $y )
object createDestination ( void )
object createLinkAnnotation ( array $rectangle , object $destination )
object createTextAnnotation ( array $rectangle , string $text [, object $encoder ] )
object createURLAnnotation ( array $rectangle , string $url )
bool curveTo2 ( float $x2 , float $y2 , float $x3 , float $y3 )
bool curveTo3 ( float $x1 , float $y1 , float $x3 , float $y3 )
bool curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )
bool drawImage ( object $image , float $x , float $y , float $width , float $height )
bool ellipse ( float $x , float $y , float $xray , float $yray )
bool endPath ( void )
bool endText ( void )
bool eofill ( void )
bool eoFillStroke ([ bool $close_path = false ] )
bool fill ( void )
bool fillStroke ([ bool $close_path = false ] )
float getCharSpace ( void )
array getCMYKFill ( void )
array getCMYKStroke ( void )
object getCurrentFont ( void )
float getCurrentFontSize ( void )
array getCurrentPos ( void )
array getCurrentTextPos ( void )
array getDash ( void )
int getFillingColorSpace ( void )
float getFlatness ( void )
int getGMode ( void )
float getGrayFill ( void )
float getGrayStroke ( void )
float getHeight ( void )
float getHorizontalScaling ( void )
int getLineCap ( void )
int getLineJoin ( void )
float getLineWidth ( void )
float getMiterLimit ( void )
array getRGBFill ( void )
array getRGBStroke ( void )
int getStrokingColorSpace ( void )
float getTextLeading ( void )
array getTextMatrix ( void )
int getTextRenderingMode ( void )
float getTextRise ( void )
float getTextWidth ( string $text )
array getTransMatrix ( void )
float getWidth ( void )
float getWordSpace ( void )
bool lineTo ( float $x , float $y )
int measureText ( string $text , float $width [, bool $wordwrap = false ] )
bool moveTextPos ( float $x , float $y [, bool $set_leading = false ] )
bool moveTo ( float $x , float $y )
bool moveToNextLine ( void )
bool rectangle ( float $x , float $y , float $width , float $height )
bool setCharSpace ( float $char_space )
bool setCMYKFill ( float $c , float $m , float $y , float $k )
bool setCMYKStroke ( float $c , float $m , float $y , float $k )
bool setDash ( array $pattern , int $phase )
bool setFlatness ( float $flatness )
bool setFontAndSize ( object $font , float $size )
bool setGrayFill ( float $value )
bool setGrayStroke ( float $value )
bool setHeight ( float $height )
bool setHorizontalScaling ( float $scaling )
bool setLineCap ( int $cap )
bool setLineJoin ( int $join )
bool setLineWidth ( float $width )
bool setMiterLimit ( float $limit )
bool setRGBFill ( float $r , float $g , float $b )
bool setRGBStroke ( float $r , float $g , float $b )
bool setRotate ( int $angle )
bool setSize ( int $size , int $direction )
bool setSlideShow ( int $type , float $disp_time , float $trans_time )
bool setTextLeading ( float $text_leading )
bool setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
bool setTextRenderingMode ( int $mode )
bool setTextRise ( float $rise )
bool setWidth ( float $width )
bool setWordSpace ( float $word_space )
bool showText ( string $text )
bool showTextNextLine ( string $text [, float $word_space = 0 [, float $char_space = 0 ]] )
bool stroke ([ bool $close_path = false ] )
bool textOut ( float $x , float $y , string $text )
bool textRect ( float $left , float $top , float $right , float $bottom , string $text [, int $align = HaruPage::TALIGN_LEFT ] )
}

Stałe predefiniowane

Type | Name | Description
int | HaruPage::GMODE_PAGE_DESCRIPTION |
int | HaruPage::GMODE_TEXT_OBJECT |
int | HaruPage::GMODE_PATH_OBJECT |
int | HaruPage::GMODE_CLIPPING_PATH |
int | HaruPage::GMODE_SHADING |
int | HaruPage::GMODE_INLINE_IMAGE |
int | HaruPage::GMODE_EXTERNAL_OBJECT |
int | HaruPage::BUTT_END |
int | HaruPage::ROUND_END |
int | HaruPage::PROJECTING_SCUARE_END |
int | HaruPage::MITER_JOIN |
int | HaruPage::ROUND_JOIN |
int | HaruPage::BEVEL_JOIN |
int | HaruPage::FILL |
int | HaruPage::STROKE |
int | HaruPage::FILL_THEN_STROKE |
int | HaruPage::INVISIBLE |
int | HaruPage::FILL_CLIPPING |
int | HaruPage::STROKE_CLIPPING |
int | HaruPage::FILL_STROKE_CLIPPING |
int | HaruPage::CLIPPING |
int | HaruPage::TALIGN_LEFT |
int | HaruPage::TALIGN_RIGHT |
int | HaruPage::TALIGN_CENTER |
int | HaruPage::TALIGN_JUSTIFY |
int | HaruPage::SIZE_LETTER |
int | HaruPage::SIZE_LEGAL |
int | HaruPage::SIZE_A3 |
int | HaruPage::SIZE_A4 |
int | HaruPage::SIZE_A5 |
int | HaruPage::SIZE_B4 |
int | HaruPage::SIZE_B5 |
int | HaruPage::SIZE_EXECUTIVE |
int | HaruPage::SIZE_US4x6 |
int | HaruPage::SIZE_US4x8 |
int | HaruPage::SIZE_US5x7 |
int | HaruPage::SIZE_COMM10 |
int | HaruPage::PORTRAIT |
int | HaruPage::LANDSCAPE |
int | HaruPage::TS_WIPE_LIGHT |
int | HaruPage::TS_WIPE_UP |
int | HaruPage::TS_WIPE_LEFT |
int | HaruPage::TS_WIPE_DOWN |
int | HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT |
int | HaruPage::TS_BARN_DOORS_HORIZONTAL_IN |
int | HaruPage::TS_BARN_DOORS_VERTICAL_OUT |
int | HaruPage::TS_BARN_DOORS_VERTICAL_IN |
int | HaruPage::TS_BOX_OUT |
int | HaruPage::TS_BOX_IN |
int | HaruPage::TS_BLINDS_HORIZONTAL |
int | HaruPage::TS_BLINDS_VERTICAL |
int | HaruPage::TS_DISSOLVE |
int | HaruPage::TS_GLITTER_RIGHT |
int | HaruPage::TS_GLITTER_DOWN |
int | HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT |
int | HaruPage::TS_REPLACE |
int | HaruPage::NUM_STYLE_DECIMAL |
int | HaruPage::NUM_STYLE_UPPER_ROMAN |
int | HaruPage::NUM_STYLE_LOWER_ROMAN |
int | HaruPage::NUM_STYLE_UPPER_LETTERS |
int | HaruPage::NUM_STYLE_LOWER_LETTERS |

Spis treści

  • HaruPage::arc — Append an arc to the current path
  • HaruPage::beginText — Begin a text object and set the current text position to (0,0)
  • HaruPage::circle — Append a circle to the current path
  • HaruPage::closePath — Append a straight line from the current point to the start point of the path
  • HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix
  • HaruPage::createDestination — Create new HaruDestination instance
  • HaruPage::createLinkAnnotation — Create new HaruAnnotation instance
  • HaruPage::createTextAnnotation — Create new HaruAnnotation instance
  • HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance
  • HaruPage::curveTo2 — Append a Bezier curve to the current path
  • HaruPage::curveTo3 — Append a Bezier curve to the current path
  • HaruPage::curveTo — Append a Bezier curve to the current path
  • HaruPage::drawImage — Show image at the page
  • HaruPage::ellipse — Append an ellipse to the current path
  • HaruPage::endPath — End current path object without filling and painting operations
  • HaruPage::endText — End current text object
  • HaruPage::eofill — Fill current path using even-odd rule
  • HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path
  • HaruPage::fill — Fill current path using nonzero winding number rule
  • HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path
  • HaruPage::getCharSpace — Get the current value of character spacing
  • HaruPage::getCMYKFill — Get the current filling color
  • HaruPage::getCMYKStroke — Get the current stroking color
  • HaruPage::getCurrentFont — Get the currently used font
  • HaruPage::getCurrentFontSize — Get the current font size
  • HaruPage::getCurrentPos — Get the current position for path painting
  • HaruPage::getCurrentTextPos — Get the current position for text printing
  • HaruPage::getDash — Get the current dash pattern
  • HaruPage::getFillingColorSpace — Get the current filling color space
  • HaruPage::getFlatness — Get the flatness of the page
  • HaruPage::getGMode — Get the current graphics mode
  • HaruPage::getGrayFill — Get the current filling color
  • HaruPage::getGrayStroke — Get the current stroking color
  • HaruPage::getHeight — Get the height of the page
  • HaruPage::getHorizontalScaling — Get the current value of horizontal scaling
  • HaruPage::getLineCap — Get the current line cap style
  • HaruPage::getLineJoin — Get the current line join style
  • HaruPage::getLineWidth — Get the current line width
  • HaruPage::getMiterLimit — Get the value of miter limit
  • HaruPage::getRGBFill — Get the current filling color
  • HaruPage::getRGBStroke — Get the current stroking color
  • HaruPage::getStrokingColorSpace — Get the current stroking color space
  • HaruPage::getTextLeading — Get the current value of line spacing
  • HaruPage::getTextMatrix — Get the current text transformation matrix of the page
  • HaruPage::getTextRenderingMode — Get the current text rendering mode
  • HaruPage::getTextRise — Get the current value of text rising
  • HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing
  • HaruPage::getTransMatrix — Get the current transformation matrix of the page
  • HaruPage::getWidth — Get the width of the page
  • HaruPage::getWordSpace — Get the current value of word spacing
  • HaruPage::lineTo — Draw a line from the current point to the specified point
  • HaruPage::measureText — Calculate the number of characters which can be included within the specified width
  • HaruPage::moveTextPos — Move text position to the specified offset
  • HaruPage::moveTo — Set starting point for new drawing path
  • HaruPage::moveToNextLine — Move text position to the start of the next line
  • HaruPage::rectangle — Append a rectangle to the current path
  • HaruPage::setCharSpace — Set character spacing for the page
  • HaruPage::setCMYKFill — Set filling color for the page
  • HaruPage::setCMYKStroke — Set stroking color for the page
  • HaruPage::setDash — Set the dash pattern for the page
  • HaruPage::setFlatness — Set flatness for the page
  • HaruPage::setFontAndSize — Set font and fontsize for the page
  • HaruPage::setGrayFill — Set filling color for the page
  • HaruPage::setGrayStroke — Sets stroking color for the page
  • HaruPage::setHeight — Set height of the page
  • HaruPage::setHorizontalScaling — Set horizontal scaling for the page
  • HaruPage::setLineCap — Set the shape to be used at the ends of lines
  • HaruPage::setLineJoin — Set line join style for the page
  • HaruPage::setLineWidth — Set line width for the page
  • HaruPage::setMiterLimit — Set the current value of the miter limit of the page
  • HaruPage::setRGBFill — Set filling color for the page
  • HaruPage::setRGBStroke — Set stroking color for the page
  • HaruPage::setRotate — Set rotation angle of the page
  • HaruPage::setSize — Set size and direction of the page
  • HaruPage::setSlideShow — Set transition style for the page
  • HaruPage::setTextLeading — Set text leading (line spacing) for the page
  • HaruPage::setTextMatrix — Set the current text transformation matrix of the page
  • HaruPage::setTextRenderingMode — Set text rendering mode for the page
  • HaruPage::setTextRise — Set the current value of text rising
  • HaruPage::setWidth — Set width of the page
  • HaruPage::setWordSpace — Set word spacing for the page
  • HaruPage::showText — Print text at the current position of the page
  • HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text
  • HaruPage::stroke — Paint current path
  • HaruPage::textOut — Print the text on the specified position
  • HaruPage::textRect — Print the text inside the specified region
HaruDoc::useKRFonts
HaruPage::arc
haru


Append an arc to the current path

HaruPage
HaruPage::beginText
HaruPage
PHP Manual

HaruPage::arc

(PECL haru >= 0.0.1)

HaruPage::arc — Append an arc to the current path

Opis

bool HaruPage::arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 )

Appends an arc to the current path.

Parametry

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

ray

The ray of the arc.

ang1

The angle of the beginning.

ang2

The angle of the end. Must be greater than ang1.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage
HaruPage::beginText
HaruPage


Begin a text object and set the current text position to (0,0)

HaruPage::arc
HaruPage::circle
HaruPage
PHP Manual

HaruPage::beginText

(PECL haru >= 0.0.1)

HaruPage::beginText — Begin a text object and set the current text position to (0,0)

Opis

bool HaruPage::beginText ( void )

Begins new text object and sets the current text position to (0,0).

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::arc
HaruPage::circle
HaruPage


Append a circle to the current path

HaruPage::beginText
HaruPage::closePath
HaruPage
PHP Manual

HaruPage::circle

(PECL haru >= 0.0.1)

HaruPage::circle — Append a circle to the current path

Opis

bool HaruPage::circle ( float $x , float $y , float $ray )

Appends a circle to the current path.

Parametry

x

Horizontal coordinate of the center point.

y

Vertical coordinate of the center point.

ray

The ray of the circle.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::beginText
HaruPage::closePath
HaruPage


Append a straight line from the current point to the start point of the path

HaruPage::circle
HaruPage::concat
HaruPage
PHP Manual

HaruPage::closePath

(PECL haru >= 0.0.1)

HaruPage::closePath — Append a straight line from the current point to the start point of the path

Opis

bool HaruPage::closePath ( void )

Appends a straight line from the current point to the start point of the path.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::circle
HaruPage::concat
HaruPage


Concatenate current transformation matrix of the page and the specified matrix

HaruPage::closePath
HaruPage::createDestination
HaruPage
PHP Manual

HaruPage::concat

(PECL haru >= 0.0.1)

HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix

Opis

bool HaruPage::concat ( float $a , float $b , float $c , float $d , float $x , float $y )

Concatenates current transformation matrix of the page and the specified matrix.

Parametry

a

b

c

d

x

y

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::closePath
HaruPage::createDestination
HaruPage


Create new HaruDestination instance

HaruPage::concat
HaruPage::createLinkAnnotation
HaruPage
PHP Manual

HaruPage::createDestination

(PECL haru >= 0.0.1)

HaruPage::createDestination — Create new HaruDestination instance

Opis

object HaruPage::createDestination ( void )

Create a new HaruDestination instance.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a new HaruDestination instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::concat
HaruPage::createLinkAnnotation
HaruPage


Create new HaruAnnotation instance

HaruPage::createDestination
HaruPage::createTextAnnotation
HaruPage
PHP Manual

HaruPage::createLinkAnnotation

(PECL haru >= 0.0.1)

HaruPage::createLinkAnnotation — Create new HaruAnnotation instance

Opis

object HaruPage::createLinkAnnotation ( array $rectangle , object $destination )

Creates a new HaruAnnotation instance.

Parametry

rectangle

An array with 4 coordinates of the clickable area.

destination

Valid HaruDestination instance.

Zwracane wartości

Returns a new HaruAnnotation instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::createDestination
HaruPage::createTextAnnotation
HaruPage


Create new HaruAnnotation instance

HaruPage::createLinkAnnotation
HaruPage::createURLAnnotation
HaruPage
PHP Manual

HaruPage::createTextAnnotation

(PECL haru >= 0.0.1)

HaruPage::createTextAnnotation — Create new HaruAnnotation instance

Opis

object HaruPage::createTextAnnotation ( array $rectangle , string $text [, object $encoder ] )

Creates a new HaruAnnotation instance.

Parametry

rectangle

An array with 4 coordinates of the annotation area.

text

The text to be displayed.

encoder

Optional HaruEncoder instance.

Zwracane wartości

Returns a new HaruAnnotation instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::createLinkAnnotation
HaruPage::createURLAnnotation
HaruPage


Create and return new HaruAnnotation instance

HaruPage::createTextAnnotation
HaruPage::curveTo2
HaruPage
PHP Manual

HaruPage::createURLAnnotation

(PECL haru >= 0.0.1)

HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance

Opis

object HaruPage::createURLAnnotation ( array $rectangle , string $url )

Creates a new HaruAnnotation instance.

Parametry

rectangle

An array with 4 coordinates of the clickable area.

url

The URL to open.

Zwracane wartości

Returns a new HaruAnnotation instance.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::createTextAnnotation
HaruPage::curveTo2
HaruPage


Append a Bezier curve to the current path

HaruPage::createURLAnnotation
HaruPage::curveTo3
HaruPage
PHP Manual

HaruPage::curveTo2

(PECL haru >= 0.0.1)

HaruPage::curveTo2 — Append a Bezier curve to the current path

Opis

bool HaruPage::curveTo2 ( float $x2 , float $y2 , float $x3 , float $y3 )

Appends a Bezier curve to the current path. The current point and the point (x2, y2) are used as the control points for the Bezier curve and current point is moved to the point (x3, y3).

Parametry

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::createURLAnnotation
HaruPage::curveTo3
HaruPage


Append a Bezier curve to the current path

HaruPage::curveTo2
HaruPage::curveTo
HaruPage
PHP Manual

HaruPage::curveTo3

(PECL haru >= 0.0.1)

HaruPage::curveTo3 — Append a Bezier curve to the current path

Opis

bool HaruPage::curveTo3 ( float $x1 , float $y1 , float $x3 , float $y3 )

Appends a Bezier curve to the current path. The point (x1, y1) and the point (x3, y3) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Parametry

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::curveTo2
HaruPage::curveTo
HaruPage


Append a Bezier curve to the current path

HaruPage::curveTo3
HaruPage::drawImage
HaruPage
PHP Manual

HaruPage::curveTo

(PECL haru >= 0.0.1)

HaruPage::curveTo — Append a Bezier curve to the current path

Opis

bool HaruPage::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Append a Bezier curve to the current path. The point (x1, y1) and the point (x2, y2) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Parametry

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::curveTo3
HaruPage::drawImage
HaruPage


Show image at the page

HaruPage::curveTo
HaruPage::ellipse
HaruPage
PHP Manual

HaruPage::drawImage

(PECL haru >= 0.0.1)

HaruPage::drawImage — Show image at the page

Opis

bool HaruPage::drawImage ( object $image , float $x , float $y , float $width , float $height )

Show image at the page.

Parametry

image

Valid HaruImage instance.

x

The left border of the area where the image is displayed.

y

The lower border of the area where the image is displayed.

width

The width of the image area.

height

The height of the image area.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::curveTo
HaruPage::ellipse
HaruPage


Append an ellipse to the current path

HaruPage::drawImage
HaruPage::endPath
HaruPage
PHP Manual

HaruPage::ellipse

(PECL haru >= 0.0.1)

HaruPage::ellipse — Append an ellipse to the current path

Opis

bool HaruPage::ellipse ( float $x , float $y , float $xray , float $yray )

Appends an ellipse to the current path.

Parametry

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

xray

The ray of the ellipse in the x direction.

yray

The ray of the ellipse in the y direction.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::drawImage
HaruPage::endPath
HaruPage


End current path object without filling and painting operations

HaruPage::ellipse
HaruPage::endText
HaruPage
PHP Manual

HaruPage::endPath

(PECL haru >= 0.0.1)

HaruPage::endPath — End current path object without filling and painting operations

Opis

bool HaruPage::endPath ( void )

Ends current path object without performing filling and painting operations.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::ellipse
HaruPage::endText
HaruPage


End current text object

HaruPage::endPath
HaruPage::eofill
HaruPage
PHP Manual

HaruPage::endText

(PECL haru >= 0.0.1)

HaruPage::endText — End current text object

Opis

bool HaruPage::endText ( void )

Finalizes current text object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::endPath
HaruPage::eofill
HaruPage


Fill current path using even-odd rule

HaruPage::endText
HaruPage::eoFillStroke
HaruPage
PHP Manual

HaruPage::eofill

(PECL haru >= 0.0.1)

HaruPage::eofill — Fill current path using even-odd rule

Opis

bool HaruPage::eofill ( void )

Fills current path using even-odd rule.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::endText
HaruPage::eoFillStroke
HaruPage


Fill current path using even-odd rule, then paint the path

HaruPage::eofill
HaruPage::fill
HaruPage
PHP Manual

HaruPage::eoFillStroke

(PECL haru >= 0.0.1)

HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path

Opis

bool HaruPage::eoFillStroke ([ bool $close_path = false ] )

Fills current path using even-odd rule, then paints the path.

Parametry

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::eofill
HaruPage::fill
HaruPage


Fill current path using nonzero winding number rule

HaruPage::eoFillStroke
HaruPage::fillStroke
HaruPage
PHP Manual

HaruPage::fill

(PECL haru >= 0.0.1)

HaruPage::fill — Fill current path using nonzero winding number rule

Opis

bool HaruPage::fill ( void )

Fills current path using nonzero winding number rule.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::eoFillStroke
HaruPage::fillStroke
HaruPage


Fill current path using nonzero winding number rule, then paint the path

HaruPage::fill
HaruPage::getCharSpace
HaruPage
PHP Manual

HaruPage::fillStroke

(PECL haru >= 0.0.1)

HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path

Opis

bool HaruPage::fillStroke ([ bool $close_path = false ] )

Fills current path using nonzero winding number rule, then paints the path.

Parametry

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::fill
HaruPage::getCharSpace
HaruPage


Get the current value of character spacing

HaruPage::fillStroke
HaruPage::getCMYKFill
HaruPage
PHP Manual

HaruPage::getCharSpace

(PECL haru >= 0.0.1)

HaruPage::getCharSpace — Get the current value of character spacing

Opis

float HaruPage::getCharSpace ( void )

Get the current value of character spacing.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current value of character spacing.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::fillStroke
HaruPage::getCMYKFill
HaruPage


Get the current filling color

HaruPage::getCharSpace
HaruPage::getCMYKStroke
HaruPage
PHP Manual

HaruPage::getCMYKFill

(PECL haru >= 0.0.1)

HaruPage::getCMYKFill — Get the current filling color

Opis

array HaruPage::getCMYKFill ( void )

Returns the current filling color.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current filling color as an array with 4 elements ("c", "m", "y" and "k").

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::getCharSpace
HaruPage::getCMYKStroke
HaruPage


Get the current stroking color

HaruPage::getCMYKFill
HaruPage::getCurrentFont
HaruPage
PHP Manual

HaruPage::getCMYKStroke

(PECL haru >= 0.0.1)

HaruPage::getCMYKStroke — Get the current stroking color

Opis

array HaruPage::getCMYKStroke ( void )

Get the current stroking color.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current stroking color as an array with 4 elements ("c", "m", "y" and "k").

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::getCMYKFill
HaruPage::getCurrentFont
HaruPage


Get the currently used font

HaruPage::getCMYKStroke
HaruPage::getCurrentFontSize
HaruPage
PHP Manual

HaruPage::getCurrentFont

(PECL haru >= 0.0.1)

HaruPage::getCurrentFont — Get the currently used font

Opis

object HaruPage::getCurrentFont ( void )

Get the currently used font.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the currently used font as an instance of HaruFont.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::getCMYKStroke
HaruPage::getCurrentFontSize
HaruPage


Get the current font size

HaruPage::getCurrentFont
HaruPage::getCurrentPos
HaruPage
PHP Manual

HaruPage::getCurrentFontSize

(PECL haru >= 0.0.1)

HaruPage::getCurrentFontSize — Get the current font size

Opis

float HaruPage::getCurrentFontSize ( void )

Get the current font size.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current font size.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::getCurrentFont
HaruPage::getCurrentPos
HaruPage


Get the current position for path painting

HaruPage::getCurrentFontSize
HaruPage::getCurrentTextPos
HaruPage
PHP Manual

HaruPage::getCurrentPos

(PECL haru >= 0.0.1)

HaruPage::getCurrentPos — Get the current position for path painting

Opis

array HaruPage::getCurrentPos ( void )

Get the current position for path painting.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current position for path painting as an array of with two elements - "x" and "y".

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::getCurrentFontSize
HaruPage::getCurrentTextPos
HaruPage


Get the current position for text printing

HaruPage::getCurrentPos
HaruPage::getDash
HaruPage
PHP Manual

HaruPage::getCurrentTextPos

(PECL haru >= 0.0.1)

HaruPage::getCurrentTextPos — Get the current position for text printing

Opis

array HaruPage::getCurrentTextPos ( void )

Get the current position for text printing.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current position for text printing as an array with 2 elements - "x" and "y".

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::getCurrentPos
HaruPage::getDash
HaruPage


Get the current dash pattern

HaruPage::getCurrentTextPos
HaruPage::getFillingColorSpace
HaruPage
PHP Manual

HaruPage::getDash

(PECL haru >= 0.0.1)

HaruPage::getDash — Get the current dash pattern

Opis

array HaruPage::getDash ( void )

Get the current dash pattern. See HaruPage::setDash() for more information on dash patterns.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current dash pattern as an array of two elements - "pattern" and "phase" or FALSE if dash pattern was not set.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setDash() - Set the dash pattern for the page

HaruPage::getCurrentTextPos
HaruPage::getFillingColorSpace
HaruPage


Get the current filling color space

HaruPage::getDash
HaruPage::getFlatness
HaruPage
PHP Manual

HaruPage::getFillingColorSpace

(PECL haru >= 0.0.1)

HaruPage::getFillingColorSpace — Get the current filling color space

Opis

int HaruPage::getFillingColorSpace ( void )

Get the current filling color space.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current filling color space. The result value is one of the following:

  • HaruDoc::CS_DEVICE_GRAY
  • HaruDoc::CS_DEVICE_RGB
  • HaruDoc::CS_DEVICE_CMYK
  • HaruDoc::CS_CAL_GRAY
  • HaruDoc::CS_CAL_RGB
  • HaruDoc::CS_LAB
  • HaruDoc::CS_ICC_BASED
  • HaruDoc::CS_SEPARATION
  • HaruDoc::CS_DEVICE_N
  • HaruDoc::CS_INDEXED
  • HaruDoc::CS_PATTERN

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::getDash
HaruPage::getFlatness
HaruPage


Get the flatness of the page

HaruPage::getFillingColorSpace
HaruPage::getGMode
HaruPage
PHP Manual

HaruPage::getFlatness

(PECL haru >= 0.0.1)

HaruPage::getFlatness — Get the flatness of the page

Opis

float HaruPage::getFlatness ( void )

Get the flatness of the page.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the flatness of the page.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setFlatness() - Set flatness for the page

HaruPage::getFillingColorSpace
HaruPage::getGMode
HaruPage


Get the current graphics mode

HaruPage::getFlatness
HaruPage::getGrayFill
HaruPage
PHP Manual

HaruPage::getGMode

(PECL haru >= 0.0.1)

HaruPage::getGMode — Get the current graphics mode

Opis

int HaruPage::getGMode ( void )

Get the current graphics mode.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current graphics mode. The result value is one of the following:

  • HaruPage::GMODE_PAGE_DESCRIPTION
  • HaruPage::GMODE_TEXT_OBJECT
  • HaruPage::GMODE_PATH_OBJECT
  • HaruPage::GMODE_CLIPPING_PATH
  • HaruPage::GMODE_SHADING
  • HaruPage::GMODE_INLINE_IMAGE
  • HaruPage::GMODE_EXTERNAL_OBJECT

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::getFlatness
HaruPage::getGrayFill
HaruPage


Get the current filling color

HaruPage::getGMode
HaruPage::getGrayStroke
HaruPage
PHP Manual

HaruPage::getGrayFill

(PECL haru >= 0.0.1)

HaruPage::getGrayFill — Get the current filling color

Opis

float HaruPage::getGrayFill ( void )

Get the current filling color.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current filling color.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setGrayFill() - Set filling color for the page

HaruPage::getGMode
HaruPage::getGrayStroke
HaruPage


Get the current stroking color

HaruPage::getGrayFill
HaruPage::getHeight
HaruPage
PHP Manual

HaruPage::getGrayStroke

(PECL haru >= 0.0.1)

HaruPage::getGrayStroke — Get the current stroking color

Opis

float HaruPage::getGrayStroke ( void )

Get the current stroking color.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current stroking color.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setGrayStroke() - Sets stroking color for the page

HaruPage::getGrayFill
HaruPage::getHeight
HaruPage


Get the height of the page

HaruPage::getGrayStroke
HaruPage::getHorizontalScaling
HaruPage
PHP Manual

HaruPage::getHeight

(PECL haru >= 0.0.1)

HaruPage::getHeight — Get the height of the page

Opis

float HaruPage::getHeight ( void )

Get the height of the page.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the height of the page.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setHeight() - Set height of the page

HaruPage::getGrayStroke
HaruPage::getHorizontalScaling
HaruPage


Get the current value of horizontal scaling

HaruPage::getHeight
HaruPage::getLineCap
HaruPage
PHP Manual

HaruPage::getHorizontalScaling

(PECL haru >= 0.0.1)

HaruPage::getHorizontalScaling — Get the current value of horizontal scaling

Opis

float HaruPage::getHorizontalScaling ( void )

Get the current value of the horizontal scaling.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current value of horizontal scaling.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setHorizontalScaling() - Set horizontal scaling for the page

HaruPage::getHeight
HaruPage::getLineCap
HaruPage


Get the current line cap style

HaruPage::getHorizontalScaling
HaruPage::getLineJoin
HaruPage
PHP Manual

HaruPage::getLineCap

(PECL haru >= 0.0.1)

HaruPage::getLineCap — Get the current line cap style

Opis

int HaruPage::getLineCap ( void )

Get the current line cap style.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current line cap style. The result value is one of the following:

  • HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
  • HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
  • HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setLineCap() - Set the shape to be used at the ends of lines

HaruPage::getHorizontalScaling
HaruPage::getLineJoin
HaruPage


Get the current line join style

HaruPage::getLineCap
HaruPage::getLineWidth
HaruPage
PHP Manual

HaruPage::getLineJoin

(PECL haru >= 0.0.1)

HaruPage::getLineJoin — Get the current line join style

Opis

int HaruPage::getLineJoin ( void )

Get the current line join style.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current line join style. The result value is one of the following:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setLineJoin() - Set line join style for the page

HaruPage::getLineCap
HaruPage::getLineWidth
HaruPage


Get the current line width

HaruPage::getLineJoin
HaruPage::getMiterLimit
HaruPage
PHP Manual

HaruPage::getLineWidth

(PECL haru >= 0.0.1)

HaruPage::getLineWidth — Get the current line width

Opis

float HaruPage::getLineWidth ( void )

Get the current line width.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current line width.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setLineWidth() - Set line width for the page

HaruPage::getLineJoin
HaruPage::getMiterLimit
HaruPage


Get the value of miter limit

HaruPage::getLineWidth
HaruPage::getRGBFill
HaruPage
PHP Manual

HaruPage::getMiterLimit

(PECL haru >= 0.0.1)

HaruPage::getMiterLimit — Get the value of miter limit

Opis

float HaruPage::getMiterLimit ( void )

Get the value of the miter limit.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the value of the miter limit.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setMiterLimit() - Set the current value of the miter limit of the page

HaruPage::getLineWidth
HaruPage::getRGBFill
HaruPage


Get the current filling color

HaruPage::getMiterLimit
HaruPage::getRGBStroke
HaruPage
PHP Manual

HaruPage::getRGBFill

(PECL haru >= 0.0.1)

HaruPage::getRGBFill — Get the current filling color

Opis

array HaruPage::getRGBFill ( void )

Get the current filling color.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current filling color as an array with 3 elements: "r", "g" and "b".

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setRGBFill() - Set filling color for the page

HaruPage::getMiterLimit
HaruPage::getRGBStroke
HaruPage


Get the current stroking color

HaruPage::getRGBFill
HaruPage::getStrokingColorSpace
HaruPage
PHP Manual

HaruPage::getRGBStroke

(PECL haru >= 0.0.1)

HaruPage::getRGBStroke — Get the current stroking color

Opis

array HaruPage::getRGBStroke ( void )

Get the current stroking color.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current stroking color.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setRGBStroke() - Set stroking color for the page

HaruPage::getRGBFill
HaruPage::getStrokingColorSpace
HaruPage


Get the current stroking color space

HaruPage::getRGBStroke
HaruPage::getTextLeading
HaruPage
PHP Manual

HaruPage::getStrokingColorSpace

(PECL haru >= 0.0.1)

HaruPage::getStrokingColorSpace — Get the current stroking color space

Opis

int HaruPage::getStrokingColorSpace ( void )

Get the current stroking color space.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current stroking color space. The list of return values is the same as for HaruPage::getFillingColorSpace()

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getFillingColorSpace() - Get the current filling color space

HaruPage::getRGBStroke
HaruPage::getTextLeading
HaruPage


Get the current value of line spacing

HaruPage::getStrokingColorSpace
HaruPage::getTextMatrix
HaruPage
PHP Manual

HaruPage::getTextLeading

(PECL haru >= 0.0.1)

HaruPage::getTextLeading — Get the current value of line spacing

Opis

float HaruPage::getTextLeading ( void )

Get the current value of line spacing.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current value of line spacing.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setTextLeading() - Set text leading (line spacing) for the page

HaruPage::getStrokingColorSpace
HaruPage::getTextMatrix
HaruPage


Get the current text transformation matrix of the page

HaruPage::getTextLeading
HaruPage::getTextRenderingMode
HaruPage
PHP Manual

HaruPage::getTextMatrix

(PECL haru >= 0.0.1)

HaruPage::getTextMatrix — Get the current text transformation matrix of the page

Opis

array HaruPage::getTextMatrix ( void )

Get the current text transformation matrix of the page.

Zwracane wartości

Returns the current text transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setTextMatrix() - Set the current text transformation matrix of the page

HaruPage::getTextLeading
HaruPage::getTextRenderingMode
HaruPage


Get the current text rendering mode

HaruPage::getTextMatrix
HaruPage::getTextRise
HaruPage
PHP Manual

HaruPage::getTextRenderingMode

(PECL haru >= 0.0.1)

HaruPage::getTextRenderingMode — Get the current text rendering mode

Opis

int HaruPage::getTextRenderingMode ( void )

Get the current text rendering mode.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current text rendering mode. The result value is one of the following:

  • HaruPage::FILL
  • HaruPage::STROKE
  • HaruPage::FILL_THEN_STROKE
  • HaruPage::INVISIBLE
  • HaruPage::FILL_CLIPPING
  • HaruPage::STROKE_CLIPPING
  • HaruPage::FILL_STROKE_CLIPPING
  • HaruPage::CLIPPING

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setTextRenderingMode() - Set text rendering mode for the page

HaruPage::getTextMatrix
HaruPage::getTextRise
HaruPage


Get the current value of text rising

HaruPage::getTextRenderingMode
HaruPage::getTextWidth
HaruPage
PHP Manual

HaruPage::getTextRise

(PECL haru >= 0.0.1)

HaruPage::getTextRise — Get the current value of text rising

Opis

float HaruPage::getTextRise ( void )

Get the current value of text rising.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current value of text rising.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setTextRise() - Set the current value of text rising

HaruPage::getTextRenderingMode
HaruPage::getTextWidth
HaruPage


Get the width of the text using current fontsize, character spacing and word spacing

HaruPage::getTextRise
HaruPage::getTransMatrix
HaruPage
PHP Manual

HaruPage::getTextWidth

(PECL haru >= 0.0.1)

HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing

Opis

float HaruPage::getTextWidth ( string $text )

Get the width of the text using current fontsize, character spacing and word spacing

Parametry

text

The text to measure.

Zwracane wartości

Returns the width of the text using current fontsize, character spacing and word spacing.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::measureText() - Calculate the number of characters which can be included within the specified width

HaruPage::getTextRise
HaruPage::getTransMatrix
HaruPage


Get the current transformation matrix of the page

HaruPage::getTextWidth
HaruPage::getWidth
HaruPage
PHP Manual

HaruPage::getTransMatrix

(PECL haru >= 0.0.1)

HaruPage::getTransMatrix — Get the current transformation matrix of the page

Opis

array HaruPage::getTransMatrix ( void )

Get the current transformation matrix of the page.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::concat() - Concatenate current transformation matrix of the page and the specified matrix

HaruPage::getTextWidth
HaruPage::getWidth
HaruPage


Get the width of the page

HaruPage::getTransMatrix
HaruPage::getWordSpace
HaruPage
PHP Manual

HaruPage::getWidth

(PECL haru >= 0.0.1)

HaruPage::getWidth — Get the width of the page

Opis

float HaruPage::getWidth ( void )

Get the width of the page.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the width of the page.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setWidth() - Set width of the page

HaruPage::getTransMatrix
HaruPage::getWordSpace
HaruPage


Get the current value of word spacing

HaruPage::getWidth
HaruPage::lineTo
HaruPage
PHP Manual

HaruPage::getWordSpace

(PECL haru >= 0.0.1)

HaruPage::getWordSpace — Get the current value of word spacing

Opis

float HaruPage::getWordSpace ( void )

Get the current value of word spacing.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current value of word spacing.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setWordSpace() - Set word spacing for the page

HaruPage::getWidth
HaruPage::lineTo
HaruPage


Draw a line from the current point to the specified point

HaruPage::getWordSpace
HaruPage::measureText
HaruPage
PHP Manual

HaruPage::lineTo

(PECL haru >= 0.0.1)

HaruPage::lineTo — Draw a line from the current point to the specified point

Opis

bool HaruPage::lineTo ( float $x , float $y )

Draws a line from the current point to the specified point.

Parametry

x

y

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::curveTo() - Append a Bezier curve to the current path
  • HaruPage::curveTo2() - Append a Bezier curve to the current path
  • HaruPage::curveTo3() - Append a Bezier curve to the current path

HaruPage::getWordSpace
HaruPage::measureText
HaruPage


Calculate the number of characters which can be included within the specified width

HaruPage::lineTo
HaruPage::moveTextPos
HaruPage
PHP Manual

HaruPage::measureText

(PECL haru >= 0.0.1)

HaruPage::measureText — Calculate the number of characters which can be included within the specified width

Opis

int HaruPage::measureText ( string $text , float $width [, bool $wordwrap = false ] )

Get the number of characters which can be included within the specified width.

Parametry

text

The text to measure.

width

The width of the area to put the text to.

wordwrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area.

Zwracane wartości

Returns the number of characters which can be included within the specified width.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruFont::measureText() - Calculate the number of characters which can be included within the specified width

HaruPage::lineTo
HaruPage::moveTextPos
HaruPage


Move text position to the specified offset

HaruPage::measureText
HaruPage::moveTo
HaruPage
PHP Manual

HaruPage::moveTextPos

(PECL haru >= 0.0.1)

HaruPage::moveTextPos — Move text position to the specified offset

Opis

bool HaruPage::moveTextPos ( float $x , float $y [, bool $set_leading = false ] )

Moves text position to the specified offset. If the start position of the current line is (x1, y1), the start of the next line is (x1 + x, y1 + y).

Parametry

x

The specified text position offset.

y

The specified text position offset.

set_leading

If set to TRUE, the function sets the text leading to -y.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::moveToNextLine() - Move text position to the start of the next line

HaruPage::measureText
HaruPage::moveTo
HaruPage


Set starting point for new drawing path

HaruPage::moveTextPos
HaruPage::moveToNextLine
HaruPage
PHP Manual

HaruPage::moveTo

(PECL haru >= 0.0.1)

HaruPage::moveTo — Set starting point for new drawing path

Opis

bool HaruPage::moveTo ( float $x , float $y )

Defines starting point for new drawing path.

Parametry

x

A new starting point coordinate.

y

A new starting point coordinate.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::moveTextPos
HaruPage::moveToNextLine
HaruPage


Move text position to the start of the next line

HaruPage::moveTo
HaruPage::rectangle
HaruPage
PHP Manual

HaruPage::moveToNextLine

(PECL haru >= 0.0.1)

HaruPage::moveToNextLine — Move text position to the start of the next line

Opis

bool HaruPage::moveToNextLine ( void )

Moves text position to the start of the next line.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::moveTextPos() - Move text position to the specified offset

HaruPage::moveTo
HaruPage::rectangle
HaruPage


Append a rectangle to the current path

HaruPage::moveToNextLine
HaruPage::setCharSpace
HaruPage
PHP Manual

HaruPage::rectangle

(PECL haru >= 0.0.1)

HaruPage::rectangle — Append a rectangle to the current path

Opis

bool HaruPage::rectangle ( float $x , float $y , float $width , float $height )

Appends a rectangle to the current drawing path.

Parametry

x

The left border of the rectangle.

y

The lower border of the rectangle.

width

The width of the rectangle.

height

The height of the rectangle.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::moveToNextLine
HaruPage::setCharSpace
HaruPage


Set character spacing for the page

HaruPage::rectangle
HaruPage::setCMYKFill
HaruPage
PHP Manual

HaruPage::setCharSpace

(PECL haru >= 0.0.1)

HaruPage::setCharSpace — Set character spacing for the page

Opis

bool HaruPage::setCharSpace ( float $char_space )

Defines character spacing for the page.

Parametry

char_space

The new character spacing for the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getCharSpace() - Get the current value of character spacing

HaruPage::rectangle
HaruPage::setCMYKFill
HaruPage


Set filling color for the page

HaruPage::setCharSpace
HaruPage::setCMYKStroke
HaruPage
PHP Manual

HaruPage::setCMYKFill

(PECL haru >= 0.0.1)

HaruPage::setCMYKFill — Set filling color for the page

Opis

bool HaruPage::setCMYKFill ( float $c , float $m , float $y , float $k )

Defines filling color for the page.

Parametry

c

m

y

k

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getCMYKFill() - Get the current filling color

HaruPage::setCharSpace
HaruPage::setCMYKStroke
HaruPage


Set stroking color for the page

HaruPage::setCMYKFill
HaruPage::setDash
HaruPage
PHP Manual

HaruPage::setCMYKStroke

(PECL haru >= 0.0.1)

HaruPage::setCMYKStroke — Set stroking color for the page

Opis

bool HaruPage::setCMYKStroke ( float $c , float $m , float $y , float $k )

Defines stroking color for the page.

Parametry

c

m

y

k

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getCMYKStroke() - Get the current stroking color

HaruPage::setCMYKFill
HaruPage::setDash
HaruPage


Set the dash pattern for the page

HaruPage::setCMYKStroke
HaruPage::setFlatness
HaruPage
PHP Manual

HaruPage::setDash

(PECL haru >= 0.0.1)

HaruPage::setDash — Set the dash pattern for the page

Opis

bool HaruPage::setDash ( array $pattern , int $phase )

Defines the dash pattern for the page.

Parametry

pattern

An array (8 elements max) which contains a pattern of dashes and gaps used for lines on the page.

phase

The phase on which the pattern begins.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getDash() - Get the current dash pattern

HaruPage::setCMYKStroke
HaruPage::setFlatness
HaruPage


Set flatness for the page

HaruPage::setDash
HaruPage::setFontAndSize
HaruPage
PHP Manual

HaruPage::setFlatness

(PECL haru >= 0.0.1)

HaruPage::setFlatness — Set flatness for the page

Opis

bool HaruPage::setFlatness ( float $flatness )

Defines flatness for the page.

Parametry

flatness

The defined flatness for the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getFlatness() - Get the flatness of the page

HaruPage::setDash
HaruPage::setFontAndSize
HaruPage


Set font and fontsize for the page

HaruPage::setFlatness
HaruPage::setGrayFill
HaruPage
PHP Manual

HaruPage::setFontAndSize

(PECL haru >= 0.0.1)

HaruPage::setFontAndSize — Set font and fontsize for the page

Opis

bool HaruPage::setFontAndSize ( object $font , float $size )

Defines current font and its size for the page.

Parametry

font

A valid HaruFont instance.

size

The size of the font.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruDoc::getFont() - Get HaruFont instance

HaruPage::setFlatness
HaruPage::setGrayFill
HaruPage


Set filling color for the page

HaruPage::setFontAndSize
HaruPage::setGrayStroke
HaruPage
PHP Manual

HaruPage::setGrayFill

(PECL haru >= 0.0.1)

HaruPage::setGrayFill — Set filling color for the page

Opis

bool HaruPage::setGrayFill ( float $value )

Defines filling color for the page.

Parametry

value

The value of gray level between 0 and 1.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getGrayFill() - Get the current filling color

HaruPage::setFontAndSize
HaruPage::setGrayStroke
HaruPage


Sets stroking color for the page

HaruPage::setGrayFill
HaruPage::setHeight
HaruPage
PHP Manual

HaruPage::setGrayStroke

(PECL haru >= 0.0.1)

HaruPage::setGrayStroke — Sets stroking color for the page

Opis

bool HaruPage::setGrayStroke ( float $value )

Defines stroking color for the page.

Parametry

value

The value of gray level between 0 and 1.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getGrayStroke() - Get the current stroking color

HaruPage::setGrayFill
HaruPage::setHeight
HaruPage


Set height of the page

HaruPage::setGrayStroke
HaruPage::setHorizontalScaling
HaruPage
PHP Manual

HaruPage::setHeight

(PECL haru >= 0.0.1)

HaruPage::setHeight — Set height of the page

Opis

bool HaruPage::setHeight ( float $height )

Defines height of the page.

Parametry

height

The defined height for the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getHeight() - Get the height of the page

HaruPage::setGrayStroke
HaruPage::setHorizontalScaling
HaruPage


Set horizontal scaling for the page

HaruPage::setHeight
HaruPage::setLineCap
HaruPage
PHP Manual

HaruPage::setHorizontalScaling

(PECL haru >= 0.0.1)

HaruPage::setHorizontalScaling — Set horizontal scaling for the page

Opis

bool HaruPage::setHorizontalScaling ( float $scaling )

Set the horizontal scaling for the page.

Parametry

scaling

The horizontal scaling for text showing on the page. The initial value is 100.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getHorizontalScaling() - Get the current value of horizontal scaling

HaruPage::setHeight
HaruPage::setLineCap
HaruPage


Set the shape to be used at the ends of lines

HaruPage::setHorizontalScaling
HaruPage::setLineJoin
HaruPage
PHP Manual

HaruPage::setLineCap

(PECL haru >= 0.0.1)

HaruPage::setLineCap — Set the shape to be used at the ends of lines

Opis

bool HaruPage::setLineCap ( int $cap )

Defines the shape to be used at the ends of lines.

Parametry

cap

Must be one of the following values:

  • HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
  • HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
  • HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getLineCap() - Get the current line cap style

HaruPage::setHorizontalScaling
HaruPage::setLineJoin
HaruPage


Set line join style for the page

HaruPage::setLineCap
HaruPage::setLineWidth
HaruPage
PHP Manual

HaruPage::setLineJoin

(PECL haru >= 0.0.1)

HaruPage::setLineJoin — Set line join style for the page

Opis

bool HaruPage::setLineJoin ( int $join )

Defines line join style for the page.

Parametry

join

Must be one of the following values:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getLineJoin() - Get the current line join style

HaruPage::setLineCap
HaruPage::setLineWidth
HaruPage


Set line width for the page

HaruPage::setLineJoin
HaruPage::setMiterLimit
HaruPage
PHP Manual

HaruPage::setLineWidth

(PECL haru >= 0.0.1)

HaruPage::setLineWidth — Set line width for the page

Opis

bool HaruPage::setLineWidth ( float $width )

Defines line width for the page.

Parametry

width

The defined line width for the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getLineWidth() - Get the current line width

HaruPage::setLineJoin
HaruPage::setMiterLimit
HaruPage


Set the current value of the miter limit of the page

HaruPage::setLineWidth
HaruPage::setRGBFill
HaruPage
PHP Manual

HaruPage::setMiterLimit

(PECL haru >= 0.0.1)

HaruPage::setMiterLimit — Set the current value of the miter limit of the page

Opis

bool HaruPage::setMiterLimit ( float $limit )

Set the current value of the miter limit of the page.

Parametry

limit

Defines the current value of the miter limit of the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getMiterLimit() - Get the value of miter limit

HaruPage::setLineWidth
HaruPage::setRGBFill
HaruPage


Set filling color for the page

HaruPage::setMiterLimit
HaruPage::setRGBStroke
HaruPage
PHP Manual

HaruPage::setRGBFill

(PECL haru >= 0.0.1)

HaruPage::setRGBFill — Set filling color for the page

Opis

bool HaruPage::setRGBFill ( float $r , float $g , float $b )

Defines filling color for the page. All values must be between 0 and 1.

Parametry

r

g

b

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getRGBFill() - Get the current filling color

HaruPage::setMiterLimit
HaruPage::setRGBStroke
HaruPage


Set stroking color for the page

HaruPage::setRGBFill
HaruPage::setRotate
HaruPage
PHP Manual

HaruPage::setRGBStroke

(PECL haru >= 0.0.1)

HaruPage::setRGBStroke — Set stroking color for the page

Opis

bool HaruPage::setRGBStroke ( float $r , float $g , float $b )

Defines stroking color for the page. All values must be between 0 and 1.

Parametry

r

g

b

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getRGBStroke() - Get the current stroking color

HaruPage::setRGBFill
HaruPage::setRotate
HaruPage


Set rotation angle of the page

HaruPage::setRGBStroke
HaruPage::setSize
HaruPage
PHP Manual

HaruPage::setRotate

(PECL haru >= 0.0.1)

HaruPage::setRotate — Set rotation angle of the page

Opis

bool HaruPage::setRotate ( int $angle )

Defines rotation angle of the page.

Parametry

angle

Must be a multiple of 90 degrees.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::setRGBStroke
HaruPage::setSize
HaruPage


Set size and direction of the page

HaruPage::setRotate
HaruPage::setSlideShow
HaruPage
PHP Manual

HaruPage::setSize

(PECL haru >= 0.0.1)

HaruPage::setSize — Set size and direction of the page

Opis

bool HaruPage::setSize ( int $size , int $direction )

Changes size and direction of the page to a predefined format.

Parametry

size

Must be one of the following values:

  • HaruPage::SIZE_LETTER
  • HaruPage::SIZE_LEGAL
  • HaruPage::SIZE_A3
  • HaruPage::SIZE_A4
  • HaruPage::SIZE_A5
  • HaruPage::SIZE_B4
  • HaruPage::SIZE_B5
  • HaruPage::SIZE_EXECUTIVE
  • HaruPage::SIZE_US4x6
  • HaruPage::SIZE_US4x8
  • HaruPage::SIZE_US5x7
  • HaruPage::SIZE_COMM10

direction

Must be one of the following values:

  • HaruPage::PORTRAIT
  • HaruPage::LANDSCAPE

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::setWidth() - Set width of the page
  • HaruPage::setHeight() - Set height of the page

HaruPage::setRotate
HaruPage::setSlideShow
HaruPage


Set transition style for the page

HaruPage::setSize
HaruPage::setTextLeading
HaruPage
PHP Manual

HaruPage::setSlideShow

(PECL haru >= 0.0.1)

HaruPage::setSlideShow — Set transition style for the page

Opis

bool HaruPage::setSlideShow ( int $type , float $disp_time , float $trans_time )

Defines transition style for the page.

Parametry

type

Must be one of the following values:

  • HaruPage::TS_WIPE_RIGHT
  • HaruPage::TS_WIPE_LEFT
  • HaruPage::TS_WIPE_UP
  • HaruPage::TS_WIPE_DOWN
  • HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT
  • HaruPage::TS_BARN_DOORS_HORIZONTAL_IN
  • HaruPage::TS_BARN_DOORS_VERTICAL_OUT
  • HaruPage::TS_BARN_DOORS_VERTICAL_IN
  • HaruPage::TS_BOX_OUT
  • HaruPage::TS_BOX_IN
  • HaruPage::TS_BLINDS_HORIZONTAL
  • HaruPage::TS_BLINDS_VERTICAL
  • HaruPage::TS_DISSOLVE
  • HaruPage::TS_GLITTER_RIGHT
  • HaruPage::TS_GLITTER_DOWN
  • HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT
  • HaruPage::TS_REPLACE

disp_time

The display duration of the page in seconds.

trans_time

The duration of the transition effect in seconds.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::setSize
HaruPage::setTextLeading
HaruPage


Set text leading (line spacing) for the page

HaruPage::setSlideShow
HaruPage::setTextMatrix
HaruPage
PHP Manual

HaruPage::setTextLeading

(PECL haru >= 0.0.1)

HaruPage::setTextLeading — Set text leading (line spacing) for the page

Opis

bool HaruPage::setTextLeading ( float $text_leading )

Set the text leading (line spacing) for the page.

Parametry

text_leading

Defines line spacing for the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getTextLeading() - Get the current value of line spacing

HaruPage::setSlideShow
HaruPage::setTextMatrix
HaruPage


Set the current text transformation matrix of the page

HaruPage::setTextLeading
HaruPage::setTextRenderingMode
HaruPage
PHP Manual

HaruPage::setTextMatrix

(PECL haru >= 0.0.1)

HaruPage::setTextMatrix — Set the current text transformation matrix of the page

Opis

bool HaruPage::setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )

Defines the text transformation matrix of the page.

Parametry

a

Width multiplier.

b

Vertical skew in radians.

c

Horizontal skew in radians.

d

Height multiplier.

x

Horizontal position for text.

y

Vertical position for text.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getTextMatrix() - Get the current text transformation matrix of the page

HaruPage::setTextLeading
HaruPage::setTextRenderingMode
HaruPage


Set text rendering mode for the page

HaruPage::setTextMatrix
HaruPage::setTextRise
HaruPage
PHP Manual

HaruPage::setTextRenderingMode

(PECL haru >= 0.0.1)

HaruPage::setTextRenderingMode — Set text rendering mode for the page

Opis

bool HaruPage::setTextRenderingMode ( int $mode )

Defines text rendering mode for the page.

Parametry

mode

Must be one of the following values:

  • HaruPage::FILL
  • HaruPage::STROKE
  • HaruPage::FILL_THEN_STROKE
  • HaruPage::INVISIBLE
  • HaruPage::FILL_CLIPPING
  • HaruPage::STROKE_CLIPPING
  • HaruPage::FILL_STROKE_CLIPPING
  • HaruPage::CLIPPING

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getTextRenderingMode() - Get the current text rendering mode

HaruPage::setTextMatrix
HaruPage::setTextRise
HaruPage


Set the current value of text rising

HaruPage::setTextRenderingMode
HaruPage::setWidth
HaruPage
PHP Manual

HaruPage::setTextRise

(PECL haru >= 0.0.1)

HaruPage::setTextRise — Set the current value of text rising

Opis

bool HaruPage::setTextRise ( float $rise )

Set the current value of text rising.

Parametry

rise

Defines the current value of text rising.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getTextRise() - Get the current value of text rising

HaruPage::setTextRenderingMode
HaruPage::setWidth
HaruPage


Set width of the page

HaruPage::setTextRise
HaruPage::setWordSpace
HaruPage
PHP Manual

HaruPage::setWidth

(PECL haru >= 0.0.1)

HaruPage::setWidth — Set width of the page

Opis

bool HaruPage::setWidth ( float $width )

Set the width of the page.

Parametry

width

Defines width of the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getWidth() - Get the width of the page

HaruPage::setTextRise
HaruPage::setWordSpace
HaruPage


Set word spacing for the page

HaruPage::setWidth
HaruPage::showText
HaruPage
PHP Manual

HaruPage::setWordSpace

(PECL haru >= 0.0.1)

HaruPage::setWordSpace — Set word spacing for the page

Opis

bool HaruPage::setWordSpace ( float $word_space )

Set the word spacing for the page.

Parametry

word_space

Defines word spacing for the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::getWordSpace() - Get the current value of word spacing

HaruPage::setWidth
HaruPage::showText
HaruPage


Print text at the current position of the page

HaruPage::setWordSpace
HaruPage::showTextNextLine
HaruPage
PHP Manual

HaruPage::showText

(PECL haru >= 0.0.1)

HaruPage::showText — Print text at the current position of the page

Opis

bool HaruPage::showText ( string $text )

Prints out the text at the current position of the page.

Parametry

text

The text to show.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::textOut() - Print the text on the specified position

HaruPage::setWordSpace
HaruPage::showTextNextLine
HaruPage


Move the current position to the start of the next line and print the text

HaruPage::showText
HaruPage::stroke
HaruPage
PHP Manual

HaruPage::showTextNextLine

(PECL haru >= 0.0.1)

HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text

Opis

bool HaruPage::showTextNextLine ( string $text [, float $word_space = 0 [, float $char_space = 0 ]] )

Moves the current position to the start of the next line and print out the text.

Parametry

text

The text to show.

word_space

The word spacing.

char_space

The character spacing.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::showText() - Print text at the current position of the page
  • HaruPage::textOut() - Print the text on the specified position

HaruPage::showText
HaruPage::stroke
HaruPage


Paint current path

HaruPage::showTextNextLine
HaruPage::textOut
HaruPage
PHP Manual

HaruPage::stroke

(PECL haru >= 0.0.1)

HaruPage::stroke — Paint current path

Opis

bool HaruPage::stroke ([ bool $close_path = false ] )

Paints the current path.

Parametry

close_path

Closes the current path if set to TRUE.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruPage::showTextNextLine
HaruPage::textOut
HaruPage


Print the text on the specified position

HaruPage::stroke
HaruPage::textRect
HaruPage
PHP Manual

HaruPage::textOut

(PECL haru >= 0.0.1)

HaruPage::textOut — Print the text on the specified position

Opis

bool HaruPage::textOut ( float $x , float $y , string $text )

Prints the text on the specified position.

Parametry

x

y

text

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::showText() - Print text at the current position of the page

HaruPage::stroke
HaruPage::textRect
HaruPage


Print the text inside the specified region

HaruPage::textOut
HaruFont
HaruPage
PHP Manual

HaruPage::textRect

(PECL haru >= 0.0.1)

HaruPage::textRect — Print the text inside the specified region

Opis

bool HaruPage::textRect ( float $left , float $top , float $right , float $bottom , string $text [, int $align = HaruPage::TALIGN_LEFT ] )

Prints the text inside the specified region.

Parametry

left

Left border of the text area.

top

Top border of the text area.

right

Right border of the text area.

bottom

Lower border of the text area.

text

The text to print.

align

Text alignment. Must be one of the following values:

  • HaruPage::TALIGN_LEFT
  • HaruPage::TALIGN_RIGHT
  • HaruPage::TALIGN_CENTER
  • HaruPage::TALIGN_JUSTIFY

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

Zobacz też:

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::showText() - Print text at the current position of the page
  • HaruPage::textOut() - Print the text on the specified position

HaruPage::textOut
HaruFont
HaruPage


The HaruFont class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Font Class.

Krótki opis klasy

HaruFont {
/* Metody */
int getAscent ( void )
int getCapHeight ( void )
int getDescent ( void )
string getEncodingName ( void )
string getFontName ( void )
array getTextWidth ( string $text )
int getUnicodeWidth ( int $character )
int getXHeight ( void )
int measureText ( string $text , float $width , float $font_size , float $char_space , float $word_space [, bool $word_wrap = false ] )
}

Spis treści

  • HaruFont::getAscent — Get the vertical ascent of the font
  • HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters
  • HaruFont::getDescent — Get the vertical descent of the font
  • HaruFont::getEncodingName — Get the name of the encoding
  • HaruFont::getFontName — Get the name of the font
  • HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces
  • HaruFont::getUnicodeWidth — Get the width of the character in the font
  • HaruFont::getXHeight — Get the distance from the baseline of lowercase letters
  • HaruFont::measureText — Calculate the number of characters which can be included within the specified width
HaruPage::textRect
HaruFont::getAscent
haru


Get the vertical ascent of the font

HaruFont
HaruFont::getCapHeight
HaruFont
PHP Manual

HaruFont::getAscent

(PECL haru >= 0.0.1)

HaruFont::getAscent — Get the vertical ascent of the font

Opis

int HaruFont::getAscent ( void )

Get the vertical ascent of the font.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the vertical ascent of the font.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont
HaruFont::getCapHeight
HaruFont


Get the distance from the baseline of uppercase letters

HaruFont::getAscent
HaruFont::getDescent
HaruFont
PHP Manual

HaruFont::getCapHeight

(PECL haru >= 0.0.1)

HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters

Opis

int HaruFont::getCapHeight ( void )

Get the distance from the baseline of uppercase letters.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the distance from the baseline of uppercase letters.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont::getAscent
HaruFont::getDescent
HaruFont


Get the vertical descent of the font

HaruFont::getCapHeight
HaruFont::getEncodingName
HaruFont
PHP Manual

HaruFont::getDescent

(PECL haru >= 0.0.1)

HaruFont::getDescent — Get the vertical descent of the font

Opis

int HaruFont::getDescent ( void )

Get the vertical descent of the font.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return the vertical descent of the font.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont::getCapHeight
HaruFont::getEncodingName
HaruFont


Get the name of the encoding

HaruFont::getDescent
HaruFont::getFontName
HaruFont
PHP Manual

HaruFont::getEncodingName

(PECL haru >= 0.0.1)

HaruFont::getEncodingName — Get the name of the encoding

Opis

string HaruFont::getEncodingName ( void )

Get the name of the font encoding.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the name of the font encoding.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont::getDescent
HaruFont::getFontName
HaruFont


Get the name of the font

HaruFont::getEncodingName
HaruFont::getTextWidth
HaruFont
PHP Manual

HaruFont::getFontName

(PECL haru >= 0.0.1)

HaruFont::getFontName — Get the name of the font

Opis

string HaruFont::getFontName ( void )

Get the name of the font.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the name of the font.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont::getEncodingName
HaruFont::getTextWidth
HaruFont


Get the total width of the text, number of characters, number of words and number of spaces

HaruFont::getFontName
HaruFont::getUnicodeWidth
HaruFont
PHP Manual

HaruFont::getTextWidth

(PECL haru >= 0.0.1)

HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces

Opis

array HaruFont::getTextWidth ( string $text )

Get the total width of the text, number of characters, number of words and number of spaces.

Parametry

text

The text to measure.

Zwracane wartości

Returns the total width of the text, number of characters, number of words and number of spaces in the given text.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont::getFontName
HaruFont::getUnicodeWidth
HaruFont


Get the width of the character in the font

HaruFont::getTextWidth
HaruFont::getXHeight
HaruFont
PHP Manual

HaruFont::getUnicodeWidth

(PECL haru >= 0.0.1)

HaruFont::getUnicodeWidth — Get the width of the character in the font

Opis

int HaruFont::getUnicodeWidth ( int $character )

Get the width of the character in the font.

Parametry

character

The code of the character.

Zwracane wartości

Returns the width of the character in the font.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont::getTextWidth
HaruFont::getXHeight
HaruFont


Get the distance from the baseline of lowercase letters

HaruFont::getUnicodeWidth
HaruFont::measureText
HaruFont
PHP Manual

HaruFont::getXHeight

(PECL haru >= 0.0.1)

HaruFont::getXHeight — Get the distance from the baseline of lowercase letters

Opis

int HaruFont::getXHeight ( void )

Gets the distance from the baseline of lowercase letters.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the distance from the baseline of lowercase letters.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont::getUnicodeWidth
HaruFont::measureText
HaruFont


Calculate the number of characters which can be included within the specified width

HaruFont::getXHeight
HaruImage
HaruFont
PHP Manual

HaruFont::measureText

(PECL haru >= 0.0.1)

HaruFont::measureText — Calculate the number of characters which can be included within the specified width

Opis

int HaruFont::measureText ( string $text , float $width , float $font_size , float $char_space , float $word_space [, bool $word_wrap = false ] )

Calculate the number of characters which can be included within the specified width.

Parametry

text

The text to fit the width.

width

The width of the area to put the text to.

font_size

The size of the font.

char_space

The character spacing.

word_space

The word spacing.

word_wrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area.

Zwracane wartości

Returns the number of characters which can be included within the specified width.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruFont::getXHeight
HaruImage
HaruFont


The HaruImage class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Image Class.

Krótki opis klasy

HaruImage {
/* Metody */
int getBitsPerComponent ( void )
string getColorSpace ( void )
int getHeight ( void )
array getSize ( void )
int getWidth ( void )
bool setColorMask ( int $rmin , int $rmax , int $gmin , int $gmax , int $bmin , int $bmax )
bool setMaskImage ( object $mask_image )
}

Spis treści

  • HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image
  • HaruImage::getColorSpace — Get the name of the color space
  • HaruImage::getHeight — Get the height of the image
  • HaruImage::getSize — Get size of the image
  • HaruImage::getWidth — Get the width of the image
  • HaruImage::setColorMask — Set the color mask of the image
  • HaruImage::setMaskImage — Set the image mask
HaruFont::measureText
HaruImage::getBitsPerComponent
haru


Get the number of bits used to describe each color component of the image

HaruImage
HaruImage::getColorSpace
HaruImage
PHP Manual

HaruImage::getBitsPerComponent

(PECL haru >= 0.0.1)

HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image

Opis

int HaruImage::getBitsPerComponent ( void )

Gets the number of bits used to describe each color component of the image.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the number of bits used to describe each color component of the image.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruImage
HaruImage::getColorSpace
HaruImage


Get the name of the color space

HaruImage::getBitsPerComponent
HaruImage::getHeight
HaruImage
PHP Manual

HaruImage::getColorSpace

(PECL haru >= 0.0.1)

HaruImage::getColorSpace — Get the name of the color space

Opis

string HaruImage::getColorSpace ( void )

Get the name of the color space.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the name of the color space of the image. The name is one of the following values:

  • "DeviceGray"
  • "DeviceRGB"
  • "DeviceCMYK"
  • "Indexed"

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruImage::getBitsPerComponent
HaruImage::getHeight
HaruImage


Get the height of the image

HaruImage::getColorSpace
HaruImage::getSize
HaruImage
PHP Manual

HaruImage::getHeight

(PECL haru >= 0.0.1)

HaruImage::getHeight — Get the height of the image

Opis

int HaruImage::getHeight ( void )

Get the height of the image.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the height of the image.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruImage::getColorSpace
HaruImage::getSize
HaruImage


Get size of the image

HaruImage::getHeight
HaruImage::getWidth
HaruImage
PHP Manual

HaruImage::getSize

(PECL haru >= 0.0.1)

HaruImage::getSize — Get size of the image

Opis

array HaruImage::getSize ( void )

Get the size of the image.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array with two elements: width and height, which contain appropriate dimensions of the image.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruImage::getHeight
HaruImage::getWidth
HaruImage


Get the width of the image

HaruImage::getSize
HaruImage::setColorMask
HaruImage
PHP Manual

HaruImage::getWidth

(PECL haru >= 0.0.1)

HaruImage::getWidth — Get the width of the image

Opis

int HaruImage::getWidth ( void )

Get the width of the image.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the width of the image.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruImage::getSize
HaruImage::setColorMask
HaruImage


Set the color mask of the image

HaruImage::getWidth
HaruImage::setMaskImage
HaruImage
PHP Manual

HaruImage::setColorMask

(PECL haru >= 0.0.1)

HaruImage::setColorMask — Set the color mask of the image

Opis

bool HaruImage::setColorMask ( int $rmin , int $rmax , int $gmin , int $gmax , int $bmin , int $bmax )

Defines the transparent color of the image using the RGB range values. The color within the range is displayed as a transparent color. The color space of the image must be RGB.

Parametry

rmin

The lower limit of red. Must be between 0 and 255.

rmax

The upper limit of red. Must be between 0 and 255.

gmin

The lower limit of green. Must be between 0 and 255.

gmax

The upper limit of green. Must be between 0 and 255.

bmin

The lower limit of blue. Must be between 0 and 255.

bmax

The upper limit of blue. Must be between 0 and 255.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruImage::getWidth
HaruImage::setMaskImage
HaruImage


Set the image mask

HaruImage::setColorMask
HaruEncoder
HaruImage
PHP Manual

HaruImage::setMaskImage

(PECL haru >= 0.0.1)

HaruImage::setMaskImage — Set the image mask

Opis

bool HaruImage::setMaskImage ( object $mask_image )

Sets the image used as image-mask. It must be 1bit gray-scale color image.

Parametry

mask_image

A valid HaruImage instance.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruImage::setColorMask
HaruEncoder
HaruImage


The HaruEncoder class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Encoder Class.

Krótki opis klasy

HaruEncoder {
/* Metody */
int getByteType ( string $text , int $index )
int getType ( void )
int getUnicode ( int $character )
int getWritingMode ( void )
}

Stałe predefiniowane

Type | Name | Description
int | HaruEncoder::TYPE_SINGLE_BYTE |
int | HaruEncoder::TYPE_DOUBLE_BYTE |
int | HaruEncoder::TYPE_UNINITIALIZED |
int | HaruEncoder::UNKNOWN |
int | HaruEncoder::WMODE_HORIZONTAL |
int | HaruEncoder::WMODE_VERTICAL |
int | HaruEncoder::BYTE_TYPE_SINGLE |
int | HaruEncoder::BYTE_TYPE_LEAD |
int | HaruEncoder::BYTE_TYPE_TRAIL |
int | HaruEncoder::BYTE_TYPE_UNKNOWN |

Spis treści

  • HaruEncoder::getByteType — Get the type of the byte in the text
  • HaruEncoder::getType — Get the type of the encoder
  • HaruEncoder::getUnicode — Convert the specified character to unicode
  • HaruEncoder::getWritingMode — Get the writing mode of the encoder
HaruImage::setMaskImage
HaruEncoder::getByteType
haru


Get the type of the byte in the text

HaruEncoder
HaruEncoder::getType
HaruEncoder
PHP Manual

HaruEncoder::getByteType

(PECL haru >= 0.0.1)

HaruEncoder::getByteType — Get the type of the byte in the text

Opis

int HaruEncoder::getByteType ( string $text , int $index )

Get the type of the byte in the text.

Parametry

text

The text.

index

The position in the text.

Zwracane wartości

Returns the type of the byte in the text on the specified position. The result is one of the following values:

  • HaruEncoder::BYTE_TYPE_SINGLE - single byte character.
  • HaruEncoder::BYTE_TYPE_LEAD - lead byte of a double-byte character.
  • HaruEncoder::BYTE_TYPE_TRAIL - trailing byte of a double-byte character.
  • HaruEncoder::BYTE_TYPE_UNKNOWN - invalid encoder or cannot detect the byte type.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruEncoder
HaruEncoder::getType
HaruEncoder


Get the type of the encoder

HaruEncoder::getByteType
HaruEncoder::getUnicode
HaruEncoder
PHP Manual

HaruEncoder::getType

(PECL haru >= 0.0.1)

HaruEncoder::getType — Get the type of the encoder

Opis

int HaruEncoder::getType ( void )

Get the type of the encoder.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the type of the encoder. The result is one of the following values:

  • HaruEncoder::TYPE_SINGLE_BYTE - the encoder is for single byte characters.
  • HaruEncoder::TYPE_DOUBLE_BYTE - the encoder is for multibyte characters.
  • HaruEncoder::TYPE_UNINITIALIZED - the encoder is not initialized.
  • HaruEncoder::UNKNOWN - the encoder is invalid.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruEncoder::getByteType
HaruEncoder::getUnicode
HaruEncoder


Convert the specified character to unicode

HaruEncoder::getType
HaruEncoder::getWritingMode
HaruEncoder
PHP Manual

HaruEncoder::getUnicode

(PECL haru >= 0.0.1)

HaruEncoder::getUnicode — Convert the specified character to unicode

Opis

int HaruEncoder::getUnicode ( int $character )

Converts the specified character to unicode.

Parametry

character

The character code to convert.

Zwracane wartości

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruEncoder::getType
HaruEncoder::getWritingMode
HaruEncoder


Get the writing mode of the encoder

HaruEncoder::getUnicode
HaruOutline
HaruEncoder
PHP Manual

HaruEncoder::getWritingMode

(PECL haru >= 0.0.1)

HaruEncoder::getWritingMode — Get the writing mode of the encoder

Opis

int HaruEncoder::getWritingMode ( void )

Get the writing mode of the encoder.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the writing mode of the encoder. The result value is on of the following:

  • HaruEncoder::WMODE_HORIZONTAL - horizontal writing mode.
  • HaruEncoder::WMODE_VERTICAL - vertical writing mode.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruEncoder::getUnicode
HaruOutline
HaruEncoder


The HaruOutline class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Outline Class.

Krótki opis klasy

HaruOutline {
/* Metody */
bool setDestination ( object $destination )
bool setOpened ( bool $opened )
}

Spis treści

  • HaruOutline::setDestination — Set the destination for the outline
  • HaruOutline::setOpened — Set the initial state of the outline
HaruEncoder::getWritingMode
HaruOutline::setDestination
haru


Set the destination for the outline

HaruOutline
HaruOutline::setOpened
HaruOutline
PHP Manual

HaruOutline::setDestination

(PECL haru >= 0.0.1)

HaruOutline::setDestination — Set the destination for the outline

Opis

bool HaruOutline::setDestination ( object $destination )

Sets a destination object which becomes a target to jump to when the outline is clicked.

Parametry

destination

A valid HaruDestination instance.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruOutline
HaruOutline::setOpened
HaruOutline


Set the initial state of the outline

HaruOutline::setDestination
HaruAnnotation
HaruOutline
PHP Manual

HaruOutline::setOpened

(PECL haru >= 0.0.1)

HaruOutline::setOpened — Set the initial state of the outline

Opis

bool HaruOutline::setOpened ( bool $opened )

Defines whether this node is opened or not when the outline is displayed for the first time.

Parametry

opened

TRUE means open, FALSE - closed.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruOutline::setDestination
HaruAnnotation
HaruOutline


The HaruAnnotation class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Annotation Class.

Krótki opis klasy

HaruAnnotation {
/* Metody */
bool setBorderStyle ( float $width , int $dash_on , int $dash_off )
bool setHighlightMode ( int $mode )
bool setIcon ( int $icon )
bool setOpened ( bool $opened )
}

Stałe predefiniowane

Type | Name | Description
int | HaruAnnotation::NO_HIGHLIGHT |
int | HaruAnnotation::INVERT_BOX |
int | HaruAnnotation::INVERT_BORDER |
int | HaruAnnotation::DOWN_APPEARANCE |
int | HaruAnnotation::ICON_COMMENT |
int | HaruAnnotation::ICON_KEY |
int | HaruAnnotation::ICON_NOTE |
int | HaruAnnotation::ICON_HELP |
int | HaruAnnotation::ICON_NEW_PARAGRAPH |
int | HaruAnnotation::ICON_PARAGRAPH |
int | HaruAnnotation::ICON_INSERT |

Spis treści

  • HaruAnnotation::setBorderStyle — Set the border style of the annotation
  • HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation
  • HaruAnnotation::setIcon — Set the icon style of the annotation
  • HaruAnnotation::setOpened — Set the initial state of the annotation
HaruOutline::setOpened
HaruAnnotation::setBorderStyle
haru


Set the border style of the annotation

HaruAnnotation
HaruAnnotation::setHighlightMode
HaruAnnotation
PHP Manual

HaruAnnotation::setBorderStyle

(PECL haru >= 0.0.1)

HaruAnnotation::setBorderStyle — Set the border style of the annotation

Opis

bool HaruAnnotation::setBorderStyle ( float $width , int $dash_on , int $dash_off )

Defines the style of the border of the annotation. This function may be used with link annotations only.

Parametry

width

The width of the border line.

dash_on

The dash style.

dash_off

The dash style.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruAnnotation
HaruAnnotation::setHighlightMode
HaruAnnotation


Set the highlighting mode of the annotation

HaruAnnotation::setBorderStyle
HaruAnnotation::setIcon
HaruAnnotation
PHP Manual

HaruAnnotation::setHighlightMode

(PECL haru >= 0.0.1)

HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation

Opis

bool HaruAnnotation::setHighlightMode ( int $mode )

Defines the appearance of the annotation when clicked. This function may be used with link annotations only.

Parametry

mode

The highlighting mode of the annotation. Can take only these values:

  • HaruAnnotation::NO_HIGHLIGHT - no highlighting.
  • HaruAnnotation::INVERT_BOX - invert the contents of the annotation.
  • HaruAnnotation::INVERT_BORDER - invert the border of the annotation.
  • HaruAnnotation::DOWN_APPEARANCE - dent the annotation.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruAnnotation::setBorderStyle
HaruAnnotation::setIcon
HaruAnnotation


Set the icon style of the annotation

HaruAnnotation::setHighlightMode
HaruAnnotation::setOpened
HaruAnnotation
PHP Manual

HaruAnnotation::setIcon

(PECL haru >= 0.0.1)

HaruAnnotation::setIcon — Set the icon style of the annotation

Opis

bool HaruAnnotation::setIcon ( int $icon )

Defines the style of the annotation icon. This function may be used with text annotations only.

Parametry

icon

The style of the icon. Can take only these values:

  • HaruAnnotation::ICON_COMMENT
  • HaruAnnotation::ICON_KEY
  • HaruAnnotation::ICON_NOTE
  • HaruAnnotation::ICON_HELP
  • HaruAnnotation::ICON_NEW_PARAGRAPH
  • HaruAnnotation::ICON_PARAGRAPH
  • HaruAnnotation::ICON_INSERT

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruAnnotation::setHighlightMode
HaruAnnotation::setOpened
HaruAnnotation


Set the initial state of the annotation

HaruAnnotation::setIcon
HaruDestination
HaruAnnotation
PHP Manual

HaruAnnotation::setOpened

(PECL haru >= 0.0.1)

HaruAnnotation::setOpened — Set the initial state of the annotation

Opis

bool HaruAnnotation::setOpened ( bool $opened )

Defines whether the annotation is initially displayed open. This function may be used with text annotations only.

Parametry

opened

TRUE means the annotation is initially displayed open, FALSE - means it's closed.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruAnnotation::setIcon
HaruDestination
HaruAnnotation


The HaruDestination class

(No version information available, might only be in SVN)

Wstęp

Haru PDF Destination Class.

Krótki opis klasy

HaruDestination {
/* Metody */
bool setFit ( void )
bool setFitB ( void )
bool setFitBH ( float $top )
bool setFitBV ( float $left )
bool setFitH ( float $top )
bool setFitR ( float $left , float $bottom , float $right , float $top )
bool setFitV ( float $left )
bool setXYZ ( float $left , float $top , float $zoom )
}

Spis treści

  • HaruDestination::setFit — Set the appearance of the page to fit the window
  • HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window
  • HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box
  • HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box
  • HaruDestination::setFitH — Set the appearance of the page to fit the window width
  • HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle
  • HaruDestination::setFitV — Set the appearance of the page to fit the window height
  • HaruDestination::setXYZ — Set the appearance of the page
HaruAnnotation::setOpened
HaruDestination::setFit
haru


Set the appearance of the page to fit the window

HaruDestination
HaruDestination::setFitB
HaruDestination
PHP Manual

HaruDestination::setFit

(PECL haru >= 0.0.1)

HaruDestination::setFit — Set the appearance of the page to fit the window

Opis

bool HaruDestination::setFit ( void )

Defines the appearance of the page to fit the window.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDestination
HaruDestination::setFitB
HaruDestination


Set the appearance of the page to fit the bounding box of the page within the window

HaruDestination::setFit
HaruDestination::setFitBH
HaruDestination
PHP Manual

HaruDestination::setFitB

(PECL haru >= 0.0.1)

HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window

Opis

bool HaruDestination::setFitB ( void )

Defines the appearance of the page to fit the bounding box of the page within the window.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDestination::setFit
HaruDestination::setFitBH
HaruDestination


Set the appearance of the page to fit the width of the bounding box

HaruDestination::setFitB
HaruDestination::setFitBV
HaruDestination
PHP Manual

HaruDestination::setFitBH

(PECL haru >= 0.0.1)

HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box

Opis

bool HaruDestination::setFitBH ( float $top )

Defines the appearance of the page to magnifying to fit the width of the bounding box and setting the top position of the page to the value of top.

Parametry

top

The top coordinates of the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDestination::setFitB
HaruDestination::setFitBV
HaruDestination


Set the appearance of the page to fit the height of the boudning box

HaruDestination::setFitBH
HaruDestination::setFitH
HaruDestination
PHP Manual

HaruDestination::setFitBV

(PECL haru >= 0.0.1)

HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box

Opis

bool HaruDestination::setFitBV ( float $left )

Defines the appearance of the page to magnifying to fit the height of the bounding box and setting the left position of the page to the value of left.

Parametry

left

The left coordinates of the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDestination::setFitBH
HaruDestination::setFitH
HaruDestination


Set the appearance of the page to fit the window width

HaruDestination::setFitBV
HaruDestination::setFitR
HaruDestination
PHP Manual

HaruDestination::setFitH

(PECL haru >= 0.0.1)

HaruDestination::setFitH — Set the appearance of the page to fit the window width

Opis

bool HaruDestination::setFitH ( float $top )

Defines the appearance of the page to fit the window width and sets the top position of the page to the value of top.

Parametry

top

The top position of the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDestination::setFitBV
HaruDestination::setFitR
HaruDestination


Set the appearance of the page to fit the specified rectangle

HaruDestination::setFitH
HaruDestination::setFitV
HaruDestination
PHP Manual

HaruDestination::setFitR

(PECL haru >= 0.0.1)

HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle

Opis

bool HaruDestination::setFitR ( float $left , float $bottom , float $right , float $top )

Defines the appearance of the page to fit the rectangle by the parameters.

Parametry

left

The left coordinates of the page.

bottom

The bottom coordinates of the page.

right

The right coordinates of the page.

top

The top coordinates of the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDestination::setFitH
HaruDestination::setFitV
HaruDestination


Set the appearance of the page to fit the window height

HaruDestination::setFitR
HaruDestination::setXYZ
HaruDestination
PHP Manual

HaruDestination::setFitV

(PECL haru >= 0.0.1)

HaruDestination::setFitV — Set the appearance of the page to fit the window height

Opis

bool HaruDestination::setFitV ( float $left )

Defines the appearance of the page to fit the window height.

Parametry

left

The left position of the page.

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDestination::setFitR
HaruDestination::setXYZ
HaruDestination


Set the appearance of the page

HaruDestination::setFitV
Ming
HaruDestination
PHP Manual

HaruDestination::setXYZ

(PECL haru >= 0.0.1)

HaruDestination::setXYZ — Set the appearance of the page

Opis

bool HaruDestination::setXYZ ( float $left , float $top , float $zoom )

Defines the appearance of the page using three parameters: left, top and zoom.

Parametry

left

The left position of the page.

top

The top position of the page.

zoom

The magnification factor. The value must be between 0.08 (8%) and 32 (3200%).

Zwracane wartości

Returns TRUE on success.

Błędy/Wyjątki

Zgłasza wyjątek HaruException gdy wystąpi błąd.

HaruDestination::setFitV
Ming
HaruDestination


Ming (flash)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • SWFAction Examples
    • SWFSPrite basic examples
  • Ming Funkcje
    • ming_keypress — Returns the action flag for keyPress(char)
    • ming_setcubicthreshold — Set cubic threshold
    • ming_setscale — Set the global scaling factor.
    • ming_setswfcompression — Sets the SWF output compression
    • ming_useconstants — Use constant pool
    • ming_useswfversion — Sets the SWF version
  • SWFAction — The SWFAction class
    • SWFAction::__construct — Creates a new SWFAction
  • SWFBitmap — The SWFBitmap class
    • SWFBitmap::__construct — Loads Bitmap object
    • SWFBitmap::getHeight — Returns the bitmap's height
    • SWFBitmap::getWidth — Returns the bitmap's width
  • SWFButton — The SWFButton class
    • SWFButton::addAction — Adds an action
    • SWFButton::addASound — Associates a sound with a button transition
    • SWFButton::addShape — Adds a shape to a button
    • SWFButton::__construct — Creates a new Button
    • SWFButton::setAction — Sets the action
    • SWFButton::setDown — Alias for addShape(shape, SWFBUTTON_DOWN)
    • SWFButton::setHit — Alias for addShape(shape, SWFBUTTON_HIT)
    • SWFButton::setMenu — enable track as menu button behaviour
    • SWFButton::setOver — Alias for addShape(shape, SWFBUTTON_OVER)
    • SWFButton::setUp — Alias for addShape(shape, SWFBUTTON_UP)
  • SWFDisplayItem — The SWFDisplayItem class
    • SWFDisplayItem::addAction — Adds this SWFAction to the given SWFSprite instance
    • SWFDisplayItem::addColor — Adds the given color to this item's color transform
    • SWFDisplayItem::endMask — Another way of defining a MASK layer
    • SWFDisplayItem::getRot — Opis
    • SWFDisplayItem::getX — Opis
    • SWFDisplayItem::getXScale — Opis
    • SWFDisplayItem::getXSkew — Opis
    • SWFDisplayItem::getY — Opis
    • SWFDisplayItem::getYScale — Opis
    • SWFDisplayItem::getYSkew — Opis
    • SWFDisplayItem::move — Moves object in relative coordinates
    • SWFDisplayItem::moveTo — Moves object in global coordinates
    • SWFDisplayItem::multColor — Multiplies the item's color transform
    • SWFDisplayItem::remove — Removes the object from the movie
    • SWFDisplayItem::rotate — Rotates in relative coordinates
    • SWFDisplayItem::rotateTo — Rotates the object in global coordinates
    • SWFDisplayItem::scale — Scales the object in relative coordinates
    • SWFDisplayItem::scaleTo — Scales the object in global coordinates
    • SWFDisplayItem::setDepth — Sets z-order
    • SWFDisplayItem::setMaskLevel — Defines a MASK layer at level
    • SWFDisplayItem::setMatrix — Sets the item's transform matrix
    • SWFDisplayItem::setName — Sets the object's name
    • SWFDisplayItem::setRatio — Sets the object's ratio
    • SWFDisplayItem::skewX — Sets the X-skew
    • SWFDisplayItem::skewXTo — Sets the X-skew
    • SWFDisplayItem::skewY — Sets the Y-skew
    • SWFDisplayItem::skewYTo — Sets the Y-skew
  • SWFFill — The SWFFill class
    • SWFFill::moveTo — Moves fill origin
    • SWFFill::rotateTo — Sets fill's rotation
    • SWFFill::scaleTo — Sets fill's scale
    • SWFFill::skewXTo — Sets fill x-skew
    • SWFFill::skewYTo — Sets fill y-skew
  • SWFFont — The SWFFont class
    • SWFFont::__construct — Loads a font definition
    • SWFFont::getAscent — Returns the ascent of the font, or 0 if not available
    • SWFFont::getDescent — Returns the descent of the font, or 0 if not available
    • SWFFont::getLeading — Returns the leading of the font, or 0 if not available
    • SWFFont::getShape — Returns the glyph shape of a char as a text string
    • SWFFont::getUTF8Width — Calculates the width of the given string in this font at full height
    • SWFFont::getWidth — Returns the string's width
  • SWFFontChar — The SWFFontChar class
    • SWFFontChar::addChars — Adds characters to a font for exporting font
    • SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font
  • SWFGradient — The SWFGradient class
    • SWFGradient::addEntry — Adds an entry to the gradient list
    • SWFGradient::__construct — Creates a gradient object
  • SWFMorph — The SWFMorph class
    • SWFMorph::__construct — Creates a new SWFMorph object
    • SWFMorph::getShape1 — Gets a handle to the starting shape
    • SWFMorph::getShape2 — Gets a handle to the ending shape
  • SWFMovie — The SWFMovie class
    • SWFMovie::add — Adds any type of data to a movie
    • SWFMovie::addExport — Opis
    • SWFMovie::addFont — Opis
    • SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie
    • SWFMovie::importChar — Opis
    • SWFMovie::importFont — Opis
    • SWFMovie::labelFrame — Labels a frame
    • SWFMovie::nextFrame — Moves to the next frame of the animation
    • SWFMovie::output — Dumps your lovingly prepared movie out
    • SWFMovie::remove — Removes the object instance from the display list
    • SWFMovie::save — Saves the SWF movie in a file
    • SWFMovie::saveToFile — Opis
    • SWFMovie::setbackground — Sets the background color
    • SWFMovie::setDimension — Sets the movie's width and height
    • SWFMovie::setFrames — Sets the total number of frames in the animation
    • SWFMovie::setRate — Sets the animation's frame rate
    • SWFMovie::startSound — Opis
    • SWFMovie::stopSound — Opis
    • SWFMovie::streamMP3 — Streams a MP3 file
    • SWFMovie::writeExports — Opis
  • SWFPrebuiltClip — The SWFPrebuiltClip class
    • SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object
  • SWFShape — The SWFShape class
    • SWFShape::addFill — Adds a solid fill to the shape
    • SWFShape::__construct — Creates a new shape object
    • SWFShape::drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
    • SWFShape::drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
    • SWFShape::drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCurve — Draws a curve (relative)
    • SWFShape::drawCurveTo — Draws a curve
    • SWFShape::drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font
    • SWFShape::drawLine — Draws a line (relative)
    • SWFShape::drawLineTo — Draws a line
    • SWFShape::movePen — Moves the shape's pen (relative)
    • SWFShape::movePenTo — Moves the shape's pen
    • SWFShape::setLeftFill — Sets left rasterizing color
    • SWFShape::setLine — Sets the shape's line style
    • SWFShape::setRightFill — Sets right rasterizing color
  • SWFSound — The SWFSound class
    • SWFSound::__construct — Returns a new SWFSound object from given file
  • SWFSoundInstance — The SWFSoundInstance class
    • SWFSoundInstance::loopCount — Opis
    • SWFSoundInstance::loopInPoint — Opis
    • SWFSoundInstance::loopOutPoint — Opis
    • SWFSoundInstance::noMultiple — Opis
  • SWFSprite — The SWFSprite class
    • SWFSprite::add — Adds an object to a sprite
    • SWFSprite::__construct — Creates a movie clip (a sprite)
    • SWFSprite::labelFrame — Labels frame
    • SWFSprite::nextFrame — Moves to the next frame of the animation
    • SWFSprite::remove — Removes an object to a sprite
    • SWFSprite::setFrames — Sets the total number of frames in the animation
    • SWFSprite::startSound — Opis
    • SWFSprite::stopSound — Opis
  • SWFText — The SWFText class
    • SWFText::addString — Draws a string
    • SWFText::addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
    • SWFText::__construct — Creates a new SWFText object
    • SWFText::getAscent — Returns the ascent of the current font at its current size, or 0 if not available
    • SWFText::getDescent — Returns the descent of the current font at its current size, or 0 if not available
    • SWFText::getLeading — Returns the leading of the current font at its current size, or 0 if not available
    • SWFText::getUTF8Width — calculates the width of the given string in this text objects current font and size
    • SWFText::getWidth — Computes string's width
    • SWFText::moveTo — Moves the pen
    • SWFText::setColor — Sets the current text color
    • SWFText::setFont — Sets the current font
    • SWFText::setHeight — Sets the current font height
    • SWFText::setSpacing — Sets the current font spacing
  • SWFTextField — The SWFTextField class
    • SWFTextField::addChars — adds characters to a font that will be available within a textfield
    • SWFTextField::addString — Concatenates the given string to the text field
    • SWFTextField::align — Sets the text field alignment
    • SWFTextField::__construct — Creates a text field object
    • SWFTextField::setBounds — Sets the text field width and height
    • SWFTextField::setColor — Sets the color of the text field
    • SWFTextField::setFont — Sets the text field font
    • SWFTextField::setHeight — Sets the font height of this text field font
    • SWFTextField::setIndentation — Sets the indentation of the first line
    • SWFTextField::setLeftMargin — Sets the left margin width of the text field
    • SWFTextField::setLineSpacing — Sets the line spacing of the text field
    • SWFTextField::setMargins — Sets the margins width of the text field
    • SWFTextField::setName — Sets the variable name
    • SWFTextField::setPadding — Sets the padding of this textfield
    • SWFTextField::setRightMargin — Sets the right margin width of the text field
  • SWFVideoStream — The SWFVideoStream class
    • SWFVideoStream::__construct — Returns a SWFVideoStream object
    • SWFVideoStream::getNumFrames — Returns the number of frames in the video
    • SWFVideoStream::setDimension — Sets video dimension
HaruDestination::setXYZ
Wstęp
Generowanie nietekstowych formatów danych


Wstęp

First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only thing that's missing is sound events.

Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.

Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know at » http://www.libming.org/.

Ming was added in PHP 4.0.5.

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.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.3.0.

Ming
Instalacja/Konfiguracja
Ming


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Ming


Wymagania

To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page: » http://www.libming.org/ along with examples, a small tutorial, and the latest news.

Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.

This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/ming.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.3.0

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

MING_NEW (integer)
MING_ZLIB (integer)
SWFBUTTON_HIT (integer)
SWFBUTTON_DOWN (integer)
SWFBUTTON_OVER (integer)
SWFBUTTON_UP (integer)
SWFBUTTON_MOUSEUPOUTSIDE (integer)
SWFBUTTON_DRAGOVER (integer)
SWFBUTTON_DRAGOUT (integer)
SWFBUTTON_MOUSEUP (integer)
SWFBUTTON_MOUSEDOWN (integer)
SWFBUTTON_MOUSEOUT (integer)
SWFBUTTON_MOUSEOVER (integer)
SWFFILL_RADIAL_GRADIENT (integer)
SWFFILL_LINEAR_GRADIENT (integer)
SWFFILL_TILED_BITMAP (integer)
SWFFILL_CLIPPED_BITMAP (integer)
SWFTEXTFIELD_HASLENGTH (integer)
SWFTEXTFIELD_NOEDIT (integer)
SWFTEXTFIELD_PASSWORD (integer)
SWFTEXTFIELD_MULTILINE (integer)
SWFTEXTFIELD_WORDWRAP (integer)
SWFTEXTFIELD_DRAWBOX (integer)
SWFTEXTFIELD_NOSELECT (integer)
SWFTEXTFIELD_HTML (integer)
SWFTEXTFIELD_ALIGN_LEFT (integer)
SWFTEXTFIELD_ALIGN_RIGHT (integer)
SWFTEXTFIELD_ALIGN_CENTER (integer)
SWFTEXTFIELD_ALIGN_JUSTIFY (integer)
SWFACTION_ONLOAD (integer)
SWFACTION_ENTERFRAME (integer)
SWFACTION_UNLOAD (integer)
SWFACTION_MOUSEMOVE (integer)
SWFACTION_MOUSEDOWN (integer)
SWFACTION_MOUSEUP (integer)
SWFACTION_KEYDOWN (integer)
SWFACTION_KEYUP (integer)
SWFACTION_DATA (integer)
Typy zasobów
Przykłady
Ming


Przykłady

Spis treści

  • SWFAction Examples
  • SWFSPrite basic examples
Stałe predefiniowane
SWFAction Examples
Ming


SWFAction Examples

This simple example will move the red square across the window.

Przykład #1 swfaction() example

<?php
  $s = new SWFShape();
  $f = $s->addFill(0xff, 0, 0);
  $s->setRightFill($f);

  $s->movePenTo(-500, -500);
  $s->drawLineTo(500, -500);
  $s->drawLineTo(500, 500);
  $s->drawLineTo(-500, 500);
  $s->drawLineTo(-500, -500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $i->setDepth(1);
  $p->nextFrame();

  for ($n=0; $n<5; ++$n) {
    $i->rotate(-15);
    $p->nextFrame();
  }

  $m = new SWFMovie();
  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(6000, 4000);

  $i = $m->add($p);
  $i->setDepth(1);
  $i->moveTo(-500,2000);
  $i->setName("box");

  $m->add(new SWFAction("/box.x += 3;"));
  $m->nextFrame();
  $m->add(new SWFAction("gotoFrame(0); play();"));
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example tracks down your mouse on the screen.

Przykład #2 swfaction() example

<?php

  $m = new SWFMovie();
  $m->setRate(36.0);
  $m->setDimension(1200, 800);
  $m->setBackground(0, 0, 0);

  /* mouse tracking sprite - empty, but follows mouse so we can
     get its x and y coordinates */

  $i = $m->add(new SWFSprite());
  $i->setName('mouse');

  $m->add(new SWFAction("
    startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
  "));

  /* might as well turn off antialiasing, since these are just squares. */

  $m->add(new SWFAction("
    this.quality = 0;
  "));

  /* morphing box */
  $r = new SWFMorph();
  $s = $r->getShape1();

  /* Note this is backwards from normal shapes.  No idea why. */
  $s->setLeftFill($s->addFill(0xff, 0xff, 0xff));
  $s->movePenTo(-40, -40);
  $s->drawLine(80, 0);
  $s->drawLine(0, 80);
  $s->drawLine(-80, 0);
  $s->drawLine(0, -80);

  $s = $r->getShape2();

  $s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
  $s->movePenTo(-1, -1);
  $s->drawLine(2, 0);
  $s->drawLine(0, 2);
  $s->drawLine(-2, 0);
  $s->drawLine(0, -2);

  /* sprite container for morphing box -
     this is just a timeline w/ the box morphing */

  $box = new SWFSprite();
  $box->add(new SWFAction("
    stop();
  "));
  $i = $box->add($r);

  for ($n=0; $n<=20; ++$n) {
    $i->setRatio($n/20);
    $box->nextFrame();
  }

  /* this container sprite allows us to use the same action code many times */

  $cell = new SWFSprite();
  $i = $cell->add($box);
  $i->setName('box');

  $cell->add(new SWFAction("

    setTarget('box');

    /* ...x means the x coordinate of the parent, i.e. (..).x */
    dx = (/mouse.x + random(6)-3 - ...x)/5;
    dy = (/mouse.y + random(6)-3 - ...y)/5;
    gotoFrame(int(dx*dx + dy*dy));

  "));

  $cell->nextFrame();
  $cell->add(new SWFAction("

    gotoFrame(0);
    play();

  "));

  $cell->nextFrame();

  /* finally, add a bunch of the cells to the movie */

  for ($x=0; $x<12; ++$x) {
    for ($y=0; $y<8; ++$y) {
      $i = $m->add($cell);
      $i->moveTo(100*$x+50, 100*$y+50);
    }
  }

  $m->nextFrame();

  $m->add(new SWFAction("

    gotoFrame(1);
    play();

  "));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Same as above, but with nice colored balls...

Przykład #3 swfaction() example

<?php

  $m = new SWFMovie();
  $m->setDimension(11000, 8000);
  $m->setBackground(0x00, 0x00, 0x00);

  $m->add(new SWFAction("

this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);

  "));

  // mouse tracking sprite
  $t = new SWFSprite();
  $i = $m->add($t);
  $i->setName('mouse');

  $g = new SWFGradient();
  $g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
  $g->addEntry(1.0, 0xff, 0xff, 0xff, 0);

  // gradient shape thing
  $s = new SWFShape();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.03);
  $s->setRightFill($f);
  $s->movePenTo(-600, -600);
  $s->drawLine(1200, 0);
  $s->drawLine(0, 1200);
  $s->drawLine(-1200, 0);
  $s->drawLine(0, -1200);

  // need to make this a sprite so we can multColor it
  $p = new SWFSprite();
  $p->add($s);
  $p->nextFrame();

  // put the shape in here, each frame a different color
  $q = new SWFSprite();
  $q->add(new SWFAction("gotoFrame(random(7)+1); stop();"));
  $i = $q->add($p);

  $i->multColor(1.0, 1.0, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 0.75, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 0.5, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 1.0);
  $q->nextFrame();

  // finally, this one contains the action code
  $p = new SWFSprite();
  $i = $p->add($q);
  $i->setName('frames');
  $p->add(new SWFAction("

dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("

this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("prevFrame(); play();"));
  $p->nextFrame();

  $i = $m->add($p);
  $i->setName('frames');
  $m->nextFrame();

  $m->add(new SWFAction("

lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;

++num;

if (num == 11)
  num = 1;

removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num);

  "));

  $m->nextFrame();
  $m->add(new SWFAction("prevFrame(); play();"));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Przykłady
SWFSPrite basic examples
Przykłady


SWFSPrite basic examples

This simple example will spin gracefully a big red square.

Przykład #1 swfsprite() example

<?php
$s = new SWFShape();
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(-500, -500);
$s->drawLineTo(500, -500);
$s->drawLineTo(500, 500);
$s->drawLineTo(-500, 500);
$s->drawLineTo(-500, -500);

$p = new SWFSprite();
$i = $p->add($s);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();

$m = new SWFMovie();
$i = $m->add($p);
$i->moveTo(1500, 1000);
$i->setName("blah");

$m->setBackground(0xff, 0xff, 0xff);
$m->setDimension(3000, 2000);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFAction Examples
Ming Funkcje
Przykłady


Ming Funkcje

Spis treści

  • ming_keypress — Returns the action flag for keyPress(char)
  • ming_setcubicthreshold — Set cubic threshold
  • ming_setscale — Set the global scaling factor.
  • ming_setswfcompression — Sets the SWF output compression
  • ming_useconstants — Use constant pool
  • ming_useswfversion — Sets the SWF version
SWFSPrite basic examples
ming_keypress
Ming


Returns the action flag for keyPress(char)

Ming Funkcje
ming_setcubicthreshold
Ming Funkcje
PHP Manual

ming_keypress

(PHP 5 <= 5.3.0, PECL ming SVN)

ming_keypress — Returns the action flag for keyPress(char)

Opis

int ming_keypress ( string $char )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Ming Funkcje
ming_setcubicthreshold
Ming Funkcje


Set cubic threshold

ming_keypress
ming_setscale
Ming Funkcje
PHP Manual

ming_setcubicthreshold

(PHP 4 >= 4.0.5, PHP 5, PECL ming SVN)

ming_setcubicthreshold — Set cubic threshold

Opis

void ming_setcubicthreshold ( int $threshold )

Sets the threshold error for drawing cubic beziers.

Parametry

threshold

The Threshold. Lower is more accurate, hence larger file size.

Zwracane wartości

Nie jest zwracana żadna wartość.

ming_keypress
ming_setscale
Ming Funkcje


Set the global scaling factor.

ming_setcubicthreshold
ming_setswfcompression
Ming Funkcje
PHP Manual

ming_setscale

(PHP 4 >= 4.0.5, PHP 5, PECL ming SVN)

ming_setscale — Set the global scaling factor.

Opis

void ming_setscale ( float $scale )

Sets the scale of the output SWF. Inside the SWF file, coordinates are measured in TWIPS, rather than PIXELS. There are 20 TWIPS in 1 pixel.

Parametry

scale

The scale to be set.

Zwracane wartości

Nie jest zwracana żadna wartość.

ming_setcubicthreshold
ming_setswfcompression
Ming Funkcje


Sets the SWF output compression

ming_setscale
ming_useconstants
Ming Funkcje
PHP Manual

ming_setswfcompression

(PHP 5.2.1-5.3.0, PECL ming SVN)

ming_setswfcompression — Sets the SWF output compression

Opis

void ming_setswfcompression ( int $level )

Sets the SWF output compression level.

Parametry

level

The new compression level. Should be a value between 1 and 9 inclusive.

Zwracane wartości

Nie jest zwracana żadna wartość.

ming_setscale
ming_useconstants
Ming Funkcje


Use constant pool

ming_setswfcompression
ming_useswfversion
Ming Funkcje
PHP Manual

ming_useconstants

(PHP 5 <= 5.3.0, PECL ming SVN)

ming_useconstants — Use constant pool

Opis

void ming_useconstants ( int $use )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

ming_setswfcompression
ming_useswfversion
Ming Funkcje


Sets the SWF version

ming_useconstants
SWFAction
Ming Funkcje
PHP Manual

ming_useswfversion

(PHP 4 >= 4.2.0, PHP 5 <= 5.3.0, PECL ming SVN)

ming_useswfversion — Sets the SWF version

Opis

void ming_useswfversion ( int $version )

Sets the SWF version to be used in the movie. This affect the bahaviour of Action Script.

Parametry

version

SWF version to use.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ming_useswfversion() example

<?php

$movie = new SWFMovie();
ming_useswfversion(4); // Flash 4

?>

ming_useconstants
SWFAction
Ming Funkcje


The SWFAction class

(No version information available, might only be in SVN)

Wstęp

SWFAction.

Krótki opis klasy

SWFAction {
/* Metody */
__construct ( string $script )
}

Opis

The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.

So what's left? The compiler recognises the following tokens:

  • break
  • for
  • continue
  • if
  • else
  • do
  • while

There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:

time()
Returns the number of milliseconds (?) elapsed since the movie started.
random(seed)
Returns a pseudo-random number in the range 0-seed.
length(expr)
Returns the length of the given expression.
int(number)
Returns the given number rounded down to the nearest integer.
concat(expr, expr)
Returns the concatenation of the given expressions.
ord(expr)
Returns the ASCII code for the given character
chr(num)
Returns the character for the given ASCII code
substr(string, location, length)
Returns the substring of length length at location location of the given string string.

Additionally, the following commands may be used:

duplicateClip(clip, name, depth)
Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.
removeClip(expr)
Removes the named movie clip.
trace(expr)
Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.
startDrag(target, lock, [left, top, right, bottom])
Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.
stopDrag()
Stop dragging my heart around. And this movie clip, too.
callFrame(expr)
Call the named frame as a function.
getURL(url, target, [method])
Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.
loadMovie(url, target)
Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).
nextFrame()
Go to the next frame.
prevFrame()
Go to the last (or, rather, previous) frame.
play()
Start playing the movie.
stop()
Stop playing the movie.
toggleQuality()
Toggle between high and low quality.
stopSounds()
Stop playing all sounds.
gotoFrame(num)
Go to frame number num. Frame numbers start at 0.
gotoFrame(name)
Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.
setTarget(expr)
Sets the context for action. Or so they say- I really have no idea what this does.
And there's one weird extra thing. The expression frameLoaded(num) can be used in if statements and while loops to check if the given frame number has been loaded yet. Well, it's supposed to, anyway, but I've never tested it and I seriously doubt it actually works. You can just use /:framesLoaded instead.

Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:

  • x
  • y
  • xScale
  • yScale
  • currentFrame - (read-only)
  • totalFrames - (read-only)
  • alpha - transparency level
  • visible - 1=on, 0=off (?)
  • width - (read-only)
  • height - (read-only)
  • rotation
  • target - (read-only) (???)
  • framesLoaded - (read-only)
  • name
  • dropTarget - (read-only) (???)
  • url - (read-only) (???)
  • highQuality - 1=high, 0=low (?)
  • focusRect - (???)
  • soundBufTime - (???)
So, setting a sprite's x position is as simple as /box.x = 100;. Why the slash in front of the box, though? That's how flash keeps track of the sprites in the movie, just like a Unix filesystem- here it shows that box is at the top level. If the sprite named box had another sprite named biff inside of it, you'd set its x position with /box/biff.x = 100;. At least, I think so; correct me if I'm wrong here.

Spis treści

  • SWFAction::__construct — Creates a new SWFAction
ming_useswfversion
SWFAction::__construct
Ming


Creates a new SWFAction

SWFAction
SWFBitmap
SWFAction
PHP Manual

SWFAction::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFAction::__construct — Creates a new SWFAction

Opis

SWFAction::__construct ( string $script )
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 SWFAction and compiles the given script in it.

Parametry

script

An ActionScript snippet to associate with the SWFAction. See SWFAction for more details.

SWFAction
SWFBitmap
SWFAction


The SWFBitmap class

(No version information available, might only be in SVN)

Wstęp

SWFBitmap.

Krótki opis klasy

SWFBitmap {
/* Metody */
__construct ( mixed $file [, mixed $alphafile ] )
float getHeight ( void )
float getWidth ( void )
}

Spis treści

  • SWFBitmap::__construct — Loads Bitmap object
  • SWFBitmap::getHeight — Returns the bitmap's height
  • SWFBitmap::getWidth — Returns the bitmap's width
SWFAction::__construct
SWFBitmap::__construct
Ming


Loads Bitmap object

SWFBitmap
SWFBitmap::getHeight
SWFBitmap
PHP Manual

SWFBitmap::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFBitmap::__construct — Loads Bitmap object

Opis

SWFBitmap::__construct ( mixed $file [, mixed $alphafile ] )
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 the new SWFBitmap object from the given file.

Parametry

For both parameters you can provide a file pointer returned by fopen() or the image data, as a binary string.

file

Informacja:

We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!

You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.

alphafile

An MSK file to be used as an alpha mask for a JPEG image.

Przykłady

Przykład #1 Importing a DBL file

<?php
$s = new SWFShape();
$f = $s->addFill(new SWFBitmap(file_get_contents("image.dbl")));
$s->setRightFill($f);

$s->drawLine(32, 0);
$s->drawLine(0, 32);
$s->drawLine(-32, 0);
$s->drawLine(0, -32);

$m = new SWFMovie();
$m->setDimension(32, 32);
$m->add($s);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Przykład #2 Using an alpha mask

<?php

$s = new SWFShape();

// .msk file generated with "gif2mask" utility
$f = $s->addFill(new SWFBitmap(file_get_contents("alphafill.jpg"), file_get_contents("alphafill.msk")));
$s->setRightFill($f);

$s->drawLine(640, 0);
$s->drawLine(0, 480);
$s->drawLine(-640, 0);
$s->drawLine(0, -480);

$c = new SWFShape();
$c->setRightFill($c->addFill(0x99, 0x99, 0x99));
$c->drawLine(40, 0);
$c->drawLine(0, 40);
$c->drawLine(-40, 0);
$c->drawLine(0, -40);

$m = new SWFMovie();
$m->setDimension(640, 480);
$m->setBackground(0xcc, 0xcc, 0xcc);

// draw checkerboard background
for ($y=0; $y<480; $y+=40) {
  for ($x=0; $x<640; $x+=80) {
    $i = $m->add($c);
    $i->moveTo($x, $y);
  }

  $y+=40;

  for ($x=40; $x<640; $x+=80) {
    $i = $m->add($c);
    $i->moveTo($x, $y);
  }
}

$m->add($s);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFBitmap
SWFBitmap::getHeight
SWFBitmap


Returns the bitmap's height

SWFBitmap::__construct
SWFBitmap::getWidth
SWFBitmap
PHP Manual

SWFBitmap::getHeight

(PHP 4 >= 4.0.5)

SWFBitmap::getHeight — Returns the bitmap's height

Opis

float SWFBitmap::getHeight ( 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 bitmap's height.

Zwracane wartości

Returns the bitmap height in pixels.

Zobacz też:

  • SWFBitmap::getWidth() - Returns the bitmap's width

SWFBitmap::__construct
SWFBitmap::getWidth
SWFBitmap


Returns the bitmap's width

SWFBitmap::getHeight
SWFButton
SWFBitmap
PHP Manual

SWFBitmap::getWidth

(PHP 4 >= 4.0.5)

SWFBitmap::getWidth — Returns the bitmap's width

Opis

float SWFBitmap::getWidth ( 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 bitmap's width.

Zwracane wartości

Returns the bitmap width in pixels.

Zobacz też:

  • SWFBitmap::getHeight() - Returns the bitmap's height

SWFBitmap::getHeight
SWFButton
SWFBitmap


The SWFButton class

(No version information available, might only be in SVN)

Wstęp

SWFButton.

Krótki opis klasy

SWFButton {
/* Metody */
void addAction ( SWFAction $action , int $flags )
SWFSoundInstance addASound ( SWFSound $sound , int $flags )
void addShape ( SWFShape $shape , int $flags )
__construct ( void )
void setAction ( SWFAction $action )
void setDown ( SWFShape $shape )
void setHit ( SWFShape $shape )
void setMenu ( int $flag )
void setOver ( SWFShape $shape )
void setUp ( SWFShape $shape )
}

Spis treści

  • SWFButton::addAction — Adds an action
  • SWFButton::addASound — Associates a sound with a button transition
  • SWFButton::addShape — Adds a shape to a button
  • SWFButton::__construct — Creates a new Button
  • SWFButton::setAction — Sets the action
  • SWFButton::setDown — Alias for addShape(shape, SWFBUTTON_DOWN)
  • SWFButton::setHit — Alias for addShape(shape, SWFBUTTON_HIT)
  • SWFButton::setMenu — enable track as menu button behaviour
  • SWFButton::setOver — Alias for addShape(shape, SWFBUTTON_OVER)
  • SWFButton::setUp — Alias for addShape(shape, SWFBUTTON_UP)
SWFBitmap::getWidth
SWFButton::addAction
Ming


Adds an action

SWFButton
SWFButton::addASound
SWFButton
PHP Manual

SWFButton::addAction

(PHP 4 >= 4.0.5)

SWFButton::addAction — Adds an action

Opis

void SWFButton::addAction ( SWFAction $action , int $flags )
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.

Adds the given action to the button for the given conditions.

Parametry

action

An SWFAction, returned by SWFAction::__construct().

flags

The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

SWFButton
SWFButton::addASound
SWFButton


Associates a sound with a button transition

SWFButton::addAction
SWFButton::addShape
SWFButton
PHP Manual

SWFButton::addASound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::addASound — Associates a sound with a button transition

Opis

SWFSoundInstance SWFButton::addASound ( SWFSound $sound , int $flags )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

SWFButton::addAction
SWFButton::addShape
SWFButton


Adds a shape to a button

SWFButton::addASound
SWFButton::__construct
SWFButton
PHP Manual

SWFButton::addShape

(PHP 4 >= 4.0.5)

SWFButton::addShape — Adds a shape to a button

Opis

void SWFButton::addShape ( SWFShape $shape , int $flags )
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.

Adds the given shape to the button.

Parametry

shape

An SWFShape instance

flags

The following flags are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN and SWFBUTTON_HIT.

SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFButton::addASound
SWFButton::__construct
SWFButton


Creates a new Button

SWFButton::addShape
SWFButton::setAction
SWFButton
PHP Manual

SWFButton::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::__construct — Creates a new Button

Opis

SWFButton::__construct ( 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.

Creates a new Button.

Przykłady

This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.

Przykład #1 Usual interactions with buttons

<?php

$f = new SWFFont("_serif");

$p = new SWFSprite();

function label($string)
{
  global $f;

  $t = new SWFTextField();
  $t->setFont($f);
  $t->addString($string);
  $t->setHeight(200);
  $t->setBounds(3200, 200);
  return $t;
}

function addLabel($string)
{
  global $p;

  $i = $p->add(label($string));
  $p->nextFrame();
  $p->remove($i);
}

$p->add(new SWFAction("stop();"));
addLabel("NO ACTION");
addLabel("SWFBUTTON_MOUSEUP");
addLabel("SWFBUTTON_MOUSEDOWN");
addLabel("SWFBUTTON_MOUSEOVER");
addLabel("SWFBUTTON_MOUSEOUT");
addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
addLabel("SWFBUTTON_DRAGOVER");
addLabel("SWFBUTTON_DRAGOUT");

function rect($r, $g, $b)
{
  $s = new SWFShape();
  $s->setRightFill($s->addFill($r, $g, $b));
  $s->drawLine(600, 0);
  $s->drawLine(0, 600);
  $s->drawLine(-600, 0);
  $s->drawLine(0, -600);

  return $s;
}

$b = new SWFButton();
$b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
$b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
$b->addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
          SWFBUTTON_MOUSEUP);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
      SWFBUTTON_MOUSEDOWN);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
      SWFBUTTON_MOUSEOVER);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
      SWFBUTTON_MOUSEOUT);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
      SWFBUTTON_MOUSEUPOUTSIDE);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
      SWFBUTTON_DRAGOVER);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
      SWFBUTTON_DRAGOUT);

$m = new SWFMovie();
$m->setDimension(4000, 3000);

$i = $m->add($p);
$i->setName("label");
$i->moveTo(400, 1900);

$i = $m->add($b);
$i->moveTo(400, 900);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.

Przykład #2 Drag example

<?php

$s = new SWFShape();
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->drawLine(1000,0);
$s->drawLine(0,1000);
$s->drawLine(-1000,0);
$s->drawLine(0,-1000);

$b = new SWFButton();
$b->addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);

$b->addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
      SWFBUTTON_MOUSEDOWN);

$b->addAction(new SWFAction("stopDrag();"),
      SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);

$p = new SWFSprite();
$p->add($b);
$p->nextFrame();

$m = new SWFMovie();
$i = $m->add($p);
$i->setName('test');
$i->moveTo(1000,1000);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFButton::addShape
SWFButton::setAction
SWFButton


Sets the action

SWFButton::__construct
SWFButton::setDown
SWFButton
PHP Manual

SWFButton::setAction

(PHP 4 >= 4.0.5)

SWFButton::setAction — Sets the action

Opis

void SWFButton::setAction ( SWFAction $action )
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 the action to be performed when the button is clicked.

This is a shortcut for SWFButton::addAction() called with the SWFBUTTON_MOUSEUP flag.

Parametry

action

An SWFAction, returned by SWFAction::__construct().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFButton::addAction() - Adds an action
  • SWFAction

SWFButton::__construct
SWFButton::setDown
SWFButton


Alias for addShape(shape, SWFBUTTON_DOWN)

SWFButton::setAction
SWFButton::setHit
SWFButton
PHP Manual

SWFButton::setDown

(PHP 4 >= 4.0.5)

SWFButton::setDown — Alias for addShape(shape, SWFBUTTON_DOWN)

Opis

void SWFButton::setDown ( SWFShape $shape )
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.

swfbutton::setdown() alias for addShape(shape, SWFBUTTON_DOWN).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

SWFButton::setAction
SWFButton::setHit
SWFButton


Alias for addShape(shape, SWFBUTTON_HIT)

SWFButton::setDown
SWFButton::setMenu
SWFButton
PHP Manual

SWFButton::setHit

(PHP 4 >= 4.0.5)

SWFButton::setHit — Alias for addShape(shape, SWFBUTTON_HIT)

Opis

void SWFButton::setHit ( SWFShape $shape )
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.

swfbutton::sethit() alias for addShape(shape, SWFBUTTON_HIT).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

SWFButton::setDown
SWFButton::setMenu
SWFButton


enable track as menu button behaviour

SWFButton::setHit
SWFButton::setOver
SWFButton
PHP Manual

SWFButton::setMenu

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFButton::setMenu — enable track as menu button behaviour

Opis

void SWFButton::setMenu ( int $flag )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flag

This parameter can be used for a slight different behavior of buttons. You can set it to 0 (off) or 1 (on).

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFButton::setHit
SWFButton::setOver
SWFButton


Alias for addShape(shape, SWFBUTTON_OVER)

SWFButton::setMenu
SWFButton::setUp
SWFButton
PHP Manual

SWFButton::setOver

(PHP 4 >= 4.0.5)

SWFButton::setOver — Alias for addShape(shape, SWFBUTTON_OVER)

Opis

void SWFButton::setOver ( SWFShape $shape )
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.

swfbutton::setover() alias for addShape(shape, SWFBUTTON_OVER).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

SWFButton::setMenu
SWFButton::setUp
SWFButton


Alias for addShape(shape, SWFBUTTON_UP)

SWFButton::setOver
SWFDisplayItem
SWFButton
PHP Manual

SWFButton::setUp

(PHP 4 >= 4.0.5)

SWFButton::setUp — Alias for addShape(shape, SWFBUTTON_UP)

Opis

void SWFButton::setUp ( SWFShape $shape )
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.

swfbutton::setup() alias for addShape(shape, SWFBUTTON_UP).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction

SWFButton::setOver
SWFDisplayItem
SWFButton


The SWFDisplayItem class

(No version information available, might only be in SVN)

Wstęp

SWFDisplayItem.

Krótki opis klasy

SWFDisplayItem {
/* Metody */
void addAction ( SWFAction $action , int $flags )
void addColor ( int $red , int $green , int $blue [, int $a ] )
void endMask ( void )
float getRot ( void )
float getX ( void )
float getXScale ( void )
float getXSkew ( void )
float getY ( void )
float getYScale ( void )
float getYSkew ( void )
void move ( float $dx , float $dy )
void moveTo ( float $x , float $y )
void multColor ( float $red , float $green , float $blue [, float $a ] )
void remove ( void )
void rotate ( float $angle )
void rotateTo ( float $angle )
void scale ( float $dx , float $dy )
void scaleTo ( float $x [, float $y ] )
void setDepth ( int $depth )
void setMaskLevel ( int $level )
void setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
void setName ( string $name )
void setRatio ( float $ratio )
void skewX ( float $ddegrees )
void skewXTo ( float $degrees )
void skewY ( float $ddegrees )
void skewYTo ( float $degrees )
}

Spis treści

  • SWFDisplayItem::addAction — Adds this SWFAction to the given SWFSprite instance
  • SWFDisplayItem::addColor — Adds the given color to this item's color transform
  • SWFDisplayItem::endMask — Another way of defining a MASK layer
  • SWFDisplayItem::getRot — Opis
  • SWFDisplayItem::getX — Opis
  • SWFDisplayItem::getXScale — Opis
  • SWFDisplayItem::getXSkew — Opis
  • SWFDisplayItem::getY — Opis
  • SWFDisplayItem::getYScale — Opis
  • SWFDisplayItem::getYSkew — Opis
  • SWFDisplayItem::move — Moves object in relative coordinates
  • SWFDisplayItem::moveTo — Moves object in global coordinates
  • SWFDisplayItem::multColor — Multiplies the item's color transform
  • SWFDisplayItem::remove — Removes the object from the movie
  • SWFDisplayItem::rotate — Rotates in relative coordinates
  • SWFDisplayItem::rotateTo — Rotates the object in global coordinates
  • SWFDisplayItem::scale — Scales the object in relative coordinates
  • SWFDisplayItem::scaleTo — Scales the object in global coordinates
  • SWFDisplayItem::setDepth — Sets z-order
  • SWFDisplayItem::setMaskLevel — Defines a MASK layer at level
  • SWFDisplayItem::setMatrix — Sets the item's transform matrix
  • SWFDisplayItem::setName — Sets the object's name
  • SWFDisplayItem::setRatio — Sets the object's ratio
  • SWFDisplayItem::skewX — Sets the X-skew
  • SWFDisplayItem::skewXTo — Sets the X-skew
  • SWFDisplayItem::skewY — Sets the Y-skew
  • SWFDisplayItem::skewYTo — Sets the Y-skew
SWFButton::setUp
SWFDisplayItem::addAction
Ming


Adds this SWFAction to the given SWFSprite instance

SWFDisplayItem
SWFDisplayItem::addColor
SWFDisplayItem
PHP Manual

SWFDisplayItem::addAction

(PHP 4 >= 4.2.0)

SWFDisplayItem::addAction — Adds this SWFAction to the given SWFSprite instance

Opis

void SWFDisplayItem::addAction ( SWFAction $action , int $flags )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

action

An SWFAction, returned by SWFAction::__construct().

flags

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFAction

SWFDisplayItem
SWFDisplayItem::addColor
SWFDisplayItem


Adds the given color to this item's color transform

SWFDisplayItem::addAction
SWFDisplayItem::endMask
SWFDisplayItem
PHP Manual

SWFDisplayItem::addColor

(PHP 4 >= 4.0.5)

SWFDisplayItem::addColor — Adds the given color to this item's color transform

Opis

void SWFDisplayItem::addColor ( int $red , int $green , int $blue [, int $a ] )
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.

swfdisplayitem::addcolor() adds the color to this item's color transform. The color is given in its RGB form.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFDisplayItem::addAction
SWFDisplayItem::endMask
SWFDisplayItem


Another way of defining a MASK layer

SWFDisplayItem::addColor
SWFDisplayItem::getRot
SWFDisplayItem
PHP Manual

SWFDisplayItem::endMask

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::endMask — Another way of defining a MASK layer

Opis

void SWFDisplayItem::endMask ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFDisplayItem::addColor
SWFDisplayItem::getRot
SWFDisplayItem


SWFDisplayItem::endMask
SWFDisplayItem::getX
SWFDisplayItem
PHP Manual

SWFDisplayItem::getRot

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getRot —

Opis

float SWFDisplayItem::getRot ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

SWFDisplayItem::endMask
SWFDisplayItem::getX
SWFDisplayItem


SWFDisplayItem::getRot
SWFDisplayItem::getXScale
SWFDisplayItem
PHP Manual

SWFDisplayItem::getX

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getX —

Opis

float SWFDisplayItem::getX ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFDisplayItem::getY() - Opis

SWFDisplayItem::getRot
SWFDisplayItem::getXScale
SWFDisplayItem


SWFDisplayItem::getX
SWFDisplayItem::getXSkew
SWFDisplayItem
PHP Manual

SWFDisplayItem::getXScale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getXScale —

Opis

float SWFDisplayItem::getXScale ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFDisplayItem::getYScale() - Opis

SWFDisplayItem::getX
SWFDisplayItem::getXSkew
SWFDisplayItem


SWFDisplayItem::getXScale
SWFDisplayItem::getY
SWFDisplayItem
PHP Manual

SWFDisplayItem::getXSkew

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getXSkew —

Opis

float SWFDisplayItem::getXSkew ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFDisplayItem::getYSkew() - Opis

SWFDisplayItem::getXScale
SWFDisplayItem::getY
SWFDisplayItem


SWFDisplayItem::getXSkew
SWFDisplayItem::getYScale
SWFDisplayItem
PHP Manual

SWFDisplayItem::getY

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getY —

Opis

float SWFDisplayItem::getY ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFDisplayItem::getX() - Opis

SWFDisplayItem::getXSkew
SWFDisplayItem::getYScale
SWFDisplayItem


SWFDisplayItem::getY
SWFDisplayItem::getYSkew
SWFDisplayItem
PHP Manual

SWFDisplayItem::getYScale

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getYScale —

Opis

float SWFDisplayItem::getYScale ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFDisplayItem::getXScale() - Opis

SWFDisplayItem::getY
SWFDisplayItem::getYSkew
SWFDisplayItem


SWFDisplayItem::getYScale
SWFDisplayItem::move
SWFDisplayItem
PHP Manual

SWFDisplayItem::getYSkew

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::getYSkew —

Opis

float SWFDisplayItem::getYSkew ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFDisplayItem::getXSkew() - Opis

SWFDisplayItem::getYScale
SWFDisplayItem::move
SWFDisplayItem


Moves object in relative coordinates

SWFDisplayItem::getYSkew
SWFDisplayItem::moveTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::move

(PHP 4 >= 4.0.5)

SWFDisplayItem::move — Moves object in relative coordinates

Opis

void SWFDisplayItem::move ( float $dx , float $dy )
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.

swfdisplayitem::move() moves the current object by (dx,dy) from its current position.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::moveTo() - Moves object in global coordinates

SWFDisplayItem::getYSkew
SWFDisplayItem::moveTo
SWFDisplayItem


Moves object in global coordinates

SWFDisplayItem::move
SWFDisplayItem::multColor
SWFDisplayItem
PHP Manual

SWFDisplayItem::moveTo

(PHP 4 >= 4.0.5)

SWFDisplayItem::moveTo — Moves object in global coordinates

Opis

void SWFDisplayItem::moveTo ( float $x , float $y )
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.

swfdisplayitem::moveto() moves the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::move() - Moves object in relative coordinates

SWFDisplayItem::move
SWFDisplayItem::multColor
SWFDisplayItem


Multiplies the item's color transform

SWFDisplayItem::moveTo
SWFDisplayItem::remove
SWFDisplayItem
PHP Manual

SWFDisplayItem::multColor

(PHP 4 >= 4.0.5)

SWFDisplayItem::multColor — Multiplies the item's color transform

Opis

void SWFDisplayItem::multColor ( float $red , float $green , float $blue [, float $a ] )
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.

swfdisplayitem::multcolor() multiplies the item's color transform by the given values.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Parametry

These parameters are floats between 0.0 and 1.0:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

This simple example will modify your picture's atmosphere to Halloween (use a landscape or bright picture).

Przykład #1 swfdisplayitem::multcolor() example

<?php

$b = new SWFBitmap(file_get_contents("backyard.jpg"));
// note use your own picture :-)
$s = new SWFShape();
$s->setRightFill($s->addFill($b));
$s->drawLine($b->getWidth(), 0);
$s->drawLine(0, $b->getHeight());
$s->drawLine(-$b->getWidth(), 0);
$s->drawLine(0, -$b->getHeight());

$m = new SWFMovie();
$m->setDimension($b->getWidth(), $b->getHeight());

$i = $m->add($s);

for ($n=0; $n<=20; ++$n) {
  $i->multColor(1.0-$n/10, 1.0, 1.0);
  $i->addColor(0xff*$n/20, 0, 0);
  $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFDisplayItem::moveTo
SWFDisplayItem::remove
SWFDisplayItem


Removes the object from the movie

SWFDisplayItem::multColor
SWFDisplayItem::rotate
SWFDisplayItem
PHP Manual

SWFDisplayItem::remove

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::remove — Removes the object from the movie

Opis

void SWFDisplayItem::remove ( 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.

swfdisplayitem::remove() removes this object from the movie's display list.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFMovie::add() - Adds any type of data to a movie

SWFDisplayItem::multColor
SWFDisplayItem::rotate
SWFDisplayItem


Rotates in relative coordinates

SWFDisplayItem::remove
SWFDisplayItem::rotateTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::rotate

(PHP 4 >= 4.0.5)

SWFDisplayItem::rotate — Rotates in relative coordinates

Opis

void SWFDisplayItem::rotate ( float $angle )
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.

swfdisplayitem::rotate() rotates the current object by angle degrees from its current rotation.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::rotateTo() - Rotates the object in global coordinates

SWFDisplayItem::remove
SWFDisplayItem::rotateTo
SWFDisplayItem


Rotates the object in global coordinates

SWFDisplayItem::rotate
SWFDisplayItem::scale
SWFDisplayItem
PHP Manual

SWFDisplayItem::rotateTo

(PHP 4 >= 4.0.5)

SWFDisplayItem::rotateTo — Rotates the object in global coordinates

Opis

void SWFDisplayItem::rotateTo ( float $angle )
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.

swfdisplayitem::rotateto() set the current object rotation to angle degrees in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

This example bring three rotating string from the background to the foreground. Pretty nice.

Przykład #1 swfdisplayitem::rotateto() example

<?php
$thetext =  "ming!";

$f = new SWFFont("Bauhaus 93.fdb");

$m = new SWFMovie();
$m->setRate(24.0);
$m->setDimension(2400, 1600);
$m->setBackground(0xff, 0xff, 0xff);

// functions with huge numbers of arbitrary
// arguments are always a good idea!  Really!

function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string)
{
  global $f, $m;

  $t = new SWFText();
  $t->setFont($f);
  $t->setColor($r, $g, $b, $a);
  $t->setHeight(960);
  $t->moveTo(-($f->getWidth($string))/2, $f->getAscent()/2);
  $t->addString($string);

  // we can add properties just like a normal PHP var,
  // as long as the names aren't already used.
  // e.g., we can't set $i->scale, because that's a function

  $i = $m->add($t);
  $i->x = $x;
  $i->y = $y;
  $i->rot = $rot;
  $i->s = $scale;
  $i->rotateTo($rot);
  $i->scale($scale, $scale);

  // but the changes are local to the function, so we have to
  // return the changed object.  kinda weird..

  return $i;
}

function step($i)
{
  $oldrot = $i->rot;
  $i->rot = 19*$i->rot/20;
  $i->x = (19*$i->x + 1200)/20;
  $i->y = (19*$i->y + 800)/20;
  $i->s = (19*$i->s + 1.0)/20;

  $i->rotateTo($i->rot);
  $i->scaleTo($i->s, $i->s);
  $i->moveTo($i->x, $i->y);

  return $i;
}

// see?  it sure paid off in legibility:

$i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
$i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
$i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);

for ($i=1; $i<=100; ++$i) {
  $i1 = step($i1);
  $i2 = step($i2);
  $i3 = step($i3);

  $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Zobacz też:

  • SWFDisplayItem::rotate() - Rotates in relative coordinates

SWFDisplayItem::rotate
SWFDisplayItem::scale
SWFDisplayItem


Scales the object in relative coordinates

SWFDisplayItem::rotateTo
SWFDisplayItem::scaleTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::scale

(PHP 4 >= 4.0.5)

SWFDisplayItem::scale — Scales the object in relative coordinates

Opis

void SWFDisplayItem::scale ( float $dx , float $dy )
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.

swfdisplayitem::scale() scales the current object by (dx,dy) from its current size.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::scaleTo() - Scales the object in global coordinates

SWFDisplayItem::rotateTo
SWFDisplayItem::scaleTo
SWFDisplayItem


Scales the object in global coordinates

SWFDisplayItem::scale
SWFDisplayItem::setDepth
SWFDisplayItem
PHP Manual

SWFDisplayItem::scaleTo

(PHP 4 >= 4.0.5)

SWFDisplayItem::scaleTo — Scales the object in global coordinates

Opis

void SWFDisplayItem::scaleTo ( float $x [, float $y ] )
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.

swfdisplayitem::scaleto() scales the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::scale() - Scales the object in relative coordinates

SWFDisplayItem::scale
SWFDisplayItem::setDepth
SWFDisplayItem


Sets z-order

SWFDisplayItem::scaleTo
SWFDisplayItem::setMaskLevel
SWFDisplayItem
PHP Manual

SWFDisplayItem::setDepth

(PHP 4 >= 4.0.5)

SWFDisplayItem::setDepth — Sets z-order

Opis

void SWFDisplayItem::setDepth ( int $depth )
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.

swfdisplayitem::setdepth() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by adding a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the later-defined one can be moved.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFDisplayItem::scaleTo
SWFDisplayItem::setMaskLevel
SWFDisplayItem


Defines a MASK layer at level

SWFDisplayItem::setDepth
SWFDisplayItem::setMatrix
SWFDisplayItem
PHP Manual

SWFDisplayItem::setMaskLevel

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFDisplayItem::setMaskLevel — Defines a MASK layer at level

Opis

void SWFDisplayItem::setMaskLevel ( int $level )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFDisplayItem::setDepth
SWFDisplayItem::setMatrix
SWFDisplayItem


Sets the item's transform matrix

SWFDisplayItem::setMaskLevel
SWFDisplayItem::setName
SWFDisplayItem
PHP Manual

SWFDisplayItem::setMatrix

(PHP 4 >= 4.0.5)

SWFDisplayItem::setMatrix — Sets the item's transform matrix

Opis

void SWFDisplayItem::setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFDisplayItem::setMaskLevel
SWFDisplayItem::setName
SWFDisplayItem


Sets the object's name

SWFDisplayItem::setMatrix
SWFDisplayItem::setRatio
SWFDisplayItem
PHP Manual

SWFDisplayItem::setName

(PHP 4 >= 4.0.5)

SWFDisplayItem::setName — Sets the object's name

Opis

void SWFDisplayItem::setName ( string $name )
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.

swfdisplayitem::setname() sets the object's name to name, for targetting with action script. Only useful on sprites.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFDisplayItem::setMatrix
SWFDisplayItem::setRatio
SWFDisplayItem


Sets the object's ratio

SWFDisplayItem::setName
SWFDisplayItem::skewX
SWFDisplayItem
PHP Manual

SWFDisplayItem::setRatio

(PHP 4 >= 4.0.5)

SWFDisplayItem::setRatio — Sets the object's ratio

Opis

void SWFDisplayItem::setRatio ( float $ratio )
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.

swfdisplayitem::setratio() sets the object's ratio to ratio. Obviously only useful for morphs.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

This simple example will morph nicely three concentric circles.

Przykład #1 swfdisplayitem::setname() example

<?php

$p = new SWFMorph();

$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0xff, 0xff);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0xff, 0xff, 0xff);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0xff, 0xff, 0xff);
$g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape1();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);

$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0, 0);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0, 0xff, 0);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0, 0, 0xff);
$g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape2();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$f->skewXTo(1.0);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);

$m = new SWFMovie();
$m->setDimension(320, 240);
$i = $m->add($p);
$i->moveTo(160, 120);

for ($n=0; $n<=1.001; $n+=0.01) {
    $i->setRatio($n);
    $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFDisplayItem::setName
SWFDisplayItem::skewX
SWFDisplayItem


Sets the X-skew

SWFDisplayItem::setRatio
SWFDisplayItem::skewXTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::skewX

(PHP 4 >= 4.0.5)

SWFDisplayItem::skewX — Sets the X-skew

Opis

void SWFDisplayItem::skewX ( float $ddegrees )
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.

swfdisplayitem::skewx() adds ddegrees to current x-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::skewXTo() - Sets the X-skew
  • SWFDisplayItem::skewY() - Sets the Y-skew
  • SWFDisplayItem::skewYTo() - Sets the Y-skew

SWFDisplayItem::setRatio
SWFDisplayItem::skewXTo
SWFDisplayItem


Sets the X-skew

SWFDisplayItem::skewX
SWFDisplayItem::skewY
SWFDisplayItem
PHP Manual

SWFDisplayItem::skewXTo

(PHP 4 >= 4.0.5)

SWFDisplayItem::skewXTo — Sets the X-skew

Opis

void SWFDisplayItem::skewXTo ( float $degrees )
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.

swfdisplayitem::skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::skewX() - Sets the X-skew
  • SWFDisplayItem::skewY() - Sets the Y-skew
  • SWFDisplayItem::skewYTo() - Sets the Y-skew

SWFDisplayItem::skewX
SWFDisplayItem::skewY
SWFDisplayItem


Sets the Y-skew

SWFDisplayItem::skewXTo
SWFDisplayItem::skewYTo
SWFDisplayItem
PHP Manual

SWFDisplayItem::skewY

(PHP 4 >= 4.0.5)

SWFDisplayItem::skewY — Sets the Y-skew

Opis

void SWFDisplayItem::skewY ( float $ddegrees )
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.

swfdisplayitem::skewy() adds ddegrees to current y-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::skewYTo() - Sets the Y-skew
  • SWFDisplayItem::skewX() - Sets the X-skew
  • SWFDisplayItem::skewXTo() - Sets the X-skew

SWFDisplayItem::skewXTo
SWFDisplayItem::skewYTo
SWFDisplayItem


Sets the Y-skew

SWFDisplayItem::skewY
SWFFill
SWFDisplayItem
PHP Manual

SWFDisplayItem::skewYTo

(PHP 4 >= 4.0.5)

SWFDisplayItem::skewYTo — Sets the Y-skew

Opis

void SWFDisplayItem::skewYTo ( float $degrees )
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.

swfdisplayitem::skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFDisplayItem::skewY() - Sets the Y-skew
  • SWFDisplayItem::skewX() - Sets the X-skew
  • SWFDisplayItem::skewXTo() - Sets the X-skew

SWFDisplayItem::skewY
SWFFill
SWFDisplayItem


The SWFFill class

(No version information available, might only be in SVN)

Wstęp

The SWFFill object allows you to transform (scale, skew, rotate) bitmap and gradient fills.

swffill objects are created by the SWFShape::addFill() method.

Krótki opis klasy

SWFFill {
/* Metody */
void moveTo ( float $x , float $y )
void rotateTo ( float $angle )
void scaleTo ( float $x [, float $y ] )
void skewXTo ( float $x )
void skewYTo ( float $y )
}

Spis treści

  • SWFFill::moveTo — Moves fill origin
  • SWFFill::rotateTo — Sets fill's rotation
  • SWFFill::scaleTo — Sets fill's scale
  • SWFFill::skewXTo — Sets fill x-skew
  • SWFFill::skewYTo — Sets fill y-skew
SWFDisplayItem::skewYTo
SWFFill::moveTo
Ming


Moves fill origin

SWFFill
SWFFill::rotateTo
SWFFill
PHP Manual

SWFFill::moveTo

(PHP 4 >= 4.0.5)

SWFFill::moveTo — Moves fill origin

Opis

void SWFFill::moveTo ( float $x , float $y )
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.

Moves the fill origin to the given global coordinates.

Parametry

x

X-coordinate

y

Y-coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFFill
SWFFill::rotateTo
SWFFill


Sets fill's rotation

SWFFill::moveTo
SWFFill::scaleTo
SWFFill
PHP Manual

SWFFill::rotateTo

(PHP 4 >= 4.0.5)

SWFFill::rotateTo — Sets fill's rotation

Opis

void SWFFill::rotateTo ( float $angle )
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 the fill rotation to the given angle.

Parametry

angle

The rotation angle, in degrees.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFFill::moveTo
SWFFill::scaleTo
SWFFill


Sets fill's scale

SWFFill::rotateTo
SWFFill::skewXTo
SWFFill
PHP Manual

SWFFill::scaleTo

(PHP 4 >= 4.0.5)

SWFFill::scaleTo — Sets fill's scale

Opis

void SWFFill::scaleTo ( float $x [, float $y ] )
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 the fill scale to the given coordinates.

Parametry

x

X-coordinate

y

Y-coordinate

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFFill::rotateTo
SWFFill::skewXTo
SWFFill


Sets fill x-skew

SWFFill::scaleTo
SWFFill::skewYTo
SWFFill
PHP Manual

SWFFill::skewXTo

(PHP 4 >= 4.0.5)

SWFFill::skewXTo — Sets fill x-skew

Opis

void SWFFill::skewXTo ( float $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.

Sets the fill x-skew to x.

Parametry

x

When x is 1.0, it is a 45-degree forward slant. More is more forward, less is more backward.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFFill::skewYTo() - Sets fill y-skew

SWFFill::scaleTo
SWFFill::skewYTo
SWFFill


Sets fill y-skew

SWFFill::skewXTo
SWFFont
SWFFill
PHP Manual

SWFFill::skewYTo

(PHP 4 >= 4.0.5)

SWFFill::skewYTo — Sets fill y-skew

Opis

void SWFFill::skewYTo ( float $y )
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 the fill y-skew to y.

Parametry

y

When y is 1.0, it is a 45-degree upward slant. More is more upward, less is more downward.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFFill::skewXTo() - Sets fill x-skew

SWFFill::skewXTo
SWFFont
SWFFill


The SWFFont class

(No version information available, might only be in SVN)

Wstęp

The SWFFont object represent a reference to the font definition, for us with SWFText::setFont() and SWFTextField::setFont().

Krótki opis klasy

SWFFont {
/* Metody */
__construct ( string $filename )
float getAscent ( void )
float getDescent ( void )
float getLeading ( void )
string getShape ( int $code )
float getUTF8Width ( string $string )
float getWidth ( string $string )
}

Spis treści

  • SWFFont::__construct — Loads a font definition
  • SWFFont::getAscent — Returns the ascent of the font, or 0 if not available
  • SWFFont::getDescent — Returns the descent of the font, or 0 if not available
  • SWFFont::getLeading — Returns the leading of the font, or 0 if not available
  • SWFFont::getShape — Returns the glyph shape of a char as a text string
  • SWFFont::getUTF8Width — Calculates the width of the given string in this font at full height
  • SWFFont::getWidth — Returns the string's width
SWFFill::skewYTo
SWFFont::__construct
Ming


Loads a font definition

SWFFont
SWFFont::getAscent
SWFFont
PHP Manual

SWFFont::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::__construct — Loads a font definition

Opis

SWFFont::__construct ( 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.

If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.

FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.

Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:

<?php
$f = newSWFFont("_sans");
?>
will give you the standard sans-serif font, probably the same as what you'd get with <font name="sans-serif"> in HTML.

SWFFont
SWFFont::getAscent
SWFFont


Returns the ascent of the font, or 0 if not available

SWFFont::__construct
SWFFont::getDescent
SWFFont
PHP Manual

SWFFont::getAscent

(PHP 4 >= 4.0.5)

SWFFont::getAscent — Returns the ascent of the font, or 0 if not available

Opis

float SWFFont::getAscent ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFFont::getDescent() - Returns the descent of the font, or 0 if not available

SWFFont::__construct
SWFFont::getDescent
SWFFont


Returns the descent of the font, or 0 if not available

SWFFont::getAscent
SWFFont::getLeading
SWFFont
PHP Manual

SWFFont::getDescent

(PHP 4 >= 4.0.5)

SWFFont::getDescent — Returns the descent of the font, or 0 if not available

Opis

float SWFFont::getDescent ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFFont::getAscent() - Returns the ascent of the font, or 0 if not available

SWFFont::getAscent
SWFFont::getLeading
SWFFont


Returns the leading of the font, or 0 if not available

SWFFont::getDescent
SWFFont::getShape
SWFFont
PHP Manual

SWFFont::getLeading

(PHP 4 >= 4.0.5)

SWFFont::getLeading — Returns the leading of the font, or 0 if not available

Opis

float SWFFont::getLeading ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

SWFFont::getDescent
SWFFont::getShape
SWFFont


Returns the glyph shape of a char as a text string

SWFFont::getLeading
SWFFont::getUTF8Width
SWFFont
PHP Manual

SWFFont::getShape

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::getShape — Returns the glyph shape of a char as a text string

Opis

string SWFFont::getShape ( int $code )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

SWFFont::getLeading
SWFFont::getUTF8Width
SWFFont


Calculates the width of the given string in this font at full height

SWFFont::getShape
SWFFont::getWidth
SWFFont
PHP Manual

SWFFont::getUTF8Width

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFont::getUTF8Width — Calculates the width of the given string in this font at full height

Opis

float SWFFont::getUTF8Width ( string $string )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFFont::getWidth() - Returns the string's width

SWFFont::getShape
SWFFont::getWidth
SWFFont


Returns the string's width

SWFFont::getUTF8Width
SWFFontChar
SWFFont
PHP Manual

SWFFont::getWidth

(PHP 4 >= 4.0.5)

SWFFont::getWidth — Returns the string's width

Opis

float SWFFont::getWidth ( string $string )
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.

swffont::getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the swftext() version of this method which uses the text object's scale.

Zobacz też:

  • SWFFont::getUTF8Width() - Calculates the width of the given string in this font at full height

SWFFont::getUTF8Width
SWFFontChar
SWFFont


The SWFFontChar class

(No version information available, might only be in SVN)

Wstęp

SWFFontChar.

Krótki opis klasy

SWFFontChar {
/* Metody */
void addChars ( string $char )
void addUTF8Chars ( string $char )
}

Spis treści

  • SWFFontChar::addChars — Adds characters to a font for exporting font
  • SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font
SWFFont::getWidth
SWFFontChar::addChars
Ming


Adds characters to a font for exporting font

SWFFontChar
SWFFontChar::addUTF8Chars
SWFFontChar
PHP Manual

SWFFontChar::addChars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFontChar::addChars — Adds characters to a font for exporting font

Opis

void SWFFontChar::addChars ( string $char )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFFontChar::addUTF8Chars() - Adds characters to a font for exporting font

SWFFontChar
SWFFontChar::addUTF8Chars
SWFFontChar


Adds characters to a font for exporting font

SWFFontChar::addChars
SWFGradient
SWFFontChar
PHP Manual

SWFFontChar::addUTF8Chars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font

Opis

void SWFFontChar::addUTF8Chars ( string $char )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFFontChar::addChars() - Adds characters to a font for exporting font

SWFFontChar::addChars
SWFGradient
SWFFontChar


The SWFGradient class

(No version information available, might only be in SVN)

Wstęp

SWFGradient.

Krótki opis klasy

SWFGradient {
/* Metody */
void addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] )
__construct ( void )
}

Spis treści

  • SWFGradient::addEntry — Adds an entry to the gradient list
  • SWFGradient::__construct — Creates a gradient object
SWFFontChar::addUTF8Chars
SWFGradient::addEntry
Ming


Adds an entry to the gradient list

SWFGradient
SWFGradient::__construct
SWFGradient
PHP Manual

SWFGradient::addEntry

(PHP 4 >= 4.3.0)

SWFGradient::addEntry — Adds an entry to the gradient list

Opis

void SWFGradient::addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] )
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.

swfgradient::addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.

red, green, blue is a color (RGB mode).

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFGradient
SWFGradient::__construct
SWFGradient


Creates a gradient object

SWFGradient::addEntry
SWFMorph
SWFGradient
PHP Manual

SWFGradient::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFGradient::__construct — Creates a gradient object

Opis

SWFGradient::__construct ( 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.

swfgradient() creates a new SWFGradient object.

After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape::addfill() method.

SWFGradient has the following methods : swfgradient::addentry().

This simple example will draw a big black-to-white gradient as background, and a reddish disc in its center.

Przykład #1 swfgradient() example

<?php

  $m = new SWFMovie();
  $m->setDimension(320, 240);

  $s = new SWFShape();

  // first gradient- black to white
  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(1.0, 0xff, 0xff, 0xff);

  $f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT);
  $f->scaleTo(0.01);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  $s = new SWFShape();

  // second gradient- radial gradient from red to transparent
  $g = new SWFGradient();
  $g->addEntry(0.0, 0xff, 0, 0, 0xff);
  $g->addEntry(1.0, 0xff, 0, 0, 0);

  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.005);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFGradient::addEntry
SWFMorph
SWFGradient


The SWFMorph class

(No version information available, might only be in SVN)

Wstęp

The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)

Krótki opis klasy

SWFMorph {
/* Metody */
__construct ( void )
SWFShape getShape1 ( void )
SWFShape getShape2 ( void )
}

Spis treści

  • SWFMorph::__construct — Creates a new SWFMorph object
  • SWFMorph::getShape1 — Gets a handle to the starting shape
  • SWFMorph::getShape2 — Gets a handle to the ending shape
SWFGradient::__construct
SWFMorph::__construct
Ming


Creates a new SWFMorph object

SWFMorph
SWFMorph::getShape1
SWFMorph
PHP Manual

SWFMorph::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMorph::__construct — Creates a new SWFMorph object

Opis

SWFMorph::__construct ( 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.

Creates a new SWFMorph object.

Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!

Przykłady

This simple example will morph a big red square into a smaller blue black-bordered square.

Przykład #1 swfmorph() example

<?php
  $p = new SWFMorph();

  $s = $p->getShape1();
  $s->setLine(0, 0, 0, 0);

  /* Note that this is backwards from normal shapes (left instead of right).
     I have no idea why, but this seems to work.. */

  $s->setLeftFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-1000,-1000);
  $s->drawLine(2000,0);
  $s->drawLine(0,2000);
  $s->drawLine(-2000,0);
  $s->drawLine(0,-2000);

  $s = $p->getShape2();
  $s->setLine(60,0,0,0);
  $s->setLeftFill($s->addFill(0, 0, 0xff));
  $s->movePenTo(0,-1000);
  $s->drawLine(1000,1000);
  $s->drawLine(-1000,1000);
  $s->drawLine(-1000,-1000);
  $s->drawLine(1000,-1000);

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setBackground(0xff, 0xff, 0xff);

  $i = $m->add($p);
  $i->moveTo(1500,1000);

  for ($r=0.0; $r<=1.0; $r+=0.1) {
    $i->setRatio($r);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMorph
SWFMorph::getShape1
SWFMorph


Gets a handle to the starting shape

SWFMorph::__construct
SWFMorph::getShape2
SWFMorph
PHP Manual

SWFMorph::getShape1

(PHP 4 >= 4.0.5)

SWFMorph::getShape1 — Gets a handle to the starting shape

Opis

SWFShape SWFMorph::getShape1 ( 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.

Gets the morph's starting shape.

Zwracane wartości

Returns a SWFShape object.

Zobacz też:

  • SWFMorph::getShape2() - Gets a handle to the ending shape

SWFMorph::__construct
SWFMorph::getShape2
SWFMorph


Gets a handle to the ending shape

SWFMorph::getShape1
SWFMovie
SWFMorph
PHP Manual

SWFMorph::getShape2

(PHP 4 >= 4.0.5)

SWFMorph::getShape2 — Gets a handle to the ending shape

Opis

SWFShape SWFMorph::getShape2 ( 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.

Gets the morph's ending shape.

Zwracane wartości

Returns a SWFShape object.

Zobacz też:

  • SWFMorph::getShape1() - Gets a handle to the starting shape

SWFMorph::getShape1
SWFMovie
SWFMorph


The SWFMovie class

(No version information available, might only be in SVN)

Wstęp

SWFMovie is a movie object representing an SWF movie.

Krótki opis klasy

SWFMovie {
/* Metody */
mixed add ( object $instance )
void addExport ( SWFCharacter $char , string $name )
mixed addFont ( SWFFont $font )
__construct ([ int $version ] )
SWFSprite importChar ( string $libswf , string $name )
SWFFontChar importFont ( string $libswf , string $name )
void labelFrame ( string $label )
void nextFrame ( void )
int output ([ int $compression ] )
void remove ( object $instance )
int save ( string $filename [, int $compression = -1 ] )
int saveToFile ( resource $x [, int $compression = -1 ] )
void setbackground ( int $red , int $green , int $blue )
void setDimension ( float $width , float $height )
void setFrames ( int $number )
void setRate ( float $rate )
SWFSoundInstance startSound ( SWFSound $sound )
void stopSound ( SWFSound $sound )
int streamMP3 ( mixed $mp3file [, float $skip = 0 ] )
void writeExports ( void )
}

Spis treści

  • SWFMovie::add — Adds any type of data to a movie
  • SWFMovie::addExport — Opis
  • SWFMovie::addFont — Opis
  • SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie
  • SWFMovie::importChar — Opis
  • SWFMovie::importFont — Opis
  • SWFMovie::labelFrame — Labels a frame
  • SWFMovie::nextFrame — Moves to the next frame of the animation
  • SWFMovie::output — Dumps your lovingly prepared movie out
  • SWFMovie::remove — Removes the object instance from the display list
  • SWFMovie::save — Saves the SWF movie in a file
  • SWFMovie::saveToFile — Opis
  • SWFMovie::setbackground — Sets the background color
  • SWFMovie::setDimension — Sets the movie's width and height
  • SWFMovie::setFrames — Sets the total number of frames in the animation
  • SWFMovie::setRate — Sets the animation's frame rate
  • SWFMovie::startSound — Opis
  • SWFMovie::stopSound — Opis
  • SWFMovie::streamMP3 — Streams a MP3 file
  • SWFMovie::writeExports — Opis
SWFMorph::getShape2
SWFMovie::add
Ming


Adds any type of data to a movie

SWFMovie
SWFMovie::addExport
SWFMovie
PHP Manual

SWFMovie::add

(PHP 4 >= 4.3.3)

SWFMovie::add — Adds any type of data to a movie

Opis

mixed SWFMovie::add ( object $instance )
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.

Adds an SWF object instance to the current movie.

Parametry

instance

Any type of object instance, like SWFShape, SWFText, SWFFont.

Zwracane wartości

For displayable types (shape, text, button, sprite), this returns an SWFDisplayItem, a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.

Zobacz też:

  • SWFMovie::remove() - Removes the object instance from the display list

SWFMovie
SWFMovie::addExport
SWFMovie


SWFMovie::add
SWFMovie::addFont
SWFMovie
PHP Manual

SWFMovie::addExport

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::addExport —

Opis

void SWFMovie::addExport ( SWFCharacter $char , string $name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::add
SWFMovie::addFont
SWFMovie


SWFMovie::addExport
SWFMovie::__construct
SWFMovie
PHP Manual

SWFMovie::addFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::addFont —

Opis

mixed SWFMovie::addFont ( SWFFont $font )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::addExport
SWFMovie::__construct
SWFMovie


Creates a new movie object, representing an SWF version 4 movie

SWFMovie::addFont
SWFMovie::importChar
SWFMovie
PHP Manual

SWFMovie::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie

Opis

SWFMovie::__construct ([ int $version ] )
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 movie object, representing an SWF movie.

Parametry

version

The desired SWF version. Default is 4.

SWFMovie::addFont
SWFMovie::importChar
SWFMovie


SWFMovie::__construct
SWFMovie::importFont
SWFMovie
PHP Manual

SWFMovie::importChar

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::importChar —

Opis

SWFSprite SWFMovie::importChar ( string $libswf , string $name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFMovie::importFont() - Opis

SWFMovie::__construct
SWFMovie::importFont
SWFMovie


SWFMovie::importChar
SWFMovie::labelFrame
SWFMovie
PHP Manual

SWFMovie::importFont

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::importFont —

Opis

SWFFontChar SWFMovie::importFont ( string $libswf , string $name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFMovie::importChar() - Opis

SWFMovie::importChar
SWFMovie::labelFrame
SWFMovie


Labels a frame

SWFMovie::importFont
SWFMovie::nextFrame
SWFMovie
PHP Manual

SWFMovie::labelFrame

(PHP 4 >= 4.3.3)

SWFMovie::labelFrame — Labels a frame

Opis

void SWFMovie::labelFrame ( string $label )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::importFont
SWFMovie::nextFrame
SWFMovie


Moves to the next frame of the animation

SWFMovie::labelFrame
SWFMovie::output
SWFMovie
PHP Manual

SWFMovie::nextFrame

(PHP 4 >= 4.3.3)

SWFMovie::nextFrame — Moves to the next frame of the animation

Opis

void SWFMovie::nextFrame ( 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.

Moves to the next frame of the animation.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::labelFrame
SWFMovie::output
SWFMovie


Dumps your lovingly prepared movie out

SWFMovie::nextFrame
SWFMovie::remove
SWFMovie
PHP Manual

SWFMovie::output

(PHP 4 >= 4.3.3)

SWFMovie::output — Dumps your lovingly prepared movie out

Opis

int SWFMovie::output ([ int $compression ] )
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.

Dumps the SWFMovie.

Don't forget to send the Content-Type HTTP header file before using this function, in order to display the movie in a browser.

Parametry

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Zwracane wartości

Return the number of bytes written or FALSE on error.

Przykłady

Przykład #1 Displaying your $movie in a browser

<?php
header('Content-type: application/x-shockwave-flash');
$movie->output();
?>

Zobacz też:

  • SWFMovie::save() - Saves the SWF movie in a file
  • SWFMovie::saveToFile() - Opis

SWFMovie::nextFrame
SWFMovie::remove
SWFMovie


Removes the object instance from the display list

SWFMovie::output
SWFMovie::save
SWFMovie
PHP Manual

SWFMovie::remove

(PHP 5.2.1-5.3.0, PECL ming SVN)

SWFMovie::remove — Removes the object instance from the display list

Opis

void SWFMovie::remove ( object $instance )
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.

Removes the given object instance from the display list.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFMovie::add() - Adds any type of data to a movie

SWFMovie::output
SWFMovie::save
SWFMovie


Saves the SWF movie in a file

SWFMovie::remove
SWFMovie::saveToFile
SWFMovie
PHP Manual

SWFMovie::save

(PHP 4 >= 4.3.3)

SWFMovie::save — Saves the SWF movie in a file

Opis

int SWFMovie::save ( string $filename [, int $compression = -1 ] )
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 SWF movie to the specified filename.

Parametry

filename

The path to the saved SWF document.

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Zwracane wartości

Return the number of bytes written or FALSE on error.

Zobacz też:

  • SWFMovie::output() - Dumps your lovingly prepared movie out
  • SWFMovie::saveToFile() - Opis

SWFMovie::remove
SWFMovie::saveToFile
SWFMovie


SWFMovie::save
SWFMovie::setbackground
SWFMovie
PHP Manual

SWFMovie::saveToFile

(PHP 4 >= 4.3.3)

SWFMovie::saveToFile —

Opis

int SWFMovie::saveToFile ( resource $x [, int $compression = -1 ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

X

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Zwracane wartości

Return the number of bytes written or FALSE on error.

Zobacz też:

  • SWFMovie::output() - Dumps your lovingly prepared movie out
  • SWFMovie::save() - Saves the SWF movie in a file

SWFMovie::save
SWFMovie::setbackground
SWFMovie


Sets the background color

SWFMovie::saveToFile
SWFMovie::setDimension
SWFMovie
PHP Manual

SWFMovie::setbackground

(PHP 4 >= 4.3.3)

SWFMovie::setbackground — Sets the background color

Opis

void SWFMovie::setbackground ( int $red , int $green , int $blue )
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 the background color.

Why is there no rgba version? Think about it, you might want to let the HTML background show through. There's a way to do that, but it only works on IE4. Search the » http://www.macromedia.com/ site for details.

Parametry

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::saveToFile
SWFMovie::setDimension
SWFMovie


Sets the movie's width and height

SWFMovie::setbackground
SWFMovie::setFrames
SWFMovie
PHP Manual

SWFMovie::setDimension

(PHP 4 >= 4.3.3)

SWFMovie::setDimension — Sets the movie's width and height

Opis

void SWFMovie::setDimension ( float $width , float $height )
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 the movie's dimension to the specified width and height.

Parametry

width

The movie width.

height

The movie height.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::setbackground
SWFMovie::setFrames
SWFMovie


Sets the total number of frames in the animation

SWFMovie::setDimension
SWFMovie::setRate
SWFMovie
PHP Manual

SWFMovie::setFrames

(PHP 4 >= 4.3.3)

SWFMovie::setFrames — Sets the total number of frames in the animation

Opis

void SWFMovie::setFrames ( int $number )
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 the total number of frames in the animation to the given number.

Parametry

number

The number of frames.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::setDimension
SWFMovie::setRate
SWFMovie


Sets the animation's frame rate

SWFMovie::setFrames
SWFMovie::startSound
SWFMovie
PHP Manual

SWFMovie::setRate

(PHP 4 >= 4.3.3)

SWFMovie::setRate — Sets the animation's frame rate

Opis

void SWFMovie::setRate ( float $rate )
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 the frame rate to the specified rate.

Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.

Parametry

rate

The frame rate, in frame per seconds.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::setFrames
SWFMovie::startSound
SWFMovie


SWFMovie::setRate
SWFMovie::stopSound
SWFMovie
PHP Manual

SWFMovie::startSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::startSound —

Opis

SWFSoundInstance SWFMovie::startSound ( SWFSound $sound )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFMovie::stopSound() - Opis

SWFMovie::setRate
SWFMovie::stopSound
SWFMovie


SWFMovie::startSound
SWFMovie::streamMP3
SWFMovie
PHP Manual

SWFMovie::stopSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::stopSound —

Opis

void SWFMovie::stopSound ( SWFSound $sound )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFMovie::startSound() - Opis

SWFMovie::startSound
SWFMovie::streamMP3
SWFMovie


Streams a MP3 file

SWFMovie::stopSound
SWFMovie::writeExports
SWFMovie
PHP Manual

SWFMovie::streamMP3

(PHP 4 >= 4.3.3)

SWFMovie::streamMP3 — Streams a MP3 file

Opis

int SWFMovie::streamMP3 ( mixed $mp3file [, float $skip = 0 ] )
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.

Streams the given MP3 file mp3file.

This method is not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it).

Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.

Parametry

mp3file

Can be a file pointer returned by fopen() or the MP3 data, as a binary string.

skip

Number of seconds to skip.

Zwracane wartości

Return number of frames.

Rejestr zmian

Wersja | Opis
5.2.0 | skip added

Przykłady

Przykład #1 Streaming example

<?php
$m = new SWFMovie();
$m->setRate(12.0);
$m->streamMp3(file_get_contents("distortobass.mp3"));
// use your own MP3

// The file is 11.85 seconds at 12.0 fps = 142 frames
$m->setFrames(142);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFMovie::stopSound
SWFMovie::writeExports
SWFMovie


SWFMovie::streamMP3
SWFPrebuiltClip
SWFMovie
PHP Manual

SWFMovie::writeExports

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFMovie::writeExports —

Opis

void SWFMovie::writeExports ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFMovie::streamMP3
SWFPrebuiltClip
SWFMovie


The SWFPrebuiltClip class

(No version information available, might only be in SVN)

Wstęp

SWFPrebuiltClip.

Krótki opis klasy

SWFPrebuiltClip {
/* Metody */
__construct ( mixed $file )
}

Spis treści

  • SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object
SWFMovie::writeExports
SWFPrebuiltClip::__construct
Ming


Returns a SWFPrebuiltClip object

SWFPrebuiltClip
SWFShape
SWFPrebuiltClip
PHP Manual

SWFPrebuiltClip::__construct

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object

Opis

SWFPrebuiltClip::__construct ( mixed $file )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

SWFPrebuiltClip
SWFShape
SWFPrebuiltClip


The SWFShape class

(No version information available, might only be in SVN)

Wstęp

SWFShape.

Krótki opis klasy

SWFShape {
/* Metody */
SWFFill addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] )
__construct ( void )
void drawArc ( float $r , float $startAngle , float $endAngle )
void drawCircle ( float $r )
int drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
int drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
int drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy )
int drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety )
void drawGlyph ( SWFFont $font , string $character [, int $size ] )
void drawLine ( float $dx , float $dy )
void drawLineTo ( float $x , float $y )
void movePen ( float $dx , float $dy )
void movePenTo ( float $x , float $y )
void setLeftFill ( SWFGradient $fill )
void setLine ( SWFShape $shape )
void setRightFill ( SWFGradient $fill )
}

Spis treści

  • SWFShape::addFill — Adds a solid fill to the shape
  • SWFShape::__construct — Creates a new shape object
  • SWFShape::drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
  • SWFShape::drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
  • SWFShape::drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points
  • SWFShape::drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points
  • SWFShape::drawCurve — Draws a curve (relative)
  • SWFShape::drawCurveTo — Draws a curve
  • SWFShape::drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font
  • SWFShape::drawLine — Draws a line (relative)
  • SWFShape::drawLineTo — Draws a line
  • SWFShape::movePen — Moves the shape's pen (relative)
  • SWFShape::movePenTo — Moves the shape's pen
  • SWFShape::setLeftFill — Sets left rasterizing color
  • SWFShape::setLine — Sets the shape's line style
  • SWFShape::setRightFill — Sets right rasterizing color
SWFPrebuiltClip::__construct
SWFShape::addFill
Ming


Adds a solid fill to the shape

SWFShape
SWFShape::__construct
SWFShape
PHP Manual

SWFShape::addFill

(PHP 4 >= 4.0.5)

SWFShape::addFill — Adds a solid fill to the shape

Opis

SWFFill SWFShape::addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] )
SWFFill addFill ( SWFBitmap $bitmap [, int $flags ] )
SWFFill addFill ( SWFGradient $gradient [, int $flags ] )
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.

SWFShape::addFill() adds a solid fill to the shape's list of fill styles. SWFShape::addFill() accepts three different types of arguments.

red, green, blue is a color (RGB mode).

The bitmap argument is an SWFBitmap() object. The flags argument can be one of the following values: SWFFILL_CLIPPED_BITMAP, SWFFILL_TILED_BITMAP, SWFFILL_LINEAR_GRADIENT or SWFFILL_RADIAL_GRADIENT. Default is SWFFILL_TILED_BITMAP for SWFBitmap and SWFFILL_LINEAR_GRADIENT for SWFGradient.

The gradient argument is an SWFGradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.

SWFShape::addFill() returns an SWFFill()
object for use with the SWFShape::setLeftFill()
and SWFShape::setRightFill() functions
described below.

Przykłady

This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..

Przykład #1 SWFShape::addFill() example

<?php

$p = new SWFMorph();

$b = new SWFBitmap(file_get_contents("alphafill.jpg"));
// use your own bitmap
$width = $b->getWidth();
$height = $b->getHeight();

$s = $p->getShape1();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);
$f->moveTo(-$width/2, -$height/4);
$f->scaleTo(1.0, 0.5);
$s->setLeftFill($f);
$s->movePenTo(-$width/2, -$height/4);
$s->drawLine($width, 0);
$s->drawLine(0, $height/2);
$s->drawLine(-$width, 0);
$s->drawLine(0, -$height/2);

$s = $p->getShape2();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);

// these two have no effect!
$f->moveTo(-$width/4, -$height/2);
$f->scaleTo(0.5, 1.0);

$s->setLeftFill($f);
$s->movePenTo(-$width/4, -$height/2);
$s->drawLine($width/2, 0);
$s->drawLine(0, $height);
$s->drawLine(-$width/2, 0);
$s->drawLine(0, -$height);

$m = new SWFMovie();
$m->setDimension($width, $height);
$i = $m->add($p);
$i->moveTo($width/2, $height/2);

for ($n=0; $n<1.001; $n+=0.03) {
    $i->setRatio($n);
    $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Zobacz też:

  • SWFShape::setLeftFill() - Sets left rasterizing color
  • SWFShape::setRightFill() - Sets right rasterizing color

SWFShape
SWFShape::__construct
SWFShape


Creates a new shape object

SWFShape::addFill
SWFShape::drawArc
SWFShape
PHP Manual

SWFShape::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::__construct — Creates a new shape object

Opis

SWFShape::__construct ( 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.

Created a new SWFShape object.

Przykłady

This simple example will draw a big red elliptic quadrant.

Przykład #1 swfshape() example

<?php
$s = new SWFShape();
$s->setLine(40, 0x7f, 0, 0);
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(200, 200);
$s->drawLineTo(6200, 200);
$s->drawLineTo(6200, 4600);
$s->drawCurveTo(200, 4600, 200, 200);

$m = new SWFMovie();
$m->setDimension(6400, 4800);
$m->setRate(12.0);
$m->add($s);
$m->nextFrame();

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFShape::addFill
SWFShape::drawArc
SWFShape


Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

SWFShape::__construct
SWFShape::drawCircle
SWFShape
PHP Manual

SWFShape::drawArc

(PHP 4 >= 4.0.5)

SWFShape::drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

Opis

void SWFShape::drawArc ( float $r , float $startAngle , float $endAngle )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFShape::drawCircle() - Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

SWFShape::__construct
SWFShape::drawCircle
SWFShape


Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

SWFShape::drawArc
SWFShape::drawCubic
SWFShape
PHP Manual

SWFShape::drawCircle

(PHP 4 >= 4.0.5)

SWFShape::drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

Opis

void SWFShape::drawCircle ( float $r )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFShape::drawArc
SWFShape::drawCubic
SWFShape


Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCircle
SWFShape::drawCubicTo
SWFShape
PHP Manual

SWFShape::drawCubic

(PHP 4 >= 4.0.5)

SWFShape::drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points

Opis

int SWFShape::drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFShape::drawCubicTo() - Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCircle
SWFShape::drawCubicTo
SWFShape


Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCubic
SWFShape::drawCurve
SWFShape
PHP Manual

SWFShape::drawCubicTo

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFShape::drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points

Opis

int SWFShape::drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFShape::drawCubic() - Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCubic
SWFShape::drawCurve
SWFShape


Draws a curve (relative)

SWFShape::drawCubicTo
SWFShape::drawCurveTo
SWFShape
PHP Manual

SWFShape::drawCurve

(PHP 4 >= 4.0.5)

SWFShape::drawCurve — Draws a curve (relative)

Opis

int SWFShape::drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy )
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.

swfshape::drawcurve() draws a quadratic curve (using the current line style,set by swfshape::setline()) from the current pen position to the relative position (anchorx,anchory) using relative control point (controlx,controly). That is, head towards the control point, then smoothly turn to the anchor point.

With 6 parameters, it draws a cubic bezier to point (x+targetdx, x+targetdy) with control points (x+controldx, y+controldy) and (x+anchordx, y+anchordy).

Zobacz też:

  • SWFShape::drawCurve()

SWFShape::drawCubicTo
SWFShape::drawCurveTo
SWFShape


Draws a curve

SWFShape::drawCurve
SWFShape::drawGlyph
SWFShape
PHP Manual

SWFShape::drawCurveTo

(PHP 4 >= 4.0.5)

SWFShape::drawCurveTo — Draws a curve

Opis

int SWFShape::drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety )
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.

swfshape::drawcurveto() draws a quadratic curve (using the current line style, set by swfshape::setline()) from the current pen position to (anchorx,anchory) using (controlx,controly) as a control point. That is, head towards the control point, then smoothly turn to the anchor point.

With 6 parameters, it draws a cubic bezier to point (targetx, targety) with control points (controlx, controly) and (anchorx, anchory).

Zobacz też:

  • SWFShape::drawCurveTo()

SWFShape::drawCurve
SWFShape::drawGlyph
SWFShape


Draws the first character in the given string into the shape using the glyph definition from the given font

SWFShape::drawCurveTo
SWFShape::drawLine
SWFShape
PHP Manual

SWFShape::drawGlyph

(PHP 4 >= 4.0.5)

SWFShape::drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font

Opis

void SWFShape::drawGlyph ( SWFFont $font , string $character [, int $size ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFShape::drawCurveTo
SWFShape::drawLine
SWFShape


Draws a line (relative)

SWFShape::drawGlyph
SWFShape::drawLineTo
SWFShape
PHP Manual

SWFShape::drawLine

(PHP 4 >= 4.0.5)

SWFShape::drawLine — Draws a line (relative)

Opis

void SWFShape::drawLine ( float $dx , float $dy )
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.

swfshape::drawline() draws a line (using the current line style set by swfshape::setline()) from the current pen position to displacement (dx,dy).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFShape::drawLineTo() - Draws a line

SWFShape::drawGlyph
SWFShape::drawLineTo
SWFShape


Draws a line

SWFShape::drawLine
SWFShape::movePen
SWFShape
PHP Manual

SWFShape::drawLineTo

(PHP 4 >= 4.0.5)

SWFShape::drawLineTo — Draws a line

Opis

void SWFShape::drawLineTo ( float $x , float $y )
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.

swfshape::setrightfill() draws a line (using the current line style, set by swfshape::setline()) from the current pen position to point (x,y) in the shape's coordinate space.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFShape::drawLine() - Draws a line (relative)

SWFShape::drawLine
SWFShape::movePen
SWFShape


Moves the shape's pen (relative)

SWFShape::drawLineTo
SWFShape::movePenTo
SWFShape
PHP Manual

SWFShape::movePen

(PHP 4 >= 4.0.5)

SWFShape::movePen — Moves the shape's pen (relative)

Opis

void SWFShape::movePen ( float $dx , float $dy )
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.

swfshape::setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in the shape's coordinate space.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFShape::movePenTo() - Moves the shape's pen

SWFShape::drawLineTo
SWFShape::movePenTo
SWFShape


Moves the shape's pen

SWFShape::movePen
SWFShape::setLeftFill
SWFShape
PHP Manual

SWFShape::movePenTo

(PHP 4 >= 4.0.5)

SWFShape::movePenTo — Moves the shape's pen

Opis

void SWFShape::movePenTo ( float $x , float $y )
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.

swfshape::setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFShape::movePen() - Moves the shape's pen (relative)

SWFShape::movePen
SWFShape::setLeftFill
SWFShape


Sets left rasterizing color

SWFShape::movePenTo
SWFShape::setLine
SWFShape
PHP Manual

SWFShape::setLeftFill

(PHP 4 >= 4.0.5)

SWFShape::setLeftFill — Sets left rasterizing color

Opis

void SWFShape::setLeftFill ( SWFGradient $fill )
void setLeftFill ( int $red , int $green , int $blue [, int $a ] )
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.

What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.

swfshape::setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.

This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.

Shortcut for $swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFShape::setRightFill() - Sets right rasterizing color

SWFShape::movePenTo
SWFShape::setLine
SWFShape


Sets the shape's line style

SWFShape::setLeftFill
SWFShape::setRightFill
SWFShape
PHP Manual

SWFShape::setLine

(PHP 4 >= 4.0.5)

SWFShape::setLine — Sets the shape's line style

Opis

void SWFShape::setLine ( SWFShape $shape )
void setLine ( int $width , int $red , int $green , int $blue [, int $a ] )
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.

swfshape::setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all other arguments are ignored). If width > 0, then line's color is set to red, green, blue. Last parameter a is optional.

You must declare all line styles before you use them (see example).

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

This simple example will draw a big "!#%*@", in funny colors and gracious style.

Przykład #1 swfshape::setline() example

<?php
$s = new SWFShape();
$f1 = $s->addFill(0xff, 0, 0);
$f2 = $s->addFill(0xff, 0x7f, 0);
$f3 = $s->addFill(0xff, 0xff, 0);
$f4 = $s->addFill(0, 0xff, 0);
$f5 = $s->addFill(0, 0, 0xff);

// bug: have to declare all line styles before you use them
$s->setLine(40, 0x7f, 0, 0);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->setLine(40, 0, 0x7f, 0);
$s->setLine(40, 0, 0, 0x7f);

$f = new SWFFont('Techno.fdb');

$s->setRightFill($f1);
$s->setLine(40, 0x7f, 0, 0);
$s->drawGlyph($f, '!');
$s->movePen($f->getWidth('!'), 0);

$s->setRightFill($f2);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->drawGlyph($f, '#');
$s->movePen($f->getWidth('#'), 0);

$s->setRightFill($f3);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->drawGlyph($f, '%');
$s->movePen($f->getWidth('%'), 0);

$s->setRightFill($f4);
$s->setLine(40, 0, 0x7f, 0);
$s->drawGlyph($f, '*');
$s->movePen($f->getWidth('*'), 0);

$s->setRightFill($f5);
$s->setLine(40, 0, 0, 0x7f);
$s->drawGlyph($f, '@');

$m = new SWFMovie();
$m->setDimension(3000,2000);
$m->setRate(12.0);
$i = $m->add($s);
$i->moveTo(1500-$f->getWidth("!#%*@")/2, 1000+$f->getAscent()/2);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFShape::setLeftFill
SWFShape::setRightFill
SWFShape


Sets right rasterizing color

SWFShape::setLine
SWFSound
SWFShape
PHP Manual

SWFShape::setRightFill

(PHP 4 >= 4.0.5)

SWFShape::setRightFill — Sets right rasterizing color

Opis

void SWFShape::setRightFill ( SWFGradient $fill )
void setRightFill ( int $red , int $green , int $blue [, int $a ] )
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.

Shortcut for $swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFShape::setLeftFill() - Sets left rasterizing color

SWFShape::setLine
SWFSound
SWFShape


The SWFSound class

(PHP 5 <= 5.3.0, PECL ming SVN)

Wstęp

SWFSound.

Krótki opis klasy

SWFSound {
/* Metody */
__construct ( string $filename [, int $flags = 0 ] )
}

Spis treści

  • SWFSound::__construct — Returns a new SWFSound object from given file
SWFShape::setRightFill
SWFSound::__construct
Ming


Returns a new SWFSound object from given file

SWFSound
SWFSoundInstance
SWFSound
PHP Manual

SWFSound::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSound::__construct — Returns a new SWFSound object from given file

Opis

SWFSound::__construct ( string $filename [, int $flags = 0 ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

SWFSound
SWFSoundInstance
SWFSound


The SWFSoundInstance class

(No version information available, might only be in SVN)

Wstęp

SWFSoundInstance objects are returned by the SWFSprite::startSound() and SWFMovie::startSound() methods.

Krótki opis klasy

SWFSoundInstance {
/* Metody */
void loopCount ( int $point )
void loopInPoint ( int $point )
void loopOutPoint ( int $point )
void noMultiple ( void )
}

Spis treści

  • SWFSoundInstance::loopCount — Opis
  • SWFSoundInstance::loopInPoint — Opis
  • SWFSoundInstance::loopOutPoint — Opis
  • SWFSoundInstance::noMultiple — Opis
SWFSound::__construct
SWFSoundInstance::loopCount
Ming


SWFSoundInstance
SWFSoundInstance::loopInPoint
SWFSoundInstance
PHP Manual

SWFSoundInstance::loopCount

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopCount —

Opis

void SWFSoundInstance::loopCount ( int $point )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

point

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFSoundInstance::loopOutPoint() - Opis

SWFSoundInstance
SWFSoundInstance::loopInPoint
SWFSoundInstance


SWFSoundInstance::loopCount
SWFSoundInstance::loopOutPoint
SWFSoundInstance
PHP Manual

SWFSoundInstance::loopInPoint

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopInPoint —

Opis

void SWFSoundInstance::loopInPoint ( int $point )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

point

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFSoundInstance::loopOutPoint() - Opis

SWFSoundInstance::loopCount
SWFSoundInstance::loopOutPoint
SWFSoundInstance


SWFSoundInstance::loopInPoint
SWFSoundInstance::noMultiple
SWFSoundInstance
PHP Manual

SWFSoundInstance::loopOutPoint

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::loopOutPoint —

Opis

void SWFSoundInstance::loopOutPoint ( int $point )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

point

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFSoundInstance::loopInPoint() - Opis

SWFSoundInstance::loopInPoint
SWFSoundInstance::noMultiple
SWFSoundInstance


SWFSoundInstance::loopOutPoint
SWFSprite
SWFSoundInstance
PHP Manual

SWFSoundInstance::noMultiple

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSoundInstance::noMultiple —

Opis

void SWFSoundInstance::noMultiple ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFSoundInstance::loopOutPoint
SWFSprite
SWFSoundInstance


The SWFSprite class

(No version information available, might only be in SVN)

Wstęp

An SWFSprite is also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.

Krótki opis klasy

SWFSprite {
/* Metody */
void add ( object $object )
__construct ( void )
void labelFrame ( string $label )
void nextFrame ( void )
void remove ( object $object )
void setFrames ( int $number )
SWFSoundInstance startSound ( SWFSound $sount )
void stopSound ( SWFSound $sount )
}

Spis treści

  • SWFSprite::add — Adds an object to a sprite
  • SWFSprite::__construct — Creates a movie clip (a sprite)
  • SWFSprite::labelFrame — Labels frame
  • SWFSprite::nextFrame — Moves to the next frame of the animation
  • SWFSprite::remove — Removes an object to a sprite
  • SWFSprite::setFrames — Sets the total number of frames in the animation
  • SWFSprite::startSound — Opis
  • SWFSprite::stopSound — Opis
SWFSoundInstance::noMultiple
SWFSprite::add
Ming


Adds an object to a sprite

SWFSprite
SWFSprite::__construct
SWFSprite
PHP Manual

SWFSprite::add

(PHP 4 >= 4.0.5)

SWFSprite::add — Adds an object to a sprite

Opis

void SWFSprite::add ( object $object )
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.

swfsprite::add() adds a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object.

For displayable types (swfshape(),
swfbutton(), swftext(),
swfaction() or swfsprite()),
this returns a handle  to the object in a display list.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFSprite
SWFSprite::__construct
SWFSprite


Creates a movie clip (a sprite)

SWFSprite::add
SWFSprite::labelFrame
SWFSprite
PHP Manual

SWFSprite::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::__construct — Creates a movie clip (a sprite)

Opis

SWFSprite::__construct ( 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.

Creates a new SWFSprite object.

SWFSprite::add
SWFSprite::labelFrame
SWFSprite


Labels frame

SWFSprite::__construct
SWFSprite::nextFrame
SWFSprite
PHP Manual

SWFSprite::labelFrame

(PHP 4 >= 4.3.3)

SWFSprite::labelFrame — Labels frame

Opis

void SWFSprite::labelFrame ( string $label )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFSprite::__construct
SWFSprite::nextFrame
SWFSprite


Moves to the next frame of the animation

SWFSprite::labelFrame
SWFSprite::remove
SWFSprite
PHP Manual

SWFSprite::nextFrame

(PHP 4 >= 4.0.5)

SWFSprite::nextFrame — Moves to the next frame of the animation

Opis

void SWFSprite::nextFrame ( 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.

swfsprite::setframes() moves to the next frame of the animation.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFSprite::labelFrame
SWFSprite::remove
SWFSprite


Removes an object to a sprite

SWFSprite::nextFrame
SWFSprite::setFrames
SWFSprite
PHP Manual

SWFSprite::remove

(PHP 4 >= 4.0.5)

SWFSprite::remove — Removes an object to a sprite

Opis

void SWFSprite::remove ( object $object )
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.

swfsprite::remove() remove a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object
from the sprite.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFSprite::nextFrame
SWFSprite::setFrames
SWFSprite


Sets the total number of frames in the animation

SWFSprite::remove
SWFSprite::startSound
SWFSprite
PHP Manual

SWFSprite::setFrames

(PHP 4 >= 4.0.5)

SWFSprite::setFrames — Sets the total number of frames in the animation

Opis

void SWFSprite::setFrames ( int $number )
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.

swfsprite::setframes() sets the total number of frames in the animation to numberofframes.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFSprite::remove
SWFSprite::startSound
SWFSprite


SWFSprite::setFrames
SWFSprite::stopSound
SWFSprite
PHP Manual

SWFSprite::startSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::startSound —

Opis

SWFSoundInstance SWFSprite::startSound ( SWFSound $sount )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFSprite::stopSound() - Opis

SWFSprite::setFrames
SWFSprite::stopSound
SWFSprite


SWFSprite::startSound
SWFText
SWFSprite
PHP Manual

SWFSprite::stopSound

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFSprite::stopSound —

Opis

void SWFSprite::stopSound ( SWFSound $sount )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFSprite::startSound() - Opis

SWFSprite::startSound
SWFText
SWFSprite


The SWFText class

(No version information available, might only be in SVN)

Wstęp

SWFText.

Krótki opis klasy

SWFText {
/* Metody */
void addString ( string $string )
void addUTF8String ( string $text )
__construct ( void )
float getAscent ( void )
float getDescent ( void )
float getLeading ( void )
float getUTF8Width ( string $string )
float getWidth ( string $string )
void moveTo ( float $x , float $y )
void setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
void setFont ( SWFFont $font )
void setHeight ( float $height )
void setSpacing ( float $spacing )
}

Spis treści

  • SWFText::addString — Draws a string
  • SWFText::addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
  • SWFText::__construct — Creates a new SWFText object
  • SWFText::getAscent — Returns the ascent of the current font at its current size, or 0 if not available
  • SWFText::getDescent — Returns the descent of the current font at its current size, or 0 if not available
  • SWFText::getLeading — Returns the leading of the current font at its current size, or 0 if not available
  • SWFText::getUTF8Width — calculates the width of the given string in this text objects current font and size
  • SWFText::getWidth — Computes string's width
  • SWFText::moveTo — Moves the pen
  • SWFText::setColor — Sets the current text color
  • SWFText::setFont — Sets the current font
  • SWFText::setHeight — Sets the current font height
  • SWFText::setSpacing — Sets the current font spacing
SWFSprite::stopSound
SWFText::addString
Ming


Draws a string

SWFText
SWFText::addUTF8String
SWFText
PHP Manual

SWFText::addString

(PHP 4 >= 4.0.5)

SWFText::addString — Draws a string

Opis

void SWFText::addString ( string $string )
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.

swftext::addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFText::addUTF8String() - Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

SWFText
SWFText::addUTF8String
SWFText


Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

SWFText::addString
SWFText::__construct
SWFText
PHP Manual

SWFText::addUTF8String

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

Opis

void SWFText::addUTF8String ( string $text )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFText::addString() - Draws a string

SWFText::addString
SWFText::__construct
SWFText


Creates a new SWFText object

SWFText::addUTF8String
SWFText::getAscent
SWFText
PHP Manual

SWFText::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::__construct — Creates a new SWFText object

Opis

SWFText::__construct ( 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.

Creates a new SWFText object, fresh for manipulating.

Przykłady

This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.

Przykład #1 swftext() example

<?php
$f = new SWFFont("Techno.fdb");
$t = new SWFText();
$t->setFont($f);
$t->moveTo(200, 2400);
$t->setColor(0xff, 0xff, 0);
$t->setHeight(1200);
$t->addString("PHP generates Flash with Ming!!");

$m = new SWFMovie();
$m->setDimension(5400, 3600);

$m->add($t);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

SWFText::addUTF8String
SWFText::getAscent
SWFText


Returns the ascent of the current font at its current size, or 0 if not available

SWFText::__construct
SWFText::getDescent
SWFText
PHP Manual

SWFText::getAscent

(PHP 4 >= 4.0.5)

SWFText::getAscent — Returns the ascent of the current font at its current size, or 0 if not available

Opis

float SWFText::getAscent ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFText::getDescent() - Returns the descent of the current font at its current size, or 0 if not available

SWFText::__construct
SWFText::getDescent
SWFText


Returns the descent of the current font at its current size, or 0 if not available

SWFText::getAscent
SWFText::getLeading
SWFText
PHP Manual

SWFText::getDescent

(PHP 4 >= 4.0.5)

SWFText::getDescent — Returns the descent of the current font at its current size, or 0 if not available

Opis

float SWFText::getDescent ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFText::getAscent() - Returns the ascent of the current font at its current size, or 0 if not available

SWFText::getAscent
SWFText::getLeading
SWFText


Returns the leading of the current font at its current size, or 0 if not available

SWFText::getDescent
SWFText::getUTF8Width
SWFText
PHP Manual

SWFText::getLeading

(PHP 4 >= 4.0.5)

SWFText::getLeading — Returns the leading of the current font at its current size, or 0 if not available

Opis

float SWFText::getLeading ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

SWFText::getDescent
SWFText::getUTF8Width
SWFText


calculates the width of the given string in this text objects current font and size

SWFText::getLeading
SWFText::getWidth
SWFText
PHP Manual

SWFText::getUTF8Width

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFText::getUTF8Width — calculates the width of the given string in this text objects current font and size

Opis

float SWFText::getUTF8Width ( string $string )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • SWFText::getWidth() - Computes string's width

SWFText::getLeading
SWFText::getWidth
SWFText


Computes string's width

SWFText::getUTF8Width
SWFText::moveTo
SWFText
PHP Manual

SWFText::getWidth

(PHP 4 >= 4.0.5)

SWFText::getWidth — Computes string's width

Opis

float SWFText::getWidth ( string $string )
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 rendered width of the string at the text object's current font, scale, and spacing settings.

Zobacz też:

  • SWFText::getUTF8Width() - calculates the width of the given string in this text objects current font and size

SWFText::getUTF8Width
SWFText::moveTo
SWFText


Moves the pen

SWFText::getWidth
SWFText::setColor
SWFText
PHP Manual

SWFText::moveTo

(PHP 4 >= 4.0.5)

SWFText::moveTo — Moves the pen

Opis

void SWFText::moveTo ( float $x , float $y )
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.

swftext::moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFText::getWidth
SWFText::setColor
SWFText


Sets the current text color

SWFText::moveTo
SWFText::setFont
SWFText
PHP Manual

SWFText::setColor

(PHP 4 >= 4.0.5)

SWFText::setColor — Sets the current text color

Opis

void SWFText::setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
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.

Changes the current text color.

Parametry

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFText::moveTo
SWFText::setFont
SWFText


Sets the current font

SWFText::setColor
SWFText::setHeight
SWFText
PHP Manual

SWFText::setFont

(PHP 4 >= 4.0.5)

SWFText::setFont — Sets the current font

Opis

void SWFText::setFont ( SWFFont $font )
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.

swftext::setfont() sets the current font to font.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFText::setColor
SWFText::setHeight
SWFText


Sets the current font height

SWFText::setFont
SWFText::setSpacing
SWFText
PHP Manual

SWFText::setHeight

(PHP 4 >= 4.0.5)

SWFText::setHeight — Sets the current font height

Opis

void SWFText::setHeight ( float $height )
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.

swftext::setheight() sets the current font height to height. Default is 240.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFText::setFont
SWFText::setSpacing
SWFText


Sets the current font spacing

SWFText::setHeight
SWFTextField
SWFText
PHP Manual

SWFText::setSpacing

(PHP 4 >= 4.0.5)

SWFText::setSpacing — Sets the current font spacing

Opis

void SWFText::setSpacing ( float $spacing )
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.

swftext::setspacing() sets the current font spacing to spacing. Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFText::setHeight
SWFTextField
SWFText


The SWFTextField class

(No version information available, might only be in SVN)

Wstęp

SWFTextField.

Krótki opis klasy

SWFTextField {
/* Metody */
void addChars ( string $chars )
void addString ( string $string )
void align ( int $alignement )
__construct ([ int $flags ] )
void setBounds ( float $width , float $height )
void setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
void setFont ( SWFFont $font )
void setHeight ( float $height )
void setIndentation ( float $width )
void setLeftMargin ( float $width )
void setLineSpacing ( float $height )
void setMargins ( float $left , float $right )
void setName ( string $name )
void setPadding ( float $padding )
void setRightMargin ( float $width )
}

Spis treści

  • SWFTextField::addChars — adds characters to a font that will be available within a textfield
  • SWFTextField::addString — Concatenates the given string to the text field
  • SWFTextField::align — Sets the text field alignment
  • SWFTextField::__construct — Creates a text field object
  • SWFTextField::setBounds — Sets the text field width and height
  • SWFTextField::setColor — Sets the color of the text field
  • SWFTextField::setFont — Sets the text field font
  • SWFTextField::setHeight — Sets the font height of this text field font
  • SWFTextField::setIndentation — Sets the indentation of the first line
  • SWFTextField::setLeftMargin — Sets the left margin width of the text field
  • SWFTextField::setLineSpacing — Sets the line spacing of the text field
  • SWFTextField::setMargins — Sets the margins width of the text field
  • SWFTextField::setName — Sets the variable name
  • SWFTextField::setPadding — Sets the padding of this textfield
  • SWFTextField::setRightMargin — Sets the right margin width of the text field
SWFText::setSpacing
SWFTextField::addChars
Ming


adds characters to a font that will be available within a textfield

SWFTextField
SWFTextField::addString
SWFTextField
PHP Manual

SWFTextField::addChars

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::addChars — adds characters to a font that will be available within a textfield

Opis

void SWFTextField::addChars ( string $chars )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SWFTextField::addString() - Concatenates the given string to the text field

SWFTextField
SWFTextField::addString
SWFTextField


Concatenates the given string to the text field

SWFTextField::addChars
SWFTextField::align
SWFTextField
PHP Manual

SWFTextField::addString

(PHP 4 >= 4.0.5)

SWFTextField::addString — Concatenates the given string to the text field

Opis

void SWFTextField::addString ( string $string )
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.

swftextfield::setname() concatenates the string string to the text field.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::addChars
SWFTextField::align
SWFTextField


Sets the text field alignment

SWFTextField::addString
SWFTextField::__construct
SWFTextField
PHP Manual

SWFTextField::align

(PHP 4 >= 4.0.5)

SWFTextField::align — Sets the text field alignment

Opis

void SWFTextField::align ( int $alignement )
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.

swftextfield::align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::addString
SWFTextField::__construct
SWFTextField


Creates a text field object

SWFTextField::align
SWFTextField::setBounds
SWFTextField
PHP Manual

SWFTextField::__construct

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::__construct — Creates a text field object

Opis

SWFTextField::__construct ([ int $flags ] )
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.

swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.

The optional flags change the text field's behavior. It has the following possibles values :

  • SWFTEXTFIELD_DRAWBOX draws the outline of the textfield
  • SWFTEXTFIELD_HASLENGTH
  • SWFTEXTFIELD_HTML allows text markup using HTML-tags
  • SWFTEXTFIELD_MULTILINE allows multiple lines
  • SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable
  • SWFTEXTFIELD_NOSELECT makes the field non-selectable
  • SWFTEXTFIELD_PASSWORD obscures the data entry
  • SWFTEXTFIELD_WORDWRAP allows text to wrap
Flags are combined with the bitwise OR operation. For example,
<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT);
?>
creates a totally useless non-editable password field.

SWFTextField has the following methods : swftextfield::setfont(),
swftextfield::setbounds(), swftextfield::align(),
swftextfield::setheight(), swftextfield::setleftmargin(),
swftextfield::setrightmargin(), swftextfield::setmargins(),
swftextfield::setindentation(), swftextfield::setlinespacing(),
swftextfield::setcolor(), swftextfield::setname() and
swftextfield::addstring().

SWFTextField::align
SWFTextField::setBounds
SWFTextField


Sets the text field width and height

SWFTextField::__construct
SWFTextField::setColor
SWFTextField
PHP Manual

SWFTextField::setBounds

(PHP 4 >= 4.0.5)

SWFTextField::setBounds — Sets the text field width and height

Opis

void SWFTextField::setBounds ( float $width , float $height )
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.

swftextfield::setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::__construct
SWFTextField::setColor
SWFTextField


Sets the color of the text field

SWFTextField::setBounds
SWFTextField::setFont
SWFTextField
PHP Manual

SWFTextField::setColor

(PHP 4 >= 4.0.5)

SWFTextField::setColor — Sets the color of the text field

Opis

void SWFTextField::setColor ( int $red , int $green , int $blue [, int $a = 255 ] )
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.

swftextfield::setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.

Parametry

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setBounds
SWFTextField::setFont
SWFTextField


Sets the text field font

SWFTextField::setColor
SWFTextField::setHeight
SWFTextField
PHP Manual

SWFTextField::setFont

(PHP 4 >= 4.2.0)

SWFTextField::setFont — Sets the text field font

Opis

void SWFTextField::setFont ( SWFFont $font )
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.

swftextfield::setfont() sets the text field font to the [browser-defined?] font font.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setColor
SWFTextField::setHeight
SWFTextField


Sets the font height of this text field font

SWFTextField::setFont
SWFTextField::setIndentation
SWFTextField
PHP Manual

SWFTextField::setHeight

(PHP 4 >= 4.0.5)

SWFTextField::setHeight — Sets the font height of this text field font

Opis

void SWFTextField::setHeight ( float $height )
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.

swftextfield::setheight() sets the font height of this text field font to the given height height. Default is 240.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setFont
SWFTextField::setIndentation
SWFTextField


Sets the indentation of the first line

SWFTextField::setHeight
SWFTextField::setLeftMargin
SWFTextField
PHP Manual

SWFTextField::setIndentation

(PHP 4 >= 4.0.5)

SWFTextField::setIndentation — Sets the indentation of the first line

Opis

void SWFTextField::setIndentation ( float $width )
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.

swftextfield::setindentation() sets the indentation of the first line in the text field, to width.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setHeight
SWFTextField::setLeftMargin
SWFTextField


Sets the left margin width of the text field

SWFTextField::setIndentation
SWFTextField::setLineSpacing
SWFTextField
PHP Manual

SWFTextField::setLeftMargin

(PHP 4 >= 4.0.5)

SWFTextField::setLeftMargin — Sets the left margin width of the text field

Opis

void SWFTextField::setLeftMargin ( float $width )
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.

swftextfield::setleftmargin() sets the left margin width of the text field to width. Default is 0.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setIndentation
SWFTextField::setLineSpacing
SWFTextField


Sets the line spacing of the text field

SWFTextField::setLeftMargin
SWFTextField::setMargins
SWFTextField
PHP Manual

SWFTextField::setLineSpacing

(PHP 4 >= 4.0.5)

SWFTextField::setLineSpacing — Sets the line spacing of the text field

Opis

void SWFTextField::setLineSpacing ( float $height )
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.

swftextfield::setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setLeftMargin
SWFTextField::setMargins
SWFTextField


Sets the margins width of the text field

SWFTextField::setLineSpacing
SWFTextField::setName
SWFTextField
PHP Manual

SWFTextField::setMargins

(PHP 4 >= 4.0.5)

SWFTextField::setMargins — Sets the margins width of the text field

Opis

void SWFTextField::setMargins ( float $left , float $right )
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.

swftextfield::setmargins() set both margins at once, for the man on the go.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setLineSpacing
SWFTextField::setName
SWFTextField


Sets the variable name

SWFTextField::setMargins
SWFTextField::setPadding
SWFTextField
PHP Manual

SWFTextField::setName

(PHP 4 >= 4.0.5)

SWFTextField::setName — Sets the variable name

Opis

void SWFTextField::setName ( string $name )
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.

swftextfield::setname() sets the variable name of this text field to name, for form posting and action scripting purposes.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setMargins
SWFTextField::setPadding
SWFTextField


Sets the padding of this textfield

SWFTextField::setName
SWFTextField::setRightMargin
SWFTextField
PHP Manual

SWFTextField::setPadding

(PHP 5 <= 5.3.0, PECL ming SVN)

SWFTextField::setPadding — Sets the padding of this textfield

Opis

void SWFTextField::setPadding ( float $padding )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setName
SWFTextField::setRightMargin
SWFTextField


Sets the right margin width of the text field

SWFTextField::setPadding
SWFVideoStream
SWFTextField
PHP Manual

SWFTextField::setRightMargin

(PHP 4 >= 4.0.5)

SWFTextField::setRightMargin — Sets the right margin width of the text field

Opis

void SWFTextField::setRightMargin ( float $width )
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.

swftextfield::setrightmargin() sets the right margin width of the text field to width. Default is 0.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFTextField::setPadding
SWFVideoStream
SWFTextField


The SWFVideoStream class

(No version information available, might only be in SVN)

Wstęp

SWFVideoStream.

Krótki opis klasy

SWFVideoStream {
/* Metody */
__construct ([ string $file ] )
int getNumFrames ( void )
void setDimension ( int $x , int $y )
}

Spis treści

  • SWFVideoStream::__construct — Returns a SWFVideoStream object
  • SWFVideoStream::getNumFrames — Returns the number of frames in the video
  • SWFVideoStream::setDimension — Sets video dimension
SWFTextField::setRightMargin
SWFVideoStream::__construct
Ming


Returns a SWFVideoStream object

SWFVideoStream
SWFVideoStream::getNumFrames
SWFVideoStream
PHP Manual

SWFVideoStream::__construct

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream::__construct — Returns a SWFVideoStream object

Opis

SWFVideoStream::__construct ([ string $file ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

SWFVideoStream
SWFVideoStream::getNumFrames
SWFVideoStream


Returns the number of frames in the video

SWFVideoStream::__construct
SWFVideoStream::setDimension
SWFVideoStream
PHP Manual

SWFVideoStream::getNumFrames

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream::getNumFrames — Returns the number of frames in the video

Opis

int SWFVideoStream::getNumFrames ( void )

This function returns the number of video-frames of a SWFVideoStream.

Zwracane wartości

Returns the number of frames, as an integer

SWFVideoStream::__construct
SWFVideoStream::setDimension
SWFVideoStream


Sets video dimension

SWFVideoStream::getNumFrames
PDF
SWFVideoStream
PHP Manual

SWFVideoStream::setDimension

(PHP 5.0.5-5.3.0, PECL ming SVN)

SWFVideoStream::setDimension — Sets video dimension

Opis

void SWFVideoStream::setDimension ( int $x , int $y )

Sets the width and height for streamed videos.

Parametry

x

Width in pixels.

y

Height in pixels.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWFVideoStream::getNumFrames
PDF
SWFVideoStream


PDF

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic Usage Examples
  • PDF Funkcje
    • PDF_activate_item — Activate structure element or other content item
    • PDF_add_annotation — Add annotation [deprecated]
    • PDF_add_bookmark — Add bookmark for current page [deprecated]
    • PDF_add_launchlink — Add launch annotation for current page [deprecated]
    • PDF_add_locallink — Add link annotation for current page [deprecated]
    • PDF_add_nameddest — Create named destination
    • PDF_add_note — Set annotation for current page [deprecated]
    • PDF_add_outline — Add bookmark for current page [deprecated]
    • PDF_add_pdflink — Add file link annotation for current page [deprecated]
    • PDF_add_table_cell — Add a cell to a new or existing table
    • PDF_add_textflow — Create Textflow or add text to existing Textflow
    • PDF_add_thumbnail — Add thumbnail for current page
    • PDF_add_weblink — Add weblink for current page [deprecated]
    • PDF_arc — Draw a counterclockwise circular arc segment
    • PDF_arcn — Draw a clockwise circular arc segment
    • PDF_attach_file — Add file attachment for current page [deprecated]
    • PDF_begin_document — Create new PDF file
    • PDF_begin_font — Start a Type 3 font definition
    • PDF_begin_glyph — Start glyph definition for Type 3 font
    • PDF_begin_item — Open structure element or other content item
    • PDF_begin_layer — Start layer
    • PDF_begin_page_ext — Start new page
    • PDF_begin_page — Start new page [deprecated]
    • PDF_begin_pattern — Start pattern definition
    • PDF_begin_template_ext — Start template definition
    • PDF_begin_template — Start template definition [deprecated]
    • PDF_circle — Draw a circle
    • PDF_clip — Clip to current path
    • PDF_close_image — Close image
    • PDF_close_pdi_page — Close the page handle
    • PDF_close_pdi — Close the input PDF document [deprecated]
    • PDF_close — Close pdf resource [deprecated]
    • PDF_closepath_fill_stroke — Close, fill and stroke current path
    • PDF_closepath_stroke — Close and stroke path
    • PDF_closepath — Close current path
    • PDF_concat — Concatenate a matrix to the CTM
    • PDF_continue_text — Output text in next line
    • PDF_create_3dview — Create 3D view
    • PDF_create_action — Create action for objects or events
    • PDF_create_annotation — Create rectangular annotation
    • PDF_create_bookmark — Create bookmark
    • PDF_create_field — Create form field
    • PDF_create_fieldgroup — Create form field group
    • PDF_create_gstate — Create graphics state object
    • PDF_create_pvf — Create PDFlib virtual file
    • PDF_create_textflow — Create textflow object
    • PDF_curveto — Draw Bezier curve
    • PDF_define_layer — Create layer definition
    • PDF_delete_pvf — Delete PDFlib virtual file
    • PDF_delete_table — Delete table object
    • PDF_delete_textflow — Delete textflow object
    • PDF_delete — Delete PDFlib object
    • PDF_encoding_set_char — Add glyph name and/or Unicode value
    • PDF_end_document — Close PDF file
    • PDF_end_font — Terminate Type 3 font definition
    • PDF_end_glyph — Terminate glyph definition for Type 3 font
    • PDF_end_item — Close structure element or other content item
    • PDF_end_layer — Deactivate all active layers
    • PDF_end_page_ext — Finish page
    • PDF_end_page — Finish page
    • PDF_end_pattern — Finish pattern
    • PDF_end_template — Finish template
    • PDF_endpath — End current path
    • PDF_fill_imageblock — Fill image block with variable data
    • PDF_fill_pdfblock — Fill PDF block with variable data
    • PDF_fill_stroke — Fill and stroke path
    • PDF_fill_textblock — Fill text block with variable data
    • PDF_fill — Fill current path
    • PDF_findfont — Prepare font for later use [deprecated]
    • PDF_fit_image — Place image or template
    • PDF_fit_pdi_page — Place imported PDF page
    • PDF_fit_table — Place table on page
    • PDF_fit_textflow — Format textflow in rectangular area
    • PDF_fit_textline — Place single line of text
    • PDF_get_apiname — Get name of unsuccessfull API function
    • PDF_get_buffer — Get PDF output buffer
    • PDF_get_errmsg — Get error text
    • PDF_get_errnum — Get error number
    • PDF_get_font — Get font [deprecated]
    • PDF_get_fontname — Get font name [deprecated]
    • PDF_get_fontsize — Font handling [deprecated]
    • PDF_get_image_height — Get image height [deprecated]
    • PDF_get_image_width — Get image width [deprecated]
    • PDF_get_majorversion — Get major version number [deprecated]
    • PDF_get_minorversion — Get minor version number [deprecated]
    • PDF_get_parameter — Get string parameter
    • PDF_get_pdi_parameter — Get PDI string parameter [deprecated]
    • PDF_get_pdi_value — Get PDI numerical parameter [deprecated]
    • PDF_get_value — Get numerical parameter
    • PDF_info_font — Query detailed information about a loaded font
    • PDF_info_matchbox — Query matchbox information
    • PDF_info_table — Retrieve table information
    • PDF_info_textflow — Query textflow state
    • PDF_info_textline — Perform textline formatting and query metrics
    • PDF_initgraphics — Reset graphic state
    • PDF_lineto — Draw a line
    • PDF_load_3ddata — Load 3D model
    • PDF_load_font — Search and prepare font
    • PDF_load_iccprofile — Search and prepare ICC profile
    • PDF_load_image — Open image file
    • PDF_makespotcolor — Make spot color
    • PDF_moveto — Set current point
    • PDF_new — Create PDFlib object
    • PDF_open_ccitt — Open raw CCITT image [deprecated]
    • PDF_open_file — Create PDF file [deprecated]
    • PDF_open_gif — Open GIF image [deprecated]
    • PDF_open_image_file — Read image from file [deprecated]
    • PDF_open_image — Use image data [deprecated]
    • PDF_open_jpeg — Open JPEG image [deprecated]
    • PDF_open_memory_image — Open image created with PHP's image functions [not supported]
    • PDF_open_pdi_document — Prepare a pdi document
    • PDF_open_pdi_page — Prepare a page
    • PDF_open_pdi — Open PDF file [deprecated]
    • PDF_open_tiff — Open TIFF image [deprecated]
    • PDF_pcos_get_number — Get value of pCOS path with type number or boolean
    • PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string
    • PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean
    • PDF_place_image — Place image on the page [deprecated]
    • PDF_place_pdi_page — Place PDF page [deprecated]
    • PDF_process_pdi — Process imported PDF document
    • PDF_rect — Draw rectangle
    • PDF_restore — Restore graphics state
    • PDF_resume_page — Resume page
    • PDF_rotate — Rotate coordinate system
    • PDF_save — Save graphics state
    • PDF_scale — Scale coordinate system
    • PDF_set_border_color — Set border color of annotations [deprecated]
    • PDF_set_border_dash — Set border dash style of annotations [deprecated]
    • PDF_set_border_style — Set border style of annotations [deprecated]
    • PDF_set_char_spacing — Set character spacing [deprecated]
    • PDF_set_duration — Set duration between pages [deprecated]
    • PDF_set_gstate — Activate graphics state object
    • PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]
    • PDF_set_info_author — Fill the author document info field [deprecated]
    • PDF_set_info_creator — Fill the creator document info field [deprecated]
    • PDF_set_info_keywords — Fill the keywords document info field [deprecated]
    • PDF_set_info_subject — Fill the subject document info field [deprecated]
    • PDF_set_info_title — Fill the title document info field [deprecated]
    • PDF_set_info — Fill document info field
    • PDF_set_layer_dependency — Define relationships among layers
    • PDF_set_leading — Set distance between text lines [deprecated]
    • PDF_set_parameter — Set string parameter
    • PDF_set_text_matrix — Set text matrix [deprecated]
    • PDF_set_text_pos — Set text position
    • PDF_set_text_rendering — Determine text rendering [deprecated]
    • PDF_set_text_rise — Set text rise [deprecated]
    • PDF_set_value — Set numerical parameter
    • PDF_set_word_spacing — Set spacing between words [deprecated]
    • PDF_setcolor — Set fill and stroke color
    • PDF_setdash — Set simple dash pattern
    • PDF_setdashpattern — Set dash pattern
    • PDF_setflat — Set flatness
    • PDF_setfont — Set font
    • PDF_setgray_fill — Set fill color to gray [deprecated]
    • PDF_setgray_stroke — Set stroke color to gray [deprecated]
    • PDF_setgray — Set color to gray [deprecated]
    • PDF_setlinecap — Set linecap parameter
    • PDF_setlinejoin — Set linejoin parameter
    • PDF_setlinewidth — Set line width
    • PDF_setmatrix — Set current transformation matrix
    • PDF_setmiterlimit — Set miter limit
    • PDF_setpolydash — Set complicated dash pattern [deprecated]
    • PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]
    • PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]
    • PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]
    • PDF_shading_pattern — Define shading pattern
    • PDF_shading — Define blend
    • PDF_shfill — Fill area with shading
    • PDF_show_boxed — Output text in a box [deprecated]
    • PDF_show_xy — Output text at given position
    • PDF_show — Output text at current position
    • PDF_skew — Skew the coordinate system
    • PDF_stringwidth — Return width of text
    • PDF_stroke — Stroke path
    • PDF_suspend_page — Suspend page
    • PDF_translate — Set origin of coordinate system
    • PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8
    • PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16
    • PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16
SWFVideoStream::setDimension
Wstęp
Generowanie nietekstowych formatów danych


Wstęp

The PDF functions in PHP can create PDF files using the PDFlib library which was initially created by Thomas Merz and is now maintained by » PDFlib GmbH.

The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. For the full and detailed explanation of each function, consult the PDFlib Reference Manual which is included in all PDFlib packages distributed by PDFlib GmbH. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.

For a jump start we urge you to take a look at the programming samples which are contained in all PDFlib distribution packages. These samples demonstrate basic text, vector, and graphics output as well as higher-level functions, such as the PDF import facility (PDI).

All of the functions in PDFlib and the PHP module have identical function names and parameters. Unless configured otherwise, all lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib Reference Manual included in the PDFlib distribution for a more thorough explanation of the coordinate system used.

With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. The main difference is the following:

In PHP 4, first a PDF resource has to be retrieved with a function call like

$p = PDF_new().

This PDF resource is used as the first parameter in all further function calls, such as in

PDF_begin_document($p, "", "").

In PHP 5 however, a PDFlib object is created with

$p = new PDFlib().

This object offers all PDFlib API functions as methods, e.g. as with

$p->begin_document("", "").

In addition, exceptions have been introduced in PHP 5 which are supported by PDFlib 6 and later as well.

Please see the examples below for more information.

Informacja:

If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.

PDF
Instalacja/Konfiguracja
PDF


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
PDF


Wymagania

PDFlib Lite is available as open source. However, the PDFlib Lite license allows free use only under certain conditions. PDFlib Lite supports a subset of PDFlib's functionality; please see the PDFlib web site for details. The full version of PDFlib is available for download at » http://www.pdflib.com/products/pdflib-family/, but requires that you purchase a license for commercial use.

Issues with older versions of PDFlib

Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.

PDFlib 4.0 or greater is supported by PHP 4.3.0 and later.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/pdflib.

To get these functions to work in PHP < 4.3.9, you have to compile PHP with --with-pdflib[=DIR] . DIR is the PDFlib base install directory, defaults to /usr/local.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

PDF_new() creates a new PDFlib object required by most PDF functions.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
PDF


Przykłady

Spis treści

  • Basic Usage Examples
Stałe predefiniowane
Basic Usage Examples
PDF


Basic Usage Examples

Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It is developed for PHP 4 and creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text "Hello world! (says PHP)".

Przykład #1 Hello World example from PDFlib distribution for PHP 4

<?php
$p = PDF_new();

/*  open new PDF file; insert a file name to create the PDF on disk */
if (PDF_begin_document($p, "", "") == 0) {
    die("Error: " . PDF_get_errmsg($p));
}

PDF_set_info($p, "Creator", "hello.php");
PDF_set_info($p, "Author", "Rainer Schaaf");
PDF_set_info($p, "Title", "Hello world (PHP)!");

PDF_begin_page_ext($p, 595, 842, "");

$font = PDF_load_font($p, "Helvetica-Bold", "winansi", "");

PDF_setfont($p, $font, 24.0);
PDF_set_text_pos($p, 50, 700);
PDF_show($p, "Hello world!");
PDF_continue_text($p, "(says PHP)");
PDF_end_page_ext($p, "");

PDF_end_document($p, "");

$buf = PDF_get_buffer($p);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=hello.pdf");
print $buf;

PDF_delete($p);
?>

The following example comes with the PDFlib distribution for PHP 5. It uses the new exception handling and object encapsulation features available in PHP 5. It creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text "Hello world! (says PHP)".

Przykład #2 Hello World example from PDFlib distribution for PHP 5

<?php

try {
    $p = new PDFlib();

    /*  open new PDF file; insert a file name to create the PDF on disk */
    if ($p->begin_document("", "") == 0) {
        die("Error: " . $p->get_errmsg());
    }

    $p->set_info("Creator", "hello.php");
    $p->set_info("Author", "Rainer Schaaf");
    $p->set_info("Title", "Hello world (PHP)!");

    $p->begin_page_ext(595, 842, "");

    $font = $p->load_font("Helvetica-Bold", "winansi", "");

    $p->setfont($font, 24.0);
    $p->set_text_pos(50, 700);
    $p->show("Hello world!");
    $p->continue_text("(says PHP)");
    $p->end_page_ext("");

    $p->end_document("");

    $buf = $p->get_buffer();
    $len = strlen($buf);

    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=hello.pdf");
    print $buf;
}
catch (PDFlibException $e) {
    die("PDFlib exception occurred in hello sample:\n" .
    "[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .
    $e->get_errmsg() . "\n");
}
catch (Exception $e) {
    die($e);
}
$p = 0;
?>

Przykłady
PDF Funkcje
Przykłady


PDF Funkcje

Remarks about Deprecated PDFlib Functions

Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib Reference Manual are supported by PHP 4 with exactly the same meaning and the same parameters. However, with PDFlib Version 5.0.4 or higher all parameters have to be specified. For compatibility reasons, this binding for PDFlib still supports most of the deprecated functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions. The documentation in this section indicates old functions as "Deprecated" and gives the replacement function to be used instead.

Spis treści

  • PDF_activate_item — Activate structure element or other content item
  • PDF_add_annotation — Add annotation [deprecated]
  • PDF_add_bookmark — Add bookmark for current page [deprecated]
  • PDF_add_launchlink — Add launch annotation for current page [deprecated]
  • PDF_add_locallink — Add link annotation for current page [deprecated]
  • PDF_add_nameddest — Create named destination
  • PDF_add_note — Set annotation for current page [deprecated]
  • PDF_add_outline — Add bookmark for current page [deprecated]
  • PDF_add_pdflink — Add file link annotation for current page [deprecated]
  • PDF_add_table_cell — Add a cell to a new or existing table
  • PDF_add_textflow — Create Textflow or add text to existing Textflow
  • PDF_add_thumbnail — Add thumbnail for current page
  • PDF_add_weblink — Add weblink for current page [deprecated]
  • PDF_arc — Draw a counterclockwise circular arc segment
  • PDF_arcn — Draw a clockwise circular arc segment
  • PDF_attach_file — Add file attachment for current page [deprecated]
  • PDF_begin_document — Create new PDF file
  • PDF_begin_font — Start a Type 3 font definition
  • PDF_begin_glyph — Start glyph definition for Type 3 font
  • PDF_begin_item — Open structure element or other content item
  • PDF_begin_layer — Start layer
  • PDF_begin_page_ext — Start new page
  • PDF_begin_page — Start new page [deprecated]
  • PDF_begin_pattern — Start pattern definition
  • PDF_begin_template_ext — Start template definition
  • PDF_begin_template — Start template definition [deprecated]
  • PDF_circle — Draw a circle
  • PDF_clip — Clip to current path
  • PDF_close_image — Close image
  • PDF_close_pdi_page — Close the page handle
  • PDF_close_pdi — Close the input PDF document [deprecated]
  • PDF_close — Close pdf resource [deprecated]
  • PDF_closepath_fill_stroke — Close, fill and stroke current path
  • PDF_closepath_stroke — Close and stroke path
  • PDF_closepath — Close current path
  • PDF_concat — Concatenate a matrix to the CTM
  • PDF_continue_text — Output text in next line
  • PDF_create_3dview — Create 3D view
  • PDF_create_action — Create action for objects or events
  • PDF_create_annotation — Create rectangular annotation
  • PDF_create_bookmark — Create bookmark
  • PDF_create_field — Create form field
  • PDF_create_fieldgroup — Create form field group
  • PDF_create_gstate — Create graphics state object
  • PDF_create_pvf — Create PDFlib virtual file
  • PDF_create_textflow — Create textflow object
  • PDF_curveto — Draw Bezier curve
  • PDF_define_layer — Create layer definition
  • PDF_delete_pvf — Delete PDFlib virtual file
  • PDF_delete_table — Delete table object
  • PDF_delete_textflow — Delete textflow object
  • PDF_delete — Delete PDFlib object
  • PDF_encoding_set_char — Add glyph name and/or Unicode value
  • PDF_end_document — Close PDF file
  • PDF_end_font — Terminate Type 3 font definition
  • PDF_end_glyph — Terminate glyph definition for Type 3 font
  • PDF_end_item — Close structure element or other content item
  • PDF_end_layer — Deactivate all active layers
  • PDF_end_page_ext — Finish page
  • PDF_end_page — Finish page
  • PDF_end_pattern — Finish pattern
  • PDF_end_template — Finish template
  • PDF_endpath — End current path
  • PDF_fill_imageblock — Fill image block with variable data
  • PDF_fill_pdfblock — Fill PDF block with variable data
  • PDF_fill_stroke — Fill and stroke path
  • PDF_fill_textblock — Fill text block with variable data
  • PDF_fill — Fill current path
  • PDF_findfont — Prepare font for later use [deprecated]
  • PDF_fit_image — Place image or template
  • PDF_fit_pdi_page — Place imported PDF page
  • PDF_fit_table — Place table on page
  • PDF_fit_textflow — Format textflow in rectangular area
  • PDF_fit_textline — Place single line of text
  • PDF_get_apiname — Get name of unsuccessfull API function
  • PDF_get_buffer — Get PDF output buffer
  • PDF_get_errmsg — Get error text
  • PDF_get_errnum — Get error number
  • PDF_get_font — Get font [deprecated]
  • PDF_get_fontname — Get font name [deprecated]
  • PDF_get_fontsize — Font handling [deprecated]
  • PDF_get_image_height — Get image height [deprecated]
  • PDF_get_image_width — Get image width [deprecated]
  • PDF_get_majorversion — Get major version number [deprecated]
  • PDF_get_minorversion — Get minor version number [deprecated]
  • PDF_get_parameter — Get string parameter
  • PDF_get_pdi_parameter — Get PDI string parameter [deprecated]
  • PDF_get_pdi_value — Get PDI numerical parameter [deprecated]
  • PDF_get_value — Get numerical parameter
  • PDF_info_font — Query detailed information about a loaded font
  • PDF_info_matchbox — Query matchbox information
  • PDF_info_table — Retrieve table information
  • PDF_info_textflow — Query textflow state
  • PDF_info_textline — Perform textline formatting and query metrics
  • PDF_initgraphics — Reset graphic state
  • PDF_lineto — Draw a line
  • PDF_load_3ddata — Load 3D model
  • PDF_load_font — Search and prepare font
  • PDF_load_iccprofile — Search and prepare ICC profile
  • PDF_load_image — Open image file
  • PDF_makespotcolor — Make spot color
  • PDF_moveto — Set current point
  • PDF_new — Create PDFlib object
  • PDF_open_ccitt — Open raw CCITT image [deprecated]
  • PDF_open_file — Create PDF file [deprecated]
  • PDF_open_gif — Open GIF image [deprecated]
  • PDF_open_image_file — Read image from file [deprecated]
  • PDF_open_image — Use image data [deprecated]
  • PDF_open_jpeg — Open JPEG image [deprecated]
  • PDF_open_memory_image — Open image created with PHP's image functions [not supported]
  • PDF_open_pdi_document — Prepare a pdi document
  • PDF_open_pdi_page — Prepare a page
  • PDF_open_pdi — Open PDF file [deprecated]
  • PDF_open_tiff — Open TIFF image [deprecated]
  • PDF_pcos_get_number — Get value of pCOS path with type number or boolean
  • PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string
  • PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean
  • PDF_place_image — Place image on the page [deprecated]
  • PDF_place_pdi_page — Place PDF page [deprecated]
  • PDF_process_pdi — Process imported PDF document
  • PDF_rect — Draw rectangle
  • PDF_restore — Restore graphics state
  • PDF_resume_page — Resume page
  • PDF_rotate — Rotate coordinate system
  • PDF_save — Save graphics state
  • PDF_scale — Scale coordinate system
  • PDF_set_border_color — Set border color of annotations [deprecated]
  • PDF_set_border_dash — Set border dash style of annotations [deprecated]
  • PDF_set_border_style — Set border style of annotations [deprecated]
  • PDF_set_char_spacing — Set character spacing [deprecated]
  • PDF_set_duration — Set duration between pages [deprecated]
  • PDF_set_gstate — Activate graphics state object
  • PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]
  • PDF_set_info_author — Fill the author document info field [deprecated]
  • PDF_set_info_creator — Fill the creator document info field [deprecated]
  • PDF_set_info_keywords — Fill the keywords document info field [deprecated]
  • PDF_set_info_subject — Fill the subject document info field [deprecated]
  • PDF_set_info_title — Fill the title document info field [deprecated]
  • PDF_set_info — Fill document info field
  • PDF_set_layer_dependency — Define relationships among layers
  • PDF_set_leading — Set distance between text lines [deprecated]
  • PDF_set_parameter — Set string parameter
  • PDF_set_text_matrix — Set text matrix [deprecated]
  • PDF_set_text_pos — Set text position
  • PDF_set_text_rendering — Determine text rendering [deprecated]
  • PDF_set_text_rise — Set text rise [deprecated]
  • PDF_set_value — Set numerical parameter
  • PDF_set_word_spacing — Set spacing between words [deprecated]
  • PDF_setcolor — Set fill and stroke color
  • PDF_setdash — Set simple dash pattern
  • PDF_setdashpattern — Set dash pattern
  • PDF_setflat — Set flatness
  • PDF_setfont — Set font
  • PDF_setgray_fill — Set fill color to gray [deprecated]
  • PDF_setgray_stroke — Set stroke color to gray [deprecated]
  • PDF_setgray — Set color to gray [deprecated]
  • PDF_setlinecap — Set linecap parameter
  • PDF_setlinejoin — Set linejoin parameter
  • PDF_setlinewidth — Set line width
  • PDF_setmatrix — Set current transformation matrix
  • PDF_setmiterlimit — Set miter limit
  • PDF_setpolydash — Set complicated dash pattern [deprecated]
  • PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]
  • PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]
  • PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]
  • PDF_shading_pattern — Define shading pattern
  • PDF_shading — Define blend
  • PDF_shfill — Fill area with shading
  • PDF_show_boxed — Output text in a box [deprecated]
  • PDF_show_xy — Output text at given position
  • PDF_show — Output text at current position
  • PDF_skew — Skew the coordinate system
  • PDF_stringwidth — Return width of text
  • PDF_stroke — Stroke path
  • PDF_suspend_page — Suspend page
  • PDF_translate — Set origin of coordinate system
  • PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8
  • PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16
  • PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16
Basic Usage Examples
PDF_activate_item
PDF


Activate structure element or other content item

PDF Funkcje
PDF_add_annotation
PDF Funkcje
PHP Manual

PDF_activate_item

(PECL pdflib >= 2.0.0)

PDF_activate_item — Activate structure element or other content item

Opis

bool PDF_activate_item ( resource $pdfdoc , int $id )

Activates a previously created structure element or other content item. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF Funkcje
PDF_add_annotation
PDF Funkcje


Add annotation [deprecated]

PDF_activate_item
PDF_add_bookmark
PDF Funkcje
PHP Manual

PDF_add_annotation

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_annotation — Add annotation [deprecated]

Opis

This function is deprecated, use PDF_create_annotation() with type=Text instead.

PDF_activate_item
PDF_add_bookmark
PDF Funkcje


Add bookmark for current page [deprecated]

PDF_add_annotation
PDF_add_launchlink
PDF Funkcje
PHP Manual

PDF_add_bookmark

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_add_bookmark — Add bookmark for current page [deprecated]

Opis

This function is deprecated since PDFlib version 6, use PDF_create_bookmark() instead.

PDF_add_annotation
PDF_add_launchlink
PDF Funkcje


Add launch annotation for current page [deprecated]

PDF_add_bookmark
PDF_add_locallink
PDF Funkcje
PHP Manual

PDF_add_launchlink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_launchlink — Add launch annotation for current page [deprecated]

Opis

bool PDF_add_launchlink ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $filename )

Adds a link to a web resource.

This function is deprecated since PDFlib version 6,
use PDF_create_action() with
type=Launch and
PDF_create_annotation() with
type=Link instead.

PDF_add_bookmark
PDF_add_locallink
PDF Funkcje


Add link annotation for current page [deprecated]

PDF_add_launchlink
PDF_add_nameddest
PDF Funkcje
PHP Manual

PDF_add_locallink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_locallink — Add link annotation for current page [deprecated]

Opis

bool PDF_add_locallink ( resource $pdfdoc , float $lowerleftx , float $lowerlefty , float $upperrightx , float $upperrighty , int $page , string $dest )

Add a link annotation to a target within the current PDF file. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with type=GoTo
and PDF_create_annotation() with
type=Link instead.

PDF_add_launchlink
PDF_add_nameddest
PDF Funkcje


Create named destination

PDF_add_locallink
PDF_add_note
PDF Funkcje
PHP Manual

PDF_add_nameddest

(PECL pdflib >= 2.0.0)

PDF_add_nameddest — Create named destination

Opis

bool PDF_add_nameddest ( resource $pdfdoc , string $name , string $optlist )

Creates a named destination on an arbitrary page in the current document. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_add_locallink
PDF_add_note
PDF Funkcje


Set annotation for current page [deprecated]

PDF_add_nameddest
PDF_add_outline
PDF Funkcje
PHP Manual

PDF_add_note

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_note — Set annotation for current page [deprecated]

Opis

bool PDF_add_note ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $contents , string $title , string $icon , int $open )

Sets an annotation for the current page. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use PDF_create_annotation() with type=Text instead.

PDF_add_nameddest
PDF_add_outline
PDF Funkcje


Add bookmark for current page [deprecated]

PDF_add_note
PDF_add_pdflink
PDF Funkcje
PHP Manual

PDF_add_outline

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_outline — Add bookmark for current page [deprecated]

Opis

This function is deprecated, use PDF_create_bookmark() instead.

PDF_add_note
PDF_add_pdflink
PDF Funkcje


Add file link annotation for current page [deprecated]

PDF_add_outline
PDF_add_table_cell
PDF Funkcje
PHP Manual

PDF_add_pdflink

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_pdflink — Add file link annotation for current page [deprecated]

Opis

bool PDF_add_pdflink ( resource $pdfdoc , float $bottom_left_x , float $bottom_left_y , float $up_right_x , float $up_right_y , string $filename , int $page , string $dest )

Add a file link annotation to a PDF target. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with
type=GoToR and
PDF_create_annotation() with
type=Link instead.

PDF_add_outline
PDF_add_table_cell
PDF Funkcje


Add a cell to a new or existing table

PDF_add_pdflink
PDF_add_textflow
PDF Funkcje
PHP Manual

PDF_add_table_cell

(PECL pdflib >= 2.1.0)

PDF_add_table_cell — Add a cell to a new or existing table

Opis

int PDF_add_table_cell ( resource $pdfdoc , int $table , int $column , int $row , string $text , string $optlist )

Adds a cell to a new or existing table.

PDF_add_pdflink
PDF_add_textflow
PDF Funkcje


Create Textflow or add text to existing Textflow

PDF_add_table_cell
PDF_add_thumbnail
PDF Funkcje
PHP Manual

PDF_add_textflow

(PECL pdflib >= 2.1.0)

PDF_add_textflow — Create Textflow or add text to existing Textflow

Opis

int PDF_add_textflow ( resource $pdfdoc , int $textflow , string $text , string $optlist )

Creates a Textflow object, or adds text and explicit options to an existing Textflow.

PDF_add_table_cell
PDF_add_thumbnail
PDF Funkcje


Add thumbnail for current page

PDF_add_textflow
PDF_add_weblink
PDF Funkcje
PHP Manual

PDF_add_thumbnail

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_thumbnail — Add thumbnail for current page

Opis

bool PDF_add_thumbnail ( resource $pdfdoc , int $image )

Adds an existing image as thumbnail for the current page. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_add_textflow
PDF_add_weblink
PDF Funkcje


Add weblink for current page [deprecated]

PDF_add_thumbnail
PDF_arc
PDF Funkcje
PHP Manual

PDF_add_weblink

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_weblink — Add weblink for current page [deprecated]

Opis

bool PDF_add_weblink ( resource $pdfdoc , float $lowerleftx , float $lowerlefty , float $upperrightx , float $upperrighty , string $url )

Adds a weblink annotation to a target url on the Web. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with type=URI
and PDF_create_annotation() with
type=Link instead.

PDF_add_thumbnail
PDF_arc
PDF Funkcje


Draw a counterclockwise circular arc segment

PDF_add_weblink
PDF_arcn
PDF Funkcje
PHP Manual

PDF_arc

(PHP 4, PECL pdflib >= 1.0.0)

PDF_arc — Draw a counterclockwise circular arc segment

Opis

bool PDF_arc ( resource $p , float $x , float $y , float $r , float $alpha , float $beta )

Adds a counterclockwise circular arc.

PDF_add_weblink
PDF_arcn
PDF Funkcje


Draw a clockwise circular arc segment

PDF_arc
PDF_attach_file
PDF Funkcje
PHP Manual

PDF_arcn

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_arcn — Draw a clockwise circular arc segment

Opis

bool PDF_arcn ( resource $p , float $x , float $y , float $r , float $alpha , float $beta )

Except for the drawing direction, this function behaves exactly like PDF_arc().

PDF_arc
PDF_attach_file
PDF Funkcje


Add file attachment for current page [deprecated]

PDF_arcn
PDF_begin_document
PDF Funkcje
PHP Manual

PDF_attach_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_attach_file — Add file attachment for current page [deprecated]

Opis

bool PDF_attach_file ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $filename , string $description , string $author , string $mimetype , string $icon )

Adds a file attachment annotation. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use PDF_create_annotation() with type=FileAttachment instead.

PDF_arcn
PDF_begin_document
PDF Funkcje


Create new PDF file

PDF_attach_file
PDF_begin_font
PDF Funkcje
PHP Manual

PDF_begin_document

(PECL pdflib >= 2.0.0)

PDF_begin_document — Create new PDF file

Opis

int PDF_begin_document ( resource $pdfdoc , string $filename , string $optlist )

Creates a new PDF file subject to various options.

PDF_attach_file
PDF_begin_font
PDF Funkcje


Start a Type 3 font definition

PDF_begin_document
PDF_begin_glyph
PDF Funkcje
PHP Manual

PDF_begin_font

(PECL pdflib >= 2.0.0)

PDF_begin_font — Start a Type 3 font definition

Opis

bool PDF_begin_font ( resource $pdfdoc , string $filename , float $a , float $b , float $c , float $d , float $e , float $f , string $optlist )

Starts a Type 3 font definition.

PDF_begin_document
PDF_begin_glyph
PDF Funkcje


Start glyph definition for Type 3 font

PDF_begin_font
PDF_begin_item
PDF Funkcje
PHP Manual

PDF_begin_glyph

(PECL pdflib >= 2.0.0)

PDF_begin_glyph — Start glyph definition for Type 3 font

Opis

bool PDF_begin_glyph ( resource $pdfdoc , string $glyphname , float $wx , float $llx , float $lly , float $urx , float $ury )

Starts a glyph definition for a Type 3 font.

PDF_begin_font
PDF_begin_item
PDF Funkcje


Open structure element or other content item

PDF_begin_glyph
PDF_begin_layer
PDF Funkcje
PHP Manual

PDF_begin_item

(PECL pdflib >= 2.0.0)

PDF_begin_item — Open structure element or other content item

Opis

int PDF_begin_item ( resource $pdfdoc , string $tag , string $optlist )

Opens a structure element or other content item with attributes supplied as options.

PDF_begin_glyph
PDF_begin_layer
PDF Funkcje


Start layer

PDF_begin_item
PDF_begin_page_ext
PDF Funkcje
PHP Manual

PDF_begin_layer

(PECL pdflib >= 2.0.0)

PDF_begin_layer — Start layer

Opis

bool PDF_begin_layer ( resource $pdfdoc , int $layer )

Starts a layer for subsequent output on the page. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function requires PDF 1.5.

PDF_begin_item
PDF_begin_page_ext
PDF Funkcje


Start new page

PDF_begin_layer
PDF_begin_page
PDF Funkcje
PHP Manual

PDF_begin_page_ext

(PECL pdflib >= 2.0.0)

PDF_begin_page_ext — Start new page

Opis

bool PDF_begin_page_ext ( resource $pdfdoc , float $width , float $height , string $optlist )

Adds a new page to the document, and specifies various options. The parameters width and height are the dimensions of the new page in points. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Common Page Sizes in Points
name | size
A0 | 2380 x 3368
A1 | 1684 x 2380
A2 | 1190 x 1684
A3 | 842 x 1190
A4 | 595 x 842
A5 | 421 x 595
A6 | 297 x 421
B5 | 501 x 709
letter (8.5" x 11") | 612 x 792
legal (8.5" x 14") | 612 x 1008
ledger (17" x 11") | 1224 x 792
11" x 17" | 792 x 1224

PDF_begin_layer
PDF_begin_page
PDF Funkcje


Start new page [deprecated]

PDF_begin_page_ext
PDF_begin_pattern
PDF Funkcje
PHP Manual

PDF_begin_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_begin_page — Start new page [deprecated]

Opis

bool PDF_begin_page ( resource $pdfdoc , float $width , float $height )

Adds a new page to the document. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use PDF_begin_page_ext() instead.

PDF_begin_page_ext
PDF_begin_pattern
PDF Funkcje


Start pattern definition

PDF_begin_page
PDF_begin_template_ext
PDF Funkcje
PHP Manual

PDF_begin_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_pattern — Start pattern definition

Opis

int PDF_begin_pattern ( resource $pdfdoc , float $width , float $height , float $xstep , float $ystep , int $painttype )

Starts a new pattern definition.

PDF_begin_page
PDF_begin_template_ext
PDF Funkcje


Start template definition

PDF_begin_pattern
PDF_begin_template
PDF Funkcje
PHP Manual

PDF_begin_template_ext

(PECL pdflib >= 2.1.0)

PDF_begin_template_ext — Start template definition

Opis

int PDF_begin_template_ext ( resource $pdfdoc , float $width , float $height , string $optlist )

Starts a new template definition.

PDF_begin_pattern
PDF_begin_template
PDF Funkcje


Start template definition [deprecated]

PDF_begin_template_ext
PDF_circle
PDF Funkcje
PHP Manual

PDF_begin_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_template — Start template definition [deprecated]

Opis

int PDF_begin_template ( resource $pdfdoc , float $width , float $height )

Starts a new template definition.

This function is deprecated since PDFlib version 7, use PDF_begin_template_ext() instead.

PDF_begin_template_ext
PDF_circle
PDF Funkcje


Draw a circle

PDF_begin_template
PDF_clip
PDF Funkcje
PHP Manual

PDF_circle

(PHP 4, PECL pdflib >= 1.0.0)

PDF_circle — Draw a circle

Opis

bool PDF_circle ( resource $pdfdoc , float $x , float $y , float $r )

Adds a circle. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_begin_template
PDF_clip
PDF Funkcje


Clip to current path

PDF_circle
PDF_close_image
PDF Funkcje
PHP Manual

PDF_clip

(PHP 4, PECL pdflib >= 1.0.0)

PDF_clip — Clip to current path

Opis

bool PDF_clip ( resource $p )

Uses the current path as clipping path, and terminate the path. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_circle
PDF_close_image
PDF Funkcje


Close image

PDF_clip
PDF_close_pdi_page
PDF Funkcje
PHP Manual

PDF_close_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close_image — Close image

Opis

bool PDF_close_image ( resource $p , int $image )

Closes an image retrieved with the PDF_open_image() function.

PDF_clip
PDF_close_pdi_page
PDF Funkcje


Close the page handle

PDF_close_image
PDF_close_pdi
PDF Funkcje
PHP Manual

PDF_close_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi_page — Close the page handle

Opis

bool PDF_close_pdi_page ( resource $p , int $page )

Closes the page handle, and frees all page-related resources. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_close_image
PDF_close_pdi
PDF Funkcje


Close the input PDF document [deprecated]

PDF_close_pdi_page
PDF_close
PDF Funkcje
PHP Manual

PDF_close_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi — Close the input PDF document [deprecated]

Opis

bool PDF_close_pdi ( resource $p , int $doc )

Closes all open page handles, and closes the input PDF document. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 7, use PDF_close_pdi_document() instead.

PDF_close_pdi_page
PDF_close
PDF Funkcje


Close pdf resource [deprecated]

PDF_close_pdi
PDF_closepath_fill_stroke
PDF Funkcje
PHP Manual

PDF_close

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close — Close pdf resource [deprecated]

Opis

bool PDF_close ( resource $p )

Closes the generated PDF file, and frees all document-related resources. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use PDF_end_document() instead.

PDF_close_pdi
PDF_closepath_fill_stroke
PDF Funkcje


Close, fill and stroke current path

PDF_close
PDF_closepath_stroke
PDF Funkcje
PHP Manual

PDF_closepath_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath_fill_stroke — Close, fill and stroke current path

Opis

bool PDF_closepath_fill_stroke ( resource $p )

Closes the path, fills, and strokes it. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_close
PDF_closepath_stroke
PDF Funkcje


Close and stroke path

PDF_closepath_fill_stroke
PDF_closepath
PDF Funkcje
PHP Manual

PDF_closepath_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath_stroke — Close and stroke path

Opis

bool PDF_closepath_stroke ( resource $p )

Closes the path, and strokes it. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_closepath_fill_stroke
PDF_closepath
PDF Funkcje


Close current path

PDF_closepath_stroke
PDF_concat
PDF Funkcje
PHP Manual

PDF_closepath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath — Close current path

Opis

bool PDF_closepath ( resource $p )

Closes the current path. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_closepath_stroke
PDF_concat
PDF Funkcje


Concatenate a matrix to the CTM

PDF_closepath
PDF_continue_text
PDF Funkcje
PHP Manual

PDF_concat

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_concat — Concatenate a matrix to the CTM

Opis

bool PDF_concat ( resource $p , float $a , float $b , float $c , float $d , float $e , float $f )

Concatenates a matrix to the current transformation matrix (CTM). Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_closepath
PDF_continue_text
PDF Funkcje


Output text in next line

PDF_concat
PDF_create_3dview
PDF Funkcje
PHP Manual

PDF_continue_text

(PHP 4, PECL pdflib >= 1.0.0)

PDF_continue_text — Output text in next line

Opis

bool PDF_continue_text ( resource $p , string $text )

Prints text at the next line. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_concat
PDF_create_3dview
PDF Funkcje


Create 3D view

PDF_continue_text
PDF_create_action
PDF Funkcje
PHP Manual

PDF_create_3dview

(PECL pdflib >= 2.1.0)

PDF_create_3dview — Create 3D view

Opis

int PDF_create_3dview ( resource $pdfdoc , string $username , string $optlist )

Creates a 3D view.

This function requires PDF 1.6.

PDF_continue_text
PDF_create_action
PDF Funkcje


Create action for objects or events

PDF_create_3dview
PDF_create_annotation
PDF Funkcje
PHP Manual

PDF_create_action

(PECL pdflib >= 2.0.0)

PDF_create_action — Create action for objects or events

Opis

int PDF_create_action ( resource $pdfdoc , string $type , string $optlist )

Creates an action which can be applied to various objects and events.

PDF_create_3dview
PDF_create_annotation
PDF Funkcje


Create rectangular annotation

PDF_create_action
PDF_create_bookmark
PDF Funkcje
PHP Manual

PDF_create_annotation

(PECL pdflib >= 2.0.0)

PDF_create_annotation — Create rectangular annotation

Opis

bool PDF_create_annotation ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $type , string $optlist )

Creates a rectangular annotation on the current page.

PDF_create_action
PDF_create_bookmark
PDF Funkcje


Create bookmark

PDF_create_annotation
PDF_create_field
PDF Funkcje
PHP Manual

PDF_create_bookmark

(PECL pdflib >= 2.0.0)

PDF_create_bookmark — Create bookmark

Opis

int PDF_create_bookmark ( resource $pdfdoc , string $text , string $optlist )

Creates a bookmark subject to various options.

PDF_create_annotation
PDF_create_field
PDF Funkcje


Create form field

PDF_create_bookmark
PDF_create_fieldgroup
PDF Funkcje
PHP Manual

PDF_create_field

(PECL pdflib >= 2.0.0)

PDF_create_field — Create form field

Opis

bool PDF_create_field ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $name , string $type , string $optlist )

Creates a form field on the current page subject to various options.

PDF_create_bookmark
PDF_create_fieldgroup
PDF Funkcje


Create form field group

PDF_create_field
PDF_create_gstate
PDF Funkcje
PHP Manual

PDF_create_fieldgroup

(PECL pdflib >= 2.0.0)

PDF_create_fieldgroup — Create form field group

Opis

bool PDF_create_fieldgroup ( resource $pdfdoc , string $name , string $optlist )

Creates a form field group subject to various options.

PDF_create_field
PDF_create_gstate
PDF Funkcje


Create graphics state object

PDF_create_fieldgroup
PDF_create_pvf
PDF Funkcje
PHP Manual

PDF_create_gstate

(PECL pdflib >= 2.0.0)

PDF_create_gstate — Create graphics state object

Opis

int PDF_create_gstate ( resource $pdfdoc , string $optlist )

Creates a graphics state object subject to various options.

PDF_create_fieldgroup
PDF_create_pvf
PDF Funkcje


Create PDFlib virtual file

PDF_create_gstate
PDF_create_textflow
PDF Funkcje
PHP Manual

PDF_create_pvf

(PECL pdflib >= 2.0.0)

PDF_create_pvf — Create PDFlib virtual file

Opis

bool PDF_create_pvf ( resource $pdfdoc , string $filename , string $data , string $optlist )

Creates a named virtual read-only file from data provided in memory.

PDF_create_gstate
PDF_create_textflow
PDF Funkcje


Create textflow object

PDF_create_pvf
PDF_curveto
PDF Funkcje
PHP Manual

PDF_create_textflow

(PECL pdflib >= 2.0.0)

PDF_create_textflow — Create textflow object

Opis

int PDF_create_textflow ( resource $pdfdoc , string $text , string $optlist )

Preprocesses text for later formatting and creates a textflow object.

PDF_create_pvf
PDF_curveto
PDF Funkcje


Draw Bezier curve

PDF_create_textflow
PDF_define_layer
PDF Funkcje
PHP Manual

PDF_curveto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_curveto — Draw Bezier curve

Opis

bool PDF_curveto ( resource $p , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Draws a Bezier curve from the current point, using 3 more control points. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_create_textflow
PDF_define_layer
PDF Funkcje


Create layer definition

PDF_curveto
PDF_delete_pvf
PDF Funkcje
PHP Manual

PDF_define_layer

(PECL pdflib >= 2.0.0)

PDF_define_layer — Create layer definition

Opis

int PDF_define_layer ( resource $pdfdoc , string $name , string $optlist )

Creates a new layer definition.

This function requires PDF 1.5.

PDF_curveto
PDF_delete_pvf
PDF Funkcje


Delete PDFlib virtual file

PDF_define_layer
PDF_delete_table
PDF Funkcje
PHP Manual

PDF_delete_pvf

(PECL pdflib >= 2.0.0)

PDF_delete_pvf — Delete PDFlib virtual file

Opis

int PDF_delete_pvf ( resource $pdfdoc , string $filename )

Deletes a named virtual file and frees its data structures (but not the contents).

PDF_define_layer
PDF_delete_table
PDF Funkcje


Delete table object

PDF_delete_pvf
PDF_delete_textflow
PDF Funkcje
PHP Manual

PDF_delete_table

(PECL pdflib >= 2.1.0)

PDF_delete_table — Delete table object

Opis

bool PDF_delete_table ( resource $pdfdoc , int $table , string $optlist )

Deletes a table and all associated data structures.

PDF_delete_pvf
PDF_delete_textflow
PDF Funkcje


Delete textflow object

PDF_delete_table
PDF_delete
PDF Funkcje
PHP Manual

PDF_delete_textflow

(PECL pdflib >= 2.0.0)

PDF_delete_textflow — Delete textflow object

Opis

bool PDF_delete_textflow ( resource $pdfdoc , int $textflow )

Deletes a textflow and the associated data structures.

PDF_delete_table
PDF_delete
PDF Funkcje


Delete PDFlib object

PDF_delete_textflow
PDF_encoding_set_char
PDF Funkcje
PHP Manual

PDF_delete

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_delete — Delete PDFlib object

Opis

bool PDF_delete ( resource $pdfdoc )

Deletes a PDFlib object, and frees all internal resources. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_delete_textflow
PDF_encoding_set_char
PDF Funkcje


Add glyph name and/or Unicode value

PDF_delete
PDF_end_document
PDF Funkcje
PHP Manual

PDF_encoding_set_char

(PECL pdflib >= 2.0.0)

PDF_encoding_set_char — Add glyph name and/or Unicode value

Opis

bool PDF_encoding_set_char ( resource $pdfdoc , string $encoding , int $slot , string $glyphname , int $uv )

Adds a glyph name and/or Unicode value to a custom encoding.

PDF_delete
PDF_end_document
PDF Funkcje


Close PDF file

PDF_encoding_set_char
PDF_end_font
PDF Funkcje
PHP Manual

PDF_end_document

(PECL pdflib >= 2.0.0)

PDF_end_document — Close PDF file

Opis

bool PDF_end_document ( resource $pdfdoc , string $optlist )

Closes the generated PDF file and applies various options.

PDF_encoding_set_char
PDF_end_font
PDF Funkcje


Terminate Type 3 font definition

PDF_end_document
PDF_end_glyph
PDF Funkcje
PHP Manual

PDF_end_font

(PECL pdflib >= 2.0.0)

PDF_end_font — Terminate Type 3 font definition

Opis

bool PDF_end_font ( resource $pdfdoc )

Terminates a Type 3 font definition.

PDF_end_document
PDF_end_glyph
PDF Funkcje


Terminate glyph definition for Type 3 font

PDF_end_font
PDF_end_item
PDF Funkcje
PHP Manual

PDF_end_glyph

(PECL pdflib >= 2.0.0)

PDF_end_glyph — Terminate glyph definition for Type 3 font

Opis

bool PDF_end_glyph ( resource $pdfdoc )

Terminates a glyph definition for a Type 3 font.

PDF_end_font
PDF_end_item
PDF Funkcje


Close structure element or other content item

PDF_end_glyph
PDF_end_layer
PDF Funkcje
PHP Manual

PDF_end_item

(PECL pdflib >= 2.0.0)

PDF_end_item — Close structure element or other content item

Opis

bool PDF_end_item ( resource $pdfdoc , int $id )

Closes a structure element or other content item.

PDF_end_glyph
PDF_end_layer
PDF Funkcje


Deactivate all active layers

PDF_end_item
PDF_end_page_ext
PDF Funkcje
PHP Manual

PDF_end_layer

(PECL pdflib >= 2.0.0)

PDF_end_layer — Deactivate all active layers

Opis

bool PDF_end_layer ( resource $pdfdoc )

Deactivates all active layers. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function requires PDF 1.5.

PDF_end_item
PDF_end_page_ext
PDF Funkcje


Finish page

PDF_end_layer
PDF_end_page
PDF Funkcje
PHP Manual

PDF_end_page_ext

(PECL pdflib >= 2.0.0)

PDF_end_page_ext — Finish page

Opis

bool PDF_end_page_ext ( resource $pdfdoc , string $optlist )

Finishes a page, and applies various options. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_end_layer
PDF_end_page
PDF Funkcje


Finish page

PDF_end_page_ext
PDF_end_pattern
PDF Funkcje
PHP Manual

PDF_end_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_end_page — Finish page

Opis

bool PDF_end_page ( resource $p )

Finishes the page. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_end_page_ext
PDF_end_pattern
PDF Funkcje


Finish pattern

PDF_end_page
PDF_end_template
PDF Funkcje
PHP Manual

PDF_end_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_pattern — Finish pattern

Opis

bool PDF_end_pattern ( resource $p )

Finishes the pattern definition. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_end_page
PDF_end_template
PDF Funkcje


Finish template

PDF_end_pattern
PDF_endpath
PDF Funkcje
PHP Manual

PDF_end_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_template — Finish template

Opis

bool PDF_end_template ( resource $p )

Finishes a template definition. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_end_pattern
PDF_endpath
PDF Funkcje


End current path

PDF_end_template
PDF_fill_imageblock
PDF Funkcje
PHP Manual

PDF_endpath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_endpath — End current path

Opis

bool PDF_endpath ( resource $p )

Ends the current path without filling or stroking it.

PDF_end_template
PDF_fill_imageblock
PDF Funkcje


Fill image block with variable data

PDF_endpath
PDF_fill_pdfblock
PDF Funkcje
PHP Manual

PDF_fill_imageblock

(PECL pdflib >= 2.0.0)

PDF_fill_imageblock — Fill image block with variable data

Opis

int PDF_fill_imageblock ( resource $pdfdoc , int $page , string $blockname , int $image , string $optlist )

Fills an image block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

PDF_endpath
PDF_fill_pdfblock
PDF Funkcje


Fill PDF block with variable data

PDF_fill_imageblock
PDF_fill_stroke
PDF Funkcje
PHP Manual

PDF_fill_pdfblock

(PECL pdflib >= 2.0.0)

PDF_fill_pdfblock — Fill PDF block with variable data

Opis

int PDF_fill_pdfblock ( resource $pdfdoc , int $page , string $blockname , int $contents , string $optlist )

Fills a PDF block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

PDF_fill_imageblock
PDF_fill_stroke
PDF Funkcje


Fill and stroke path

PDF_fill_pdfblock
PDF_fill_textblock
PDF Funkcje
PHP Manual

PDF_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_fill_stroke — Fill and stroke path

Opis

bool PDF_fill_stroke ( resource $p )

Fills and strokes the current path with the current fill and stroke color. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_fill_pdfblock
PDF_fill_textblock
PDF Funkcje


Fill text block with variable data

PDF_fill_stroke
PDF_fill
PDF Funkcje
PHP Manual

PDF_fill_textblock

(PECL pdflib >= 2.0.0)

PDF_fill_textblock — Fill text block with variable data

Opis

int PDF_fill_textblock ( resource $pdfdoc , int $page , string $blockname , string $text , string $optlist )

Fills a text block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).

PDF_fill_stroke
PDF_fill
PDF Funkcje


Fill current path

PDF_fill_textblock
PDF_findfont
PDF Funkcje
PHP Manual

PDF_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_fill — Fill current path

Opis

bool PDF_fill ( resource $p )

Fills the interior of the current path with the current fill color. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_fill_textblock
PDF_findfont
PDF Funkcje


Prepare font for later use [deprecated]

PDF_fill
PDF_fit_image
PDF Funkcje
PHP Manual

PDF_findfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_findfont — Prepare font for later use [deprecated]

Opis

int PDF_findfont ( resource $p , string $fontname , string $encoding , int $embed )

Search for a font and prepare it for later use with PDF_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of builtin, macroman, winansi, host, a user-defined encoding name or the name of a CMap. Parameter embed is optional before PHP 4.3.5 or with PDFlib less than 5.

This function is deprecated since PDFlib version 5, use PDF_load_font() instead.

PDF_fill
PDF_fit_image
PDF Funkcje


Place image or template

PDF_findfont
PDF_fit_pdi_page
PDF Funkcje
PHP Manual

PDF_fit_image

(PECL pdflib >= 2.0.0)

PDF_fit_image — Place image or template

Opis

bool PDF_fit_image ( resource $pdfdoc , int $image , float $x , float $y , string $optlist )

Places an image or template on the page, subject to various options. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_findfont
PDF_fit_pdi_page
PDF Funkcje


Place imported PDF page

PDF_fit_image
PDF_fit_table
PDF Funkcje
PHP Manual

PDF_fit_pdi_page

(PECL pdflib >= 2.0.0)

PDF_fit_pdi_page — Place imported PDF page

Opis

bool PDF_fit_pdi_page ( resource $pdfdoc , int $page , float $x , float $y , string $optlist )

Places an imported PDF page on the page, subject to various options. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_fit_image
PDF_fit_table
PDF Funkcje


Place table on page

PDF_fit_pdi_page
PDF_fit_textflow
PDF Funkcje
PHP Manual

PDF_fit_table

(PECL pdflib >= 2.1.0)

PDF_fit_table — Place table on page

Opis

string PDF_fit_table ( resource $pdfdoc , int $table , float $llx , float $lly , float $urx , float $ury , string $optlist )

Places a table on the page fully or partially.

PDF_fit_pdi_page
PDF_fit_textflow
PDF Funkcje


Format textflow in rectangular area

PDF_fit_table
PDF_fit_textline
PDF Funkcje
PHP Manual

PDF_fit_textflow

(PECL pdflib >= 2.0.0)

PDF_fit_textflow — Format textflow in rectangular area

Opis

string PDF_fit_textflow ( resource $pdfdoc , int $textflow , float $llx , float $lly , float $urx , float $ury , string $optlist )

Formats the next portion of a textflow into a rectangular area.

PDF_fit_table
PDF_fit_textline
PDF Funkcje


Place single line of text

PDF_fit_textflow
PDF_get_apiname
PDF Funkcje
PHP Manual

PDF_fit_textline

(PECL pdflib >= 2.0.0)

PDF_fit_textline — Place single line of text

Opis

bool PDF_fit_textline ( resource $pdfdoc , string $text , float $x , float $y , string $optlist )

Places a single line of text on the page, subject to various options. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_fit_textflow
PDF_get_apiname
PDF Funkcje


Get name of unsuccessfull API function

PDF_fit_textline
PDF_get_buffer
PDF Funkcje
PHP Manual

PDF_get_apiname

(PECL pdflib >= 2.0.0)

PDF_get_apiname — Get name of unsuccessfull API function

Opis

string PDF_get_apiname ( resource $pdfdoc )

Gets the name of the API function which threw the last exception or failed.

PDF_fit_textline
PDF_get_buffer
PDF Funkcje


Get PDF output buffer

PDF_get_apiname
PDF_get_errmsg
PDF Funkcje
PHP Manual

PDF_get_buffer

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_buffer — Get PDF output buffer

Opis

string PDF_get_buffer ( resource $p )

Fetches the buffer containing the generated PDF data.

PDF_get_apiname
PDF_get_errmsg
PDF Funkcje


Get error text

PDF_get_buffer
PDF_get_errnum
PDF Funkcje
PHP Manual

PDF_get_errmsg

(PECL pdflib >= 2.0.0)

PDF_get_errmsg — Get error text

Opis

string PDF_get_errmsg ( resource $pdfdoc )

Gets the text of the last thrown exception or the reason for a failed function call.

PDF_get_buffer
PDF_get_errnum
PDF Funkcje


Get error number

PDF_get_errmsg
PDF_get_font
PDF Funkcje
PHP Manual

PDF_get_errnum

(PECL pdflib >= 2.0.0)

PDF_get_errnum — Get error number

Opis

int PDF_get_errnum ( resource $pdfdoc )

Gets the number of the last thrown exception or the reason for a failed function call.

PDF_get_errmsg
PDF_get_font
PDF Funkcje


Get font [deprecated]

PDF_get_errnum
PDF_get_fontname
PDF Funkcje
PHP Manual

PDF_get_font

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_font — Get font [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter font instead.

PDF_get_errnum
PDF_get_fontname
PDF Funkcje


Get font name [deprecated]

PDF_get_font
PDF_get_fontsize
PDF Funkcje
PHP Manual

PDF_get_fontname

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontname — Get font name [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_get_parameter() with the parameter fontname instead.

PDF_get_font
PDF_get_fontsize
PDF Funkcje


Font handling [deprecated]

PDF_get_fontname
PDF_get_image_height
PDF Funkcje
PHP Manual

PDF_get_fontsize

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontsize — Font handling [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter fontsizeinstead.

PDF_get_fontname
PDF_get_image_height
PDF Funkcje


Get image height [deprecated]

PDF_get_fontsize
PDF_get_image_width
PDF Funkcje
PHP Manual

PDF_get_image_height

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_image_height — Get image height [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter imageheight instead.

PDF_get_fontsize
PDF_get_image_width
PDF Funkcje


Get image width [deprecated]

PDF_get_image_height
PDF_get_majorversion
PDF Funkcje
PHP Manual

PDF_get_image_width

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_image_width — Get image width [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter imagewidth instead.

PDF_get_image_height
PDF_get_majorversion
PDF Funkcje


Get major version number [deprecated]

PDF_get_image_width
PDF_get_minorversion
PDF Funkcje
PHP Manual

PDF_get_majorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

PDF_get_majorversion — Get major version number [deprecated]

Opis

int PDF_get_majorversion ( void )

This function is deprecated since PDFlib version 5, use PDF_get_value() with the parameter major instead.

PDF_get_image_width
PDF_get_minorversion
PDF Funkcje


Get minor version number [deprecated]

PDF_get_majorversion
PDF_get_parameter
PDF Funkcje
PHP Manual

PDF_get_minorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

PDF_get_minorversion — Get minor version number [deprecated]

Opis

int PDF_get_minorversion ( void )

Returns the minor version number of the PDFlib version.

This function is deprecated since PDFlib version 5, use PDF_get_value() with the parameter minor instead.

PDF_get_majorversion
PDF_get_parameter
PDF Funkcje


Get string parameter

PDF_get_minorversion
PDF_get_pdi_parameter
PDF Funkcje
PHP Manual

PDF_get_parameter

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_get_parameter — Get string parameter

Opis

string PDF_get_parameter ( resource $p , string $key , float $modifier )

Gets the contents of some PDFlib parameter with string type.

PDF_get_minorversion
PDF_get_pdi_parameter
PDF Funkcje


Get PDI string parameter [deprecated]

PDF_get_parameter
PDF_get_pdi_value
PDF Funkcje
PHP Manual

PDF_get_pdi_parameter

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_parameter — Get PDI string parameter [deprecated]

Opis

string PDF_get_pdi_parameter ( resource $p , string $key , int $doc , int $page , int $reserved )

Gets the contents of a PDI document parameter with string type.

This function is deprecated since PDFlib version 7, use PDF_pcos_get_string() instead.

PDF_get_parameter
PDF_get_pdi_value
PDF Funkcje


Get PDI numerical parameter [deprecated]

PDF_get_pdi_parameter
PDF_get_value
PDF Funkcje
PHP Manual

PDF_get_pdi_value

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_value — Get PDI numerical parameter [deprecated]

Opis

float PDF_get_pdi_value ( resource $p , string $key , int $doc , int $page , int $reserved )

Gets the contents of a PDI document parameter with numerical type.

This function is deprecated since PDFlib version 7, use PDF_pcos_get_number() instead.

PDF_get_pdi_parameter
PDF_get_value
PDF Funkcje


Get numerical parameter

PDF_get_pdi_value
PDF_info_font
PDF Funkcje
PHP Manual

PDF_get_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_get_value — Get numerical parameter

Opis

float PDF_get_value ( resource $p , string $key , float $modifier )

Gets the value of some PDFlib parameter with numerical type.

PDF_get_pdi_value
PDF_info_font
PDF Funkcje


Query detailed information about a loaded font

PDF_get_value
PDF_info_matchbox
PDF Funkcje
PHP Manual

PDF_info_font

(PECL pdflib >= 2.1.0)

PDF_info_font — Query detailed information about a loaded font

Opis

float PDF_info_font ( resource $pdfdoc , int $font , string $keyword , string $optlist )

Queries detailed information about a loaded font.

PDF_get_value
PDF_info_matchbox
PDF Funkcje


Query matchbox information

PDF_info_font
PDF_info_table
PDF Funkcje
PHP Manual

PDF_info_matchbox

(PECL pdflib >= 2.1.0)

PDF_info_matchbox — Query matchbox information

Opis

float PDF_info_matchbox ( resource $pdfdoc , string $boxname , int $num , string $keyword )

Queries information about a matchbox on the current page.

PDF_info_font
PDF_info_table
PDF Funkcje


Retrieve table information

PDF_info_matchbox
PDF_info_textflow
PDF Funkcje
PHP Manual

PDF_info_table

(PECL pdflib >= 2.1.0)

PDF_info_table — Retrieve table information

Opis

float PDF_info_table ( resource $pdfdoc , int $table , string $keyword )

Retrieves table information related to the most recently placed table instance.

PDF_info_matchbox
PDF_info_textflow
PDF Funkcje


Query textflow state

PDF_info_table
PDF_info_textline
PDF Funkcje
PHP Manual

PDF_info_textflow

(PECL pdflib >= 2.0.0)

PDF_info_textflow — Query textflow state

Opis

float PDF_info_textflow ( resource $pdfdoc , int $textflow , string $keyword )

Queries the current state of a textflow.

PDF_info_table
PDF_info_textline
PDF Funkcje


Perform textline formatting and query metrics

PDF_info_textflow
PDF_initgraphics
PDF Funkcje
PHP Manual

PDF_info_textline

(PECL pdflib >= 2.1.0)

PDF_info_textline — Perform textline formatting and query metrics

Opis

float PDF_info_textline ( resource $pdfdoc , string $text , string $keyword , string $optlist )

Performs textline formatting and queries the resulting metrics.

PDF_info_textflow
PDF_initgraphics
PDF Funkcje


Reset graphic state

PDF_info_textline
PDF_lineto
PDF Funkcje
PHP Manual

PDF_initgraphics

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_initgraphics — Reset graphic state

Opis

bool PDF_initgraphics ( resource $p )

Reset all color and graphics state parameters to their defaults. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_info_textline
PDF_lineto
PDF Funkcje


Draw a line

PDF_initgraphics
PDF_load_3ddata
PDF Funkcje
PHP Manual

PDF_lineto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_lineto — Draw a line

Opis

bool PDF_lineto ( resource $p , float $x , float $y )

Draws a line from the current point to another point. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_initgraphics
PDF_load_3ddata
PDF Funkcje


Load 3D model

PDF_lineto
PDF_load_font
PDF Funkcje
PHP Manual

PDF_load_3ddata

(PECL pdflib >= 2.1.0)

PDF_load_3ddata — Load 3D model

Opis

int PDF_load_3ddata ( resource $pdfdoc , string $filename , string $optlist )

Loads a 3D model from a disk-based or virtual file.

This function requires PDF 1.6.

PDF_lineto
PDF_load_font
PDF Funkcje


Search and prepare font

PDF_load_3ddata
PDF_load_iccprofile
PDF Funkcje
PHP Manual

PDF_load_font

(PECL pdflib >= 2.0.0)

PDF_load_font — Search and prepare font

Opis

int PDF_load_font ( resource $pdfdoc , string $fontname , string $encoding , string $optlist )

Searches for a font and prepares it for later use.

PDF_load_3ddata
PDF_load_iccprofile
PDF Funkcje


Search and prepare ICC profile

PDF_load_font
PDF_load_image
PDF Funkcje
PHP Manual

PDF_load_iccprofile

(PECL pdflib >= 2.0.0)

PDF_load_iccprofile — Search and prepare ICC profile

Opis

int PDF_load_iccprofile ( resource $pdfdoc , string $profilename , string $optlist )

Searches for an ICC profile, and prepares it for later use.

PDF_load_font
PDF_load_image
PDF Funkcje


Open image file

PDF_load_iccprofile
PDF_makespotcolor
PDF Funkcje
PHP Manual

PDF_load_image

(PECL pdflib >= 2.0.0)

PDF_load_image — Open image file

Opis

int PDF_load_image ( resource $pdfdoc , string $imagetype , string $filename , string $optlist )

Opens a disk-based or virtual image file subject to various options.

PDF_load_iccprofile
PDF_makespotcolor
PDF Funkcje


Make spot color

PDF_load_image
PDF_moveto
PDF Funkcje
PHP Manual

PDF_makespotcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_makespotcolor — Make spot color

Opis

int PDF_makespotcolor ( resource $p , string $spotname )

Finds a built-in spot color name, or makes a named spot color from the current fill color. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_load_image
PDF_moveto
PDF Funkcje


Set current point

PDF_makespotcolor
PDF_new
PDF Funkcje
PHP Manual

PDF_moveto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_moveto — Set current point

Opis

bool PDF_moveto ( resource $p , float $x , float $y )

Sets the current point for graphics output. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_makespotcolor
PDF_new
PDF Funkcje


Create PDFlib object

PDF_moveto
PDF_open_ccitt
PDF Funkcje
PHP Manual

PDF_new

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_new — Create PDFlib object

Opis

resource PDF_new ( void )

Creates a new PDFlib object with default settings.

PDF_moveto
PDF_open_ccitt
PDF Funkcje


Open raw CCITT image [deprecated]

PDF_new
PDF_open_file
PDF Funkcje
PHP Manual

PDF_open_ccitt

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_ccitt — Open raw CCITT image [deprecated]

Opis

int PDF_open_ccitt ( resource $pdfdoc , string $filename , int $width , int $height , int $BitReverse , int $k , int $Blackls1 )

Opens a raw CCITT image.

This function is deprecated since PDFlib version 5, use PDF_load_image() instead.

PDF_new
PDF_open_file
PDF Funkcje


Create PDF file [deprecated]

PDF_open_ccitt
PDF_open_gif
PDF Funkcje
PHP Manual

PDF_open_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_file — Create PDF file [deprecated]

Opis

bool PDF_open_file ( resource $p , string $filename )

Creates a new PDF file using the supplied file name. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use PDF_begin_document() instead.

PDF_open_ccitt
PDF_open_gif
PDF Funkcje


Open GIF image [deprecated]

PDF_open_file
PDF_open_image_file
PDF Funkcje
PHP Manual

PDF_open_gif

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_gif — Open GIF image [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

PDF_open_file
PDF_open_image_file
PDF Funkcje


Read image from file [deprecated]

PDF_open_gif
PDF_open_image
PDF Funkcje
PHP Manual

PDF_open_image_file

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_image_file — Read image from file [deprecated]

Opis

int PDF_open_image_file ( resource $p , string $imagetype , string $filename , string $stringparam , int $intparam )

Opens an image file.

This function is deprecated since PDFlib version 5, use PDF_load_image() with the colorize, ignoremask, invert, mask, masked, and page options instead.

PDF_open_gif
PDF_open_image
PDF Funkcje


Use image data [deprecated]

PDF_open_image_file
PDF_open_jpeg
PDF Funkcje
PHP Manual

PDF_open_image

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_image — Use image data [deprecated]

Opis

int PDF_open_image ( resource $p , string $imagetype , string $source , string $data , int $length , int $width , int $height , int $components , int $bpc , string $params )

Uses image data from a variety of data sources.

This function is deprecated since PDFlib version 5, use virtual files and PDF_load_image() instead.

PDF_open_image_file
PDF_open_jpeg
PDF Funkcje


Open JPEG image [deprecated]

PDF_open_image
PDF_open_memory_image
PDF Funkcje
PHP Manual

PDF_open_jpeg

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_jpeg — Open JPEG image [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

PDF_open_image
PDF_open_memory_image
PDF Funkcje


Open image created with PHP's image functions [not supported]

PDF_open_jpeg
PDF_open_pdi_document
PDF Funkcje
PHP Manual

PDF_open_memory_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_memory_image — Open image created with PHP's image functions [not supported]

Opis

int PDF_open_memory_image ( resource $p , resource $image )

This function is not supported by PDFlib GmbH.

PDF_open_jpeg
PDF_open_pdi_document
PDF Funkcje


Prepare a pdi document

PDF_open_memory_image
PDF_open_pdi_page
PDF Funkcje
PHP Manual

PDF_open_pdi_document

(PECL pdflib >= 2.1.0)

PDF_open_pdi_document — Prepare a pdi document

Opis

int PDF_open_pdi_document ( resource $p , string $filename , string $optlist )

Open a disk-based or virtual PDF document and prepare it for later use.

PDF_open_memory_image
PDF_open_pdi_page
PDF Funkcje


Prepare a page

PDF_open_pdi_document
PDF_open_pdi
PDF Funkcje
PHP Manual

PDF_open_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi_page — Prepare a page

Opis

int PDF_open_pdi_page ( resource $p , int $doc , int $pagenumber , string $optlist )

Prepares a page for later use with PDF_fit_pdi_page().

PDF_open_pdi_document
PDF_open_pdi
PDF Funkcje


Open PDF file [deprecated]

PDF_open_pdi_page
PDF_open_tiff
PDF Funkcje
PHP Manual

PDF_open_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi — Open PDF file [deprecated]

Opis

int PDF_open_pdi ( resource $pdfdoc , string $filename , string $optlist , int $len )

Opens a disk-based or virtual PDF document and prepares it for later use.

This function is deprecated since PDFlib version 7, use PDF_open_pdi_document() instead.

PDF_open_pdi_page
PDF_open_tiff
PDF Funkcje


Open TIFF image [deprecated]

PDF_open_pdi
PDF_pcos_get_number
PDF Funkcje
PHP Manual

PDF_open_tiff

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_tiff — Open TIFF image [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.

PDF_open_pdi
PDF_pcos_get_number
PDF Funkcje


Get value of pCOS path with type number or boolean

PDF_open_tiff
PDF_pcos_get_stream
PDF Funkcje
PHP Manual

PDF_pcos_get_number

(PECL pdflib >= 2.1.0)

PDF_pcos_get_number — Get value of pCOS path with type number or boolean

Opis

float PDF_pcos_get_number ( resource $p , int $doc , string $path )

Gets the value of a pCOS path with type number or boolean.

PDF_open_tiff
PDF_pcos_get_stream
PDF Funkcje


Get contents of pCOS path with type stream, fstream, or string

PDF_pcos_get_number
PDF_pcos_get_string
PDF Funkcje
PHP Manual

PDF_pcos_get_stream

(PECL pdflib >= 2.1.0)

PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string

Opis

string PDF_pcos_get_stream ( resource $p , int $doc , string $optlist , string $path )

Gets the contents of a pCOS path with type stream, fstream, or string.

PDF_pcos_get_number
PDF_pcos_get_string
PDF Funkcje


Get value of pCOS path with type name, string, or boolean

PDF_pcos_get_stream
PDF_place_image
PDF Funkcje
PHP Manual

PDF_pcos_get_string

(PECL pdflib >= 2.1.0)

PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean

Opis

string PDF_pcos_get_string ( resource $p , int $doc , string $path )

Gets the value of a pCOS path with type name, string, or boolean.

PDF_pcos_get_stream
PDF_place_image
PDF Funkcje


Place image on the page [deprecated]

PDF_pcos_get_string
PDF_place_pdi_page
PDF Funkcje
PHP Manual

PDF_place_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_place_image — Place image on the page [deprecated]

Opis

bool PDF_place_image ( resource $pdfdoc , int $image , float $x , float $y , float $scale )

Places an image and scales it. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 5, use PDF_fit_image() instead.

PDF_pcos_get_string
PDF_place_pdi_page
PDF Funkcje


Place PDF page [deprecated]

PDF_place_image
PDF_process_pdi
PDF Funkcje
PHP Manual

PDF_place_pdi_page

(PHP 4 >= 4.0.6, PECL pdflib >= 1.0.0)

PDF_place_pdi_page — Place PDF page [deprecated]

Opis

bool PDF_place_pdi_page ( resource $pdfdoc , int $page , float $x , float $y , float $sx , float $sy )

Places a PDF page and scales it. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 5, use PDF_fit_pdi_page() instead.

PDF_place_image
PDF_process_pdi
PDF Funkcje


Process imported PDF document

PDF_place_pdi_page
PDF_rect
PDF Funkcje
PHP Manual

PDF_process_pdi

(PECL pdflib >= 2.0.0)

PDF_process_pdi — Process imported PDF document

Opis

int PDF_process_pdi ( resource $pdfdoc , int $doc , int $page , string $optlist )

Processes certain elements of an imported PDF document.

PDF_place_pdi_page
PDF_rect
PDF Funkcje


Draw rectangle

PDF_process_pdi
PDF_restore
PDF Funkcje
PHP Manual

PDF_rect

(PHP 4, PECL pdflib >= 1.0.0)

PDF_rect — Draw rectangle

Opis

bool PDF_rect ( resource $p , float $x , float $y , float $width , float $height )

Draws a rectangle. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_process_pdi
PDF_restore
PDF Funkcje


Restore graphics state

PDF_rect
PDF_resume_page
PDF Funkcje
PHP Manual

PDF_restore

(PHP 4, PECL pdflib >= 1.0.0)

PDF_restore — Restore graphics state

Opis

bool PDF_restore ( resource $p )

Restores the most recently saved graphics state. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_rect
PDF_resume_page
PDF Funkcje


Resume page

PDF_restore
PDF_rotate
PDF Funkcje
PHP Manual

PDF_resume_page

(PECL pdflib >= 2.0.0)

PDF_resume_page — Resume page

Opis

bool PDF_resume_page ( resource $pdfdoc , string $optlist )

Resumes a page to add more content to it.

PDF_restore
PDF_rotate
PDF Funkcje


Rotate coordinate system

PDF_resume_page
PDF_save
PDF Funkcje
PHP Manual

PDF_rotate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_rotate — Rotate coordinate system

Opis

bool PDF_rotate ( resource $p , float $phi )

Rotates the coordinate system. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_resume_page
PDF_save
PDF Funkcje


Save graphics state

PDF_rotate
PDF_scale
PDF Funkcje
PHP Manual

PDF_save

(PHP 4, PECL pdflib >= 1.0.0)

PDF_save — Save graphics state

Opis

bool PDF_save ( resource $p )

Saves the current graphics state. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_rotate
PDF_scale
PDF Funkcje


Scale coordinate system

PDF_save
PDF_set_border_color
PDF Funkcje
PHP Manual

PDF_scale

(PHP 4, PECL pdflib >= 1.0.0)

PDF_scale — Scale coordinate system

Opis

bool PDF_scale ( resource $p , float $sx , float $sy )

Scales the coordinate system. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_save
PDF_set_border_color
PDF Funkcje


Set border color of annotations [deprecated]

PDF_scale
PDF_set_border_dash
PDF Funkcje
PHP Manual

PDF_set_border_color

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_border_color — Set border color of annotations [deprecated]

Opis

bool PDF_set_border_color ( resource $p , float $red , float $green , float $blue )

Sets the border color for all kinds of annotations. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use the option annotcolor in PDF_create_annotation() instead.

PDF_scale
PDF_set_border_dash
PDF Funkcje


Set border dash style of annotations [deprecated]

PDF_set_border_color
PDF_set_border_style
PDF Funkcje
PHP Manual

PDF_set_border_dash

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_border_dash — Set border dash style of annotations [deprecated]

Opis

bool PDF_set_border_dash ( resource $pdfdoc , float $black , float $white )

Sets the border dash style for all kinds of annotations. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use the option dasharray in PDF_create_annotation() instead.

PDF_set_border_color
PDF_set_border_style
PDF Funkcje


Set border style of annotations [deprecated]

PDF_set_border_dash
PDF_set_char_spacing
PDF Funkcje
PHP Manual

PDF_set_border_style

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_border_style — Set border style of annotations [deprecated]

Opis

bool PDF_set_border_style ( resource $pdfdoc , string $style , float $width )

Sets the border style for all kinds of annotations. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 6, use the options borderstyle and linewidth in PDF_create_annotation() instead.

PDF_set_border_dash
PDF_set_char_spacing
PDF Funkcje


Set character spacing [deprecated]

PDF_set_border_style
PDF_set_duration
PDF Funkcje
PHP Manual

PDF_set_char_spacing

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_char_spacing — Set character spacing [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_value() with parameter charspacing instead.

PDF_set_border_style
PDF_set_duration
PDF Funkcje


Set duration between pages [deprecated]

PDF_set_char_spacing
PDF_set_gstate
PDF Funkcje
PHP Manual

PDF_set_duration

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_duration — Set duration between pages [deprecated]

Opis

This function is deprecated since PDFlib version 3, use the duration option in PDF_begin_page_ext() or PDF_end_page_ext() instead.

PDF_set_char_spacing
PDF_set_gstate
PDF Funkcje


Activate graphics state object

PDF_set_duration
PDF_set_horiz_scaling
PDF Funkcje
PHP Manual

PDF_set_gstate

(PECL pdflib >= 2.0.0)

PDF_set_gstate — Activate graphics state object

Opis

bool PDF_set_gstate ( resource $pdfdoc , int $gstate )

Activates a graphics state object.

PDF_set_duration
PDF_set_horiz_scaling
PDF Funkcje


Set horizontal text scaling [deprecated]

PDF_set_gstate
PDF_set_info_author
PDF Funkcje
PHP Manual

PDF_set_horiz_scaling

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_value() with parameter horizscaling instead.

PDF_set_gstate
PDF_set_info_author
PDF Funkcje


Fill the author document info field [deprecated]

PDF_set_horiz_scaling
PDF_set_info_creator
PDF Funkcje
PHP Manual

PDF_set_info_author

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_author — Fill the author document info field [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_horiz_scaling
PDF_set_info_creator
PDF Funkcje


Fill the creator document info field [deprecated]

PDF_set_info_author
PDF_set_info_keywords
PDF Funkcje
PHP Manual

PDF_set_info_creator

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_creator — Fill the creator document info field [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_info_author
PDF_set_info_keywords
PDF Funkcje


Fill the keywords document info field [deprecated]

PDF_set_info_creator
PDF_set_info_subject
PDF Funkcje
PHP Manual

PDF_set_info_keywords

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_keywords — Fill the keywords document info field [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_info_creator
PDF_set_info_subject
PDF Funkcje


Fill the subject document info field [deprecated]

PDF_set_info_keywords
PDF_set_info_title
PDF Funkcje
PHP Manual

PDF_set_info_subject

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_subject — Fill the subject document info field [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_info_keywords
PDF_set_info_title
PDF Funkcje


Fill the title document info field [deprecated]

PDF_set_info_subject
PDF_set_info
PDF Funkcje
PHP Manual

PDF_set_info_title

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_title — Fill the title document info field [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.

PDF_set_info_subject
PDF_set_info
PDF Funkcje


Fill document info field

PDF_set_info_title
PDF_set_layer_dependency
PDF Funkcje
PHP Manual

PDF_set_info

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_info — Fill document info field

Opis

bool PDF_set_info ( resource $p , string $key , string $value )

Fill document information field key with value. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_set_info_title
PDF_set_layer_dependency
PDF Funkcje


Define relationships among layers

PDF_set_info
PDF_set_leading
PDF Funkcje
PHP Manual

PDF_set_layer_dependency

(PECL pdflib >= 2.0.0)

PDF_set_layer_dependency — Define relationships among layers

Opis

bool PDF_set_layer_dependency ( resource $pdfdoc , string $type , string $optlist )

Defines hierarchical and group relationships among layers. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function requires PDF 1.5.

PDF_set_info
PDF_set_leading
PDF Funkcje


Set distance between text lines [deprecated]

PDF_set_layer_dependency
PDF_set_parameter
PDF Funkcje
PHP Manual

PDF_set_leading

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_leading — Set distance between text lines [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_value() with the parameter leading instead.

PDF_set_layer_dependency
PDF_set_parameter
PDF Funkcje


Set string parameter

PDF_set_leading
PDF_set_text_matrix
PDF Funkcje
PHP Manual

PDF_set_parameter

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_parameter — Set string parameter

Opis

bool PDF_set_parameter ( resource $p , string $key , string $value )

Sets some PDFlib parameter with string type. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_set_leading
PDF_set_text_matrix
PDF Funkcje


Set text matrix [deprecated]

PDF_set_parameter
PDF_set_text_pos
PDF Funkcje
PHP Manual

PDF_set_text_matrix

(PHP 4 <= 4.0.4)

PDF_set_text_matrix — Set text matrix [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_scale(), PDF_translate(), PDF_rotate(), or PDF_skew() instead.

PDF_set_parameter
PDF_set_text_pos
PDF Funkcje


Set text position

PDF_set_text_matrix
PDF_set_text_rendering
PDF Funkcje
PHP Manual

PDF_set_text_pos

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_pos — Set text position

Opis

bool PDF_set_text_pos ( resource $p , float $x , float $y )

Sets the position for text output on the page. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_set_text_matrix
PDF_set_text_rendering
PDF Funkcje


Determine text rendering [deprecated]

PDF_set_text_pos
PDF_set_text_rise
PDF Funkcje
PHP Manual

PDF_set_text_rendering

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_rendering — Determine text rendering [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_value() with the textrendering parameter instead.

PDF_set_text_pos
PDF_set_text_rise
PDF Funkcje


Set text rise [deprecated]

PDF_set_text_rendering
PDF_set_value
PDF Funkcje
PHP Manual

PDF_set_text_rise

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_rise — Set text rise [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_value() with the textrise parameter instead.

PDF_set_text_rendering
PDF_set_value
PDF Funkcje


Set numerical parameter

PDF_set_text_rise
PDF_set_word_spacing
PDF Funkcje
PHP Manual

PDF_set_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_value — Set numerical parameter

Opis

bool PDF_set_value ( resource $p , string $key , float $value )

Sets the value of some PDFlib parameter with numerical type. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_set_text_rise
PDF_set_word_spacing
PDF Funkcje


Set spacing between words [deprecated]

PDF_set_value
PDF_setcolor
PDF Funkcje
PHP Manual

PDF_set_word_spacing

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_word_spacing — Set spacing between words [deprecated]

Opis

This function is deprecated since PDFlib version 3, use PDF_set_value() with the wordspacing parameter instead.

PDF_set_value
PDF_setcolor
PDF Funkcje


Set fill and stroke color

PDF_set_word_spacing
PDF_setdash
PDF Funkcje
PHP Manual

PDF_setcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setcolor — Set fill and stroke color

Opis

bool PDF_setcolor ( resource $p , string $fstype , string $colorspace , float $c1 , float $c2 , float $c3 , float $c4 )

Sets the current color space and color. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_set_word_spacing
PDF_setdash
PDF Funkcje


Set simple dash pattern

PDF_setcolor
PDF_setdashpattern
PDF Funkcje
PHP Manual

PDF_setdash

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setdash — Set simple dash pattern

Opis

bool PDF_setdash ( resource $pdfdoc , float $b , float $w )

Sets the current dash pattern to b black and w white units. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_setcolor
PDF_setdashpattern
PDF Funkcje


Set dash pattern

PDF_setdash
PDF_setflat
PDF Funkcje
PHP Manual

PDF_setdashpattern

(PECL pdflib >= 2.0.0)

PDF_setdashpattern — Set dash pattern

Opis

bool PDF_setdashpattern ( resource $pdfdoc , string $optlist )

Sets a dash pattern defined by an option list. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_setdash
PDF_setflat
PDF Funkcje


Set flatness

PDF_setdashpattern
PDF_setfont
PDF Funkcje
PHP Manual

PDF_setflat

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setflat — Set flatness

Opis

bool PDF_setflat ( resource $pdfdoc , float $flatness )

Sets the flatness parameter. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_setdashpattern
PDF_setfont
PDF Funkcje


Set font

PDF_setflat
PDF_setgray_fill
PDF Funkcje
PHP Manual

PDF_setfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setfont — Set font

Opis

bool PDF_setfont ( resource $pdfdoc , int $font , float $fontsize )

Sets the current font in the specified size, using a font handle returned by PDF_load_font(). Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_setflat
PDF_setgray_fill
PDF Funkcje


Set fill color to gray [deprecated]

PDF_setfont
PDF_setgray_stroke
PDF Funkcje
PHP Manual

PDF_setgray_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray_fill — Set fill color to gray [deprecated]

Opis

bool PDF_setgray_fill ( resource $p , float $g )

Sets the current fill color to a gray value between 0 and 1 inclusive. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setfont
PDF_setgray_stroke
PDF Funkcje


Set stroke color to gray [deprecated]

PDF_setgray_fill
PDF_setgray
PDF Funkcje
PHP Manual

PDF_setgray_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray_stroke — Set stroke color to gray [deprecated]

Opis

bool PDF_setgray_stroke ( resource $p , float $g )

Sets the current stroke color to a gray value between 0 and 1 inclusive. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setgray_fill
PDF_setgray
PDF Funkcje


Set color to gray [deprecated]

PDF_setgray_stroke
PDF_setlinecap
PDF Funkcje
PHP Manual

PDF_setgray

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray — Set color to gray [deprecated]

Opis

bool PDF_setgray ( resource $p , float $g )

Sets the current fill and stroke color to a gray value between 0 and 1 inclusive. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setgray_stroke
PDF_setlinecap
PDF Funkcje


Set linecap parameter

PDF_setgray
PDF_setlinejoin
PDF Funkcje
PHP Manual

PDF_setlinecap

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinecap — Set linecap parameter

Opis

bool PDF_setlinecap ( resource $p , int $linecap )

Sets the linecap parameter to control the shape at the end of a path with respect to stroking.

PDF_setgray
PDF_setlinejoin
PDF Funkcje


Set linejoin parameter

PDF_setlinecap
PDF_setlinewidth
PDF Funkcje
PHP Manual

PDF_setlinejoin

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinejoin — Set linejoin parameter

Opis

bool PDF_setlinejoin ( resource $p , int $value )

Sets the linejoin parameter to specify the shape at the corners of paths that are stroked. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_setlinecap
PDF_setlinewidth
PDF Funkcje


Set line width

PDF_setlinejoin
PDF_setmatrix
PDF Funkcje
PHP Manual

PDF_setlinewidth

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinewidth — Set line width

Opis

bool PDF_setlinewidth ( resource $p , float $width )

Sets the current line width. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_setlinejoin
PDF_setmatrix
PDF Funkcje


Set current transformation matrix

PDF_setlinewidth
PDF_setmiterlimit
PDF Funkcje
PHP Manual

PDF_setmatrix

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setmatrix — Set current transformation matrix

Opis

bool PDF_setmatrix ( resource $p , float $a , float $b , float $c , float $d , float $e , float $f )

Explicitly sets the current transformation matrix. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_setlinewidth
PDF_setmiterlimit
PDF Funkcje


Set miter limit

PDF_setmatrix
PDF_setpolydash
PDF Funkcje
PHP Manual

PDF_setmiterlimit

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setmiterlimit — Set miter limit

Opis

bool PDF_setmiterlimit ( resource $pdfdoc , float $miter )

Sets the miter limit.Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_setmatrix
PDF_setpolydash
PDF Funkcje


Set complicated dash pattern [deprecated]

PDF_setmiterlimit
PDF_setrgbcolor_fill
PDF Funkcje
PHP Manual

PDF_setpolydash

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setpolydash — Set complicated dash pattern [deprecated]

Opis

This function is deprecated since PDFlib version 5, use PDF_setdashpattern() instead.

PDF_setmiterlimit
PDF_setrgbcolor_fill
PDF Funkcje


Set fill rgb color values [deprecated]

PDF_setpolydash
PDF_setrgbcolor_stroke
PDF Funkcje
PHP Manual

PDF_setrgbcolor_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]

Opis

bool PDF_setrgbcolor_fill ( resource $p , float $red , float $green , float $blue )

Sets the current fill color to the supplied RGB values. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setpolydash
PDF_setrgbcolor_stroke
PDF Funkcje


Set stroke rgb color values [deprecated]

PDF_setrgbcolor_fill
PDF_setrgbcolor
PDF Funkcje
PHP Manual

PDF_setrgbcolor_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]

Opis

bool PDF_setrgbcolor_stroke ( resource $p , float $red , float $green , float $blue )

Sets the current stroke color to the supplied RGB values. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setrgbcolor_fill
PDF_setrgbcolor
PDF Funkcje


Set fill and stroke rgb color values [deprecated]

PDF_setrgbcolor_stroke
PDF_shading_pattern
PDF Funkcje
PHP Manual

PDF_setrgbcolor

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]

Opis

bool PDF_setrgbcolor ( resource $p , float $red , float $green , float $blue )

Sets the current fill and stroke color to the supplied RGB values. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.

PDF_setrgbcolor_stroke
PDF_shading_pattern
PDF Funkcje


Define shading pattern

PDF_setrgbcolor
PDF_shading
PDF Funkcje
PHP Manual

PDF_shading_pattern

(PECL pdflib >= 2.0.0)

PDF_shading_pattern — Define shading pattern

Opis

int PDF_shading_pattern ( resource $pdfdoc , int $shading , string $optlist )

Defines a shading pattern using a shading object.

This function requires PDF 1.4 or above.

PDF_setrgbcolor
PDF_shading
PDF Funkcje


Define blend

PDF_shading_pattern
PDF_shfill
PDF Funkcje
PHP Manual

PDF_shading

(PECL pdflib >= 2.0.0)

PDF_shading — Define blend

Opis

int PDF_shading ( resource $pdfdoc , string $shtype , float $x0 , float $y0 , float $x1 , float $y1 , float $c1 , float $c2 , float $c3 , float $c4 , string $optlist )

Defines a blend from the current fill color to another color.

This function requires PDF 1.4 or above.

PDF_shading_pattern
PDF_shfill
PDF Funkcje


Fill area with shading

PDF_shading
PDF_show_boxed
PDF Funkcje
PHP Manual

PDF_shfill

(PECL pdflib >= 2.0.0)

PDF_shfill — Fill area with shading

Opis

bool PDF_shfill ( resource $pdfdoc , int $shading )

Fills an area with a shading, based on a shading object.

This function requires PDF 1.4 or above.

PDF_shading
PDF_show_boxed
PDF Funkcje


Output text in a box [deprecated]

PDF_shfill
PDF_show_xy
PDF Funkcje
PHP Manual

PDF_show_boxed

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show_boxed — Output text in a box [deprecated]

Opis

int PDF_show_boxed ( resource $p , string $text , float $left , float $top , float $width , float $height , string $mode , string $feature )

This function is deprecated since PDFlib version 6, use PDF_fit_textline() for single lines, or the PDF_*_textflow() functions for multi-line formatting instead.

PDF_shfill
PDF_show_xy
PDF Funkcje


Output text at given position

PDF_show_boxed
PDF_show
PDF Funkcje
PHP Manual

PDF_show_xy

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show_xy — Output text at given position

Opis

bool PDF_show_xy ( resource $p , string $text , float $x , float $y )

Prints text in the current font. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_show_boxed
PDF_show
PDF Funkcje


Output text at current position

PDF_show_xy
PDF_skew
PDF Funkcje
PHP Manual

PDF_show

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show — Output text at current position

Opis

bool PDF_show ( resource $pdfdoc , string $text )

Prints text in the current font and size at the current position. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_show_xy
PDF_skew
PDF Funkcje


Skew the coordinate system

PDF_show
PDF_stringwidth
PDF Funkcje
PHP Manual

PDF_skew

(PHP 4, PECL pdflib >= 1.0.0)

PDF_skew — Skew the coordinate system

Opis

bool PDF_skew ( resource $p , float $alpha , float $beta )

Skews the coordinate system in x and y direction by alpha and beta degrees. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_show
PDF_stringwidth
PDF Funkcje


Return width of text

PDF_skew
PDF_stroke
PDF Funkcje
PHP Manual

PDF_stringwidth

(PHP 4, PECL pdflib >= 1.0.0)

PDF_stringwidth — Return width of text

Opis

float PDF_stringwidth ( resource $p , string $text , int $font , float $fontsize )

Returns the width of text in an arbitrary font.

PDF_skew
PDF_stroke
PDF Funkcje


Stroke path

PDF_stringwidth
PDF_suspend_page
PDF Funkcje
PHP Manual

PDF_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_stroke — Stroke path

Opis

bool PDF_stroke ( resource $p )

Strokes the path with the current color and line width, and clear it. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

PDF_stringwidth
PDF_suspend_page
PDF Funkcje


Suspend page

PDF_stroke
PDF_translate
PDF Funkcje
PHP Manual

PDF_suspend_page

(PECL pdflib >= 2.0.0)

PDF_suspend_page — Suspend page

Opis

bool PDF_suspend_page ( resource $pdfdoc , string $optlist )

Suspends the current page so that it can later be resumed with PDF_resume_page().

PDF_stroke
PDF_translate
PDF Funkcje


Set origin of coordinate system

PDF_suspend_page
PDF_utf16_to_utf8
PDF Funkcje
PHP Manual

PDF_translate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_translate — Set origin of coordinate system

Opis

bool PDF_translate ( resource $p , float $tx , float $ty )

Translates the origin of the coordinate system.

PDF_suspend_page
PDF_utf16_to_utf8
PDF Funkcje


Convert string from UTF-16 to UTF-8

PDF_translate
PDF_utf32_to_utf16
PDF Funkcje
PHP Manual

PDF_utf16_to_utf8

(PECL pdflib >= 2.0.3)

PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8

Opis

string PDF_utf16_to_utf8 ( resource $pdfdoc , string $utf16string )

Converts a string from UTF-16 format to UTF-8.

PDF_translate
PDF_utf32_to_utf16
PDF Funkcje


Convert string from UTF-32 to UTF-16

PDF_utf16_to_utf8
PDF_utf8_to_utf16
PDF Funkcje
PHP Manual

PDF_utf32_to_utf16

(PECL pdflib >= Unknown future)

PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16

Opis

string PDF_utf32_to_utf16 ( resource $pdfdoc , string $utf32string , string $ordering )

Converts a string from UTF-32 format to UTF-16.

PDF_utf16_to_utf8
PDF_utf8_to_utf16
PDF Funkcje


Convert string from UTF-8 to UTF-16

PDF_utf32_to_utf16
PS
PDF Funkcje
PHP Manual

PDF_utf8_to_utf16

(PECL pdflib >= 2.0.3)

PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16

Opis

string PDF_utf8_to_utf16 ( resource $pdfdoc , string $utf8string , string $ordering )

Converts a string from UTF-8 format to UTF-16.

PDF_utf32_to_utf16
PS
PDF Funkcje


PostScript document creation

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • PS Funkcje
    • ps_add_bookmark — Add bookmark to current page
    • ps_add_launchlink — Adds link which launches file
    • ps_add_locallink — Adds link to a page in the same document
    • ps_add_note — Adds note to current page
    • ps_add_pdflink — Adds link to a page in a second pdf document
    • ps_add_weblink — Adds link to a web location
    • ps_arc — Draws an arc counterclockwise
    • ps_arcn — Draws an arc clockwise
    • ps_begin_page — Start a new page
    • ps_begin_pattern — Start a new pattern
    • ps_begin_template — Start a new template
    • ps_circle — Draws a circle
    • ps_clip — Clips drawing to current path
    • ps_close_image — Closes image and frees memory
    • ps_close — Closes a PostScript document
    • ps_closepath_stroke — Closes and strokes path
    • ps_closepath — Closes path
    • ps_continue_text — Continue text in next line
    • ps_curveto — Draws a curve
    • ps_delete — Deletes all resources of a PostScript document
    • ps_end_page — End a page
    • ps_end_pattern — End a pattern
    • ps_end_template — End a template
    • ps_fill_stroke — Fills and strokes the current path
    • ps_fill — Fills the current path
    • ps_findfont — Loads a font
    • ps_get_buffer — Fetches the full buffer containig the generated PS data
    • ps_get_parameter — Gets certain parameters
    • ps_get_value — Gets certain values
    • ps_hyphenate — Hyphenates a word
    • ps_include_file — Reads an external file with raw PostScript code
    • ps_lineto — Draws a line
    • ps_makespotcolor — Create spot color
    • ps_moveto — Sets current point
    • ps_new — Creates a new PostScript document object
    • ps_open_file — Opens a file for output
    • ps_open_image_file — Opens image from file
    • ps_open_image — Reads an image for later placement
    • ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
    • ps_place_image — Places image on the page
    • ps_rect — Draws a rectangle
    • ps_restore — Restore previously save context
    • ps_rotate — Sets rotation factor
    • ps_save — Save current context
    • ps_scale — Sets scaling factor
    • ps_set_border_color — Sets color of border for annotations
    • ps_set_border_dash — Sets length of dashes for border of annotations
    • ps_set_border_style — Sets border style of annotations
    • ps_set_info — Sets information fields of document
    • ps_set_parameter — Sets certain parameters
    • ps_set_text_pos — Sets position for text output
    • ps_set_value — Sets certain values
    • ps_setcolor — Sets current color
    • ps_setdash — Sets appearance of a dashed line
    • ps_setflat — Sets flatness
    • ps_setfont — Sets font to use for following output
    • ps_setgray — Sets gray value
    • ps_setlinecap — Sets appearance of line ends
    • ps_setlinejoin — Sets how contected lines are joined
    • ps_setlinewidth — Sets width of a line
    • ps_setmiterlimit — Sets the miter limit
    • ps_setoverprintmode — Sets overprint mode
    • ps_setpolydash — Sets appearance of a dashed line
    • ps_shading_pattern — Creates a pattern based on a shading
    • ps_shading — Creates a shading for later use
    • ps_shfill — Fills an area with a shading
    • ps_show_boxed — Output text in a box
    • ps_show_xy2 — Output text at position
    • ps_show_xy — Output text at given position
    • ps_show2 — Output a text at current position
    • ps_show — Output text
    • ps_string_geometry — Gets geometry of a string
    • ps_stringwidth — Gets width of a string
    • ps_stroke — Draws the current path
    • ps_symbol_name — Gets name of a glyph
    • ps_symbol_width — Gets width of a glyph
    • ps_symbol — Output a glyph
    • ps_translate — Sets translation
PDF_utf8_to_utf16
Wstęp
Generowanie nietekstowych formatów danych


Wstęp

This module allows to create PostScript documents. It has many similarities with the pdf extension. Actually the API is almost identical and one can in many cases just replace the prefix of each function from pdf_ to ps_. This also works for functions which has no meaning in the PostScript document (like adding hyperlinks) but will have an effect if the document is converted to PDF.

Documents created by this extension are sometimes even superior to documents created with the pdf extension, because pslib's text rendering functions can handle kerning, hyphenation and ligatures which results in much better output of boxed text.

PS
Instalacja/Konfiguracja
PS


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
PS


Wymagania

You need at least PHP 4.3.0 and pslib >= 0.1.12. The ps library (pslib) is available at » http://pslib.sourceforge.net/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/ps.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines a PostScript document resource returned by ps_new().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

The following two tables lists all constants defined by the ps extension.

Contants for line caps
Name | Meaning
ps_LINECAP_BUTT |
ps_LINECAP_ROUND |
ps_LINECAP_SQUARED |
Contants for line joins
Name | Meaning
ps_LINEJOIN_MITER |
ps_LINEJOIN_ROUND |
ps_LINEJOIN_BEVEL |

Typy zasobów
PS Funkcje
PS


PS Funkcje

Contact Information

If you have comments, bugfixes, enhancements for either this extension or pslib then please drop me a mail » steinm@php.net. Any help is very welcome.

Spis treści

  • ps_add_bookmark — Add bookmark to current page
  • ps_add_launchlink — Adds link which launches file
  • ps_add_locallink — Adds link to a page in the same document
  • ps_add_note — Adds note to current page
  • ps_add_pdflink — Adds link to a page in a second pdf document
  • ps_add_weblink — Adds link to a web location
  • ps_arc — Draws an arc counterclockwise
  • ps_arcn — Draws an arc clockwise
  • ps_begin_page — Start a new page
  • ps_begin_pattern — Start a new pattern
  • ps_begin_template — Start a new template
  • ps_circle — Draws a circle
  • ps_clip — Clips drawing to current path
  • ps_close_image — Closes image and frees memory
  • ps_close — Closes a PostScript document
  • ps_closepath_stroke — Closes and strokes path
  • ps_closepath — Closes path
  • ps_continue_text — Continue text in next line
  • ps_curveto — Draws a curve
  • ps_delete — Deletes all resources of a PostScript document
  • ps_end_page — End a page
  • ps_end_pattern — End a pattern
  • ps_end_template — End a template
  • ps_fill_stroke — Fills and strokes the current path
  • ps_fill — Fills the current path
  • ps_findfont — Loads a font
  • ps_get_buffer — Fetches the full buffer containig the generated PS data
  • ps_get_parameter — Gets certain parameters
  • ps_get_value — Gets certain values
  • ps_hyphenate — Hyphenates a word
  • ps_include_file — Reads an external file with raw PostScript code
  • ps_lineto — Draws a line
  • ps_makespotcolor — Create spot color
  • ps_moveto — Sets current point
  • ps_new — Creates a new PostScript document object
  • ps_open_file — Opens a file for output
  • ps_open_image_file — Opens image from file
  • ps_open_image — Reads an image for later placement
  • ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
  • ps_place_image — Places image on the page
  • ps_rect — Draws a rectangle
  • ps_restore — Restore previously save context
  • ps_rotate — Sets rotation factor
  • ps_save — Save current context
  • ps_scale — Sets scaling factor
  • ps_set_border_color — Sets color of border for annotations
  • ps_set_border_dash — Sets length of dashes for border of annotations
  • ps_set_border_style — Sets border style of annotations
  • ps_set_info — Sets information fields of document
  • ps_set_parameter — Sets certain parameters
  • ps_set_text_pos — Sets position for text output
  • ps_set_value — Sets certain values
  • ps_setcolor — Sets current color
  • ps_setdash — Sets appearance of a dashed line
  • ps_setflat — Sets flatness
  • ps_setfont — Sets font to use for following output
  • ps_setgray — Sets gray value
  • ps_setlinecap — Sets appearance of line ends
  • ps_setlinejoin — Sets how contected lines are joined
  • ps_setlinewidth — Sets width of a line
  • ps_setmiterlimit — Sets the miter limit
  • ps_setoverprintmode — Sets overprint mode
  • ps_setpolydash — Sets appearance of a dashed line
  • ps_shading_pattern — Creates a pattern based on a shading
  • ps_shading — Creates a shading for later use
  • ps_shfill — Fills an area with a shading
  • ps_show_boxed — Output text in a box
  • ps_show_xy2 — Output text at position
  • ps_show_xy — Output text at given position
  • ps_show2 — Output a text at current position
  • ps_show — Output text
  • ps_string_geometry — Gets geometry of a string
  • ps_stringwidth — Gets width of a string
  • ps_stroke — Draws the current path
  • ps_symbol_name — Gets name of a glyph
  • ps_symbol_width — Gets width of a glyph
  • ps_symbol — Output a glyph
  • ps_translate — Sets translation
Stałe predefiniowane
ps_add_bookmark
PS


Add bookmark to current page

PS Funkcje
ps_add_launchlink
PS Funkcje
PHP Manual

ps_add_bookmark

(PECL ps >= 1.1.0)

ps_add_bookmark — Add bookmark to current page

Opis

int ps_add_bookmark ( resource $psdoc , string $text [, int $parent = 0 [, int $open = 0 ]] )

Adds a bookmark for the current page. Bookmarks usually appear in PDF-Viewers left of the page in a hierarchical tree. Clicking on a bookmark will jump to the given page.

Notatki nie będą widoczne ani podczas przeglądania dokumentu, ani na wydruku. Notatki będą widoczne jeśli dokument zostanie przekonwertowany do formatu PDF za pomocą Acrobat Distiller™ lub Ghostview.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text used for displaying the bookmark.

parent

A bookmark previously created by this function which is used as the parent of the new bookmark.

open

If open is unequal to zero the bookmark will be shown open by the pdf viewer.

Zwracane wartości

The returned value is a reference for the bookmark. It is only used if the bookmark shall be used as a parent. The value is greater zero if the function succeeds. In case of an error zero will be returned.

Zobacz też:

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

PS Funkcje
ps_add_launchlink
PS Funkcje


Adds link which launches file

ps_add_bookmark
ps_add_locallink
PS Funkcje
PHP Manual

ps_add_launchlink

(PECL ps >= 1.1.0)

ps_add_launchlink — Adds link which launches file

Opis

bool ps_add_launchlink ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , string $filename )

Places a hyperlink at the given position pointing to a file program which is being started when clicked on. The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

Notatki nie będą widoczne ani podczas przeglądania dokumentu, ani na wydruku. Notatki będą widoczne jeśli dokument zostanie przekonwertowany do formatu PDF za pomocą Acrobat Distiller™ lub Ghostview.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

filename

The path of the program to be started, when the link is clicked on.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

ps_add_bookmark
ps_add_locallink
PS Funkcje


Adds link to a page in the same document

ps_add_launchlink
ps_add_note
PS Funkcje
PHP Manual

ps_add_locallink

(PECL ps >= 1.1.0)

ps_add_locallink — Adds link to a page in the same document

Opis

bool ps_add_locallink ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , int $page , string $dest )

Places a hyperlink at the given position pointing to a page in the same document. Clicking on the link will jump to the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

Notatki nie będą widoczne ani podczas przeglądania dokumentu, ani na wydruku. Notatki będą widoczne jeśli dokument zostanie przekonwertowany do formatu PDF za pomocą Acrobat Distiller™ lub Ghostview.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

page

The number of the page displayed when clicking on the link.

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

ps_add_launchlink
ps_add_note
PS Funkcje


Adds note to current page

ps_add_locallink
ps_add_pdflink
PS Funkcje
PHP Manual

ps_add_note

(PECL ps >= 1.1.0)

ps_add_note — Adds note to current page

Opis

bool ps_add_note ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , string $contents , string $title , string $icon , int $open )

Adds a note at a certain position on the page. Notes are like little rectangular sheets with text on it, which can be placed anywhere on a page. They are shown either folded or unfolded. If folded, the specified icon is used as a placeholder.

Notatki nie będą widoczne ani podczas przeglądania dokumentu, ani na wydruku. Notatki będą widoczne jeśli dokument zostanie przekonwertowany do formatu PDF za pomocą Acrobat Distiller™ lub Ghostview.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

contents

The text of the note.

title

The title of the note as displayed in the header of the note.

icon

The icon shown if the note is folded. This parameter can be set to comment, insert, note, paragraph, newparagraph, key, or help.

open

If open is unequal to zero the note will be shown unfolded after opening the document with a pdf viewer.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_weblink() - Adds link to a web location

ps_add_locallink
ps_add_pdflink
PS Funkcje


Adds link to a page in a second pdf document

ps_add_note
ps_add_weblink
PS Funkcje
PHP Manual

ps_add_pdflink

(PECL ps >= 1.1.0)

ps_add_pdflink — Adds link to a page in a second pdf document

Opis

bool ps_add_pdflink ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , string $filename , int $page , string $dest )

Places a hyperlink at the given position pointing to a second pdf document. Clicking on the link will branch to the document at the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

Notatki nie będą widoczne ani podczas przeglądania dokumentu, ani na wydruku. Notatki będą widoczne jeśli dokument zostanie przekonwertowany do formatu PDF za pomocą Acrobat Distiller™ lub Ghostview.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

filename

The name of the pdf document to be opened when clicking on this link.

page

The page number of the destination pdf document

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_weblink() - Adds link to a web location

ps_add_note
ps_add_weblink
PS Funkcje


Adds link to a web location

ps_add_pdflink
ps_arc
PS Funkcje
PHP Manual

ps_add_weblink

(PECL ps >= 1.1.0)

ps_add_weblink — Adds link to a web location

Opis

bool ps_add_weblink ( resource $psdoc , float $llx , float $lly , float $urx , float $ury , string $url )

Places a hyperlink at the given position pointing to a web page. The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

Notatki nie będą widoczne ani podczas przeglądania dokumentu, ani na wydruku. Notatki będą widoczne jeśli dokument zostanie przekonwertowany do formatu PDF za pomocą Acrobat Distiller™ lub Ghostview.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

url

The url of the hyperlink to be opened when clicking on this link, e.g. http://www.php.net.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_pdflink() - Adds link to a page in a second pdf document

ps_add_pdflink
ps_arc
PS Funkcje


Draws an arc counterclockwise

ps_add_weblink
ps_arcn
PS Funkcje
PHP Manual

ps_arc

(PECL ps >= 1.1.0)

ps_arc — Draws an arc counterclockwise

Opis

bool ps_arc ( resource $psdoc , float $x , float $y , float $radius , float $alpha , float $beta )

Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn counterclockwise (use ps_arcn() to draw clockwise). The subpath added to the current path starts on the arc at angle alpha and ends on the arc at angle beta.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

alpha

The start angle given in degrees.

beta

The end angle given in degrees.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_arcn() - Draws an arc clockwise

ps_add_weblink
ps_arcn
PS Funkcje


Draws an arc clockwise

ps_arc
ps_begin_page
PS Funkcje
PHP Manual

ps_arcn

(PECL ps >= 1.1.0)

ps_arcn — Draws an arc clockwise

Opis

bool ps_arcn ( resource $psdoc , float $x , float $y , float $radius , float $alpha , float $beta )

Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn clockwise (use ps_arc() to draw counterclockwise). The subpath added to the current path starts on the arc at angle beta and ends on the arc at angle alpha.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

alpha

The starting angle given in degrees.

beta

The end angle given in degrees.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_arc() - Draws an arc counterclockwise

ps_arc
ps_begin_page
PS Funkcje


Start a new page

ps_arcn
ps_begin_pattern
PS Funkcje
PHP Manual

ps_begin_page

(PECL ps >= 1.1.0)

ps_begin_page — Start a new page

Opis

bool ps_begin_page ( resource $psdoc , float $width , float $height )

Starts a new page. Although the parameters width and height imply a different page size for each page, this is not possible in PostScript. The first call of ps_begin_page() will set the page size for the whole document. Consecutive calls will have no effect, except for creating a new page. The situation is different if you intent to convert the PostScript document into PDF. This function places pdfmarks into the document which can set the size for each page indiviually. The resulting PDF document will have different page sizes.

Though PostScript does not know different page sizes, pslib places a bounding box for each page into the document. This size is evaluated by some PostScript viewers and will have precedence over the BoundingBox in the Header of the document. This can lead to unexpected results when you set a BoundingBox whose lower left corner is not (0, 0), because the bounding box of the page will always have a lower left corner (0, 0) and overwrites the global setting.

Each page is encapsulated into save/restore. This means, that most of the settings made on one page will not be retained on the next page.

If there is up to the first call of ps_begin_page() no call of ps_findfont(), then the header of the PostScript document will be output and the bounding box will be set to the size of the first page. The lower left corner of the bounding box is set to (0, 0). If ps_findfont() was called before, then the header has been output already, and the document will not have a valid bounding box. In order to prevent this, one should call ps_set_info() to set the info field BoundingBox and possibly Orientation before any ps_findfont() or ps_begin_page() calls.

Informacja:

Up to version 0.2.6 of pslib, this function will always overwrite the BoundingBox and Orientation, if it has been set before with ps_set_info() and ps_findfont() has not been called before.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the page in pixel, e.g. 596 for A4 format.

height

The height of the page in pixel, e.g. 842 for A4 format.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_end_page() - End a page
  • ps_findfont() - Loads a font
  • ps_set_info() - Sets information fields of document

ps_arcn
ps_begin_pattern
PS Funkcje


Start a new pattern

ps_begin_page
ps_begin_template
PS Funkcje
PHP Manual

ps_begin_pattern

(PECL ps >= 1.2.0)

ps_begin_pattern — Start a new pattern

Opis

int ps_begin_pattern ( resource $psdoc , float $width , float $height , float $xstep , float $ystep , int $painttype )

Starts a new pattern. A pattern is like a page containing e.g. a drawing which can be used for filling areas. It is used like a color by calling ps_setcolor() and setting the color space to pattern.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the pattern in pixel.

height

The height of the pattern in pixel.

x-step

The distance in pixel of placements of the pattern in horizontal direction.

y-step

The distance in pixel of placements of the pattern in vertical direction.

painttype

Must be 1 or 2.

Zwracane wartości

The identifier of the pattern lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Creating and using a pattern

<?php
$ps = ps_new();

if (!ps_open_file($ps, "pattern.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "pattern.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Pattern example");

$pspattern = ps_begin_pattern($ps, 10.0, 10.0, 10.0, 10.0, 1);
ps_setlinewidth($ps, 0.2);
ps_setcolor($ps, "stroke", "rgb", 0.0, 0.0, 1.0, 0.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 7, 7);
ps_stroke($ps);
ps_moveto($ps, 0, 7);
ps_lineto($ps, 7, 0);
ps_stroke($ps);
ps_end_pattern($ps);

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "both", "pattern", $pspattern, 0.0, 0.0, 0.0);
ps_rect($ps, 50, 400, 200, 200);
ps_fill($ps);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?>

Zobacz też:

  • ps_end_pattern() - End a pattern
  • ps_setcolor() - Sets current color
  • ps_shading_pattern() - Creates a pattern based on a shading

ps_begin_page
ps_begin_template
PS Funkcje


Start a new template

ps_begin_pattern
ps_circle
PS Funkcje
PHP Manual

ps_begin_template

(PECL ps >= 1.2.0)

ps_begin_template — Start a new template

Opis

int ps_begin_template ( resource $psdoc , float $width , float $height )

Starts a new template. A template is called a form in the postscript language. It is created similar to a pattern but used like an image. Templates are often used for drawings which are placed several times through out the document, e.g. like a company logo. All drawing functions may be used within a template. The template will not be drawn until it is placed by ps_place_image().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the template in pixel.

height

The height of the template in pixel.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Creating and using a template

<?php
$ps = ps_new();

if (!ps_open_file($ps, "template.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "template.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Template example");

$pstemplate = ps_begin_template($ps, 30.0, 30.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 30, 30);
ps_moveto($ps, 0, 30);
ps_lineto($ps, 30, 0);
ps_stroke($ps);
ps_end_template($ps);

ps_begin_page($ps, 596, 842);
ps_place_image($ps, $pstemplate, 20.0, 20.0, 1.0);
ps_place_image($ps, $pstemplate, 50.0, 30.0, 0.5);
ps_place_image($ps, $pstemplate, 70.0, 70.0, 0.6);
ps_place_image($ps, $pstemplate, 30.0, 50.0, 1.3);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?>

Zobacz też:

  • ps_end_template() - End a template

ps_begin_pattern
ps_circle
PS Funkcje


Draws a circle

ps_begin_template
ps_clip
PS Funkcje
PHP Manual

ps_circle

(PECL ps >= 1.1.0)

ps_circle — Draws a circle

Opis

bool ps_circle ( resource $psdoc , float $x , float $y , float $radius )

Draws a circle with its middle point at (x, y). The circle starts and ends at position (x+radius, y). If this function is called outside a path it will start a new path. If it is called within a path it will add the circle as a subpath. If the last drawing operation does not end in point (x+radius, y) then there will be a gap in the path.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_arc() - Draws an arc counterclockwise
  • ps_arcn() - Draws an arc clockwise

ps_begin_template
ps_clip
PS Funkcje


Clips drawing to current path

ps_circle
ps_close_image
PS Funkcje
PHP Manual

ps_clip

(PECL ps >= 1.1.0)

ps_clip — Clips drawing to current path

Opis

bool ps_clip ( resource $psdoc )

Takes the current path and uses it to define the border of a clipping area. Everything drawn outside of that area will not be visible.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_closepath() - Closes path

ps_circle
ps_close_image
PS Funkcje


Closes image and frees memory

ps_clip
ps_close
PS Funkcje
PHP Manual

ps_close_image

(PECL ps >= 1.1.0)

ps_close_image — Closes image and frees memory

Opis

void ps_close_image ( resource $psdoc , int $imageid )

Closes an image and frees its resources. Once an image is closed it cannot be used anymore.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

imageid

Resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

Zwracane wartości

Returns NULL on success lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • ps_open_image() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

ps_clip
ps_close
PS Funkcje


Closes a PostScript document

ps_close_image
ps_closepath_stroke
PS Funkcje
PHP Manual

ps_close

(PECL ps >= 1.1.0)

ps_close — Closes a PostScript document

Opis

bool ps_close ( resource $psdoc )

Closes the PostScript document.

This function writes the trailer of the PostScript document. It also writes the bookmark tree. ps_close() does not free any resources, which is done by ps_delete().

This function is also called by ps_delete() if it has not been called before.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_open_file() - Opens a file for output
  • ps_delete() - Deletes all resources of a PostScript document

ps_close_image
ps_closepath_stroke
PS Funkcje


Closes and strokes path

ps_close
ps_closepath
PS Funkcje
PHP Manual

ps_closepath_stroke

(PECL ps >= 1.1.0)

ps_closepath_stroke — Closes and strokes path

Opis

bool ps_closepath_stroke ( resource $psdoc )

Connects the last point with first point of a path and draws the resulting closed line.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_closepath() - Closes path

ps_close
ps_closepath
PS Funkcje


Closes path

ps_closepath_stroke
ps_continue_text
PS Funkcje
PHP Manual

ps_closepath

(PECL ps >= 1.1.0)

ps_closepath — Closes path

Opis

bool ps_closepath ( resource $psdoc )

Connects the last point with the first point of a path. The resulting path can be used for stroking, filling, clipping, etc..

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_clip() - Clips drawing to current path
  • ps_closepath_stroke() - Closes and strokes path

ps_closepath_stroke
ps_continue_text
PS Funkcje


Continue text in next line

ps_closepath
ps_curveto
PS Funkcje
PHP Manual

ps_continue_text

(PECL ps >= 1.1.0)

ps_continue_text — Continue text in next line

Opis

bool ps_continue_text ( resource $psdoc , string $text )

Output a text one line below the last line. The line spacing is taken from the value "leading" which must be set with ps_set_value(). The actual position of the text is determined by the values "textx" and "texty" which can be requested with ps_get_value()

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to output.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_show() - Output text
  • ps_show_xy() - Output text at given position
  • ps_show_boxed() - Output text in a box

ps_closepath
ps_curveto
PS Funkcje


Draws a curve

ps_continue_text
ps_delete
PS Funkcje
PHP Manual

ps_curveto

(PECL ps >= 1.1.0)

ps_curveto — Draws a curve

Opis

bool ps_curveto ( resource $psdoc , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Add a section of a cubic Bézier curve described by the three given control points to the current path.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x1

x-coordinate of first control point.

y1

y-coordinate of first control point.

x2

x-coordinate of second control point.

y2

y-coordinate of second control point.

x3

x-coordinate of third control point.

y3

y-coordinate of third control point.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_lineto() - Draws a line

ps_continue_text
ps_delete
PS Funkcje


Deletes all resources of a PostScript document

ps_curveto
ps_end_page
PS Funkcje
PHP Manual

ps_delete

(PECL ps >= 1.1.0)

ps_delete — Deletes all resources of a PostScript document

Opis

bool ps_delete ( resource $psdoc )

Mainly frees memory used by the document. Also closes a file, if it was not closed before with ps_close(). You should in any case close the file with ps_close() before, because ps_close() not just closes the file but also outputs a trailor containing PostScript comments like the number of pages in the document and adding the bookmark hierarchy.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_close() - Closes a PostScript document

ps_curveto
ps_end_page
PS Funkcje


End a page

ps_delete
ps_end_pattern
PS Funkcje
PHP Manual

ps_end_page

(PECL ps >= 1.1.0)

ps_end_page — End a page

Opis

bool ps_end_page ( resource $psdoc )

Ends a page which was started with ps_begin_page(). Ending a page will leave the current drawing context, which e.g. requires to reload fonts if they were loading within the page, and to set many other drawing parameters like the line width, or color..

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_begin_page() - Start a new page

ps_delete
ps_end_pattern
PS Funkcje


End a pattern

ps_end_page
ps_end_template
PS Funkcje
PHP Manual

ps_end_pattern

(PECL ps >= 1.2.0)

ps_end_pattern — End a pattern

Opis

bool ps_end_pattern ( resource $psdoc )

Ends a pattern which was started with ps_begin_pattern(). Once a pattern has been ended, it can be used like a color to fill areas.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_begin_pattern() - Start a new pattern

ps_end_page
ps_end_template
PS Funkcje


End a template

ps_end_pattern
ps_fill_stroke
PS Funkcje
PHP Manual

ps_end_template

(PECL ps >= 1.2.0)

ps_end_template — End a template

Opis

bool ps_end_template ( resource $psdoc )

Ends a template which was started with ps_begin_template(). Once a template has been ended, it can be used like an image.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_begin_template() - Start a new template

ps_end_pattern
ps_fill_stroke
PS Funkcje


Fills and strokes the current path

ps_end_template
ps_fill
PS Funkcje
PHP Manual

ps_fill_stroke

(PECL ps >= 1.1.0)

ps_fill_stroke — Fills and strokes the current path

Opis

bool ps_fill_stroke ( resource $psdoc )

Fills and draws the path constructed with previously called drawing functions like ps_lineto().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_fill() - Fills the current path
  • ps_stroke() - Draws the current path

ps_end_template
ps_fill
PS Funkcje


Fills the current path

ps_fill_stroke
ps_findfont
PS Funkcje
PHP Manual

ps_fill

(PECL ps >= 1.1.0)

ps_fill — Fills the current path

Opis

bool ps_fill ( resource $psdoc )

Fills the path constructed with previously called drawing functions like ps_lineto().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_fill_stroke() - Fills and strokes the current path
  • ps_stroke() - Draws the current path

ps_fill_stroke
ps_findfont
PS Funkcje


Loads a font

ps_fill
ps_get_buffer
PS Funkcje
PHP Manual

ps_findfont

(PECL ps >= 1.1.0)

ps_findfont — Loads a font

Opis

int ps_findfont ( resource $psdoc , string $fontname , string $encoding [, bool $embed = false ] )

Loads a font for later use. Before text is output with a loaded font it must be set with ps_setfont(). This function needs the adobe font metric file in order to calculate the space used up by the characters. A font which is loaded within a page will only be available on that page. Fonts which are to be used in the complete document have to be loaded before the first call of ps_begin_page(). Calling ps_findfont() between pages will make that font available for all following pages.

The name of the afm file must be fontname.afm. If the font shall be embedded the file fontname.pfb containing the font outline must be present as well.

Calling ps_findfont() before the first page requires to output the postscript header which includes the BoundingBox for the whole document. Usually the BoundingBox is set with the first call of ps_begin_page() which now comes after ps_findfont(). Consequently the BoundingBox has not been set and a warning will be issued when ps_findfont() is called. In order to prevent this situation, one should call ps_set_parameter() to set the BoundingBox before ps_findfont() is called.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

fontname

The name of the font.

encoding

ps_findfont() will try to load the file passed in the parameter encoding. Encoding files are of the same syntax as those used by dvips(1). They contain a font encoding vector (which is currently not used but must be present) and a list of extra ligatures to extend the list of ligatures derived from the afm file.

encoding can be NULL or the empty string if the default encoding (TeXBase1) shall be used.

If the encoding is set to builtin then there will be no reencoding and the font specific encoding will be used. This is very useful with symbol fonts.

embed

If set to a value >0 the font will be embedded into the document. This requires the font outline (.pfb file) to be present.

Zwracane wartości

Returns the identifier of the font or zero in case of an error. The identifier is a positive number.

Zobacz też:

  • ps_begin_page() - Start a new page
  • ps_setfont() - Sets font to use for following output

ps_fill
ps_get_buffer
PS Funkcje


Fetches the full buffer containig the generated PS data

ps_findfont
ps_get_parameter
PS Funkcje
PHP Manual

ps_get_buffer

(PECL ps >= 1.1.0)

ps_get_buffer — Fetches the full buffer containig the generated PS data

Opis

string ps_get_buffer ( resource $psdoc )

This function is not implemented yet. It will always return an empty string. The idea for a later implementation is to write the contents of the postscript file into an internal buffer if in memory creation is requested, and retrieve the buffer content with this function. Currently, documents created in memory are send to the browser without buffering.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zobacz też:

  • ps_open_file() - Opens a file for output

ps_findfont
ps_get_parameter
PS Funkcje


Gets certain parameters

ps_get_buffer
ps_get_value
PS Funkcje
PHP Manual

ps_get_parameter

(PECL ps >= 1.1.0)

ps_get_parameter — Gets certain parameters

Opis

string ps_get_parameter ( resource $psdoc , string $name [, float $modifier ] )

Gets several parameters which were directly set by ps_set_parameter() or indirectly by one of the other functions. Parameters are by definition string values. This function cannot be used to retrieve resources which were also set by ps_set_parameter().

The parameter name can have the following values.

fontname

The name of the currently active font or the font whose identifier is passed in parameter modifier.

fontencoding

The encoding of the currently active font.

dottedversion

The version of the underlying pslib library in the format <major>.<minor>.<subminor>

scope

The current drawing scope. Can be object, document, null, page, pattern, path, template, prolog, font, glyph.

ligaturedisolvechar

The character which dissolves a ligature. If your are using a font which contains the ligature `ff' and `|' is the char to dissolve the ligature, then `f|f' will result in two `f' instead of the ligature `ff'.

imageencoding

The encoding used for encoding images. Can be either hex or 85. hex encoding uses two bytes in the postscript file each byte in the image. 85 stand for Ascii85 encoding.

linenumbermode

Set to paragraph if lines are numbered within a paragraph or box if they are numbered within the surrounding box.

linebreak

Only used if text is output with ps_show_boxed(). If set to TRUE a carriage return will add a line break.

parbreak

Only used if text is output with ps_show_boxed(). If set to TRUE a carriage return will start a new paragraph.

hyphenation

Only used if text is output with ps_show_boxed(). If set to TRUE the paragraph will be hyphenated if a hypen dictionary is set and exists.

hyphendict

Filename of the dictionary used for hyphenation pattern.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the parameter.

modifier

An identifier needed if a parameter of a resource is requested, e.g. the size of an image. In such a case the resource id is passed.

Zwracane wartości

Returns the value of the parameter lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • ps_set_parameter() - Sets certain parameters

ps_get_buffer
ps_get_value
PS Funkcje


Gets certain values

ps_get_parameter
ps_hyphenate
PS Funkcje
PHP Manual

ps_get_value

(PECL ps >= 1.1.0)

ps_get_value — Gets certain values

Opis

float ps_get_value ( resource $psdoc , string $name [, float $modifier ] )

Gets several values which were set by ps_set_value(). Values are by definition float values.

The parameter name can have the following values.

fontsize

The size of the currently active font or the font whose identifier is passed in parameter modifier.

font

The currently active font itself.

imagewidth

The width of the image whose id is passed in the parameter modifier.

imageheight

The height of the image whose id is passed in the parameter modifier.

capheight

The height of a capital M in the currently active font or the font whose identifier is passed in parameter modifier.

ascender

The ascender of the currently active font or the font whose identifier is passed in parameter modifier.

descender

The descender of the currently active font or the font whose identifier is passed in parameter modifier.

italicangle

The italicangle of the currently active font or the font whose identifier is passed in parameter modifier.

underlineposition

The underlineposition of the currently active font or the font whose identifier is passed in parameter modifier.

underlinethickness

The underlinethickness of the currently active font or the font whose identifier is passed in parameter modifier.

textx

The current x-position for text output.

texty

The current y-position for text output.

textrendering

The current mode for text rendering.

textrise

The space by which text is risen above the base line.

leading

The distance between text lines in points.

wordspacing

The space between words as a multiple of the width of a space char.

charspacing

The space between chars. If charspacing is != 0.0 ligatures will always be dissolved.

hyphenminchars

Minimum number of chars hyphenated at the end of a word.

parindent

Indention of the first n line in a paragraph.

numindentlines

Number of line in a paragraph to indent if parindent != 0.0.

parskip

Distance between paragraphs.

linenumberspace

Overall space in front of each line for the line number.

linenumbersep

Space between the line and the line number.

major

The major version number of pslib.

minor

The minor version number of pslib.

subminor, revision

The subminor version number of pslib.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the value.

modifier

The parameter modifier specifies the resource for which the value is to be retrieved. This can be the id of a font or an image.

Zwracane wartości

Returns the value of the parameter or FALSE.

Zobacz też:

  • ps_set_value() - Sets certain values

ps_get_parameter
ps_hyphenate
PS Funkcje


Hyphenates a word

ps_get_value
ps_include_file
PS Funkcje
PHP Manual

ps_hyphenate

(PECL ps >= 1.1.1)

ps_hyphenate — Hyphenates a word

Opis

array ps_hyphenate ( resource $psdoc , string $text )

Hyphenates the passed word. ps_hyphenate() evaluates the value hyphenminchars (set by ps_set_value()) and the parameter hyphendict (set by ps_set_parameter()). hyphendict must be set before calling this function.

This function requires the locale category LC_CTYPE to be set properly. This is done when the extension is initialized by using the environment variables. On Unix systems read the man page of locale for more information.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

text should not contain any non alpha characters. Possible positions for breaks are returned in an array of interger numbers. Each number is the position of the char in text after which a hyphenation can take place.

Zwracane wartości

An array of integers indicating the position of possible breaks in the text lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Hyphennate a text

<?php
$word = "Koordinatensystem";
$psdoc = ps_new();
ps_set_parameter($psdoc, "hyphendict", "hyph_de.dic");
$hyphens = ps_hyphenate($psdoc, $word);
for($i=0; $i<strlen($word); $i++) {
  echo $word[$i];
  if(in_array($i, $hyphens))
    echo "-";
}
ps_delete($psdoc);
?>

Powyższy przykład wyświetli:

Ko-ordi-na-ten-sys-tem

Zobacz też:

  • ps_show_boxed() - Output text in a box
  • locale(1)

ps_get_value
ps_include_file
PS Funkcje


Reads an external file with raw PostScript code

ps_hyphenate
ps_lineto
PS Funkcje
PHP Manual

ps_include_file

(PECL ps >= 1.3.4)

ps_include_file — Reads an external file with raw PostScript code

Opis

bool ps_include_file ( resource $psdoc , string $file )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

file

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ps_hyphenate
ps_lineto
PS Funkcje


Draws a line

ps_include_file
ps_makespotcolor
PS Funkcje
PHP Manual

ps_lineto

(PECL ps >= 1.1.0)

ps_lineto — Draws a line

Opis

bool ps_lineto ( resource $psdoc , float $x , float $y )

Adds a straight line from the current point to the given coordinates to the current path. Use ps_moveto() to set the starting point of the line.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the end point of the line.

y

y-coordinate of the end point of the line.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Drawing a rectangle

<?php
$ps = ps_new();
if (!ps_open_file($ps, "rectangle.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Lineto example");

ps_begin_page($ps, 596, 842);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?>

Zobacz też:

  • ps_moveto() - Sets current point

ps_include_file
ps_makespotcolor
PS Funkcje


Create spot color

ps_lineto
ps_moveto
PS Funkcje
PHP Manual

ps_makespotcolor

(PECL ps >= 1.1.0)

ps_makespotcolor — Create spot color

Opis

int ps_makespotcolor ( resource $psdoc , string $name [, int $reserved = 0 ] )

Creates a spot color from the current fill color. The fill color must be defined in rgb, cmyk or gray colorspace. The spot color name can be an arbitrary name. A spot color can be set as any color with ps_setcolor(). When the document is not printed but displayed by an postscript viewer the given color in the specified color space is use.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the spot color, e.g. Pantone 5565.

Zwracane wartości

The id of the new spot color or 0 in case of an error.

Przykłady

Przykład #1 Creating and using a spot color

<?php
$ps = ps_new();
if (!ps_open_file($ps, "spotcolor.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "spotcolor.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Spot color example");

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "fill", "cmyk", 0.37, 0.0, 0.34, 0.34);
$spotcolor = ps_makespotcolor($ps, "PANTONE 5565 C", 0);
ps_setcolor($ps, "fill", "spot", $spotcolor, 0.5, 0.0, 0.0);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_fill($ps);
ps_end_page($ps);

ps_delete($ps);
?>

This example creates the spot color "PANTONE 5565 C" which is a darker green (olive) and fills a rectangle with 50% intensity.

Zobacz też:

  • ps_setcolor() - Sets current color

ps_lineto
ps_moveto
PS Funkcje


Sets current point

ps_makespotcolor
ps_new
PS Funkcje
PHP Manual

ps_moveto

(PECL ps >= 1.1.0)

ps_moveto — Sets current point

Opis

bool ps_moveto ( resource $psdoc , float $x , float $y )

Sets the current point to new coordinates. If this is the first call of ps_moveto() after a previous path has been ended then it will start a new path. If this function is called in the middle of a path it will just set the current point and start a subpath.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the point to move to.

y

y-coordinate of the point to move to.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_lineto() - Draws a line

ps_makespotcolor
ps_new
PS Funkcje


Creates a new PostScript document object

ps_moveto
ps_open_file
PS Funkcje
PHP Manual

ps_new

(PECL ps >= 1.1.0)

ps_new — Creates a new PostScript document object

Opis

resource ps_new ( void )

Creates a new document instance. It does not create the file on disk or in memory, it just sets up everything. ps_new() is usually followed by a call of ps_open_file() to actually create the postscript document.

Zwracane wartości

Resource of PostScript document lub FALSE w przypadku niepowodzenia. The return value is passed to all other functions as the first argument.

Zobacz też:

  • ps_delete() - Deletes all resources of a PostScript document

ps_moveto
ps_open_file
PS Funkcje


Opens a file for output

ps_new
ps_open_image_file
PS Funkcje
PHP Manual

ps_open_file

(PECL ps >= 1.1.0)

ps_open_file — Opens a file for output

Opis

bool ps_open_file ( resource $psdoc [, string $filename ] )

Creates a new file on disk and writes the PostScript document into it. The file will be closed when ps_close() is called.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

filename

The name of the postscript file. If filename is not passed the document will be created in memory and all output will go straight to the browser.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_close() - Closes a PostScript document

ps_new
ps_open_image_file
PS Funkcje


Opens image from file

ps_open_file
ps_open_image
PS Funkcje
PHP Manual

ps_open_image_file

(PECL ps >= 1.1.0)

ps_open_image_file — Opens image from file

Opis

int ps_open_image_file ( resource $psdoc , string $type , string $filename [, string $stringparam [, int $intparam = 0 ]] )

Loads an image for later use.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of the image. Possible values are png, jpeg, or eps.

filename

The name of the file containing the image data.

stringparam

Not used.

intparam

Not used.

Zwracane wartości

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

Zobacz też:

  • ps_open_image() - Reads an image for later placement
  • ps_place_image() - Places image on the page
  • ps_close_image() - Closes image and frees memory

ps_open_file
ps_open_image
PS Funkcje


Reads an image for later placement

ps_open_image_file
ps_open_memory_image
PS Funkcje
PHP Manual

ps_open_image

(PECL ps >= 1.1.0)

ps_open_image — Reads an image for later placement

Opis

int ps_open_image ( resource $psdoc , string $type , string $source , string $data , int $lenght , int $width , int $height , int $components , int $bpc , string $params )

Reads an image which is already available in memory. The parameter source is currently not evaluated and assumed to be memory. The image data is a sequence of pixels starting in th upper left corner and ending in the lower right corner. Each pixel consists of components color components, and each component has bpc bits.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of the image. Possible values are png, jpeg, or eps.

source

Not used.

data

The image data.

length

The length of the image data.

width

The width of the image.

height

The height of the image.

components

The number of components for each pixel. This can be 1 (gray scale images), 3 (rgb images), or 4 (cmyk, rgba images).

bpc

Number of bits per component (quite often 8).

params

Zwracane wartości

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

Zobacz też:

  • ps_open_image_file() - Opens image from file
  • ps_place_image() - Places image on the page
  • ps_close_image() - Closes image and frees memory

ps_open_image_file
ps_open_memory_image
PS Funkcje


Takes an GD image and returns an image for placement in a PS document

ps_open_image
ps_place_image
PS Funkcje
PHP Manual

ps_open_memory_image

(PECL ps >= 1.1.0)

ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document

Opis

int ps_open_memory_image ( resource $psdoc , int $gd )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

gd

ps_open_image
ps_place_image
PS Funkcje


Places image on the page

ps_open_memory_image
ps_rect
PS Funkcje
PHP Manual

ps_place_image

(PECL ps >= 1.1.0)

ps_place_image — Places image on the page

Opis

bool ps_place_image ( resource $psdoc , int $imageid , float $x , float $y , float $scale )

Places a formerly loaded image on the page. The image can be scaled. If the image shall be rotated as well, you will have to rotate the coordinate system before with ps_rotate().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

imageid

The resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

x

x-coordinate of the lower left corner of the image.

y

y-coordinate of the lower left corner of the image.

scale

The scaling factor for the image. A scale of 1.0 will result in a resolution of 72 dpi, because each pixel is equivalent to 1 point.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_open_image() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

ps_open_memory_image
ps_rect
PS Funkcje


Draws a rectangle

ps_place_image
ps_restore
PS Funkcje
PHP Manual

ps_rect

(PECL ps >= 1.1.0)

ps_rect — Draws a rectangle

Opis

bool ps_rect ( resource $psdoc , float $x , float $y , float $width , float $height )

Draws a rectangle with its lower left corner at (x, y). The rectangle starts and ends in its lower left corner. If this function is called outside a path it will start a new path. If it is called within a path it will add the rectangle as a subpath. If the last drawing operation does not end in the lower left corner then there will be a gap in the path.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the lower left corner of the rectangle.

y

y-coordinate of the lower left corner of the rectangle.

width

The width of the image.

height

The height of the image.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_arc() - Draws an arc counterclockwise
  • ps_cirle()
  • ps_lineto() - Draws a line

ps_place_image
ps_restore
PS Funkcje


Restore previously save context

ps_rect
ps_rotate
PS Funkcje
PHP Manual

ps_restore

(PECL ps >= 1.1.0)

ps_restore — Restore previously save context

Opis

bool ps_restore ( resource $psdoc )

Restores a previously saved graphics context. Any call of ps_save() must be accompanied by a call to ps_restore(). All coordinate transformations, line style settings, color settings, etc. are being restored to the state before the call of ps_save().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_save() - Save current context

ps_rect
ps_rotate
PS Funkcje


Sets rotation factor

ps_restore
ps_save
PS Funkcje
PHP Manual

ps_rotate

(PECL ps >= 1.1.0)

ps_rotate — Sets rotation factor

Opis

bool ps_rotate ( resource $psdoc , float $rot )

Sets the rotation of the coordinate system.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

rot

Angle of rotation in degree.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Rotation of the coordinate system

<?php
function rectangle($ps) {
    ps_moveto($ps, 0, 0);
    ps_lineto($ps, 0, 50);
    ps_lineto($ps, 50, 50);
    ps_lineto($ps, 50, 0);
    ps_lineto($ps, 0, 0);
    ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "rotation.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rotation.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Rotation example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 100, 100);
ps_rotate($ps, 45);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text without rotation");
ps_end_page($ps);

ps_delete($ps);
?>

The above example illustrates a very common way of rotating a graphic (in this case just a rectangle) by simply rotating the coordinate system. Since the graphic's coordinate system assumes (0,0) to be the origin, the page coordinate system is also translated to place the graphics not on the edge of the page. Pay attention to the order of ps_translate() and ps_rotate(). In the above case the rectancle is rotated around the point (100, 100) in the untranslated coordinate system. Switching the two statements has a completely different result.

In order to output the following text at the original position, all modifications of the coordinate system are encapsulated in ps_save() and ps_restore().

Zobacz też:

  • ps_scale() - Sets scaling factor
  • ps_translate() - Sets translation

ps_restore
ps_save
PS Funkcje


Save current context

ps_rotate
ps_scale
PS Funkcje
PHP Manual

ps_save

(PECL ps >= 1.1.0)

ps_save — Save current context

Opis

bool ps_save ( resource $psdoc )

Saves the current graphics context, containing colors, translation and rotation settings and some more. A saved context can be restored with ps_restore().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_restore() - Restore previously save context

ps_rotate
ps_scale
PS Funkcje


Sets scaling factor

ps_save
ps_set_border_color
PS Funkcje
PHP Manual

ps_scale

(PECL ps >= 1.1.0)

ps_scale — Sets scaling factor

Opis

bool ps_scale ( resource $psdoc , float $x , float $y )

Sets horizontal and vertical scaling of the coordinate system.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

Scaling factor in horizontal direction.

y

Scaling factor in vertical direction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_rotate() - Sets rotation factor
  • ps_translate() - Sets translation

ps_save
ps_set_border_color
PS Funkcje


Sets color of border for annotations

ps_scale
ps_set_border_dash
PS Funkcje
PHP Manual

ps_set_border_color

(PECL ps >= 1.1.0)

ps_set_border_color — Sets color of border for annotations

Opis

bool ps_set_border_color ( resource $psdoc , float $red , float $green , float $blue )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the color of the rectangle's border line.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

red

The red component of the border color.

green

The green component of the border color.

blue

The blue component of the border color.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_set_border_dash() - Sets length of dashes for border of annotations
  • ps_set_border_style() - Sets border style of annotations

ps_scale
ps_set_border_dash
PS Funkcje


Sets length of dashes for border of annotations

ps_set_border_color
ps_set_border_style
PS Funkcje
PHP Manual

ps_set_border_dash

(PECL ps >= 1.1.0)

ps_set_border_dash — Sets length of dashes for border of annotations

Opis

bool ps_set_border_dash ( resource $psdoc , float $black , float $white )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the length of the black and white portion of a dashed border line.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

black

The length of the dash.

white

The length of the gap between dashes.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_set_border_color() - Sets color of border for annotations
  • ps_set_border_style() - Sets border style of annotations

ps_set_border_color
ps_set_border_style
PS Funkcje


Sets border style of annotations

ps_set_border_dash
ps_set_info
PS Funkcje
PHP Manual

ps_set_border_style

(PECL ps >= 1.1.0)

ps_set_border_style — Sets border style of annotations

Opis

bool ps_set_border_style ( resource $psdoc , string $style , float $width )

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the appearance and width of the border line.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

style

style can be solid or dashed.

width

The line width of the border.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_set_border_color() - Sets color of border for annotations
  • ps_set_border_dash() - Sets length of dashes for border of annotations

ps_set_border_dash
ps_set_info
PS Funkcje


Sets information fields of document

ps_set_border_style
ps_set_parameter
PS Funkcje
PHP Manual

ps_set_info

(PECL ps >= 1.1.0)

ps_set_info — Sets information fields of document

Opis

bool ps_set_info ( resource $p , string $key , string $val )

Sets certain information fields of the document. This fields will be shown as a comment in the header of the PostScript file. If the document is converted to pdf this fields will also be used for the document information.

The BoundingBox is usually set to the value given to the first page. This only works if ps_findfont() has not been called before. In such cases the BoundingBox would be left unset unless you set it explicitly with this function.

This function will have no effect anymore when the header of the postscript file has been already written. It must be called before the first page or the first call of ps_findfont().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

key

The name of the information field to set. The values which can be set are Keywords, Subject, Title, Creator, Author, BoundingBox, and Orientation. Be aware that some of them has a meaning to PostScript viewers.

value

The value of the information field. The field Orientation can be set to either Portrait or Landscape. The BoundingBox is a string consisting of four numbers. The first two numbers are the coordinates of the lower left corner of the page. The last two numbers are the coordinates of the upper right corner.

Informacja:

Up to version 0.2.6 of pslib, the BoundingBox and Orientation will be overwritten by ps_begin_page(), unless ps_findfont() has been called before.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_findfont() - Loads a font
  • ps_begin_page() - Start a new page

ps_set_border_style
ps_set_parameter
PS Funkcje


Sets certain parameters

ps_set_info
ps_set_text_pos
PS Funkcje
PHP Manual

ps_set_parameter

(PECL ps >= 1.1.0)

ps_set_parameter — Sets certain parameters

Opis

bool ps_set_parameter ( resource $psdoc , string $name , string $value )

Sets several parameters which are used by many functions. Parameters are by definition string values.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

For a list of possible names see ps_get_parameter().

value

The value of the parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_get_parameters()
  • ps_set_value() - Sets certain values

ps_set_info
ps_set_text_pos
PS Funkcje


Sets position for text output

ps_set_parameter
ps_set_value
PS Funkcje
PHP Manual

ps_set_text_pos

(PECL ps >= 1.1.0)

ps_set_text_pos — Sets position for text output

Opis

bool ps_set_text_pos ( resource $psdoc , float $x , float $y )

Set the position for the next text output. You may alternatively set the x and y value separately by calling ps_set_value() and choosing textx respectively texty as the value name.

If you want to output text at a certain position it is more convenient to use ps_show_xy() instead of setting the text position and calling ps_show().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the new text position.

y

y-coordinate of the new text position.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Placing text at a given position

<?php
$ps = ps_new();
if (!ps_open_file($ps, "text.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Text placement example");

ps_begin_page($ps, 596, 842);
$psfont = ps_findfont($ps, "Helvetica", "", 0);
ps_setfont($ps, $psfont, 8.0);
ps_show_xy($ps, "Some text at (100, 100)", 100, 100);

ps_set_value($ps, "textx", 100);
ps_set_value($ps, "texty", 120);
ps_show($ps, "Some text at (100, 120)");
ps_end_page($ps);

ps_delete($ps);
?>

Zobacz też:

  • ps_set_value() - Sets certain values
  • ps_show() - Output text

ps_set_parameter
ps_set_value
PS Funkcje


Sets certain values

ps_set_text_pos
ps_setcolor
PS Funkcje
PHP Manual

ps_set_value

(PECL ps >= 1.1.0)

ps_set_value — Sets certain values

Opis

bool ps_set_value ( resource $psdoc , string $name , float $value )

Sets several values which are used by many functions. Parameters are by definition float values.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

The name can be one of the following:

textrendering

The way how text is shown.

textx

The x coordinate for text output.

texty

The y coordinate for text output.

wordspacing

The distance between words relative to the width of a space.

leading

The distance between lines in pixels.

value

The value of the parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_get_value() - Gets certain values
  • ps_set_parameter() - Sets certain parameters

ps_set_text_pos
ps_setcolor
PS Funkcje


Sets current color

ps_set_value
ps_setdash
PS Funkcje
PHP Manual

ps_setcolor

(PECL ps >= 1.1.0)

ps_setcolor — Sets current color

Opis

bool ps_setcolor ( resource $psdoc , string $type , string $colorspace , float $c1 , float $c2 , float $c3 , float $c4 )

Sets the color for drawing, filling, or both.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The parameter type can be both, fill, or fillstroke.

colorspace

The colorspace should be one of gray, rgb, cmyk, spot, pattern. Depending on the colorspace either only the first, the first three or all parameters will be used.

c1

Depending on the colorspace this is either the red component (rgb), the cyan component (cmyk), the gray value (gray), the identifier of the spot color or the identifier of the pattern.

c2

Depending on the colorspace this is either the green component (rgb), the magenta component (cmyk).

c3

Depending on the colorspace this is either the blue component (rgb), the yellow component (cmyk).

c4

This must only be set in cmyk colorspace and specifies the black component.

Bugs

The second parameter is currently not always evaluated. The color is sometimes set for filling and drawing just as if fillstroke were passed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ps_set_value
ps_setdash
PS Funkcje


Sets appearance of a dashed line

ps_setcolor
ps_setflat
PS Funkcje
PHP Manual

ps_setdash

(PECL ps >= 1.1.0)

ps_setdash — Sets appearance of a dashed line

Opis

bool ps_setdash ( resource $psdoc , float $on , float $off )

Sets the length of the black and white portions of a dashed line.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

on

The length of the dash.

off

The length of the gap between dashes.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_setpolydash() - Sets appearance of a dashed line

ps_setcolor
ps_setflat
PS Funkcje


Sets flatness

ps_setdash
ps_setfont
PS Funkcje
PHP Manual

ps_setflat

(PECL ps >= 1.1.0)

ps_setflat — Sets flatness

Opis

bool ps_setflat ( resource $psdoc , float $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The value must be between 0.2 and 1.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ps_setdash
ps_setfont
PS Funkcje


Sets font to use for following output

ps_setflat
ps_setgray
PS Funkcje
PHP Manual

ps_setfont

(PECL ps >= 1.1.0)

ps_setfont — Sets font to use for following output

Opis

bool ps_setfont ( resource $psdoc , int $fontid , float $size )

Sets a font, which has to be loaded before with ps_findfont(). Outputting text without setting a font results in an error.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

fontid

The font identifier as returned by ps_findfont().

size

The size of the font.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_findfont() - Loads a font
  • ps_set_text_pos() - Sets position for text output for an example.

ps_setflat
ps_setgray
PS Funkcje


Sets gray value

ps_setfont
ps_setlinecap
PS Funkcje
PHP Manual

ps_setgray

(PECL ps >= 1.1.0)

ps_setgray — Sets gray value

Opis

bool ps_setgray ( resource $psdoc , float $gray )

Sets the gray value for all following drawing operations.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

gray

The value must be between 0 (white) and 1 (black).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_setcolor() - Sets current color

ps_setfont
ps_setlinecap
PS Funkcje


Sets appearance of line ends

ps_setgray
ps_setlinejoin
PS Funkcje
PHP Manual

ps_setlinecap

(PECL ps >= 1.1.0)

ps_setlinecap — Sets appearance of line ends

Opis

bool ps_setlinecap ( resource $psdoc , int $type )

Sets how line ends look like.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of line ends. Possible values are PS_LINECAP_BUTT, PS_LINECAP_ROUND, or PS_LINECAP_SQUARED.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

ps_setgray
ps_setlinejoin
PS Funkcje


Sets how contected lines are joined

ps_setlinecap
ps_setlinewidth
PS Funkcje
PHP Manual

ps_setlinejoin

(PECL ps >= 1.1.0)

ps_setlinejoin — Sets how contected lines are joined

Opis

bool ps_setlinejoin ( resource $psdoc , int $type )

Sets how lines are joined.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The way lines are joined. Possible values are PS_LINEJOIN_MITER, PS_LINEJOIN_ROUND, or PS_LINEJOIN_BEVEL.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

ps_setlinecap
ps_setlinewidth
PS Funkcje


Sets width of a line

ps_setlinejoin
ps_setmiterlimit
PS Funkcje
PHP Manual

ps_setlinewidth

(PECL ps >= 1.1.0)

ps_setlinewidth — Sets width of a line

Opis

bool ps_setlinewidth ( resource $psdoc , float $width )

Sets the line width for all following drawing operations.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of lines in points.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setmiterlimit() - Sets the miter limit

ps_setlinejoin
ps_setmiterlimit
PS Funkcje


Sets the miter limit

ps_setlinewidth
ps_setoverprintmode
PS Funkcje
PHP Manual

ps_setmiterlimit

(PECL ps >= 1.1.0)

ps_setmiterlimit — Sets the miter limit

Opis

bool ps_setmiterlimit ( resource $psdoc , float $value )

If two lines join in a small angle and the line join is set to PS_LINEJOIN_MITER, then the resulting spike will be very long. The miter limit is the maximum ratio of the miter length (the length of the spike) and the line width.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The maximum ratio between the miter length and the line width. Larger values (> 10) will result in very long spikes when two lines meet in a small angle. Keep the default unless you know what you are doing.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setlinewidth() - Sets width of a line

ps_setlinewidth
ps_setoverprintmode
PS Funkcje


Sets overprint mode

ps_setmiterlimit
ps_setpolydash
PS Funkcje
PHP Manual

ps_setoverprintmode

(PECL ps >= 1.3.0)

ps_setoverprintmode — Sets overprint mode

Opis

bool ps_setoverprintmode ( resource $psdoc , int $mode )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

mode

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ps_setmiterlimit
ps_setpolydash
PS Funkcje


Sets appearance of a dashed line

ps_setoverprintmode
ps_shading_pattern
PS Funkcje
PHP Manual

ps_setpolydash

(PECL ps >= 1.1.0)

ps_setpolydash — Sets appearance of a dashed line

Opis

bool ps_setpolydash ( resource $psdoc , float $arr )

Sets the length of the black and white portions of a dashed line. ps_setpolydash() is used to set more complicated dash patterns.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

arr

arr is a list of length elements alternately for the black and white portion.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Drawing a dashed line

<?php
$ps = ps_new();
if (!ps_open_file($ps, "polydash.ps")) {
   print "Cannot open PostScript file\n";
     exit;
}

ps_set_info($ps, "Creator", "polydash.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Poly dash example");

ps_begin_page($ps, 596, 842);
ps_setpolydash($ps, array(10, 5, 2, 5));
ps_moveto($ps, 100, 100);
ps_lineto($ps, 200, 200);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?>

This example draws a line with a 10 and 2 points long line, and gaps of 5 points inbetween.

Zobacz też:

  • ps_setdash() - Sets appearance of a dashed line

ps_setoverprintmode
ps_shading_pattern
PS Funkcje


Creates a pattern based on a shading

ps_setpolydash
ps_shading
PS Funkcje
PHP Manual

ps_shading_pattern

(PECL ps >= 1.3.0)

ps_shading_pattern — Creates a pattern based on a shading

Opis

int ps_shading_pattern ( resource $psdoc , int $shadingid , string $optlist )

Creates a pattern based on a shading, which has to be created before with ps_shading(). Shading patterns can be used like regular patterns.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

optlist

This argument is not currently used.

Zwracane wartości

The identifier of the pattern lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • ps_shading() - Creates a shading for later use
  • ps_shfill() - Fills an area with a shading

ps_setpolydash
ps_shading
PS Funkcje


Creates a shading for later use

ps_shading_pattern
ps_shfill
PS Funkcje
PHP Manual

ps_shading

(PECL ps >= 1.3.0)

ps_shading — Creates a shading for later use

Opis

int ps_shading ( resource $psdoc , string $type , float $x0 , float $y0 , float $x1 , float $y1 , float $c1 , float $c2 , float $c3 , float $c4 , string $optlist )

Creates a shading, which can be used by ps_shfill() or ps_shading_pattern().

The color of the shading can be in any color space except for pattern.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of shading can be either radial or axial. Each shading starts with the current fill color and ends with the given color values passed in the parameters c1 to c4 (see ps_setcolor() for their meaning).

x0, x1, y0, y1

The coordinates x0, y0, x1, y1 are the start and end point of the shading. If the type of shading is radial the two points are the middle points of a starting and ending circle.

c1, c2, c3, c4

See ps_setcolor() for their meaning.

optlist

If the shading is of type radial the optlist must also contain the parameters r0 and r1 with the radius of the start and end circle.

Zwracane wartości

Returns the identifier of the pattern lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • ps_shading_pattern() - Creates a pattern based on a shading
  • ps_shfill() - Fills an area with a shading

ps_shading_pattern
ps_shfill
PS Funkcje


Fills an area with a shading

ps_shading
ps_show_boxed
PS Funkcje
PHP Manual

ps_shfill

(PECL ps >= 1.3.0)

ps_shfill — Fills an area with a shading

Opis

bool ps_shfill ( resource $psdoc , int $shadingid )

Fills an area with a shading, which has to be created before with ps_shading(). This is an alternative way to creating a pattern from a shading ps_shading_pattern() and using the pattern as the filling color.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_shading() - Creates a shading for later use
  • ps_shading_pattern() - Creates a pattern based on a shading

ps_shading
ps_show_boxed
PS Funkcje


Output text in a box

ps_shfill
ps_show_xy2
PS Funkcje
PHP Manual

ps_show_boxed

(PECL ps >= 1.1.0)

ps_show_boxed — Output text in a box

Opis

int ps_show_boxed ( resource $psdoc , string $text , float $left , float $bottom , float $width , float $height , string $hmode [, string $feature ] )

Outputs a text in a given box. The lower left corner of the box is at (left, bottom). Line breaks will be inserted where needed. Multiple spaces are treated as one. Tabulators are treated as spaces.

The text will be hyphenated if the parameter hyphenation is set to TRUE and the parameter hyphendict contains a valid filename for a hyphenation file. The line spacing is taken from the value leading. Paragraphs can be separated by an empty line just like in TeX. If the value parindent is set to value > 0.0 then the first n lines will be indented. The number n of lines is set by the parameter numindentlines. In order to prevent indenting of the first m paragraphs set the value parindentskip to a positive number.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output into the given box.

left

x-coordinate of the lower left corner of the box.

bottom

y-coordinate of the lower left corner of the box.

width

Width of the box.

height

Height of the box.

hmode

The parameter hmode can be "justify", "fulljustify", "right", "left", or "center". The difference of "justify" and "fulljustify" just affects the last line of the box. In fulljustify mode the last line will be left and right justified unless this is also the last line of paragraph. In justify mode it will always be left justified.

feature

Used parameters

The output of ps_show_boxed() can be configured with several parameters and values which must be set with either ps_set_parameter() or ps_set_value(). Beside the parameters and values which affect text output, the following parameters and values are evaluated.

leading (value)

Distance between baselines of two consecutive lines.

linebreak (parameter)

Set to "true" if you want a carriage return to start a new line instead of treating it as a space. Defaults to "false".

parbreak (parameter)

Set to "true" if you want a carriage return on a single line to start a new paragraph instead of treating it as a space. Defaults to "true".

hyphenation (parameter)

Set to "true" in order to turn hyphenation on. This requires a dictionary to be set with the parameter "hyphendict". Defaults to "false".

hyphendict (parameter)

Filename of the dictionary used for hyphenation pattern (see below).

hyphenminchar (value)

The number of chars which must at least be left over before or after the hyphen. This implies that only words of at least two times this value will be hyphenated. The default value is three. Setting a value of zero will result in the default value.

parindent (value)

Set the amount of space in pixel for indenting the first m lines of a paragraph. m can be set with the value "numindentlines".

parskip (value)

Set the amount of extra space in pixel between paragraphs. Defaults to 0 which will result in a normal line distance.

numindentlines (value)

Number of lines from the start of the paragraph which will be indented. Defaults to 1.

parindentskip (value)

Number of paragraphs in the box whose first lines will not be indented. This defaults to 0. This is useful for paragraphs right after a section heading or text being continued in a second box. In both case one would set this to 1.

linenumbermode (parameter)

Set how lines are to be numbered. Possible values are "box" for numbering lines in the whole box or "paragraph" to number lines within each paragraph.

linenumberspace (value)

The space for the column left of the numbered line containing the line number. The line number will be right justified into this column. Defaults to 20.

linenumbersep (value)

The space between the column with line numbers and the line itself. Defaults to 5.

Hyphenation

Text is hyphenated if the parameter hyphenation is set to true and a valid hyphenation dictionary is set. pslib does not ship its own hyphenation dictionary but uses one from openoffice, scribus or koffice. You can find their dictionaries for different languages in one of the following directories if the software is installed:

  • /usr/share/apps/koffice/hyphdicts/
  • /usr/lib/scribus/dicts/
  • /usr/lib/openoffice/share/dict/ooo/
Currently scribus appears to have the most complete hyphenation dictionaries.

Zwracane wartości

Number of characters that could not be written.

Zobacz też:

  • ps_continue_text() - Continue text in next line

ps_shfill
ps_show_xy2
PS Funkcje


Output text at position

ps_show_boxed
ps_show_xy
PS Funkcje
PHP Manual

ps_show_xy2

(PECL ps >= 1.1.0)

ps_show_xy2 — Output text at position

Opis

bool ps_show_xy2 ( resource $psdoc , string $text , int $len , float $xcoor , float $ycoor )

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.

ps_show_boxed
ps_show_xy
PS Funkcje


Output text at given position

ps_show_xy2
ps_show2
PS Funkcje
PHP Manual

ps_show_xy

(PECL ps >= 1.1.0)

ps_show_xy — Output text at given position

Opis

bool ps_show_xy ( resource $psdoc , string $text , float $x , float $y )

Output a text at the given text position.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

x

x-coordinate of the lower left corner of the box surrounding the text.

y

y-coordinate of the lower left corner of the box surrounding the text.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_continue_text() - Continue text in next line
  • ps_show() - Output text

ps_show_xy2
ps_show2
PS Funkcje


Output a text at current position

ps_show_xy
ps_show
PS Funkcje
PHP Manual

ps_show2

(PECL ps >= 1.1.0)

ps_show2 — Output a text at current position

Opis

bool ps_show2 ( resource $psdoc , string $text , int $len )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

len

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ps_show_xy
ps_show
PS Funkcje


Output text

ps_show2
ps_string_geometry
PS Funkcje
PHP Manual

ps_show

(PECL ps >= 1.1.0)

ps_show — Output text

Opis

bool ps_show ( resource $psdoc , string $text )

Output a text at the current text position. The text position can be set by storing the x and y coordinates into the values textx and texty with the function ps_set_value(). The function will issue an error if a font was not set before with ps_setfont().

ps_show() evaluates the following parameters and values as set by ps_set_parameter() and ps_set_value().

charspacing (value)

Distance between two consecutive glyphs. If this value is unequal to zero then all ligatures will be resolved. Values less than zero are allowed.

kerning (parameter)

Setting this parameter to "false" will turn off kerning. Kerning is turned on by default.

ligatures (parameter)

Setting this parameter to "false" will turn off the use of ligatures. Ligatures are turned on by default.

underline (parameter)

Setting this parameter to "true" will turn on underlining. Underlining is turned off by default.

overline (parameter)

Setting this parameter to "true" will turn on overlining. Overlining is turned off by default.

strikeout (parameter)

Setting this parameter to "true" will turn on striking out. Striking out is turned off by default.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_continue_text() - Continue text in next line
  • ps_show_xy() - Output text at given position
  • ps_setfont() - Sets font to use for following output

ps_show2
ps_string_geometry
PS Funkcje


Gets geometry of a string

ps_show
ps_stringwidth
PS Funkcje
PHP Manual

ps_string_geometry

(PECL ps >= 1.2.0)

ps_string_geometry — Gets geometry of a string

Opis

array ps_string_geometry ( resource $psdoc , string $text [, int $fontid = 0 [, float $size = 0.0 ]] )

This function is similar to ps_stringwidth() but returns an array of dimensions containing the width, ascender, and descender of the text.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text for which the geometry is to be calculated.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Zwracane wartości

An array of the dimensions of a string. The element 'width' contains the width of the string as returned by ps_stringwidth(). The element 'descender' contains the maximum descender and 'ascender' the maximum ascender of the string.

Zobacz też:

  • ps_continue_text() - Continue text in next line
  • ps_stringwidth() - Gets width of a string

ps_show
ps_stringwidth
PS Funkcje


Gets width of a string

ps_string_geometry
ps_stroke
PS Funkcje
PHP Manual

ps_stringwidth

(PECL ps >= 1.1.0)

ps_stringwidth — Gets width of a string

Opis

float ps_stringwidth ( resource $psdoc , string $text [, int $fontid = 0 [, float $size = 0.0 ]] )

Calculates the width of a string in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width. If kerning is turned on, it will be taken into account.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text for which the width is to be calculated.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Zwracane wartości

Width of a string in points.

Zobacz też:

  • ps_string_geometry() - Gets geometry of a string

ps_string_geometry
ps_stroke
PS Funkcje


Draws the current path

ps_stringwidth
ps_symbol_name
PS Funkcje
PHP Manual

ps_stroke

(PECL ps >= 1.1.0)

ps_stroke — Draws the current path

Opis

bool ps_stroke ( resource $psdoc )

Draws the path constructed with previously called drawing functions like ps_lineto().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_closepath_stroke() - Closes and strokes path
  • ps_fill() - Fills the current path
  • ps_fill_stroke() - Fills and strokes the current path

ps_stringwidth
ps_symbol_name
PS Funkcje


Gets name of a glyph

ps_stroke
ps_symbol_width
PS Funkcje
PHP Manual

ps_symbol_name

(PECL ps >= 1.2.0)

ps_symbol_name — Gets name of a glyph

Opis

string ps_symbol_name ( resource $psdoc , int $ord [, int $fontid = 0 ] )

This function needs an Adobe font metrics file to know which glyphs are available.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The parameter ord is the position of the glyph in the font encoding vector.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

Zwracane wartości

The name of a glyph in the given font.

Zobacz też:

  • ps_symbol() - Output a glyph
  • ps_symbol_width() - Gets width of a glyph

ps_stroke
ps_symbol_width
PS Funkcje


Gets width of a glyph

ps_symbol_name
ps_symbol
PS Funkcje
PHP Manual

ps_symbol_width

(PECL ps >= 1.2.0)

ps_symbol_width — Gets width of a glyph

Opis

float ps_symbol_width ( resource $psdoc , int $ord [, int $fontid = 0 [, float $size = 0.0 ]] )

Calculates the width of a glyph in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

Zwracane wartości

The width of a glyph in points.

Zobacz też:

  • ps_symbol() - Output a glyph
  • ps_symbol_name() - Gets name of a glyph

ps_symbol_name
ps_symbol
PS Funkcje


Output a glyph

ps_symbol_width
ps_translate
PS Funkcje
PHP Manual

ps_symbol

(PECL ps >= 1.2.0)

ps_symbol — Output a glyph

Opis

bool ps_symbol ( resource $psdoc , int $ord )

Output the glyph at position ord in the font encoding vector of the current font. The font encoding for a font can be set when loading the font with ps_findfont().

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ps_symbol_name() - Gets name of a glyph
  • ps_symbol_width() - Gets width of a glyph

ps_symbol_width
ps_translate
PS Funkcje


Sets translation

ps_symbol
RPM Reader
PS Funkcje
PHP Manual

ps_translate

(PECL ps >= 1.1.0)

ps_translate — Sets translation

Opis

bool ps_translate ( resource $psdoc , float $x , float $y )

Sets a new initial point of the coordinate system.

Parametry

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the origin of the translated coordinate system.

y

y-coordinate of the origin of the translated coordinate system.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Translation of the coordinate system

<?php
function rectangle($ps) {
    ps_moveto($ps, 0, 0);
    ps_lineto($ps, 0, 50);
    ps_lineto($ps, 50, 50);
    ps_lineto($ps, 50, 0);
    ps_lineto($ps, 0, 0);
    ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "translate.ps")) {
  print "Cannot open PostScript file\n";
  exit;
}

ps_set_info($ps, "Creator", "translate.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Translated example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_translate($ps, -500, -750);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_delete($ps);
?>

The above example demonstrates two possible ways to place a graphic (in this case just a rectangle) at any position on the page, while the graphic itself uses its own coordinate system. The trick is to change the origin of the current coordinate system before drawing the rectangle. The translation has to be undone after the graphic has been drawn.

On the second page a slightly different and more elegant approach is applied. Instead of undoing the translation with a second call of ps_translate() the graphics context is saved before modifying the coordinate system and restored after drawing the rectangle.

Zobacz też:

  • ps_scale() - Sets scaling factor
  • ps_rotate() - Sets rotation factor

ps_symbol
RPM Reader
PS Funkcje


RPM Header Reading

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • RPM Reader Funkcje
    • rpm_close — Closes an RPM file
    • rpm_get_tag — Retrieves a header tag from an RPM file
    • rpm_is_valid — Tests a filename for validity as an RPM file
    • rpm_open — Opens an RPM file
    • rpm_version — Returns a string representing the current version of the rpmreader extension
ps_translate
Wstęp
Generowanie nietekstowych formatów danych


Wstęp

This module allows you to read the meta information stored in the headers of a » RedHat Package Manager (» RPM) file.

RPM Reader
Instalacja/Konfiguracja
RPM Reader


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
RPM Reader


Wymagania

The RPMReader extension requires PHP 5.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/rpmreader.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

There is one resource type used by the RPMReader module. The resource is a file pointer which identifies the RPM file with which to work.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

The following list of constants are used to obtain information using the rpm_get_tag() function. These constants represent the tag number to be retrieved from the RPM file's header section. Descriptions are given below as to what data the tag number constants reference.

RPMREADER_MINIMUM (integer)
The minimum valid value of any RPM tag number.
RPMREADER_NAME (integer)
The name of the RPM package.
RPMREADER_VERSION (integer)
The version of the RPM package.
RPMREADER_RELEASE (integer)
The release of the RPM package.
RPMREADER_EPOCH (integer)
RPMREADER_SERIAL (integer)
RPMREADER_SUMMARY (integer)
The summary text of the RPM package.
RPMREADER_DESCRIPTION (integer)
The full description text of the RPM package.
RPMREADER_BUILDTIME (integer)
The date and time when the RPM package was built.
RPMREADER_BUILDHOST (integer)
The name of the host on which the RPM package was built.
RPMREADER_INSTALLTIME (integer)
RPMREADER_SIZE (integer)
The size of the RPM package.
RPMREADER_DISTRIBUTION (integer)
RPMREADER_VENDOR (integer)
RPMREADER_GIF (integer)
RPMREADER_XPM (integer)
RPMREADER_LICENSE (integer)
RPMREADER_COPYRIGHT (integer)
RPMREADER_PACKAGER (integer)
RPMREADER_GROUP (integer)
RPMREADER_SOURCE (integer)
RPMREADER_PATCH (integer)
RPMREADER_URL (integer)
RPMREADER_OS (integer)
RPMREADER_ARCH (integer)
RPMREADER_PREIN (integer)
RPMREADER_POSTIN (integer)
RPMREADER_PREUN (integer)
RPMREADER_POSTUN (integer)
RPMREADER_OLDFILENAMES (integer)
The list of files in an RPM package (deprecated format). The correct way is now to use a combination of 3 tags (RPMREADER_BASENAMES, RPMREADER_DIRINDEXES, RPMREADER_DIRNAMES) in what RPM now calls "CompressedFileNames". This tag is still used in older RPM files that did not use the "CompressedFileNames" method and is maintained for backward compatibility.
RPMREADER_FILESIZES (integer)
RPMREADER_FILESTATES (integer)
RPMREADER_FILEMODES (integer)
RPMREADER_FILERDEVS (integer)
RPMREADER_FILEMTIMES (integer)
RPMREADER_FILEMD5S (integer)
RPMREADER_FILELINKTOS (integer)
RPMREADER_FILEFLAGS (integer)
RPMREADER_FILEUSERNAME (integer)
RPMREADER_FILEGROUPNAME (integer)
RPMREADER_ICON (integer)
RPMREADER_SOURCERPM (integer)
RPMREADER_FILEVERIFYFLAGS (integer)
RPMREADER_ARCHIVESIZE (integer)
RPMREADER_PROVIDENAME (integer)
RPMREADER_PROVIDES (integer)
RPMREADER_REQUIREFLAGS (integer)
RPMREADER_REQUIRENAME (integer)
RPMREADER_REQUIREVERSION (integer)
RPMREADER_CONFLICTFLAGS (integer)
RPMREADER_CONFLICTNAME (integer)
RPMREADER_CONFLICTVERSION (integer)
RPMREADER_EXCLUDEARCH (integer)
RPMREADER_EXCLUDEOS (integer)
RPMREADER_EXCLUSIVEARCH (integer)
RPMREADER_EXCLUSIVEOS (integer)
RPMREADER_RPMVERSION (integer)
RPMREADER_TRIGGERSCRIPTS (integer)
RPMREADER_TRIGGERNAME (integer)
RPMREADER_TRIGGERVERSION (integer)
RPMREADER_TRIGGERFLAGS (integer)
RPMREADER_TRIGGERINDEX (integer)
RPMREADER_VERIFYSCRIPT (integer)
RPMREADER_CHANGELOGTIME (integer)
The list of dates from changelog entries.
RPMREADER_CHANGELOGNAME (integer)
The list of changelog entry names.
RPMREADER_CHANGELOGTEXT (integer)
The list of the text from changelog entries.
RPMREADER_PREINPROG (integer)
RPMREADER_POSTINPROG (integer)
RPMREADER_PREUNPROG (integer)
RPMREADER_POSTUNPROG (integer)
RPMREADER_BUILDARCHS (integer)
RPMREADER_OBSOLETENAME (integer)
RPMREADER_OBSOLETES (integer)
RPMREADER_VERIFYSCRIPTPROG (integer)
RPMREADER_TRIGGERSCRIPTPROG (integer)
RPMREADER_COOKIE (integer)
RPMREADER_FILEDEVICES (integer)
RPMREADER_FILEINODES (integer)
RPMREADER_FILELANGS (integer)
RPMREADER_PREFIXES (integer)
RPMREADER_INSTPREFIXES (integer)
RPMREADER_PROVIDEFLAGS (integer)
RPMREADER_PROVIDEVERSION (integer)
RPMREADER_OBSOLETEFLAGS (integer)
RPMREADER_OBSOLETEVERSION (integer)
RPMREADER_DIRINDEXES (integer)
The list of indices that relate directory names to files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_BASENAMES (integer)
The list of the names of files in the RPM package without path information. This tag is used in conjunction with RPMREADER_DIRINDEXES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_DIRNAMES (integer)
The list of directory names used by files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRINDEXES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_OPTFLAGS (integer)
RPMREADER_DISTURL (integer)
RPMREADER_PAYLOADFORMAT (integer)
RPMREADER_PAYLOADCOMPRESSOR (integer)
RPMREADER_PAYLOADFLAGS (integer)
RPMREADER_INSTALLCOLOR (integer)
RPMREADER_INSTALLTID (integer)
RPMREADER_REMOVETID (integer)
RPMREADER_RHNPLATFORM (integer)
RPMREADER_PLATFORM (integer)
RPMREADER_PATCHESNAME (integer)
RPMREADER_PATCHESFLAGS (integer)
RPMREADER_PATCHESVERSION (integer)
RPMREADER_CACHECTIME (integer)
RPMREADER_CACHEPKGPATH (integer)
RPMREADER_CACHEPKGSIZE (integer)
RPMREADER_CACHEPKGMTIME (integer)
RPMREADER_FILECOLORS (integer)
RPMREADER_FILECLASS (integer)
RPMREADER_CLASSDICT (integer)
RPMREADER_FILEDEPENDSX (integer)
RPMREADER_FILEDEPENDSN (integer)
RPMREADER_DEPENDSDICT (integer)
RPMREADER_SOURCEPKGID (integer)
RPMREADER_FILECONTEXTS (integer)
RPMREADER_FSCONTEXTS (integer)
RPMREADER_RECONTEXTS (integer)
RPMREADER_POLICIES (integer)
RPMREADER_MAXIMUM (integer)
The maximum valid value of any RPM tag number.

Typy zasobów
Przykłady
RPM Reader


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
RPM Reader


Basic usage

This example will open an RPM file and read the name, version, and release from the RPM file, echo the results, and close the RPM file.

Przykład #1 Basic RPMReader Example

<?php

$filename = "/path/to/file.rpm";

// open file
$rpmr = rpm_open($filename);

// get "Name" tag
$name = rpm_get_tag($rpmr, RPMREADER_NAME);

// get "Version" tag
$ver = rpm_get_tag($rpmr, RPMREADER_VERSION);

// get "Release" tag
$rel = rpm_get_tag($rpmr, RPMREADER_RELEASE);

echo "$name-$ver-$rel<br>\n";

// close file
rpm_close($rpmr);

?>
Przykłady
RPM Reader Funkcje
Przykłady


RPM Reader Funkcje

Spis treści

  • rpm_close — Closes an RPM file
  • rpm_get_tag — Retrieves a header tag from an RPM file
  • rpm_is_valid — Tests a filename for validity as an RPM file
  • rpm_open — Opens an RPM file
  • rpm_version — Returns a string representing the current version of the rpmreader extension
Basic usage
rpm_close
RPM Reader


Closes an RPM file

RPM Reader Funkcje
rpm_get_tag
RPM Reader Funkcje
PHP Manual

rpm_close

(PECL rpmreader >= 0.1.0)

rpm_close — Closes an RPM file

Opis

bool rpm_close ( resource $rpmr )

rpm_close() will close an RPM file pointer.

Parametry

rpmr

A file pointer resource successfully opened by rpm_open().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 rpm_close() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

Zobacz też:

  • rpm_open() - Opens an RPM file

RPM Reader Funkcje
rpm_get_tag
RPM Reader Funkcje


Retrieves a header tag from an RPM file

rpm_close
rpm_is_valid
RPM Reader Funkcje
PHP Manual

rpm_get_tag

(PECL rpmreader >= 0.1.0)

rpm_get_tag — Retrieves a header tag from an RPM file

Opis

mixed rpm_get_tag ( resource $rpmr , int $tagnum )

rpm_get_tag() will retrieve a given tag from the RPM file's header and return it.

Parametry

rpmr

A file pointer resource successfully opened by rpm_open().

tagnum

The tag number to retrieve from the RPM header. This value can be specified using the list of constants defined by this module.

Zwracane wartości

The return value can be of various types depending on the tagnum supplied to the function.

Przykłady

Przykład #1 rpm_get_tag() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

$name = rpm_get_tag($rpmr, RPMREADER_NAME);
echo "$name<br>\n";

rpm_close($rpmr);

?>

Zobacz też:

  • rpm_open() - Opens an RPM file
  • rpm_close() - Closes an RPM file

rpm_close
rpm_is_valid
RPM Reader Funkcje


Tests a filename for validity as an RPM file

rpm_get_tag
rpm_open
RPM Reader Funkcje
PHP Manual

rpm_is_valid

(PECL rpmreader >= 0.1.0)

rpm_is_valid — Tests a filename for validity as an RPM file

Opis

bool rpm_is_valid ( string $filename )

rpm_is_valid() will test an RPM file for validity as an RPM file. This is not the same as rpm_open() as it only checks the file for validity but does not return a file pointer to be used by further functions.

Parametry

filename

The filename of the RPM file you wish to check for validity.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 rpm_is_valid() example

<?php

$file = "/path/to/file.rpm";

if (rpm_is_valid($file)) {
    echo "File is recognized as an RPM file.<br>\n";
}
else {
    echo "File is not recognized as an RPM file.<br>\n";
}

?>

rpm_get_tag
rpm_open
RPM Reader Funkcje


Opens an RPM file

rpm_is_valid
rpm_version
RPM Reader Funkcje
PHP Manual

rpm_open

(PECL rpmreader >= 0.1.0)

rpm_open — Opens an RPM file

Opis

resource rpm_open ( string $filename )

rpm_open() will open an RPM file and will determine if the file is a valid RPM file.

Parametry

filename

The filename of the RPM file you wish to open.

Zwracane wartości

If the open succeeds, then rpm_open() will return a file pointer resource to the newly opened file. On error, the function will return FALSE.

Przykłady

Przykład #1 rpm_open() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

Zobacz też:

  • rpm_close() - Closes an RPM file

rpm_is_valid
rpm_version
RPM Reader Funkcje


Returns a string representing the current version of the rpmreader extension

rpm_open
SWF
RPM Reader Funkcje
PHP Manual

rpm_version

(PECL rpmreader >= 0.3.0)

rpm_version — Returns a string representing the current version of the rpmreader extension

Opis

string rpm_version ( void )

rpm_version() will return the current version of the rpmreader extension.

Zwracane wartości

rpm_version() will return a string representing the rpmreader version currently loaded in PHP.

Przykłady

Przykład #1 rpm_version() example

<?php

$rpmr_ver = rpm_version();

echo "$rpmr_ver<br />\n";

?>

rpm_open
SWF
RPM Reader Funkcje


Shockwave Flash

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • SWF Funkcje
    • swf_actiongeturl — Get a URL from a Shockwave Flash movie
    • swf_actiongotoframe — Play a frame and then stop
    • swf_actiongotolabel — Display a frame with the specified label
    • swf_actionnextframe — Go forward one frame
    • swf_actionplay — Start playing the flash movie from the current frame
    • swf_actionprevframe — Go backwards one frame
    • swf_actionsettarget — Set the context for actions
    • swf_actionstop — Stop playing the flash movie at the current frame
    • swf_actiontogglequality — Toggle between low and high quality
    • swf_actionwaitforframe — Skip actions if a frame has not been loaded
    • swf_addbuttonrecord — Controls location, appearance and active area of the current button
    • swf_addcolor — Set the global add color to the rgba value specified
    • swf_closefile — Close the current Shockwave Flash file
    • swf_definebitmap — Define a bitmap
    • swf_definefont — Defines a font
    • swf_defineline — Define a line
    • swf_definepoly — Define a polygon
    • swf_definerect — Define a rectangle
    • swf_definetext — Define a text string
    • swf_endbutton — End the definition of the current button
    • swf_enddoaction — End the current action
    • swf_endshape — Completes the definition of the current shape
    • swf_endsymbol — End the definition of a symbol
    • swf_fontsize — Change the font size
    • swf_fontslant — Set the font slant
    • swf_fonttracking — Set the current font tracking
    • swf_getbitmapinfo — Get information about a bitmap
    • swf_getfontinfo — Gets font information
    • swf_getframe — Get the frame number of the current frame
    • swf_labelframe — Label the current frame
    • swf_lookat — Define a viewing transformation
    • swf_modifyobject — Modify an object
    • swf_mulcolor — Sets the global multiply color to the rgba value specified
    • swf_nextid — Returns the next free object id
    • swf_oncondition — Describe a transition used to trigger an action list
    • swf_openfile — Open a new Shockwave Flash file
    • swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport
    • swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport
    • swf_perspective — Define a perspective projection transformation
    • swf_placeobject — Place an object onto the screen
    • swf_polarview — Define the viewer's position with polar coordinates
    • swf_popmatrix — Restore a previous transformation matrix
    • swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved
    • swf_pushmatrix — Push the current transformation matrix back onto the stack
    • swf_removeobject — Remove an object
    • swf_rotate — Rotate the current transformation
    • swf_scale — Scale the current transformation
    • swf_setfont — Change the current font
    • swf_setframe — Switch to a specified frame
    • swf_shapearc — Draw a circular arc
    • swf_shapecurveto3 — Draw a cubic bezier curve
    • swf_shapecurveto — Draw a quadratic bezier curve between two points
    • swf_shapefillbitmapclip — Set current fill mode to clipped bitmap
    • swf_shapefillbitmaptile — Set current fill mode to tiled bitmap
    • swf_shapefilloff — Turns off filling
    • swf_shapefillsolid — Set the current fill style to the specified color
    • swf_shapelinesolid — Set the current line style
    • swf_shapelineto — Draw a line
    • swf_shapemoveto — Move the current position
    • swf_showframe — Display the current frame
    • swf_startbutton — Start the definition of a button
    • swf_startdoaction — Start a description of an action list for the current frame
    • swf_startshape — Start a complex shape
    • swf_startsymbol — Define a symbol
    • swf_textwidth — Get the width of a string
    • swf_translate — Translate the current transformations
    • swf_viewport — Select an area for future drawing
rpm_version
Wstęp
Generowanie nietekstowych formatów danych


Wstęp

PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.

Informacja:

The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.

For up to date SWF support take a look at the MING functions.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0.

SWF
Instalacja/Konfiguracja
SWF


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SWF


Wymagania

You need the libswf library to compile PHP with support for this extension. You can download libswf at » ftp://ftp.sgi.com/sgi/graphics/grafica/flash/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/swf.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

MOD_COLOR (integer)
MOD_MATRIX (integer)
TYPE_PUSHBUTTON (integer)
TYPE_MENUBUTTON (integer)
BSHitTest (float)
BSDown (float)
BSOver (float)
BSUp (float)
OverDowntoIdle (integer)
IdletoOverDown (integer)
OutDowntoIdle (integer)
OutDowntoOverDown (integer)
OverDowntoOutDown (integer)
OverUptoOverDown (integer)
OverUptoIdle (integer)
IdletoOverUp (integer)
ButtonEnter (integer)
ButtonExit (integer)
MenuEnter (integer)
MenuExit (integer)
Typy zasobów
Przykłady
SWF


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
SWF


Basic usage

Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:

Przykład #1 SWF example

<?php
swf_openfile("test.swf", 256, 256, 30, 1, 1, 1);
swf_ortho2(-100, 100, -100, 100);
swf_defineline(1, -70, 0, 70, 0, .2);
swf_definerect(4, 60, -10, 70, 0, 0);
swf_definerect(5, -60, 0, -70, 10, 0);
swf_addcolor(0, 0, 0, 0);

swf_definefont(10, "Mod");
swf_fontsize(5);
swf_fontslant(10);
swf_definetext(11, "This be Flash wit PHP!", 1);

swf_pushmatrix();
swf_translate(-50, 80, 0);
swf_placeobject(11, 60);
swf_popmatrix();

for ($i = 0; $i < 30; $i++) {
    $p = $i/(30-1);
    swf_pushmatrix();
    swf_scale(1-($p*.9), 1, 1);
    swf_rotate(60*$p, 'z');
    swf_translate(20+20*$p, $p/1.5, 0);
    swf_rotate(270*$p,  'z');
    swf_addcolor($p, 0, $p/1.2, -$p);
    swf_placeobject(1, 50);
    swf_placeobject(4, 50);
    swf_placeobject(5, 50);
    swf_popmatrix();
    swf_showframe();
}

for ($i = 0; $i < 30; $i++) {
    swf_removeobject(50);
    if (($i%4) == 0) {
        swf_showframe();
    }
}

swf_startdoaction();
swf_actionstop();
swf_enddoaction();

swf_closefile();
?>

Przykłady
SWF Funkcje
Przykłady


SWF Funkcje

Spis treści

  • swf_actiongeturl — Get a URL from a Shockwave Flash movie
  • swf_actiongotoframe — Play a frame and then stop
  • swf_actiongotolabel — Display a frame with the specified label
  • swf_actionnextframe — Go forward one frame
  • swf_actionplay — Start playing the flash movie from the current frame
  • swf_actionprevframe — Go backwards one frame
  • swf_actionsettarget — Set the context for actions
  • swf_actionstop — Stop playing the flash movie at the current frame
  • swf_actiontogglequality — Toggle between low and high quality
  • swf_actionwaitforframe — Skip actions if a frame has not been loaded
  • swf_addbuttonrecord — Controls location, appearance and active area of the current button
  • swf_addcolor — Set the global add color to the rgba value specified
  • swf_closefile — Close the current Shockwave Flash file
  • swf_definebitmap — Define a bitmap
  • swf_definefont — Defines a font
  • swf_defineline — Define a line
  • swf_definepoly — Define a polygon
  • swf_definerect — Define a rectangle
  • swf_definetext — Define a text string
  • swf_endbutton — End the definition of the current button
  • swf_enddoaction — End the current action
  • swf_endshape — Completes the definition of the current shape
  • swf_endsymbol — End the definition of a symbol
  • swf_fontsize — Change the font size
  • swf_fontslant — Set the font slant
  • swf_fonttracking — Set the current font tracking
  • swf_getbitmapinfo — Get information about a bitmap
  • swf_getfontinfo — Gets font information
  • swf_getframe — Get the frame number of the current frame
  • swf_labelframe — Label the current frame
  • swf_lookat — Define a viewing transformation
  • swf_modifyobject — Modify an object
  • swf_mulcolor — Sets the global multiply color to the rgba value specified
  • swf_nextid — Returns the next free object id
  • swf_oncondition — Describe a transition used to trigger an action list
  • swf_openfile — Open a new Shockwave Flash file
  • swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport
  • swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport
  • swf_perspective — Define a perspective projection transformation
  • swf_placeobject — Place an object onto the screen
  • swf_polarview — Define the viewer's position with polar coordinates
  • swf_popmatrix — Restore a previous transformation matrix
  • swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved
  • swf_pushmatrix — Push the current transformation matrix back onto the stack
  • swf_removeobject — Remove an object
  • swf_rotate — Rotate the current transformation
  • swf_scale — Scale the current transformation
  • swf_setfont — Change the current font
  • swf_setframe — Switch to a specified frame
  • swf_shapearc — Draw a circular arc
  • swf_shapecurveto3 — Draw a cubic bezier curve
  • swf_shapecurveto — Draw a quadratic bezier curve between two points
  • swf_shapefillbitmapclip — Set current fill mode to clipped bitmap
  • swf_shapefillbitmaptile — Set current fill mode to tiled bitmap
  • swf_shapefilloff — Turns off filling
  • swf_shapefillsolid — Set the current fill style to the specified color
  • swf_shapelinesolid — Set the current line style
  • swf_shapelineto — Draw a line
  • swf_shapemoveto — Move the current position
  • swf_showframe — Display the current frame
  • swf_startbutton — Start the definition of a button
  • swf_startdoaction — Start a description of an action list for the current frame
  • swf_startshape — Start a complex shape
  • swf_startsymbol — Define a symbol
  • swf_textwidth — Get the width of a string
  • swf_translate — Translate the current transformations
  • swf_viewport — Select an area for future drawing
Basic usage
swf_actiongeturl
SWF


Get a URL from a Shockwave Flash movie

SWF Funkcje
swf_actiongotoframe
SWF Funkcje
PHP Manual

swf_actiongeturl

(PHP 4)

swf_actiongeturl — Get a URL from a Shockwave Flash movie

Opis

void swf_actiongeturl ( string $url , string $target )

Gets the URL specified by the parameter url with the given target.

Parametry

url

The URL, as a string.

target

The target, as a string.

Zwracane wartości

Nie jest zwracana żadna wartość.

SWF Funkcje
swf_actiongotoframe
SWF Funkcje


Play a frame and then stop

swf_actiongeturl
swf_actiongotolabel
SWF Funkcje
PHP Manual

swf_actiongotoframe

(PHP 4)

swf_actiongotoframe — Play a frame and then stop

Opis

void swf_actiongotoframe ( int $framenumber )

The swf_actiongotoframe() function will go to the frame specified by framenumber, play it, and then stop.

Parametry

framenumber

The frame number.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_actiongeturl
swf_actiongotolabel
SWF Funkcje


Display a frame with the specified label

swf_actiongotoframe
swf_actionnextframe
SWF Funkcje
PHP Manual

swf_actiongotolabel

(PHP 4)

swf_actiongotolabel — Display a frame with the specified label

Opis

void swf_actiongotolabel ( string $label )

The swf_actiongotolabel() function displays the frame with the label given by the label parameter and then stops.

Parametry

label

The frame label.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_actiongotoframe
swf_actionnextframe
SWF Funkcje


Go forward one frame

swf_actiongotolabel
swf_actionplay
SWF Funkcje
PHP Manual

swf_actionnextframe

(PHP 4)

swf_actionnextframe — Go forward one frame

Opis

void swf_actionnextframe ( void )

Go forward one frame.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_actionprevframe() - Go backwards one frame

swf_actiongotolabel
swf_actionplay
SWF Funkcje


Start playing the flash movie from the current frame

swf_actionnextframe
swf_actionprevframe
SWF Funkcje
PHP Manual

swf_actionplay

(PHP 4)

swf_actionplay — Start playing the flash movie from the current frame

Opis

void swf_actionplay ( void )

Start playing the flash movie from the current frame.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_actionstop() - Stop playing the flash movie at the current frame

swf_actionnextframe
swf_actionprevframe
SWF Funkcje


Go backwards one frame

swf_actionplay
swf_actionsettarget
SWF Funkcje
PHP Manual

swf_actionprevframe

(PHP 4)

swf_actionprevframe — Go backwards one frame

Opis

void swf_actionprevframe ( void )

Go backwards one frame.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_actionnextframe() - Go forward one frame

swf_actionplay
swf_actionsettarget
SWF Funkcje


Set the context for actions

swf_actionprevframe
swf_actionstop
SWF Funkcje
PHP Manual

swf_actionsettarget

(PHP 4)

swf_actionsettarget — Set the context for actions

Opis

void swf_actionsettarget ( string $target )

Sets the context for all actions. You can use this to control other flash movies that are currently playing.

Parametry

target

The target, as a string.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_actionprevframe
swf_actionstop
SWF Funkcje


Stop playing the flash movie at the current frame

swf_actionsettarget
swf_actiontogglequality
SWF Funkcje
PHP Manual

swf_actionstop

(PHP 4)

swf_actionstop — Stop playing the flash movie at the current frame

Opis

void swf_actionstop ( void )

Stop playing the flash movie at the current frame.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_actionplay() - Start playing the flash movie from the current frame

swf_actionsettarget
swf_actiontogglequality
SWF Funkcje


Toggle between low and high quality

swf_actionstop
swf_actionwaitforframe
SWF Funkcje
PHP Manual

swf_actiontogglequality

(PHP 4)

swf_actiontogglequality — Toggle between low and high quality

Opis

void swf_actiontogglequality ( void )

Toggle the flash movie between high and low quality.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_actionstop
swf_actionwaitforframe
SWF Funkcje


Skip actions if a frame has not been loaded

swf_actiontogglequality
swf_addbuttonrecord
SWF Funkcje
PHP Manual

swf_actionwaitforframe

(PHP 4)

swf_actionwaitforframe — Skip actions if a frame has not been loaded

Opis

void swf_actionwaitforframe ( int $framenumber , int $skipcount )

The swf_actionwaitforframe() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.

Parametry

framenumber

The frame number.

skipcount

The number of actions to skip.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_actiontogglequality
swf_addbuttonrecord
SWF Funkcje


Controls location, appearance and active area of the current button

swf_actionwaitforframe
swf_addcolor
SWF Funkcje
PHP Manual

swf_addbuttonrecord

(PHP 4)

swf_addbuttonrecord — Controls location, appearance and active area of the current button

Opis

void swf_addbuttonrecord ( int $states , int $shapeid , int $depth )

Allow you to define the specifics of using a button.

Parametry

states

Defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp.

shapeid

The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button.

depth

This parameter is the placement of the button in the current frame.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 swf_addbuttonrecord() example

<?php
swf_startButton($objid, TYPE_MENUBUTTON);
swf_addButtonRecord(BSDown|BSOver, $buttonImageId, 340);
swf_onCondition(MenuEnter);
swf_actionGetUrl("http://www.example.com", "_level1");
swf_onCondition(MenuExit);
swf_actionGetUrl("", "_level1");
swf_endButton();
?>

swf_actionwaitforframe
swf_addcolor
SWF Funkcje


Set the global add color to the rgba value specified

swf_addbuttonrecord
swf_closefile
SWF Funkcje
PHP Manual

swf_addcolor

(PHP 4)

swf_addcolor — Set the global add color to the rgba value specified

Opis

void swf_addcolor ( float $r , float $g , float $b , float $a )

Sets the global add color to the specified color. This color is then
implicitly used by the swf_placeobject(),
swf_modifyobject() and
swf_addbuttonrecord() functions.

The color of the object will be add by the given values when the object is written to the screen.

Parametry

r

Red value

g

Green value

b

Blue value

a

Alpha value

These parameters can be either positive or negative.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_addbuttonrecord
swf_closefile
SWF Funkcje


Close the current Shockwave Flash file

swf_addcolor
swf_definebitmap
SWF Funkcje
PHP Manual

swf_closefile

(PHP 4)

swf_closefile — Close the current Shockwave Flash file

Opis

void swf_closefile ([ int $return_file ] )

Close a file that was opened by the swf_openfile() function.

Parametry

return_file

If set then the contents of the SWF file are returned from the function.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Creating a simple flash file based on user input and outputting it and saving it in a database

<?php

// The $text variable is submitted by the
// user

// Global variables for database
// access (used in the swf_savedata() function)
$DBHOST = "localhost";
$DBUSER = "sterling";
$DBPASS = "secret";

swf_openfile("php://stdout", 256, 256, 30, 1, 1, 1);

    swf_definefont(10, "Ligon-Bold");
        swf_fontsize(12);
        swf_fontslant(10);

    swf_definetext(11, $text, 1);

    swf_pushmatrix();
        swf_translate(-50, 80, 0);
        swf_placeobject(11, 60);
    swf_popmatrix();

    swf_showframe();

    swf_startdoaction();
        swf_actionstop();
    swf_enddoaction();

$data = swf_closefile(1);

$data ?
  swf_savedata($data) :
  die("Error could not save SWF file");

// void swf_savedata(string data)
// Save the generated file a database
// for later retrieval
function swf_savedata($data)
{
    global $DBHOST,
           $DBUSER,
           $DBPASS;

    $dbh = @mysql_connect($DBHOST, $DBUSER, $DBPASS);

    if (!$dbh) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    $stmt = "INSERT INTO swf_files (file) VALUES ('$data')";

    $sth = @mysql_query($stmt, $dbh);

    if (!$sth) {
        die (sprintf("Error [%d]: %s",
                      mysql_errno(), mysql_error()));
    }

    @mysql_free_result($sth);
    @mysql_close($dbh);
}
?>

Zobacz też:

  • swf_openfile() - Open a new Shockwave Flash file

swf_addcolor
swf_definebitmap
SWF Funkcje


Define a bitmap

swf_closefile
swf_definefont
SWF Funkcje
PHP Manual

swf_definebitmap

(PHP 4)

swf_definebitmap — Define a bitmap

Opis

void swf_definebitmap ( int $objid , string $image_name )

The swf_definebitmap() function defines a bitmap given an image.

Parametry

objid

An SWF object id.

image_name

A GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_closefile
swf_definefont
SWF Funkcje


Defines a font

swf_definebitmap
swf_defineline
SWF Funkcje
PHP Manual

swf_definefont

(PHP 4)

swf_definefont — Defines a font

Opis

void swf_definefont ( int $fontid , string $fontname )

The swf_definefont() function defines a font parameter and gives it the specified id. It then sets the font given by fontname to the current font.

Parametry

fontid

The id to be given to the font.

fontname

The font so be set as current font.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_definetext() - Define a text string

swf_definebitmap
swf_defineline
SWF Funkcje


Define a line

swf_definefont
swf_definepoly
SWF Funkcje
PHP Manual

swf_defineline

(PHP 4)

swf_defineline — Define a line

Opis

void swf_defineline ( int $objid , float $x1 , float $y1 , float $x2 , float $y2 , float $width )

Defines a line.

Parametry

objid

The object id.

x1

x-coordinate of start point.

y1

y-coordinate of start point.

x2

x-coordinate of end point.

y2

y-coordinate of end point.

width

The line width.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_definefont
swf_definepoly
SWF Funkcje


Define a polygon

swf_defineline
swf_definerect
SWF Funkcje
PHP Manual

swf_definepoly

(PHP 4)

swf_definepoly — Define a polygon

Opis

void swf_definepoly ( int $objid , array $coords , int $npoints , float $width )

Defines a polygon given an array of x, y coordinates.

Parametry

objid

The object id.

coords

An array of x, y coordinates.

npoints

The number of overall points that are contained in the array given by coords

width

The width of the polygon's border, if set to 0.0 the polygon is filled.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_defineline
swf_definerect
SWF Funkcje


Define a rectangle

swf_definepoly
swf_definetext
SWF Funkcje
PHP Manual

swf_definerect

(PHP 4)

swf_definerect — Define a rectangle

Opis

void swf_definerect ( int $objid , float $x1 , float $y1 , float $x2 , float $y2 , float $width )

Defines a rectangle with an upper left hand coordinate and a lower right hand coordinate.

Parametry

objid

The object id.

x1

x-coordinate of upper left point.

y1

y-coordinate of upper left point.

x2

x-coordinate of lower right point.

y2

y-coordinate of lower right point.

width

Width of the rectangles border, if the width is 0.0 then the rectangle is filled.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_definepoly
swf_definetext
SWF Funkcje


Define a text string

swf_definerect
swf_endbutton
SWF Funkcje
PHP Manual

swf_definetext

(PHP 4)

swf_definetext — Define a text string

Opis

void swf_definetext ( int $objid , string $str , int $docenter )

Defines a text string using the current font and font size.

Parametry

objid

The object id.

str

The text, as a string.

docenter

The docenter is where the word is centered, if docenter is 1, then the word is centered in x.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Horizontal text example

<?php

$Xposition = 50;
$Yposition = 50;
$Zposition = 0;
$Obj_depth = 1;

$char = 'THIS IS THE TEXT';

swf_pushmatrix();

swf_definefont (swf_nextid(), "Mod");
swf_fontsize(10);

$secondid = swf_nextid();
swf_definetext($secondid, $char, 1);
swf_translate($Xposition, $Yposition, Zposition);
swf_placeobject($secondid, $Obj_depth);
swf_popmatrix();

?>

Zobacz też:

  • swf_definefont() - Defines a font

swf_definerect
swf_endbutton
SWF Funkcje


End the definition of the current button

swf_definetext
swf_enddoaction
SWF Funkcje
PHP Manual

swf_endbutton

(PHP 4)

swf_endbutton — End the definition of the current button

Opis

void swf_endbutton ( void )

The swf_endbutton() function ends the definition of the current button.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_startbutton() - Start the definition of a button

swf_definetext
swf_enddoaction
SWF Funkcje


End the current action

swf_endbutton
swf_endshape
SWF Funkcje
PHP Manual

swf_enddoaction

(PHP 4)

swf_enddoaction — End the current action

Opis

void swf_enddoaction ( void )

Ends the current action started by the swf_startdoaction() function.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_startdoaction() - Start a description of an action list for the current frame

swf_endbutton
swf_endshape
SWF Funkcje


Completes the definition of the current shape

swf_enddoaction
swf_endsymbol
SWF Funkcje
PHP Manual

swf_endshape

(PHP 4)

swf_endshape — Completes the definition of the current shape

Opis

void swf_endshape ( void )

The swf_endshape() completes the definition of the current shape.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_startshape() - Start a complex shape

swf_enddoaction
swf_endsymbol
SWF Funkcje


End the definition of a symbol

swf_endshape
swf_fontsize
SWF Funkcje
PHP Manual

swf_endsymbol

(PHP 4)

swf_endsymbol — End the definition of a symbol

Opis

void swf_endsymbol ( void )

Ends the definition of a symbol that was started by the swf_startsymbol() function.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_startsymbol() - Define a symbol

swf_endshape
swf_fontsize
SWF Funkcje


Change the font size

swf_endsymbol
swf_fontslant
SWF Funkcje
PHP Manual

swf_fontsize

(PHP 4)

swf_fontsize — Change the font size

Opis

void swf_fontsize ( float $size )

Changes the font size to the value given by the size parameter.

Parametry

size

The font size, as an integer.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_endsymbol
swf_fontslant
SWF Funkcje


Set the font slant

swf_fontsize
swf_fonttracking
SWF Funkcje
PHP Manual

swf_fontslant

(PHP 4)

swf_fontslant — Set the font slant

Opis

void swf_fontslant ( float $slant )

Set the current font slant to the angle indicated by the slant parameter.

Parametry

slant

Positive values create a forward slant, negative values create a negative slant.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_fontsize
swf_fonttracking
SWF Funkcje


Set the current font tracking

swf_fontslant
swf_getbitmapinfo
SWF Funkcje
PHP Manual

swf_fonttracking

(PHP 4)

swf_fonttracking — Set the current font tracking

Opis

void swf_fonttracking ( float $tracking )

Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.

Parametry

tracking

The font tracking.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_fontslant
swf_getbitmapinfo
SWF Funkcje


Get information about a bitmap

swf_fonttracking
swf_getfontinfo
SWF Funkcje
PHP Manual

swf_getbitmapinfo

(PHP 4)

swf_getbitmapinfo — Get information about a bitmap

Opis

array swf_getbitmapinfo ( int $bitmapid )

Returns information about a bitmap.

Parametry

bitmapid

The bitmap id.

Zwracane wartości

Returns an array with the following elements:

  • "size" - The size in bytes of the bitmap.
  • "width" - The width in pixels of the bitmap.
  • "height" - The height in pixels of the bitmap.

swf_fonttracking
swf_getfontinfo
SWF Funkcje


Gets font information

swf_getbitmapinfo
swf_getframe
SWF Funkcje
PHP Manual

swf_getfontinfo

(PHP 4)

swf_getfontinfo — Gets font information

Opis

array swf_getfontinfo ( void )

Gets information about the font by giving the height in pixels of a capital A and a lowercase x.

Zwracane wartości

Returns an associative array with the following parameters:

  • Aheight - The height in pixels of a capital A.
  • xheight - The height in pixels of a lowercase x.

swf_getbitmapinfo
swf_getframe
SWF Funkcje


Get the frame number of the current frame

swf_getfontinfo
swf_labelframe
SWF Funkcje
PHP Manual

swf_getframe

(PHP 4)

swf_getframe — Get the frame number of the current frame

Opis

int swf_getframe ( void )

The swf_getframe() function gets the number of the current frame.

Zwracane wartości

Returns the current frame number, as an integer.

Zobacz też:

  • swf_setframe() - Switch to a specified frame

swf_getfontinfo
swf_labelframe
SWF Funkcje


Label the current frame

swf_getframe
swf_lookat
SWF Funkcje
PHP Manual

swf_labelframe

(PHP 4)

swf_labelframe — Label the current frame

Opis

void swf_labelframe ( string $name )

Labels the current frame with the given name.

Parametry

name

The frame label.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_getframe
swf_lookat
SWF Funkcje


Define a viewing transformation

swf_labelframe
swf_modifyobject
SWF Funkcje
PHP Manual

swf_lookat

(PHP 4)

swf_lookat — Define a viewing transformation

Opis

void swf_lookat ( float $view_x , float $view_y , float $view_z , float $reference_x , float $reference_y , float $reference_z , float $twist )

Defines a viewing transformation by giving the viewing position and the coordinates of a reference point in the scene.

Parametry

view_x

x-coordinate for the viewing position

view_y

y-coordinate for the viewing position

view_z

z-coordinate for the viewing position

reference_x

x-coordinate for the reference point

reference_y

y-coordinate for the reference point

reference_z

z-coordinate for the reference point

twist

Controls the rotation along with viewer's z axis.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A simple 3D-rotation around a text

<?php

header('Content-type: application/x-shockwave-flash');

swf_openfile("php://stdout", 320, 200, 25, 1, 1, 1);

swf_ortho(-100, 100, -100, 100, -100, 100); // create 3D coordinates

swf_definefont(0, "Pix3");
swf_addcolor(0, 0, 0, 1);
swf_fontsize(10);
swf_fonttracking(0.2);

for ($i = 0; $i < 628; $i += 8) {
    $j = $i / 100;
    swf_pushmatrix();
    swf_translate(0, 0, 0);
    swf_perspective(100, 1, 0, 10);
    swf_lookat(sin($j) * 60, 50, cos($j) * 60, 0, 0, 0, 0);

    swf_definetext (1, 'HotKey@', 0);
    swf_translate(-50,0,0);

    swf_placeobject(1,10);

    swf_definetext(2, 'example.com', 0);
    swf_translate(55, 0, 0);
    swf_placeobject(2, 11);

    swf_showframe();
    swf_removeobject(10);
    swf_removeobject(11);
    swf_popmatrix();
}

swf_closefile();
?>

swf_labelframe
swf_modifyobject
SWF Funkcje


Modify an object

swf_lookat
swf_mulcolor
SWF Funkcje
PHP Manual

swf_modifyobject

(PHP 4)

swf_modifyobject — Modify an object

Opis

void swf_modifyobject ( int $depth , int $how )

Updates the position and/or color of the object at the specified depth.

Parametry

depth

The depth, as an integer.

how

Determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both.

MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_lookat
swf_mulcolor
SWF Funkcje


Sets the global multiply color to the rgba value specified

swf_modifyobject
swf_nextid
SWF Funkcje
PHP Manual

swf_mulcolor

(PHP 4)

swf_mulcolor — Sets the global multiply color to the rgba value specified

Opis

void swf_mulcolor ( float $r , float $g , float $b , float $a )

Sets the global multiply color to the given one. This color is then
implicitly used by the swf_placeobject(),
swf_modifyobject() and
swf_addbuttonrecord() functions.

The color of the object will be multiplied by the given color values when the object is written to the screen.

Parametry

r

Red value

g

Green value

b

Blue value

a

Alpha value

These parameters can be either positive or negative.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_modifyobject
swf_nextid
SWF Funkcje


Returns the next free object id

swf_mulcolor
swf_oncondition
SWF Funkcje
PHP Manual

swf_nextid

(PHP 4)

swf_nextid — Returns the next free object id

Opis

int swf_nextid ( void )

The swf_nextid() function returns the next available object id.

Zwracane wartości

Returns the id, as an integer.

swf_mulcolor
swf_oncondition
SWF Funkcje


Describe a transition used to trigger an action list

swf_nextid
swf_openfile
SWF Funkcje
PHP Manual

swf_oncondition

(PHP 4)

swf_oncondition — Describe a transition used to trigger an action list

Opis

void swf_oncondition ( int $transition )

The swf_oncondition() function describes a transition that will trigger an action list.

Parametry

transition

There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:

  • IdletoOverUp
  • OverUptoIdle
  • OverUptoOverDown
  • OverDowntoOverUp
  • IdletoOverDown
  • OutDowntoIdle
  • MenuEnter (IdletoOverUp|IdletoOverDown)
  • MenuExit (OverUptoIdle|OverDowntoIdle)
For TYPE_PUSHBUTTON there are the following options:
  • IdletoOverUp
  • OverUptoIdle
  • OverUptoOverDown
  • OverDowntoOverUp
  • OverDowntoOutDown
  • OutDowntoOverDown
  • OutDowntoIdle
  • ButtonEnter (IdletoOverUp|OutDowntoOverDown)
  • ButtonExit (OverUptoIdle|OverDowntoOutDown)

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_nextid
swf_openfile
SWF Funkcje


Open a new Shockwave Flash file

swf_oncondition
swf_ortho2
SWF Funkcje
PHP Manual

swf_openfile

(PHP 4)

swf_openfile — Open a new Shockwave Flash file

Opis

void swf_openfile ( string $filename , float $width , float $height , float $framerate , float $r , float $g , float $b )

Opens a new file. This must be the first function you call, otherwise your script will not work.

Parametry

filename

The path to the SWF file. If you want to send your output to the screen, set this to php://stdout.

width

The movie width

height

The movie height

framerate

The frame rate.

r

Red value for the background.

g

Green value for the background.

b

Blue value for the background.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
4.0.1 | Support for php://stdout was added.

Zobacz też:

  • swf_closefile() - Close the current Shockwave Flash file

swf_oncondition
swf_ortho2
SWF Funkcje


Defines 2D orthographic mapping of user coordinates onto the current viewport

swf_openfile
swf_ortho
SWF Funkcje
PHP Manual

swf_ortho2

(PHP 4)

swf_ortho2 — Defines 2D orthographic mapping of user coordinates onto the current viewport

Opis

void swf_ortho2 ( float $xmin , float $xmax , float $ymin , float $ymax )

Defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie.

If a perspective transformation is desired, swf_perspective() can be used.

Parametry

xmin

xmax

ymin

ymax

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_ortho() - Defines an orthographic mapping of user coordinates onto the current viewport

swf_openfile
swf_ortho
SWF Funkcje


Defines an orthographic mapping of user coordinates onto the current viewport

swf_ortho2
swf_perspective
SWF Funkcje
PHP Manual

swf_ortho

(PHP 4 >= 4.0.1)

swf_ortho — Defines an orthographic mapping of user coordinates onto the current viewport

Opis

void swf_ortho ( float $xmin , float $xmax , float $ymin , float $ymax , float $zmin , float $zmax )

Defines an 3D orthographic mapping of user coordinates onto the current viewport.

Parametry

xmin

xmax

ymin

ymax

zmin

zmax

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_ortho2() - Defines 2D orthographic mapping of user coordinates onto the current viewport

swf_ortho2
swf_perspective
SWF Funkcje


Define a perspective projection transformation

swf_ortho
swf_placeobject
SWF Funkcje
PHP Manual

swf_perspective

(PHP 4)

swf_perspective — Define a perspective projection transformation

Opis

void swf_perspective ( float $fovy , float $aspect , float $near , float $far )

Defines a perspective projection transformation.

Informacja:

Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.

Parametry

fovy

A field-of-view angle in the y direction.

aspect

The aspect ratio of the viewport that is being drawn onto.

near

The near clipping plane.

far

The far clipping plane.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_ortho
swf_placeobject
SWF Funkcje


Place an object onto the screen

swf_perspective
swf_polarview
SWF Funkcje
PHP Manual

swf_placeobject

(PHP 4)

swf_placeobject — Place an object onto the screen

Opis

void swf_placeobject ( int $objid , int $depth )

Places the object in the current frame at a specified depth.

This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.

Parametry

objid

The object id.

depth

Must be between 1 and 65535.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_perspective
swf_polarview
SWF Funkcje


Define the viewer's position with polar coordinates

swf_placeobject
swf_popmatrix
SWF Funkcje
PHP Manual

swf_polarview

(PHP 4)

swf_polarview — Define the viewer's position with polar coordinates

Opis

void swf_polarview ( float $dist , float $azimuth , float $incidence , float $twist )

The swf_polarview() function defines the viewer's position in polar coordinates.

Parametry

dist

The distance between the viewpoint to the world space origin.

azimuth

Defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis.

incidence

Defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis.

twist

Specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_placeobject
swf_popmatrix
SWF Funkcje


Restore a previous transformation matrix

swf_polarview
swf_posround
SWF Funkcje
PHP Manual

swf_popmatrix

(PHP 4)

swf_popmatrix — Restore a previous transformation matrix

Opis

void swf_popmatrix ( void )

Restores a previous transformation matrix.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_pushmatrix() - Push the current transformation matrix back onto the stack

swf_polarview
swf_posround
SWF Funkcje


Enables or Disables the rounding of the translation when objects are placed or moved

swf_popmatrix
swf_pushmatrix
SWF Funkcje
PHP Manual

swf_posround

(PHP 4)

swf_posround — Enables or Disables the rounding of the translation when objects are placed or moved

Opis

void swf_posround ( int $round )

Enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled.

Parametry

round

Whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_popmatrix
swf_pushmatrix
SWF Funkcje


Push the current transformation matrix back onto the stack

swf_posround
swf_removeobject
SWF Funkcje
PHP Manual

swf_pushmatrix

(PHP 4)

swf_pushmatrix — Push the current transformation matrix back onto the stack

Opis

void swf_pushmatrix ( void )

Pushes the current transformation matrix back onto the stack.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_popmatrix() - Restore a previous transformation matrix

swf_posround
swf_removeobject
SWF Funkcje


Remove an object

swf_pushmatrix
swf_rotate
SWF Funkcje
PHP Manual

swf_removeobject

(PHP 4)

swf_removeobject — Remove an object

Opis

void swf_removeobject ( int $depth )

Removes the last object drawn at the depth specified by depth.

Parametry

depth

The depth, as an integer.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_pushmatrix
swf_rotate
SWF Funkcje


Rotate the current transformation

swf_removeobject
swf_scale
SWF Funkcje
PHP Manual

swf_rotate

(PHP 4)

swf_rotate — Rotate the current transformation

Opis

void swf_rotate ( float $angle , string $axis )

Rotates the current transformation by a given angle around the given axis.

Parametry

angle

The rotation angle.

axis

The axis. Valid values axis are x (the x axis), y (the y axis) or z (the z axis).

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_removeobject
swf_scale
SWF Funkcje


Scale the current transformation

swf_rotate
swf_setfont
SWF Funkcje
PHP Manual

swf_scale

(PHP 4)

swf_scale — Scale the current transformation

Opis

void swf_scale ( float $x , float $y , float $z )

The swf_scale() scales curve coordinates by the given value.

Parametry

x

x scale factor.

y

y scale factor.

z

z scale factor.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_rotate
swf_setfont
SWF Funkcje


Change the current font

swf_scale
swf_setframe
SWF Funkcje
PHP Manual

swf_setfont

(PHP 4)

swf_setfont — Change the current font

Opis

void swf_setfont ( int $fontid )

The swf_setfont() sets the current font to the value given by the fontid parameter.

Parametry

fontid

The font identifier.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_scale
swf_setframe
SWF Funkcje


Switch to a specified frame

swf_setfont
swf_shapearc
SWF Funkcje
PHP Manual

swf_setframe

(PHP 4)

swf_setframe — Switch to a specified frame

Opis

void swf_setframe ( int $framenumber )

Changes the active frame to the specified on.

Parametry

framenumber

The frame number to be set.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_getframe() - Get the frame number of the current frame

swf_setfont
swf_shapearc
SWF Funkcje


Draw a circular arc

swf_setframe
swf_shapecurveto3
SWF Funkcje
PHP Manual

swf_shapearc

(PHP 4)

swf_shapearc — Draw a circular arc

Opis

void swf_shapearc ( float $x , float $y , float $r , float $ang1 , float $ang2 )

Draws a circular arc.

Parametry

x

x-coordinate of the center.

y

y-coordinate of the center.

r

The arc radius.

ang1

The start angle.

ang2

The end angle.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_setframe
swf_shapecurveto3
SWF Funkcje


Draw a cubic bezier curve

swf_shapearc
swf_shapecurveto
SWF Funkcje
PHP Manual

swf_shapecurveto3

(PHP 4)

swf_shapecurveto3 — Draw a cubic bezier curve

Opis

void swf_shapecurveto3 ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 )

Draw a cubic bezier curve using the given coordinates.

The current position is then set to the x3,y3 coordinate.

Parametry

x1

x-coordinate of the first off curve control point.

y1

y-coordinate of the first off curve control point.

x2

x-coordinate of the second off curve control point.

y2

y-coordinate of the second off curve control point.

x3

x-coordinate of the endpoint.

y3

y-coordinate of the endpoint.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_shapecurveto() - Draw a quadratic bezier curve between two points

swf_shapearc
swf_shapecurveto
SWF Funkcje


Draw a quadratic bezier curve between two points

swf_shapecurveto3
swf_shapefillbitmapclip
SWF Funkcje
PHP Manual

swf_shapecurveto

(PHP 4)

swf_shapecurveto — Draw a quadratic bezier curve between two points

Opis

void swf_shapecurveto ( float $x1 , float $y1 , float $x2 , float $y2 )

Draws a quadratic bezier curve from the current location, though the two given points.

The current position is then set to the point defined by the x2 and y2 parameters.

Parametry

x1

x-coordinate of the first point.

y1

y-coordinate of the first point.

x2

x-coordinate of the second point.

y2

y-coordinate of the second point.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_shapecurveto3() - Draw a cubic bezier curve

swf_shapecurveto3
swf_shapefillbitmapclip
SWF Funkcje


Set current fill mode to clipped bitmap

swf_shapecurveto
swf_shapefillbitmaptile
SWF Funkcje
PHP Manual

swf_shapefillbitmapclip

(PHP 4)

swf_shapefillbitmapclip — Set current fill mode to clipped bitmap

Opis

void swf_shapefillbitmapclip ( int $bitmapid )

Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap.

Parametry

bitmapid

The bitmap id.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_shapefillbitmaptile() - Set current fill mode to tiled bitmap

swf_shapecurveto
swf_shapefillbitmaptile
SWF Funkcje


Set current fill mode to tiled bitmap

swf_shapefillbitmapclip
swf_shapefilloff
SWF Funkcje
PHP Manual

swf_shapefillbitmaptile

(PHP 4)

swf_shapefillbitmaptile — Set current fill mode to tiled bitmap

Opis

void swf_shapefillbitmaptile ( int $bitmapid )

Sets the fill to bitmap tile, empty spaces will be filled by the bitmap.

Parametry

bitmapid

The bitmap id.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_shapefillbitmapclip() - Set current fill mode to clipped bitmap

swf_shapefillbitmapclip
swf_shapefilloff
SWF Funkcje


Turns off filling

swf_shapefillbitmaptile
swf_shapefillsolid
SWF Funkcje
PHP Manual

swf_shapefilloff

(PHP 4)

swf_shapefilloff — Turns off filling

Opis

void swf_shapefilloff ( void )

Turns off filling for the current shape.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_shapefillbitmaptile
swf_shapefillsolid
SWF Funkcje


Set the current fill style to the specified color

swf_shapefilloff
swf_shapelinesolid
SWF Funkcje
PHP Manual

swf_shapefillsolid

(PHP 4)

swf_shapefillsolid — Set the current fill style to the specified color

Opis

void swf_shapefillsolid ( float $r , float $g , float $b , float $a )

Sets the current fill style to solid, and then sets the fill color to the given color.

Parametry

r

Red value

g

Green value

b

Blue value

a

Alpha value

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_shapefilloff
swf_shapelinesolid
SWF Funkcje


Set the current line style

swf_shapefillsolid
swf_shapelineto
SWF Funkcje
PHP Manual

swf_shapelinesolid

(PHP 4)

swf_shapelinesolid — Set the current line style

Opis

void swf_shapelinesolid ( float $r , float $g , float $b , float $a , float $width )

Sets the current line style to the given color and width.

Parametry

r

Red value

g

Green value

b

Blue value

a

Alpha value

width

The line width. If 0.0 is given then no lines are drawn.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_shapefillsolid
swf_shapelineto
SWF Funkcje


Draw a line

swf_shapelinesolid
swf_shapemoveto
SWF Funkcje
PHP Manual

swf_shapelineto

(PHP 4)

swf_shapelineto — Draw a line

Opis

void swf_shapelineto ( float $x , float $y )

Draws a line to the x and y coordinates. The current position is then set to that point.

Parametry

x

x-coordinate of the target.

y

y-coordinate of the target.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_shapelinesolid
swf_shapemoveto
SWF Funkcje


Move the current position

swf_shapelineto
swf_showframe
SWF Funkcje
PHP Manual

swf_shapemoveto

(PHP 4)

swf_shapemoveto — Move the current position

Opis

void swf_shapemoveto ( float $x , float $y )

Moves the current position to the given point.

Parametry

x

x-coordinate of the target.

y

y-coordinate of the target.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_shapelineto
swf_showframe
SWF Funkcje


Display the current frame

swf_shapemoveto
swf_startbutton
SWF Funkcje
PHP Manual

swf_showframe

(PHP 4)

swf_showframe — Display the current frame

Opis

void swf_showframe ( void )

Outputs the current frame.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_shapemoveto
swf_startbutton
SWF Funkcje


Start the definition of a button

swf_showframe
swf_startdoaction
SWF Funkcje
PHP Manual

swf_startbutton

(PHP 4)

swf_startbutton — Start the definition of a button

Opis

void swf_startbutton ( int $objid , int $type )

Starts the definition of a button.

Parametry

objid

The object id.

type

Can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_endbutton() - End the definition of the current button

swf_showframe
swf_startdoaction
SWF Funkcje


Start a description of an action list for the current frame

swf_startbutton
swf_startshape
SWF Funkcje
PHP Manual

swf_startdoaction

(PHP 4)

swf_startdoaction — Start a description of an action list for the current frame

Opis

void swf_startdoaction ( void )

Starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_enddoaction() - End the current action

swf_startbutton
swf_startshape
SWF Funkcje


Start a complex shape

swf_startdoaction
swf_startsymbol
SWF Funkcje
PHP Manual

swf_startshape

(PHP 4)

swf_startshape — Start a complex shape

Opis

void swf_startshape ( int $objid )

Starts a complex shape.

Parametry

objid

The object id.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_endshape() - Completes the definition of the current shape

swf_startdoaction
swf_startsymbol
SWF Funkcje


Define a symbol

swf_startshape
swf_textwidth
SWF Funkcje
PHP Manual

swf_startsymbol

(PHP 4)

swf_startsymbol — Define a symbol

Opis

void swf_startsymbol ( int $objid )

Defines an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously.

Parametry

objid

The object id you want to define as a symbol.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • swf_endsymbol() - End the definition of a symbol

swf_startshape
swf_textwidth
SWF Funkcje


Get the width of a string

swf_startsymbol
swf_translate
SWF Funkcje
PHP Manual

swf_textwidth

(PHP 4)

swf_textwidth — Get the width of a string

Opis

float swf_textwidth ( string $str )

Gives the width of the string in pixels, using the current font and font size.

Parametry

str

The string.

Zwracane wartości

Returns the line width, as a float.

swf_startsymbol
swf_translate
SWF Funkcje


Translate the current transformations

swf_textwidth
swf_viewport
SWF Funkcje
PHP Manual

swf_translate

(PHP 4)

swf_translate — Translate the current transformations

Opis

void swf_translate ( float $x , float $y , float $z )

Translates the current transformation by the given values.

Parametry

x

x value.

y

y value.

z

z value.

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_textwidth
swf_viewport
SWF Funkcje


Select an area for future drawing

swf_translate
Rozszerzenia kontroli procesów
SWF Funkcje
PHP Manual

swf_viewport

(PHP 4)

swf_viewport — Select an area for future drawing

Opis

void swf_viewport ( float $xmin , float $xmax , float $ymin , float $ymax )

Selects an area for future drawing for xmin to xmax and ymin to ymax, if this function is not called the area defaults to the size of the screen.

Parametry

xmin

xmax

ymin

ymax

Zwracane wartości

Nie jest zwracana żadna wartość.

swf_translate
Rozszerzenia kontroli procesów
SWF Funkcje


Rozszerzenia kontroli procesów

  • Eio
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Eio Funkcje
  • Expect
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Expect Funkcje
  • Libevent
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Libevent Funkcje
  • PCNTL — Process Control
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • PCNTL Funkcje
  • POSIX
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • POSIX Funkcje
  • Program execution — System program execution
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Program execution Funkcje
  • Semaphore — Semaphore, Shared Memory and IPC
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Semaphore Funkcje
  • Shared Memory
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Shared Memory Funkcje
swf_viewport
Eio
Opis funkcji


Eio

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Eio Funkcje
    • eio_busy — Artificially increase load. Could be useful in tests, benchmarking.
    • eio_cancel — Cancels a request
    • eio_chmod — Change file/direcrory permissions.
    • eio_chown — Change file/direcrory permissions.
    • eio_close — Close file
    • eio_custom — Execute custom request like any other eio_* call.
    • eio_dup2 — Duplicate a file descriptor
    • eio_event_loop — Polls libeio until all requests proceeded
    • eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file
    • eio_fchmod — Change file permissions.
    • eio_fchown — Change file ownership
    • eio_fdatasync — Synchronize a file's in-core state with storage device.
    • eio_fstat — Get file status
    • eio_fstatvfs — Get file system statistics
    • eio_fsync — Synchronize a file's in-core state with storage device
    • eio_ftruncate — Truncate a file
    • eio_futime — Change file last access and modification times
    • eio_get_event_stream — Get stream representing a variable used in internal communications with libeio.
    • eio_grp_add — Adds a request to the request group.
    • eio_grp_cancel — Cancels a request group
    • eio_grp_limit — Set group limit
    • eio_grp — Createsa request group.
    • eio_link — Create a hardlink for file
    • eio_lstat — Get file status
    • eio_mkdir — Create directory
    • eio_mknod — Create a special or ordinary file.
    • eio_nop — Does nothing, except go through the whole request cycle.
    • eio_npending — Returns number of finished, but unhandled requests
    • eio_nready — Returns number of not-yet handled requests
    • eio_nreqs — Returns number of requests to be processed
    • eio_nthreads — Returns number of threads currently in use
    • eio_open — Opens a file
    • eio_poll — Can be to be called whenever there are pending requests that need finishing.
    • eio_read — Read from a file descriptor at given offset.
    • eio_readahead — Perform file readahead into page cache
    • eio_readdir — Reads through a whole directory
    • eio_readlink — Read value of a symbolic link.
    • eio_realpath — Get the canonicalized absolute pathname.
    • eio_rename — Change the name or location of a file.
    • eio_rmdir — Remove a directory
    • eio_sendfile — Transfer data between file descriptors
    • eio_set_max_idle — Set maximum number of idle threads.
    • eio_set_max_parallel — Set maximum parallel threads
    • eio_set_max_poll_reqs — Set maximum number of requests processed in a poll.
    • eio_set_max_poll_time — Set maximum poll time
    • eio_set_min_parallel — Set minimum parallel thread number
    • eio_stat — Get file status
    • eio_statvfs — Get file system statistics
    • eio_symlink — Create a symbolic link
    • eio_sync_file_range — Sync a file segment with disk
    • eio_sync — Commit buffer cache to disk
    • eio_syncfs — Calls Linux' syncfs syscall, if available
    • eio_truncate — Truncate a file
    • eio_unlink — Delete a name and possibly the file it refers to
    • eio_utime — Change file last access and modification times.
    • eio_write — Write to file
Rozszerzenia kontroli procesów
Wstęp
Rozszerzenia kontroli procesów


Wstęp

This extension provides asyncronous POSIX I/O by means of » libeio C library written by Marc Lehmann.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

Ostrzeżenie

It is important to aware that each request is executed in a thread, and the order of execution of continuously queued requests basically is unpredictable. For instance, the following piece of code is incorrect.

Przykład #1 Incorrect requests

<?php
// Request to create symlink of $filename to $link
eio_symlink($filename, $link);

// Request to move $filename to $new_filename
eio_rename($filename, $new_filename);

// Process requests
eio_event_loop();
?>
In the example above eio_rename() request may finish before eio_symlink(). To fix it you might call eio_rename() in the callback of eio_symlink():

Przykład #2 Calling request from a request callback

<?php
function my_symlink_done($filename, $result) {
 // Request to move $filename to $new_filename
 eio_rename($filename, "/path/to/new-name");

 // Process requests
 eio_event_loop();
}

// Request to create symlink of $filename to $link
eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_done", $filename);

// Process requests
eio_event_loop();
?>
Alternatively, you might want to create a request group:

Przykład #3 Calling request from a request callback

<?php
/* Is called when the group requests are done */
function my_grp_done($data, $result) {
 // ...
}

function my_symlink_done($filename, $result) {
 // Create eio_rename request and add it to the group
 $req = eio_rename($filename, "/path/to/new-name");
 eio_grp_add($grp, $req);
 // You might want to add more requests...
}

// Create a request group
$grp = eio_grp("my_grp_done", "my_grp_data");

// Create eio_symlink request and add it to the group
// Pass $filename to the callback
$req = eio_symlink($filename, $link,
  EIO_PRI_DEFAULT, "my_symlink_done", $filename);
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>
Group is a special kind of request that could accumulate a set of regular eio requests. This could be used to create a complex request that opens, reads and closes a file.

Since version 0.3.0 alpha, a variable used in communications with libeio internally, could be retrieved with eio_get_event_stream(). The variable could be used to bind to an event loop supported by some other extension. You might organize a simple event loop where eio and libevent work together:

Przykład #4 Using eio with libevent

<?php
function my_eio_poll($fd, $events, $arg) {
    /* Some libevent regulation might go here .. */
    if (eio_nreqs()) {
        eio_poll();
    }
    /* .. and here */
}

function my_res_cb($d, $r) {
    var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

// This stream is used to bind with libevent
$fd = eio_get_event_stream();

eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

Eio
Instalacja/Konfiguracja
Eio


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Eio


Wymagania

This extension has » libeio library embedded. So you do NOT need to install libeio separately.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/eio.

For information about manual installation, please read the file INSTALL included in the package.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

There are two resource types in this extension: request and request group.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

Request priority constants:

EIO_PRI_MIN (integer)
Request minimal prioriry
EIO_PRI_DEFAULT (integer)
Request default prioriry
EIO_PRI_MAX (integer)
Request maximal prioriry

Flags used with eio_readdir():

EIO_READDIR_DENTS (integer)
eio_readdir() flag. If specified, the result argument of the callback becomes an array with the following keys: 'names' - array of directory names 'dents' - array of struct eio_dirent-like arrays having the following keys each: 'name' - the directory name; 'type' - one of EIO_DT_* constants; 'inode' - the inode number, if available, otherwise unspecified;
EIO_READDIR_DIRS_FIRST (integer)
When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order.
EIO_READDIR_STAT_ORDER (integer)
When this flag is specified, then the names will be returned in an order suitable for stat'ing each one. When planning to stat() all files in the given directory, the returned order will likely be fastest.
EIO_READDIR_FOUND_UNKNOWN (integer)
EIO_DT_UNKNOWN (integer)
Unknown node type(very common). Further stat() needed.
EIO_DT_FIFO (integer)
FIFO node type
EIO_DT_CHR (integer)
Node type
EIO_DT_MPC (integer)
Multiplexed char device (v7+coherent) node type
EIO_DT_DIR (integer)
Directory node type
EIO_DT_NAM (integer)
Xenix special named file node type
EIO_DT_BLK (integer)
Node type
EIO_DT_MPB (integer)
Multiplexed block device (v7+coherent)
EIO_DT_REG (integer)
Node type
EIO_DT_NWK (integer)
EIO_DT_CMP (integer)
HP-UX network special node type
EIO_DT_LNK (integer)
Link node type
EIO_DT_SOCK (integer)
Socket node type
EIO_DT_DOOR (integer)
Solaris door node type
EIO_DT_WHT (integer)
Node type
EIO_DT_MAX (integer)
Highest node type value

Access modes for eio_open() flags argument:

EIO_O_RDONLY (integer)
EIO_O_WRONLY (integer)
EIO_O_RDWR (integer)
EIO_O_NONBLOCK (integer)
EIO_O_APPEND (integer)
EIO_O_CREAT (integer)
EIO_O_TRUNC (integer)
EIO_O_EXCL (integer)
EIO_O_FSYNC (integer)

mode argument flags for eio_open():

EIO_S_IRUSR (integer)
EIO_S_IWUSR (integer)
EIO_S_IXUSR (integer)
EIO_S_IRGRP (integer)
EIO_S_IWGRP (integer)
EIO_S_IXGRP (integer)
EIO_S_IROTH (integer)
EIO_S_IWOTH (integer)
EIO_S_IXOTH (integer)
EIO_S_IFREG (integer)
EIO_S_IFCHR (integer)
EIO_S_IFBLK (integer)
EIO_S_IFIFO (integer)
EIO_S_IFSOCK (integer)

eio_sync_file_range() flags:

EIO_SYNC_FILE_RANGE_WAIT_BEFORE (integer)
EIO_SYNC_FILE_RANGE_WRITE (integer)
EIO_SYNC_FILE_RANGE_WAIT_AFTER (integer)

eio_fallocate() flags:

EIO_FALLOC_FL_KEEP_SIZE (integer)

Informacja:

EIO_S_I* constants have the same meaning as their S_I* POSIX counterparts.

Informacja:

EIO_SYNC_FILE_* constants have the same meaning as their SYNC_FILE_** counterparts.

Informacja:

EIO_O_* constants have the same meaning as their O_* POSIX counterparts.

Typy zasobów
Przykłady
Eio


Przykłady

Przykład #1 Cancelling a request

<?php
 /* Is called when eio_nop() finished */
 function my_nop_cb($data, $result) {
  echo "my_nop ", $data, "\n";
 }

// This eio_nop() call will be cancelled
$req = eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "1");
var_dump($req);
eio_cancel($req);

// This time eio_nop() will be processed
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "2");

// Process requests
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

resource(4) of type (EIO Request Descriptor)
my_nop 2

Przykład #2 Calling eio_chmod()

<?php
$temp_filename = dirname(__FILE__) ."/eio-temp-file.tmp";
touch($temp_filename);

/* Is called when eio_chmod() finished */
function my_chmod_callback($data, $result) {
    global $temp_filename;

    if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {
        echo "eio_chmod_ok";
    }

    @unlink($temp_filename);
}

eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback");
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

eio_chmod_ok

Przykład #3 Making a custom request

<?php
/* Callback for the custom callback */
function my_custom_callback($data, $result) {
    var_dump($data);
    var_dump(count($result));
    var_dump($result['data_modified']);
    var_dump($result['result']);
}

/* The custom request */
function my_custom($data) {
    var_dump($data);

    $result  = array(
        'result'        => 1001,
        'data_modified' => "my custom data",
    );

    return $result;
}

$data = "my_custom_data";
$req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data);
var_dump($req);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

resource(4) of type (EIO Request Descriptor)
string(14) "my_custom_data"
string(14) "my_custom_data"
int(2)
string(14) "my custom data"
int(1001)

Przykład #4 Grouping requests

<?php
/*
 * Create a group request to open, read and close a file
 */

$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
 global $temp_filename;
 var_dump($result == 0);
 @unlink($temp_filename);
}

/* Is called when eio_open() done */
function my_grp_file_opened_callback($data, $result) {
 global $my_file_fd, $grp;

 $my_file_fd = $result;

 var_dump($result > 0);

 // Create eio_read() request and add it to the group
 $req = eio_read($my_file_fd, 4, 0, EIO_PRI_DEFAULT, "my_grp_file_read_callback");
 eio_grp_add($grp, $req);
}

/* Is called when eio_read() done */
function my_grp_file_read_callback($data, $result) {
 global $my_file_fd, $grp;

 var_dump($result);

 // Create eio_close() request and add it to the group
 $req = eio_close($my_file_fd);
 eio_grp_add($grp, $req);
}

$grp = eio_grp("my_grp_done", "my_grp_data");

// Create eio_open() request and add it to the group
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
  EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
eio_grp_add($grp, $req);
var_dump($grp);

eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

resource(6) of type (EIO Group Descriptor)
bool(true)
string(4) "some"
bool(true)

Przykład #5 Using eio with libevent

<?php
function my_eio_poll($fd, $events, $arg) {
    /* Some libevent regulation might go here .. */
    if (eio_nreqs()) {
        eio_poll();
    }
    /* .. and here */
}

function my_nop_cb($d, $r) {
    var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

$fd = eio_get_event_stream();
var_dump($fd);

eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_nop_cb", "nop data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

Powyższy przykład wyświetli coś podobnego do:

int(3)
int(0)
string(8) "nop data"
int(0)
string(10) "mkdir data"

Stałe predefiniowane
Eio Funkcje
Eio


Eio Funkcje

Spis treści

  • eio_busy — Artificially increase load. Could be useful in tests, benchmarking.
  • eio_cancel — Cancels a request
  • eio_chmod — Change file/direcrory permissions.
  • eio_chown — Change file/direcrory permissions.
  • eio_close — Close file
  • eio_custom — Execute custom request like any other eio_* call.
  • eio_dup2 — Duplicate a file descriptor
  • eio_event_loop — Polls libeio until all requests proceeded
  • eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file
  • eio_fchmod — Change file permissions.
  • eio_fchown — Change file ownership
  • eio_fdatasync — Synchronize a file's in-core state with storage device.
  • eio_fstat — Get file status
  • eio_fstatvfs — Get file system statistics
  • eio_fsync — Synchronize a file's in-core state with storage device
  • eio_ftruncate — Truncate a file
  • eio_futime — Change file last access and modification times
  • eio_get_event_stream — Get stream representing a variable used in internal communications with libeio.
  • eio_grp_add — Adds a request to the request group.
  • eio_grp_cancel — Cancels a request group
  • eio_grp_limit — Set group limit
  • eio_grp — Createsa request group.
  • eio_link — Create a hardlink for file
  • eio_lstat — Get file status
  • eio_mkdir — Create directory
  • eio_mknod — Create a special or ordinary file.
  • eio_nop — Does nothing, except go through the whole request cycle.
  • eio_npending — Returns number of finished, but unhandled requests
  • eio_nready — Returns number of not-yet handled requests
  • eio_nreqs — Returns number of requests to be processed
  • eio_nthreads — Returns number of threads currently in use
  • eio_open — Opens a file
  • eio_poll — Can be to be called whenever there are pending requests that need finishing.
  • eio_read — Read from a file descriptor at given offset.
  • eio_readahead — Perform file readahead into page cache
  • eio_readdir — Reads through a whole directory
  • eio_readlink — Read value of a symbolic link.
  • eio_realpath — Get the canonicalized absolute pathname.
  • eio_rename — Change the name or location of a file.
  • eio_rmdir — Remove a directory
  • eio_sendfile — Transfer data between file descriptors
  • eio_set_max_idle — Set maximum number of idle threads.
  • eio_set_max_parallel — Set maximum parallel threads
  • eio_set_max_poll_reqs — Set maximum number of requests processed in a poll.
  • eio_set_max_poll_time — Set maximum poll time
  • eio_set_min_parallel — Set minimum parallel thread number
  • eio_stat — Get file status
  • eio_statvfs — Get file system statistics
  • eio_symlink — Create a symbolic link
  • eio_sync_file_range — Sync a file segment with disk
  • eio_sync — Commit buffer cache to disk
  • eio_syncfs — Calls Linux' syncfs syscall, if available
  • eio_truncate — Truncate a file
  • eio_unlink — Delete a name and possibly the file it refers to
  • eio_utime — Change file last access and modification times.
  • eio_write — Write to file
Przykłady
eio_busy
Eio


Artificially increase load. Could be useful in tests, benchmarking.

Eio Funkcje
eio_cancel
Eio Funkcje
PHP Manual

eio_busy

(PECL eio >= 0.0.1dev)

eio_busy — Artificially increase load. Could be useful in tests, benchmarking.

Opis

resource eio_busy ( int $delay [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_busy() artificially increases load taking delay seconds to execute. May be used for debugging, or benchmarking.

Parametry

delay

Delay in seconds

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

This callback is called when all the group requests are done.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_busy() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_nop
Eio Funkcje
eio_cancel
Eio Funkcje


Cancels a request

eio_busy
eio_chmod
Eio Funkcje
PHP Manual

eio_cancel

(PECL eio >= 0.0.1dev)

eio_cancel — Cancels a request

Opis

void eio_cancel ( resource $req )

eio_cancel() cancels a request specified by req

Parametry

req

The request resource

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 eio_cancel() example

<?php
 /* Is called when eio_nop() finished */
 function my_nop_cb($data, $result) {
  echo "my_nop ", $data, "\n";
 }

// This eio_nop() call will be cancelled
$req = eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "1");
var_dump($req);
eio_cancel($req);

// This time eio_nop() will be processed
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "2");

// Process requests
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

resource(4) of type (EIO Request Descriptor)
my_nop 2

Zobacz też:

  • eio_grp_cancel
eio_busy
eio_chmod
Eio Funkcje


Change file/direcrory permissions.

eio_cancel
eio_chown
Eio Funkcje
PHP Manual

eio_chmod

(PECL eio >= 0.0.1dev)

eio_chmod — Change file/direcrory permissions.

Opis

resource eio_chmod ( string $path , int $mode [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_chmod() changes file, or direcrory permissions. The new permissions are specified by mode.

Parametry

path

Path to the target file or directory

Ostrzeżenie

Avoid relative paths

mode

The new permissions. E.g. 0644.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_chmod() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_chown
eio_cancel
eio_chown
Eio Funkcje


Change file/direcrory permissions.

eio_chmod
eio_close
Eio Funkcje
PHP Manual

eio_chown

(PECL eio >= 0.0.1dev)

eio_chown — Change file/direcrory permissions.

Opis

resource eio_chown ( string $path , int $uid [, int $gid = -1 [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]]] )

Changes file, or directory permissions.

Parametry

path

Path to file or directory.

Ostrzeżenie

Avoid relative paths

uid

User ID. Is ignored when equal to -1.

gid

Group ID. Is ignored when equal to -1.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_chown() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_chmod
eio_chmod
eio_close
Eio Funkcje


Close file

eio_chown
eio_custom
Eio Funkcje
PHP Manual

eio_close

(PECL eio >= 0.0.1dev)

eio_close — Close file

Opis

resource eio_close ( int $fd [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_close() closes file specified by fd.

Parametry

fd

The file descriptor

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_close() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_open
eio_chown
eio_custom
Eio Funkcje


Execute custom request like any other eio_* call.

eio_close
eio_dup2
Eio Funkcje
PHP Manual

eio_custom

(PECL eio >= 0.0.1dev)

eio_custom — Execute custom request like any other eio_* call.

Opis

resource eio_custom ( callback $execute , int $pri , callback $callback [, mixed $data = NULL ] )

eio_custom() executes custom function specified by execute processing it just like any other eio_* call.

Parametry

execute

Specifies the request function that should match the following prototype:

      mixed execute(mixed data);
callback is event completion callback that should match the following prototype:
      void callback(mixed data, mixed result);
data is the data passed to execute via data argument without modifications result value returned by execute

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_custom() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_custom() example

<?php
/* Callback for the custom callback */
function my_custom_callback($data, $result) {
    var_dump($data);
    var_dump(count($result));
    var_dump($result['data_modified']);
    var_dump($result['result']);
}

/* The custom request */
function my_custom($data) {
    var_dump($data);

    $result  = array(
        'result'        => 1001,
        'data_modified' => "my custom data",
    );

    return $result;
}

$data = "my_custom_data";
$req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data);
var_dump($req);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

resource(4) of type (EIO Request Descriptor)
string(14) "my_custom_data"
string(14) "my_custom_data"
int(2)
string(14) "my custom data"
int(1001)
eio_close
eio_dup2
Eio Funkcje


Duplicate a file descriptor

eio_custom
eio_event_loop
Eio Funkcje
PHP Manual

eio_dup2

(PECL eio >= 0.0.1dev)

eio_dup2 — Duplicate a file descriptor

Opis

resource eio_dup2 ( int $fd , int $fd2 [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_dup2() duplicates file descriptor.

Parametry

fd

Source file descriptor

fd2

Target file descriptor

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_dup2() returns request resource on success or FALSE on error.

eio_custom
eio_event_loop
Eio Funkcje


Polls libeio until all requests proceeded

eio_dup2
eio_fallocate
Eio Funkcje
PHP Manual

eio_event_loop

(PECL eio >= 0.0.1dev)

eio_event_loop — Polls libeio until all requests proceeded

Opis

bool eio_event_loop ( void )

eio_event_loop() polls libeio until all requests proceeded.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

eio_event_loop() returns TRUE on success or FALSE on error.

Przykłady

Przykład #1 eio_event_loop() example

<?php
$temp_filename = "eio-temp-file.tmp";
touch($temp_filename);

/* Is called when eio_chmod() finished */
function my_chmod_callback($data, $result) {
    global $temp_filename;

    if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {
        echo "eio_chmod_ok";
    }

    @unlink($temp_filename);
}

eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback");
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

eio_chmod_ok

Zobacz też:

  • eio_poll
eio_dup2
eio_fallocate
Eio Funkcje


Allows the caller to directly manipulate the allocated disk space for a file

eio_event_loop
eio_fchmod
Eio Funkcje
PHP Manual

eio_fallocate

(PECL eio >= 0.0.1dev)

eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file

Opis

resource eio_fallocate ( int $fd , int $mode , int $offset , int $length [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_fallocate() allows the caller to directly manipulate the allocated disk space for the file specified by fd file descriptor for the byte range starting at offset and continuing for length bytes.

Informacja: File should be opened for writing

EIO_O_CREAT should be logically OR'd with EIO_O_WRONLY, or EIO_O_RDWR

Parametry

fd

The file descriptor, e.g. returned by eio_open().

mode

Currently only one flag is supported for mode: EIO_FALLOC_FL_KEEP_SIZE (the same as POSIX constant FALLOC_FL_KEEP_SIZE).

offset

Specifies start of the byte range.

length

Specifies length the byte range.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_fallocate() returns request resource on success or FALSE on error.

eio_event_loop
eio_fchmod
Eio Funkcje


Change file permissions.

eio_fallocate
eio_fchown
Eio Funkcje
PHP Manual

eio_fchmod

(PECL eio >= 0.0.1dev)

eio_fchmod — Change file permissions.

Opis

resource eio_fchmod ( int $fd , int $mode [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_fchmod() changes permissions for the file specified by fd file descriptor.

Parametry

fd

The file descriptor, e.g. returned by eio_open().

mode

The new permissions. E.g. 0644.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_fchmod() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_fchown
eio_fallocate
eio_fchown
Eio Funkcje


Change file ownership

eio_fchmod
eio_fdatasync
Eio Funkcje
PHP Manual

eio_fchown

(PECL eio >= 0.0.1dev)

eio_fchown — Change file ownership

Opis

resource eio_fchown ( int $fd , int $uid [, int $gid = -1 [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]]] )

eio_fchown() changes ownership of the file specified by fd file descriptor.

Parametry

fd

The file descriptor.

uid

User ID. Is ignored when equal to -1.

gid

Group ID. Is ignored when equal to -1.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zobacz też:

  • eio_fchmod
eio_fchmod
eio_fdatasync
Eio Funkcje


Synchronize a file's in-core state with storage device.

eio_fchown
eio_fstat
Eio Funkcje
PHP Manual

eio_fdatasync

(PECL eio >= 0.0.1dev)

eio_fdatasync — Synchronize a file's in-core state with storage device.

Opis

resource eio_fdatasync ( int $fd [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_fdatasync() synchronizes a file's in-core state with storage device.

Parametry

fd

The file descriptor, e.g. returned by eio_open().

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_fdatasync() returns request resource on success or FALSE on error.

eio_fchown
eio_fstat
Eio Funkcje


Get file status

eio_fdatasync
eio_fstatvfs
Eio Funkcje
PHP Manual

eio_fstat

(PECL eio >= 0.0.1dev)

eio_fstat — Get file status

Opis

resource eio_fstat ( int $fd , int $pri , callback $callback [, mixed $data ] )

eio_fstat() returns file status information in result argument of callback

Parametry

fd

The file descriptor.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_busy() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_lstat() example

<?php
// Create temporary file
$tmp_filename = dirname(__FILE__) ."/eio-file.tmp";
touch($tmp_filename);

/* Is called when eio_fstat() done */
function my_res_cb($data, $result) {
 // Should output array with stat info
 var_dump($result);

 if ($data['fd']) {
  // Close temporary file
  eio_close($data['fd']);
  eio_event_loop();
 }
 // Remove temporary file
 @unlink($data['file']);
}

/* Is called when eio_open() done */
function my_open_cb($data, $result) {
 // Prepare data for callback
 $d = array(
  'fd'  => $result,
  'file'=> $data
 );
 // Request stat info
 eio_fstat($result, EIO_PRI_DEFAULT, "my_res_cb", $d);
 // Process request(s)
 eio_event_loop();
}

// Open temporary file
eio_open($tmp_filename, EIO_O_RDONLY, NULL, EIO_PRI_DEFAULT,
  "my_open_cb", $tmp_filename);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

array(12) {
 ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2489159)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318239506)
  ["st_mtime"]=>
  int(1318239506)
  ["st_ctime"]=>
  int(1318239506)
}

Zobacz też:

  • eio_lstat
  • eio_stat
eio_fdatasync
eio_fstatvfs
Eio Funkcje


Get file system statistics

eio_fstat
eio_fsync
Eio Funkcje
PHP Manual

eio_fstatvfs

(PECL eio >= 0.0.1dev)

eio_fstatvfs — Get file system statistics

Opis

resource eio_fstatvfs ( int $fd , int $pri , callback $callback [, mixed $data ] )

eio_fstatvfs() returns file system statistics in result of callback.

Parametry

fd

A file descriptor of a file within the mounted file system.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_fstatvfs() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_statvfs
eio_fstat
eio_fsync
Eio Funkcje


Synchronize a file's in-core state with storage device

eio_fstatvfs
eio_ftruncate
Eio Funkcje
PHP Manual

eio_fsync

(PECL eio >= 0.0.1dev)

eio_fsync — Synchronize a file's in-core state with storage device

Opis

resource eio_fsync ( int $fd [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

Synchronize a file's in-core state with storage device

Parametry

fd

The file descriptor.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_fsync() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_sync
eio_fstatvfs
eio_ftruncate
Eio Funkcje


Truncate a file

eio_fsync
eio_futime
Eio Funkcje
PHP Manual

eio_ftruncate

(PECL eio >= 0.0.1dev)

eio_ftruncate — Truncate a file

Opis

resource eio_ftruncate ( int $fd [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]]] )

eio_ftruncate() causes a regular file referenced by fd file descriptor to be truncated to precisely length bytes.

Parametry

fd

The file descriptor.

offset

Offset from beginning of the file

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_ftruncate() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_truncate
eio_fsync
eio_futime
Eio Funkcje


Change file last access and modification times

eio_ftruncate
eio_get_event_stream
Eio Funkcje
PHP Manual

eio_futime

(PECL eio >= 0.0.1dev)

eio_futime — Change file last access and modification times

Opis

resource eio_futime ( int $fd , float $atime , float $mtime [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_futime() changes file last access and modification times.

Parametry

fd

The file descriptor, e.g. returned by eio_open()

atime

Access time

mtime

Modification time

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_futime() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_utime
eio_ftruncate
eio_get_event_stream
Eio Funkcje


Get stream representing a variable used in internal communications with libeio.

eio_futime
eio_grp_add
Eio Funkcje
PHP Manual

eio_get_event_stream

(PECL eio >= 0.3.1b)

eio_get_event_stream — Get stream representing a variable used in internal communications with libeio.

Opis

mixed eio_get_event_stream ( void )

eio_get_event_stream() acquires stream representing a variable used in internal communications with libeio. Could be used to bind with some event loop provided by other PECL extension, for example libevent.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

eio_get_event_stream() returns stream on success; otherwise, NULL

Przykłady

Przykład #1 Using eio with libevent

<?php
function my_eio_poll($fd, $events, $arg) {
    /* Some libevent regulation might go here .. */
    if (eio_nreqs()) {
        eio_poll();
    }
    /* .. and here */
}

function my_res_cb($d, $r) {
    var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

$fd = eio_get_event_stream();
var_dump($fd);

eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

Powyższy przykład wyświetli coś podobnego do:

int(3)
int(0)
string(8) "nop data"
int(0)
string(10) "mkdir data"
eio_futime
eio_grp_add
Eio Funkcje


Adds a request to the request group.

eio_get_event_stream
eio_grp_cancel
Eio Funkcje
PHP Manual

eio_grp_add

(PECL eio >= 0.0.1dev)

eio_grp_add — Adds a request to the request group.

Opis

void eio_grp_add ( resource $grp , resource $req )

eio_grp_add() adds a request to the request group.

Parametry

grp

The request group resource returned by eio_grp()

req

The request resource

Zwracane wartości

eio_grp_add() doesn't return a value.

Przykłady

Przykład #1 Grouping requests

<?php
/*
 * Create a group request to open, read and close a file
 */

// Create temporary file and write some bytes to it
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
 var_dump($result == 0);
 @unlink($data);
}

/* Is called when eio_open() done */
function my_grp_file_opened_callback($data, $result) {
 global $grp;

 // $result should contain the file descriptor
 var_dump($result > 0);

 // Create eio_read() request and add it to the group
 // Pass file descriptor to the callback
 $req = eio_read($result, 4, 0,
   EIO_PRI_DEFAULT, "my_grp_file_read_callback", $result);
 eio_grp_add($grp, $req);
}

/* Is called when eio_read() done */
function my_grp_file_read_callback($data, $result) {
 global $grp;

 // Read bytes
 var_dump($result);

 // Create eio_close() request and add it to the group
 // $data should contain the file descriptor
 $req = eio_close($data);
 eio_grp_add($grp, $req);
}

// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);
var_dump($grp);

// Create eio_open() request and add it to the group
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
  EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

resource(6) of type (EIO Group Descriptor)
bool(true)
string(4) "some"
bool(true)

Zobacz też:

  • eio_grp
  • eio_grp_cancel
  • eio_grp_limit
eio_get_event_stream
eio_grp_cancel
Eio Funkcje


Cancels a request group

eio_grp_add
eio_grp_limit
Eio Funkcje
PHP Manual

eio_grp_cancel

(PECL eio >= 0.0.1dev)

eio_grp_cancel — Cancels a request group

Opis

void eio_grp_cancel ( resource $grp )

eio_grp_cancel() cancels a group request specified by grp request group resource.

Parametry

grp

The request group resource returned by eio_grp().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • eio_grp
  • eio_grp_add
eio_grp_add
eio_grp_limit
Eio Funkcje


Set group limit

eio_grp_cancel
eio_grp
Eio Funkcje
PHP Manual

eio_grp_limit

(PECL eio >= 0.0.1dev)

eio_grp_limit — Set group limit

Opis

void eio_grp_limit ( resource $grp , int $limit )

Limit number of requests in the request group.

Parametry

grp

The request group resource.

limit

Number of requests in the group.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • eio_grp_add
eio_grp_cancel
eio_grp
Eio Funkcje


Createsa request group.

eio_grp_limit
eio_link
Eio Funkcje
PHP Manual

eio_grp

(PECL eio >= 0.0.1dev)

eio_grp — Createsa request group.

Opis

resource eio_grp ( callback $callback [, string $data = NULL ] )

eio_grp() creates a request group.

Parametry

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_grp() returns request group resource on success or FALSE on error.

Przykłady

Przykład #1 eio_grp() example

<?php
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);
$my_file_fd = NULL;

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
 // Remove the file, if it still exists
 @unlink($data);
}

/* Is called when the temporary file is opened */
function my_grp_file_opened_callback($data, $result) {
 global $my_file_fd, $grp;

 $my_file_fd = $result;

 $req = eio_read($my_file_fd, 4, 0,
   EIO_PRI_DEFAULT, "my_grp_file_read_callback");
 eio_grp_add($grp, $req);
}

/* Is called when the file is read */
function my_grp_file_read_callback($data, $result) {
 global $my_file_fd, $grp;

 var_dump($result);

 // Create request to close the file
 $req = eio_close($my_file_fd);

 // Add request to the group
 eio_grp_add($grp, $req);
}

// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);

// Create request
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
  EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);

// Add request to the group
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

string(4) "some"

Zobacz też:

  • eio_grp_cancel
  • eio_grp_add
eio_grp_limit
eio_link
Eio Funkcje


Create a hardlink for file

eio_grp
eio_lstat
Eio Funkcje
PHP Manual

eio_link

(PECL eio >= 0.0.1dev)

eio_link — Create a hardlink for file

Opis

resource eio_link ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_link() creates a hardlink new_path for a file specified by path.

Parametry

path

Source file path.

new_path

Target file path.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

Przykłady

Przykład #1 eio_link() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";

function my_hardlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && !is_link($data));
    @unlink($data);

    eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}

function my_symlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && is_link($data));

    if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
        @unlink($link);
        @unlink($filename);
    }
}

function my_readlink_cb($data, $result) {
    global $filename, $link;
    var_dump($result);

    @unlink($link);
    @unlink($filename);
}

eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
string(%d) "%ssymlink.dat"

Zobacz też:

  • eio_symlink
eio_grp
eio_lstat
Eio Funkcje


Get file status

eio_link
eio_mkdir
Eio Funkcje
PHP Manual

eio_lstat

(PECL eio >= 0.0.1dev)

eio_lstat — Get file status

Opis

resource eio_lstat ( string $path , int $pri , callback $callback [, mixed $data = NULL ] )

eio_lstat() returns file status information in result argument of callback

Parametry

path

The file path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_lstat() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_lstat() example

<?php
$tmp_filename = dirname(__FILE__). "/eio-file.tmp";
touch($tmp_filename);

function my_res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

function my_open_cb($data, $result) {
    eio_close($result);
    eio_event_loop();

    @unlink($data);
}

eio_lstat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_lstat");
eio_open($tmp_filename, EIO_O_RDONLY, NULL,
 EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

string(9) "eio_lstat"
array(12) {
 ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2099197)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318235777)
  ["st_mtime"]=>
  int(1318235777)
  ["st_ctime"]=>
  int(1318235777)
}

Zobacz też:

  • eio_stat
  • eio_fstat
eio_link
eio_mkdir
Eio Funkcje


Create directory

eio_lstat
eio_mknod
Eio Funkcje
PHP Manual

eio_mkdir

(PECL eio >= 0.0.1dev)

eio_mkdir — Create directory

Opis

resource eio_mkdir ( string $path , int $mode [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_mkdir() creates directory with specified access mode.

Parametry

path

Path for the new directory.

mode

Access mode, e.g. 0755

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_mkdir() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_mkdir() example

<?php
$temp_dirname = "eio-temp-dir";

/* Is called when eio_mkdir() finishes */
function my_mkdir_callback($data, $result) {
 if ($result == 0 && is_dir($temp_dirname)
   && !is_readable($temp_dirname)
   && is_writable($temp_dirname)) {
  echo "eio_mkdir_ok";
 }

 // Remove directory
    if (file_exists($data))
        rmdir($temp_dirname);
}

// Create directory with access mode 0300
eio_mkdir($temp_dirname, 0300, EIO_PRI_DEFAULT, "my_mkdir_callback", $temp_dirname);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

eio_mkdir_ok

Zobacz też:

  • eio_rmdir
eio_lstat
eio_mknod
Eio Funkcje


Create a special or ordinary file.

eio_mkdir
eio_nop
Eio Funkcje
PHP Manual

eio_mknod

(PECL eio >= 0.0.1dev)

eio_mknod — Create a special or ordinary file.

Opis

resource eio_mknod ( string $path , int $mode , int $dev [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_mknod() creates ordinary or special(often) file.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

path

Path for the new node(file).

mode

Specifies both the permissions to use and the type of node to be created. It should be a combination (using bitwise OR) of one of the file types listed below and the permissions for the new node(e.g. 0640). Possible file types are: EIO_S_IFREG(regular file), EIO_S_IFCHR(character file), EIO_S_IFBLK(block special file), EIO_S_IFIFO(FIFO - named pipe) and EIO_S_IFSOCK(UNIX domain socket). To specify permissions EIO_S_I* constants could be used.

dev

If the file type is EIO_S_IFCHR or EIO_S_IFBLK then dev specifies the major and minor numbers of the newly created device special file. Otherwise dev ignored. See mknod(2) man page for details.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_mknod() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_mknod() example

<?php
// FIFO name
$temp_filename = "/tmp/eio-temp-fifo";

/* Is called when eio_mknod() finishes */
function my_mknod_callback($data, $result) {
    $s = stat($data);
    var_dump($s);

    if ($result == 0) {
        echo "eio_mknod_ok";
    }

    @unlink($data);
}

eio_mknod($temp_filename, EIO_S_IFIFO, 0,
    EIO_PRI_DEFAULT, "my_mknod_callback", $temp_filename);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

array(26) {
  [0]=>
  int(17)
  [1]=>
  int(2337608)
  [2]=>
  int(4096)
  [3]=>
  int(1)
  [4]=>
  int(1000)
  [5]=>
  int(100)
  [6]=>
  int(0)
  [7]=>
  int(0)
  [8]=>
  int(1318241261)
  [9]=>
  int(1318241261)
  [10]=>
  int(1318241261)
  [11]=>
  int(4096)
  [12]=>
  int(0)
  ["dev"]=>
  int(17)
  ["ino"]=>
  int(2337608)
  ["mode"]=>
  int(4096)
  ["nlink"]=>
  int(1)
  ["uid"]=>
  int(1000)
  ["gid"]=>
  int(100)
  ["rdev"]=>
  int(0)
  ["size"]=>
  int(0)
  ["atime"]=>
  int(1318241261)
  ["mtime"]=>
  int(1318241261)
  ["ctime"]=>
  int(1318241261)
  ["blksize"]=>
  int(4096)
  ["blocks"]=>
  int(0)
}
eio_mknod_ok

Zobacz też:

  • eio_open
eio_mkdir
eio_nop
Eio Funkcje


Does nothing, except go through the whole request cycle.

eio_mknod
eio_npending
Eio Funkcje
PHP Manual

eio_nop

(PECL eio >= 0.0.1dev)

eio_nop — Does nothing, except go through the whole request cycle.

Opis

resource eio_nop ([ int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_nop() does nothing, except go through the whole request cycle. Could be useful in debugging.

Parametry

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_nop() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_busy
eio_mknod
eio_npending
Eio Funkcje


Returns number of finished, but unhandled requests

eio_nop
eio_nready
Eio Funkcje
PHP Manual

eio_npending

(PECL eio >= 0.0.1dev)

eio_npending — Returns number of finished, but unhandled requests

Opis

int eio_npending ( void )

eio_npending() returns number of finished, but unhandled requests

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

eio_npending() returns number of finished, but unhandled requests.

Zobacz też:

  • eio_nreqs
  • eio_nready
  • eio_nthreads
eio_nop
eio_nready
Eio Funkcje


Returns number of not-yet handled requests

eio_npending
eio_nreqs
Eio Funkcje
PHP Manual

eio_nready

(PECL eio >= 0.0.1dev)

eio_nready — Returns number of not-yet handled requests

Opis

int eio_nready ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

eio_nready() returns number of not-yet handled requests

Zobacz też:

  • eio_nreqs
  • eio_nready
  • eio_nthreads
eio_npending
eio_nreqs
Eio Funkcje


Returns number of requests to be processed

eio_nready
eio_nthreads
Eio Funkcje
PHP Manual

eio_nreqs

(PECL eio >= 0.0.1dev)

eio_nreqs — Returns number of requests to be processed

Opis

int eio_nreqs ( void )

eio_nreqs() could be called in a custom loop calling eio_poll().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

eio_nreqs() returns number of requests to be processed.

Przykłady

Przykład #1 eio_nreqs() example

<?php
function res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");

while (eio_nreqs()) {
    eio_poll();
}
?>

Powyższy przykład wyświetli coś podobnego do:

string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)

Zobacz też:

  • eio_poll
  • eio_nready
eio_nready
eio_nthreads
Eio Funkcje


Returns number of threads currently in use

eio_nreqs
eio_open
Eio Funkcje
PHP Manual

eio_nthreads

(PECL eio >= 0.0.1dev)

eio_nthreads — Returns number of threads currently in use

Opis

int eio_nthreads ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

eio_nthreads() returns number of threads currently in use.

Zobacz też:

  • eio_npending
  • eio_nready
  • eio_nreqs
eio_nreqs
eio_open
Eio Funkcje


Opens a file

eio_nthreads
eio_poll
Eio Funkcje
PHP Manual

eio_open

(PECL eio >= 0.0.1dev)

eio_open — Opens a file

Opis

resource eio_open ( string $path , int $flags , int $mode , int $pri , callback $callback [, mixed $data = NULL ] )

eio_open() opens file specified by path in access mode mode with

Parametry

path

Path of the file to be opened.

Ostrzeżenie

In some SAPIs(e.g. PHP-FPM) it could fail, if you don't specify full path.

flags

One of EIO_O_* constants, or their combinations. EIO_O_* constants have the same meaning, as their corresponding O_* counterparts defined in fnctl.h C header file. Default is EIO_O_RDWR.

mode

One of EIO_S_I* constants, or their combination (via bitwise OR operator). The constants have the same meaning as their S_I* counterparts defined in » sys/stat.h C header file. Required, if a file is created. Otherwise ignored.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_open() returns file descriptor in result argument of callback on success; otherwise, result is equal to -1.

Przykłady

Przykład #1 eio_open() example

<?php
$temp_filename = "eio-temp-file.tmp";

/* Is called when eio_close() finishes */
function my_close_cb($data, $result) {
 // Zero indicates success
    var_dump($result == 0);
 @unlink($data);
}

/* Is called when eio_open() finishes */
function my_file_opened_callback($data, $result) {
 // $result should contain the file descriptor
    var_dump($result > 0);

    if ($result > 0) {
  // Close the file
        eio_close($result, EIO_PRI_DEFAULT, "my_close_cb", $data);
        eio_event_loop();
    }
}

// Create new file for reading and writing
// Deny group and others to do anything with that file
eio_open($temp_filename, EIO_O_CREAT | EIO_O_RDWR, EIO_S_IRUSR | EIO_S_IWUSR,
  EIO_PRI_DEFAULT, "my_file_opened_callback", $temp_filename);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)

Zobacz też:

  • eio_mknod
eio_nthreads
eio_poll
Eio Funkcje


Can be to be called whenever there are pending requests that need finishing.

eio_open
eio_read
Eio Funkcje
PHP Manual

eio_poll

(PECL eio >= 0.0.1dev)

eio_poll — Can be to be called whenever there are pending requests that need finishing.

Opis

int eio_poll ( void )

eio_poll() can be used to implement special event loop. For this eio_nreqs() could be used to test if there are unprocessed requests.

Informacja:

Applicable only when implementing userspace event loop.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

If any request invocation returns a non-zero value, returns that value. Otherwise, it returns 0.

Przykłady

Przykład #1 eio_poll() example

<?php
function res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");

while (eio_nreqs()) {
    // Some specific IPC or so
    eio_poll();
}
?>

Powyższy przykład wyświetli coś podobnego do:

string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)

Zobacz też:

  • eio_nreqs
eio_open
eio_read
Eio Funkcje


Read from a file descriptor at given offset.

eio_poll
eio_readahead
Eio Funkcje
PHP Manual

eio_read

(PECL eio >= 0.0.1dev)

eio_read — Read from a file descriptor at given offset.

Opis

resource eio_read ( int $fd , int $length , int $offset , int $pri , callback $callback [, mixed $data = NULL ] )

eio_read() reads up to length bytes from fd file descriptor at offset. The read bytes are stored in result argument of callback.

Parametry

fd

The file descriptor

length

Maximum number of bytes to read.

offset

Offset within the file.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_read() stores read bytes in result argument of callback function.

Przykłady

Przykład #1 eio_read() example

<?php
// Open a temporary file and write some bytes there
$temp_filename = "eio-temp-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "1234567890");
fclose($fp);

/* Is called when eio_read() is done */
function my_read_cb($data, $result) {
    global $temp_filename;

 // Output read bytes
    var_dump($result);

 // Close file
    eio_close($data);
    eio_event_loop();

 // Remove temporary file
    @unlink($temp_filename);
}

/* Is called when eio_open() is done */
function my_file_opened_callback($data, $result) {
 // $result should contain the file descriptor
    if ($result > 0) {
  // Read 5 bytes starting from third
        eio_read($result, 5, 2, EIO_PRI_DEFAULT, "my_read_cb", $result);
        eio_event_loop();
    } else {
  // eio_open() failed
        unlink($data);
    }
}

// Open the file for reading and writing
eio_open($temp_filename, EIO_O_RDWR, NULL,
    EIO_PRI_DEFAULT, "my_file_opened_callback", $temp_filename);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

string(5) "34567"

Zobacz też:

  • eio_open
  • eio_write
  • eio_close
  • eio_event_loop
eio_poll
eio_readahead
Eio Funkcje


Perform file readahead into page cache

eio_read
eio_readdir
Eio Funkcje
PHP Manual

eio_readahead

(PECL eio >= 0.0.1dev)

eio_readahead — Perform file readahead into page cache

Opis

resource eio_readahead ( int $fd , int $offset , int $length [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_readahead() populates the page cache with data from a file so that subsequent reads from that file will not block on disk I/O. See READAHEAD(2) man page for details.

Parametry

fd

The file descriptor

offset

Starting point from which data is to be read.

length

Number of bytes to be read.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_readahead() returns request resource on success or FALSE on error.

eio_read
eio_readdir
Eio Funkcje


Reads through a whole directory

eio_readahead
eio_readlink
Eio Funkcje
PHP Manual

eio_readdir

(PECL eio >= 0.0.1dev)

eio_readdir — Reads through a whole directory

Opis

resource eio_readdir ( string $path , int $flags , int $pri , callback $callback [, string $data = NULL ] )

Reads through a whole directory(via the opendir, readdir and closedir system calls) and returns either the names or an array in result argument of callback function, depending on the flags argument.

Parametry

path

Directory path.

flags

Combination of EIO_READDIR_* constants.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_readdir() returns request resource on success, or FALSE on error. Sets result argument of callback function according to flags:

EIO_READDIR_DENTS (integer)
eio_readdir() flag. If specified, the result argument of the callback becomes an array with the following keys: 'names' - array of directory names 'dents' - array of struct eio_dirent-like arrays having the following keys each: 'name' - the directory name; 'type' - one of EIO_DT_* constants; 'inode' - the inode number, if available, otherwise unspecified;
EIO_READDIR_DIRS_FIRST (integer)
When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order.
EIO_READDIR_STAT_ORDER (integer)
When this flag is specified, then the names will be returned in an order suitable for stat'ing each one. When planning to stat() all files in the given directory, the returned order will likely be fastest.
EIO_READDIR_FOUND_UNKNOWN (integer)

Node types:

EIO_DT_UNKNOWN (integer)
Unknown node type(very common). Further stat() needed.
EIO_DT_FIFO (integer)
FIFO node type
EIO_DT_CHR (integer)
Node type
EIO_DT_MPC (integer)
Multiplexed char device (v7+coherent) node type
EIO_DT_DIR (integer)
Directory node type
EIO_DT_NAM (integer)
Xenix special named file node type
EIO_DT_BLK (integer)
Node type
EIO_DT_MPB (integer)
Multiplexed block device (v7+coherent)
EIO_DT_REG (integer)
Node type
EIO_DT_NWK (integer)
EIO_DT_CMP (integer)
HP-UX network special node type
EIO_DT_LNK (integer)
Link node type
EIO_DT_SOCK (integer)
Socket node type
EIO_DT_DOOR (integer)
Solaris door node type
EIO_DT_WHT (integer)
Node type
EIO_DT_MAX (integer)
Highest node type value

Przykłady

Przykład #1 eio_readdir() example

<?php
/* Is called when eio_readdir() finishes */
function my_readdir_callback($data, $result) {
    echo __FUNCTION__, " called\n";
    echo "data: "; var_dump($data);
    echo "result: "; var_dump($result);
    echo "\n";
}

eio_readdir("/var/spool/news", EIO_READDIR_STAT_ORDER | EIO_READDIR_DIRS_FIRST,
  EIO_PRI_DEFAULT, "my_readdir_callback");
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

my_readdir_callback called
data: NULL
result: array(2) {
 ["names"]=>
  array(7) {
   [0]=>
    string(7) "archive"
    [1]=>
    string(8) "articles"
    [2]=>
    string(8) "incoming"
    [3]=>
    string(7) "innfeed"
    [4]=>
    string(8) "outgoing"
    [5]=>
    string(8) "overview"
    [6]=>
    string(3) "tmp"
  }
 ["dents"]=>
  array(7) {
   [0]=>
    array(3)
    {
     ["name"]=>
      string(7)
      "archive"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393265)
    }
   [1]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "articles"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393266)
    }
   [2]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "incoming"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393267)
    }
   [3]=>
    array(3)
    {
     ["name"]=>
      string(7)
      "innfeed"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393269)
    }
   [4]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "outgoing"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393270)
    }
   [5]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "overview"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393271)
    }
   [6]=>
    array(3)
    {
     ["name"]=>
      string(3)
      "tmp"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393272)
    }
  }
}
eio_readahead
eio_readlink
Eio Funkcje


Read value of a symbolic link.

eio_readdir
eio_realpath
Eio Funkcje
PHP Manual

eio_readlink

(PECL eio >= 0.0.1dev)

eio_readlink — Read value of a symbolic link.

Opis

resource eio_readlink ( string $path , int $pri , callback $callback [, string $data = NULL ] )

Parametry

path

Source symbolic link path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_readlink() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_readlink() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";

function my_hardlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && !is_link($data));
    @unlink($data);

    eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}

function my_symlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && is_link($data));

    if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
        @unlink($link);
        @unlink($filename);
    }
}

function my_readlink_cb($data, $result) {
    global $filename, $link;
    var_dump($result);

    @unlink($link);
    @unlink($filename);
}

eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
string(16) "/tmp/symlink.dat"

Zobacz też:

  • eio_symlink
eio_readdir
eio_realpath
Eio Funkcje


Get the canonicalized absolute pathname.

eio_readlink
eio_rename
Eio Funkcje
PHP Manual

eio_realpath

(PECL eio >= 0.0.1dev)

eio_realpath — Get the canonicalized absolute pathname.

Opis

resource eio_realpath ( string $path , int $pri , callback $callback [, string $data = NULL ] )

eio_realpath() returns the canonicalized absolute pathname in result argument of callback function.

Parametry

path

Short pathname

pri

callback

data

Zwracane wartości

Przykłady

Przykład #1 eio_realpath() example

<?php
var_dump(getcwd());

function my_realpath_allback($data, $result) {
    var_dump($result);
}

eio_realpath("../", EIO_PRI_DEFAULT, "my_realpath_allback");
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

string(12) "/home/ruslan"
string(5) "/home"
eio_readlink
eio_rename
Eio Funkcje


Change the name or location of a file.

eio_realpath
eio_rmdir
Eio Funkcje
PHP Manual

eio_rename

(PECL eio >= 0.0.1dev)

eio_rename — Change the name or location of a file.

Opis

resource eio_rename ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_rename() renames or moves a file to new location.

Parametry

path

Source path

new_path

Target path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_rename() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_rename() example

<?php
$filename = dirname(__FILE__)."/eio-temp-file.dat";
touch($filename);
$new_filename = dirname(__FILE__)."/eio-temp-file-new.dat";

function my_rename_cb($data, $result) {
    global $filename, $new_filename;

    if ($result == 0 && !file_exists($filename) && file_exists($new_filename)) {
        @unlink($new_filename);
        echo "eio_rename_ok";
    } else {
        @unlink($filename);
    }
}

eio_rename($filename, $new_filename, EIO_PRI_DEFAULT, "my_rename_cb", $filename);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

eio_rename_ok
eio_realpath
eio_rmdir
Eio Funkcje


Remove a directory

eio_rename
eio_sendfile
Eio Funkcje
PHP Manual

eio_rmdir

(PECL eio >= 0.0.1dev)

eio_rmdir — Remove a directory

Opis

resource eio_rmdir ( string $path [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_rmdir() removes a directory.

Parametry

path

Directory path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_rmdir() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_rmdir() example

<?php
$temp_dirname = "eio-temp-dir";
mkdir($temp_dirname);

function my_rmdir_callback($data, $result) {
    if ($result == 0 && !file_exists($data)) {
        echo "eio_rmdir_ok";
    } else if (file_exists($data)) {
        rmdir($data);
    }
}

eio_rmdir($temp_dirname, EIO_PRI_DEFAULT, "my_rmdir_callback", $temp_dirname);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

eio_rmdir_ok

Zobacz też:

  • eio_mkdir
eio_rename
eio_sendfile
Eio Funkcje


Transfer data between file descriptors

eio_rmdir
eio_set_max_idle
Eio Funkcje
PHP Manual

eio_sendfile

(PECL eio >= 0.0.1dev)

eio_sendfile — Transfer data between file descriptors

Opis

resource eio_sendfile ( int $out_fd , int $in_fd , int $offset , int $length [, int $pri [, callback $callback [, string $data ]]] )

eio_sendfile() copies data between one file descriptor and another. See SENDFILE(2) man page for details.

Parametry

out_fd

Output file descriptor. Should be opened for writing.

in_fd

Input file descriptor. Should be opened for reading.

offset

Offset within the source file.

length

Number of bytes to copy.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_sendfile() returns request resource on success or FALSE on error.

eio_rmdir
eio_set_max_idle
Eio Funkcje


Set maximum number of idle threads.

eio_sendfile
eio_set_max_parallel
Eio Funkcje
PHP Manual

eio_set_max_idle

(PECL eio >= 0.0.1dev)

eio_set_max_idle — Set maximum number of idle threads.

Opis

void eio_set_max_idle ( int $nthreads )

Parametry

nthreads

Number of idle threads.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • eio_set_min_parallel
  • eio_set_max_parallel
eio_sendfile
eio_set_max_parallel
Eio Funkcje


Set maximum parallel threads

eio_set_max_idle
eio_set_max_poll_reqs
Eio Funkcje
PHP Manual

eio_set_max_parallel

(PECL eio >= 0.0.1dev)

eio_set_max_parallel — Set maximum parallel threads

Opis

void eio_set_max_parallel ( int $nthreads )

Parametry

nthreads

Number of parallel threads

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • eio_set_min_parallel
eio_set_max_idle
eio_set_max_poll_reqs
Eio Funkcje


Set maximum number of requests processed in a poll.

eio_set_max_parallel
eio_set_max_poll_time
Eio Funkcje
PHP Manual

eio_set_max_poll_reqs

(PECL eio >= 0.0.1dev)

eio_set_max_poll_reqs — Set maximum number of requests processed in a poll.

Opis

void eio_set_max_poll_reqs ( int $nreqs )

Parametry

nreqs

Number of requests

Zwracane wartości

Nie jest zwracana żadna wartość.

eio_set_max_parallel
eio_set_max_poll_time
Eio Funkcje


Set maximum poll time

eio_set_max_poll_reqs
eio_set_min_parallel
Eio Funkcje
PHP Manual

eio_set_max_poll_time

(PECL eio >= 0.0.1dev)

eio_set_max_poll_time — Set maximum poll time

Opis

void eio_set_max_poll_time ( float $nseconds )

Polling stops, if poll took longer than nseconds seconds.

Parametry

nseconds

Number of seconds

Zwracane wartości

Nie jest zwracana żadna wartość.

eio_set_max_poll_reqs
eio_set_min_parallel
Eio Funkcje


Set minimum parallel thread number

eio_set_max_poll_time
eio_stat
Eio Funkcje
PHP Manual

eio_set_min_parallel

(PECL eio >= 0.0.1dev)

eio_set_min_parallel — Set minimum parallel thread number

Opis

void eio_set_min_parallel ( string $nthreads )

Parametry

nthreads

Number of parallel threads.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • eio_set_max_parallel
eio_set_max_poll_time
eio_stat
Eio Funkcje


Get file status

eio_set_min_parallel
eio_statvfs
Eio Funkcje
PHP Manual

eio_stat

(PECL eio >= 0.0.1dev)

eio_stat — Get file status

Opis

resource eio_stat ( string $path , int $pri , callback $callback [, mixed $data = NULL ] )

eio_stat() returns file status information in result argument of callback

Parametry

path

The file path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_stat() returns request resource on success or FALSE on error. On success assigns result argument of callback to an array.

Przykłady

Przykład #1 eio_stat() example

<?php
$tmp_filename = "eio-file.tmp";
touch($tmp_filename);

function my_res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

function my_open_cb($data, $result) {
    eio_close($result);
    eio_event_loop();

    @unlink($data);
}

eio_stat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_stat");
eio_open($tmp_filename, EIO_O_RDONLY, NULL,
 EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

string(8) "eio_stat"
array(12) {
  ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2489173)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318250380)
  ["st_mtime"]=>
  int(1318250380)
  ["st_ctime"]=>
  int(1318250380)
}

Zobacz też:

  • eio_lstat
  • eio_fstat
eio_set_min_parallel
eio_statvfs
Eio Funkcje


Get file system statistics

eio_stat
eio_symlink
Eio Funkcje
PHP Manual

eio_statvfs

(PECL eio >= 0.0.1dev)

eio_statvfs — Get file system statistics

Opis

resource eio_statvfs ( string $path , int $pri , callback $callback [, mixed $data ] )

eio_statvfs() returns file system statistics information in result argument of callback

Parametry

path

Pathname of any file within the mounted file system

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_statvfs() returns request resource on success or FALSE on error. On success assigns result argument of callback to an array.

Przykłady

Przykład #1 eio_statvfs() example

<?php
$tmp_filename = '/tmp/eio-file.tmp';
touch($tmp_filename);

function my_statvfs_callback($data, $result) {
    var_dump($data);
    var_dump($result);

 @unlink($data);
}

eio_statvfs($tmp_filename, EIO_PRI_DEFAULT, "my_statvfs_callback", $tmp_filename);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

string(17) "/tmp/eio-file.tmp"
array(11) {
  ["f_bsize"]=>
  int(4096)
  ["f_frsize"]=>
  int(4096)
  ["f_blocks"]=>
  int(262144)
  ["f_bfree"]=>
  int(262111)
  ["f_bavail"]=>
  int(262111)
  ["f_files"]=>
  int(1540815)
  ["f_ffree"]=>
  int(1540743)
  ["f_favail"]=>
  int(1540743)
  ["f_fsid"]=>
  int(0)
  ["f_flag"]=>
  int(4102)
  ["f_namemax"]=>
  int(255)
}
eio_stat
eio_symlink
Eio Funkcje


Create a symbolic link

eio_statvfs
eio_sync_file_range
Eio Funkcje
PHP Manual

eio_symlink

(PECL eio >= 0.0.1dev)

eio_symlink — Create a symbolic link

Opis

resource eio_symlink ( string $path , string $new_path [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_symlink() creates a symbolic link new_path to path.

Parametry

path

Source path

new_path

Target path

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_symlink() returns request resource on success or FALSE on error.

Przykłady

Przykład #1 eio_symlink() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";

function my_symlink_cb($data, $result) {
    global $link, $filename;
    var_dump(file_exists($data) && is_link($data));

    if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
        @unlink($link);
        @unlink($filename);
    }
}

function my_readlink_cb($data, $result) {
    global $filename, $link;
    var_dump($result);

    @unlink($link);
    @unlink($filename);
}

eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
eio_event_loop();
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
string(16) "/tmp/symlink.dat"

Zobacz też:

  • eio_link
eio_statvfs
eio_sync_file_range
Eio Funkcje


Sync a file segment with disk

eio_symlink
eio_sync
Eio Funkcje
PHP Manual

eio_sync_file_range

(PECL eio >= 0.0.1dev)

eio_sync_file_range — Sync a file segment with disk

Opis

resource eio_sync_file_range ( int $fd , int $offset , int $nbytes , int $flags [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_sync_file_range() permits fine control when synchronizing the open file referred to by the file descriptor fd with disk.

Parametry

fd

File descriptor

offset

The starting byte of the file range to be synchronized

nbytes

Specifies the length of the range to be synchronized, in bytes. If nbytes is zero, then all bytes from offset through to the end of file are synchronized.

flags

A bit-mask. Can include any of the following values: EIO_SYNC_FILE_RANGE_WAIT_BEFORE, EIO_SYNC_FILE_RANGE_WRITE, EIO_SYNC_FILE_RANGE_WAIT_AFTER. These flags have the same meaning as their SYNC_FILE_RANGE_* counterparts(see SYNC_FILE_RANGE(2) man page).

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_sync_file_range() returns request resource on success or FALSE on error.

eio_symlink
eio_sync
Eio Funkcje


Commit buffer cache to disk

eio_sync_file_range
eio_syncfs
Eio Funkcje
PHP Manual

eio_sync

(PECL eio >= 0.0.1dev)

eio_sync — Commit buffer cache to disk

Opis

resource eio_sync ([ int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

eio_sync() returns request resource on success or FALSE on error.

eio_sync_file_range
eio_syncfs
Eio Funkcje


Calls Linux' syncfs syscall, if available

eio_sync
eio_truncate
Eio Funkcje
PHP Manual

eio_syncfs

(PECL eio >= 0.0.1dev)

eio_syncfs — Calls Linux' syncfs syscall, if available

Opis

resource eio_syncfs ( int $fd [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

Parametry

fd

File descriptor

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_syncfs() returns request resource on success or FALSE on error.

eio_sync
eio_truncate
Eio Funkcje


Truncate a file

eio_syncfs
eio_unlink
Eio Funkcje
PHP Manual

eio_truncate

(PECL eio >= 0.0.1dev)

eio_truncate — Truncate a file

Opis

resource eio_truncate ( string $path [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]]] )

eio_truncate() causes the regular file named by path to be truncated to a size of precisely length bytes

Parametry

path

File path

offset

Offset from beginning of the file.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_busy() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_ftruncate
eio_syncfs
eio_unlink
Eio Funkcje


Delete a name and possibly the file it refers to

eio_truncate
eio_utime
Eio Funkcje
PHP Manual

eio_unlink

(PECL eio >= 0.0.1dev)

eio_unlink — Delete a name and possibly the file it refers to

Opis

resource eio_unlink ( string $path [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

eio_unlink() deletes a name from the file system.

Parametry

path

Path to file

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_unlink() returns request resource on success or FALSE on error.

eio_truncate
eio_utime
Eio Funkcje


Change file last access and modification times.

eio_unlink
eio_write
Eio Funkcje
PHP Manual

eio_utime

(PECL eio >= 0.0.1dev)

eio_utime — Change file last access and modification times.

Opis

resource eio_utime ( string $path , float $atime , float $mtime [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]] )

Parametry

path

Path to the file.

atime

Access time

mtime

Modification time

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_utime() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_futime
eio_unlink
eio_write
Eio Funkcje


Write to file

eio_utime
Expect
Eio Funkcje
PHP Manual

eio_write

(PECL eio >= 0.0.1dev)

eio_write — Write to file

Opis

resource eio_write ( int $fd , string &$str [, int $length = 0 [, int $offset = 0 [, int $pri = EIO_PRI_DEFAULT [, callback $callback = NULL [, mixed $data = NULL ]]]]] )

eio_write() writes up to length bytes from str at offset offset from the beginning of the file.

Parametry

fd

The file descriptor, e.g. returned by eio_open()

str

Source string

length

Maximum number of bytes to write.

offset

Offset from the beginning of file.

pri

The request priority: EIO_PRI_DEFAULT, EIO_PRI_MIN, EIO_PRI_MAX, or NULL. If NULL passed, pri internally is set to EIO_PRI_DEFAULT.

callback

callback function is called when the request is done. It should match the following prototype:

void callback($data, $result);
$data is custom data passed to the request. $result contains request-specific result value; basically, the value returned by corresponding system call.

data

Arbitrary variable passed to callback.

Zwracane wartości

eio_write() returns request resource on success or FALSE on error.

Zobacz też:

  • eio_open
eio_utime
Expect
Eio Funkcje


Expect

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Expect Usage Examples
  • Expect Funkcje
    • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process
eio_write
Wstęp
Rozszerzenia kontroli procesów


Wstęp

This extension allows to interact with processes through PTY. You may consider using the expect:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.

Expect
Instalacja/Konfiguracja
Expect


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Expect


Wymagania

This module uses the functions of the » expect library. You need libexpect version >= 5.43.0.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/expect.

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 PHP with expect support by using the --with-expect[=DIR] configure option.

Windows users will enable php_expect.dll inside of php.ini in order to use these functions. W PHP 4 ten DLL znajduje się w podkatalogu extensions/ binarnej dystrybucji PHP dla Windows. DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

In order to configure expect extension, there are configuration options in the configuration file php.ini.

Expect Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Changelog
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |
expect.match_max | "" | 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.

expect.timeout integer

The timeout period for waiting for the data, when using the expect_expectl() function.

A value of "-1" disables a timeout from occurring.

Informacja:

A value of "0" causes the expect_expectl() function to return immediately.

expect.loguser boolean

Whether expect should send any output from the spawned process to stdout. Since interactive programs typically echo their input, this usually suffices to show both sides of the conversation.

expect.logfile string

Name of the file, where the output from the spawned process will be written. If this file doesn't exist, it will be created.

Informacja:

If this configuration is not empty, the output is written regardless of the value of expect.loguser.

expect.match_max integer

Changes default size (2000 bytes) of the buffer used to match asterisks in patterns.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

expect_popen() returns an open PTY stream used by expect_expectl().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

EXP_GLOB (integer)
Indicates that the pattern is a glob-style string pattern.
EXP_EXACT (integer)
Indicates that the pattern is an exact string.
EXP_REGEXP (integer)
Indicates that the pattern is a regexp-style string pattern.
EXP_EOF (integer)
Value, returned by expect_expectl(), when EOF is reached.
EXP_TIMEOUT (integer)
Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout
EXP_FULLBUFFER (integer)
Value, returned by expect_expectl() if no pattern have been matched.
Typy zasobów
Przykłady
Expect


Przykłady

Spis treści

  • Expect Usage Examples
Stałe predefiniowane
Expect Usage Examples
Expect


Expect Usage Examples

Przykład #1 Expect Usage Example

This example connects to the remote host via SSH, and prints the remote uptime.

<?php
ini_set("expect.loguser", "Off");

$stream = fopen("expect://ssh root@remotehost uptime", "r");

$cases = array (
    array (0 => "password:", 1 => PASSWORD)
);

switch (expect_expectl ($stream, $cases)) {
    case PASSWORD:
        fwrite ($stream, "password\n");
        break;

    default:
        die ("Error was occurred while connecting to the remote host!\n");
}

while ($line = fgets($stream)) {
      print $line;
}
fclose ($stream);
?>

The following example connects to the remote host, determines whether installed OS is for 32 or 64 bit, then runs update for specific package.

Przykład #2 Another Expect Usage Example

<?php
ini_set("expect.timeout", -1);
ini_set("expect.loguser", "Off");

$stream = expect_popen("ssh root@remotehost");

while (true) {
    switch (expect_expectl ($stream, array (
            array ("password:", PASSWORD), // SSH is asking for password
            array ("yes/no)?", YESNO), // SSH is asking whether to store the host entry
            array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
    ))) {
        case PASSWORD:
            fwrite ($stream, "secret\n");
            break;

        case YESNO:
            fwrite ($stream, "yes\n");
            break;

        case SHELL:
            fwrite ($stream, "uname -a\n");
            while (true) {
                    switch (expect_expectl ($stream, array (
                            array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
                            array ("^Linux.*$", UNAME, EXP_REGEXP), // uname -a output
                    ), $match)) {
                        case UNAME:
                            $uname .= $match[0];
                            break;

                        case SHELL:
                            // Run update:
                            if (strstr ($uname, "x86_64")) {
                                    fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_64bit.rpm\n");
                            } else {
                                    fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_32bit.rpm\n");
                            }
                            fwrite ($stream, "exit\n");
                            break 2;

                        case EXP_TIMEOUT:
                        case EXP_EOF:
                            break 2;

                        default:
                            die ("Error has occurred!\n");
                    }
            }
            break 2;

        case EXP_TIMEOUT:
        case EXP_EOF:
            break 2;

        default:
            die ("Error has occurred!\n");
    }
}

fclose ($stream);
?>
Przykłady
Expect Funkcje
Przykłady


Expect Funkcje

Spis treści

  • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
  • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process
Expect Usage Examples
expect_expectl
Expect


Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

Expect Funkcje
expect_popen
Expect Funkcje
PHP Manual

expect_expectl

(PECL expect >= 0.1.0)

expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

Opis

int expect_expectl ( resource $expect , array $cases [, array &$match ] )

Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.

If match is provided, then it is filled with the result of search. The matched string can be found in match[0]. The match substrings (according to the parentheses) in the original pattern can be found in match[1], match[2], and so on, up to match[9] (the limitation of libexpect).

Parametry

expect

An Expect stream, previously opened with expect_popen().

cases

An array of expect cases. Each expect case is an indexed array, as described in the following table:

Expect Case Array
Index Key | Value Type | Description | Is Mandatory | Default Value
0 | string | pattern, that will be matched against the output from the stream | yes
1 | mixed | value, that will be returned by this function, if the pattern matches | yes
2 | integer | pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP | no | EXP_GLOB

Zwracane wartości

Returns value associated with the pattern that was matched.

On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER

Rejestr zmian

Wersja | Opis
0.2.1 | Prior to version 0.2.1, in match parameter a match string was returned, not an array of match substrings.

Przykłady

Przykład #1 expect_expectl() example

<?php
// Copies file from remote host:
ini_set("expect.timeout", 30);

$stream = fopen("expect://scp user@remotehost:/var/log/messages /home/user/messages.txt", "r");

$cases = array(
    // array(pattern, value to return if pattern matched)
    array("password:", "asked for password"),
    array("yes/no)?",  "asked for yes/no")
);

while (true) {
    switch (expect_expectl($stream, $cases)) {
        case "asked for password":
            fwrite($stream, "my password\n");
            break;
        case "asked for yes/no":
            fwrite($stream, "yes\n");
            break;
        case EXP_TIMEOUT:
        case EXP_EOF:
            break 2; // break both the switch statement and the while loop
        default:
            die "Error has occurred!";
    }
}

fclose($stream);
?>

Zobacz też:

  • expect_popen() - Execute command via Bourne shell, and open the PTY stream to the process

Expect Funkcje
expect_popen
Expect Funkcje


Execute command via Bourne shell, and open the PTY stream to the process

expect_expectl
Libevent
Expect Funkcje
PHP Manual

expect_popen

(PECL expect >= 0.1.0)

expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

Opis

resource expect_popen ( string $command )

Execute command via Bourne shell, and open the PTY stream to the process.

Parametry

command

Command to execute.

Zwracane wartości

Returns an open PTY stream to the processes stdio, stdout, and stderr.

On failure this function returns FALSE.

Przykłady

Przykład #1 expect_popen() example

<?php
// Login to the PHP.net CVS repository:
$stream = expect_popen ("cvs -d :pserver:anonymous@cvs.php.net:/repository login");
sleep (3);
fwrite ($stream, "phpfi\n");
fclose ($stream);
?>

Zobacz też:

  • popen() - Otwiera wskaźnik pliku do procesu

expect_expectl
Libevent
Expect Funkcje


Libevent

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Libevent Funkcje
    • event_add — Add an event to the set of monitored events
    • event_base_free — Destroy event base
    • event_base_loop — Handle events
    • event_base_loopbreak — Abort event loop
    • event_base_loopexit — Exit loop after a time
    • event_base_new — Create and initialize new event base
    • event_base_priority_init — Set the number of event priority levels
    • event_base_set — Associate event base with an event
    • event_buffer_base_set — Associate buffered event with an event base
    • event_buffer_disable — Disable a buffered event
    • event_buffer_enable — Enable a buffered event
    • event_buffer_fd_set — Change a buffered event file descriptor
    • event_buffer_free — Destroy buffered event
    • event_buffer_new — Create new buffered event
    • event_buffer_priority_set — Assign a priority to a buffered event
    • event_buffer_read — Read data from a buffered event
    • event_buffer_set_callback — Set or reset callbacks for a buffered event
    • event_buffer_timeout_set — Set read and write timeouts for a buffered event
    • event_buffer_watermark_set — Set the watermarks for read and write events
    • event_buffer_write — Write data to a buffered event
    • event_del — Remove an event from the set of monitored events
    • event_free — Free event resource
    • event_new — Create new event
    • event_set — Prepare an event
expect_popen
Wstęp
Rozszerzenia kontroli procesów


Wstęp

Libevent is a library that provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached.

More information about Libevent can be found at » http://www.monkey.org/~provos/libevent/.

Libevent
Instalacja/Konfiguracja
Libevent


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Libevent


Wymagania

This extension requires » libevent library. Minimal required version is 1.4.0.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/libevent.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

There are several resource types used in the extension. These resources are event, event base and buffered event.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

EV_TIMEOUT (integer)
EV_READ (integer)
EV_WRITE (integer)
EV_SIGNAL (integer)
EV_PERSIST (integer)
EVLOOP_NONBLOCK (integer)
EVLOOP_ONCE (integer)
Typy zasobów
Przykłady
Libevent


Przykłady

Przykład #1 polling STDIN using basic API

<?php

function print_line($fd, $events, $arg)
{
    static $max_requests = 0;

    $max_requests++;

    if ($max_requests == 10) {
        // exit loop after 10 writes
        event_base_loopexit($arg[1]);
    }

    // print the line
    echo  fgets($fd);
}

// create base and event
$base = event_base_new();
$event = event_new();

$fd = STDIN;

// set event flags
event_set($event, $fd, EV_READ | EV_PERSIST, "print_line", array($event, $base));
// set event base
event_base_set($event, $base);

// enable event
event_add($event);
// start event loop
event_base_loop($base);

?>

Przykład #2 polling STDIN using buffered event API

<?php

function print_line($buf, $arg)
{
    static $max_requests;

    $max_requests++;

    if ($max_requests == 10) {
        event_base_loopexit($arg);
    }

    // print the line
    echo event_buffer_read($buf, 4096);
}

function error_func($buf, $what, $arg)
{
    // handle errors
}

$base = event_base_new();
$eb = event_buffer_new(STDIN, "print_line", NULL, "error_func", $base);

event_buffer_base_set($eb, $base);
event_buffer_enable($eb, EV_READ);

event_base_loop($base);

?>

Stałe predefiniowane
Libevent Funkcje
Libevent


Libevent Funkcje

Spis treści

  • event_add — Add an event to the set of monitored events
  • event_base_free — Destroy event base
  • event_base_loop — Handle events
  • event_base_loopbreak — Abort event loop
  • event_base_loopexit — Exit loop after a time
  • event_base_new — Create and initialize new event base
  • event_base_priority_init — Set the number of event priority levels
  • event_base_set — Associate event base with an event
  • event_buffer_base_set — Associate buffered event with an event base
  • event_buffer_disable — Disable a buffered event
  • event_buffer_enable — Enable a buffered event
  • event_buffer_fd_set — Change a buffered event file descriptor
  • event_buffer_free — Destroy buffered event
  • event_buffer_new — Create new buffered event
  • event_buffer_priority_set — Assign a priority to a buffered event
  • event_buffer_read — Read data from a buffered event
  • event_buffer_set_callback — Set or reset callbacks for a buffered event
  • event_buffer_timeout_set — Set read and write timeouts for a buffered event
  • event_buffer_watermark_set — Set the watermarks for read and write events
  • event_buffer_write — Write data to a buffered event
  • event_del — Remove an event from the set of monitored events
  • event_free — Free event resource
  • event_new — Create new event
  • event_set — Prepare an event
Przykłady
event_add
Libevent


Add an event to the set of monitored events

Libevent Funkcje
event_base_free
Libevent Funkcje
PHP Manual

event_add

(PECL libevent >= 0.0.1)

event_add — Add an event to the set of monitored events

Opis

bool event_add ( resource $event [, int $timeout = -1 ] )

event_add() schedules the execution of the event when the event specified in event_set() occurs or in at least the time specified by the timeout argument. If timeout was not specified, not timeout is set. The event must be already initalized by event_set() and event_base_set() functions. If the event already has a timeout set, it is replaced by the new one.

Parametry

event

Valid event resource.

timeout

Optional timeout (in microseconds).

Zwracane wartości

event_add() returns TRUE on success or FALSE on error.

Libevent Funkcje
event_base_free
Libevent Funkcje


Destroy event base

event_add
event_base_loop
Libevent Funkcje
PHP Manual

event_base_free

(PECL libevent >= 0.0.1)

event_base_free — Destroy event base

Opis

void event_base_free ( resource $event_base )

Destroys the specified event_base and frees all the resources associated. Note that it's not possible to destroy an event base with events attached to it.

Parametry

event_base

Valid event base resource.

event_add
event_base_loop
Libevent Funkcje


Handle events

event_base_free
event_base_loopbreak
Libevent Funkcje
PHP Manual

event_base_loop

(PECL libevent >= 0.0.1)

event_base_loop — Handle events

Opis

int event_base_loop ( resource $event_base [, int $flags = 0 ] )

Starts event loop for the specified event base.

Parametry

event_base

Valid event base resource.

flags

Optional parameter, which can take any combination of EVLOOP_ONCE and EVLOOP_NONBLOCK.

Zwracane wartości

event_base_loop() returns 0 on success, -1 on error and 1 if no events were registered.

event_base_free
event_base_loopbreak
Libevent Funkcje


Abort event loop

event_base_loop
event_base_loopexit
Libevent Funkcje
PHP Manual

event_base_loopbreak

(PECL libevent >= 0.0.1)

event_base_loopbreak — Abort event loop

Opis

bool event_base_loopbreak ( resource $event_base )

Abort the active event loop immediately. The behaviour is similar to break statement.

Parametry

event_base

Valid event base resource.

Zwracane wartości

event_base_loopbreak() returns TRUE on success or FALSE on error.

event_base_loop
event_base_loopexit
Libevent Funkcje


Exit loop after a time

event_base_loopbreak
event_base_new
Libevent Funkcje
PHP Manual

event_base_loopexit

(PECL libevent >= 0.0.1)

event_base_loopexit — Exit loop after a time

Opis

bool event_base_loopexit ( resource $event_base [, int $timeout = -1 ] )

The next event loop iteration after the given timer expires will complete normally, then exit without blocking for events again.

Parametry

event_base

Valid event base resource.

timeout

Optional timeout parameter (in microseconds).

Zwracane wartości

event_base_loopexit() returns TRUE on success or FALSE on error.

event_base_loopbreak
event_base_new
Libevent Funkcje


Create and initialize new event base

event_base_loopexit
event_base_priority_init
Libevent Funkcje
PHP Manual

event_base_new

(PECL libevent >= 0.0.1)

event_base_new — Create and initialize new event base

Opis

resource event_base_new ( void )

Returns new event base, which can be used later in event_base_set(), event_base_loop() and other functions.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

event_base_new() returns valid event base resource on success or FALSE on error.

event_base_loopexit
event_base_priority_init
Libevent Funkcje


Set the number of event priority levels

event_base_new
event_base_set
Libevent Funkcje
PHP Manual

event_base_priority_init

(PECL libevent >= 0.0.2)

event_base_priority_init — Set the number of event priority levels

Opis

bool event_base_priority_init ( resource $event_base , int $npriorities )

Sets the number of different event priority levels.

By default all events are scheduled with the same priority (npriorities/2). Using event_base_priority_init() you can change the number of event priority levels and then set a desired priority for each event.

Parametry

event_base

Valid event base resource.

npriorities

The number of event priority levels.

Zwracane wartości

event_base_priority_init() returns TRUE on success or FALSE on error.

event_base_new
event_base_set
Libevent Funkcje


Associate event base with an event

event_base_priority_init
event_buffer_base_set
Libevent Funkcje
PHP Manual

event_base_set

(PECL libevent >= 0.0.1)

event_base_set — Associate event base with an event

Opis

bool event_base_set ( resource $event , resource $event_base )

Associates the event_base with the event.

Parametry

event

Valid event resource.

event_base

Valid event base resource.

Zwracane wartości

event_base_set() returns TRUE on success or FALSE on error.

event_base_priority_init
event_buffer_base_set
Libevent Funkcje


Associate buffered event with an event base

event_base_set
event_buffer_disable
Libevent Funkcje
PHP Manual

event_buffer_base_set

(PECL libevent >= 0.0.1)

event_buffer_base_set — Associate buffered event with an event base

Opis

bool event_buffer_base_set ( resource $bevent , resource $event_base )

Assign the specified bevent to the event_base.

Parametry

bevent

Valid buffered event resource.

event_base

Valid event base resource.

Zwracane wartości

event_buffer_base_set() returns TRUE on success or FALSE on error.

event_base_set
event_buffer_disable
Libevent Funkcje


Disable a buffered event

event_buffer_base_set
event_buffer_enable
Libevent Funkcje
PHP Manual

event_buffer_disable

(PECL libevent >= 0.0.1)

event_buffer_disable — Disable a buffered event

Opis

bool event_buffer_disable ( resource $bevent , int $events )

Disables the specified buffered event.

Parametry

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Zwracane wartości

event_buffer_disable() returns TRUE on success or FALSE on error.

event_buffer_base_set
event_buffer_enable
Libevent Funkcje


Enable a buffered event

event_buffer_disable
event_buffer_fd_set
Libevent Funkcje
PHP Manual

event_buffer_enable

(PECL libevent >= 0.0.1)

event_buffer_enable — Enable a buffered event

Opis

bool event_buffer_enable ( resource $bevent , int $events )

Enables the specified buffered event.

Parametry

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Zwracane wartości

event_buffer_enable() returns TRUE on success or FALSE on error.

event_buffer_disable
event_buffer_fd_set
Libevent Funkcje


Change a buffered event file descriptor

event_buffer_enable
event_buffer_free
Libevent Funkcje
PHP Manual

event_buffer_fd_set

(PECL libevent >= 0.0.1)

event_buffer_fd_set — Change a buffered event file descriptor

Opis

void event_buffer_fd_set ( resource $bevent , resource $fd )

Changes the file descriptor on which the buffered event operates.

Parametry

bevent

Valid buffered event resource.

fd

Valid PHP stream, must be castable to file descriptor.

event_buffer_enable
event_buffer_free
Libevent Funkcje


Destroy buffered event

event_buffer_fd_set
event_buffer_new
Libevent Funkcje
PHP Manual

event_buffer_free

(PECL libevent >= 0.0.1)

event_buffer_free — Destroy buffered event

Opis

void event_buffer_free ( resource $bevent )

Destroys the specified buffered event and frees all the resources associated.

Parametry

bevent

Valid buffered event resource.

event_buffer_fd_set
event_buffer_new
Libevent Funkcje


Create new buffered event

event_buffer_free
event_buffer_priority_set
Libevent Funkcje
PHP Manual

event_buffer_new

(PECL libevent >= 0.0.1)

event_buffer_new — Create new buffered event

Opis

resource event_buffer_new ( resource $stream , mixed $readcb , mixed $writecb , mixed $errorcb [, mixed $arg ] )

Libevent provides an abstraction layer on top of the regular event API. Using buffered event you don't need to deal with the I/O manually, instead it provides input and output buffers that get filled and drained automatically.

Parametry

stream

Valid PHP stream resource. Must be castable to file descriptor.

readcb

Callback to invoke where there is data to read, or NULL if no callback is desired.

writecb

Callback to invoke where the descriptor is ready for writing, or NULL if no callback is desired.

errorcb

Callback to invoke where there is an error on the descriptor, cannot be NULL.

arg

An argument that will be passed to each of the callbacks (optional).

Zwracane wartości

event_buffer_new() returns new buffered event resource on success or FALSE on error.

event_buffer_free
event_buffer_priority_set
Libevent Funkcje


Assign a priority to a buffered event

event_buffer_new
event_buffer_read
Libevent Funkcje
PHP Manual

event_buffer_priority_set

(PECL libevent >= 0.0.1)

event_buffer_priority_set — Assign a priority to a buffered event

Opis

bool event_buffer_priority_set ( resource $bevent , int $priority )

Assign a priority to the bevent.

Parametry

bevent

Valid buffered event resource.

priority

Priority level. Cannot be less than zero and cannot exceed maximum priority level of the event base (see event_base_priority_init()).

Zwracane wartości

event_buffer_priority_set() returns TRUE on success or FALSE on error.

event_buffer_new
event_buffer_read
Libevent Funkcje


Read data from a buffered event

event_buffer_priority_set
event_buffer_set_callback
Libevent Funkcje
PHP Manual

event_buffer_read

(PECL libevent >= 0.0.1)

event_buffer_read — Read data from a buffered event

Opis

string event_buffer_read ( resource $bevent , int $data_size )

Reads data from the input buffer of the buffered event.

Parametry

bevent

Valid buffered event resource.

data_size

Data size in bytes.

event_buffer_priority_set
event_buffer_set_callback
Libevent Funkcje


Set or reset callbacks for a buffered event

event_buffer_read
event_buffer_timeout_set
Libevent Funkcje
PHP Manual

event_buffer_set_callback

(PECL libevent >= 0.0.4)

event_buffer_set_callback — Set or reset callbacks for a buffered event

Opis

bool event_buffer_set_callback ( resource $event , mixed $readcb , mixed $writecb , mixed $errorcb [, mixed $arg ] )

Sets or changes existing callbacks for the buffered event.

Parametry

event

Valid buffered event resource.

readcb

Callback to invoke where there is data to read, or NULL if no callback is desired.

writecb

Callback to invoke where the descriptor is ready for writing, or NULL if no callback is desired.

errorcb

Callback to invoke where there is an error on the descriptor, cannot be NULL.

arg

An argument that will be passed to each of the callbacks (optional).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

event_buffer_read
event_buffer_timeout_set
Libevent Funkcje


Set read and write timeouts for a buffered event

event_buffer_set_callback
event_buffer_watermark_set
Libevent Funkcje
PHP Manual

event_buffer_timeout_set

(PECL libevent >= 0.0.1)

event_buffer_timeout_set — Set read and write timeouts for a buffered event

Opis

void event_buffer_timeout_set ( resource $bevent , int $read_timeout , int $write_timeout )

Sets the read and write timeouts for the specified buffered event.

Parametry

bevent

Valid buffered event resource.

read_timeout

Read timeout (in seconds).

write_timeout

Write timeout (in seconds).

event_buffer_set_callback
event_buffer_watermark_set
Libevent Funkcje


Set the watermarks for read and write events

event_buffer_timeout_set
event_buffer_write
Libevent Funkcje
PHP Manual

event_buffer_watermark_set

(PECL libevent >= 0.0.1)

event_buffer_watermark_set — Set the watermarks for read and write events

Opis

void event_buffer_watermark_set ( resource $bevent , int $events , int $lowmark , int $highmark )

Sets the watermarks for read and write events. Libevent does not invoke read callback unless there is at least lowmark bytes in the input buffer; if the read buffer is beyond the highmark, reading is stopped. On output, the write callback is invoked whenever the buffered data falls below the lowmark.

Parametry

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

lowmark

Low watermark.

highmark

High watermark.

event_buffer_timeout_set
event_buffer_write
Libevent Funkcje


Write data to a buffered event

event_buffer_watermark_set
event_del
Libevent Funkcje
PHP Manual

event_buffer_write

(PECL libevent >= 0.0.1)

event_buffer_write — Write data to a buffered event

Opis

bool event_buffer_write ( resource $bevent , string $data [, int $data_size = -1 ] )

Writes data to the specified buffered event. The data is appended to the output buffer and written to the descriptor when it becomes available for writing.

Parametry

bevent

Valid buffered event resource.

data

The data to be written.

data_size

Optional size parameter. event_buffer_write() writes all the data by default.

Zwracane wartości

event_buffer_write() returns TRUE on success or FALSE on error.

event_buffer_watermark_set
event_del
Libevent Funkcje


Remove an event from the set of monitored events

event_buffer_write
event_free
Libevent Funkcje
PHP Manual

event_del

(PECL libevent >= 0.0.1)

event_del — Remove an event from the set of monitored events

Opis

bool event_del ( resource $event )

Cancels the event.

Parametry

event

Valid event resource.

Zwracane wartości

event_del() returns TRUE on success or FALSE on error.

event_buffer_write
event_free
Libevent Funkcje


Free event resource

event_del
event_new
Libevent Funkcje
PHP Manual

event_free

(PECL libevent >= 0.0.1)

event_free — Free event resource

Opis

void event_free ( resource $event )

Frees previously created event resource.

Parametry

event

Valid event resource.

event_del
event_new
Libevent Funkcje


Create new event

event_free
event_set
Libevent Funkcje
PHP Manual

event_new

(PECL libevent >= 0.0.1)

event_new — Create new event

Opis

resource event_new ( void )

Creates and returns a new event resource.

Zwracane wartości

event_new() returns a new event resource on success or FALSE on error.

event_free
event_set
Libevent Funkcje


Prepare an event

event_new
PCNTL
Libevent Funkcje
PHP Manual

event_set

(PECL libevent >= 0.0.1)

event_set — Prepare an event

Opis

bool event_set ( resource $event , mixed $fd , int $events , mixed $callback [, mixed $arg ] )

Prepares the event to be used in event_add(). The event is prepared to call the function specified by the callback on the events specified in parameter events, which is a set of the following flags: EV_TIMEOUT, EV_SIGNAL, EV_READ, EV_WRITE and EV_PERSIST.

If EV_SIGNAL bit is set in parameter events, the fd is interpreted as signal number.

After initializing the event, use event_base_set() to associate the event with its event base.

In case of matching event, these three arguments are passed to the callback function:

fd

Signal number or resource indicating the stream.

events

A flag indicating the event. Consists of the following flags: EV_TIMEOUT, EV_SIGNAL, EV_READ, EV_WRITE and EV_PERSIST.

arg

Optional parameter, previously passed to event_set() as arg.

Parametry

event

Valid event resource.

fd

Valid PHP stream resource. The stream must be castable to file descriptor, so you most likely won't be able to use any of filtered streams.

events

A set of flags indicating the desired event, can be EV_READ and/or EV_WRITE. The additional flag EV_PERSIST makes the event to persist until event_del() is called, otherwise the callback is invoked only once.

callback

Callback function to be called when the matching event occurs.

arg

Optional callback parameter.

Zwracane wartości

event_set() returns TRUE on success or FALSE on error.

Rejestr zmian

Wersja | Opis
0.0.4 | EV_SIGNAL support was added.
event_new
PCNTL
Libevent Funkcje


Process Control

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • PCNTL Funkcje
    • pcntl_alarm — Set an alarm clock for delivery of a signal
    • pcntl_exec — Executes specified program in current process space
    • pcntl_fork — Forks the currently running process
    • pcntl_getpriority — Get the priority of any process
    • pcntl_setpriority — Change the priority of any process
    • pcntl_signal_dispatch — Calls signal handlers for pending signals
    • pcntl_signal — Installs a signal handler
    • pcntl_sigprocmask — Sets and retrieves blocked signals
    • pcntl_sigtimedwait — Waits for signals, with a timeout
    • pcntl_sigwaitinfo — Waits for signals
    • pcntl_wait — Waits on or returns the status of a forked child
    • pcntl_waitpid — Waits on or returns the status of a forked child
    • pcntl_wexitstatus — Returns the return code of a terminated child
    • pcntl_wifexited — Checks if status code represents a normal exit
    • pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal
    • pcntl_wifstopped — Checks whether the child process is currently stopped
    • pcntl_wstopsig — Returns the signal which caused the child to stop
    • pcntl_wtermsig — Returns the signal which caused the child to terminate
event_set
Wstęp
Rozszerzenia kontroli procesów


Wstęp

Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).

PCNTL now uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You use the declare() statement to specify the locations in your program where callbacks are allowed to occur. This allows you to minimize the overhead of handling asynchronous events. In the past, compiling PHP with pcntl enabled would always incur this overhead, whether or not your script actually used pcntl.

There is one adjustment that all pcntl scripts prior to PHP 4.3.0 must make for them to work which is to either to use declare() on a section where you wish to allow callbacks or to just enable it across the entire script using the new global syntax of declare().

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

PCNTL
Instalacja/Konfiguracja
PCNTL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
PCNTL


Instalacja

Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with --enable-pcntl configuration option when compiling PHP to enable Process Control support.

Informacja:

Currently, this module will not function on non-Unix platforms (Windows).

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.

WNOHANG (integer)
WUNTRACED (integer)
SIG_IGN (integer)
SIG_DFL (integer)
SIG_ERR (integer)
SIGHUP (integer)
SIGINT (integer)
SIGQUIT (integer)
SIGILL (integer)
SIGTRAP (integer)
SIGABRT (integer)
SIGIOT (integer)
SIGBUS (integer)
SIGFPE (integer)
SIGKILL (integer)
SIGUSR1 (integer)
SIGSEGV (integer)
SIGUSR2 (integer)
SIGPIPE (integer)
SIGALRM (integer)
SIGTERM (integer)
SIGSTKFLT (integer)
SIGCLD (integer)
SIGCHLD (integer)
SIGCONT (integer)
SIGSTOP (integer)
SIGTSTP (integer)
SIGTTIN (integer)
SIGTTOU (integer)
SIGURG (integer)
SIGXCPU (integer)
SIGXFSZ (integer)
SIGVTALRM (integer)
SIGPROF (integer)
SIGWINCH (integer)
SIGPOLL (integer)
SIGIO (integer)
SIGPWR (integer)
SIGSYS (integer)
SIGBABY (integer)
SIG_BLOCK (integer)
Available since PHP 5.3.0.
SIG_UNBLOCK (integer)
Available since PHP 5.3.0.
SIG_SETMASK (integer)
Available since PHP 5.3.0.
SI_USER (integer)
Available since PHP 5.3.0.
SI_NOINFO (integer)
Available since PHP 5.3.0.
SI_KERNEL (integer)
Available since PHP 5.3.0.
SI_QUEUE (integer)
Available since PHP 5.3.0.
SI_TIMER (integer)
Available since PHP 5.3.0.
SI_MSGGQ (integer)
Available since PHP 5.3.0.
SI_ASYNCIO (integer)
Available since PHP 5.3.0.
SI_SIGIO (integer)
Available since PHP 5.3.0.
SI_TKILL (integer)
Available since PHP 5.3.0.
CLD_EXITED (integer)
Available since PHP 5.3.0.
CLD_KILLED (integer)
Available since PHP 5.3.0.
CLD_DUMPED (integer)
Available since PHP 5.3.0.
CLD_TRAPPED (integer)
Available since PHP 5.3.0.
CLD_STOPPED (integer)
Available since PHP 5.3.0.
CLD_CONTINUED (integer)
Available since PHP 5.3.0.
TRAP_BRKPT (integer)
Available since PHP 5.3.0.
TRAP_TRACE (integer)
Available since PHP 5.3.0.
POLL_IN (integer)
Available since PHP 5.3.0.
POLL_OUT (integer)
Available since PHP 5.3.0.
POLL_MSG (integer)
Available since PHP 5.3.0.
POLL_ERR (integer)
Available since PHP 5.3.0.
POLL_PRI (integer)
Available since PHP 5.3.0.
POLL_HUP (integer)
Available since PHP 5.3.0.
ILL_ILLOPC (integer)
Available since PHP 5.3.0.
ILL_ILLOPN (integer)
Available since PHP 5.3.0.
ILL_ILLADR (integer)
Available since PHP 5.3.0.
ILL_ILLTRP (integer)
Available since PHP 5.3.0.
ILL_PRVOPC (integer)
Available since PHP 5.3.0.
ILL_PRVREG (integer)
Available since PHP 5.3.0.
ILL_COPROC (integer)
Available since PHP 5.3.0.
ILL_BADSTK (integer)
Available since PHP 5.3.0.
FPE_INTDIV (integer)
Available since PHP 5.3.0.
FPE_INTOVF (integer)
Available since PHP 5.3.0.
FPE_FLTDIV (integer)
Available since PHP 5.3.0.
FPE_FLTOVF (integer)
Available since PHP 5.3.0.
FPE_FLTUND (integer)
Available since PHP 5.3.0.
FPE_FLTRES (integer)
Available since PHP 5.3.0.
FPE_FLTINV (integer)
Available since PHP 5.3.0.
FPE_FLTSUB (integer)
Available since PHP 5.3.0.
SEGV_MAPERR (integer)
Available since PHP 5.3.0.
SEGV_ACCERR (integer)
Available since PHP 5.3.0.
BUS_ADRALN (integer)
Available since PHP 5.3.0.
BUS_ADRERR (integer)
Available since PHP 5.3.0.
BUS_OBJERR (integer)
Available since PHP 5.3.0.
Typy zasobów
Przykłady
PCNTL


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
PCNTL


Basic usage

This example forks off a daemon process with a signal handler.

Przykład #1 Process Control Example

<?php
declare(ticks=1);

$pid = pcntl_fork();
if ($pid == -1) {
     die("could not fork");
} else if ($pid) {
     exit(); // we are the parent
} else {
     // we are the child
}

// detatch from the controlling terminal
if (posix_setsid() == -1) {
    die("could not detach from terminal");
}

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// loop forever performing tasks
while (1) {

    // do something interesting here

}

function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         default:
             // handle all other signals
     }

}

?>
Przykłady
PCNTL Funkcje
Przykłady


PCNTL Funkcje

Zobacz też:

A look at the section about POSIX functions may be useful.

Spis treści

  • pcntl_alarm — Set an alarm clock for delivery of a signal
  • pcntl_exec — Executes specified program in current process space
  • pcntl_fork — Forks the currently running process
  • pcntl_getpriority — Get the priority of any process
  • pcntl_setpriority — Change the priority of any process
  • pcntl_signal_dispatch — Calls signal handlers for pending signals
  • pcntl_signal — Installs a signal handler
  • pcntl_sigprocmask — Sets and retrieves blocked signals
  • pcntl_sigtimedwait — Waits for signals, with a timeout
  • pcntl_sigwaitinfo — Waits for signals
  • pcntl_wait — Waits on or returns the status of a forked child
  • pcntl_waitpid — Waits on or returns the status of a forked child
  • pcntl_wexitstatus — Returns the return code of a terminated child
  • pcntl_wifexited — Checks if status code represents a normal exit
  • pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal
  • pcntl_wifstopped — Checks whether the child process is currently stopped
  • pcntl_wstopsig — Returns the signal which caused the child to stop
  • pcntl_wtermsig — Returns the signal which caused the child to terminate
Basic usage
pcntl_alarm
PCNTL


Set an alarm clock for delivery of a signal

PCNTL Funkcje
pcntl_exec
PCNTL Funkcje
PHP Manual

pcntl_alarm

(PHP 4 >= 4.3.0, PHP 5)

pcntl_alarm — Set an alarm clock for delivery of a signal

Opis

int pcntl_alarm ( int $seconds )

Creates a timer that will send a SIGALRM signal to the process after the given number of seconds. Any call to pcntl_alarm() will cancel any previously set alarm.

Parametry

seconds

The number of seconds to wait. If seconds is zero, no new alarm is created.

Zwracane wartości

Returns the time in seconds that any previously scheduled alarm had remaining before it was to be delivered, or 0 if there was no previously scheduled alarm.

PCNTL Funkcje
pcntl_exec
PCNTL Funkcje


Executes specified program in current process space

pcntl_alarm
pcntl_fork
PCNTL Funkcje
PHP Manual

pcntl_exec

(PHP 4 >= 4.2.0, PHP 5)

pcntl_exec — Executes specified program in current process space

Opis

void pcntl_exec ( string $path [, array $args [, array $envs ]] )

Executes the program with the given arguments.

Parametry

path

path must be the path to a binary executable or a script with a valid path pointing to an executable in the shebang ( #!/usr/local/bin/perl for example) as the first line. See your system's man execve(2) page for additional information.

args

args is an array of argument strings passed to the program.

envs

envs is an array of strings which are passed as environment to the program. The array is in the format of name => value, the key being the name of the environmental variable and the value being the value of that variable.

Zwracane wartości

Returns FALSE on error and does not return on success.

pcntl_alarm
pcntl_fork
PCNTL Funkcje


Forks the currently running process

pcntl_exec
pcntl_getpriority
PCNTL Funkcje
PHP Manual

pcntl_fork

(PHP 4 >= 4.1.0, PHP 5)

pcntl_fork — Forks the currently running process

Opis

int pcntl_fork ( void )

The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.

Zwracane wartości

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.

Przykłady

Przykład #1 pcntl_fork() example

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
}

?>

Zobacz też:

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler
  • setproctitle() - Set the process title

pcntl_exec
pcntl_getpriority
PCNTL Funkcje


Get the priority of any process

pcntl_fork
pcntl_setpriority
PCNTL Funkcje
PHP Manual

pcntl_getpriority

(PHP 5)

pcntl_getpriority — Get the priority of any process

Opis

int pcntl_getpriority ([ int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] )

pcntl_getpriority() gets the priority of pid. Because priority levels can differ between system types and kernel versions, please see your system's getpriority(2) man page for specific details.

Parametry

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Zwracane wartości

pcntl_getpriority() returns the priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Zobacz też:

  • pcntl_setpriority() - Change the priority of any process

pcntl_fork
pcntl_setpriority
PCNTL Funkcje


Change the priority of any process

pcntl_getpriority
pcntl_signal_dispatch
PCNTL Funkcje
PHP Manual

pcntl_setpriority

(PHP 5)

pcntl_setpriority — Change the priority of any process

Opis

bool pcntl_setpriority ( int $priority [, int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] )

pcntl_setpriority() sets the priority of pid.

Parametry

priority

priority is generally a value in the range -20 to 20. The default priority is 0 while a lower numerical value causes more favorable scheduling. Because priority levels can differ between system types and kernel versions, please see your system's setpriority(2) man page for specific details.

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • pcntl_getpriority() - Get the priority of any process

pcntl_getpriority
pcntl_signal_dispatch
PCNTL Funkcje


Calls signal handlers for pending signals

pcntl_setpriority
pcntl_signal
PCNTL Funkcje
PHP Manual

pcntl_signal_dispatch

(PHP 5 >= 5.3.0)

pcntl_signal_dispatch — Calls signal handlers for pending signals

Opis

bool pcntl_signal_dispatch ( void )

The pcntl_signal_dispatch() function calls the signal handlers installed by pcntl_signal() for each pending signal.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pcntl_signal_dispatch() example

<?php
echo "Installing signal handler...\n";
pcntl_signal(SIGHUP,  function($signo) {
     echo "signal handler called\n";
});

echo "Generating signal SIGHUP to self...\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Dispatching...\n";
pcntl_signal_dispatch();

echo "Done\n";

?>

Powyższy przykład wyświetli coś podobnego do:

Installing signal handler...
Generating signal SIGHUP to self...
Dispatching...
signal handler called
Done

Zobacz też:

  • pcntl_signal() - Installs a signal handler
  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

pcntl_setpriority
pcntl_signal
PCNTL Funkcje


Installs a signal handler

pcntl_signal_dispatch
pcntl_sigprocmask
PCNTL Funkcje
PHP Manual

pcntl_signal

(PHP 4 >= 4.1.0, PHP 5)

pcntl_signal — Installs a signal handler

Opis

bool pcntl_signal ( int $signo , callback $handler [, bool $restart_syscalls = true ] )

The pcntl_signal() function installs a new signal handler for the signal indicated by signo.

Parametry

signo

The signal number.

handler

The signal handler which may be the name of a user created function, or method, or either of the two global constants SIG_IGN or SIG_DFL.

Informacja:

Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends.

restart_syscalls

Specifies whether system call restarting should be used when this signal arrives.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
4.3.0 | The restart_syscalls parameter was added.
4.3.0 | The ability to use an object method as a callback became available.
4.3.0 | As of PHP 4.3.0 PCNTL uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly (as used in the above example).

Przykłady

Przykład #1 pcntl_signal() example

<?php
// tick use required as of PHP 4.3.0
declare(ticks = 1);

// signal handler function
function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             echo "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

echo "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// or use an object, available as of PHP 4.3.0
// pcntl_signal(SIGUSR1, array($obj, "do_something");

echo"Generating signal SIGTERM to self...\n";

// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n";

?>

Zobacz też:

  • pcntl_fork() - Forks the currently running process
  • pcntl_waitpid() - Waits on or returns the status of a forked child

pcntl_signal_dispatch
pcntl_sigprocmask
PCNTL Funkcje


Sets and retrieves blocked signals

pcntl_signal
pcntl_sigtimedwait
PCNTL Funkcje
PHP Manual

pcntl_sigprocmask

(PHP 5 >= 5.3.0)

pcntl_sigprocmask — Sets and retrieves blocked signals

Opis

bool pcntl_sigprocmask ( int $how , array $set [, array &$oldset ] )

The pcntl_sigprocmask() function adds, removes or sets blocked signals, depending on the how parameter.

Parametry

how

Sets the behavior of pcntl_sigprocmask(). Possible values:

  • SIG_BLOCK: Add the signals to the currently blocked signals.
  • SIG_UNBLOCK: Remove the signals from the currently blocked signals.
  • SIG_SETMASK: Replace the currently blocked signals by the given list of signals.

set

List of signals.

oldset

The oldset parameter is set to an array containing the list of the previously blocked signals.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 pcntl_sigprocmask() example

<?php
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));
$oldset = array();
pcntl_sigprocmask(SIG_UNBLOCK, array(SIGHUP), $oldset);
?>

Zobacz też:

  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

pcntl_signal
pcntl_sigtimedwait
PCNTL Funkcje


Waits for signals, with a timeout

pcntl_sigprocmask
pcntl_sigwaitinfo
PCNTL Funkcje
PHP Manual

pcntl_sigtimedwait

(PHP 5 >= 5.3.0)

pcntl_sigtimedwait — Waits for signals, with a timeout

Opis

int pcntl_sigtimedwait ( array $set [, array &$siginfo [, int $seconds = 0 [, int $nanoseconds = 0 ]]] )

The pcntl_sigtimedwait() function operates in exactly the same way as pcntl_sigwaitinfo() except that it takes two additional parameters, seconds and nanoseconds, which enable an upper bound to be placed on the time for which the script is suspended.

Parametry

set

Array of signals to wait for.

siginfo

The siginfo is set to an array containing informations about the signal. See pcntl_sigwaitinfo().

seconds

Timeout in seconds.

nanoseconds

Timeout in nanoseconds.

Zwracane wartości

On success, pcntl_sigtimedwait() returns a signal number.

Zobacz też:

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals

pcntl_sigprocmask
pcntl_sigwaitinfo
PCNTL Funkcje


Waits for signals

pcntl_sigtimedwait
pcntl_wait
PCNTL Funkcje
PHP Manual

pcntl_sigwaitinfo

(PHP 5 >= 5.3.0)

pcntl_sigwaitinfo — Waits for signals

Opis

int pcntl_sigwaitinfo ( array $set [, array &$siginfo ] )

The pcntl_sigwaitinfo() function suspends execution of the calling script until one of the signals given in set are delivered. If one of the signal is already pending (e.g. blocked by pcntl_sigprocmask()), pcntl_sigwaitinfo() will return immediately.

Parametry

set

Array of signals to wait for.

siginfo

The siginfo parameter is set to an array containing informations about the signal.

The following elements are set for all signals:

  • signo: Signal number
  • errno: An error number
  • code: Signal code

The following elements may be set for the SIGCHLD signal:

  • status: Exit value or signal
  • utime: User time consumed
  • stime: System time consumed
  • pid: Sending process ID
  • uid: Real user ID of sending process

The following elements may be set for the SIGILL, SIGFPE, SIGSEGV and SIGBUS signals:

  • addr: Memory location which caused fault

The following element may be set for the SIGPOLL signal:

  • band: Band event
  • fd: File descriptor number

Zwracane wartości

On success, pcntl_sigwaitinfo() returns a signal number.

Przykłady

Przykład #1 pcntl_sigwaitinfo() example

<?php
echo "Blocking SIGHUP signal\n";
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));

echo "Sending SIGHUP to self\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Waiting for signals\n";
$info = array();
pcntl_sigwaitinfo(array(SIGHUP), $info);
?>

Zobacz też:

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout

pcntl_sigtimedwait
pcntl_wait
PCNTL Funkcje


Waits on or returns the status of a forked child

pcntl_sigwaitinfo
pcntl_waitpid
PCNTL Funkcje
PHP Manual

pcntl_wait

(PHP 5)

pcntl_wait — Waits on or returns the status of a forked child

Opis

int pcntl_wait ( int &$status [, int $options = 0 ] )

The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's wait(2) man page for specific details as to how wait works on your system.

Informacja:

This function is equivalent to calling pcntl_waitpid() with a -1 pid and no options.

Parametry

status

pcntl_wait() will store status information
in the status parameter which can be
evaluated using the following functions:
pcntl_wifexited(),
pcntl_wifstopped(),
pcntl_wifsignaled(),
pcntl_wexitstatus(),
pcntl_wtermsig() and
pcntl_wstopsig().

options

If wait3 is available on your system (mostly BSD-style systems), you can provide the optional options parameter. If this parameter is not provided, wait will be used for the system call. If wait3 is not available, providing a value for options will have no effect. The value of options is the value of zero or more of the following two constants OR'ed together:

Possible values for options
WNOHANG | Return immediately if no child has exited.
WUNTRACED | Return for children which are stopped, and whose status has not been reported.

Zwracane wartości

pcntl_wait() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was provided as an option (on wait3-available systems) and no child was available.

Zobacz też:

  • pcntl_fork() - Forks the currently running process
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifexited() - Checks if status code represents a normal exit
  • pcntl_wifstopped() - Checks whether the child process is currently stopped
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal
  • pcntl_wexitstatus() - Returns the return code of a terminated child
  • pcntl_wtermsig() - Returns the signal which caused the child to terminate
  • pcntl_wstopsig() - Returns the signal which caused the child to stop
  • pcntl_waitpid() - Waits on or returns the status of a forked child

pcntl_sigwaitinfo
pcntl_waitpid
PCNTL Funkcje


Waits on or returns the status of a forked child

pcntl_wait
pcntl_wexitstatus
PCNTL Funkcje
PHP Manual

pcntl_waitpid

(PHP 4 >= 4.1.0, PHP 5)

pcntl_waitpid — Waits on or returns the status of a forked child

Opis

int pcntl_waitpid ( int $pid , int &$status [, int $options = 0 ] )

Suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function.

If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.

Parametry

pid

The value of pid can be one of the following:

possible values for pid
< -1 | wait for any child process whose process group ID is equal to the absolute value of pid.
-1 | wait for any child process; this is the same behaviour that the wait function exhibits.
0 | wait for any child process whose process group ID is equal to that of the calling process.
> 0 | wait for the child whose process ID is equal to the value of pid.

Informacja:

Specifying -1 as the pid is equivalent to the functionality pcntl_wait() provides (minus options).

status

pcntl_waitpid() will store status information
in the status parameter which can be
evaluated using the following functions:
pcntl_wifexited(),
pcntl_wifstopped(),
pcntl_wifsignaled(),
pcntl_wexitstatus(),
pcntl_wtermsig() and
pcntl_wstopsig().

options

The value of options is the value of zero or more of the following two global constants OR'ed together:

possible values for options
WNOHANG | return immediately if no child has exited.
WUNTRACED | return for children which are stopped, and whose status has not been reported.

Zwracane wartości

pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available

Zobacz też:

  • pcntl_fork() - Forks the currently running process
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifexited() - Checks if status code represents a normal exit
  • pcntl_wifstopped() - Checks whether the child process is currently stopped
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal
  • pcntl_wexitstatus() - Returns the return code of a terminated child
  • pcntl_wtermsig() - Returns the signal which caused the child to terminate
  • pcntl_wstopsig() - Returns the signal which caused the child to stop

pcntl_wait
pcntl_wexitstatus
PCNTL Funkcje


Returns the return code of a terminated child

pcntl_waitpid
pcntl_wifexited
PCNTL Funkcje
PHP Manual

pcntl_wexitstatus

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wexitstatus — Returns the return code of a terminated child

Opis

int pcntl_wexitstatus ( int $status )

Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.

Parametry

status

status jest parametrem podawanym do prawidłowego wywołania funkcji pcntl_waitpid().

Zwracane wartości

Returns the return code, as an integer.

Zobacz też:

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wifexited() - Checks if status code represents a normal exit

pcntl_waitpid
pcntl_wifexited
PCNTL Funkcje


Checks if status code represents a normal exit

pcntl_wexitstatus
pcntl_wifsignaled
PCNTL Funkcje
PHP Manual

pcntl_wifexited

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifexited — Checks if status code represents a normal exit

Opis

bool pcntl_wifexited ( int $status )

Checks whether the child status code represents a normal exit.

Parametry

status

status jest parametrem podawanym do prawidłowego wywołania funkcji pcntl_waitpid().

Zwracane wartości

Returns TRUE if the child status code represents a normal exit, FALSE otherwise.

Zobacz też:

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wexitstatus() - Returns the return code of a terminated child

pcntl_wexitstatus
pcntl_wifsignaled
PCNTL Funkcje


Checks whether the status code represents a termination due to a signal

pcntl_wifexited
pcntl_wifstopped
PCNTL Funkcje
PHP Manual

pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal

Opis

bool pcntl_wifsignaled ( int $status )

Checks whether the child process exited because of a signal which was not caught.

Parametry

status

status jest parametrem podawanym do prawidłowego wywołania funkcji pcntl_waitpid().

Zwracane wartości

Returns TRUE if the child process exited because of a signal which was not caught, FALSE otherwise.

Zobacz też:

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler

pcntl_wifexited
pcntl_wifstopped
PCNTL Funkcje


Checks whether the child process is currently stopped

pcntl_wifsignaled
pcntl_wstopsig
PCNTL Funkcje
PHP Manual

pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wifstopped — Checks whether the child process is currently stopped

Opis

bool pcntl_wifstopped ( int $status )

Checks whether the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.

Parametry

status

status jest parametrem podawanym do prawidłowego wywołania funkcji pcntl_waitpid().

Zwracane wartości

Returns TRUE if the child process which caused the return is currently stopped, FALSE otherwise.

Zobacz też:

  • pcntl_waitpid() - Waits on or returns the status of a forked child

pcntl_wifsignaled
pcntl_wstopsig
PCNTL Funkcje


Returns the signal which caused the child to stop

pcntl_wifstopped
pcntl_wtermsig
PCNTL Funkcje
PHP Manual

pcntl_wstopsig

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wstopsig — Returns the signal which caused the child to stop

Opis

int pcntl_wstopsig ( int $status )

Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.

Parametry

status

status jest parametrem podawanym do prawidłowego wywołania funkcji pcntl_waitpid().

Zwracane wartości

Returns the signal number.

Zobacz też:

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wifstopped() - Checks whether the child process is currently stopped

pcntl_wifstopped
pcntl_wtermsig
PCNTL Funkcje


Returns the signal which caused the child to terminate

pcntl_wstopsig
POSIX
PCNTL Funkcje
PHP Manual

pcntl_wtermsig

(PHP 4 >= 4.1.0, PHP 5)

pcntl_wtermsig — Returns the signal which caused the child to terminate

Opis

int pcntl_wtermsig ( int $status )

Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.

Parametry

status

status jest parametrem podawanym do prawidłowego wywołania funkcji pcntl_waitpid().

Zwracane wartości

Returns the signal number, as an integer.

Zobacz też:

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal

pcntl_wstopsig
POSIX
PCNTL Funkcje


POSIX

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • POSIX Funkcje
    • posix_access — Determine accessibility of a file
    • posix_ctermid — Get path name of controlling terminal
    • posix_errno — Alias dla posix_get_last_error
    • posix_get_last_error — Retrieve the error number set by the last posix function that failed
    • posix_getcwd — Pathname of current directory
    • posix_getegid — Return the effective group ID of the current process
    • posix_geteuid — Return the effective user ID of the current process
    • posix_getgid — Return the real group ID of the current process
    • posix_getgrgid — Return info about a group by group id
    • posix_getgrnam — Return info about a group by name
    • posix_getgroups — Return the group set of the current process
    • posix_getlogin — Return login name
    • posix_getpgid — Get process group id for job control
    • posix_getpgrp — Return the current process group identifier
    • posix_getpid — Return the current process identifier
    • posix_getppid — Return the parent process identifier
    • posix_getpwnam — Return info about a user by username
    • posix_getpwuid — Return info about a user by user id
    • posix_getrlimit — Return info about system resource limits
    • posix_getsid — Get the current sid of the process
    • posix_getuid — Return the real user ID of the current process
    • posix_initgroups — Calculate the group access list
    • posix_isatty — Determine if a file descriptor is an interactive terminal
    • posix_kill — Send a signal to a process
    • posix_mkfifo — Create a fifo special file (a named pipe)
    • posix_mknod — Create a special or ordinary file (POSIX.1)
    • posix_setegid — Set the effective GID of the current process
    • posix_seteuid — Set the effective UID of the current process
    • posix_setgid — Set the GID of the current process
    • posix_setpgid — Set process group id for job control
    • posix_setsid — Make the current process a session leader
    • posix_setuid — Set the UID of the current process
    • posix_strerror — Retrieve the system error message associated with the given errno
    • posix_times — Get process times
    • posix_ttyname — Determine terminal device name
    • posix_uname — Get system name
pcntl_wtermsig
Wstęp
Rozszerzenia kontroli procesów


Wstęp

This module contains an interface to those functions defined in the IEEE 1003.1 (POSIX.1) standards document which are not accessible through other means.

Ostrzeżenie

Sensitive data can be retrieved with the POSIX functions, e.g. posix_getpwnam() and friends. None of the POSIX function perform any kind of access checking when safe mode is enabled. It's therefore strongly advised to disable the POSIX extension at all (use --disable-posix in your configure line) if you're operating in such an environment.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

POSIX
Instalacja/Konfiguracja
POSIX


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
POSIX


Instalacja

POSIX functions are enabled by default. You can disable POSIX-like functions with --disable-posix .

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

POSIX_F_OK (integer)
Check whether the file exists.
POSIX_R_OK (integer)
Check whether the file exists and has read permissions.
POSIX_W_OK (integer)
Check whether the file exists and has write permissions.
POSIX_X_OK (integer)
Check whether the file exists and has execute permissions.
POSIX_S_IFBLK (integer)
Block special file
POSIX_S_IFCHR (integer)
Character special file
POSIX_S_IFIFO (integer)
FIFO (named pipe) special file
POSIX_S_IFREG (integer)
Normal file
POSIX_S_IFSOCK (integer)
Socket

Informacja:

These constants are available since PHP 5.1.0. Please also note that some of them may not be available in your system.

Typy zasobów
POSIX Funkcje
POSIX


POSIX Funkcje

Zobacz też:

The section about Process Control Functions maybe of interest for you.

Spis treści

  • posix_access — Determine accessibility of a file
  • posix_ctermid — Get path name of controlling terminal
  • posix_errno — Alias dla posix_get_last_error
  • posix_get_last_error — Retrieve the error number set by the last posix function that failed
  • posix_getcwd — Pathname of current directory
  • posix_getegid — Return the effective group ID of the current process
  • posix_geteuid — Return the effective user ID of the current process
  • posix_getgid — Return the real group ID of the current process
  • posix_getgrgid — Return info about a group by group id
  • posix_getgrnam — Return info about a group by name
  • posix_getgroups — Return the group set of the current process
  • posix_getlogin — Return login name
  • posix_getpgid — Get process group id for job control
  • posix_getpgrp — Return the current process group identifier
  • posix_getpid — Return the current process identifier
  • posix_getppid — Return the parent process identifier
  • posix_getpwnam — Return info about a user by username
  • posix_getpwuid — Return info about a user by user id
  • posix_getrlimit — Return info about system resource limits
  • posix_getsid — Get the current sid of the process
  • posix_getuid — Return the real user ID of the current process
  • posix_initgroups — Calculate the group access list
  • posix_isatty — Determine if a file descriptor is an interactive terminal
  • posix_kill — Send a signal to a process
  • posix_mkfifo — Create a fifo special file (a named pipe)
  • posix_mknod — Create a special or ordinary file (POSIX.1)
  • posix_setegid — Set the effective GID of the current process
  • posix_seteuid — Set the effective UID of the current process
  • posix_setgid — Set the GID of the current process
  • posix_setpgid — Set process group id for job control
  • posix_setsid — Make the current process a session leader
  • posix_setuid — Set the UID of the current process
  • posix_strerror — Retrieve the system error message associated with the given errno
  • posix_times — Get process times
  • posix_ttyname — Determine terminal device name
  • posix_uname — Get system name
Stałe predefiniowane
posix_access
POSIX


Determine accessibility of a file

POSIX Funkcje
posix_ctermid
POSIX Funkcje
PHP Manual

posix_access

(PHP 5 >= 5.1.0)

posix_access — Determine accessibility of a file

Opis

bool posix_access ( string $file [, int $mode = POSIX_F_OK ] )

posix_access() checks the user's permission of a file.

Parametry

file

The name of the file to be tested.

mode

A mask consisting of one or more of POSIX_F_OK, POSIX_R_OK, POSIX_W_OK and POSIX_X_OK.

POSIX_R_OK, POSIX_W_OK and POSIX_X_OK request checking whether the file exists and has read, write and execute permissions, respectively. POSIX_F_OK just requests checking for the existence of the file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 posix_access() example

This example will check if the $file is readable and writable, otherwise will print an error message.

<?php

$file = 'some_file';

if (posix_access($file, POSIX_R_OK | POSIX_W_OK)) {
    echo 'The file is readable and writable!';

} else {
    $error = posix_get_last_error();

    echo "Error $error: " . posix_strerror($error);
}

?>

Notatki

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

Zobacz też:

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed
  • posix_strerror() - Retrieve the system error message associated with the given errno

POSIX Funkcje
posix_ctermid
POSIX Funkcje


Get path name of controlling terminal

posix_access
posix_errno
POSIX Funkcje
PHP Manual

posix_ctermid

(PHP 4, PHP 5)

posix_ctermid — Get path name of controlling terminal

Opis

string posix_ctermid ( void )

Generates a string which is the pathname for the current controlling terminal for the process. On error this will set errno, which can be checked using posix_get_last_error()

Zwracane wartości

Upon successful completion, returns string of the pathname to the current controlling terminal. Otherwise FALSE is returned and errno is set, which can be checked with posix_get_last_error().

Przykłady

Przykład #1 posix_ctermid() example

This example will display the path to the current TTY.

<?php
echo "I am running from ".posix_ctermid();
?>

Zobacz też:

  • posix_ttyname() - Determine terminal device name
  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

posix_access
posix_errno
POSIX Funkcje


Alias dla posix_get_last_error

posix_ctermid
posix_get_last_error
POSIX Funkcje
PHP Manual

posix_errno

(PHP 4 >= 4.2.0, PHP 5)

posix_errno — Alias dla posix_get_last_error()

Opis

Ta funkcja jest aliasem dla: posix_get_last_error().

posix_ctermid
posix_get_last_error
POSIX Funkcje


Retrieve the error number set by the last posix function that failed

posix_errno
posix_getcwd
POSIX Funkcje
PHP Manual

posix_get_last_error

(PHP 4 >= 4.2.0, PHP 5)

posix_get_last_error — Retrieve the error number set by the last posix function that failed

Opis

int posix_get_last_error ( void )

Retrieve the error number set by the last posix function that failed. The system error message associated with the errno may be checked with posix_strerror().

Zwracane wartości

Returns the errno (error number) set by the last posix function that failed. If no errors exist, 0 is returned.

Przykłady

Przykład #1 posix_get_last_error() example

This example attempt to kill a bogus process id, which will set the last error. We will then print out the last errno.

<?php
posix_kill(999459,SIGKILL);
echo 'Your error returned was '.posix_get_last_error(); //Your error was ___
?>

Zobacz też:

  • posix_strerror() - Retrieve the system error message associated with the given errno

posix_errno
posix_getcwd
POSIX Funkcje


Pathname of current directory

posix_get_last_error
posix_getegid
POSIX Funkcje
PHP Manual

posix_getcwd

(PHP 4, PHP 5)

posix_getcwd — Pathname of current directory

Opis

string posix_getcwd ( void )

Gets the absolute pathname of the script's current working directory. On error, it sets errno which can be checked using posix_get_last_error()

Zwracane wartości

Returns a string of the absolute pathname on success. On error, returns FALSE and sets errno which can be checked with posix_get_last_error().

Przykłady

Przykład #1 posix_getcwd() example

This example will return the absolute path of the current working directory of the script.

<?php
echo 'My current working directory is '.posix_getcwd();
?>

Notatki

Informacja:

This function can fail on

  • Read or Search permission was denied
  • Pathname no longer exists

posix_get_last_error
posix_getegid
POSIX Funkcje


Return the effective group ID of the current process

posix_getcwd
posix_geteuid
POSIX Funkcje
PHP Manual

posix_getegid

(PHP 4, PHP 5)

posix_getegid — Return the effective group ID of the current process

Opis

int posix_getegid ( void )

Return the numeric effective group ID of the current process.

Zwracane wartości

Returns an integer of the effective group ID.

Przykłady

Przykład #1 posix_getegid() example

This example will print out the effective group id, once it is changed with posix_setegid().

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

Notatki

posix_getegid() is different than posix_getgid() because effective group ID can be changed by a calling process using posix_setegid().

Zobacz też:

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process

posix_getcwd
posix_geteuid
POSIX Funkcje


Return the effective user ID of the current process

posix_getegid
posix_getgid
POSIX Funkcje
PHP Manual

posix_geteuid

(PHP 4, PHP 5)

posix_geteuid — Return the effective user ID of the current process

Opis

int posix_geteuid ( void )

Return the numeric effective user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

Zwracane wartości

Returns the user id, as an integer

Przykłady

Przykład #1 posix_geteuid() example

This example will show the current user id then set the effective user id to a separate id using posix_seteuid(), then show the difference between the real id and the effective id.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_seteuid(10000);
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10000
?>

Zobacz też:

  • posix_getpwuid() - Return info about a user by user id
  • posix_getuid() - Return the real user ID of the current process
  • posix_setuid() - Set the UID of the current process
  • POSIX man page GETEUID(2)

posix_getegid
posix_getgid
POSIX Funkcje


Return the real group ID of the current process

posix_geteuid
posix_getgrgid
POSIX Funkcje
PHP Manual

posix_getgid

(PHP 4, PHP 5)

posix_getgid — Return the real group ID of the current process

Opis

int posix_getgid ( void )

Return the numeric real group ID of the current process.

Zwracane wartości

Returns the real group id, as an integer.

Przykłady

Przykład #1 posix_getgid() example

This example will print out the real group id, even once the effective group id has been changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

Zobacz też:

  • posix_getgrgid() - Return info about a group by group id
  • posix_getegid() - Return the effective group ID of the current process
  • posix_setgid() - Set the GID of the current process
  • POSIX man page GETGID(2)

posix_geteuid
posix_getgrgid
POSIX Funkcje


Return info about a group by group id

posix_getgid
posix_getgrnam
POSIX Funkcje
PHP Manual

posix_getgrgid

(PHP 4, PHP 5)

posix_getgrgid — Return info about a group by group id

Opis

array posix_getgrgid ( int $gid )

Gets information about a group provided its id.

Parametry

gid

The group id.

Zwracane wartości

The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID, should be the same as the gid parameter used when calling the function, and hence redundant.
members | This consists of an array of string's for all the members in the group.

Rejestr zmian

Wersja | Opis
4.2.0 | Prior to this version, members was simply an integer representing the number of members in the group, and the member names were returned with numerical indices.

Przykłady

Przykład #1 Example use of posix_getgrgid()

<?php

$groupid   = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

Zobacz też:

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrnam() - Return info about a group by name
  • filegroup() - Pobiera grupę pliku
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)

posix_getgid
posix_getgrnam
POSIX Funkcje


Return info about a group by name

posix_getgrgid
posix_getgroups
POSIX Funkcje
PHP Manual

posix_getgrnam

(PHP 4, PHP 5)

posix_getgrnam — Return info about a group by name

Opis

array posix_getgrnam ( string $name )

Gets information about a group provided its name.

Parametry

name

The name of the group

Zwracane wartości

The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name. This should be the same as the name parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID of the group in numeric form.
members | This consists of an array of string's for all the members in the group.

Rejestr zmian

Wersja | Opis
4.2.0 | Prior to this version, members was simply an integer representing the number of members in the group, and the member names were returned with numerical indices.

Przykłady

Przykład #1 Example use of posix_getgrnam()

<?php

$groupinfo = posix_getgrnam("toons");

print_r($groupinfo);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

Zobacz też:

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrgid() - Return info about a group by group id
  • filegroup() - Pobiera grupę pliku
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)

posix_getgrgid
posix_getgroups
POSIX Funkcje


Return the group set of the current process

posix_getgrnam
posix_getlogin
POSIX Funkcje
PHP Manual

posix_getgroups

(PHP 4, PHP 5)

posix_getgroups — Return the group set of the current process

Opis

array posix_getgroups ( void )

Gets the group set of the current process.

Zwracane wartości

Returns an array of integers containing the numeric group ids of the group set of the current process.

Przykłady

Przykład #1 Example use of posix_getgroups()

<?php

$groups = posix_getgroups();

print_r($groups);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => 4
    [1] => 20
    [2] => 24
    [3] => 25
    [4] => 29
    [5] => 30
    [6] => 33
    [7] => 44
    [8] => 46
    [9] => 104
    [10] => 109
    [11] => 110
    [12] => 1000
)

Zobacz też:

  • posix_getgrgid() - Return info about a group by group id

posix_getgrnam
posix_getlogin
POSIX Funkcje


Return login name

posix_getgroups
posix_getpgid
POSIX Funkcje
PHP Manual

posix_getlogin

(PHP 4, PHP 5)

posix_getlogin — Return login name

Opis

string posix_getlogin ( void )

Returns the login name of the user owning the current process.

Zwracane wartości

Returns the login name of the user, as a string.

Przykłady

Przykład #1 Example use of posix_getlogin()

<?php
echo posix_getlogin(); //apache
?>

Zobacz też:

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETLOGIN(3)

posix_getgroups
posix_getpgid
POSIX Funkcje


Get process group id for job control

posix_getlogin
posix_getpgrp
POSIX Funkcje
PHP Manual

posix_getpgid

(PHP 4, PHP 5)

posix_getpgid — Get process group id for job control

Opis

int posix_getpgid ( int $pid )

Returns the process group identifier of the process pid lub FALSE w przypadku niepowodzenia.

Parametry

pid

The process id.

Zwracane wartości

Returns the identifier, as an integer.

Przykłady

Przykład #1 Example use of posix_getpgid()

<?php
$pid = posix_getppid();
echo posix_getpgid($pid); //35
?>

Notatki

Informacja:

This is a not POSIX function, but is common on BSD and System V systems. If the system does not support this function, then it will not be included at compile time. This may be checked with function_exists().

Zobacz też:

  • posix_getppid() - Return the parent process identifier
  • man page SETPGID(2)

posix_getlogin
posix_getpgrp
POSIX Funkcje


Return the current process group identifier

posix_getpgid
posix_getpid
POSIX Funkcje
PHP Manual

posix_getpgrp

(PHP 4, PHP 5)

posix_getpgrp — Return the current process group identifier

Opis

int posix_getpgrp ( void )

Return the process group identifier of the current process.

Zwracane wartości

Returns the identifier, as an integer.

Zobacz też:

  • POSIX.1 and the getpgrp(2) manual page on the POSIX system for more information on process groups.

posix_getpgid
posix_getpid
POSIX Funkcje


Return the current process identifier

posix_getpgrp
posix_getppid
POSIX Funkcje
PHP Manual

posix_getpid

(PHP 4, PHP 5)

posix_getpid — Return the current process identifier

Opis

int posix_getpid ( void )

Return the process identifier of the current process.

Zwracane wartości

Returns the identifier, as an integer.

Przykłady

Przykład #1 Example use of posix_getpid()

<?php
echo posix_getpid(); //8805
?>

Zobacz też:

  • posix_kill() - Send a signal to a process
  • POSIX man page GETPID(2)

posix_getpgrp
posix_getppid
POSIX Funkcje


Return the parent process identifier

posix_getpid
posix_getpwnam
POSIX Funkcje
PHP Manual

posix_getppid

(PHP 4, PHP 5)

posix_getppid — Return the parent process identifier

Opis

int posix_getppid ( void )

Return the process identifier of the parent process of the current process.

Zwracane wartości

Returns the identifier, as an integer.

Przykłady

Przykład #1 Example use of posix_getppid()

<?php
echo posix_getppid(); //8259
?>

posix_getpid
posix_getpwnam
POSIX Funkcje


Return info about a user by username

posix_getppid
posix_getpwuid
POSIX Funkcje
PHP Manual

posix_getpwnam

(PHP 4, PHP 5)

posix_getpwnam — Return info about a user by username

Opis

array posix_getpwnam ( string $username )

Returns an array of information about the given user.

Parametry

username

An alphanumeric username.

Zwracane wartości

On success an array with the following elements is returned, else FALSE is returned:

The user information array
Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not the real, full name. This should be the same as the username parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID of the user in numeric form.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Przykłady

Przykład #1 Example use of posix_getpwnam()

<?php

$userinfo = posix_getpwnam("tom");

print_r($userinfo);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [geocs]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

Zobacz też:

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETPWNAM(3)

posix_getppid
posix_getpwuid
POSIX Funkcje


Return info about a user by user id

posix_getpwnam
posix_getrlimit
POSIX Funkcje
PHP Manual

posix_getpwuid

(PHP 4, PHP 5)

posix_getpwuid — Return info about a user by user id

Opis

array posix_getpwuid ( int $uid )

Returns an array of information about the user referenced by the given user ID.

Parametry

uid

The user identifier.

Zwracane wartości

Returns an associative array with the following elements:

The user information array
Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not the real, full name.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID, should be the same as the uid parameter used when calling the function, and hence redundant.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Przykłady

Przykład #1 Example use of posix_getpwuid()

<?php

$userinfo = posix_getpwuid(10000);

print_r($userinfo);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [geocs]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

Zobacz też:

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETPWNAM(3)

posix_getpwnam
posix_getrlimit
POSIX Funkcje


Return info about system resource limits

posix_getpwuid
posix_getsid
POSIX Funkcje
PHP Manual

posix_getrlimit

(PHP 4, PHP 5)

posix_getrlimit — Return info about system resource limits

Opis

array posix_getrlimit ( void )

posix_getrlimit() returns an array of information about the current resource's soft and hard limits.

Each resource has an associated soft and hard limit. The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit. An unprivileged process may only set its soft limit to a value from 0 to the hard limit, and irreversibly lower its hard limit.

Zwracane wartości

Returns an associative array of elements for each limit that is defined. Each limit has a soft and a hard limit.

List of possible limits returned
Limit name | Limit description
core | The maximum size of the core file. When 0, not core files are created. When core files are larger than this size, they will be truncated at this size.
totalmem | The maximum size of the memory of the process, in bytes.
virtualmem | The maximum size of the virtual memory for the process, in bytes.
data | The maximum size of the data segment for the process, in bytes.
stack | The maximum size of the process stack, in bytes.
rss | The maximum number of virtual pages resident in RAM
maxproc | The maximum number of processes that can be created for the real user ID of the calling process.
memlock | The maximum number of bytes of memory that may be locked into RAM.
cpu | The amount of time the process is allowed to use the CPU.
filesize | The maximum size of the data segment for the process, in bytes.
openfiles | One more than the maximum number of open file descriptors.

Przykłady

Przykład #1 Example use of posix_getrlimit()

<?php

$limits = posix_getrlimit();

print_r($limits);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [soft core] => 0
    [hard core] => unlimited
    [soft data] => unlimited
    [hard data] => unlimited
    [soft stack] => 8388608
    [hard stack] => unlimited
    [soft totalmem] => unlimited
    [hard totalmem] => unlimited
    [soft rss] => unlimited
    [hard rss] => unlimited
    [soft maxproc] => unlimited
    [hard maxproc] => unlimited
    [soft memlock] => unlimited
    [hard memlock] => unlimited
    [soft cpu] => unlimited
    [hard cpu] => unlimited
    [soft filesize] => unlimited
    [hard filesize] => unlimited
    [soft openfiles] => 1024
    [hard openfiles] => 1024
)

Notatki

Informacja:

This is a not POSIX function, but is common on BSD and System V systems. If the system does not support this function, then it will not be included at compile time. This may be checked with function_exists().

Zobacz też:

  • man page GETRLIMIT(2)

posix_getpwuid
posix_getsid
POSIX Funkcje


Get the current sid of the process

posix_getrlimit
posix_getuid
POSIX Funkcje
PHP Manual

posix_getsid

(PHP 4, PHP 5)

posix_getsid — Get the current sid of the process

Opis

int posix_getsid ( int $pid )

Return the session id of the process pid. The session id of a process is the process group id of the session leader.

Parametry

pid

The process identifier. If set to 0, the current process is assumed. If an invalid pid is specified, then FALSE is returned and an error is set which can be checked with posix_get_last_error().

Zwracane wartości

Returns the identifier, as an integer.

Przykłady

Przykład #1 Example use of posix_getsid()

<?php
$pid = posix_getpid();
echo posix_getsid($pid); //8805
?>

Zobacz też:

  • posix_getpgid() - Get process group id for job control
  • posix_setsid() - Make the current process a session leader
  • POSIX man page GETSID(2)

posix_getrlimit
posix_getuid
POSIX Funkcje


Return the real user ID of the current process

posix_getsid
posix_initgroups
POSIX Funkcje
PHP Manual

posix_getuid

(PHP 4, PHP 5)

posix_getuid — Return the real user ID of the current process

Opis

int posix_getuid ( void )

Return the numeric real user ID of the current process.

Zwracane wartości

Returns the user id, as an integer

Przykłady

Przykład #1 Example use of posix_getuid()

<?php
echo posix_getuid(); //10000
?>

Zobacz też:

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETUID(2)

posix_getsid
posix_initgroups
POSIX Funkcje


Calculate the group access list

posix_getuid
posix_isatty
POSIX Funkcje
PHP Manual

posix_initgroups

(PHP 5 >= 5.2.0)

posix_initgroups — Calculate the group access list

Opis

bool posix_initgroups ( string $name , int $base_group_id )

Calculates the group access list for the user specified in name.

Parametry

name

The user to calculate the list for.

base_group_id

Typically the group number from the password file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • The Unix manual page for initgroups(3).

posix_getuid
posix_isatty
POSIX Funkcje


Determine if a file descriptor is an interactive terminal

posix_initgroups
posix_kill
POSIX Funkcje
PHP Manual

posix_isatty

(PHP 4, PHP 5)

posix_isatty — Determine if a file descriptor is an interactive terminal

Opis

bool posix_isatty ( int $fd )

Determines if the file descriptor fd refers to a valid terminal type device.

Parametry

fd

The file descriptor.

Zwracane wartości

Returns TRUE if fd is an open descriptor connected to a terminal and FALSE otherwise.

Zobacz też:

  • posix_ttyname() - Determine terminal device name

posix_initgroups
posix_kill
POSIX Funkcje


Send a signal to a process

posix_isatty
posix_mkfifo
POSIX Funkcje
PHP Manual

posix_kill

(PHP 4, PHP 5)

posix_kill — Send a signal to a process

Opis

bool posix_kill ( int $pid , int $sig )

Send the signal sig to the process with the process identifier pid.

Parametry

pid

The process identifier.

sig

One of the PCNTL signals constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • The kill(2) manual page of the POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.

posix_isatty
posix_mkfifo
POSIX Funkcje


Create a fifo special file (a named pipe)

posix_kill
posix_mknod
POSIX Funkcje
PHP Manual

posix_mkfifo

(PHP 4, PHP 5)

posix_mkfifo — Create a fifo special file (a named pipe)

Opis

bool posix_mkfifo ( string $pathname , int $mode )

posix_mkfifo() creates a special FIFO file which exists in the file system and acts as a bidirectional communication endpoint for processes.

Parametry

pathname

Path to the FIFO file.

mode

The second parameter mode has to be given in octal notation (e.g. 0644). The permission of the newly created FIFO also depends on the setting of the current umask(). The permissions of the created file are (mode & ~umask).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Gdy włączony jest tryb bezpieczny, PHP sprawdza, czy pliki lub katalogi, na których zostaną wykonane operacje mają takie same UID (owner) jak skrypt, który jest aktualnie wykonywany.

posix_kill
posix_mknod
POSIX Funkcje


Create a special or ordinary file (POSIX.1)

posix_mkfifo
posix_setegid
POSIX Funkcje
PHP Manual

posix_mknod

(PHP 5 >= 5.1.0)

posix_mknod — Create a special or ordinary file (POSIX.1)

Opis

bool posix_mknod ( string $pathname , int $mode [, int $major = 0 [, int $minor = 0 ]] )

Creates a special or ordinary file.

Parametry

pathname

The file to create

mode

This parameter is constructed by a bitwise OR between file type (one of the following constants: POSIX_S_IFREG, POSIX_S_IFCHR, POSIX_S_IFBLK, POSIX_S_IFIFO or POSIX_S_IFSOCK) and permissions.

major

The major device kernel identifier (required to pass when using S_IFCHR or S_IFBLK).

minor

The minor device kernel identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A posix_mknod() example

<?php

$file = '/tmp/tmpfile';  // file name
$type = POSIX_S_IFBLK;   // file type
$permissions = 0777;     // octal
$major = 1;
$minor = 8;              // /dev/random

if (!posix_mknod($file, $type | $permissions, $major, $minor)) {
    die('Error ' . posix_get_last_error() . ': ' . posix_strerror(posix_get_last_error()));
}

?>

Zobacz też:

  • posix_mkfifo() - Create a fifo special file (a named pipe)

posix_mkfifo
posix_setegid
POSIX Funkcje


Set the effective GID of the current process

posix_mknod
posix_seteuid
POSIX Funkcje
PHP Manual

posix_setegid

(PHP 4 >= 4.0.2, PHP 5)

posix_setegid — Set the effective GID of the current process

Opis

bool posix_setegid ( int $gid )

Set the effective group ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function.

Parametry

gid

The group id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 posix_setegid() example

This example will print out the effective group id, once changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

Zobacz też:

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process

posix_mknod
posix_seteuid
POSIX Funkcje


Set the effective UID of the current process

posix_setegid
posix_setgid
POSIX Funkcje
PHP Manual

posix_seteuid

(PHP 4 >= 4.0.2, PHP 5)

posix_seteuid — Set the effective UID of the current process

Opis

bool posix_seteuid ( int $uid )

Set the real user ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function.

Parametry

uid

The user id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • posix_setgid() - Set the GID of the current process

posix_setegid
posix_setgid
POSIX Funkcje


Set the GID of the current process

posix_seteuid
posix_setpgid
POSIX Funkcje
PHP Manual

posix_setgid

(PHP 4, PHP 5)

posix_setgid — Set the GID of the current process

Opis

bool posix_setgid ( int $gid )

Set the real group ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Informacja:

If the caller is a super user, this will also set the effective group id.

Parametry

gid

The group id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 posix_setgid() example

This example will print out the effective group id, once it is changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setgid(40);
echo 'My real group id is '.posix_getgid(); //40
echo 'My effective group id is '.posix_getegid(); //40
?>

Zobacz też:

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process

posix_seteuid
posix_setpgid
POSIX Funkcje


Set process group id for job control

posix_setgid
posix_setsid
POSIX Funkcje
PHP Manual

posix_setpgid

(PHP 4, PHP 5)

posix_setpgid — Set process group id for job control

Opis

bool posix_setpgid ( int $pid , int $pgid )

Let the process pid join the process group pgid.

Parametry

pid

The process id.

pgid

The process group id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • See POSIX.1 and the setsid(2) manual page on the POSIX system for more informations on process groups and job control.

posix_setgid
posix_setsid
POSIX Funkcje


Make the current process a session leader

posix_setpgid
posix_setuid
POSIX Funkcje
PHP Manual

posix_setsid

(PHP 4, PHP 5)

posix_setsid — Make the current process a session leader

Opis

int posix_setsid ( void )

Make the current process a session leader.

Zwracane wartości

Returns the session id, or -1 on errors.

Zobacz też:

  • The POSIX.1 and the setsid(2) manual page on the POSIX system for more information on process groups and job control.

posix_setpgid
posix_setuid
POSIX Funkcje


Set the UID of the current process

posix_setsid
posix_strerror
POSIX Funkcje
PHP Manual

posix_setuid

(PHP 4, PHP 5)

posix_setuid — Set the UID of the current process

Opis

bool posix_setuid ( int $uid )

Set the real user ID of the current process. This is a privileged function that needs appropriate privileges (usually root) on the system to be able to perform this function.

Parametry

uid

The user id.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 posix_setuid() example

This example will show the current user id and then set it to a different value.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_setuid(10000);
echo posix_getuid()."\n"; //10000
echo posix_geteuid()."\n"; //10000
?>

Zobacz też:

  • posix_setgid() - Set the GID of the current process
  • posix_seteuid() - Set the effective UID of the current process
  • posix_getuid() - Return the real user ID of the current process
  • posix_geteuid() - Return the effective user ID of the current process

posix_setsid
posix_strerror
POSIX Funkcje


Retrieve the system error message associated with the given errno

posix_setuid
posix_times
POSIX Funkcje
PHP Manual

posix_strerror

(PHP 4 >= 4.2.0, PHP 5)

posix_strerror — Retrieve the system error message associated with the given errno

Opis

string posix_strerror ( int $errno )

Returns the POSIX system error message associated with the given errno. You may get the errno parameter by calling posix_get_last_error().

Parametry

errno

A POSIX error number, returned by posix_get_last_error(). If set to 0, then the string "Success" is returned.

Zwracane wartości

Returns the error message, as a string.

Przykłady

Przykład #1 posix_strerror() example

This example will attempt to kill a process which does not exist, then will print out the corresponding error message.

<?php
posix_kill(50,SIGKILL);
echo posix_strerror(posix_get_last_error())."\n";
?>

Powyższy przykład wyświetli coś podobnego do:

No such process

Zobacz też:

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

posix_setuid
posix_times
POSIX Funkcje


Get process times

posix_strerror
posix_ttyname
POSIX Funkcje
PHP Manual

posix_times

(PHP 4, PHP 5)

posix_times — Get process times

Opis

array posix_times ( void )

Gets information about the current CPU usage.

Zwracane wartości

Returns a hash of strings with information about the current process CPU usage. The indices of the hash are:

  • ticks - the number of clock ticks that have elapsed since reboot.
  • utime - user time used by the current process.
  • stime - system time used by the current process.
  • cutime - user time used by current process and children.
  • cstime - system time used by current process and children.

Notatki

Ostrzeżenie

This function isn't reliable to use, it may return negative values for high times.

Przykłady

Przykład #1 Example use of posix_times()

<?php

$times = posix_times();

print_r($times);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [ticks] => 25814410
    [utime] => 1
    [stime] => 1
    [cutime] => 0
    [cstime] => 0
)

posix_strerror
posix_ttyname
POSIX Funkcje


Determine terminal device name

posix_times
posix_uname
POSIX Funkcje
PHP Manual

posix_ttyname

(PHP 4, PHP 5)

posix_ttyname — Determine terminal device name

Opis

string posix_ttyname ( int $fd )

Returns a string for the absolute path to the current terminal device that is open on the file descriptor fd.

Parametry

fd

The file descriptor.

Zwracane wartości

On success, returns a string of the absolute path of the fd. On failure, returns FALSE

posix_times
posix_uname
POSIX Funkcje


Get system name

posix_ttyname
Program execution
POSIX Funkcje
PHP Manual

posix_uname

(PHP 4, PHP 5)

posix_uname — Get system name

Opis

array posix_uname ( void )

Gets information about the system.

Posix requires that assumptions must not be made about the format of the values, e.g. the assumption that a release may contain three digits or anything else returned by this function.

Zwracane wartości

Returns a hash of strings with information about the system. The indices of the hash are

  • sysname - operating system name (e.g. Linux)
  • nodename - system name (e.g. valiant)
  • release - operating system release (e.g. 2.2.10)
  • version - operating system version (e.g. #4 Tue Jul 20 17:01:36 MEST 1999)
  • machine - system architecture (e.g. i586)
  • domainname - DNS domainname (e.g. example.com)

domainname is a GNU extension and not part of POSIX.1, so this field is only available on GNU systems or when using the GNU libc.

Przykłady

Przykład #1 Example use of posix_uname()

<?php
$uname=posix_uname();
print_r($uname);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [sysname] => Linux
    [nodename] => funbox
    [release] => 2.6.20-15-server
    [version] => #2 SMP Sun Apr 15 07:41:34 UTC 2007
    [machine] => i686
)

posix_ttyname
Program execution
POSIX Funkcje


System program execution

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Program execution Funkcje
    • escapeshellarg — Escape a string to be used as a shell argument
    • escapeshellcmd — Escape shell metacharacters
    • exec — Execute an external program
    • passthru — Execute an external program and display raw output
    • proc_close — Close a process opened by proc_open and return the exit code of that process
    • proc_get_status — Get information about a process opened by proc_open
    • proc_nice — Change the priority of the current process
    • proc_open — Execute a command and open file pointers for input/output
    • proc_terminate — Kills a process opened by proc_open
    • shell_exec — Execute command via shell and return the complete output as a string
    • system — Execute an external program and display the output
posix_uname
Wstęp
Rozszerzenia kontroli procesów


Wstęp

Those functions provide means to execute commands on the system itself, and means to secure such commands.

Informacja:

All execution functions call the commands through cmd.exe under Windows. Therefore the user calling these functions needs appropriate privilege to run this command. The only exception is proc_open() with bypass_shell option.

Program execution
Instalacja/Konfiguracja
Program execution


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Program execution


Typy zasobów

This extension defines a process resource, returned by proc_open().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Program execution Funkcje
Program execution


Program execution Funkcje

Notatki

Ostrzeżenie

Open files with lock (especially open sessions) should be closed before executing a program in the background.

Zobacz też:

These functions are also closely related to the backtick operator. Also, while in tryb bezpieczny you must consider the safe_mode_exec_dir directive.

Spis treści

  • escapeshellarg — Escape a string to be used as a shell argument
  • escapeshellcmd — Escape shell metacharacters
  • exec — Execute an external program
  • passthru — Execute an external program and display raw output
  • proc_close — Close a process opened by proc_open and return the exit code of that process
  • proc_get_status — Get information about a process opened by proc_open
  • proc_nice — Change the priority of the current process
  • proc_open — Execute a command and open file pointers for input/output
  • proc_terminate — Kills a process opened by proc_open
  • shell_exec — Execute command via shell and return the complete output as a string
  • system — Execute an external program and display the output
Stałe predefiniowane
escapeshellarg
Program execution


Escape a string to be used as a shell argument

Program execution Funkcje
escapeshellcmd
Program execution Funkcje
PHP Manual

escapeshellarg

(PHP 4 >= 4.0.3, PHP 5)

escapeshellarg — Escape a string to be used as a shell argument

Opis

string escapeshellarg ( string $arg )

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator.

Parametry

arg

The argument that will be escaped.

Zwracane wartości

The escaped string.

Przykłady

Przykład #1 escapeshellarg() example

<?php
system('ls '.escapeshellarg($dir));
?>

Zobacz też:

  • escapeshellcmd() - Escape shell metacharacters
  • exec() - Execute an external program
  • popen() - Otwiera wskaźnik pliku do procesu
  • system() - Execute an external program and display the output
  • backtick operator

Program execution Funkcje
escapeshellcmd
Program execution Funkcje


Escape shell metacharacters

escapeshellarg
exec
Program execution Funkcje
PHP Manual

escapeshellcmd

(PHP 4, PHP 5)

escapeshellcmd — Escape shell metacharacters

Opis

string escapeshellcmd ( string $command )

escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator.

Following characters are preceded by a backslash: #&;`|*?~<>^()[]{}$\, \x0A and \xFF. ' and " are escaped only if they are not paired. In Windows, all these characters plus % are replaced by a space instead.

Parametry

command

The command that will be escaped.

Zwracane wartości

The escaped string.

Przykłady

Przykład #1 escapeshellcmd() example

<?php
// We allow arbitrary number of arguments intentionaly here.
$command = './configure '.$_POST['configure_options'];

$escaped_command = escapeshellcmd($command);

system($escaped_command);
?>

Ostrzeżenie

escapeshellcmd() should be used on the whole command string, and it still allows the attacker to pass arbitrary number of arguments. For escaping a single argument escapeshellarg() should be used instead.

Zobacz też:

  • escapeshellarg() - Escape a string to be used as a shell argument
  • exec() - Execute an external program
  • popen() - Otwiera wskaźnik pliku do procesu
  • system() - Execute an external program and display the output
  • backtick operator

escapeshellarg
exec
Program execution Funkcje


Execute an external program

escapeshellcmd
passthru
Program execution Funkcje
PHP Manual

exec

(PHP 4, PHP 5)

exec — Execute an external program

Opis

string exec ( string $command [, array &$output [, int &$return_var ]] )

exec() executes the given command.

Parametry

command

The command that will be executed.

output

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

return_var

If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.

Zwracane wartości

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

To get the output of the executed command, be sure to set and use the output parameter.

Przykłady

Przykład #1 An exec() example

<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>

Notatki

Ostrzeżenie

Jeśli planowane jest przekazanie danych pochodzących od użytkownika do tej funkcji, powinno sie skorzystać z funkcji escapeshellarg() lub escapeshellcmd() aby mieć pewność, że użytkownicy nie mogą uruchomić dowolnych poleceń systemowych.

Informacja:

Jeśli program uruchamiany w tle zawiera tę funkcję, należy upewnić się, że wyjście tego programu jest przekierowane do pliku lub innego strumienia wyjściowego. W przeciwnym przypadku PHP zawiesi działanie aż do zakończenia działania wykonywanego programu.

Informacja: Jeśli tryb bezpieczny został włączony, możliwe jest wykonywanie programów tylko z katalogu określonego przez safe_mode_exec_dir. Ze względów praktycznych, nie można podawać elementów .. w ścieżce do pliku wykonywalnego.

Ostrzeżenie

Jeśli włączony jest tryb bezpieczny, ciągi zawierające polecenia są filtrowane przez funkcję escapeshellcmd(). W związku z tym, echo y | echo x staje się echo y \| echo x.

Zobacz też:

  • system() - Execute an external program and display the output
  • passthru() - Execute an external program and display raw output
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator

escapeshellcmd
passthru
Program execution Funkcje


Execute an external program and display raw output

exec
proc_close
Program execution Funkcje
PHP Manual

passthru

(PHP 4, PHP 5)

passthru — Execute an external program and display raw output

Opis

void passthru ( string $command [, int &$return_var ] )

The passthru() function is similar to the exec() function in that it executes a command. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

Parametry

command

The command that will be executed.

return_var

If the return_var argument is present, the return status of the Unix command will be placed here.

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Ostrzeżenie

Jeśli planowane jest przekazanie danych pochodzących od użytkownika do tej funkcji, powinno sie skorzystać z funkcji escapeshellarg() lub escapeshellcmd() aby mieć pewność, że użytkownicy nie mogą uruchomić dowolnych poleceń systemowych.

Informacja:

Jeśli program uruchamiany w tle zawiera tę funkcję, należy upewnić się, że wyjście tego programu jest przekierowane do pliku lub innego strumienia wyjściowego. W przeciwnym przypadku PHP zawiesi działanie aż do zakończenia działania wykonywanego programu.

Informacja: Jeśli tryb bezpieczny został włączony, możliwe jest wykonywanie programów tylko z katalogu określonego przez safe_mode_exec_dir. Ze względów praktycznych, nie można podawać elementów .. w ścieżce do pliku wykonywalnego.

Ostrzeżenie

Jeśli włączony jest tryb bezpieczny, ciągi zawierające polecenia są filtrowane przez funkcję escapeshellcmd(). W związku z tym, echo y | echo x staje się echo y \| echo x.

Zobacz też:

  • exec() - Execute an external program
  • system() - Execute an external program and display the output
  • popen() - Otwiera wskaźnik pliku do procesu
  • escapeshellcmd() - Escape shell metacharacters
  • backtick operator

exec
proc_close
Program execution Funkcje


Close a process opened by proc_open and return the exit code of that process

passthru
proc_get_status
Program execution Funkcje
PHP Manual

proc_close

(PHP 4 >= 4.3.0, PHP 5)

proc_close — Close a process opened by proc_open() and return the exit code of that process

Opis

int proc_close ( resource $process )

proc_close() is similar to pclose() except that it only works on processes opened by proc_open(). proc_close() waits for the process to terminate, and returns its exit code. If you have open pipes to that process, you should fclose() them prior to calling this function in order to avoid a deadlock - the child process may not be able to exit while the pipes are open.

Parametry

process

The proc_open() resource that will be closed.

Zwracane wartości

Returns the termination status of the process that was run. In case of an error then -1 is returned.

Notatki

Informacja: Unix Only:

proc_close() is internally implemented using the waitpid(3) system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used.

passthru
proc_get_status
Program execution Funkcje


Get information about a process opened by proc_open

proc_close
proc_nice
Program execution Funkcje
PHP Manual

proc_get_status

(PHP 5)

proc_get_status — Get information about a process opened by proc_open()

Opis

array proc_get_status ( resource $process )

proc_get_status() fetches data about a process opened using proc_open().

Parametry

process

The proc_open() resource that will be evaluated.

Zwracane wartości

An array of collected information on success, and FALSE on failure. The returned array contains the following elements:

element | type | description
command | string | The command string that was passed to proc_open().
pid | int | process id
running | bool | TRUE if the process is still running, FALSE if it has terminated.
signaled | bool | TRUE if the child process has been terminated by an uncaught signal. Always set to FALSE on Windows.
stopped | bool | TRUE if the child process has been stopped by a signal. Always set to FALSE on Windows.
exitcode | int | The exit code returned by the process (which is only meaningful if running is FALSE). Only first call of this function return real value, next calls return -1.
termsig | int | The number of the signal that caused the child process to terminate its execution (only meaningful if signaled is TRUE).
stopsig | int | The number of the signal that caused the child process to stop its execution (only meaningful if stopped is TRUE).

Zobacz też:

  • proc_open() - Execute a command and open file pointers for input/output

proc_close
proc_nice
Program execution Funkcje


Change the priority of the current process

proc_get_status
proc_open
Program execution Funkcje
PHP Manual

proc_nice

(PHP 5)

proc_nice — Change the priority of the current process

Opis

bool proc_nice ( int $increment )

proc_nice() changes the priority of the current process by the amount specified in increment. A positive increment will lower the priority of the current process, whereas a negative increment will raise the priority.

proc_nice() is not related to proc_open() and its associated functions in any way.

Parametry

increment

The increment value of the priority change.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is also generated.

Notatki

Informacja: Availability

proc_nice() will only exist if your system has 'nice' capabilities. 'nice' conforms to: SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3. This means that proc_nice() is not available on Windows.

proc_get_status
proc_open
Program execution Funkcje


Execute a command and open file pointers for input/output

proc_nice
proc_terminate
Program execution Funkcje
PHP Manual

proc_open

(PHP 4 >= 4.3.0, PHP 5)

proc_open — Execute a command and open file pointers for input/output

Opis

resource proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd [, array $env [, array $other_options ]]] )

proc_open() is similar to popen() but provides a much greater degree of control over the program execution.

Parametry

cmd

The command to execute

descriptorspec

An indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. 0 is stdin, 1 is stdout, while 2 is stderr.

Each element can be:

  • An array describing the pipe to pass to the process. The first element is the descriptor type and the second element is an option for the given type. Valid types are pipe (the second element is either r to pass the read end of the pipe to the process, or w to pass the write end) and file (the second element is a filename).
  • A stream resource representing a real file descriptor (e.g. opened file, a socket, STDIN).

The file descriptor numbers are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxiliary file descriptors.

pipes

Will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created.

cwd

The initial working dir for the command. This must be an absolute directory path, or NULL if you want to use the default value (the working dir of the current PHP process)

env

An array with the environment variables for the command that will be run, or NULL to use the same environment as the current PHP process

other_options

Allows you to specify additional options. Currently supported options include:

  • suppress_errors (windows only): suppresses errors generated by this function when it's set to TRUE
  • bypass_shell (windows only): bypass cmd.exe shell when set to TRUE
  • context: stream context used when opening files (created with stream_context_create())

Zwracane wartości

Returns a resource representing the process, which should be freed using proc_close() when you are finished with it. On failure returns FALSE.

Rejestr zmian

Wersja | Opis
5.2.1 | Added the bypass_shell option to the other_options parameter.
5.0.0 | Added the cwd, env and other_options parameters.

Przykłady

Przykład #1 A proc_open() example

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], '<?php print_r($_ENV); ?>');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [some_option] => aeiou
    [PWD] => /tmp
    [SHLVL] => 1
    [_] => /usr/local/bin/php
)
command returned 0

Notatki

Informacja:

Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process as inheritable handles, but since the Windows architecture does not associate file descriptor numbers with low-level handles, the child process does not (yet) have a means of accessing those handles. Stdin, stdout and stderr work as expected.

Informacja:

If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

Zobacz też:

  • popen() - Otwiera wskaźnik pliku do procesu
  • exec() - Execute an external program
  • system() - Execute an external program and display the output
  • passthru() - Execute an external program and display raw output
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • The backtick operator

proc_nice
proc_terminate
Program execution Funkcje


Kills a process opened by proc_open

proc_open
shell_exec
Program execution Funkcje
PHP Manual

proc_terminate

(PHP 5)

proc_terminate — Kills a process opened by proc_open

Opis

bool proc_terminate ( resource $process [, int $signal = 15 ] )

Signals a process (created using proc_open()) that it should terminate. proc_terminate() returns immediately and does not wait for the process to terminate.

proc_terminate() allows you terminate the process and continue with other tasks. You may poll the process (to see if it has stopped yet) by using the proc_get_status() function.

Parametry

process

The proc_open() resource that will be closed.

signal

This optional parameter is only useful on POSIX operating systems; you may specify a signal to send to the process using the kill(2) system call. The default is SIGTERM.

Zwracane wartości

Returns the termination status of the process that was run.

Rejestr zmian

Wersja | Opis
5.2.2 | Previous versions used to destroy the given process resource.

Zobacz też:

  • proc_open() - Execute a command and open file pointers for input/output
  • proc_close() - Close a process opened by proc_open and return the exit code of that process
  • proc_get_status() - Get information about a process opened by proc_open

proc_open
shell_exec
Program execution Funkcje


Execute command via shell and return the complete output as a string

proc_terminate
system
Program execution Funkcje
PHP Manual

shell_exec

(PHP 4, PHP 5)

shell_exec — Execute command via shell and return the complete output as a string

Opis

string shell_exec ( string $cmd )

This function is identical to the backtick operator.

Parametry

cmd

The command that will be executed.

Zwracane wartości

The output from the executed command or NULL if an error occurred.

Przykłady

Przykład #1 A shell_exec() example

<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>

Notatki

Informacja:

Ta funkcja jest niedostępna jeśli PHP działa w trybie bezpiecznym

Zobacz też:

  • exec() - Execute an external program
  • escapeshellcmd() - Escape shell metacharacters

proc_terminate
system
Program execution Funkcje


Execute an external program and display the output

shell_exec
Semaphore
Program execution Funkcje
PHP Manual

system

(PHP 4, PHP 5)

system — Execute an external program and display the output

Opis

string system ( string $command [, int &$return_var ] )

system() is just like the C version of the function in that it executes the given command and outputs the result.

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Parametry

command

The command that will be executed.

return_var

If the return_var argument is present, then the return status of the executed command will be written to this variable.

Zwracane wartości

Returns the last line of the command output on success, and FALSE on failure.

Przykłady

Przykład #1 system() example

<?php
echo '<pre>';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('ls', $retval);

// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

Notatki

Ostrzeżenie

Jeśli planowane jest przekazanie danych pochodzących od użytkownika do tej funkcji, powinno sie skorzystać z funkcji escapeshellarg() lub escapeshellcmd() aby mieć pewność, że użytkownicy nie mogą uruchomić dowolnych poleceń systemowych.

Informacja:

Jeśli program uruchamiany w tle zawiera tę funkcję, należy upewnić się, że wyjście tego programu jest przekierowane do pliku lub innego strumienia wyjściowego. W przeciwnym przypadku PHP zawiesi działanie aż do zakończenia działania wykonywanego programu.

Informacja: Jeśli tryb bezpieczny został włączony, możliwe jest wykonywanie programów tylko z katalogu określonego przez safe_mode_exec_dir. Ze względów praktycznych, nie można podawać elementów .. w ścieżce do pliku wykonywalnego.

Ostrzeżenie

Jeśli włączony jest tryb bezpieczny, ciągi zawierające polecenia są filtrowane przez funkcję escapeshellcmd(). W związku z tym, echo y | echo x staje się echo y \| echo x.

Zobacz też:

  • exec() - Execute an external program
  • passthru() - Execute an external program and display raw output
  • popen() - Otwiera wskaźnik pliku do procesu
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator

shell_exec
Semaphore
Program execution Funkcje


Semaphore, Shared Memory and IPC

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Semaphore Funkcje
    • ftok — Convert a pathname and a project identifier to a System V IPC key
    • msg_get_queue — Create or attach to a message queue
    • msg_queue_exists — Check whether a message queue exists
    • msg_receive — Receive a message from a message queue
    • msg_remove_queue — Destroy a message queue
    • msg_send — Send a message to a message queue
    • msg_set_queue — Set information in the message queue data structure
    • msg_stat_queue — Returns information from the message queue data structure
    • sem_acquire — Acquire a semaphore
    • sem_get — Get a semaphore id
    • sem_release — Release a semaphore
    • sem_remove — Remove a semaphore
    • shm_attach — Creates or open a shared memory segment
    • shm_detach — Disconnects from shared memory segment
    • shm_get_var — Returns a variable from shared memory
    • shm_has_var — Check whether a specific entry exists
    • shm_put_var — Inserts or updates a variable in shared memory
    • shm_remove_var — Removes a variable from shared memory
    • shm_remove — Removes shared memory from Unix systems
system
Wstęp
Rozszerzenia kontroli procesów


Wstęp

This module provides wrappers for the System V IPC family of functions. It includes semaphores, shared memory and inter-process messaging (IPC).

Semaphores may be used to provide exclusive access to resources on the current machine, or to limit the number of processes that may simultaneously use a resource.

This module provides also shared memory functions using System V shared memory. Shared memory may be used to provide access to global variables. Different httpd-daemons and even other programs (such as Perl, C, ...) are able to access this data to provide a global data-exchange. Remember, that shared memory is NOT safe against simultaneous access. Use semaphores for synchronization.

Limits of Shared Memory by the Unix OS
SHMMAX | max size of shared memory, normally 131072 bytes
SHMMIN | minimum size of shared memory, normally 1 byte
SHMMNI | max amount of shared memory segments on a system, normally 100
SHMSEG | max amount of shared memory segments per process, normally 6

The messaging functions may be used to send and receive messages to/from other processes. They provide a simple and effective means of exchanging data between processes, without the need for setting up an alternative using Unix domain sockets.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

Semaphore
Instalacja/Konfiguracja
Semaphore


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Semaphore


Instalacja

Support for this functions are not enabled by default. To enable System V semaphore support compile PHP with the option --enable-sysvsem . To enable the System V shared memory support compile PHP with the option --enable-sysvshm . To enable the System V messages support compile PHP with the option --enable-sysvmsg .

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Semaphore Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
sysvshm.init_mem | 10000 | 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.

sysvshm.init_mem int

A default size of the shared memory segment.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

System V message constants
Constant | Type | Changelog
MSG_IPC_NOWAIT | integer |
MSG_EAGAIN | integer | As of 5.2.0
MSG_ENOMSG | integer | As of 5.2.0
MSG_NOERROR | integer |
MSG_EXCEPT | integer |

Typy zasobów
Semaphore Funkcje
Semaphore


Semaphore Funkcje

Spis treści

  • ftok — Convert a pathname and a project identifier to a System V IPC key
  • msg_get_queue — Create or attach to a message queue
  • msg_queue_exists — Check whether a message queue exists
  • msg_receive — Receive a message from a message queue
  • msg_remove_queue — Destroy a message queue
  • msg_send — Send a message to a message queue
  • msg_set_queue — Set information in the message queue data structure
  • msg_stat_queue — Returns information from the message queue data structure
  • sem_acquire — Acquire a semaphore
  • sem_get — Get a semaphore id
  • sem_release — Release a semaphore
  • sem_remove — Remove a semaphore
  • shm_attach — Creates or open a shared memory segment
  • shm_detach — Disconnects from shared memory segment
  • shm_get_var — Returns a variable from shared memory
  • shm_has_var — Check whether a specific entry exists
  • shm_put_var — Inserts or updates a variable in shared memory
  • shm_remove_var — Removes a variable from shared memory
  • shm_remove — Removes shared memory from Unix systems
Stałe predefiniowane
ftok
Semaphore


Convert a pathname and a project identifier to a System V IPC key

Semaphore Funkcje
msg_get_queue
Semaphore Funkcje
PHP Manual

ftok

(PHP 4 >= 4.2.0, PHP 5)

ftok — Convert a pathname and a project identifier to a System V IPC key

Opis

int ftok ( string $pathname , string $proj )

The function converts the pathname of an existing accessible file and a project identifier into an integer for use with for example shmop_open() and other System V IPC keys.

Parametry

pathname

Path to an accessible file.

proj

Project identifier. This must be a one character string.

Zwracane wartości

On success the return value will be the created key value, otherwise -1 is returned.

Zobacz też:

  • shmop_open() - Create or open shared memory block
  • sem_get() - Get a semaphore id

Semaphore Funkcje
msg_get_queue
Semaphore Funkcje


Create or attach to a message queue

ftok
msg_queue_exists
Semaphore Funkcje
PHP Manual

msg_get_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_get_queue — Create or attach to a message queue

Opis

resource msg_get_queue ( int $key [, int $perms = 0666 ] )

msg_get_queue() returns an id that can be used to access the System V message queue with the given key. The first call creates the message queue with the optional perms. A second call to msg_get_queue() for the same key will return a different message queue identifier, but both identifiers access the same underlying message queue.

Parametry

key

Message queue numeric ID

perms

Queue permissions. Default to 0666. If the message queue already exists, the perms will be ignored.

Zwracane wartości

Returns a resource handle that can be used to access the System V message queue.

Zobacz też:

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

ftok
msg_queue_exists
Semaphore Funkcje


Check whether a message queue exists

msg_get_queue
msg_receive
Semaphore Funkcje
PHP Manual

msg_queue_exists

(PHP 5 >= 5.3.0)

msg_queue_exists — Check whether a message queue exists

Opis

bool msg_queue_exists ( int $key )

Checks whether the message queue key exists.

Parametry

key

Queue key.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure

msg_get_queue
msg_receive
Semaphore Funkcje


Receive a message from a message queue

msg_queue_exists
msg_remove_queue
Semaphore Funkcje
PHP Manual

msg_receive

(PHP 4 >= 4.3.0, PHP 5)

msg_receive — Receive a message from a message queue

Opis

bool msg_receive ( resource $queue , int $desiredmsgtype , int &$msgtype , int $maxsize , mixed &$message [, bool $unserialize = true [, int $flags = 0 [, int &$errorcode ]]] )

msg_receive() will receive the first message from the specified queue of the type specified by desiredmsgtype.

Parametry

queue

desiredmsgtype

If desiredmsgtype is 0, the message from the front of the queue is returned. If desiredmsgtype is greater than 0, then the first message of that type is returned. If desiredmsgtype is less than 0, the first message on the queue with the lowest type less than or equal to the absolute value of desiredmsgtype will be read. If no messages match the criteria, your script will wait until a suitable message arrives on the queue. You can prevent the script from blocking by specifying MSG_IPC_NOWAIT in the flags parameter.

msgtype

The type of the message that was received will be stored in this parameter.

maxsize

The maximum size of message to be accepted is specified by the maxsize; if the message in the queue is larger than this size the function will fail (unless you set flags as described below).

message

The received message will be stored in message, unless there were errors receiving the message.

unserialize

If set to TRUE, the message is treated as though it was serialized using the same mechanism as the session module. The message will be unserialized and then returned to your script. This allows you to easily receive arrays or complex object structures from other PHP scripts, or if you are using the WDDX serializer, from any WDDX compatible source.

If unserialize is FALSE, the message will be returned as a binary-safe string.

flags

The optional flags allows you to pass flags to the low-level msgrcv system call. It defaults to 0, but you may specify one or more of the following values (by adding or ORing them together).

Flag values for msg_receive
MSG_IPC_NOWAIT | If there are no messages of the desiredmsgtype, return immediately and do not wait. The function will fail and return an integer value corresponding to MSG_ENOMSG.
MSG_EXCEPT | Using this flag in combination with a desiredmsgtype greater than 0 will cause the function to receive the first message that is not equal to desiredmsgtype.
MSG_NOERROR | If the message is longer than maxsize, setting this flag will truncate the message to maxsize and will not signal an error.

errorcode

If the function fails, the optional errorcode will be set to the value of the system errno variable.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Upon successful completion the message queue data structure is updated as follows: msg_lrpid is set to the process-ID of the calling process, msg_qnum is decremented by 1 and msg_rtime is set to the current time.

Zobacz też:

  • msg_remove_queue() - Destroy a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

msg_queue_exists
msg_remove_queue
Semaphore Funkcje


Destroy a message queue

msg_receive
msg_send
Semaphore Funkcje
PHP Manual

msg_remove_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_remove_queue — Destroy a message queue

Opis

bool msg_remove_queue ( resource $queue )

msg_remove_queue() destroys the message queue specified by the queue. Only use this function when all processes have finished working with the message queue and you need to release the system resources held by it.

Parametry

queue

Message queue resource handle

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msg_get_queue() - Create or attach to a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

msg_receive
msg_send
Semaphore Funkcje


Send a message to a message queue

msg_remove_queue
msg_set_queue
Semaphore Funkcje
PHP Manual

msg_send

(PHP 4 >= 4.3.0, PHP 5)

msg_send — Send a message to a message queue

Opis

bool msg_send ( resource $queue , int $msgtype , mixed $message [, bool $serialize = true [, bool $blocking = true [, int &$errorcode ]]] )

msg_send() sends a message of type msgtype (which MUST be greater than 0) to the message queue specified by queue.

Parametry

queue

msgtype

message

serialize

The optional serialize controls how the message is sent. serialize defaults to TRUE which means that the message is serialized using the same mechanism as the session module before being sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are using the WDDX serializer, to any WDDX compatible client.

blocking

If the message is too large to fit in the queue, your script will wait until another process reads messages from the queue and frees enough space for your message to be sent. This is called blocking; you can prevent blocking by setting the optional blocking parameter to FALSE, in which case msg_send() will immediately return FALSE if the message is too big for the queue, and set the optional errorcode to MSG_EAGAIN, indicating that you should try to send your message again a little later on.

errorcode

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Upon successful completion the message queue data structure is updated as follows: msg_lspid is set to the process-ID of the calling process, msg_qnum is incremented by 1 and msg_stime is set to the current time.

Zobacz też:

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

msg_remove_queue
msg_set_queue
Semaphore Funkcje


Set information in the message queue data structure

msg_send
msg_stat_queue
Semaphore Funkcje
PHP Manual

msg_set_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_set_queue — Set information in the message queue data structure

Opis

bool msg_set_queue ( resource $queue , array $data )

msg_set_queue() allows you to change the values of the msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes fields of the underlying message queue data structure.

Changing the data structure will require that PHP be running as the same user that created the queue, owns the queue (as determined by the existing msg_perm.xxx fields), or be running with root privileges. root privileges are required to raise the msg_qbytes values above the system defined limit.

Parametry

queue

Message queue resource handle

data

You specify the values you require by setting the value of the keys that you require in the data array.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_get_queue() - Create or attach to a message queue

msg_send
msg_stat_queue
Semaphore Funkcje


Returns information from the message queue data structure

msg_set_queue
sem_acquire
Semaphore Funkcje
PHP Manual

msg_stat_queue

(PHP 4 >= 4.3.0, PHP 5)

msg_stat_queue — Returns information from the message queue data structure

Opis

array msg_stat_queue ( resource $queue )

msg_stat_queue() returns the message queue meta data for the message queue specified by the queue. This is useful, for example, to determine which process sent the message that was just received.

Parametry

queue

Message queue resource handle

Zwracane wartości

The return value is an array whose keys and values have the following meanings:

Array structure for msg_stat_queue
msg_perm.uid | The uid of the owner of the queue.
msg_perm.gid | The gid of the owner of the queue.
msg_perm.mode | The file access mode of the queue.
msg_stime | The time that the last message was sent to the queue.
msg_rtime | The time that the last message was received from the queue.
msg_ctime | The time that the queue was last changed.
msg_qnum | The number of messages waiting to be read from the queue.
msg_qbytes | The maximum number of bytes allowed in one message queue. On Linux, this value may be read and modified via /proc/sys/kernel/msgmnb.
msg_lspid | The pid of the process that sent the last message to the queue.
msg_lrpid | The pid of the process that received the last message from the queue.

Zobacz też:

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_get_queue() - Create or attach to a message queue
  • msg_set_queue() - Set information in the message queue data structure

msg_set_queue
sem_acquire
Semaphore Funkcje


Acquire a semaphore

msg_stat_queue
sem_get
Semaphore Funkcje
PHP Manual

sem_acquire

(PHP 4, PHP 5)

sem_acquire — Acquire a semaphore

Opis

bool sem_acquire ( resource $sem_identifier )

sem_acquire() blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its maximum number of semaphore to be exceeded.

After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.

Parametry

sem_identifier

sem_identifier is a semaphore resource, obtained from sem_get().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore

msg_stat_queue
sem_get
Semaphore Funkcje


Get a semaphore id

sem_acquire
sem_release
Semaphore Funkcje
PHP Manual

sem_get

(PHP 4, PHP 5)

sem_get — Get a semaphore id

Opis

resource sem_get ( int $key [, int $max_acquire = 1 [, int $perm = 0666 [, int $auto_release = 1 ]]] )

sem_get() returns an id that can be used to access the System V semaphore with the given key.

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

Parametry

key

max_acquire

The number of processes that can acquire the semaphore simultaneously is set to max_acquire.

perm

The semaphore permissions. Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

auto_release

Specifies if the semaphore should be automatically released on request shutdown.

Zwracane wartości

Returns a positive semaphore identifier on success, or FALSE on error.

Rejestr zmian

Wersja | Opis
4.3.0 | The auto_release parameter was added.

Zobacz też:

  • sem_acquire() - Acquire a semaphore
  • sem_release() - Release a semaphore
  • ftok() - Convert a pathname and a project identifier to a System V IPC key

sem_acquire
sem_release
Semaphore Funkcje


Release a semaphore

sem_get
sem_remove
Semaphore Funkcje
PHP Manual

sem_release

(PHP 4, PHP 5)

sem_release — Release a semaphore

Opis

bool sem_release ( resource $sem_identifier )

sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.

After releasing the semaphore, sem_acquire() may be called to re-acquire it.

Parametry

sem_identifier

A Semaphore resource handle as returned by sem_get().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • sem_get() - Get a semaphore id
  • sem_acquire() - Acquire a semaphore

sem_get
sem_remove
Semaphore Funkcje


Remove a semaphore

sem_release
shm_attach
Semaphore Funkcje
PHP Manual

sem_remove

(PHP 4 >= 4.1.0, PHP 5)

sem_remove — Remove a semaphore

Opis

bool sem_remove ( resource $sem_identifier )

sem_remove() removes the given semaphore.

After removing the semaphore, it is no longer accessible.

Parametry

sem_identifier

A semaphore resource identifier as returned by sem_get().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore
  • sem_acquire() - Acquire a semaphore

sem_release
shm_attach
Semaphore Funkcje


Creates or open a shared memory segment

sem_remove
shm_detach
Semaphore Funkcje
PHP Manual

shm_attach

(PHP 4, PHP 5)

shm_attach — Creates or open a shared memory segment

Opis

resource shm_attach ( int $key [, int $memsize [, int $perm = 0666 ]] )

shm_attach() returns an id that can be used to access the System V shared memory with the given key, the first call creates the shared memory segment with memsize and the optional perm-bits perm.

A second call to shm_attach() for the same key will return a different shared memory identifier, but both identifiers access the same underlying shared memory. memsize and perm will be ignored.

Parametry

key

A numeric shared memory segment ID

memsize

The memory size. If not provided, default to the sysvshm.init_mem in the php.ini, otherwise 10000 bytes.

perm

The optional permission bits. Default to 0666.

Zwracane wartości

Returns a shared memory segment identifier.

Rejestr zmian

Wersja | Opis
5.3.0 | This function now returns a zasób instead of an integer.

Notatki

Informacja:

This function used to return an integer value prior to PHP 5.3.0. To achieve the same value in a portable manner, the return value can be cast to an integer like:

<?php
// Create a temporary file and return its path
$tmp = tempnam('/tmp', 'PHP');

// Get the file token key
$key = ftok($tmp, 'a');

// Attach the SHM resource, notice the cast afterwards
$id = shm_attach($key);

if ($id === false) {
    die('Unable to create the shared memory segment');
}

// Cast to integer, since prior to PHP 5.3.0 the resource id
// is returned which can be exposed when casting a resource
// to an integer
$id = (integer) $id;
?>

Zobacz też:

  • shm_detach() - Disconnects from shared memory segment
  • ftok() - Convert a pathname and a project identifier to a System V IPC key

sem_remove
shm_detach
Semaphore Funkcje


Disconnects from shared memory segment

shm_attach
shm_get_var
Semaphore Funkcje
PHP Manual

shm_detach

(PHP 4, PHP 5)

shm_detach — Disconnects from shared memory segment

Opis

bool shm_detach ( resource $shm_identifier )

shm_detach() disconnects from the shared memory given by the shm_identifier created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.

Parametry

shm_identifier

A shared memory resource handle as returned by shm_attach()

Zwracane wartości

shm_detach() always returns TRUE.

Zobacz też:

  • shm_attach() - Creates or open a shared memory segment
  • shm_remove() - Removes shared memory from Unix systems
  • shm_remove_var() - Removes a variable from shared memory

shm_attach
shm_get_var
Semaphore Funkcje


Returns a variable from shared memory

shm_detach
shm_has_var
Semaphore Funkcje
PHP Manual

shm_get_var

(PHP 4, PHP 5)

shm_get_var — Returns a variable from shared memory

Opis

mixed shm_get_var ( resource $shm_identifier , int $variable_key )

shm_get_var() returns the variable with a given variable_key, in the given shared memory segment. The variable is still present in the shared memory.

Parametry

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Zwracane wartości

Returns the variable with the given key.

Zobacz też:

  • shm_has_var() - Check whether a specific entry exists
  • shm_put_var() - Inserts or updates a variable in shared memory

shm_detach
shm_has_var
Semaphore Funkcje


Check whether a specific entry exists

shm_get_var
shm_put_var
Semaphore Funkcje
PHP Manual

shm_has_var

(PHP 5 >= 5.3.0)

shm_has_var — Check whether a specific entry exists

Opis

bool shm_has_var ( resource $shm_identifier , int $variable_key )

Checks whether a specific key exists inside a shared memory segment.

Parametry

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Zwracane wartości

Returns TRUE if the entry exists, otherwise FALSE

Zobacz też:

  • shm_get_var() - Returns a variable from shared memory
  • shm_put_var() - Inserts or updates a variable in shared memory

shm_get_var
shm_put_var
Semaphore Funkcje


Inserts or updates a variable in shared memory

shm_has_var
shm_remove_var
Semaphore Funkcje
PHP Manual

shm_put_var

(PHP 4, PHP 5)

shm_put_var — Inserts or updates a variable in shared memory

Opis

bool shm_put_var ( resource $shm_identifier , int $variable_key , mixed $variable )

shm_put_var() inserts or updates the variable with the given variable_key.

Warnings (E_WARNING level) will be issued if shm_identifier is not a valid SysV shared memory index or if there was not enough shared memory remaining to complete your request.

Parametry

shm_identifier

A shared memory resource handle as returned by shm_attach()

variable_key

The variable key.

variable

The variable. All variable types that serialize() supports may be used: generally this means all types except for resources and some internal objects that cannot be serialized.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • shm_get_var() - Returns a variable from shared memory
  • shm_has_var() - Check whether a specific entry exists

shm_has_var
shm_remove_var
Semaphore Funkcje


Removes a variable from shared memory

shm_put_var
shm_remove
Semaphore Funkcje
PHP Manual

shm_remove_var

(PHP 4, PHP 5)

shm_remove_var — Removes a variable from shared memory

Opis

bool shm_remove_var ( resource $shm_identifier , int $variable_key )

Removes a variable with a given variable_key and frees the occupied memory.

Parametry

shm_identifier

The shared memory identifier as returned by shm_attach()

variable_key

The variable key.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • shm_remove() - Removes shared memory from Unix systems

shm_put_var
shm_remove
Semaphore Funkcje


Removes shared memory from Unix systems

shm_remove_var
Shared Memory
Semaphore Funkcje
PHP Manual

shm_remove

(PHP 4, PHP 5)

shm_remove — Removes shared memory from Unix systems

Opis

bool shm_remove ( resource $shm_identifier )

shm_remove() removes the shared memory shm_identifier. All data will be destroyed.

Parametry

shm_identifier

The shared memory identifier as returned by shm_attach()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • shm_remove_var() - Removes a variable from shared memory

shm_remove_var
Shared Memory
Semaphore Funkcje


Shared Memory

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • Shared Memory Funkcje
    • shmop_close — Close shared memory block
    • shmop_delete — Delete shared memory block
    • shmop_open — Create or open shared memory block
    • shmop_read — Read data from shared memory block
    • shmop_size — Get size of shared memory block
    • shmop_write — Write data into shared memory block
shm_remove
Wstęp
Rozszerzenia kontroli procesów


Wstęp

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete Unix shared memory segments.

Informacja: Versions of Windows previous to Windows 2000 do not support shared memory.

Informacja: In PHP 4.0.3, these functions were prefixed by shm rather than shmop.

Shared Memory
Instalacja/Konfiguracja
Shared Memory


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Shared Memory


Instalacja

To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Shared Memory


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
Shared Memory


Basic usage

Przykład #1 Shared Memory Operations Overview

<?php

// Create 100 byte shared memory block with system id of 0xff3
$shm_id = shmop_open(0xff3, "c", 0644, 100);
if (!$shm_id) {
    echo "Couldn't create shared memory segment\n";
}

// Get shared memory block's size
$shm_size = shmop_size($shm_id);
echo "SHM Block Size: " . $shm_size . " has been created.\n";

// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if ($shm_bytes_written != strlen("my shared memory block")) {
    echo "Couldn't write the entire length of data\n";
}

// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if (!$my_string) {
    echo "Couldn't read from shared memory block\n";
}
echo "The data inside shared memory was: " . $my_string . "\n";

//Now lets delete the block and close the shared memory segment
if (!shmop_delete($shm_id)) {
    echo "Couldn't mark shared memory block for deletion.";
}
shmop_close($shm_id);

?>

Przykłady
Shared Memory Funkcje
Przykłady


Shared Memory Funkcje

Spis treści

  • shmop_close — Close shared memory block
  • shmop_delete — Delete shared memory block
  • shmop_open — Create or open shared memory block
  • shmop_read — Read data from shared memory block
  • shmop_size — Get size of shared memory block
  • shmop_write — Write data into shared memory block
Basic usage
shmop_close
Shared Memory


Close shared memory block

Shared Memory Funkcje
shmop_delete
Shared Memory Funkcje
PHP Manual

shmop_close

(PHP 4 >= 4.0.4, PHP 5)

shmop_close — Close shared memory block

Opis

void shmop_close ( int $shmid )

shmop_close() is used to close a shared memory block.

Parametry

shmid

The shared memory block identifier created by shmop_open()

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

Zobacz też:

  • shmop_open() - Create or open shared memory block

Shared Memory Funkcje
shmop_delete
Shared Memory Funkcje


Delete shared memory block

shmop_close
shmop_open
Shared Memory Funkcje
PHP Manual

shmop_delete

(PHP 4 >= 4.0.4, PHP 5)

shmop_delete — Delete shared memory block

Opis

bool shmop_delete ( int $shmid )

shmop_delete() is used to delete a shared memory block.

Parametry

shmid

The shared memory block identifier created by shmop_open()

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Deleting shared memory block

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.

shmop_close
shmop_open
Shared Memory Funkcje


Create or open shared memory block

shmop_delete
shmop_read
Shared Memory Funkcje
PHP Manual

shmop_open

(PHP 4 >= 4.0.4, PHP 5)

shmop_open — Create or open shared memory block

Opis

int shmop_open ( int $key , string $flags , int $mode , int $size )

shmop_open() can create or open a shared memory block.

Parametry

key

System's id for the shared memory block. Can be passed as a decimal or hex.

flags

The flags that you can use:

  • "a" for access (sets SHM_RDONLY for shmat) use this flag when you need to open an existing shared memory segment for read only
  • "c" for create (sets IPC_CREATE) use this flag when you need to create a new shared memory segment or if a segment with the same key exists, try to open it for read and write
  • "w" for read & write access use this flag when you need to read and write to a shared memory segment, use this flag in most cases.
  • "n" create a new memory segment (sets IPC_CREATE|IPC_EXCL) use this flag when you want to create a new shared memory segment but if one already exists with the same flag, fail. This is useful for security purposes, using this you can prevent race condition exploits.

mode

The permissions that you wish to assign to your memory segment, those are the same as permission for a file. Permissions need to be passed in octal form, like for example 0644

size

The size of the shared memory block you wish to create in bytes

Informacja:

Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment.

Zwracane wartości

On success shmop_open() will return an id that you can use to access the shared memory segment you've created. FALSE is returned on failure.

Przykłady

Przykład #1 Create a new shared memory block

<?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?>

This example opened a shared memory block with a system id returned by ftok().

Zobacz też:

  • shmop_close() - Close shared memory block
  • shmop_delete() - Delete shared memory block

shmop_delete
shmop_read
Shared Memory Funkcje


Read data from shared memory block

shmop_open
shmop_size
Shared Memory Funkcje
PHP Manual

shmop_read

(PHP 4 >= 4.0.4, PHP 5)

shmop_read — Read data from shared memory block

Opis

string shmop_read ( int $shmid , int $start , int $count )

shmop_read() will read a string from shared memory block.

Parametry

shmid

The shared memory block identifier created by shmop_open()

start

Offset from which to start reading

count

The number of bytes to read

Zwracane wartości

Returns the data lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Reading shared memory block

<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>

This example will read 50 bytes from shared memory block and place the data inside $shm_data.

Zobacz też:

  • shmop_write() - Write data into shared memory block

shmop_open
shmop_size
Shared Memory Funkcje


Get size of shared memory block

shmop_read
shmop_write
Shared Memory Funkcje
PHP Manual

shmop_size

(PHP 4 >= 4.0.4, PHP 5)

shmop_size — Get size of shared memory block

Opis

int shmop_size ( int $shmid )

shmop_size() is used to get the size, in bytes of the shared memory block.

Parametry

shmid

The shared memory block identifier created by shmop_open()

Zwracane wartości

Returns an int, which represents the number of bytes the shared memory block occupies.

Przykłady

Przykład #1 Getting the size of the shared memory block

<?php
$shm_size = shmop_size($shm_id);
?>

This example will put the size of shared memory block identified by $shm_id into $shm_size.

shmop_read
shmop_write
Shared Memory Funkcje


Write data into shared memory block

shmop_size
Inne podstawowe rozszerzenia
Shared Memory Funkcje
PHP Manual

shmop_write

(PHP 4 >= 4.0.4, PHP 5)

shmop_write — Write data into shared memory block

Opis

int shmop_write ( int $shmid , string $data , int $offset )

shmop_write() will write a string into shared memory block.

Parametry

shmid

The shared memory block identifier created by shmop_open()

data

A string to write into shared memory block

offset

Specifies where to start writing data inside the shared memory segment.

Zwracane wartości

The size of the written data, or FALSE on failure.

Przykłady

Przykład #1 Writing to shared memory block

<?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>

This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.

Zobacz też:

  • shmop_read() - Read data from shared memory block

shmop_size
Inne podstawowe rozszerzenia
Shared Memory Funkcje


Inne podstawowe rozszerzenia

  • GeoIP — Geo IP Location
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • GeoIP Funkcje
  • JSON — JavaScript Object Notation
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • JsonSerializable — The JsonSerializable class
    • Funkcje JSON
  • Judy — Judy Arrays
    • Wstęp
    • Instalacja/Konfiguracja
    • Judy — The Judy class
    • Judy Funkcje
  • Lua
    • Wstęp
    • Instalacja/Konfiguracja
    • Lua — The Lua class
    • LuaClosure — The LuaClosure class
  • Misc. — Miscellaneous Functions
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Misc. Funkcje
  • Parsekit
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Parsekit Funkcje
  • SPL — Standard PHP Library (SPL)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Struktury danych
    • Iteratory
    • Interfejsy
    • Wyjątki
    • SPL Funkcje
    • Obsługa plików
    • Różne klasy i interfejsy
  • SPL Types — SPL Type Handling
    • Wstęp
    • Instalacja/Konfiguracja
    • SplType — The SplType class
    • SplInt — The SplInt class
    • SplFloat — The SplFloat class
    • SplEnum — The SplEnum class
    • SplBool — The SplBool class
    • SplString — The SplString class
  • Streams
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Stream Filters
    • Stream Contexts
    • Stream Errors
    • Przykłady
    • streamWrapper — The streamWrapper class
    • Stream Funkcje
  • Tidy
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • tidy — The tidy class
    • tidyNode — The tidyNode class
    • Funkcje Tidy
  • Tokenizer
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Funkcje Tokenizer
  • URL Funkcje
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • URL Funkcje
  • V8js — V8 Javascript Engine Integration
    • Wstęp
    • Instalacja/Konfiguracja
    • Przykłady
    • V8Js — The V8Js class
    • V8JsException — The V8JsException class
  • Yaml — YAML Data Serialization
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Yaml Funkcje
  • Yaf
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Application Configuration
    • Yaf_Application — The Yaf_Application class
    • Yaf_Bootstrap_Abstract — The Yaf_Bootstrap_Abstract class
    • Yaf_Dispatcher — The Yaf_Dispatcher class
    • Yaf_Config_Abstract — The Yaf_Config_Abstract class
    • Yaf_Config_Ini — The Yaf_Config_Ini class
    • Yaf_Config_Simple — The Yaf_Config_Simple class
    • Yaf_Controller_Abstract — The Yaf_Controller_Abstract class
    • Yaf_Action_Abstract — The Yaf_Action_Abstract class
    • Yaf_View_Interface — The Yaf_View_Interface class
    • Yaf_View_Simple — The Yaf_View_Simple class
    • Yaf_Loader — The Yaf_Loader class
    • Yaf_Plugin_Abstract — The Yaf_Plugin_Abstract class
    • Yaf_Registry — The Yaf_Registry class
    • Yaf_Request_Abstract — The Yaf_Request_Abstract class
    • Yaf_Request_Http — The Yaf_Request_Http class
    • Yaf_Request_Simple — The Yaf_Request_Simple class
    • Yaf_Response_Abstract — The Yaf_Response_Abstract class
    • Yaf_Route_Interface — The Yaf_Route_Interface class
    • Yaf_Route_Map — The Yaf_Route_Map class
    • Yaf_Route_Regex — The Yaf_Route_Regex class
    • Yaf_Route_Rewrite — The Yaf_Route_Rewrite class
    • Yaf_Router — The Yaf_Router class
    • Yaf_Route_Simple — The Yaf_Route_Simple class
    • Yaf_Route_Static — The Yaf_Route_Static class
    • Yaf_Route_Supervar — The Yaf_Route_Supervar class
    • Yaf_Session — The Yaf_Session class
    • Yaf_Exception — The Yaf_Exception class
    • Yaf_Exception_TypeError — The Yaf_Exception_TypeError class
    • Yaf_Exception_StartupError — The Yaf_Exception_StartupError class
    • Yaf_Exception_DispatchFailed — The Yaf_Exception_DispatchFailed class
    • Yaf_Exception_RouterFailed — The Yaf_Exception_RouterFailed class
    • Yaf_Exception_LoadFailed — The Yaf_Exception_LoadFailed class
    • Yaf_Exception_LoadFailed_Module — The Yaf_Exception_LoadFailed_Module class
    • Yaf_Exception_LoadFailed_Controller — The Yaf_Exception_LoadFailed_Controller class
    • Yaf_Exception_LoadFailed_Action — The Yaf_Exception_LoadFailed_Action class
    • Yaf_Exception_LoadFailed_View — The Yaf_Exception_LoadFailed_View class
shmop_write
GeoIP
Opis funkcji


Geo IP Location

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • GeoIP Funkcje
    • geoip_continent_code_by_name — Get the two letter continent code
    • geoip_country_code_by_name — Get the two letter country code
    • geoip_country_code3_by_name — Get the three letter country code
    • geoip_country_name_by_name — Get the full country name
    • geoip_database_info — Get GeoIP Database information
    • geoip_db_avail — Determine if GeoIP Database is available
    • geoip_db_filename — Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info — Returns detailed information about all GeoIP database types
    • geoip_id_by_name — Get the Internet connection type
    • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
    • geoip_org_by_name — Get the organization name
    • geoip_record_by_name — Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name — Get the country code and region
    • geoip_region_name_by_code — Returns the region name for some country and region code combo
    • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo
Inne podstawowe rozszerzenia
Wstęp
Inne podstawowe rozszerzenia


Wstęp

The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP.

GeoIP
Instalacja/Konfiguracja
GeoIP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
GeoIP


Wymagania

This extension requires the GeoIP C library version 1.4.0 or higher to be installed. You can grab the latest version from » http://www.maxmind.com/app/c and compile it yourself.

By default, you will only have access to the Free GeoIP Country or GeoLite City databases. While this module can work with other types of database, you must buy a commercial license from » Maxmind.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/geoip.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

GEOIP_COUNTRY_EDITION (integer)
GEOIP_REGION_EDITION_REV0 (integer)
GEOIP_CITY_EDITION_REV0 (integer)
GEOIP_ORG_EDITION (integer)
GEOIP_ISP_EDITION (integer)
GEOIP_CITY_EDITION_REV1 (integer)
GEOIP_REGION_EDITION_REV1 (integer)
GEOIP_PROXY_EDITION (integer)
GEOIP_ASNUM_EDITION (integer)
GEOIP_NETSPEED_EDITION (integer)
GEOIP_DOMAIN_EDITION (integer)

The following constants are for net speed:

GEOIP_UNKNOWN_SPEED (integer)
GEOIP_DIALUP_SPEED (integer)
GEOIP_CABLEDSL_SPEED (integer)
GEOIP_CORPORATE_SPEED (integer)
Typy zasobów
GeoIP Funkcje
GeoIP


GeoIP Funkcje

Spis treści

  • geoip_continent_code_by_name — Get the two letter continent code
  • geoip_country_code_by_name — Get the two letter country code
  • geoip_country_code3_by_name — Get the three letter country code
  • geoip_country_name_by_name — Get the full country name
  • geoip_database_info — Get GeoIP Database information
  • geoip_db_avail — Determine if GeoIP Database is available
  • geoip_db_filename — Returns the filename of the corresponding GeoIP Database
  • geoip_db_get_all_info — Returns detailed information about all GeoIP database types
  • geoip_id_by_name — Get the Internet connection type
  • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
  • geoip_org_by_name — Get the organization name
  • geoip_record_by_name — Returns the detailed City information found in the GeoIP Database
  • geoip_region_by_name — Get the country code and region
  • geoip_region_name_by_code — Returns the region name for some country and region code combo
  • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo
Stałe predefiniowane
geoip_continent_code_by_name
GeoIP


Get the two letter continent code

GeoIP Funkcje
geoip_country_code_by_name
GeoIP Funkcje
PHP Manual

geoip_continent_code_by_name

(PECL geoip >= 1.0.3)

geoip_continent_code_by_name — Get the two letter continent code

Opis

string geoip_continent_code_by_name ( string $hostname )

The geoip_continent_code_by_name() function will return the two letter continent code corresponding to a hostname or an IP address.

Parametry

hostname

The hostname or IP address whose location is to be looked-up.

Zwracane wartości

Returns the two letter continent code on success, or FALSE if the address cannot be found in the database.

Przykłady

Przykład #1 A geoip_continent_code_by_name() example

This will print where the host example.com is located.

<?php
$continent = geoip_continent_code_by_name('www.example.com');
if ($continent) {
    echo 'This host is located in: ' . $continent;
}
?>

Powyższy przykład wyświetli:

 This host is located in: NA

Zobacz też:

  • geoip_country_code_by_name() - Get the two letter country code

GeoIP Funkcje
geoip_country_code_by_name
GeoIP Funkcje


Get the two letter country code

geoip_continent_code_by_name
geoip_country_code3_by_name
GeoIP Funkcje
PHP Manual

geoip_country_code_by_name

(PECL geoip >= 0.2.0)

geoip_country_code_by_name — Get the two letter country code

Opis

string geoip_country_code_by_name ( string $hostname )

The geoip_country_code_by_name() function will return the two letter country code corresponding to a hostname or an IP address.

Parametry

hostname

The hostname or IP address whose location is to be looked-up.

Zwracane wartości

Returns the two letter ISO country code on success, or FALSE if the address cannot be found in the database.

Przykłady

Przykład #1 A geoip_country_code_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

Powyższy przykład wyświetli:

This host is located in: US

Zobacz też:

  • geoip_country_code3_by_name() - Get the three letter country code
  • geoip_country_name_by_name() - Get the full country name

geoip_continent_code_by_name
geoip_country_code3_by_name
GeoIP Funkcje


Get the three letter country code

geoip_country_code_by_name
geoip_country_name_by_name
GeoIP Funkcje
PHP Manual

geoip_country_code3_by_name

(PECL geoip >= 0.2.0)

geoip_country_code3_by_name — Get the three letter country code

Opis

string geoip_country_code3_by_name ( string $hostname )

The geoip_country_code3_by_name() function will return the three letter country code corresponding to a hostname or an IP address.

Parametry

hostname

The hostname or IP address whose location is to be looked-up.

Zwracane wartości

Returns the three letter country code on success, or FALSE if the address cannot be found in the database.

Przykłady

Przykład #1 A geoip_country_code3_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code3_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

Powyższy przykład wyświetli:

This host is located in: USA

Zobacz też:

  • geoip_country_code_by_name() - Get the two letter country code
  • geoip_country_name_by_name() - Get the full country name

geoip_country_code_by_name
geoip_country_name_by_name
GeoIP Funkcje


Get the full country name

geoip_country_code3_by_name
geoip_database_info
GeoIP Funkcje
PHP Manual

geoip_country_name_by_name

(PECL geoip >= 0.2.0)

geoip_country_name_by_name — Get the full country name

Opis

string geoip_country_name_by_name ( string $hostname )

The geoip_country_name_by_name() function will return the full country name corresponding to a hostname or an IP address.

Parametry

hostname

The hostname or IP address whose location is to be looked-up.

Zwracane wartości

Returns the country name on success, or FALSE if the address cannot be found in the database.

Przykłady

Przykład #1 A geoip_country_name_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_name_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

Powyższy przykład wyświetli:

 This host is located in: United States

Zobacz też:

  • geoip_country_code_by_name() - Get the two letter country code
  • geoip_country_code3_by_name() - Get the three letter country code

geoip_country_code3_by_name
geoip_database_info
GeoIP Funkcje


Get GeoIP Database information

geoip_country_name_by_name
geoip_db_avail
GeoIP Funkcje
PHP Manual

geoip_database_info

(PECL geoip >= 0.2.0)

geoip_database_info — Get GeoIP Database information

Opis

string geoip_database_info ([ int $database = GEOIP_COUNTRY_EDITION ] )

The geoip_database_info() function returns the corresponding GeoIP Database version as it is defined inside the binary file.

If this function is called without arguments, it returns the version of the GeoIP Free Country Edition.

Parametry

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Zwracane wartości

Returns the corresponding database version, or NULL on error.

Przykłady

Przykład #1 A geoip_region_by_name() example

This will output the current database version string.

<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

Powyższy przykład wyświetli:

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

geoip_country_name_by_name
geoip_db_avail
GeoIP Funkcje


Determine if GeoIP Database is available

geoip_database_info
geoip_db_filename
GeoIP Funkcje
PHP Manual

geoip_db_avail

(PECL geoip >= 1.0.1)

geoip_db_avail — Determine if GeoIP Database is available

Opis

bool geoip_db_avail ( int $database )

The geoip_db_avail() function returns if the corresponding GeoIP Database is available and can be opened on disk.

It does not indicate if the file is a proper database, only if it is readable.

Parametry

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Zwracane wartości

Returns TRUE is database exists, FALSE if not found, or NULL on error.

Przykłady

Przykład #1 A geoip_db_avail() example

This will output the current database version string.

<?php

if (geoip_db_avail(GEOIP_COUNTRY_EDITION))
    print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

Powyższy przykład wyświetli:

GEO-106FREE 20080801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

geoip_database_info
geoip_db_filename
GeoIP Funkcje


Returns the filename of the corresponding GeoIP Database

geoip_db_avail
geoip_db_get_all_info
GeoIP Funkcje
PHP Manual

geoip_db_filename

(PECL geoip >= 1.0.1)

geoip_db_filename — Returns the filename of the corresponding GeoIP Database

Opis

string geoip_db_filename ( int $database )

The geoip_db_filename() function returns the filename of the corresponding GeoIP Database.

It does not indicate if the file exists or not on disk, only where the library is looking for the database.

Parametry

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Zwracane wartości

Returns the filename of the corresponding database, or NULL on error.

Przykłady

Przykład #1 A geoip_db_filename() example

This will output the filename of the corresponding database.

<?php

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

Powyższy przykład wyświetli:

/usr/share/GeoIP/GeoIP.dat

geoip_db_avail
geoip_db_get_all_info
GeoIP Funkcje


Returns detailed information about all GeoIP database types

geoip_db_filename
geoip_id_by_name
GeoIP Funkcje
PHP Manual

geoip_db_get_all_info

(PECL geoip >= 1.0.1)

geoip_db_get_all_info — Returns detailed information about all GeoIP database types

Opis

array geoip_db_get_all_info ( void )

The geoip_db_get_all_info() function will return detailed information as a multi-dimensional array about all the GeoIP database types.

This function is available even if no databases are installed. It will simply list them as non-available.

The names of the different keys of the returning associative array are as follows:

  • "available" -- Boolean, indicate if DB is available (see geoip_db_avail())
  • "description" -- The database description
  • "filename" -- The database filename on disk (see geoip_db_filename())

Zwracane wartości

Returns the associative array.

Przykłady

Przykład #1 A geoip_db_get_all_info() example

This will print the array containing all the information.

<?php
$infos = geoip_db_get_all_info();
if (is_array($infos)) {
    var_dump($infos);
}
?>

Powyższy przykład wyświetli:

array(11) {
  [1]=>
  array(3) {
    ["available"]=>
    bool(true)
    ["description"]=>
    string(21) "GeoIP Country Edition"
    ["filename"]=>
    string(32) "/usr/share/GeoIP/GeoIP.dat"
  }

[ ... ]

  [11]=>
  array(3) {
    ["available"]=>
    bool(false)
    ["description"]=>
    string(25) "GeoIP Domain Name Edition"
    ["filename"]=>
    string(38) "/usr/share/GeoIP/GeoIPDomain.dat"
  }
}

Przykład #2 A geoip_db_get_all_info() example

You can use the various constants as keys to get only parts of the information.

<?php
$infos = geoip_db_get_all_info();
if ($infos[GEOIP_COUNTRY_EDITION]['available']) {
    echo $infos[GEOIP_COUNTRY_EDITION]['description'];
}
?>

Powyższy przykład wyświetli:

GeoIP Country Edition

geoip_db_filename
geoip_id_by_name
GeoIP Funkcje


Get the Internet connection type

geoip_db_get_all_info
geoip_isp_by_name
GeoIP Funkcje
PHP Manual

geoip_id_by_name

(PECL geoip >= 0.2.0)

geoip_id_by_name — Get the Internet connection type

Opis

int geoip_id_by_name ( string $hostname )

The geoip_id_by_name() function will return the Internet connection type corresponding to a hostname or an IP address.

The return value is numeric and can be compared to the following constants:

  • GEOIP_UNKNOWN_SPEED
  • GEOIP_DIALUP_SPEED
  • GEOIP_CABLEDSL_SPEED
  • GEOIP_CORPORATE_SPEED

Parametry

hostname

The hostname or IP address whose connection type is to be looked-up.

Zwracane wartości

Returns the connection type.

Przykłady

Przykład #1 A geoip_id_by_name() example

This will output the connection type of the host example.com.

<?php
$netspeed = geoip_id_by_name('www.example.com');

echo 'The connection type is ';

switch ($netspeed) {
    case GEOIP_DIALUP_SPEED:
        echo 'dial-up';
        break;
    case GEOIP_CABLEDSL_SPEED:
        echo 'cable or DSL';
        break;
    case GEOIP_CORPORATE_SPEED:
        echo 'corporate';
        break;
    case GEOIP_UNKNOWN_SPEED:
    default:
        echo 'unknown';
}
?>

Powyższy przykład wyświetli:

The connection type is corporate

geoip_db_get_all_info
geoip_isp_by_name
GeoIP Funkcje


Get the Internet Service Provider (ISP) name

geoip_id_by_name
geoip_org_by_name
GeoIP Funkcje
PHP Manual

geoip_isp_by_name

(PECL geoip >= 1.0.2)

geoip_isp_by_name — Get the Internet Service Provider (ISP) name

Opis

string geoip_isp_by_name ( string $hostname )

The geoip_isp_by_name() function will return the name of the Internet Service Provider (ISP) that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP ISP Edition. A warning will be issued if the proper database cannot be located.

Parametry

hostname

The hostname or IP address.

Zwracane wartości

Returns the ISP name on success, or FALSE if the address cannot be found in the database.

Przykłady

Przykład #1 A geoip_isp_by_name() example

This will print the ISP name of host example.com.

<?php
$isp = geoip_isp_by_name('www.example.com');
if ($isp) {
    echo 'This host IP is from ISP: ' . $isp;
}
?>

Powyższy przykład wyświetli:

This host IP is from ISP: ICANN c/o Internet Assigned Numbers Authority

geoip_id_by_name
geoip_org_by_name
GeoIP Funkcje


Get the organization name

geoip_isp_by_name
geoip_record_by_name
GeoIP Funkcje
PHP Manual

geoip_org_by_name

(PECL geoip >= 0.2.0)

geoip_org_by_name — Get the organization name

Opis

string geoip_org_by_name ( string $hostname )

The geoip_org_by_name() function will return the name of the organization that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP Organization, ISP or AS Edition. A warning will be issued if the proper database cannot be located.

Parametry

hostname

The hostname or IP address.

Zwracane wartości

Returns the organization name on success, or FALSE if the address cannot be found in the database.

Przykłady

Przykład #1 A geoip_org_by_name() example

This will print to whom the host example.com IP is allocated.

<?php
$org = geoip_org_by_name('www.example.com');
if ($org) {
    echo 'This host IP is allocated to: ' . $org;
}
?>

Powyższy przykład wyświetli:

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority

geoip_isp_by_name
geoip_record_by_name
GeoIP Funkcje


Returns the detailed City information found in the GeoIP Database

geoip_org_by_name
geoip_region_by_name
GeoIP Funkcje
PHP Manual

geoip_record_by_name

(PECL geoip >= 0.2.0)

geoip_record_by_name — Returns the detailed City information found in the GeoIP Database

Opis

array geoip_record_by_name ( string $hostname )

The geoip_record_by_name() function will return the record information corresponding to a hostname or an IP address.

This function is available for both GeoLite City Edition and commercial GeoIP City Edition. A warning will be issued if the proper database cannot be located.

The names of the different keys of the returning associative array are as follows:

  • "continent_code" -- Two letter continent code (as of version 1.0.4 with libgeoip 1.4.3 or newer)
  • "country_code" -- Two letter country code (see geoip_country_code_by_name())
  • "country_code3" -- Three letter country code (see geoip_country_code3_by_name())
  • "country_name" -- The country name (see geoip_country_name_by_name())
  • "region" -- The region code (ex: CA for California)
  • "city" -- The city.
  • "postal_code" -- The Postal Code, FSA or Zip Code.
  • "latitude" -- The Latitude as signed double.
  • "longitude" -- The Longitude as signed double.
  • "dma_code" -- Designated Market Area code (USA and Canada only)
  • "area_code" -- The PSTN area code (ex: 212)

Parametry

hostname

The hostname or IP address whose record is to be looked-up.

Zwracane wartości

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Rejestr zmian

Wersja | Opis
1.0.4 | Adding the continent_code with GeoIP Library 1.4.3 or newer only
1.0.3 | Adding country_code3 and country_name

Przykłady

Przykład #1 A geoip_record_by_name() example

This will print the array containing the record of host example.com.

<?php
$record = geoip_record_by_name('www.example.com');
if ($record) {
    print_r($record);
}
?>

Powyższy przykład wyświetli:

Array
(
    [continent_code] => NA
    [country_code] => US
    [country_code3] => USA
    [country_name] => United States
    [region] => CA
    [city] => Marina Del Rey
    [postal_code] =>
    [latitude] => 33.9776992798
    [longitude] => -118.435096741
    [dma_code] => 803
    [area_code] => 310
)

geoip_org_by_name
geoip_region_by_name
GeoIP Funkcje


Get the country code and region

geoip_record_by_name
geoip_region_name_by_code
GeoIP Funkcje
PHP Manual

geoip_region_by_name

(PECL geoip >= 0.2.0)

geoip_region_by_name — Get the country code and region

Opis

array geoip_region_by_name ( string $hostname )

The geoip_region_by_name() function will return the country and region corresponding to a hostname or an IP address.

This function is currently only available to users who have bought a commercial GeoIP Region Edition. A warning will be issued if the proper database cannot be located.

The names of the different keys of the returning associative array are as follows:

  • "country_code" -- Two letter country code (see geoip_country_code_by_name())
  • "region" -- The region code (ex: CA for California)

Parametry

hostname

The hostname or IP address whose region is to be looked-up.

Zwracane wartości

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Przykłady

Przykład #1 A geoip_region_by_name() example

This will print the array containing the country code and region of the host example.com.

<?php
$region = geoip_region_by_name('www.example.com');
if ($region) {
    print_r($region);
}
?>

Powyższy przykład wyświetli:

Array
(
    [country_code] => US
    [region] => CA
)

geoip_record_by_name
geoip_region_name_by_code
GeoIP Funkcje


Returns the region name for some country and region code combo

geoip_region_by_name
geoip_time_zone_by_country_and_region
GeoIP Funkcje
PHP Manual

geoip_region_name_by_code

(PECL geoip >= 1.0.4)

geoip_region_name_by_code — Returns the region name for some country and region code combo

Opis

string geoip_region_name_by_code ( string $country_code , string $region_code )

The geoip_region_name_by_code() function will return the region name corresponding to a country and region code combo.

In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post.

For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check » http://www.maxmind.com/app/fips10_4 for a detailed list of FIPS 10-4 codes.

This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database.

Parametry

country_code

The two-letter country code (see geoip_country_code_by_name())

region_code

The two-letter (or digit) region code (see geoip_region_by_name())

Zwracane wartości

Returns the region name on success, or FALSE if the country and region code combo cannot be found.

Przykłady

Przykład #1 A geoip_region_name_by_code() example using region code for US/Canada

This will print the region name for country CA (Canada), region QC (Quebec).

<?php
$region = geoip_region_name_by_code('CA', 'QC');
if ($region) {
    echo 'Region name for CA/QC is: ' . $region;
}
?>

Powyższy przykład wyświetli:

Region name for CA/QC is: Quebec

Przykład #2 A geoip_region_name_by_code() example using FIPS codes

This will print the region name for country JP (Japan), region 01.

<?php
$region = geoip_region_name_by_code('JP', '01');
if ($region) {
    echo 'Region name for JP/01 is: ' . $region;
}
?>

Powyższy przykład wyświetli:

Region name for JP/01 is: Aichi

geoip_region_by_name
geoip_time_zone_by_country_and_region
GeoIP Funkcje


Returns the time zone for some country and region code combo

geoip_region_name_by_code
JSON
GeoIP Funkcje
PHP Manual

geoip_time_zone_by_country_and_region

(PECL geoip >= 1.0.4)

geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo

Opis

string geoip_time_zone_by_country_and_region ( string $country_code [, string $region_code ] )

The geoip_time_zone_by_country_and_region() function will return the time zone corresponding to a country and region code combo.

In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post.

For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check » http://www.maxmind.com/app/fips10_4 for a detailed list of FIPS 10-4 codes.

This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database.

Parametry

country_code

The two-letter country code (see geoip_country_code_by_name())

region_code

The two-letter (or digit) region code (see geoip_region_by_name())

Zwracane wartości

Returns the time zone on success, or FALSE if the country and region code combo cannot be found.

Przykłady

Przykład #1 A geoip_time_zone_by_country_and_region() example using region code for US/Canada

This will print the time zone for country CA (Canada), region QC (Quebec).

<?php
$timezone = geoip_time_zone_by_country_and_region('CA', 'QC');
if ($timezone) {
    echo 'Time zone for CA/QC is: ' . $timezone;
}
?>

Powyższy przykład wyświetli:

Time zone for CA/QC is: America/Montreal

Przykład #2 A geoip_time_zone_by_country_and_region() example using FIPS codes

This will print the time zone for country JP (Japan), region 01 (Aichi).

<?php
$timezone = geoip_time_zone_by_country_and_region('JP', '01');
if ($timezone) {
    echo 'Time zone for JP/01 is: ' . $timezone;
}
?>

Powyższy przykład wyświetli:

Time zone for JP/01 is: Asia/Tokyo

geoip_region_name_by_code
JSON
GeoIP Funkcje


JavaScript Object Notation

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • JsonSerializable — The JsonSerializable class
    • JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON
  • Funkcje JSON
    • json_decode — Dekoduje łańcuch JSON
    • json_encode — Zwraca JSON reprezentujący wartość
    • json_last_error — Zwraca ostatni błąd JSON
geoip_time_zone_by_country_and_region
Wstęp
Inne podstawowe rozszerzenia


Wstęp

To rozszerzenie implementuje format wymiany danych » JavaScript Object Notation (JSON). Dekodowanie jest obsługiwane przez parser oparty na kodzie JSON_checker Douglasa Crockforda.

JSON
Instalacja/Konfiguracja
JSON


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
JSON


Wymagania

By używać tych funkcji, nie trzeba niczego instalować. Są one częścią jądra PHP.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Od PHP 5.2.0 JSON jest rozszerzeniem standardowym i domyślnie skompilowanym z 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/json

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Poniższe stałe definiują typy błędów zwracanych za pomocą json_last_error(). Stałe są dostępne od PHP 5.3.0.

JSON_ERROR_NONE (integer)
Nie wystąpił żaden błąd.
JSON_ERROR_DEPTH (integer)
Przekroczono maksymalny poziom zagnieżdżenia danych.
JSON_ERROR_CTRL_CHAR (integer)
Błąd znaku kontrolnego. Prawdopodobnie został on nieprawidłowo zakodowany.
JSON_ERROR_SYNTAX (integer)
Błąd składni.
JSON_ERROR_UTF8 (integer)
Spreparowane znaki UTF-8. Możliwe, że nieprawidłowo zakodowane. Ta stała jest dostępna od PHP 5.3.1.

Następujące stałe mogą być użyte jako kombinacja opcji dla json_encode(). Stałe dostępne są od PHP 5.3.0.

JSON_HEX_TAG (integer)
Konwertuje wszystkie < i > na \u003C i \u003E.
JSON_HEX_AMP (integer)
Konwertuje wszystkie & na \u0026.
JSON_HEX_APOS (integer)
Konwertuje wszystkie pojedyńcze cudzyszłowy ' na \u0027.
JSON_HEX_QUOT (integer)
Konwertuje wszystkie podwójne cudzysłowy " na \u0022.
JSON_FORCE_OBJECT (integer)
Zwraca obiekt zamiast tablicy, kiedy zostanie użyta nieasocjacyjna tablica. Jest to szczególnie użyteczne, kiedy na wyjściu oczekujemy obiektu, a tablica jest pusta.
Typy zasobów
JsonSerializable
JSON


The JsonSerializable class

(PHP 5 >= 5.4.0)

Wstęp

Krótki opis klasy

JsonSerializable {
/* Metody */
abstract public mixed jsonSerialize ( void )
}

Spis treści

  • JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON
Stałe predefiniowane
JsonSerializable::jsonSerialize
JSON


Specify data which should be serialized to JSON

JsonSerializable
Funkcje JSON
JsonSerializable
PHP Manual

JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0)

JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON

Opis

abstract public mixed JsonSerializable::jsonSerialize ( 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

Return data which should be serialized by json_encode().

JsonSerializable
Funkcje JSON
JsonSerializable


Funkcje JSON

Spis treści

  • json_decode — Dekoduje łańcuch JSON
  • json_encode — Zwraca JSON reprezentujący wartość
  • json_last_error — Zwraca ostatni błąd JSON
JsonSerializable::jsonSerialize
json_decode
JSON


Dekoduje łańcuch JSON

Funkcje JSON
json_encode
Funkcje JSON
PHP Manual

json_decode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_decode — Dekoduje łańcuch JSON

Opis

mixed json_decode ( string $json [, bool $asocjacyjnie = false [, int $poziom_zagłębienia = 512 [, int $opcje = 0 ]]] )

Konwertuje łańcuch JSON do zmiennej PHP.

Parametry

json

Dekodowany json string.

Ta funkcja działa tylko z danymi w kodowaniu znaków UTF-8.

asocjacyjnie

Gdy jest ustawiony na TRUE, zwracane obiekty zostaną przekonwertowane do tablic asocjacyjnych.

poziom_zagłębienia

Limit zagnieżdżania danych określony przez użytkownika.

opcje

Maska bitowa - opcje dekodowania JSON. Obecnie obsługiwana jest tylko JSON_BIGINT_AS_STRING (domyślnie jest rzutowanie typów large integer na float)

Ta zmiana istnieje w wersji testowej PHP, i będzie prawdopodobnie istniała w nowszych wersjach niż PHP 5.3.

Zwracane wartości

Zwraca wartość zakodowaną w json w odpowiednim typie PHP. Wartości true, false i null (niezależnie od wielkości liter) są zwracane odpowiednio jako TRUE, FALSE i NULL. NULL jest zwracany jeśli parametr json nie może zostać odkodowany, lub jeżeli zakodowane dane znajdują się głębiej niż ustalony limit zagnieżdżania.

Przykłady

Przykład #1 Przykład json_decode()

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

Powyższy przykład wyświetli:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Przykład #2 Inny przykład

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

Przykład #3 Różne przykłady błędów json_decode()

<?php

// poniższe łańcucy są prawidłowe w JavaScript, ale nieprawidłowe w JSON

// nazwa i wartość musi być zawarta w podwójny cudzysłów
// pojedyńcze cudzysłowy nie są prawidłowe
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// nazwa musi być zawarta w podwójny cudzysłów
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// przecinki na końcu nie są dozwolone
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Przykład #4 Błędy - poziom zagłębienia

<?php
// Kodowanie danych.
$json = json_encode(
    array(
        1 => array(
            'English' => array(
                'One',
                'January'
            ),
            'Polish' => array(
                'Jeden',
                'Styczeń'
            )
        )
    )
);

// Określenie błędów.
$json_errors = array(
    JSON_ERROR_NONE => 'Nie wystąpił żaden błąd',
    JSON_ERROR_DEPTH => 'Przekroczono maksymalny poziom zagłębienia',
    JSON_ERROR_CTRL_CHAR => 'Błąd zanku sterującego, prawdopodobnie nieprawidłowo zakodowany',
    JSON_ERROR_SYNTAX => 'Błąd składni',
);

// Pokaż błędy na różych poziomach zagłębienia.
foreach(range(4, 3, -1) as $depth) {
    var_dump(json_decode($json, True, $depth));
    echo 'Ostatni błąd : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
    }
?>

Powyższy przykład wyświetli:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["Polish"]=>
    array(2) {
      [0]=>
      string(3) "Jeden"
      [1]=>
      string(7) "Styczeń"
    }
  }
}
Ostatni błąd : Nie wystąpił żaden błąd

NULL
Ostatni błąd : Przekroczono maksymalny poziom zagłębienia

Przykład #5 Dekodowanie json_decode() - large integers

<?php
$json = '12345678901234567890';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

?>

Powyższy przykład wyświetli:

float(1.2345678901235E+19)
string(20) "12345678901234567890"

Notatki

Informacja:

Specyfikacja JSON nie jest taka sama jak w JavaScript, tylko jest podzbiorem JavaScript.

Informacja:

W przypadku niepowodzenia dekodowania danych funkcja json_last_error() może zostać użyta do ścisłego ustalenia rodzaju błędu.

Rejestr zmian

Wersja | Opis
Zmiany w przyszłości | Dodano parametr opcje.
5.3.0 | Dodano opcjonalny parametr poziom_zagłębienia. Domyślny limit zagnieżdżania danych został zwiększony z 128 do 512
5.2.3 | Limit zagnieżdżania danych został zwiększony z 20 do 128

Zobacz też:

  • json_encode() - Zwraca JSON reprezentujący wartość
  • json_last_error() - Zwraca ostatni błąd JSON

Funkcje JSON
json_encode
Funkcje JSON


Zwraca JSON reprezentujący wartość

json_decode
json_last_error
Funkcje JSON
PHP Manual

json_encode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_encode — Zwraca JSON reprezentujący wartość

Opis

string json_encode ( mixed $wartość [, int $opcje = 0 ] )

Zwraca łańcuch JSON reprezentujący wartość.

Parametry

wartość

wartość zostanie zakodowana i może być dowolnego typu, wykluczając zasoby.

Ta funkcja działa tylko na danych zakodowanych w formacie UTF-8.

opcje

Struktura bitów składająca się z JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT.

Zwracane wartości

W przypadku powodzenia zwraca zakodowany string JSON.

Rejestr zmian

Wersja | Opis
5.3.0 | Dodano parametr opcje.
5.2.1 | Dodano do JSON obsługę kodowania podstawowych typów.

Przykłady

Przykład #1 Przykład json_encode()

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?>

Powyższy przykład wyświetli:

{"a":1,"b":2,"c":3,"d":4,"e":5}

Przykład #2 Przykład json_encode() pokazuje zastosowanie parametru: opcje

<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&');

echo "Standardowo: ", json_encode($a), "\n";
echo "Znaczniki: ",   json_encode($a,JSON_HEX_TAG), "\n";
echo "Apostrofy: ",   json_encode($a,JSON_HEX_APOS), "\n";
echo "Cudzysłowy: ",   json_encode($a,JSON_HEX_QUOT), "\n";
echo "Znaki et (etki): ",    json_encode($a,JSON_HEX_AMP), "\n";
echo "Wszystkie opcje: ",    json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), "\n\n";

$b = array();

echo "Pusta tablica zwracana jako tablica: ", json_encode($b), "\n";
echo "Pusta tablica zwracana jako obiekt: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo "Nieasocjacyjna tablica zwracana jako tablica: ", json_encode($c), "\n";
echo "Nieasocjacyjna tablica zwracana jako obiekt: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";

$d = array('foo' => 'bar', 'baz' => 'long');

echo "Asocjacyjna tablica zwracana zawsze jako obiekt: ", json_encode($d), "\n";
echo "Asocjacyjna tablica zwracana zawsze jako obiekt: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>

Powyższy przykład wyświetli:

Standardowo: ["<foo>","'bar'","\"baz\"","&blong&"]
Znaczniki: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&"]
Apostrofy: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&"]
Cudzysłowy: ["<foo>","'bar'","\u0022baz\u0022","&blong&"]
Znaki et (etki): ["<foo>","'bar'","\"baz\"","\u0026blong\u0026"]
Wszystkie opcje: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026"]

Pusta tablica zwracana jako tablica: []
Pusta tablica zwracana jako obiekt: {}

Nieasocjacyjna tablica zwracana jako tablica: [[1,2,3]]
Nieasocjacyjna tablica zwracana jako obiekt: {"0":{"0":1,"1":2,"2":3}}

Asocjacyjna tablica zwracana zawsze jako obiekt: {"foo":"bar","baz":"long"}
Asocjacyjna tablica zwracana zawsze jako obiekt: {"foo":"bar","baz":"long"}

Notatki

Informacja:

W przypadku wystąpienia błędu kodowania, funkcja json_last_error() może być użyta do dokładnego określenia rodzaju błędu.

Zobacz też:

  • json_decode() - Dekoduje łańcuch JSON
  • json_last_error() - Zwraca ostatni błąd JSON

json_decode
json_last_error
Funkcje JSON


Zwraca ostatni błąd JSON

json_encode
Judy
Funkcje JSON
PHP Manual

json_last_error

(PHP 5 >= 5.3.0)

json_last_error — Zwraca ostatni błąd JSON

Opis

int json_last_error ( void )

Zwraca ostatni błąd, który wystąpił podaczas parsowania JSON.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwaraca kod błędu jako integer. Wartość może być jedną z następujących stałych:

JSON error codes
Stała | Znaczenie | Dostępność
JSON_ERROR_NONE | Nie wystąpił żaden błąd |
JSON_ERROR_DEPTH | Przekroczono maksymalny poziom zagnieżdżenia danych |
JSON_ERROR_CTRL_CHAR | Błąd znaku kontrolnego. Prawdopodobnie został nieprawidłowo zakodowany |
JSON_ERROR_STATE_MISMATCH | Niepoprawny składniowo lub zniekształcony JSON |
JSON_ERROR_SYNTAX | Błąd składni |
JSON_ERROR_UTF8 | Nieprawidłowe znaki UTF-8. Możliwe, że nieprawidłowo zakodowane | PHP 5.3.3

Przykłady

Przykład #1 Przykład json_last_error()

<?php
// Prawidłowy łańcuch znaków JSON
$json[] = '{"Organizacja": "PHP Documentation Team"}';

// Nieprawidłowy łańcuch znaków JSON spowoduje błąd składni.
// W tym przypadku został użyty znak ' zamiast "
$json[] = "{'Organizacja': 'PHP Documentation Team'}";

foreach($json as $string)
{
    echo 'Dekodowanie: ' . $string;
    json_decode($string);

    switch(json_last_error())
    {
        case JSON_ERROR_DEPTH:
            echo ' - Przekroczono maksymalny poziom zagnieżdżania danych';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Znaleziono niespodziewany znak kontrolny';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Błąd składni. Źle skonstruowany JSON';
        break;
        case JSON_ERROR_NONE:
            echo ' - Brak błędów';
        break;
    }

    echo PHP_EOL;
}
?>

Powyższy przykład wyświetli:

Decoding: {"Organizacja": "PHP Documentation Team"} - Brak błędów
Decoding: {'Organizacja': 'PHP Documentation Team'} - Błąd składni. Źle skonstruowany JSON

Zobacz też:

  • json_decode() - Dekoduje łańcuch JSON

json_encode
Judy
Funkcje JSON


Judy Arrays

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Judy — The Judy class
    • Judy::byCount — Locate the Nth index present in the Judy array
    • Judy::__construct — Construct a new Judy object
    • Judy::count — Count the number of elements in the Judy array
    • Judy::__destruct — Destruct a Judy object
    • Judy::first — Search for the first index in the Judy array
    • Judy::firstEmpty — Search for the first absent index in the Judy array
    • Judy::free — Free the entire Judy array
    • Judy::getType — Return the type of the current Judy array
    • Judy::last — Search for the last index in the Judy array
    • Judy::lastEmpty — Search for the last absent index in the Judy array
    • Judy::memoryUsage — Return the memory used by the Judy array
    • Judy::next — Search for the next index in the Judy array
    • Judy::nextEmpty — Search for the next absent index in the Judy array
    • Judy::offsetExists — Whether a offset exists
    • Judy::offsetGet — Offset to retrieve
    • Judy::offsetSet — Offset to set
    • Judy::offsetUnset — Offset to unset
    • Judy::prev — Search for the previous index in the Judy array
    • Judy::prevEmpty — Search for the previous absent index in the Judy array
    • Judy::size — Return the size of the current Judy array
  • Judy Funkcje
    • judy_type — Return the type of a Judy array
    • judy_version — Return or print the current PHP Judy version
json_last_error
Wstęp
Inne podstawowe rozszerzenia


Wstęp

PHP Judy is a PECL extension for the » Judy C library implementing dynamic sparse arrays.

A Judy array is a complex but very fast associative array data structure for storing and looking up values using integer or string keys. Unlike normal arrays, Judy arrays may be sparse; that is, they may have large ranges of unassigned indices.

A Judy array consumes memory only when populated yet can grow to take advantage of all available memory. Judy's key benefits are: scalability, performance, memory efficiency, and ease of use. Judy arrays are designed to grow without tuning into the peta-element range, scaling near O(log-base-256) -- 1 more RAM access at 256 X population.

Judy
Instalacja/Konfiguracja
Judy


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Judy


Wymagania

This extension require the » Judy C library.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/judy

The latest PECL/judy Win32 DLL is available here: » php_judy.dll

Installation on Linux Systems

From sources

Download and install » libJudy, then :

     phpize
     ./configure --with-judy[=DIR]
     make
     make test
     make install

Ubuntu/Debian

libJudy can be installed with apt-get :

    apt-get install libjudydebian1 libjudy-dev
Then by installing the Judy extension from PECL or from the sources.

Installation on Windows Systems

Download » libJudy, then extract the sources and open the Visual Studio command prompt and navigate to the source directory. Then execute :

build
This creates "Judy.lib", copy this into the php-sdk library folder and name it "libJudy.lib" Then copy the include file "judy.h" into the php-sdk includes folder.

Next, the PHP Judy extension can be installed from PECL or from the sources by extracting the pecl/judy into your build folder where the build scripts will be able to pick it up, e.g.:

    C:\php\pecl\judy\
If your source of PHP is located in:
    C:\php\src\
The rest of the steps is pretty straight forward, like any other external extension:
    buildconf
    configure --with-judy=shared
    nmake

Installation on Mac OS X

Download and install » libJudy. Then install the Judy extension from PECL or from the sources.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
Judy
Instalacja/Konfiguracja


The Judy class

(No version information available, might only be in SVN)

Wstęp

The Judy class implements the ArrayAccess interface and the Iterator interface. This class, once instantiated, can be accessed like a PHP array.

A PHP Judy object (or Judy Array) can be one of the following type :

  • Judy::BITSET
  • Judy::INT_TO_INT
  • Judy::INT_TO_MIXED
  • Judy::STRING_TO_INT
  • Judy::STRING_TO_MIXED

Przykład #1 Judy array example

<?php
    $judy = new Judy(Judy::INT_TO_MIXED);
    $judy[1] = "one";
    $judy[2] = array('a', 'b', 'c');
    $judy[3] = new Judy(Judy::BITSET);
?>

Krótki opis klasy

Judy implements ArrayAccess , Iterator {
/* Constants */
const integer BITSET = 1 ;
const integer INT_TO_INT = 2 ;
const integer INT_TO_MIXED = 3 ;
const integer STRING_TO_INT = 4 ;
const integer STRING_TO_MIXED = 5 ;
/* Metody */
public int byCount ( int $nth_index )
public __construct ( int $judy_type )
public int count ([ int $index_start = 0 [, int $index_end = -1 ]] )
public void __destruct ( void )
public mixed first ([ mixed $index ] )
public int firstEmpty ([ mixed $index = 0 ] )
public int free ( void )
public int getType ( void )
public void last ([ string $index ] )
public int lastEmpty ([ int $index = -1 ] )
public int memoryUsage ( void )
public mixed next ( mixed $index )
public int nextEmpty ( int $index )
public bool offsetExists ( mixed $offset )
public mixed offsetGet ( mixed $offset )
public bool offsetSet ( mixed $offset , mixed $value )
public bool offsetUnset ( mixed $offset )
public mixed prev ( mixed $index )
public int prevEmpty ( mixed $index )
public void size ( void )
}

Stałe predefiniowane

Judy::BITSET

Define the Judy Array as a Bitset with keys as Integer and Values as a Boolean

Judy::INT_TO_INT

Define the Judy Array with key/values as Integer, and Integer only.

Judy::INT_TO_MIXED

Define the Judy Array with keys as Integer and Values of any type.

Judy::STRING_TO_INT

Define the Judy Array with keys as a String and Values as Integer, and Integer only.

Judy::STRING_TO_MIXED

Define the Judy Array with keys as a String and Values of any type.

Spis treści

  • Judy::byCount — Locate the Nth index present in the Judy array
  • Judy::__construct — Construct a new Judy object
  • Judy::count — Count the number of elements in the Judy array
  • Judy::__destruct — Destruct a Judy object
  • Judy::first — Search for the first index in the Judy array
  • Judy::firstEmpty — Search for the first absent index in the Judy array
  • Judy::free — Free the entire Judy array
  • Judy::getType — Return the type of the current Judy array
  • Judy::last — Search for the last index in the Judy array
  • Judy::lastEmpty — Search for the last absent index in the Judy array
  • Judy::memoryUsage — Return the memory used by the Judy array
  • Judy::next — Search for the next index in the Judy array
  • Judy::nextEmpty — Search for the next absent index in the Judy array
  • Judy::offsetExists — Whether a offset exists
  • Judy::offsetGet — Offset to retrieve
  • Judy::offsetSet — Offset to set
  • Judy::offsetUnset — Offset to unset
  • Judy::prev — Search for the previous index in the Judy array
  • Judy::prevEmpty — Search for the previous absent index in the Judy array
  • Judy::size — Return the size of the current Judy array
Typy zasobów
Judy::byCount
Judy


Locate the Nth index present in the Judy array

Judy
Judy::__construct
Judy
PHP Manual

Judy::byCount

(PECL judy >= 0.1.1)

Judy::byCount — Locate the Nth index present in the Judy array

Opis

public int Judy::byCount ( int $nth_index )

Locate the Nth index present in the Judy array.

Parametry

nth_index

Nth index to return. If nth_index equal 1, then it will return the first index in the array.

Zwracane wartości

Return the index at the given Nth position.

Judy
Judy::__construct
Judy


Construct a new Judy object

Judy::byCount
Judy::count
Judy
PHP Manual

Judy::__construct

(PECL judy >= 0.1.1)

Judy::__construct — Construct a new Judy object

Opis

public Judy::__construct ( int $judy_type )

Construct a new Judy object. A Judy object can be accessed like a PHP Array.

Parametry

judy_type

The Judy type to be used.

Zwracane wartości

Return the new Judy instance.

Judy::byCount
Judy::count
Judy


Count the number of elements in the Judy array

Judy::__construct
Judy::__destruct
Judy
PHP Manual

Judy::count

(PECL judy >= 0.1.1)

Judy::count — Count the number of elements in the Judy array

Opis

public int Judy::count ([ int $index_start = 0 [, int $index_end = -1 ]] )

Count the number of elements in the Judy array.

Parametry

index_start

Start counting from the given index. Default is first index.

index_end

Stop counting when reaching this index. Default is last index.

Zwracane wartości

Return the number of elements.

Judy::__construct
Judy::__destruct
Judy


Destruct a Judy object

Judy::count
Judy::first
Judy
PHP Manual

Judy::__destruct

(PECL judy >= 0.1.1)

Judy::__destruct — Destruct a Judy object

Opis

public void Judy::__destruct ( void )

Destruct a Judy object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Judy::count
Judy::first
Judy


Search for the first index in the Judy array

Judy::__destruct
Judy::firstEmpty
Judy
PHP Manual

Judy::first

(PECL judy >= 0.1.1)

Judy::first — Search for the first index in the Judy array

Opis

public mixed Judy::first ([ mixed $index ] )

Search (inclusive) for the first index present that is equal to or greater than the passed Index.

Parametry

index

The index can be an integer or a string corresponding to the index where to start the search.

Zwracane wartości

Return the corresponding index in the array.

Judy::__destruct
Judy::firstEmpty
Judy


Search for the first absent index in the Judy array

Judy::first
Judy::free
Judy
PHP Manual

Judy::firstEmpty

(PECL judy >= 0.1.1)

Judy::firstEmpty — Search for the first absent index in the Judy array

Opis

public int Judy::firstEmpty ([ mixed $index = 0 ] )

Search (inclusive) for the first absent index that is equal to or greater than the passed Index.

Parametry

index

The index can be an integer or a string corresponding to the index where to start the search.

Zwracane wartości

Return the corresponding index in the array.

Judy::first
Judy::free
Judy


Free the entire Judy array

Judy::firstEmpty
Judy::getType
Judy
PHP Manual

Judy::free

(PECL judy >= 0.1.1)

Judy::free — Free the entire Judy array

Opis

public int Judy::free ( void )

Free the entire Judy array.

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

Judy::firstEmpty
Judy::getType
Judy


Return the type of the current Judy array

Judy::free
Judy::last
Judy
PHP Manual

Judy::getType

(PECL judy >= 0.1.1)

Judy::getType — Return the type of the current Judy array

Opis

public int Judy::getType ( void )

Return an integer corresponding to the Judy type of the current object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return an integer corresponding to a Judy type.

Judy::free
Judy::last
Judy


Search for the last index in the Judy array

Judy::getType
Judy::lastEmpty
Judy
PHP Manual

Judy::last

(PECL judy >= 0.1.1)

Judy::last — Search for the last index in the Judy array

Opis

public void Judy::last ([ string $index ] )

Search (inclusive) for the last index present that is equal to or less than the passed Index.

Parametry

index

The index can be an integer or a string corresponding to the index where to start the search.

Zwracane wartości

Return the corresponding index in the array.

Judy::getType
Judy::lastEmpty
Judy


Search for the last absent index in the Judy array

Judy::last
Judy::memoryUsage
Judy
PHP Manual

Judy::lastEmpty

(PECL judy >= 0.1.1)

Judy::lastEmpty — Search for the last absent index in the Judy array

Opis

public int Judy::lastEmpty ([ int $index = -1 ] )

Search (inclusive) for the last absent index that is equal to or less than the passed Index.

Parametry

index

The index can be an integer or a string corresponding to the index where to start the search.

Zwracane wartości

Return the corresponding index in the array.

Judy::last
Judy::memoryUsage
Judy


Return the memory used by the Judy array

Judy::lastEmpty
Judy::next
Judy
PHP Manual

Judy::memoryUsage

(PECL judy >= 0.1.1)

Judy::memoryUsage — Return the memory used by the Judy array

Opis

public int Judy::memoryUsage ( void )

Return the memory used by the Judy array.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return the memory used in bytes.

Judy::lastEmpty
Judy::next
Judy


Search for the next index in the Judy array

Judy::memoryUsage
Judy::nextEmpty
Judy
PHP Manual

Judy::next

(PECL judy >= 0.1.1)

Judy::next — Search for the next index in the Judy array

Opis

public mixed Judy::next ( mixed $index )

Search (exclusive) for the next index present that is greater than the passed Index.

Parametry

index

The index can be an integer or a string corresponding to the index where to start the search.

Zwracane wartości

Return the corresponding index in the array.

Judy::memoryUsage
Judy::nextEmpty
Judy


Search for the next absent index in the Judy array

Judy::next
Judy::offsetExists
Judy
PHP Manual

Judy::nextEmpty

(PECL judy >= 0.1.1)

Judy::nextEmpty — Search for the next absent index in the Judy array

Opis

public int Judy::nextEmpty ( int $index )

Search (exclusive) for the next absent index that is greater than the passed Index.

Parametry

index

The index can be an integer or a string corresponding to the index where to start the search.

Zwracane wartości

Return the corresponding index in the array.

Judy::next
Judy::offsetExists
Judy


Whether a offset exists

Judy::nextEmpty
Judy::offsetGet
Judy
PHP Manual

Judy::offsetExists

(PECL judy >= 0.1.1)

Judy::offsetExists — Whether a offset exists

Opis

public bool Judy::offsetExists ( mixed $offset )

Whether or not an offset exists.

Parametry

offset

An offset to check for.

Zwracane wartości

Returns TRUE on success or FALSE on failure.

Judy::nextEmpty
Judy::offsetGet
Judy


Offset to retrieve

Judy::offsetExists
Judy::offsetSet
Judy
PHP Manual

Judy::offsetGet

(PECL judy >= 0.1.1)

Judy::offsetGet — Offset to retrieve

Opis

public mixed Judy::offsetGet ( mixed $offset )

Returns the value at specified offset.

Parametry

offset

The offset to retrieve.

Zwracane wartości

Can return all value types.

Judy::offsetExists
Judy::offsetSet
Judy


Offset to set

Judy::offsetGet
Judy::offsetUnset
Judy
PHP Manual

Judy::offsetSet

(PECL judy >= 0.1.1)

Judy::offsetSet — Offset to set

Opis

public bool Judy::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

No value is returned.

Judy::offsetGet
Judy::offsetUnset
Judy


Offset to unset

Judy::offsetSet
Judy::prev
Judy
PHP Manual

Judy::offsetUnset

(PECL judy >= 0.1.1)

Judy::offsetUnset — Offset to unset

Opis

public bool Judy::offsetUnset ( mixed $offset )

Unsets an offset.

Parametry

offset

The offset to unset.

Zwracane wartości

No value is returned.

Judy::offsetSet
Judy::prev
Judy


Search for the previous index in the Judy array

Judy::offsetUnset
Judy::prevEmpty
Judy
PHP Manual

Judy::prev

(PECL judy >= 0.1.1)

Judy::prev — Search for the previous index in the Judy array

Opis

public mixed Judy::prev ( mixed $index )

Search (exclusive) for the previous index present that is less than the passed Index.

Parametry

index

The index can be an integer or a string corresponding to the index where to start the search.

Zwracane wartości

Return the corresponding index in the array.

Judy::offsetUnset
Judy::prevEmpty
Judy


Search for the previous absent index in the Judy array

Judy::prev
Judy::size
Judy
PHP Manual

Judy::prevEmpty

(PECL judy >= 0.1.1)

Judy::prevEmpty — Search for the previous absent index in the Judy array

Opis

public int Judy::prevEmpty ( mixed $index )

Search (exclusive) for the previous index absent that is less than the passed Index.

Parametry

index

The index can be an integer or a string corresponding to the index where to start the search.

Zwracane wartości

Return the corresponding index in the array.

Judy::prev
Judy::size
Judy


Return the size of the current Judy array

Judy::prevEmpty
Judy Funkcje
Judy
PHP Manual

Judy::size

(PECL judy >= 0.1.1)

Judy::size — Return the size of the current Judy array

Opis

public void Judy::size ( void )

This method is an alias of Judy::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

Return an integer.

Judy::prevEmpty
Judy Funkcje
Judy


Judy Funkcje

Spis treści

  • judy_type — Return the type of a Judy array
  • judy_version — Return or print the current PHP Judy version
Judy::size
judy_type
Judy


Return the type of a Judy array

Judy Funkcje
judy_version
Judy Funkcje
PHP Manual

judy_type

(PECL judy >= 0.1.1)

judy_type — Return the type of a Judy array

Opis

int judy_type ( Judy $array )

judy_type() return an integer corresponding to the Judy type of the specified Judy array.

Parametry

array

The Judy Array to test.

Zwracane wartości

Return an integer corresponding to a Judy type.

Judy Funkcje
judy_version
Judy Funkcje


Return or print the current PHP Judy version

judy_type
Lua
Judy Funkcje
PHP Manual

judy_version

(PECL judy >= 0.1.1)

judy_version — Return or print the current PHP Judy version

Opis

string judy_version ( void )

Return a string of the PHP Judy version. If the return value is not used, the string will be printed.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return a string of the PHP Judy version.

judy_type
Lua
Judy Funkcje


Lua

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Lua — The Lua class
    • Lua::assign — Assign a PHP variable to Lua
    • Lua::call — Call Lua functions
    • Lua::__construct — Lua constructor
    • Lua::eval — Evaluate a string as Lua code
    • Lua::getVersion — The getversion purpose
    • Lua::include — Parse a Lua script file
    • Lua::registerCallback — Register a PHP function to Lua
  • LuaClosure — The LuaClosure class
    • LuaClosure::__invoke — invoke luaclosure
judy_version
Wstęp
Inne podstawowe rozszerzenia


Wstęp

"Lua is a powerful, fast, light-weight, embeddable scripting language." This extension embeds the lua interpreter and offers an OO-API to lua variables and functions.

Lua
Instalacja/Konfiguracja
Lua


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Lua


Wymagania

To use this extension, you will need Lua installed, available on the » Lua homepage

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/lua.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
Lua
Instalacja/Konfiguracja


The Lua class

(PECL lua >=0.9.0)

Wstęp

Krótki opis klasy

Lua {
/* Constants */
const string LUA_VERSION = Lua 5.1.4 ;
/* Metody */
public mixed assign ( string $name , string $value )
public mixed call ( callback $lua_func [, array $args [, int $use_self = 0 ]] )
public mixed __call ( callback $lua_func [, array $args [, int $use_self = 0 ]] )
public __construct ( string $lua_script_file = NULL )
public mixed eval ( string $statements )
public string getVersion ( void )
public mixed include ( string $file )
public mixed registerCallback ( string $name , callback $function )
}

Stałe predefiniowane

Lua::LUA_VERSION

Spis treści

  • Lua::assign — Assign a PHP variable to Lua
  • Lua::call — Call Lua functions
  • Lua::__construct — Lua constructor
  • Lua::eval — Evaluate a string as Lua code
  • Lua::getVersion — The getversion purpose
  • Lua::include — Parse a Lua script file
  • Lua::registerCallback — Register a PHP function to Lua
Typy zasobów
Lua::assign
Lua


Assign a PHP variable to Lua

Lua
Lua::call
Lua
PHP Manual

Lua::assign

(PECL lua >=0.9.0)

Lua::assign — Assign a PHP variable to Lua

Opis

public mixed Lua::assign ( string $name , string $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Returns $this or NULL on failure.

Przykłady

Przykład #1 Lua::assign()example

<?php
$lua = new Lua();
$lua->assign("php_var", array(1=>1, 2, 3)); //lua table index begin with 1
$lua->eval(<<<CODE
    print(php_var);
CODE
);
?>

Powyższy przykład wyświetli:

Array
 (
     [1] => 1
     [2] => 2
     [3] => 3
 )
Lua
Lua::call
Lua


Call Lua functions

Lua::assign
Lua::__construct
Lua
PHP Manual

Lua::call

Lua::__call

(PECL lua >=0.9.0)

Lua::call -- Lua::__call — Call Lua functions

Opis

public mixed Lua::call ( callback $lua_func [, array $args [, int $use_self = 0 ]] )
public mixed Lua::__call ( callback $lua_func [, array $args [, int $use_self = 0 ]] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

lua_func

Function name in lua

args

Arguments passed to the Lua function

use_self

Whether to use self

Zwracane wartości

Returns result of the called function, NULL for wrong arguments or FALSE on other failure.

Przykłady

Przykład #1 Lua::call()example

<?php
$lua = new Lua();
$lua->eval(<<<CODE
    function dummy(foo, bar)
        print(foo, ",", bar)
    end
CODE
);
$lua->call("dummy", array("Lua", "geiliable\n"));
$lua->dummy("Lua", "geiliable"); // __call()
var_dump($lua->call(array("table", "concat"), array(array(1=>1, 2=>2, 3=>3), "-")));
?>

Powyższy przykład wyświetli:

Lua,geiliable
Lua,geiliable
string(5) "1-2-3"

Zobacz też:

  • __call()
Lua::assign
Lua::__construct
Lua


Lua constructor

Lua::call
Lua::eval
Lua
PHP Manual

Lua::__construct

(PECL lua >=0.9.0)

Lua::__construct — Lua constructor

Opis

public Lua::__construct ( string $lua_script_file = NULL )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

lua_script_file

Zwracane wartości

Lua::call
Lua::eval
Lua


Evaluate a string as Lua code

Lua::__construct
Lua::getVersion
Lua
PHP Manual

Lua::eval

(PECL lua >=0.9.0)

Lua::eval — Evaluate a string as Lua code

Opis

public mixed Lua::eval ( string $statements )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

statements

Zwracane wartości

Returns result of evaled code, NULL for wrong arguments or FALSE on other failure.

Przykłady

Przykład #1 Lua::eval()example

<?php
$lua = new Lua();
$lua->eval(<<<CODE
    print(2);
CODE
);
?>

Powyższy przykład wyświetli:

2
Lua::__construct
Lua::getVersion
Lua


The getversion purpose

Lua::eval
Lua::include
Lua
PHP Manual

Lua::getVersion

(PECL lua >=0.9.0)

Lua::getVersion — The getversion purpose

Opis

public string Lua::getVersion ( 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

Returns Lua::LUA_VERSION.

Lua::eval
Lua::include
Lua


Parse a Lua script file

Lua::getVersion
Lua::registerCallback
Lua
PHP Manual

Lua::include

(PECL lua >=0.9.0)

Lua::include — Parse a Lua script file

Opis

public mixed Lua::include ( string $file )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

file

Zwracane wartości

Returns result of included code, NULL for wrong arguments or FALSE on other failure.

Lua::getVersion
Lua::registerCallback
Lua


Register a PHP function to Lua

Lua::include
LuaClosure
Lua
PHP Manual

Lua::registerCallback

(No version information available, might only be in SVN)

Lua::registerCallback — Register a PHP function to Lua

Opis

public mixed Lua::registerCallback ( string $name , callback $function )

Register a PHP function to Lua as a function named "$name"

Parametry

name

function

A valid PHP function callback

Zwracane wartości

Returns $this, NULL for wrong arguments or FALSE on other failure.

Przykłady

Przykład #1 Lua::registerCallback()example

<?php
$lua = new Lua();
$lua->registerCallback("echo", "var_dump");
$lua->eval(<<<CODE
    echo({1, 2, 3});
CODE
);
?>

Powyższy przykład wyświetli:

array(3) {
  [1]=>
  float(1)
  [2]=>
  float(2)
  [3]=>
  float(3)
}
Lua::include
LuaClosure
Lua


The LuaClosure class

(PECL lua >=0.9.0)

Wstęp

LuaClosure is a wrapper class for LUA_TFUNCTION which could be return from calling to Lua function.

Krótki opis klasy

LuaClosure {
/* Metody */
public void __invoke ( mixed $arg [, mixed $... ] )
}

Spis treści

  • LuaClosure::__invoke — invoke luaclosure
Lua::registerCallback
LuaClosure::__invoke
Lua


invoke luaclosure

LuaClosure
Misc.
LuaClosure
PHP Manual

LuaClosure::__invoke

(PECL lua >=0.9.0)

LuaClosure::__invoke — invoke luaclosure

Opis

public void LuaClosure::__invoke ( mixed $arg [, mixed $... ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

arg

...

Zwracane wartości

Przykłady

Przykład #1 LuaClosure::__invoke()example

<?php
$lua = new Lua();
$closure = $lua->eval(<<<CODE
    return (function ()
        print("hello world")
    end)
CODE
);

$lua->call($closure);
/* after PHP 5.3 */
$closure();
?>

Powyższy przykład wyświetli:

hello worldhello world
LuaClosure
Misc.
LuaClosure


Miscellaneous Functions

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Misc. Funkcje
    • connection_aborted — Check whether client disconnected
    • connection_status — Returns connection status bitfield
    • connection_timeout — Check if the script timed out
    • constant — Returns the value of a constant
    • define — Defines a named constant
    • defined — Checks whether a given named constant exists
    • die — Equivalent to exit
    • eval — Evaluate a string as PHP code
    • exit — Output a message and terminate the current script
    • get_browser — Tells what the user's browser is capable of
    • __halt_compiler — Halts the compiler execution
    • highlight_file — Syntax highlighting of a file
    • highlight_string — Syntax highlighting of a string
    • ignore_user_abort — Set whether a client disconnect should abort script execution
    • pack — Pack data into binary string
    • php_check_syntax — Check the PHP syntax of (and execute) the specified file
    • php_strip_whitespace — Return source with stripped comments and whitespace
    • show_source — Alias dla highlight_file
    • sleep — Delay execution
    • sys_getloadavg — Gets system load average
    • time_nanosleep — Delay for a number of seconds and nanoseconds
    • time_sleep_until — Make the script sleep until the specified time
    • uniqid — Generate a unique ID
    • unpack — Unpack data from binary string
    • usleep — Delay execution in microseconds
LuaClosure::__invoke
Wstęp
Inne podstawowe rozszerzenia


Wstęp

These functions were placed here because none of the other categories seemed to fit.

Misc.
Instalacja/Konfiguracja
Misc.


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Misc.


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Misc. Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
ignore_user_abort | "0" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | Removed in PHP 5.4.0.
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
browscap | 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.

ignore_user_abort boolean

FALSE by default. If changed to TRUE scripts will not be terminated after a client has aborted their connection.

See also ignore_user_abort().

highlight.bg string
highlight.comment string
highlight.default string
highlight.html string
highlight.keyword string
highlight.string string

Colors for Syntax Highlighting mode. Anything that's acceptable in <font color="??????"> would work.

browscap string

Name (e.g.: browscap.ini) and location of browser capabilities file. See also get_browser().

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

CONNECTION_ABORTED (integer)
CONNECTION_NORMAL (integer)
CONNECTION_TIMEOUT (integer)
__COMPILER_HALT_OFFSET__ (integer)
Added in PHP 5.1.
Typy zasobów
Misc. Funkcje
Misc.


Misc. Funkcje

Spis treści

  • connection_aborted — Check whether client disconnected
  • connection_status — Returns connection status bitfield
  • connection_timeout — Check if the script timed out
  • constant — Returns the value of a constant
  • define — Defines a named constant
  • defined — Checks whether a given named constant exists
  • die — Equivalent to exit
  • eval — Evaluate a string as PHP code
  • exit — Output a message and terminate the current script
  • get_browser — Tells what the user's browser is capable of
  • __halt_compiler — Halts the compiler execution
  • highlight_file — Syntax highlighting of a file
  • highlight_string — Syntax highlighting of a string
  • ignore_user_abort — Set whether a client disconnect should abort script execution
  • pack — Pack data into binary string
  • php_check_syntax — Check the PHP syntax of (and execute) the specified file
  • php_strip_whitespace — Return source with stripped comments and whitespace
  • show_source — Alias dla highlight_file
  • sleep — Delay execution
  • sys_getloadavg — Gets system load average
  • time_nanosleep — Delay for a number of seconds and nanoseconds
  • time_sleep_until — Make the script sleep until the specified time
  • uniqid — Generate a unique ID
  • unpack — Unpack data from binary string
  • usleep — Delay execution in microseconds
Stałe predefiniowane
connection_aborted
Misc.


Check whether client disconnected

Misc. Funkcje
connection_status
Misc. Funkcje
PHP Manual

connection_aborted

(PHP 4, PHP 5)

connection_aborted — Check whether client disconnected

Opis

int connection_aborted ( void )

Checks whether the client disconnected.

Zwracane wartości

Returns 1 if client disconnected, 0 otherwise.

Zobacz też:

  • connection_status() - Returns connection status bitfield
  • ignore_user_abort() - Set whether a client disconnect should abort script execution
  • Connection Handling for a complete description of connection handling in PHP.

Misc. Funkcje
connection_status
Misc. Funkcje


Returns connection status bitfield

connection_aborted
connection_timeout
Misc. Funkcje
PHP Manual

connection_status

(PHP 4, PHP 5)

connection_status — Returns connection status bitfield

Opis

int connection_status ( void )

Gets the connection status bitfield.

Zwracane wartości

Returns the connection status bitfield, which can be used against the CONNECTION_XXX constants to determine the connection status.

Zobacz też:

  • connection_aborted() - Check whether client disconnected
  • ignore_user_abort() - Set whether a client disconnect should abort script execution
  • Connection Handling for a complete description of connection handling in PHP.

connection_aborted
connection_timeout
Misc. Funkcje


Check if the script timed out

connection_status
constant
Misc. Funkcje
PHP Manual

connection_timeout

(PHP 4 <= 4.0.4)

connection_timeout — Check if the script timed out

Opis

int connection_timeout ( void )

Determines whether the script timed out.

Zwracane wartości

Returns 1 if the script timed out, 0 otherwise.

Notatki

Ostrzeżenie

Deprecated

This function is deprecated, and doesn't even exist anymore as of 4.0.5.

Zobacz też:

  • connection_status() - Returns connection status bitfield
  • Connection Handling for a complete description of connection handling in PHP.

connection_status
constant
Misc. Funkcje


Returns the value of a constant

connection_timeout
define
Misc. Funkcje
PHP Manual

constant

(PHP 4 >= 4.0.4, PHP 5)

constant — Returns the value of a constant

Opis

mixed constant ( string $name )

Return the value of the constant indicated by name.

constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

This function works also with class constants.

Parametry

name

The constant name.

Zwracane wartości

Returns the value of the constant, or NULL if the constant is not defined.

Błędy/Wyjątki

An E_WARNING level error is generated if the constant is not defined.

Przykłady

Przykład #1 constant() example

<?php

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

interface bar {
    const test = 'foobar!';
}

class foo {
    const test = 'foobar!';
}

$const = 'test';

var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"

?>

Zobacz też:

  • define() - Defines a named constant
  • defined() - Checks whether a given named constant exists
  • The section on Constants

connection_timeout
define
Misc. Funkcje


Defines a named constant

constant
defined
Misc. Funkcje
PHP Manual

define

(PHP 4, PHP 5)

define — Defines a named constant

Opis

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

Defines a named constant at runtime.

Parametry

name

The name of the constant.

value

The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior.

case_insensitive

If set to TRUE, the constant will be defined case-insensitive. The default behavior is case-sensitive; i.e. CONSTANT and Constant represent different values.

Informacja:

Case-insensitive constants are stored as lower-case.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.

define("GREETING", "Hello you.", true);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you."

?>

Zobacz też:

  • defined() - Checks whether a given named constant exists
  • constant() - Returns the value of a constant
  • The section on Constants

constant
defined
Misc. Funkcje


Checks whether a given named constant exists

define
die
Misc. Funkcje
PHP Manual

defined

(PHP 4, PHP 5)

defined — Checks whether a given named constant exists

Opis

bool defined ( string $name )

Checks whether the given constant exists and is defined.

Informacja:

If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().

Parametry

name

The constant name.

Zwracane wartości

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Przykłady

Przykład #1 Checking Constants

<?php
/* Note the use of quotes, this is important.  This example is checking
 * if the string 'TEST' is the name of a constant named TEST */
if (defined('TEST')) {
    echo TEST;
}
?>

Zobacz też:

  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values
  • function_exists() - Return TRUE if the given function has been defined
  • The section on Constants

define
die
Misc. Funkcje


Equivalent to exit

defined
eval
Misc. Funkcje
PHP Manual

die

(PHP 4, PHP 5)

die — Equivalent to exit()

Opis

This language construct is equivalent to exit().

defined
eval
Misc. Funkcje


Evaluate a string as PHP code

die
exit
Misc. Funkcje
PHP Manual

eval

(PHP 4, PHP 5)

eval — Evaluate a string as PHP code

Opis

mixed eval ( string $code )

Evaluates the given code as PHP.

Uwaga

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Parametry

code

Valid PHP code to be evaluated.

The code mustn't be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<? echo "Hi!"; >'. It is still possible to leave and reenter PHP mode though using the appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!<? echo "Back in PHP mode!";'.

Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon. 'echo "Hi!"' for example will cause a parse error, whereas 'echo "Hi!";' will work.

A return statement will immediately terminate the evaluation of the code.

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain visible after it terminates.

Zwracane wartości

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().

Przykłady

Przykład #1 eval() example - simple text merge

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>

Powyższy przykład wyświetli:

This is a $string with my $name in it.
This is a cup with my coffee in it.

Notatki

Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Wskazówka

Ze wszystkim, co wysyła dane bezpośrednio do przeglądarki, możesz używać funkcji kontroli wyjścia aby przejąć wyjście tej funkcji i zapisać je w zmiennej tekstowej (na przykład).

Informacja:

In case of a fatal error in the evaluated code, the whole script exits.

Zobacz też:

  • call_user_func() - Call the callback given by the first parameter

die
exit
Misc. Funkcje


Output a message and terminate the current script

eval
get_browser
Misc. Funkcje
PHP Manual

exit

(PHP 4, PHP 5)

exit — Output a message and terminate the current script

Opis

void exit ([ string $status ] )
void exit ( int $status )

Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit() is called.

Parametry

status

If status is a string, this function prints the status just before exiting.

If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

Informacja: PHP >= 4.2.0 does NOT print the status if it is an integer.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 exit() example

<?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

?>

Przykład #2 exit() status example

<?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?>

Przykład #3 Shutdown functions and destructors run regardless

<?php
class Foo
{
    public function __destruct()
    {
        echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
    }
}

function shutdown()
{
    echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
}

$foo = new Foo();
register_shutdown_function('shutdown');

exit();
echo 'This will not be output.';
?>

Powyższy przykład wyświetli:

 Shutdown: shutdown()
 Destruct: Foo::__destruct()

Notatki

Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Informacja:

This language construct is equivalent to die().

Zobacz też:

  • register_shutdown_function() - Register a function for execution on shutdown

eval
get_browser
Misc. Funkcje


Tells what the user's browser is capable of

exit
__halt_compiler
Misc. Funkcje
PHP Manual

get_browser

(PHP 4, PHP 5)

get_browser — Tells what the user's browser is capable of

Opis

mixed get_browser ([ string $user_agent [, bool $return_array = false ]] )

Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.

Parametry

user_agent

The User Agent to be analyzed. By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing this parameter.

You can bypass this parameter with a NULL value.

return_array

If set to TRUE, this function will return an array instead of an object.

Zwracane wartości

The information is returned in an object or an array which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/FALSE values for features such as frames, JavaScript, and cookies; and so forth.

The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie(), reload, and check for the value.

Rejestr zmian

Wersja | Opis
4.3.2 | The optional parameter return_array was added.

Przykłady

Przykład #1 Listing all information about the users browser

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

Powyższy przykład wyświetli coś podobnego do:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

Notatki

Informacja:

In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.

browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here.

While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

exit
__halt_compiler
Misc. Funkcje


Halts the compiler execution

get_browser
highlight_file
Misc. Funkcje
PHP Manual

__halt_compiler

(PHP 5 >= 5.1.0)

__halt_compiler — Halts the compiler execution

Opis

void __halt_compiler ( void )

Halts the execution of the compiler. This can be useful to embed data in PHP scripts, like the installation files.

Byte position of the data start can be determined by the __COMPILER_HALT_OFFSET__ constant which is defined only if there is a __halt_compiler() presented in the file.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A __halt_compiler() example

<?php

// open this file
$fp = fopen(__FILE__, 'r');

// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);

// and output it
var_dump(stream_get_contents($fp));

// the end of the script execution
__halt_compiler(); the installation data (eg. tar, gz, PHP, etc.)

Notatki

Informacja:

__halt_compiler() can only be used from the outermost scope.

get_browser
highlight_file
Misc. Funkcje


Syntax highlighting of a file

__halt_compiler
highlight_string
Misc. Funkcje
PHP Manual

highlight_file

(PHP 4, PHP 5)

highlight_file — Syntax highlighting of a file

Opis

mixed highlight_file ( string $filename [, bool $return = false ] )

Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf:

AddType application/x-httpd-php-source .phps

Parametry

filename

Path to the PHP file to be highlighted.

return

Set this parameter to TRUE to make this function return the highlighted code.

Zwracane wartości

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.

Rejestr zmian

Wersja | Opis
4.2.1 | This function is now also affected by safe_mode and open_basedir.
4.2.0 | The return parameter was added.

Notatki

Uwaga

Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

Informacja:

Ta funkcja używa wewnętrznie buforowania wyjścia, więc nie może być użyta wewnątrz funkcji callback podanej w wywołaniu ob_start().

Zobacz też:

  • highlight_string() - Syntax highlighting of a string

__halt_compiler
highlight_string
Misc. Funkcje


Syntax highlighting of a string

highlight_file
ignore_user_abort
Misc. Funkcje
PHP Manual

highlight_string

(PHP 4, PHP 5)

highlight_string — Syntax highlighting of a string

Opis

mixed highlight_string ( string $str [, bool $return = false ] )

Outputs or returns a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP.

Parametry

str

The PHP code to be highlighted. This should include the opening tag.

return

Set this parameter to TRUE to make this function return the highlighted code.

Zwracane wartości

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.

Rejestr zmian

Wersja | Opis
4.2.0 | The return parameter was added.

Przykłady

Przykład #1 highlight_string() example

<?php
highlight_string('<?php phpinfo(); ?>');
?>

The above example will output (in PHP 4):

<code><font color="#000000">
<font color="#0000BB">&lt;?php phpinfo</font><font color="#007700">(); </font><font color="#0000BB">?&gt;</font>
</font>
</code>

The above example will output (in PHP 5):

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

Notatki

Informacja:

Ta funkcja używa wewnętrznie buforowania wyjścia, więc nie może być użyta wewnątrz funkcji callback podanej w wywołaniu ob_start().

Zobacz też:

  • highlight_file() - Syntax highlighting of a file

highlight_file
ignore_user_abort
Misc. Funkcje


Set whether a client disconnect should abort script execution

highlight_string
pack
Misc. Funkcje
PHP Manual

ignore_user_abort

(PHP 4, PHP 5)

ignore_user_abort — Set whether a client disconnect should abort script execution

Opis

int ignore_user_abort ([ string $value ] )

Sets whether a client disconnect should cause a script to be aborted.

When running PHP as a command line script, and the script's tty goes away without the script being terminated then the script will die the next time it tries to write anything, unless value is set to TRUE

Parametry

value

If set, this function will set the ignore_user_abort ini setting to the given value. If not, this function will only return the previous setting without changing it.

Zwracane wartości

Returns the previous setting, as an integer.

Przykłady

Przykład #1 A ignore_user_abort() example

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

echo 'Testing connection handling in PHP';

// Run a pointless loop that sometime
// hopefully will make us click away from
// page or click the "Stop" button.
while(1)
{
    // Did the connection fail?
    if(connection_status() != CONNECTION_NORMAL)
    {
        break;
    }

    // Sleep for 10 seconds
    sleep(10);
}

// If this is reached, then the 'break'
// was triggered from inside the while loop

// So here we can log, or perform any other tasks
// we need without actually being dependent on the
// browser.
?>

Notatki

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see flush().

Zobacz też:

  • connection_aborted() - Check whether client disconnected
  • connection_status() - Returns connection status bitfield
  • Connection Handling for a complete description of connection handling in PHP.

highlight_string
pack
Misc. Funkcje


Pack data into binary string

ignore_user_abort
php_check_syntax
Misc. Funkcje
PHP Manual

pack

(PHP 4, PHP 5)

pack — Pack data into binary string

Opis

string pack ( string $format [, mixed $args [, mixed $... ]] )

Pack given arguments into binary string according to format.

The idea for this function was taken from Perl and all formatting codes work the same as in Perl. However, there are some formatting codes that are missing such as Perl's "u" format code.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

Parametry

format

The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.

Currently implemented formats are:

pack() format characters
Code | Description
a | NUL-padded string
A | SPACE-padded string
h | Hex string, low nibble first
H | Hex string, high nibble first
c | signed char
C | unsigned char
s | signed short (always 16 bit, machine byte order)
S | unsigned short (always 16 bit, machine byte order)
n | unsigned short (always 16 bit, big endian byte order)
v | unsigned short (always 16 bit, little endian byte order)
i | signed integer (machine dependent size and byte order)
I | unsigned integer (machine dependent size and byte order)
l | signed long (always 32 bit, machine byte order)
L | unsigned long (always 32 bit, machine byte order)
N | unsigned long (always 32 bit, big endian byte order)
V | unsigned long (always 32 bit, little endian byte order)
f | float (machine dependent size and representation)
d | double (machine dependent size and representation)
x | NUL byte
X | Back up one byte
@ NUL-fill to absolute position

args

Zwracane wartości

Returns a binary string containing data.

Przykłady

Przykład #1 pack() example

<?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?>

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Notatki

Uwaga

Note that PHP internally stores integer values as signed values of a machine-dependent size (C type long). Integer literals and operations that yield numbers outside the bounds of the integer type will be stored as float. When packing these floats as integers, they are first cast into the integer type. This may or may not result in the desired byte pattern.

The most relevant case is when packing unsigned numbers that would be representable with the integer type if it were unsigned. In systems where the integer type has a 32-bit size, the cast usually results in the same byte pattern as if the integer were unsigned (although this relies on implementation-defined unsigned to signed conversions, as per the C standard). In systems where the integer type has 64-bit size, the float most likely does not have a mantissa large enough to hold the value without loss of precision. If those systems also have a native 64-bit C int type (most UNIX-like systems don't), the only way to use the I pack format in the upper range is to create integer negative values with the same byte representation as the desired unsigned value.

Zobacz też:

  • unpack() - Unpack data from binary string

ignore_user_abort
php_check_syntax
Misc. Funkcje


Check the PHP syntax of (and execute) the specified file

pack
php_strip_whitespace
Misc. Funkcje
PHP Manual

php_check_syntax

(PHP 5 <= 5.0.4)

php_check_syntax — Check the PHP syntax of (and execute) the specified file

Opis

bool php_check_syntax ( string $filename [, string &$error_message ] )

Performs a syntax (lint) check on the specified filename testing for scripting errors.

This is similar to using php -l from the commandline except that this function will execute (but not output) the checked filename.

For example, if a function is defined in filename, this defined function will be available to the file that executed php_check_syntax(), but output from filename will be suppressed.

Informacja:

For technical reasons, this function is deprecated and removed from PHP. Instead, use php -l somefile.php from the commandline.

Parametry

filename

The name of the file being checked.

error_message

If the error_message parameter is used, it will contain the error message generated by the syntax check. error_message is passed by reference.

Zwracane wartości

Returns TRUE if the lint check passed, and FALSE if the link check failed or if filename cannot be opened.

Rejestr zmian

Wersja | Opis
5.0.5 | This function was removed from PHP.
5.0.3 | Calling exit() after php_check_syntax() resulted in a Segfault.
5.0.1 | error_message is passed by reference.

Przykłady

php -l somefile.php

Powyższy przykład wyświetli coś podobnego do:

PHP Parse error: unexpected T_STRING in /tmp/somefile.php on line 81

Zobacz też:

  • include()
  • is_readable() - Tells whether a file exists and is readable

pack
php_strip_whitespace
Misc. Funkcje


Return source with stripped comments and whitespace

php_check_syntax
show_source
Misc. Funkcje
PHP Manual

php_strip_whitespace

(PHP 5)

php_strip_whitespace — Return source with stripped comments and whitespace

Opis

string php_strip_whitespace ( string $filename )

Returns the PHP source code in filename with PHP comments and whitespace removed. This may be useful for determining the amount of actual code in your scripts compared with the amount of comments. This is similar to using php -w from the commandline.

Parametry

filename

Path to the PHP file.

Zwracane wartości

The stripped source code will be returned on success, or an empty string on failure.

Informacja:

This function works as described as of PHP 5.0.1. Before this it would only return an empty string. For more information on this bug and its prior behavior, see bug report » #29606.

Przykłady

Przykład #1 php_strip_whitespace() example

<?php
// PHP comment here

/*
 * Another PHP comment
 */

echo        php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
?>

Powyższy przykład wyświetli:

<?php
 echo php_strip_whitespace(__FILE__); do_nothing(); ?>

Notice the PHP comments are gone, as are the whitespace and newline after the first echo statement.

php_check_syntax
show_source
Misc. Funkcje


Alias dla highlight_file

php_strip_whitespace
sleep
Misc. Funkcje
PHP Manual

show_source

(PHP 4, PHP 5)

show_source — Alias dla highlight_file()

Opis

Ta funkcja jest aliasem dla: highlight_file().

php_strip_whitespace
sleep
Misc. Funkcje


Delay execution

show_source
sys_getloadavg
Misc. Funkcje
PHP Manual

sleep

(PHP 4, PHP 5)

sleep — Delay execution

Opis

int sleep ( int $seconds )

Delays the program execution for the given number of seconds.

Parametry

seconds

Halt time in seconds.

Zwracane wartości

Returns zero on success, or FALSE on error.

If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be 192 (the value of the WAIT_IO_COMPLETION constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep.

Błędy/Wyjątki

If the specified number of seconds is negative, this function will generate a E_WARNING.

Rejestr zmian

Wersja | Opis
5.3.4 | Before PHP 5.3.4, on Windows, sleep() always returns NULL when sleep has occurred, regardless of whether the sleep was interrupted or not.

Przykłady

Przykład #1 sleep() example

<?php

// current time
echo date('h:i:s') . "\n";

// sleep for 10 seconds
sleep(10);

// wake up !
echo date('h:i:s') . "\n";

?>

This example will output (after 10 seconds)

05:31:23
05:31:33

Zobacz też:

  • usleep() - Delay execution in microseconds
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

show_source
sys_getloadavg
Misc. Funkcje


Gets system load average

sleep
time_nanosleep
Misc. Funkcje
PHP Manual

sys_getloadavg

(PHP 5 >= 5.1.3)

sys_getloadavg — Gets system load average

Opis

array sys_getloadavg ( void )

Returns three samples representing the average system load (the number of processes in the system run queue) over the last 1, 5 and 15 minutes, respectively.

Zwracane wartości

Returns an array with three samples (last 1, 5 and 15 minutes).

Przykłady

Przykład #1 A sys_getloadavg() example

<?php
$load = sys_getloadavg();
if ($load[0] > 80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}
?>

Notatki

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

sleep
time_nanosleep
Misc. Funkcje


Delay for a number of seconds and nanoseconds

sys_getloadavg
time_sleep_until
Misc. Funkcje
PHP Manual

time_nanosleep

(PHP 5)

time_nanosleep — Delay for a number of seconds and nanoseconds

Opis

mixed time_nanosleep ( int $seconds , int $nanoseconds )

Delays program execution for the given number of seconds and nanoseconds.

Parametry

seconds

Must be a non-negative integer.

nanoseconds

Must be a non-negative integer less than 1 billion.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

If the delay was interrupted by a signal, an associative array will be returned with the components:

  • seconds - number of seconds remaining in the delay
  • nanoseconds - number of nanoseconds remaining in the delay

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.

Przykłady

Przykład #1 time_nanosleep() example

<?php
// Careful! This won't work as expected if an array is returned
if (time_nanosleep(0, 500000000)) {
    echo "Slept for half a second.\n";
}

// This is better:
if (time_nanosleep(0, 500000000) === true) {
    echo "Slept for half a second.\n";
}

// And this is the best:
$nano = time_nanosleep(2, 100000);

if ($nano === true) {
    echo "Slept for 2 seconds, 100 microseconds.\n";
} elseif ($nano === false) {
    echo "Sleeping failed.\n";
} elseif (is_array($nano)) {
    $seconds = $nano['seconds'];
    $nanoseconds = $nano['nanoseconds'];
    echo "Interrupted by a signal.\n";
    echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds.";
}
?>

Zobacz też:

  • sleep() - Delay execution
  • usleep() - Delay execution in microseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

sys_getloadavg
time_sleep_until
Misc. Funkcje


Make the script sleep until the specified time

time_nanosleep
uniqid
Misc. Funkcje
PHP Manual

time_sleep_until

(PHP 5 >= 5.1.0)

time_sleep_until — Make the script sleep until the specified time

Opis

bool time_sleep_until ( float $timestamp )

Makes the script sleep until the specified timestamp.

Parametry

timestamp

The timestamp when the script should wake.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.

Błędy/Wyjątki

If the specified timestamp is in the past, this function will generate a E_WARNING.

Przykłady

Przykład #1 A time_sleep_until() example

<?php

//returns false and generates a warning
var_dump(time_sleep_until(time()-1));

// may only work on faster computers, will sleep up to 0.2 seconds
var_dump(time_sleep_until(microtime(true)+0.2));

?>

Notatki

Informacja: All signals will be delivered after the script wakes up.

Zobacz też:

  • sleep() - Delay execution
  • usleep() - Delay execution in microseconds
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • set_time_limit() - Limits the maximum execution time

time_nanosleep
uniqid
Misc. Funkcje


Generate a unique ID

time_sleep_until
unpack
Misc. Funkcje
PHP Manual

uniqid

(PHP 4, PHP 5)

uniqid — Generate a unique ID

Opis

string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )

Gets a prefixed unique identifier based on the current time in microseconds.

Parametry

prefix

Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.

With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.

more_entropy

If set to TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which should make the results more unique.

Zwracane wartości

Returns the unique identifier, as a string.

Przykłady

Przykład #1 uniqid() Example

<?php
/* A uniqid, like: 4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());

/* We can also prefix the uniqid, this the same as
 * doing:
 *
 * $uniqid = $prefix . uniqid();
 * $uniqid = uniqid($prefix);
 */
printf("uniqid('php_'): %s\r\n", uniqid('php_'));

/* We can also activate the more_entropy parameter, which is
 * required on some systems, like Cygwin. This makes uniqid()
 * produce a value like: 4b340550242239.64159797
 */
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>

Rejestr zmian

Wersja | Opis
5.0.0 | The prefix parameter was made optional.
4.3.1 | The limit of 114 characters long for prefix was raised.

Notatki

Informacja:

Under Cygwin, the more_entropy must be set to TRUE for this function to work.

time_sleep_until
unpack
Misc. Funkcje


Unpack data from binary string

uniqid
usleep
Misc. Funkcje
PHP Manual

unpack

(PHP 4, PHP 5)

unpack — Unpack data from binary string

Opis

array unpack ( string $format , string $data )

Unpacks from a binary string into an array according to the given format.

The unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /. If a repeater argument is present, then each of the array keys will have a sequence number behind the given name.

Parametry

format

See pack() for an explanation of the format codes.

data

The packed data.

Zwracane wartości

Returns an associative array containing unpacked elements of binary string.

Przykłady

Przykład #1 unpack() example

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("cchars/nint", $binarydata);
?>

The resulting array will contain the entries "chars" with value 4 and "int" with 160.

Przykład #2 unpack() example with a repeater

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("c2chars/nint", $binarydata);
?>

The resulting array will contain the entries "chars1", "chars2" and "int".

Notatki

Uwaga

Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.

Uwaga

Be aware that if you do not name an element, an empty string is used. If you do not name more than one element, this means that some data is overwritten as the keys are the same such as in:

Przykład #3 unpack() example with unnamed keys

<?php
$binarydata = "\x32\x42\x00\xa0";
$array = unpack("c2/n", $binarydata);
var_dump($array);
?>

The resulting array will contain the entries "1" with value 160 and "2" with 66. The first value from the c specifier is overwritten by the first value from the n specifier.

Zobacz też:

  • pack() - Pack data into binary string

uniqid
usleep
Misc. Funkcje


Delay execution in microseconds

unpack
Parsekit
Misc. Funkcje
PHP Manual

usleep

(PHP 4, PHP 5)

usleep — Delay execution in microseconds

Opis

void usleep ( int $micro_seconds )

Delays program execution for the given number of micro seconds.

Parametry

micro_seconds

Halt time in micro seconds. A micro second is one millionth of a second.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
5.0.0 | This function now works on Windows systems.

Przykłady

Przykład #1 usleep() example

<?php

// Current time
echo date('h:i:s') . "\n";

// wait for 2 seconds
usleep(2000000);

// back!
echo date('h:i:s') . "\n";

?>

Powyższy przykład wyświetli:

11:13:28
11:13:30

Zobacz też:

  • sleep() - Delay execution
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time

unpack
Parsekit
Misc. Funkcje


Parsekit

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Parsekit Funkcje
    • parsekit_compile_file — Compile a string of PHP code and return the resulting op array
    • parsekit_compile_string — Compile a string of PHP code and return the resulting op array
    • parsekit_func_arginfo — Return information regarding function argument(s)
usleep
Wstęp
Inne podstawowe rozszerzenia


Wstęp

These functions allow runtime analysis of opcodes compiled from PHP scripts.

Parsekit
Instalacja/Konfiguracja
Parsekit


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Parsekit


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/parsekit.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

PARSEKIT_QUIET (int)
Return full detail, but without unnecessary NULL entries.
PARSEKIT_SIMPLE (int)
Return shorthand opcode notation.
PARSEKIT_EXTENDED_VALUE (int)
Opnode Flag
PARSEKIT_RESULT_CONST (int)
Opnode Flag
PARSEKIT_RESULT_EA_TYPE (int)
Opnode Flag
PARSEKIT_RESULT_JMP_ADDR (int)
Opnode Flag
PARSEKIT_RESULT_OPARRAY (int)
Opnode Flag
PARSEKIT_RESULT_OPLINE (int)
Opnode Flag
PARSEKIT_RESULT_VAR (int)
Opnode Flag
PARSEKIT_USAGE_UNKNOWN (int)
Opnode Flag
PARSEKIT_ZEND_INTERNAL_CLASS (int)
Class Type
PARSEKIT_ZEND_USER_CLASS (int)
Class Type
PARSEKIT_ZEND_EVAL_CODE (int)
Function Type
PARSEKIT_ZEND_INTERNAL_FUNCTION (int)
Function Type
PARSEKIT_ZEND_OVERLOADED_FUNCTION (int)
Function Type
PARSEKIT_ZEND_OVERLOADED_FUNCTION_TEMPORARY (int) PHP >= 5.0.0
Function Type
PARSEKIT_ZEND_USER_FUNCTION (int)
Function Type
PARSEKIT_IS_CONST (int)
Node Type
PARSEKIT_IS_TMP_VAR (int)
Node Type
PARSEKIT_IS_UNUSED (int)
Node Type
PARSEKIT_IS_VAR (int)
Node Type
PARSEKIT_ZEND_ADD (int)
Opcode
PARSEKIT_ZEND_ADD_ARRAY_ELEMENT (int)
Opcode
PARSEKIT_ZEND_ADD_CHAR (int)
Opcode
PARSEKIT_ZEND_ADD_INTERFACE (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ADD_STRING (int)
Opcode
PARSEKIT_ZEND_ADD_VAR (int)
Opcode
PARSEKIT_ZEND_ASSIGN (int)
Opcode
PARSEKIT_ZEND_ASSIGN_ADD (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_AND (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_OR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_XOR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_CONCAT (int)
Opcode
PARSEKIT_ZEND_ASSIGN_DIM (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ASSIGN_DIV (int)
Opcode
PARSEKIT_ZEND_ASSIGN_MOD (int)
Opcode
PARSEKIT_ZEND_ASSIGN_MUL (int)
Opcode
PARSEKIT_ZEND_ASSIGN_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ASSIGN_REF (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SL (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SUB (int)
Opcode
PARSEKIT_ZEND_BEGIN_SILENCE (int)
Opcode
PARSEKIT_ZEND_BOOL (int)
Opcode
PARSEKIT_ZEND_BOOL_NOT (int)
Opcode
PARSEKIT_ZEND_BOOL_XOR (int)
Opcode
PARSEKIT_ZEND_BRK (int)
Opcode
PARSEKIT_ZEND_BW_AND (int)
Opcode
PARSEKIT_ZEND_BW_NOT (int)
Opcode
PARSEKIT_ZEND_BW_OR (int)
Opcode
PARSEKIT_ZEND_BW_XOR (int)
Opcode
PARSEKIT_ZEND_CASE (int)
Opcode
PARSEKIT_ZEND_CAST (int)
Opcode
PARSEKIT_ZEND_CATCH (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_CLONE (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_CONCAT (int)
Opcode
PARSEKIT_ZEND_CONT (int)
Opcode
PARSEKIT_ZEND_DECLARE_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DECLARE_FUNCTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DECLARE_INHERITED_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DIV (int)
Opcode
PARSEKIT_ZEND_DO_FCALL (int)
Opcode
PARSEKIT_ZEND_DO_FCALL_BY_NAME (int)
Opcode
PARSEKIT_ZEND_ECHO (int)
Opcode
PARSEKIT_ZEND_END_SILENCE (int)
Opcode
PARSEKIT_ZEND_EXIT (int)
Opcode
PARSEKIT_ZEND_EXT_FCALL_BEGIN (int)
Opcode
PARSEKIT_ZEND_EXT_FCALL_END (int)
Opcode
PARSEKIT_ZEND_EXT_NOP (int)
Opcode
PARSEKIT_ZEND_EXT_STMT (int)
Opcode
PARSEKIT_ZEND_FETCH_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_FETCH_CONSTANT (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_R (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_TMP_VAR (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_W (int)
Opcode
PARSEKIT_ZEND_FETCH_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_R (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_W (int)
Opcode
PARSEKIT_ZEND_FETCH_R (int)
Opcode
PARSEKIT_ZEND_FETCH_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_W (int)
Opcode
PARSEKIT_ZEND_FE_FETCH (int)
Opcode
PARSEKIT_ZEND_FE_RESET (int)
Opcode
PARSEKIT_ZEND_FREE (int)
Opcode
PARSEKIT_ZEND_HANDLE_EXCEPTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_CONST (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_FUNCTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INCLUDE_OR_EVAL (int)
Opcode
PARSEKIT_ZEND_INIT_ARRAY (int)
Opcode
PARSEKIT_ZEND_INIT_CTOR_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_FCALL_BY_NAME (int)
Opcode
PARSEKIT_ZEND_INIT_METHOD_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_STATIC_METHOD_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_STRING (int)
Opcode
PARSEKIT_ZEND_INSTANCEOF (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY (int) PHP < 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_DIM_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_PROP_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_VAR (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IS_EQUAL (int)
Opcode
PARSEKIT_ZEND_IS_IDENTICAL (int)
Opcode
PARSEKIT_ZEND_IS_NOT_EQUAL (int)
Opcode
PARSEKIT_ZEND_IS_NOT_IDENTICAL (int)
Opcode
PARSEKIT_ZEND_IS_SMALLER (int)
Opcode
PARSEKIT_ZEND_IS_SMALLER_OR_EQUAL (int)
Opcode
PARSEKIT_ZEND_JMP (int)
Opcode
PARSEKIT_ZEND_JMPNZ (int)
Opcode
PARSEKIT_ZEND_JMPNZ_EX (int)
Opcode
PARSEKIT_ZEND_JMPZ (int)
Opcode
PARSEKIT_ZEND_JMPZNZ (int)
Opcode
PARSEKIT_ZEND_JMPZ_EX (int)
Opcode
PARSEKIT_ZEND_JMP_NO_CTOR (int)
Opcode
PARSEKIT_ZEND_MOD (int)
Opcode
PARSEKIT_ZEND_MUL (int)
Opcode
PARSEKIT_ZEND_NEW (int)
Opcode
PARSEKIT_ZEND_NOP (int)
Opcode
PARSEKIT_ZEND_OP_DATA (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_POST_DEC (int)
Opcode
PARSEKIT_ZEND_POST_DEC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_POST_INC (int)
Opcode
PARSEKIT_ZEND_POST_INC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRE_DEC (int)
Opcode
PARSEKIT_ZEND_PRE_DEC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRE_INC (int)
Opcode
PARSEKIT_ZEND_PRE_INC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRINT (int)
Opcode
PARSEKIT_ZEND_QM_ASSIGN (int)
Opcode
PARSEKIT_ZEND_RAISE_ABSTRACT_ERROR (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_RECV (int)
Opcode
PARSEKIT_ZEND_RECV_INIT (int)
Opcode
PARSEKIT_ZEND_RETURN (int)
Opcode
PARSEKIT_ZEND_SEND_REF (int)
Opcode
PARSEKIT_ZEND_SEND_VAL (int)
Opcode
PARSEKIT_ZEND_SEND_VAR (int)
Opcode
PARSEKIT_ZEND_SEND_VAR_NO_REF (int)
Opcode
PARSEKIT_ZEND_SL (int)
Opcode
PARSEKIT_ZEND_SR (int)
Opcode
PARSEKIT_ZEND_SUB (int)
Opcode
PARSEKIT_ZEND_SWITCH_FREE (int)
Opcode
PARSEKIT_ZEND_THROW (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_TICKS (int)
Opcode
PARSEKIT_ZEND_UNSET_DIM_OBJ (int)
Opcode
PARSEKIT_ZEND_UNSET_VAR (int)
Opcode
PARSEKIT_ZEND_VERIFY_ABSTRACT_CLASS (int) PHP >= 5.0.0
Opcode

Typy zasobów
Parsekit Funkcje
Parsekit


Parsekit Funkcje

Spis treści

  • parsekit_compile_file — Compile a string of PHP code and return the resulting op array
  • parsekit_compile_string — Compile a string of PHP code and return the resulting op array
  • parsekit_func_arginfo — Return information regarding function argument(s)
Stałe predefiniowane
parsekit_compile_file
Parsekit


Compile a string of PHP code and return the resulting op array

Parsekit Funkcje
parsekit_compile_string
Parsekit Funkcje
PHP Manual

parsekit_compile_file

(PECL parsekit >= 0.2.0)

parsekit_compile_file — Compile a string of PHP code and return the resulting op array

Opis

array parsekit_compile_file ( string $filename [, array &$errors [, int $options = PARSEKIT_QUIET ]] )
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

filename

A string containing the name of the file to compile. Similar to the argument to include().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Zwracane wartości

Returns a complex multi-layer array structure as detailed below.

Przykłady

Przykład #1 parsekit_compile_file() example

<?php
var_dump(parsekit_compile_file('hello_world.php', $errors, PARSEKIT_SIMPLE));
?>

Powyższy przykład wyświetli:

array(5) {
  [0]=>
  string(37) "ZEND_ECHO UNUSED 'Hello World' UNUSED"
  [1]=>
  string(30) "ZEND_RETURN UNUSED NULL UNUSED"
  [2]=>
  string(42) "ZEND_HANDLE_EXCEPTION UNUSED UNUSED UNUSED"
  ["function_table"]=>
  NULL
  ["class_table"]=>
  NULL
}

Zobacz też:

  • parsekit_compile_string() - Compile a string of PHP code and return the resulting op array

Parsekit Funkcje
parsekit_compile_string
Parsekit Funkcje


Compile a string of PHP code and return the resulting op array

parsekit_compile_file
parsekit_func_arginfo
Parsekit Funkcje
PHP Manual

parsekit_compile_string

(PECL parsekit >= 0.2.0)

parsekit_compile_string — Compile a string of PHP code and return the resulting op array

Opis

array parsekit_compile_string ( string $phpcode [, array &$errors [, int $options = PARSEKIT_QUIET ]] )
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

phpcode

A string containing phpcode. Similar to the argument to eval().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Zwracane wartości

Returns a complex multi-layer array structure as detailed below.

Przykłady

Przykład #1 parsekit_compile_string() example

<?php
  $ops = parsekit_compile_string('
echo "Foo\n";
', $errors, PARSEKIT_QUIET);

  var_dump($ops);
?>

Powyższy przykład wyświetli:

array(20) {
  ["type"]=>
  int(4)
  ["type_name"]=>
  string(14) "ZEND_EVAL_CODE"
  ["fn_flags"]=>
  int(0)
  ["num_args"]=>
  int(0)
  ["required_num_args"]=>
  int(0)
  ["pass_rest_by_reference"]=>
  bool(false)
  ["uses_this"]=>
  bool(false)
  ["line_start"]=>
  int(0)
  ["line_end"]=>
  int(0)
  ["return_reference"]=>
  bool(false)
  ["refcount"]=>
  int(1)
  ["last"]=>
  int(3)
  ["size"]=>
  int(3)
  ["T"]=>
  int(0)
  ["last_brk_cont"]=>
  int(0)
  ["current_brk_cont"]=>
  int(-1)
  ["backpatch_count"]=>
  int(0)
  ["done_pass_two"]=>
  bool(true)
  ["filename"]=>
  string(17) "Parsekit Compiler"
  ["opcodes"]=>
  array(3) {
    [8594800]=>
    array(5) {
      ["opcode"]=>
      int(40)
      ["opcode_name"]=>
      string(9) "ZEND_ECHO"
      ["flags"]=>
      int(768)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &string(4) "Foo
"
      }
      ["lineno"]=>
      int(2)
    }
    ["859484C"]=>
    array(6) {
      ["opcode"]=>
      int(62)
      ["opcode_name"]=>
      string(11) "ZEND_RETURN"
      ["flags"]=>
      int(16777984)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &NULL
      }
      ["extended_value"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
    [8594898]=>
    array(4) {
      ["opcode"]=>
      int(149)
      ["opcode_name"]=>
      string(21) "ZEND_HANDLE_EXCEPTION"
      ["flags"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
  }
}

Zobacz też:

  • parsekit_compile_file() - Compile a string of PHP code and return the resulting op array

parsekit_compile_file
parsekit_func_arginfo
Parsekit Funkcje


Return information regarding function argument(s)

parsekit_compile_string
SPL
Parsekit Funkcje
PHP Manual

parsekit_func_arginfo

(PECL parsekit >= 0.3.0)

parsekit_func_arginfo — Return information regarding function argument(s)

Opis

array parsekit_func_arginfo ( mixed $function )
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

function

A string describing a function, or an array describing a class/method.

Zwracane wartości

Returns an array containing argument information.

Przykłady

Przykład #1 parsekit_func_arginfo() example

<?php
function foo($bar, stdClass $baz, &$bomb, $bling = false) {
}

var_dump(parsekit_func_arginfo('foo'));
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  array(3) {
    ["name"]=>
    string(3) "bar"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
  [1]=>
  array(4) {
    ["name"]=>
    string(3) "baz"
    ["class_name"]=>
    string(8) "stdClass"
    ["allow_null"]=>
    bool(false)
    ["pass_by_reference"]=>
    bool(false)
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(4) "bomb"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(true)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(5) "bling"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
}

parsekit_compile_string
SPL
Parsekit Funkcje


Standard PHP Library (SPL)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Struktury danych
    • SplDoublyLinkedList — The SplDoublyLinkedList class
    • SplStack — The SplStack class
    • SplQueue — The SplQueue class
    • SplHeap — The SplHeap class
    • SplMaxHeap — The SplMaxHeap class
    • SplMinHeap — The SplMinHeap class
    • SplPriorityQueue — The SplPriorityQueue class
    • SplFixedArray — The SplFixedArray class
    • SplObjectStorage — The SplObjectStorage class
  • Iteratory
    • AppendIterator — The AppendIterator class
    • ArrayIterator — The ArrayIterator class
    • CachingIterator — The CachingIterator class
    • CallbackFilterIterator — The CallbackFilterIterator class
    • DirectoryIterator — The DirectoryIterator class
    • EmptyIterator — The EmptyIterator class
    • FilesystemIterator — The FilesystemIterator class
    • FilterIterator — The FilterIterator class
    • GlobIterator — The GlobIterator class
    • InfiniteIterator — The InfiniteIterator class
    • IteratorIterator — The IteratorIterator class
    • LimitIterator — The LimitIterator class
    • MultipleIterator — The MultipleIterator class
    • NoRewindIterator — The NoRewindIterator class
    • ParentIterator — The ParentIterator class
    • RecursiveArrayIterator — The RecursiveArrayIterator class
    • RecursiveCachingIterator — The RecursiveCachingIterator class
    • RecursiveCallbackFilterIterator — The RecursiveCallbackFilterIterator class
    • RecursiveDirectoryIterator — The RecursiveDirectoryIterator class
    • RecursiveFilterIterator — The RecursiveFilterIterator class
    • RecursiveIteratorIterator — The RecursiveIteratorIterator class
    • RecursiveRegexIterator — The RecursiveRegexIterator class
    • RecursiveTreeIterator — The RecursiveTreeIterator class
    • RegexIterator — The RegexIterator class
  • Interfejsy
    • Countable — The Countable interface
    • OuterIterator — The OuterIterator interface
    • RecursiveIterator — The RecursiveIterator interface
    • SeekableIterator — The SeekableIterator interface
  • Wyjątki
    • BadFunctionCallException — The BadFunctionCallException class
    • BadMethodCallException — The BadMethodCallException class
    • DomainException — The DomainException class
    • InvalidArgumentException — The InvalidArgumentException class
    • LengthException — The LengthException class
    • LogicException — The LogicException class
    • OutOfBoundsException — The OutOfBoundsException class
    • OutOfRangeException — The OutOfRangeException class
    • OverflowException — The OverflowException class
    • RangeException — The RangeException class
    • RuntimeException — The RuntimeException class
    • UnderflowException — The UnderflowException class
    • UnexpectedValueException — The UnexpectedValueException class
  • SPL Funkcje
    • class_implements — Return the interfaces which are implemented by the given class
    • class_parents — Return the parent classes of the given class
    • class_uses — Return the traits used by the given class
    • iterator_apply — Call a function for every element in an iterator
    • iterator_count — Count the elements in an iterator
    • iterator_to_array — Copy the iterator into an array
    • spl_autoload_call — Try all registered __autoload() function to load the requested class
    • spl_autoload_extensions — Register and return default file extensions for spl_autoload
    • spl_autoload_functions — Return all registered __autoload() functions
    • spl_autoload_register — Register given function as __autoload() implementation
    • spl_autoload_unregister — Unregister given function as __autoload() implementation
    • spl_autoload — Default implementation for __autoload()
    • spl_classes — Return available SPL classes
    • spl_object_hash — Return hash id for given object
  • Obsługa plików
    • SplFileInfo — The SplFileInfo class
    • SplFileObject — The SplFileObject class
    • SplTempFileObject — The SplTempFileObject class
  • Różne klasy i interfejsy
    • ArrayObject — The ArrayObject class
    • SplObserver — The SplObserver interface
    • SplSubject — The SplSubject interface
parsekit_func_arginfo
Wstęp
Inne podstawowe rozszerzenia


Wstęp

SPL is a collection of interfaces and classes that are meant to solve standard problems.

Informacja:

Legacy "doxygen" documentation can be found » here.

SPL
Instalacja/Konfiguracja
SPL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SPL


Instalacja

This extension is available and compiled by default in PHP 5.0.0.

Informacja:

As of PHP 5.3.0 this extension can no longer be disabled and is therefore always available.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Ostrzeżenie

SPL uses class constants since PHP 5.1. Prior releases use global constants in the form RIT_LEAVES_ONLY.

RecursiveIteratorIterator::LEAVES_ONLY (integer)
RecursiveIteratorIterator::SELF_FIRST (integer)
RecursiveIteratorIterator::CHILD_FIRST (integer)
CachingIterator::CALL_TOSTRING (integer)
CachingIterator::CATCH_GET_CHILD (integer)
Typy zasobów
Struktury danych
SPL


Struktury danych

Spis treści

  • SplDoublyLinkedList
  • SplStack
  • SplQueue
  • SplHeap
  • SplMaxHeap
  • SplMinHeap
  • SplPriorityQueue
  • SplFixedArray
  • SplObjectStorage

SPL provides a set of standard datastructures. They are grouped here by their underlying implementation which usually defines their general field of application.

Doubly Linked Lists

A Doubly Linked List (DLL) is a list of nodes linked in both directions to each others. Iterator's operations, access to both ends, addition or removal of nodes have a cost of O(1) when the underlying structure is a DLL. It hence provides a decent implementation for stacks and queues.

  • SplDoublyLinkedList
    • SplStack
    • SplQueue

Heaps

Heaps are tree-like structures that follow the heap-property: each node is greater than or equal to its children, when compared using the implemented compare method which is global to the heap.

  • SplHeap
    • SplMaxHeap
    • SplMinHeap
  • SplPriorityQueue

Arrays

Arrays are structures that store the data in a continuous way, accessible via indexes. Don't confuse them with PHP arrays: PHP arrays are in fact implemented as ordered hashtables.

  • SplFixedArray

Map

A map is a datastructure holding key-value pairs. PHP arrays can be seen as maps from integers/strings to values. SPL provides a map from objects to data. This map can also be used as an object set.

  • SplObjectStorage
Stałe predefiniowane
SplDoublyLinkedList
SPL


The SplDoublyLinkedList class

(PHP 5 >= 5.3.0)

Wstęp

The SplDoublyLinkedList class provides the main functionalities of a doubly linked list.

Krótki opis klasy

SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Metody */
__construct ( void )
mixed bottom ( void )
int count ( void )
mixed current ( void )
int getIteratorMode ( void )
bool isEmpty ( void )
mixed key ( void )
void next ( void )
bool offsetExists ( mixed $index )
mixed offsetGet ( mixed $index )
void offsetSet ( mixed $index , mixed $newval )
void offsetUnset ( mixed $index )
mixed pop ( void )
void prev ( void )
void push ( mixed $value )
void rewind ( void )
void setIteratorMode ( int $mode )
mixed shift ( void )
mixed top ( void )
void unshift ( mixed $value )
bool valid ( void )
}

Spis treści

  • SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list
  • SplDoublyLinkedList::__construct — Constructs a new doubly linked list
  • SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list.
  • SplDoublyLinkedList::current — Return current array entry
  • SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration
  • SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty.
  • SplDoublyLinkedList::key — Return current node index
  • SplDoublyLinkedList::next — Move to next entry
  • SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists
  • SplDoublyLinkedList::offsetGet — Returns the value at the specified $index
  • SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval
  • SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index
  • SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list
  • SplDoublyLinkedList::prev — Move to previous entry
  • SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list
  • SplDoublyLinkedList::rewind — Rewind iterator back to the start
  • SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration
  • SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list
  • SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list
  • SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element
  • SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes
Struktury danych
SplDoublyLinkedList::bottom
Struktury danych


Peeks at the node from the beginning of the doubly linked list

SplDoublyLinkedList
SplDoublyLinkedList::__construct
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::bottom

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list

Opis

mixed SplDoublyLinkedList::bottom ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value of the first node.

Błędy/Wyjątki

Throws RuntimeException when the data-structure is empty.

SplDoublyLinkedList
SplDoublyLinkedList::__construct
SplDoublyLinkedList


Constructs a new doubly linked list

SplDoublyLinkedList::bottom
SplDoublyLinkedList::count
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::__construct

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::__construct — Constructs a new doubly linked list

Opis

SplDoublyLinkedList::__construct() ( void )

This constructs a new empty doubly linked list.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplDoublyLinkedList::__construct() example

<?php
$dll = new SplDoublyLinkedList();

$dll->push(2);
$dll->push(3);
$dll->unshift(5);

var_dump($dll);
?>

Powyższy przykład wyświetli:

object(SplDoublyLinkedList)#1 (2) {
  ["flags":"SplDoublyLinkedList":private]=>
  int(0)
  ["dllist":"SplDoublyLinkedList":private]=>
  array(3) {
    [0]=>
    int(5)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
}

SplDoublyLinkedList::bottom
SplDoublyLinkedList::count
SplDoublyLinkedList


Counts the number of elements in the doubly linked list.

SplDoublyLinkedList::__construct
SplDoublyLinkedList::current
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::count

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list.

Opis

int SplDoublyLinkedList::count ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the number of elements in the doubly linked list.

SplDoublyLinkedList::__construct
SplDoublyLinkedList::current
SplDoublyLinkedList


Return current array entry

SplDoublyLinkedList::count
SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::current

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::current — Return current array entry

Opis

mixed SplDoublyLinkedList::current ( void )

Get the current doubly linked list node.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current node value.

SplDoublyLinkedList::count
SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList


Returns the mode of iteration

SplDoublyLinkedList::current
SplDoublyLinkedList::isEmpty
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::getIteratorMode

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration

Opis

int SplDoublyLinkedList::getIteratorMode ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the different modes and flags that affect the iteration.

SplDoublyLinkedList::current
SplDoublyLinkedList::isEmpty
SplDoublyLinkedList


Checks whether the doubly linked list is empty.

SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList::key
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::isEmpty

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty.

Opis

bool SplDoublyLinkedList::isEmpty ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns whether the doubly linked list is empty.

SplDoublyLinkedList::getIteratorMode
SplDoublyLinkedList::key
SplDoublyLinkedList


Return current node index

SplDoublyLinkedList::isEmpty
SplDoublyLinkedList::next
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::key

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::key — Return current node index

Opis

mixed SplDoublyLinkedList::key ( void )

This function returns the current node index

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current node index.

SplDoublyLinkedList::isEmpty
SplDoublyLinkedList::next
SplDoublyLinkedList


Move to next entry

SplDoublyLinkedList::key
SplDoublyLinkedList::offsetExists
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::next

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::next — Move to next entry

Opis

void SplDoublyLinkedList::next ( void )

Move the iterator to the next node.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplDoublyLinkedList::key
SplDoublyLinkedList::offsetExists
SplDoublyLinkedList


Returns whether the requested $index exists

SplDoublyLinkedList::next
SplDoublyLinkedList::offsetGet
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetExists

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists

Opis

bool SplDoublyLinkedList::offsetExists ( mixed $index )

Parametry

index

The index being checked.

Zwracane wartości

TRUE if the requested index exists, otherwise FALSE

SplDoublyLinkedList::next
SplDoublyLinkedList::offsetGet
SplDoublyLinkedList


Returns the value at the specified $index

SplDoublyLinkedList::offsetExists
SplDoublyLinkedList::offsetSet
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetGet

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetGet — Returns the value at the specified $index

Opis

mixed SplDoublyLinkedList::offsetGet ( mixed $index )

Parametry

index

The index with the value.

Zwracane wartości

The value at the specified index.

Błędy/Wyjątki

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

SplDoublyLinkedList::offsetExists
SplDoublyLinkedList::offsetSet
SplDoublyLinkedList


Sets the value at the specified $index to $newval

SplDoublyLinkedList::offsetGet
SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetSet

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval

Opis

void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )

Sets the value at the specified index to newval.

Parametry

index

The index being set.

newval

The new value for the index.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

SplDoublyLinkedList::offsetGet
SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList


Unsets the value at the specified $index

SplDoublyLinkedList::offsetSet
SplDoublyLinkedList::pop
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::offsetUnset

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index

Opis

void SplDoublyLinkedList::offsetUnset ( mixed $index )

Unsets the value at the specified index.

Parametry

index

The index being unset.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

SplDoublyLinkedList::offsetSet
SplDoublyLinkedList::pop
SplDoublyLinkedList


Pops a node from the end of the doubly linked list

SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList::prev
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::pop

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list

Opis

mixed SplDoublyLinkedList::pop ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value of the popped node.

Błędy/Wyjątki

Throws RuntimeException when the data-structure is empty.

SplDoublyLinkedList::offsetUnset
SplDoublyLinkedList::prev
SplDoublyLinkedList


Move to previous entry

SplDoublyLinkedList::pop
SplDoublyLinkedList::push
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::prev

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::prev — Move to previous entry

Opis

void SplDoublyLinkedList::prev ( void )

Move the iterator to the previous node.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplDoublyLinkedList::pop
SplDoublyLinkedList::push
SplDoublyLinkedList


Pushes an element at the end of the doubly linked list

SplDoublyLinkedList::prev
SplDoublyLinkedList::rewind
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::push

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list

Opis

void SplDoublyLinkedList::push ( mixed $value )

Pushes value at the end of the doubly linked list.

Parametry

value

The value to push.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplDoublyLinkedList::prev
SplDoublyLinkedList::rewind
SplDoublyLinkedList


Rewind iterator back to the start

SplDoublyLinkedList::push
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::rewind

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::rewind — Rewind iterator back to the start

Opis

void SplDoublyLinkedList::rewind ( void )

This rewinds the iterator to the beginning.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplDoublyLinkedList::push
SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList


Sets the mode of iteration

SplDoublyLinkedList::rewind
SplDoublyLinkedList::shift
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::setIteratorMode

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration

Opis

void SplDoublyLinkedList::setIteratorMode ( int $mode )

Parametry

mode

There are two orthogonal sets of modes that can be set:

  • The direction of the iteration (either one or the other):
    • SplDoublyLinkedList::IT_MODE_LIFO (Stack style)
    • SplDoublyLinkedList::IT_MODE_FIFO (Queue style)
  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Zwracane wartości

Nie jest zwracana żadna wartość.

SplDoublyLinkedList::rewind
SplDoublyLinkedList::shift
SplDoublyLinkedList


Shifts a node from the beginning of the doubly linked list

SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList::top
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::shift

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list

Opis

mixed SplDoublyLinkedList::shift ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value of the shifted node.

Błędy/Wyjątki

Throws RuntimeException when the data-structure is empty.

SplDoublyLinkedList::setIteratorMode
SplDoublyLinkedList::top
SplDoublyLinkedList


Peeks at the node from the end of the doubly linked list

SplDoublyLinkedList::shift
SplDoublyLinkedList::unshift
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::top

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list

Opis

mixed SplDoublyLinkedList::top ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value of the last node.

Błędy/Wyjątki

Throws RuntimeException when the data-structure is empty.

SplDoublyLinkedList::shift
SplDoublyLinkedList::unshift
SplDoublyLinkedList


Prepends the doubly linked list with an element

SplDoublyLinkedList::top
SplDoublyLinkedList::valid
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::unshift

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element

Opis

void SplDoublyLinkedList::unshift ( mixed $value )

Prepends value at the beginning of the doubly linked list.

Parametry

value

The value to unshift.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplDoublyLinkedList::top
SplDoublyLinkedList::valid
SplDoublyLinkedList


Check whether the doubly linked list contains more nodes

SplDoublyLinkedList::unshift
SplStack
SplDoublyLinkedList
PHP Manual

SplDoublyLinkedList::valid

(PHP 5 >= 5.3.0)

SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

Opis

bool SplDoublyLinkedList::valid ( void )

Checks if the doubly linked list contains any more nodes.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the doubly linked list contains any more nodes, FALSE otherwise.

SplDoublyLinkedList::unshift
SplStack
SplDoublyLinkedList


The SplStack class

(PHP 5 >= 5.3.0)

Wstęp

The SplStack class provides the main functionalities of a stack implemented using a doubly linked list.

Krótki opis klasy

SplStack extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Metody */
__construct ( void )
void setIteratorMode ( int $mode )
/* Metody dziedziczone */
mixed SplDoublyLinkedList::bottom ( void )
int SplDoublyLinkedList::count ( void )
mixed SplDoublyLinkedList::current ( void )
int SplDoublyLinkedList::getIteratorMode ( void )
bool SplDoublyLinkedList::isEmpty ( void )
mixed SplDoublyLinkedList::key ( void )
void SplDoublyLinkedList::next ( void )
bool SplDoublyLinkedList::offsetExists ( mixed $index )
mixed SplDoublyLinkedList::offsetGet ( mixed $index )
void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
void SplDoublyLinkedList::offsetUnset ( mixed $index )
mixed SplDoublyLinkedList::pop ( void )
void SplDoublyLinkedList::prev ( void )
void SplDoublyLinkedList::push ( mixed $value )
void SplDoublyLinkedList::rewind ( void )
void SplDoublyLinkedList::setIteratorMode ( int $mode )
mixed SplDoublyLinkedList::shift ( void )
mixed SplDoublyLinkedList::top ( void )
void SplDoublyLinkedList::unshift ( mixed $value )
bool SplDoublyLinkedList::valid ( void )
}

Spis treści

  • SplStack::__construct — Constructs a new stack implemented using a doubly linked list
  • SplStack::setIteratorMode — Sets the mode of iteration
SplDoublyLinkedList::valid
SplStack::__construct
Struktury danych


Constructs a new stack implemented using a doubly linked list

SplStack
SplStack::setIteratorMode
SplStack
PHP Manual

SplStack::__construct

(PHP 5 >= 5.3.0)

SplStack::__construct — Constructs a new stack implemented using a doubly linked list

Opis

SplStack::__construct() ( void )

This constructs a new empty stack.

Informacja:

This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_LIFO.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplStack::__construct() example

<?php
$q = new SplStack();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

Powyższy przykład wyświetli:

3
2
1

SplStack
SplStack::setIteratorMode
SplStack


Sets the mode of iteration

SplStack::__construct
SplQueue
SplStack
PHP Manual

SplStack::setIteratorMode

(PHP 5 >= 5.3.0)

SplStack::setIteratorMode — Sets the mode of iteration

Opis

void SplStack::setIteratorMode ( int $mode )

Parametry

mode

There is only one iteration parameter you can modify.

  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is 0x2 : SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP

Ostrzeżenie

The direction of iteration can no longer be changed for SplStacks. Trying to do so will result in a RuntimeException being thrown.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplStack::__construct
SplQueue
SplStack


The SplQueue class

(PHP 5 >= 5.3.0)

Wstęp

The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list.

Krótki opis klasy

SplQueue extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Metody */
__construct ( void )
mixed dequeue ( void )
void enqueue ( mixed $value )
void setIteratorMode ( int $mode )
/* Metody dziedziczone */
mixed SplDoublyLinkedList::bottom ( void )
int SplDoublyLinkedList::count ( void )
mixed SplDoublyLinkedList::current ( void )
int SplDoublyLinkedList::getIteratorMode ( void )
bool SplDoublyLinkedList::isEmpty ( void )
mixed SplDoublyLinkedList::key ( void )
void SplDoublyLinkedList::next ( void )
bool SplDoublyLinkedList::offsetExists ( mixed $index )
mixed SplDoublyLinkedList::offsetGet ( mixed $index )
void SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval )
void SplDoublyLinkedList::offsetUnset ( mixed $index )
mixed SplDoublyLinkedList::pop ( void )
void SplDoublyLinkedList::prev ( void )
void SplDoublyLinkedList::push ( mixed $value )
void SplDoublyLinkedList::rewind ( void )
void SplDoublyLinkedList::setIteratorMode ( int $mode )
mixed SplDoublyLinkedList::shift ( void )
mixed SplDoublyLinkedList::top ( void )
void SplDoublyLinkedList::unshift ( mixed $value )
bool SplDoublyLinkedList::valid ( void )
}

Spis treści

  • SplQueue::__construct — Constructs a new queue implemented using a doubly linked list
  • SplQueue::dequeue — Dequeues a node from the queue
  • SplQueue::enqueue — Adds an element to the queue.
  • SplQueue::setIteratorMode — Sets the mode of iteration
SplStack::setIteratorMode
SplQueue::__construct
Struktury danych


Constructs a new queue implemented using a doubly linked list

SplQueue
SplQueue::dequeue
SplQueue
PHP Manual

SplQueue::__construct

(PHP 5 >= 5.3.0)

SplQueue::__construct — Constructs a new queue implemented using a doubly linked list

Opis

SplQueue::__construct() ( void )

This constructs a new empty queue.

Informacja:

This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_FIFO.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplQueue::__construct() example

<?php
$q = new SplQueue();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

Powyższy przykład wyświetli:

1
2
3

Przykład #2 Efficiently handling tasks with SplQueue

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);

// ... enqueue some tasks on the queue ...

// process them
foreach ($q as $task) {
    // ... process $task ...

    // add new tasks on the queue
    $q[] = $newTask;
    // ...
}
?>

SplQueue
SplQueue::dequeue
SplQueue


Dequeues a node from the queue

SplQueue::__construct
SplQueue::enqueue
SplQueue
PHP Manual

SplQueue::dequeue

(PHP 5 >= 5.3.0)

SplQueue::dequeue — Dequeues a node from the queue

Opis

mixed SplQueue::dequeue ( void )

Dequeues value from the top of the queue.

Informacja:

SplQueue::dequeue() is an alias of SplDoublyLinkedList::shift().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value of the dequeued node.

SplQueue::__construct
SplQueue::enqueue
SplQueue


Adds an element to the queue.

SplQueue::dequeue
SplQueue::setIteratorMode
SplQueue
PHP Manual

SplQueue::enqueue

(PHP 5 >= 5.3.0)

SplQueue::enqueue — Adds an element to the queue.

Opis

void SplQueue::enqueue ( mixed $value )

Enqueues value at the end of the queue.

Informacja:

SplQueue::enqueue() is an alias of SplDoublyLinkedList::push().

Parametry

value

The value to enqueue.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplQueue::dequeue
SplQueue::setIteratorMode
SplQueue


Sets the mode of iteration

SplQueue::enqueue
SplHeap
SplQueue
PHP Manual

SplQueue::setIteratorMode

(PHP 5 >= 5.3.0)

SplQueue::setIteratorMode — Sets the mode of iteration

Opis

void SplQueue::setIteratorMode ( int $mode )

Parametry

mode

There is only one iteration parameter you can modify.

  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Ostrzeżenie

The direction of iteration can not be changed for SplQueues, it is always SplDoublyLinkedList::IT_MODE_FIFO.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws a RuntimeException on trying to change the direction of iteration by using SplDoublyLinkedList::IT_MODE_LIFO.

SplQueue::enqueue
SplHeap
SplQueue


The SplHeap class

(PHP 5 >= 5.3.0)

Wstęp

The SplHeap class provides the main functionalities of a Heap.

Krótki opis klasy

abstract SplHeap implements Iterator , Countable {
/* Metody */
__construct ( void )
abstract int compare ( mixed $value1 , mixed $value2 )
int count ( void )
mixed current ( void )
mixed extract ( void )
void insert ( mixed $value )
bool isEmpty ( void )
mixed key ( void )
void next ( void )
void recoverFromCorruption ( void )
void rewind ( void )
mixed top ( void )
bool valid ( void )
}

Spis treści

  • SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.
  • SplHeap::__construct — Constructs a new empty heap
  • SplHeap::count — Counts the number of elements in the heap.
  • SplHeap::current — Return current node pointed by the iterator
  • SplHeap::extract — Extracts a node from top of the heap and sift up.
  • SplHeap::insert — Inserts an element in the heap by sifting it up.
  • SplHeap::isEmpty — Checks whether the heap is empty.
  • SplHeap::key — Return current node index
  • SplHeap::next — Move to the next node
  • SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap.
  • SplHeap::rewind — Rewind iterator back to the start (no-op)
  • SplHeap::top — Peeks at the node from the top of the heap
  • SplHeap::valid — Check whether the heap contains more nodes
SplQueue::setIteratorMode
SplHeap::compare
Struktury danych


Compare elements in order to place them correctly in the heap while sifting up.

SplHeap
SplHeap::__construct
SplHeap
PHP Manual

SplHeap::compare

(PHP 5 >= 5.3.0)

SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Opis

abstract int SplHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Ostrzeżenie

Throwing exceptions in SplHeap::compare() can corrupt the Heap and place it in a blocked state. You can unblock it by calling SplHeap::recoverFromCorruption(). However, some elements might not be placed correctly and it may hence break the heap-property.

Parametry

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Zwracane wartości

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Informacja:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

SplHeap
SplHeap::__construct
SplHeap


Constructs a new empty heap

SplHeap::compare
SplHeap::count
SplHeap
PHP Manual

SplHeap::__construct

(PHP 5 >= 5.3.0)

SplHeap::__construct — Constructs a new empty heap

Opis

SplHeap::__construct() ( void )

This constructs a new empty heap.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplHeap::compare
SplHeap::count
SplHeap


Counts the number of elements in the heap.

SplHeap::__construct
SplHeap::current
SplHeap
PHP Manual

SplHeap::count

(PHP 5 >= 5.3.0)

SplHeap::count — Counts the number of elements in the heap.

Opis

int SplHeap::count ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the number of elements in the heap.

SplHeap::__construct
SplHeap::current
SplHeap


Return current node pointed by the iterator

SplHeap::count
SplHeap::extract
SplHeap
PHP Manual

SplHeap::current

(PHP 5 >= 5.3.0)

SplHeap::current — Return current node pointed by the iterator

Opis

mixed SplHeap::current ( void )

Get the current datastructure node.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current node value.

SplHeap::count
SplHeap::extract
SplHeap


Extracts a node from top of the heap and sift up.

SplHeap::current
SplHeap::insert
SplHeap
PHP Manual

SplHeap::extract

(PHP 5 >= 5.3.0)

SplHeap::extract — Extracts a node from top of the heap and sift up.

Opis

mixed SplHeap::extract ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value of the extracted node.

Błędy/Wyjątki

Throws RuntimeException when the data-structure is empty.

SplHeap::current
SplHeap::insert
SplHeap


Inserts an element in the heap by sifting it up.

SplHeap::extract
SplHeap::isEmpty
SplHeap
PHP Manual

SplHeap::insert

(PHP 5 >= 5.3.0)

SplHeap::insert — Inserts an element in the heap by sifting it up.

Opis

void SplHeap::insert ( mixed $value )

Insert value in the heap.

Parametry

value

The value to insert.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplHeap::extract
SplHeap::isEmpty
SplHeap


Checks whether the heap is empty.

SplHeap::insert
SplHeap::key
SplHeap
PHP Manual

SplHeap::isEmpty

(PHP 5 >= 5.3.0)

SplHeap::isEmpty — Checks whether the heap is empty.

Opis

bool SplHeap::isEmpty ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns whether the heap is empty.

SplHeap::insert
SplHeap::key
SplHeap


Return current node index

SplHeap::isEmpty
SplHeap::next
SplHeap
PHP Manual

SplHeap::key

(PHP 5 >= 5.3.0)

SplHeap::key — Return current node index

Opis

mixed SplHeap::key ( void )

This function returns the current node index

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current node index.

SplHeap::isEmpty
SplHeap::next
SplHeap


Move to the next node

SplHeap::key
SplHeap::recoverFromCorruption
SplHeap
PHP Manual

SplHeap::next

(PHP 5 >= 5.3.0)

SplHeap::next — Move to the next node

Opis

void SplHeap::next ( void )

Extracts the top node from the heap.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplHeap::key
SplHeap::recoverFromCorruption
SplHeap


Recover from the corrupted state and allow further actions on the heap.

SplHeap::next
SplHeap::rewind
SplHeap
PHP Manual

SplHeap::recoverFromCorruption

(PHP 5 >= 5.3.0)

SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap.

Opis

void SplHeap::recoverFromCorruption ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplHeap::next
SplHeap::rewind
SplHeap


Rewind iterator back to the start (no-op)

SplHeap::recoverFromCorruption
SplHeap::top
SplHeap
PHP Manual

SplHeap::rewind

(PHP 5 >= 5.3.0)

SplHeap::rewind — Rewind iterator back to the start (no-op)

Opis

void SplHeap::rewind ( void )

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplHeap::recoverFromCorruption
SplHeap::top
SplHeap


Peeks at the node from the top of the heap

SplHeap::rewind
SplHeap::valid
SplHeap
PHP Manual

SplHeap::top

(PHP 5 >= 5.3.0)

SplHeap::top — Peeks at the node from the top of the heap

Opis

mixed SplHeap::top ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value of the node on the top.

Błędy/Wyjątki

Throws RuntimeException when the data-structure is empty.

SplHeap::rewind
SplHeap::valid
SplHeap


Check whether the heap contains more nodes

SplHeap::top
SplMaxHeap
SplHeap
PHP Manual

SplHeap::valid

(PHP 5 >= 5.3.0)

SplHeap::valid — Check whether the heap contains more nodes

Opis

bool SplHeap::valid ( void )

Checks if the heap contains any more nodes.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the heap contains any more nodes, FALSE otherwise.

SplHeap::top
SplMaxHeap
SplHeap


The SplMaxHeap class

(PHP 5 >= 5.3.0)

Wstęp

The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.

Krótki opis klasy

SplMaxHeap extends SplHeap implements Iterator , Countable {
/* Metody */
int compare ( mixed $value1 , mixed $value2 )
/* Metody dziedziczone */
abstract int SplHeap::compare ( mixed $value1 , mixed $value2 )
int SplHeap::count ( void )
mixed SplHeap::current ( void )
mixed SplHeap::extract ( void )
void SplHeap::insert ( mixed $value )
bool SplHeap::isEmpty ( void )
mixed SplHeap::key ( void )
void SplHeap::next ( void )
void SplHeap::recoverFromCorruption ( void )
void SplHeap::rewind ( void )
mixed SplHeap::top ( void )
bool SplHeap::valid ( void )
}

Spis treści

  • SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.
SplHeap::valid
SplMaxHeap::compare
Struktury danych


Compare elements in order to place them correctly in the heap while sifting up.

SplMaxHeap
SplMinHeap
SplMaxHeap
PHP Manual

SplMaxHeap::compare

(PHP 5 >= 5.3.0)

SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Opis

int SplMaxHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Parametry

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Zwracane wartości

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Informacja:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

SplMaxHeap
SplMinHeap
SplMaxHeap


The SplMinHeap class

(PHP 5 >= 5.3.0)

Wstęp

The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.

Krótki opis klasy

SplMinHeap extends SplHeap implements Iterator , Countable {
/* Metody */
int compare ( mixed $value1 , mixed $value2 )
/* Metody dziedziczone */
abstract int SplHeap::compare ( mixed $value1 , mixed $value2 )
int SplHeap::count ( void )
mixed SplHeap::current ( void )
mixed SplHeap::extract ( void )
void SplHeap::insert ( mixed $value )
bool SplHeap::isEmpty ( void )
mixed SplHeap::key ( void )
void SplHeap::next ( void )
void SplHeap::recoverFromCorruption ( void )
void SplHeap::rewind ( void )
mixed SplHeap::top ( void )
bool SplHeap::valid ( void )
}

Spis treści

  • SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.
SplMaxHeap::compare
SplMinHeap::compare
Struktury danych


Compare elements in order to place them correctly in the heap while sifting up.

SplMinHeap
SplPriorityQueue
SplMinHeap
PHP Manual

SplMinHeap::compare

(PHP 5 >= 5.3.0)

SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up.

Opis

int SplMinHeap::compare ( mixed $value1 , mixed $value2 )

Compare value1 with value2.

Parametry

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Zwracane wartości

Result of the comparison, positive integer if value1 is lower than value2, 0 if they are equal, negative integer otherwise.

Informacja:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

SplMinHeap
SplPriorityQueue
SplMinHeap


The SplPriorityQueue class

(PHP 5 >= 5.3.0)

Wstęp

The SplPriorityQueue class provides the main functionalities of an prioritized queue, implemented using a heap.

Krótki opis klasy

SplPriorityQueue implements Iterator , Countable {
/* Metody */
__construct ( void )
int compare ( mixed $priority1 , mixed $priority2 )
int count ( void )
mixed current ( void )
mixed extract ( void )
void insert ( mixed $value , mixed $priority )
bool isEmpty ( void )
mixed key ( void )
void next ( void )
void recoverFromCorruption ( void )
void rewind ( void )
void setExtractFlags ( int $flags )
mixed top ( void )
bool valid ( void )
}

Spis treści

  • SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up.
  • SplPriorityQueue::__construct — Constructs a new empty queue
  • SplPriorityQueue::count — Counts the number of elements in the queue.
  • SplPriorityQueue::current — Return current node pointed by the iterator
  • SplPriorityQueue::extract — Extracts a node from top of the heap and sift up.
  • SplPriorityQueue::insert — Inserts an element in the queue by sifting it up.
  • SplPriorityQueue::isEmpty — Checks whether the queue is empty.
  • SplPriorityQueue::key — Return current node index
  • SplPriorityQueue::next — Move to the next node
  • SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue.
  • SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)
  • SplPriorityQueue::setExtractFlags — Sets the mode of extraction
  • SplPriorityQueue::top — Peeks at the node from the top of the queue
  • SplPriorityQueue::valid — Check whether the queue contains more nodes
SplMinHeap::compare
SplPriorityQueue::compare
Struktury danych


Compare priorities in order to place elements correctly in the heap while sifting up.

SplPriorityQueue
SplPriorityQueue::__construct
SplPriorityQueue
PHP Manual

SplPriorityQueue::compare

(PHP 5 >= 5.3.0)

SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up.

Opis

int SplPriorityQueue::compare ( mixed $priority1 , mixed $priority2 )

Compare priority1 with priority2.

Parametry

priority1

The priority of the first node being compared.

priority2

The priority of the second node being compared.

Zwracane wartości

Result of the comparison, positive integer if priority1 is greater than priority2, 0 if they are equal, negative integer otherwise.

Informacja:

Multiple elements with the same priority will get dequeued in no particular order.

SplPriorityQueue
SplPriorityQueue::__construct
SplPriorityQueue


Constructs a new empty queue

SplPriorityQueue::compare
SplPriorityQueue::count
SplPriorityQueue
PHP Manual

SplPriorityQueue::__construct

(PHP 5 >= 5.3.0)

SplPriorityQueue::__construct — Constructs a new empty queue

Opis

SplPriorityQueue::__construct() ( void )

This constructs a new empty queue.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplPriorityQueue::compare
SplPriorityQueue::count
SplPriorityQueue


Counts the number of elements in the queue.

SplPriorityQueue::__construct
SplPriorityQueue::current
SplPriorityQueue
PHP Manual

SplPriorityQueue::count

(PHP 5 >= 5.3.0)

SplPriorityQueue::count — Counts the number of elements in the queue.

Opis

int SplPriorityQueue::count ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the number of elements in the queue.

SplPriorityQueue::__construct
SplPriorityQueue::current
SplPriorityQueue


Return current node pointed by the iterator

SplPriorityQueue::count
SplPriorityQueue::extract
SplPriorityQueue
PHP Manual

SplPriorityQueue::current

(PHP 5 >= 5.3.0)

SplPriorityQueue::current — Return current node pointed by the iterator

Opis

mixed SplPriorityQueue::current ( void )

Get the current datastructure node.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value or priority (or both) of the current node, depending on the extract flag.

SplPriorityQueue::count
SplPriorityQueue::extract
SplPriorityQueue


Extracts a node from top of the heap and sift up.

SplPriorityQueue::current
SplPriorityQueue::insert
SplPriorityQueue
PHP Manual

SplPriorityQueue::extract

(PHP 5 >= 5.3.0)

SplPriorityQueue::extract — Extracts a node from top of the heap and sift up.

Opis

mixed SplPriorityQueue::extract ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value or priority (or both) of the extracted node, depending on the extract flag.

SplPriorityQueue::current
SplPriorityQueue::insert
SplPriorityQueue


Inserts an element in the queue by sifting it up.

SplPriorityQueue::extract
SplPriorityQueue::isEmpty
SplPriorityQueue
PHP Manual

SplPriorityQueue::insert

(PHP 5 >= 5.3.0)

SplPriorityQueue::insert — Inserts an element in the queue by sifting it up.

Opis

void SplPriorityQueue::insert ( mixed $value , mixed $priority )

Insert value with the priority priority in the queue.

Parametry

value

The value to insert.

priority

The associated priority.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplPriorityQueue::extract
SplPriorityQueue::isEmpty
SplPriorityQueue


Checks whether the queue is empty.

SplPriorityQueue::insert
SplPriorityQueue::key
SplPriorityQueue
PHP Manual

SplPriorityQueue::isEmpty

(PHP 5 >= 5.3.0)

SplPriorityQueue::isEmpty — Checks whether the queue is empty.

Opis

bool SplPriorityQueue::isEmpty ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns whether the queue is empty.

SplPriorityQueue::insert
SplPriorityQueue::key
SplPriorityQueue


Return current node index

SplPriorityQueue::isEmpty
SplPriorityQueue::next
SplPriorityQueue
PHP Manual

SplPriorityQueue::key

(PHP 5 >= 5.3.0)

SplPriorityQueue::key — Return current node index

Opis

mixed SplPriorityQueue::key ( void )

This function returns the current node index

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current node index.

SplPriorityQueue::isEmpty
SplPriorityQueue::next
SplPriorityQueue


Move to the next node

SplPriorityQueue::key
SplPriorityQueue::recoverFromCorruption
SplPriorityQueue
PHP Manual

SplPriorityQueue::next

(PHP 5 >= 5.3.0)

SplPriorityQueue::next — Move to the next node

Opis

void SplPriorityQueue::next ( void )

Extracts the top node from the queue.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplPriorityQueue::key
SplPriorityQueue::recoverFromCorruption
SplPriorityQueue


Recover from the corrupted state and allow further actions on the queue.

SplPriorityQueue::next
SplPriorityQueue::rewind
SplPriorityQueue
PHP Manual

SplPriorityQueue::recoverFromCorruption

(PHP 5 >= 5.3.0)

SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue.

Opis

void SplPriorityQueue::recoverFromCorruption ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplPriorityQueue::next
SplPriorityQueue::rewind
SplPriorityQueue


Rewind iterator back to the start (no-op)

SplPriorityQueue::recoverFromCorruption
SplPriorityQueue::setExtractFlags
SplPriorityQueue
PHP Manual

SplPriorityQueue::rewind

(PHP 5 >= 5.3.0)

SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)

Opis

void SplPriorityQueue::rewind ( void )

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplPriorityQueue::recoverFromCorruption
SplPriorityQueue::setExtractFlags
SplPriorityQueue


Sets the mode of extraction

SplPriorityQueue::rewind
SplPriorityQueue::top
SplPriorityQueue
PHP Manual

SplPriorityQueue::setExtractFlags

(PHP 5 >= 5.3.0)

SplPriorityQueue::setExtractFlags — Sets the mode of extraction

Opis

void SplPriorityQueue::setExtractFlags ( int $flags )

Parametry

flags

Defines what is extracted by  SplPriorityQueue::current(),
 SplPriorityQueue::top() and
 SplPriorityQueue::extract().

  • SplPriorityQueue::EXTR_DATA (0x00000001): Extract the data
  • SplPriorityQueue::EXTR_PRIORITY (0x00000002): Extract the priority
  • SplPriorityQueue::EXTR_BOTH (0x00000003): Extract an array containing both

The default mode is SplPriorityQueue::EXTR_DATA.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplPriorityQueue::rewind
SplPriorityQueue::top
SplPriorityQueue


Peeks at the node from the top of the queue

SplPriorityQueue::setExtractFlags
SplPriorityQueue::valid
SplPriorityQueue
PHP Manual

SplPriorityQueue::top

(PHP 5 >= 5.3.0)

SplPriorityQueue::top — Peeks at the node from the top of the queue

Opis

mixed SplPriorityQueue::top ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value or priority (or both) of the top node, depending on the extract flag.

SplPriorityQueue::setExtractFlags
SplPriorityQueue::valid
SplPriorityQueue


Check whether the queue contains more nodes

SplPriorityQueue::top
SplFixedArray
SplPriorityQueue
PHP Manual

SplPriorityQueue::valid

(PHP 5 >= 5.3.0)

SplPriorityQueue::valid — Check whether the queue contains more nodes

Opis

bool SplPriorityQueue::valid ( void )

Checks if the queue contains any more nodes.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the queue contains any more nodes, FALSE otherwise.

SplPriorityQueue::top
SplFixedArray
SplPriorityQueue


The SplFixedArray class

(PHP 5 >= 5.3.0)

Wstęp

The SplFixedArray class provides the main functionalities of array. The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation.

Krótki opis klasy

SplFixedArray implements Iterator , ArrayAccess , Countable {
/* Metody */
public __construct ([ int $size = 0 ] )
public int count ( void )
public mixed current ( void )
public static SplFixedArray fromArray ( array $array [, bool $save_indexes = true ] )
public int getSize ( void )
public int key ( void )
public void next ( void )
public bool offsetExists ( int $index )
public mixed offsetGet ( int $index )
public void offsetSet ( int $index , mixed $newval )
public void offsetUnset ( int $index )
public void rewind ( void )
public int setSize ( int $size )
public array toArray ( void )
public bool valid ( void )
}

Przykłady

Przykład #1 SplFixedArray usage example

<?php
// Initialize the array with a fixed length
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["4"]); // string(3) "foo"

// Increase the size of the array to 10
$array->setSize(10);

$array[9] = "asdf";

// Shrink the array to a size of 2
$array->setSize(2);

// The following lines throw a RuntimeException: Index invalid or out of range
try {
    var_dump($array["non-numeric"]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[-1]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[5]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}
?>

Powyższy przykład wyświetli:

NULL
int(2)
string(3) "foo"
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range

Spis treści

  • SplFixedArray::__construct — Constructs a new fixed array
  • SplFixedArray::count — Returns the size of the array
  • SplFixedArray::current — Return current array entry
  • SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance
  • SplFixedArray::getSize — Gets the size of the array
  • SplFixedArray::key — Return current array index
  • SplFixedArray::next — Move to next entry
  • SplFixedArray::offsetExists — Returns whether the requested index exists
  • SplFixedArray::offsetGet — Returns the value at the specified index
  • SplFixedArray::offsetSet — Sets a new value at a specified index
  • SplFixedArray::offsetUnset — Unsets the value at the specified $index
  • SplFixedArray::rewind — Rewind iterator back to the start
  • SplFixedArray::setSize — Change the size of an array
  • SplFixedArray::toArray — Returns a PHP array from the fixed array
  • SplFixedArray::valid — Check whether the array contains more elements
SplPriorityQueue::valid
SplFixedArray::__construct
Struktury danych


Constructs a new fixed array

SplFixedArray
SplFixedArray::count
SplFixedArray
PHP Manual

SplFixedArray::__construct

(PHP 5 >= 5.3.0)

SplFixedArray::__construct — Constructs a new fixed array

Opis

public SplFixedArray::__construct() ([ int $size = 0 ] )

Initializes a fixed array with a number of NULL values equal to size.

Parametry

size

The size of the fixed array. This expects a number between 0 and PHP_INT_MAX.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws InvalidArgumentException when size is a negative number.

Raises E_WARNING when size cannot be parsed as a number.

Przykłady

Przykład #1 SplFixedArray::__construct() example

<?php
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

foreach($array as $v) {
  var_dump($v);
}
?>

Powyższy przykład wyświetli:

NULL
int(2)
NULL
NULL
string(3) "foo"

SplFixedArray
SplFixedArray::count
SplFixedArray


Returns the size of the array

SplFixedArray::__construct
SplFixedArray::current
SplFixedArray
PHP Manual

SplFixedArray::count

(PHP 5 >= 5.3.0)

SplFixedArray::count — Returns the size of the array

Opis

public int SplFixedArray::count ( void )

Returns the size of the array.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the size of the array.

Przykłady

Przykład #1 SplFixedArray::count() example

<?php
$array = new SplFixedArray(5);
echo $array->count() . "\n";
echo count($array) . "\n";
?>

Powyższy przykład wyświetli:

5
5

Notatki

Informacja:

This method is functionally equivalent to SplFixedArray::getSize().

Informacja:

The count of elements is always equal to the set size because all values are initially initialized with NULL.

Zobacz też:

  • SplFixedArray::getSize() - Gets the size of the array
SplFixedArray::__construct
SplFixedArray::current
SplFixedArray


Return current array entry

SplFixedArray::count
SplFixedArray::fromArray
SplFixedArray
PHP Manual

SplFixedArray::current

(PHP 5 >= 5.3.0)

SplFixedArray::current — Return current array entry

Opis

public mixed SplFixedArray::current ( void )

Get the current array element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current element value.

Błędy/Wyjątki

Throws RuntimeException when the internal array pointer points to an invalid index or is out of bounds.

SplFixedArray::count
SplFixedArray::fromArray
SplFixedArray


Import a PHP array in a SplFixedArray instance

SplFixedArray::current
SplFixedArray::getSize
SplFixedArray
PHP Manual

SplFixedArray::fromArray

(PHP 5 >= 5.3.0)

SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance

Opis

public static SplFixedArray SplFixedArray::fromArray ( array $array [, bool $save_indexes = true ] )

Import the PHP array array in a new SplFixedArray instance

Parametry

array

The array to import.

save_indexes

Try to save the numeric indexes used in the original array.

Zwracane wartości

Returns an instance of SplFixedArray containing the array content.

Przykłady

Przykład #1 SplFixedArray::fromArray() example

<?php
$fa = SplFixedArray::fromArray(array(1 => 1, 0 => 2, 3 => 3));

var_dump($fa);

$fa = SplFixedArray::fromArray(array(1 => 1, 0 => 2, 3 => 3), false);

var_dump($fa);
?>

Powyższy przykład wyświetli:

object(SplFixedArray)#1 (4) {
  [0]=>
  int(2)
  [1]=>
  int(1)
  [2]=>
  NULL
  [3]=>
  int(3)
}
object(SplFixedArray)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

SplFixedArray::current
SplFixedArray::getSize
SplFixedArray


Gets the size of the array

SplFixedArray::fromArray
SplFixedArray::key
SplFixedArray
PHP Manual

SplFixedArray::getSize

(PHP 5 >= 5.3.0)

SplFixedArray::getSize — Gets the size of the array

Opis

public int SplFixedArray::getSize ( void )

Gets the size of the array.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the size of the array, as an integer.

Przykłady

Przykład #1 SplFixedArray::getSize() example

<?php
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
$array->setSize(10);
echo $array->getSize()."\n";
?>

Powyższy przykład wyświetli:

5
10

Notatki

Informacja:

This method is functionally equivalent to SplFixedArray::count()

Zobacz też:

  • SplFixedArray::count() - Returns the size of the array
SplFixedArray::fromArray
SplFixedArray::key
SplFixedArray


Return current array index

SplFixedArray::getSize
SplFixedArray::next
SplFixedArray
PHP Manual

SplFixedArray::key

(PHP 5 >= 5.3.0)

SplFixedArray::key — Return current array index

Opis

public int SplFixedArray::key ( void )

Returns the current array index.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current array index.

SplFixedArray::getSize
SplFixedArray::next
SplFixedArray


Move to next entry

SplFixedArray::key
SplFixedArray::offsetExists
SplFixedArray
PHP Manual

SplFixedArray::next

(PHP 5 >= 5.3.0)

SplFixedArray::next — Move to next entry

Opis

public void SplFixedArray::next ( void )

Move the iterator to the next array entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplFixedArray::key
SplFixedArray::offsetExists
SplFixedArray


Returns whether the requested index exists

SplFixedArray::next
SplFixedArray::offsetGet
SplFixedArray
PHP Manual

SplFixedArray::offsetExists

(PHP 5 >= 5.3.0)

SplFixedArray::offsetExists — Returns whether the requested index exists

Opis

public bool SplFixedArray::offsetExists ( int $index )

Checks whether the requested index index exists.

Parametry

index

The index being checked.

Zwracane wartości

TRUE if the requested index exists, otherwise FALSE

SplFixedArray::next
SplFixedArray::offsetGet
SplFixedArray


Returns the value at the specified index

SplFixedArray::offsetExists
SplFixedArray::offsetSet
SplFixedArray
PHP Manual

SplFixedArray::offsetGet

(PHP 5 >= 5.3.0)

SplFixedArray::offsetGet — Returns the value at the specified index

Opis

public mixed SplFixedArray::offsetGet ( int $index )

Returns the value at the index index.

Parametry

index

The index with the value.

Zwracane wartości

The value at the specified index.

Błędy/Wyjątki

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

SplFixedArray::offsetExists
SplFixedArray::offsetSet
SplFixedArray


Sets a new value at a specified index

SplFixedArray::offsetGet
SplFixedArray::offsetUnset
SplFixedArray
PHP Manual

SplFixedArray::offsetSet

(PHP 5 >= 5.3.0)

SplFixedArray::offsetSet — Sets a new value at a specified index

Opis

public void SplFixedArray::offsetSet ( int $index , mixed $newval )

Sets the value at the specified index to newval.

Parametry

index

The index being set.

newval

The new value for the index.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

SplFixedArray::offsetGet
SplFixedArray::offsetUnset
SplFixedArray


Unsets the value at the specified $index

SplFixedArray::offsetSet
SplFixedArray::rewind
SplFixedArray
PHP Manual

SplFixedArray::offsetUnset

(PHP 5 >= 5.3.0)

SplFixedArray::offsetUnset — Unsets the value at the specified $index

Opis

public void SplFixedArray::offsetUnset ( int $index )

Unsets the value at the specified index.

Parametry

index

The index being unset.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

SplFixedArray::offsetSet
SplFixedArray::rewind
SplFixedArray


Rewind iterator back to the start

SplFixedArray::offsetUnset
SplFixedArray::setSize
SplFixedArray
PHP Manual

SplFixedArray::rewind

(PHP 5 >= 5.3.0)

SplFixedArray::rewind — Rewind iterator back to the start

Opis

public void SplFixedArray::rewind ( void )

Rewinds the iterator to the beginning.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplFixedArray::offsetUnset
SplFixedArray::setSize
SplFixedArray


Change the size of an array

SplFixedArray::rewind
SplFixedArray::toArray
SplFixedArray
PHP Manual

SplFixedArray::setSize

(PHP 5 >= 5.3.0)

SplFixedArray::setSize — Change the size of an array

Opis

public int SplFixedArray::setSize ( int $size )

Change the size of an array to the new size of size. If size is less than the current array size, any values after the new size will be discarded. If size is greater than the current array size, the array will be padded with NULL values.

Parametry

size

The new array size. This should be a value between 0 and PHP_INT_MAX.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws InvalidArgumentException when size is less than zero.

Raises E_WARNING when size cannot be used as a number.

Przykłady

Przykład #1 SplFixedArray::setSize() example

<?php
   $array = new SplFixedArray(5);
   echo $array->getSize()."\n";
   $array->setSize(10);
   echo $array->getSize()."\n";
?>

Powyższy przykład wyświetli:

5
10

SplFixedArray::rewind
SplFixedArray::toArray
SplFixedArray


Returns a PHP array from the fixed array

SplFixedArray::setSize
SplFixedArray::valid
SplFixedArray
PHP Manual

SplFixedArray::toArray

(PHP 5 >= 5.3.0)

SplFixedArray::toArray — Returns a PHP array from the fixed array

Opis

public array SplFixedArray::toArray ( void )

Returns a PHP array from the fixed array.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a PHP array, similar to the fixed array.

Przykłady

Przykład #1 SplFixedArray::toArray() example

<?php
$fa = new SplFixedArray(3);
$fa[0] = 0;
$fa[2] = 2;
var_dump($fa->toArray());
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  int(0)
  [1]=>
  NULL
  [2]=>
  int(2)
}

SplFixedArray::setSize
SplFixedArray::valid
SplFixedArray


Check whether the array contains more elements

SplFixedArray::toArray
SplObjectStorage
SplFixedArray
PHP Manual

SplFixedArray::valid

(PHP 5 >= 5.3.0)

SplFixedArray::valid — Check whether the array contains more elements

Opis

public bool SplFixedArray::valid ( void )

Checks if the array contains any more elements.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the array contains any more elements, FALSE otherwise.

SplFixedArray::toArray
SplObjectStorage
SplFixedArray


The SplObjectStorage class

(PHP 5 >= 5.3.0)

Wstęp

The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects.

Krótki opis klasy

SplObjectStorage implements Countable , Iterator , Traversable , Serializable , ArrayAccess {
/* Metody */
public void addAll ( SplObjectStorage $storage )
public void attach ( object $object [, mixed $data = NULL ] )
public bool contains ( object $object )
public int count ( void )
public object current ( void )
public void detach ( object $object )
public string getHash ( string $object )
public mixed getInfo ( void )
public int key ( void )
public void next ( void )
public bool offsetExists ( object $object )
public mixed offsetGet ( object $object )
public void offsetSet ( object $object [, mixed $data = NULL ] )
public void offsetUnset ( object $object )
public void removeAll ( SplObjectStorage $storage )
public void removeAllExcept ( SplObjectStorage $storage )
public void rewind ( void )
public string serialize ( void )
public void setInfo ( mixed $data )
public void unserialize ( string $serialized )
public bool valid ( void )
}

Przykłady

Przykład #1 SplObjectStorage as a set

<?php
// As an object set
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s->attach($o1);
$s->attach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));

$s->detach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));
?>

Powyższy przykład wyświetli:

bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

Przykład #2 SplObjectStorage as a map

<?php
// As a map from objects to data
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s[$o1] = "data for object 1";
$s[$o2] = array(1,2,3);

if (isset($s[$o2])) {
    var_dump($s[$o2]);
}
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Spis treści

  • SplObjectStorage::addAll — Adds all objects from another storage
  • SplObjectStorage::attach — Adds an object in the storage
  • SplObjectStorage::contains — Checks if the storage contains a specific object
  • SplObjectStorage::count — Returns the number of objects in the storage
  • SplObjectStorage::current — Returns the current storage entry
  • SplObjectStorage::detach — Removes an object from the storage
  • SplObjectStorage::getHash — Calculate a unique identifier for the contained objects
  • SplObjectStorage::getInfo — Returns the data associated with the current iterator entry
  • SplObjectStorage::key — Returns the index at which the iterator currently is
  • SplObjectStorage::next — Move to the next entry
  • SplObjectStorage::offsetExists — Checks whether an object exists in the storage
  • SplObjectStorage::offsetGet — Returns the data associated with an object
  • SplObjectStorage::offsetSet — Associates data to an object in the storage
  • SplObjectStorage::offsetUnset — Removes an object from the storage
  • SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage
  • SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage
  • SplObjectStorage::rewind — Rewind the iterator to the first storage element
  • SplObjectStorage::serialize — Serializes the storage
  • SplObjectStorage::setInfo — Sets the data associated with the current iterator entry
  • SplObjectStorage::unserialize — Unserializes a storage from its string representation
  • SplObjectStorage::valid — Returns if the current iterator entry is valid
SplFixedArray::valid
SplObjectStorage::addAll
Struktury danych


Adds all objects from another storage

SplObjectStorage
SplObjectStorage::attach
SplObjectStorage
PHP Manual

SplObjectStorage::addAll

(PHP 5 >= 5.3.0)

SplObjectStorage::addAll — Adds all objects from another storage

Opis

public void SplObjectStorage::addAll ( SplObjectStorage $storage )

Adds all objects-data pairs from a different storage in the current storage.

Parametry

storage

The storage you want to import.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::addAll() example

<?php
$o = new StdClass;
$a = new SplObjectStorage();
$a[$o] = "hello";

$b = new SplObjectStorage();
$b->addAll($a);
echo $b[$o]."\n";
?>

Powyższy przykład wyświetli coś podobnego do:

hello

Zobacz też:

  • SplObjectStorage::removeAll() - Removes objects contained in another storage from the current storage

SplObjectStorage
SplObjectStorage::attach
SplObjectStorage


Adds an object in the storage

SplObjectStorage::addAll
SplObjectStorage::contains
SplObjectStorage
PHP Manual

SplObjectStorage::attach

(PHP 5 >= 5.1.0)

SplObjectStorage::attach — Adds an object in the storage

Opis

public void SplObjectStorage::attach ( object $object [, mixed $data = NULL ] )

Adds an object inside the storage, and optionaly associate it to some data.

Parametry

object

The object to add.

data

The data to associate with the object.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::attach() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$s = new SplObjectStorage();
$s->attach($o1); // similar to $s[$o1] = NULL;
$s->attach($o2, "hello"); // similar to $s[$o2] = "hello";

var_dump($s[$o1]);
var_dump($s[$o2]);

?>

Powyższy przykład wyświetli coś podobnego do:

NULL
string(5) "hello"

Rejestr zmian

Wersja | Opis
5.3.0 | Added the data parameter.

Zobacz też:

  • SplObjectStorage::detach() - Removes an object from the storage
  • SplObjectStorage::offsetSet() - Associates data to an object in the storage

SplObjectStorage::addAll
SplObjectStorage::contains
SplObjectStorage


Checks if the storage contains a specific object

SplObjectStorage::attach
SplObjectStorage::count
SplObjectStorage
PHP Manual

SplObjectStorage::contains

(PHP 5 >= 5.1.0)

SplObjectStorage::contains — Checks if the storage contains a specific object

Opis

public bool SplObjectStorage::contains ( object $object )

Checks if the storage contains the object provided.

Parametry

object

The object to look for.

Zwracane wartości

Returns TRUE if the object is in the storage, FALSE otherwise.

Przykłady

Przykład #1 SplObjectStorage::contains() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;

$s = new SplObjectStorage();

$s[$o1] = "hello";
var_dump($s->contains($o1));
var_dump($s->contains($o2));
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(false)

Zobacz też:

  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage

SplObjectStorage::attach
SplObjectStorage::count
SplObjectStorage


Returns the number of objects in the storage

SplObjectStorage::contains
SplObjectStorage::current
SplObjectStorage
PHP Manual

SplObjectStorage::count

(PHP 5 >= 5.1.0)

SplObjectStorage::count — Returns the number of objects in the storage

Opis

public int SplObjectStorage::count ( void )

Counts the number of objects in the storage.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The number of objects in the storage.

Przykłady

Przykład #1 SplObjectStorage::count() example

<?php
$s = new SplObjectStorage();
$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1);
$s->attach($o2);
$s->attach($o1);
var_dump($s->count());
var_dump(count($s));
?>

Powyższy przykład wyświetli coś podobnego do:

int(2)
int(2)

Zobacz też:

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::detach() - Removes an object from the storage

SplObjectStorage::contains
SplObjectStorage::current
SplObjectStorage


Returns the current storage entry

SplObjectStorage::count
SplObjectStorage::detach
SplObjectStorage
PHP Manual

SplObjectStorage::current

(PHP 5 >= 5.1.0)

SplObjectStorage::current — Returns the current storage entry

Opis

public object SplObjectStorage::current ( void )

Returns the current storage entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The object at the current iterator position.

Przykłady

Przykład #1 SplObjectStorage::current() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

Zobacz też:

  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

SplObjectStorage::count
SplObjectStorage::detach
SplObjectStorage


Removes an object from the storage

SplObjectStorage::current
SplObjectStorage::getHash
SplObjectStorage
PHP Manual

SplObjectStorage::detach

(PHP 5 >= 5.1.0)

SplObjectStorage::detach — Removes an object from the storage

Opis

public void SplObjectStorage::detach ( object $object )

Removes the object from the storage.

Parametry

object

The object to remove.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::detach() example

<?php
$o = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->detach($o);
var_dump(count($s));
?>

Powyższy przykład wyświetli coś podobnego do:

int(1)
int(0)

Zobacz też:

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::removeAll() - Removes objects contained in another storage from the current storage

SplObjectStorage::current
SplObjectStorage::getHash
SplObjectStorage


Calculate a unique identifier for the contained objects

SplObjectStorage::detach
SplObjectStorage::getInfo
SplObjectStorage
PHP Manual

SplObjectStorage::getHash

(No version information available, might only be in SVN)

SplObjectStorage::getHash — Calculate a unique identifier for the contained objects

Opis

public string SplObjectStorage::getHash ( string $object )

The function calculates an identifier for the objects added to this SplObjectStorage object.

The implementation in SplObjectStorage returns the same value as spl_object_hash().

This identifier must be unique among the objects contained. This means this object will never contain more than one object with the same identifier. As such, it can be used to implement a set (a collection of unique values) where the quality of an object being unique is determined by the value returned by this function being unique.

Parametry

object

The object whose identifier is to be calculated.

Zwracane wartości

A string with the calculated identifier. An exception is thrown if any other type is returned.

Przykłady

Przykład #1 SplObjectStorage::getHash() example

<?php
class OneSpecimenPerClassStorage extends SplObjectStorage {
    public function getHash($o) {
        return get_class($o);
    }
}
class A {}

$s = new OneSpecimenPerClassStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o3 = new A;

$s[$o1] = 1;
//$o2 is considered equal to $o1 so the value is replaced
$s[$o2] = 2;
$s[$o3] = 3;

//these are considered equal to the objects before
//so they can be used to access the values stored under them
$p1 = new stdClass;
$p2 = new A;
echo $s[$p1], "\n";
echo $s[$p2], "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

2
3

SplObjectStorage::detach
SplObjectStorage::getInfo
SplObjectStorage


Returns the data associated with the current iterator entry

SplObjectStorage::getHash
SplObjectStorage::key
SplObjectStorage
PHP Manual

SplObjectStorage::getInfo

(PHP 5 >= 5.3.0)

SplObjectStorage::getInfo — Returns the data associated with the current iterator entry

Opis

public mixed SplObjectStorage::getInfo ( void )

Returns the data, or info, associated with the object pointed by the current iterator position.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The data associated with the current iterator position.

Przykłady

Przykład #1 SplObjectStorage::getInfo() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

Zobacz też:

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::setInfo() - Sets the data associated with the current iterator entry

SplObjectStorage::getHash
SplObjectStorage::key
SplObjectStorage


Returns the index at which the iterator currently is

SplObjectStorage::getInfo
SplObjectStorage::next
SplObjectStorage
PHP Manual

SplObjectStorage::key

(PHP 5 >= 5.1.0)

SplObjectStorage::key — Returns the index at which the iterator currently is

Opis

public int SplObjectStorage::key ( void )

Returns the index at which the iterator currently is.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The index corresponding to the position of the iterator.

Przykłady

Przykład #1 SplObjectStorage::key() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)

    var_dump($index);
    var_dump($object);
    $s->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

Zobacz też:

  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid

SplObjectStorage::getInfo
SplObjectStorage::next
SplObjectStorage


Move to the next entry

SplObjectStorage::key
SplObjectStorage::offsetExists
SplObjectStorage
PHP Manual

SplObjectStorage::next

(PHP 5 >= 5.1.0)

SplObjectStorage::next — Move to the next entry

Opis

public void SplObjectStorage::next ( void )

Moves the iterator to the next object in the storage.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::next() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)

    var_dump($index);
    var_dump($object);
    $s->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

Zobacz też:

  • SPLObjectStorage::rewind() - Rewind the iterator to the first storage element

SplObjectStorage::key
SplObjectStorage::offsetExists
SplObjectStorage


Checks whether an object exists in the storage

SplObjectStorage::next
SplObjectStorage::offsetGet
SplObjectStorage
PHP Manual

SplObjectStorage::offsetExists

(PHP 5 >= 5.3.0)

SplObjectStorage::offsetExists — Checks whether an object exists in the storage

Opis

public bool SplObjectStorage::offsetExists ( object $object )

Checks whether an object exists in the storage.

Parametry

object

The object to look for.

Zwracane wartości

Returns TRUE if the object exists in the storage, and FALSE otherwise.

Przykłady

Przykład #1 SplObjectStorage::offsetExists() example

<?php
$s = new SplObjectStorage;
$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1);

var_dump($s->offsetExists($o1)); // Similar to isset($s[$o1])
var_dump($s->offsetExists($o2)); // Similar to isset($s[$o2])
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(false)

Zobacz też:

  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

SplObjectStorage::next
SplObjectStorage::offsetGet
SplObjectStorage


Returns the data associated with an object

SplObjectStorage::offsetExists
SplObjectStorage::offsetSet
SplObjectStorage
PHP Manual

SplObjectStorage::offsetGet

(PHP 5 >= 5.3.0)

SplObjectStorage::offsetGet — Returns the data associated with an object

Opis

public mixed SplObjectStorage::offsetGet ( object $object )

Returns the data associated with an object in the storage.

Parametry

object

The object to look for.

Zwracane wartości

The data previously associated with the object in the storage.

Błędy/Wyjątki

Throws UnexpectedValueException when object could not be found.

Przykłady

Przykład #1 SplObjectStorage::offsetGet() example

<?php
$s = new SplObjectStorage;

$o1 = new StdClass;
$o2 = new StdClass;

$s[$o1] = "hello";
$s->attach($o2);

var_dump($s->offsetGet($o1)); // Similar to $s[$o1]
var_dump($s->offsetGet($o2)); // Similar to $s[$o2]
?>

Powyższy przykład wyświetli coś podobnego do:

string(5) "hello"
NULL

Zobacz też:

  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

SplObjectStorage::offsetExists
SplObjectStorage::offsetSet
SplObjectStorage


Associates data to an object in the storage

SplObjectStorage::offsetGet
SplObjectStorage::offsetUnset
SplObjectStorage
PHP Manual

SplObjectStorage::offsetSet

(PHP 5 >= 5.3.0)

SplObjectStorage::offsetSet — Associates data to an object in the storage

Opis

public void SplObjectStorage::offsetSet ( object $object [, mixed $data = NULL ] )

Associate data to an object in the storage.

Informacja:

SplObjectStorage::offsetSet() is an alias of SplObjectStorage::attach().

Parametry

object

The object to associate data with.

data

The data to associate with the object.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::offsetSet() example

<?php
$s = new SplObjectStorage;

$o1 = new StdClass;

$s->offsetSet($o1, "hello"); // Similar to $s[$o1] = "hello";

var_dump($s[$o1]);
?>

Powyższy przykład wyświetli coś podobnego do:

string(5) "hello"

Zobacz też:

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

SplObjectStorage::offsetGet
SplObjectStorage::offsetUnset
SplObjectStorage


Removes an object from the storage

SplObjectStorage::offsetSet
SplObjectStorage::removeAll
SplObjectStorage
PHP Manual

SplObjectStorage::offsetUnset

(PHP 5 >= 5.3.0)

SplObjectStorage::offsetUnset — Removes an object from the storage

Opis

public void SplObjectStorage::offsetUnset ( object $object )

Removes an object from the storage.

Informacja:

SplObjectStorage::offsetUnset() is an alias of SplObjectStorage::detach().

Parametry

object

The object to remove.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::offsetUnset() example

<?php
$o = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->offsetUnset($o); // Similar to unset($s[$o])
var_dump(count($s));
?>

Powyższy przykład wyświetli coś podobnego do:

int(1)
int(0)

Zobacz też:

  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage

SplObjectStorage::offsetSet
SplObjectStorage::removeAll
SplObjectStorage


Removes objects contained in another storage from the current storage

SplObjectStorage::offsetUnset
SplObjectStorage::removeAllExcept
SplObjectStorage
PHP Manual

SplObjectStorage::removeAll

(PHP 5 >= 5.3.0)

SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage

Opis

public void SplObjectStorage::removeAll ( SplObjectStorage $storage )

Removes objects contained in another storage from the current storage.

Parametry

storage

The storage containing the elements to remove.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::removeAll() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$a = new SplObjectStorage();
$a[$o1] = "foo";

$b = new SplObjectStorage();
$b[$o1] = "bar";
$b[$o2] = "gee";

var_dump(count($b));
$b->removeAll($a);
var_dump(count($b));
?>

Powyższy przykład wyświetli coś podobnego do:

int(2)
int(1)

Zobacz też:

  • SplObjectStorage::addAll() - Adds all objects from another storage

SplObjectStorage::offsetUnset
SplObjectStorage::removeAllExcept
SplObjectStorage


Removes all objects except for those contained in another storage from the current storage

SplObjectStorage::removeAll
SplObjectStorage::rewind
SplObjectStorage
PHP Manual

SplObjectStorage::removeAllExcept

(PHP 5 >= 5.3.6)

SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage

Opis

public void SplObjectStorage::removeAllExcept ( SplObjectStorage $storage )

Removes all objects except for those contained in another storage from the current storage.

Parametry

storage

The storage containing the elements to retain in the current storage.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::removeAllExcept() example

<?php
$a = (object) 'a';
$b = (object) 'b';
$c = (object) 'c';

$foo = new SplObjectStorage;
$foo->attach($a);
$foo->attach($b);

$bar = new SplObjectStorage;
$bar->attach($b);
$bar->attach($c);

$foo->removeAllExcept($bar);
var_dump($foo->contains($a));
var_dump($foo->contains($b));
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)

SplObjectStorage::removeAll
SplObjectStorage::rewind
SplObjectStorage


Rewind the iterator to the first storage element

SplObjectStorage::removeAllExcept
SplObjectStorage::serialize
SplObjectStorage
PHP Manual

SplObjectStorage::rewind

(PHP 5 >= 5.1.0)

SplObjectStorage::rewind — Rewind the iterator to the first storage element

Opis

public void SplObjectStorage::rewind ( void )

Rewind the iterator to the first storage element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::rewind() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

int(1)
int(0)

Zobacz też:

  • SplObjectStorage::next() - Move to the next entry

SplObjectStorage::removeAllExcept
SplObjectStorage::serialize
SplObjectStorage


Serializes the storage

SplObjectStorage::rewind
SplObjectStorage::setInfo
SplObjectStorage
PHP Manual

SplObjectStorage::serialize

(PHP 5 >= 5.2.2)

SplObjectStorage::serialize — Serializes the storage

Opis

public string SplObjectStorage::serialize ( void )

Returns a string representation of the storage.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A string representing the storage.

Przykłady

Przykład #1 SplObjectStorage::serialize() example

<?php
$s = new SplObjectStorage;
$o = new StdClass;
$s[$o] = "data";

echo $s->serialize()."\n";
?>

Powyższy przykład wyświetli coś podobnego do:

x:i:1;O:8:"stdClass":0:{},s:4:"data";;m:a:0:{}

Zobacz też:

  • SplObjectStorage::unserialize() - Unserializes a storage from its string representation

SplObjectStorage::rewind
SplObjectStorage::setInfo
SplObjectStorage


Sets the data associated with the current iterator entry

SplObjectStorage::serialize
SplObjectStorage::unserialize
SplObjectStorage
PHP Manual

SplObjectStorage::setInfo

(PHP 5 >= 5.3.0)

SplObjectStorage::setInfo — Sets the data associated with the current iterator entry

Opis

public void SplObjectStorage::setInfo ( mixed $data )

Associates data, or info, with the object currently pointed to by the iterator.

Parametry

data

The data to associate with the current iterator entry.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::setInfo() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $s->setInfo("new");
    $s->next();
}
var_dump($s[$o1]);
var_dump($s[$o2]);
?>

Powyższy przykład wyświetli coś podobnego do:

string(3) "new"
string(3) "new"

Zobacz też:

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

SplObjectStorage::serialize
SplObjectStorage::unserialize
SplObjectStorage


Unserializes a storage from its string representation

SplObjectStorage::setInfo
SplObjectStorage::valid
SplObjectStorage
PHP Manual

SplObjectStorage::unserialize

(PHP 5 >= 5.2.2)

SplObjectStorage::unserialize — Unserializes a storage from its string representation

Opis

public void SplObjectStorage::unserialize ( string $serialized )

Unserializes storage entries and attach them to the current storage.

Parametry

serialized

The serialized representation of a storage.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplObjectStorage::unserialize() example

<?php
$s1 = new SplObjectStorage;
$s2 = new SplObjectStorage;
$o = new StdClass;
$s1[$o] = "data";

$s2->unserialize($s1->serialize());

var_dump(count($s2));
?>

Powyższy przykład wyświetli coś podobnego do:

int(1)

Zobacz też:

  • SplObjectStorage::serialize() - Serializes the storage

SplObjectStorage::setInfo
SplObjectStorage::valid
SplObjectStorage


Returns if the current iterator entry is valid

SplObjectStorage::unserialize
Iteratory
SplObjectStorage
PHP Manual

SplObjectStorage::valid

(PHP 5 >= 5.1.0)

SplObjectStorage::valid — Returns if the current iterator entry is valid

Opis

public bool SplObjectStorage::valid ( void )

Returns if the current iterator entry is valid.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the iterator entry is valid, FALSE otherwise.

Przykłady

Przykład #1 SplObjectStorage::valid() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    echo $s->key()."\n";
    $s->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

0
1

Zobacz też:

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

SplObjectStorage::unserialize
Iteratory
SplObjectStorage


Iteratory

Spis treści

  • AppendIterator
  • ArrayIterator
  • CachingIterator
  • CallbackFilterIterator
  • DirectoryIterator
  • EmptyIterator
  • FilesystemIterator
  • FilterIterator
  • GlobIterator
  • InfiniteIterator
  • IteratorIterator
  • LimitIterator
  • MultipleIterator
  • NoRewindIterator
  • ParentIterator
  • RecursiveArrayIterator
  • RecursiveCachingIterator
  • RecursiveCallbackFilterIterator
  • RecursiveDirectoryIterator
  • RecursiveFilterIterator
  • RecursiveIteratorIterator
  • RecursiveRegexIterator
  • RecursiveTreeIterator
  • RegexIterator

SPL provides a set of iterators to traverse over objects.

Undocumented Iterators

  • RecursiveTreeIterator
SplObjectStorage::valid
AppendIterator
SPL


The AppendIterator class

(PHP 5 >= 5.1.0)

Wstęp

An Iterator that iterates over several iterators one after the other.

Krótki opis klasy

AppendIterator extends IteratorIterator implements OuterIterator , Traversable , Iterator {
/* Metody */
public __construct ( void )
public void append ( Iterator $iterator )
public void current ( void )
public void getArrayIterator ( void )
public void getInnerIterator ( void )
public void getIteratorIndex ( void )
public void key ( void )
public void next ( void )
public void rewind ( void )
public void valid ( void )
/* Metody dziedziczone */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public void IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Spis treści

  • AppendIterator::append — Appends an iterator
  • AppendIterator::__construct — Constructs an AppendIterator
  • AppendIterator::current — Gets the current value
  • AppendIterator::getArrayIterator — The getArrayIterator method
  • AppendIterator::getInnerIterator — Gets an inner iterator
  • AppendIterator::getIteratorIndex — Gets an index of iterators
  • AppendIterator::key — Gets the current key
  • AppendIterator::next — Moves to the next element
  • AppendIterator::rewind — Rewinds the Iterator
  • AppendIterator::valid — Checks validity of the current element
Iteratory
AppendIterator::append
Iteratory


Appends an iterator

AppendIterator
AppendIterator::__construct
AppendIterator
PHP Manual

AppendIterator::append

(PHP 5 >= 5.1.0)

AppendIterator::append — Appends an iterator

Opis

public void AppendIterator::append ( Iterator $iterator )

Appends an iterator.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iterator

The iterator to append.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • AppendIterator::__construct() - Constructs an AppendIterator

AppendIterator
AppendIterator::__construct
AppendIterator


Constructs an AppendIterator

AppendIterator::append
AppendIterator::current
AppendIterator
PHP Manual

AppendIterator::__construct

(PHP 5 >= 5.1.0)

AppendIterator::__construct — Constructs an AppendIterator

Opis

public AppendIterator::__construct() ( void )

Constructs an AppendIterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Iterating AppendIterator with foreach

<?php
$pizzas   = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));

$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);

foreach ($appendIterator as $key => $item) {
    echo "$key => $item", PHP_EOL;
}
?>

Powyższy przykład wyświetli coś podobnego do:

0 => Margarita
1 => Siciliana
2 => Hawaii
0 => Cheese
1 => Anchovies
2 => Olives
3 => Pineapple
4 => Ham

Przykład #2 Iterating AppendIterator with the AppendIterator API

<?php
$pizzas   = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));

$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);

while ($appendIterator->valid()) {
    printf(
        '%s => %s => %s%s',
        $appendIterator->getIteratorIndex(),
        $appendIterator->key(),
        $appendIterator->current(),
        PHP_EOL
    );
    $appendIterator->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

0 => 0 => Margarita
0 => 1 => Siciliana
0 => 2 => Hawaii
1 => 0 => Cheese
1 => 1 => Anchovies
1 => 2 => Olives
1 => 3 => Pineapple
1 => 4 => Ham

Notatki

Uwaga

When using iterator_to_array() to copy the values of the AppendIterator into an array, you have to set the optional use_key argument to FALSE. When use_key is not FALSE any keys reoccuring in inner iterators will get overwritten in the returned array. There is no way to preserve the original keys.

Zobacz też:

  • AppendIterator::append() - Appends an iterator

AppendIterator::append
AppendIterator::current
AppendIterator


Gets the current value

AppendIterator::__construct
AppendIterator::getArrayIterator
AppendIterator
PHP Manual

AppendIterator::current

(PHP 5 >= 5.1.0)

AppendIterator::current — Gets the current value

Opis

public void AppendIterator::current ( void )

Gets the current value.

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 current value if it is valid or NULL otherwise.

Zobacz też:

  • AppendIterator::next() - Moves to the next element

AppendIterator::__construct
AppendIterator::getArrayIterator
AppendIterator


The getArrayIterator method

AppendIterator::current
AppendIterator::getInnerIterator
AppendIterator
PHP Manual

AppendIterator::getArrayIterator

(PHP 5 >= 5.1.0)

AppendIterator::getArrayIterator — The getArrayIterator method

Opis

public void AppendIterator::getArrayIterator ( void )

The getArrayIterator method

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

Zobacz też:

  • AppendIterator::getInnerIterator() - Gets an inner iterator

AppendIterator::current
AppendIterator::getInnerIterator
AppendIterator


Gets an inner iterator

AppendIterator::getArrayIterator
AppendIterator::getIteratorIndex
AppendIterator
PHP Manual

AppendIterator::getInnerIterator

(PHP 5 >= 5.1.0)

AppendIterator::getInnerIterator — Gets an inner iterator

Opis

public void AppendIterator::getInnerIterator ( void )

Get an inner iterator

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 current inner Iterator.

Zobacz też:

  • AppendIterator::getArrayIterator() - The getArrayIterator method

AppendIterator::getArrayIterator
AppendIterator::getIteratorIndex
AppendIterator


Gets an index of iterators

AppendIterator::getInnerIterator
AppendIterator::key
AppendIterator
PHP Manual

AppendIterator::getIteratorIndex

(PHP 5 >= 5.1.0)

AppendIterator::getIteratorIndex — Gets an index of iterators

Opis

public void AppendIterator::getIteratorIndex ( void )

Get an index of iterators.

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 index of iterators.

Zobacz też:

  • AppendIterator::getInnerIterator() - Gets an inner iterator

AppendIterator::getInnerIterator
AppendIterator::key
AppendIterator


Gets the current key

AppendIterator::getIteratorIndex
AppendIterator::next
AppendIterator
PHP Manual

AppendIterator::key

(PHP 5 >= 5.1.0)

AppendIterator::key — Gets the current key

Opis

public void AppendIterator::key ( void )

Get the current key

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 current key if it is valid or NULL otherwise.

Zobacz też:

  • AppendIterator::current() - Gets the current value

AppendIterator::getIteratorIndex
AppendIterator::next
AppendIterator


Moves to the next element

AppendIterator::key
AppendIterator::rewind
AppendIterator
PHP Manual

AppendIterator::next

(PHP 5 >= 5.1.0)

AppendIterator::next — Moves to the next element

Opis

public void AppendIterator::next ( void )

Moves to the next element. If this means to another Iterator then it rewinds that Iterator.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • AppendIterator::rewind() - Rewinds the Iterator

AppendIterator::key
AppendIterator::rewind
AppendIterator


Rewinds the Iterator

AppendIterator::next
AppendIterator::valid
AppendIterator
PHP Manual

AppendIterator::rewind

(PHP 5 >= 5.1.0)

AppendIterator::rewind — Rewinds the Iterator

Opis

public void AppendIterator::rewind ( void )

Rewind to the first element of the first inner Iterator.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • AppendIterator::next() - Moves to the next element

AppendIterator::next
AppendIterator::valid
AppendIterator


Checks validity of the current element

AppendIterator::rewind
ArrayIterator
AppendIterator
PHP Manual

AppendIterator::valid

(PHP 5 >= 5.1.0)

AppendIterator::valid — Checks validity of the current element

Opis

public void AppendIterator::valid ( void )

Checks validity of the current element.

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

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • AppendIterator::append() - Appends an iterator

AppendIterator::rewind
ArrayIterator
AppendIterator


The ArrayIterator class

(PHP 5)

Wstęp

This iterator allows to unset and modify values and keys while iterating over Arrays and Objects.

When you want to iterate over the same array multiple times you need to instantiate ArrayObject and let it create ArrayIterator instances that refer to it either by using foreach or by calling its getIterator() method manually.

Krótki opis klasy

ArrayIterator implements Iterator , Traversable , ArrayAccess , SeekableIterator , Countable , Serializable {
/* Metody */
public void append ( mixed $value )
public void asort ( void )
public __construct ( mixed $array )
public int count ( void )
public mixed current ( void )
public array getArrayCopy ( void )
public void getFlags ( void )
public mixed key ( void )
public void ksort ( void )
public void natcasesort ( void )
public void natsort ( void )
public void next ( void )
public void offsetExists ( string $index )
public mixed offsetGet ( string $index )
public void offsetSet ( string $index , string $newval )
public void offsetUnset ( string $index )
public void rewind ( void )
public void seek ( int $position )
public string serialize ( void )
public void setFlags ( string $flags )
public void uasort ( string $cmp_function )
public void uksort ( string $cmp_function )
public string unserialize ( string $serialized )
public bool valid ( void )
}

Spis treści

  • ArrayIterator::append — Append an element
  • ArrayIterator::asort — Sort array by values
  • ArrayIterator::__construct — Construct an ArrayIterator
  • ArrayIterator::count — Count elements
  • ArrayIterator::current — Return current array entry
  • ArrayIterator::getArrayCopy — Get array copy
  • ArrayIterator::getFlags — Get flags
  • ArrayIterator::key — Return current array key
  • ArrayIterator::ksort — Sort array by keys
  • ArrayIterator::natcasesort — Sort an array naturally, case insensitive
  • ArrayIterator::natsort — Sort an array naturally
  • ArrayIterator::next — Move to next entry
  • ArrayIterator::offsetExists — Check if offset exists
  • ArrayIterator::offsetGet — Get value for an offset
  • ArrayIterator::offsetSet — Set value for an offset
  • ArrayIterator::offsetUnset — Unset value for an offset
  • ArrayIterator::rewind — Rewind array back to the start
  • ArrayIterator::seek — Seek to position
  • ArrayIterator::serialize — Serialize
  • ArrayIterator::setFlags — Set behaviour flags
  • ArrayIterator::uasort — User defined sort
  • ArrayIterator::uksort — User defined sort
  • ArrayIterator::unserialize — Unserialize
  • ArrayIterator::valid — Check whether array contains more entries
AppendIterator::valid
ArrayIterator::append
Iteratory


Append an element

ArrayIterator
ArrayIterator::asort
ArrayIterator
PHP Manual

ArrayIterator::append

(PHP 5 >= 5.0.0)

ArrayIterator::append — Append an element

Opis

public void ArrayIterator::append ( mixed $value )

Appends value as the last element.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

value

The value to append.

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja:

This method cannot be called when the ArrayIterator refers to an object.

Zobacz też:

  • ArrayIterator::next() - Move to next entry

ArrayIterator
ArrayIterator::asort
ArrayIterator


Sort array by values

ArrayIterator::append
ArrayIterator::__construct
ArrayIterator
PHP Manual

ArrayIterator::asort

(PHP 5 >= 5.2.0)

ArrayIterator::asort — Sort array by values

Opis

public void ArrayIterator::asort ( void )

Sorts an array by values.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • ArrayIterator::natsort() - Sort an array naturally

ArrayIterator::append
ArrayIterator::__construct
ArrayIterator


Construct an ArrayIterator

ArrayIterator::asort
ArrayIterator::count
ArrayIterator
PHP Manual

ArrayIterator::__construct

(PHP 5 >= 5.0.0)

ArrayIterator::__construct — Construct an ArrayIterator

Opis

public ArrayIterator::__construct ( mixed $array )

Constructs an ArrayIterator object.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

array

The array or object to be iterated on.

Zwracane wartości

An ArrayIterator object.

Błędy/Wyjątki

ArrayIterator::__construct() throws an InvalidArgumentException if anything besides an array or an object is given.

Zobacz też:

  • ArrayIterator::getArrayCopy() - Get array copy

ArrayIterator::asort
ArrayIterator::count
ArrayIterator


Count elements

ArrayIterator::__construct
ArrayIterator::current
ArrayIterator
PHP Manual

ArrayIterator::count

(PHP 5 >= 5.0.0)

ArrayIterator::count — Count elements

Opis

public int ArrayIterator::count ( void )

Gets the number of elements in the array, or the number of public properties in the object.

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 elements or public properties in the associated array or object, respectively.

Zobacz też:

  • ArrayIterator::getFlags() - Get flags

ArrayIterator::__construct
ArrayIterator::current
ArrayIterator


Return current array entry

ArrayIterator::count
ArrayIterator::getArrayCopy
ArrayIterator
PHP Manual

ArrayIterator::current

(PHP 5 >= 5.0.0)

ArrayIterator::current — Return current array entry

Opis

public mixed ArrayIterator::current ( void )

Get the current array entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current array entry.

Przykłady

Przykład #1 ArrayIterator::current() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

for($iterator = $arrayobject->getIterator();
    $iterator->valid();
    $iterator->next()) {

    echo $iterator->key() . ' => ' . $iterator->current() . "\n";
}
?>

Powyższy przykład wyświetli:

1 => one
2 => two
3 => three

ArrayIterator::count
ArrayIterator::getArrayCopy
ArrayIterator


Get array copy

ArrayIterator::current
ArrayIterator::getFlags
ArrayIterator
PHP Manual

ArrayIterator::getArrayCopy

(PHP 5 >= 5.0.0)

ArrayIterator::getArrayCopy — Get array copy

Opis

public array ArrayIterator::getArrayCopy ( void )

Get a copy of an array.

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

A copy of the array, or array of public properties if ArrayIterator refers to an object.

Zobacz też:

  • ArrayIterator::valid() - Check whether array contains more entries

ArrayIterator::current
ArrayIterator::getFlags
ArrayIterator


Get flags

ArrayIterator::getArrayCopy
ArrayIterator::key
ArrayIterator
PHP Manual

ArrayIterator::getFlags

(PHP 5 >= 5.1.0)

ArrayIterator::getFlags — Get flags

Opis

public void ArrayIterator::getFlags ( void )

Get the current flags.

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 current flags.

Zobacz też:

  • ArrayIterator::valid() - Check whether array contains more entries

ArrayIterator::getArrayCopy
ArrayIterator::key
ArrayIterator


Return current array key

ArrayIterator::getFlags
ArrayIterator::ksort
ArrayIterator
PHP Manual

ArrayIterator::key

(PHP 5 >= 5.0.0)

ArrayIterator::key — Return current array key

Opis

public mixed ArrayIterator::key ( void )

This function returns the current array key

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current array key.

Przykłady

Przykład #1 ArrayIterator::key() example

<?php
$array = array('key' => 'value');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

echo $iterator->key(); //key
?>

ArrayIterator::getFlags
ArrayIterator::ksort
ArrayIterator


Sort array by keys

ArrayIterator::key
ArrayIterator::natcasesort
ArrayIterator
PHP Manual

ArrayIterator::ksort

(PHP 5 >= 5.2.0)

ArrayIterator::ksort — Sort array by keys

Opis

public void ArrayIterator::ksort ( void )

Sorts an array by the keys.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • ArrayIterator::natsort() - Sort an array naturally

ArrayIterator::key
ArrayIterator::natcasesort
ArrayIterator


Sort an array naturally, case insensitive

ArrayIterator::ksort
ArrayIterator::natsort
ArrayIterator
PHP Manual

ArrayIterator::natcasesort

(PHP 5 >= 5.2.0)

ArrayIterator::natcasesort — Sort an array naturally, case insensitive

Opis

public void ArrayIterator::natcasesort ( void )

Sort the entries by values using a case insensitive "natural order" algorithm.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natsort() - Sort an array naturally
  • natcasesort() - Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków

ArrayIterator::ksort
ArrayIterator::natsort
ArrayIterator


Sort an array naturally

ArrayIterator::natcasesort
ArrayIterator::next
ArrayIterator
PHP Manual

ArrayIterator::natsort

(PHP 5 >= 5.2.0)

ArrayIterator::natsort — Sort an array naturally

Opis

public void ArrayIterator::natsort ( void )

Sort the entries by values using "natural order" algorithm.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • natsort() - Sortuj tablicę używając algortmu "porządek naturalny"

ArrayIterator::natcasesort
ArrayIterator::next
ArrayIterator


Move to next entry

ArrayIterator::natsort
ArrayIterator::offsetExists
ArrayIterator
PHP Manual

ArrayIterator::next

(PHP 5 >= 5.0.0)

ArrayIterator::next — Move to next entry

Opis

public void ArrayIterator::next ( void )

The iterator to the next entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayIterator::next() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    echo $iterator->key() . ' => ' . $iterator->current() . "\n";

    $iterator->next();
}
?>

Powyższy przykład wyświetli:

0 => zero
1 => one

ArrayIterator::natsort
ArrayIterator::offsetExists
ArrayIterator


Check if offset exists

ArrayIterator::next
ArrayIterator::offsetGet
ArrayIterator
PHP Manual

ArrayIterator::offsetExists

(PHP 5 >= 5.0.0)

ArrayIterator::offsetExists — Check if offset exists

Opis

public void ArrayIterator::offsetExists ( string $index )

Checks if the offset exists.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

The offset being checked.

Zwracane wartości

TRUE if the offset exists, otherwise FALSE

Zobacz też:

  • ArrayIterator::valid() - Check whether array contains more entries

ArrayIterator::next
ArrayIterator::offsetGet
ArrayIterator


Get value for an offset

ArrayIterator::offsetExists
ArrayIterator::offsetSet
ArrayIterator
PHP Manual

ArrayIterator::offsetGet

(PHP 5 >= 5.0.0)

ArrayIterator::offsetGet — Get value for an offset

Opis

public mixed ArrayIterator::offsetGet ( string $index )

Gets the value from the provided offset.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

The offset to get the value from.

Zwracane wartości

The value at offset index.

Zobacz też:

  • ArrayIterator::offsetSet() - Set value for an offset
  • ArrayIterator::offsetUnset() - Unset value for an offset

ArrayIterator::offsetExists
ArrayIterator::offsetSet
ArrayIterator


Set value for an offset

ArrayIterator::offsetGet
ArrayIterator::offsetUnset
ArrayIterator
PHP Manual

ArrayIterator::offsetSet

(PHP 5 >= 5.0.0)

ArrayIterator::offsetSet — Set value for an offset

Opis

public void ArrayIterator::offsetSet ( string $index , string $newval )

Sets a value for a given offset.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

The index to set for.

newval

The new value to store at the index.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::offSetGet() - Get value for an offset
  • ArrayIterator::offSetUnset() - Unset value for an offset

ArrayIterator::offsetGet
ArrayIterator::offsetUnset
ArrayIterator


Unset value for an offset

ArrayIterator::offsetSet
ArrayIterator::rewind
ArrayIterator
PHP Manual

ArrayIterator::offsetUnset

(PHP 5 >= 5.0.0)

ArrayIterator::offsetUnset — Unset value for an offset

Opis

public void ArrayIterator::offsetUnset ( string $index )

Unsets a value for an offset.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

The offset to unset.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::offSetGet() - Get value for an offset
  • ArrayIterator::offSetSet() - Set value for an offset

ArrayIterator::offsetSet
ArrayIterator::rewind
ArrayIterator


Rewind array back to the start

ArrayIterator::offsetUnset
ArrayIterator::seek
ArrayIterator
PHP Manual

ArrayIterator::rewind

(PHP 5 >= 5.0.0)

ArrayIterator::rewind — Rewind array back to the start

Opis

public void ArrayIterator::rewind ( void )

This rewinds the iterator to the beginning.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayIterator::rewind() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';
$arrayobject[] = 'two';

$iterator = $arrayobject->getIterator();

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the begining
echo $iterator->key(); //0
?>

ArrayIterator::offsetUnset
ArrayIterator::seek
ArrayIterator


Seek to position

ArrayIterator::rewind
ArrayIterator::serialize
ArrayIterator
PHP Manual

ArrayIterator::seek

(PHP 5 >= 5.0.0)

ArrayIterator::seek — Seek to position

Opis

public void ArrayIterator::seek ( int $position )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

position

The position to seek to.

Zwracane wartości

Nie jest zwracana żadna wartość.

ArrayIterator::rewind
ArrayIterator::serialize
ArrayIterator


Serialize

ArrayIterator::seek
ArrayIterator::setFlags
ArrayIterator
PHP Manual

ArrayIterator::serialize

(PHP 5 >= 5.3.0)

ArrayIterator::serialize — Serialize

Opis

public string ArrayIterator::serialize ( void )

Serialize.

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 serialized ArrayIterator.

Zobacz też:

  • ArrayIterator::unserialize() - Unserialize

ArrayIterator::seek
ArrayIterator::setFlags
ArrayIterator


Set behaviour flags

ArrayIterator::serialize
ArrayIterator::uasort
ArrayIterator
PHP Manual

ArrayIterator::setFlags

(PHP 5 >= 5.1.0)

ArrayIterator::setFlags — Set behaviour flags

Opis

public void ArrayIterator::setFlags ( string $flags )

Sets behaviour flags.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flags

A bitmask as follows:

  • 0 = Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).
  • 1 = Array indices can be accessed as properties in read/write.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::getFlags() - Get flags

ArrayIterator::serialize
ArrayIterator::uasort
ArrayIterator


User defined sort

ArrayIterator::setFlags
ArrayIterator::uksort
ArrayIterator
PHP Manual

ArrayIterator::uasort

(PHP 5 >= 5.2.0)

ArrayIterator::uasort — User defined sort

Opis

public void ArrayIterator::uasort ( string $cmp_function )

Sort the entries by values using user defined function.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

cmp_function

The compare function used for the sort.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::uksort() - User defined sort
  • usort() - Sortuje tablicę według wartości korzystając ze zdefiniowanej przez użytkownika funkcji porównującej

ArrayIterator::setFlags
ArrayIterator::uksort
ArrayIterator


User defined sort

ArrayIterator::uasort
ArrayIterator::unserialize
ArrayIterator
PHP Manual

ArrayIterator::uksort

(PHP 5 >= 5.2.0)

ArrayIterator::uksort — User defined sort

Opis

public void ArrayIterator::uksort ( string $cmp_function )

Sort the entries by key using user defined function.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

cmp_function

The compare function used for the sort.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ArrayIterator::uasort() - User defined sort
  • uksort() - Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez użytkownika funkcji porównującej

ArrayIterator::uasort
ArrayIterator::unserialize
ArrayIterator


Unserialize

ArrayIterator::uksort
ArrayIterator::valid
ArrayIterator
PHP Manual

ArrayIterator::unserialize

(PHP 5 >= 5.3.0)

ArrayIterator::unserialize — Unserialize

Opis

public string ArrayIterator::unserialize ( string $serialized )

Unserialize.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

serialized

The serialized ArrayIterator object to be unserialized.

Zwracane wartości

The ArrayIterator.

Zobacz też:

  • ArrayIterator::serialize() - Serialize

ArrayIterator::uksort
ArrayIterator::valid
ArrayIterator


Check whether array contains more entries

ArrayIterator::unserialize
CachingIterator
ArrayIterator
PHP Manual

ArrayIterator::valid

(PHP 5 >= 5.0.0)

ArrayIterator::valid — Check whether array contains more entries

Opis

public bool ArrayIterator::valid ( void )

Checks if the array contains any more entries.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayIterator::valid() example

<?php
$array = array('1' => 'one');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

var_dump($iterator->valid()); //bool(true)

$iterator->next(); // advance to the next item

//bool(false) because there is only one array element
var_dump($iterator->valid());
?>

ArrayIterator::unserialize
CachingIterator
ArrayIterator


The CachingIterator class

(PHP 5)

Wstęp

This object supports cached iteration over another iterator.

Krótki opis klasy

CachingIterator extends IteratorIterator implements OuterIterator , Traversable , Iterator , ArrayAccess , Countable {
/* Stałe */
const integer CALL_TOSTRING = 1 ;
const integer CATCH_GET_CHILD = 16 ;
const integer TOSTRING_USE_KEY = 2 ;
const integer TOSTRING_USE_CURRENT = 4 ;
const integer TOSTRING_USE_INNER = 8 ;
const integer FULL_CACHE = 256 ;
/* Metody */
public __construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
public int count ( void )
public void current ( void )
public void getCache ( void )
public void getFlags ( void )
public void getInnerIterator ( void )
public void hasNext ( void )
public void key ( void )
public void next ( void )
public void offsetExists ( string $index )
public void offsetGet ( string $index )
public void offsetSet ( string $index , string $newval )
public void offsetUnset ( string $index )
public void rewind ( void )
public void setFlags ( bitmask $flags )
public void __toString ( void )
public void valid ( void )
}

Stałe predefiniowane

CachingIterator::CALL_TOSTRING

Convert every element to string.

CachingIterator::CATCH_GET_CHILD

Don't throw exception in accessing children.

CachingIterator::TOSTRING_USE_KEY

Use key for conversion to string.

CachingIterator::TOSTRING_USE_CURRENT

Use current for conversion to string.

CachingIterator::TOSTRING_USE_INNER

Use inner for conversion to string.

CachingIterator::FULL_CACHE

Cache all read data.

Spis treści

  • CachingIterator::__construct — Construct a new CachingIterator object for the iterator.
  • CachingIterator::count — The number of elements in the iterator
  • CachingIterator::current — Return the current element
  • CachingIterator::getCache — The getCache purpose
  • CachingIterator::getFlags — Get flags used
  • CachingIterator::getInnerIterator — Returns the inner iterator
  • CachingIterator::hasNext — Check whether the inner iterator has a valid next element
  • CachingIterator::key — Return the key for the current element
  • CachingIterator::next — Move the iterator forward
  • CachingIterator::offsetExists — The offsetExists purpose
  • CachingIterator::offsetGet — The offsetGet purpose
  • CachingIterator::offsetSet — The offsetSet purpose
  • CachingIterator::offsetUnset — The offsetUnset purpose
  • CachingIterator::rewind — Rewind the iterator
  • CachingIterator::setFlags — The setFlags purpose
  • CachingIterator::__toString — Return the string representation of the current element
  • CachingIterator::valid — Check whether the current element is valid
ArrayIterator::valid
CachingIterator::__construct
Iteratory


Construct a new CachingIterator object for the iterator.

CachingIterator
CachingIterator::count
CachingIterator
PHP Manual

CachingIterator::__construct

(PHP 5)

CachingIterator::__construct — Construct a new CachingIterator object for the iterator.

Opis

public CachingIterator::__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iterator

Iterator to cache

flags

Bitmask of flags.

CachingIterator
CachingIterator::count
CachingIterator


The number of elements in the iterator

CachingIterator::__construct
CachingIterator::current
CachingIterator
PHP Manual

CachingIterator::count

(PHP 5 >= 5.2.2)

CachingIterator::count — The number of elements in the iterator

Opis

public int CachingIterator::count ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

May return the number of elements in the iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The count of the elements iterated over.

CachingIterator::__construct
CachingIterator::current
CachingIterator


Return the current element

CachingIterator::count
CachingIterator::getCache
CachingIterator
PHP Manual

CachingIterator::current

(PHP 5)

CachingIterator::current — Return the current element

Opis

public void CachingIterator::current ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

May return the current element in the iteration.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Mixed

Zobacz też:

  • Iterator::current() - Return the current element

CachingIterator::count
CachingIterator::getCache
CachingIterator


The getCache purpose

CachingIterator::current
CachingIterator::getFlags
CachingIterator
PHP Manual

CachingIterator::getCache

(PHP 5 >= 5.2.0)

CachingIterator::getCache — The getCache purpose

Opis

public void CachingIterator::getCache ( 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

Description...

CachingIterator::current
CachingIterator::getFlags
CachingIterator


Get flags used

CachingIterator::getCache
CachingIterator::getInnerIterator
CachingIterator
PHP Manual

CachingIterator::getFlags

(PHP 5 >= 5.2.0)

CachingIterator::getFlags — Get flags used

Opis

public void CachingIterator::getFlags ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Get the bitmask of the flags used for this CachingIterator instance.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Description...

CachingIterator::getCache
CachingIterator::getInnerIterator
CachingIterator


Returns the inner iterator

CachingIterator::getFlags
CachingIterator::hasNext
CachingIterator
PHP Manual

CachingIterator::getInnerIterator

(PHP 5)

CachingIterator::getInnerIterator — Returns the inner iterator

Opis

public void CachingIterator::getInnerIterator ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the iterator sent to the constructor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an object implementing the Iterator interface.

CachingIterator::getFlags
CachingIterator::hasNext
CachingIterator


Check whether the inner iterator has a valid next element

CachingIterator::getInnerIterator
CachingIterator::key
CachingIterator
PHP Manual

CachingIterator::hasNext

(PHP 5)

CachingIterator::hasNext — Check whether the inner iterator has a valid next element

Opis

public void CachingIterator::hasNext ( 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

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

CachingIterator::getInnerIterator
CachingIterator::key
CachingIterator


Return the key for the current element

CachingIterator::hasNext
CachingIterator::next
CachingIterator
PHP Manual

CachingIterator::key

(PHP 5)

CachingIterator::key — Return the key for the current element

Opis

public void CachingIterator::key ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

This method may return a key for the current element.

Parametry

Ta funkcja nie posiada parametrów.

CachingIterator::hasNext
CachingIterator::next
CachingIterator


Move the iterator forward

CachingIterator::key
CachingIterator::offsetExists
CachingIterator
PHP Manual

CachingIterator::next

(PHP 5)

CachingIterator::next — Move the iterator forward

Opis

public void CachingIterator::next ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Move the iterator forward.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

CachingIterator::key
CachingIterator::offsetExists
CachingIterator


The offsetExists purpose

CachingIterator::next
CachingIterator::offsetGet
CachingIterator
PHP Manual

CachingIterator::offsetExists

(PHP 5 >= 5.2.0)

CachingIterator::offsetExists — The offsetExists purpose

Opis

public void CachingIterator::offsetExists ( string $index )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

The index being checked.

Zwracane wartości

Returns TRUE if an entry referenced by the offset exists, FALSE otherwise.

CachingIterator::next
CachingIterator::offsetGet
CachingIterator


The offsetGet purpose

CachingIterator::offsetExists
CachingIterator::offsetSet
CachingIterator
PHP Manual

CachingIterator::offsetGet

(PHP 5 >= 5.2.0)

CachingIterator::offsetGet — The offsetGet purpose

Opis

public void CachingIterator::offsetGet ( string $index )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

Description...

Zwracane wartości

Description...

CachingIterator::offsetExists
CachingIterator::offsetSet
CachingIterator


The offsetSet purpose

CachingIterator::offsetGet
CachingIterator::offsetUnset
CachingIterator
PHP Manual

CachingIterator::offsetSet

(PHP 5 >= 5.2.0)

CachingIterator::offsetSet — The offsetSet purpose

Opis

public void CachingIterator::offsetSet ( string $index , string $newval )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

The index of the element to be set.

newval

The new value for the index.

Zwracane wartości

Nie jest zwracana żadna wartość.

CachingIterator::offsetGet
CachingIterator::offsetUnset
CachingIterator


The offsetUnset purpose

CachingIterator::offsetSet
CachingIterator::rewind
CachingIterator
PHP Manual

CachingIterator::offsetUnset

(PHP 5 >= 5.2.0)

CachingIterator::offsetUnset — The offsetUnset purpose

Opis

public void CachingIterator::offsetUnset ( string $index )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

index

The index of the element to be unset.

Zwracane wartości

Nie jest zwracana żadna wartość.

CachingIterator::offsetSet
CachingIterator::rewind
CachingIterator


Rewind the iterator

CachingIterator::offsetUnset
CachingIterator::setFlags
CachingIterator
PHP Manual

CachingIterator::rewind

(PHP 5)

CachingIterator::rewind — Rewind the iterator

Opis

public void CachingIterator::rewind ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Rewind the iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

CachingIterator::offsetUnset
CachingIterator::setFlags
CachingIterator


The setFlags purpose

CachingIterator::rewind
CachingIterator::__toString
CachingIterator
PHP Manual

CachingIterator::setFlags

(PHP 5 >= 5.2.0)

CachingIterator::setFlags — The setFlags purpose

Opis

public void CachingIterator::setFlags ( bitmask $flags )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Set the flags for the CachingIterator object.

Parametry

flags

Bitmask of the flags to set.

Zwracane wartości

Nie jest zwracana żadna wartość.

CachingIterator::rewind
CachingIterator::__toString
CachingIterator


Return the string representation of the current element

CachingIterator::setFlags
CachingIterator::valid
CachingIterator
PHP Manual

CachingIterator::__toString

(PHP 5)

CachingIterator::__toString — Return the string representation of the current element

Opis

public void CachingIterator::__toString ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Get the string representation of the current element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The string representation of the current element.

CachingIterator::setFlags
CachingIterator::valid
CachingIterator


Check whether the current element is valid

CachingIterator::__toString
CallbackFilterIterator
CachingIterator
PHP Manual

CachingIterator::valid

(PHP 5)

CachingIterator::valid — Check whether the current element is valid

Opis

public void CachingIterator::valid ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Check whether the current element is valid.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

CachingIterator::__toString
CallbackFilterIterator
CachingIterator


The CallbackFilterIterator class

(PHP 5 >= 5.4.0)

Wstęp

Krótki opis klasy

CallbackFilterIterator extends FilterIterator implements Iterator , Traversable , OuterIterator {
/* Metody */
public __construct ( Iterator $iterator , callback $callback )
public string accept ( void )
/* Metody dziedziczone */
abstract bool FilterIterator::accept ( void )
FilterIterator::__construct ( Iterator $iterator )
mixed FilterIterator::current ( void )
Iterator FilterIterator::getInnerIterator ( void )
mixed FilterIterator::key ( void )
void FilterIterator::next ( void )
void FilterIterator::rewind ( void )
bool FilterIterator::valid ( void )
}

Przykłady

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Przykład #1 Available callback arguments

<?php

/**
 * Callback for CallbackFilterIterator
 *
 * @param $current   Current item's value
 * @param $key       Current item's key
 * @param $iterator  Iterator being filtered
 * @return boolean   TRUE to accept the current item, FALSE otherwise
 */
function my_callback($current, $key, $iterator) {
    // Your filtering code here
}

?>

Any callback may be used; such as a string containing a function name, an array for a method, or an anonymous function.

Przykład #2 Callback basic examples

<?php

$dir = new FilesystemIterator(__DIR__);

// Filter large files ( > 100MB)
function is_large_file($current) {
    return $current->isFile() && $current->getSize() > 104857600;
}
$large_files = new CallbackFilterIterator($dir, 'is_large_file');

// Filter directories
$files = new CallbackFilterIterator($dir, function ($current, $key, $iterator) {
    return $current->isDir() && ! $iterator->isDot();
});

?>

Spis treści

  • CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments
  • CallbackFilterIterator::__construct — Create a filtered iterator from another iterator
CachingIterator::valid
CallbackFilterIterator::accept
Iteratory


Calls the callback with the current value, the current key and the inner iterator as arguments

CallbackFilterIterator
CallbackFilterIterator::__construct
CallbackFilterIterator
PHP Manual

CallbackFilterIterator::accept

(PHP 5 >= 5.4.0)

CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments

Opis

public string CallbackFilterIterator::accept ( void )

This method calls the callback with the current value, current key and the inner iterator.

The callback is expected to return TRUE if the current item is to be accepted, or FALSE otherwise.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE to accept the current item, or FALSE otherwise.

Zobacz też:

  • CallbackFilterIterator Examples
  • CallbackFilterIterator::__construct() - Create a filtered iterator from another iterator

CallbackFilterIterator
CallbackFilterIterator::__construct
CallbackFilterIterator


Create a filtered iterator from another iterator

CallbackFilterIterator::accept
DirectoryIterator
CallbackFilterIterator
PHP Manual

CallbackFilterIterator::__construct

(PHP 5 >= 5.4.0)

CallbackFilterIterator::__construct — Create a filtered iterator from another iterator

Opis

public CallbackFilterIterator::__construct() ( Iterator $iterator , callback $callback )

Creates a filtered iterator using the callback to determine which items are accepted or rejected.

Parametry

iterator

The iterator to be filtered.

callback

The callback, which should return TRUE to accept the current item or FALSE otherwise. See Examples.

May be any valid callback value.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • CallbackFilterIterator Examples
  • CallbackFilterIterator::accept() - Calls the callback with the current value, the current key and the inner iterator as arguments

CallbackFilterIterator::accept
DirectoryIterator
CallbackFilterIterator


The DirectoryIterator class

(PHP 5)

Wstęp

The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

Krótki opis klasy

DirectoryIterator extends SplFileInfo implements Iterator , Traversable , SeekableIterator {
/* Metody */
public __construct ( string $path )
public DirectoryIterator current ( void )
public int getATime ( void )
public string getBasename ([ string $suffix ] )
public int getCTime ( void )
public string getExtension ( void )
public string getFilename ( void )
public int getGroup ( void )
public int getInode ( void )
public int getMTime ( void )
public int getOwner ( void )
public string getPath ( void )
public string getPathname ( void )
public int getPerms ( void )
public int getSize ( void )
public string getType ( void )
public bool isDir ( void )
public bool isDot ( void )
public bool isExecutable ( void )
public bool isFile ( void )
public bool isLink ( void )
public bool isReadable ( void )
public bool isWritable ( void )
public string key ( void )
public void next ( void )
public void rewind ( void )
public void seek ( int $position )
public string __toString ( void )
public bool valid ( void )
}

Spis treści

  • DirectoryIterator::__construct — Constructs a new directory iterator from a path
  • DirectoryIterator::current — Return the current DirectoryIterator item.
  • DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getBasename — Get base name of current DirectoryIterator item.
  • DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item
  • DirectoryIterator::getExtension — Returns the file extension component of path
  • DirectoryIterator::getFilename — Return file name of current DirectoryIterator item.
  • DirectoryIterator::getGroup — Get group for the current DirectoryIterator item
  • DirectoryIterator::getInode — Get inode for the current DirectoryIterator item
  • DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item
  • DirectoryIterator::getOwner — Get owner of current DirectoryIterator item
  • DirectoryIterator::getPath — Get path of current Iterator item without filename
  • DirectoryIterator::getPathname — Return path and file name of current DirectoryIterator item
  • DirectoryIterator::getPerms — Get the permissions of current DirectoryIterator item
  • DirectoryIterator::getSize — Get size of current DirectoryIterator item
  • DirectoryIterator::getType — Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir — Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link
  • DirectoryIterator::isReadable — Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable — Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::key — Return the key for the current DirectoryIterator item
  • DirectoryIterator::next — Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start
  • DirectoryIterator::seek — Seek to a DirectoryIterator item
  • DirectoryIterator::__toString — Get file name as a string
  • DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file
CallbackFilterIterator::__construct
DirectoryIterator::__construct
Iteratory


Constructs a new directory iterator from a path

DirectoryIterator
DirectoryIterator::current
DirectoryIterator
PHP Manual

DirectoryIterator::__construct

(PHP 5)

DirectoryIterator::__construct — Constructs a new directory iterator from a path

Opis

public DirectoryIterator::__construct() ( string $path )

Constructs a new directory iterator from a path.

Parametry

path

The path of the directory to traverse.

Błędy/Wyjątki

Throws an UnexpectedValueException if the path cannot be opened.

Przykłady

Przykład #1 A DirectoryIterator::__construct() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
    }
}
?>

Zobacz też:

  • SplFileInfo
  • Iterator

DirectoryIterator
DirectoryIterator::current
DirectoryIterator


Return the current DirectoryIterator item.

DirectoryIterator::__construct
DirectoryIterator::getATime
DirectoryIterator
PHP Manual

DirectoryIterator::current

(PHP 5)

DirectoryIterator::current — Return the current DirectoryIterator item.

Opis

public DirectoryIterator DirectoryIterator::current ( void )

Get the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current DirectoryIterator item.

Przykłady

Przykład #1 A DirectoryIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
while($iterator->valid()) {
    $file = $iterator->current();
    echo $iterator->key() . " => " . $file->getFilename() . "\n";
    $iterator->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

0 => .
1 => ..
2 => apple.jpg
3 => banana.jpg
4 => index.php
5 => pear.jpg

Zobacz też:

  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::current() - Return the current element

DirectoryIterator::__construct
DirectoryIterator::getATime
DirectoryIterator


Get last access time of the current DirectoryIterator item

DirectoryIterator::current
DirectoryIterator::getBasename
DirectoryIterator
PHP Manual

DirectoryIterator::getATime

(PHP 5)

DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item

Opis

public int DirectoryIterator::getATime ( void )

Get the last access time of the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the time the file was last accessed, as a Unix timestamp.

Przykłady

Przykład #1 A DirectoryIterator::getATime() example

Displays a list of the files in the directory of the script and their last access times.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getATime() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979

Zobacz też:

  • DirectoryIterator::getCTime() - Get inode change time of the current DirectoryIterator item
  • DirectoryIterator::getMTime() - Get last modification time of current DirectoryIterator item
  • fileatime() - Pobiera ostatni czas dostępu do pliku

DirectoryIterator::current
DirectoryIterator::getBasename
DirectoryIterator


Get base name of current DirectoryIterator item.

DirectoryIterator::getATime
DirectoryIterator::getCTime
DirectoryIterator
PHP Manual

DirectoryIterator::getBasename

(PHP 5 >= 5.2.2)

DirectoryIterator::getBasename — Get base name of current DirectoryIterator item.

Opis

public string DirectoryIterator::getBasename ([ string $suffix ] )

Get the base name of the current DirectoryIterator item.

Parametry

suffix

If the base name ends in suffix, this will be cut.

Zwracane wartości

The base name of the current DirectoryIterator item.

Przykłady

Przykład #1 A DirectoryIterator::getBasename() example

This example will list the full base name and the base name with suffix .jpg removed for the files in the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getBasename() . "\n";
        echo $fileinfo->getBasename('.jpg') . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg
apple
banana.jpg
banana
index.php
index.php
pear.jpg
pear

Zobacz też:

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • basename() - Zwraca nazwę pliku, będącego składową ścieżki
  • pathinfo() - Zwraca informacje o ścieżce do pliku

DirectoryIterator::getATime
DirectoryIterator::getCTime
DirectoryIterator


Get inode change time of the current DirectoryIterator item

DirectoryIterator::getBasename
DirectoryIterator::getExtension
DirectoryIterator
PHP Manual

DirectoryIterator::getCTime

(PHP 5)

DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item

Opis

public int DirectoryIterator::getCTime ( void )

Get the inode change time for the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the last change time of the file, as a Unix timestamp.

Przykłady

Przykład #1 DirectoryIterator::getCTime() example

This example displays the file name and last change time of the files in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " changed at " . $fileinfo->getCTime() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg changed at 1240398312
banana.jpg changed at 1238605440
index.php changed at 1240398935
pear.jpg changed at 1237423740

Zobacz też:

  • DirectoryIterator::getATime() - Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getMTime() - Get last modification time of current DirectoryIterator item
  • filectime() - Pobiera i-węzłowy czas zmiany pliku

DirectoryIterator::getBasename
DirectoryIterator::getExtension
DirectoryIterator


Returns the file extension component of path

DirectoryIterator::getCTime
DirectoryIterator::getFilename
DirectoryIterator
PHP Manual

DirectoryIterator::getExtension

(No version information available, might only be in SVN)

DirectoryIterator::getExtension — Returns the file extension component of path

Opis

public string DirectoryIterator::getExtension ( 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

DirectoryIterator::getCTime
DirectoryIterator::getFilename
DirectoryIterator


Return file name of current DirectoryIterator item.

DirectoryIterator::getExtension
DirectoryIterator::getGroup
DirectoryIterator
PHP Manual

DirectoryIterator::getFilename

(PHP 5)

DirectoryIterator::getFilename — Return file name of current DirectoryIterator item.

Opis

public string DirectoryIterator::getFilename ( void )

Get the file name of the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the file name of the current DirectoryIterator item.

Przykłady

Przykład #1 A DirectoryIterator::getFilename() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    echo $fileinfo->getFilename() . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

Zobacz też:

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item.
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • pathinfo() - Zwraca informacje o ścieżce do pliku

DirectoryIterator::getExtension
DirectoryIterator::getGroup
DirectoryIterator


Get group for the current DirectoryIterator item

DirectoryIterator::getFilename
DirectoryIterator::getInode
DirectoryIterator
PHP Manual

DirectoryIterator::getGroup

(PHP 5)

DirectoryIterator::getGroup — Get group for the current DirectoryIterator item

Opis

public int DirectoryIterator::getGroup ( void )

Get the group id of the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the group id of the current DirectoryIterator item in numerical format.

Przykłady

Przykład #1 DirectoryIterator::getGroup() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
$groupid  = $iterator->getGroup();
echo 'Directory belongs to group id ' . $groupid . "\n";
print_r(posix_getgrgid($groupid));
?>

Powyższy przykład wyświetli coś podobnego do:

Directory belongs to group id 42
Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

Zobacz też:

  • DirectoryIterator::getiNode() - Get inode for the current DirectoryIterator item
  • DirectoryIterator::getOwner() - Get owner of current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • filegroup() - Pobiera grupę pliku
  • posix_getgrgid() - Return info about a group by group id

DirectoryIterator::getFilename
DirectoryIterator::getInode
DirectoryIterator


Get inode for the current DirectoryIterator item

DirectoryIterator::getGroup
DirectoryIterator::getMTime
DirectoryIterator
PHP Manual

DirectoryIterator::getInode

(PHP 5)

DirectoryIterator::getInode — Get inode for the current DirectoryIterator item

Opis

public int DirectoryIterator::getInode ( void )

Get the inode number for the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the inode number for the file.

Przykłady

Przykład #1 DirectoryIterator::getInode() example

This example displays the inode number for the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
echo $iterator->getInode();
?>

Zobacz też:

  • DirectoryIterator::getGroup() - Get group for the current DirectoryIterator item
  • DirectoryIterator::getOwner() - Get owner of current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • fileinode() - Pobiera i-węzeł pliku

DirectoryIterator::getGroup
DirectoryIterator::getMTime
DirectoryIterator


Get last modification time of current DirectoryIterator item

DirectoryIterator::getInode
DirectoryIterator::getOwner
DirectoryIterator
PHP Manual

DirectoryIterator::getMTime

(PHP 5)

DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item

Opis

public int DirectoryIterator::getMTime ( void )

Get the last modification time of the current DirectoryIterator item, as a Unix timestamp.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The last modification time of the file, as a Unix timestamp.

Przykłady

Przykład #1 A DirectoryIterator::getMTime() example

Displays a list of the files in the directory of the script and their last modified times.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getMTime() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979

Zobacz też:

  • DirectoryIterator::getATime() - Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getCTime() - Get inode change time of the current DirectoryIterator item
  • filemtime() - Pobiera czas ostatniej modyfikacji pliku

DirectoryIterator::getInode
DirectoryIterator::getOwner
DirectoryIterator


Get owner of current DirectoryIterator item

DirectoryIterator::getMTime
DirectoryIterator::getPath
DirectoryIterator
PHP Manual

DirectoryIterator::getOwner

(PHP 5)

DirectoryIterator::getOwner — Get owner of current DirectoryIterator item

Opis

public int DirectoryIterator::getOwner ( void )

Get the owner of the current DirectoryIterator item, in numerical format.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The file owner of the file, in numerical format.

Przykłady

Przykład #1 DirectoryIterator::getOwner() example

This example displays the owner of the directory which contains the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
print_r(posix_getpwuid($iterator->getOwner()));
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [name] => tom
    [passwd] => x
    [uid] => 501
    [gid] => 42
    [gecos] => Tom Cat
    [dir] => /home/tom
    [shell] => /bin/bash
)

Zobacz też:

  • DirectoryIterator::getGroup() - Get group for the current DirectoryIterator item
  • DirectoryIterator::getiNode() - Get inode for the current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • posix_getpwuid() - Return info about a user by user id

DirectoryIterator::getMTime
DirectoryIterator::getPath
DirectoryIterator


Get path of current Iterator item without filename

DirectoryIterator::getOwner
DirectoryIterator::getPathname
DirectoryIterator
PHP Manual

DirectoryIterator::getPath

(PHP 5)

DirectoryIterator::getPath — Get path of current Iterator item without filename

Opis

public string DirectoryIterator::getPath ( void )

Get the path to the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the path to the file, omitting the file name and any trailing slash.

Przykłady

Przykład #1 DirectoryIterator::getPath() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
echo $iterator->getPath();
?>

Powyższy przykład wyświetli coś podobnego do:

/home/examples/public_html

Zobacz też:

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item.
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • pathinfo() - Zwraca informacje o ścieżce do pliku

DirectoryIterator::getOwner
DirectoryIterator::getPathname
DirectoryIterator


Return path and file name of current DirectoryIterator item

DirectoryIterator::getPath
DirectoryIterator::getPerms
DirectoryIterator
PHP Manual

DirectoryIterator::getPathname

(PHP 5)

DirectoryIterator::getPathname — Return path and file name of current DirectoryIterator item

Opis

public string DirectoryIterator::getPathname ( void )

Get the path and file name of the current file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns he path and file name of current file. Directories do not have a trailing slash.

Przykłady

Przykład #1 DirectoryIterator::getPathname() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getPathname() . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

/home/examples/.
/home/examples/..
/home/examples/apple.jpg
/home/examples/banana.jpg
/home/examples/getpathname.php
/home/examples/pear.jpg

Zobacz też:

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item.
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • pathinfo() - Zwraca informacje o ścieżce do pliku

DirectoryIterator::getPath
DirectoryIterator::getPerms
DirectoryIterator


Get the permissions of current DirectoryIterator item

DirectoryIterator::getPathname
DirectoryIterator::getSize
DirectoryIterator
PHP Manual

DirectoryIterator::getPerms

(PHP 5)

DirectoryIterator::getPerms — Get the permissions of current DirectoryIterator item

Opis

public int DirectoryIterator::getPerms ( void )

Get the permissions of the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the permissions of the file, as a decimal integer.

Przykłady

Przykład #1 DirectoryIterator::getPerms() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        $octal_perms = substr(sprintf('%o', $fileinfo->getPerms()), -4);
        echo $fileinfo->getFilename() . " " . $octal_perms . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg 0644
banana.jpg 0644
index.php 0744
pear.jpg 0644

Zobacz też:

  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to

DirectoryIterator::getPathname
DirectoryIterator::getSize
DirectoryIterator


Get size of current DirectoryIterator item

DirectoryIterator::getPerms
DirectoryIterator::getType
DirectoryIterator
PHP Manual

DirectoryIterator::getSize

(PHP 5)

DirectoryIterator::getSize — Get size of current DirectoryIterator item

Opis

public int DirectoryIterator::getSize ( void )

Get the file size for the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the size of the file, in bytes.

Przykłady

Przykład #1 DirectoryIterator::getSize() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getSize() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg 15385
banana.jpg 15190
example.php 170
pear.jpg 34406

Zobacz też:

  • filesize() - Pobiera rozmiar pliku

DirectoryIterator::getPerms
DirectoryIterator::getType
DirectoryIterator


Determine the type of the current DirectoryIterator item

DirectoryIterator::getSize
DirectoryIterator::isDir
DirectoryIterator
PHP Manual

DirectoryIterator::getType

(PHP 5)

DirectoryIterator::getType — Determine the type of the current DirectoryIterator item

Opis

public string DirectoryIterator::getType ( void )

Determines which file type the current DirectoryIterator item belongs to. One of file, link, or dir.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string representing the type of the file. May be one of file, link, or dir.

Przykłady

Przykład #1 DirectoryIterator::getType() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getFilename() . " " . $fileinfo->getType() . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

. dir
.. dir
apple.jpg file
banana.jpg file
example.php file
pear.jpg file

Zobacz też:

  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link

DirectoryIterator::getSize
DirectoryIterator::isDir
DirectoryIterator


Determine if current DirectoryIterator item is a directory

DirectoryIterator::getType
DirectoryIterator::isDot
DirectoryIterator
PHP Manual

DirectoryIterator::isDir

(PHP 5)

DirectoryIterator::isDir — Determine if current DirectoryIterator item is a directory

Opis

public bool DirectoryIterator::isDir ( void )

Determines if the current DirectoryIterator item is a directory.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if it is a directory, otherwise FALSE

Przykłady

Przykład #1 DirectoryIterator::isDir() example

This example lists the directories within the directory of the current script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isDir()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

.
..
apples
bananas
pears

Zobacz też:

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link

DirectoryIterator::getType
DirectoryIterator::isDot
DirectoryIterator


Determine if current DirectoryIterator item is '.' or '..'

DirectoryIterator::isDir
DirectoryIterator::isExecutable
DirectoryIterator
PHP Manual

DirectoryIterator::isDot

(PHP 5)

DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'

Opis

public bool DirectoryIterator::isDot ( void )

Determines if the current DirectoryIterator item is a directory and either . or ...

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the entry is . or .., otherwise FALSE

Przykłady

Przykład #1 A DirectoryIterator::isDot() example

This example will list all files, omitting the . and .. entries.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg
banana.jpg
example.php
pears.jpg

Zobacz też:

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link

DirectoryIterator::isDir
DirectoryIterator::isExecutable
DirectoryIterator


Determine if current DirectoryIterator item is executable

DirectoryIterator::isDot
DirectoryIterator::isFile
DirectoryIterator
PHP Manual

DirectoryIterator::isExecutable

(PHP 5)

DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable

Opis

public bool DirectoryIterator::isExecutable ( void )

Determines if the current DirectoryIterator item is executable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the entry is executable, otherwise FALSE

Przykłady

Przykład #1 DirectoryIterator::isExecutable() example

This example lists files in the directory containing the script which are executable.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isExecutable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

example.php
myscript.sh

Zobacz też:

  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item

DirectoryIterator::isDot
DirectoryIterator::isFile
DirectoryIterator


Determine if current DirectoryIterator item is a regular file

DirectoryIterator::isExecutable
DirectoryIterator::isLink
DirectoryIterator
PHP Manual

DirectoryIterator::isFile

(PHP 5)

DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file

Opis

public bool DirectoryIterator::isFile ( void )

Determines if the current DirectoryIterator item is a regular file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the file exists and is a regular file (not a link or dir), otherwise FALSE

Przykłady

Przykład #1 DirectoryIterator::isFile() example

This example will list all regular files in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg
banana.jpg
example.php
pears.jpg

Zobacz też:

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link

DirectoryIterator::isExecutable
DirectoryIterator::isLink
DirectoryIterator


Determine if current DirectoryIterator item is a symbolic link

DirectoryIterator::isFile
DirectoryIterator::isReadable
DirectoryIterator
PHP Manual

DirectoryIterator::isLink

(PHP 5)

DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link

Opis

public bool DirectoryIterator::isLink ( void )

Determines if the current DirectoryIterator item is a symbolic link.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the item is a symbolic link, otherwise FALSE

Przykłady

Przykład #1 A DirectoryIterator::isLink() example

This example contains a recursive function for removing a directory tree.

<?php
/**
 * This function will recursively delete all files in the given path, without
 * following symlinks.
 *
 * @param string $path Path to the directory to remove.
 */
function removeDir($path) {
    $dir = new DirectoryIterator($path);
    foreach ($dir as $fileinfo) {
        if ($fileinfo->isFile() || $fileinfo->isLink()) {
            unlink($fileinfo->getPathName());
        } elseif (!$fileinfo->isDot() && $fileinfo->isDir()) {
            removeDir($fileinfo->getPathName());
        }
    }
    rmdir($path);
}

removeDir('foo');
?>

Zobacz też:

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file

DirectoryIterator::isFile
DirectoryIterator::isReadable
DirectoryIterator


Determine if current DirectoryIterator item can be read

DirectoryIterator::isLink
DirectoryIterator::isWritable
DirectoryIterator
PHP Manual

DirectoryIterator::isReadable

(PHP 5)

DirectoryIterator::isReadable — Determine if current DirectoryIterator item can be read

Opis

public bool DirectoryIterator::isReadable ( void )

Determines if the current DirectoryIterator item is readable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the file is readable, otherwise FALSE

Przykłady

Przykład #1 DirectoryIterator::isReadable() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isReadable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg
banana.jpg
example.php
pears.jpg

Zobacz też:

  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item

DirectoryIterator::isLink
DirectoryIterator::isWritable
DirectoryIterator


Determine if current DirectoryIterator item can be written to

DirectoryIterator::isReadable
DirectoryIterator::key
DirectoryIterator
PHP Manual

DirectoryIterator::isWritable

(PHP 5)

DirectoryIterator::isWritable — Determine if current DirectoryIterator item can be written to

Opis

public bool DirectoryIterator::isWritable ( void )

Determines if the current DirectoryIterator item is writable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the file/directory is writable, otherwise FALSE

Przykłady

Przykład #1 DirectoryIterator::isWritable() example

This example lists the files and directories which can be opened for writing in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isWritable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

apples.txt
bananas.html
pears

Zobacz też:

  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read

DirectoryIterator::isReadable
DirectoryIterator::key
DirectoryIterator


Return the key for the current DirectoryIterator item

DirectoryIterator::isWritable
DirectoryIterator::next
DirectoryIterator
PHP Manual

DirectoryIterator::key

(PHP 5)

DirectoryIterator::key — Return the key for the current DirectoryIterator item

Opis

public string DirectoryIterator::key ( void )

Get the key for the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The key for the current DirectoryIterator item.

Przykłady

Przykład #1 A DirectoryIterator::key() example

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->key() . " => " . $fileinfo->getFilename() . "\n";
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

0 => apple.jpg
1 => banana.jpg
2 => index.php
3 => pear.jpg

Zobacz też:

  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::key() - Return the key of the current element

DirectoryIterator::isWritable
DirectoryIterator::next
DirectoryIterator


Move forward to next DirectoryIterator item

DirectoryIterator::key
DirectoryIterator::rewind
DirectoryIterator
PHP Manual

DirectoryIterator::next

(PHP 5)

DirectoryIterator::next — Move forward to next DirectoryIterator item

Opis

public void DirectoryIterator::next ( void )

Move forward to the next DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 DirectoryIterator::next() example

List the contents of a directory using a while loop.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
while($iterator->valid()) {
    echo $iterator->getFilename() . "\n";
    $iterator->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

Zobacz też:

  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::next() - Move forward to next element

DirectoryIterator::key
DirectoryIterator::rewind
DirectoryIterator


Rewind the DirectoryIterator back to the start

DirectoryIterator::next
DirectoryIterator::seek
DirectoryIterator
PHP Manual

DirectoryIterator::rewind

(PHP 5)

DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start

Opis

public void DirectoryIterator::rewind ( void )

Rewind the DirectoryIterator back to the start.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 DirectoryIterator::rewind() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the beginning
echo $iterator->key(); //0
?>

Zobacz też:

  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::rewind() - Rewind the Iterator to the first element

DirectoryIterator::next
DirectoryIterator::seek
DirectoryIterator


Seek to a DirectoryIterator item

DirectoryIterator::rewind
DirectoryIterator::__toString
DirectoryIterator
PHP Manual

DirectoryIterator::seek

(PHP 5 >= 5.3.0)

DirectoryIterator::seek — Seek to a DirectoryIterator item

Opis

public void DirectoryIterator::seek ( int $position )

Seek to a given position in the DirectoryIterator.

Parametry

position

The zero-based numeric position to seek to.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 DirectoryIterator::seek() example

Seek to the fourth item in the directory containing the script. The first two are usually . and ..

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
$iterator->seek(3);
if ($iterator->valid()) {
    echo $iterator->getFilename();
} else {
    echo 'No file at position 3';
}
?>

Zobacz też:

  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • SeekableIterator::seek() - Seeks to a position

DirectoryIterator::rewind
DirectoryIterator::__toString
DirectoryIterator


Get file name as a string

DirectoryIterator::seek
DirectoryIterator::valid
DirectoryIterator
PHP Manual

DirectoryIterator::__toString

(PHP 5)

DirectoryIterator::__toString — Get file name as a string

Opis

public string DirectoryIterator::__toString ( void )

Get the file name of the current DirectoryIterator item.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the file name of the current DirectoryIterator item.

Przykłady

Przykład #1 A DirectoryIterator::__toString() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    echo $fileinfo;
}
?>

Powyższy przykład wyświetli coś podobnego do:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

Zobacz też:

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • The __toString() magic method

DirectoryIterator::seek
DirectoryIterator::valid
DirectoryIterator


Check whether current DirectoryIterator position is a valid file

DirectoryIterator::__toString
EmptyIterator
DirectoryIterator
PHP Manual

DirectoryIterator::valid

(PHP 5)

DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file

Opis

public bool DirectoryIterator::valid ( void )

Check whether current DirectoryIterator position is a valid file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the position is valid, otherwise FALSE

Przykłady

Przykład #1 A DirectoryIterator::valid() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));

// Loop to end of iterator
while($iterator->valid()) {
    $iterator->next();
}

$iterator->valid(); // FALSE
$iterator->rewind();
$iterator->valid(); // TRUE

?>

Zobacz też:

  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • Iterator::valid() - Checks if current position is valid

DirectoryIterator::__toString
EmptyIterator
DirectoryIterator


The EmptyIterator class

(PHP 5 >= 5.1.0)

Wstęp

The EmptyIterator class for an empty iterator.

Krótki opis klasy

EmptyIterator implements Iterator , Traversable {
/* Metody */
public void current ( void )
public void key ( void )
public void next ( void )
public void rewind ( void )
public void valid ( void )
}

Spis treści

  • EmptyIterator::current — The current() method
  • EmptyIterator::key — The key() method
  • EmptyIterator::next — The next() method
  • EmptyIterator::rewind — The rewind() method
  • EmptyIterator::valid — The valid() method
DirectoryIterator::valid
EmptyIterator::current
Iteratory


The current() method

EmptyIterator
EmptyIterator::key
EmptyIterator
PHP Manual

EmptyIterator::current

(PHP 5 >= 5.1.0)

EmptyIterator::current — The current() method

Opis

public void EmptyIterator::current ( void )

This function must not be called. It throws an exception upon access.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Ta funkcja nie posiada parametrów.

Błędy/Wyjątki

Throws an Exception if called.

Zwracane wartości

Nie jest zwracana żadna wartość.

EmptyIterator
EmptyIterator::key
EmptyIterator


The key() method

EmptyIterator::current
EmptyIterator::next
EmptyIterator
PHP Manual

EmptyIterator::key

(PHP 5 >= 5.1.0)

EmptyIterator::key — The key() method

Opis

public void EmptyIterator::key ( void )

This function must not be called. It throws an exception upon access.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Ta funkcja nie posiada parametrów.

Błędy/Wyjątki

Throws an Exception if called.

Zwracane wartości

Nie jest zwracana żadna wartość.

EmptyIterator::current
EmptyIterator::next
EmptyIterator


The next() method

EmptyIterator::key
EmptyIterator::rewind
EmptyIterator
PHP Manual

EmptyIterator::next

(PHP 5 >= 5.1.0)

EmptyIterator::next — The next() method

Opis

public void EmptyIterator::next ( void )

No operation, nothing to do.

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

Nie jest zwracana żadna wartość.

EmptyIterator::key
EmptyIterator::rewind
EmptyIterator


The rewind() method

EmptyIterator::next
EmptyIterator::valid
EmptyIterator
PHP Manual

EmptyIterator::rewind

(PHP 5 >= 5.1.0)

EmptyIterator::rewind — The rewind() method

Opis

public void EmptyIterator::rewind ( void )

No operation, nothing to do.

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

Nie jest zwracana żadna wartość.

EmptyIterator::next
EmptyIterator::valid
EmptyIterator


The valid() method

EmptyIterator::rewind
FilesystemIterator
EmptyIterator
PHP Manual

EmptyIterator::valid

(PHP 5 >= 5.1.0)

EmptyIterator::valid — The valid() method

Opis

public void EmptyIterator::valid ( void )

The EmptyIterator valid() method.

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

FALSE

EmptyIterator::rewind
FilesystemIterator
EmptyIterator


The FilesystemIterator class

(PHP 5 >= 5.3.0)

Wstęp

The Filesystem iterator

Krótki opis klasy

FilesystemIterator extends DirectoryIterator implements SeekableIterator , Traversable , Iterator {
/* Stałe */
const integer CURRENT_AS_PATHNAME = 32 ;
const integer CURRENT_AS_FILEINFO = 0 ;
const integer CURRENT_AS_SELF = 16 ;
const integer CURRENT_MODE_MASK = 240 ;
const integer KEY_AS_PATHNAME = 0 ;
const integer KEY_AS_FILENAME = 256 ;
const integer FOLLOW_SYMLINKS = 512 ;
const integer KEY_MODE_MASK = 3840 ;
const integer NEW_CURRENT_AND_KEY = 256 ;
const integer SKIP_DOTS = 4096 ;
const integer UNIX_PATHS = 8192 ;
/* Metody */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public mixed current ( void )
public int getFlags ( void )
public string key ( void )
public void next ( void )
public void rewind ( void )
public void setFlags ([ int $flags ] )
/* Metody dziedziczone */
public DirectoryIterator DirectoryIterator::current ( void )
public int DirectoryIterator::getATime ( void )
public string DirectoryIterator::getBasename ([ string $suffix ] )
public int DirectoryIterator::getCTime ( void )
public string DirectoryIterator::getExtension ( void )
public string DirectoryIterator::getFilename ( void )
public int DirectoryIterator::getGroup ( void )
public int DirectoryIterator::getInode ( void )
public int DirectoryIterator::getMTime ( void )
public int DirectoryIterator::getOwner ( void )
public string DirectoryIterator::getPath ( void )
public string DirectoryIterator::getPathname ( void )
public int DirectoryIterator::getPerms ( void )
public int DirectoryIterator::getSize ( void )
public string DirectoryIterator::getType ( void )
public bool DirectoryIterator::isDir ( void )
public bool DirectoryIterator::isDot ( void )
public bool DirectoryIterator::isExecutable ( void )
public bool DirectoryIterator::isFile ( void )
public bool DirectoryIterator::isLink ( void )
public bool DirectoryIterator::isReadable ( void )
public bool DirectoryIterator::isWritable ( void )
public string DirectoryIterator::key ( void )
public void DirectoryIterator::next ( void )
public void DirectoryIterator::rewind ( void )
public void DirectoryIterator::seek ( int $position )
public string DirectoryIterator::__toString ( void )
public bool DirectoryIterator::valid ( void )
}

Stałe predefiniowane

FilesystemIterator::CURRENT_AS_PATHNAME

Makes FilesystemIterator::current() return the pathname.

FilesystemIterator::CURRENT_AS_FILEINFO

Makes FilesystemIterator::current() return an SplFileInfo instance.

FilesystemIterator::CURRENT_AS_SELF

Makes FilesystemIterator::current() return $this (the FilesystemIterator).

FilesystemIterator::CURRENT_MODE_MASK

Masks FilesystemIterator::current()

FilesystemIterator::KEY_AS_PATHNAME

Makes FilesystemIterator::key() return the pathname.

FilesystemIterator::KEY_AS_FILENAME

Makes FilesystemIterator::key() return the filename.

FilesystemIterator::FOLLOW_SYMLINKS

Makes RecursiveDirectoryIterator::hasChildren() follow symlinks.

FilesystemIterator::KEY_MODE_MASK

Masks FilesystemIterator::key()

FilesystemIterator::NEW_CURRENT_AND_KEY

Same as FilesystemIterator::KEY_AS_FILENAME | FilesystemIterator::CURRENT_AS_FILEINFO.

FilesystemIterator::SKIP_DOTS

Skips dot files (. and ..).

FilesystemIterator::UNIX_PATHS

Makes paths use Unix-style forward slash irrespective of system default.

Rejestr zmian

Wersja | Opis
5.3.1 | Added FilesystemIterator::FOLLOW_SYMLINKS

Spis treści

  • FilesystemIterator::__construct — Constructs a new filesystem iterator
  • FilesystemIterator::current — The current file
  • FilesystemIterator::getFlags — Get the handling flags
  • FilesystemIterator::key — Retrieve the key for the current file
  • FilesystemIterator::next — Move to the next file
  • FilesystemIterator::rewind — Rewinds back to the beginning
  • FilesystemIterator::setFlags — Sets handling flags
EmptyIterator::valid
FilesystemIterator::__construct
Iteratory


Constructs a new filesystem iterator

FilesystemIterator
FilesystemIterator::current
FilesystemIterator
PHP Manual

FilesystemIterator::__construct

(PHP 5 >= 5.3.0)

FilesystemIterator::__construct — Constructs a new filesystem iterator

Opis

public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )

Constructs a new filesystem iterator from the path.

Parametry

path

The path of the filesystem item to be iterated over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under FilesystemIterator predefined constants. They can also be set later with FilesystemIterator::setFlags()

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws an UnexpectedValueException if the path cannot be found.

Przykłady

Przykład #1 FilesystemIterator::__construct() example

<?php
$it = new FilesystemIterator(dirname(__FILE__));
foreach ($it as $fileinfo) {
    echo $fileinfo->getFilename() . "\n";
}
?>

Powyższy przykład wyświetli:

apples.jpg
banana.jpg
example.php

Zobacz też:

  • FilesystemIterator::setFlags() - Sets handling flags
  • DirectoryIterator::__construct() - Constructs a new directory iterator from a path

FilesystemIterator
FilesystemIterator::current
FilesystemIterator


The current file

FilesystemIterator::__construct
FilesystemIterator::getFlags
FilesystemIterator
PHP Manual

FilesystemIterator::current

(PHP 5 >= 5.3.0)

FilesystemIterator::current — The current file

Opis

public mixed FilesystemIterator::current ( void )

Get file information of the current element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.

Przykłady

Przykład #1 FilesystemIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::CURRENT_AS_PATHNAME);
foreach ($iterator as $fileinfo) {
    echo $iterator->current() . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

Zobacz też:

  • FilesystemIterator constants
  • DirectoryIterator::current() - Return the current DirectoryIterator item.
  • DirectoryIterator::getFileName() - Return file name of current DirectoryIterator item.

FilesystemIterator::__construct
FilesystemIterator::getFlags
FilesystemIterator


Get the handling flags

FilesystemIterator::current
FilesystemIterator::key
FilesystemIterator
PHP Manual

FilesystemIterator::getFlags

(PHP 5 >= 5.3.0)

FilesystemIterator::getFlags — Get the handling flags

Opis

public int FilesystemIterator::getFlags ( void )

Gets the handling flags, as set in FilesystemIterator::__construct() or FilesystemIterator::setFlags().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The integer value of the set flags.

Zobacz też:

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • FilesystemIterator::setFlags() - Sets handling flags

FilesystemIterator::current
FilesystemIterator::key
FilesystemIterator


Retrieve the key for the current file

FilesystemIterator::getFlags
FilesystemIterator::next
FilesystemIterator
PHP Manual

FilesystemIterator::key

(PHP 5 >= 5.3.0)

FilesystemIterator::key — Retrieve the key for the current file

Opis

public string FilesystemIterator::key ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the pathname or filename depending on the set flags. See the FilesystemIterator constants.

Przykłady

Przykład #1 FilesystemIterator::key() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME);
foreach ($iterator as $fileinfo) {
    echo $iterator->key() . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg
banana.jpg
example.php

Zobacz też:

  • FilesystemIterator constants
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item.
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item

FilesystemIterator::getFlags
FilesystemIterator::next
FilesystemIterator


Move to the next file

FilesystemIterator::key
FilesystemIterator::rewind
FilesystemIterator
PHP Manual

FilesystemIterator::next

(PHP 5 >= 5.3.0)

FilesystemIterator::next — Move to the next file

Opis

public void FilesystemIterator::next ( void )

Move to the next file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 FilesystemIterator::next() example

List the contents of a directory using a while loop.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__));
while($iterator->valid()) {
    echo $iterator->getFilename() . "\n";
    $iterator->next();
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg
banana.jpg
example.php

Zobacz też:

  • DirectoryIterator::next() - Move forward to next DirectoryIterator item

FilesystemIterator::key
FilesystemIterator::rewind
FilesystemIterator


Rewinds back to the beginning

FilesystemIterator::next
FilesystemIterator::setFlags
FilesystemIterator
PHP Manual

FilesystemIterator::rewind

(PHP 5 >= 5.3.0)

FilesystemIterator::rewind — Rewinds back to the beginning

Opis

public void FilesystemIterator::rewind ( void )

Rewinds the directory back to the start.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 FilesystemIterator::rewind() example

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME);

echo $iterator->key() . "\n";

$iterator->next();
echo $iterator->key() . "\n";

$iterator->rewind();
echo $iterator->key() . "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

apple.jpg
banana.jpg
apple.jpg

Zobacz też:

  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start

FilesystemIterator::next
FilesystemIterator::setFlags
FilesystemIterator


Sets handling flags

FilesystemIterator::rewind
FilterIterator
FilesystemIterator
PHP Manual

FilesystemIterator::setFlags

(PHP 5 >= 5.3.0)

FilesystemIterator::setFlags — Sets handling flags

Opis

public void FilesystemIterator::setFlags ([ int $flags ] )

Sets handling flags.

Parametry

flags

The handling flags to set. See the FilesystemIterator constants.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 FilesystemIterator::key() example

This example demonstrates the difference between the FilesystemIterator::KEY_AS_PATHNAME and FilesystemIterator::KEY_AS_FILENAME flags.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_PATHNAME);
echo "Key as Pathname:\n";
foreach ($iterator as $key => $fileinfo) {
    echo $key . "\n";
}

$iterator->setFlags(FilesystemIterator::KEY_AS_FILENAME);
echo "\nKey as Filename:\n";
foreach ($iterator as $key => $fileinfo) {
    echo $key . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Key as Pathname:
/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

Key as Filename:
apple.jpg
banana.jpg
example.php

Zobacz też:

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • FilesystemIterator::getFlags() - Get the handling flags

FilesystemIterator::rewind
FilterIterator
FilesystemIterator


The FilterIterator class

(PHP 5 >= 5.1.0)

Wstęp

This abstract iterator filters out unwanted values. This class should be extended to implement custom iterator filters. The FilterIterator::accept() must be implemented in the subclass.

Krótki opis klasy

abstract FilterIterator extends IteratorIterator implements OuterIterator , Traversable , Iterator {
/* Metody */
abstract bool accept ( void )
__construct ( Iterator $iterator )
mixed current ( void )
Iterator getInnerIterator ( void )
mixed key ( void )
void next ( void )
void rewind ( void )
bool valid ( void )
}

Spis treści

  • FilterIterator::accept — Check whether the current element of the iterator is acceptable
  • FilterIterator::__construct — Construct a filterIterator
  • FilterIterator::current — Get the current element value
  • FilterIterator::getInnerIterator — Get the inner iterator
  • FilterIterator::key — Get the current key
  • FilterIterator::next — Move the iterator forward
  • FilterIterator::rewind — Rewind the iterator
  • FilterIterator::valid — Check whether the current element is valid
FilesystemIterator::setFlags
FilterIterator::accept
Iteratory


Check whether the current element of the iterator is acceptable

FilterIterator
FilterIterator::__construct
FilterIterator
PHP Manual

FilterIterator::accept

(PHP 5 >= 5.1.0)

FilterIterator::accept — Check whether the current element of the iterator is acceptable

Opis

abstract bool FilterIterator::accept ( void )

Returns whether the current element of the iterator is acceptable through this filter.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the current element is acceptable, otherwise FALSE.

Przykłady

Przykład #1 FilterIterator::accept() example

<?php
// This iterator filters all values with less than 10 characters
class LengthFilterIterator extends FilterIterator {

    public function accept() {
        // Only accept strings with a length of 10 and greater
        return strlen(parent::current()) > 10;
    }

}

$arrayIterator = new ArrayIterator(array('test1', 'more than 10 characters'));
$lengthFilter = new LengthFilterIterator($arrayIterator);

foreach ($lengthFilter as $value) {
    echo $value . "\n";
}
?>

Powyższy przykład wyświetli:

more than 10 characters

FilterIterator
FilterIterator::__construct
FilterIterator


Construct a filterIterator

FilterIterator::accept
FilterIterator::current
FilterIterator
PHP Manual

FilterIterator::__construct

(PHP 5 >= 5.1.0)

FilterIterator::__construct — Construct a filterIterator

Opis

FilterIterator::__construct ( Iterator $iterator )

Constructs a new FilterIterator, which consists of a passed in iterator with filters applied to it.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iterator

The iterator that is being filtered.

Zwracane wartości

The FilterIterator.

Zobacz też:

  • LimitIterator::__construct() - Construct a LimitIterator

FilterIterator::accept
FilterIterator::current
FilterIterator


Get the current element value

FilterIterator::__construct
FilterIterator::getInnerIterator
FilterIterator
PHP Manual

FilterIterator::current

(PHP 5 >= 5.1.0)

FilterIterator::current — Get the current element value

Opis

mixed FilterIterator::current ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Get the current element value.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current element value.

Zobacz też:

  • FilterIterator::key() - Get the current key
  • FilterIterator::next() - Move the iterator forward

FilterIterator::__construct
FilterIterator::getInnerIterator
FilterIterator


Get the inner iterator

FilterIterator::current
FilterIterator::key
FilterIterator
PHP Manual

FilterIterator::getInnerIterator

(PHP 5 >= 5.1.0)

FilterIterator::getInnerIterator — Get the inner iterator

Opis

Iterator FilterIterator::getInnerIterator ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Get the inner iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The inner iterator.

FilterIterator::current
FilterIterator::key
FilterIterator


Get the current key

FilterIterator::getInnerIterator
FilterIterator::next
FilterIterator
PHP Manual

FilterIterator::key

(PHP 5 >= 5.1.0)

FilterIterator::key — Get the current key

Opis

mixed FilterIterator::key ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Get the current key.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current key.

Zobacz też:

  • FilterIterator::next() - Move the iterator forward
  • FilterIterator::current() - Get the current element value

FilterIterator::getInnerIterator
FilterIterator::next
FilterIterator


Move the iterator forward

FilterIterator::key
FilterIterator::rewind
FilterIterator
PHP Manual

FilterIterator::next

(PHP 5 >= 5.1.0)

FilterIterator::next — Move the iterator forward

Opis

void FilterIterator::next ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Move the iterator forward.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • FilterIterator::current() - Get the current element value
  • FilterIterator::next()

FilterIterator::key
FilterIterator::rewind
FilterIterator


Rewind the iterator

FilterIterator::next
FilterIterator::valid
FilterIterator
PHP Manual

FilterIterator::rewind

(PHP 5 >= 5.1.0)

FilterIterator::rewind — Rewind the iterator

Opis

void FilterIterator::rewind ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Rewind the iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • FilterIterator::current() - Get the current element value
  • FilterIterator::key() - Get the current key
  • FilterIterator::next() - Move the iterator forward

FilterIterator::next
FilterIterator::valid
FilterIterator


Check whether the current element is valid

FilterIterator::rewind
GlobIterator
FilterIterator
PHP Manual

FilterIterator::valid

(PHP 5 >= 5.1.0)

FilterIterator::valid — Check whether the current element is valid

Opis

bool FilterIterator::valid ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Checks whether the current element is valid.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the current element is valid, otherwise FALSE

FilterIterator::rewind
GlobIterator
FilterIterator


The GlobIterator class

(PHP 5 >= 5.3.0)

Wstęp

Iterates through a file system in a similar fashion to glob().

Krótki opis klasy

GlobIterator extends FilesystemIterator implements Iterator , Traversable , SeekableIterator , Countable {
/* Metody */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )
public int count ( void )
/* Metody dziedziczone */
public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public mixed FilesystemIterator::current ( void )
public int FilesystemIterator::getFlags ( void )
public string FilesystemIterator::key ( void )
public void FilesystemIterator::next ( void )
public void FilesystemIterator::rewind ( void )
public void FilesystemIterator::setFlags ([ int $flags ] )
}

Spis treści

  • GlobIterator::__construct — Construct a directory using glob
  • GlobIterator::count — Get the number of directories and files
FilterIterator::valid
GlobIterator::__construct
Iteratory


Construct a directory using glob

GlobIterator
GlobIterator::count
GlobIterator
PHP Manual

GlobIterator::__construct

(PHP 5 >= 5.3.0)

GlobIterator::__construct — Construct a directory using glob

Opis

public GlobIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )

Constructs a new directory iterator from a glob expression.

Parametry

path

The path of the directory.

flags

Option flags, the flags may be a bitmask of the FilesystemIterator constants.

Przykłady

Przykład #1 GlobIterator example

<?php
$iterator = new GlobIterator('*.dll', FilesystemIterator::KEY_AS_FILENAME);

if(!$iterator->count())
{
    echo 'No matches';
}
else
{
    $n = 0;

    printf("Matched %d item(s)\r\n", $iterator->count());

    foreach($iterator as $item)
    {
        printf("[%d] %s\r\n", ++$n, $iterator->key());
    }
}
?>

Powyższy przykład wyświetli coś podobnego do:

Matched 2 item(s)
[1] php5ts.dll
[2] php_gd2.dll

Zobacz też:

  • DirectoryIterator::__construct() - Constructs a new directory iterator from a path
  • GlobIterator::count() - Get the number of directories and files
  • glob() - Find pathnames matching a pattern

GlobIterator
GlobIterator::count
GlobIterator


Get the number of directories and files

GlobIterator::__construct
InfiniteIterator
GlobIterator
PHP Manual

GlobIterator::count

(PHP 5 >= 5.3.0)

GlobIterator::count — Get the number of directories and files

Opis

public int GlobIterator::count ( void )

Gets the number of directories and files found by the glob expression.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The number of returned directories and files, as an integer.

Przykłady

Przykład #1 GlobIterator::count() example

<?php
$iterator = new GlobIterator('*.xml');

printf("Matched %d item(s)\r\n", $iterator->count());
?>

Powyższy przykład wyświetli coś podobnego do:

Matched 8 item(s)

Zobacz też:

  • GlobIterator::__construct() - Construct a directory using glob
  • count() - Zlicza ilość elementów w tablicy lub pól obiektu
  • glob() - Find pathnames matching a pattern

GlobIterator::__construct
InfiniteIterator
GlobIterator


The InfiniteIterator class

(PHP 5 >= 5.1.0)

Wstęp

The InfiniteIterator allows one to infinitely iterate over an iterator without having to manually rewind the iterator upon reaching its end.

Krótki opis klasy

InfiniteIterator extends IteratorIterator implements OuterIterator , Traversable , Iterator {
/* Metody */
public __construct ( Iterator $iterator )
public void next ( void )
/* Metody dziedziczone */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public void IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Spis treści

  • InfiniteIterator::__construct — Constructs an InfiniteIterator
  • InfiniteIterator::next — Moves the inner Iterator forward or rewinds it
GlobIterator::count
InfiniteIterator::__construct
Iteratory


Constructs an InfiniteIterator

InfiniteIterator
InfiniteIterator::next
InfiniteIterator
PHP Manual

InfiniteIterator::__construct

(PHP 5 >= 5.1.0)

InfiniteIterator::__construct — Constructs an InfiniteIterator

Opis

public InfiniteIterator::__construct ( Iterator $iterator )

Constructs an InfiniteIterator from an Iterator.

Parametry

iterator

The iterator to infinitely iterate over.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws an E_RECOVERABLE_ERROR if the iterator parameter is not an Iterator.

Przykłady

Przykład #1 InfiniteIterator::__construct() example

<?php
$arrayit  = new ArrayIterator(array('cat','dog'));
$infinite = new InfiniteIterator($arrayit);
$limit    = new LimitIterator($infinite, 0, 7);
foreach($limit as $value)
{
    echo "$value\n";
}
?>

Powyższy przykład wyświetli:

cat
dog
cat
dog
cat
dog
cat

Zobacz też:

  • InfiniteIterator::next() - Moves the inner Iterator forward or rewinds it

InfiniteIterator
InfiniteIterator::next
InfiniteIterator


Moves the inner Iterator forward or rewinds it

InfiniteIterator::__construct
IteratorIterator
InfiniteIterator
PHP Manual

InfiniteIterator::next

(PHP 5 >= 5.1.0)

InfiniteIterator::next — Moves the inner Iterator forward or rewinds it

Opis

public void InfiniteIterator::next ( void )

Moves the inner Iterator forward to its next element if there is one, otherwise rewinds the inner Iterator back to the beginning.

Informacja:

Even an InfiniteIterator stops if its inner Iterator is empty.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • InfiniteIterator::__construct() - Constructs an InfiniteIterator

InfiniteIterator::__construct
IteratorIterator
InfiniteIterator


The IteratorIterator class

(PHP 5 >= 5.1.0)

Wstęp

This iterator wrapper allows the conversion of anything that is Traversable into an Iterator. It is important to understand that most classes that do not implement Iterators have reasons as most likely they do not allow the full Iterator feature set. If so, techniques should be provided to prevent misuse, otherwise expect exceptions or fatal errors.

Krótki opis klasy

IteratorIterator implements Iterator , Traversable , OuterIterator {
/* Metody */
public __construct ( Traversable $iterator )
public mixed current ( void )
public Traversable getInnerIterator ( void )
public void key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
}

Spis treści

  • IteratorIterator::__construct — Create an iterator from anything that is traversable
  • IteratorIterator::current — Get the current value
  • IteratorIterator::getInnerIterator — Get the inner iterator
  • IteratorIterator::key — Get the key of the current element
  • IteratorIterator::next — Forward to the next element
  • IteratorIterator::rewind — Rewind to the first element
  • IteratorIterator::valid — Checks if the iterator is valid
InfiniteIterator::next
IteratorIterator::__construct
Iteratory


Create an iterator from anything that is traversable

IteratorIterator
IteratorIterator::current
IteratorIterator
PHP Manual

IteratorIterator::__construct

(PHP 5 >= 5.1.0)

IteratorIterator::__construct — Create an iterator from anything that is traversable

Opis

public IteratorIterator::__construct ( Traversable $iterator )

Creates an iterator from anything that is traversable.

Parametry

iterator

The traversable iterator.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • Traversable

IteratorIterator
IteratorIterator::current
IteratorIterator


Get the current value

IteratorIterator::__construct
IteratorIterator::getInnerIterator
IteratorIterator
PHP Manual

IteratorIterator::current

(PHP 5 >= 5.1.0)

IteratorIterator::current — Get the current value

Opis

public mixed IteratorIterator::current ( void )

Get the value of the current element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The value of the current element.

Zobacz też:

  • IteratorIterator::key() - Get the key of the current element

IteratorIterator::__construct
IteratorIterator::getInnerIterator
IteratorIterator


Get the inner iterator

IteratorIterator::current
IteratorIterator::key
IteratorIterator
PHP Manual

IteratorIterator::getInnerIterator

(PHP 5 >= 5.1.0)

IteratorIterator::getInnerIterator — Get the inner iterator

Opis

public Traversable IteratorIterator::getInnerIterator ( void )

Get the inner iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The inner iterator as passed to IteratorIterator::__construct().

Zobacz też:

  • Iterator
  • OuterIterator

IteratorIterator::current
IteratorIterator::key
IteratorIterator


Get the key of the current element

IteratorIterator::getInnerIterator
IteratorIterator::next
IteratorIterator
PHP Manual

IteratorIterator::key

(PHP 5 >= 5.1.0)

IteratorIterator::key — Get the key of the current element

Opis

public void IteratorIterator::key ( void )

Get the key of the current element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The key of the current element.

Zobacz też:

  • IteratorIterator::current() - Get the current value

IteratorIterator::getInnerIterator
IteratorIterator::next
IteratorIterator


Forward to the next element

IteratorIterator::key
IteratorIterator::rewind
IteratorIterator
PHP Manual

IteratorIterator::next

(PHP 5 >= 5.1.0)

IteratorIterator::next — Forward to the next element

Opis

public void IteratorIterator::next ( void )

Forward to the next element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • IteratorIterator::rewind() - Rewind to the first element
  • IteratorIterator::valid() - Checks if the iterator is valid

IteratorIterator::key
IteratorIterator::rewind
IteratorIterator


Rewind to the first element

IteratorIterator::next
IteratorIterator::valid
IteratorIterator
PHP Manual

IteratorIterator::rewind

(PHP 5 >= 5.1.0)

IteratorIterator::rewind — Rewind to the first element

Opis

public void IteratorIterator::rewind ( void )

Rewinds to the first element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • IteratorIterator::next() - Forward to the next element
  • IteratorIterator::valid() - Checks if the iterator is valid

IteratorIterator::next
IteratorIterator::valid
IteratorIterator


Checks if the iterator is valid

IteratorIterator::rewind
LimitIterator
IteratorIterator
PHP Manual

IteratorIterator::valid

(PHP 5 >= 5.1.0)

IteratorIterator::valid — Checks if the iterator is valid

Opis

public bool IteratorIterator::valid ( void )

Checks if the iterator is valid.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the iterator is valid, otherwise FALSE

Zobacz też:

  • iterator_count() - Count the elements in an iterator
  • IteratorIterator::current() - Get the current value

IteratorIterator::rewind
LimitIterator
IteratorIterator


The LimitIterator class

(PHP 5 >= 5.1.0)

Wstęp

The LimitIterator class allows iteration over a limited subset of items in an Iterator.

Krótki opis klasy

LimitIterator extends IteratorIterator implements OuterIterator , Traversable , Iterator {
/* Metody */
public __construct ( Iterator $iterator [, int $offset = 0 [, int $count = -1 ]] )
public mixed current ( void )
public Iterator getInnerIterator ( void )
public int getPosition ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public int seek ( int $position )
public bool valid ( void )
}

Przykłady

Przykład #1 LimitIterator usage example

<?php

// Create an iterator to be limited
$fruits = new ArrayIterator(array(
    'apple',
    'banana',
    'cherry',
    'damson',
    'elderberry'
));

// Loop over first three fruits only
foreach (new LimitIterator($fruits, 0, 3) as $fruit) {
    var_dump($fruit);
}

echo "\n";

// Loop from third fruit until the end
// Note: offset starts from zero for apple
foreach (new LimitIterator($fruits, 2) as $fruit) {
    var_dump($fruit);
}

?>

Powyższy przykład wyświetli:

string(5) "apple"
string(6) "banana"
string(6) "cherry"

string(6) "cherry"
string(6) "damson"
string(10) "elderberry"

Spis treści

  • LimitIterator::__construct — Construct a LimitIterator
  • LimitIterator::current — Get current element
  • LimitIterator::getInnerIterator — Get inner iterator
  • LimitIterator::getPosition — Return the current position
  • LimitIterator::key — Get current key
  • LimitIterator::next — Move the iterator forward
  • LimitIterator::rewind — Rewind the iterator to the specified starting offset
  • LimitIterator::seek — Seek to the given position
  • LimitIterator::valid — Check whether the current element is valid
IteratorIterator::valid
LimitIterator::__construct
Iteratory


Construct a LimitIterator

LimitIterator
LimitIterator::current
LimitIterator
PHP Manual

LimitIterator::__construct

(PHP 5 >= 5.1.0)

LimitIterator::__construct — Construct a LimitIterator

Opis

public LimitIterator::__construct ( Iterator $iterator [, int $offset = 0 [, int $count = -1 ]] )

Constructs a new LimitIterator from an iterator with a given starting offset and maximum count.

Parametry

iterator

The Iterator to limit.

offset

Optional offset of the limit.

count

Optional count of the limit.

Zwracane wartości

The new LimitIterator.

Błędy/Wyjątki

Throws an OutOfRangeException if the offset is less than 0 or the count is less than -1.

Przykłady

Przykład #1 LimitIterator::__construct() example

<?php
$ait = new ArrayIterator(array('a', 'b', 'c', 'd', 'e'));
$lit = new LimitIterator($ait, 1, 3);
foreach ($lit as $value) {
    echo $value . "\n";
}
?>

Powyższy przykład wyświetli:

b
c
d

Zobacz też:

  • LimitIterator examples

LimitIterator
LimitIterator::current
LimitIterator


Get current element

LimitIterator::__construct
LimitIterator::getInnerIterator
LimitIterator
PHP Manual

LimitIterator::current

(PHP 5 >= 5.1.0)

LimitIterator::current — Get current element

Opis

public mixed LimitIterator::current ( void )

Gets the current element of the inner Iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current element or NULL if there is none.

Zobacz też:

  • LimitIterator::key() - Get current key
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

LimitIterator::__construct
LimitIterator::getInnerIterator
LimitIterator


Get inner iterator

LimitIterator::current
LimitIterator::getPosition
LimitIterator
PHP Manual

LimitIterator::getInnerIterator

(PHP 5 >= 5.1.0)

LimitIterator::getInnerIterator — Get inner iterator

Opis

public Iterator LimitIterator::getInnerIterator ( void )

Gets the inner Iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The inner iterator passed to LimitIterator::__construct().

Zobacz też:

  • LimitIterator::__construct() - Construct a LimitIterator
  • IteratorIterator::getInnerIterator() - Get the inner iterator

LimitIterator::current
LimitIterator::getPosition
LimitIterator


Return the current position

LimitIterator::getInnerIterator
LimitIterator::key
LimitIterator
PHP Manual

LimitIterator::getPosition

(PHP 5 >= 5.1.0)

LimitIterator::getPosition — Return the current position

Opis

public int LimitIterator::getPosition ( void )

Gets the current zero-based position of the inner Iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current position.

Przykłady

Przykład #1 LimitIterator::getPosition() example

<?php
$fruits = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry',
    'd' => 'damson',
    'e' => 'elderberry'
);
$array_it = new ArrayIterator($fruits);
$limit_it = new LimitIterator($array_it, 2, 3);
foreach ($limit_it as $item) {
    echo $limit_it->getPosition() . ' ' . $item . "\n";
}
?>

Powyższy przykład wyświetli:

2 cherry
3 damson
4 elderberry

Zobacz też:

  • FilterIterator::key() - Get the current key

LimitIterator::getInnerIterator
LimitIterator::key
LimitIterator


Get current key

LimitIterator::getPosition
LimitIterator::next
LimitIterator
PHP Manual

LimitIterator::key

(PHP 5 >= 5.1.0)

LimitIterator::key — Get current key

Opis

public mixed LimitIterator::key ( void )

Gets the key for the current item in the inner Iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the key for the current item.

Zobacz też:

  • LimitIterator::getPosition() - Return the current position
  • LimitIterator::current() - Get current element
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

LimitIterator::getPosition
LimitIterator::next
LimitIterator


Move the iterator forward

LimitIterator::key
LimitIterator::rewind
LimitIterator
PHP Manual

LimitIterator::next

(PHP 5 >= 5.1.0)

LimitIterator::next — Move the iterator forward

Opis

public void LimitIterator::next ( void )

Moves the iterator forward.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

LimitIterator::key
LimitIterator::rewind
LimitIterator


Rewind the iterator to the specified starting offset

LimitIterator::next
LimitIterator::seek
LimitIterator
PHP Manual

LimitIterator::rewind

(PHP 5 >= 5.1.0)

LimitIterator::rewind — Rewind the iterator to the specified starting offset

Opis

public void LimitIterator::rewind ( void )

Rewinds the iterator to the starting offset specified in LimitIterator::__construct().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

LimitIterator::next
LimitIterator::seek
LimitIterator


Seek to the given position

LimitIterator::rewind
LimitIterator::valid
LimitIterator
PHP Manual

LimitIterator::seek

(PHP 5 >= 5.1.0)

LimitIterator::seek — Seek to the given position

Opis

public int LimitIterator::seek ( int $position )

Moves the iterator to the offset specified by position.

Parametry

position

The position to seek to.

Zwracane wartości

Returns the offset position after seeking.

Błędy/Wyjątki

Throws an OutOfBoundsException if the position is outside of the limits specified in LimitIterator::__construct().

Zobacz też:

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::valid() - Check whether the current element is valid

LimitIterator::rewind
LimitIterator::valid
LimitIterator


Check whether the current element is valid

LimitIterator::seek
MultipleIterator
LimitIterator
PHP Manual

LimitIterator::valid

(PHP 5 >= 5.1.0)

LimitIterator::valid — Check whether the current element is valid

Opis

public bool LimitIterator::valid ( void )

Checks whether the current element is valid.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::seek() - Seek to the given position

LimitIterator::seek
MultipleIterator
LimitIterator


The MultipleIterator class

(PHP 5 >= 5.3.0)

Wstęp

An Iterator that sequentially iterates over all attached iterators

Krótki opis klasy

MultipleIterator implements Iterator , Traversable {
/* Stałe */
const integer MIT_NEED_ANY = 0 ;
const integer MIT_NEED_ALL = 1 ;
const integer MIT_KEYS_NUMERIC = 0 ;
const integer MIT_KEYS_ASSOC = 2 ;
/* Metody */
public __construct ([ int $flags = MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC ] )
public void attachIterator ( Iterator $iterator [, string $infos ] )
public void containsIterator ( Iterator $iterator )
public void countIterators ( void )
public void current ( void )
public void detachIterator ( Iterator $iterator )
public void getFlags ( void )
public void key ( void )
public void next ( void )
public void rewind ( void )
public void setFlags ( int $flags )
public void valid ( void )
}

Stałe predefiniowane

MultipleIterator::MIT_NEED_ANY

Do not require all sub iterators to be valid in iteration.

MultipleIterator::MIT_NEED_ALL

Require all sub iterators to be valid in iteration.

MultipleIterator::MIT_KEYS_NUMERIC

Keys are created from the sub iterators position.

MultipleIterator::MIT_KEYS_ASSOC

Keys are created from sub iterators associated information.

Spis treści

  • MultipleIterator::attachIterator — Attaches iterator information
  • MultipleIterator::__construct — Constructs a new MultipleIterator
  • MultipleIterator::containsIterator — Checks if an iterator is attached
  • MultipleIterator::countIterators — Gets the number of attached iterator instances
  • MultipleIterator::current — Gets the registered iterator instances
  • MultipleIterator::detachIterator — Detaches an iterator
  • MultipleIterator::getFlags — Gets the flag information
  • MultipleIterator::key — Gets the registered iterator instances
  • MultipleIterator::next — Moves all attached iterator instances forward
  • MultipleIterator::rewind — Rewinds all attached iterator instances
  • MultipleIterator::setFlags — Sets flags
  • MultipleIterator::valid — Checks the validity of sub iterators
LimitIterator::valid
MultipleIterator::attachIterator
Iteratory


Attaches iterator information

MultipleIterator
MultipleIterator::__construct
MultipleIterator
PHP Manual

MultipleIterator::attachIterator

(PHP 5 >= 5.3.0)

MultipleIterator::attachIterator — Attaches iterator information

Opis

public void MultipleIterator::attachIterator ( Iterator $iterator [, string $infos ] )

Attaches iterator information.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iterator

The new iterator to attach.

infos

The associative information for the Iterator, which must be an integer, a string, or NULL.

Zwracane wartości

Description...

Błędy/Wyjątki

An IllegalValueException if the iterator parameter is invalid, or if infos is already associated information.

Zobacz też:

  • MultipleIterator::__construct() - Constructs a new MultipleIterator

MultipleIterator
MultipleIterator::__construct
MultipleIterator


Constructs a new MultipleIterator

MultipleIterator::attachIterator
MultipleIterator::containsIterator
MultipleIterator
PHP Manual

MultipleIterator::__construct

(PHP 5 >= 5.3.0)

MultipleIterator::__construct — Constructs a new MultipleIterator

Opis

public MultipleIterator::__construct() ([ int $flags = MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC ] )

Construct a new MultipleIterator.

Parametry

flags

The flags to set, according to the Flag Constants.

  • MultipleIterator::MIT_NEED_ALL or MultipleIterator::MIT_NEED_ANY
  • MultipleIterator::MIT_KEYS_NUMERIC or MultipleIterator::MIT_KEYS_ASSOC

Defaults to MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Iterating a MultipleIterator

<?php
$people = new ArrayIterator(array('John', 'Jane', 'Jack', 'Judy'));
$roles  = new ArrayIterator(array('Developer', 'Scrum Master', 'Project Owner'));

$team = new MultipleIterator($flags);
$team->attachIterator($people, 'person');
$team->attachIterator($roles, 'role');

foreach ($team as $member) {
    print_r($member);
}
?>

Output with $flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC

Array
(
    [0] => John
    [1] => Developer
)
Array
(
    [0] => Jane
    [1] => Scrum Master
)
Array
(
    [0] => Jack
    [1] => Project Owner
)

Output with $flags = MIT_NEED_ANY|MIT_KEYS_NUMERIC

Array
(
    [0] => John
    [1] => Developer
)
Array
(
    [0] => Jane
    [1] => Scrum Master
)
Array
(
    [0] => Jack
    [1] => Project Owner
)
Array
(
    [0] => Judy
    [1] =>
)

Output with $flags = MIT_NEED_ALL|MIT_KEYS_ASSOC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)

Output with $flags = MIT_NEED_ANY|MIT_KEYS_NUMERIC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)
Array
(
    [person] => Judy
    [role] =>
)

Zobacz też:

  • Flag Constants
  • MultipleIterator::valid() - Checks the validity of sub iterators

MultipleIterator::attachIterator
MultipleIterator::containsIterator
MultipleIterator


Checks if an iterator is attached

MultipleIterator::__construct
MultipleIterator::countIterators
MultipleIterator
PHP Manual

MultipleIterator::containsIterator

(PHP 5 >= 5.3.0)

MultipleIterator::containsIterator — Checks if an iterator is attached

Opis

public void MultipleIterator::containsIterator ( Iterator $iterator )

Checks if an iterator is attached or not.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iterator

The iterator to check.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • MultipleIterator::valid() - Checks the validity of sub iterators

MultipleIterator::__construct
MultipleIterator::countIterators
MultipleIterator


Gets the number of attached iterator instances

MultipleIterator::containsIterator
MultipleIterator::current
MultipleIterator
PHP Manual

MultipleIterator::countIterators

(PHP 5 >= 5.3.0)

MultipleIterator::countIterators — Gets the number of attached iterator instances

Opis

public void MultipleIterator::countIterators ( void )

Gets the number of attached iterator instances.

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 attached iterator instances (as an integer).

Zobacz też:

  • MultipleIterator::containsIterator() - Checks if an iterator is attached

MultipleIterator::containsIterator
MultipleIterator::current
MultipleIterator


Gets the registered iterator instances

MultipleIterator::countIterators
MultipleIterator::detachIterator
MultipleIterator
PHP Manual

MultipleIterator::current

(PHP 5 >= 5.3.0)

MultipleIterator::current — Gets the registered iterator instances

Opis

public void MultipleIterator::current ( void )

Get the registered iterator instances.

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 all registered iterator instances, or FALSE if no sub iterator is attached.

Błędy/Wyjątki

A RuntimeException if mode MIT_NEED_ALL is set and at least one attached iterator is not valid. Or an IllegalValueException if a key is NULL and MIT_KEYS_ASSOC is set.

Zobacz też:

  • MultipleIterator::valid() - Checks the validity of sub iterators

MultipleIterator::countIterators
MultipleIterator::detachIterator
MultipleIterator


Detaches an iterator

MultipleIterator::current
MultipleIterator::getFlags
MultipleIterator
PHP Manual

MultipleIterator::detachIterator

(PHP 5 >= 5.3.0)

MultipleIterator::detachIterator — Detaches an iterator

Opis

public void MultipleIterator::detachIterator ( Iterator $iterator )

Detaches an iterator.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iterator

The iterator to detach.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • MultipleIterator::attachIterator() - Attaches iterator information

MultipleIterator::current
MultipleIterator::getFlags
MultipleIterator


Gets the flag information

MultipleIterator::detachIterator
MultipleIterator::key
MultipleIterator
PHP Manual

MultipleIterator::getFlags

(PHP 5 >= 5.3.0)

MultipleIterator::getFlags — Gets the flag information

Opis

public void MultipleIterator::getFlags ( void )

Gets information about the flags.

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

Information about the flags, as an integer.

Zobacz też:

  • Flag Constants
  • MultipleIterator::__construct() - Constructs a new MultipleIterator
  • MultipleIterator::setFlags() - Sets flags

MultipleIterator::detachIterator
MultipleIterator::key
MultipleIterator


Gets the registered iterator instances

MultipleIterator::getFlags
MultipleIterator::next
MultipleIterator
PHP Manual

MultipleIterator::key

(PHP 5 >= 5.3.0)

MultipleIterator::key — Gets the registered iterator instances

Opis

public void MultipleIterator::key ( void )

Get the registered iterator instances.

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 all registered iterator instances, or FALSE if no sub iterator is attached.

Błędy/Wyjątki

A LogicException if mode MIT_NEED_ALL is set, and at least one attached iterator is not valid.

Zobacz też:

  • MultipleIterator::current() - Gets the registered iterator instances

MultipleIterator::getFlags
MultipleIterator::next
MultipleIterator


Moves all attached iterator instances forward

MultipleIterator::key
MultipleIterator::rewind
MultipleIterator
PHP Manual

MultipleIterator::next

(PHP 5 >= 5.3.0)

MultipleIterator::next — Moves all attached iterator instances forward

Opis

public void MultipleIterator::next ( void )

Moves all attached iterator instances forward.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • MultipleIterator::rewind() - Rewinds all attached iterator instances

MultipleIterator::key
MultipleIterator::rewind
MultipleIterator


Rewinds all attached iterator instances

MultipleIterator::next
MultipleIterator::setFlags
MultipleIterator
PHP Manual

MultipleIterator::rewind

(PHP 5 >= 5.3.0)

MultipleIterator::rewind — Rewinds all attached iterator instances

Opis

public void MultipleIterator::rewind ( void )

Rewinds all attached iterator instances.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • MultipleIterator::next() - Moves all attached iterator instances forward

MultipleIterator::next
MultipleIterator::setFlags
MultipleIterator


Sets flags

MultipleIterator::rewind
MultipleIterator::valid
MultipleIterator
PHP Manual

MultipleIterator::setFlags

(PHP 5 >= 5.3.0)

MultipleIterator::setFlags — Sets flags

Opis

public void MultipleIterator::setFlags ( int $flags )

Sets flags.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flags

The flags to set, according to the Flag Constants

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • Flag Constants
  • MultipleIterator::__construct() - Constructs a new MultipleIterator
  • MultipleIterator::getFlags() - Gets the flag information

MultipleIterator::rewind
MultipleIterator::valid
MultipleIterator


Checks the validity of sub iterators

MultipleIterator::setFlags
NoRewindIterator
MultipleIterator
PHP Manual

MultipleIterator::valid

(PHP 5 >= 5.3.0)

MultipleIterator::valid — Checks the validity of sub iterators

Opis

public void MultipleIterator::valid ( void )

Checks the validity of sub iterators.

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

Returns TRUE if one or all sub iterators are valid depending on flags, otherwise FALSE

Zobacz też:

  • MultipleIterator::__construct() - Constructs a new MultipleIterator

MultipleIterator::setFlags
NoRewindIterator
MultipleIterator


The NoRewindIterator class

(PHP 5 >= 5.1.0)

Wstęp

This iterator cannot be rewinded.

Krótki opis klasy

NoRewindIterator extends IteratorIterator {
/* Metody */
public __construct ( Iterator $iterator )
public mixed current ( void )
public iterator getInnerIterator ( void )
public mixed key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
/* Metody dziedziczone */
public IteratorIterator::__construct ( Traversable $iterator )
public mixed IteratorIterator::current ( void )
public Traversable IteratorIterator::getInnerIterator ( void )
public void IteratorIterator::key ( void )
public void IteratorIterator::next ( void )
public void IteratorIterator::rewind ( void )
public bool IteratorIterator::valid ( void )
}

Spis treści

  • NoRewindIterator::__construct — Construct a NoRewindIterator
  • NoRewindIterator::current — Get the current value
  • NoRewindIterator::getInnerIterator — Get the inner iterator
  • NoRewindIterator::key — Get the current key
  • NoRewindIterator::next — Forward to the next element
  • NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator.
  • NoRewindIterator::valid — Validates the iterator
MultipleIterator::valid
NoRewindIterator::__construct
Iteratory


Construct a NoRewindIterator

NoRewindIterator
NoRewindIterator::current
NoRewindIterator
PHP Manual

NoRewindIterator::__construct

(PHP 5 >= 5.1.0)

NoRewindIterator::__construct — Construct a NoRewindIterator

Opis

public NoRewindIterator::__construct ( Iterator $iterator )

Constructs a NoRewindIterator.

Parametry

iterator

The iterator being used.

Zwracane wartości

A NoRewindIterator() based on the passed in iterator.

Przykłady

Przykład #1 NoRewindIterator::__construct() example

The second loop does not output because the iterator is only used once, as it does not rewind.

<?php
$fruit = array('apple', 'banana', 'cranberry');

$arr = new ArrayObject($fruit);
$it  = new NoRewindIterator($arr->getIterator());

echo "Fruit A:\n";
foreach( $it as $item ) {
    echo $item . "\n";
}

echo "Fruit B:\n";
foreach( $it as $item ) {
    echo $item . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Fruit A:
apple
banana
cranberry
Fruit B:

Zobacz też:

  • NoRewindIterator::valid() - Validates the iterator

NoRewindIterator
NoRewindIterator::current
NoRewindIterator


Get the current value

NoRewindIterator::__construct
NoRewindIterator::getInnerIterator
NoRewindIterator
PHP Manual

NoRewindIterator::current

(PHP 5 >= 5.1.0)

NoRewindIterator::current — Get the current value

Opis

public mixed NoRewindIterator::current ( void )

Gets the current value.

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 current value.

Zobacz też:

  • NoRewindIterator::key() - Get the current key

NoRewindIterator::__construct
NoRewindIterator::getInnerIterator
NoRewindIterator


Get the inner iterator

NoRewindIterator::current
NoRewindIterator::key
NoRewindIterator
PHP Manual

NoRewindIterator::getInnerIterator

(PHP 5 >= 5.1.0)

NoRewindIterator::getInnerIterator — Get the inner iterator

Opis

public iterator NoRewindIterator::getInnerIterator ( void )

Gets the inner iterator, that was passed in to NoRewindIterator.

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 inner iterator, as passed to NoRewindIterator::__construct().

Zobacz też:

  • NoRewindIterator::valid() - Validates the iterator

NoRewindIterator::current
NoRewindIterator::key
NoRewindIterator


Get the current key

NoRewindIterator::getInnerIterator
NoRewindIterator::next
NoRewindIterator
PHP Manual

NoRewindIterator::key

(PHP 5 >= 5.1.0)

NoRewindIterator::key — Get the current key

Opis

public mixed NoRewindIterator::key ( void )

Gets the current key.

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 current key.

Zobacz też:

  • NoRewindIterator::next() - Forward to the next element

NoRewindIterator::getInnerIterator
NoRewindIterator::next
NoRewindIterator


Forward to the next element

NoRewindIterator::key
NoRewindIterator::rewind
NoRewindIterator
PHP Manual

NoRewindIterator::next

(PHP 5 >= 5.1.0)

NoRewindIterator::next — Forward to the next element

Opis

public void NoRewindIterator::next ( void )

Forwards to the next element.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • NoRewindIterator::rewind() - Prevents the rewind operation on the inner iterator.

NoRewindIterator::key
NoRewindIterator::rewind
NoRewindIterator


Prevents the rewind operation on the inner iterator.

NoRewindIterator::next
NoRewindIterator::valid
NoRewindIterator
PHP Manual

NoRewindIterator::rewind

(PHP 5 >= 5.1.0)

NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator.

Opis

public void NoRewindIterator::rewind ( void )

Prevents the rewind operation on the inner iterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 NoRewindIterator::rewind() example

This example demonstrates that calling rewind on a NoRewindIterator object has no effect.

<?php
$fruits = array("lemon", "orange", "apple", "pear");

$noRewindIterator = new NoRewindIterator(new ArrayIterator($fruits));

echo $noRewindIterator->current() . "\n";
$noRewindIterator->next();
// now rewind the iterator (nothing should happen)
$noRewindIterator->rewind();
echo $noRewindIterator->current() . "\n";
?>

Powyższy przykład wyświetli:

lemon
orange

NoRewindIterator::next
NoRewindIterator::valid
NoRewindIterator


Validates the iterator

NoRewindIterator::rewind
ParentIterator
NoRewindIterator
PHP Manual

NoRewindIterator::valid

(PHP 5 >= 5.1.0)

NoRewindIterator::valid — Validates the iterator

Opis

public bool NoRewindIterator::valid ( void )

Checks whether the iterator is valid.

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

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • NoRewindIterator::getInnerIterator() - Get the inner iterator

NoRewindIterator::rewind
ParentIterator
NoRewindIterator


The ParentIterator class

(PHP 5 >= 5.1.0)

Wstęp

This extended FilterIterator allows a recursive iteration using RecursiveIteratorIterator that only shows those elements which have children.

Krótki opis klasy

ParentIterator extends RecursiveFilterIterator implements RecursiveIterator , OuterIterator , Traversable , Iterator {
/* Metody */
public bool accept ( void )
public __construct ( RecursiveIterator $iterator )
public ParentIterator getChildren ( void )
public bool hasChildren ( void )
public void next ( void )
public void rewind ( void )
}

Spis treści

  • ParentIterator::accept — Determines acceptability
  • ParentIterator::__construct — Constructs a ParentIterator
  • ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator
  • ParentIterator::hasChildren — Check whether the inner iterator's current element has children
  • ParentIterator::next — Move the iterator forward
  • ParentIterator::rewind — Rewind the iterator
NoRewindIterator::valid
ParentIterator::accept
Iteratory


Determines acceptability

ParentIterator
ParentIterator::__construct
ParentIterator
PHP Manual

ParentIterator::accept

(PHP 5 >= 5.1.0)

ParentIterator::accept — Determines acceptability

Opis

public bool ParentIterator::accept ( void )

Determines if the current element has children.

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

TRUE if the current element is acceptable, otherwise FALSE.

Zobacz też:

  • ParentIterator::hasChildren() - Check whether the inner iterator's current element has children
  • FilterIterator::accept() - Check whether the current element of the iterator is acceptable

ParentIterator
ParentIterator::__construct
ParentIterator


Constructs a ParentIterator

ParentIterator::accept
ParentIterator::getChildren
ParentIterator
PHP Manual

ParentIterator::__construct

(PHP 5 >= 5.1.0)

ParentIterator::__construct — Constructs a ParentIterator

Opis

public ParentIterator::__construct ( RecursiveIterator $iterator )

Constructs a ParentIterator on an iterator.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iterator

The iterator being constructed upon.

Zwracane wartości

The ParentIterator.

ParentIterator::accept
ParentIterator::getChildren
ParentIterator


Return the inner iterator's children contained in a ParentIterator

ParentIterator::__construct
ParentIterator::hasChildren
ParentIterator
PHP Manual

ParentIterator::getChildren

(PHP 5 >= 5.1.0)

ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator

Opis

public ParentIterator ParentIterator::getChildren ( void )

Get the inner iterator's children contained in a ParentIterator.

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 object.

ParentIterator::__construct
ParentIterator::hasChildren
ParentIterator


Check whether the inner iterator's current element has children

ParentIterator::getChildren
ParentIterator::next
ParentIterator
PHP Manual

ParentIterator::hasChildren

(PHP 5 >= 5.1.0)

ParentIterator::hasChildren — Check whether the inner iterator's current element has children

Opis

public bool ParentIterator::hasChildren ( void )

Check whether the inner iterator's current element has children.

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

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ParentIterator::getChildren
ParentIterator::next
ParentIterator


Move the iterator forward

ParentIterator::hasChildren
ParentIterator::rewind
ParentIterator
PHP Manual

ParentIterator::next

(PHP 5 >= 5.1.0)

ParentIterator::next — Move the iterator forward

Opis

public void ParentIterator::next ( void )

Moves the iterator forward.

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

Nie jest zwracana żadna wartość.

ParentIterator::hasChildren
ParentIterator::rewind
ParentIterator


Rewind the iterator

ParentIterator::next
RecursiveArrayIterator
ParentIterator
PHP Manual

ParentIterator::rewind

(PHP 5 >= 5.1.0)

ParentIterator::rewind — Rewind the iterator

Opis

public void ParentIterator::rewind ( void )

Rewinds the iterator.

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

Nie jest zwracana żadna wartość.

ParentIterator::next
RecursiveArrayIterator
ParentIterator


The RecursiveArrayIterator class

(PHP 5 >= 5.1.0)

Wstęp

This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally it is possible to iterate over the current iterator entry.

Krótki opis klasy

RecursiveArrayIterator extends ArrayIterator implements RecursiveIterator {
/* Metody */
public RecursiveArrayIterator getChildren ( void )
public bool hasChildren ( void )
/* Inherits */
public void ArrayIterator::append ( mixed $value )
public void ArrayIterator::asort ( void )
public ArrayIterator::__construct ( mixed $array )
public int ArrayIterator::count ( void )
public mixed ArrayIterator::current ( void )
public array ArrayIterator::getArrayCopy ( void )
public void ArrayIterator::getFlags ( void )
public mixed ArrayIterator::key ( void )
public void ArrayIterator::ksort ( void )
public void ArrayIterator::natcasesort ( void )
public void ArrayIterator::natsort ( void )
public void ArrayIterator::next ( void )
public void ArrayIterator::offsetExists ( string $index )
public mixed ArrayIterator::offsetGet ( string $index )
public void ArrayIterator::offsetSet ( string $index , string $newval )
public void ArrayIterator::offsetUnset ( string $index )
public void ArrayIterator::rewind ( void )
public void ArrayIterator::seek ( int $position )
public string ArrayIterator::serialize ( void )
public void ArrayIterator::setFlags ( string $flags )
public void ArrayIterator::uasort ( string $cmp_function )
public void ArrayIterator::uksort ( string $cmp_function )
public string ArrayIterator::unserialize ( string $serialized )
public bool ArrayIterator::valid ( void )
}

Spis treści

  • RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object.
  • RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object.
ParentIterator::rewind
RecursiveArrayIterator::getChildren
Iteratory


Returns an iterator for the current entry if it is an array or an object.

RecursiveArrayIterator
RecursiveArrayIterator::hasChildren
RecursiveArrayIterator
PHP Manual

RecursiveArrayIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object.

Opis

public RecursiveArrayIterator RecursiveArrayIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An iterator for the current entry, if it is an array or object.

Błędy/Wyjątki

An InvalidArgumentException will be thrown if the current entry does not contain an array or an object.

Przykłady

Przykład #1 RecursiveArrayIterator::getChildren() example

<?php
$fruits = array("a" => "lemon", "b" => "orange", array("a" => "apple", "p" => "pear"));

$iterator = new RecursiveArrayIterator($fruits);

while ($iterator->valid()) {

    if ($iterator->hasChildren()) {
        // print all children
        foreach ($iterator->getChildren() as $key => $value) {
            echo $key . ' : ' . $value . "\n";
        }
    } else {
        echo "No children.\n";
    }

    $iterator->next();
}
?>

Powyższy przykład wyświetli:

No children.
No children.
a : apple
p : pear

Zobacz też:

  • RecursiveArrayIterator::hasChildren() - Returns whether current entry is an array or an object.

RecursiveArrayIterator
RecursiveArrayIterator::hasChildren
RecursiveArrayIterator


Returns whether current entry is an array or an object.

RecursiveArrayIterator::getChildren
RecursiveCachingIterator
RecursiveArrayIterator
PHP Manual

RecursiveArrayIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object.

Opis

public bool RecursiveArrayIterator::hasChildren ( void )

Returns whether current entry is an array or an object for which an iterator can be obtained via RecursiveArrayIterator::getChildren().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the current entry is an array or an object, otherwise FALSE is returned.

Przykłady

Przykład #1 RecursiveArrayIterator::hasChildren() example

<?php
$fruits = array("a" => "lemon", "b" => "orange", array("a" => "apple", "p" => "pear"));

$iterator = new RecursiveArrayIterator($fruits);

while ($iterator->valid()) {

    // Check if there are children
    if ($iterator->hasChildren()) {
        // print all children
        foreach ($iterator->getChildren() as $key => $value) {
            echo $key . ' : ' . $value . "\n";
        }
    } else {
        echo "No children.\n";
    }

    $iterator->next();
}
?>

Powyższy przykład wyświetli:

No children.
No children.
a : apple
p : pear

Zobacz też:

  • RecursiveArrayIterator::getChildren() - Returns an iterator for the current entry if it is an array or an object.

RecursiveArrayIterator::getChildren
RecursiveCachingIterator
RecursiveArrayIterator


The RecursiveCachingIterator class

(PHP 5 >= 5.1.0)

Wstęp

...

Krótki opis klasy

RecursiveCachingIterator extends CachingIterator implements Countable , ArrayAccess , Iterator , Traversable , OuterIterator , RecursiveIterator {
/* Metody */
__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
RecursiveCachingIterator getChildren ( void )
bool hasChildren ( void )
/* Inherits */
public CachingIterator::__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )
public int CachingIterator::count ( void )
public void CachingIterator::current ( void )
public void CachingIterator::getCache ( void )
public void CachingIterator::getFlags ( void )
public void CachingIterator::getInnerIterator ( void )
public void CachingIterator::hasNext ( void )
public void CachingIterator::key ( void )
public void CachingIterator::next ( void )
public void CachingIterator::offsetExists ( string $index )
public void CachingIterator::offsetGet ( string $index )
public void CachingIterator::offsetSet ( string $index , string $newval )
public void CachingIterator::offsetUnset ( string $index )
public void CachingIterator::rewind ( void )
public void CachingIterator::setFlags ( bitmask $flags )
public void CachingIterator::__toString ( void )
public void CachingIterator::valid ( void )
}

Spis treści

  • RecursiveCachingIterator::__construct — Construct
  • RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator
  • RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children
RecursiveArrayIterator::hasChildren
RecursiveCachingIterator::__construct
Iteratory


Construct

RecursiveCachingIterator
RecursiveCachingIterator::getChildren
RecursiveCachingIterator
PHP Manual

RecursiveCachingIterator::__construct

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::__construct — Construct

Opis

RecursiveCachingIterator::__construct ( Iterator $iterator [, string $flags = self::CALL_TOSTRING ] )

Constructs a new RecursiveCachingIterator, which consists of a passed in iterator.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

iterator

The iterator being used.

flags

The flags. Use CALL_TOSTRING to call RecursiveCachingIterator::__toString() for every element (the default), and/or CATCH_GET_CHILD to catch exceptions when trying to get children.

Zwracane wartości

The RecursiveCachingIterator.

Zobacz też:

  • CachingIterator::__construct() - Construct a new CachingIterator object for the iterator.

RecursiveCachingIterator
RecursiveCachingIterator::getChildren
RecursiveCachingIterator


Return the inner iterator's children as a RecursiveCachingIterator

RecursiveCachingIterator::__construct
RecursiveCachingIterator::hasChildren
RecursiveCachingIterator
PHP Manual

RecursiveCachingIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator

Opis

RecursiveCachingIterator RecursiveCachingIterator::getChildren ( 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

The inner iterator's children, as a RecursiveCachingIterator.

RecursiveCachingIterator::__construct
RecursiveCachingIterator::hasChildren
RecursiveCachingIterator


Check whether the current element of the inner iterator has children

RecursiveCachingIterator::getChildren
RecursiveCallbackFilterIterator
RecursiveCachingIterator
PHP Manual

RecursiveCachingIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children

Opis

bool RecursiveCachingIterator::hasChildren ( 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

TRUE if the inner iterator has children, otherwise FALSE

RecursiveCachingIterator::getChildren
RecursiveCallbackFilterIterator
RecursiveCachingIterator


The RecursiveCallbackFilterIterator class

(PHP 5 >= 5.4.0)

Wstęp

Krótki opis klasy

RecursiveCallbackFilterIterator extends CallbackFilterIterator implements OuterIterator , Traversable , Iterator , RecursiveIterator {
/* Metody */
public __construct ( RecursiveIterator $iterator , string $callback )
public RecursiveCallbackFilterIterator getChildren ( void )
public void hasChildren ( void )
/* Metody dziedziczone */
public string CallbackFilterIterator::accept ( void )
}

Przykłady

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Przykład #1 Available callback arguments

<?php

/**
 * Callback for RecursiveCallbackFilterIterator
 *
 * @param $current   Current item's value
 * @param $key       Current item's key
 * @param $iterator  Iterator being filtered
 * @return boolean   TRUE to accept the current item, FALSE otherwise
 */
function my_callback($current, $key, $iterator) {
    // Your filtering code here
}

?>

Filtering a recursive iterator generally involves two conditions. The first is that, to allow recursion, the callback function should return TRUE if the current iterator item has children. The second is the normal filter condition, such as a file size or extension check as in the example below.

Przykład #2 Recursive callback basic example

<?php

$dir = new FilesystemIterator(__DIR__);

// Filter large files ( > 100MB)
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
    // Allow recursion
    if ($iterator->hasChildren()) {
        return TRUE;
    }
    // Check for large file
    if ($current->isFile() && $current->getSize() > 104857600) {
        return TRUE;
    }
    return FALSE;
});

foreach (new RecursiveIteratorIterator($files) as $file) {
    echo $file->getPathname() . PHP_EOL;
}

?>

Spis treści

  • RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
  • RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children
RecursiveCachingIterator::hasChildren
RecursiveCallbackFilterIterator::__construct
Iteratory


Create a RecursiveCallbackFilterIterator from a RecursiveIterator

RecursiveCallbackFilterIterator
RecursiveCallbackFilterIterator::getChildren
RecursiveCallbackFilterIterator
PHP Manual

RecursiveCallbackFilterIterator::__construct

(PHP 5 >= 5.4.0)

RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator

Opis

public RecursiveCallbackFilterIterator::__construct() ( RecursiveIterator $iterator , string $callback )

Creates a filtered iterator from a RecursiveIterator using the callback to determine which items are accepted or rejected.

Parametry

iterator

The recursive iterator to be filtered.

callback

The callback, which should return TRUE to accept the current item or FALSE otherwise. See Examples.

May be any valid callback value.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
  • RecursiveCallbackFilteriterator::hasChildren() - Check whether the inner iterator's current element has children

RecursiveCallbackFilterIterator
RecursiveCallbackFilterIterator::getChildren
RecursiveCallbackFilterIterator


Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

RecursiveCallbackFilterIterator::__construct
RecursiveCallbackFilterIterator::hasChildren
RecursiveCallbackFilterIterator
PHP Manual

RecursiveCallbackFilterIterator::getChildren

(PHP 5 >= 5.4.0)

RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

Opis

public RecursiveCallbackFilterIterator RecursiveCallbackFilterIterator::getChildren ( void )

Fetches the filtered children of the inner iterator.

RecursiveCallbackFilterIterator::hasChildren() should be used to determine if there are children to be fetched.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a RecursiveCallbackFilterIterator containing the children.

Zobacz też:

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::__construct() - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilteriterator::hasChildren() - Check whether the inner iterator's current element has children

RecursiveCallbackFilterIterator::__construct
RecursiveCallbackFilterIterator::hasChildren
RecursiveCallbackFilterIterator


Check whether the inner iterator's current element has children

RecursiveCallbackFilterIterator::getChildren
RecursiveDirectoryIterator
RecursiveCallbackFilterIterator
PHP Manual

RecursiveCallbackFilterIterator::hasChildren

(PHP 5 >= 5.4.0)

RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Opis

public void RecursiveCallbackFilterIterator::hasChildren ( void )

Returns TRUE if the current element has children, FALSE otherwise.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the current element has children, FALSE otherwise.

Przykłady

Przykład #1 RecursiveCallbackFilterIterator::hasChildren() basic usage

<?php

$dir = new FilesystemIterator(__DIR__);

// Recursively iterate over XML files
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
    // Allow recursion into directories
    if ($iterator->hasChildren()) {
        return TRUE;
    }
    // Check for XML file
    if (!strcasecmp($current->getExtension(), 'xml')) {
        return TRUE;
    }
    return FALSE;
});

?>

Zobacz też:

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::__construct() - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilteriterator::getChildren() - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

RecursiveCallbackFilterIterator::getChildren
RecursiveDirectoryIterator
RecursiveCallbackFilterIterator


The RecursiveDirectoryIterator class

(PHP 5)

Wstęp

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

Krótki opis klasy

RecursiveDirectoryIterator extends FilesystemIterator implements Traversable , Iterator , SeekableIterator , RecursiveIterator {
/* Metody */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )
public mixed getChildren ( void )
public string getSubPath ( void )
public string getSubPathname ( void )
public bool hasChildren ([ bool $allow_links ] )
public string key ( void )
public void next ( void )
public void rewind ( void )
/* Inherits */
public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public mixed FilesystemIterator::current ( void )
public int FilesystemIterator::getFlags ( void )
public string FilesystemIterator::key ( void )
public void FilesystemIterator::next ( void )
public void FilesystemIterator::rewind ( void )
public void FilesystemIterator::setFlags ([ int $flags ] )
}

Rejestr zmian

Wersja | Opis
5.3.0 | The FilesystemIterator was introduced as the parent class. Previously, the parent was the DirectoryIterator.
5.3.0 | Implements SeekableIterator.
5.2.11, 5.3.1 | Added RecursiveDirectoryIterator::FOLLOW_SYMLINKS

Spis treści

  • RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator
  • RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory
  • RecursiveDirectoryIterator::getSubPath — Get sub path
  • RecursiveDirectoryIterator::getSubPathname — Get sub path and name
  • RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'
  • RecursiveDirectoryIterator::key — Return path and filename of current dir entry
  • RecursiveDirectoryIterator::next — Move to next entry
  • RecursiveDirectoryIterator::rewind — Rewind dir back to the start
RecursiveCallbackFilterIterator::hasChildren
RecursiveDirectoryIterator::__construct
Iteratory


Constructs a RecursiveDirectoryIterator

RecursiveDirectoryIterator
RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::__construct

(PHP 5 >= 5.1.2)

RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator

Opis

public RecursiveDirectoryIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )

Constructs a RecursiveDirectoryIterator() for the provided path.

Parametry

path

The path of the directory to be iterated over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under FilesystemIterator predefined constants. They can also be set later with FilesystemIterator::setFlags().

Zwracane wartości

Returns the newly created RecursiveDirectoryIterator.

Błędy/Wyjątki

Throws an UnexpectedValueException if the path cannot be found or is not a directory.

Przykłady

Przykład #1 RecursiveDirectoryIterator example

<?php

$directory = '/tmp';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

while($it->valid()) {

    if (!$it->isDot()) {
        echo 'SubPathName: ' . $it->getSubPathName() . "\n";
        echo 'SubPath:     ' . $it->getSubPath() . "\n";
        echo 'Key:         ' . $it->key() . "\n\n";
    }

    $it->next();
}

?>

Powyższy przykład wyświetli coś podobnego do:

SubPathName: fruit/apple.xml
SubPath:     fruit
Key:         /tmp/fruit/apple.xml

SubPathName: stuff.xml
SubPath:
Key:         /tmp/stuff.xml

SubPathName: veggies/carrot.xml
SubPath:     veggies
Key:         /tmp/veggies/carrot.xml

Zobacz też:

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • RecursiveIteratorIterator::__construct() - Construct a RecursiveIteratorIterator
  • FilesystemIterator predefined constants

RecursiveDirectoryIterator
RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator


Returns an iterator for the current entry if it is a directory

RecursiveDirectoryIterator::__construct
RecursiveDirectoryIterator::getSubPath
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory

Opis

public mixed RecursiveDirectoryIterator::getChildren ( 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

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.

RecursiveDirectoryIterator::__construct
RecursiveDirectoryIterator::getSubPath
RecursiveDirectoryIterator


Get sub path

RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator::getSubPathname
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::getSubPath

(PHP 5 >= 5.1.0)

RecursiveDirectoryIterator::getSubPath — Get sub path

Opis

public string RecursiveDirectoryIterator::getSubPath ( void )

Gets the sub path.

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 sub path (sub directory).

Zobacz też:

  • RecursiveDirectoryIterator::getSubPathName() - Get sub path and name
  • RecursiveDirectoryIterator::key() - Return path and filename of current dir entry

RecursiveDirectoryIterator::getChildren
RecursiveDirectoryIterator::getSubPathname
RecursiveDirectoryIterator


Get sub path and name

RecursiveDirectoryIterator::getSubPath
RecursiveDirectoryIterator::hasChildren
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::getSubPathname

(PHP 5 >= 5.1.0)

RecursiveDirectoryIterator::getSubPathname — Get sub path and name

Opis

public string RecursiveDirectoryIterator::getSubPathname ( void )

Gets the sub path and filename.

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 sub path (sub directory) and filename.

Zobacz też:

  • RecursiveDirectoryIterator::getSubPath() - Get sub path
  • RecursiveDirectoryIterator::key() - Return path and filename of current dir entry

RecursiveDirectoryIterator::getSubPath
RecursiveDirectoryIterator::hasChildren
RecursiveDirectoryIterator


Returns whether current entry is a directory and not '.' or '..'

RecursiveDirectoryIterator::getSubPathname
RecursiveDirectoryIterator::key
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::hasChildren

(PHP 5)

RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'

Opis

public bool RecursiveDirectoryIterator::hasChildren ([ bool $allow_links ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

allow_links

Zwracane wartości

Returns whether the current entry is a directory, but not '.' or '..'

RecursiveDirectoryIterator::getSubPathname
RecursiveDirectoryIterator::key
RecursiveDirectoryIterator


Return path and filename of current dir entry

RecursiveDirectoryIterator::hasChildren
RecursiveDirectoryIterator::next
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::key

(PHP 5)

RecursiveDirectoryIterator::key — Return path and filename of current dir entry

Opis

public string RecursiveDirectoryIterator::key ( 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

The path and filename of the current dir entry.

RecursiveDirectoryIterator::hasChildren
RecursiveDirectoryIterator::next
RecursiveDirectoryIterator


Move to next entry

RecursiveDirectoryIterator::key
RecursiveDirectoryIterator::rewind
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::next

(PHP 5)

RecursiveDirectoryIterator::next — Move to next entry

Opis

public void RecursiveDirectoryIterator::next ( 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

Nie jest zwracana żadna wartość.

RecursiveDirectoryIterator::key
RecursiveDirectoryIterator::rewind
RecursiveDirectoryIterator


Rewind dir back to the start

RecursiveDirectoryIterator::next
RecursiveFilterIterator
RecursiveDirectoryIterator
PHP Manual

RecursiveDirectoryIterator::rewind

(PHP 5)

RecursiveDirectoryIterator::rewind — Rewind dir back to the start

Opis

public void RecursiveDirectoryIterator::rewind ( 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

Nie jest zwracana żadna wartość.

RecursiveDirectoryIterator::next
RecursiveFilterIterator
RecursiveDirectoryIterator


The RecursiveFilterIterator class

(PHP 5 >= 5.1.0)

Wstęp

This abstract iterator filters out unwanted values for a RecursiveIterator. This class should be extended to implement custom filters. The RecursiveFilterIterator::accept() must be implemented in the subclass.

Krótki opis klasy

RecursiveFilterIterator extends FilterIterator implements Iterator , Traversable , OuterIterator , RecursiveIterator {
/* Metody */
public __construct ( RecursiveIterator $iterator )
public void getChildren ( void )
public void hasChildren ( void )
/* Metody dziedziczone */
abstract bool FilterIterator::accept ( void )
FilterIterator::__construct ( Iterator $iterator )
mixed FilterIterator::current ( void )
Iterator FilterIterator::getInnerIterator ( void )
mixed FilterIterator::key ( void )
void FilterIterator::next ( void )
void FilterIterator::rewind ( void )
bool FilterIterator::valid ( void )
}

Spis treści

  • RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator
  • RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children
RecursiveDirectoryIterator::rewind
RecursiveFilterIterator::__construct
Iteratory


Create a RecursiveFilterIterator from a RecursiveIterator

RecursiveFilterIterator
RecursiveFilterIterator::getChildren
RecursiveFilterIterator
PHP Manual

RecursiveFilterIterator::__construct

(PHP 5 >= 5.1.0)

RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator

Opis

public RecursiveFilterIterator::__construct ( RecursiveIterator $iterator )

Create a RecursiveFilterIterator from a RecursiveIterator.

Parametry

iterator

The RecursiveIterator to be filtered.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Basic RecursiveFilterIterator() example

<?php
class TestsOnlyFilter extends RecursiveFilterIterator {
    public function accept() {
        // Accept the current item if we can recurse into it
        // or it is a value starting with "test"
        return $this->hasChildren() || (strpos($this->current(), "test") !== FALSE);
    }
}

$arrary   = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter   = new TestsOnlyFilter($iterator);

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

test1
test3
test4
test5

Przykład #2 RecursiveFilterIterator() example

<?php
class StartsWithFilter extends RecursiveFilterIterator {

    protected $word;

    public function __construct(RecursiveIterator $rit, $word) {
        $this->word = $word;
        parent::__construct($rit);
    }

    public function accept() {
        return $this->hasChildren() OR strpos($this->current(), $this->word) === 0;
    }

    public function getChildren() {
        return new self($this->getInnerIterator()->getChildren(), $this->word);
    }
}

$array    = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter   = new StartsWithFilter($iterator, "test");

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

test1
test3
test4
test5

Zobacz też:

  • RecursiveFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveFilterIterator::hasChildren() - Check whether the inner iterator's current element has children
  • FilterIterator::accept() - Check whether the current element of the iterator is acceptable

RecursiveFilterIterator
RecursiveFilterIterator::getChildren
RecursiveFilterIterator


Return the inner iterator's children contained in a RecursiveFilterIterator

RecursiveFilterIterator::__construct
RecursiveFilterIterator::hasChildren
RecursiveFilterIterator
PHP Manual

RecursiveFilterIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator

Opis

public void RecursiveFilterIterator::getChildren ( void )

Return the inner iterator's children contained in a RecursiveFilterIterator.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a RecursiveFilterIterator containing the inner iterator's children.

Zobacz też:

  • RecursiveFilterIterator::hasChildren() - Check whether the inner iterator's current element has children
  • RecursiveIterator::getChildren() - Returns an iterator for the current entry.

RecursiveFilterIterator::__construct
RecursiveFilterIterator::hasChildren
RecursiveFilterIterator


Check whether the inner iterator's current element has children

RecursiveFilterIterator::getChildren
RecursiveIteratorIterator
RecursiveFilterIterator
PHP Manual

RecursiveFilterIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Opis

public void RecursiveFilterIterator::hasChildren ( void )

Check whether the inner iterator's current element has children.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the inner iterator has children, otherwise FALSE

Zobacz też:

  • RecursiveFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveIterator::hasChildren() - Returns if an iterator can be created fot the current entry.

RecursiveFilterIterator::getChildren
RecursiveIteratorIterator
RecursiveFilterIterator


The RecursiveIteratorIterator class

(PHP 5)

Wstęp

Can be used to iterate through recursive iterators.

Krótki opis klasy

RecursiveIteratorIterator implements OuterIterator , Traversable , Iterator {
/* Metody */
public void beginChildren ( void )
public void beginIteration ( void )
public RecursiveIterator callGetChildren ( void )
public bool callHasChildren ( void )
public __construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )
public mixed current ( void )
public void endChildren ( void )
public void endIteration ( void )
public int getDepth ( void )
public iterator getInnerIterator ( void )
public mixed getMaxDepth ( void )
public RecursiveIterator getSubIterator ( void )
public mixed key ( void )
public void next ( void )
public void nextElement ( void )
public void rewind ( void )
public void setMaxDepth ([ string $max_depth = -1 ] )
public bool valid ( void )
/* Metody dziedziczone */
public Iterator OuterIterator::getInnerIterator ( void )
}

Spis treści

  • RecursiveIteratorIterator::beginChildren — Begin children
  • RecursiveIteratorIterator::beginIteration — Begin Iteration
  • RecursiveIteratorIterator::callGetChildren — Get children
  • RecursiveIteratorIterator::callHasChildren — Has children
  • RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator
  • RecursiveIteratorIterator::current — Access the current element value
  • RecursiveIteratorIterator::endChildren — End children
  • RecursiveIteratorIterator::endIteration — End Iteration
  • RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration
  • RecursiveIteratorIterator::getInnerIterator — Get inner iterator
  • RecursiveIteratorIterator::getMaxDepth — Get max depth
  • RecursiveIteratorIterator::getSubIterator — The current active sub iterator
  • RecursiveIteratorIterator::key — Access the current key
  • RecursiveIteratorIterator::next — Move forward to the next element
  • RecursiveIteratorIterator::nextElement — Next element
  • RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator
  • RecursiveIteratorIterator::setMaxDepth — Set max depth
  • RecursiveIteratorIterator::valid — Check whether the current position is valid
RecursiveFilterIterator::hasChildren
RecursiveIteratorIterator::beginChildren
Iteratory


Begin children

RecursiveIteratorIterator
RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::beginChildren

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::beginChildren — Begin children

Opis

public void RecursiveIteratorIterator::beginChildren ( void )

Is called after calling RecursiveIteratorIterator::getChildren(), and its associated RecursiveIteratorIterator::rewind().

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

Nie jest zwracana żadna wartość.

RecursiveIteratorIterator
RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator


Begin Iteration

RecursiveIteratorIterator::beginChildren
RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::beginIteration

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::beginIteration — Begin Iteration

Opis

public void RecursiveIteratorIterator::beginIteration ( void )

Called when iteration begins (after the first RecursiveIteratorIterator::rewind() call.

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

Nie jest zwracana żadna wartość.

RecursiveIteratorIterator::beginChildren
RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator


Get children

RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::callGetChildren

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::callGetChildren — Get children

Opis

public RecursiveIterator RecursiveIteratorIterator::callGetChildren ( void )

Get children of the current element.

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

A RecursiveIterator().

RecursiveIteratorIterator::beginIteration
RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator


Has children

RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator::__construct
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::callHasChildren

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::callHasChildren — Has children

Opis

public bool RecursiveIteratorIterator::callHasChildren ( void )

Called for each element to test whether it has children.

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

TRUE if the element has children, otherwise FALSE

RecursiveIteratorIterator::callGetChildren
RecursiveIteratorIterator::__construct
RecursiveIteratorIterator


Construct a RecursiveIteratorIterator

RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator::current
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::__construct

(PHP 5 >= 5.1.3)

RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator

Opis

public RecursiveIteratorIterator::__construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )

Creates a RecursiveIteratorIterator from a RecursiveIterator.

Parametry

iterator

The iterator being constructed from. Either a RecursiveIterator or IteratorAggregate.

mode

Optional mode. Possible values are

  • RecursiveIteratorIterator::LEAVES_ONLY - The default. Lists only leaves in iteration.
  • RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.
  • RecursiveIteratorIterator::CHILD_FIRST - Lists leaves and parents in iteration with leaves coming first.

flags

Optional flag. Possible values are RecursiveIteratorIterator::CATCH_GET_CHILD which will then ignore exceptions thrown in calls to RecursiveIteratorIterator::getChildren().

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Iterating a RecursiveIteratorIterator

<?php
$array = array(
    array(
        array(
            array(
                'leaf-0-0-0-0',
                'leaf-0-0-0-1'
            ),
            'leaf-0-0-0'
        ),
        array(
            array(
                'leaf-0-1-0-0',
                'leaf-0-1-0-1'
            ),
            'leaf-0-1-0'
        ),
        'leaf-0-0'
    )
);

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($array),
    $mode
);
foreach ($iterator as $key => $leaf) {
    echo "$key => $leaf", PHP_EOL;
}
?>

Output with $mode = RecursiveIteratorIterator::LEAVES_ONLY

0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
0 => leaf-0-0-0
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
0 => leaf-0-1-0
0 => leaf-0-0

Output with $mode = RecursiveIteratorIterator::SELF_FIRST

0 => Array
0 => Array
0 => Array
0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
1 => leaf-0-0-0
1 => Array
0 => Array
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
1 => leaf-0-1-0
2 => leaf-0-0

Output with $mode = RecursiveIteratorIterator::CHILD_FIRST

0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
0 => Array
1 => leaf-0-0-0
0 => Array
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
0 => Array
1 => leaf-0-1-0
1 => Array
2 => leaf-0-0
0 => Array

RecursiveIteratorIterator::callHasChildren
RecursiveIteratorIterator::current
RecursiveIteratorIterator


Access the current element value

RecursiveIteratorIterator::__construct
RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::current

(PHP 5)

RecursiveIteratorIterator::current — Access the current element value

Opis

public mixed RecursiveIteratorIterator::current ( 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

The current elements value.

RecursiveIteratorIterator::__construct
RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator


End children

RecursiveIteratorIterator::current
RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::endChildren

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::endChildren — End children

Opis

public void RecursiveIteratorIterator::endChildren ( void )

Called when end recursing one level.

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

Nie jest zwracana żadna wartość.

RecursiveIteratorIterator::current
RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator


End Iteration

RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::endIteration

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::endIteration — End Iteration

Opis

public void RecursiveIteratorIterator::endIteration ( void )

Called when the iteration ends (when RecursiveIteratorIterator::valid() first returns FALSE.

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

Nie jest zwracana żadna wartość.

RecursiveIteratorIterator::endChildren
RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator


Get the current depth of the recursive iteration

RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::getDepth

(PHP 5)

RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration

Opis

public int RecursiveIteratorIterator::getDepth ( 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

The current depth of the recursive iteration.

RecursiveIteratorIterator::endIteration
RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator


Get inner iterator

RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator::getMaxDepth
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::getInnerIterator

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::getInnerIterator — Get inner iterator

Opis

public iterator RecursiveIteratorIterator::getInnerIterator ( void )

Gets the current active sub iterator.

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 current active sub iterator.

RecursiveIteratorIterator::getDepth
RecursiveIteratorIterator::getMaxDepth
RecursiveIteratorIterator


Get max depth

RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator::getSubIterator
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::getMaxDepth

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::getMaxDepth — Get max depth

Opis

public mixed RecursiveIteratorIterator::getMaxDepth ( void )

Gets the maximum allowable depth.

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 maximum accepted depth, or FALSE if any depth is allowed.

Zobacz też:

  • RecursiveIteratorIterator::setMaxDepth() - Set max depth

RecursiveIteratorIterator::getInnerIterator
RecursiveIteratorIterator::getSubIterator
RecursiveIteratorIterator


The current active sub iterator

RecursiveIteratorIterator::getMaxDepth
RecursiveIteratorIterator::key
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::getSubIterator

(PHP 5)

RecursiveIteratorIterator::getSubIterator — The current active sub iterator

Opis

public RecursiveIterator RecursiveIteratorIterator::getSubIterator ( 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

The current active sub iterator.

RecursiveIteratorIterator::getMaxDepth
RecursiveIteratorIterator::key
RecursiveIteratorIterator


Access the current key

RecursiveIteratorIterator::getSubIterator
RecursiveIteratorIterator::next
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::key

(PHP 5)

RecursiveIteratorIterator::key — Access the current key

Opis

public mixed RecursiveIteratorIterator::key ( 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

The current key.

RecursiveIteratorIterator::getSubIterator
RecursiveIteratorIterator::next
RecursiveIteratorIterator


Move forward to the next element

RecursiveIteratorIterator::key
RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::next

(PHP 5)

RecursiveIteratorIterator::next — Move forward to the next element

Opis

public void RecursiveIteratorIterator::next ( 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

Nie jest zwracana żadna wartość.

RecursiveIteratorIterator::key
RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator


Next element

RecursiveIteratorIterator::next
RecursiveIteratorIterator::rewind
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::nextElement

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::nextElement — Next element

Opis

public void RecursiveIteratorIterator::nextElement ( void )

Called when the next element is available.

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

Nie jest zwracana żadna wartość.

RecursiveIteratorIterator::next
RecursiveIteratorIterator::rewind
RecursiveIteratorIterator


Rewind the iterator to the first element of the top level inner iterator

RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator::setMaxDepth
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::rewind

(PHP 5)

RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator

Opis

public void RecursiveIteratorIterator::rewind ( 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

Nie jest zwracana żadna wartość.

RecursiveIteratorIterator::nextElement
RecursiveIteratorIterator::setMaxDepth
RecursiveIteratorIterator


Set max depth

RecursiveIteratorIterator::rewind
RecursiveIteratorIterator::valid
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::setMaxDepth

(PHP 5 >= 5.1.0)

RecursiveIteratorIterator::setMaxDepth — Set max depth

Opis

public void RecursiveIteratorIterator::setMaxDepth ([ string $max_depth = -1 ] )

Set the maximum allowed depth.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

max_depth

The maximum allowed depth. -1 is used for any depth.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Emits an Exception if max_depth is less than -1.

RecursiveIteratorIterator::rewind
RecursiveIteratorIterator::valid
RecursiveIteratorIterator


Check whether the current position is valid

RecursiveIteratorIterator::setMaxDepth
RecursiveRegexIterator
RecursiveIteratorIterator
PHP Manual

RecursiveIteratorIterator::valid

(PHP 5)

RecursiveIteratorIterator::valid — Check whether the current position is valid

Opis

public bool RecursiveIteratorIterator::valid ( 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

TRUE if the current position is valid, otherwise FALSE

RecursiveIteratorIterator::setMaxDepth
RecursiveRegexIterator
RecursiveIteratorIterator


The RecursiveRegexIterator class

(PHP 5 >= 5.2.0)

Wstęp

This recursive iterator can filter another recursive iterator via a regular expression.

Krótki opis klasy

RecursiveRegexIterator extends RegexIterator implements RecursiveIterator {
/* Metody */
public __construct ( RecursiveIterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )
public RecursiveRegexIterator getChildren ( void )
public bool hasChildren ( void )
/* Metody dziedziczone */
public RecursiveIterator RecursiveIterator::getChildren ( void )
public bool RecursiveIterator::hasChildren ( void )
public bool RegexIterator::accept ( void )
public int RegexIterator::getFlags ( void )
public int RegexIterator::getMode ( void )
public int RegexIterator::getPregFlags ( void )
public string RegexIterator::getRegex ( void )
public void RegexIterator::setFlags ( int $flags )
public void RegexIterator::setMode ( int $mode )
public void RegexIterator::setPregFlags ( int $preg_flags )
}

Spis treści

  • RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator.
  • RecursiveRegexIterator::getChildren — Returns an iterator for the current entry.
  • RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry.
RecursiveIteratorIterator::valid
RecursiveRegexIterator::__construct
Iteratory


Creates a new RecursiveRegexIterator.

RecursiveRegexIterator
RecursiveRegexIterator::getChildren
RecursiveRegexIterator
PHP Manual

RecursiveRegexIterator::__construct

(PHP 5 >= 5.2.0)

RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator.

Opis

public RecursiveRegexIterator::__construct() ( RecursiveIterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )

Creates a new regular expression iterator.

Parametry

iterator

The recursive iterator to apply this regex filter to.

regex

The regular expression to match.

mode

Operation mode, see RegexIterator::setMode() for a list of modes.

flags

Special flags, see RegexIterator::setFlags() for a list of available flags.

preg_flags

The regular expression flags. These flags depend on the operation mode parameter:

RegexIterator preg_flags
operation mode | available flags
RecursiveRegexIterator::ALL_MATCHES | See preg_match_all().
RecursiveRegexIterator::GET_MATCH | See preg_match().
RecursiveRegexIterator::MATCH | See preg_match().
RecursiveRegexIterator::REPLACE | none.
RecursiveRegexIterator::SPLIT | See preg_split().

Przykłady

Przykład #1 RecursiveRegexIterator::__construct() example

Creates a new RegexIterator that filters all strings that start with 'test'.

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $key1 => $value1) {

    if ($rRegexIterator->hasChildren()) {

        // print all children
        echo "Children: ";
        foreach ($rRegexIterator->getChildren() as $key => $value) {
            echo $value . " ";
        }
        echo "\n";
    } else {
        echo "No children\n";
    }

}
?>

Powyższy przykład wyświetli coś podobnego do:

No children
Children: test4 test5

Zobacz też:

  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression

RecursiveRegexIterator
RecursiveRegexIterator::getChildren
RecursiveRegexIterator


Returns an iterator for the current entry.

RecursiveRegexIterator::__construct
RecursiveRegexIterator::hasChildren
RecursiveRegexIterator
PHP Manual

RecursiveRegexIterator::getChildren

(PHP 5 >= 5.2.0)

RecursiveRegexIterator::getChildren — Returns an iterator for the current entry.

Opis

public RecursiveRegexIterator RecursiveRegexIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An iterator for the current entry, if it can be iterated over by the inner iterator.

Błędy/Wyjątki

An InvalidArgumentException will be thrown if the current entry does not contain a value that can be iterated over by the inner iterator.

Przykłady

Przykład #1 RecursiveRegexIterator::getChildren() example

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $key1 => $value1) {

    if ($rRegexIterator->hasChildren()) {

        // print all children
        echo "Children: ";
        foreach ($rRegexIterator->getChildren() as $key => $value) {
            echo $value . " ";
        }
        echo "\n";
    } else {
        echo "No children\n";
    }

}
?>

Powyższy przykład wyświetli:

No children
Children: test4 test5

Zobacz też:

  • RecursiveRegexIterator::hasChildren() - Returns whether an iterator can be obtained for the current entry.

RecursiveRegexIterator::__construct
RecursiveRegexIterator::hasChildren
RecursiveRegexIterator


Returns whether an iterator can be obtained for the current entry.

RecursiveRegexIterator::getChildren
RecursiveTreeIterator
RecursiveRegexIterator
PHP Manual

RecursiveRegexIterator::hasChildren

(PHP 5 >= 5.2.0)

RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry.

Opis

public bool RecursiveRegexIterator::hasChildren ( void )

Returns whether an iterator can be obtained for the current entry. This iterator can be obtained via RecursiveRegexIterator::getChildren().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if an iterator can be obtained for the current entry, otherwise returns FALSE.

Przykłady

Przykład #1 RecursiveRegexIterator::hasChildren() example

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $value) {
    var_dump($rRegexIterator->hasChildren());
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:

  • RecursiveRegexIterator::getChildren() - Returns an iterator for the current entry.

RecursiveRegexIterator::getChildren
RecursiveTreeIterator
RecursiveRegexIterator


The RecursiveTreeIterator class

(PHP 5 >= 5.3.0)

Wstęp

Allows iterating over a RecursiveIterator to generate an ASCII graphic tree.

Krótki opis klasy

RecursiveTreeIterator extends RecursiveIteratorIterator implements OuterIterator , Traversable , Iterator {
/* Stałe */
const integer BYPASS_CURRENT = 4 ;
const integer BYPASS_KEY = 8 ;
const integer PREFIX_LEFT = 0 ;
const integer PREFIX_MID_HAS_NEXT = 1 ;
const integer PREFIX_MID_LAST = 2 ;
const integer PREFIX_END_HAS_NEXT = 3 ;
const integer PREFIX_END_LAST = 4 ;
const integer PREFIX_RIGHT = 5 ;
/* Metody */
public void beginChildren ( void )
public RecursiveIterator beginIteration ( void )
public RecursiveIterator callGetChildren ( void )
public bool callHasChildren ( void )
public __construct ( RecursiveIterator|IteratorAggregate $it [, int $flags = RecursiveTreeIterator::BYPASS_KEY [, int $cit_flags = CachingIterator::CATCH_GET_CHILD [, int $mode = RecursiveIteratorIterator::SELF_FIRST ]]] )
public string current ( void )
public void endChildren ( void )
public void endIteration ( void )
public string getEntry ( void )
public void getPostfix ( void )
public string getPrefix ( void )
public string key ( void )
public void next ( void )
public void nextElement ( void )
public void rewind ( void )
public void setPrefixPart ( int $part , string $value )
public bool valid ( void )
/* Metody dziedziczone */
public void RecursiveIteratorIterator::beginChildren ( void )
public void RecursiveIteratorIterator::beginIteration ( void )
public RecursiveIterator RecursiveIteratorIterator::callGetChildren ( void )
public bool RecursiveIteratorIterator::callHasChildren ( void )
public RecursiveIteratorIterator::__construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )
public mixed RecursiveIteratorIterator::current ( void )
public void RecursiveIteratorIterator::endChildren ( void )
public void RecursiveIteratorIterator::endIteration ( void )
public int RecursiveIteratorIterator::getDepth ( void )
public iterator RecursiveIteratorIterator::getInnerIterator ( void )
public mixed RecursiveIteratorIterator::getMaxDepth ( void )
public RecursiveIterator RecursiveIteratorIterator::getSubIterator ( void )
public mixed RecursiveIteratorIterator::key ( void )
public void RecursiveIteratorIterator::next ( void )
public void RecursiveIteratorIterator::nextElement ( void )
public void RecursiveIteratorIterator::rewind ( void )
public void RecursiveIteratorIterator::setMaxDepth ([ string $max_depth = -1 ] )
public bool RecursiveIteratorIterator::valid ( void )
}

Stałe predefiniowane

RecursiveTreeIterator::BYPASS_CURRENT

RecursiveTreeIterator::BYPASS_KEY

RecursiveTreeIterator::PREFIX_LEFT

RecursiveTreeIterator::PREFIX_MID_HAS_NEXT

RecursiveTreeIterator::PREFIX_MID_LAST

RecursiveTreeIterator::PREFIX_END_HAS_NEXT

RecursiveTreeIterator::PREFIX_END_LAST

RecursiveTreeIterator::PREFIX_RIGHT

Spis treści

  • RecursiveTreeIterator::beginChildren — Begin children
  • RecursiveTreeIterator::beginIteration — Begin iteration
  • RecursiveTreeIterator::callGetChildren — Get children
  • RecursiveTreeIterator::callHasChildren — Has children
  • RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator
  • RecursiveTreeIterator::current — Get current element
  • RecursiveTreeIterator::endChildren — End children
  • RecursiveTreeIterator::endIteration — End iteration
  • RecursiveTreeIterator::getEntry — Get current entry
  • RecursiveTreeIterator::getPostfix — Get the postfix
  • RecursiveTreeIterator::getPrefix — Get the prefix
  • RecursiveTreeIterator::key — Get the key of the current element
  • RecursiveTreeIterator::next — Move to next element
  • RecursiveTreeIterator::nextElement — Next element
  • RecursiveTreeIterator::rewind — Rewind iterator
  • RecursiveTreeIterator::setPrefixPart — Set a part of the prefix
  • RecursiveTreeIterator::valid — Check validity
RecursiveRegexIterator::hasChildren
RecursiveTreeIterator::beginChildren
Iteratory


Begin children

RecursiveTreeIterator
RecursiveTreeIterator::beginIteration
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::beginChildren

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::beginChildren — Begin children

Opis

public void RecursiveTreeIterator::beginChildren ( void )

Called when recursing one level down.

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

Nie jest zwracana żadna wartość.

RecursiveTreeIterator
RecursiveTreeIterator::beginIteration
RecursiveTreeIterator


Begin iteration

RecursiveTreeIterator::beginChildren
RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::beginIteration

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::beginIteration — Begin iteration

Opis

public RecursiveIterator RecursiveTreeIterator::beginIteration ( void )

Called when iteration begins (after the first RecursiveTreeIterator::rewind() call).

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

A RecursiveIterator.

RecursiveTreeIterator::beginChildren
RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator


Get children

RecursiveTreeIterator::beginIteration
RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::callGetChildren

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::callGetChildren — Get children

Opis

public RecursiveIterator RecursiveTreeIterator::callGetChildren ( void )

Gets children of the current element.

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

A RecursiveIterator.

RecursiveTreeIterator::beginIteration
RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator


Has children

RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator::__construct
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::callHasChildren

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::callHasChildren — Has children

Opis

public bool RecursiveTreeIterator::callHasChildren ( void )

Called for each element to test whether it has children.

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

TRUE if there are children, otherwise FALSE

RecursiveTreeIterator::callGetChildren
RecursiveTreeIterator::__construct
RecursiveTreeIterator


Construct a RecursiveTreeIterator

RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator::current
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::__construct

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator

Opis

 public  RecursiveTreeIterator::__construct
  ( RecursiveIterator|IteratorAggregate $it
 [, int $flags = RecursiveTreeIterator::BYPASS_KEY
 [, int $cit_flags = CachingIterator::CATCH_GET_CHILD
 [, int $mode = RecursiveIteratorIterator::SELF_FIRST
]]] )

Constructs a new RecursiveTreeIterator from the supplied recursive iterator.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

it

The RecursiveIterator or IteratorAggregate to iterate over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under RecursiveTreeIterator predefined constants.

caching_it_flags

Flags to affect the behavior of the RecursiveCachingIterator used internally.

mode

Flags to affect the behavior of the RecursiveIteratorIterator used internally.

Zwracane wartości

Nie jest zwracana żadna wartość.

RecursiveTreeIterator::callHasChildren
RecursiveTreeIterator::current
RecursiveTreeIterator


Get current element

RecursiveTreeIterator::__construct
RecursiveTreeIterator::endChildren
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::current

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::current — Get current element

Opis

public string RecursiveTreeIterator::current ( void )

Gets the current element prefixed and postfixed.

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

Returns the current element prefixed and postfixed.

RecursiveTreeIterator::__construct
RecursiveTreeIterator::endChildren
RecursiveTreeIterator


End children

RecursiveTreeIterator::current
RecursiveTreeIterator::endIteration
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::endChildren

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::endChildren — End children

Opis

public void RecursiveTreeIterator::endChildren ( void )

Called when end recursing one level.

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

Nie jest zwracana żadna wartość.

RecursiveTreeIterator::current
RecursiveTreeIterator::endIteration
RecursiveTreeIterator


End iteration

RecursiveTreeIterator::endChildren
RecursiveTreeIterator::getEntry
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::endIteration

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::endIteration — End iteration

Opis

public void RecursiveTreeIterator::endIteration ( void )

Called when the iteration ends (when RecursiveTreeIterator::valid() first returns FALSE)

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

Nie jest zwracana żadna wartość.

RecursiveTreeIterator::endChildren
RecursiveTreeIterator::getEntry
RecursiveTreeIterator


Get current entry

RecursiveTreeIterator::endIteration
RecursiveTreeIterator::getPostfix
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::getEntry

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::getEntry — Get current entry

Opis

public string RecursiveTreeIterator::getEntry ( void )

Gets the part of the tree built for the current element.

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

Returns the part of the tree built for the current element.

RecursiveTreeIterator::endIteration
RecursiveTreeIterator::getPostfix
RecursiveTreeIterator


Get the postfix

RecursiveTreeIterator::getEntry
RecursiveTreeIterator::getPrefix
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::getPostfix

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::getPostfix — Get the postfix

Opis

public void RecursiveTreeIterator::getPostfix ( void )

Gets the string to place after the current element.

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

Returns the string to place after the current element.

RecursiveTreeIterator::getEntry
RecursiveTreeIterator::getPrefix
RecursiveTreeIterator


Get the prefix

RecursiveTreeIterator::getPostfix
RecursiveTreeIterator::key
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::getPrefix

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::getPrefix — Get the prefix

Opis

public string RecursiveTreeIterator::getPrefix ( void )

Gets the string to place in front of current element

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

Returns the string to place in front of current element

RecursiveTreeIterator::getPostfix
RecursiveTreeIterator::key
RecursiveTreeIterator


Get the key of the current element

RecursiveTreeIterator::getPrefix
RecursiveTreeIterator::next
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::key

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::key — Get the key of the current element

Opis

public string RecursiveTreeIterator::key ( void )

Gets the current key prefixed and postfixed.

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

Returns the current key prefixed and postfixed.

RecursiveTreeIterator::getPrefix
RecursiveTreeIterator::next
RecursiveTreeIterator


Move to next element

RecursiveTreeIterator::key
RecursiveTreeIterator::nextElement
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::next

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::next — Move to next element

Opis

public void RecursiveTreeIterator::next ( void )

Moves forward to the next element.

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

Nie jest zwracana żadna wartość.

RecursiveTreeIterator::key
RecursiveTreeIterator::nextElement
RecursiveTreeIterator


Next element

RecursiveTreeIterator::next
RecursiveTreeIterator::rewind
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::nextElement

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::nextElement — Next element

Opis

public void RecursiveTreeIterator::nextElement ( void )

Called when the next element is available.

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

Nie jest zwracana żadna wartość.

RecursiveTreeIterator::next
RecursiveTreeIterator::rewind
RecursiveTreeIterator


Rewind iterator

RecursiveTreeIterator::nextElement
RecursiveTreeIterator::setPrefixPart
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::rewind

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::rewind — Rewind iterator

Opis

public void RecursiveTreeIterator::rewind ( void )

Rewinds the iterator to the first element of the top level inner iterator.

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

Nie jest zwracana żadna wartość.

RecursiveTreeIterator::nextElement
RecursiveTreeIterator::setPrefixPart
RecursiveTreeIterator


Set a part of the prefix

RecursiveTreeIterator::rewind
RecursiveTreeIterator::valid
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::setPrefixPart

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::setPrefixPart — Set a part of the prefix

Opis

public void RecursiveTreeIterator::setPrefixPart ( int $part , string $value )

Sets a part of the prefix used in the graphic tree.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

part

One of the RecursiveTreeIterator::PREFIX_* constants.

value

The value to assign to the part of the prefix specified in part.

Zwracane wartości

Nie jest zwracana żadna wartość.

RecursiveTreeIterator::rewind
RecursiveTreeIterator::valid
RecursiveTreeIterator


Check validity

RecursiveTreeIterator::setPrefixPart
RegexIterator
RecursiveTreeIterator
PHP Manual

RecursiveTreeIterator::valid

(PHP 5 >= 5.3.0)

RecursiveTreeIterator::valid — Check validity

Opis

public bool RecursiveTreeIterator::valid ( void )

Check whether the current position is valid.

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

TRUE if the current position is valid, otherwise FALSE

RecursiveTreeIterator::setPrefixPart
RegexIterator
RecursiveTreeIterator


The RegexIterator class

(PHP 5 >= 5.2.0)

Wstęp

This iterator can be used to filter another iterator based on a regular expression.

Krótki opis klasy

RegexIterator extends FilterIterator {
/* Stałe */
const integer MATCH = 0 ;
const integer GET_MATCH = 1 ;
const integer ALL_MATCHES = 2 ;
const integer SPLIT = 3 ;
const integer REPLACE = 4 ;
const integer USE_KEY = 1 ;
/* Metody */
public __construct ( Iterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )
public bool accept ( void )
public int getFlags ( void )
public int getMode ( void )
public int getPregFlags ( void )
public string getRegex ( void )
public void setFlags ( int $flags )
public void setMode ( int $mode )
public void setPregFlags ( int $preg_flags )
/* Metody dziedziczone */
abstract bool FilterIterator::accept ( void )
FilterIterator::__construct ( Iterator $iterator )
mixed FilterIterator::current ( void )
Iterator FilterIterator::getInnerIterator ( void )
mixed FilterIterator::key ( void )
void FilterIterator::next ( void )
void FilterIterator::rewind ( void )
bool FilterIterator::valid ( void )
}

Stałe predefiniowane

RegexIterator operation modes

RegexIterator::ALL_MATCHES

Return all matches for the current entry (see preg_match_all()).

RegexIterator::GET_MATCH

Return the first match for the current entry (see preg_match()).

RegexIterator::MATCH

Only execute match (filter) for the current entry (see preg_match()).

RegexIterator::REPLACE

Replace the current entry (see preg_replace(); Not fully implemented yet)

RegexIterator::SPLIT

Returns the split values for the current entry (see preg_split()).

RegexIterator Flags

RegexIterator::USE_KEY

Special flag: Match the entry key instead of the entry value.

Spis treści

  • RegexIterator::accept — Get accept status
  • RegexIterator::__construct — Create a new RegexIterator
  • RegexIterator::getFlags — Get flags
  • RegexIterator::getMode — Returns operation mode.
  • RegexIterator::getPregFlags — Returns the regular expression flags.
  • RegexIterator::getRegex — Returns current regular expression
  • RegexIterator::setFlags — Sets the flags.
  • RegexIterator::setMode — Sets the operation mode.
  • RegexIterator::setPregFlags — Sets the regular expression flags.
RecursiveTreeIterator::valid
RegexIterator::accept
Iteratory


Get accept status

RegexIterator
RegexIterator::__construct
RegexIterator
PHP Manual

RegexIterator::accept

(PHP 5 >= 5.2.0)

RegexIterator::accept — Get accept status

Opis

public bool RegexIterator::accept ( void )

Matches (string)  RegexIterator::current()
(or  RegexIterator::key() if the
RegexIterator::USE_KEY flag is set)
against the regular expression.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if a match, FALSE otherwise.

Przykłady

Przykład #1 RegexIterator::accept() example

This example shows that only items matching the regular expression are accepted.

<?php
$names = new ArrayIterator(array('Ann', 'Bob', 'Charlie', 'David'));
$filter = new RegexIterator($names, '/^[B-D]/');
foreach ($filter as $name) {
    echo $name . PHP_EOL;
}
?>

Powyższy przykład wyświetli:

Bob
Charlie
David

Zobacz też:

  • RegexIterator constants
  • RegexIterator::setFlags() - Sets the flags.

RegexIterator
RegexIterator::__construct
RegexIterator


Create a new RegexIterator

RegexIterator::accept
RegexIterator::getFlags
RegexIterator
PHP Manual

RegexIterator::__construct

(PHP 5 >= 5.2.0)

RegexIterator::__construct — Create a new RegexIterator

Opis

public RegexIterator::__construct() ( Iterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )

Create a new RegexIterator which filters an Iterator using a regular expression.

Parametry

iterator

The iterator to apply this regex filter to.

regex

The regular expression to match.

mode

Operation mode, see RegexIterator::setMode() for a list of modes.

flags

Special flags, see RegexIterator::setFlags() for a list of available flags.

preg_flags

The regular expression flags. These flags depend on the operation mode parameter:

RegexIterator preg_flags
operation mode | available flags
RegexIterator::ALL_MATCHES | See preg_match_all().
RegexIterator::GET_MATCH | See preg_match().
RegexIterator::MATCH | See preg_match().
RegexIterator::REPLACE | none.
RegexIterator::SPLIT | See preg_split().

Przykłady

Przykład #1 RegexIterator::__construct() example

Creates a new RegexIterator that filters all strings that start with 'test'.

<?php
$arrayIterator = new ArrayIterator(array('test 1', 'another test', 'test 123'));
$regexIterator = new RegexIterator($arrayIterator, '/^test/');

foreach ($regexIterator as $value) {
    echo $value . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

test 1
test 123

Zobacz też:

  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression

RegexIterator::accept
RegexIterator::getFlags
RegexIterator


Get flags

RegexIterator::__construct
RegexIterator::getMode
RegexIterator
PHP Manual

RegexIterator::getFlags

(PHP 5 >= 5.2.0)

RegexIterator::getFlags — Get flags

Opis

public int RegexIterator::getFlags ( void )

Returns the flags, see RegexIterator::setFlags() for a list of available flags.

Zwracane wartości

Returns the set flags.

Przykłady

Przykład #1 RegexIterator::getFlags() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/');
$regexIterator->setFlags(RegexIterator::USE_KEY);

if ($regexIterator->getFlags() & RegexIterator::USE_KEY) {
    echo 'Filtering based on the array keys.';
} else {
    echo 'Filtering based on the array values.';
}
?>

Powyższy przykład wyświetli:

Filtering based on the array keys.

Zobacz też:

  • RegexIterator::setFlags() - Sets the flags.

RegexIterator::__construct
RegexIterator::getMode
RegexIterator


Returns operation mode.

RegexIterator::getFlags
RegexIterator::getPregFlags
RegexIterator
PHP Manual

RegexIterator::getMode

(PHP 5 >= 5.2.0)

RegexIterator::getMode — Returns operation mode.

Opis

public int RegexIterator::getMode ( void )

Returns the operation mode, see RegexIterator::setMode() for the list of operation modes.

Zwracane wartości

Returns the operation mode.

Przykłady

Przykład #1 RegexIterator::getMode() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^[a-z]+/', RegexIterator::GET_MATCH);

$mode = $regexIterator->getMode();
if ($mode & RegexIterator::GET_MATCH) {
    echo 'Getting the match for each item.';
} elseif ($mode & RegexIterator::ALL_MATCHES) {
    echo 'Getting all matches for each item.';
} elseif ($mode & RegexIterator::MATCH) {
    echo 'Getting each item if it matches.';
} elseif ($mode & RegexIterator::SPLIT) {
    echo 'Getting split pieces of each.';
}
?>

Powyższy przykład wyświetli:

Getting the match for each item.

Zobacz też:

  • RegexIterator::setMode() - Sets the operation mode.

RegexIterator::getFlags
RegexIterator::getPregFlags
RegexIterator


Returns the regular expression flags.

RegexIterator::getMode
RegexIterator::getRegex
RegexIterator
PHP Manual

RegexIterator::getPregFlags

(PHP 5 >= 5.2.0)

RegexIterator::getPregFlags — Returns the regular expression flags.

Opis

public int RegexIterator::getPregFlags ( void )

Returns the regular expression flags, see RegexIterator::__construct() for the list of flags.

Zwracane wartości

Returns a bitmask of the regular expression flags.

Przykłady

Przykład #1 RegexIterator::getPregFlags() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/\s/', RegexIterator::SPLIT);
$regexIterator->setPregFlags(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);

if ($regexIterator->getPregFlags() & PREG_SPLIT_NO_EMPTY) {
    echo 'Ignoring empty pieces';
} else {
    echo 'Not ignoring empty pieces';
}

?>

Powyższy przykład wyświetli:

Ignoring empty pieces

Zobacz też:

  • RegexIterator::setPregFlags() - Sets the regular expression flags.

RegexIterator::getMode
RegexIterator::getRegex
RegexIterator


Returns current regular expression

RegexIterator::getPregFlags
RegexIterator::setFlags
RegexIterator
PHP Manual

RegexIterator::getRegex

(No version information available, might only be in SVN)

RegexIterator::getRegex — Returns current regular expression

Opis

public string RegexIterator::getRegex ( 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

RegexIterator::getPregFlags
RegexIterator::setFlags
RegexIterator


Sets the flags.

RegexIterator::getRegex
RegexIterator::setMode
RegexIterator
PHP Manual

RegexIterator::setFlags

(PHP 5 >= 5.2.0)

RegexIterator::setFlags — Sets the flags.

Opis

public void RegexIterator::setFlags ( int $flags )

Sets the flags.

Parametry

flags

The flags to set, a bitmask of class constants.

The available flags are listed below. The actual meanings of these flags are described in the predefined constants.

RegexIterator flags
value | constant
1 | RegexIterator::USE_KEY

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 RegexIterator::setFlags() example

Creates a new RegexIterator that filters all entries whose key starts with 'test'.

<?php
$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/');
$regexIterator->setFlags(RegexIterator::USE_KEY);

foreach ($regexIterator as $key => $value) {
    echo $key . ' => ' . $value . "\n";
}
?>

Powyższy przykład wyświetli:

teststr2 => another test

Zobacz też:

  • RegexIterator::getFlags() - Get flags

RegexIterator::getRegex
RegexIterator::setMode
RegexIterator


Sets the operation mode.

RegexIterator::setFlags
RegexIterator::setPregFlags
RegexIterator
PHP Manual

RegexIterator::setMode

(PHP 5 >= 5.2.0)

RegexIterator::setMode — Sets the operation mode.

Opis

public void RegexIterator::setMode ( int $mode )

Sets the operation mode.

Parametry

mode

The operation mode.

The available modes are listed below. The actual meanings of these modes are described in the predefined constants.

RegexIterator modes
value | constant
0 | RegexIterator::MATCH
1 | RegexIterator::GET_MATCH
2 | RegexIterator::ALL_MATCHES
3 | RegexIterator::SPLIT
4 | RegexIterator::REPLACE

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 RegexIterator::setMode() example

<?php
$test = array ('str1' => 'test 1', 'test str2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
// Filter everything that starts with 'test ' followed by one or more numbers.
$regexIterator = new RegexIterator($arrayIterator, '/^test (\d+)/');
// Operation mode: Replace actual value with the matches
$regexIterator->setMode(RegexIterator::GET_MATCH);

foreach ($regexIterator as $key => $value) {
    // print out the matched number(s)
    echo $key . ' => ' . $value[1] . PHP_EOL;
}
?>

Powyższy przykład wyświetli coś podobnego do:

str1 => 1
str3 => 123

Zobacz też:

  • RegexIterator::getMode() - Returns operation mode.

RegexIterator::setFlags
RegexIterator::setPregFlags
RegexIterator


Sets the regular expression flags.

RegexIterator::setMode
Interfejsy
RegexIterator
PHP Manual

RegexIterator::setPregFlags

(PHP 5 >= 5.2.0)

RegexIterator::setPregFlags — Sets the regular expression flags.

Opis

public void RegexIterator::setPregFlags ( int $preg_flags )

Sets the regular expression flags.

Parametry

preg_flags

The regular expression flags. See RegexIterator::__construct() for an overview of available flags.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 RegexIterator::setPregFlags() example

Creates a new RegexIterator that filters all entries with where the array key starts with 'test'.

<?php
$test = array ('test 1', 'another test', 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/', RegexIterator::GET_MATCH);

$regexIterator->setPregFlags(PREG_OFFSET_CAPTURE);

foreach ($regexIterator as $key => $value) {
    var_dump($value);
}
?>

Powyższy przykład wyświetli coś podobnego do:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}

Zobacz też:

  • RegexIterator::getPregFlags() - Returns the regular expression flags.

RegexIterator::setMode
Interfejsy
RegexIterator


Interfejsy

Spis treści

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator

SPL dostarcza kilka interfejsów.

Patrz także: Predefined Interfaces

Lista interfejsów

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator
  • SplObserver
  • SplSubject
RegexIterator::setPregFlags
Countable
SPL


The Countable interface

(PHP 5 >= 5.1.0)

Wstęp

Classes implementing Countable can be used with the count() function.

Zestawienie interfejsu

Countable {
/* Metody */
abstract public int count ( void )
}

Spis treści

  • Countable::count — Count elements of an object
Interfejsy
Countable::count
Interfejsy


Count elements of an object

Countable
OuterIterator
Countable
PHP Manual

Countable::count

(PHP 5 >= 5.1.0)

Countable::count — Count elements of an object

Opis

abstract public int Countable::count ( void )

This method is executed when using the count() function on an object implementing Countable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The custom count as an integer.

Informacja:

The return value is cast to an integer.

Przykłady

Przykład #1 Countable::count() example

<?php
class myCounter implements Countable {
    public function count() {
        static $count = 0;
        return ++$count;
    }
}

$counter = new myCounter;

for($i=0; $i<10; ++$i) {
    echo "I have been count()ed " . count($counter) . " times\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

I have been count()ed 1 times
I have been count()ed 2 times
I have been count()ed 3 times
I have been count()ed 4 times
I have been count()ed 5 times
I have been count()ed 6 times
I have been count()ed 7 times
I have been count()ed 8 times
I have been count()ed 9 times
I have been count()ed 10 times

Countable
OuterIterator
Countable


The OuterIterator interface

(PHP 5 >= 5.1.0)

Wstęp

Classes implementing OuterIterator can be used to iterate over iterators.

Zestawienie interfejsu

OuterIterator extends Iterator {
/* Metody */
public Iterator getInnerIterator ( void )
/* Metody dziedziczone */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Spis treści

  • OuterIterator::getInnerIterator — Returns the inner iterator for the current entry.
Countable::count
OuterIterator::getInnerIterator
Interfejsy


Returns the inner iterator for the current entry.

OuterIterator
RecursiveIterator
OuterIterator
PHP Manual

OuterIterator::getInnerIterator

(PHP 5 >= 5.1.0)

OuterIterator::getInnerIterator — Returns the inner iterator for the current entry.

Opis

public Iterator OuterIterator::getInnerIterator ( void )

Returns the inner iterator for the current iterator entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The inner iterator for the current entry.

OuterIterator
RecursiveIterator
OuterIterator


The RecursiveIterator interface

(PHP 5 >= 5.1.0)

Wstęp

Classes implementing RecursiveIterator can be used to iterate over iterators recursively.

Zestawienie interfejsu

RecursiveIterator extends Iterator {
/* Metody */
public RecursiveIterator getChildren ( void )
public bool hasChildren ( void )
/* Metody dziedziczone */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Spis treści

  • RecursiveIterator::getChildren — Returns an iterator for the current entry.
  • RecursiveIterator::hasChildren — Returns if an iterator can be created fot the current entry.
OuterIterator::getInnerIterator
RecursiveIterator::getChildren
Interfejsy


Returns an iterator for the current entry.

RecursiveIterator
RecursiveIterator::hasChildren
RecursiveIterator
PHP Manual

RecursiveIterator::getChildren

(PHP 5 >= 5.1.0)

RecursiveIterator::getChildren — Returns an iterator for the current entry.

Opis

public RecursiveIterator RecursiveIterator::getChildren ( void )

Returns an iterator for the current iterator entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An iterator for the current entry.

Zobacz też:

  • RecursiveIterator::hasChildren() - Returns if an iterator can be created fot the current entry.

RecursiveIterator
RecursiveIterator::hasChildren
RecursiveIterator


Returns if an iterator can be created fot the current entry.

RecursiveIterator::getChildren
SeekableIterator
RecursiveIterator
PHP Manual

RecursiveIterator::hasChildren

(PHP 5 >= 5.1.0)

RecursiveIterator::hasChildren — Returns if an iterator can be created fot the current entry.

Opis

public bool RecursiveIterator::hasChildren ( void )

Returns if an iterator can be created fot the current entry. RecursiveIterator::getChildren().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the current entry can be iterated over, otherwise returns FALSE.

Zobacz też:

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry.

RecursiveIterator::getChildren
SeekableIterator
RecursiveIterator


The SeekableIterator interface

(PHP 5 >= 5.1.0)

Wstęp

The Seekable iterator.

Zestawienie interfejsu

SeekableIterator extends Iterator {
/* Metody */
abstract public void seek ( int $position )
/* Metody dziedziczone */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public boolean Iterator::valid ( void )
}

Przykład #1 Basic usage

This example demonstrates creating a custom SeekableIterator, seeking to a position and handling an invalid position.

<?php
class MySeekableIterator implements SeekableIterator {

    private $position = 0;

    private $array = array(
        "first element",
        "second element",
        "third element",
        "fourth element"
    );

    public function seek($position) {
      $this->position = $position;

      if (!$this->valid()) {
          throw new OutOfBoundsException("invalid seek position ($position)");
      }
    }

    /* Methods required for Iterator interface */

    public function __construct() {
        $this->position = 0;
    }

    public function rewind() {
        $this->position = 0;
    }

    public function current() {
        return $this->array[$this->position];
    }

    public function key() {
        return $this->position;
    }

    public function next() {
        ++$this->position;
    }

    public function valid() {
        return isset($this->array[$this->position]);
    }
}

try {

    $it = new MySeekableIterator;
    echo $it->current(), "\n";

    $it->seek(2);
    echo $it->current(), "\n";

    $it->seek(1);
    echo $it->current(), "\n";

    $it->seek(10);

} catch (OutOfBoundsException $e) {
    echo $e->getMessage();
}
?>

Powyższy przykład wyświetli coś podobnego do:

first element
third element
second element
invalid seek position (10)

Spis treści

  • SeekableIterator::seek — Seeks to a position
RecursiveIterator::hasChildren
SeekableIterator::seek
Interfejsy


Seeks to a position

SeekableIterator
Wyjątki
SeekableIterator
PHP Manual

SeekableIterator::seek

(PHP 5 >= 5.1.0)

SeekableIterator::seek — Seeks to a position

Opis

abstract public void SeekableIterator::seek ( int $position )

Seeks to a given position in the iterator.

Parametry

position

The position to seek to.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Implementations should throw an OutOfBoundsException if the position is not seekable.

Przykłady

Przykład #1 SeekableIterator::seek() example

Seek to the item at position 3 in the iterator (ArrayIterator implements SeekableIterator).

<?php
$array = array("apple", "banana", "cherry", "damson", "elderberry");
$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current();
?>

Powyższy przykład wyświetli coś podobnego do:

damson

Zobacz też:

  • SeekableIterator
  • Iterator

SeekableIterator
Wyjątki
SeekableIterator


Wyjątki

Spis treści

  • BadFunctionCallException
  • BadMethodCallException
  • DomainException
  • InvalidArgumentException
  • LengthException
  • LogicException
  • OutOfBoundsException
  • OutOfRangeException
  • OverflowException
  • RangeException
  • RuntimeException
  • UnderflowException
  • UnexpectedValueException

SPL dostarcza kilka standardowych wyjątków.

patrz także: Predefined Exceptions

SeekableIterator::seek
BadFunctionCallException
SPL


The BadFunctionCallException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown if a callback refers to an undefined function or if some arguments are missing.

Krótki opis klasy

BadFunctionCallException extends LogicException {
/* 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 )
}
Wyjątki
BadMethodCallException
Wyjątki


The BadMethodCallException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown if a callback refers to an undefined method or if some arguments are missing.

Krótki opis klasy

BadMethodCallException extends BadFunctionCallException {
/* 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 )
}
BadFunctionCallException
DomainException
Wyjątki


The DomainException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown if a value does not adhere to a defined valid data domain.

Krótki opis klasy

DomainException extends LogicException {
/* 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 )
}
BadMethodCallException
InvalidArgumentException
Wyjątki


The InvalidArgumentException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown if an argument does not match with the expected value.

Krótki opis klasy

InvalidArgumentException extends LogicException {
/* 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 )
}
DomainException
LengthException
Wyjątki


The LengthException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown if a length is invalid.

Krótki opis klasy

LengthException extends LogicException {
/* 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 )
}
InvalidArgumentException
LogicException
Wyjątki


The LogicException class

(PHP 5 >= 5.1.0)

Wstęp

Exception that represents error in the program logic. This kind of exceptions should directly lead to a fix in your code.

Krótki opis klasy

LogicException extends Exception {
/* 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 )
}
LengthException
OutOfBoundsException
Wyjątki


The OutOfBoundsException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.

Krótki opis klasy

OutOfBoundsException extends RuntimeException {
/* 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 )
}
LogicException
OutOfRangeException
Wyjątki


The OutOfRangeException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.

Krótki opis klasy

OutOfRangeException extends LogicException {
/* 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 )
}
OutOfBoundsException
OverflowException
Wyjątki


The OverflowException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown when adding an element to a full container.

Krótki opis klasy

OverflowException extends RuntimeException {
/* 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 )
}
OutOfRangeException
RangeException
Wyjątki


The RangeException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.

Krótki opis klasy

RangeException extends RuntimeException {
/* 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 )
}
OverflowException
RuntimeException
Wyjątki


The RuntimeException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown if an error which can only be found on runtime occurs.

Krótki opis klasy

RuntimeException extends Exception {
/* 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 )
}
RangeException
UnderflowException
Wyjątki


The UnderflowException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown when performing an invalid operation on an empty container, such as removing an element.

Krótki opis klasy

UnderflowException extends RuntimeException {
/* 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 )
}
RuntimeException
UnexpectedValueException
Wyjątki


The UnexpectedValueException class

(PHP 5 >= 5.1.0)

Wstęp

Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type or value not including arithmetic or buffer related errors.

Krótki opis klasy

UnexpectedValueException extends RuntimeException {
/* 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 )
}
UnderflowException
SPL Funkcje
Wyjątki


SPL Funkcje

Spis treści

  • class_implements — Return the interfaces which are implemented by the given class
  • class_parents — Return the parent classes of the given class
  • class_uses — Return the traits used by the given class
  • iterator_apply — Call a function for every element in an iterator
  • iterator_count — Count the elements in an iterator
  • iterator_to_array — Copy the iterator into an array
  • spl_autoload_call — Try all registered __autoload() function to load the requested class
  • spl_autoload_extensions — Register and return default file extensions for spl_autoload
  • spl_autoload_functions — Return all registered __autoload() functions
  • spl_autoload_register — Register given function as __autoload() implementation
  • spl_autoload_unregister — Unregister given function as __autoload() implementation
  • spl_autoload — Default implementation for __autoload()
  • spl_classes — Return available SPL classes
  • spl_object_hash — Return hash id for given object
UnexpectedValueException
class_implements
SPL


Return the interfaces which are implemented by the given class

SPL Funkcje
class_parents
SPL Funkcje
PHP Manual

class_implements

(PHP 5 >= 5.1.0)

class_implements — Return the interfaces which are implemented by the given class

Opis

array class_implements ( mixed $class [, bool $autoload = true ] )

This function returns an array with the names of the interfaces that the given class and its parents implement.

Parametry

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload() magic method.

Zwracane wartości

An array on success, or FALSE on error.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the option to pass the class parameter as a string. Added the autoload parameter.

Przykłady

Przykład #1 class_implements() example

<?php

interface foo { }
class bar implements foo {}

print_r(class_implements(new bar));

// since PHP 5.1.0 you may also specify the parameter as a string
print_r(class_implements('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_implements('not_loaded', true));

?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [foo] => foo
)

Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

Zobacz też:

  • class_parents() - Return the parent classes of the given class
  • get_declared_interfaces() - Returns an array of all declared interfaces

SPL Funkcje
class_parents
SPL Funkcje


Return the parent classes of the given class

class_implements
class_uses
SPL Funkcje
PHP Manual

class_parents

(PHP 5 >= 5.1.0)

class_parents — Return the parent classes of the given class

Opis

array class_parents ( mixed $class [, bool $autoload = true ] )

This function returns an array with the name of the parent classes of the given class.

Parametry

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload() magic method.

Zwracane wartości

An array on success, or FALSE on error.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the option to pass the class parameter as a string. Added the autoload parameter.

Przykłady

Przykład #1 class_parents() example

<?php

class foo { }
class bar extends foo {}

print_r(class_parents(new bar));

// since PHP 5.1.0 you may also specify the parameter as a string
print_r(class_parents('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_parents('not_loaded', true));
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [foo] => foo
)

Array
(
    [parent_of_not_loaded] => parent_of_not_loaded
)

Zobacz też:

  • class_implements() - Return the interfaces which are implemented by the given class

class_implements
class_uses
SPL Funkcje


Return the traits used by the given class

class_parents
iterator_apply
SPL Funkcje
PHP Manual

class_uses

(No version information available, might only be in SVN)

class_uses — Return the traits used by the given class

Opis

array class_uses ( mixed $class [, bool $autoload = true ] )

This function returns an array with the names of the traits that the given class uses. This does however not include any traits used by a parent class.

Parametry

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload() magic method.

Zwracane wartości

An array on success, or FALSE on error.

Przykłady

Przykład #1 class_uses() example

<?php

trait foo { }
class bar {
  use foo;
}

print_r(class_uses(new bar));

print_r(class_uses('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_implements('not_loaded', true));
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [foo] => foo
)

Array
(
    [foo] => foo
)

Array
(
    [trait_of_not_loaded] => trait_of_not_loaded
)

Zobacz też:

  • class_parents() - Return the parent classes of the given class
  • get_declared_traits() - Returns an array of all declared traits

class_parents
iterator_apply
SPL Funkcje


Call a function for every element in an iterator

class_uses
iterator_count
SPL Funkcje
PHP Manual

iterator_apply

(PHP 5 >= 5.1.0)

iterator_apply — Call a function for every element in an iterator

Opis

int iterator_apply ( Traversable $iterator , callback $function [, array $args ] )

Calls a function for every element in an iterator.

Parametry

iterator

The class to iterate over.

function

The callback function to call on every element.

Informacja: The function must return TRUE in order to continue iterating over the iterator.

args

Arguments to pass to the callback function.

Zwracane wartości

Returns the iteration count.

Przykłady

Przykład #1 iterator_apply() example

<?php
function print_caps(Iterator $iterator) {
    echo strtoupper($iterator->current()) . "\n";
    return TRUE;
}

$it = new ArrayIterator(array("Apples", "Bananas", "Cherries"));
iterator_apply($it, "print_caps", array($it));
?>

Powyższy przykład wyświetli:

APPLES
BANANAS
CHERRIES

Zobacz też:

  • array_walk() - Zastosuj funkcję użytkownika do każdego elementu tablicy

class_uses
iterator_count
SPL Funkcje


Count the elements in an iterator

iterator_apply
iterator_to_array
SPL Funkcje
PHP Manual

iterator_count

(PHP 5 >= 5.1.0)

iterator_count — Count the elements in an iterator

Opis

int iterator_count ( Traversable $iterator )

Count the elements in an iterator.

Parametry

iterator

The iterator being counted.

Zwracane wartości

The number of elements in iterator.

Przykłady

Przykład #1 iterator_count() example

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_count($iterator));
?>

Powyższy przykład wyświetli:

int(4)

iterator_apply
iterator_to_array
SPL Funkcje


Copy the iterator into an array

iterator_count
spl_autoload_call
SPL Funkcje
PHP Manual

iterator_to_array

(PHP 5 >= 5.1.0)

iterator_to_array — Copy the iterator into an array

Opis

array iterator_to_array ( Traversable $iterator [, bool $use_keys = true ] )

Copy the elements of an iterator into an array.

Parametry

iterator

The iterator being copied.

use_keys

Whether to use the iterator element keys as index.

Zwracane wartości

An array containing the elements of the iterator.

Rejestr zmian

Wersja | Opis
5.2.1 | The use_keys parameter was added.

Przykłady

Przykład #1 iterator_to_array() example

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_to_array($iterator, true));
var_dump(iterator_to_array($iterator, false));
?>

Powyższy przykład wyświetli:

array(4) {
  ["recipe"]=>
  string(8) "pancakes"
  [0]=>
  string(3) "egg"
  [1]=>
  string(4) "milk"
  [2]=>
  string(5) "flour"
}
array(4) {
  [0]=>
  string(8) "pancakes"
  [1]=>
  string(3) "egg"
  [2]=>
  string(4) "milk"
  [3]=>
  string(5) "flour"
}

iterator_count
spl_autoload_call
SPL Funkcje


Try all registered __autoload() function to load the requested class

iterator_to_array
spl_autoload_extensions
SPL Funkcje
PHP Manual

spl_autoload_call

(PHP 5 >= 5.1.2)

spl_autoload_call — Try all registered __autoload() function to load the requested class

Opis

void spl_autoload_call ( string $class_name )

This function can be used to manually search for a class or interface using the registered __autoload functions.

Parametry

class_name

The class name being searched.

Zwracane wartości

Nie jest zwracana żadna wartość.

iterator_to_array
spl_autoload_extensions
SPL Funkcje


Register and return default file extensions for spl_autoload

spl_autoload_call
spl_autoload_functions
SPL Funkcje
PHP Manual

spl_autoload_extensions

(PHP 5 >= 5.1.2)

spl_autoload_extensions — Register and return default file extensions for spl_autoload

Opis

string spl_autoload_extensions ([ string $file_extensions ] )

This function can modify and check the file extensions that the built in __autoload() fallback function spl_autoload() will be using.

Parametry

file_extensions

When calling without an argument, it simply returns the current list of extensions each separated by comma. To modify the list of file extensions, simply invoke the functions with the new list of file extensions to use in a single string with each extensions separated by comma.

Zwracane wartości

A comma delimited list of default file extensions for spl_autoload().

spl_autoload_call
spl_autoload_functions
SPL Funkcje


Return all registered __autoload() functions

spl_autoload_extensions
spl_autoload_register
SPL Funkcje
PHP Manual

spl_autoload_functions

(PHP 5 >= 5.1.2)

spl_autoload_functions — Return all registered __autoload() functions

Opis

array spl_autoload_functions ( void )

Get all registered __autoload() functions.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of all registered __autoload functions. If the autoload stack is not activated then the return value is FALSE. If no function is registered the return value will be an empty array.

spl_autoload_extensions
spl_autoload_register
SPL Funkcje


Register given function as __autoload() implementation

spl_autoload_functions
spl_autoload_unregister
SPL Funkcje
PHP Manual

spl_autoload_register

(PHP 5 >= 5.1.2)

spl_autoload_register — Register given function as __autoload() implementation

Opis

bool spl_autoload_register ([ callback $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

Register a function with the spl provided __autoload stack. If the stack is not yet activated it will be activated.

If your code has an existing __autoload function then this function must be explicitly registered on the __autoload stack. This is because spl_autoload_register() will effectively replace the engine cache for the __autoload function by either spl_autoload() or spl_autoload_call().

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

Parametry

autoload_function

The autoload function being registered. If no parameter is provided, then the default implementation of spl_autoload() will be registered.

throw

This parameter specifies whether spl_autoload_register() should throw exceptions when the autoload_function cannot be registered.

prepend

If true, spl_autoload_register() will prepend the autoloader on the autoload stack instead of appending it.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.0 | Namespaces support was introduced.
5.3.0 | The prepend parameter was added.

Przykłady

Przykład #1 spl_autoload_register() example

<?php

namespace Foobar;

class Foo {
    static public function test($name) {
        print '[['. $name .']]';
    }
}

spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0

new InexistentClass;

?>

Powyższy przykład wyświetli coś podobnego do:

[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...

Zobacz też:

  • __autoload() - Attempt to load undefined class

spl_autoload_functions
spl_autoload_unregister
SPL Funkcje


Unregister given function as __autoload() implementation

spl_autoload_register
spl_autoload
SPL Funkcje
PHP Manual

spl_autoload_unregister

(PHP 5 >= 5.1.2)

spl_autoload_unregister — Unregister given function as __autoload() implementation

Opis

bool spl_autoload_unregister ( mixed $autoload_function )

Unregister a function from the spl provided __autoload stack. If the stack is activated and empty after unregistering the given function then it will be deactivated.

When this function results in the autoload stack being deactivated, any __autoload function that previously existed will not be reactivated.

Parametry

autoload_function

The autoload function being unregistered.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

spl_autoload_register
spl_autoload
SPL Funkcje


Default implementation for __autoload()

spl_autoload_unregister
spl_classes
SPL Funkcje
PHP Manual

spl_autoload

(PHP 5 >= 5.1.2)

spl_autoload — Default implementation for __autoload()

Opis

void spl_autoload ( string $class_name [, string $file_extensions = spl_autoload_extensions() ] )

This function is intended to be used as a default implementation for __autoload(). If nothing else is specified and spl_autoload_register() is called without any parameters then this functions will be used for any later call to __autoload().

Parametry

class_name

The lowercased name of the class (and namespace) being instantiated.

file_extensions

By default it checks all include paths to contain filenames built up by the lowercase class name appended by the filename extensions .inc and .php.

Zwracane wartości

Nie jest zwracana żadna wartość.

spl_autoload_unregister
spl_classes
SPL Funkcje


Return available SPL classes

spl_autoload
spl_object_hash
SPL Funkcje
PHP Manual

spl_classes

(PHP 5)

spl_classes — Return available SPL classes

Opis

array spl_classes ( void )

This function returns an array with the current available SPL classes.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array containing the currently available SPL classes.

Przykłady

Przykład #1 spl_classes() example

<?php

print_r(spl_classes());

?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [ArrayObject] => ArrayObject
    [ArrayIterator] => ArrayIterator
    [CachingIterator] => CachingIterator
    [RecursiveCachingIterator] => RecursiveCachingIterator
    [DirectoryIterator] => DirectoryIterator
    [FilterIterator] => FilterIterator
    [LimitIterator] => LimitIterator
    [ParentIterator] => ParentIterator
    [RecursiveDirectoryIterator] => RecursiveDirectoryIterator
    [RecursiveIterator] => RecursiveIterator
    [RecursiveIteratorIterator] => RecursiveIteratorIterator
    [SeekableIterator] => SeekableIterator
    [SimpleXMLIterator] => SimpleXMLIterator
)

spl_autoload
spl_object_hash
SPL Funkcje


Return hash id for given object

spl_classes
Obsługa plików
SPL Funkcje
PHP Manual

spl_object_hash

(PHP 5 >= 5.2.0)

spl_object_hash — Return hash id for given object

Opis

string spl_object_hash ( object $obj )

This function returns a unique identifier for the object. This id can be used as a hash key for storing objects or for identifying an object.

Parametry

object

Any object.

Zwracane wartości

A string that is unique for each currently existing object and is always the same for each object.

Przykłady

Przykład #1 A spl_object_hash() example

<?php
$id = spl_object_hash($object);
$storage[$id] = $object;
?>

Notatki

Informacja:

When an object is destroyed, its hash may be reused for other objects.

spl_classes
Obsługa plików
SPL Funkcje


Obsługa plików

Spis treści

  • SplFileInfo
  • SplFileObject
  • SplTempFileObject

SPL dostarcza kilka klas do pracy na plikach.

spl_object_hash
SplFileInfo
SPL


The SplFileInfo class

(PHP 5 >= 5.1.2)

Wstęp

The SplFileInfo class offers a high-level object oriented interface to information for an individual file.

Krótki opis klasy

SplFileInfo {
/* Metody */
public __construct ( string $file_name )
public int getATime ( void )
public string getBasename ([ string $suffix ] )
public int getCTime ( void )
public string getExtension ( void )
public SplFileInfo getFileInfo ([ string $class_name ] )
public string getFilename ( void )
public int getGroup ( void )
public int getInode ( void )
public string getLinkTarget ( void )
public int getMTime ( void )
public int getOwner ( void )
public string getPath ( void )
public SplFileInfo getPathInfo ([ string $class_name ] )
public string getPathname ( void )
public int getPerms ( void )
public string getRealPath ( void )
public int getSize ( void )
public string getType ( void )
public bool isDir ( void )
public bool isExecutable ( void )
public bool isFile ( void )
public bool isLink ( void )
public bool isReadable ( void )
public bool isWritable ( void )
public SplFileObject openFile ([ string $open_mode = r [, bool $use_include_path = false [, resource $context = NULL ]]] )
public void setFileClass ([ string $class_name ] )
public void setInfoClass ([ string $class_name ] )
public void __toString ( void )
}

Spis treści

  • SplFileInfo::__construct — Construct a new SplFileInfo object
  • SplFileInfo::getATime — Gets last access time of the file
  • SplFileInfo::getBasename — Gets the base name of the file
  • SplFileInfo::getCTime — Gets the inode change time
  • SplFileInfo::getExtension — Gets the file extension
  • SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file
  • SplFileInfo::getFilename — Gets the filename
  • SplFileInfo::getGroup — Gets the file group
  • SplFileInfo::getInode — Gets the inode for the file
  • SplFileInfo::getLinkTarget — Gets the target of a link
  • SplFileInfo::getMTime — Gets the last modified time
  • SplFileInfo::getOwner — Gets the owner of the file
  • SplFileInfo::getPath — Gets the path without filename
  • SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path
  • SplFileInfo::getPathname — Gets the path to the file
  • SplFileInfo::getPerms — Gets file permissions
  • SplFileInfo::getRealPath — Gets absolute path to file
  • SplFileInfo::getSize — Gets file size
  • SplFileInfo::getType — Gets file type
  • SplFileInfo::isDir — Tells if the file is a directory
  • SplFileInfo::isExecutable — Tells if the file is executable
  • SplFileInfo::isFile — Tells if the object references a regular file
  • SplFileInfo::isLink — Tells if the file is a link
  • SplFileInfo::isReadable — Tells if file is readable
  • SplFileInfo::isWritable — Tells if the entry is writable
  • SplFileInfo::openFile — Gets an SplFileObject object for the file
  • SplFileInfo::setFileClass — Sets the class name used with SplFileInfo::openFile
  • SplFileInfo::setInfoClass — Sets the class used with getFileInfo and getPathInfo
  • SplFileInfo::__toString — Returns the path to the file as a string
Obsługa plików
SplFileInfo::__construct
Obsługa plików


Construct a new SplFileInfo object

SplFileInfo
SplFileInfo::getATime
SplFileInfo
PHP Manual

SplFileInfo::__construct

(PHP 5 >= 5.1.2)

SplFileInfo::__construct — Construct a new SplFileInfo object

Opis

public SplFileInfo::__construct ( string $file_name )

Creates a new SplFileInfo object for the file_name specified. The file does not need to exist, or be readable.

Parametry

file_name

Path to the file.

Przykłady

Przykład #1 SplFileInfo::__construct() example

<?php
$info = new SplFileInfo('example.php');
if ($info->isFile()) {
    echo $info->getRealPath();
}
?>

SplFileInfo
SplFileInfo::getATime
SplFileInfo


Gets last access time of the file

SplFileInfo::__construct
SplFileInfo::getBasename
SplFileInfo
PHP Manual

SplFileInfo::getATime

(PHP 5 >= 5.1.2)

SplFileInfo::getATime — Gets last access time of the file

Opis

public int SplFileInfo::getATime ( void )

Gets the last access time for the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the time the file was last accessed.

Błędy/Wyjątki

Throws RunTimeException on error.

Zobacz też:

  • fileatime() - Pobiera ostatni czas dostępu do pliku

SplFileInfo::__construct
SplFileInfo::getBasename
SplFileInfo


Gets the base name of the file

SplFileInfo::getATime
SplFileInfo::getCTime
SplFileInfo
PHP Manual

SplFileInfo::getBasename

(PHP 5 >= 5.2.2)

SplFileInfo::getBasename — Gets the base name of the file

Opis

public string SplFileInfo::getBasename ([ string $suffix ] )

This method returns the base name of the file, directory, or link without path info.

Parametry

suffix

Optional suffix to omit from the base name returned.

Zwracane wartości

Returns the base name without path information.

Przykłady

Przykład #1 SplFileInfo::getBasename() example

<?php
$info = new SplFileInfo('file.txt');
var_dump($info->getBasename());

$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename());

$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename('.txt'));
?>

Powyższy przykład wyświetli coś podobnego do:

string(8) "file.txt"
string(8) "file.txt"
string(4) "file"

Zobacz też:

  • SplFileInfo::getFilename() - Gets the filename

SplFileInfo::getATime
SplFileInfo::getCTime
SplFileInfo


Gets the inode change time

SplFileInfo::getBasename
SplFileInfo::getExtension
SplFileInfo
PHP Manual

SplFileInfo::getCTime

(PHP 5 >= 5.1.2)

SplFileInfo::getCTime — Gets the inode change time

Opis

public int SplFileInfo::getCTime ( void )

Returns the inode change time for the file. The time returned is a Unix timestamp.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The last change time, in a Unix timestamp.

Błędy/Wyjątki

Throws RunTimeException on error.

Przykłady

Przykład #1 SplFileInfo::getCTime() example

<?php
$info = new SplFileInfo(__FILE__);
echo 'Last changed at ' . date('g:i a', $info->getCTime());
?>

Powyższy przykład wyświetli coś podobnego do:

Last changed at 1:49 pm

Zobacz też:

  • filectime() - Pobiera i-węzłowy czas zmiany pliku

SplFileInfo::getBasename
SplFileInfo::getExtension
SplFileInfo


Gets the file extension

SplFileInfo::getCTime
SplFileInfo::getFileInfo
SplFileInfo
PHP Manual

SplFileInfo::getExtension

(PHP 5 >= 5.3.6)

SplFileInfo::getExtension — Gets the file extension

Opis

public string SplFileInfo::getExtension ( void )

Retrieves the file extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string containing the file extension, or an empty string if the file has no extension.

Przykłady

Przykład #1 SplFileInfo::getExtension() example

<?php

$info = new SplFileInfo('foo.txt');
var_dump($info->getExtension());

$info = new SplFileInfo('photo.jpg');
var_dump($info->getExtension());

$info = new SplFileInfo('something.tar.gz');
var_dump($info->getExtension());

?>

Powyższy przykład wyświetli:

string(3) "txt"
string(3) "jpg"
string(2) "gz"

Notatki

Informacja:

This method is only available as of PHP 5.3.6. Another way of getting the extension is to use the pathinfo() function.

<?php
$extension = pathinfo($info->getFilename(), PATHINFO_EXTENSION);
?>

Zobacz też:

  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getBasename() - Gets the base name of the file
  • pathinfo() - Zwraca informacje o ścieżce do pliku
SplFileInfo::getCTime
SplFileInfo::getFileInfo
SplFileInfo


Gets an SplFileInfo object for the file

SplFileInfo::getExtension
SplFileInfo::getFilename
SplFileInfo
PHP Manual

SplFileInfo::getFileInfo

(PHP 5 >= 5.1.2)

SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file

Opis

public SplFileInfo SplFileInfo::getFileInfo ([ string $class_name ] )

This method gets an SplFileInfo object for the referenced file.

Parametry

class_name

Name of an SplFileInfo derived class to use.

Zwracane wartości

An SplFileInfo object created for the file.

Zobacz też:

  • SplFileInfo::setInfoClass() - Sets the class used with getFileInfo and getPathInfo

SplFileInfo::getExtension
SplFileInfo::getFilename
SplFileInfo


Gets the filename

SplFileInfo::getFileInfo
SplFileInfo::getGroup
SplFileInfo
PHP Manual

SplFileInfo::getFilename

(PHP 5 >= 5.1.2)

SplFileInfo::getFilename — Gets the filename

Opis

public string SplFileInfo::getFilename ( void )

Gets the filename without any path information.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The filename.

Przykłady

Przykład #1 SplFileInfo::getFilename() example

<?php
$info = new SplFileInfo('foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('http://www.php.net/');
var_dump($info->getFilename());

$info = new SplFileInfo('http://www.php.net/svn.php');
var_dump($info->getFilename());
?>

Powyższy przykład wyświetli coś podobnego do:

string(7) "foo.txt"
string(7) "foo.txt"
string(0) ""
string(7) "svn.php"

Zobacz też:

  • SplFileInfo::getBasename() - Gets the base name of the file

SplFileInfo::getFileInfo
SplFileInfo::getGroup
SplFileInfo


Gets the file group

SplFileInfo::getFilename
SplFileInfo::getInode
SplFileInfo
PHP Manual

SplFileInfo::getGroup

(PHP 5 >= 5.1.2)

SplFileInfo::getGroup — Gets the file group

Opis

public int SplFileInfo::getGroup ( void )

Gets the file group. The group ID is returned in numerical format.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The group id in numerical format.

Błędy/Wyjątki

Throws RuntimeException on error.

Przykłady

Przykład #1 SplFileInfo::getGroup() example

<?php
$info = new SplFileInfo(__FILE__);
print_r(posix_getgrgid($info->getGroup()));
?>

Powyższy przykład wyświetli coś podobnego do:

Zobacz też:

  • posix_getgrgid() - Return info about a group by group id

SplFileInfo::getFilename
SplFileInfo::getInode
SplFileInfo


Gets the inode for the file

SplFileInfo::getGroup
SplFileInfo::getLinkTarget
SplFileInfo
PHP Manual

SplFileInfo::getInode

(PHP 5 >= 5.1.2)

SplFileInfo::getInode — Gets the inode for the file

Opis

public int SplFileInfo::getInode ( void )

Gets the inode number for the filesystem object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the inode number for the filesystem object.

Błędy/Wyjątki

Throws RuntimeException on error.

Zobacz też:

  • fileinode() - Pobiera i-węzeł pliku

SplFileInfo::getGroup
SplFileInfo::getLinkTarget
SplFileInfo


Gets the target of a link

SplFileInfo::getInode
SplFileInfo::getMTime
SplFileInfo
PHP Manual

SplFileInfo::getLinkTarget

(PHP 5 >= 5.2.2)

SplFileInfo::getLinkTarget — Gets the target of a link

Opis

public string SplFileInfo::getLinkTarget ( void )

Gets the target of a filesystem link.

Informacja:

The target may not be the real path on the filesystem. Use SplFileInfo::getRealPath() to determine the true path on the filesystem.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the target of the filesystem link.

Błędy/Wyjątki

Throws RuntimeException on error.

Przykłady

Przykład #1 SplFileInfo::getLinkTarget() example

<?php
$info = new SplFileInfo('/Users/bbieber/workspace');
if ($info->isLink()) {
    var_dump($info->getLinkTarget());
    var_dump($info->getRealPath());
}
?>

Powyższy przykład wyświetli coś podobnego do:

string(19) "Documents/workspace"
string(34) "/Users/bbieber/Documents/workspace"

Zobacz też:

  • SplFileInfo::isLink() - Tells if the file is a link
  • SplFileInfo::getRealPath() - Gets absolute path to file

SplFileInfo::getInode
SplFileInfo::getMTime
SplFileInfo


Gets the last modified time

SplFileInfo::getLinkTarget
SplFileInfo::getOwner
SplFileInfo
PHP Manual

SplFileInfo::getMTime

(PHP 5 >= 5.1.2)

SplFileInfo::getMTime — Gets the last modified time

Opis

public int SplFileInfo::getMTime ( void )

Returns the time when the contents of the file were changed. The time returned is a Unix timestamp.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the last modified time for the file, in a Unix timestamp.

Zobacz też:

  • filemtime() - Pobiera czas ostatniej modyfikacji pliku

SplFileInfo::getLinkTarget
SplFileInfo::getOwner
SplFileInfo


Gets the owner of the file

SplFileInfo::getMTime
SplFileInfo::getPath
SplFileInfo
PHP Manual

SplFileInfo::getOwner

(PHP 5 >= 5.1.2)

SplFileInfo::getOwner — Gets the owner of the file

Opis

public int SplFileInfo::getOwner ( void )

Gets the file owner. The owner ID is returned in numerical format.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The owner id in numerical format.

Błędy/Wyjątki

Throws RuntimeException on error.

Przykłady

Przykład #1 SplFileInfo::getOwner() example

<?php
$info = new SplFileInfo('file.txt');
print_r(posix_getpwuid($info->getOwner()));
?>

Zobacz też:

  • posix_getpwuid() - Return info about a user by user id
  • SplFileInfo::getGroup() - Gets the file group

SplFileInfo::getMTime
SplFileInfo::getPath
SplFileInfo


Gets the path without filename

SplFileInfo::getOwner
SplFileInfo::getPathInfo
SplFileInfo
PHP Manual

SplFileInfo::getPath

(PHP 5 >= 5.1.2)

SplFileInfo::getPath — Gets the path without filename

Opis

public string SplFileInfo::getPath ( void )

Returns the path to the file, omitting the filename and any trailing slash.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the path to the file.

Przykłady

Przykład #1 SplFileInfo::getPath() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPath());

$info = new SplFileInfo('/usr/');
var_dump($info->getPath());?>

Powyższy przykład wyświetli coś podobnego do:

string(8) "/usr/bin"
string(4) "/usr"

Zobacz też:

  • SplFileInfo::getRealPath() - Gets absolute path to file
  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getPathInfo() - Gets an SplFileInfo object for the path

SplFileInfo::getOwner
SplFileInfo::getPathInfo
SplFileInfo


Gets an SplFileInfo object for the path

SplFileInfo::getPath
SplFileInfo::getPathname
SplFileInfo
PHP Manual

SplFileInfo::getPathInfo

(PHP 5 >= 5.1.2)

SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path

Opis

public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )

Gets an SplFileInfo object for the parent of the current file.

Parametry

class_name

Name of an SplFileInfo derived class to use.

Zwracane wartości

Returns an SplFileInfo object for the parent path of the file.

Przykłady

Przykład #1 SplFileInfo::getPathInfo() example

<?php
$info = new SplFileInfo('/usr/bin/php');
$parent_info = $info->getPathInfo();
var_dump($parent_info->getRealPath());
?>

Powyższy przykład wyświetli coś podobnego do:

string(8) "/usr/bin"

Zobacz też:

  • SplFileInfo::setInfoClass() - Sets the class used with getFileInfo and getPathInfo

SplFileInfo::getPath
SplFileInfo::getPathname
SplFileInfo


Gets the path to the file

SplFileInfo::getPathInfo
SplFileInfo::getPerms
SplFileInfo
PHP Manual

SplFileInfo::getPathname

(PHP 5 >= 5.1.2)

SplFileInfo::getPathname — Gets the path to the file

Opis

public string SplFileInfo::getPathname ( void )

Returns the path to the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The path to the file.

Przykłady

Przykład #1 SplFileInfo::getPathname() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPathname());
?>

Powyższy przykład wyświetli coś podobnego do:

string(12) "/usr/bin/php"

Zobacz też:

  • SplFileInfo::getRealPath() - Gets absolute path to file

SplFileInfo::getPathInfo
SplFileInfo::getPerms
SplFileInfo


Gets file permissions

SplFileInfo::getPathname
SplFileInfo::getRealPath
SplFileInfo
PHP Manual

SplFileInfo::getPerms

(PHP 5 >= 5.1.2)

SplFileInfo::getPerms — Gets file permissions

Opis

public int SplFileInfo::getPerms ( void )

Gets the file permissions for the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the file permissions.

Przykłady

Przykład #1 SplFileInfo::getPerms() example

<?php
$info = new SplFileInfo('/tmp');
echo substr(sprintf('%o', $info->getPerms()), -4);

$info = new SplFileInfo(__FILE__);
echo substr(sprintf('%o', $info->getPerms()), -4);
?>

Powyższy przykład wyświetli coś podobnego do:

1777
0644

SplFileInfo::getPathname
SplFileInfo::getRealPath
SplFileInfo


Gets absolute path to file

SplFileInfo::getPerms
SplFileInfo::getSize
SplFileInfo
PHP Manual

SplFileInfo::getRealPath

(PHP 5 >= 5.2.2)

SplFileInfo::getRealPath — Gets absolute path to file

Opis

public string SplFileInfo::getRealPath ( void )

This method expands all symbolic links, resolves relative references and returns the real path to the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the path to the file.

Przykłady

Przykład #1 SplFileInfo::getRealPath() example

<?php
$info = new SplFileInfo('/..//./../../'.__FILE__);
var_dump($info->getRealPath());

$info = new SplFileInfo('/tmp');
var_dump($info->getRealPath());
?>

Powyższy przykład wyświetli coś podobnego do:

string(28) "/private/tmp/phptempfile.php"
string(12) "/private/tmp"

Zobacz też:

  • SplFileInfo::isLink() - Tells if the file is a link

SplFileInfo::getPerms
SplFileInfo::getSize
SplFileInfo


Gets file size

SplFileInfo::getRealPath
SplFileInfo::getType
SplFileInfo
PHP Manual

SplFileInfo::getSize

(PHP 5 >= 5.1.2)

SplFileInfo::getSize — Gets file size

Opis

public int SplFileInfo::getSize ( void )

Returns the filesize in bytes for the file referenced.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The filesize in bytes.

Błędy/Wyjątki

A RuntimeException will be thrown if the file does not exist or an error occurs.

Zobacz też:

  • filesize() - Pobiera rozmiar pliku

SplFileInfo::getRealPath
SplFileInfo::getType
SplFileInfo


Gets file type

SplFileInfo::getSize
SplFileInfo::isDir
SplFileInfo
PHP Manual

SplFileInfo::getType

(PHP 5 >= 5.1.2)

SplFileInfo::getType — Gets file type

Opis

public string SplFileInfo::getType ( void )

Returns the type of the file referenced.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A string representing the type of the entry. May be one of file, link, or dir

Błędy/Wyjątki

Throws a RuntimeException on error.

Przykłady

Przykład #1 SplFileInfo::getType() example

<?php

$info = new SplFileInfo(__FILE__);
echo $info->getType().PHP_EOL;

$info = new SplFileInfo(dirname(__FILE__));
echo $info->getType();

?>

Powyższy przykład wyświetli coś podobnego do:

file
dir

SplFileInfo::getSize
SplFileInfo::isDir
SplFileInfo


Tells if the file is a directory

SplFileInfo::getType
SplFileInfo::isExecutable
SplFileInfo
PHP Manual

SplFileInfo::isDir

(PHP 5 >= 5.1.2)

SplFileInfo::isDir — Tells if the file is a directory

Opis

public bool SplFileInfo::isDir ( void )

This method can be used to determine if the file is a directory.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if a directory, FALSE otherwise.

Przykłady

Przykład #1 SplFileInfo::isDir() example

<?php
$d = new SplFileInfo(dirname(__FILE__));
var_dump($d->isDir());

$d = new SplFileInfo(__FILE__);
var_dump($d->isDir());
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(false)

SplFileInfo::getType
SplFileInfo::isExecutable
SplFileInfo


Tells if the file is executable

SplFileInfo::isDir
SplFileInfo::isFile
SplFileInfo
PHP Manual

SplFileInfo::isExecutable

(PHP 5 >= 5.1.2)

SplFileInfo::isExecutable — Tells if the file is executable

Opis

public bool SplFileInfo::isExecutable ( void )

Checks if the file is executable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if executable, FALSE otherwise.

Przykłady

Przykład #1 SplFileInfo::isExecutable() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->isExecutable());

$info = new SplFileInfo('/usr/bin');
var_dump($info->isExecutable());

$info = new SplFileInfo('foo');
var_dump($info->isExecutable());
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
bool(false)

SplFileInfo::isDir
SplFileInfo::isFile
SplFileInfo


Tells if the object references a regular file

SplFileInfo::isExecutable
SplFileInfo::isLink
SplFileInfo
PHP Manual

SplFileInfo::isFile

(PHP 5 >= 5.1.2)

SplFileInfo::isFile — Tells if the object references a regular file

Opis

public bool SplFileInfo::isFile ( void )

Checks if the file referenced by this SplFileInfo object exists and is a regular file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the file exists and is a regular file (not a link), FALSE otherwise.

Przykłady

Przykład #1 SplFileInfo::isFile() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isFile());

$info = new SplFileInfo(dirname(__FILE__));
var_dump($info->isFile());
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(false)

SplFileInfo::isExecutable
SplFileInfo::isLink
SplFileInfo


Tells if the file is a link

SplFileInfo::isFile
SplFileInfo::isReadable
SplFileInfo
PHP Manual

SplFileInfo::isLink

(PHP 5 >= 5.1.2)

SplFileInfo::isLink — Tells if the file is a link

Opis

public bool SplFileInfo::isLink ( void )

Use this method to check if the file referenced by the SplFileInfo object is a link.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the file is a link, FALSE otherwise.

Przykłady

Przykład #1 SplFileInfo::isLink() example

<?php
$info = new SplFileInfo('/path/to/symlink');
if ($info->isLink()) {
    echo 'The real path is '.$info->getRealPath();
}
?>

Zobacz też:

  • SplFileInfo::getRealPath() - Gets absolute path to file

SplFileInfo::isFile
SplFileInfo::isReadable
SplFileInfo


Tells if file is readable

SplFileInfo::isLink
SplFileInfo::isWritable
SplFileInfo
PHP Manual

SplFileInfo::isReadable

(PHP 5 >= 5.1.2)

SplFileInfo::isReadable — Tells if file is readable

Opis

public bool SplFileInfo::isReadable ( void )

Check if the file is readable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if readable, FALSE otherwise.

Przykłady

Przykład #1 SplFileInfo::isReadable() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isReadable());

$info = new SplFileInfo('foo');
var_dump($info->isReadable());
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(false)

SplFileInfo::isLink
SplFileInfo::isWritable
SplFileInfo


Tells if the entry is writable

SplFileInfo::isReadable
SplFileInfo::openFile
SplFileInfo
PHP Manual

SplFileInfo::isWritable

(PHP 5 >= 5.1.2)

SplFileInfo::isWritable — Tells if the entry is writable

Opis

public bool SplFileInfo::isWritable ( void )

Checks if the current entry is writable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if writable, FALSE otherwise;

SplFileInfo::isReadable
SplFileInfo::openFile
SplFileInfo


Gets an SplFileObject object for the file

SplFileInfo::isWritable
SplFileInfo::setFileClass
SplFileInfo
PHP Manual

SplFileInfo::openFile

(PHP 5 >= 5.1.2)

SplFileInfo::openFile — Gets an SplFileObject object for the file

Opis

public SplFileObject SplFileInfo::openFile ([ string $open_mode = r [, bool $use_include_path = false [, resource $context = NULL ]]] )

Creates an SplFileObject object of the file. This is useful because SplFileObject contains additional methods for manipulating the file whereas SplFileInfo is only useful for gaining information, like whether the file is writable.

Parametry

open_mode

The mode for opening the file. See the fopen() documentation for descriptions of possible modes. The default is read only.

use_include_path

Gdy jest ustawiony na TRUE to nazwa pliku jest szukana wewnątrz katalogów określonych za pomocą include_path

context

Opis kontekstów podano w części podręcznika poświęconej kontekstom.

Zwracane wartości

The opened file as an SplFileObject object.

Błędy/Wyjątki

A RuntimeException if the file cannot be opened (e.g. insufficient access rights).

Przykłady

Przykład #1 SplFileInfo::openFile() example

<?php
$fileinfo = new SplFileInfo('/tmp/foo.txt');

if ($fileinfo->isWritable()) {

    $fileobj = $fileinfo->openFile('a');

    $fileobj->fwrite("appended this sample text");
}
?>

Zobacz też:

  • SplFileObject
  • stream_context_create() - Create a streams context
  • fopen() - Otwiera plik lub URL

SplFileInfo::isWritable
SplFileInfo::setFileClass
SplFileInfo


Sets the class name used with SplFileInfo::openFile

SplFileInfo::openFile
SplFileInfo::setInfoClass
SplFileInfo
PHP Manual

SplFileInfo::setFileClass

(PHP 5 >= 5.1.2)

SplFileInfo::setFileClass — Sets the class name used with SplFileInfo::openFile()

Opis

public void SplFileInfo::setFileClass ([ string $class_name ] )

Set the class name which SplFileInfo will use to open files with when openFile() is called. The class name passed to this method must be derived from SplFileObject.

Parametry

class_name

The class name to use when openFile() is called.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplFileInfo::setFileClass() example

<?php
// Create a class extending SplFileObject
class MyFoo extends SplFileObject {}

$info = new SplFileInfo(__FILE__);
// Set the class to use
$info->setFileClass('MyFoo');
var_dump($info->openFile());
?>

Powyższy przykład wyświetli coś podobnego do:

object(MyFoo)#2 (0) { }

Zobacz też:

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file

SplFileInfo::openFile
SplFileInfo::setInfoClass
SplFileInfo


Sets the class used with getFileInfo and getPathInfo

SplFileInfo::setFileClass
SplFileInfo::__toString
SplFileInfo
PHP Manual

SplFileInfo::setInfoClass

(PHP 5 >= 5.1.2)

SplFileInfo::setInfoClass — Sets the class used with getFileInfo and getPathInfo

Opis

public void SplFileInfo::setInfoClass ([ string $class_name ] )

Use this method to set a custom class which will be used when getFileInfo and getPathInfo are called. The class name passed to this method must be derived from SplFileInfo.

Parametry

class_name

The class name to use.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplFileInfo::setFileClass() example

<?php
// Define a class which extends SplFileInfo
class MyFoo extends SplFileInfo {}

$info = new SplFileInfo('foo');
// Set the class name to use
$info->setInfoClass('MyFoo');
var_dump($info->getFileInfo());
?>

Powyższy przykład wyświetli coś podobnego do:

object(MyFoo)#2 (0) { }

Zobacz też:

  • SplFileInfo::getFileInfo() - Gets an SplFileInfo object for the file

SplFileInfo::setFileClass
SplFileInfo::__toString
SplFileInfo


Returns the path to the file as a string

SplFileInfo::setInfoClass
SplFileObject
SplFileInfo
PHP Manual

SplFileInfo::__toString

(PHP 5 >= 5.1.2)

SplFileInfo::__toString — Returns the path to the file as a string

Opis

public void SplFileInfo::__toString ( void )

This method will return the file name of the referenced file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the path to the file.

Przykłady

Przykład #1 SplFileInfo::__toString() example

<?php
$info = new SplFileInfo('foo');
var_dump($info->__toString());
echo $info.PHP_EOL;

$info = new SplFileInfo('/usr/bin/php');
var_dump($info->__toString());
echo $info.PHP_EOL;
?>

Powyższy przykład wyświetli coś podobnego do:

string(3) "foo"
foo
string(12) "/usr/bin/php"
/usr/bin/php

SplFileInfo::setInfoClass
SplFileObject
SplFileInfo


The SplFileObject class

(PHP 5 >= 5.1.0)

Wstęp

The SplFileObject class offers an object oriented interface for a file.

Krótki opis klasy

SplFileObject extends SplFileInfo implements RecursiveIterator , Traversable , Iterator , SeekableIterator {
/* Stałe */
const integer DROP_NEW_LINE = 1 ;
const integer READ_AHEAD = 2 ;
const integer SKIP_EMPTY = 6 ;
const integer READ_CSV = 8 ;
/* Metody */
public __construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )
public string|array current ( void )
public bool eof ( void )
public bool fflush ( void )
public string fgetc ( void )
 public array fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )
public string fgets ( void )
public string fgetss ([ string $allowable_tags ] )
public bool flock ( int $operation [, int &$wouldblock ] )
public int fpassthru ( void )
public int fputcsv ( string $fields [, string $delimiter [, string $enclosure ]] )
public mixed fscanf ( string $format [, mixed &$... ] )
public int fseek ( int $offset [, int $whence = SEEK_SET ] )
public array fstat ( void )
public int ftell ( void )
public bool ftruncate ( int $size )
public int fwrite ( string $str [, int $length ] )
public void getChildren ( void )
public array getCsvControl ( void )
public int getFlags ( void )
public int getMaxLineLen ( void )
public bool hasChildren ( void )
public int key ( void )
public void next ( void )
public void rewind ( void )
public void seek ( int $line_pos )
 public void setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )
public void setFlags ( int $flags )
public void setMaxLineLen ( int $max_len )
public bool valid ( void )
/* Metody dziedziczone */
public SplFileInfo::__construct ( string $file_name )
public int SplFileInfo::getATime ( void )
public string SplFileInfo::getBasename ([ string $suffix ] )
public int SplFileInfo::getCTime ( void )
public string SplFileInfo::getExtension ( void )
public SplFileInfo SplFileInfo::getFileInfo ([ string $class_name ] )
public string SplFileInfo::getFilename ( void )
public int SplFileInfo::getGroup ( void )
public int SplFileInfo::getInode ( void )
public string SplFileInfo::getLinkTarget ( void )
public int SplFileInfo::getMTime ( void )
public int SplFileInfo::getOwner ( void )
public string SplFileInfo::getPath ( void )
public SplFileInfo SplFileInfo::getPathInfo ([ string $class_name ] )
public string SplFileInfo::getPathname ( void )
public int SplFileInfo::getPerms ( void )
public string SplFileInfo::getRealPath ( void )
public int SplFileInfo::getSize ( void )
public string SplFileInfo::getType ( void )
public bool SplFileInfo::isDir ( void )
public bool SplFileInfo::isExecutable ( void )
public bool SplFileInfo::isFile ( void )
public bool SplFileInfo::isLink ( void )
public bool SplFileInfo::isReadable ( void )
public bool SplFileInfo::isWritable ( void )
public SplFileObject SplFileInfo::openFile ([ string $open_mode = r [, bool $use_include_path = false [, resource $context = NULL ]]] )
public void SplFileInfo::setFileClass ([ string $class_name ] )
public void SplFileInfo::setInfoClass ([ string $class_name ] )
public void SplFileInfo::__toString ( void )
}

Stałe predefiniowane

SplFileObject::DROP_NEW_LINE

Drop newlines at the end of a line.

SplFileObject::READ_AHEAD

Read on rewind/next.

SplFileObject::SKIP_EMPTY

Skips empty lines in the file.

SplFileObject::READ_CSV

Read lines as CSV rows.

Spis treści

  • SplFileObject::__construct — Construct a new file object.
  • SplFileObject::current — Retrieve current line of file
  • SplFileObject::eof — Reached end of file
  • SplFileObject::fflush — Flushes the output to the file
  • SplFileObject::fgetc — Gets character from file
  • SplFileObject::fgetcsv — Gets line from file and parse as CSV fields
  • SplFileObject::fgets — Gets line from file
  • SplFileObject::fgetss — Gets line from file and strip HTML tags
  • SplFileObject::flock — Portable file locking
  • SplFileObject::fpassthru — Output all remaining data on a file pointer
  • SplFileObject::fputcsv — Output a field array as a CSV line
  • SplFileObject::fscanf — Parses input from file according to a format
  • SplFileObject::fseek — Seek to a position
  • SplFileObject::fstat — Gets information about the file
  • SplFileObject::ftell — Return current file position
  • SplFileObject::ftruncate — Truncates the file to a given length
  • SplFileObject::fwrite — Write to file
  • SplFileObject::getChildren — No purpose
  • SplFileObject::getCsvControl — Get the delimiter and enclosure character for CSV
  • SplFileObject::getCurrentLine — Alias of SplFileObject::fgets
  • SplFileObject::getFlags — Gets flags for the SplFileObject
  • SplFileObject::getMaxLineLen — Get maximum line length
  • SplFileObject::hasChildren — SplFileObject does not have children
  • SplFileObject::key — Get line number
  • SplFileObject::next — Read next line
  • SplFileObject::rewind — Rewind the file to the first line
  • SplFileObject::seek — Seek to specified line
  • SplFileObject::setCsvControl — Set the delimiter and enclosure character for CSV
  • SplFileObject::setFlags — Sets flags for the SplFileObject
  • SplFileObject::setMaxLineLen — Set maximum line length
  • SplFileObject::__toString — Alias of SplFileObject::current
  • SplFileObject::valid — Not at EOF
SplFileInfo::__toString
SplFileObject::__construct
Obsługa plików


Construct a new file object.

SplFileObject
SplFileObject::current
SplFileObject
PHP Manual

SplFileObject::__construct

(PHP 5 >= 5.1.0)

SplFileObject::__construct — Construct a new file object.

Opis

public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )

Construct a new file object.

Parametry

filename

The file to read.

Wskazówka

Jeśli włączona jest dyrektywa konfiguracyjna fopen wrappers, możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz fopen wrappers aby uzyskać listę obsługiwanych protokołów.

open_mode

The mode in which to open the file. See fopen() for a list of allowed modes.

use_include_path

Whether to search in the include_path for filename.

context

A valid context resource created with stream_context_create().

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws a RuntimeException if the filename cannot be opened.

Przykłady

Przykład #1 SplFileObject::__construct() example

This example opens the current file and iterates over its contents line by line.

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $line) {
    echo $line;
}
?>

Powyższy przykład wyświetli coś podobnego do:

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $line) {
    echo $line;
}
?>

Zobacz też:

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file
  • fopen() - Otwiera plik lub URL

SplFileObject
SplFileObject::current
SplFileObject


Retrieve current line of file

SplFileObject::__construct
SplFileObject::eof
SplFileObject
PHP Manual

SplFileObject::current

(PHP 5 >= 5.1.0)

SplFileObject::current — Retrieve current line of file

Opis

public string|array SplFileObject::current ( void )

Retrieves the current line of the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Retrieves the current line of the file. If the SplFileObject::READ_CSV flag is set, this method returns an array containing the current line parsed as CSV data.

Przykłady

Przykład #1 SplFileObject::current() example

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $k => $line) {
   echo ($file->key() + 1) . ': ' . $file->current();
}
?>

Powyższy przykład wyświetli coś podobnego do:

1: <?php
2: $file = new SplFileObject(__FILE__);
3: foreach ($file as $line) {
4:     echo ($file->key() + 1) . ': ' . $file->current();
5: }
6: ?>

Zobacz też:

  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

SplFileObject::__construct
SplFileObject::eof
SplFileObject


Reached end of file

SplFileObject::current
SplFileObject::fflush
SplFileObject
PHP Manual

SplFileObject::eof

(PHP 5 >= 5.1.0)

SplFileObject::eof — Reached end of file

Opis

public bool SplFileObject::eof ( void )

Determine whether the end of file has been reached

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if file is at EOF, FALSE otherwise.

Przykłady

Przykład #1 SplFileObject::eof() example

<?php
$file = new SplFileObject("fruits.txt");
while ( ! $file->eof()) {
    echo $file->fgets();
}
?>

Powyższy przykład wyświetli coś podobnego do:

apple
banana
cherry
date
elderberry

Zobacz też:

  • SplFileObject::valid() - Not at EOF
  • feof() - Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)

SplFileObject::current
SplFileObject::fflush
SplFileObject


Flushes the output to the file

SplFileObject::eof
SplFileObject::fgetc
SplFileObject
PHP Manual

SplFileObject::fflush

(PHP 5 >= 5.1.0)

SplFileObject::fflush — Flushes the output to the file

Opis

public bool SplFileObject::fflush ( void )

Forces a write of all buffered output to the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 SplFileObject::fflush() example

<?php
$file = new SplFileObject('misc.txt', 'r+');
$file->rewind();
$file->fwrite("Foo");
$file->fflush();
$file->ftruncate($file->ftell());
?>

Zobacz też:

  • SplFileObject::fwrite() - Write to file

SplFileObject::eof
SplFileObject::fgetc
SplFileObject


Gets character from file

SplFileObject::fflush
SplFileObject::fgetcsv
SplFileObject
PHP Manual

SplFileObject::fgetc

(PHP 5 >= 5.1.0)

SplFileObject::fgetc — Gets character from file

Opis

public string SplFileObject::fgetc ( void )

Gets a character from the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string containing a single character read from the file or FALSE on EOF.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 SplFileObject::fgetc() example

<?php
$file = new SplFileObject('file.txt');
while (false !== ($char = $file->fgetc())) {
    echo "$char\n";
}
?>

Zobacz też:

  • SplFileObject::fgets() - Gets line from file

SplFileObject::fflush
SplFileObject::fgetcsv
SplFileObject


Gets line from file and parse as CSV fields

SplFileObject::fgetc
SplFileObject::fgets
SplFileObject
PHP Manual

SplFileObject::fgetcsv

(PHP 5 >= 5.1.0)

SplFileObject::fgetcsv — Gets line from file and parse as CSV fields

Opis

 public array SplFileObject::fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )

Gets a line from the file which is in CSV format and returns an array containing the fields read.

Parametry

delimiter

The field delimiter (one character only). Defaults as a comma or the value set using SplFileObject::setCsvControl().

enclosure

The field enclosure character (one character only). Defaults as a double quotation mark or the value set using SplFileObject::setCsvControl().

escape

The escape character (one character only). Defaults as a backslash (\) or the value set using SplFileObject::setCsvControl().

Zwracane wartości

Returns an indexed array containing the fields read, or FALSE on error.

Informacja:

A blank line in a CSV file will be returned as an array comprising a single NULL field unless using SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE, in which case empty lines are skipped.

Przykłady

Przykład #1 SplFileObject::fgetcsv() example

<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
    var_dump($file->fgetcsv());
}
?>

Przykład #2 SplFileObject::READ_CSV example

<?php
$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    list($animal, $class, $legs) = $row;
    printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>

Contents of animals.csv

crocodile,reptile,4
dolphin,mammal,0
duck,bird,2
koala,mammal,4
salmon,fish,0

Powyższy przykład wyświetli coś podobnego do:

A crocodile is a reptile with 4 legs
A dolphin is a mammal with 0 legs
A duck is a bird with 2 legs
A koala is a mammal with 4 legs
A salmon is a fish with 0 legs

Zobacz też:

  • SplFileObject::setCsvControl() - Set the delimiter and enclosure character for CSV
  • SplFileObject::setFlags() - Sets flags for the SplFileObject
  • SplFileObject::READ_CSV
  • SplFileObject::current() - Retrieve current line of file

SplFileObject::fgetc
SplFileObject::fgets
SplFileObject


Gets line from file

SplFileObject::fgetcsv
SplFileObject::fgetss
SplFileObject
PHP Manual

SplFileObject::fgets

(PHP 5 >= 5.1.0)

SplFileObject::fgets — Gets line from file

Opis

public string SplFileObject::fgets ( void )

Gets a line from the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string containing the next line from the file, or FALSE on error.

Błędy/Wyjątki

Throws a RuntimeException if the file cannot be read.

Przykłady

Przykład #1 SplFileObject::fgets() example

This example simply outputs the contents of file.txt line-by-line.

<?php
$file = new SplFileObject("file.txt");
while (!$file->eof()) {
    echo $file->fgets();
}
?>

Zobacz też:

  • fgets() - Pobiera linię ze wskaźnika pliku
  • SplFileObject::fgetss() - Gets line from file and strip HTML tags
  • SplFileObject::fgetc() - Gets character from file
  • SplFileObject::current() - Retrieve current line of file

SplFileObject::fgetcsv
SplFileObject::fgetss
SplFileObject


Gets line from file and strip HTML tags

SplFileObject::fgets
SplFileObject::flock
SplFileObject
PHP Manual

SplFileObject::fgetss

(PHP 5 >= 5.1.0)

SplFileObject::fgetss — Gets line from file and strip HTML tags

Opis

public string SplFileObject::fgetss ([ string $allowable_tags ] )

Identical to SplFileObject::fgets(), except that SplFileObject::fgetss() attempts to strip any HTML and PHP tags from the text it reads.

Parametry

allowable_tags

You can use the optional third parameter to specify tags which should not be stripped.

Zwracane wartości

Returns a string containing the next line of the file with HTML and PHP code stripped, or FALSE on error.

Przykłady

Przykład #1 SplFileObject::fgetss() example

<?php
$str = <<<EOD
<html><body>
 <p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents("sample.php", $str);

$file = new SplFileObject("sample.php");
while (!$file->eof()) {
    echo $file->fgetss();
}
?>

Powyższy przykład wyświetli coś podobnego do:

 Welcome! Today is the  of .

Text outside of the HTML block.

Zobacz też:

  • fgetss() - Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
  • SplFileObject::fgets() - Gets line from file
  • SplFileObject::fgetc() - Gets character from file
  • SplFileObject::current() - Retrieve current line of file

SplFileObject::fgets
SplFileObject::flock
SplFileObject


Portable file locking

SplFileObject::fgetss
SplFileObject::fpassthru
SplFileObject
PHP Manual

SplFileObject::flock

(PHP 5 >= 5.1.0)

SplFileObject::flock — Portable file locking

Opis

public bool SplFileObject::flock ( int $operation [, int &$wouldblock ] )

Locks or unlocks the file in the same portable way as flock().

Parametry

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB to not block while locking (not supported on Windows).

wouldblock

Set to TRUE if the lock would block (EWOULDBLOCK errno condition).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 SplFileObject::flock() example

<?php
$file = new SplFileObject("/tmp/lock.txt", "w");
if ($file->flock(LOCK_EX)) { // do an exclusive lock
    $file->ftruncate(0);     // truncate file
    $file->fwrite("Write something here\n");
    $file->flock(LOCK_UN);   // release the lock
} else {
    echo "Couldn't get the lock!";
}
?>

Zobacz też:

  • flock() - Portable advisory file locking

SplFileObject::fgetss
SplFileObject::fpassthru
SplFileObject


Output all remaining data on a file pointer

SplFileObject::flock
SplFileObject::fputcsv
SplFileObject
PHP Manual

SplFileObject::fpassthru

(PHP 5 >= 5.1.0)

SplFileObject::fpassthru — Output all remaining data on a file pointer

Opis

public int SplFileObject::fpassthru ( void )

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call SplFileObject::rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the number of characters read from handle and passed through to the output.

Przykłady

Przykład #1 SplFileObject::fpassthru() example

<?php

// Open the file in binary mode
$file = new SplFileObject("./img/ok.png", "rb");

// Send the right headers
header("Content-Type: image/png");
header("Content-Length: " . $file->getSize());

// Dump the picture and end script
$file->fpassthru();
exit;

?>

Zobacz też:

  • fpassthru() - Output all remaining data on a file pointer

SplFileObject::flock
SplFileObject::fputcsv
SplFileObject


Output a field array as a CSV line

SplFileObject::fpassthru
SplFileObject::fscanf
SplFileObject
PHP Manual

SplFileObject::fputcsv

(No version information available, might only be in SVN)

SplFileObject::fputcsv — Output a field array as a CSV line

Opis

public int SplFileObject::fputcsv ( string $fields [, string $delimiter [, string $enclosure ]] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

fields

delimiter

enclosure

Zwracane wartości

SplFileObject::fpassthru
SplFileObject::fscanf
SplFileObject


Parses input from file according to a format

SplFileObject::fputcsv
SplFileObject::fseek
SplFileObject
PHP Manual

SplFileObject::fscanf

(PHP 5 >= 5.1.0)

SplFileObject::fscanf — Parses input from file according to a format

Opis

public mixed SplFileObject::fscanf ( string $format [, mixed &$... ] )

Reads a line from the file and interprets it according to the specified format, which is described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the line from the file. This means that even a tab \t in the format string can match a single space character in the input stream.

Parametry

format

The specified format as described in the sprintf() documentation.

...

The optional assigned values.

Zwracane wartości

If only one parameter is passed to this method, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Przykłady

Przykład #1 SplFileObject::fscanf() example

<?php
$file = new SplFileObject("misc.txt");
while ($userinfo = $file->fscanf("%s %s %s")) {
    list ($name, $profession, $countrycode) = $userinfo;
    // Do something with $name $professi
}
?>

Contents of users.txt

javier   argonaut    pe
hiroshi  sculptor    jp
robert   slacker     us
luigi    florist     it

Zobacz też:

  • fscanf() - Przetwarza dane z pliku według formatu

SplFileObject::fputcsv
SplFileObject::fseek
SplFileObject


Seek to a position

SplFileObject::fscanf
SplFileObject::fstat
SplFileObject
PHP Manual

SplFileObject::fseek

(PHP 5 >= 5.1.0)

SplFileObject::fseek — Seek to a position

Opis

public int SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] )

Seek to a position in the file measured in bytes from the beginning of the file, obtained by adding offset to the position specified by whence.

Parametry

offset

The offset. A negative value can be used to move backwards through the file which is useful when SEEK_END is used as the whence value.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

If whence is not specified, it is assumed to be SEEK_SET.

Zwracane wartości

Returns 0 if the seek was successful, -1 otherwise. Note that seeking past EOF is not considered an error.

Przykłady

Przykład #1 SplFileObject::fseek() example

<?php
$file = new SplFileInfo("somefile.txt");

// Read first line
$data = $file->fgets();

// Move back to the beginning of the file
// Same as $file->rewind();
$file->fseek(0);
?>

Zobacz też:

  • fseek() - Seeks on a file pointer

SplFileObject::fscanf
SplFileObject::fstat
SplFileObject


Gets information about the file

SplFileObject::fseek
SplFileObject::ftell
SplFileObject
PHP Manual

SplFileObject::fstat

(PHP 5 >= 5.1.0)

SplFileObject::fstat — Gets information about the file

Opis

public array SplFileObject::fstat ( void )

Gathers the statistics of the file. Behaves identically to fstat().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

Przykłady

Przykład #1 SplFileObject::fstat() example

<?php
$file = new SplFileObject("/etc/passwd");
$stat = $file->fstat();

// Print only the associative part
print_r(array_slice($stat, 13));

?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

Zobacz też:

  • fstat() - Pobiera informacje o pliku używając otwartego wskaźnika pliku
  • stat() - Gives information about a file

SplFileObject::fseek
SplFileObject::ftell
SplFileObject


Return current file position

SplFileObject::fstat
SplFileObject::ftruncate
SplFileObject
PHP Manual

SplFileObject::ftell

(PHP 5 >= 5.1.0)

SplFileObject::ftell — Return current file position

Opis

public int SplFileObject::ftell ( void )

Returns the position of the file pointer which represents the current offset in the file stream.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the position of the file pointer as an integer, or FALSE on error.

Przykłady

Przykład #1 SplFileObject::ftell() example

<?php
$file = new SplFileObject("/etc/passwd");

// Read first line
$data = $file->fgets();

// Where are we?
echo $file->ftell();
?>

Zobacz też:

  • ftell() - Mówi o pozycji odczyt/zapis wskaźnika pliku

SplFileObject::fstat
SplFileObject::ftruncate
SplFileObject


Truncates the file to a given length

SplFileObject::ftell
SplFileObject::fwrite
SplFileObject
PHP Manual

SplFileObject::ftruncate

(PHP 5 >= 5.1.0)

SplFileObject::ftruncate — Truncates the file to a given length

Opis

public bool SplFileObject::ftruncate ( int $size )

Truncates the file to size bytes.

Parametry

size

The size to truncate to.

Informacja:

If size is larger than the file it is extended with null bytes.

If size is smaller than the file, the extra data will be lost.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 SplFileObject::ftruncate() example

<?php
// Create file containing "Hello World!"
$file = new SplFileObject("/tmp/ftruncate", "w+");
$file->fwrite("Hello World!");

// Truncate to 5 bytes
$file->ftruncate(5);

// Rewind and read data
$file->rewind();
echo $file->fgets();
?>

Powyższy przykład wyświetli coś podobnego do:

Hello

Zobacz też:

  • ftruncate() - Przycina plik do podanej długości

SplFileObject::ftell
SplFileObject::fwrite
SplFileObject


Write to file

SplFileObject::ftruncate
SplFileObject::getChildren
SplFileObject
PHP Manual

SplFileObject::fwrite

(PHP 5 >= 5.1.0)

SplFileObject::fwrite — Write to file

Opis

public int SplFileObject::fwrite ( string $str [, int $length ] )

Writes the contents of string to the file

Parametry

str

The string to be written to the file.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Zwracane wartości

Returns the number of bytes written, or NULL on error.

Przykłady

Przykład #1 SplFileObject::fwrite() example

<?php
$file = new SplFileObject("fwrite.txt", "w");
$written = $file->fwrite("12345");
echo "Wrote $written bytes to file";
?>

Powyższy przykład wyświetli coś podobnego do:

Wrote 5 bytes to file

Zobacz też:

  • fwrite() - Zapis pliku binarnie bezpieczny

SplFileObject::ftruncate
SplFileObject::getChildren
SplFileObject


No purpose

SplFileObject::fwrite
SplFileObject::getCsvControl
SplFileObject
PHP Manual

SplFileObject::getChildren

(PHP 5 >= 5.1.0)

SplFileObject::getChildren — No purpose

Opis

public void SplFileObject::getChildren ( void )

An SplFileObject does not have children so this method returns NULL.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry.

SplFileObject::fwrite
SplFileObject::getCsvControl
SplFileObject


Get the delimiter and enclosure character for CSV

SplFileObject::getChildren
SplFileObject::getCurrentLine
SplFileObject
PHP Manual

SplFileObject::getCsvControl

(PHP 5 >= 5.2.0)

SplFileObject::getCsvControl — Get the delimiter and enclosure character for CSV

Opis

public array SplFileObject::getCsvControl ( void )

Gets the delimiter and enclosure character used for parsing CSV fields.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an indexed array containing the delimiter and enclosure character.

Przykłady

Przykład #1 SplFileObject::getCsvControl() example

<?php
$file = new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => ,
    [1] => "
)

Zobacz też:

  • SplFileObject::setCsvControl() - Set the delimiter and enclosure character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

SplFileObject::getChildren
SplFileObject::getCurrentLine
SplFileObject


Alias of SplFileObject::fgets

SplFileObject::getCsvControl
SplFileObject::getFlags
SplFileObject
PHP Manual

SplFileObject::getCurrentLine

(PHP 5 >= 5.1.2)

SplFileObject::getCurrentLine — Alias of SplFileObject::fgets()

Opis

This method is an alias of SplFileObject::fgets().

SplFileObject::getCsvControl
SplFileObject::getFlags
SplFileObject


Gets flags for the SplFileObject

SplFileObject::getCurrentLine
SplFileObject::getMaxLineLen
SplFileObject
PHP Manual

SplFileObject::getFlags

(PHP 5 >= 5.1.0)

SplFileObject::getFlags — Gets flags for the SplFileObject

Opis

public int SplFileObject::getFlags ( void )

Gets the flags set for an instance of SplFileObject as an integer.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer representing the flags.

Przykłady

Przykład #1 SplFileObject::getFlags() example

<?php
$file = new SplFileObject(__FILE__, "r");

if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo "Skipping empty lines\n";
} else {
    echo "Not skipping empty lines\n";
}

$file->setFlags(SplFileObject::SKIP_EMPTY);

if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo "Skipping empty lines\n";
} else {
    echo "Not skipping empty lines\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Not skipping empty lines
Skipping empty lines

Zobacz też:

  • SplFileObject::setFlags() - Sets flags for the SplFileObject

SplFileObject::getCurrentLine
SplFileObject::getMaxLineLen
SplFileObject


Get maximum line length

SplFileObject::getFlags
SplFileObject::hasChildren
SplFileObject
PHP Manual

SplFileObject::getMaxLineLen

(PHP 5 >= 5.1.0)

SplFileObject::getMaxLineLen — Get maximum line length

Opis

public int SplFileObject::getMaxLineLen ( void )

Gets the maximum line length as set by SplFileObject::setMaxLineLen().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the maximum line length if one has been set with SplFileObject::setMaxLineLen(), default is 0.

Przykłady

Przykład #1 SplFileObject::getMaxLineLen() example

<?php
$file = new SplFileObject("file.txt");
var_dump($file->getMaxLineLen());

$file->setMaxLineLen(20);
var_dump($file->getMaxLineLen());
?>

Powyższy przykład wyświetli coś podobnego do:

int(0)
int(20)

Zobacz też:

  • Classname::Method()

SplFileObject::getFlags
SplFileObject::hasChildren
SplFileObject


SplFileObject does not have children

SplFileObject::getMaxLineLen
SplFileObject::key
SplFileObject
PHP Manual

SplFileObject::hasChildren

(PHP 5 >= 5.1.2)

SplFileObject::hasChildren — SplFileObject does not have children

Opis

public bool SplFileObject::hasChildren ( void )

An SplFileObject does not have children so this method always return FALSE.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns FALSE

Zobacz też:

  • RecursiveIterator::hasChildren() - Returns if an iterator can be created fot the current entry.

SplFileObject::getMaxLineLen
SplFileObject::key
SplFileObject


Get line number

SplFileObject::hasChildren
SplFileObject::next
SplFileObject
PHP Manual

SplFileObject::key

(PHP 5 >= 5.1.0)

SplFileObject::key — Get line number

Opis

public int SplFileObject::key ( void )

Gets the current line number.

Informacja:

This number may not reflect the actual line number in the file if SplFileObject::setMaxLineLen() is used to read fixed lengths of the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current line number.

Przykłady

Przykład #1 SplFileObject::key() example

<?php
$file = new SplFileObject("lipsum.txt");
foreach ($file as $line) {
    echo $file->key() . ". " . $line;
}
?>

Powyższy przykład wyświetli coś podobnego do:

0. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
1. Duis nec sapien felis, ac sodales nisl.
2. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Przykład #2 SplFileObject::key() example with SplFileObject::setMaxLineLen()

<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
    echo $file->key() . ". " . $line . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

0. Lorem ipsum dolor s
1. it amet, consectetu
2. r adipiscing elit.
3.

4. Duis nec sapien fel
5. is, ac sodales nisl
6. .

7. Lorem ipsum dolor s
8. it amet, consectetu
9. r adipiscing elit.

Zobacz też:

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

SplFileObject::hasChildren
SplFileObject::next
SplFileObject


Read next line

SplFileObject::key
SplFileObject::rewind
SplFileObject
PHP Manual

SplFileObject::next

(PHP 5 >= 5.1.0)

SplFileObject::next — Read next line

Opis

public void SplFileObject::next ( void )

Moves ahead to the next line in the file.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplFileObject::next() example

<?php
// Read through file line by line
$file = new SplFileObject("misc.txt");
while (!$file->eof()) {
    echo $file->current();
    $file->next();
}
?>

Zobacz też:

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

SplFileObject::key
SplFileObject::rewind
SplFileObject


Rewind the file to the first line

SplFileObject::next
SplFileObject::seek
SplFileObject
PHP Manual

SplFileObject::rewind

(PHP 5 >= 5.1.0)

SplFileObject::rewind — Rewind the file to the first line

Opis

public void SplFileObject::rewind ( void )

Rewinds the file back to the first line.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws a RuntimeException if cannot be rewound.

Przykłady

Przykład #1 SplFileObject::rewind() example

<?php
$file = new SplFileObject("misc.txt");

// Loop over whole file
foreach ($file as $line) { }

// Rewind to first line
$file->rewind();

// Output first line
echo $file->current();
?>

Zobacz też:

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::valid() - Not at EOF

SplFileObject::next
SplFileObject::seek
SplFileObject


Seek to specified line

SplFileObject::rewind
SplFileObject::setCsvControl
SplFileObject
PHP Manual

SplFileObject::seek

(PHP 5 >= 5.1.0)

SplFileObject::seek — Seek to specified line

Opis

public void SplFileObject::seek ( int $line_pos )

Seek to specified line in the file.

Parametry

line_pos

The zero-based line number to seek to.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws a LogicException if the line_pos is negative.

Przykłady

Przykład #1 SplFileObject::seek() example

This example outputs the third line of the script which is found at position 2.

<?php
$file = new SplFileObject(__FILE__);
$file->seek(2);
echo $file->current();
?>

Powyższy przykład wyświetli coś podobnego do:

$file->seek(2);

Zobacz też:

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

SplFileObject::rewind
SplFileObject::setCsvControl
SplFileObject


Set the delimiter and enclosure character for CSV

SplFileObject::seek
SplFileObject::setFlags
SplFileObject
PHP Manual

SplFileObject::setCsvControl

(PHP 5 >= 5.2.0)

SplFileObject::setCsvControl — Set the delimiter and enclosure character for CSV

Opis

 public void SplFileObject::setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )

Sets the delimiter and enclosure character for parsing CSV fields.

Parametry

delimiter

The field delimiter (one character only).

enclosure

The field enclosure character (one character only).

escape

The field escape character (one character only).

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplFileObject::setCsvControl() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl('|');
foreach ($file as $row) {
    list ($fruit, $quantity) = $row;
    // Do something with values
}
?>

Contents of data.csv

<?php
apples|20
bananas|14
cherries|87
?>

Zobacz też:

  • SplFileObject::getCsvControl() - Get the delimiter and enclosure character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

SplFileObject::seek
SplFileObject::setFlags
SplFileObject


Sets flags for the SplFileObject

SplFileObject::setCsvControl
SplFileObject::setMaxLineLen
SplFileObject
PHP Manual

SplFileObject::setFlags

(PHP 5 >= 5.1.0)

SplFileObject::setFlags — Sets flags for the SplFileObject

Opis

public void SplFileObject::setFlags ( int $flags )

Sets the flags to be used by the SplFileObject.

Parametry

flags

Bit mask of the flags to set. See SplFileObject constants for the available flags.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SplFileObject::setFlags() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $fields) {
    var_dump($fields);
}
?>

Zobacz też:

  • SplFileObject::getFlags() - Gets flags for the SplFileObject

SplFileObject::setCsvControl
SplFileObject::setMaxLineLen
SplFileObject


Set maximum line length

SplFileObject::setFlags
SplFileObject::__toString
SplFileObject
PHP Manual

SplFileObject::setMaxLineLen

(PHP 5 >= 5.1.0)

SplFileObject::setMaxLineLen — Set maximum line length

Opis

public void SplFileObject::setMaxLineLen ( int $max_len )

Sets the maximum length of a line to be read.

Parametry

max_len

The maximum length of a line.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws DomainException when max_len is less than zero.

Przykłady

Przykład #1 SplFileObject::setMaxLineLen() example

<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
    echo $line . "\n";
}
?>

Contents of lipsum.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis nec sapien felis, ac sodales nisl.
Nulla vitae magna vitae purus aliquet consequat.

Powyższy przykład wyświetli coś podobnego do:

Lorem ipsum dolor s
it amet, consectetu
r adipiscing elit.

Duis nec sapien fel
is, ac sodales nisl
.

Nulla vitae magna v
itae purus aliquet
consequat.

Zobacz też:

  • Classname::Method()

SplFileObject::setFlags
SplFileObject::__toString
SplFileObject


Alias of SplFileObject::current

SplFileObject::setMaxLineLen
SplFileObject::valid
SplFileObject
PHP Manual

SplFileObject::__toString

(PHP 5 >= 5.1.0)

SplFileObject::__toString — Alias of SplFileObject::current()

Opis

This method is an alias of SplFileObject::current().

SplFileObject::setMaxLineLen
SplFileObject::valid
SplFileObject


Not at EOF

SplFileObject::__toString
SplTempFileObject
SplFileObject
PHP Manual

SplFileObject::valid

(PHP 5 >= 5.1.0)

SplFileObject::valid — Not at EOF

Opis

public bool SplFileObject::valid ( void )

Check whether EOF has been reached.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if not reached EOF, FALSE otherwise.

Przykłady

Przykład #1 SplFileObject::valid() example

<?php
// Loop over a file, line by line
$file = new SplFileObject("file.txt");
while ($file->valid()) {
    echo $file->fgets();
}
?>

Zobacz też:

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line

SplFileObject::__toString
SplTempFileObject
SplFileObject


The SplTempFileObject class

(PHP 5 >= 5.1.2)

Wstęp

The SplTempFileObject class offers an object oriented interface for a temporary file.

Krótki opis klasy

SplTempFileObject extends SplFileObject implements SeekableIterator , Iterator , Traversable , RecursiveIterator {
/* Metody */
__construct ([ int $max_memory ] )
/* Metody dziedziczone */
public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = false [, resource $context ]]] )
public string|array SplFileObject::current ( void )
public bool SplFileObject::eof ( void )
public bool SplFileObject::fflush ( void )
public string SplFileObject::fgetc ( void )
 public array SplFileObject::fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )
public string SplFileObject::fgets ( void )
public string SplFileObject::fgetss ([ string $allowable_tags ] )
public bool SplFileObject::flock ( int $operation [, int &$wouldblock ] )
public int SplFileObject::fpassthru ( void )
public int SplFileObject::fputcsv ( string $fields [, string $delimiter [, string $enclosure ]] )
public mixed SplFileObject::fscanf ( string $format [, mixed &$... ] )
public int SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] )
public array SplFileObject::fstat ( void )
public int SplFileObject::ftell ( void )
public bool SplFileObject::ftruncate ( int $size )
public int SplFileObject::fwrite ( string $str [, int $length ] )
public void SplFileObject::getChildren ( void )
public array SplFileObject::getCsvControl ( void )
public int SplFileObject::getFlags ( void )
public int SplFileObject::getMaxLineLen ( void )
public bool SplFileObject::hasChildren ( void )
public int SplFileObject::key ( void )
public void SplFileObject::next ( void )
public void SplFileObject::rewind ( void )
public void SplFileObject::seek ( int $line_pos )
 public void SplFileObject::setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] )
public void SplFileObject::setFlags ( int $flags )
public void SplFileObject::setMaxLineLen ( int $max_len )
public bool SplFileObject::valid ( void )
}

Spis treści

  • SplTempFileObject::__construct — Construct a new temporary file object
SplFileObject::valid
SplTempFileObject::__construct
Obsługa plików


Construct a new temporary file object

SplTempFileObject
Różne klasy i interfejsy
SplTempFileObject
PHP Manual

SplTempFileObject::__construct

(PHP 5 >= 5.1.2)

SplTempFileObject::__construct — Construct a new temporary file object

Opis

SplTempFileObject::__construct ([ int $max_memory ] )

Construct a new temporary file object.

Parametry

max_memory

The maximum amount of memory (in bytes, default is 2 MB) for the temporary file to use. If the temporary file exceeds this size, it will be moved to a file in the system's temp directory.

If max_memory is negative, only memory will be used. If max_memory is zero, no memory will be used.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws a RuntimeException if an error occurs.

Przykłady

Przykład #1 SplTempFileObject() example

This example writes a temporary file in memory which can be written to and read from.

<?php
$temp = new SplTempFileObject();
$temp->fwrite("This is the first line\n");
$temp->fwrite("And this is the second.\n");
echo "Written " . $temp->ftell() . " bytes to temporary file.\n\n";

// Rewind and read what was written
$temp->rewind();
foreach ($temp as $line) {
    echo $line;
}
?>

Powyższy przykład wyświetli coś podobnego do:

Written 47 bytes to temporary file.

This is the first line
And this is the second.

Zobacz też:

  • SplFileObject
  • PHP input/output streams (for php://temp and php://memory)

SplTempFileObject
Różne klasy i interfejsy
SplTempFileObject


Różne klasy i interfejsy

Spis treści

  • ArrayObject
  • SplObserver
  • SplSubject

Pozostałe klasy i interfejsy SPL.

SplTempFileObject::__construct
ArrayObject
SPL


The ArrayObject class

(PHP 5)

Wstęp

This class allows objects to work as arrays.

Krótki opis klasy

ArrayObject implements IteratorAggregate , Traversable , ArrayAccess , Serializable , Countable {
/* Stałe */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Metody */
public __construct ([ mixed $input [, int $flags [, string $iterator_class ]]] )
public void append ( mixed $value )
public void asort ( void )
public int count ( void )
public array exchangeArray ( mixed $input )
public array getArrayCopy ( void )
public int getFlags ( void )
public ArrayIterator getIterator ( void )
public string getIteratorClass ( void )
public void ksort ( void )
public void natcasesort ( void )
public void natsort ( void )
public bool offsetExists ( mixed $index )
public mixed offsetGet ( mixed $index )
public void offsetSet ( mixed $index , mixed $newval )
public void offsetUnset ( mixed $index )
public void serialize ( void )
public void setFlags ( int $flags )
public void setIteratorClass ( string $iterator_class )
public void uasort ( callback $cmp_function )
public void uksort ( callback $cmp_function )
public void unserialize ( string $serialized )
}

Stałe predefiniowane

ArrayObject Flags

ArrayObject::STD_PROP_LIST

Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

ArrayObject::ARRAY_AS_PROPS

Entries can be accessed as properties (read and write).

Rejestr zmian

Wersja | Opis
5.3.0 | Implements Serializable.

Spis treści

  • ArrayObject::append — Appends the value
  • ArrayObject::asort — Sort the entries by value
  • ArrayObject::__construct — Construct a new array object
  • ArrayObject::count — Get the number of public properties in the ArrayObject
  • ArrayObject::exchangeArray — Exchange the array for another one.
  • ArrayObject::getArrayCopy — Creates a copy of the ArrayObject.
  • ArrayObject::getFlags — Gets the behavior flags.
  • ArrayObject::getIterator — Create a new iterator from an ArrayObject instance
  • ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject.
  • ArrayObject::ksort — Sort the entries by key
  • ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::natsort — Sort entries using a "natural order" algorithm
  • ArrayObject::offsetExists — Returns whether the requested index exists
  • ArrayObject::offsetGet — Returns the value at the specified index
  • ArrayObject::offsetSet — Sets the value at the specified index to newval
  • ArrayObject::offsetUnset — Unsets the value at the specified index
  • ArrayObject::serialize — Serialize an ArrayObject
  • ArrayObject::setFlags — Sets the behavior flags.
  • ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject.
  • ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function
  • ArrayObject::unserialize — Unserialize an ArrayObject
Różne klasy i interfejsy
ArrayObject::append
Różne klasy i interfejsy


Appends the value

ArrayObject
ArrayObject::asort
ArrayObject
PHP Manual

ArrayObject::append

(PHP 5 >= 5.0.0)

ArrayObject::append — Appends the value

Opis

public void ArrayObject::append ( mixed $value )

Appends a new value as the last element.

Informacja:

This method cannot be called when the ArrayObject was constructed from an object. Use ArrayObject::offsetSet() instead.

Parametry

value

The value being appended.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::append() example

<?php
$arrayobj = new ArrayObject(array('first','second','third'));
$arrayobj->append('fourth');
$arrayobj->append(array('five', 'six'));
var_dump($arrayobj);
?>

Powyższy przykład wyświetli:

object(ArrayObject)#1 (5) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
  [3]=>
  string(6) "fourth"
  [4]=>
  array(2) {
    [0]=>
    string(4) "five"
    [1]=>
    string(3) "six"
  }
}

Zobacz też:

  • ArrayObject::offsetSet() - Sets the value at the specified index to newval

ArrayObject
ArrayObject::asort
ArrayObject


Sort the entries by value

ArrayObject::append
ArrayObject::__construct
ArrayObject
PHP Manual

ArrayObject::asort

(PHP 5 >= 5.2.0)

ArrayObject::asort — Sort the entries by value

Opis

public void ArrayObject::asort ( void )

Sorts the entries such that the keys maintain their correlation with the entries they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::asort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->asort();

foreach ($fruitArrayObject as $key => $val) {
    echo "$key = $val\n";
}
?>

Powyższy przykład wyświetli:

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the key associated with each entry has been maintained.

Zobacz też:

  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

ArrayObject::append
ArrayObject::__construct
ArrayObject


Construct a new array object

ArrayObject::asort
ArrayObject::count
ArrayObject
PHP Manual

ArrayObject::__construct

(PHP 5 >= 5.0.0)

ArrayObject::__construct — Construct a new array object

Opis

public ArrayObject::__construct() ([ mixed $input [, int $flags [, string $iterator_class ]]] )

This constructs a new array object.

Parametry

input

The input parameter accepts an array or an Object.

flags

Flags to control the behaviour of the ArrayObject object.

iterator_class

Specify the class that will be used for iteration of the ArrayObject object. ArrayIterator is the default class used.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::__construct() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

var_dump($arrayobject);
?>

Powyższy przykład wyświetli:

object(ArrayObject)#1 (3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

Zobacz też:

  • ArrayObject::setflags() - Sets the behavior flags.

ArrayObject::asort
ArrayObject::count
ArrayObject


Get the number of public properties in the ArrayObject

ArrayObject::__construct
ArrayObject::exchangeArray
ArrayObject
PHP Manual

ArrayObject::count

(PHP 5 >= 5.0.0)

ArrayObject::count — Get the number of public properties in the ArrayObject

Opis

public int ArrayObject::count ( void )

Get the number of public properties in the ArrayObject.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The number of public properties in the ArrayObject.

Informacja:

When the ArrayObject is constructed from an array all properties are public.

Przykłady

Przykład #1 ArrayObject::count() example

<?php
class Example {
    public $public = 'prop:public';
    private $prv   = 'prop:private';
    protected $prt = 'prop:protected';
}

$arrayobj = new ArrayObject(new Example());
var_dump($arrayobj->count());

$arrayobj = new ArrayObject(array('first','second','third'));
var_dump($arrayobj->count());
?>

Powyższy przykład wyświetli:

int(1)
int(3)

ArrayObject::__construct
ArrayObject::exchangeArray
ArrayObject


Exchange the array for another one.

ArrayObject::count
ArrayObject::getArrayCopy
ArrayObject
PHP Manual

ArrayObject::exchangeArray

(PHP 5 >= 5.1.0)

ArrayObject::exchangeArray — Exchange the array for another one.

Opis

public array ArrayObject::exchangeArray ( mixed $input )

Exchange the current array with another array or object.

Parametry

input

The new array or object to exchange with the current array.

Zwracane wartości

Returns the old array.

Przykłady

Przykład #1 ArrayObject::exchangeArray() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
// Array of locations in Europe
$locations = array('Amsterdam', 'Paris', 'London');

$fruitsArrayObject = new ArrayObject($fruits);

// Now exchange fruits for locations
$old = $fruitsArrayObject->exchangeArray($locations);
print_r($old);
print_r($fruitsArrayObject);

?>

Powyższy przykład wyświetli:

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)
ArrayObject Object
(
    [0] => Amsterdam
    [1] => Paris
    [2] => London
)

ArrayObject::count
ArrayObject::getArrayCopy
ArrayObject


Creates a copy of the ArrayObject.

ArrayObject::exchangeArray
ArrayObject::getFlags
ArrayObject
PHP Manual

ArrayObject::getArrayCopy

(PHP 5 >= 5.0.0)

ArrayObject::getArrayCopy — Creates a copy of the ArrayObject.

Opis

public array ArrayObject::getArrayCopy ( void )

Exports the ArrayObject to an array.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a copy of the array. When the ArrayObject refers to an object an array of the public properties of that object will be returned.

Przykłady

Przykład #1 ArrayObject::getArrayCopy() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);
$fruitsArrayObject['pears'] = 4;

// create a copy of the array
$copy = $fruitsArrayObject->getArrayCopy();
print_r($copy);

?>

Powyższy przykład wyświetli:

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
    [pears] => 4
)

ArrayObject::exchangeArray
ArrayObject::getFlags
ArrayObject


Gets the behavior flags.

ArrayObject::getArrayCopy
ArrayObject::getIterator
ArrayObject
PHP Manual

ArrayObject::getFlags

(PHP 5 >= 5.1.0)

ArrayObject::getFlags — Gets the behavior flags.

Opis

public int ArrayObject::getFlags ( void )

Gets the behavior flags of the ArrayObject. See the ArrayObject::setFlags method for a list of the available flags.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the behavior flags of the ArrayObject.

Przykłady

Przykład #1 ArrayObject::getFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current flags
$flags = $fruitsArrayObject->getFlags();
var_dump($flags);

// Set new flags
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);

// Get the new flags
$flags = $fruitsArrayObject->getFlags();
var_dump($flags);
?>

Powyższy przykład wyświetli:

int(0)
int(2)

Zobacz też:

  • The ArrayObject::setFlags method

ArrayObject::getArrayCopy
ArrayObject::getIterator
ArrayObject


Create a new iterator from an ArrayObject instance

ArrayObject::getFlags
ArrayObject::getIteratorClass
ArrayObject
PHP Manual

ArrayObject::getIterator

(PHP 5 >= 5.0.0)

ArrayObject::getIterator — Create a new iterator from an ArrayObject instance

Opis

public ArrayIterator ArrayObject::getIterator ( void )

Create a new iterator from an ArrayObject instance.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An iterator from an ArrayObject.

Przykłady

Przykład #1 ArrayObject::getIterator() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    echo $iterator->key() . ' => ' . $iterator->current() . "\n";

    $iterator->next();
}
?>

Powyższy przykład wyświetli:

1 => one
2 => two
3 => three

ArrayObject::getFlags
ArrayObject::getIteratorClass
ArrayObject


Gets the iterator classname for the ArrayObject.

ArrayObject::getIterator
ArrayObject::ksort
ArrayObject
PHP Manual

ArrayObject::getIteratorClass

(PHP 5 >= 5.1.0)

ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject.

Opis

public string ArrayObject::getIteratorClass ( void )

Gets the class name of the array iterator that is used by ArrayObject::getIterator().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the iterator class name that is used to iterate over this object.

Przykłady

Przykład #1 ArrayObject::getIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
    // custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current class name
$className = $fruitsArrayObject->getIteratorClass();
var_dump($className);

// Set new classname
$fruitsArrayObject->setIteratorClass('MyArrayIterator');

// Get the new iterator classname
$className = $fruitsArrayObject->getIteratorClass();
var_dump($className);
?>

Powyższy przykład wyświetli:

string(13) "ArrayIterator"
string(15) "MyArrayIterator"

Zobacz też:

  • The ArrayObject::setIteratorClass method

ArrayObject::getIterator
ArrayObject::ksort
ArrayObject


Sort the entries by key

ArrayObject::getIteratorClass
ArrayObject::natcasesort
ArrayObject
PHP Manual

ArrayObject::ksort

(PHP 5 >= 5.2.0)

ArrayObject::ksort — Sort the entries by key

Opis

public void ArrayObject::ksort ( void )

Sorts the entries by key, maintaining key to entry correlations. This is useful mainly for associative arrays.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::ksort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->ksort();

foreach ($fruitArrayObject as $key => $val) {
    echo "$key = $val\n";
}
 ?>

Powyższy przykład wyświetli:

a = orange
b = banana
c = apple
d = lemon

Zobacz też:

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

ArrayObject::getIteratorClass
ArrayObject::natcasesort
ArrayObject


Sort an array using a case insensitive "natural order" algorithm

ArrayObject::ksort
ArrayObject::natsort
ArrayObject
PHP Manual

ArrayObject::natcasesort

(PHP 5 >= 5.2.0)

ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm

Opis

public void ArrayObject::natcasesort ( void )

This method is a case insensitive version of ArrayObject::natsort.

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::natcasesort() example

<?php
$array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo "Standard sorting\n";
print_r($arr1);

$arr2->natcasesort();
echo "\nNatural order sorting (case-insensitive)\n";
print_r($arr2);
?>

Powyższy przykład wyświetli:

Standard sorting
ArrayObject Object
(
    [0] => IMG0.png
    [5] => IMG3.png
    [4] => img1.png
    [2] => img10.png
    [1] => img12.png
    [3] => img2.png
)

Natural order sorting (case-insensitive)
ArrayObject Object
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

Zobacz też:

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

ArrayObject::ksort
ArrayObject::natsort
ArrayObject


Sort entries using a "natural order" algorithm

ArrayObject::natcasesort
ArrayObject::offsetExists
ArrayObject
PHP Manual

ArrayObject::natsort

(PHP 5 >= 5.2.0)

ArrayObject::natsort — Sort entries using a "natural order" algorithm

Opis

public void ArrayObject::natsort ( void )

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in ArrayObject::asort) method can be seen in the example below.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::natsort() example

<?php
$array = array("img12.png", "img10.png", "img2.png", "img1.png");

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo "Standard sorting\n";
print_r($arr1);

$arr2->natsort();
echo "\nNatural order sorting\n";
print_r($arr2);
?>

Powyższy przykład wyświetli:

Standard sorting
ArrayObject Object
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
ArrayObject Object
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

Zobacz też:

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

ArrayObject::natcasesort
ArrayObject::offsetExists
ArrayObject


Returns whether the requested index exists

ArrayObject::natsort
ArrayObject::offsetGet
ArrayObject
PHP Manual

ArrayObject::offsetExists

(PHP 5 >= 5.0.0)

ArrayObject::offsetExists — Returns whether the requested index exists

Opis

public bool ArrayObject::offsetExists ( mixed $index )

Parametry

index

The index being checked.

Zwracane wartości

TRUE if the requested index exists, otherwise FALSE

Przykłady

Przykład #1 ArrayObject::offsetExists() example

<?php
$arrayobj = new ArrayObject(array('zero', 'one', 'example'=>'e.g.'));
var_dump($arrayobj->offsetExists(1));
var_dump($arrayobj->offsetExists('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

Powyższy przykład wyświetli:

bool(true)
bool(true)
bool(false)

ArrayObject::natsort
ArrayObject::offsetGet
ArrayObject


Returns the value at the specified index

ArrayObject::offsetExists
ArrayObject::offsetSet
ArrayObject
PHP Manual

ArrayObject::offsetGet

(PHP 5 >= 5.0.0)

ArrayObject::offsetGet — Returns the value at the specified index

Opis

public mixed ArrayObject::offsetGet ( mixed $index )

Parametry

index

The index with the value.

Zwracane wartości

The value at the specified index or FALSE.

Przykłady

Przykład #1 ArrayObject::offsetGet() example

<?php
$arrayobj = new ArrayObject(array('zero', 7, 'example'=>'e.g.'));
var_dump($arrayobj->offsetGet(1));
var_dump($arrayobj->offsetGet('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

Powyższy przykład wyświetli:

int(7)
string(4) "e.g."
bool(false)

ArrayObject::offsetExists
ArrayObject::offsetSet
ArrayObject


Sets the value at the specified index to newval

ArrayObject::offsetGet
ArrayObject::offsetUnset
ArrayObject
PHP Manual

ArrayObject::offsetSet

(PHP 5 >= 5.0.0)

ArrayObject::offsetSet — Sets the value at the specified index to newval

Opis

public void ArrayObject::offsetSet ( mixed $index , mixed $newval )

Sets the value at the specified index to newval.

Parametry

index

The index being set.

newval

The new value for the index.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::offsetSet() example

<?php
class Example {
    public $property = 'prop:public';
}
$arrayobj = new ArrayObject(new Example());
$arrayobj->offsetSet(4, 'four');
$arrayobj->offsetSet('group', array('g1', 'g2'));
var_dump($arrayobj);

$arrayobj = new ArrayObject(array('zero','one'));
$arrayobj->offsetSet(null, 'last');
var_dump($arrayobj);
?>

Powyższy przykład wyświetli:

object(ArrayObject)#1 (3) {
  ["property"]=>
  string(11) "prop:public"
  [4]=>
  string(4) "four"
  ["group"]=>
  array(2) {
    [0]=>
    string(2) "g1"
    [1]=>
    string(2) "g2"
  }
}
object(ArrayObject)#3 (3) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(4) "last"
}

Zobacz też:

  • ArrayObject::append() - Appends the value

ArrayObject::offsetGet
ArrayObject::offsetUnset
ArrayObject


Unsets the value at the specified index

ArrayObject::offsetSet
ArrayObject::serialize
ArrayObject
PHP Manual

ArrayObject::offsetUnset

(PHP 5 >= 5.0.0)

ArrayObject::offsetUnset — Unsets the value at the specified index

Opis

public void ArrayObject::offsetUnset ( mixed $index )

Unsets the value at the specified index.

Parametry

index

The index being unset.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::offsetUnset() example

<?php
$arrayobj = new ArrayObject(array(0=>'zero',2=>'two'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>

Powyższy przykład wyświetli:

object(ArrayObject)#1 (1) {
  [0]=>
  string(4) "zero"
}

ArrayObject::offsetSet
ArrayObject::serialize
ArrayObject


Serialize an ArrayObject

ArrayObject::offsetUnset
ArrayObject::setFlags
ArrayObject
PHP Manual

ArrayObject::serialize

(PHP 5 >= 5.3.0)

ArrayObject::serialize — Serialize an ArrayObject

Opis

public void ArrayObject::serialize ( void )

Serializes an ArrayObject.

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 serialized representation of the ArrayObject.

Przykłady

Przykład #1 ArrayObject::serialize() example

<?php
$o = new ArrayObject();

$s1 = serialize($o);
$s2 = $o->serialize();

var_dump($s1);
var_dump($s2);
?>

Powyższy przykład wyświetli:

string(45) "C:11:"ArrayObject":21:{x:i:0;a:0:{};m:a:0:{}}"
string(21) "x:i:0;a:0:{};m:a:0:{}"

Zobacz też:

  • ArrayObject::unserialize() - Unserialize an ArrayObject
  • serialize() - Generates a storable representation of a value
  • Serializing Objects

ArrayObject::offsetUnset
ArrayObject::setFlags
ArrayObject


Sets the behavior flags.

ArrayObject::serialize
ArrayObject::setIteratorClass
ArrayObject
PHP Manual

ArrayObject::setFlags

(PHP 5 >= 5.1.0)

ArrayObject::setFlags — Sets the behavior flags.

Opis

public void ArrayObject::setFlags ( int $flags )

Set the flags that change the behavior of the ArrayObject.

Parametry

flags

The new ArrayObject behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions.

The available behavior flags are listed below. The actual meanings of these flags are described in the predefined constants.

ArrayObject behavior flags
value | constant
1 | ArrayObject::STD_PROP_LIST
2 | ArrayObject::ARRAY_AS_PROPS

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::setFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Try to use array key as property
var_dump($fruitsArrayObject->lemons);
// Set the flag so that the array keys can be used as properties of the ArrayObject
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);
// Try it again
var_dump($fruitsArrayObject->lemons);
?>

Powyższy przykład wyświetli:

NULL
int(1)

ArrayObject::serialize
ArrayObject::setIteratorClass
ArrayObject


Sets the iterator classname for the ArrayObject.

ArrayObject::setFlags
ArrayObject::uasort
ArrayObject
PHP Manual

ArrayObject::setIteratorClass

(PHP 5 >= 5.1.0)

ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject.

Opis

public void ArrayObject::setIteratorClass ( string $iterator_class )

Sets the classname of the array iterator that is used by ArrayObject::getIterator().

Parametry

iterator_class

The classname of the array iterator to use when iterating over this object.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::setIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
    // custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Set the iterator classname to the newly
$fruitsArrayObject->setIteratorClass('MyArrayIterator');
print_r($fruitsArrayObject->getIterator());

?>

Powyższy przykład wyświetli:

MyArrayIterator Object
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)

ArrayObject::setFlags
ArrayObject::uasort
ArrayObject


Sort the entries with a user-defined comparison function and maintain key association

ArrayObject::setIteratorClass
ArrayObject::uksort
ArrayObject
PHP Manual

ArrayObject::uasort

(PHP 5 >= 5.2.0)

ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association

Opis

public void ArrayObject::uasort ( callback $cmp_function )

This function sorts the entries such that keys maintain their correlation with the entry that they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Parametry

cmp_function

Function cmp_function should accept two parameters which will be filled by pairs of entries. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::uasort() example

<?php
// Comparison function
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
$arrayObject = new ArrayObject($array);
print_r($arrayObject);

// Sort and print the resulting array
$arrayObject->uasort('cmp');
print_r($arrayObject);
?>

Powyższy przykład wyświetli:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

Zobacz też:

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function

ArrayObject::setIteratorClass
ArrayObject::uksort
ArrayObject


Sort the entries by keys using a user-defined comparison function

ArrayObject::uasort
ArrayObject::unserialize
ArrayObject
PHP Manual

ArrayObject::uksort

(PHP 5 >= 5.2.0)

ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function

Opis

public void ArrayObject::uksort ( callback $cmp_function )

This function sorts the keys of the entries using a user-supplied comparison function. The key to entry correlations will be maintained.

Parametry

cmp_function

The callback comparison function.

Function cmp_function should accept two parameters which will be filled by pairs of entry keys. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 ArrayObject::uksort() example

<?php
function cmp($a, $b) {
    $a = preg_replace('@^(a|an|the) @', '', $a);
    $b = preg_replace('@^(a|an|the) @', '', $b);
    return strcasecmp($a, $b);
}

$array = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);
$arrayObject = new ArrayObject($array);
$arrayObject->uksort('cmp');

foreach ($arrayObject as $key => $value) {
    echo "$key: $value\n";
}
?>

Powyższy przykład wyświetli:

an apple: 3
a banana: 4
the Earth: 2
John: 1

Zobacz też:

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association

ArrayObject::uasort
ArrayObject::unserialize
ArrayObject


Unserialize an ArrayObject

ArrayObject::uksort
SplObserver
ArrayObject
PHP Manual

ArrayObject::unserialize

(PHP 5 >= 5.3.0)

ArrayObject::unserialize — Unserialize an ArrayObject

Opis

public void ArrayObject::unserialize ( string $serialized )

Unserializes a serialized ArrayObject.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

serialized

The serialized ArrayObject.

Zwracane wartości

The unserialized ArrayObject.

Zobacz też:

  • ArrayIterator::serialize() - Serialize
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects

ArrayObject::uksort
SplObserver
ArrayObject


The SplObserver interface

(PHP 5 >= 5.1.0)

Wstęp

The SplObserver interface is used alongside SplSubject to implement the Observer Design Pattern.

Zestawienie interfejsu

SplObserver {
/* Metody */
abstract public void update ( SplSubject $subject )
}

Spis treści

  • SplObserver::update — Receive update from subject
ArrayObject::unserialize
SplObserver::update
Różne klasy i interfejsy


Receive update from subject

SplObserver
SplSubject
SplObserver
PHP Manual

SplObserver::update

(PHP 5 >= 5.1.0)

SplObserver::update — Receive update from subject

Opis

abstract public void SplObserver::update ( SplSubject $subject )

This method is called when any SplSubject to which the observer is attached calls SplSubject::notify().

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

subject

The SplSubject notifying the observer of an update.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplObserver
SplSubject
SplObserver


The SplSubject interface

(PHP 5 >= 5.1.0)

Wstęp

The SplSubject interface is used alongside SplObserver to implement the Observer Design Pattern.

Zestawienie interfejsu

SplSubject {
/* Metody */
abstract public void attach ( SplObserver $observer )
abstract public void detach ( SplObserver $observer )
abstract public void notify ( void )
}

Spis treści

  • SplSubject::attach — Attach an SplObserver
  • SplSubject::detach — Detach an observer
  • SplSubject::notify — Notify an observer
SplObserver::update
SplSubject::attach
Różne klasy i interfejsy


Attach an SplObserver

SplSubject
SplSubject::detach
SplSubject
PHP Manual

SplSubject::attach

(PHP 5 >= 5.1.0)

SplSubject::attach — Attach an SplObserver

Opis

abstract public void SplSubject::attach ( SplObserver $observer )

Attaches an SplObserver so that it can be notified of updates.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

observer

The SplObserver to attach.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplSubject
SplSubject::detach
SplSubject


Detach an observer

SplSubject::attach
SplSubject::notify
SplSubject
PHP Manual

SplSubject::detach

(PHP 5 >= 5.1.0)

SplSubject::detach — Detach an observer

Opis

abstract public void SplSubject::detach ( SplObserver $observer )

Detaches an observer from the subject to no longer notify it of updates.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

observer

The SplObserver to detach.

Zwracane wartości

Nie jest zwracana żadna wartość.

SplSubject::attach
SplSubject::notify
SplSubject


Notify an observer

SplSubject::detach
SPL Types
SplSubject
PHP Manual

SplSubject::notify

(PHP 5 >= 5.1.0)

SplSubject::notify — Notify an observer

Opis

abstract public void SplSubject::notify ( void )

Notifies all attached observers.

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

Nie jest zwracana żadna wartość.

SplSubject::detach
SPL Types
SplSubject


SPL Type Handling

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • SplType — The SplType class
    • SplType::__construct — Creates a new value of some type
  • SplInt — The SplInt class
  • SplFloat — The SplFloat class
  • SplEnum — The SplEnum class
    • SplEnum::getConstList — Returns all consts (possible values) as an array.
  • SplBool — The SplBool class
  • SplString — The SplString class
SplSubject::notify
Wstęp
Inne podstawowe rozszerzenia


Wstęp

This extension aims at helping people making PHP a stronger typed language and can be a good alternative to scalar type hinting. It provides different typehandling classes as such as integer, float, bool, enum and string

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.

SPL Types
Instalacja/Konfiguracja
SPL Types


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SPL Types


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/SPL_Types.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
SplType
Instalacja/Konfiguracja


The SplType class

(No version information available, might only be in SVN)

Wstęp

Parent class for all SPL types.

Krótki opis klasy

abstract SplType {
/* Constants */
const NULL __default = null ;
/* Metody */
__construct ([ mixed $initial_value [, bool $strict ]] )
}

Stałe predefiniowane

SplType::__default

Spis treści

  • SplType::__construct — Creates a new value of some type
Typy zasobów
SplType::__construct
SPL Types


Creates a new value of some type

SplType
SplInt
SplType
PHP Manual

SplType::__construct

(PECL spl_types >= 0.1.0)

SplType::__construct — Creates a new value of some type

Opis

SplType::__construct ([ mixed $initial_value [, bool $strict ]] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

initial_value

Type and default value depends on the extension class.

strict

Whether to set the object's sctrictness.

Błędy/Wyjątki

Throws an UnexpectedValueException if incompatible type is given.

SplType
SplInt
SplType


The SplInt class

(No version information available, might only be in SVN)

Wstęp

The SplInt class is used to enforce strong typing of the integer type.

Krótki opis klasy

SplInt extends SplType {
/* Constants */
const integer __default = 0 ;
/* Metody dziedziczone */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Stałe predefiniowane

SplInt::__default

Przykłady

Przykład #1 SplInt usage example

<?php
$int = new SplInt(94);

try {
    $int = 'Try to cast a string value for fun';
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

echo $int . PHP_EOL;
?>

Powyższy przykład wyświetli:

Value not an integer
94

SplType::__construct
SplFloat
SPL Types


The SplFloat class

(No version information available, might only be in SVN)

Wstęp

The SplFloat class is used to enforce strong typing of the float type.

Krótki opis klasy

SplFloat extends SplType {
/* Constants */
const float __default = 0 ;
/* Metody dziedziczone */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Stałe predefiniowane

SplFloat::__default

Przykłady

Przykład #1 SplFloat usage example

<?php
$float = new SplFloat(3.154);
$newFloat = new SplFloat(3);

try {
    $float = 'Try to cast a string value for fun';
} catch (UnexpectedValueException $uve) {
    echo $e->getMessage() . PHP_EOL;
}

echo $float . PHP_EOL;
echo $newFloat . PHP_EOL;
?>

Powyższy przykład wyświetli:

Value not a float
3.154
3

SplInt
SplEnum
SPL Types


The SplEnum class

(No version information available, might only be in SVN)

Wstęp

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

Krótki opis klasy

SplEnum extends SplType {
/* Constants */
const NULL __default = null ;
/* Metody */
public array getConstList ([ bool $include_default = false ] )
/* Metody dziedziczone */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Stałe predefiniowane

SplEnum::__default

Przykłady

Przykład #1 SplEnum usage example

<?php
class Month extends SplEnum {
    const __default = self::January;

    const January = 1;
    const February = 2;
    const March = 3;
    const April = 4;
    const May = 5;
    const June = 6;
    const July = 7;
    const August = 8;
    const September = 9;
    const October = 10;
    const November = 11;
    const December = 12;
}

echo new Month(Month::June) . PHP_EOL;

try {
    new Month(13);
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}
?>

Powyższy przykład wyświetli:

6
Value not a const in enum Month

Spis treści

  • SplEnum::getConstList — Returns all consts (possible values) as an array.
SplFloat
SplEnum::getConstList
SPL Types


Returns all consts (possible values) as an array.

SplEnum
SplBool
SplEnum
PHP Manual

SplEnum::getConstList

(PECL spl_types >= 0.1.0)

SplEnum::getConstList — Returns all consts (possible values) as an array.

Opis

public array SplEnum::getConstList ([ bool $include_default = false ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

include_default

Whether to include __default property.

Zwracane wartości

Przykłady

Przykład #1 SplEnum::getConstList() example

<?php
$bool = new SplBool;
var_dump($bool->getConstList(true));
?>

Powyższy przykład wyświetli:

array(3) {
  ["__default"]=>
  bool(false)
  ["false"]=>
  bool(false)
  ["true"]=>
  bool(true)
}

SplEnum
SplBool
SplEnum


The SplBool class

(No version information available, might only be in SVN)

Wstęp

The SplBool class is used to enforce strong typing of the bool type.

Krótki opis klasy

SplBool extends SplEnum {
/* Constants */
const boolean __default = false ;
const boolean false = false ;
const boolean true = true ;
/* Metody dziedziczone */
public array SplEnum::getConstList ([ bool $include_default = false ] )
}

Stałe predefiniowane

SplBool::__default

SplBool::false

SplBool::true

Przykłady

Przykład #1 SplBool usage example

<?php
$true = new SplBool(true);
if ($true) {
    echo "TRUE\n";
}

$false = new SplBool;
if ($false) {
    echo "FALSE\n";
}
?>

Powyższy przykład wyświetli:

TRUE

SplEnum::getConstList
SplString
SPL Types


The SplString class

(No version information available, might only be in SVN)

Wstęp

The SplString class is used to enforce strong typing of the string type.

Krótki opis klasy

SplString extends SplType {
/* Constants */
const integer __default = 0 ;
/* Metody dziedziczone */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Stałe predefiniowane

SplString::__default

Przykłady

Przykład #1 SplString usage example

<?php
$string = new SplString("Testing");

try {
    $string = array();
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

var_dump($string);
echo $string; // Outputs "Testing"
?>

Powyższy przykład wyświetli:

Value not a string
object(SplString)#1 (1) {
  ["__default"]=>
  string(7) "Testing"
}
Testing

SplBool
Streams
SPL Types


Streams

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Stream Classes
  • Stałe predefiniowane
  • Stream Filters
  • Stream Contexts
  • Stream Errors
  • Przykłady
    • Example class registered as stream wrapper
  • streamWrapper — The streamWrapper class
    • streamWrapper::__construct — Constructs a new stream wrapper
    • streamWrapper::__destruct — Destructs an existing stream wrapper
    • streamWrapper::dir_closedir — Close directory handle
    • streamWrapper::dir_opendir — Open directory handle
    • streamWrapper::dir_readdir — Read entry from directory handle
    • streamWrapper::dir_rewinddir — Rewind directory handle
    • streamWrapper::mkdir — Create a directory
    • streamWrapper::rename — Renames a file or directory
    • streamWrapper::rmdir — Removes a directory
    • streamWrapper::stream_cast — Retrieve the underlaying resource
    • streamWrapper::stream_close — Close an resource
    • streamWrapper::stream_eof — Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush — Flushes the output
    • streamWrapper::stream_lock — Advisory file locking
    • streamWrapper::stream_metadata — Change stream options
    • streamWrapper::stream_open — Opens file or URL
    • streamWrapper::stream_read — Read from stream
    • streamWrapper::stream_seek — Seeks to specific location in a stream
    • streamWrapper::stream_set_option — Change stream options
    • streamWrapper::stream_stat — Retrieve information about a file resource
    • streamWrapper::stream_tell — Retrieve the current position of a stream
    • streamWrapper::stream_write — Write to stream
    • streamWrapper::unlink — Delete a file
    • streamWrapper::url_stat — Retrieve information about a file
  • Stream Funkcje
    • set_socket_blocking — Alias dla stream_set_blocking
    • stream_bucket_append — Append bucket to brigade
    • stream_bucket_make_writeable — Return a bucket object from the brigade for operating on
    • stream_bucket_new — Create a new bucket for use on the current stream
    • stream_bucket_prepend — Prepend bucket to brigade
    • stream_context_create — Create a streams context
    • stream_context_get_default — Retrieve the default streams context
    • stream_context_get_options — Retrieve options for a stream/wrapper/context
    • stream_context_get_params — Retrieves parameters from a context
    • stream_context_set_default — Set the default streams context
    • stream_context_set_option — Sets an option for a stream/wrapper/context
    • stream_context_set_params — Set parameters for a stream/wrapper/context
    • stream_copy_to_stream — Copies data from one stream to another
    • stream_encoding — Set character set for stream encoding
    • stream_filter_append — Attach a filter to a stream
    • stream_filter_prepend — Attach a filter to a stream
    • stream_filter_register — Register a user defined stream filter
    • stream_filter_remove — Remove a filter from a stream
    • stream_get_contents — Reads remainder of a stream into a string
    • stream_get_filters — Retrieve list of registered filters
    • stream_get_line — Gets line from stream resource up to a given delimiter
    • stream_get_meta_data — Retrieves header/meta data from streams/file pointers
    • stream_get_transports — Retrieve list of registered socket transports
    • stream_get_wrappers — Retrieve list of registered streams
    • stream_is_local — Checks if a stream is a local stream
    • stream_notification_callback — A callback function for the notification context paramater
    • stream_register_wrapper — Alias dla stream_wrapper_register
    • stream_resolve_include_path — Resolve filename against the include path
    • stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
    • stream_set_blocking — Set blocking/non-blocking mode on a stream
    • stream_set_read_buffer — Set read file buffering on the given stream
    • stream_set_timeout — Set timeout period on a stream
    • stream_set_write_buffer — Sets write file buffering on the given stream
    • stream_socket_accept — Accept a connection on a socket created by stream_socket_server
    • stream_socket_client — Open Internet or Unix domain socket connection
    • stream_socket_enable_crypto — Turns encryption on/off on an already connected socket
    • stream_socket_get_name — Retrieve the name of the local or remote sockets
    • stream_socket_pair — Creates a pair of connected, indistinguishable socket streams
    • stream_socket_recvfrom — Receives data from a socket, connected or not
    • stream_socket_sendto — Sends a message to a socket, whether it is connected or not
    • stream_socket_server — Create an Internet or Unix domain server socket
    • stream_socket_shutdown — Shutdown a full-duplex connection
    • stream_supports_lock — Tells whether the stream supports locking.
    • stream_wrapper_register — Register a URL wrapper implemented as a PHP class
    • stream_wrapper_restore — Restores a previously unregistered built-in wrapper
    • stream_wrapper_unregister — Unregister a URL wrapper
SplString
Wstęp
Inne podstawowe rozszerzenia


Wstęp

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.

A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Supported Protocols and Wrappers), and additional, custom wrappers may be added either within a PHP script using stream_wrapper_register(), or directly from an extension using the API Reference in Working with streams. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers().

A stream is referenced as: scheme://target

  • scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Supported Protocols and Wrappers for a list of PHP built-in wrappers. If no wrapper is specified, the function default is used (typically file://).
  • target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Supported Protocols and Wrappers for a description of targets for built-in streams.

Informacja:

Information on using streams within the PHP source code can be found in the Streams API for PHP Extension Authors reference.

Streams
Instalacja/Konfiguracja
Streams


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Stream Classes
Wstęp
Wymagania
Streams


Instalacja

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.

Instalacja
Stream Classes
Instalacja/Konfiguracja


Stream Classes

User designed wrappers can be registered via stream_wrapper_register(), using the class definition shown on that manual page.

class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_filter_register() for details on implementing user defined filters.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

Constant | Description
STREAM_FILTER_READ * | Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when reading
STREAM_FILTER_WRITE * | Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when writing
STREAM_FILTER_ALL * | This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE
PSFS_PASS_ON * | Return Code indicating that the userspace filter returned buckets in $out.
PSFS_FEED_ME * | Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
PSFS_ERR_FATAL * | Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
PSFS_FLAG_NORMAL | Regular read/write.
PSFS_FLAG_FLUSH_INC | An incremental flush.
PSFS_FLAG_FLUSH_CLOSE | Final flush prior to closing.
STREAM_USE_PATH | Flag indicating if the stream used the include path.
STREAM_REPORT_ERRORS | Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.
STREAM_CLIENT_ASYNC_CONNECT * | Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client().
STREAM_CLIENT_CONNECT * | Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENT * | Client socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BIND * | Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTEN * | Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error.
STREAM_NOTIFY_RESOLVE * | A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT | A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED | Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS | The mime-type of resource has been identified, refer to message for a description of the discovered type.
STREAM_NOTIFY_FILE_SIZE_IS | The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED | The external resource has redirected the stream to an alternate location. Refer to message.
STREAM_NOTIFY_PROGRESS | Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED * | There is no more data available on the stream.
STREAM_NOTIFY_FAILURE | A generic error occurred on the stream, consult message and message_code for details.
STREAM_NOTIFY_AUTH_RESULT | Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO | Normal, non-error related, notification.
STREAM_NOTIFY_SEVERITY_WARN | Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR | A critical error occurred. Processing cannot continue.
STREAM_IPPROTO_ICMP + | Provides a ICMP socket.
STREAM_IPPROTO_IP + | Provides a IP socket.
STREAM_IPPROTO_RAW + | Provides a RAW socket.
STREAM_IPPROTO_TCP + | Provides a TCP socket.
STREAM_IPPROTO_UDP + | Provides a UDP socket.
STREAM_PF_INET + | Internet Protocol Version 4 (IPv4).
STREAM_PF_INET6 + | Internet Protocol Version 6 (IPv6).
STREAM_PF_UNIX + | Unix system internal protocols.
STREAM_SOCK_DGRAM + | Provides datagrams, which are connectionless messages (UDP, for example).
STREAM_SOCK_RAW + | Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user.
STREAM_SOCK_RDM + | Provides a RDM (Reliably-delivered messages) socket.
STREAM_SOCK_SEQPACKET + | Provides a sequenced packet stream socket.
STREAM_SOCK_STREAM + | Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example).
STREAM_SHUT_RD | Used with stream_socket_shutdown() to disable further receptions. Added in PHP 5.2.1.
STREAM_SHUT_WR | Used with stream_socket_shutdown() to disable further transmissions. Added in PHP 5.2.1.
STREAM_SHUT_RDWR | Used with stream_socket_shutdown() to disable further receptions and transmissions. Added in PHP 5.2.1.
STREAM_CAST_FOR_SELECT | Stream casting, for when stream_select() is calling stream_cast().
STREAM_CAST_AS_STREAM | Stream casting, when stream_cast() is called otherwise (see above).
STREAM_META_TOUCH | Used with stream_metadata(), to specify touch() call.
STREAM_META_OWNER | Used with stream_metadata(), to specify chown() call.
STREAM_META_OWNER_NAME | Used with stream_metadata(), to specify chown() call.
STREAM_META_GROUP | Used with stream_metadata(), to specify chgrp() call.
STREAM_META_GROUP_NAME | Used with stream_metadata(), to specify chgrp() call.
STREAM_META_ACCESS | Used with stream_metadata(), to specify chmod() call.

Informacja: The constants marked with * are just available since PHP 5.0.0.

Informacja: The constants marked with + are available since PHP 5.1.0 and are meant to be used with stream_socket_pair(). Please note that some of these constants might not be available in your system.

Informacja: The STREAM_META_* constants are available since PHP 5.4.0 and are meant to be used with stream_metadata().

Stream Classes
Stream Filters
Streams


Stream Filters

A filter is a final piece of code which may perform operations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_filter_register() or in an extension using the API Reference in Working with streams. To access the list of currently registered filters, use stream_get_filters().

Stałe predefiniowane
Stream Contexts
Streams


Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found in the Context options and parameters chapter.

Parameters can be specified for contexts using the stream_context_set_params() function.

Stream Filters
Stream Errors
Streams


Stream Errors

As with any file or socket related function, an operation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occurs an E_WARNING message will be generated describing the nature of the error.

Stream Contexts
Przykłady
Streams


Przykłady

Spis treści

  • Example class registered as stream wrapper

Przykład #1 Using file_get_contents() to retrieve data from multiple sources

<?php
/* Read local file from /home/bar */
$localfile = file_get_contents("/home/bar/foo.txt");

/* Identical to above, explicitly naming FILE scheme */
$localfile = file_get_contents("file:///home/bar/foo.txt");

/* Read remote file from www.example.com using HTTP */
$httpfile  = file_get_contents("http://www.example.com/foo.txt");

/* Read remote file from www.example.com using HTTPS */
$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTP */
$ftpfile   = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTPS */
$ftpsfile  = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?>

Przykład #2 Making a POST request to an https server

<?php
/* Send POST request to https://secure.example.com/form_action.php
* Include form elements named "foo" and "bar" with dummy values
*/

$sock = fsockopen("ssl://secure.example.com", 443, $errno, $errstr, 30);
if (!$sock) die("$errstr ($errno)\n");

$data = "foo=" . urlencode("Value for Foo") . "&bar=" . urlencode("Value for Bar");

fwrite($sock, "POST /form_action.php HTTP/1.0\r\n");
fwrite($sock, "Host: secure.example.com\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, "$data\r\n");
fwrite($sock, "\r\n");

$headers = "";
while ($str = trim(fgets($sock, 4096)))
$headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);

fclose($sock);
?>

Przykład #3 Writing data to a compressed file

<?php
/* Create a compressed file containing an arbitrarty string
* File can be read back using compress.zlib stream or just
* decompressed from the command line using 'gzip -d foo-bar.txt.gz'
*/
$fp = fopen("compress.zlib://foo-bar.txt.gz", "wb");
if (!$fp) die("Unable to create file.");

fwrite($fp, "This is a test.\n");

fclose($fp);
?>

Stream Errors
Example class registered as stream wrapper
Streams


Example class registered as stream wrapper

The example below implements a var:// protocol handler that allows read/write access to a named global variable using standard filesystem stream functions such as fread(). The var:// protocol implemented below, given the URL "var://foo" will read/write data to/from $GLOBALS["foo"].

Przykład #1 A Stream for reading/writing global variables

<?php

class VariableStream {
    var $position;
    var $varname;

    function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;

        return true;
    }

    function stream_read($count)
    {
        $ret = substr($GLOBALS[$this->varname], $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }

    function stream_write($data)
    {
        $left = substr($GLOBALS[$this->varname], 0, $this->position);
        $right = substr($GLOBALS[$this->varname], $this->position + strlen($data));
        $GLOBALS[$this->varname] = $left . $data . $right;
        $this->position += strlen($data);
        return strlen($data);
    }

    function stream_tell()
    {
        return $this->position;
    }

    function stream_eof()
    {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }

    function stream_seek($offset, $whence)
    {
        switch ($whence) {
            case SEEK_SET:
                if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) {
                     $this->position = $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            case SEEK_CUR:
                if ($offset >= 0) {
                     $this->position += $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            case SEEK_END:
                if (strlen($GLOBALS[$this->varname]) + $offset >= 0) {
                     $this->position = strlen($GLOBALS[$this->varname]) + $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            default:
                return false;
        }
    }

    function stream_metadata($path, $option, $var)
    {
        if($option == STREAM_META_TOUCH) {
            $url = parse_url($path);
            $varname = $url["host"];
            if(!isset($GLOBALS[$varname])) {
                $GLOBALS[$varname] = '';
            }
            return true;
        }
        return false;
    }
}

stream_wrapper_register("var", "VariableStream")
    or die("Failed to register protocol");

$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

?>

Powyższy przykład wyświetli:

line1
line2
line3
string(18) "line1
line2
line3
"

Przykłady
streamWrapper
Przykłady


The streamWrapper class

(No version information available, might only be in SVN)

Wstęp

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Informacja:

This is NOT a real class, only a prototype of how a class defining its own protocol should be.

Informacja:

Implementing the methods in other ways then described here can lead to undefined behaviour.

An instance of this class is initialized as soon as a stream function tries to access the protocol it is associated with.

Krótki opis klasy

streamWrapper {
/* Właściwości */
public resource $context ;
/* Metody */
__construct ( void )
__destruct ( void )
public bool dir_closedir ( void )
public bool dir_opendir ( string $path , int $options )
public string dir_readdir ( void )
public bool dir_rewinddir ( void )
public bool mkdir ( string $path , int $mode , int $options )
public bool rename ( string $path_from , string $path_to )
public bool rmdir ( string $path , int $options )
public resource stream_cast ( int $cast_as )
public void stream_close ( void )
public bool stream_eof ( void )
public bool stream_flush ( void )
public bool stream_lock ( mode $operation )
public bool stream_metadata ( int $path , int $option , int $var )
public bool stream_open ( string $path , string $mode , int $options , string &$opened_path )
public string stream_read ( int $count )
public bool stream_seek ( int $offset , int $whence = SEEK_SET )
public bool stream_set_option ( int $option , int $arg1 , int $arg2 )
public array stream_stat ( void )
public int stream_tell ( void )
public int stream_write ( string $data )
public bool unlink ( string $path )
public array url_stat ( string $path , int $flags )
}

Właściwości

resource context

The current context, or NULL if no context was passed to the caller function.

Use the stream_context_get_options() to parse the context.

Informacja:

This property must be public so PHP can populate it with the actual context resource.

Rejestr zmian

Wersja | Opis
5.0.0 | Added the context property.

Zobacz też:

  • Example class registered as stream wrapper
  • stream_wrapper_register()
  • stream_wrapper_unregister()
  • stream_wrapper_restore()

Spis treści

  • streamWrapper::__construct — Constructs a new stream wrapper
  • streamWrapper::__destruct — Destructs an existing stream wrapper
  • streamWrapper::dir_closedir — Close directory handle
  • streamWrapper::dir_opendir — Open directory handle
  • streamWrapper::dir_readdir — Read entry from directory handle
  • streamWrapper::dir_rewinddir — Rewind directory handle
  • streamWrapper::mkdir — Create a directory
  • streamWrapper::rename — Renames a file or directory
  • streamWrapper::rmdir — Removes a directory
  • streamWrapper::stream_cast — Retrieve the underlaying resource
  • streamWrapper::stream_close — Close an resource
  • streamWrapper::stream_eof — Tests for end-of-file on a file pointer
  • streamWrapper::stream_flush — Flushes the output
  • streamWrapper::stream_lock — Advisory file locking
  • streamWrapper::stream_metadata — Change stream options
  • streamWrapper::stream_open — Opens file or URL
  • streamWrapper::stream_read — Read from stream
  • streamWrapper::stream_seek — Seeks to specific location in a stream
  • streamWrapper::stream_set_option — Change stream options
  • streamWrapper::stream_stat — Retrieve information about a file resource
  • streamWrapper::stream_tell — Retrieve the current position of a stream
  • streamWrapper::stream_write — Write to stream
  • streamWrapper::unlink — Delete a file
  • streamWrapper::url_stat — Retrieve information about a file
Example class registered as stream wrapper
streamWrapper::__construct
Streams


Constructs a new stream wrapper

streamWrapper
streamWrapper::__destruct
streamWrapper
PHP Manual

streamWrapper::__construct

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::__construct — Constructs a new stream wrapper

Opis

streamWrapper::__construct ( void )

Called when opening the stream wrapper, right before streamWrapper::stream_open().

Parametry

Ta funkcja nie posiada parametrów.

streamWrapper
streamWrapper::__destruct
streamWrapper


Destructs an existing stream wrapper

streamWrapper::__construct
streamWrapper::dir_closedir
streamWrapper
PHP Manual

streamWrapper::__destruct

(No version information available, might only be in SVN)

streamWrapper::__destruct — Destructs an existing stream wrapper

Opis

streamWrapper::__destruct ( void )

Called when closing the stream wrapper, right before streamWrapper::stream_flush().

Parametry

Ta funkcja nie posiada parametrów.

streamWrapper::__construct
streamWrapper::dir_closedir
streamWrapper


Close directory handle

streamWrapper::__destruct
streamWrapper::dir_opendir
streamWrapper
PHP Manual

streamWrapper::dir_closedir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_closedir — Close directory handle

Opis

public bool streamWrapper::dir_closedir ( void )

This method is called in response to closedir().

Any resources which were locked, or allocated, during opening and use of the directory stream should be released.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • closedir() - Zamyka wskaźnik katalogu
  • streamWrapper::dir_opendir() - Open directory handle

streamWrapper::__destruct
streamWrapper::dir_opendir
streamWrapper


Open directory handle

streamWrapper::dir_closedir
streamWrapper::dir_readdir
streamWrapper
PHP Manual

streamWrapper::dir_opendir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_opendir — Open directory handle

Opis

public bool streamWrapper::dir_opendir ( string $path , int $options )

This method is called in response to opendir().

Parametry

path

Specifies the URL that was passed to opendir().

Informacja:

The URL can be broken apart with parse_url().

options

Whether or not to enforce safe_mode (0x04).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • opendir() - Otwiera katalog
  • streamWrapper::dir_closedir() - Close directory handle
  • parse_url() - Przetwarza adres URL i zwraca jego składowe

streamWrapper::dir_closedir
streamWrapper::dir_readdir
streamWrapper


Read entry from directory handle

streamWrapper::dir_opendir
streamWrapper::dir_rewinddir
streamWrapper
PHP Manual

streamWrapper::dir_readdir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_readdir — Read entry from directory handle

Opis

public string streamWrapper::dir_readdir ( void )

This method is called in response to readdir().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Should return string representing the next filename, or FALSE if there is no next file.

Informacja:

The return value will be casted to string.

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Przykłady

Przykład #1 Listing files from tar archives

<?php
class streamWrapper {
    protected $fp;

    public function dir_opendir($path, $options) {
        $url = parse_url($path);

        $path = $url["host"] . $url["path"];

        if (!is_readable($path)) {
            trigger_error("$path isn't readable for me", E_USER_NOTICE);
            return false;
        }
        if (!is_file($path)) {
            trigger_error("$path isn't a file", E_USER_NOTICE);
            return false;
        }

        $this->fp = fopen($path, "rb");
        return true;
    }

    public function dir_readdir() {
        // Extract the header for this entry
        $header      = fread($this->fp, 512);
        $data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1filetype/a100link/a100linkedfile", $header);

        // Trim the filename and filesize
        $filename    = trim($data["filename"]);

        // No filename? We are the end of the archive
        if (!$filename) {
            return false;
        }

        $octal_bytes = trim($data["size"]);
        // Filesize is defined in octects
        $bytes       = octdec($octal_bytes);

        // tar rounds up filesizes up to multiple of 512 bytes (zero filled)
        $rest        = $bytes % 512;
        if ($rest > 0) {
            $bytes      += 512 - $rest;
        }

        // Seek over the file
        fseek($this->fp, $bytes, SEEK_CUR);

        return $filename;
    }

    public function dir_closedir() {
        return fclose($this->fp);
    }

    public function dir_rewinddir() {
        return fseek($this->fp, 0, SEEK_SET);
    }
}

stream_wrapper_register("tar", "streamWrapper");
$handle = opendir("tar://example.tar");
while (false !== ($file = readdir($handle))) {
    var_dump($file);
}

echo "Rewinding..\n";
rewind($handle);
var_dump(readdir($handle));

closedir($handle);
?>

Powyższy przykład wyświetli coś podobnego do:

string(13) "construct.xml"
string(16) "dir-closedir.xml"
string(15) "dir-opendir.xml"
string(15) "dir-readdir.xml"
string(17) "dir-rewinddir.xml"
string(9) "mkdir.xml"
string(10) "rename.xml"
string(9) "rmdir.xml"
string(15) "stream-cast.xml"
string(16) "stream-close.xml"
string(14) "stream-eof.xml"
string(16) "stream-flush.xml"
string(15) "stream-lock.xml"
string(15) "stream-open.xml"
string(15) "stream-read.xml"
string(15) "stream-seek.xml"
string(21) "stream-set-option.xml"
string(15) "stream-stat.xml"
string(15) "stream-tell.xml"
string(16) "stream-write.xml"
string(10) "unlink.xml"
string(12) "url-stat.xml"
Rewinding..
string(13) "construct.xml"

Zobacz też:

  • readdir() - Czyta zawartość katalogu

streamWrapper::dir_opendir
streamWrapper::dir_rewinddir
streamWrapper


Rewind directory handle

streamWrapper::dir_readdir
streamWrapper::mkdir
streamWrapper
PHP Manual

streamWrapper::dir_rewinddir

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::dir_rewinddir — Rewind directory handle

Opis

public bool streamWrapper::dir_rewinddir ( void )

This method is called in response to rewinddir().

Should reset the output generated by streamWrapper::dir_readdir(). i.e.: The next call to streamWrapper::dir_readdir() should return the first entry in the location returned by streamWrapper::dir_opendir().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • rewinddir() - Ustawia wskaźnik katalogu na początek
  • streamWrapper::dir_readdir() - Read entry from directory handle

streamWrapper::dir_readdir
streamWrapper::mkdir
streamWrapper


Create a directory

streamWrapper::dir_rewinddir
streamWrapper::rename
streamWrapper
PHP Manual

streamWrapper::mkdir

(PHP 5)

streamWrapper::mkdir — Create a directory

Opis

public bool streamWrapper::mkdir ( string $path , int $mode , int $options )

This method is called in response to mkdir().

Informacja:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support creating directories.

Parametry

path

Directory which should be created.

mode

The value passed to mkdir().

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Notatki

Informacja:

Właściwość streamWrapper->context jest aktualizowana, jeśli do wywołującej funkcji jest przekazywany prawidłowy kontekst.

Zobacz też:

  • mkdir() - Tworzy katalog
  • streamwrapper::rmdir() - Removes a directory

streamWrapper::dir_rewinddir
streamWrapper::rename
streamWrapper


Renames a file or directory

streamWrapper::mkdir
streamWrapper::rmdir
streamWrapper
PHP Manual

streamWrapper::rename

(PHP 5)

streamWrapper::rename — Renames a file or directory

Opis

public bool streamWrapper::rename ( string $path_from , string $path_to )

This method is called in response to rename().

Should attempt to rename path_from to path_to

Informacja:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support renaming files.

Parametry

path_from

The URL to the current file.

path_to

The URL which the path_from should be renamed to.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Notatki

Informacja:

Właściwość streamWrapper->context jest aktualizowana, jeśli do wywołującej funkcji jest przekazywany prawidłowy kontekst.

Zobacz też:

  • rename() - Renames a file or directory

streamWrapper::mkdir
streamWrapper::rmdir
streamWrapper


Removes a directory

streamWrapper::rename
streamWrapper::stream_cast
streamWrapper
PHP Manual

streamWrapper::rmdir

(PHP 5)

streamWrapper::rmdir — Removes a directory

Opis

public bool streamWrapper::rmdir ( string $path , int $options )

This method is called in response to rmdir().

Informacja:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing directories.

Parametry

path

The directory URL which should be removed.

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Notatki

Informacja:

Właściwość streamWrapper->context jest aktualizowana, jeśli do wywołującej funkcji jest przekazywany prawidłowy kontekst.

Zobacz też:

  • rmdir() - Usuwanie katalogów
  • streamwrapper::mkdir() - Create a directory
  • streamwrapper::unlink() - Delete a file

streamWrapper::rename
streamWrapper::stream_cast
streamWrapper


Retrieve the underlaying resource

streamWrapper::rmdir
streamWrapper::stream_close
streamWrapper
PHP Manual

streamWrapper::stream_cast

(PHP 5 >= 5.3.0)

streamWrapper::stream_cast — Retrieve the underlaying resource

Opis

public resource streamWrapper::stream_cast ( int $cast_as )

This method is called in response to stream_select().

Parametry

cast_as

Can be STREAM_CAST_FOR_SELECT when stream_select() is calling stream_cast() or STREAM_CAST_AS_STREAM when stream_cast() is called for other uses.

Zwracane wartości

Should return the underlying stream resource used by the wrapper, or FALSE.

Zobacz też:

  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

streamWrapper::rmdir
streamWrapper::stream_close
streamWrapper


Close an resource

streamWrapper::stream_cast
streamWrapper::stream_eof
streamWrapper
PHP Manual

streamWrapper::stream_close

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_close — Close an resource

Opis

public void streamWrapper::stream_close ( void )

This method is called in response to fclose().

All resources that were locked, or allocated, by the wrapper should be released.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • fclose() - Zamyka otwarty wskaźnik pliku
  • streamWrapper::dir_closedir() - Close directory handle

streamWrapper::stream_cast
streamWrapper::stream_eof
streamWrapper


Tests for end-of-file on a file pointer

streamWrapper::stream_close
streamWrapper::stream_flush
streamWrapper
PHP Manual

streamWrapper::stream_eof

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_eof — Tests for end-of-file on a file pointer

Opis

public bool streamWrapper::stream_eof ( void )

This method is called in response to feof().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Should return TRUE if the read/write position is at the end of the stream and if no more data is available to be read, or FALSE otherwise.

Notatki

Ostrzeżenie

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

Zobacz też:

  • feof() - Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)

streamWrapper::stream_close
streamWrapper::stream_flush
streamWrapper


Flushes the output

streamWrapper::stream_eof
streamWrapper::stream_lock
streamWrapper
PHP Manual

streamWrapper::stream_flush

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_flush — Flushes the output

Opis

public bool streamWrapper::stream_flush ( void )

This method is called in response to fflush().

If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Should return TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.

Notatki

Informacja:

If not implemented, FALSE is assumed as the return value.

Zobacz też:

  • fflush() - Przekierowuje wyjście do pliku

streamWrapper::stream_eof
streamWrapper::stream_lock
streamWrapper


Advisory file locking

streamWrapper::stream_flush
streamWrapper::stream_metadata
streamWrapper
PHP Manual

streamWrapper::stream_lock

(PHP 5)

streamWrapper::stream_lock — Advisory file locking

Opis

public bool streamWrapper::stream_lock ( mode $operation )

This method is called in response to flock(), when file_put_contents() (when flags contains LOCK_EX), stream_set_blocking() and when closing the stream (LOCK_UN).

Parametry

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB if you don't want flock() to block while locking. (not supported on Windows)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Emits E_WARNING if call to this method fails (i.e. not implemented).

Zobacz też:

  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • flock() - Portable advisory file locking

streamWrapper::stream_flush
streamWrapper::stream_metadata
streamWrapper


Change stream options

streamWrapper::stream_lock
streamWrapper::stream_open
streamWrapper
PHP Manual

streamWrapper::stream_metadata

(No version information available, might only be in SVN)

streamWrapper::stream_metadata — Change stream options

Opis

public bool streamWrapper::stream_metadata ( int $path , int $option , int $var )

This method is called to set metadata on the stream. It is called when one of the following functions is called on a stream URL:

  • touch()
  • chmod()
  • chown()
  • chgrp()
Please note that some of these operations may not be available on your system.

Informacja: The function is available since PHP 5.4.0.

Parametry

path

The file path or URL to set metadata. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

option

One of:

  • PHP_STREAM_META_TOUCH (The method was called in response to touch())
  • PHP_STREAM_META_OWNER_NAME (The method was called in response to chown() with string parameter)
  • PHP_STREAM_META_OWNER (The method was called in response to chown())
  • PHP_STREAM_META_GROUP_NAME (The method was called in response to chgrp())
  • PHP_STREAM_META_GROUP (The method was called in response to chgrp())
  • PHP_STREAM_META_ACCESS (The method was called in response to chmod())

arg1

If option is

  • PHP_STREAM_META_TOUCH: Array consisting of two arguments of the touch() function.
  • PHP_STREAM_META_OWNER_NAME or PHP_STREAM_META_GROUP_NAME: The name of the owner user/group as string.
  • PHP_STREAM_META_OWNER or PHP_STREAM_META_GROUP: The value owner user/group argument as integer.
  • PHP_STREAM_META_ACCESS: The argument of the chmod() as integer.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If option is not implemented, FALSE should be returned.

Zobacz też:

  • touch() - Ustawia czas modyfikacji pliku
  • chmod() - Zmienia prawa dostępu do pliku
  • chown() - Zmienia właściciela pliku
  • chgrp() - Zmienia grupę pliku

streamWrapper::stream_lock
streamWrapper::stream_open
streamWrapper


Opens file or URL

streamWrapper::stream_metadata
streamWrapper::stream_read
streamWrapper
PHP Manual

streamWrapper::stream_open

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_open — Opens file or URL

Opis

public bool streamWrapper::stream_open ( string $path , string $mode , int $options , string &$opened_path )

This method is called immediately after the wrapper is initialized (f.e. by fopen() and file_get_contents()).

Parametry

path

Specifies the URL that was passed to the original function.

Informacja:

The URL can be broken apart with parse_url(). Note that only URLs delimited by :// are supported. : and :/ while technically valid URLs, are not.

mode

The mode used to open the file, as detailed for fopen().

Informacja:

Remember to check if the mode is valid for the path requested.

options

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_USE_PATH | If path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORS | If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.

opened_path

If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path should be set to the full path of the file/resource that was actually opened.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Notatki

Informacja:

Właściwość streamWrapper->context jest aktualizowana, jeśli do wywołującej funkcji jest przekazywany prawidłowy kontekst.

Zobacz też:

  • fopen() - Otwiera plik lub URL
  • parse_url() - Przetwarza adres URL i zwraca jego składowe

streamWrapper::stream_metadata
streamWrapper::stream_read
streamWrapper


Read from stream

streamWrapper::stream_open
streamWrapper::stream_seek
streamWrapper
PHP Manual

streamWrapper::stream_read

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_read — Read from stream

Opis

public string streamWrapper::stream_read ( int $count )

This method is called in response to fread() and fgets().

Informacja:

Remember to update the read/write position of the stream (by the number of bytes that were successfully read).

Parametry

count

How many bytes of data from the current position should be returned.

Zwracane wartości

If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string.

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Informacja:

If the return value is longer then count an E_WARNING error will be emitted, and excess data will be lost.

Notatki

Informacja:

streamWrapper::stream_eof() is called directly after calling streamWrapper::stream_read() to check if EOF has been reached. If not implemented, EOF is assumed.

Ostrzeżenie

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

Zobacz też:

  • fread() - Odczyt pliku binarnie bezpieczy
  • fgets() - Pobiera linię ze wskaźnika pliku

streamWrapper::stream_open
streamWrapper::stream_seek
streamWrapper


Seeks to specific location in a stream

streamWrapper::stream_read
streamWrapper::stream_set_option
streamWrapper
PHP Manual

streamWrapper::stream_seek

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_seek — Seeks to specific location in a stream

Opis

public bool streamWrapper::stream_seek ( int $offset , int $whence = SEEK_SET )

This method is called in response to fseek().

The read/write position of the stream should be updated according to the offset and whence.

Parametry

offset

The stream offset to seek to.

whence

Possible values:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

Zwracane wartości

Return TRUE if the position was updated, FALSE otherwise.

Notatki

Informacja:

If not implemented, FALSE is assumed as the return value.

Informacja:

Upon success,
 streamWrapper::stream_tell() is called directly after
calling  streamWrapper::stream_seek(). If
 streamWrapper::stream_tell() fails, the return
value to the caller function will be set to FALSE

Informacja:

Not all seeks operations on the stream will result in this function being called. PHP streams have read buffering enabled by default (see also stream_set_read_buffer()) and seeking may be done by merely moving the buffer pointer.

Zobacz też:

  • fseek() - Seeks on a file pointer

streamWrapper::stream_read
streamWrapper::stream_set_option
streamWrapper


Change stream options

streamWrapper::stream_seek
streamWrapper::stream_stat
streamWrapper
PHP Manual

streamWrapper::stream_set_option

(PHP 5 >= 5.3.0)

streamWrapper::stream_set_option — Change stream options

Opis

public bool streamWrapper::stream_set_option ( int $option , int $arg1 , int $arg2 )

This method is called to set options on the stream.

Parametry

option

One of:

  • STREAM_OPTION_BLOCKING (The method was called in response to stream_set_blocking())
  • STREAM_OPTION_READ_TIMEOUT (The method was called in response to stream_set_timeout())
  • STREAM_OPTION_WRITE_BUFFER (The method was called in response to stream_set_write_buffer())

arg1

If option is

  • STREAM_OPTION_BLOCKING: requested blocking mode (1 meaning block 0 not blocking).
  • STREAM_OPTION_READ_TIMEOUT: the timeout in seconds.
  • STREAM_OPTION_WRITE_BUFFER: buffer mode (STREAM_BUFFER_NONE or STREAM_BUFFER_FULL).

arg2

If option is

  • STREAM_OPTION_BLOCKING: This option is not set.
  • STREAM_OPTION_READ_TIMEOUT: the timeout in microseconds.
  • STREAM_OPTION_WRITE_BUFFER: the requested buffer size.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If option is not implemented, FALSE should be returned.

Zobacz też:

  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • stream_set_write_buffer() - Sets write file buffering on the given stream

streamWrapper::stream_seek
streamWrapper::stream_stat
streamWrapper


Retrieve information about a file resource

streamWrapper::stream_set_option
streamWrapper::stream_tell
streamWrapper
PHP Manual

streamWrapper::stream_stat

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_stat — Retrieve information about a file resource

Opis

public array streamWrapper::stream_stat ( void )

This method is called in response to fstat().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

See stat().

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Zobacz też:

  • stat() - Gives information about a file
  • streamwrapper::url_stat() - Retrieve information about a file

streamWrapper::stream_set_option
streamWrapper::stream_tell
streamWrapper


Retrieve the current position of a stream

streamWrapper::stream_stat
streamWrapper::stream_write
streamWrapper
PHP Manual

streamWrapper::stream_tell

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_tell — Retrieve the current position of a stream

Opis

public int streamWrapper::stream_tell ( void )

This method is called in response to fseek() to determine the current position.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Should return the current position of the stream.

Zobacz też:

  • streamWrapper::stream_tell()

streamWrapper::stream_stat
streamWrapper::stream_write
streamWrapper


Write to stream

streamWrapper::stream_tell
streamWrapper::unlink
streamWrapper
PHP Manual

streamWrapper::stream_write

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::stream_write — Write to stream

Opis

public int streamWrapper::stream_write ( string $data )

This method is called in response to fwrite().

Informacja:

Remember to update the current position of the stream by number of bytes that were successfully written.

Parametry

data

Should be stored into the underlying stream.

Informacja:

If there is not enough room in the underlying stream, store as much as possible.

Zwracane wartości

Should return the number of bytes that were successfully stored, or 0 if none could be stored.

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Informacja:

If the return value is greater the length of data, E_WARNING will be emitted and the return value will truncated to its length.

Zobacz też:

  • fwrite() - Zapis pliku binarnie bezpieczny

streamWrapper::stream_tell
streamWrapper::unlink
streamWrapper


Delete a file

streamWrapper::stream_write
streamWrapper::url_stat
streamWrapper
PHP Manual

streamWrapper::unlink

(PHP 5)

streamWrapper::unlink — Delete a file

Opis

public bool streamWrapper::unlink ( string $path )

This method is called in response to unlink().

Informacja:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing files.

Parametry

path

The file URL which should be deleted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Notatki

Informacja:

Właściwość streamWrapper->context jest aktualizowana, jeśli do wywołującej funkcji jest przekazywany prawidłowy kontekst.

Zobacz też:

  • unlink() - Kasowanie pliku
  • streamWrapper::rmdir() - Removes a directory

streamWrapper::stream_write
streamWrapper::url_stat
streamWrapper


Retrieve information about a file

streamWrapper::unlink
Stream Funkcje
streamWrapper
PHP Manual

streamWrapper::url_stat

(PHP 4 >= 4.3.2, PHP 5)

streamWrapper::url_stat — Retrieve information about a file

Opis

public array streamWrapper::url_stat ( string $path , int $flags )

This method is called in response to all stat() related functions, such as:

  • chmod() (only when safe_mode is enabled)
  • copy()
  • fileperms()
  • fileinode()
  • filesize()
  • fileowner()
  • filegroup()
  • fileatime()
  • filemtime()
  • filectime()
  • filetype()
  • is_writable()
  • is_readable()
  • is_executable()
  • is_file()
  • is_dir()
  • is_link()
  • file_exists()
  • lstat()
  • stat()
  • SplFileInfo::getPerms()
  • SplFileInfo::getInode()
  • SplFileInfo::getSize()
  • SplFileInfo::getOwner()
  • SplFileInfo::getGroup()
  • SplFileInfo::getATime()
  • SplFileInfo::getMTime()
  • SplFileInfo::getCTime()
  • SplFileInfo::getType()
  • SplFileInfo::isWritable()
  • SplFileInfo::isReadable()
  • SplFileInfo::isExecutable()
  • SplFileInfo::isFile()
  • SplFileInfo::isDir()
  • SplFileInfo::isLink()
  • RecursiveDirectoryIterator::hasChildren()

Parametry

path

The file path or URL to stat. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

flags

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_URL_STAT_LINK | For resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype().
STREAM_URL_STAT_QUIET | If this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error() function during stating of the path.

Zwracane wartości

Should return as many elements as stat() does. Unknown or unavailable values should be set to a rational value (usually 0).

Błędy/Wyjątki

Zgłasza E_WARNING jeśli wywołanie tej metody nie powiedzie się (np. nie jest zaimplementowana).

Notatki

Informacja:

Właściwość streamWrapper->context jest aktualizowana, jeśli do wywołującej funkcji jest przekazywany prawidłowy kontekst.

Zobacz też:

  • stat() - Gives information about a file
  • streamwrapper::stream_stat() - Retrieve information about a file resource

streamWrapper::unlink
Stream Funkcje
streamWrapper


Stream Funkcje

Spis treści

  • set_socket_blocking — Alias dla stream_set_blocking
  • stream_bucket_append — Append bucket to brigade
  • stream_bucket_make_writeable — Return a bucket object from the brigade for operating on
  • stream_bucket_new — Create a new bucket for use on the current stream
  • stream_bucket_prepend — Prepend bucket to brigade
  • stream_context_create — Create a streams context
  • stream_context_get_default — Retrieve the default streams context
  • stream_context_get_options — Retrieve options for a stream/wrapper/context
  • stream_context_get_params — Retrieves parameters from a context
  • stream_context_set_default — Set the default streams context
  • stream_context_set_option — Sets an option for a stream/wrapper/context
  • stream_context_set_params — Set parameters for a stream/wrapper/context
  • stream_copy_to_stream — Copies data from one stream to another
  • stream_encoding — Set character set for stream encoding
  • stream_filter_append — Attach a filter to a stream
  • stream_filter_prepend — Attach a filter to a stream
  • stream_filter_register — Register a user defined stream filter
  • stream_filter_remove — Remove a filter from a stream
  • stream_get_contents — Reads remainder of a stream into a string
  • stream_get_filters — Retrieve list of registered filters
  • stream_get_line — Gets line from stream resource up to a given delimiter
  • stream_get_meta_data — Retrieves header/meta data from streams/file pointers
  • stream_get_transports — Retrieve list of registered socket transports
  • stream_get_wrappers — Retrieve list of registered streams
  • stream_is_local — Checks if a stream is a local stream
  • stream_notification_callback — A callback function for the notification context paramater
  • stream_register_wrapper — Alias dla stream_wrapper_register
  • stream_resolve_include_path — Resolve filename against the include path
  • stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • stream_set_blocking — Set blocking/non-blocking mode on a stream
  • stream_set_read_buffer — Set read file buffering on the given stream
  • stream_set_timeout — Set timeout period on a stream
  • stream_set_write_buffer — Sets write file buffering on the given stream
  • stream_socket_accept — Accept a connection on a socket created by stream_socket_server
  • stream_socket_client — Open Internet or Unix domain socket connection
  • stream_socket_enable_crypto — Turns encryption on/off on an already connected socket
  • stream_socket_get_name — Retrieve the name of the local or remote sockets
  • stream_socket_pair — Creates a pair of connected, indistinguishable socket streams
  • stream_socket_recvfrom — Receives data from a socket, connected or not
  • stream_socket_sendto — Sends a message to a socket, whether it is connected or not
  • stream_socket_server — Create an Internet or Unix domain server socket
  • stream_socket_shutdown — Shutdown a full-duplex connection
  • stream_supports_lock — Tells whether the stream supports locking.
  • stream_wrapper_register — Register a URL wrapper implemented as a PHP class
  • stream_wrapper_restore — Restores a previously unregistered built-in wrapper
  • stream_wrapper_unregister — Unregister a URL wrapper
streamWrapper::url_stat
set_socket_blocking
Streams


Alias dla stream_set_blocking

Stream Funkcje
stream_bucket_append
Stream Funkcje
PHP Manual

set_socket_blocking

(PHP 4, PHP 5)

set_socket_blocking — Alias dla stream_set_blocking()

Opis

Ta funkcja jest aliasem dla: stream_set_blocking()

Ostrzeżenie

Ten alias funkcji jest PRZESTARZAŁY od PHP 5.3.0. Używanie tego aliasu nie jest zalecane.

Stream Funkcje
stream_bucket_append
Stream Funkcje


Append bucket to brigade

set_socket_blocking
stream_bucket_make_writeable
Stream Funkcje
PHP Manual

stream_bucket_append

(PHP 5)

stream_bucket_append — Append bucket to brigade

Opis

void stream_bucket_append ( resource $brigade , resource $bucket )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

set_socket_blocking
stream_bucket_make_writeable
Stream Funkcje


Return a bucket object from the brigade for operating on

stream_bucket_append
stream_bucket_new
Stream Funkcje
PHP Manual

stream_bucket_make_writeable

(PHP 5)

stream_bucket_make_writeable — Return a bucket object from the brigade for operating on

Opis

object stream_bucket_make_writeable ( resource $brigade )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

stream_bucket_append
stream_bucket_new
Stream Funkcje


Create a new bucket for use on the current stream

stream_bucket_make_writeable
stream_bucket_prepend
Stream Funkcje
PHP Manual

stream_bucket_new

(PHP 5)

stream_bucket_new — Create a new bucket for use on the current stream

Opis

object stream_bucket_new ( resource $stream , string $buffer )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

stream_bucket_make_writeable
stream_bucket_prepend
Stream Funkcje


Prepend bucket to brigade

stream_bucket_new
stream_context_create
Stream Funkcje
PHP Manual

stream_bucket_prepend

(PHP 5)

stream_bucket_prepend — Prepend bucket to brigade

Opis

void stream_bucket_prepend ( resource $brigade , resource $bucket )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

stream_bucket_new
stream_context_create
Stream Funkcje


Create a streams context

stream_bucket_prepend
stream_context_get_default
Stream Funkcje
PHP Manual

stream_context_create

(PHP 4 >= 4.3.0, PHP 5)

stream_context_create — Create a streams context

Opis

resource stream_context_create ([ array $options [, array $params ]] )

Creates and returns a stream context with any options supplied in options preset.

Parametry

options

Must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Default to an empty array.

params

Must be an associative array in the format $arr['parameter'] = $value. Refer to context parameters for a listing of standard stream parameters.

Zwracane wartości

A stream context resource.

Rejestr zmian

Wersja | Opis
5.3.0 | Added the optional params argument.

Przykłady

Przykład #1 Using stream_context_create()

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

/* Sends an http request to www.example.com
   with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>

Zobacz też:

  • stream_context_set_option() - Sets an option for a stream/wrapper/context
  • Listing of supported wrappers (Supported Protocols and Wrappers)
  • Context options (Context options and parameters)
stream_bucket_prepend
stream_context_get_default
Stream Funkcje


Retrieve the default streams context

stream_context_create
stream_context_get_options
Stream Funkcje
PHP Manual

stream_context_get_default

(PHP 5 >= 5.1.0)

stream_context_get_default — Retrieve the default streams context

Opis

resource stream_context_get_default ([ array $options ] )

Returns the default stream context which is used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Options for the default context can optionally be specified with this function using the same syntax as stream_context_create().

Parametry

options
options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Informacja:

As of PHP 5.3.0, the stream_context_set_default() function can be used to set the default context.

Zwracane wartości

A stream context resource.

Przykłady

Przykład #1 Using stream_context_get_default()

<?php
$default_opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar",
    'proxy'=>"tcp://10.54.1.39:8000"
  )
);

$alternate_opts = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>"Content-type: application/x-www-form-urlencoded\r\n" .
              "Content-length: " . strlen("baz=bomb"),
    'content'=>"baz=bomb"
  )
);

$default = stream_context_get_default($default_opts);
$alternate = stream_context_create($alternate_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');

/* Sends a POST request directly to www.example.com
 * Using context options specified in $alternate_opts
 */
readfile('http://www.example.com', false, $alternate);

?>

Zobacz też:

  • stream_context_create() - Create a streams context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).

stream_context_create
stream_context_get_options
Stream Funkcje


Retrieve options for a stream/wrapper/context

stream_context_get_default
stream_context_get_params
Stream Funkcje
PHP Manual

stream_context_get_options

(PHP 4 >= 4.3.0, PHP 5)

stream_context_get_options — Retrieve options for a stream/wrapper/context

Opis

array stream_context_get_options ( resource $stream_or_context )

Returns an array of options on the specified stream or context.

Parametry

stream_or_context

The stream or context to get options from

Zwracane wartości

Returns an associative array with the options.

Przykłady

Przykład #1 stream_context_get_options() example

<?php
$params = array("method" => "POST");

stream_context_get_default(array("http" => $params));

var_dump(stream_context_get_options(stream_context_get_default()));

?>

Powyższy przykład wyświetli coś podobnego do:

array(1) {
  ["http"]=>
  array(1) {
    ["method"]=>
    string(4) "POST"
  }
}

stream_context_get_default
stream_context_get_params
Stream Funkcje


Retrieves parameters from a context

stream_context_get_options
stream_context_set_default
Stream Funkcje
PHP Manual

stream_context_get_params

(PHP 5 >= 5.3.0)

stream_context_get_params — Retrieves parameters from a context

Opis

array stream_context_get_params ( resource $stream_or_context )

Retrieves parameter and options information from the stream or context.

Parametry

stream_or_context

A stream resource or a context resource

Zwracane wartości

Returns an associate array containing all context options and parameters.

Przykłady

Przykład #1 stream_context_get_params() example

Basic usage example

<?php
$ctx = stream_context_create();
$params = array("notification" => "stream_notification_callback");
stream_context_set_params($ctx, $params);

var_dump(stream_context_get_params($ctx));
?>

Powyższy przykład wyświetli coś podobnego do:

array(2) {
  ["notification"]=>
  string(28) "stream_notification_callback"
  ["options"]=>
  array(0) {
  }
}

Zobacz też:

  • stream_context_set_option() - Sets an option for a stream/wrapper/context
  • stream_context_get_params()
  • stream_context_set_params() - Set parameters for a stream/wrapper/context

stream_context_get_options
stream_context_set_default
Stream Funkcje


Set the default streams context

stream_context_get_params
stream_context_set_option
Stream Funkcje
PHP Manual

stream_context_set_default

(PHP 5 >= 5.3.0)

stream_context_set_default — Set the default streams context

Opis

resource stream_context_set_default ( array $options )

Set the default stream context which will be used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Uses the same syntax as stream_context_create().

Parametry

options

The options to set for the default context.

Informacja:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Zwracane wartości

Returns the default stream context.

Przykłady

Przykład #1 stream_context_set_default() example

<?php
$default_opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar",
    'proxy'=>"tcp://10.54.1.39:8000"
  )
);

$default = stream_context_set_default($default_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');
?>

Zobacz też:

  • stream_context_create() - Create a streams context
  • stream_context_get_default() - Retrieve the default streams context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).

stream_context_get_params
stream_context_set_option
Stream Funkcje


Sets an option for a stream/wrapper/context

stream_context_set_default
stream_context_set_params
Stream Funkcje
PHP Manual

stream_context_set_option

(PHP 4 >= 4.3.0, PHP 5)

stream_context_set_option — Sets an option for a stream/wrapper/context

Opis

bool stream_context_set_option ( resource $stream_or_context , string $wrapper , string $option , mixed $value )
bool stream_context_set_option ( resource $stream_or_context , array $options )

Sets an option on the specified context. value is set to option for wrapper

Parametry

stream_or_context

The stream or context resource to apply the options too.

options

The options to set for the default context.

Informacja:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Refer to context options and parameters for a listing of stream options.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

stream_context_set_default
stream_context_set_params
Stream Funkcje


Set parameters for a stream/wrapper/context

stream_context_set_option
stream_copy_to_stream
Stream Funkcje
PHP Manual

stream_context_set_params

(PHP 4 >= 4.3.0, PHP 5)

stream_context_set_params — Set parameters for a stream/wrapper/context

Opis

bool stream_context_set_params ( resource $stream_or_context , array $params )

Sets parameters on the specified context.

Parametry

stream_or_context

The stream or context to apply the parameters too.

params

An array of parameters to set.

Informacja:

params should be an associative array of the structure: $params['paramname'] = "paramvalue";.

Supported parameters

Parameters | Purpose
notification | Name of user-defined callback function to be called whenever a stream triggers a notification.
options | Array of options as in context options and parameters.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • stream_notification_callback() - A callback function for the notification context paramater
stream_context_set_option
stream_copy_to_stream
Stream Funkcje


Copies data from one stream to another

stream_context_set_params
stream_encoding
Stream Funkcje
PHP Manual

stream_copy_to_stream

(PHP 5)

stream_copy_to_stream — Copies data from one stream to another

Opis

int stream_copy_to_stream ( resource $source , resource $dest [, int $maxlength = -1 [, int $offset = 0 ]] )

Makes a copy of up to maxlength bytes of data from the current position (or from the offset position, if specified) in source to dest. If maxlength is not specified, all remaining content in source will be copied.

Parametry

source

The source stream

dest

The destination stream

maxlength

Maximum bytes to copy

offset

The offset where to start to copy data

Zwracane wartości

Returns the total count of bytes copied.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the offset parameter

Przykłady

Przykład #1 A stream_copy_to_stream() example

<?php
$src = fopen('http://www.example.com', 'r');
$dest1 = fopen('first1k.txt', 'w');
$dest2 = fopen('remainder.txt', 'w');

echo stream_copy_to_stream($src, $dest1, 1024) . " bytes copied to first1k.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n";

?>

Zobacz też:

  • copy() - Kopiuje plik

stream_context_set_params
stream_encoding
Stream Funkcje


Set character set for stream encoding

stream_copy_to_stream
stream_filter_append
Stream Funkcje
PHP Manual

stream_encoding

(No version information available, might only be in SVN)

stream_encoding — Set character set for stream encoding

Opis

bool stream_encoding ( resource $stream [, string $encoding ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

stream_copy_to_stream
stream_filter_append
Stream Funkcje


Attach a filter to a stream

stream_encoding
stream_filter_prepend
Stream Funkcje
PHP Manual

stream_filter_append

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_append — Attach a filter to a stream

Opis

resource stream_filter_append ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] )

Adds filtername to the list of filters attached to stream.

Parametry

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.

params

This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend().

Zwracane wartości

Returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove().

Rejestr zmian

Wersja | Opis
5.1.0 | Prior to PHP 5.1.0, this function returns TRUE on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Controlling where filters are applied

<?php
/* Open a test file for reading and writing */
$fp = fopen('test.txt', 'w+');

/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* Write a simple string to the file
 * it will be ROT13 transformed on the
 * way out */
fwrite($fp, "This is a test\n");

/* Back up to the beginning of the file */
rewind($fp);

/* Read the contents of the file back out.
 * Had the filter been applied to the
 * read filter chain as well, we would see
 * the text ROT13ed back to its original state */
fpassthru($fp);

fclose($fp);

/* Expected Output
   ---------------

Guvf vf n grfg

 */
?>

Notatki

Informacja: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Informacja: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().

Informacja: When a filter is added for read and write, two instances of the filter are created. stream_filter_append() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

Zobacz też:

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_prepend() - Attach a filter to a stream
  • stream_get_filters() - Retrieve list of registered filters
stream_encoding
stream_filter_prepend
Stream Funkcje


Attach a filter to a stream

stream_filter_append
stream_filter_register
Stream Funkcje
PHP Manual

stream_filter_prepend

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_prepend — Attach a filter to a stream

Opis

resource stream_filter_prepend ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] )

Adds filtername to the list of filters attached to stream.

Parametry

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_prepend() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. See stream_filter_append() for an example of using this parameter.

params

This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use stream_filter_append().

Zwracane wartości

Returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove().

Rejestr zmian

Wersja | Opis
5.1.0 | Prior to PHP 5.1.0, this function returns TRUE on success lub FALSE w przypadku niepowodzenia.

Notatki

Informacja: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Informacja: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will not be reprocessed through the new filter at that time. This differs from the behavior of stream_filter_append().

Informacja: When a filter is added for read and write, two instances of the filter are created. stream_filter_prepend() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

Zobacz też:

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream
stream_filter_append
stream_filter_register
Stream Funkcje


Register a user defined stream filter

stream_filter_prepend
stream_filter_remove
Stream Funkcje
PHP Manual

stream_filter_register

(PHP 5)

stream_filter_register — Register a user defined stream filter

Opis

bool stream_filter_register ( string $filtername , string $classname )

stream_filter_register() allows you to implement your own filter on any registered stream used with all the other filesystem functions (such as fopen(), fread() etc.).

Parametry

filtername

The filter name to be registered.

classname

To implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions as defined below. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.

int filter ( resource $in , resource $out , int &$consumed , bool $closing )

This method is called whenever data is read from or written to the attached stream (such as with fread() or fwrite()). in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered. out is a resource pointing to a second bucket brigade into which your modified buckets should be placed. consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket. If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE. The filter() method must return one of three values upon completion.

Return Value | Meaning
PSFS_PASS_ON | Filter processed successfully with data available in the out bucket brigade.
PSFS_FEED_ME | Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default) | The filter experienced an unrecoverable error and cannot continue.

bool onCreate ( void )
This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it. Your implementation of this method should return FALSE on failure, or TRUE on success. When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

Property | Contents
FilterClass->filtername | A string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->params | The contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().
FilterClass->stream | The stream resource being filtered. Maybe available only during filter() calls when the closing parameter is set to FALSE.

void onClose ( void )

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialized during onCreate() this would be the time to destroy or dispose of them.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

stream_filter_register() will return FALSE if the filtername is already defined.

Przykłady

Przykład #1 Filter for capitalizing characters on foo-bar.txt stream

The example below implements a filter named strtoupper on the foo-bar.txt stream which will capitalize all letter characters written to/read from that stream.

<?php

/* Define our filter class */
class strtoupper_filter extends php_user_filter {
  function filter($in, $out, &$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $bucket->data = strtoupper($bucket->data);
      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }
}

/* Register our filter with PHP */
stream_filter_register("strtoupper", "strtoupper_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened */
stream_filter_append($fp, "strtoupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");

?>

Powyższy przykład wyświetli:

LINE1
WORD - 2
EASY AS 123

Przykład #2 Registering a generic filter class to match multiple filter names.

<?php

/* Define our filter class */
class string_filter extends php_user_filter {
  var $mode;

  function filter($in, $out, &$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      if ($this->mode == 1) {
        $bucket->data = strtoupper($bucket->data);
      } elseif ($this->mode == 0) {
        $bucket->data = strtolower($bucket->data);
      }

      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }

  function onCreate()
  {
    if ($this->filtername == 'str.toupper') {
      $this->mode = 1;
    } elseif ($this->filtername == 'str.tolower') {
      $this->mode = 0;
    } else {
      /* Some other str.* filter was asked for,
         report failure so that PHP will keep looking */
      return false;
    }

    return true;
  }
}

/* Register our filter with PHP */
stream_filter_register("str.*", "string_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened
   We could alternately bind to str.tolower here */
stream_filter_append($fp, "str.toupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");
?>

Powyższy przykład wyświetli:

LINE1
WORD - 2
EASY AS 123

Zobacz też:

  • stream_wrapper_register() - Register a URL wrapper implemented as a PHP class
  • stream_filter_append() - Attach a filter to a stream
  • stream_filter_prepend() - Attach a filter to a stream

stream_filter_prepend
stream_filter_remove
Stream Funkcje


Remove a filter from a stream

stream_filter_register
stream_get_contents
Stream Funkcje
PHP Manual

stream_filter_remove

(PHP 5 >= 5.1.0)

stream_filter_remove — Remove a filter from a stream

Opis

bool stream_filter_remove ( resource $stream_filter )

Removes a stream filter previously added to a stream with stream_filter_prepend() or stream_filter_append(). Any data remaining in the filter's internal buffer will be flushed through to the next filter before removing it.

Parametry

stream_filter

The stream filter to be removed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Dynamicly refiltering a stream

<?php
/* Open a test file for reading and writing */
$fp = fopen("test.txt", "rw");

$rot13_filter = stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);
fwrite($fp, "This is ");
stream_filter_remove($rot13_filter);
fwrite($fp, "a test\n");

rewind($fp);
fpassthru($fp);
fclose($fp);

?>

Powyższy przykład wyświetli:

Guvf vf a test

Zobacz też:

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream
  • stream_filter_prepend() - Attach a filter to a stream

stream_filter_register
stream_get_contents
Stream Funkcje


Reads remainder of a stream into a string

stream_filter_remove
stream_get_filters
Stream Funkcje
PHP Manual

stream_get_contents

(PHP 5)

stream_get_contents — Reads remainder of a stream into a string

Opis

string stream_get_contents ( resource $handle [, int $maxlength = -1 [, int $offset = -1 ]] )

Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

Parametry

handle (resource)

A stream resource (e.g. returned from fopen())

maxlength (integer)

The maximum bytes to read. Defaults to -1 (read all the remaining buffer).

offset (integer)

Seek to the specified offset before reading. If this number is negative, no seeking will occur and reading will start from the current position.

Zwracane wartości

Returns a string lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja | Opis
5.1.0 | The offset was added.

Przykłady

Przykład #1 stream_get_contents() example

<?php

if ($stream = fopen('http://www.example.com', 'r')) {
    // print all the page starting at the offset 10
    echo stream_get_contents($stream, -1, 10);

    fclose($stream);
}

if ($stream = fopen('http://www.example.net', 'r')) {
    // print the first 5 bytes
    echo stream_get_contents($stream, 5);

    fclose($stream);
}

?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • fgets() - Pobiera linię ze wskaźnika pliku
  • fread() - Odczyt pliku binarnie bezpieczy
  • fpassthru() - Output all remaining data on a file pointer

stream_filter_remove
stream_get_filters
Stream Funkcje


Retrieve list of registered filters

stream_get_contents
stream_get_line
Stream Funkcje
PHP Manual

stream_get_filters

(PHP 5)

stream_get_filters — Retrieve list of registered filters

Opis

array stream_get_filters ( void )

Retrieve the list of registered filters on the running system.

Zwracane wartości

Returns an indexed array containing the name of all stream filters available.

Przykłady

Przykład #1 Using stream_get_filters()

<?php
$streamlist = stream_get_filters();
print_r($streamlist);
?>

Powyższy przykład wyświetli coś podobnego do:

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

Zobacz też:

  • stream_filter_register() - Register a user defined stream filter
  • stream_get_wrappers() - Retrieve list of registered streams
stream_get_contents
stream_get_line
Stream Funkcje


Gets line from stream resource up to a given delimiter

stream_get_filters
stream_get_meta_data
Stream Funkcje
PHP Manual

stream_get_line

(PHP 5)

stream_get_line — Gets line from stream resource up to a given delimiter

Opis

string stream_get_line ( resource $handle , int $length [, string $ending ] )

Gets a line from the given handle.

Reading ends when length bytes have been read, when the string specified by ending is found (which is not included in the return value), or on EOF (whichever comes first).

This function is nearly identical to fgets() except in that it allows end of line delimiters other than the standard \n, \r, and \r\n, and does not return the delimiter itself.

Parametry

handle

A valid file handle.

length

The number of bytes to read from the handle.

ending

An optional string delimiter.

Zwracane wartości

Returns a string of up to length bytes read from the file pointed to by handle.

If an error occurs, returns FALSE.

Zobacz też:

  • fread() - Odczyt pliku binarnie bezpieczy
  • fgets() - Pobiera linię ze wskaźnika pliku
  • fgetc() - Pobiera znak ze wskaźnika pliku
stream_get_filters
stream_get_meta_data
Stream Funkcje


Retrieves header/meta data from streams/file pointers

stream_get_line
stream_get_transports
Stream Funkcje
PHP Manual

stream_get_meta_data

(PHP 4 >= 4.3.0, PHP 5)

stream_get_meta_data — Retrieves header/meta data from streams/file pointers

Opis

array stream_get_meta_data ( resource $stream )

Returns information about an existing stream.

Parametry

stream

The stream can be any stream created by fopen(), fsockopen() and pfsockopen().

Zwracane wartości

The result array contains the following items:

  • timed_out (bool) - TRUE if the stream timed out while waiting for data on the last call to fread() or fgets().

  • blocked (bool) - TRUE if the stream is in blocking IO mode. See stream_set_blocking().

  • eof (bool) - TRUE if the stream has reached end-of-file. Note that for socket streams this member can be TRUE even when unread_bytes is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.

  • unread_bytes (int) - the number of bytes currently contained in the PHP's own internal buffer.

    Informacja: You shouldn't use this value in a script.

  • stream_type (string) - a label describing the underlying implementation of the stream.

  • wrapper_type (string) - a label describing the protocol wrapper implementation layered over the stream. See Supported Protocols and Wrappers for more information about wrappers.

  • wrapper_data (mixed) - wrapper specific data attached to this stream. See Supported Protocols and Wrappers for more information about wrappers and their wrapper data.

  • filters (array) - and array containing the names of any filters that have been stacked onto this stream. Documentation on filters can be found in the Filters appendix.

  • mode (string) - the type of access required for this stream (see Table 1 of the fopen() reference)

  • seekable (bool) - whether the current stream can be seeked.

  • uri (string) - the URI/filename associated with this stream.

Rejestr zmian

Wersja | Opis
5.0.0 | The following entries were added in the returned array: mode, seekable, and uri.
4.3.0 | The following entries were added in the returned array: stream_type, wrapper_type, wrapper_data, and filters.
4.3.0 | socket_get_status() is an alias for this function. Prior to PHP 4.3.0, it was used to retrieve the first four items, for socket based streams only.

Przykłady

Przykład #1 stream_get_meta_data() example

<?php
$url = 'http://www.example.com/';

if (!$fp = fopen($url, 'r')) {
    trigger_error("Unable to open URL ($url)", E_USER_ERROR);
}

$meta = stream_get_meta_data($fp);

print_r($meta);

fclose($fp);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [wrapper_data] => Array
        (
            [0] => HTTP/1.1 200 OK
            [1] => Server: Apache/2.2.3 (Red Hat)
            [2] => Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
            [3] => ETag: "b300b4-1b6-4059a80bfd280"
            [4] => Accept-Ranges: bytes
            [5] => Content-Type: text/html; charset=UTF-8
            [6] => Set-Cookie: FOO=BAR; expires=Fri, 21-Dec-2012 12:00:00 GMT; path=/; domain=.example.com
            [6] => Connection: close
            [7] => Date: Fri, 16 Oct 2009 12:00:00 GMT
            [8] => Age: 1164
            [9] => Content-Length: 438
        )

    [wrapper_type] => http
    [stream_type] => tcp_socket/ssl
    [mode] => r
    [unread_bytes] => 438
    [seekable] =>
    [uri] => http://www.example.com/
    [timed_out] =>
    [blocked] => 1
    [eof] =>
)

Notatki

Informacja:

This function does NOT work on sockets created by the Socket extension.

Zobacz też:

  • get_headers() - Fetches all the headers sent by the server in response to a HTTP request
  • $http_response_header

stream_get_line
stream_get_transports
Stream Funkcje


Retrieve list of registered socket transports

stream_get_meta_data
stream_get_wrappers
Stream Funkcje
PHP Manual

stream_get_transports

(PHP 5)

stream_get_transports — Retrieve list of registered socket transports

Opis

array stream_get_transports ( void )

Returns an indexed array containing the name of all socket transports available on the running system.

Zwracane wartości

Returns an indexed array of socket transports names.

Przykłady

Przykład #1 Using stream_get_transports()

<?php
$xportlist = stream_get_transports();
print_r($xportlist);
?>

Powyższy przykład wyświetli coś podobnego do:

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

Zobacz też:

  • stream_get_filters() - Retrieve list of registered filters
  • stream_get_wrappers() - Retrieve list of registered streams
stream_get_meta_data
stream_get_wrappers
Stream Funkcje


Retrieve list of registered streams

stream_get_transports
stream_is_local
Stream Funkcje
PHP Manual

stream_get_wrappers

(PHP 5)

stream_get_wrappers — Retrieve list of registered streams

Opis

array stream_get_wrappers ( void )

Retrieve list of registered streams available on the running system.

Zwracane wartości

Returns an indexed array containing the name of all stream wrappers available on the running system.

Przykłady

Przykład #1 stream_get_wrappers() example

<?php
print_r(stream_get_wrappers());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
)

Przykład #2 Checking for the existence of a stream wrapper

<?php
// check for the existence of the bzip2 stream wrapper
if (in_array('compress.bzip2', stream_get_wrappers())) {
    echo 'compress.bzip2:// support enabled.';
} else {
    echo 'compress.bzip2:// support not enabled.';
}
?>

Zobacz też:

  • stream_wrapper_register() - Register a URL wrapper implemented as a PHP class
stream_get_transports
stream_is_local
Stream Funkcje


Checks if a stream is a local stream

stream_get_wrappers
stream_notification_callback
Stream Funkcje
PHP Manual

stream_is_local

(PHP 5 >= 5.2.4)

stream_is_local — Checks if a stream is a local stream

Opis

bool stream_is_local ( mixed $stream_or_url )

Checks if a stream, or a URL, is a local one or not.

Parametry

stream_or_url

The stream resource or URL to check.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 stream_is_local() example

Basic usage example.

<?php
var_dump(stream_is_local("http://example.com"));
var_dump(stream_is_local("/etc"));
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)

stream_get_wrappers
stream_notification_callback
Stream Funkcje


A callback function for the notification context paramater

stream_is_local
stream_register_wrapper
Stream Funkcje
PHP Manual

stream_notification_callback

(PHP 5 >= 5.2.0)

stream_notification_callback — A callback function for the notification context paramater

Opis

void stream_notification_callback ( int $notification_code , int $severity , string $message , int $message_code , int $bytes_transferred , int $bytes_max )

A callback function, used by the notification context parameter, called during an event.

Informacja:

This is not a real function, only a prototype of how the function should be.

Parametry

notification_code

One of the STREAM_NOTIFY_* notification constants.

severity

One of the STREAM_NOTIFY_SEVERITY_* notification constants.

message

Passed if a descriptive message is available for the event.

message_code

Passed if a descriptive message code is available for the event.

The meaning of this value is dependent on the specific wrapper in use.

bytes_transferred

If applicable, the bytes_transferred will be populated.

bytes_max

If applicable, the bytes_max will be populated.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 stream_notification_callback() example

<?php
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {

    switch($notification_code) {
        case STREAM_NOTIFY_RESOLVE:
        case STREAM_NOTIFY_AUTH_REQUIRED:
        case STREAM_NOTIFY_COMPLETED:
        case STREAM_NOTIFY_FAILURE:
        case STREAM_NOTIFY_AUTH_RESULT:
            var_dump($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max);
            /* Ignore */
            break;

        case STREAM_NOTIFY_REDIRECTED:
            echo "Being redirected to: ", $message;
            break;

        case STREAM_NOTIFY_CONNECT:
            echo "Connected...";
            break;

        case STREAM_NOTIFY_FILE_SIZE_IS:
            echo "Got the filesize: ", $bytes_max;
            break;

        case STREAM_NOTIFY_MIME_TYPE_IS:
            echo "Found the mime-type: ", $message;
            break;

        case STREAM_NOTIFY_PROGRESS:
            echo "Made some progress, downloaded ", $bytes_transferred, " so far";
            break;
    }
    echo "\n";
}

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

file_get_contents("http://php.net/contact", false, $ctx);
?>

Powyższy przykład wyświetli coś podobnego do:

Connected...
Found the mime-type: text/html; charset=utf-8
Being redirected to: http://no.php.net/contact
Connected...
Got the filesize: 0
Found the mime-type: text/html; charset=utf-8
Being redirected to: http://no.php.net/contact.php
Connected...
Got the filesize: 4589
Found the mime-type: text/html;charset=utf-8
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 1440 so far
Made some progress, downloaded 2880 so far
Made some progress, downloaded 4320 so far
Made some progress, downloaded 5760 so far
Made some progress, downloaded 6381 so far
Made some progress, downloaded 7002 so far

Przykład #2 Simple progressbar for commandline download client

<?php
function usage($argv) {
    echo "Usage:\n";
    printf("\tphp %s <http://example.com/file> <localfile>\n", $argv[0]);
    exit(1);
}

function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
    static $filesize = null;

    switch($notification_code) {
    case STREAM_NOTIFY_RESOLVE:
    case STREAM_NOTIFY_AUTH_REQUIRED:
    case STREAM_NOTIFY_COMPLETED:
    case STREAM_NOTIFY_FAILURE:
    case STREAM_NOTIFY_AUTH_RESULT:
        /* Ignore */
        break;

    case STREAM_NOTIFY_REDIRECTED:
        echo "Being redirected to: ", $message, "\n";
        break;

    case STREAM_NOTIFY_CONNECT:
        echo "Connected...\n";
        break;

    case STREAM_NOTIFY_FILE_SIZE_IS:
        $filesize = $bytes_max;
        echo "Filesize: ", $filesize, "\n";
        break;

    case STREAM_NOTIFY_MIME_TYPE_IS:
        echo "Mime-type: ", $message, "\n";
        break;

    case STREAM_NOTIFY_PROGRESS:
        if ($bytes_transferred > 0) {
            if (!isset($filesize)) {
                printf("\rUnknown filesize.. %2d kb done..", $bytes_transferred/1024);
            } else {
                $length = (int)(($bytes_transferred/$filesize)*100);
                printf("\r[%-100s] %d%% (%2d/%2d kb)", str_repeat("=", $length). ">", $length, ($bytes_transferred/1024), $filesize/1024);
            }
        }
        break;
    }
}

isset($argv[1], $argv[2]) or usage($argv);

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

$fp = fopen($argv[1], "r", false, $ctx);
if (is_resource($fp) && file_put_contents($argv[2], $fp)) {
    echo "\nDone!\n";
    exit(0);
}

$err = error_get_last();
echo "\nErrrrrorr..\n", $err["message"], "\n";
exit(1);
?>

Executing the example above with: php -n fetch.php http://no2.php.net/get/php-5-LATEST.tar.bz2/from/this/mirror php-latest.tar.bz2 will output something similar too:

Connected...
Mime-type: text/html; charset=utf-8
Being redirected to: http://no2.php.net/distributions/php-5.2.5.tar.bz2
Connected...
Filesize: 7773024
Mime-type: application/octet-stream
[========================================>                                                           ] 40% (3076/7590 kb)

Zobacz też:

  • Context parameters

stream_is_local
stream_register_wrapper
Stream Funkcje


Alias dla stream_wrapper_register

stream_notification_callback
stream_resolve_include_path
Stream Funkcje
PHP Manual

stream_register_wrapper

(PHP 4 >= 4.3.0, PHP 5)

stream_register_wrapper — Alias dla stream_wrapper_register()

Opis

Ta funkcja jest aliasem dla: stream_wrapper_register().

stream_notification_callback
stream_resolve_include_path
Stream Funkcje


Resolve filename against the include path

stream_register_wrapper
stream_select
Stream Funkcje
PHP Manual

stream_resolve_include_path

(PHP 5 >= 5.3.2)

stream_resolve_include_path — Resolve filename against the include path

Opis

string stream_resolve_include_path ( string $filename )

Resolve filename against the include path according to the same rules as fopen()/include().

Parametry

filename

The filename to resolve.

Zwracane wartości

Returns a string containing the resolved absolute filename, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 stream_resolve_include_path() example

Basic usage example.

<?php
var_dump(stream_resolve_include_path("test.php"));
?>

Powyższy przykład wyświetli coś podobnego do:

string(22) "/var/www/html/test.php"

stream_register_wrapper
stream_select
Stream Funkcje


Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

stream_resolve_include_path
stream_set_blocking
Stream Funkcje
PHP Manual

stream_select

(PHP 4 >= 4.3.0, PHP 5)

stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

Opis

int stream_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )

The stream_select() function accepts arrays of streams and waits for them to change status. Its operation is equivalent to that of the socket_select() function except in that it acts on streams.

Parametry

read

The streams listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a stream resource is also ready on end-of-file, in which case an fread() will return a zero length string).

write

The streams listed in the write array will be watched to see if a write will not block.

except

The streams listed in the except array will be watched for high priority exceptional ("out-of-band") data arriving.

Informacja:

When stream_select() returns, the arrays read, write and except are modified to indicate which stream resource(s) actually changed status.

You do not need to pass every array to stream_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after stream_select() returns.
tv_sec

The tv_sec and tv_usec together form the timeout parameter, tv_sec specifies the number of seconds while tv_usec the number of microseconds. The timeout is an upper bound on the amount of time that stream_select() will wait before it returns. If tv_sec and tv_usec are both set to 0, stream_select() will not wait for data - instead it will return immediately, indicating the current status of the streams.

If tv_sec is NULL stream_select() can block indefinitely, returning only when an event on one of the watched streams occurs (or if a signal interrupts the system call).

Ostrzeżenie

Using a timeout value of 0 allows you to instantaneously poll the status of the streams, however, it is NOT a good idea to use a 0 timeout value in a loop as it will cause your script to consume too much CPU time.

It is much better to specify a timeout value of a few seconds, although if you need to be checking and running other code concurrently, using a timeout value of at least 200000 microseconds will help reduce the CPU usage of your script.

Remember that the timeout value is the maximum time that will elapse; stream_select() will return as soon as the requested streams are ready for use.

tv_usec

See tv_sec description.

Zwracane wartości

On success stream_select() returns the number of stream resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned and a warning raised (this can happen if the system call is interrupted by an incoming signal).

Przykłady

Przykład #1 stream_select() Example

This example checks to see if data has arrived for reading on either $stream1 or $stream2. Since the timeout value is 0 it will return immediately:

<?php
/* Prepare the read array */
$read   = array($stream1, $stream2);
$write  = NULL;
$except = NULL;
if (false === ($num_changed_streams = stream_select($read, $write, $except, 0))) {
    /* Error handling */
} elseif ($num_changed_streams > 0) {
    /* At least on one of the streams something interesting happened */
}
?>

Notatki

Informacja:

Due to a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

<?php
$e = NULL;
stream_select($r, $w, $e, 0);
?>

Informacja:

Be sure to use the === operator when checking for an error. Since the stream_select() may return 0 the comparison with == would evaluate to TRUE:

<?php
$e = NULL;
if (false === stream_select($r, $w, $e, 0)) {
    echo "stream_select() failed\n";
}
?>

Informacja:

If you read/write to a stream returned in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.

Informacja:

Some streams (like zlib) cannot be selected by this function.

Informacja:

Windows compatibility: stream_select() used on a pipe returned from proc_open() may cause data loss under Windows 98.

Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.

Zobacz też:

  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
stream_resolve_include_path
stream_set_blocking
Stream Funkcje


Set blocking/non-blocking mode on a stream

stream_select
stream_set_read_buffer
Stream Funkcje
PHP Manual

stream_set_blocking

(PHP 4 >= 4.3.0, PHP 5)

stream_set_blocking — Set blocking/non-blocking mode on a stream

Opis

bool stream_set_blocking ( resource $stream , int $mode )

Sets blocking or non-blocking mode on a stream.

This function works for any stream that supports non-blocking mode (currently, regular files and socket streams).

Parametry

stream

The stream.

mode

If mode is 0, the given stream will be switched to non-blocking mode, and if 1, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
4.3.0 | Prior to PHP 4.3.0, this function only worked on socket based streams.

Notatki

Informacja:

This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.

Zobacz też:

  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
stream_select
stream_set_read_buffer
Stream Funkcje


Set read file buffering on the given stream

stream_set_blocking
stream_set_timeout
Stream Funkcje
PHP Manual

stream_set_read_buffer

(PHP 5 >= 5.3.3)

stream_set_read_buffer — Set read file buffering on the given stream

Opis

int stream_set_read_buffer ( resource $stream , int $buffer )

Sets the read buffer. It's the equivalent of stream_set_write_buffer(), but for read operations.

Parametry

stream

The file pointer.

buffer

The number of bytes to buffer. If buffer is 0 then read operations are unbuffered. This ensures that all reads with fread() are completed before other processes are allowed to write to that output stream.

Zwracane wartości

Returns 0 on success, or EOF if the request cannot be honored.

Zobacz też:

  • stream_set_write_buffer() - Sets write file buffering on the given stream
stream_set_blocking
stream_set_timeout
Stream Funkcje


Set timeout period on a stream

stream_set_read_buffer
stream_set_write_buffer
Stream Funkcje
PHP Manual

stream_set_timeout

(PHP 4 >= 4.3.0, PHP 5)

stream_set_timeout — Set timeout period on a stream

Opis

bool stream_set_timeout ( resource $stream , int $seconds [, int $microseconds = 0 ] )

Sets the timeout value on stream, expressed in the sum of seconds and microseconds.

When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to TRUE, although no error/warning is generated.

Parametry

stream

The target stream.

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
4.3.0 | As of PHP 4.3, this function can (potentially) work on any kind of stream. In PHP 4.3, socket based streams are still the only kind supported in the PHP core, although streams from other extensions may support this function.

Przykłady

Przykład #1 stream_set_timeout() example

<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
    echo "Unable to open\n";
} else {

    fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
    stream_set_timeout($fp, 2);
    $res = fread($fp, 2000);

    $info = stream_get_meta_data($fp);
    fclose($fp);

    if ($info['timed_out']) {
        echo 'Connection timed out!';
    } else {
        echo $res;
    }

}
?>

Notatki

Informacja:

This function doesn't work with advanced operations like stream_socket_recvfrom(), use stream_select() with timeout parameter instead.

This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.

Zobacz też:

  • fsockopen() - Open Internet or Unix domain socket connection
  • fopen() - Otwiera plik lub URL
stream_set_read_buffer
stream_set_write_buffer
Stream Funkcje


Sets write file buffering on the given stream

stream_set_timeout
stream_socket_accept
Stream Funkcje
PHP Manual

stream_set_write_buffer

(PHP 4 >= 4.3.0, PHP 5)

stream_set_write_buffer — Sets write file buffering on the given stream

Opis

int stream_set_write_buffer ( resource $stream , int $buffer )

Sets the buffering for write operations on the given stream to buffer bytes.

Output using fwrite() is normally buffered at 8K. This means that if there are two processes wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write.

Parametry

stream

The file pointer.

buffer

The number of bytes to buffer. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.

Zwracane wartości

Returns 0 on success, or EOF if the request cannot be honored.

Przykłady

Przykład #1 stream_set_write_buffer() example

The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.

<?php
$fp = fopen($file, "w");
if ($fp) {
  stream_set_write_buffer($fp, 0);
  fwrite($fp, $output);
  fclose($fp);
}
?>

Zobacz też:

  • fopen() - Otwiera plik lub URL
  • fwrite() - Zapis pliku binarnie bezpieczny
stream_set_timeout
stream_socket_accept
Stream Funkcje


Accept a connection on a socket created by stream_socket_server

stream_set_write_buffer
stream_socket_client
Stream Funkcje
PHP Manual

stream_socket_accept

(PHP 5)

stream_socket_accept — Accept a connection on a socket created by stream_socket_server()

Opis

resource stream_socket_accept ( resource $server_socket [, float $timeout = ini_get("default_socket_timeout") [, string &$peername ]] )

Accept a connection on a socket previously created by stream_socket_server().

Parametry

server_socket

The server socket to accept a connection from.

timeout

Override the default socket accept timeout. Time should be given in seconds.

peername

Will be set to the name (address) of the client which connected, if included and available from the selected transport.

Informacja:

Can also be determined later using stream_socket_get_name().

Zwracane wartości

Returns a stream to the accepted socket connection lub FALSE w przypadku niepowodzenia.

Notatki

Ostrzeżenie

This function should not be used with UDP server sockets. Instead, use stream_socket_recvfrom() and stream_socket_sendto().

Zobacz też:

  • stream_socket_server() - Create an Internet or Unix domain server socket
  • stream_socket_get_name() - Retrieve the name of the local or remote sockets
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Pobiera linię ze wskaźnika pliku
  • fgetss() - Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
  • fwrite() - Zapis pliku binarnie bezpieczny
  • fclose() - Zamyka otwarty wskaźnik pliku
  • feof() - Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
  • cURL Funkcje

stream_set_write_buffer
stream_socket_client
Stream Funkcje


Open Internet or Unix domain socket connection

stream_socket_accept
stream_socket_enable_crypto
Stream Funkcje
PHP Manual

stream_socket_client

(PHP 5)

stream_socket_client — Open Internet or Unix domain socket connection

Opis

resource stream_socket_client ( string $remote_socket [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") [, int $flags = STREAM_CLIENT_CONNECT [, resource $context ]]]]] )

Initiates a stream or datagram connection to the destination specified by remote_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem.

Informacja:

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Parametry

remote_socket

Address to the socket to connect to.

errno

Will be set to the system level error number if connection fails.

errstr

Will be set to the system level error message if the connection fails.

timeout

Number of seconds until the connect() system call should timeout.

Informacja: This parameter only applies when not making asynchronous connection attempts.

Informacja:

To set a timeout for reading/writing data over the socket, use the stream_set_timeout(), as the timeout only applies while making connecting the socket.

flags

Bitmask field which may be set to any combination of connection flags. Currently the select of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

context

A valid context resource created with stream_context_create().

Zwracane wartości

On success a stream resource is returned which may
be used together with the other file functions (such as
fgets(), fgetss(),
fwrite(), fclose(), and
feof()), FALSE on failure.

Błędy/Wyjątki

On failure the errno and errstr arguments will be populated with the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Przykłady

Przykład #1 stream_socket_client() example

<?php
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}
?>

Przykład #2 Using UDP connection

Retrieving the day and time from the UDP service "daytime" (port 13) on localhost.

<?php
$fp = stream_socket_client("udp://127.0.0.1:13", $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Notatki

Ostrzeżenie

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Informacja: Podając numerycznie adres IPv6 (np. fe80::1), adres musi być objęty nawiasami kwadratowymi. Na przykład tcp://[fe80::1]:80.

Informacja:

Depending on the environment, the Unix domain or the optional connect timeout may not be available. A list of available transports can be retrieved using stream_get_transports(). See List of Supported Socket Transports for a list of built in transports.

Zobacz też:

  • stream_socket_server() - Create an Internet or Unix domain server socket
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • fgets() - Pobiera linię ze wskaźnika pliku
  • fgetss() - Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
  • fwrite() - Zapis pliku binarnie bezpieczny
  • fclose() - Zamyka otwarty wskaźnik pliku
  • feof() - Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
  • cURL Funkcje

stream_socket_accept
stream_socket_enable_crypto
Stream Funkcje


Turns encryption on/off on an already connected socket

stream_socket_client
stream_socket_get_name
Stream Funkcje
PHP Manual

stream_socket_enable_crypto

(PHP 5 >= 5.1.0)

stream_socket_enable_crypto — Turns encryption on/off on an already connected socket

Opis

mixed stream_socket_enable_crypto ( resource $stream , bool $enable [, int $crypto_type [, resource $session_stream ]] )

Enable or disable encryption on the stream.

Once the crypto settings are established, cryptography can be turned on and off dynamically by passing TRUE or FALSE in the enable parameter.

Parametry

stream

The stream resource.

enable

Enable/disable cryptography on the stream.

crypto_type

Setup encryption on the stream. Valid methods are

  • STREAM_CRYPTO_METHOD_SSLv2_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv3_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv23_CLIENT
  • STREAM_CRYPTO_METHOD_TLS_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv2_SERVER
  • STREAM_CRYPTO_METHOD_SSLv3_SERVER
  • STREAM_CRYPTO_METHOD_SSLv23_SERVER
  • STREAM_CRYPTO_METHOD_TLS_SERVER

session_stream

Seed the stream with settings from session_stream.

Zwracane wartości

Returns TRUE on success, FALSE if negotiation has failed or 0 if there isn't enough data and you should try again (only for non-blocking sockets).

Przykłady

Przykład #1 stream_socket_enable_crypto() example

<?php
$fp = stream_socket_client("tcp://myproto.example.com:31337", $errno, $errstr, 30);
if (!$fp) {
    die("Unable to connect: $errstr ($errno)");
}

/* Turn on encryption for login phase */
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
fwrite($fp, "USER god\r\n");
fwrite($fp, "PASS secret\r\n");

/* Turn off encryption for the rest */
stream_socket_enable_crypto($fp, false);

while ($motd = fgets($fp)) {
    echo $motd;
}

fclose($fp);
?>

Powyższy przykład wyświetli coś podobnego do:

Zobacz też:

  • OpenSSL Funkcje
    •

  • List of Supported Socket Transports
    •

stream_socket_client

stream_socket_get_name

Stream Funkcje


Retrieve the name of the local or remote sockets

stream_socket_enable_crypto
stream_socket_pair
Stream Funkcje
PHP Manual

stream_socket_get_name

(PHP 5)

stream_socket_get_name — Retrieve the name of the local or remote sockets

Opis

string stream_socket_get_name ( resource $handle , bool $want_peer )

Returns the local or remote name of a given socket connection.

Parametry

handle

The socket to get the name of.

want_peer

If set to TRUE the remote socket name will be returned, if set to FALSE the local socket name will be returned.

Zwracane wartości

The name of the socket.

Zobacz też:

  • stream_socket_accept() - Accept a connection on a socket created by stream_socket_server

stream_socket_enable_crypto
stream_socket_pair
Stream Funkcje


Creates a pair of connected, indistinguishable socket streams

stream_socket_get_name
stream_socket_recvfrom
Stream Funkcje
PHP Manual

stream_socket_pair

(PHP 5 >= 5.1.0)

stream_socket_pair — Creates a pair of connected, indistinguishable socket streams

Opis

array stream_socket_pair ( int $domain , int $type , int $protocol )

stream_socket_pair() creates a pair of connected, indistinguishable socket streams. This function is commonly used in IPC (Inter-Process Communication).

Parametry

domain

The protocol family to be used: STREAM_PF_INET, STREAM_PF_INET6 or STREAM_PF_UNIX

type

The type of communication to be used: STREAM_SOCK_DGRAM, STREAM_SOCK_RAW, STREAM_SOCK_RDM, STREAM_SOCK_SEQPACKET or STREAM_SOCK_STREAM

protocol

The protocol to be used: STREAM_IPPROTO_ICMP, STREAM_IPPROTO_IP, STREAM_IPPROTO_RAW, STREAM_IPPROTO_TCP or STREAM_IPPROTO_UDP

Informacja: Please consult the Streams constant list for further details on each constant.

Zwracane wartości

Returns an array with the two socket resources on success, or FALSE on failure.

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.

Przykłady

Przykład #1 A stream_socket_pair() example

This example shows the basic usage of stream_socket_pair() in Inter-Process Comunication.

<?php

$sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid     = pcntl_fork();

if ($pid == -1) {
     die('could not fork');

} else if ($pid) {
     /* parent */
    fclose($sockets[0]);

    fwrite($sockets[1], "child PID: $pid\n");
    echo fgets($sockets[1]);

    fclose($sockets[1]);

} else {
    /* child */
    fclose($sockets[1]);

    fwrite($sockets[0], "message from child\n");
    echo fgets($sockets[0]);

    fclose($sockets[0]);
}

?>

Powyższy przykład wyświetli coś podobnego do:

child PID: 1378
message from child

stream_socket_get_name
stream_socket_recvfrom
Stream Funkcje


Receives data from a socket, connected or not

stream_socket_pair
stream_socket_sendto
Stream Funkcje
PHP Manual

stream_socket_recvfrom

(PHP 5)

stream_socket_recvfrom — Receives data from a socket, connected or not

Opis

string stream_socket_recvfrom ( resource $socket , int $length [, int $flags = 0 [, string &$address ]] )

stream_socket_recvfrom() accepts data from a remote socket up to length bytes.

Parametry

socket

The remote socket.

length

The number of bytes to receive from the socket.

flags

The value of flags can be any combination of the following:

Possible values for flags
STREAM_OOB | Process OOB (out-of-band) data.
STREAM_PEEK | Retrieve data from the socket, but do not consume the buffer. Subsequent calls to fread() or stream_socket_recvfrom() will see the same data.

address

If address is provided it will be populated with the address of the remote socket.

Zwracane wartości

Returns the read data, as a string

Przykłady

Przykład #1 stream_socket_recvfrom() example

<?php
/* Open a server socket to port 1234 on localhost */
$server = stream_socket_server('tcp://127.0.0.1:1234');

/* Accept a connection */
$socket = stream_socket_accept($server);

/* Grab a packet (1500 is a typical MTU size) of OOB data */
echo "Received Out-Of-Band: '" . stream_socket_recvfrom($socket, 1500, STREAM_OOB) . "'\n";

/* Take a peek at the normal in-band data, but don't comsume it. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500, STREAM_PEEK) . "'\n";

/* Get the exact same packet again, but remove it from the buffer this time. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500) . "'\n";

/* Close it up */
fclose($socket);
fclose($server);
?>

Notatki

Informacja:

If a message received is longer than the length parameter, excess bytes may be discarded depending on the type of socket the message is received from (such as UDP).

Informacja:

Calls to stream_socket_recvfrom() on socket-based streams, after calls to buffer-based stream functions (like fread() or stream_get_line()) read data directly from the socket and bypass the stream buffer.

Zobacz też:

  • stream_socket_sendto() - Sends a message to a socket, whether it is connected or not
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_server() - Create an Internet or Unix domain server socket
stream_socket_pair
stream_socket_sendto
Stream Funkcje


Sends a message to a socket, whether it is connected or not

stream_socket_recvfrom
stream_socket_server
Stream Funkcje
PHP Manual

stream_socket_sendto

(PHP 5)

stream_socket_sendto — Sends a message to a socket, whether it is connected or not

Opis

int stream_socket_sendto ( resource $socket , string $data [, int $flags = 0 [, string $address ]] )

Sends the specified data through the socket.

Parametry

socket

The socket to send data to.

data

The data to be sent.

flags

The value of flags can be any combination of the following:

possible values for flags
STREAM_OOB Process OOB (out-of-band) data.

address

The address specified when the socket stream was created will be used unless an alternate address is specified in address.

If specified, it must be in dotted quad (or [ipv6]) format.

Zwracane wartości

Returns a result code, as an integer.

Przykłady

Przykład #1 stream_socket_sendto() Example

<?php
/* Open a socket to port 1234 on localhost */
$socket = stream_socket_client('tcp://127.0.0.1:1234');

/* Send ordinary data via ordinary channels. */
fwrite($socket, "Normal data transmit.");

/* Send more data out of band. */
stream_socket_sendto($socket, "Out of Band data.", STREAM_OOB);

/* Close it up */
fclose($socket);
?>

Zobacz też:

  • stream_socket_recvfrom() - Receives data from a socket, connected or not
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_server() - Create an Internet or Unix domain server socket
stream_socket_recvfrom
stream_socket_server
Stream Funkcje


Create an Internet or Unix domain server socket

stream_socket_sendto
stream_socket_shutdown
Stream Funkcje
PHP Manual

stream_socket_server

(PHP 5)

stream_socket_server — Create an Internet or Unix domain server socket

Opis

resource stream_socket_server ( string $local_socket [, int &$errno [, string &$errstr [, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN [, resource $context ]]]] )

Creates a stream or datagram socket on the specified local_socket.

This function only creates a socket, to begin accepting connections use stream_socket_accept().

Parametry

local_socket

The type of socket created is determined by the transport specified using standard URL formatting: transport://target.

For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem.

Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using stream_get_transports(). See List of Supported Socket Transports for a list of bulitin transports.

errno

If the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level socket(), bind(), and listen() calls. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the bind() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

errstr

See errno description.

flags

A bitmask field which may be set to any combination of socket creation flags.

Informacja:

For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.

context

Zwracane wartości

Returns the created stream, or FALSE on error.

Przykłady

Przykład #1 Using TCP server sockets

<?php
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
  echo "$errstr ($errno)<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
    fclose($conn);
  }
  fclose($socket);
}
?>

The example below shows how to act as a time server which can respond to time queries as shown in an example on stream_socket_client().

Informacja: Most systems require root access to create a server socket on a port below 1024.

Przykład #2 Using UDP server sockets

<?php
$socket = stream_socket_server("udp://127.0.0.1:1113", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
    die("$errstr ($errno)");
}

do {
    $pkt = stream_socket_recvfrom($socket, 1, 0, $peer);
    echo "$peer\n";
    stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer);
} while ($pkt !== false);

?>

Notatki

Informacja: Podając numerycznie adres IPv6 (np. fe80::1), adres musi być objęty nawiasami kwadratowymi. Na przykład tcp://[fe80::1]:80.

Zobacz też:

  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Pobiera linię ze wskaźnika pliku
  • fgetss() - Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
  • fwrite() - Zapis pliku binarnie bezpieczny
  • fclose() - Zamyka otwarty wskaźnik pliku
  • feof() - Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
  • Curl extension
stream_socket_sendto
stream_socket_shutdown
Stream Funkcje


Shutdown a full-duplex connection

stream_socket_server
stream_supports_lock
Stream Funkcje
PHP Manual

stream_socket_shutdown

(PHP 5 >= 5.2.1)

stream_socket_shutdown — Shutdown a full-duplex connection

Opis

bool stream_socket_shutdown ( resource $stream , int $how )

Shutdowns (partially or not) a full-duplex connection.

Parametry

stream

An open stream (opened with stream_socket_client(), for example)

how

One of the following constants: STREAM_SHUT_RD (disable further receptions), STREAM_SHUT_WR (disable further transmissions) or STREAM_SHUT_RDWR (disable further receptions and transmissions).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A stream_socket_shutdown() example

<?php

$server = stream_socket_server('tcp://127.0.0.1:1337');
$client = stream_socket_client('tcp://127.0.0.1:1337');

var_dump(fputs($client, "hello"));

stream_socket_shutdown($client, STREAM_SHUT_WR);
var_dump(fputs($client, "hello")); // doesn't work now

?>

Powyższy przykład wyświetli coś podobnego do:

int(5)

Notice: fputs(): send of 5 bytes failed with errno=32 Broken pipe in test.php on line 9
int(0)

Zobacz też:

  • fclose() - Zamyka otwarty wskaźnik pliku

stream_socket_server
stream_supports_lock
Stream Funkcje


Tells whether the stream supports locking.

stream_socket_shutdown
stream_wrapper_register
Stream Funkcje
PHP Manual

stream_supports_lock

(PHP 5 >= 5.3.0)

stream_supports_lock — Tells whether the stream supports locking.

Opis

bool stream_supports_lock ( resource $stream )

Tells whether the stream supports locking through flock().

Parametry

stream

The stream to check.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • flock() - Portable advisory file locking

stream_socket_shutdown
stream_wrapper_register
Stream Funkcje


Register a URL wrapper implemented as a PHP class

stream_supports_lock
stream_wrapper_restore
Stream Funkcje
PHP Manual

stream_wrapper_register

(PHP 4 >= 4.3.2, PHP 5)

stream_wrapper_register — Register a URL wrapper implemented as a PHP class

Opis

bool stream_wrapper_register ( string $protocol , string $classname [, int $flags = 0 ] )

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Parametry

protocol

The wrapper name to be registered.

classname

The classname which implements the protocol.

flags

Should be set to STREAM_IS_URL if protocol is a URL protocol. Default is 0, local stream.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

stream_wrapper_register() will return FALSE if the protocol already has a handler.

Rejestr zmian

Wersja | Opis
5.2.4 | Added the flags parameter.

Przykłady

Przykład #1 How to register a stream wrapper

<?php
$existed = in_array("var", stream_get_wrappers());
if ($existed) {
    stream_wrapper_unregister("var");
}
stream_wrapper_register("var", "VariableStream");
$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

if ($existed) {
    stream_wrapper_restore("var");
}

?>

Powyższy przykład wyświetli:

line1
line2
line3
string(18) "line1
line2
line3
"

Zobacz też:

  • The streamWrapper prototype class
  • Example class registered as stream wrapper
  • stream_wrapper_unregister() - Unregister a URL wrapper
  • stream_wrapper_restore() - Restores a previously unregistered built-in wrapper
  • stream_get_wrappers() - Retrieve list of registered streams

stream_supports_lock
stream_wrapper_restore
Stream Funkcje


Restores a previously unregistered built-in wrapper

stream_wrapper_register
stream_wrapper_unregister
Stream Funkcje
PHP Manual

stream_wrapper_restore

(PHP 5 >= 5.1.0)

stream_wrapper_restore — Restores a previously unregistered built-in wrapper

Opis

bool stream_wrapper_restore ( string $protocol )

Restores a built-in wrapper previously unregistered with stream_wrapper_unregister().

Parametry

protocol

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

stream_wrapper_register
stream_wrapper_unregister
Stream Funkcje


Unregister a URL wrapper

stream_wrapper_restore
Tidy
Stream Funkcje
PHP Manual

stream_wrapper_unregister

(PHP 5 >= 5.1.0)

stream_wrapper_unregister — Unregister a URL wrapper

Opis

bool stream_wrapper_unregister ( string $protocol )

Allows you to disable an already defined stream wrapper. Once the wrapper has been disabled you may override it with a user-defined wrapper using stream_wrapper_register() or reenable it later on with stream_wrapper_restore().

Parametry

protocol

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

stream_wrapper_restore
Tidy
Stream Funkcje


Tidy

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Przykład Tidy
  • tidy — The tidy class
    • tidy::body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree
    • tidy::cleanRepair — Execute configured cleanup and repair operations on parsed markup
    • tidy::__construct — Constructs a new tidy object
    • tidy::diagnose — Run configured diagnostics on parsed and repaired markup
    • tidy::$errorBuffer — Return warnings and errors which occurred parsing the specified document
    • tidy::getConfig — Get current Tidy configuration
    • tidy::getHtmlVer — Get the Detected HTML version for the specified document
    • tidy::getOpt — Returns the value of the specified configuration option for the tidy document
    • tidy::getoptdoc — Returns the documentation for the given option name
    • tidy::getRelease — Get release date (version) for Tidy library
    • tidy::getStatus — Get status of specified document
    • tidy::head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree
    • tidy::html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree
    • tidy::isXhtml — Indicates if the document is a XHTML document
    • tidy::isXml — Indicates if the document is a generic (non HTML/XHTML) XML document
    • tidy::parseFile — Parse markup in file or URI
    • tidy::parseString — Parse a document stored in a string
    • tidy::repairFile — Repair a file and return it as a string
    • tidy::repairString — Repair a string using an optionally provided configuration file
    • tidy::root — Returns a tidyNode object representing the root of the tidy parse tree
  • tidyNode — The tidyNode class
    • tidyNode::getParent — Zwraca rodzica bieżącego węzła
    • tidyNode::hasChildren — Sprawdza, czy węzeł posiada potomków
    • tidyNode::hasSiblings — Sprawdza, czy węzeł posiada sąsiadów
    • tidyNode::isAsp — Sprawdza, czy węzeł jest kodem ASP
    • tidyNode::isComment — Sprawdza, czy węzeł jest komentarzem
    • tidyNode::isHtml — Sprawdza, czy węzeł jest częścią dokumentu HTML
    • tidyNode::isJste — Sprawdza, czy węzeł jest kodem JSTE
    • tidyNode::isPhp — Sprawdza, czy węzeł jest kodem PHP
    • tidyNode::isText — Sprawdza, czy węzeł jest tekstem (nie jest znacznikiem)
  • Funkcje Tidy
    • ob_tidyhandler — Funkcja zwrotna do czyszczenia bufora wyjścia dla funkcji ob_start
    • tidy_access_count — Zwraca liczbę dostępnych ostrzeżeń napotkanych w określonym dokumencie
    • tidy_config_count — Zwraca liczbę błędów konfiguracji Tidy napotkanych w określonym dokumencie
    • tidy_error_count — Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie
    • tidy_get_output — Zwraca łańcuch zawierający poprawiony przez Tidy kod HTML, XHTML lub XML
    • tidy_load_config — Wczytuje plik konfiguracyjny Tidy w formacie ASCII z określonym kodowaniem znaków narodowych
    • tidy_reset_config — Przywraca domyślne wartości konfiguracji Tidy
    • tidy_save_config — Zapisuje bieżące ustawienia konfiguracyjne Tidy we wskazanym pliku
    • tidy_set_encoding — Ustawia kodowanie znaków narodowych dla dokumentów wejściowych i wyjściowych
    • tidy_setopt — Uaktualnia ustawienia konfiguracji dla określonego dokumentu tidy
    • tidy_warning_count — Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie
stream_wrapper_unregister
Wstęp
Inne podstawowe rozszerzenia


Wstęp

Tidy jest rozszerzeniem opakowującym bibliotekę libTidy (ang. Tidy HTML clean and repair; w wolnym tłumaczeniu: robienie porządków - czyść i napraw kod HTML), która pozwala nie tylko porządkować i manipulować dokumentami HTML, ale również poruszać się po drzewie węzłów dokumentu.

Tidy
Instalacja/Konfiguracja
Tidy


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Tidy


Wymagania

Aby używać rozszerzenia Tidy należy zainstalować bibliotekę libTidy, która jest dostępna na witrynie » http://tidy.sourceforge.net/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To rozszerzenie jest dołączone do PHP 5 i nowszych wersji. Rozszerzenie można zainstalować używając opcji konfiguracyjnej --with-tidy .

Użytkownicy PHP 4 umogą używać (starego) rozszerzenia PECL: » http://pecl.php.net/package/tidy.

Informacja:

Tidy 1.0 współpracuje z PHP 4, natomiast nowsze wersje rozszerzenia Tidy są przeznaczone dla PHP 5 i nowszych wersji.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Opcje konfiguracyjne Tidy
Nazwa | Wartość domyślna | Możliwość zmian | Rejestr zmian
tidy.default_config | "" | PHP_INI_SYSTEM | Dostępna od PHP 5.0.0.
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR w PHP 5. Dostępna od PHP 5.0.0.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

tidy.default_config string

Domyślna ścieżka do pliku konfiguracyjnego tidy.

tidy.clean_output boolean

Włącza/wyłącza wysyłanie wyników przetworzonych przez Tidy na standardowe wyjście.

Ostrzeżenie

Nie ustawiaj tej opcji tidy.clean_output na TRUE jeżeli generujesz treść nietekstową np. dynamiczne obrazy.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

Każda stała TIDY_TAG_XXX przedstawia znacznik HTML. Na przykład, TIDY_TAG_A przedstawia znacznik <a href="XX">link</a>. Każda stała TIDY_ATTR_XXX przedstawia atrybut HTML. Na przykład TIDY_ATTR_HREF przedstawia atrybut href w poprzednim przykładzie.

Zdefiniowane są następujące stałe:

znaczniki tidy
stała
TIDY_TAG_UNKNOWN
TIDY_TAG_A
TIDY_TAG_ABBR
TIDY_TAG_ACRONYM
TIDY_TAG_ALIGN
TIDY_TAG_APPLET
TIDY_TAG_AREA
TIDY_TAG_B
TIDY_TAG_BASE
TIDY_TAG_BASEFONT
TIDY_TAG_BDO
TIDY_TAG_BGSOUND
TIDY_TAG_BIG
TIDY_TAG_BLINK
TIDY_TAG_BLOCKQUOTE
TIDY_TAG_BODY
TIDY_TAG_BR
TIDY_TAG_BUTTON
TIDY_TAG_CAPTION
TIDY_TAG_CENTER
TIDY_TAG_CITE
TIDY_TAG_CODE
TIDY_TAG_COL
TIDY_TAG_COLGROUP
TIDY_TAG_COMMENT
TIDY_TAG_DD
TIDY_TAG_DEL
TIDY_TAG_DFN
TIDY_TAG_DIR
TIDY_TAG_DIV
TIDY_TAG_DL
TIDY_TAG_DT
TIDY_TAG_EM
TIDY_TAG_EMBED
TIDY_TAG_FIELDSET
TIDY_TAG_FONT
TIDY_TAG_FORM
TIDY_TAG_FRAME
TIDY_TAG_FRAMESET
TIDY_TAG_H1
TIDY_TAG_H2
TIDY_TAG_H3
TIDY_TAG_H4
TIDY_TAG_H5
TIDY_TAG_H6
TIDY_TAG_HEAD
TIDY_TAG_HR
TIDY_TAG_HTML
TIDY_TAG_I
TIDY_TAG_IFRAME
TIDY_TAG_ILAYER
TIDY_TAG_IMG
TIDY_TAG_INPUT
TIDY_TAG_INS
TIDY_TAG_ISINDEX
TIDY_TAG_KBD
TIDY_TAG_KEYGEN
TIDY_TAG_LABEL
TIDY_TAG_LAYER
TIDY_TAG_LEGEND
TIDY_TAG_LI
TIDY_TAG_LINK
TIDY_TAG_LISTING
TIDY_TAG_MAP
TIDY_TAG_MARQUEE
TIDY_TAG_MENU
TIDY_TAG_META
TIDY_TAG_MULTICOL
TIDY_TAG_NOBR
TIDY_TAG_NOEMBED
TIDY_TAG_NOFRAMES
TIDY_TAG_NOLAYER
TIDY_TAG_NOSAVE
TIDY_TAG_NOSCRIPT
TIDY_TAG_OBJECT
TIDY_TAG_OL
TIDY_TAG_OPTGROUP
TIDY_TAG_OPTION
TIDY_TAG_P
TIDY_TAG_PARAM
TIDY_TAG_PLAINTEXT
TIDY_TAG_PRE
TIDY_TAG_Q
TIDY_TAG_RP
TIDY_TAG_RT
TIDY_TAG_RTC
TIDY_TAG_RUBY
TIDY_TAG_S
TIDY_TAG_SAMP
TIDY_TAG_SCRIPT
TIDY_TAG_SELECT
TIDY_TAG_SERVER
TIDY_TAG_SERVLET
TIDY_TAG_SMALL
TIDY_TAG_SPACER
TIDY_TAG_SPAN
TIDY_TAG_STRIKE
TIDY_TAG_STRONG
TIDY_TAG_STYLE
TIDY_TAG_SUB
TIDY_TAG_TABLE
TIDY_TAG_TBODY
TIDY_TAG_TD
TIDY_TAG_TEXTAREA
TIDY_TAG_TFOOT
TIDY_TAG_TH
TIDY_TAG_THEAD
TIDY_TAG_TITLE
TIDY_TAG_TR
TIDY_TAG_TR
TIDY_TAG_TT
TIDY_TAG_U
TIDY_TAG_UL
TIDY_TAG_VAR
TIDY_TAG_WBR
TIDY_TAG_XMP

atrybuty tidy
stała
TIDY_ATTR_UNKNOWN
TIDY_ATTR_ABBR
TIDY_ATTR_ACCEPT
TIDY_ATTR_ACCEPT_CHARSET
TIDY_ATTR_ACCESSKEY
TIDY_ATTR_ACTION
TIDY_ATTR_ADD_DATE
TIDY_ATTR_ALIGN
TIDY_ATTR_ALINK
TIDY_ATTR_ALT
TIDY_ATTR_ARCHIVE
TIDY_ATTR_AXIS
TIDY_ATTR_BACKGROUND
TIDY_ATTR_BGCOLOR
TIDY_ATTR_BGPROPERTIES
TIDY_ATTR_BORDER
TIDY_ATTR_BORDERCOLOR
TIDY_ATTR_BOTTOMMARGIN
TIDY_ATTR_CELLPADDING
TIDY_ATTR_CELLSPACING
TIDY_ATTR_CHAR
TIDY_ATTR_CHAROFF
TIDY_ATTR_CHARSET
TIDY_ATTR_CHECKED
TIDY_ATTR_CITE
TIDY_ATTR_CLASS
TIDY_ATTR_CLASSID
TIDY_ATTR_CLEAR
TIDY_ATTR_CODE
TIDY_ATTR_CODEBASE
TIDY_ATTR_CODETYPE
TIDY_ATTR_COLOR
TIDY_ATTR_COLS
TIDY_ATTR_COLSPAN
TIDY_ATTR_COMPACT
TIDY_ATTR_CONTENT
TIDY_ATTR_COORDS
TIDY_ATTR_DATA
TIDY_ATTR_DATAFLD
TIDY_ATTR_DATAPAGESIZE
TIDY_ATTR_DATASRC
TIDY_ATTR_DATETIME
TIDY_ATTR_DECLARE
TIDY_ATTR_DEFER
TIDY_ATTR_DIR
TIDY_ATTR_DISABLED
TIDY_ATTR_ENCODING
TIDY_ATTR_ENCTYPE
TIDY_ATTR_FACE
TIDY_ATTR_FOR
TIDY_ATTR_FRAME
TIDY_ATTR_FRAMEBORDER
TIDY_ATTR_FRAMESPACING
TIDY_ATTR_GRIDX
TIDY_ATTR_GRIDY
TIDY_ATTR_HEADERS
TIDY_ATTR_HEIGHT
TIDY_ATTR_HREF
TIDY_ATTR_HREFLANG
TIDY_ATTR_HSPACE
TIDY_ATTR_HTTP_EQUIV
TIDY_ATTR_ID
TIDY_ATTR_ISMAP
TIDY_ATTR_LABEL
TIDY_ATTR_LANG
TIDY_ATTR_LANGUAGE
TIDY_ATTR_LAST_MODIFIED
TIDY_ATTR_LAST_VISIT
TIDY_ATTR_LEFTMARGIN
TIDY_ATTR_LINK
TIDY_ATTR_LONGDESC
TIDY_ATTR_LOWSRC
TIDY_ATTR_MARGINHEIGHT
TIDY_ATTR_MARGINWIDTH
TIDY_ATTR_MAXLENGTH
TIDY_ATTR_MEDIA
TIDY_ATTR_METHOD
TIDY_ATTR_MULTIPLE
TIDY_ATTR_NAME
TIDY_ATTR_NOHREF
TIDY_ATTR_NORESIZE
TIDY_ATTR_NOSHADE
TIDY_ATTR_NOWRAP
TIDY_ATTR_OBJECT
TIDY_ATTR_OnAFTERUPDATE
TIDY_ATTR_OnBEFOREUNLOAD
TIDY_ATTR_OnBEFOREUPDATE
TIDY_ATTR_OnBLUR
TIDY_ATTR_OnCHANGE
TIDY_ATTR_OnCLICK
TIDY_ATTR_OnDATAAVAILABLE
TIDY_ATTR_OnDATASETCHANGED
TIDY_ATTR_OnDATASETCOMPLETE
TIDY_ATTR_OnDBLCLICK
TIDY_ATTR_OnERRORUPDATE
TIDY_ATTR_OnFOCUS
TIDY_ATTR_OnKEYDOWN
TIDY_ATTR_OnKEYPRESS
TIDY_ATTR_OnKEYUP
TIDY_ATTR_OnLOAD
TIDY_ATTR_OnMOUSEDOWN
TIDY_ATTR_OnMOUSEMOVE
TIDY_ATTR_OnMOUSEOUT
TIDY_ATTR_OnMOUSEOVER
TIDY_ATTR_OnMOUSEUP
TIDY_ATTR_OnRESET
TIDY_ATTR_OnROWENTER
TIDY_ATTR_OnROWEXIT
TIDY_ATTR_OnSELECT
TIDY_ATTR_OnSUBMIT
TIDY_ATTR_OnUNLOAD
TIDY_ATTR_PROFILE
TIDY_ATTR_PROMPT
TIDY_ATTR_RBSPAN
TIDY_ATTR_READONLY
TIDY_ATTR_REL
TIDY_ATTR_REV
TIDY_ATTR_RIGHTMARGIN
TIDY_ATTR_ROWS
TIDY_ATTR_ROWSPAN
TIDY_ATTR_RULES
TIDY_ATTR_SCHEME
TIDY_ATTR_SCOPE
TIDY_ATTR_SCROLLING
TIDY_ATTR_SELECTED
TIDY_ATTR_SHAPE
TIDY_ATTR_SHOWGRID
TIDY_ATTR_SHOWGRIDX
TIDY_ATTR_SHOWGRIDY
TIDY_ATTR_SIZE
TIDY_ATTR_SPAN
TIDY_ATTR_SRC
TIDY_ATTR_STANDBY
TIDY_ATTR_START
TIDY_ATTR_STYLE
TIDY_ATTR_SUMMARY
TIDY_ATTR_TABINDEX
TIDY_ATTR_TARGET
TIDY_ATTR_TEXT
TIDY_ATTR_TITLE
TIDY_ATTR_TOPMARGIN
TIDY_ATTR_TYPE
TIDY_ATTR_USEMAP
TIDY_ATTR_VALIGN
TIDY_ATTR_VALUE
TIDY_ATTR_VALUETYPE
TIDY_ATTR_VERSION
TIDY_ATTR_VLINK
TIDY_ATTR_VSPACE
TIDY_ATTR_WIDTH
TIDY_ATTR_WRAP
TIDY_ATTR_XML_LANG
TIDY_ATTR_XML_SPACE
TIDY_ATTR_XMLNS

typy węzłów tidy
stała | opis
TIDY_NODETYPE_ROOT | podstawowy węzeł
TIDY_NODETYPE_DOCTYPE | typ dokumentu
TIDY_NODETYPE_COMMENT | komentarz HTML
TIDY_NODETYPE_PROCINS | instrukcja przetwarzania
TIDY_NODETYPE_TEXT | tekst
TIDY_NODETYPE_START | znacznik otwierający
TIDY_NODETYPE_END | znacznik zamykający
TIDY_NODETYPE_STARTEND | pusty znacznik
TIDY_NODETYPE_CDATA | CDATA
TIDY_NODETYPE_SECTION | sekcja XML
TIDY_NODETYPE_ASP | kod ASP
TIDY_NODETYPE_JSTE | kod JSTE
TIDY_NODETYPE_PHP | kod PHP
TIDY_NODETYPE_XMLDECL | deklaracja XML

Typy zasobów
Przykłady
Tidy


Przykłady

Spis treści

  • Przykład Tidy
Stałe predefiniowane
Przykład Tidy
Tidy


Przykład Tidy

Ten prosty przykład pokazuje podstawowe użycie Tidy.

Przykład #1 Podstawowe użycie Tidy

<?php
ob_start();
?>
<html>przykładowy dokument html</html>
<?php
$html = ob_get_clean();

// konfiguracja Tidy
$config = array(
           'indent'         => true,
           'output-xhtml'   => true,
           'wrap'           => 200);

// przetwarzanie Tidy
$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

// wynik
echo $tidy;
?>

Przykłady
tidy
Przykłady


The tidy class

(No version information available, might only be in SVN)

Wstęp

An HTML node in an HTML file, as detected by tidy.

Krótki opis klasy

tidy {
/* Właściwości */
string $errorBuffer;
/* Metody */
tidyNode body ( void )
bool cleanRepair ( void )
__construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )
bool diagnose ( void )
array getConfig ( void )
int getHtmlVer ( void )
mixed getOpt ( string $option )
string getOptDoc ( string $optname )
string getRelease ( void )
int getStatus ( void )
tidyNode head ( void )
tidyNode html ( void )
bool isXhtml ( void )
bool isXml ( void )
bool parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )
bool parseString ( string $input [, mixed $config [, string $encoding ]] )
string repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )
string repairString ( string $data [, mixed $config [, string $encoding ]] )
tidyNode root ( void )
}

Spis treści

  • tidy::body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::cleanRepair — Execute configured cleanup and repair operations on parsed markup
  • tidy::__construct — Constructs a new tidy object
  • tidy::diagnose — Run configured diagnostics on parsed and repaired markup
  • tidy::$errorBuffer — Return warnings and errors which occurred parsing the specified document
  • tidy::getConfig — Get current Tidy configuration
  • tidy::getHtmlVer — Get the Detected HTML version for the specified document
  • tidy::getOpt — Returns the value of the specified configuration option for the tidy document
  • tidy::getoptdoc — Returns the documentation for the given option name
  • tidy::getRelease — Get release date (version) for Tidy library
  • tidy::getStatus — Get status of specified document
  • tidy::head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree
  • tidy::isXhtml — Indicates if the document is a XHTML document
  • tidy::isXml — Indicates if the document is a generic (non HTML/XHTML) XML document
  • tidy::parseFile — Parse markup in file or URI
  • tidy::parseString — Parse a document stored in a string
  • tidy::repairFile — Repair a file and return it as a string
  • tidy::repairString — Repair a string using an optionally provided configuration file
  • tidy::root — Returns a tidyNode object representing the root of the tidy parse tree
Przykład Tidy
tidy::body
Tidy


Returns a tidyNode object starting from the <body> tag of the tidy parse tree

tidy
tidy::cleanRepair
tidy
PHP Manual

tidy::body

tidy_get_body

(PHP 5, PECL tidy 0.5.2-1.0)

tidy::body -- tidy_get_body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree

Opis

Styl obiektowy

tidyNode tidy::body ( void )

Styl proceduralny

tidyNode tidy_get_body ( tidy $object )

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Returns the detected HTML version.

Ostrzeżenie

This function is not yet implemented in the Tidylib itself, so it always return 0.

Przykłady

Przykład #1 tidy::getBody() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$body = $tidy->Body();
echo $body->value;
?>

Powyższy przykład wyświetli:

<body>
<p>paragraph</p>
</body>

Notatki

Informacja: Ta funkcja jest dostępna tylko z Zend Engine 2 (PHP >= 5.0.0.)

Zobacz też:

  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree
tidy
tidy::cleanRepair
tidy


Execute configured cleanup and repair operations on parsed markup

tidy::body
tidy::__construct
tidy
PHP Manual

tidy::cleanRepair

tidy_clean_repair

(PHP 5, PECL tidy >= 0.5.2)

tidy::cleanRepair -- tidy_clean_repair — Execute configured cleanup and repair operations on parsed markup

Opis

Styl obiektowy

bool tidy::cleanRepair ( void )

Styl proceduralny

bool tidy_clean_repair ( tidy $object )

This function cleans and repairs the given tidy object.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 tidy::cleanrepair() example

<?php
$html = '<p>test</I>';

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

echo $tidy;
?>

Powyższy przykład wyświetli:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

Zobacz też:

  • tidy::repairFile() - Repair a file and return it as a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file
tidy::body
tidy::__construct
tidy


Constructs a new tidy object

tidy::cleanRepair
tidy::diagnose
tidy
PHP Manual

tidy::__construct

(PHP 5, PECL tidy >= 0.5.2)

tidy::__construct — Constructs a new tidy object

Opis

tidy::__construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )

Constructs a new tidy object.

Parametry

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Zwracane wartości

Returns the new tidy instance.

Przykłady

Przykład #1 tidy::__construct() example

<?php

$html = <<< HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <bt />
text</p>
</body></html>

HTML;

$tidy = new tidy();
$tidy->ParseString($html);

$tidy->cleanRepair();

if ($tidy->errorBuffer) {
    echo "The following errors were detected:\n";
    echo $tidy->errorBuffer;
}

?>

Powyższy przykład wyświetli:

The following errors were detected:
line 8 column 14 - Error: <bt> is not recognized!
line 8 column 14 - Warning: discarding unexpected <bt>

Zobacz też:

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
tidy::cleanRepair
tidy::diagnose
tidy


Run configured diagnostics on parsed and repaired markup

tidy::__construct
tidy::$errorBuffer
tidy
PHP Manual

tidy::diagnose

tidy_diagnose

(PHP 5, PECL tidy >= 0.5.2)

tidy::diagnose -- tidy_diagnose — Run configured diagnostics on parsed and repaired markup

Opis

Styl obiektowy

bool tidy::diagnose ( void )

Styl proceduralny

bool tidy_diagnose ( tidy $object )

Runs diagnostic tests on the given tidy object, adding some more information about the document in the error buffer.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 tidy::diagnose() example

<?php

$html = <<< HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<p>paragraph</p>
HTML;

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

// note the difference between the two outputs
echo $tidy->errorBuffer . "\n";

$tidy->diagnose();
echo $tidy->errorBuffer;

?>

Powyższy przykład wyświetli:

line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
Info: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
Info: Document content looks like XHTML 1.0 Strict
2 warnings, 0 errors were found!

Zobacz też:

  • tidy::errorBuffer()
tidy::__construct
tidy::$errorBuffer
tidy


Return warnings and errors which occurred parsing the specified document

tidy::diagnose
tidy::getConfig
tidy
PHP Manual

tidy::$errorBuffer

tidy_get_error_buffer

(PHP 5, PECL tidy >= 0.5.2)

tidy::$errorBuffer -- tidy_get_error_buffer — Return warnings and errors which occurred parsing the specified document

Opis

Styl obiektowy (property):

string $tidy->errorBuffer;

Styl proceduralny:

string tidy_get_error_buffer ( tidy $tidy )

Returns warnings and errors which occurred parsing the specified document.

Parametry

tidy

Obiekt Tidy.

Zwracane wartości

Returns the error buffer as a string.

Przykłady

Przykład #1 tidy_get_error_buffer() example

<?php
$html = '<p>paragraph</p>';

$tidy = tidy_parse_string($html);

echo tidy_get_error_buffer($tidy);
/* or in OO: */
echo $tidy->errorBuffer;
?>

Powyższy przykład wyświetli:

line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 1 - Warning: inserting missing 'title' element

Zobacz też:

  • tidy_access_count() - Zwraca liczbę dostępnych ostrzeżeń napotkanych w określonym dokumencie
  • tidy_error_count() - Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie
  • tidy_warning_count() - Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie
tidy::diagnose
tidy::getConfig
tidy


Get current Tidy configuration

tidy::$errorBuffer
tidy::getHtmlVer
tidy
PHP Manual

tidy::getConfig

tidy_get_config

(PHP 5, PECL tidy >= 0.7.0)

tidy::getConfig -- tidy_get_config — Get current Tidy configuration

Opis

Styl obiektowy

array tidy::getConfig ( void )

Styl proceduralny

array tidy_get_config ( tidy $object )

Gets the list of the configuration options in use by the given tidy object.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Returns an array of configuration options.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

Przykłady

Przykład #1 tidy::getConfig() example

<?php
$html = '<p>test</p>';
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($html, $config);

print_r($tidy->getConfig());
?>

Powyższy przykład wyświetli:

Array
(
    [indent-spaces] => 2
    [wrap] => 200
    [tab-size] => 8
    [char-encoding] => 1
    [input-encoding] => 3
    [output-encoding] => 1
    [newline] => 1
    [doctype-mode] => 1
    [doctype] =>
    [repeated-attributes] => 1
    [alt-text] =>
    [slide-style] =>
    [error-file] =>
    [output-file] =>
    [write-back] =>
    [markup] => 1
    [show-warnings] => 1
    [quiet] =>
    [indent] => 1
    [hide-endtags] =>
    [input-xml] =>
    [output-xml] => 1
    [output-xhtml] => 1
    [output-html] =>
    [add-xml-decl] =>
    [uppercase-tags] =>
    [uppercase-attributes] =>
    [bare] =>
    [clean] =>
    [logical-emphasis] =>
    [drop-proprietary-attributes] =>
    [drop-font-tags] =>
    [drop-empty-paras] => 1
    [fix-bad-comments] => 1
    [break-before-br] =>
    [split] =>
    [numeric-entities] =>
    [quote-marks] =>
    [quote-nbsp] => 1
    [quote-ampersand] => 1
    [wrap-attributes] =>
    [wrap-script-literals] =>
    [wrap-sections] => 1
    [wrap-asp] => 1
    [wrap-jste] => 1
    [wrap-php] => 1
    [fix-backslash] => 1
    [indent-attributes] =>
    [assume-xml-procins] =>
    [add-xml-space] =>
    [enclose-text] =>
    [enclose-block-text] =>
    [keep-time] =>
    [word-2000] =>
    [tidy-mark] =>
    [gnu-emacs] =>
    [gnu-emacs-file] =>
    [literal-attributes] =>
    [show-body-only] =>
    [fix-uri] => 1
    [lower-literals] => 1
    [hide-comments] =>
    [indent-cdata] =>
    [force-output] => 1
    [show-errors] => 6
    [ascii-chars] => 1
    [join-classes] =>
    [join-styles] => 1
    [escape-cdata] =>
    [language] =>
    [ncr] => 1
    [output-bom] => 2
    [replace-color] =>
    [css-prefix] =>
    [new-inline-tags] =>
    [new-blocklevel-tags] =>
    [new-empty-tags] =>
    [new-pre-tags] =>
    [accessibility-check] => 0
    [vertical-space] =>
    [punctuation-wrap] =>
    [merge-divs] => 1
)

Zobacz też:

  • tidy_reset_config() - Przywraca domyślne wartości konfiguracji Tidy
  • tidy_save_config() - Zapisuje bieżące ustawienia konfiguracyjne Tidy we wskazanym pliku
tidy::$errorBuffer
tidy::getHtmlVer
tidy


Get the Detected HTML version for the specified document

tidy::getConfig
tidy::getOpt
tidy
PHP Manual

tidy::getHtmlVer

tidy_get_html_ver

(PHP 5, PECL tidy >= 0.5.2)

tidy::getHtmlVer -- tidy_get_html_ver — Get the Detected HTML version for the specified document

Opis

Styl obiektowy

int tidy::getHtmlVer ( void )

Styl proceduralny

int tidy_get_html_ver ( tidy $object )

Returns the detected HTML version for the specified tidy object.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Returns the detected HTML version.

Ostrzeżenie

This function is not yet implemented in the Tidylib itself, so it always return 0.

tidy::getConfig
tidy::getOpt
tidy


Returns the value of the specified configuration option for the tidy document

tidy::getHtmlVer
tidy::getoptdoc
tidy
PHP Manual

tidy::getOpt

tidy_getopt

(PHP 5, PECL tidy >= 0.5.2)

tidy::getOpt -- tidy_getopt — Returns the value of the specified configuration option for the tidy document

Opis

Styl obiektowy

mixed tidy::getOpt ( string $option )

Styl proceduralny

mixed tidy_getopt ( tidy $object , string $option )

Returns the value of the specified option for the specified tidy object.

Parametry

object

Obiekt Tidy.

option

You will find a list with each configuration option and their types at: » http://tidy.sourceforge.net/docs/quickref.html.

Zwracane wartości

Returns the value of the specified option. The return type depends on the type of the specified one.

Przykłady

Przykład #1 tidy_getopt() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

$config = array('accessibility-check' => 3,
                'alt-text' => 'some text');

$tidy = new tidy();
$tidy->parseString($html, $config);

var_dump($tidy->getOpt('accessibility-check')); //integer
var_dump($tidy->getOpt('lower-literals')); //boolean
var_dump($tidy->getOpt('alt-text')); //string

?>

Powyższy przykład wyświetli:

int(3)
bool(true)
string(9) "some text"

tidy::getHtmlVer
tidy::getoptdoc
tidy


Returns the documentation for the given option name

tidy::getOpt
tidy::getRelease
tidy
PHP Manual

tidy::getoptdoc

tidy_get_opt_doc

(PHP 5 >= 5.1.0)

tidy::getoptdoc -- tidy_get_opt_doc — Returns the documentation for the given option name

Opis

Styl obiektowy

string tidy::getOptDoc ( string $optname )

Styl proceduralny

string tidy_get_opt_doc ( tidy $object , string $optname )

tidy_get_opt_doc() returns the documentation for the given option name.

Informacja:

You need at least libtidy from 25 April, 2005 for this function be available.

Parametry

object

Obiekt Tidy.

optname

The option name

Zwracane wartości

Returns a string if the option exists and has documentation available, or FALSE otherwise.

Przykłady

Przykład #1 Print all options along with their documentation and default value

<?php

$tidy = new tidy;
$config = $tidy->getConfig();

ksort($config);

foreach ($config as $opt => $val) {

    if (!$doc = $tidy->getOptDoc($opt))
        $doc = 'no documentation available!';

    $val = ($tidy->getOpt($opt) === true)  ? 'true'  : $val;
    $val = ($tidy->getOpt($opt) === false) ? 'false' : $val;

    echo "<p><b>$opt</b> (default: '$val')<br />".
         "$doc</p><hr />\n";
}

?>

Zobacz też:

  • tidy::getconfig() - Get current Tidy configuration
  • tidy::getopt() - Returns the value of the specified configuration option for the tidy document

tidy::getOpt
tidy::getRelease
tidy


Get release date (version) for Tidy library

tidy::getoptdoc
tidy::getStatus
tidy
PHP Manual

tidy::getRelease

tidy_get_release

(PHP 5, PECL tidy >= 0.5.2)

tidy::getRelease -- tidy_get_release — Get release date (version) for Tidy library

Opis

Styl obiektowy

string tidy::getRelease ( void )

Styl proceduralny

string tidy_get_release ( void )

Gets the release date of the Tidy library.

Zwracane wartości

Returns a string with the release date of the Tidy library.

tidy::getoptdoc
tidy::getStatus
tidy


Get status of specified document

tidy::getRelease
tidy::head
tidy
PHP Manual

tidy::getStatus

tidy_get_status

(PHP 5, PECL tidy >= 0.5.2)

tidy::getStatus -- tidy_get_status — Get status of specified document

Opis

Styl obiektowy

int tidy::getStatus ( void )

Styl proceduralny

int tidy_get_status ( tidy $object )

Returns the status for the specified tidy object.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.

Przykłady

Przykład #1 tidy::getStatus() example

<?php
$html = '<p>paragraph</i>';
$tidy = new tidy();
$tidy->parseString($html);

$tidy2 = new tidy();
$html2 = '<bogus>test</bogus>';
$tidy2->parseString($html2);

echo $tidy->getStatus(); //1

echo $tidy2->getStatus(); //2
?>

tidy::getRelease
tidy::head
tidy


Returns a tidyNode object starting from the <head> tag of the tidy parse tree

tidy::getStatus
tidy::html
tidy
PHP Manual

tidy::head

tidy_get_head

(PHP 5, PECL tidy 0.5.2-1.0.0)

tidy::head -- tidy_get_head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree

Opis

Styl obiektowy

tidyNode tidy::head ( void )

Styl proceduralny

tidyNode tidy_get_head ( tidy $object )

Returns a tidyNode object starting from the <head> tag of the tidy parse tree.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Returns the tidyNode object.

Przykłady

Przykład #1 tidy::head() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$head = $tidy->head();
echo $head->value;
?>

Powyższy przykład wyświetli:

<head>
<title>test</title>
</head>

Notatki

Informacja: Ta funkcja jest dostępna tylko z Zend Engine 2 (PHP >= 5.0.0.)

Zobacz też:

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree
tidy::getStatus
tidy::html
tidy


Returns a tidyNode object starting from the <html> tag of the tidy parse tree

tidy::head
tidy::isXhtml
tidy
PHP Manual

tidy::html

tidy_get_html

(PHP 5, PECL tidy 0.5.2-1.0.0)

tidy::html -- tidy_get_html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree

Opis

Styl obiektowy

tidyNode tidy::html ( void )

Styl proceduralny

tidyNode tidy_get_html ( tidy $object )

Returns a tidyNode object starting from the <html> tag of the tidy parse tree.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Returns the tidyNode object.

Przykłady

Przykład #1 tidy::html() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$html = $tidy->html();
echo $html->value;
?>

Powyższy przykład wyświetli:

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

Notatki

Informacja: Ta funkcja jest dostępna tylko z Zend Engine 2 (PHP >= 5.0.0.)

Zobacz też:

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
tidy::head
tidy::isXhtml
tidy


Indicates if the document is a XHTML document

tidy::html
tidy::isXml
tidy
PHP Manual

tidy::isXhtml

tidy_is_xhtml

(PHP 5, PECL tidy >= 0.5.2)

tidy::isXhtml -- tidy_is_xhtml — Indicates if the document is a XHTML document

Opis

Styl obiektowy

bool tidy::isXhtml ( void )

Styl proceduralny

bool tidy_is_xhtml ( tidy $object )

Tells if the document is a XHTML document.

Parametry

object

Obiekt Tidy.

Zwracane wartości

This function returns TRUE if the specified tidy object is a XHTML document, or FALSE otherwise.

Ostrzeżenie

This function is not yet implemented in the Tidylib itself, so it always return FALSE.

tidy::html
tidy::isXml
tidy


Indicates if the document is a generic (non HTML/XHTML) XML document

tidy::isXhtml
tidy::parseFile
tidy
PHP Manual

tidy::isXml

tidy_is_xml

(PHP 5, PECL tidy >= 0.5.2)

tidy::isXml -- tidy_is_xml — Indicates if the document is a generic (non HTML/XHTML) XML document

Opis

Styl obiektowy

bool tidy::isXml ( void )

Styl proceduralny

bool tidy_is_xml ( tidy $object )

Tells if the document is a generic (non HTML/XHTML) XML document.

Parametry

object

Obiekt Tidy.

Zwracane wartości

This function returns TRUE if the specified tidy object is a generic XML document (non HTML/XHTML), or FALSE otherwise.

Ostrzeżenie

This function is not yet implemented in the Tidylib itself, so it always return FALSE.

tidy::isXhtml
tidy::parseFile
tidy


Parse markup in file or URI

tidy::isXml
tidy::parseString
tidy
PHP Manual

tidy::parseFile

tidy_parse_file

(PHP 5, PECL tidy >= 0.5.2)

tidy::parseFile -- tidy_parse_file — Parse markup in file or URI

Opis

Styl obiektowy

bool tidy::parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Styl proceduralny

tidy tidy_parse_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Parses the given file.

Parametry

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, see » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 tidy::parseFile() example

<?php
$tidy = new tidy();
$tidy->parseFile('file.html');

$tidy->cleanRepair();

if(!empty($tidy->errorBuffer)) {
    echo "The following errors or warnings occured:\n";
    echo $tidy->errorBuffer;
}
?>

Notatki

Informacja: Opcjonalne parametry config i encoding zostały dodane w Tidy 2.0.

Zobacz też:

  • tidy::parsestring() - Parse a document stored in a string
  • tidy::repairfile() - Repair a file and return it as a string
  • tidy::repairstring() - Repair a string using an optionally provided configuration file
tidy::isXml
tidy::parseString
tidy


Parse a document stored in a string

tidy::parseFile
tidy::repairFile
tidy
PHP Manual

tidy::parseString

tidy_parse_string

(PHP 5, PECL tidy >= 0.5.2)

tidy::parseString -- tidy_parse_string — Parse a document stored in a string

Opis

Styl obiektowy

bool tidy::parseString ( string $input [, mixed $config [, string $encoding ]] )

Styl proceduralny

tidy tidy_parse_string ( string $input [, mixed $config [, string $encoding ]] )

Parses a document stored in a string.

Parametry

input

The data to be parsed.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

Zwracane wartości

Returns a new tidy instance.

Przykłady

Przykład #1 tidy::parseString() example

<?php
ob_start();
?>

<html>
  <head>
   <title>test</title>
  </head>
  <body>
   <p>error<br>another line</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($buffer, $config, 'UTF8');

$tidy->cleanRepair();
echo $tidy;
?>

Powyższy przykład wyświetli:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      test
    </title>
  </head>
  <body>
    <p>
      error<br />
      another line
    </p>
  </body>
</html>

Notatki

Informacja: Opcjonalne parametry config i encoding zostały dodane w Tidy 2.0.

Zobacz też:

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::repairFile() - Repair a file and return it as a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file
tidy::parseFile
tidy::repairFile
tidy


Repair a file and return it as a string

tidy::parseString
tidy::repairString
tidy
PHP Manual

tidy::repairFile

tidy_repair_file

(PHP 5, PECL tidy >= 0.7.0)

tidy::repairFile -- tidy_repair_file — Repair a file and return it as a string

Opis

Styl obiektowy

string tidy::repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Styl proceduralny

string tidy_repair_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = false ]]] )

Repairs the given file and returns it as a string.

Parametry

filename

The file to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Zwracane wartości

Returns the repaired contents as a string.

Przykłady

Przykład #1 tidy::repairFile() example

<?php
$file = 'file.html';

$tidy = new tidy();
$repaired = $tidy->repairfile($file);
rename($file, $file . '.bak');

file_put_contents($file, $repaired);
?>

Notatki

Informacja: Opcjonalne parametry config i encoding zostały dodane w Tidy 2.0.

Zobacz też:

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file
tidy::parseString
tidy::repairString
tidy


Repair a string using an optionally provided configuration file

tidy::repairFile
tidy::root
tidy
PHP Manual

tidy::repairString

tidy_repair_string

(PHP 5, PECL tidy >= 0.7.0)

tidy::repairString -- tidy_repair_string — Repair a string using an optionally provided configuration file

Opis

Styl obiektowy

string tidy::repairString ( string $data [, mixed $config [, string $encoding ]] )

Styl proceduralny

string tidy_repair_string ( string $data [, mixed $config [, string $encoding ]] )

Repairs the given string.

Parametry

data

The data to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check » http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

Zwracane wartości

Returns the repaired string.

Przykłady

Przykład #1 tidy::repairString() example

<?php
ob_start();
?>

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>error</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$tidy = new tidy();
$clean = $tidy->repairString($buffer);

echo $clean;
?>

Powyższy przykład wyświetli:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>test</title>
</head>
<body>
<p>error</p>
</body>
</html>

Notatki

Informacja: Opcjonalne parametry config i encoding zostały dodane w Tidy 2.0.

Zobacz też:

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
  • tidy::repairFile() - Repair a file and return it as a string
tidy::repairFile
tidy::root
tidy


Returns a tidyNode object representing the root of the tidy parse tree

tidy::repairString
tidyNode
tidy
PHP Manual

tidy::root

tidy_get_root

(PHP 5, PECL tidy 0.5.2-1.0.0)

tidy::root -- tidy_get_root — Returns a tidyNode object representing the root of the tidy parse tree

Opis

Styl obiektowy

tidyNode tidy::root ( void )

Styl proceduralny

tidyNode tidy_get_root ( tidy $object )

Returns a tidyNode object representing the root of the tidy parse tree.

Parametry

object

Obiekt Tidy.

Zwracane wartości

Returns the tidyNode object.

Przykłady

Przykład #1 tidy::root() example

<?php

$html = <<< HTML
<html><body>

<p>paragraph</p>
<br/>

</body></html>
HTML;

$tidy = tidy_parse_string($html);
dump_nodes($tidy->root(), 1);

function dump_nodes($node, $indent) {

    if($node->hasChildren()) {
        foreach($node->child as $child) {
            echo str_repeat('.', $indent*2) . ($child->name ? $child->name : '"'.$child->value.'"'). "\n";

            dump_nodes($child, $indent+1);
        }
    }
}
?>

Powyższy przykład wyświetli:

..html
....head
......title
....body
......p
........"paragraph"
......br

Notatki

Informacja: Ta funkcja jest dostępna tylko z Zend Engine 2 (PHP >= 5.0.0.)

tidy::repairString
tidyNode
tidy


The tidyNode class

(No version information available, might only be in SVN)

Wstęp

An HTML node in an HTML file, as detected by tidy.

Krótki opis klasy

tidyNode {
/* Właściwości */
$value;
$name;
$type;
$line;
$column;
$proprietary;
$id;
$attribute;
$child;
/* Metody */
tidyNode getParent ( void )
bool hasChildren ( void )
bool hasSiblings ( void )
bool isAsp ( void )
bool isComment ( void )
bool isHtml ( void )
bool isJste ( void )
bool isPhp ( void )
bool isText ( void )
}

Właściwości

value

The HTML representation of the node, including the surrounding tags.

name

The name of the HTML node

type

The type of the tag (one of the constants above, e.g. TIDY_NODETYPE_PHP)

line

The line number at which the tags is located in the file

column

The column number at which the tags is located in the file

proprietary

Indicates if the node is a proprietary tag

id

The ID of the tag (one of the constants above, e.g. TIDY_TAG_FRAME)

attribute

An array of string, representing the attributes names (as keys) of the current node.

child

An array of tidyNode, representing the children of the current node.

Wersja | Opis
5.1.0 | line, column and proprietary were added

Spis treści

  • tidyNode::getParent — Zwraca rodzica bieżącego węzła
  • tidyNode::hasChildren — Sprawdza, czy węzeł posiada potomków
  • tidyNode::hasSiblings — Sprawdza, czy węzeł posiada sąsiadów
  • tidyNode::isAsp — Sprawdza, czy węzeł jest kodem ASP
  • tidyNode::isComment — Sprawdza, czy węzeł jest komentarzem
  • tidyNode::isHtml — Sprawdza, czy węzeł jest częścią dokumentu HTML
  • tidyNode::isJste — Sprawdza, czy węzeł jest kodem JSTE
  • tidyNode::isPhp — Sprawdza, czy węzeł jest kodem PHP
  • tidyNode::isText — Sprawdza, czy węzeł jest tekstem (nie jest znacznikiem)
tidy::root
tidyNode::getParent
Tidy


Zwraca rodzica bieżącego węzła

tidyNode
tidyNode::hasChildren
tidyNode
PHP Manual

tidyNode::getParent

(PHP 5 >= 5.2.2)

tidyNode::getParent — Zwraca rodzica bieżącego węzła

Opis

tidyNode tidyNode::getParent ( void )

Zwraca rodzica bieżącego węzła.

Przykłady

Przykład #1 Przykład tidyNode::hasChildren()

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* kod JSTE */
  alert('Hello World');
#>
 </head>
 <body>
 Hello World
 </body>
</html>

HTML;

$tidy = tidy_parse_string($html);
$num = 0;

$node = $tidy->html()->child[0]->child[0];

var_dump($node->getparent()->name);
?>

Powyższy przykład wyświetli:

string(4) "head"

Zwracane wartości

Zwraca tidyNode jeśli węzeł posiada rodzica, w przeciwnym przypadku zwraca NULL .

tidyNode
tidyNode::hasChildren
tidyNode


Sprawdza, czy węzeł posiada potomków

tidyNode::getParent
tidyNode::hasSiblings
tidyNode
PHP Manual

tidyNode::hasChildren

(PHP 5 >= 5.0.1)

tidyNode::hasChildren — Sprawdza, czy węzeł posiada potomków

Opis

bool tidyNode::hasChildren ( void )

Informuje, czy węzeł posiada potomków.

Zwracane wartości

Zwraca TRUE jeśli węzeł posiada potomków, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Przykład tidyNode::hasChildren()

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>tytuł</title>'; ?>
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>
</head>
<body>

<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

<!-- Komentarz -->
Witaj świecie
</body></html>
Poza HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// znacznik head
var_dump($tidy->html()->child[0]->hasChildren());

// PHP wewnątrz znacznika head
var_dump($tidy->html()->child[0]->child[0]->hasChildren());

?>

Powyższy przykład wyświetli:

bool(true)
bool(false)

Notatki

Informacja:

W PHP 4/Tidy 1 stosowano zapis: tidy_node::has_children().

tidyNode::getParent
tidyNode::hasSiblings
tidyNode


Sprawdza, czy węzeł posiada sąsiadów

tidyNode::hasChildren
tidyNode::isAsp
tidyNode
PHP Manual

tidyNode::hasSiblings

(PHP 5 >= 5.0.1)

tidyNode::hasSiblings — Sprawdza, czy węzeł posiada sąsiadów

Opis

bool tidyNode::hasSiblings ( void )

Informuje, czy węzeł posiada sąsiadów.

Zwracane wartości

Zwraca TRUE jeśli węzeł posiada sąsiadów, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Przykład tidyNode::hasSiblings()

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>tytuł</title>'; ?>
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>
</head>
<body>

<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

<!-- Komentarz -->
Witaj świecie
</body></html>
Poza HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// znacznik html
var_dump($tidy->html()->hasSiblings());

// znacznik head
var_dump($tidy->html()->child[0]->hasSiblings());

?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Notatki

Informacja:

W PHP 4/Tidy 1 stosowano zapis: tidy_node::has_siblings().

tidyNode::hasChildren
tidyNode::isAsp
tidyNode


Sprawdza, czy węzeł jest kodem ASP

tidyNode::hasSiblings
tidyNode::isComment
tidyNode
PHP Manual

tidyNode::isAsp

(PHP 5 >= 5.0.1)

tidyNode::isAsp — Sprawdza, czy węzeł jest kodem ASP

Opis

bool tidyNode::isAsp ( void )

Informuje, czy bieżący węzeł jest kodem ASP (Active Server Pages).

Zwracane wartości

Zwraca TRUE jeśli węzeł jest kodem ASP, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Wyodrębnienie kodu ASP ze złożonego dokumentu HTML

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>
</head>
<body>

<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

<!-- Komentarz -->
Witaj świecie
</body></html>
Poza HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node, $node_type) {

    // sprawdza, czy bieżący węzeł jest typu, o który pytamy
    if($node->isAsp()) {
        echo "\n\n# węzeł asp #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // sprawdza, czy bieżący węzeł posiada potomków
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

Powyższy przykład wyświetli:

# węzeł asp #1
<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

Notatki

Informacja:

W PHP 4/Tidy 1 stosowano zapis: tidy_node::is_asp().

tidyNode::hasSiblings
tidyNode::isComment
tidyNode


Sprawdza, czy węzeł jest komentarzem

tidyNode::isAsp
tidyNode::isHtml
tidyNode
PHP Manual

tidyNode::isComment

(PHP 5 >= 5.0.1)

tidyNode::isComment — Sprawdza, czy węzeł jest komentarzem

Opis

bool tidyNode::isComment ( void )

Informuje, czy węzeł jest komentarzem.

Zwracane wartości

Zwraca TRUE jeśli węzeł jest komentarzem, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Wyodrębnienie komentarzy ze złożonego dokumentu HTML

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>
</head>
<body>

<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

<!-- Comments -->
Witaj świecie
</body></html>
Poza HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html(), 'comment');

function get_nodes($node, $node_type) {

    // sprawdza, czy bieżący węzeł jest typu, o który pytamy
    if($node->{"is$node_type"}()) {
        echo "\n\n# $node_type node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // sprawdza, czy bieżący węzeł posiada potomków
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child, $node_type);
        }
    }
}

?>

Powyższy przykład wyświetli:

# węzeł JSTE #1
<#
  /* JSTE code */
  alert('Witaj świecie');
#>

/*
var_dump($tidy->html()->child[0]->hasChildren());
var_dump($tidy->html()->child[0]->child[0]->hasChildren());
*/

Notatki

Informacja:

W PHP 4/Tidy 1 stosowano zapis: tidy_node::is_comment().

tidyNode::isAsp
tidyNode::isHtml
tidyNode


Sprawdza, czy węzeł jest częścią dokumentu HTML

tidyNode::isComment
tidyNode::isJste
tidyNode
PHP Manual

tidyNode::isHtml

(PHP 5 >= 5.0.1)

tidyNode::isHtml — Sprawdza, czy węzeł jest częścią dokumentu HTML

Opis

bool tidyNode::isHtml ( void )

Informuje, czy węzeł jest częścią dokumentu HTML.

Zwracane wartości

Zwraca TRUE jeśli węzeł jest częścią dokumentu HTML, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Wyodrębnienie kodu HTML ze złożonego dokumentu HTML

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>tytuł</title>'; ?>
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>
</head>
<body>

<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

<!-- Komentarz -->
Witaj świecie
</body></html>
Poza HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html(), 'text');

function get_nodes($node, $node_type) {
    // sprawdza, czy bieżący węzeł jest typu, o który pytamy
    if($node->{"is$node_type"}()) {
        echo "\n\n# $node_type node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // sprawdza, czy bieżący węzeł posiada potomków
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child, $node_type);
        }
    }
}

?>

Powyższy przykład wyświetli:

# węzeł HTML #1
<html>
<head>
<?php echo '<title>tytuł</title>'; ?><#
  /* kod JSTE */
  alert('Witaj świecie');
#>
<title></title>
</head>
<body>
<?php
  // kod PHP
  echo 'Witaj świecie!';
?><%
  /* kod ASP */
  response.write("Witaj świecie!")
%><!-- Komentarz -->
Witaj świecie Poza HTML
</body>
</html>

# węzeł HTML #2
<head>
<?php echo '<title>tytuł</title>'; ?><#
  /* kod JSTE */
  alert('Witaj świecie');
#>
<title></title>
</head>

# węzeł HTML #3
<?php echo '<title>tytuł</title>'; ?>

# węzeł HTML #4
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>

# węzeł HTML #5
<title></title>

# węzeł HTML #6
<body>
<?php
  // kod PHP
  echo 'Witaj świecie!';
?><%
  /* kod ASP */
  response.write("Witaj świecie!")
%><!-- Komentarz -->
Witaj świeciePoza HTML
</body>

# węzeł HTML #7
<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

# węzeł HTML #8
<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

# węzeł HTML #9
<!-- Komentarz -->

# węzeł HTML #10
Witaj świecie

# węzeł HTML #11
Poza HTML

Notatki

Informacja:

W PHP 4/Tidy 1 stosowano zapis: tidy_node::is_html().

tidyNode::isComment
tidyNode::isJste
tidyNode


Sprawdza, czy węzeł jest kodem JSTE

tidyNode::isHtml
tidyNode::isPhp
tidyNode
PHP Manual

tidyNode::isJste

(PHP 5 >= 5.0.1)

tidyNode::isJste — Sprawdza, czy węzeł jest kodem JSTE

Opis

bool tidyNode::isJste ( void )

Informuje, czy węzeł jest kodem JSTE.

Zwracane wartości

Zwraca TRUE jeśli węzeł jest kodem JSTE, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Wyodrębnienie kodu JSTE ze złożonego dokumentu HTML

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>tytuł</title>'; ?>
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>
</head>
<body>

<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

<!-- Komentarz -->
Witaj świecie
</body></html>
Poza HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html(), 'text');

function get_nodes($node, $node_type) {

    // sprawdza, czy bieżący węzeł jest typu, o który pytamy
    if($node->{"is$node_type"}()) {
        echo "\n\n# $node_type node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // sprawdza, czy bieżący węzeł posiada potomków
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child, $node_type);
        }
    }
}

?>

Powyższy przykład wyświetli:

# węzeł JSTE #1
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>

/*
var_dump($tidy->html()->child[0]->hasChildren());
var_dump($tidy->html()->child[0]->child[0]->hasChildren());
*/

Notatki

Informacja:

W PHP 4/Tidy 1 stosowano zapis: tidy_node::is_jste().

tidyNode::isHtml
tidyNode::isPhp
tidyNode


Sprawdza, czy węzeł jest kodem PHP

tidyNode::isJste
tidyNode::isText
tidyNode
PHP Manual

tidyNode::isPhp

(PHP 5 >= 5.0.1)

tidyNode::isPhp — Sprawdza, czy węzeł jest kodem PHP

Opis

bool tidyNode::isPhp ( void )

Informuje, czy węzeł jest kodem PHP.

Zwracane wartości

Zwraca TRUE jeśli bieżący węzeł jest kodem PHP, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Wyodrębnienie kodu PHP ze złożonego dokumentu HTML

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>tytuł</title>'; ?>
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>
</head>
<body>

<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

<!-- Komentarz -->
Witaj świecie
</body></html>
Poza HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html(), 'php');

function get_nodes($node, $node_type) {

    // sprawdza, czy bieżący węzeł jest typu, o który pytamy
    if($node->{"is$node_type"}()) {
        echo "\n\n# $node_type node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // sprawdza, czy bieżący węzeł posiada potomków
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child, $node_type);
        }
    }
}

?>

Powyższy przykład wyświetli:

# węzeł PHP #1
<?php echo '<title>tytuł</title>'; ?>

# węzeł PHP #2
<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

Notatki

Informacja:

W PHP 4/Tidy 1 stosowano zapis: tidy_node::is_php().

tidyNode::isJste
tidyNode::isText
tidyNode


Sprawdza, czy węzeł jest tekstem (nie jest znacznikiem)

tidyNode::isPhp
Funkcje Tidy
tidyNode
PHP Manual

tidyNode::isText

(PHP 5 >= 5.0.1)

tidyNode::isText — Sprawdza, czy węzeł jest tekstem (nie jest znacznikiem)

Opis

bool tidyNode::isText ( void )

Informuje, czy węzeł jest tekstem (nie jest znacznikiem).

Zwracane wartości

Zwraca TRUE jeśli węzeł jest tekstem, w przeciwnym przypadku zwraca FALSE.

Przykłady

Przykład #1 Wyodrębnienie tekstu ze złożonego dokumentu HTML

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>tytuł</title>'; ?>
<#
  /* kod JSTE */
  alert('Witaj świecie');
#>
</head>
<body>

<?php
  // kod PHP
  echo 'Witaj świecie!';
?>

<%
  /* kod ASP */
  response.write("Witaj świecie!")
%>

<!-- Komentarz -->
Witaj świecie
</body></html>
Poza HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html(), 'text');

function get_nodes($node, $node_type) {

    // sprawdza, czy bieżący węzeł jest typu, o który pytamy
    if($node->{"is$node_type"}()) {
        echo "\n\n# $node_type node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // sprawdza, czy bieżący węzeł posiada potomków
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child, $node_type);
        }
    }
}

?>

Powyższy przykład wyświetli:

# text node #1
Witaj świecie

# text node #2
Poza HTML

Notatki

Informacja:

W PHP 4/Tidy 1 stosowano zapis: tidy_node::is_text().

tidyNode::isPhp
Funkcje Tidy
tidyNode


Funkcje Tidy

Spis treści

  • ob_tidyhandler — Funkcja zwrotna do czyszczenia bufora wyjścia dla funkcji ob_start
  • tidy_access_count — Zwraca liczbę dostępnych ostrzeżeń napotkanych w określonym dokumencie
  • tidy_config_count — Zwraca liczbę błędów konfiguracji Tidy napotkanych w określonym dokumencie
  • tidy_error_count — Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie
  • tidy_get_output — Zwraca łańcuch zawierający poprawiony przez Tidy kod HTML, XHTML lub XML
  • tidy_load_config — Wczytuje plik konfiguracyjny Tidy w formacie ASCII z określonym kodowaniem znaków narodowych
  • tidy_reset_config — Przywraca domyślne wartości konfiguracji Tidy
  • tidy_save_config — Zapisuje bieżące ustawienia konfiguracyjne Tidy we wskazanym pliku
  • tidy_set_encoding — Ustawia kodowanie znaków narodowych dla dokumentów wejściowych i wyjściowych
  • tidy_setopt — Uaktualnia ustawienia konfiguracji dla określonego dokumentu tidy
  • tidy_warning_count — Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie
tidyNode::isText
ob_tidyhandler
Tidy


Funkcja zwrotna do czyszczenia bufora wyjścia dla funkcji ob_start

Funkcje Tidy
tidy_access_count
Funkcje Tidy
PHP Manual

ob_tidyhandler

(PHP 5)

ob_tidyhandler — Funkcja zwrotna do czyszczenia bufora wyjścia dla funkcji ob_start

Opis

string ob_tidyhandler ( string $wejście [, int $tryb ] )

Funkcja zwrotna do poprawiania bufora wyjścia dla funkcji ob_start().

Parametry

wejście

Bufor.

tryb

Tryb bufora.

Zwracane wartości

Zwraca zmodyfikowany bufor.

Przykłady

Przykład #1 Przykład ob_tidyhandler()

<?php
ob_start('ob_tidyhandler');

echo '<p>test</i>';
?>

Powyższy przykład wyświetli:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

Zobacz też:

  • ob_start() - Turn on output buffering

Funkcje Tidy
tidy_access_count
Funkcje Tidy


Zwraca liczbę dostępnych ostrzeżeń napotkanych w określonym dokumencie

ob_tidyhandler
tidy_config_count
Funkcje Tidy
PHP Manual

tidy_access_count

(PHP 5, PECL tidy >= 0.5.2)

tidy_access_count — Zwraca liczbę dostępnych ostrzeżeń napotkanych w określonym dokumencie

Opis

int tidy_access_count ( tidy $obiekt )

tidy_access_count() zwraca liczbę dostępnych ostrzeżeń znalezionych w danym dokumencie.

Parametry

obiekt

Obiekt Tidy.

Zwracane wartości

Zwraca liczbę ostrzeżeń.

Przykłady

Przykład #1 Przykład tidy_access_count()

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Tytuł</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

// wybierz poziom sprawdzania dostępności: 1, 2 lub 3
$config = array('accessibility-check' => 3);

$tidy = new tidy();
$tidy->parseString($html, $config);
$tidy->CleanRepair();

/* Nigdy nie zapomnij wywołać tej metody! */
$tidy->diagnose();

echo tidy_access_count($tidy); //5

?>

Notatki

Informacja:

Ponieważ biblioteka Tidy została tak zaprojektowana, należy wywołać tidy_diagnose() przed tidy_access_count(), bo inaczej ta funkcja zawsze będzie zwracała 0. Należy także aktywować opcję accessibility-check.

Zobacz też:

  • tidy_error_count() - Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie
  • tidy_warning_count() - Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie

ob_tidyhandler
tidy_config_count
Funkcje Tidy


Zwraca liczbę błędów konfiguracji Tidy napotkanych w określonym dokumencie

tidy_access_count
tidy_error_count
Funkcje Tidy
PHP Manual

tidy_config_count

(PHP 5, PECL tidy >= 0.5.2)

tidy_config_count — Zwraca liczbę błędów konfiguracji Tidy napotkanych w określonym dokumencie

Opis

int tidy_config_count ( tidy $obiekt )

tidy_config_count() zwraca liczbę błędów napotkanych w konfiguracji określonego obiektu tidy.

Parametry

obiekt

Obiekt Tidy.

Zwracane wartości

Zwraca liczbę błędów.

Przykłady

Przykład #1 Przykład tidy_config_count()

<?php
$html = '<p>test</I>';

$config = array('doctype' => 'bogus');

$tidy = tidy_parse_string($html, $config);

/* Zwróci 1, ponieważ 'bogus' nie jest prawidłowym typem dokumentu */
echo tidy_config_count($tidy);
?>

tidy_access_count
tidy_error_count
Funkcje Tidy


Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie

tidy_config_count
tidy_get_output
Funkcje Tidy
PHP Manual

tidy_error_count

(PHP 5, PECL tidy >= 0.5.2)

tidy_error_count — Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie

Opis

int tidy_error_count ( tidy $obiekt )

Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie.

Parametry

obiekt

Obiekt Tidy.

Zwracane wartości

Zwraca liczbę błędów.

Przykłady

Przykład #1 Przykład tidy_error_count()

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1

echo $tidy->errorBuffer;
?>

Powyższy przykład wyświetli:

1
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 8 - Warning: discarding unexpected </i>
line 2 column 1 - Error: <bogustag> is not recognized!
line 2 column 1 - Warning: discarding unexpected <bogustag>
line 2 column 16 - Warning: discarding unexpected </bogustag>
line 1 column 1 - Warning: inserting missing 'title' element

Zobacz też:

  • tidy_access_count() - Zwraca liczbę dostępnych ostrzeżeń napotkanych w określonym dokumencie
  • tidy_warning_count() - Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie
tidy_config_count
tidy_get_output
Funkcje Tidy


Zwraca łańcuch zawierający poprawiony przez Tidy kod HTML, XHTML lub XML

tidy_error_count
tidy_load_config
Funkcje Tidy
PHP Manual

tidy_get_output

(PHP 5, PECL tidy >= 0.5.2)

tidy_get_output — Zwraca łańcuch zawierający poprawiony przez Tidy kod HTML, XHTML lub XML

Opis

string tidy_get_output ( tidy $obiekt )

Zwraca łańcuch zawierający poprawiony kod HTML, XHTML lub XML.

Parametry

obiekt

Obiekt Tidy.

Zwracane wartości

Zwraca kod poprawiony przez Tidy.

Przykłady

Przykład #1 Przykład tidy_get_output()

<?php

$html = '<p>paragraf</i>';
$tidy = tidy_parse_string($html);

$tidy->CleanRepair();

echo tidy_get_output($tidy);
?>

Powyższy przykład wyświetli:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>paragraf</p>
</body>
</html>

tidy_error_count
tidy_load_config
Funkcje Tidy


Wczytuje plik konfiguracyjny Tidy w formacie ASCII z określonym kodowaniem znaków narodowych

tidy_get_output
tidy_reset_config
Funkcje Tidy
PHP Manual

tidy_load_config

(PECL tidy >= 0.5.2)

tidy_load_config — Wczytuje plik konfiguracyjny Tidy w formacie ASCII z określonym kodowaniem znaków narodowych

Opis

void tidy_load_config ( string $nazwa_pliku , string $kodowanie_znaków )

Ta funkcja wczytuje plik konfiguracyjny Tidy, z określonym kodowaniem_znaków.

Parametry

nazwa_pliku

kodowanie_znaków

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja: Ta funkcja jest dostępna tylko w Tidy 1.0. W wersji 2.0 stała się niepotrzebna i w związku z tym została usunięta.

tidy_get_output
tidy_reset_config
Funkcje Tidy


Przywraca domyślne wartości konfiguracji Tidy

tidy_load_config
tidy_save_config
Funkcje Tidy
PHP Manual

tidy_reset_config

(PECL tidy >= 0.7.0)

tidy_reset_config — Przywraca domyślne wartości konfiguracji Tidy

Opis

bool tidy_reset_config ( void )

Ta funkcja ustawia domyślne wartości konfiguracji Tidy.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja jest dostępna tylko w Tidy 1.0. W wersji 2.0 stała się niepotrzebna i w związku z tym została usunięta.

tidy_load_config
tidy_save_config
Funkcje Tidy


Zapisuje bieżące ustawienia konfiguracyjne Tidy we wskazanym pliku

tidy_reset_config
tidy_set_encoding
Funkcje Tidy
PHP Manual

tidy_save_config

(PECL tidy >= 0.5.2)

tidy_save_config — Zapisuje bieżące ustawienia konfiguracyjne Tidy we wskazanym pliku

Opis

bool tidy_save_config ( string $nazwa_pliku )

Zapisuje bieżące ustawienia konfiguracyjne w określonym pliku. Zapisywane są tylko wartości różne od domyślnych.

Parametry

nazwa_pliku

Ścieżka do pliku konfiguracyjnego.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja jest dostępna tylko w Tidy 1.0. W wersji 2.0 stała się niepotrzebna i w związku z tym została usunięta.

Zobacz też:

  • tidy_get_config() - Get current Tidy configuration
  • tidy_getopt() - Returns the value of the specified configuration option for the tidy document
  • tidy_reset_config() - Przywraca domyślne wartości konfiguracji Tidy
  • tidy_setopt() - Uaktualnia ustawienia konfiguracji dla określonego dokumentu tidy

tidy_reset_config
tidy_set_encoding
Funkcje Tidy


Ustawia kodowanie znaków narodowych dla dokumentów wejściowych i wyjściowych

tidy_save_config
tidy_setopt
Funkcje Tidy
PHP Manual

tidy_set_encoding

(PECL tidy >= 0.5.2)

tidy_set_encoding — Ustawia kodowanie znaków narodowych dla dokumentów wejściowych i wyjściowych

Opis

bool tidy_set_encoding ( string $kodowanie_znaków )

Ustawia kodowanie znaków narodowych dla dokumentów wejściowych i wyjściowych.

Parametry

kodowanie_znaków

Parametr kodowanie_znaków ustawia kodowanie znaków narodowych dla dokumentów wejściowych i wyjściowych. Dopuszczalne wartości kodowania znaków to: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, i shiftjis.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja jest dostępna tylko w Tidy 1.0. W wersji 2.0 stała się niepotrzebna i w związku z tym została usunięta.

tidy_save_config
tidy_setopt
Funkcje Tidy


Uaktualnia ustawienia konfiguracji dla określonego dokumentu tidy

tidy_set_encoding
tidy_warning_count
Funkcje Tidy
PHP Manual

tidy_setopt

(PECL tidy >= 0.5.2)

tidy_setopt — Uaktualnia ustawienia konfiguracji dla określonego dokumentu tidy

Opis

bool tidy_setopt ( string $opcja , mixed $wartość )

tidy_setopt() uaktualnia określony parametr opcja ustawiając nową wartość.

Parametry

opcja

Nazwa opcji tidy. Lista dostępnych opcji konfiguracyjnych znajduje się pod adresesm: » http://tidy.sourceforge.net/docs/quickref.html.

wartość

Wartość opcji tidy.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład tidy_setopt()

<?php
$html = '<p>test</i>';

$tidy = tidy_parse_string($html);

tidy_setopt('indent', FALSE);
?>

Notatki

Informacja: Ta funkcja jest dostępna tylko w Tidy 1.0. W wersji 2.0 stała się niepotrzebna i w związku z tym została usunięta.

Zobacz też:

  • tidy_getopt() - Returns the value of the specified configuration option for the tidy document
  • tidy_get_config() - Get current Tidy configuration
  • tidy_reset_config() - Przywraca domyślne wartości konfiguracji Tidy
  • tidy_save_config() - Zapisuje bieżące ustawienia konfiguracyjne Tidy we wskazanym pliku
tidy_set_encoding
tidy_warning_count
Funkcje Tidy


Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie

tidy_setopt
Tokenizer
Funkcje Tidy
PHP Manual

tidy_warning_count

(PHP 5, PECL tidy >= 0.5.2)

tidy_warning_count — Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie

Opis

int tidy_warning_count ( tidy $obiekt )

Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie.

Parametry

obiekt

Obiekt Tidy.

Zwracane wartości

Zwraca liczbe ostrzeżeń.

Przykłady

Przykład #1 Przykład tidy_warning_count()

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1
echo tidy_warning_count($tidy) . "\n"; //5
?>

Zobacz też:

  • tidy_error_count() - Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie
  • tidy_access_count() - Zwraca liczbę dostępnych ostrzeżeń napotkanych w określonym dokumencie

tidy_setopt
Tokenizer
Funkcje Tidy


Tokenizer

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Funkcje Tokenizer
    • token_get_all — Dzieli zadane źródło na tokeny PHP
    • token_name — Zwraca symboliczną nazwę danego tokena PHP
tidy_warning_count
Wstęp
Inne podstawowe rozszerzenia


Wstęp

Funkcje tokenizera są interfejsem dostępu do wewnętrznego tokenizera, wbudowanego w Zend Engine. Używając tych funkcji można napisać swoje własne narzędzia do analizy lub modyfikacji kodu PHP, bez potrzeby zajmowania się specyfikacją języka na poziomie analizy leksykalnej.

Zobacz też: dodatek o tokenach.

Tokenizer
Instalacja/Konfiguracja
Tokenizer


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Tokenizer


Instalacja

Począwszy od PHP 4.3.0 te funkcje są dostępne domyślnie. Dla starszych wersji musimy skonfigurować i skompilować PHP z opcją --enable-tokenizer . Możemy wyłączyć obsługę tokenizera podczas kompilacji PHP za pomocą opcji --disable-tokenizer .

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: Wbudowana obsługa tokenizera jest dostępna od PHP 4.3.0.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

Gdy rozszerzenie zostało skompilowane z PHP lub załadowane dynamicznie, tokeny wymienione w List of Parser Tokens są zdefiniowane jako stałe.

Typy zasobów
Przykłady
Tokenizer


Przykłady

Poniżej zamieszczony jest prosty przykład skryptu PHP, który używa tokenizera. Skrypt wczytuje plik PHP, usuwa wszystkie komentarze z kodu źródłowego i wyświetla sam czysty kod.

Przykład #1 Usuwanie komentarzy za pomocą tokenizera

<?php
  /* T_ML_COMMENT nie istnieje w PHP 5.
   * Następujące trzy linie definiują tę stałą, by zachować kompatybilność
   * wsteczną.
   *
   * Kolejne dwie linie definiują istniejącą tylko w PHP 5 stałą
   * T_DOC_COMMENT, którą w PHP 4 podmienimy jako T_ML_COMMENT.
   */
  if (!defined('T_ML_COMMENT')) {
    define('T_ML_COMMENT', T_COMMENT);
  } else {
    define('T_DOC_COMMENT', T_ML_COMMENT);
  }

  $kod = file_get_contents("jakisplik.php");
  $tokeny = token_get_all($kod);

  foreach ($tokeny as $token) {
    if (is_string($token)) {
      // prosty token jednoznakowy
      echo $token;
    } else {
      // tablica definiująca token
      list($id, $tekst) = $token;

      switch ($id) {
        case T_COMMENT:
        case T_ML_COMMENT: // to zdefiniowaliśmy
        case T_DOC_COMMENT: // to też
          // brak akcji dla komentarzy
          break;
        default:
          // wszystko inne -> wyświetl "takie, jakie jest"
          echo $tekst;
          break;
      }
    }
  }
?>
Stałe predefiniowane
Funkcje Tokenizer
Tokenizer


Funkcje Tokenizer

Spis treści

  • token_get_all — Dzieli zadane źródło na tokeny PHP
  • token_name — Zwraca symboliczną nazwę danego tokena PHP
Przykłady
token_get_all
Tokenizer


Dzieli zadane źródło na tokeny PHP

Funkcje Tokenizer
token_name
Funkcje Tokenizer
PHP Manual

token_get_all

(PHP 4 >= 4.2.0, PHP 5)

token_get_all — Dzieli zadane źródło na tokeny PHP

Opis

array token_get_all ( string $źródło )

token_get_all() parsuje zadane źródło, czyli ciąg znaków zawierający kod PHP, zamieniając je na tokeny języka PHP przy użyciu analizy leksykalnej silnika Zend.

Listę tokenów identyfikowanych przez parser znajdziesz w List of Parser Tokens, możesz także użyć funkcji token_name() by przetłumaczyć wartość tokena na jego nazwę.

Parametry

źródło

Źródło PHP do sparsowania.

Zwracane wartości

Tablica zindentyfikowanych tokenów. Każdy pojedynczy token identyfikowany jest poprzez pojedynczy znak (np.: ;, ., >, !, etc...), lub trójelementową tablicę zawierającą indeks tokenu w elemencie 0 i łańcuch znaków zawierający oryginalny token w elemencie 1 i numer linii w elemencie 2.

Przykłady

Przykład #1 Przykłady użycia token_get_all()

<?php
  $tokeny = token_get_all('<?php echo; ?>'); /* => array(
                                                    array(T_OPEN_TAG, '<?php'),
                                                    array(T_ECHO, 'echo'),
                                                    ';',
                                                    array(T_CLOSE_TAG, '?>') ); */
.
/* W następnym przykładzie zwróć uwagę na fakt, iż ciąg znaków jest parsowany
   jako T_INLINE_HTML, inaczej niż oczekiwane T_COMMENT (T_ML_COMMENT w PHP
   <5). Jest tak z powodu braku w "kodzie" otwierających/zamykających tagów
   PHP. Jest to jednoznaczne z komentarzem znajdującym się poza tagami <?php
   ?> w normalnym pliku. */
  $tokeny = token_get_all('/* koment. */'); // => array(array(T_INLINE_HTML, '/* koment. */'));
?>

Rejestr zmian

Wersja | Opis
5.2.2 | Numer linii jest zwracany w elemencie 2

Funkcje Tokenizer
token_name
Funkcje Tokenizer


Zwraca symboliczną nazwę danego tokena PHP

token_get_all
URL Funkcje
Funkcje Tokenizer
PHP Manual

token_name

(PHP 4 >= 4.2.0, PHP 5)

token_name — Zwraca symboliczną nazwę danego tokena PHP

Opis

string token_name ( int $token )

token_name() pobiera symboliczną nazwę tokena dla wartości podanej w parametrze token.

Parametry

token

Wartość tokena.

Zwracane wartości

Nazwa symboliczna podanego tokenu.

Przykłady

Przykład #1 Przykład token_name()

<?php
// 260 jest wartością tokena dla tokena T_REQUIRE
echo token_name(260);        // -> "T_REQUIRE"

// stała zdefiniowana dla tokena odpowiada swojej nazwie
echo token_name(T_FUNCTION); // -> "T_FUNCTION"
?>

Zobacz też:

  • Lista parsowanych tokenów

token_get_all
URL Funkcje
Funkcje Tokenizer


URL Funkcje

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • URL Funkcje
    • base64_decode — Dekoduje dane zakodowane algorytmem MIME base64
    • base64_encode — Koduje dane za pomocą algorytmu MIME base64
    • get_headers — Fetches all the headers sent by the server in response to a HTTP request
    • get_meta_tags — Extracts all meta tag content attributes from a file and returns an array
    • http_build_query — Generate URL-encoded query string
    • parse_url — Przetwarza adres URL i zwraca jego składowe
    • rawurldecode — Dekoduje łańcuchy zakodowane metodą kodowania URL'i
    • rawurlencode — Koduje URL'e zgodnie z RFC 1738
    • urldecode — Dekoduje łańcuchy zakodowane metodą kodowania URL'i
    • urlencode — Koduje łańcuch metodą kodowania URLi
token_name
Wstęp
Inne podstawowe rozszerzenia


Wstęp

Postępowanie z łańcuchami zawierającymi URL: kodowanie, dekodowanie i przetwarzanie.

URL Funkcje
Instalacja/Konfiguracja
URL Funkcje


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
URL Funkcje


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.

Poniższe stałe są przeznaczone do użycia z parse_url() i dostępne są od PHP 5.1.2.

PHP_URL_SCHEME (integer)
PHP_URL_HOST (integer)
PHP_URL_PORT (integer)
PHP_URL_USER (integer)
PHP_URL_PASS (integer)
PHP_URL_PATH (integer)
PHP_URL_QUERY (integer)
PHP_URL_FRAGMENT (integer)
PHP_QUERY_RFC1738 (integer)
PHP_QUERY_RFC3986 (integer)
Typy zasobów
URL Funkcje
URL Funkcje


URL Funkcje
PHP Manual

URL Funkcje

Spis treści

  • base64_decode — Dekoduje dane zakodowane algorytmem MIME base64
  • base64_encode — Koduje dane za pomocą algorytmu MIME base64
  • get_headers — Fetches all the headers sent by the server in response to a HTTP request
  • get_meta_tags — Extracts all meta tag content attributes from a file and returns an array
  • http_build_query — Generate URL-encoded query string
  • parse_url — Przetwarza adres URL i zwraca jego składowe
  • rawurldecode — Dekoduje łańcuchy zakodowane metodą kodowania URL'i
  • rawurlencode — Koduje URL'e zgodnie z RFC 1738
  • urldecode — Dekoduje łańcuchy zakodowane metodą kodowania URL'i
  • urlencode — Koduje łańcuch metodą kodowania URLi
Stałe predefiniowane
base64_decode
URL Funkcje
PHP Manual


Dekoduje dane zakodowane algorytmem MIME base64

URL Funkcje
base64_encode
URL Funkcje
PHP Manual

base64_decode

(PHP 4, PHP 5)

base64_decode — Dekoduje dane zakodowane algorytmem MIME base64

Opis

string base64_decode ( string $dane_zakodowane )

base64_decode() dekoduje dane_zakodowane i zwraca oryginalną postać danych lub FALSE w przypadku niepowodzenia. Dane wynikowe mogą być binarne.

Przykład #1 base64_decode() przykład

<?php
  $str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
  echo base64_decode($str);
  ?>

Ten przykład wygeneruje:

  This is an encoded string

Patrz także: base64_encode(), » RFC 2045 sekcja 6.8.

URL Funkcje
base64_encode
URL Funkcje


Koduje dane za pomocą algorytmu MIME base64

base64_decode
get_headers
URL Funkcje
PHP Manual

base64_encode

(PHP 4, PHP 5)

base64_encode — Koduje dane za pomocą algorytmu MIME base64

Opis

string base64_encode ( string $dane )

base64_encode() zwraca dane zakodowane za pomocą algorytmu base64. Ten sposób kodowania został zaprojektowany, aby móc bezpiecznie przesyłać dane binarne, poprzez warstwy transportujące nie zaprojektowane do obsługi 8 bitowego przesyłania informacji, np. treść emaili.

Dane zakodowane tą funkcją zajmują ok 33% więcej miejsca niż dane oryginalne.

Przykład #1 base64_encode() przykład

<?php
    $str = 'This is an encoded string';
    echo base64_encode($str);
  ?>

Ten przykład wygeneruje:

  VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

   Patrz także
   base64_decode(),
   chunk_split(),
convert_uuencode() i
   » RFC 2045 sekcja 6.8.

base64_decode
get_headers
URL Funkcje


Fetches all the headers sent by the server in response to a HTTP request

base64_encode
get_meta_tags
URL Funkcje
PHP Manual

get_headers

(PHP 5)

get_headers — Fetches all the headers sent by the server in response to a HTTP request

Opis

array get_headers ( string $url [, int $format = 0 ] )

get_headers() returns an array with the headers sent by the server in response to a HTTP request.

Parametry

url

The target URL.

format

If the optional format parameter is set to non-zero, get_headers() parses the response and sets the array's keys.

Zwracane wartości

Returns an indexed or associative array with the headers, or FALSE on failure.

Rejestr zmian

Wersja | Opis
5.1.3 | This function now uses the default stream context, which can be set/changed with the stream_context_set_default() function.

Przykłady

Przykład #1 get_headers() example

<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

Przykład #2 get_headers() using HEAD example

<?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
$headers = get_headers('http://example.com');
?>

Zobacz też:

  • apache_request_headers() - Fetch all HTTP request headers

base64_encode
get_meta_tags
URL Funkcje


Extracts all meta tag content attributes from a file and returns an array

get_headers
http_build_query
URL Funkcje
PHP Manual

get_meta_tags

(PHP 4, PHP 5)

get_meta_tags — Extracts all meta tag content attributes from a file and returns an array

Opis

array get_meta_tags ( string $filename [, bool $use_include_path = false ] )

Opens filename and parses it line by line for <meta> tags in the file. The parsing stops at </head>.

Parametry

filename

The path to the HTML file, as a string. This can be a local file or an URL.

Przykład #1 What get_meta_tags() parses

<meta name="author" content="name">
<meta name="keywords" content="php documentation">
<meta name="DESCRIPTION" content="a php manual">
<meta name="geo.position" content="49.33;-86.59">
</head> <!-- parsing stops here -->
(pay attention to line endings - PHP uses a native function to parse the input, so a Mac file won't work on Unix).

use_include_path

Setting use_include_path to TRUE will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.

Zwracane wartości

Returns an array with all the parsed meta tags.

The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case. If two meta tags have the same name, only the last one is returned.

Rejestr zmian

Wersja | Opis
4.0.5 | Support for unquoted HTML attributes was added.

Przykłady

Przykład #2 What get_meta_tags() returns

<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>

Notatki

Informacja:

Only meta tags with name attributes will be parsed.

Zobacz też:

  • htmlentities() - Convert all applicable characters to HTML entities
  • urlencode() - Koduje łańcuch metodą kodowania URLi

get_headers
http_build_query
URL Funkcje


Generate URL-encoded query string

get_meta_tags
parse_url
URL Funkcje
PHP Manual

http_build_query

(PHP 5)

http_build_query — Generate URL-encoded query string

Opis

string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

Generates a URL-encoded query string from the associative (or indexed) array provided.

Parametry

query_data

May be an array or object containing properties.

If query_data is an array, it may be a simple one-dimensional structure, or an array of arrays (which in turn may contain other arrays).

If query_data is an object, then only public properties will be incorporated into the result.

numeric_prefix

If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only.

This is meant to allow for legal variable names when the data is decoded by PHP or another CGI application later on.

arg_separator

arg_separator.output is used to separate arguments, unless this parameter is specified, and is then used.

enc_type

By default, PHP_QUERY_RFC1738.

If enc_type is PHP_QUERY_RFC1738, then encoding is performed per » RFC 1738 and the application/x-www-form-urlencoded media type, which implies that spaces are encoded as plus (+) signs.

If enc_type is PHP_QUERY_RFC3986, then encoding is performed according to » RFC 3986, and spaces will be percent encoded (%20).

Zwracane wartości

Returns a URL-encoded string.

Rejestr zmian

Wersja | Opis
5.4.0 | The enc_type parameter was added.
5.1.3 | Square brackets are escaped.
5.1.2 | The arg_separator parameter was added.

Przykłady

Przykład #1 Simple usage of http_build_query()

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&amp;');

?>

Powyższy przykład wyświetli:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

Przykład #2 http_build_query() with numerically index elements.

<?php
$data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' =>'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, 'myvar_');
?>

Powyższy przykład wyświetli:

0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor

Przykład #3 http_build_query() with complex arrays

<?php
$data = array('user'=>array('name'=>'Bob Smith',
                            'age'=>47,
                            'sex'=>'M',
                            'dob'=>'5/12/1956'),
              'pastimes'=>array('golf', 'opera', 'poker', 'rap'),
              'children'=>array('bobby'=>array('age'=>12,
                                               'sex'=>'M'),
                                'sally'=>array('age'=>8,
                                               'sex'=>'F')),
              'CEO');

echo http_build_query($data, 'flags_');
?>

this will output : (word wrapped for readability)

user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M&
user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera&
pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12&
children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8&
children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO

Informacja:

Only the numerically indexed element in the base array "CEO" received a prefix. The other numeric indices, found under pastimes, do not require a string prefix to be legal variable names.

Przykład #4 Using http_build_query() with an object

<?php
class parentClass {
    public    $pub      = 'publicParent';
    protected $prot     = 'protectedParent';
    private   $priv     = 'privateParent';
    public    $pub_bar  = Null;
    protected $prot_bar = Null;
    private   $priv_bar = Null;

    public function __construct(){
        $this->pub_bar  = new childClass();
        $this->prot_bar = new childClass();
        $this->priv_bar = new childClass();
    }
}

class childClass {
    public    $pub  = 'publicChild';
    protected $prot = 'protectedChild';
    private   $priv = 'privateChild';
}

$parent = new parentClass();

echo http_build_query($parent);
?>

Powyższy przykład wyświetli:

pub=publicParent&pub_bar%5Bpub%5D=publicChild

Zobacz też:

  • parse_str() - Parses the string into variables
  • parse_url() - Przetwarza adres URL i zwraca jego składowe
  • urlencode() - Koduje łańcuch metodą kodowania URLi
  • array_walk() - Zastosuj funkcję użytkownika do każdego elementu tablicy

get_meta_tags
parse_url
URL Funkcje


Przetwarza adres URL i zwraca jego składowe

http_build_query
rawurldecode
URL Funkcje
PHP Manual

parse_url

(PHP 4, PHP 5)

parse_url — Przetwarza adres URL i zwraca jego składowe

Opis

mixed parse_url ( string $url [, int $składnik ] )

Funkcja przetwarza URL i zwraca tablicę asocjacyjną zawierającą każdy z komponentów wchodzących w skład URL.

Ta funkcja nie służy do sprawdzania poprawności podanego URL, tylko rozbija go na podane niżej części. Częściowe URLe także są obsługiwane parse_url() postara się przetworzyć je poprawnie.

Parametry

url

Adres URL do przetworzenia

składnik

Podaj jedną ze stałych PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT aby otrzymać określony składnik URL jako string.

Zwracane wartości

W przypadku poważnie zdeformowanych URLi, parse_url() może zwrócić FALSE i wyemitować E_WARNING. W przeciwnym wypadku zostanie zwrócona asocjatywna tablica, której składowe mogą być następujące (wystąpi przynajmnej jedena):

  • scheme (protokół) - np. http
  • host
  • port
  • user (użytkownik)
  • pass (hasło)
  • path (ścieżka)
  • query (zapytanie) - po znaku ?
  • fragment - po znaku #

Jeśli parametr składnik jest określony, zwracany jest string zamiast array.

Rejestr zmian

Wersja | Opis
5.1.2 | Dodano parametr składnik

Przykłady

Przykład #1 A parse_url() przykład

<?php
$url = 'http://uzytkownik:haslo@serwer/sciezka?arg=wartosc#kotwica';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

Powyższy przykład wyświetli:

Array
(
    [scheme] => http
    [host] => serwer
    [user] => uzytkownik
    [pass] => haslo
    [path] => /sciezka
    [query] => arg=wartosc
    [fragment] => kotwica
)
/sciezka

Notatki

Informacja:

Funkcja nie działa na relatywnych URLach.

Informacja:

Ta funkcja jest przeznaczona do przetwarzania URLi, a nie URI. Jednakże, aby zastosować wymóg wstecznej kompatybilności PHP, zrobiono wyjątek dla protokołu file:// gdzie potrójne ukośniki (file:///...) są dozwolone. Dla innych protokołów jest to nieprawidłowe.

Zobacz też:

  • pathinfo() - Zwraca informacje o ścieżce do pliku
  • parse_str() - Parses the string into variables
  • http_build_query() - Generate URL-encoded query string
  • dirname() - Zwraca nazwę katalogu, będącego składową ścieżki
  • basename() - Zwraca nazwę pliku, będącego składową ścieżki

http_build_query
rawurldecode
URL Funkcje


Dekoduje łańcuchy zakodowane metodą kodowania URL'i

parse_url
rawurlencode
URL Funkcje
PHP Manual

rawurldecode

(PHP 4, PHP 5)

rawurldecode — Dekoduje łańcuchy zakodowane metodą kodowania URL'i

Opis

string rawurldecode ( string $str )

Zwraca łańcuch w którym sekwencje dwóch cyfr szesnastkowych poprzedzone znakiem procenta (%), zastąpione są przez ich odpowiednik znakowy.

Parametry

str

URL do zdekodowania.

Zwracane wartości

Zwraca zdekodowany URL jako łańcuch znaków.

Przykłady

Przykład #1 rawurldecode() przykład

<?php

echo rawurldecode('foo%20bar%40baz'); // foo bar@baz

?>

Notatki

Informacja:

rawurldecode() nie zmienia symbolu plus ('+') na spację. Robi to urldecode().

Zobacz też:

  • rawurlencode() - Koduje URL'e zgodnie z RFC 1738
  • urldecode() - Dekoduje łańcuchy zakodowane metodą kodowania URL'i
  • urlencode() - Koduje łańcuch metodą kodowania URLi

parse_url
rawurlencode
URL Funkcje


Koduje URL'e zgodnie z RFC 1738

rawurldecode
urldecode
URL Funkcje
PHP Manual

rawurlencode

(PHP 4, PHP 5)

rawurlencode — Koduje URL'e zgodnie z RFC 1738

Opis

string rawurlencode ( string $str )

Zwraca łańcuch w którym wszystkie nie alfanumeryczne znaki z wyjątkiem -_. zostały zastąpione przez dwie cyfry szesnastkowe poprzedzone znakiem procenta (%). Ten sposób kodowania został opisany w RFC 1738. Zabezpiecza dane wejściowe przed zinterpretowaniem ich jako znaki specjalne URL'a oraz zabezpiecza URL'e przed zniekształceniem ich podczas konwersji znaków dokonywanych przez media transmisyjne (np. niektóre systemy pocztowe). Na przykład, jeśli chcesz dołączyć hasło do URL'a FTP:

Przykład #1 rawurlencode() przykład 1

<?php
echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
     '@ftp.example.com/x.txt">';
?>

Lub, jeśli podajesz informację w części PATH_INFO (ścieżka) URL'a:

Przykład #2 rawurlencode() przykład 2

<?php
echo '<a href="http://example.com/department_list_script/',
    rawurlencode('sales and marketing/Miami'), '">';
?>

Patrz także: rawurldecode(),
urldecode(),
urlencode() i
» RFC 1738.

rawurldecode
urldecode
URL Funkcje


Dekoduje łańcuchy zakodowane metodą kodowania URL'i

rawurlencode
urlencode
URL Funkcje
PHP Manual

urldecode

(PHP 4, PHP 5)

urldecode — Dekoduje łańcuchy zakodowane metodą kodowania URL'i

Opis

string urldecode ( string $str )

Odkodowuje każdy %## kod z danego łańcucha. Zwracany jest zdekodowany łańcuch.

Przykład #1 urldecode() przykład

<?php
$a = explode('&', $QUERY_STRING);
$i = 0;
while ($i < count($a)) {
    $b = split('=', $a[$i]);
    echo 'Wartość parametru ', htmlspecialchars(urldecode($b[0])),
         ' wynosi ', htmlspecialchars(urldecode($b[1])), "<br />\n";
    $i++;
}
?>

Patrz także: urlencode(),
rawurlencode() i
rawurldecode().

rawurlencode
urlencode
URL Funkcje


Koduje łańcuch metodą kodowania URLi

urldecode
V8js
URL Funkcje
PHP Manual

urlencode

(PHP 4, PHP 5)

urlencode — Koduje łańcuch metodą kodowania URLi

Opis

string urlencode ( string $str )

Zwraca łańcuch w którym wszystkie nie alfanumeryczne znaki z wyjątkiem

-_.
zostały zastąpione przez dwie cyfry szesnastkowe poprzedzone znakiem procenta (%), a spacje kodowane są jako znak (+). To kodowanie jest takie same jak wykorzystywane przy przesyłaniu danych z formularzy WWW, tj. takie samo jak w media typie: application/x-www-form-urlencoded. Różni się od kodowania z RFC1738 (zobacz rawurlencode()) tym, że z powodów historycznych, spacje są kodowane jako znak plus (+). Funkcja ta jest odpowiednia do zakodowania łańcucha używanego w zapytaniu URL oraz jako zmienna przekazywana do następnej strony:

Przykład #1 urlencode() przykład

<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>

Notka: Uważaj na zmienne, które mogą zawierać HTML'owe encje. Rzeczy jak &amp, &copy i &pound są przetwarzane przez przeglądarkę i ich aktualna postać jest używana dalej zamiast porządanej nazwy zmiennej. To jest oczywisty problem, o którym W3C informuje ludzi od lat. Referencje są tutaj: » http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2. PHP obsługuje zmianę separatora argumentów na zalecany przez W3C średnik poprzez dyrektywę arg_separator .ini. Niestety większość przeglądarek nie wysyła danych z formularza w formacie używającym średnik jako separator. Bardziej przenośnym rozwiązaniem jest użycie &amp; jako separatora zamiast &. Nie musisz zmieniać PHP'owego arg_separator aby to uzyskać. Zostaw separator jako &, ale koduj swoje URL'e używając htmlentities()lub htmlspecialchars().

Przykład #2 urlencode() i htmlentities() przykład

<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>

Patrz także: urldecode(),
htmlentities(),
rawurldecode() i
rawurlencode().

urldecode
V8js
URL Funkcje


V8 Javascript Engine Integration

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Przykłady
  • V8Js — The V8Js class
    • V8Js::__construct — Construct a new V8Js object
    • V8Js::executeString — Execute a string as Javascript code
    • V8Js::getExtensions — Return an array of registered extensions
    • V8Js::getPendingException — Return pending uncaught Javascript exception
    • V8Js::registerExtension — Register Javascript extensions for V8Js
  • V8JsException — The V8JsException class
    • V8JsException::getJsFileName — The getJsFileName purpose
    • V8JsException::getJsLineNumber — The getJsLineNumber purpose
    • V8JsException::getJsSourceLine — The getJsSourceLine purpose
    • V8JsException::getJsTrace — The getJsTrace purpose
urlencode
Wstęp
Inne podstawowe rozszerzenia


Wstęp

This extension embeds the » V8 Javascript Engine into PHP.

V8js
Instalacja/Konfiguracja
V8js


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
V8js


Wymagania

PHP 5.3.3+ and V8 library and headers installed in proper paths.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/v8js

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

V8js Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
v8js.max_disposed_contexts | 25 | PHP_INI_ALL |
v8js.flags |  | PHP_INI_ALL |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

v8js.max_disposed_contexts integer

Sets limit for disposed contexts before forcing V8 to do garbage collection.

v8js.flags string

Sets V8 command line flags. The list of available flags can be obtained in CLI mode by setting this parameter to --help. Example:

$ php -r 'ini_set("v8js.flags", "--help"); new V8Js;' | less

Informacja:

For these flags to be effective in runtime the ini_set() call has to be done before any V8Js objects are instantiated!

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Przykłady

Basic usage

Przykład #1 Basic Javascript execution

<?php

$v8 = new V8Js();

/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;

try {
  var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
  var_dump($e);
}

?>

Powyższy przykład wyświetli:

Hello World!
int(13)
Typy zasobów
V8Js
V8js


The V8Js class

(No version information available, might only be in SVN)

Wstęp

This is the core class for V8Js extension. Each instance created from this class has own context in which all Javascript is compiled and executed.

See V8Js::__construct() for more information.

Krótki opis klasy

V8Js {
/* Constants */
const string V8_VERSION ;
const integer FLAG_NONE = 1 ;
const integer FLAG_FORCE_ARRAY = 2 ;
/* Methods */
public __construct ([ string $object_name = "PHP" [, array $variables = array() [, array $extensions = array() [, bool $report_uncaught_exceptions = TRUE ]]]] )
public mixed executeString ( string $script [, string $identifier = "V8Js::executeString()" [, int $flags = V8Js::FLAG_NONE ]] )
public static array getExtensions ( void )
public V8JsException getPendingException ( void )
public static bool registerExtension ( string $extension_name , string $script [, array $dependencies = array() [, bool $auto_enable = FALSE ]] )
}

Stałe predefiniowane

V8Js::V8_VERSION

The V8 Javascript Engine version.

V8Js::FLAG_NONE

No flags.

V8Js::FLAG_FORCE_ARRAY

Forces all JS objects to be associative arrays in PHP.

Spis treści

  • V8Js::__construct — Construct a new V8Js object
  • V8Js::executeString — Execute a string as Javascript code
  • V8Js::getExtensions — Return an array of registered extensions
  • V8Js::getPendingException — Return pending uncaught Javascript exception
  • V8Js::registerExtension — Register Javascript extensions for V8Js
Przykłady
V8Js::__construct
V8js


Construct a new V8Js object

V8Js
V8Js::executeString
V8Js
PHP Manual

V8Js::__construct

(PECL v8js >= 0.1.0)

V8Js::__construct — Construct a new V8Js object

Opis

 public  V8Js::__construct
  ([ string $object_name = "PHP"
 [, array $variables = array()
 [, array $extensions = array()
 [, bool $report_uncaught_exceptions = TRUE
]]]] )

Constructs a new V8Js object.

Parametry

object_name

The name of the object passed to Javascript. Defaults to PHP.

variables

Map of PHP variables that will be available in Javascript. Must be an associative array in format array("name-for-js" => "name-of-php-variable"). Defaults to empty array.

extensions

List of extensions registered using V8Js::registerExtension() which should be available in the Javascript context of the created V8Js object.

Informacja:

Extensions registered to be enabled automatically do not need to be listed in this array. Also if an extension has dependencies, those dependencies can be omitted as well. Defaults to empty array.

report_uncaught_exceptions

Controls whether uncaught Javascript exceptions are reported immediately or not. Defaults to TRUE. If set to FALSE the uncaught exception can be accessed using V8Js::getPendingException().

Zwracane wartości

Returns a new V8Js context object.

V8Js
V8Js::executeString
V8Js


Execute a string as Javascript code

V8Js::__construct
V8Js::getExtensions
V8Js
PHP Manual

V8Js::executeString

(PECL v8js >= 0.1.0)

V8Js::executeString — Execute a string as Javascript code

Opis

public mixed V8Js::executeString ( string $script [, string $identifier = "V8Js::executeString()" [, int $flags = V8Js::FLAG_NONE ]] )

Compiles and executes the string passed with script as Javascript code.

Parametry

script

The code string to be executed.

identifier

Identifier string for the executed code. Used for debugging.

flags

Execution flags. This value must be one of the V8Js::FLAG_* constants, defaulting to V8Js::FLAG_NONE.

  • V8Js::FLAG_NONE: no flags

  • V8Js::FLAG_FORCE_ARRAY: forces all Javascript objects passed to PHP to be associative arrays

Zwracane wartości

Returns the last variable instantiated in the Javascript code converted to matching PHP variable type.

V8Js::__construct
V8Js::getExtensions
V8Js


Return an array of registered extensions

V8Js::executeString
V8Js::getPendingException
V8Js
PHP Manual

V8Js::getExtensions

(PECL v8js >= 0.1.0)

V8Js::getExtensions — Return an array of registered extensions

Opis

public static array V8Js::getExtensions ( void )

This function returns array of Javascript extensions registered using V8Js::registerExtension().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array of registered extensions or an empty array if there are none.

V8Js::executeString
V8Js::getPendingException
V8Js


Return pending uncaught Javascript exception

V8Js::getExtensions
V8Js::registerExtension
V8Js
PHP Manual

V8Js::getPendingException

(PECL v8js >= 0.1.0)

V8Js::getPendingException — Return pending uncaught Javascript exception

Opis

public V8JsException V8Js::getPendingException ( void )

Returns any pending uncaught Javascript exception as V8JsException left from earlier V8Js::executeString() call(s).

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Either V8JsException or NULL.

V8Js::getExtensions
V8Js::registerExtension
V8Js


Register Javascript extensions for V8Js

V8Js::getPendingException
V8JsException
V8Js
PHP Manual

V8Js::registerExtension

(PECL v8js >= 0.1.0)

V8Js::registerExtension — Register Javascript extensions for V8Js

Opis

public static bool V8Js::registerExtension ( string $extension_name , string $script [, array $dependencies = array() [, bool $auto_enable = FALSE ]] )

Registers passed Javascript script as extension to be used in V8Js contexts.

Parametry

extension_name

Name of the extension to be registered.

script

The Javascript code to be registered.

dependencies

Array of extension names the extension to be registered depends on. Any such extension is enabled automatically when this extension is loaded.

Informacja:

All extensions, including the dependencies, must be registered before any V8Js are created which use them.

auto_enable

If set to TRUE, the extension will be enabled automatically in all V8Js contexts. Defaults to FALSE.

Zwracane wartości

Returns TRUE if extension was registered succesfully, FALSE otherwise.

V8Js::getPendingException
V8JsException
V8Js


The V8JsException class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

V8JsException extends Exception {
/* Properties */
protected $JsFileName ;
protected $JsLineNumber ;
protected $JsSourceLine ;
protected $JsTrace ;
/* Methods */
final public string getJsFileName ( void )
final public int getJsLineNumber ( void )
final public int getJsSourceLine ( void )
final public string getJsTrace ( void )
/* Inherited methods */
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

message

code

file

line

JsFileName

JsLineNumber

JsSourceLine

JsTrace

Spis treści

  • V8JsException::getJsFileName — The getJsFileName purpose
  • V8JsException::getJsLineNumber — The getJsLineNumber purpose
  • V8JsException::getJsSourceLine — The getJsSourceLine purpose
  • V8JsException::getJsTrace — The getJsTrace purpose
V8Js::registerExtension
V8JsException::getJsFileName
V8js


The getJsFileName purpose

V8JsException
V8JsException::getJsLineNumber
V8JsException
PHP Manual

V8JsException::getJsFileName

(PECL v8js >= 0.1.0)

V8JsException::getJsFileName — The getJsFileName purpose

Opis

final public string V8JsException::getJsFileName ( 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

V8JsException
V8JsException::getJsLineNumber
V8JsException


The getJsLineNumber purpose

V8JsException::getJsFileName
V8JsException::getJsSourceLine
V8JsException
PHP Manual

V8JsException::getJsLineNumber

(PECL v8js >= 0.1.0)

V8JsException::getJsLineNumber — The getJsLineNumber purpose

Opis

final public int V8JsException::getJsLineNumber ( 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

V8JsException::getJsFileName
V8JsException::getJsSourceLine
V8JsException


The getJsSourceLine purpose

V8JsException::getJsLineNumber
V8JsException::getJsTrace
V8JsException
PHP Manual

V8JsException::getJsSourceLine

(PECL v8js >= 0.1.0)

V8JsException::getJsSourceLine — The getJsSourceLine purpose

Opis

final public int V8JsException::getJsSourceLine ( 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

V8JsException::getJsLineNumber
V8JsException::getJsTrace
V8JsException


The getJsTrace purpose

V8JsException::getJsSourceLine
Yaml
V8JsException
PHP Manual

V8JsException::getJsTrace

(PECL v8js >= 0.1.0)

V8JsException::getJsTrace — The getJsTrace purpose

Opis

final public string V8JsException::getJsTrace ( 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

V8JsException::getJsSourceLine
Yaml
V8JsException


YAML Data Serialization

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Yaml Funkcje
    • yaml_emit_file — Send the YAML representation of a value to a file
    • yaml_emit — Returns the YAML representation of a value
    • yaml_parse_file — Parse a YAML stream from a file
    • yaml_parse_url — Parse a Yaml stream from a URL
    • yaml_parse — Parse a YAML stream
V8JsException::getJsTrace
Wstęp
Inne podstawowe rozszerzenia


Wstęp

This extension implements the » YAML Ain't Markup Language (YAML) data serialization standard. Parsing and emiting are handled by the » LibYAML library.

Yaml
Instalacja/Konfiguracja
Yaml


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Yaml


Wymagania

This extension requires the » LibYAML C library version 0.1.0 or higher to be installed.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/yaml.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Yaml Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
yaml.decode_binary | 0 | PHP_INI_ALL |
yaml.decode_timestamp | 0 | PHP_INI_ALL |
yaml.output_canonical | 0 | PHP_INI_ALL |
yaml.output_indent | 2 | PHP_INI_ALL |
yaml.output_width | 80 | PHP_INI_ALL |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

yaml.decode_binary boolean

Off by default, but can be set to on to cause base64 binary encoded entities which have the explicit tag "tag:yaml.org,2002:binary" to be decoded.

yaml.decode_timestamp integer

Controls the decoding of both implicit and explict "tag:yaml.org,2002:timestamp" scalars in the YAML document stream. The default setting of 0 will not apply any decoding. A setting of 1 will use strtotime() to parse the timestamp value as a Unix timestamp. A setting of 2 will use date_create() to parse the timestamp value as DateTime object.

yaml.output_canonical boolean

Off by default, but can be set to on to cause canonical form output.

yaml.output_indent integer

Number of spaces to indent sections. Value should be between 1 and 10.

yaml.output_width integer

Set the preferred line width. -1 means unlimited.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

Scalar entity styles usable by yaml_parse() callback methods.
YAML_ANY_SCALAR_STYLE (integer)
YAML_PLAIN_SCALAR_STYLE (integer)
YAML_SINGLE_QUOTED_SCALAR_STYLE (integer)
YAML_DOUBLE_QUOTED_SCALAR_STYLE (integer)
YAML_LITERAL_SCALAR_STYLE (integer)
YAML_FOLDED_SCALAR_STYLE (integer)
Common tags usable by yaml_parse() callback methods.
YAML_NULL_TAG (string)
"tag:yaml.org,2002:null"
YAML_BOOL_TAG (string)
"tag:yaml.org,2002:bool"
YAML_STR_TAG (string)
"tag:yaml.org,2002:str"
YAML_INT_TAG (string)
"tag:yaml.org,2002:int"
YAML_FLOAT_TAG (string)
"tag:yaml.org,2002:float"
YAML_TIMESTAMP_TAG (string)
"tag:yaml.org,2002:timestamp"
YAML_SEQ_TAG (string)
"tag:yaml.org,2002:seq"
YAML_MAP_TAG (string)
"tag:yaml.org,2002:map"
YAML_PHP_TAG (string)
"!php/object"
Encoding types for yaml_emit()
YAML_ANY_ENCODING (integer)
Let the emitter choose an encoding.
YAML_UTF8_ENCODING (integer)
Encode as UTF8.
YAML_UTF16LE_ENCODING (integer)
Encode as UTF16LE.
YAML_UTF16BE_ENCODING (integer)
Encode as UTF16BE.
Linebreak types for yaml_emit()
YAML_ANY_BREAK (integer)
Let emitter choose linebreak character.
YAML_CR_BREAK (integer)
Use \r as break character (Mac style).
YAML_LN_BREAK (integer)
Use \n as break character (Unix style).
YAML_CRLN_BREAK (integer)
Use \r\n as break character (DOS style).
Typy zasobów
Przykłady
Yaml


Przykłady

Przykład #1 Yaml Example

<?php
$addr = array(
    "given" => "Chris",
    "family"=> "Dumars",
    "address"=> array(
        "lines"=> "458 Walkman Dr.
        Suite #292",
        "city"=> "Royal Oak",
        "state"=> "MI",
        "postal"=> 48046,
      ),
  );
$invoice = array (
    "invoice"=> 34843,
    "date"=> "2001-01-23",
    "bill-to"=> $addr,
    "ship-to"=> $addr,
    "product"=> array(
        array(
            "sku"=> "BL394D",
            "quantity"=> 4,
            "description"=> "Basketball",
            "price"=> 450,
          ),
        array(
            "sku"=> "BL4438H",
            "quantity"=> 1,
            "description"=> "Super Hoop",
            "price"=> 2392,
          ),
      ),
    "tax"=> 251.42,
    "total"=> 4443.52,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
    );

// generate a YAML representation of the invoice
$yaml = yaml_emit($invoice);
var_dump($yaml);

// convert the YAML back into a PHP variable
$parsed = yaml_parse($yaml);

// check that roundtrip conversion produced an equivalent structure
var_dump($parsed == $invoice);
?>

Powyższy przykład wyświetli coś podobnego do:

string(631) "---
invoice: 34843
date: "2001-01-23"
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"
bool(true)
Stałe predefiniowane
Yaml Funkcje
Yaml


Yaml Funkcje

Spis treści

  • yaml_emit_file — Send the YAML representation of a value to a file
  • yaml_emit — Returns the YAML representation of a value
  • yaml_parse_file — Parse a YAML stream from a file
  • yaml_parse_url — Parse a Yaml stream from a URL
  • yaml_parse — Parse a YAML stream
Przykłady
yaml_emit_file
Yaml


Send the YAML representation of a value to a file

Yaml Funkcje
yaml_emit
Yaml Funkcje
PHP Manual

yaml_emit_file

(PECL yaml >= 0.5.0)

yaml_emit_file — Send the YAML representation of a value to a file

Opis

bool yaml_emit_file ( string $filename , mixed $data [, int $encoding = YAML_ANY_ENCODING [, int $linebreak = YAML_ANY_BREAK ]] )

Generate a YAML representation of the provided data in the filename.

Parametry

filename

Path to the file.

data

The data being encoded. Can be any type except a resource.

encoding

Output character encoding chosen from YAML_ANY_ENCODING, YAML_UTF8_ENCODING, YAML_UTF16LE_ENCODING, YAML_UTF16BE_ENCODING. Defaults to YAML_ANY_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK. Defaults to YAML_ANY_BREAK.

Zwracane wartości

Returns TRUE on success.

Zobacz też:

  • yaml_emit() - Returns the YAML representation of a value
  • yaml_parse() - Parse a YAML stream

Yaml Funkcje
yaml_emit
Yaml Funkcje


Returns the YAML representation of a value

yaml_emit_file
yaml_parse_file
Yaml Funkcje
PHP Manual

yaml_emit

(PECL yaml >= 0.5.0)

yaml_emit — Returns the YAML representation of a value

Opis

string yaml_emit ( mixed $data [, int $encoding = YAML_ANY_ENCODING [, int $linebreak = YAML_ANY_BREAK ]] )

Generate a YAML representation of the provided data.

Parametry

data

The data being encoded. Can be any type except a resource.

encoding

Output character encoding chosen from YAML_ANY_ENCODING, YAML_UTF8_ENCODING, YAML_UTF16LE_ENCODING, YAML_UTF16BE_ENCODING. Defaults to YAML_ANY_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK. Defaults to YAML_ANY_BREAK.

Zwracane wartości

Returns a YAML encoded string on success.

Przykłady

Przykład #1 yaml_emit() example

<?php
$addr = array(
    "given" => "Chris",
    "family"=> "Dumars",
    "address"=> array(
        "lines"=> "458 Walkman Dr.
        Suite #292",
        "city"=> "Royal Oak",
        "state"=> "MI",
        "postal"=> 48046,
      ),
  );
$invoice = array (
    "invoice"=> 34843,
    "date"=> 980208000,
    "bill-to"=> $addr,
    "ship-to"=> $addr,
    "product"=> array(
        array(
            "sku"=> "BL394D",
            "quantity"=> 4,
            "description"=> "Basketball",
            "price"=> 450,
          ),
        array(
            "sku"=> "BL4438H",
            "quantity"=> 1,
            "description"=> "Super Hoop",
            "price"=> 2392,
          ),
      ),
    "tax"=> 251.42,
    "total"=> 4443.52,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
  );
var_dump(yaml_emit($invoice));
?>

Powyższy przykład wyświetli coś podobnego do:

string(628) "---
invoice: 34843
date: 980208000
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"

Zobacz też:

  • yaml_emit_file() - Send the YAML representation of a value to a file
  • yaml_parse() - Parse a YAML stream

yaml_emit_file
yaml_parse_file
Yaml Funkcje


Parse a YAML stream from a file

yaml_emit
yaml_parse_url
Yaml Funkcje
PHP Manual

yaml_parse_file

(PECL yaml >= 0.4.0)

yaml_parse_file — Parse a YAML stream from a file

Opis

mixed yaml_parse_file ( string $filename [, int $pos = 0 [, int &$ndocs [, array $callbacks ]]] )

Convert all or part of a YAML document stream read from a file to a PHP variable.

Parametry

filename

Path to the file.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callback mappings.

Zwracane wartości

Returns the value encoded in input in appropriate PHP type lub FALSE w przypadku niepowodzenia. If pos is -1 an array will be returned with one entry for each document found in the stream.

Zobacz też:

  • yaml_parse() - Parse a YAML stream
  • yaml_parse_url() - Parse a Yaml stream from a URL
  • yaml_emit() - Returns the YAML representation of a value

yaml_emit
yaml_parse_url
Yaml Funkcje


Parse a Yaml stream from a URL

yaml_parse_file
yaml_parse
Yaml Funkcje
PHP Manual

yaml_parse_url

(PECL yaml >= 0.4.0)

yaml_parse_url — Parse a Yaml stream from a URL

Opis

mixed yaml_parse_url ( string $url [, int $pos = 0 [, int &$ndocs [, array $callbacks ]]] )

Convert all or part of a YAML document stream read from a URL to a PHP variable.

Parametry

url

url should be of the form "scheme://...". PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callback mappings.

Zwracane wartości

Returns the value encoded in input in appropriate PHP type lub FALSE w przypadku niepowodzenia. If pos is -1 an array will be returned with one entry for each document found in the stream.

Zobacz też:

  • yaml_parse() - Parse a YAML stream
  • yaml_parse_file() - Parse a YAML stream from a file
  • yaml_emit() - Returns the YAML representation of a value

yaml_parse_file
yaml_parse
Yaml Funkcje


Parse a YAML stream

yaml_parse_url
Yaf
Yaml Funkcje
PHP Manual

yaml_parse

(PECL yaml >= 0.4.0)

yaml_parse — Parse a YAML stream

Opis

mixed yaml_parse ( string $input [, int $pos = 0 [, int &$ndocs [, array $callbacks ]]] )

Convert all or part of a YAML document stream to a PHP variable.

Parametry

input

The string to parse as a YAML document stream.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callback mappings.

Zwracane wartości

Returns the value encoded in input in appropriate PHP type lub FALSE w przypadku niepowodzenia. If pos is -1 an array will be returned with one entry for each document found in the stream.

Przykłady

Przykład #1 yaml_parse() example

<?php
$yaml = <<<EOD
---
invoice: 34843
date: "2001-01-23"
bill-to: &id001
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to: *id001
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
EOD;

$parsed = yaml_parse($yaml);
var_dump($parsed);
?>

Powyższy przykład wyświetli coś podobnego do:

array(8) {
  ["invoice"]=>
  int(34843)
  ["date"]=>
  string(10) "2001-01-23"
  ["bill-to"]=>
  &array(3) {
    ["given"]=>
    string(5) "Chris"
    ["family"]=>
    string(6) "Dumars"
    ["address"]=>
    array(4) {
      ["lines"]=>
      string(34) "458 Walkman Dr.
        Suite #292"
      ["city"]=>
      string(9) "Royal Oak"
      ["state"]=>
      string(2) "MI"
      ["postal"]=>
      int(48046)
    }
  }
  ["ship-to"]=>
  &array(3) {
    ["given"]=>
    string(5) "Chris"
    ["family"]=>
    string(6) "Dumars"
    ["address"]=>
    array(4) {
      ["lines"]=>
      string(34) "458 Walkman Dr.
        Suite #292"
      ["city"]=>
      string(9) "Royal Oak"
      ["state"]=>
      string(2) "MI"
      ["postal"]=>
      int(48046)
    }
  }
  ["product"]=>
  array(2) {
    [0]=>
    array(4) {
      ["sku"]=>
      string(6) "BL394D"
      ["quantity"]=>
      int(4)
      ["description"]=>
      string(10) "Basketball"
      ["price"]=>
      int(450)
    }
    [1]=>
    array(4) {
      ["sku"]=>
      string(7) "BL4438H"
      ["quantity"]=>
      int(1)
      ["description"]=>
      string(10) "Super Hoop"
      ["price"]=>
      int(2392)
    }
  }
  ["tax"]=>
  float(251.42)
  ["total"]=>
  float(4443.52)
  ["comments"]=>
  string(68) "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338."
}

Zobacz też:

  • yaml_parse_file() - Parse a YAML stream from a file
  • yaml_parse_url() - Parse a Yaml stream from a URL
  • yaml_emit() - Returns the YAML representation of a value

yaml_parse_url
Yaf
Yaml Funkcje


Yaf

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Application Configuration
  • Yaf_Application — The Yaf_Application class
    • Yaf_Application::app — Retrive an Application instance
    • Yaf_Application::bootstrap — Call bootstrap
    • Yaf_Application::clearLastError — Clear the last error info
    • Yaf_Application::__clone — Yaf_Application can not be cloned
    • Yaf_Application::__construct — Yaf_Application constructor
    • Yaf_Application::__destruct — The __destruct purpose
    • Yaf_Application::environ — Retrive environ
    • Yaf_Application::execute — Execute a callback
    • Yaf_Application::getAppDirectory — Get the application directory
    • Yaf_Application::getConfig — Retrive the config instance
    • Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance
    • Yaf_Application::getLastErrorMsg — Get message of the last occurred error
    • Yaf_Application::getLastErrorNo — Get code of last occurred error
    • Yaf_Application::getModules — Get defined module names
    • Yaf_Application::run — Start Yaf_Application
    • Yaf_Application::setAppDirectory — Change the application directory
    • Yaf_Application::__sleep — Yaf_Application can not be serialized
    • Yaf_Application::__wakeup — Yaf_Application can not be unserialized
  • Yaf_Bootstrap_Abstract — The Yaf_Bootstrap_Abstract class
  • Yaf_Dispatcher — The Yaf_Dispatcher class
    • Yaf_Dispatcher::autoRender — Switch on/off autorendering
    • Yaf_Dispatcher::catchException — Switch on/off exception catching
    • Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned
    • Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor
    • Yaf_Dispatcher::disableView — Disable view rendering
    • Yaf_Dispatcher::dispatch — Dispatch a request
    • Yaf_Dispatcher::enableView — enable view rendering
    • Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing
    • Yaf_Dispatcher::getApplication — Retrive the application
    • Yaf_Dispatcher::getInstance — Retrive the dispatcher instance
    • Yaf_Dispatcher::getRequest — Retrive the request instance
    • Yaf_Dispatcher::getRouter — Retrive router instance
    • Yaf_Dispatcher::initView — Initialize view and return it
    • Yaf_Dispatcher::registerPlugin — Register a plugin
    • Yaf_Dispatcher::returnResponse — The returnResponse purpose
    • Yaf_Dispatcher::setAppDirectory — Change the application directory
    • Yaf_Dispatcher::setDefaultAction — Change default action name
    • Yaf_Dispatcher::setDefaultController — Change default controller name
    • Yaf_Dispatcher::setDefaultModule — Change default module name
    • Yaf_Dispatcher::setErrorHandler — The setErrorHandler purpose
    • Yaf_Dispatcher::setRequest — The setRequest purpose
    • Yaf_Dispatcher::setView — Set a custom view engine
    • Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized
    • Yaf_Dispatcher::throwException — Switch on/off exception throwing
    • Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized
  • Yaf_Config_Abstract — The Yaf_Config_Abstract class
    • Yaf_Config_Abstract::get — Getter
    • Yaf_Config_Abstract::readonly — Find a config whether readonly
    • Yaf_Config_Abstract::set — Setter
    • Yaf_Config_Abstract::toArray — Cast to array
  • Yaf_Config_Ini — The Yaf_Config_Ini class
    • Yaf_Config_Ini::__construct — The __construct purpose
    • Yaf_Config_Ini::count — The count purpose
    • Yaf_Config_Ini::current — The current purpose
    • Yaf_Config_Ini::__get — The __get purpose
    • Yaf_Config_Ini::__isset — The __isset purpose
    • Yaf_Config_Ini::key — The key purpose
    • Yaf_Config_Ini::next — The next purpose
    • Yaf_Config_Ini::offsetExists — The offsetExists purpose
    • Yaf_Config_Ini::offsetGet — The offsetGet purpose
    • Yaf_Config_Ini::offsetSet — The offsetSet purpose
    • Yaf_Config_Ini::offsetUnset — The offsetUnset purpose
    • Yaf_Config_Ini::readonly — The readonly purpose
    • Yaf_Config_Ini::rewind — The rewind purpose
    • Yaf_Config_Ini::__set — The __set purpose
    • Yaf_Config_Ini::toArray — The toArray purpose
    • Yaf_Config_Ini::valid — The valid purpose
  • Yaf_Config_Simple — The Yaf_Config_Simple class
    • Yaf_Config_Simple::__construct — The __construct purpose
    • Yaf_Config_Simple::count — The count purpose
    • Yaf_Config_Simple::current — The current purpose
    • Yaf_Config_Simple::__get — The __get purpose
    • Yaf_Config_Simple::__isset — The __isset purpose
    • Yaf_Config_Simple::key — The key purpose
    • Yaf_Config_Simple::next — The next purpose
    • Yaf_Config_Simple::offsetExists — The offsetExists purpose
    • Yaf_Config_Simple::offsetGet — The offsetGet purpose
    • Yaf_Config_Simple::offsetSet — The offsetSet purpose
    • Yaf_Config_Simple::offsetUnset — The offsetUnset purpose
    • Yaf_Config_Simple::readonly — The readonly purpose
    • Yaf_Config_Simple::rewind — The rewind purpose
    • Yaf_Config_Simple::__set — The __set purpose
    • Yaf_Config_Simple::toArray — The toArray purpose
    • Yaf_Config_Simple::valid — The valid purpose
  • Yaf_Controller_Abstract — The Yaf_Controller_Abstract class
    • Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned
    • Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor
    • Yaf_Controller_Abstract::display — The display purpose
    • Yaf_Controller_Abstract::forward — The forward purpose
    • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName — The getModuleName purpose
    • Yaf_Controller_Abstract::getRequest — The getRequest purpose
    • Yaf_Controller_Abstract::getResponse — The getResponse purpose
    • Yaf_Controller_Abstract::getView — The getView purpose
    • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
    • Yaf_Controller_Abstract::initView — The initView purpose
    • Yaf_Controller_Abstract::redirect — The redirect purpose
    • Yaf_Controller_Abstract::render — The render purpose
    • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose
  • Yaf_Action_Abstract — The Yaf_Action_Abstract class
    • Yaf_Action_Abstract::execute — Execute the action
    • Yaf_Action_Abstract::getController — get controller instance
  • Yaf_View_Interface — The Yaf_View_Interface class
    • Yaf_View_Interface::assign — Assign value to View engine
    • Yaf_View_Interface::display — Render and output a template
    • Yaf_View_Interface::getScriptPath — The getScriptPath purpose
    • Yaf_View_Interface::render — Render a template
    • Yaf_View_Interface::setScriptPath — The setScriptPath purpose
  • Yaf_View_Simple — The Yaf_View_Simple class
    • Yaf_View_Simple::assign — Assign values
    • Yaf_View_Simple::assignRef — The assignRef purpose
    • Yaf_View_Simple::__construct — The __construct purpose
    • Yaf_View_Simple::display — Render and dispaly
    • Yaf_View_Simple::__get — The __get purpose
    • Yaf_View_Simple::getScriptPath — Get template base directory
    • Yaf_View_Simple::__isset — The __isset purpose
    • Yaf_View_Simple::render — Render template
    • Yaf_View_Simple::__set — Set value to engine
    • Yaf_View_Simple::setScriptPath — Set tempalte base directory
  • Yaf_Loader — The Yaf_Loader class
    • Yaf_Loader::autoload — The autoload purpose
    • Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose
    • Yaf_Loader::__clone — The __clone purpose
    • Yaf_Loader::__construct — The __construct purpose
    • Yaf_Loader::getInstance — The getInstance purpose
    • Yaf_Loader::getLibraryPath — get the library path
    • Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose
    • Yaf_Loader::import — The import purpose
    • Yaf_Loader::isLocalName — The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace — The registerLocalNamespace purpose
    • Yaf_Loader::setLibraryPath — Change the library path
    • Yaf_Loader::__sleep — The __sleep purpose
    • Yaf_Loader::__wakeup — The __wakeup purpose
  • Yaf_Plugin_Abstract — The Yaf_Plugin_Abstract class
    • Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup — The dispatchLoopStartup purpose
    • Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse — The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup — RouterStartup hook
  • Yaf_Registry — The Yaf_Registry class
    • Yaf_Registry::__clone — The __clone purpose
    • Yaf_Registry::__construct — The __construct purpose
    • Yaf_Registry::del — The del purpose
    • Yaf_Registry::get — The get purpose
    • Yaf_Registry::has — The has purpose
    • Yaf_Registry::set — The set purpose
  • Yaf_Request_Abstract — The Yaf_Request_Abstract class
    • Yaf_Request_Abstract::getActionName — The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName — The getControllerName purpose
    • Yaf_Request_Abstract::getEnv — The getEnv purpose
    • Yaf_Request_Abstract::getException — The getException purpose
    • Yaf_Request_Abstract::getLanguage — The getLanguage purpose
    • Yaf_Request_Abstract::getMethod — The getMethod purpose
    • Yaf_Request_Abstract::getModuleName — The getModuleName purpose
    • Yaf_Request_Abstract::getParam — The getParam purpose
    • Yaf_Request_Abstract::getParams — The getParams purpose
    • Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose
    • Yaf_Request_Abstract::getServer — The getServer purpose
    • Yaf_Request_Abstract::isCli — The isCli purpose
    • Yaf_Request_Abstract::isDispatched — The isDispatched purpose
    • Yaf_Request_Abstract::isGet — The isGet purpose
    • Yaf_Request_Abstract::isHead — The isHead purpose
    • Yaf_Request_Abstract::isOptions — The isOptions purpose
    • Yaf_Request_Abstract::isPost — The isPost purpose
    • Yaf_Request_Abstract::isPut — The isPut purpose
    • Yaf_Request_Abstract::isRouted — The isRouted purpose
    • Yaf_Request_Abstract::isXmlHttpRequest — The isXmlHttpRequest purpose
    • Yaf_Request_Abstract::setActionName — The setActionName purpose
    • Yaf_Request_Abstract::setBaseUri — The setBaseUri purpose
    • Yaf_Request_Abstract::setControllerName — The setControllerName purpose
    • Yaf_Request_Abstract::setDispatched — The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName — The setModuleName purpose
    • Yaf_Request_Abstract::setParam — The setParam purpose
    • Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted — The setRouted purpose
  • Yaf_Request_Http — The Yaf_Request_Http class
    • Yaf_Request_Http::__clone — The __clone purpose
    • Yaf_Request_Http::__construct — The __construct purpose
    • Yaf_Request_Http::get — The get purpose
    • Yaf_Request_Http::getCookie — The getCookie purpose
    • Yaf_Request_Http::getFiles — The getFiles purpose
    • Yaf_Request_Http::getPost — The getPost purpose
    • Yaf_Request_Http::getQuery — fetch a query parameter
    • Yaf_Request_Http::getRequest — The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest — The isXmlHttpRequest purpose
  • Yaf_Request_Simple — The Yaf_Request_Simple class
    • Yaf_Request_Simple::__clone — The __clone purpose
    • Yaf_Request_Simple::__construct — The __construct purpose
    • Yaf_Request_Simple::get — The get purpose
    • Yaf_Request_Simple::getCookie — The getCookie purpose
    • Yaf_Request_Simple::getFiles — The getFiles purpose
    • Yaf_Request_Simple::getPost — The getPost purpose
    • Yaf_Request_Simple::getQuery — The getQuery purpose
    • Yaf_Request_Simple::getRequest — The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest — The isXmlHttpRequest purpose
  • Yaf_Response_Abstract — The Yaf_Response_Abstract class
    • Yaf_Response_Abstract::appendBody — The appendBody purpose
    • Yaf_Response_Abstract::clearBody — The clearBody purpose
    • Yaf_Response_Abstract::clearHeaders — The clearHeaders purpose
    • Yaf_Response_Abstract::__clone — The __clone purpose
    • Yaf_Response_Abstract::__construct — The __construct purpose
    • Yaf_Response_Abstract::__destruct — The __destruct purpose
    • Yaf_Response_Abstract::getBody — The getBody purpose
    • Yaf_Response_Abstract::getHeader — The getHeader purpose
    • Yaf_Response_Abstract::prependBody — The prependBody purpose
    • Yaf_Response_Abstract::response — The response purpose
    • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody — The setBody purpose
    • Yaf_Response_Abstract::setHeader — The setHeader purpose
    • Yaf_Response_Abstract::setRedirect — The setRedirect purpose
    • Yaf_Response_Abstract::__toString — The __toString purpose
  • Yaf_Route_Interface — The Yaf_Route_Interface class
    • Yaf_Route_Interface::route — route a request
  • Yaf_Route_Map — The Yaf_Route_Map class
    • Yaf_Route_Map::__construct — The __construct purpose
    • Yaf_Route_Map::route — The route purpose
  • Yaf_Route_Regex — The Yaf_Route_Regex class
    • Yaf_Route_Regex::__construct — The __construct purpose
    • Yaf_Route_Regex::route — The route purpose
  • Yaf_Route_Rewrite — The Yaf_Route_Rewrite class
    • Yaf_Route_Rewrite::__construct — The __construct purpose
    • Yaf_Route_Rewrite::route — The route purpose
  • Yaf_Router — The Yaf_Router class
    • Yaf_Router::addConfig — Add config-defined routes into Router
    • Yaf_Router::addRoute — Add new Route into Router
    • Yaf_Router::__construct — Yaf_Router constructor
    • Yaf_Router::getCurrentRoute — Get the effective route name
    • Yaf_Router::getRoute — The getRoute purpose
    • Yaf_Router::getRoutes — The getRoutes purpose
    • Yaf_Router::route — The route purpose
  • Yaf_Route_Simple — The Yaf_Route_Simple class
    • Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor
    • Yaf_Route_Simple::route — Route a request
  • Yaf_Route_Static — The Yaf_Route_Static class
    • Yaf_Route_Static::match — The match purpose
    • Yaf_Route_Static::route — Route a request
  • Yaf_Route_Supervar — The Yaf_Route_Supervar class
    • Yaf_Route_Supervar::__construct — The __construct purpose
    • Yaf_Route_Supervar::route — The route purpose
  • Yaf_Session — The Yaf_Session class
    • Yaf_Session::__clone — The __clone purpose
    • Yaf_Session::__construct — The __construct purpose
    • Yaf_Session::count — The count purpose
    • Yaf_Session::current — The current purpose
    • Yaf_Session::del — The del purpose
    • Yaf_Session::__get — The __get purpose
    • Yaf_Session::getInstance — The getInstance purpose
    • Yaf_Session::has — The has purpose
    • Yaf_Session::__isset — The __isset purpose
    • Yaf_Session::key — The key purpose
    • Yaf_Session::next — The next purpose
    • Yaf_Session::offsetExists — The offsetExists purpose
    • Yaf_Session::offsetGet — The offsetGet purpose
    • Yaf_Session::offsetSet — The offsetSet purpose
    • Yaf_Session::offsetUnset — The offsetUnset purpose
    • Yaf_Session::rewind — The rewind purpose
    • Yaf_Session::__set — The __set purpose
    • Yaf_Session::__sleep — The __sleep purpose
    • Yaf_Session::start — The start purpose
    • Yaf_Session::__unset — The __unset purpose
    • Yaf_Session::valid — The valid purpose
    • Yaf_Session::__wakeup — The __wakeup purpose
  • Yaf_Exception — The Yaf_Exception class
    • Yaf_Exception::__construct — The __construct purpose
    • Yaf_Exception::getPrevious — The getPrevious purpose
  • Yaf_Exception_TypeError — The Yaf_Exception_TypeError class
  • Yaf_Exception_StartupError — The Yaf_Exception_StartupError class
  • Yaf_Exception_DispatchFailed — The Yaf_Exception_DispatchFailed class
  • Yaf_Exception_RouterFailed — The Yaf_Exception_RouterFailed class
  • Yaf_Exception_LoadFailed — The Yaf_Exception_LoadFailed class
  • Yaf_Exception_LoadFailed_Module — The Yaf_Exception_LoadFailed_Module class
  • Yaf_Exception_LoadFailed_Controller — The Yaf_Exception_LoadFailed_Controller class
  • Yaf_Exception_LoadFailed_Action — The Yaf_Exception_LoadFailed_Action class
  • Yaf_Exception_LoadFailed_View — The Yaf_Exception_LoadFailed_View class
yaml_parse
Wstęp
Inne podstawowe rozszerzenia


Wstęp

The Yet Another Framework(Yaf) extension is a PHP framework, used for developing web application, It provides OO interfaces to PHPer for developing web application.

Yaf require PHP version greater than 5.2.1, and could not run with early version of PHP.

A simple Yaf benchmark can be found at » Yaf Performance.

Yaf
Instalacja/Konfiguracja
Yaf


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Yaf


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/yaf.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Yaf Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
yaf.library |  | its PHP_INI_ALL value |
yaf.action_prefer | 0 | its PHP_INI_ALL value |
yaf.lowcase_path | 0 | its PHP_INI_ALL value |
yaf.use_spl_autoload | 0 | its PHP_INI_ALL value |
yaf.forward_limit | 5 | its PHP_INI_ALL value |
yaf.name_suffix | 1 | its PHP_INI_ALL value |
yaf.name_separator |  | its PHP_INI_ALL value |
yaf.cache_config | 0 | its PHP_INI_SYS value |
yaf.st_compatible | 0 | its PHP_INI_ALL value |
yaf.environ | product | its PHP_INI_ALL value |
yaf.use_namespace | 0 | its PHP_INI_ALL value |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

yaf.library string

The global library path, Yaf_loader will search global library in this directory.

yaf.action_prefer integer

If there is only one part in PATH_INFO, should it consider as a controller or action.

If this configure On, it will be considered as a Action name.

yaf.lowcase_path integer

Whether lowercase all the path during the class autoloading.

yaf.use_spl_autoload integer

When this value is On, if Yaf_Loader can not find a class, it will return FALSE, then give chance to other auto load function to be called.

When this value is Off(default), Yaf_Loader::autoload() will always return TRUE.

yaf.forward_limit integer

The max forward count, default is 5. that means you can have a max value of 5 in the forward stack.

This is a protection for prevent recursive Yaf_Controller_Abstract::forward().

yaf.name_suffix integer

When this On, Yaf_Loader will indetify a class by it's suffix to decide whether it is a MVC Class.

When this Off, Yaf_Loader will look at the prefix of the class name.

yaf.name_separator string

When this is not empty, Yaf_Loader will identify the class suffix and string value of this.

For example, when this value is "_", Yaf_Loader will take Index_Controller as a Controller Class, IndexController as a normal class.

yaf.cache_config integer

If this is On, and in the meantime you are using ini config file as the parameter of Yaf_Application(), the compiling result of the ini config file will be cached in the PHP process.

Informacja:

Yaf examine the mtime of the ini file, if it was changed since last compiling, Yaf will reload it.

Ostrzeżenie

Yaf use the ini file path as the cache entry key, so do use the absolute path in ini file path, otherwise there might be some conflicts if two application use the same relative path of ini config.

yaf.st_compatible integer

yaf.environ string

This value is "product" by default, used for Yaf to fetch the config section of a ini config file.

That is, if this value is "product", Yaf will use the section named "product" in the ini config file(the first parameter of the Yaf_Application) as the final config of the Yaf_Application.

yaf.use_namespace integer

Only works as of PHP 5.3, if this value is On, All class of Yaf will named in namespace style.

For example, Yaf_Route_Rewrite => \Yaf\Route\Rewrite, Yaf_Controller_Abstract => \Yaf\Controller_Abstract (Abstract is the keyword, can not used as a class name)

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

YAF_VERSION (string)
YAF_ENVIRON (string)
YAF_ERR_STARTUP_FAILED (integer)
YAF_ERR_ROUTE_FAILED (integer)
YAF_ERR_DISPATCH_FAILED (integer)
YAF_ERR_AUTOLOAD_FAILED (integer)
YAF_ERR_NOTFOUND_MODULE (integer)
YAF_ERR_NOTFOUND_CONTROLLER (integer)
YAF_ERR_NOTFOUND_ACTION (integer)
YAF_ERR_NOTFOUND_VIEW (integer)
YAF_ERR_CALL_FAILED (integer)
YAF_ERR_TYPE_ERROR (integer)

Typy zasobów
Przykłady
Yaf


Przykłady

Przykład #1 A classic Application directory layout

- index.php
- .htaccess
+ conf
  |- application.ini //application config
- application/
  - Bootstrap.php
  + controllers
     - Index.php //default controller
  + views
     |+ index
        - index.phtml //view template for default action
  + modules
  - library
  - models
  - plugins

Przykład #2 Entry

index.php in the top directory is the only way in of the application, you should rewrite all request to it(you can use .htaccess in Apache+php_mod)

<?php
define("APPLICATION_PATH",  dirname(__FILE__));

$app  = new Yaf_Application(APPLICATION_PATH . "/conf/application.ini");
$app->bootstrap() //call bootstrap methods defined in Bootstrap.php
 ->run();
?>

Przykład #3 Rewrite rule

#for apache (.htaccess)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php

#for nginx
server {
  listen ****;
  server_name  domain.com;
  root   document_root;
  index  index.php index.html index.htm;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php/$1 last;
  }
}

#for lighttpd
$HTTP["host"] =~ "(www.)?domain.com$" {
  url.rewrite = (
     "^/(.+)/?$"  => "/index.php/$1",
  )
}

Przykład #4 Application config

[yaf]
;APPLICATION_PATH is the constant defined in index.php
application.directory=APPLICATION_PATH "/application/"

;product section inherit from yaf section
[product:yaf]
foo=bar

Przykład #5 Default controller

<?php
class IndexController extends Yaf_Controller_Abstract {
   /* default action */
   public function indexAction() {
       $this->view->word = "hello world";
   }
}
?>
?>

Przykład #6 Default view template

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   <?php echo $word;?>
 </body>
</htlm>

Przykład #7 Run the Applicatioin

Powyższy przykład wyświetli coś podobnego do:

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   hello world
 </body>
</htlm>
Stałe predefiniowane
Application Configuration
Yaf


Application Configuration

You should give an array of config or an ini config file(see Yaf_Config_Ini) path to Yaf_Application::__construct().

Yaf configurations could be merged with user configurations. The difference is, Yaf configurations are prefixed with "yaf." or "application.", if there are both "yaf." and "application.", "application." will be accepcted preferentially.

Przykład #1 An array of yaf configuration example

<?php
    $configs = array(
            "application" => array(
                "directory" => dirname(__FILE__),
                "dispatcher" => array(
                      "catchException" => 0,
                    ),
                "view" => array(
                       "ext" => "phtml",
                    ),
                ),
           );
    $app = new Yaf_Application($config);
?>

Przykład #2 an ini file of yaf configuration example

[yaf]
yaf.directory = APPLICATION_PATH "/appliation"
yaf.dispatcher.catchException = 0

[product : yaf]
; user configuartions list here

Yaf Application Config
Nazwa | Domyślnie | Rejestr zmian
application.directory |  |
application.ext | "php" |
application.view.ext | "phtml" |
application.modules | "index" |
application.library | application.directory . "/library" |
application.library.directory | application.directory . "/library" |
application.library.namespace | "" |
application.bootstrap | application.directory . "/Bootstrap" . application.ext |
application.baseUri | "" |
application.dispatcher.throwException | 1 |
application.dispatcher.catchException | 0 |
application.dispatcher.defaultModule | "index" |
application.dispatcher.defaultController | "index" |
application.dispatcher.defaultAction | "index" |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

application.directory string

The directory of the application, that is the folder which contains the "controllers", "views", "models", "plugins" folders.

Informacja:

This config entry is the only one which doesn't has a default value, which means you should always define it.

application.ext string

The file ext of the PHP script, used in class autoloading( Yaf_Loader).

application.view.ext string

The file ext of the view template script.

application.modules string

A commaseparated list of the registered modules, used in the route process, especially while there are more than three segments in the PATH_INFO,

Yaf need a way to find out whether the first segment is a module name or not.

application.library string

The local library directory, see Yaf_Loader and yaf.library.

Informacja:

As of Yaf 2.1.6, this config entry can also be a array, when it is array, then the library path will try to use the value of application.library.directory

application.library.directory string

Introduced in Yaf 2.1.6

application.library.namespace string

A comma separated prefix of local library namespace.

Introduced in Yaf 2.1.6

application.bootstrap string

A absolute path of the Bootstrap class script.

application.baseUri string

Used to remove a fixed prefix of request uri in route process. Take a example, comes a request with request uri "/prefix/controller/action". if you set application.baseUri to "/prefix", then only "/controller/action" will take as the PATH_INFO in route process.

In generally, you have no need to set this value.

application.dispatcher.throwException bool

If this is On, Yaf will throw exception while some error occurring. see also Yaf_Dispatcher::throwException().

application.dispatcher.catchException bool

If this is On, Yaf will forward to Error controller, Error Action while there is a uncaught exception. see also Yaf_Dispatcher::catchException().

application.dispatcher.defaultModule string

The default module name, see also Yaf_Dispatcher::setDefaultModule().

application.dispatcher.defaultController string

The default controller name, see also Yaf_Dispatcher::setDefaultController().

application.dispatcher.defaultAction string

The default action name, see also Yaf_Dispatcher::setDefaultAction().

Przykłady
Yaf_Application
Yaf


The Yaf_Application class

(No version information available, might only be in SVN)

Wstęp

Yaf_Application provides a bootstrapping facility for applications which provides reusable resources, common- and module-based bootstrap classes and dependency checking.

Informacja:

Yaf_Application implements the singleton pattern, and Yaf_Application can not be serialized or unserialized which will cause problem when you try to use PHPUnit to write some test case for Yaf.

You may use @backupGlobals annotation of PHPUnit to control the backup and restore operations for global variables. thus can solve this promblem.

Krótki opis klasy

final Yaf_Application {
/* Właściwości */
protected $config ;
protected $dispatcher ;
protected static $_app ;
protected $_modules ;
protected $_running ;
protected $_environ ;
/* Metody */
public static void app ( void )
public void bootstrap ([ Yaf_Bootstrap_Abstract $bootstrap ] )
public Yaf_Application clearLastError ( void )
private void __clone ( void )
public __construct ( mixed $config [, string $envrion ] )
public void __destruct ( void )
public void environ ( void )
public void execute ( callback $entry , string $... )
public Yaf_Application getAppDirectory ( void )
public Yaf_Config_Abstract getConfig ( void )
public Yaf_Dispatcher getDispatcher ( void )
public string getLastErrorMsg ( void )
public int getLastErrorNo ( void )
public array getModules ( void )
public void run ( void )
public Yaf_Application setAppDirectory ( string $directory )
private void __sleep ( void )
private void __wakeup ( void )
}

Właściwości

config

dispatcher

_app

_modules

_running

_environ

Spis treści

  • Yaf_Application::app — Retrive an Application instance
  • Yaf_Application::bootstrap — Call bootstrap
  • Yaf_Application::clearLastError — Clear the last error info
  • Yaf_Application::__clone — Yaf_Application can not be cloned
  • Yaf_Application::__construct — Yaf_Application constructor
  • Yaf_Application::__destruct — The __destruct purpose
  • Yaf_Application::environ — Retrive environ
  • Yaf_Application::execute — Execute a callback
  • Yaf_Application::getAppDirectory — Get the application directory
  • Yaf_Application::getConfig — Retrive the config instance
  • Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance
  • Yaf_Application::getLastErrorMsg — Get message of the last occurred error
  • Yaf_Application::getLastErrorNo — Get code of last occurred error
  • Yaf_Application::getModules — Get defined module names
  • Yaf_Application::run — Start Yaf_Application
  • Yaf_Application::setAppDirectory — Change the application directory
  • Yaf_Application::__sleep — Yaf_Application can not be serialized
  • Yaf_Application::__wakeup — Yaf_Application can not be unserialized
Application Configuration
Yaf_Application::app
Yaf


Retrive an Application instance

Yaf_Application
Yaf_Application::bootstrap
Yaf_Application
PHP Manual

Yaf_Application::app

(PECL yaf >=1.0.0)

Yaf_Application::app — Retrive an Application instance

Opis

public static void Yaf_Application::app ( void )

Retrive the Yaf_Application instance, alternatively, we also could use Yaf_Dispatcher::getApplication().

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 Yaf_Application instance, if no Yaf_Application initialized before, NULL will be returned.

Zobacz też:

  • Yaf_Dispatcher::getApplication() - Retrive the application
Yaf_Application
Yaf_Application::bootstrap
Yaf_Application


Call bootstrap

Yaf_Application::app
Yaf_Application::clearLastError
Yaf_Application
PHP Manual

Yaf_Application::bootstrap

(PECL yaf >=1.0.0)

Yaf_Application::bootstrap — Call bootstrap

Opis

public void Yaf_Application::bootstrap ([ Yaf_Bootstrap_Abstract $bootstrap ] )

Run a Bootstrap, all the methods defined in the Bootstrap and named with prefix "_init" will be called according to their declaration order, if the parameter bootstrap is not supplied, Yaf will look for a Bootstrap under application.directory.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

bootstrap

A Yaf_Bootstrap_Abstract instance

Zwracane wartości

Yaf_Application instance

Przykłady

Przykład #1 A Bootstrap()example

<?php
/**
 * This file should be under the APPLICATION_PATH . "/application/"(which was defined in the config passed to Yaf_Application).
 * and named Bootstrap.php,  so the Yaf_Application can find it
 */
class Bootstrap extends Yaf_Bootstrap_Abstract {
    function _initConfig(Yaf_Dispatcher $dispatcher) {
        echo "1st called\n";
    }

    function _initPlugin($dispatcher) {
        echo "2nd called\n";
    }
}
?>

Przykład #2 Yaf_Application::bootstrap()example

<?php

defined('APPLICATION_PATH')                  // APPLICATION_PATH will be used in the ini config file
    || define('APPLICATION_PATH', __DIR__)); //__DIR__ was introduced after PHP 5.3

$application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini');
$application->bootstrap();
?>

Powyższy przykład wyświetli coś podobnego do:

1st called
2nd called

Zobacz też:

  • Yaf_Bootstrap_Abstract
Yaf_Application::app
Yaf_Application::clearLastError
Yaf_Application


Clear the last error info

Yaf_Application::bootstrap
Yaf_Application::__clone
Yaf_Application
PHP Manual

Yaf_Application::clearLastError

(PECL yaf >=2.1.2)

Yaf_Application::clearLastError — Clear the last error info

Opis

public Yaf_Application Yaf_Application::clearLastError ( 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

Przykłady

Przykład #1 Yaf_Application::clearLastError()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   Yaf_Application::app()->clearLastError();
   var_dump(Yaf_Application::app()->getLastErrorNo());
}

$config = array(
 "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

Powyższy przykład wyświetli coś podobnego do:

int(0)
Yaf_Application::bootstrap
Yaf_Application::__clone
Yaf_Application


Yaf_Application can not be cloned

Yaf_Application::clearLastError
Yaf_Application::__construct
Yaf_Application
PHP Manual

Yaf_Application::__clone

(PECL yaf >=1.0.0)

Yaf_Application::__clone — Yaf_Application can not be cloned

Opis

private void Yaf_Application::__clone ( 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

Yaf_Application::clearLastError
Yaf_Application::__construct
Yaf_Application


Yaf_Application constructor

Yaf_Application::__clone
Yaf_Application::__destruct
Yaf_Application
PHP Manual

Yaf_Application::__construct

(PECL yaf >=1.0.0)

Yaf_Application::__construct — Yaf_Application constructor

Opis

public Yaf_Application::__construct ( mixed $config [, string $envrion ] )

Instance a Yaf_Application.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

config

A ini config file path, or a config array

If is a ini config file, there should be a section named as the one defined by yaf.environ, which is "product" by default.

Informacja:

If you use a ini configuration file as your applicatioin's config container. you would open the yaf.cache_config to improve performance.

And the config entry(and there default value) list blow:

Przykład #1 A ini config file example

[product]
;this one should alway be defined, and have no default value
application.directory=APPLICATION_PATH

;following configs have default value, you may no need to define them
application.library = APPLICATION_PATH . "/library"
application.dispatcher.throwException=1
application.dispatcher.catchException=1

application.baseUri=""

;the php script ext name
ap.ext=php

;the view template ext name
ap.view.ext=phtml

ap.dispatcher.defaultModuel=Index
ap.dispatcher.defaultController=Index
ap.dispatcher.defaultAction=index

;defined modules
ap.modules=Index

envrion

Which section will be loaded as the final config

Zwracane wartości

Przykłady

Przykład #2 Yaf_Application::__construct()example

<?php
defined('APPLICATION_PATH')                  // APPLICATION_PATH will be used in the ini config file
    || define('APPLICATION_PATH', __DIR__)); //__DIR__ was introduced after PHP 5.3

$application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini');
$application->bootstrap()->run();
?>

Powyższy przykład wyświetli coś podobnego do:

Przykład #3 Yaf_Application::__construct()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
$application->bootstrap()->run();
?>

Powyższy przykład wyświetli coś
podobnego do:

Zobacz też:

  • Yaf_Config_Ini
    •

Yaf_Application::__clone

Yaf_Application::__destruct

Yaf_Application


The __destruct purpose

Yaf_Application::__construct
Yaf_Application::environ
Yaf_Application
PHP Manual

Yaf_Application::__destruct

(PECL yaf >=1.0.0)

Yaf_Application::__destruct — The __destruct purpose

Opis

public void Yaf_Application::__destruct ( 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

Yaf_Application::__construct
Yaf_Application::environ
Yaf_Application


Retrive environ

Yaf_Application::__destruct
Yaf_Application::execute
Yaf_Application
PHP Manual

Yaf_Application::environ

(PECL yaf >=1.0.0)

Yaf_Application::environ — Retrive environ

Opis

public void Yaf_Application::environ ( void )

Retrive environ which was defined in yaf.environ which has a default value "product".

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

Przykłady

Przykład #1 Yaf_Application::environ()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->environ());
?>

Powyższy przykład wyświetli coś podobnego do:

product
Yaf_Application::__destruct
Yaf_Application::execute
Yaf_Application


Execute a callback

Yaf_Application::environ
Yaf_Application::getAppDirectory
Yaf_Application
PHP Manual

Yaf_Application::execute

(PECL yaf >=1.0.0)

Yaf_Application::execute — Execute a callback

Opis

public void Yaf_Application::execute ( callback $entry , string $... )

This method is typically used to run Yaf_Application in a crontab work. Make the crontab work can also use the autoloader and Bootstrap mechanism.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

entry

...

Zwracane wartości

Przykłady

Przykład #1 Yaf_Application::execute()example

<?php
function main($argc, $argv) {
}

$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
$application->execute("main", $argc,  $argv);
?>

Powyższy przykład wyświetli coś podobnego do:

Yaf_Application::environ

Yaf_Application::getAppDirectory

Yaf_Application


Get the application directory

Yaf_Application::execute
Yaf_Application::getConfig
Yaf_Application
PHP Manual

Yaf_Application::getAppDirectory

(PECL yaf >=2.1.4)

Yaf_Application::getAppDirectory — Get the application directory

Opis

public Yaf_Application Yaf_Application::getAppDirectory ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

directory

Zwracane wartości

Yaf_Application::execute
Yaf_Application::getConfig
Yaf_Application


Retrive the config instance

Yaf_Application::getAppDirectory
Yaf_Application::getDispatcher
Yaf_Application
PHP Manual

Yaf_Application::getConfig

(PECL yaf >=1.0.0)

Yaf_Application::getConfig — Retrive the config instance

Opis

public Yaf_Config_Abstract Yaf_Application::getConfig ( 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

A Yaf_Config_Abstract instance

Przykłady

Przykład #1 Yaf_Application::getConfig()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getConfig());
?>

Powyższy przykład wyświetli coś podobnego do:

Yaf_Config_Simple Object
(
    [_config:protected] => Array
        (
            [application] => Array
                (
                    [directory] => /home/laruence/local/www/htdocs/application
                )

        )

    [_readonly:protected] => 1
)
Yaf_Application::getAppDirectory
Yaf_Application::getDispatcher
Yaf_Application


Get Yaf_Dispatcher instance

Yaf_Application::getConfig
Yaf_Application::getLastErrorMsg
Yaf_Application
PHP Manual

Yaf_Application::getDispatcher

(PECL yaf >=1.0.0)

Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance

Opis

public Yaf_Dispatcher Yaf_Application::getDispatcher ( 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

Przykłady

Przykład #1 Yaf_Application::getDispatcher()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getDispatcher());
?>

Powyższy przykład wyświetli coś podobnego do:

Yaf_Dispatcher Object
(
    [_router:protected] => Yaf_Router Object
        (
            [_routes:protected] => Array
                (
                    [_default] => Yaf_Route_Static Object
                        (
                        )

                )

            [_current:protected] =>
        )

    [_view:protected] =>
    [_request:protected] => Yaf_Request_Http Object
        (
            [module] =>
            [controller] =>
            [action] =>
            [method] => Cli
            [params:protected] => Array
                (
                )

            [language:protected] =>
            [_exception:protected] =>
            [_base_uri:protected] =>
            [uri:protected] =>
            [dispatched:protected] =>
            [routed:protected] =>
        )

    [_plugins:protected] => Array
        (
        )

    [_auto_render:protected] => 1
    [_return_response:protected] =>
    [_instantly_flush:protected] =>
    [_default_module:protected] => Index
    [_default_controller:protected] => Index
    [_default_action:protected] => index
    [_response] => Yaf_Response_Cli Object
        (
            [_header:protected] => Array
                (
                )

            [_body:protected] =>
            [_sendheader:protected] =>
        )

)
Yaf_Application::getConfig
Yaf_Application::getLastErrorMsg
Yaf_Application


Get message of the last occurred error

Yaf_Application::getDispatcher
Yaf_Application::getLastErrorNo
Yaf_Application
PHP Manual

Yaf_Application::getLastErrorMsg

(PECL yaf >=2.1.2)

Yaf_Application::getLastErrorMsg — Get message of the last occurred error

Opis

public string Yaf_Application::getLastErrorMsg ( 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

Przykłady

Przykład #1 Yaf_Application::getLastErrorMsg()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   var_dump(Yaf_Application::app()->getLastErrorMsg());
}

$config = array(
 "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

Powyższy przykład wyświetli coś podobnego do:

string(69) "Could not find controller script /tmp/notexists/controllers/Index.php"
Yaf_Application::getDispatcher
Yaf_Application::getLastErrorNo
Yaf_Application


Get code of last occurred error

Yaf_Application::getLastErrorMsg
Yaf_Application::getModules
Yaf_Application
PHP Manual

Yaf_Application::getLastErrorNo

(PECL yaf >=2.1.2)

Yaf_Application::getLastErrorNo — Get code of last occurred error

Opis

public int Yaf_Application::getLastErrorNo ( 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

Przykłady

Przykład #1 Yaf_Application::getLastErrorNo()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   var_dump(Yaf_Application::app()->getLastErrorNo());
   var_dump(Yaf_Application::app()->getLastErrorNo() == YAF_ERR_NOTFOUND_CONTROLLER);
}

$config = array(
  "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

Powyższy przykład wyświetli coś podobnego do:

int(516)
bool(true)
Yaf_Application::getLastErrorMsg
Yaf_Application::getModules
Yaf_Application


Get defined module names

Yaf_Application::getLastErrorNo
Yaf_Application::run
Yaf_Application
PHP Manual

Yaf_Application::getModules

(PECL yaf >=1.0.0)

Yaf_Application::getModules — Get defined module names

Opis

public array Yaf_Application::getModules ( void )

Get the modules list defined in config, if no one defined, there will always be a module named "Index".

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

Przykłady

Przykład #1 Yaf_Application::getModules()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getModules());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => Index
)
Yaf_Application::getLastErrorNo
Yaf_Application::run
Yaf_Application


Start Yaf_Application

Yaf_Application::getModules
Yaf_Application::setAppDirectory
Yaf_Application
PHP Manual

Yaf_Application::run

(PECL yaf >=1.0.0)

Yaf_Application::run — Start Yaf_Application

Opis

public void Yaf_Application::run ( void )

Run a Yaf_Application, let the Yaf_Application accpect a request, and route the request, dispatch to controller/action, and render response. return response to client fianlly.

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

Yaf_Application::getModules
Yaf_Application::setAppDirectory
Yaf_Application


Change the application directory

Yaf_Application::run
Yaf_Application::__sleep
Yaf_Application
PHP Manual

Yaf_Application::setAppDirectory

(PECL yaf >=2.1.4)

Yaf_Application::setAppDirectory — Change the application directory

Opis

public Yaf_Application Yaf_Application::setAppDirectory ( string $directory )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

directory

Zwracane wartości

Yaf_Application::run
Yaf_Application::__sleep
Yaf_Application


Yaf_Application can not be serialized

Yaf_Application::setAppDirectory
Yaf_Application::__wakeup
Yaf_Application
PHP Manual

Yaf_Application::__sleep

(PECL yaf >=1.0.0)

Yaf_Application::__sleep — Yaf_Application can not be serialized

Opis

private void Yaf_Application::__sleep ( 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

Yaf_Application::setAppDirectory
Yaf_Application::__wakeup
Yaf_Application


Yaf_Application can not be unserialized

Yaf_Application::__sleep
Yaf_Bootstrap_Abstract
Yaf_Application
PHP Manual

Yaf_Application::__wakeup

(PECL yaf >=1.0.0)

Yaf_Application::__wakeup — Yaf_Application can not be unserialized

Opis

private void Yaf_Application::__wakeup ( 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

Yaf_Application::__sleep
Yaf_Bootstrap_Abstract
Yaf_Application


The Yaf_Bootstrap_Abstract class

(No version information available, might only be in SVN)

Wstęp

Bootstrap is a mechanism used to do some intial config before a Application run.

User may define their own Bootstrap class by inheriting Yaf_Bootstrap_Abstract

Any method declared in Bootstrap class with leading "_init", will be called by Yaf_Application::bootstrap() one by one according to their defined order.

Krótki opis klasy

abstract Yaf_Bootstrap_Abstract {
/* Właściwości */
/* Metody */
}
Yaf_Application::__wakeup
Yaf_Dispatcher
Yaf


The Yaf_Dispatcher class

(No version information available, might only be in SVN)

Wstęp

Yaf_Dispatcher purpose is to initialize the request environment, route the incoming request, and then dispatch any discovered actions; it aggregates any responses and returns them when the process is complete.

Yaf_Dispatcher also implements the Singleton pattern, meaning only a single instance of it may be available at any given time. This allows it to also act as a registry on which the other objects in the dispatch process may draw.

Krótki opis klasy

final Yaf_Dispatcher {
/* Właściwości */
protected $_router ;
protected $_view ;
protected $_request ;
protected $_plugins ;
protected static $_instance ;
protected $_auto_render ;
protected $_return_response ;
protected $_instantly_flush ;
protected $_default_module ;
protected $_default_controller ;
protected $_default_action ;
/* Metody */
public Yaf_Dispatcher autoRender ( bool $flag )
public Yaf_Dispatcher catchException ([ bool $flag ] )
private void __clone ( void )
public __construct ( void )
public Yaf_Dispatcher disableView ( void )
public Yaf_Response_Abstract dispatch ( Yaf_Request_Abstract $request )
public Yaf_Dispatcher enableView ( void )
public Yaf_Dispatcher flushInstantly ( bool $flag )
public Yaf_Application getApplication ( void )
public static Yaf_Dispatcher getInstance ( void )
public Yaf_Request_Abstract getRequest ( void )
public Yaf_Router getRouter ( void )
public Yaf_View_Interface initView ( string $templates_dir [, array $options ] )
public Yaf_Dispatcher registerPlugin ( Yaf_Plugin_Abstract $plugin )
public Yaf_Dispatcher returnResponse ( bool $flag )
public Yaf_Dispatcher setAppDirectory ( string $directory )
public Yaf_Dispatcher setDefaultAction ( string $action )
public Yaf_Dispatcher setDefaultController ( string $controller )
public Yaf_Dispatcher setDefaultModule ( string $module )
public Yaf_Dispatcher setErrorHandler ( call $callback , int $error_types )
public Yaf_Dispatcher setRequest ( Yaf_Request_Abstract $request )
public Yaf_Dispatcher setView ( Yaf_View_Interface $view )
private void __sleep ( void )
public Yaf_Dispatcher throwException ([ bool $flag ] )
private void __wakeup ( void )
}

Właściwości

_router

_view

_request

_plugins

_instance

_auto_render

_return_response

_instantly_flush

_default_module

_default_controller

_default_action

Spis treści

  • Yaf_Dispatcher::autoRender — Switch on/off autorendering
  • Yaf_Dispatcher::catchException — Switch on/off exception catching
  • Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned
  • Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor
  • Yaf_Dispatcher::disableView — Disable view rendering
  • Yaf_Dispatcher::dispatch — Dispatch a request
  • Yaf_Dispatcher::enableView — enable view rendering
  • Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing
  • Yaf_Dispatcher::getApplication — Retrive the application
  • Yaf_Dispatcher::getInstance — Retrive the dispatcher instance
  • Yaf_Dispatcher::getRequest — Retrive the request instance
  • Yaf_Dispatcher::getRouter — Retrive router instance
  • Yaf_Dispatcher::initView — Initialize view and return it
  • Yaf_Dispatcher::registerPlugin — Register a plugin
  • Yaf_Dispatcher::returnResponse — The returnResponse purpose
  • Yaf_Dispatcher::setAppDirectory — Change the application directory
  • Yaf_Dispatcher::setDefaultAction — Change default action name
  • Yaf_Dispatcher::setDefaultController — Change default controller name
  • Yaf_Dispatcher::setDefaultModule — Change default module name
  • Yaf_Dispatcher::setErrorHandler — The setErrorHandler purpose
  • Yaf_Dispatcher::setRequest — The setRequest purpose
  • Yaf_Dispatcher::setView — Set a custom view engine
  • Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized
  • Yaf_Dispatcher::throwException — Switch on/off exception throwing
  • Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized
Yaf_Bootstrap_Abstract
Yaf_Dispatcher::autoRender
Yaf


Switch on/off autorendering

Yaf_Dispatcher
Yaf_Dispatcher::catchException
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::autoRender

(PECL yaf >=1.0.0)

Yaf_Dispatcher::autoRender — Switch on/off autorendering

Opis

public Yaf_Dispatcher Yaf_Dispatcher::autoRender ( bool $flag )

Yaf_Dispatcher will render automatically after dispatches a incoming request, you can prevent the rendering by calling this method with flag TRUE

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flag

bool

Zwracane wartości

Przykłady

Przykład #1 Yaf_Dispatcher::autoRender()example

<?php
class IndexController extends Yaf_Controller_Abstract {
     /* init method will be called as soon as a controller is initialized */
     public function init() {
         if ($this->getRequest()->isXmlHttpRequest()) {
             //do not call render for ajax request
             //we will outpu a json string
             Yaf_Dispatcher::getInstance()->autoRender(FALSE);
         }
     }
}
?>

Powyższy przykład wyświetli coś podobnego do:

Yaf_Dispatcher

Yaf_Dispatcher::catchException

Yaf_Dispatcher


Switch on/off exception catching

Yaf_Dispatcher::autoRender
Yaf_Dispatcher::__clone
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::catchException

(PECL yaf >=1.0.0)

Yaf_Dispatcher::catchException — Switch on/off exception catching

Opis

public Yaf_Dispatcher Yaf_Dispatcher::catchException ([ bool $flag ] )

While the application.dispatcher.throwException is On(you can also calling to Yaf_Dispatcher::throwException(TRUE)() to enable it), Yaf will throw Exception whe error occurrs instead of trigger error.

then if you enable Yaf_Dispatcher::catchException()(also can enabled by set application.dispatcher.catchException), all Un-caught Exceptions will be caught by ErrorController::error if you have defined one.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flag

Zwracane wartości

Przykłady

Przykład #1 Yaf_Dispatcher::catchException()example

/* if you defined a ErrorController like following */
<?php
class ErrorController extends Yaf_Controller_Abstract {
     /**
      * you can also call to Yaf_Request_Abstract::getException to get the
      * un-caught exception.
      */
     public function error($exception) {
        /* error occurs */
        switch ($exception->getCode()) {
            case YAF_ERR_NOTFOUND_MODULE:
            case YAF_ERR_NOTFOUND_CONTROLLER:
            case YAF_ERR_NOTFOUND_ACTION:
            case YAF_ERR_NOTFOUND_VIEW:
                echo 404, ":", $exception->getMessage();
                break;
            default :
                $message = $exception->getMessage();
                echo 0, ":", $exception->getMessage();
                break;
        }
     }
}
?>

Powyższy przykład wyświetli coś podobnego do:

/* now if some error occur, assuming access a non-exists controller(or you can throw a exception yourself): */
404:Could not find controller script **/application/controllers/No-exists-controller.php

Zobacz też:

  • Yaf_Dispatcher::throwException() - Switch on/off exception throwing
Yaf_Dispatcher::autoRender
Yaf_Dispatcher::__clone
Yaf_Dispatcher


Yaf_Dispatcher can not be cloned

Yaf_Dispatcher::catchException
Yaf_Dispatcher::__construct
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__clone

(PECL yaf >=1.0.0)

Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned

Opis

private void Yaf_Dispatcher::__clone ( 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

Yaf_Dispatcher::catchException
Yaf_Dispatcher::__construct
Yaf_Dispatcher


Yaf_Dispatcher constructor

Yaf_Dispatcher::__clone
Yaf_Dispatcher::disableView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__construct

(PECL yaf >=1.0.0)

Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor

Opis

public Yaf_Dispatcher::__construct ( 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

Yaf_Dispatcher::__clone
Yaf_Dispatcher::disableView
Yaf_Dispatcher


Disable view rendering

Yaf_Dispatcher::__construct
Yaf_Dispatcher::dispatch
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::disableView

(PECL yaf >=1.0.0)

Yaf_Dispatcher::disableView — Disable view rendering

Opis

public Yaf_Dispatcher Yaf_Dispatcher::disableView ( 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

Yaf_Dispatcher::__construct
Yaf_Dispatcher::dispatch
Yaf_Dispatcher


Dispatch a request

Yaf_Dispatcher::disableView
Yaf_Dispatcher::enableView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::dispatch

(PECL yaf >=1.0.0)

Yaf_Dispatcher::dispatch — Dispatch a request

Opis

public Yaf_Response_Abstract Yaf_Dispatcher::dispatch ( Yaf_Request_Abstract $request )

This method does the heavy work of the Yaf_Dispatcher. It take a request object.

The dispatch process has three distinct events:

  • Routing
  • Dispatching
  • Response
Routing takes place exactly once, using the values in the request object when dispatch() is called. Dispatching takes place in a loop; a request may either indicate multiple actions to dispatch, or the controller or a plugin may reset the request object to force additional actions to dispatch(see Yaf_Plugin_Abstract. When all is done, the Yaf_Dispatcher returns a response.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

Zwracane wartości

Yaf_Dispatcher::disableView
Yaf_Dispatcher::enableView
Yaf_Dispatcher


enable view rendering

Yaf_Dispatcher::dispatch
Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::enableView

(PECL yaf >=1.0.0)

Yaf_Dispatcher::enableView — enable view rendering

Opis

public Yaf_Dispatcher Yaf_Dispatcher::enableView ( 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

Yaf_Dispatcher::dispatch
Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher


Switch on/off the instant flushing

Yaf_Dispatcher::enableView
Yaf_Dispatcher::getApplication
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::flushInstantly

(PECL yaf >=1.0.0)

Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing

Opis

public Yaf_Dispatcher Yaf_Dispatcher::flushInstantly ( bool $flag )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flag

Zwracane wartości

Yaf_Dispatcher::enableView
Yaf_Dispatcher::getApplication
Yaf_Dispatcher


Retrive the application

Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher::getInstance
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getApplication

(PECL yaf >=1.0.0)

Yaf_Dispatcher::getApplication — Retrive the application

Opis

public Yaf_Application Yaf_Dispatcher::getApplication ( void )

Retrive the Yaf_Application instance. same as Yaf_Application::app().

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

Zobacz też:

  • Yaf_Application::app() - Retrive an Application instance
Yaf_Dispatcher::flushInstantly
Yaf_Dispatcher::getInstance
Yaf_Dispatcher


Retrive the dispatcher instance

Yaf_Dispatcher::getApplication
Yaf_Dispatcher::getRequest
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getInstance

(PECL yaf >=1.0.0)

Yaf_Dispatcher::getInstance — Retrive the dispatcher instance

Opis

public static Yaf_Dispatcher Yaf_Dispatcher::getInstance ( 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

Yaf_Dispatcher::getApplication
Yaf_Dispatcher::getRequest
Yaf_Dispatcher


Retrive the request instance

Yaf_Dispatcher::getInstance
Yaf_Dispatcher::getRouter
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getRequest

(PECL yaf >=1.0.0)

Yaf_Dispatcher::getRequest — Retrive the request instance

Opis

public Yaf_Request_Abstract Yaf_Dispatcher::getRequest ( 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

Yaf_Dispatcher::getInstance
Yaf_Dispatcher::getRouter
Yaf_Dispatcher


Retrive router instance

Yaf_Dispatcher::getRequest
Yaf_Dispatcher::initView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::getRouter

(PECL yaf >=1.0.0)

Yaf_Dispatcher::getRouter — Retrive router instance

Opis

public Yaf_Router Yaf_Dispatcher::getRouter ( 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

Yaf_Dispatcher::getRequest
Yaf_Dispatcher::initView
Yaf_Dispatcher


Initialize view and return it

Yaf_Dispatcher::getRouter
Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::initView

(PECL yaf >=1.0.0)

Yaf_Dispatcher::initView — Initialize view and return it

Opis

public Yaf_View_Interface Yaf_Dispatcher::initView ( string $templates_dir [, array $options ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

templates_dir

options

Zwracane wartości

Yaf_Dispatcher::getRouter
Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher


Register a plugin

Yaf_Dispatcher::initView
Yaf_Dispatcher::returnResponse
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::registerPlugin

(PECL yaf >=1.0.0)

Yaf_Dispatcher::registerPlugin — Register a plugin

Opis

public Yaf_Dispatcher Yaf_Dispatcher::registerPlugin ( Yaf_Plugin_Abstract $plugin )

Register a plugin(see Yaf_Plugin_Abstract). Generally, we register plugins in Bootstrap(see Yaf_Bootstrap_Abstract).

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

plugin

Zwracane wartości

Przykłady

Przykład #1 Yaf_Dispatcher::registerPlugin()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {
  public function _initPlugin(Yaf_Dispatcher $dispatcher) {
    /**
    * Yaf assumes plugin scripts under [application.directory] .  "/plugins"
    * for this case, it will be:
    * [application.directory] . "/plugins/" . "User" . [application.ext]
    */
    $user = new UserPlugin();
    $dispatcher->registerPlugin($user);
  }
}
?>

Zobacz też:

  • Yaf_Plugin_Abstract
  • Yaf_Bootstrap_Abstract
Yaf_Dispatcher::initView
Yaf_Dispatcher::returnResponse
Yaf_Dispatcher


The returnResponse purpose

Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher::setAppDirectory
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::returnResponse

(PECL yaf >=1.0.0)

Yaf_Dispatcher::returnResponse — The returnResponse purpose

Opis

public Yaf_Dispatcher Yaf_Dispatcher::returnResponse ( bool $flag )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flag

Zwracane wartości

Yaf_Dispatcher::registerPlugin
Yaf_Dispatcher::setAppDirectory
Yaf_Dispatcher


Change the application directory

Yaf_Dispatcher::returnResponse
Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setAppDirectory

(PECL yaf <=2.1.4)

Yaf_Dispatcher::setAppDirectory — Change the application directory

Opis

public Yaf_Dispatcher Yaf_Dispatcher::setAppDirectory ( string $directory )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

directory

Zwracane wartości

Yaf_Dispatcher::returnResponse
Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher


Change default action name

Yaf_Dispatcher::setAppDirectory
Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setDefaultAction

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setDefaultAction — Change default action name

Opis

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultAction ( string $action )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

action

Zwracane wartości

Yaf_Dispatcher::setAppDirectory
Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher


Change default controller name

Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setDefaultController

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setDefaultController — Change default controller name

Opis

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultController ( string $controller )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

controller

Zwracane wartości

Yaf_Dispatcher::setDefaultAction
Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher


Change default module name

Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setDefaultModule

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setDefaultModule — Change default module name

Opis

public Yaf_Dispatcher Yaf_Dispatcher::setDefaultModule ( string $module )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

module

Zwracane wartości

Yaf_Dispatcher::setDefaultController
Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher


The setErrorHandler purpose

Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher::setRequest
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setErrorHandler

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setErrorHandler — The setErrorHandler purpose

Opis

public Yaf_Dispatcher Yaf_Dispatcher::setErrorHandler ( call $callback , int $error_types )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

callback

error_types

Zwracane wartości

Yaf_Dispatcher::setDefaultModule
Yaf_Dispatcher::setRequest
Yaf_Dispatcher


The setRequest purpose

Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher::setView
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setRequest

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setRequest — The setRequest purpose

Opis

public Yaf_Dispatcher Yaf_Dispatcher::setRequest ( Yaf_Request_Abstract $request )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

plugin

Zwracane wartości

Yaf_Dispatcher::setErrorHandler
Yaf_Dispatcher::setView
Yaf_Dispatcher


Set a custom view engine

Yaf_Dispatcher::setRequest
Yaf_Dispatcher::__sleep
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::setView

(PECL yaf >=1.0.0)

Yaf_Dispatcher::setView — Set a custom view engine

Opis

public Yaf_Dispatcher Yaf_Dispatcher::setView ( Yaf_View_Interface $view )

This method proviods a solution for that if you want use a custom view engine instead of Yaf_View_Simple

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

view

A Yaf_View_Interface instance

Zwracane wartości

Przykłady

Przykład #1 A custom View engine()example

<?php
require "/path/to/smarty/Smarty.class.php";

class Smarty_Adapter implements Yaf_View_Interface
{
    /**
     * Smarty object
     * @var Smarty
     */
    public $_smarty;

    /**
     * Constructor
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array()) {
        $this->_smarty = new Smarty;

        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }

        foreach ($extraParams as $key => $value) {
            $this->_smarty->$key = $value;
        }
    }

    /**
     * Set the path to the templates
     *
     * @param string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_smarty->template_dir = $path;
            return;
        }

        throw new Exception('Invalid path provided');
    }

    /**
     * Assign a variable to the template
     *
     * @param string $key The variable name.
     * @param mixed $val The variable value.
     * @return void
     */
    public function __set($key, $val)
    {
        $this->_smarty->assign($key, $val);
    }

    /**
     * Allows testing with empty() and isset() to work
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return (null !== $this->_smarty->get_template_vars($key));
    }

    /**
     * Allows unset() on object properties to work
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->_smarty->clear_assign($key);
    }

    /**
     * Assign variables to the template
     *
     * Allows setting a specific key to the specified value, OR passing
     * an array of key => value pairs to set en masse.
     *
     * @see __set()
     * @param string|array $spec The assignment strategy to use (key or
     * array of key => value pairs)
     * @param mixed $value (Optional) If assigning a named variable,
     * use this as the value.
     * @return void
     */
    public function assign($spec, $value = null) {
        if (is_array($spec)) {
            $this->_smarty->assign($spec);
            return;
        }

        $this->_smarty->assign($spec, $value);
    }

    /**
     * Clear all assigned variables
     *
     * Clears all variables assigned to Yaf_View either via
     * {@link assign()} or property overloading
     * ({@link __get()}/{@link __set()}).
     *
     * @return void
     */
    public function clearVars() {
        $this->_smarty->clear_all_assign();
    }

    /**
     * Processes a template and returns the output.
     *
     * @param string $name The template to process.
     * @return string The output.
     */
    public function render($name, $value = NULL) {
        return $this->_smarty->fetch($name);
    }

    public function display($name, $value = NULL) {
        echo $this->_smarty->fetch($name);
    }

}
?>

Przykład #2 Yaf_Dispatcher::setView()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {

    /**
     * there are some config for smarty in the config:
     *
     * smarty.left_delimiter   = "{{"
     * smarty.right_delimiter  = "}}"
     * smarty.template_dir     = APPLICATION_PATH "/views/scripts/"
     * smarty.compile_dir      = APPLICATION_PATH "/views/templates_c/"
     * smarty.cache_dir        = APPLICATION_PATH "/views/templates_d/"
     *
     */
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initLocalName() {
        /** we put class Smarty_Adapter under the local library directory */
        Yaf_Loader::getInstance()->registerLocalNamespace('Smarty');
    }

    public function _initSmarty(Yaf_Dispatcher $dispatcher) {
        $smarty = new Smarty_Adapter(null, Yaf_Registry::get("config")->get("smarty"));
        $dispatcher->setView($smarty);
        /* now the Smarty view engine become the default view engine of Yaf */
    }
}
?>

Zobacz też:

  • Yaf_View_Interface
  • Yaf_View_Simple
Yaf_Dispatcher::setRequest
Yaf_Dispatcher::__sleep
Yaf_Dispatcher


Yaf_Dispatcher can not be serialized

Yaf_Dispatcher::setView
Yaf_Dispatcher::throwException
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__sleep

(PECL yaf >=1.0.0)

Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized

Opis

private void Yaf_Dispatcher::__sleep ( 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

Yaf_Dispatcher::setView
Yaf_Dispatcher::throwException
Yaf_Dispatcher


Switch on/off exception throwing

Yaf_Dispatcher::__sleep
Yaf_Dispatcher::__wakeup
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::throwException

(PECL yaf >=1.0.0)

Yaf_Dispatcher::throwException — Switch on/off exception throwing

Opis

public Yaf_Dispatcher Yaf_Dispatcher::throwException ([ bool $flag ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flag

Zwracane wartości

Yaf_Dispatcher::__sleep
Yaf_Dispatcher::__wakeup
Yaf_Dispatcher


Yaf_Dispatcher can not be unserialized

Yaf_Dispatcher::throwException
Yaf_Config_Abstract
Yaf_Dispatcher
PHP Manual

Yaf_Dispatcher::__wakeup

(PECL yaf >=1.0.0)

Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized

Opis

private void Yaf_Dispatcher::__wakeup ( 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

Yaf_Dispatcher::throwException
Yaf_Config_Abstract
Yaf_Dispatcher


The Yaf_Config_Abstract class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

abstract Yaf_Config_Abstract {
/* Właściwości */
protected $_config ;
protected $_readonly ;
/* Metody */
abstract public mixed get ( string $name , mixed $value )
abstract public bool readonly ( void )
abstract public Yaf_Config_Abstract set ( void )
abstract public array toArray ( void )
}

Właściwości

_config

_readonly

Spis treści

  • Yaf_Config_Abstract::get — Getter
  • Yaf_Config_Abstract::readonly — Find a config whether readonly
  • Yaf_Config_Abstract::set — Setter
  • Yaf_Config_Abstract::toArray — Cast to array
Yaf_Dispatcher::__wakeup
Yaf_Config_Abstract::get
Yaf


Getter

Yaf_Config_Abstract
Yaf_Config_Abstract::readonly
Yaf_Config_Abstract
PHP Manual

Yaf_Config_Abstract::get

(PECL yaf >=1.0.0)

Yaf_Config_Abstract::get — Getter

Opis

abstract public mixed Yaf_Config_Abstract::get ( string $name , mixed $value )

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

Yaf_Config_Abstract
Yaf_Config_Abstract::readonly
Yaf_Config_Abstract


Find a config whether readonly

Yaf_Config_Abstract::get
Yaf_Config_Abstract::set
Yaf_Config_Abstract
PHP Manual

Yaf_Config_Abstract::readonly

(PECL yaf >=1.0.0)

Yaf_Config_Abstract::readonly — Find a config whether readonly

Opis

abstract public bool Yaf_Config_Abstract::readonly ( 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

Yaf_Config_Abstract::get
Yaf_Config_Abstract::set
Yaf_Config_Abstract


Setter

Yaf_Config_Abstract::readonly
Yaf_Config_Abstract::toArray
Yaf_Config_Abstract
PHP Manual

Yaf_Config_Abstract::set

(PECL yaf >=1.0.0)

Yaf_Config_Abstract::set — Setter

Opis

abstract public Yaf_Config_Abstract Yaf_Config_Abstract::set ( 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

Yaf_Config_Abstract::readonly
Yaf_Config_Abstract::toArray
Yaf_Config_Abstract


Cast to array

Yaf_Config_Abstract::set
Yaf_Config_Ini
Yaf_Config_Abstract
PHP Manual

Yaf_Config_Abstract::toArray

(PECL yaf >=1.0.0)

Yaf_Config_Abstract::toArray — Cast to array

Opis

abstract public array Yaf_Config_Abstract::toArray ( 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

Yaf_Config_Abstract::set
Yaf_Config_Ini
Yaf_Config_Abstract


The Yaf_Config_Ini class

(No version information available, might only be in SVN)

Wstęp

Yaf_Config_Ini enables developers to store configuration data in a familiar INI format and read them in the application by using nested object property syntax. The INI format is specialized to provide both the ability to have a hierarchy of configuration data keys and inheritance between configuration data sections. Configuration data hierarchies are supported by separating the keys with the dot or period character ("."). A section may extend or inherit from another section by following the section name with a colon character (":") and the name of the section from which data are to be inherited.

Informacja:

Yaf_Config_Ini utilizes the » parse_ini_file() PHP function. Please review this documentation to be aware of its specific behaviors, which propagate to Yaf_Config_Ini, such as how the special values of "TRUE", "FALSE", "yes", "no", and "NULL" are handled.

Krótki opis klasy

Yaf_Config_Ini extends Yaf_Config_Abstract implements Iterator , Traversable , ArrayAccess , Countable {
/* Właściwości */
/* Metody */
public __construct ( string $config_file [, string $section ] )
public void count ( void )
public void current ( void )
public void __get ([ string $name ] )
public void __isset ( string $name )
public void key ( void )
public void next ( void )
public void offsetExists ( string $name )
public void offsetGet ( string $name )
public void offsetSet ( string $name , string $value )
public void offsetUnset ( string $name )
public void readonly ( void )
public void rewind ( void )
public void __set ( string $name , mixed $value )
public void toArray ( void )
public void valid ( void )
/* Metody dziedziczone */
abstract public mixed Yaf_Config_Abstract::get ( string $name , mixed $value )
abstract public bool Yaf_Config_Abstract::readonly ( void )
abstract public Yaf_Config_Abstract Yaf_Config_Abstract::set ( void )
abstract public array Yaf_Config_Abstract::toArray ( void )
}

Właściwości

_config

_readonly

Przykłady

Przykład #1 Yaf_Config_Ini()example

This example illustrates a basic use of Yaf_Config_Ini for loading configuration data from an INI file. In this example there are configuration data for both a production system and for a staging system. Because the staging system configuration data are very similar to those for production, the staging section inherits from the production section. In this case, the decision is arbitrary and could have been written conversely, with the production section inheriting from the staging section, though this may not be the case for more complex situations. Suppose, then, that the following configuration data are contained in /path/to/config.ini:

; Production site configuration data
[production]
webhost                  = www.example.com
database.adapter         = pdo_mysql
database.params.host     = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname   = dbname

; Staging site configuration data inherits from production and
; overrides values as necessary
[staging : production]
database.params.host     = dev.example.com
database.params.username = devuser
database.params.password = devsecret
<?php
$config = new Yaf_Config_Ini('/path/to/config.ini', 'staging');

var_dump($config->database->params->host);
var_dump($config->database->params->dbname);
var_dump($config->get("database.params.username"));
?>

Powyższy przykład wyświetli coś podobnego do:

string(15) "dev.example.com"
string(6) "dbname"
string(7) "devuser

Spis treści

  • Yaf_Config_Ini::__construct — The __construct purpose
  • Yaf_Config_Ini::count — The count purpose
  • Yaf_Config_Ini::current — The current purpose
  • Yaf_Config_Ini::__get — The __get purpose
  • Yaf_Config_Ini::__isset — The __isset purpose
  • Yaf_Config_Ini::key — The key purpose
  • Yaf_Config_Ini::next — The next purpose
  • Yaf_Config_Ini::offsetExists — The offsetExists purpose
  • Yaf_Config_Ini::offsetGet — The offsetGet purpose
  • Yaf_Config_Ini::offsetSet — The offsetSet purpose
  • Yaf_Config_Ini::offsetUnset — The offsetUnset purpose
  • Yaf_Config_Ini::readonly — The readonly purpose
  • Yaf_Config_Ini::rewind — The rewind purpose
  • Yaf_Config_Ini::__set — The __set purpose
  • Yaf_Config_Ini::toArray — The toArray purpose
  • Yaf_Config_Ini::valid — The valid purpose
Yaf_Config_Abstract::toArray
Yaf_Config_Ini::__construct
Yaf


The __construct purpose

Yaf_Config_Ini
Yaf_Config_Ini::count
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__construct

(PECL yaf >=1.0.0)

Yaf_Config_Ini::__construct — The __construct purpose

Opis

public Yaf_Config_Ini::__construct ( string $config_file [, string $section ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

config_file

section

Zwracane wartości

Yaf_Config_Ini
Yaf_Config_Ini::count
Yaf_Config_Ini


The count purpose

Yaf_Config_Ini::__construct
Yaf_Config_Ini::current
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::count

(PECL yaf >=1.0.0)

Yaf_Config_Ini::count — The count purpose

Opis

public void Yaf_Config_Ini::count ( 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

Yaf_Config_Ini::__construct
Yaf_Config_Ini::current
Yaf_Config_Ini


The current purpose

Yaf_Config_Ini::count
Yaf_Config_Ini::__get
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::current

(PECL yaf >=1.0.0)

Yaf_Config_Ini::current — The current purpose

Opis

public void Yaf_Config_Ini::current ( 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

Yaf_Config_Ini::count
Yaf_Config_Ini::__get
Yaf_Config_Ini


The __get purpose

Yaf_Config_Ini::current
Yaf_Config_Ini::__isset
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__get

(PECL yaf >=1.0.0)

Yaf_Config_Ini::__get — The __get purpose

Opis

public void Yaf_Config_Ini::__get ([ string $name ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Ini::current
Yaf_Config_Ini::__isset
Yaf_Config_Ini


The __isset purpose

Yaf_Config_Ini::__get
Yaf_Config_Ini::key
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__isset

(PECL yaf >=1.0.0)

Yaf_Config_Ini::__isset — The __isset purpose

Opis

public void Yaf_Config_Ini::__isset ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Ini::__get
Yaf_Config_Ini::key
Yaf_Config_Ini


The key purpose

Yaf_Config_Ini::__isset
Yaf_Config_Ini::next
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::key

(PECL yaf >=1.0.0)

Yaf_Config_Ini::key — The key purpose

Opis

public void Yaf_Config_Ini::key ( 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

Yaf_Config_Ini::__isset
Yaf_Config_Ini::next
Yaf_Config_Ini


The next purpose

Yaf_Config_Ini::key
Yaf_Config_Ini::offsetExists
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::next

(PECL yaf >=1.0.0)

Yaf_Config_Ini::next — The next purpose

Opis

public void Yaf_Config_Ini::next ( 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

Yaf_Config_Ini::key
Yaf_Config_Ini::offsetExists
Yaf_Config_Ini


The offsetExists purpose

Yaf_Config_Ini::next
Yaf_Config_Ini::offsetGet
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::offsetExists

(PECL yaf >=1.0.0)

Yaf_Config_Ini::offsetExists — The offsetExists purpose

Opis

public void Yaf_Config_Ini::offsetExists ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Ini::next
Yaf_Config_Ini::offsetGet
Yaf_Config_Ini


The offsetGet purpose

Yaf_Config_Ini::offsetExists
Yaf_Config_Ini::offsetSet
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::offsetGet

(PECL yaf >=1.0.0)

Yaf_Config_Ini::offsetGet — The offsetGet purpose

Opis

public void Yaf_Config_Ini::offsetGet ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Ini::offsetExists
Yaf_Config_Ini::offsetSet
Yaf_Config_Ini


The offsetSet purpose

Yaf_Config_Ini::offsetGet
Yaf_Config_Ini::offsetUnset
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::offsetSet

(PECL yaf >=1.0.0)

Yaf_Config_Ini::offsetSet — The offsetSet purpose

Opis

public void Yaf_Config_Ini::offsetSet ( string $name , string $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_Config_Ini::offsetGet
Yaf_Config_Ini::offsetUnset
Yaf_Config_Ini


The offsetUnset purpose

Yaf_Config_Ini::offsetSet
Yaf_Config_Ini::readonly
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::offsetUnset

(PECL yaf >=1.0.0)

Yaf_Config_Ini::offsetUnset — The offsetUnset purpose

Opis

public void Yaf_Config_Ini::offsetUnset ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Ini::offsetSet
Yaf_Config_Ini::readonly
Yaf_Config_Ini


The readonly purpose

Yaf_Config_Ini::offsetUnset
Yaf_Config_Ini::rewind
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::readonly

(PECL yaf >=1.0.0)

Yaf_Config_Ini::readonly — The readonly purpose

Opis

public void Yaf_Config_Ini::readonly ( 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

Yaf_Config_Ini::offsetUnset
Yaf_Config_Ini::rewind
Yaf_Config_Ini


The rewind purpose

Yaf_Config_Ini::readonly
Yaf_Config_Ini::__set
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::rewind

(PECL yaf >=1.0.0)

Yaf_Config_Ini::rewind — The rewind purpose

Opis

public void Yaf_Config_Ini::rewind ( 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

Yaf_Config_Ini::readonly
Yaf_Config_Ini::__set
Yaf_Config_Ini


The __set purpose

Yaf_Config_Ini::rewind
Yaf_Config_Ini::toArray
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::__set

(PECL yaf >=1.0.0)

Yaf_Config_Ini::__set — The __set purpose

Opis

public void Yaf_Config_Ini::__set ( string $name , mixed $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_Config_Ini::rewind
Yaf_Config_Ini::toArray
Yaf_Config_Ini


The toArray purpose

Yaf_Config_Ini::__set
Yaf_Config_Ini::valid
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::toArray

(PECL yaf >=1.0.0)

Yaf_Config_Ini::toArray — The toArray purpose

Opis

public void Yaf_Config_Ini::toArray ( 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

Yaf_Config_Ini::__set
Yaf_Config_Ini::valid
Yaf_Config_Ini


The valid purpose

Yaf_Config_Ini::toArray
Yaf_Config_Simple
Yaf_Config_Ini
PHP Manual

Yaf_Config_Ini::valid

(PECL yaf >=1.0.0)

Yaf_Config_Ini::valid — The valid purpose

Opis

public void Yaf_Config_Ini::valid ( 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

Yaf_Config_Ini::toArray
Yaf_Config_Simple
Yaf_Config_Ini


The Yaf_Config_Simple class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Config_Simple extends Yaf_Config_Abstract implements Iterator , Traversable , ArrayAccess , Countable {
/* Właściwości */
protected $_readonly ;
/* Metody */
public __construct ( string $config_file [, string $section ] )
public void count ( void )
public void current ( void )
public void __get ([ string $name ] )
public void __isset ( string $name )
public void key ( void )
public void next ( void )
public void offsetExists ( string $name )
public void offsetGet ( string $name )
public void offsetSet ( string $name , string $value )
public void offsetUnset ( string $name )
public void readonly ( void )
public void rewind ( void )
public void __set ( string $name , string $value )
public void toArray ( void )
public void valid ( void )
/* Metody dziedziczone */
abstract public mixed Yaf_Config_Abstract::get ( string $name , mixed $value )
abstract public bool Yaf_Config_Abstract::readonly ( void )
abstract public Yaf_Config_Abstract Yaf_Config_Abstract::set ( void )
abstract public array Yaf_Config_Abstract::toArray ( void )
}

Właściwości

_config

_readonly

Spis treści

  • Yaf_Config_Simple::__construct — The __construct purpose
  • Yaf_Config_Simple::count — The count purpose
  • Yaf_Config_Simple::current — The current purpose
  • Yaf_Config_Simple::__get — The __get purpose
  • Yaf_Config_Simple::__isset — The __isset purpose
  • Yaf_Config_Simple::key — The key purpose
  • Yaf_Config_Simple::next — The next purpose
  • Yaf_Config_Simple::offsetExists — The offsetExists purpose
  • Yaf_Config_Simple::offsetGet — The offsetGet purpose
  • Yaf_Config_Simple::offsetSet — The offsetSet purpose
  • Yaf_Config_Simple::offsetUnset — The offsetUnset purpose
  • Yaf_Config_Simple::readonly — The readonly purpose
  • Yaf_Config_Simple::rewind — The rewind purpose
  • Yaf_Config_Simple::__set — The __set purpose
  • Yaf_Config_Simple::toArray — The toArray purpose
  • Yaf_Config_Simple::valid — The valid purpose
Yaf_Config_Ini::valid
Yaf_Config_Simple::__construct
Yaf


The __construct purpose

Yaf_Config_Simple
Yaf_Config_Simple::count
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::__construct

(PECL yaf >=1.0.0)

Yaf_Config_Simple::__construct — The __construct purpose

Opis

public Yaf_Config_Simple::__construct ( string $config_file [, string $section ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

config_file

section

Zwracane wartości

Yaf_Config_Simple
Yaf_Config_Simple::count
Yaf_Config_Simple


The count purpose

Yaf_Config_Simple::__construct
Yaf_Config_Simple::current
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::count

(PECL yaf >=1.0.0)

Yaf_Config_Simple::count — The count purpose

Opis

public void Yaf_Config_Simple::count ( 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

Yaf_Config_Simple::__construct
Yaf_Config_Simple::current
Yaf_Config_Simple


The current purpose

Yaf_Config_Simple::count
Yaf_Config_Simple::__get
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::current

(PECL yaf >=1.0.0)

Yaf_Config_Simple::current — The current purpose

Opis

public void Yaf_Config_Simple::current ( 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

Yaf_Config_Simple::count
Yaf_Config_Simple::__get
Yaf_Config_Simple


The __get purpose

Yaf_Config_Simple::current
Yaf_Config_Simple::__isset
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::__get

(PECL yaf >=1.0.0)

Yaf_Config_Simple::__get — The __get purpose

Opis

public void Yaf_Config_Simple::__get ([ string $name ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Simple::current
Yaf_Config_Simple::__isset
Yaf_Config_Simple


The __isset purpose

Yaf_Config_Simple::__get
Yaf_Config_Simple::key
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::__isset

(PECL yaf >=1.0.0)

Yaf_Config_Simple::__isset — The __isset purpose

Opis

public void Yaf_Config_Simple::__isset ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Simple::__get
Yaf_Config_Simple::key
Yaf_Config_Simple


The key purpose

Yaf_Config_Simple::__isset
Yaf_Config_Simple::next
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::key

(PECL yaf >=1.0.0)

Yaf_Config_Simple::key — The key purpose

Opis

public void Yaf_Config_Simple::key ( 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

Yaf_Config_Simple::__isset
Yaf_Config_Simple::next
Yaf_Config_Simple


The next purpose

Yaf_Config_Simple::key
Yaf_Config_Simple::offsetExists
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::next

(PECL yaf >=1.0.0)

Yaf_Config_Simple::next — The next purpose

Opis

public void Yaf_Config_Simple::next ( 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

Yaf_Config_Simple::key
Yaf_Config_Simple::offsetExists
Yaf_Config_Simple


The offsetExists purpose

Yaf_Config_Simple::next
Yaf_Config_Simple::offsetGet
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::offsetExists

(PECL yaf >=1.0.0)

Yaf_Config_Simple::offsetExists — The offsetExists purpose

Opis

public void Yaf_Config_Simple::offsetExists ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Simple::next
Yaf_Config_Simple::offsetGet
Yaf_Config_Simple


The offsetGet purpose

Yaf_Config_Simple::offsetExists
Yaf_Config_Simple::offsetSet
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::offsetGet

(PECL yaf >=1.0.0)

Yaf_Config_Simple::offsetGet — The offsetGet purpose

Opis

public void Yaf_Config_Simple::offsetGet ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Simple::offsetExists
Yaf_Config_Simple::offsetSet
Yaf_Config_Simple


The offsetSet purpose

Yaf_Config_Simple::offsetGet
Yaf_Config_Simple::offsetUnset
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::offsetSet

(PECL yaf >=1.0.0)

Yaf_Config_Simple::offsetSet — The offsetSet purpose

Opis

public void Yaf_Config_Simple::offsetSet ( string $name , string $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_Config_Simple::offsetGet
Yaf_Config_Simple::offsetUnset
Yaf_Config_Simple


The offsetUnset purpose

Yaf_Config_Simple::offsetSet
Yaf_Config_Simple::readonly
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::offsetUnset

(PECL yaf >=1.0.0)

Yaf_Config_Simple::offsetUnset — The offsetUnset purpose

Opis

public void Yaf_Config_Simple::offsetUnset ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Config_Simple::offsetSet
Yaf_Config_Simple::readonly
Yaf_Config_Simple


The readonly purpose

Yaf_Config_Simple::offsetUnset
Yaf_Config_Simple::rewind
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::readonly

(PECL yaf >=1.0.0)

Yaf_Config_Simple::readonly — The readonly purpose

Opis

public void Yaf_Config_Simple::readonly ( 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

Yaf_Config_Simple::offsetUnset
Yaf_Config_Simple::rewind
Yaf_Config_Simple


The rewind purpose

Yaf_Config_Simple::readonly
Yaf_Config_Simple::__set
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::rewind

(PECL yaf >=1.0.0)

Yaf_Config_Simple::rewind — The rewind purpose

Opis

public void Yaf_Config_Simple::rewind ( 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

Yaf_Config_Simple::readonly
Yaf_Config_Simple::__set
Yaf_Config_Simple


The __set purpose

Yaf_Config_Simple::rewind
Yaf_Config_Simple::toArray
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::__set

(PECL yaf >=1.0.0)

Yaf_Config_Simple::__set — The __set purpose

Opis

public void Yaf_Config_Simple::__set ( string $name , string $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_Config_Simple::rewind
Yaf_Config_Simple::toArray
Yaf_Config_Simple


The toArray purpose

Yaf_Config_Simple::__set
Yaf_Config_Simple::valid
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::toArray

(PECL yaf >=1.0.0)

Yaf_Config_Simple::toArray — The toArray purpose

Opis

public void Yaf_Config_Simple::toArray ( 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

Yaf_Config_Simple::__set
Yaf_Config_Simple::valid
Yaf_Config_Simple


The valid purpose

Yaf_Config_Simple::toArray
Yaf_Controller_Abstract
Yaf_Config_Simple
PHP Manual

Yaf_Config_Simple::valid

(PECL yaf >=1.0.0)

Yaf_Config_Simple::valid — The valid purpose

Opis

public void Yaf_Config_Simple::valid ( 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

Yaf_Config_Simple::toArray
Yaf_Controller_Abstract
Yaf_Config_Simple


The Yaf_Controller_Abstract class

(No version information available, might only be in SVN)

Wstęp

Yaf_Controller_Abstract is the heart of Yaf's system. MVC stands for Model-View-Controller and is a design pattern targeted at separating application logic from display logic.

Every custom controller shall inherit Yaf_Controller_Abstract.

You will find that you can not define __construct function for your custom controller, thus, Yaf_Controller_Abstract provides a magic method: Yaf_Controller_Abstract::init().

If you have defined a init() method in your custom controller, it will be called as long as the controller was instantiated.

Action may have arguments, when a request coming, if there are the same name variable in the request parameters(see Yaf_Request_Abstract::getParam()) after routed, Yaf will pass them to the action method(see Yaf_Action_Abstract::execute()).

Krótki opis klasy

abstract Yaf_Controller_Abstract {
/* Właściwości */
public $actions ;
protected $_module ;
protected $_name ;
protected $_request ;
protected $_response ;
protected $_invoke_args ;
protected $_view ;
/* Metody */
final private void __clone ( void )
final private __construct ( void )
final protected void display ( string $tpl [, array $parameters ] )
final public void forward ( string $module [, string $controller [, string $action [, array $paramters ]]] )
final public void getInvokeArg ( string $name )
final public void getInvokeArgs ( void )
final public void getModuleName ( void )
final public void getRequest ( void )
final public void getResponse ( void )
final public void getView ( void )
final public void getViewpath ( void )
final public void initView ([ array $options ] )
final public void redirect ( string $url )
final protected void render ( string $tpl [, array $parameters ] )
final public void setViewpath ( string $view_directory )
}

Właściwości

actions

You can also define a action method in a separate PHP script by using this property and Yaf_Action_Abstract.

Przykład #1 define action in a separate file

<?php
class IndexController extends Yaf_Controller_Abstract {
    protected $actions = array(
        /** now dummyAction is defined in a separate file */
        "dummy" => "actions/Dummy_action.php",
    );

    /* action method may have arguments */
    public indexAction($name, $id) {
       assert($name == $this->getRequest()->getParam("name"));
       assert($id   == $this->_request->getParam("id"));
    }
}
?>

Przykład #2 Dummy_action.php

<?php
class DummyAction extends Yaf_Action_Abstract {
    /* a action class shall define this method  as the entry point */
    public execute() {
    }
}
?>

_module

module name

_name

_request

the request object

_response

_invoke_args

_view

view engine object

Spis treści

  • Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned
  • Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor
  • Yaf_Controller_Abstract::display — The display purpose
  • Yaf_Controller_Abstract::forward — The forward purpose
  • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
  • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
  • Yaf_Controller_Abstract::getModuleName — The getModuleName purpose
  • Yaf_Controller_Abstract::getRequest — The getRequest purpose
  • Yaf_Controller_Abstract::getResponse — The getResponse purpose
  • Yaf_Controller_Abstract::getView — The getView purpose
  • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
  • Yaf_Controller_Abstract::initView — The initView purpose
  • Yaf_Controller_Abstract::redirect — The redirect purpose
  • Yaf_Controller_Abstract::render — The render purpose
  • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose
Yaf_Config_Simple::valid
Yaf_Controller_Abstract::__clone
Yaf


Yaf_Controller_Abstract can not be cloned

Yaf_Controller_Abstract
Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::__clone

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned

Opis

final private void Yaf_Controller_Abstract::__clone ( 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

Yaf_Controller_Abstract
Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract


Yaf_Controller_Abstract constructor

Yaf_Controller_Abstract::__clone
Yaf_Controller_Abstract::display
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::__construct

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor

Opis

final private Yaf_Controller_Abstract::__construct ( 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

Yaf_Controller_Abstract::__clone
Yaf_Controller_Abstract::display
Yaf_Controller_Abstract


The display purpose

Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::display

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::display — The display purpose

Opis

final protected void Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

tpl

parameters

Zwracane wartości

Yaf_Controller_Abstract::__construct
Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract


The forward purpose

Yaf_Controller_Abstract::display
Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::forward

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::forward — The forward purpose

Opis

final public void Yaf_Controller_Abstract::forward ( string $module [, string $controller [, string $action [, array $paramters ]]] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

module

controller

action

paramters

Zwracane wartości

Yaf_Controller_Abstract::display
Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract


The getInvokeArg purpose

Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getInvokeArg

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose

Opis

final public void Yaf_Controller_Abstract::getInvokeArg ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Controller_Abstract::forward
Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract


The getInvokeArgs purpose

Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getInvokeArgs

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose

Opis

final public void Yaf_Controller_Abstract::getInvokeArgs ( 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

Yaf_Controller_Abstract::getInvokeArg
Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract


The getModuleName purpose

Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getModuleName

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getModuleName — The getModuleName purpose

Opis

final public void Yaf_Controller_Abstract::getModuleName ( 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

Yaf_Controller_Abstract::getInvokeArgs
Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract


The getRequest purpose

Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getRequest

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getRequest — The getRequest purpose

Opis

final public void Yaf_Controller_Abstract::getRequest ( 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

Yaf_Controller_Abstract::getModuleName
Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract


The getResponse purpose

Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getResponse

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getResponse — The getResponse purpose

Opis

final public void Yaf_Controller_Abstract::getResponse ( 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

Yaf_Controller_Abstract::getRequest
Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract


The getView purpose

Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getView

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getView — The getView purpose

Opis

final public void Yaf_Controller_Abstract::getView ( 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

Yaf_Controller_Abstract::getResponse
Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract


The getViewpath purpose

Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::getViewpath

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::getViewpath — The getViewpath purpose

Opis

final public void Yaf_Controller_Abstract::getViewpath ( 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

Yaf_Controller_Abstract::getView
Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract


The initView purpose

Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::initView

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::initView — The initView purpose

Opis

final public void Yaf_Controller_Abstract::initView ([ array $options ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

options

Zwracane wartości

Yaf_Controller_Abstract::getViewpath
Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract


The redirect purpose

Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract::render
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::redirect

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::redirect — The redirect purpose

Opis

final public void Yaf_Controller_Abstract::redirect ( string $url )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

url

Zwracane wartości

Yaf_Controller_Abstract::initView
Yaf_Controller_Abstract::render
Yaf_Controller_Abstract


The render purpose

Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract::setViewpath
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::render

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::render — The render purpose

Opis

final protected void Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

tpl

parameters

Zwracane wartości

Yaf_Controller_Abstract::redirect
Yaf_Controller_Abstract::setViewpath
Yaf_Controller_Abstract


The setViewpath purpose

Yaf_Controller_Abstract::render
Yaf_Action_Abstract
Yaf_Controller_Abstract
PHP Manual

Yaf_Controller_Abstract::setViewpath

(PECL yaf >=1.0.0)

Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

Opis

final public void Yaf_Controller_Abstract::setViewpath ( string $view_directory )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

view_directory

Zwracane wartości

Yaf_Controller_Abstract::render
Yaf_Action_Abstract
Yaf_Controller_Abstract


The Yaf_Action_Abstract class

(No version information available, might only be in SVN)

Wstęp

A action can be defined in a separate file in Yaf(see Yaf_Controller_Abstract). that is a action method can also be a Yaf_Action_Abstract class.

Since there should be a entry point which can be called by Yaf (as of PHP 5.3, there is a new magic method __invoke, but Yaf is not only works with PHP 5.3+, Yaf choose another magic method execute), you must implement the abstract method Yaf_Action_Abstract::execute() in your custom action class.

Krótki opis klasy

Yaf_Action_Abstract extends Yaf_Controller_Abstract {
/* Właściwości */
protected $_controller ;
/* Metody */
abstract publicmixed execute ([ mixed $arg [, mixed $... ]] )
publicYaf_Controller_Abstract getController ( void )
/* Metody dziedziczone */
final private void Yaf_Controller_Abstract::__clone ( void )
final private Yaf_Controller_Abstract::__construct ( void )
final protected void Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] )
final public void Yaf_Controller_Abstract::forward ( string $module [, string $controller [, string $action [, array $paramters ]]] )
final public void Yaf_Controller_Abstract::getInvokeArg ( string $name )
final public void Yaf_Controller_Abstract::getInvokeArgs ( void )
final public void Yaf_Controller_Abstract::getModuleName ( void )
final public void Yaf_Controller_Abstract::getRequest ( void )
final public void Yaf_Controller_Abstract::getResponse ( void )
final public void Yaf_Controller_Abstract::getView ( void )
final public void Yaf_Controller_Abstract::getViewpath ( void )
final public void Yaf_Controller_Abstract::initView ([ array $options ] )
final public void Yaf_Controller_Abstract::redirect ( string $url )
final protected void Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] )
final public void Yaf_Controller_Abstract::setViewpath ( string $view_directory )
}

Właściwości

_module

_name

_request

_response

_invoke_args

_view

_controller

Spis treści

  • Yaf_Action_Abstract::execute — Execute the action
  • Yaf_Action_Abstract::getController — get controller instance
Yaf_Controller_Abstract::setViewpath
Yaf_Action_Abstract::execute
Yaf


Execute the action

Yaf_Action_Abstract
Yaf_Action_Abstract::getController
Yaf_Action_Abstract
PHP Manual

Yaf_Action_Abstract::execute

(PECL yaf >=1.0.0)

Yaf_Action_Abstract::execute — Execute the action

Opis

abstract publicmixed Yaf_Action_Abstract::execute ([ mixed $arg [, mixed $... ]] )

Yaf_Action_Abstract::execute() may have agruments.

Informacja:

The value retrived from the request is not safe. you should do some filtering work before you use it.

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

Przykłady

Przykład #1 Yaf_Action_Abstract::execute()example

<?php
/**
 * A controller example
 */
class ProductController extends Yaf_Controller_Abstract {
      protected $actions = array(
          "index" => "actions/Index.php",
      );
}
?>

Przykład #2 Yaf_Action_Abstract::execute()example

<?php
/**
 * ListAction
 */
class ListAction extends Yaf_Action_Abstract {
     public function execute ($name, $id) {
         assert($name == $this->getRequest()->getParam("name"));
         assert($id   == $this->getRequest()->getParam("id"));
     }
}
?>

Powyższy przykład wyświetli coś podobnego do:

/**
 * Now assuming we are using the Yaf_Route_Static route
 * for request: http://yourdomain/product/list/name/yaf/id/22
 * will result:
 */
 bool(true)
 bool(true)

Zobacz też:

Yaf_Action_Abstract
Yaf_Action_Abstract::getController
Yaf_Action_Abstract


get controller instance

Yaf_Action_Abstract::execute
Yaf_View_Interface
Yaf_Action_Abstract
PHP Manual

Yaf_Action_Abstract::getController

(PECL yaf >=1.0.0)

Yaf_Action_Abstract::getController — get controller instance

Opis

publicYaf_Controller_Abstract Yaf_Action_Abstract::getController ( void )

Retrive the controller object.

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

Yaf_Action_Abstract::execute
Yaf_View_Interface
Yaf_Action_Abstract


The Yaf_View_Interface class

(No version information available, might only be in SVN)

Wstęp

Yaf provides a ability for developers to use coustom view engine instead of build-in engine which is Yaf_View_Simple. There is a example to explain how to do this, please see Yaf_Dispatcher::setView().

Krótki opis klasy

Yaf_View_Interface {
/* Metody */
abstract public bool assign ( string $name [, string $value ] )
abstract public bool display ( string $tpl [, array $tpl_vars ] )
abstract public void getScriptPath ( void )
abstract public string render ( string $tpl [, array $tpl_vars ] )
abstract public void setScriptPath ( string $template_dir )
}

Spis treści

  • Yaf_View_Interface::assign — Assign value to View engine
  • Yaf_View_Interface::display — Render and output a template
  • Yaf_View_Interface::getScriptPath — The getScriptPath purpose
  • Yaf_View_Interface::render — Render a template
  • Yaf_View_Interface::setScriptPath — The setScriptPath purpose
Yaf_Action_Abstract::getController
Yaf_View_Interface::assign
Yaf


Assign value to View engine

Yaf_View_Interface
Yaf_View_Interface::display
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::assign

(PECL yaf >=1.0.0)

Yaf_View_Interface::assign — Assign value to View engine

Opis

abstract public bool Yaf_View_Interface::assign ( string $name [, string $value ] )

Assigan values to View engine, then the value can access directly by name in template.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_View_Interface
Yaf_View_Interface::display
Yaf_View_Interface


Render and output a template

Yaf_View_Interface::assign
Yaf_View_Interface::getScriptPath
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::display

(PECL yaf >=1.0.0)

Yaf_View_Interface::display — Render and output a template

Opis

abstract public bool Yaf_View_Interface::display ( string $tpl [, array $tpl_vars ] )

Render a template and output the result immediatly.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

tpl

tpl_vars

Zwracane wartości

Yaf_View_Interface::assign
Yaf_View_Interface::getScriptPath
Yaf_View_Interface


The getScriptPath purpose

Yaf_View_Interface::display
Yaf_View_Interface::render
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::getScriptPath

(PECL yaf >=1.0.0)

Yaf_View_Interface::getScriptPath — The getScriptPath purpose

Opis

abstract public void Yaf_View_Interface::getScriptPath ( 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

Yaf_View_Interface::display
Yaf_View_Interface::render
Yaf_View_Interface


Render a template

Yaf_View_Interface::getScriptPath
Yaf_View_Interface::setScriptPath
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::render

(PECL yaf >=1.0.0)

Yaf_View_Interface::render — Render a template

Opis

abstract public string Yaf_View_Interface::render ( string $tpl [, array $tpl_vars ] )

Render a template and return the result.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

tpl

tpl_vars

Zwracane wartości

Yaf_View_Interface::getScriptPath
Yaf_View_Interface::setScriptPath
Yaf_View_Interface


The setScriptPath purpose

Yaf_View_Interface::render
Yaf_View_Simple
Yaf_View_Interface
PHP Manual

Yaf_View_Interface::setScriptPath

(PECL yaf >=1.0.0)

Yaf_View_Interface::setScriptPath — The setScriptPath purpose

Opis

abstract public void Yaf_View_Interface::setScriptPath ( string $template_dir )

Set the templates base directory, this is usually called by Yaf_Dispatcher

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

template_dir

A absolute path to the template directory, by default, Yaf_Dispatcher use application.directory . "/views" as this paramter.

Zwracane wartości

Yaf_View_Interface::render
Yaf_View_Simple
Yaf_View_Interface


The Yaf_View_Simple class

(No version information available, might only be in SVN)

Wstęp

Yaf_View_Simple is the built-in template engine in Yaf, it is a simple but fast template engine, and only support PHP script template.

Krótki opis klasy

Yaf_View_Simple implements Yaf_View_Interface {
/* Właściwości */
protected $_tpl_vars ;
protected $_tpl_dir ;
/* Metody */
public bool assign ( string $name [, mixed $value ] )
public bool assignRef ( string $name , mixed &$value )
public __construct ( string $tempalte_dir [, array $options ] )
public bool display ( string $tpl [, array $tpl_vars ] )
public void __get ( string $name )
public string getScriptPath ( void )
public void __isset ( string $name )
public string render ( string $tpl [, array $tpl_vars ] )
public void __set ( string $name , mixed $value )
public bool setScriptPath ( string $template_dir )
}

Właściwości

_tpl_vars

_tpl_dir

Spis treści

  • Yaf_View_Simple::assign — Assign values
  • Yaf_View_Simple::assignRef — The assignRef purpose
  • Yaf_View_Simple::__construct — The __construct purpose
  • Yaf_View_Simple::display — Render and dispaly
  • Yaf_View_Simple::__get — The __get purpose
  • Yaf_View_Simple::getScriptPath — Get template base directory
  • Yaf_View_Simple::__isset — The __isset purpose
  • Yaf_View_Simple::render — Render template
  • Yaf_View_Simple::__set — Set value to engine
  • Yaf_View_Simple::setScriptPath — Set tempalte base directory
Yaf_View_Interface::setScriptPath
Yaf_View_Simple::assign
Yaf


Assign values

Yaf_View_Simple
Yaf_View_Simple::assignRef
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::assign

(PECL yaf >=1.0.0)

Yaf_View_Simple::assign — Assign values

Opis

public bool Yaf_View_Simple::assign ( string $name [, mixed $value ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

A string or an array.

if is string, then the next argument $value is required.

value

mixed value

Zwracane wartości

Przykłady

Przykład #1 Yaf_View_Simple::assign()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->assign("foo", "bar");
        $this->_view->assign( array( "key" => "value", "name" => "value"));
    }
?>

Przykład #2 template()example

<html>
 <head>
  <title><?php echo $foo; ?></title>
 </head>
<body>
  <?php
    foreach ($this->_tpl_vars as $name => value) {
         echo $$name; // or echo $this->_tpl_vars[$name];
    }
  ?>
</body>
</html>

Zobacz też:

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::assign() - Assign value to View engine
  • Yaf_View_Simple::__set() - Set value to engine
Yaf_View_Simple
Yaf_View_Simple::assignRef
Yaf_View_Simple


The assignRef purpose

Yaf_View_Simple::assign
Yaf_View_Simple::__construct
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::assignRef

(PECL yaf >=1.0.0)

Yaf_View_Simple::assignRef — The assignRef purpose

Opis

public bool Yaf_View_Simple::assignRef ( string $name , mixed &$value )

unlike Yaf_View_Simple::assign(), this method assign a ref value to engine.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

A string name which will be used to access the value in the tempalte.

value

mixed value

Zwracane wartości

Przykłady

Przykład #1 Yaf_View_Simple::assignRef()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $value = "bar";
        $this->getView()->assign("foo", $value);

        /* plz note that there was a bug before Yaf 2.1.4,
         * which make following output "bar";
         */
        $dummy = $this->getView()->render("index/index.phtml");
        echo $value;

        //prevent the auto-render
        Yaf_Dispatcher::getInstance()->autoRender(FALSE);
    }
?>

Przykład #2 template()example

<html>
 <head>
  <title><?php echo $foo;  $foo = "changed"; ?></title>
 </head>
<body>
</body>
</html>

Powyższy przykład wyświetli coś podobnego do:

/* access the index controller will result: */
changed

Zobacz też:

  • Yaf_View_Simple::assign() - Assign values
  • Yaf_View_Simple::__set() - Set value to engine
Yaf_View_Simple::assign
Yaf_View_Simple::__construct
Yaf_View_Simple


The __construct purpose

Yaf_View_Simple::assignRef
Yaf_View_Simple::display
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__construct

(PECL yaf >=1.0.0)

Yaf_View_Simple::__construct — The __construct purpose

Opis

public Yaf_View_Simple::__construct ( string $tempalte_dir [, array $options ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

tempalte_dir

The base directory of the templates, by default, it is APPLICATOIN . "/views" for Yaf.

options

Zwracane wartości

Yaf_View_Simple::assignRef
Yaf_View_Simple::display
Yaf_View_Simple


Render and dispaly

Yaf_View_Simple::__construct
Yaf_View_Simple::__get
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::display

(PECL yaf >=1.0.0)

Yaf_View_Simple::display — Render and dispaly

Opis

public bool Yaf_View_Simple::display ( string $tpl [, array $tpl_vars ] )

Render a template and dispaly the result instantly.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

tpl

tpl_vars

Zwracane wartości

Yaf_View_Simple::__construct
Yaf_View_Simple::__get
Yaf_View_Simple


The __get purpose

Yaf_View_Simple::display
Yaf_View_Simple::getScriptPath
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__get

(PECL yaf >=1.0.0)

Yaf_View_Simple::__get — The __get purpose

Opis

public void Yaf_View_Simple::__get ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_View_Simple::display
Yaf_View_Simple::getScriptPath
Yaf_View_Simple


Get template base directory

Yaf_View_Simple::__get
Yaf_View_Simple::__isset
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::getScriptPath

(PECL yaf >=1.0.0)

Yaf_View_Simple::getScriptPath — Get template base directory

Opis

public string Yaf_View_Simple::getScriptPath ( 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

Yaf_View_Simple::__get
Yaf_View_Simple::__isset
Yaf_View_Simple


The __isset purpose

Yaf_View_Simple::getScriptPath
Yaf_View_Simple::render
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__isset

(PECL yaf >=1.0.0)

Yaf_View_Simple::__isset — The __isset purpose

Opis

public void Yaf_View_Simple::__isset ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_View_Simple::getScriptPath
Yaf_View_Simple::render
Yaf_View_Simple


Render template

Yaf_View_Simple::__isset
Yaf_View_Simple::__set
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::render

(PECL yaf >=1.0.0)

Yaf_View_Simple::render — Render template

Opis

public string Yaf_View_Simple::render ( string $tpl [, array $tpl_vars ] )

Render a tempalte and return the result.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

tpl

tpl_vars

Zwracane wartości

Yaf_View_Simple::__isset
Yaf_View_Simple::__set
Yaf_View_Simple


Set value to engine

Yaf_View_Simple::render
Yaf_View_Simple::setScriptPath
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::__set

(PECL yaf >=1.0.0)

Yaf_View_Simple::__set — Set value to engine

Opis

public void Yaf_View_Simple::__set ( string $name , mixed $value )

This is a easier way to instead of Yaf_View_Simple::assign().

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

A string value name.

value

Mixed value.

Zwracane wartości

Przykłady

Przykład #1 Yaf_View_Simple::__set()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->foo = "bar"; // same as assign("foo", "bar");
    }
?>

Zobacz też:

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::assign() - Assign value to View engine
Yaf_View_Simple::render
Yaf_View_Simple::setScriptPath
Yaf_View_Simple


Set tempalte base directory

Yaf_View_Simple::__set
Yaf_Loader
Yaf_View_Simple
PHP Manual

Yaf_View_Simple::setScriptPath

(PECL yaf >=1.0.0)

Yaf_View_Simple::setScriptPath — Set tempalte base directory

Opis

public bool Yaf_View_Simple::setScriptPath ( string $template_dir )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

template_dir

Zwracane wartości

Yaf_View_Simple::__set
Yaf_Loader
Yaf_View_Simple


The Yaf_Loader class

(No version information available, might only be in SVN)

Wstęp

Yaf_Loader introduces a comprehensive autoloading solution for Yaf.

The first time an instance of Yaf_Application is retrieved, Yaf_Loader will instance a singleton, and registers itself with spl_autoload. You retrieve an instance using the Yaf_Loader::getInstance()

Yaf_Loader attempt to load a class only one shot, if failed, depend on yaf.use_spl_auload, if this config is On Yaf_Loader::autoload() will return FALSE, thus give the chance to other autoload function. if it is Off (by default), Yaf_Loader::autoload() will return TRUE, and more important is that a very usefull warning will be triggerd (very usefull to find out why a class could not be loaded).

Informacja:

Please keep yaf.use_spl_autoload Off unless there is some library have their own autoload mechanism and impossible to rewrite it.

By default, Yaf_Loader assume all library (class defined script) store in the global library directory, which is defined in the php.ini(yaf.library).

If you want Yaf_Loader search some classes(libraries) in the local class directory(which is defined in application.ini, and by default, it is application.directory . "/libraray"), you should register the class prefix using the Yaf_Loader::registerLocalNameSpace()

Let's see some examples(assuming APPLICATION_PATH is application.directory):

Przykład #1 Config example

// Assuming the following configure in php.ini:
yaf.libraray = "/global_dir"

//Assuming the following configure in application.ini
application.libraray = APPLICATION_PATH "/library"
Assuming the following local name space registerd:

Przykład #2 Register localnamespace

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
     public function _initLoader($dispatcher) {
          Yaf_Loader::getInstance()->registerLocalNameSpace(array("Foo", "Bar"));
     }
?>
Then the autoload examples:

Przykład #3 Load class example

class Foo_Bar_Test =>
  // APPLICATION_PATH/library/Foo/Bar/Test.php

class GLO_Name  =>
  // /global_dir/Glo/Name.php

class BarNon_Test
  // /global_dir/Barnon/Test.php
As of PHP 5.3, you can use namespace:

Przykład #4 Load namespace class example

class \Foo\Bar\Dummy =>
   // APPLICATION_PATH/library/Foo/Bar/Dummy.php

class \FooBar\Bar\Dummy =>
   // /global_dir/FooBar/Bar/Dummy.php

You may noticed that all the folder wth the first letter capitalized, you can make them lowercase by set yaf.lowcase_path = On in php.ini

Yaf_Loader is also designed to load the MVC classes, and the rule is:

Przykład #5 MVC class loading example

Controller Classes =>
// APPLICATION_PATH/controllers/

Model Classes =>
// APPLICATION_PATH/models/

Plugin Classes =>
// APPLICATION_PATH/plugins/
Yaf identify a class's suffix(this is by default, you can also change to the prefix by change the configure yaf.name_suffix) to decide whether it is a MVC class:

Przykład #6 MVC class distinctions

Controller Classes =>
    // ***Controller

Model Classes =>
    // ***Model

Plugin Classes =>
    // ***Plugin
some examples:

Przykład #7 MVC loading example

class IndexController
    // APPLICATION_PATH/controllers/Index.php

class DataModel =>
   // APPLICATION_PATH/models/Data.php

class DummyPlugin =>
  // APPLICATION_PATH/plugins/Dummy.php

class A_B_TestModel =>
  // APPLICATION_PATH/models/A/B/Test.php
also, the directory will be affected by yaf.lowcase_path.

Krótki opis klasy

Yaf_Loader {
/* Właściwości */
protected $_local_ns ;
protected $_library ;
protected $_global_library ;
static $_instance ;
/* Metody */
public void autoload ( void )
public void clearLocalNamespace ( void )
private void __clone ( void )
public __construct ( void )
public static void getInstance ( void )
public Yaf_Loader getLibraryPath ([ bool $is_global = false ] )
public void getLocalNamespace ( void )
public static void import ( void )
public void isLocalName ( void )
public void registerLocalNamespace ( void )
public Yaf_Loader setLibraryPath ( string $directory [, bool $is_global = false ] )
private void __sleep ( void )
private void __wakeup ( void )
}

Właściwości

_local_ns

_library

By default, this value is application.directory . "/library", you can change this either in the application.ini(application.library) or call to Yaf_Loader::setLibraryPath()

_global_library

_instance

Spis treści

  • Yaf_Loader::autoload — The autoload purpose
  • Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose
  • Yaf_Loader::__clone — The __clone purpose
  • Yaf_Loader::__construct — The __construct purpose
  • Yaf_Loader::getInstance — The getInstance purpose
  • Yaf_Loader::getLibraryPath — get the library path
  • Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose
  • Yaf_Loader::import — The import purpose
  • Yaf_Loader::isLocalName — The isLocalName purpose
  • Yaf_Loader::registerLocalNamespace — The registerLocalNamespace purpose
  • Yaf_Loader::setLibraryPath — Change the library path
  • Yaf_Loader::__sleep — The __sleep purpose
  • Yaf_Loader::__wakeup — The __wakeup purpose
Yaf_View_Simple::setScriptPath
Yaf_Loader::autoload
Yaf


The autoload purpose

Yaf_Loader
Yaf_Loader::clearLocalNamespace
Yaf_Loader
PHP Manual

Yaf_Loader::autoload

(PECL yaf >=1.0.0)

Yaf_Loader::autoload — The autoload purpose

Opis

public void Yaf_Loader::autoload ( 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

Yaf_Loader
Yaf_Loader::clearLocalNamespace
Yaf_Loader


The clearLocalNamespace purpose

Yaf_Loader::autoload
Yaf_Loader::__clone
Yaf_Loader
PHP Manual

Yaf_Loader::clearLocalNamespace

(PECL yaf >=1.0.0)

Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose

Opis

public void Yaf_Loader::clearLocalNamespace ( 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

Yaf_Loader::autoload
Yaf_Loader::__clone
Yaf_Loader


The __clone purpose

Yaf_Loader::clearLocalNamespace
Yaf_Loader::__construct
Yaf_Loader
PHP Manual

Yaf_Loader::__clone

(PECL yaf >=1.0.0)

Yaf_Loader::__clone — The __clone purpose

Opis

private void Yaf_Loader::__clone ( 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

Yaf_Loader::clearLocalNamespace
Yaf_Loader::__construct
Yaf_Loader


The __construct purpose

Yaf_Loader::__clone
Yaf_Loader::getInstance
Yaf_Loader
PHP Manual

Yaf_Loader::__construct

(PECL yaf >=1.0.0)

Yaf_Loader::__construct — The __construct purpose

Opis

public Yaf_Loader::__construct ( 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

Yaf_Loader::__clone
Yaf_Loader::getInstance
Yaf_Loader


The getInstance purpose

Yaf_Loader::__construct
Yaf_Loader::getLibraryPath
Yaf_Loader
PHP Manual

Yaf_Loader::getInstance

(PECL yaf >=1.0.0)

Yaf_Loader::getInstance — The getInstance purpose

Opis

public static void Yaf_Loader::getInstance ( 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

Yaf_Loader::__construct
Yaf_Loader::getLibraryPath
Yaf_Loader


get the library path

Yaf_Loader::getInstance
Yaf_Loader::getLocalNamespace
Yaf_Loader
PHP Manual

Yaf_Loader::getLibraryPath

(PECL yaf >=2.1.4)

Yaf_Loader::getLibraryPath — get the library path

Opis

public Yaf_Loader Yaf_Loader::getLibraryPath ([ bool $is_global = false ] )

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

Yaf_Loader::getInstance
Yaf_Loader::getLocalNamespace
Yaf_Loader


The getLocalNamespace purpose

Yaf_Loader::getLibraryPath
Yaf_Loader::import
Yaf_Loader
PHP Manual

Yaf_Loader::getLocalNamespace

(PECL yaf >=1.0.0)

Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose

Opis

public void Yaf_Loader::getLocalNamespace ( 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

Yaf_Loader::getLibraryPath
Yaf_Loader::import
Yaf_Loader


The import purpose

Yaf_Loader::getLocalNamespace
Yaf_Loader::isLocalName
Yaf_Loader
PHP Manual

Yaf_Loader::import

(PECL yaf >=1.0.0)

Yaf_Loader::import — The import purpose

Opis

public static void Yaf_Loader::import ( 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

Yaf_Loader::getLocalNamespace
Yaf_Loader::isLocalName
Yaf_Loader


The isLocalName purpose

Yaf_Loader::import
Yaf_Loader::registerLocalNamespace
Yaf_Loader
PHP Manual

Yaf_Loader::isLocalName

(PECL yaf >=1.0.0)

Yaf_Loader::isLocalName — The isLocalName purpose

Opis

public void Yaf_Loader::isLocalName ( 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

Yaf_Loader::import
Yaf_Loader::registerLocalNamespace
Yaf_Loader


The registerLocalNamespace purpose

Yaf_Loader::isLocalName
Yaf_Loader::setLibraryPath
Yaf_Loader
PHP Manual

Yaf_Loader::registerLocalNamespace

(PECL yaf >=1.0.0)

Yaf_Loader::registerLocalNamespace — The registerLocalNamespace purpose

Opis

public void Yaf_Loader::registerLocalNamespace ( 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

Yaf_Loader::isLocalName
Yaf_Loader::setLibraryPath
Yaf_Loader


Change the library path

Yaf_Loader::registerLocalNamespace
Yaf_Loader::__sleep
Yaf_Loader
PHP Manual

Yaf_Loader::setLibraryPath

(PECL yaf >=2.1.4)

Yaf_Loader::setLibraryPath — Change the library path

Opis

public Yaf_Loader Yaf_Loader::setLibraryPath ( string $directory [, bool $is_global = false ] )

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

Yaf_Loader::registerLocalNamespace
Yaf_Loader::__sleep
Yaf_Loader


The __sleep purpose

Yaf_Loader::setLibraryPath
Yaf_Loader::__wakeup
Yaf_Loader
PHP Manual

Yaf_Loader::__sleep

(PECL yaf >=1.0.0)

Yaf_Loader::__sleep — The __sleep purpose

Opis

private void Yaf_Loader::__sleep ( 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

Yaf_Loader::setLibraryPath
Yaf_Loader::__wakeup
Yaf_Loader


The __wakeup purpose

Yaf_Loader::__sleep
Yaf_Plugin_Abstract
Yaf_Loader
PHP Manual

Yaf_Loader::__wakeup

(PECL yaf >=1.0.0)

Yaf_Loader::__wakeup — The __wakeup purpose

Opis

private void Yaf_Loader::__wakeup ( 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

Yaf_Loader::__sleep
Yaf_Plugin_Abstract
Yaf_Loader


The Yaf_Plugin_Abstract class

(No version information available, might only be in SVN)

Wstęp

Plugins allow for easy extensibility and customization of the framework.

Plugins are classes. The actual class definition will vary based on the component -- you may need to implement this interface, but the fact remains that the plugin is itself a class.

A plugin could be loaded into Yaf by using Yaf_Dispatcher::registerPlugin(), after registerd, All the methods which the plugin implemented according to this interface, will be called at the proper time.

Krótki opis klasy

Yaf_Plugin_Abstract {
/* Metody */
public void dispatchLoopShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void dispatchLoopStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void postDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void preDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void preResponse ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void routerShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
public void routerStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )
}

Spis treści

  • Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup — The dispatchLoopStartup purpose
  • Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose
  • Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose
  • Yaf_Plugin_Abstract::preResponse — The preResponse purpose
  • Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose
  • Yaf_Plugin_Abstract::routerStartup — RouterStartup hook
Yaf_Loader::__wakeup
Yaf_Plugin_Abstract::dispatchLoopShutdown
Yaf


The dispatchLoopShutdown purpose

Yaf_Plugin_Abstract
Yaf_Plugin_Abstract::dispatchLoopStartup
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::dispatchLoopShutdown

(PECL yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose

Opis

public void Yaf_Plugin_Abstract::dispatchLoopShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

This is the latest hook in Yaf plugin hook system, if a custom plugin implement this method, then it will be called after the dispatch loop finished.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

response

Zwracane wartości

Zobacz też:

  • Yaf_Plugin_Abstract::routerStartup() - RouterStartup hook
  • Yaf_Plugin_Abstract::routerShutdown() - The routerShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - The dispatchLoopStartup purpose
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
Yaf_Plugin_Abstract
Yaf_Plugin_Abstract::dispatchLoopStartup
Yaf_Plugin_Abstract


The dispatchLoopStartup purpose

Yaf_Plugin_Abstract::dispatchLoopShutdown
Yaf_Plugin_Abstract::postDispatch
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::dispatchLoopStartup

(PECL yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopStartup — The dispatchLoopStartup purpose

Opis

public void Yaf_Plugin_Abstract::dispatchLoopStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

response

Zwracane wartości

Yaf_Plugin_Abstract::dispatchLoopShutdown
Yaf_Plugin_Abstract::postDispatch
Yaf_Plugin_Abstract


The postDispatch purpose

Yaf_Plugin_Abstract::dispatchLoopStartup
Yaf_Plugin_Abstract::preDispatch
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::postDispatch

(PECL yaf >=1.0.0)

Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose

Opis

public void Yaf_Plugin_Abstract::postDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

response

Zwracane wartości

Yaf_Plugin_Abstract::dispatchLoopStartup
Yaf_Plugin_Abstract::preDispatch
Yaf_Plugin_Abstract


The preDispatch purpose

Yaf_Plugin_Abstract::postDispatch
Yaf_Plugin_Abstract::preResponse
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::preDispatch

(PECL yaf >=1.0.0)

Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose

Opis

public void Yaf_Plugin_Abstract::preDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

response

Zwracane wartości

Yaf_Plugin_Abstract::postDispatch
Yaf_Plugin_Abstract::preResponse
Yaf_Plugin_Abstract


The preResponse purpose

Yaf_Plugin_Abstract::preDispatch
Yaf_Plugin_Abstract::routerShutdown
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::preResponse

(PECL yaf >=1.0.0)

Yaf_Plugin_Abstract::preResponse — The preResponse purpose

Opis

public void Yaf_Plugin_Abstract::preResponse ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

response

Zwracane wartości

Yaf_Plugin_Abstract::preDispatch
Yaf_Plugin_Abstract::routerShutdown
Yaf_Plugin_Abstract


The routerShutdown purpose

Yaf_Plugin_Abstract::preResponse
Yaf_Plugin_Abstract::routerStartup
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::routerShutdown

(PECL yaf >=1.0.0)

Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose

Opis

public void Yaf_Plugin_Abstract::routerShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

This hook will be trigged after the route process finished, this hook is usually used for login check.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

response

Zwracane wartości

Przykłady

Przykład #1 Yaf_Plugin_Abstract::routerShutdown()example

<?php
class UserInitPlugin extends Yaf_Plugin_Abstract {

    public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
        $controller = $request->getControllerName();

        /**
         * Use access controller is unecessary for APIs
         */
        if (in_array(strtolower($controller), array(
            'api',
        ))) {
            return TRUE;
        }

        if (Yaf_Session::getInstance()->has("login")) {
            return TRUE;
        }

        /* Use access check failed, need to login */
        $response->redirect("http://yourdomain.com/login/");
        return FALSE;
    }
?>

Zobacz też:

  • Yaf_Plugin_Abstract::routerStartup() - RouterStartup hook
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - The dispatchLoopStartup purpose
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
  • Yaf_Plugin_Abstract::dispatchLoopShutdown() - The dispatchLoopShutdown purpose
Yaf_Plugin_Abstract::preResponse
Yaf_Plugin_Abstract::routerStartup
Yaf_Plugin_Abstract


RouterStartup hook

Yaf_Plugin_Abstract::routerShutdown
Yaf_Registry
Yaf_Plugin_Abstract
PHP Manual

Yaf_Plugin_Abstract::routerStartup

(PECL yaf >=1.0.0)

Yaf_Plugin_Abstract::routerStartup — RouterStartup hook

Opis

public void Yaf_Plugin_Abstract::routerStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response )

This is the earliest hook in Yaf plugin hook system, if a custom plugin implement this method, then it will be called before routing a request.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

response

Zwracane wartości

Zobacz też:

  • Yaf_Plugin_Abstract::routerShutdown() - The routerShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - The dispatchLoopStartup purpose
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
  • Yaf_Plugin_Abstract::dispatchLoopShutdown() - The dispatchLoopShutdown purpose
Yaf_Plugin_Abstract::routerShutdown
Yaf_Registry
Yaf_Plugin_Abstract


The Yaf_Registry class

(No version information available, might only be in SVN)

Wstęp

All methods of Yaf_Registry declared as static, making it unversally accessible. This provides the ability to get or set any custom data from anyway in your code as necessary.

Krótki opis klasy

Yaf_Registry {
/* Właściwości */
static $_instance ;
protected $_entries ;
/* Metody */
private void __clone ( void )
__construct ( void )
public static void del ( string $name )
public static void get ( string $name )
public static void has ( string $name )
public static void set ( string $name , string $value )
}

Właściwości

_instance

_entries

Spis treści

  • Yaf_Registry::__clone — The __clone purpose
  • Yaf_Registry::__construct — The __construct purpose
  • Yaf_Registry::del — The del purpose
  • Yaf_Registry::get — The get purpose
  • Yaf_Registry::has — The has purpose
  • Yaf_Registry::set — The set purpose
Yaf_Plugin_Abstract::routerStartup
Yaf_Registry::__clone
Yaf


The __clone purpose

Yaf_Registry
Yaf_Registry::__construct
Yaf_Registry
PHP Manual

Yaf_Registry::__clone

(PECL yaf >=1.0.0)

Yaf_Registry::__clone — The __clone purpose

Opis

private void Yaf_Registry::__clone ( 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

Yaf_Registry
Yaf_Registry::__construct
Yaf_Registry


The __construct purpose

Yaf_Registry::__clone
Yaf_Registry::del
Yaf_Registry
PHP Manual

Yaf_Registry::__construct

(PECL yaf >=1.0.0)

Yaf_Registry::__construct — The __construct purpose

Opis

Yaf_Registry::__construct ( 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

Yaf_Registry::__clone
Yaf_Registry::del
Yaf_Registry


The del purpose

Yaf_Registry::__construct
Yaf_Registry::get
Yaf_Registry
PHP Manual

Yaf_Registry::del

(PECL yaf >=1.0.0)

Yaf_Registry::del — The del purpose

Opis

public static void Yaf_Registry::del ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Registry::__construct
Yaf_Registry::get
Yaf_Registry


The get purpose

Yaf_Registry::del
Yaf_Registry::has
Yaf_Registry
PHP Manual

Yaf_Registry::get

(PECL yaf >=1.0.0)

Yaf_Registry::get — The get purpose

Opis

public static void Yaf_Registry::get ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Registry::del
Yaf_Registry::has
Yaf_Registry


The has purpose

Yaf_Registry::get
Yaf_Registry::set
Yaf_Registry
PHP Manual

Yaf_Registry::has

(PECL yaf >=1.0.0)

Yaf_Registry::has — The has purpose

Opis

public static void Yaf_Registry::has ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Registry::get
Yaf_Registry::set
Yaf_Registry


The set purpose

Yaf_Registry::has
Yaf_Request_Abstract
Yaf_Registry
PHP Manual

Yaf_Registry::set

(PECL yaf >=1.0.0)

Yaf_Registry::set — The set purpose

Opis

public static void Yaf_Registry::set ( string $name , string $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_Registry::has
Yaf_Request_Abstract
Yaf_Registry


The Yaf_Request_Abstract class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http ;
const string SCHEME_HTTPS = https ;
/* Właściwości */
public $module ;
public $controller ;
public $action ;
public $method ;
protected $params ;
protected $language ;
protected $_exception ;
protected $_base_uri ;
protected $uri ;
protected $dispatched ;
protected $routed ;
/* Metody */
public void getActionName ( void )
public void getBaseUri ( void )
public void getControllerName ( void )
public void getEnv ( string $name [, string $default ] )
public void getException ( void )
public void getLanguage ( void )
public void getMethod ( void )
public void getModuleName ( void )
public void getParam ( string $name [, string $default ] )
public void getParams ( void )
public void getRequestUri ( void )
public void getServer ( string $name [, string $default ] )
public void isCli ( void )
public void isDispatched ( void )
public void isGet ( void )
public void isHead ( void )
public void isOptions ( void )
public void isPost ( void )
public void isPut ( void )
public void isRouted ( void )
public void isXmlHttpRequest ( void )
public void setActionName ( string $action )
public void setBaseUri ( string $uir )
public void setControllerName ( string $controller )
public void setDispatched ( void )
public void setModuleName ( string $module )
public void setParam ( string $name [, string $value ] )
public void setRequestUri ( string $uir )
public void setRouted ([ string $flag ] )
}

Właściwości

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Stałe predefiniowane

Yaf_Request_Abstract::SCHEME_HTTP

Yaf_Request_Abstract::SCHEME_HTTPS

Spis treści

  • Yaf_Request_Abstract::getActionName — The getActionName purpose
  • Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose
  • Yaf_Request_Abstract::getControllerName — The getControllerName purpose
  • Yaf_Request_Abstract::getEnv — The getEnv purpose
  • Yaf_Request_Abstract::getException — The getException purpose
  • Yaf_Request_Abstract::getLanguage — The getLanguage purpose
  • Yaf_Request_Abstract::getMethod — The getMethod purpose
  • Yaf_Request_Abstract::getModuleName — The getModuleName purpose
  • Yaf_Request_Abstract::getParam — The getParam purpose
  • Yaf_Request_Abstract::getParams — The getParams purpose
  • Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose
  • Yaf_Request_Abstract::getServer — The getServer purpose
  • Yaf_Request_Abstract::isCli — The isCli purpose
  • Yaf_Request_Abstract::isDispatched — The isDispatched purpose
  • Yaf_Request_Abstract::isGet — The isGet purpose
  • Yaf_Request_Abstract::isHead — The isHead purpose
  • Yaf_Request_Abstract::isOptions — The isOptions purpose
  • Yaf_Request_Abstract::isPost — The isPost purpose
  • Yaf_Request_Abstract::isPut — The isPut purpose
  • Yaf_Request_Abstract::isRouted — The isRouted purpose
  • Yaf_Request_Abstract::isXmlHttpRequest — The isXmlHttpRequest purpose
  • Yaf_Request_Abstract::setActionName — The setActionName purpose
  • Yaf_Request_Abstract::setBaseUri — The setBaseUri purpose
  • Yaf_Request_Abstract::setControllerName — The setControllerName purpose
  • Yaf_Request_Abstract::setDispatched — The setDispatched purpose
  • Yaf_Request_Abstract::setModuleName — The setModuleName purpose
  • Yaf_Request_Abstract::setParam — The setParam purpose
  • Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose
  • Yaf_Request_Abstract::setRouted — The setRouted purpose
Yaf_Registry::set
Yaf_Request_Abstract::getActionName
Yaf


The getActionName purpose

Yaf_Request_Abstract
Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getActionName

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getActionName — The getActionName purpose

Opis

public void Yaf_Request_Abstract::getActionName ( 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

Yaf_Request_Abstract
Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract


The getBaseUri purpose

Yaf_Request_Abstract::getActionName
Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getBaseUri

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose

Opis

public void Yaf_Request_Abstract::getBaseUri ( 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

Yaf_Request_Abstract::getActionName
Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract


The getControllerName purpose

Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getControllerName

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getControllerName — The getControllerName purpose

Opis

public void Yaf_Request_Abstract::getControllerName ( 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

Yaf_Request_Abstract::getBaseUri
Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract


The getEnv purpose

Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract::getException
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getEnv

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getEnv — The getEnv purpose

Opis

public void Yaf_Request_Abstract::getEnv ( string $name [, string $default ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

default

Zwracane wartości

Yaf_Request_Abstract::getControllerName
Yaf_Request_Abstract::getException
Yaf_Request_Abstract


The getException purpose

Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract::getLanguage
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getException

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getException — The getException purpose

Opis

public void Yaf_Request_Abstract::getException ( 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

Yaf_Request_Abstract::getEnv
Yaf_Request_Abstract::getLanguage
Yaf_Request_Abstract


The getLanguage purpose

Yaf_Request_Abstract::getException
Yaf_Request_Abstract::getMethod
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getLanguage

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getLanguage — The getLanguage purpose

Opis

public void Yaf_Request_Abstract::getLanguage ( 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

Yaf_Request_Abstract::getException
Yaf_Request_Abstract::getMethod
Yaf_Request_Abstract


The getMethod purpose

Yaf_Request_Abstract::getLanguage
Yaf_Request_Abstract::getModuleName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getMethod

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getMethod — The getMethod purpose

Opis

public void Yaf_Request_Abstract::getMethod ( 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

Yaf_Request_Abstract::getLanguage
Yaf_Request_Abstract::getModuleName
Yaf_Request_Abstract


The getModuleName purpose

Yaf_Request_Abstract::getMethod
Yaf_Request_Abstract::getParam
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getModuleName

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getModuleName — The getModuleName purpose

Opis

public void Yaf_Request_Abstract::getModuleName ( 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

Yaf_Request_Abstract::getMethod
Yaf_Request_Abstract::getParam
Yaf_Request_Abstract


The getParam purpose

Yaf_Request_Abstract::getModuleName
Yaf_Request_Abstract::getParams
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getParam

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getParam — The getParam purpose

Opis

public void Yaf_Request_Abstract::getParam ( string $name [, string $default ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

default

Zwracane wartości

Yaf_Request_Abstract::getModuleName
Yaf_Request_Abstract::getParams
Yaf_Request_Abstract


The getParams purpose

Yaf_Request_Abstract::getParam
Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getParams

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getParams — The getParams purpose

Opis

public void Yaf_Request_Abstract::getParams ( 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

Yaf_Request_Abstract::getParam
Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract


The getRequestUri purpose

Yaf_Request_Abstract::getParams
Yaf_Request_Abstract::getServer
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getRequestUri

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose

Opis

public void Yaf_Request_Abstract::getRequestUri ( 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

Yaf_Request_Abstract::getParams
Yaf_Request_Abstract::getServer
Yaf_Request_Abstract


The getServer purpose

Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract::isCli
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::getServer

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::getServer — The getServer purpose

Opis

public void Yaf_Request_Abstract::getServer ( string $name [, string $default ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

default

Zwracane wartości

Yaf_Request_Abstract::getRequestUri
Yaf_Request_Abstract::isCli
Yaf_Request_Abstract


The isCli purpose

Yaf_Request_Abstract::getServer
Yaf_Request_Abstract::isDispatched
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isCli

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isCli — The isCli purpose

Opis

public void Yaf_Request_Abstract::isCli ( 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

Yaf_Request_Abstract::getServer
Yaf_Request_Abstract::isDispatched
Yaf_Request_Abstract


The isDispatched purpose

Yaf_Request_Abstract::isCli
Yaf_Request_Abstract::isGet
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isDispatched

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isDispatched — The isDispatched purpose

Opis

public void Yaf_Request_Abstract::isDispatched ( 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

Yaf_Request_Abstract::isCli
Yaf_Request_Abstract::isGet
Yaf_Request_Abstract


The isGet purpose

Yaf_Request_Abstract::isDispatched
Yaf_Request_Abstract::isHead
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isGet

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isGet — The isGet purpose

Opis

public void Yaf_Request_Abstract::isGet ( 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

Yaf_Request_Abstract::isDispatched
Yaf_Request_Abstract::isHead
Yaf_Request_Abstract


The isHead purpose

Yaf_Request_Abstract::isGet
Yaf_Request_Abstract::isOptions
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isHead

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isHead — The isHead purpose

Opis

public void Yaf_Request_Abstract::isHead ( 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

Yaf_Request_Abstract::isGet
Yaf_Request_Abstract::isOptions
Yaf_Request_Abstract


The isOptions purpose

Yaf_Request_Abstract::isHead
Yaf_Request_Abstract::isPost
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isOptions

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isOptions — The isOptions purpose

Opis

public void Yaf_Request_Abstract::isOptions ( 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

Yaf_Request_Abstract::isHead
Yaf_Request_Abstract::isPost
Yaf_Request_Abstract


The isPost purpose

Yaf_Request_Abstract::isOptions
Yaf_Request_Abstract::isPut
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isPost

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isPost — The isPost purpose

Opis

public void Yaf_Request_Abstract::isPost ( 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

Yaf_Request_Abstract::isOptions
Yaf_Request_Abstract::isPut
Yaf_Request_Abstract


The isPut purpose

Yaf_Request_Abstract::isPost
Yaf_Request_Abstract::isRouted
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isPut

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isPut — The isPut purpose

Opis

public void Yaf_Request_Abstract::isPut ( 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

Yaf_Request_Abstract::isPost
Yaf_Request_Abstract::isRouted
Yaf_Request_Abstract


The isRouted purpose

Yaf_Request_Abstract::isPut
Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isRouted

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isRouted — The isRouted purpose

Opis

public void Yaf_Request_Abstract::isRouted ( 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

Yaf_Request_Abstract::isPut
Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract


The isXmlHttpRequest purpose

Yaf_Request_Abstract::isRouted
Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::isXmlHttpRequest

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::isXmlHttpRequest — The isXmlHttpRequest purpose

Opis

public void Yaf_Request_Abstract::isXmlHttpRequest ( 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

Yaf_Request_Abstract::isRouted
Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract


The setActionName purpose

Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setActionName

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::setActionName — The setActionName purpose

Opis

public void Yaf_Request_Abstract::setActionName ( string $action )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

action

Zwracane wartości

Yaf_Request_Abstract::isXmlHttpRequest
Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract


The setBaseUri purpose

Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setBaseUri

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::setBaseUri — The setBaseUri purpose

Opis

public void Yaf_Request_Abstract::setBaseUri ( string $uir )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

uir

Zwracane wartości

Yaf_Request_Abstract::setActionName
Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract


The setControllerName purpose

Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract::setDispatched
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setControllerName

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::setControllerName — The setControllerName purpose

Opis

public void Yaf_Request_Abstract::setControllerName ( string $controller )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

controller

Zwracane wartości

Yaf_Request_Abstract::setBaseUri
Yaf_Request_Abstract::setDispatched
Yaf_Request_Abstract


The setDispatched purpose

Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract::setModuleName
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setDispatched

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::setDispatched — The setDispatched purpose

Opis

public void Yaf_Request_Abstract::setDispatched ( 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

Yaf_Request_Abstract::setControllerName
Yaf_Request_Abstract::setModuleName
Yaf_Request_Abstract


The setModuleName purpose

Yaf_Request_Abstract::setDispatched
Yaf_Request_Abstract::setParam
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setModuleName

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::setModuleName — The setModuleName purpose

Opis

public void Yaf_Request_Abstract::setModuleName ( string $module )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

module

Zwracane wartości

Yaf_Request_Abstract::setDispatched
Yaf_Request_Abstract::setParam
Yaf_Request_Abstract


The setParam purpose

Yaf_Request_Abstract::setModuleName
Yaf_Request_Abstract::setRequestUri
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setParam

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::setParam — The setParam purpose

Opis

public void Yaf_Request_Abstract::setParam ( string $name [, string $value ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_Request_Abstract::setModuleName
Yaf_Request_Abstract::setRequestUri
Yaf_Request_Abstract


The setRequestUri purpose

Yaf_Request_Abstract::setParam
Yaf_Request_Abstract::setRouted
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setRequestUri

(PECL yaf >=2.1.0)

Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose

Opis

public void Yaf_Request_Abstract::setRequestUri ( string $uir )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

uir

Zwracane wartości

Yaf_Request_Abstract::setParam
Yaf_Request_Abstract::setRouted
Yaf_Request_Abstract


The setRouted purpose

Yaf_Request_Abstract::setRequestUri
Yaf_Request_Http
Yaf_Request_Abstract
PHP Manual

Yaf_Request_Abstract::setRouted

(PECL yaf >=1.0.0)

Yaf_Request_Abstract::setRouted — The setRouted purpose

Opis

public void Yaf_Request_Abstract::setRouted ([ string $flag ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

flag

Zwracane wartości

Yaf_Request_Abstract::setRequestUri
Yaf_Request_Http
Yaf_Request_Abstract


The Yaf_Request_Http class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Request_Http extends Yaf_Request_Abstract {
/* Właściwości */
/* Metody */
private void __clone ( void )
__construct ( void )
public void get ( void )
public void getCookie ( void )
public void getFiles ( void )
public void getPost ( void )
public void getQuery ( void )
public void getRequest ( void )
public void isXmlHttpRequest ( void )
/* Metody dziedziczone */
public void Yaf_Request_Abstract::getActionName ( void )
public void Yaf_Request_Abstract::getBaseUri ( void )
public void Yaf_Request_Abstract::getControllerName ( void )
public void Yaf_Request_Abstract::getEnv ( string $name [, string $default ] )
public void Yaf_Request_Abstract::getException ( void )
public void Yaf_Request_Abstract::getLanguage ( void )
public void Yaf_Request_Abstract::getMethod ( void )
public void Yaf_Request_Abstract::getModuleName ( void )
public void Yaf_Request_Abstract::getParam ( string $name [, string $default ] )
public void Yaf_Request_Abstract::getParams ( void )
public void Yaf_Request_Abstract::getRequestUri ( void )
public void Yaf_Request_Abstract::getServer ( string $name [, string $default ] )
public void Yaf_Request_Abstract::isCli ( void )
public void Yaf_Request_Abstract::isDispatched ( void )
public void Yaf_Request_Abstract::isGet ( void )
public void Yaf_Request_Abstract::isHead ( void )
public void Yaf_Request_Abstract::isOptions ( void )
public void Yaf_Request_Abstract::isPost ( void )
public void Yaf_Request_Abstract::isPut ( void )
public void Yaf_Request_Abstract::isRouted ( void )
public void Yaf_Request_Abstract::isXmlHttpRequest ( void )
public void Yaf_Request_Abstract::setActionName ( string $action )
public void Yaf_Request_Abstract::setBaseUri ( string $uir )
public void Yaf_Request_Abstract::setControllerName ( string $controller )
public void Yaf_Request_Abstract::setDispatched ( void )
public void Yaf_Request_Abstract::setModuleName ( string $module )
public void Yaf_Request_Abstract::setParam ( string $name [, string $value ] )
public void Yaf_Request_Abstract::setRequestUri ( string $uir )
public void Yaf_Request_Abstract::setRouted ([ string $flag ] )
}

Właściwości

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Spis treści

  • Yaf_Request_Http::__clone — The __clone purpose
  • Yaf_Request_Http::__construct — The __construct purpose
  • Yaf_Request_Http::get — The get purpose
  • Yaf_Request_Http::getCookie — The getCookie purpose
  • Yaf_Request_Http::getFiles — The getFiles purpose
  • Yaf_Request_Http::getPost — The getPost purpose
  • Yaf_Request_Http::getQuery — fetch a query parameter
  • Yaf_Request_Http::getRequest — The getRequest purpose
  • Yaf_Request_Http::isXmlHttpRequest — The isXmlHttpRequest purpose
Yaf_Request_Abstract::setRouted
Yaf_Request_Http::__clone
Yaf


The __clone purpose

Yaf_Request_Http
Yaf_Request_Http::__construct
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::__clone

(PECL yaf >=1.0.0)

Yaf_Request_Http::__clone — The __clone purpose

Opis

private void Yaf_Request_Http::__clone ( 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

Yaf_Request_Http
Yaf_Request_Http::__construct
Yaf_Request_Http


The __construct purpose

Yaf_Request_Http::__clone
Yaf_Request_Http::get
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::__construct

(PECL yaf >=1.0.0)

Yaf_Request_Http::__construct — The __construct purpose

Opis

Yaf_Request_Http::__construct ( 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

Yaf_Request_Http::__clone
Yaf_Request_Http::get
Yaf_Request_Http


The get purpose

Yaf_Request_Http::__construct
Yaf_Request_Http::getCookie
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::get

(PECL yaf >=1.0.0)

Yaf_Request_Http::get — The get purpose

Opis

public void Yaf_Request_Http::get ( 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

Yaf_Request_Http::__construct
Yaf_Request_Http::getCookie
Yaf_Request_Http


The getCookie purpose

Yaf_Request_Http::get
Yaf_Request_Http::getFiles
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getCookie

(PECL yaf >=1.0.0)

Yaf_Request_Http::getCookie — The getCookie purpose

Opis

public void Yaf_Request_Http::getCookie ( 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

Yaf_Request_Http::get
Yaf_Request_Http::getFiles
Yaf_Request_Http


The getFiles purpose

Yaf_Request_Http::getCookie
Yaf_Request_Http::getPost
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getFiles

(PECL yaf >=1.0.0)

Yaf_Request_Http::getFiles — The getFiles purpose

Opis

public void Yaf_Request_Http::getFiles ( 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

Yaf_Request_Http::getCookie
Yaf_Request_Http::getPost
Yaf_Request_Http


The getPost purpose

Yaf_Request_Http::getFiles
Yaf_Request_Http::getQuery
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getPost

(PECL yaf >=1.0.0)

Yaf_Request_Http::getPost — The getPost purpose

Opis

public void Yaf_Request_Http::getPost ( 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

Yaf_Request_Http::getFiles
Yaf_Request_Http::getQuery
Yaf_Request_Http


fetch a query parameter

Yaf_Request_Http::getPost
Yaf_Request_Http::getRequest
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getQuery

(PECL yaf >=1.0.0)

Yaf_Request_Http::getQuery — fetch a query parameter

Opis

public void Yaf_Request_Http::getQuery ( void )

Fetch a query parameter in $_GET.

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

Yaf_Request_Http::getPost
Yaf_Request_Http::getRequest
Yaf_Request_Http


The getRequest purpose

Yaf_Request_Http::getQuery
Yaf_Request_Http::isXmlHttpRequest
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::getRequest

(PECL yaf >=1.0.0)

Yaf_Request_Http::getRequest — The getRequest purpose

Opis

public void Yaf_Request_Http::getRequest ( 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

Yaf_Request_Http::getQuery
Yaf_Request_Http::isXmlHttpRequest
Yaf_Request_Http


The isXmlHttpRequest purpose

Yaf_Request_Http::getRequest
Yaf_Request_Simple
Yaf_Request_Http
PHP Manual

Yaf_Request_Http::isXmlHttpRequest

(PECL yaf >=1.0.0)

Yaf_Request_Http::isXmlHttpRequest — The isXmlHttpRequest purpose

Opis

public void Yaf_Request_Http::isXmlHttpRequest ( 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

Yaf_Request_Http::getRequest
Yaf_Request_Simple
Yaf_Request_Http


The Yaf_Request_Simple class

(No version information available, might only be in SVN)

Wstęp

Yaf_Request_Simple is particularlly used for test puporse. ie. simulate some espacial request under CLI mode.

Krótki opis klasy

Yaf_Request_Simple extends Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http ;
const string SCHEME_HTTPS = https ;
/* Właściwości */
/* Metody */
private void __clone ( void )
__construct ( void )
public void get ( void )
public void getCookie ( void )
public void getFiles ( void )
public void getPost ( void )
public void getQuery ( void )
public void getRequest ( void )
public void isXmlHttpRequest ( void )
/* Metody dziedziczone */
public void Yaf_Request_Abstract::getActionName ( void )
public void Yaf_Request_Abstract::getBaseUri ( void )
public void Yaf_Request_Abstract::getControllerName ( void )
public void Yaf_Request_Abstract::getEnv ( string $name [, string $default ] )
public void Yaf_Request_Abstract::getException ( void )
public void Yaf_Request_Abstract::getLanguage ( void )
public void Yaf_Request_Abstract::getMethod ( void )
public void Yaf_Request_Abstract::getModuleName ( void )
public void Yaf_Request_Abstract::getParam ( string $name [, string $default ] )
public void Yaf_Request_Abstract::getParams ( void )
public void Yaf_Request_Abstract::getRequestUri ( void )
public void Yaf_Request_Abstract::getServer ( string $name [, string $default ] )
public void Yaf_Request_Abstract::isCli ( void )
public void Yaf_Request_Abstract::isDispatched ( void )
public void Yaf_Request_Abstract::isGet ( void )
public void Yaf_Request_Abstract::isHead ( void )
public void Yaf_Request_Abstract::isOptions ( void )
public void Yaf_Request_Abstract::isPost ( void )
public void Yaf_Request_Abstract::isPut ( void )
public void Yaf_Request_Abstract::isRouted ( void )
public void Yaf_Request_Abstract::isXmlHttpRequest ( void )
public void Yaf_Request_Abstract::setActionName ( string $action )
public void Yaf_Request_Abstract::setBaseUri ( string $uir )
public void Yaf_Request_Abstract::setControllerName ( string $controller )
public void Yaf_Request_Abstract::setDispatched ( void )
public void Yaf_Request_Abstract::setModuleName ( string $module )
public void Yaf_Request_Abstract::setParam ( string $name [, string $value ] )
public void Yaf_Request_Abstract::setRequestUri ( string $uir )
public void Yaf_Request_Abstract::setRouted ([ string $flag ] )
}

Właściwości

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Stałe predefiniowane

Yaf_Request_Simple::SCHEME_HTTP

Yaf_Request_Simple::SCHEME_HTTPS

Spis treści

  • Yaf_Request_Simple::__clone — The __clone purpose
  • Yaf_Request_Simple::__construct — The __construct purpose
  • Yaf_Request_Simple::get — The get purpose
  • Yaf_Request_Simple::getCookie — The getCookie purpose
  • Yaf_Request_Simple::getFiles — The getFiles purpose
  • Yaf_Request_Simple::getPost — The getPost purpose
  • Yaf_Request_Simple::getQuery — The getQuery purpose
  • Yaf_Request_Simple::getRequest — The getRequest purpose
  • Yaf_Request_Simple::isXmlHttpRequest — The isXmlHttpRequest purpose
Yaf_Request_Http::isXmlHttpRequest
Yaf_Request_Simple::__clone
Yaf


The __clone purpose

Yaf_Request_Simple
Yaf_Request_Simple::__construct
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::__clone

(PECL yaf >=1.0.0)

Yaf_Request_Simple::__clone — The __clone purpose

Opis

private void Yaf_Request_Simple::__clone ( 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

Yaf_Request_Simple
Yaf_Request_Simple::__construct
Yaf_Request_Simple


The __construct purpose

Yaf_Request_Simple::__clone
Yaf_Request_Simple::get
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::__construct

(PECL yaf >=1.0.0)

Yaf_Request_Simple::__construct — The __construct purpose

Opis

Yaf_Request_Simple::__construct ( 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

Yaf_Request_Simple::__clone
Yaf_Request_Simple::get
Yaf_Request_Simple


The get purpose

Yaf_Request_Simple::__construct
Yaf_Request_Simple::getCookie
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::get

(PECL yaf >=1.0.0)

Yaf_Request_Simple::get — The get purpose

Opis

public void Yaf_Request_Simple::get ( 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

Yaf_Request_Simple::__construct
Yaf_Request_Simple::getCookie
Yaf_Request_Simple


The getCookie purpose

Yaf_Request_Simple::get
Yaf_Request_Simple::getFiles
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getCookie

(PECL yaf >=1.0.0)

Yaf_Request_Simple::getCookie — The getCookie purpose

Opis

public void Yaf_Request_Simple::getCookie ( 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

Yaf_Request_Simple::get
Yaf_Request_Simple::getFiles
Yaf_Request_Simple


The getFiles purpose

Yaf_Request_Simple::getCookie
Yaf_Request_Simple::getPost
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getFiles

(PECL yaf >=1.0.0)

Yaf_Request_Simple::getFiles — The getFiles purpose

Opis

public void Yaf_Request_Simple::getFiles ( 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

Yaf_Request_Simple::getCookie
Yaf_Request_Simple::getPost
Yaf_Request_Simple


The getPost purpose

Yaf_Request_Simple::getFiles
Yaf_Request_Simple::getQuery
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getPost

(PECL yaf >=1.0.0)

Yaf_Request_Simple::getPost — The getPost purpose

Opis

public void Yaf_Request_Simple::getPost ( 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

Yaf_Request_Simple::getFiles
Yaf_Request_Simple::getQuery
Yaf_Request_Simple


The getQuery purpose

Yaf_Request_Simple::getPost
Yaf_Request_Simple::getRequest
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getQuery

(PECL yaf >=1.0.0)

Yaf_Request_Simple::getQuery — The getQuery purpose

Opis

public void Yaf_Request_Simple::getQuery ( 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

Yaf_Request_Simple::getPost
Yaf_Request_Simple::getRequest
Yaf_Request_Simple


The getRequest purpose

Yaf_Request_Simple::getQuery
Yaf_Request_Simple::isXmlHttpRequest
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::getRequest

(PECL yaf >=1.0.0)

Yaf_Request_Simple::getRequest — The getRequest purpose

Opis

public void Yaf_Request_Simple::getRequest ( 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

Yaf_Request_Simple::getQuery
Yaf_Request_Simple::isXmlHttpRequest
Yaf_Request_Simple


The isXmlHttpRequest purpose

Yaf_Request_Simple::getRequest
Yaf_Response_Abstract
Yaf_Request_Simple
PHP Manual

Yaf_Request_Simple::isXmlHttpRequest

(PECL yaf >=1.0.0)

Yaf_Request_Simple::isXmlHttpRequest — The isXmlHttpRequest purpose

Opis

public void Yaf_Request_Simple::isXmlHttpRequest ( 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

Yaf_Request_Simple::getRequest
Yaf_Response_Abstract
Yaf_Request_Simple


The Yaf_Response_Abstract class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Response_Abstract {
/* Właściwości */
protected $_header ;
protected $_body ;
protected $_sendheader ;
/* Metody */
public void appendBody ( void )
public void clearBody ( void )
public void clearHeaders ( void )
private void __clone ( void )
public __construct ( void )
public void __destruct ( void )
public void getBody ( void )
public void getHeader ( void )
public void prependBody ( void )
public void response ( void )
protected void setAllHeaders ( void )
public void setBody ( void )
public void setHeader ( void )
public void setRedirect ( void )
private void __toString ( void )
}

Właściwości

_header

_body

_sendheader

Spis treści

  • Yaf_Response_Abstract::appendBody — The appendBody purpose
  • Yaf_Response_Abstract::clearBody — The clearBody purpose
  • Yaf_Response_Abstract::clearHeaders — The clearHeaders purpose
  • Yaf_Response_Abstract::__clone — The __clone purpose
  • Yaf_Response_Abstract::__construct — The __construct purpose
  • Yaf_Response_Abstract::__destruct — The __destruct purpose
  • Yaf_Response_Abstract::getBody — The getBody purpose
  • Yaf_Response_Abstract::getHeader — The getHeader purpose
  • Yaf_Response_Abstract::prependBody — The prependBody purpose
  • Yaf_Response_Abstract::response — The response purpose
  • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
  • Yaf_Response_Abstract::setBody — The setBody purpose
  • Yaf_Response_Abstract::setHeader — The setHeader purpose
  • Yaf_Response_Abstract::setRedirect — The setRedirect purpose
  • Yaf_Response_Abstract::__toString — The __toString purpose
Yaf_Request_Simple::isXmlHttpRequest
Yaf_Response_Abstract::appendBody
Yaf


The appendBody purpose

Yaf_Response_Abstract
Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::appendBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::appendBody — The appendBody purpose

Opis

public void Yaf_Response_Abstract::appendBody ( 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

Yaf_Response_Abstract
Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract


The clearBody purpose

Yaf_Response_Abstract::appendBody
Yaf_Response_Abstract::clearHeaders
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::clearBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::clearBody — The clearBody purpose

Opis

public void Yaf_Response_Abstract::clearBody ( 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

Yaf_Response_Abstract::appendBody
Yaf_Response_Abstract::clearHeaders
Yaf_Response_Abstract


The clearHeaders purpose

Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract::__clone
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::clearHeaders

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::clearHeaders — The clearHeaders purpose

Opis

public void Yaf_Response_Abstract::clearHeaders ( 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

Yaf_Response_Abstract::clearBody
Yaf_Response_Abstract::__clone
Yaf_Response_Abstract


The __clone purpose

Yaf_Response_Abstract::clearHeaders
Yaf_Response_Abstract::__construct
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::__clone

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::__clone — The __clone purpose

Opis

private void Yaf_Response_Abstract::__clone ( 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

Yaf_Response_Abstract::clearHeaders
Yaf_Response_Abstract::__construct
Yaf_Response_Abstract


The __construct purpose

Yaf_Response_Abstract::__clone
Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::__construct

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::__construct — The __construct purpose

Opis

public Yaf_Response_Abstract::__construct ( 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

Yaf_Response_Abstract::__clone
Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract


The __destruct purpose

Yaf_Response_Abstract::__construct
Yaf_Response_Abstract::getBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::__destruct

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::__destruct — The __destruct purpose

Opis

public void Yaf_Response_Abstract::__destruct ( 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

Yaf_Response_Abstract::__construct
Yaf_Response_Abstract::getBody
Yaf_Response_Abstract


The getBody purpose

Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::getBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::getBody — The getBody purpose

Opis

public void Yaf_Response_Abstract::getBody ( 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

Yaf_Response_Abstract::__destruct
Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract


The getHeader purpose

Yaf_Response_Abstract::getBody
Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::getHeader

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::getHeader — The getHeader purpose

Opis

public void Yaf_Response_Abstract::getHeader ( 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

Yaf_Response_Abstract::getBody
Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract


The prependBody purpose

Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract::response
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::prependBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::prependBody — The prependBody purpose

Opis

public void Yaf_Response_Abstract::prependBody ( 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

Yaf_Response_Abstract::getHeader
Yaf_Response_Abstract::response
Yaf_Response_Abstract


The response purpose

Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::response

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::response — The response purpose

Opis

public void Yaf_Response_Abstract::response ( 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

Yaf_Response_Abstract::prependBody
Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract


The setAllHeaders purpose

Yaf_Response_Abstract::response
Yaf_Response_Abstract::setBody
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setAllHeaders

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose

Opis

protected void Yaf_Response_Abstract::setAllHeaders ( 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

Yaf_Response_Abstract::response
Yaf_Response_Abstract::setBody
Yaf_Response_Abstract


The setBody purpose

Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setBody

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::setBody — The setBody purpose

Opis

public void Yaf_Response_Abstract::setBody ( 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

Yaf_Response_Abstract::setAllHeaders
Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract


The setHeader purpose

Yaf_Response_Abstract::setBody
Yaf_Response_Abstract::setRedirect
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setHeader

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::setHeader — The setHeader purpose

Opis

public void Yaf_Response_Abstract::setHeader ( 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

Yaf_Response_Abstract::setBody
Yaf_Response_Abstract::setRedirect
Yaf_Response_Abstract


The setRedirect purpose

Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract::__toString
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::setRedirect

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::setRedirect — The setRedirect purpose

Opis

public void Yaf_Response_Abstract::setRedirect ( 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

Yaf_Response_Abstract::setHeader
Yaf_Response_Abstract::__toString
Yaf_Response_Abstract


The __toString purpose

Yaf_Response_Abstract::setRedirect
Yaf_Route_Interface
Yaf_Response_Abstract
PHP Manual

Yaf_Response_Abstract::__toString

(PECL yaf >=1.0.0)

Yaf_Response_Abstract::__toString — The __toString purpose

Opis

private void Yaf_Response_Abstract::__toString ( 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

Yaf_Response_Abstract::setRedirect
Yaf_Route_Interface
Yaf_Response_Abstract


The Yaf_Route_Interface class

(No version information available, might only be in SVN)

Wstęp

Yaf_Route_Interface used for developer defined their custom route.

Krótki opis klasy

Yaf_Route_Interface {
/* Metody */
abstract public bool route ( Yaf_Request_Abstract $request )
}

Spis treści

  • Yaf_Route_Interface::route — route a request
Yaf_Response_Abstract::__toString
Yaf_Route_Interface::route
Yaf


route a request

Yaf_Route_Interface
Yaf_Route_Map
Yaf_Route_Interface
PHP Manual

Yaf_Route_Interface::route

(PECL yaf >=1.0.0)

Yaf_Route_Interface::route — route a request

Opis

abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )

Yaf_Route_Interface::route() is the only method that a custom route should implement.

if this method return TRUE, then the route process will be end. otherwise, Yaf_Router will call next route in the route stack to route request.

This method would set the route result to the parameter request, by
calling  Yaf_Request_Abstract::setControllerName(),
 Yaf_Request_Abstract::setActionName() and
 Yaf_Request_Abstract::setModuleName().

This method should also call Yaf_Request_Abstract::setRouted() to make the request routed at last.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

A Yaf_Request_Abstract instance.

Zwracane wartości

Yaf_Route_Interface
Yaf_Route_Map
Yaf_Route_Interface


The Yaf_Route_Map class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Route_Map implements Yaf_Route_Interface {
/* Właściwości */
protected $_ctl_router ;
protected $_delimeter ;
/* Metody */
public __construct ([ string $controller_prefer = false [, string $delimiter = '' ]] )
public bool route ( Yaf_Request_Abstract $request )
}

Właściwości

_ctl_router

_delimeter

Spis treści

  • Yaf_Route_Map::__construct — The __construct purpose
  • Yaf_Route_Map::route — The route purpose
Yaf_Route_Interface::route
Yaf_Route_Map::__construct
Yaf


The __construct purpose

Yaf_Route_Map
Yaf_Route_Map::route
Yaf_Route_Map
PHP Manual

Yaf_Route_Map::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Map::__construct — The __construct purpose

Opis

public Yaf_Route_Map::__construct ([ string $controller_prefer = false [, string $delimiter = '' ]] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

controller_prefer

Whether the result should considering as controller or action

delimiter

Zwracane wartości

Przykłady

Przykład #1 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Map());
?>

Powyższy przykład wyświetli coś podobnego do:

/* for http://yourdomain.com/product/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product_foo_bar",
)

Przykład #2 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Map(true, "_"));
?>

Powyższy przykład wyświetli coś podobnego do:

/* for http://yourdomain.com/user/list/_/foo/22
 * route will result in following values:
 */
array(
    "action" => "user_list",
)

/**
 * and request parameters:
 */
array(
  "foo"   => 22,
)

Zobacz też:

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
Yaf_Route_Map
Yaf_Route_Map::route
Yaf_Route_Map


The route purpose

Yaf_Route_Map::__construct
Yaf_Route_Regex
Yaf_Route_Map
PHP Manual

Yaf_Route_Map::route

(PECL yaf >=1.0.0)

Yaf_Route_Map::route — The route purpose

Opis

public bool Yaf_Route_Map::route ( Yaf_Request_Abstract $request )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

Zwracane wartości

Yaf_Route_Map::__construct
Yaf_Route_Regex
Yaf_Route_Map


The Yaf_Route_Regex class

(No version information available, might only be in SVN)

Wstęp

Yaf_Route_Regex is the most flexible route among the Yaf built-in routes.

Krótki opis klasy

Yaf_Route_Regex extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Właściwości */
protected $_route ;
protected $_default ;
protected $_maps ;
protected $_verify ;
/* Metody */
public __construct ( string $match , array $route [, array $map [, array $verify ]] )
public bool route ( Yaf_Request_Abstract $request )
/* Metody dziedziczone */
abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )
}

Właściwości

_route

_default

_maps

_verify

Spis treści

  • Yaf_Route_Regex::__construct — The __construct purpose
  • Yaf_Route_Regex::route — The route purpose
Yaf_Route_Map::route
Yaf_Route_Regex::__construct
Yaf


The __construct purpose

Yaf_Route_Regex
Yaf_Route_Regex::route
Yaf_Route_Regex
PHP Manual

Yaf_Route_Regex::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Regex::__construct — The __construct purpose

Opis

public Yaf_Route_Regex::__construct ( string $match , array $route [, array $map [, array $verify ]] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

match

A complete Regex pattern, will be used to match a request uri, if doesn't matched, Yaf_Route_Regex will return FALSE.

route

When the match pattern matches the request uri, Yaf_Route_Regex will use this to decide which m/c/a to routed.

either of m/c/a in this array is optianl, if you don't assgian a specific value, it will be routed to default.

map

A array to assign name to the captrues in the match result.

verify

Zwracane wartości

Przykłady

Przykład #1 Yaf_Route_Regex()example

<?php
   /**
    * Add a regex route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Regex(
           "#^/product/([^/]+)/([^/])+#", //match request uri leading "/product"
           array(
               'controller' => "product",  //route to product controller,
           ),
           array(
              1 => "name",   // now you can call $request->getParam("name")
              2 => "id",     // to get the first captrue in the match pattern.
           )
        )
    );
?>

Przykład #2 Yaf_Route_Regex()example

<?php
   /**
    * Add a regex route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "regex",          //Yaf_Route_Regex route
           "match" => "#(.*)#",         //match arbitrary request uri
           "route" => array(
               'controller' => "product",  //route to product controller,
               'action'     => "dummy",    //route to dummy action
           ),
           "map" => array(
              1 => "uri",   // now you can call $request->getParam("uri")
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

Zobacz też:

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Rewrite
  • Yaf_Route_Map
Yaf_Route_Regex
Yaf_Route_Regex::route
Yaf_Route_Regex


The route purpose

Yaf_Route_Regex::__construct
Yaf_Route_Rewrite
Yaf_Route_Regex
PHP Manual

Yaf_Route_Regex::route

(PECL yaf >=1.0.0)

Yaf_Route_Regex::route — The route purpose

Opis

public bool Yaf_Route_Regex::route ( Yaf_Request_Abstract $request )

Route a incoming request.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

Zwracane wartości

If the pattern given by the first parameter of Yaf_Route_Regex::_construct() matche the request uri, return TRUE, otherwise return FALSE.

Yaf_Route_Regex::__construct
Yaf_Route_Rewrite
Yaf_Route_Regex


The Yaf_Route_Rewrite class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Route_Rewrite extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Właściwości */
protected $_route ;
protected $_default ;
protected $_verify ;
/* Metody */
public __construct ( string $match , array $route [, array $verify ] )
public bool route ( Yaf_Request_Abstract $request )
/* Metody dziedziczone */
abstract public bool Yaf_Route_Interface::route ( Yaf_Request_Abstract $request )
}

Właściwości

_route

_default

_verify

Spis treści

  • Yaf_Route_Rewrite::__construct — The __construct purpose
  • Yaf_Route_Rewrite::route — The route purpose
Yaf_Route_Regex::route
Yaf_Route_Rewrite::__construct
Yaf


The __construct purpose

Yaf_Route_Rewrite
Yaf_Route_Rewrite::route
Yaf_Route_Rewrite
PHP Manual

Yaf_Route_Rewrite::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Rewrite::__construct — The __construct purpose

Opis

public Yaf_Route_Rewrite::__construct ( string $match , array $route [, array $verify ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

match

A pattern, will be used to match a request uri, if doesn't matched, Yaf_Route_Rewrite will return FALSE.

route

When the match pattern matches the request uri, Yaf_Route_Rewrite will use this to decide which m/c/a to routed.

either of m/c/a in this array is optianl, if you don't assgian a specific value, it will be routed to default.

verify

Zwracane wartości

Przykłady

Przykład #1 Yaf_Route_Rewrite()example

<?php
   /**
    * Add a rewrite route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_rewrite(
           "/product/:name/:id/*", //match request uri leading "/product"
           array(
               'controller' => "product",  //route to product controller,
           ),
        )
    );
?>

Powyższy przykład wyświetli coś podobnego do:

/* for http://yourdomain.com/product/foo/22/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product",
  "module"     => "index", //(default)
  "action"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "name" => "foo",
  "id"   => 22,
  "foo"  => bar
)

Przykład #2 Yaf_Route_Rewrite()example

<?php
   /**
    * Add a rewrite route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "rewrite",        //Yaf_Route_Rewrite route
           "match" => "/user-list/:id", //match only /user/list/?/
           "route" => array(
               'controller' => "user",  //route to user controller,
               'action'     => "list",  //route to list action
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

Powyższy przykład wyświetli coś podobnego do:

/* for http://yourdomain.com/user-list/22
 * route will result in following values:
 */
array(
  "controller" => "user",
  "action"     => "list",
  "module"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "id"   => 22,
)

Zobacz też:

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Map
Yaf_Route_Rewrite
Yaf_Route_Rewrite::route
Yaf_Route_Rewrite


The route purpose

Yaf_Route_Rewrite::__construct
Yaf_Router
Yaf_Route_Rewrite
PHP Manual

Yaf_Route_Rewrite::route

(PECL yaf >=1.0.0)

Yaf_Route_Rewrite::route — The route purpose

Opis

public bool Yaf_Route_Rewrite::route ( Yaf_Request_Abstract $request )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

Zwracane wartości

Yaf_Route_Rewrite::__construct
Yaf_Router
Yaf_Route_Rewrite


The Yaf_Router class

(No version information available, might only be in SVN)

Wstęp

Yaf_Router is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request. This values of the module, controller, action and other parameters are packaged into a Yaf_Request_Abstract object which is then processed by Yaf_Dispatcher. Routing occurs only once: when the request is initially received and before the first controller is dispatched. Yaf_Router is designed to allow for mod_rewrite-like functionality using pure PHP structures. It is very loosely based on Ruby on Rails routing and does not require any prior knowledge of webserver URL rewriting. It is designed to work with a single Apache mod_rewrite rule (one of):

Przykład #1 Rewrite rule for Apache

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css|html)$ index.php
or (preferred):

Przykład #2 Rewrite rule for Apache

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
If using Lighttpd, the following rewrite rule is valid:

Przykład #3 Rewrite rule for Lighttpd

url.rewrite-once = (
  ".*\?(.*)$" => "/index.php?$1",
  ".*\.(js|ico|gif|jpg|png|css|html)$" => "$0",
  "" => "/index.php"
)
If using Nginx, use the following rewrite rule:

Przykład #4 Rewrite rule for Nginx

server {
  listen ****;
  server_name  yourdomain.com;
  root   document_root;
  index  index.php index.html;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php/$1 last;
  }
}

Default route

Yaf_Router comes preconfigured with a default route, which will match URIs in the shape of controller/action. Additionally, a module name may be specified as the first path element, allowing URIs of the form module/controller/action. Finally, it will also match any additional parameters appended to the URI by default - controller/action/var1/value1/var2/value2.

Informacja:

Module name must be defined in config, considering application.module="Index,Foo,Bar", in this case, only index, foo and bar can be considerd as a module name. if doesn't config, there is only one module named "Index".

Some examples of how such routes are matched:

Przykład #5 Yaf_Route_Static(default route)example

// Assuming the following configure:
$conf = array(
   "application" => array(
      "modules" => "Index,Blog",
   ),
);

Controller only:
http://example/news
    controller == news
Action only(when defined yaf.action_prefer=1 in php.ini)
    action  == news

Invalid module maps to controller name:
http://example/foo
    controller == foo

Module + controller:
http://example/blog/archive
    module     == blog
    controller == archive

Module + controller + action:
http://example/blog/archive/list
    module     == blog
    controller == archive
    action     == list

Module + controller + action + params:
http://example/blog/archive/list/sort/alpha/date/desc
    module     == blog
    controller == archive
    action     == list
    sort       == alpha
    date       == desc

Krótki opis klasy

Yaf_Router {
/* Właściwości */
protected $_routes ;
protected $_current ;
/* Metody */
public void addConfig ( Yaf_Config_Abstract $config )
public Yaf_Router addRoute ( string $name , Yaf_Route_Abstract $route )
public __construct ( void )
public string getCurrentRoute ( void )
public void getRoute ( string $name )
public void getRoutes ( void )
public bool route ( Yaf_Request_Abstract $request )
}

Właściwości

_routes

_current

Spis treści

  • Yaf_Router::addConfig — Add config-defined routes into Router
  • Yaf_Router::addRoute — Add new Route into Router
  • Yaf_Router::__construct — Yaf_Router constructor
  • Yaf_Router::getCurrentRoute — Get the effective route name
  • Yaf_Router::getRoute — The getRoute purpose
  • Yaf_Router::getRoutes — The getRoutes purpose
  • Yaf_Router::route — The route purpose
Yaf_Route_Rewrite::route
Yaf_Router::addConfig
Yaf


Add config-defined routes into Router

Yaf_Router
Yaf_Router::addRoute
Yaf_Router
PHP Manual

Yaf_Router::addConfig

(PECL yaf >=1.0.0)

Yaf_Router::addConfig — Add config-defined routes into Router

Opis

public void Yaf_Router::addConfig ( Yaf_Config_Abstract $config )

Add Routes defined in application.ini into Yaf_Router's route stack

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

Przykłady

Przykład #1 application.ini()example

;the order is very important, the prior one will be called first

;a rewrite route match request /product/*/*
routes.route_name.type="rewrite"
routes.route_name.match="/product/:name/:value"
routes.route_name.route.controller=product
routes.route_name.route.action=info

;a regex route match request /list/*/*
routes.route_name1.type="regex"
routes.route_name1.match="#^list/([^/]*)/([^/]*)#"
routes.route_name1.route.controller=Index
routes.route_name1.route.action=action
routes.route_name1.map.1=name
routes.route_name1.map.2=value

;a simple router match /**?r=PATH_INFO
routes.route_name3.type="supervar"
routes.route_name3.varname=r

;a simple route match /**?c=controller&a=action&m=module
routes.route_name2.type="simple"
routes.route_name2.controller=c
routes.route_name2.module=m
routes.route_name2.action=a

Przykład #2 Yaf_Dispatcher::autoConfig()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        /**
         * we can add some pre-defined routes in application.ini
         */
        $router->addConfig(Yaf_Registry::get("config")->routes);
    }
?>

Zobacz też:

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
  • Yaf_Route_Map
Yaf_Router
Yaf_Router::addRoute
Yaf_Router


Add new Route into Router

Yaf_Router::addConfig
Yaf_Router::__construct
Yaf_Router
PHP Manual

Yaf_Router::addRoute

(PECL yaf >=1.0.0)

Yaf_Router::addRoute — Add new Route into Router

Opis

public Yaf_Router Yaf_Router::addRoute ( string $name , Yaf_Route_Abstract $route )

defaultly, Yaf_Router using a Yaf_Route_Static as its defualt route. you can add new routes into Router's route stack by calling this method.

the newer route will be called before the older(route stack), and if the newer router return TRUE, the router process will be end. otherwise, the older one will be called.

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

Przykłady

Przykład #1 Yaf_Dispatcher::autoRender()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        /**
         * we can add some pre-defined routes in application.ini
         */
        $router->addConfig(Yaf_Registry::get("config")->routes);
        /**
         * add a Rewrite route, then for a request uri:
         * http://***/product/list/22/foo
         * will be matched by this route, and result:
         *
         *  [module] =>
         *  [controller] => product
         *  [action] => info
         *  [method] => GET
         *  [params:protected] => Array
         *      (
         *          [id] => 22
         *          [name] => foo
         *      )
         *
         */
        $route  = new Yaf_Route_Rewrite(
            "/product/list/:id/:name",
            array(
                "controller" => "product",
                "action"     => "info",
            )
        );

        $router->addRoute('dummy', $route);
    }
?>

Zobacz też:

  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
  • Yaf_Route_Map
Yaf_Router::addConfig
Yaf_Router::__construct
Yaf_Router


Yaf_Router constructor

Yaf_Router::addRoute
Yaf_Router::getCurrentRoute
Yaf_Router
PHP Manual

Yaf_Router::__construct

(PECL yaf >=1.0.0)

Yaf_Router::__construct — Yaf_Router constructor

Opis

public Yaf_Router::__construct ( 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

Yaf_Router::addRoute
Yaf_Router::getCurrentRoute
Yaf_Router


Get the effective route name

Yaf_Router::__construct
Yaf_Router::getRoute
Yaf_Router
PHP Manual

Yaf_Router::getCurrentRoute

(PECL yaf >=1.0.0)

Yaf_Router::getCurrentRoute — Get the effective route name

Opis

public string Yaf_Router::getCurrentRoute ( void )

Get the name of the route which is effective in the route process.

Informacja:

You should call this method after the route process finished, since before that, this method will always return NULL.

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

String, the name of the effective route.

Przykłady

Przykład #1 Register some routes in Bootstrap

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        $rewrite_route  = new Yaf_Route_Rewrite(
            "/product/list/:page",
            array(
                "controller" => "product",
                "action"     => "list",
            )
        );

        $regex_route  = new Yaf_Route_Rewrite(
            "#^/product/info/(\d+)",
            array(
                "controller" => "product",
                "action"     => "info",
            )
        );

        $router->addRoute('rewrite', $rewrite_route)->addRoute('regex', $regex_route);
    }

    /**
     * register plugin
     */
    public function __initPlugins(Yaf_Dispatcher $dispatcher) {
        $dispatcher->registerPlugin(new DummyPlugin());
    }
?>

Przykład #2 plugin Dummy.php (under application.directory/plugins)

<?php
class DummyPlugin extends Yaf_Plugin_Abstract {

    public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
         var_dump(Yaf_Dispatcher::getInstance()->getRouter()->getCurrentRoute());
    }
?>
?>

Powyższy przykład wyświetli coś podobnego do:

/* for http://yourdomain.com/product/list/1
 * DummyPlugin will output:
 */
string(7) "rewrite"

/* for http://yourdomain.com/product/info/34
 * DummyPlugin will output:
 */
string(5) "regex"

/* for other request URI
 * DummyPlugin will output:
 */
string(8) "_default"

Zobacz też:

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - Add new Route into Router
Yaf_Router::__construct
Yaf_Router::getRoute
Yaf_Router


The getRoute purpose

Yaf_Router::getCurrentRoute
Yaf_Router::getRoutes
Yaf_Router
PHP Manual

Yaf_Router::getRoute

(PECL yaf >=1.0.0)

Yaf_Router::getRoute — The getRoute purpose

Opis

public void Yaf_Router::getRoute ( string $name )

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

Yaf_Router::getCurrentRoute
Yaf_Router::getRoutes
Yaf_Router


The getRoutes purpose

Yaf_Router::getRoute
Yaf_Router::route
Yaf_Router
PHP Manual

Yaf_Router::getRoutes

(PECL yaf >=1.0.0)

Yaf_Router::getRoutes — The getRoutes purpose

Opis

public void Yaf_Router::getRoutes ( 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

Yaf_Router::getRoute
Yaf_Router::route
Yaf_Router


The route purpose

Yaf_Router::getRoutes
Yaf_Route_Simple
Yaf_Router
PHP Manual

Yaf_Router::route

(PECL yaf >=1.0.0)

Yaf_Router::route — The route purpose

Opis

public bool Yaf_Router::route ( Yaf_Request_Abstract $request )

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

Yaf_Router::getRoutes
Yaf_Route_Simple
Yaf_Router


The Yaf_Route_Simple class

(No version information available, might only be in SVN)

Wstęp

Yaf_Route_Simple will match the query string, and find the route info.

all you need to do is tell Yaf_Route_Simple what key in the $_GET is module, what key is controller, and what key is action.

Yaf_Route_Simple::route() will always return TRUE, so it is important put Yaf_Route_Simple in the front of the Route stack, otherwise all the other routes will not be called.

Krótki opis klasy

Yaf_Route_Simple implements Yaf_Route_Interface {
/* Właściwości */
protected $controller ;
protected $module ;
protected $action ;
/* Metody */
public __construct ( string $module_name , string $controller_name , string $action_name )
public bool route ( Yaf_Request_Abstract $request )
}

Właściwości

controller

module

action

Spis treści

  • Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor
  • Yaf_Route_Simple::route — Route a request
Yaf_Router::route
Yaf_Route_Simple::__construct
Yaf


Yaf_Route_Simple constructor

Yaf_Route_Simple
Yaf_Route_Simple::route
Yaf_Route_Simple
PHP Manual

Yaf_Route_Simple::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor

Opis

public Yaf_Route_Simple::__construct ( string $module_name , string $controller_name , string $action_name )

Yaf_Route_Simple will get route info from query string. and the parameters of this constructor will used as keys while searching for the route info in $_GET.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

module_name

The key name of the module info.

controller_name

the key name of the controller info.

action_name

the key name of the action info.

Zwracane wartości

Always return TRUE.

Przykłady

Przykład #1 Yaf_Route_Simple::route()example

<?php
   $route = new Yaf_Route_Simple("m", "controller", "act");
   Yaf_Router::getInstance()->addRoute("simple", $route);
?>

Przykład #2 Yaf_Route_Simple::route()example

Request: http://yourdomain.com/path/?controller=a&act=b
=> module = default(index), controller = a, action = b

Request: http://yourdomain.com/path
=> module = default(index), controller = default(index), action = default(index)

Zobacz też:

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Static::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose
Yaf_Route_Simple
Yaf_Route_Simple::route
Yaf_Route_Simple


Route a request

Yaf_Route_Simple::__construct
Yaf_Route_Static
Yaf_Route_Simple
PHP Manual

Yaf_Route_Simple::route

(PECL yaf >=1.0.0)

Yaf_Route_Simple::route — Route a request

Opis

public bool Yaf_Route_Simple::route ( Yaf_Request_Abstract $request )

see Yaf_Route_Simple::__construct()

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

Zwracane wartości

always be TRUE

Zobacz też:

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Static::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose
Yaf_Route_Simple::__construct
Yaf_Route_Static
Yaf_Route_Simple


The Yaf_Route_Static class

(No version information available, might only be in SVN)

Wstęp

Defaultly, Yaf_Router only have a Yaf_Route_Static as its default route.

And Yaf_Route_Static is designed to handle the 80% requirement.

please *NOTE* that it is unecessary to instance a Yaf_Route_Static, also unecesary to add it into Yaf_Router's route stack, since there is always be one in Yaf_Router's route stack, and always be called at the last time.

Krótki opis klasy

Yaf_Route_Static implements Yaf_Router {
/* Metody */
public void match ( string $uri )
public bool route ( Yaf_Request_Abstract $request )
}

Spis treści

  • Yaf_Route_Static::match — The match purpose
  • Yaf_Route_Static::route — Route a request
Yaf_Route_Simple::route
Yaf_Route_Static::match
Yaf


The match purpose

Yaf_Route_Static
Yaf_Route_Static::route
Yaf_Route_Static
PHP Manual

Yaf_Route_Static::match

(PECL yaf >=1.0.0)

Yaf_Route_Static::match — The match purpose

Opis

public void Yaf_Route_Static::match ( string $uri )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

uri

Zwracane wartości

Yaf_Route_Static
Yaf_Route_Static::route
Yaf_Route_Static


Route a request

Yaf_Route_Static::match
Yaf_Route_Supervar
Yaf_Route_Static
PHP Manual

Yaf_Route_Static::route

(PECL yaf >=1.0.0)

Yaf_Route_Static::route — Route a request

Opis

public bool Yaf_Route_Static::route ( Yaf_Request_Abstract $request )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

Zwracane wartości

always be TRUE

Przykłady

Przykład #1 Yaf_Route_Static::route()example

// assuming there is only one module defined:Index
Request: http://yourdomain.com/a/b
=> module = index, controller=a, action=b

//assuming ap.action_prefer = On
Request: http://yourdomain.com/b
=> module = default(index), controller = default(index), action = b

//assuming ap.action_prefer = Off
Request: http://yourdomain.com/b
=> module = default(index), controller = b, action = default(index)

Request: http://yourdomain.com/a/b/foo/bar/test/a/id/4
=> module = default(index), controller = a, action = b, request parameters: foo = bar, test = a, id = 4

Zobacz też:

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Simple::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose
Yaf_Route_Static::match
Yaf_Route_Supervar
Yaf_Route_Static


The Yaf_Route_Supervar class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Route_Supervar implements Yaf_Route_Interface {
/* Właściwości */
protected $_var_name ;
/* Metody */
public __construct ( string $supervar_name )
public bool route ( Yaf_Request_Abstract $request )
}

Właściwości

_var_name

Spis treści

  • Yaf_Route_Supervar::__construct — The __construct purpose
  • Yaf_Route_Supervar::route — The route purpose
Yaf_Route_Static::route
Yaf_Route_Supervar::__construct
Yaf


The __construct purpose

Yaf_Route_Supervar
Yaf_Route_Supervar::route
Yaf_Route_Supervar
PHP Manual

Yaf_Route_Supervar::__construct

(PECL yaf >=1.0.0)

Yaf_Route_Supervar::__construct — The __construct purpose

Opis

public Yaf_Route_Supervar::__construct ( string $supervar_name )

Yaf_Route_Supervar is similar with Yaf_Route_Static, the difference is Yaf_Route_Supervar will look for path info in query string, and the parameter supervar_name is the key.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

supervar_name

The name of key.

Zwracane wartości

Przykłady

Przykład #1 Yaf_Route_Supervar()example

<?php
   /**
    * Add a supervar route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Supervar("r"));
    );
?>

Powyższy przykład wyświetli coś podobnego do:

/** for request: http://yourdomain.com/xx/oo/?r=/ctr/act/var/value
  * will result in following:
  */
  array (
    "module"   => index(default),
    "controller" => ctr,
    "action"     => act,
    "params"     => array(
          "var" => value,
     )
  )

Zobacz też:

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Regex
  • Yaf_Route_Simple
  • Yaf_Route_Rewrite
  • Yaf_Route_Map
Yaf_Route_Supervar
Yaf_Route_Supervar::route
Yaf_Route_Supervar


The route purpose

Yaf_Route_Supervar::__construct
Yaf_Session
Yaf_Route_Supervar
PHP Manual

Yaf_Route_Supervar::route

(PECL yaf >=1.0.0)

Yaf_Route_Supervar::route — The route purpose

Opis

public bool Yaf_Route_Supervar::route ( Yaf_Request_Abstract $request )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

request

Zwracane wartości

If there is a key(which was defined in Yaf_Route_Supervar::__construct()) in $_GET, return TRUE. otherwise return FALSE.

Yaf_Route_Supervar::__construct
Yaf_Session
Yaf_Route_Supervar


The Yaf_Session class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Session implements Iterator , Traversable , ArrayAccess , Countable {
/* Właściwości */
protected static $_instance ;
protected $_session ;
protected $_started ;
/* Metody */
private void __clone ( void )
__construct ( void )
public void count ( void )
public void current ( void )
public void del ( string $name )
public void __get ( string $name )
public static void getInstance ( void )
public void has ( string $name )
public void __isset ( string $name )
public void key ( void )
public void next ( void )
public void offsetExists ( string $name )
public void offsetGet ( string $name )
public void offsetSet ( string $name , string $value )
public void offsetUnset ( string $name )
public void rewind ( void )
public void __set ( string $name , string $value )
private void __sleep ( void )
public void start ( void )
public void __unset ( string $name )
public void valid ( void )
private void __wakeup ( void )
}

Właściwości

_instance

_session

_started

Spis treści

  • Yaf_Session::__clone — The __clone purpose
  • Yaf_Session::__construct — The __construct purpose
  • Yaf_Session::count — The count purpose
  • Yaf_Session::current — The current purpose
  • Yaf_Session::del — The del purpose
  • Yaf_Session::__get — The __get purpose
  • Yaf_Session::getInstance — The getInstance purpose
  • Yaf_Session::has — The has purpose
  • Yaf_Session::__isset — The __isset purpose
  • Yaf_Session::key — The key purpose
  • Yaf_Session::next — The next purpose
  • Yaf_Session::offsetExists — The offsetExists purpose
  • Yaf_Session::offsetGet — The offsetGet purpose
  • Yaf_Session::offsetSet — The offsetSet purpose
  • Yaf_Session::offsetUnset — The offsetUnset purpose
  • Yaf_Session::rewind — The rewind purpose
  • Yaf_Session::__set — The __set purpose
  • Yaf_Session::__sleep — The __sleep purpose
  • Yaf_Session::start — The start purpose
  • Yaf_Session::__unset — The __unset purpose
  • Yaf_Session::valid — The valid purpose
  • Yaf_Session::__wakeup — The __wakeup purpose
Yaf_Route_Supervar::route
Yaf_Session::__clone
Yaf


The __clone purpose

Yaf_Session
Yaf_Session::__construct
Yaf_Session
PHP Manual

Yaf_Session::__clone

(PECL yaf >=1.0.0)

Yaf_Session::__clone — The __clone purpose

Opis

private void Yaf_Session::__clone ( 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

Yaf_Session
Yaf_Session::__construct
Yaf_Session


The __construct purpose

Yaf_Session::__clone
Yaf_Session::count
Yaf_Session
PHP Manual

Yaf_Session::__construct

(PECL yaf >=1.0.0)

Yaf_Session::__construct — The __construct purpose

Opis

Yaf_Session::__construct ( 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

Yaf_Session::__clone
Yaf_Session::count
Yaf_Session


The count purpose

Yaf_Session::__construct
Yaf_Session::current
Yaf_Session
PHP Manual

Yaf_Session::count

(PECL yaf >=1.0.0)

Yaf_Session::count — The count purpose

Opis

public void Yaf_Session::count ( 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

Yaf_Session::__construct
Yaf_Session::current
Yaf_Session


The current purpose

Yaf_Session::count
Yaf_Session::del
Yaf_Session
PHP Manual

Yaf_Session::current

(PECL yaf >=1.0.0)

Yaf_Session::current — The current purpose

Opis

public void Yaf_Session::current ( 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

Yaf_Session::count
Yaf_Session::del
Yaf_Session


The del purpose

Yaf_Session::current
Yaf_Session::__get
Yaf_Session
PHP Manual

Yaf_Session::del

(PECL yaf >=1.0.0)

Yaf_Session::del — The del purpose

Opis

public void Yaf_Session::del ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Session::current
Yaf_Session::__get
Yaf_Session


The __get purpose

Yaf_Session::del
Yaf_Session::getInstance
Yaf_Session
PHP Manual

Yaf_Session::__get

(PECL yaf >=1.0.0)

Yaf_Session::__get — The __get purpose

Opis

public void Yaf_Session::__get ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Session::del
Yaf_Session::getInstance
Yaf_Session


The getInstance purpose

Yaf_Session::__get
Yaf_Session::has
Yaf_Session
PHP Manual

Yaf_Session::getInstance

(PECL yaf >=1.0.0)

Yaf_Session::getInstance — The getInstance purpose

Opis

public static void Yaf_Session::getInstance ( 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

Yaf_Session::__get
Yaf_Session::has
Yaf_Session


The has purpose

Yaf_Session::getInstance
Yaf_Session::__isset
Yaf_Session
PHP Manual

Yaf_Session::has

(PECL yaf >=1.0.0)

Yaf_Session::has — The has purpose

Opis

public void Yaf_Session::has ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Session::getInstance
Yaf_Session::__isset
Yaf_Session


The __isset purpose

Yaf_Session::has
Yaf_Session::key
Yaf_Session
PHP Manual

Yaf_Session::__isset

(PECL yaf >=1.0.0)

Yaf_Session::__isset — The __isset purpose

Opis

public void Yaf_Session::__isset ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Session::has
Yaf_Session::key
Yaf_Session


The key purpose

Yaf_Session::__isset
Yaf_Session::next
Yaf_Session
PHP Manual

Yaf_Session::key

(PECL yaf >=1.0.0)

Yaf_Session::key — The key purpose

Opis

public void Yaf_Session::key ( 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

Yaf_Session::__isset
Yaf_Session::next
Yaf_Session


The next purpose

Yaf_Session::key
Yaf_Session::offsetExists
Yaf_Session
PHP Manual

Yaf_Session::next

(PECL yaf >=1.0.0)

Yaf_Session::next — The next purpose

Opis

public void Yaf_Session::next ( 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

Yaf_Session::key
Yaf_Session::offsetExists
Yaf_Session


The offsetExists purpose

Yaf_Session::next
Yaf_Session::offsetGet
Yaf_Session
PHP Manual

Yaf_Session::offsetExists

(PECL yaf >=1.0.0)

Yaf_Session::offsetExists — The offsetExists purpose

Opis

public void Yaf_Session::offsetExists ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Session::next
Yaf_Session::offsetGet
Yaf_Session


The offsetGet purpose

Yaf_Session::offsetExists
Yaf_Session::offsetSet
Yaf_Session
PHP Manual

Yaf_Session::offsetGet

(PECL yaf >=1.0.0)

Yaf_Session::offsetGet — The offsetGet purpose

Opis

public void Yaf_Session::offsetGet ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Session::offsetExists
Yaf_Session::offsetSet
Yaf_Session


The offsetSet purpose

Yaf_Session::offsetGet
Yaf_Session::offsetUnset
Yaf_Session
PHP Manual

Yaf_Session::offsetSet

(PECL yaf >=1.0.0)

Yaf_Session::offsetSet — The offsetSet purpose

Opis

public void Yaf_Session::offsetSet ( string $name , string $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_Session::offsetGet
Yaf_Session::offsetUnset
Yaf_Session


The offsetUnset purpose

Yaf_Session::offsetSet
Yaf_Session::rewind
Yaf_Session
PHP Manual

Yaf_Session::offsetUnset

(PECL yaf >=1.0.0)

Yaf_Session::offsetUnset — The offsetUnset purpose

Opis

public void Yaf_Session::offsetUnset ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Session::offsetSet
Yaf_Session::rewind
Yaf_Session


The rewind purpose

Yaf_Session::offsetUnset
Yaf_Session::__set
Yaf_Session
PHP Manual

Yaf_Session::rewind

(PECL yaf >=1.0.0)

Yaf_Session::rewind — The rewind purpose

Opis

public void Yaf_Session::rewind ( 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

Yaf_Session::offsetUnset
Yaf_Session::__set
Yaf_Session


The __set purpose

Yaf_Session::rewind
Yaf_Session::__sleep
Yaf_Session
PHP Manual

Yaf_Session::__set

(PECL yaf >=1.0.0)

Yaf_Session::__set — The __set purpose

Opis

public void Yaf_Session::__set ( string $name , string $value )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

value

Zwracane wartości

Yaf_Session::rewind
Yaf_Session::__sleep
Yaf_Session


The __sleep purpose

Yaf_Session::__set
Yaf_Session::start
Yaf_Session
PHP Manual

Yaf_Session::__sleep

(PECL yaf >=1.0.0)

Yaf_Session::__sleep — The __sleep purpose

Opis

private void Yaf_Session::__sleep ( 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

Yaf_Session::__set
Yaf_Session::start
Yaf_Session


The start purpose

Yaf_Session::__sleep
Yaf_Session::__unset
Yaf_Session
PHP Manual

Yaf_Session::start

(PECL yaf >=1.0.0)

Yaf_Session::start — The start purpose

Opis

public void Yaf_Session::start ( 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

Yaf_Session::__sleep
Yaf_Session::__unset
Yaf_Session


The __unset purpose

Yaf_Session::start
Yaf_Session::valid
Yaf_Session
PHP Manual

Yaf_Session::__unset

(PECL yaf >=1.0.0)

Yaf_Session::__unset — The __unset purpose

Opis

public void Yaf_Session::__unset ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

Yaf_Session::start
Yaf_Session::valid
Yaf_Session


The valid purpose

Yaf_Session::__unset
Yaf_Session::__wakeup
Yaf_Session
PHP Manual

Yaf_Session::valid

(PECL yaf >=1.0.0)

Yaf_Session::valid — The valid purpose

Opis

public void Yaf_Session::valid ( 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

Yaf_Session::__unset
Yaf_Session::__wakeup
Yaf_Session


The __wakeup purpose

Yaf_Session::valid
Yaf_Exception
Yaf_Session
PHP Manual

Yaf_Session::__wakeup

(PECL yaf >=1.0.0)

Yaf_Session::__wakeup — The __wakeup purpose

Opis

private void Yaf_Session::__wakeup ( 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

Yaf_Session::valid
Yaf_Exception
Yaf_Session


The Yaf_Exception class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception extends Exception {
/* Właściwości */
protected $message ;
protected $code ;
protected $previous ;
/* Metody */
public __construct ( void )
public void getPrevious ( 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

message

code

file

line

previous

Spis treści

  • Yaf_Exception::__construct — The __construct purpose
  • Yaf_Exception::getPrevious — The getPrevious purpose
Yaf_Session::__wakeup
Yaf_Exception::__construct
Yaf


The __construct purpose

Yaf_Exception
Yaf_Exception::getPrevious
Yaf_Exception
PHP Manual

Yaf_Exception::__construct

(PECL yaf >=1.0.0)

Yaf_Exception::__construct — The __construct purpose

Opis

public Yaf_Exception::__construct ( 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

Yaf_Exception
Yaf_Exception::getPrevious
Yaf_Exception


The getPrevious purpose

Yaf_Exception::__construct
Yaf_Exception_TypeError
Yaf_Exception
PHP Manual

Yaf_Exception::getPrevious

(PECL yaf >=1.0.0)

Yaf_Exception::getPrevious — The getPrevious purpose

Opis

public void Yaf_Exception::getPrevious ( 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

Yaf_Exception::__construct
Yaf_Exception_TypeError
Yaf_Exception


The Yaf_Exception_TypeError class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_TypeError extends Yaf_Exception {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception::getPrevious
Yaf_Exception_StartupError
Yaf


The Yaf_Exception_StartupError class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_StartupError extends Yaf_Exception {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_TypeError
Yaf_Exception_DispatchFailed
Yaf


The Yaf_Exception_DispatchFailed class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_DispatchFailed extends Yaf_Exception {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_StartupError
Yaf_Exception_RouterFailed
Yaf


The Yaf_Exception_RouterFailed class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_RouterFailed extends Yaf_Exception {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_DispatchFailed
Yaf_Exception_LoadFailed
Yaf


The Yaf_Exception_LoadFailed class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_LoadFailed extends Yaf_Exception {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_RouterFailed
Yaf_Exception_LoadFailed_Module
Yaf


The Yaf_Exception_LoadFailed_Module class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_LoadFailed_Module extends Yaf_Exception_LoadFailed {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_LoadFailed
Yaf_Exception_LoadFailed_Controller
Yaf


The Yaf_Exception_LoadFailed_Controller class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_LoadFailed_Controller extends Yaf_Exception_LoadFailed {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_LoadFailed_Module
Yaf_Exception_LoadFailed_Action
Yaf


The Yaf_Exception_LoadFailed_Action class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_LoadFailed_Action extends Yaf_Exception_LoadFailed {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_LoadFailed_Controller
Yaf_Exception_LoadFailed_View
Yaf


The Yaf_Exception_LoadFailed_View class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

Yaf_Exception_LoadFailed_View extends Yaf_Exception_LoadFailed {
/* Właściwości */
/* Metody */
/* Metody dziedziczone */
public Yaf_Exception::__construct ( void )
public void Yaf_Exception::getPrevious ( void )
}
Yaf_Exception_LoadFailed_Action
Inne serwisy
Yaf


Inne serwisy

  • AMQP
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • AMQPConnection — The AMQPConnection class
    • AMQPExchange — The AMQPExchange class
    • AMQPQueue — The AMQPQueue class
  • chdb — Constant hash database
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • chdb — The chdb class
    • chdb Funkcje
  • cURL — Client URL Library
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • cURL Funkcje
  • FAM — File Alteration Monitor
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • FAM Funkcje
  • FTP
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • FTP Funkcje
  • Gearman
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • GearmanClient — The GearmanClient class
    • GearmanJob — The GearmanJob class
    • GearmanTask — The GearmanTask class
    • GearmanWorker — The GearmanWorker class
  • Gopher — Net Gopher
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Gopher Funkcje
  • Gupnp
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Gupnp Funkcje
  • HTTP
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Request Options — Options usable with the HttpRequest class and request functions
    • HttpDeflateStream — The HttpDeflateStream class
    • HttpInflateStream — The HttpInflateStream class
    • HttpMessage — The HttpMessage class
    • HttpQueryString — The HttpQueryString class
    • HttpRequest — The HttpRequest
    • HttpRequestPool — The HttpRequestPool class
    • HttpResponse — The HttpResponse
    • HTTP Funkcje
  • Hyperwave
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Integration with Apache
    • Hyperwave Funkcje
  • Hyperwave API
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Hyperwave API Funkcje
  • Java — PHP / Java Integration
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Java Servlet SAPI
    • Przykłady
    • Java Funkcje
  • LDAP — Lightweight Directory Access Protocol
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Using the PHP LDAP calls
    • Przykłady
    • LDAP Funkcje
  • Lotus Notes
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Lotus Notes Funkcje
  • Memcache
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Memcache — The Memcache class
    • Memcache Funkcje
  • Memcached
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Expiration Times
    • Callbacks
    • Sessions support
    • Memcached — The Memcached class
  • mqseries
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • mqseries Funkcje
  • Network
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Network Funkcje
  • RRD — RRDtool
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • RRD Funkcje
    • RRDCreator — The RRDCreator class
    • RRDGraph — The RRDGraph class
    • RRDUpdater — The RRDUpdater class
  • SAM — Simple Asynchronous Messaging
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • SAM Funkcje
  • SNMP
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • SNMP Funkcje
    • SNMP — The SNMP class
    • SNMPException — The SNMPException class
  • Sockets
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Socket Errors
    • Socket Funkcje
  • SSH2 — Secure Shell2
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • SSH2 Funkcje
  • Stomp — Stomp Client
    • Wstęp
    • Instalacja/Konfiguracja
    • Przykłady
    • Stomp Funkcje
    • Stomp — The Stomp class
    • StompFrame — The StompFrame class
    • StompException — The StompException class
  • SVM — Support Vector Machine
    • Wstęp
    • Instalacja/Konfiguracja
    • Przykłady
    • SVM — The SVM class
    • SVMModel — The SVMModel class
  • SVN — Subversion
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • SVN Funkcje
  • TCP — TCP Wrappers
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • TCP Funkcje
  • Varnish
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • VarnishAdmin — The VarnishAdmin class
    • VarnishStat — The VarnishStat class
    • VarnishLog — The VarnishLog class
  • YAZ
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • YAZ Funkcje
  • YP/NIS
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • YP/NIS Funkcje
Yaf_Exception_LoadFailed_View
AMQP
Opis funkcji


AMQP

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • AMQPConnection — The AMQPConnection class
    • AMQPConnection::connect — Establish a connection with the AMQP broker.
    • AMQPConnection::__construct — Create an instance of AMQPConnection
    • AMQPConnection::disconnect — Closes the connection with the AMQP broker.
    • AMQPConnection::isConnected — Determine if the AMQPConnection object is connected to the broker.
    • AMQPConnection::reconnect — Closes any open connection and creates a new connection with the AMQP broker.
    • AMQPConnection::setHost — Set the amqp host.
    • AMQPConnection::setLogin — Set the login.
    • AMQPConnection::setPassword — Set the password.
    • AMQPConnection::setPort — Set the port.
    • AMQPConnection::setVhost — Set the amqp virtual host
  • AMQPExchange — The AMQPExchange class
    • AMQPExchange::bind — The bind purpose
    • AMQPExchange::__construct — Create an instance of AMQPExchange
    • AMQPExchange::declare — Declare a new exchange on the broker.
    • AMQPExchange::delete — Delete the exchange from the broker.
    • AMQPExchange::publish — Publish a message to an exchange.
  • AMQPQueue — The AMQPQueue class
    • AMQPQueue::ack — Acknowledge the receipt of a message
    • AMQPQueue::bind — Bind the given queue to a routing key on an exchange.
    • AMQPQueue::cancel — Cancel a queue binding.
    • AMQPQueue::__construct — Create an instance of an AMQPQueue object.
    • AMQPQueue::consume — The consume purpose
    • AMQPQueue::declare — Declare a new queue
    • AMQPQueue::delete — Delete a queue and its contents.
    • AMQPQueue::get — Retrieve the next message from the queue.
    • AMQPQueue::purge — Purge the contents of a queue
    • AMQPQueue::unbind — Unbind the queue from a routing key.
Inne serwisy
Wstęp
Inne serwisy


Wstęp

» AMQP stands for » Advanced Message Queue Protocol, which is an open standard middleware layer for message routing and queuing. This extension is compatible with any Version 0-8 compatible AMQP broker, such as » RabbitMQ and » OpenAMQ.

This extension relies on the » librabbitmq RPC library for communicating with the AMQP broker. Though named "rabbit", this library is compatible with all Version 0-8 compatible AMQP brokers.

AMQP
Instalacja/Konfiguracja
AMQP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
AMQP


Wymagania

This extension requires » librabbitmq client library.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To install the AMQP PHP extension, you must first install the » librabbitmq library. Use the following steps to download and install the library:

# Download the rabbitmq-c library
  hg clone http://hg.rabbitmq.com/rabbitmq-c/rev/3c549bb09c16 rabbitmq-c
  cd rabbitmq-c
  # Add the codegen requirement
  hg clone http://hg.rabbitmq.com/rabbitmq-codegen/rev/f8b34141e6cb codegen
  # Configure, compile and install
  autoreconf -i && ./configure && make && sudo make install

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/amqp.

Note to Windows users: This extension does not currently support Windows since the librabbitmq library does not yet support Windows.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Amqp Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
amqp.host | localhost | PHP_INI_ALL |
amqp.vhost | / | PHP_INI_ALL |
amqp.port | 5672 | PHP_INI_ALL |
amqp.login | guest | PHP_INI_ALL |
amqp.password | guest | PHP_INI_ALL |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

amqp.host string

The host to which to connect.

amqp.vhost string

The virtual host to which to connect on the host.

amqp.port integer

The port on which to connect.

amqp.login string

The login (username) used for authenticating against the host.

amqp.password string

The password used for authenticating against the host.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

AMQP_DURABLE (integer)
Durable exchanges and queues will survive a broker restart, complete with all of their data.
AMQP_PASSIVE (integer)
Passive exchanges are queues will not be redeclared, but the broker will throw an error if the exchange or queue does not exist.
AMQP_EXCLUSIVE (integer)
Valid for queues only, this flag indicates that only one client can be listening to and consuming from this queue.
AMQP_AUTODELETE (integer)
For exchanges, the auto delete flag indicates that the exchange will be deleted as soon as no more queues are bound to it. If no queues were ever bound the exchange, the exchange will never be deleted. For queues, the auto delete flag indicates that the queue will be deleted as soon as there are no more listeners subscribed to it. If no subscription has ever been active, the queue will never be deleted. Note: Exclusive queues will always be automatically deleted with the client disconnects.
AMQP_INTERNAL (integer)
Clients are not allowed to make specific queue bindings to exchanges defined with this flag.
AMQP_NOLOCAL (integer)
When passed to the consume method for a clustered environment, do not consume from the local node.
AMQP_NOACK (integer)
When passed to the consumer method, the messages will not be marked as delivered.
AMQP_IFEMPTY (integer)
Passed on queue creation, this flag indicates that the queue should be deleted if it becomes empty.
AMQP_IFUNUSED (integer)
Passed on queue or exchange creation, this flag indicates that the queue or exchange should be deleted when no clients are connected to the given queue or exchange.
AMQP_MANDATORY (integer)
When publishing a message, the message must be routed to a valid queue. If it is not, an error will be returned.
AMQP_IMMEDIATE (integer)
When publishing a message, mark this message for immediate processing by the broker. (High priority message.)
AMQP_MULTIPLE (integer)
?
AMQP_EX_TYPE_DIRECT (string)
A direct exchange type.
AMQP_EX_TYPE_FANOUT (string)
A fanout exchange type.
AMQP_EX_TYPE_TOPIC (string)
A topic exchange type.
AMQP_EX_TYPE_HEADER (string)
A header exchange type.

Typy zasobów
Przykłady
AMQP


Przykłady

Przykład #1 AMQP Example

<?php

// Create a connection
$cnn = new AMQPConnection();
$cnn->connect();

// Declare a new exchange
$ex = new AMQPExchange($cnn);
$ex->declare('exchange1', AMQP_EX_TYPE_FANOUT);

// Create a new queue
$q = new AMQPQueue($cnn);
$q->declare('queue1');

// Bind it on the exchange to routing.key
$ex->bind('queue1', 'routing.key');

// Publish a message to the exchange with a routing key
$ex->publish('message', 'routing.key');

// Read from the queue
$msg = $q->consume();

?>
Stałe predefiniowane
AMQPConnection
AMQP


The AMQPConnection class

(No version information available, might only be in SVN)

Wstęp

Represents a connection to an AMQP broker.

Krótki opis klasy

AMQPConnection {
/* Methods */
public bool connect ( void )
public __construct ([ array $credentials = array() ] )
public bool disconnect ( void )
public bool isConnected ( void )
public bool reconnect ( void )
public bool setHost ( string $host )
public bool setLogin ( string $login )
public bool setPassword ( string $password )
public bool setPort ( int $port )
public bool setVhost ( string $vhost )
}

Spis treści

  • AMQPConnection::connect — Establish a connection with the AMQP broker.
  • AMQPConnection::__construct — Create an instance of AMQPConnection
  • AMQPConnection::disconnect — Closes the connection with the AMQP broker.
  • AMQPConnection::isConnected — Determine if the AMQPConnection object is connected to the broker.
  • AMQPConnection::reconnect — Closes any open connection and creates a new connection with the AMQP broker.
  • AMQPConnection::setHost — Set the amqp host.
  • AMQPConnection::setLogin — Set the login.
  • AMQPConnection::setPassword — Set the password.
  • AMQPConnection::setPort — Set the port.
  • AMQPConnection::setVhost — Set the amqp virtual host
Przykłady
AMQPConnection::connect
AMQP


Establish a connection with the AMQP broker.

AMQPConnection
AMQPConnection::__construct
AMQPConnection
PHP Manual

AMQPConnection::connect

(No version information available, might only be in SVN)

AMQPConnection::connect — Establish a connection with the AMQP broker.

Opis

public bool AMQPConnection::connect ( void )

This method will initiate a connection with the AMQP broker.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 AMQPConnection::connect() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the login details
$cnn->setLogin('mylogin');
$cnn->setPassword('mypass');

if ($cnn->connect()) {
    echo "Established a connection to the broker";
}
else {
    echo "Cannot connect to the broker";
}

?>

AMQPConnection
AMQPConnection::__construct
AMQPConnection


Create an instance of AMQPConnection

AMQPConnection::connect
AMQPConnection::disconnect
AMQPConnection
PHP Manual

AMQPConnection::__construct

(PECL amqp >= Unknown)

AMQPConnection::__construct — Create an instance of AMQPConnection

Opis

public AMQPConnection::__construct ([ array $credentials = array() ] )

Creates an AMQPConnection instance representing a connection to an AMQP broker.

Parametry

credentials

The credentials is an optional array of credential information for connecting to the AMQP broker.

Supported indexes
key | Description | Default value
host The host to connect too

Informacja: Max 32 characters

 amqp.host
port | Port on the host | amqp.port
vhost The virtual host on the host

Informacja: Max 32 characters

 amqp.vhost
login The login name to use.

Informacja: Max 32 characters

 amqp.login
password Password

Informacja: Max 32 characters

 amqp.password

All other keys will be ignored.

Zwracane wartości

An AMQPConnection object.

Błędy/Wyjątki

Throws AMQPException exception on parameter parsing failures, and option errors.

Przykłady

Przykład #1 AMQPConnection::__construct() example

<?php

/* Create a connection using the INI values */
$connection1 = new AMQPConnection();

/* Specifying all keys */
$connection2 = new AMQPConnection(array(
    'host' => 'example.host',
    'vhost' => '/',
    'port' => 5763,
    'login' => 'user',
    'password' => 'password'
));

?>

Notatki

Informacja:

A connection will not be established untill AMQPConnection::connect() is called.

AMQPConnection::connect
AMQPConnection::disconnect
AMQPConnection


Closes the connection with the AMQP broker.

AMQPConnection::__construct
AMQPConnection::isConnected
AMQPConnection
PHP Manual

AMQPConnection::disconnect

(No version information available, might only be in SVN)

AMQPConnection::disconnect — Closes the connection with the AMQP broker.

Opis

public bool AMQPConnection::disconnect ( void )

This method will close an open connection with the AMQP broker.

Parametry

void

Zwracane wartości

Returns true if connection was successfully closed, false otherwise.

Przykłady

Przykład #1 AMQPConnection::disconnect() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the login details
$cnn->setLogin('mylogin');
$cnn->setPassword('mypass');

if (!$cnn->connect()) {
    throw new Exception('Could not connect');
}

// do something interesting

if (!$cnn->disconnect()) {
    throw new Exception('Could not disconnect');
}

?>

AMQPConnection::__construct
AMQPConnection::isConnected
AMQPConnection


Determine if the AMQPConnection object is connected to the broker.

AMQPConnection::disconnect
AMQPConnection::reconnect
AMQPConnection
PHP Manual

AMQPConnection::isConnected

(PECL amqp >= Unknown)

AMQPConnection::isConnected — Determine if the AMQPConnection object is connected to the broker.

Opis

public bool AMQPConnection::isConnected ( void )

This method will check whether the connection to the AMQP broker is still valid. It does so by checking the return status of the last command.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns true if connected, false otherwise

Przykłady

Przykład #1 AMQPConnection::isConnected() example

<?php

/* Create a new connection */
$conn = new AMQPConnection();
$conn->connect();

/* Check that connection is working */
if ($conn->isConnected()) {
    echo "Connected to the broker \o/";
}
else {
    echo "Cannot connect to the broker";
}

?>

AMQPConnection::disconnect
AMQPConnection::reconnect
AMQPConnection


Closes any open connection and creates a new connection with the AMQP broker.

AMQPConnection::isConnected
AMQPConnection::setHost
AMQPConnection
PHP Manual

AMQPConnection::reconnect

(No version information available, might only be in SVN)

AMQPConnection::reconnect — Closes any open connection and creates a new connection with the AMQP broker.

Opis

public bool AMQPConnection::reconnect ( void )

This method will close any open connections and initiate a new connection with the AMQP broker.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 AMQPConnection::reconnect() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the login details
$cnn->setLogin('mylogin');
$cnn->setPassword('mypass');

$cnn->connect();

// do something interesting

// ensure we have a valid connection
if (!$cnn->reconnect()) {
    echo "Could not reconnect to server";
}

?>

AMQPConnection::isConnected
AMQPConnection::setHost
AMQPConnection


Set the amqp host.

AMQPConnection::reconnect
AMQPConnection::setLogin
AMQPConnection
PHP Manual

AMQPConnection::setHost

(No version information available, might only be in SVN)

AMQPConnection::setHost — Set the amqp host.

Opis

public bool AMQPConnection::setHost ( string $host )

This method will set the hostname used to connect to the AMQP broker.

Parametry

host

The hostname of the AMQP broker.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws an AMQPConnectionException if host is longer then 1024characters.

Przykłady

Przykład #1 AMQPConnection::setHost() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the hostname
$cnn->setHost('myhost.com');

?>

AMQPConnection::reconnect
AMQPConnection::setLogin
AMQPConnection


Set the login.

AMQPConnection::setHost
AMQPConnection::setPassword
AMQPConnection
PHP Manual

AMQPConnection::setLogin

(No version information available, might only be in SVN)

AMQPConnection::setLogin — Set the login.

Opis

public bool AMQPConnection::setLogin ( string $login )

This method will set the login string used to connect to the AMQP broker.

Parametry

login

The login string used to authenticate with the AMQP broker.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws an AMQPConnectionException if login is longer then 32characters.

Przykłady

Przykład #1 AMQPConnection::setLogin() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the login
$cnn->setLogin('myusername');

?>

AMQPConnection::setHost
AMQPConnection::setPassword
AMQPConnection


Set the password.

AMQPConnection::setLogin
AMQPConnection::setPort
AMQPConnection
PHP Manual

AMQPConnection::setPassword

(No version information available, might only be in SVN)

AMQPConnection::setPassword — Set the password.

Opis

public bool AMQPConnection::setPassword ( string $password )

This method will set the password string used to connect to the AMQP broker.

Parametry

password

The password string used to authenticate with the AMQP broker.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws an AMQPConnectionException if password is longer then 32characters.

Przykłady

Przykład #1 AMQPConnection::setPassword() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the password
$cnn->setPassword('mypassword');

?>

AMQPConnection::setLogin
AMQPConnection::setPort
AMQPConnection


Set the port.

AMQPConnection::setPassword
AMQPConnection::setVhost
AMQPConnection
PHP Manual

AMQPConnection::setPort

(No version information available, might only be in SVN)

AMQPConnection::setPort — Set the port.

Opis

public bool AMQPConnection::setPort ( int $port )

This method will set the port used to connect to the AMQP broker.

Parametry

port

The port used to connect to the AMQP broker.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws an AMQPConnectionException if port is longer not between 1 and 65535.

Przykłady

Przykład #1 AMQPConnection::setPort() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the port
$cnn->setPort(5672);

?>

AMQPConnection::setPassword
AMQPConnection::setVhost
AMQPConnection


Set the amqp virtual host

AMQPConnection::setPort
AMQPExchange
AMQPConnection
PHP Manual

AMQPConnection::setVhost

(No version information available, might only be in SVN)

AMQPConnection::setVhost — Set the amqp virtual host

Opis

public bool AMQPConnection::setVhost ( string $vhost )

Sets the virtual host to which to connect on the AMQP broker.

Parametry

host

The virtual host to use on the AMQP broker.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws an AMQPConnectionException if host is longer then 32characters.

Przykłady

Przykład #1 AMQPConnection::setVhost() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();

// set the hostname
$cnn->setVhost('myvhost');

?>

AMQPConnection::setPort
AMQPExchange
AMQPConnection


The AMQPExchange class

(No version information available, might only be in SVN)

Wstęp

Represents an AMQP exchange.

Krótki opis klasy

AMQPExchange {
/* Methods */
public bool bind ( string $queue_name , string $routing_key )
public __construct ( AMQPConnection $connection [, string $exchange_name = "" ] )
public bool declare ([ string $exchange_name = "" [, string $exchange_type = AMQP_EX_TYPE_DIRECT [, int $flags = 0 ]]] )
public bool delete ([ string $exchange_name = NULL [, int $params = 0 ]] )
public bool publish ( string $message , string $routing_key [, int $params = 0 [, array $attributes ]] )
}

Spis treści

  • AMQPExchange::bind — The bind purpose
  • AMQPExchange::__construct — Create an instance of AMQPExchange
  • AMQPExchange::declare — Declare a new exchange on the broker.
  • AMQPExchange::delete — Delete the exchange from the broker.
  • AMQPExchange::publish — Publish a message to an exchange.
AMQPConnection::setVhost
AMQPExchange::bind
AMQP


The bind purpose

AMQPExchange
AMQPExchange::__construct
AMQPExchange
PHP Manual

AMQPExchange::bind

(PECL amqp >= Unknown)

AMQPExchange::bind — The bind purpose

Opis

public bool AMQPExchange::bind ( string $queue_name , string $routing_key )

Bind an exchange to a queue using the specified routing key.

Parametry

queue_name

The name of the queue to which to bind.

routing_key

The routing key to use as a binding.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws AMQPExchangeException on failure.

AMQPExchange
AMQPExchange::__construct
AMQPExchange


Create an instance of AMQPExchange

AMQPExchange::bind
AMQPExchange::declare
AMQPExchange
PHP Manual

AMQPExchange::__construct

(PECL amqp >= Unknown)

AMQPExchange::__construct — Create an instance of AMQPExchange

Opis

public AMQPExchange::__construct ( AMQPConnection $connection [, string $exchange_name = "" ] )

Returns a new instance of an AMQPExchange object, associated with the given AMQPConnection object. If the exchange_name parameter is specified and the an exchange by that name exists on the broker, an instance of that specific exchange will be returned. Otherwise, the exchange_name is ignored.

Parametry

AMQPConnection

A valid AMQPConnection object, connected to a broker.

exchange_name

The name of an existing exchange to represent.

Zwracane wartości

An AMQPExchange object.

Błędy/Wyjątki

Throws AMQPExchangeException when connection is not connect to a broker.

AMQPExchange::bind
AMQPExchange::declare
AMQPExchange


Declare a new exchange on the broker.

AMQPExchange::__construct
AMQPExchange::delete
AMQPExchange
PHP Manual

AMQPExchange::declare

(PECL amqp >= Unknown)

AMQPExchange::declare — Declare a new exchange on the broker.

Opis

public bool AMQPExchange::declare ([ string $exchange_name = "" [, string $exchange_type = AMQP_EX_TYPE_DIRECT [, int $flags = 0 ]]] )

Declare a new exchange on the broker with the given information. If an exchange by that name already exists and the exchange_type and/or flags are specified, the exchange settings will be updated.

If no exchange_type is specified and the exchange does not exist, the exchange type will default to "direct".

Parametry

exchange_name

The name of the exchange.

exchange_type

The type of the exchange. Can be any of AMQP_EX_TYPE_DIRECT, AMQP_EX_TYPE_FANOUT, AMQP_EX_TYPE_TOPIC or AMQP_EX_TYPE_HEADER.

flags

A bitmask of any of the flags: AMQP_PASSIVE, AMQP_DURABLE, AMQP_AUTODELETE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws AMQPExchangeException on failure.

Przykłady

Przykład #1 AMQPExchange::declare() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();
$cnn->connect();

$ex = new AMQPExchange($cnn);
$ex->declare('new_topic_exchange', AMQP_EX_TYPE_DIRECT, AMQP_DURABLE | AMQP_AUTODELETE);

?>

AMQPExchange::__construct
AMQPExchange::delete
AMQPExchange


Delete the exchange from the broker.

AMQPExchange::declare
AMQPExchange::publish
AMQPExchange
PHP Manual

AMQPExchange::delete

(PECL amqp >= Unknown)

AMQPExchange::delete — Delete the exchange from the broker.

Opis

public bool AMQPExchange::delete ([ string $exchange_name = NULL [, int $params = 0 ]] )

Delete and exchange from the broker.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

exchange_name

The name of the exchange to delete. If the AMQPExchange object is already bound to an existing exchange and then exchange_name is not specified, the exchange bound to the AMQPExchange object will be deleted.

params

Optionally AMQP_IFUNUSED can be specified to indicate the exchange should not be deleted until no clients are connected to it.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 AMQPExchange::delete() example

<?php

/* Create a new connection */
$cnn = new AMQPConnection();
$cnn->connect();

/* Create a new exchange */
$ex = new AMQPExchange($cnn);
$ex->declare('new_topic_exchange', AMQP_EX_TYPE_DIRECT, AMQP_DURABLE | AMQP_AUTODELETE);

/* Delete the previous exchange */
$ex2 = new AMQPExchange($cnn);
$ex2->delete('new_topic_exchange');

?>

AMQPExchange::declare
AMQPExchange::publish
AMQPExchange


Publish a message to an exchange.

AMQPExchange::delete
AMQPQueue
AMQPExchange
PHP Manual

AMQPExchange::publish

(PECL amqp >= Unknown)

AMQPExchange::publish — Publish a message to an exchange.

Opis

public bool AMQPExchange::publish ( string $message , string $routing_key [, int $params = 0 [, array $attributes ]] )

Publish a message to the exchange represented by the AMQPExchange object.

Parametry

message

The message to publish.

routing_key

The routing key to which to publish.

params

One or more of AMQP_MANDATORY and AMQP_IMMEDIATE.

attributes

Supported indexes
key | Description | Default value
Content-type | text/plain
Content-encoding | NULL
message_id | NULL
user_id | NULL
app_id | NULL
delivery_mode | NULL
priority | NULL
timestamp | NULL
expiration | NULL
type | NULL
reply_to | NULL

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws an AMQPExchangeException on failure.

AMQPExchange::delete
AMQPQueue
AMQPExchange


The AMQPQueue class

(No version information available, might only be in SVN)

Wstęp

Represents an AMQP queue.

Krótki opis klasy

AMQPQueue {
/* Methods */
public bool ack ( int $delivery_tag [, int $flags = NULL ] )
public bool bind ( string $exchange_name , string $routing_key )
public bool cancel ([ string $consumer_tag = "" ] )
public __construct ( AMQPConnection $amqp_connection [, string $queue_name = "" ] )
public array consume ([ array $options = array() ] )
public int declare ([ string $queue_name = "" [, int $flags = AMQP_AUTODELETE ]] )
public bool delete ( string $queue_name )
public array get ([ int $flags = AMQP_NOACK ] )
public bool purge ( string $queue_name )
public bool unbind ( string $exchange_name , string $routing_key )
}

Spis treści

  • AMQPQueue::ack — Acknowledge the receipt of a message
  • AMQPQueue::bind — Bind the given queue to a routing key on an exchange.
  • AMQPQueue::cancel — Cancel a queue binding.
  • AMQPQueue::__construct — Create an instance of an AMQPQueue object.
  • AMQPQueue::consume — The consume purpose
  • AMQPQueue::declare — Declare a new queue
  • AMQPQueue::delete — Delete a queue and its contents.
  • AMQPQueue::get — Retrieve the next message from the queue.
  • AMQPQueue::purge — Purge the contents of a queue
  • AMQPQueue::unbind — Unbind the queue from a routing key.
AMQPExchange::publish
AMQPQueue::ack
AMQP


Acknowledge the receipt of a message

AMQPQueue
AMQPQueue::bind
AMQPQueue
PHP Manual

AMQPQueue::ack

(No version information available, might only be in SVN)

AMQPQueue::ack — Acknowledge the receipt of a message

Opis

public bool AMQPQueue::ack ( int $delivery_tag [, int $flags = NULL ] )

This method allows the acknowledgement of a message that is retrieved with the AMQP_NOACK flag through AMQPQueue::get() or AMQPQueue::consume()

Parametry

delivery_tag

The message delivery tag of which to acknowledge receipt.

flags

The only valid flag that can be passed is AMQP_MULTIPLE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 AMQPQueue::ack() example with AMQPQueue::get()

<?php

/* Create a connection using all default credentials: */
$connection = new AMQPConnection();
$connection->connect();

/* create a queue object */
$queue = new AMQPQueue($connection);

//declare the queue
$queue->declare('myqueue');

//get the next message, but don't mark it as delivered
$message = $queue->get(AMQP_NOACK);

echo $message['msg'];

//acknowledge the message as received
$queue->ack($message['delivery_tag']);

?>

Przykład #2 AMQPQueue::ack() example with AMQPQueue::consume()

<?php

/* Create a connection using all default credentials: */
$connection = new AMQPConnection();
$connection->connect();

/* create a queue object */
$queue = new AMQPQueue($connection);

//declare the queue
$queue->declare('myqueue');

$options = array(
    'min' => 1,
    'max' => 10,
    'ack' => false
);

//get the messages, but don't mark them as delivered
$messages = $queue->consume($options);

foreach ($messages as $message) {
    echo $message['message_body'];
    //acknowledge the message as received
    $queue->ack($message['delivery_tag']);
}

?>

AMQPQueue
AMQPQueue::bind
AMQPQueue


Bind the given queue to a routing key on an exchange.

AMQPQueue::ack
AMQPQueue::cancel
AMQPQueue
PHP Manual

AMQPQueue::bind

(PECL amqp >= Unknown)

AMQPQueue::bind — Bind the given queue to a routing key on an exchange.

Opis

public bool AMQPQueue::bind ( string $exchange_name , string $routing_key )

The bind method will bind the given queue to the specified routing key on the given exchange.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

exchange_name

The exchange name on which to bind.

routing_key

The routing key to which to bind.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

AMQPQueue::ack
AMQPQueue::cancel
AMQPQueue


Cancel a queue binding.

AMQPQueue::bind
AMQPQueue::__construct
AMQPQueue
PHP Manual

AMQPQueue::cancel

(PECL amqp >= Unknown)

AMQPQueue::cancel — Cancel a queue binding.

Opis

public bool AMQPQueue::cancel ([ string $consumer_tag = "" ] )

Cancel a queue that is already bound to an exchange and routing key.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

consumer_tag

The queue name to cancel, if the queue object is not already representative of a queue.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

AMQPQueue::bind
AMQPQueue::__construct
AMQPQueue


Create an instance of an AMQPQueue object.

AMQPQueue::cancel
AMQPQueue::consume
AMQPQueue
PHP Manual

AMQPQueue::__construct

(PECL amqp >= Unknown)

AMQPQueue::__construct — Create an instance of an AMQPQueue object.

Opis

public AMQPQueue::__construct ( AMQPConnection $amqp_connection [, string $queue_name = "" ] )

Creates an AMQPQueue instance representing an AMQP queue on the broker.

Parametry

amqp_connection

A valid AMQPConnection object.

queue_name

The name of the queue to construct. If no queue name is specified, the broker will generate one.

Zwracane wartości

AMQPQueue::cancel
AMQPQueue::consume
AMQPQueue


The consume purpose

AMQPQueue::__construct
AMQPQueue::declare
AMQPQueue
PHP Manual

AMQPQueue::consume

(PECL amqp >= Unknown)

AMQPQueue::consume — The consume purpose

Opis

public array AMQPQueue::consume ([ array $options = array() ] )

This is a blocking function, in that the function will not return until the minimum number of of messages as specified by the min are read off of the queue. To use a non-blocking function, see AMQPQueue::get().

Parametry

options

options is a an array of consume options. The keys used in the options array are: min, max, and ack. All other keys will be ignored.

For each missing option, the extension will check the ini settings or use the default value.

Zwracane wartości

An array containing the messages consumed. The number of returned messages will be at least the number given by min in the options array. But not more than the number given by max.

Przykłady

Przykład #1 AMQPQueue::consume() example

<?php

/* Create a connection using all default credentials: */
$connection = new AMQPConnection();
$connection->connect();

/* create a queue object */
$queue = new AMQPQueue($connection);

//declare the queue
$queue->declare('myqueue');

$options = array(
    'min' => 1,
    'max' => 10,
    'ack' => true
);

//get the messages
$messages = $queue->consume($options);

foreach ($messages as $message) {
    echo $message['message_body'];
}

?>

AMQPQueue::__construct
AMQPQueue::declare
AMQPQueue


Declare a new queue

AMQPQueue::consume
AMQPQueue::delete
AMQPQueue
PHP Manual

AMQPQueue::declare

(PECL amqp >= Unknown)

AMQPQueue::declare — Declare a new queue

Opis

public int AMQPQueue::declare ([ string $queue_name = "" [, int $flags = AMQP_AUTODELETE ]] )

Declare a new queue on the broker.

Parametry

queue_name

The name of the queue to declare.

flags

A bitmask of any of the flags: AMQP_AUTODELETE, AMQP_PASSIVE, AMQP_DURABLE, AMQP_NOACK.

Zwracane wartości

Returns the message count.

AMQPQueue::consume
AMQPQueue::delete
AMQPQueue


Delete a queue and its contents.

AMQPQueue::declare
AMQPQueue::get
AMQPQueue
PHP Manual

AMQPQueue::delete

(PECL amqp >= Unknown)

AMQPQueue::delete — Delete a queue and its contents.

Opis

public bool AMQPQueue::delete ( string $queue_name )

Delete a queue from the broker, including its entire contents of unread or unacknowledged messages.

Parametry

queue_name

The name of the queue to delete.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

AMQPQueue::declare
AMQPQueue::get
AMQPQueue


Retrieve the next message from the queue.

AMQPQueue::delete
AMQPQueue::purge
AMQPQueue
PHP Manual

AMQPQueue::get

(PECL amqp >= Unknown)

AMQPQueue::get — Retrieve the next message from the queue.

Opis

public array AMQPQueue::get ([ int $flags = AMQP_NOACK ] )

Retrieve the next message from the queue. This is a non-blocking operation, which means that if there is no message on the queue, the function will return immediately with no message.

Parametry

flags

A bitmask of any of the flags: AMQP_NOACK.

Zwracane wartości

Returns array possibly containing keys routing_key, exchange, delivery_tag, Content-type, Content-encoding, type, timestamp, priority, expiration, user_id, app_id, message_id, Reply-to, count, msg.

Przykłady

Przykład #1 AMQPQueue::get() example

<?php

/* Create a connection using all default credentials: */
$connection = new AMQPConnection();
$connection->connect();

/* create a queue object */
$queue = new AMQPQueue($connection);

//declare the queue
$queue->declare('myqueue');

//get the next message
$message = $queue->get();

echo $message['msg'];

?>

AMQPQueue::delete
AMQPQueue::purge
AMQPQueue


Purge the contents of a queue

AMQPQueue::get
AMQPQueue::unbind
AMQPQueue
PHP Manual

AMQPQueue::purge

(PECL amqp >= Unknown)

AMQPQueue::purge — Purge the contents of a queue

Opis

public bool AMQPQueue::purge ( string $queue_name )

Purge the contents of a queue.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

queue_name

The name of the queue to purge

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

AMQPQueue::get
AMQPQueue::unbind
AMQPQueue


Unbind the queue from a routing key.

AMQPQueue::purge
chdb
AMQPQueue
PHP Manual

AMQPQueue::unbind

(PECL amqp >= Unknown)

AMQPQueue::unbind — Unbind the queue from a routing key.

Opis

public bool AMQPQueue::unbind ( string $exchange_name , string $routing_key )

Remove a routing key binding on an exchange from the given queue.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

exchange_name

The name of the exchange on which the queue is bound.

routing_key

The binding routing key used by the queue.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

AMQPQueue::purge
chdb
AMQPQueue


Constant hash database

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • chdb — The chdb class
    • chdb::__construct — Creates a chdb instance
    • chdb::get — Gets the value associated with a key
  • chdb Funkcje
    • chdb_create — Creates a chdb file
AMQPQueue::unbind
Wstęp
Inne serwisy


Wstęp

CHDB (constant hash database) is a fast key-value database for constant data, realized by using a memory-mapped file and thus providing the following functionalities:

  • Extremely fast initial load, regardless of the size of the database.

  • Only the pages of the file which are actually used are loaded from the disk.

  • Once a page is loaded it is shared across multiple processes.

  • Loaded pages are cached across multiple requests and even process recycling.

A typical use of CHDB is as a faster alternative to defining many PHP constants.

CHDB is internally implemented as a hash-table using a » perfect hashing function, thus guaranteeing worst case O(1) lookup time.

chdb
Instalacja/Konfiguracja
chdb


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
chdb


Wymagania

This module uses » cmph (version 0.9) for providing the » perfect hashing function.

cmph 0.9 is required to install this module.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/chdb

» cmph (version 0.9) is required for installing this extension. If cmph is installed in a non-standard directory, use the --with-libcmph-dir=DIR switch, where DIR is the cmph install prefix.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
chdb


Przykłady

Przykład #1 Creating a chdb file

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

?>

The above example will generate a chdb file named data.chdb and containing the key-value pairs defined in $data.

Przykład #2 Loading and looking up a chdb file

<?php

$chdb = new chdb('data.chdb');
$value1 = $chdb->get('key1');
$value2 = $chdb->get('key2');

echo $value1, PHP_EOL;
echo $value2, PHP_EOL;

?>

Powyższy przykład wyświetli coś podobnego do:

value1
value2
Stałe predefiniowane
chdb
chdb


The chdb class

(No version information available, might only be in SVN)

Wstęp

Represents a loaded chdb file.

Krótki opis klasy

chdb {
/* Methods */
public __construct ( string $pathname )
public string get ( string $key )
}

Spis treści

  • chdb::__construct — Creates a chdb instance
  • chdb::get — Gets the value associated with a key
Przykłady
chdb::__construct
chdb


Creates a chdb instance

chdb
chdb::get
chdb
PHP Manual

chdb::__construct

(PECL chdb >= 0.1.0)

chdb::__construct — Creates a chdb instance

Opis

public chdb::__construct ( string $pathname )

Loads a chdb file, by mapping it into memory.

Informacja:

While some validity checks are performed on the specified file, they are mostly there to avoid the possibility of common mistakes (for example, loading a file which is not a chdb database, or that is somehow incompatible with the current system). A maliciously crafted chdb file can thus be dangerous if loaded, so chdb files should be trusted and treated with the same security protections used for PHP shared libraries.

Parametry

pathname

The name of the file to load.

Błędy/Wyjątki

Throws an exception in case the chdb file hasn't been successfully loaded.

Informacja:

A valid chdb file might fail to load in case it was created on an architecture with a different endianness, with a different version of chdb, or if the file is too big to be mapped into memory (mostly in case of huge files and 32-bit architectures). In these cases the load will fail by throwing an exception, but otherwise not performing any illegal operation.

chdb
chdb::get
chdb


Gets the value associated with a key

chdb::__construct
chdb Funkcje
chdb
PHP Manual

chdb::get

(PECL chdb >= 0.1.0)

chdb::get — Gets the value associated with a key

Opis

public string chdb::get ( string $key )

Gets the value associated with a key from a chdb database.

Parametry

key

The key for which to get the value.

Zwracane wartości

Returns a string containing the value associated with the given key, or NULL if not found.

Przykłady

Przykład #1 chdb::get() example

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

$chdb = new chdb('data.chdb');
$value1 = $chdb->get('key1');
$value2 = $chdb->get('key2');

echo $value1, PHP_EOL;
echo $value2, PHP_EOL;

?>

Powyższy przykład wyświetli coś podobnego do:

value1
value2
chdb::__construct
chdb Funkcje
chdb


chdb Funkcje

Spis treści

  • chdb_create — Creates a chdb file
chdb::get
chdb_create
chdb


Creates a chdb file

chdb Funkcje
cURL
chdb Funkcje
PHP Manual

chdb_create

(PECL chdb >= 0.1.0)

chdb_create — Creates a chdb file

Opis

bool chdb_create ( string $pathname , array $data )

chdb_create() creates a chdb file containing the specified key-value pairs.

Informacja:

chdb files are not portable across little-endian and big-endian environments. Except for that, they are portable across different architectures. Also compatibility across different versions of chdb is not guaranteed.

Parametry

pathname

The name of the file to create.

If a file with the same name already exists, it is overwritten.

data

An array containing the key-value pairs to store in the chdb file.

Keys and values are converted to strings before being written to the file, as chdb only support the string type. Note that binary strings are supported as well, both as keys and values.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws an exception in case the chdb file hasn't been successfully created.

Przykłady

Przykład #1 chdb_create() example

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

?>

The above example will generate a chdb file named data.chdb and containing the key-value pairs defined in $data.

chdb Funkcje
cURL
chdb Funkcje


Client URL Library

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic curl example
  • cURL Funkcje
    • curl_close — Close a cURL session
    • curl_copy_handle — Copy a cURL handle along with all of its preferences
    • curl_errno — Return the last error number
    • curl_error — Return a string containing the last error for the current session
    • curl_exec — Perform a cURL session
    • curl_getinfo — Get information regarding a specific transfer
    • curl_init — Initialize a cURL session
    • curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle
    • curl_multi_close — Close a set of cURL handles
    • curl_multi_exec — Run the sub-connections of the current cURL handle
    • curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
    • curl_multi_info_read — Get information about the current transfers
    • curl_multi_init — Returns a new cURL multi handle
    • curl_multi_remove_handle — Remove a multi handle from a set of cURL handles
    • curl_multi_select — Wait for activity on any curl_multi connection
    • curl_setopt_array — Set multiple options for a cURL transfer
    • curl_setopt — Set an option for a cURL transfer
    • curl_version — Gets cURL version information
chdb_create
Wstęp
Inne serwisy


Wstęp

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

These functions have been added in PHP 4.0.2.

cURL
Instalacja/Konfiguracja
cURL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
cURL


Wymagania

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To use PHP's cURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the include directory there should be a folder named curl which should contain the easy.h and curl.h files. There should be a file named libcurl.a located in the lib directory. Beginning with PHP 4.3.0 you can configure PHP to use cURL for URL streams --with-curlwrappers .

Informacja: Note to Win32 Users
In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

cURL Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
curl.cainfo | NULL | PHP_INI_SYSTEM | Available since PHP 5.3.7.
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.

curl.cainfo string

A default value for the CURLOPT_CAINFO option. This is required to be an absolute path.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines two resource types: a cURL handle and a cURL multi handle.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

Descriptions and uses for these constants are described within the curl_setopt() and curl_getinfo() documentation.

CURLOPT_AUTOREFERER (integer)
Available since PHP 5.1.0
CURLOPT_COOKIESESSION (integer)
Available since PHP 5.1.0
CURLOPT_DNS_USE_GLOBAL_CACHE (integer)
CURLOPT_DNS_CACHE_TIMEOUT (integer)
CURLOPT_FTP_SSL (integer)
Available since PHP 5.2.0
CURLFTPSSL_TRY (integer)
Available since PHP 5.2.0
CURLFTPSSL_ALL (integer)
Available since PHP 5.2.0
CURLFTPSSL_CONTROL (integer)
Available since PHP 5.2.0
CURLFTPSSL_NONE (integer)
Available since PHP 5.2.0
CURLOPT_PRIVATE (integer)
Available since PHP 5.2.4
CURLOPT_FTPSSLAUTH (integer)
Available since PHP 5.1.0
CURLOPT_PORT (integer)
CURLOPT_FILE (integer)
CURLOPT_INFILE (integer)
CURLOPT_INFILESIZE (integer)
CURLOPT_URL (integer)
CURLOPT_PROXY (integer)
CURLOPT_VERBOSE (integer)
CURLOPT_HEADER (integer)
CURLOPT_HTTPHEADER (integer)
CURLOPT_NOPROGRESS (integer)
CURLOPT_NOBODY (integer)
CURLOPT_FAILONERROR (integer)
CURLOPT_UPLOAD (integer)
CURLOPT_POST (integer)
CURLOPT_FTPLISTONLY (integer)
CURLOPT_FTPAPPEND (integer)
CURLOPT_FTP_CREATE_MISSING_DIRS (integer)
CURLOPT_NETRC (integer)
CURLOPT_FOLLOWLOCATION (integer)
This constant is not available when open_basedir or safe_mode are enabled.
CURLOPT_FTPASCII (integer)
CURLOPT_PUT (integer)
CURLOPT_MUTE (integer)
CURLOPT_USERPWD (integer)
CURLOPT_PROXYUSERPWD (integer)
CURLOPT_RANGE (integer)
CURLOPT_TIMEOUT (integer)
CURLOPT_TIMEOUT_MS (integer)
CURLOPT_TCP_NODELAY (integer)
Available since PHP 5.2.1
CURLOPT_POSTFIELDS (integer)
CURLOPT_PROGRESSFUNCTION (integer)
Available since PHP 5.3.0
CURLOPT_REFERER (integer)
CURLOPT_USERAGENT (integer)
CURLOPT_FTPPORT (integer)
CURLOPT_FTP_USE_EPSV (integer)
CURLOPT_LOW_SPEED_LIMIT (integer)
CURLOPT_LOW_SPEED_TIME (integer)
CURLOPT_RESUME_FROM (integer)
CURLOPT_COOKIE (integer)
CURLOPT_SSLCERT (integer)
CURLOPT_SSLCERTPASSWD (integer)
CURLOPT_WRITEHEADER (integer)
CURLOPT_SSL_VERIFYHOST (integer)
CURLOPT_COOKIEFILE (integer)
CURLOPT_SSLVERSION (integer)
CURLOPT_TIMECONDITION (integer)
CURLOPT_TIMEVALUE (integer)
CURLOPT_CUSTOMREQUEST (integer)
CURLOPT_STDERR (integer)
CURLOPT_TRANSFERTEXT (integer)
CURLOPT_RETURNTRANSFER (integer)
CURLOPT_QUOTE (integer)
CURLOPT_POSTQUOTE (integer)
CURLOPT_INTERFACE (integer)
CURLOPT_KRB4LEVEL (integer)
CURLOPT_HTTPPROXYTUNNEL (integer)
CURLOPT_FILETIME (integer)
CURLOPT_WRITEFUNCTION (integer)
CURLOPT_READFUNCTION (integer)
CURLOPT_PASSWDFUNCTION (integer)
CURLOPT_HEADERFUNCTION (integer)
CURLOPT_MAXREDIRS (integer)
CURLOPT_MAXCONNECTS (integer)
CURLOPT_CLOSEPOLICY (integer)
CURLOPT_FRESH_CONNECT (integer)
CURLOPT_FORBID_REUSE (integer)
CURLOPT_RANDOM_FILE (integer)
CURLOPT_EGDSOCKET (integer)
CURLOPT_CONNECTTIMEOUT (integer)
CURLOPT_CONNECTTIMEOUT_MS (integer)
CURLOPT_SSL_VERIFYPEER (integer)
CURLOPT_CAINFO (integer)
CURLOPT_CAPATH (integer)
CURLOPT_COOKIEJAR (integer)
CURLOPT_SSL_CIPHER_LIST (integer)
CURLOPT_BINARYTRANSFER (integer)
CURLOPT_NOSIGNAL (integer)
CURLOPT_PROXYTYPE (integer)
CURLOPT_BUFFERSIZE (integer)
CURLOPT_HTTPGET (integer)
CURLOPT_HTTP_VERSION (integer)
CURLOPT_SSLKEY (integer)
CURLOPT_SSLKEYTYPE (integer)
CURLOPT_SSLKEYPASSWD (integer)
CURLOPT_SSLENGINE (integer)
CURLOPT_SSLENGINE_DEFAULT (integer)
CURLOPT_SSLCERTTYPE (integer)
CURLOPT_CRLF (integer)
CURLOPT_ENCODING (integer)
CURLOPT_PROXYPORT (integer)
CURLOPT_UNRESTRICTED_AUTH (integer)
CURLOPT_FTP_USE_EPRT (integer)
CURLOPT_HTTP200ALIASES (integer)
CURLOPT_HTTPAUTH (integer)
CURLAUTH_BASIC (integer)
CURLAUTH_DIGEST (integer)
CURLAUTH_GSSNEGOTIATE (integer)
CURLAUTH_NTLM (integer)
CURLAUTH_ANY (integer)
CURLAUTH_ANYSAFE (integer)
CURLOPT_PROXYAUTH (integer)
CURLOPT_MAX_RECV_SPEED_LARGE (integer)
Available since PHP 5.4.0 and cURL 7.15.5
CURLOPT_MAX_SEND_SPEED_LARGE (integer)
Available since PHP 5.4.0 and cURL 7.15.5
CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)
CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)
CURLCLOSEPOLICY_SLOWEST (integer)
CURLCLOSEPOLICY_CALLBACK (integer)
CURLCLOSEPOLICY_OLDEST (integer)
CURLINFO_PRIVATE (integer)
Available since PHP 5.2.4
CURLINFO_EFFECTIVE_URL (integer)
CURLINFO_HTTP_CODE (integer)
CURLINFO_HEADER_OUT (integer)
Available since PHP 5.1.3
CURLINFO_HEADER_SIZE (integer)
CURLINFO_REQUEST_SIZE (integer)
CURLINFO_TOTAL_TIME (integer)
CURLINFO_NAMELOOKUP_TIME (integer)
CURLINFO_CONNECT_TIME (integer)
CURLINFO_PRETRANSFER_TIME (integer)
CURLINFO_SIZE_UPLOAD (integer)
CURLINFO_SIZE_DOWNLOAD (integer)
CURLINFO_SPEED_DOWNLOAD (integer)
CURLINFO_SPEED_UPLOAD (integer)
CURLINFO_FILETIME (integer)
CURLINFO_SSL_VERIFYRESULT (integer)
CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)
CURLINFO_CONTENT_LENGTH_UPLOAD (integer)
CURLINFO_STARTTRANSFER_TIME (integer)
CURLINFO_CONTENT_TYPE (integer)
CURLINFO_REDIRECT_TIME (integer)
CURLINFO_REDIRECT_COUNT (integer)
CURL_TIMECOND_IFMODSINCE (integer)
CURL_TIMECOND_IFUNMODSINCE (integer)
CURL_TIMECOND_LASTMOD (integer)
CURL_VERSION_IPV6 (integer)
CURL_VERSION_KERBEROS4 (integer)
CURL_VERSION_SSL (integer)
CURL_VERSION_LIBZ (integer)
CURLVERSION_NOW (integer)
CURLE_OK (integer)
CURLE_UNSUPPORTED_PROTOCOL (integer)
CURLE_FAILED_INIT (integer)
CURLE_URL_MALFORMAT (integer)
CURLE_URL_MALFORMAT_USER (integer)
CURLE_COULDNT_RESOLVE_PROXY (integer)
CURLE_COULDNT_RESOLVE_HOST (integer)
CURLE_COULDNT_CONNECT (integer)
CURLE_FTP_WEIRD_SERVER_REPLY (integer)
CURLE_FTP_ACCESS_DENIED (integer)
CURLE_FTP_USER_PASSWORD_INCORRECT (integer)
CURLE_FTP_WEIRD_PASS_REPLY (integer)
CURLE_FTP_WEIRD_USER_REPLY (integer)
CURLE_FTP_WEIRD_PASV_REPLY (integer)
CURLE_FTP_WEIRD_227_FORMAT (integer)
CURLE_FTP_CANT_GET_HOST (integer)
CURLE_FTP_CANT_RECONNECT (integer)
CURLE_FTP_COULDNT_SET_BINARY (integer)
CURLE_PARTIAL_FILE (integer)
CURLE_FTP_COULDNT_RETR_FILE (integer)
CURLE_FTP_WRITE_ERROR (integer)
CURLE_FTP_QUOTE_ERROR (integer)
CURLE_HTTP_NOT_FOUND (integer)
CURLE_WRITE_ERROR (integer)
CURLE_MALFORMAT_USER (integer)
CURLE_FTP_COULDNT_STOR_FILE (integer)
CURLE_READ_ERROR (integer)
CURLE_OUT_OF_MEMORY (integer)
CURLE_OPERATION_TIMEOUTED (integer)
CURLE_FTP_COULDNT_SET_ASCII (integer)
CURLE_FTP_PORT_FAILED (integer)
CURLE_FTP_COULDNT_USE_REST (integer)
CURLE_FTP_COULDNT_GET_SIZE (integer)
CURLE_HTTP_RANGE_ERROR (integer)
CURLE_HTTP_POST_ERROR (integer)
CURLE_SSL_CONNECT_ERROR (integer)
CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)
CURLE_FILE_COULDNT_READ_FILE (integer)
CURLE_LDAP_CANNOT_BIND (integer)
CURLE_LDAP_SEARCH_FAILED (integer)
CURLE_LIBRARY_NOT_FOUND (integer)
CURLE_FUNCTION_NOT_FOUND (integer)
CURLE_ABORTED_BY_CALLBACK (integer)
CURLE_BAD_FUNCTION_ARGUMENT (integer)
CURLE_BAD_CALLING_ORDER (integer)
CURLE_HTTP_PORT_FAILED (integer)
CURLE_BAD_PASSWORD_ENTERED (integer)
CURLE_TOO_MANY_REDIRECTS (integer)
CURLE_UNKNOWN_TELNET_OPTION (integer)
CURLE_TELNET_OPTION_SYNTAX (integer)
CURLE_OBSOLETE (integer)
CURLE_SSL_PEER_CERTIFICATE (integer)
CURLE_GOT_NOTHING (integer)
CURLE_SSL_ENGINE_NOTFOUND (integer)
CURLE_SSL_ENGINE_SETFAILED (integer)
CURLE_SEND_ERROR (integer)
CURLE_RECV_ERROR (integer)
CURLE_SHARE_IN_USE (integer)
CURLE_SSL_CERTPROBLEM (integer)
CURLE_SSL_CIPHER (integer)
CURLE_SSL_CACERT (integer)
CURLE_BAD_CONTENT_ENCODING (integer)
CURLE_LDAP_INVALID_URL (integer)
CURLE_FILESIZE_EXCEEDED (integer)
CURLE_FTP_SSL_FAILED (integer)
CURLFTPAUTH_DEFAULT (integer)
Available since PHP 5.1.0
CURLFTPAUTH_SSL (integer)
Available since PHP 5.1.0
CURLFTPAUTH_TLS (integer)
Available since PHP 5.1.0
CURLPROXY_HTTP (integer)
CURLPROXY_SOCKS5 (integer)
CURL_NETRC_OPTIONAL (integer)
CURL_NETRC_IGNORED (integer)
CURL_NETRC_REQUIRED (integer)
CURL_HTTP_VERSION_NONE (integer)
CURL_HTTP_VERSION_1_0 (integer)
CURL_HTTP_VERSION_1_1 (integer)
CURLM_CALL_MULTI_PERFORM (integer)
CURLM_OK (integer)
CURLM_BAD_HANDLE (integer)
CURLM_BAD_EASY_HANDLE (integer)
CURLM_OUT_OF_MEMORY (integer)
CURLM_INTERNAL_ERROR (integer)
CURLMSG_DONE (integer)
Typy zasobów
Przykłady
cURL


Przykłady

Spis treści

  • Basic curl example
Stałe predefiniowane
Basic curl example
cURL


Basic curl example

Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close(). Here is an example that uses the cURL functions to fetch the example.com homepage into a file:

Przykład #1 Using PHP's cURL module to fetch the example.com homepage

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

Przykłady
cURL Funkcje
Przykłady


cURL Funkcje

Spis treści

  • curl_close — Close a cURL session
  • curl_copy_handle — Copy a cURL handle along with all of its preferences
  • curl_errno — Return the last error number
  • curl_error — Return a string containing the last error for the current session
  • curl_exec — Perform a cURL session
  • curl_getinfo — Get information regarding a specific transfer
  • curl_init — Initialize a cURL session
  • curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle
  • curl_multi_close — Close a set of cURL handles
  • curl_multi_exec — Run the sub-connections of the current cURL handle
  • curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
  • curl_multi_info_read — Get information about the current transfers
  • curl_multi_init — Returns a new cURL multi handle
  • curl_multi_remove_handle — Remove a multi handle from a set of cURL handles
  • curl_multi_select — Wait for activity on any curl_multi connection
  • curl_setopt_array — Set multiple options for a cURL transfer
  • curl_setopt — Set an option for a cURL transfer
  • curl_version — Gets cURL version information
Basic curl example
curl_close
cURL


Close a cURL session

cURL Funkcje
curl_copy_handle
cURL Funkcje
PHP Manual

curl_close

(PHP 4 >= 4.0.2, PHP 5)

curl_close — Close a cURL session

Opis

void curl_close ( resource $ch )

Closes a cURL session and frees all resources. The cURL handle, ch, is also deleted.

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Zobacz też:

  • curl_init() - Initialize a cURL session
  • curl_multi_close() - Close a set of cURL handles

cURL Funkcje
curl_copy_handle
cURL Funkcje


Copy a cURL handle along with all of its preferences

curl_close
curl_errno
cURL Funkcje
PHP Manual

curl_copy_handle

(PHP 5)

curl_copy_handle — Copy a cURL handle along with all of its preferences

Opis

resource curl_copy_handle ( resource $ch )

Copies a cURL handle keeping the same preferences.

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

Zwracane wartości

Returns a new cURL handle.

Przykłady

Przykład #1 Copying a cURL handle

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);

// copy the handle
$ch2 = curl_copy_handle($ch);

// grab URL (http://www.example.com/) and pass it to the browser
curl_exec($ch2);

// close cURL resources, and free up system resources
curl_close($ch2);
curl_close($ch);
?>

curl_close
curl_errno
cURL Funkcje


Return the last error number

curl_copy_handle
curl_error
cURL Funkcje
PHP Manual

curl_errno

(PHP 4 >= 4.0.3, PHP 5)

curl_errno — Return the last error number

Opis

int curl_errno ( resource $ch )

Returns the error number for the last cURL operation.

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

Zwracane wartości

Returns the error number or 0 (zero) if no error occurred.

Przykłady

Przykład #1 curl_errno() example

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');

// Execute
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);

// Check if any error occured
if(curl_errno($ch))
{
    echo 'Curl error: ' . curl_error($ch);
}

// Close handle
curl_close($ch);
?>

Zobacz też:

  • curl_error() - Return a string containing the last error for the current session
  • » Curl error codes

curl_copy_handle
curl_error
cURL Funkcje


Return a string containing the last error for the current session

curl_errno
curl_exec
cURL Funkcje
PHP Manual

curl_error

(PHP 4 >= 4.0.3, PHP 5)

curl_error — Return a string containing the last error for the current session

Opis

string curl_error ( resource $ch )

Returns a clear text error message for the last cURL operation.

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

Zwracane wartości

Returns the error message or '' (the empty string) if no error occurred.

Przykłady

Przykład #1 curl_error() example

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);
?>

Zobacz też:

  • curl_errno() - Return the last error number
  • » Curl error codes

curl_errno
curl_exec
cURL Funkcje


Perform a cURL session

curl_error
curl_getinfo
cURL Funkcje
PHP Manual

curl_exec

(PHP 4 >= 4.0.2, PHP 5)

curl_exec — Perform a cURL session

Opis

mixed curl_exec ( resource $ch )

Execute the given cURL session.

This function should be called after initializing a cURL session and all the options for the session are set.

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

Przykłady

Przykład #1 Fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Zobacz też:

  • curl_multi_exec() - Run the sub-connections of the current cURL handle

curl_error
curl_getinfo
cURL Funkcje


Get information regarding a specific transfer

curl_exec
curl_init
cURL Funkcje
PHP Manual

curl_getinfo

(PHP 4 >= 4.0.4, PHP 5)

curl_getinfo — Get information regarding a specific transfer

Opis

mixed curl_getinfo ( resource $ch [, int $opt = 0 ] )

Gets information about the last transfer.

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

opt

This may be one of the following constants:

  • CURLINFO_EFFECTIVE_URL - Last effective URL
  • CURLINFO_HTTP_CODE - Last received HTTP code
  • CURLINFO_FILETIME - Remote time of the retrieved document, if -1 is returned the time of the document is unknown
  • CURLINFO_TOTAL_TIME - Total transaction time in seconds for last transfer
  • CURLINFO_NAMELOOKUP_TIME - Time in seconds until name resolving was complete
  • CURLINFO_CONNECT_TIME - Time in seconds it took to establish the connection
  • CURLINFO_PRETRANSFER_TIME - Time in seconds from start until just before file transfer begins
  • CURLINFO_STARTTRANSFER_TIME - Time in seconds until the first byte is about to be transferred
  • CURLINFO_REDIRECT_TIME - Time in seconds of all redirection steps before final transaction was started
  • CURLINFO_SIZE_UPLOAD - Total number of bytes uploaded
  • CURLINFO_SIZE_DOWNLOAD - Total number of bytes downloaded
  • CURLINFO_SPEED_DOWNLOAD - Average download speed
  • CURLINFO_SPEED_UPLOAD - Average upload speed
  • CURLINFO_HEADER_SIZE - Total size of all headers received
  • CURLINFO_HEADER_OUT - The request string sent. For this to work, add the CURLINFO_HEADER_OUT option to the handle by calling curl_setopt()
  • CURLINFO_REQUEST_SIZE - Total size of issued requests, currently only for HTTP requests
  • CURLINFO_SSL_VERIFYRESULT - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD - content-length of download, read from Content-Length: field
  • CURLINFO_CONTENT_LENGTH_UPLOAD - Specified size of upload
  • CURLINFO_CONTENT_TYPE - Content-Type: of the requested document, NULL indicates server did not send valid Content-Type: header

Zwracane wartości

If opt is given, returns its value as a string. Otherwise, returns an associative array with the following elements (which correspond to opt), or FALSE on failure:

  • "url"
  • "content_type"
  • "http_code"
  • "header_size"
  • "request_size"
  • "filetime"
  • "ssl_verify_result"
  • "redirect_count"
  • "total_time"
  • "namelookup_time"
  • "connect_time"
  • "pretransfer_time"
  • "size_upload"
  • "size_download"
  • "speed_download"
  • "speed_upload"
  • "download_content_length"
  • "upload_content_length"
  • "starttransfer_time"
  • "redirect_time"
  • "certinfo"
  • "request_header" (This is only set if the CURLINFO_HEADER_OUT is set by a previous call to curl_setopt())

Rejestr zmian

Wersja | Opis
5.1.3 | Introduced CURLINFO_HEADER_OUT.

Przykłady

Przykład #1 curl_getinfo() example

<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');

// Execute
curl_exec($ch);

// Check if any error occured
if(!curl_errno($ch))
{
 $info = curl_getinfo($ch);

 echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}

// Close handle
curl_close($ch);
?>

Notatki

Informacja:

Information gathered by this function is kept if the handle is re-used. This means that unless a statistic is overridden internally by this function, the previous info is returned.

curl_exec
curl_init
cURL Funkcje


Initialize a cURL session

curl_getinfo
curl_multi_add_handle
cURL Funkcje
PHP Manual

curl_init

(PHP 4 >= 4.0.2, PHP 5)

curl_init — Initialize a cURL session

Opis

resource curl_init ([ string $url = NULL ] )

Initializes a new session and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions.

Parametry

url

If provided, the CURLOPT_URL option will be set to its value. You can manually set this using the curl_setopt() function.

Informacja:

The file protocol is disabled by cURL if open_basedir is set.

Zwracane wartości

Returns a cURL handle on success, FALSE on errors.

Przykłady

Przykład #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Zobacz też:

  • curl_close() - Close a cURL session
  • curl_multi_init() - Returns a new cURL multi handle

curl_getinfo
curl_multi_add_handle
cURL Funkcje


Add a normal cURL handle to a cURL multi handle

curl_init
curl_multi_close
cURL Funkcje
PHP Manual

curl_multi_add_handle

(PHP 5)

curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle

Opis

int curl_multi_add_handle ( resource $mh , resource $ch )

Adds the ch handle to the multi handle mh

Parametry

mh

Wielokrotny uchwyt cURL zwrócony przez curl_multi_init().

ch

Uchwyt cURL zwrócony przez curl_init().

Zwracane wartości

Returns 0 on success, or one of the CURLM_XXX errors code.

Przykłady

Przykład #1 curl_multi_add_handle() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
//execute the handles
do {
    curl_multi_exec($mh,$running);
} while($running > 0);

//close all the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
?>

Zobacz też:

  • curl_multi_remove_handle() - Remove a multi handle from a set of cURL handles
  • curl_multi_init() - Returns a new cURL multi handle
  • curl_init() - Initialize a cURL session

curl_init
curl_multi_close
cURL Funkcje


Close a set of cURL handles

curl_multi_add_handle
curl_multi_exec
cURL Funkcje
PHP Manual

curl_multi_close

(PHP 5)

curl_multi_close — Close a set of cURL handles

Opis

void curl_multi_close ( resource $mh )

Closes a set of cURL handles.

Parametry

mh

Wielokrotny uchwyt cURL zwrócony przez curl_multi_init().

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 curl_multi_close() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$running=null;
//execute the handles
do {
    curl_multi_exec($mh,$running);
} while ($running > 0);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

Zobacz też:

  • curl_multi_init() - Returns a new cURL multi handle
  • curl_close() - Close a cURL session

curl_multi_add_handle
curl_multi_exec
cURL Funkcje


Run the sub-connections of the current cURL handle

curl_multi_close
curl_multi_getcontent
cURL Funkcje
PHP Manual

curl_multi_exec

(PHP 5)

curl_multi_exec — Run the sub-connections of the current cURL handle

Opis

int curl_multi_exec ( resource $mh , int &$still_running )

Processes each of the handles in the stack. This method can be called whether or not a handle needs to read or write data.

Parametry

mh

Wielokrotny uchwyt cURL zwrócony przez curl_multi_init().

still_running

A reference to a flag to tell whether the operations are still running.

Zwracane wartości

A cURL code defined in the cURL Predefined Constants.

Informacja:

This only returns errors regarding the whole multi stack. There might still have occurred problems on individual transfers even when this function returns CURLM_OK.

Przykłady

Przykład #1 curl_multi_exec() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

Zobacz też:

  • curl_multi_init() - Returns a new cURL multi handle
  • curl_multi_select() - Wait for activity on any curl_multi connection
  • curl_exec() - Perform a cURL session

curl_multi_close
curl_multi_getcontent
cURL Funkcje


Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

curl_multi_exec
curl_multi_info_read
cURL Funkcje
PHP Manual

curl_multi_getcontent

(PHP 5)

curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

Opis

string curl_multi_getcontent ( resource $ch )

If CURLOPT_RETURNTRANSFER is an option that is set for a specific handle, then this function will return the content of that cURL handle in the form of a string.

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

Zwracane wartości

Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set.

Zobacz też:

  • curl_multi_init() - Returns a new cURL multi handle

curl_multi_exec
curl_multi_info_read
cURL Funkcje


Get information about the current transfers

curl_multi_getcontent
curl_multi_init
cURL Funkcje
PHP Manual

curl_multi_info_read

(PHP 5)

curl_multi_info_read — Get information about the current transfers

Opis

array curl_multi_info_read ( resource $mh [, int &$msgs_in_queue = NULL ] )

Ask the multi handle if there are any messages or information from the individual transfers. Messages may include information such as an error code from the transfer or just the fact that a transfer is completed.

Repeated calls to this function will return a new result each time, until a FALSE is returned as a signal that there is no more to get at this point. The integer pointed to with msgs_in_queue will contain the number of remaining messages after this function was called.

Ostrzeżenie

The data the returned resource points to will not survive calling curl_multi_remove_handle().

Parametry

mh

Wielokrotny uchwyt cURL zwrócony przez curl_multi_init().

msgs_in_queue

Number of messages that are still in the queue

Zwracane wartości

On success, returns an associative array for the message, FALSE on failure.

Contents of the returned array
Key: | Value:
msg | The CURLMSG_DONE constant. Other return values are currently not available.
result | One of the CURLE_* constants. If everything is OK, the CURLE_OK will be the result.
handle | Resource of type curl indicates the handle which it concerns.

Przykłady

Przykład #1 A curl_multi_info_read() example

<?php

$urls = array(
   "http://www.cnn.com/",
   "http://www.bbc.co.uk/",
   "http://www.yahoo.com/"
);

$mh = curl_multi_init();

foreach ($urls as $i => $url) {
    $conn[$i] = curl_init($url);
    curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($mh, $conn[$i]);
}

do {
    $status = curl_multi_exec($mh, $active);
    $info = curl_multi_info_read($mh);
    if (false !== $info) {
        var_dump($info);
    }
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);

foreach ($urls as $i => $url) {
    $res[$i] = curl_multi_getcontent($conn[$i]);
    curl_close($conn[$i]);
}

var_dump(curl_multi_info_read($mh));

?>

Powyższy przykład wyświetli coś podobnego do:

array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(5) of type (curl)
}
array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(7) of type (curl)
}
array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(6) of type (curl)
}
bool(false)

Rejestr zmian

Wersja | Opis
5.2.0 | msgs_in_queue was added.

Zobacz też:

  • curl_multi_init() - Returns a new cURL multi handle

curl_multi_getcontent
curl_multi_init
cURL Funkcje


Returns a new cURL multi handle

curl_multi_info_read
curl_multi_remove_handle
cURL Funkcje
PHP Manual

curl_multi_init

(PHP 5)

curl_multi_init — Returns a new cURL multi handle

Opis

resource curl_multi_init ( void )

Allows the processing of multiple cURL handles in parallel.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a cURL multi handle resource on success, FALSE on failure.

Przykłady

Przykład #1 curl_multi_init() example

This example will create two cURL handles, add them to a multi handle, and then run them in parallel.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

Zobacz też:

  • curl_init() - Initialize a cURL session
  • curl_multi_close() - Close a set of cURL handles

curl_multi_info_read
curl_multi_remove_handle
cURL Funkcje


Remove a multi handle from a set of cURL handles

curl_multi_init
curl_multi_select
cURL Funkcje
PHP Manual

curl_multi_remove_handle

(PHP 5)

curl_multi_remove_handle — Remove a multi handle from a set of cURL handles

Opis

int curl_multi_remove_handle ( resource $mh , resource $ch )

Removes a given ch handle from the given mh handle. When the ch handle has been removed, it is again perfectly legal to run curl_exec() on this handle. Removing the ch handle while being used, will effectively halt the transfer in progress involving that handle.

Parametry

mh

Wielokrotny uchwyt cURL zwrócony przez curl_multi_init().

ch

Uchwyt cURL zwrócony przez curl_init().

Zwracane wartości

Returns 0 on success, or one of the CURLM_XXX error codes.

Zobacz też:

  • curl_init() - Initialize a cURL session
  • curl_multi_init() - Returns a new cURL multi handle
  • curl_multi_add_handle() - Add a normal cURL handle to a cURL multi handle

curl_multi_init
curl_multi_select
cURL Funkcje


Wait for activity on any curl_multi connection

curl_multi_remove_handle
curl_setopt_array
cURL Funkcje
PHP Manual

curl_multi_select

(PHP 5)

curl_multi_select — Wait for activity on any curl_multi connection

Opis

int curl_multi_select ( resource $mh [, float $timeout = 1.0 ] )

Blocks until there is activity on any of the curl_multi connections.

Parametry

mh

Wielokrotny uchwyt cURL zwrócony przez curl_multi_init().

timeout

Time, in seconds, to wait for a response.

Zwracane wartości

On success, returns the number of descriptors contained in the descriptor sets. On failure, this function will return -1 on a select failure or timeout (from the underlying select system call).

Zobacz też:

  • curl_multi_init() - Returns a new cURL multi handle

curl_multi_remove_handle
curl_setopt_array
cURL Funkcje


Set multiple options for a cURL transfer

curl_multi_select
curl_setopt
cURL Funkcje
PHP Manual

curl_setopt_array

(PHP 5 >= 5.1.3)

curl_setopt_array — Set multiple options for a cURL transfer

Opis

bool curl_setopt_array ( resource $ch , array $options )

Sets multiple options for a cURL session. This function is useful for setting a large amount of cURL options without repetitively calling curl_setopt().

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

options

An array specifying which options to set and their values. The keys should be valid curl_setopt() constants or their integer equivalents.

Zwracane wartości

Returns TRUE if all options were successfully set. If an option could not be successfully set, FALSE is immediately returned, ignoring any future options in the options array.

Przykłady

Przykład #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
$options = array(CURLOPT_URL => 'http://www.example.com/',
                 CURLOPT_HEADER => false
                );

curl_setopt_array($ch, $options);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Prior to PHP 5.1.3 this function can be simulated with:

Przykład #2 Our own implementation of curl_setopt_array()

<?php
if (!function_exists('curl_setopt_array')) {
   function curl_setopt_array(&$ch, $curl_options)
   {
       foreach ($curl_options as $option => $value) {
           if (!curl_setopt($ch, $option, $value)) {
               return false;
           }
       }
       return true;
   }
}
?>

Notatki

Informacja:

As with curl_setopt(), passing an array to CURLOPT_POST will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

Zobacz też:

  • curl_setopt() - Set an option for a cURL transfer

curl_multi_select
curl_setopt
cURL Funkcje


Set an option for a cURL transfer

curl_setopt_array
curl_version
cURL Funkcje
PHP Manual

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt — Set an option for a cURL transfer

Opis

bool curl_setopt ( resource $ch , int $option , mixed $value )

Sets an option on the given cURL session handle.

Parametry

ch

Uchwyt cURL zwrócony przez curl_init().

option

The CURLOPT_XXX option to set.

value

The value to be set on option.

value should be a bool for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_AUTOREFERER | TRUE to automatically set the Referer: field in requests where it follows a Location: redirect.
CURLOPT_BINARYTRANSFER | TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used.
CURLOPT_COOKIESESSION | TRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies or not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only.
CURLOPT_CERTINFO | TRUE to output SSL certification information to STDERR on secure transfers. | Available since PHP 5.3.2. Requires CURLOPT_VERBOSE to be on to have an effect.
CURLOPT_CRLF | TRUE to convert Unix newlines to CRLF newlines on transfers.
CURLOPT_DNS_USE_GLOBAL_CACHE | TRUE to use a global DNS cache. This option is not thread-safe and is enabled by default.
CURLOPT_FAILONERROR | TRUE to fail silently if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code.
CURLOPT_FILETIME | TRUE to attempt to retrieve the modification date of the remote document. This value can be retrieved using the CURLINFO_FILETIME option with curl_getinfo().
CURLOPT_FOLLOWLOCATION | TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
CURLOPT_FORBID_REUSE | TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
CURLOPT_FRESH_CONNECT | TRUE to force the use of a new connection instead of a cached one.
CURLOPT_FTP_USE_EPRT | TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only.
CURLOPT_FTP_USE_EPSV | TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV.
CURLOPT_FTP_CREATE_MISSING_DIRS | TRUE to create missing directories when an FTP operation encounters a path that currently doesn't exist.
CURLOPT_FTPAPPEND | TRUE to append to the remote file instead of overwriting it.
CURLOPT_FTPASCII | An alias of CURLOPT_TRANSFERTEXT. Use that instead.
CURLOPT_FTPLISTONLY | TRUE to only list the names of an FTP directory.
CURLOPT_HEADER | TRUE to include the header in the output.
CURLINFO_HEADER_OUT | TRUE to track the handle's request string. | Available since PHP 5.1.3. The CURLINFO_ prefix is intentional.
CURLOPT_HTTPGET | TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.
CURLOPT_HTTPPROXYTUNNEL | TRUE to tunnel through a given HTTP proxy.
CURLOPT_MUTE | TRUE to be completely silent with regards to the cURL functions.
CURLOPT_NETRC | TRUE to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with.
CURLOPT_NOBODY | TRUE to exclude the body from the output. Request method is then set to HEAD. Changing this to FALSE does not change it to GET.
CURLOPT_NOPROGRESS

TRUE to disable the progress meter for cURL transfers.

Informacja:

PHP automatically sets this option to TRUE, this should only be changed for debugging purposes.

CURLOPT_NOSIGNAL | TRUE to ignore any cURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used. | Added in cURL 7.10.
CURLOPT_POST | TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_PUT | TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
CURLOPT_RETURNTRANSFER | TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
CURLOPT_SSL_VERIFYPEER | FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. | TRUE by default as of cURL 7.10. Default bundle installed as of cURL 7.10.
CURLOPT_TRANSFERTEXT | TRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode.
CURLOPT_UNRESTRICTED_AUTH | TRUE to keep sending the username and password when following locations (using CURLOPT_FOLLOWLOCATION), even when the hostname has changed.
CURLOPT_UPLOAD | TRUE to prepare for an upload.
CURLOPT_VERBOSE | TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.

value should be an integer for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_BUFFERSIZE | The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. | Added in cURL 7.10.
CURLOPT_CLOSEPOLICY | Either CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. There are three other CURLCLOSEPOLICY_ constants, but cURL does not support them yet.
CURLOPT_CONNECTTIMEOUT | The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
CURLOPT_CONNECTTIMEOUT_MS | The number of milliseconds to wait while trying to connect. Use 0 to wait indefinitely. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. | Added in cURL 7.16.2. Available since PHP 5.2.3.
CURLOPT_DNS_CACHE_TIMEOUT | The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default.
CURLOPT_FTPSSLAUTH | The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide). | Added in cURL 7.12.2.
CURLOPT_HTTP_VERSION | CURL_HTTP_VERSION_NONE (default, lets CURL decide which version to use), CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).
CURLOPT_HTTPAUTH

The HTTP authentication method(s) to use. The options are: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE.

The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.

CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLOPT_INFILESIZE | The expected size, in bytes, of the file when uploading a file to a remote site. Note that using this option will not stop libcurl from sending more data, as exactly what is sent depends on CURLOPT_READFUNCTION.
CURLOPT_LOW_SPEED_LIMIT | The transfer speed, in bytes per second, that the transfer should be below during the count of CURLOPT_LOW_SPEED_TIME seconds before PHP considers the transfer too slow and aborts.
CURLOPT_LOW_SPEED_TIME | The number of seconds the transfer speed should be below CURLOPT_LOW_SPEED_LIMIT before PHP considers the transfer too slow and aborts.
CURLOPT_MAXCONNECTS | The maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close.
CURLOPT_MAXREDIRS | The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION.
CURLOPT_PORT | An alternative port number to connect to.
CURLOPT_PROTOCOLS

Bitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in the transfer. This allows you to have a libcurl built to support a wide range of protocols but still limit specific transfers to only be allowed to use a subset of them. By default libcurl will accept all protocols it supports. See also CURLOPT_REDIR_PROTOCOLS.

Valid protocol options are: CURLPROTO_HTTP, CURLPROTO_HTTPS, CURLPROTO_FTP, CURLPROTO_FTPS, CURLPROTO_SCP, CURLPROTO_SFTP, CURLPROTO_TELNET, CURLPROTO_LDAP, CURLPROTO_LDAPS, CURLPROTO_DICT, CURLPROTO_FILE, CURLPROTO_TFTP, CURLPROTO_ALL

Added in cURL 7.19.4.
CURLOPT_PROXYAUTH | The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported. | Added in cURL 7.10.7.
CURLOPT_PROXYPORT | The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY.
CURLOPT_PROXYTYPE | Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. | Added in cURL 7.10.
CURLOPT_REDIR_PROTOCOLS | Bitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in a transfer that it follows to in a redirect when CURLOPT_FOLLOWLOCATION is enabled. This allows you to limit specific transfers to only be allowed to use a subset of protocols in redirections. By default libcurl will allow all protocols except for FILE and SCP. This is a difference compared to pre-7.19.4 versions which unconditionally would follow to all protocols supported. See also CURLOPT_PROTOCOLS for protocol constant values. | Added in cURL 7.19.4.
CURLOPT_RESUME_FROM | The offset, in bytes, to resume a transfer from.
CURLOPT_SSL_VERIFYHOST | 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided. In production environments the value of this option should be kept at 2 (default value).
CURLOPT_SSLVERSION | The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases this must be set manually.
CURLOPT_TIMECONDITION | How CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADER is TRUE. Use CURL_TIMECOND_IFUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default.
CURLOPT_TIMEOUT | The maximum number of seconds to allow cURL functions to execute.
CURLOPT_TIMEOUT_MS | The maximum number of milliseconds to allow cURL functions to execute. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. | Added in cURL 7.16.2. Available since PHP 5.2.3.
CURLOPT_TIMEVALUE | The time in seconds since January 1st, 1970. The time will be used by CURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used.
CURLOPT_MAX_RECV_SPEED_LARGE | If a download exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value. Defaults to unlimited speed. | Added in cURL 7.15.5. Available since PHP 5.4.0.
CURLOPT_MAX_SEND_SPEED_LARGE | If an upload exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value. Defaults to unlimited speed. | Added in cURL 7.15.5. Available since PHP 5.4.0.

value should be a string for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_CAINFO | The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER. | Requires absolute path.
CURLOPT_CAPATH | A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE | The contents of the "Cookie: " header to be used in the HTTP request. Note that multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red")
CURLOPT_COOKIEFILE | The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.
CURLOPT_COOKIEJAR | The name of a file to save all internal cookies to when the handle is closed, e.g. after a call to curl_close.
CURLOPT_CUSTOMREQUEST

A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

Informacja:

Don't do this without making sure the server supports the custom request method first.

CURLOPT_EGDSOCKET | Like CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket.
CURLOPT_ENCODING | The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent. | Added in cURL 7.10.
CURLOPT_FTPPORT | The value which will be used to get the IP address to use for the FTP "POST" instruction. The "POST" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.
CURLOPT_INTERFACE | The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.
CURLOPT_KRB4LEVEL | The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.
CURLOPT_POSTFIELDS | The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.
CURLOPT_PROXY | The HTTP proxy to tunnel requests through.
CURLOPT_PROXYUSERPWD | A username and password formatted as "[username]:[password]" to use for the connection to the proxy.
CURLOPT_RANDOM_FILE | A filename to be used to seed the random number generator for SSL.
CURLOPT_RANGE | Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".
CURLOPT_REFERER | The contents of the "Referer: " header to be used in a HTTP request.
CURLOPT_SSL_CIPHER_LIST | A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.
CURLOPT_SSLCERT | The name of a file containing a PEM formatted certificate.
CURLOPT_SSLCERTPASSWD | The password required to use the CURLOPT_SSLCERT certificate.
CURLOPT_SSLCERTTYPE | The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG". | Added in cURL 7.9.3.
CURLOPT_SSLENGINE | The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT | The identifier for the crypto engine used for asymmetric crypto operations.
CURLOPT_SSLKEY | The name of a file containing a private SSL key.
CURLOPT_SSLKEYPASSWD

The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.

Informacja:

Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe.

CURLOPT_SSLKEYTYPE | The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG".
CURLOPT_URL | The URL to fetch. This can also be set when initializing a session with curl_init().
CURLOPT_USERAGENT | The contents of the "User-Agent: " header to be used in a HTTP request.
CURLOPT_USERPWD | A username and password formatted as "[username]:[password]" to use for the connection.

value should be an array for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_HTTP200ALIASES | An array of HTTP 200 responses that will be treated as valid responses and not as errors. | Added in cURL 7.10.3.
CURLOPT_HTTPHEADER | An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
CURLOPT_POSTQUOTE | An array of FTP commands to execute on the server after the FTP request has been performed.
CURLOPT_QUOTE | An array of FTP commands to execute on the server prior to the FTP request.

value should be a stream resource (using fopen(), for example) for the following values of the option parameter:

Option | Set value to
CURLOPT_FILE | The file that the transfer should be written to. The default is STDOUT (the browser window).
CURLOPT_INFILE | The file that the transfer should be read from when uploading.
CURLOPT_STDERR | An alternative location to output errors to instead of STDERR.
CURLOPT_WRITEHEADER | The file that the header part of the transfer is written to.

value should be a string that is the name of a valid callback function for the following values of the option parameter:

Option | Set value to
CURLOPT_HEADERFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written when using this callback function. Return the number of bytes written.
CURLOPT_PASSWDFUNCTION | The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.
CURLOPT_PROGRESSFUNCTION | The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a file-descriptor resource, and the third is length. Return the string containing the data.
CURLOPT_READFUNCTION | The name of a callback function where the callback function takes three parameters. The first is the cURL resource, the second is a stream resource provided to cURL through the option CURLOPT_INFILE, and the third is the maximum amount of data to be read. The callback function must return a string with a length equal or smaller than the amount of data requested, typically by reading it from the passed stream resource. It should return an empty string to signal EOF.
CURLOPT_WRITEFUNCTION | The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be saved by using this callback function. It must return the exact number of bytes written or the transfer will be aborted with an error.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.2.10 | Introduced CURLOPT_PROTOCOLS, and CURLOPT_REDIR_PROTOCOLS.
5.1.0 | Introduced CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH, and CURLOPT_TIMECONDITION.
5.0.0 | Introduced CURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE, and CURLOPT_HTTP200ALIASES.

Przykłady

Przykład #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Przykład #2 Uploading file

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

Powyższy przykład wyświetli:

Array
(
    [name] => Foo
)
Array
(
    [file] => Array
        (
            [name] => test.png
            [type] => image/png
            [tmp_name] => /tmp/phpcpjNeQ
            [error] => 0
            [size] => 279
        )

)

Notatki

Informacja:

Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

Zobacz też:

  • curl_setopt_array() - Set multiple options for a cURL transfer

curl_setopt_array
curl_version
cURL Funkcje


Gets cURL version information

curl_setopt
FAM
cURL Funkcje
PHP Manual

curl_version

(PHP 4 >= 4.0.2, PHP 5)

curl_version — Gets cURL version information

Opis

array curl_version ([ int $age = CURLVERSION_NOW ] )

Returns information about the cURL version.

Parametry

age

Zwracane wartości

Returns an associative array with the following elements:

Indice | Value description
version_number | cURL 24 bit version number
version | cURL version number, as a string
ssl_version_number | OpenSSL 24 bit version number
ssl_version | OpenSSL version number, as a string
libz_version | zlib version number, as a string
host | Information about the host where cURL was built
age |
features | A bitmask of the CURL_VERSION_XXX constants
protocols | An array of protocols names supported by cURL

Przykłady

Przykład #1 curl_version() example

This example will check which features that's available in cURL build by using the 'features' bitmask returned by curl_version().

<?php
// Get curl version array
$version = curl_version();

// These are the bitfields that can be used
// to check for features in the curl build
$bitfields = Array(
            'CURL_VERSION_IPV6',
            'CURL_VERSION_KERBEROS4',
            'CURL_VERSION_SSL',
            'CURL_VERSION_LIBZ'
            );

foreach($bitfields as $feature)
{
    echo $feature . ($version['features'] & constant($feature) ? ' matches' : ' does not match');
    echo PHP_EOL;
}
?>

curl_setopt
FAM
cURL Funkcje


File Alteration Monitor

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • FAM Funkcje
    • fam_cancel_monitor — Terminate monitoring
    • fam_close — Close FAM connection
    • fam_monitor_collection — Monitor a collection of files in a directory for changes
    • fam_monitor_directory — Monitor a directory for changes
    • fam_monitor_file — Monitor a regular file for changes
    • fam_next_event — Get next pending FAM event
    • fam_open — Open connection to FAM daemon
    • fam_pending — Check for pending FAM events
    • fam_resume_monitor — Resume suspended monitoring
    • fam_suspend_monitor — Temporarily suspend monitoring
curl_version
Wstęp
Inne serwisy


Wstęp

FAM monitors files and directories, notifying interested applications of changes. More information about FAM is available at » http://oss.sgi.com/projects/fam/.

A PHP script may specify a list of files for FAM to monitor using the functions provided by this extension.

The FAM process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

FAM
Instalacja/Konfiguracja
FAM


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
FAM


Wymagania

This extension uses the functions of the » FAM library, developed by SGI. Therefore you have to download and install the FAM library.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/fam.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

There are two resource types used in the FAM module. The first one is the connection to the FAM service returned by fam_open(), the second a monitoring resource returned by the fam_monitor_XXX functions.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

FAM event constants
Constant | Description
FAMChanged (integer) | Some value which can be obtained with fstat(1) changed for a file or directory.
FAMDeleted (integer) | A file or directory was deleted or renamed.
FAMStartExecuting (integer) | An executable file started executing.
FAMStopExecuting (integer) | An executable file that was running finished.
FAMCreated (integer) | A file was created in a directory.
FAMMoved (integer) | This event never occurs.
FAMAcknowledge (integer) | An event in response to fam_cancel_monitor().
FAMExists (integer) | An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued.
FAMEndExist (integer) | Event after the last FAMEExists event.
Typy zasobów
FAM Funkcje
FAM


FAM Funkcje

Spis treści

  • fam_cancel_monitor — Terminate monitoring
  • fam_close — Close FAM connection
  • fam_monitor_collection — Monitor a collection of files in a directory for changes
  • fam_monitor_directory — Monitor a directory for changes
  • fam_monitor_file — Monitor a regular file for changes
  • fam_next_event — Get next pending FAM event
  • fam_open — Open connection to FAM daemon
  • fam_pending — Check for pending FAM events
  • fam_resume_monitor — Resume suspended monitoring
  • fam_suspend_monitor — Temporarily suspend monitoring
Stałe predefiniowane
fam_cancel_monitor
FAM


Terminate monitoring

FAM Funkcje
fam_close
FAM Funkcje
PHP Manual

fam_cancel_monitor

(PHP 5 <= 5.0.5)

fam_cancel_monitor — Terminate monitoring

Opis

bool fam_cancel_monitor ( resource $fam , resource $fam_monitor )

Terminates monitoring on a resource.

In addition an FAMAcknowledge event occurs.

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fam_monitor_file() - Monitor a regular file for changes
  • fam_monitor_directory() - Monitor a directory for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_suspend_monitor() - Temporarily suspend monitoring

FAM Funkcje
fam_close
FAM Funkcje


Close FAM connection

fam_cancel_monitor
fam_monitor_collection
FAM Funkcje
PHP Manual

fam_close

(PHP 5 <= 5.0.5)

fam_close — Close FAM connection

Opis

void fam_close ( resource $fam )

Closes a connection to the FAM service.

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • fam_monitor_open()

fam_cancel_monitor
fam_monitor_collection
FAM Funkcje


Monitor a collection of files in a directory for changes

fam_close
fam_monitor_directory
FAM Funkcje
PHP Manual

fam_monitor_collection

(PHP 5 <= 5.0.5)

fam_monitor_collection — Monitor a collection of files in a directory for changes

Opis

resource fam_monitor_collection ( resource $fam , string $dirname , int $depth , string $mask )

Requests monitoring for a collection of files within a directory.

A FAM event will be generated whenever the status of the files change. The possible event codes are described in detail in the constants part of this section.

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

dirname

Directory path to the monitored files

depth

The maximum search depth starting from this directory

mask

A shell pattern mask restricting the file names to look for

Zwracane wartości

Returns a monitoring resource or FALSE on errors.

Zobacz też:

  • fam_monitor_file() - Monitor a regular file for changes
  • fam_monitor_directory() - Monitor a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring

fam_close
fam_monitor_directory
FAM Funkcje


Monitor a directory for changes

fam_monitor_collection
fam_monitor_file
FAM Funkcje
PHP Manual

fam_monitor_directory

(PHP 5 <= 5.0.5)

fam_monitor_directory — Monitor a directory for changes

Opis

resource fam_monitor_directory ( resource $fam , string $dirname )

Requests monitoring for a directory and all contained files.

A FAM event will be generated whenever the status of the directory (i.e. the result of function stat() on that directory) or its content (i.e. the results of readdir()) changes.

The possible event codes are described in detail in the constants part of this section.

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

dirname

Path to the monitored directory

Zwracane wartości

Returns a monitoring resource or FALSE on errors.

Zobacz też:

  • fam_monitor_file() - Monitor a regular file for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring

fam_monitor_collection
fam_monitor_file
FAM Funkcje


Monitor a regular file for changes

fam_monitor_directory
fam_next_event
FAM Funkcje
PHP Manual

fam_monitor_file

(PHP 5 <= 5.0.5)

fam_monitor_file — Monitor a regular file for changes

Opis

resource fam_monitor_file ( resource $fam , string $filename )

Requests monitoring for a single file. A FAM event will be generated whenever the file status changes (i.e. the result of function stat() on that file).

The possible event codes are described in detail in the constants part of this section.

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

filename

Path to the monitored file

Zwracane wartości

Returns a monitoring resource or FALSE on errors.

Zobacz też:

  • fam_monitor_directory() - Monitor a directory for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring

fam_monitor_directory
fam_next_event
FAM Funkcje


Get next pending FAM event

fam_monitor_file
fam_open
FAM Funkcje
PHP Manual

fam_next_event

(PHP 5 <= 5.0.5)

fam_next_event — Get next pending FAM event

Opis

array fam_next_event ( resource $fam )

Returns the next pending FAM event.

The function will block until an event is available which can be checked for using fam_pending().

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

Zwracane wartości

Returns an array that contains a FAM event code in the 'code' element, the path of the file this event applies to in the 'filename' element and optionally a hostname in the 'hostname' element.

The possible event codes are described in detail in the constants part of this section.

Zobacz też:

  • fam_pending() - Check for pending FAM events

fam_monitor_file
fam_open
FAM Funkcje


Open connection to FAM daemon

fam_next_event
fam_pending
FAM Funkcje
PHP Manual

fam_open

(PHP 5 <= 5.0.5)

fam_open — Open connection to FAM daemon

Opis

resource fam_open ([ string $appname ] )

Opens a connection to the FAM service daemon.

Parametry

appname

A string identifying the application for logging reasons

Zwracane wartości

Returns a resource representing a connection to the FAM service on success or FALSE on errors.

Zobacz też:

  • fam_close() - Close FAM connection

fam_next_event
fam_pending
FAM Funkcje


Check for pending FAM events

fam_open
fam_resume_monitor
FAM Funkcje
PHP Manual

fam_pending

(PHP 5 <= 5.0.5)

fam_pending — Check for pending FAM events

Opis

int fam_pending ( resource $fam )

Checks for pending FAM events.

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

Zwracane wartości

Returns non-zero if events are available to be fetched using fam_next_event(), zero otherwise.

Zobacz też:

  • fam_next_event() - Get next pending FAM event

fam_open
fam_resume_monitor
FAM Funkcje


Resume suspended monitoring

fam_pending
fam_suspend_monitor
FAM Funkcje
PHP Manual

fam_resume_monitor

(PHP 5 <= 5.0.5)

fam_resume_monitor — Resume suspended monitoring

Opis

bool fam_resume_monitor ( resource $fam , resource $fam_monitor )

Resumes monitoring of a resource previously suspended using fam_suspend_monitor().

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fam_suspend_monitor() - Temporarily suspend monitoring

fam_pending
fam_suspend_monitor
FAM Funkcje


Temporarily suspend monitoring

fam_resume_monitor
FTP
FAM Funkcje
PHP Manual

fam_suspend_monitor

(PHP 5 <= 5.0.5)

fam_suspend_monitor — Temporarily suspend monitoring

Opis

bool fam_suspend_monitor ( resource $fam , resource $fam_monitor )

fam_suspend_monitor() temporarily suspend monitoring of a resource.

Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.

Parametry

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • fam_cancel_monitor() - Terminate monitoring
  • fam_resume_monitor() - Resume suspended monitoring

fam_resume_monitor
FTP
FAM Funkcje


FTP

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • FTP Funkcje
    • ftp_alloc — Allocates space for a file to be uploaded
    • ftp_cdup — Zmienia bieżący katalog na nadrzędny
    • ftp_chdir — Zmienia bieżący katalog na serwerze FTP
    • ftp_chmod — Set permissions on a file via FTP
    • ftp_close — Zamyka połączenie FTP
    • ftp_connect — Opens an FTP connection
    • ftp_delete — Usuwa plik na serwerze FTP
    • ftp_exec — Żąda wykonanie polecenia przez serwer FTP
    • ftp_fget — Pobiera plik z serwera FTP i zapisuje do otwartego pliku
    • ftp_fput — Wysyła dane z otwartego pliku na serwer FTP
    • ftp_get_option — Pobiera ustawienia dotyczące strumienia FTP
    • ftp_get — Pobiera plik z serwera FTP
    • ftp_login — Loguje się w ramach połączenia FTP
    • ftp_mdtm — Zwraca czas ostatniej modyfikacji podanego pliku
    • ftp_mkdir — Tworzy katalog
    • ftp_nb_continue — Continues retrieving/sending a file (non-blocking)
    • ftp_nb_fget — Retrieves a file from the FTP server and writes it to an open file (non-blocking)
    • ftp_nb_fput — Stores a file from an open file to the FTP server (non-blocking)
    • ftp_nb_get — Retrieves a file from the FTP server and writes it to a local file (non-blocking)
    • ftp_nb_put — Stores a file on the FTP server (non-blocking)
    • ftp_nlist — Zwraca listę plików z podanego katalogu
    • ftp_pasv — Włącza lub wyłącza tryb pasywny
    • ftp_put — Przesyła plik na serwer FTP
    • ftp_pwd — Zwraca nazwę katalogu bieżącego
    • ftp_quit — Alias dla ftp_close
    • ftp_raw — Sends an arbitrary command to an FTP server
    • ftp_rawlist — Zwraca szczegółową listę plików z podanego katalogu
    • ftp_rename — Zmienia nazwę pliku lub katalogu na serwerze FTP
    • ftp_rmdir — Usuwa katalog
    • ftp_set_option — Set miscellaneous runtime FTP options
    • ftp_site — Wysyła polecenie SITE do serwera FTP
    • ftp_size — Zwraca rozmiar podanego pliku
    • ftp_ssl_connect — Opens an Secure SSL-FTP connection
    • ftp_systype — Zwraca identyfikator typu systemu dla zdalnego serwera FTP
fam_suspend_monitor
Wstęp
Inne serwisy


Wstęp

The functions in this extension implement client access to files servers speaking the File Transfer Protocol (FTP) as defined in » http://www.faqs.org/rfcs/rfc959. This extension is meant for detailed access to an FTP server providing a wide range of control to the executing script. If you only wish to read from or write to a file on an FTP server, consider using the ftp:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.

FTP
Instalacja/Konfiguracja
FTP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
FTP


Instalacja

In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP.

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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension uses one resource type, which is the link identifier of the FTP connection, returned by ftp_connect() or ftp_ssl_connect().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

FTP_ASCII (integer)

FTP_TEXT (integer)

FTP_BINARY (integer)

FTP_IMAGE (integer)

FTP_TIMEOUT_SEC (integer)

Więcej informacji można znaleźć w opisie funkcji ftp_set_option().

Poniższe stałe zostały dodane w PHP 4.3.0.

FTP_AUTOSEEK (integer)

Więcej informacji można znaleźć w opisie funkcji ftp_set_option().

FTP_AUTORESUME (integer)

Automatycznzie określa pozycję wznowienia transferudla operacji GET i PUT (działa tylko przy włączonym FTP_AUTOSEEK)

FTP_FAILED (integer)

Transfer asynchroniczny się nie powiódł.

FTP_FINISHED (integer)

Transfer asynchroniczny został zakończony.

FTP_MOREDATA (integer)

Transfer asynchroniczny jest ciągle aktywny.

Typy zasobów
Przykłady
FTP


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
FTP


Basic usage

Przykład #1 FTP example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
    echo "FTP connection has failed!";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name";
    exit;
} else {
    echo "Connected to $ftp_server, for user $ftp_user_name";
}

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
    echo "FTP upload has failed!";
} else {
    echo "Uploaded $source_file to $ftp_server as $destination_file";
}

// close the FTP stream
ftp_close($conn_id);
?>

Przykłady
FTP Funkcje
Przykłady


FTP Funkcje

Spis treści

  • ftp_alloc — Allocates space for a file to be uploaded
  • ftp_cdup — Zmienia bieżący katalog na nadrzędny
  • ftp_chdir — Zmienia bieżący katalog na serwerze FTP
  • ftp_chmod — Set permissions on a file via FTP
  • ftp_close — Zamyka połączenie FTP
  • ftp_connect — Opens an FTP connection
  • ftp_delete — Usuwa plik na serwerze FTP
  • ftp_exec — Żąda wykonanie polecenia przez serwer FTP
  • ftp_fget — Pobiera plik z serwera FTP i zapisuje do otwartego pliku
  • ftp_fput — Wysyła dane z otwartego pliku na serwer FTP
  • ftp_get_option — Pobiera ustawienia dotyczące strumienia FTP
  • ftp_get — Pobiera plik z serwera FTP
  • ftp_login — Loguje się w ramach połączenia FTP
  • ftp_mdtm — Zwraca czas ostatniej modyfikacji podanego pliku
  • ftp_mkdir — Tworzy katalog
  • ftp_nb_continue — Continues retrieving/sending a file (non-blocking)
  • ftp_nb_fget — Retrieves a file from the FTP server and writes it to an open file (non-blocking)
  • ftp_nb_fput — Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_get — Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_put — Stores a file on the FTP server (non-blocking)
  • ftp_nlist — Zwraca listę plików z podanego katalogu
  • ftp_pasv — Włącza lub wyłącza tryb pasywny
  • ftp_put — Przesyła plik na serwer FTP
  • ftp_pwd — Zwraca nazwę katalogu bieżącego
  • ftp_quit — Alias dla ftp_close
  • ftp_raw — Sends an arbitrary command to an FTP server
  • ftp_rawlist — Zwraca szczegółową listę plików z podanego katalogu
  • ftp_rename — Zmienia nazwę pliku lub katalogu na serwerze FTP
  • ftp_rmdir — Usuwa katalog
  • ftp_set_option — Set miscellaneous runtime FTP options
  • ftp_site — Wysyła polecenie SITE do serwera FTP
  • ftp_size — Zwraca rozmiar podanego pliku
  • ftp_ssl_connect — Opens an Secure SSL-FTP connection
  • ftp_systype — Zwraca identyfikator typu systemu dla zdalnego serwera FTP
Basic usage
ftp_alloc
FTP


Allocates space for a file to be uploaded

FTP Funkcje
ftp_cdup
FTP Funkcje
PHP Manual

ftp_alloc

(PHP 5)

ftp_alloc — Allocates space for a file to be uploaded

Opis

bool ftp_alloc ( resource $ftp_stream , int $filesize [, string &$result ] )

Sends an ALLO command to the remote FTP server to allocate space for a file to be uploaded.

Informacja:

Many FTP servers do not support this command. These servers may return a failure code (FALSE) indicating the command is not supported or a success code (TRUE) to indicate that pre-allocation is not necessary and the client should continue as though the operation were successful. Because of this, it may be best to reserve this function for servers which explicitly require preallocation.

Parametry

ftp_stream

The link identifier of the FTP connection.

filesize

The number of bytes to allocate.

result

A textual representation of the servers response will be returned by reference in result if a variable is provided.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 ftp_alloc() example

<?php

$file = "/home/user/myfile";

// connect to the server
$conn_id = ftp_connect('ftp.example.com');
$login_result = ftp_login($conn_id, 'anonymous', 'user@example.com');

if (ftp_alloc($conn_id, filesize($file), $result)) {
  echo "Space successfully allocated on server.  Sending $file.\n";
  ftp_put($conn_id, '/incomming/myfile', $file, FTP_BINARY);
} else {
  echo "Unable to allocate space on server.  Server said: $result\n";
}

ftp_close($conn_id);

?>

Zobacz też:

  • ftp_put() - Przesyła plik na serwer FTP
  • ftp_fput() - Wysyła dane z otwartego pliku na serwer FTP

FTP Funkcje
ftp_cdup
FTP Funkcje


Zmienia bieżący katalog na nadrzędny

ftp_alloc
ftp_chdir
FTP Funkcje
PHP Manual

ftp_cdup

(PHP 4, PHP 5)

ftp_cdup — Zmienia bieżący katalog na nadrzędny

Opis

bool ftp_cdup ( resource $strumień_ftp )

Zmienia bieżący katalog na nadrzędny.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_cdup()

<?php
// nawiąż połączenie
$conn_id = ftp_connect($ftp_server);

// zaloguj się
$login_result = ftp_login($conn_id, $ftp_nazwa_uzytkownika, $ftp_haslo);

// zmień bieżący katalog na 'html'
ftp_chdir($conn_id, 'html');

echo ftp_pwd($conn_id); // /html

// powróć do katalogu nadrzędnego
if (ftp_cdup($conn_id)) {
  echo "cdup wykonane pomyślnie\n";
} else {
  echo "Błąd w wykonaniu cdup\n";
}

echo ftp_pwd($conn_id); // /

ftp_close($conn_id);
?>

Zobacz też:

  • ftp_chdir() - Zmienia bieżący katalog na serwerze FTP
  • ftp_pwd() - Zwraca nazwę katalogu bieżącego

ftp_alloc
ftp_chdir
FTP Funkcje


Zmienia bieżący katalog na serwerze FTP

ftp_cdup
ftp_chmod
FTP Funkcje
PHP Manual

ftp_chdir

(PHP 4, PHP 5)

ftp_chdir — Zmienia bieżący katalog na serwerze FTP

Opis

bool ftp_chdir ( resource $strumień_ftp , string $katalog )

Zmienia bieżący katalog na podany jako argument.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

katalog

Katalog docelowy.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Jeśli zmiana katalogu się nie powiedzie, PHP wygeneruje także ostrzeżenie.

Przykłady

Przykład #1 Przykład użycia ftp_chdir()

<?php

// Nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// Logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Weryfikacja połączenia
if ((!$conn_id) || (!$login_result)) {
    die("Połączenie z serwerem FTP nie zostało nawiązane!");
}

echo "Bieżący katalog: " . ftp_pwd($conn_id) . "\n";

// Próba zmiany katalogu bieżącego na 'jakis_katalog'
if (ftp_chdir($conn_id, "jakis_katalog")) {
    echo "Bieżący katalog to teraz: " . ftp_pwd($conn_id) . "\n";
} else {
    echo "Nie powiodła się zmiana katalogu\n";
}

// Zamknięcie połączenia
ftp_close($conn_id);
?>

Zobacz też:

  • ftp_cdup() - Zmienia bieżący katalog na nadrzędny
  • ftp_pwd() - Zwraca nazwę katalogu bieżącego

ftp_cdup
ftp_chmod
FTP Funkcje


Set permissions on a file via FTP

ftp_chdir
ftp_close
FTP Funkcje
PHP Manual

ftp_chmod

(PHP 5)

ftp_chmod — Set permissions on a file via FTP

Opis

int ftp_chmod ( resource $ftp_stream , int $mode , string $filename )

Sets the permissions on the specified remote file to mode.

Parametry

ftp_stream

The link identifier of the FTP connection.

mode

The new permissions, given as an octal value.

filename

The remote file.

Zwracane wartości

Returns the new file permissions on success or FALSE on error.

Przykłady

Przykład #1 ftp_chmod() example

<?php
$file = 'public_html/index.php';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to chmod $file to 644
if (ftp_chmod($conn_id, 0644, $file) !== false) {
 echo "$file chmoded successfully to 644\n";
} else {
 echo "could not chmod $file\n";
}

// close the connection
ftp_close($conn_id);
?>

Zobacz też:

  • chmod() - Zmienia prawa dostępu do pliku

ftp_chdir
ftp_close
FTP Funkcje


Zamyka połączenie FTP

ftp_chmod
ftp_connect
FTP Funkcje
PHP Manual

ftp_close

(PHP 4 >= 4.2.0, PHP 5)

ftp_close — Zamyka połączenie FTP

Opis

bool ftp_close ( resource $strumień_ftp )

ftp_close() zamyka połączenie o podanym identyfikatorze i zwalnia przypisane do niego zasoby.

Informacja:

Po wywołaniu tej funkcji nie jest możliwe korzystanie z danego połączenia FTP - należy stworzyć nowe za pomocą funkcji ftp_connect().

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_close()

<?php

// Nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// Logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Wyświetlenie bieżącego katalogu
echo ftp_pwd($conn_id); // /

// Zamknięcie połączenia
ftp_close($conn_id);
?>

Zobacz też:

  • ftp_connect() - Opens an FTP connection

ftp_chmod
ftp_connect
FTP Funkcje


Opens an FTP connection

ftp_close
ftp_delete
FTP Funkcje
PHP Manual

ftp_connect

(PHP 4, PHP 5)

ftp_connect — Opens an FTP connection

Opis

resource ftp_connect ( string $host [, int $port [, int $timeout ]] )

ftp_connect() otwiera połączenie z serwerem FTP podanym jak argument.

Parametry

host

Adres serwera ftp. Wartość tego argumentu nie powinna mieć żadnych znaków przed nazwą hosta, jak również nie powinien zaczynać się od ftp://.

port

Argument ten określa port, z którym ma nastąpić połączenie. Jeśli argument ten zostanie pominięty, albo podana zostanie wartość zero, użyty zostanie domyślny port usługi FTP, czyli 21.

timeout

Argument ten określa maksymalny czas, jaki mogą zająć wszystkie następujace po sobie operacje sieciowe. Jeśli argument ten zostanie pominięty, uznana zostanie domyślna wartość 90 sekund. Wartość ta może być później odczytana i zmieniona za pomocą funkcji ftp_set_option() i ftp_get_option().

Zwracane wartości

W przypadku powodzenia zwraca strumień FTP lub FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_connect()

<?php

$ftp_server = "ftp.example.com";

// nawiąż połączenie lub zakończ pracę.
$conn_id = ftp_connect($ftp_server) or die("Nie można nawiązać połączenia z $ftp_server");

?>

Rejestr zmian

Wersja | Opis
4.2.0 | Dodany parametr timeout.

Zobacz też:

  • ftp_close() - Zamyka połączenie FTP
  • ftp_ssl_connect() - Opens an Secure SSL-FTP connection

ftp_close
ftp_delete
FTP Funkcje


Usuwa plik na serwerze FTP

ftp_connect
ftp_exec
FTP Funkcje
PHP Manual

ftp_delete

(PHP 4, PHP 5)

ftp_delete — Usuwa plik na serwerze FTP

Opis

bool ftp_delete ( resource $strumień_ftp , string $ścieżka )

ftp_delete() usuwa plik, do którego ścieżka podawana jest jako argument.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

ścieżka

Plik do usunięcia.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_delete()

<?php
$plik = 'public_html/old.txt';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// próba usunięcia $plik
if (ftp_delete($conn_id, $plik)) {
 echo "Plik $plik został usunięty\n";
} else {
 echo "Nie powiodła się próba usunięcia pliku $plik\n";
}

// zamknięcie połączenia
ftp_close($conn_id);
?>

ftp_connect
ftp_exec
FTP Funkcje


Żąda wykonanie polecenia przez serwer FTP

ftp_delete
ftp_fget
FTP Funkcje
PHP Manual

ftp_exec

(PHP 4 >= 4.0.3, PHP 5)

ftp_exec — Żąda wykonanie polecenia przez serwer FTP

Opis

bool ftp_exec ( resource $strumień_ftp , string $polecenie )

Wysyła żądanie SITE EXEC polecenie do serwera FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

polecenie

Polecenie do wykonania.

Zwracane wartości

Zwraca TRUE jeśli polecenie zostało pomyślnie wykonane (to znaczy serwer zwrócił kod 200). W przeciwnym przypadku zwracana jest wartość FALSE.

Przykłady

Przykład #1 Przykład użycia ftp_exec()

<?php

// przygotowanie polecenia
$polecenie = 'ls -al >files.txt';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// próba wywołania polecenia
if (ftp_exec($conn_id, $polecenie)) {
    echo "$polecenie wykonane pomyślnie\n";
} else {
    echo "Nie można wykonać polecenia $polecenie\n";
}

// zamknięcie połączenia
ftp_close($conn_id);

?>

Zobacz też:

  • ftp_raw() - Sends an arbitrary command to an FTP server

ftp_delete
ftp_fget
FTP Funkcje


Pobiera plik z serwera FTP i zapisuje do otwartego pliku

ftp_exec
ftp_fput
FTP Funkcje
PHP Manual

ftp_fget

(PHP 4, PHP 5)

ftp_fget — Pobiera plik z serwera FTP i zapisuje do otwartego pliku

Opis

bool ftp_fget ( resource $strumień_ftp , resource $uchwyt , string $plik_zdalny , int $tryb [, int $pozycja_wznowienia ] )

ftp_fget() pobiera plik_zdalny z serwera FTP i zapisuje go do podanego uchwytu pliku.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

uchwyt

Otwarty uchwyt do pliku, w którym będą zapisane dane.

plik_zdalny

Ścieżka do pliku zdalnego.

tryb

Tryb transferu. Musi to być FTP_ASCII lub FTP_BINARY.

resumepos

Pozycja w pliku zdalnym, od której rozpoczęte zostanie pobieranie.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_fget()

<?php

// ścieżki do plików
$plik_zdalny = 'jakis_plik.txt';
$plik_lokalny = 'plik_lokalny.txt';

// otwarcie pliku do zapisu
$uchwyt = fopen($plik_lokalny, 'w');

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// próba pobrania pliku $plik_zdalny
if (ftp_fget($conn_id, $uchwyt, $plik_zdalny, FTP_ASCII, 0)) {
 echo "pomyślnie pobrano plik $plik_zdalny\n";
} else {
 echo "próba pobrania pliku $plik_zdalny do $plik_lokalny nie powiodła się\n";
}

// zamknięcie połączenia i uchwytu
ftp_close($conn_id);
fclose($uchwyt);

?>

Rejestr zmian

Wersja | Opis
4.3.0 | Dodany argument resumepos.

Zobacz też:

  • ftp_get() - Pobiera plik z serwera FTP
  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)

ftp_exec
ftp_fput
FTP Funkcje


Wysyła dane z otwartego pliku na serwer FTP

ftp_fget
ftp_get_option
FTP Funkcje
PHP Manual

ftp_fput

(PHP 4, PHP 5)

ftp_fput — Wysyła dane z otwartego pliku na serwer FTP

Opis

bool ftp_fput ( resource $strumień_ftp , string $plik_zdalny , resource $uchwyt , int $tryb [, int $pozycja_początkowa ] )

ftp_fput() wysyła na serwer FTP dane z podanego uchwytu do otwartego pliku.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

plik_zdalny

Ścieżka do pliku zdalnego.

uchwyt

Wskaźnik do otwartego pliku lokalnego. Czytanie kończy się w momencie napotkania końca pliku.

tryb

Tryb transferu. Musi to być FTP_ASCII lub FTP_BINARY.

pozycja_początkowa

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_fput()

<?php

// otwarcie pliku do odczytu
$file = 'jakiśplik.txt';
$fp = fopen($file, 'r');

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// próba przesłania $file
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
    echo "Pomyślnie przesłano $file\n";
} else {
    echo "Wystąpiły problemy w czasie przesyłania $file\n";
}

// zamknięcie połączenia i otwartego pliku
ftp_close($conn_id);
fclose($fp);

?>

Rejestr zmian

Wersja | Opis
4.3.0 | Dodano parametr pozycja_początkowa.

Zobacz też:

  • ftp_put() - Przesyła plik na serwer FTP
  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)

ftp_fget
ftp_get_option
FTP Funkcje


Pobiera ustawienia dotyczące strumienia FTP

ftp_fput
ftp_get
FTP Funkcje
PHP Manual

ftp_get_option

(PHP 4 >= 4.2.0, PHP 5)

ftp_get_option — Pobiera ustawienia dotyczące strumienia FTP

Opis

mixed ftp_get_option ( resource $strumień_ftp , int $opcja )

Funkcja ta zwraca wartość opcji podanej jako drugi argument dla wybranego połączenia FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

opcja

W chwili obecnej obsługiwane są poniższe opcje:

Obsługiwane opcje połączenia FTP
FTP_TIMEOUT_SEC | Zwraca bieżący czas przedawnienia dla operacji sieciowych.
FTP_AUTOSEEK | Zwraca TRUE jeśli ta opcja jest włączona, FALSE w przeciwnym przypadku.

Zwracane wartości

W przypadku powodzenia zwracana jest wartość opcji, lub FALSE jeśli podana opcja nie jest obsługiwana. W tym drugim przypadku wyświetlany jest także komunikat ostrzeżenia.

Przykłady

Przykład #1 Przykład użycia ftp_get_option()

<?php
// Pobranie czasu przedawnienia operacji sieciowych
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);
?>

Zobacz też:

  • ftp_set_option() - Set miscellaneous runtime FTP options

ftp_fput
ftp_get
FTP Funkcje


Pobiera plik z serwera FTP

ftp_get_option
ftp_login
FTP Funkcje
PHP Manual

ftp_get

(PHP 4, PHP 5)

ftp_get — Pobiera plik z serwera FTP

Opis

bool ftp_get ( resource $strumień_ftp , string $plik_lokalny , string $plik_zdalny , int $tryb [, int $pozycja_wznowienia ] )

ftp_get() pobiera zdalny plik z serwera FTP i zapisuje go do lokalnego pliku.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

plik_lokalny

Ścieżka do pliku lokalnego (zostanie on nadpisany, jeśli plik taki już istnieje).

plik_zdalny

Ścieżka do pliku zdalnego.

tryb

Tryb transferu. Musi to być FTP_ASCII lub FTP_BINARY.

pozycja_wznowienia

Pozycja w pliku zdalnym, od której rozpoczęte zostanie pobieranie.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_get()

<?php

// definicja zmiennych
$plik_lokalny = 'local.zip';
$plik_zdalny = 'server.zip';

// ustanowienie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// próba pobrania $plik_zdalny i zapisania go do $plik_lokalny
if (ftp_get($conn_id, $plik_lokalny, $plik_zdalny, FTP_BINARY)) {
    echo "Pomyślnie zapisano $plik_lokalny\n";
} else {
    echo "Problem.\n";
}

// zamknięcie połączenia
ftp_close($conn_id);

?>

Rejestr zmian

Wersja | Opis
4.3.0 | Dodano parametr resumepos

Zobacz też:

  • ftp_pasv() - Włącza lub wyłącza tryb pasywny
  • ftp_fget() - Pobiera plik z serwera FTP i zapisuje do otwartego pliku
  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)

ftp_get_option
ftp_login
FTP Funkcje


Loguje się w ramach połączenia FTP

ftp_get
ftp_mdtm
FTP Funkcje
PHP Manual

ftp_login

(PHP 4, PHP 5)

ftp_login — Loguje się w ramach połączenia FTP

Opis

bool ftp_login ( resource $strumień_ftp , string $nazwa_użytkownika , string $hasło )

Loguje się w ramach podanego strumienia FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

nazwa_użytkownika

Nazwa użytkownika (USER).

hasło

Hasło (PASS).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Jeśli logowanie się nie powiedzie, PHP wygeneruje także ostrzeżenie.

Przykłady

Przykład #1 Przykład użycia ftp_login()

<?php

$ftp_serwer            = "ftp.example.com";
$ftp_nazwa_uzytkownika = "foo";
$ftp_haslo             = "bar";

// nawiązanie połączenia lub zakończenie działania skryptu
$conn_id = ftp_connect($ftp_serwer) or die("Nie można połączyć się z $ftp_serwer");

// próba logowania
if (@ftp_login($conn_id, $ftp_nazwa_uzytkownika, $ftp_haslo)) {
    echo "Połączony jako $ftp_nazwa_uzytkownika@$ftp_serwer\n";
} else {
    echo "Nie można zalogować się jako $ftp_nazwa_uzytkownika\n";
}

// zamknięcie połączenia
ftp_close($conn_id);

?>

ftp_get
ftp_mdtm
FTP Funkcje


Zwraca czas ostatniej modyfikacji podanego pliku

ftp_login
ftp_mkdir
FTP Funkcje
PHP Manual

ftp_mdtm

(PHP 4, PHP 5)

ftp_mdtm — Zwraca czas ostatniej modyfikacji podanego pliku

Opis

int ftp_mdtm ( resource $strumień_ftp , string $plik_zdalny )

ftp_mdtm() zwraca czas ostatniej modyfikacji pliku zdalnego.

Informacja:

Nie wszystkie serwery FTP obsługują tą opcję.

Informacja:

ftp_mdtm() nie działa dla katalogów.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

plik_zdalny

Plik, którego data ostatniej modyfikacji ma być zwrócona.

Zwracane wartości

Zwraca czas ostatniej modyfikacji w postaci Uniksowego znacznika czasu (timestamp) w przypadku sukcesu, lub -1 w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_mdtm()

<?php

$plik = 'plik.txt';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

//  pobranie czasu ostatniej modyfikacji
$buff = ftp_mdtm($conn_id, $plik);

if ($buff != -1) {
    // plik.txt został zmodyfikowany 26.03.2003 14:16:41.
    echo "$plik został zmodyfikowany " . date("d.m.Y H:i:s.", $buff);
} else {
    echo "Data modyfikacji nie została pobrana.";
}

// zamknięcie połączenia
ftp_close($conn_id);

?>

ftp_login
ftp_mkdir
FTP Funkcje


Tworzy katalog

ftp_mdtm
ftp_nb_continue
FTP Funkcje
PHP Manual

ftp_mkdir

(PHP 4, PHP 5)

ftp_mkdir — Tworzy katalog

Opis

string ftp_mkdir ( resource $strumień_ftp , string $katalog )

Tworzy podany katalog na serwerze FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

katalog

Nazwa katalogu, który ma być stworzony.

Zwracane wartości

Zwraca nazwę nowo stworzonego katalogu, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_mkdir()

<?php

$katalog = 'www';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// próba stworzenia katalogu
if (ftp_mkdir($conn_id, $katalog)) {
 echo "Pomyślnie stworzono katalog $katalog\n";
} else {
 echo "Wystąpiły błędy przy tworzeniu katalogu $katalog\n";
}

// zamknięcie połączenia
ftp_close($conn_id);
?>

Zobacz też:

  • ftp_rmdir() - Usuwa katalog

ftp_mdtm
ftp_nb_continue
FTP Funkcje


Continues retrieving/sending a file (non-blocking)

ftp_mkdir
ftp_nb_fget
FTP Funkcje
PHP Manual

ftp_nb_continue

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_continue — Continues retrieving/sending a file (non-blocking)

Opis

int ftp_nb_continue ( resource $ftp_stream )

Continues retrieving/sending a file non-blocking.

Parametry

ftp_stream

The link identifier of the FTP connection.

Zwracane wartości

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Przykłady

Przykład #1 ftp_nb_continue() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

ftp_mkdir
ftp_nb_fget
FTP Funkcje


Retrieves a file from the FTP server and writes it to an open file (non-blocking)

ftp_nb_continue
ftp_nb_fput
FTP Funkcje
PHP Manual

ftp_nb_fget

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_fget — Retrieves a file from the FTP server and writes it to an open file (non-blocking)

Opis

int ftp_nb_fget ( resource $ftp_stream , resource $handle , string $remote_file , int $mode [, int $resumepos = 0 ] )

ftp_nb_fget() retrieves a remote file from the FTP server.

The difference between this function and ftp_fget() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Parametry

ftp_stream

The link identifier of the FTP connection.

handle

An open file pointer in which we store the data.

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Zwracane wartości

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Przykłady

Przykład #1 ftp_nb_fget() example

<?php

// open some file for reading
$file = 'index.php';
$fp = fopen($file, 'w');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the download
$ret = ftp_nb_fget($conn_id, $fp, $file, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

// close filepointer
fclose($fp);
?>

Zobacz też:

  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_fget() - Pobiera plik z serwera FTP i zapisuje do otwartego pliku
  • ftp_get() - Pobiera plik z serwera FTP

ftp_nb_continue
ftp_nb_fput
FTP Funkcje


Stores a file from an open file to the FTP server (non-blocking)

ftp_nb_fget
ftp_nb_get
FTP Funkcje
PHP Manual

ftp_nb_fput

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_fput — Stores a file from an open file to the FTP server (non-blocking)

Opis

int ftp_nb_fput ( resource $ftp_stream , string $remote_file , resource $handle , int $mode [, int $startpos = 0 ] )

ftp_nb_fput() uploads the data from a file pointer to a remote file on the FTP server.

The difference between this function and the ftp_fput() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Parametry

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

handle

An open file pointer on the local file. Reading stops at end of file.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

The position in the remote file to start uploading to.

Zwracane wartości

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Przykłady

Przykład #1 ftp_nb_fput() example

<?php

$file = 'index.php';

$fp = fopen($file, 'r');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the upload
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue upload...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

fclose($fp);
?>

Zobacz też:

  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_put() - Przesyła plik na serwer FTP
  • ftp_fput() - Wysyła dane z otwartego pliku na serwer FTP

ftp_nb_fget
ftp_nb_get
FTP Funkcje


Retrieves a file from the FTP server and writes it to a local file (non-blocking)

ftp_nb_fput
ftp_nb_put
FTP Funkcje
PHP Manual

ftp_nb_get

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_get — Retrieves a file from the FTP server and writes it to a local file (non-blocking)

Opis

int ftp_nb_get ( resource $ftp_stream , string $local_file , string $remote_file , int $mode [, int $resumepos = 0 ] )

ftp_nb_get() retrieves a remote file from the FTP server, and saves it into a local file.

The difference between this function and ftp_get() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Parametry

ftp_stream

The link identifier of the FTP connection.

local_file

The local file path (will be overwritten if the file already exists).

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Zwracane wartości

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Przykłady

Przykład #1 ftp_nb_get() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Przykład #2 Resuming a download with ftp_nb_get()

<?php

// Initate
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY,
                      filesize("test"));
// OR: $ret = ftp_nb_get($my_connection, "test", "README",
//                           FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Przykład #3 Resuming a download at position 100 to a new file with ftp_nb_get()

<?php

// Disable Autoseek
ftp_set_option($my_connection, FTP_AUTOSEEK, false);

// Initiate
$ret = ftp_nb_get($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

   /* ... */

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
?>

In the example above, newfile is 100 bytes smaller than README on the FTP server because we started reading at offset 100. If we didn't disable FTP_AUTOSEEK, the first 100 bytes of newfile would be '\0'.

Zobacz też:

  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_fget() - Pobiera plik z serwera FTP i zapisuje do otwartego pliku
  • ftp_get() - Pobiera plik z serwera FTP

ftp_nb_fput
ftp_nb_put
FTP Funkcje


Stores a file on the FTP server (non-blocking)

ftp_nb_get
ftp_nlist
FTP Funkcje
PHP Manual

ftp_nb_put

(PHP 4 >= 4.3.0, PHP 5)

ftp_nb_put — Stores a file on the FTP server (non-blocking)

Opis

int ftp_nb_put ( resource $ftp_stream , string $remote_file , string $local_file , int $mode [, int $startpos = 0 ] )

ftp_nb_put() stores a local file on the FTP server.

The difference between this function and the ftp_put() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Parametry

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

local_file

The local file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

The position in the remote file to start uploading to.

Zwracane wartości

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Przykłady

Przykład #1 ftp_nb_put() example

<?php

// Initiate the Upload
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

Przykład #2 Resuming an upload with ftp_nb_put()

<?php

// Initiate
$ret = ftp_nb_put($my_connection, "test.remote", "test.local",
                      FTP_BINARY, ftp_size("test.remote"));
// OR: $ret = ftp_nb_put($my_connection, "test.remote", "test.local",
//                           FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

Zobacz też:

  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_put() - Przesyła plik na serwer FTP
  • ftp_fput() - Wysyła dane z otwartego pliku na serwer FTP

ftp_nb_get
ftp_nlist
FTP Funkcje


Zwraca listę plików z podanego katalogu

ftp_nb_put
ftp_pasv
FTP Funkcje
PHP Manual

ftp_nlist

(PHP 4, PHP 5)

ftp_nlist — Zwraca listę plików z podanego katalogu

Opis

array ftp_nlist ( resource $strumień_ftp , string $katalog )

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

katalog

Katalog, którego zawartość ma być zwrócona. Parametr ten może także zawierać argumenty, na przykład ftp_nlist($conn_id, "-la /twój/katalog"); Należy pamiętać, że parametr ten nie jest dalej przetwarzany, więc mogą się pojawić pewne problemy z nazwami plików zawierającymi spacje i inne znaki.

Zwracane wartości

Zwraca tablicę nazw plików z podanego katalogu w przypadku powodzenia, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_nlist()

<?php

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// pobranie zawartości bieżącego katalogu
$zawartosc = ftp_nlist($conn_id, ".");

// wyświetlenie zawartości
var_dump($zawartosc);

?>

Powyższy przykład wyświetli coś podobnego do:

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

Zobacz też:

  • ftp_rawlist() - Zwraca szczegółową listę plików z podanego katalogu

ftp_nb_put
ftp_pasv
FTP Funkcje


Włącza lub wyłącza tryb pasywny

ftp_nlist
ftp_put
FTP Funkcje
PHP Manual

ftp_pasv

(PHP 4, PHP 5)

ftp_pasv — Włącza lub wyłącza tryb pasywny

Opis

bool ftp_pasv ( resource $strumień_ftp , bool $pasv )

ftp_pasv() włącza lub wyłącza tryb pasywny, w którym połączenia danych inicjowane są przez klienta, a nie przez serwer. Tryb taki może być niezbędny, jeśli klient jest za firewallem.

Proszę zauważyć, że ftp_pasv() może być wywołana wyłącznie po prawidłowym zalogowaniu się w innym przypadku zawiedzie.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

pasv

Jeśli argument ten ma wartośc TRUE, tryb pasywny jest włączany. Jeśli nie, zostaje wyłączony.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_pasv()

<?php
$plik = 'plik.txt';
$plik_zdalny = 'readme.txt';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// włączenie trybu pasywnego
ftp_pasv($conn_id, true);

// przesłanie pliku
if (ftp_put($conn_id, $plik_zdalny, $plik, FTP_ASCII)) {
 echo "Plik $plik został pomyślnie przesłany\n";
} else {
 echo "Napotkano problemy w czasie przesyłania pliku $plik\n";
}

// zamknięcie połączenia
ftp_close($conn_id);
?>

ftp_nlist
ftp_put
FTP Funkcje


Przesyła plik na serwer FTP

ftp_pasv
ftp_pwd
FTP Funkcje
PHP Manual

ftp_put

(PHP 4, PHP 5)

ftp_put — Przesyła plik na serwer FTP

Opis

bool ftp_put ( resource $strumień_ftp , string $plik_zdalny , string $plik_lokalny , int $tryb [, int $pozycja_początkowa ] )

ftp_put() przesyła plik lokalny na serwer FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

plik_zdalny

Ścieżka pliku zdalnego.

plik_lokalny

Ścieżka do pliku lokalnego.

tryb

Tryb transferu. Musi to być FTP_ASCII lub FTP_BINARY.

pozycja_początkowa

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_put()

<?php
$plik = 'plik.txt';
$plik_zdalny = 'readme.txt';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// przesłanie pliku
if (ftp_put($conn_id, $plik_zdalny, $plik, FTP_ASCII)) {
 echo "Plik $plik został pomyślnie przesłany\n";
} else {
 echo "Napotkano problemy w czasie przesyłania pliku $plik\n";
}

// zamknięcie połączenia
ftp_close($conn_id);
?>

Rejestr zmian

Wersja | Opis
4.3.0 | Dodano argument pozycja_początkowa.

Zobacz też:

  • ftp_pasv() - Włącza lub wyłącza tryb pasywny
  • ftp_fput() - Wysyła dane z otwartego pliku na serwer FTP
  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)

ftp_pasv
ftp_pwd
FTP Funkcje


Zwraca nazwę katalogu bieżącego

ftp_put
ftp_quit
FTP Funkcje
PHP Manual

ftp_pwd

(PHP 4, PHP 5)

ftp_pwd — Zwraca nazwę katalogu bieżącego

Opis

string ftp_pwd ( resource $strumień_ftp )

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

Zwracane wartości

Zwraca nazwę bieżącego katalogu, lub FALSE w przypadku napotkania błędu.

Przykłady

Przykład #1 Przykład użycia ftp_pwd()

<?php

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// zmiana katalogu bieżącego na public_html
ftp_chdir($conn_id, 'public_html');

// wyświetlenie katalogu bieżącego
echo ftp_pwd($conn_id); // /public_html

// zamknięcie połączenia
ftp_close($conn_id);
?>

Zobacz też:

  • ftp_chdir() - Zmienia bieżący katalog na serwerze FTP
  • ftp_cdup() - Zmienia bieżący katalog na nadrzędny

ftp_put
ftp_quit
FTP Funkcje


Alias dla ftp_close

ftp_pwd
ftp_raw
FTP Funkcje
PHP Manual

ftp_quit

(PHP 4, PHP 5)

ftp_quit — Alias dla ftp_close()

Opis

Ta funkcja jest aliasem dla: ftp_close().

ftp_pwd
ftp_raw
FTP Funkcje


Sends an arbitrary command to an FTP server

ftp_quit
ftp_rawlist
FTP Funkcje
PHP Manual

ftp_raw

(PHP 5)

ftp_raw — Sends an arbitrary command to an FTP server

Opis

array ftp_raw ( resource $ftp_stream , string $command )

Sends an arbitrary command to the FTP server.

Parametry

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Zwracane wartości

Returns the server's response as an array of strings. No parsing is performed on the response string, nor does ftp_raw() determine if the command succeeded.

Przykłady

Przykład #1 Using ftp_raw() to login to an FTP server manually.

<?php
$fp = ftp_connect("ftp.example.com");

/* This is the same as:
   ftp_login($fp, "joeblow", "secret"); */
ftp_raw($fp, "USER joeblow");
ftp_raw($fp, "PASS secret");
?>

Zobacz też:

  • ftp_exec() - Żąda wykonanie polecenia przez serwer FTP

ftp_quit
ftp_rawlist
FTP Funkcje


Zwraca szczegółową listę plików z podanego katalogu

ftp_raw
ftp_rename
FTP Funkcje
PHP Manual

ftp_rawlist

(PHP 4, PHP 5)

ftp_rawlist — Zwraca szczegółową listę plików z podanego katalogu

Opis

array ftp_rawlist ( resource $strumień_ftp , string $katalog [, bool $rekurencyjnie ] )

ftp_rawlist() wywołuje polecenie FTP LIST i zwraca wynik tego polecenia w postaci tablicy.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

katalog

Ścieżka do wybranego katalogu.

rekurencyjnie

Jeśli argument ten ma wartość TRUE, wydane zostanie polecenie LIST -R.

Zwracane wartości

Zwraca tablicę, w której każdy element odpowiada jednej linijce tekstu.

Wynik nie jest przetwarzany w żaden sposób. Do interpretacji wyników może być użyty identyfikator typu systemu zwracany przez funkcję ftp_systype().

Przykłady

Przykład #1 Przykład użycia ftp_rawlist()

<?php

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// pobranie listy plików dla katalogu głównego
$buff = ftp_rawlist($conn_id, '/');

// zamknięcie połączenia
ftp_close($conn_id);

// wyświetlenie bufora
var_dump($buff);
?>

Powyższy przykład wyświetli coś podobnego do:

array(3) {
  [0]=>
  string(65) "drwxr-x---   3 vincent  vincent      4096 Jul 12 12:16 public_ftp"
  [1]=>
  string(66) "drwxr-x---  15 vincent  vincent      4096 Nov  3 21:31 public_html"
  [2]=>
  string(73) "lrwxrwxrwx   1 vincent  vincent        11 Jul 12 12:16 www -> public_html"
}

Rejestr zmian

Wersja | Opis
4.3.0 | Dodano argument recursive.

Zobacz też:

  • ftp_nlist() - Zwraca listę plików z podanego katalogu

ftp_raw
ftp_rename
FTP Funkcje


Zmienia nazwę pliku lub katalogu na serwerze FTP

ftp_rawlist
ftp_rmdir
FTP Funkcje
PHP Manual

ftp_rename

(PHP 4, PHP 5)

ftp_rename — Zmienia nazwę pliku lub katalogu na serwerze FTP

Opis

bool ftp_rename ( resource $strumień_ftp , string $stara_nazwa , string $nowa_nazwa )

ftp_rename() zmienia nazwę pliku lub katalogu znajdującego się na serwerze FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

stara_nazwa

Stara nazwa pliku lub katalogu.

nowa_nazwa

Nowa nazwa.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_rename()

<?php
$stary_plik = 'plik.txt.bak';
$nowy_plik  = 'plik.txt';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// próba zmiany nazwy $stary_plik na $nowy_plik
if (ftp_rename($conn_id, $stary_plik, $nowy_plik)) {
 echo "Pomyślnie zmieniono nazwę pliku $stary_plik na $nowy_plik\n";
} else {
 echo "Wystąpił problem przy zmianie nazwy $stary_plik na $nowy_plik\n";
}

// zamknięcie połączenia
ftp_close($conn_id);
?>

ftp_rawlist
ftp_rmdir
FTP Funkcje


Usuwa katalog

ftp_rename
ftp_set_option
FTP Funkcje
PHP Manual

ftp_rmdir

(PHP 4, PHP 5)

ftp_rmdir — Usuwa katalog

Opis

bool ftp_rmdir ( resource $strumień_ftp , string $directory )

Usuwa podany katalog z serwera FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

katalog

Katalog do usunięcia. Musi to być względna lub bezwzględna ścieżka do pustego katalogu.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_rmdir()

<?php

$katalog = 'www/';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// próba usunięcia katalogu
if (ftp_rmdir($conn_id, $katalog)) {
    echo "Pomyślnie usunięto katalog $katalog\n";
} else {
    echo "Wystąpiły problemy przy usuwaniu katalogu $katalog\n";
}

// zamknięcie połączenia
ftp_close($conn_id);

?>

Zobacz też:

  • ftp_mkdir() - Tworzy katalog

ftp_rename
ftp_set_option
FTP Funkcje


Set miscellaneous runtime FTP options

ftp_rmdir
ftp_site
FTP Funkcje
PHP Manual

ftp_set_option

(PHP 4 >= 4.2.0, PHP 5)

ftp_set_option — Set miscellaneous runtime FTP options

Opis

bool ftp_set_option ( resource $strumień_ftp , int $opcja , mixed $wartość )

Funkcja ta zmienia wartości różnych ustawień dotyczących połączeń FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

opcja

Aktualnie obsługiwane są poniższe opcje:

Obsługiwane opcje połączeń FTP
FTP_TIMEOUT_SEC | Zmienia czas przedawnienia, podawany w sekundach, używany przy wsyzstkich operacjach sieciowych. wartość musi być wartością całkowitą większą od zera. Wartość domyślna to 90 sekund.
FTP_AUTOSEEK | Jeśli ta opcja jest włączona, żądania GET lub PUT z parameterami pozycja_wznowienia lub pozycja_początkowa najpierw będzie szukać wskazanej pozycji wewnątrz pliku. Opcja ta jest domyślnie włączona.

wartość

Argument ten zależy od tego, która opcja ma być zmieniana.

Zwracane wartości

Zwraca wartość TRUE jeśli opcja mogła być ustawiona, FALSE w przeciwnym przypadku. PHP wygeneruje ostrzeżenie jeśli podana opcja nie jest obsługiwana lub wartość nie odpowiada oczekiwaniom dotyczącym wybranej opcji.

Przykłady

Przykład #1 Przykład użycia ftp_set_option()

<?php
// Ustawienie czasu przedawnienia na 100 sekund
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);
?>

Zobacz też:

  • ftp_get_option() - Pobiera ustawienia dotyczące strumienia FTP

ftp_rmdir
ftp_site
FTP Funkcje


Wysyła polecenie SITE do serwera FTP

ftp_set_option
ftp_size
FTP Funkcje
PHP Manual

ftp_site

(PHP 4, PHP 5)

ftp_site — Wysyła polecenie SITE do serwera FTP

Opis

bool ftp_site ( resource $strumień_ftp , string $polecenie )

ftp_site() wysyła podane polecenie SITE do serwera FTP

Polecenia SITE nie są ustandaryzowane i mogą się różnić zależnie od serwera FTP. Są one przydatne w przypadku ustalania praw dostępu do plików lub przynależności do grup.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

polecenie

Polecenie SITE. Nalezy pamiętać, że argument ten nie jest przetwarzany, co może spowodować pewne błędy przy plikach zawierających spacje i inne znaki.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Wysyłanie polecenia SITE do serwera FTP

<?php
// Łączenie z serwerem
$conn = ftp_connect('ftp.example.com');
if (!$conn) die('Nie można się połączyć z ftp.example.com');

// Logowanie jako "uzytkownik" z hasłem "haslo"
if (!ftp_login($conn, 'uzytkownik', 'haslo')) die('Błąd przy logowaniu się do ftp.example.com');

// Wykonanie polecenia "SITE CHMOD 0600 /home/uzytkownik/plik"
if (ftp_site($conn, 'CHMOD 0600 /home/uzytkownik/plik')) {
   echo "Polecenie wykonane pomyślnie.\n";
} else {
   die('Wykonanie polecenia się nie powiodło.');
}
?>

Zobacz też:

  • ftp_raw() - Sends an arbitrary command to an FTP server

ftp_set_option
ftp_size
FTP Funkcje


Zwraca rozmiar podanego pliku

ftp_site
ftp_ssl_connect
FTP Funkcje
PHP Manual

ftp_size

(PHP 4, PHP 5)

ftp_size — Zwraca rozmiar podanego pliku

Opis

int ftp_size ( resource $strumień_ftp , string $plik_zdalny )

ftp_size() zwraca rozmiar podanego pliku zdalnego wyrażony w bajtach.

Informacja:

Nie wszystkie serwery obsługują tą opcję.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

plik_zdalny

Plik zdalny, którego rozmiar ma być zwrócony.

Zwracane wartości

Zwraca rozmiar pliku w przypadku powodzenia lub -1 w przypadku błędu.

Przykłady

Przykład #1 Przykład użycia ftp_size()

<?php

$plik = 'plik.txt';

// nawiązanie połączenia
$conn_id = ftp_connect($ftp_server);

// logowanie
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// pobranie rozmiaru pliku $plik
$res = ftp_size($conn_id, $plik);

if ($res != -1) {
    echo "Rozmiar pliku $plik to $res bajtów";
} else {
    echo "Nie można pobrać wielkości pliku.";
}

// zamknięcie połączenia
ftp_close($conn_id);

?>

Zobacz też:

  • ftp_rawlist() - Zwraca szczegółową listę plików z podanego katalogu

ftp_site
ftp_ssl_connect
FTP Funkcje


Opens an Secure SSL-FTP connection

ftp_size
ftp_systype
FTP Funkcje
PHP Manual

ftp_ssl_connect

(PHP 4 >= 4.3.0, PHP 5)

ftp_ssl_connect — Opens an Secure SSL-FTP connection

Opis

resource ftp_ssl_connect ( string $host [, int $port = 21 [, int $timeout = 90 ]] )

ftp_ssl_connect() opens an explicit SSL-FTP connection to the specified host.

Informacja: Why this function may not exist

ftp_ssl_connect() is only available if both the ftp module and the OpenSSL support is built statically into php, this means that on Windows this function will be undefined in the official PHP builds. To make this function available on Windows you must compile your own PHP binaries.

Informacja:

ftp_ssl_connect() is not intended for use with sFTP. To use sFTP with PHP, please see ssh2_sftp().

Parametry

host

The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.

port

This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

timeout

This parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Zwracane wartości

Returns a SSL-FTP stream on success or FALSE on error.

Rejestr zmian

Wersja | Opis
5.2.2 | The function was changed to return FALSE when it can't use an SSL connection, instead of fallbacking to a non-SSL one as previously.

Przykłady

Przykład #1 ftp_ssl_connect() example

<?php

// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

echo ftp_pwd($conn_id); // /

// close the ssl connection
ftp_close($conn_id);
?>

Zobacz też:

  • ftp_connect() - Opens an FTP connection

ftp_size
ftp_systype
FTP Funkcje


Zwraca identyfikator typu systemu dla zdalnego serwera FTP

ftp_ssl_connect
Gearman
FTP Funkcje
PHP Manual

ftp_systype

(PHP 4, PHP 5)

ftp_systype — Zwraca identyfikator typu systemu dla zdalnego serwera FTP

Opis

string ftp_systype ( resource $strumień_ftp )

Zwraca identyfikator typu systemu dla zdalnego serwera FTP.

Parametry

strumień_ftp

Identyfikator połączenia z serwerem FTP.

Zwracane wartości

Zwraca typ zdalnego systemu lub FALSE w przypadku napotkania błędu.

Przykłady

Przykład #1 Przykład użycia ftp_systype()

<?php

// połączenie ftp
$ftp = ftp_connect('ftp.example.com');
ftp_login($ftp, 'użytkownik', 'hasło');

// pobranie typu systemu
if ($type = ftp_systype($ftp)) {
    echo "Example.com pracuje na $type\n";
} else {
    echo "Nie można pobrać tytpu systemu";
}

?>

Powyższy przykład wyświetli coś podobnego do:

Example.com pracuje na UNIX

ftp_ssl_connect
Gearman
FTP Funkcje


Gearman

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
    • Basic Gearman client and worker, background
    • Basic Gearman client and worker, submitting tasks
  • GearmanClient — The GearmanClient class
    • GearmanClient::addOptions — Add client options
    • GearmanClient::addServer — Add a job server to the client
    • GearmanClient::addServers — Add a list of job servers to the client
    • GearmanClient::addTask — Add a task to be run in parallel
    • GearmanClient::addTaskBackground — Add a background task to be run in parallel
    • GearmanClient::addTaskHigh — Add a high priority task to run in parallel
    • GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel
    • GearmanClient::addTaskLow — Add a low priority task to run in parallel
    • GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel
    • GearmanClient::addTaskStatus — Add a task to get status
    • GearmanClient::clearCallbacks — Clear all task callback functions
    • GearmanClient::clone — Create a copy of a GearmanClient object
    • GearmanClient::__construct — Create a GearmanClient instance
    • GearmanClient::context — Get the application context
    • GearmanClient::data — Get the application data (deprecated)
    • GearmanClient::do — Run a single task and return a result [deprecated]
    • GearmanClient::doBackground — Run a task in the background
    • GearmanClient::doHigh — Run a single high priority task
    • GearmanClient::doHighBackground — Run a high priority task in the background
    • GearmanClient::doJobHandle — Get the job handle for the running task
    • GearmanClient::doLow — Run a single low priority task
    • GearmanClient::doLowBackground — Run a low priority task in the background
    • GearmanClient::doNormal — Run a single task and return a result
    • GearmanClient::doStatus — Get the status for the running task
    • GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]
    • GearmanClient::error — Returns an error string for the last error encountered.
    • GearmanClient::getErrno — Get an errno value
    • GearmanClient::jobStatus — Get the status of a background job
    • GearmanClient::ping — Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions — Remove client options
    • GearmanClient::returnCode — Get the last Gearman return code
    • GearmanClient::runTasks — Run a list of tasks in parallel
    • GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
    • GearmanClient::setCompleteCallback — Set a function to be called on task completion
    • GearmanClient::setContext — Set application context
    • GearmanClient::setCreatedCallback — Set a callback for when a task is queued
    • GearmanClient::setData — Set application data (deprecated)
    • GearmanClient::setDataCallback — Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback — Set a callback for worker exceptions
    • GearmanClient::setFailCallback — Set callback for job failure
    • GearmanClient::setOptions — Set client options
    • GearmanClient::setStatusCallback — Set a callback for collecting task status
    • GearmanClient::setTimeout — Set socket I/O activity timeout
    • GearmanClient::setWarningCallback — Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
    • GearmanClient::timeout — Get current socket I/O activity timeout value
  • GearmanJob — The GearmanJob class
    • GearmanJob::complete — Send the result and complete status (deprecated)
    • GearmanJob::__construct — Create a GearmanJob instance
    • GearmanJob::data — Send data for a running job (deprecated)
    • GearmanJob::exception — Send exception for running job (deprecated)
    • GearmanJob::fail — Send fail status (deprecated)
    • GearmanJob::functionName — Get function name
    • GearmanJob::handle — Get the job handle
    • GearmanJob::returnCode — Get last return code
    • GearmanJob::sendComplete — Send the result and complete status
    • GearmanJob::sendData — Send data for a running job
    • GearmanJob::sendException — Send exception for running job (exception)
    • GearmanJob::sendFail — Send fail status
    • GearmanJob::sendStatus — Send status
    • GearmanJob::sendWarning — Send a warning
    • GearmanJob::setReturn — Set a return value
    • GearmanJob::status — Send status (deprecated)
    • GearmanJob::unique — Get the unique identifier
    • GearmanJob::warning — Send a warning (deprecated)
    • GearmanJob::workload — Get workload
    • GearmanJob::workloadSize — Get size of work load
  • GearmanTask — The GearmanTask class
    • GearmanTask::__construct — Create a GearmanTask instance
    • GearmanTask::create — Create a task (deprecated)
    • GearmanTask::data — Get data returned for a task
    • GearmanTask::dataSize — Get the size of returned data
    • GearmanTask::function — Get associated function name (deprecated)
    • GearmanTask::functionName — Get associated function name
    • GearmanTask::isKnown — Determine if task is known
    • GearmanTask::isRunning — Test whether the task is currently running
    • GearmanTask::jobHandle — Get the job handle
    • GearmanTask::recvData — Read work or result data into a buffer for a task
    • GearmanTask::returnCode — Get the last return code
    • GearmanTask::sendData — Send data for a task (deprecated)
    • GearmanTask::sendWorkload — Send data for a task
    • GearmanTask::taskDenominator — Get completion percentage denominator
    • GearmanTask::taskNumerator — Get completion percentage numerator
    • GearmanTask::unique — Get the unique identifier for a task
    • GearmanTask::uuid — Get the unique identifier for a task (deprecated)
  • GearmanWorker — The GearmanWorker class
    • GearmanWorker::addFunction — Register and add callback function
    • GearmanWorker::addOptions — Add worker options
    • GearmanWorker::addServer — Add a job server
    • GearmanWorker::addServers — Add job servers
    • GearmanWorker::clone — Create a copy of the worker
    • GearmanWorker::__construct — Create a GearmanWorker instance
    • GearmanWorker::echo — Test job server response
    • GearmanWorker::error — Get the last error encountered
    • GearmanWorker::getErrno — Get errno
    • GearmanWorker::options — Get worker options
    • GearmanWorker::register — Register a function with the job server
    • GearmanWorker::removeOptions — Remove worker options
    • GearmanWorker::returnCode — Get last Gearman return code
    • GearmanWorker::setOptions — Set worker options
    • GearmanWorker::setTimeout — Set socket I/O activity timeout
    • GearmanWorker::timeout — Get socket I/O activity timeout
    • GearmanWorker::unregister — Unregister a function name with the job servers
    • GearmanWorker::unregisterAll — Unregister all function names with the job servers
    • GearmanWorker::wait — Wait for activity from one of the job servers
    • GearmanWorker::work — Wait for and perform jobs
ftp_systype
Wstęp
Inne serwisy


Wstęp

» Gearman is a generic application framework for farming out work to multiple machines or processes. It allows applications to complete tasks in parallel, to load balance processing, and to call functions between languages. The framework can be used in a variety of applications, from high-availability web sites to the transport of database replication events.

This extension provides classes for writing Gearman clients and workers.

Gearman
Instalacja/Konfiguracja
Gearman


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Gearman


Wymagania

This extension requires the » libgearman library and a running Gearman server.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/gearman

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Return values. Always check GearmanClient::error() or GearmanWorker() for a string error, as it may contain more details:

GEARMAN_SUCCESS (integer)
Whatever action was taken was successful.
GEARMAN_IO_WAIT (integer)
When in non-blocking mode, an event is hit that would have blocked.
GEARMAN_ERRNO (integer)
A system error. Check GearmanClient::errno() or GearmanWorker::errno() for the system error code that was returned.
GEARMAN_NO_ACTIVE_FDS (integer)
GearmanClient::wait() or GearmanWorker() was called with no connections.
GEARMAN_UNEXPECTED_PACKET (integer)
Indicates something going very wrong in gearmand. Applies only to GearmanWorker.
GEARMAN_GETADDRINFO (integer)
DNS resolution failed (invalid host, port, etc).
GEARMAN_NO_SERVERS (integer)
Did not call GearmanClient::addServer() before submitting jobs or tasks.
GEARMAN_LOST_CONNECTION (integer)
Lost a connection during a request.
GEARMAN_MEMORY_ALLOCATION_FAILURE (integer)
Memory allocation failed (ran out of memory).
GEARMAN_SERVER_ERROR (integer)
Something went wrong in the Gearman server and it could not handle the request gracefully.
GEARMAN_WORK_DATA (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Sent to update the client with data from a running job. A worker uses this when it needs to send updates, send partial results, or flush data during long running jobs.
GEARMAN_WORK_WARNING (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Updates the client with a warning. The behavior is just like GEARMAN_WORK_DATA, but should be treated as a warning instead of normal response data.
GEARMAN_WORK_STATUS (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Sent to update the status of a long running job. Use GearmanClient::doStatus() to obtain the percentage complete of the task.
GEARMAN_WORK_EXCEPTION (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Indicates that a job failed with a given exception.
GEARMAN_WORK_FAIL (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Indicates that the job failed.
GEARMAN_COULD_NOT_CONNECT (integer)
Failed to connect to servers.
GEARMAN_INVALID_FUNCTION_NAME (integer)
Trying to register a function name of NULL or using the callback interface without specifying callbacks.
GEARMAN_INVALID_WORKER_FUNCTION (integer)
Trying to register a function with a NULL callback function.
GEARMAN_NO_REGISTERED_FUNCTIONS (integer)
When a worker gets a job for a function it did not register.
GEARMAN_NO_JOBS (integer)
For a non-blocking worker, when GearmanWorker::work() does not have any active jobs.
GEARMAN_ECHO_DATA_CORRUPTION (integer)
After GearmanClient::echo() or GearmanWorker::echo() the data returned doesn't match the data sent.
GEARMAN_NEED_WORKLOAD_FN (integer)
When the client opted to stream the workload of a task, but did not specify a workload callback function.
GEARMAN_PAUSE (integer)
For the non-blocking client task interface, can be returned from the task callback to "pause" the call and return from GearmanClient::runTasks(). Call GearmanClient::runTasks() again to continue.
GEARMAN_UNKNOWN_STATE (integer)
Internal client/worker state error.
GEARMAN_SEND_BUFFER_TOO_SMALL (integer)
Internal error: trying to flush more data in one atomic chunk than is possible due to hard-coded buffer sizes.
GEARMAN_TIMEOUT (integer)
Hit the timeout limit set by the client/worker.

GearmanClient options:

GEARMAN_CLIENT_NON_BLOCKING (integer)
Run the cient in a non-blocking mode.
GEARMAN_CLIENT_UNBUFFERED_RESULT (integer)
Allow the client to read data in chunks rather than have the library buffer the entire data result and pass that back.
GEARMAN_CLIENT_FREE_TASKS (integer)
Automatically free task objects once they are complete. This is the default setting in this extension to prevent memory leaks.

GearmanWorker options:

GEARMAN_WORKER_NON_BLOCKING (integer)
Run the worker in non-blocking mode.
GEARMAN_WORKER_GRAB_UNIQ (integer)
Return the client assigned unique ID in addition to the job handle.

Base Gearman configuration:

GEARMAN_DEFAULT_TCP_HOST (string)
GEARMAN_DEFAULT_TCP_PORT (integer)
GEARMAN_DEFAULT_SOCKET_TIMEOUT (integer)
GEARMAN_DEFAULT_SOCKET_SEND_SIZE (integer)
GEARMAN_DEFAULT_SOCKET_RECV_SIZE (integer)
GEARMAN_MAX_ERROR_SIZE (integer)
GEARMAN_PACKET_HEADER_SIZE (integer)
GEARMAN_JOB_HANDLE_SIZE (integer)
GEARMAN_OPTION_SIZE (integer)
GEARMAN_UNIQUE_SIZE (integer)
GEARMAN_MAX_COMMAND_ARGS (integer)
GEARMAN_ARGS_BUFFER_SIZE (integer)
GEARMAN_SEND_BUFFER_SIZE (integer)
GEARMAN_RECV_BUFFER_SIZE (integer)
GEARMAN_WORKER_WAIT_TIMEOUT (integer)

Typy zasobów
Przykłady
Gearman


Przykłady

Spis treści

  • Basic usage
  • Basic Gearman client and worker, background
  • Basic Gearman client and worker, submitting tasks
Stałe predefiniowane
Basic usage
Gearman


Basic usage

Przykład #1 Basic Gearman client and worker

This example shows a very simple client and worker. The client sends a string to the job server, and the worker reverses the string and sends it back. The job is performed synchronously.

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->do("reverse", "Hello!");

  # Check for various return packets and errors.
  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x, $workload_size);
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

Powyższy przykład wyświetli coś podobnego do:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:36
Workload: Hello! (6)
Sending status: 1/6 complete
Sending status: 2/6 complete
Sending status: 3/6 complete
Sending status: 4/6 complete
Sending status: 5/6 complete
Sending status: 6/6 complete
Result: !olleH

% php reverse_client.php
Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH

Przykłady
Basic Gearman client and worker, background
Przykłady


Basic Gearman client and worker, background

Przykład #1 Basic Gearman client and worker, background

This example shows a very simple client and worker. The client sends a string to the job server as a background job, and the worker reverses the string. Note that since the work is performed asynchronously, the client does not wait for the job to complete and exits (and hence the client never receives the results).

<?php

# create our client object
$gmclient= new GearmanClient();

# add the default server (localhost)
$gmclient->addServer();

# run reverse client in the background
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

echo "done!\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x, $workload_size);
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

Powyższy przykład wyświetli coś podobnego do:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:41
Workload: this is a test (14)
1/14 complete
2/14 complete
3/14 complete
4/14 complete
5/14 complete
6/14 complete
7/14 complete
8/14 complete
9/14 complete
10/14 complete
11/14 complete
12/14 complete
13/14 complete
14/14 complete
Result: tset a si siht

% php reverse_client_bg.php
done!

Basic usage
Basic Gearman client and worker, submitting tasks
Przykłady


Basic Gearman client and worker, submitting tasks

Przykład #1 Basic Gearman client and worker, submitting tasks

In this exmple, the basic reverse client extended to run two tasks in parallel. The reverse worker is unchanged except to add sending of data back during processing.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default server (localhost)
$gmc->addServer();

# register some callbacks
$gmc->setCreatedCallback("reverse_created");
$gmc->setDataCallback("reverse_data");
$gmc->setStatusCallback("reverse_status");
$gmc->setCompleteCallback("reverse_complete");
$gmc->setFailCallback("reverse_fail");

# set some arbitrary application data
$data['foo'] = 'bar';

# add two tasks
$task= $gmc->addTask("reverse", "foo", $data);
$task2= $gmc->addTaskLow("reverse", "bar", NULL);

# run the tasks in parallel (assuming multiple workers)
if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}

echo "DONE\n";

function reverse_created($task)
{
    echo "CREATED: " . $task->jobHandle() . "\n";
}

function reverse_status($task)
{
    echo "STATUS: " . $task->jobHandle() . " - " . $task->taskNumerator() .
         "/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->jobHandle() . ", " . $task->data() . "\n";
}

function reverse_fail($task)
{
    echo "FAILED: " . $task->jobHandle() . "\n";
}

function reverse_data($task)
{
    echo "DATA: " . $task->data() . "\n";
}

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

Powyższy przykład wyświetli coś podobnego do:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:45
Workload: foo (3)
1/3 complete
2/3 complete
3/3 complete
Result: oof
Received job: H:foo.local:44
Workload: bar (3)
1/3 complete
2/3 complete
3/3 complete
Result: rab

% php reverse_client_task.php
CREATED: H:foo.local:44
CREATED: H:foo.local:45
STATUS: H:foo.local:45 - 1/3
DATA: f
STATUS: H:foo.local:45 - 2/3
DATA: o
STATUS: H:foo.local:45 - 3/3
DATA: o
COMPLETE: H:foo.local:45, oof
STATUS: H:foo.local:44 - 1/3
DATA: b
STATUS: H:foo.local:44 - 2/3
DATA: a
STATUS: H:foo.local:44 - 3/3
DATA: r
COMPLETE: H:foo.local:44, rab
DONE

Basic Gearman client and worker, background
GearmanClient
Przykłady


The GearmanClient class

(No version information available, might only be in SVN)

Wstęp

Represents a class for connecting to a Gearman job server and making requests to perform some function on provided data. The function performed must be one registerd by a Gearman worker and the data passed is opaque to the job server.

Krótki opis klasy

GearmanClient {
/* Metody */
public bool addOptions ( int $options )
public bool addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] )
public bool addServers ([ string $servers = 127.0.0.1:4730 ] )
public GearmanTask addTask ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskHigh ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskHighBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskLow ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskLowBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )
public GearmanTask addTaskStatus ( string $job_handle [, string &$context ] )
public bool clearCallbacks ( void )
public GearmanClient clone ( void )
public __construct ( void )
public string context ( void )
public string data ( void )
public string do ( string $function_name , string $workload [, string $unique ] )
public string doBackground ( string $function_name , string $workload [, string $unique ] )
public string doHigh ( string $function_name , string $workload [, string $unique ] )
public string doHighBackground ( string $function_name , string $workload [, string $unique ] )
public string doJobHandle ( void )
public string doLow ( string $function_name , string $workload [, string $unique ] )
public string doLowBackground ( string $function_name , string $workload [, string $unique ] )
public string doNormal ( string $function_name , string $workload [, string $unique ] )
public array doStatus ( void )
public bool echo ( string $workload )
public string error ( void )
public int getErrno ( void )
public array jobStatus ( string $job_handle )
public bool ping ( string $workload )
public bool removeOptions ( int $options )
public int returnCode ( void )
public bool runTasks ( void )
public void setClientCallback ( callback $callback )
public bool setCompleteCallback ( callback $callback )
public bool setContext ( string $context )
public bool setCreatedCallback ( string $callback )
public bool setData ( string $data )
public bool setDataCallback ( callback $callback )
public bool setExceptionCallback ( callback $callback )
public bool setFailCallback ( callback $callback )
public bool setOptions ( int $options )
public bool setStatusCallback ( callback $callback )
public bool setTimeout ( int $timeout )
public bool setWarningCallback ( callback $callback )
public bool setWorkloadCallback ( callback $callback )
public int timeout ( void )
}

Spis treści

  • GearmanClient::addOptions — Add client options
  • GearmanClient::addServer — Add a job server to the client
  • GearmanClient::addServers — Add a list of job servers to the client
  • GearmanClient::addTask — Add a task to be run in parallel
  • GearmanClient::addTaskBackground — Add a background task to be run in parallel
  • GearmanClient::addTaskHigh — Add a high priority task to run in parallel
  • GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLow — Add a low priority task to run in parallel
  • GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel
  • GearmanClient::addTaskStatus — Add a task to get status
  • GearmanClient::clearCallbacks — Clear all task callback functions
  • GearmanClient::clone — Create a copy of a GearmanClient object
  • GearmanClient::__construct — Create a GearmanClient instance
  • GearmanClient::context — Get the application context
  • GearmanClient::data — Get the application data (deprecated)
  • GearmanClient::do — Run a single task and return a result [deprecated]
  • GearmanClient::doBackground — Run a task in the background
  • GearmanClient::doHigh — Run a single high priority task
  • GearmanClient::doHighBackground — Run a high priority task in the background
  • GearmanClient::doJobHandle — Get the job handle for the running task
  • GearmanClient::doLow — Run a single low priority task
  • GearmanClient::doLowBackground — Run a low priority task in the background
  • GearmanClient::doNormal — Run a single task and return a result
  • GearmanClient::doStatus — Get the status for the running task
  • GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]
  • GearmanClient::error — Returns an error string for the last error encountered.
  • GearmanClient::getErrno — Get an errno value
  • GearmanClient::jobStatus — Get the status of a background job
  • GearmanClient::ping — Send data to all job servers to see if they echo it back
  • GearmanClient::removeOptions — Remove client options
  • GearmanClient::returnCode — Get the last Gearman return code
  • GearmanClient::runTasks — Run a list of tasks in parallel
  • GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
  • GearmanClient::setCompleteCallback — Set a function to be called on task completion
  • GearmanClient::setContext — Set application context
  • GearmanClient::setCreatedCallback — Set a callback for when a task is queued
  • GearmanClient::setData — Set application data (deprecated)
  • GearmanClient::setDataCallback — Callback function when there is a data packet for a task
  • GearmanClient::setExceptionCallback — Set a callback for worker exceptions
  • GearmanClient::setFailCallback — Set callback for job failure
  • GearmanClient::setOptions — Set client options
  • GearmanClient::setStatusCallback — Set a callback for collecting task status
  • GearmanClient::setTimeout — Set socket I/O activity timeout
  • GearmanClient::setWarningCallback — Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
  • GearmanClient::timeout — Get current socket I/O activity timeout value
Basic Gearman client and worker, submitting tasks
GearmanClient::addOptions
Gearman


Add client options

GearmanClient
GearmanClient::addServer
GearmanClient
PHP Manual

GearmanClient::addOptions

(PECL gearman >= 0.6.0)

GearmanClient::addOptions — Add client options

Opis

public bool GearmanClient::addOptions ( int $options )

Adds one or more options to those already set.

Parametry

options

The options to add

Zwracane wartości

Always returns TRUE.

GearmanClient
GearmanClient::addServer
GearmanClient


Add a job server to the client

GearmanClient::addOptions
GearmanClient::addServers
GearmanClient
PHP Manual

GearmanClient::addServer

(PECL gearman >= 0.5.0)

GearmanClient::addServer — Add a job server to the client

Opis

public bool GearmanClient::addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] )

Adds a job server to a list of servers that can be used to run a task. No socket I/O happens here; the server is simply added to the list.

Parametry

host

Nazwa hosta serwera roboczego.

port

Port serwera roboczego.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Adding two job servers

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add two job servers, the first on the default 4730 port
$gmclient->addServer("10.0.0.1");
$gmclient->addServer("10.0.0.2", 7003);

?>

Zobacz też:

  • GearmanClient::addServers() - Add a list of job servers to the client

GearmanClient::addOptions
GearmanClient::addServers
GearmanClient


Add a list of job servers to the client

GearmanClient::addServer
GearmanClient::addTask
GearmanClient
PHP Manual

GearmanClient::addServers

(PECL gearman >= 0.5.0)

GearmanClient::addServers — Add a list of job servers to the client

Opis

public bool GearmanClient::addServers ([ string $servers = 127.0.0.1:4730 ] )

Adds a list of job servers that can be used to run a task. No socket I/O happens here; the servers are simply added to the full list of servers.

Parametry

servers

A comma-separated list of servers, each server specified in the format 'host:port'.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Add two job servers

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add multiple job servers, the first on the default 4730 port
$gmclient->addServers("10.0.0.1,10.0.0.2:7003");

?>

Zobacz też:

  • GearmanClient::addServer() - Add a job server to the client

GearmanClient::addServer
GearmanClient::addTask
GearmanClient


Add a task to be run in parallel

GearmanClient::addServers
GearmanClient::addTaskBackground
GearmanClient
PHP Manual

GearmanClient::addTask

(PECL gearman >= 0.5.0)

GearmanClient::addTask — Add a task to be run in parallel

Opis

public GearmanTask GearmanClient::addTask ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Note that enough workers need to be available for the tasks to all run in parallel.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Zwracane wartości

A GearmanTask object or FALSE if the task could not be added.

Przykłady

Przykład #1 Basic submission of two tasks

<?php

# Create our gearman client
$gmclient= new GearmanClient();

# add the default job server
$gmclient->addServer();

# add a task to perform the "reverse" function on the string "Hello World!"
$gmclient->addTask("reverse", "Hello World!", null, "1");

# add another task to perform the "reverse" function on the string "!dlroW olleH"
$gmclient->addTask("reverse", "!dlroW olleH", null, "2");

# set a function to be called when the work is complete
$gmclient->setCompleteCallback("complete");

# run the tasks
$gmclient->runTasks();

function complete($task)
{
  print "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

COMPLETE: 2, Hello World!
COMPLETE: 1, !dlroW olleH

Przykład #2 Basic submission of two tasks with passing application context

<?php

$client = new GearmanClient();
$client->addServer();

# Add some tasks for a placeholder of where to put the results
$results = array();
$client->addTask("reverse", "Hello World!", &$results, "t1");
$client->addTask("reverse", "!dlroW olleH", &$results, "t2");

$client->setCompleteCallback("reverse_complete");
$client->runTasks();

# The results should now be filled in from the callbacks
foreach ($results as $id => $result)
   echo $id . ": " . $result['handle'] . ", " . $result['data'] . "\n";

function reverse_complete($task, $results)
{
   $results[$task->unique()] = array("handle"=>$task->jobHandle(), "data"=>$task->data());
}

?>

Powyższy przykład wyświetli coś podobnego do:

t2: H.foo:21, Hello World!
t1: H:foo:22, !dlroW olleH

Zobacz też:

  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

GearmanClient::addServers
GearmanClient::addTaskBackground
GearmanClient


Add a background task to be run in parallel

GearmanClient::addTask
GearmanClient::addTaskHigh
GearmanClient
PHP Manual

GearmanClient::addTaskBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskBackground — Add a background task to be run in parallel

Opis

public GearmanTask GearmanClient::addTaskBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Zwracane wartości

A GearmanTask object or FALSE if the task could not be added.

Przykłady

Przykład #1 Two tasks, one background and one not

This example illustrates the difference between running a background task and a normal task. The client adds two tasks to execute the same function, but one is added with addTaskBackground(). A callback is set so that progress of the job can be tracked. A simple worker with an artificial delay reports on the job progress and the client picks this up through the callback. Two workers are run for this example. Note that the background task does not show in the client output.

<?php

# The client script

# create our gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set a couple of callbacks so we can track progress
$gmc->setCompleteCallback("reverse_complete");
$gmc->setStatusCallback("reverse_status");

# add a task for the "reverse" function
$task= $gmc->addTask("reverse", "Hello World!", null, "1");

# add another task, but this one to run in the background
$task= $gmc->addTaskBackground("reverse", "!dlroW olleH", null, "2");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}

echo "DONE\n";

function reverse_status($task)
{
    echo "STATUS: " . $task->unique() . ", " . $task->jobHandle() . " - " . $task->taskNumerator() .
         "/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>
<?php

# The worker script

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

Worker output for two workers running:

Received job: H:foo.local:65
Workload: !dlroW olleH (12)
1/12 complete
Received job: H:foo.local:66
Workload: Hello World! (12)
1/12 complete
2/12 complete
2/12 complete
3/12 complete
3/12 complete
4/12 complete
4/12 complete
5/12 complete
5/12 complete
6/12 complete
6/12 complete
7/12 complete
7/12 complete
8/12 complete
8/12 complete
9/12 complete
9/12 complete
10/12 complete
10/12 complete
11/12 complete
11/12 complete
12/12 complete
12/12 complete
Result: !dlroW olleH
Result: Hello World!

Client output:

STATUS: 1, H:foo.local:66 - 1/12
STATUS: 1, H:foo.local:66 - 2/12
STATUS: 1, H:foo.local:66 - 3/12
STATUS: 1, H:foo.local:66 - 4/12
STATUS: 1, H:foo.local:66 - 5/12
STATUS: 1, H:foo.local:66 - 6/12
STATUS: 1, H:foo.local:66 - 7/12
STATUS: 1, H:foo.local:66 - 8/12
STATUS: 1, H:foo.local:66 - 9/12
STATUS: 1, H:foo.local:66 - 10/12
STATUS: 1, H:foo.local:66 - 11/12
STATUS: 1, H:foo.local:66 - 12/12
COMPLETE: 1, !dlroW olleH
DONE

Zobacz też:

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

GearmanClient::addTask
GearmanClient::addTaskHigh
GearmanClient


Add a high priority task to run in parallel

GearmanClient::addTaskBackground
GearmanClient::addTaskHighBackground
GearmanClient
PHP Manual

GearmanClient::addTaskHigh

(PECL gearman >= 0.5.0)

GearmanClient::addTaskHigh — Add a high priority task to run in parallel

Opis

public GearmanTask GearmanClient::addTaskHigh ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a high priority task to be run in parallel with other tasks. Call this method for all the high priority tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Zwracane wartości

A GearmanTask object or FALSE if the task could not be added.

Przykłady

Przykład #1 A high priority task along with two normal tasks

A high priority task is included among two other tasks. A single worker is available, so that tasks are run one at a time, with the high priority task run first.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set the callback for when the job is complete
$gmc->setCompleteCallback("reverse_complete");

# add tasks, one of which is high priority
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
$task= $gmc->addTaskHigh("reverse", "!dlroW olleH", null, "2");
$task= $gmc->addTask("reverse", "Hello World!", null, "3");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}
echo "DONE\n";

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

COMPLETE: 2, Hello World!
COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
DONE

Zobacz też:

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

GearmanClient::addTaskBackground
GearmanClient::addTaskHighBackground
GearmanClient


Add a high priority background task to be run in parallel

GearmanClient::addTaskHigh
GearmanClient::addTaskLow
GearmanClient
PHP Manual

GearmanClient::addTaskHighBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel

Opis

public GearmanTask GearmanClient::addTaskHighBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a high priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Zwracane wartości

A GearmanTask object or FALSE if the task could not be added.

Zobacz też:

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

GearmanClient::addTaskHigh
GearmanClient::addTaskLow
GearmanClient


Add a low priority task to run in parallel

GearmanClient::addTaskHighBackground
GearmanClient::addTaskLowBackground
GearmanClient
PHP Manual

GearmanClient::addTaskLow

(PECL gearman >= 0.5.0)

GearmanClient::addTaskLow — Add a low priority task to run in parallel

Opis

public GearmanTask GearmanClient::addTaskLow ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a low priority will be selected from the queue after those of normal or low priority.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Zwracane wartości

A GearmanTask object or FALSE if the task could not be added.

Przykłady

Przykład #1 A low priority task along with two normal tasks

A low priority task is included among two other tasks. A single worker is available, so that tasks are run one at a time, with the low priority task run last.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set the callback for when the job is complete
$gmc->setCompleteCallback("reverse_complete");

# add tasks, one of which is low priority
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
$task= $gmc->addTaskLow("reverse", "!dlroW olleH", null, "2");
$task= $gmc->addTask("reverse", "Hello World!", null, "3");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}
echo "DONE\n";

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
COMPLETE: 2, Hello World!
DONE

Zobacz też:

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

GearmanClient::addTaskHighBackground
GearmanClient::addTaskLowBackground
GearmanClient


Add a low priority background task to be run in parallel

GearmanClient::addTaskLow
GearmanClient::addTaskStatus
GearmanClient
PHP Manual

GearmanClient::addTaskLowBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel

Opis

public GearmanTask GearmanClient::addTaskLowBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] )

Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a low priority will be selected from the queue after those of normal or high priority.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Zwracane wartości

A GearmanTask object or FALSE if the task could not be added.

Zobacz też:

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

GearmanClient::addTaskLow
GearmanClient::addTaskStatus
GearmanClient


Add a task to get status

GearmanClient::addTaskLowBackground
GearmanClient::clearCallbacks
GearmanClient
PHP Manual

GearmanClient::addTaskStatus

(PECL gearman >= 0.5.0)

GearmanClient::addTaskStatus — Add a task to get status

Opis

public GearmanTask GearmanClient::addTaskStatus ( string $job_handle [, string &$context ] )

Used to request status information from the Gearman server, which will call the specified status callback (set using GearmanClient::setStatusCallback()).

Parametry

job_handle

The job handle for the task to get status for

context

Data to be passed to the status callback, generally a reference to an array or object

Zwracane wartości

A GearmanTask object.

Przykłady

Przykład #1 Monitor completion of multiple background tasks

An artificial delay is introduced in the worker in this example to simulate a long running process. There is only one worker running for this example.

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* start some background jobs and save the handles */
$handles = array();
$handles[0] = $gmclient->doBackground("reverse", "Hello World!");
$handles[1] = $gmclient->doBackground("reverse", "!dlroW olleH");

$gmclient->setStatusCallback("reverse_status");

/* Poll the server to see when those background jobs finish; */
/* a better method would be to use event callbacks */
do
{
   /* Use the context variable to track how many tasks have completed */
   $done = 0;
   $gmclient->addTaskStatus($handles[0], &$done);
   $gmclient->addTaskStatus($handles[1], &$done);
   $gmclient->runTasks();
   echo "Done: $done\n";
   sleep(1);
}
while ($done != 2);

function reverse_status($task, $done)
{
   if (!$task->isKnown())
      $done++;
}

?>

Powyższy przykład wyświetli coś podobnego do:

Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 2

Zobacz też:

  • GearmanClient::setStatusCallback() - Set a callback for collecting task status

GearmanClient::addTaskLowBackground
GearmanClient::clearCallbacks
GearmanClient


Clear all task callback functions

GearmanClient::addTaskStatus
GearmanClient::clone
GearmanClient
PHP Manual

GearmanClient::clearCallbacks

(PECL gearman >= 0.5.0)

GearmanClient::clearCallbacks — Clear all task callback functions

Opis

public bool GearmanClient::clearCallbacks ( void )

Clears all the task callback functions that have previously been set.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Always returns TRUE.

Zobacz też:

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::addTaskStatus
GearmanClient::clone
GearmanClient


Create a copy of a GearmanClient object

GearmanClient::clearCallbacks
GearmanClient::__construct
GearmanClient
PHP Manual

GearmanClient::clone

(PECL gearman >= 0.5.0)

GearmanClient::clone — Create a copy of a GearmanClient object

Opis

public GearmanClient GearmanClient::clone ( void )

Creates a copy of a GearmanClient object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A GearmanClient on success, FALSE on failure.

GearmanClient::clearCallbacks
GearmanClient::__construct
GearmanClient


Create a GearmanClient instance

GearmanClient::clone
GearmanClient::context
GearmanClient
PHP Manual

GearmanClient::__construct

(PECL gearman >= 0.5.0)

GearmanClient::__construct — Create a GearmanClient instance

Opis

public GearmanClient::__construct ( void )

Creates a GearmanClient instance representing a client that connects to the job server and submits tasks to complete.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A GearmanClient object.

Zobacz też:

  • GearmanClient::clone() - Create a copy of a GearmanClient object

GearmanClient::clone
GearmanClient::context
GearmanClient


Get the application context

GearmanClient::__construct
GearmanClient::data
GearmanClient
PHP Manual

GearmanClient::context

(PECL gearman >= 0.6.0)

GearmanClient::context — Get the application context

Opis

public string GearmanClient::context ( void )

Get the application context previously set with GearmanClient::setContext().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The same context data structure set with GearmanClient::setContext()

Zobacz też:

  • GearmanClient::setContext() - Set application context

GearmanClient::__construct
GearmanClient::data
GearmanClient


Get the application data (deprecated)

GearmanClient::context
GearmanClient::do
GearmanClient
PHP Manual

GearmanClient::data

(PECL gearman <= 0.5.0)

GearmanClient::data — Get the application data (deprecated)

Opis

public string GearmanClient::data ( void )

Get the application data previously set with GearmanClient::setData().

Informacja:

This method was replaced by GearmanClient::setContext() in the 0.6.0 release of the Gearman extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The same string data set with GearmanClient::setData()

Zobacz też:

  • GearmanClient::setData() - Set application data (deprecated)

GearmanClient::context
GearmanClient::do
GearmanClient


Run a single task and return a result [deprecated]

GearmanClient::data
GearmanClient::doBackground
GearmanClient
PHP Manual

GearmanClient::do

(PECL gearman >= 0.5.0)

GearmanClient::do — Run a single task and return a result [deprecated]

Opis

public string GearmanClient::do ( string $function_name , string $workload [, string $unique ] )

The GearmanClient::do() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::doNormal().

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Zwracane wartości

A string representing the results of running a task.

Przykłady

Przykład #1 Simple job submission with immediate return

<?php

# Client code

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

$result = $gmclient->doNormal("reverse", "Hello!");

echo "Success: $result\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

Powyższy przykład wyświetli coś podobnego do:

Starting
Sending job
Success: !olleH

Przykład #2 Submitting a job and retrieving incremental status

A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to GearmanClient::do() produces status information on the running job.

<?php

# Client code

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");
  # Check for various return packets and errors.

  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      echo "Error: " . $gmclient->error() . "\n";
      echo "Errno: " . $gmclient->getErrno() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>
<?php

# Worker code

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " + $x + 1 . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

Powyższy przykład wyświetli coś podobnego do:

Worker output:

Starting
Waiting for job...
Received job: H:foo.local:106
Workload: Hello! (6)
1/6 complete
2/6 complete
3/6 complete
4/6 complete
5/6 complete
6/6 complete
Result: !olleH

Client output:

Starting
Sending job
Status: 1/6 complete
Data: H
Status: 2/6 complete
Data: e
Status: 3/6 complete
Data: l
Status: 4/6 complete
Data: l
Status: 5/6 complete
Data: o
Status: 6/6 complete
Data: !
Success: !olleH

Zobacz też:

  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

GearmanClient::data
GearmanClient::doBackground
GearmanClient


Run a task in the background

GearmanClient::do
GearmanClient::doHigh
GearmanClient
PHP Manual

GearmanClient::doBackground

(PECL gearman >= 0.5.0)

GearmanClient::doBackground — Run a task in the background

Opis

public string GearmanClient::doBackground ( string $function_name , string $workload [, string $unique ] )

Runs a task in the background, returning a job handle which can be used to get the status of the running task.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Zwracane wartości

The job handle for the submitted task.

Przykłady

Przykład #1 Submit and monitor a background job

The worker in this example has an artificial delay introduced to mimic a long running job. The client script periodically checks the status of the running job.

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* run reverse client */
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

$done = false;
do
{
   sleep(3);
   $stat = $gmclient->jobStatus($job_handle);
   if (!$stat[0]) // the job is known so it is not done
      $done = true;
   echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denomintor: " . $stat[3] . "\n";
}
while(!$done);

echo "done!\n";

?>

Powyższy przykład wyświetli coś podobnego do:

Running: true, numerator: 3, denomintor: 14
Running: true, numerator: 6, denomintor: 14
Running: true, numerator: 9, denomintor: 14
Running: true, numerator: 12, denomintor: 14
Running: false, numerator: 0, denomintor: 0
done!

Zobacz też:

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

GearmanClient::do
GearmanClient::doHigh
GearmanClient


Run a single high priority task

GearmanClient::doBackground
GearmanClient::doHighBackground
GearmanClient
PHP Manual

GearmanClient::doHigh

(PECL gearman >= 0.5.0)

GearmanClient::doHigh — Run a single high priority task

Opis

public string GearmanClient::doHigh ( string $function_name , string $workload [, string $unique ] )

Runs a single high priority task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result. High priority tasks will get precedence over normal and low priority tasks in the job queue.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Zwracane wartości

A string representing the results of running a task.

Zobacz też:

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

GearmanClient::doBackground
GearmanClient::doHighBackground
GearmanClient


Run a high priority task in the background

GearmanClient::doHigh
GearmanClient::doJobHandle
GearmanClient
PHP Manual

GearmanClient::doHighBackground

(PECL gearman >= 0.5.0)

GearmanClient::doHighBackground — Run a high priority task in the background

Opis

public string GearmanClient::doHighBackground ( string $function_name , string $workload [, string $unique ] )

Runs a high priority task in the background, returning a job handle which can be used to get the status of the running task. High priority tasks take precedence over normal and low priority tasks in the job queue.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Zwracane wartości

The job handle for the submitted task.

Zobacz też:

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

GearmanClient::doHigh
GearmanClient::doJobHandle
GearmanClient


Get the job handle for the running task

GearmanClient::doHighBackground
GearmanClient::doLow
GearmanClient
PHP Manual

GearmanClient::doJobHandle

(PECL gearman >= 0.5.0)

GearmanClient::doJobHandle — Get the job handle for the running task

Opis

public string GearmanClient::doJobHandle ( void )

Gets that job handle for a running task. This should be used between repeated GearmanClient::doNormal() calls. The job handle can then be used to get information on the task.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The job handle for the running task.

Zobacz też:

  • GearmanClient::jobStatus() - Get the status of a background job

GearmanClient::doHighBackground
GearmanClient::doLow
GearmanClient


Run a single low priority task

GearmanClient::doJobHandle
GearmanClient::doLowBackground
GearmanClient
PHP Manual

GearmanClient::doLow

(PECL gearman >= 0.5.0)

GearmanClient::doLow — Run a single low priority task

Opis

public string GearmanClient::doLow ( string $function_name , string $workload [, string $unique ] )

Runs a single low priority task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result. Normal and high priority tasks will get precedence over low priority tasks in the job queue.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Zwracane wartości

A string representing the results of running a task.

Zobacz też:

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

GearmanClient::doJobHandle
GearmanClient::doLowBackground
GearmanClient


Run a low priority task in the background

GearmanClient::doLow
GearmanClient::doNormal
GearmanClient
PHP Manual

GearmanClient::doLowBackground

(PECL gearman >= 0.5.0)

GearmanClient::doLowBackground — Run a low priority task in the background

Opis

public string GearmanClient::doLowBackground ( string $function_name , string $workload [, string $unique ] )

Runs a low priority task in the background, returning a job handle which can be used to get the status of the running task. Normal and high priority tasks take precedence over low priority tasks in the job queue.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Zwracane wartości

The job handle for the submitted task.

Zobacz też:

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background

GearmanClient::doLow
GearmanClient::doNormal
GearmanClient


Run a single task and return a result

GearmanClient::doLowBackground
GearmanClient::doStatus
GearmanClient
PHP Manual

GearmanClient::doNormal

(No version information available, might only be in SVN)

GearmanClient::doNormal — Run a single task and return a result

Opis

public string GearmanClient::doNormal ( string $function_name , string $workload [, string $unique ] )

Runs a single task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result.

Parametry

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Zwracane wartości

A string representing the results of running a task.

Przykłady

Przykład #1 Simple job submission with immediate return

<?php

?>
<?php

# Client code

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

$result = $gmclient->doNormal("reverse", "Hello!");

echo "Success: $result\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

Powyższy przykład wyświetli coś podobnego do:

Starting
Sending job
Success: !olleH

Przykład #2 Submitting a job and retrieving incremental status

A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to GearmanClient::doNormal() produces status information on the running job.

<?php

# Client code

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");
  # Check for various return packets and errors.

  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      echo "Error: " . $gmclient->error() . "\n";
      echo "Errno: " . $gmclient->getErrno() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>
<?php

# Worker code

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " + $x + 1 . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

Powyższy przykład wyświetli coś podobnego do:

Worker output:

Starting
Waiting for job...
Received job: H:foo.local:106
Workload: Hello! (6)
1/6 complete
2/6 complete
3/6 complete
4/6 complete
5/6 complete
6/6 complete
Result: !olleH

Client output:

Starting
Sending job
Status: 1/6 complete
Data: H
Status: 2/6 complete
Data: e
Status: 3/6 complete
Data: l
Status: 4/6 complete
Data: l
Status: 5/6 complete
Data: o
Status: 6/6 complete
Data: !
Success: !olleH

Zobacz też:

  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

GearmanClient::doLowBackground
GearmanClient::doStatus
GearmanClient


Get the status for the running task

GearmanClient::doNormal
GearmanClient::echo
GearmanClient
PHP Manual

GearmanClient::doStatus

(PECL gearman >= 0.5.0)

GearmanClient::doStatus — Get the status for the running task

Opis

public array GearmanClient::doStatus ( void )

Returns the status for the running task. This should be used between repeated GearmanClient::doNormal() calls.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array representing the percentage completion given as a fraction, with the first element the numerator and the second element the denomintor.

Przykłady

Przykład #1 Get the status of a long running job

The worker in this example has an artificial delay added during processing of the string to be reversed. After each delay it calls GearmanJob::status() which the client then picks up.

<?php

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");

  # Check for various return packets and errors.
  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      break;
    case GEARMAN_WORK_STATUS:
      # get the current job status
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>

Powyższy przykład wyświetli coś podobnego do:

Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH

Zobacz też:

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanJob::status() - Send status (deprecated)

GearmanClient::doNormal
GearmanClient::echo
GearmanClient


Send data to all job servers to see if they echo it back [deprecated]

GearmanClient::doStatus
GearmanClient::error
GearmanClient
PHP Manual

GearmanClient::echo

(PECL gearman >= 0.5.0)

GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]

Opis

public bool GearmanClient::echo ( string $workload )

The GearmanClient::echo() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::ping().

Parametry

workload

Some arbitrary serialized data to be echo back

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

GearmanClient::doStatus
GearmanClient::error
GearmanClient


Returns an error string for the last error encountered.

GearmanClient::echo
GearmanClient::getErrno
GearmanClient
PHP Manual

GearmanClient::error

(PECL gearman >= 0.5.0)

GearmanClient::error — Returns an error string for the last error encountered.

Opis

public string GearmanClient::error ( void )

Returns an error string for the last error encountered.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A human readable error string.

Zobacz też:

  • GearmanClient::getErrno() - Get an errno value

GearmanClient::echo
GearmanClient::getErrno
GearmanClient


Get an errno value

GearmanClient::error
GearmanClient::jobStatus
GearmanClient
PHP Manual

GearmanClient::getErrno

(PECL gearman >= 0.5.0)

GearmanClient::getErrno — Get an errno value

Opis

public int GearmanClient::getErrno ( void )

Value of errno in the case of a GEARMAN_ERRNO return value.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A valid Gearman errno.

Zobacz też:

  • GearmanClient::error() - Returns an error string for the last error encountered.

GearmanClient::error
GearmanClient::jobStatus
GearmanClient


Get the status of a background job

GearmanClient::getErrno
GearmanClient::ping
GearmanClient
PHP Manual

GearmanClient::jobStatus

gearman_job_status

(PECL gearman >= 0.5.0)

GearmanClient::jobStatus -- gearman_job_status — Get the status of a background job

Opis

Styl obiektowy (method):

public array GearmanClient::jobStatus ( string $job_handle )

Gets the status for a background job given a job handle. The status information will specify whether the job is known, whether the job is currently running, and the percentage completion.

Parametry

job_handle

The job handle assigned by the Gearman server

Zwracane wartości

An array containing status information for the job corresponding to the supplied job handle. The first array element is a boolean indicating whether the job is even known, the second is a boolean indicating whether the job is still running, and the third and fourth elements correspond to the numerator and denominator of the fractional completion percentage, respectively.

Przykłady

Przykład #1 Monitor the status of a long running background job

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* run reverse client */
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

$done = false;
do
{
   sleep(3);
   $stat = $gmclient->jobStatus($job_handle);
   if (!$stat[0]) // the job is known so it is not done
      $done = true;
   echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denomintor: " . $stat[3] . "\n";
}
while(!$done);

echo "done!\n";

?>

Powyższy przykład wyświetli coś podobnego do:

Running: true, numerator: 3, denomintor: 14
Running: true, numerator: 6, denomintor: 14
Running: true, numerator: 9, denomintor: 14
Running: true, numerator: 12, denomintor: 14
Running: false, numerator: 0, denomintor: 0
done!

Zobacz też:

  • GearmanClient::doStatus() - Get the status for the running task

GearmanClient::getErrno
GearmanClient::ping
GearmanClient


Send data to all job servers to see if they echo it back

GearmanClient::jobStatus
GearmanClient::removeOptions
GearmanClient
PHP Manual

GearmanClient::ping

(No version information available, might only be in SVN)

GearmanClient::ping — Send data to all job servers to see if they echo it back

Opis

public bool GearmanClient::ping ( string $workload )

Sends some arbitrary data to all job servers to see if they echo it back. The data sent is not used or processed in any other way. Primarily used for testing and debugging.

Parametry

workload

Some arbitrary serialized data to be echo back

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

GearmanClient::jobStatus
GearmanClient::removeOptions
GearmanClient


Remove client options

GearmanClient::ping
GearmanClient::returnCode
GearmanClient
PHP Manual

GearmanClient::removeOptions

(PECL gearman >= 0.6.0)

GearmanClient::removeOptions — Remove client options

Opis

public bool GearmanClient::removeOptions ( int $options )

Removes (unsets) one or more options.

Parametry

options

The options to be removed (unset)

Zwracane wartości

Always returns TRUE.

GearmanClient::ping
GearmanClient::returnCode
GearmanClient


Get the last Gearman return code

GearmanClient::removeOptions
GearmanClient::runTasks
GearmanClient
PHP Manual

GearmanClient::returnCode

(PECL gearman >= 0.5.0)

GearmanClient::returnCode — Get the last Gearman return code

Opis

public int GearmanClient::returnCode ( void )

Returns the last Gearman return code.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A valid Gearman return code.

GearmanClient::removeOptions
GearmanClient::runTasks
GearmanClient


Run a list of tasks in parallel

GearmanClient::returnCode
GearmanClient::setClientCallback
GearmanClient
PHP Manual

GearmanClient::runTasks

(PECL gearman >= 0.5.0)

GearmanClient::runTasks — Run a list of tasks in parallel

Opis

public bool GearmanClient::runTasks ( void )

For a set of tasks previously added with GearmanClient::addTask(), GearmanClient::addTaskHigh(), GearmanClient::addTaskLow(), GearmanClient::addTaskBackground(), GearmanClient::addTaskHighBackground(), or GearmanClient::addTaskLowBackground(), this call starts running the tasks in parallel.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::addTask() - Add a task to be run in parallel

GearmanClient::returnCode
GearmanClient::setClientCallback
GearmanClient


Callback function when there is a data packet for a task (deprecated)

GearmanClient::runTasks
GearmanClient::setCompleteCallback
GearmanClient
PHP Manual

GearmanClient::setClientCallback

(PECL gearman <= 0.5.0)

GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)

Opis

public void GearmanClient::setClientCallback ( callback $callback )

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Informacja:

This method has been replaced by GearmanClient::setDataCallback() in the 0.6.0 release of the Gearman extension.

Parametry

callback

A function or method to call

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::runTasks
GearmanClient::setCompleteCallback
GearmanClient


Set a function to be called on task completion

GearmanClient::setClientCallback
GearmanClient::setContext
GearmanClient
PHP Manual

GearmanClient::setCompleteCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCompleteCallback — Set a function to be called on task completion

Opis

public bool GearmanClient::setCompleteCallback ( callback $callback )

Use to set a function to be called when a task is completed. The callback function should accept a single argument, a GearmanTask oject.

Parametry

callback

A function to be called

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::setClientCallback
GearmanClient::setContext
GearmanClient


Set application context

GearmanClient::setCompleteCallback
GearmanClient::setCreatedCallback
GearmanClient
PHP Manual

GearmanClient::setContext

(PECL gearman >= 0.6.0)

GearmanClient::setContext — Set application context

Opis

public bool GearmanClient::setContext ( string $context )

Sets an arbitrary string to provide application context that can later be retrieved by GearmanClient::context().

Parametry

context

Arbitrary context data

Zwracane wartości

Always returns TRUE.

Zobacz też:

  • GearmanClient::context() - Get the application context

GearmanClient::setCompleteCallback
GearmanClient::setCreatedCallback
GearmanClient


Set a callback for when a task is queued

GearmanClient::setContext
GearmanClient::setData
GearmanClient
PHP Manual

GearmanClient::setCreatedCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCreatedCallback — Set a callback for when a task is queued

Opis

public bool GearmanClient::setCreatedCallback ( string $callback )

Sets a function to be called when a task is received and queued by the Gearman job server. The callback should accept a single argument, a GearmanClient oject.

Parametry

callback

A function to call

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::setContext
GearmanClient::setData
GearmanClient


Set application data (deprecated)

GearmanClient::setCreatedCallback
GearmanClient::setDataCallback
GearmanClient
PHP Manual

GearmanClient::setData

(PECL gearman <= 0.5.0)

GearmanClient::setData — Set application data (deprecated)

Opis

public bool GearmanClient::setData ( string $data )

Sets some arbitrary application data that can later be retrieved by GearmanClient::data().

Informacja:

This method has been replaced by GearmanCient::setContext() in the 0.6.0 release of the Gearman extension.

Parametry

data

Zwracane wartości

Always returns TRUE.

Zobacz też:

  • GearmanClient::data() - Get the application data (deprecated)

GearmanClient::setCreatedCallback
GearmanClient::setDataCallback
GearmanClient


Callback function when there is a data packet for a task

GearmanClient::setData
GearmanClient::setExceptionCallback
GearmanClient
PHP Manual

GearmanClient::setDataCallback

(PECL gearman >= 0.6.0)

GearmanClient::setDataCallback — Callback function when there is a data packet for a task

Opis

public bool GearmanClient::setDataCallback ( callback $callback )

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Parametry

callback

A function or method to call

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::setData
GearmanClient::setExceptionCallback
GearmanClient


Set a callback for worker exceptions

GearmanClient::setDataCallback
GearmanClient::setFailCallback
GearmanClient
PHP Manual

GearmanClient::setExceptionCallback

(PECL gearman >= 0.5.0)

GearmanClient::setExceptionCallback — Set a callback for worker exceptions

Opis

public bool GearmanClient::setExceptionCallback ( callback $callback )

Specifies a function to call when a worker for a task sends an exception.

Parametry

callback

Function to call when the worker throws an exception

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::setDataCallback
GearmanClient::setFailCallback
GearmanClient


Set callback for job failure

GearmanClient::setExceptionCallback
GearmanClient::setOptions
GearmanClient
PHP Manual

GearmanClient::setFailCallback

(PECL gearman >= 0.5.0)

GearmanClient::setFailCallback — Set callback for job failure

Opis

public bool GearmanClient::setFailCallback ( callback $callback )

Sets the callback function to be used when a task does not complete successfully. The function should accept a single argument, a GearmanTask object.

Parametry

callback

A function to call

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::setExceptionCallback
GearmanClient::setOptions
GearmanClient


Set client options

GearmanClient::setFailCallback
GearmanClient::setStatusCallback
GearmanClient
PHP Manual

GearmanClient::setOptions

(PECL gearman >= 0.5.0)

GearmanClient::setOptions — Set client options

Opis

public bool GearmanClient::setOptions ( int $options )

Sets one or more client options.

Parametry

options

The options to be set

Zwracane wartości

Always returns TRUE.

GearmanClient::setFailCallback
GearmanClient::setStatusCallback
GearmanClient


Set a callback for collecting task status

GearmanClient::setOptions
GearmanClient::setTimeout
GearmanClient
PHP Manual

GearmanClient::setStatusCallback

(PECL gearman >= 0.5.0)

GearmanClient::setStatusCallback — Set a callback for collecting task status

Opis

public bool GearmanClient::setStatusCallback ( callback $callback )

Sets a callback function used for getting updated status information from a worker. The function should accept a single argument, a GearmanTask object.

Parametry

callback

A function to call

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::setOptions
GearmanClient::setTimeout
GearmanClient


Set socket I/O activity timeout

GearmanClient::setStatusCallback
GearmanClient::setWarningCallback
GearmanClient
PHP Manual

GearmanClient::setTimeout

(PECL gearman >= 0.6.0)

GearmanClient::setTimeout — Set socket I/O activity timeout

Opis

public bool GearmanClient::setTimeout ( int $timeout )

Sets the timeout for socket I/O activity.

Parametry

timeout

An interval of time in milliseconds

Zwracane wartości

Always returns TRUE.

GearmanClient::setStatusCallback
GearmanClient::setWarningCallback
GearmanClient


Set a callback for worker warnings

GearmanClient::setTimeout
GearmanClient::setWorkloadCallback
GearmanClient
PHP Manual

GearmanClient::setWarningCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWarningCallback — Set a callback for worker warnings

Opis

public bool GearmanClient::setWarningCallback ( callback $callback )

Sets a function to be called when a worker sends a warning. The callback should accept a single argument, a GearmanTask object.

Parametry

callback

A function to call

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

GearmanClient::setTimeout
GearmanClient::setWorkloadCallback
GearmanClient


Set a callback for accepting incremental data updates

GearmanClient::setWarningCallback
GearmanClient::timeout
GearmanClient
PHP Manual

GearmanClient::setWorkloadCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates

Opis

public bool GearmanClient::setWorkloadCallback ( callback $callback )

Sets a function to be called when a worker needs to send back data prior to job completion. A worker can do this when it needs to send updates, send partial results, or flush data during long running jobs. The callback should accept a single argument, a GearmanTask object.

Parametry

callback

A function to call

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings

GearmanClient::setWarningCallback
GearmanClient::timeout
GearmanClient


Get current socket I/O activity timeout value

GearmanClient::setWorkloadCallback
GearmanJob
GearmanClient
PHP Manual

GearmanClient::timeout

(PECL gearman >= 0.6.0)

GearmanClient::timeout — Get current socket I/O activity timeout value

Opis

public int GearmanClient::timeout ( void )

Returns the timeout in milliseconds to wait for I/O activity.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Timeout in milliseconds to wait for I/O activity. A negative value means an infinite timeout.

Zobacz też:

  • GearmanClient::setTimeout() - Set socket I/O activity timeout

GearmanClient::setWorkloadCallback
GearmanJob
GearmanClient


The GearmanJob class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

GearmanJob {
/* Metody */
public bool complete ( string $result )
public __construct ( void )
public bool data ( string $data )
public bool exception ( string $exception )
public bool fail ( void )
public string functionName ( void )
public string handle ( void )
public int returnCode ( void )
public bool sendComplete ( string $result )
public bool sendData ( string $data )
public bool sendException ( string $exception )
public bool sendFail ( void )
public bool sendStatus ( int $numerator , int $denominator )
public bool sendWarning ( string $warning )
public bool setReturn ( int $gearman_return_t )
public bool status ( int $numerator , int $denominator )
public string unique ( void )
public bool warning ( string $warning )
public string workload ( void )
public int workloadSize ( void )
}

Spis treści

  • GearmanJob::complete — Send the result and complete status (deprecated)
  • GearmanJob::__construct — Create a GearmanJob instance
  • GearmanJob::data — Send data for a running job (deprecated)
  • GearmanJob::exception — Send exception for running job (deprecated)
  • GearmanJob::fail — Send fail status (deprecated)
  • GearmanJob::functionName — Get function name
  • GearmanJob::handle — Get the job handle
  • GearmanJob::returnCode — Get last return code
  • GearmanJob::sendComplete — Send the result and complete status
  • GearmanJob::sendData — Send data for a running job
  • GearmanJob::sendException — Send exception for running job (exception)
  • GearmanJob::sendFail — Send fail status
  • GearmanJob::sendStatus — Send status
  • GearmanJob::sendWarning — Send a warning
  • GearmanJob::setReturn — Set a return value
  • GearmanJob::status — Send status (deprecated)
  • GearmanJob::unique — Get the unique identifier
  • GearmanJob::warning — Send a warning (deprecated)
  • GearmanJob::workload — Get workload
  • GearmanJob::workloadSize — Get size of work load
GearmanClient::timeout
GearmanJob::complete
Gearman


Send the result and complete status (deprecated)

GearmanJob
GearmanJob::__construct
GearmanJob
PHP Manual

GearmanJob::complete

(PECL gearman <= 0.5.0)

GearmanJob::complete — Send the result and complete status (deprecated)

Opis

public bool GearmanJob::complete ( string $result )

Sends result data and the complete status update for this job.

Informacja:

This method has been replaced by GearmanJob::sendComplete() in the 0.6.0 release of the Gearman extension.

Parametry

result

Serialized result data.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::sendFail() - Send fail status
  • GearmanJob::setReturn() - Set a return value

GearmanJob
GearmanJob::__construct
GearmanJob


Create a GearmanJob instance

GearmanJob::complete
GearmanJob::data
GearmanJob
PHP Manual

GearmanJob::__construct

(PECL gearman >= 0.5.0)

GearmanJob::__construct — Create a GearmanJob instance

Opis

public GearmanJob::__construct ( void )

Creates a GearmanJob instance representing a job the worker is to complete.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A GearmanJob object.

GearmanJob::complete
GearmanJob::data
GearmanJob


Send data for a running job (deprecated)

GearmanJob::__construct
GearmanJob::exception
GearmanJob
PHP Manual

GearmanJob::data

(PECL gearman <= 0.5.0)

GearmanJob::data — Send data for a running job (deprecated)

Opis

public bool GearmanJob::data ( string $data )

Sends data to the job server (and any listening clients) for this job.

Informacja:

This method has been replaced by GearmanJob::sendData() in the 0.6.0 release of the Gearman extension.

Parametry

data

Arbitrary serialized data.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::workload() - Get workload
  • GearmanTask::data() - Get data returned for a task

GearmanJob::__construct
GearmanJob::exception
GearmanJob


Send exception for running job (deprecated)

GearmanJob::data
GearmanJob::fail
GearmanJob
PHP Manual

GearmanJob::exception

(PECL gearman <= 0.5.0)

GearmanJob::exception — Send exception for running job (deprecated)

Opis

public bool GearmanJob::exception ( string $exception )

Sends the supplied exception when this job is running.

Informacja:

This method has been replaced by GearmanJob::sendException() in the 0.6.0 release of the Gearman extension.

Parametry

exception

An exception description.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

GearmanJob::data
GearmanJob::fail
GearmanJob


Send fail status (deprecated)

GearmanJob::exception
GearmanJob::functionName
GearmanJob
PHP Manual

GearmanJob::fail

(PECL gearman <= 0.5.0)

GearmanJob::fail — Send fail status (deprecated)

Opis

public bool GearmanJob::fail ( void )

Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception).

Informacja:

This method has been replaced by GearmanJob::sendFail() in the 0.6.0 release of the Gearman extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

GearmanJob::exception
GearmanJob::functionName
GearmanJob


Get function name

GearmanJob::fail
GearmanJob::handle
GearmanJob
PHP Manual

GearmanJob::functionName

(PECL gearman >= 0.5.0)

GearmanJob::functionName — Get function name

Opis

public string GearmanJob::functionName ( void )

Returns the function name for this job. This is the function the work will execute to perform the job.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The name of a function.

Zobacz też:

  • GearmanTask::function() - Get associated function name (deprecated)

GearmanJob::fail
GearmanJob::handle
GearmanJob


Get the job handle

GearmanJob::functionName
GearmanJob::returnCode
GearmanJob
PHP Manual

GearmanJob::handle

(PECL gearman >= 0.5.0)

GearmanJob::handle — Get the job handle

Opis

public string GearmanJob::handle ( void )

Returns the opaque job handle assigned by the job server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An opaque job handle.

Zobacz też:

  • GearmanTask::jobHandle() - Get the job handle

GearmanJob::functionName
GearmanJob::returnCode
GearmanJob


Get last return code

GearmanJob::handle
GearmanJob::sendComplete
GearmanJob
PHP Manual

GearmanJob::returnCode

(PECL gearman >= 0.5.0)

GearmanJob::returnCode — Get last return code

Opis

public int GearmanJob::returnCode ( void )

Returns the last return code issued by the job server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A valid Gearman return code.

Zobacz też:

  • GearmanTask::returnCode() - Get the last return code

GearmanJob::handle
GearmanJob::sendComplete
GearmanJob


Send the result and complete status

GearmanJob::returnCode
GearmanJob::sendData
GearmanJob
PHP Manual

GearmanJob::sendComplete

(PECL gearman >= 0.6.0)

GearmanJob::sendComplete — Send the result and complete status

Opis

public bool GearmanJob::sendComplete ( string $result )

Sends result data and the complete status update for this job.

Parametry

result

Serialized result data.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::sendFail() - Send fail status
  • GearmanJob::setReturn() - Set a return value

GearmanJob::returnCode
GearmanJob::sendData
GearmanJob


Send data for a running job

GearmanJob::sendComplete
GearmanJob::sendException
GearmanJob
PHP Manual

GearmanJob::sendData

(PECL gearman >= 0.6.0)

GearmanJob::sendData — Send data for a running job

Opis

public bool GearmanJob::sendData ( string $data )

Sends data to the job server (and any listening clients) for this job.

Parametry

data

Arbitrary serialized data.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::workload() - Get workload
  • GearmanTask::data() - Get data returned for a task

GearmanJob::sendComplete
GearmanJob::sendException
GearmanJob


Send exception for running job (exception)

GearmanJob::sendData
GearmanJob::sendFail
GearmanJob
PHP Manual

GearmanJob::sendException

(PECL gearman >= 0.6.0)

GearmanJob::sendException — Send exception for running job (exception)

Opis

public bool GearmanJob::sendException ( string $exception )

Sends the supplied exception when this job is running.

Parametry

exception

An exception description.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

GearmanJob::sendData
GearmanJob::sendFail
GearmanJob


Send fail status

GearmanJob::sendException
GearmanJob::sendStatus
GearmanJob
PHP Manual

GearmanJob::sendFail

(PECL gearman >= 0.6.0)

GearmanJob::sendFail — Send fail status

Opis

public bool GearmanJob::sendFail ( void )

Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception).

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

GearmanJob::sendException
GearmanJob::sendStatus
GearmanJob


Send status

GearmanJob::sendFail
GearmanJob::sendWarning
GearmanJob
PHP Manual

GearmanJob::sendStatus

(PECL gearman >= 0.6.0)

GearmanJob::sendStatus — Send status

Opis

public bool GearmanJob::sendStatus ( int $numerator , int $denominator )

Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.

Parametry

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::jobStatus() - Get the status of a background job
  • GearmanTask::taskDenominator() - Get completion percentage denominator
  • GearmanTask::taskNumerator() - Get completion percentage numerator

GearmanJob::sendFail
GearmanJob::sendWarning
GearmanJob


Send a warning

GearmanJob::sendStatus
GearmanJob::setReturn
GearmanJob
PHP Manual

GearmanJob::sendWarning

(PECL gearman >= 0.6.0)

GearmanJob::sendWarning — Send a warning

Opis

public bool GearmanJob::sendWarning ( string $warning )

Sends a warning for this job while it is running.

Parametry

warning

A warning messages.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::sendComplete() - Send the result and complete status
  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::sendFail() - Send fail status

GearmanJob::sendStatus
GearmanJob::setReturn
GearmanJob


Set a return value

GearmanJob::sendWarning
GearmanJob::status
GearmanJob
PHP Manual

GearmanJob::setReturn

(PECL gearman >= 0.5.0)

GearmanJob::setReturn — Set a return value

Opis

public bool GearmanJob::setReturn ( int $gearman_return_t )

Sets the return value for this job, indicates how the job completed.

Parametry

gearman_return_t

A valid Gearman return value.

Zwracane wartości

Description...

GearmanJob::sendWarning
GearmanJob::status
GearmanJob


Send status (deprecated)

GearmanJob::setReturn
GearmanJob::unique
GearmanJob
PHP Manual

GearmanJob::status

(PECL gearman <= 0.5.0)

GearmanJob::status — Send status (deprecated)

Opis

public bool GearmanJob::status ( int $numerator , int $denominator )

Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.

Informacja:

This method has been replaced by GearmanJob::sendStatus() in the 0.6.0 release of the Gearman extenstion.

Parametry

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanClient::jobStatus() - Get the status of a background job
  • GearmanTask::taskDenominator() - Get completion percentage denominator
  • GearmanTask::taskNumerator() - Get completion percentage numerator

GearmanJob::setReturn
GearmanJob::unique
GearmanJob


Get the unique identifier

GearmanJob::status
GearmanJob::warning
GearmanJob
PHP Manual

GearmanJob::unique

(PECL gearman >= 0.5.0)

GearmanJob::unique — Get the unique identifier

Opis

public string GearmanJob::unique ( void )

Returns the unique identifiter for this job. The identifier is assigned by the client.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An opaque unique identifier.

Zobacz też:

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanTask::uuid() - Get the unique identifier for a task (deprecated)

GearmanJob::status
GearmanJob::warning
GearmanJob


Send a warning (deprecated)

GearmanJob::unique
GearmanJob::workload
GearmanJob
PHP Manual

GearmanJob::warning

(PECL gearman <= 0.5.0)

GearmanJob::warning — Send a warning (deprecated)

Opis

public bool GearmanJob::warning ( string $warning )

Sends a warning for this job while it is running.

Informacja:

This method has been replaced by GearmanJob::sendWarning() in the 0.6.0 release of the Gearman extension.

Parametry

warning

A warning messages.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • GearmanJob::sendComplete() - Send the result and complete status
  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::sendFail() - Send fail status

GearmanJob::unique
GearmanJob::workload
GearmanJob


Get workload

GearmanJob::warning
GearmanJob::workloadSize
GearmanJob
PHP Manual

GearmanJob::workload

(PECL gearman >= 0.5.0)

GearmanJob::workload — Get workload

Opis

public string GearmanJob::workload ( void )

Returns the workload for the job. This is serialized data that is to be processed by the worker.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Serialized data.

Zobacz też:

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanJob::workloadSize() - Get size of work load

GearmanJob::warning
GearmanJob::workloadSize
GearmanJob


Get size of work load

GearmanJob::workload
GearmanTask
GearmanJob
PHP Manual

GearmanJob::workloadSize

(PECL gearman >= 0.5.0)

GearmanJob::workloadSize — Get size of work load

Opis

public int GearmanJob::workloadSize ( void )

Returns the size of the job's work load (the data the worker is to process) in bytes.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The size in bytes.

Zobacz też:

  • GearmanJob::workload() - Get workload

GearmanJob::workload
GearmanTask
GearmanJob


The GearmanTask class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

GearmanTask {
/* Metody */
public __construct ( void )
public GearmanTask create ( void )
public string data ( void )
public int dataSize ( void )
public string function ( void )
public string functionName ( void )
public bool isKnown ( void )
public bool isRunning ( void )
public string jobHandle ( void )
public array recvData ( int $data_len )
public int returnCode ( void )
public int sendData ( string $data )
public int sendWorkload ( string $data )
public int taskDenominator ( void )
public int taskNumerator ( void )
public string unique ( void )
public string uuid ( void )
}

Spis treści

  • GearmanTask::__construct — Create a GearmanTask instance
  • GearmanTask::create — Create a task (deprecated)
  • GearmanTask::data — Get data returned for a task
  • GearmanTask::dataSize — Get the size of returned data
  • GearmanTask::function — Get associated function name (deprecated)
  • GearmanTask::functionName — Get associated function name
  • GearmanTask::isKnown — Determine if task is known
  • GearmanTask::isRunning — Test whether the task is currently running
  • GearmanTask::jobHandle — Get the job handle
  • GearmanTask::recvData — Read work or result data into a buffer for a task
  • GearmanTask::returnCode — Get the last return code
  • GearmanTask::sendData — Send data for a task (deprecated)
  • GearmanTask::sendWorkload — Send data for a task
  • GearmanTask::taskDenominator — Get completion percentage denominator
  • GearmanTask::taskNumerator — Get completion percentage numerator
  • GearmanTask::unique — Get the unique identifier for a task
  • GearmanTask::uuid — Get the unique identifier for a task (deprecated)
GearmanJob::workloadSize
GearmanTask::__construct
Gearman


Create a GearmanTask instance

GearmanTask
GearmanTask::create
GearmanTask
PHP Manual

GearmanTask::__construct

(PECL gearman >= 0.5.0)

GearmanTask::__construct — Create a GearmanTask instance

Opis

public GearmanTask::__construct ( void )

Creates a GearmanTask instance representing a task to be submitted to a job server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A GearmanTask object.

GearmanTask
GearmanTask::create
GearmanTask


Create a task (deprecated)

GearmanTask::__construct
GearmanTask::data
GearmanTask
PHP Manual

GearmanTask::create

(PECL gearman <= 0.5.0)

GearmanTask::create — Create a task (deprecated)

Opis

public GearmanTask GearmanTask::create ( void )

Returns a new GearmanTask object.

Informacja:

This method was removed in the 0.6.0 version of the Gearman extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A GearmanTask oject lub FALSE w przypadku niepowodzenia.

GearmanTask::__construct
GearmanTask::data
GearmanTask


Get data returned for a task

GearmanTask::create
GearmanTask::dataSize
GearmanTask
PHP Manual

GearmanTask::data

(PECL gearman >= 0.5.0)

GearmanTask::data — Get data returned for a task

Opis

public string GearmanTask::data ( void )

Returns data being returned for a task by a worker.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The serialized data, or FALSE if no data is present.

Zobacz też:

  • GearmanTask::dataSize() - Get the size of returned data

GearmanTask::create
GearmanTask::dataSize
GearmanTask


Get the size of returned data

GearmanTask::data
GearmanTask::function
GearmanTask
PHP Manual

GearmanTask::dataSize

(PECL gearman >= 0.5.0)

GearmanTask::dataSize — Get the size of returned data

Opis

public int GearmanTask::dataSize ( void )

Returns the size of the data being returned for a task.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The data size, or FALSE if there is no data.

Zobacz też:

  • GearmanTask::data() - Get data returned for a task

GearmanTask::data
GearmanTask::function
GearmanTask


Get associated function name (deprecated)

GearmanTask::dataSize
GearmanTask::functionName
GearmanTask
PHP Manual

GearmanTask::function

(PECL gearman <= 0.5.0)

GearmanTask::function — Get associated function name (deprecated)

Opis

public string GearmanTask::function ( void )

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Informacja:

This method has been replaced by GearmanTask::functionName() in the 0.6.0 release of the Gearman extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A function name.

GearmanTask::dataSize
GearmanTask::functionName
GearmanTask


Get associated function name

GearmanTask::function
GearmanTask::isKnown
GearmanTask
PHP Manual

GearmanTask::functionName

(PECL gearman >= 0.6.0)

GearmanTask::functionName — Get associated function name

Opis

public string GearmanTask::functionName ( void )

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A function name.

GearmanTask::function
GearmanTask::isKnown
GearmanTask


Determine if task is known

GearmanTask::functionName
GearmanTask::isRunning
GearmanTask
PHP Manual

GearmanTask::isKnown

(PECL gearman >= 0.5.0)

GearmanTask::isKnown — Determine if task is known

Opis

public bool GearmanTask::isKnown ( void )

Gets the status information for whether or not this task is known to the job server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the task is known, FALSE otherwise.

GearmanTask::functionName
GearmanTask::isRunning
GearmanTask


Test whether the task is currently running

GearmanTask::isKnown
GearmanTask::jobHandle
GearmanTask
PHP Manual

GearmanTask::isRunning

(PECL gearman >= 0.5.0)

GearmanTask::isRunning — Test whether the task is currently running

Opis

public bool GearmanTask::isRunning ( void )

Indicates whether or not this task is currently running.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the task is running, FALSE otherwise.

GearmanTask::isKnown
GearmanTask::jobHandle
GearmanTask


Get the job handle

GearmanTask::isRunning
GearmanTask::recvData
GearmanTask
PHP Manual

GearmanTask::jobHandle

gearman_job_handle

(PECL gearman >= 0.5.0)

GearmanTask::jobHandle -- gearman_job_handle — Get the job handle

Opis

public string GearmanTask::jobHandle ( void )

Returns the job handle for this task.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The opaque job handle.

Zobacz też:

  • GearmanClient::doJobHandle() - Get the job handle for the running task

GearmanTask::isRunning
GearmanTask::recvData
GearmanTask


Read work or result data into a buffer for a task

GearmanTask::jobHandle
GearmanTask::returnCode
GearmanTask
PHP Manual

GearmanTask::recvData

(PECL gearman >= 0.5.0)

GearmanTask::recvData — Read work or result data into a buffer for a task

Opis

public array GearmanTask::recvData ( int $data_len )

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

data_len

Length of data to be read.

Zwracane wartości

An array whose first element is the length of data read and the second is the data buffer. Returns FALSE if the read failed.

Zobacz też:

  • GearmanTask::sendData() - Send data for a task (deprecated)

GearmanTask::jobHandle
GearmanTask::returnCode
GearmanTask


Get the last return code

GearmanTask::recvData
GearmanTask::sendData
GearmanTask
PHP Manual

GearmanTask::returnCode

(PECL gearman >= 0.5.0)

GearmanTask::returnCode — Get the last return code

Opis

public int GearmanTask::returnCode ( void )

Returns the last Gearman return code for this task.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A valid Gearman return code.

Zobacz też:

  • GearmanClient::returnCode() - Get the last Gearman return code

GearmanTask::recvData
GearmanTask::sendData
GearmanTask


Send data for a task (deprecated)

GearmanTask::returnCode
GearmanTask::sendWorkload
GearmanTask
PHP Manual

GearmanTask::sendData

(PECL gearman <= 0.5.0)

GearmanTask::sendData — Send data for a task (deprecated)

Opis

public int GearmanTask::sendData ( string $data )

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

data

Data to send to the worker.

Zwracane wartości

The length of data sent, or FALSE if the send failed.

Zobacz też:

  • GearmanTask::recvData() - Read work or result data into a buffer for a task

GearmanTask::returnCode
GearmanTask::sendWorkload
GearmanTask


Send data for a task

GearmanTask::sendData
GearmanTask::taskDenominator
GearmanTask
PHP Manual

GearmanTask::sendWorkload

(PECL gearman >= 0.6.0)

GearmanTask::sendWorkload — Send data for a task

Opis

public int GearmanTask::sendWorkload ( string $data )

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

data

Data to send to the worker.

Zwracane wartości

The length of data sent, or FALSE if the send failed.

Zobacz też:

  • GearmanTask::recvData() - Read work or result data into a buffer for a task

GearmanTask::sendData
GearmanTask::taskDenominator
GearmanTask


Get completion percentage denominator

GearmanTask::sendWorkload
GearmanTask::taskNumerator
GearmanTask
PHP Manual

GearmanTask::taskDenominator

(PECL gearman >= 0.5.0)

GearmanTask::taskDenominator — Get completion percentage denominator

Opis

public int GearmanTask::taskDenominator ( void )

Returns the denominator of the percentage of the task that is complete expressed as a fraction.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A number between 0 and 100, or FALSE if cannot be determined.

Zobacz też:

  • GearmanTask::taskNumerator() - Get completion percentage numerator

GearmanTask::sendWorkload
GearmanTask::taskNumerator
GearmanTask


Get completion percentage numerator

GearmanTask::taskDenominator
GearmanTask::unique
GearmanTask
PHP Manual

GearmanTask::taskNumerator

(PECL gearman >= 0.5.0)

GearmanTask::taskNumerator — Get completion percentage numerator

Opis

public int GearmanTask::taskNumerator ( void )

Returns the numerator of the percentage of the task that is complete expressed as a fraction.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A number between 0 and 100, or FALSE if cannot be determined.

Zobacz też:

  • GearmanTask::taskDenominator() - Get completion percentage denominator

GearmanTask::taskDenominator
GearmanTask::unique
GearmanTask


Get the unique identifier for a task

GearmanTask::taskNumerator
GearmanTask::uuid
GearmanTask
PHP Manual

GearmanTask::unique

(PECL gearman >= 0.6.0)

GearmanTask::unique — Get the unique identifier for a task

Opis

public string GearmanTask::unique ( void )

Returns the unique identifier for this task. This is assigned by the GearmanClient, as opposed to the job handle which is set by the Gearman job server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The unique identifier, or FALSE if no identifier is assigned.

Zobacz też:

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanClient::addTask() - Add a task to be run in parallel

GearmanTask::taskNumerator
GearmanTask::uuid
GearmanTask


Get the unique identifier for a task (deprecated)

GearmanTask::unique
GearmanWorker
GearmanTask
PHP Manual

GearmanTask::uuid

(PECL gearman <= 0.5.0)

GearmanTask::uuid — Get the unique identifier for a task (deprecated)

Opis

public string GearmanTask::uuid ( void )

Returns the unique identifier for this task. This is assigned by the GearmanClient, as opposed to the job handle which is set by the Gearman job server.

Informacja:

This method has been replaced by GearmanTask::unique() in the 0.6.0 release of the Gearman extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The unique identifier, or FALSE if no identifier is assigned.

Zobacz też:

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanClient::addTask() - Add a task to be run in parallel

GearmanTask::unique
GearmanWorker
GearmanTask


The GearmanWorker class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

GearmanWorker {
/* Metody */
public bool addFunction ( string $function_name , callback $function [, mixed &$context [, int $timeout ]] )
public bool addOptions ( int $option )
public bool addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] )
public bool addServers ( string $servers = 127.0.0.1:4730 )
public void clone ( void )
public __construct ( void )
public bool echo ( string $workload )
public string error ( void )
public int getErrno ( void )
public int options ( void )
public bool register ( string $function_name [, int $timeout ] )
public bool removeOptions ( int $option )
public int returnCode ( void )
public bool setOptions ( int $option )
public bool setTimeout ( int $timeout )
public int timeout ( void )
public bool unregister ( string $function_name )
public bool unregisterAll ( void )
public bool wait ( void )
public bool work ( void )
}

Spis treści

  • GearmanWorker::addFunction — Register and add callback function
  • GearmanWorker::addOptions — Add worker options
  • GearmanWorker::addServer — Add a job server
  • GearmanWorker::addServers — Add job servers
  • GearmanWorker::clone — Create a copy of the worker
  • GearmanWorker::__construct — Create a GearmanWorker instance
  • GearmanWorker::echo — Test job server response
  • GearmanWorker::error — Get the last error encountered
  • GearmanWorker::getErrno — Get errno
  • GearmanWorker::options — Get worker options
  • GearmanWorker::register — Register a function with the job server
  • GearmanWorker::removeOptions — Remove worker options
  • GearmanWorker::returnCode — Get last Gearman return code
  • GearmanWorker::setOptions — Set worker options
  • GearmanWorker::setTimeout — Set socket I/O activity timeout
  • GearmanWorker::timeout — Get socket I/O activity timeout
  • GearmanWorker::unregister — Unregister a function name with the job servers
  • GearmanWorker::unregisterAll — Unregister all function names with the job servers
  • GearmanWorker::wait — Wait for activity from one of the job servers
  • GearmanWorker::work — Wait for and perform jobs
GearmanTask::uuid
GearmanWorker::addFunction
Gearman


Register and add callback function

GearmanWorker
GearmanWorker::addOptions
GearmanWorker
PHP Manual

GearmanWorker::addFunction

(PECL gearman >= 0.5.0)

GearmanWorker::addFunction — Register and add callback function

Opis

public bool GearmanWorker::addFunction ( string $function_name , callback $function [, mixed &$context [, int $timeout ]] )

Registers a function name with the job server and specifies a callback corresponding to that function. Optionally specify extra application context data to be used when the callback is called and a timeout.

Parametry

function_name

The name of a function to register with the job server

function

A callback that gets called when a job for the registered function name is submitted

context

A reference to arbitrary application context data that can be modified by the worker function

timeout

An interval of time in seconds

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Simple worker making use of extra application context data

<?php

# get a gearman worker
$worker= new GearmanWorker();

# add the default server (localhost)
$worker->addServer();

# define a variable to hold application data
$count= 0;

# add the "reverse" function
$worker->addFunction("reverse", "reverse_cb", &$count);

# start the worker
while ($worker->work());

function reverse_cb($job, $count)
{
  $count++;
  return "$count: " . strrev($job->workload());
}

?>

Running a client that submits two jobs for the reverse function would have output similar to the following:

1: olleh
2: dlrow

Zobacz też:

  • GearmanClient::do() - Run a single task and return a result [deprecated]

GearmanWorker
GearmanWorker::addOptions
GearmanWorker


Add worker options

GearmanWorker::addFunction
GearmanWorker::addServer
GearmanWorker
PHP Manual

GearmanWorker::addOptions

(PECL gearman >= 0.6.0)

GearmanWorker::addOptions — Add worker options

Opis

public bool GearmanWorker::addOptions ( int $option )

Adds one or more options to the options previously set.

Parametry

option

The options to be added

Zwracane wartości

Always returns TRUE.

Zobacz też:

  • GearmanWorker::options() - Get worker options
  • GearmanClient::setOptions() - Set client options
  • GearmanClient::removeOptions() - Remove client options

GearmanWorker::addFunction
GearmanWorker::addServer
GearmanWorker


Add a job server

GearmanWorker::addOptions
GearmanWorker::addServers
GearmanWorker
PHP Manual

GearmanWorker::addServer

(PECL gearman >= 0.5.0)

GearmanWorker::addServer — Add a job server

Opis

public bool GearmanWorker::addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] )

Adds a job server to this worker. This goes into a list of servers than can be used to run jobs. No socket I/O happens here.

Parametry

host

Nazwa hosta serwera roboczego.

port

Port serwera roboczego.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Add alternate Gearman servers

<?php
$worker= new GearmanWorker();
$worker->addServer("10.0.0.1");
$worker->addServer("10.0.0.2", 7003);
?>

Zobacz też:

  • GearmanWorker::addServers() - Add job servers

GearmanWorker::addOptions
GearmanWorker::addServers
GearmanWorker


Add job servers

GearmanWorker::addServer
GearmanWorker::clone
GearmanWorker
PHP Manual

GearmanWorker::addServers

(PECL gearman >= 0.5.0)

GearmanWorker::addServers — Add job servers

Opis

public bool GearmanWorker::addServers ( string $servers = 127.0.0.1:4730 )

Adds one or more job servers to this worker. These go into a list of servers that can be used to run jobs. No socket I/O happens here.

Parametry

servers

A comma separated list of job servers in the format host:port. If no port is specified, it defaults to 4730.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Add two job servers

<?php

$worker= new GearmanWorker();
$worker->addServers("10.0.0.1,10.0.0.2:7003");

?>

Zobacz też:

  • GearmanWorker::addServer() - Add a job server

GearmanWorker::addServer
GearmanWorker::clone
GearmanWorker


Create a copy of the worker

GearmanWorker::addServers
GearmanWorker::__construct
GearmanWorker
PHP Manual

GearmanWorker::clone

(PECL gearman >= 0.5.0)

GearmanWorker::clone — Create a copy of the worker

Opis

public void GearmanWorker::clone ( void )

Creates a copy of the worker.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A GearmanWorker object

GearmanWorker::addServers
GearmanWorker::__construct
GearmanWorker


Create a GearmanWorker instance

GearmanWorker::clone
GearmanWorker::echo
GearmanWorker
PHP Manual

GearmanWorker::__construct

(PECL gearman >= 0.5.0)

GearmanWorker::__construct — Create a GearmanWorker instance

Opis

public GearmanWorker::__construct ( void )

Creates a GearmanWorker instance representing a worker that connects to the job server and accepts tasks to run.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A GearmanWorker object

Zobacz też:

  • GearmanWorker::clone() - Create a copy of the worker

GearmanWorker::clone
GearmanWorker::echo
GearmanWorker


Test job server response

GearmanWorker::__construct
GearmanWorker::error
GearmanWorker
PHP Manual

GearmanWorker::echo

(PECL gearman >= 0.6.0)

GearmanWorker::echo — Test job server response

Opis

public bool GearmanWorker::echo ( string $workload )

Sends data to all job servers to see if they echo it back. This is a test function to see if job servers are responding properly.

Parametry

workload

Arbitrary serialized data

Zwracane wartości

Standard Gearman return value.

Zobacz też:

  • GearmanClient::echo() - Send data to all job servers to see if they echo it back [deprecated]

GearmanWorker::__construct
GearmanWorker::error
GearmanWorker


Get the last error encountered

GearmanWorker::echo
GearmanWorker::getErrno
GearmanWorker
PHP Manual

GearmanWorker::error

(PECL gearman >= 0.5.0)

GearmanWorker::error — Get the last error encountered

Opis

public string GearmanWorker::error ( void )

Returns an error string for the last error encountered.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An error string.

Zobacz też:

  • GearmanWorker::getErrno() - Get errno

GearmanWorker::echo
GearmanWorker::getErrno
GearmanWorker


Get errno

GearmanWorker::error
GearmanWorker::options
GearmanWorker
PHP Manual

GearmanWorker::getErrno

(PECL gearman >= 0.5.0)

GearmanWorker::getErrno — Get errno

Opis

public int GearmanWorker::getErrno ( void )

Returns the value of errno in the case of a GEARMAN_ERRNO return value.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A valid errno.

Zobacz też:

  • GearmanWorker::error() - Get the last error encountered

GearmanWorker::error
GearmanWorker::options
GearmanWorker


Get worker options

GearmanWorker::getErrno
GearmanWorker::register
GearmanWorker
PHP Manual

GearmanWorker::options

(PECL gearman >= 0.6.0)

GearmanWorker::options — Get worker options

Opis

public int GearmanWorker::options ( void )

Gets the options previously set for the worker.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The options currently set for the worker.

Zobacz też:

  • GearmanWorker::setOptions() - Set worker options

GearmanWorker::getErrno
GearmanWorker::register
GearmanWorker


Register a function with the job server

GearmanWorker::options
GearmanWorker::removeOptions
GearmanWorker
PHP Manual

GearmanWorker::register

(PECL gearman >= 0.6.0)

GearmanWorker::register — Register a function with the job server

Opis

public bool GearmanWorker::register ( string $function_name [, int $timeout ] )

Registers a function name with the job server with an optional timeout. The timeout specifies how many seconds the server will wait before marking a job as failed. If the timeout is set to zero, there is no timeout.

Parametry

function_name

The name of a function to register with the job server

timeout

An interval of time in seconds

Zwracane wartości

A standard Gearman return value.

Zobacz też:

  • GearmanWorker::unregister() - Unregister a function name with the job servers
  • GearmanWorker::unregisterAll() - Unregister all function names with the job servers

GearmanWorker::options
GearmanWorker::removeOptions
GearmanWorker


Remove worker options

GearmanWorker::register
GearmanWorker::returnCode
GearmanWorker
PHP Manual

GearmanWorker::removeOptions

(PECL gearman >= 0.6.0)

GearmanWorker::removeOptions — Remove worker options

Opis

public bool GearmanWorker::removeOptions ( int $option )

Removes (unsets) one or more worker options.

Parametry

option

The options to be removed (unset)

Zwracane wartości

Always returns TRUE.

Zobacz też:

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::setOptions() - Set worker options
  • GearmanWorker::addOptions() - Add worker options

GearmanWorker::register
GearmanWorker::returnCode
GearmanWorker


Get last Gearman return code

GearmanWorker::removeOptions
GearmanWorker::setOptions
GearmanWorker
PHP Manual

GearmanWorker::returnCode

(PECL gearman >= 0.5.0)

GearmanWorker::returnCode — Get last Gearman return code

Opis

public int GearmanWorker::returnCode ( void )

Returns the last Gearman return code.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A valid Gearman return code.

Zobacz też:

  • GearmanWorker::error() - Get the last error encountered
  • GearmanWorker::getErrno() - Get errno

GearmanWorker::removeOptions
GearmanWorker::setOptions
GearmanWorker


Set worker options

GearmanWorker::returnCode
GearmanWorker::setTimeout
GearmanWorker
PHP Manual

GearmanWorker::setOptions

(PECL gearman >= 0.5.0)

GearmanWorker::setOptions — Set worker options

Opis

public bool GearmanWorker::setOptions ( int $option )

Sets one or more options to the supplied value.

Parametry

option

The options to be set

Zwracane wartości

Always returns TRUE.

Zobacz też:

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::addOptions() - Add worker options
  • GearmanWorker::removeOptions() - Remove worker options
  • GearmanClient::setOptions() - Set client options

GearmanWorker::returnCode
GearmanWorker::setTimeout
GearmanWorker


Set socket I/O activity timeout

GearmanWorker::setOptions
GearmanWorker::timeout
GearmanWorker
PHP Manual

GearmanWorker::setTimeout

(PECL gearman >= 0.6.0)

GearmanWorker::setTimeout — Set socket I/O activity timeout

Opis

public bool GearmanWorker::setTimeout ( int $timeout )

Sets the interval of time to wait for socket I/O activity.

Parametry

timeout

An interval of time in milliseconds. A negative value indicates an infinite timeout.

Zwracane wartości

Always returns TRUE.

Przykłady

Przykład #1 A simple worker with a 5 second timeout

<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

# Set the timeout to 5 seconds
$gmworker->setTimeout(5000);

echo "Waiting for job...\n";
while(@$gmworker->work() || $gmworker->returnCode() == GEARMAN_TIMEOUT)
{
  if ($gmworker->returnCode() == GEARMAN_TIMEOUT)
  {
    # Normally one would want to do something useful here ...
    echo "Timeout. Waiting for next job...\n";
    continue;
  }

  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

echo "Done\n";

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

Running the worker with no submitted jobs will generate output that looks like the following:

Starting
Waiting for job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...

Zobacz też:

  • GearmanWorker::timeout() - Get socket I/O activity timeout

GearmanWorker::setOptions
GearmanWorker::timeout
GearmanWorker


Get socket I/O activity timeout

GearmanWorker::setTimeout
GearmanWorker::unregister
GearmanWorker
PHP Manual

GearmanWorker::timeout

(PECL gearman >= 0.6.0)

GearmanWorker::timeout — Get socket I/O activity timeout

Opis

public int GearmanWorker::timeout ( void )

Returns the current time to wait, in milliseconds, for socket I/O activity.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A time period is milliseconds. A negative value indicates an infinite timeout.

Zobacz też:

  • GearmanWorker::setTimeout() - Set socket I/O activity timeout

GearmanWorker::setTimeout
GearmanWorker::unregister
GearmanWorker


Unregister a function name with the job servers

GearmanWorker::timeout
GearmanWorker::unregisterAll
GearmanWorker
PHP Manual

GearmanWorker::unregister

(PECL gearman >= 0.6.0)

GearmanWorker::unregister — Unregister a function name with the job servers

Opis

public bool GearmanWorker::unregister ( string $function_name )

Unregisters a function name with the job servers ensuring that no more jobs (for that function) are sent to this worker.

Parametry

function_name

The name of a function to register with the job server

Zwracane wartości

A standard Gearman return value.

Zobacz też:

  • GearmanWorker::register() - Register a function with the job server
  • GearmanWorker::unregisterAll() - Unregister all function names with the job servers

GearmanWorker::timeout
GearmanWorker::unregisterAll
GearmanWorker


Unregister all function names with the job servers

GearmanWorker::unregister
GearmanWorker::wait
GearmanWorker
PHP Manual

GearmanWorker::unregisterAll

(PECL gearman >= 0.6.0)

GearmanWorker::unregisterAll — Unregister all function names with the job servers

Opis

public bool GearmanWorker::unregisterAll ( void )

Unregisters all previously registered functions, ensuring that no more jobs are sent to this worker.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A standard Gearman return value.

Zobacz też:

  • GearmanWorker::register() - Register a function with the job server
  • GearmanWorker::unregister() - Unregister a function name with the job servers

GearmanWorker::unregister
GearmanWorker::wait
GearmanWorker


Wait for activity from one of the job servers

GearmanWorker::unregisterAll
GearmanWorker::work
GearmanWorker
PHP Manual

GearmanWorker::wait

(PECL gearman >= 0.6.0)

GearmanWorker::wait — Wait for activity from one of the job servers

Opis

public bool GearmanWorker::wait ( void )

Causes the worker to wait for activity from one of the Gearman job servers when operating in non-blocking I/O mode. On failure, issues a E_WARNING with the last Gearman error encountered.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Running worker in non-blocking mode

<?php

echo "Starting\n";

# Create our worker object
$worker= new GearmanWorker();

# Make the worker non-blocking
$worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);

# Add the default server (localhost, port 4730)
$worker->addServer();

# Add our reverse function
$worker->addFunction('reverse', 'reverse_fn');

# Try to grab a job
while (@$worker->work() ||
       $worker->returnCode() == GEARMAN_IO_WAIT ||
       $worker->returnCode() == GEARMAN_NO_JOBS)
{
  if ($worker->returnCode() == GEARMAN_SUCCESS)
    continue;

  echo "Waiting for next job...\n";
  if (!@$worker->wait())
  {
    if ($worker->returnCode() == GEARMAN_NO_ACTIVE_FDS)
    {
      # We are not connected to any servers, so wait a bit before
      # trying to reconnect.
      sleep(5);
      continue;
    }
    break;
  }
}

echo "Worker Error: " . $worker->error() . "\n";

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

Zobacz też:

  • GearmanWorker::work() - Wait for and perform jobs

GearmanWorker::unregisterAll
GearmanWorker::work
GearmanWorker


Wait for and perform jobs

GearmanWorker::wait
Gopher
GearmanWorker
PHP Manual

GearmanWorker::work

(PECL gearman >= 0.5.0)

GearmanWorker::work — Wait for and perform jobs

Opis

public bool GearmanWorker::work ( void )

Waits for a job to be assigned and then calls the appropriate callback function. Issues an E_WARNING with the last Gearman error if the return code is not one of GEARMAN_SUCCESS, GEARMAN_IO_WAIT, or GEARMAN_WORK_FAIL.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 GearmanWorker::work() example

<?php

# create the worker
$worker = new GearmanWorker();

# add the default job server (localhost)
$worker->addServer();

# add the reverse function
$worker->addFunction("reverse", "my_reverse_function");

# start te worker listening for job submissions
while ($worker->work());

function my_reverse_function($job)
{
  return strrev($job->workload());
}

?>

Zobacz też:

  • GearmanWorker::addFunction() - Register and add callback function

GearmanWorker::wait
Gopher
GearmanWorker


Net Gopher

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic Example
  • Gopher Funkcje
    • gopher_parsedir — Translate a gopher formatted directory entry into an associative array.
GearmanWorker::work
Wstęp
Inne serwisy


Wstęp

The gopher protocol, as defined by » RFC 1436, is generally considered the ancestor of the modern HTTP protocol. However, gopher was also intended to provide references to non-gopher resources including telnet, wais, nntp, and even http. This extension adds gopher support to PHP's URL Wrappers, and provides a helper function gopher_parsedir() to make sense of gopher formatted directory listings.

Gopher
Instalacja/Konfiguracja
Gopher


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Gopher


Instalacja

Prerequisite: PHP 4.3.0 or higher.

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/net_gopher

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Net_Gopher constants
Constant | Value | Description
GOPHER_DOCUMENT | 0 | Standard text/plain document.
GOPHER_DIRECTORY | 1 | A resource containing a gopher formatted directory listing.
GOPHER_BINHEX | 4 | A BinHex encoded binary file.
GOPHER_DOSBINARY | 5 | A DOS formatted binary archive.
GOPHER_UUENCODED | 6 | A UUEncoded file.
GOPHER_BINARY | 9 | A generic binary file.
GOPHER_INFO | 255 | An Informational entry
GOPHER_HTTP | 254 | A reference to an HTTP resource.
GOPHER_UNKNOWN | -1 | An unrecognized entry.
Typy zasobów
Przykłady
Gopher


Przykłady

Spis treści

  • Basic Example
Stałe predefiniowane
Basic Example
Gopher


Basic Example

<?php
readfile("gopher://gopher.example.com/somedocument");
?>
Przykłady
Gopher Funkcje
Przykłady


Gopher Funkcje

Spis treści

  • gopher_parsedir — Translate a gopher formatted directory entry into an associative array.
Basic Example
gopher_parsedir
Gopher


Translate a gopher formatted directory entry into an associative array.

Gopher Funkcje
Gupnp
Gopher Funkcje
PHP Manual

gopher_parsedir

(PECL net_gopher >= 0.1)

gopher_parsedir — Translate a gopher formatted directory entry into an associative array.

Opis

array gopher_parsedir ( string $dirent )

gopher_parsedir() parses a gopher formatted directory entry into an associative array.

While gopher returns text/plain documents for actual document requests. A request to a directory (such as /) will return specially encoded series of lines with each line being one directory entry or information line.

Parametry

dirent

The directory entry.

Zwracane wartości

Returns an associative array whose components are:

  • type - One of the GOPHER_XXX constants.
  • title - The name of the resource.
  • path - The path of the resource.
  • host - The domain name of the host that has this document (or directory).
  • port - The port at which to connect on host.

Upon failure, the additional data entry of the returned array will hold the parsed line.

Przykłady

Przykład #1 Hypothetical output from gopher://gopher.example.com/

0All about my gopher site.               /allabout.txt               gopher.example.com    70
9A picture of my cat.                    /pics/cat.png               gopher.example.com    70
1A collection of my writings.            /stories                    gopher.example.com    70
hThe HTTP version of this site.          URL:http://www.example.com  gopher.example.com    70
1Mirror of this site in Spain.           /                           gopher.ejemplo.co.es  70
iWelcome to my gopher site.                                          error.host            1
iPlease select one of the options above                              error.host            1
iSend complaints to /dev/null                                        error.host            1
iLong live gopher!                                                   error.host            1

In the example above, the root directory at gopher.example.com knows about one DOCUMENT identified by 0 located at gopher://gopher.example.com:70/allabout.txt. It also knows about two other directory (which have their own listing files) at gopher://gopher.exmaple.com:70/stories and at gopher://gopher.ejemplo.co.es:70/. In addition there is a binary file, a link to an HTTP url, and several informative lines.

By passing each line of the directory listing into gopher_parsedir(), an associative array is formed containing a parsed out version of the data.

Przykład #2 Using gopher_parsedir()

<?php
$directory = file("gopher://gopher.example.com");

foreach($directory as $dirent) {
    print_r(gopher_parsedir($dirent));
}
?>

Powyższy przykład wyświetli:

Array (
  [type] => 0
  [title] => All about my gopher site.
  [path] => /allabout.txt
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 9
  [title] => A picture of my cat.
  [path] => /pics/cat.png
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => A collection of my writings.
  [path] => /stories
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 254
  [title] => The HTTP version of this site.
  [path] => URL:http://www.example.com
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => Mirror of this site in Spain.
  [path] => /
  [host] => gopher.ejemplo.co.es
  [port] => 70
)
Array (
  [type] => 255
  [title] => Welcome to my gopher site.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Please select one of the options above.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Send complaints to /dev/null
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Long live gopher!
  [path] =>
  [host] => error.host
  [port] => 1
)

Gopher Funkcje
Gupnp
Gopher Funkcje


Gupnp

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Browsing devices and services
    • Implementing the BinaryLight device
  • Gupnp Funkcje
    • gupnp_context_get_host_ip — Get the IP address
    • gupnp_context_get_port — Get the port
    • gupnp_context_get_subscription_timeout — Get the event subscription timeout
    • gupnp_context_host_path — Start hosting
    • gupnp_context_new — Create a new context
    • gupnp_context_set_subscription_timeout — Sets the event subscription timeout
    • gupnp_context_timeout_add — Sets a function to be called at regular intervals
    • gupnp_context_unhost_path — Stop hosting
    • gupnp_control_point_browse_start — Start browsing
    • gupnp_control_point_browse_stop — Stop browsing
    • gupnp_control_point_callback_set — Set control point callback
    • gupnp_control_point_new — Create a new control point
    • gupnp_device_action_callback_set — Set device callback function
    • gupnp_device_info_get_service — Get the service with type
    • gupnp_device_info_get — Get info of root device
    • gupnp_root_device_get_available — Check whether root device is available
    • gupnp_root_device_get_relative_location — Get the relative location of root device.
    • gupnp_root_device_new — Create a new root device
    • gupnp_root_device_set_available — Set whether or not root_device is available
    • gupnp_root_device_start — Start main loop
    • gupnp_root_device_stop — Stop main loop
    • gupnp_service_action_get — Retrieves the specified action arguments
    • gupnp_service_action_return_error — Return error code
    • gupnp_service_action_return — Return succesfully
    • gupnp_service_action_set — Sets the specified action return values
    • gupnp_service_freeze_notify — Freeze new notifications
    • gupnp_service_info_get_introspection — Get resource introspection of service
    • gupnp_service_info_get — Get full info of service
    • gupnp_service_introspection_get_state_variable — Returns the state variable data
    • gupnp_service_notify — Notifies listening clients
    • gupnp_service_proxy_action_get — Send action to the service and get value
    • gupnp_service_proxy_action_set — Send action to the service and set value
    • gupnp_service_proxy_add_notify — Sets up callback for variable change notification
    • gupnp_service_proxy_callback_set — Set service proxy callback for signal
    • gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service
    • gupnp_service_proxy_remove_notify — Cancels the variable change notification
    • gupnp_service_proxy_send_action — Send action with multiple parameters synchronously
    • gupnp_service_proxy_set_subscribed — (Un)subscribes to the service.
    • gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones.
gopher_parsedir
Wstęp
Inne serwisy


Wstęp

GUPnP is an object-oriented open source framework for creating UPnP devices and control points, written in C using GObject and libsoup. This extension wraps GUPnP and provides similar API. All sources and additional documentation can be obtained from the » official site

Gupnp
Instalacja/Konfiguracja
Gupnp


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Gupnp


Wymagania

In order to use PECL/Gupnp functions you need to install the » gUPnP library version 0.12.7 or greater. It also requires glib-2.0, gssdp-1.0, libsoup-2.4 or greater for all of them.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/gupnp

Informacja: If ./configure is having trouble finding the libgupnp files (for example, it was installed into a custom prefix directory), use ./configure --with-gupnp=$PREFIX, where $PREFIX is installation prefix of libgupnp.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

GUPNP_TYPE_BOOLEAN (integer)
GUPNP_TYPE_INT (integer)
GUPNP_TYPE_LONG (integer)
GUPNP_TYPE_DOUBLE (integer)
GUPNP_TYPE_FLOAT (integer)
GUPNP_TYPE_STRING (integer)
GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE (integer)
GUPNP_SIGNAL_DEVICE_PROXY_UNAVAILABLE (integer)
GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE (integer)
GUPNP_SIGNAL_SERVICE_PROXY_UNAVAILABLE (integer)
GUPNP_SIGNAL_ACTION_INVOKED (integer)
GUPNP_SIGNAL_NOTIFY_FAILED (integer)
GUPNP_SIGNAL_SUBSCRIPTION_LOST (integer)
GUPNP_CONTROL_ERROR_INVALID_ACTION (integer)
GUPNP_CONTROL_ERROR_INVALID_ARGS (integer)
GUPNP_CONTROL_ERROR_OUT_OF_SYNC (integer)
GUPNP_CONTROL_ERROR_ACTION_FAILED (integer)

Typy zasobów
Przykłady
Gupnp


Przykłady

Spis treści

  • Browsing devices and services
  • Implementing the BinaryLight device
Stałe predefiniowane
Browsing devices and services
Gupnp


Browsing devices and services

This example shows how to obtain information about all devices and services. It starts an infinite loop (use CLI), and if any of available devices or services are found, the proper callback function will be invoked.

Przykład #1 Search for all UPnP devices and services.

<?php

/* Callback for available device */
function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("\ttype:     %s\n", $type);
    printf("\tlocation: %s\n", $location);
}

/* Callback for available service */
function service_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_service_info_get($proxy);

    $type = $info['service_type'];
    $location = $info['location'];

    printf("Service available:\n");
    printf("\ttype:     %s\n", $type);
    printf("\tlocation: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

/* Set callbacks */
gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');
gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE, 'service_proxy_available_cb');

/* Start for browsing (infinite loop, hit Ctrl-C to interrupt) */
gupnp_control_point_browse_start($cp);

?>

Przykłady
Implementing the BinaryLight device
Przykłady


Implementing the BinaryLight device

This is an example of UPnP device/service, implementing the BinaryLight device and SwitchPower services to emulate a light switch.

The user interface was purposely simplified in order to show basic concepts and methods.

Przykład #1 Implementing light server

<?php

/* SetTarget */
function set_target_cb($service, $action, $arg)
{
    /* Get the new target value */
    $target = gupnp_service_action_get($action, 'NewTargetValue', GUPNP_TYPE_BOOLEAN);

    /* If the new target doesn't match the current status, change the status and
       emit a notification that the status has changed. */
    if ($target != $GLOBALS['status']) {
        $GLOBALS['status'] = $target;
        gupnp_service_notify($service, 'Status', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
        printf("The light is now %s.\n", $GLOBALS['status'] ? "on" : "off");
    }

    /* Return success to the client */
    gupnp_service_action_return($action);
}

/* GetTarget */
function get_target_cb($service, $action, $arg)
{
    gupnp_service_action_set($action, 'RetTargetValue', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
    gupnp_service_action_return($action);
}

/* GetStatus */
function get_status_cb($service, $action, $arg)
{
    gupnp_service_action_set($action, 'ResultStatus', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
    gupnp_service_action_return($action);
}

/* By default the light is off */
$GLOBALS['status'] = false;
printf("The light is now %s.\n", $GLOBALS['status'] ? "on" : "off");

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* Host the directory that contains device and service description files */
gupnp_context_host_path($context, "./web", "");

/* Create root device */
$location = "/BinaryLight.xml";
$dev = gupnp_root_device_new($context, $location);
gupnp_root_device_set_available($dev, true);

/* Get the switch service from the root device */
$service_type = "urn:schemas-upnp-org:service:SwitchPower:1";
$service = gupnp_device_info_get_service($dev, $service_type);
if (!$service) {
    die("Cannot get SwitchPower1 service\n");
}

/* Set callback for action GetStatus */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "GetStatus",
    "get_status_cb", "action data, GetStatus");

/* Set callback for action GetTarget */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "GetTarget",
    "get_target_cb", "action data, GetTarget");

/* Set callback for action SetTarget */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "SetTarget",
    "set_target_cb", "action data, SetTarget");

/* Run the main loop */
gupnp_root_device_start($dev);

?>

Przykład #2 Implementing light client

<?php

function service_proxy_available_cb($proxy, $arg)
{
    $mode = $arg['mode'];

    printf("Set subscribed\n");
    gupnp_service_proxy_set_subscribed($proxy, true);

    /* Add notify if status will be changed */
    if (!gupnp_service_proxy_add_notify($proxy, "Status",
            GUPNP_TYPE_BOOLEAN, "status_changed_cb", NULL)) {
        printf("Failed to add notify\n");
    }

    if ($mode == 'TOGGLE') {
        /* We're toggling, so first fetch the current status */
        $target = gupnp_service_proxy_action_get($proxy, 'GetStatus', 'ResultStatus', GUPNP_TYPE_BOOLEAN);

        /* And then toggle it */
        $target = ! $target;
    } else {
        /* Mode is a boolean, so the target is the mode thanks to our well chosen
           enumeration values. */
        $target = ($mode == 'ON') ? true : false;
    }

    /* Set the target */
    if (!gupnp_service_proxy_action_set($proxy, 'SetTarget', 'NewTargetValue', $target, GUPNP_TYPE_BOOLEAN)) {
        printf("Cannot set switch\n");
    } else {
        printf("Set switch to %s.\n", $target ? "on" : "off");
    }

    /* Stop browsing */
    gupnp_control_point_browse_stop($arg['cp']);
}

function status_changed_cb($variable, $value, $arg)
{
    printf("Status has been changed\n");
    printf("\tvariable name: %s\n", $variable);
    printf("\tvalue: %s\n", (int)$value);
    printf("\n");
}

/* Check and parse command line arguments */
if (count($argv) != 2) {
    printf("Usage: light-client.php [on|off|toggle]\n");
    exit(-1);
}

if ($argv[1] == "on") {
    $mode = 'ON';
} elseif ($argv[1] == "off") {
    $mode = 'OFF';
} elseif ($argv[1] == "toggle") {
    $mode = 'TOGGLE';
} else {
    usage ();
    exit(-1);
}

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* Create the control point, searching for SwitchPower services */
$cp = gupnp_control_point_new ($context,
        "urn:schemas-upnp-org:service:SwitchPower:1");

/* Connect to the service-found callback */
$cb = "service_proxy_available_cb";
$arg = array('mode' => $mode, 'cp' => $cp);
gupnp_control_point_callback_set($cp, GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE, $cb, $arg);

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>

Browsing devices and services
Gupnp Funkcje
Przykłady


Gupnp Funkcje

Spis treści

  • gupnp_context_get_host_ip — Get the IP address
  • gupnp_context_get_port — Get the port
  • gupnp_context_get_subscription_timeout — Get the event subscription timeout
  • gupnp_context_host_path — Start hosting
  • gupnp_context_new — Create a new context
  • gupnp_context_set_subscription_timeout — Sets the event subscription timeout
  • gupnp_context_timeout_add — Sets a function to be called at regular intervals
  • gupnp_context_unhost_path — Stop hosting
  • gupnp_control_point_browse_start — Start browsing
  • gupnp_control_point_browse_stop — Stop browsing
  • gupnp_control_point_callback_set — Set control point callback
  • gupnp_control_point_new — Create a new control point
  • gupnp_device_action_callback_set — Set device callback function
  • gupnp_device_info_get_service — Get the service with type
  • gupnp_device_info_get — Get info of root device
  • gupnp_root_device_get_available — Check whether root device is available
  • gupnp_root_device_get_relative_location — Get the relative location of root device.
  • gupnp_root_device_new — Create a new root device
  • gupnp_root_device_set_available — Set whether or not root_device is available
  • gupnp_root_device_start — Start main loop
  • gupnp_root_device_stop — Stop main loop
  • gupnp_service_action_get — Retrieves the specified action arguments
  • gupnp_service_action_return_error — Return error code
  • gupnp_service_action_return — Return succesfully
  • gupnp_service_action_set — Sets the specified action return values
  • gupnp_service_freeze_notify — Freeze new notifications
  • gupnp_service_info_get_introspection — Get resource introspection of service
  • gupnp_service_info_get — Get full info of service
  • gupnp_service_introspection_get_state_variable — Returns the state variable data
  • gupnp_service_notify — Notifies listening clients
  • gupnp_service_proxy_action_get — Send action to the service and get value
  • gupnp_service_proxy_action_set — Send action to the service and set value
  • gupnp_service_proxy_add_notify — Sets up callback for variable change notification
  • gupnp_service_proxy_callback_set — Set service proxy callback for signal
  • gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service
  • gupnp_service_proxy_remove_notify — Cancels the variable change notification
  • gupnp_service_proxy_send_action — Send action with multiple parameters synchronously
  • gupnp_service_proxy_set_subscribed — (Un)subscribes to the service.
  • gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones.
Implementing the BinaryLight device
gupnp_context_get_host_ip
Gupnp


Get the IP address

Gupnp Funkcje
gupnp_context_get_port
Gupnp Funkcje
PHP Manual

gupnp_context_get_host_ip

(PECL gupnp >= 0.1.0)

gupnp_context_get_host_ip — Get the IP address

Opis

string gupnp_context_get_host_ip ( resource $context )

Get the IP address we advertise ourselves as using.

Parametry

context

A context identifier, returned by gupnp_context_new().

Zwracane wartości

Returns the IP address for the current context and FALSE on error.

Przykłady

Przykład #1 Create new UPnP context and get IP address of the host

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Get IP address for the UPnP context */
$ip = gupnp_context_get_host_ip($context);
echo $ip;

?>

Zobacz też:

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_port() - Get the port

Gupnp Funkcje
gupnp_context_get_port
Gupnp Funkcje


Get the port

gupnp_context_get_host_ip
gupnp_context_get_subscription_timeout
Gupnp Funkcje
PHP Manual

gupnp_context_get_port

(PECL gupnp >= 0.1.0)

gupnp_context_get_port — Get the port

Opis

int gupnp_context_get_port ( resource $context )

Get the port that the SOAP server is running on.

Parametry

context

A context identifier, returned by gupnp_context_new().

Zwracane wartości

Returns the port number for the current context and FALSE on error.

Przykłady

Przykład #1 Create new UPnP context and get port number

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Get the port number for the UPnP context */
$port = gupnp_context_get_port($context);
echo $port;

?>

Zobacz też:

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_host_ip() - Get the IP address

gupnp_context_get_host_ip
gupnp_context_get_subscription_timeout
Gupnp Funkcje


Get the event subscription timeout

gupnp_context_get_port
gupnp_context_host_path
Gupnp Funkcje
PHP Manual

gupnp_context_get_subscription_timeout

(PECL gupnp >= 0.1.0)

gupnp_context_get_subscription_timeout — Get the event subscription timeout

Opis

int gupnp_context_get_subscription_timeout ( resource $context )

Get the event subscription timeout (in seconds), or 0 meaning there is no timeout.

Parametry

context

A context identifier, returned by gupnp_context_new().

Zwracane wartości

The event subscription timeout in seconds.

Zobacz też:

  • gupnp_context_new() - Create a new context
  • gupnp_context_set_subscription_timeout() - Sets the event subscription timeout

gupnp_context_get_port
gupnp_context_host_path
Gupnp Funkcje


Start hosting

gupnp_context_get_subscription_timeout
gupnp_context_new
Gupnp Funkcje
PHP Manual

gupnp_context_host_path

(PECL gupnp >= 0.1.0)

gupnp_context_host_path — Start hosting

Opis

bool gupnp_context_host_path ( resource $context , string $local_path , string $server_path )

Start hosting local_path at server_path. Files with the path local_path.LOCALE (if they exist) will be served up when LOCALE is specified in the request's Accept-Language header.

Parametry

context

A context identifier, returned by gupnp_context_new().

local_path

Path to the local file or folder to be hosted.

server_path

Web server path where local_path should be hosted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Create new UPnP context and set host path

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Host current directory */
gupnp_context_host_path($context, "./web", "");

?>

Zobacz też:

  • gupnp_context_new() - Create a new context
  • gupnp_context_unhost_path() - Stop hosting

gupnp_context_get_subscription_timeout
gupnp_context_new
Gupnp Funkcje


Create a new context

gupnp_context_host_path
gupnp_context_set_subscription_timeout
Gupnp Funkcje
PHP Manual

gupnp_context_new

(PECL gupnp >= 0.1.0)

gupnp_context_new — Create a new context

Opis

resource gupnp_context_new ([ string $host_ip [, int $port = 0 ]] )

Create a new context with the specified host_ip and port.

Parametry

host_ip

The local host's IP address, or NULL to use the IP address of the first non-loopback network interface.

port

Port to run on, or 0 if you don't care what port is used.

Zwracane wartości

A context identifier.

Przykłady

Przykład #1 Create new UPnP context

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

?>

Błędy/Wyjątki

Issues E_WARNING with unable to create context.

gupnp_context_host_path
gupnp_context_set_subscription_timeout
Gupnp Funkcje


Sets the event subscription timeout

gupnp_context_new
gupnp_context_timeout_add
Gupnp Funkcje
PHP Manual

gupnp_context_set_subscription_timeout

(PECL gupnp >= 0.1.0)

gupnp_context_set_subscription_timeout — Sets the event subscription timeout

Opis

void gupnp_context_set_subscription_timeout ( resource $context , int $timeout )

Sets the event subscription timeout (in seconds) to time out. Note that any client side subscriptions will automatically be renewed.

Parametry

context

A context identifier, returned by gupnp_context_new().

timeout

The event subscription timeout in seconds. Use 0 if you don't want subscriptions to time out.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_subscription_timeout() - Get the event subscription timeout

gupnp_context_new
gupnp_context_timeout_add
Gupnp Funkcje


Sets a function to be called at regular intervals

gupnp_context_set_subscription_timeout
gupnp_context_unhost_path
Gupnp Funkcje
PHP Manual

gupnp_context_timeout_add

(PECL gupnp >= 0.1.0)

gupnp_context_timeout_add — Sets a function to be called at regular intervals

Opis

bool gupnp_context_timeout_add ( resource $context , int $timeout , mixed $callback [, mixed $arg ] )

Sets a function to be called at regular intervals.

Parametry

context

A context identifier, returned by gupnp_context_new().

timeout

A timeout in miliseconds.

callback

The callback function calling every timeout period of time. Typically, callback function takes on arg parameter.

arg

User data for callback.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Create new UPnP context and set callback

<?php

$user_data = "user data";

function timeout_cb($arg)
{
    printf("Call timeout_cb, user data: '%s'", $arg);
    return true;
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$dev = gupnp_root_device_new($context, "/devicedesc.xml");

/* Set callback for timeout */
gupnp_context_timeout_add($context, 5000, "timeout_cb", $user_data);

/* Run the main loop */
gupnp_root_device_start($dev);

?>

Błędy/Wyjątki

Issues E_WARNING with not valid callback function.

Zobacz też:

  • gupnp_context_new() - Create a new context

gupnp_context_set_subscription_timeout
gupnp_context_unhost_path
Gupnp Funkcje


Stop hosting

gupnp_context_timeout_add
gupnp_control_point_browse_start
Gupnp Funkcje
PHP Manual

gupnp_context_unhost_path

(PECL gupnp >= 0.1.0)

gupnp_context_unhost_path — Stop hosting

Opis

bool gupnp_context_unhost_path ( resource $context , string $server_path )

Stop hosting the file or folder at server_path.

Parametry

context

A context identifier, returned by gupnp_context_new().

server_path

Web server path where the file or folder is hosted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_context_new() - Create a new context
  • gupnp_context_host_path() - Start hosting

gupnp_context_timeout_add
gupnp_control_point_browse_start
Gupnp Funkcje


Start browsing

gupnp_context_unhost_path
gupnp_control_point_browse_stop
Gupnp Funkcje
PHP Manual

gupnp_control_point_browse_start

(PECL gupnp >= 0.1.0)

gupnp_control_point_browse_start — Start browsing

Opis

bool gupnp_control_point_browse_start ( resource $cpoint )

Start the search and calls user-defined callback.

Parametry

cpoint

A control point identifier, returned by gupnp_control_point_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Create new UPnP context and start browsing

<?php

function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("type:     %s\n", $type);
    printf("location: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>

Zobacz też:

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_stop() - Stop browsing

gupnp_context_unhost_path
gupnp_control_point_browse_stop
Gupnp Funkcje


Stop browsing

gupnp_control_point_browse_start
gupnp_control_point_callback_set
Gupnp Funkcje
PHP Manual

gupnp_control_point_browse_stop

(PECL gupnp >= 0.1.0)

gupnp_control_point_browse_stop — Stop browsing

Opis

bool gupnp_control_point_browse_stop ( resource $cpoint )

Stop the search and calls user-defined callback.

Parametry

cpoint

A control point identifier, returned by gupnp_control_point_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_start() - Start browsing

gupnp_control_point_browse_start
gupnp_control_point_callback_set
Gupnp Funkcje


Set control point callback

gupnp_control_point_browse_stop
gupnp_control_point_new
Gupnp Funkcje
PHP Manual

gupnp_control_point_callback_set

(PECL gupnp >= 0.1.0)

gupnp_control_point_callback_set — Set control point callback

Opis

bool gupnp_control_point_callback_set ( resource $cpoint , int $signal , mixed $callback [, mixed $arg ] )

Set control point callback function for signal.

Parametry

cpoint

A control point identifier, returned by gupnp_control_point_new().

signal

The value of signal. Signal can be one of the following values:

GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE
Emitted whenever a new device has become available.
GUPNP_SIGNAL_DEVICE_PROXY_UNAVAILABLE
Emitted whenever a device is not available any more.
GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE
Emitted whenever a new service has become available.
GUPNP_SIGNAL_SERVICE_PROXY_UNAVAILABLE
Emitted whenever a service is not available any more.

callback

The callback function for the certain signal. Typically, callback function takes on two parameters. The proxy parameter's identifier being the first, and the arg second.

arg

User data for callback.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Create new UPnP context and start browsing

<?php

function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("type:     %s\n", $type);
    printf("location: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>

Błędy/Wyjątki

Issues E_WARNING with not valid callback function.

Zobacz też:

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_start() - Start browsing

gupnp_control_point_browse_stop
gupnp_control_point_new
Gupnp Funkcje


Create a new control point

gupnp_control_point_callback_set
gupnp_device_action_callback_set
Gupnp Funkcje
PHP Manual

gupnp_control_point_new

(PECL gupnp >= 0.1.0)

gupnp_control_point_new — Create a new control point

Opis

resource gupnp_control_point_new ( resource $context , string $target )

Create a new control point with the specified target.

Parametry

context

A context identifier, returned by gupnp_context_new().

target

The search target. target should be a service or device name, such as urn:schemas-upnp-org:service:WANIPConnection:1 or urn:schemas-upnp-org:device:MediaRenderer:1.

Zwracane wartości

A control point identifier.

gupnp_control_point_callback_set
gupnp_device_action_callback_set
Gupnp Funkcje


Set device callback function

gupnp_control_point_new
gupnp_device_info_get_service
Gupnp Funkcje
PHP Manual

gupnp_device_action_callback_set

(PECL gupnp >= 0.1.0)

gupnp_device_action_callback_set — Set device callback function

Opis

bool gupnp_device_action_callback_set ( resource $root_device , int $signal , string $action_name , mixed $callback [, mixed $arg ] )

Set device callback function for signal and action.

Parametry

root_device

A root device identifier, returned by gupnp_root_device_new().

signal

The value of signal. Signal can be one of the following values:

GUPNP_SIGNAL_ACTION_INVOKED
Emitted whenever an action is invoked. Handler should process action and must call either gupnp_service_action_return() or gupnp_service_action_return_error().
GUPNP_SIGNAL_NOTIFY_FAILED
Emitted whenever notification of a client fails.

action_name

The name of action.

callback

The callback function for the certain signal. Typically, callback function takes on three parameters. The service parameter's identifier being the first, action parameter's identifier (in case GUPNP_SIGNAL_ACTION_INVOKED signal) or error parameter's message (in case GUPNP_SIGNAL_NOTIFY_FAILED signal) being the second, and the arg is third.

arg

User data for callback.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Issues E_WARNING either with not valid callback function or with not valid signal.

Zobacz też:

  • gupnp_root_device_new() - Create a new root device

gupnp_control_point_new
gupnp_device_info_get_service
Gupnp Funkcje


Get the service with type

gupnp_device_action_callback_set
gupnp_device_info_get
Gupnp Funkcje
PHP Manual

gupnp_device_info_get_service

(PECL gupnp >= 0.1.0)

gupnp_device_info_get_service — Get the service with type

Opis

resource gupnp_device_info_get_service ( resource $root_device , string $type )

Get the service with type or false if no such device was found.

Parametry

root_device

A root device identifier, returned by gupnp_root_device_new().

type

The type of the service to be retrieved.

Zwracane wartości

A service identifier.

Przykłady

Przykład #1 Create new UPnP context and get device info service

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$location = "/BinaryLight1.xml";
$dev = gupnp_root_device_new($context, $location);

/* Set root device is available */
gupnp_root_device_set_available($dev, true);

/* Get the switch service from the root device */
$service_type = "urn:schemas-upnp-org:service:SwitchPower:1";
$service = gupnp_device_info_get_service($dev, $service_type);
if (!$service) {
    die("Cannot get SwitchPower1 service\n");
}

?>

gupnp_device_action_callback_set
gupnp_device_info_get
Gupnp Funkcje


Get info of root device

gupnp_device_info_get_service
gupnp_root_device_get_available
Gupnp Funkcje
PHP Manual

gupnp_device_info_get

(PECL gupnp >= 0.1.0)

gupnp_device_info_get — Get info of root device

Opis

array gupnp_device_info_get ( resource $root_device )

Get info of root device.

Parametry

root_device

A root device identifier, returned by gupnp_root_device_new().

Zwracane wartości

Return array wich contains the information of the root device (like location, url, udn and etc).

gupnp_device_info_get_service
gupnp_root_device_get_available
Gupnp Funkcje


Check whether root device is available

gupnp_device_info_get
gupnp_root_device_get_relative_location
Gupnp Funkcje
PHP Manual

gupnp_root_device_get_available

(PECL gupnp >= 0.1.0)

gupnp_root_device_get_available — Check whether root device is available

Opis

bool gupnp_root_device_get_available ( resource $root_device )

Get whether or not root_device is available (announcing its presence).

Parametry

root_device

A root device identifier, returned by gupnp_root_device_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_root_device_set_available() - Set whether or not root_device is available

gupnp_device_info_get
gupnp_root_device_get_relative_location
Gupnp Funkcje


Get the relative location of root device.

gupnp_root_device_get_available
gupnp_root_device_new
Gupnp Funkcje
PHP Manual

gupnp_root_device_get_relative_location

(PECL gupnp >= 0.1.0)

gupnp_root_device_get_relative_location — Get the relative location of root device.

Opis

string gupnp_root_device_get_relative_location ( resource $root_device )

Get the relative location of root device.

Parametry

root_device

A root device identifier, returned by gupnp_root_device_new().

Zwracane wartości

The relative location of root device

gupnp_root_device_get_available
gupnp_root_device_new
Gupnp Funkcje


Create a new root device

gupnp_root_device_get_relative_location
gupnp_root_device_set_available
Gupnp Funkcje
PHP Manual

gupnp_root_device_new

(PECL gupnp >= 0.1.0)

gupnp_root_device_new — Create a new root device

Opis

resource gupnp_root_device_new ( resource $context , string $location , string $description_dir )

Create a new root device, automatically downloading and parsing location.

Parametry

context

A context identifier, returned by gupnp_context_new().

location

Location of the description file for this device, relative to the HTTP root

Zwracane wartości

A root device identifier.

Przykłady

Przykład #1 Create new UPnP context and get device info service

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$location = "/BinaryLight1.xml";
$dev = gupnp_root_device_new($context, $location);

?>

Zobacz też:

  • gupnp_root_device_set_available() - Set whether or not root_device is available
  • gupnp_root_device_start() - Start main loop
  • gupnp_root_device_stop() - Stop main loop

gupnp_root_device_get_relative_location
gupnp_root_device_set_available
Gupnp Funkcje


Set whether or not root_device is available

gupnp_root_device_new
gupnp_root_device_start
Gupnp Funkcje
PHP Manual

gupnp_root_device_set_available

(PECL gupnp >= 0.1.0)

gupnp_root_device_set_available — Set whether or not root_device is available

Opis

bool gupnp_root_device_set_available ( resource $root_device , bool $available )

Controls whether or not root_device is available (announcing its presence).

Parametry

root_device

A root device identifier, returned by gupnp_root_device_new().

available

Set TRUE if root_device should be available.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_root_device_get_available() - Check whether root device is available

gupnp_root_device_new
gupnp_root_device_start
Gupnp Funkcje


Start main loop

gupnp_root_device_set_available
gupnp_root_device_stop
Gupnp Funkcje
PHP Manual

gupnp_root_device_start

(PECL gupnp >= 0.1.0)

gupnp_root_device_start — Start main loop

Opis

bool gupnp_root_device_start ( resource $root_device )

Start root server's main loop.

Parametry

root_device

A root device identifier, returned by gupnp_root_device_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_root_device_stop() - Stop main loop

gupnp_root_device_set_available
gupnp_root_device_stop
Gupnp Funkcje


Stop main loop

gupnp_root_device_start
gupnp_service_action_get
Gupnp Funkcje
PHP Manual

gupnp_root_device_stop

(PECL gupnp >= 0.1.0)

gupnp_root_device_stop — Stop main loop

Opis

bool gupnp_root_device_stop ( resource $root_device )

Stop root server's main loop.

Parametry

root_device

A root device identifier, returned by gupnp_root_device_new().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_root_device_start() - Start main loop

gupnp_root_device_start
gupnp_service_action_get
Gupnp Funkcje


Retrieves the specified action arguments

gupnp_root_device_stop
gupnp_service_action_return_error
Gupnp Funkcje
PHP Manual

gupnp_service_action_get

(PECL gupnp >= 0.1.0)

gupnp_service_action_get — Retrieves the specified action arguments

Opis

mixed gupnp_service_action_get ( resource $action , string $name , int $type )

Retrieves the specified action arguments.

Parametry

action

A service action identifier.

name

The name of the variable to retrieve.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Zwracane wartości

The value of the variable.

Błędy/Wyjątki

Issues E_WARNING with not correctly defined type of the variable.

Zobacz też:

  • gupnp_service_action_set() - Sets the specified action return values

gupnp_root_device_stop
gupnp_service_action_return_error
Gupnp Funkcje


Return error code

gupnp_service_action_get
gupnp_service_action_return
Gupnp Funkcje
PHP Manual

gupnp_service_action_return_error

(PECL gupnp >= 0.1.0)

gupnp_service_action_return_error — Return error code

Opis

bool gupnp_service_action_return_error ( resource $action , int $error_code [, string $error_description ] )

Return error code.

Parametry

action

A service action identifier.

error_code

The error code. Signal can be one of the following values or user defined:

GUPNP_CONTROL_ERROR_INVALID_ACTION
The action name was invalid.
GUPNP_CONTROL_ERROR_INVALID_ARGS
The action arguments were invalid.
GUPNP_CONTROL_ERROR_OUT_OF_SYNC
Out of sync (deprecated).
GUPNP_CONTROL_ERROR_ACTION_FAILED
The action failed.

error_description

The error description.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_service_action_return() - Return succesfully

gupnp_service_action_get
gupnp_service_action_return
Gupnp Funkcje


Return succesfully

gupnp_service_action_return_error
gupnp_service_action_set
Gupnp Funkcje
PHP Manual

gupnp_service_action_return

(PECL gupnp >= 0.1.0)

gupnp_service_action_return — Return succesfully

Opis

bool gupnp_service_action_return ( resource $action )

Return succesfully.

Parametry

action

A service action identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_service_action_return_error() - Return error code

gupnp_service_action_return_error
gupnp_service_action_set
Gupnp Funkcje


Sets the specified action return values

gupnp_service_action_return
gupnp_service_freeze_notify
Gupnp Funkcje
PHP Manual

gupnp_service_action_set

(PECL gupnp >= 0.1.0)

gupnp_service_action_set — Sets the specified action return values

Opis

bool gupnp_service_action_set ( resource $action , string $name , int $type , mixed $value )

Sets the specified action return values.

Parametry

action

A service action identifier.

name

The name of the variable to retrieve.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

value

The value of the variable to retrieve.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Issues E_WARNING with neither not correctly defined type of the variable or the value is not corresponding to the defined type.

Zobacz też:

  • gupnp_service_action_get() - Retrieves the specified action arguments

gupnp_service_action_return
gupnp_service_freeze_notify
Gupnp Funkcje


Freeze new notifications

gupnp_service_action_set
gupnp_service_info_get_introspection
Gupnp Funkcje
PHP Manual

gupnp_service_freeze_notify

(PECL gupnp >= 0.1.0)

gupnp_service_freeze_notify — Freeze new notifications

Opis

bool gupnp_service_freeze_notify ( resource $service )

Causes new notifications to be queued up until gupnp_service_thaw_notify() is called.

Parametry

service

A service identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_service_notify() - Notifies listening clients
  • gupnp_service_thaw_notify() - Sends out any pending notifications and stops queuing of new ones.

gupnp_service_action_set
gupnp_service_info_get_introspection
Gupnp Funkcje


Get resource introspection of service

gupnp_service_freeze_notify
gupnp_service_info_get
Gupnp Funkcje
PHP Manual

gupnp_service_info_get_introspection

(PECL gupnp >= 0.1.0)

gupnp_service_info_get_introspection — Get resource introspection of service

Opis

mixed gupnp_service_info_get_introspection ( resource $proxy [, mixed $callback [, mixed $arg ]] )

Get resource introspection of service or register callback if corresponding parameter was passed.

Parametry

proxy

A service proxy identifier.

callback

The callback function to be called when introspection object is ready. Typically, callback function takes on three parameters. The introspection parameter's identifier being the first, error parameter's message being the second, and the arg is third.

arg

User data for callback.

Zwracane wartości

Return true if callback function was defined. Return introspection identifier if callback function was omited.

Błędy/Wyjątki

Issues E_WARNING with not valid callback function.

gupnp_service_freeze_notify
gupnp_service_info_get
Gupnp Funkcje


Get full info of service

gupnp_service_info_get_introspection
gupnp_service_introspection_get_state_variable
Gupnp Funkcje
PHP Manual

gupnp_service_info_get

(PECL gupnp >= 0.1.0)

gupnp_service_info_get — Get full info of service

Opis

array gupnp_service_info_get ( resource $proxy )

Get full info of service.

Parametry

proxy

A service proxy identifier.

Zwracane wartości

Return array wich contains the information of the service (like location, url, udn and etc).

gupnp_service_info_get_introspection
gupnp_service_introspection_get_state_variable
Gupnp Funkcje


Returns the state variable data

gupnp_service_info_get
gupnp_service_notify
Gupnp Funkcje
PHP Manual

gupnp_service_introspection_get_state_variable

(PECL gupnp >= 0.1.0)

gupnp_service_introspection_get_state_variable — Returns the state variable data

Opis

array gupnp_service_introspection_get_state_variable ( resource $introspection , string $variable_name )

Returns the state variable data by the name variable_name in this service.

Parametry

introspection

A introspection identifier.

variable_name

The name of the variable to retreive.

Zwracane wartości

Return the state variable data or FALSE.

gupnp_service_info_get
gupnp_service_notify
Gupnp Funkcje


Notifies listening clients

gupnp_service_introspection_get_state_variable
gupnp_service_proxy_action_get
Gupnp Funkcje
PHP Manual

gupnp_service_notify

(PECL gupnp >= 0.1.0)

gupnp_service_notify — Notifies listening clients

Opis

bool gupnp_service_notify ( resource $service , string $name , int $type , mixed $value )

Notifies listening clients that the property have changed to the specified values.

Parametry

service

A service identifier.

name

The name of the variable.

type

The type of the variable. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

value

The value of the variable.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Issues E_WARNING with either not correctly defined type of the variable or the value is not corresponding to the defined type.

Zobacz też:

  • gupnp_service_freeze_notify() - Freeze new notifications
  • gupnp_service_thaw_notify() - Sends out any pending notifications and stops queuing of new ones.

gupnp_service_introspection_get_state_variable
gupnp_service_proxy_action_get
Gupnp Funkcje


Send action to the service and get value

gupnp_service_notify
gupnp_service_proxy_action_set
Gupnp Funkcje
PHP Manual

gupnp_service_proxy_action_get

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_action_get — Send action to the service and get value

Opis

mixed gupnp_service_proxy_action_get ( resource $proxy , string $action , string $name , int $type )

Send action with parameters to the service exposed by proxy synchronously and get value.

Parametry

proxy

A service proxy identifier.

action

An action.

name

The action name.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Zwracane wartości

Return value of the action.

Błędy/Wyjątki

Issues E_WARNING with either not correctly defined type of the action or unable to send action.

Zobacz też:

  • gupnp_service_proxy_action_set() - Send action to the service and set value
  • gupnp_service_proxy_send_action() - Send action with multiple parameters synchronously

gupnp_service_notify
gupnp_service_proxy_action_set
Gupnp Funkcje


Send action to the service and set value

gupnp_service_proxy_action_get
gupnp_service_proxy_add_notify
Gupnp Funkcje
PHP Manual

gupnp_service_proxy_action_set

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_action_set — Send action to the service and set value

Opis

bool gupnp_service_proxy_action_set ( resource $proxy , string $action , string $name , mixed $value , int $type )

Send action with parameters to the service exposed by proxy synchronously and set value.

Parametry

proxy

A service proxy identifier.

action

An action.

name

The action name.

value

The action value.

type

The type of the action. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Issues E_WARNING with either not correctly defined type of the action or unable to send action.

Zobacz też:

  • gupnp_service_proxy_action_get() - Send action to the service and get value
  • gupnp_service_proxy_send_action() - Send action with multiple parameters synchronously

gupnp_service_proxy_action_get
gupnp_service_proxy_add_notify
Gupnp Funkcje


Sets up callback for variable change notification

gupnp_service_proxy_action_set
gupnp_service_proxy_callback_set
Gupnp Funkcje
PHP Manual

gupnp_service_proxy_add_notify

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_add_notify — Sets up callback for variable change notification

Opis

bool gupnp_service_proxy_add_notify ( resource $proxy , string $value , int $type , mixed $callback [, mixed $arg ] )

Sets up callback to be called whenever a change notification for variable is recieved.

Parametry

proxy

A service proxy identifier.

value

The variable to add notification for.

type

The type of the variable. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

callback

The callback to call when variable changes. Typically, callback function takes on three parameters. The variable parameter being the first, value parameter being the second, and the arg is third.

arg

User data for callback.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_service_proxy_remove_notify() - Cancels the variable change notification

gupnp_service_proxy_action_set
gupnp_service_proxy_callback_set
Gupnp Funkcje


Set service proxy callback for signal

gupnp_service_proxy_add_notify
gupnp_service_proxy_get_subscribed
Gupnp Funkcje
PHP Manual

gupnp_service_proxy_callback_set

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_callback_set — Set service proxy callback for signal

Opis

bool gupnp_service_proxy_callback_set ( resource $proxy , int $signal , mixed $callback [, mixed $arg ] )

Set service proxy callback for signal.

Parametry

proxy

A service proxy identifier.

signal

The value of signal.

GUPNP_SIGNAL_SUBSCRIPTION_LOST
Emitted whenever the subscription to this service has been lost due to an error condition.

callback

The callback function for the certain signal. Typically, callback function takes on two parameters. error parameter's message being the first, and the arg is second.

arg

User data for callback.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Issues E_WARNING either with not valid callback function or with not valid signal.

gupnp_service_proxy_add_notify
gupnp_service_proxy_get_subscribed
Gupnp Funkcje


Check whether subscription is valid to the service

gupnp_service_proxy_callback_set
gupnp_service_proxy_remove_notify
Gupnp Funkcje
PHP Manual

gupnp_service_proxy_get_subscribed

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service

Opis

bool gupnp_service_proxy_get_subscribed ( resource $proxy )

Check whether subscription is valid to the service.

Parametry

proxy

A service proxy identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_service_proxy_set_subscribed() - (Un)subscribes to the service.

gupnp_service_proxy_callback_set
gupnp_service_proxy_remove_notify
Gupnp Funkcje


Cancels the variable change notification

gupnp_service_proxy_get_subscribed
gupnp_service_proxy_send_action
Gupnp Funkcje
PHP Manual

gupnp_service_proxy_remove_notify

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_remove_notify — Cancels the variable change notification

Opis

bool gupnp_service_proxy_remove_notify ( resource $proxy , string $value )

Cancels the variable change notification.

Parametry

proxy

A service proxy identifier.

value

The variable to add notification for.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_service_proxy_add_notify() - Sets up callback for variable change notification

gupnp_service_proxy_get_subscribed
gupnp_service_proxy_send_action
Gupnp Funkcje


Send action with multiple parameters synchronously

gupnp_service_proxy_remove_notify
gupnp_service_proxy_set_subscribed
Gupnp Funkcje
PHP Manual

gupnp_service_proxy_send_action

(PECL gupnp >= 0.2.0)

gupnp_service_proxy_send_action — Send action with multiple parameters synchronously

Opis

array gupnp_service_proxy_send_action ( resource $proxy , string $action , array $in_params , array $out_params )

Send action action with parameters in_params to the service exposed by proxy synchronously and return out_params with values or FALSE on error.

Parametry

proxy

A service proxy identifier.

action

An action.

in_params

An array of in parameters. Each entry in in_params is supposed to an array containing name, type and value of the parameters.

out_params

An array of out parameters. Each entry in out_params is supposed to an array containing name and type of the parameters.

Zwracane wartości

Return out_params array with values or FALSE on error.

Błędy/Wyjątki

Issues E_WARNING with either not correctly defined in_params and out_params or unable to send action.

Zobacz też:

  • gupnp_service_proxy_action_get() - Send action to the service and get value
  • gupnp_service_proxy_action_set() - Send action to the service and set value

gupnp_service_proxy_remove_notify
gupnp_service_proxy_set_subscribed
Gupnp Funkcje


(Un)subscribes to the service.

gupnp_service_proxy_send_action
gupnp_service_thaw_notify
Gupnp Funkcje
PHP Manual

gupnp_service_proxy_set_subscribed

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_set_subscribed — (Un)subscribes to the service.

Opis

bool gupnp_service_proxy_set_subscribed ( resource $proxy , bool $subscribed )

(Un)subscribes to the service.

Parametry

proxy

A service proxy identifier.

subscribed

Set TRUE to subscribe to this service.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_service_proxy_get_subscribed() - Check whether subscription is valid to the service

gupnp_service_proxy_send_action
gupnp_service_thaw_notify
Gupnp Funkcje


Sends out any pending notifications and stops queuing of new ones.

gupnp_service_proxy_set_subscribed
HTTP
Gupnp Funkcje
PHP Manual

gupnp_service_thaw_notify

(PECL gupnp >= 0.1.0)

gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones.

Opis

bool gupnp_service_thaw_notify ( resource $service )

Sends out any pending notifications and stops queuing of new ones.

Parametry

service

A service identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • gupnp_service_notify() - Notifies listening clients
  • gupnp_service_freeze_notify() - Freeze new notifications

gupnp_service_proxy_set_subscribed
HTTP
Gupnp Funkcje


HTTP

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Installing the HTTP extension — Installation/Configuration
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Request Options — Options usable with the HttpRequest class and request functions
  • HttpDeflateStream — The HttpDeflateStream class
    • HttpDeflateStream::__construct — HttpDeflateStream class constructor
    • HttpDeflateStream::factory — HttpDeflateStream class factory
    • HttpDeflateStream::finish — Finalize deflate stream
    • HttpDeflateStream::flush — Flush deflate stream
    • HttpDeflateStream::update — Update deflate stream
  • HttpInflateStream — The HttpInflateStream class
    • HttpInflateStream::__construct — HttpInflateStream class constructor
    • HttpInflateStream::factory — HttpInflateStream class factory
    • HttpInflateStream::finish — Finalize inflate stream
    • HttpInflateStream::flush — Flush inflate stream
    • HttpInflateStream::update — Update inflate stream
  • HttpMessage — The HttpMessage class
    • HttpMessage::addHeaders — Add headers
    • HttpMessage::__construct — HttpMessage constructor
    • HttpMessage::detach — Detach HttpMessage
    • HttpMessage::factory — Create HttpMessage from string
    • HttpMessage::fromEnv — Create HttpMessage from environment
    • HttpMessage::fromString — Create HttpMessage from string
    • HttpMessage::getBody — Get message body
    • HttpMessage::getHeader — Get header
    • HttpMessage::getHeaders — Get message headers
    • HttpMessage::getHttpVersion — Get HTTP version
    • HttpMessage::getParentMessage — Get parent message
    • HttpMessage::getRequestMethod — Get request method
    • HttpMessage::getRequestUrl — Get request URL
    • HttpMessage::getResponseCode — Get response code
    • HttpMessage::getResponseStatus — Get response status
    • HttpMessage::getType — Get message type
    • HttpMessage::guessContentType — Guess content type
    • HttpMessage::prepend — Prepend message(s)
    • HttpMessage::reverse — Reverse message chain
    • HttpMessage::send — Send message
    • HttpMessage::setBody — Set message body
    • HttpMessage::setHeaders — Set headers
    • HttpMessage::setHttpVersion — Set HTTP version
    • HttpMessage::setRequestMethod — Set request method
    • HttpMessage::setRequestUrl — Set request URL
    • HttpMessage::setResponseCode — Set response code
    • HttpMessage::setResponseStatus — Set response status
    • HttpMessage::setType — Set message type
    • HttpMessage::toMessageTypeObject — Create HTTP object regarding message type
    • HttpMessage::toString — Get string representation
  • HttpQueryString — The HttpQueryString class
    • HttpQueryString::__construct — HttpQueryString constructor
    • HttpQueryString::get — Get (part of) query string
    • HttpQueryString::mod — Modifiy query string copy
    • HttpQueryString::set — Set query string params
    • HttpQueryString::singleton — HttpQueryString singleton
    • HttpQueryString::toArray — Get query string as array
    • HttpQueryString::toString — Get query string
    • HttpQueryString::xlate — Change query strings charset
  • HttpRequest — The HttpRequest
    • HttpRequest::addCookies — Add cookies
    • HttpRequest::addHeaders — Add headers
    • HttpRequest::addPostFields — Add post fields
    • HttpRequest::addPostFile — Add post file
    • HttpRequest::addPutData — Add put data
    • HttpRequest::addQueryData — Add query data
    • HttpRequest::addRawPostData — Add raw post data
    • HttpRequest::addSslOptions — Add ssl options
    • HttpRequest::clearHistory — Clear history
    • HttpRequest::__construct — HttpRequest constructor
    • HttpRequest::enableCookies — Enable cookies
    • HttpRequest::getContentType — Get content type
    • HttpRequest::getCookies — Get cookies
    • HttpRequest::getHeaders — Get headers
    • HttpRequest::getHistory — Get history
    • HttpRequest::getMethod — Get method
    • HttpRequest::getOptions — Get options
    • HttpRequest::getPostFields — Get post fields
    • HttpRequest::getPostFiles — Get post files
    • HttpRequest::getPutData — Get put data
    • HttpRequest::getPutFile — Get put file
    • HttpRequest::getQueryData — Get query data
    • HttpRequest::getRawPostData — Get raw post data
    • HttpRequest::getRawRequestMessage — Get raw request message
    • HttpRequest::getRawResponseMessage — Get raw response message
    • HttpRequest::getRequestMessage — Get request message
    • HttpRequest::getResponseBody — Get response body
    • HttpRequest::getResponseCode — Get response code
    • HttpRequest::getResponseCookies — Get response cookie(s)
    • HttpRequest::getResponseData — Get response data
    • HttpRequest::getResponseHeader — Get response header(s)
    • HttpRequest::getResponseInfo — Get response info
    • HttpRequest::getResponseMessage — Get response message
    • HttpRequest::getResponseStatus — Get response status
    • HttpRequest::getSslOptions — Get ssl options
    • HttpRequest::getUrl — Get url
    • HttpRequest::resetCookies — Reset cookies
    • HttpRequest::send — Send request
    • HttpRequest::setBody — Set request body to send, overwriting previously set request body.
    • HttpRequest::setContentType — Set content type
    • HttpRequest::setCookies — Set cookies
    • HttpRequest::setHeaders — Set headers
    • HttpRequest::setMethod — Set method
    • HttpRequest::setOptions — Set options
    • HttpRequest::setPostFields — Set post fields
    • HttpRequest::setPostFiles — Set post files
    • HttpRequest::setPutData — Set put data
    • HttpRequest::setPutFile — Set put file
    • HttpRequest::setQueryData — Set query data
    • HttpRequest::setRawPostData — Set raw post data
    • HttpRequest::setSslOptions — Set ssl options
    • HttpRequest::setUrl — Set URL
  • HttpRequestPool — The HttpRequestPool class
    • HttpRequestPool::attach — Attach HttpRequest
    • HttpRequestPool::__construct — HttpRequestPool constructor
    • HttpRequestPool::__destruct — HttpRequestPool destructor
    • HttpRequestPool::detach — Detach HttpRequest
    • HttpRequestPool::getAttachedRequests — Get attached requests
    • HttpRequestPool::getFinishedRequests — Get finished requests
    • HttpRequestPool::reset — Reset request pool
    • HttpRequestPool::send — Send all requests
    • HttpRequestPool::socketPerform — Perform socket actions
    • HttpRequestPool::socketSelect — Perform socket select
  • HttpResponse — The HttpResponse
    • HttpResponse::capture — Capture script output
    • HttpResponse::getBufferSize — Get buffer size
    • HttpResponse::getCache — Get cache
    • HttpResponse::getCacheControl — Get cache control
    • HttpResponse::getContentDisposition — Get content disposition
    • HttpResponse::getContentType — Get content type
    • HttpResponse::getData — Get data
    • HttpResponse::getETag — Get ETag
    • HttpResponse::getFile — Get file
    • HttpResponse::getGzip — Get gzip
    • HttpResponse::getHeader — Get header
    • HttpResponse::getLastModified — Get last modified
    • HttpResponse::getRequestBody — Get request body
    • HttpResponse::getRequestBodyStream — Get request body stream
    • HttpResponse::getRequestHeaders — Get request headers
    • HttpResponse::getStream — Get Stream
    • HttpResponse::getThrottleDelay — Get throttle delay
    • HttpResponse::guessContentType — Guess content type
    • HttpResponse::redirect — Redirect
    • HttpResponse::send — Send response
    • HttpResponse::setBufferSize — Set buffer size
    • HttpResponse::setCache — Set cache
    • HttpResponse::setCacheControl — Set cache control
    • HttpResponse::setContentDisposition — Set content disposition
    • HttpResponse::setContentType — Set content type
    • HttpResponse::setData — Set data
    • HttpResponse::setETag — Set ETag
    • HttpResponse::setFile — Set file
    • HttpResponse::setGzip — Set gzip
    • HttpResponse::setHeader — Set header
    • HttpResponse::setLastModified — Set last modified
    • HttpResponse::setStream — Set stream
    • HttpResponse::setThrottleDelay — Set throttle delay
    • HttpResponse::status — Send HTTP response status
  • HTTP Funkcje
    • http_cache_etag — Caching by ETag
    • http_cache_last_modified — Caching by last modification
    • http_chunked_decode — Decode chunked-encoded data
    • http_deflate — Deflate data
    • http_inflate — Inflate data
    • http_build_cookie — Build cookie string
    • http_date — Compose HTTP RFC compliant date
    • http_get_request_body_stream — Get request body as stream
    • http_get_request_body — Get request body as string
    • http_get_request_headers — Get request headers as array
    • http_match_etag — Match ETag
    • http_match_modified — Match last modification
    • http_match_request_header — Match any header
    • http_support — Check built-in HTTP support
    • http_negotiate_charset — Negotiate clients preferred character set
    • http_negotiate_content_type — Negotiate clients preferred content type
    • http_negotiate_language — Negotiate clients preferred language
    • ob_deflatehandler — Deflate output handler
    • ob_etaghandler — ETag output handler
    • ob_inflatehandler — Inflate output handler
    • http_parse_cookie — Parse HTTP cookie
    • http_parse_headers — Parse HTTP headers
    • http_parse_message — Parse HTTP messages
    • http_parse_params — Parse parameter list
    • http_persistent_handles_clean — Clean up persistent handles
    • http_persistent_handles_count — Stat persistent handles
    • http_persistent_handles_ident — Get/set ident of persistent handles
    • http_get — Perform GET request
    • http_head — Perform HEAD request
    • http_post_data — Perform POST request with pre-encoded data
    • http_post_fields — Perform POST request with data to be encoded
    • http_put_data — Perform PUT request with data
    • http_put_file — Perform PUT request with file
    • http_put_stream — Perform PUT request with stream
    • http_request_body_encode — Encode request body
    • http_request_method_exists — Check whether request method exists
    • http_request_method_name — Get request method name
    • http_request_method_register — Register request method
    • http_request_method_unregister — Unregister request method
    • http_request — Perform custom request
    • http_redirect — Issue HTTP redirect
    • http_send_content_disposition — Send Content-Disposition
    • http_send_content_type — Send Content-Type
    • http_send_data — Send arbitrary data
    • http_send_file — Send file
    • http_send_last_modified — Send Last-Modified
    • http_send_status — Send HTTP response status
    • http_send_stream — Send stream
    • http_throttle — HTTP throttling
    • http_build_str — Build query string
    • http_build_url — Build a URL
gupnp_service_thaw_notify
Wstęp
Inne serwisy


Wstęp

Celem rozszerzenia HTTP jest dostarczenie wygodnego i potężnego zbioru funkcjonalności dla jednych z głównych zastosowań PHP.

Ułatwia obsługę HTTPowych adresów, dat, przekierowań, nagłówków i wiadomości, dostarcza sposobów negocjacji z klientami preferowanego języka i kodowania znaków, w tak wygodny sposób jak wysyłanie dowolnych danych z możliwością buforowania i wznawiania.

Dostarcza potężnego mechanizmu żądań, jeśli jest zbudowany z obsługą CURL'a. Równoległe żądania są dostępne dla PHP 5 lub wyżej.

Dodatkowo w adnotacji o API w tym podręczniku możesz znaleźć informację na temat instalacji i konfiguracji a także jakie globalne stałe zostały predefiniowane. Więcej w następujących sekcjach:

HTTP
Instalacja/Konfiguracja
HTTP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Installing the HTTP extension
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
HTTP


Wymagania

Klasa HttpResponse wymaga przynajmniej PHP v5.1. Każda inna klasa jest dostępna od PHP v5.0.

Informacja: Poczuj się ostrzeżony, że niektóre metody nie są dostępne z PHP v5.0.

Wymagania instalacyjne pod Windows

Aby mozliwe było załadowanie rozszerzenia pod Windows, musisz dodatkowo załadować następujące rozszerzenia PHP: hash, iconv i SPL.

Wymagania instalacyjne na inne platformy

Rozszerzenie musi być zbudowane ze wsparciem » libcurl aby włączyć funkcjonalność zapytań (--with-http-curl-requests). Wymagana jest wersja biblioteki nowsza lub równa v7.12.3.

Aby włączyć obsługę wysyłania i odbierania skompresowanych odpowiedzi, rozszerzenie musi byc zbudowane ze wsparciem » zlib (--with-http-zlib-compression). Wymagana jest wersja biblioteki nowsza lub równa v1.2.2.

Odgadywanie rodzaju treści może być włączone poprzez zbudowanie tego rozszerzenia z obsługą » libmagic (--with-http-magic-mime).

Instalacja/Konfiguracja
Installing the HTTP extension
Instalacja/Konfiguracja


Installation/Configuration

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/pecl_http.

Informacja: The official name of this extension is pecl_http.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

HTTP Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Opis
http.etag.mode | "MD5" | PHP_INI_ALL | The hashing algorithm used to generate the ETag. MD5, SHA1, and CRC32 are always available. If the hash extension is enabled, any hashing algorithms this extension provides are available, too.
http.log.cache | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write successful cache hits.
http.log.redirect | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write redirects.
http.log.not_found | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write "file not found" errors.
http.log.allowed_methods | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write "allowed methods" violations.
http.log.composite | "" | PHP_INI_ALL | The path (or stream wrapper url) to a log file in which to write all events.
http.request.methods.allowed | "" | PHP_INI_ALL | Allowed request methods. If a client issues a request with a request method other than listed here, PHP exits with a status of "405 Method not allowed". Patrz ustawienia INI http.force_exit co znaczą "exist".
http.request.methods.custom | "" | PHP_INI_PERDIR|PHP_INI_SYSTEM | Custom request methods. If you want to use any non-standard request methods, you can register them with this INI setting or http_request_method_register().
http.request.datashare.cookie | "0" | PHP_INI_SYSTEM | Whether the global HttpRequestDataShare should by default share cookie information.
http.request.datashare.dns | "1" | PHP_INI_SYSTEM | Whether the global HttpRequestDataShare should by default share name lookup information.
http.request.datashare.ssl | "0" | PHP_INI_SYSTEM | Whether the global HttpRequestDataShare should by default share SSL session information. This is not yet implemented in libcurl.
http.request.datashare.connect | "0" | PHP_INI_SYSTEM | Whether the global HttpRequestDataShare should by default share connect information. This is not yet implemented in libcurl.
http.persistent.handles.limit | "-1" | PHP_INI_SYSTEM | The maximum amount of persistent handles to keep alive.
http.persistent.handles.ident | "GLOBAL" | PHP_INI_ALL | The ident of persistent handles.
http.send.inflate.start_auto | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM | Whether to automatically start the inflate output handler.
http.send.inflate.start_flags | "0" | PHP_INI_ALL | Initialization settings for the inflate output handler.
http.send.deflate.start_auto | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM | Whether to automatically start the deflate output handler.
http.send.deflate.start_flags | "0" | PHP_INI_ALL | Initialization settings for the deflate output handler. See deflate constants.
http.send.not_found_404 | "1" | PHP_INI_ALL | Whether to automatically exit with a status of "404 Not found", if http_send_file() was not able to find the specified file. Patrz ustawienia INI http.force_exit co znaczą "exist".
http.only_exceptions | "0" | PHP_INI_ALL | Whether all notices/warnings/errors should be thrown as exceptions.
http.force_exit | "1" | PHP_INI_ALL | Each occasion where "exits with a status of..." is mentioned, usually causes the halt of the scripting engine. Disable this option if you alternatively want to start a discarding (dev/null) output handler and continue script execution.

Installing the HTTP extension
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines a stream resource returned by http_get_request_body_stream() and (thereafter) HttpResponse::getStream().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

Constants usable with http_support()
HTTP_SUPPORT (integer)
querying for this constant will always return TRUE
HTTP_SUPPORT_REQUESTS (integer)
whether support to issue HTTP requests is given, ie. libcurl support was compiled in
HTTP_SUPPORT_MAGICMIME (integer)
whether support to guess the Content-Type of HTTP messages is given, ie. libmagic support was compiled in
HTTP_SUPPORT_ENCODINGS (integer)
whether support for zlib encodings is given, ie. libz support was compiled in
HTTP_SUPPORT_SSLREQUESTS (integer)
whether support to issue HTTP requests over SSL is given, ie. linked libcurl was built with SSL support
Constants usable with http_parse_params()
HTTP_PARAMS_ALLOW_COMMA (integer)
allow commands additionally to semicolons as separator
HTTP_PARAMS_ALLOW_FAILURE (integer)
continue parsing after an error occurred
HTTP_PARAMS_RAISE_ERROR (integer)
raise PHP warnings on parse errors
HTTP_PARAMS_DEFAULT (integer)
all three values above, bitwise or'ed
Constants usable with http_parse_cookie() and its return value
HTTP_COOKIE_PARSE_RAW (integer)
don't urldecode values
HTTP_COOKIE_SECURE (integer)
whether "secure" was found in the cookie's parameters list
HTTP_COOKIE_HTTPONLY (integer)
whether "httpOnly" was found in the cookie's parameter list
Constants usable with http_deflate() and HttpDeflateStream
HTTP_DEFLATE_LEVEL_DEF (integer)
HTTP_DEFLATE_LEVEL_MIN (integer)
HTTP_DEFLATE_LEVEL_MAX (integer)
HTTP_DEFLATE_TYPE_ZLIB (integer)
HTTP_DEFLATE_TYPE_GZIP (integer)
HTTP_DEFLATE_TYPE_RAW (integer)
HTTP_DEFLATE_STRATEGY_DEF (integer)
HTTP_DEFLATE_STRATEGY_FILT (integer)
HTTP_DEFLATE_STRATEGY_HUFF (integer)
HTTP_DEFLATE_STRATEGY_RLE (integer)
HTTP_DEFLATE_STRATEGY_FIXED (integer)
Constants usable with HttpDeflateStream and HttpInflateStream
HTTP_ENCODING_STREAM_FLUSH_NONE (integer)
don't flush
HTTP_ENCODING_STREAM_FLUSH_SYNC (integer)
synchronized flush only
HTTP_ENCODING_STREAM_FLUSH_FULL (integer)
full data flush
Constants used for error reporting and Exceptions
HTTP_E_RUNTIME (integer)
runtime error
HTTP_E_INVALID_PARAM (integer)
an invalid parameter was passed
HTTP_E_HEADER (integer)
header() or similar operation failed
HTTP_E_MALFORMED_HEADERS (integer)
HTTP header parse error
HTTP_E_REQUEST_METHOD (integer)
unknown/invalid request method
HTTP_E_MESSAGE_TYPE (integer)
with operation incompatible message type
HTTP_E_ENCODING (integer)
encoding/decoding error
HTTP_E_REQUEST (integer)
request failure
HTTP_E_REQUEST_POOL (integer)
request pool failure
HTTP_E_SOCKET (integer)
socket exception
HTTP_E_RESPONSE (integer)
response failure
HTTP_E_URL (integer)
invalid URL
HTTP_E_QUERYSTRING (integer)
querystring operation failure
Constants usable with HttpMessage
HTTP_MSG_NONE (integer)
the message is of no specific type
HTTP_MSG_REQUEST (integer)
request style message
HTTP_MSG_RESPONSE (integer)
response style message
Constants usable with HttpQueryString
HTTP_QUERYSTRING_TYPE_BOOL (integer)
HTTP_QUERYSTRING_TYPE_INT (integer)
HTTP_QUERYSTRING_TYPE_FLOAT (integer)
HTTP_QUERYSTRING_TYPE_STRING (integer)
HTTP_QUERYSTRING_TYPE_ARRAY (integer)
HTTP_QUERYSTRING_TYPE_OBJECT (integer)
Constants used for the httpauthtype Opcja żądania
HTTP_AUTH_BASIC (integer)
use "basic" authentication
HTTP_AUTH_DIGEST (integer)
use "digest" authentication
HTTP_AUTH_NTLM (integer)
use "NTLM" authentication
HTTP_AUTH_GSSNEG (integer)
use "GSS-NEGOTIATE" authentication
HTTP_AUTH_ANY (integer)
try any authentication scheme
Constants used for the HTTP protocol version Opcja żądania
HTTP_VERSION_ANY (integer)
no specific HTTP protocol version
HTTP_VERSION_1_0 (integer)
HTTP version 1.0
HTTP_VERSION_1_1 (integer)
HTTP version 1.1
Constants used for the SSL protocol type and version Opcja żądania
HTTP_SSL_VERSION_ANY (integer)
no specific SSL protocol version
HTTP_SSL_VERSION_TLSv1 (integer)
use TLSv1 only
HTTP_SSL_VERSION_SSLv3 (integer)
use SSLv3 only
HTTP_SSL_VERSION_SSLv2 (integer)
use SSLv2 only
Constants used for the proxytype Opcja żądania
HTTP_PROXY_SOCKS4 (integer)
the proxy is a SOCKS4 type proxy
HTTP_PROXY_SOCKS5 (integer)
the proxy is a SOCKS5 type proxy
HTTP_PROXY_HTTP (integer)
standard HTTP proxy
Constants used for the ipresolve Opcja żądania
HTTP_IPRESOLVE_V4 (integer)
use IPv4 only for name lookups
HTTP_IPRESOLVE_V6 (integer)
use IPv6 only for name lookups
HTTP_IPRESOLVE_ANY (integer)
use any IP mechanism only for name lookups
Predefined HTTP request method constants
HTTP_METH_GET (integer)
HTTP_METH_HEAD (integer)
HTTP_METH_POST (integer)
HTTP_METH_PUT (integer)
HTTP_METH_DELETE (integer)
HTTP_METH_OPTIONS (integer)
HTTP_METH_TRACE (integer)
HTTP_METH_CONNECT (integer)
HTTP_METH_PROPFIND (integer)
HTTP_METH_PROPPATCH (integer)
HTTP_METH_MKCOL (integer)
HTTP_METH_COPY (integer)
HTTP_METH_MOVE (integer)
HTTP_METH_LOCK (integer)
HTTP_METH_UNLOCK (integer)
HTTP_METH_VERSION_CONTROL (integer)
HTTP_METH_REPORT (integer)
HTTP_METH_CHECKOUT (integer)
HTTP_METH_CHECKIN (integer)
HTTP_METH_UNCHECKOUT (integer)
HTTP_METH_MKWORKSPACE (integer)
HTTP_METH_UPDATE (integer)
HTTP_METH_LABEL (integer)
HTTP_METH_MERGE (integer)
HTTP_METH_BASELINE_CONTROL (integer)
HTTP_METH_MKACTIVITY (integer)
HTTP_METH_ACL (integer)
Constants usable with http_redirect()
HTTP_REDIRECT (integer)
guess applicable redirect method
HTTP_REDIRECT_PERM (integer)
permanent redirect (301 Moved permanently)
HTTP_REDIRECT_FOUND (integer)
standard redirect (302 Found)

Informacja: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

HTTP_REDIRECT_POST (integer)
redirect applicable to POST requests (303 See other)
HTTP_REDIRECT_PROXY (integer)
proxy redirect (305 Use proxy)
HTTP_REDIRECT_TEMP (integer)
temporary redirect (307 Temporary Redirect)
Constants usable with http_build_url()
HTTP_URL_REPLACE (integer)
replace every part of the first URL when there's one of the second URL
HTTP_URL_JOIN_PATH (integer)
join relative paths
HTTP_URL_JOIN_QUERY (integer)
join query strings
HTTP_URL_STRIP_USER (integer)
strip any user authentication information
HTTP_URL_STRIP_PASS (integer)
strip any password authentication information
HTTP_URL_STRIP_AUTH (integer)
strip any authentication information
HTTP_URL_STRIP_PORT (integer)
strip explicit port numbers
HTTP_URL_STRIP_PATH (integer)
strip complete path
HTTP_URL_STRIP_QUERY (integer)
strip query string
HTTP_URL_STRIP_FRAGMENT (integer)
strip any fragments (#identifier)
HTTP_URL_STRIP_ALL (integer)
strip anything but scheme and host
Typy zasobów
Request Options
HTTP


Options usable with the HttpRequest class and request functions

Options related to time outs
timeout (integer)
seconds the whole request may take to complete
connecttimeout (integer)
seconds the connect, including name resolving, may take
dns_cache_timeout (integer)
seconds after an dns cache entry times out
Options related to urls
url (string)
the request url
port (integer)
use another port as specified in the url
redirect (integer)
whether and how many redirects to follow; defaults to 0
unrestrictedauth (bool)
whether to continue sending credentials on redirects to a different host
referer (string)
the referring url to send
Options related to cookies
encodecookies (bool)
whether custom cookies should be urlencode()d prior sending
cookies (array)
list of cookies as associative array like array("cookie" => "value")
cookiestore (string)
path to a file where cookies are/will be stored
cookiesession (bool)
don't load session cookies from cookiestore if TRUE
Options related to headers
useragent (string)
the user agent to send; defaults to PECL::HTTP/x.y.z (PHP/x.y.z); omitted if explicitly set to an empty string
lastmodified (int)
timestamp for If-(Un)Modified-Since header
etag (string)
quoted etag for If-(None-)Match header
headers (array)
list of custom headers as associative array like array("header" => "value")
Options related to authentication
httpauth (string)
http credentials in "user:pass" format
httpauthtype (int)
HTTP authentication type constant
(array)
Options related to proxies
proxyhost (string)
proxy host in "host[:port]" format
proxyport (int)
use another proxy port as specified in proxyhost
proxytype (int)
HTTP proxy type constant
proxyauth (string)
proxy credentials in "user:pass" format
proxyauthtype (int)
HTTP authentication type constant
Options related to the transfer
compress (bool)
whether to request and accept a gzip/deflate content encoded response
resume (int)
start the download at the specified byte offset if server support is given (indicated by a 206 response code)
range (array)
array of arrays, each containing two integers, specifying the ranges to download if server support is given (indicated by a 206 response code); only recognized if the resume option is empty
Options imposing limits
maxfilesize (integer)
maximum file size that should be downloaded; has no effect, if the size of the requested entity is unknown (eg. dynamic pages with chunked transfer encoding etc.)
low_speed_limit (int)
the lowest transfer speed a successful request may have
low_speed_time (int)
the time in which low_speed_limit must be transferred for a successful request
max_send_speed (int)
maximum send speed in bytes per second
max_recv_speed (int)
maximum receive speed in bytes per second
Callback options
onprogress (callback)
progress callback
Network options
interface (string)
outgoing network interface (ifname, ip or hostname)
portrange (array)
2 integers specifying outgoing portrange to try
SSL options
ssl (array)

Informacja: SSL options are set through an array with the single "ssl" request option name.

cert (string)
path to certificate
certtype (string)
type of certificate
certpasswd (string)
password for certificate
key (string)
path to key
keytype (string)
type of key
keypasswd (string)
password for key
engine (string)
ssl engine to use
version (int)
ssl version to use
verifypeer (bool)
whether to verify the peer
verifyhost (bool)
whether to verify the host
cipher_list (string)
list of allowed ciphers
cainfo (string)
capath (string)
random_file (string)
egdsocket (string)
Stałe predefiniowane
HttpDeflateStream
HTTP


The HttpDeflateStream class

(No version information available, might only be in SVN)

Krótki opis klasy

HttpDeflateStream {
public __construct ([ int $flags = 0 ] )
static public HttpDeflateStream factory ([ int $flags = 0 [, string $class_name = "HttpDeflateStream" ]] )
public string finish ([ string $data ] )
public string flush ([ string $data ] )
public string update ( string $data )
}

Class Members

Stałe predefiniowane

Type | Name | Description
int | TYPE_GZIP | gzip encoding
int | TYPE_ZLIB | zlib AKA deflate encoding
int | TYPE_RAW | raw deflate encoding
int | LEVEL_DEF | default compression level
int | LEVEL_MIN | minimum compression level
int | LEVEL_MAX | maximum compression level
int | STRATEGY_DEF | default strategy
int | STRATEGY_FILT | filtered strategy
int | STRATEGY_HUFF | Huffman strategy
int | STRATEGY_RLE | RLE strategy
int | STRATEGY_FIXED | fixed strategy
int | FLUSH_NONE | no forced flush
int | FLUSH_SYNC | synching flush
int | FLUSH_FULL | full flush

Przykłady

Przykład #1 A HttpDeflateStream example

<?php
$stream = new HttpDeflateStream(
    HttpDeflateStream::TYPE_GZIP |
    HttpDeflateStream::LEVEL_MAX |
    HttpDeflateStream::FLUSH_SYNC);

echo $stream->update($data);
echo $stream->finish();
?>

Spis treści

  • HttpDeflateStream::__construct — HttpDeflateStream class constructor
  • HttpDeflateStream::factory — HttpDeflateStream class factory
  • HttpDeflateStream::finish — Finalize deflate stream
  • HttpDeflateStream::flush — Flush deflate stream
  • HttpDeflateStream::update — Update deflate stream
Request Options
HttpDeflateStream::__construct
HTTP


HttpDeflateStream class constructor

HttpDeflateStream
HttpDeflateStream::factory
HttpDeflateStream
PHP Manual

HttpDeflateStream::__construct

(PECL pecl_http >= 0.21.0)

HttpDeflateStream::__construct — HttpDeflateStream class constructor

Opis

public HttpDeflateStream::__construct ([ int $flags = 0 ] )

Creates a new HttpDeflateStream object instance.

See the deflate stream constants table for possible flags.

Parametry

flags

initialization flags

Zobacz też:

  • HttpDeflateStream::factory() - HttpDeflateStream class factory

HttpDeflateStream
HttpDeflateStream::factory
HttpDeflateStream


HttpDeflateStream class factory

HttpDeflateStream::__construct
HttpDeflateStream::finish
HttpDeflateStream
PHP Manual

HttpDeflateStream::factory

(PECL pecl_http >= 1.4.0)

HttpDeflateStream::factory — HttpDeflateStream class factory

Opis

static public HttpDeflateStream HttpDeflateStream::factory ([ int $flags = 0 [, string $class_name = "HttpDeflateStream" ]] )

Creates a new HttpDeflateStream object instance.

See the deflate stream constants table for possible flags.

Parametry

flags

initialization flags

class_name

name of a subclass of HttpDeflateStream

Zobacz też:

  • HttpDeflateStream::__construct() - HttpDeflateStream class constructor

HttpDeflateStream::__construct
HttpDeflateStream::finish
HttpDeflateStream


Finalize deflate stream

HttpDeflateStream::factory
HttpDeflateStream::flush
HttpDeflateStream
PHP Manual

HttpDeflateStream::finish

(PECL pecl_http >= 0.21.0)

HttpDeflateStream::finish — Finalize deflate stream

Opis

public string HttpDeflateStream::finish ([ string $data ] )

Finalizes the deflate stream. The deflate stream can be reused after finalizing.

Parametry

data

data to deflate

Zwracane wartości

Returns the final part of deflated data.

HttpDeflateStream::factory
HttpDeflateStream::flush
HttpDeflateStream


Flush deflate stream

HttpDeflateStream::finish
HttpDeflateStream::update
HttpDeflateStream
PHP Manual

HttpDeflateStream::flush

(PECL pecl_http >= 0.21.0)

HttpDeflateStream::flush — Flush deflate stream

Opis

public string HttpDeflateStream::flush ([ string $data ] )

Flushes the deflate stream.

Parametry

data

more data to deflate

Zwracane wartości

Returns some deflated data as string on success lub FALSE w przypadku niepowodzenia.

HttpDeflateStream::finish
HttpDeflateStream::update
HttpDeflateStream


Update deflate stream

HttpDeflateStream::flush
HttpInflateStream
HttpDeflateStream
PHP Manual

HttpDeflateStream::update

(PECL pecl_http >= 0.21.0)

HttpDeflateStream::update — Update deflate stream

Opis

public string HttpDeflateStream::update ( string $data )

Passes more data through the deflate stream.

Parametry

data

data to deflate

Zwracane wartości

Returns deflated data on success lub FALSE w przypadku niepowodzenia.

HttpDeflateStream::flush
HttpInflateStream
HttpDeflateStream


The HttpInflateStream class

(No version information available, might only be in SVN)

Krótki opis klasy

HttpInflateStream {
public __construct ([ int $flags = 0 ] )
public HttpInflateStream factory ([ int $flags = 0 [, string $class_name = "HttpInflateStream" ]] )
public string finish ([ string $data ] )
public string flush ([ string $data ] )
public string update ( string $data )
}

Class Members

Constants

Type | Name | Description
int | FLUSH_NONE | no forced flush
int | FLUSH_SYNC | synching flush
int | FLUSH_FULL | full flush

Informacja:

Flushing usually has no effect on inflate streams.

Przykłady

Przykład #1 A HttpInflateStream example

<?php
$stream = new HttpInflateStream;
echo $stream->update($data);
echo $stream->finish();
?>

Spis treści

  • HttpInflateStream::__construct — HttpInflateStream class constructor
  • HttpInflateStream::factory — HttpInflateStream class factory
  • HttpInflateStream::finish — Finalize inflate stream
  • HttpInflateStream::flush — Flush inflate stream
  • HttpInflateStream::update — Update inflate stream
HttpDeflateStream::update
HttpInflateStream::__construct
HTTP


HttpInflateStream class constructor

HttpInflateStream
HttpInflateStream::factory
HttpInflateStream
PHP Manual

HttpInflateStream::__construct

(PECL pecl_http >= 1.0.0)

HttpInflateStream::__construct — HttpInflateStream class constructor

Opis

public HttpInflateStream::__construct ([ int $flags = 0 ] )

Creates a new HttpInflateStream object instance.

See the inflate constants table for possible flags.

Parametry

flags

initialization flags

Zobacz też:

  • HttpInflateStream::factory() - HttpInflateStream class factory

HttpInflateStream
HttpInflateStream::factory
HttpInflateStream


HttpInflateStream class factory

HttpInflateStream::__construct
HttpInflateStream::finish
HttpInflateStream
PHP Manual

HttpInflateStream::factory

(PECL pecl_http >= 1.4.0)

HttpInflateStream::factory — HttpInflateStream class factory

Opis

public HttpInflateStream HttpInflateStream::factory ([ int $flags = 0 [, string $class_name = "HttpInflateStream" ]] )

Creates a new HttpInflateStream object instance.

See the inflate constants table for possible flags.

Parametry

flags

initialization flags

class_name

name of a subclass of HttpInflateStream

Zobacz też:

  • HttpInflateStream::__construct() - HttpInflateStream class constructor

HttpInflateStream::__construct
HttpInflateStream::finish
HttpInflateStream


Finalize inflate stream

HttpInflateStream::factory
HttpInflateStream::flush
HttpInflateStream
PHP Manual

HttpInflateStream::finish

(PECL pecl_http >= 0.21.0)

HttpInflateStream::finish — Finalize inflate stream

Opis

public string HttpInflateStream::finish ([ string $data ] )

Finalizes the inflate stream. The inflate stream can be reused after finalizing.

Parametry

data

data to inflate

Zwracane wartości

Returns the final part of inflated data.

HttpInflateStream::factory
HttpInflateStream::flush
HttpInflateStream


Flush inflate stream

HttpInflateStream::finish
HttpInflateStream::update
HttpInflateStream
PHP Manual

HttpInflateStream::flush

(PECL pecl_http >= 0.21.0)

HttpInflateStream::flush — Flush inflate stream

Opis

public string HttpInflateStream::flush ([ string $data ] )

Flushes the inflate stream.

Informacja:

Flushing usually has no effect on inflate streams.

Parametry

data

more data to inflate

Zwracane wartości

Returns some inflated data as string on success lub FALSE w przypadku niepowodzenia.

HttpInflateStream::finish
HttpInflateStream::update
HttpInflateStream


Update inflate stream

HttpInflateStream::flush
HttpMessage
HttpInflateStream
PHP Manual

HttpInflateStream::update

(PECL pecl_http >= 0.21.0)

HttpInflateStream::update — Update inflate stream

Opis

public string HttpInflateStream::update ( string $data )

Passes more data through the inflate stream.

Parametry

data

data to inflate

Zwracane wartości

Returns inflated data on success lub FALSE w przypadku niepowodzenia.

HttpInflateStream::flush
HttpMessage
HttpInflateStream


The HttpMessage class

(No version information available, might only be in SVN)

Krótki opis klasy

HttpMessage implements Iterator , Countable , Serializable {
public void addHeaders ( array $headers [, bool $append = false ] )
public __construct ([ string $message ] )
public HttpMessage detach ( void )
static public HttpMessage factory ([ string $raw_message [, string $class_name = "HttpMessage" ]] )
static public HttpMessage fromEnv ( int $message_type [, string $class_name = "HttpMessage" ] )
static public HttpMessage fromString ([ string $raw_message [, string $class_name = "HttpMessage" ]] )
public string getBody ( void )
public string getHeader ( string $header )
public array getHeaders ( void )
public string getHttpVersion ( void )
public HttpMessage getParentMessage ( void )
public string getRequestMethod ( void )
public string getRequestUrl ( void )
public int getResponseCode ( void )
public string getResponseStatus ( void )
public int getType ( void )
public string guessContentType ( string $magic_file [, int $magic_mode = MAGIC_MIME ] )
public void prepend ( HttpMessage $message [, bool $top = true ] )
public HttpMessage reverse ( void )
public bool send ( void )
public void setBody ( string $body )
public void setHeaders ( array $headers )
public bool setHttpVersion ( string $version )
public bool setRequestMethod ( string $method )
public bool setRequestUrl ( string $url )
public bool setResponseCode ( int $code )
public bool setResponseStatus ( string $status )
public void setType ( int $type )
public HttpRequest|HttpResponse toMessageTypeObject ( void )
public string toString ([ bool $include_parent = false ] )
}

Class Members

Właściwości

Instance Properties
Modifiers | Type | Name | Description
protected | int | type | message type
protected | string | body | message body
protected | float | httpVersion | HTTP protocol version
protected | array | headers | message headers
protected | string | requestMethod | request method name
protected | requestUrl | string | request URL
protected | int | responseCode | response code
protected | string | responseStatus | response status message
protected | HttpMessage | parentMessage | reference to parent message

Informacja:

None of these default properties can be accessed by reference, array key/index notation nor be used in increment or decrement operations.

Stałe predefiniowane

Type | Name | Description
int | TYPE_NONE | message has is of no specific type
int | TYPE_REQUEST | message is a request style HTTP message
int | TYPE_RESPONSE | message is a response style HTTP message

Spis treści

  • HttpMessage::addHeaders — Add headers
  • HttpMessage::__construct — HttpMessage constructor
  • HttpMessage::detach — Detach HttpMessage
  • HttpMessage::factory — Create HttpMessage from string
  • HttpMessage::fromEnv — Create HttpMessage from environment
  • HttpMessage::fromString — Create HttpMessage from string
  • HttpMessage::getBody — Get message body
  • HttpMessage::getHeader — Get header
  • HttpMessage::getHeaders — Get message headers
  • HttpMessage::getHttpVersion — Get HTTP version
  • HttpMessage::getParentMessage — Get parent message
  • HttpMessage::getRequestMethod — Get request method
  • HttpMessage::getRequestUrl — Get request URL
  • HttpMessage::getResponseCode — Get response code
  • HttpMessage::getResponseStatus — Get response status
  • HttpMessage::getType — Get message type
  • HttpMessage::guessContentType — Guess content type
  • HttpMessage::prepend — Prepend message(s)
  • HttpMessage::reverse — Reverse message chain
  • HttpMessage::send — Send message
  • HttpMessage::setBody — Set message body
  • HttpMessage::setHeaders — Set headers
  • HttpMessage::setHttpVersion — Set HTTP version
  • HttpMessage::setRequestMethod — Set request method
  • HttpMessage::setRequestUrl — Set request URL
  • HttpMessage::setResponseCode — Set response code
  • HttpMessage::setResponseStatus — Set response status
  • HttpMessage::setType — Set message type
  • HttpMessage::toMessageTypeObject — Create HTTP object regarding message type
  • HttpMessage::toString — Get string representation
HttpInflateStream::update
HttpMessage::addHeaders
HTTP


Add headers

HttpMessage
HttpMessage::__construct
HttpMessage
PHP Manual

HttpMessage::addHeaders

(PECL pecl_http >= 0.10.0)

HttpMessage::addHeaders — Add headers

Opis

public void HttpMessage::addHeaders ( array $headers [, bool $append = false ] )

Add headers. If append is true, headers with the same name will be separated, else overwritten.

Parametry

headers

associative array containing the additional HTTP headers to add to the messages existing headers

append

if true, and a header with the same name of one to add exists already, this respective header will be converted to an array containing both header values, otherwise it will be overwritten with the new header value

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpMessage
HttpMessage::__construct
HttpMessage


HttpMessage constructor

HttpMessage::addHeaders
HttpMessage::detach
HttpMessage
PHP Manual

HttpMessage::__construct

(PECL pecl_http >= 0.10.0)

HttpMessage::__construct — HttpMessage constructor

Opis

public HttpMessage::__construct ([ string $message ] )

Instantiate a new HttpMessage object.

The constructed object will actually represent the last message of the passed string. If there were prior messages, those can be accessed by HttpMessage::getParentMessage().

Parametry

message

a single or several consecutive HTTP messages

Błędy/Wyjątki

Throws HttpMalformedHeaderException.

HttpMessage::addHeaders
HttpMessage::detach
HttpMessage


Detach HttpMessage

HttpMessage::__construct
HttpMessage::factory
HttpMessage
PHP Manual

HttpMessage::detach

(PECL pecl_http >= 0.22.0)

HttpMessage::detach — Detach HttpMessage

Opis

public HttpMessage HttpMessage::detach ( void )

Returns a clone of an HttpMessage object detached from any parent messages.

Parametry

Zwracane wartości

Returns detached HttpMessage object copy.

HttpMessage::__construct
HttpMessage::factory
HttpMessage


Create HttpMessage from string

HttpMessage::detach
HttpMessage::fromEnv
HttpMessage
PHP Manual

HttpMessage::factory

(PECL pecl_http >= 1.4.0)

HttpMessage::factory — Create HttpMessage from string

Opis

static public HttpMessage HttpMessage::factory ([ string $raw_message [, string $class_name = "HttpMessage" ]] )

Create an HttpMessage object from a string.

Parametry

raw_message

a single or several consecutive HTTP messages

class_name

a class extending HttpMessage

Zwracane wartości

Returns an HttpMessage object on success or NULL on failure.

Błędy/Wyjątki

Throws HttpMalformedHeadersException.

Zobacz też:

  • HttpMessage::fromEnv() - Create HttpMessage from environment.

HttpMessage::detach
HttpMessage::fromEnv
HttpMessage


Create HttpMessage from environment

HttpMessage::factory
HttpMessage::fromString
HttpMessage
PHP Manual

HttpMessage::fromEnv

(PECL pecl_http >= 1.5.0)

HttpMessage::fromEnv — Create HttpMessage from environment

Opis

static public HttpMessage HttpMessage::fromEnv ( int $message_type [, string $class_name = "HttpMessage" ] )

Create an HttpMessage object from script environment.

Parametry

message_type

The message type. See HttpMessage type constants.

class_name

a class extending HttpMessage

Zwracane wartości

Returns an HttpMessage object on success or NULL on failure.

Zobacz też:

  • HttpMessage::factory() - Create HttpMessage from string.

HttpMessage::factory
HttpMessage::fromString
HttpMessage


Create HttpMessage from string

HttpMessage::fromEnv
HttpMessage::getBody
HttpMessage
PHP Manual

HttpMessage::fromString

(PECL pecl_http 0.10.0-1.3.3)

HttpMessage::fromString — Create HttpMessage from string

Opis

static public HttpMessage HttpMessage::fromString ([ string $raw_message [, string $class_name = "HttpMessage" ]] )

Create an HttpMessage object from a string.

Ten alias jest nie zalecany i istnieje tylko dla zachowania kompatybilności wstecznej. Zaleca się nie używanie tego aliasu, jako że może on zostać usunięty w przyszłości z PHP.

Parametry

raw_message

a single or several consecutive HTTP messages

class_name

a class extending HttpMessage

Zwracane wartości

Returns an HttpMessage object on success or NULL on failure.

Błędy/Wyjątki

Throws HttpMalformedHeadersException.

Zobacz też:

  • HttpMessage::factory() - Create HttpMessage from string.

HttpMessage::fromEnv
HttpMessage::getBody
HttpMessage


Get message body

HttpMessage::fromString
HttpMessage::getHeader
HttpMessage
PHP Manual

HttpMessage::getBody

(PECL pecl_http >= 0.10.0)

HttpMessage::getBody — Get message body

Opis

public string HttpMessage::getBody ( void )

Get the body of the parsed HttpMessage.

Zwracane wartości

Returns the message body as string.

HttpMessage::fromString
HttpMessage::getHeader
HttpMessage


Get header

HttpMessage::getBody
HttpMessage::getHeaders
HttpMessage
PHP Manual

HttpMessage::getHeader

(PECL pecl_http >= 1.1.0)

HttpMessage::getHeader — Get header

Opis

public string HttpMessage::getHeader ( string $header )

Get message header.

Parametry

header

header name

Zwracane wartości

Returns the header value on success or NULL if the header does not exist.

HttpMessage::getBody
HttpMessage::getHeaders
HttpMessage


Get message headers

HttpMessage::getHeader
HttpMessage::getHttpVersion
HttpMessage
PHP Manual

HttpMessage::getHeaders

(PECL pecl_http >= 0.10.0)

HttpMessage::getHeaders — Get message headers

Opis

public array HttpMessage::getHeaders ( void )

Get message headers.

Zwracane wartości

Returns an associative array containing the messages HTTP headers.

HttpMessage::getHeader
HttpMessage::getHttpVersion
HttpMessage


Get HTTP version

HttpMessage::getHeaders
HttpMessage::getParentMessage
HttpMessage
PHP Manual

HttpMessage::getHttpVersion

(PECL pecl_http >= 0.10.0)

HttpMessage::getHttpVersion — Get HTTP version

Opis

public string HttpMessage::getHttpVersion ( void )

Get the HTTP Protocol Version of the Message.

Zwracane wartości

Returns the HTTP protocol version as string.

HttpMessage::getHeaders
HttpMessage::getParentMessage
HttpMessage


Get parent message

HttpMessage::getHttpVersion
HttpMessage::getRequestMethod
HttpMessage
PHP Manual

HttpMessage::getParentMessage

(PECL pecl_http >= 0.10.0)

HttpMessage::getParentMessage — Get parent message

Opis

public HttpMessage HttpMessage::getParentMessage ( void )

Get parent Message.

Zwracane wartości

Returns the parent HttpMessage object.

Błędy/Wyjątki

Throws HttpRuntimeException.

HttpMessage::getHttpVersion
HttpMessage::getRequestMethod
HttpMessage


Get request method

HttpMessage::getParentMessage
HttpMessage::getRequestUrl
HttpMessage
PHP Manual

HttpMessage::getRequestMethod

(PECL pecl_http >= 0.10.0)

HttpMessage::getRequestMethod — Get request method

Opis

public string HttpMessage::getRequestMethod ( void )

Get the Request Method of the Message.

Zwracane wartości

Returns the request method name on success, or FALSE if the message is not of type HttpMessage::TYPE_REQUEST.

HttpMessage::getParentMessage
HttpMessage::getRequestUrl
HttpMessage


Get request URL

HttpMessage::getRequestMethod
HttpMessage::getResponseCode
HttpMessage
PHP Manual

HttpMessage::getRequestUrl

(PECL pecl_http >= 0.21.0)

HttpMessage::getRequestUrl — Get request URL

Opis

public string HttpMessage::getRequestUrl ( void )

Get the Request URL of the Message.

Parametry

Zwracane wartości

Returns the request URL as string on success, or FALSE if the message is not of type HttpMessage::TYPE_REQUEST.

HttpMessage::getRequestMethod
HttpMessage::getResponseCode
HttpMessage


Get response code

HttpMessage::getRequestUrl
HttpMessage::getResponseStatus
HttpMessage
PHP Manual

HttpMessage::getResponseCode

(PECL pecl_http >= 0.10.0)

HttpMessage::getResponseCode — Get response code

Opis

public int HttpMessage::getResponseCode ( void )

Get the Response Code of the Message.

Zwracane wartości

Returns the HTTP response code if the message is of type HttpMessage::TYPE_RESPONSE, else FALSE.

HttpMessage::getRequestUrl
HttpMessage::getResponseStatus
HttpMessage


Get response status

HttpMessage::getResponseCode
HttpMessage::getType
HttpMessage
PHP Manual

HttpMessage::getResponseStatus

(PECL pecl_http >= 0.23.0)

HttpMessage::getResponseStatus — Get response status

Opis

public string HttpMessage::getResponseStatus ( void )

Get the Response Status of the message (i.e. the string following the response code).

Zwracane wartości

Returns the HTTP response status string if the message is of type HttpMessage::TYPE_RESPONSE, else FALSE.

HttpMessage::getResponseCode
HttpMessage::getType
HttpMessage


Get message type

HttpMessage::getResponseStatus
HttpMessage::guessContentType
HttpMessage
PHP Manual

HttpMessage::getType

(PECL pecl_http >= 0.10.0)

HttpMessage::getType — Get message type

Opis

public int HttpMessage::getType ( void )

Get Message Type. Either HTTP_MSG_NONE, HTTP_MSG_REQUEST or HTTP_MSG_RESPONSE.

Zwracane wartości

Returns the HttpMessage::TYPE.

HttpMessage::getResponseStatus
HttpMessage::guessContentType
HttpMessage


Guess content type

HttpMessage::getType
HttpMessage::prepend
HttpMessage
PHP Manual

HttpMessage::guessContentType

(PECL pecl_http >= 1.0.0)

HttpMessage::guessContentType — Guess content type

Opis

public string HttpMessage::guessContentType ( string $magic_file [, int $magic_mode = MAGIC_MIME ] )

Attempts to guess the content type of the message body through libmagic.

Parametry

magic_file

the magic.mime database to use

magic_mode

flags for libmagic

Zwracane wartości

Returns the guessed content type on success lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Throws HttpRuntimeException, HttpInvalidParamException.

HttpMessage::getType
HttpMessage::prepend
HttpMessage


Prepend message(s)

HttpMessage::guessContentType
HttpMessage::reverse
HttpMessage
PHP Manual

HttpMessage::prepend

(PECL pecl_http >= 0.22.0)

HttpMessage::prepend — Prepend message(s)

Opis

public void HttpMessage::prepend ( HttpMessage $message [, bool $top = true ] )

Prepends message(s) to the HTTP message.

Parametry

message

HttpMessage object to prepend

top

whether to prepend to the top most or right this message

Błędy/Wyjątki

Throws HttpInvalidParamException if the message is located within the same message chain.

HttpMessage::guessContentType
HttpMessage::reverse
HttpMessage


Reverse message chain

HttpMessage::prepend
HttpMessage::send
HttpMessage
PHP Manual

HttpMessage::reverse

(PECL pecl_http >= 0.23.0)

HttpMessage::reverse — Reverse message chain

Opis

public HttpMessage HttpMessage::reverse ( void )

Reorders the message chain in reverse order.

Zwracane wartości

Returns the most parent HttpMessage object.

HttpMessage::prepend
HttpMessage::send
HttpMessage


Send message

HttpMessage::reverse
HttpMessage::setBody
HttpMessage
PHP Manual

HttpMessage::send

(PECL pecl_http >= 0.10.0)

HttpMessage::send — Send message

Opis

public bool HttpMessage::send ( void )

Send the Message according to its type as Response or Request.

This provides limited functionality compared to HttpRequest and HttpResponse.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpMessage::reverse
HttpMessage::setBody
HttpMessage


Set message body

HttpMessage::send
HttpMessage::setHeaders
HttpMessage
PHP Manual

HttpMessage::setBody

(PECL pecl_http >= 0.14.0)

HttpMessage::setBody — Set message body

Opis

public void HttpMessage::setBody ( string $body )

Set the body of the HttpMessage.

Informacja:

Don't forget to update any headers accordingly.

Parametry

body

the new body of the message

HttpMessage::send
HttpMessage::setHeaders
HttpMessage


Set headers

HttpMessage::setBody
HttpMessage::setHttpVersion
HttpMessage
PHP Manual

HttpMessage::setHeaders

(PECL pecl_http >= 0.10.0)

HttpMessage::setHeaders — Set headers

Opis

public void HttpMessage::setHeaders ( array $headers )

Sets new headers.

Parametry

headers

associative array containing the new HTTP headers, which will replace all previous HTTP headers of the message

HttpMessage::setBody
HttpMessage::setHttpVersion
HttpMessage


Set HTTP version

HttpMessage::setHeaders
HttpMessage::setRequestMethod
HttpMessage
PHP Manual

HttpMessage::setHttpVersion

(PECL pecl_http >= 0.10.0)

HttpMessage::setHttpVersion — Set HTTP version

Opis

public bool HttpMessage::setHttpVersion ( string $version )

Set the HTTP Protocol version of the Message.

Parametry

version

the HTTP protocol version

Zwracane wartości

Returns TRUE on success, or FALSE if supplied version is out of range (1.0/1.1).

HttpMessage::setHeaders
HttpMessage::setRequestMethod
HttpMessage


Set request method

HttpMessage::setHttpVersion
HttpMessage::setRequestUrl
HttpMessage
PHP Manual

HttpMessage::setRequestMethod

(PECL pecl_http >= 0.10.0)

HttpMessage::setRequestMethod — Set request method

Opis

public bool HttpMessage::setRequestMethod ( string $method )

Set the Request Method of the HTTP Message.

Parametry

method

the request method name

Zwracane wartości

Returns TRUE on success, or FALSE if the message is not of type HttpMessage::TYPE_REQUEST or an invalid request method was supplied.

HttpMessage::setHttpVersion
HttpMessage::setRequestUrl
HttpMessage


Set request URL

HttpMessage::setRequestMethod
HttpMessage::setResponseCode
HttpMessage
PHP Manual

HttpMessage::setRequestUrl

(PECL pecl_http >= 0.21.0)

HttpMessage::setRequestUrl — Set request URL

Opis

public bool HttpMessage::setRequestUrl ( string $url )

Set the Request URL of the HTTP Message.

Parametry

url

the request URL

Zwracane wartości

Returns TRUE on success, or FALSE if the message is not of type HttpMessage::TYPE_REQUEST or supplied URL was empty.

HttpMessage::setRequestMethod
HttpMessage::setResponseCode
HttpMessage


Set response code

HttpMessage::setRequestUrl
HttpMessage::setResponseStatus
HttpMessage
PHP Manual

HttpMessage::setResponseCode

(PECL pecl_http >= 0.10.0)

HttpMessage::setResponseCode — Set response code

Opis

public bool HttpMessage::setResponseCode ( int $code )

Set the response code of an HTTP Response Message.

Parametry

code

HTTP response code

Zwracane wartości

Returns TRUE on success, or FALSE if the message is not of type HttpMessage::TYPE_RESPONSE or the response code is out of range (100-510).

HttpMessage::setRequestUrl
HttpMessage::setResponseStatus
HttpMessage


Set response status

HttpMessage::setResponseCode
HttpMessage::setType
HttpMessage
PHP Manual

HttpMessage::setResponseStatus

(PECL pecl_http >= 0.23.0)

HttpMessage::setResponseStatus — Set response status

Opis

public bool HttpMessage::setResponseStatus ( string $status )

Set the Response Status of the HTTP message (i.e. the string following the response code).

Parametry

status

the response status text

Zwracane wartości

Returns TRUE on success or FALSE if the message is not of type HttpMessage::TYPE_RESPONSE.

HttpMessage::setResponseCode
HttpMessage::setType
HttpMessage


Set message type

HttpMessage::setResponseStatus
HttpMessage::toMessageTypeObject
HttpMessage
PHP Manual

HttpMessage::setType

(PECL pecl_http >= 0.10.0)

HttpMessage::setType — Set message type

Opis

public void HttpMessage::setType ( int $type )

Set Message Type. Either HTTP_MSG_NONE, HTTP_MSG_REQUEST or HTTP_MSG_RESPONSE.

Parametry

type

the HttpMessage::TYPE_*

HttpMessage::setResponseStatus
HttpMessage::toMessageTypeObject
HttpMessage


Create HTTP object regarding message type

HttpMessage::setType
HttpMessage::toString
HttpMessage
PHP Manual

HttpMessage::toMessageTypeObject

(PECL pecl_http >= 0.22.0)

HttpMessage::toMessageTypeObject — Create HTTP object regarding message type

Opis

public HttpRequest|HttpResponse HttpMessage::toMessageTypeObject ( void )

Creates an object regarding to the type of the message.

Parametry

Zwracane wartości

Returns either an HttpRequest or HttpResponse object on success, or NULL on failure.

Błędy/Wyjątki

Throws HttpRuntimeException, HttpMessageTypeException, HttpHeaderException.

HttpMessage::setType
HttpMessage::toString
HttpMessage


Get string representation

HttpMessage::toMessageTypeObject
HttpQueryString
HttpMessage
PHP Manual

HttpMessage::toString

(PECL pecl_http >= 0.10.0)

HttpMessage::toString — Get string representation

Opis

public string HttpMessage::toString ([ bool $include_parent = false ] )

Get the string representation of the Message.

Parametry

include_parent

specifies whether the returned string should also contain any parent messages

Zwracane wartości

Returns the message as string.

HttpMessage::toMessageTypeObject
HttpQueryString
HttpMessage


The HttpQueryString class

(No version information available, might only be in SVN)

Krótki opis klasy

HttpQueryString implements ArrayAccess , Serializable {
final public __construct ([ bool $global = true [, mixed $add ]] )
public mixed get ([ string $key [, mixed $type = 0 [, mixed $defval = NULL [, bool $delete = false ]]]] )
public HttpQueryString mod ( mixed $params )
public string set ( mixed $params )
static public HttpQueryString singleton ([ bool $global = true ] )
public array toArray ( void )
public string toString ( void )
public bool xlate ( string $ie , string $oe )
}

Class Members

Właściwości

Instance Properties
Modifiers | Type | Name | Description
private | array | queryArray | query parameters
private | string | queryString | serialized query parameters
Static Properties
Modifiers | Type | Name | Description
private | array | instance | holds singletons

Stałe predefiniowane

Type | Name | Description
int | TYPE_BOOL | retrieve query param as bool
int | TYPE_INT | retrieve query param as int
int | TYPE_FLOAT | retrieve query param as float
int | TYPE_STRING | retrieve query param as string
int | TYPE_ARRAY | retrieve query param as array
int | TYPE_OBJECT | retrieve query param as object

Spis treści

  • HttpQueryString::__construct — HttpQueryString constructor
  • HttpQueryString::get — Get (part of) query string
  • HttpQueryString::mod — Modifiy query string copy
  • HttpQueryString::set — Set query string params
  • HttpQueryString::singleton — HttpQueryString singleton
  • HttpQueryString::toArray — Get query string as array
  • HttpQueryString::toString — Get query string
  • HttpQueryString::xlate — Change query strings charset
HttpMessage::toString
HttpQueryString::__construct
HTTP


HttpQueryString constructor

HttpQueryString
HttpQueryString::get
HttpQueryString
PHP Manual

HttpQueryString::__construct

(PECL pecl_http >= 0.22.0)

HttpQueryString::__construct — HttpQueryString constructor

Opis

final public HttpQueryString::__construct ([ bool $global = true [, mixed $add ]] )

Creates a new HttpQueryString object instance.

Operates on and modifies $_GET and $_SERVER['QUERY_STRING'] if global is TRUE.

Parametry

global

whether to operate on $_GET and $_SERVER['QUERY_STRING']

add

additional/initial query string parameters

Błędy/Wyjątki

Throws HttpRuntimeException.

HttpQueryString
HttpQueryString::get
HttpQueryString


Get (part of) query string

HttpQueryString::__construct
HttpQueryString::mod
HttpQueryString
PHP Manual

HttpQueryString::get

(PECL pecl_http >= 0.22.0)

HttpQueryString::get — Get (part of) query string

Opis

public mixed HttpQueryString::get ([ string $key [, mixed $type = 0 [, mixed $defval = NULL [, bool $delete = false ]]]] )

Get (part of) the query string.

The type parameter is either one of the HttpQueryString::TYPE_* constants or a type abbreviation like "b" for bool, "i" for int, "f" for float, "s" for string, "a" for array and "o" for a stdClass object.

Parametry

key

key of the query string param to retrieve

type

which variable type to enforce

defval

default value if key does not exist

delete

whether to remove the key/value pair from the query string

Zwracane wartości

Returns the value of the query string param or the whole query string if no key was specified on success or defval if key does not exist.

HttpQueryString::__construct
HttpQueryString::mod
HttpQueryString


Modifiy query string copy

HttpQueryString::get
HttpQueryString::set
HttpQueryString
PHP Manual

HttpQueryString::mod

(PECL pecl_http >= 1.1.0)

HttpQueryString::mod — Modifiy query string copy

Opis

public HttpQueryString HttpQueryString::mod ( mixed $params )

Copies the query string object and sets provided params at the clone.

Parametry

params

query string params to add

Zwracane wartości

Returns a new HttpQueryString object

HttpQueryString::get
HttpQueryString::set
HttpQueryString


Set query string params

HttpQueryString::mod
HttpQueryString::singleton
HttpQueryString
PHP Manual

HttpQueryString::set

(PECL pecl_http >= 0.22.0)

HttpQueryString::set — Set query string params

Opis

public string HttpQueryString::set ( mixed $params )

Set query string entry/entries. NULL values will unset the variable.

Parametry

params

query string params to add

Zwracane wartości

Returns the current query string.

HttpQueryString::mod
HttpQueryString::singleton
HttpQueryString


HttpQueryString singleton

HttpQueryString::set
HttpQueryString::toArray
HttpQueryString
PHP Manual

HttpQueryString::singleton

(PECL pecl_http >= 0.25.0)

HttpQueryString::singleton — HttpQueryString singleton

Opis

static public HttpQueryString HttpQueryString::singleton ([ bool $global = true ] )

Get a single instance (differentiates between the global setting).

Parametry

global

whether to operate on $_GET and $_SERVER['QUERY_STRING']

Zwracane wartości

Returns always the same HttpQueryString instance regarding the global setting.

Błędy/Wyjątki

Throws HttpRuntimeException.

HttpQueryString::set
HttpQueryString::toArray
HttpQueryString


Get query string as array

HttpQueryString::singleton
HttpQueryString::toString
HttpQueryString
PHP Manual

HttpQueryString::toArray

(PECL pecl_http >= 0.22.0)

HttpQueryString::toArray — Get query string as array

Opis

public array HttpQueryString::toArray ( void )

Get the query string represented as associative array.

Zwracane wartości

Returns the array representation of the query string.

HttpQueryString::singleton
HttpQueryString::toString
HttpQueryString


Get query string

HttpQueryString::toArray
HttpQueryString::xlate
HttpQueryString
PHP Manual

HttpQueryString::toString

(PECL pecl_http >= 0.22.0)

HttpQueryString::toString — Get query string

Opis

public string HttpQueryString::toString ( void )

Get the query string.

Parametry

Zwracane wartości

Returns the string representation of the query string.

HttpQueryString::toArray
HttpQueryString::xlate
HttpQueryString


Change query strings charset

HttpQueryString::toString
HttpRequest
HttpQueryString
PHP Manual

HttpQueryString::xlate

(PECL pecl_http >= 0.25.0)

HttpQueryString::xlate — Change query strings charset

Opis

public bool HttpQueryString::xlate ( string $ie , string $oe )

Converts the query string from the source encoding ie to the target encoding oe.

Ostrzeżenie

Don't use any character set that can contain NUL bytes like UTF-16.

Informacja:

This method requires ext/iconv to be enabled and loaded.

Parametry

ie

input encoding

oe

output encoding

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpQueryString::toString
HttpRequest
HttpQueryString


The HttpRequest

(No version information available, might only be in SVN)

Krótki opis klasy

HttpRequest {
public bool addCookies ( array $cookies )
public bool addHeaders ( array $headers )
public bool addPostFields ( array $post_data )
public bool addPostFile ( string $name , string $file [, string $content_type = "application/x-octetstream" ] )
public bool addPutData ( string $put_data )
public bool addQueryData ( array $query_params )
public bool addRawPostData ( string $raw_post_data )
public bool addSslOptions ( array $options )
public void clearHistory ( void )
public __construct ([ string $url [, int $request_method = HTTP_METH_GET [, array $options ]]] )
public bool enableCookies ( void )
public string getContentType ( void )
public array getCookies ( void )
public array getHeaders ( void )
public HttpMessage getHistory ( void )
public int getMethod ( void )
public array getOptions ( void )
public array getPostFields ( void )
public array getPostFiles ( void )
public string getPutData ( void )
public string getPutFile ( void )
public string getQueryData ( void )
public string getRawPostData ( void )
public string getRawRequestMessage ( void )
public string getRawResponseMessage ( void )
public HttpMessage getRequestMessage ( void )
public string getResponseBody ( void )
public int getResponseCode ( void )
public array getResponseCookies ([ int $flags = 0 [, array $allowed_extras ]] )
public array getResponseData ( void )
public mixed getResponseHeader ([ string $name ] )
public mixed getResponseInfo ([ string $name ] )
public HttpMessage getResponseMessage ( void )
public string getResponseStatus ( void )
public array getSslOptions ( void )
public string getUrl ( void )
public bool resetCookies ([ bool $session_only = false ] )
public HttpMessage send ( void )
bool setBody ([ string $request_body_data ] )
public bool setContentType ( string $content_type )
public bool setCookies ([ array $cookies ] )
public bool setHeaders ([ array $headers ] )
public bool setMethod ( int $request_method )
public bool setOptions ([ array $options ] )
public bool setPostFields ( array $post_data )
public bool setPostFiles ( array $post_files )
public bool setPutData ([ string $put_data ] )
public bool setPutFile ([ string $file = "" ] )
public bool setQueryData ( mixed $query_data )
public bool setRawPostData ([ string $raw_post_data ] )
public bool setSslOptions ([ array $options ] )
public bool setUrl ( string $url )
}

Class Members

Właściwości

Instance Properties
Modifiers | Type | Name | Description
private | array | options | request options to configure the request; see Opcje żądania
private array postFields form data:
array("fieldname" => "fieldvalue")
private array postFiles files to upload:
array(array("name" => "image", "file" => "/home/u/images/u.png", "type" => "image/png"))
private | array | responseInfo | information (statistical) about the request/response; see Informacje żądania/odpowiedzi
private | HttpMessage | responseMessage | the response message
private | integer | responseCode | the numerical response code
private | string | responseStatus | the literal response status text
private | integer | method | the request method to use
private | string | url | the request url
private | string | contentType | the content type to use for raw post requests
private | string | rawPostData | raw post data
private | string | queryData | query parameters
private | string | putFile | the file to upload with a PUT request
private | string | putData | raw data to upload with a PUT request
private | HttpMessage | history | the whole request/response history if history logging is enabled
public | boolean | recordHistory | whether to enable history logging

Stałe predefiniowane

Type | Name | Description
integer | METH_GET | GET request method
integer | METH_HEAD | HEAD request method
integer | METH_POST | POST request method
integer | METH_PUT | PUT request method
integer | METH_DELETE | DELETE request method
integer | METH_OPTIONS | OPTIONS request method
integer | METH_TRACE | TRACE request method
integer | METH_CONNECT | CONNECT request method
integer | METH_PROPFIND | PROPFIND request method
integer | METH_PROPPATCH | PROPPATCH request method
integer | METH_MKCOL | MKCOL request method
integer | METH_COPY | COPY request method
integer | METH_MOVE | MOVE request method
integer | METH_LOCK | LOCK request method
integer | METH_UNLOCK | UNLOCK request method
integer | METH_VERSION_CONTROL | VERSION-CONTROL request method
integer | METH_REPORT | REPORT request method
integer | METH_CHECKOUT | CHECKOUT request method
integer | METH_CHECKIN | CHECKIN request method
integer | METH_UNCHECKOUT | UNCHECKOUT request method
integer | METH_MKWORKSPACE | MKWORKSPACE request method
integer | METH_UPDATE | UPDATE request method
integer | METH_LABEL | LABEL request method
integer | METH_MERGE | MERGE request method
integer | METH_BASELINE_CONTROL | BASELINE-CONTROL request method
integer | METH_MKACTIVITY | MKACTIVITY request method
integer | METH_ACL | ACL request method
integer | VERSION_1_0 | HTTP protocol version 1.0
integer | VERSION_1_1 | HTTP protocol version 1.1
integer | VERSION_ANY | any HTTP protocol version
integer | AUTH_BASIC | basic authentication
integer | AUTH_DIGEST | digest authentication
integer | AUTH_NTLM | NTLM authentication
integer | AUTH_GSSNEG | GSS negotiate authentication
integer | AUTH_ANY | any authentication
integer | PROXY_SOCKS4 | SOCKS v4 proxy
integer | PROXY_SOCKS5 | SOCKS v5 proxy
integer | PROXY_HTTP | HTTP proxy
integer | SSL_VERSION_TLSv1 | use TLS v1
integer | SSL_VERSION_SSLv2 | use SSL v2
integer | SSL_VERSION_SSLv3 | use SSL v3
integer | SSL_VERSION_ANY | use any SSL/TLS method
integer | IPRESOLVE_V4 | resolve via IPv4 only
integer | IPRESOLVE_V6 | resolve via IPv6 only
integer | IPRESOLVE_ANY | use any resolving methods

Spis treści

  • HttpRequest::addCookies — Add cookies
  • HttpRequest::addHeaders — Add headers
  • HttpRequest::addPostFields — Add post fields
  • HttpRequest::addPostFile — Add post file
  • HttpRequest::addPutData — Add put data
  • HttpRequest::addQueryData — Add query data
  • HttpRequest::addRawPostData — Add raw post data
  • HttpRequest::addSslOptions — Add ssl options
  • HttpRequest::clearHistory — Clear history
  • HttpRequest::__construct — HttpRequest constructor
  • HttpRequest::enableCookies — Enable cookies
  • HttpRequest::getContentType — Get content type
  • HttpRequest::getCookies — Get cookies
  • HttpRequest::getHeaders — Get headers
  • HttpRequest::getHistory — Get history
  • HttpRequest::getMethod — Get method
  • HttpRequest::getOptions — Get options
  • HttpRequest::getPostFields — Get post fields
  • HttpRequest::getPostFiles — Get post files
  • HttpRequest::getPutData — Get put data
  • HttpRequest::getPutFile — Get put file
  • HttpRequest::getQueryData — Get query data
  • HttpRequest::getRawPostData — Get raw post data
  • HttpRequest::getRawRequestMessage — Get raw request message
  • HttpRequest::getRawResponseMessage — Get raw response message
  • HttpRequest::getRequestMessage — Get request message
  • HttpRequest::getResponseBody — Get response body
  • HttpRequest::getResponseCode — Get response code
  • HttpRequest::getResponseCookies — Get response cookie(s)
  • HttpRequest::getResponseData — Get response data
  • HttpRequest::getResponseHeader — Get response header(s)
  • HttpRequest::getResponseInfo — Get response info
  • HttpRequest::getResponseMessage — Get response message
  • HttpRequest::getResponseStatus — Get response status
  • HttpRequest::getSslOptions — Get ssl options
  • HttpRequest::getUrl — Get url
  • HttpRequest::resetCookies — Reset cookies
  • HttpRequest::send — Send request
  • HttpRequest::setBody — Set request body to send, overwriting previously set request body.
  • HttpRequest::setContentType — Set content type
  • HttpRequest::setCookies — Set cookies
  • HttpRequest::setHeaders — Set headers
  • HttpRequest::setMethod — Set method
  • HttpRequest::setOptions — Set options
  • HttpRequest::setPostFields — Set post fields
  • HttpRequest::setPostFiles — Set post files
  • HttpRequest::setPutData — Set put data
  • HttpRequest::setPutFile — Set put file
  • HttpRequest::setQueryData — Set query data
  • HttpRequest::setRawPostData — Set raw post data
  • HttpRequest::setSslOptions — Set ssl options
  • HttpRequest::setUrl — Set URL
HttpQueryString::xlate
HttpRequest::addCookies
HTTP


Add cookies

HttpRequest
HttpRequest::addHeaders
HttpRequest
PHP Manual

HttpRequest::addCookies

(PECL pecl_http >= 0.10.0)

HttpRequest::addCookies — Add cookies

Opis

public bool HttpRequest::addCookies ( array $cookies )

Add custom cookies.

Informacja: Opcja żądania encodecookies sprawdza czy wartości ciastka powinny być zakodowane urlencode().

Informacja: Podlega dowolnej metodzie żądania.

Parametry

cookies

an associative array containing any cookie name/value pairs to add

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A HttpRequest::addCookies() example

<?php
$r = new HttpRequest;
$r->addCookies(
    array(
        "cookie_name" => "cookie value",
    )
);
?>

Zobacz też:

  • HttpRequest::setCookies() - Set cookies

HttpRequest
HttpRequest::addHeaders
HttpRequest


Add headers

HttpRequest::addCookies
HttpRequest::addPostFields
HttpRequest
PHP Manual

HttpRequest::addHeaders

(PECL pecl_http >= 0.10.0)

HttpRequest::addHeaders — Add headers

Opis

public bool HttpRequest::addHeaders ( array $headers )

Add request header name/value pairs.

Parametry

headers

an associative array as parameter containing additional header name/value pairs

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::addCookies
HttpRequest::addPostFields
HttpRequest


Add post fields

HttpRequest::addHeaders
HttpRequest::addPostFile
HttpRequest
PHP Manual

HttpRequest::addPostFields

(PECL pecl_http >= 0.10.0)

HttpRequest::addPostFields — Add post fields

Opis

public bool HttpRequest::addPostFields ( array $post_data )

Adds POST data entries, leaving previously set unchanged, unless a post entry with the same name already exists.

Affects only POST and custom requests.

Parametry

post_data

an associative array as parameter containing the post fields

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::addHeaders
HttpRequest::addPostFile
HttpRequest


Add post file

HttpRequest::addPostFields
HttpRequest::addPutData
HttpRequest
PHP Manual

HttpRequest::addPostFile

(PECL pecl_http >= 0.10.0)

HttpRequest::addPostFile — Add post file

Opis

public bool HttpRequest::addPostFile ( string $name , string $file [, string $content_type = "application/x-octetstream" ] )

Add a file to the POST request, leaving previously set files unchanged.

Affects only POST and custom requests. Cannot be used with raw post data.

Parametry

name

the form element name

file

the path to the file

content_type

the content type of the file

Zwracane wartości

Returns TRUE on success, or FALSE if the content type seems not to contain a primary and a secondary content type part.

HttpRequest::addPostFields
HttpRequest::addPutData
HttpRequest


Add put data

HttpRequest::addPostFile
HttpRequest::addQueryData
HttpRequest
PHP Manual

HttpRequest::addPutData

(PECL pecl_http >= 0.25.0)

HttpRequest::addPutData — Add put data

Opis

public bool HttpRequest::addPutData ( string $put_data )

Add PUT data, leaving previously set PUT data unchanged.

Affects only PUT requests.

Parametry

put_data

the data to concatenate

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::addPostFile
HttpRequest::addQueryData
HttpRequest


Add query data

HttpRequest::addPutData
HttpRequest::addRawPostData
HttpRequest
PHP Manual

HttpRequest::addQueryData

(PECL pecl_http >= 0.10.0)

HttpRequest::addQueryData — Add query data

Opis

public bool HttpRequest::addQueryData ( array $query_params )

Add parameters to the query parameter list, leaving previously set unchanged.

Affects any request type.

Parametry

query_params

an associative array as parameter containing the query fields to add

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::addPutData
HttpRequest::addRawPostData
HttpRequest


Add raw post data

HttpRequest::addQueryData
HttpRequest::addSslOptions
HttpRequest
PHP Manual

HttpRequest::addRawPostData

(PECL pecl_http 0.14.0-1.4.1)

HttpRequest::addRawPostData — Add raw post data

Opis

public bool HttpRequest::addRawPostData ( string $raw_post_data )

Add raw post data, leaving previously set raw post data unchanged.

Affects only POST and custom requests.

Parametry

raw_post_data

the raw post data to concatenate

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::addQueryData
HttpRequest::addSslOptions
HttpRequest


Add ssl options

HttpRequest::addRawPostData
HttpRequest::clearHistory
HttpRequest
PHP Manual

HttpRequest::addSslOptions

(PECL pecl_http >= 0.12.0)

HttpRequest::addSslOptions — Add ssl options

Opis

public bool HttpRequest::addSslOptions ( array $options )

Set additional SSL options.

Parametry

options

an associative array as parameter containing additional SSL specific options

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::addRawPostData
HttpRequest::clearHistory
HttpRequest


Clear history

HttpRequest::addSslOptions
HttpRequest::__construct
HttpRequest
PHP Manual

HttpRequest::clearHistory

(PECL pecl_http >= 0.15.0)

HttpRequest::clearHistory — Clear history

Opis

public void HttpRequest::clearHistory ( void )

Clears all history messages.

Informacja:

History is only logged if recordHistory was enabled.

HttpRequest::addSslOptions
HttpRequest::__construct
HttpRequest


HttpRequest constructor

HttpRequest::clearHistory
HttpRequest::enableCookies
HttpRequest
PHP Manual

HttpRequest::__construct

(PECL pecl_http >= 0.10.0)

HttpRequest::__construct — HttpRequest constructor

Opis

public HttpRequest::__construct ([ string $url [, int $request_method = HTTP_METH_GET [, array $options ]]] )

Instantiate a new HttpRequest object.

Parametry

url

the target request url

request_method

the request method to use

options

an associative array with request options

Błędy/Wyjątki

Throws HttpException.

HttpRequest::clearHistory
HttpRequest::enableCookies
HttpRequest


Enable cookies

HttpRequest::__construct
HttpRequest::getContentType
HttpRequest
PHP Manual

HttpRequest::enableCookies

(PECL pecl_http >= 1.0.0)

HttpRequest::enableCookies — Enable cookies

Opis

public bool HttpRequest::enableCookies ( void )

Enable automatic sending of received cookies.

Informacja:

Note that custom set cookies will be sent anyway.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::__construct
HttpRequest::getContentType
HttpRequest


Get content type

HttpRequest::enableCookies
HttpRequest::getCookies
HttpRequest
PHP Manual

HttpRequest::getContentType

(PECL pecl_http >= 0.10.0)

HttpRequest::getContentType — Get content type

Opis

public string HttpRequest::getContentType ( void )

Get the previously set content type.

Zwracane wartości

Returns the previously set content type as string.

HttpRequest::enableCookies
HttpRequest::getCookies
HttpRequest


Get cookies

HttpRequest::getContentType
HttpRequest::getHeaders
HttpRequest
PHP Manual

HttpRequest::getCookies

(PECL pecl_http >= 0.10.0)

HttpRequest::getCookies — Get cookies

Opis

public array HttpRequest::getCookies ( void )

Get previously set cookies.

Zwracane wartości

Returns an associative array containing any previously set cookies.

HttpRequest::getContentType
HttpRequest::getHeaders
HttpRequest


Get headers

HttpRequest::getCookies
HttpRequest::getHistory
HttpRequest
PHP Manual

HttpRequest::getHeaders

(PECL pecl_http >= 0.10.0)

HttpRequest::getHeaders — Get headers

Opis

public array HttpRequest::getHeaders ( void )

Get previously set request headers.

Zwracane wartości

Returns an associative array containing all currently set headers.

HttpRequest::getCookies
HttpRequest::getHistory
HttpRequest


Get history

HttpRequest::getHeaders
HttpRequest::getMethod
HttpRequest
PHP Manual

HttpRequest::getHistory

(PECL pecl_http >= 0.15.0)

HttpRequest::getHistory — Get history

Opis

public HttpMessage HttpRequest::getHistory ( void )

Get all sent requests and received responses as an HttpMessage object.

If you want to record history, set the instance variable HttpRequest::recordHistory to TRUE.

The returned object references the last received response, use HttpMessage::getParentMessage() to access the data of previously sent requests and received responses.

Zwracane wartości

Returns an HttpMessage object representing the complete request/response history.

Błędy/Wyjątki

Throws HttpRuntimeException.

HttpRequest::getHeaders
HttpRequest::getMethod
HttpRequest


Get method

HttpRequest::getHistory
HttpRequest::getOptions
HttpRequest
PHP Manual

HttpRequest::getMethod

(PECL pecl_http >= 0.10.0)

HttpRequest::getMethod — Get method

Opis

public int HttpRequest::getMethod ( void )

Get the previously set request method.

Zwracane wartości

Returns the currently set request method.

HttpRequest::getHistory
HttpRequest::getOptions
HttpRequest


Get options

HttpRequest::getMethod
HttpRequest::getPostFields
HttpRequest
PHP Manual

HttpRequest::getOptions

(PECL pecl_http >= 0.10.0)

HttpRequest::getOptions — Get options

Opis

public array HttpRequest::getOptions ( void )

Get currently set options.

Zwracane wartości

Returns an associative array containing currently set options.

HttpRequest::getMethod
HttpRequest::getPostFields
HttpRequest


Get post fields

HttpRequest::getOptions
HttpRequest::getPostFiles
HttpRequest
PHP Manual

HttpRequest::getPostFields

(PECL pecl_http >= 0.10.0)

HttpRequest::getPostFields — Get post fields

Opis

public array HttpRequest::getPostFields ( void )

Get previously set POST data.

Parametry

Zwracane wartości

Returns the currently set post fields as associative array.

HttpRequest::getOptions
HttpRequest::getPostFiles
HttpRequest


Get post files

HttpRequest::getPostFields
HttpRequest::getPutData
HttpRequest
PHP Manual

HttpRequest::getPostFiles

(PECL pecl_http >= 0.10.0)

HttpRequest::getPostFiles — Get post files

Opis

public array HttpRequest::getPostFiles ( void )

Get all previously added POST files.

Zwracane wartości

Returns an array containing currently set post files.

HttpRequest::getPostFields
HttpRequest::getPutData
HttpRequest


Get put data

HttpRequest::getPostFiles
HttpRequest::getPutFile
HttpRequest
PHP Manual

HttpRequest::getPutData

(PECL pecl_http >= 0.25.0)

HttpRequest::getPutData — Get put data

Opis

public string HttpRequest::getPutData ( void )

Get previously set PUT data.

Zwracane wartości

Returns a string containing the currently set PUT data.

HttpRequest::getPostFiles
HttpRequest::getPutFile
HttpRequest


Get put file

HttpRequest::getPutData
HttpRequest::getQueryData
HttpRequest
PHP Manual

HttpRequest::getPutFile

(PECL pecl_http >= 0.10.0)

HttpRequest::getPutFile — Get put file

Opis

public string HttpRequest::getPutFile ( void )

Get previously set put file.

Zwracane wartości

Returns a string containing the path to the currently set put file.

HttpRequest::getPutData
HttpRequest::getQueryData
HttpRequest


Get query data

HttpRequest::getPutFile
HttpRequest::getRawPostData
HttpRequest
PHP Manual

HttpRequest::getQueryData

(PECL pecl_http >= 0.10.0)

HttpRequest::getQueryData — Get query data

Opis

public string HttpRequest::getQueryData ( void )

Get the current query data in form of an urlencoded query string.

Zwracane wartości

Returns a string containing the urlencoded query.

HttpRequest::getPutFile
HttpRequest::getRawPostData
HttpRequest


Get raw post data

HttpRequest::getQueryData
HttpRequest::getRawRequestMessage
HttpRequest
PHP Manual

HttpRequest::getRawPostData

(PECL pecl_http 0.14.0-1.4.1)

HttpRequest::getRawPostData — Get raw post data

Opis

public string HttpRequest::getRawPostData ( void )

Get previously set raw post data.

Parametry

Zwracane wartości

Returns a string containing the currently set raw post data.

HttpRequest::getQueryData
HttpRequest::getRawRequestMessage
HttpRequest


Get raw request message

HttpRequest::getRawPostData
HttpRequest::getRawResponseMessage
HttpRequest
PHP Manual

HttpRequest::getRawRequestMessage

(PECL pecl_http >= 0.21.0)

HttpRequest::getRawRequestMessage — Get raw request message

Opis

public string HttpRequest::getRawRequestMessage ( void )

Get sent HTTP message.

Parametry

Zwracane wartości

Returns an HttpMessage in a form of a string.

HttpRequest::getRawPostData
HttpRequest::getRawResponseMessage
HttpRequest


Get raw response message

HttpRequest::getRawRequestMessage
HttpRequest::getRequestMessage
HttpRequest
PHP Manual

HttpRequest::getRawResponseMessage

(PECL pecl_http >= 0.21.0)

HttpRequest::getRawResponseMessage — Get raw response message

Opis

public string HttpRequest::getRawResponseMessage ( void )

Get the entire HTTP response.

Parametry

Zwracane wartości

Returns the complete web server response, including the headers in a form of a string.

HttpRequest::getRawRequestMessage
HttpRequest::getRequestMessage
HttpRequest


Get request message

HttpRequest::getRawResponseMessage
HttpRequest::getResponseBody
HttpRequest
PHP Manual

HttpRequest::getRequestMessage

(PECL pecl_http >= 0.11.0)

HttpRequest::getRequestMessage — Get request message

Opis

public HttpMessage HttpRequest::getRequestMessage ( void )

Get sent HTTP message.

If redirects were allowed and several responses were received, the data references the last received response. Use HttpMessage::getParentMessage() to access the data of previously sent requests within this request cycle.

Informacja:

Note that the internal request message is immutable, that means that the request message received through HttpRequest::getRequestMessage() will always look the same for the same request, regardless of any changes you may have made to the returned object.

Zwracane wartości

Returns an HttpMessage object representing the sent request.

Błędy/Wyjątki

Throws HttpMalformedHeadersException, HttpEncodingException.

HttpRequest::getRawResponseMessage
HttpRequest::getResponseBody
HttpRequest


Get response body

HttpRequest::getRequestMessage
HttpRequest::getResponseCode
HttpRequest
PHP Manual

HttpRequest::getResponseBody

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseBody — Get response body

Opis

public string HttpRequest::getResponseBody ( void )

Get the response body after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Parametry

Zwracane wartości

Returns a string containing the response body.

HttpRequest::getRequestMessage
HttpRequest::getResponseCode
HttpRequest


Get response code

HttpRequest::getResponseBody
HttpRequest::getResponseCookies
HttpRequest
PHP Manual

HttpRequest::getResponseCode

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseCode — Get response code

Opis

public int HttpRequest::getResponseCode ( void )

Get the response code after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Zwracane wartości

Returns an int representing the response code.

HttpRequest::getResponseBody
HttpRequest::getResponseCookies
HttpRequest


Get response cookie(s)

HttpRequest::getResponseCode
HttpRequest::getResponseData
HttpRequest
PHP Manual

HttpRequest::getResponseCookies

(PECL pecl_http >= 0.23.0)

HttpRequest::getResponseCookies — Get response cookie(s)

Opis

public array HttpRequest::getResponseCookies ([ int $flags = 0 [, array $allowed_extras ]] )

Get response cookie(s) after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Parametry

flags

http_parse_cookie() flags

allowed_extras

allowed keys treated as extra information instead of cookie names

Zwracane wartości

Returns an array of stdClass objects like http_parse_cookie() would return.

HttpRequest::getResponseCode
HttpRequest::getResponseData
HttpRequest


Get response data

HttpRequest::getResponseCookies
HttpRequest::getResponseHeader
HttpRequest
PHP Manual

HttpRequest::getResponseData

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseData — Get response data

Opis

public array HttpRequest::getResponseData ( void )

* Get all response data after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Zwracane wartości

Returns an associative array with the key "headers" containing an associative array holding all response headers, as well as the key "body" containing a string with the response body.

HttpRequest::getResponseCookies
HttpRequest::getResponseHeader
HttpRequest


Get response header(s)

HttpRequest::getResponseData
HttpRequest::getResponseInfo
HttpRequest
PHP Manual

HttpRequest::getResponseHeader

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseHeader — Get response header(s)

Opis

public mixed HttpRequest::getResponseHeader ([ string $name ] )

Get response header(s) after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response.

Parametry

name

header to read; if empty, all response headers will be returned

Zwracane wartości

Returns either a string with the value of the header matching name if requested, FALSE on failure, or an associative array containing all response headers.

HttpRequest::getResponseData
HttpRequest::getResponseInfo
HttpRequest


Get response info

HttpRequest::getResponseHeader
HttpRequest::getResponseMessage
HttpRequest
PHP Manual

HttpRequest::getResponseInfo

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseInfo — Get response info

Opis

public mixed HttpRequest::getResponseInfo ([ string $name ] )

Get response info after the request has been sent.

See http_get() for a full list of returned info.

If redirects were allowed and several responses were received, the data references the last received response.

Parametry

name

the info to read; if empty or omitted, an associative array containing all available info will be returned

Zwracane wartości

Returns either a scalar containing the value of the info matching name if requested, FALSE on failure, or an associative array containing all available info.

HttpRequest::getResponseHeader
HttpRequest::getResponseMessage
HttpRequest


Get response message

HttpRequest::getResponseInfo
HttpRequest::getResponseStatus
HttpRequest
PHP Manual

HttpRequest::getResponseMessage

(PECL pecl_http >= 0.10.0)

HttpRequest::getResponseMessage — Get response message

Opis

public HttpMessage HttpRequest::getResponseMessage ( void )

Get the full response as HttpMessage object after the request has been sent.

If redirects were allowed and several responses were received, the data references the last received response. Use HttpMessage::getParentMessage() to access the data of previously received responses within this request cycle.

Zwracane wartości

Returns an HttpMessage object of the response.

Błędy/Wyjątki

Throws HttpException, HttpRuntimeException.

HttpRequest::getResponseInfo
HttpRequest::getResponseStatus
HttpRequest


Get response status

HttpRequest::getResponseMessage
HttpRequest::getSslOptions
HttpRequest
PHP Manual

HttpRequest::getResponseStatus

(PECL pecl_http >= 0.23.0)

HttpRequest::getResponseStatus — Get response status

Opis

public string HttpRequest::getResponseStatus ( void )

Get the response status (i.e. the string after the response code) after the message has been sent.

Zwracane wartości

Returns a string containing the response status text.

HttpRequest::getResponseMessage
HttpRequest::getSslOptions
HttpRequest


Get ssl options

HttpRequest::getResponseStatus
HttpRequest::getUrl
HttpRequest
PHP Manual

HttpRequest::getSslOptions

(PECL pecl_http >= 0.10.0)

HttpRequest::getSslOptions — Get ssl options

Opis

public array HttpRequest::getSslOptions ( void )

Get previously set SSL options.

Zwracane wartości

Returns an associative array containing any previously set SSL options.

HttpRequest::getResponseStatus
HttpRequest::getUrl
HttpRequest


Get url

HttpRequest::getSslOptions
HttpRequest::resetCookies
HttpRequest
PHP Manual

HttpRequest::getUrl

(PECL pecl_http >= 0.10.0)

HttpRequest::getUrl — Get url

Opis

public string HttpRequest::getUrl ( void )

Get the previously set request URL.

Zwracane wartości

Returns the currently set request url as string.

HttpRequest::getSslOptions
HttpRequest::resetCookies
HttpRequest


Reset cookies

HttpRequest::getUrl
HttpRequest::send
HttpRequest
PHP Manual

HttpRequest::resetCookies

(PECL pecl_http >= 1.0.0)

HttpRequest::resetCookies — Reset cookies

Opis

public bool HttpRequest::resetCookies ([ bool $session_only = false ] )

Reset all automatically received/sent cookies.

Informacja:

Note that custom set cookies are not affected.

Parametry

session_only

whether only session cookies should be reset (needs libcurl >= v7.15.4, else libcurl >= v7.14.1)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::getUrl
HttpRequest::send
HttpRequest


Send request

HttpRequest::resetCookies
HttpRequest::setBody
HttpRequest
PHP Manual

HttpRequest::send

(PECL pecl_http >= 0.10.0)

HttpRequest::send — Send request

Opis

public HttpMessage HttpRequest::send ( void )

Send the HTTP request.

Informacja:

While an exception may be thrown, the transfer could have succeeded at least partially, so you might want to check the return values of various HttpRequest::getResponse*() methods.

Zwracane wartości

Returns the received response as HttpMessage object.

Błędy/Wyjątki

Throws HttpRuntimeException, HttpRequestException, HttpMalformedHeaderException, HttpEncodingException.

Przykłady

Przykład #1 GET example

<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
    $r->send();
    if ($r->getResponseCode() == 200) {
        file_put_contents('local.rss', $r->getResponseBody());
    }
} catch (HttpException $ex) {
    echo $ex;
}
?>

Przykład #2 POST example

<?php
$r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
$r->addPostFile('image', 'profile.jpg', 'image/jpeg');
try {
    echo $r->send()->getBody();
} catch (HttpException $ex) {
    echo $ex;
}
?>

HttpRequest::resetCookies
HttpRequest::setBody
HttpRequest


Set request body to send, overwriting previously set request body.

HttpRequest::send
HttpRequest::setContentType
HttpRequest
PHP Manual

HttpRequest::setBody

(PECL pecl_http >= 1.5.0)

HttpRequest::setBody — Set request body to send, overwriting previously set request body.

Opis

bool HttpRequest::setBody ([ string $request_body_data ] )

Set request body to send, overwriting previously set request body.

Parametry

request_body_data

The request body to overwrite the existing request body with.

Uwaga

Ensure that a Content-Type is specified in the request body.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Uwaga

This method was previously available as HttpRequest::setRawPostData().

Zobacz też:

  • HttpRequest::setRawPostData() - Set raw post data

HttpRequest::send
HttpRequest::setContentType
HttpRequest


Set content type

HttpRequest::setBody
HttpRequest::setCookies
HttpRequest
PHP Manual

HttpRequest::setContentType

(PECL pecl_http >= 0.10.0)

HttpRequest::setContentType — Set content type

Opis

public bool HttpRequest::setContentType ( string $content_type )

Set the content type the post request should have.

Parametry

content_type

the content type of the request (primary/secondary)

Zwracane wartości

Returns TRUE on success, or FALSE if the content type does not seem to contain a primary and a secondary part.

HttpRequest::setBody
HttpRequest::setCookies
HttpRequest


Set cookies

HttpRequest::setContentType
HttpRequest::setHeaders
HttpRequest
PHP Manual

HttpRequest::setCookies

(PECL pecl_http >= 0.12.0)

HttpRequest::setCookies — Set cookies

Opis

public bool HttpRequest::setCookies ([ array $cookies ] )

Set custom cookies.

Parametry

cookies

an associative array as parameter containing cookie name/value pairs; if empty or omitted, all previously set cookies will be unset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setContentType
HttpRequest::setHeaders
HttpRequest


Set headers

HttpRequest::setCookies
HttpRequest::setMethod
HttpRequest
PHP Manual

HttpRequest::setHeaders

(PECL pecl_http >= 0.12.0)

HttpRequest::setHeaders — Set headers

Opis

public bool HttpRequest::setHeaders ([ array $headers ] )

Set request header name/value pairs.

Parametry

headers

an associative array as parameter containing header name/value pairs; if empty or omitted, all previously set headers will be unset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setCookies
HttpRequest::setMethod
HttpRequest


Set method

HttpRequest::setHeaders
HttpRequest::setOptions
HttpRequest
PHP Manual

HttpRequest::setMethod

(PECL pecl_http >= 0.10.0)

HttpRequest::setMethod — Set method

Opis

public bool HttpRequest::setMethod ( int $request_method )

Set the request method.

Parametry

request_method

the request method to use

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setHeaders
HttpRequest::setOptions
HttpRequest


Set options

HttpRequest::setMethod
HttpRequest::setPostFields
HttpRequest
PHP Manual

HttpRequest::setOptions

(PECL pecl_http >= 0.10.0)

HttpRequest::setOptions — Set options

Opis

public bool HttpRequest::setOptions ([ array $options ] )

Set the request options to use.

Patrz po pełną listę Opcje żądania.

Parametry

options

an associative array, which values will overwrite the currently set request options; if empty or omitted, the options of the HttpRequest object will be reset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setMethod
HttpRequest::setPostFields
HttpRequest


Set post fields

HttpRequest::setOptions
HttpRequest::setPostFiles
HttpRequest
PHP Manual

HttpRequest::setPostFields

(PECL pecl_http >= 0.10.0)

HttpRequest::setPostFields — Set post fields

Opis

public bool HttpRequest::setPostFields ( array $post_data )

Set the POST data entries, overwriting previously set POST data.

Affects only POST and custom requests.

Parametry

post_data

an associative array containing the post fields; if empty, the post data will be unset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setOptions
HttpRequest::setPostFiles
HttpRequest


Set post files

HttpRequest::setPostFields
HttpRequest::setPutData
HttpRequest
PHP Manual

HttpRequest::setPostFiles

(PECL pecl_http >= 0.10.0)

HttpRequest::setPostFiles — Set post files

Opis

public bool HttpRequest::setPostFiles ( array $post_files )

Set files to post, overwriting previously set post files.

Affects only POST and requests. Cannot be used with raw post data.

Parametry

post_files

an array containing the files to post; if empty, the post files will be unset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setPostFields
HttpRequest::setPutData
HttpRequest


Set put data

HttpRequest::setPostFiles
HttpRequest::setPutFile
HttpRequest
PHP Manual

HttpRequest::setPutData

(PECL pecl_http >= 0.25.0)

HttpRequest::setPutData — Set put data

Opis

public bool HttpRequest::setPutData ([ string $put_data ] )

Set PUT data to send, overwriting previously set PUT data.

Affects only PUT requests.

Only either PUT data or PUT file can be used for each request. PUT data has higher precedence and will be used even if a PUT file is set.

Parametry

put_data

the data to upload

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setPostFiles
HttpRequest::setPutFile
HttpRequest


Set put file

HttpRequest::setPutData
HttpRequest::setQueryData
HttpRequest
PHP Manual

HttpRequest::setPutFile

(PECL pecl_http >= 0.10.0)

HttpRequest::setPutFile — Set put file

Opis

public bool HttpRequest::setPutFile ([ string $file = "" ] )

Set file to put. Affects only PUT requests.

Parametry

file

the path to the file to send; if empty or omitted the put file will be unset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setPutData
HttpRequest::setQueryData
HttpRequest


Set query data

HttpRequest::setPutFile
HttpRequest::setRawPostData
HttpRequest
PHP Manual

HttpRequest::setQueryData

(PECL pecl_http >= 0.10.0)

HttpRequest::setQueryData — Set query data

Opis

public bool HttpRequest::setQueryData ( mixed $query_data )

Set the URL query parameters to use, overwriting previously set query parameters.

Affects any request types.

Parametry

query_data

a string or associative array parameter containing the pre-encoded query string or to be encoded query fields; if empty, the query data will be unset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setPutFile
HttpRequest::setRawPostData
HttpRequest


Set raw post data

HttpRequest::setQueryData
HttpRequest::setSslOptions
HttpRequest
PHP Manual

HttpRequest::setRawPostData

(PECL pecl_http 0.14.0-1.4.1)

HttpRequest::setRawPostData — Set raw post data

Opis

public bool HttpRequest::setRawPostData ([ string $raw_post_data ] )

Set raw post data to send, overwriting previously set raw post data. Don't forget to specify a content type. Affects only POST and custom requests.

Only either post fields or raw post data can be used for each request. Raw post data has higher precedence and will be used even if post fields are set.

Ostrzeżenie

This function alias is DEPRECATED and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future. HttpRequest::setBody() should be used instead.

Parametry

raw_post_data

raw post data

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpRequest::setBody() - Set request body to send, overwriting previously set request body.

HttpRequest::setQueryData
HttpRequest::setSslOptions
HttpRequest


Set ssl options

HttpRequest::setRawPostData
HttpRequest::setUrl
HttpRequest
PHP Manual

HttpRequest::setSslOptions

(PECL pecl_http >= 0.10.0)

HttpRequest::setSslOptions — Set ssl options

Opis

public bool HttpRequest::setSslOptions ([ array $options ] )

Set SSL options.

Parametry

options

an associative array containing any SSL specific options; if empty or omitted, the SSL options will be reset

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setRawPostData
HttpRequest::setUrl
HttpRequest


Set URL

HttpRequest::setSslOptions
HttpRequestPool
HttpRequest
PHP Manual

HttpRequest::setUrl

(PECL pecl_http >= 0.10.0)

HttpRequest::setUrl — Set URL

Opis

public bool HttpRequest::setUrl ( string $url )

Set the request URL.

Parametry

url

the request url

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequest::setSslOptions
HttpRequestPool
HttpRequest


The HttpRequestPool class

(No version information available, might only be in SVN)

Krótki opis klasy

HttpRequestPool implements Iterator , Countable {
public bool attach ( HttpRequest $request )
public __construct ([ HttpRequest $request [, HttpRequest $... ]] )
void __destruct ( void )
bool detach ( HttpRequest $request )
array getAttachedRequests ( void )
array getFinishedRequests ( void )
void reset ( void )
bool send ( void )
protected bool socketPerform ( void )
protected bool socketSelect ([ float $timeout = 0 ] )
}

Class Members

Właściwości

The HttpRequestPool class does not have any properties.

Stałe predefiniowane

The HttpRequestPool class does not have any constants.

Spis treści

  • HttpRequestPool::attach — Attach HttpRequest
  • HttpRequestPool::__construct — HttpRequestPool constructor
  • HttpRequestPool::__destruct — HttpRequestPool destructor
  • HttpRequestPool::detach — Detach HttpRequest
  • HttpRequestPool::getAttachedRequests — Get attached requests
  • HttpRequestPool::getFinishedRequests — Get finished requests
  • HttpRequestPool::reset — Reset request pool
  • HttpRequestPool::send — Send all requests
  • HttpRequestPool::socketPerform — Perform socket actions
  • HttpRequestPool::socketSelect — Perform socket select
HttpRequest::setUrl
HttpRequestPool::attach
HTTP


Attach HttpRequest

HttpRequestPool
HttpRequestPool::__construct
HttpRequestPool
PHP Manual

HttpRequestPool::attach

(PECL pecl_http >= 0.10.0)

HttpRequestPool::attach — Attach HttpRequest

Opis

public bool HttpRequestPool::attach ( HttpRequest $request )

Attach an HttpRequest object to this HttpRequestPool.

Ostrzeżenie

Set all options prior attaching!

Parametry

request

an HttpRequest object not already attached to any HttpRequestPool object

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws HttpInvalidParamException, HttpRequestException, HttpRequestPoolException, HttpEncodingException.

HttpRequestPool
HttpRequestPool::__construct
HttpRequestPool


HttpRequestPool constructor

HttpRequestPool::attach
HttpRequestPool::__destruct
HttpRequestPool
PHP Manual

HttpRequestPool::__construct

(PECL pecl_http >= 0.10.0)

HttpRequestPool::__construct — HttpRequestPool constructor

Opis

public HttpRequestPool::__construct ([ HttpRequest $request [, HttpRequest $... ]] )

Instantiate a new HttpRequestPool object. An HttpRequestPool is able to send several HttpRequests in parallel.

Accepts virtually infinite optional parameters each referencing an HttpRequest object.

Parametry

request

HttpRequest object to attach

...

Błędy/Wyjątki

Throws HttpRequestPoolException (HttpRequestException, HttpInvalidParamException).

Przykłady

Przykład #1 A HttpRequestPool example

<?php
try {
    $pool = new HttpRequestPool(
        new HttpRequest('http://www.google.com/', HttpRequest::METH_HEAD),
        new HttpRequest('http://www.php.net/', HttpRequest::METH_HEAD)
    );
    $pool->send();
    foreach($pool as $request) {
        printf("%s is %s (%d)\n",
            $request->getUrl(),
            $request->getResponseCode() ? 'alive' : 'not alive',
            $request->getResponseCode()
        );
    }
} catch (HttpException $e) {
    echo $e;
}
?>

HttpRequestPool::attach
HttpRequestPool::__destruct
HttpRequestPool


HttpRequestPool destructor

HttpRequestPool::__construct
HttpRequestPool::detach
HttpRequestPool
PHP Manual

HttpRequestPool::__destruct

(PECL pecl_http >= 0.10.0)

HttpRequestPool::__destruct — HttpRequestPool destructor

Opis

void HttpRequestPool::__destruct ( void )

Clean up HttpRequestPool object.

HttpRequestPool::__construct
HttpRequestPool::detach
HttpRequestPool


Detach HttpRequest

HttpRequestPool::__destruct
HttpRequestPool::getAttachedRequests
HttpRequestPool
PHP Manual

HttpRequestPool::detach

(PECL pecl_http >= 0.10.0)

HttpRequestPool::detach — Detach HttpRequest

Opis

bool HttpRequestPool::detach ( HttpRequest $request )

Detach an HttpRequest object from this HttpRequestPool.

Parametry

request

an HttpRequest object attached to this HttpRequestPool object

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws HttpInvalidParamException, HttpRequestPoolException.

HttpRequestPool::__destruct
HttpRequestPool::getAttachedRequests
HttpRequestPool


Get attached requests

HttpRequestPool::detach
HttpRequestPool::getFinishedRequests
HttpRequestPool
PHP Manual

HttpRequestPool::getAttachedRequests

(PECL pecl_http >= 0.16.0)

HttpRequestPool::getAttachedRequests — Get attached requests

Opis

array HttpRequestPool::getAttachedRequests ( void )

Get attached HttpRequest objects.

Parametry

Zwracane wartości

Returns an array containing all currently attached HttpRequest objects.

HttpRequestPool::detach
HttpRequestPool::getFinishedRequests
HttpRequestPool


Get finished requests

HttpRequestPool::getAttachedRequests
HttpRequestPool::reset
HttpRequestPool
PHP Manual

HttpRequestPool::getFinishedRequests

(PECL pecl_http >= 0.16.0)

HttpRequestPool::getFinishedRequests — Get finished requests

Opis

array HttpRequestPool::getFinishedRequests ( void )

Get attached HttpRequest objects that already have finished their work.

Parametry

Zwracane wartości

Returns an array containing all attached HttpRequest objects that already have finished their work.

HttpRequestPool::getAttachedRequests
HttpRequestPool::reset
HttpRequestPool


Reset request pool

HttpRequestPool::getFinishedRequests
HttpRequestPool::send
HttpRequestPool
PHP Manual

HttpRequestPool::reset

(PECL pecl_http >= 0.10.0)

HttpRequestPool::reset — Reset request pool

Opis

void HttpRequestPool::reset ( void )

Detach all attached HttpRequest objects.

HttpRequestPool::getFinishedRequests
HttpRequestPool::send
HttpRequestPool


Send all requests

HttpRequestPool::reset
HttpRequestPool::socketPerform
HttpRequestPool
PHP Manual

HttpRequestPool::send

(PECL pecl_http >= 0.10.0)

HttpRequestPool::send — Send all requests

Opis

bool HttpRequestPool::send ( void )

Send all attached HttpRequest objects in parallel.

Parametry

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws HttpRequestPoolException (HttpSocketException, HttpRequestException, HttpMalformedHeaderException).

HttpRequestPool::reset
HttpRequestPool::socketPerform
HttpRequestPool


Perform socket actions

HttpRequestPool::send
HttpRequestPool::socketSelect
HttpRequestPool
PHP Manual

HttpRequestPool::socketPerform

(PECL pecl_http >= 0.15.0)

HttpRequestPool::socketPerform — Perform socket actions

Opis

protected bool HttpRequestPool::socketPerform ( void )

Returns TRUE until each request has finished its transaction.

Zwracane wartości

Returns TRUE until each request has finished its transaction.

Przykłady

Przykład #1 A HttpRequestPool::socketPerform() example

<?php
class MyPool extends HttpRequestPool
{
    public function send()
    {
        while ($this->socketPerform()) {
            if (!$this->socketSelect()) {
                throw new HttpSocketExcpetion;
            }
        }
    }

    protected final function socketPerform()
    {
        $result = parent::socketPerform();
        foreach ($this->getFinishedRequests() as $r) {
            $this->detach($r);
            // handle response of finished request
        }
        return $result;
    }
}
?>

HttpRequestPool::send
HttpRequestPool::socketSelect
HttpRequestPool


Perform socket select

HttpRequestPool::socketPerform
HttpResponse
HttpRequestPool
PHP Manual

HttpRequestPool::socketSelect

(PECL pecl_http >= 0.10.0)

HttpRequestPool::socketSelect — Perform socket select

Opis

protected bool HttpRequestPool::socketSelect ([ float $timeout = 0 ] )

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

HttpRequestPool::socketPerform
HttpResponse
HttpRequestPool


The HttpResponse

(No version information available, might only be in SVN)

Krótki opis klasy

HttpResponse {
static void capture ( void )
static int getBufferSize ( void )
static bool getCache ( void )
static string getCacheControl ( void )
static string getContentDisposition ( void )
static string getContentType ( void )
static string getData ( void )
static string getETag ( void )
static string getFile ( void )
static bool getGzip ( void )
static mixed getHeader ([ string $name ] )
static int getLastModified ( void )
static string getRequestBody ( void )
static resource getRequestBodyStream ( void )
static array getRequestHeaders ( void )
static resource getStream ( void )
static float getThrottleDelay ( void )
static string guessContentType ( string $magic_file [, int $magic_mode = MAGIC_MIME ] )
static void redirect ([ string $url [, array $params [, bool $session = false [, int $status ]]]] )
static bool send ([ bool $clean_ob = true ] )
static bool setBufferSize ( int $bytes )
static bool setCache ( bool $cache )
static bool setCacheControl ( string $control [, int $max_age = 0 [, bool $must_revalidate = true ]] )
static bool setContentDisposition ( string $filename [, bool $inline = false ] )
static bool setContentType ( string $content_type )
static bool setData ( mixed $data )
static bool setETag ( string $etag )
static bool setFile ( string $file )
static bool setGzip ( bool $gzip )
static bool setHeader ( string $name [, mixed $value [, bool $replace = true ]] )
static bool setLastModified ( int $timestamp )
static bool setStream ( resource $stream )
static bool setThrottleDelay ( float $seconds )
static bool status ( int $status )
}

Class Members

Właściwości

Static Properties
Modifiers | Type | Name | Description
protected | boolean | cache | whether caching the response should be attempted
protected | boolean | gzip | whether the sent entity should be gzip'ed on the fly
protected | string | eTag | the generated or custom ETag
protected | integer | lastModified | the generated or custom timestamp of last modification
protected | string | cacheControl | Cache-Control setting
protected | string | contentType | the Content-Type of the sent entity
protected | string | contentDisposition | the Content-Disposition of the sent entity
protected | integer | bufferSize | the chunk buffer size used for throttling
protected | double | throttleDelay | the seconds to delay when throttling

Stałe predefiniowane

Type | Name | Description
integer | REDIRECT | guess applicable redirect method
integer | REDIRECT_PERM | permanent redirect (301 Moved permanently)
integer | REDIRECT_FOUND | standard redirect (302 Found)
integer | REDIRECT_POST | redirect applicable to POST requests (303 See other)
integer | REDIRECT_PROXY | proxy redirect (305 Use proxy)
integer | REDIRECT_TEMP | temporary redirect (307 Temporary Redirect)

Spis treści

  • HttpResponse::capture — Capture script output
  • HttpResponse::getBufferSize — Get buffer size
  • HttpResponse::getCache — Get cache
  • HttpResponse::getCacheControl — Get cache control
  • HttpResponse::getContentDisposition — Get content disposition
  • HttpResponse::getContentType — Get content type
  • HttpResponse::getData — Get data
  • HttpResponse::getETag — Get ETag
  • HttpResponse::getFile — Get file
  • HttpResponse::getGzip — Get gzip
  • HttpResponse::getHeader — Get header
  • HttpResponse::getLastModified — Get last modified
  • HttpResponse::getRequestBody — Get request body
  • HttpResponse::getRequestBodyStream — Get request body stream
  • HttpResponse::getRequestHeaders — Get request headers
  • HttpResponse::getStream — Get Stream
  • HttpResponse::getThrottleDelay — Get throttle delay
  • HttpResponse::guessContentType — Guess content type
  • HttpResponse::redirect — Redirect
  • HttpResponse::send — Send response
  • HttpResponse::setBufferSize — Set buffer size
  • HttpResponse::setCache — Set cache
  • HttpResponse::setCacheControl — Set cache control
  • HttpResponse::setContentDisposition — Set content disposition
  • HttpResponse::setContentType — Set content type
  • HttpResponse::setData — Set data
  • HttpResponse::setETag — Set ETag
  • HttpResponse::setFile — Set file
  • HttpResponse::setGzip — Set gzip
  • HttpResponse::setHeader — Set header
  • HttpResponse::setLastModified — Set last modified
  • HttpResponse::setStream — Set stream
  • HttpResponse::setThrottleDelay — Set throttle delay
  • HttpResponse::status — Send HTTP response status
HttpRequestPool::socketSelect
HttpResponse::capture
HTTP


Capture script output

HttpResponse
HttpResponse::getBufferSize
HttpResponse
PHP Manual

HttpResponse::capture

(PECL pecl_http >= 0.10.0)

HttpResponse::capture — Capture script output

Opis

static void HttpResponse::capture ( void )

Capture script output.

Przykłady

Przykład #1 A HttpResponse::capture() example

<?php
HttpResponse::setCache(true);
HttpResponse::capture();
// script follows
?>

Zobacz też:

  • HttpResponse::send() - Send response

HttpResponse
HttpResponse::getBufferSize
HttpResponse


Get buffer size

HttpResponse::capture
HttpResponse::getCache
HttpResponse
PHP Manual

HttpResponse::getBufferSize

(PECL pecl_http >= 0.10.0)

HttpResponse::getBufferSize — Get buffer size

Opis

static int HttpResponse::getBufferSize ( void )

Get current buffer size.

Zwracane wartości

Returns an int representing the current buffer size in bytes.

Zobacz też:

  • HttpResponse::setBufferSize() - Set buffer size
  • HttpResponse::getThrottleDelay() - Get throttle delay
  • HttpResponse::setThrottleDelay() - Set throttle delay

HttpResponse::capture
HttpResponse::getCache
HttpResponse


Get cache

HttpResponse::getBufferSize
HttpResponse::getCacheControl
HttpResponse
PHP Manual

HttpResponse::getCache

(PECL pecl_http >= 0.10.0)

HttpResponse::getCache — Get cache

Opis

static bool HttpResponse::getCache ( void )

Get current caching setting.

Zwracane wartości

Returns TRUE if caching should be attempted, else FALSE.

Zobacz też:

  • HttpResponse::setCacheControl() - Set cache control
  • HttpResponse::getCacheControl() - Get cache control
  • HttpResponse::setCache() - Set cache

HttpResponse::getBufferSize
HttpResponse::getCacheControl
HttpResponse


Get cache control

HttpResponse::getCache
HttpResponse::getContentDisposition
HttpResponse
PHP Manual

HttpResponse::getCacheControl

(PECL pecl_http >= 0.10.0)

HttpResponse::getCacheControl — Get cache control

Opis

static string HttpResponse::getCacheControl ( void )

Get current Cache-Control header setting.

Zwracane wartości

Returns the current cache control setting as a string like sent in a header.

Zobacz też:

  • HttpResponse::setCacheControl() - Set cache control
  • HttpResponse::setCache() - Set cache
  • HttpResponse::getCache() - Get cache

HttpResponse::getCache
HttpResponse::getContentDisposition
HttpResponse


Get content disposition

HttpResponse::getCacheControl
HttpResponse::getContentType
HttpResponse
PHP Manual

HttpResponse::getContentDisposition

(PECL pecl_http >= 0.10.0)

HttpResponse::getContentDisposition — Get content disposition

Opis

static string HttpResponse::getContentDisposition ( void )

Get current Content-Disposition setting.

Zwracane wartości

Returns the current content disposition as string like sent in a header.

Zobacz też:

  • HttpResponse::setContentDisposition() - Set content disposition
  • HttpResponse::getContentType() - Get content type
  • HttpResponse::setContentType() - Set content type

HttpResponse::getCacheControl
HttpResponse::getContentType
HttpResponse


Get content type

HttpResponse::getContentDisposition
HttpResponse::getData
HttpResponse
PHP Manual

HttpResponse::getContentType

(PECL pecl_http >= 0.10.0)

HttpResponse::getContentType — Get content type

Opis

static string HttpResponse::getContentType ( void )

Get current Content-Type header setting.

Zwracane wartości

Returns the currently set content type as string.

Zobacz też:

  • HttpResponse::getContentDisposition() - Get content disposition
  • HttpResponse::setContentDisposition() - Set content disposition
  • HttpResponse::setContentType() - Set content type
  • HttpResponse::guessContentType() - Guess content type

HttpResponse::getContentDisposition
HttpResponse::getData
HttpResponse


Get data

HttpResponse::getContentType
HttpResponse::getETag
HttpResponse
PHP Manual

HttpResponse::getData

(PECL pecl_http >= 0.10.0)

HttpResponse::getData — Get data

Opis

static string HttpResponse::getData ( void )

Get the previously set data to be sent.

Zwracane wartości

Returns a string containing the previously set data to send.

Zobacz też:

  • HttpResponse::setData() - Set data
  • HttpResponse::getFile() - Get file
  • HttpResponse::setFile() - Set file
  • HttpResponse::getStream() - Get Stream
  • HttpResponse::setStream() - Set stream

HttpResponse::getContentType
HttpResponse::getETag
HttpResponse


Get ETag

HttpResponse::getData
HttpResponse::getFile
HttpResponse
PHP Manual

HttpResponse::getETag

(PECL pecl_http >= 0.10.0)

HttpResponse::getETag — Get ETag

Opis

static string HttpResponse::getETag ( void )

Get calculated or previously set custom ETag.

Zwracane wartości

Returns the calculated or previously set ETag as unquoted string.

Zobacz też:

  • HttpResponse::getLastModified() - Get last modified
  • HttpResponse::setLastModified() - Set last modified
  • HttpResponse::setETag() - Set ETag

HttpResponse::getData
HttpResponse::getFile
HttpResponse


Get file

HttpResponse::getETag
HttpResponse::getGzip
HttpResponse
PHP Manual

HttpResponse::getFile

(PECL pecl_http >= 0.10.0)

HttpResponse::getFile — Get file

Opis

static string HttpResponse::getFile ( void )

Get the previously set file to be sent.

Zwracane wartości

Returns the previously set path to the file to send as string.

Zobacz też:

  • HttpResponse::getData() - Get data
  • HttpResponse::setData() - Set data
  • HttpResponse::setFile() - Set file
  • HttpResponse::getStream() - Get Stream
  • HttpResponse::setStream() - Set stream

HttpResponse::getETag
HttpResponse::getGzip
HttpResponse


Get gzip

HttpResponse::getFile
HttpResponse::getHeader
HttpResponse
PHP Manual

HttpResponse::getGzip

(PECL pecl_http >= 0.10.0)

HttpResponse::getGzip — Get gzip

Opis

static bool HttpResponse::getGzip ( void )

Get current gzip'ing setting.

Zwracane wartości

Returns TRUE if GZip compression is enabled, else FALSE.

Zobacz też:

  • HttpResponse::setGzip() - Set gzip

HttpResponse::getFile
HttpResponse::getHeader
HttpResponse


Get header

HttpResponse::getGzip
HttpResponse::getLastModified
HttpResponse
PHP Manual

HttpResponse::getHeader

(PECL pecl_http >= 0.12.0)

HttpResponse::getHeader — Get header

Opis

static mixed HttpResponse::getHeader ([ string $name ] )

Get header(s) about to be sent.

Informacja:

To może nie działać jak się spodziewasz z następującymi SAPI: Apache2 w/PHP < 5.1.3.

Parametry

name

specifies the name of the header to read; if empty or omitted, an associative array with all headers will be returned

Zwracane wartości

Returns either a string containing the value of the header matching name, FALSE on failure, or an associative array with all headers.

Zobacz też:

  • HttpResponse::setHeader() - Set header

HttpResponse::getGzip
HttpResponse::getLastModified
HttpResponse


Get last modified

HttpResponse::getHeader
HttpResponse::getRequestBody
HttpResponse
PHP Manual

HttpResponse::getLastModified

(PECL pecl_http >= 0.12.0)

HttpResponse::getLastModified — Get last modified

Opis

static int HttpResponse::getLastModified ( void )

Get calculated or previously set custom Last-Modified date.

Zwracane wartości

Returns the calculated or previously set Unix timestamp.

Zobacz też:

  • HttpResponse::setLastModified() - Set last modified
  • HttpResponse::getETag() - Get ETag
  • HttpResponse::setETag() - Set ETag

HttpResponse::getHeader
HttpResponse::getRequestBody
HttpResponse


Get request body

HttpResponse::getLastModified
HttpResponse::getRequestBodyStream
HttpResponse
PHP Manual

HttpResponse::getRequestBody

(PECL pecl_http >= 0.10.0)

HttpResponse::getRequestBody — Get request body

Opis

static string HttpResponse::getRequestBody ( void )

Ta funkcja jest aliasem dla: http_get_request_body().

HttpResponse::getLastModified
HttpResponse::getRequestBodyStream
HttpResponse


Get request body stream

HttpResponse::getRequestBody
HttpResponse::getRequestHeaders
HttpResponse
PHP Manual

HttpResponse::getRequestBodyStream

(PECL pecl_http >= 0.10.0)

HttpResponse::getRequestBodyStream — Get request body stream

Opis

static resource HttpResponse::getRequestBodyStream ( void )

Ta funkcja jest aliasem dla: http_get_request_body_stream().

HttpResponse::getRequestBody
HttpResponse::getRequestHeaders
HttpResponse


Get request headers

HttpResponse::getRequestBodyStream
HttpResponse::getStream
HttpResponse
PHP Manual

HttpResponse::getRequestHeaders

(PECL pecl_http >= 0.10.0)

HttpResponse::getRequestHeaders — Get request headers

Opis

static array HttpResponse::getRequestHeaders ( void )

Ta funkcja jest aliasem dla: http_get_request_headers().

HttpResponse::getRequestBodyStream
HttpResponse::getStream
HttpResponse


Get Stream

HttpResponse::getRequestHeaders
HttpResponse::getThrottleDelay
HttpResponse
PHP Manual

HttpResponse::getStream

(PECL pecl_http >= 0.10.0)

HttpResponse::getStream — Get Stream

Opis

static resource HttpResponse::getStream ( void )

Get the previously set resource to be sent.

Parametry

Zwracane wartości

Returns the previously set resource.

Zobacz też:

  • HttpResponse::getData() - Get data
  • HttpResponse::setData() - Set data
  • HttpResponse::getFile() - Get file
  • HttpResponse::setFile() - Set file
  • HttpResponse::setStream() - Set stream

HttpResponse::getRequestHeaders
HttpResponse::getThrottleDelay
HttpResponse


Get throttle delay

HttpResponse::getStream
HttpResponse::guessContentType
HttpResponse
PHP Manual

HttpResponse::getThrottleDelay

(PECL pecl_http >= 0.10.0)

HttpResponse::getThrottleDelay — Get throttle delay

Opis

static float HttpResponse::getThrottleDelay ( void )

Get the current throttle delay.

Zwracane wartości

Returns a double representing the throttle delay in seconds.

Zobacz też:

  • HttpResponse::getBufferSize() - Get buffer size
  • HttpResponse::setBufferSize() - Set buffer size
  • HttpResponse::setThrottleDelay() - Set throttle delay

HttpResponse::getStream
HttpResponse::guessContentType
HttpResponse


Guess content type

HttpResponse::getThrottleDelay
HttpResponse::redirect
HttpResponse
PHP Manual

HttpResponse::guessContentType

(PECL pecl_http >= 0.13.0)

HttpResponse::guessContentType — Guess content type

Opis

static string HttpResponse::guessContentType ( string $magic_file [, int $magic_mode = MAGIC_MIME ] )

Attempts to guess the content type of supplied payload through libmagic.

If the attempt is successful, the guessed Content-Type will automatically be set as response Content-Type.

Parametry

magic_file

specifies the magic.mime database to use

magic_mode

flags for libmagic

Zwracane wartości

Returns the guessed content type on success lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Throws HttpRuntimeException, HttpInvalidParamException.

Zobacz też:

  • HttpResponse::getContentType() - Get content type
  • HttpResponse::setContentType() - Set content type

HttpResponse::getThrottleDelay
HttpResponse::redirect
HttpResponse


Redirect

HttpResponse::guessContentType
HttpResponse::send
HttpResponse
PHP Manual

HttpResponse::redirect

(PECL pecl_http >= 0.10.0)

HttpResponse::redirect — Redirect

Opis

static void HttpResponse::redirect ([ string $url [, array $params [, bool $session = false [, int $status ]]]] )

Ta funkcja jest aliasem dla: http_redirect().

HttpResponse::guessContentType
HttpResponse::send
HttpResponse


Send response

HttpResponse::redirect
HttpResponse::setBufferSize
HttpResponse
PHP Manual

HttpResponse::send

(PECL pecl_http >= 0.10.0)

HttpResponse::send — Send response

Opis

static bool HttpResponse::send ([ bool $clean_ob = true ] )

Finally send the entity.

A successful caching attempt will exit PHP, and write a log entry if the ustawienia INI http.log.cache is set. Patrz ustawienia INI http.force_exit co znaczą "exist".

Parametry

clean_ob

whether to destroy all previously started output handlers and their buffers

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A HttpResponse::send() example

<?php
HttpResponse::setCache(true);
HttpResponse::setContentType('application/pdf');
HttpResponse::setContentDisposition("$user.pdf", false);
HttpResponse::setFile('sheet.pdf');
HttpResponse::send();
?>

Zobacz też:

  • HttpResponse::capture() - Capture script output

HttpResponse::redirect
HttpResponse::setBufferSize
HttpResponse


Set buffer size

HttpResponse::send
HttpResponse::setCache
HttpResponse
PHP Manual

HttpResponse::setBufferSize

(PECL pecl_http >= 0.10.0)

HttpResponse::setBufferSize — Set buffer size

Opis

static bool HttpResponse::setBufferSize ( int $bytes )

Sets the send buffer size of the throttling mechanism.

Informacja: Zapewnia podstawowy mechanizm dławiący, który będzie podtrzymywać bieżący proces lub wątek, dopóki nie zostanie wysłana całość.

Informacja:

To może nie działać jak się spodziewasz z następującymi SAPI: FastCGI.

Parametry

bytes

the chunk size in bytes

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getBufferSize() - Get buffer size
  • HttpResponse::getThrottleDelay() - Get throttle delay
  • HttpResponse::setThrottleDelay() - Set throttle delay

HttpResponse::send
HttpResponse::setCache
HttpResponse


Set cache

HttpResponse::setBufferSize
HttpResponse::setCacheControl
HttpResponse
PHP Manual

HttpResponse::setCache

(PECL pecl_http >= 0.10.0)

HttpResponse::setCache — Set cache

Opis

static bool HttpResponse::setCache ( bool $cache )

Whether it should be attempted to cache the entity.

This will result in necessary caching headers and checks of clients If-Modified-Since and If-None-Match headers. If one of those headers matches a 304 Not Modified status code will be issued.

Informacja:

If you're using sessions, be sure that you set session.cache_limiter to something more appropriate than "no-cache"!

Parametry

cache

whether caching should be attempted

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::setCacheControl() - Set cache control
  • HttpResponse::getCacheControl() - Get cache control
  • HttpResponse::getCachel()

HttpResponse::setBufferSize
HttpResponse::setCacheControl
HttpResponse


Set cache control

HttpResponse::setCache
HttpResponse::setContentDisposition
HttpResponse
PHP Manual

HttpResponse::setCacheControl

(PECL pecl_http >= 0.10.0)

HttpResponse::setCacheControl — Set cache control

Opis

static bool HttpResponse::setCacheControl ( string $control [, int $max_age = 0 [, bool $must_revalidate = true ]] )

Define a custom Cache-Control header, usually being private or public;

Parametry

control

the primary cache control setting

max_age

the max-age in seconds, suggesting how long the cache entry is valid on the client side

must_revalidate

whether the cached entity should be revalidated by the client for every request

Zwracane wartości

Returns TRUE on success, or FALSE if control does not match one of public, private or no-cache.

Zobacz też:

  • HttpResponse::getCacheControl() - Get cache control
  • HttpResponse::setCache() - Set cache
  • HttpResponse::getCache() - Get cache

HttpResponse::setCache
HttpResponse::setContentDisposition
HttpResponse


Set content disposition

HttpResponse::setCacheControl
HttpResponse::setContentType
HttpResponse
PHP Manual

HttpResponse::setContentDisposition

(PECL pecl_http >= 0.10.0)

HttpResponse::setContentDisposition — Set content disposition

Opis

static bool HttpResponse::setContentDisposition ( string $filename [, bool $inline = false ] )

Set the Content-Disposition. Nagłowek Content-Disposition jest bardzo użyteczny jeśli dane aktualnie wysyłane pochodzą z pliku lub czegoś podobnego, które powinny być "zapisane" przez klienta/użytkownika (np. przez okienko popup przeglądarki "Zapisz jako...").

Parametry

filename

the file name the "Save as..." dialog should display

inline

if set to true and the user agent knows how to handle the content type, it will probably not cause the popup window to be shown

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getContentDisposition() - Get content disposition
  • HttpResponse::getContentType() - Get content type
  • HttpResponse::setContentType() - Set content type

HttpResponse::setCacheControl
HttpResponse::setContentType
HttpResponse


Set content type

HttpResponse::setContentDisposition
HttpResponse::setData
HttpResponse
PHP Manual

HttpResponse::setContentType

(PECL pecl_http >= 0.10.0)

HttpResponse::setContentType — Set content type

Opis

static bool HttpResponse::setContentType ( string $content_type )

Set the Content-Type of the sent entity.

Parametry

content_type

the content type of the sent entity (primary/secondary)

Zwracane wartości

Returns TRUE on success, or FALSE if the content type does not seem to contain a primary and secondary content type part.

Zobacz też:

  • HttpResponse::getContentDisposition() - Get content disposition
  • HttpResponse::setContentDisposition() - Set content disposition
  • HttpResponse::getContentType() - Get content type
  • HttpResponse::guessContentType() - Guess content type

HttpResponse::setContentDisposition
HttpResponse::setData
HttpResponse


Set data

HttpResponse::setContentType
HttpResponse::setETag
HttpResponse
PHP Manual

HttpResponse::setData

(PECL pecl_http >= 0.10.0)

HttpResponse::setData — Set data

Opis

static bool HttpResponse::setData ( mixed $data )

Set the data to be sent.

Informacja: Wcześniej obliczony lub zdefiniowany ETag i Last-Modified zostanie obliczony ponownie i zdefiniowany.

Parametry

data

data to send

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getData() - Get data
  • HttpResponse::getFile() - Get file
  • HttpResponse::setFile() - Set file
  • HttpResponse::getStream() - Get Stream
  • HttpResponse::setStream() - Set stream

HttpResponse::setContentType
HttpResponse::setETag
HttpResponse


Set ETag

HttpResponse::setData
HttpResponse::setFile
HttpResponse
PHP Manual

HttpResponse::setETag

(PECL pecl_http >= 0.10.0)

HttpResponse::setETag — Set ETag

Opis

static bool HttpResponse::setETag ( string $etag )

Set a custom ETag. Use this only if you know what you're doing.

Parametry

etag

unquoted string as parameter containing the ETag

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getLastModified() - Get last modified
  • HttpResponse::setLastModified() - Set last modified
  • HttpResponse::getETag() - Get ETag

HttpResponse::setData
HttpResponse::setFile
HttpResponse


Set file

HttpResponse::setETag
HttpResponse::setGzip
HttpResponse
PHP Manual

HttpResponse::setFile

(PECL pecl_http >= 0.10.0)

HttpResponse::setFile — Set file

Opis

static bool HttpResponse::setFile ( string $file )

Set the file to be sent.

Informacja: Wcześniej obliczony lub zdefiniowany ETag i Last-Modified zostanie obliczony ponownie i zdefiniowany.

Parametry

file

the path to the file to send

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getData() - Get data
  • HttpResponse::setData() - Set data
  • HttpResponse::getFile() - Get file
  • HttpResponse::getStream() - Get Stream
  • HttpResponse::setStream() - Set stream

HttpResponse::setETag
HttpResponse::setGzip
HttpResponse


Set gzip

HttpResponse::setFile
HttpResponse::setHeader
HttpResponse
PHP Manual

HttpResponse::setGzip

(PECL pecl_http >= 0.10.0)

HttpResponse::setGzip — Set gzip

Opis

static bool HttpResponse::setGzip ( bool $gzip )

Enable on-thy-fly gzip'ing of the sent entity.

Parametry

gzip

whether GZip compression should be enabled

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getGzip() - Get gzip

HttpResponse::setFile
HttpResponse::setHeader
HttpResponse


Set header

HttpResponse::setGzip
HttpResponse::setLastModified
HttpResponse
PHP Manual

HttpResponse::setHeader

(PECL pecl_http >= 0.12.0)

HttpResponse::setHeader — Set header

Opis

static bool HttpResponse::setHeader ( string $name [, mixed $value [, bool $replace = true ]] )

Send an HTTP header.

Parametry

name

the name of the header

value

the value of the header; if not set, no header with this name will be sent

replace

whether an existing header should be replaced

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getHeader() - Get header

HttpResponse::setGzip
HttpResponse::setLastModified
HttpResponse


Set last modified

HttpResponse::setHeader
HttpResponse::setStream
HttpResponse
PHP Manual

HttpResponse::setLastModified

(PECL pecl_http >= 0.12.0)

HttpResponse::setLastModified — Set last modified

Opis

static bool HttpResponse::setLastModified ( int $timestamp )

Set a custom Last-Modified date.

Parametry

timestamp

Unix timestamp representing the last modification time of the sent entity

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getLastModified() - Get last modified
  • HttpResponse::getETag() - Get ETag
  • HttpResponse::setETag() - Set ETag

HttpResponse::setHeader
HttpResponse::setStream
HttpResponse


Set stream

HttpResponse::setLastModified
HttpResponse::setThrottleDelay
HttpResponse
PHP Manual

HttpResponse::setStream

(PECL pecl_http >= 0.10.0)

HttpResponse::setStream — Set stream

Opis

static bool HttpResponse::setStream ( resource $stream )

Set the resource to be sent.

Informacja: Wcześniej obliczony lub zdefiniowany ETag i Last-Modified zostanie obliczony ponownie i zdefiniowany.

Parametry

stream

already opened stream from which the data to send will be read

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getData() - Get data
  • HttpResponse::setData() - Set data
  • HttpResponse::getFile() - Get file
  • HttpResponse::setFile() - Set file
  • HttpResponse::getStream() - Get Stream

HttpResponse::setLastModified
HttpResponse::setThrottleDelay
HttpResponse


Set throttle delay

HttpResponse::setStream
HttpResponse::status
HttpResponse
PHP Manual

HttpResponse::setThrottleDelay

(PECL pecl_http >= 0.10.0)

HttpResponse::setThrottleDelay — Set throttle delay

Opis

static bool HttpResponse::setThrottleDelay ( float $seconds )

Sets the throttle delay.

Informacja: Zapewnia podstawowy mechanizm dławiący, który będzie podtrzymywać bieżący proces lub wątek, dopóki nie zostanie wysłana całość.

Informacja:

To może nie działać jak się spodziewasz z następującymi SAPI: FastCGI.

Parametry

seconds

seconds to sleep after each chunk sent

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • HttpResponse::getBufferSize() - Get buffer size
  • HttpResponse::setBufferSize() - Set buffer size
  • HttpResponse::getThrottleDelay() - Get throttle delay

HttpResponse::setStream
HttpResponse::status
HttpResponse


Send HTTP response status

HttpResponse::setThrottleDelay
HTTP Funkcje
HttpResponse
PHP Manual

HttpResponse::status

(PECL pecl_http >= 0.12.0)

HttpResponse::status — Send HTTP response status

Opis

static bool HttpResponse::status ( int $status )

Ta funkcja jest aliasem dla: http_send_status().

HttpResponse::setThrottleDelay
HTTP Funkcje
HttpResponse


HTTP Funkcje

Poprzedni spis wbudowanych funkcji dotyczących HTTP prezentowany na tej strony, znajdziesz w kategori sieciowość.

Poniższe funkcje nie wymagają modułu HTTP, aby były dostępne: header(), headers_list(), headers_sent(), setcookie() i setrawcookie().

Grupy funkcji

Buforowanie

  • http_cache_etag()
  • http_cache_last_modified()

Kodowanie

  • http_chunked_decode()
  • http_deflate()
  • http_inflate()

Różne

  • http_build_cookie()
  • http_date()
  • http_get_request_body_stream()
  • http_get_request_body()
  • http_get_request_headers()
  • http_match_etag()
  • http_match_modified()
  • http_match_request_header()
  • http_support()

Negocjacja

  • http_negotiate_charset()
  • http_negotiate_content_type()
  • http_negotiate_language()

Obsługa wyjścia

  • ob_deflatehandler()
  • ob_etaghandler()
  • ob_inflatehandler()

Przetwarzanie

  • http_parse_cookie()
  • http_parse_headers()
  • http_parse_message()
  • http_parse_params()

Żądania

  • http_get()
  • http_head()
  • http_post_data()
  • http_post_fields()
  • http_put_data()
  • http_put_file()
  • http_put_stream()
  • http_request_body_encode()
  • http_request_method_exists()
  • http_request_method_name()
  • http_request_method_register()
  • http_request_method_unregister()
  • http_request()

Odpowiedzi

  • http_redirect()
  • http_send_content_disposition()
  • http_send_content_type()
  • http_send_data()
  • http_send_file()
  • http_send_last_modified()
  • http_send_status()
  • http_send_stream()
  • http_throttle()

URLe

  • http_build_str()
  • http_build_url()

Stałe uchwyty

  • http_persistent_handles_count()
  • http_persistent_handles_ident()
  • http_persistent_handles_clean()

Spis treści

  • http_cache_etag — Caching by ETag
  • http_cache_last_modified — Caching by last modification
  • http_chunked_decode — Decode chunked-encoded data
  • http_deflate — Deflate data
  • http_inflate — Inflate data
  • http_build_cookie — Build cookie string
  • http_date — Compose HTTP RFC compliant date
  • http_get_request_body_stream — Get request body as stream
  • http_get_request_body — Get request body as string
  • http_get_request_headers — Get request headers as array
  • http_match_etag — Match ETag
  • http_match_modified — Match last modification
  • http_match_request_header — Match any header
  • http_support — Check built-in HTTP support
  • http_negotiate_charset — Negotiate clients preferred character set
  • http_negotiate_content_type — Negotiate clients preferred content type
  • http_negotiate_language — Negotiate clients preferred language
  • ob_deflatehandler — Deflate output handler
  • ob_etaghandler — ETag output handler
  • ob_inflatehandler — Inflate output handler
  • http_parse_cookie — Parse HTTP cookie
  • http_parse_headers — Parse HTTP headers
  • http_parse_message — Parse HTTP messages
  • http_parse_params — Parse parameter list
  • http_persistent_handles_clean — Clean up persistent handles
  • http_persistent_handles_count — Stat persistent handles
  • http_persistent_handles_ident — Get/set ident of persistent handles
  • http_get — Perform GET request
  • http_head — Perform HEAD request
  • http_post_data — Perform POST request with pre-encoded data
  • http_post_fields — Perform POST request with data to be encoded
  • http_put_data — Perform PUT request with data
  • http_put_file — Perform PUT request with file
  • http_put_stream — Perform PUT request with stream
  • http_request_body_encode — Encode request body
  • http_request_method_exists — Check whether request method exists
  • http_request_method_name — Get request method name
  • http_request_method_register — Register request method
  • http_request_method_unregister — Unregister request method
  • http_request — Perform custom request
  • http_redirect — Issue HTTP redirect
  • http_send_content_disposition — Send Content-Disposition
  • http_send_content_type — Send Content-Type
  • http_send_data — Send arbitrary data
  • http_send_file — Send file
  • http_send_last_modified — Send Last-Modified
  • http_send_status — Send HTTP response status
  • http_send_stream — Send stream
  • http_throttle — HTTP throttling
  • http_build_str — Build query string
  • http_build_url — Build a URL
HttpResponse::status
http_cache_etag
HTTP


Caching by ETag

HTTP Funkcje
http_cache_last_modified
HTTP Funkcje
PHP Manual

http_cache_etag

(PECL pecl_http >= 0.1.0)

http_cache_etag — Caching by ETag

Opis

bool http_cache_etag ([ string $etag ] )

Attempts to cache the sent entity by its ETag, either supplied or generated by the hash algorithm specified by the ustawienia INI http.etag.mode.

If the clients If-None-Match header matches the supplied/calculated ETag, the body is considered cached on the clients side and a 304 Not Modified status code is issued.

A log entry is written to the cache log if the ustawienia INI http.log.cache is set and the cache attempt was successful.

Informacja: Ta funkcja może być użyta w powiązaniu z http_send_data(), http_send_file() i http_send_stream().

If this function is used outside the http_send_*() API, it facilitates the ob_etaghandler().

Parametry

etag

custom ETag

Zwracane wartości

Zwraca FALSE lub exist w przypadku sukcesu with 304 Not Modified if the entity is cached. Patrz ustawienia INI http.force_exit co znaczą "exist".

Przykłady

Przykład #1 A http_cache_etag() example

<?php
http_cache_etag();
http_send_data("data");
?>

Zobacz też:

  • http_cache_last_modified() - Caching by last modification
  • ob_etaghandler() - ETag output handler
  • http_match_etag() - Match ETag
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

HTTP Funkcje
http_cache_last_modified
HTTP Funkcje


Caching by last modification

http_cache_etag
http_chunked_decode
HTTP Funkcje
PHP Manual

http_cache_last_modified

(PECL pecl_http >= 0.1.0)

http_cache_last_modified — Caching by last modification

Opis

bool http_cache_last_modified ([ int $timestamp_or_expires ] )

Attempts to cache the sent entity by its last modification date.

If the supplied argument is greater than 0, it is handled as timestamp and will be sent as date of last modification. If it is 0 or omitted, the current time will be sent as Last-Modified date. If it's negative, it is handled as expiration time in seconds, which means that if the requested last modification date is not between the calculated timespan, the Last-Modified header is updated and the actual body will be sent.

A log entry will be written to the cache log if the ustawienia INI http.log.cache is set and the cache attempt was successful.

Informacja: Ta funkcja może być użyta w powiązaniu z http_send_data(), http_send_file() i http_send_stream().

Parametry

timestamp_or_expires

Unix timestamp

Zwracane wartości

Zwraca FALSE lub exist w przypadku sukcesu with 304 Not Modified if the entity is cached. Patrz ustawienia INI http.force_exit co znaczą "exist".

Przykłady

Przykład #1 A http_cache_last_modified() example

Caching for 5 seconds.

<?php
http_cache_last_modified(-5);
printf("%s\n", http_date());
?>

Zobacz też:

  • http_cache_etag() - Caching by ETag
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_cache_etag
http_chunked_decode
HTTP Funkcje


Decode chunked-encoded data

http_cache_last_modified
http_deflate
HTTP Funkcje
PHP Manual

http_chunked_decode

(PECL pecl_http >= 0.1.0)

http_chunked_decode — Decode chunked-encoded data

Opis

string http_chunked_decode ( string $encoded )

Decodes a string which is HTTP-chunked encoded.

Parametry

encoded

chunked encoded string

Zwracane wartości

Returns the decoded string on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 A http_chunked_decode() example

<?php
$string = "".
    "05\r\n".
    "this \r\n".
    "07\r\n".
    "string \r\n".
    "12\r\n".
    "is chunked encoded\r\n".
    "01\n\r\n".
    "00";
echo http_chunked_decode($string);
?>

Powyższy przykład wyświetli:

this string is chunked encoded

http_cache_last_modified
http_deflate
HTTP Funkcje


Deflate data

http_chunked_decode
http_inflate
HTTP Funkcje
PHP Manual

http_deflate

(PECL pecl_http >= 0.15.0)

http_deflate — Deflate data

Opis

string http_deflate ( string $data [, int $flags = 0 ] )

Compress data with gzip, zlib AKA deflate or raw deflate encoding.

See the deflate constants table for possible values for the flags parameter.

Parametry

data

String containing the data that should be encoded

flags

deflate options

Zwracane wartości

Returns the encoded string on success, or NULL on failure.

Zobacz też:

  • http_inflate() - Inflate data
  • HttpDeflateStream

http_chunked_decode
http_inflate
HTTP Funkcje


Inflate data

http_deflate
http_build_cookie
HTTP Funkcje
PHP Manual

http_inflate

(PECL pecl_http >= 0.15.0)

http_inflate — Inflate data

Opis

string http_inflate ( string $data )

Decompress data compressed with either gzip, deflate AKA zlib or raw deflate encoding.

Parametry

data

string containing the compressed data

Zwracane wartości

Returns the decoded string on success, or NULL on failure.

Zobacz też:

  • http_deflate() - Deflate data
  • HttpInflateStream

http_deflate
http_build_cookie
HTTP Funkcje


Build cookie string

http_inflate
http_date
HTTP Funkcje
PHP Manual

http_build_cookie

(PECL pecl_http >= 1.2.0)

http_build_cookie — Build cookie string

Opis

string http_build_cookie ( array $cookie )

Build a cookie string from an array/object like returned by http_parse_cookie().

Parametry

cookie

a cookie list like returned from http_parse_cookie()

Zwracane wartości

Returns the cookie(s) as string.

Zobacz też:

  • http_parse_cookie() - Parse HTTP cookie

http_inflate
http_date
HTTP Funkcje


Compose HTTP RFC compliant date

http_build_cookie
http_get_request_body_stream
HTTP Funkcje
PHP Manual

http_date

(PECL pecl_http >= 0.1.0)

http_date — Compose HTTP RFC compliant date

Opis

string http_date ([ int $timestamp ] )

Compose a valid HTTP date regarding RFC 1123 looking like: Wed, 22 Dec 2004 11:34:47 GMT.

Parametry

timestamp

Unix timestamp; current time if omitted

Zwracane wartości

Returns the HTTP date as string.

Zobacz też:

  • date() - Formatuje lokalny czas/datę

http_build_cookie
http_get_request_body_stream
HTTP Funkcje


Get request body as stream

http_date
http_get_request_body
HTTP Funkcje
PHP Manual

http_get_request_body_stream

(PECL pecl_http >= 0.22.0)

http_get_request_body_stream — Get request body as stream

Opis

resource http_get_request_body_stream ( void )

Create a stream to read the raw request body (e.g. POST or PUT data).

This function can only be used once if the request method was another than POST.

Parametry

Zwracane wartości

Returns the raw request body as stream on success or NULL on failure.

Zobacz też:

  • http_get_request_body() - Get request body as string
  • http_get_request_headers() - Get request headers as array
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_date
http_get_request_body
HTTP Funkcje


Get request body as string

http_get_request_body_stream
http_get_request_headers
HTTP Funkcje
PHP Manual

http_get_request_body

(PECL pecl_http >= 0.10.0)

http_get_request_body — Get request body as string

Opis

string http_get_request_body ( void )

Get the raw request body (e.g. POST or PUT data).

This function can not be used after http_get_request_body_stream() if the request method was another than POST.

Parametry

Zwracane wartości

Returns the raw request body as string on success or NULL on failure.

Zobacz też:

  • http_get_request_body_stream() - Get request body as stream
  • http_get_request_headers() - Get request headers as array
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_get_request_body_stream
http_get_request_headers
HTTP Funkcje


Get request headers as array

http_get_request_body
http_match_etag
HTTP Funkcje
PHP Manual

http_get_request_headers

(PECL pecl_http >= 0.10.0)

http_get_request_headers — Get request headers as array

Opis

array http_get_request_headers ( void )

Get a list of incoming HTTP headers.

Parametry

Zwracane wartości

Returns an associative array of incoming request headers.

Zobacz też:

  • http_get_request_body() - Get request body as string
  • http_get_request_body_stream() - Get request body as stream
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_get_request_body
http_match_etag
HTTP Funkcje


Match ETag

http_get_request_headers
http_match_modified
HTTP Funkcje
PHP Manual

http_match_etag

(PECL pecl_http >= 0.1.0)

http_match_etag — Match ETag

Opis

bool http_match_etag ( string $etag [, bool $for_range = false ] )

Matches the given ETag against the clients If-Match resp. If-None-Match HTTP headers.

Parametry

etag

the ETag to match

for_range

if set to TRUE, the header usually used to validate HTTP ranges will be checked

Zwracane wartości

Returns TRUE if ETag matches or the header contained the asterisk ("*"), else FALSE.

Zobacz też:

  • http_match_last_modified()
  • http_match_request_header() - Match any header
  • http_cache_etag() - Caching by ETag
  • http_cache_last_modified() - Caching by last modification
  • ob_etaghandler() - ETag output handler

http_get_request_headers
http_match_modified
HTTP Funkcje


Match last modification

http_match_etag
http_match_request_header
HTTP Funkcje
PHP Manual

http_match_modified

(PECL pecl_http >= 0.1.0)

http_match_modified — Match last modification

Opis

bool http_match_modified ([ int $timestamp = -1 [, bool $for_range = false ]] )

Matches the given Unix timestamp against the clients If-Modified-Since resp. If-Unmodified-Since HTTP headers.

Parametry

timestamp

Unix timestamp; current time, if omitted

for_range

if set to TRUE, the header usually used to validate HTTP ranges will be checked

Zwracane wartości

Returns TRUE if timestamp represents an earlier date than the header, else FALSE.

Zobacz też:

  • http_match_etag() - Match ETag
  • http_match_request_header() - Match any header
  • http_cache_etag() - Caching by ETag
  • http_cache_last_modified() - Caching by last modification

http_match_etag
http_match_request_header
HTTP Funkcje


Match any header

http_match_modified
http_support
HTTP Funkcje
PHP Manual

http_match_request_header

(PECL pecl_http >= 0.10.0)

http_match_request_header — Match any header

Opis

bool http_match_request_header ( string $header , string $value [, bool $match_case = false ] )

Match an incoming HTTP header.

Parametry

header

the header name (case-insensitive)

value

the header value that should be compared

match_case

whether the value should be compared case sensitively

Zwracane wartości

Returns TRUE if header value matches, else FALSE.

Zobacz też:

  • http_match_etag() - Match ETag
  • http_match_last_modified()

http_match_modified
http_support
HTTP Funkcje


Check built-in HTTP support

http_match_request_header
http_negotiate_charset
HTTP Funkcje
PHP Manual

http_support

(PECL pecl_http >= 0.15.0)

http_support — Check built-in HTTP support

Opis

int http_support ([ int $feature = 0 ] )

Check for features that require external libraries.

See the feature support constants table for possible values for the feature argument.

Parametry

feature

feature to probe for

Zwracane wartości

Returns integer, whether requested feature is supported, or a bitmask with all supported features if feature was omitted.

Przykłady

Przykład #1 A http_support() example

<?php
if (!http_support(HTTP_SUPPORT_REQUESTS)) {
    die("Need HTTP request support!\n");
}
?>

http_match_request_header
http_negotiate_charset
HTTP Funkcje


Negotiate clients preferred character set

http_support
http_negotiate_content_type
HTTP Funkcje
PHP Manual

http_negotiate_charset

(PECL pecl_http >= 0.1.0)

http_negotiate_charset — Negotiate clients preferred character set

Opis

string http_negotiate_charset ( array $supported [, array &$result ] )

This function negotiates the clients preferred charset based on its Accept-Charset HTTP header. The qualifier is recognized and charsets without qualifier are rated highest.

Parametry

supported

array containing the supported charsets as values

result

will be filled with an array containing the negotiation results

Zwracane wartości

Returns the negotiated charset or the default charset (i.e. first array entry) if none match.

Przykłady

Przykład #1 Using http_negotiate_charset()

<?php
$charsets = array(
        'iso-8859-1', // default
        'iso-8859-2',
        'iso-8859-15',
        'utf-8'
);

$pref = http_negotiate_charset($charsets, $result);

if (strcmp($pref, 'iso-8859-1')) {
        iconv_set_encoding('internal_encoding', 'iso-8859-1');
        iconv_set_encoding('output_encoding', $pref);
        ob_start('ob_iconv_handler');
}

print_r($result);
?>

http_support
http_negotiate_content_type
HTTP Funkcje


Negotiate clients preferred content type

http_negotiate_charset
http_negotiate_language
HTTP Funkcje
PHP Manual

http_negotiate_content_type

(PECL pecl_http >= 0.19.0)

http_negotiate_content_type — Negotiate clients preferred content type

Opis

string http_negotiate_content_type ( array $supported [, array &$result ] )

This function negotiates the clients preferred content type based on its Accept HTTP header. The qualifier is recognized and content types without qualifier are rated highest.

Parametry

supported

array containing the supported content types as values

result

will be filled with an array containing the negotiation results

Zwracane wartości

Returns the negotiated content type or the default content type (i.e. first array entry) if none match.

Przykłady

Przykład #1 Using http_negotiate_content_type()

<?php
$content_types = array('application/xhtml+xml', 'text/html');
http_send_content_type(http_negotiate_content_type($content_types));
?>

http_negotiate_charset
http_negotiate_language
HTTP Funkcje


Negotiate clients preferred language

http_negotiate_content_type
ob_deflatehandler
HTTP Funkcje
PHP Manual

http_negotiate_language

(PECL pecl_http >= 0.1.0)

http_negotiate_language — Negotiate clients preferred language

Opis

string http_negotiate_language ( array $supported [, array &$result ] )

This function negotiates the clients preferred language based on its Accept-Language HTTP header. The qualifier is recognized and languages without qualifier are rated highest. The qualifier will be decreased by 10% for partial matches (i.e. matching primary language).

Parametry

supported

array containing the supported languages as values

result

will be filled with an array containing the negotiation results

Zwracane wartości

Returns the negotiated language or the default language (i.e. first array entry) if none match.

Przykłady

Przykład #1 Using http_negotiate_language()

<?php
$langs = array(
        'en-US',// default
        'fr',
        'fr-FR',
        'de',
        'de-DE',
        'de-AT',
        'de-CH',
);

include './langs/'. http_negotiate_language($langs, $result) .'.php';

print_r($result);
?>

http_negotiate_content_type
ob_deflatehandler
HTTP Funkcje


Deflate output handler

http_negotiate_language
ob_etaghandler
HTTP Funkcje
PHP Manual

ob_deflatehandler

(PECL pecl_http >= 0.21.0)

ob_deflatehandler — Deflate output handler

Opis

string ob_deflatehandler ( string $data , int $mode )

Do użycia z ob_start().

Informacja: Uchwyt wyjściowy może być użyty tylko raz.

The deflate output buffer handler can only be used once.

It conflicts with ob_gzhandler() and zlib.output_compression as well and should not be used after mbstring extension's mb_output_handler() and session extension's URL-Rewriter (AKA session.use_trans_sid).

Zobacz też:

  • ob_inflatehandler() - Inflate output handler
  • ob_start() - Turn on output buffering

http_negotiate_language
ob_etaghandler
HTTP Funkcje


ETag output handler

ob_deflatehandler
ob_inflatehandler
HTTP Funkcje
PHP Manual

ob_etaghandler

(PECL pecl_http >= 0.10.0)

ob_etaghandler — ETag output handler

Opis

string ob_etaghandler ( string $data , int $mode )

Do użycia z ob_start().

Output buffer handler generating an ETag with the hash algorithm specified with the ustawienia INI http.etag.mode.

This output handler is used by http_cache_etag().

Zobacz też:

  • http_cache_etag() - Caching by ETag
  • http_match_etag() - Match ETag

ob_deflatehandler
ob_inflatehandler
HTTP Funkcje


Inflate output handler

ob_etaghandler
http_parse_cookie
HTTP Funkcje
PHP Manual

ob_inflatehandler

(PECL pecl_http >= 0.21.0)

ob_inflatehandler — Inflate output handler

Opis

string ob_inflatehandler ( string $data , int $mode )

Do użycia z ob_start().

Same restrictions as with ob_deflatehandler() apply.

Zobacz też:

  • ob_deflatehandler() - Deflate output handler
  • ob_start() - Turn on output buffering

ob_etaghandler
http_parse_cookie
HTTP Funkcje


Parse HTTP cookie

ob_inflatehandler
http_parse_headers
HTTP Funkcje
PHP Manual

http_parse_cookie

(PECL pecl_http >= 0.20.0)

http_parse_cookie — Parse HTTP cookie

Opis

object http_parse_cookie ( string $cookie [, int $flags [, array $allowed_extras ]] )

Parses HTTP cookies like sent in a response into a struct.

Parametry

cookie

string containing the value of a Set-Cookie response header

flags

parse flags (HTTP_COOKIE_PARSE_RAW)

allowed_extras

array containing recognized extra keys; by default all unknown keys will be treated as cookie names

Zwracane wartości

Returns a stdClass object on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Using http_parse_cookie()

<?php
print_r(http_parse_cookie("foo=bar; bar=baz; path=/; domain=example.com; comment=; secure", 0, array("comment")));
?>

Powyższy przykład wyświetli:

stdClass Object
(
  [cookies] => Array
  (
    [foo] => bar
    [bar] => baz
  )

  [extras] => Array
  (
    [comment] =>
  )

  [flags] => 16
  [expires] => 0
  [path] => /
  [domain] => example.com
)

Zobacz też:

  • http_parse_headers() - Parse HTTP headers
  • http_parse_message() - Parse HTTP messages
  • http_build_cookie() - Build cookie string

ob_inflatehandler
http_parse_headers
HTTP Funkcje


Parse HTTP headers

http_parse_cookie
http_parse_message
HTTP Funkcje
PHP Manual

http_parse_headers

(PECL pecl_http >= 0.10.0)

http_parse_headers — Parse HTTP headers

Opis

array http_parse_headers ( string $header )

Parses HTTP headers into an associative array.

Parametry

header

string containing HTTP headers

Zwracane wartości

Returns an array on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Using http_parse_headers()

<?php
$headers = "content-type: text/html; charset=UTF-8\r\n".
  "Server: Funky/1.0\r\n".
  "Set-Cookie: foo=bar\r\n".
  "Set-Cookie: baz=quux\r\n".
  "Folded: works\r\n\ttoo\r\n";
print_r(http_parse_headers($headers));
?>

Powyższy przykład wyświetli:

Array
(
  [Content-Type] => text/html; chatset=UTF-8
  [Server] => Funky/1.0
  [Set-Cookie] => Array
  (
    [0] => foo=bar
    [1] => baz=quux
  )
  [Folded] => works
    too
)

Zobacz też:

  • http_parse_message() - Parse HTTP messages
  • http_parse_cookie() - Parse HTTP cookie

http_parse_cookie
http_parse_message
HTTP Funkcje


Parse HTTP messages

http_parse_headers
http_parse_params
HTTP Funkcje
PHP Manual

http_parse_message

(PECL pecl_http >= 0.12.0)

http_parse_message — Parse HTTP messages

Opis

object http_parse_message ( string $message )

Parses the HTTP message into a simple recursive object.

Parametry

message

string containing a single HTTP message or several consecutive HTTP messages

Zwracane wartości

Returns a hierarchical object structure of the parsed messages.

Przykłady

Przykład #1 Using http_parse_message()

<?php
define ('URL', 'http://www.example.com/');
print_r(http_parse_message(http_get(URL, array('redirect' => 3))));
?>

Powyższy przykład wyświetli coś podobnego do:

stdClass object
(
  [type] => 2
  [httpVersion] => 1.1
  [responseCode] => 200
  [headers] => Array
  (
    [Content-Length] => 3
    [Server] => Apache
  )
  [body] => Hi!
  [parentMessage] => stdClass object
  (
    [type] => 2
    [httpVersion] => 1.1
    [responseCode] => 302
    [headers] => Array
    (
      [Content-Length] => 0
      [Location] => ...
    )
    [body] =>
    [parentMessage] => ...
  )
)

Zobacz też:

  • http_parse_headers() - Parse HTTP headers
  • the HttpMessage class

http_parse_headers
http_parse_params
HTTP Funkcje


Parse parameter list

http_parse_message
http_persistent_handles_clean
HTTP Funkcje
PHP Manual

http_parse_params

(PECL pecl_http >= 1.0.0)

http_parse_params — Parse parameter list

Opis

object http_parse_params ( string $param [, int $flags = HTTP_PARAMS_DEFAULT ] )

Parse parameter list.

See the params parsing constants table for possible values of the flags argument.

Parametry

param

Parameters

flags

Parse flags

Zwracane wartości

Returns parameter list as stdClass object.

Przykłady

Przykład #1 A http_parse_params() example

<?php
var_dump(http_parse_params("text/html; charset=\"utf8\""));
?>

Powyższy przykład wyświetli:

object(stdClass)#1 (1) {
  ["params"]=>
  array(2) {
    [0]=>
    string(9) "text/html"
    [1]=>
    array(1) {
      ["charset"]=>
      string(4) "utf8"
    }
  }
}

Zobacz też:

  • http_parse_headers() - Parse HTTP headers
  • http_parse_cookie() - Parse HTTP cookie
  • http_parse_message() - Parse HTTP messages

http_parse_message
http_persistent_handles_clean
HTTP Funkcje


Clean up persistent handles

http_parse_params
http_persistent_handles_count
HTTP Funkcje
PHP Manual

http_persistent_handles_clean

(PECL pecl_http >= 1.5.0)

http_persistent_handles_clean — Clean up persistent handles

Opis

string http_persistent_handles_clean ([ string $ident ] )

Clean up (close) persistent handles, optionally identified with ident.

Parametry

clean

the identification string

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • http_persistent_handles_ident() - Get/set ident of persistent handles
  • http_persistent_handles_count() - Stat persistent handles

http_parse_params
http_persistent_handles_count
HTTP Funkcje


Stat persistent handles

http_persistent_handles_clean
http_persistent_handles_ident
HTTP Funkcje
PHP Manual

http_persistent_handles_count

(PECL pecl_http >= 1.5.0)

http_persistent_handles_count — Stat persistent handles

Opis

object http_persistent_handles_count ( void )

List statistics about persistent handles usage.

Parametry

Zwracane wartości

Returns persistent handles statistics as stdClass object on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 A http_persistent_handles_count() example

<?php
print_r(http_persistent_handles_count());
?>

Powyższy przykład wyświetli:

stdClass Object
(
    [http_request] => Array
        (
            [GLOBAL] => Array
                (
                    [used] => 0
                    [free] => 1
                )

        )

    [http_request_datashare] => Array
        (
            [GLOBAL] => Array
                (
                    [used] => 1
                    [free] => 0
                )

        )

    [http_request_pool] => Array
        (
        )

)

Zobacz też:

  • http_persistent_handles_ident() - Get/set ident of persistent handles
  • http_persistent_handles_clean() - Clean up persistent handles

http_persistent_handles_clean
http_persistent_handles_ident
HTTP Funkcje


Get/set ident of persistent handles

http_persistent_handles_count
http_get
HTTP Funkcje
PHP Manual

http_persistent_handles_ident

(PECL pecl_http >= 1.5.0)

http_persistent_handles_ident — Get/set ident of persistent handles

Opis

string http_persistent_handles_ident ([ string $ident ] )

Query or define the ident of persistent handles.

Parametry

ident

the identification string

Zwracane wartości

Returns the prior ident as string on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 A http_persistent_handles_ident() example

<?php
echo http_persistent_handles_ident("CUSTOM"), "\n";
echo http_persistent_handles_ident("MyApp1"), "\n";
http_get("http://www.example.com/");
print_r(http_persistent_handles_count());
?>

Powyższy przykład wyświetli:

GLOBAL
CUSTOM
stdClass Object
(
[http_request] => Array
(
[MyApp1] => Array
(
[used] => 0
[free] => 1
)

)

[http_request_datashare] => Array
(
[GLOBAL] => Array
(
[used] => 1
[free] => 0
)

)

[http_request_pool] => Array
(
)

)

Zobacz też:

  • http_persistent_handles_count() - Stat persistent handles
  • http_persistent_handles_clean() - Clean up persistent handles

http_persistent_handles_count
http_get
HTTP Funkcje


Perform GET request

http_persistent_handles_ident
http_head
HTTP Funkcje
PHP Manual

http_get

(PECL pecl_http >= 0.1.0)

http_get — Perform GET request

Opis

string http_get ( string $url [, array $options [, array &$info ]] )

Performs an HTTP GET request on the supplied url.

Patrz po pełną listę Opcje żądania.

Parametry

url

URL

options

Opcje żądania

info

Will be filled with request/response information

Zwracane wartości

Zwraca łańcuch znaków z odpowiedziami HTTP w przypadku powodzenia, lub FALSE w przypadku błędu

Przykłady

Przykład #1 A http_get() example

<?php
$response = http_get("http://www.example.com/", array("timeout"=>1), $info);
print_r($info);
?>

Powyższy przykład wyświetli:

array (
  'effective_url' => 'http://www.example.com/',
  'response_code' => 302,
  'connect_code' => 0,
  'filetime' => -1,
  'total_time' => 0.212348,
  'namelookup_time' => 0.038296,
  'connect_time' => 0.104144,
  'pretransfer_time' => 0.104307,
  'starttransfer_time' => 0.212077,
  'redirect_time' => 0,
  'redirect_count' => 0,
  'size_upload' => 0,
  'size_download' => 218,
  'speed_download' => 1026,
  'speed_upload' => 0,
  'header_size' => 307,
  'request_size' => 103,
  'ssl_verifyresult' => 0,
  'ssl_engines' =>
  array (
    0 => 'dynamic',
    1 => 'cswift',
    2 => 'chil',
    3 => 'atalla',
    4 => 'nuron',
    5 => 'ubsec',
    6 => 'aep',
    7 => 'sureware',
    8 => '4758cca',
  ),
  'content_length_download' => 218,
  'content_length_upload' => 0,
  'content_type' => 'text/html',
  'httpauth_avail' => 0,
  'proxyauth_avail' => 0,
  'num_connects' => 1,
  'os_errno' => 0,
  'error' => '',
)

http_persistent_handles_ident
http_head
HTTP Funkcje


Perform HEAD request

http_get
http_post_data
HTTP Funkcje
PHP Manual

http_head

(PECL pecl_http >= 0.1.0)

http_head — Perform HEAD request

Opis

string http_head ( string $url [, array $options [, array &$info ]] )

Performs an HTTP HEAD request on the supplied url.

Patrz po pełną listę Opcje żądania.

Parametry

url

URL

options

Opcje żądania

info

Informacje żądania/odpowiedzi

Zwracane wartości

Zwraca łańcuch znaków z odpowiedziami HTTP w przypadku powodzenia, lub FALSE w przypadku błędu

http_get
http_post_data
HTTP Funkcje


Perform POST request with pre-encoded data

http_head
http_post_fields
HTTP Funkcje
PHP Manual

http_post_data

(PECL pecl_http >= 0.1.0)

http_post_data — Perform POST request with pre-encoded data

Opis

string http_post_data ( string $url , string $data [, array $options [, array &$info ]] )

Performs an HTTP POST request on the supplied url.

Patrz po pełną listę Opcje żądania.

Parametry

url

URL

data

String containing the pre-encoded post data

options

Opcje żądania

info

Informacje żądania/odpowiedzi

Zwracane wartości

Zwraca łańcuch znaków z odpowiedziami HTTP w przypadku powodzenia, lub FALSE w przypadku błędu

http_head
http_post_fields
HTTP Funkcje


Perform POST request with data to be encoded

http_post_data
http_put_data
HTTP Funkcje
PHP Manual

http_post_fields

(PECL pecl_http >= 0.10.0)

http_post_fields — Perform POST request with data to be encoded

Opis

string http_post_fields ( string $url , array $data [, array $files [, array $options [, array &$info ]]] )

Performs an HTTP POST request on the supplied url.

Patrz po pełną listę Opcje żądania.

Parametry

url

URL

data

Associative array of POST values

files

Array of files to post

options

Opcje żądania

info

Informacje żądania/odpowiedzi

Zwracane wartości

Zwraca łańcuch znaków z odpowiedziami HTTP w przypadku powodzenia, lub FALSE w przypadku błędu

Przykłady

Przykład #1 A http_post_fields() example

<?php
$fields = array(
    'name' => 'mike',
    'pass' => 'se_ret'
);
$files = array(
    array(
        'name' => 'uimg',
        'type' => 'image/jpeg',
        'file' => './profile.jpg',
    )
);

$response = http_post_fields("http://www.example.com/", $fields, $files);
?>

http_post_data
http_put_data
HTTP Funkcje


Perform PUT request with data

http_post_fields
http_put_file
HTTP Funkcje
PHP Manual

http_put_data

(PECL pecl_http >= 0.25.0)

http_put_data — Perform PUT request with data

Opis

string http_put_data ( string $url , string $data [, array $options [, array &$info ]] )

Performs an HTTP PUT request on the supplied url.

Patrz po pełną listę Opcje żądania.

Parametry

url

URL

data

PUT request body

options

Opcje żądania

info

Informacje żądania/odpowiedzi

Zwracane wartości

Zwraca łańcuch znaków z odpowiedziami HTTP w przypadku powodzenia, lub FALSE w przypadku błędu

http_post_fields
http_put_file
HTTP Funkcje


Perform PUT request with file

http_put_data
http_put_stream
HTTP Funkcje
PHP Manual

http_put_file

(PECL pecl_http >= 0.10.0)

http_put_file — Perform PUT request with file

Opis

string http_put_file ( string $url , string $file [, array $options [, array &$info ]] )

Performs an HTTP PUT request on the supplied url.

Patrz po pełną listę Opcje żądania.

Parametry

url

URL

file

The file to put

options

Opcje żądania

info

Informacje żądania/odpowiedzi

Zwracane wartości

Zwraca łańcuch znaków z odpowiedziami HTTP w przypadku powodzenia, lub FALSE w przypadku błędu

http_put_data
http_put_stream
HTTP Funkcje


Perform PUT request with stream

http_put_file
http_request_body_encode
HTTP Funkcje
PHP Manual

http_put_stream

(PECL pecl_http >= 0.10.0)

http_put_stream — Perform PUT request with stream

Opis

string http_put_stream ( string $url , resource $stream [, array $options [, array &$info ]] )

Performs an HTTP PUT request on the supplied url.

Patrz po pełną listę Opcje żądania.

Parametry

url

URL

stream

The stream to read the PUT request body from

options

Opcje żądania

info

Informacje żądania/odpowiedzi

Zwracane wartości

Zwraca łańcuch znaków z odpowiedziami HTTP w przypadku powodzenia, lub FALSE w przypadku błędu

http_put_file
http_request_body_encode
HTTP Funkcje


Encode request body

http_put_stream
http_request_method_exists
HTTP Funkcje
PHP Manual

http_request_body_encode

(PECL pecl_http >= 1.0.0)

http_request_body_encode — Encode request body

Opis

string http_request_body_encode ( array $fields , array $files )

Generate x-www-form-urlencoded resp. form-data encoded request body.

Parametry

fields

POST fields

files

POST files

Zwracane wartości

Returns encoded string on success lub FALSE w przypadku niepowodzenia.

http_put_stream
http_request_method_exists
HTTP Funkcje


Check whether request method exists

http_request_body_encode
http_request_method_name
HTTP Funkcje
PHP Manual

http_request_method_exists

(PECL pecl_http >= 0.10.0)

http_request_method_exists — Check whether request method exists

Opis

int http_request_method_exists ( mixed $method )

Check if a request method is registered (or available by default).

Parametry

method

request method name or ID

Zwracane wartości

Returns TRUE if the request method is known, else FALSE.

http_request_body_encode
http_request_method_name
HTTP Funkcje


Get request method name

http_request_method_exists
http_request_method_register
HTTP Funkcje
PHP Manual

http_request_method_name

(PECL pecl_http >= 0.10.0)

http_request_method_name — Get request method name

Opis

string http_request_method_name ( int $method )

Get the literal string representation of a standard or registered request method.

Parametry

method

request method ID

Zwracane wartości

Returns the request method name as string on success lub FALSE w przypadku niepowodzenia.

http_request_method_exists
http_request_method_register
HTTP Funkcje


Register request method

http_request_method_name
http_request_method_unregister
HTTP Funkcje
PHP Manual

http_request_method_register

(PECL pecl_http >= 0.10.0)

http_request_method_register — Register request method

Opis

int http_request_method_register ( string $method )

Register a custom request method.

Parametry

method

the request method name to register

Zwracane wartości

Returns the ID of the request method on success lub FALSE w przypadku niepowodzenia.

http_request_method_name
http_request_method_unregister
HTTP Funkcje


Unregister request method

http_request_method_register
http_request
HTTP Funkcje
PHP Manual

http_request_method_unregister

(PECL pecl_http >= 0.10.0)

http_request_method_unregister — Unregister request method

Opis

bool http_request_method_unregister ( mixed $method )

Unregister a previously registered custom request method.

Parametry

method

The request method name or ID

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

http_request_method_register
http_request
HTTP Funkcje


Perform custom request

http_request_method_unregister
http_redirect
HTTP Funkcje
PHP Manual

http_request

(PECL pecl_http >= 1.0.0)

http_request — Perform custom request

Opis

string http_request ( int $method , string $url [, string $body [, array $options [, array &$info ]]] )

Performs a custom HTTP request on the supplied url.

Patrz po pełną listę Opcje żądania.

Parametry

method

Request method

url

URL

body

Request body

options

Opcje żądania

info

Informacje żądania/odpowiedzi

Zwracane wartości

Zwraca łańcuch znaków z odpowiedziami HTTP w przypadku powodzenia, lub FALSE w przypadku błędu

http_request_method_unregister
http_redirect
HTTP Funkcje


Issue HTTP redirect

http_request
http_send_content_disposition
HTTP Funkcje
PHP Manual

http_redirect

(PECL pecl_http >= 0.1.0)

http_redirect — Issue HTTP redirect

Opis

bool http_redirect ([ string $url [, array $params [, bool $session = false [, int $status = 0 ]]]] )

Redirect to the given url.

The supplied url will be expanded with http_build_url(), the params array will be treated with http_build_str() and the session identification will be appended if session is true. The HTTP response code will be set according to status. You can use one of the redirect constants for convenience. Please see » RFC 2616 for which redirect response code to use in which situation. By default PHP will decide which response status fits best.

To be RFC compliant, "Redirecting to <a>URL</a>." will be displayed, if the client doesn't redirect immediately, and the request method was another one than HEAD.

A log entry will be written to the redirect log, if the ustawienia INI http.log.redirect is set and the redirect attempt was successful.

Parametry

url

the URL to redirect to

params

associative array of query parameters

session

whether to append session information

status

custom response status code

Zwracane wartości

Zwraca FALSE lub exist w przypadku sukcesu with the specified redirection status code. Patrz ustawienia INI http.force_exit co znaczą "exist".

Przykłady

Przykład #1 A http_redirect() example

<?php
http_redirect("relpath", array("name" => "value"), true, HTTP_REDIRECT_PERM);
?>

Powyższy przykład wyświetli:

HTTP/1.1 301 Moved Permanently
X-Powered-By: PHP/5.2.2
Content-Type: text/html
Location: http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc

Redirecting to <a href="http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc">http://www.example.com/curdir/relpath?name=value&PHPSESSID=abc</a>.

Zobacz też:

  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_request
http_send_content_disposition
HTTP Funkcje


Send Content-Disposition

http_redirect
http_send_content_type
HTTP Funkcje
PHP Manual

http_send_content_disposition

(PECL pecl_http >= 0.10.0)

http_send_content_disposition — Send Content-Disposition

Opis

bool http_send_content_disposition ( string $filename [, bool $inline = false ] )

Send the Content-Disposition. Nagłowek Content-Disposition jest bardzo użyteczny jeśli dane aktualnie wysyłane pochodzą z pliku lub czegoś podobnego, które powinny być "zapisane" przez klienta/użytkownika (np. przez okienko popup przeglądarki "Zapisz jako...").

Informacja: Ta funkcja będzie przypuszczalnie użyta w powiązaniu z http_send_data(), http_send_file() i http_send_stream().

Parametry

filename

the file name the "Save as..." dialog should display

inline

if set to TRUE and the user agent knows how to handle the content type, it will probably not cause the popup window to be shown

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • http_send_data() - Send arbitrary data
  • http_send_file() - Send file
  • http_send_stream() - Send stream
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_redirect
http_send_content_type
HTTP Funkcje


Send Content-Type

http_send_content_disposition
http_send_data
HTTP Funkcje
PHP Manual

http_send_content_type

(PECL pecl_http >= 0.10.0)

http_send_content_type — Send Content-Type

Opis

bool http_send_content_type ([ string $content_type = "application/x-octetstream" ] )

Send the Content-Type of the sent entity.

Informacja: Ta funkcja będzie przypuszczalnie użyta w powiązaniu z http_send_data(), http_send_file() i http_send_stream().

Parametry

content_type

the desired content type (primary/secondary)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Raises an E_WARNING when the content_type doesn't seem to contain a primary and a secondary part.

Zobacz też:

  • http_send_data() - Send arbitrary data
  • http_send_file() - Send file
  • http_send_stream() - Send stream
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_send_content_disposition
http_send_data
HTTP Funkcje


Send arbitrary data

http_send_content_type
http_send_file
HTTP Funkcje
PHP Manual

http_send_data

(PECL pecl_http >= 0.1.0)

http_send_data — Send arbitrary data

Opis

bool http_send_data ( string $data )

Sends raw data with support for (multiple) range requests.

Parametry

data

data to send

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • http_send_file() - Send file
  • http_send_stream() - Send stream
  • http_throttle() - HTTP throttling
  • http_send_content_type() - Send Content-Type
  • http_send_content_disposition() - Send Content-Disposition
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_send_content_type
http_send_file
HTTP Funkcje


Send file

http_send_data
http_send_last_modified
HTTP Funkcje
PHP Manual

http_send_file

(PECL pecl_http >= 0.1.0)

http_send_file — Send file

Opis

bool http_send_file ( string $file )

Sends a file with support for (multiple) range requests.

This functions behaviour and further action is dependent on the following ustawienia INIs: http.send.not_found_404 i http.log.not_found.

If the ustawienia INI http.send.not_found_404 is enabled and the ustawienia INI http.log.not_found points to a writable file, a log message is written when the file was not found.

Parametry

file

the file to send

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 A http_send_file() example

<?php
http_send_content_disposition("document.pdf", true);
http_send_content_type("application/pdf");
http_throttle(0.1, 2048);
http_send_file("../report.pdf");
?>

Powyższy przykład wyświetli:

HTTP/1.1 206 Partial Content
X-Powered-By: PHP/5.2.2
Accept-Ranges: bytes
Content-Length: 12345
Content-Range: bytes 0-12344
Content-Type: application/pdf
Content-Disposition: inline; filename="document.pdf"

%PDF...

Zobacz też:

  • http_send_data() - Send arbitrary data
  • http_send_stream() - Send stream
  • http_throttle() - HTTP throttling
  • http_send_content_type() - Send Content-Type
  • http_send_content_disposition() - Send Content-Disposition
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_send_data
http_send_last_modified
HTTP Funkcje


Send Last-Modified

http_send_file
http_send_status
HTTP Funkcje
PHP Manual

http_send_last_modified

(PECL pecl_http >= 0.1.0)

http_send_last_modified — Send Last-Modified

Opis

bool http_send_last_modified ([ int $timestamp = time() ] )

Send a Last-Modified header with a valid HTTP date.

Informacja: Ta funkcja będzie przypuszczalnie użyta w powiązaniu z http_send_data(), http_send_file() i http_send_stream().

Parametry

timestamp

a Unix timestamp, converted to a valid HTTP date; if omitted, the current time will be sent

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_send_file
http_send_status
HTTP Funkcje


Send HTTP response status

http_send_last_modified
http_send_stream
HTTP Funkcje
PHP Manual

http_send_status

(PECL pecl_http >= 0.1.0)

http_send_status — Send HTTP response status

Opis

bool http_send_status ( int $status )

Send HTTP status code.

Parametry

status

HTTP status code (100-599)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_send_last_modified
http_send_stream
HTTP Funkcje


Send stream

http_send_status
http_throttle
HTTP Funkcje
PHP Manual

http_send_stream

(PECL pecl_http >= 0.1.0)

http_send_stream — Send stream

Opis

bool http_send_stream ( resource $stream )

Sends an already opened stream with support for (multiple) range requests.

Parametry

stream

stream to read from (must be seekable)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • http_send_data() - Send arbitrary data
  • http_send_file() - Send file
  • http_throttle() - HTTP throttling
  • http_send_content_type() - Send Content-Type
  • http_send_content_disposition() - Send Content-Disposition
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_send_status
http_throttle
HTTP Funkcje


HTTP throttling

http_send_stream
http_build_str
HTTP Funkcje
PHP Manual

http_throttle

(PECL pecl_http >= 0.10.0)

http_throttle — HTTP throttling

Opis

void http_throttle ( float $sec [, int $bytes = 40960 ] )

Sets the throttle delay and send buffer size.

Informacja: Ta funkcja będzie przypuszczalnie użyta w powiązaniu z http_send_data(), http_send_file() i http_send_stream().

Informacja: Zapewnia podstawowy mechanizm dławiący, który będzie podtrzymywać bieżący proces lub wątek, dopóki nie zostanie wysłana całość.

Informacja:

To może nie działać jak się spodziewasz z następującymi SAPI: FastCGI.

Parametry

sec

seconds to sleep after each chunk sent

bytes

the chunk size in bytes

Przykłady

Przykład #1 A http_throttle() example

Send file with approximately 20 kbyte/s.

<?php
// ~ 20 kbyte/s
# http_throttle(1, 20000);
# http_throttle(0.5, 10000);
http_throttle(0.1, 2000);
http_send_file('document.pdf');
?>

Zobacz też:

  • http_send_data() - Send arbitrary data
  • http_send_file() - Send file
  • http_send_stream() - Send stream
  • Klasa HttpResponse jeśli używasz PHP 5.1.0 lub późniejszego

http_send_stream
http_build_str
HTTP Funkcje


Build query string

http_throttle
http_build_url
HTTP Funkcje
PHP Manual

http_build_str

(PECL pecl_http >= 0.23.0)

http_build_str — Build query string

Opis

string http_build_str ( array $query [, string $prefix [, string $arg_separator = ini_get("arg_separator.output") ]] )

Opponent to parse_str().

Parametry

query

associative array of query string parameters

prefix

top level prefix

arg_separator

argument separator to use (by default the INI setting arg_separator.output will be used, or "&" if neither is set

Zwracane wartości

Returns the built query as string on success lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • standard http_build_query() - Generate URL-encoded query string
  • http_build_url() - Build a URL

http_throttle
http_build_url
HTTP Funkcje


Build a URL

http_build_str
Hyperwave
HTTP Funkcje
PHP Manual

http_build_url

(PECL pecl_http >= 0.21.0)

http_build_url — Build a URL

Opis

string http_build_url ([ mixed $url [, mixed $parts [, int $flags = HTTP_URL_REPLACE [, array &$new_url ]]]] )

Build a URL.

The parts of the second URL will be merged into the first according to the flags argument.

Parametry

url

(part(s) of) an URL in form of a string or associative array like parse_url() returns

parts

same as the first argument

flags

a bitmask of binary or'ed HTTP_URL constants; HTTP_URL_REPLACE is the default

new_url

if set, it will be filled with the parts of the composed url like parse_url() would return

Zwracane wartości

Returns the new URL as string on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 A http_build_url() example

<?php
echo http_build_url("http://user@www.example.com/pub/index.php?a=b#files",
    array(
        "scheme" => "ftp",
        "host" => "ftp.example.com",
        "path" => "files/current/",
        "query" => "a=c"
    ),
    HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT
);
?>

Powyższy przykład wyświetli:

ftp://ftp.example.com/pub/files/current/?a=c

Zobacz też:

  • parse_url() - Przetwarza adres URL i zwraca jego składowe
  • http_build_str() - Build query string

http_build_str
Hyperwave
HTTP Funkcje


Hyperwave

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Integration with Apache
  • Hyperwave Funkcje
    • hw_Array2Objrec — Convert attributes from object array to object record
    • hw_changeobject — Changes attributes of an object (obsolete)
    • hw_Children — Object ids of children
    • hw_ChildrenObj — Object records of children
    • hw_Close — Closes the Hyperwave connection
    • hw_Connect — Opens a connection
    • hw_connection_info — Prints information about the connection to Hyperwave server
    • hw_cp — Copies objects
    • hw_Deleteobject — Deletes object
    • hw_DocByAnchor — Object id object belonging to anchor
    • hw_DocByAnchorObj — Object record object belonging to anchor
    • hw_Document_Attributes — Object record of hw_document
    • hw_Document_BodyTag — Body tag of hw_document
    • hw_Document_Content — Returns content of hw_document
    • hw_Document_SetContent — Sets/replaces content of hw_document
    • hw_Document_Size — Size of hw_document
    • hw_dummy — Hyperwave dummy function
    • hw_EditText — Retrieve text document
    • hw_Error — Error number
    • hw_ErrorMsg — Returns error message
    • hw_Free_Document — Frees hw_document
    • hw_GetAnchors — Object ids of anchors of document
    • hw_GetAnchorsObj — Object records of anchors of document
    • hw_GetAndLock — Return object record and lock object
    • hw_GetChildColl — Object ids of child collections
    • hw_GetChildCollObj — Object records of child collections
    • hw_GetChildDocColl — Object ids of child documents of collection
    • hw_GetChildDocCollObj — Object records of child documents of collection
    • hw_GetObject — Object record
    • hw_GetObjectByQuery — Search object
    • hw_GetObjectByQueryColl — Search object in collection
    • hw_GetObjectByQueryCollObj — Search object in collection
    • hw_GetObjectByQueryObj — Search object
    • hw_GetParents — Object ids of parents
    • hw_GetParentsObj — Object records of parents
    • hw_getrellink — Get link from source to dest relative to rootid
    • hw_GetRemote — Gets a remote document
    • hw_getremotechildren — Gets children of remote document
    • hw_GetSrcByDestObj — Returns anchors pointing at object
    • hw_GetText — Retrieve text document
    • hw_getusername — Name of currently logged in user
    • hw_Identify — Identifies as user
    • hw_InCollections — Check if object ids in collections
    • hw_Info — Info about connection
    • hw_InsColl — Insert collection
    • hw_InsDoc — Insert document
    • hw_insertanchors — Inserts only anchors into text
    • hw_InsertDocument — Upload any document
    • hw_InsertObject — Inserts an object record
    • hw_mapid — Maps global id on virtual local id
    • hw_Modifyobject — Modifies object record
    • hw_mv — Moves objects
    • hw_New_Document — Create new document
    • hw_objrec2array — Convert attributes from object record to object array
    • hw_Output_Document — Prints hw_document
    • hw_pConnect — Make a persistent database connection
    • hw_PipeDocument — Retrieve any document
    • hw_Root — Root object id
    • hw_setlinkroot — Set the id to which links are calculated
    • hw_stat — Returns status string
    • hw_Unlock — Unlock object
    • hw_Who — List of currently logged in users
http_build_url
Wstęp
Inne serwisy


Wstęp

Hyperwave has been developed at » IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5 is available at » http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave API module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'de:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.

Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)

Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them. The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.

Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name my_object is mapped to http://host/my_object disregarding where it resides in the Hyperwave hierarchy. An object with name parent/my_object could be the child of my_object in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.

Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. http://host/php_script/my_object and the script php_script evaluates the $PATH_INFO variable and retrieves the object with name my_object from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLs like all e.g. starting with http://host/Hyperwave This is basically sharing of a namespace by the web and Hyperwave server.

Based on the above mechanism links are insert into documents.

It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'.

The network protocol to communicate with the Hyperwave server is called » HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.

Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.

Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.

  • object ID: A unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.
  • object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.
  • object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.
  • hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.

Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:

Hidden
Number of object records with attribute PresentationHints set to Hidden.
CollectionHead
Number of object records with attribute PresentationHints set to CollectionHead.
FullCollectionHead
Number of object records with attribute PresentationHints set to FullCollectionHead.
CollectionHeadNr
Index in array of object records with attribute PresentationHints set to CollectionHead.
FullCollectionHeadNr
Index in array of object records with attribute PresentationHints set to FullCollectionHead.
Total
Total: Number of object records.

Hyperwave
Instalacja/Konfiguracja
Hyperwave


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Hyperwave


Wymagania

This extension needs a Hyperwave server downloadable from » http://www.hyperwave.com/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/hyperwave.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Hyperwave configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.2. Removed in PHP 5.0.0.
hyperwave.default_port | "418" | PHP_INI_ALL | Removed in PHP 5.0.0.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

HW_ATTR_LANG (integer)
HW_ATTR_NR (integer)
HW_ATTR_NONE (integer)
Typy zasobów
Integration with Apache
Hyperwave


Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]
Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:
RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]
This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with
RewriteEngine on
You will need scripts:
  • to return the object itself
  • to allow searching
  • to identify yourself
  • to set your profile
  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.

As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.

Stałe predefiniowane
Hyperwave Funkcje
Hyperwave


Hyperwave Funkcje

Todo

There are still some things to do:

  • The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().
  • The names of several functions are not fixed, yet.
  • Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.
  • Conversion form object record into object array needs to handle any multiple attribute.

Spis treści

  • hw_Array2Objrec — Convert attributes from object array to object record
  • hw_changeobject — Changes attributes of an object (obsolete)
  • hw_Children — Object ids of children
  • hw_ChildrenObj — Object records of children
  • hw_Close — Closes the Hyperwave connection
  • hw_Connect — Opens a connection
  • hw_connection_info — Prints information about the connection to Hyperwave server
  • hw_cp — Copies objects
  • hw_Deleteobject — Deletes object
  • hw_DocByAnchor — Object id object belonging to anchor
  • hw_DocByAnchorObj — Object record object belonging to anchor
  • hw_Document_Attributes — Object record of hw_document
  • hw_Document_BodyTag — Body tag of hw_document
  • hw_Document_Content — Returns content of hw_document
  • hw_Document_SetContent — Sets/replaces content of hw_document
  • hw_Document_Size — Size of hw_document
  • hw_dummy — Hyperwave dummy function
  • hw_EditText — Retrieve text document
  • hw_Error — Error number
  • hw_ErrorMsg — Returns error message
  • hw_Free_Document — Frees hw_document
  • hw_GetAnchors — Object ids of anchors of document
  • hw_GetAnchorsObj — Object records of anchors of document
  • hw_GetAndLock — Return object record and lock object
  • hw_GetChildColl — Object ids of child collections
  • hw_GetChildCollObj — Object records of child collections
  • hw_GetChildDocColl — Object ids of child documents of collection
  • hw_GetChildDocCollObj — Object records of child documents of collection
  • hw_GetObject — Object record
  • hw_GetObjectByQuery — Search object
  • hw_GetObjectByQueryColl — Search object in collection
  • hw_GetObjectByQueryCollObj — Search object in collection
  • hw_GetObjectByQueryObj — Search object
  • hw_GetParents — Object ids of parents
  • hw_GetParentsObj — Object records of parents
  • hw_getrellink — Get link from source to dest relative to rootid
  • hw_GetRemote — Gets a remote document
  • hw_getremotechildren — Gets children of remote document
  • hw_GetSrcByDestObj — Returns anchors pointing at object
  • hw_GetText — Retrieve text document
  • hw_getusername — Name of currently logged in user
  • hw_Identify — Identifies as user
  • hw_InCollections — Check if object ids in collections
  • hw_Info — Info about connection
  • hw_InsColl — Insert collection
  • hw_InsDoc — Insert document
  • hw_insertanchors — Inserts only anchors into text
  • hw_InsertDocument — Upload any document
  • hw_InsertObject — Inserts an object record
  • hw_mapid — Maps global id on virtual local id
  • hw_Modifyobject — Modifies object record
  • hw_mv — Moves objects
  • hw_New_Document — Create new document
  • hw_objrec2array — Convert attributes from object record to object array
  • hw_Output_Document — Prints hw_document
  • hw_pConnect — Make a persistent database connection
  • hw_PipeDocument — Retrieve any document
  • hw_Root — Root object id
  • hw_setlinkroot — Set the id to which links are calculated
  • hw_stat — Returns status string
  • hw_Unlock — Unlock object
  • hw_Who — List of currently logged in users
Integration with Apache
hw_Array2Objrec
Hyperwave


Convert attributes from object array to object record

Hyperwave Funkcje
hw_changeobject
Hyperwave Funkcje
PHP Manual

hw_Array2Objrec

(PHP 4)

hw_Array2Objrec — Convert attributes from object array to object record

Opis

string hw_array2objrec ( array $object_array )

Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.

Parametry

object_array

The array.

Zwracane wartości

Returns an object record.

Zobacz też:

  • hw_objrec2array() - Convert attributes from object record to object array

Hyperwave Funkcje
hw_changeobject
Hyperwave Funkcje


Changes attributes of an object (obsolete)

hw_Array2Objrec
hw_Children
Hyperwave Funkcje
PHP Manual

hw_changeobject

(PHP 4)

hw_changeobject — Changes attributes of an object (obsolete)

Opis

bool hw_changeobject ( int $link , int $objid , array $attributes )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_Array2Objrec
hw_Children
Hyperwave Funkcje


Object ids of children

hw_changeobject
hw_ChildrenObj
Hyperwave Funkcje
PHP Manual

hw_Children

(PHP 4)

hw_Children — Object ids of children

Opis

array hw_children ( int $connection , int $objectID )

Returns the identifiers of the collection children.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_changeobject
hw_ChildrenObj
Hyperwave Funkcje


Object records of children

hw_Children
hw_Close
Hyperwave Funkcje
PHP Manual

hw_ChildrenObj

(PHP 4)

hw_ChildrenObj — Object records of children

Opis

array hw_childrenobj ( int $connection , int $objectID )

Returns the object records of the collection children.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_Children
hw_Close
Hyperwave Funkcje


Closes the Hyperwave connection

hw_ChildrenObj
hw_Connect
Hyperwave Funkcje
PHP Manual

hw_Close

(PHP 4)

hw_Close — Closes the Hyperwave connection

Opis

bool hw_close ( int $connection )

Closes down the connection to a Hyperwave server.

Parametry

connection

The connection identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

hw_ChildrenObj
hw_Connect
Hyperwave Funkcje


Opens a connection

hw_Close
hw_connection_info
Hyperwave Funkcje
PHP Manual

hw_Connect

(PHP 4)

hw_Connect — Opens a connection

Opis

int hw_connect ( string $host , int $port [, string $username ], string $password )

Opens a connection to a Hyperwave server. You can have multiple connections open at once.

Parametry

host

The server host name.

port

The server port number.

username

The Hyperwave user name. If omitted, no identification with the server will be done. It is similar to identify as user anonymous.

password

The password for username. Keep in mind, that the password is not encrypted.

Zwracane wartości

Returns a connection index on success, or FALSE if the connection could not be made.

Zobacz też:

  • hw_pconnect() - Make a persistent database connection

hw_Close
hw_connection_info
Hyperwave Funkcje


Prints information about the connection to Hyperwave server

hw_Connect
hw_cp
Hyperwave Funkcje
PHP Manual

hw_connection_info

(PHP 4)

hw_connection_info — Prints information about the connection to Hyperwave server

Opis

void hw_connection_info ( int $link )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_Connect
hw_cp
Hyperwave Funkcje


Copies objects

hw_connection_info
hw_Deleteobject
Hyperwave Funkcje
PHP Manual

hw_cp

(PHP 4)

hw_cp — Copies objects

Opis

int hw_cp ( int $connection , array $object_id_array , int $destination_id )

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

Parametry

connection

The connection identifier.

object_id_array

An array of object ids.

destination_id

The target collection id.

Zwracane wartości

Returns the number of copied objects.

Zobacz też:

  • hw_mv() - Moves objects

hw_connection_info
hw_Deleteobject
Hyperwave Funkcje


Deletes object

hw_cp
hw_DocByAnchor
Hyperwave Funkcje
PHP Manual

hw_Deleteobject

(PHP 4)

hw_Deleteobject — Deletes object

Opis

bool hw_deleteobject ( int $connection , int $object_to_delete )

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Parametry

connection

The connection identifier.

object_to_delete

The object identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_mv() - Moves objects

hw_cp
hw_DocByAnchor
Hyperwave Funkcje


Object id object belonging to anchor

hw_Deleteobject
hw_DocByAnchorObj
Hyperwave Funkcje
PHP Manual

hw_DocByAnchor

(PHP 4)

hw_DocByAnchor — Object id object belonging to anchor

Opis

int hw_docbyanchor ( int $connection , int $anchorID )

Returns an th object id of the document to which anchorID belongs.

Parametry

connection

The connection identifier.

anchorID

The anchor identifier.

Zwracane wartości

Returns the document object id.

hw_Deleteobject
hw_DocByAnchorObj
Hyperwave Funkcje


Object record object belonging to anchor

hw_DocByAnchor
hw_Document_Attributes
Hyperwave Funkcje
PHP Manual

hw_DocByAnchorObj

(PHP 4)

hw_DocByAnchorObj — Object record object belonging to anchor

Opis

string hw_docbyanchorobj ( int $connection , int $anchorID )

Returns an th object record of the document to which anchorID belongs.

Parametry

connection

The connection identifier.

anchorID

The anchor identifier.

Zwracane wartości

Returns an object record.

hw_DocByAnchor
hw_Document_Attributes
Hyperwave Funkcje


Object record of hw_document

hw_DocByAnchorObj
hw_Document_BodyTag
Hyperwave Funkcje
PHP Manual

hw_Document_Attributes

(PHP 4)

hw_Document_Attributes — Object record of hw_document

Opis

string hw_document_attributes ( int $hw_document )

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

Parametry

hw_document

The document identifier.

Zwracane wartości

Returns the object record of the document.

Zobacz też:

  • hw_document_bodytag() - Body tag of hw_document
  • hw_document_size() - Size of hw_document

hw_DocByAnchorObj
hw_Document_BodyTag
Hyperwave Funkcje


Body tag of hw_document

hw_Document_Attributes
hw_Document_Content
Hyperwave Funkcje
PHP Manual

hw_Document_BodyTag

(PHP 4)

hw_Document_BodyTag — Body tag of hw_document

Opis

string hw_document_bodytag ( int $hw_document [, string $prefix ] )

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

Parametry

hw_document

The document identifier.

prefix

Zwracane wartości

Returns the BODY tag as a string.

Zobacz też:

  • hw_document_attributes() - Object record of hw_document
  • hw_document_size() - Size of hw_document

hw_Document_Attributes
hw_Document_Content
Hyperwave Funkcje


Returns content of hw_document

hw_Document_BodyTag
hw_Document_SetContent
Hyperwave Funkcje
PHP Manual

hw_Document_Content

(PHP 4)

hw_Document_Content — Returns content of hw_document

Opis

string hw_document_content ( int $hw_document )

Gets the content of the document.

Parametry

hw_document

The document identifier.

Zwracane wartości

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

Zobacz też:

  • hw_document_attributes() - Object record of hw_document
  • hw_document_size() - Size of hw_document
  • hw_document_setcontent() - Sets/replaces content of hw_document

hw_Document_BodyTag
hw_Document_SetContent
Hyperwave Funkcje


Sets/replaces content of hw_document

hw_Document_Content
hw_Document_Size
Hyperwave Funkcje
PHP Manual

hw_Document_SetContent

(PHP 4)

hw_Document_SetContent — Sets/replaces content of hw_document

Opis

bool hw_document_setcontent ( int $hw_document , string $content )

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.

Parametry

hw_document

The document identifier.

content

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_document_attributes() - Object record of hw_document
  • hw_document_size() - Size of hw_document
  • hw_document_content() - Returns content of hw_document

hw_Document_Content
hw_Document_Size
Hyperwave Funkcje


Size of hw_document

hw_Document_SetContent
hw_dummy
Hyperwave Funkcje
PHP Manual

hw_Document_Size

(PHP 4)

hw_Document_Size — Size of hw_document

Opis

int hw_document_size ( int $hw_document )

Gets the size of the document.

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

Parametry

hw_document

The document identifier.

Zwracane wartości

Returns the size in bytes of the document.

Zobacz też:

  • hw_document_attributes() - Object record of hw_document
  • hw_document_bodytag() - Body tag of hw_document

hw_Document_SetContent
hw_dummy
Hyperwave Funkcje


Hyperwave dummy function

hw_Document_Size
hw_EditText
Hyperwave Funkcje
PHP Manual

hw_dummy

(PHP 4)

hw_dummy — Hyperwave dummy function

Opis

string hw_dummy ( int $link , int $id , int $msgid )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_Document_Size
hw_EditText
Hyperwave Funkcje


Retrieve text document

hw_dummy
hw_Error
Hyperwave Funkcje
PHP Manual

hw_EditText

(PHP 4)

hw_EditText — Retrieve text document

Opis

bool hw_edittext ( int $connection , int $hw_document )

Uploads the text document to the server. The object record of the document may not be modified while the document is edited.

This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

Parametry

connection

The connection identifier.

hw_document

The document identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_pipedocument() - Retrieve any document
  • hw_free_document() - Frees hw_document
  • hw_document_bodytag() - Body tag of hw_document
  • hw_document_size() - Size of hw_document
  • hw_output_document() - Prints hw_document
  • hw_gettext() - Retrieve text document

hw_dummy
hw_Error
Hyperwave Funkcje


Error number

hw_EditText
hw_ErrorMsg
Hyperwave Funkcje
PHP Manual

hw_Error

(PHP 4)

hw_Error — Error number

Opis

int hw_error ( int $connection )

Returns the last error number, for the last command.

Parametry

connection

The connection identifier.

Zwracane wartości

Returns the last error number or 0 if no error occurred.

Zobacz też:

  • hw_errormsg() - Returns error message

hw_EditText
hw_ErrorMsg
Hyperwave Funkcje


Returns error message

hw_Error
hw_Free_Document
Hyperwave Funkcje
PHP Manual

hw_ErrorMsg

(PHP 4)

hw_ErrorMsg — Returns error message

Opis

string hw_errormsg ( int $connection )

Returns a string containing the last error message related to the last command.

Parametry

connection

The connection identifier.

Zwracane wartości

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed.

Zobacz też:

  • hw_error() - Error number

hw_Error
hw_Free_Document
Hyperwave Funkcje


Frees hw_document

hw_ErrorMsg
hw_GetAnchors
Hyperwave Funkcje
PHP Manual

hw_Free_Document

(PHP 4)

hw_Free_Document — Frees hw_document

Opis

bool hw_free_document ( int $hw_document )

Frees the memory occupied by the Hyperwave document.

Parametry

hw_document

The document identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

hw_ErrorMsg
hw_GetAnchors
Hyperwave Funkcje


Object ids of anchors of document

hw_Free_Document
hw_GetAnchorsObj
Hyperwave Funkcje
PHP Manual

hw_GetAnchors

(PHP 4)

hw_GetAnchors — Object ids of anchors of document

Opis

array hw_getanchors ( int $connection , int $objectID )

Returns an array of object ids with anchors of the specified document.

Parametry

connection

The connection identifier.

objectID

The document object id.

Zwracane wartości

Returns an array of object ids.

hw_Free_Document
hw_GetAnchorsObj
Hyperwave Funkcje


Object records of anchors of document

hw_GetAnchors
hw_GetAndLock
Hyperwave Funkcje
PHP Manual

hw_GetAnchorsObj

(PHP 4)

hw_GetAnchorsObj — Object records of anchors of document

Opis

array hw_getanchorsobj ( int $connection , int $objectID )

Returns records with anchors of the document with object ID objectID.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an array of object records.

hw_GetAnchors
hw_GetAndLock
Hyperwave Funkcje


Return object record and lock object

hw_GetAnchorsObj
hw_GetChildColl
Hyperwave Funkcje
PHP Manual

hw_GetAndLock

(PHP 4)

hw_GetAndLock — Return object record and lock object

Opis

string hw_getandlock ( int $connection , int $objectID )

Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns the object record for the object with ID objectID.

Zobacz też:

  • hw_unlock() - Unlock object
  • hw_getobject() - Object record

hw_GetAnchorsObj
hw_GetChildColl
Hyperwave Funkcje


Object ids of child collections

hw_GetAndLock
hw_GetChildCollObj
Hyperwave Funkcje
PHP Manual

hw_GetChildColl

(PHP 4)

hw_GetChildColl — Object ids of child collections

Opis

array hw_getchildcoll ( int $connection , int $objectID )

Returns object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an array of object ids.

Zobacz też:

  • hw_children() - Object ids of children
  • hw_getchilddoccoll() - Object ids of child documents of collection

hw_GetAndLock
hw_GetChildCollObj
Hyperwave Funkcje


Object records of child collections

hw_GetChildColl
hw_GetChildDocColl
Hyperwave Funkcje
PHP Manual

hw_GetChildCollObj

(PHP 4)

hw_GetChildCollObj — Object records of child collections

Opis

array hw_getchildcollobj ( int $connection , int $objectID )

Returns object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an array of object records.

Zobacz też:

  • hw_childrenobj() - Object records of children
  • hw_getchilddoccollobj() - Object records of child documents of collection

hw_GetChildColl
hw_GetChildDocColl
Hyperwave Funkcje


Object ids of child documents of collection

hw_GetChildCollObj
hw_GetChildDocCollObj
Hyperwave Funkcje
PHP Manual

hw_GetChildDocColl

(PHP 4)

hw_GetChildDocColl — Object ids of child documents of collection

Opis

array hw_getchilddoccoll ( int $connection , int $objectID )

Returns array of object ids for child documents of a collection.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an array of object ids.

Zobacz też:

  • hw_children() - Object ids of children
  • hw_getchildcoll() - Object ids of child collections

hw_GetChildCollObj
hw_GetChildDocCollObj
Hyperwave Funkcje


Object records of child documents of collection

hw_GetChildDocColl
hw_GetObject
Hyperwave Funkcje
PHP Manual

hw_GetChildDocCollObj

(PHP 4)

hw_GetChildDocCollObj — Object records of child documents of collection

Opis

array hw_getchilddoccollobj ( int $connection , int $objectID )

Returns an array of object records for child documents of a collection.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an array of object records.

Zobacz też:

  • hw_childrenobj() - Object records of children
  • hw_getchildcollobj() - Object records of child collections

hw_GetChildDocColl
hw_GetObject
Hyperwave Funkcje


Object record

hw_GetChildDocCollObj
hw_GetObjectByQuery
Hyperwave Funkcje
PHP Manual

hw_GetObject

(PHP 4)

hw_GetObject — Object record

Opis

mixed hw_getobject ( int $connection , mixed $objectID [, string $query ] )

Gets an object record. If the second parameter is an array of integer the function will

Parametry

connection

The connection identifier.

objectID

The object identifier, or an array of identifiers.

query

The query string has the following syntax:

<expr> ::= "(" <expr> ")" |
           "!" &lt;expr> |          /* NOT */
           <expr> "||" <expr> |  /* OR */
           <expr> "&amp;&amp;" <expr> |  /* AND */
           <attribute> <operator> <value>

<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */

<operator> ::= "=" |    /* equal */
               "<" |    /* less than (string compare) */
               ">" |    /* greater than (string compare) */
               "~"      /* regular expression matching */
The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.

Zwracane wartości

Returns the object record for the given object ID if the second parameter is an integer.

If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.

Zobacz też:

  • hw_getandlock() - Return object record and lock object
  • hw_getobjectbyquery() - Search object

hw_GetChildDocCollObj
hw_GetObjectByQuery
Hyperwave Funkcje


Search object

hw_GetObject
hw_GetObjectByQueryColl
Hyperwave Funkcje
PHP Manual

hw_GetObjectByQuery

(PHP 4)

hw_GetObjectByQuery — Search object

Opis

array hw_getobjectbyquery ( int $connection , string $query , int $max_hits )

Searches for objects on the whole server and returns an array of object ids.

Parametry

connection

The connection identifier.

query

The query will only work with indexed attributes.

max_hits

The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

Zwracane wartości

Returns an array of object ids.

Zobacz też:

  • hw_getobjectbyqueryobj() - Search object

hw_GetObject
hw_GetObjectByQueryColl
Hyperwave Funkcje


Search object in collection

hw_GetObjectByQuery
hw_GetObjectByQueryCollObj
Hyperwave Funkcje
PHP Manual

hw_GetObjectByQueryColl

(PHP 4)

hw_GetObjectByQueryColl — Search object in collection

Opis

array hw_getobjectbyquerycoll ( int $connection , int $objectID , string $query , int $max_hits )

Searches for objects in collection with ID objectID and returns an array of object ids.

Parametry

connection

The connection identifier.

objectID

The collection id.

query

The query will only work with indexed attributes.

max_hits

The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

Zwracane wartości

Returns an array of object ids.

Zobacz też:

  • hw_getobjectbyquerycollobj() - Search object in collection

hw_GetObjectByQuery
hw_GetObjectByQueryCollObj
Hyperwave Funkcje


Search object in collection

hw_GetObjectByQueryColl
hw_GetObjectByQueryObj
Hyperwave Funkcje
PHP Manual

hw_GetObjectByQueryCollObj

(PHP 4)

hw_GetObjectByQueryCollObj — Search object in collection

Opis

array hw_getobjectbyquerycollobj ( int $connection , int $objectID , string $query , int $max_hits )

Searches for objects in collection with ID objectID and returns an array of object records.

Parametry

connection

The connection identifier.

objectID

The collection id.

query

The query will only work with indexed attributes.

max_hits

The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

Zwracane wartości

Returns an array of object records.

Zobacz też:

  • hw_getobjectbyquerycoll() - Search object in collection

hw_GetObjectByQueryColl
hw_GetObjectByQueryObj
Hyperwave Funkcje


Search object

hw_GetObjectByQueryCollObj
hw_GetParents
Hyperwave Funkcje
PHP Manual

hw_GetObjectByQueryObj

(PHP 4)

hw_GetObjectByQueryObj — Search object

Opis

array hw_getobjectbyqueryobj ( int $connection , string $query , int $max_hits )

Searches for objects on the whole server and returns an array of object records.

Parametry

connection

The connection identifier.

query

The query will only work with indexed attributes.

max_hits

The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

Zwracane wartości

Returns an array of object records.

Zobacz też:

  • hw_getobjectbyquery() - Search object

hw_GetObjectByQueryCollObj
hw_GetParents
Hyperwave Funkcje


Object ids of parents

hw_GetObjectByQueryObj
hw_GetParentsObj
Hyperwave Funkcje
PHP Manual

hw_GetParents

(PHP 4)

hw_GetParents — Object ids of parents

Opis

array hw_getparents ( int $connection , int $objectID )

Returns the object identifiers of the parents of an object.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

hw_GetObjectByQueryObj
hw_GetParentsObj
Hyperwave Funkcje


Object records of parents

hw_GetParents
hw_getrellink
Hyperwave Funkcje
PHP Manual

hw_GetParentsObj

(PHP 4)

hw_GetParentsObj — Object records of parents

Opis

array hw_getparentsobj ( int $connection , int $objectID )

Returns object records and statistical information about the object records. Each object record belongs to a parent of the object with ID objectID.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array.

hw_GetParents
hw_getrellink
Hyperwave Funkcje


Get link from source to dest relative to rootid

hw_GetParentsObj
hw_GetRemote
Hyperwave Funkcje
PHP Manual

hw_getrellink

(PHP 4)

hw_getrellink — Get link from source to dest relative to rootid

Opis

string hw_getrellink ( int $link , int $rootid , int $sourceid , int $destid )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_GetParentsObj
hw_GetRemote
Hyperwave Funkcje


Gets a remote document

hw_getrellink
hw_getremotechildren
Hyperwave Funkcje
PHP Manual

hw_GetRemote

(PHP 4)

hw_GetRemote — Gets a remote document

Opis

int hw_getremote ( int $connection , int $objectID )

Gets a remote document.

Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database.

In order to be able to access external sources through remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI.

Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

Parametry

connection

The connection identifier.

objectID

The object identifier.

Zwracane wartości

Returns a remote document.

Zobacz też:

  • hw_getremotechildren() - Gets children of remote document

hw_getrellink
hw_getremotechildren
Hyperwave Funkcje


Gets children of remote document

hw_GetRemote
hw_GetSrcByDestObj
Hyperwave Funkcje
PHP Manual

hw_getremotechildren

(PHP 4)

hw_getremotechildren — Gets children of remote document

Opis

mixed hw_getremotechildren ( int $connection , string $object_record )

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide.

If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

Parametry

connection

The connection identifier.

object_record

The object record.

Zwracane wartości

If the number of children is 1 the function will return the document itself formatted by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactly such an object record looks like is up to the HGI.

Zobacz też:

  • hw_getremote() - Gets a remote document

hw_GetRemote
hw_GetSrcByDestObj
Hyperwave Funkcje


Returns anchors pointing at object

hw_getremotechildren
hw_GetText
Hyperwave Funkcje
PHP Manual

hw_GetSrcByDestObj

(PHP 4)

hw_GetSrcByDestObj — Returns anchors pointing at object

Opis

array hw_getsrcbydestobj ( int $connection , int $objectID )

Gets the object records of all anchors pointing to the object with ID objectID.

Parametry

connection

The connection identifier.

objectID

The object identifier. The object can either be a document or an anchor of type destination.

Zwracane wartości

Returns an array of object records.

Zobacz też:

  • hw_getanchors() - Object ids of anchors of document

hw_getremotechildren
hw_GetText
Hyperwave Funkcje


Retrieve text document

hw_GetSrcByDestObj
hw_getusername
Hyperwave Funkcje
PHP Manual

hw_GetText

(PHP 4)

hw_GetText — Retrieve text document

Opis

int hw_gettext ( int $connection , int $objectID [, mixed $rootID/prefix ] )

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already.

This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

Parametry

connection

The connection identifier.

objectID

The object identifier.

rootID/prefix

The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A href="/internet_movie">. The actual location of the source and destination object in the document hierarchy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php/internet_movie'. 'my_script.php' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.

If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object.

If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the separator between hierarchy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierarchy onto the file system.

Zwracane wartości

Returns the text document.

Zobacz też:

  • hw_pipedocument() - Retrieve any document
  • hw_free_document() - Frees hw_document
  • hw_document_bodytag() - Body tag of hw_document
  • hw_document_size() - Size of hw_document
  • hw_output_document() - Prints hw_document

hw_GetSrcByDestObj
hw_getusername
Hyperwave Funkcje


Name of currently logged in user

hw_GetText
hw_Identify
Hyperwave Funkcje
PHP Manual

hw_getusername

(PHP 4)

hw_getusername — Name of currently logged in user

Opis

string hw_getusername ( int $connection )

Returns the username of the connection.

Parametry

connection

The connection identifier.

Zwracane wartości

Returns the username as a string.

hw_GetText
hw_Identify
Hyperwave Funkcje


Identifies as user

hw_getusername
hw_InCollections
Hyperwave Funkcje
PHP Manual

hw_Identify

(PHP 4)

hw_Identify — Identifies as user

Opis

string hw_identify ( int $link , string $username , string $password )

Identifies as user with username and password. Identification is only valid for the current session. I do not think this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.

Parametry

link

The connection identifier.

username

The username.

password

The password.

Zobacz też:

  • hw_connect() - Opens a connection

hw_getusername
hw_InCollections
Hyperwave Funkcje


Check if object ids in collections

hw_Identify
hw_Info
Hyperwave Funkcje
PHP Manual

hw_InCollections

(PHP 4)

hw_InCollections — Check if object ids in collections

Opis

array hw_incollections ( int $connection , array $object_id_array , array $collection_id_array , int $return_collections )

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array.

Parametry

connection

The connection identifier.

object_id_array

An array of object ids.

collection_id_array

An array of collection ids.

return_collections

When set to 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array.

When set to 1, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

Zwracane wartości

Returns an array of object ids.

hw_Identify
hw_Info
Hyperwave Funkcje


Info about connection

hw_InCollections
hw_InsColl
Hyperwave Funkcje
PHP Manual

hw_Info

(PHP 4)

hw_Info — Info about connection

Opis

string hw_info ( int $connection )

Returns information about the current connection.

Parametry

connection

The connection identifier.

Zwracane wartości

The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

hw_InCollections
hw_InsColl
Hyperwave Funkcje


Insert collection

hw_Info
hw_InsDoc
Hyperwave Funkcje
PHP Manual

hw_InsColl

(PHP 4)

hw_InsColl — Insert collection

Opis

int hw_inscoll ( int $connection , int $objectID , array $object_array )

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

Parametry

connection

The connection identifier.

objectID

object_array

Zwracane wartości

hw_Info
hw_InsDoc
Hyperwave Funkcje


Insert document

hw_InsColl
hw_insertanchors
Hyperwave Funkcje
PHP Manual

hw_InsDoc

(PHP 4)

hw_InsDoc — Insert document

Opis

int hw_insdoc ( resource $connection , int $parentID , string $object_record [, string $text ] )

Inserts a new document with attributes as in object_record into acollection.

If you want to insert a general document of any kind use hw_insertdocument() instead.

Parametry

connection

The connection identifier.

parentID

The collection id.

object_record

Object attributes.

text

If provided, this ascii text will be inserted too.

Zwracane wartości

Zobacz też:

  • hw_insertdocument() - Upload any document
  • hw_inscoll() - Insert collection

hw_InsColl
hw_insertanchors
Hyperwave Funkcje


Inserts only anchors into text

hw_InsDoc
hw_InsertDocument
Hyperwave Funkcje
PHP Manual

hw_insertanchors

(PHP 4 >= 4.0.4)

hw_insertanchors — Inserts only anchors into text

Opis

bool hw_insertanchors ( int $hwdoc , array $anchorecs , array $dest [, array $urlprefixes ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_InsDoc
hw_InsertDocument
Hyperwave Funkcje


Upload any document

hw_insertanchors
hw_InsertObject
Hyperwave Funkcje
PHP Manual

hw_InsertDocument

(PHP 4)

hw_InsertDocument — Upload any document

Opis

int hw_insertdocument ( int $connection , int $parent_id , int $hw_document )

Uploads a document into the given collection.

The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType.

Parametry

connection

The connection identifier.

parent_id

The collection identifier.

hw_document

The document identifier.

Zwracane wartości

The functions returns the object id of the new document or FALSE.

Zobacz też:

  • hw_pipedocument() - Retrieve any document

hw_insertanchors
hw_InsertObject
Hyperwave Funkcje


Inserts an object record

hw_InsertDocument
hw_mapid
Hyperwave Funkcje
PHP Manual

hw_InsertObject

(PHP 4)

hw_InsertObject — Inserts an object record

Opis

int hw_insertobject ( int $connection , string $object_rec , string $parameter )

Inserts an object into the server.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no corresponding link in the annotation text.

Parametry

connection

The connection identifier.

object_rec

The object can be any valid hyperwave object.

parameter

See the HG-CSP documentation for a detailed information on how the parameters have to be.

Zobacz też:

  • hw_pipedocument() - Retrieve any document
  • hw_insertdocument() - Upload any document
  • hw_insdoc() - Insert document
  • hw_inscoll() - Insert collection

hw_InsertDocument
hw_mapid
Hyperwave Funkcje


Maps global id on virtual local id

hw_InsertObject
hw_Modifyobject
Hyperwave Funkcje
PHP Manual

hw_mapid

(PHP 4)

hw_mapid — Maps global id on virtual local id

Opis

int hw_mapid ( int $connection , int $server_id , int $object_id )

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id.

This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject().

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

Parametry

connection

The connection identifier.

server_id

The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

object_id

The object identifier.

Zwracane wartości

Returns the virtual object id.

hw_InsertObject
hw_Modifyobject
Hyperwave Funkcje


Modifies object record

hw_mapid
hw_mv
Hyperwave Funkcje
PHP Manual

hw_Modifyobject

(PHP 4)

hw_Modifyobject — Modifies object record

Opis

bool hw_modifyobject ( int $connection , int $object_to_change , array $remove , array $add [, int $mode ] )

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is necessary if you want to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.

If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().

Przykład #1 modifying an attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => "books");
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
In order to delete/add a name=value pair from/to the object record just pass the remove/add array and set the last/third parameter to an empty array. If the attribute is the first one with that name to add, set attribute value in the remove array to an integer.

Przykład #2 adding a completely new attribute

<?php
       // $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => 0);
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Informacja: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:

Przykład #3 modifying Title attribute

<?php
       $remarr = array("Title" => "en:Books");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
or

Przykład #4 modifying Title attribute

<?php
       $remarr = array("Title" => array("en" => "Books"));
       $addarr = array("Title" => array("en" => "Articles", "ge"=>"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>
This removes the English title 'Books' and adds the English title 'Articles' and the German title 'Artikel'.

Przykład #5 removing attribute

<?php
       $remarr = array("Title" => "");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
?>

Informacja: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.

Informacja: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.

Informacja: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.

Informacja: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.

Informacja: You may not surround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.

Parametry

connection

The connection identifier.

object_to_change

The object to be changed.

remove

An array of attributes to remove.

add

An array of attributes to add.

mode

The last parameter determines if the modification is performed recursively. 1 means recursive modification. If some of the objects cannot be modified they will be skipped without notice. hw_error() may not indicate an error though some of the objects could not be modified.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

hw_mapid
hw_mv
Hyperwave Funkcje


Moves objects

hw_Modifyobject
hw_New_Document
Hyperwave Funkcje
PHP Manual

hw_mv

(PHP 4)

hw_mv — Moves objects

Opis

int hw_mv ( int $connection , array $object_id_array , int $source_id , int $destination_id )

Moves the specified objects from a collection to another.

Parametry

connection

The connection identifier.

object_id_array

An array of object ids.

source_id

The source collection id.

destination_id

The target collection id. If set to 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().

Zwracane wartości

Returns the number of moved objects.

Zobacz też:

  • hw_cp() - Copies objects
  • hw_deleteobject() - Deletes object

hw_Modifyobject
hw_New_Document
Hyperwave Funkcje


Create new document

hw_mv
hw_objrec2array
Hyperwave Funkcje
PHP Manual

hw_New_Document

(PHP 4)

hw_New_Document — Create new document

Opis

int hw_new_document ( string $object_record , string $document_data , int $document_size )

Returns a new Hyperwave document with the given document data and object record.

This function does not insert the document into the Hyperwave server.

Parametry

object_record

The object record.

document_data

The document data.

document_size

The document size. Must be the length of document_data.

Zwracane wartości

Returns the new Hyperwave document.

Zobacz też:

  • hw_free_document() - Frees hw_document
  • hw_document_size() - Size of hw_document
  • hw_document_bodytag() - Body tag of hw_document
  • hw_output_document() - Prints hw_document
  • hw_insertdocument() - Upload any document

hw_mv
hw_objrec2array
Hyperwave Funkcje


Convert attributes from object record to object array

hw_New_Document
hw_Output_Document
Hyperwave Funkcje
PHP Manual

hw_objrec2array

(PHP 4)

hw_objrec2array — Convert attributes from object record to object array

Opis

array hw_objrec2array ( string $object_record [, array $format ] )

Converts an object_record into an object array.

Parametry

object_record

The object record.

format

An associative array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE.

Zwracane wartości

Returns an array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long.

Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour.

Zobacz też:

  • hw_array2objrec() - Convert attributes from object array to object record

hw_New_Document
hw_Output_Document
Hyperwave Funkcje


Prints hw_document

hw_objrec2array
hw_pConnect
Hyperwave Funkcje
PHP Manual

hw_Output_Document

(PHP 4)

hw_Output_Document — Prints hw_document

Opis

bool hw_output_document ( int $hw_document )

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

Parametry

hw_document

The document identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

hw_objrec2array
hw_pConnect
Hyperwave Funkcje


Make a persistent database connection

hw_Output_Document
hw_PipeDocument
Hyperwave Funkcje
PHP Manual

hw_pConnect

(PHP 4)

hw_pConnect — Make a persistent database connection

Opis

int hw_pconnect ( string $host , int $port [, string $username ], string $password )

Opens a persistent connection to a Hyperwave server. You can have multiple persistent connections open at once.

Parametry

host

The server host name.

port

The server port number.

username

The Hyperwave user name. If omitted, no identification with the server will be done. It is similar to identify as user anonymous.

password

The password for username. Keep in mind, that the password is not encrypted.

Zwracane wartości

Returns a connection index on success, or FALSE if the connection could not be made.

Zobacz też:

  • hw_connect() - Opens a connection

hw_Output_Document
hw_PipeDocument
Hyperwave Funkcje


Retrieve any document

hw_pConnect
hw_Root
Hyperwave Funkcje
PHP Manual

hw_PipeDocument

(PHP 4)

hw_PipeDocument — Retrieve any document

Opis

int hw_pipedocument ( int $connection , int $objectID [, array $url_prefixes ] )

Gets the Hyperwave document with the given object ID. If the document has anchors which can be inserted, they will have been inserted already.

The document will be transferred via a special data connection which does not block the control connection.

Parametry

connection

The connection identifier.

objectID

The object identifier.

url_prefixes

Zwracane wartości

Returns the Hyperwave document.

Zobacz też:

  • hw_gettext() - Retrieve text document
  • hw_free_document() - Frees hw_document
  • hw_document_size() - Size of hw_document
  • hw_document_bodytag() - Body tag of hw_document
  • hw_output_document() - Prints hw_document

hw_pConnect
hw_Root
Hyperwave Funkcje


Root object id

hw_PipeDocument
hw_setlinkroot
Hyperwave Funkcje
PHP Manual

hw_Root

(PHP 4)

hw_Root — Root object id

Opis

int hw_root ( void )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

Zwracane wartości

Returns 0.

hw_PipeDocument
hw_setlinkroot
Hyperwave Funkcje


Set the id to which links are calculated

hw_Root
hw_stat
Hyperwave Funkcje
PHP Manual

hw_setlinkroot

(PHP 4)

hw_setlinkroot — Set the id to which links are calculated

Opis

int hw_setlinkroot ( int $link , int $rootid )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_Root
hw_stat
Hyperwave Funkcje


Returns status string

hw_setlinkroot
hw_Unlock
Hyperwave Funkcje
PHP Manual

hw_stat

(PHP 4)

hw_stat — Returns status string

Opis

string hw_stat ( int $link )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

hw_setlinkroot
hw_Unlock
Hyperwave Funkcje


Unlock object

hw_stat
hw_Who
Hyperwave Funkcje
PHP Manual

hw_Unlock

(PHP 4)

hw_Unlock — Unlock object

Opis

bool hw_unlock ( int $connection , int $objectID )

Unlocks a document, so other users regain access.

Parametry

connection

The connection identifier.

objectID

The document object identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_getandlock() - Return object record and lock object

hw_stat
hw_Who
Hyperwave Funkcje


List of currently logged in users

hw_Unlock
Hyperwave API
Hyperwave Funkcje
PHP Manual

hw_Who

(PHP 4)

hw_Who — List of currently logged in users

Opis

array hw_who ( int $connection )

Gets the list of currently logged in users.

Parametry

connection

The connection identifier.

Zwracane wartości

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initiated the request.

hw_Unlock
Hyperwave API
Hyperwave Funkcje


Hyperwave API

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Hyperwave API Funkcje
    • hw_api::checkin — Checks in an object
    • hw_api::checkout — Checks out an object
    • hw_api::children — Returns children of an object
    • hw_api::content — Returns content of an object
    • hw_api::copy — Copies physically
    • hw_api::dbstat — Returns statistics about database server
    • hw_api::dcstat — Returns statistics about document cache server
    • hw_api::dstanchors — Returns a list of all destination anchors
    • hw_api::dstofsrcanchor — Returns destination of a source anchor
    • hw_api::find — Search for objects
    • hw_api::ftstat — Returns statistics about fulltext server
    • hw_api::hwstat — Returns statistics about Hyperwave server
    • hw_api::identify — Log into Hyperwave Server
    • hw_api::info — Returns information about server configuration
    • hw_api::insert — Inserts a new object
    • hw_api::insertanchor — Inserts a new object of type anchor
    • hw_api::insertcollection — Inserts a new object of type collection
    • hw_api::insertdocument — Inserts a new object of type document
    • hw_api::link — Creates a link to an object
    • hw_api::lock — Locks an object
    • hw_api::move — Moves object between collections
    • hw_api::object — Retrieve attribute information
    • hw_api::objectbyanchor — Returns the object an anchor belongs to
    • hw_api::parents — Returns parents of an object
    • hw_api::remove — Delete an object
    • hw_api::replace — Replaces an object
    • hw_api::setcommittedversion — Commits version other than last version
    • hw_api::srcanchors — Returns a list of all source anchors
    • hw_api::srcsofdst — Returns source of a destination object
    • hw_api::unlock — Unlocks a locked object
    • hw_api::user — Returns the own user object
    • hw_api::userlist — Returns a list of all logged in users
    • hw_api_attribute::key — Returns key of the attribute
    • hw_api_attribute::langdepvalue — Returns value for a given language
    • hw_api_attribute::value — Returns value of the attribute
    • hw_api_attribute::values — Returns all values of the attribute
    • hw_api_content::mimetype — Returns mimetype
    • hw_api_content::read — Read content
    • hw_api_error::count — Returns number of reasons
    • hw_api_error::reason — Returns reason of error
    • hw_api_object::assign — Clones object
    • hw_api_object::attreditable — Checks whether an attribute is editable
    • hw_api_object::count — Returns number of attributes
    • hw_api_object::insert — Inserts new attribute
    • hw_api_object::remove — Removes attribute
    • hw_api_object::title — Returns the title attribute
    • hw_api_object::value — Returns value of attribute
    • hw_api_reason::description — Returns description of reason
    • hw_api_reason::type — Returns type of reason
    • hwapi_attribute_new — Creates instance of class hw_api_attribute
    • hwapi_content_new — Create new instance of class hw_api_content
    • hwapi_hgcsp — Returns object of class hw_api
    • hwapi_object_new — Creates a new instance of class hwapi_object_new
hw_Who
Wstęp
Inne serwisy


Wstęp

Hyperwave has been developed at » IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5, is available at » http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.2.0.

Hyperwave API
Instalacja/Konfiguracja
Hyperwave API


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Hyperwave API


Wymagania

Since 2001 there is a Hyperwave SDK available. It supports Java, JavaScript and C++. This PHP Extension is based on the C++ interface. In order to activate the hwapi support in PHP you will have to install the Hyperwave SDK first.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/hwapi.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.2.0

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Hyperwave API configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
hwapi.allow_persistent | "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.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Hyperwave API Funkcje
Hyperwave API


Hyperwave API Funkcje

Integration with Apache

The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.

Classes

The API provided by the HW_API extension is fully object oriented. It is very similar to the C++ interface of the Hyperwave SDK. It consist of the following classes.

  • HW_API
  • HW_API_Object
  • HW_API_Attribute
  • HW_API_Error
  • HW_API_Content
  • HW_API_Reason
Some basic classes like HW_API_String, HW_API_String_Array, etc., which exist in the Hyperwave SDK have not been implemented since PHP has powerful replacements for them.

Each class has certain method, whose names are identical to its counterparts in the Hyperwave SDK. Passing arguments to this function differs from all the other PHP extensions but is close to the C++ API of the HW SDK. Instead of passing several parameters they are all put into an associated array and passed as one parameter. The names of the keys are identical to those documented in the HW SDK. The common parameters are listed below. If other parameters are required they will be documented if needed.

  • objectIdentifier The name or id of an object, e.g. "rootcollection", "0x873A8768 0x00000002".
  • parentIdentifier The name or id of an object which is considered to be a parent.
  • object An instance of class HW_API_Object.
  • parameters An instance of class HW_API_Object.
  • version The version of an object.
  • mode An integer value determine the way an operation is executed.
  • attributeSelector Any array of strings, each containing a name of an attribute. This is used if you retrieve the object record and want to include certain attributes.
  • objectQuery A query to select certain object out of a list of objects. This is used to reduce the number of objects which was delivered by a function like hw_api::children() or hw_api::find().

Informacja:

Methods returning boolean can return TRUE, FALSE or HW_API_Error object.

Spis treści

  • hw_api::checkin — Checks in an object
  • hw_api::checkout — Checks out an object
  • hw_api::children — Returns children of an object
  • hw_api::content — Returns content of an object
  • hw_api::copy — Copies physically
  • hw_api::dbstat — Returns statistics about database server
  • hw_api::dcstat — Returns statistics about document cache server
  • hw_api::dstanchors — Returns a list of all destination anchors
  • hw_api::dstofsrcanchor — Returns destination of a source anchor
  • hw_api::find — Search for objects
  • hw_api::ftstat — Returns statistics about fulltext server
  • hw_api::hwstat — Returns statistics about Hyperwave server
  • hw_api::identify — Log into Hyperwave Server
  • hw_api::info — Returns information about server configuration
  • hw_api::insert — Inserts a new object
  • hw_api::insertanchor — Inserts a new object of type anchor
  • hw_api::insertcollection — Inserts a new object of type collection
  • hw_api::insertdocument — Inserts a new object of type document
  • hw_api::link — Creates a link to an object
  • hw_api::lock — Locks an object
  • hw_api::move — Moves object between collections
  • hw_api::object — Retrieve attribute information
  • hw_api::objectbyanchor — Returns the object an anchor belongs to
  • hw_api::parents — Returns parents of an object
  • hw_api::remove — Delete an object
  • hw_api::replace — Replaces an object
  • hw_api::setcommittedversion — Commits version other than last version
  • hw_api::srcanchors — Returns a list of all source anchors
  • hw_api::srcsofdst — Returns source of a destination object
  • hw_api::unlock — Unlocks a locked object
  • hw_api::user — Returns the own user object
  • hw_api::userlist — Returns a list of all logged in users
  • hw_api_attribute::key — Returns key of the attribute
  • hw_api_attribute::langdepvalue — Returns value for a given language
  • hw_api_attribute::value — Returns value of the attribute
  • hw_api_attribute::values — Returns all values of the attribute
  • hw_api_content::mimetype — Returns mimetype
  • hw_api_content::read — Read content
  • hw_api_error::count — Returns number of reasons
  • hw_api_error::reason — Returns reason of error
  • hw_api_object::assign — Clones object
  • hw_api_object::attreditable — Checks whether an attribute is editable
  • hw_api_object::count — Returns number of attributes
  • hw_api_object::insert — Inserts new attribute
  • hw_api_object::remove — Removes attribute
  • hw_api_object::title — Returns the title attribute
  • hw_api_object::value — Returns value of attribute
  • hw_api_reason::description — Returns description of reason
  • hw_api_reason::type — Returns type of reason
  • hwapi_attribute_new — Creates instance of class hw_api_attribute
  • hwapi_content_new — Create new instance of class hw_api_content
  • hwapi_hgcsp — Returns object of class hw_api
  • hwapi_object_new — Creates a new instance of class hwapi_object_new
Stałe predefiniowane
hw_api::checkin
Hyperwave API


Checks in an object

Hyperwave API Funkcje
hw_api::checkout
Hyperwave API Funkcje
PHP Manual

hw_api::checkin

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::checkin — Checks in an object

Opis

bool hw_api::checkin ( array $parameter )

This function checks in an object or a whole hierarchy of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'comment', 'mode' and 'objectQuery'. 'version' sets the version of the object. It consists of the major and minor version separated by a period. If the version is not set, the minor version is incremented. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL
Checks in and commits the object. The object must be a document.
HW_API_CHECKIN_RECURSIVE
If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.
HW_API_CHECKIN_FORCE_VERSION_CONTROL
Checks in an object even if it is not under version control.
HW_API_CHECKIN_REVERT_IF_NOT_CHANGED
Check if the new version is different from the last version. Unless this is the case the object will be checked in.
HW_API_CHECKIN_KEEP_TIME_MODIFIED
Keeps the time modified from the most recent object.
HW_API_CHECKIN_NO_AUTO_COMMIT
The object is not automatically committed on check-in.

Parametry

parameter

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_api::checkout

Hyperwave API Funkcje
hw_api::checkout
Hyperwave API Funkcje


Checks out an object

hw_api::checkin
hw_api::children
Hyperwave API Funkcje
PHP Manual

hw_api::checkout

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::checkout — Checks out an object

Opis

bool hw_api::checkout ( array $parameter )

This function checks out an object or a whole hierarchy of objects.

Parametry

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL
Checks out an object. The object must be a document.
HW_API_CHECKIN_RECURSIVE
If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_api::checkin

hw_api::checkin
hw_api::children
Hyperwave API Funkcje


Returns children of an object

hw_api::checkout
hw_api::content
Hyperwave API Funkcje
PHP Manual

hw_api::children

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::children — Returns children of an object

Opis

array hw_api::children ( array $parameter )

Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query.

Parametry

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Zwracane wartości

The return value is an array of objects of type HW_API_Object or HW_API_Error.

Zobacz też:

  • hw_api::parents

hw_api::checkout
hw_api::content
Hyperwave API Funkcje


Returns content of an object

hw_api::children
hw_api::copy
Hyperwave API Funkcje
PHP Manual

hw_api::content

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::content — Returns content of an object

Opis

HW_API_Content hw_api::content ( array $parameter )

This function returns the content of a document as an object of type hw_api_content.

Parametry

parameter

The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN.

HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable.

HW_API_CONTENT_REACHABLELINKS tells this method to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

Zwracane wartości

Returns an instance of hw_api_content.

hw_api::children
hw_api::copy
Hyperwave API Funkcje


Copies physically

hw_api::content
hw_api::dbstat
Hyperwave API Funkcje
PHP Manual

hw_api::copy

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::copy — Copies physically

Opis

hw_api_content hw_api::copy ( array $parameter )

This function will make a physical copy including the content if it exists and returns the new object or an error object.

Parametry

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

Zwracane wartości

Returns the copied object.

Zobacz też:

  • hw_api::move
  • hw_api::link

hw_api::content
hw_api::dbstat
Hyperwave API Funkcje


Returns statistics about database server

hw_api::copy
hw_api::dcstat
Hyperwave API Funkcje
PHP Manual

hw_api::dbstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dbstat — Returns statistics about database server

Opis

hw_api_object hw_api::dbstat ( array $parameter )

Returns statistics about database server.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::dcstat
  • hw_api::hwstat
  • hw_api::ftstat

hw_api::copy
hw_api::dcstat
Hyperwave API Funkcje


Returns statistics about document cache server

hw_api::dbstat
hw_api::dstanchors
Hyperwave API Funkcje
PHP Manual

hw_api::dcstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dcstat — Returns statistics about document cache server

Opis

hw_api_object hw_api::dcstat ( array $parameter )

Returns statistics about document cache server.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::dbstat
  • hw_api::hwstat
  • hw_api::ftstat

hw_api::dbstat
hw_api::dstanchors
Hyperwave API Funkcje


Returns a list of all destination anchors

hw_api::dcstat
hw_api::dstofsrcanchor
Hyperwave API Funkcje
PHP Manual

hw_api::dstanchors

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dstanchors — Returns a list of all destination anchors

Opis

array hw_api::dstanchors ( array $parameter )

Retrieves all destination anchors of an object.

Parametry

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Zwracane wartości

Zobacz też:

  • hw_api::srcanchors

hw_api::dcstat
hw_api::dstofsrcanchor
Hyperwave API Funkcje


Returns destination of a source anchor

hw_api::dstanchors
hw_api::find
Hyperwave API Funkcje
PHP Manual

hw_api::dstofsrcanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dstofsrcanchor — Returns destination of a source anchor

Opis

hw_api_object hw_api::dstofsrcanchor ( array $parameter )

Retrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document.

Parametry

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Zwracane wartości

Zobacz też:

  • hw_api::srcanchors
  • hw_api::dstanchors
  • hw_api::objectbyanchor

hw_api::dstanchors
hw_api::find
Hyperwave API Funkcje


Search for objects

hw_api::dstofsrcanchor
hw_api::ftstat
Hyperwave API Funkcje
PHP Manual

hw_api::find

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::find — Search for objects

Opis

array hw_api::find ( array $parameter )

This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index.

Parametry

parameter

The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'languages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', 'numberOfObjectsToGet' and 'exactMatchUnit' can be passed.

Zwracane wartości

hw_api::dstofsrcanchor
hw_api::ftstat
Hyperwave API Funkcje


Returns statistics about fulltext server

hw_api::find
hw_api::hwstat
Hyperwave API Funkcje
PHP Manual

hw_api::ftstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::ftstat — Returns statistics about fulltext server

Opis

hw_api_object hw_api::ftstat ( array $parameter )

Returns statistics about fulltext server.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::hwstat

hw_api::find
hw_api::hwstat
Hyperwave API Funkcje


Returns statistics about Hyperwave server

hw_api::ftstat
hw_api::identify
Hyperwave API Funkcje
PHP Manual

hw_api::hwstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::hwstat — Returns statistics about Hyperwave server

Opis

hw_api_object hw_api::hwstat ( array $parameter )

Returns statistics about Hyperwave server.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::ftstat

hw_api::ftstat
hw_api::identify
Hyperwave API Funkcje


Log into Hyperwave Server

hw_api::hwstat
hw_api::info
Hyperwave API Funkcje
PHP Manual

hw_api::identify

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::identify — Log into Hyperwave Server

Opis

bool hw_api::identify ( array $parameter )

Logs into the Hyperwave Server.

Parametry

parameter

The parameter array must contain the elements 'username' and 'password'.

Zwracane wartości

Returns an object of typeHW_API_Error if identification failed or TRUE if it was successful.

hw_api::hwstat
hw_api::info
Hyperwave API Funkcje


Returns information about server configuration

hw_api::identify
hw_api::insert
Hyperwave API Funkcje
PHP Manual

hw_api::info

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::info — Returns information about server configuration

Opis

array hw_api::info ( array $parameter )

Returns information about server configuration.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::ftstat
  • hw_api::hwstat

hw_api::identify
hw_api::insert
Hyperwave API Funkcje


Inserts a new object

hw_api::info
hw_api::insertanchor
Hyperwave API Funkcje
PHP Manual

hw_api::insert

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insert — Inserts a new object

Opis

hw_api_object hw_api::insert ( array $parameter )

Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set.

Parametry

parameter

The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding further attributes like the destination (attribute key is 'Parent'). 'content' is the content of the document. 'mode' can be a combination of the following flags:

HW_API_INSERT_NORMAL
The object in inserted into the server.
HW_API_INSERT_FORCE_VERSION_CONTROL
HW_API_INSERT_AUTOMATIC_CHECKOUT
HW_API_INSERT_PLAIN
HW_API_INSERT_KEEP_TIME_MODIFIED
HW_API_INSERT_DELAY_INDEXING

Zwracane wartości

Zobacz też:

  • hw_api::replace

hw_api::info
hw_api::insertanchor
Hyperwave API Funkcje


Inserts a new object of type anchor

hw_api::insert
hw_api::insertcollection
Hyperwave API Funkcje
PHP Manual

hw_api::insertanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insertanchor — Inserts a new object of type anchor

Opis

hw_api_object hw_api::insertanchor ( array $parameter )

This function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor.

Parametry

parameter

The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.

Zwracane wartości

Zobacz też:

  • hw_api::insert
  • hw_api::insertdocument
  • hw_api::insertcollection

hw_api::insert
hw_api::insertcollection
Hyperwave API Funkcje


Inserts a new object of type collection

hw_api::insertanchor
hw_api::insertdocument
Hyperwave API Funkcje
PHP Manual

hw_api::insertcollection

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insertcollection — Inserts a new object of type collection

Opis

hw_api_object hw_api::insertcollection ( array $parameter )

This function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection.

Parametry

parameter

The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

Zwracane wartości

Zobacz też:

  • hw_api::insert
  • hw_api::insertdocument
  • hw_api::insertanchor

hw_api::insertanchor
hw_api::insertdocument
Hyperwave API Funkcje


Inserts a new object of type document

hw_api::insertcollection
hw_api::link
Hyperwave API Funkcje
PHP Manual

hw_api::insertdocument

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insertdocument — Inserts a new object of type document

Opis

hw_api_object hw_api::insertdocument ( array $parameter )

This function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document.

Parametry

parameter

The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'.

See hwapi_insert() for the meaning of each element.

Zwracane wartości

Zobacz też:

  • hw_api::insert
  • hw_api::insertcollection
  • hw_api::insertanchor

hw_api::insertcollection
hw_api::link
Hyperwave API Funkcje


Creates a link to an object

hw_api::insertdocument
hw_api::lock
Hyperwave API Funkcje
PHP Manual

hw_api::link

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::link — Creates a link to an object

Opis

bool hw_api::link ( array $parameter )

Creates a link to an object. Accessing this link is like accessing the object to links points to.

Parametry

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

Zwracane wartości

The function returns TRUE on success or an error object.

Zobacz też:

  • hw_api::copy

hw_api::insertdocument
hw_api::lock
Hyperwave API Funkcje


Locks an object

hw_api::link
hw_api::move
Hyperwave API Funkcje
PHP Manual

hw_api::lock

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::lock — Locks an object

Opis

bool hw_api::lock ( array $parameter )

Locks an object for exclusive editing by the user calling this function. The object can be only unlocked by this user or the system user.

Parametry

parameter

The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'.

'mode' determines how an object is locked. HW_API_LOCK_NORMAL means, an object is locked until it is unlocked. HW_API_LOCK_RECURSIVE is only valid for collection and locks all objects within the collection and possible subcollections. HW_API_LOCK_SESSION means, an object is locked only as long as the session is valid.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_api::unlock

hw_api::link
hw_api::move
Hyperwave API Funkcje


Moves object between collections

hw_api::lock
hw_api::object
Hyperwave API Funkcje
PHP Manual

hw_api::move

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::move — Moves object between collections

Opis

bool hw_api::move ( array $parameter )

Moves object between collections.

Parametry

parameter

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_objrec2array() - Convert attributes from object record to object array

hw_api::lock
hw_api::object
Hyperwave API Funkcje


Retrieve attribute information

hw_api::move
hw_api::objectbyanchor
Hyperwave API Funkcje
PHP Manual

hw_api::object

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::object — Retrieve attribute information

Opis

hw_api_object hw_api::object ( array $parameter )

This function retrieves the attribute information of an object of any version. It will not return the document content.

Parametry

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

Zwracane wartości

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.

Przykłady

This simple example retrieves an object and checks for errors.

Przykład #1 Retrieve an object

<?php
function handle_error($error)
{
  $reason = $error->reason(0);
  echo "Type: <b>";
  switch ($reason->type()) {
    case 0:
      echo "Error";
      break;
    case 1:
      echo "Warning";
      break;
    case 2:
      echo "Message";
      break;
  }
  echo "</b><br />\n";
  echo "Description: " . $reason->description("en") . "<br />\n";
}

function list_attr($obj)
{
  echo "<table>\n";
  $count = $obj->count();
  for ($i=0; $i<$count; $i++) {
    $attr = $obj->attribute($i);
    printf("<tr><td align=\"right\" bgcolor=\"#c0c0c0\"><b>%s</b></td><td bgcolor=\"#F0F0F0\">%s</td></tr>\n",
             $attr->key(), $attr->value());
  }
  echo "</table>\n";
}

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=>"rootcollection", "attributeSelector"=>array("Title", "Name", "DocumentType"));
$root = $hwapi->object($parms);
if (get_class($root) == "HW_API_Error") {
  handle_error($root);
  exit;
}
list_attr($root);
?>

Zobacz też:

  • hw_api::content

hw_api::move
hw_api::objectbyanchor
Hyperwave API Funkcje


Returns the object an anchor belongs to

hw_api::object
hw_api::parents
Hyperwave API Funkcje
PHP Manual

hw_api::objectbyanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::objectbyanchor — Returns the object an anchor belongs to

Opis

hw_api_object hw_api::objectbyanchor ( array $parameter )

This function retrieves an object the specified anchor belongs to.

Parametry

parameter

The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Zwracane wartości

Zobacz też:

  • hw_api::dstofsrcanchor
  • hw_api::srcanchors
  • hw_api::dstanchors

hw_api::object
hw_api::parents
Hyperwave API Funkcje


Returns parents of an object

hw_api::objectbyanchor
hw_api::remove
Hyperwave API Funkcje
PHP Manual

hw_api::parents

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::parents — Returns parents of an object

Opis

array hw_api::parents ( array $parameter )

Retrieves the parents of an object. The parents can be further filtered by specifying an object query.

Parametry

parameter

The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

Zwracane wartości

The return value is an array of objects of type HW_API_Object or HW_API_Error.

Zobacz też:

  • hw_api::children

hw_api::objectbyanchor
hw_api::remove
Hyperwave API Funkcje


Delete an object

hw_api::parents
hw_api::replace
Hyperwave API Funkcje
PHP Manual

hw_api::remove

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::remove — Delete an object

Opis

bool hw_api::remove ( array $parameter )

Removes an object from the specified parent. Collections will be removed recursively.

Parametry

parameter

You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance.

The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be skipped.

The optional parameter 'mode' determines how the deletion is performed. In normal mode the object will not be removed physically until all instances are removed. In physical mode all instances of the object will be deleted immediately. In removelinks mode all references to and from the objects will be deleted as well. In nonrecursive the deletion is not performed recursive. Removing a collection which is not empty will cause an error.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_api::move

hw_api::parents
hw_api::replace
Hyperwave API Funkcje


Replaces an object

hw_api::remove
hw_api::setcommittedversion
Hyperwave API Funkcje
PHP Manual

hw_api::replace

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::replace — Replaces an object

Opis

hw_api_object hw_api::replace ( array $parameter )

Replaces the attributes and the content of an object.

Parametry

parameter

The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document.

'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL
The object on the server is replace with the object passed.
HW_API_REPLACE_FORCE_VERSION_CONTROL
HW_API_REPLACE_AUTOMATIC_CHECKOUT
HW_API_REPLACE_AUTOMATIC_CHECKIN
HW_API_REPLACE_PLAIN
HW_API_REPLACE_REVERT_IF_NOT_CHANGED
HW_API_REPLACE_KEEP_TIME_MODIFIED

Zwracane wartości

Zobacz też:

  • hw_api::insert

hw_api::remove
hw_api::setcommittedversion
Hyperwave API Funkcje


Commits version other than last version

hw_api::replace
hw_api::srcanchors
Hyperwave API Funkcje
PHP Manual

hw_api::setcommittedversion

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::setcommittedversion — Commits version other than last version

Opis

hw_api_object hw_api::setcommittedversion ( array $parameter )

Commits a version of a document. The committed version is the one which is visible to users with read access. By default the last version is the committed version.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::checkin
  • hw_api::checkout

hw_api::replace
hw_api::srcanchors
Hyperwave API Funkcje


Returns a list of all source anchors

hw_api::setcommittedversion
hw_api::srcsofdst
Hyperwave API Funkcje
PHP Manual

hw_api::srcanchors

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::srcanchors — Returns a list of all source anchors

Opis

array hw_api::srcanchors ( array $parameter )

Retrieves all source anchors of an object.

Parametry

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Zwracane wartości

Zobacz też:

  • hw_api::dstanchors

hw_api::setcommittedversion
hw_api::srcsofdst
Hyperwave API Funkcje


Returns source of a destination object

hw_api::srcanchors
hw_api::unlock
Hyperwave API Funkcje
PHP Manual

hw_api::srcsofdst

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::srcsofdst — Returns source of a destination object

Opis

array hw_api::srcsofdst ( array $parameter )

Retrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document.

Parametry

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

Zwracane wartości

Zobacz też:

  • hw_api::dstofsrcanchor

hw_api::srcanchors
hw_api::unlock
Hyperwave API Funkcje


Unlocks a locked object

hw_api::srcsofdst
hw_api::user
Hyperwave API Funkcje
PHP Manual

hw_api::unlock

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::unlock — Unlocks a locked object

Opis

bool hw_api::unlock ( array $parameter )

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object.

Parametry

parameter

The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Zwracane wartości

Returns TRUE on success or an object of class HW_API_Error.

Zobacz też:

  • hw_api::lock

hw_api::srcsofdst
hw_api::user
Hyperwave API Funkcje


Returns the own user object

hw_api::unlock
hw_api::userlist
Hyperwave API Funkcje
PHP Manual

hw_api::user

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::user — Returns the own user object

Opis

hw_api_object hw_api::user ( array $parameter )

Returns the own user object.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::userlist

hw_api::unlock
hw_api::userlist
Hyperwave API Funkcje


Returns a list of all logged in users

hw_api::user
hw_api_attribute::key
Hyperwave API Funkcje
PHP Manual

hw_api::userlist

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::userlist — Returns a list of all logged in users

Opis

array hw_api::userlist ( array $parameter )

Returns a list of all logged in users.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::user

hw_api::user
hw_api_attribute::key
Hyperwave API Funkcje


Returns key of the attribute

hw_api::userlist
hw_api_attribute::langdepvalue
Hyperwave API Funkcje
PHP Manual

hw_api_attribute::key

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::key — Returns key of the attribute

Opis

string hw_api_attribute::key ( void )

Returns the name of the attribute.

Zwracane wartości

Returns the name of the attribute as a string.

Zobacz też:

  • hw_api_attribute::value

hw_api::userlist
hw_api_attribute::langdepvalue
Hyperwave API Funkcje


Returns value for a given language

hw_api_attribute::key
hw_api_attribute::value
Hyperwave API Funkcje
PHP Manual

hw_api_attribute::langdepvalue

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::langdepvalue — Returns value for a given language

Opis

string hw_api_attribute::langdepvalue ( string $language )

Returns the value in the given language of the attribute.

Parametry

language

Zwracane wartości

Returns the value of the attribute as a string.

Zobacz też:

  • hw_api_attribute::value

hw_api_attribute::key
hw_api_attribute::value
Hyperwave API Funkcje


Returns value of the attribute

hw_api_attribute::langdepvalue
hw_api_attribute::values
Hyperwave API Funkcje
PHP Manual

hw_api_attribute::value

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::value — Returns value of the attribute

Opis

string hw_api_attribute::value ( void )

Gets the value of the attribute.

Zwracane wartości

Returns the value, as a string.

Zobacz też:

  • hw_api_attribute::key
  • hw_api_attribute::values

hw_api_attribute::langdepvalue
hw_api_attribute::values
Hyperwave API Funkcje


Returns all values of the attribute

hw_api_attribute::value
hw_api_content::mimetype
Hyperwave API Funkcje
PHP Manual

hw_api_attribute::values

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::values — Returns all values of the attribute

Opis

array hw_api_attribute::values ( void )

Gets all values of the attribute.

Zwracane wartości

Returns an array of attribute values.

Zobacz też:

  • hw_api_attribute::value

hw_api_attribute::value
hw_api_content::mimetype
Hyperwave API Funkcje


Returns mimetype

hw_api_attribute::values
hw_api_content::read
Hyperwave API Funkcje
PHP Manual

hw_api_content::mimetype

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_content::mimetype — Returns mimetype

Opis

string hw_api_content::mimetype ( void )

Returns the mimetype of the content.

Zwracane wartości

Returns the mimetype as a string.

hw_api_attribute::values
hw_api_content::read
Hyperwave API Funkcje


Read content

hw_api_content::mimetype
hw_api_error::count
Hyperwave API Funkcje
PHP Manual

hw_api_content::read

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_content::read — Read content

Opis

string hw_api_content::read ( string $buffer , int $len )

Reads len bytes from the content into the given buffer.

Parametry

buffer

len

Number of bytes to read.

Zwracane wartości

hw_api_content::mimetype
hw_api_error::count
Hyperwave API Funkcje


Returns number of reasons

hw_api_content::read
hw_api_error::reason
Hyperwave API Funkcje
PHP Manual

hw_api_error::count

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_error::count — Returns number of reasons

Opis

int hw_api_error::count ( void )

Returns the number of error reasons.

Zwracane wartości

Returns the number of errors, as an integer.

Zobacz też:

  • hw_api_error::reason

hw_api_content::read
hw_api_error::reason
Hyperwave API Funkcje


Returns reason of error

hw_api_error::count
hw_api_object::assign
Hyperwave API Funkcje
PHP Manual

hw_api_error::reason

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_error::reason — Returns reason of error

Opis

HW_API_Reason hw_api_error::reason ( void )

Returns the first error reason.

Zwracane wartości

Zobacz też:

  • hw_api_error::count

hw_api_error::count
hw_api_object::assign
Hyperwave API Funkcje


Clones object

hw_api_error::reason
hw_api_object::attreditable
Hyperwave API Funkcje
PHP Manual

hw_api_object::assign

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::assign — Clones object

Opis

bool hw_api_object::assign ( array $parameter )

Clones the attributes of an object.

Parametry

parameter

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

hw_api_error::reason
hw_api_object::attreditable
Hyperwave API Funkcje


Checks whether an attribute is editable

hw_api_object::assign
hw_api_object::count
Hyperwave API Funkcje
PHP Manual

hw_api_object::attreditable

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::attreditable — Checks whether an attribute is editable

Opis

bool hw_api_object::attreditable ( array $parameter )

Checks whether an attribute is editable.

Parametry

parameter

Zwracane wartości

Returns TRUE if the attribute is editable, FALSE otherwise.

hw_api_object::assign
hw_api_object::count
Hyperwave API Funkcje


Returns number of attributes

hw_api_object::attreditable
hw_api_object::insert
Hyperwave API Funkcje
PHP Manual

hw_api_object::count

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::count — Returns number of attributes

Opis

int hw_api_object::count ( array $parameter )

Returns the number of attributes.

Parametry

parameter

Zwracane wartości

Returns the number as an integer.

hw_api_object::attreditable
hw_api_object::insert
Hyperwave API Funkcje


Inserts new attribute

hw_api_object::count
hw_api_object::remove
Hyperwave API Funkcje
PHP Manual

hw_api_object::insert

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::insert — Inserts new attribute

Opis

bool hw_api_object::insert ( HW_API_Attribute $attribute )

Adds an attribute to the object.

Parametry

attribute

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_api_object::remove

hw_api_object::count
hw_api_object::remove
Hyperwave API Funkcje


Removes attribute

hw_api_object::insert
hw_api_object::title
Hyperwave API Funkcje
PHP Manual

hw_api_object::remove

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::remove — Removes attribute

Opis

bool hw_api_object::remove ( string $name )

Removes the attribute with the given name.

Parametry

name

The attribute name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • hw_api_object::insert

hw_api_object::insert
hw_api_object::title
Hyperwave API Funkcje


Returns the title attribute

hw_api_object::remove
hw_api_object::value
Hyperwave API Funkcje
PHP Manual

hw_api_object::title

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::title — Returns the title attribute

Opis

string hw_api_object::title ( array $parameter )

Returns the title attribute.

Parametry

parameter

Zwracane wartości

Returns the title as a string.

hw_api_object::remove
hw_api_object::value
Hyperwave API Funkcje


Returns value of attribute

hw_api_object::title
hw_api_reason::description
Hyperwave API Funkcje
PHP Manual

hw_api_object::value

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::value — Returns value of attribute

Opis

string hw_api_object::value ( string $name )

Returns value of an attribute.

Parametry

name

The attribute name.

Zwracane wartości

Returns the value of the attribute with the given name or FALSE if an error occurred.

hw_api_object::title
hw_api_reason::description
Hyperwave API Funkcje


Returns description of reason

hw_api_object::value
hw_api_reason::type
Hyperwave API Funkcje
PHP Manual

hw_api_reason::description

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_reason::description — Returns description of reason

Opis

string hw_api_reason::description ( void )

Returns the description of a reason

Zwracane wartości

Returns the description, as a string.

hw_api_object::value
hw_api_reason::type
Hyperwave API Funkcje


Returns type of reason

hw_api_reason::description
hwapi_attribute_new
Hyperwave API Funkcje
PHP Manual

hw_api_reason::type

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_reason::type — Returns type of reason

Opis

HW_API_Reason hw_api_reason::type ( void )

Returns the type of a reason.

Zwracane wartości

Returns an instance of HW_API_Reason.

hw_api_reason::description
hwapi_attribute_new
Hyperwave API Funkcje


Creates instance of class hw_api_attribute

hw_api_reason::type
hwapi_content_new
Hyperwave API Funkcje
PHP Manual

hwapi_attribute_new

(No version information available, might only be in SVN)

hwapi_attribute_new — Creates instance of class hw_api_attribute

Opis

HW_API_Attribute hwapi_attribute_new ([ string $name [, string $value ]] )

Creates a new instance of hw_api_attribute with the given name and value.

Parametry

name

The attribute name.

value

The attribute value.

Zwracane wartości

Returns an instance of hw_api_attribute.

hw_api_reason::type
hwapi_content_new
Hyperwave API Funkcje


Create new instance of class hw_api_content

hwapi_attribute_new
hwapi_hgcsp
Hyperwave API Funkcje
PHP Manual

hwapi_content_new

(No version information available, might only be in SVN)

hwapi_content_new — Create new instance of class hw_api_content

Opis

HW_API_Content hwapi_content_new ( string $content , string $mimetype )

Creates a new content object from the string content.

Parametry

content

mimetype

The mimetype for the contents.

Zwracane wartości

hwapi_attribute_new
hwapi_hgcsp
Hyperwave API Funkcje


Returns object of class hw_api

hwapi_content_new
hwapi_object_new
Hyperwave API Funkcje
PHP Manual

hwapi_hgcsp

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hwapi_hgcsp — Returns object of class hw_api

Opis

HW_API hwapi_hgcsp ( string $hostname [, int $port ] )

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP.

Parametry

hostname

The host name.

port

If you do not pass a port number, 418 is used.

Zwracane wartości

Returns an instance of HW_API.

hwapi_content_new
hwapi_object_new
Hyperwave API Funkcje


Creates a new instance of class hwapi_object_new

hwapi_hgcsp
Java
Hyperwave API Funkcje
PHP Manual

hwapi_object_new

(No version information available, might only be in SVN)

hwapi_object_new — Creates a new instance of class hwapi_object_new

Opis

hw_api_object hwapi_object_new ( array $parameter )

Creates a new instance of the class hw_api_object.

Parametry

parameter

Zwracane wartości

Zobacz też:

  • hw_api::lock

hwapi_hgcsp
Java
Hyperwave API Funkcje


PHP / Java Integration

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Java Servlet SAPI
  • Przykłady
    • Basic usage
  • Java Funkcje
    • java_last_exception_clear — Clear last Java exception
    • java_last_exception_get — Get last Java exception
hwapi_object_new
Wstęp
Inne serwisy


Wstęp

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

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.

Java
Instalacja/Konfiguracja
Java


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Java


Wymagania

You need a Java VM installed on your machine to use this extension.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/java.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0

Informacja: PHP 4 specific notes

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 PHP with Java support by using the --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared extension. Additional build instructions can be found in php-src/ext/java/README.

Windows users will enable php_java.dll inside of php.ini in order to use these functions. W PHP 4 ten DLL znajduje się w podkatalogu extensions/ binarnej dystrybucji PHP dla Windows.

In order to enable this module on a Windows environment with PHP <= 4.0.6, you must make jvm.dll available to your systems PATH. No additional DLL is needed for PHP versions > 4.0.6.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Java configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
java.class.path | NULL | PHP_INI_ALL |
java.home | NULL | PHP_INI_ALL |
java.library.path | NULL | PHP_INI_ALL |
java.library | JAVALIB | PHP_INI_ALL |
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Java Servlet SAPI
Java


Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advantage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.
  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

Stałe predefiniowane
Przykłady
Java


Przykłady

Spis treści

  • Basic usage
Java Servlet SAPI
Basic usage
Java


Basic usage

Przykład #1 Java Example

<?php
// get instance of Java class java.lang.System in PHP
$system = new Java('java.lang.System');

// demonstrate property access
echo 'Java version=' . $system->getProperty('java.version') . '<br />';
echo 'Java vendor=' . $system->getProperty('java.vendor') . '<br />';
echo 'OS=' . $system->getProperty('os.name') . ' ' .
             $system->getProperty('os.version') . ' on ' .
             $system->getProperty('os.arch') . ' <br />';

// java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',
                      "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

echo $formatter->format(new Java('java.util.Date'));
?>

Przykład #2 AWT Example

<?php
// This example is only intended to be run using the CLI.

$frame  = new Java('java.awt.Frame', 'PHP');
$button = new Java('java.awt.Button', 'Hello Java World!');

$frame->add('North', $button);
$frame->validate();
$frame->pack();
$frame->visible = True;

$thread = new Java('java.lang.Thread');
$thread->sleep(10000);

$frame->dispose();
?>
Notes:
  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionality through static methods.
  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.
  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

    • java_last_exception_get()
    • java_last_exception_clear()

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match. Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from. Once a method is selected, the parameters are coerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).
  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangeably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.

Przykłady
Java Funkcje
Przykłady


Java Funkcje

Spis treści

  • java_last_exception_clear — Clear last Java exception
  • java_last_exception_get — Get last Java exception
Basic usage
java_last_exception_clear
Java


Clear last Java exception

Java Funkcje
java_last_exception_get
Java Funkcje
PHP Manual

java_last_exception_clear

(PHP 4 >= 4.0.2)

java_last_exception_clear — Clear last Java exception

Opis

void java_last_exception_clear ( void )

Clears last Java exception.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

See java_last_exception_get() for an example.

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.

Java Funkcje
java_last_exception_get
Java Funkcje


Get last Java exception

java_last_exception_clear
LDAP
Java Funkcje
PHP Manual

java_last_exception_get

(PHP 4 >= 4.0.2)

java_last_exception_get — Get last Java exception

Opis

object java_last_exception_get ( void )

Gets last Java exception.

Zwracane wartości

Returns an exception object.

Przykłady

The following example demonstrates the usage of Java's exception handler from within PHP:

Przykład #1 Java exception handler

<?php
$stack = new Java('java.util.Stack');
$stack->push(1);

// This should succeed
$result = $stack->pop();
$ex = java_last_exception_get();
if (!$ex) {
  echo "$result\n";
}

// This should fail (error suppressed by @)
$result = @$stack->pop();
$ex = java_last_exception_get();
if ($ex) {
  echo $ex->toString();
}

// Clear last exception
java_last_exception_clear();
?>

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.

java_last_exception_clear
LDAP
Java Funkcje


Lightweight Directory Access Protocol

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Using the PHP LDAP calls
  • Przykłady
    • Basic usage
  • LDAP Funkcje
    • ldap_8859_to_t61 — Translate 8859 characters to t61 characters
    • ldap_add — Add entries to LDAP directory
    • ldap_bind — Bind to LDAP directory
    • ldap_close — Alias dla ldap_unbind
    • ldap_compare — Compare value of attribute found in entry specified with DN
    • ldap_connect — Connect to an LDAP server
    • ldap_count_entries — Count the number of entries in a search
    • ldap_delete — Delete an entry from a directory
    • ldap_dn2ufn — Convert DN to User Friendly Naming format
    • ldap_err2str — Convert LDAP error number into string error message
    • ldap_errno — Return the LDAP error number of the last LDAP command
    • ldap_error — Return the LDAP error message of the last LDAP command
    • ldap_explode_dn — Splits DN into its component parts
    • ldap_first_attribute — Return first attribute
    • ldap_first_entry — Return first result id
    • ldap_first_reference — Return first reference
    • ldap_free_result — Free result memory
    • ldap_get_attributes — Get attributes from a search result entry
    • ldap_get_dn — Get the DN of a result entry
    • ldap_get_entries — Get all result entries
    • ldap_get_option — Get the current value for given option
    • ldap_get_values_len — Get all binary values from a result entry
    • ldap_get_values — Get all values from a result entry
    • ldap_list — Single-level search
    • ldap_mod_add — Add attribute values to current attributes
    • ldap_mod_del — Delete attribute values from current attributes
    • ldap_mod_replace — Replace attribute values with new ones
    • ldap_modify — Modify an LDAP entry
    • ldap_next_attribute — Get the next attribute in result
    • ldap_next_entry — Get next result entry
    • ldap_next_reference — Get next reference
    • ldap_parse_reference — Extract information from reference entry
    • ldap_parse_result — Extract information from result
    • ldap_read — Read an entry
    • ldap_rename — Modify the name of an entry
    • ldap_sasl_bind — Bind to LDAP directory using SASL
    • ldap_search — Search LDAP tree
    • ldap_set_option — Set the value of the given option
    • ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing
    • ldap_sort — Sort LDAP result entries
    • ldap_start_tls — Start TLS
    • ldap_t61_to_8859 — Translate t61 characters to 8859 characters
    • ldap_unbind — Unbind from LDAP directory
java_last_exception_get
Wstęp
Inne serwisy


Wstęp

LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.

The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.

To refer to a file in a subdirectory on your hard disk, you might use something like:

   /usr/local/myapp/docs

The forwards slash marks each division in the reference, and the sequence is read from left to right.

The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be:

   cn=John Smith,ou=Accounts,o=My Company,c=US

The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as:

   country = US
   organization = My Company
   organizationalUnit = Accounts
   commonName = John Smith

In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.

Lots of information about LDAP can be found at

  • » Mozilla

  • » OpenLDAP Project

The Netscape SDK contains a helpful » Programmer's Guide in HTML format.

LDAP
Instalacja/Konfiguracja
LDAP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
LDAP


Wymagania

You will need to get and compile LDAP client libraries from either » OpenLDAP or » Bind9.net in order to compile PHP with LDAP support.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory. To enable SASL support, be sure --with-ldap-sasl[=DIR] is used, and that sasl.h exists on the system.

Informacja: Note to Win32 Users

Aby poprawnie działało rozszerzenie, pliki DLL muszą znajdować się w miejscu wskazanym przez PATH systemu Windows. Aby uzyskać więcej informacji zobacz FAQ zatytułowane "Jak mam dodać mój katalog PHP do PATH w Windows". Chociaż skopiowanie plików DLL z folderu PHP do systemowego katalogu Windows także zadziała (ponieważ katalog systemowy jest domyślnie w PATH systemu), ale nie jest to wymagane. To rozszerzenie wymaga następujących plików znajdujących się w PATH: libeay32.dll and ssleay32.dll

Versions before PHP 4.3.0 additionally require libsasl.dll.

In order to use Oracle LDAP libraries, proper Oracle environment has to be set.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

LDAP configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
ldap.max_links | "-1" | PHP_INI_SYSTEM |
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

Most LDAP functions operate on or return resources (e.g. ldap_connect() returns a positive LDAP link identifier required by most LDAP functions).

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

LDAP_DEREF_NEVER (integer)
LDAP_DEREF_SEARCHING (integer)
LDAP_DEREF_FINDING (integer)
LDAP_DEREF_ALWAYS (integer)
LDAP_OPT_DEREF (integer)
Specifies alternative rules for following aliases at the server.
LDAP_OPT_SIZELIMIT (integer)

Specifies the maximum number of entries that can be returned on a search operation.

Informacja: The actual size limit for operations is also bounded by the server's configured maximum number of return entries. The lesser of these two settings is the actual size limit.

LDAP_OPT_TIMELIMIT (integer)
Specifies the number of seconds to wait for search results.

Informacja: The actual time limit for operations is also bounded by the server's configured maximum time. The lesser of these two settings is the actual time limit.

LDAP_OPT_NETWORK_TIMEOUT (integer)
Option for ldap_set_option() to allow setting network timeout. (Available as of PHP 5.3.0)
LDAP_OPT_PROTOCOL_VERSION (integer)
Specifies the LDAP protocol to be used (V2 or V3).
LDAP_OPT_ERROR_NUMBER (integer)
LDAP_OPT_REFERRALS (integer)
Specifies whether to automatically follow referrals returned by the LDAP server.
LDAP_OPT_RESTART (integer)
LDAP_OPT_HOST_NAME (integer)
LDAP_OPT_ERROR_STRING (integer)
LDAP_OPT_MATCHED_DN (integer)
LDAP_OPT_SERVER_CONTROLS (integer)
Specifies a default list of server controls to be sent with each request.
LDAP_OPT_CLIENT_CONTROLS (integer)
Specifies a default list of client controls to be processed with each request.
LDAP_OPT_DEBUG_LEVEL (integer)
Specifies a bitwise level for debug traces.
GSLC_SSL_NO_AUTH (integer)
GSLC_SSL_ONEWAY_AUTH (integer)
GSLC_SSL_TWOWAY_AUTH (integer)
Typy zasobów
Using the PHP LDAP calls
LDAP


Using the PHP LDAP calls

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:

  ldap_connect()    // establish connection to server
     |
  ldap_bind()       // anonymous or authenticated "login"
     |
  do something like search or update the directory
  and display the results
     |
  ldap_close()      // "logout"

Stałe predefiniowane
Przykłady
LDAP


Przykłady

Spis treści

  • Basic usage
Using the PHP LDAP calls
Basic usage
LDAP


Basic usage

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Przykład #1 LDAP search example

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is " . $ds . "<br />";

if ($ds) {
    echo "Binding ...";
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is " . $r . "<br />";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds, "o=My Company, c=US", "sn=S*");
    echo "Search result is " . $sr . "<br />";

    echo "Number of entires returned is " . ldap_count_entries($ds, $sr) . "<br />";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for " . $info["count"] . " items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: " . $info[$i]["dn"] . "<br />";
        echo "first cn entry is: " . $info[$i]["cn"][0] . "<br />";
        echo "first email entry is: " . $info[$i]["mail"][0] . "<br /><hr />";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>
Przykłady
LDAP Funkcje
Przykłady


LDAP Funkcje

Spis treści

  • ldap_8859_to_t61 — Translate 8859 characters to t61 characters
  • ldap_add — Add entries to LDAP directory
  • ldap_bind — Bind to LDAP directory
  • ldap_close — Alias dla ldap_unbind
  • ldap_compare — Compare value of attribute found in entry specified with DN
  • ldap_connect — Connect to an LDAP server
  • ldap_count_entries — Count the number of entries in a search
  • ldap_delete — Delete an entry from a directory
  • ldap_dn2ufn — Convert DN to User Friendly Naming format
  • ldap_err2str — Convert LDAP error number into string error message
  • ldap_errno — Return the LDAP error number of the last LDAP command
  • ldap_error — Return the LDAP error message of the last LDAP command
  • ldap_explode_dn — Splits DN into its component parts
  • ldap_first_attribute — Return first attribute
  • ldap_first_entry — Return first result id
  • ldap_first_reference — Return first reference
  • ldap_free_result — Free result memory
  • ldap_get_attributes — Get attributes from a search result entry
  • ldap_get_dn — Get the DN of a result entry
  • ldap_get_entries — Get all result entries
  • ldap_get_option — Get the current value for given option
  • ldap_get_values_len — Get all binary values from a result entry
  • ldap_get_values — Get all values from a result entry
  • ldap_list — Single-level search
  • ldap_mod_add — Add attribute values to current attributes
  • ldap_mod_del — Delete attribute values from current attributes
  • ldap_mod_replace — Replace attribute values with new ones
  • ldap_modify — Modify an LDAP entry
  • ldap_next_attribute — Get the next attribute in result
  • ldap_next_entry — Get next result entry
  • ldap_next_reference — Get next reference
  • ldap_parse_reference — Extract information from reference entry
  • ldap_parse_result — Extract information from result
  • ldap_read — Read an entry
  • ldap_rename — Modify the name of an entry
  • ldap_sasl_bind — Bind to LDAP directory using SASL
  • ldap_search — Search LDAP tree
  • ldap_set_option — Set the value of the given option
  • ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing
  • ldap_sort — Sort LDAP result entries
  • ldap_start_tls — Start TLS
  • ldap_t61_to_8859 — Translate t61 characters to 8859 characters
  • ldap_unbind — Unbind from LDAP directory
Basic usage
ldap_8859_to_t61
LDAP


Translate 8859 characters to t61 characters

LDAP Funkcje
ldap_add
LDAP Funkcje
PHP Manual

ldap_8859_to_t61

(PHP 4 >= 4.0.2, PHP 5)

ldap_8859_to_t61 — Translate 8859 characters to t61 characters

Opis

string ldap_8859_to_t61 ( string $value )

Translate ISO-8859 characters to t61 characters.

This function is useful if you have to talk to a legacy LDAPv2 server.

Parametry

value

The text to be translated.

Zwracane wartości

Return the t61 translation of value.

Zobacz też:

  • ldap_t61_to_8859() - Translate t61 characters to 8859 characters

LDAP Funkcje
ldap_add
LDAP Funkcje


Add entries to LDAP directory

ldap_8859_to_t61
ldap_bind
LDAP Funkcje
PHP Manual

ldap_add

(PHP 4, PHP 5)

ldap_add — Add entries to LDAP directory

Opis

bool ldap_add ( resource $link_identifier , string $dn , array $entry )

Add entries in the LDAP directory.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

An array that specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.

<?php
$entree["attribut1"] = "value";
$entree["attribut2"][0] = "value1";
$entree["attribut2"][1] = "value2";
?>

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Complete example with authenticated bind

<?php
$ds = ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r = ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");

    // prepare data
    $info["cn"] = "John Jones";
    $info["sn"] = "Jones";
    $info["mail"] = "jonj@example.com";
    $info["objectclass"] = "person";

    // add data to directory
    $r = ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • ldap_delete() - Delete an entry from a directory

ldap_8859_to_t61
ldap_bind
LDAP Funkcje


Bind to LDAP directory

ldap_add
ldap_close
LDAP Funkcje
PHP Manual

ldap_bind

(PHP 4, PHP 5)

ldap_bind — Bind to LDAP directory

Opis

bool ldap_bind ( resource $link_identifier [, string $bind_rdn = NULL [, string $bind_password = NULL ]] )

Binds to the LDAP directory with specified RDN and password.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

bind_rdn

bind_password

If bind_rdn and bind_password are not specified, an anonymous bind is attempted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using LDAP Bind

<?php

// using ldap bind
$ldaprdn  = 'uname';     // ldap rdn or dn
$ldappass = 'password';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...";
    } else {
        echo "LDAP bind failed...";
    }

}

?>

Przykład #2 Using LDAP Bind Anonymously

<?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding anonymously
    $ldapbind = ldap_bind($ldapconn);

    if ($ldapbind) {
        echo "LDAP bind anonymous successful...";
    } else {
        echo "LDAP bind anonymous failed...";
    }

}

?>

Zobacz też:

  • ldap_unbind() - Unbind from LDAP directory

ldap_add
ldap_close
LDAP Funkcje


Alias dla ldap_unbind

ldap_bind
ldap_compare
LDAP Funkcje
PHP Manual

ldap_close

(PHP 4, PHP 5)

ldap_close — Alias dla ldap_unbind()

Opis

Ta funkcja jest aliasem dla: ldap_unbind().

ldap_bind
ldap_compare
LDAP Funkcje


Compare value of attribute found in entry specified with DN

ldap_close
ldap_connect
LDAP Funkcje
PHP Manual

ldap_compare

(PHP 4 >= 4.0.2, PHP 5)

ldap_compare — Compare value of attribute found in entry specified with DN

Opis

mixed ldap_compare ( resource $link_identifier , string $dn , string $attribute , string $value )

Compare value of attribute with value of same attribute in an LDAP directory entry.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

attribute

The attribute name.

value

The compared value.

Zwracane wartości

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

Przykłady

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

Przykład #1 Complete example of password check

<?php

$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {

    // bind
    if (ldap_bind($ds)) {

        // prepare data
        $dn = "cn=Matti Meikku, ou=My Unit, o=My Company, c=FI";
        $value = "secretpassword";
        $attr = "password";

        // compare value
        $r=ldap_compare($ds, $dn, $attr, $value);

        if ($r === -1) {
            echo "Error: " . ldap_error($ds);
        } elseif ($r === true) {
            echo "Password correct.";
        } elseif ($r === false) {
            echo "Wrong guess! Password incorrect.";
        }

    } else {
        echo "Unable to bind to LDAP server.";
    }

    ldap_close($ds);

} else {
    echo "Unable to connect to LDAP server.";
}
?>

Notatki

Ostrzeżenie

ldap_compare() can NOT be used to compare BINARY values!

ldap_close
ldap_connect
LDAP Funkcje


Connect to an LDAP server

ldap_compare
ldap_count_entries
LDAP Funkcje
PHP Manual

ldap_connect

(PHP 4, PHP 5)

ldap_connect — Connect to an LDAP server

Opis

resource ldap_connect ([ string $hostname = NULL [, int $port = 389 ]] )

Establishes a connection to a LDAP server on a specified hostname and port.

Parametry

hostname

If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and set this parameter as ldaps://hostname/.

port

The port to connect to. Not used when using URLs.

Zwracane wartości

Returns a positive LDAP link identifier on success, or FALSE on error. When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does not actually connect but just initializes the connecting parameters. The actual connect happens with the next calls to ldap_* funcs, usually with ldap_bind().

If no arguments are specified then the link identifier of the already opened link will be returned.

Rejestr zmian

Wersja | Opis
4.0.4 | URL and SSL support was added.

Przykłady

Przykład #1 Example of connecting to LDAP server.

<?php

// LDAP variables
$ldaphost = "ldap.example.com";  // your ldap servers
$ldapport = 389;                 // your ldap server's port number

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost, $ldapport)
          or die("Could not connect to $ldaphost");

?>

Przykład #2 Example of connecting securely to LDAP server.

<?php

// make sure your host is the correct one
// that you issued your secure certificate to
$ldaphost = "ldaps://ldap.example.com/";

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost)
          or die("Could not connect to {$ldaphost}");

?>

Zobacz też:

  • ldap_bind() - Bind to LDAP directory

ldap_compare
ldap_count_entries
LDAP Funkcje


Count the number of entries in a search

ldap_connect
ldap_delete
LDAP Funkcje
PHP Manual

ldap_count_entries

(PHP 4, PHP 5)

ldap_count_entries — Count the number of entries in a search

Opis

int ldap_count_entries ( resource $link_identifier , resource $result_identifier )

Returns the number of entries stored in the result of previous search operations.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

The internal LDAP result.

Zwracane wartości

Returns number of entries in the result or FALSE on error.

ldap_connect
ldap_delete
LDAP Funkcje


Delete an entry from a directory

ldap_count_entries
ldap_dn2ufn
LDAP Funkcje
PHP Manual

ldap_delete

(PHP 4, PHP 5)

ldap_delete — Delete an entry from a directory

Opis

bool ldap_delete ( resource $link_identifier , string $dn )

Deletes a particular entry in LDAP directory.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ldap_add() - Add entries to LDAP directory

ldap_count_entries
ldap_dn2ufn
LDAP Funkcje


Convert DN to User Friendly Naming format

ldap_delete
ldap_err2str
LDAP Funkcje
PHP Manual

ldap_dn2ufn

(PHP 4, PHP 5)

ldap_dn2ufn — Convert DN to User Friendly Naming format

Opis

string ldap_dn2ufn ( string $dn )

Turns the specified dn, into a more user-friendly form, stripping off type names.

Parametry

dn

The distinguished name of an LDAP entity.

Zwracane wartości

Returns the user friendly name.

ldap_delete
ldap_err2str
LDAP Funkcje


Convert LDAP error number into string error message

ldap_dn2ufn
ldap_errno
LDAP Funkcje
PHP Manual

ldap_err2str

(PHP 4, PHP 5)

ldap_err2str — Convert LDAP error number into string error message

Opis

string ldap_err2str ( int $errno )

Returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Parametry

errno

The error number.

Zwracane wartości

Returns the error message, as a string.

Przykłady

Przykład #1 Enumerating all LDAP error messages

<?php
  for ($i=0; $i<100; $i++) {
    printf("Error $i: %s<br />\n", ldap_err2str($i));
  }
?>

Zobacz też:

  • ldap_errno() - Return the LDAP error number of the last LDAP command
  • ldap_error() - Return the LDAP error message of the last LDAP command

ldap_dn2ufn
ldap_errno
LDAP Funkcje


Return the LDAP error number of the last LDAP command

ldap_err2str
ldap_error
LDAP Funkcje
PHP Manual

ldap_errno

(PHP 4, PHP 5)

ldap_errno — Return the LDAP error number of the last LDAP command

Opis

int ldap_errno ( resource $link_identifier )

Returns the standardized error number returned by the last LDAP command. This number can be converted into a textual error message using ldap_err2str().

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

Zwracane wartości

Return the LDAP error number of the last LDAP command for this link.

Przykłady

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

Przykład #1 Generating and catching an error

<?php
// This example contains an error, which we will catch.
$ld = ldap_connect("localhost");
$bind = ldap_bind($ld);
// syntax error in filter expression (errno 87),
// must be "objectclass=*" to work.
$res =  @ldap_search($ld, "o=Myorg, c=DE", "objectclass");
if (!$res) {
    echo "LDAP-Errno: " . ldap_errno($ld) . "<br />\n";
    echo "LDAP-Error: " . ldap_error($ld) . "<br />\n";
    die("Argh!<br />\n");
}
$info = ldap_get_entries($ld, $res);
echo $info["count"] . " matching entries.<br />\n";
?>

Zobacz też:

  • ldap_err2str() - Convert LDAP error number into string error message
  • ldap_error() - Return the LDAP error message of the last LDAP command

ldap_err2str
ldap_error
LDAP Funkcje


Return the LDAP error message of the last LDAP command

ldap_errno
ldap_explode_dn
LDAP Funkcje
PHP Manual

ldap_error

(PHP 4, PHP 5)

ldap_error — Return the LDAP error message of the last LDAP command

Opis

string ldap_error ( resource $link_identifier )

Returns the string error message explaining the error generated by the last LDAP command for the given link_identifier. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

Zwracane wartości

Returns string error message.

Zobacz też:

  • ldap_err2str() - Convert LDAP error number into string error message
  • ldap_errno() - Return the LDAP error number of the last LDAP command

ldap_errno
ldap_explode_dn
LDAP Funkcje


Splits DN into its component parts

ldap_error
ldap_first_attribute
LDAP Funkcje
PHP Manual

ldap_explode_dn

(PHP 4, PHP 5)

ldap_explode_dn — Splits DN into its component parts

Opis

array ldap_explode_dn ( string $dn , int $with_attrib )

Splits the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN.

Parametry

dn

The distinguished name of an LDAP entity.

with_attrib

Used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.

Zwracane wartości

Returns an array of all DN components. The first element in this array has count key and represents the number of returned values, next elements are numerically indexed DN components.

ldap_error
ldap_first_attribute
LDAP Funkcje


Return first attribute

ldap_explode_dn
ldap_first_entry
LDAP Funkcje
PHP Manual

ldap_first_attribute

(PHP 4, PHP 5)

ldap_first_attribute — Return first attribute

Opis

string ldap_first_attribute ( resource $link_identifier , resource $result_entry_identifier )

Gets the first attribute in the given entry. Remaining attributes are retrieved by calling ldap_next_attribute() successively.

Similar to reading entries, attributes are also read one by one from a particular entry.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

ber_identifier

ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to ldap_next_attribute() , which modifies that pointer.

Informacja:

This parameter is no longer used as this is now handled automatically by PHP. For backwards compatibility PHP will not throw an error if this parameter is passed.

Zwracane wartości

Returns the first attribute in the entry on success and FALSE on error.

Rejestr zmian

Wersja | Opis
5.2.4 | The ber_identifier was removed. This is now handled automatically by PHP.

Zobacz też:

  • ldap_next_attribute() - Get the next attribute in result
  • ldap_get_attributes() - Get attributes from a search result entry

ldap_explode_dn
ldap_first_entry
LDAP Funkcje


Return first result id

ldap_first_attribute
ldap_first_reference
LDAP Funkcje
PHP Manual

ldap_first_entry

(PHP 4, PHP 5)

ldap_first_entry — Return first result id

Opis

resource ldap_first_entry ( resource $link_identifier , resource $result_identifier )

Returns the entry identifier for first entry in the result. This entry identifier is then supplied to ldap_next_entry() routine to get successive entries from the result.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

Zwracane wartości

Returns the result entry identifier for the first entry on success and FALSE on error.

Zobacz też:

  • ldap_get_entries() - Get all result entries

ldap_first_attribute
ldap_first_reference
LDAP Funkcje


Return first reference

ldap_first_entry
ldap_free_result
LDAP Funkcje
PHP Manual

ldap_first_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_first_reference — Return first reference

Opis

resource ldap_first_reference ( resource $link , resource $result )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ldap_first_entry
ldap_free_result
LDAP Funkcje


Free result memory

ldap_first_reference
ldap_get_attributes
LDAP Funkcje
PHP Manual

ldap_free_result

(PHP 4, PHP 5)

ldap_free_result — Free result memory

Opis

bool ldap_free_result ( resource $result_identifier )

Frees up the memory allocated internally to store the result. All result memory will be automatically freed when the script terminates.

Typically all the memory allocated for the LDAP result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.

Parametry

result_identifier

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

ldap_first_reference
ldap_get_attributes
LDAP Funkcje


Get attributes from a search result entry

ldap_free_result
ldap_get_dn
LDAP Funkcje
PHP Manual

ldap_get_attributes

(PHP 4, PHP 5)

ldap_get_attributes — Get attributes from a search result entry

Opis

array ldap_get_attributes ( resource $link_identifier , resource $result_entry_identifier )

Reads attributes and values from an entry in the search result.

Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.

return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute

return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = (i+1)th value of the attribute

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Zwracane wartości

Returns a complete entry information in a multi-dimensional array on success and FALSE on error.

Przykłady

Przykład #1 Show the list of attributes held for a particular directory entry

<?php
// $ds is the link identifier for the directory

// $sr is a valid search result from a prior call to
// one of the ldap directory search calls

$entry = ldap_first_entry($ds, $sr);

$attrs = ldap_get_attributes($ds, $entry);

echo $attrs["count"] . " attributes held for this entry:<p>";

for ($i=0; $i < $attrs["count"]; $i++) {
    echo $attrs[$i] . "<br />";
}
?>

Zobacz też:

  • ldap_first_attribute() - Return first attribute
  • ldap_next_attribute() - Get the next attribute in result

ldap_free_result
ldap_get_dn
LDAP Funkcje


Get the DN of a result entry

ldap_get_attributes
ldap_get_entries
LDAP Funkcje
PHP Manual

ldap_get_dn

(PHP 4, PHP 5)

ldap_get_dn — Get the DN of a result entry

Opis

string ldap_get_dn ( resource $link_identifier , resource $result_entry_identifier )

Finds out the DN of an entry in the result.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Zwracane wartości

Returns the DN of the result entry and FALSE on error.

ldap_get_attributes
ldap_get_entries
LDAP Funkcje


Get all result entries

ldap_get_dn
ldap_get_option
LDAP Funkcje
PHP Manual

ldap_get_entries

(PHP 4, PHP 5)

ldap_get_entries — Get all result entries

Opis

array ldap_get_entries ( resource $link_identifier , resource $result_identifier )

Reads multiple entries from the given result, and then reading the attributes and multiple values.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

Zwracane wartości

Returns a complete result information in a multi-dimensional array on success and FALSE on error.

The structure of the array is as follows. The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)

return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry

return_value[i]["dn"] =  DN of the ith entry in the result

return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = NAME of the jth attribute in the ith entry in the result

return_value[i]["attribute"]["count"] = number of values for
                                        attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry

Zobacz też:

  • ldap_first_entry() - Return first result id
  • ldap_next_entry() - Get next result entry

ldap_get_dn
ldap_get_option
LDAP Funkcje


Get the current value for given option

ldap_get_entries
ldap_get_values_len
LDAP Funkcje
PHP Manual

ldap_get_option

(PHP 4 >= 4.0.4, PHP 5)

ldap_get_option — Get the current value for given option

Opis

bool ldap_get_option ( resource $link_identifier , int $option , mixed &$retval )

Sets retval to the value of the specified option.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

option

The parameter option can be one of:

Option | Type
LDAP_OPT_DEREF | integer
LDAP_OPT_SIZELIMIT | integer
LDAP_OPT_TIMELIMIT | integer
LDAP_OPT_NETWORK_TIMEOUT | integer
LDAP_OPT_PROTOCOL_VERSION | integer
LDAP_OPT_ERROR_NUMBER | integer
LDAP_OPT_REFERRALS | bool
LDAP_OPT_RESTART | bool
LDAP_OPT_HOST_NAME | string
LDAP_OPT_ERROR_STRING | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array

retval

This will be set to the option value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Check protocol version

<?php
// $ds is a valid link identifier for a directory server
if (ldap_get_option($ds, LDAP_OPT_PROTOCOL_VERSION, $version)) {
    echo "Using protocol version $version\n";
} else {
    echo "Unable to determine protocol version\n";
}
?>

Notatki

Informacja:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

Zobacz też:

  • ldap_set_option() - Set the value of the given option

ldap_get_entries
ldap_get_values_len
LDAP Funkcje


Get all binary values from a result entry

ldap_get_option
ldap_get_values
LDAP Funkcje
PHP Manual

ldap_get_values_len

(PHP 4, PHP 5)

ldap_get_values_len — Get all binary values from a result entry

Opis

array ldap_get_values_len ( resource $link_identifier , resource $result_entry_identifier , string $attribute )

Reads all the values of the attribute in the entry in the result.

This function is used exactly like ldap_get_values() except that it handles binary data and not string data.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

attribute

Zwracane wartości

Returns an array of values for the attribute on success and FALSE on error. Individual values are accessed by integer index in the array. The first index is 0. The number of values can be found by indexing "count" in the resultant array.

Zobacz też:

  • ldap_get_values() - Get all values from a result entry

ldap_get_option
ldap_get_values
LDAP Funkcje


Get all values from a result entry

ldap_get_values_len
ldap_list
LDAP Funkcje
PHP Manual

ldap_get_values

(PHP 4, PHP 5)

ldap_get_values — Get all values from a result entry

Opis

array ldap_get_values ( resource $link_identifier , resource $result_entry_identifier , string $attribute )

Reads all the values of the attribute in the entry in the result.

This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.

You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

attribute

Zwracane wartości

Returns an array of values for the attribute on success and FALSE on error. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"

    return_value["count"] = number of values for attribute
    return_value[0] = first value of attribute
    return_value[i] = ith value of attribute

Przykłady

Przykład #1 List all values of the "mail" attribute for a directory entry

<?php
// $ds is a valid link identifier for a directory server

// $sr is a valid search result from a prior call to
//     one of the ldap directory search calls

// $entry is a valid entry identifier from a prior call to
//        one of the calls that returns a directory entry

$values = ldap_get_values($ds, $entry, "mail");

echo $values["count"] . " email addresses for this entry.<br />";

for ($i=0; $i < $values["count"]; $i++) {
    echo $values[$i] . "<br />";
}
?>

Zobacz też:

  • ldap_get_values_len() - Get all binary values from a result entry

ldap_get_values_len
ldap_list
LDAP Funkcje


Single-level search

ldap_get_values
ldap_mod_add
LDAP Funkcje
PHP Manual

ldap_list

(PHP 4, PHP 5)

ldap_list — Single-level search

Opis

resource ldap_list ( resource $link_identifier , string $base_dn , string $filter [, array $attributes [, int $attrsonly [, int $sizelimit [, int $timelimit [, int $deref ]]]]] )

Performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.

LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Informacja:

This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Informacja:

This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

Zwracane wartości

Returns a search result identifier or FALSE on error.

Rejestr zmian

Wersja | Opis
4.0.5 | Parallel searches support was added. See ldap_search() for details.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

Przykłady

Przykład #1 Produce a list of all organizational units of an organization

<?php
// $ds is a valid link identifier for a directory server

$basedn = "o=My Company, c=US";
$justthese = array("ou");

$sr = ldap_list($ds, $basedn, "ou=*", $justthese);

$info = ldap_get_entries($ds, $sr);

for ($i=0; $i < $info["count"]; $i++) {
    echo $info[$i]["ou"][0];
}
?>

Zobacz też:

  • ldap_search() - Search LDAP tree

ldap_get_values
ldap_mod_add
LDAP Funkcje


Add attribute values to current attributes

ldap_list
ldap_mod_del
LDAP Funkcje
PHP Manual

ldap_mod_add

(PHP 4, PHP 5)

ldap_mod_add — Add attribute values to current attributes

Opis

bool ldap_mod_add ( resource $link_identifier , string $dn , array $entry )

Adds one or more attributes to the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level additions are done by the ldap_add() function.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_replace() - Replace attribute values with new ones

ldap_list
ldap_mod_del
LDAP Funkcje


Delete attribute values from current attributes

ldap_mod_add
ldap_mod_replace
LDAP Funkcje
PHP Manual

ldap_mod_del

(PHP 4, PHP 5)

ldap_mod_del — Delete attribute values from current attributes

Opis

bool ldap_mod_del ( resource $link_identifier , string $dn , array $entry )

Removes one or more attributes from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level deletions are done by the ldap_delete() function.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_mod_replace() - Replace attribute values with new ones

ldap_mod_add
ldap_mod_replace
LDAP Funkcje


Replace attribute values with new ones

ldap_mod_del
ldap_modify
LDAP Funkcje
PHP Manual

ldap_mod_replace

(PHP 4, PHP 5)

ldap_mod_replace — Replace attribute values with new ones

Opis

bool ldap_mod_replace ( resource $link_identifier , string $dn , array $entry )

Replaces one or more attributes from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level modifications are done by the ldap_modify() function.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_add() - Add attribute values to current attributes

ldap_mod_del
ldap_modify
LDAP Funkcje


Modify an LDAP entry

ldap_mod_replace
ldap_next_attribute
LDAP Funkcje
PHP Manual

ldap_modify

(PHP 4, PHP 5)

ldap_modify — Modify an LDAP entry

Opis

bool ldap_modify ( resource $link_identifier , string $dn , array $entry )

Modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • ldap_rename() - Modify the name of an entry

ldap_mod_replace
ldap_next_attribute
LDAP Funkcje


Get the next attribute in result

ldap_modify
ldap_next_entry
LDAP Funkcje
PHP Manual

ldap_next_attribute

(PHP 4, PHP 5)

ldap_next_attribute — Get the next attribute in result

Opis

string ldap_next_attribute ( resource $link_identifier , resource $result_entry_identifier )

Retrieves the attributes in an entry. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

ber_identifier

The internal state of the pointer is maintained by this parameter.

Informacja:

This parameter is no longer used as this is now handled automatically by PHP. For backwards compatibility PHP will not throw an error if this parameter is passed.

Zwracane wartości

Returns the next attribute in an entry on success and FALSE on error.

Rejestr zmian

Wersja | Opis
5.2.4 | The ber_identifier was removed. This is now handled automatically by PHP.

Zobacz też:

  • ldap_get_attributes() - Get attributes from a search result entry

ldap_modify
ldap_next_entry
LDAP Funkcje


Get next result entry

ldap_next_attribute
ldap_next_reference
LDAP Funkcje
PHP Manual

ldap_next_entry

(PHP 4, PHP 5)

ldap_next_entry — Get next result entry

Opis

resource ldap_next_entry ( resource $link_identifier , resource $result_entry_identifier )

Retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Zwracane wartości

Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.

Zobacz też:

  • ldap_get_entries() - Get all result entries

ldap_next_attribute
ldap_next_reference
LDAP Funkcje


Get next reference

ldap_next_entry
ldap_parse_reference
LDAP Funkcje
PHP Manual

ldap_next_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_next_reference — Get next reference

Opis

resource ldap_next_reference ( resource $link , resource $entry )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ldap_next_entry
ldap_parse_reference
LDAP Funkcje


Extract information from reference entry

ldap_next_reference
ldap_parse_result
LDAP Funkcje
PHP Manual

ldap_parse_reference

(PHP 4 >= 4.0.5, PHP 5)

ldap_parse_reference — Extract information from reference entry

Opis

bool ldap_parse_reference ( resource $link , resource $entry , array &$referrals )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ldap_next_reference
ldap_parse_result
LDAP Funkcje


Extract information from result

ldap_parse_reference
ldap_read
LDAP Funkcje
PHP Manual

ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5)

ldap_parse_result — Extract information from result

Opis

bool ldap_parse_result ( resource $link , resource $result , int &$errcode [, string &$matcheddn [, string &$errmsg [, array &$referrals ]]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ldap_parse_reference
ldap_read
LDAP Funkcje


Read an entry

ldap_parse_result
ldap_rename
LDAP Funkcje
PHP Manual

ldap_read

(PHP 4, PHP 5)

ldap_read — Read an entry

Opis

resource ldap_read ( resource $link_identifier , string $base_dn , string $filter [, array $attributes [, int $attrsonly [, int $sizelimit [, int $timelimit [, int $deref ]]]]] )

Performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of objectClass=*. If you know which entry types are used on the directory server, you might use an appropriate filter such as objectClass=inetOrgPerson.

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Informacja:

This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Informacja:

This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

Zwracane wartości

Returns a search result identifier or FALSE on error.

Rejestr zmian

Wersja | Opis
4.0.5 | Parallel searches support was added. See ldap_search() for details.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

ldap_parse_result
ldap_rename
LDAP Funkcje


Modify the name of an entry

ldap_read
ldap_sasl_bind
LDAP Funkcje
PHP Manual

ldap_rename

(PHP 4 >= 4.0.5, PHP 5)

ldap_rename — Modify the name of an entry

Opis

bool ldap_rename ( resource $link_identifier , string $dn , string $newrdn , string $newparent , bool $deleteoldrdn )

The entry specified by dn is renamed/moved.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

newrdn

The new RDN.

newparent

The new parent/superior entry.

deleteoldrdn

If TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

Zobacz też:

  • ldap_modify() - Modify an LDAP entry

ldap_read
ldap_sasl_bind
LDAP Funkcje


Bind to LDAP directory using SASL

ldap_rename
ldap_search
LDAP Funkcje
PHP Manual

ldap_sasl_bind

(PHP 5)

ldap_sasl_bind — Bind to LDAP directory using SASL

Opis

bool ldap_sasl_bind ( resource $link [, string $binddn = NULL [, string $password = NULL [, string $sasl_mech = NULL [, string $sasl_realm = NULL [, string $sasl_authc_id = NULL [, string $sasl_authz_id = NULL [, string $props = NULL ]]]]]]] )
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

Informacja: Requirement
ldap_sasl_bind() requires SASL support (sasl.h). Be sure --with-ldap-sasl is used when configuring PHP otherwise this function will be undefined.

Rejestr zmian

Wersja | Opis
5.3.3 | Support on Windows was added.

ldap_rename
ldap_search
LDAP Funkcje


Search LDAP tree

ldap_sasl_bind
ldap_set_option
LDAP Funkcje
PHP Manual

ldap_search

(PHP 4, PHP 5)

ldap_search — Search LDAP tree

Opis

resource ldap_search ( resource $link_identifier , string $base_dn , string $filter [, array $attributes [, int $attrsonly [, int $sizelimit [, int $timelimit [, int $deref ]]]]] )

Performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory.

From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

The search filter can be simple or advanced, using boolean operators in the format described in the LDAP documentation (see the » Netscape Directory SDK for full information on filters).

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Informacja:

This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Informacja:

This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

Zwracane wartości

Returns a search result identifier or FALSE on error.

Rejestr zmian

Wersja | Opis
4.0.5 | Parallel searches support was added.
4.0.2 | The attrsonly, sizelimit, timelimit and deref were added.

Przykłady

The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.

Przykład #1 LDAP search

<?php
// $ds is a valid link identifier for a directory server

// $person is all or part of a person's name, eg "Jo"

$dn = "o=My Company, c=US";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array("ou", "sn", "givenname", "mail");

$sr=ldap_search($ds, $dn, $filter, $justthese);

$info = ldap_get_entries($ds, $sr);

echo $info["count"]." entries returned\n";
?>

ldap_sasl_bind
ldap_set_option
LDAP Funkcje


Set the value of the given option

ldap_search
ldap_set_rebind_proc
LDAP Funkcje
PHP Manual

ldap_set_option

(PHP 4 >= 4.0.4, PHP 5)

ldap_set_option — Set the value of the given option

Opis

bool ldap_set_option ( resource $link_identifier , int $option , mixed $newval )

Sets the value of the specified option to be newval.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

option

The parameter option can be one of:

Option | Type | Available since
LDAP_OPT_DEREF | integer
LDAP_OPT_SIZELIMIT | integer
LDAP_OPT_TIMELIMIT | integer
LDAP_OPT_NETWORK_TIMEOUT | integer | PHP 5.3.0
LDAP_OPT_PROTOCOL_VERSION | integer
LDAP_OPT_ERROR_NUMBER | integer
LDAP_OPT_REFERRALS | bool
LDAP_OPT_RESTART | bool
LDAP_OPT_HOST_NAME | string
LDAP_OPT_ERROR_STRING | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array

LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls, this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value, and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean value. iscritical defaults to FALSE if not supplied. See » draft-ietf-ldapext-ldap-c-api-xx.txt for details. See also the second example below.

newval

The new value for the specified option.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Set protocol version

<?php
// $ds is a valid link identifier for a directory server
if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
    echo "Using LDAPv3";
} else {
    echo "Failed to set protocol version to 3";
}
?>

Przykład #2 Set server controls

<?php
// $ds is a valid link identifier for a directory server
// control with no value
$ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical" => true);
// iscritical defaults to FALSE
$ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => "magic");
// try to set both controls
if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2))) {
    echo "Failed to set server controls";
}
?>

Notatki

Informacja:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

Zobacz też:

  • ldap_get_option() - Get the current value for given option

ldap_search
ldap_set_rebind_proc
LDAP Funkcje


Set a callback function to do re-binds on referral chasing

ldap_set_option
ldap_sort
LDAP Funkcje
PHP Manual

ldap_set_rebind_proc

(PHP 4 >= 4.2.0, PHP 5)

ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing

Opis

bool ldap_set_rebind_proc ( resource $link , callback $callback )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ldap_set_option
ldap_sort
LDAP Funkcje


Sort LDAP result entries

ldap_set_rebind_proc
ldap_start_tls
LDAP Funkcje
PHP Manual

ldap_sort

(PHP 4 >= 4.2.0, PHP 5)

ldap_sort — Sort LDAP result entries

Opis

bool ldap_sort ( resource $link , resource $result , string $sortfilter )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ldap_set_rebind_proc
ldap_start_tls
LDAP Funkcje


Start TLS

ldap_sort
ldap_t61_to_8859
LDAP Funkcje
PHP Manual

ldap_start_tls

(PHP 4 >= 4.2.0, PHP 5)

ldap_start_tls — Start TLS

Opis

bool ldap_start_tls ( resource $link )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ldap_sort
ldap_t61_to_8859
LDAP Funkcje


Translate t61 characters to 8859 characters

ldap_start_tls
ldap_unbind
LDAP Funkcje
PHP Manual

ldap_t61_to_8859

(PHP 4 >= 4.0.2, PHP 5)

ldap_t61_to_8859 — Translate t61 characters to 8859 characters

Opis

string ldap_t61_to_8859 ( string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

ldap_start_tls
ldap_unbind
LDAP Funkcje


Unbind from LDAP directory

ldap_t61_to_8859
Lotus Notes
LDAP Funkcje
PHP Manual

ldap_unbind

(PHP 4, PHP 5)

ldap_unbind — Unbind from LDAP directory

Opis

bool ldap_unbind ( resource $link_identifier )

Unbinds from the LDAP directory.

Parametry

link_identifier

An LDAP link identifier, returned by ldap_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ldap_bind() - Bind to LDAP directory

ldap_t61_to_8859
Lotus Notes
LDAP Funkcje


Lotus Notes

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Lotus Notes Funkcje
    • notes_body — Open the message msg_number in the specified mailbox on the specified server (leave serv
    • notes_copy_db — Copy a Lotus Notes database
    • notes_create_db — Create a Lotus Notes database
    • notes_create_note — Create a note using form form_name
    • notes_drop_db — Drop a Lotus Notes database
    • notes_find_note — Returns a note id found in database_name
    • notes_header_info — Open the message msg_number in the specified mailbox on the specified server (leave serv
    • notes_list_msgs — Returns the notes from a selected database_name
    • notes_mark_read — Mark a note_id as read for the User user_name
    • notes_mark_unread — Mark a note_id as unread for the User user_name
    • notes_nav_create — Create a navigator name, in database_name
    • notes_search — Find notes that match keywords in database_name
    • notes_unread — Returns the unread note id's for the current User user_name
    • notes_version — Get the version Lotus Notes
ldap_unbind
Wstęp
Inne serwisy


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.

Lotus Notes
Instalacja/Konfiguracja
Lotus Notes


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Lotus Notes


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/notes.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Lotus Notes Funkcje
Lotus Notes


Lotus Notes Funkcje

Spis treści

  • notes_body — Open the message msg_number in the specified mailbox on the specified server (leave serv
  • notes_copy_db — Copy a Lotus Notes database
  • notes_create_db — Create a Lotus Notes database
  • notes_create_note — Create a note using form form_name
  • notes_drop_db — Drop a Lotus Notes database
  • notes_find_note — Returns a note id found in database_name
  • notes_header_info — Open the message msg_number in the specified mailbox on the specified server (leave serv
  • notes_list_msgs — Returns the notes from a selected database_name
  • notes_mark_read — Mark a note_id as read for the User user_name
  • notes_mark_unread — Mark a note_id as unread for the User user_name
  • notes_nav_create — Create a navigator name, in database_name
  • notes_search — Find notes that match keywords in database_name
  • notes_unread — Returns the unread note id's for the current User user_name
  • notes_version — Get the version Lotus Notes
Stałe predefiniowane
notes_body
Lotus Notes


Open the message msg_number in the specified mailbox on the specified server (leave serv

Lotus Notes Funkcje
notes_copy_db
Lotus Notes Funkcje
PHP Manual

notes_body

(PHP 4 >= 4.0.5)

notes_body — Open the message msg_number in the specified mailbox on the specified server (leave serv

Opis

array notes_body ( string $server , string $mailbox , int $msg_number )
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.

Lotus Notes Funkcje
notes_copy_db
Lotus Notes Funkcje


Copy a Lotus Notes database

notes_body
notes_create_db
Lotus Notes Funkcje
PHP Manual

notes_copy_db

(PHP 4 >= 4.0.5)

notes_copy_db — Copy a Lotus Notes database

Opis

bool notes_copy_db ( string $from_database_name , string $to_database_name )
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.

notes_body
notes_create_db
Lotus Notes Funkcje


Create a Lotus Notes database

notes_copy_db
notes_create_note
Lotus Notes Funkcje
PHP Manual

notes_create_db

(PHP 4 >= 4.0.5)

notes_create_db — Create a Lotus Notes database

Opis

bool notes_create_db ( string $database_name )
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.

notes_copy_db
notes_create_note
Lotus Notes Funkcje


Create a note using form form_name

notes_create_db
notes_drop_db
Lotus Notes Funkcje
PHP Manual

notes_create_note

(PHP 4 >= 4.0.5)

notes_create_note — Create a note using form form_name

Opis

bool notes_create_note ( string $database_name , string $form_name )
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.

notes_create_db
notes_drop_db
Lotus Notes Funkcje


Drop a Lotus Notes database

notes_create_note
notes_find_note
Lotus Notes Funkcje
PHP Manual

notes_drop_db

(PHP 4 >= 4.0.5)

notes_drop_db — Drop a Lotus Notes database

Opis

bool notes_drop_db ( string $database_name )
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.

notes_create_note
notes_find_note
Lotus Notes Funkcje


Returns a note id found in database_name

notes_drop_db
notes_header_info
Lotus Notes Funkcje
PHP Manual

notes_find_note

(PHP 4 >= 4.0.5)

notes_find_note — Returns a note id found in database_name

Opis

int notes_find_note ( string $database_name , string $name [, string $type ] )
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.

notes_drop_db
notes_header_info
Lotus Notes Funkcje


Open the message msg_number in the specified mailbox on the specified server (leave serv

notes_find_note
notes_list_msgs
Lotus Notes Funkcje
PHP Manual

notes_header_info

(PHP 4 >= 4.0.5)

notes_header_info — Open the message msg_number in the specified mailbox on the specified server (leave serv

Opis

object notes_header_info ( string $server , string $mailbox , int $msg_number )
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.

notes_find_note
notes_list_msgs
Lotus Notes Funkcje


Returns the notes from a selected database_name

notes_header_info
notes_mark_read
Lotus Notes Funkcje
PHP Manual

notes_list_msgs

(PHP 4 >= 4.0.5)

notes_list_msgs — Returns the notes from a selected database_name

Opis

bool notes_list_msgs ( string $db )
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.

notes_header_info
notes_mark_read
Lotus Notes Funkcje


Mark a note_id as read for the User user_name

notes_list_msgs
notes_mark_unread
Lotus Notes Funkcje
PHP Manual

notes_mark_read

(PHP 4 >= 4.0.5)

notes_mark_read — Mark a note_id as read for the User user_name

Opis

bool notes_mark_read ( string $database_name , string $user_name , string $note_id )
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.

notes_list_msgs
notes_mark_unread
Lotus Notes Funkcje


Mark a note_id as unread for the User user_name

notes_mark_read
notes_nav_create
Lotus Notes Funkcje
PHP Manual

notes_mark_unread

(PHP 4 >= 4.0.5)

notes_mark_unread — Mark a note_id as unread for the User user_name

Opis

bool notes_mark_unread ( string $database_name , string $user_name , string $note_id )
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.

notes_mark_read
notes_nav_create
Lotus Notes Funkcje


Create a navigator name, in database_name

notes_mark_unread
notes_search
Lotus Notes Funkcje
PHP Manual

notes_nav_create

(PHP 4 >= 4.0.5)

notes_nav_create — Create a navigator name, in database_name

Opis

bool notes_nav_create ( string $database_name , string $name )
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.

notes_mark_unread
notes_search
Lotus Notes Funkcje


Find notes that match keywords in database_name

notes_nav_create
notes_unread
Lotus Notes Funkcje
PHP Manual

notes_search

(PHP 4 >= 4.0.5)

notes_search — Find notes that match keywords in database_name

Opis

array notes_search ( string $database_name , string $keywords )
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.

notes_nav_create
notes_unread
Lotus Notes Funkcje


Returns the unread note id's for the current User user_name

notes_search
notes_version
Lotus Notes Funkcje
PHP Manual

notes_unread

(PHP 4 >= 4.0.5)

notes_unread — Returns the unread note id's for the current User user_name

Opis

array notes_unread ( string $database_name , string $user_name )
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.

notes_search
notes_version
Lotus Notes Funkcje


Get the version Lotus Notes

notes_unread
Memcache
Lotus Notes Funkcje
PHP Manual

notes_version

(PHP 4 >= 4.0.5)

notes_version — Get the version Lotus Notes

Opis

float notes_version ( string $database_name )
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.

notes_unread
Memcache
Lotus Notes Funkcje


Memcache

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • Memcache — The Memcache class
    • Memcache::add — Add an item to the server
    • Memcache::addServer — Add a memcached server to connection pool
    • Memcache::close — Close memcached server connection
    • Memcache::connect — Open memcached server connection
    • Memcache::decrement — Decrement item's value
    • Memcache::delete — Delete item from the server
    • Memcache::flush — Flush all existing items at the server
    • Memcache::get — Retrieve item from the server
    • Memcache::getExtendedStats — Get statistics from all servers in pool
    • Memcache::getServerStatus — Returns server status
    • Memcache::getStats — Get statistics of the server
    • Memcache::getVersion — Return version of the server
    • Memcache::increment — Increment item's value
    • Memcache::pconnect — Open memcached server persistent connection
    • Memcache::replace — Replace value of the existing item
    • Memcache::set — Store data at the server
    • Memcache::setCompressThreshold — Enable automatic compression of large values
    • Memcache::setServerParams — Changes server parameters and status at runtime
  • Memcache Funkcje
    • memcache_debug — Turn debug output on/off
notes_version
Wstęp
Inne serwisy


Wstęp

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.memcached.org/.

Memcache
Instalacja/Konfiguracja
Memcache


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Memcache


Wymagania

This module uses functions of » zlib to support on-the-fly data compression. Zlib is required to install this module.

PHP 4.3.3 or newer is required to use the memcache extension.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/memcache.

Informacja:

It's possible to disable memcache session handler support. The 'pecl install' option prompts for this (default is enabled) however when compiling statically into PHP the --disable-memcache-session configure option may be used.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Memcache Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
memcache.allow_failover | "1" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since memcache 2.1.0.
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
session.save_handler | "files" | PHP_INI_ALL | Supported since memcache 2.1.2
session.save_path | "" | PHP_INI_ALL | Supported since memcache 2.1.2
memcache.protocol | ascii | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.redundancy | 1 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.session_redundancy | 2 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.compress_threshold | 20000 | >PHP_INI_ALL | Supported since memcache 3.0.3
memcache.lock_timeout | 15 | >PHP_INI_ALL | Supported since memcache 3.0.4
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.

memcache.allow_failover boolean

Whether to transparently failover to other servers on errors.

memcache.max_failover_attempts integer

Defines how many servers to try when setting and getting data. Used only in conjunction with memcache.allow_failover.

memcache.chunk_size integer

Data will be transferred in chunks of this size, setting the value lower requires more network writes. Try increasing this value to 32768 if noticing otherwise inexplicable slowdowns.

memcache.default_port string

The default TCP port number to use when connecting to the memcached server if no other port is specified.

memcache.hash_strategy string

Controls which strategy to use when mapping keys to servers. Set this value to consistent to enable consistent hashing which allows servers to be added or removed from the pool without causing keys to be remapped. Setting this value to standard results in the old strategy being used.

memcache.hash_function string

Controls which hash function to apply when mapping keys to servers, crc32 uses the standard CRC32 hash while fnv uses FNV-1a.

session.save_handler string

Use memcache as a session handler by setting this value to memcache.

session.save_path string

Defines a comma separated of server urls to use for session storage, for example "tcp://host1:11211, tcp://host2:11211".

Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. For example "tcp://host1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

memcache.protocol string

memcache.redundancy integer

memcache.session_redundancy integer

memcache.compress_threshold integer

memcache.lock_timeout integer

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

Memcache Constants
Name | Description
MEMCACHE_COMPRESSED (integer) | Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() i Memcache::replace().
MEMCACHE_HAVE_SESSION (integer) | 1 if this Memcache session handler is available, 0 otherwise.
Typy zasobów
Przykłady
Memcache


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
Memcache


Basic usage

Przykład #1 memcache extension overview example

In this example, an object is being saved in the cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in the cache.

<?php

$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";

var_dump($get_result);

?>

Przykład #2 Using memcache session handler

<?php

$session_save_path = "tcp://$host:$port?persistent=1&weight=2&timeout=2&retry_interval=10,  ,tcp://$host:$port  ";
ini_set('session.save_handler', 'memcache');
ini_set('session.save_path', $session_save_path);

?>

Przykłady
Memcache
Przykłady


The Memcache class

(No version information available, might only be in SVN)

Wstęp

Represents a connection to a set of memcache servers.

Krótki opis klasy

Memcache {
bool add ( string $key , mixed $var [, int $flag [, int $expire ]] )
bool addServer ( string $host [, int $port = 11211 [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callback $failure_callback [, int $timeoutms ]]]]]]]] )
bool close ( void )
bool connect ( string $host [, int $port [, int $timeout ]] )
int decrement ( string $key [, int $value = 1 ] )
bool delete ( string $key [, int $timeout = 0 ] )
bool flush ( void )
string get ( string $key [, int &$flags ] )
array getExtendedStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )
int getServerStatus ( string $host [, int $port = 11211 ] )
array getStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )
string getVersion ( void )
int increment ( string $key [, int $value = 1 ] )
mixed pconnect ( string $host [, int $port [, int $timeout ]] )
bool replace ( string $key , mixed $var [, int $flag [, int $expire ]] )
bool set ( string $key , mixed $var [, int $flag [, int $expire ]] )
bool setCompressThreshold ( int $threshold [, float $min_savings ] )
bool setServerParams ( string $host [, int $port = 11211 [, int $timeout [, int $retry_interval = false [, bool $status [, callback $failure_callback ]]]]] )
}

Spis treści

  • Memcache::add — Add an item to the server
  • Memcache::addServer — Add a memcached server to connection pool
  • Memcache::close — Close memcached server connection
  • Memcache::connect — Open memcached server connection
  • Memcache::decrement — Decrement item's value
  • Memcache::delete — Delete item from the server
  • Memcache::flush — Flush all existing items at the server
  • Memcache::get — Retrieve item from the server
  • Memcache::getExtendedStats — Get statistics from all servers in pool
  • Memcache::getServerStatus — Returns server status
  • Memcache::getStats — Get statistics of the server
  • Memcache::getVersion — Return version of the server
  • Memcache::increment — Increment item's value
  • Memcache::pconnect — Open memcached server persistent connection
  • Memcache::replace — Replace value of the existing item
  • Memcache::set — Store data at the server
  • Memcache::setCompressThreshold — Enable automatic compression of large values
  • Memcache::setServerParams — Changes server parameters and status at runtime
Basic usage
Memcache::add
Memcache


Add an item to the server

Memcache
Memcache::addServer
Memcache
PHP Manual

Memcache::add

(PECL memcache >= 0.2.0)

Memcache::add — Add an item to the server

Opis

bool Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] )

Memcache::add() stores variable var with key only if such key doesn't exist at the server yet. Also you can use memcache_add() function.

Parametry

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Returns FALSE if such key already exist. For the rest Memcache::add() behaves similarly to Memcache::set().

Przykłady

Przykład #1 Memcache::add() example

<?php

$memcache_obj = memcache_connect("localhost", 11211);

/* procedural API */
memcache_add($memcache_obj, 'var_key', 'test variable', false, 30);

/* OO API */
$memcache_obj->add('var_key', 'test variable', false, 30);

?>

Zobacz też:

  • Memcache::set() - Store data at the server
  • Memcache::replace() - Replace value of the existing item

Memcache
Memcache::addServer
Memcache


Add a memcached server to connection pool

Memcache::add
Memcache::close
Memcache
PHP Manual

Memcache::addServer

(PECL memcache >= 2.0.0)

Memcache::addServer — Add a memcached server to connection pool

Opis

bool Memcache::addServer ( string $host [, int $port = 11211 [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callback $failure_callback [, int $timeoutms ]]]]]]]] )

Memcache::addServer() adds a server to the connection pool. The connection, which was opened using Memcache::addServer() will be automatically closed at the end of script execution, you can also close it manually with Memcache::close(). You can also use the memcache_add_server() function.

When using this method (as opposed to Memcache::connect() and Memcache::pconnect()) the network connection is not established until actually needed. Thus there is no overhead in adding a large number of servers to the pool, even though they might not all be used.

Failover may occur at any stage in any of the methods, as long as other servers are available the request the user won't notice. Any kind of socket or Memcached server level errors (except out-of-memory) may trigger the failover. Normal client errors such as adding an existing key will not trigger a failover.

Informacja:

This function has been added to Memcache version 2.0.0.

Parametry

host

Point to the host where memcached is listening for connections. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

persistent

Controls the use of a persistent connection. Default to TRUE.

weight

Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

retry_interval

Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Neither this nor the persistent parameter has any effect when the extension is loaded dynamically via dl().

Each failed connection struct has its own timeout and before it has expired the struct will be skipped when selecting backends to serve a request. Once expired the connection will be successfully reconnected or marked as failed for another retry_interval seconds. The typical effect is that each web server child will retry the connection about every retry_interval seconds when serving a page.

status

Controls if the server should be flagged as online. Setting this parameter to FALSE and retry_interval to -1 allows a failed server to be kept in the pool so as not to affect the key distribution algorithm. Requests for this server will then failover or fail immediately depending on the memcache.allow_failover setting. Default to TRUE, meaning the server should be considered online.

failure_callback

Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server.

timeoutms

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::addServer() example

<?php

/* OO API */

$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
$memcache->addServer('memcache_host2', 11211);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_add_server($memcache_obj, 'memcache_host2', 11211);

?>

Zobacz też:

  • Memcache::connect() - Open memcached server connection
  • Memcache::pconnect() - Open memcached server persistent connection
  • Memcache::close() - Close memcached server connection
  • Memcache::setServerParams() - Changes server parameters and status at runtime
  • Memcache::getServerStatus() - Returns server status

Memcache::add
Memcache::close
Memcache


Close memcached server connection

Memcache::addServer
Memcache::connect
Memcache
PHP Manual

Memcache::close

(PECL memcache >= 0.4.0)

Memcache::close — Close memcached server connection

Opis

bool Memcache::close ( void )

Memcache::close() closes connection to memcached server. This function doesn't close persistent connections, which are closed only during web-server shutdown/restart. Also you can use memcache_close() function.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::close() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/*
do something here ..
*/
memcache_close($memcache_obj);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/*
do something here ..
*/
$memcache_obj->close();

?>

Zobacz też:

  • Memcache::connect() - Open memcached server connection
  • Memcache::pconnect() - Open memcached server persistent connection

Memcache::addServer
Memcache::connect
Memcache


Open memcached server connection

Memcache::close
Memcache::decrement
Memcache
PHP Manual

Memcache::connect

(PECL memcache >= 0.2.0)

Memcache::connect — Open memcached server connection

Opis

bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )

Memcache::connect() establishes a connection to the memcached server. The connection, which was opened using Memcache::connect() will be automatically closed at the end of script execution. Also you can close it with Memcache::close(). Also you can use memcache_connect() function.

Parametry

host

Point to the host where memcached is listening for connections. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::connect() example

<?php

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);

/* OO API */

$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);

?>

Zobacz też:

  • Memcache::pconnect() - Open memcached server persistent connection
  • Memcache::close() - Close memcached server connection

Memcache::close
Memcache::decrement
Memcache


Decrement item's value

Memcache::connect
Memcache::delete
Memcache
PHP Manual

Memcache::decrement

(PECL memcache >= 0.2.0)

Memcache::decrement — Decrement item's value

Opis

int Memcache::decrement ( string $key [, int $value = 1 ] )

Memcache::decrement() decrements value of the item by value. Similarly to Memcache::increment(), current value of the item is being converted to numerical and after that value is substracted.

Informacja:

New item's value will not be less than zero.

Informacja:

Do not use Memcache::decrement() with item, which was stored compressed, because consequent call to Memcache::get() will fail.

Memcache::decrement() does not create an item if it didn't exist. Also you can use memcache_decrement() function.

Parametry

key

Key of the item do decrement.

value

Decrement the item by value.

Zwracane wartości

Returns item's new value on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Memcache::decrement() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* decrement item by 2 */
$new_value = memcache_decrement($memcache_obj, 'test_item', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* decrement item by 3 */
$new_value = $memcache_obj->decrement('test_item', 3);
?>

Zobacz też:

  • Memcache::increment() - Increment item's value
  • Memcache::replace() - Replace value of the existing item

Memcache::connect
Memcache::delete
Memcache


Delete item from the server

Memcache::decrement
Memcache::flush
Memcache
PHP Manual

Memcache::delete

(PECL memcache >= 0.2.0)

Memcache::delete — Delete item from the server

Opis

bool Memcache::delete ( string $key [, int $timeout = 0 ] )

Memcache::delete() deletes an item with the key.

Parametry

key

The key associated with the item to delete.

timeout

This deprecated parameter is not supported, and defaults to 0 seconds. Do not use this parameter.

Rejestr zmian

Wersja | Opis
Unknown | It's not recommended to use the timeout parameter. The behavior differs between memcached versions, but setting to 0 is safe. Other values for this deprecated feature may cause the memcache delete to fail.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::delete() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

/* item will be deleted by the server */
memcache_delete($memcache_obj, 'key_to_delete');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->delete('key_to_delete');

?>

Zobacz też:

  • Memcache::set() - Store data at the server
  • Memcache::replace() - Replace value of the existing item

Memcache::decrement
Memcache::flush
Memcache


Flush all existing items at the server

Memcache::delete
Memcache::get
Memcache
PHP Manual

Memcache::flush

(PECL memcache >= 1.0.0)

Memcache::flush — Flush all existing items at the server

Opis

bool Memcache::flush ( void )

Memcache::flush() immediately invalidates all existing items. Memcache::flush() doesn't actually free any resources, it only marks all the items as expired, so occupied memory will be overwritten by new items. Also you can use memcache_flush() function.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::flush() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

memcache_flush($memcache_obj);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->flush();

?>

Memcache::delete
Memcache::get
Memcache


Retrieve item from the server

Memcache::flush
Memcache::getExtendedStats
Memcache
PHP Manual

Memcache::get

(PECL memcache >= 0.2.0)

Memcache::get — Retrieve item from the server

Opis

string Memcache::get ( string $key [, int &$flags ] )
array Memcache::get ( array $keys [, array &$flags ] )

Memcache::get() returns previously stored data if an item with such key exists on the server at this moment.

You can pass array of keys to Memcache::get() to get array of values. The result array will contain only found key-value pairs.

Parametry

key

The key or array of keys to fetch.

flags

If present, flags fetched along with the values will be written to this parameter. These flags are the same as the ones given to for example Memcache::set(). The lowest byte of the int is reserved for pecl/memcache internal usage (e.g. to indicate compression and serialization status).

Zwracane wartości

Returns the string associated with the key or FALSE on failure or if such key was not found.

Przykłady

Przykład #1 Memcache::get() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, 'some_key');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get('some_key');

/*
You also can use array of keys as a parameter.
If such item wasn't found at the server, the result
array simply will not include such key.
*/

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, Array('some_key', 'another_key'));

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get(Array('some_key', 'second_key'));

?>

Memcache::flush
Memcache::getExtendedStats
Memcache


Get statistics from all servers in pool

Memcache::get
Memcache::getServerStatus
Memcache
PHP Manual

Memcache::getExtendedStats

(PECL memcache >= 2.0.0)

Memcache::getExtendedStats — Get statistics from all servers in pool

Opis

array Memcache::getExtendedStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )

Memcache::getExtendedStats() returns a two-dimensional associative array with server statistics. Array keys correspond to host:port of server and values contain the individual server statistics. A failed server will have its corresponding entry set to FALSE. You can also use the memcache_get_extended_stats() function.

Informacja:

This function has been added to Memcache version 2.0.0.

Parametry

type

The type of statistics to fetch. Valid values are {reset, malloc, maps, cachedump, slabs, items, sizes}. According to the memcached protocol spec these additional arguments "are subject to change for the convenience of memcache developers".

slabid

Used in conjunction with type set to cachedump to identify the slab to dump from. The cachedump command ties up the server and is strictly to be used for debugging purposes.

limit

Used in conjunction with type set to cachedump to limit the number of entries to dump.

Ostrzeżenie

The cachedump stat type has been removed from the memcached daemon due to security reasons.

Zwracane wartości

Returns a two-dimensional associative array of server statistics or FALSE on failure.

Przykłady

Przykład #1 Memcache::getExtendedStats() example

<?php
    $memcache_obj = new Memcache;
    $memcache_obj->addServer('memcache_host', 11211);
    $memcache_obj->addServer('failed_host', 11211);

    $stats = $memcache_obj->getExtendedStats();
    print_r($stats);
?>

Powyższy przykład wyświetli:

Array
(
    [memcache_host:11211] => Array
        (
            [pid] => 3756
            [uptime] => 603011
            [time] => 1133810435
            [version] => 1.1.12
            [rusage_user] => 0.451931
            [rusage_system] => 0.634903
            [curr_items] => 2483
            [total_items] => 3079
            [bytes] => 2718136
            [curr_connections] => 2
            [total_connections] => 807
            [connection_structures] => 13
            [cmd_get] => 9748
            [cmd_set] => 3096
            [get_hits] => 5976
            [get_misses] => 3772
            [bytes_read] => 3448968
            [bytes_written] => 2318883
            [limit_maxbytes] => 33554432
        )

    [failed_host:11211] => false
)

Zobacz też:

  • Memcache::getVersion() - Return version of the server
  • Memcache::getStats() - Get statistics of the server

Memcache::get
Memcache::getServerStatus
Memcache


Returns server status

Memcache::getExtendedStats
Memcache::getStats
Memcache
PHP Manual

Memcache::getServerStatus

(PECL memcache >= 2.1.0)

Memcache::getServerStatus — Returns server status

Opis

int Memcache::getServerStatus ( string $host [, int $port = 11211 ] )

Memcache::getServerStatus() returns a the servers online/offline status. You can also use memcache_get_server_status() function.

Informacja:

This function has been added to Memcache version 2.1.0.

Parametry

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections.

Zwracane wartości

Returns a the servers status. 0 if server is failed, non-zero otherwise

Przykłady

Przykład #1 Memcache::getServerStatus() example

<?php

/* OO API */
$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
echo $memcache->getServerStatus('memcache_host', 11211);

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_server_status($memcache, 'memcache_host', 11211);

?>

Zobacz też:

  • Memcache::addServer() - Add a memcached server to connection pool
  • Memcache::setServerParams() - Changes server parameters and status at runtime

Memcache::getExtendedStats
Memcache::getStats
Memcache


Get statistics of the server

Memcache::getServerStatus
Memcache::getVersion
Memcache
PHP Manual

Memcache::getStats

(PECL memcache >= 0.2.0)

Memcache::getStats — Get statistics of the server

Opis

array Memcache::getStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )

Memcache::getStats() returns an associative array with server's statistics. Array keys correspond to stats parameters and values to parameter's values. Also you can use memcache_get_stats() function.

Parametry

type

The type of statistics to fetch. Valid values are {reset, malloc, maps, cachedump, slabs, items, sizes}. According to the memcached protocol spec these additional arguments "are subject to change for the convenience of memcache developers".

slabid

Used in conjunction with type set to cachedump to identify the slab to dump from. The cachedump command ties up the server and is strictly to be used for debugging purposes.

limit

Used in conjunction with type set to cachedump to limit the number of entries to dump.

Zwracane wartości

Returns an associative array of server statistics lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • Memcache::getVersion() - Return version of the server
  • Memcache::getExtendedStats() - Get statistics from all servers in pool

Memcache::getServerStatus
Memcache::getVersion
Memcache


Return version of the server

Memcache::getStats
Memcache::increment
Memcache
PHP Manual

Memcache::getVersion

(PECL memcache >= 0.2.0)

Memcache::getVersion — Return version of the server

Opis

string Memcache::getVersion ( void )

Memcache::getVersion() returns a string with server's version number. Also you can use memcache_get_version() function.

Zwracane wartości

Returns a string of server version number lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Memcache::getVersion() example

<?php

/* OO API */
$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
echo $memcache->getVersion();

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_version($memcache);

?>

Zobacz też:

  • Memcache::getExtendedStats() - Get statistics from all servers in pool
  • Memcache::getStats() - Get statistics of the server

Memcache::getStats
Memcache::increment
Memcache


Increment item's value

Memcache::getVersion
Memcache::pconnect
Memcache
PHP Manual

Memcache::increment

(PECL memcache >= 0.2.0)

Memcache::increment — Increment item's value

Opis

int Memcache::increment ( string $key [, int $value = 1 ] )

Memcache::increment() increments value of an item by the specified value. If item specified by key was not numeric and cannot be converted to a number, it will change its value to value. Memcache::increment() does not create an item if it doesn't already exist.

Informacja:

Do not use Memcache::increment() with items that have been stored compressed because subsequent calls to Memcache::get() will fail.

Also you can use memcache_increment() function.

Parametry

key

Key of the item to increment.

value

Increment the item by value.

Zwracane wartości

Returns new items value on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Memcache::increment() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* increment counter by 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* increment counter by 3 */
$current_value = $memcache_obj->increment('counter', 3);

?>

Zobacz też:

  • Memcache::decrement() - Decrement item's value
  • Memcache::replace() - Replace value of the existing item

Memcache::getVersion
Memcache::pconnect
Memcache


Open memcached server persistent connection

Memcache::increment
Memcache::replace
Memcache
PHP Manual

Memcache::pconnect

(PECL memcache >= 0.4.0)

Memcache::pconnect — Open memcached server persistent connection

Opis

mixed Memcache::pconnect ( string $host [, int $port [, int $timeout ]] )

Memcache::pconnect() is similar to Memcache::connect() with the difference, that the connection it establishes is persistent. This connection is not closed after the end of script execution and by Memcache::close() function. Also you can use memcache_pconnect() function.

Parametry

host

Point to the host where memcached is listening for connections. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

Zwracane wartości

Returns a Memcache object lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Memcache::pconnect() example

<?php

/* procedural API */
$memcache_obj = memcache_pconnect('memcache_host', 11211);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->pconnect('memcache_host', 11211);

?>

Zobacz też:

  • Memcache::connect() - Open memcached server connection

Memcache::increment
Memcache::replace
Memcache


Replace value of the existing item

Memcache::pconnect
Memcache::set
Memcache
PHP Manual

Memcache::replace

(PECL memcache >= 0.2.0)

Memcache::replace — Replace value of the existing item

Opis

bool Memcache::replace ( string $key , mixed $var [, int $flag [, int $expire ]] )

Memcache::replace() should be used to replace value of
existing item with key. In case if item with such
key doesn't exists, Memcache::replace() returns
FALSE. For the rest Memcache::replace() behaves
similarly to Memcache::set().
Also you can use memcache_replace() function.

Parametry

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::replace() example

<?php

$memcache_obj = memcache_connect('memcache_host', 11211);

/* procedural API */
memcache_replace($memcache_obj, "test_key", "some variable", false, 30);

/* OO API */
$memcache_obj->replace("test_key", "some variable", false, 30);

?>

Zobacz też:

  • Memcache::set() - Store data at the server
  • Memcache::add() - Add an item to the server

Memcache::pconnect
Memcache::set
Memcache


Store data at the server

Memcache::replace
Memcache::setCompressThreshold
Memcache
PHP Manual

Memcache::set

(PECL memcache >= 0.2.0)

Memcache::set — Store data at the server

Opis

bool Memcache::set ( string $key , mixed $var [, int $flag [, int $expire ]] )

Memcache::set() stores an item var with key on the memcached server. Parameter expire is expiration time in seconds. If it's 0, the item never expires (but memcached server doesn't guarantee this item to be stored all the time, it could be deleted from the cache to make place for other items). You can use MEMCACHE_COMPRESSED constant as flag value if you want to use on-the-fly compression (uses zlib).

Informacja:

Remember that resource variables (i.e. file and connection descriptors) cannot be stored in the cache, because they cannot be adequately represented in serialized state.

Also you can use memcache_set() function.

Parametry

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::set() example

<?php
/* procedural API */

/* connect to memcached server */
$memcache_obj = memcache_connect('memcache_host', 11211);

/*
set value of item with key 'var_key'
using 0 as flag value, compression is not used
expire time is 30 seconds
*/
memcache_set($memcache_obj, 'var_key', 'some variable', 0, 30);

echo memcache_get($memcache_obj, 'var_key');

?>

Przykład #2 Memcache::set() example

<?php
/* OO API */

$memcache_obj = new Memcache;

/* connect to memcached server */
$memcache_obj->connect('memcache_host', 11211);

/*
set value of item with key 'var_key', using on-the-fly compression
expire time is 50 seconds
*/
$memcache_obj->set('var_key', 'some really big variable', MEMCACHE_COMPRESSED, 50);

echo $memcache_obj->get('var_key');

?>

Zobacz też:

  • Memcache::add() - Add an item to the server
  • Memcache::replace() - Replace value of the existing item

Memcache::replace
Memcache::setCompressThreshold
Memcache


Enable automatic compression of large values

Memcache::set
Memcache::setServerParams
Memcache
PHP Manual

Memcache::setCompressThreshold

(PECL memcache >= 2.0.0)

Memcache::setCompressThreshold — Enable automatic compression of large values

Opis

bool Memcache::setCompressThreshold ( int $threshold [, float $min_savings ] )

Memcache::setCompressThreshold() enables automatic compression of large values. You can also use the memcache_set_compress_threshold() function.

Informacja:

This function has been added to Memcache version 2.0.0.

Parametry

threshold

Controls the minimum value length before attempting to compress automatically.

min_saving

Specifies the minimum amount of savings to actually store the value compressed. The supplied value must be between 0 and 1. Default value is 0.2 giving a minimum 20% compression savings.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::setCompressThreshold() example

<?php

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->addServer('memcache_host', 11211);
$memcache_obj->setCompressThreshold(20000, 0.2);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_compress_threshold($memcache_obj, 20000, 0.2);

?>

Memcache::set
Memcache::setServerParams
Memcache


Changes server parameters and status at runtime

Memcache::setCompressThreshold
Memcache Funkcje
Memcache
PHP Manual

Memcache::setServerParams

(PECL memcache >= 2.1.0)

Memcache::setServerParams — Changes server parameters and status at runtime

Opis

bool Memcache::setServerParams ( string $host [, int $port = 11211 [, int $timeout [, int $retry_interval = false [, bool $status [, callback $failure_callback ]]]]] )

Memcache::setServerParams() changes server parameters at runtime. You can also use the memcache_set_server_params() function.

Informacja:

This function has been added to Memcache version 2.1.0.

Parametry

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

retry_interval

Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Neither this nor the persistent parameter has any effect when the extension is loaded dynamically via dl().

status

Controls if the server should be flagged as online. Setting this parameter to FALSE and retry_interval to -1 allows a failed server to be kept in the pool so as not to affect the key distribution algoritm. Requests for this server will then failover or fail immediately depending on the memcache.allow_failover setting. Default to TRUE, meaning the server should be considered online.

failure_callback

Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcache::setServerParams() example

<?php

function _callback_memcache_failure($host, $port) {
    print "memcache '$host:$port' failed";
}

/* OO API */

$memcache = new Memcache;

// Add the server in offline mode
$memcache->addServer('memcache_host', 11211, false, 1, 1, -1, false);

// Bring the server back online
$memcache->setServerParams('memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_server_params($memcache_obj, 'memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

?>

Zobacz też:

  • Memcache::addServer() - Add a memcached server to connection pool
  • Memcache::getServerStatus() - Returns server status

Memcache::setCompressThreshold
Memcache Funkcje
Memcache


Memcache Funkcje

Spis treści

  • memcache_debug — Turn debug output on/off
Memcache::setServerParams
memcache_debug
Memcache


Turn debug output on/off

Memcache Funkcje
Memcached
Memcache Funkcje
PHP Manual

memcache_debug

(PECL memcache >= 0.2.0)

memcache_debug — Turn debug output on/off

Opis

bool memcache_debug ( bool $on_off )

memcache_debug() turns on debug output if parameter on_off is equal to TRUE and turns off if it's FALSE.

Informacja:

memcache_debug() is accessible only if PHP was built with --enable-debug option and always returns TRUE in this case. Otherwise, this function has no effect and always returns FALSE.

Parametry

on_off

Turns debug output on if equals to TRUE. Turns debug output off if equals to FALSE.

Zwracane wartości

Returns TRUE if PHP was built with --enable-debug option, otherwise returns FALSE.

Memcache Funkcje
Memcached
Memcache Funkcje


Memcached

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Expiration Times
  • Callbacks
    • Result callbacks
    • Read-through cache callbacks
  • Sessions support
  • Memcached — The Memcached class
    • Memcached::add — Add an item under a new key
    • Memcached::addByKey — Add an item under a new key on a specific server
    • Memcached::addServer — Add a server to the server pool
    • Memcached::addServers — Add multiple servers to the server pool
    • Memcached::append — Append data to an existing item
    • Memcached::appendByKey — Append data to an existing item on a specific server
    • Memcached::cas — Compare and swap an item
    • Memcached::casByKey — Compare and swap an item on a specific server
    • Memcached::__construct — Create a Memcached instance
    • Memcached::decrement — Decrement numeric item's value
    • Memcached::delete — Delete an item
    • Memcached::deleteByKey — Delete an item from a specific server
    • Memcached::fetch — Fetch the next result
    • Memcached::fetchAll — Fetch all the remaining results
    • Memcached::flush — Invalidate all items in the cache
    • Memcached::get — Retrieve an item
    • Memcached::getByKey — Retrieve an item from a specific server
    • Memcached::getDelayed — Request multiple items
    • Memcached::getDelayedByKey — Request multiple items from a specific server
    • Memcached::getMulti — Retrieve multiple items
    • Memcached::getMultiByKey — Retrieve multiple items from a specific server
    • Memcached::getOption — Retrieve a Memcached option value
    • Memcached::getResultCode — Return the result code of the last operation
    • Memcached::getResultMessage — Return the message describing the result of the last operation
    • Memcached::getServerByKey — Map a key to a server
    • Memcached::getServerList — Get the list of the servers in the pool
    • Memcached::getStats — Get server pool statistics
    • Memcached::getVersion — Get server pool version info
    • Memcached::increment — Increment numeric item's value
    • Memcached::prepend — Prepend data to an existing item
    • Memcached::prependByKey — Prepend data to an existing item on a specific server
    • Memcached::replace — Replace the item under an existing key
    • Memcached::replaceByKey — Replace the item under an existing key on a specific server
    • Memcached::set — Store an item
    • Memcached::setByKey — Store an item on a specific server
    • Memcached::setMulti — Store multiple items
    • Memcached::setMultiByKey — Store multiple items on a specific server
    • Memcached::setOption — Set a Memcached option
memcache_debug
Wstęp
Inne serwisy


Wstęp

» memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://libmemcached.org/libMemcached.html.

Memcached
Instalacja/Konfiguracja
Memcached


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Memcached


Wymagania

This extension requires » libmemcached client library.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/memcached.

If libmemcached is installed in a non-standard location, use --with-libmemcached-dir=DIR switch, where DIR is the libmemcached install prefix. This directory has to contain the include/libmemcached/memcached.h file.

Zlib is required for compression support. To specify non-standard installation of Zlib, use --with-zlib-dir=DIR switch, where DIR is the Zlib install prefix.

Session handler support is enabled by default. To disable it, use --disable-memcached-session switch.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Memcached::OPT_COMPRESSION

Enables or disables payload compression. When enabled, item values longer than a certain threshold (currently 100 bytes) will be compressed during storage and decompressed during retrieval transparently.

Type: boolean, default: TRUE.

Memcached::OPT_SERIALIZER

Specifies the serializer to use for serializing non-scalar values. The valid serializers are Memcached::SERIALIZER_PHP or Memcached::SERIALIZER_IGBINARY. The latter is supported only when memcached is configured with --enable-memcached-igbinary option and the igbinary extension is loaded.

Type: integer, default: Memcached::SERIALIZER_PHP.

Memcached::SERIALIZER_PHP

The default PHP serializer.

Memcached::SERIALIZER_IGBINARY

The » igbinary serializer. Instead of textual representation it stores PHP data structures in a compact binary form, resulting in space and time gains.

Memcached::SERIALIZER_JSON

The JSON serializer. Requires PHP 5.2.10+.

Memcached::OPT_PREFIX_KEY

This can be used to create a "domain" for your item keys. The value specified here will be prefixed to each of the keys. It cannot be longer than 128 characters and will reduce the maximum available key size. The prefix is applied only to the item keys, not to the server keys.

Type: string, default: "".

Memcached::OPT_HASH

Specifies the hashing algorithm used for the item keys. The valid values are supplied via Memcached::HASH_* constants. Each hash algorithm has its advantages and its disadvantages. Go with the default if you don't know or don't care.

Type: integer, default: Memcached::HASH_DEFAULT

Memcached::HASH_DEFAULT

The default (Jenkins one-at-a-time) item key hashing algorithm.

Memcached::HASH_MD5

MD5 item key hashing algorithm.

Memcached::HASH_CRC

CRC item key hashing algorithm.

Memcached::HASH_FNV1_64

FNV1_64 item key hashing algorithm.

Memcached::HASH_FNV1A_64

FNV1_64A item key hashing algorithm.

Memcached::HASH_FNV1_32

FNV1_32 item key hashing algorithm.

Memcached::HASH_FNV1A_32

FNV1_32A item key hashing algorithm.

Memcached::HASH_HSIEH

Hsieh item key hashing algorithm.

Memcached::HASH_MURMUR

Murmur item key hashing algorithm.

Memcached::OPT_DISTRIBUTION

Specifies the method of distributing item keys to the servers. Currently supported methods are modulo and consistent hashing. Consistent hashing delivers better distribution and allows servers to be added to the cluster with minimal cache losses.

Type: integer, default: Memcached::DISTRIBUTION_MODULA.

Memcached::DISTRIBUTION_MODULA

Modulo-based key distribution algorithm.

Memcached::DISTRIBUTION_CONSISTENT

Consistent hashing key distribution algorithm (based on libketama).

Memcached::OPT_LIBKETAMA_COMPATIBLE

Enables or disables compatibility with libketama-like behavior. When enabled, the item key hashing algorithm is set to MD5 and distribution is set to be weighted consistent hashing distribution. This is useful because other libketama-based clients (Python, Ruby, etc.) with the same server configuration will be able to access the keys transparently.

Informacja:

It is highly recommended to enable this option if you want to use consistent hashing, and it may be enabled by default in future releases.

Type: boolean, default: FALSE.

Memcached::OPT_BUFFER_WRITES

Enables or disables buffered I/O. Enabling buffered I/O causes storage commands to "buffer" instead of being sent. Any action that retrieves data causes this buffer to be sent to the remote connection. Quitting the connection or closing down the connection will also cause the buffered data to be pushed to the remote connection.

Type: boolean, default: FALSE.

Memcached::OPT_BINARY_PROTOCOL

Enable the use of the binary protocol. Please note that you cannot toggle this option on an open connection.

Type: boolean, default: FALSE.

Memcached::OPT_NO_BLOCK

Enables or disables asynchronous I/O. This is the fastest transport available for storage functions.

Type: boolean, default: FALSE.

Memcached::OPT_TCP_NODELAY

Enables or disables the no-delay feature for connecting sockets (may be faster in some environments).

Type: boolean, default: FALSE.

Memcached::OPT_SOCKET_SEND_SIZE

The maximum socket send buffer in bytes.

Type: integer, default: varies by platform/kernel configuration.

Memcached::OPT_SOCKET_RECV_SIZE

The maximum socket receive buffer in bytes.

Type: integer, default: varies by platform/kernel configuration.

Memcached::OPT_CONNECT_TIMEOUT

In non-blocking mode this set the value of the timeout during socket connection, in milliseconds.

Type: integer, default: 1000.

Memcached::OPT_RETRY_TIMEOUT

The amount of time, in seconds, to wait until retrying a failed connection attempt.

Type: integer, default: 0.

Memcached::OPT_SEND_TIMEOUT

Socket sending timeout, in microseconds. In cases where you cannot use non-blocking I/O this will allow you to still have timeouts on the sending of data.

Type: integer, default: 0.

Memcached::OPT_RECV_TIMEOUT

Socket reading timeout, in microseconds. In cases where you cannot use non-blocking I/O this will allow you to still have timeouts on the reading of data.

Type: integer, default: 0.

Memcached::OPT_POLL_TIMEOUT

Timeout for connection polling, in milliseconds.

Type: integer, default: 1000.

Memcached::OPT_CACHE_LOOKUPS

Enables or disables caching of DNS lookups.

Type: boolean, default: FALSE.

Memcached::OPT_SERVER_FAILURE_LIMIT

Specifies the failure limit for server connection attempts. The server will be removed after this many continuous connection failures.

Type: integer, default: 0.

Memcached::HAVE_IGBINARY

Indicates whether igbinary serializer support is available.

Type: boolean.

Memcached::HAVE_JSON

Indicates whether JSON serializer support is available.

Type: boolean.

Memcached::GET_PRESERVE_ORDER

A flag for Memcached::getMulti() and Memcached::getMultiByKey() to ensure that the keys are returned in the same order as they were requested in. Non-existing keys get a default value of NULL.

Memcached::RES_SUCCESS

The operation was successful.

Memcached::RES_FAILURE

The operation failed in some fashion.

Memcached::RES_HOST_LOOKUP_FAILURE

DNS lookup failed.

Memcached::RES_UNKNOWN_READ_FAILURE

Failed to read network data.

Memcached::RES_PROTOCOL_ERROR

Bad command in memcached protocol.

Memcached::RES_CLIENT_ERROR

Error on the client side.

Memcached::RES_SERVER_ERROR

Error on the server side.

Memcached::RES_WRITE_FAILURE

Failed to write network data.

Memcached::RES_DATA_EXISTS

Failed to do compare-and-swap: item you are trying to store has been modified since you last fetched it.

Memcached::RES_NOTSTORED

Item was not stored: but not because of an error. This normally means that either the condition for an "add" or a "replace" command wasn't met, or that the item is in a delete queue.

Memcached::RES_NOTFOUND

Item with this key was not found (with "get" operation or "cas" operations).

Memcached::RES_PARTIAL_READ

Partial network data read error.

Memcached::RES_SOME_ERRORS

Some errors occurred during multi-get.

Memcached::RES_NO_SERVERS

Server list is empty.

Memcached::RES_END

End of result set.

Memcached::RES_ERRNO

System error.

Memcached::RES_BUFFERED

The operation was buffered.

Memcached::RES_TIMEOUT

The operation timed out.

Memcached::RES_BAD_KEY_PROVIDED

Bad key.

Memcached::RES_CONNECTION_SOCKET_CREATE_FAILURE

Failed to create network socket.

Memcached::RES_PAYLOAD_FAILURE

Payload failure: could not compress/decompress or serialize/unserialize the value.

Typy zasobów
Expiration Times
Memcached


Expiration Times

Some storage commands involve sending an expiration value (relative to an item or to an operation requested by the client) to the server. In all such cases, the actual value sent may either be Unix time (number of seconds since January 1, 1970, as an integer), or a number of seconds starting from current time. In the latter case, this number of seconds may not exceed 60*60*24*30 (number of seconds in 30 days); if the expiration value is larger than that, the server will consider it to be real Unix time value rather than an offset from current time.

If the expiration value is 0 (the default), the item never expires (although it may be deleted from the server to make place for other items).

Stałe predefiniowane
Callbacks
Memcached


Callbacks

Spis treści

  • Result callbacks
  • Read-through cache callbacks
Expiration Times
Result callbacks
Memcached


Result callbacks

Result callbacks are invoked by Memcached::getDelayed() or Memcached::getDelayedBykey() methods for each item in the result set. The callback is passed the Memcached object and the array with the item information. The callback does not have to return anything.

Przykład #1 Result callback example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items);
$m->getDelayed(array('key1', 'key3'), true, 'result_cb');

function result_cb($memc, $item)
{
    var_dump($item);
}
?>

Powyższy przykład wyświetli coś podobnego do:

array(3) {
  ["key"]=>
  string(4) "key1"
  ["value"]=>
  string(6) "value1"
  ["cas"]=>
  float(49)
}
array(3) {
  ["key"]=>
  string(4) "key3"
  ["value"]=>
  string(6) "value3"
  ["cas"]=>
  float(50)
}
Callbacks
Read-through cache callbacks
Callbacks


Read-through cache callbacks

Read-through cache callbacks are invoked when an item cannot be retrieved from the server. The callback is passed the Memcached object, the requested key, and the by-reference value variable. The callback is responsible for setting the value and returning true or false. If the callback returns true, Memcached will store the populated value on the server and return it to the original calling function. Only Memcached::get() and Memcached::getByKey() support these callbacks, because the memcache protocol does not provide information on which keys were not found in the multi-key request.

Przykład #1 Read-through callback example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$profile_info = $m->get('user:'.$user_id, 'user_info_cb');

function user_info_cb($memc, $key, &$value)
{
    $user_id = substr($key, 5);
    /* lookup profile info in the DB */
    /* ... */
    $value = $profile_info;
    return true;
}
?>
Result callbacks
Sessions support
Callbacks


Sessions support

Memcached provides a custom session handler that can be used to store user sessions in memcache. A completely separate memcached instance is used for that internally, so you can use a different server pool if necessary. The session keys are stored under the prefix memc.sess.key., so be aware of this if you use the same server pool for sessions and generic caching.

session.save_handler string

Set to memcached to enable sessions support.

session.save_path string

Defines a comma separated of hostname:port entries to use for session server pool, for example "sess1:11211, sess2:11211".

Read-through cache callbacks
Memcached
Memcached


The Memcached class

(No version information available, might only be in SVN)

Wstęp

Represents a connection to a set of memcached servers.

Krótki opis klasy

Memcached {
public __construct ([ string $persistent_id ] )
public bool add ( string $key , mixed $value [, int $expiration ] )
public bool addByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
public bool addServer ( string $host , int $port [, int $weight = 0 ] )
public bool addServers ( array $servers )
public bool append ( string $key , string $value )
public bool appendByKey ( string $server_key , string $key , string $value )
public bool cas ( float $cas_token , string $key , mixed $value [, int $expiration ] )
public bool casByKey ( float $cas_token , string $server_key , string $key , mixed $value [, int $expiration ] )
public int decrement ( string $key [, int $offset = 1 ] )
public bool delete ( string $key [, int $time = 0 ] )
public bool deleteByKey ( string $server_key , string $key [, int $time = 0 ] )
public array fetch ( void )
public array fetchAll ( void )
public bool flush ([ int $delay = 0 ] )
public mixed get ( string $key [, callback $cache_cb [, float &$cas_token ]] )
public mixed getByKey ( string $server_key , string $key [, callback $cache_cb [, float &$cas_token ]] )
public bool getDelayed ( array $keys [, bool $with_cas [, callback $value_cb ]] )
public bool getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callback $value_cb ]] )
public mixed getMulti ( array $keys [, array &$cas_tokens [, int $flags ]] )
public array getMultiByKey ( string $server_key , array $keys [, string &$cas_tokens [, int $flags ]] )
public mixed getOption ( int $option )
public int getResultCode ( void )
public string getResultMessage ( void )
public array getServerByKey ( string $server_key )
public array getServerList ( void )
public array getStats ( void )
public array getVersion ( void )
public int increment ( string $key [, int $offset = 1 ] )
public bool prepend ( string $key , string $value )
public bool prependByKey ( string $server_key , string $key , string $value )
public bool replace ( string $key , mixed $value [, int $expiration ] )
public bool replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
public bool set ( string $key , mixed $value [, int $expiration ] )
public bool setByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )
public bool setMulti ( array $items [, int $expiration ] )
public bool setMultiByKey ( string $server_key , array $items [, int $expiration ] )
public bool setOption ( int $option , mixed $value )
}

Spis treści

  • Memcached::add — Add an item under a new key
  • Memcached::addByKey — Add an item under a new key on a specific server
  • Memcached::addServer — Add a server to the server pool
  • Memcached::addServers — Add multiple servers to the server pool
  • Memcached::append — Append data to an existing item
  • Memcached::appendByKey — Append data to an existing item on a specific server
  • Memcached::cas — Compare and swap an item
  • Memcached::casByKey — Compare and swap an item on a specific server
  • Memcached::__construct — Create a Memcached instance
  • Memcached::decrement — Decrement numeric item's value
  • Memcached::delete — Delete an item
  • Memcached::deleteByKey — Delete an item from a specific server
  • Memcached::fetch — Fetch the next result
  • Memcached::fetchAll — Fetch all the remaining results
  • Memcached::flush — Invalidate all items in the cache
  • Memcached::get — Retrieve an item
  • Memcached::getByKey — Retrieve an item from a specific server
  • Memcached::getDelayed — Request multiple items
  • Memcached::getDelayedByKey — Request multiple items from a specific server
  • Memcached::getMulti — Retrieve multiple items
  • Memcached::getMultiByKey — Retrieve multiple items from a specific server
  • Memcached::getOption — Retrieve a Memcached option value
  • Memcached::getResultCode — Return the result code of the last operation
  • Memcached::getResultMessage — Return the message describing the result of the last operation
  • Memcached::getServerByKey — Map a key to a server
  • Memcached::getServerList — Get the list of the servers in the pool
  • Memcached::getStats — Get server pool statistics
  • Memcached::getVersion — Get server pool version info
  • Memcached::increment — Increment numeric item's value
  • Memcached::prepend — Prepend data to an existing item
  • Memcached::prependByKey — Prepend data to an existing item on a specific server
  • Memcached::replace — Replace the item under an existing key
  • Memcached::replaceByKey — Replace the item under an existing key on a specific server
  • Memcached::set — Store an item
  • Memcached::setByKey — Store an item on a specific server
  • Memcached::setMulti — Store multiple items
  • Memcached::setMultiByKey — Store multiple items on a specific server
  • Memcached::setOption — Set a Memcached option
Sessions support
Memcached::add
Memcached


Add an item under a new key

Memcached
Memcached::addByKey
Memcached
PHP Manual

Memcached::add

(PECL memcached >= 0.1.0)

Memcached::add — Add an item under a new key

Opis

public bool Memcached::add ( string $key , mixed $value [, int $expiration ] )

Memcached::add() is similar to Memcached::set(), but the operation fails if the key already exists on the server.

Parametry

key

Klucz określający przechowywaną wartość.

value

Wartość do przechowania.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key already exists.

Zobacz też:

  • Memcached::addByKey() - Add an item under a new key on a specific server
  • Memcached::set() - Store an item
  • Memcached::replace() - Replace the item under an existing key

Memcached
Memcached::addByKey
Memcached


Add an item under a new key on a specific server

Memcached::add
Memcached::addServer
Memcached
PHP Manual

Memcached::addByKey

(PECL memcached >= 0.1.0)

Memcached::addByKey — Add an item under a new key on a specific server

Opis

public bool Memcached::addByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )

Memcached::addByKey() is functionally equivalent to Memcached::add(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

key

Klucz określający przechowywaną wartość.

value

Wartość do przechowania.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key already exists.

Zobacz też:

  • Memcached::add() - Add an item under a new key
  • Memcached::set() - Store an item
  • Memcached::replace() - Replace the item under an existing key

Memcached::add
Memcached::addServer
Memcached


Add a server to the server pool

Memcached::addByKey
Memcached::addServers
Memcached
PHP Manual

Memcached::addServer

(PECL memcached >= 0.1.0)

Memcached::addServer — Add a server to the server pool

Opis

public bool Memcached::addServer ( string $host , int $port [, int $weight = 0 ] )

Memcached::addServer() adds the specified server to the server pool. No connection is established to the server at this time, but if you are using consistent key distribution option (via Memcached::DISTRIBUTION_CONSISTENT or Memcached::OPT_LIBKETAMA_COMPATIBLE), some of the internal data structures will have to be updated. Thus, if you need to add multiple servers, it is better to use Memcached::addServers() as the update then happens only once.

The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

Parametry

host

The hostname of the memcache server. If the hostname is invalid, data-related operations will set Memcached::RES_HOST_LOOKUP_FAILURE result code.

port

The port on which memcache is running. Usually, this is 11211.

weight

The weight of the server relative to the total weight of all the servers in the pool. This controls the probability of the server being selected for operations. This is used only with consistent distribution option and usually corresponds to the amount of memory available to memcache on that server.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcached::addServer() example

<?php
$m = new Memcached();

/* Add 2 servers, so that the second one
   is twice as likely to be selected. */
$m->addServer('mem1.domain.com', 11211, 33);
$m->addServer('mem2.domain.com', 11211, 67);
?>

Zobacz też:

  • Memcached::addServers() - Add multiple servers to the server pool

Memcached::addByKey
Memcached::addServers
Memcached


Add multiple servers to the server pool

Memcached::addServer
Memcached::append
Memcached
PHP Manual

Memcached::addServers

(PECL memcached >= 0.1.1)

Memcached::addServers — Add multiple servers to the server pool

Opis

public bool Memcached::addServers ( array $servers )

Memcached::addServers() adds servers to the server pool. Each entry in servers is supposed to be an array containing hostname, port, and, optionally, weight of the server. No connection is established to the servers at this time.

The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

Parametry

array

Array of the servers to add to the pool.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Memcached::addServers() example

<?php
$m = new Memcached();

$servers = array(
    array('mem1.domain.com', 11211, 33),
    array('mem2.domain.com', 11211, 67)
);
$m->addServers($servers);
?>

Zobacz też:

  • Memcached::addServer() - Add a server to the server pool

Memcached::addServer
Memcached::append
Memcached


Append data to an existing item

Memcached::addServers
Memcached::appendByKey
Memcached
PHP Manual

Memcached::append

(PECL memcached >= 0.1.0)

Memcached::append — Append data to an existing item

Opis

public bool Memcached::append ( string $key , string $value )

Memcached::append() appends the given value string to the value of an existing item. The reason that value is forced to be a string is that appending mixed types is not well-defined.

Informacja:

If the Memcached::OPT_COMPRESSION is enabled, the operation will fail and a warning will be issued, because appending compressed data to a value that is potentially already compressed is not possible.

Parametry

key

Klucz określający przechowywaną wartość.

value

The string to append.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Przykłady

Przykład #1 Memcached::append() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);

$m->set('foo', 'abc');
$m->append('foo', 'def');
var_dump($m->get('foo'));
?>

Powyższy przykład wyświetli:

string(6) "abcdef"

Zobacz też:

  • Memcached::appendByKey() - Append data to an existing item on a specific server
  • Memcached::prepend() - Prepend data to an existing item

Memcached::addServers
Memcached::appendByKey
Memcached


Append data to an existing item on a specific server

Memcached::append
Memcached::cas
Memcached
PHP Manual

Memcached::appendByKey

(PECL memcached >= 0.1.0)

Memcached::appendByKey — Append data to an existing item on a specific server

Opis

public bool Memcached::appendByKey ( string $server_key , string $key , string $value )

Memcached::appendByKey() is functionally equivalent to Memcached::append(), except that the free-form server_key can be used to map the key to a specific server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

key

Klucz określający przechowywaną wartość.

value

The string to append.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Zobacz też:

  • Memcached::append() - Append data to an existing item
  • Memcached::prepend() - Prepend data to an existing item

Memcached::append
Memcached::cas
Memcached


Compare and swap an item

Memcached::appendByKey
Memcached::casByKey
Memcached
PHP Manual

Memcached::cas

(PECL memcached >= 0.1.0)

Memcached::cas — Compare and swap an item

Opis

public bool Memcached::cas ( float $cas_token , string $key , mixed $value [, int $expiration ] )

Memcached::cas() performs a "check and set" operation, so that the item will be stored only if no other client has updated it since it was last fetched by this client. The check is done via the cas_token parameter which is a unique 64-bit value assigned to the existing item by memcache. See the documentation for Memcached::get*() methods for how to obtain this token. Note that the token is represented as a double due to the limitations of PHP's integer space.

Parametry

cas_token

Unique value associated with the existing item. Generated by memcache.

key

Klucz określający przechowywaną wartość.

value

Wartość do przechowania.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_DATA_EXISTS if the item you are trying to store has been modified since you last fetched it.

Przykłady

Przykład #1 Memcached::cas() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

do {
    /* fetch IP list and its token */
    $ips = $m->get('ip_block', null, $cas);
    /* if list doesn't exist yet, create it and do
       an atomic add which will fail if someone else already added it */
    if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
        $ips = array($_SERVER['REMOTE_ADDR']);
        $m->add('ip_block', $ips);
    /* otherwise, add IP to the list and store via compare-and-swap
       with the token, which will fail if someone else updated the list */
    } else {
        $ips[] = $_SERVER['REMOTE_ADDR'];
        $m->cas($cas, 'ip_block', $ips);
    }
} while ($m->getResultCode() != Memcached::RES_SUCCESS);

?>

Zobacz też:

  • Memcached::casByKey() - Compare and swap an item on a specific server

Memcached::appendByKey
Memcached::casByKey
Memcached


Compare and swap an item on a specific server

Memcached::cas
Memcached::__construct
Memcached
PHP Manual

Memcached::casByKey

(PECL memcached >= 0.1.0)

Memcached::casByKey — Compare and swap an item on a specific server

Opis

public bool Memcached::casByKey ( float $cas_token , string $server_key , string $key , mixed $value [, int $expiration ] )

Memcached::casByKey() is functionally equivalent to Memcached::cas(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parametry

cas_token

Unique value associated with the existing item. Generated by memcache.

server_key

Klucz identyfikujący serwer do przechowywania wartości.

key

Klucz określający przechowywaną wartość.

value

Wartość do przechowania.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_DATA_EXISTS if the item you are trying to store has been modified since you last fetched it.

Zobacz też:

  • Memcached::cas() - Compare and swap an item

Memcached::cas
Memcached::__construct
Memcached


Create a Memcached instance

Memcached::casByKey
Memcached::decrement
Memcached
PHP Manual

Memcached::__construct

(PECL memcached >= 0.1.0)

Memcached::__construct — Create a Memcached instance

Opis

public Memcached::__construct() ([ string $persistent_id ] )

Creates a Memcached instance representing the connection to the memcache servers.

Parametry

persistent_id

By default the Memcached instances are destroyed at the end of the request. To create an instance that persists between requests, use persistent_id to specify a unique ID for the instance. All instances created with the same persistent_id will share the same connection.

Zwracane wartości

A Memcached object.

Przykłady

Przykład #1 Creating a Memcached object

<?php
/* Create a regular instance */
$m = new Memcached();
echo get_class($m);

/* Create a persistent instance */
$m2 = new Memcached('story_pool');
$m3 = new Memcached('story_pool');

/* now $m2 and $m3 share the same connection */
?>

Memcached::casByKey
Memcached::decrement
Memcached


Decrement numeric item's value

Memcached::__construct
Memcached::delete
Memcached
PHP Manual

Memcached::decrement

(PECL memcached >= 0.1.0)

Memcached::decrement — Decrement numeric item's value

Opis

public int Memcached::decrement ( string $key [, int $offset = 1 ] )

Memcached::decrement() decrements a numeric item's value by the specified offset. If the item's value is not numeric, it is treated as if the value were 0. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrement() will fail if the item does not exist.

Parametry

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

Zwracane wartości

Returns item's new value on success lub FALSE w przypadku niepowodzenia. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Przykłady

Przykład #1 Memcached::decrement() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 5);
$m->decrement('counter');
var_dump($m->get('counter'));

$m->decrement('counter', 10);
var_dump($m->get('counter'));
?>

Powyższy przykład wyświetli:

int(4)
int(0)

Zobacz też:

  • Memcached::increment() - Increment numeric item's value

Memcached::__construct
Memcached::delete
Memcached


Delete an item

Memcached::decrement
Memcached::deleteByKey
Memcached
PHP Manual

Memcached::delete

(PECL memcached >= 0.1.0)

Memcached::delete — Delete an item

Opis

public bool Memcached::delete ( string $key [, int $time = 0 ] )

Memcached::delete() deletes the key from the server. The time parameter is the amount of time in seconds (or Unix time until which) the client wishes the server to refuse add and replace commands for this key. For this amount of time, the item is put into a delete queue, which means that it won't possible to retrieve it by the get command, but add and replace command with this key will also fail (the set command will succeed, however). After the time passes, the item is finally deleted from server memory. The parameter time defaults to 0 (which means that the item will be deleted immediately and further storage commands with this key will succeed).

Parametry

key

The key to be deleted.

time

The amount of time the server will wait to delete the item.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Przykłady

Przykład #1 Memcached::delete() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->delete('key1');
?>

Zobacz też:

  • Memcached::deleteByKey() - Delete an item from a specific server

Memcached::decrement
Memcached::deleteByKey
Memcached


Delete an item from a specific server

Memcached::delete
Memcached::fetch
Memcached
PHP Manual

Memcached::deleteByKey

(PECL memcached >= 0.1.0)

Memcached::deleteByKey — Delete an item from a specific server

Opis

public bool Memcached::deleteByKey ( string $server_key , string $key [, int $time = 0 ] )

Memcached::deleteByKey() is functionally equivalent to Memcached::delete(), except that the free-form server_key can be used to map the key to a specific server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

key

The key to be deleted.

time

The amount of time the server will wait to delete the item.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Zobacz też:

  • Memcached::delete() - Delete an item

Memcached::delete
Memcached::fetch
Memcached


Fetch the next result

Memcached::deleteByKey
Memcached::fetchAll
Memcached
PHP Manual

Memcached::fetch

(PECL memcached >= 0.1.0)

Memcached::fetch — Fetch the next result

Opis

public array Memcached::fetch ( void )

Memcached::fetch() retrieves the next result from the last request.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the next result or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_END if result set is exhausted.

Przykłady

Przykład #1 Memcached::fetch() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
while ($result = $m->fetch()) {
    var_dump($result);
}
?>

Powyższy przykład wyświetli coś podobnego do:

array(3) {
  ["key"]=>
  string(3) "int"
  "value"]=>
  int(99)
  ["cas"]=>
  float(2363)
}
array(3) {
  ["key"]=>
  string(5) "array"
  ["value"]=>
  array(2) {
    [0]=>
    int(11)
    [1]=>
    int(12)
  }
  ["cas"]=>
  float(2365)
}

Zobacz też:

  • Memcached::fetchAll() - Fetch all the remaining results
  • Memcached::getDelayed() - Request multiple items

Memcached::deleteByKey
Memcached::fetchAll
Memcached


Fetch all the remaining results

Memcached::fetch
Memcached::flush
Memcached
PHP Manual

Memcached::fetchAll

(PECL memcached >= 0.1.0)

Memcached::fetchAll — Fetch all the remaining results

Opis

public array Memcached::fetchAll ( void )

Memcached::fetchAll() retrieves all the remaining results from the last request.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the results lub FALSE w przypadku niepowodzenia. Użyj Memcached::getResultCode(), jeśli to konieczne.

Przykłady

Przykład #1 Memcached::getDelayed() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
var_dump($m->fetchAll());
?>

Powyższy przykład wyświetli:

array(2) {
  [0]=>
  array(3) {
    ["key"]=>
    string(3) "int"
    ["value"]=>
    int(99)
    ["cas"]=>
    float(2363)
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(5) "array"
    ["value"]=>
    array(2) {
      [0]=>
      int(11)
      [1]=>
      int(12)
    }
    ["cas"]=>
    float(2365)
  }
}

Zobacz też:

  • Memcached::fetch() - Fetch the next result
  • Memcached::getDelayed() - Request multiple items

Memcached::fetch
Memcached::flush
Memcached


Invalidate all items in the cache

Memcached::fetchAll
Memcached::get
Memcached
PHP Manual

Memcached::flush

(PECL memcached >= 0.1.0)

Memcached::flush — Invalidate all items in the cache

Opis

public bool Memcached::flush ([ int $delay = 0 ] )

Memcached::flush() invalidates all existing cache items immediately (by default) or after the delay specified. After invalidation none of the items will be returned in response to a retrieval command (unless it's stored again under the same key after Memcached::flush() has invalidated the items). The flush does not actually free all the memory taken up by the existing items; that will happen gradually as new items are stored.

Parametry

delay

Numer of seconds to wait before invalidating the items.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Użyj Memcached::getResultCode(), jeśli to konieczne.

Przykłady

Przykład #1 Memcached::flush() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

/* flush all items in 10 seconds */
$m->flush(10);
?>

Memcached::fetchAll
Memcached::get
Memcached


Retrieve an item

Memcached::flush
Memcached::getByKey
Memcached
PHP Manual

Memcached::get

(PECL memcached >= 0.1.0)

Memcached::get — Retrieve an item

Opis

public mixed Memcached::get ( string $key [, callback $cache_cb [, float &$cas_token ]] )

Memcached::get() returns the item that was previously stored under the key. If the item is found and cas_token variable is provided, it will contain the CAS token value for the item. See Memcached::cas() for how to use CAS tokens. Read-through caching callback may be specified via cache_cb parameter.

Parametry

key

The key of the item to retrieve.

cache_cb

Read-through caching callback or NULL.

cas_token

The variable to store the CAS token in.

Zwracane wartości

Returns the value stored in the cache or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Przykłady

Przykład #1 Memcached::get() example #1

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('foo', 100);
var_dump($m->get('foo'));
?>

Powyższy przykład wyświetli:

int(100)

Przykład #2 Memcached::get() example #2

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

if (!($ip = $m->get('ip_block'))) {
    if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
        $ip = array();
        $m->set('ip_block', $ip);
    } else {
        /* log error */
        /* ...       */
    }
}
?>

Zobacz też:

  • Memcached::getByKey() - Retrieve an item from a specific server
  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::getDelayed() - Request multiple items

Memcached::flush
Memcached::getByKey
Memcached


Retrieve an item from a specific server

Memcached::get
Memcached::getDelayed
Memcached
PHP Manual

Memcached::getByKey

(PECL memcached >= 0.1.0)

Memcached::getByKey — Retrieve an item from a specific server

Opis

public mixed Memcached::getByKey ( string $server_key , string $key [, callback $cache_cb [, float &$cas_token ]] )

Memcached::getByKey() is functionally equivalent to Memcached::get(), except that the free-form server_key can be used to map the key to a specific server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

key

The key of the item to fetch.

cache_cb

Read-through caching callback or NULL

cas_token

The variable to store the CAS token in.

Zwracane wartości

Returns the value stored in the cache or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Zobacz też:

  • Memcached::get() - Retrieve an item
  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::getDelayed() - Request multiple items

Memcached::get
Memcached::getDelayed
Memcached


Request multiple items

Memcached::getByKey
Memcached::getDelayedByKey
Memcached
PHP Manual

Memcached::getDelayed

(PECL memcached >= 0.1.0)

Memcached::getDelayed — Request multiple items

Opis

public bool Memcached::getDelayed ( array $keys [, bool $with_cas [, callback $value_cb ]] )

Memcached::getDelayed() issues a request to memcache for multiple items the keys of which are specified in the keys array. The method does not wait for response and returns right away. When you are ready to collect the items, call either Memcached::fetch() or Memcached::fetchAll(). If with_cas is true, the CAS token values will also be requested.

Instead of fetching the results explicitly, you can specify a result callback via value_cb parameter.

Parametry

keys

Array of keys to request.

with_cas

Whether to request CAS token values also.

value_cb

The result callback or NULL.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Użyj Memcached::getResultCode(), jeśli to konieczne.

Przykłady

Przykład #1 Memcached::getDelayed() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
var_dump($m->fetchAll());
?>

Powyższy przykład wyświetli:

array(2) {
  [0]=>
  array(3) {
    ["key"]=>
    string(3) "int"
    ["value"]=>
    int(99)
    ["cas"]=>
    float(2363)
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(5) "array"
    ["value"]=>
    array(2) {
      [0]=>
      int(11)
      [1]=>
      int(12)
    }
    ["cas"]=>
    float(2365)
  }
}

Zobacz też:

  • Memcached::getDelayedByKey() - Request multiple items from a specific server
  • Memcached::fetch() - Fetch the next result
  • Memcached::fetchAll() - Fetch all the remaining results

Memcached::getByKey
Memcached::getDelayedByKey
Memcached


Request multiple items from a specific server

Memcached::getDelayed
Memcached::getMulti
Memcached
PHP Manual

Memcached::getDelayedByKey

(PECL memcached >= 0.1.0)

Memcached::getDelayedByKey — Request multiple items from a specific server

Opis

public bool Memcached::getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callback $value_cb ]] )

Memcached::getDelayedByKey() is functionally equivalent to Memcached::getDelayed(), except that the free-form server_key can be used to map the keys to a specific server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

keys

Array of keys to request.

with_cas

Whether to request CAS token values also.

value_cb

The result callback or NULL.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Użyj Memcached::getResultCode(), jeśli to konieczne.

Zobacz też:

  • Memcached::getDelayed() - Request multiple items
  • Memcached::fetch() - Fetch the next result
  • Memcached::fetchAll() - Fetch all the remaining results

Memcached::getDelayed
Memcached::getMulti
Memcached


Retrieve multiple items

Memcached::getDelayedByKey
Memcached::getMultiByKey
Memcached
PHP Manual

Memcached::getMulti

(PECL memcached >= 0.1.0)

Memcached::getMulti — Retrieve multiple items

Opis

public mixed Memcached::getMulti ( array $keys [, array &$cas_tokens [, int $flags ]] )

Memcached::getMulti() is similar to Memcached::get(), but instead of a single key item, it retrieves multiple items the keys of which are specified in the keys array. If cas_tokens variable is provided, it is filled with the CAS token values for the found items.

Informacja:

Unlike Memcached::get() it is not possible to specify a read-through cache callback for Memcached::getMulti(), because the memcache protocol does not provide information on which keys were not found in the multi-key request.

The flags parameter can be used to specify additional options for Memcached::getMulti(). Currently, the only available option is Memcached::GET_PRESERVE_ORDER that ensures that the keys are returned in the same order as they were requested in.

Parametry

keys

Array of keys to retrieve.

cas_tokens

The variable to store the CAS tokens for the found items.

flags

The flags for the get operation.

Zwracane wartości

Returns the array of found items lub FALSE w przypadku niepowodzenia. Użyj Memcached::getResultCode(), jeśli to konieczne.

Przykłady

Przykład #1 Memcached::getMulti() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items);
$result = $m->getMulti(array('key1', 'key3', 'badkey'), $cas);
var_dump($result, $cas);
?>

Powyższy przykład wyświetli coś podobnego do:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key3"]=>
  string(6) "value3"
}
array(2) {
  ["key1"]=>
  float(2360)
  ["key3"]=>
  float(2362)
}

Przykład #2 Memcached::GET_PRESERVE_ORDER example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$data = array(
    'foo' => 'foo-data',
    'bar' => 'bar-data',
    'baz' => 'baz-data',
    'lol' => 'lol-data',
    'kek' => 'kek-data',
);

$m->setMulti($data, 3600);

$null = null;
$keys = array_keys($data);
$keys[] = 'zoo';
$got = $m->getMulti($keys, $null, Memcached::GET_PRESERVE_ORDER);

foreach ($got as $k => $v) {
    echo "$k $v\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

foo foo-data
bar bar-data
baz baz-data
lol lol-data
kek kek-data
zoo

Zobacz też:

  • Memcached::getMultiByKey() - Retrieve multiple items from a specific server
  • Memcached::get() - Retrieve an item
  • Memcached::getDelayed() - Request multiple items

Memcached::getDelayedByKey
Memcached::getMultiByKey
Memcached


Retrieve multiple items from a specific server

Memcached::getMulti
Memcached::getOption
Memcached
PHP Manual

Memcached::getMultiByKey

(PECL memcached >= 0.1.0)

Memcached::getMultiByKey — Retrieve multiple items from a specific server

Opis

public array Memcached::getMultiByKey ( string $server_key , array $keys [, string &$cas_tokens [, int $flags ]] )

Memcached::getMultiByKey() is functionally equivalent to Memcached::getMulti(), except that the free-form server_key can be used to map the keys to a specific server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

keys

Array of keys to retrieve.

cas_tokens

The variable to store the CAS tokens for the found items.

flags

The flags for the get operation.

Zwracane wartości

Returns the array of found items lub FALSE w przypadku niepowodzenia. Użyj Memcached::getResultCode(), jeśli to konieczne.

Zobacz też:

  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::get() - Retrieve an item
  • Memcached::getDelayed() - Request multiple items

Memcached::getMulti
Memcached::getOption
Memcached


Retrieve a Memcached option value

Memcached::getMultiByKey
Memcached::getResultCode
Memcached
PHP Manual

Memcached::getOption

(PECL memcached >= 0.1.0)

Memcached::getOption — Retrieve a Memcached option value

Opis

public mixed Memcached::getOption ( int $option )

This method returns the value of a Memcached option. Some options correspond to the ones defined by libmemcached, and some are specific to the extension. See Memcached Constants for more information.

Parametry

option

One of the Memcached::OPT_* constants.

Zwracane wartości

Returns the value of the requested option, or FALSE on error.

Przykłady

Przykład #1 Retrieving Memcached options

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_COMPRESSION));
var_dump($m->getOption(Memcached::OPT_POLL_TIMEOUT));
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
int(1000)

Zobacz też:

  • Memcached::setOption() - Set a Memcached option
  • Memcached Constants

Memcached::getMultiByKey
Memcached::getResultCode
Memcached


Return the result code of the last operation

Memcached::getOption
Memcached::getResultMessage
Memcached
PHP Manual

Memcached::getResultCode

(PECL memcached >= 0.1.0)

Memcached::getResultCode — Return the result code of the last operation

Opis

public int Memcached::getResultCode ( void )

Memcached::getResultCode() returns one of the Memcached::RES_* constants that is the result of the last executed Memcached method.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Result code of the last Memcached operation.

Przykłady

Przykład #1 Memcached::getResultCode() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->add('foo', 'bar');
if ($m->getResultCode() == Memcached::RES_NOTSTORED) {
    /* ... */
}
?>

Memcached::getOption
Memcached::getResultMessage
Memcached


Return the message describing the result of the last operation

Memcached::getResultCode
Memcached::getServerByKey
Memcached
PHP Manual

Memcached::getResultMessage

(PECL memcached >= 1.0.0)

Memcached::getResultMessage — Return the message describing the result of the last operation

Opis

public string Memcached::getResultMessage ( void )

Memcached::getResultMessage() returns a string that describes the result code of the last executed Memcached method.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Message describing the result of the last Memcached operation.

Przykłady

Przykład #1 Memcached::getResultMessage() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->add('foo', 'bar'); // first time should succeed
$m->add('foo', 'bar');
echo $m->getResultMessage(),"\n";
?>

Powyższy przykład wyświetli:

NOT STORED

Memcached::getResultCode
Memcached::getServerByKey
Memcached


Map a key to a server

Memcached::getResultMessage
Memcached::getServerList
Memcached
PHP Manual

Memcached::getServerByKey

(PECL memcached >= 0.1.0)

Memcached::getServerByKey — Map a key to a server

Opis

public array Memcached::getServerByKey ( string $server_key )

Memcached::getServerByKey() returns the server that would be selected by a particular server_key in all the Memcached::*ByKey() operations.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Użyj Memcached::getResultCode(), jeśli to konieczne.

Przykłady

Przykład #1 Memcached::getServerByKey() example

<?php
$m = new Memcached();
$m->addServers(array(
    array('mem1.domain.com', 11211, 40),
    array('mem2.domain.com', 11211, 40),
    array('mem3.domain.com', 11211, 20),
));

$m->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);

var_dump($m->getServerByKey('user'));
var_dump($m->getServerByKey('log'));
var_dump($m->getServerByKey('ip'));
?>

Powyższy przykład wyświetli coś podobnego do:

array(3) {
  ["host"]=>
  string(15) "mem3.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(20)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}

Memcached::getResultMessage
Memcached::getServerList
Memcached


Get the list of the servers in the pool

Memcached::getServerByKey
Memcached::getStats
Memcached
PHP Manual

Memcached::getServerList

(PECL memcached >= 0.1.0)

Memcached::getServerList — Get the list of the servers in the pool

Opis

public array Memcached::getServerList ( void )

Memcached::getServerList() returns the list of all servers that are in its server pool.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The list of all servers in the server pool.

Przykłady

Przykład #1 Memcached::getServerList() example

<?php
$m = new Memcached();
$m->addServers(array(
    array('mem1.domain.com', 11211, 20),
    array('mem2.domain.com', 11311, 80),
));
var_dump($m->getServerList());
?>

Powyższy przykład wyświetli:

array(2) {
  [0]=>
  array(3) {
    ["host"]=>
    string(15) "mem1.domain.com"
    ["port"]=>
    int(11211)
    ["weight"]=>
    int(20)
  }
  [1]=>
  array(3) {
    ["host"]=>
    string(15) "mem2.domain.com"
    ["port"]=>
    int(11311)
    ["weight"]=>
    int(80)
  }
}

Memcached::getServerByKey
Memcached::getStats
Memcached


Get server pool statistics

Memcached::getServerList
Memcached::getVersion
Memcached
PHP Manual

Memcached::getStats

(PECL memcached >= 0.1.0)

Memcached::getStats — Get server pool statistics

Opis

public array Memcached::getStats ( void )

Memcached::getStats() returns an array containing the state of all available memcache servers. See » memcache protocol specification for details on these statistics.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Array of server statistics, one entry per server.

Przykłady

Przykład #1 Memcached::getStats() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getStats());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [localhost:11211] => Array
        (
            [pid] => 4933
            [uptime] => 786123
            [threads] => 1
            [time] => 1233868010
            [pointer_size] => 32
            [rusage_user_seconds] => 0
            [rusage_user_microseconds] => 140000
            [rusage_system_seconds] => 23
            [rusage_system_microseconds] => 210000
            [curr_items] => 145
            [total_items] => 2374
            [limit_maxbytes] => 67108864
            [curr_connections] => 2
            [total_connections] => 151
            [connection_structures] => 3
            [bytes] => 20345
            [cmd_get] => 213343
            [cmd_set] => 2381
            [get_hits] => 204223
            [get_misses] => 9120
            [evictions] => 0
            [bytes_read] => 9092476
            [bytes_written] => 15420512
            [version] => 1.2.6
        )

)

Memcached::getServerList
Memcached::getVersion
Memcached


Get server pool version info

Memcached::getStats
Memcached::increment
Memcached
PHP Manual

Memcached::getVersion

(PECL memcached >= 0.1.5)

Memcached::getVersion — Get server pool version info

Opis

public array Memcached::getVersion ( void )

Memcached::getVersion() returns an array containing the version info for all available memcache servers.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Array of server versions, one entry per server.

Przykłady

Przykład #1 Memcached::getVersion() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getVersion());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [localhost:11211] => 1.2.6
)

Memcached::getStats
Memcached::increment
Memcached


Increment numeric item's value

Memcached::getVersion
Memcached::prepend
Memcached
PHP Manual

Memcached::increment

(PECL memcached >= 0.1.0)

Memcached::increment — Increment numeric item's value

Opis

public int Memcached::increment ( string $key [, int $offset = 1 ] )

Memcached::increment() increments a numeric item's value by the specified offset. If the item's value is not numeric, it is treated as if the value were 0. Memcached::increment() will fail if the item does not exist.

Parametry

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

Zwracane wartości

Returns new item's value on success lub FALSE w przypadku niepowodzenia. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Przykłady

Przykład #1 Memcached::increment() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 0);
$m->increment('counter');
$m->increment('counter', 10);
var_dump($m->get('counter'));

$m->set('key', 'abc');
$m->increment('counter');
?>

Powyższy przykład wyświetli:

int(11)
string(1) "1"

Zobacz też:

  • Memcached::decrement() - Decrement numeric item's value

Memcached::getVersion
Memcached::prepend
Memcached


Prepend data to an existing item

Memcached::increment
Memcached::prependByKey
Memcached
PHP Manual

Memcached::prepend

(PECL memcached >= 0.1.0)

Memcached::prepend — Prepend data to an existing item

Opis

public bool Memcached::prepend ( string $key , string $value )

Memcached::prepend() prepends the given value string to the value of an existing item. The reason that value is forced to be a string is that prepending mixed types is not well-defined.

Informacja:

If the Memcached::OPT_COMPRESSION is enabled, the operation will fail and a warning will be issued, because prepending compressed data to a value that is potentially already compressed is not possible.

Parametry

key

The key of the item to prepend the data to.

value

The string to prepend.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Przykłady

Przykład #1 Memcached::prepend() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);

$m->set('foo', 'abc');
$m->prepend('foo', 'def');
var_dump($m->get('foo'));
?>

Powyższy przykład wyświetli:

string(6) "defabc"

Zobacz też:

  • Memcached::prependByKey() - Prepend data to an existing item on a specific server
  • Memcached::append() - Append data to an existing item

Memcached::increment
Memcached::prependByKey
Memcached


Prepend data to an existing item on a specific server

Memcached::prepend
Memcached::replace
Memcached
PHP Manual

Memcached::prependByKey

(PECL memcached >= 0.1.0)

Memcached::prependByKey — Prepend data to an existing item on a specific server

Opis

public bool Memcached::prependByKey ( string $server_key , string $key , string $value )

Memcached::prependByKey() is functionally equivalent to Memcached::prepend(), except that the free-form server_key can be used to map the key to a specific server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

key

The key of the item to prepend the data to.

value

The string to prepend.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Zobacz też:

  • Memcached::prepend() - Prepend data to an existing item
  • Memcached::append() - Append data to an existing item

Memcached::prepend
Memcached::replace
Memcached


Replace the item under an existing key

Memcached::prependByKey
Memcached::replaceByKey
Memcached
PHP Manual

Memcached::replace

(PECL memcached >= 0.1.0)

Memcached::replace — Replace the item under an existing key

Opis

public bool Memcached::replace ( string $key , mixed $value [, int $expiration ] )

Memcached::replace() is similar to Memcached::set(), but the operation fails if the key does not exist on the server.

Parametry

key

Klucz określający przechowywaną wartość.

value

Wartość do przechowania.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Zobacz też:

  • Memcached::replaceByKey() - Replace the item under an existing key on a specific server
  • Memcached::set() - Store an item
  • Memcached::add() - Add an item under a new key

Memcached::prependByKey
Memcached::replaceByKey
Memcached


Replace the item under an existing key on a specific server

Memcached::replace
Memcached::set
Memcached
PHP Manual

Memcached::replaceByKey

(PECL memcached >= 0.1.0)

Memcached::replaceByKey — Replace the item under an existing key on a specific server

Opis

public bool Memcached::replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )

Memcached::replaceByKey() is functionally equivalent to Memcached::replace(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

key

Klucz określający przechowywaną wartość.

value

Wartość do przechowania.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Zobacz też:

  • Memcached::replace() - Replace the item under an existing key
  • Memcached::set() - Store an item
  • Memcached::add() - Add an item under a new key

Memcached::replace
Memcached::set
Memcached


Store an item

Memcached::replaceByKey
Memcached::setByKey
Memcached
PHP Manual

Memcached::set

(PECL memcached >= 0.1.0)

Memcached::set — Store an item

Opis

public bool Memcached::set ( string $key , mixed $value [, int $expiration ] )

Memcached::set() stores the value on a memcache server under the specified key. The expiration parameter can be used to control when the value is considered expired.

The value can be any valid PHP type except for resources, because those cannot be represented in a serialized form. If the Memcached::OPT_COMPRESSION option is turned on, the serialized value will also be compressed before storage.

Parametry

key

Klucz określający przechowywaną wartość.

value

Wartość do przechowania.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Użyj Memcached::getResultCode(), jeśli to konieczne.

Przykłady

Przykład #1 Memcached::set() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));
/* expire 'object' key in 5 minutes */
$m->set('object', new stdclass, time() + 300);

var_dump($m->get('int'));
var_dump($m->get('string'));
var_dump($m->get('array'));
var_dump($m->get('object'));
?>

Powyższy przykład wyświetli coś podobnego do:

int(99)
string(15) "a simple string"
array(2) {
  [0]=>
  int(11)
  [1]=>
  int(12)
}
object(stdClass)#1 (0) {
}

Zobacz też:

  • Memcached::setByKey() - Store an item on a specific server
  • Memcached::add() - Add an item under a new key
  • Memcached::replace() - Replace the item under an existing key

Memcached::replaceByKey
Memcached::setByKey
Memcached


Store an item on a specific server

Memcached::set
Memcached::setMulti
Memcached
PHP Manual

Memcached::setByKey

(PECL memcached >= 0.1.0)

Memcached::setByKey — Store an item on a specific server

Opis

public bool Memcached::setByKey ( string $server_key , string $key , mixed $value [, int $expiration ] )

Memcached::setByKey() is functionally equivalent to Memcached::set(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

key

Klucz określający przechowywaną wartość.

value

Wartość do przechowania.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Użyj Memcached::getResultCode(), jeśli to konieczne.

Przykłady

Przykład #1 Memcached::setByKey() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

/* keep IP blocks on a certain server */
$m->setByKey('api-cache', 'block-ip:169.254.253.252', 1);
$m->setByKey('api-cache', 'block-ip:169.127.127.202', 1);
?>

Zobacz też:

  • Memcached::set() - Store an item

Memcached::set
Memcached::setMulti
Memcached


Store multiple items

Memcached::setByKey
Memcached::setMultiByKey
Memcached
PHP Manual

Memcached::setMulti

(PECL memcached >= 0.1.0)

Memcached::setMulti — Store multiple items

Opis

public bool Memcached::setMulti ( array $items [, int $expiration ] )

Memcached::setMulti() is similar to Memcached::set(), but instead of a single key/value item, it works on multiple items specified in items. The expiration time applies to all the items at once.

Parametry

items

Tablica, para kluczy/wartości do przechowywania na serwerze.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Użyj Memcached::getResultCode(), jeśli to konieczne.

Przykłady

Przykład #1 Memcached::setMulti() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items, time() + 300);
?>

Zobacz też:

  • Memcached::setMultiByKey() - Store multiple items on a specific server
  • Memcached::set() - Store an item

Memcached::setByKey
Memcached::setMultiByKey
Memcached


Store multiple items on a specific server

Memcached::setMulti
Memcached::setOption
Memcached
PHP Manual

Memcached::setMultiByKey

(PECL memcached >= 0.1.0)

Memcached::setMultiByKey — Store multiple items on a specific server

Opis

public bool Memcached::setMultiByKey ( string $server_key , array $items [, int $expiration ] )

Memcached::setMultiByKey() is functionally equivalent to Memcached::setMulti(), except that the free-form server_key can be used to map the keys from items to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parametry

server_key

Klucz identyfikujący serwer do przechowywania wartości.

items

Tablica, para kluczy/wartości do przechowywania na serwerze.

expiration

Czas wygaśnięcia, domyślnie 0. Zobacz Czasy wygaśnięcia, aby dowiedzieć się wiecej.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Użyj Memcached::getResultCode(), jeśli to konieczne.

Zobacz też:

  • Memcached::setMulti() - Store multiple items
  • Memcached::set() - Store an item

Memcached::setMulti
Memcached::setOption
Memcached


Set a Memcached option

Memcached::setMultiByKey
mqseries
Memcached
PHP Manual

Memcached::setOption

(PECL memcached >= 0.1.0)

Memcached::setOption — Set a Memcached option

Opis

public bool Memcached::setOption ( int $option , mixed $value )

This method sets the value of a Memcached option. Some options correspond to the ones defined by libmemcached, and some are specific to the extension. See Memcached Constants for more information.

The options listed below require values specified via constants.

  • Memcached::OPT_HASH requires Memcached::HASH_* values.

  • Memcached::OPT_DISTRIBUTION requires Memcached::DISTRIBUTION_* values.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Setting a Memcached option

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
$m->setOption(Memcached::OPT_HASH, Memcached::HASH_MURMUR);
$m->setOption(Memcached::OPT_PREFIX_KEY, "widgets");
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
?>

Powyższy przykład wyświetli:

bool(true)
Prefix key is now: widgets

Zobacz też:

  • Memcached::getOption() - Retrieve a Memcached option value

Memcached::setMultiByKey
mqseries
Memcached


mqseries

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • mqseries Funkcje
    • mqseries_back — MQSeries MQBACK
    • mqseries_begin — MQseries MQBEGIN
    • mqseries_close — MQSeries MQCLOSE
    • mqseries_cmit — MQSeries MQCMIT
    • mqseries_conn — MQSeries MQCONN
    • mqseries_connx — MQSeries MQCONNX
    • mqseries_disc — MQSeries MQDISC
    • mqseries_get — MQSeries MQGET
    • mqseries_inq — MQSeries MQINQ
    • mqseries_open — MQSeries MQOPEN
    • mqseries_put1 — MQSeries MQPUT1
    • mqseries_put — MQSeries MQPUT
    • mqseries_set — MQSeries MQSET
    • mqseries_strerror — Returns the error message corresponding to a result code (MQRC).
Memcached::setOption
Wstęp
Inne serwisy


Wstęp

This extension aims to provide an interface for communicating with IBMs WebSphere MQ series Queue managers.

The interface mimics the C-API client interface of WebSphere MQ Series as close as possible. Using the same naming conventions and possibilities of the C-API. In order to understand the workings of this extension some level of understanding the C-API is required.

For MQ-options, MQ-structures, MQ-results etc. please read the WebSphere MQ Application Programming Guide and WebSphere MQ Application Programming Reference.

mqseries
Instalacja/Konfiguracja
mqseries


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
mqseries


Wymagania

A working IBM WebSphere MQ installation. If building the extension the SDK for IBM WebSphere MQ is also required.

Informacja: Be aware that when running against a IBM WebSphere MQ Client installation some methods are not available. This is not a problem of the extension but just the way the WebSphere MQ Client Interface works.

Installation requirements on non windows platforms

Build the extension and put it in the PHP extension directory.

Installation requirements on Windows

No additional requirements.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/mqseries.

Informacja: The official name of this extension is mqseries.

There are two ways to connect to a queue manager. These depend on the way the extension is compiled and linked.

  • First one and also the default one is using the mqic libraries. Compiling and linking the extension against these IBM WebSphere MQSeries libraries allows the extension to connect to the Queue manager using the client interface. Remote connections are possible this way.

  • The other way is to compile and link against the mqm libraries. Using these libraries it is possible to make use of the transaction management of a queue manager.

Currently selecting the libraries to use is done by changing the config.m4 file.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

There are no extra configuration parameters.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines a connection and object_handle resources.

The mqseries_conn() and mqseries_connx() define the connectionn handles.

The mqseries_open() defines the object handle.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

For each WebSphere MQ Constant there is a mqseries counterpart.

For definitions and usage see the WebSphere MQ Application Programming Guide and WebSphere MQ Application Programming Reference red books.

The name of the mqseries counterpart is made by appending the WebSphere MQ constant with MQSERIES_, for example the CompletionCode constants are:

mqseries constants
PHP Constant | MQ Constant
MQSERIES_MQCC_OK | MQCC_OK
MQSERIES_MQCC_WARNING | MQCC_WARNING
MQSERIES_MQCC_FAILED | MQCC_FAILED
MQSERIES_MQCC_UNKNOWN | MQCC_UNKNOWN

Typy zasobów
mqseries Funkcje
mqseries


mqseries Funkcje

Spis treści

  • mqseries_back — MQSeries MQBACK
  • mqseries_begin — MQseries MQBEGIN
  • mqseries_close — MQSeries MQCLOSE
  • mqseries_cmit — MQSeries MQCMIT
  • mqseries_conn — MQSeries MQCONN
  • mqseries_connx — MQSeries MQCONNX
  • mqseries_disc — MQSeries MQDISC
  • mqseries_get — MQSeries MQGET
  • mqseries_inq — MQSeries MQINQ
  • mqseries_open — MQSeries MQOPEN
  • mqseries_put1 — MQSeries MQPUT1
  • mqseries_put — MQSeries MQPUT
  • mqseries_set — MQSeries MQSET
  • mqseries_strerror — Returns the error message corresponding to a result code (MQRC).
Stałe predefiniowane
mqseries_back
mqseries


MQSeries MQBACK

mqseries Funkcje
mqseries_begin
mqseries Funkcje
PHP Manual

mqseries_back

(PECL mqseries >= 0.10.0)

mqseries_back — MQSeries MQBACK

Opis

void mqseries_back ( resource $hconn , resource &$compCode , resource &$reason )

The mqseries_back() (MQBACK) call indicates to the queue manager that all the message gets and puts that have occurred since the last syncpoint are to be backed out. Messages put as part of a unit of work are deleted; messages retrieved as part of a unit of work are reinstated on the queue.

Using mqseries_back() only works in conjunction with mqseries_begin() and only function when connecting directly to a Queueu manager. Not via the mqclient interface.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_back() example

<?php
    mqseries_back($conn, $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

Notatki

Informacja:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

Zobacz też:

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_begin() - MQseries MQBEGIN

mqseries Funkcje
mqseries_begin
mqseries Funkcje


MQseries MQBEGIN

mqseries_back
mqseries_close
mqseries Funkcje
PHP Manual

mqseries_begin

(PECL mqseries >= 0.10.0)

mqseries_begin — MQseries MQBEGIN

Opis

void mqseries_begin ( resource $hconn , array $beginOptions , resource &$compCode , resource &$reason )

The mqseries_begin() (MQBEGIN) call begins a unit of work that is coordinated by the queue manager, and that may involve external resource managers.

Using mqseries_begin() starts the unit of work. Either mqseries_back() or mqseries_cmit() ends the unit of work.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_begin() example

<?php
    $mqbo = array();
    mqseries_begin( $conn,
                    $mqbo,
                    $comp_code,
                    $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        /* reason code 2121 is a warning for more information see MQSeries reference manual.*/
        if ($reason !== 2121) {
            printf("CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        }
    }
?>

Notatki

Informacja:

mqseries_begin() will not function when using MQSeries Client to connect to a Queueu Manager.

Zobacz też:

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_back() - MQSeries MQBACK
  • mqseries_cmit() - MQSeries MQCMIT

mqseries_back
mqseries_close
mqseries Funkcje


MQSeries MQCLOSE

mqseries_begin
mqseries_cmit
mqseries Funkcje
PHP Manual

mqseries_close

(PECL mqseries >= 0.10.0)

mqseries_close — MQSeries MQCLOSE

Opis

void mqseries_close ( resource $hconn , resource $hobj , int $options , resource &$compCode , resource &$reason )

The mqseries_close() (MQCLOSE) call relinquishes access to an object, and is the inverse of the mqseries_open() (MQOPEN) call.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

options

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_close() example

<?php
    mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("close CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

Zobacz też:

  • mqseries_open() - MQSeries MQOPEN
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

mqseries_begin
mqseries_cmit
mqseries Funkcje


MQSeries MQCMIT

mqseries_close
mqseries_conn
mqseries Funkcje
PHP Manual

mqseries_cmit

(PECL mqseries >= 0.10.0)

mqseries_cmit — MQSeries MQCMIT

Opis

void mqseries_cmit ( resource $hconn , resource &$compCode , resource &$reason )

The mqseries_cmit() (MQCMIT) call indicates to the queue manager that the application has reached a syncpoint, and that all of the message gets and puts that have occurred since the last syncpoint are to be made permanent. Messages put as part of a unit of work are made available to other applications; messages retrieved as part of a unit of work are deleted.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_cmit() example

<?php
    mqseries_cmit($conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("cmit CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

Notatki

Informacja:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

Zobacz też:

  • mqseries_begin() - MQseries MQBEGIN
  • mqseries_back() - MQSeries MQBACK
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

mqseries_close
mqseries_conn
mqseries Funkcje


MQSeries MQCONN

mqseries_cmit
mqseries_connx
mqseries Funkcje
PHP Manual

mqseries_conn

(PECL mqseries >= 0.10.0)

mqseries_conn — MQSeries MQCONN

Opis

void mqseries_conn ( string $qManagerName , resource &$hconn , resource &$compCode , resource &$reason )

The mqseries_conn() (MQCONN) call connects an application program to a queue manager. It provides a queue manager connection handle, which is used by the application on subsequent message queuing calls.

Parametry

qManagerName

Name of queue manager.

Name of the queue manager the application wishes to connect.

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_conn() example

<?php
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("conn CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

Zobacz też:

  • mqseries_disc() - MQSeries MQDISC

mqseries_cmit
mqseries_connx
mqseries Funkcje


MQSeries MQCONNX

mqseries_conn
mqseries_disc
mqseries Funkcje
PHP Manual

mqseries_connx

(PECL mqseries >= 0.10.0)

mqseries_connx — MQSeries MQCONNX

Opis

void mqseries_connx ( string $qManagerName , array &$connOptions , resource &$hconn , resource &$compCode , resource &$reason )

The mqseries_connx() (MQCONNX) call connects an application program to a queue manager. It provides a queue manager connection handle, which is used by the application on subsequent MQ calls.

Parametry

qManagerName

Name of queue manager.

Name of the queue manager the application wishes to connect.

connOps

Options that control the action of function

See also the MQCNO structure.

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_connx() example

<?php
    $mqcno = array(
        'Version' => MQSERIES_MQCNO_VERSION_2,
        'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
        'MQCD' => array('ChannelName' => 'MQNX9420.CLIENT',
        'ConnectionName' => 'localhost',
        'TransportType' => MQSERIES_MQXPT_TCP)
    );

    mqseries_connx('MQNX9420', $mqcno, $conn, $comp_code,$reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("Connx CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }

?>

Zobacz też:

  • mqseries_disc() - MQSeries MQDISC

mqseries_conn
mqseries_disc
mqseries Funkcje


MQSeries MQDISC

mqseries_connx
mqseries_get
mqseries Funkcje
PHP Manual

mqseries_disc

(PECL mqseries >= 0.10.0)

mqseries_disc — MQSeries MQDISC

Opis

void mqseries_disc ( resource $hconn , resource &$compCode , resource &$reason )

The mqseries_disc() (MQDISC) call breaks the connection between the queue manager and the application program, and is the inverse of the mqseries_conn() (MQCONN) or mqseries_connx() (MQCONNX) call.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_disc() example

<?php
    mqseries_disc($conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("disc CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

Zobacz też:

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

mqseries_connx
mqseries_get
mqseries Funkcje


MQSeries MQGET

mqseries_disc
mqseries_inq
mqseries Funkcje
PHP Manual

mqseries_get

(PECL mqseries >= 0.10.0)

mqseries_get — MQSeries MQGET

Opis

void mqseries_get ( resource $hConn , resource $hObj , array &$md , array &$gmo , int &$bufferLength , string &$msg , int &$data_length , resource &$compCode , resource &$reason )

The mqseries_get() (MQGET) call retrieves a message from a local queue that has been opened using the mqseries_open() (MQOPEN) call

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

md

Message descriptor (MQMD).

gmo

Get message options (MQGMO).

bufferLength

Expected length of the result buffer

msg

Buffer holding the message that was retrieved from the object.

data_length

Actual buffer length

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_get() example

<?php
// open connection to the queue manager
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connection to the testq queue
    mqseries_open(
                $conn,
                array('ObjectName' => 'TESTQ'),
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
// $obj now holds the reference to the object (TESTQ)

// setup empty message descriptor.
    $mdg = array();
// setup get message options
    $gmo = array('Options' => MQSERIES_MQGMO_FAIL_IF_QUIESCING | MQSERIES_MQGMO_WAIT, 'WaitInterval' => 3000);

// get the message from the queueu
    mqseries_get($conn, $obj, $mdg, $gmo, 255, $msg, $data_length, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("GET CompCode:%d Reason:%d Text:%s<br>", $comp_code, $reason, mqseries_strerror($reason));
    }

 // open connection to the queue manager
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connection to the testq queue
    mqseries_open(
                $conn,
                array('ObjectName' => 'TESTQ'),
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
// $obj now holds the reference to the object (TESTQ)

?>

Zobacz też:

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_put() - MQSeries MQPUT

mqseries_disc
mqseries_inq
mqseries Funkcje


MQSeries MQINQ

mqseries_get
mqseries_open
mqseries Funkcje
PHP Manual

mqseries_inq

(PECL mqseries >= 0.10.0)

mqseries_inq — MQSeries MQINQ

Opis

void mqseries_inq ( resource $hconn , resource $hobj , int $selectorCount , array $selectors , int $intAttrCount , resource &$intAttr , int $charAttrLength , resource &$charAttr , resource &$compCode , resource &$reason )

The mqseries_inq() (MQINQ) call returns an array of integers and a set of character strings containing the attributes of an object.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

selectorCount

Count of selectors.

selectors

Array of attribute selectors.

intAttrLength

Count of integer attributes.

intAttr

Array of integer attributes.

charAttrLength

Length of character attributes buffer.

charAttr

Character attributes.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_inq() example

<?php
    $int_attr = array();
    $char_attr = "";

    mqseries_inq($conn, $obj, 1, array(MQSERIES_MQCA_Q_MGR_NAME), 0, $int_attr, 48, $char_attr, $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("INQ CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    } else {
        echo "INQ QManager name result ".$char_attr."<br>\n";
    }
?>

Zobacz też:

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN

mqseries_get
mqseries_open
mqseries Funkcje


MQSeries MQOPEN

mqseries_inq
mqseries_put1
mqseries Funkcje
PHP Manual

mqseries_open

(PECL mqseries >= 0.10.0)

mqseries_open — MQSeries MQOPEN

Opis

void mqseries_open ( resource $hconn , array &$objDesc , int $option , resource &$hobj , resource &$compCode , resource &$reason )

The mqseries_open() (MQOPEN) call establishes access to an object.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

objDesc

Object descriptor. (MQOD)

options

Options that control the action of the function.

hObj

Object handle.

This handle represents the object to be used.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_open() example

<?php
    $mqods = array('ObjectName' => 'TESTQ');
    mqseries_open(
                $conn,
                $mqods,
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("open CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

Zobacz też:

  • mqseries_close() - MQSeries MQCLOSE

mqseries_inq
mqseries_put1
mqseries Funkcje


MQSeries MQPUT1

mqseries_open
mqseries_put
mqseries Funkcje
PHP Manual

mqseries_put1

(PECL mqseries >= 0.10.0)

mqseries_put1 — MQSeries MQPUT1

Opis

void mqseries_put1 ( resource $hconn , resource &$objDesc , resource &$msgDesc , resource &$pmo , string $buffer , resource &$compCode , resource &$reason )

The mqseries_put1() (MQPUT1) call puts one message on a queue. The queue need not be open.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

objDesc

Object descriptor. (MQOD)

This is a structure which identifies the queue to which the message is added.

msgDesc

Message descriptor (MQMD).

pmo

Put message options (MQPMO).

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET

mqseries_open
mqseries_put
mqseries Funkcje


MQSeries MQPUT

mqseries_put1
mqseries_set
mqseries Funkcje
PHP Manual

mqseries_put

(PECL mqseries >= 0.10.0)

mqseries_put — MQSeries MQPUT

Opis

void mqseries_put ( resource $hConn , resource $hObj , array &$md , array &$pmo , string $message , resource &$compCode , resource &$reason )

The mqseries_put() (MQPUT) call puts a message on a queue or distribution list. The queue or distribution list must already be open.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

md

Message descriptor (MQMD).

pmo

Put message options (MQPMO).

message

The actual message to put onto the queue.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 mqseries_put() example

<?php
// open connection to the queue manager
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connectio to the testq queueu
    mqseries_open(
                $conn,
                array('ObjectName' => 'TESTQ'),
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
// $obj now holds the reference to the object (TESTQ)

// setup the message descriptor array. Check MQSeries reference manuals.
    $md = array(
                'Version' => MQSERIES_MQMD_VERSION_1,
                'Expiry' => MQSERIES_MQEI_UNLIMITED,
                'Report' => MQSERIES_MQRO_NONE,
                'MsgType' => MQSERIES_MQMT_DATAGRAM,
                'Format' => MQSERIES_MQFMT_STRING,
                'Priority' => 1,
                'Persistence' => MQSERIES_MQPER_PERSISTENT);

// setup the put message options.
    $pmo = array('Options' => MQSERIES_MQPMO_NEW_MSG_ID|MQSERIES_MQPMO_SYNCPOINT);

// put the message 'Ping' on the queueu.
    mqseries_put($conn, $obj, $md, $pmo, 'Ping', $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("put CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }

// close the object reference $obj
    mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);

// disconnect from the queue manager.
    mqseries_disc($conn, $comp_code, $reason);

?>

Zobacz też:

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET

mqseries_put1
mqseries_set
mqseries Funkcje


MQSeries MQSET

mqseries_put
mqseries_strerror
mqseries Funkcje
PHP Manual

mqseries_set

(PECL mqseries >= 0.10.0)

mqseries_set — MQSeries MQSET

Opis

void mqseries_set ( resource $hconn , resource $hobj , int $selectorcount , array $selectors , int $intattrcount , array $intattrs , int $charattrlength , array $charattrs , resource &$compCode , resource &$reason )

The mqseries_set() (MQSET) call is used to change the attributes of an object represented by a handle. The object must be a queue.

Parametry

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • mqseries_inq() - MQSeries MQINQ

mqseries_put
mqseries_strerror
mqseries Funkcje


Returns the error message corresponding to a result code (MQRC).

mqseries_set
Network
mqseries Funkcje
PHP Manual

mqseries_strerror

(PECL mqseries >= 0.10.0)

mqseries_strerror — Returns the error message corresponding to a result code (MQRC).

Opis

string mqseries_strerror ( int $reason )

mqseries_strerror() returns the message that correspond to the reason result code.

Parametry

reason

Reason code qualifying the compCode.

Zwracane wartości

string representation of the reason code message.

Przykłady

Przykład #1 mqseries_strerror() example

<?php
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("open CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

Powyższy przykład wyświetli:

Connx CompCode:2 Reason:2059 Text:Queue manager not available for connection.

mqseries_set
Network
mqseries Funkcje


Network

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Network Funkcje
    • checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address
    • closelog — Close connection to system logger
    • define_syslog_variables — Initializes all syslog related variables
    • dns_check_record — Alias dla checkdnsrr
    • dns_get_mx — Alias dla getmxrr
    • dns_get_record — Fetch DNS Resource Records associated with a hostname
    • fsockopen — Open Internet or Unix domain socket connection
    • gethostbyaddr — Get the Internet host name corresponding to a given IP address
    • gethostbyname — Get the IPv4 address corresponding to a given Internet host name
    • gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name
    • gethostname — Gets the host name
    • getmxrr — Get MX records corresponding to a given Internet host name
    • getprotobyname — Get protocol number associated with protocol name
    • getprotobynumber — Get protocol name associated with protocol number
    • getservbyname — Get port number associated with an Internet service and protocol
    • getservbyport — Get Internet service which corresponds to port and protocol
    • header_register_callback — Call a header function
    • header_remove — Remove previously set headers
    • header — Send a raw HTTP header
    • headers_list — Returns a list of response headers sent (or ready to send)
    • headers_sent — Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło
    • http_response_code — Get or Set the HTTP response code
    • inet_ntop — Converts a packed internet address to a human readable representation
    • inet_pton — Converts a human readable IP address to its packed in_addr representation
    • ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
    • long2ip — Converts an (IPv4) Internet network address into a string in Internet standard dotted format
    • openlog — Open connection to system logger
    • pfsockopen — Open persistent Internet or Unix domain socket connection
    • setcookie — Send a cookie
    • setrawcookie — Send a cookie without urlencoding the cookie value
    • socket_get_status — Alias dla stream_get_meta_data
    • socket_set_blocking — Alias dla stream_set_blocking
    • socket_set_timeout — Alias dla stream_set_timeout
    • syslog — Generate a system log message
mqseries_strerror
Wstęp
Inne serwisy


Wstęp

Provides various networking functions.

Network
Instalacja/Konfiguracja
Network


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Network


Wymagania

Functions checkdnsrr(), getmxrr() and dns_get_record() requires Bind on Linux.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Network Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
define_syslog_variables | "0" | PHP_INI_ALL | Deprecated in PHP 5.3.0. Removed in 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.

define_syslog_variables boolean

Whether or not to define the various syslog variables (e.g. $LOG_PID, $LOG_CRON, etc.). Turning it off is a good idea performance-wise. At runtime, you can define these variables by calling define_syslog_variables().

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines a file pointer resource returned by fsockopen() and pfsockopen().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

Poniższe stałe są częścią jądra PHP a więc są zawsze widoczne.

openlog() Options
Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_NOWAIT |
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
openlog() Facilities
Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use, these are not available in Windows
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem
syslog() Priorities (in descending order)
Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message
dns_get_record() Options
Constant | Description
DNS_A | IPv4 Address Resource
DNS_MX | Mail Exchanger Resource
DNS_CNAME | Alias (Canonical Name) Resource
DNS_NS | Authoritative Name Server Resource
DNS_PTR | Pointer Resource
DNS_HINFO | Host Info Resource (See IANA's » Operating System Names for the meaning of these values)
DNS_SOA | Start of Authority Resource
DNS_TXT | Text Resource
DNS_ANY | Any Resource Record. On most systems this returns all resource records, however it should not be counted upon for critical uses. Try DNS_ALL instead.
DNS_AAAA | IPv6 Address Resource
DNS_ALL | Iteratively query the name server for each available record type.
Typy zasobów
Network Funkcje
Network


Network Funkcje

Spis treści

  • checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address
  • closelog — Close connection to system logger
  • define_syslog_variables — Initializes all syslog related variables
  • dns_check_record — Alias dla checkdnsrr
  • dns_get_mx — Alias dla getmxrr
  • dns_get_record — Fetch DNS Resource Records associated with a hostname
  • fsockopen — Open Internet or Unix domain socket connection
  • gethostbyaddr — Get the Internet host name corresponding to a given IP address
  • gethostbyname — Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name
  • gethostname — Gets the host name
  • getmxrr — Get MX records corresponding to a given Internet host name
  • getprotobyname — Get protocol number associated with protocol name
  • getprotobynumber — Get protocol name associated with protocol number
  • getservbyname — Get port number associated with an Internet service and protocol
  • getservbyport — Get Internet service which corresponds to port and protocol
  • header_register_callback — Call a header function
  • header_remove — Remove previously set headers
  • header — Send a raw HTTP header
  • headers_list — Returns a list of response headers sent (or ready to send)
  • headers_sent — Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło
  • http_response_code — Get or Set the HTTP response code
  • inet_ntop — Converts a packed internet address to a human readable representation
  • inet_pton — Converts a human readable IP address to its packed in_addr representation
  • ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
  • long2ip — Converts an (IPv4) Internet network address into a string in Internet standard dotted format
  • openlog — Open connection to system logger
  • pfsockopen — Open persistent Internet or Unix domain socket connection
  • setcookie — Send a cookie
  • setrawcookie — Send a cookie without urlencoding the cookie value
  • socket_get_status — Alias dla stream_get_meta_data
  • socket_set_blocking — Alias dla stream_set_blocking
  • socket_set_timeout — Alias dla stream_set_timeout
  • syslog — Generate a system log message
Stałe predefiniowane
checkdnsrr
Network


Check DNS records corresponding to a given Internet host name or IP address

Network Funkcje
closelog
Network Funkcje
PHP Manual

checkdnsrr

(PHP 4, PHP 5)

checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address

Opis

bool checkdnsrr ( string $host [, string $type = "MX" ] )

Searches DNS for records of type type corresponding to host.

Parametry

host

host may either be the IP address in dotted-quad notation or the host name.

type

type may be any one of: A, MX, NS, SOA, PTR, CNAME, AAAA, A6, SRV, NAPTR, TXT or ANY.

Zwracane wartości

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.
5.2.4 | TXT type was added.
5.0.0 | AAAA type was added.

Notatki

Informacja:

For compatibility with Windows before this was implemented, then try the » PEAR class » Net_DNS.

Zobacz też:

  • dns_get_record() - Fetch DNS Resource Records associated with a hostname
  • getmxrr() - Get MX records corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • the named(8) manual page

Network Funkcje
closelog
Network Funkcje


Close connection to system logger

checkdnsrr
define_syslog_variables
Network Funkcje
PHP Manual

closelog

(PHP 4, PHP 5)

closelog — Close connection to system logger

Opis

bool closelog ( void )

closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • syslog() - Generate a system log message
  • openlog() - Open connection to system logger

checkdnsrr
define_syslog_variables
Network Funkcje


Initializes all syslog related variables

closelog
dns_check_record
Network Funkcje
PHP Manual

define_syslog_variables

(PHP 4, PHP 5)

define_syslog_variables — Initializes all syslog related variables

Opis

void define_syslog_variables ( void )

Initializes all variables used in the syslog functions.

Zwracane wartości

Nie jest zwracana żadna wartość.

Syslog variables
Variable | Constant equal | Meaning | Notes
$LOG_EMERG | LOG_EMERG | System is unusable |
$LOG_ALERT | LOG_ALERT | Immediate action required |
$LOG_CRIT | LOG_CRIT | Critical conditions |
$LOG_ERR | LOG_ERR |  |
$LOG_WARNING | LOG_WARNING |  |
$LOG_NOTICE | LOG_NOTICE |  |
$LOG_INFO | LOG_INFO |  |
$LOG_DEBUG | LOG_DEBUG |  |
$LOG_KERN | LOG_KERN |  |
$LOG_USER | LOG_USER | Genetic user level |
$LOG_MAIL | LOG_MAIL | Log to email |
$LOG_DAEMON | LOG_DAEMON | Other system daemons |
$LOG_AUTH | LOG_AUTH |  |
$LOG_SYSLOG | LOG_SYSLOG |  | Not available on Netware
$LOG_LPR | LOG_LPR |  |
$LOG_NEWS | LOG_NEWS | Usenet new | Not available on HP-UX
$LOG_CRON | LOG_CRON |  | Not available on all platforms
$LOG_AUTHPRIV | LOG_AUTHPRIV |  | Not available on AIX
$LOG_LOCAL0 | LOG_LOCAL0 |  | Not available on Windows and Netware
$LOG_LOCAL1 | LOG_LOCAL1 |  | Not available on Windows and Netware
$LOG_LOCAL2 | LOG_LOCAL2 |  | Not available on Windows and Netware
$LOG_LOCAL3 | LOG_LOCAL3 |  | Not available on Windows and Netware
$LOG_LOCAL4 | LOG_LOCAL4 |  | Not available on Windows and Netware
$LOG_LOCAL5 | LOG_LOCAL5 |  | Not available on Windows and Netware
$LOG_LOCAL6 | LOG_LOCAL6 |  | Not available on Windows and Netware
$LOG_LOCAL7 | LOG_LOCAL7 |  | Not available on Windows and Netware
$LOG_PID | LOG_PID |  |
$LOG_CONS | LOG_CONS |  |
$LOG_ODELAY | LOG_ODELAY |  |
$LOG_NDELAY | LOG_NDELAY |  |
$LOG_NOWAIT | LOG_NOWAIT |  | Not available on BeOS
$LOG_PERROR | LOG_PERROR |  | Not available on AIX
Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Przykłady

Przykład #1 define_syslog_variables() example

<?php
// Check if syslog variables already is defined
if(!get_cfg_var('define_syslog_variables'))
{
    define_syslog_variables();
}

// Open the log
openlog('', $LOG_ODELAY, $LOG_MAIL | $LOG_USER);

// Continue script ...
?>

Rejestr zmian

Wersja | Opis
5.3.0 | This function now throws an E_DEPRECATED notice.

Zobacz też:

  • openlog() - Open connection to system logger
  • syslog() - Generate a system log message
  • closelog() - Close connection to system logger

closelog
dns_check_record
Network Funkcje


Alias dla checkdnsrr

define_syslog_variables
dns_get_mx
Network Funkcje
PHP Manual

dns_check_record

(PHP 5)

dns_check_record — Alias dla checkdnsrr()

Opis

Ta funkcja jest aliasem dla: checkdnsrr().

define_syslog_variables
dns_get_mx
Network Funkcje


Alias dla getmxrr

dns_check_record
dns_get_record
Network Funkcje
PHP Manual

dns_get_mx

(PHP 5)

dns_get_mx — Alias dla getmxrr()

Opis

Ta funkcja jest aliasem dla: getmxrr().

dns_check_record
dns_get_record
Network Funkcje


Fetch DNS Resource Records associated with a hostname

dns_get_mx
fsockopen
Network Funkcje
PHP Manual

dns_get_record

(PHP 5)

dns_get_record — Fetch DNS Resource Records associated with a hostname

Opis

array dns_get_record ( string $hostname [, int $type = DNS_ANY [, array &$authns [, array &$addtl ]]] )

Fetch DNS Resource Records associated with the given hostname.

Parametry

hostname

hostname should be a valid DNS hostname such as "www.example.com". Reverse lookups can be generated using in-addr.arpa notation, but gethostbyaddr() is more suitable for the majority of reverse lookups.

Informacja:

Per DNS standards, email addresses are given in user.host format (for example: hostmaster.example.com as opposed to hostmaster@example.com), be sure to check this value and modify if necessary before using it with a functions such as mail().

type

By default, dns_get_record() will search for any resource records associated with hostname. To limit the query, specify the optional type parameter. May be any one of the following: DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY.

Informacja:

Because of eccentricities in the performance of libresolv between platforms, DNS_ANY will not always return every record, the slower DNS_ALL will collect all records more reliably.

authns

Passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers.

addtl

Passed by reference and, if given, will be populated with any Additional Records.

Zwracane wartości

This function returns an array of associative arrays, lub FALSE w przypadku niepowodzenia. Each associative array contains at minimum the following keys:

Basic DNS attributes
Attribute | Meaning
host | The record in the DNS namespace to which the rest of the associated data refers.
class | dns_get_record() only returns Internet class records and as such this parameter will always return IN.
type | String containing the record type. Additional attributes will also be contained in the resulting array dependant on the value of type. See table below.
ttl | "Time To Live" remaining for this record. This will not equal the record's original ttl, but will rather equal the original ttl minus whatever length of time has passed since the authoritative name server was queried.

Other keys in associative arrays dependant on 'type'
Type | Extra Columns
A | ip: An IPv4 addresses in dotted decimal notation.
MX | pri: Priority of mail exchanger. Lower numbers indicate greater priority. target: FQDN of the mail exchanger. See also dns_get_mx().
CNAME | target: FQDN of location in DNS namespace to which the record is aliased.
NS | target: FQDN of the name server which is authoritative for this hostname.
PTR | target: Location within the DNS namespace to which this record points.
TXT | txt: Arbitrary string data associated with this record.
HINFO | cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See IANA's » Operating System Names for the meaning of these values.
SOA | mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contain for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records.
AAAA | ipv6: IPv6 address
A6(PHP >= 5.1.0) | masklen: Length (in bits) to inherit from the target specified by chain. ipv6: Address for this specific record to merge with chain. chain: Parent record to merge with ipv6 data.
SRV | pri: (Priority) lowest priorities should be used first. weight: Ranking to weight which of commonly prioritized targets should be chosen at random. target and port: hostname and port where the requested service can be found. For additional information see: » RFC 2782
NAPTR | order and pref: Equivalent to pri and weight above. flags, services, regex, and replacement: Parameters as defined by » RFC 2915.

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.
5.3.0 | Prior to this release, if the authns parameter was given, the addtl parameter was also required.

Przykłady

Przykład #1 Using dns_get_record()

<?php
$result = dns_get_record("php.net");
print_r($result);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)

Przykład #2 Using dns_get_record() and DNS_ANY

Since it's very common to want the IP address of a mail server once the MX record has been resolved, dns_get_record() also returns an array in addtl which contains associate records. authns is returned as well containing a list of authoritative name servers.

<?php
/* Request "ANY" record for php.net,
   and create $authns and $addtl arrays
   containing list of name servers and
   any additional records which go with
   them */
$result = dns_get_record("php.net", DNS_ANY, $authns, $addtl);
echo "Result = ";
print_r($result);
echo "Auth NS = ";
print_r($authns);
echo "Additional = ";
print_r($addtl);
?>

Powyższy przykład wyświetli coś podobnego do:

Result = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)
Auth NS = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [1] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [2] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [3] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

)
Additional = Array
(
    [0] => Array
        (
            [host] => pair2.php.net
            [type] => A
            [ip] => 216.92.131.5
            [class] => IN
            [ttl] => 6766
        )

    [1] => Array
        (
            [host] => remote1.easydns.com
            [type] => A
            [ip] => 64.39.29.212
            [class] => IN
            [ttl] => 100384
        )

    [2] => Array
        (
            [host] => remote2.easydns.com
            [type] => A
            [ip] => 212.100.224.80
            [class] => IN
            [ttl] => 81241
        )

    [3] => Array
        (
            [host] => ns1.easydns.com
            [type] => A
            [ip] => 216.220.40.243
            [class] => IN
            [ttl] => 81241
        )

    [4] => Array
        (
            [host] => ns2.easydns.com
            [type] => A
            [ip] => 216.220.40.244
            [class] => IN
            [ttl] => 81241
        )

)

Notatki

Informacja:

For compatibility with versions before PHP 5.3.0 on some operating systems, try the » PEAR class » Net_DNS.

Zobacz też:

  • dns_get_mx() - Alias dla getmxrr
  • dns_check_record() - Alias dla checkdnsrr

dns_get_mx
fsockopen
Network Funkcje


Open Internet or Unix domain socket connection

dns_get_record
gethostbyaddr
Network Funkcje
PHP Manual

fsockopen

(PHP 4, PHP 5)

fsockopen — Open Internet or Unix domain socket connection

Opis

resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )

Initiates a socket connection to the resource specified by hostname.

PHP supports targets in the Internet and Unix domains as described in List of Supported Socket Transports. A list of supported transports can also be retrieved using stream_get_transports().

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

The function stream_socket_client() is similar but provides a richer set of options, including non-blocking connection and the ability to provide a stream context.

Parametry

hostname

If OpenSSL support is installed, you may prefix the hostname with either ssl:// or tls:// to use an SSL or TLS client connection over TCP/IP to connect to the remote host.

port

The port number.

errno

If provided, holds the system level error number that occurred in the system-level connect() call.

If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket.

errstr

The error message as a string.

timeout

The connection timeout, in seconds.

Informacja:

If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to fsockopen() only applies while connecting the socket.

Zwracane wartości

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()). If the call fails, it will return FALSE

Błędy/Wyjątki

Throws E_WARNING if hostname is not a valid domain.

Rejestr zmian

Wersja | Opis
4.3.0 | Added support for the timeout parameter on win32.
4.3.0 | SSL and TLS over TCP/IP support was added.

Przykłady

Przykład #1 fsockopen() Example

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

Przykład #2 Using UDP connection

The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Notatki

Informacja:

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

Ostrzeżenie

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Informacja: Podając numerycznie adres IPv6 (np. fe80::1), adres musi być objęty nawiasami kwadratowymi. Na przykład tcp://[fe80::1]:80.

Zobacz też:

  • pfsockopen() - Open persistent Internet or Unix domain socket connection
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Pobiera linię ze wskaźnika pliku
  • fgetss() - Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
  • fwrite() - Zapis pliku binarnie bezpieczny
  • fclose() - Zamyka otwarty wskaźnik pliku
  • feof() - Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
  • socket_connect() - Initiates a connection on a socket
  • The Curl extension

dns_get_record
gethostbyaddr
Network Funkcje


Get the Internet host name corresponding to a given IP address

fsockopen
gethostbyname
Network Funkcje
PHP Manual

gethostbyaddr

(PHP 4, PHP 5)

gethostbyaddr — Get the Internet host name corresponding to a given IP address

Opis

string gethostbyaddr ( string $ip_address )

Returns the host name of the Internet host specified by ip_address.

Parametry

ip_address

The host IP address.

Zwracane wartości

Returns the host name on success, the unmodified ip_address on failure, or FALSE on malformed input.

Przykłady

Przykład #1 A simple gethostbyaddr() example

<?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);

echo $hostname;
?>

Zobacz też:

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name

fsockopen
gethostbyname
Network Funkcje


Get the IPv4 address corresponding to a given Internet host name

gethostbyaddr
gethostbynamel
Network Funkcje
PHP Manual

gethostbyname

(PHP 4, PHP 5)

gethostbyname — Get the IPv4 address corresponding to a given Internet host name

Opis

string gethostbyname ( string $hostname )

Returns the IPv4 address of the Internet host specified by hostname.

Parametry

hostname

The host name.

Zwracane wartości

Returns the IPv4 address or a string containing the unmodified hostname on failure.

Przykłady

Przykład #1 A simple gethostbyname() example

<?php
$ip = gethostbyname('www.example.com');

echo $ip;
?>

Zobacz też:

  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation
  • inet_ntop() - Converts a packed internet address to a human readable representation

gethostbyaddr
gethostbynamel
Network Funkcje


Get a list of IPv4 addresses corresponding to a given Internet host name

gethostbyname
gethostname
Network Funkcje
PHP Manual

gethostbynamel

(PHP 4, PHP 5)

gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name

Opis

array gethostbynamel ( string $hostname )

Returns a list of IPv4 addresses to which the Internet host specified by hostname resolves.

Parametry

hostname

The host name.

Zwracane wartości

Returns an array of IPv4 addresses or FALSE if hostname could not be resolved.

Przykłady

Przykład #1 gethostbynamel() example

<?php
$hosts = gethostbynamel('www.example.com');
print_r($hosts);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => 192.0.34.166
)

Zobacz też:

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • checkdnsrr() - Check DNS records corresponding to a given Internet host name or IP address
  • getmxrr() - Get MX records corresponding to a given Internet host name
  • the named(8) manual page

gethostbyname
gethostname
Network Funkcje


Gets the host name

gethostbynamel
getmxrr
Network Funkcje
PHP Manual

gethostname

(PHP >= 5.3.0)

gethostname — Gets the host name

Opis

string gethostname ( void )

gethostname() gets the standard host name for the local machine.

Zwracane wartości

Returns a string with the hostname on success, otherwise FALSE is returned.

Przykłady

Przykład #1 A simple gethostname() example

<?php
echo gethostname(); // may output e.g,: sandie

// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

Zobacz też:

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • php_uname() - Returns information about the operating system PHP is running on

gethostbynamel
getmxrr
Network Funkcje


Get MX records corresponding to a given Internet host name

gethostname
getprotobyname
Network Funkcje
PHP Manual

getmxrr

(PHP 4, PHP 5)

getmxrr — Get MX records corresponding to a given Internet host name

Opis

bool getmxrr ( string $hostname , array &$mxhosts [, array &$weight ] )

Searches DNS for MX records corresponding to hostname.

Parametry

hostname

The Internet host name.

mxhosts

A list of the MX records found is placed into the array mxhosts.

weight

If the weight array is given, it will be filled with the weight information gathered.

Zwracane wartości

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.

Notatki

Informacja:

This function should not be used for the purposes of address verification. Only the mailexchangers found in DNS are returned, however, according to » RFC 2821 when no mail exchangers are listed, hostname itself should be used as the only mail exchanger with a priority of 0.

Informacja:

For compatibility with Windows before this was implemented, then try the » PEAR class » Net_DNS.

Zobacz też:

  • checkdnsrr() - Check DNS records corresponding to a given Internet host name or IP address
  • dns_get_record() - Fetch DNS Resource Records associated with a hostname
  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • the named(8) manual page

gethostname
getprotobyname
Network Funkcje


Get protocol number associated with protocol name

getmxrr
getprotobynumber
Network Funkcje
PHP Manual

getprotobyname

(PHP 4, PHP 5)

getprotobyname — Get protocol number associated with protocol name

Opis

int getprotobyname ( string $name )

getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.

Parametry

name

The protocol name.

Zwracane wartości

Returns the protocol number, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 getprotobyname() example

<?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
if ($get_prot === FALSE) {
    echo 'Invalid Protocol';
} else {
    echo 'Protocol #' . $get_prot;
}
?>

Zobacz też:

  • getprotobynumber() - Get protocol name associated with protocol number

getmxrr
getprotobynumber
Network Funkcje


Get protocol name associated with protocol number

getprotobyname
getservbyname
Network Funkcje
PHP Manual

getprotobynumber

(PHP 4, PHP 5)

getprotobynumber — Get protocol name associated with protocol number

Opis

string getprotobynumber ( int $number )

getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.

Parametry

number

The protocol number.

Zwracane wartości

Returns the protocol name as a string, lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • getprotobyname() - Get protocol number associated with protocol name

getprotobyname
getservbyname
Network Funkcje


Get port number associated with an Internet service and protocol

getprotobynumber
getservbyport
Network Funkcje
PHP Manual

getservbyname

(PHP 4, PHP 5)

getservbyname — Get port number associated with an Internet service and protocol

Opis

int getservbyname ( string $service , string $protocol )

getservbyname() returns the Internet port which corresponds to service for the specified protocol as per /etc/services.

Parametry

service

The Internet service name, as a string.

protocol

protocol is either "tcp" or "udp" (in lowercase).

Zwracane wartości

Returns the port number, or FALSE if service or protocol is not found.

Przykłady

Przykład #1 getservbyname() example

<?php
$services = array('http', 'ftp', 'ssh', 'telnet', 'imap',
'smtp', 'nicname', 'gopher', 'finger', 'pop3', 'www');

foreach ($services as $service) {
    $port = getservbyname($service, 'tcp');
    echo $service . ": " . $port . "<br />\n";
}
?>

Zobacz też:

  • getservbyport() - Get Internet service which corresponds to port and protocol
  • » http://www.iana.org/assignments/port-numbers for a complete list of port numbers.

getprotobynumber
getservbyport
Network Funkcje


Get Internet service which corresponds to port and protocol

getservbyname
header_register_callback
Network Funkcje
PHP Manual

getservbyport

(PHP 4, PHP 5)

getservbyport — Get Internet service which corresponds to port and protocol

Opis

string getservbyport ( int $port , string $protocol )

getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services.

Parametry

port

The port number.

protocol

protocol is either "tcp" or "udp" (in lowercase).

Zwracane wartości

Returns the Internet service name as a string.

Zobacz też:

  • getservbyname() - Get port number associated with an Internet service and protocol

getservbyname
header_register_callback
Network Funkcje


Call a header function

getservbyport
header_remove
Network Funkcje
PHP Manual

header_register_callback

(No version information available, might only be in SVN)

header_register_callback — Call a header function

Opis

bool header_register_callback ( callback $callback )

Registers a function that will be called when PHP starts sending output.

The callback is executed just after PHP prepares all headers to be sent, and before any other output is sent, creating a window to manipulate the outgoing headers before being sent.

Parametry

callback

Function called just before the headers are sent. It gets no parameters and the return value is ignored.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 header_register_callback() example

<?php

header('Content-Type: text/plain');
header('X-Test: foo');

function foo() {
 foreach (headers_list() as $header) {
   if (strpos($header, 'X-Powered-By:') !== false) {
     header_remove('X-Powered-By');
   }
   header_remove('X-Test');
 }
}

$result = header_register_callback('foo');
echo "a";
?>

Powyższy przykład wyświetli coś podobnego do:

Content-Type: text/plain

a

Notatki

header_register_callback() is executed just as the headers are about to be sent out, so any output from this function can break output.

Informacja:

Headers will only be accessible and output when a SAPI that supports them is in use.

Zobacz też:

  • headers_list() - Returns a list of response headers sent (or ready to send)
  • header_remove() - Remove previously set headers
  • header() - Send a raw HTTP header
getservbyport
header_remove
Network Funkcje


Remove previously set headers

header_register_callback
header
Network Funkcje
PHP Manual

header_remove

(PHP 5 >= 5.3.0)

header_remove — Remove previously set headers

Opis

void header_remove ([ string $name ] )

Removes an HTTP header previously set using header().

Parametry

name

The header name to be removed.

Informacja: This parameter is case-insensitive.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Unsetting specific header.

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove("X-Foo");
?>

Powyższy przykład wyświetli coś podobnego do:

X-Bar: Baz

Przykład #2 Unsetting all previously set headers.

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove();
?>

Powyższy przykład wyświetli coś podobnego do:

Notatki

Uwaga

    This function will remove all headers set by PHP,
    including cookies, session and the X-Powered-By headers.

Informacja:

    Headers will only be accessible and output when a SAPI that supports them
    is in use.

Zobacz też:

  • header() - Send a raw HTTP header
    •

  • headers_sent() - Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło
    •

header_register_callback

header

Network Funkcje


Send a raw HTTP header

header_remove
headers_list
Network Funkcje
PHP Manual

header

(PHP 4, PHP 5)

header — Send a raw HTTP header

Opis

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
?>

Parametry

string

The header string.

There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

<?php
header("HTTP/1.0 404 Not Found");
?>

For FastCGI you must use the following for a 404 response:

<?php
header("Status: 404 Not Found");
?>

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

replace

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>

http_response_code

Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the string is not empty.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
4.4.2 and 5.1.2 | This function now prevents more than one header to be sent at once as a protection against header injection attacks.
4.3.0 | The http_response_code parameter was added.
4.0.4 | The replace parameter was added.

Przykłady

Przykład #1 Download dialog

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

Przykład #2 Caching directives

PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

Informacja:

You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.

Notatki

Informacja:

Headers will only be accessible and output when a SAPI that supports them is in use.

Informacja:

You can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

Informacja:

The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

Informacja:

There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later.

Informacja: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).

Informacja:

HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

<?php
/* Redirect to a different page in the current directory that was requested */
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>

Informacja:

Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.

Zobacz też:

  • headers_sent() - Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło
  • setcookie() - Send a cookie
  • The section on HTTP authentication

header_remove
headers_list
Network Funkcje


Returns a list of response headers sent (or ready to send)

header
headers_sent
Network Funkcje
PHP Manual

headers_list

(PHP 5)

headers_list — Returns a list of response headers sent (or ready to send)

Opis

array headers_list ( void )

headers_list() will return a list of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent().

Zwracane wartości

Returns a numerically indexed array of headers.

Przykłady

Przykład #1 Examples using headers_list()

<?php

/* setcookie() will add a response header on its own */
setcookie('foo', 'bar');

/* Define a custom response header
   This will be ignored by most clients */
header("X-Sample-Test: foo");

/* Specify plain text content in our response */
header('Content-type: text/plain');

/* What headers are going to be sent? */
var_dump(headers_list());

?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  string(23) "X-Powered-By: PHP/5.1.3"
  [1]=>
  string(19) "Set-Cookie: foo=bar"
  [2]=>
  string(18) "X-Sample-Test: foo"
  [3]=>
  string(24) "Content-type: text/plain"
}

Notatki

Informacja:

Headers will only be accessible and output when a SAPI that supports them is in use.

Zobacz też:

  • headers_sent() - Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło
  • header() - Send a raw HTTP header
  • setcookie() - Send a cookie
  • apache_response_headers() - Pobiera wszystkie nagłówki HTTP odpowiedzi serwera
  • http_response_code() - Get or Set the HTTP response code

header
headers_sent
Network Funkcje


Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło

headers_list
http_response_code
Network Funkcje
PHP Manual

headers_sent

(PHP 4, PHP 5)

headers_sent — Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło

Opis

bool headers_sent ([ string &$plik [, int &$linia ]] )

Sprawdza czy już zostały wysłane nagłówki i w którym miejscu to nastąpiło.

Jeśli blok nagłówkowy został już wysłany, to nie można dodawać nowych linii nagłówka za pomocą funkcji header(). Użycie tej funkcji pozwala także zabezpieczyć się przed otrzymywaniem komunikatów błędów związanych z nagłówkami HTTP. Inną możliwością jest stosowanie buforowania wyjścia.

Parametry

plik

Jeśli są podane opcjonalne parametry plik i linia, funkcja headers_sent() umieści nazwę pliku źródłowego i numer linii, w której rozpoczęło się wysyłanie na wyjście, odpowiednio w zmiennych plik i linia.

linia

Numer linii, w której rozpocząło się wysyłanie na wyjście.

Zwracane wartości

headers_sent() zwraca FALSE jeśli nagłówki HTTP nie zostały wysłane, w przeciwnym wypadku zwraca TRUE.

Rejestr zmian

Wersja | Opis
4.3.0 | Zostały dodane opcjonalne parametry plik i linia.

Przykłady

Przykład #1 Przykład użycia headers_sent()

<?php

// If no headers are sent, send one
if (!headers_sent()) {
    header('Location: http://www.example.com/');
    exit;
}

// An example using the optional file and line parameters, as of PHP 4.3.0
// Note that $filename and $linenum are passed in for later use.
// Do not assign them values beforehand.
if (!headers_sent($filename, $linenum)) {
    header('Location: http://www.example.com/');
    exit;

// You would most likely trigger an error here.
} else {

    echo "Headers already sent in $filename on line $linenum\n" .
          "Cannot redirect, for now please click this <a " .
          "href=\"http://www.example.com\">link</a> instead\n";
    exit;
}

?>

Zobacz też:

  • ob_start() - Turn on output buffering
  • trigger_error() - Generates a user-level error/warning/notice message
  • headers_list() - Returns a list of response headers sent (or ready to send)
  • header() - Send a raw HTTP header - szczegółowy opis tego zagadnienia.

headers_list
http_response_code
Network Funkcje


Get or Set the HTTP response code

headers_sent
inet_ntop
Network Funkcje
PHP Manual

http_response_code

(No version information available, might only be in SVN)

http_response_code — Get or Set the HTTP response code

Opis

int http_response_code ([ int $response_code ] )

If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.

Parametry

response_code

The optional response_code will set the response code.

<?php
http_response_code(404);
?>

Zwracane wartości

The current response code. By default the return value is int(200).

Przykłady

Przykład #1 Examples using headers_list()

<?php

// Get the current default response code
var_dump(http_response_code()); // int(200)

// Set our response code
http_response_code(404);

// Get our new response code
var_dump(http_response_code()); // int(404)
?>

Powyższy przykład wyświetli:

Zobacz też:

  • header() - Send a raw HTTP header
  • headers_list() - Returns a list of response headers sent (or ready to send)

headers_sent
inet_ntop
Network Funkcje


Converts a packed internet address to a human readable representation

http_response_code
inet_pton
Network Funkcje
PHP Manual

inet_ntop

(PHP 5 >= 5.1.0)

inet_ntop — Converts a packed internet address to a human readable representation

Opis

string inet_ntop ( string $in_addr )

This function converts a 32bit IPv4, or 128bit IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate string representation.

Parametry

in_addr

A 32bit IPv4, or 128bit IPv6 address.

Zwracane wartości

Returns a string representation of the address lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 inet_ntop() Example

<?php
$packed = chr(127) . chr(0) . chr(0) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.

Zobacz też:

  • long2ip() - Converts an (IPv4) Internet network address into a string in Internet standard dotted format
  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation

http_response_code
inet_pton
Network Funkcje


Converts a human readable IP address to its packed in_addr representation

inet_ntop
ip2long
Network Funkcje
PHP Manual

inet_pton

(PHP 5 >= 5.1.0)

inet_pton — Converts a human readable IP address to its packed in_addr representation

Opis

string inet_pton ( string $address )

This function converts a human readable IPv4 or IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate 32bit or 128bit binary structure.

Parametry

address

A human readable IPv4 or IPv6 address.

Zwracane wartości

Returns the in_addr representation of the given address, or FALSE if a syntactically invalid address is given (for example, an IPv4 address without dots or an IPv6 address without colons).

Przykłady

Przykład #1 inet_pton() Example

<?php
$in_addr = inet_pton('127.0.0.1');

$in6_addr = inet_pton('::1');
?>

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now available on Windows platforms.

Zobacz też:

  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
  • long2ip() - Converts an (IPv4) Internet network address into a string in Internet standard dotted format
  • inet_ntop() - Converts a packed internet address to a human readable representation

inet_ntop
ip2long
Network Funkcje


Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

inet_pton
long2ip
Network Funkcje
PHP Manual

ip2long

(PHP 4, PHP 5)

ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

Opis

int ip2long ( string $ip_address )

The function ip2long() generates an IPv4 Internet network address from its Internet standard format (dotted string) representation.

ip2long() will also work with non-complete IP addresses. Read » http://publibn.boulder.ibm.com/doc_link/en_US/a_doc_lib/libs/commtrf2/inet_addr.htm for more info.

Parametry

ip_address

A standard format address.

Zwracane wartości

Returns the IPv4 address or FALSE if ip_address is invalid.

Rejestr zmian

Wersja | Opis
5.2.10 | Prior to this version, ip2long() would sometimes return a valid number even if passed an value which was not an (IPv4) Internet Protocol dotted address.
5.0.0 | Prior to this version, ip2long() returned -1 on failure.

Przykłady

Przykład #1 ip2long() Example

<?php
$ip = gethostbyname('www.example.com');
$out = "The following URLs are equivalent:<br />\n";
$out .= 'http://www.example.com/, http://' . $ip . '/, and http://' . sprintf("%u", ip2long($ip)) . "/<br />\n";
echo $out;
?>

Przykład #2 Displaying an IP address

This second example shows how to print a converted address with the printf() function in both PHP 4 and PHP 5:

<?php
$ip   = gethostbyname('www.example.com');
$long = ip2long($ip);

if ($long == -1 || $long === FALSE) {
    echo 'Invalid IP, please try again';
} else {
    echo $ip   . "\n";           // 192.0.34.166
    echo $long . "\n";           // -1073732954
    printf("%u\n", ip2long($ip)); // 3221234342
}
?>

Przykład #3 IP validation

ip2long() should not be used as the sole form of IP validation. Combine it with long2ip():

<?php
// make sure IPs are valid. also converts a non-complete IP into
// a proper dotted quad as explained below.
$ip = long2ip(ip2long("127.0.0.1")); // "127.0.0.1"
$ip = long2ip(ip2long("10.0.0")); // "10.0.0.0"
$ip = long2ip(ip2long("10.0.256")); // "10.0.1.0"
?>

Notatki

Informacja:

Because PHP's integer type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

Informacja:

ip2long() will return FALSE for the IP 255.255.255.255 in PHP 5 <= 5.0.2. It was fixed in PHP 5.0.3 where it returns -1 (same as PHP 4).

Zobacz też:

  • long2ip() - Converts an (IPv4) Internet network address into a string in Internet standard dotted format
  • sprintf() - Return a formatted string

inet_pton
long2ip
Network Funkcje


Converts an (IPv4) Internet network address into a string in Internet standard dotted format

ip2long
openlog
Network Funkcje
PHP Manual

long2ip

(PHP 4, PHP 5)

long2ip — Converts an (IPv4) Internet network address into a string in Internet standard dotted format

Opis

string long2ip ( string $proper_address )

The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper address representation.

Parametry

proper_address

A proper address representation.

Zwracane wartości

Returns the Internet IP address as a string.

Zobacz też:

  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address

ip2long
openlog
Network Funkcje


Open connection to system logger

long2ip
pfsockopen
Network Funkcje
PHP Manual

openlog

(PHP 4, PHP 5)

openlog — Open connection to system logger

Opis

bool openlog ( string $ident , int $option , int $facility )

openlog() opens a connection to the system logger for a program.

The use of openlog() is optional. It will automatically be called by syslog() if necessary, in which case ident will default to FALSE.

Parametry

ident

The string ident is added to each message.

option

The option argument is used to indicate what logging options will be used when generating a log message.

openlog() Options
Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
You can use one or more of this options. When using multiple options you need to OR them, i.e. to open the connection immediately, write to the console and include the PID in each message, you will use: LOG_CONS | LOG_NDELAY | LOG_PID

facility

The facility argument is used to specify what type of program is logging the message. This allows you to specify (in your machine's syslog configuration) how messages coming from different facilities will be handled.

openlog() Facilities
Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use, these are not available in Windows
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem

Informacja:

LOG_USER is the only valid log type under Windows operating systems

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • syslog() - Generate a system log message
  • closelog() - Close connection to system logger

long2ip
pfsockopen
Network Funkcje


Open persistent Internet or Unix domain socket connection

openlog
setcookie
Network Funkcje
PHP Manual

pfsockopen

(PHP 4, PHP 5)

pfsockopen — Open persistent Internet or Unix domain socket connection

Opis

resource pfsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )

This function behaves exactly as fsockopen() with the difference that the connection is not closed after the script finishes. It is the persistent version of fsockopen().

Parametry

For parameter information, see the fsockopen() documentation.

Zobacz też:

  • fsockopen() - Open Internet or Unix domain socket connection

openlog
setcookie
Network Funkcje


Send a cookie

pfsockopen
setrawcookie
Network Funkcje
PHP Manual

setcookie

(PHP 4, PHP 5)

setcookie — Send a cookie

Opis

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.

Parametry

All the arguments except the name argument are optional. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire argument is integer, it cannot be skipped with an empty string, use a zero (0) instead.

» RFC 6265 provides the normative reference on how each setcookie() parameter is interpreted.

name

The name of the cookie.

value

The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']

expire

The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

Informacja:

You may notice the expire parameter takes on a Unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT, this is because PHP does this conversion internally.

path

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

domain

The domain that the cookie is available to. Setting the domain to 'www.example.com' will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as 'example.com' will be available to higher subdomains, such as 'www.example.com'. Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.

secure

Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]).

httponly

When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. Added in PHP 5.2.0. TRUE or FALSE

Zwracane wartości

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Przykłady

Some examples follow how to send cookies:

Przykład #1 setcookie() send example

<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5. To see the contents of our test cookie in a script, simply use one of the following examples:

<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>

Przykład #2 setcookie() delete example

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:

<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

Przykład #3 setcookie() and arrays

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
    foreach ($_COOKIE['cookie'] as $name => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name : $value <br />\n";
    }
}
?>

Powyższy przykład wyświetli:

three : cookiethree
two : cookietwo
one : cookieone

Rejestr zmian

Wersja | Opis
5.2.0 | The httponly parameter was added.

Notatki

Informacja:

You can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

Informacja:

If the PHP directive register_globals is set to on then cookie values will also be made into variables. In our examples below, $TestCookie will exist. It's recommended to use $_COOKIE.

Common Pitfalls:

  • Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
  • Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.
  • Because setting a cookie with a value of FALSE will try to delete the cookie, you should not use boolean values. Instead, use 0 for FALSE and 1 for TRUE.
  • Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes.

Multiple calls to setcookie() are performed in the order called.

Zobacz też:

  • header() - Send a raw HTTP header
  • setrawcookie() - Send a cookie without urlencoding the cookie value
  • cookies section
  • » RFC 6265
  • » RFC 2109

pfsockopen
setrawcookie
Network Funkcje


Send a cookie without urlencoding the cookie value

setcookie
socket_get_status
Network Funkcje
PHP Manual

setrawcookie

(PHP 5)

setrawcookie — Send a cookie without urlencoding the cookie value

Opis

bool setrawcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.

Parametry

For parameter information, see the setcookie() documentation.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.2.0 | The httponly parameter was added.

Zobacz też:

  • setcookie() - Send a cookie

setcookie
socket_get_status
Network Funkcje


Alias dla stream_get_meta_data

setrawcookie
socket_set_blocking
Network Funkcje
PHP Manual

socket_get_status

(PHP 4, PHP 5)

socket_get_status — Alias dla stream_get_meta_data()

Opis

Ta funkcja jest aliasem dla: stream_get_meta_data().

setrawcookie
socket_set_blocking
Network Funkcje


Alias dla stream_set_blocking

socket_get_status
socket_set_timeout
Network Funkcje
PHP Manual

socket_set_blocking

(PHP 4, PHP 5)

socket_set_blocking — Alias dla stream_set_blocking()

Opis

Ta funkcja jest aliasem dla: stream_set_blocking().

socket_get_status
socket_set_timeout
Network Funkcje


Alias dla stream_set_timeout

socket_set_blocking
syslog
Network Funkcje
PHP Manual

socket_set_timeout

(PHP 4, PHP 5)

socket_set_timeout — Alias dla stream_set_timeout()

Opis

Ta funkcja jest aliasem dla: stream_set_timeout().

socket_set_blocking
syslog
Network Funkcje


Generate a system log message

socket_set_timeout
RRD
Network Funkcje
PHP Manual

syslog

(PHP 4, PHP 5)

syslog — Generate a system log message

Opis

bool syslog ( int $priority , string $message )

syslog() generates a log message that will be distributed by the system logger.

For information on setting up a user defined log handler, see the syslog.conf (5) Unix manual page. More information on the syslog facilities and option can be found in the man pages for syslog (3) on Unix machines.

Parametry

priority

priority is a combination of the facility and the level. Possible values are:

syslog() Priorities (in descending order)
Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message

message

The message to send, except that the two characters %m will be replaced by the error message string (strerror) corresponding to the present value of errno.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using syslog()

<?php
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
openlog("myScriptLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);

// some code

if (authorized_client()) {
    // do something
} else {
    // unauthorized client!
    // log the attempt
    $access = date("Y/m/d H:i:s");
    syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
}

closelog();
?>

Notatki

On Windows NT, the syslog service is emulated using the Event Log.

Informacja:

Use of LOG_LOCAL0 through LOG_LOCAL7 for the facility parameter of openlog() is not available in Windows.

Zobacz też:

  • openlog() - Open connection to system logger
  • closelog() - Close connection to system logger

socket_set_timeout
RRD
Network Funkcje


RRDtool

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Procedural PECL/rrd example
    • OOP PECL/rrd example
  • RRD Funkcje
    • rrd_create — Creates rrd database file
    • rrd_error — Gets latest error message.
    • rrd_fetch — Fetch the data for graph as array.
    • rrd_first — Gets the timestamp of the first sample from rrd file.
    • rrd_graph — Creates image from a data.
    • rrd_info — Gets information about rrd file
    • rrd_last — Gets unix timestamp of the last sample.
    • rrd_lastupdate — Gets information about last updated data.
    • rrd_restore — Restores the RRD file from XML dump.
    • rrd_tune — Tunes some RRD database file header options.
    • rrd_update — Updates the RRD database.
    • rrd_version — Gets information about underlying rrdtool library
    • rrd_xport — Exports the information about RRD database.
  • RRDCreator — The RRDCreator class
    • RRDCreator::addArchive — Adds RRA - archive of data values for each data source.
    • RRDCreator::addDataSource — Adds data source definition for RRD database.
    • RRDCreator::__construct — Creates new RRDCreator instance
    • RRDCreator::save — Saves the RRD database to a file
  • RRDGraph — The RRDGraph class
    • RRDGraph::__construct — Creates new RRDGraph instance
    • RRDGraph::save — Saves the result of query into image
    • RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph.
    • RRDGraph::setOptions — Sets the options for rrd graph export
  • RRDUpdater — The RRDUpdater class
    • RRDUpdater::__construct — Creates new RRDUpdater instance
    • RRDUpdater::update — Update the RRD database file
syslog
Wstęp
Inne serwisy


Wstęp

The PECL/rrd extension provides bindings to the RRDtool C library. RRDtool is the open source industry standard, high performance data logging and graphing system for time series data.

The RRDtool homepage is » http://www.mrtg.org/rrdtool/.

RRD
Instalacja/Konfiguracja
RRD


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
RRD


Wymagania

You need to install librrd first to be able to use PECL/rrd. Most common option is using of librrd-dev package from your favourite linux distro. PECL/rrd is tested with librrd 1.4.3, older or newer versions might or might not work for you. PECL/rrd installation is tested with PHP 5.3.2 or newer.

Ostrzeżenie

Librrd and hence extension itself aren't mostly thread safe. There are many global and shared states in librrd. It can be dangerous use this extension in multi threaded environments like Apache2 mpm worker. If there are many parallel requests, one request can change some global librrd state of other runnig requests.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/rrd.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
RRD


Przykłady

Spis treści

  • Procedural PECL/rrd example
  • OOP PECL/rrd example
Stałe predefiniowane
Procedural PECL/rrd example
RRD


Procedural PECL/rrd example

Przykład #1 Procedural usage of rrd

<?php
$rrdFile = dirname(__FILE__) . "/speed.rrd";

//create rrd file
rrd_create($rrdFile,
 array(
  "--start",920804400,
  "DS:speed:COUNTER:600:U:U",
  "RRA:AVERAGE:0.5:1:24",
  "RRA:AVERAGE:0.5:6:10"
  )
);

//update rrd file
rrd_update($rrdFile,
 array(
  "920804700:12345",
  "920805000:12357"
  )
);

//graph output
rrd_graph(dirname(__FILE__) . "/speed.png",
 array(
  "--start", "920804400",
  "--end", "920808000",
  "--vertical-label", "m/s",
  "DEF:myspeed=$rrdFile:speed:AVERAGE",
  "CDEF:realspeed=myspeed,1000,*",
  "LINE2:realspeed#FF0000"
 )
);
?>

Przykłady
OOP PECL/rrd example
Przykłady


OOP PECL/rrd example

Przykład #1 OO usage of rrd

<?php
$rrdFile = dirname(__FILE__) . "/speed.rrd";
$outputPngFile = dirname(__FILE__) . "/speed.png";

$creator = new RRDCreator($rrdFile, "now -10d", 500);
$creator->addDataSource("speed:COUNTER:600:U:U");
$creator->addArchive("AVERAGE:0.5:1:24");
$creator->addArchive("AVERAGE:0.5:6:10");
$creator->save();

$updater = new RRDUpdater($rrdFile);
$updater->update(array("speed" => "12345"), "920804700");
$updater->update(array("speed" => "12357"), "920805000");

$graphObj = new RRDGraph($outputPngFile);
$graphObj->setOptions(
    array(
        "--start" => "920804400",
        "--end" => 920808000,
        "--vertical-label" => "m/s",
        "DEF:myspeed=$rrdFile:speed:AVERAGE",
        "CDEF:realspeed=myspeed,1000,*",
        "LINE2:realspeed#FF0000"
    )
);
$graphObj->save();
?>

Procedural PECL/rrd example
RRD Funkcje
Przykłady


RRD Funkcje

Spis treści

  • rrd_create — Creates rrd database file
  • rrd_error — Gets latest error message.
  • rrd_fetch — Fetch the data for graph as array.
  • rrd_first — Gets the timestamp of the first sample from rrd file.
  • rrd_graph — Creates image from a data.
  • rrd_info — Gets information about rrd file
  • rrd_last — Gets unix timestamp of the last sample.
  • rrd_lastupdate — Gets information about last updated data.
  • rrd_restore — Restores the RRD file from XML dump.
  • rrd_tune — Tunes some RRD database file header options.
  • rrd_update — Updates the RRD database.
  • rrd_version — Gets information about underlying rrdtool library
  • rrd_xport — Exports the information about RRD database.
OOP PECL/rrd example
rrd_create
RRD


Creates rrd database file

RRD Funkcje
rrd_error
RRD Funkcje
PHP Manual

rrd_create

(PECL rrd >= 0.9.0)

rrd_create — Creates rrd database file

Opis

bool rrd_create ( string $filename , array $options )

Creates the rdd database file.

Parametry

filename

Filename for newly created rrd file.

options

Options for rrd create - list of strings. See man page of rrd create for whole list of options.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

RRD Funkcje
rrd_error
RRD Funkcje


Gets latest error message.

rrd_create
rrd_fetch
RRD Funkcje
PHP Manual

rrd_error

(PECL rrd >= 0.9.0)

rrd_error — Gets latest error message.

Opis

string rrd_error ( void )

Returns latest global rrd error message.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Latest error message.

rrd_create
rrd_fetch
RRD Funkcje


Fetch the data for graph as array.

rrd_error
rrd_first
RRD Funkcje
PHP Manual

rrd_fetch

(PECL rrd >= 0.9.0)

rrd_fetch — Fetch the data for graph as array.

Opis

array rrd_fetch ( string $filename , array $options )

Gets data for graph output from RRD database file as array. This function has same result as rrd_graph(), but fetched data are returned as array, no image file is created.

Parametry

filename

RRD database file name.

options

Array of options for resolution specification.

Zwracane wartości

Returns information about retrieved graph data.

rrd_error
rrd_first
RRD Funkcje


Gets the timestamp of the first sample from rrd file.

rrd_fetch
rrd_graph
RRD Funkcje
PHP Manual

rrd_first

(PECL rrd >= 0.9.0)

rrd_first — Gets the timestamp of the first sample from rrd file.

Opis

int rrd_first ( string $file [, int $raaindex = 0 ] )

Returns the first data sample from the specified RRA of the RRD file.

Parametry

file

RRD database file name.

raaindex

The index number of the RRA that is to be examined. Default value is 0.

Zwracane wartości

Integer number of unix timestamp, FALSE if some error occurs.

rrd_fetch
rrd_graph
RRD Funkcje


Creates image from a data.

rrd_first
rrd_info
RRD Funkcje
PHP Manual

rrd_graph

(PECL rrd >= 0.9.0)

rrd_graph — Creates image from a data.

Opis

array rrd_graph ( string $filename , array $options )

Creates image for a particular data from RRD file.

Parametry

filename

RRD database file name.

options

Options for generating image. See man page of rrd graph for all possible options. All options (data definitions, variable defintions, etc.) are allowed.

Zwracane wartości

Array with information about generated image is returned, FALSE when error occurs.

rrd_first
rrd_info
RRD Funkcje


Gets information about rrd file

rrd_graph
rrd_last
RRD Funkcje
PHP Manual

rrd_info

(PECL rrd >= 0.9.0)

rrd_info — Gets information about rrd file

Opis

array rrd_info ( string $filename )

Returns information about particular RRD database file.

Parametry

file

RRD database file name.

Zwracane wartości

Array with information about requsted RRD file, FALSE when error occurs.

rrd_graph
rrd_last
RRD Funkcje


Gets unix timestamp of the last sample.

rrd_info
rrd_lastupdate
RRD Funkcje
PHP Manual

rrd_last

(PECL rrd >= 0.9.0)

rrd_last — Gets unix timestamp of the last sample.

Opis

int rrd_last ( string $filename )

Returns the UNIX timestamp of the most recent update of the RRD database.

Parametry

filename

RRD database file name.

Zwracane wartości

Integer as unix timestamp of the most recent data from the RRD database.

rrd_info
rrd_lastupdate
RRD Funkcje


Gets information about last updated data.

rrd_last
rrd_restore
RRD Funkcje
PHP Manual

rrd_lastupdate

(PECL rrd >= 0.9.0)

rrd_lastupdate — Gets information about last updated data.

Opis

array rrd_lastupdate ( string $filename )

Gets array of the UNIX timestamp and the values stored for each date in the most recent update of the RRD database file.

Parametry

file

RRD database file name.

Zwracane wartości

Array of information about last update, FALSE when error occurs.

rrd_last
rrd_restore
RRD Funkcje


Restores the RRD file from XML dump.

rrd_lastupdate
rrd_tune
RRD Funkcje
PHP Manual

rrd_restore

(PECL rrd >= 0.9.0)

rrd_restore — Restores the RRD file from XML dump.

Opis

bool rrd_restore ( string $xml_file , string $rrd_file [, array $options ] )

Restores the RRD file from the XML dump.

Parametry

xml_file

XML filename with the dump of the original RRD database file.

rrd_file

Restored RRD database file name.

options

Array of options for restoring. See man page for rrd restore.

Zwracane wartości

Returns TRUE on success, FALSE otherwise.

rrd_lastupdate
rrd_tune
RRD Funkcje


Tunes some RRD database file header options.

rrd_restore
rrd_update
RRD Funkcje
PHP Manual

rrd_tune

(PECL rrd >= 0.9.0)

rrd_tune — Tunes some RRD database file header options.

Opis

bool rrd_tune ( string $filename , array $options )

Change some options in the RRD dabase header file. E.g. renames the source for the data etc.

Parametry

filename

RRD database file name.

options

Options with RRD database file properties which will be changed. See rrd tune man page for details.

Zwracane wartości

Returns TRUE on success, FALSE otherwise.

rrd_restore
rrd_update
RRD Funkcje


Updates the RRD database.

rrd_tune
rrd_version
RRD Funkcje
PHP Manual

rrd_update

(PECL rrd >= 0.9.0)

rrd_update — Updates the RRD database.

Opis

bool rrd_update ( string $filename , array $options )

Updates the RRD database file. The input data is time interpolated according to the properties of the RRD database file.

Parametry

filename

RRD database file name. This database will be updated.

options

Options for updating the RRD database. This is list of strings. See man page of rrd update for whole list of options.

Zwracane wartości

Returns TRUE on success, FALSE when error occurs.

rrd_tune
rrd_version
RRD Funkcje


Gets information about underlying rrdtool library

rrd_update
rrd_xport
RRD Funkcje
PHP Manual

rrd_version

(PECL rrd >= 1.0.0)

rrd_version — Gets information about underlying rrdtool library

Opis

string rrd_version ( void )

Returns information about underlying rrdtool library.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

String with rrdtool version number e.g. "1.4.3".

rrd_update
rrd_xport
RRD Funkcje


Exports the information about RRD database.

rrd_version
RRDCreator
RRD Funkcje
PHP Manual

rrd_xport

(PECL rrd >= 0.9.0)

rrd_xport — Exports the information about RRD database.

Opis

array rrd_xport ( array $options )

Exports the information about RRD database file. This data can be converted to XML file via user space PHP script and then restored back as RRD database file.

Parametry

options

Array of options for the export, see rrd xport man page.

Zwracane wartości

Array with information about RRD database file, FALSE when error occurs.

rrd_version
RRDCreator
RRD Funkcje


The RRDCreator class

(No version information available, might only be in SVN)

Wstęp

Class for creation of RRD database file.

Krótki opis klasy

RRDCreator {
/* Metody */
public void addArchive ( string $description )
public void addDataSource ( string $description )
public __construct ( string $path [, string $startTime [, int $step = 0 ]] )
public bool save ( void )
}

Spis treści

  • RRDCreator::addArchive — Adds RRA - archive of data values for each data source.
  • RRDCreator::addDataSource — Adds data source definition for RRD database.
  • RRDCreator::__construct — Creates new RRDCreator instance
  • RRDCreator::save — Saves the RRD database to a file
rrd_xport
RRDCreator::addArchive
RRD


Adds RRA - archive of data values for each data source.

RRDCreator
RRDCreator::addDataSource
RRDCreator
PHP Manual

RRDCreator::addArchive

(PECL rrd >= 0.9.0)

RRDCreator::addArchive — Adds RRA - archive of data values for each data source.

Opis

public void RRDCreator::addArchive ( string $description )

Adds RRA definition by description of archive. Archive consists of a number of data values or statistics for each of the defined data-sources (DS). Data sources are defined by method RRDCreator::addDataSource(). You need call this method for each requested archive.

Parametry

description

Definition of archive - RRA. This has same format as RRA definition in rrd create command. See man page of rrd create for more details.

Zwracane wartości

Nie jest zwracana żadna wartość.

RRDCreator
RRDCreator::addDataSource
RRDCreator


Adds data source definition for RRD database.

RRDCreator::addArchive
RRDCreator::__construct
RRDCreator
PHP Manual

RRDCreator::addDataSource

(PECL rrd >= 0.9.0)

RRDCreator::addDataSource — Adds data source definition for RRD database.

Opis

public void RRDCreator::addDataSource ( string $description )

RRD can accept input from several data sources (DS), e.g incomming and outgoing traffic. This method adds data source by description. You need call this method for each data source.

Parametry

description

Definition of data source - DS. This has same format as DS definition in rrd create command. See man page of rrd create for more details.

Zwracane wartości

Nie jest zwracana żadna wartość.

RRDCreator::addArchive
RRDCreator::__construct
RRDCreator


Creates new RRDCreator instance

RRDCreator::addDataSource
RRDCreator::save
RRDCreator
PHP Manual

RRDCreator::__construct

(PECL rrd >= 0.9.0)

RRDCreator::__construct — Creates new RRDCreator instance

Opis

public RRDCreator::__construct ( string $path [, string $startTime [, int $step = 0 ]] )

Creates new RRDCreator instance.

Parametry

path

Path for newly created RRD database file.

startTime

Time for the first value in RRD database. Parameter supports all formats which are supported by rrd create call.

intstep

Base interval in seconds with which data will be fed into the RRD database.

Zwracane wartości

Nie jest zwracana żadna wartość.

RRDCreator::addDataSource
RRDCreator::save
RRDCreator


Saves the RRD database to a file

RRDCreator::__construct
RRDGraph
RRDCreator
PHP Manual

RRDCreator::save

(PECL rrd >= 0.9.0)

RRDCreator::save — Saves the RRD database to a file

Opis

public bool RRDCreator::save ( void )

Saves the RRD database into file, which name is defined by RRDCreator::__construct().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

RRDCreator::__construct
RRDGraph
RRDCreator


The RRDGraph class

(No version information available, might only be in SVN)

Wstęp

Class for exporting data from RRD database to image file.

Krótki opis klasy

RRDGraph {
/* Metody */
public __construct ( string $path )
public array save ( void )
public array saveVerbose ( void )
public void setOptions ( array $options )
}

Spis treści

  • RRDGraph::__construct — Creates new RRDGraph instance
  • RRDGraph::save — Saves the result of query into image
  • RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph.
  • RRDGraph::setOptions — Sets the options for rrd graph export
RRDCreator::save
RRDGraph::__construct
RRD


Creates new RRDGraph instance

RRDGraph
RRDGraph::save
RRDGraph
PHP Manual

RRDGraph::__construct

(PECL rrd >= 0.9.0)

RRDGraph::__construct — Creates new RRDGraph instance

Opis

public RRDGraph::__construct ( string $path )

Creates new RRDGraph instance. This instance is responsible for rendering the result of RRD database query into image.

Parametry

path

Full path for the newly created image.

Zwracane wartości

Nie jest zwracana żadna wartość.

RRDGraph
RRDGraph::save
RRDGraph


Saves the result of query into image

RRDGraph::__construct
RRDGraph::saveVerbose
RRDGraph
PHP Manual

RRDGraph::save

(PECL rrd >= 0.9.0)

RRDGraph::save — Saves the result of query into image

Opis

public array RRDGraph::save ( void )

Saves the result of RRD database query into image defined by RRDGraph::__construct().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Array with information about generated image is returned, FALSE if error occurs.

RRDGraph::__construct
RRDGraph::saveVerbose
RRDGraph


Saves the RRD database query into image and returns the verbose information about generated graph.

RRDGraph::save
RRDGraph::setOptions
RRDGraph
PHP Manual

RRDGraph::saveVerbose

(PECL rrd >= 0.9.0)

RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph.

Opis

public array RRDGraph::saveVerbose ( void )

Saves the RRD database query into image file defined by method RRDGraph::__construct() and returns the verbose information about generated graph, if "-" is used as image filename, image data are also returned in result array.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Array with detailed information about generated image is returned, optionally with image data, FALSE if error occurs.

RRDGraph::save
RRDGraph::setOptions
RRDGraph


Sets the options for rrd graph export

RRDGraph::saveVerbose
RRDUpdater
RRDGraph
PHP Manual

RRDGraph::setOptions

(PECL rrd >= 0.9.0)

RRDGraph::setOptions — Sets the options for rrd graph export

Opis

public void RRDGraph::setOptions ( array $options )

Parametry

options

List of options for the image generation from the RRD database file. It can be list of strings or list of strings with keys for better readability. Read the rrd graph man pages for list of available options.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 RRDGraph::setOptions() examples

<?php
$graphObj->setOptions(array(
    "--start" => "920804400",
    "--end" => 920808000,
    "--vertical-label" => "m/s",
    "DEF:myspeed=$rrdFile:speed:AVERAGE",
    "CDEF:realspeed=myspeed,1000,*",
    "LINE2:realspeed#FF0000"
));
?>

RRDGraph::saveVerbose
RRDUpdater
RRDGraph


The RRDUpdater class

(No version information available, might only be in SVN)

Wstęp

Class for updating RDD database file.

Krótki opis klasy

RRDUpdater {
/* Metody */
public __construct ( string $path )
public bool update ( array $values [, string $time = time() ] )
}

Spis treści

  • RRDUpdater::__construct — Creates new RRDUpdater instance
  • RRDUpdater::update — Update the RRD database file
RRDGraph::setOptions
RRDUpdater::__construct
RRD


Creates new RRDUpdater instance

RRDUpdater
RRDUpdater::update
RRDUpdater
PHP Manual

RRDUpdater::__construct

(PECL rrd >= 0.9.0)

RRDUpdater::__construct — Creates new RRDUpdater instance

Opis

public RRDUpdater::__construct ( string $path )

Creates new RRDUpdater instance. This instance is responsible for updating the RRD database file.

Parametry

path

Filesystem path for RRD database file, which will be updated.

Zwracane wartości

Nie jest zwracana żadna wartość.

RRDUpdater
RRDUpdater::update
RRDUpdater


Update the RRD database file

RRDUpdater::__construct
SAM
RRDUpdater
PHP Manual

RRDUpdater::update

(PECL rrd >= 0.9.0)

RRDUpdater::update — Update the RRD database file

Opis

public bool RRDUpdater::update ( array $values [, string $time = time() ] )

Updates the RRD file defined via RRDUpdater::__construct(). The file is updated with a specific values.

Parametry

values

Data for update. Key is data source name.

time

Time value for updating the RRD with a particulat data. Default value is current time.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws a Exception on error.

Przykłady

Przykład #1 RRDUpdater::update() examples

<?php
$updator = new RRDUpdater("speed.rrd");
//updates the data source "speed" with value "12411"
//for time defined by timestamp "920807700"
$updator->update(array("speed" => "12411"), "920807700");
?>

RRDUpdater::__construct
SAM
RRDUpdater


Simple Asynchronous Messaging

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Connections
    • Messages
    • Messaging operations
    • Publish/Subscribe and subscriptions to topics
    • Error handling
  • SAM Funkcje
    • SAMConnection::commit — Commits (completes) the current unit of work.
    • SAMConnection::connect — Establishes a connection to a Messaging Server
    • SAMConnection::__construct — Creates a new connection to a Messaging Server
    • SAMConnection::disconnect — Disconnects from a Messaging Server
    • SAMConnection::errno — Contains the unique numeric error code of the last executed SAM operation.
    • SAMConnection::error — Contains the text description of the last failed SAM operation.
    • SAMConnection::isConnected — Queries whether a connection is established to a Messaging Server
    • SAMConnection::peek — Read a message from a queue without removing it from the queue.
    • SAMConnection::peekAll — Read one or more messages from a queue without removing it from the queue.
    • SAMConnection::receive — Receive a message from a queue or subscription.
    • SAMConnection::remove — Remove a message from a queue.
    • SAMConnection::rollback — Cancels (rolls back) an in-flight unit of work.
    • SAMConnection::send — Send a message to a queue or publish an item to a topic.
    • SAMConnection::setDebug — Turn on or off additional debugging output.
    • SAMConnection::subscribe — Create a subscription to a specified topic.
    • SAMConnection::unsubscribe — Cancel a subscription to a specified topic.
    • SAMMessage::body — The body of the message.
    • SAMMessage::__construct — Creates a new Message object
    • SAMMessage::header — The header properties of the message.
RRDUpdater::update
Wstęp
Inne serwisy


Wstęp

This extension provides access to the functionality of messaging and queueing systems, such as the IBM WebSphere MQSeries family of products, from PHP scripts. The interface is designed to make it extremely simple to do the more commonly required tasks such as deliver simple text messages to queues while still allowing skilled users to do more complex messaging operations. For many users the complexities of setting up numerous options can be simply ignored.

The SAM extension is a framework that provides a very simple API that can be used to access a number of messaging middleware systems. Currently the package includes built-in support for the MQTT (MQ Telemetry Transport) messaging protocol and support for the IBM Messaging and Queuing middleware products. SAM is designed to be readily extended to support other messaging systems and extension modules may be written in C or PHP.

SAM
Instalacja/Konfiguracja
SAM


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SAM


Wymagania

The SAM extension interfaces to the IBM Messaging and Queuing middleware products using a set of libraries and some client side code referred to as XMS. This package is available as a free download in the guise of IBM support pack IA94. There is a description of this package and download links in the article » Introducing XMS - The IBM Message Service API.

If you intend to use SAM to access the Messaging and Queuing infrastructure within WebSphere MQ then you will also need to have installed a local MQ queue manager or installed the WebSphere MQ clients package. The clients package is freely available as a support pack (» MQC6).

If you are only aiming to experiment with sending messages to and from WebSphere Application Server queues using the WebSphere Platform Messaging protocol (WPM) then you do not need to install the MQC6 package.

After installing these packages you will need to ensure the XMS binary and, if you are using it, the MQ client bin directory are included in the PATH environment variable so that Apache and PHP can find the dependent .DLLs/libraries.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/sam.

The SAM framework and MQTT support can be built and used without any other prerequisites. Support for protocols other than MQTT is provided via a set of libraries and some client side code referred to as XMS.

If you only intend to use the built-in MQTT support then you can build and configure SAM as an extension or simply refer to php_sam.php with a require() or require_once() clause in your PHP script. In this case you need only install the code without building the extension using the pear installer:

pecl install -B SAM

Linux installation steps

The sam extension is supplied as a PECL module, which you should be able to download and install in one step as follows:

pecl install sam
(Depending on your php environment, you will probably need to be root to do this.)

Make sure that the module is loaded by PHP, by adding following line to php.ini:

extension=sam.so
If you intend to use the XMS support to access the IBM Messaging and Queuing family you must also enable the SAM XMS extension.
extension=sam_xms.so

If you cannot use the PEAR installer, you can download the extension and build it manually:

pear download sam          #downloads sam-<version>.tgz
tar -xzf sam-<version>.tgz
cd sam-<version>
phpize
./configure
make
make install               #you may need to be root for this step

To work with the very latest source, you'll need to extract it from SVN and build manually as above.

Windows installation steps

You will probably need to build the sam extension for Windows as there are only a limited range of pre-built binaries available from the SAM website. The extension can be built using the standard Windows extension build procedures.

You will need the PHP source tree for the version of PHP you wish to build the SAM extension against which you can obtain from php.net. This should be unpacked into a working directory of your choice.

You will also need the libraries and headers used by PHP extensions available from http://www.php.net/extra/win32build.zip and this should be unzipped so that is in your working directory.

You should have something like:

c:\php-build\-
              |
              |---php-5.0.5--|---build
              |              |---ext
              |              |--- ...
              |
              |---win32build--|---bin
                              |---include
                              |---lib

You will need a compiler such as the free version of Visual Studio C++ Express from the Microsoft web site. Also you need the Microsoft SDK Microsoft Windows Platform which again can be downloaded from the Microsoft web site.

Obtain the SAM extension source using pear (pecl download sam) or by using SVN and copy the files to a new "sam" directory under the "ext" directory in your PHP source tree.

To build the extension open a build environment window by going to the start

menu->all programs->microsoft platform SDK for windows->
open build environment window->windows 200 build environment->
set windows 2000 build environment (retail)

This should open a command prompt with all the environment variables set up to access the platform SDK etc. You then need to set the environment variables for Visual Studio by issuing the command vcvars32.bat in the window.

Change directory to your working directory e.g. cd c:\php-build. Then make sure the win32build tools are accessible by adding them to the PATH environment variable:

set PATH=..\win32build\bin;%PATH%

Run the buildconf.bat command. This should rebuild the configure.js file.

Run the cscript command with the appropriate options. To build just the SAM extension framework and MQTT support use:

cscript /nologo configure.js --with-sam
To build the SAM framework and the XMS support use:
cscript /nologo configure.js --with-sam --with-sam_xms="c:\program files\ibm\xms"

The additional parameter passed for sam_xms is the installation path to the XMS libraries and runtime that were installed as described under prerequisites at the top of this page.

You can specify whatever other cscript parameters you require to include or exclude items from the php build or select options.

Assuming all has gone well so far you can now finally run a make for the SAM framework!

nmake php_sam.dll
Also if you are using the XMS support you must make the sam_xms extensions:
nmake php_sam_xms.dll

If you have used Visual Studio 2005 to build the DLLs please see below for additional steps that must be carried out before proceeding further.

The DLLs created (php_sam.dll and optionally php_sam_xms.dll) can now be copied to the subdirectory appropriate for your PHP set-up. Make sure that the module(s) are loaded by PHP, by adding following line to php.ini:

extension=php_sam.dll
If you intend to use the XMS support to access the IBM Messaging and Queuing family you must also enable the SAM XMS extension.
extension=php_sam_xms.dll

Additional steps for Visual Studio 2005

If you build the SAM extension with the Microsoft Visual Studio 2005 compiler and tools you need to perform an additional step in the build process to ensure the php_sam.dll is able to link with the C runtime libraries at runtime. This step includes the dependancy manifest into the DLL. Switch to the directory where the php_sam.dll has been generated (usually Release_TS or Debug_TS below the php source directory) and issue the following magic incantation:

mt.exe -manifest php_sam.dll.manifest -outputresource:php_sam.dll;2
If you are using the XMS capabilities you will need to do the same with the SAM XMS DLL:
mt.exe -manifest php_sam_xms.dll.manifest -outputresource:php_sam_xms.dll;2

If you build the SAM extension using the compiler and libraries from Microsoft Visual Studio 2005 you will also need to ensure that the runtime components are installed on the system on which you intend to use SAM. This can be accomplished by installing Visual Studio 2005 or by using the freely distributable » runtime package.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Protocol support and mapping

The SAM framework can be extended to support other messaging protocols and connection mechanisms. To add support for a new protocol or connection library a support class has to be defined, either as a C extension or as a PHP script, and a "factory" script must be created. The support class must implement all the methods of the SAMConnection class though it should not inherit from SAMConnection. The factory script will be called by the SAM framework to create an instance of the implemented class. The way SAM chooses which factory to call is based on the protocol specified as the first parameter of the "connect" call.

By default the built-in MQTT support will be used if a connect call specifies a protocol of SAM_MQTT ("mqtt"), for any other protocol SAM will attempt to use the XMS support extension. To add support for additional protocols or to modify the default behavior entries may be added to php.ini in the [sam] section. The default mapping is equivalent to the following entries:

[sam]
sam.factory.mqtt=mqtt
sam.factory.wmq=xms
sam.factory.wmq:client=xms
sam.factory.wmq:bindings=xms
sam.factory.wpm=xms
sam.factory.rtt=xms
As can be seen from these examples the entries take the form of "sam.factory.pppp=xxx" where pppp is the protocol string specified on the connect call and xxx is a factory suffix. Note: SAM defines constants for these protocol strings such that SAM_WMQ=wmq, SAM_WPM=wpm, SAM_RTT=rtt, SAM_MQTT=mqtt, etc.

When identifying the support code to use on a connect call SAM looks up the protocol name in the php.ini entries and then invokes a factory script named sam_factory_xxx.php. If no entry is found the support will default to XMS.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

SAM_AUTO (string)
Automatic behaviour
SAM_BOOLEAN (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_BUS (string)
Connect attribute used to set the name of the enterprise service bus to connect to.
SAM_BYTE (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_BYTES (string)
Message body type descriptor.
SAM_CORRELID (string)
Attribute used on receive, send and remove requests to identify specific messages.
SAM_DELIVERYMODE (string)
Message header property.
SAM_DOUBLE (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_ENDPOINTS (string)
Connect attribute used to define the possible endpoints to connect to.
SAM_FLOAT (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_HOST (string)
Connect attribute used to set the hostname of the required messaging server.
SAM_INT (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_LONG (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_MANUAL (string)
Manual (script controlled) behaviour
SAM_MESSAGEID (string)
Attribute used on receive and remove requests to identify specific messages.
SAM_MQTT (string)
Connect protocol definition for selecting the MQTT (MQ Telemetry Transport) protocol.
SAM_MQTT_CLEANSTART (bool)
Optional connect option to indicate to an MQTT server that all previous connection data for this client should be removed and that subscriptions should be deleted when the client disconnects explicitly or unexpectedly.
SAM_NON_PERSISTENT (string)
Connect attribute value used to request messages are not made persistent on the messaging server.
SAM_PASSWORD (string)
Connect attribute used to define the password to be used for the user account being used to connect to a messaging server that requires authorisation for connections.
SAM_PERSISTENT (string)
Connect attribute value used to request messages are made persistent on the messaging server to protect against loss of messages in the event of failure.
SAM_PORT (string)
Connect attribute used to set the port number on which to communicate with the messaging server.
SAM_PRIORITY (string)
Option name used on send requests to specify a delivery priority value.
SAM_REPLY_TO (string)
Message property used to specify the queue identity on to which the script expects response or reply messages to be posted.
SAM_RTT (string)
Connect protocol definition for selecting the IBM Realtime Transport protocol for communication with a business integration messaging server.
SAM_STRING (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_TARGETCHAIN (string)
Connection attribute used to set the required target chain identifier.
SAM_TEXT (string)
Message body type descriptor.
SAM_TIMETOLIVE (string)
Message send option name used to specify the length of time a message should be retained in milliseconds.
SAM_TRANSACTIONS (string)
Connection attribute used to set required transactional behaviour. May be set to SAM_AUTO (default) or SAM_MANUAL.
SAM_USERID (string)
Connect attribute used to define the account to being used to connect to a messaging server that requires authorisation for connections.
SAM_WAIT (string)
Receive property used to specify the wait timeout to be used when receiving a message from a queue or subscription.
SAM_WMQ (string)
Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with the desired messaging server.
SAM_WMQ_BINDINGS (string)
Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with a local messaging server.
SAM_WMQ_CLIENT (string)
Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with a remote messaging server.
SAM_WMQ_TARGET_CLIENT (string)
Option name used on send requests to specify the target client mode. This can either be default to 'jms' or 'mq'. The default is 'jms' which means an RFH2 header is sent with the message whereas the 'mq' setting means no RFH2 is included.
SAM_WPM (string)
Connect protocol definition for selecting the IBM WebSphere Platform Messaging protocol for communication with a WebSphere Application Server messaging server.
Typy zasobów
Przykłady
SAM


Przykłady

Spis treści

  • Connections
  • Messages
  • Messaging operations
  • Publish/Subscribe and subscriptions to topics
  • Error handling
Stałe predefiniowane
Connections
SAM


Connections

In order to perform any messaging and queueing functions a connection must be established with a messaging server by creating a SAMConnection object and calling its "connect" method, with a set of connection properties, to connect the PHP script to the messaging server. Until such time as the SAMConnection object is destroyed the connection will be maintained and available for use. All SAMConnection objects are destroyed when the PHP script exits.

A set of default properties may be used in connecting to a messaging server but as a minimum the PHP script must specify a protocol to be used.

Przykład #1 Creating a connection and connecting to a remote WebSphere MQSeries Messaging Server

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'myhost.mycompany.com',
                              SAM_PORT => 1506,
                              SAM_BROKER => 'mybroker'));
?>

Przykład #2 Creating a connection and connecting to a remote WebSphere Application Server

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WPM, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1',
                              SAM_TARGETCHAIN => 'InboundBasicMessaging'));
?>

Przykład #3 Creating a connection and connecting to an MQTT server

<?php
$conn = new SAMConnection();
$conn->connect(SAM_MQTT, array(SAM_HOST => 'myhost.mycompany.com',
                               SAM_PORT => 1883));
?>

Przykłady
Messages
Przykłady


Messages

Messages sent to and received from queues are represented by the SAMMessage object. The SAMMessage object encapsulates the body of the message (if one exists) and the header properties associated with the message. A SAMMessage object is either supplied as a parameter to a messaging operation or returned as a result.

Przykład #1 Creating a message with a simple text body

<?php
$msg = new SAMMessage('This is a simple text message');
?>

Messages may have header properties associated with them that provide control over the transport of the message or further information to the receiving application. By default message properties are delivered to the underlying messaging system as strings and in this case they may be set with the following simple syntax:

Przykład #2 Setting a text format property using the default syntax

<?php
$msg->header->myPropertyName = 'textData';
?>

If it is desired to pass type information an alternative syntax may be used where the value and the type hint are passed in an associative array:

Przykład #3 Setting a property using a type hint

<?php
$msg->header->myPropertyName = array(3.14159, SAM_FLOAT);
?>

Properties may also be extracted from the header of a message.

Przykład #4 Retrieving a property from a message header

<?php
$myProperty = $msg->header->myPropertyName;
?>

Connections
Messaging operations
Przykłady


Messaging operations

All messaging operations are performed through calls to methods on the connection object. To add a message to a queue the "send" method is used, to obtain a message from a queue the "receive" method is used. Other methods provide publish and subscribe functionality and control of transaction boundaries.

Przykład #1 Adding a message to a queue and receiving a response

<?php
$msg = new SAMMessage('This is a simple text message');
$msg->header->SAM_REPLY_TO = 'queue://receive/test';
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
  // The Send failed!
  echo "Send failed ($conn->errno) $conn->error";
} else {
  $resp = $conn->receive('queue://receive/test', array(SAM_CORRELID => $correlid));
}
?>

Messages
Publish/Subscribe and subscriptions to topics
Przykłady


Publish/Subscribe and subscriptions to topics

SAM allows messages to be sent either to queues or, for WebSphere MQ and WPM, to publish/subscribe topics. A topic destination is specified to SAM in the usual way, i.e. in the form 'topic://fred', rather than the form 'queue://AQUEUE' used for point to point operation. To use publish/subscribe it is simply necessary to specify the correct broker name on the SAMConnect "connect" call and the desired topic in the destination argument to the SAMConnect "send" and "receive" calls. The PHP interface is otherwise identical to the point to point model.

By default, SAM creates non-durable subscriptions when using publish/subscribe. This means that if a client application is inactive when messages are published to a topic, then it will not receive them when it subsequently restarted. SAM does also allow durable subscriptions to be made to topics when using WPM or WebSphere MQ publish/subscribe. The purpose of these subscriptions is to allow data to be received by a client application even if that client was not active at the time the data was published.

Durable subscriptions are specified by using the SAMConnect "subscribe" call. This method takes the destination topic as an input parameter and returns a subscription identifier that may be used on subsequent "receive" calls. When the subscription is no longer required the SAMConnection "unsubscribe" method should be used to delete the subscription.

Przykład #1 Creating a durable subscription to a topic

<?php

$subName = $conn->subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?>

Przykład #2 Subscribing to a topic using a WebSphere Platform Messaging (WPM) server

<?php
$conn = new SAMConnection();
// Note: For pub/sub on WPM, when connecting the name of a messaging engine
//   to hold the durable subscription (SAM_WPM_DUR_SUB_HOME) must be specified.
$conn->connect(SAM_WMQ, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1',
                              SAM_TARGETCHAIN => 'InboundBasicMessaging',
                              SAM_WPM_DUR_SUB_HOME => 'MyMachineNode01.server1-Bus1'));

$subName = $conn->subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?>

Przykład #3 Receiving published data using a durable subscription

<?php

$msg = $conn->receive($subName);
if ($msg) {
   echo "Received a message OK";
} else {
   echo "The receive failed";
}

?>

Przykład #4 Deleting a durable subscription to a topic

<?php

if (!$conn->unsubscribe($subName)) {
   echo "Unsubscribe failed";
}

?>

Messaging operations
Error handling
Przykłady


Error handling

All SAMConnection methods that provide access to messaging operations return FALSE if an error occurred in processing the request. In addition the SAMConnection object has two properties, "errno" and "error", that provide respectively the error number and text description of the last error to occur on the connection.

Przykład #1 Handling an error from a method that returns no result

<?php
if (!$conn->commit()) {
    // The commit failed!
    echo "Commit failed ($conn->errno) $conn->error";
}
?>

Przykład #2 Handling an error from a method that returns a result

<?php
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
  // The Send failed!
  echo "Send failed ($conn->errno) $conn->error";
} else {
  /* ... */
}
?>

Publish/Subscribe and subscriptions to topics
SAM Funkcje
Przykłady


SAM Funkcje

Klasy predefiniowane

SAMConnection

Object representing a connection to a Messaging Server

Konstruktor

  • new SAMConnection - construct a new connection object to allow connection to a messaging infrastructure.

Metody

  • commit - a method that commits (successfully completes) an in-flight unit of work.

  • connect - a method that connects a PHP script to a messaging server.

  • disconnect - a method that disconnects a PHP script from a messaging server.

  • isConnected - a method that checks whether a PHP script is connected to a messaging server.

  • peek - a method that receives a message from a queue without removing it from the queue.

  • peekAll - a method that receives one or messages from a queue without removing them from the queue.

  • receive - a method that receives a message from a queue or subscription.

  • remove - a method that removes a message from a queue.

  • rollback - a method that cancels (rolls back) an in-flight unit of work.

  • send - a method that sends a message to a queue or posts to a topic

  • setDebug - a method that switches additional debugging output on or off

  • subscribe - a method that creates a subscription to one or more topics

  • unsubscribe - a method that destroys a subscription to one or more topics

Właściwości

  • errno - the numeric error code for the last encountered error on this connection. This property is set to 0 if the last operation was successful.

  • error - the text description for the last encountered error on this connection

SAMMessage

Object representing a message to be sent or received

Konstruktor

  • new SAMMessage - construct a new message.

Właściwości

  • body - the body of the message.

  • header - the header properties of the message.

Spis treści

  • SAMConnection::commit — Commits (completes) the current unit of work.
  • SAMConnection::connect — Establishes a connection to a Messaging Server
  • SAMConnection::__construct — Creates a new connection to a Messaging Server
  • SAMConnection::disconnect — Disconnects from a Messaging Server
  • SAMConnection::errno — Contains the unique numeric error code of the last executed SAM operation.
  • SAMConnection::error — Contains the text description of the last failed SAM operation.
  • SAMConnection::isConnected — Queries whether a connection is established to a Messaging Server
  • SAMConnection::peek — Read a message from a queue without removing it from the queue.
  • SAMConnection::peekAll — Read one or more messages from a queue without removing it from the queue.
  • SAMConnection::receive — Receive a message from a queue or subscription.
  • SAMConnection::remove — Remove a message from a queue.
  • SAMConnection::rollback — Cancels (rolls back) an in-flight unit of work.
  • SAMConnection::send — Send a message to a queue or publish an item to a topic.
  • SAMConnection::setDebug — Turn on or off additional debugging output.
  • SAMConnection::subscribe — Create a subscription to a specified topic.
  • SAMConnection::unsubscribe — Cancel a subscription to a specified topic.
  • SAMMessage::body — The body of the message.
  • SAMMessage::__construct — Creates a new Message object
  • SAMMessage::header — The header properties of the message.
Error handling
SAMConnection::commit
SAM


Commits (completes) the current unit of work.

SAM Funkcje
SAMConnection::connect
SAM Funkcje
PHP Manual

SAMConnection::commit

(PECL sam >= 0.1.0)

SAMConnection::commit — Commits (completes) the current unit of work.

Opis

bool SAMConnection::commit ( void )

Calling the "commit" method on a Connection object commits (completes) all in-flight transactions that are part of the current unit of work.

Zwracane wartości

This method returns FALSE if an error occurs.

Przykłady

Przykład #1 Committing the current unit of work

<?php
  if (!$conn->commit()) {
    // The commit failed!
    echo "Commit failed ($conn->errno) $conn->error";
  }
?>

Zobacz też:

  • SAMConnection::rollback

SAM Funkcje
SAMConnection::connect
SAM Funkcje


Establishes a connection to a Messaging Server

SAMConnection::commit
SAMConnection::__construct
SAM Funkcje
PHP Manual

SAMConnection::connect

(PECL sam >= 0.1.0)

SAMConnection::connect — Establishes a connection to a Messaging Server

Opis

bool SAMConnection::connect ( string $protocol [, array $properties ] )

Calling the "connect" method on a SAMConnection object connects the PHP script to a messaging server. No messages can be sent or received until a connection is made.

Parametry

Zwracane wartości

This method returns FALSE if an error occurs.

Przykłady

Przykład #1 Creating a connection to a Messaging Server using the IBM MQSeries protocol (WMQ)

<?php

$conn->connect(SAM_WMQ, array(SAM_HOST => 'Myhost.myco.com', SAM_PORT => 1506, SAM_BROKER => 'MyBroker'));

?>

Przykład #2 Creating a connection with application transaction control and default host and port values

<?php

$conn->connect(SAM_WMQ, array(SAM_BROKER => 'MyBroker', SAM_TRANSACTIONS => SAM_MANUAL));

?>

Przykład #3 Creating a connection to a Messaging Server using the IBM WebSphere Platform Messaging protocol (WPM)

<?php

$conn->connect(SAM_WPM, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1', SAM_TARGETCHAIN => 'InboundBasicMessaging'));

?>

Zobacz też:

  • SAMConnection::isConnected
  • SAMConnection::disconnect

SAMConnection::commit
SAMConnection::__construct
SAM Funkcje


Creates a new connection to a Messaging Server

SAMConnection::connect
SAMConnection::disconnect
SAM Funkcje
PHP Manual

SAMConnection::__construct

(PECL sam >= 0.1.0)

SAMConnection::__construct — Creates a new connection to a Messaging Server

Opis

SAMConnection::__construct() ( void )

Creates a new SAMConnection object.

Przykłady

Przykład #1 Creating a connection object and connecting to a Messaging Server

<?php

$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => localhost, SAM_PORT => 1414, SAM_BROKER => 'bull'));

?>

SAMConnection::connect
SAMConnection::disconnect
SAM Funkcje


Disconnects from a Messaging Server

SAMConnection::__construct
SAMConnection::errno
SAM Funkcje
PHP Manual

SAMConnection::disconnect

(PECL sam >= 0.1.0)

SAMConnection::disconnect — Disconnects from a Messaging Server

Opis

bool SAMConnection::disconnect ( void )

Calling the "disconnect" method on a SAMConnection object disconnects the PHP script from a messaging server. No messages can be sent or received after a connection has been disconnected.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Disconnecting from a Messaging Server

<?php

$conn->disconnect();

?>

Zobacz też:

  • SAMConnection::isConnected
  • SAMConnection::connect

SAMConnection::__construct
SAMConnection::errno
SAM Funkcje


Contains the unique numeric error code of the last executed SAM operation.

SAMConnection::disconnect
SAMConnection::error
SAM Funkcje
PHP Manual

SAMConnection::errno

(PECL sam >= 0.1.0)

SAMConnection::errno — Contains the unique numeric error code of the last executed SAM operation.

Description

int $SAMConnection->errno;

Contains the numeric error code of the last executed SAM operation on this connection. If the last operation completed successfully this property contains 0.

Zwracane wartości

An integer greater than zero indicates the last error type encountered on the connection. Zero indicates that the last operation on this connection completed successfully.

Przykłady

Przykład #1 Using the error number and description properties

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'localhost', SAM_PORT => 1506));
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

Zobacz też:

  • SAMConnection::error

SAMConnection::disconnect
SAMConnection::error
SAM Funkcje


Contains the text description of the last failed SAM operation.

SAMConnection::errno
SAMConnection::isConnected
SAM Funkcje
PHP Manual

SAMConnection::error

(PECL sam >= 0.1.0)

SAMConnection::error — Contains the text description of the last failed SAM operation.

Opis

string $SAMConnection->error;

Contains the text description of the last failed SAM operation on this connection. If the last operation completed successfully this property contains an empty string.

Zwracane wartości

A string containing the text description of the last error type encountered on the connection. An empty string indicates that the last operation on this connection completed successfully.

Przykłady

Przykład #1 Using the error number and description properties

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'localhost', SAM_PORT => 1506));
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

Zobacz też:

  • SAMConnection::errno

SAMConnection::errno
SAMConnection::isConnected
SAM Funkcje


Queries whether a connection is established to a Messaging Server

SAMConnection::error
SAMConnection::peek
SAM Funkcje
PHP Manual

SAMConnection::isConnected

(PECL sam >= 0.1.0)

SAMConnection::isConnected — Queries whether a connection is established to a Messaging Server

Opis

bool SAMConnection::isConnected ( void )

Calling the "isConnected" method on a Connection object will check whether the PHP script is connected to a messaging server. No messages can be sent or received unless a connection has been established with a Messaging server.

Zwracane wartości

This method returns TRUE if the SAMConnection object is successfully connected to a Messaging server or FALSE otherwise.

Przykłady

Przykład #1 Checking whether there us a connection to a Messaging Server

<?php

if ($conn->isConnected()) {
  echo 'Connection is active.';
} else {
  echo 'No active connection!';
}

?>

Zobacz też:

  • SAMConnection::disconnect
  • SAMConnection::connect

SAMConnection::error
SAMConnection::peek
SAM Funkcje


Read a message from a queue without removing it from the queue.

SAMConnection::isConnected
SAMConnection::peekAll
SAM Funkcje
PHP Manual

SAMConnection::peek

(PECL sam >= 0.1.0)

SAMConnection::peek — Read a message from a queue without removing it from the queue.

Opis

SAMMessage SAMConnection::peek ( string $target [, array $properties ] )

Parametry

target

The identity of the queue from which to peek the message.

properties

An optional associative array of properties describing other parameters to control the peek operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of the message. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of the message which is to be peeked.

Zwracane wartości

This method returns a SAMMessage object or FALSE if an error occurs.

Przykłady

Przykład #1 Retrieve the next message from a queue without removing it

<?php
$msg = $conn->peek('queue://receive/test');

if (!$msg) {
  // The peek failed!
  echo "Peek failed ($conn->errno) $conn->error";
}
?>

Przykład #2 Retrieve a specific message from a queue without removing it from the queue

<?php

$msg = $conn->peek('queue://receive/test', array(SAM_MESSAGEID => $messageId));

?>

Zobacz też:

  • SAMConnection::peekAll

SAMConnection::isConnected
SAMConnection::peekAll
SAM Funkcje


Read one or more messages from a queue without removing it from the queue.

SAMConnection::peek
SAMConnection::receive
SAM Funkcje
PHP Manual

SAMConnection::peekAll

(PECL sam >= 0.2.0)

SAMConnection::peekAll — Read one or more messages from a queue without removing it from the queue.

Opis

array SAMConnection::peekAll ( string $target [, array $properties ] )

Parametry

target

The identity of the queue from which messages should be peeked.

properties

An optional associative array of properties describing other parameters to control the peek operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of messages to be peeked. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of a message which is to be peeked.

Zwracane wartości

This method returns an array of SAMMessage objects or FALSE if an error occurs.

Przykłady

Przykład #1 Retrieve all messages in a queue without removing them

<?php
$msgArray = $conn->peekAll('queue://receive/test');
if ($msgArray) {
   foreach ( $msgArray as $key => $msg) {
       echo "Message $key: body = $msg->body\n";
   }
} else {
   echo "PeekAll failed ($conn->errno) $conn->error";
}
?>

Przykład #2 Retrieve all messages from a queue with a matching correlation id

<?php

   $msgArray = $conn->peekAll('queue://receive/test', array(SAM_CORRELID => $correlId ));
   if ($msgArray) {

      foreach ( $msgArray as $key => $msg) {
            echo "Message $key: body = $msg->body\n";
         }
   } else {
      echo "PeekAll failed ($conn->errno) $conn->error";
   }

?>

Zobacz też:

  • SAMConnection::peek

SAMConnection::peek
SAMConnection::receive
SAM Funkcje


Receive a message from a queue or subscription.

SAMConnection::peekAll
SAMConnection::remove
SAM Funkcje
PHP Manual

SAMConnection::receive

(PECL sam >= 0.1.0)

SAMConnection::receive — Receive a message from a queue or subscription.

Opis

SAMMessage SAMConnection::receive ( string $target [, array $properties ] )

Parametry

target

The identity of the queue, topic or subscription from which to receive the message.

properties

An optional associative array of properties describing other parameters to control the receive operation.

Property name | Possible values
SAM_CORRELID | Used to request selection of the message to receive based upon the correlation id string of the message.
SAM_MESSAGEID | Used to request selection of the message to receive based upon the message id string of the message.
SAM_WAIT | Timeout value in milliseconds to control how long the request should block waiting to receive a message before returning with a failure if no message is available on the queue or topic. The default value is 0 meaning wait indefinitely and should be used with caution as the request may wait until the overall PHP script processing time limit has expired if no message becomes available.

Zwracane wartości

This method returns a SAMMessage object or FALSE if an error occurs.

Przykłady

Przykład #1 Receiving a message from a queue

<?php
$msg = $conn->receive('queue://receive/test');

if (!$msg) {
  // The receive failed!
  echo "Receive failed ($conn->errno) $conn->error";
}
?>

Przykład #2 Receiving a message from a queue with options

In this example the SAM_CORRELID option is used to specify a correlation id string to be used to identify the message to receive. A wait timeout of 10 seconds is also specified.

<?php

$msg = $conn->receive('queue://receive/test', array(SAM_CORRELID => $token, SAM_WAIT => 10000));

?>

Przykład #3 Receiving a message from a subscription

In this example we show how to receive a message from a subscription id.

<?php
$msg = $conn->receive($subscriptionName);

if (!$msg) {
  // The receive failed!
  echo "Receive failed ($conn->errno) $conn->error";
}
?>

Please note that $subscriptionName is a subscription id returned from an earlier subscribe call.

Zobacz też:

  • SAMConnection::send

SAMConnection::peekAll
SAMConnection::remove
SAM Funkcje


Remove a message from a queue.

SAMConnection::receive
SAMConnection::rollback
SAM Funkcje
PHP Manual

SAMConnection::remove

(PECL sam >= 0.1.0)

SAMConnection::remove — Remove a message from a queue.

Opis

SAMMessage SAMConnection::remove ( string $target [, array $properties ] )

Removes a message from a queue.

Parametry

target

The identity of the queue from which to remove the message.

properties

An optional associative array of properties describing other parameters to control the remove operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of the message. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of the message which is to be removed.

Zwracane wartości

This method returns FALSE if an error occurs.

Przykłady

Przykład #1 Removing a message from a queue by message id

<?php
if (!$conn->remove('queue://receive/test', array(SAM_MESSAGEID => $messageId))) {
  // The remove failed!
  echo "Remove failed ($conn->errno) $conn->error";
}
?>

SAMConnection::receive
SAMConnection::rollback
SAM Funkcje


Cancels (rolls back) an in-flight unit of work.

SAMConnection::remove
SAMConnection::send
SAM Funkcje
PHP Manual

SAMConnection::rollback

(PECL sam >= 0.1.0)

SAMConnection::rollback — Cancels (rolls back) an in-flight unit of work.

Opis

bool SAMConnection::rollback ( void )

Rolls back an in-flight unit of work.

Zwracane wartości

This method returns FALSE if an error occurs.

Przykłady

Przykład #1 Cancelling an in-flight unit of work

<?php
if (!$conn->rollback()) {
  // The rollback failed!
  echo "Rollback failed ($conn->errno) $conn->error";
}
?>

Zobacz też:

  • SAMConnection::commit

SAMConnection::remove
SAMConnection::send
SAM Funkcje


Send a message to a queue or publish an item to a topic.

SAMConnection::rollback
SAMConnection::setDebug
SAM Funkcje
PHP Manual

SAMConnection::send

(PECL sam >= 0.1.0)

SAMConnection::send — Send a message to a queue or publish an item to a topic.

Opis

string SAMConnection::send ( string $target , SAMMessage $msg [, array $properties ] )

The "send" method is used to send a message to a specific queue or to publish to a specific topic. The method returns a correlation id that can be used as a selector to identify reply or response messages when these are requested.

Parametry

target

If sending a message, the identity of the queue (queue://queuename) or if publishing to a topic the identity of the topic (topic://topicname) to which the message is to be delivered.

msg

The message to be sent or published.

properties

An optional associative array of properties describing other parameters to control the receive operation.

Property name | Possible values
SAM_DELIVERYMODE | Indicates whether the messaging server should ensure delivery or whether it is acceptable for messages to be lost in the case of system failures. The value of this property may be set to either SAM_PERSISTENT, to indicate that message loss is not acceptable, or SAM_NON_PERSISTENT, if message loss is acceptable. The resulting behaviour of the send will vary depending on the capabilities of the messaging server the PHP script is currently connected to. If the server does not support persistent messages and SAM_PERSISTENT is specified the send request will fail with an error indication showing the capability is not available.
SAM_PRIORITY | A numeric value between 0 and 9 indicating the desired message delivery priority. A priority value of 0 indicates the lowest priority while 9 indicates highest priority. If no priority is specified a default will be assigned which is dependent on the messaging server being used.
SAM_CORRELID | A string to be assigned as a correlation id for this message. If no value is given the messaging server may assign a value automatically.
SAM_TIMETOLIVE | A time in milliseconds indicating how long the messaging server should retain the message on a queue before discarding it. The default value is 0 indicating the message should be retained indefinitely.
SAM_WMQ_TARGET_CLIENT | This property is only valid when using WebSphere MQ and indicates whether or not an RFH2 header should be included with the message. This option may be set to either 'jms' or 'mq'. The default is 'jms' which means that an RFH2 header is included. If the value 'mq' is specified then no RFH2 is included with the message.

Zwracane wartości

A correlation id string that can be used in a subsequent receive call as a selector to obtain any reply or response that has been requested or FALSE if an error occurred.

Informacja:

A correlation id will only be returned for a successful send to a queue destination (queue://xxxx) in which case it will reflect the message identity of the message on the queue. In the case of a send being used to publish data to a topic the return value will be TRUE as no correlation id is available for return.

Przykłady

Przykład #1 Send a message to a queue

<?php
$msg = new SAMMessage('This is a simple text message');
$correlId = $conn->send('queue://send/test', $msg);
if (!$correlId) {
    // The send failed!
    echo "Send failed ($conn->errno) $conn->error";
}

?>

Przykład #2 Publish a message to a topic

<?php
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

Przykład #3 Send a request and receive a response

<?php
$msg = new SAMMessage('This is a simple text message');
$msg->header->SAM_REPLY_TO = 'queue://receive/test';
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
} else {
    $resp = $conn->receive('queue://receive/test', array(SAM_CORRELID => $correlid));
}
?>

Zobacz też:

  • SAMConnection::receive

SAMConnection::rollback
SAMConnection::setDebug
SAM Funkcje


Turn on or off additional debugging output.

SAMConnection::send
SAMConnection::subscribe
SAM Funkcje
PHP Manual

SAMConnection::setDebug

(PECL sam >= 1.1.0)

SAMConnection::setDebug — Turn on or off additional debugging output.

Opis

The "setdebug" method is used to turn on or off additional debugging output. The SAM framework will provide method/function entry and exit trace data plus additional information. Protocol specific implementations also provide extra output.

void SAMConnection::setDebug ( bool $switch )

Parametry

switch

If this parameter is set to TRUE additional debugging output will be provided. If the value is set to FALSE output of additional information will be stopped.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Turn on debugging output

<?php
$conn->setdebug(TRUE);
?>

Przykład #2 Turn off debugging output

<?php
$conn->setdebug(FALSE);
?>

SAMConnection::send
SAMConnection::subscribe
SAM Funkcje


Create a subscription to a specified topic.

SAMConnection::setDebug
SAMConnection::unsubscribe
SAM Funkcje
PHP Manual

SAMConnection::subscribe

(PECL sam >= 0.1.0)

SAMConnection::subscribe — Create a subscription to a specified topic.

Opis

string SAMConnection::subscribe ( string $targetTopic )

The "subscribe" method is used to create a new subscription to a specified topic.

Parametry

targetTopic

The identity of the topic (topic://topicname) to subscribe to.

Zwracane wartości

A subscription identifier that can be used in a subsequent receive call as a selector to obtain any topic data or FALSE if an error occurred. The subscription identifier should be used in the receive call in place of the simple topic name.

Przykłady

Przykład #1 Subscribe to a topic

<?php
$subid = $conn->subscribe('topic://A');
if (!$subid) {
  // The subscribe failed!
  echo "Subscribe failed ($conn->errno) $conn->error";
}
?>

Zobacz też:

  • SAMConnection::unsubscribe

SAMConnection::setDebug
SAMConnection::unsubscribe
SAM Funkcje


Cancel a subscription to a specified topic.

SAMConnection::subscribe
SAMMessage::body
SAM Funkcje
PHP Manual

SAMConnection::unsubscribe

(PECL sam >= 0.1.0)

SAMConnection::unsubscribe — Cancel a subscription to a specified topic.

Opis

bool SAMConnection::unsubscribe ( string $subscriptionId [, string $targetTopic ] )

The "unsubscribe" method is used to delete an existing subscription to a specified topic.

Parametry

subscriptionId

The identifier of an existing subscription as returned by a call to the subscribe method.

Zwracane wartości

This method returns FALSE if an error occurs.

Przykłady

Przykład #1 Delete a subscription

<?php
if (!$conn->unsubscribe($subid)) {
    // The unsubscribe failed!
    echo "Unsubscribe failed ($conn->errno) $conn->error";
}
?>

Zobacz też:

  • SAMConnection::subscribe

SAMConnection::subscribe
SAMMessage::body
SAM Funkcje


The body of the message.

SAMConnection::unsubscribe
SAMMessage::__construct
SAM Funkcje
PHP Manual

SAMMessage::body

(PECL sam >= 0.1.0)

SAMMessage::body — The body of the message.

Opis

string $SAMMessage->body;

The "body" property contains the actual body of the message. It may not always be set.

Przykłady

Przykład #1 Setting a text string into the body of a message

<?php
$msg = new SAMMessage();
$msg->body = 'This is a simple message';

?>

Zobacz też:

  • SAMMessage::header

SAMConnection::unsubscribe
SAMMessage::__construct
SAM Funkcje


Creates a new Message object

SAMMessage::body
SAMMessage::header
SAM Funkcje
PHP Manual

SAMMessage::__construct

(PECL sam >= 0.1.0)

SAMMessage::__construct — Creates a new Message object

Opis

SAMMessage::__construct() ([ mixed $body ] )

Creates a new SAMMessage object optionally specifying a message body.

Parametry

body

The optional body for the message.

Przykłady

Przykład #1 Creating a message

<?php

$msg = new SAMMessage();

?>

Przykład #2 Creating a message with a simple text payload

<?php

$msg = new SAMMessage('This is a simple text message');

?>

SAMMessage::body
SAMMessage::header
SAM Funkcje


The header properties of the message.

SAMMessage::__construct
SNMP
SAM Funkcje
PHP Manual

SAMMessage::header

(PECL sam >= 0.1.0)

SAMMessage::header — The header properties of the message.

Opis

object $SAMMessage->header;

The header property is a container for any system or user properties that area associated with the message.

Properties may be assigned by the sender of a message to control the way the messaging systems handles it or may be assigned by the messaging system itself to tell the recipient extra information about the message or the way in which it has been handled.

Some properties are understood by SAM in which case constants have been defined for them. The majority of properties however are ignored by the SAM implementation and simply passed through to the underlying messaging systems allowing the application to use messaging specific property names or to define its own "user" properties.

The SAM defined properties are as follows:

Property name | Possible values
SAM_MESSAGEID | When a message is received this field contains the unique identifier of the message as allocated by the underlying messaging system. When sending a message this field is ignored.
SAM_REPLY_TO | A string providing the identity of the queue on to which responses to this message should be posted.
SAM_TYPE

An indication of the type of message to be sent. The value may be SAM_TEXT indicating the contents of the message body is a text string, or SAM_BYTES indicating the contents of the message body are some application defined format.

The way in which this property is used may depend on the underlying messaging server. For instance a messaging server that supports the JMS (Java Message Service) specification may interpret this value and send messages of type "jms_text" and "jms_bytes". In addition, if the SAM_TYPE property is set to SAM_TEXT the data provided for the message body is expected to be a UTF8 encoded string.

When setting the values of properties it is often useful to give a hint as to the format in which the property should be delivered to the messaging system. By default property values are delivered as text and the following simple syntax may be used to set a value:

Przykład #1 Setting a text format property using the default syntax

<?php
$msg = new SAMMessage();

$msg->header->myPropertyName = 'textData';
?>

If it is desired to pass type information an alternative syntax may be used where the value and the type hint are passed in an associative array:

Przykład #2 Setting a text format property using a type hint

<?php
$msg = new SAMMessage();

$msg->header->myPropertyName = array('textData', SAM_STRING);
?>

When passing a type hint the type entry should be one of the SAM defined constant values as defined by the following table:

Constant | Type description
SAM_BOOLEAN | Any value passed will be interpreted as logical true or false. If the value cannot be interpreted as a PHP boolean value the value passed to the messaging system is undefined.
SAM_BYTE | An 8-bit signed integer value. SAM will attempt to convert the property value specified into a single byte value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 8-bit signed binary value data may be lost in the conversion.
SAM_DOUBLE | A long floating point value. SAM will attempt to convert the property value specified into a floating point value with 15 digits of precision. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the passed value cannot be expressed as a 15 digit floating point value data may be lost in the conversion.
SAM_FLOAT | A short floating point value. SAM will attempt to convert the property value specified into a floating point value with 7 digits of precision. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the passed value cannot be expressed as a 7 digit floating point value data may be lost in the conversion.
SAM_INT | An 32-bit signed integer value. SAM will attempt to convert the property value specified into a 32-bit value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 32-bit signed binary value data may be lost in the conversion.
SAM_LONG | An 64-bit signed integer value. SAM will attempt to convert the property value specified into a 64-bit value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 64-bit signed binary value data may be lost in the conversion.
SAM_STRING | SAM will interpret the property value specified as a string and pass it to the messaging system accordingly.

Przykłady

Przykład #3 Setting properties as the sender of a message

<?php
$msg = new SAMMessage('This is a test message');

// defining SAM specific properties...
$msg->header->SAM_REPLY_TO = 'queue://test/replyQueue';

// defining arbitrary properties...
//
// a default string property
$msg->header->myStringProp1 = 'a string property';
// a string property with a type hint
$msg->header->myStringProp2 = array('another string property', SAM_STRING);

// a boolean property
$msg->header->myBoolProp = array(FALSE, SAM_BOOL);

// numeric format properties
$msg->header->myIntProp = array(32768, SAM_INT);
$msg->header->myLongProp = array(9876543, SAM_LONG);
$msg->header->myByteProp1 = array(123, SAM_BYTE);
$msg->header->myByteProp2 = array('12', SAM_BYTE);
$msg->header->myFloatProp = array(3.141592, SAM_FLOAT);
$msg->header->myDoubleProp = array(3.14159265358979, SAM_DOUBLE);
?>

Przykład #4 Retreiving property values from a message

<?php

// accessing an application specific property
$intProp = $msg->header->MyIntProp;

// accessing a messaging system specific property
$encoding = $msg->header->JMS_IBM_Msgtype;

?>

Zobacz też:

  • SAMMessage::body

SAMMessage::__construct
SNMP
SAM Funkcje


SNMP

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • SNMP Funkcje
    • snmp_get_quick_print — Fetches the current value of the UCD library's quick_print setting
    • snmp_get_valueretrieval — Return the method how the SNMP values will be returned
    • snmp_read_mib — Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print — Return all objects including their respective object id within the specified one
    • snmp_set_oid_output_format — Set the OID output format
    • snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library
    • snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
    • snmp2_get — Fetch an SNMP object
    • snmp2_getnext — Fetch the SNMP object which follows the given object id
    • snmp2_real_walk — Return all objects including their respective object ID within the specified one
    • snmp2_set — Set the value of an SNMP object
    • snmp2_walk — Fetch all the SNMP objects from an agent
    • snmp3_get — Fetch an SNMP object
    • snmp3_getnext — Fetch the SNMP object which follows the given object id
    • snmp3_real_walk — Return all objects including their respective object ID within the specified one
    • snmp3_set — Set the value of an SNMP object
    • snmp3_walk — Fetch all the SNMP objects from an agent
    • snmpget — Fetch an SNMP object
    • snmpgetnext — Fetch the SNMP object which follows the given object id
    • snmprealwalk — Return all objects including their respective object ID within the specified one
    • snmpset — Set the value of an SNMP object
    • snmpwalk — Fetch all the SNMP objects from an agent
    • snmpwalkoid — Query for a tree of information about a network entity
  • SNMP — The SNMP class
    • SNMP::close — Close SNMP session
    • SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent
    • SNMP::get — Fetch an SNMP object
    • SNMP::getErrno — Get last error code
    • SNMP::getError — Get last error message
    • SNMP::getnext — Fetch an SNMP object which follows the given object id
    • SNMP::set — Set the value of an SNMP object
    • SNMP::setSecurity — Configures security-related SNMPv3 session parameters
    • SNMP::walk — Fetch SNMP object subtree
  • SNMPException — The SNMPException class
SAMMessage::header
Wstęp
Inne serwisy


Wstęp

The SNMP extension provides a very simple and easily usable toolset for managing remote devices via the Simple Network Management Protocol.

As it is a wrapper around the underlying Net-SNMP (or UCD-SNMP on older systems) library, all basic concepts are the same and the PHP functions change their behaviour depending on the Net-SNMP configuration files and environment variables.

Beginning with PHP 5.4, an OO API is available.

More information about Net-SNMP can be found at » http://www.net-snmp.org/

SNMP
Instalacja/Konfiguracja
SNMP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SNMP


Wymagania

In order to use the SNMP functions requires installation of the » Net-SNMP package. SNMPv3 functions available only when » OpenSSL package is installed too.

On Windows SNMP functions are only available on NT and not on Win95/98.

Begining with PHP 5.4.0 Net-SNMP version 5.3+ is required for Unix installations and Net-SNMP version 5.4+ for Windows.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

PHP 5.3.0, 5.3.1 and 5.3.2 do not have SNMP support. SNMP support has restored in PHP 5.3.3.

The Windows distribution of Net-SNMP contains support files for SNMP in the mibs directory. This directory should be moved to DRIVE:\usr\mibs, where DRIVE must be replaced with the driveletter where PHP is installed on, e.g.c:\usr\mibs. Alternatively you may set MIBDIRS environment variable pointed to your MIBs folder.

Important notes for PHP prior to 5.4.0: In order to use the UCD SNMP package, you need to define NO_ZEROLENGTH_COMMUNITY to 1 before compiling it. After configuring UCD SNMP, edit config.h or acconfig.h and search for NO_ZEROLENGTH_COMMUNITY. Uncomment the #define line. It should look like this afterwards:

#define NO_ZEROLENGTH_COMMUNITY 1
Now compile PHP --with-snmp[=DIR] .

If you see strange segmentation faults in combination with SNMP commands, you did not follow the above instructions. If you do not want to recompile UCD SNMP, you can compile PHP with the --enable-ucd-snmp-hack switch which will work around the misfeature.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

For the snmp_set_oid_output_format()
SNMP_OID_OUTPUT_SUFFIX (integer)
As of 5.4.0
SNMP_OID_OUTPUT_MODULE (integer)
As of 5.4.0
SNMP_OID_OUTPUT_FULL (integer)
As of 5.2.0
SNMP_OID_OUTPUT_NUMERIC (integer)
As of 5.2.0
SNMP_OID_OUTPUT_UCD (integer)
As of 5.4.0
SNMP_OID_OUTPUT_NONE (integer)
As of 5.4.0
For the snmp_set_valueretrieval()
SNMP_VALUE_LIBRARY (integer)
SNMP_VALUE_PLAIN (integer)
SNMP_VALUE_OBJECT (integer)
SNMP types as returned if SNMP_VALUE_OBJECT was used with snmp_set_valueretrieval()
SNMP_BIT_STR (integer)
SNMP_OCTET_STR (integer)
SNMP_OPAQUE (integer)
SNMP_NULL (integer)
SNMP_OBJECT_ID (integer)
SNMP_IPADDRESS (integer)
SNMP_COUNTER (integer)
SNMP_UNSIGNED (integer)
SNMP_TIMETICKS (integer)
SNMP_UINTEGER (integer)
SNMP_INTEGER (integer)
SNMP_COUNTER64 (integer)
Typy zasobów
SNMP Funkcje
SNMP


SNMP Funkcje

Spis treści

  • snmp_get_quick_print — Fetches the current value of the UCD library's quick_print setting
  • snmp_get_valueretrieval — Return the method how the SNMP values will be returned
  • snmp_read_mib — Reads and parses a MIB file into the active MIB tree
  • snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer
  • snmp_set_oid_numeric_print — Return all objects including their respective object id within the specified one
  • snmp_set_oid_output_format — Set the OID output format
  • snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library
  • snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
  • snmp2_get — Fetch an SNMP object
  • snmp2_getnext — Fetch the SNMP object which follows the given object id
  • snmp2_real_walk — Return all objects including their respective object ID within the specified one
  • snmp2_set — Set the value of an SNMP object
  • snmp2_walk — Fetch all the SNMP objects from an agent
  • snmp3_get — Fetch an SNMP object
  • snmp3_getnext — Fetch the SNMP object which follows the given object id
  • snmp3_real_walk — Return all objects including their respective object ID within the specified one
  • snmp3_set — Set the value of an SNMP object
  • snmp3_walk — Fetch all the SNMP objects from an agent
  • snmpget — Fetch an SNMP object
  • snmpgetnext — Fetch the SNMP object which follows the given object id
  • snmprealwalk — Return all objects including their respective object ID within the specified one
  • snmpset — Set the value of an SNMP object
  • snmpwalk — Fetch all the SNMP objects from an agent
  • snmpwalkoid — Query for a tree of information about a network entity
Stałe predefiniowane
snmp_get_quick_print
SNMP


Fetches the current value of the UCD library's quick_print setting

SNMP Funkcje
snmp_get_valueretrieval
SNMP Funkcje
PHP Manual

snmp_get_quick_print

(PHP 4, PHP 5)

snmp_get_quick_print — Fetches the current value of the UCD library's quick_print setting

Opis

bool snmp_get_quick_print ( void )

Returns the current value stored in the UCD Library for quick_print. quick_print is off by default.

Zwracane wartości

Returns TRUE if quick_print is on, FALSE otherwise.

Przykłady

Przykład #1 snmp_get_quick_print() example

<?php
$quickprint = snmp_get_quick_print();
?>

Zobacz też:

  • snmp_set_quick_print() - Set the value of quick_print within the UCD SNMP library for a full description of what quick_print does.

SNMP Funkcje
snmp_get_valueretrieval
SNMP Funkcje


Return the method how the SNMP values will be returned

snmp_get_quick_print
snmp_read_mib
SNMP Funkcje
PHP Manual

snmp_get_valueretrieval

(PHP 4 >= 4.3.3, PHP 5)

snmp_get_valueretrieval — Return the method how the SNMP values will be returned

Opis

int snmp_get_valueretrieval ( void )

Zwracane wartości

OR-ed combitantion of constants ( SNMP_VALUE_LIBRARY or SNMP_VALUE_PLAIN ) with possible SNMP_VALUE_OBJECT set.

Przykłady

Przykład #1 Using snmp_get_valueretrieval

<?php
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 if (snmp_get_valueretrieval() & SNMP_VALUE_OBJECT) {
   echo $ret->value;
 } else {
   echo $ret;
 }
?>

Zobacz też:

  • snmp_set_valueretrieval() - Specify the method how the SNMP values will be returned
  • Stałe predefiniowane

snmp_get_quick_print
snmp_read_mib
SNMP Funkcje


Reads and parses a MIB file into the active MIB tree

snmp_get_valueretrieval
snmp_set_enum_print
SNMP Funkcje
PHP Manual

snmp_read_mib

(PHP 5)

snmp_read_mib — Reads and parses a MIB file into the active MIB tree

Opis

bool snmp_read_mib ( string $filename )

This function is used to load additional, e.g. vendor specific, MIBs so that human readable OIDs like VENDOR-MIB::foo.1 instead of error prone numeric OIDs can be used.

The order in which the MIBs are loaded does matter as the underlying Net-SNMP libary will print warnings if referenced objects cannot be resolved.

Parametry

filename

The filename of the MIB.

Przykłady

Przykład #1 Using snmp_read_mib()

<?php
 print_r( snmprealwalk('localhost', 'public', '.1.3.6.1.2.1.2.3.4.5') );

 snmp_read_mib('./FOO-BAR-MIB.txt');
 print_r( snmprealwalk('localhost', 'public', 'FOO-BAR-MIB::someTable' );
?>

The above example is made up but the results would look like:

Array
(
    [iso.3.6.1.2.1.2.3.4.5.0] => Gauge32: 6
)
Array
(
    [FOO-BAR-MIB::someTable.0] => Gauge32: 6
)

snmp_get_valueretrieval
snmp_set_enum_print
SNMP Funkcje


Return all values that are enums with their enum value instead of the raw integer

snmp_read_mib
snmp_set_oid_numeric_print
SNMP Funkcje
PHP Manual

snmp_set_enum_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer

Opis

bool snmp_set_enum_print ( int $enum_print )

This function toggles if snmpwalk/snmpget etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

Parametry

enum_print

As the value is interpreted as boolean by the Net-SNMP library, it can only be "0" or "1".

Przykłady

Przykład #1 Using snmp_set_enum_print()

<?php
 snmp_set_enum_print(0);
 echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";
 snmp_set_enum_print(1);
 echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";
?>

The above would return

 INTEGER: up(1)
 INTEGER: 1

Notatki

Informacja:

snmp_set_enum_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

snmp_read_mib
snmp_set_oid_numeric_print
SNMP Funkcje


Return all objects including their respective object id within the specified one

snmp_set_enum_print
snmp_set_oid_output_format
SNMP Funkcje
PHP Manual

snmp_set_oid_numeric_print

(PHP 4 >= 4.3.0, PHP 5)

snmp_set_oid_numeric_print — Return all objects including their respective object id within the specified one

Opis

void snmp_set_oid_numeric_print ( int $oid_format )

Ta funkcja jest aliasem dla: snmp_set_oid_output_format().

Rejestr zmian

Wersja | Opis
5.2.0 | Since PHP 5.2.0.

Zobacz też:

  • snmp_set_oid_output_format() - Set the OID output format

snmp_set_enum_print
snmp_set_oid_output_format
SNMP Funkcje


Set the OID output format

snmp_set_oid_numeric_print
snmp_set_quick_print
SNMP Funkcje
PHP Manual

snmp_set_oid_output_format

(PHP 5 >= 5.2.0)

snmp_set_oid_output_format — Set the OID output format

Opis

bool snmp_set_oid_output_format ( int $oid_format = SNMP_OID_OUTPUT_MODULE )

snmp_set_oid_output_format() sets the output format to be full or numeric.

Parametry

oid_format
OID .1.3.6.1.2.1.1.3.0 representation for various oid_format values
SNMP_OID_OUTPUT_FULL | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC | .1.3.6.1.2.1.1.3.0

Begining from PHP 5.4.0 four additional constants available:

SNMP_OID_OUTPUT_MODULE | DISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIX | sysUpTimeInstance
SNMP_OID_OUTPUT_UCD | system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONE | Undefined

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja:

snmp_set_oid_output_format() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

Przykłady

Przykład #1 Using snmprealwalk()

<?php

 snmp_read_mib("/usr/share/mibs/netsnmp/NET-SNMP-TC");

 // default or SNMP_OID_OUTPUT_MODULE in PHP >= 5.3.6
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );

 snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );

 snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL);
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );
?>

The above would output:

 Array
 (
    [RFC1213-MIB::sysObjectID.0] => OID: NET-SNMP-TC::linux
 )
 Array
 (
    [.1.3.6.1.2.1.1.2.0] => OID: .1.3.6.1.4.1.8072.3.2.10
 )
 Array
 (
    [.iso.org.dod.internet.mgmt.mib-2.system.sysObjectID.0] => OID: .iso.org.dod.internet.private.enterprises.netSnmp.netSnmpEnumerations.netSnmpAgentOIDs.linux
 )

snmp_set_oid_numeric_print
snmp_set_quick_print
SNMP Funkcje


Set the value of quick_print within the UCD SNMP library

snmp_set_oid_output_format
snmp_set_valueretrieval
SNMP Funkcje
PHP Manual

snmp_set_quick_print

(PHP 4, PHP 5)

snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library

Opis

bool snmp_set_quick_print ( bool $quick_print )

Sets the value of quick_print within the UCD SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.

By default the UCD SNMP library returns verbose values, quick_print is used to return only the value.

Currently strings are still returned with extra quotes, this will be corrected in a later release.

Parametry

quick_print

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Setting quick_print is often used when using the information returned rather than displaying it.

Przykład #1 Using snmp_set_quick_print()

<?php
snmp_set_quick_print(0);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
snmp_set_quick_print(1);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
?>

Powyższy przykład wyświetli coś podobnego do:

'Timeticks: (0) 0:00:00.00'
'0:00:00.00'

Zobacz też:

  • snmp_get_quick_print() - Fetches the current value of the UCD library's quick_print setting

snmp_set_oid_output_format
snmp_set_valueretrieval
SNMP Funkcje


Specify the method how the SNMP values will be returned

snmp_set_quick_print
snmp2_get
SNMP Funkcje
PHP Manual

snmp_set_valueretrieval

(PHP 4 >= 4.3.3, PHP 5)

snmp_set_valueretrieval — Specify the method how the SNMP values will be returned

Opis

bool snmp_set_valueretrieval ( int $method = SNMP_VALUE_LIBRARY )

Parametry

method
types
SNMP_VALUE_LIBRARY | The return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAIN | The return values will be the plain value without the SNMP type hint.
SNMP_VALUE_OBJECT | The return values will be objects with the properties "value" and "type", where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way "value" is returned is based on which one of constants SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set.

Przykłady

Przykład #1 Using snmp_set_valueretrieval()

<?php
 snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // $ret = "STRING: lo"

 snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // $ret = "lo";

 snmp_set_valueretrieval(SNMP_VALUE_OBJECT);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => lo
 // )

 // PHP 5.4+ examples
 snmp_set_valueretrieval(SNMP_VALUE_OBJECT | SNMP_VALUE_PLAIN);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => lo
 // )

 snmp_set_valueretrieval(SNMP_VALUE_OBJECT | SNMP_VALUE_LIBRARY);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => STRING: lo
 // )

?>

Rejestr zmian

Wersja | Opis
5.4.0 | Constants SNMP_VALUE_PLAIN or SNMP_VALUE_LIBRARY may be combined with SNMP_VALUE_OBJECT resulting different way of representing contents of value array element in return value of GET-function. If no SNMP_VALUE_{PLAIN,LIBRARY} constant is accompanying SNMP_VALUE_OBJECT, SNMP_VALUE_LIBRARY is used. Prior to 5.4.0 SNMP_VALUE_OBJECT effecively meant SNMP_VALUE_OBJECT|SNMP_VALUE_PLAIN.

Zobacz też:

  • snmp_get_valueretrieval() - Return the method how the SNMP values will be returned
  • Stałe predefiniowane

snmp_set_quick_print
snmp2_get
SNMP Funkcje


Fetch an SNMP object

snmp_set_valueretrieval
snmp2_getnext
SNMP Funkcje
PHP Manual

snmp2_get

(PHP 5 >= 5.2.0)

snmp2_get — Fetch an SNMP object

Opis

string snmp2_get ( string $host , string $community , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp2_get() function is used to read the value of an SNMP object specified by the object_id.

Parametry

host

The SNMP agent.

community

The read community.

object_id

The SNMP object.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns SNMP object value on success or FALSE on error.

Przykłady

Przykład #1 Using snmp2_get()

<?php
$syscontact = snmp2_get("127.0.0.1", "public", "system.SysContact.0");
?>

Zobacz też:

  • snmp2_set() - Set the value of an SNMP object

snmp_set_valueretrieval
snmp2_getnext
SNMP Funkcje


Fetch the SNMP object which follows the given object id

snmp2_get
snmp2_real_walk
SNMP Funkcje
PHP Manual

snmp2_getnext

(PHP >= 5.2.0)

snmp2_getnext — Fetch the SNMP object which follows the given object id

Opis

string snmp2_getnext ( string $host , string $community , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp2_get_next() function is used to read the value of the SNMP object that follows the specified object_id.

Parametry

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Przykłady

Przykład #1 Using snmp2_get_next()

<?php
$nameOfSecondInterface = snmp2_get_netxt('localhost', 'public', 'IF-MIB::ifName.1';
?>

Zobacz też:

  • snmp2_get() - Fetch an SNMP object
  • snmp2_walk() - Fetch all the SNMP objects from an agent

snmp2_get
snmp2_real_walk
SNMP Funkcje


Return all objects including their respective object ID within the specified one

snmp2_getnext
snmp2_set
SNMP Funkcje
PHP Manual

snmp2_real_walk

(PHP >= 5.2.0)

snmp2_real_walk — Return all objects including their respective object ID within the specified one

Opis

array snmp2_real_walk ( string $host , string $community , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp2_real_walk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parametry

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Przykłady

Przykład #1 Using snmp2_real_walk()

<?php
 print_r(snmp2_real_walk("localhost", "public", "IF-MIB::ifName"));
?>

The above will output something like:

    Array
      (
      [IF-MIB::ifName.1] => STRING: lo
      [IF-MIB::ifName.2] => STRING: eth0
      [IF-MIB::ifName.3] => STRING: eth2
      [IF-MIB::ifName.4] => STRING: sit0
      [IF-MIB::ifName.5] => STRING: sixxs
    )

Zobacz też:

  • snmp2_walk() - Fetch all the SNMP objects from an agent

snmp2_getnext
snmp2_set
SNMP Funkcje


Set the value of an SNMP object

snmp2_real_walk
snmp2_walk
SNMP Funkcje
PHP Manual

snmp2_set

(PHP >= 5.2.0)

snmp2_set — Set the value of an SNMP object

Opis

bool snmp2_set ( string $host , string $community , string $object_id , string $type , string $value [, string $timeout = 1000000 [, string $retries = 5 ]] )

snmp2_set() is used to set the value of an SNMP object specified by the object_id.

Parametry

host

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Przykłady

Przykład #1 Using snmp2_set()

<?php
  snmp2_set("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Przykład #2 Using snmp2_set() for setting BITS SNMP object id

<?php
  snmp2_set("localhost", "public", 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmp2_set("localhost", "public", 'FOO-MIB::bar.42', 'x', 'F0');
?>

Zobacz też:

  • snmp2_get() - Fetch an SNMP object

snmp2_real_walk
snmp2_walk
SNMP Funkcje


Fetch all the SNMP objects from an agent

snmp2_set
snmp3_get
SNMP Funkcje
PHP Manual

snmp2_walk

(PHP >= 5.2.0)

snmp2_walk — Fetch all the SNMP objects from an agent

Opis

array snmp2_walk ( string $host , string $community , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

snmp2_walk() function is used to read all the values from an SNMP agent specified by the hostname.

Parametry

host

The SNMP agent (server).

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Przykłady

Przykład #1 snm2_pwalk() Example

<?php
$a = snmp2_walk("127.0.0.1", "public", "");

foreach ($a as $val) {
    echo "$val\n";
}

?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

Zobacz też:

  • snmp2_real_walk() - Return all objects including their respective object ID within the specified one

snmp2_set
snmp3_get
SNMP Funkcje


Fetch an SNMP object

snmp2_walk
snmp3_getnext
SNMP Funkcje
PHP Manual

snmp3_get

(PHP 4, PHP 5)

snmp3_get — Fetch an SNMP object

Opis

string snmp3_get ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp3_get() function is used to read the value of an SNMP object specified by the object_id.

Parametry

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns SNMP object value on success or FALSE on error.

Przykłady

Przykład #1 Using snmp3_get()

<?php
$nameOfSecondInterface = snmp3_get('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.2');
?>

Zobacz też:

  • snmp3_set() - Set the value of an SNMP object

snmp2_walk
snmp3_getnext
SNMP Funkcje


Fetch the SNMP object which follows the given object id

snmp3_get
snmp3_real_walk
SNMP Funkcje
PHP Manual

snmp3_getnext

(PHP 5)

snmp3_getnext — Fetch the SNMP object which follows the given object id

Opis

string snmp3_getnext ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp3_getnext() function is used to read the value of the SNMP object that follows the specified object_id.

Parametry

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Przykłady

Przykład #1 Using snmp3_getnext()

<?php
$nameOfSecondInterface = snmp3_getnext('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.1');
?>

Zobacz też:

  • snmp3_get() - Fetch an SNMP object
  • snmp3_walk() - Fetch all the SNMP objects from an agent

snmp3_get
snmp3_real_walk
SNMP Funkcje


Return all objects including their respective object ID within the specified one

snmp3_getnext
snmp3_set
SNMP Funkcje
PHP Manual

snmp3_real_walk

(PHP 4, PHP 5)

snmp3_real_walk — Return all objects including their respective object ID within the specified one

Opis

array snmp3_real_walk ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

The snmp3_real_walk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parametry

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Przykłady

Przykład #1 Using snmp3_real_walk()

<?php
 var_export(snmp3_real_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName'));
?>

The above will output something like:

array (
  'IF-MIB::ifName.1' => 'STRING: lo',
  'IF-MIB::ifName.2' => 'STRING: eth0',
  'IF-MIB::ifName.3' => 'STRING: eth2',
  'IF-MIB::ifName.4' => 'STRING: sit0',
  'IF-MIB::ifName.5' => 'STRING: sixxs',
)

Zobacz też:

  • snmpwalk() - Fetch all the SNMP objects from an agent

snmp3_getnext
snmp3_set
SNMP Funkcje


Set the value of an SNMP object

snmp3_real_walk
snmp3_walk
SNMP Funkcje
PHP Manual

snmp3_set

(PHP 4, PHP 5)

snmp3_set — Set the value of an SNMP object

Opis

bool snmp3_set ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id , string $type , string $value [, int $timeout = 1000000 [, int $retries = 5 ]] )

snmp3_set() is used to set the value of an SNMP object specified by the object_id.

Even if the security level does not use an auth or priv protocol/password valid values have to be specified.

Parametry

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Przykłady

Przykład #1 Using snmp3_set()

<?php
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifAlias.3', 's', "foo");
?>

Przykład #2 Using snmp3_set() for setting BITS SNMP object id

<?php
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'FOO-MIB::bar.42', 'x', 'F0');
?>
snmp3_real_walk
snmp3_walk
SNMP Funkcje


Fetch all the SNMP objects from an agent

snmp3_set
snmpget
SNMP Funkcje
PHP Manual

snmp3_walk

(PHP 4, PHP 5)

snmp3_walk — Fetch all the SNMP objects from an agent

Opis

array snmp3_walk ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, string $timeout = 1000000 [, string $retries = 5 ]] )

snmp3_walk() function is used to read all the values from an SNMP agent specified by the hostname.

Even if the security level does not use an auth or priv protocol/password valid values have to be specified.

Parametry

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Przykłady

Przykład #1 snmp3_walk() Example

<?php
$ret = snmp3_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName');
var_export($ret);
?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost:

array (
  0 => 'STRING: lo',
  1 => 'STRING: eth0',
  2 => 'STRING: eth2',
  3 => 'STRING: sit0',
  4 => 'STRING: sixxs',
)

Zobacz też:

  • snmp3_real_walk() - Return all objects including their respective object ID within the specified one

snmp3_set
snmpget
SNMP Funkcje


Fetch an SNMP object

snmp3_walk
snmpgetnext
SNMP Funkcje
PHP Manual

snmpget

(PHP 4, PHP 5)

snmpget — Fetch an SNMP object

Opis

string snmpget ( string $hostname , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] )

The snmpget() function is used to read the value of an SNMP object specified by the object_id.

Parametry

hostname

The SNMP agent.

community

The read community.

object_id

The SNMP object.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns SNMP object value on success or FALSE on error.

Przykłady

Przykład #1 Using snmpget()

<?php
$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");
?>

Zobacz też:

  • snmpset() - Set the value of an SNMP object

snmp3_walk
snmpgetnext
SNMP Funkcje


Fetch the SNMP object which follows the given object id

snmpget
snmprealwalk
SNMP Funkcje
PHP Manual

snmpgetnext

(PHP 5)

snmpgetnext — Fetch the SNMP object which follows the given object id

Opis

string snmpgetnext ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] )

The snmpgetnext() function is used to read the value of the SNMP object that follows the specified object_id.

Parametry

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Przykłady

Przykład #1 Using snmpgetnext()

<?php
$nameOfSecondInterface = snmpgetnetxt('localhost', 'public', 'IF-MIB::ifName.1';
?>

Zobacz też:

  • snmpget() - Fetch an SNMP object
  • snmpwalk() - Fetch all the SNMP objects from an agent

snmpget
snmprealwalk
SNMP Funkcje


Return all objects including their respective object ID within the specified one

snmpgetnext
snmpset
SNMP Funkcje
PHP Manual

snmprealwalk

(PHP 4, PHP 5)

snmprealwalk — Return all objects including their respective object ID within the specified one

Opis

array snmprealwalk ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] )

The snmprealwalk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parametry

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Przykłady

Przykład #1 Using snmprealwalk()

<?php
 print_r(snmprealwalk("localhost", "public", "IF-MIB::ifName"));
?>

The above will output something like:

    Array
      (
      [IF-MIB::ifName.1] => STRING: lo
      [IF-MIB::ifName.2] => STRING: eth0
      [IF-MIB::ifName.3] => STRING: eth2
      [IF-MIB::ifName.4] => STRING: sit0
      [IF-MIB::ifName.5] => STRING: sixxs
    )

Zobacz też:

  • snmpwalk() - Fetch all the SNMP objects from an agent

snmpgetnext
snmpset
SNMP Funkcje


Set the value of an SNMP object

snmprealwalk
snmpwalk
SNMP Funkcje
PHP Manual

snmpset

(PHP 4, PHP 5)

snmpset — Set the value of an SNMP object

Opis

bool snmpset ( string $host , string $community , string $object_id , string $type , mixed $value [, int $timeout = 1000000 [, int $retries = 5 ]] )

snmpset() is used to set the value of an SNMP object specified by the object_id.

Parametry

host

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Przykłady

Przykład #1 Using snmpset()

<?php
  snmpset("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Przykład #2 Using snmpset() for setting BITS SNMP object id

<?php
  snmpset("localhost", "public", 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmpset("localhost", "public", 'FOO-MIB::bar.42', 'x', 'F0');
?>

Zobacz też:

  • snmpget() - Fetch an SNMP object

snmprealwalk
snmpwalk
SNMP Funkcje


Fetch all the SNMP objects from an agent

snmpset
snmpwalkoid
SNMP Funkcje
PHP Manual

snmpwalk

(PHP 4, PHP 5)

snmpwalk — Fetch all the SNMP objects from an agent

Opis

array snmpwalk ( string $hostname , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] )

snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname.

Parametry

hostname

The SNMP agent (server).

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Przykłady

Przykład #1 snmpwalk() Example

<?php
$a = snmpwalk("127.0.0.1", "public", "");

foreach ($a as $val) {
    echo "$val\n";
}

?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

Zobacz też:

  • snmprealwalk() - Return all objects including their respective object ID within the specified one

snmpset
snmpwalkoid
SNMP Funkcje


Query for a tree of information about a network entity

snmpwalk
SNMP
SNMP Funkcje
PHP Manual

snmpwalkoid

(PHP 4, PHP 5)

snmpwalkoid — Query for a tree of information about a network entity

Opis

array snmpwalkoid ( string $hostname , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] )

snmpwalkoid() function is used to read all object ids and their respective values from an SNMP agent specified by hostname.

The existence of snmpwalkoid() and snmpwalk() has historical reasons. Both functions are provided for backward compatibility. Use snmprealwalk() instead.

Parametry

hostname

The SNMP agent.

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Zwracane wartości

Returns an associative array with object ids and their respective object value starting from the object_id as root or FALSE on error.

Przykłady

Przykład #1 snmpwalkoid() Example

<?php
$a = snmpwalkoid("127.0.0.1", "public", "");
for (reset($a); $i = key($a); next($a)) {
    echo "$i: $a[$i]<br />\n";
}
?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

Zobacz też:

  • snmpwalk() - Fetch all the SNMP objects from an agent

snmpwalk
SNMP
SNMP Funkcje


The SNMP class

(No version information available, might only be in SVN)

Wstęp

Represents SNMP session.

Krótki opis klasy

SNMP {
/* Właściwości */
public int $max_oids ;
public int $valueretrieval ;
public bool $quick_print ;
public bool $enum_print ;
public int $oid_output_format ;
public bool $oid_increasing_check ;
public int $exceptions_enabled ;
public array $info ;
/* Metody */
__construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )
bool close ( void )
mixed get ( mixed $object_id [, bool $preserve_keys = false ] )
int getErrno ( void )
string getError ( void )
mixed getnext ( mixed $object_id )
bool set ( mixed $object_id , mixed $type , mixed $value )
bool setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] )
array walk ( string $object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters ]]] )
/* Stałe */
const integer ERRNO_NOERROR = 0 ;
const integer ERRNO_GENERIC = 2 ;
const integer ERRNO_TIMEOUT = 4 ;
const integer ERRNO_ERROR_IN_REPLY = 8 ;
const integer ERRNO_OID_NOT_INCREASING = 16 ;
const integer ERRNO_OID_PARSING_ERROR = 32 ;
const integer ERRNO_MULTIPLE_SET_QUERIES = 64 ;
const integer ERRNO_ANY = 126 ;
const integer VERSION_1 = 0 ;
const integer VERSION_2C = 1 ;
const integer VERSION_2c = 1 ;
const integer VERSION_3 = 3 ;
}

Właściwości

max_oids

Maximum OID per GET/SET/GETBULK request

valueretrieval

Controls the method how the SNMP values will be returned

SNMP_VALUE_LIBRARY | The return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAIN | The return values will be the plain value without the SNMP type hint.
SNMP_VALUE_OBJECT | The return values will be objects with the properties "value" and "type", where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way "value" is returned is based on which one of SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set
quick_print

Value of quick_print within the NET-SNMP library

Sets the value of quick_print within the NET-SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.

enum_print

Controls the way enum values are printed

Parameter toggles if walk/get etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

oid_output_format

Controls OID output format

OID .1.3.6.1.2.1.1.3.0 representation for various oid_output_format values
SNMP_OID_OUTPUT_FULL | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC | .1.3.6.1.2.1.1.3.0
SNMP_OID_OUTPUT_MODULE | DISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIX | sysUpTimeInstance
SNMP_OID_OUTPUT_UCD | system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONE | Undefined
oid_increasing_check

Controls disabling check for increasing OID while walking OID tree

Some SNMP agents are known for returning OIDs out of order but can complete the walk anyway. Other agents return OIDs that are out of order and can cause SNMP::walk() to loop indefinitely until memory limit will be reached. PHP SNMP library by default performs OID increasing check and stops walking on OID tree when it detects possible loop with issuing warning about non-increasing OID faced. Set oid_increasing_check to FALSE to disable this check.

exceptions_enabled

Controls which failures will raise SNMPException instead of warning. Use bitwise OR'ed SNMP::ERRNO_* constants. By default all SNMP exceptions are disabled.

info

Read-only property with remote agent configuration: hostname, port, default timeout, default retries count

Stałe predefiniowane

SNMP Error Types

SNMP::ERRNO_NOERROR

No SNMP-specific error occured.

SNMP::ERRNO_GENERIC

A generic SNMP error occured.

SNMP::ERRNO_TIMEOUT

Request to SNMP agent timed out.

SNMP::ERRNO_ERROR_IN_REPLY

SNMP agent returned an error in reply.

SNMP::ERRNO_OID_NOT_INCREASING

SNMP agent faced OID cycling reporning non-increasing OID while executing (BULK)WALK command. This indicates bogus remote SNMP agent.

SNMP::ERRNO_OID_PARSING_ERROR

Library failed while parsing OID (and/or type for SET command). No queries has been made.

SNMP::ERRNO_MULTIPLE_SET_QUERIES

Library will use multiple queries for SET operation requested. That means that operation will be performed in a non-transaction manner and second or subsequent chunks may fail if a type or value failure will be faced.

SNMP::ERRNO_ANY

All SNMP::ERRNO_* codes bitwise OR'ed.

SNMP Protocol Versions

SNMP::VERSION_1

SNMP::VERSION_2C, SNMP::VERSION_2c

SNMP::VERSION_3

Spis treści

  • SNMP::close — Close SNMP session
  • SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent
  • SNMP::get — Fetch an SNMP object
  • SNMP::getErrno — Get last error code
  • SNMP::getError — Get last error message
  • SNMP::getnext — Fetch an SNMP object which follows the given object id
  • SNMP::set — Set the value of an SNMP object
  • SNMP::setSecurity — Configures security-related SNMPv3 session parameters
  • SNMP::walk — Fetch SNMP object subtree
snmpwalkoid
SNMP::close
SNMP


Close SNMP session

SNMP
SNMP::__construct
SNMP
PHP Manual

SNMP::close

(PHP 5 >= 5.4.0)

SNMP::close — Close SNMP session

Opis

bool SNMP::close ( void )

Frees previously allocated SNMP session object.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 SNMP::close() example

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  # ...
  # get, walk, etc goes here
  # ...
  $session->close();
?>

Zobacz też:

  • SNMP::__construct() - Creates SNMP instance representing session to remote SNMP agent
SNMP
SNMP::__construct
SNMP


Creates SNMP instance representing session to remote SNMP agent

SNMP::close
SNMP::get
SNMP
PHP Manual

SNMP::__construct

(PHP 5 >= 5.4.0)

SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent

Opis

SNMP::__construct() ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )

The function description goes here.

Parametry

version

SNMP protocol version:
SNMP::VERSION_1,
SNMP::VERSION_2C,
SNMP::VERSION_3.

hostname

The SNMP agent. hostname may be suffixed with optional SNMP agent port after colon. IPv6 addresses must be enclosed in square brackets if used with port. If FQDN is used for hostname it will be resolved by php-snmp library, not by Net-SNMP engine. Usage of IPv6 addresses when specifying FQDN may be forced by enclosing FQDN into square brackets. Here it is some examples:

IPv4 with default port | 127.0.0.1
IPv6 with default port | ::1 or [::1]
IPv4 with specific port | 127.0.0.1:1161
IPv6 with specific port | [::1]:1161
FQDN with default port | host.domain
FQDN with specific port | host.domain:1161
FQDN with default port, force usage of IPv6 address | [host.domain]
FQDN with specific port, force usage of IPv6 address | [host.domain]:1161

community

The purpuse of community is SNMP version specific:

SNMP::VERSION_1 | SNMP community
SNMP::VERSION_2C | SNMP community
SNMP::VERSION_3 | SNMPv3 securityName
timeout

The number of microseconds until the first timeout.

retries

The number of retries in case timeout occurs.

Zwracane wartości

Returns SNMP object representing remote SNMP agent.

Błędy/Wyjątki

SNMP::__construct() throws an exception when parameters count or types are wrong or unknown SNMP protocol version specified.

Przykłady

Przykład #1 Fetching sysLocation

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $sysdescr = $session->get("sysDescr.0");
  echo "$sysdescr\n";
?>

Powyższy przykład wyświetli coś podobnego do:

STRING: Test server

Zobacz też:

  • SNMP::close() - Close SNMP session
SNMP::close
SNMP::get
SNMP


Fetch an SNMP object

SNMP::__construct
SNMP::getErrno
SNMP
PHP Manual

SNMP::get

(PHP 5 >= 5.4.0)

SNMP::get — Fetch an SNMP object

Opis

mixed SNMP::get ( mixed $object_id [, bool $preserve_keys = false ] )

Fetch an SNMP object specified in object_id using GET query.

Parametry

If object_id is a string, then SNMP::get() will return SNMP object as string. If object_id is a array, all requested SNMP objects will be returned as associative array of the SNMP object ids and their values.

object_id

The SNMP object (OID) or objects

preserve_keys

When object_id is a array and preserve_keys set to TRUE keys in results will be taken exactly as in object_id, otherwise SNMP::oid_output_format property is used to determinate the form of keys.

Zwracane wartości

Returns SNMP objects requested as string or array depending on object_id type or FALSE on error.

Błędy/Wyjątki

This method do not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occure user should set exceptions_enabled SNMP class parameter to corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Przykłady

Przykład #1 Single SNMP object

Single SNMP object may be requested in two ways: as string resulting string return value or as single-element array with associative array as output.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $sysdescr = $session->get("sysDescr.0");
  echo "$sysdescr\n";
  $sysdescr = $session->get(array("sysDescr.0"));
  print_r($sysdescr);
?>

Powyższy przykład wyświetli coś podobnego do:

STRING: Test server
Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
)

Przykład #2 Miltiple SNMP objects

$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $results = $session->get(array("sysDescr.0", "sysName.0"));
  print_r($results);
  $session->close();

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysName.0] => STRING: myhost.nodomain
)

Zobacz też:

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message
SNMP::__construct
SNMP::getErrno
SNMP


Get last error code

SNMP::get
SNMP::getError
SNMP
PHP Manual

SNMP::getErrno

(PHP 5 >= 5.4.0)

SNMP::getErrno — Get last error code

Opis

int SNMP::getErrno ( void )

Returns error code from last SNMP request.

Zwracane wartości

Returns one of SNMP error code values described in constants chapter.

Przykłady

Przykład #1 SNMP::getErrno() example

<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getErrno() == SNMP::ERRNO_TIMEOUT);
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:

  • SNMP::getError() - Get last error message
SNMP::get
SNMP::getError
SNMP


Get last error message

SNMP::getErrno
SNMP::getnext
SNMP
PHP Manual

SNMP::getError

(PHP 5 >= 5.4.0)

SNMP::getError — Get last error message

Opis

string SNMP::getError ( void )

Returns string with error from last SNMP request.

Zwracane wartości

String describing error from last SNMP request.

Przykłady

Przykład #1 SNMP::getError() example

<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getError());
?>

Powyższy przykład wyświetli:

bool(false)
string(26) "No response from 127.0.0.1"

Zobacz też:

  • SNMP::getErrno() - Get last error code
SNMP::getErrno
SNMP::getnext
SNMP


Fetch an SNMP object which follows the given object id

SNMP::getError
SNMP::set
SNMP
PHP Manual

SNMP::getnext

(PHP 5 >= 5.4.0)

SNMP::getnext — Fetch an SNMP object which follows the given object id

Opis

mixed SNMP::getnext ( mixed $object_id )

Fetch an SNMP object that follows specified object_id.

Parametry

If object_id is a string, then SNMP::getnext() will return SNMP object as string. If object_id is a array, all requested SNMP objects will be returned as associative array of the SNMP object ids and their values.

object_id

The SNMP object (OID) or objects

Zwracane wartości

Returns SNMP objects requested as string or array depending on object_id type or FALSE on error.

Błędy/Wyjątki

This method do not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occure user should set exceptions_enabled SNMP class parameter to corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Przykłady

Przykład #1 Single SNMP object

Single SNMP object may be requested in two ways: as string resulting string return value or as single-element array with associative array as output.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $nsysdescr = $session->getnext("sysDescr.0");
  echo "$nsysdescr\n";
  $nsysdescr = $session->getnext(array("sysDescr.0"));
  print_r($nsysdescr);
?>

Powyższy przykład wyświetli coś podobnego do:

OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
)

Przykład #2 Miltiple SNMP objects

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $results = $session->getnext(array("sysDescr.0", "sysName.0"));
  print_r($results);
  $session->close();
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [SNMPv2-MIB::sysLocation.0] => STRING: Nowhere
)

Zobacz też:

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message
SNMP::getError
SNMP::set
SNMP


Set the value of an SNMP object

SNMP::getnext
SNMP::setSecurity
SNMP
PHP Manual

SNMP::set

(PHP 5 >= 5.4.0)

SNMP::set — Set the value of an SNMP object

Opis

bool SNMP::set ( mixed $object_id , mixed $type , mixed $value )

Requests remote SNMP agent setting the value of one or more SNMP objects specified by the object_id.

Parametry

If object_id is string, both type and value must be string too. If object_id is array value must be equal-sized array containing corresponding values, type may be either string (it's value will be used for all object_id-value pairs) or equal-sized array with per-OID value. When any other parameters' combinations are used, a number of E_WARNING messages may be shown with detailed description.

object_id

The SNMP object id

When count of OIDs in object_id array is greater than max_oids object property set method will have to use multiple queries to perform requested value updates. In this case type and value checks are made per-chunk so second or subsequent requests may fail due to wrong type or value for OID requested. To mark this a warning is raised when count of OIDs in object_id array is greater than max_oids.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

This method do not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occure user should set exceptions_enabled SNMP class parameter to corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Przykłady

Przykład #1 Set single SNMP object id

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set('SNMPv2-MIB::sysContact.0', 's', "Nobody");
?>

Przykład #2 Set multiple values using single SNMP::set() call

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set(array('SNMPv2-MIB::sysContact.0', 'SNMPv2-MIB::sysLocation.0'), array('s', 's'), array("Nobody", "Nowhere"));
// or
  $session->set(array('SNMPv2-MIB::sysContact.0', 'SNMPv2-MIB::sysLocation.0'), 's', array("Nobody", "Nowhere"));
?>

Przykład #3 Using SNMP::set() for setting BITS SNMP object id

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set('FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  $session->set('FOO-MIB::bar.42', 'x', 'F0');
?>

Zobacz też:

  • SNMP::get() - Fetch an SNMP object

SNMP::getnext
SNMP::setSecurity
SNMP


Configures security-related SNMPv3 session parameters

SNMP::set
SNMP::walk
SNMP
PHP Manual

SNMP::setSecurity

(PHP 5 >= 5.4.0)

SNMP::setSecurity — Configures security-related SNMPv3 session parameters

Opis

bool SNMP::setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] )

setSecurity configures security-related session parameters used in SNMP protocol version 3

Parametry

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

contextName

the context name

contextEngineID

the context EngineID

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 SNMP::setSecurity() example

<?php
  $session = new SNMP(SNMP::VERSION_3, $hostname, $rwuser, $timeout, $retries);
  $session->setSecurity('authPriv', 'MD5', $auth_pass, 'AES', $priv_pass, '', 'aeeeff');
?>

Zobacz też:

  • SNMP::__construct() - Creates SNMP instance representing session to remote SNMP agent
SNMP::set
SNMP::walk
SNMP


Fetch SNMP object subtree

SNMP::setSecurity
SNMPException
SNMP
PHP Manual

SNMP::walk

(PHP 5 >= 5.4.0)

SNMP::walk — Fetch SNMP object subtree

Opis

array SNMP::walk ( string $object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters ]]] )

SNMP::walk() is used to read SNMP subtree rooted at specified object_id.

Parametry

object_id

Root of subtree to be fetched

suffix_as_key

By default full OID notation is used for keys in output array. If set to TRUE subtree prefix will be removed from keys leaving only suffix of object_id.

non_repeaters

This specifies the number of supplied variables that should not be iterated over. The default is to use this value from SNMP object.

max_repetitions

This specifies the maximum number of iterations over the repeating variables. The default is to use this value from SNMP object.

Zwracane wartości

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. When a SNMP error occures SNMP::getErrno() and SNMP::getError() can be used for retrieving error number (specific to SNMP extension, see class constants) and error message respectively.

Błędy/Wyjątki

This method do not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occure user should set exceptions_enabled SNMP class parameter to corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Przykłady

Przykład #1 SNMP::walk() example

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $fulltree = $session->walk(".");
  print_r($fulltree);
  $session->close();
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [DISMAN-EVENT-MIB::sysUpTimeInstance] => Timeticks: (1150681750) 133 days, 4:20:17.50
    [SNMPv2-MIB::sysContact.0] => STRING: Nobody
    [SNMPv2-MIB::sysName.0] => STRING: server.localdomain
    ...
)

Przykład #2 suffix_as_key example

suffix_as_key may be used when merging multiple SNMP subtrees into one. This example maps interface names to their type.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $session->valueretrieval = SNMP_VALUE_PLAIN;
  $ifDescr = $session->walk(".1.3.6.1.2.1.2.2.1.2", TRUE);
  $session->valueretrieval = SNMP_VALUE_LIBRARY;
  $ifType = $session->walk(".1.3.6.1.2.1.2.2.1.3", TRUE);
  print_r($ifDescr);
  print_r($ifType);
  $result = array();
  foreach($ifDescr as $i => $n) {
    $result[$n] = $ifType[$i];
  }
  print_r($result);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [1] => igb0
    [2] => igb1
    [3] => ipfw0
    [4] => lo0
    [5] => lagg0
)
Array
(
    [1] => INTEGER: ieee8023adLag(161)
    [2] => INTEGER: ieee8023adLag(161)
    [3] => INTEGER: ethernetCsmacd(6)
    [4] => INTEGER: softwareLoopback(24)
    [5] => INTEGER: ethernetCsmacd(6)
)
Array
(
    [igb0] => INTEGER: ieee8023adLag(161)
    [igb1] => INTEGER: ieee8023adLag(161)
    [ipfw0] => INTEGER: ethernetCsmacd(6)
    [lo0] => INTEGER: softwareLoopback(24)
    [lagg0] => INTEGER: ethernetCsmacd(6)
)

Zobacz też:

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message
SNMP::setSecurity
SNMPException
SNMP


The SNMPException class

(No version information available, might only be in SVN)

Wstęp

Represents an error raised by SNMP. You should not throw a SNMPException from your own code. See Exceptions for more information about Exceptions in PHP.

Krótki opis klasy

SNMPException extends RuntimeException {
/* Właściwości */
protected string $message ;
protected string $code ;
/* 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

message

Textual error message. Exception::getMessage() to access it.

code

SNMPlibrary error code. Use Exception::getCode() to access it.

SNMP::walk
Sockets
SNMP


Sockets

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Socket Errors
  • Socket Funkcje
    • socket_accept — Accepts a connection on a socket
    • socket_bind — Binds a name to a socket
    • socket_clear_error — Clears the error on the socket or the last error code
    • socket_close — Closes a socket resource
    • socket_connect — Initiates a connection on a socket
    • socket_create_listen — Opens a socket on port to accept connections
    • socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array
    • socket_create — Create a socket (endpoint for communication)
    • socket_get_option — Gets socket options for the socket
    • socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_last_error — Returns the last error on the socket
    • socket_listen — Listens for a connection on a socket
    • socket_read — Reads a maximum of length bytes from a socket
    • socket_recv — Receives data from a connected socket
    • socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
    • socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send — Sends data to a connected socket
    • socket_sendto — Sends a message to a socket, whether it is connected or not
    • socket_set_block — Sets blocking mode on a socket resource
    • socket_set_nonblock — Sets nonblocking mode for file descriptor fd
    • socket_set_option — Sets socket options for the socket
    • socket_shutdown — Shuts down a socket for receiving, sending, or both
    • socket_strerror — Return a string describing a socket error
    • socket_write — Write to a socket
SNMPException
Wstęp
Inne serwisy


Wstęp

The socket extension implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client.

For a more generic client-side socket interface, see
stream_socket_client(),
stream_socket_server(),
fsockopen(), and
pfsockopen().

When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.

Those unfamiliar with socket programming can find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP. The » Unix Socket FAQ might be a good start.

Sockets
Instalacja/Konfiguracja
Sockets


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Sockets


Instalacja

The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.

Informacja: Obsługa protokołu IPv6 została dodana w PHP 5.0.0.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

socket_accept(),
socket_create_listen() and
socket_create() return socket resources.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

AF_UNIX (integer)
AF_INET (integer)
AF_INET6 (integer)
Only available if compiled with IPv6 support.
SOCK_STREAM (integer)
SOCK_DGRAM (integer)
SOCK_RAW (integer)
SOCK_SEQPACKET (integer)
SOCK_RDM (integer)
MSG_OOB (integer)
MSG_WAITALL (integer)
MSG_PEEK (integer)
MSG_DONTROUTE (integer)
MSG_EOR (integer)
Not available on Windows platforms.
MSG_EOF (integer)
Not available on Windows platforms.
SO_DEBUG (integer)
SO_REUSEADDR (integer)
SO_KEEPALIVE (integer)
SO_DONTROUTE (integer)
SO_LINGER (integer)
SO_BROADCAST (integer)
SO_OOBINLINE (integer)
SO_SNDBUF (integer)
SO_RCVBUF (integer)
SO_SNDLOWAT (integer)
SO_RCVLOWAT (integer)
SO_SNDTIMEO (integer)
SO_RCVTIMEO (integer)
SO_TYPE (integer)
SO_ERROR (integer)
TCP_NODELAY (integer)
Used to disable Nagle TCP algorithm. Added in PHP 5.2.7.
SOL_SOCKET (integer)
PHP_NORMAL_READ (integer)
PHP_BINARY_READ (integer)
SOL_TCP (integer)
SOL_UDP (integer)

The following constants are only defined under Windows.

SOCKET_EINTR (integer)
SOCKET_EBADF (integer)
SOCKET_EACCES (integer)
SOCKET_EFAULT (integer)
SOCKET_EINVAL (integer)
SOCKET_EMFILE (integer)
SOCKET_EWOULDBLOCK (integer)
SOCKET_EINPROGRESS (integer)
SOCKET_EALREADY (integer)
SOCKET_ENOTSOCK (integer)
SOCKET_EDESTADDRREQ (integer)
SOCKET_EMSGSIZE (integer)
SOCKET_EPROTOTYPE (integer)
SOCKET_ENOPROTOOPT (integer)
SOCKET_EPROTONOSUPPORT (integer)
SOCKET_ESOCKTNOSUPPORT (integer)
SOCKET_EOPNOTSUPP (integer)
SOCKET_EPFNOSUPPORT (integer)
SOCKET_EAFNOSUPPORT (integer)
SOCKET_EADDRINUSE (integer)
SOCKET_EADDRNOTAVAIL (integer)
SOCKET_ENETDOWN (integer)
SOCKET_ENETUNREACH (integer)
SOCKET_ENETRESET (integer)
SOCKET_ECONNABORTED (integer)
SOCKET_ECONNRESET (integer)
SOCKET_ENOBUFS (integer)
SOCKET_EISCONN (integer)
SOCKET_ENOTCONN (integer)
SOCKET_ESHUTDOWN (integer)
SOCKET_ETOOMYREFS (integer)
SOCKET_ETIMEDOUT (integer)
SOCKET_ECONNREFUSED (integer)
SOCKET_ELOOP (integer)
SOCKET_ENAMETOOLONG (integer)
SOCKET_EHOSTDOWN (integer)
SOCKET_EHOSTUNREACH (integer)
SOCKET_ENOTEMPTY (integer)
SOCKET_EPROCLIM (integer)
SOCKET_EUSERS (integer)
SOCKET_EDUOT (integer)
SOCKET_ESTALE (integer)
SOCKET_EREMOTE (integer)
SOCKET_EDISCON (integer)
SOCKET_SYSNOTREADY (integer)
SOCKET_VERNOTSUPPORTED (integer)
SOCKET_NOTINITIALISED (integer)
SOCKET_HOST_NOT_FOUND (integer)
SOCKET_TRY_AGAIN (integer)
SOCKET_NO_RECOVERY (integer)
SOCKET_NO_DATA (integer)
SOCKET_NO_ADDRESS (integer)

The following constants are only available on UNIX-like platforms. Each constant is only defined if their equal is available on the platform.

SOCKET_EPERM (integer)
Operation not permitted.
SOCKET_ENOENT (integer)
No such file or directory.
SOCKET_EINTR (integer)
Interrupted system call.
SOCKET_EIO (integer)
I/O error.
SOCKET_ENXIO (integer)
No such device or address.
SOCKET_E2BIG (integer)
Arg list too long.
SOCKET_EBADF (integer)
Bad file number.
SOCKET_EAGAIN (integer)
Try again.
SOCKET_ENOMEM (integer)
Out of memory.
SOCKET_EACCES (integer)
Permission denied.
SOCKET_EFAULT (integer)
Bad address.
SOCKET_ENOTBLK (integer)
Block device required.
SOCKET_EBUSY (integer)
Device or resource busy.
SOCKET_EEXIST (integer)
File exists.
SOCKET_EXDEV (integer)
Cross-device link.
SOCKET_ENODEV (integer)
No such device.
SOCKET_ENOTDIR (integer)
Not a directory.
SOCKET_EISDIR (integer)
Is a directory.
SOCKET_EINVAL (integer)
Invalid argument.
SOCKET_ENFILE (integer)
File table overflow.
SOCKET_EMFILE (integer)
Too many open files.
SOCKET_ENOTTY (integer)
Not a typewriter.
SOCKET_ENOSPC (integer)
No space left on device.
SOCKET_ESPIPE (integer)
Illegal seek.
SOCKET_EROFS (integer)
Read-only file system.
SOCKET_EMLINK (integer)
Too many links.
SOCKET_EPIPE (integer)
Broken pipe.
SOCKET_ENAMETOOLONG (integer)
File name too long.
SOCKET_ENOLCK (integer)
No record locks available.
SOCKET_ENOSYS (integer)
Function not implemented.
SOCKET_ENOTEMPTY (integer)
Directory not empty.
SOCKET_ELOOP (integer)
Too many symbolic links encountered.
SOCKET_EWOULDBLOCK (integer)
Operation would block.
SOCKET_ENOMSG (integer)
No message of desired type.
SOCKET_EIDRM (integer)
Identifier removed.
SOCKET_ECHRNG (integer)
Channel number out of range.
SOCKET_EL2NSYNC (integer)
Level 2 not synchronized.
SOCKET_EL3HLT (integer)
Level 3 halted.
SOCKET_EL3RST (integer)
Level 3 reset.
SOCKET_ELNRNG (integer)
Link number out of range.
SOCKET_EUNATCH (integer)
Protocol driver not attached.
SOCKET_ENOCSI (integer)
No CSI structure available.
SOCKET_EL2HLT (integer)
Level 2 halted.
SOCKET_EBADE (integer)
Invalid exchange.
SOCKET_EBADR (integer)
Invalid request descriptor.
SOCKET_EXFULL (integer)
Exchange full.
SOCKET_ENOANO (integer)
No anode.
SOCKET_EBADRQC (integer)
Invalid request code.
SOCKET_EBADSLT (integer)
Invalid slot.
SOCKET_ENOSTR (integer)
Device not a stream.
SOCKET_ENODATA (integer)
No data available.
SOCKET_ETIME (integer)
Timer expired.
SOCKET_ENOSR (integer)
Out of streams resources.
SOCKET_ENONET (integer)
Machine is not on the network.
SOCKET_EREMOTE (integer)
Object is remote.
SOCKET_ENOLINK (integer)
Link has been severed.
SOCKET_EADV (integer)
Advertise error.
SOCKET_ESRMNT (integer)
Srmount error.
SOCKET_ECOMM (integer)
Communication error on send.
SOCKET_EPROTO (integer)
Protocol error.
SOCKET_EMULTIHOP (integer)
Multihop attempted.
SOCKET_EBADMSG (integer)
Not a data message.
SOCKET_ENOTUNIQ (integer)
Name not unique on network.
SOCKET_EBADFD (integer)
File descriptor in bad state.
SOCKET_EREMCHG (integer)
Remote address changed.
SOCKET_ERESTART (integer)
Interrupted system call should be restarted.
SOCKET_ESTRPIPE (integer)
Streams pipe error.
SOCKET_EUSERS (integer)
Too many users.
SOCKET_ENOTSOCK (integer)
Socket operation on non-socket.
SOCKET_EDESTADDRREQ (integer)
Destination address required.
SOCKET_EMSGSIZE (integer)
Message too long.
SOCKET_EPROTOTYPE (integer)
Protocol wrong type for socket.
SOCKET_EPROTOOPT (integer)
Protocol not available.
SOCKET_EPROTONOSUPPORT (integer)
Protocol not supported.
SOCKET_ESOCKTNOSUPPORT (integer)
Socket type not supported.
SOCKET_EOPNOTSUPP (integer)
Operation not supported on transport endpoint.
SOCKET_EPFNOSUPPORT (integer)
Protocol family not supported.
SOCKET_EAFNOSUPPORT (integer)
Address family not supported by protocol.
SOCKET_ADDRINUSE (integer)
Address already in use.
SOCKET_EADDRNOTAVAIL (integer)
Cannot assign requested address.
SOCKET_ENETDOWN (integer)
Network is down.
SOCKET_ENETUNREACH (integer)
Network is unreachable.
SOCKET_ENETRESET (integer)
Network dropped connection because of reset.
SOCKET_ECONNABORTED (integer)
Software caused connection abort.
SOCKET_ECONNRESET (integer)
Connection reset by peer.
SOCKET_ENOBUFS (integer)
No buffer space available.
SOCKET_EISCONN (integer)
Transport endpoint is already connected.
SOCKET_ENOTCONN (integer)
Transport endpoint is not connected.
SOCKET_ESHUTDOWN (integer)
Cannot send after transport endpoint shutdown.
SOCKET_ETOOMANYREFS (integer)
Too many references: cannot splice.
SOCKET_ETIMEDOUT (integer)
Connection timed out.
SOCKET_ECONNREFUSED (integer)
Connection refused.
SOCKET_EHOSTDOWN (integer)
Host is down.
SOCKET_EHOSTUNREACH (integer)
No route to host.
SOCKET_EALREADY (integer)
Operation already in progress.
SOCKET_EINPROGRESS (integer)
Operation now in progress.
SOCKET_EISNAM (integer)
Is a named type file.
SOCKET_EREMOTEIO (integer)
Remote I/O error.
SOCKET_EDQUOT (integer)
Quota exceeded.
SOCKET_ENOMEDIUM (integer)
No medium found.
SOCKET_EMEDIUMTYPE (integer)
Wrong medium type.
Typy zasobów
Przykłady
Sockets


Przykłady

Przykład #1 Socket example: Simple TCP/IP server

This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter 'quit'.

#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        $talkback = "PHP: You said '$buf'.\n";
        socket_write($msgsock, $talkback, strlen($talkback));
        echo "$buf\n";
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?>

Przykład #2 Socket example: Simple TCP/IP client

This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.

<?php
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
?>

Stałe predefiniowane
Socket Errors
Sockets


Socket Errors

The socket extension was written to provide a usable interface to the powerful BSD sockets. Care has been taken that the functions work equally well on Win32 and Unix implementations. Almost all of the sockets functions may fail under certain conditions and therefore emit an E_WARNING message describing the error. Sometimes this doesn't happen to the desire of the developer. For example the function socket_read() may suddenly emit an E_WARNING message because the connection broke unexpectedly. It's common to suppress the warning with the @-operator and catch the error code within the application with the socket_last_error() function. You may call the socket_strerror() function with this error code to retrieve a string describing the error. See their description for more information.

Informacja:

The E_WARNING messages generated by the socket extension are in English though the retrieved error message will appear depending on the current locale (LC_MESSAGES):

Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet

Przykłady
Socket Funkcje
Sockets


Socket Funkcje

Spis treści

  • socket_accept — Accepts a connection on a socket
  • socket_bind — Binds a name to a socket
  • socket_clear_error — Clears the error on the socket or the last error code
  • socket_close — Closes a socket resource
  • socket_connect — Initiates a connection on a socket
  • socket_create_listen — Opens a socket on port to accept connections
  • socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array
  • socket_create — Create a socket (endpoint for communication)
  • socket_get_option — Gets socket options for the socket
  • socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_last_error — Returns the last error on the socket
  • socket_listen — Listens for a connection on a socket
  • socket_read — Reads a maximum of length bytes from a socket
  • socket_recv — Receives data from a connected socket
  • socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
  • socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
  • socket_send — Sends data to a connected socket
  • socket_sendto — Sends a message to a socket, whether it is connected or not
  • socket_set_block — Sets blocking mode on a socket resource
  • socket_set_nonblock — Sets nonblocking mode for file descriptor fd
  • socket_set_option — Sets socket options for the socket
  • socket_shutdown — Shuts down a socket for receiving, sending, or both
  • socket_strerror — Return a string describing a socket error
  • socket_write — Write to a socket
Socket Errors
socket_accept
Sockets


Accepts a connection on a socket

Socket Funkcje
socket_bind
Socket Funkcje
PHP Manual

socket_accept

(PHP 4 >= 4.1.0, PHP 5)

socket_accept — Accepts a connection on a socket

Opis

resource socket_accept ( resource $socket )

After the socket socket has been created using socket_create(), bound to a name with socket_bind(), and told to listen for connections with socket_listen(), this function will accept incoming connections on that socket. Once a successful connection is made, a new socket resource is returned, which may be used for communication. If there are multiple connections queued on the socket, the first will be used. If there are no pending connections, socket_accept() will block until a connection becomes present. If socket has been made non-blocking using socket_set_blocking() or socket_set_nonblock(), FALSE will be returned.

The socket resource returned by socket_accept() may not be used to accept new connections. The original listening socket socket, however, remains open and may be reused.

Parametry

socket

A valid socket resource created with socket_create().

Zwracane wartości

Returns a new socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

Zobacz też:

  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_bind() - Binds a name to a socket
  • socket_strerror() - Return a string describing a socket error

Socket Funkcje
socket_bind
Socket Funkcje


Binds a name to a socket

socket_accept
socket_clear_error
Socket Funkcje
PHP Manual

socket_bind

(PHP 4 >= 4.1.0, PHP 5)

socket_bind — Binds a name to a socket

Opis

bool socket_bind ( resource $socket , string $address [, int $port = 0 ] )

Binds the name given in address to the socket described by socket. This has to be done before a connection is be established using socket_connect() or socket_listen().

Parametry

socket

A valid socket resource created with socket_create().

address

If the socket is of the AF_INET family, the address is an IP in dotted-quad notation (e.g. 127.0.0.1).

If the socket is of the AF_UNIX family, the address is the path of a Unix-domain socket (e.g. /tmp/my.sock).

port (Optional)

The port parameter is only used when binding an AF_INET socket, and designates the port on which to listen for connections.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Przykłady

Przykład #1 Using socket_bind() to set the source address

<?php
// Create a new socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// An example list of IP addresses owned by the computer
$sourceips['kevin']    = '127.0.0.1';
$sourceips['madcoder'] = '127.0.0.2';

// Bind the source address
socket_bind($sock, $sourceips['madcoder']);

// Connect to destination address
socket_connect($sock, '127.0.0.1', 80);

// Write
$request = 'GET / HTTP/1.1' . "\r\n" .
           'Host: example.com' . "\r\n\r\n";
socket_write($sock, $request);

// Close
socket_close($sock);

?>

Notatki

Informacja:

This function must be used on the socket before socket_connect().

Informacja:

Windows 9x/ME compatibility note: socket_last_error() may return an invalid error code if trying to bind the socket to a wrong address that does not belong to your machine.

Zobacz też:

  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_accept
socket_clear_error
Socket Funkcje


Clears the error on the socket or the last error code

socket_bind
socket_close
Socket Funkcje
PHP Manual

socket_clear_error

(PHP 4 >= 4.2.0, PHP 5)

socket_clear_error — Clears the error on the socket or the last error code

Opis

void socket_clear_error ([ resource $socket ] )

This function clears the error code on the given socket or the global last socket error if no socket is specified.

This function allows explicitly resetting the error code value either of a socket or of the extension global last error code. This may be useful to detect within a part of the application if an error occurred or not.

Parametry

socket

A valid socket resource created with socket_create().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_bind
socket_close
Socket Funkcje


Closes a socket resource

socket_clear_error
socket_connect
Socket Funkcje
PHP Manual

socket_close

(PHP 4 >= 4.1.0, PHP 5)

socket_close — Closes a socket resource

Opis

void socket_close ( resource $socket )

socket_close() closes the socket resource given by socket. This function is specific to sockets and cannot be used on any other type of resources.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_strerror() - Return a string describing a socket error

socket_clear_error
socket_connect
Socket Funkcje


Initiates a connection on a socket

socket_close
socket_create_listen
Socket Funkcje
PHP Manual

socket_connect

(PHP 4 >= 4.1.0, PHP 5)

socket_connect — Initiates a connection on a socket

Opis

bool socket_connect ( resource $socket , string $address [, int $port = 0 ] )

Initiate a connection to address using the socket resource socket, which must be a valid socket resource created with socket_create().

Parametry

socket

address

The address parameter is either an IPv4 address in dotted-quad notation (e.g. 127.0.0.1) if socket is AF_INET, a valid IPv6 address (e.g. ::1) if IPv6 support is enabled and socket is AF_INET6 or the pathname of a Unix domain socket, if the socket family is AF_UNIX.

port

The port parameter is only used and is mandatory when connecting to an AF_INET or an AF_INET6 socket, and designates the port on the remote host to which a connection should be made.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Informacja:

If the socket is non-blocking then this function returns FALSE with an error Operation now in progress.

Zobacz też:

  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_close
socket_create_listen
Socket Funkcje


Opens a socket on port to accept connections

socket_connect
socket_create_pair
Socket Funkcje
PHP Manual

socket_create_listen

(PHP 4 >= 4.1.0, PHP 5)

socket_create_listen — Opens a socket on port to accept connections

Opis

resource socket_create_listen ( int $port [, int $backlog = 128 ] )

socket_create_listen() creates a new socket resource of type AF_INET listening on all local interfaces on the given port waiting for new connections.

This function is meant to ease the task of creating a new socket which only listens to accept new connections.

Parametry

port

The port on which to listen on all interfaces.

backlog

The backlog parameter defines the maximum length the queue of pending connections may grow to. SOMAXCONN may be passed as backlog parameter, see socket_listen() for more information.

Zwracane wartości

socket_create_listen() returns a new socket resource on success or FALSE on error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Notatki

Informacja:

If you want to create a socket which only listens on a certain interface you need to use socket_create(), socket_bind() and socket_listen().

Zobacz też:

  • socket_create() - Create a socket (endpoint for communication)
  • socket_create_pair() - Creates a pair of indistinguishable sockets and stores them in an array
  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_connect
socket_create_pair
Socket Funkcje


Creates a pair of indistinguishable sockets and stores them in an array

socket_create_listen
socket_create
Socket Funkcje
PHP Manual

socket_create_pair

(PHP 4 >= 4.1.0, PHP 5)

socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array

Opis

bool socket_create_pair ( int $domain , int $type , int $protocol , array &$fd )

socket_create_pair() creates two connected and indistinguishable sockets, and stores them in fd. This function is commonly used in IPC (InterProcess Communication).

Parametry

domain

The domain parameter specifies the protocol family to be used by the socket. See socket_create() for the full list.

type

The type parameter selects the type of communication to be used by the socket. See socket_create() for the full list.

protocol

The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.

See socket_create() for the full list of supported protocols.

fd

Reference to an array in which the two socket resources will be inserted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
5.3.0 | This function is now re-enabled on Windows platforms.
4.3.0 | This function was due to a bug made unavailable on Windows platforms.

Przykłady

Przykład #1 socket_create_pair() example

<?php
$sockets = array();

/* On Windows we need to use AF_INET */
$domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);

/* Setup socket pair */
if (socket_create_pair($domain, SOCK_STREAM, 0, $sockets) === false) {
    echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and Recieve Data */
if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {
    echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
}
if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) {
    echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
}
var_dump($data);

/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?>

Przykład #2 socket_create_pair() IPC example

<?php
$ary = array();
$strone = 'Message From Parent.';
$strtwo = 'Message From Child.';

if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ary) === false) {
    echo "socket_create_pair() failed. Reason: ".socket_strerror(socket_last_error());
}
$pid = pcntl_fork();
if ($pid == -1) {
    echo 'Could not fork Process.';
} elseif ($pid) {
    /*parent*/
    socket_close($ary[0]);
    if (socket_write($ary[1], $strone, strlen($strone)) === false) {
        echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[1]));
    }
    if (socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo) {
        echo "Recieved $strtwo\n";
    }
    socket_close($ary[1]);
} else {
    /*child*/
    socket_close($ary[1]);
    if (socket_write($ary[0], $strtwo, strlen($strtwo)) === false) {
        echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[0]));
    }
    if (socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone) {
        echo "Recieved $strone\n";
    }
    socket_close($ary[0]);
}
?>

Zobacz też:

  • socket_create() - Create a socket (endpoint for communication)
  • socket_create_listen() - Opens a socket on port to accept connections
  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_create_listen
socket_create
Socket Funkcje


Create a socket (endpoint for communication)

socket_create_pair
socket_get_option
Socket Funkcje
PHP Manual

socket_create

(PHP 4 >= 4.1.0, PHP 5)

socket_create — Create a socket (endpoint for communication)

Opis

resource socket_create ( int $domain , int $type , int $protocol )

Creates and returns a socket resource, also referred to as an endpoint of communication. A typical network connection is made up of 2 sockets, one performing the role of the client, and another performing the role of the server.

Parametry

domain

The domain parameter specifies the protocol family to be used by the socket.

Available address/protocol families
Domain | Description
AF_INET | IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family.
AF_INET6 | IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family.
AF_UNIX | Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).
type

The type parameter selects the type of communication to be used by the socket.

Available socket types
Type | Description
SOCK_STREAM | Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type.
SOCK_DGRAM | Supports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type.
SOCK_SEQPACKET | Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call.
SOCK_RAW | Provides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping).
SOCK_RDM | Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.
protocol

The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.

Common protocols
Name | Description
icmp | The Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP.
udp | The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead.
tcp | The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission.

Zwracane wartości

socket_create() returns a socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

Rejestr zmian

Wersja | Opis
5.0.0 | The AF_INET6 constant was added.

Błędy/Wyjątki

If an invalid domain or type is given, socket_create() defaults to AF_INET and SOCK_STREAM respectively and additionally emits an E_WARNING message.

Zobacz też:

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_create_pair
socket_get_option
Socket Funkcje


Gets socket options for the socket

socket_create
socket_getpeername
Socket Funkcje
PHP Manual

socket_get_option

(PHP 4 >= 4.3.0, PHP 5)

socket_get_option — Gets socket options for the socket

Opis

mixed socket_get_option ( resource $socket , int $level , int $optname )

The socket_get_option() function retrieves the value for the option specified by the optname parameter for the specified socket.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

level

The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function.

optname
Available Socket Options
Option | Description | Type
SO_DEBUG | Reports whether debugging information is being recorded. | int
SO_BROADCAST | Reports whether transmission of broadcast messages is supported. | int
SO_REUSEADDR | Reports whether local addresses can be reused. | int
SO_KEEPALIVE | Reports whether connections are kept active with periodic transmission of messages. If the connected socket fails to respond to these messages, the connection is broken and processes writing to that socket are notified with a SIGPIPE signal. | int
SO_LINGER

Reports whether the socket lingers on socket_close() if data is present. By default, when the socket is closed, it attempts to send all unsent data. In the case of a connection-oriented socket, socket_close() will wait for its peer to acknowledge the data.

If l_onoff is non-zero and l_linger is zero, all the unsent data will be discarded and RST (reset) is sent to the peer in the case of a connection-oriented socket.

On the other hand, if l_onoff is non-zero and l_linger is non-zero, socket_close() will block until all the data is sent or the time specified in l_linger elapses. If the socket is non-blocking, socket_close() will fail and return an error.

array. The array will contain two keys: l_onoff and l_linger.
SO_OOBINLINE | Reports whether the socket leaves out-of-band data inline. | int
SO_SNDBUF | Reports the size of the send buffer. | int
SO_RCVBUF | Reports the size of the receive buffer. | int
SO_ERROR | Reports information about error status and clears it. | int (cannot be set by socket_set_option())
SO_TYPE | Reports the socket type (e.g. SOCK_STREAM). | int (cannot be set by socket_set_option())
SO_DONTROUTE | Reports whether outgoing messages bypass the standard routing facilities. | int
SO_RCVLOWAT | Reports the minimum number of bytes to process for socket input operations. | int
SO_RCVTIMEO | Reports the timeout value for input operations. | array. The array will contain two keys: sec which is the seconds part on the timeout value and usec which is the microsecond part of the timeout value.
SO_SNDTIMEO | Reports the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent. | array. The array will contain two keys: sec which is the seconds part on the timeout value and usec which is the microsecond part of the timeout value.
SO_SNDLOWAT | Reports the minimum number of bytes to process for socket output operations. | int
TCP_NODELAY | Reports whether the Nagle TCP algorithm is disabled. | int
MCAST_JOIN_GROUP | Joins a multicast group. (added in PHP 5.4) | array with keys "group", specifying a string with an IPv4 or IPv6 multicast address and "interface", specifying either an interface number (type int) or a string with the interface name, like "eth0". 0 can be specified to indicate the interface should be selected using routing rules. (can only be used in socket_set_option())
MCAST_LEAVE_GROUP | Leaves a multicast group. (added in PHP 5.4) | array. See MCAST_JOIN_GROUP for more information. (can only be used in socket_set_option())
MCAST_BLOCK_SOURCE | Blocks packets arriving from a specific source to a specific multicast group, which must have been previously joined. (added in PHP 5.4) | array with the same keys as MCAST_JOIN_GROUP, plus one extra key, source, which maps to a string specifying an IPv4 or IPv6 address of the source to be blocked. (can only be used in socket_set_option())
MCAST_UNBLOCK_SOURCE | Unblocks (start receiving again) packets arriving from a specific source address to a specific multicast group, which must have been previously joined. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
MCAST_JOIN_SOURCE_GROUP | Receive packets destined to a specific multicast group whose source address matches a specific value. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
MCAST_LEAVE_SOURCE_GROUP | Stop receiving packets destined to a specific multicast group whose soure address matches a specific value. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
IP_MULTICAST_IF | The outgoing interface for IPv4 multicast packets. (added in PHP 5.4) | Either int specifying the interface number or a string with an interface name, like eth0. The value 0 can be used to indicate the routing table is to used in the interface selection. The function socket_get_option() returns an interface index. Note that, unlike the C API, this option does NOT take an IP address. This eliminates the interface difference between IP_MULTICAST_IF and IPV6_MULTICAST_IF.
IPV6_MULTICAST_IF | The outgoing interface for IPv6 multicast packets. (added in PHP 5.4) | The same as IP_MULTICAST_IF.
IP_MULTICAST_LOOP | The multicast loopback policy for IPv4 packets, which determines whether multicast packets sent by this socket also reach receivers in the same host that have joined the same multicast group on the outgoing interface used by this socket. This is the case by default. (added in PHP 5.4) | int (either 0 or 1). For socket_set_option() any value will be accepted and will be converted to a boolean following the usual PHP rules.
IPV6_MULTICAST_LOOP | Analogous to IP_MULTICAST_LOOP, but for IPv6. (added in PHP 5.4) | int. See IP_MULTICAST_LOOP.
IP_MULTICAST_TTL | The time-to-live of outgoing IPv4 multicast packets. This should be a value between 0 (don't leave the interface) and 255. The default value is 1 (only the local network is reached). (added in PHP 5.4) | int between 0 and 255.
IPV6_MULTICAST_HOPS | Analogous to IP_MULTICAST_TTL, but for IPv6 packets. The value -1 is also accepted, meaning the route default should be used. (added in PHP 5.4) | int between -1 and 255.

Zwracane wartości

Returns the value of the given option, or FALSE on errors.

Przykłady

Przykład #1 socket_set_option() example

<?php
$socket = socket_create_listen(1223);

$linger = array('l_linger' => 1, 'l_onoff' => 1);
socket_set_option($socket, SOL_SOCKET, SO_LINGER, $linger);

var_dump(socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR));
?>

Rejestr zmian

Wersja | Opis
4.3.0 | The name of this function was changed. It used to be called socket_getopt().

socket_create
socket_getpeername
Socket Funkcje


Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

socket_get_option
socket_getsockname
Socket Funkcje
PHP Manual

socket_getpeername

(PHP 4 >= 4.1.0, PHP 5)

socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

Opis

bool socket_getpeername ( resource $socket , string &$address [, int &$port ] )

Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

address

If the given socket is of type AF_INET or AF_INET6, socket_getpeername() will return the peers (remote) IP address in appropriate notation (e.g. 127.0.0.1 or fe80::1) in the address parameter and, if the optional port parameter is present, also the associated port.

If the given socket is of type AF_UNIX, socket_getpeername() will return the Unix filesystem path (e.g. /var/run/daemon.sock) in the address parameter.

port

If given, this will hold the port associated to address.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. socket_getpeername() may also return FALSE if the socket type is not any of AF_INET, AF_INET6, or AF_UNIX, in which case the last socket error code is not updated.

Notatki

Informacja:

socket_getpeername() should not be used with AF_UNIX sockets created with socket_accept(). Only sockets created with socket_connect() or a primary server socket following a call to socket_bind() will return meaningful values.

Informacja:

For having socket_getpeername() to return a meaningful value, the socket it is applied upon must of course be one for which the concept of "peer" makes sense.

Zobacz też:

  • socket_getsockname() - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_get_option
socket_getsockname
Socket Funkcje


Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

socket_getpeername
socket_last_error
Socket Funkcje
PHP Manual

socket_getsockname

(PHP 4 >= 4.1.0, PHP 5)

socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

Opis

bool socket_getsockname ( resource $socket , string &$addr [, int &$port ] )

Informacja: socket_getsockname() should not be used with AF_UNIX sockets created with socket_connect(). Only sockets created with socket_accept() or a primary server socket following a call to socket_bind() will return meaningful values.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

addr

If the given socket is of type AF_INET or AF_INET6, socket_getsockname() will return the local IP address in appropriate notation (e.g. 127.0.0.1 or fe80::1) in the address parameter and, if the optional port parameter is present, also the associated port.

If the given socket is of type AF_UNIX, socket_getsockname() will return the Unix filesystem path (e.g. /var/run/daemon.sock) in the address parameter.

port

If provided, this will hold the associated port.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. socket_getsockname() may also return FALSE if the socket type is not any of AF_INET, AF_INET6, or AF_UNIX, in which case the last socket error code is not updated.

Zobacz też:

  • socket_getpeername() - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_getpeername
socket_last_error
Socket Funkcje


Returns the last error on the socket

socket_getsockname
socket_listen
Socket Funkcje
PHP Manual

socket_last_error

(PHP 4 >= 4.1.0, PHP 5)

socket_last_error — Returns the last error on the socket

Opis

int socket_last_error ([ resource $socket ] )

If a socket resource is passed to this function, the last error which occurred on this particular socket is returned. If the socket resource is omitted, the error code of the last failed socket function is returned. The latter is particularly helpful for functions like socket_create() which don't return a socket on failure and socket_select() which can fail for reasons not directly tied to a particular socket. The error code is suitable to be fed to socket_strerror() which returns a string describing the given error code.

Parametry

socket

A valid socket resource created with socket_create().

Zwracane wartości

This function returns a socket error code.

Przykłady

Przykład #1 socket_last_error() example

<?php
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if ($socket === false) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg");
}
?>

Notatki

Informacja:

socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.

socket_getsockname
socket_listen
Socket Funkcje


Listens for a connection on a socket

socket_last_error
socket_read
Socket Funkcje
PHP Manual

socket_listen

(PHP 4 >= 4.1.0, PHP 5)

socket_listen — Listens for a connection on a socket

Opis

bool socket_listen ( resource $socket [, int $backlog = 0 ] )

After the socket socket has been created using socket_create() and bound to a name with socket_bind(), it may be told to listen for incoming connections on socket.

socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

Parametry

socket

A valid socket resource created with socket_create().

backlog

A maximum of backlog incoming connections will be queued for processing. If a connection request arrives with the queue full the client may receive an error with an indication of ECONNREFUSED, or, if the underlying protocol supports retransmission, the request may be ignored so that retries may succeed.

Informacja:

The maximum number passed to the backlog parameter highly depends on the underlying platform. On Linux, it is silently truncated to SOMAXCONN. On win32, if passed SOMAXCONN, the underlying service provider responsible for the socket will set the backlog to a maximum reasonable value. There is no standard provision to find out the actual backlog value on this platform.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Zobacz też:

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_strerror() - Return a string describing a socket error

socket_last_error
socket_read
Socket Funkcje


Reads a maximum of length bytes from a socket

socket_listen
socket_recv
Socket Funkcje
PHP Manual

socket_read

(PHP 4 >= 4.1.0, PHP 5)

socket_read — Reads a maximum of length bytes from a socket

Opis

string socket_read ( resource $socket , int $length [, int $type = PHP_BINARY_READ ] )

The function socket_read() reads from the socket resource socket created by the socket_create() or socket_accept() functions.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

length

The maximum number of bytes read is specified by the length parameter. Otherwise you can use \r, \n, or \0 to end reading (depending on the type parameter, see below).

type

Optional type parameter is a named constant:

  • PHP_BINARY_READ (Default) - use the system recv() function. Safe for reading binary data.
  • PHP_NORMAL_READ - reading stops at \n or \r.

Zwracane wartości

socket_read() returns the data as a string on success, or FALSE on error (including if the remote host has closed the connection). The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of the error.

Informacja:

socket_read() returns a zero length string ("") when there is no more data to read.

Rejestr zmian

Wersja | Opis
4.1.0 | The default value for type was changed from PHP_NORMAL_READ to PHP_BINARY_READ

Zobacz też:

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error
  • socket_write() - Write to a socket

socket_listen
socket_recv
Socket Funkcje


Receives data from a connected socket

socket_read
socket_recvfrom
Socket Funkcje
PHP Manual

socket_recv

(PHP 4 >= 4.1.0, PHP 5)

socket_recv — Receives data from a connected socket

Opis

int socket_recv ( resource $socket , string &$buf , int $len , int $flags )

The socket_recv() function receives len bytes of data in buf from socket. socket_recv() can be used to gather data from connected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function.

buf is passed by reference, so it must be specified as a variable in the argument list. Data read from socket by socket_recv() will be returned in buf.

Parametry

socket

The socket must be a socket resource previously created by socket_create().

buf

The data received will be fetched to the variable specified with buf. If an error occurs, if the connection is reset, or if no data is available, buf will be set to NULL.

len

Up to len bytes will be fetched from remote host.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
Flag | Description
MSG_OOB | Process out-of-band data.
MSG_PEEK | Receive data from the beginning of the receive queue without removing it from the queue.
MSG_WAITALL | Block until at least len are received. However, if a signal is caught or the remote host disconnects, the function may return less data.
MSG_DONTWAIT | With this flag set, the function returns even if it would normally have blocked.

Zwracane wartości

socket_recv() returns the number of bytes received, or FALSE if there was an error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

Przykłady

Przykład #1 socket_recv() example

This example is a simple rewrite of the first example from Przykłady to use socket_recv().

<?php
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
$buf = 'This is my buffer.';
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
    echo "Read $bytes bytes from socket_recv(). Closing socket...";
} else {
    echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
socket_close($socket);

echo $buf . "\n";
echo "OK.\n\n";
?>

The above example will produce something like:

<h2>TCP/IP Connection</h2>
OK.
Attempting to connect to '208.77.188.166' on port '80'...OK.
Sending HTTP HEAD request...OK.
Reading response:

Closing socket...HTTP/1.1 200 OK
Date: Mon, 14 Sep 2009 08:56:36 GMT
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
ETag: "b80f4-1b6-80bfd280"
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8

OK.

socket_read
socket_recvfrom
Socket Funkcje


Receives data from a socket whether or not it is connection-oriented

socket_recv
socket_select
Socket Funkcje
PHP Manual

socket_recvfrom

(PHP 4 >= 4.1.0, PHP 5)

socket_recvfrom — Receives data from a socket whether or not it is connection-oriented

Opis

int socket_recvfrom ( resource $socket , string &$buf , int $len , int $flags , string &$name [, int &$port ] )

The socket_recvfrom() function receives len bytes of data in buf from name on port port (if the socket is not of type AF_UNIX) using socket. socket_recvfrom() can be used to gather data from both connected and unconnected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function.

The name and port must be passed by reference. If the socket is not connection-oriented, name will be set to the internet protocol address of the remote host or the path to the UNIX socket. If the socket is connection-oriented, name is NULL. Additionally, the port will contain the port of the remote host in the case of an unconnected AF_INET or AF_INET6 socket.

Parametry

socket

The socket must be a socket resource previously created by socket_create().

buf

The data received will be fetched to the variable specified with buf.

len

Up to len bytes will be fetched from remote host.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
Flag | Description
MSG_OOB | Process out-of-band data.
MSG_PEEK | Receive data from the beginning of the receive queue without removing it from the queue.
MSG_WAITALL | Block until at least len are received. However, if a signal is caught or the remote host disconnects, the function may return less data.
MSG_DONTWAIT | With this flag set, the function returns even if it would normally have blocked.
name

If the socket is of the type AF_UNIX type, name is the path to the file. Else, for unconnected sockets, name is the IP address of, the remote host, or NULL if the socket is connection-oriented.

port

This argument only applies to AF_INET and AF_INET6 sockets, and specifies the remote port from which the data is received. If the socket is connection-oriented, port will be NULL.

Zwracane wartości

socket_recvfrom() returns the number of bytes received, or FALSE if there was an error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

Przykłady

Przykład #1 socket_recvfrom() example

<?php
error_reporting(E_ALL | E_STRICT);

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 1223);

$from = '';
$port = 0;
socket_recvfrom($socket, $buf, 12, 0, $from, $port);

echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
?>

This example will initiate a UDP socket on port 1223 of 127.0.0.1 and print at most 12 characters received from a remote host.

Rejestr zmian

Wersja | Opis
4.3.0 | socket_recvfrom() is now binary safe.

Zobacz też:

  • socket_recv() - Receives data from a connected socket
  • socket_send() - Sends data to a connected socket
  • socket_sendto() - Sends a message to a socket, whether it is connected or not
  • socket_create() - Create a socket (endpoint for communication)

socket_recv
socket_select
Socket Funkcje


Runs the select() system call on the given arrays of sockets with a specified timeout

socket_recvfrom
socket_send
Socket Funkcje
PHP Manual

socket_select

(PHP 4 >= 4.1.0, PHP 5)

socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout

Opis

int socket_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )

socket_select() accepts arrays of sockets and waits for them to change status. Those coming with BSD sockets background will recognize that those socket resource arrays are in fact the so-called file descriptor sets. Three independent arrays of socket resources are watched.

Parametry

read

The sockets listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a socket resource is also ready on end-of-file, in which case a socket_read() will return a zero length string).

write

The sockets listed in the write array will be watched to see if a write will not block.

except

The sockets listed in the except array will be watched for exceptions.

tv_sec

The tv_sec and tv_usec together form the timeout parameter. The timeout is an upper bound on the amount of time elapsed before socket_select() return. tv_sec may be zero , causing socket_select() to return immediately. This is useful for polling. If tv_sec is NULL (no timeout), socket_select() can block indefinitely.

tv_usec

Ostrzeżenie

On exit, the arrays are modified to indicate which socket resource actually changed status.

You do not need to pass every array to socket_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after socket_select() returns.

Informacja:

Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

Przykład #1 Using NULL with socket_select()

<?php
$e = NULL;
socket_select($r, $w, $e, 0);
?>

Zwracane wartości

On success socket_select() returns the number of socket resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned. The error code can be retrieved with socket_last_error().

Informacja:

Be sure to use the === operator when checking for an error. Since the socket_select() may return 0 the comparison with == would evaluate to TRUE:

Przykład #2 Understanding socket_select()'s result

<?php
$e = NULL;
if (false === socket_select($r, $w, $e, 0)) {
    echo "socket_select() failed, reason: " .
        socket_strerror(socket_last_error()) . "\n";
}
?>

Przykłady

Przykład #3 socket_select() example

<?php
/* Prepare the read array */
$read   = array($socket1, $socket2);
$write  = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);

if ($num_changed_sockets === false) {
    /* Error handling */
} else if ($num_changed_sockets > 0) {
    /* At least at one of the sockets something interesting happened */
}
?>

Notatki

Informacja:

Be aware that some socket implementations need to be handled very carefully. A few basic rules:

  • You should always try to use socket_select() without timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and difficult to debug.
  • No socket resource must be added to any set if you do not intend to check its result after the socket_select() call, and respond appropriately. After socket_select() returns, all socket resources in all arrays must be checked. Any socket resource that is available for writing must be written to, and any socket resource available for reading must be read from.
  • If you read/write to a socket returns in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.
  • It's common to most socket implementations that the only exception caught with the except array is out-of-bound data received on a socket.

Zobacz też:

  • socket_read() - Reads a maximum of length bytes from a socket
  • socket_write() - Write to a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error

socket_recvfrom
socket_send
Socket Funkcje


Sends data to a connected socket

socket_select
socket_sendto
Socket Funkcje
PHP Manual

socket_send

(PHP 4 >= 4.1.0, PHP 5)

socket_send — Sends data to a connected socket

Opis

int socket_send ( resource $socket , string $buf , int $len , int $flags )

The function socket_send() sends len bytes to the socket socket from buf.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

buf

A buffer containing the data that will be sent to the remote host.

len

The number of bytes that will be sent to the remote host from buf.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
MSG_OOB | Send OOB (out-of-band) data.
MSG_EOR | Indicate a record mark. The sent data completes the record.
MSG_EOF | Close the sender side of the socket and include an appropriate notification of this at the end of the sent data. The sent data completes the transaction.
MSG_DONTROUTE | Bypass routing, use direct interface.

Zwracane wartości

socket_send() returns the number of bytes sent, or FALSE on error.

Zobacz też:

  • socket_sendto() - Sends a message to a socket, whether it is connected or not

socket_select
socket_sendto
Socket Funkcje


Sends a message to a socket, whether it is connected or not

socket_send
socket_set_block
Socket Funkcje
PHP Manual

socket_sendto

(PHP 4 >= 4.1.0, PHP 5)

socket_sendto — Sends a message to a socket, whether it is connected or not

Opis

int socket_sendto ( resource $socket , string $buf , int $len , int $flags , string $addr [, int $port = 0 ] )

The function socket_sendto() sends len bytes from buf through the socket socket to the port at the address addr.

Parametry

socket

A valid socket resource created using socket_create().

buf

The sent data will be taken from buffer buf.

len

len bytes from buf will be sent.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
MSG_OOB | Send OOB (out-of-band) data.
MSG_EOR | Indicate a record mark. The sent data completes the record.
MSG_EOF | Close the sender side of the socket and include an appropriate notification of this at the end of the sent data. The sent data completes the transaction.
MSG_DONTROUTE | Bypass routing, use direct interface.

addr

IP address of the remote host.

port

port is the remote port number at which the data will be sent.

Zwracane wartości

socket_sendto() returns the number of bytes sent to the remote host, or FALSE if an error occurred.

Przykłady

Przykład #1 socket_sendto() Example

<?php
    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

    $msg = "Ping !";
    $len = strlen($msg);

    socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 1223);
    socket_close($sock);
?>

Zobacz też:

  • socket_send() - Sends data to a connected socket

socket_send
socket_set_block
Socket Funkcje


Sets blocking mode on a socket resource

socket_sendto
socket_set_nonblock
Socket Funkcje
PHP Manual

socket_set_block

(PHP 4 >= 4.2.0, PHP 5)

socket_set_block — Sets blocking mode on a socket resource

Opis

bool socket_set_block ( resource $socket )

The socket_set_block() function removes the O_NONBLOCK flag on the socket specified by the socket parameter.

When an operation (e.g. receive, send, connect, accept, ...) is performed on a blocking socket, the script will pause its execution until it receives a signal or it can perform the operation.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 socket_set_block() example

<?php
$socket = socket_create_listen(1223);
socket_set_block($socket);

socket_accept($socket);
?>

This example creates a listening socket on all interfaces on port 1223 and sets the socket to O_BLOCK mode. socket_accept() will hang until there is a connection to accept.

Zobacz też:

  • socket_set_nonblock() - Sets nonblocking mode for file descriptor fd
  • socket_set_option() - Sets socket options for the socket

socket_sendto
socket_set_nonblock
Socket Funkcje


Sets nonblocking mode for file descriptor fd

socket_set_block
socket_set_option
Socket Funkcje
PHP Manual

socket_set_nonblock

(PHP 4 >= 4.1.0, PHP 5)

socket_set_nonblock — Sets nonblocking mode for file descriptor fd

Opis

bool socket_set_nonblock ( resource $socket )

The socket_set_nonblock() function sets the O_NONBLOCK flag on the socket specified by the socket parameter.

When an operation (e.g. receive, send, connect, accept, ...) is performed on a non-blocking socket, the script will not pause its execution until it receives a signal or it can perform the operation. Rather, if the operation would result in a block, the called function will fail.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 socket_set_nonblock() example

<?php
$socket = socket_create_listen(1223);
socket_set_nonblock($socket);

socket_accept($socket);
?>

This example creates a listening socket on all interfaces on port 1223 and sets the socket to O_NONBLOCK mode. socket_accept() will immediately fail unless there is a pending connection exactly at this moment.

Zobacz też:

  • socket_set_block() - Sets blocking mode on a socket resource
  • socket_set_option() - Sets socket options for the socket

socket_set_block
socket_set_option
Socket Funkcje


Sets socket options for the socket

socket_set_nonblock
socket_shutdown
Socket Funkcje
PHP Manual

socket_set_option

(PHP 4 >= 4.3.0, PHP 5)

socket_set_option — Sets socket options for the socket

Opis

bool socket_set_option ( resource $socket , int $level , int $optname , mixed $optval )

The socket_set_option() function sets the option specified by the optname parameter, at the specified protocol level, to the value pointed to by the optval parameter for the socket.

Parametry

socket

A valid socket resource created with socket_create() or socket_accept().

level

The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function.

optname

The available socket options are the same as those for the socket_get_option() function.

optval

The option value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 socket_set_option() example

<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!is_resource($socket)) {
    echo 'Unable to create socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!socket_bind($socket, '127.0.0.1', 1223)) {
    echo 'Unable to bind socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

$rval = socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR);

if ($rval === false) {
    echo 'Unable to get socket option: '. socket_strerror(socket_last_error()) . PHP_EOL;
} else if ($rval !== 0) {
    echo 'SO_REUSEADDR is set on socket !' . PHP_EOL;
}
?>

Rejestr zmian

Wersja | Opis
4.3.0 | This function was renamed. It used to be called socket_setopt().

socket_set_nonblock
socket_shutdown
Socket Funkcje


Shuts down a socket for receiving, sending, or both

socket_set_option
socket_strerror
Socket Funkcje
PHP Manual

socket_shutdown

(PHP 4 >= 4.1.0, PHP 5)

socket_shutdown — Shuts down a socket for receiving, sending, or both

Opis

bool socket_shutdown ( resource $socket [, int $how = 2 ] )

The socket_shutdown() function allows you to stop incoming, outgoing or all data (the default) from being sent through the socket

Parametry

socket

A valid socket resource created with socket_create().

how

The value of how can be one of the following:

possible values for how
0 | Shutdown socket reading
1 | Shutdown socket writing
2 | Shutdown socket reading and writing

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

socket_set_option
socket_strerror
Socket Funkcje


Return a string describing a socket error

socket_shutdown
socket_write
Socket Funkcje
PHP Manual

socket_strerror

(PHP 4 >= 4.1.0, PHP 5)

socket_strerror — Return a string describing a socket error

Opis

string socket_strerror ( int $errno )

socket_strerror() takes as its errno parameter a socket error code as returned by socket_last_error() and returns the corresponding explanatory text.

Informacja:

Although the error messages generated by the socket extension are in English, the system messages retrieved with this function will appear depending on the current locale (LC_MESSAGES).

Parametry

errno

A valid socket error number, likely produced by socket_last_error().

Zwracane wartości

Returns the error message associated with the errno parameter.

Przykłady

Przykład #1 socket_strerror() example

<?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
   echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (false == (@socket_bind($socket, '127.0.0.1', 80))) {
   echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
?>

The expected output from the above example (assuming the script is not run with root privileges):

socket_bind() failed: reason: Permission denied

Zobacz też:

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)

socket_shutdown
socket_write
Socket Funkcje


Write to a socket

socket_strerror
SSH2
Socket Funkcje
PHP Manual

socket_write

(PHP 4 >= 4.1.0, PHP 5)

socket_write — Write to a socket

Opis

int socket_write ( resource $socket , string $buffer [, int $length = 0 ] )

The function socket_write() writes to the socket from the given buffer.

Parametry

socket

buffer

The buffer to be written.

length

The optional parameter length can specify an alternate length of bytes written to the socket. If this length is greater then the buffer length, it is silently truncated to the length of the buffer.

Zwracane wartości

Returns the number of bytes successfully written to the socket lub FALSE w przypadku niepowodzenia. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Informacja:

It is perfectly valid for socket_write() to return zero which means no bytes have been written. Be sure to use the === operator to check for FALSE in case of an error.

Notatki

Informacja:

socket_write() does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data.

Zobacz też:

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_read() - Reads a maximum of length bytes from a socket
  • socket_strerror() - Return a string describing a socket error

socket_strerror
SSH2
Socket Funkcje


Secure Shell2

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • SSH2 Funkcje
    • ssh2_auth_hostbased_file — Authenticate using a public hostkey
    • ssh2_auth_none — Authenticate as "none"
    • ssh2_auth_password — Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file — Authenticate using a public key
    • ssh2_connect — Connect to an SSH server
    • ssh2_exec — Execute a command on a remote server
    • ssh2_fetch_stream — Fetch an extended data stream
    • ssh2_fingerprint — Retrieve fingerprint of remote server
    • ssh2_methods_negotiated — Return list of negotiated methods
    • ssh2_publickey_add — Add an authorized publickey
    • ssh2_publickey_init — Initialize Publickey subsystem
    • ssh2_publickey_list — List currently authorized publickeys
    • ssh2_publickey_remove — Remove an authorized publickey
    • ssh2_scp_recv — Request a file via SCP
    • ssh2_scp_send — Send a file via SCP
    • ssh2_sftp_lstat — Stat a symbolic link
    • ssh2_sftp_mkdir — Create a directory
    • ssh2_sftp_readlink — Return the target of a symbolic link
    • ssh2_sftp_realpath — Resolve the realpath of a provided path string
    • ssh2_sftp_rename — Rename a remote file
    • ssh2_sftp_rmdir — Remove a directory
    • ssh2_sftp_stat — Stat a file on a remote filesystem
    • ssh2_sftp_symlink — Create a symlink
    • ssh2_sftp_unlink — Delete a file
    • ssh2_sftp — Initialize SFTP subsystem
    • ssh2_shell — Request an interactive shell
    • ssh2_tunnel — Open a tunnel through a remote server
socket_write
Wstęp
Inne serwisy


Wstęp

Bindings to the » libssh2 library which provide access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport.

SSH2
Instalacja/Konfiguracja
SSH2


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SSH2


Wymagania

The » OpenSSL and » libssh2 libraries are required. Ensure that the development libraries are installed, where a typical package name might be openssl-dev.

Informacja: Version 0.4 or newer of the libssh2 library is required, although it's possible newer releases of pecl/ssh2 may require newer versions (see the release notes).

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/ssh2.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

SSH2_FINGERPRINT_MD5 (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an MD5 hash.
SSH2_FINGERPRINT_SHA1 (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an SHA1 hash.
SSH2_FINGERPRINT_HEX (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a string of hexits.
SSH2_FINGERPRINT_RAW (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a raw string of 8-bit characters.
SSH2_TERM_UNIT_CHARS (integer)
Flag to ssh2_shell() specifying that width and height are provided as character sizes.
SSH2_TERM_UNIT_PIXELS (integer)
Flag to ssh2_shell() specifying that width and height are provided in pixel units.
SSH2_DEFAULT_TERM_WIDTH (integer)
Default terminal width requested by ssh2_shell().
SSH2_DEFAULT_TERM_HEIGHT (integer)
Default terminal height requested by ssh2_shell().
SSH2_DEFAULT_TERM_UNIT (integer)
Default terminal units requested by ssh2_shell().
SSH2_STREAM_STDIO (integer)
Flag to ssh2_fetch_stream() requesting STDIO subchannel.
SSH2_STREAM_STDERR (integer)
Flag to ssh2_fetch_stream() requesting STDERR subchannel.
SSH2_DEFAULT_TERMINAL (string)
Default terminal type (e.g. vt102, ansi, xterm, vanilla) requested by ssh2_shell().
Typy zasobów
SSH2 Funkcje
SSH2


SSH2 Funkcje

Spis treści

  • ssh2_auth_hostbased_file — Authenticate using a public hostkey
  • ssh2_auth_none — Authenticate as "none"
  • ssh2_auth_password — Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file — Authenticate using a public key
  • ssh2_connect — Connect to an SSH server
  • ssh2_exec — Execute a command on a remote server
  • ssh2_fetch_stream — Fetch an extended data stream
  • ssh2_fingerprint — Retrieve fingerprint of remote server
  • ssh2_methods_negotiated — Return list of negotiated methods
  • ssh2_publickey_add — Add an authorized publickey
  • ssh2_publickey_init — Initialize Publickey subsystem
  • ssh2_publickey_list — List currently authorized publickeys
  • ssh2_publickey_remove — Remove an authorized publickey
  • ssh2_scp_recv — Request a file via SCP
  • ssh2_scp_send — Send a file via SCP
  • ssh2_sftp_lstat — Stat a symbolic link
  • ssh2_sftp_mkdir — Create a directory
  • ssh2_sftp_readlink — Return the target of a symbolic link
  • ssh2_sftp_realpath — Resolve the realpath of a provided path string
  • ssh2_sftp_rename — Rename a remote file
  • ssh2_sftp_rmdir — Remove a directory
  • ssh2_sftp_stat — Stat a file on a remote filesystem
  • ssh2_sftp_symlink — Create a symlink
  • ssh2_sftp_unlink — Delete a file
  • ssh2_sftp — Initialize SFTP subsystem
  • ssh2_shell — Request an interactive shell
  • ssh2_tunnel — Open a tunnel through a remote server
Stałe predefiniowane
ssh2_auth_hostbased_file
SSH2


Authenticate using a public hostkey

SSH2 Funkcje
ssh2_auth_none
SSH2 Funkcje
PHP Manual

ssh2_auth_hostbased_file

(PECL ssh2 >= 0.9.0)

ssh2_auth_hostbased_file — Authenticate using a public hostkey

Opis

bool ssh2_auth_hostbased_file ( resource $session , string $username , string $hostname , string $pubkeyfile , string $privkeyfile [, string $passphrase [, string $local_username ]] )

Authenticate using a public hostkey read from a file.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

hostname

pubkeyfile

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

local_username

If local_username is omitted, then the value for username will be used for it.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Authentication using a public hostkey

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_hostbased_file($connection, 'remoteusername', 'myhost.example.com',
                             '/usr/local/etc/hostkey_rsa.pub',
                             '/usr/local/etc/hostkey_rsa', 'secret',
                             'localusername')) {
  echo "Public Key Hostbased Authentication Successful\n";
} else {
  die('Public Key Hostbased Authentication Failed');
}
?>

Notatki

Informacja:

ssh2_auth_hostbased_file() requires libssh2 >= 0.7 and PHP/SSH2 >= 0.7

SSH2 Funkcje
ssh2_auth_none
SSH2 Funkcje


Authenticate as "none"

ssh2_auth_hostbased_file
ssh2_auth_password
SSH2 Funkcje
PHP Manual

ssh2_auth_none

(PECL ssh2 >= 0.9.0)

ssh2_auth_none — Authenticate as "none"

Opis

mixed ssh2_auth_none ( resource $session , string $username )

Attempt "none" authentication which usually will (and should) fail. As part of the failure, this function will return an array of accepted authentication methods.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

Zwracane wartości

Returns TRUE if the server does accept "none" as an authentication method, or an array of accepted authentication methods on failure.

Przykłady

Przykład #1 Retrieving a list of authentication methods

<?php
$connection = ssh2_connect('shell.example.com', 22);

$auth_methods = ssh2_auth_none($connection, 'user');

if (in_array('password', $auth_methods)) {
  echo "Server supports password based authentication\n";
}
?>

ssh2_auth_hostbased_file
ssh2_auth_password
SSH2 Funkcje


Authenticate over SSH using a plain password

ssh2_auth_none
ssh2_auth_pubkey_file
SSH2 Funkcje
PHP Manual

ssh2_auth_password

(PECL ssh2 >= 0.9.0)

ssh2_auth_password — Authenticate over SSH using a plain password

Opis

bool ssh2_auth_password ( resource $session , string $username , string $password )

Authenticate over SSH using a plain password

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

password

Password for username

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Authenticating with a password

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_password($connection, 'username', 'secret')) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}
?>

ssh2_auth_none
ssh2_auth_pubkey_file
SSH2 Funkcje


Authenticate using a public key

ssh2_auth_password
ssh2_connect
SSH2 Funkcje
PHP Manual

ssh2_auth_pubkey_file

(PECL ssh2 >= 0.9.0)

ssh2_auth_pubkey_file — Authenticate using a public key

Opis

bool ssh2_auth_pubkey_file ( resource $session , string $username , string $pubkeyfile , string $privkeyfile [, string $passphrase ] )

Authenticate using a public key read from a file.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

pubkeyfile

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Authentication using a public key

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_pubkey_file($connection, 'username',
                          '/home/username/.ssh/id_rsa.pub',
                          '/home/username/.ssh/id_rsa', 'secret')) {
  echo "Public Key Authentication Successful\n";
} else {
  die('Public Key Authentication Failed');
}
?>

ssh2_auth_password
ssh2_connect
SSH2 Funkcje


Connect to an SSH server

ssh2_auth_pubkey_file
ssh2_exec
SSH2 Funkcje
PHP Manual

ssh2_connect

(PECL ssh2 >= 0.9.0)

ssh2_connect — Connect to an SSH server

Opis

resource ssh2_connect ( string $host [, int $port = 22 [, array $methods [, array $callbacks ]]] )

Establish a connection to a remote SSH server.

Once connected, the client should verify the server's hostkey using ssh2_fingerprint(), then authenticate using either password or public key.

Parametry

host

port

methods

methods may be an associative array with up to four parameters as described below.

methods may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values*
kex | List of key exchange methods to advertise, comma separated in order of preference. | diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, and diffie-hellman-group-exchange-sha1
hostkey | List of hostkey methods to advertise, come separated in order of preference. | ssh-rsa and ssh-dss
client_to_server | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server.
server_to_client | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from server to client.

* - Supported Values are dependent on methods supported by underlying library. See » libssh2 documentation for additional information.

client_to_server and server_to_client may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values*
crypt | List of crypto methods to advertise, comma separated in order of preference. | rijndael-cbc@lysator.liu.se, aes256-cbc, aes192-cbc, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, arcfour, and none**
comp | List of compression methods to advertise, comma separated in order of preference. | zlib and none
mac | List of MAC methods to advertise, come separated in order of preference. | hmac-sha1, hmac-sha1-96, hmac-ripemd160, hmac-ripemd160@openssh.com, and none**

Informacja: Crypt and MAC method "none"

For security reasons, none is disabled by the underlying » libssh2 library unless explicitly enabled during build time by using the appropriate ./configure options. See documentation for the underlying library for more information.

callbacks

callbacks may be an associative array with any or all of the following parameters.

Callbacks parameters
Index | Meaning | Prototype
ignore | Name of function to call when an SSH2_MSG_IGNORE packet is received | void ignore_cb($message)
debug | Name of function to call when an SSH2_MSG_DEBUG packet is received | void debug_cb($message, $language, $always_display)
macerror | Name of function to call when a packet is received but the message authentication code failed. If the callback returns TRUE, the mismatch will be ignored, otherwise the connection will be terminated. | bool macerror_cb($packet)
disconnect | Name of function to call when an SSH2_MSG_DISCONNECT packet is received | void disconnect_cb($reason, $message, $language)

Zwracane wartości

Returns a resource on success, or FALSE on error.

Przykłady

Przykład #1 ssh2_connect() example

Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.

<?php
/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
  printf("Server disconnected with reason code [%d] and message: %s\n",
         $reason, $message);
}

$methods = array(
  'kex' => 'diffie-hellman-group1-sha1',
  'client_to_server' => array(
    'crypt' => '3des-cbc',
    'comp' => 'none'),
  'server_to_client' => array(
    'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
    'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);
if (!$connection) die('Connection failed');
?>

Zobacz też:

  • ssh2_fingerprint() - Retrieve fingerprint of remote server
  • ssh2_auth_none() - Authenticate as "none"
  • ssh2_auth_password() - Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file() - Authenticate using a public key

ssh2_auth_pubkey_file
ssh2_exec
SSH2 Funkcje


Execute a command on a remote server

ssh2_connect
ssh2_fetch_stream
SSH2 Funkcje
PHP Manual

ssh2_exec

(PECL ssh2 >= 0.9.0)

ssh2_exec — Execute a command on a remote server

Opis

resource ssh2_exec ( resource $session , string $command [, string $pty [, array $env [, int $width = 80 [, int $height = 25 [, int $width_height_type = SSH2_TERM_UNIT_CHARS ]]]]] )

Execute a command at the remote end and allocate a channel for it.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

command

pty

env

env may be passed as an associative array of name/value pairs to set in the target environment.

width

Width of the virtual terminal.

height

Height of the virtual terminal.

width_height_type

width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

Zwracane wartości

Returns a stream on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Executing a command

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
?>

Zobacz też:

  • ssh2_connect() - Connect to an SSH server
  • ssh2_shell() - Request an interactive shell
  • ssh2_tunnel() - Open a tunnel through a remote server

ssh2_connect
ssh2_fetch_stream
SSH2 Funkcje


Fetch an extended data stream

ssh2_exec
ssh2_fingerprint
SSH2 Funkcje
PHP Manual

ssh2_fetch_stream

(PECL ssh2 >= 0.9.0)

ssh2_fetch_stream — Fetch an extended data stream

Opis

resource ssh2_fetch_stream ( resource $channel , int $streamid )

Fetches an alternate substream associated with an SSH2 channel stream. The SSH2 protocol currently defines only one substream, STDERR, which has a substream ID of SSH2_STREAM_STDERR (defined as 1).

Parametry

channel

streamid

An SSH2 channel stream.

Zwracane wartości

Returns the requested stream resource.

Przykłady

Przykład #1 Opening a shell and retrieving the stderr stream associated with it

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stdio_stream = ssh2_shell($connection);
$stderr_stream = ssh2_fetch_stream($stdio_stream, SSH2_STREAM_STDERR);
?>

Zobacz też:

  • ssh2_shell() - Request an interactive shell
  • ssh2_exec() - Execute a command on a remote server
  • ssh2_connect() - Connect to an SSH server

ssh2_exec
ssh2_fingerprint
SSH2 Funkcje


Retrieve fingerprint of remote server

ssh2_fetch_stream
ssh2_methods_negotiated
SSH2 Funkcje
PHP Manual

ssh2_fingerprint

(PECL ssh2 >= 0.9.0)

ssh2_fingerprint — Retrieve fingerprint of remote server

Opis

string ssh2_fingerprint ( resource $session [, int $flags = SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX ] )

Returns a server hostkey hash from an active session.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

flags

flags may be either of SSH2_FINGERPRINT_MD5 or SSH2_FINGERPRINT_SHA1 logically ORed with SSH2_FINGERPRINT_HEX or SSH2_FINGERPRINT_RAW.

Zwracane wartości

Returns the hostkey hash as a string.

Przykłady

Przykład #1 Checking the fingerprint against a known value

<?php
$known_host = '6F89C2F0A719B30CC38ABDF90755F2E4';

$connection = ssh2_connect('shell.example.com', 22);

$fingerprint = ssh2_fingerprint($connection,
               SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);

if ($fingerprint != $known_host) {
  die("HOSTKEY MISMATCH!\n" .
      "Possible Man-In-The-Middle Attack?");
}
?>

ssh2_fetch_stream
ssh2_methods_negotiated
SSH2 Funkcje


Return list of negotiated methods

ssh2_fingerprint
ssh2_publickey_add
SSH2 Funkcje
PHP Manual

ssh2_methods_negotiated

(PECL ssh2 >= 0.9.0)

ssh2_methods_negotiated — Return list of negotiated methods

Opis

array ssh2_methods_negotiated ( resource $session )

Returns list of negotiated methods.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Zwracane wartości

Przykłady

Przykład #1 Determining what methods were negotiated

<?php
$connection = ssh2_connect('shell.example.com', 22);
$methods = ssh2_methods_negotiated($connection);

echo "Encryption keys were negotiated using: {$methods['kex']}\n";
echo "Server identified using an {$methods['hostkey']} with ";
echo "fingerprint: " . ssh2_fingerprint($connection) . "\n";

echo "Client to Server packets will use methods:\n";
echo "\tCrypt: {$methods['client_to_server']['crypt']}\n";
echo "\tComp: {$methods['client_to_server']['comp']}\n";
echo "\tMAC: {$methods['client_to_server']['mac']}\n";

echo "Server to Client packets will use methods:\n";
echo "\tCrypt: {$methods['server_to_client']['crypt']}\n";
echo "\tComp: {$methods['server_to_client']['comp']}\n";
echo "\tMAC: {$methods['server_to_client']['mac']}\n";

?>

Zobacz też:

  • ssh2_connect() - Connect to an SSH server

ssh2_fingerprint
ssh2_publickey_add
SSH2 Funkcje


Add an authorized publickey

ssh2_methods_negotiated
ssh2_publickey_init
SSH2 Funkcje
PHP Manual

ssh2_publickey_add

(PECL ssh2 >= 0.10)

ssh2_publickey_add — Add an authorized publickey

Opis

bool ssh2_publickey_add ( resource $pkey , string $algoname , string $blob [, bool $overwrite = false [, array $attributes ]] )

Informacja: Podsystem klucza publicznego używany jest do zarządzania kluczami publicznymi na serwerze, do którego klient już jest autoryzowany. Aby autoryzować się do zdalnego systemu używając autoryzacji klucza publicznego, należy skorzystać z funkcji ssh2_auth_pubkey_file().

Parametry

pkey

Publickey Subsystem resource created by ssh2_publickey_init().

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

overwrite

If the specified key already exists, should it be overwritten?

attributes

Associative array of attributes to assign to this public key. Refer to ietf-secsh-publickey-subsystem for a list of supported attributes. To mark an attribute as mandatory, precede its name with an asterisk. If the server is unable to support an attribute marked mandatory, it will abort the add process.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Adding a publickey with ssh2_publickey_add()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'password');
$pkey = ssh2_publickey_init($ssh2);

$keyblob = base64_decode('
AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5PTrLRdjNONxXH1tVFGn0
Bd26BF0aCP9qyJRlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xj
zaLpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VEHYckxQ16CjSTibI5X
69GmnYC9PNqEYq/1TP+HF10=');

ssh2_publickey_add($pkey, 'ssh-rsa', $keyblob, false, array('comment'=>"John's Key"));
?>

Zobacz też:

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_remove() - Remove an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

ssh2_methods_negotiated
ssh2_publickey_init
SSH2 Funkcje


Initialize Publickey subsystem

ssh2_publickey_add
ssh2_publickey_list
SSH2 Funkcje
PHP Manual

ssh2_publickey_init

(PECL ssh2 >= 0.10)

ssh2_publickey_init — Initialize Publickey subsystem

Opis

resource ssh2_publickey_init ( resource $session )

Request the Publickey subsystem from an already connected SSH2 server.

The publickey subsystem allows an already connected and authenticated client to manage the list of authorized public keys stored on the target server in an implementation agnostic manner. If the remote server does not support the publickey subsystem, the ssh2_publickey_init() function will return FALSE.

Parametry

session

Zwracane wartości

Returns an SSH2 Publickey Subsystem resource for use with all other ssh2_publickey_*() methods lub FALSE w przypadku niepowodzenia.

Notatki

Informacja: Podsystem klucza publicznego używany jest do zarządzania kluczami publicznymi na serwerze, do którego klient już jest autoryzowany. Aby autoryzować się do zdalnego systemu używając autoryzacji klucza publicznego, należy skorzystać z funkcji ssh2_auth_pubkey_file().

Zobacz też:

  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_remove() - Remove an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

ssh2_publickey_add
ssh2_publickey_list
SSH2 Funkcje


List currently authorized publickeys

ssh2_publickey_init
ssh2_publickey_remove
SSH2 Funkcje
PHP Manual

ssh2_publickey_list

(PECL ssh2 >= 0.10)

ssh2_publickey_list — List currently authorized publickeys

Opis

array ssh2_publickey_list ( resource $pkey )

List currently authorized publickeys.

Parametry

pkey

Publickey Subsystem resource

Zwracane wartości

Returns a numerically indexed array of keys, each of which is an associative array containing: name, blob, and attrs elements.

Publickey elements
Array Key | Meaning
name | Name of algorithm used by this publickey, for example: ssh-dss or ssh-rsa.
blob | Publickey blob as raw binary data.
attrs | Attributes assigned to this publickey. The most common attribute, and the only one supported by publickey version 1 servers, is comment, which may be any freeform string.

Przykłady

Przykład #1 Listing authorized keys with ssh2_publickey_list()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'secret');
$pkey = ssh2_publickey_init($ssh2);

$list = ssh2_publickey_list($pkey);

foreach($list as $key) {
  echo "Key: {$key['name']}\n";
  echo "Blob: " . chunk_split(base64_encode($key['blob']), 40, "\n") . "\n";
  echo "Comment: {$key['attrs']['comment']}\n\n";
}
?>

Powyższy przykład wyświetli:

Key: ssh-rsa
Blob: AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5P
TrLRdjNONxXH1tVFGn0Bd26BF0aCP9qyJRlvdJ3j
4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xjza
Lpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VE
HYckxQ16CjSTibI5X69GmnYC9PNqEYq/1TP+HF10
Comment: John's Key

Key: ssh-rsa
Blob: AAAAB3NzaHVt6VqSGd5C1yc2EAAAABIwA232dnJA
AIEA5HVt6VqSGd5PTrLRdjNONxX/1TP+HF1HVt6V
qSGd50H1tVFGn0BB3NzaC1yc2EAd26BF0aCP9qyJ
RlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26HVt6Vq
SGd5sDHwfL351xjzaLpipu\BGB3NzaC1yc2EA/1T
Comment: Alice's Key

Notatki

Informacja: Podsystem klucza publicznego używany jest do zarządzania kluczami publicznymi na serwerze, do którego klient już jest autoryzowany. Aby autoryzować się do zdalnego systemu używając autoryzacji klucza publicznego, należy skorzystać z funkcji ssh2_auth_pubkey_file().

Zobacz też:

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_remove() - Remove an authorized publickey

ssh2_publickey_init
ssh2_publickey_remove
SSH2 Funkcje


Remove an authorized publickey

ssh2_publickey_list
ssh2_scp_recv
SSH2 Funkcje
PHP Manual

ssh2_publickey_remove

(PECL ssh2 >= 0.10)

ssh2_publickey_remove — Remove an authorized publickey

Opis

bool ssh2_publickey_remove ( resource $pkey , string $algoname , string $blob )

Removes an authorized publickey.

Parametry

pkey

Publickey Subsystem Resource

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Podsystem klucza publicznego używany jest do zarządzania kluczami publicznymi na serwerze, do którego klient już jest autoryzowany. Aby autoryzować się do zdalnego systemu używając autoryzacji klucza publicznego, należy skorzystać z funkcji ssh2_auth_pubkey_file().

Zobacz też:

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

ssh2_publickey_list
ssh2_scp_recv
SSH2 Funkcje


Request a file via SCP

ssh2_publickey_remove
ssh2_scp_send
SSH2 Funkcje
PHP Manual

ssh2_scp_recv

(PECL ssh2 >= 0.9.0)

ssh2_scp_recv — Request a file via SCP

Opis

bool ssh2_scp_recv ( resource $session , string $remote_file , string $local_file )

Copy a file from the remote server to the local filesystem using the SCP protocol.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

remote_file

Path to the remote file.

local_file

Path to the local file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Downloading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_recv($connection, '/remote/filename', '/local/filename');
?>

Zobacz też:

  • ssh2_scp_send() - Send a file via SCP
  • copy() - Kopiuje plik

ssh2_publickey_remove
ssh2_scp_send
SSH2 Funkcje


Send a file via SCP

ssh2_scp_recv
ssh2_sftp_lstat
SSH2 Funkcje
PHP Manual

ssh2_scp_send

(PECL ssh2 >= 0.9.0)

ssh2_scp_send — Send a file via SCP

Opis

bool ssh2_scp_send ( resource $session , string $local_file , string $remote_file [, int $create_mode = 0644 ] )

Copy a file from the local filesystem to the remote server using the SCP protocol.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

local_file

Path to the local file.

remote_file

Path to the remote file.

create_mode

The file will be created with the mode specified by create_mode.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Uploading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?>

Zobacz też:

  • ssh2_scp_recv() - Request a file via SCP
  • copy() - Kopiuje plik

ssh2_scp_recv
ssh2_sftp_lstat
SSH2 Funkcje


Stat a symbolic link

ssh2_scp_send
ssh2_sftp_mkdir
SSH2 Funkcje
PHP Manual

ssh2_sftp_lstat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_lstat — Stat a symbolic link

Opis

array ssh2_sftp_lstat ( resource $sftp , string $path )

Stats a symbolic link on the remote filesystem without following the link.

This function is similar to using the lstat() function with the ssh2.sftp:// wrapper in PHP 5 and returns the same values.

Parametry

sftp

path

Path to the remote symbolic link.

Zwracane wartości

See the documentation for stat() for details on the values which may be returned.

Przykłady

Przykład #1 Stating a symbolic link via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_lstat($sftp, '/path/to/symlink');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

Zobacz też:

  • ssh2_sftp_stat() - Stat a file on a remote filesystem
  • lstat() - Podaje informacje o pliku lub dowiązaniu symbolicznym
  • stat() - Gives information about a file

ssh2_scp_send
ssh2_sftp_mkdir
SSH2 Funkcje


Create a directory

ssh2_sftp_lstat
ssh2_sftp_readlink
SSH2 Funkcje
PHP Manual

ssh2_sftp_mkdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_mkdir — Create a directory

Opis

bool ssh2_sftp_mkdir ( resource $sftp , string $dirname [, int $mode = 0777 [, bool $recursive = false ]] )

Creates a directory on the remote file server with permissions set to mode.

This function is similar to using mkdir() with the ssh2.sftp:// wrapper.

Parametry

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

Path of the new directory.

mode

Permissions on the new directory.

recursive

If recursive is TRUE any parent directories required for dirname will be automatically created as well.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Creating a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_mkdir($sftp, '/home/username/newdir');
/* Or:  mkdir("ssh2.sftp://$sftp/home/username/newdir"); */
?>

Zobacz też:

  • mkdir() - Tworzy katalog
  • ssh2_sftp_rmdir() - Remove a directory

ssh2_sftp_lstat
ssh2_sftp_readlink
SSH2 Funkcje


Return the target of a symbolic link

ssh2_sftp_mkdir
ssh2_sftp_realpath
SSH2 Funkcje
PHP Manual

ssh2_sftp_readlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_readlink — Return the target of a symbolic link

Opis

string ssh2_sftp_readlink ( resource $sftp , string $link )

Returns the target of a symbolic link.

Parametry

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

link

Path of the symbolic link.

Zwracane wartości

Returns the target of the symbolic link.

Przykłady

Przykład #1 Reading a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$target = ssh2_sftp_readlink($sftp, '/tmp/mysql.sock');
/* $target is now (e.g.): '/var/run/mysql.sock' */
?>

Zobacz też:

  • readlink() - Zwraca cel linku symbolicznego
  • ssh2_sftp_symlink() - Create a symlink

ssh2_sftp_mkdir
ssh2_sftp_realpath
SSH2 Funkcje


Resolve the realpath of a provided path string

ssh2_sftp_readlink
ssh2_sftp_rename
SSH2 Funkcje
PHP Manual

ssh2_sftp_realpath

(PECL ssh2 >= 0.9.0)

ssh2_sftp_realpath — Resolve the realpath of a provided path string

Opis

string ssh2_sftp_realpath ( resource $sftp , string $filename )

Translates filename into the effective real path on the remote filesystem.

Parametry

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Zwracane wartości

Returns the real path as a string.

Przykłady

Przykład #1 Resolving a pathname

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$realpath = ssh2_sftp_realpath($sftp, '/home/username/../../../..//./usr/../etc/passwd');
/* $realpath is now: '/etc/passwd' */
?>

Zobacz też:

  • realpath() - Returns canonicalized absolute pathname
  • ssh2_sftp_symlink() - Create a symlink
  • ssh2_sftp_readlink() - Return the target of a symbolic link

ssh2_sftp_readlink
ssh2_sftp_rename
SSH2 Funkcje


Rename a remote file

ssh2_sftp_realpath
ssh2_sftp_rmdir
SSH2 Funkcje
PHP Manual

ssh2_sftp_rename

(PECL ssh2 >= 0.9.0)

ssh2_sftp_rename — Rename a remote file

Opis

bool ssh2_sftp_rename ( resource $sftp , string $from , string $to )

Renames a file on the remote filesystem.

Parametry

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

from

The current file that is being renamed.

to

The new file name that replaces from.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Renaming a file via sftp

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rename($sftp, '/home/username/oldname', '/home/username/newname');
?>

Zobacz też:

  • rename() - Renames a file or directory

ssh2_sftp_realpath
ssh2_sftp_rmdir
SSH2 Funkcje


Remove a directory

ssh2_sftp_rename
ssh2_sftp_stat
SSH2 Funkcje
PHP Manual

ssh2_sftp_rmdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_rmdir — Remove a directory

Opis

bool ssh2_sftp_rmdir ( resource $sftp , string $dirname )

Removes a directory from the remote file server.

This function is similar to using rmdir() with the ssh2.sftp:// wrapper.

Parametry

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Removing a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rmdir($sftp, '/home/username/deltodel');
/* Or:  rmdir("ssh2.sftp://$sftp/home/username/dirtodel"); */
?>

Zobacz też:

  • rmdir() - Usuwanie katalogów
  • ssh2_sftp_mkdir() - Create a directory

ssh2_sftp_rename
ssh2_sftp_stat
SSH2 Funkcje


Stat a file on a remote filesystem

ssh2_sftp_rmdir
ssh2_sftp_symlink
SSH2 Funkcje
PHP Manual

ssh2_sftp_stat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_stat — Stat a file on a remote filesystem

Opis

array ssh2_sftp_stat ( resource $sftp , string $path )

Stats a file on the remote filesystem following any symbolic links.

This function is similar to using the stat() function with the ssh2.sftp:// wrapper in PHP 5 and returns the same values.

Parametry

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

path

Zwracane wartości

See the documentation for stat() for details on the values which may be returned.

Przykłady

Przykład #1 Stating a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_stat($sftp, '/path/to/file');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

Zobacz też:

  • ssh2_sftp_lstat() - Stat a symbolic link
  • lstat() - Podaje informacje o pliku lub dowiązaniu symbolicznym
  • stat() - Gives information about a file

ssh2_sftp_rmdir
ssh2_sftp_symlink
SSH2 Funkcje


Create a symlink

ssh2_sftp_stat
ssh2_sftp_unlink
SSH2 Funkcje
PHP Manual

ssh2_sftp_symlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_symlink — Create a symlink

Opis

bool ssh2_sftp_symlink ( resource $sftp , string $target , string $link )

Creates a symbolic link named link on the remote filesystem pointing to target.

Parametry

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

target

Target of the symbolic link.

link

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Creating a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_symlink($sftp, '/var/run/mysql.sock', '/tmp/mysql.sock');
?>

Zobacz też:

  • ssh2_sftp_readlink() - Return the target of a symbolic link
  • symlink() - Tworzy dowiązanie symboliczne

ssh2_sftp_stat
ssh2_sftp_unlink
SSH2 Funkcje


Delete a file

ssh2_sftp_symlink
ssh2_sftp
SSH2 Funkcje
PHP Manual

ssh2_sftp_unlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_unlink — Delete a file

Opis

bool ssh2_sftp_unlink ( resource $sftp , string $filename )

Deletes a file on the remote filesystem.

Parametry

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Deleting a file

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_unlink($sftp, '/home/username/stale_file');
?>

Zobacz też:

  • unlink() - Kasowanie pliku

ssh2_sftp_symlink
ssh2_sftp
SSH2 Funkcje


Initialize SFTP subsystem

ssh2_sftp_unlink
ssh2_shell
SSH2 Funkcje
PHP Manual

ssh2_sftp

(PECL ssh2 >= 0.9.0)

ssh2_sftp — Initialize SFTP subsystem

Opis

resource ssh2_sftp ( resource $session )

Request the SFTP subsystem from an already connected SSH2 server.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Zwracane wartości

This method returns an SSH2 SFTP resource for use with all other ssh2_sftp_*() methods and the ssh2.sftp:// fopen wrapper.

Przykłady

Przykład #1 Opening a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);

$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
?>

Zobacz też:

  • ssh2_scp_recv() - Request a file via SCP
  • ssh2_scp_send() - Send a file via SCP

ssh2_sftp_unlink
ssh2_shell
SSH2 Funkcje


Request an interactive shell

ssh2_sftp
ssh2_tunnel
SSH2 Funkcje
PHP Manual

ssh2_shell

(PECL ssh2 >= 0.9.0)

ssh2_shell — Request an interactive shell

Opis

resource ssh2_shell ( resource $session [, string $term_type = "vanilla" [, array $env [, int $width = 80 [, int $height = 25 [, int $width_height_type = SSH2_TERM_UNIT_CHARS ]]]]] )

Open a shell at the remote end and allocate a stream for it.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

term_type

term_type should correspond to one of the entries in the target system's /etc/termcap file.

env

env may be passed as an associative array of name/value pairs to set in the target environment.

width

Width of the virtual terminal.

height

Height of the virtual terminal.

width_height_type

width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

Zwracane wartości

Przykłady

Przykład #1 Executing a command

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_shell($connection, 'vt102', null, 80, 24, SSH2_TERM_UNIT_CHARS);
?>

Zobacz też:

  • ssh2_exec() - Execute a command on a remote server
  • ssh2_tunnel() - Open a tunnel through a remote server
  • ssh2_fetch_stream() - Fetch an extended data stream

ssh2_sftp
ssh2_tunnel
SSH2 Funkcje


Open a tunnel through a remote server

ssh2_shell
Stomp
SSH2 Funkcje
PHP Manual

ssh2_tunnel

(PECL ssh2 >= 0.9.0)

ssh2_tunnel — Open a tunnel through a remote server

Opis

resource ssh2_tunnel ( resource $session , string $host , int $port )

Open a socket stream to an arbitrary host/port by way of the currently connected SSH server.

Parametry

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

host

port

Zwracane wartości

Przykłady

Przykład #1 Opening a tunnel to an arbitrary host

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_pubkey_file($connection, 'username', 'id_dsa.pub', 'id_dsa');

$tunnel = ssh2_tunnel($connection, '10.0.0.101', 12345);
?>

Zobacz też:

  • ssh2_connect() - Connect to an SSH server
  • fsockopen() - Open Internet or Unix domain socket connection

ssh2_shell
Stomp
SSH2 Funkcje


Stomp Client

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Przykłady
  • Stomp Funkcje
    • stomp_connect_error — Returns a string description of the last connect error
    • stomp_version — Gets the current stomp extension version
  • Stomp — The Stomp class
    • Stomp::abort — Rolls back a transaction in progress
    • Stomp::ack — Acknowledges consumption of a message
    • Stomp::begin — Starts a transaction
    • Stomp::commit — Commits a transaction in progress
    • Stomp::__construct — Opens a connection
    • Stomp::__destruct — Closes stomp connection
    • Stomp::error — Gets the last stomp error
    • Stomp::getReadTimeout — Gets read timeout
    • Stomp::getSessionId — Gets the current stomp session ID
    • Stomp::hasFrame — Indicates whether or not there is a frame ready to read
    • Stomp::readFrame — Reads the next frame
    • Stomp::send — Sends a message
    • Stomp::setReadTimeout — Sets read timeout
    • Stomp::subscribe — Registers to listen to a given destination
    • Stomp::unsubscribe — Removes an existing subscription
  • StompFrame — The StompFrame class
    • StompFrame::__construct — Constructor
  • StompException — The StompException class
    • StompException::getDetails — Get exception details
ssh2_tunnel
Wstęp
Inne serwisy


Wstęp

This extension allows php applications to communicate with any Stomp compliant Message Brokers through easy object oriented and procedural interfaces. » Stomp official site

Stomp
Instalacja/Konfiguracja
Stomp


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Stomp


Wymagania

PECL/stomp requires PHP 5.2.2 or newer.

The » OpenSSL package >= 0.9.6 and the openssl extension may also be required to use stomp over SSL.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/stomp

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Stomp Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
stomp.default_broker | tcp://localhost:61613 | PHP_INI_ALL |
stomp.default_connection_timeout_sec | 2 | PHP_INI_ALL |
stomp.default_connection_timeout_usec | 0 | PHP_INI_ALL |
stomp.default_read_timeout_sec | 2 | PHP_INI_ALL |
stomp.default_read_timeout_usec | 0 | PHP_INI_ALL |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

stomp.default_broker string

The default broker URI to use when connecting to the message broker if no other URI is specified.

stomp.default_connection_timeout_sec integer

The seconds part of the default connection timeout.

stomp.default_connection_timeout_usec integer

The microseconds part of the default connection timeout.

stomp.default_read_timeout_sec integer

The seconds part of the default reading timeout.

stomp.default_read_timeout_usec integer

The microseconds part of the default reading timeout.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

There is only one resource type used in the stomp extension - it's the link identifier for a stomp connection.

Konfiguracja wykonawcza
Przykłady
Instalacja/Konfiguracja


Przykłady

Przykład #1 Styl obiektowy

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* send a message to the queue 'foo' */
$stomp->send($queue, $msg);

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe($queue);

/* read a frame */
$frame = $stomp->readFrame();

if ($frame->body === $msg) {
    var_dump($frame);

    /* acknowledge that the frame was received */
    $stomp->ack($frame);
}

/* close connection */
unset($stomp);

?>

Powyższy przykład wyświetli coś podobnego do:

object(StompFrame)#2 (3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["headers"]=>
  array(5) {
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:2:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257226805828"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
  ["body"]=>
  string(3) "bar"
}

Przykład #2 Styl proceduralny

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, $queue, $msg, array('transaction' => 't1'));

/* commit a transaction */
stomp_commit($link, 't1');

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, $queue);

/* read a frame */
$frame = stomp_read_frame($link);

if ($frame['body'] === $msg) {
    var_dump($frame);

    /* acknowledge that the frame was received */
    stomp_ack($link, $frame['headers']['message-id']);
}

/* close connection */
stomp_close($link);

?>

Powyższy przykład wyświetli coś podobnego do:

array(3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["body"]=>
  string(3) "bar"
  ["headers"]=>
  array(6) {
    ["transaction"]=>
    string(2) "t1"
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:3:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257227037059"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
}

Typy zasobów
Stomp Funkcje
Stomp


Stomp Funkcje

Spis treści

  • stomp_connect_error — Returns a string description of the last connect error
  • stomp_version — Gets the current stomp extension version
Przykłady
stomp_connect_error
Stomp


Returns a string description of the last connect error

Stomp Funkcje
stomp_version
Stomp Funkcje
PHP Manual

stomp_connect_error

(PECL stomp >= 0.3.0)

stomp_connect_error — Returns a string description of the last connect error

Opis

string stomp_connect_error ( void )

Returns a string description of the last connect error.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A string that describes the error, or NULL if no error occurred.

Przykłady

Przykład #1 stomp_connect_error() example

<?php
$link = stomp_connect('http://localhost:61613');

if(!$link) {
    die('Connection failed: ' . stomp_connect_error());
}
?>

Powyższy przykład wyświetli coś podobnego do:

Connection failed: Invalid Broker URI scheme

Stomp Funkcje
stomp_version
Stomp Funkcje


Gets the current stomp extension version

stomp_connect_error
Stomp
Stomp Funkcje
PHP Manual

stomp_version

(PECL stomp >= 0.1.0)

stomp_version — Gets the current stomp extension version

Opis

string stomp_version ( void )

Returns a string containing the version of the current stomp extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

It returns the current stomp extension version

Przykłady

Przykład #1 stomp_version() example

<?php

var_dump(stomp_version());

?>

Powyższy przykład wyświetli coś podobnego do:

string(5) "0.2.0"

stomp_connect_error
Stomp
Stomp Funkcje


The Stomp class

(No version information available, might only be in SVN)

Wstęp

Represents a connection between PHP and a Stomp compliant Message Broker.

Krótki opis klasy

Stomp {
/* Metody */
public bool abort ( string $transaction_id [, array $headers ] )
public bool ack ( mixed $msg [, array $headers ] )
public bool begin ( string $transaction_id [, array $headers ] )
public bool commit ( string $transaction_id [, array $headers ] )
public __construct ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )
public bool __destruct ( void )
public string error ( void )
public array getReadTimeout ( void )
public string getSessionId ( void )
public bool hasFrame ( void )
public stompframe readFrame ([ string $class_name = "stompFrame" ] )
public bool send ( string $destination , mixed $msg [, array $headers ] )
public void setReadTimeout ( int $seconds [, int $microseconds ] )
public bool subscribe ( string $destination [, array $headers ] )
public bool unsubscribe ( string $destination [, array $headers ] )
}

Spis treści

  • Stomp::abort — Rolls back a transaction in progress
  • Stomp::ack — Acknowledges consumption of a message
  • Stomp::begin — Starts a transaction
  • Stomp::commit — Commits a transaction in progress
  • Stomp::__construct — Opens a connection
  • Stomp::__destruct — Closes stomp connection
  • Stomp::error — Gets the last stomp error
  • Stomp::getReadTimeout — Gets read timeout
  • Stomp::getSessionId — Gets the current stomp session ID
  • Stomp::hasFrame — Indicates whether or not there is a frame ready to read
  • Stomp::readFrame — Reads the next frame
  • Stomp::send — Sends a message
  • Stomp::setReadTimeout — Sets read timeout
  • Stomp::subscribe — Registers to listen to a given destination
  • Stomp::unsubscribe — Removes an existing subscription
stomp_version
Stomp::abort
Stomp


Rolls back a transaction in progress

Stomp
Stomp::ack
Stomp
PHP Manual

Stomp::abort

stomp_abort

(PECL stomp >= 0.1.0)

Stomp::abort -- stomp_abort — Rolls back a transaction in progress

Opis

Styl obiektowy (method):

public bool Stomp::abort ( string $transaction_id [, array $headers ] )

Styl proceduralny:

bool stomp_abort ( resource $link , string $transaction_id [, array $headers ] )

Rolls back a transaction in progress.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction to abort.

headers

Associative array containing the additional headers (example: receipt).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Wskazówka

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* begin a transaction */
$stomp->begin('t1');

/* send a message to the queue */
$stomp->send('/queue/foo', 'bar', array('transaction' => 't1'));

/* rollback */
$stomp->abort('t1');

/* close connection */
unset($stomp);
?>

Przykład #2 Styl proceduralny

<?php

/* connection */
$link = stomp_connect('tcp://localhost:61613');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1'));

/* rollback */
stomp_abort($link, 't1');

/* close connection */
stomp_close($link);

?>

Stomp
Stomp::ack
Stomp


Acknowledges consumption of a message

Stomp::abort
Stomp::begin
Stomp
PHP Manual

Stomp::ack

stomp_ack

(PECL stomp >= 0.1.0)

Stomp::ack -- stomp_ack — Acknowledges consumption of a message

Opis

Styl obiektowy (method):

public bool Stomp::ack ( mixed $msg [, array $headers ] )

Styl proceduralny:

bool stomp_ack ( resource $link , mixed $msg [, array $headers ] )

Acknowledges consumption of a message from a subscription using client acknowledgment.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

msg

The message/messageId to be acknowledged.

headers

Associative array containing the additional headers (example: receipt).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Wskazówka

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Przykłady

Przykład #1 Styl obiektowy

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* send a message to the queue 'foo' */
$stomp->send($queue, $msg);

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe($queue);

/* read a frame */
$frame = $stomp->readFrame();

if ($frame->body === $msg) {
    /* acknowledge that the frame was received */
    $stomp->ack($frame);
}

/* remove the subscription */
$stomp->unsubscribe($queue);

/* close connection */
unset($stomp);

?>

Przykład #2 Styl proceduralny

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, $queue, $msg, array('transaction' => 't1'));

/* commit a transaction */
stomp_commit($link, 't1');

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, $queue);

/* read a frame */
$frame = stomp_read_frame($link);

if ($frame['body'] === $msg) {
    /* acknowledge that the frame was received */
    stomp_ack($link, $frame['headers']['message-id']);
}

/* remove the subscription */
stomp_unsubscribe($link, $queue);

/* close connection */
stomp_close($link);

?>

Stomp::abort
Stomp::begin
Stomp


Starts a transaction

Stomp::ack
Stomp::commit
Stomp
PHP Manual

Stomp::begin

stomp_begin

(PECL stomp >= 0.1.0)

Stomp::begin -- stomp_begin — Starts a transaction

Opis

Styl obiektowy (method):

public bool Stomp::begin ( string $transaction_id [, array $headers ] )

Styl proceduralny:

bool stomp_begin ( resource $link , string $transaction_id [, array $headers ] )

Starts a transaction.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction id.

headers

Associative array containing the additional headers (example: receipt).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Wskazówka

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Przykłady

See stomp_commit() or stomp_abort().

Stomp::ack
Stomp::commit
Stomp


Commits a transaction in progress

Stomp::begin
Stomp::__construct
Stomp
PHP Manual

Stomp::commit

stomp_commit

(PECL stomp >= 0.1.0)

Stomp::commit -- stomp_commit — Commits a transaction in progress

Opis

Styl obiektowy (method):

public bool Stomp::commit ( string $transaction_id [, array $headers ] )

Styl proceduralny:

bool stomp_commit ( resource $link , string $transaction_id [, array $headers ] )

Commits a transaction in progress.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction id.

headers

Associative array containing the additional headers (example: receipt).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Wskazówka

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* begin a transaction */
$stomp->begin('t1');

/* send a message to the queue */
$stomp->send('/queue/foo', 'bar', array('transaction' => 't1'));

/* commit */
$stomp->commit('t1');

/* close connection */
unset($stomp);

?>

Przykład #2 Styl proceduralny

<?php

/* connection */
$link = stomp_connect('tcp://localhost:61613');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1'));

/* commit */
stomp_commit($link, 't1');

/* close connection */
stomp_close($link);

?>

Stomp::begin
Stomp::__construct
Stomp


Opens a connection

Stomp::commit
Stomp::__destruct
Stomp
PHP Manual

Stomp::__construct

stomp_connect

(PECL stomp >= 0.1.0)

Stomp::__construct -- stomp_connect — Opens a connection

Opis

Styl obiektowy (constructor):

public Stomp::__construct ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )

Styl proceduralny:

resource stomp_connect ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )

Opens a connection to a stomp compliant Message Broker.

Parametry

broker

The broker URI

username

The username.

password

The password.

headers

Associative array containing the additional headers (example: receipt).

Zwracane wartości

Informacja:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Rejestr zmian

Wersja | Opis
1.0.1 | The headers parameter was added

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* close connection */
unset($stomp);

?>

Przykład #2 Styl proceduralny

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* close connection */
stomp_close($link);

?>

Stomp::commit
Stomp::__destruct
Stomp


Closes stomp connection

Stomp::__construct
Stomp::error
Stomp
PHP Manual

Stomp::__destruct

stomp_close

(PECL stomp >= 0.1.0)

Stomp::__destruct -- stomp_close — Closes stomp connection

Opis

Styl obiektowy (destructor):

public bool Stomp::__destruct ( void )

Styl proceduralny:

bool stomp_close ( resource $link )

Closes a previously opened connection.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

See stomp_connect().

Stomp::__construct
Stomp::error
Stomp


Gets the last stomp error

Stomp::__destruct
Stomp::getReadTimeout
Stomp
PHP Manual

Stomp::error

stomp_error

(PECL stomp >= 0.1.0)

Stomp::error -- stomp_error — Gets the last stomp error

Opis

Styl obiektowy (method):

public string Stomp::error ( void )

Styl proceduralny:

string stomp_error ( resource $link )

Gets the last stomp error.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Zwracane wartości

Returns an error string or FALSE if no error occurred.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->error());

if (!$stomp->abort('unknown-transaction', array('receipt' => 'foo'))) {
    var_dump($stomp->error());
}

/* close connection */
unset($stomp);

?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
string(43) "Invalid transaction id: unknown-transaction"

Przykład #2 Styl proceduralny

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_error($link));

if (!stomp_abort($link, 'unknown-transaction', array('receipt' => 'foo'))) {
    var_dump(stomp_error($link));
}

/* close connection */
stomp_close($link);

?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
string(43) "Invalid transaction id: unknown-transaction"

Stomp::__destruct
Stomp::getReadTimeout
Stomp


Gets read timeout

Stomp::error
Stomp::getSessionId
Stomp
PHP Manual

Stomp::getReadTimeout

stomp_get_read_timeout

(PECL stomp >= 0.3.0)

Stomp::getReadTimeout -- stomp_get_read_timeout — Gets read timeout

Opis

Styl obiektowy (method):

public array Stomp::getReadTimeout ( void )

Styl proceduralny:

array stomp_get_read_timeout ( resource $link )

Gets read timeout

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Zwracane wartości

Returns an array with 2 elements: sec and usec.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->getReadTimeout());

/* close connection */
unset($stomp);

?>

Powyższy przykład wyświetli coś podobnego do:

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}

Przykład #2 Styl proceduralny

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_get_read_timeout($link));

/* close connection */
stomp_close($link);

?>

Powyższy przykład wyświetli coś podobnego do:

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}

Stomp::error
Stomp::getSessionId
Stomp


Gets the current stomp session ID

Stomp::getReadTimeout
Stomp::hasFrame
Stomp
PHP Manual

Stomp::getSessionId

stomp_get_session_id

(PECL stomp >= 0.1.0)

Stomp::getSessionId -- stomp_get_session_id — Gets the current stomp session ID

Opis

Styl obiektowy (method):

public string Stomp::getSessionId ( void )

Styl proceduralny:

string stomp_get_session_id ( resource $link )

Gets the current stomp session ID.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Zwracane wartości

string session id on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->getSessionId());

/* close connection */
unset($stomp);

?>

Powyższy przykład wyświetli coś podobnego do:

string(35) "ID:php.net-52873-1257291895530-4:14"

Przykład #2 Styl proceduralny

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_get_session_id($link));

/* close connection */
stomp_close($link);

?>

Powyższy przykład wyświetli coś podobnego do:

string(35) "ID:php.net-52873-1257291895530-4:14"

Stomp::getReadTimeout
Stomp::hasFrame
Stomp


Indicates whether or not there is a frame ready to read

Stomp::getSessionId
Stomp::readFrame
Stomp
PHP Manual

Stomp::hasFrame

stomp_has_frame

(PECL stomp >= 0.1.0)

Stomp::hasFrame -- stomp_has_frame — Indicates whether or not there is a frame ready to read

Opis

Styl obiektowy (method):

public bool Stomp::hasFrame ( void )

Styl proceduralny:

bool stomp_has_frame ( resource $link )

Indicates whether or not there is a frame ready to read.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Zwracane wartości

Returns TRUE if a frame is ready to read, or FALSE otherwise.

Stomp::getSessionId
Stomp::readFrame
Stomp


Reads the next frame

Stomp::hasFrame
Stomp::send
Stomp
PHP Manual

Stomp::readFrame

stomp_read_frame

(PECL stomp >= 0.1.0)

Stomp::readFrame -- stomp_read_frame — Reads the next frame

Opis

Styl obiektowy (method):

public stompframe Stomp::readFrame ([ string $class_name = "stompFrame" ] )

Styl proceduralny:

array stomp_read_frame ( resource $link )

Reads the next frame. It is possible to instantiate an object of a specific class, and pass parameters to that class's constructor.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

class_name

The name of the class to instantiate. If not specified, a stompFrame object is returned.

Zwracane wartości

Informacja:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Rejestr zmian

Wersja | Opis
Stomp 0.4.0 | class_name parameter was added.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe('/queue/foo');

/* read a frame */
var_dump($stomp->readFrame());

/* close connection */
unset($stomp);

?>

Powyższy przykład wyświetli coś podobnego do:

object(StompFrame)#2 (3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["headers"]=>
  array(5) {
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:2:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257226805828"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
  ["body"]=>
  string(3) "bar"
}

Przykład #2 Styl proceduralny

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, '/queue/foo');

/* read a frame */
$frame = stomp_read_frame($link);

/* close connection */
stomp_close($link);

?>

Powyższy przykład wyświetli coś podobnego do:

array(3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["body"]=>
  string(3) "bar"
  ["headers"]=>
  array(6) {
    ["transaction"]=>
    string(2) "t1"
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:3:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257227037059"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
}

Stomp::hasFrame
Stomp::send
Stomp


Sends a message

Stomp::readFrame
Stomp::setReadTimeout
Stomp
PHP Manual

Stomp::send

stomp_send

(PECL stomp >= 0.1.0)

Stomp::send -- stomp_send — Sends a message

Opis

Styl obiektowy (method):

public bool Stomp::send ( string $destination , mixed $msg [, array $headers ] )

Styl proceduralny:

bool stomp_send ( resource $link , string $destination , mixed $msg [, array $headers ] )

Sends a message to the Message Broker.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Where to send the message

msg

Message to send.

headers

Associative array containing the additional headers (example: receipt).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Wskazówka

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Przykłady

See stomp_ack().

Stomp::readFrame
Stomp::setReadTimeout
Stomp


Sets read timeout

Stomp::send
Stomp::subscribe
Stomp
PHP Manual

Stomp::setReadTimeout

stomp_set_read_timeout

(PECL stomp >= 0.3.0)

Stomp::setReadTimeout -- stomp_set_read_timeout — Sets read timeout

Opis

Styl obiektowy (method):

public void Stomp::setReadTimeout ( int $seconds [, int $microseconds ] )

Styl proceduralny:

void stomp_set_read_timeout ( resource $link , int $seconds [, int $microseconds ] )

Sets read timeout.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Przykłady

Przykład #1 Styl obiektowy

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

$stomp->setReadTimeout(10);

/* close connection */
unset($stomp);

?>

Przykład #2 Styl proceduralny

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

stomp_set_read_timeout($link, 10);

/* close connection */
stomp_close($link);

?>

Stomp::send
Stomp::subscribe
Stomp


Registers to listen to a given destination

Stomp::setReadTimeout
Stomp::unsubscribe
Stomp
PHP Manual

Stomp::subscribe

stomp_subscribe

(PECL stomp >= 0.1.0)

Stomp::subscribe -- stomp_subscribe — Registers to listen to a given destination

Opis

Styl obiektowy (method):

public bool Stomp::subscribe ( string $destination [, array $headers ] )

Styl proceduralny:

bool stomp_subscribe ( resource $link , string $destination [, array $headers ] )

Registers to listen to a given destination.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Destination to subscribe to.

headers

Associative array containing the additional headers (example: receipt).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Wskazówka

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Przykłady

See stomp_ack().

Stomp::setReadTimeout
Stomp::unsubscribe
Stomp


Removes an existing subscription

Stomp::subscribe
StompFrame
Stomp
PHP Manual

Stomp::unsubscribe

stomp_unsubscribe

(PECL stomp >= 0.1.0)

Stomp::unsubscribe -- stomp_unsubscribe — Removes an existing subscription

Opis

Styl obiektowy (method):

public bool Stomp::unsubscribe ( string $destination [, array $headers ] )

Styl proceduralny:

bool stomp_unsubscribe ( resource $link , string $destination [, array $headers ] )

Removes an existing subscription.

Parametry

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Subscription to remove.

headers

Associative array containing the additional headers (example: receipt).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Wskazówka

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Przykłady

See stomp_ack().

Stomp::subscribe
StompFrame
Stomp


The StompFrame class

(No version information available, might only be in SVN)

Wstęp

Represents a message which was sent or received from a Stomp compliant Message Broker.

Krótki opis klasy

StompFrame {
/* Właściwości */
public $command ;
public $headers ;
public $body ;
/* Metody */
__construct ([ string $command [, array $headers [, string $body ]]] )
}

Właściwości

command

Frame command.

headers

Frame headers (array).

body

Frame body.

Spis treści

  • StompFrame::__construct — Constructor
Stomp::unsubscribe
StompFrame::__construct
Stomp


Constructor

StompFrame
StompException
StompFrame
PHP Manual

StompFrame::__construct

(PECL stomp >= 0.1.0)

StompFrame::__construct — Constructor

Opis

StompFrame::__construct ([ string $command [, array $headers [, string $body ]]] )

Constructor.

Parametry

command

Frame command

headers

Frame headers (array).

body

Frame body.

StompFrame
StompException
StompFrame


The StompException class

(No version information available, might only be in SVN)

Wstęp

Represents an error raised by the stomp extension. See Exceptions for more information about Exceptions in PHP.

Krótki opis klasy

StompException extends Exception {
/* 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 )
/* Metody */
public string getDetails ( void )
}

Spis treści

  • StompException::getDetails — Get exception details
StompFrame::__construct
StompException::getDetails
Stomp


Get exception details

StompException
SVM
StompException
PHP Manual

StompException::getDetails

(No version information available, might only be in SVN)

StompException::getDetails — Get exception details

Opis

public string StompException::getDetails ( void )

Get exception details.

Zwracane wartości

string containing the error details.

StompException
SVM
StompException


Support Vector Machine

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Przykłady
  • SVM — The SVM class
    • SVM::__construct — Construct a new SVM object
    • SVM::crossvalidate — Test training params on subsets of the training data.
    • SVM::getOptions — Return the current training parameters
    • SVM::setOptions — Set training parameters
    • SVM::train — Create a SVMModel based on training data
  • SVMModel — The SVMModel class
    • SVMModel::checkProbabilityModel — Returns true if the model has probability information
    • SVMModel::__construct — Construct a new SVMModel
    • SVMModel::getLabels — Get the labels the model was trained on
    • SVMModel::getNrClass — Returns the number of classes the model was trained with
    • SVMModel::getSvmType — Get the SVM type the model was trained with
    • SVMModel::getSvrProbability — Get the sigma value for regression types
    • SVMModel::load — Load a saved SVM Model
    • SVMModel::predict_probability — Return class probabilities for previous unseen data
    • SVMModel::predict — Predict a value for previously unseen data
    • SVMModel::save — Save a model to a file
StompException::getDetails
Wstęp
Inne serwisy


Wstęp

LibSVM is an efficient solver for SVM classification and regression problems. The svm extension wraps this in a PHP interface for easy use in PHP scripts.

SVM
Instalacja/Konfiguracja
SVM


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SVM


Wymagania

Libsvm itself is required, and is available through some package management - libsvm-devel for RPM based system or libsvm-dev for Debian based ones. Alternatively it is available direct from the website. If installing from the » official website then some steps will need to be taken as the package does not install automatically. For example, assuming the latest version is 3.1:

wget http://www.csie.ntu.edu.tw/~cjlin/cgi-bin/libsvm.cgi?+http://www.csie.ntu.edu.tw/~cjlin/libsvm+tar.gz
tar xvzf libsvm-3.1.tar.gz
cd libsvm-3.1
make lib
cp libsvm.so.1 /usr/lib
ln -s libsvm.so.1 libsvm.so
ldconfig
ldconfig --print | grep libsvm

This last step should show libsvm is installed.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/svm

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Przykłady

The basic process is to define parameters, supply training data to generate a model on, then make predictions based on the model. There are a default set of parameters that should get some results with most any input, so we'll start by looking at the data.

Data is supplied in either a file, a stream, or as an array. If supplied in a file or a stream, it must contain one line per training example, which must be formatted as an integer class (usually 1 and -1) followed by a series of feature/value pairs, in increasing feature order. The features are integers, the values floats, usually scaled 0-1. For example:

-1 1:0.43 3:0.12 9284:0.2

In a document classification problem, say a spam checker, each line would represent a document. There would be two classes, -1 for spam, 1 for ham. Each feature would represent some word, and the value would represent that importance of that word to the document (perhaps the frequency count, with the total scaled to unit length). Features that were 0 (e.g. the word did not appear in the document at all) would simply not be included.

In array mode, the data must be passed as an array of arrays. Each sub-array must have the class as the first element, then key => value sets for the feature values pairs.

This data is passed to the SVM class's train function, which will return an SVM model is successful.

Once a model has been generated, it can be used to make predictions about previously unseen data. This can be passed as an array to the model's predict function, in the same format as before, but without the label. The response will be the class.

Models can be saved and restored as required, using the save and load functions, which both take a file location.

Przykład #1 Train from array

<?php
$data = array(
    array(-1, 1 => 0.43, 3 => 0.12, 9284 => 0.2),
    array(1, 1 => 0.22, 5 => 0.01, 94 => 0.11),
);

$svm = new SVM();
$model = $svm->train($data);

$data = array(1 => 0.43, 3 => 0.12, 9284 => 0.2);
$result = $model->predict($data);
var_dump($result);
$model->save('model.svm');
?>

Powyższy przykład wyświetli coś podobnego do:

int(-1)

Przykład #2 Train from a file

<?php
$svm = new SVM();
$model = $svm->train("traindata.txt");
?>

Typy zasobów
SVM
SVM


The SVM class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

SVM {
/* Constants */
const integer C_SVC = 0 ;
const integer NU_SVC = 1 ;
const integer ONE_CLASS = 2 ;
const integer EPSILON_SVR = 3 ;
const integer NU_SVR = 4 ;
const integer KERNEL_LINEAR = 0 ;
const integer KERNEL_POLY = 1 ;
const integer KERNEL_RBF = 2 ;
const integer KERNEL_SIGMOID = 3 ;
const integer KERNEL_PRECOMPUTED = 4 ;
const integer OPT_TYPE = 101 ;
const integer OPT_KERNEL_TYPE = 102 ;
const integer OPT_DEGREE = 103 ;
const integer OPT_SHRINKING = 104 ;
const integer OPT_PROPABILITY = 105 ;
const integer OPT_GAMMA = 201 ;
const integer OPT_NU = 202 ;
const integer OPT_EPS = 203 ;
const integer OPT_P = 204 ;
const integer OPT_COEF_ZERO = 205 ;
const integer OPT_C = 206 ;
const integer OPT_CACHE_SIZE = 207 ;
/* Methods */
public __construct ( void )
public float svm::crossvalidate ( array $problem , int $number_of_folds )
public array getOptions ( void )
public bool setOptions ( array $params )
public SVMModel svm::train ( array $problem [, array $weights ] )
}

Stałe predefiniowane

SVM Constants

SVM::C_SVC

The basic C_SVC SVM type. The default, and a good starting point

SVM::NU_SVC

The NU_SVC type uses a different, more flexible, error weighting

SVM::ONE_CLASS

One class SVM type. Train just on a single class, using outliers as negative examples

SVM::EPSILON_SVR

A SVM type for regression (predicting a value rather than just a class)

SVM::NU_SVR

A NU style SVM regression type

SVM::KERNEL_LINEAR

A very simple kernel, can work well on large document classification problems

SVM::KERNEL_POLY

A polynomial kernel

SVM::KERNEL_RBF

The common Gaussian RBD kernel. Handles non-linear problems well and is a good default for classification

SVM::KERNEL_SIGMOID

A kernel based on the sigmoid function. Using this makes the SVM very similar to a two layer sigmoid based neural network

SVM::KERNEL_PRECOMPUTED

A precomputed kernel - currently unsupported.

SVM::OPT_TYPE

The options key for the SVM type

SVM::OPT_KERNEL_TYPE

The options key for the kernel type

SVM::OPT_DEGREE

SVM::OPT_SHRINKING

Training parameter, boolean, for whether to use the shrinking heuristics

SVM::OPT_PROBABILITY

Training parameter, boolean, for whether to collect and use probability estimates

SVM::OPT_GAMMA

Algorithm parameter for Poly, RBF and Sigmoid kernel types.

SVM::OPT_NU

The option key for the nu parameter, only used in the NU_ SVM types

SVM::OPT_EPS

The option key for the Epsilon parameter, used in epsilon regression

SVM::OPT_P

Training parameter used by Episilon SVR regression

SVM::OPT_COEF_ZERO

Algorithm parameter for poly and sigmoid kernels

SVM::OPT_C

The option for the cost parameter that controls tradeoff between errors and generality - effectively the penalty for misclassifying training examples.

SVM::OPT_CACHE_SIZE

Memory cache size, in MB

Spis treści

  • SVM::__construct — Construct a new SVM object
  • SVM::crossvalidate — Test training params on subsets of the training data.
  • SVM::getOptions — Return the current training parameters
  • SVM::setOptions — Set training parameters
  • SVM::train — Create a SVMModel based on training data
Przykłady
SVM::__construct
SVM


Construct a new SVM object

SVM
SVM::crossvalidate
SVM
PHP Manual

SVM::__construct

(PECL svm >= 0.1.0)

SVM::__construct — Construct a new SVM object

Opis

public SVM::__construct ( void )

Constructs a new SVM object ready to accept training data.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Throws SVMException if the libsvm library could not be loaded

SVM
SVM::crossvalidate
SVM


Test training params on subsets of the training data.

SVM::__construct
SVM::getOptions
SVM
PHP Manual

SVM::crossvalidate

(PECL svm >= 0.1.0)

SVM::crossvalidate — Test training params on subsets of the training data.

Opis

public float svm::crossvalidate ( array $problem , int $number_of_folds )

Crossvalidate can be used to test the effectiveness of the current parameter set on a subset of the training data. Given a problem set and a n "folds", it separates the problem set into n subsets, and the repeatedly trains on one subset and tests on another. While the accuracy will generally be lower than a SVM trained on the enter data set, the accuracy score returned should be relatively useful, so it can be used to test different training parameters.

Parametry

problem

The problem data. This can either be in the form of an array, the URL of an SVMLight formatted file, or a stream to an opened SVMLight formatted datasource.

number_of_folds

The number of sets the data should be divided into and cross tested. A higher number means smaller training sets and less reliability. 5 is a good number to start with.

Zwracane wartości

The correct percentage, expressed as a floating point number from 0-1. In the case of NU_SVC or EPSILON_SVR kernels the mean squared error will returned instead.

Zobacz też:

  • SVM::train() - Create a SVMModel based on training data

SVM::__construct
SVM::getOptions
SVM


Return the current training parameters

SVM::crossvalidate
SVM::setOptions
SVM
PHP Manual

SVM::getOptions

(PECL svm >= 0.1.0)

SVM::getOptions — Return the current training parameters

Opis

public array SVM::getOptions ( void )

Retrieve an array containing the training parameters. The parameters will be keyed on the predefined SVM constants.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array of configuration settings.

SVM::crossvalidate
SVM::setOptions
SVM


Set training parameters

SVM::getOptions
SVM::train
SVM
PHP Manual

SVM::setOptions

(PECL svm >= 0.1.0)

SVM::setOptions — Set training parameters

Opis

public bool SVM::setOptions ( array $params )

Set one or more training parameters.

Parametry

params

An array of training parameters, keyed on the SVM constants.

Zwracane wartości

Return true on success, throws SVMException on error.

SVM::getOptions
SVM::train
SVM


Create a SVMModel based on training data

SVM::setOptions
SVMModel
SVM
PHP Manual

SVM::train

(PECL svm >= 0.1.0)

SVM::train — Create a SVMModel based on training data

Opis

public SVMModel svm::train ( array $problem [, array $weights ] )

Train a support vector machine based on the supplied training data.

Parametry

problem

The problem can be provided in three different ways. An array, where the data should start with the class label (usually 1 or -1) then followed by a sparse data set of dimension => data pairs. A URL to a file containing a SVM Light formatted problem, with the each line being a new training example, the start of each line containing the class (1, -1) then a series of tab separated data values shows as key:value. A opened stream pointing to a data source formatted as in the file above.

weights

Weights are an optional set of weighting parameters for the different classes, to help account for unbalanced training sets. For example, if the classes were 1 and -1, and -1 had significantly more example than one, the weight for -1 could be 0.5. Weights should be in the range 0-1.

Zwracane wartości

Returns an SVMModel that can be used to classify previously unseen data. Throws SVMException on error

SVM::setOptions
SVMModel
SVM


The SVMModel class

(No version information available, might only be in SVN)

Wstęp

The SVMModel is the end result of the training process. It can be used to classify previously unseen data.

Krótki opis klasy

SVMModel {
/* Methods */
public bool checkProbabilityModel ( void )
public __construct ([ string $filename ] )
public array getLabels ( void )
public int getNrClass ( void )
public int getSvmType ( void )
public float getSvrProbability ( void )
public bool load ( string $filename )
public float predict_probability ( array $data )
public float predict ( array $data )
public bool save ( string $filename )
}

Spis treści

  • SVMModel::checkProbabilityModel — Returns true if the model has probability information
  • SVMModel::__construct — Construct a new SVMModel
  • SVMModel::getLabels — Get the labels the model was trained on
  • SVMModel::getNrClass — Returns the number of classes the model was trained with
  • SVMModel::getSvmType — Get the SVM type the model was trained with
  • SVMModel::getSvrProbability — Get the sigma value for regression types
  • SVMModel::load — Load a saved SVM Model
  • SVMModel::predict_probability — Return class probabilities for previous unseen data
  • SVMModel::predict — Predict a value for previously unseen data
  • SVMModel::save — Save a model to a file
SVM::train
SVMModel::checkProbabilityModel
SVM


Returns true if the model has probability information

SVMModel
SVMModel::__construct
SVMModel
PHP Manual

SVMModel::checkProbabilityModel

(PECL svm >= 0.1.5)

SVMModel::checkProbabilityModel — Returns true if the model has probability information

Opis

public bool SVMModel::checkProbabilityModel ( void )

Returns true if the model contains probability information.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return a boolean value

SVMModel
SVMModel::__construct
SVMModel


Construct a new SVMModel

SVMModel::checkProbabilityModel
SVMModel::getLabels
SVMModel
PHP Manual

SVMModel::__construct

(PECL svm >= 0.1.0)

SVMModel::__construct — Construct a new SVMModel

Opis

public SVMModel::__construct ([ string $filename ] )

Build a new SVMModel. Models will usually be created from the SVM::train function, but then saved models may be restored directly.

Parametry

filename

The filename for the saved model file this model should load.

Zwracane wartości

Throws SVMException on error

Zobacz też:

  • SVMModel::load() - Load a saved SVM Model

SVMModel::checkProbabilityModel
SVMModel::getLabels
SVMModel


Get the labels the model was trained on

SVMModel::__construct
SVMModel::getNrClass
SVMModel
PHP Manual

SVMModel::getLabels

(PECL svm >= 0.1.5)

SVMModel::getLabels — Get the labels the model was trained on

Opis

public array SVMModel::getLabels ( void )

Return an array of labels that the model was trained on. For regression and one class models an empty array is returned.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return an array of labels

Zobacz też:

  • SVMModel::getNrClass() - Returns the number of classes the model was trained with

SVMModel::__construct
SVMModel::getNrClass
SVMModel


Returns the number of classes the model was trained with

SVMModel::getLabels
SVMModel::getSvmType
SVMModel
PHP Manual

SVMModel::getNrClass

(PECL svm >= 0.1.5)

SVMModel::getNrClass — Returns the number of classes the model was trained with

Opis

public int SVMModel::getNrClass ( void )

Returns the number of classes the model was trained with, will return 2 for one class and regression models.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return an integer number of classes

SVMModel::getLabels
SVMModel::getSvmType
SVMModel


Get the SVM type the model was trained with

SVMModel::getNrClass
SVMModel::getSvrProbability
SVMModel
PHP Manual

SVMModel::getSvmType

(PECL svm >= 0.1.5)

SVMModel::getSvmType — Get the SVM type the model was trained with

Opis

public int SVMModel::getSvmType ( void )

Returns an integer value representing the type of the SVM model used, e.g SVM::C_SVC.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Return an integer SVM type

SVMModel::getNrClass
SVMModel::getSvrProbability
SVMModel


Get the sigma value for regression types

SVMModel::getSvmType
SVMModel::load
SVMModel
PHP Manual

SVMModel::getSvrProbability

(PECL svm >= 0.1.5)

SVMModel::getSvrProbability — Get the sigma value for regression types

Opis

public float SVMModel::getSvrProbability ( void )

For regression models, returns a sigma value. If there is no probability information or the model is not SVR, 0 is returned.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a sigma value

SVMModel::getSvmType
SVMModel::load
SVMModel


Load a saved SVM Model

SVMModel::getSvrProbability
SVMModel::predict_probability
SVMModel
PHP Manual

SVMModel::load

(PECL svm >= 0.1.00.1.0)

SVMModel::load — Load a saved SVM Model

Opis

public bool SVMModel::load ( string $filename )

Load a model file ready for classification or regression.

Parametry

filename

The filename of the model.

Zwracane wartości

Throws SVMException on error. Returns true on success.

Zobacz też:

  • SVMModel::save() - Save a model to a file

SVMModel::getSvrProbability
SVMModel::predict_probability
SVMModel


Return class probabilities for previous unseen data

SVMModel::load
SVMModel::predict
SVMModel
PHP Manual

SVMModel::predict_probability

(PECL svm >= 0.1.4)

SVMModel::predict_probability — Return class probabilities for previous unseen data

Opis

public float SVMModel::predict_probability ( array $data )

This function accepts an array of data and attempts to predict the class, as with the predict function. Additionally, however, this function returns an array of probabilities, one per class in the model, which represent the estimated chance of the data supplied being a member of that class. Requires that the model to be used has been trained with the probability parameter set to true.

Parametry

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

probabilities

The supplied value will be filled with the probabilities. This will be either null, in the case of a model without probability information, or an array where the index is the class name and the value the predicted probability.

Zwracane wartości

Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error

Zobacz też:

  • SVM::predict()

SVMModel::load
SVMModel::predict
SVMModel


Predict a value for previously unseen data

SVMModel::predict_probability
SVMModel::save
SVMModel
PHP Manual

SVMModel::predict

(PECL svm >= 0.1.0)

SVMModel::predict — Predict a value for previously unseen data

Opis

public float SVMModel::predict ( array $data )

This function accepts an array of data and attempts to predict the class or regression value based on the model extracted from previously trained data.

Parametry

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

Zwracane wartości

Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error

Zobacz też:

  • SVM::train() - Create a SVMModel based on training data

SVMModel::predict_probability
SVMModel::save
SVMModel


Save a model to a file

SVMModel::predict
SVN
SVMModel
PHP Manual

SVMModel::save

(PECL svm >= 0.1.0)

SVMModel::save — Save a model to a file

Opis

public bool SVMModel::save ( string $filename )

Save the model data to a file, for later use.

Parametry

filename

The file to save the model to.

Zwracane wartości

Throws SVMException on error. Returns true on success.

Zobacz też:

  • SVMModel::load() - Load a saved SVM Model

SVMModel::predict
SVN
SVMModel


Subversion

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • SVN Funkcje
    • svn_add — Schedules the addition of an item in a working directory
    • svn_auth_get_parameter — Retrieves authentication parameter
    • svn_auth_set_parameter — Sets an authentication parameter
    • svn_blame — Get the SVN blame for a file
    • svn_cat — Returns the contents of a file in a repository
    • svn_checkout — Checks out a working copy from the repository
    • svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version — Returns the version of the SVN client libraries
    • svn_commit — Sends changes from the local working copy to the repository
    • svn_delete — Delete items from a working copy or repository.
    • svn_diff — Recursively diffs two paths
    • svn_export — Export the contents of a SVN directory
    • svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise
    • svn_fs_apply_text — Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 — Create a new transaction
    • svn_fs_change_node_prop — Return true if everything is ok, false otherwise
    • svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed — Return true if content is different, false otherwise
    • svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise
    • svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise
    • svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length — Returns the length of a file from a given version of the fs
    • svn_fs_is_dir — Return true if the path points to a directory, false otherwise
    • svn_fs_is_file — Return true if the path points to a file, false otherwise
    • svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise
    • svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise
    • svn_fs_node_created_rev — Returns the revision in which path under fsroot was created
    • svn_fs_node_prop — Returns the value of a property for a node
    • svn_fs_props_changed — Return true if props are different, false otherwise
    • svn_fs_revision_prop — Fetches the value of a named property
    • svn_fs_revision_root — Get a handle on a specific version of the repository root
    • svn_fs_txn_root — Creates and returns a transaction root
    • svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem
    • svn_import — Imports an unversioned path into a repository
    • svn_log — Returns the commit log messages of a repository URL
    • svn_ls — Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir — Creates a directory in a working copy or repository
    • svn_repos_create — Create a new subversion repository at path
    • svn_repos_fs_begin_txn_for_commit — Create a new transaction
    • svn_repos_fs_commit_txn — Commits a transaction and returns the new revision
    • svn_repos_fs — Gets a handle on the filesystem for a repository
    • svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open — Open a shared lock on a repository.
    • svn_repos_recover — Run recovery procedures on the repository located at path.
    • svn_revert — Revert changes to the working copy
    • svn_status — Returns the status of working copy files and directories
    • svn_update — Update working copy
SVMModel::save
Wstęp
Inne serwisy


Wstęp

This extension implements PHP bindings for » Subversion (SVN), a version control system, allowing PHP scripts to communicate with SVN repositories and working copies without direct command line calls to the svn executable.

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.

SVN
Instalacja/Konfiguracja
SVN


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SVN


Wymagania

The Subversion binaries are not necessary to use this extension. However, when compiling the extension, libsvn (the Subversion headers) must be available.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/svn

If ./configure is having trouble finding the SVN files (for example, Subversion was installed with a different prefix directory), use ./configure --with-svn=$USR_PATH to specify the directory where the include/subversion-1/ folder is located.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Ostrzeżenie

If the extension is compiled against libsvn 1.3, functions that work with working copies will fail when used on working copies created by Subversion 1.4.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

SVN_REVISION_HEAD (integer)
Magic number (-1) specifying the HEAD revision
Constants usable with svn_auth_set_parameter()
SVN_AUTH_PARAM_DEFAULT_USERNAME (string)
Property for default username to use when performing basic authentication
SVN_AUTH_PARAM_DEFAULT_PASSWORD (string)
Property for default password to use when performing basic authentication
SVN_AUTH_PARAM_NON_INTERACTIVE (string)
SVN_AUTH_PARAM_DONT_STORE_PASSWORDS (string)
SVN_AUTH_PARAM_NO_AUTH_CACHE (string)
SVN_AUTH_PARAM_SSL_SERVER_FAILURES (string)
SVN_AUTH_PARAM_SSL_SERVER_CERT_INFO (string)
SVN_AUTH_PARAM_CONFIG (string)
SVN_AUTH_PARAM_SERVER_GROUP (string)
SVN_AUTH_PARAM_CONFIG_DIR (string)
PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS (string)
Custom property for ignoring SSL cert verification errors
Filesystem constants
SVN_FS_CONFIG_FS_TYPE (string)
Configuration key that determines filesystem type
SVN_FS_TYPE_BDB (string)
Filesystem is Berkeley-DB implementation
SVN_FS_TYPE_FSFS (string)
Filesystem is native-filesystem implementation
Reserved property constants
SVN_PROP_REVISION_DATE (string)
svn:date
SVN_PROP_REVISION_ORIG_DATE (string)
svn:original-date
SVN_PROP_REVISION_AUTHOR (string)
svn:author
SVN_PROP_REVISION_LOG (string)
svn:log
Working copy status constants
SVN_WC_STATUS_NONE (int)
Status does not exist
SVN_WC_STATUS_UNVERSIONED (int)
Item is not versioned in working copy
SVN_WC_STATUS_NORMAL (int)
Item exists, nothing else is happening
SVN_WC_STATUS_ADDED (int)
Item is scheduled for addition
SVN_WC_STATUS_MISSING (int)
Item is versioned but missing from the working copy
SVN_WC_STATUS_DELETED (int)
Item is scheduled for deletion
SVN_WC_STATUS_REPLACED (int)
Item was deleted and then re-added
SVN_WC_STATUS_MODIFIED (int)
Item (text or properties) was modified
SVN_WC_STATUS_MERGED (int)
Item's local modifications were merged with repository modifications
SVN_WC_STATUS_CONFLICTED (int)
Item's local modifications conflicted with repository modifications
SVN_WC_STATUS_IGNORED (int)
Item is unversioned but configured to be ignored
SVN_WC_STATUS_OBSTRUCTED (int)
Unversioned item is in the way of a versioned resource
SVN_WC_STATUS_EXTERNAL (int)
Unversioned path that is populated using svn:externals
SVN_WC_STATUS_INCOMPLETE (int)
Directory does not contain complete entries list
Node type constants
SVN_NODE_NONE (int)
Absent
SVN_NODE_FILE (int)
File
SVN_NODE_DIR (int)
Directory
SVN_NODE_UNKNOWN (int)
Something Subversion cannot identify
Typy zasobów
SVN Funkcje
SVN


SVN Funkcje

Spis treści

  • svn_add — Schedules the addition of an item in a working directory
  • svn_auth_get_parameter — Retrieves authentication parameter
  • svn_auth_set_parameter — Sets an authentication parameter
  • svn_blame — Get the SVN blame for a file
  • svn_cat — Returns the contents of a file in a repository
  • svn_checkout — Checks out a working copy from the repository
  • svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
  • svn_client_version — Returns the version of the SVN client libraries
  • svn_commit — Sends changes from the local working copy to the repository
  • svn_delete — Delete items from a working copy or repository.
  • svn_diff — Recursively diffs two paths
  • svn_export — Export the contents of a SVN directory
  • svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise
  • svn_fs_apply_text — Creates and returns a stream that will be used to replace
  • svn_fs_begin_txn2 — Create a new transaction
  • svn_fs_change_node_prop — Return true if everything is ok, false otherwise
  • svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot
  • svn_fs_contents_changed — Return true if content is different, false otherwise
  • svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise
  • svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise
  • svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type
  • svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs
  • svn_fs_file_length — Returns the length of a file from a given version of the fs
  • svn_fs_is_dir — Return true if the path points to a directory, false otherwise
  • svn_fs_is_file — Return true if the path points to a file, false otherwise
  • svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise
  • svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise
  • svn_fs_node_created_rev — Returns the revision in which path under fsroot was created
  • svn_fs_node_prop — Returns the value of a property for a node
  • svn_fs_props_changed — Return true if props are different, false otherwise
  • svn_fs_revision_prop — Fetches the value of a named property
  • svn_fs_revision_root — Get a handle on a specific version of the repository root
  • svn_fs_txn_root — Creates and returns a transaction root
  • svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem
  • svn_import — Imports an unversioned path into a repository
  • svn_log — Returns the commit log messages of a repository URL
  • svn_ls — Returns list of directory contents in repository URL, optionally at revision number
  • svn_mkdir — Creates a directory in a working copy or repository
  • svn_repos_create — Create a new subversion repository at path
  • svn_repos_fs_begin_txn_for_commit — Create a new transaction
  • svn_repos_fs_commit_txn — Commits a transaction and returns the new revision
  • svn_repos_fs — Gets a handle on the filesystem for a repository
  • svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath
  • svn_repos_open — Open a shared lock on a repository.
  • svn_repos_recover — Run recovery procedures on the repository located at path.
  • svn_revert — Revert changes to the working copy
  • svn_status — Returns the status of working copy files and directories
  • svn_update — Update working copy
Stałe predefiniowane
svn_add
SVN


Schedules the addition of an item in a working directory

SVN Funkcje
svn_auth_get_parameter
SVN Funkcje
PHP Manual

svn_add

(PECL svn >= 0.1.0)

svn_add — Schedules the addition of an item in a working directory

Opis

bool svn_add ( string $path [, bool $recursive = true [, bool $force = false ]] )

Adds the file, directory or symbolic link at path to the working directory. The item will be added to the repository the next time you call svn_commit() on the working copy.

Parametry

path

Path of item to add.

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

recursive

If item is directory, whether or not to recursively add all of its contents. Default is TRUE

force

If true, Subversion will recurse into already versioned directories in order to add unversioned files that may be hiding in those directories. Default is FALSE

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.

Przykłady

Przykład #1 svn_add() example

In a working directory where svn status returns:

$ svn status
?      foobar.txt

...this code:

<?php
svn_add('foobar.txt');
?>

...will schedule foobar.txt for addition into the repository.

Zobacz też:

  • » SVN documentation on svn add

SVN Funkcje
svn_auth_get_parameter
SVN Funkcje


Retrieves authentication parameter

svn_add
svn_auth_set_parameter
SVN Funkcje
PHP Manual

svn_auth_get_parameter

(PECL svn >= 0.1.0)

svn_auth_get_parameter — Retrieves authentication parameter

Opis

string svn_auth_get_parameter ( string $key )

Retrieves authentication parameter at key. For a list of valid keys and their meanings, consult the authentication constants list.

Parametry

key

String key name. Use the authentication constants defined by this extension to specify a key.

Zwracane wartości

Returns the string value of the parameter at key; returns NULL if parameter does not exist.

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ż:

  • svn_auth_set_parameter() - Sets an authentication parameter
  • Authentication constants

svn_add
svn_auth_set_parameter
SVN Funkcje


Sets an authentication parameter

svn_auth_get_parameter
svn_blame
SVN Funkcje
PHP Manual

svn_auth_set_parameter

(PECL svn >= 0.1.0)

svn_auth_set_parameter — Sets an authentication parameter

Opis

void svn_auth_set_parameter ( string $key , string $value )

Sets authentication parameter at key to value. For a list of valid keys and their meanings, consult the authentication constants list.

Parametry

key

String key name. Use the authentication constants defined by this extension to specify a key.

value

String value to set to parameter at key. Format of value varies with the parameter.

Zwracane wartości

Nie jest zwracana żadna wartość.

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.

Przykłady

Przykład #1 Default authentication example

This example configures SVN so that the default username to use is 'Bob' and the default password is 'abc123':

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123');
?>

Zobacz też:

  • svn_auth_get_parameter() - Retrieves authentication parameter
  • Authentication constants

svn_auth_get_parameter
svn_blame
SVN Funkcje


Get the SVN blame for a file

svn_auth_set_parameter
svn_cat
SVN Funkcje
PHP Manual

svn_blame

(PECL svn >= 0.3.0)

svn_blame — Get the SVN blame for a file

Opis

array svn_blame ( string $repository_url [, int $revision_no = SVN_REVISION_HEAD ] )

Get the SVN blame of a file from a repository URL.

Parametry

repository_url

The repository URL.

revision_no

The revision number.

Zwracane wartości

An array of SVN blame information separated by line which includes the revision number, line number, line of code, author, and date.

Przykłady

Przykład #1 svn_blame() example

<?php
$svnurl = 'http://svn.example.org/svnroot/foo/trunk/index.php';

print_r( svn_blame($svnurl) );

?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] = Array
          (
           [rev] = 1
           [line_no] = 1
           [line] = Hello World
           [author] = joesmith
           [date] = 2007-07-02T05:51:26.628396Z
          )
    [1] = Array
          ...

Zobacz też:

  • svn_diff() - Recursively diffs two paths
  • svn_logs()
  • svn_status() - Returns the status of working copy files and directories

svn_auth_set_parameter
svn_cat
SVN Funkcje


Returns the contents of a file in a repository

svn_blame
svn_checkout
SVN Funkcje
PHP Manual

svn_cat

(PECL svn >= 0.1.0)

svn_cat — Returns the contents of a file in a repository

Opis

string svn_cat ( string $repos_url [, int $revision_no ] )

Returns the contents of the URL repos_url to a file in the repository, optionally at revision number revision_no.

Parametry

repos_url

String URL path to item in a repository.

revision_no

Integer revision number of item to retrieve, default is the HEAD revision.

Zwracane wartości

Returns the string contents of the item from the repository on success, and FALSE on failure.

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.

Przykłady

Przykład #1 Basic example

This example retrieves the contents of a file at revision 28:

<?php
$contents = svn_cat('http://www.example.com/svnroot/calc/gui.c', 28)
?>

Zobacz też:

  • svn_list()
  • » SVN documentation on svn cat

svn_blame
svn_checkout
SVN Funkcje


Checks out a working copy from the repository

svn_cat
svn_cleanup
SVN Funkcje
PHP Manual

svn_checkout

(PECL svn >= 0.1.0)

svn_checkout — Checks out a working copy from the repository

Opis

bool svn_checkout ( string $repos , string $targetpath [, int $revision [, int $flags = 0 ]] )

Checks out a working copy from the repository at repos to targetpath at revision revision.

Parametry

repos

String URL path to directory in repository to check out.

targetpath

String local path to directory to check out in to

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

revision

Integer revision number of repository to check out. Default is HEAD, the most recent revision.

flags

Any combination of SVN_NON_RECURSIVE and SVN_IGNORE_EXTERNALS.

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.

Przykłady

Przykład #1 Basic example

This example demonstrates how to check out a directory from a repository to a directory named calc:

<?php
svn_checkout('http://www.example.com/svnroot/calc/trunk', dirname(__FILE__) . '/calc');
?>

The dirname(__FILE__) call is necessary in order to convert the calc relative path into an absolute one. If calc exists, you can also use realpath() to retrieve an absolute path.

Zobacz też:

  • svn_add() - Schedules the addition of an item in a working directory
  • svn_commit() - Sends changes from the local working copy to the repository
  • svn_status() - Returns the status of working copy files and directories
  • svn_update() - Update working copy
  • » SVN documentation on svn checkout

svn_cat
svn_cleanup
SVN Funkcje


Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

svn_checkout
svn_client_version
SVN Funkcje
PHP Manual

svn_cleanup

(PECL svn >= 0.1.0)

svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

Opis

bool svn_cleanup ( string $workingdir )

Recursively cleanup working copy directory workingdir, finishing any incomplete operations and removing working copy locks. Use when a working copy is in limbo and needs to be usable again.

Parametry

workingdir

String path to local working directory to cleanup

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

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.

Przykłady

Przykład #1 Basic example

This example demonstrates clean up of a working copy in a directory named help-me:

<?php
svn_cleanup(realpath('help-me'));
?>

The realpath() call is necessary due to SVN's quirky handling of relative paths.

Zobacz też:

  • update()
  • » SVN documentation on svn cleanup

svn_checkout
svn_client_version
SVN Funkcje


Returns the version of the SVN client libraries

svn_cleanup
svn_commit
SVN Funkcje
PHP Manual

svn_client_version

(PECL svn >= 0.1.0)

svn_client_version — Returns the version of the SVN client libraries

Opis

string svn_client_version ( void )

Returns the version of the SVN client libraries

Zwracane wartości

String version number, usually in form of x.y.z.

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.

Przykłady

Przykład #1 Basic example

<?php
echo svn_client_version();
?>

Powyższy przykład wyświetli coś podobnego do:

1.3.1

svn_cleanup
svn_commit
SVN Funkcje


Sends changes from the local working copy to the repository

svn_client_version
svn_delete
SVN Funkcje
PHP Manual

svn_commit

(PECL svn >= 0.1.0)

svn_commit — Sends changes from the local working copy to the repository

Opis

array svn_commit ( string $log , array $targets [, bool $dontrecurse = false ] )

Commits changes made in the local working copy files enumerated in the targets array to the repository, with the log message log. Directories in the targets array will be recursively committed unless dontrecurse is set to true.

Informacja: This function does not have any parameters for specifying authentication, so a username and password must be set using svn_auth_set_parameter()

Parametry

log

String log text to commit

targets

Array of local paths of files to be committed

Ostrzeżenie

This parameter must be an array, a string for a single target is not acceptable.

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

dontrecurse

Boolean flag to disable recursive committing of directories in the targets array. Default is FALSE.

Zwracane wartości

Returns array in form of:

array(
    0 => integer revision number of commit
    1 => string ISO 8601 date and time of commit
    2 => name of committer
)

Returns FALSE on failure.

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.

Przykłady

Przykład #1 Basic example

This example commits the calculator directory to a repository, using the username Bob and the password abc123 (hopefully, his password is stronger):

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123');
var_dump(svn_commit('Log message of Bob\'s commit', array(realpath('calculator'))));
?>

Powyższy przykład wyświetli:

array(
  0 => 1415,
  1 => '2007-05-26T01:44:28.453125Z',
  2 => 'Bob'
)

Zobacz też:

  • svn_auth_set_parameter() - Sets an authentication parameter
  • » SVN documentation on svn commit

svn_client_version
svn_delete
SVN Funkcje


Delete items from a working copy or repository.

svn_commit
svn_diff
SVN Funkcje
PHP Manual

svn_delete

(PECL svn >= 0.4.0)

svn_delete — Delete items from a working copy or repository.

Opis

bool svn_delete ( string $path [, bool $force = false ] )

Deletes the file, directory or symbolic link at path from the working directory. The item will be deleted from the repository the next time you call svn_commit() on the working copy.

Parametry

path

Path of item to delete.

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

force

If TRUE, the file will be deleted even if it has local modifications. Otherwise, local modifications will result in a failure. Default is FALSE

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.

Zobacz też:

  • » SVN documentation on svn delete

svn_commit
svn_diff
SVN Funkcje


Recursively diffs two paths

svn_delete
svn_export
SVN Funkcje
PHP Manual

svn_diff

(PECL svn >= 0.1.0)

svn_diff — Recursively diffs two paths

Opis

array svn_diff ( string $path1 , int $rev1 , string $path2 , int $rev2 )

Recursively diffs two paths, path1 and path2.

Informacja:

This is not a general-purpose diff utility. Only local files that are versioned may be diffed: other files will fail.

Parametry

path1

First path to diff. This can be a URL to a file/directory in an SVN repository or a local file/directory path.

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

Ostrzeżenie

If a local file path has only backslashes and no forward slashes, this extension will fail to find the path. Always replace all backslashes with forward slashes when using this function.

rev1

First path's revision number. Use SVN_REVISION_HEAD to specify the most recent revision.

path2

Second path to diff. See path1 for description.

rev2

Second path's revision number. See rev1 for description.

Zwracane wartości

Returns an array-list consisting of two streams: the first is the diff output and the second contains error stream output. The streams can be read using fread(). Returns FALSE or NULL on error.

The diff output will, by default, be in the form of Subversion's custom unified diff format, but an » external diff engine may be used depending on Subversion's configuration.

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.

Przykłady

Przykład #1 Basic example

This example demonstrates the basic usage of this function, and the retrieval of contents from the stream:

<?php
list($diff, $errors) = svn_diff(
    'http://www.example.com/svnroot/trunk/foo', SVN_REVISION_HEAD,
    'http://www.example.com/svnroot/branches/dev/foo', SVN_REVISION_HEAD
);
if (!$diff) exit;
$contents = '';
while (!feof($diff)) {
  $contents .= fread($diff, 8192);
}
fclose($diff);
fclose($errors);
var_dump($contents);
?>

Powyższy przykład wyświetli:

Index: http://www.example.com/svnroot/trunk/foo
===================================================================
--- http://www.example.com/svnroot/trunk/foo        (.../foo) (revision 23)
+++ http://www.example.com/svnroot/branches/dev/foo (.../foo) (revision 27)
 // further diff output

Przykład #2 Diffing two revisions of a repository path

This example implements a wrapper function that allows a user to easily diff two revisions of the same item using an external repository path (the default syntax is somewhat verbose):

<?php
function svn_diff_same_item($path, $rev1, $rev2) {
    return svn_diff($path, $rev1, $path, $rev2);
}
?>

Przykład #3 Portably diffing two local files

This example implements a wrapper function that portably diffs two local files, compensating for the realpath() fix and the backslashes bug:

<?php
function svn_diff_local($path1, $rev1, $path2, $rev2) {
    $path1 = str_replace('\\', '/', realpath($path1));
    $path2 = str_replace('\\', '/', realpath($path2));
    return svn_diff($path1, $rev1, $path2, $rev2);
}
?>

Zobacz też:

  • » SVN documentation on svn diff

svn_delete
svn_export
SVN Funkcje


Export the contents of a SVN directory

svn_diff
svn_fs_abort_txn
SVN Funkcje
PHP Manual

svn_export

(PECL svn >= 0.3.0)

svn_export — Export the contents of a SVN directory

Opis

bool svn_export ( string $frompath , string $topath [, bool $working_copy = true [, int $revision_no = -1 ]] )

Export the contents of either a working copy or repository into a 'clean' directory.

Parametry

frompath

The path to the current repository.

topath

The path to the new repository.

working_copy

If TRUE, it will export uncommitted files from the working copy.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 svn_export() example

<?php
$working_dir     = '../';
$new_working_dir = '/home/user/devel/foo/trunk';

svn_export($working_dir, $new_working_dir);
?>

Zobacz też:

  • svn_import() - Imports an unversioned path into a repository

svn_diff
svn_fs_abort_txn
SVN Funkcje


Abort a transaction, returns true if everything is okay, false otherwise

svn_export
svn_fs_apply_text
SVN Funkcje
PHP Manual

svn_fs_abort_txn

(PECL svn >= 0.2.0)

svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise

Opis

bool svn_fs_abort_txn ( resource $txn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Abort a transaction, returns true if everything is okay, false otherwise

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.

svn_export
svn_fs_apply_text
SVN Funkcje


Creates and returns a stream that will be used to replace

svn_fs_abort_txn
svn_fs_begin_txn2
SVN Funkcje
PHP Manual

svn_fs_apply_text

(PECL svn >= 0.2.0)

svn_fs_apply_text — Creates and returns a stream that will be used to replace

Opis

resource svn_fs_apply_text ( resource $root , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Creates and returns a stream that will be used to replace

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.

svn_fs_abort_txn
svn_fs_begin_txn2
SVN Funkcje


Create a new transaction

svn_fs_apply_text
svn_fs_change_node_prop
SVN Funkcje
PHP Manual

svn_fs_begin_txn2

(PECL svn >= 0.2.0)

svn_fs_begin_txn2 — Create a new transaction

Opis

resource svn_fs_begin_txn2 ( resource $repos , int $rev )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Create a new transaction

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.

svn_fs_apply_text
svn_fs_change_node_prop
SVN Funkcje


Return true if everything is ok, false otherwise

svn_fs_begin_txn2
svn_fs_check_path
SVN Funkcje
PHP Manual

svn_fs_change_node_prop

(PECL svn >= 0.2.0)

svn_fs_change_node_prop — Return true if everything is ok, false otherwise

Opis

bool svn_fs_change_node_prop ( resource $root , string $path , string $name , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Return true if everything is ok, false otherwise

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.

svn_fs_begin_txn2
svn_fs_check_path
SVN Funkcje


Determines what kind of item lives at path in a given repository fsroot

svn_fs_change_node_prop
svn_fs_contents_changed
SVN Funkcje
PHP Manual

svn_fs_check_path

(PECL svn >= 0.1.0)

svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot

Opis

int svn_fs_check_path ( resource $fsroot , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Determines what kind of item lives at path in a given repository fsroot

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.

svn_fs_change_node_prop
svn_fs_contents_changed
SVN Funkcje


Return true if content is different, false otherwise

svn_fs_check_path
svn_fs_copy
SVN Funkcje
PHP Manual

svn_fs_contents_changed

(PECL svn >= 0.2.0)

svn_fs_contents_changed — Return true if content is different, false otherwise

Opis

bool svn_fs_contents_changed ( resource $root1 , string $path1 , resource $root2 , string $path2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Return true if content is different, false otherwise

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.

svn_fs_check_path
svn_fs_copy
SVN Funkcje


Copies a file or a directory, returns true if all is ok, false otherwise

svn_fs_contents_changed
svn_fs_delete
SVN Funkcje
PHP Manual

svn_fs_copy

(PECL svn >= 0.2.0)

svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise

Opis

bool svn_fs_copy ( resource $from_root , string $from_path , resource $to_root , string $to_path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Copies a file or a directory, returns true if all is ok, false otherwise

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.

svn_fs_contents_changed
svn_fs_delete
SVN Funkcje


Deletes a file or a directory, return true if all is ok, false otherwise

svn_fs_copy
svn_fs_dir_entries
SVN Funkcje
PHP Manual

svn_fs_delete

(PECL svn >= 0.2.0)

svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise

Opis

bool svn_fs_delete ( resource $root , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Deletes a file or a directory, return true if all is ok, false otherwise

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.

svn_fs_copy
svn_fs_dir_entries
SVN Funkcje


Enumerates the directory entries under path; returns a hash of dir names to file type

svn_fs_delete
svn_fs_file_contents
SVN Funkcje
PHP Manual

svn_fs_dir_entries

(PECL svn >= 0.1.0)

svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type

Opis

array svn_fs_dir_entries ( resource $fsroot , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Enumerates the directory entries under path; returns a hash of dir names to file type

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.

svn_fs_delete
svn_fs_file_contents
SVN Funkcje


Returns a stream to access the contents of a file from a given version of the fs

svn_fs_dir_entries
svn_fs_file_length
SVN Funkcje
PHP Manual

svn_fs_file_contents

(PECL svn >= 0.1.0)

svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs

Opis

resource svn_fs_file_contents ( resource $fsroot , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns a stream to access the contents of a file from a given version of the fs

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.

svn_fs_dir_entries
svn_fs_file_length
SVN Funkcje


Returns the length of a file from a given version of the fs

svn_fs_file_contents
svn_fs_is_dir
SVN Funkcje
PHP Manual

svn_fs_file_length

(PECL svn >= 0.1.0)

svn_fs_file_length — Returns the length of a file from a given version of the fs

Opis

int svn_fs_file_length ( resource $fsroot , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the length of a file from a given version of the fs

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.

svn_fs_file_contents
svn_fs_is_dir
SVN Funkcje


Return true if the path points to a directory, false otherwise

svn_fs_file_length
svn_fs_is_file
SVN Funkcje
PHP Manual

svn_fs_is_dir

(PECL svn >= 0.2.0)

svn_fs_is_dir — Return true if the path points to a directory, false otherwise

Opis

bool svn_fs_is_dir ( resource $root , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Return true if the path points to a directory, false otherwise

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.

svn_fs_file_length
svn_fs_is_file
SVN Funkcje


Return true if the path points to a file, false otherwise

svn_fs_is_dir
svn_fs_make_dir
SVN Funkcje
PHP Manual

svn_fs_is_file

(PECL svn >= 0.2.0)

svn_fs_is_file — Return true if the path points to a file, false otherwise

Opis

bool svn_fs_is_file ( resource $root , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Return true if the path points to a file, false otherwise

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.

svn_fs_is_dir
svn_fs_make_dir
SVN Funkcje


Creates a new empty directory, returns true if all is ok, false otherwise

svn_fs_is_file
svn_fs_make_file
SVN Funkcje
PHP Manual

svn_fs_make_dir

(PECL svn >= 0.2.0)

svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise

Opis

bool svn_fs_make_dir ( resource $root , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Creates a new empty directory, returns true if all is ok, false otherwise

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.

svn_fs_is_file
svn_fs_make_file
SVN Funkcje


Creates a new empty file, returns true if all is ok, false otherwise

svn_fs_make_dir
svn_fs_node_created_rev
SVN Funkcje
PHP Manual

svn_fs_make_file

(PECL svn >= 0.2.0)

svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise

Opis

bool svn_fs_make_file ( resource $root , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Creates a new empty file, returns true if all is ok, false otherwise

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.

svn_fs_make_dir
svn_fs_node_created_rev
SVN Funkcje


Returns the revision in which path under fsroot was created

svn_fs_make_file
svn_fs_node_prop
SVN Funkcje
PHP Manual

svn_fs_node_created_rev

(PECL svn >= 0.1.0)

svn_fs_node_created_rev — Returns the revision in which path under fsroot was created

Opis

int svn_fs_node_created_rev ( resource $fsroot , string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the revision in which path under fsroot was created

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.

svn_fs_make_file
svn_fs_node_prop
SVN Funkcje


Returns the value of a property for a node

svn_fs_node_created_rev
svn_fs_props_changed
SVN Funkcje
PHP Manual

svn_fs_node_prop

(PECL svn >= 0.1.0)

svn_fs_node_prop — Returns the value of a property for a node

Opis

string svn_fs_node_prop ( resource $fsroot , string $path , string $propname )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the value of a property for a node

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.

svn_fs_node_created_rev
svn_fs_props_changed
SVN Funkcje


Return true if props are different, false otherwise

svn_fs_node_prop
svn_fs_revision_prop
SVN Funkcje
PHP Manual

svn_fs_props_changed

(PECL svn >= 0.2.0)

svn_fs_props_changed — Return true if props are different, false otherwise

Opis

bool svn_fs_props_changed ( resource $root1 , string $path1 , resource $root2 , string $path2 )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Return true if props are different, false otherwise

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.

svn_fs_node_prop
svn_fs_revision_prop
SVN Funkcje


Fetches the value of a named property

svn_fs_props_changed
svn_fs_revision_root
SVN Funkcje
PHP Manual

svn_fs_revision_prop

(PECL svn >= 0.1.0)

svn_fs_revision_prop — Fetches the value of a named property

Opis

string svn_fs_revision_prop ( resource $fs , int $revnum , string $propname )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Fetches the value of a named property

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.

svn_fs_props_changed
svn_fs_revision_root
SVN Funkcje


Get a handle on a specific version of the repository root

svn_fs_revision_prop
svn_fs_txn_root
SVN Funkcje
PHP Manual

svn_fs_revision_root

(PECL svn >= 0.1.0)

svn_fs_revision_root — Get a handle on a specific version of the repository root

Opis

resource svn_fs_revision_root ( resource $fs , int $revnum )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Get a handle on a specific version of the repository root

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.

svn_fs_revision_prop
svn_fs_txn_root
SVN Funkcje


Creates and returns a transaction root

svn_fs_revision_root
svn_fs_youngest_rev
SVN Funkcje
PHP Manual

svn_fs_txn_root

(PECL svn >= 0.2.0)

svn_fs_txn_root — Creates and returns a transaction root

Opis

resource svn_fs_txn_root ( resource $txn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Creates and returns a transaction root

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.

svn_fs_revision_root
svn_fs_youngest_rev
SVN Funkcje


Returns the number of the youngest revision in the filesystem

svn_fs_txn_root
svn_import
SVN Funkcje
PHP Manual

svn_fs_youngest_rev

(PECL svn >= 0.1.0)

svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem

Opis

int svn_fs_youngest_rev ( resource $fs )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Returns the number of the youngest revision in the filesystem

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.

svn_fs_txn_root
svn_import
SVN Funkcje


Imports an unversioned path into a repository

svn_fs_youngest_rev
svn_log
SVN Funkcje
PHP Manual

svn_import

(PECL svn >= 0.2.0)

svn_import — Imports an unversioned path into a repository

Opis

bool svn_import ( string $path , string $url , bool $nonrecursive )

Commits unversioned path into repository at url. If path is a directory and nonrecursive is FALSE, the directory will be imported recursively.

Parametry

path

Path of file or directory to import.

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

url

Repository URL to import into.

nonrecursive

Whether or not to refrain from recursively processing directories.

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.

Przykłady

Przykład #1 Basic example

This example demonstrates a basic use-case of this function. To import a directory named new-files into the repository at http://www.example.com/svnroot/incoming/abc, use:

<?php
svn_import(realpath('new-files'), 'http://www.example.com/svnroot/incoming/abc', false);
?>

Zobacz też:

  • svn_add() - Schedules the addition of an item in a working directory
  • » SVN documentation for svn import

svn_fs_youngest_rev
svn_log
SVN Funkcje


Returns the commit log messages of a repository URL

svn_import
svn_ls
SVN Funkcje
PHP Manual

svn_log

(PECL svn >= 0.1.0)

svn_log — Returns the commit log messages of a repository URL

Opis

array svn_log ( string $repos_url [, int $start_revision [, int $end_revision [, int $limit = 0 [, int $flags = SVN_DISCOVER_CHANGED_PATHS | SVN_STOP_ON_COPY ]]]] )

svn_log() returns the complete history of the item at the repository URL repos_url, or the history of a specific revision if start_revision is set. This function is equivalent to svn log --verbose -r $start_revision $repos_url.

Parametry

repos_url

Repository URL of the item to retrieve log history from.

start_revision

Revision number of the first log to retrieve. Use SVN_REVISION_HEAD to retrieve the log from the most recent revision.

end_revision

Revision number of the last log to retrieve. Defaults to start_revision if specified or to SVN_REVISION_INITIAL otherwise.

limit

Number of logs to retrieve.

flags

Any combination of SVN_OMIT_MESSAGES, SVN_DISCOVER_CHANGED_PATHS and SVN_STOP_ON_COPY.

Zwracane wartości

On success, this function returns an array file listing in the format of:

[0] => Array, ordered most recent (highest) revision first
(
    [rev] => integer revision number
    [author] => string author name
    [msg] => string log message
    [date] => string date formatted per ISO 8601, i.e. date('c')
    [paths] => Array, describing changed files
        (
            [0] => Array
                (
                    [action] => string letter signifying change
                    [path] =>  absolute repository path of changed file
                )
            [1] => ...
        )
)
[1] => ...

Informacja:

The output will always be a numerically indexed array of arrays, even when there are none or only one log message(s).

The value of action is a subset of the » status output in the first column, where possible values are:

Actions
Letter | Description
M | Item/props was modified
A | Item was added
D | Item was deleted
R | Item was replaced

If no changes were made to the item, an empty array is returned.

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.

Przykłady

Przykład #1 svn_log() example

<?php
print_r( svn_log('http://www.example.com/', 23) );
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => Array
    (
        [rev] => 23
        [author] => 'joe'
        [msg] => 'Add cheese and salami to our sandwich.'
        [date] => '2007-04-06T16:00:27-04:00'
        [paths] => Array
            (
                [0] => Array
                    (
                        [action] => 'M'
                        [path] =>  '/sandwich.txt'
                    )
            )
    )
)

Zobacz też:

  • » SVN documentation on svn log

svn_import
svn_ls
SVN Funkcje


Returns list of directory contents in repository URL, optionally at revision number

svn_log
svn_mkdir
SVN Funkcje
PHP Manual

svn_ls

(PECL svn >= 0.1.0)

svn_ls — Returns list of directory contents in repository URL, optionally at revision number

Opis

array svn_ls ( string $repos_url [, int $revision_no = SVN_REVISION_HEAD [, bool $recurse = false [, bool $peg = false ]]] )

This function queries the repository URL and returns a list of files and directories, optionally from a specific revision. This is equivalent to svn list $repos_url[@$revision_no]

Informacja:

This function does not work with working copies. repos_url must be a repository URL.

Parametry

url

URL of the repository, eg. http://www.example.com/svnroot. To access a local Subversion repository via filesystem, use the file URI scheme, eg. file:///home/user/svn-repos

revision

Integer revision number to retrieve listing of. When omitted, the HEAD revision is used.

recurse

Enables recursion.

Zwracane wartości

On success, this function returns an array file listing in the format of:

[0] => Array
    (
        [created_rev] => integer revision number of last edit
        [last_author] => string author name of last edit
        [size] => integer byte file size of file
        [time] => string date of last edit in form 'M d H:i'
                  or 'M d Y', depending on how old the file is
        [time_t] => integer unix timestamp of last edit
        [name] => name of file/directory
        [type] => type, can be 'file' or 'dir'
    )
[1] => ...

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.

Przykłady

Przykład #1 svn_ls() example

<?php
print_r( svn_ls('http://www.example.com/svnroot/') );
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => Array
        (
            [created_rev] => 20
            [last_author] => Joe
            [size] => 0
            [time] => Apr 02 09:28
            [time_t] => 1175520529
            [name] => tags
            [type] => dir
        )
    [1] => Array
        (
            [created_rev] => 23
            [last_author] => Bob
            [size] => 0
            [time] => Apr 02 15:15
            [time_t] => 1175541322
            [name] => trunk
            [type] => dir
        )
)

Zobacz też:

  • » SVN documentation on svn list

svn_log
svn_mkdir
SVN Funkcje


Creates a directory in a working copy or repository

svn_ls
svn_repos_create
SVN Funkcje
PHP Manual

svn_mkdir

(PECL svn >= 0.4.0)

svn_mkdir — Creates a directory in a working copy or repository

Opis

bool svn_mkdir ( string $path [, string $log_message ] )

Creates a directory in a working copy or repository.

Parametry

path

The path to the working copy or repository.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • svn_add() - Schedules the addition of an item in a working directory
  • svn_copy()

svn_ls
svn_repos_create
SVN Funkcje


Create a new subversion repository at path

svn_mkdir
svn_repos_fs_begin_txn_for_commit
SVN Funkcje
PHP Manual

svn_repos_create

(PECL svn >= 0.1.0)

svn_repos_create — Create a new subversion repository at path

Opis

resource svn_repos_create ( string $path [, array $config [, array $fsconfig ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Create a new subversion repository at path

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.

svn_mkdir
svn_repos_fs_begin_txn_for_commit
SVN Funkcje


Create a new transaction

svn_repos_create
svn_repos_fs_commit_txn
SVN Funkcje
PHP Manual

svn_repos_fs_begin_txn_for_commit

(PECL svn >= 0.2.0)

svn_repos_fs_begin_txn_for_commit — Create a new transaction

Opis

resource svn_repos_fs_begin_txn_for_commit ( resource $repos , int $rev , string $author , string $log_msg )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Create a new transaction

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.

svn_repos_create
svn_repos_fs_commit_txn
SVN Funkcje


Commits a transaction and returns the new revision

svn_repos_fs_begin_txn_for_commit
svn_repos_fs
SVN Funkcje
PHP Manual

svn_repos_fs_commit_txn

(PECL svn >= 0.2.0)

svn_repos_fs_commit_txn — Commits a transaction and returns the new revision

Opis

int svn_repos_fs_commit_txn ( resource $txn )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Commits a transaction and returns the new revision

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.

svn_repos_fs_begin_txn_for_commit
svn_repos_fs
SVN Funkcje


Gets a handle on the filesystem for a repository

svn_repos_fs_commit_txn
svn_repos_hotcopy
SVN Funkcje
PHP Manual

svn_repos_fs

(PECL svn >= 0.1.0)

svn_repos_fs — Gets a handle on the filesystem for a repository

Opis

resource svn_repos_fs ( resource $repos )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Gets a handle on the filesystem for a repository

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.

svn_repos_fs_commit_txn
svn_repos_hotcopy
SVN Funkcje


Make a hot-copy of the repos at repospath; copy it to destpath

svn_repos_fs
svn_repos_open
SVN Funkcje
PHP Manual

svn_repos_hotcopy

(PECL svn >= 0.1.0)

svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath

Opis

bool svn_repos_hotcopy ( string $repospath , string $destpath , bool $cleanlogs )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Make a hot-copy of the repos at repospath; copy it to destpath

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.

svn_repos_fs
svn_repos_open
SVN Funkcje


Open a shared lock on a repository.

svn_repos_hotcopy
svn_repos_recover
SVN Funkcje
PHP Manual

svn_repos_open

(PECL svn >= 0.1.0)

svn_repos_open — Open a shared lock on a repository.

Opis

resource svn_repos_open ( string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Open a shared lock on a repository.

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.

svn_repos_hotcopy
svn_repos_recover
SVN Funkcje


Run recovery procedures on the repository located at path.

svn_repos_open
svn_revert
SVN Funkcje
PHP Manual

svn_repos_recover

(PECL svn >= 0.1.0)

svn_repos_recover — Run recovery procedures on the repository located at path.

Opis

bool svn_repos_recover ( string $path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Run recovery procedures on the repository located at path.

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.

svn_repos_open
svn_revert
SVN Funkcje


Revert changes to the working copy

svn_repos_recover
svn_status
SVN Funkcje
PHP Manual

svn_revert

(PECL svn >= 0.3.0)

svn_revert — Revert changes to the working copy

Opis

bool svn_revert ( string $path [, bool $recursive = false ] )

Revert any local changes to the path in a working copy.

Parametry

path

The path to the working repository.

recursive

Optionally make recursive changes.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • svn_delete() - Delete items from a working copy or repository.
  • svn_export() - Export the contents of a SVN directory

svn_repos_recover
svn_status
SVN Funkcje


Returns the status of working copy files and directories

svn_revert
svn_update
SVN Funkcje
PHP Manual

svn_status

(PECL svn >= 0.1.0)

svn_status — Returns the status of working copy files and directories

Opis

array svn_status ( string $path [, int $flags = 0 ] )

Returns the status of working copy files and directories, giving modifications, additions, deletions and other changes to items in the working copy.

Parametry

path

Local path to file or directory to retrieve status of.

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

flags

Any combination of SVN_NON_RECURSIVE, SVN_ALL (regardless of modification status), SVN_SHOW_UPDATES (entries will be added for items that are out-of-date), SVN_NO_IGNORE (disregard svn:ignore properties when scanning for new files) and SVN_IGNORE_EXTERNALS.

Zwracane wartości

Returns a numerically indexed array of associative arrays detailing the status of items in the repository:

Array (
    [0] => Array (
        // information on item
    )
    [1] => ...
)

The information on the item is an associative array that can contain the following keys:

path
String path to file/directory of this entry on local filesystem.
text_status
Status of item's text. Odwołaj się do stałych statusu po możliwe wartości.
repos_text_status
Status of item's text in repository. Only accurate if update was set to TRUE. Odwołaj się do stałych statusu po możliwe wartości.
prop_status
Status of item's properties. Odwołaj się do stałych statusu po możliwe wartości.
repos_prop_status
Status of item's property in repository. Only accurate if update was set to TRUE. Odwołaj się do stałych statusu po możliwe wartości.
locked
Whether or not the item is locked. (Only set if TRUE.)
copied
Whether or not the item was copied (scheduled for addition with history). (Only set if TRUE.)
switched
Whether or not the item was switched using the switch command. (Only set if TRUE)

These keys are only set if the item is versioned:

name
Base name of item in repository.
url
URL of item in repository.
repos
Base URL of repository.
revision
Integer revision of item in working copy.
kind
Type of item, i.e. file or directory. Odwołaj się do stałych typów po możliwe wartości.
schedule
Scheduled action for item, i.e. addition or deletion. Constants for these magic numbers are not available, they can be emulated by using:
<?php
if (!defined('svn_wc_schedule_normal')) {
    define('svn_wc_schedule_normal',  0); // nothing special
    define('svn_wc_schedule_add',     1); // item will be added
    define('svn_wc_schedule_delete',  2); // item will be deleted
    define('svn_wc_schedule_replace', 3); // item will be added and deleted
}
?>
deleted
Whether or not the item was deleted, but parent revision lags behind. (Only set if TRUE.)
absent
Whether or not the item is absent, that is, Subversion knows that there should be something there but there isn't. (Only set if TRUE.)
incomplete
Whether or not the entries file for a directory is incomplete. (Only set if TRUE.)
cmt_date
Integer Unix timestamp of last commit date. (Unaffected by update.)
cmt_rev
Integer revision of last commit. (Unaffected by update.)
cmt_author
String author of last commit. (Unaffected by update.)
prop_time
Integer Unix timestamp of last up-to-date time for properties
text_time
Integer Unix timestamp of last up-to-date time for text

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.

Przykłady

Przykład #1 Basic example

This example demonstrates a basic, theoretical usage of this function.

<?php
print_r(svn_status(realpath('wc')));
?>

Powyższy przykład wyświetli coś podobnego do:

Array (
    [0] => Array (
        [path] => /home/bob/wc/sandwich.txt
        [text_status] => 8 // item was modified
        [repos_text_status] => 1 // no information available, use update
        [prop_status] => 3 // no changes
        [repos_prop_status] => 1 // no information available, use update
        [name] => sandwich.txt
        [url] => http://www.example.com/svnroot/deli/trunk/sandwich.txt
        [repos] => http://www.example.com/svnroot/
        [revision] => 123
        [kind] => 1 // file
        [schedule] => 0 // no special actions scheduled
        [cmt_date] => 1165543135
        [cmt_rev] => 120
        [cmt_author] => Alice
        [prop_time] => 1180201728
        [text_time] => 1180201729
    )
)

Zobacz też:

  • svn_update() - Update working copy
  • svn_log() - Returns the commit log messages of a repository URL
  • » SVN documentation for svn status

svn_revert
svn_update
SVN Funkcje


Update working copy

svn_status
TCP
SVN Funkcje
PHP Manual

svn_update

(PECL svn >= 0.1.0)

svn_update — Update working copy

Opis

int svn_update ( string $path [, int $revno = SVN_REVISION_HEAD [, bool $recurse = true ]] )

Update working copy at path to revision revno. If recurse is true, directories will be recursively updated.

Parametry

path

Path to local working copy.

Informacja: Względne ścieżki zostaną rozwiązane, jeśli bieżący katalog roboczy jest jednym z zawierających binaria PHP. Aby odwołać się do skryptu roboczego katalogu, użyj realpath() lub dirname(__FILE__).

revno

Revision number to update to, default is SVN_REVISION_HEAD.

recurse

Whether or not to recursively update directories.

Zwracane wartości

Returns new revision number on success, returns FALSE on failure.

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.

Przykłady

Przykład #1 Basic example

This example demonstrates basic usage of this function:

<?php
echo svn_update(realpath('working-copy'));
?>

Powyższy przykład wyświetli coś podobnego do:

234

Zobacz też:

  • svn_checkout() - Checks out a working copy from the repository
  • svn_commit() - Sends changes from the local working copy to the repository
  • » SVN documentation for svn update

svn_status
TCP
SVN Funkcje


TCP Wrappers

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • TCP Funkcje
    • tcpwrap_check — Performs a tcpwrap check
svn_update
Wstęp
Inne serwisy


Wstęp

The TCP wrappers provides a classical Unix mechanism which has been designed to check if the remote client is able to connect from the given IP address.

TCP
Instalacja/Konfiguracja
TCP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
TCP


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/tcpwrap.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
TCP Funkcje
TCP


TCP Funkcje

Spis treści

  • tcpwrap_check — Performs a tcpwrap check
Stałe predefiniowane
tcpwrap_check
TCP


Performs a tcpwrap check

TCP Funkcje
Varnish
TCP Funkcje
PHP Manual

tcpwrap_check

(PECL tcpwrap >= 0.1.0)

tcpwrap_check — Performs a tcpwrap check

Opis

bool tcpwrap_check ( string $daemon , string $address [, string $user [, bool $nodns = false ]] )

This function consults the /etc/hosts.allow and /etc/hosts.deny files to check if access to service daemon should be granted or denied for a client.

Parametry

daemon

The service name.

address

The client remote address. Can be either an IP address or a domain name.

user

An optional user name.

nodns

If address looks like domain name then DNS is used to resolve it to IP address; set nodns to TRUE to avoid this.

Zwracane wartości

This function returns TRUE if access should be granted, FALSE otherwise.

Przykłady

Przykład #1 Deny all connections from localhost

If your /etc/hosts.deny file contains:

php: 127.0.0.1

And your code looks like:

<?php
if (!tcpwrap_check('php', $_SERVER['REMOTE_ADDR'])) {
  die('You are not welcome here');
}
?>

Zobacz też:

For more details please consult hosts_access(3) man page.

TCP Funkcje
Varnish
TCP Funkcje


Varnish

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic VarnishAdmin usage
    • Basic VarnishStat usage
    • Basic VarnishLog usage
  • VarnishAdmin — The VarnishAdmin class
    • VarnishAdmin::auth — Authenticate on a varnish instance
    • VarnishAdmin::ban — Ban URLs using a VCL expression
    • VarnishAdmin::banUrl — Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic — Clear varnish instance panic messages
    • VarnishAdmin::connect — Connect to a varnish instance administration interface
    • VarnishAdmin::__construct — VarnishAdmin constructor
    • VarnishAdmin::getPanic — Get the last panic message on a varnish instance
    • VarnishAdmin::getParams — Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning — Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat — Set the class compat configuration param
    • VarnishAdmin::setHost — Set the class host configuration param
    • VarnishAdmin::setIdent — Set the class ident configuration param
    • VarnishAdmin::setParam — Set configuration param on the current varnish instance
    • VarnishAdmin::setPort — Set the class port configuration param
    • VarnishAdmin::setSecret — Set the class secret configuration param
    • VarnishAdmin::setTimeout — Set the class timeout configuration param
    • VarnishAdmin::start — Start varnish worker process
    • VarnishAdmin::stop — Stop varnish worker process
  • VarnishStat — The VarnishStat class
    • VarnishStat::__construct — VarnishStat constructor
    • VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot
  • VarnishLog — The VarnishLog class
    • VarnishLog::__construct — Varnishlog constructor
    • VarnishLog::getLine — Get next log line
    • VarnishLog::getTagName — Get the log tag string representation by its index
tcpwrap_check
Wstęp
Inne serwisy


Wstęp

Varnish Cache is an open source, state of the art web application accelerator. The extension makes it possible to interact with a running varnish instance through TCP socket or shared memory.

Varnish
Instalacja/Konfiguracja
Varnish


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Varnish


Wymagania

To use this extension, you will need Varnish Cache of the version >=3.0 installed, available on the » Varnish Cache homepage

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/varnish.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

VARNISH_STATUS_SYNTAX (integer)
VARNISH_STATUS_UNKNOWN (integer)
VARNISH_STATUS_UNIMPL (integer)
VARNISH_STATUS_TOOFEW (integer)
VARNISH_STATUS_TOOMANY (integer)
VARNISH_STATUS_PARAM (integer)
VARNISH_STATUS_AUTH (integer)
VARNISH_STATUS_OK (integer)
VARNISH_STATUS_CANT (integer)
VARNISH_STATUS_COMMS (integer)
VARNISH_STATUS_CLOSE (integer)
VARNISH_CONFIG_IDENT (string)
VARNISH_CONFIG_HOST (string)
VARNISH_CONFIG_PORT (string)
VARNISH_CONFIG_TIMEOUT (string)
VARNISH_CONFIG_SECRET (string)
VARNISH_CONFIG_COMPAT (string)
VARNISH_COMPAT_2 (integer)
VARNISH_COMPAT_3 (integer)

Typy zasobów
Przykłady
Varnish


Przykłady

Spis treści

  • Basic VarnishAdmin usage
  • Basic VarnishStat usage
  • Basic VarnishLog usage
Stałe predefiniowane
Basic VarnishAdmin usage
Varnish


Basic VarnishAdmin usage

The example illustrates a simple usage of the ban functionality

Przykład #1 Ban an URL

<?php

$args = array(
    VARNISH_CONFIG_HOST    => "::1",
    VARNISH_CONFIG_PORT    => 6082,
    VARNISH_CONFIG_SECRET  => "5174826b-8595-4958-aa7a-0609632ad7ca",
    VARNISH_CONFIG_TIMEOUT => 300,
);

$va = new VarnishAdmin($args);

try {
    if(!$va->connect()) {
        throw new VarnishException("Connection failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    if(!$va->auth()) {
        throw new VarnishException("Auth failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    $status = $va->ban('req.url ~ "^/$"');
    if (VARNISH_STATUS_OK != $status) {
        throw new VarnishException("Ban method returned $status status\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

exit(0);

?>
Przykłady
Basic VarnishStat usage
Przykłady


Basic VarnishStat usage

The example illustrates getting varnish statistic snapshot from shared memory

Przykład #1 Get statistic snapshot

<?php

$vs = new VarnishStat;

try {
    $data = $vs->getSnapshot();
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

exit(0);
?>
Basic VarnishAdmin usage
Basic VarnishLog usage
Przykłady


Basic VarnishLog usage

The example illustrates reading varnish log lines from shared memory

Przykład #1 Read varnish shared memory log

<?php

$vl = new VarnishLog;
while(1) {
    $line = $vl->getLine();
    printf("%s %d %s", VarnishLog::getTagName($line['tag'], $line['id'],
    $line['data']);
}

exit(0);
?>
Basic VarnishStat usage
VarnishAdmin
Przykłady


The VarnishAdmin class

(PECL varnish >= 0.3)

Wstęp

Krótki opis klasy

VarnishAdmin {
/* Metody */
public bool auth ( void )
public int ban ( string $vcl_regex )
public int banUrl ( string $vcl_regex )
public int clearPanic ( void )
public bool connect ( void )
public __construct ([ array $args ] )
public string getPanic ( void )
public array getParams ( void )
public bool isRunning ( void )
public void setCompat ( int $compat )
public void setHost ( string $host )
public void setIdent ( string $ident )
public int setParam ( string $name , string|integer $value )
public void setPort ( int $port )
public void setSecret ( string $secret )
public void setTimeout ( int $timeout )
public int start ( void )
public int stop ( void )
}

Spis treści

  • VarnishAdmin::auth — Authenticate on a varnish instance
  • VarnishAdmin::ban — Ban URLs using a VCL expression
  • VarnishAdmin::banUrl — Ban an URL using a VCL expression
  • VarnishAdmin::clearPanic — Clear varnish instance panic messages
  • VarnishAdmin::connect — Connect to a varnish instance administration interface
  • VarnishAdmin::__construct — VarnishAdmin constructor
  • VarnishAdmin::getPanic — Get the last panic message on a varnish instance
  • VarnishAdmin::getParams — Fetch current varnish instance configuration parameters
  • VarnishAdmin::isRunning — Check if the varnish slave process is currently running
  • VarnishAdmin::setCompat — Set the class compat configuration param
  • VarnishAdmin::setHost — Set the class host configuration param
  • VarnishAdmin::setIdent — Set the class ident configuration param
  • VarnishAdmin::setParam — Set configuration param on the current varnish instance
  • VarnishAdmin::setPort — Set the class port configuration param
  • VarnishAdmin::setSecret — Set the class secret configuration param
  • VarnishAdmin::setTimeout — Set the class timeout configuration param
  • VarnishAdmin::start — Start varnish worker process
  • VarnishAdmin::stop — Stop varnish worker process
Basic VarnishLog usage
VarnishAdmin::auth
Varnish


Authenticate on a varnish instance

VarnishAdmin
VarnishAdmin::ban
VarnishAdmin
PHP Manual

VarnishAdmin::auth

(PECL varnish >= 0.3)

VarnishAdmin::auth — Authenticate on a varnish instance

Opis

public bool VarnishAdmin::auth ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

VarnishAdmin
VarnishAdmin::ban
VarnishAdmin


Ban URLs using a VCL expression

VarnishAdmin::auth
VarnishAdmin::banUrl
VarnishAdmin
PHP Manual

VarnishAdmin::ban

(PECL varnish >= 0.3)

VarnishAdmin::ban — Ban URLs using a VCL expression

Opis

public int VarnishAdmin::ban ( string $vcl_regex )

Parametry

vcl_regex

Varnish VCL expression. It's based on the varnish ban command.

Zwracane wartości

Returns the varnish command status.

VarnishAdmin::auth
VarnishAdmin::banUrl
VarnishAdmin


Ban an URL using a VCL expression

VarnishAdmin::ban
VarnishAdmin::clearPanic
VarnishAdmin
PHP Manual

VarnishAdmin::banUrl

(PECL varnish >= 0.3)

VarnishAdmin::banUrl — Ban an URL using a VCL expression

Opis

public int VarnishAdmin::banUrl ( string $vcl_regex )

Parametry

vcl_regex

URL regular expression in PCRE compatible syntax. It's based on the ban.url varnish command.

Zwracane wartości

Returns the varnish command status.

VarnishAdmin::ban
VarnishAdmin::clearPanic
VarnishAdmin


Clear varnish instance panic messages

VarnishAdmin::banUrl
VarnishAdmin::connect
VarnishAdmin
PHP Manual

VarnishAdmin::clearPanic

(PECL varnish >= 0.4)

VarnishAdmin::clearPanic — Clear varnish instance panic messages

Opis

public int VarnishAdmin::clearPanic ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the varnish command status.

VarnishAdmin::banUrl
VarnishAdmin::connect
VarnishAdmin


Connect to a varnish instance administration interface

VarnishAdmin::clearPanic
VarnishAdmin::__construct
VarnishAdmin
PHP Manual

VarnishAdmin::connect

(PECL varnish >= 0.3)

VarnishAdmin::connect — Connect to a varnish instance administration interface

Opis

public bool VarnishAdmin::connect ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

VarnishAdmin::clearPanic
VarnishAdmin::__construct
VarnishAdmin


VarnishAdmin constructor

VarnishAdmin::connect
VarnishAdmin::getPanic
VarnishAdmin
PHP Manual

VarnishAdmin::__construct

(PECL varnish >= 0.3)

VarnishAdmin::__construct — VarnishAdmin constructor

Opis

public VarnishAdmin::__construct ([ array $args ] )

Parametry

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident
VARNISH_CONFIG_HOST - varnish instance ip
VARNISH_CONFIG_PORT - varnish instance port
VARNISH_CONFIG_SECRET - varnish instance secret
VARNISH_CONFIG_TIMEOUT - connection read timeout
VARNISH_CONFIG_COMPAT - varnish major version compatibility

Zwracane wartości

Przykłady

Przykład #1 VarnishAdmin::__construct() example

<?php
    $args = array(
        VARNISH_CONFIG_HOST => "::1",
        VARNISH_CONFIG_PORT => 6082,
        VARNISH_CONFIG_SECRET => "5174826b-8595-4958-aa7a-0609632ad7ca",
        VARNISH_CONFIG_TIMEOUT => 300,
    );
    $va = new VarnishAdmin($args);
?>
VarnishAdmin::connect
VarnishAdmin::getPanic
VarnishAdmin


Get the last panic message on a varnish instance

VarnishAdmin::__construct
VarnishAdmin::getParams
VarnishAdmin
PHP Manual

VarnishAdmin::getPanic

(PECL varnish >= 0.4)

VarnishAdmin::getPanic — Get the last panic message on a varnish instance

Opis

public string VarnishAdmin::getPanic ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the last panic message on the current varnish instance.

VarnishAdmin::__construct
VarnishAdmin::getParams
VarnishAdmin


Fetch current varnish instance configuration parameters

VarnishAdmin::getPanic
VarnishAdmin::isRunning
VarnishAdmin
PHP Manual

VarnishAdmin::getParams

(PECL varnish >= 0.4)

VarnishAdmin::getParams — Fetch current varnish instance configuration parameters

Opis

public array VarnishAdmin::getParams ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array with the varnish configuration parameters.

VarnishAdmin::getPanic
VarnishAdmin::isRunning
VarnishAdmin


Check if the varnish slave process is currently running

VarnishAdmin::getParams
VarnishAdmin::setCompat
VarnishAdmin
PHP Manual

VarnishAdmin::isRunning

(PECL varnish >= 0.3)

VarnishAdmin::isRunning — Check if the varnish slave process is currently running

Opis

public bool VarnishAdmin::isRunning ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

VarnishAdmin::getParams
VarnishAdmin::setCompat
VarnishAdmin


Set the class compat configuration param

VarnishAdmin::isRunning
VarnishAdmin::setHost
VarnishAdmin
PHP Manual

VarnishAdmin::setCompat

(PECL varnish >= 0.9.2)

VarnishAdmin::setCompat — Set the class compat configuration param

Opis

public void VarnishAdmin::setCompat ( int $compat )

Parametry

compat

Varnish compatibility option.

Zwracane wartości

VarnishAdmin::isRunning
VarnishAdmin::setHost
VarnishAdmin


Set the class host configuration param

VarnishAdmin::setCompat
VarnishAdmin::setIdent
VarnishAdmin
PHP Manual

VarnishAdmin::setHost

(PECL varnish >= 0.8)

VarnishAdmin::setHost — Set the class host configuration param

Opis

public void VarnishAdmin::setHost ( string $host )

Parametry

host

Connection host configuration parameter.

Zwracane wartości

VarnishAdmin::setCompat
VarnishAdmin::setIdent
VarnishAdmin


Set the class ident configuration param

VarnishAdmin::setHost
VarnishAdmin::setParam
VarnishAdmin
PHP Manual

VarnishAdmin::setIdent

(PECL varnish >= 0.8)

VarnishAdmin::setIdent — Set the class ident configuration param

Opis

public void VarnishAdmin::setIdent ( string $ident )

Parametry

ident

Connection ident configuration parameter.

Zwracane wartości

VarnishAdmin::setHost
VarnishAdmin::setParam
VarnishAdmin


Set configuration param on the current varnish instance

VarnishAdmin::setIdent
VarnishAdmin::setPort
VarnishAdmin
PHP Manual

VarnishAdmin::setParam

(PECL varnish >= 0.4)

VarnishAdmin::setParam — Set configuration param on the current varnish instance

Opis

public int VarnishAdmin::setParam ( string $name , string|integer $value )

Parametry

name

Varnish configuration param name.

value

Varnish configuration param value.

Zwracane wartości

Returns the varnish command status.

VarnishAdmin::setIdent
VarnishAdmin::setPort
VarnishAdmin


Set the class port configuration param

VarnishAdmin::setParam
VarnishAdmin::setSecret
VarnishAdmin
PHP Manual

VarnishAdmin::setPort

(PECL varnish >= 0.8)

VarnishAdmin::setPort — Set the class port configuration param

Opis

public void VarnishAdmin::setPort ( int $port )

Parametry

port

Connection port configuration parameter.

Zwracane wartości

VarnishAdmin::setParam
VarnishAdmin::setSecret
VarnishAdmin


Set the class secret configuration param

VarnishAdmin::setPort
VarnishAdmin::setTimeout
VarnishAdmin
PHP Manual

VarnishAdmin::setSecret

(PECL varnish >= 0.8)

VarnishAdmin::setSecret — Set the class secret configuration param

Opis

public void VarnishAdmin::setSecret ( string $secret )

Parametry

secret

Connection secret configuration parameter.

Zwracane wartości

VarnishAdmin::setPort
VarnishAdmin::setTimeout
VarnishAdmin


Set the class timeout configuration param

VarnishAdmin::setSecret
VarnishAdmin::start
VarnishAdmin
PHP Manual

VarnishAdmin::setTimeout

(PECL varnish >= 0.8)

VarnishAdmin::setTimeout — Set the class timeout configuration param

Opis

public void VarnishAdmin::setTimeout ( int $timeout )

Parametry

timeout

Connection timeout configuration parameter.

Zwracane wartości

VarnishAdmin::setSecret
VarnishAdmin::start
VarnishAdmin


Start varnish worker process

VarnishAdmin::setTimeout
VarnishAdmin::stop
VarnishAdmin
PHP Manual

VarnishAdmin::start

(PECL varnish >= 0.3)

VarnishAdmin::start — Start varnish worker process

Opis

public int VarnishAdmin::start ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the varnish command status.

VarnishAdmin::setTimeout
VarnishAdmin::stop
VarnishAdmin


Stop varnish worker process

VarnishAdmin::start
VarnishStat
VarnishAdmin
PHP Manual

VarnishAdmin::stop

(PECL varnish >= 0.3)

VarnishAdmin::stop — Stop varnish worker process

Opis

public int VarnishAdmin::stop ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the varnish command status.

VarnishAdmin::start
VarnishStat
VarnishAdmin


The VarnishStat class

(PECL varnish >= 0.3)

Wstęp

Krótki opis klasy

VarnishStat {
/* Metody */
public __construct ([ array $args ] )
public array getSnapshot ( void )
}

Spis treści

  • VarnishStat::__construct — VarnishStat constructor
  • VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot
VarnishAdmin::stop
VarnishStat::__construct
Varnish


VarnishStat constructor

VarnishStat
VarnishStat::getSnapshot
VarnishStat
PHP Manual

VarnishStat::__construct

(PECL varnish >= 0.3)

VarnishStat::__construct — VarnishStat constructor

Opis

public VarnishStat::__construct ([ array $args ] )

Parametry

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

Zwracane wartości

VarnishStat
VarnishStat::getSnapshot
VarnishStat


Get the current varnish instance statistics snapshot

VarnishStat::__construct
VarnishLog
VarnishStat
PHP Manual

VarnishStat::getSnapshot

(PECL varnish >= 0.3)

VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot

Opis

public array VarnishStat::getSnapshot ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Array with the varnish statistic snapshot. The array keys are identical to that in the varnishstat tool.

VarnishStat::__construct
VarnishLog
VarnishStat


The VarnishLog class

(PECL varnish >= 0.6)

Wstęp

Krótki opis klasy

VarnishLog {
/* Constants */
const integer TAG_Debug = 0 ;
const integer TAG_Error = 1 ;
const integer TAG_CLI = 2 ;
const integer TAG_StatSess = 3 ;
const integer TAG_ReqEnd = 4 ;
const integer TAG_SessionOpen = 5 ;
const integer TAG_SessionClose = 6 ;
const integer TAG_BackendOpen = 7 ;
const integer TAG_BackendXID = 8 ;
const integer TAG_BackendReuse = 9 ;
const integer TAG_BackendClose = 10 ;
const integer TAG_HttpGarbage = 11 ;
const integer TAG_Backend = 12 ;
const integer TAG_Length = 13 ;
const integer TAG_FetchError = 14 ;
const integer TAG_RxRequest = 15 ;
const integer TAG_RxResponse = 16 ;
const integer TAG_RxStatus = 17 ;
const integer TAG_RxURL = 18 ;
const integer TAG_RxProtocol = 19 ;
const integer TAG_RxHeader = 20 ;
const integer TAG_TxRequest = 21 ;
const integer TAG_TxResponse = 22 ;
const integer TAG_TxStatus = 23 ;
const integer TAG_TxURL = 24 ;
const integer TAG_TxProtocol = 25 ;
const integer TAG_TxHeader = 26 ;
const integer TAG_ObjRequest = 27 ;
const integer TAG_ObjResponse = 28 ;
const integer TAG_ObjStatus = 29 ;
const integer TAG_ObjURL = 30 ;
const integer TAG_ObjProtocol = 31 ;
const integer TAG_ObjHeader = 32 ;
const integer TAG_LostHeader = 33 ;
const integer TAG_TTL = 34 ;
const integer TAG_Fetch_Body = 35 ;
const integer TAG_VCL_acl = 36 ;
const integer TAG_VCL_call = 37 ;
const integer TAG_VCL_trace = 38 ;
const integer TAG_VCL_return = 39 ;
const integer TAG_VCL_error = 40 ;
const integer TAG_ReqStart = 41 ;
const integer TAG_Hit = 42 ;
const integer TAG_HitPass = 43 ;
const integer TAG_ExpBan = 44 ;
const integer TAG_ExpKill = 45 ;
const integer TAG_WorkThread = 46 ;
const integer TAG_ESI_xmlerror = 47 ;
const integer TAG_Hash = 48 ;
const integer TAG_Backend_health = 49 ;
const integer TAG_VCL_Log = 50 ;
const integer TAG_Gzip = 51 ;
/* Metody */
public __construct ([ array $args ] )
public array getLine ( void )
public static string getTagName ( int $index )
}

Stałe predefiniowane

VarnishLog::TAG_Debug

VarnishLog::TAG_Error

VarnishLog::TAG_CLI

VarnishLog::TAG_StatSess

VarnishLog::TAG_ReqEnd

VarnishLog::TAG_SessionOpen

VarnishLog::TAG_SessionClose

VarnishLog::TAG_BackendOpen

VarnishLog::TAG_BackendXID

VarnishLog::TAG_BackendReuse

VarnishLog::TAG_BackendClose

VarnishLog::TAG_HttpGarbage

VarnishLog::TAG_Backend

VarnishLog::TAG_Length

VarnishLog::TAG_FetchError

VarnishLog::TAG_RxRequest

VarnishLog::TAG_RxResponse

VarnishLog::TAG_RxStatus

VarnishLog::TAG_RxURL

VarnishLog::TAG_RxProtocol

VarnishLog::TAG_RxHeader

VarnishLog::TAG_TxRequest

VarnishLog::TAG_TxResponse

VarnishLog::TAG_TxStatus

VarnishLog::TAG_TxURL

VarnishLog::TAG_TxProtocol

VarnishLog::TAG_TxHeader

VarnishLog::TAG_ObjRequest

VarnishLog::TAG_ObjResponse

VarnishLog::TAG_ObjStatus

VarnishLog::TAG_ObjURL

VarnishLog::TAG_ObjProtocol

VarnishLog::TAG_ObjHeader

VarnishLog::TAG_LostHeader

VarnishLog::TAG_TTL

VarnishLog::TAG_Fetch_Body

VarnishLog::TAG_VCL_acl

VarnishLog::TAG_VCL_call

VarnishLog::TAG_VCL_trace

VarnishLog::TAG_VCL_return

VarnishLog::TAG_VCL_error

VarnishLog::TAG_ReqStart

VarnishLog::TAG_Hit

VarnishLog::TAG_HitPass

VarnishLog::TAG_ExpBan

VarnishLog::TAG_ExpKill

VarnishLog::TAG_WorkThread

VarnishLog::TAG_ESI_xmlerror

VarnishLog::TAG_Hash

VarnishLog::TAG_Backend_health

VarnishLog::TAG_VCL_Log

VarnishLog::TAG_Gzip

Spis treści

  • VarnishLog::__construct — Varnishlog constructor
  • VarnishLog::getLine — Get next log line
  • VarnishLog::getTagName — Get the log tag string representation by its index
VarnishStat::getSnapshot
VarnishLog::__construct
Varnish


Varnishlog constructor

VarnishLog
VarnishLog::getLine
VarnishLog
PHP Manual

VarnishLog::__construct

(PECL varnish >= 0.6)

VarnishLog::__construct — Varnishlog constructor

Opis

public VarnishLog::__construct ([ array $args ] )

Parametry

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

Zwracane wartości

VarnishLog
VarnishLog::getLine
VarnishLog


Get next log line

VarnishLog::__construct
VarnishLog::getTagName
VarnishLog
PHP Manual

VarnishLog::getLine

(PECL varnish >= 0.6)

VarnishLog::getLine — Get next log line

Opis

public array VarnishLog::getLine ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array with the log line data.

VarnishLog::__construct
VarnishLog::getTagName
VarnishLog


Get the log tag string representation by its index

VarnishLog::getLine
YAZ
VarnishLog
PHP Manual

VarnishLog::getTagName

(PECL varnish >= 0.6)

VarnishLog::getTagName — Get the log tag string representation by its index

Opis

public static string VarnishLog::getTagName ( int $index )

Parametry

index

Log tag index.

Zwracane wartości

Returns the log tag name as string.

VarnishLog::getLine
YAZ
VarnishLog


YAZ

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • YAZ Funkcje
    • yaz_addinfo — Returns additional error information
    • yaz_ccl_conf — Configure CCL parser
    • yaz_ccl_parse — Invoke CCL Parser
    • yaz_close — Close YAZ connection
    • yaz_connect — Prepares for a connection to a Z39.50 server
    • yaz_database — Specifies the databases within a session
    • yaz_element — Specifies Element-Set Name for retrieval
    • yaz_errno — Returns error number
    • yaz_error — Returns error description
    • yaz_es_result — Inspects Extended Services Result
    • yaz_es — Prepares for an Extended Service Request
    • yaz_get_option — Returns value of option for connection
    • yaz_hits — Returns number of hits for last search
    • yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present — Prepares for retrieval (Z39.50 present)
    • yaz_range — Specifies a range of records to retrieve
    • yaz_record — Returns a record
    • yaz_scan_result — Returns Scan Response result
    • yaz_scan — Prepares for a scan
    • yaz_schema — Specifies schema for retrieval
    • yaz_search — Prepares for a search
    • yaz_set_option — Sets one or more options for connection
    • yaz_sort — Sets sorting criteria
    • yaz_syntax — Specifies the preferred record syntax for retrieval
    • yaz_wait — Wait for Z39.50 requests to complete
VarnishLog::getTagName
Wstęp
Inne serwisy


Wstęp

This extension offers a PHP interface to the YAZ toolkit that implements the » Z39.50 Protocol for Information Retrieval. With this extension you can easily implement a Z39.50 origin (client) that searches or scans Z39.50 targets (servers) in parallel.

The module hides most of the complexity of Z39.50 so it should be fairly easy to use. It supports persistent stateless connections very similar to those offered by the various RDB APIs that are available for PHP. This means that sessions are stateless but shared among users, thus saving the connect and initialize phase steps in most cases.

YAZ is available at » http://www.indexdata.dk/yaz/. You can find news information, example scripts, etc. for this extension at » http://www.indexdata.dk/phpyaz/.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0.

YAZ
Instalacja/Konfiguracja
YAZ


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
YAZ


Wymagania

Obtain YAZ (ANSI/NISO Z39.50 support) and install it. YAZ can be fetched in source or in various prebuilt packages from the » YAZ archive. Systems such as Debian GNU/Linux, Suse Linux, FreeBSD also has YAZ as part of their distribution.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/yaz

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Informacja: Information specific to Windows users

php_yaz.dll depends on yaz.dll. The yaz.dll is part of the Win32 ZIP from the PHP site. It is also part of the Windows YAZ install available from the » YAZ WIN32 area.

On windows, don't forget to add the PHP directory to the PATH, so that the yaz.dll file can be found by the system.

Ostrzeżenie

Rozszerzenia IMAP, recode, YAZ i Cyrus nie mogą być używane razem. Dzieje się tak z powodu współdzielenia tych samych oznaczeń wewnętrznych. Notatka: problem nie dotyczy Yaz 2.0 i nowszych wersji.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

YAZ configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
yaz.max_links | "100" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.0.0.
yaz.log_file | NULL | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.0.0.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
YAZ


Przykłady

PHP/YAZ keeps track of connections with targets (Z-Associations). A resource represents a connection to a target.

The script below demonstrates the parallel searching feature of the API. When invoked with no arguments it prints a query form; else (arguments are supplied) it searches the targets as given in array host.

Przykład #1 Parallel searching using Yaz

<?php
$host=$_REQUEST[host];
$query=$_REQUEST[query];
$num_hosts = count($host);
if (empty($query) || count($host) == 0) {
    echo '<form method="get">
    <input type="checkbox"
    name="host[]" value="bagel.indexdata.dk/gils" />
        GILS test
    <input type="checkbox"
    name="host[]" value="localhost:9999/Default" />
        local test
    <input type="checkbox" checked="checked"
    name="host[]" value="z3950.loc.gov:7090/voyager" />
        Library of Congress
    <br />
    RPN Query:
    <input type="text" size="30" name="query" />
    <input type="submit" name="action" value="Search" />
    </form>
    ';
} else {
    echo 'You searched for ' . htmlspecialchars($query) . '<br />';
    for ($i = 0; $i < $num_hosts; $i++) {
        $id[] = yaz_connect($host[$i]);
        yaz_syntax($id[$i], "usmarc");
        yaz_range($id[$i], 1, 10);
        yaz_search($id[$i], "rpn", $query);
    }
    yaz_wait();
    for ($i = 0; $i < $num_hosts; $i++) {
        echo '<hr />' . $host[$i] . ':';
        $error = yaz_error($id[$i]);
        if (!empty($error)) {
            echo "Error: $error";
        } else {
            $hits = yaz_hits($id[$i]);
            echo "Result Count $hits";
        }
        echo '<dl>';
        for ($p = 1; $p <= 10; $p++) {
            $rec = yaz_record($id[$i], $p, "string");
            if (empty($rec)) continue;
            echo "<dt><b>$p</b></dt><dd>";
            echo nl2br($rec);
            echo "</dd>";
        }
        echo '</dl>';
    }
}
?>

Stałe predefiniowane
YAZ Funkcje
YAZ


YAZ Funkcje

Spis treści

  • yaz_addinfo — Returns additional error information
  • yaz_ccl_conf — Configure CCL parser
  • yaz_ccl_parse — Invoke CCL Parser
  • yaz_close — Close YAZ connection
  • yaz_connect — Prepares for a connection to a Z39.50 server
  • yaz_database — Specifies the databases within a session
  • yaz_element — Specifies Element-Set Name for retrieval
  • yaz_errno — Returns error number
  • yaz_error — Returns error description
  • yaz_es_result — Inspects Extended Services Result
  • yaz_es — Prepares for an Extended Service Request
  • yaz_get_option — Returns value of option for connection
  • yaz_hits — Returns number of hits for last search
  • yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package
  • yaz_present — Prepares for retrieval (Z39.50 present)
  • yaz_range — Specifies a range of records to retrieve
  • yaz_record — Returns a record
  • yaz_scan_result — Returns Scan Response result
  • yaz_scan — Prepares for a scan
  • yaz_schema — Specifies schema for retrieval
  • yaz_search — Prepares for a search
  • yaz_set_option — Sets one or more options for connection
  • yaz_sort — Sets sorting criteria
  • yaz_syntax — Specifies the preferred record syntax for retrieval
  • yaz_wait — Wait for Z39.50 requests to complete
Przykłady
yaz_addinfo
YAZ


Returns additional error information

YAZ Funkcje
yaz_ccl_conf
YAZ Funkcje
PHP Manual

yaz_addinfo

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_addinfo — Returns additional error information

Opis

string yaz_addinfo ( resource $id )

Returns additional error information for the last request on the server.

With some servers, this function may return the same string as yaz_error().

Parametry

id

The connection resource returned by yaz_connect().

Zwracane wartości

A string containing additional error information or an empty string if the last operation was successful or if no additional information was provided by the server.

Zobacz też:

  • yaz_error() - Returns error description
  • yaz_errno() - Returns error number

YAZ Funkcje
yaz_ccl_conf
YAZ Funkcje


Configure CCL parser

yaz_addinfo
yaz_ccl_parse
YAZ Funkcje
PHP Manual

yaz_ccl_conf

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_ccl_conf — Configure CCL parser

Opis

void yaz_ccl_conf ( resource $id , array $config )

This function configures the CCL query parser for a server with definitions of access points (CCL qualifiers) and their mapping to RPN.

To map a specific CCL query to RPN afterwards call the yaz_ccl_parse() function.

Parametry

id

The connection resource returned by yaz_connect().

config

An array of configuration. Each key of the array is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN.

The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.

Additional information can be found on the » CCL page.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each field is mapped to their BIB-1 equivalent. It is assumed that variable $id is the connection ID.

Przykład #1 CCL configuration

<?php
$fields = array(
  "ti" => "1=4",
  "au"   => "1=1",
  "isbn" => "1=7"
);
yaz_ccl_conf($id, $fields);
?>

Zobacz też:

  • yaz_ccl_parse() - Invoke CCL Parser

yaz_addinfo
yaz_ccl_parse
YAZ Funkcje


Invoke CCL Parser

yaz_ccl_conf
yaz_close
YAZ Funkcje
PHP Manual

yaz_ccl_parse

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_ccl_parse — Invoke CCL Parser

Opis

bool yaz_ccl_parse ( resource $id , string $query , array &$result )

This function invokes a CCL parser. It converts a given CCL FIND query to an RPN query which may be passed to the yaz_search() function to perform a search.

To define a set of valid CCL fields call yaz_ccl_conf() prior to this function.

Parametry

id

The connection resource returned by yaz_connect().

query

The CCL FIND query.

result

If the function was executed successfully, this will be an array containing the valid RPN query under the key rpn.

Upon failure, three indexes are set in this array to indicate the cause of failure:

  • errorcode - the CCL error code (integer)

  • errorstring - the CCL error string

  • errorpos - approximate position in query of failure (integer is character position)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 CCL Parsing

We will try to search using CCL. In the example below, $ccl is a CCL query.

<?php

yaz_ccl_conf($id, $fields);  // see example for yaz_ccl_conf
if (!yaz_ccl_parse($id, $ccl, &$cclresult)) {
    echo 'Error: ' . $cclresult["errorstring"];
} else {
    $rpn = $cclresult["rpn"];
    yaz_search($id, "rpn", $rpn);
}
?>
yaz_ccl_conf
yaz_close
YAZ Funkcje


Close YAZ connection

yaz_ccl_parse
yaz_connect
YAZ Funkcje
PHP Manual

yaz_close

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_close — Close YAZ connection

Opis

bool yaz_close ( resource $id )

Closes the connection given by parameter id.

Informacja:

This function will only close a non-persistent connection opened by setting the persistent option to FALSE with yaz_connect().

Parametry

id

The connection resource returned by yaz_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • yaz_connect() - Prepares for a connection to a Z39.50 server

yaz_ccl_parse
yaz_connect
YAZ Funkcje


Prepares for a connection to a Z39.50 server

yaz_close
yaz_database
YAZ Funkcje
PHP Manual

yaz_connect

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_connect — Prepares for a connection to a Z39.50 server

Opis

mixed yaz_connect ( string $zurl [, mixed $options ] )

This function returns a connection resource on success, zero on failure.

yaz_connect() prepares for a connection to a Z39.50 server. This function is non-blocking and does not attempt to establish a connection - it merely prepares a connect to be performed later when yaz_wait() is called.

Informacja:

The » YAZ proxy is a freely available Z39.50 proxy.

Parametry

zurl

A string that takes the form host[:port][/database]. If port is omitted, port 210 is used. If database is omitted Default is used.

options

If given as a string, it is treated as the Z39.50 V2 authentication string (OpenAuth).

If given as an array, the contents of the array serves as options.

user

Username for authentication.

group

Group for authentication.

password

Password for authentication.

cookie

Cookie for session (YAZ proxy).

proxy

Proxy for connection (YAZ proxy).

persistent

A boolean. If TRUE the connection is persistent; If FALSE the connection is not persistent. By default connections are persistent.

Informacja:

If you open a persistent connection, you won't be able to close it later with yaz_close().

piggyback

A boolean. If TRUE piggyback is enabled for searches; If FALSE piggyback is disabled. By default piggyback is enabled.

Enabling piggyback is more efficient and usually saves a network-round-trip for first time fetches of records. However, a few Z39.50 servers do not support piggyback or they ignore element set names. For those, piggyback should be disabled.

charset

A string that specifies character set to be used in Z39.50 language and character set negotiation. Use strings such as: ISO-8859-1, UTF-8, UTF-16.

Most Z39.50 servers do not support this feature (and thus, this is ignored). Many servers use the ISO-8859-1 encoding for queries and messages. MARC21/USMARC records are not affected by this setting.

preferredMessageSize

An integer that specifies the maximum byte size of all records to be returned by a target during retrieval. See the » Z39.50 standard for more information.

Informacja:

This option is supported in PECL YAZ 1.0.5 or later.

maximumRecordSize

An integer that specifies the maximum byte size of a single record to be returned by a target during retrieval. This entity is referred to as Exceptional-record-size in the » Z39.50 standard.

Informacja:

This option is supported in PECL YAZ 1.0.5 or later.

Zwracane wartości

A connection resource on success, FALSE on error.

Rejestr zmian

Wersja | Opis
4.1.0 | The parameter options was added.

Zobacz też:

  • yaz_close() - Close YAZ connection

yaz_close
yaz_database
YAZ Funkcje


Specifies the databases within a session

yaz_connect
yaz_element
YAZ Funkcje
PHP Manual

yaz_database

(PHP 4 >= 4.0.6, PECL yaz >= 0.9.0)

yaz_database — Specifies the databases within a session

Opis

bool yaz_database ( resource $id , string $databases )

This function allows you to change databases within a session by specifying one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect().

Parametry

id

The connection resource returned by yaz_connect().

databases

A string containing one or more databases. Multiple databases are separated by a plus sign +.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

yaz_connect
yaz_element
YAZ Funkcje


Specifies Element-Set Name for retrieval

yaz_database
yaz_errno
YAZ Funkcje
PHP Manual

yaz_element

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_element — Specifies Element-Set Name for retrieval

Opis

bool yaz_element ( resource $id , string $elementset )

This function sets the element set name for retrieval.

Call this function before yaz_search() or yaz_present() to specify the element set name for records to be retrieved.

Informacja:

If this function appears to have no effect, see the description of the piggybacking option in yaz_connect().

Parametry

id

The connection resource returned by yaz_connect().

elementset

Most servers support F (for full records) and B (for brief records).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

yaz_database
yaz_errno
YAZ Funkcje


Returns error number

yaz_element
yaz_error
YAZ Funkcje
PHP Manual

yaz_errno

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_errno — Returns error number

Opis

int yaz_errno ( resource $id )

Returns an error number for the server (last request) identified by id.

yaz_errno() should be called after network activity for each server - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search).

Parametry

id

The connection resource returned by yaz_connect().

Zwracane wartości

Returns an error code. The error code is either a Z39.50 diagnostic code (usually a Bib-1 diagnostic) or a client side error code which is generated by PHP/YAZ itself, such as "Connect failed", "Init Rejected", etc.

Zobacz też:

  • yaz_error() - Returns error description
  • yaz_addinfo() - Returns additional error information

yaz_element
yaz_error
YAZ Funkcje


Returns error description

yaz_errno
yaz_es_result
YAZ Funkcje
PHP Manual

yaz_error

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_error — Returns error description

Opis

string yaz_error ( resource $id )

yaz_error() returns an English text message corresponding to the last error number as returned by yaz_errno().

Parametry

id

The connection resource returned by yaz_connect().

Zwracane wartości

Returns an error text message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful.

Zobacz też:

  • yaz_errno() - Returns error number
  • yaz_addinfo() - Returns additional error information

yaz_errno
yaz_es_result
YAZ Funkcje


Inspects Extended Services Result

yaz_error
yaz_es
YAZ Funkcje
PHP Manual

yaz_es_result

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

yaz_es_result — Inspects Extended Services Result

Opis

array yaz_es_result ( resource $id )

This function inspects the last returned Extended Service result from a server. An Extended Service is initiated by either yaz_item_order() or yaz_es().

Parametry

id

The connection resource returned by yaz_connect().

Zwracane wartości

Returns array with element targetReference for the reference for the extended service operation (generated and returned from the server).

Zobacz też:

  • yaz_es() - Prepares for an Extended Service Request

yaz_error
yaz_es
YAZ Funkcje


Prepares for an Extended Service Request

yaz_es_result
yaz_get_option
YAZ Funkcje
PHP Manual

yaz_es

(PECL yaz >= 0.9.0)

yaz_es — Prepares for an Extended Service Request

Opis

void yaz_es ( resource $id , string $type , array $args )

This function prepares for an Extended Service Request. Extended Services is family of various Z39.50 facilities, such as Record Update, Item Order, Database administration etc.

Informacja:

Many Z39.50 Servers do not support Extended Services.

The yaz_es() creates an Extended Service Request packages and puts it into a queue of operations. Use yaz_wait() to send the request(s) to the server. After completion of yaz_wait() the result of the Extended Service operation should be expected with a call to yaz_es_result().

Parametry

id

The connection resource returned by yaz_connect().

type

A string which represents the type of the Extended Service: itemorder (Item Order), create (Create Database), drop (Drop Database), commit (Commit Operation), update (Update Record), xmlupdate (XML Update). Each type is specified in the following section.

args

An array with extended service options plus package specific options. The options are identical to those offered in the C API of ZOOM C. Refer to the ZOOM » Extended Services.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Record Update

<?php
$con = yaz_connect("myhost/database");
$args = array (
    "record" => "<gils><title>some title</title></gils>",
    "syntax" => "xml",
    "action" => "specialUpdate"
);
yaz_es($con, "update", $args);
yaz_wait();
$result = yaz_es_result($id);
?>

Zobacz też:

  • yaz_es_result() - Inspects Extended Services Result

yaz_es_result
yaz_get_option
YAZ Funkcje


Returns value of option for connection

yaz_es
yaz_hits
YAZ Funkcje
PHP Manual

yaz_get_option

(PECL yaz >= 0.9.0)

yaz_get_option — Returns value of option for connection

Opis

string yaz_get_option ( resource $id , string $name )

Returns the value of the option specified with name.

Parametry

id

The connection resource returned by yaz_connect().

name

The option name.

Zwracane wartości

Returns the value of the specified option or an empty string if the option wasn't set.

Zobacz też:

  • The description of yaz_set_option() - Sets one or more options for connection for available options

yaz_es
yaz_hits
YAZ Funkcje


Returns number of hits for last search

yaz_get_option
yaz_itemorder
YAZ Funkcje
PHP Manual

yaz_hits

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_hits — Returns number of hits for last search

Opis

int yaz_hits ( resource $id [, array &$searchresult ] )

yaz_hits() returns the number of hits for the last search.

Parametry

id

The connection resource returned by yaz_connect().

searchresult

Result array for detailed search result information.

Zwracane wartości

Returns the number of hits for the last search or 0 if no search was performed.

The search result array (if supplied) holds information that is returned by a Z39.50 server in the SearchResult-1 format part of a search response. The SearchResult-1 format can be used to obtain information about hit counts for various parts of the query (subquery). In particular, it is possible to obtain hit counts for the individual search terms in a query. Information for first subquery is in $array[0], second subquery in $array[1], and so forth.

searchresult members
Element | Description
id | Sub query ID2 (string)
count | Result count / hits (integer)
subquery.term | Sub query term (string)
interpretation.term | Interpretated sub query term (string)
recommendation.term | Recommended sub query term (string)

Informacja:

The SearchResult facility requires PECL YAZ 1.0.5 or later and YAZ 2.1.9 or later.

Informacja:

Very few Z39.50 implementations support the SearchResult facility.

yaz_get_option
yaz_itemorder
YAZ Funkcje


Prepares for Z39.50 Item Order with an ILL-Request package

yaz_hits
yaz_present
YAZ Funkcje
PHP Manual

yaz_itemorder

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package

Opis

void yaz_itemorder ( resource $id , array $args )

This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item Order Extended Service to Transport ILL (Profile/1). See » this and the » specification.

Parametry

id

The connection resource returned by yaz_connect().

args

Must be an associative array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.

The ILL-Request parameters are:

protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note

There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:

package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item

Zwracane wartości

Nie jest zwracana żadna wartość.

yaz_hits
yaz_present
YAZ Funkcje


Prepares for retrieval (Z39.50 present)

yaz_itemorder
yaz_range
YAZ Funkcje
PHP Manual

yaz_present

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_present — Prepares for retrieval (Z39.50 present)

Opis

bool yaz_present ( resource $id )

This function prepares for retrieval of records after a successful search.

The yaz_range() function should be called prior to this function to specify the range of records to be retrieved.

Parametry

id

The connection resource returned by yaz_connect().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

yaz_itemorder
yaz_range
YAZ Funkcje


Specifies a range of records to retrieve

yaz_present
yaz_record
YAZ Funkcje
PHP Manual

yaz_range

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_range — Specifies a range of records to retrieve

Opis

void yaz_range ( resource $id , int $start , int $number )

Specifies a range of records to retrieve.

This function should be called before yaz_search() or yaz_present().

Parametry

id

The connection resource returned by yaz_connect().

start

Specifies the position of the first record to be retrieved. The records numbers goes from 1 to yaz_hits().

number

Specifies the number of records to be retrieved.

Zwracane wartości

Nie jest zwracana żadna wartość.

yaz_present
yaz_record
YAZ Funkcje


Returns a record

yaz_range
yaz_scan_result
YAZ Funkcje
PHP Manual

yaz_record

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_record — Returns a record

Opis

string yaz_record ( resource $id , int $pos , string $type )

The yaz_record() function inspects a record in the current result set at the position specified by parameter pos.

Parametry

id

The connection resource returned by yaz_connect().

pos

The record position. Records positions in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

type

The type specifies the form of the returned record.

Informacja:

It is the application which is responsible for actually ensuring that the records are returned from the Z39.50/SRW server in the proper format. The type given only specifies a conversion to take place on the client side (in PHP/YAZ).

Besides conversion of the transfer record to a string/array, PHP/YAZ it is also possible to perform a character set conversion of the record. Especially for USMARC/MARC21 that is recommended since these are typically returned in the character set MARC-8 that is not supported by browsers, etc. To specify a conversion, add ; charset=from, to where from is the original character set of the record and to is the resulting character set (as seen by PHP).

string

The record is returned as a string for simple display. In this mode, all MARC records are converted to a line-by-line format since ISO2709 is hardly readable. XML records and SUTRS are returned in their original format. GRS-1 are returned in a (ugly) line-by-line format.

This format is suitable if records are to be displayed in a quick way - for debugging - or because it is not feasible to perform proper display.

xml

The record is returned as an XML string if possible. In this mode, all MARC records are converted to » MARCXML. XML records and SUTRS are returned in their original format. GRS-1 is not supported.

This format is similar to string except that MARC records are converted to MARCXML

This format is suitable if records are processed by an XML parser or XSLT processor afterwards.

raw

The record is returned as a string in its original form. This type is suitable for MARC, XML and SUTRS. It does not work for GRS-1.

MARC records are returned as a ISO2709 string. XML and SUTRS are returned as strings.

syntax

The syntax of the record is returned as a string, i.e. USmarc, GRS-1, XML, etc.

database

The name of database associated with record at the position is returned as a string.

array

The record is returned as an array that reflects the GRS-1 structure. This type is suitable for MARC and GRS-1. XML, SUTRS are not supported and if the actual record is XML or SUTRS an empty string will be returned.

The array returned consists of a list corresponding to each leaf/internal node of GRS-1. Each list item consists a sub list with first element path and data (if data is available).

The path which is a string holds a list of each tree component (of the structured GRS-1 record) from root to leaf. Each component is a tag type, tag value pair of the form (type, value

String tags normally has a corresponding tag type 3. MARC can also be returned as an array (they are converted to GRS-1 internally).

Zwracane wartości

Returns the record at position pos or an empty string if no record exists at the given position.

If no database record exists at the given position an empty string is returned.

Przykłady

Przykład #1 Array for GRS-1 record

Consider this GRS-1 record:

(4,52)Robert M. Pirsig
(4,70)
      (4,90)
            (2,7)Transworld Publishers, ltd.
This record has two nodes at root level. First element at root level is (4,52) [tag type 4, tag value 52], and has data Robert M. Pirsig. Second element at root level (4,70) has a subtree with a single element (4,90). (4,90) has yet another sub tree (2,7) with data Transworld Publishers, ltd..

If this record is present at position $p, then

<?php

$ar = yaz_record($id, $p, "array");
print_r($ar);

?>
will output:
Array
(
    [0] => Array
        (
            [0] => (4,52)
            [1] => Robert M. Pirsig
        )
    [1] => Array
        (
            [0] => (4,70)
        )
    [2] => Array
        (
            [0] => (4,70)(4,90)
        )
    [3] => Array
        (
            [0] => (4,70)(4,90)(2,7)
            [1] => Transworld Publishers, ltd.
        )
)

Przykład #2 Working with MARCXML

The following PHP snippet returns a MARC21/USMARC record as MARCXML. The original record is returned in marc-8 (unknown to most XML parsers), so we convert it to UTF-8 (which all XML parsers must support).

<?php
$rec = yaz_record($id, $p, "xml; charset=marc-8,utf-8");
?>

The record $rec can be processed with the Sablotron XSLT processor as follows:

<?php

$xslfile = 'display.xsl';
$processor = xslt_create();
$parms = array('/_xml' => $rec);
$res = xslt_process($processor, 'arg:/_xml', $xslfile, NULL, $parms);
xslt_free($processor);
$res = preg_replace("'</?html[^>]*>'", '', $res);
echo $res;

?>

For PHP 5 the XSL extension must be used instead of Sablotron XSLT.

yaz_range
yaz_scan_result
YAZ Funkcje


Returns Scan Response result

yaz_record
yaz_scan
YAZ Funkcje
PHP Manual

yaz_scan_result

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_scan_result — Returns Scan Response result

Opis

array yaz_scan_result ( resource $id [, array &$result ] )

yaz_scan_result() returns terms and associated information as received from the server in the last performed yaz_scan().

Parametry

id

The connection resource returned by yaz_connect().

result

If given, this array will be modified to hold additional information taken from the Scan Response:

  • number - Number of entries returned

  • stepsize - Step size

  • position - Position of term

  • status - Scan status

Zwracane wartości

Returns an array (0..n-1) where n is the number of terms returned. Each value is a pair where the first item is the term, and the second item is the result-count.

yaz_record
yaz_scan
YAZ Funkcje


Prepares for a scan

yaz_scan_result
yaz_schema
YAZ Funkcje
PHP Manual

yaz_scan

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_scan — Prepares for a scan

Opis

void yaz_scan ( resource $id , string $type , string $startterm [, array $flags ] )

This function prepares for a Z39.50 Scan Request on the specified connection.

To actually transfer the Scan Request to the server and receive the Scan Response, yaz_wait() must be called. Upon completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.

Parametry

id

The connection resource returned by yaz_connect().

type

Currently only type rpn is supported.

startterm

Starting term point for the scan.

The form in which the starting term is specified is given by parameter type.

The syntax this parameter is similar to the RPN query as described in yaz_search(). It consists of zero or more @attr-operator specifications, then followed by exactly one token.

flags

This optional parameter specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags array: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size).

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 PHP function that scans titles

<?php
function scan_titles($id, $startterm)
{
  yaz_scan($id, "rpn", "@attr 1=4 " . $startterm);
  yaz_wait();
  $errno = yaz_errno($id);
  if ($errno == 0) {
    $ar = yaz_scan_result($id, $options);
    echo 'Scan ok; ';
    foreach ($options as $key => $val) {
      echo "$key = $val &nbsp;";
    }
    echo '<br /><table>';
    while (list($key, list($k, $term, $tcount)) = each($ar)) {
      if (empty($k)) continue;
      echo "<tr><td>$term</td><td>$tcount</td></tr>";
    }
    echo '</table>';
  } else {
    echo "Scan failed. Error: " . yaz_error($id) . "<br />";
  }
}
?>

yaz_scan_result
yaz_schema
YAZ Funkcje


Specifies schema for retrieval

yaz_scan
yaz_search
YAZ Funkcje
PHP Manual

yaz_schema

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

yaz_schema — Specifies schema for retrieval

Opis

void yaz_schema ( resource $id , string $schema )

yaz_schema() specifies the schema for retrieval.

This function should be called before yaz_search() or yaz_present().

Parametry

id

The connection resource returned by yaz_connect().

schema

Must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.13.4) or as one of the known registered schemas: GILS-schema, Holdings, Zthes, ...

Zwracane wartości

Nie jest zwracana żadna wartość.

yaz_scan
yaz_search
YAZ Funkcje


Prepares for a search

yaz_schema
yaz_set_option
YAZ Funkcje
PHP Manual

yaz_search

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_search — Prepares for a search

Opis

bool yaz_search ( resource $id , string $type , string $query )

yaz_search() prepares for a search on the given connection.

Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.

Parametry

id

The connection resource returned by yaz_connect().

type

This parameter represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation.

query

The RPN query is a textual representation of the Type-1 query as defined by the Z39.50 standard. However, in the text representation as used by YAZ a prefix notation is used, that is the operator precedes the operands. The query string is a sequence of tokens where white space is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.

RPN Operators
Construct | Description
@and query1 query2 | intersection of query1 and query2
@or query1 query2 | union of query1 and query2
@not query1 query2 | query1 and not query2
@set name | result set reference
@attrset set query | specifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query
@attr [set] type=value query | applies attribute to query. The type and value are integers specifying the attribute-type and attribute-value respectively. The set, if given, specifies the attribute-set.

You can find information about attributes at the » Z39.50 Maintenance Agency site.

Informacja:

If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Query Examples

You can search for simple terms, like this:

computer
which matches documents where "computer" occur. No attributes are specified.

The query

"knuth donald"
matches documents where "knuth donald" occur (provided that the server supports phrase search).

This query applies two attributes for the same phrase.

@attr 1=1003 @attr 4=1 "knuth donald"
First attribute is type 1 (Bib-1 use), attribute value is 1003 (Author). Second attribute has is type 4 (structure), value 1 (phrase), so this should match documents where Donald Knuth is author.

The query

@and @or a b @not @or c d e
would in infix notation look like (a or b) and ((c or d) not e).

Another, more complex, one:

@attrset gils @and @attr 1=4 art @attr 1=2000 company
The query as a whole uses the GILS attributeset. The query matches documents where art occur in the title (GILS,BIB-1) and in which company occur as Distributor (GILS).

yaz_schema
yaz_set_option
YAZ Funkcje


Sets one or more options for connection

yaz_search
yaz_sort
YAZ Funkcje
PHP Manual

yaz_set_option

(PECL yaz >= 0.9.0)

yaz_set_option — Sets one or more options for connection

Opis

void yaz_set_option ( resource $id , string $name , string $value )
void yaz_set_option ( resource $id , array $options )

Sets one or more options on the given connection.

Parametry

id

The connection resource returned by yaz_connect().

name or options

May be either a string or an array.

If given as a string, this will be the name of the option to set. You'll need to give it's value.

If given as an array, this will be an associative array (option name => option value).

PHP/YAZ Connection Options
Name | Description
implementationName | implementation name of server
implementationVersion | implementation version of server
implementationId | implementation ID of server
schema | schema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema()
preferredRecordSyntax | record syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax()
start | offset for first record to be retrieved via yaz_search() or yaz_present(). First record is numbered has a start value of 0. Second record has start value 1. Setting this option in combination with option count has the same effect as calling yaz_range() except that records are numbered from 1 in yaz_range()
count | maximum number of records to be retrieved via yaz_search() or yaz_present().
elementSetName | element-set-name for retrieval. Setting this option is equivalent to calling yaz_element().
value

The new value of the option. Use this only if the previous argument is a string.

Zwracane wartości

Nie jest zwracana żadna wartość.

yaz_search
yaz_sort
YAZ Funkcje


Sets sorting criteria

yaz_set_option
yaz_syntax
YAZ Funkcje
PHP Manual

yaz_sort

(PHP 4 >= 4.0.7, PECL yaz >= 0.9.0)

yaz_sort — Sets sorting criteria

Opis

void yaz_sort ( resource $id , string $criteria )

This function sets sorting criteria and enables Z39.50 Sort.

Call this function before yaz_search(). Using this function alone does not have any effect. When used in conjunction with yaz_search(), a Z39.50 Sort will be sent after a search response has been received and before any records are retrieved with Z39.50 Present (yaz_present().

Parametry

id

The connection resource returned by yaz_connect().

criteria

A string that takes the form field1 flags1 field2 flags2 where field1 specifies the primary attributes for sort, field2 seconds, etc..

The field specifies either a numerical attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field may specify a plain string criteria (e.g. title. The flags is a sequence of the following characters which may not be separated by any white space.

Sort Flags
a

Sort ascending

d

Sort descending

i

Case insensitive sorting

s

Case sensitive sorting

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Sort Criterias

To sort on Bib1 attribute title, case insensitive, and ascending you would use the following sort criteria:

1=4 ia

If the secondary sorting criteria should be author, case sensitive and ascending you would use:

1=4 ia 1=1003 sa

yaz_set_option
yaz_syntax
YAZ Funkcje


Specifies the preferred record syntax for retrieval

yaz_sort
yaz_wait
YAZ Funkcje
PHP Manual

yaz_syntax

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_syntax — Specifies the preferred record syntax for retrieval

Opis

void yaz_syntax ( resource $id , string $syntax )

yaz_syntax() specifies the preferred record syntax for retrieval

This function should be called before yaz_search() or yaz_present().

Parametry

id

The connection resource returned by yaz_connect().

syntax

The syntax must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.5.10) or as one of the known registered record syntaxes (sutrs, usmarc, grs1, xml, etc.).

Zwracane wartości

Nie jest zwracana żadna wartość.

yaz_sort
yaz_wait
YAZ Funkcje


Wait for Z39.50 requests to complete

yaz_syntax
YP/NIS
YAZ Funkcje
PHP Manual

yaz_wait

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_wait — Wait for Z39.50 requests to complete

Opis

mixed yaz_wait ([ array &$options ] )

This function carries out networked (blocked) activity for outstanding
requests which have been prepared by the functions
yaz_connect(), yaz_search(),
yaz_present(), yaz_scan() and
yaz_itemorder().

yaz_wait() returns when all servers have either completed all requests or aborted (in case of errors).

Parametry

options

An associative array of options:

timeout

Sets timeout in seconds. If a server has not responded within the timeout it is considered dead and yaz_wait() returns. The default value for timeout is 15 seconds.

event

A boolean.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. In event mode, returns resource lub FALSE w przypadku niepowodzenia.

yaz_syntax
YP/NIS
YAZ Funkcje


YP/NIS

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • YP/NIS Funkcje
    • yp_all — Traverse the map and call a function on each entry
    • yp_cat — Return an array containing the entire map
    • yp_err_string — Returns the error string associated with the given error code
    • yp_errno — Returns the error code of the previous operation
    • yp_first — Returns the first key-value pair from the named map
    • yp_get_default_domain — Fetches the machine's default NIS domain
    • yp_master — Returns the machine name of the master NIS server for a map
    • yp_match — Returns the matched line
    • yp_next — Returns the next key-value pair in the named map
    • yp_order — Returns the order number for a map
yaz_wait
Wstęp
Inne serwisy


Wstęp

NIS (formerly called Yellow Pages) allows network management of important administrative files (e.g. the password file). For more information refer to the NIS manpage and » The Linux NIS(YP)/NYS/NIS+ HOWTO. There is also a book called » Managing NFS and NIS by Hal Stern.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

YP/NIS
Instalacja/Konfiguracja
YP/NIS


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
YP/NIS


Wymagania

None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/yp

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

YPERR_ACCESS (integer)
access violation (this has only been added recently and is only available from PECL SVN for now)
YPERR_BADARGS (integer)
The function arguments are bad
YPERR_BADDB (integer)
YP database is bad
YPERR_BUSY (integer)
Database busy
YPERR_DOMAIN (integer)
cannot bind to server in this domain
YPERR_KEY (integer)
no such key in map
YPERR_MAP (integer)
no such map in server's domain
YPERR_NODOM (integer)
Local domain name not set
YPERR_NOMORE (integer)
No more records in map database
YPERR_PMAP (integer)
Can't communicate with portmapper
YPERR_RESRC (integer)
resource allocation failure
YPERR_RPC (integer)
RPC failure - domain has been unbound
YPERR_YPBIND (integer)
Can't communicate with ypbind
YPERR_YPERR (integer)
internal yp server or client error
YPERR_YPSERV (integer)
Can't communicate with ypserv
YPERR_VERS (integer)
YP version mismatch
Typy zasobów
YP/NIS Funkcje
YP/NIS


YP/NIS Funkcje

Spis treści

  • yp_all — Traverse the map and call a function on each entry
  • yp_cat — Return an array containing the entire map
  • yp_err_string — Returns the error string associated with the given error code
  • yp_errno — Returns the error code of the previous operation
  • yp_first — Returns the first key-value pair from the named map
  • yp_get_default_domain — Fetches the machine's default NIS domain
  • yp_master — Returns the machine name of the master NIS server for a map
  • yp_match — Returns the matched line
  • yp_next — Returns the next key-value pair in the named map
  • yp_order — Returns the order number for a map
Stałe predefiniowane
yp_all
YP/NIS


Traverse the map and call a function on each entry

YP/NIS Funkcje
yp_cat
YP/NIS Funkcje
PHP Manual

yp_all

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

yp_all — Traverse the map and call a function on each entry

Opis

void yp_all ( string $domain , string $map , string $callback )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

domain

The NIS domain name.

map

The NIS map.

callback

Zwracane wartości

Nie jest zwracana żadna wartość.

YP/NIS Funkcje
yp_cat
YP/NIS Funkcje


Return an array containing the entire map

yp_all
yp_err_string
YP/NIS Funkcje
PHP Manual

yp_cat

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

yp_cat — Return an array containing the entire map

Opis

array yp_cat ( string $domain , string $map )

Returns all map entries.

Parametry

domain

The NIS domain name.

map

The NIS map.

Zwracane wartości

Returns an array of all map entries, the maps key values as array indices and the maps entries as array data.

yp_all
yp_err_string
YP/NIS Funkcje


Returns the error string associated with the given error code

yp_cat
yp_errno
YP/NIS Funkcje
PHP Manual

yp_err_string

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

yp_err_string — Returns the error string associated with the given error code

Opis

string yp_err_string ( int $errorcode )

Returns the error message associated with the given error code. Useful to indicate what exactly went wrong.

Parametry

errorcode

The error code.

Zwracane wartości

Returns the error message, as a string.

Przykłady

Przykład #1 Example for NIS errors

<?php
echo "Error: " . yp_err_string(yp_errno());
?>

Zobacz też:

  • yp_errno() - Returns the error code of the previous operation

yp_cat
yp_errno
YP/NIS Funkcje


Returns the error code of the previous operation

yp_err_string
yp_first
YP/NIS Funkcje
PHP Manual

yp_errno

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5)

yp_errno — Returns the error code of the previous operation

Opis

int yp_errno ( void )

Returns the error code of the previous operation.

Zwracane wartości

Returns one of the YPERR_XXX error constants.

Zobacz też:

  • yp_err_string() - Returns the error string associated with the given error code

yp_err_string
yp_first
YP/NIS Funkcje


Returns the first key-value pair from the named map

yp_errno
yp_get_default_domain
YP/NIS Funkcje
PHP Manual

yp_first

(PHP 4, PHP 5 <= 5.0.5)

yp_first — Returns the first key-value pair from the named map

Opis

array yp_first ( string $domain , string $map )

Gets the first key-value pair from the named map in the named domain.

Parametry

domain

The NIS domain name.

map

The NIS map.

Zwracane wartości

Returns the first key-value pair as an array on success, or FALSE on errors.

Przykłady

Przykład #1 Example for the NIS first

<?php
$entry = yp_first($domain, "passwd.byname");

$key = key($entry);
$value = $entry[$key];

echo "First entry in this map has key " . $key . " and value " . $value;
?>

Zobacz też:

  • yp_next() - Returns the next key-value pair in the named map
  • yp_get_default_domain() - Fetches the machine's default NIS domain

yp_errno
yp_get_default_domain
YP/NIS Funkcje


Fetches the machine's default NIS domain

yp_first
yp_master
YP/NIS Funkcje
PHP Manual

yp_get_default_domain

(PHP 4, PHP 5 <= 5.0.5)

yp_get_default_domain — Fetches the machine's default NIS domain

Opis

string yp_get_default_domain ( void )

Returns the default domain of the node. Can be used as the domain parameter for successive NIS calls.

A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.

Zwracane wartości

Returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.

Przykłady

Przykład #1 Example for the default domain

<?php
$domain = yp_get_default_domain();
echo "Default NIS domain is: " . $domain;
?>

yp_first
yp_master
YP/NIS Funkcje


Returns the machine name of the master NIS server for a map

yp_get_default_domain
yp_match
YP/NIS Funkcje
PHP Manual

yp_master

(PHP 4, PHP 5 <= 5.0.5)

yp_master — Returns the machine name of the master NIS server for a map

Opis

string yp_master ( string $domain , string $map )

Returns the machine name of the master NIS server for a map.

Parametry

domain

The NIS domain name.

map

The NIS map.

Zwracane wartości

Przykłady

Przykład #1 Example for the NIS master

<?php
$number = yp_master($domain, $mapname);
echo "Master for this map is: " . $master;
?>

Zobacz też:

  • yp_get_default_domain() - Fetches the machine's default NIS domain

yp_get_default_domain
yp_match
YP/NIS Funkcje


Returns the matched line

yp_master
yp_next
YP/NIS Funkcje
PHP Manual

yp_match

(PHP 4, PHP 5 <= 5.0.5)

yp_match — Returns the matched line

Opis

string yp_match ( string $domain , string $map , string $key )

Returns the value associated with the passed key out of the specified map.

Parametry

domain

The NIS domain name.

map

The NIS map.

key

This key must be exact.

Zwracane wartości

Returns the value, or FALSE on errors.

Przykłady

Przykład #1 Example for NIS match

<?php
$entry = yp_match($domain, "passwd.byname", "joe");
echo "Matched entry is: " . $entry;
?>

Powyższy przykład wyświetli coś podobnego do:

joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash

Zobacz też:

  • yp_get_default_domain() - Fetches the machine's default NIS domain

yp_master
yp_next
YP/NIS Funkcje


Returns the next key-value pair in the named map

yp_match
yp_order
YP/NIS Funkcje
PHP Manual

yp_next

(PHP 4, PHP 5 <= 5.0.5)

yp_next — Returns the next key-value pair in the named map

Opis

array yp_next ( string $domain , string $map , string $key )

Returns the next key-value pair in the named map after the specified key.

Parametry

domain

map

key

Zwracane wartości

Returns the next key-value pair as an array, or FALSE on errors.

Przykłady

Przykład #1 Example for NIS next

<?php
$entry = yp_next($domain, "passwd.byname", "joe");

if (!$entry) {
    echo "No more entries found\n";
    echo "<!--" . yp_errno() . ": " . yp_err_string() . "-->";
}

$key = key($entry);

echo "The next entry after joe has key " . $key
      . " and value " . $entry[$key];
?>

Zobacz też:

  • yp_first() - Returns the first key-value pair from the named map
  • yp_get_default_domain() - Fetches the machine's default NIS domain

yp_match
yp_order
YP/NIS Funkcje


Returns the order number for a map

yp_next
Systemy wyszukiwania informacji
YP/NIS Funkcje
PHP Manual

yp_order

(PHP 4, PHP 5 <= 5.0.5)

yp_order — Returns the order number for a map

Opis

int yp_order ( string $domain , string $map )

Gets the order number for a map.

Parametry

domain

map

Zwracane wartości

Returns the order number for a map or FALSE on error.

Przykłady

Przykład #1 Example for the NIS order

<?php
    $number = yp_order($domain, $mapname);
    echo "Order number for this map is: " . $number;
?>

Zobacz też:

  • yp_get_default_domain() - Fetches the machine's default NIS domain

yp_next
Systemy wyszukiwania informacji
YP/NIS Funkcje


Systemy wyszukiwania informacji

  • mnoGoSearch
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • mnoGoSearch Funkcje
  • Solr — Apache Solr
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Solr Funkcje
    • Przykłady
    • SolrUtils — The SolrUtils class
    • SolrInputDocument — The SolrInputDocument class
    • SolrDocument — The SolrDocument class
    • SolrDocumentField — The SolrDocumentField class
    • SolrObject — The SolrObject class
    • SolrClient — The SolrClient class
    • SolrResponse — The SolrResponse class
    • SolrQueryResponse — The SolrQueryResponse class
    • SolrUpdateResponse — The SolrUpdateResponse class
    • SolrPingResponse — The SolrPingResponse class
    • SolrGenericResponse — The SolrGenericResponse class
    • SolrParams — The SolrParams class
    • SolrModifiableParams — The SolrModifiableParams class
    • SolrQuery — The SolrQuery class
    • SolrException — The SolrException class
    • SolrClientException — The SolrClientException class
    • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalOperationException — The SolrIllegalOperationException class
  • Sphinx — Sphinx Client
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • SphinxClient — The SphinxClient class
  • Swish — Swish Indexing
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Swish Funkcje
yp_order
mnoGoSearch
Opis funkcji


mnoGoSearch

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • mnoGoSearch Funkcje
    • udm_add_search_limit — Add various search limits
    • udm_alloc_agent_array — Allocate mnoGoSearch session
    • udm_alloc_agent — Allocate mnoGoSearch session
    • udm_api_version — Get mnoGoSearch API version
    • udm_cat_list — Get all the categories on the same level with the current one
    • udm_cat_path — Get the path to the current category
    • udm_check_charset — Check if the given charset is known to mnogosearch
    • udm_check_stored — Check connection to stored
    • udm_clear_search_limits — Clear all mnoGoSearch search restrictions
    • udm_close_stored — Close connection to stored
    • udm_crc32 — Return CRC32 checksum of given string
    • udm_errno — Get mnoGoSearch error number
    • udm_error — Get mnoGoSearch error message
    • udm_find — Perform search
    • udm_free_agent — Free mnoGoSearch session
    • udm_free_ispell_data — Free memory allocated for ispell data
    • udm_free_res — Free mnoGoSearch result
    • udm_get_doc_count — Get total number of documents in database
    • udm_get_res_field — Fetch a result field
    • udm_get_res_param — Get mnoGoSearch result parameters
    • udm_hash32 — Return Hash32 checksum of gived string
    • udm_load_ispell_data — Load ispell data
    • udm_open_stored — Open connection to stored
    • udm_set_agent_param — Set mnoGoSearch agent session parameters
Systemy wyszukiwania informacji
Wstęp
Systemy wyszukiwania informacji


Wstęp

These functions allow you to access the mnoGoSearch (former UdmSearch) free search engine. mnoGoSearch is a full-featured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has a number of unique features, which makes it appropriate for a wide range of applications from search within your site to a specialized search system such as cooking recipes or newspaper search, FTP archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is an indexing mechanism (indexer). The purpose of the indexer is to walk through HTTP, FTP, NEWS servers or local files, recursively grabbing all the documents and storing meta-data about that documents in an SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data is collected by the indexer for later use in a search process. The search is performed via Web interface. C, CGI, PHP and Perl search front ends are included.

More information about mnoGoSearch can be found at » http://www.mnogosearch.org/.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

mnoGoSearch
Instalacja/Konfiguracja
mnoGoSearch


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
mnoGoSearch


Wymagania

Download mnoGosearch from » http://www.mnogosearch.org/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/mnogosearch.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Informacja:

PHP contains built-in MySQL access library, which can be used to access MySQL. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic MySQL libraries. Thus, if you use mnoGoSearch with MySQL, during PHP configuration you have to indicate the directory of your MySQL installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch --with-mysql=/usr .

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

UDM_FIELD_URLID (integer)
UDM_FIELD_URL (integer)
UDM_FIELD_CONTENT (integer)
UDM_FIELD_TITLE (integer)
UDM_FIELD_KEYWORDS (integer)
UDM_FIELD_DESC (integer)
UDM_FIELD_DESCRIPTION (integer)
UDM_FIELD_TEXT (integer)
UDM_FIELD_SIZE (integer)
UDM_FIELD_RATING (integer)
UDM_FIELD_SCORE (integer)
UDM_FIELD_MODIFIED (integer)
UDM_FIELD_ORDER (integer)
UDM_FIELD_CRC (integer)
UDM_FIELD_CATEGORY (integer)
UDM_FIELD_LANG (integer)
UDM_FIELD_CHARSET (integer)
UDM_PARAM_PAGE_SIZE (integer)
UDM_PARAM_PAGE_NUM (integer)
UDM_PARAM_SEARCH_MODE (integer)
UDM_PARAM_CACHE_MODE (integer)
UDM_PARAM_TRACK_MODE (integer)
UDM_PARAM_PHRASE_MODE (integer)
UDM_PARAM_CHARSET (integer)
UDM_PARAM_LOCAL_CHARSET (integer)
UDM_PARAM_BROWSER_CHARSET (integer)
UDM_PARAM_STOPTABLE (integer)
UDM_PARAM_STOP_TABLE (integer)
UDM_PARAM_STOPFILE (integer)
UDM_PARAM_STOP_FILE (integer)
UDM_PARAM_WEIGHT_FACTOR (integer)
UDM_PARAM_WORD_MATCH (integer)
UDM_PARAM_MAX_WORD_LEN (integer)
UDM_PARAM_MAX_WORDLEN (integer)
UDM_PARAM_MIN_WORD_LEN (integer)
UDM_PARAM_MIN_WORDLEN (integer)
UDM_PARAM_ISPELL_PREFIXES (integer)
UDM_PARAM_ISPELL_PREFIX (integer)
UDM_PARAM_PREFIXES (integer)
UDM_PARAM_PREFIX (integer)
UDM_PARAM_CROSS_WORDS (integer)
UDM_PARAM_CROSSWORDS (integer)
UDM_PARAM_VARDIR (integer)
UDM_PARAM_DATADIR (integer)
UDM_PARAM_HLBEG (integer)
UDM_PARAM_HLEND (integer)
UDM_PARAM_SYNONYM (integer)
UDM_PARAM_SEARCHD (integer)
UDM_PARAM_QSTRING (integer)
UDM_PARAM_REMOTE_ADDR (integer)
UDM_LIMIT_CAT (integer)
UDM_LIMIT_URL (integer)
UDM_LIMIT_TAG (integer)
UDM_LIMIT_LANG (integer)
UDM_LIMIT_DATE (integer)
UDM_PARAM_FOUND (integer)
UDM_PARAM_NUM_ROWS (integer)
UDM_PARAM_WORDINFO (integer)
UDM_PARAM_WORD_INFO (integer)
UDM_PARAM_SEARCHTIME (integer)
UDM_PARAM_SEARCH_TIME (integer)
UDM_PARAM_FIRST_DOC (integer)
UDM_PARAM_LAST_DOC (integer)
UDM_MODE_ALL (integer)
UDM_MODE_ANY (integer)
UDM_MODE_BOOL (integer)
UDM_MODE_PHRASE (integer)
UDM_CACHE_ENABLED (integer)
UDM_CACHE_DISABLED (integer)
UDM_TRACK_ENABLED (integer)
UDM_TRACK_DISABLED (integer)
UDM_PHRASE_ENABLED (integer)
UDM_PHRASE_DISABLED (integer)
UDM_CROSS_WORDS_ENABLED (integer)
UDM_CROSSWORDS_ENABLED (integer)
UDM_CROSS_WORDS_DISABLED (integer)
UDM_CROSSWORDS_DISABLED (integer)
UDM_PREFIXES_ENABLED (integer)
UDM_PREFIX_ENABLED (integer)
UDM_ISPELL_PREFIXES_ENABLED (integer)
UDM_ISPELL_PREFIX_ENABLED (integer)
UDM_PREFIXES_DISABLED (integer)
UDM_PREFIX_DISABLED (integer)
UDM_ISPELL_PREFIXES_DISABLED (integer)
UDM_ISPELL_PREFIX_DISABLED (integer)
UDM_ISPELL_TYPE_AFFIX (integer)
UDM_ISPELL_TYPE_SPELL (integer)
UDM_ISPELL_TYPE_DB (integer)
UDM_ISPELL_TYPE_SERVER (integer)
UDM_MATCH_WORD (integer)
UDM_MATCH_BEGIN (integer)
UDM_MATCH_SUBSTR (integer)
UDM_MATCH_END (integer)
Typy zasobów
mnoGoSearch Funkcje
mnoGoSearch


mnoGoSearch Funkcje

Spis treści

  • udm_add_search_limit — Add various search limits
  • udm_alloc_agent_array — Allocate mnoGoSearch session
  • udm_alloc_agent — Allocate mnoGoSearch session
  • udm_api_version — Get mnoGoSearch API version
  • udm_cat_list — Get all the categories on the same level with the current one
  • udm_cat_path — Get the path to the current category
  • udm_check_charset — Check if the given charset is known to mnogosearch
  • udm_check_stored — Check connection to stored
  • udm_clear_search_limits — Clear all mnoGoSearch search restrictions
  • udm_close_stored — Close connection to stored
  • udm_crc32 — Return CRC32 checksum of given string
  • udm_errno — Get mnoGoSearch error number
  • udm_error — Get mnoGoSearch error message
  • udm_find — Perform search
  • udm_free_agent — Free mnoGoSearch session
  • udm_free_ispell_data — Free memory allocated for ispell data
  • udm_free_res — Free mnoGoSearch result
  • udm_get_doc_count — Get total number of documents in database
  • udm_get_res_field — Fetch a result field
  • udm_get_res_param — Get mnoGoSearch result parameters
  • udm_hash32 — Return Hash32 checksum of gived string
  • udm_load_ispell_data — Load ispell data
  • udm_open_stored — Open connection to stored
  • udm_set_agent_param — Set mnoGoSearch agent session parameters
Stałe predefiniowane
udm_add_search_limit
mnoGoSearch


Add various search limits

mnoGoSearch Funkcje
udm_alloc_agent_array
mnoGoSearch Funkcje
PHP Manual

udm_add_search_limit

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_add_search_limit — Add various search limits

Opis

bool udm_add_search_limit ( resource $agent , int $var , string $val )

udm_add_search_limit() adds search restrictions.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

var

Defines the parameter, indicating limits. Possible var values:

  • UDM_LIMIT_URL - defines document URL limitations to limit the search through subsection of the database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://www.example.___/catalog may stand for http://www.example.com/catalog and http://www.example.net/catalog.
  • UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the search will be made among both of the tags.
  • UDM_LIMIT_LANG - defines document language limitations.
  • UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you can have one category inside another and so on. You have to use two characters for each level. Use a hex number going from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to search for sites under that category then you pass it cat=010201 in the URL.

  • UDM_LIMIT_DATE - defines limitation by date the document was modified.

    Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:

    <?php
    udm_add_search_limit    ($udm, UDM_LIMIT_DATE, "&lt;908012006");
    ?>

    If > character is used, then the search will be restricted to those documents having a modification date greater than entered, if <, then smaller.

val

Defines the value of the current parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

mnoGoSearch Funkcje
udm_alloc_agent_array
mnoGoSearch Funkcje


Allocate mnoGoSearch session

udm_add_search_limit
udm_alloc_agent
mnoGoSearch Funkcje
PHP Manual

udm_alloc_agent_array

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_alloc_agent_array — Allocate mnoGoSearch session

Opis

resource udm_alloc_agent_array ( array $databases )

udm_alloc_agent_array() will create an agent with multiple database connections.

Parametry

databases

The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().

Zwracane wartości

Returns a resource link identifier on success lub FALSE w przypadku niepowodzenia.

Zobacz też:

  • udm_alloc_agent() - Allocate mnoGoSearch session

udm_add_search_limit
udm_alloc_agent
mnoGoSearch Funkcje


Allocate mnoGoSearch session

udm_alloc_agent_array
udm_api_version
mnoGoSearch Funkcje
PHP Manual

udm_alloc_agent

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_alloc_agent — Allocate mnoGoSearch session

Opis

resource udm_alloc_agent ( string $dbaddr [, string $dbmode ] )

Allocate a mnoGoSearch session.

Parametry

dbaddr

dbaddr - URL-style database description, with options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format for dbaddr: DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/. Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, and ibase. Actually, it does not matter for native libraries support, but ODBC users should specify one of the supported values. If your database type is not supported, you may use unknown instead.

dbmode

dbmode - You may select the SQL database mode of words storage. Possible values of dbmode are: single, multi, crc, or crc-multi. When single is specified, all words are stored in the same table. If multi is selected, words will be located in different tables depending of their lengths. "multi" mode is usually faster, but requires more tables in the database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorithm instead of words. This mode requires less disk space and it is faster comparing with "single" and "multi" modes. crc-multi uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like in "multi" mode.

Informacja:

dbaddr and dbmode must match those used during indexing.

Zwracane wartości

Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.

Notatki

Informacja:

In fact this function does not open a connection to the database and thus does not check the entered login and password. Establishing a connection to the database and login/password verification is done by udm_find().

udm_alloc_agent_array
udm_api_version
mnoGoSearch Funkcje


Get mnoGoSearch API version

udm_alloc_agent
udm_cat_list
mnoGoSearch Funkcje
PHP Manual

udm_api_version

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_api_version — Get mnoGoSearch API version

Opis

int udm_api_version ( void )

Gets the mnoGoSearch API version.

This function allows the user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.

Zwracane wartości

udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.

Przykłady

Przykład #1 udm_api_version() example

<?php
if (udm_api_version() >= 30111) {
    echo  "Total number of URLs in database: " . udm_get_doc_count($udm) . "<br />\n";
}
?>

udm_alloc_agent
udm_cat_list
mnoGoSearch Funkcje


Get all the categories on the same level with the current one

udm_api_version
udm_cat_path
mnoGoSearch Funkcje
PHP Manual

udm_cat_list

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_cat_list — Get all the categories on the same level with the current one

Opis

array udm_cat_list ( resource $agent , string $category )

Gets all the categories on the same level with the current one.

The function can be useful for developing categories tree browser.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

category

Zwracane wartości

Returns an array listing all categories of the same level as the current category in the categories tree.

The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.

$array[0] will contain '020300'
  $array[1] will contain 'Audi'
  $array[2] will contain '020301'
  $array[3] will contain 'BMW'
  $array[4] will contain '020302'
  $array[5] will contain 'Opel'
  ...
 etc.

Przykłady

Following is an example of displaying links of the current level in format:

Audi
  BMW
  Opel
  ...

Przykład #1 udm_cat_list()example

<?php
 $cat_list_arr = udm_cat_list($udm_agent, $cat);
 $cat_list = '';
 for ($i=0; $i<count($cat_list_arr); $i+=2) {
    $path = $cat_list_arr[$i];
    $name = $cat_list_arr[$i+1];
    $cat_list .= "<a href=\"$_SERVER[PHP_SELF]?cat=$path\">$name</a><br />";
 }
?>

Zobacz też:

  • udm_cat_path() - Get the path to the current category

udm_api_version
udm_cat_path
mnoGoSearch Funkcje


Get the path to the current category

udm_cat_list
udm_check_charset
mnoGoSearch Funkcje
PHP Manual

udm_cat_path

(PHP 4 >= 4.0.6, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_cat_path — Get the path to the current category

Opis

array udm_cat_path ( resource $agent , string $category )

Returns an array describing the path in the categories tree from the tree root to the current one, specified by category.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

category

Zwracane wartości

The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.

For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:

 $array[0] will contain ''
 $array[1] will contain 'Root'
 $array[2] will contain '02'
 $array[3] will contain 'Sport'
 $array[4] will contain '0203'
 $array[5] will contain 'Auto'
 $array[4] will contain '02031D'
 $array[5] will contain 'Ferrari'

Przykłady

Przykład #1 Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'

<?php
  $cat_path_arr = udm_cat_path($udm_agent, $cat);
  $cat_path = '';
  for ($i=0; $i<count($cat_path_arr); $i+=2) {
    $path = $cat_path_arr[$i];
    $name = $cat_path_arr[$i+1];
    $cat_path .= " > <a href=\"$_SERVER[PHP_SELF]?cat=$path\">$name</a> ";
  }
?>

Zobacz też:

  • udm_cat_list() - Get all the categories on the same level with the current one

udm_cat_list
udm_check_charset
mnoGoSearch Funkcje


Check if the given charset is known to mnogosearch

udm_cat_path
udm_check_stored
mnoGoSearch Funkcje
PHP Manual

udm_check_charset

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_check_charset — Check if the given charset is known to mnogosearch

Opis

bool udm_check_charset ( resource $agent , string $charset )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

udm_cat_path
udm_check_stored
mnoGoSearch Funkcje


Check connection to stored

udm_check_charset
udm_clear_search_limits
mnoGoSearch Funkcje
PHP Manual

udm_check_stored

(PHP 4 >= 4.2.0)

udm_check_stored — Check connection to stored

Opis

int udm_check_stored ( resource $agent , int $link , string $doc_id )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

udm_check_charset
udm_clear_search_limits
mnoGoSearch Funkcje


Clear all mnoGoSearch search restrictions

udm_check_stored
udm_close_stored
mnoGoSearch Funkcje
PHP Manual

udm_clear_search_limits

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_clear_search_limits — Clear all mnoGoSearch search restrictions

Opis

bool udm_clear_search_limits ( resource $agent )

udm_clear_search_limits() resets defined search limitations.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

Zwracane wartości

Returns TRUE.

Zobacz też:

  • udm_add_search_limit() - Add various search limits

udm_check_stored
udm_close_stored
mnoGoSearch Funkcje


Close connection to stored

udm_clear_search_limits
udm_crc32
mnoGoSearch Funkcje
PHP Manual

udm_close_stored

(PHP 4 >= 4.2.0)

udm_close_stored — Close connection to stored

Opis

int udm_close_stored ( resource $agent , int $link )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

udm_clear_search_limits
udm_crc32
mnoGoSearch Funkcje


Return CRC32 checksum of given string

udm_close_stored
udm_errno
mnoGoSearch Funkcje
PHP Manual

udm_crc32

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_crc32 — Return CRC32 checksum of given string

Opis

int udm_crc32 ( resource $agent , string $str )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

udm_close_stored
udm_errno
mnoGoSearch Funkcje


Get mnoGoSearch error number

udm_crc32
udm_error
mnoGoSearch Funkcje
PHP Manual

udm_errno

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_errno — Get mnoGoSearch error number

Opis

int udm_errno ( resource $agent )

Receiving numeric agent error code.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

Zwracane wartości

Returns the mnoGoSearch error number, zero if no error.

udm_crc32
udm_error
mnoGoSearch Funkcje


Get mnoGoSearch error message

udm_errno
udm_find
mnoGoSearch Funkcje
PHP Manual

udm_error

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_error — Get mnoGoSearch error message

Opis

string udm_error ( resource $agent )

Gets the agent error message.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

Zwracane wartości

udm_error() returns mnoGoSearch error message, empty string if no error.

udm_errno
udm_find
mnoGoSearch Funkcje


Perform search

udm_error
udm_free_agent
mnoGoSearch Funkcje
PHP Manual

udm_find

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_find — Perform search

Opis

resource udm_find ( resource $agent , string $query )

Performs a search.

The search itself. The first argument - session, the next one - query itself. To find something just type words you want to find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc". Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select "bool" match mode in the search from.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

query

mnoGoSearch understands the following boolean operators:

& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".

| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".

~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!

() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is simple and powerful at the same time. Just consider query as usual boolean expression.

Zwracane wartości

Returns a result link identifier on success lub FALSE w przypadku niepowodzenia.

udm_error
udm_free_agent
mnoGoSearch Funkcje


Free mnoGoSearch session

udm_find
udm_free_ispell_data
mnoGoSearch Funkcje
PHP Manual

udm_free_agent

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_free_agent — Free mnoGoSearch session

Opis

int udm_free_agent ( resource $agent )

Freeing up memory allocated for agent session.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

udm_find
udm_free_ispell_data
mnoGoSearch Funkcje


Free memory allocated for ispell data

udm_free_agent
udm_free_res
mnoGoSearch Funkcje
PHP Manual

udm_free_ispell_data

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_free_ispell_data — Free memory allocated for ispell data

Opis

bool udm_free_ispell_data ( int $agent )

Frees the memory allocated for ispell data.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

Zwracane wartości

udm_free_ispell_data() always returns TRUE.

Notatki

Informacja:

This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.

udm_free_agent
udm_free_res
mnoGoSearch Funkcje


Free mnoGoSearch result

udm_free_ispell_data
udm_get_doc_count
mnoGoSearch Funkcje
PHP Manual

udm_free_res

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_free_res — Free mnoGoSearch result

Opis

bool udm_free_res ( resource $res )

Freeing up memory allocated for results.

Parametry

res

A link to a result identifier, received after call to udm_find().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

udm_free_ispell_data
udm_get_doc_count
mnoGoSearch Funkcje


Get total number of documents in database

udm_free_res
udm_get_res_field
mnoGoSearch Funkcje
PHP Manual

udm_get_doc_count

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_get_doc_count — Get total number of documents in database

Opis

int udm_get_doc_count ( resource $agent )

udm_get_doc_count() returns the number of documents in the database.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

Zwracane wartości

Returns the number of documents.

Notatki

Informacja:

This function is supported only in mnoGoSearch 3.1.11 or later.

udm_free_res
udm_get_res_field
mnoGoSearch Funkcje


Fetch a result field

udm_get_doc_count
udm_get_res_param
mnoGoSearch Funkcje
PHP Manual

udm_get_res_field

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_get_res_field — Fetch a result field

Opis

string udm_get_res_field ( resource $res , int $row , int $field )

Fetch a mnoGoSearch result field.

Parametry

res

res - a link to result identifier, received after call to udm_find().

row

row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.

field

field - field identifier, may have the following values:

  • UDM_FIELD_URL - document URL field
  • UDM_FIELD_CONTENT - document Content-type field (for example, text/html).
  • UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).
  • UDM_FIELD_TITLE - document title field.
  • UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).
  • UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).
  • UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).
  • UDM_FIELD_SIZE - document size.
  • UDM_FIELD_URLID - unique URL ID of the link.
  • UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).
  • UDM_FIELD_MODIFIED - last-modified field in unixtime format.
  • UDM_FIELD_ORDER - the number of the current document in set of found documents.
  • UDM_FIELD_CRC - document CRC.

Zwracane wartości

udm_get_res_field() returns result field value on success, FALSE on error.

udm_get_doc_count
udm_get_res_param
mnoGoSearch Funkcje


Get mnoGoSearch result parameters

udm_get_res_field
udm_hash32
mnoGoSearch Funkcje
PHP Manual

udm_get_res_param

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_get_res_param — Get mnoGoSearch result parameters

Opis

string udm_get_res_param ( resource $res , int $param )

Gets the mnoGoSearch result parameters.

Parametry

res

res - a link to result identifier, received after call to udm_find().

param

param - parameter identifier, may have the following values:

  • UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.
  • UDM_PARAM_FOUND - total number of results matching the query.
  • UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"
  • UDM_PARAM_SEARCHTIME - search time in seconds.
  • UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.
  • UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.

Zwracane wartości

udm_get_res_param() returns result parameter value on success, FALSE on error.

udm_get_res_field
udm_hash32
mnoGoSearch Funkcje


Return Hash32 checksum of gived string

udm_get_res_param
udm_load_ispell_data
mnoGoSearch Funkcje
PHP Manual

udm_hash32

(PHP 4 >= 4.3.3, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_hash32 — Return Hash32 checksum of gived string

Opis

int udm_hash32 ( resource $agent , string $str )

udm_hash32() will take a string str and return a quite unique 32-bit hash number from it.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

str

The input string.

Zwracane wartości

Returns a 32-bit hash number.

Zobacz też:

  • udm_alloc_agent() - Allocate mnoGoSearch session

udm_get_res_param
udm_load_ispell_data
mnoGoSearch Funkcje


Load ispell data

udm_hash32
udm_open_stored
mnoGoSearch Funkcje
PHP Manual

udm_load_ispell_data

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_load_ispell_data — Load ispell data

Opis

bool udm_load_ispell_data ( resource $agent , int $var , string $val1 , string $val2 , int $flag )

udm_load_ispell_data() loads ispell data.

After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use UDM_ISPELL_TYPE_SERVER mode.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

var

Indicates the source for ispell data. May have the following values:

  • UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2 are ignored and should be left blank. flag should be equal to 1.

    Informacja:

    flag indicates that after loading ispell data from defined source it should be sorted (it is necessary for correct functioning of ispell). In case of loading ispell data from files there may be several calls to udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if ispell tables are absent, the function will return FALSE and code and error message will be accessible through udm_error() and udm_errno().

  • UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    Przykład #1 udm_load_ispell_data() example

    <?php
    if ((! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'en', '/opt/ispell/en.aff', 0)) ||
        (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'ru', '/opt/ispell/ru.aff', 0)) ||
        (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'en', '/opt/ispell/en.dict', 0)) ||
        (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'ru', '/opt/ispell/ru.dict', 1))) {
        exit;
    }
    ?>

    Informacja:

    flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    <?php
    if ((! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'en', '/opt/ispell/en.aff', 0)) ||
       (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'ru', '/opt/ispell/ru.aff', 0)) ||
       (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'en', '/opt/ispell/en.dict', 0)) ||
       (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'ru', '/opt/ispell/ru.dict', 1))) {
     exit;
     }
    ?>

    Informacja:

    flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag parameter in this case is not needed since ispell data is stored on spellserver already sorted.

    Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default), sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi) list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by omitting loading and sorting all the spell data).

    udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion does not work.

    Informacja:

    This function is available in mnoGoSearch 3.1.12 or later.

    Example:
    <?php
    if (!udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SERVER, '', '', 1)) {
        echo     "Error loading ispell data from server<br />\n";
        exit;
    }
    ?>

The fastest mode is UDM_ISPELL_TYPE_SERVER. UDM_ISPELL_TYPE_TEXT is slower and UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to speed up DB mode in future versions and it is going to be faster than TEXT mode.

val1

val2

flag

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #2 udm_load_ispell_data() example

<?php
if (! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_DB, '', '', 1)) {
  printf("Error #%d: '%s'\n", udm_errno($udm), udm_error($udm));
  exit;
}
?>

udm_hash32
udm_open_stored
mnoGoSearch Funkcje


Open connection to stored

udm_load_ispell_data
udm_set_agent_param
mnoGoSearch Funkcje
PHP Manual

udm_open_stored

(PHP 4 >= 4.2.0)

udm_open_stored — Open connection to stored

Opis

int udm_open_stored ( resource $agent , string $storedaddr )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

udm_load_ispell_data
udm_set_agent_param
mnoGoSearch Funkcje


Set mnoGoSearch agent session parameters

udm_open_stored
Solr
mnoGoSearch Funkcje
PHP Manual

udm_set_agent_param

(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)

udm_set_agent_param — Set mnoGoSearch agent session parameters

Opis

bool udm_set_agent_param ( resource $agent , int $var , string $val )

Defines mnoGoSearch session parameters.

Parametry

agent

A link to Agent, received after call to udm_alloc_agent().

var

The following parameters and their values are available:

  • UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning from 0, with UDM_PARAM_PAGE_SIZE results per page).
  • UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.
  • UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL - boolean search. See udm_find() for details on boolean search.
  • UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.
  • UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search, front-end uses those tables to store query words, a number of found documents and current Unix timestamp in seconds. Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.
  • UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf). Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE). In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning with 3.1.11 phrases are supported in cachemode as well. Examples of phrase search: "Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you need to put double quotes around the phrase
  • UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g. koi8-r, cp1251, ...
  • UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch - while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the module looks for the file in relation to current path, i.e. to the path where the PHP script is executed.)
  • UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.
  • UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title, keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the indexer.conf. Let's imagine that we have these weights:
          URLWeight     1
      BodyWeight    2
      TitleWeight   4
      KeywordWeight 8
      DescWeight    16
    As far as indexer uses bit OR operation for word weights when some word presents several time in the same document, it is possible at search time to detect word appearance in different document parts. Word which appears only in the body will have 00000010 aggregate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight. This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For the given above weights configuration:
           E is a factor for weight 1  (URL Weight bit)
       D is a factor for weight 2  (BodyWeight bit)
       C is a factor for weight 4  (TitleWeight bit)
       B is a factor for weight 8  (KeywordWeight bit)
       A is a factor for weight 16 (DescWeight bit)
    Examples: UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only. UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only. UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and Body. UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:
            Description with factor 15  (F hex)
        Keywords with factor 9
        Title with factor  4
        Body with factor 2
        URL with factor 1
    If UDM_PARAM_WEIGHT_FACTOR variable is omitted, original weight value is taken to sort results. For a given above weight configuration it means that document description has a most big weight 16.
  • UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and other modes since they use word CRC and do not support substring search. Available values: UDM_MATCH_BEGIN - word beginning match; UDM_MATCH_END - word ending match; UDM_MATCH_WORD - whole word match; UDM_MATCH_SUBSTR - word substring match.
  • UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3 characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.
  • UDM_PARAM_ISPELL_PREFIXES - Possible values: UDM_PREFIXES_ENABLED and UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data with udm_load_ispell_data().
  • UDM_PARAM_CROSS_WORDS - enables or disables crosswords support. Possible values: UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED. The crosswords feature allows to assign words between <a href="xxx"> and </a> also to a document this link leads to. It works in SQL database mode and is not supported in built-in database and Cachemode.
  • UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values.

val

Rejestr zmian

Wersja | Opis
4.1.0 | UDM_PARAM_VARDIR was added.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Crosswords are supported only in mnoGoSearch 3.1.11 or later.

udm_open_stored
Solr
mnoGoSearch Funkcje


Apache Solr

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Solr Funkcje
    • solr_get_version — Returns the current version of the Apache Solr extension
  • Przykłady
  • SolrUtils — The SolrUtils class
    • SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars — Escapes a lucene query string
    • SolrUtils::getSolrVersion — Returns the current version of the Solr extension
    • SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string
  • SolrInputDocument — The SolrInputDocument class
    • SolrInputDocument::addField — Adds a field to the document
    • SolrInputDocument::clear — Resets the input document
    • SolrInputDocument::__clone — Creates a copy of a SolrDocument
    • SolrInputDocument::__construct — Constructor
    • SolrInputDocument::deleteField — Removes a field from the document
    • SolrInputDocument::__destruct — Destructor
    • SolrInputDocument::fieldExists — Checks if a field exists
    • SolrInputDocument::getBoost — Retrieves the current boost value for the document
    • SolrInputDocument::getField — Retrieves a field by name
    • SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount — Returns the number of fields in the document
    • SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document
    • SolrInputDocument::merge — Merges one input document into another
    • SolrInputDocument::reset — This is an alias of SolrInputDocument::clear
    • SolrInputDocument::setBoost — Sets the boost value for this document
    • SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field
    • SolrInputDocument::sort — Sorts the fields within the document
    • SolrInputDocument::toArray — Returns an array representation of the input document
  • SolrDocument — The SolrDocument class
    • SolrDocument::addField — Adds a field to the document
    • SolrDocument::clear — Drops all the fields in the document
    • SolrDocument::__clone — Creates a copy of a SolrDocument object
    • SolrDocument::__construct — Constructor
    • SolrDocument::current — Retrieves the current field
    • SolrDocument::deleteField — Removes a field from the document
    • SolrDocument::__destruct — Destructor
    • SolrDocument::fieldExists — Checks if a field exists in the document
    • SolrDocument::__get — Acess the field as a property
    • SolrDocument::getField — Retrieves a field by name
    • SolrDocument::getFieldCount — Returns the number of fields in this document
    • SolrDocument::getFieldNames — Returns an array of fields names in the document
    • SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object
    • SolrDocument::__isset — Checks if a field exists
    • SolrDocument::key — Retrieves the current key
    • SolrDocument::merge — Merges source to the current SolrDocument
    • SolrDocument::next — Moves the internal pointer to the next field
    • SolrDocument::offsetExists — Checks if a particular field exists
    • SolrDocument::offsetGet — Retrieves a field
    • SolrDocument::offsetSet — Adds a field to the document
    • SolrDocument::offsetUnset — Removes a field
    • SolrDocument::reset — This is an alias to SolrDocument::clear()
    • SolrDocument::rewind — Resets the internal pointer to the beginning
    • SolrDocument::serialize — Used for custom serialization
    • SolrDocument::__set — Adds another field to the document
    • SolrDocument::sort — Sorts the fields in the document
    • SolrDocument::toArray — Returns an array representation of the document
    • SolrDocument::unserialize — Custom serialization of SolrDocument objects
    • SolrDocument::__unset — Removes a field from the document
    • SolrDocument::valid — Checks if the current position internally is still valid
  • SolrDocumentField — The SolrDocumentField class
    • SolrDocumentField::__construct — Constructor
    • SolrDocumentField::__destruct — Destructor
  • SolrObject — The SolrObject class
    • SolrObject::__construct — Creates Solr object
    • SolrObject::__destruct — Destructor
    • SolrObject::getPropertyNames — Returns an array of all the names of the properties
    • SolrObject::offsetExists — Checks if the property exists
    • SolrObject::offsetGet — Used to retrieve a property
    • SolrObject::offsetSet — Sets the value for a property
    • SolrObject::offsetUnset — Sets the value for the property
  • SolrClient — The SolrClient class
    • SolrClient::addDocument — Adds a document to the index
    • SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit — Finalizes all add/deletes made to the index
    • SolrClient::__construct — Constructor for the SolrClient object
    • SolrClient::deleteById — Delete by Id
    • SolrClient::deleteByIds — Deletes by Ids
    • SolrClient::deleteByQueries — Removes all documents matching any of the queries
    • SolrClient::deleteByQuery — Deletes all documents matching the given query
    • SolrClient::__destruct — Destructor for SolrClient
    • SolrClient::getDebug — Returns the debug data for the last connection attempt
    • SolrClient::getOptions — Returns the client options set internally
    • SolrClient::optimize — Defragments the index
    • SolrClient::ping — Checks if Solr server is still up
    • SolrClient::query — Sends a query to the server
    • SolrClient::request — Sends a raw update request
    • SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet — Changes the specified servlet type to a new value
    • SolrClient::threads — Checks the threads status
  • SolrResponse — The SolrResponse class
    • SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus — Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status
    • SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse — Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server
    • SolrResponse::getRequestUrl — Returns the full URL the request was sent to
    • SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode — Sets the parse mode
    • SolrResponse::success — Was the request a success
  • SolrQueryResponse — The SolrQueryResponse class
    • SolrQueryResponse::__construct — Constructor
    • SolrQueryResponse::__destruct — Destructor
  • SolrUpdateResponse — The SolrUpdateResponse class
    • SolrUpdateResponse::__construct — Constructor
    • SolrUpdateResponse::__destruct — Destructor
  • SolrPingResponse — The SolrPingResponse class
    • SolrPingResponse::__construct — Constructor
    • SolrPingResponse::__destruct — Destructor
    • SolrPingResponse::getResponse — Returns the response from the server
  • SolrGenericResponse — The SolrGenericResponse class
    • SolrGenericResponse::__construct — Constructor
    • SolrGenericResponse::__destruct — Destructor
  • SolrParams — The SolrParams class
    • SolrParams::add — This is an alias for SolrParams::addParam
    • SolrParams::addParam — Adds a parameter to the object
    • SolrParams::get — This is an alias for SolrParams::getParam
    • SolrParams::getParam — Returns a parameter value
    • SolrParams::getParams — Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams — Returns an array of URL-encoded parameters
    • SolrParams::serialize — Used for custom serialization
    • SolrParams::set — An alias of SolrParams::setParam
    • SolrParams::setParam — Sets the parameter to the specified value
    • SolrParams::toString — Returns all the name-value pair parameters in the object
    • SolrParams::unserialize — Used for custom serialization
  • SolrModifiableParams — The SolrModifiableParams class
    • SolrModifiableParams::__construct — Constructor
    • SolrModifiableParams::__destruct — Destructor
  • SolrQuery — The SolrQuery class
    • SolrQuery::addFacetDateField — Maps to facet.date
    • SolrQuery::addFacetDateOther — Adds another facet.date.other parameter
    • SolrQuery::addFacetField — Adds another field to the facet
    • SolrQuery::addFacetQuery — Adds a facet query
    • SolrQuery::addField — Specifies which fields to return in the result
    • SolrQuery::addFilterQuery — Specifies a filter query
    • SolrQuery::addHighlightField — Maps to hl.fl
    • SolrQuery::addMltField — Sets a field to use for similarity
    • SolrQuery::addMltQueryField — Maps to mlt.qf
    • SolrQuery::addSortField — Used to control how the results should be sorted
    • SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField — Maps to stats.field parameter
    • SolrQuery::__construct — Constructor
    • SolrQuery::__destruct — Destructor
    • SolrQuery::getFacet — Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields — Returns all the facet.date fields
    • SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields — Returns all the facet fields
    • SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod — Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix — Returns the facet prefix
    • SolrQuery::getFacetQueries — Returns all the facet queries
    • SolrQuery::getFacetSort — Returns the facet sort type
    • SolrQuery::getFields — Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries — Returns an array of filter queries
    • SolrQuery::getHighlight — Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount — Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields — Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields — Returns the query fields and their boosts
    • SolrQuery::getQuery — Returns the main query
    • SolrQuery::getRows — Returns the maximum number of documents
    • SolrQuery::getSortFields — Returns all the sort fields
    • SolrQuery::getStart — Returns the offset in the complete result set
    • SolrQuery::getStats — Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets — Returns all the stats facets that were set
    • SolrQuery::getStatsFields — Returns all the statistics fields
    • SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField — Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound — Returns the term to start at
    • SolrQuery::getTermsMaxCount — Returns the maximum document frequency
    • SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix — Returns the term prefix
    • SolrQuery::getTermsReturnRaw — Whether or not to return raw characters
    • SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound — Returns the term to stop at
    • SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeFacetDateField — Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField — Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery — Removes one of the facet.query parameters
    • SolrQuery::removeField — Removes a field from the list of fields
    • SolrQuery::removeFilterQuery — Removes a filter query
    • SolrQuery::removeHighlightField — Removes one of the fields used for highlighting
    • SolrQuery::removeMltField — Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField — Removes one of the sort fields
    • SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField — Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler — Toggles the echoHandler parameter
    • SolrQuery::setEchoParams — Determines what kind of parameters to include in the response
    • SolrQuery::setExplainOther — Sets the explainOther common query parameter
    • SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd — Maps to facet.date.end
    • SolrQuery::setFacetDateGap — Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart — Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit — Maps to facet.limit
    • SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount — Maps to facet.mincount
    • SolrQuery::setFacetMissing — Maps to facet.missing
    • SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort — Determines the ordering of the facet field constraints
    • SolrQuery::setHighlight — Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField — Specifies the backup field to use
    • SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt — Enables or disables moreLikeThis
    • SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount — Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength — Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength — Sets the minimum word length
    • SolrQuery::setOmitHeader — Exclude the header from the returned results
    • SolrQuery::setQuery — Sets the search query
    • SolrQuery::setRows — Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo — Flag to show debug information
    • SolrQuery::setStart — Specifies the number of rows to skip
    • SolrQuery::setStats — Enables or disables the Stats component
    • SolrQuery::setTerms — Enables or disables the TermsComponent
    • SolrQuery::setTermsField — Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set
    • SolrQuery::setTermsLimit — Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound — Specifies the Term to start from
    • SolrQuery::setTermsMaxCount — Sets the maximum document frequency
    • SolrQuery::setTermsMinCount — Sets the minimum document frequency
    • SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term
    • SolrQuery::setTermsSort — Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound — Sets the term to stop at
    • SolrQuery::setTimeAllowed — The time allowed for search to finish
  • SolrException — The SolrException class
    • SolrException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrClientException — The SolrClientException class
    • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrIllegalOperationException — The SolrIllegalOperationException class
    • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown
udm_set_agent_param
Wstęp
Systemy wyszukiwania informacji


Wstęp

The Solr extension allows you to communicate effectively with the Apache Solr server in PHP 5.

The Solr extension is an extremely fast, light-weight, feature-rich library that allows PHP developers to communicate effectively with Solr server instances.

It is compatible with both versions 1.3 and 1.4 of Apache Solr.

There are built-in tools to add documents and make updates to the solr server.

It also contains tools that allows you to build advanced queries to the server when searching for documents.

Solr
Instalacja/Konfiguracja
Solr


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Solr


Wymagania

PHP version 5.2.11 or later is required.

The libxml and curl extensions must also be enabled for the Apache Solr extension to be available.

libxml2 2.6.31 or later is required.

libcurl 7.18.0 or later is also required.

The above library versions are required and attempting to hack the code to make it compile is strongly discouraged. It will fail, possibly with errors that could be hard to debug

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/solr.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Informacja:

The solr module can be compiled in debug mode by passing the --enable-solr-debug flag to configure

When building manually, be sure to include curl and libxml support within the build.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

SOLR_MAJOR_VERSION (integer)
SOLR_MINOR_VERSION (integer)
SOLR_PATCH_VERSION (integer)
SOLR_EXTENSION_VERSION (string)

Typy zasobów
Solr Funkcje
Solr


Solr Funkcje

Spis treści

  • solr_get_version — Returns the current version of the Apache Solr extension
Stałe predefiniowane
solr_get_version
Solr


Returns the current version of the Apache Solr extension

Solr Funkcje
Przykłady
Solr Funkcje
PHP Manual

solr_get_version

(PECL solr >= 0.9.1)

solr_get_version — Returns the current version of the Apache Solr extension

Opis

string solr_get_version ( void )

This function returns the current version of the extension as a string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

It returns a string on success and FALSE on failure.

Błędy/Wyjątki

This function throws no errors or exceptions.

Przykłady

Przykład #1 solr_get_version() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

$solr_version = solr_get_version();

print $solr_version;

?>

Powyższy przykład wyświetli coś podobnego do:

0.9.6

Zobacz też:

  • SolrUtils::getSolrVersion() - Returns the current version of the Solr extension

Solr Funkcje
Przykłady
Solr Funkcje


Przykłady

Examples of how to use the Apache Solr extension in PHP

Przykład #1 Contents of the BootStrap file

<?php

/* Domain name of the Solr server */
define('SOLR_SERVER_HOSTNAME', 'solr.example.com');

/* Whether or not to run in secure mode */
define('SOLR_SECURE', true);

/* HTTP Port to connection */
define('SOLR_SERVER_PORT', ((SOLR_SECURE) ? 8443 : 8983));

/* HTTP Basic Authentication Username */
define('SOLR_SERVER_USERNAME', 'admin');

/* HTTP Basic Authentication password */
define('SOLR_SERVER_PASSWORD', 'changeit');

/* HTTP connection timeout */
/* This is maximum time in seconds allowed for the http data transfer operation. Default value is 30 seconds */
define('SOLR_SERVER_TIMEOUT', 10);

/* File name to a PEM-formatted private key + private certificate (concatenated in that order) */
define('SOLR_SSL_CERT', 'certs/combo.pem');

/* File name to a PEM-formatted private certificate only */
define('SOLR_SSL_CERT_ONLY', 'certs/solr.crt');

/* File name to a PEM-formatted private key */
define('SOLR_SSL_KEY', 'certs/solr.key');

/* Password for PEM-formatted private key file */
define('SOLR_SSL_KEYPASSWORD', 'StrongAndSecurePassword');

/* Name of file holding one or more CA certificates to verify peer with*/
define('SOLR_SSL_CAINFO', 'certs/cacert.crt');

/* Name of directory holding multiple CA certificates to verify peer with */
define('SOLR_SSL_CAPATH', 'certs/');

?>

Przykład #2 Adding a document to the index

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

print_r($updateResponse->getResponse());

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 446
        )

)

Przykład #3 Merging one document into another document

<?php

include "bootstrap.php";

$doc = new SolrDocument();

$second_doc = new SolrDocument();

$doc->addField('id', 1123);

$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";

$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat   = 'Information Technology';

$second_doc->addField('cat', 'Lucene Search');

$second_doc->merge($doc, true);

print_r($second_doc->toArray());

?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [document_boost] => 0
    [field_count] => 3
    [fields] => Array
        (
            [0] => SolrDocumentField Object
                (
                    [name] => cat
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => Software
                            [1] => Custom Search
                            [2] => Information Technology
                        )

                )

            [1] => SolrDocumentField Object
                (
                    [name] => id
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => 1123
                        )

                )

            [2] => SolrDocumentField Object
                (
                    [name] => features
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => PHP Client Side
                            [1] => Fast development cycles
                        )

                )

        )

)

Przykład #4 Searching for documents - SolrObject responses

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [wt] => xml
                    [rows] => 50
                    [start] => 0
                    [indent] => on
                    [q] => lucene
                    [fl] => cat,features,id,timestamp
                    [version] => 2.2
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 3
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => Software
                                    [1] => Lucene
                                )

                            [id] => 334456
                        )

                    [1] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => Software
                                    [1] => Lucene
                                )

                            [id] => 334455
                        )

                    [2] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => software
                                    [1] => search
                                )

                            [features] => Array
                                (
                                    [0] => Advanced Full-Text Search Capabilities using Lucene
                                    [1] => Optimized for High Volume Web Traffic
                                    [2] => Standards Based Open Interfaces - XML and HTTP
                                    [3] => Comprehensive HTML Administration Interfaces
                                    [4] => Scalability - Efficient Replication to other Solr Search Servers
                                    [5] => Flexible and Adaptable with XML configuration and Schema
                                    [6] => Good unicode support: héllo (hello with an accent over the e)
                                )

                            [id] => SOLR1000
                            [timestamp] => 2009-09-04T20:38:55.906
                        )

                )

        )

)

Przykład #5 Searching for documents - SolrDocument responses

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);

$response = $query_response->getResponse();

print_r($response);

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [wt] => xml
                    [rows] => 50
                    [start] => 0
                    [indent] => on
                    [q] => lucene
                    [fl] => cat,features,id,timestamp
                    [version] => 2.2
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 3
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 19740
                        )

                    [1] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 25485
                        )

                    [2] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 25052
                        )

                )

        )

)

Przykład #6 Simple TermsComponent example - basic

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

$query->setTermsField('cat');

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [electronics] => 14
                    [Lucene] => 4
                    [Software] => 4
                    [memory] => 3
                    [card] => 2
                    [connector] => 2
                    [drive] => 2
                    [graphics] => 2
                    [hard] => 2
                    [monitor] => 2
                )

        )

)

Przykład #7 Simple TermsComponent example - using a prefix

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

/* Return only terms starting with $prefix */
$prefix = 'c';

$query->setTermsField('cat')->setTermsPrefix($prefix);

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                    [camera] => 1
                    [copier] => 1
                )

        )

)

Przykład #8 Simple TermsComponent example - specifying a minimum frequency

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

/* Return only terms starting with $prefix */
$prefix = 'c';

/* Return only terms with a frequency of 2 or greater */
$min_frequency = 2;

$query->setTermsField('cat')->setTermsPrefix($prefix)->setTermsMinCount($min_frequency);

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 0
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                )

        )

)

Przykład #9 Simple Facet Example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2);

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
            [1] => 3
            [184] => 3
            [2] => 3
            [3200] => 3
            [400] => 3
            [500] => 3
            [ddr] => 3
            [i] => 3
            [ipod] => 3
            [memori] => 3
            [pc] => 3
            [pin] => 3
            [pod] => 3
            [sdram] => 3
            [system] => 3
            [unbuff] => 3
            [canon] => 2
            [corsair] => 2
            [drive] => 2
            [hard] => 2
            [mb] => 2
            [n] => 2
            [power] => 2
            [retail] => 2
            [video] => 2
            [x] => 2
        )

)

Przykład #10 Simple Facet Example - with optional field override for mincount

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
        )

)

Przykład #11 Connecting to SSL-Enabled Server

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'timeout'  => SOLR_SERVER_TIMEOUT,
    'secure'   => SOLR_SECURE,
    'ssl_cert' => SOLR_SSL_CERT_ONLY,
    'ssl_key'  => SOLR_SSL_KEY,
    'ssl_keypassword' => SOLR_SSL_KEYPASSWORD,
    'ssl_cainfo' => SOLR_SSL_CAINFO,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
        )

)
solr_get_version
SolrUtils
Solr


The SolrUtils class

(No version information available, might only be in SVN)

Wstęp

Contains utility methods for retrieving the current extension version and preparing query phrases.

Also contains method for escaping query strings and parsing XML responses.

Krótki opis klasy

abstract SolrUtils {
/* Metody */
public static SolrObject digestXmlResponse ( string $xmlresponse [, int $parse_mode = 0 ] )
public static string escapeQueryChars ( string $str )
public static string getSolrVersion ( void )
public static string queryPhrase ( string $str )
}

Spis treści

  • SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject
  • SolrUtils::escapeQueryChars — Escapes a lucene query string
  • SolrUtils::getSolrVersion — Returns the current version of the Solr extension
  • SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string
Przykłady
SolrUtils::digestXmlResponse
Solr


Parses an response XML string into a SolrObject

SolrUtils
SolrUtils::escapeQueryChars
SolrUtils
PHP Manual

SolrUtils::digestXmlResponse

(PECL solr >= 0.9.2)

SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject

Opis

public static SolrObject SolrUtils::digestXmlResponse ( string $xmlresponse [, int $parse_mode = 0 ] )

This method parses an response XML string from the Apache Solr server into a SolrObject. It throws a SolrException if there was an error.

Parametry

xmlresponse

The XML response string from the Solr server.

parse_mode

Use SolrResponse::PARSE_SOLR_OBJ or SolrResponse::PARSE_SOLR_DOC

Zwracane wartości

Returns the SolrObject representing the XML response.

If the parse_mode parameter is set to SolrResponse::PARSE_SOLR_OBJ Solr documents will be parses as SolrObject instances.

If it is set to SolrResponse::PARSE_SOLR_DOC, they will be parsed as SolrDocument instances.

SolrUtils
SolrUtils::escapeQueryChars
SolrUtils


Escapes a lucene query string

SolrUtils::digestXmlResponse
SolrUtils::getSolrVersion
SolrUtils
PHP Manual

SolrUtils::escapeQueryChars

(PECL solr >= 0.9.2)

SolrUtils::escapeQueryChars — Escapes a lucene query string

Opis

public static string SolrUtils::escapeQueryChars ( string $str )

Lucene supports escaping special characters that are part of the query syntax.

The current list special characters are:

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \

These characters are part of the query syntax and must be escaped

Parametry

str

This is the query string to be escaped.

Zwracane wartości

Returns the escaped string lub FALSE w przypadku niepowodzenia.

SolrUtils::digestXmlResponse
SolrUtils::getSolrVersion
SolrUtils


Returns the current version of the Solr extension

SolrUtils::escapeQueryChars
SolrUtils::queryPhrase
SolrUtils
PHP Manual

SolrUtils::getSolrVersion

(PECL solr >= 0.9.2)

SolrUtils::getSolrVersion — Returns the current version of the Solr extension

Opis

public static string SolrUtils::getSolrVersion ( void )

Returns the current Solr version.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The current version of the Apache Solr extension.

SolrUtils::escapeQueryChars
SolrUtils::queryPhrase
SolrUtils


Prepares a phrase from an unescaped lucene string

SolrUtils::getSolrVersion
SolrInputDocument
SolrUtils
PHP Manual

SolrUtils::queryPhrase

(PECL solr >= 0.9.2)

SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string

Opis

public static string SolrUtils::queryPhrase ( string $str )

Prepares a phrase from an unescaped lucene string.

Parametry

str

The lucene phrase.

Zwracane wartości

Returns the phrase contained in double quotes.

SolrUtils::getSolrVersion
SolrInputDocument
SolrUtils


The SolrInputDocument class

(No version information available, might only be in SVN)

Wstęp

This class represents a Solr document that is about to be submitted to the Solr index.

Krótki opis klasy

final SolrInputDocument {
/* Stałe */
const integer SORT_DEFAULT = 1 ;
const integer SORT_ASC = 1 ;
const integer SORT_DESC = 2 ;
const integer SORT_FIELD_NAME = 1 ;
const integer SORT_FIELD_VALUE_COUNT = 2 ;
const integer SORT_FIELD_BOOST_VALUE = 4 ;
/* Metody */
public bool addField ( string $fieldName , string $fieldValue [, float $fieldBoostValue = 0.0 ] )
public bool clear ( void )
public void __clone ( void )
public __construct ( void )
public bool deleteField ( string $fieldName )
public void __destruct ( void )
public bool fieldExists ( string $fieldName )
public float getBoost ( void )
public SolrDocumentField getField ( string $fieldName )
public float getFieldBoost ( string $fieldName )
public int getFieldCount ( void )
public array getFieldNames ( void )
public bool merge ( SolrInputDocument $sourceDoc [, bool $overwrite = true ] )
public bool reset ( void )
public bool setBoost ( float $documentBoostValue )
public bool setFieldBoost ( string $fieldName , float $fieldBoostValue )
public bool sort ( int $sortOrderBy [, int $sortDirection = SolrInputDocument::SORT_ASC ] )
public array toArray ( void )
}

Stałe predefiniowane

SolrInputDocument Class Constants

SolrInputDocument::SORT_DEFAULT

Sorts the fields in ascending order.

SolrInputDocument::SORT_ASC

Sorts the fields in ascending order.

SolrInputDocument::SORT_DESC

Sorts the fields in descending order.

SolrInputDocument::SORT_FIELD_NAME

Sorts the fields by name

SolrInputDocument::SORT_FIELD_VALUE_COUNT

Sorts the fields by number of values.

SolrInputDocument::SORT_FIELD_BOOST_VALUE

Sorts the fields by boost value.

Spis treści

  • SolrInputDocument::addField — Adds a field to the document
  • SolrInputDocument::clear — Resets the input document
  • SolrInputDocument::__clone — Creates a copy of a SolrDocument
  • SolrInputDocument::__construct — Constructor
  • SolrInputDocument::deleteField — Removes a field from the document
  • SolrInputDocument::__destruct — Destructor
  • SolrInputDocument::fieldExists — Checks if a field exists
  • SolrInputDocument::getBoost — Retrieves the current boost value for the document
  • SolrInputDocument::getField — Retrieves a field by name
  • SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field
  • SolrInputDocument::getFieldCount — Returns the number of fields in the document
  • SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document
  • SolrInputDocument::merge — Merges one input document into another
  • SolrInputDocument::reset — This is an alias of SolrInputDocument::clear
  • SolrInputDocument::setBoost — Sets the boost value for this document
  • SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field
  • SolrInputDocument::sort — Sorts the fields within the document
  • SolrInputDocument::toArray — Returns an array representation of the input document
SolrUtils::queryPhrase
SolrInputDocument::addField
Solr


Adds a field to the document

SolrInputDocument
SolrInputDocument::clear
SolrInputDocument
PHP Manual

SolrInputDocument::addField

(PECL solr >= 0.9.2)

SolrInputDocument::addField — Adds a field to the document

Opis

public bool SolrInputDocument::addField ( string $fieldName , string $fieldValue [, float $fieldBoostValue = 0.0 ] )

For multi-value fields, if a valid boost value is specified, the specified value will be multiplied by the current boost value for this field.

Parametry

fieldName

The name of the field

fieldValue

The value for the field.

fieldBoostValue

The index time boost for the field. Though this cannot be negative, you can still pass values less than 1.0 but they must be greater than zero.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrInputDocument
SolrInputDocument::clear
SolrInputDocument


Resets the input document

SolrInputDocument::addField
SolrInputDocument::__clone
SolrInputDocument
PHP Manual

SolrInputDocument::clear

(PECL solr >= 0.9.2)

SolrInputDocument::clear — Resets the input document

Opis

public bool SolrInputDocument::clear ( void )

Resets the document by dropping all the fields and resets the document boost to zero.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrInputDocument::addField
SolrInputDocument::__clone
SolrInputDocument


Creates a copy of a SolrDocument

SolrInputDocument::clear
SolrInputDocument::__construct
SolrInputDocument
PHP Manual

SolrInputDocument::__clone

(PECL solr >= 0.9.2)

SolrInputDocument::__clone — Creates a copy of a SolrDocument

Opis

public void SolrInputDocument::__clone ( void )

Should not be called directly. It is used to create a deep copy of a SolrInputDocument.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Creates a new SolrInputDocument instance.

SolrInputDocument::clear
SolrInputDocument::__construct
SolrInputDocument


Constructor

SolrInputDocument::__clone
SolrInputDocument::deleteField
SolrInputDocument
PHP Manual

SolrInputDocument::__construct

(PECL solr >= 0.9.2)

SolrInputDocument::__construct — Constructor

Opis

public SolrInputDocument::__construct ( void )

Constructor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None.

SolrInputDocument::__clone
SolrInputDocument::deleteField
SolrInputDocument


Removes a field from the document

SolrInputDocument::__construct
SolrInputDocument::__destruct
SolrInputDocument
PHP Manual

SolrInputDocument::deleteField

(PECL solr >= 0.9.2)

SolrInputDocument::deleteField — Removes a field from the document

Opis

public bool SolrInputDocument::deleteField ( string $fieldName )

Removes a field from the document.

Parametry

fieldName

The name of the field.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrInputDocument::__construct
SolrInputDocument::__destruct
SolrInputDocument


Destructor

SolrInputDocument::deleteField
SolrInputDocument::fieldExists
SolrInputDocument
PHP Manual

SolrInputDocument::__destruct

(PECL solr >= 0.9.2)

SolrInputDocument::__destruct — Destructor

Opis

public void SolrInputDocument::__destruct ( void )

Destructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None.

SolrInputDocument::deleteField
SolrInputDocument::fieldExists
SolrInputDocument


Checks if a field exists

SolrInputDocument::__destruct
SolrInputDocument::getBoost
SolrInputDocument
PHP Manual

SolrInputDocument::fieldExists

(PECL solr >= 0.9.2)

SolrInputDocument::fieldExists — Checks if a field exists

Opis

public bool SolrInputDocument::fieldExists ( string $fieldName )

Checks if a field exists

Parametry

fieldName

Name of the field.

Zwracane wartości

Returns TRUE if the field was found and FALSE if it was not found.

SolrInputDocument::__destruct
SolrInputDocument::getBoost
SolrInputDocument


Retrieves the current boost value for the document

SolrInputDocument::fieldExists
SolrInputDocument::getField
SolrInputDocument
PHP Manual

SolrInputDocument::getBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getBoost — Retrieves the current boost value for the document

Opis

public float SolrInputDocument::getBoost ( void )

Retrieves the current boost value for the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the boost value on success and FALSE on failure.

SolrInputDocument::fieldExists
SolrInputDocument::getField
SolrInputDocument


Retrieves a field by name

SolrInputDocument::getBoost
SolrInputDocument::getFieldBoost
SolrInputDocument
PHP Manual

SolrInputDocument::getField

(PECL solr >= 0.9.2)

SolrInputDocument::getField — Retrieves a field by name

Opis

public SolrDocumentField SolrInputDocument::getField ( string $fieldName )

Retrieves a field in the document.

Parametry

fieldName

The name of the field.

Zwracane wartości

Returns a SolrDocumentField object on success and FALSE on failure.

SolrInputDocument::getBoost
SolrInputDocument::getFieldBoost
SolrInputDocument


Retrieves the boost value for a particular field

SolrInputDocument::getField
SolrInputDocument::getFieldCount
SolrInputDocument
PHP Manual

SolrInputDocument::getFieldBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field

Opis

public float SolrInputDocument::getFieldBoost ( string $fieldName )

Retrieves the boost value for a particular field.

Parametry

fieldName

The name of the field.

Zwracane wartości

Returns the boost value for the field or FALSE if there was an error.

SolrInputDocument::getField
SolrInputDocument::getFieldCount
SolrInputDocument


Returns the number of fields in the document

SolrInputDocument::getFieldBoost
SolrInputDocument::getFieldNames
SolrInputDocument
PHP Manual

SolrInputDocument::getFieldCount

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldCount — Returns the number of fields in the document

Opis

public int SolrInputDocument::getFieldCount ( void )

Returns the number of fields in the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success lub FALSE w przypadku niepowodzenia.

SolrInputDocument::getFieldBoost
SolrInputDocument::getFieldNames
SolrInputDocument


Returns an array containing all the fields in the document

SolrInputDocument::getFieldCount
SolrInputDocument::merge
SolrInputDocument
PHP Manual

SolrInputDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document

Opis

public array SolrInputDocument::getFieldNames ( void )

Returns an array containing all the fields in the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and FALSE on failure.

SolrInputDocument::getFieldCount
SolrInputDocument::merge
SolrInputDocument


Merges one input document into another

SolrInputDocument::getFieldNames
SolrInputDocument::reset
SolrInputDocument
PHP Manual

SolrInputDocument::merge

(PECL solr >= 0.9.2)

SolrInputDocument::merge — Merges one input document into another

Opis

public bool SolrInputDocument::merge ( SolrInputDocument $sourceDoc [, bool $overwrite = true ] )

Merges one input document into another.

Parametry

sourceDoc

The source document.

overwrite

If this is TRUE it will replace matching fields in the destination document.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. In the future, this will be modified to return the number of fields in the new document.

SolrInputDocument::getFieldNames
SolrInputDocument::reset
SolrInputDocument


This is an alias of SolrInputDocument::clear

SolrInputDocument::merge
SolrInputDocument::setBoost
SolrInputDocument
PHP Manual

SolrInputDocument::reset

(PECL solr >= 0.9.2)

SolrInputDocument::reset — This is an alias of SolrInputDocument::clear

Opis

public bool SolrInputDocument::reset ( void )

This is an alias of SolrInputDocument::clear

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrInputDocument::merge
SolrInputDocument::setBoost
SolrInputDocument


Sets the boost value for this document

SolrInputDocument::reset
SolrInputDocument::setFieldBoost
SolrInputDocument
PHP Manual

SolrInputDocument::setBoost

(PECL solr >= 0.9.2)

SolrInputDocument::setBoost — Sets the boost value for this document

Opis

public bool SolrInputDocument::setBoost ( float $documentBoostValue )

Sets the boost value for this document.

Parametry

documentBoostValue

The index-time boost value for this document.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrInputDocument::reset
SolrInputDocument::setFieldBoost
SolrInputDocument


Sets the index-time boost value for a field

SolrInputDocument::setBoost
SolrInputDocument::sort
SolrInputDocument
PHP Manual

SolrInputDocument::setFieldBoost

(PECL solr >= 0.9.2)

SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field

Opis

public bool SolrInputDocument::setFieldBoost ( string $fieldName , float $fieldBoostValue )

Sets the index-time boost value for a field. This replaces the current boost value for this field.

Parametry

fieldName

The name of the field.

fieldBoostValue

The index time boost value.

SolrInputDocument::setBoost
SolrInputDocument::sort
SolrInputDocument


Sorts the fields within the document

SolrInputDocument::setFieldBoost
SolrInputDocument::toArray
SolrInputDocument
PHP Manual

SolrInputDocument::sort

(PECL solr >= 0.9.2)

SolrInputDocument::sort — Sorts the fields within the document

Opis

public bool SolrInputDocument::sort ( int $sortOrderBy [, int $sortDirection = SolrInputDocument::SORT_ASC ] )

The fields are rearranged according to the specified criteria and sort direction

   Fields can be sorted by boost values, field names and number of values.

   The $order_by parameter must be one of :

   * SolrInputDocument::SORT_FIELD_NAME
   * SolrInputDocument::SORT_FIELD_BOOST_VALUE
   * SolrInputDocument::SORT_FIELD_VALUE_COUNT

   The sort direction can be one of :

   * SolrInputDocument::SORT_DEFAULT
   * SolrInputDocument::SORT_ASC
   * SolrInputDocument::SORT_DESC

Parametry

sortOrderBy

The sort criteria

sortDirection

The sort direction

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrInputDocument::setFieldBoost
SolrInputDocument::toArray
SolrInputDocument


Returns an array representation of the input document

SolrInputDocument::sort
SolrDocument
SolrInputDocument
PHP Manual

SolrInputDocument::toArray

(PECL solr >= 0.9.2)

SolrInputDocument::toArray — Returns an array representation of the input document

Opis

public array SolrInputDocument::toArray ( void )

Returns an array representation of the input document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array containing the fields. It returns FALSE on failure.

SolrInputDocument::sort
SolrDocument
SolrInputDocument


The SolrDocument class

(No version information available, might only be in SVN)

Wstęp

Represents a Solr document retrieved from a query response.

Krótki opis klasy

final SolrDocument implements ArrayAccess , Iterator , Traversable , Serializable {
/* Stałe */
const integer SORT_DEFAULT = 1 ;
const integer SORT_ASC = 1 ;
const integer SORT_DESC = 2 ;
const integer SORT_FIELD_NAME = 1 ;
const integer SORT_FIELD_VALUE_COUNT = 2 ;
const integer SORT_FIELD_BOOST_VALUE = 4 ;
/* Metody */
public bool addField ( string $fieldName , string $fieldValue )
public bool clear ( void )
public void __clone ( void )
public __construct ( void )
public SolrDocumentField current ( void )
public bool deleteField ( string $fieldName )
public void __destruct ( void )
public bool fieldExists ( string $fieldName )
public SolrDocumentField __get ( string $fieldName )
public SolrDocumentField getField ( string $fieldName )
public int getFieldCount ( void )
public array getFieldNames ( void )
public SolrInputDocument getInputDocument ( void )
public bool __isset ( string $fieldName )
public string key ( void )
public bool merge ( SolrDocument $sourceDoc [, bool $overwrite = true ] )
public void next ( void )
public bool offsetExists ( string $fieldName )
public SolrDocumentField offsetGet ( string $fieldName )
public void offsetSet ( string $fieldName , string $fieldValue )
public void offsetUnset ( string $fieldName )
public bool reset ( void )
public void rewind ( void )
public string serialize ( void )
public bool __set ( string $fieldName , string $fieldValue )
public bool sort ( int $sortOrderBy [, int $sortDirection = SolrDocument::SORT_ASC ] )
public array toArray ( void )
public void unserialize ( string $serialized )
public bool __unset ( string $fieldName )
public bool valid ( void )
}

Stałe predefiniowane

SolrDocument::SORT_DEFAULT

Default mode for sorting fields within the document.

SolrDocument::SORT_ASC

Sorts the fields in ascending order

SolrDocument::SORT_DESC

Sorts the fields in descending order

SolrDocument::SORT_FIELD_NAME

Sorts the fields by field name.

SolrDocument::SORT_FIELD_VALUE_COUNT

Sorts the fields by number of values in each field.

SolrDocument::SORT_FIELD_BOOST_VALUE

Sorts the fields by thier boost values.

Spis treści

  • SolrDocument::addField — Adds a field to the document
  • SolrDocument::clear — Drops all the fields in the document
  • SolrDocument::__clone — Creates a copy of a SolrDocument object
  • SolrDocument::__construct — Constructor
  • SolrDocument::current — Retrieves the current field
  • SolrDocument::deleteField — Removes a field from the document
  • SolrDocument::__destruct — Destructor
  • SolrDocument::fieldExists — Checks if a field exists in the document
  • SolrDocument::__get — Acess the field as a property
  • SolrDocument::getField — Retrieves a field by name
  • SolrDocument::getFieldCount — Returns the number of fields in this document
  • SolrDocument::getFieldNames — Returns an array of fields names in the document
  • SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object
  • SolrDocument::__isset — Checks if a field exists
  • SolrDocument::key — Retrieves the current key
  • SolrDocument::merge — Merges source to the current SolrDocument
  • SolrDocument::next — Moves the internal pointer to the next field
  • SolrDocument::offsetExists — Checks if a particular field exists
  • SolrDocument::offsetGet — Retrieves a field
  • SolrDocument::offsetSet — Adds a field to the document
  • SolrDocument::offsetUnset — Removes a field
  • SolrDocument::reset — This is an alias to SolrDocument::clear()
  • SolrDocument::rewind — Resets the internal pointer to the beginning
  • SolrDocument::serialize — Used for custom serialization
  • SolrDocument::__set — Adds another field to the document
  • SolrDocument::sort — Sorts the fields in the document
  • SolrDocument::toArray — Returns an array representation of the document
  • SolrDocument::unserialize — Custom serialization of SolrDocument objects
  • SolrDocument::__unset — Removes a field from the document
  • SolrDocument::valid — Checks if the current position internally is still valid
SolrInputDocument::toArray
SolrDocument::addField
Solr


Adds a field to the document

SolrDocument
SolrDocument::clear
SolrDocument
PHP Manual

SolrDocument::addField

(PECL solr >= 0.9.2)

SolrDocument::addField — Adds a field to the document

Opis

public bool SolrDocument::addField ( string $fieldName , string $fieldValue )

This method adds a field to the SolrDocument instance.

Parametry

fieldName

The name of the field

fieldValue

The value of the field.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument
SolrDocument::clear
SolrDocument


Drops all the fields in the document

SolrDocument::addField
SolrDocument::__clone
SolrDocument
PHP Manual

SolrDocument::clear

(PECL solr >= 0.9.2)

SolrDocument::clear — Drops all the fields in the document

Opis

public bool SolrDocument::clear ( void )

Resets the current object. Discards all the fields and resets the document boost to zero.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::addField
SolrDocument::__clone
SolrDocument


Creates a copy of a SolrDocument object

SolrDocument::clear
SolrDocument::__construct
SolrDocument
PHP Manual

SolrDocument::__clone

(PECL solr >= 0.9.2)

SolrDocument::__clone — Creates a copy of a SolrDocument object

Opis

public void SolrDocument::__clone ( void )

Creates a copy of a SolrDocument object. Not to be called directly.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None.

SolrDocument::clear
SolrDocument::__construct
SolrDocument


Constructor

SolrDocument::__clone
SolrDocument::current
SolrDocument
PHP Manual

SolrDocument::__construct

(PECL solr >= 0.9.2)

SolrDocument::__construct — Constructor

Opis

public SolrDocument::__construct ( void )

Constructor for SolrDocument

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

SolrDocument::__clone
SolrDocument::current
SolrDocument


Retrieves the current field

SolrDocument::__construct
SolrDocument::deleteField
SolrDocument
PHP Manual

SolrDocument::current

(PECL solr >= 0.9.2)

SolrDocument::current — Retrieves the current field

Opis

public SolrDocumentField SolrDocument::current ( void )

Retrieves the current field

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the field

SolrDocument::__construct
SolrDocument::deleteField
SolrDocument


Removes a field from the document

SolrDocument::current
SolrDocument::__destruct
SolrDocument
PHP Manual

SolrDocument::deleteField

(PECL solr >= 0.9.2)

SolrDocument::deleteField — Removes a field from the document

Opis

public bool SolrDocument::deleteField ( string $fieldName )

Removes a field from the document.

Parametry

fieldName

Name of the field

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::current
SolrDocument::__destruct
SolrDocument


Destructor

SolrDocument::deleteField
SolrDocument::fieldExists
SolrDocument
PHP Manual

SolrDocument::__destruct

(PECL solr >= 0.9.2)

SolrDocument::__destruct — Destructor

Opis

public void SolrDocument::__destruct ( void )

Destructor for SolrDocument.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

SolrDocument::deleteField
SolrDocument::fieldExists
SolrDocument


Checks if a field exists in the document

SolrDocument::__destruct
SolrDocument::__get
SolrDocument
PHP Manual

SolrDocument::fieldExists

(PECL solr >= 0.9.2)

SolrDocument::fieldExists — Checks if a field exists in the document

Opis

public bool SolrDocument::fieldExists ( string $fieldName )

Checks if the requested field as a valid fieldname in the document.

Parametry

fieldName

The name of the field.

Zwracane wartości

Returns TRUE if the field is present and FALSE if it does not.

SolrDocument::__destruct
SolrDocument::__get
SolrDocument


Acess the field as a property

SolrDocument::fieldExists
SolrDocument::getField
SolrDocument
PHP Manual

SolrDocument::__get

(PECL solr >= 0.9.2)

SolrDocument::__get — Acess the field as a property

Opis

public SolrDocumentField SolrDocument::__get ( string $fieldName )

Magic method for accessing the field as a property.

Parametry

fieldName

The name of the field.

Zwracane wartości

Returns a SolrDocumentField instance.

SolrDocument::fieldExists
SolrDocument::getField
SolrDocument


Retrieves a field by name

SolrDocument::__get
SolrDocument::getFieldCount
SolrDocument
PHP Manual

SolrDocument::getField

(PECL solr >= 0.9.2)

SolrDocument::getField — Retrieves a field by name

Opis

public SolrDocumentField SolrDocument::getField ( string $fieldName )

Retrieves a field by name.

Parametry

fieldName

Name of the field.

Zwracane wartości

Returns a SolrDocumentField on success and FALSE on failure.

SolrDocument::__get
SolrDocument::getFieldCount
SolrDocument


Returns the number of fields in this document

SolrDocument::getField
SolrDocument::getFieldNames
SolrDocument
PHP Manual

SolrDocument::getFieldCount

(PECL solr >= 0.9.2)

SolrDocument::getFieldCount — Returns the number of fields in this document

Opis

public int SolrDocument::getFieldCount ( void )

Returns the number of fields in this document. Multi-value fields are only counted once.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and FALSE on failure.

SolrDocument::getField
SolrDocument::getFieldNames
SolrDocument


Returns an array of fields names in the document

SolrDocument::getFieldCount
SolrDocument::getInputDocument
SolrDocument
PHP Manual

SolrDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrDocument::getFieldNames — Returns an array of fields names in the document

Opis

public array SolrDocument::getFieldNames ( void )

Returns an array of fields names in the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array containing the names of the fields in this document.

SolrDocument::getFieldCount
SolrDocument::getInputDocument
SolrDocument


Returns a SolrInputDocument equivalent of the object

SolrDocument::getFieldNames
SolrDocument::__isset
SolrDocument
PHP Manual

SolrDocument::getInputDocument

(PECL solr >= 0.9.2)

SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object

Opis

public SolrInputDocument SolrDocument::getInputDocument ( void )

Returns a SolrInputDocument equivalent of the object. This is useful if one wishes to resubmit/update a document retrieved from a query.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a SolrInputDocument on success and NULL on failure.

SolrDocument::getFieldNames
SolrDocument::__isset
SolrDocument


Checks if a field exists

SolrDocument::getInputDocument
SolrDocument::key
SolrDocument
PHP Manual

SolrDocument::__isset

(PECL solr >= 0.9.2)

SolrDocument::__isset — Checks if a field exists

Opis

public bool SolrDocument::__isset ( string $fieldName )

Checks if a field exists

Parametry

fieldName

Name of the field.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::getInputDocument
SolrDocument::key
SolrDocument


Retrieves the current key

SolrDocument::__isset
SolrDocument::merge
SolrDocument
PHP Manual

SolrDocument::key

(PECL solr >= 0.9.2)

SolrDocument::key — Retrieves the current key

Opis

public string SolrDocument::key ( void )

Retrieves the current key.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current key.

SolrDocument::__isset
SolrDocument::merge
SolrDocument


Merges source to the current SolrDocument

SolrDocument::key
SolrDocument::next
SolrDocument
PHP Manual

SolrDocument::merge

(PECL solr >= 0.9.2)

SolrDocument::merge — Merges source to the current SolrDocument

Opis

public bool SolrDocument::merge ( SolrDocument $sourceDoc [, bool $overwrite = true ] )

Merges source to the current SolrDocument.

Parametry

sourceDoc

The source document.

overwrite

If this is TRUE then fields with the same name in the destination document will be overwritten.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::key
SolrDocument::next
SolrDocument


Moves the internal pointer to the next field

SolrDocument::merge
SolrDocument::offsetExists
SolrDocument
PHP Manual

SolrDocument::next

(PECL solr >= 0.9.2)

SolrDocument::next — Moves the internal pointer to the next field

Opis

public void SolrDocument::next ( void )

Moves the internal pointer to the next field.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method has no return value.

SolrDocument::merge
SolrDocument::offsetExists
SolrDocument


Checks if a particular field exists

SolrDocument::next
SolrDocument::offsetGet
SolrDocument
PHP Manual

SolrDocument::offsetExists

(PECL solr >= 0.9.2)

SolrDocument::offsetExists — Checks if a particular field exists

Opis

public bool SolrDocument::offsetExists ( string $fieldName )

Checks if a particular field exists. This is used when the object is treated as an array.

Parametry

fieldName

The name of the field.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::next
SolrDocument::offsetGet
SolrDocument


Retrieves a field

SolrDocument::offsetExists
SolrDocument::offsetSet
SolrDocument
PHP Manual

SolrDocument::offsetGet

(PECL solr >= 0.9.2)

SolrDocument::offsetGet — Retrieves a field

Opis

public SolrDocumentField SolrDocument::offsetGet ( string $fieldName )

This is used to retrieve the field when the object is treated as an array.

Parametry

fieldName

The name of the field.

Zwracane wartości

Returns a SolrDocumentField object.

SolrDocument::offsetExists
SolrDocument::offsetSet
SolrDocument


Adds a field to the document

SolrDocument::offsetGet
SolrDocument::offsetUnset
SolrDocument
PHP Manual

SolrDocument::offsetSet

(PECL solr >= 0.9.2)

SolrDocument::offsetSet — Adds a field to the document

Opis

public void SolrDocument::offsetSet ( string $fieldName , string $fieldValue )

Used when the object is treated as an array to add a field to the document.

Parametry

fieldName

The name of the field.

fieldValue

The value for this field.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::offsetGet
SolrDocument::offsetUnset
SolrDocument


Removes a field

SolrDocument::offsetSet
SolrDocument::reset
SolrDocument
PHP Manual

SolrDocument::offsetUnset

(PECL solr >= 0.9.2)

SolrDocument::offsetUnset — Removes a field

Opis

public void SolrDocument::offsetUnset ( string $fieldName )

Removes a field from the document.

Parametry

fieldName

The name of the field.

Zwracane wartości

No return value.

SolrDocument::offsetSet
SolrDocument::reset
SolrDocument


This is an alias to SolrDocument::clear()

SolrDocument::offsetUnset
SolrDocument::rewind
SolrDocument
PHP Manual

SolrDocument::reset

(PECL solr >= 0.9.2)

SolrDocument::reset — This is an alias to SolrDocument::clear()

Opis

public bool SolrDocument::reset ( void )

This is an alias to SolrDocument::clear()

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::offsetUnset
SolrDocument::rewind
SolrDocument


Resets the internal pointer to the beginning

SolrDocument::reset
SolrDocument::serialize
SolrDocument
PHP Manual

SolrDocument::rewind

(PECL solr >= 0.9.2)

SolrDocument::rewind — Resets the internal pointer to the beginning

Opis

public void SolrDocument::rewind ( void )

Resets the internal pointer to the beginning.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method has no return value.

SolrDocument::reset
SolrDocument::serialize
SolrDocument


Used for custom serialization

SolrDocument::rewind
SolrDocument::__set
SolrDocument
PHP Manual

SolrDocument::serialize

(PECL solr >= 0.9.2)

SolrDocument::serialize — Used for custom serialization

Opis

public string SolrDocument::serialize ( void )

Used for custom serialization.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string representing the serialized Solr document.

SolrDocument::rewind
SolrDocument::__set
SolrDocument


Adds another field to the document

SolrDocument::serialize
SolrDocument::sort
SolrDocument
PHP Manual

SolrDocument::__set

(PECL solr >= 0.9.2)

SolrDocument::__set — Adds another field to the document

Opis

public bool SolrDocument::__set ( string $fieldName , string $fieldValue )

Adds another field to the document. Used to set the fields as new properties.

Parametry

fieldName

Name of the field.

fieldValue

Field value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::serialize
SolrDocument::sort
SolrDocument


Sorts the fields in the document

SolrDocument::__set
SolrDocument::toArray
SolrDocument
PHP Manual

SolrDocument::sort

(PECL solr >= 0.9.2)

SolrDocument::sort — Sorts the fields in the document

Opis

public bool SolrDocument::sort ( int $sortOrderBy [, int $sortDirection = SolrDocument::SORT_ASC ] )

The fields are rearranged according to the specified criteria and sort direction

   Fields can be sorted by boost values, field names and number of values.

   The sortOrderBy parameter must be one of :

   * SolrDocument::SORT_FIELD_NAME
   * SolrDocument::SORT_FIELD_BOOST_VALUE
   * SolrDocument::SORT_FIELD_VALUE_COUNT

   The sortDirection can be one of :

   * SolrDocument::SORT_DEFAULT
   * SolrDocument::SORT_ASC
   * SolrDocument::SORT_DESC

   The default way is to sort in ascending order.

Parametry

sortOrderBy

The sort criteria.

sortDirection

The sort direction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::__set
SolrDocument::toArray
SolrDocument


Returns an array representation of the document

SolrDocument::sort
SolrDocument::unserialize
SolrDocument
PHP Manual

SolrDocument::toArray

(PECL solr >= 0.9.2)

SolrDocument::toArray — Returns an array representation of the document

Opis

public array SolrDocument::toArray ( void )

Returns an array representation of the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array representation of the document.

Przykłady

Przykład #1 SolrDocument::toArray() example

<?php

$doc = new SolrDocument();

$doc->addField('id', 1123);

$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";

$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat   = 'Information Technology';

print_r($doc->toArray());

?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [document_boost] => 0
    [field_count] => 3
    [fields] => Array
        (
            [0] => SolrDocumentField Object
                (
                    [name] => id
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => 1123
                        )

                )

            [1] => SolrDocumentField Object
                (
                    [name] => features
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => PHP Client Side
                            [1] => Fast development cycles
                        )

                )

            [2] => SolrDocumentField Object
                (
                    [name] => cat
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => Software
                            [1] => Custom Search
                            [2] => Information Technology
                        )

                )

        )

)

SolrDocument::sort
SolrDocument::unserialize
SolrDocument


Custom serialization of SolrDocument objects

SolrDocument::toArray
SolrDocument::__unset
SolrDocument
PHP Manual

SolrDocument::unserialize

(PECL solr >= 0.9.2)

SolrDocument::unserialize — Custom serialization of SolrDocument objects

Opis

public void SolrDocument::unserialize ( string $serialized )

Custom serialization of SolrDocument objects

Parametry

serialized

An XML representation of the document.

Zwracane wartości

None.

SolrDocument::toArray
SolrDocument::__unset
SolrDocument


Removes a field from the document

SolrDocument::unserialize
SolrDocument::valid
SolrDocument
PHP Manual

SolrDocument::__unset

(PECL solr >= 0.9.2)

SolrDocument::__unset — Removes a field from the document

Opis

public bool SolrDocument::__unset ( string $fieldName )

Removes a field from the document when the field is access as an object property.

Parametry

fieldName

The name of the field.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrDocument::unserialize
SolrDocument::valid
SolrDocument


Checks if the current position internally is still valid

SolrDocument::__unset
SolrDocumentField
SolrDocument
PHP Manual

SolrDocument::valid

(PECL solr >= 0.9.2)

SolrDocument::valid — Checks if the current position internally is still valid

Opis

public bool SolrDocument::valid ( void )

Checks if the current position internally is still valid. It is used during foreach operations.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE on success and FALSE if the current position is no longer valid.

SolrDocument::__unset
SolrDocumentField
SolrDocument


The SolrDocumentField class

(No version information available, might only be in SVN)

Wstęp

This represents a field in a Solr document. All its properties are read-only.

Krótki opis klasy

final SolrDocumentField {
/* Właściwości */
readonly public string $name ;
readonly public float $boost ;
readonly public array $values ;
/* Metody */
public __construct ( void )
public void __destruct ( void )
}

Właściwości

name

The name of the field.

boost

The boost value for the field

values

An array of values for this field

Spis treści

  • SolrDocumentField::__construct — Constructor
  • SolrDocumentField::__destruct — Destructor
SolrDocument::valid
SolrDocumentField::__construct
Solr


Constructor

SolrDocumentField
SolrDocumentField::__destruct
SolrDocumentField
PHP Manual

SolrDocumentField::__construct

(PECL solr >= 0.9.2)

SolrDocumentField::__construct — Constructor

Opis

public SolrDocumentField::__construct ( void )

Constructor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None.

SolrDocumentField
SolrDocumentField::__destruct
SolrDocumentField


Destructor

SolrDocumentField::__construct
SolrObject
SolrDocumentField
PHP Manual

SolrDocumentField::__destruct

(PECL solr >= 0.9.2)

SolrDocumentField::__destruct — Destructor

Opis

public void SolrDocumentField::__destruct ( void )

Destructor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None.

SolrDocumentField::__construct
SolrObject
SolrDocumentField


The SolrObject class

(No version information available, might only be in SVN)

Wstęp

This is an object whose properties can also by accessed using the array syntax. All its properties are read-only.

Krótki opis klasy

final SolrObject implements ArrayAccess {
/* Metody */
public __construct ( void )
public void __destruct ( void )
public array getPropertyNames ( void )
public bool offsetExists ( string $property_name )
public mixed offsetGet ( string $property_name )
public void offsetSet ( string $property_name , string $property_value )
public void offsetUnset ( string $property_name )
}

Spis treści

  • SolrObject::__construct — Creates Solr object
  • SolrObject::__destruct — Destructor
  • SolrObject::getPropertyNames — Returns an array of all the names of the properties
  • SolrObject::offsetExists — Checks if the property exists
  • SolrObject::offsetGet — Used to retrieve a property
  • SolrObject::offsetSet — Sets the value for a property
  • SolrObject::offsetUnset — Sets the value for the property
SolrDocumentField::__destruct
SolrObject::__construct
Solr


Creates Solr object

SolrObject
SolrObject::__destruct
SolrObject
PHP Manual

SolrObject::__construct

(PECL solr >= 0.9.2)

SolrObject::__construct — Creates Solr object

Opis

public SolrObject::__construct ( void )

Creates Solr object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

Przykłady

Przykład #1 SolrObject::__construct() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

SolrObject
SolrObject::__destruct
SolrObject


Destructor

SolrObject::__construct
SolrObject::getPropertyNames
SolrObject
PHP Manual

SolrObject::__destruct

(PECL solr >= 0.9.2)

SolrObject::__destruct — Destructor

Opis

public void SolrObject::__destruct ( void )

The destructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None.

SolrObject::__construct
SolrObject::getPropertyNames
SolrObject


Returns an array of all the names of the properties

SolrObject::__destruct
SolrObject::offsetExists
SolrObject
PHP Manual

SolrObject::getPropertyNames

(PECL solr >= 0.9.2)

SolrObject::getPropertyNames — Returns an array of all the names of the properties

Opis

public array SolrObject::getPropertyNames ( void )

Returns an array of all the names of the properties

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array.

SolrObject::__destruct
SolrObject::offsetExists
SolrObject


Checks if the property exists

SolrObject::getPropertyNames
SolrObject::offsetGet
SolrObject
PHP Manual

SolrObject::offsetExists

(PECL solr >= 0.9.2)

SolrObject::offsetExists — Checks if the property exists

Opis

public bool SolrObject::offsetExists ( string $property_name )

Checks if the property exists. This is used when the object is treated as an array.

Parametry

property_name

The name of the property.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrObject::getPropertyNames
SolrObject::offsetGet
SolrObject


Used to retrieve a property

SolrObject::offsetExists
SolrObject::offsetSet
SolrObject
PHP Manual

SolrObject::offsetGet

(PECL solr >= 0.9.2)

SolrObject::offsetGet — Used to retrieve a property

Opis

public mixed SolrObject::offsetGet ( string $property_name )

Used to get the value of a property. This is used when the object is treated as an array.

Parametry

property_name

Name of the property.

Zwracane wartości

Returns the property value.

SolrObject::offsetExists
SolrObject::offsetSet
SolrObject


Sets the value for a property

SolrObject::offsetGet
SolrObject::offsetUnset
SolrObject
PHP Manual

SolrObject::offsetSet

(PECL solr >= 0.9.2)

SolrObject::offsetSet — Sets the value for a property

Opis

public void SolrObject::offsetSet ( string $property_name , string $property_value )

Sets the value for a property. This is used when the object is treated as an array. This object is read-only. This should never be attempted.

Parametry

property_name

The name of the property.

property_value

The new value.

Zwracane wartości

None.

SolrObject::offsetGet
SolrObject::offsetUnset
SolrObject


Sets the value for the property

SolrObject::offsetSet
SolrClient
SolrObject
PHP Manual

SolrObject::offsetUnset

(PECL solr >= 0.9.2)

SolrObject::offsetUnset — Sets the value for the property

Opis

public void SolrObject::offsetUnset ( string $property_name )

Sets the value for the property. This is used when the object is treated as an array. This object is read-only. This should never be attempted.

Parametry

property_name

The name of the property.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 SolrObject::offsetUnset() example

<?php
/* ... */
?>

Powyższy przykład wyświetli coś podobnego do:

...

Zobacz też:

  • Classname::Method()

SolrObject::offsetSet
SolrClient
SolrObject


The SolrClient class

(No version information available, might only be in SVN)

Wstęp

Used to send requests to a Solr server. Currently, cloning and serialization of SolrClient instances is not supported.

Krótki opis klasy

final SolrClient {
/* Stałe */
const integer SEARCH_SERVLET_TYPE = 1 ;
const integer UPDATE_SERVLET_TYPE = 2 ;
const integer THREADS_SERVLET_TYPE = 4 ;
const integer PING_SERVLET_TYPE = 8 ;
const integer TERMS_SERVLET_TYPE = 16 ;
const string DEFAULT_SEARCH_SERVLET = select ;
const string DEFAULT_UPDATE_SERVLET = update ;
const string DEFAULT_THREADS_SERVLET = admin/threads ;
const string DEFAULT_PING_SERVLET = admin/ping ;
const string DEFAULT_TERMS_SERVLET = terms ;
/* Metody */
public SolrUpdateResponse addDocument ( SolrInputDocument $doc [, bool $allowDups = false [, int $commitWithin = 0 ]] )
public void addDocuments ( array $docs [, bool $allowDups = false [, int $commitWithin = 0 ]] )
public SolrUpdateResponse commit ([ int $maxSegments = "1" [, bool $waitFlush = true [, bool $waitSearcher = true ]]] )
public __construct ( array $clientOptions )
public SolrUpdateResponse deleteById ( string $id )
public SolrUpdateResponse deleteByIds ( array $ids )
public SolrUpdateResponse deleteByQueries ( array $queries )
public SolrUpdateResponse deleteByQuery ( string $query )
public void __destruct ( void )
public string getDebug ( void )
public array getOptions ( void )
public SolrUpdateResponse optimize ([ int $maxSegments = "1" [, bool $waitFlush = true [, bool $waitSearcher = true ]]] )
public SolrPingResponse ping ( void )
public SolrQueryResponse query ( SolrParams $query )
public void request ( string $raw_request )
public SolrUpdateResponse rollback ( void )
public void setResponseWriter ( string $responseWriter )
public bool setServlet ( int $type , string $value )
public void threads ( void )
}

Stałe predefiniowane

SolrClient::SEARCH_SERVLET_TYPE

Used when updating the search servlet.

SolrClient::UPDATE_SERVLET_TYPE

Used when updating the update servlet.

SolrClient::THREADS_SERVLET_TYPE

Used when updating the threads servlet.

SolrClient::PING_SERVLET_TYPE

Used when updating the ping servlet.

SolrClient::TERMS_SERVLET_TYPE

Used when updating the terms servlet.

SolrClient::DEFAULT_SEARCH_SERVLET

This is the intial value for the search servlet.

SolrClient::DEFAULT_UPDATE_SERVLET

This is the intial value for the update servlet.

SolrClient::DEFAULT_THREADS_SERVLET

This is the intial value for the threads servlet.

SolrClient::DEFAULT_PING_SERVLET

This is the intial value for the ping servlet.

SolrClient::DEFAULT_TERMS_SERVLET

This is the intial value for the terms servlet used for the TermsComponent

Spis treści

  • SolrClient::addDocument — Adds a document to the index
  • SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index
  • SolrClient::commit — Finalizes all add/deletes made to the index
  • SolrClient::__construct — Constructor for the SolrClient object
  • SolrClient::deleteById — Delete by Id
  • SolrClient::deleteByIds — Deletes by Ids
  • SolrClient::deleteByQueries — Removes all documents matching any of the queries
  • SolrClient::deleteByQuery — Deletes all documents matching the given query
  • SolrClient::__destruct — Destructor for SolrClient
  • SolrClient::getDebug — Returns the debug data for the last connection attempt
  • SolrClient::getOptions — Returns the client options set internally
  • SolrClient::optimize — Defragments the index
  • SolrClient::ping — Checks if Solr server is still up
  • SolrClient::query — Sends a query to the server
  • SolrClient::request — Sends a raw update request
  • SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit
  • SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr
  • SolrClient::setServlet — Changes the specified servlet type to a new value
  • SolrClient::threads — Checks the threads status
SolrObject::offsetUnset
SolrClient::addDocument
Solr


Adds a document to the index

SolrClient
SolrClient::addDocuments
SolrClient
PHP Manual

SolrClient::addDocument

(PECL solr >= 0.9.2)

SolrClient::addDocument — Adds a document to the index

Opis

public SolrUpdateResponse SolrClient::addDocument ( SolrInputDocument $doc [, bool $allowDups = false [, int $commitWithin = 0 ]] )

This method adds a document to the index.

Parametry

doc

The SolrInputDocument instance.

allowDups

If FALSE duplicates will be overwritten.

commitWithin

Number of milliseconds within which to commit this document. Available since Solr 1.4

Zwracane wartości

Returns a SolrUpdateResponse object or throws a SolrClientException on failure.

Przykłady

Przykład #1 SolrClient::addDocument() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

print_r($updateResponse->getResponse());

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

Zobacz też:

  • SolrClient::addDocuments() - Adds a collection of SolrInputDocument instances to the index

SolrClient
SolrClient::addDocuments
SolrClient


Adds a collection of SolrInputDocument instances to the index

SolrClient::addDocument
SolrClient::commit
SolrClient
PHP Manual

SolrClient::addDocuments

(PECL solr >= 0.9.2)

SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index

Opis

public void SolrClient::addDocuments ( array $docs [, bool $allowDups = false [, int $commitWithin = 0 ]] )

Adds a collection of documents to the index.

Parametry

docs

An array containing the collection of SolrInputDocument instances. This array must be an actual variable.

allowDups

If FALSE duplicates will be overwritten.

commitWithin

Number of milliseconds within which to commit the documents to the index. This was only available since Solr 1.4

Zwracane wartości

Returns a SolrUpdateResponse object on success and throws a SolrClientException on failure.

Przykłady

Przykład #1 SolrClient::addDocuments() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$doc2 = clone $doc;

$doc2->deleteField('id');
$doc2->addField('id', 334456);

$docs = array($doc, $doc2);

$updateResponse = $client->addDocuments($docs);

print_r($updateResponse->getResponse());

?>

Powyższy przykład wyświetli coś podobnego do:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

)

Zobacz też:

  • SolrClient::addDocument() - Adds a document to the index

SolrClient::addDocument
SolrClient::commit
SolrClient


Finalizes all add/deletes made to the index

SolrClient::addDocuments
SolrClient::__construct
SolrClient
PHP Manual

SolrClient::commit

(PECL solr >= 0.9.2)

SolrClient::commit — Finalizes all add/deletes made to the index

Opis

public SolrUpdateResponse SolrClient::commit ([ int $maxSegments = "1" [, bool $waitFlush = true [, bool $waitSearcher = true ]]] )

This method finalizes all add/deletes made to the index.

Parametry

maxSegments

Optimizes down to at most this number of segments. Since Solr 1.3

waitFlush

Block until index changes are flushed to disk.

waitSearcher

Block until a new searcher is opened and registered as the main query searcher, making the changes visible.

Zwracane wartości

Returns a SolrUpdateResponse object on success or throws a SolrClientException on failure.

Zobacz też:

  • SolrClient::optimize() - Defragments the index
  • SolrClient::rollback() - Rollbacks all add/deletes made to the index since the last commit

SolrClient::addDocuments
SolrClient::__construct
SolrClient


Constructor for the SolrClient object

SolrClient::commit
SolrClient::deleteById
SolrClient
PHP Manual

SolrClient::__construct

(PECL solr >= 0.9.2)

SolrClient::__construct — Constructor for the SolrClient object

Opis

public SolrClient::__construct ( array $clientOptions )

Constructor for the SolrClient object

Parametry

clientOptions

This is an array containing one of the following keys :

- secure          (Boolean value indicating whether or not to connect in secure mode)
 - hostname        (The hostname for the Solr server)
 - port            (The port number)
 - path            (The path to solr)
 - wt              (The name of the response writer e.g. xml, phpnative)
 - login           (The username used for HTTP Authentication, if any)
 - password        (The HTTP Authentication password)
 - proxy_host      (The hostname for the proxy server, if any)
 - proxy_port      (The proxy port)
 - proxy_login     (The proxy username)
 - proxy_password  (The proxy password)
 - timeout         (This is maximum time in seconds allowed for the http data transfer operation. Default is 30 seconds)
 - ssl_cert        (File name to a PEM-formatted file containing the private key + private certificate (concatenated in that order) )
 - ssl_key         (File name to a PEM-formatted private key file only)
 - ssl_keypassword (Password for private key)
 - ssl_cainfo      (Name of file holding one or more CA certificates to verify peer with)
 - ssl_capath      (Name of directory holding multiple CA certificates to verify peer with )

 Please note the if the ssl_cert file only contains the private certificate, you have to specify a separate ssl_key file

 The ssl_keypassword option is required if the ssl_cert or ssl_key options are set.

Przykłady

Przykład #1 SolrClient::__construct() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_PATH_TO_SOLR,
    'wt'       => SOLR_PHP_NATIVE_RESPONSE_WRITER,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

?>

Powyższy przykład wyświetli coś podobnego do:

Zobacz też:

  • SolrClient::getOptions() - Returns the client options set internally

SolrClient::commit
SolrClient::deleteById
SolrClient


Delete by Id

SolrClient::__construct
SolrClient::deleteByIds
SolrClient
PHP Manual

SolrClient::deleteById

(PECL solr >= 0.9.2)

SolrClient::deleteById — Delete by Id

Opis

public SolrUpdateResponse SolrClient::deleteById ( string $id )

Deletes the document with the specified ID. Where ID is the value of the uniqueKey field declared in the schema

Parametry

id

The value of the uniqueKey field declared in the schema

Zwracane wartości

Returns a SolrUpdateResponse on success and throws a SolrClientException on failure.

Zobacz też:

  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

SolrClient::__construct
SolrClient::deleteByIds
SolrClient


Deletes by Ids

SolrClient::deleteById
SolrClient::deleteByQueries
SolrClient
PHP Manual

SolrClient::deleteByIds

(PECL solr >= 0.9.2)

SolrClient::deleteByIds — Deletes by Ids

Opis

public SolrUpdateResponse SolrClient::deleteByIds ( array $ids )

Deletes a collection of documents with the specified set of ids.

Parametry

ids

An array of IDs representing the uniqueKey field declared in the schema for each document to be deleted. This must be an actual php variable.

Zwracane wartości

Returns a SolrUpdateResponse on success and throws a SolrClientException on failure.

Zobacz też:

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

SolrClient::deleteById
SolrClient::deleteByQueries
SolrClient


Removes all documents matching any of the queries

SolrClient::deleteByIds
SolrClient::deleteByQuery
SolrClient
PHP Manual

SolrClient::deleteByQueries

(PECL solr >= 0.9.2)

SolrClient::deleteByQueries — Removes all documents matching any of the queries

Opis

public SolrUpdateResponse SolrClient::deleteByQueries ( array $queries )

Removes all documents matching any of the queries

Parametry

queries

The array of queries. This must be an actual php variable.

Zwracane wartości

Returns a SolrUpdateResponse on success and throws a SolrClientException on failure.

Zobacz też:

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query

SolrClient::deleteByIds
SolrClient::deleteByQuery
SolrClient


Deletes all documents matching the given query

SolrClient::deleteByQueries
SolrClient::__destruct
SolrClient
PHP Manual

SolrClient::deleteByQuery

(PECL solr >= 0.9.2)

SolrClient::deleteByQuery — Deletes all documents matching the given query

Opis

public SolrUpdateResponse SolrClient::deleteByQuery ( string $query )

Deletes all documents matching the given query.

Parametry

query

The query

Zwracane wartości

Returns a SolrUpdateResponse on success and throws a SolrClientException on failure.

Zobacz też:

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

SolrClient::deleteByQueries
SolrClient::__destruct
SolrClient


Destructor for SolrClient

SolrClient::deleteByQuery
SolrClient::getDebug
SolrClient
PHP Manual

SolrClient::__destruct

(PECL solr >= 0.9.2)

SolrClient::__destruct — Destructor for SolrClient

Opis

public void SolrClient::__destruct ( void )

Destructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Destructor for SolrClient

Zobacz też:

  • SolrClient::__construct() - Constructor for the SolrClient object

SolrClient::deleteByQuery
SolrClient::getDebug
SolrClient


Returns the debug data for the last connection attempt

SolrClient::__destruct
SolrClient::getOptions
SolrClient
PHP Manual

SolrClient::getDebug

(PECL solr >= 0.9.7)

SolrClient::getDebug — Returns the debug data for the last connection attempt

Opis

public string SolrClient::getDebug ( void )

Returns the debug data for the last connection attempt

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string on success and null if there is nothing to return.

SolrClient::__destruct
SolrClient::getOptions
SolrClient


Returns the client options set internally

SolrClient::getDebug
SolrClient::optimize
SolrClient
PHP Manual

SolrClient::getOptions

(PECL solr >= 0.9.6)

SolrClient::getOptions — Returns the client options set internally

Opis

public array SolrClient::getOptions ( void )

Returns the client options set internally. Very useful for debugging. The values returned are readonly and can only be set when the object is instantiated.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array containing all the options for the SolrClient object set internally.

Zobacz też:

  • SolrClient::__construct() - Constructor for the SolrClient object

SolrClient::getDebug
SolrClient::optimize
SolrClient


Defragments the index

SolrClient::getOptions
SolrClient::ping
SolrClient
PHP Manual

SolrClient::optimize

(PECL solr >= 0.9.2)

SolrClient::optimize — Defragments the index

Opis

public SolrUpdateResponse SolrClient::optimize ([ int $maxSegments = "1" [, bool $waitFlush = true [, bool $waitSearcher = true ]]] )

Defragments the index for faster search performance.

Parametry

maxSegments

Optimizes down to at most this number of segments. Since Solr 1.3

waitFlush

Block until index changes are flushed to disk.

waitSearcher

Block until a new searcher is opened and registered as the main query searcher, making the changes visible.

Zwracane wartości

Returns a SolrUpdateResponse on success or throws a SolrClientException on failure.

Zobacz też:

  • SolrClient::commit() - Finalizes all add/deletes made to the index
  • SolrClient::rollback() - Rollbacks all add/deletes made to the index since the last commit

SolrClient::getOptions
SolrClient::ping
SolrClient


Checks if Solr server is still up

SolrClient::optimize
SolrClient::query
SolrClient
PHP Manual

SolrClient::ping

(PECL solr >= 0.9.2)

SolrClient::ping — Checks if Solr server is still up

Opis

public SolrPingResponse SolrClient::ping ( void )

Checks if the Solr server is still alive. Sends a HEAD request to the Apache Solr server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a SolrPingResponse object on success and throws a SolrClientException on failure.

Przykłady

Przykład #1 SolrClient::ping() example

<?php
$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$pingresponse = $client->ping();

?>

Powyższy przykład wyświetli coś podobnego do:

SolrClient::optimize
SolrClient::query
SolrClient


Sends a query to the server

SolrClient::ping
SolrClient::request
SolrClient
PHP Manual

SolrClient::query

(PECL solr >= 0.9.2)

SolrClient::query — Sends a query to the server

Opis

public SolrQueryResponse SolrClient::query ( SolrParams $query )

Sends a query to the server.

Parametry

query

A SolrParam object. It is recommended to use SolrQuery for advanced queries.

Zwracane wartości

Returns a SolrQueryResponse object on success and throws a SolrClientException object on failure.

Przykłady

Przykład #1 SolrClient::query() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);

?>

Powyższy przykład wyświetli coś podobnego do:

SolrClient::ping
SolrClient::request
SolrClient


Sends a raw update request

SolrClient::query
SolrClient::rollback
SolrClient
PHP Manual

SolrClient::request

(PECL solr >= 0.9.2)

SolrClient::request — Sends a raw update request

Opis

public void SolrClient::request ( string $raw_request )

Sends a raw XML update request to the server

Parametry

raw_request

An XML string with the raw request to the server.

Zwracane wartości

Returns a SolrUpdateResponse on success. Throws a SolrClientException on failure.

Przykłady

Przykład #1 SolrClient::request() example

<?php
$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$update_response = $client->request("<commit/>");

$response = $update_response->getResponse();

print_r($response);
?>

Powyższy przykład wyświetli coś podobnego do:

...

SolrClient::query
SolrClient::rollback
SolrClient


Rollbacks all add/deletes made to the index since the last commit

SolrClient::request
SolrClient::setResponseWriter
SolrClient
PHP Manual

SolrClient::rollback

(PECL solr >= 0.9.2)

SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit

Opis

public SolrUpdateResponse SolrClient::rollback ( void )

Rollbacks all add/deletes made to the index since the last commit. It neither calls any event listeners nor creates a new searcher.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a SolrUpdateResponse on success or throws a SolrClientException on failure.

Zobacz też:

  • SolrClient::commit() - Finalizes all add/deletes made to the index
  • SolrClient::optimize() - Defragments the index

SolrClient::request
SolrClient::setResponseWriter
SolrClient


Sets the response writer used to prepare the response from Solr

SolrClient::rollback
SolrClient::setServlet
SolrClient
PHP Manual

SolrClient::setResponseWriter

(PECL solr >= 0.9.11)

SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr

Opis

public void SolrClient::setResponseWriter ( string $responseWriter )

Sets the response writer used to prepare the response from Solr

Parametry

responseWriter

One of the following :

- xml
 - phpnative

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SolrClient::setResponseWriter() example

<?php

// This is my custom class for objects
class SolrClass
{
   public $_properties = array();

   public function __get($property_name) {

      if (property_exists($this, $property_name)) {

          return $this->$property_name;

      } else if (isset($_properties[$property_name])) {

          return $_properties[$property_name];
      }

      return null;
   }
}

$options = array
(
  'hostname' => 'localhost',
  'port' => 8983,
  'path' => '/solr/core1'
);

$client = new SolrClient($options);

// This uses the org.apache.solr.request.PHPNativeResponseWriter class on Solr
// Visit the following pages for more details
// https://issues.apache.org/jira/browse/SOLR-1967
// http://wiki.apache.org/solr/QueryResponseWriter
// http://wiki.apache.org/solr/SolPHP
$client->setResponseWriter("phpnative");

//$response = $client->ping();

$query = new SolrQuery();

$query->setQuery("*:*");

$query->set("objectClassName", "SolrClass");

$query->set("objectPropertiesStorageMode", 1); // 0 for independent properties, 1 for combined

try
{

$response = $client->query($query);

$resp = $response->getResponse();

print_r($response);

print_r($resp);

} catch (Exception $e) {

print_r($e);

}

?>

Powyższy przykład wyświetli coś podobnego do:

SolrClient::rollback
SolrClient::setServlet
SolrClient


Changes the specified servlet type to a new value

SolrClient::setResponseWriter
SolrClient::threads
SolrClient
PHP Manual

SolrClient::setServlet

(PECL solr >= 0.9.2)

SolrClient::setServlet — Changes the specified servlet type to a new value

Opis

public bool SolrClient::setServlet ( int $type , string $value )

Changes the specified servlet type to a new value

Parametry

type

One of the following :

- SolrClient::SEARCH_SERVLET_TYPE
 - SolrClient::UPDATE_SERVLET_TYPE
 - SolrClient::THREADS_SERVLET_TYPE
 - SolrClient::PING_SERVLET_TYPE
 - SolrClient::TERMS_SERVLET_TYPE

value

The new value for the servlet

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrClient::setResponseWriter
SolrClient::threads
SolrClient


Checks the threads status

SolrClient::setServlet
SolrResponse
SolrClient
PHP Manual

SolrClient::threads

(PECL solr >= 0.9.2)

SolrClient::threads — Checks the threads status

Opis

public void SolrClient::threads ( void )

Checks the threads status

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a SolrGenericResponse object.

SolrClient::setServlet
SolrResponse
SolrClient


The SolrResponse class

(No version information available, might only be in SVN)

Wstęp

Represents a response from the Solr server.

Krótki opis klasy

abstract SolrResponse {
/* Stałe */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Właściwości */
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Metody */
public string getDigestedResponse ( void )
public int getHttpStatus ( void )
public string getHttpStatusMessage ( void )
public string getRawRequest ( void )
public string getRawRequestHeaders ( void )
public string getRawResponse ( void )
public string getRawResponseHeaders ( void )
public string getRequestUrl ( void )
public SolrObject getResponse ( void )
public bool setParseMode ([ int $parser_mode = 0 ] )
public bool success ( void )
}

Właściwości

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request.

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server.

http_raw_response

The response message from the server.

http_digested_response

The response in PHP serialized format.

Stałe predefiniowane

SolrResponse Class Constants

SolrResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Spis treści

  • SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data
  • SolrResponse::getHttpStatus — Returns the HTTP status of the response
  • SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status
  • SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
  • SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server
  • SolrResponse::getRawResponse — Returns the raw response from the server
  • SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server
  • SolrResponse::getRequestUrl — Returns the full URL the request was sent to
  • SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
  • SolrResponse::setParseMode — Sets the parse mode
  • SolrResponse::success — Was the request a success
SolrClient::threads
SolrResponse::getDigestedResponse
Solr


Returns the XML response as serialized PHP data

SolrResponse
SolrResponse::getHttpStatus
SolrResponse
PHP Manual

SolrResponse::getDigestedResponse

(PECL solr >= 0.9.2)

SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data

Opis

public string SolrResponse::getDigestedResponse ( void )

Returns the XML response as serialized PHP data

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the XML response as serialized PHP data

SolrResponse
SolrResponse::getHttpStatus
SolrResponse


Returns the HTTP status of the response

SolrResponse::getDigestedResponse
SolrResponse::getHttpStatusMessage
SolrResponse
PHP Manual

SolrResponse::getHttpStatus

(PECL solr >= 0.9.2)

SolrResponse::getHttpStatus — Returns the HTTP status of the response

Opis

public int SolrResponse::getHttpStatus ( void )

Returns the HTTP status of the response.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the HTTP status of the response.

SolrResponse::getDigestedResponse
SolrResponse::getHttpStatusMessage
SolrResponse


Returns more details on the HTTP status

SolrResponse::getHttpStatus
SolrResponse::getRawRequest
SolrResponse
PHP Manual

SolrResponse::getHttpStatusMessage

(PECL solr >= 0.9.2)

SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status

Opis

public string SolrResponse::getHttpStatusMessage ( void )

Returns more details on the HTTP status.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns more details on the HTTP status

SolrResponse::getHttpStatus
SolrResponse::getRawRequest
SolrResponse


Returns the raw request sent to the Solr server

SolrResponse::getHttpStatusMessage
SolrResponse::getRawRequestHeaders
SolrResponse
PHP Manual

SolrResponse::getRawRequest

(PECL solr >= 0.9.2)

SolrResponse::getRawRequest — Returns the raw request sent to the Solr server

Opis

public string SolrResponse::getRawRequest ( void )

Returns the raw request sent to the Solr server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the raw request sent to the Solr server

SolrResponse::getHttpStatusMessage
SolrResponse::getRawRequestHeaders
SolrResponse


Returns the raw request headers sent to the Solr server

SolrResponse::getRawRequest
SolrResponse::getRawResponse
SolrResponse
PHP Manual

SolrResponse::getRawRequestHeaders

(PECL solr >= 0.9.2)

SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server

Opis

public string SolrResponse::getRawRequestHeaders ( void )

Returns the raw request headers sent to the Solr server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the raw request headers sent to the Solr server

SolrResponse::getRawRequest
SolrResponse::getRawResponse
SolrResponse


Returns the raw response from the server

SolrResponse::getRawRequestHeaders
SolrResponse::getRawResponseHeaders
SolrResponse
PHP Manual

SolrResponse::getRawResponse

(PECL solr >= 0.9.2)

SolrResponse::getRawResponse — Returns the raw response from the server

Opis

public string SolrResponse::getRawResponse ( void )

Returns the raw response from the server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the raw response from the server.

SolrResponse::getRawRequestHeaders
SolrResponse::getRawResponseHeaders
SolrResponse


Returns the raw response headers from the server

SolrResponse::getRawResponse
SolrResponse::getRequestUrl
SolrResponse
PHP Manual

SolrResponse::getRawResponseHeaders

(PECL solr >= 0.9.2)

SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server

Opis

public string SolrResponse::getRawResponseHeaders ( void )

Returns the raw response headers from the server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the raw response headers from the server.

SolrResponse::getRawResponse
SolrResponse::getRequestUrl
SolrResponse


Returns the full URL the request was sent to

SolrResponse::getRawResponseHeaders
SolrResponse::getResponse
SolrResponse
PHP Manual

SolrResponse::getRequestUrl

(PECL solr >= 0.9.2)

SolrResponse::getRequestUrl — Returns the full URL the request was sent to

Opis

public string SolrResponse::getRequestUrl ( void )

Returns the full URL the request was sent to.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the full URL the request was sent to

SolrResponse::getRawResponseHeaders
SolrResponse::getResponse
SolrResponse


Returns a SolrObject representing the XML response from the server

SolrResponse::getRequestUrl
SolrResponse::setParseMode
SolrResponse
PHP Manual

SolrResponse::getResponse

(PECL solr >= 0.9.2)

SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server

Opis

public SolrObject SolrResponse::getResponse ( void )

Returns a SolrObject representing the XML response from the server.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a SolrObject representing the XML response from the server

SolrResponse::getRequestUrl
SolrResponse::setParseMode
SolrResponse


Sets the parse mode

SolrResponse::getResponse
SolrResponse::success
SolrResponse
PHP Manual

SolrResponse::setParseMode

(PECL solr >= 0.9.2)

SolrResponse::setParseMode — Sets the parse mode

Opis

public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )

Sets the parse mode.

Parametry

parser_mode

SolrResponse::PARSE_SOLR_DOC parses documents in SolrDocument instances. SolrResponse::PARSE_SOLR_OBJ parses document into SolrObjects.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SolrResponse::getResponse
SolrResponse::success
SolrResponse


Was the request a success

SolrResponse::setParseMode
SolrQueryResponse
SolrResponse
PHP Manual

SolrResponse::success

(PECL solr >= 0.9.2)

SolrResponse::success — Was the request a success

Opis

public bool SolrResponse::success ( void )

Used to check if the request to the server was successful.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if it was successful and FALSE if it was not.

SolrResponse::setParseMode
SolrQueryResponse
SolrResponse


The SolrQueryResponse class

(No version information available, might only be in SVN)

Wstęp

Represents a response to a query request.

Krótki opis klasy

final SolrQueryResponse extends SolrResponse {
/* Stałe */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Właściwości */
/* Metody */
public __construct ( void )
public void __destruct ( void )
/* Metody dziedziczone */
public string SolrResponse::getDigestedResponse ( void )
public int SolrResponse::getHttpStatus ( void )
public string SolrResponse::getHttpStatusMessage ( void )
public string SolrResponse::getRawRequest ( void )
public string SolrResponse::getRawRequestHeaders ( void )
public string SolrResponse::getRawResponse ( void )
public string SolrResponse::getRawResponseHeaders ( void )
public string SolrResponse::getRequestUrl ( void )
public SolrObject SolrResponse::getResponse ( void )
public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )
public bool SolrResponse::success ( void )
}

Właściwości

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server

http_raw_response

The response message from the server

http_digested_response

The response in PHP serialized format.

Stałe predefiniowane

SolrQueryResponse Class constants

SolrQueryResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrQueryResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Spis treści

  • SolrQueryResponse::__construct — Constructor
  • SolrQueryResponse::__destruct — Destructor
SolrResponse::success
SolrQueryResponse::__construct
Solr


Constructor

SolrQueryResponse
SolrQueryResponse::__destruct
SolrQueryResponse
PHP Manual

SolrQueryResponse::__construct

(PECL solr >= 0.9.2)

SolrQueryResponse::__construct — Constructor

Opis

public SolrQueryResponse::__construct ( void )

Constructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrQueryResponse
SolrQueryResponse::__destruct
SolrQueryResponse


Destructor

SolrQueryResponse::__construct
SolrUpdateResponse
SolrQueryResponse
PHP Manual

SolrQueryResponse::__destruct

(PECL solr >= 0.9.2)

SolrQueryResponse::__destruct — Destructor

Opis

public void SolrQueryResponse::__destruct ( void )

Destructor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrQueryResponse::__construct
SolrUpdateResponse
SolrQueryResponse


The SolrUpdateResponse class

(No version information available, might only be in SVN)

Wstęp

Represents a response to an update request.

Krótki opis klasy

final SolrUpdateResponse extends SolrResponse {
/* Stałe */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Właściwości */
/* Metody */
public __construct ( void )
public void __destruct ( void )
/* Metody dziedziczone */
public string SolrResponse::getDigestedResponse ( void )
public int SolrResponse::getHttpStatus ( void )
public string SolrResponse::getHttpStatusMessage ( void )
public string SolrResponse::getRawRequest ( void )
public string SolrResponse::getRawRequestHeaders ( void )
public string SolrResponse::getRawResponse ( void )
public string SolrResponse::getRawResponseHeaders ( void )
public string SolrResponse::getRequestUrl ( void )
public SolrObject SolrResponse::getResponse ( void )
public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )
public bool SolrResponse::success ( void )
}

Właściwości

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server

http_raw_response

The response message from the server

http_digested_response

The response in PHP serialized format.

Stałe predefiniowane

SolrUpdateResponse Class Constants

SolrUpdateResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrUpdateResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Spis treści

  • SolrUpdateResponse::__construct — Constructor
  • SolrUpdateResponse::__destruct — Destructor
SolrQueryResponse::__destruct
SolrUpdateResponse::__construct
Solr


Constructor

SolrUpdateResponse
SolrUpdateResponse::__destruct
SolrUpdateResponse
PHP Manual

SolrUpdateResponse::__construct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__construct — Constructor

Opis

public SolrUpdateResponse::__construct ( void )

Constructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrUpdateResponse
SolrUpdateResponse::__destruct
SolrUpdateResponse


Destructor

SolrUpdateResponse::__construct
SolrPingResponse
SolrUpdateResponse
PHP Manual

SolrUpdateResponse::__destruct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__destruct — Destructor

Opis

public void SolrUpdateResponse::__destruct ( void )

Destructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrUpdateResponse::__construct
SolrPingResponse
SolrUpdateResponse


The SolrPingResponse class

(No version information available, might only be in SVN)

Wstęp

Represents a response to a ping request to the server

Krótki opis klasy

final SolrPingResponse extends SolrResponse {
/* Stałe */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Właściwości */
/* Metody */
public __construct ( void )
public void __destruct ( void )
public string getResponse ( void )
/* Metody dziedziczone */
public string SolrResponse::getDigestedResponse ( void )
public int SolrResponse::getHttpStatus ( void )
public string SolrResponse::getHttpStatusMessage ( void )
public string SolrResponse::getRawRequest ( void )
public string SolrResponse::getRawRequestHeaders ( void )
public string SolrResponse::getRawResponse ( void )
public string SolrResponse::getRawResponseHeaders ( void )
public string SolrResponse::getRequestUrl ( void )
public SolrObject SolrResponse::getResponse ( void )
public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )
public bool SolrResponse::success ( void )
}

Właściwości

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server

http_raw_response

The response message from the server

http_digested_response

The response in PHP serialized format.

Stałe predefiniowane

SolrPingResponse Class Constants

SolrPingResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrPingResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Spis treści

  • SolrPingResponse::__construct — Constructor
  • SolrPingResponse::__destruct — Destructor
  • SolrPingResponse::getResponse — Returns the response from the server
SolrUpdateResponse::__destruct
SolrPingResponse::__construct
Solr


Constructor

SolrPingResponse
SolrPingResponse::__destruct
SolrPingResponse
PHP Manual

SolrPingResponse::__construct

(PECL solr >= 0.9.2)

SolrPingResponse::__construct — Constructor

Opis

public SolrPingResponse::__construct ( void )

Constructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrPingResponse
SolrPingResponse::__destruct
SolrPingResponse


Destructor

SolrPingResponse::__construct
SolrPingResponse::getResponse
SolrPingResponse
PHP Manual

SolrPingResponse::__destruct

(PECL solr >= 0.9.2)

SolrPingResponse::__destruct — Destructor

Opis

public void SolrPingResponse::__destruct ( void )

Destructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrPingResponse::__construct
SolrPingResponse::getResponse
SolrPingResponse


Returns the response from the server

SolrPingResponse::__destruct
SolrGenericResponse
SolrPingResponse
PHP Manual

SolrPingResponse::getResponse

(PECL solr >= 0.9.2)

SolrPingResponse::getResponse — Returns the response from the server

Opis

public string SolrPingResponse::getResponse ( void )

Returns the response from the server. This should be empty because the request as a HEAD request.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an empty string.

SolrPingResponse::__destruct
SolrGenericResponse
SolrPingResponse


The SolrGenericResponse class

(No version information available, might only be in SVN)

Wstęp

Represents a response from the solr server.

Krótki opis klasy

final SolrGenericResponse extends SolrResponse {
/* Stałe */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Właściwości */
/* Metody */
public __construct ( void )
public void __destruct ( void )
/* Metody dziedziczone */
public string SolrResponse::getDigestedResponse ( void )
public int SolrResponse::getHttpStatus ( void )
public string SolrResponse::getHttpStatusMessage ( void )
public string SolrResponse::getRawRequest ( void )
public string SolrResponse::getRawRequestHeaders ( void )
public string SolrResponse::getRawResponse ( void )
public string SolrResponse::getRawResponseHeaders ( void )
public string SolrResponse::getRequestUrl ( void )
public SolrObject SolrResponse::getResponse ( void )
public bool SolrResponse::setParseMode ([ int $parser_mode = 0 ] )
public bool SolrResponse::success ( void )
}

Właściwości

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server

http_raw_response

The response message from the server

http_digested_response

The response in PHP serialized format.

Stałe predefiniowane

SolrGenericResponse Class constants

SolrGenericResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrGenericResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Spis treści

  • SolrGenericResponse::__construct — Constructor
  • SolrGenericResponse::__destruct — Destructor
SolrPingResponse::getResponse
SolrGenericResponse::__construct
Solr


Constructor

SolrGenericResponse
SolrGenericResponse::__destruct
SolrGenericResponse
PHP Manual

SolrGenericResponse::__construct

(PECL solr >= 0.9.2)

SolrGenericResponse::__construct — Constructor

Opis

public SolrGenericResponse::__construct ( void )

Constructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrGenericResponse
SolrGenericResponse::__destruct
SolrGenericResponse


Destructor

SolrGenericResponse::__construct
SolrParams
SolrGenericResponse
PHP Manual

SolrGenericResponse::__destruct

(PECL solr >= 0.9.2)

SolrGenericResponse::__destruct — Destructor

Opis

public void SolrGenericResponse::__destruct ( void )

Destructor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrGenericResponse::__construct
SolrParams
SolrGenericResponse


The SolrParams class

(No version information available, might only be in SVN)

Wstęp

Represents a collection of name-value pairs sent to the Solr server during a request.

Krótki opis klasy

abstract SolrParams implements Serializable {
/* Metody */
final public SolrParams add ( string $name , string $value )
public SolrParams addParam ( string $name , string $value )
final public mixed get ( string $param_name )
final public mixed getParam ([ string $param_name ] )
final public array getParams ( void )
final public array getPreparedParams ( void )
final public string serialize ( void )
final public void set ( string $name , string $value )
public SolrParams setParam ( string $name , string $value )
final public string toString ([ bool $url_encode = false ] )
final public void unserialize ( string $serialized )
}

Spis treści

  • SolrParams::add — This is an alias for SolrParams::addParam
  • SolrParams::addParam — Adds a parameter to the object
  • SolrParams::get — This is an alias for SolrParams::getParam
  • SolrParams::getParam — Returns a parameter value
  • SolrParams::getParams — Returns an array of non URL-encoded parameters
  • SolrParams::getPreparedParams — Returns an array of URL-encoded parameters
  • SolrParams::serialize — Used for custom serialization
  • SolrParams::set — An alias of SolrParams::setParam
  • SolrParams::setParam — Sets the parameter to the specified value
  • SolrParams::toString — Returns all the name-value pair parameters in the object
  • SolrParams::unserialize — Used for custom serialization
SolrGenericResponse::__destruct
SolrParams::add
Solr


This is an alias for SolrParams::addParam

SolrParams
SolrParams::addParam
SolrParams
PHP Manual

SolrParams::add

(PECL solr >= 0.9.2)

SolrParams::add — This is an alias for SolrParams::addParam

Opis

final public SolrParams SolrParams::add ( string $name , string $value )

This is an alias for SolrParams::addParam

Parametry

name

The name of the parameter

value

The value of the parameter

Zwracane wartości

Returns a SolrParams instance on success

SolrParams
SolrParams::addParam
SolrParams


Adds a parameter to the object

SolrParams::add
SolrParams::get
SolrParams
PHP Manual

SolrParams::addParam

(PECL solr >= 0.9.2)

SolrParams::addParam — Adds a parameter to the object

Opis

public SolrParams SolrParams::addParam ( string $name , string $value )

Adds a parameter to the object. This is used for parameters that can be specified multiple times.

Parametry

name

Name of parameter

value

Value of parameter

Zwracane wartości

Returns a SolrParam object on success and FALSE on failure.

SolrParams::add
SolrParams::get
SolrParams


This is an alias for SolrParams::getParam

SolrParams::addParam
SolrParams::getParam
SolrParams
PHP Manual

SolrParams::get

(PECL solr >= 0.9.2)

SolrParams::get — This is an alias for SolrParams::getParam

Opis

final public mixed SolrParams::get ( string $param_name )

This is an alias for SolrParams::getParam

Parametry

param_name

Then name of the parameter

Zwracane wartości

Returns an array or string depending on the type of parameter

SolrParams::addParam
SolrParams::getParam
SolrParams


Returns a parameter value

SolrParams::get
SolrParams::getParams
SolrParams
PHP Manual

SolrParams::getParam

(PECL solr >= 0.9.2)

SolrParams::getParam — Returns a parameter value

Opis

final public mixed SolrParams::getParam ([ string $param_name ] )

Returns a parameter with name param_name

Parametry

param_name

The name of the parameter

Zwracane wartości

Returns a string or an array depending on the type of the parameter

SolrParams::get
SolrParams::getParams
SolrParams


Returns an array of non URL-encoded parameters

SolrParams::getParam
SolrParams::getPreparedParams
SolrParams
PHP Manual

SolrParams::getParams

(PECL solr >= 0.9.2)

SolrParams::getParams — Returns an array of non URL-encoded parameters

Opis

final public array SolrParams::getParams ( void )

Returns an array of non URL-encoded parameters

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array of non URL-encoded parameters

SolrParams::getParam
SolrParams::getPreparedParams
SolrParams


Returns an array of URL-encoded parameters

SolrParams::getParams
SolrParams::serialize
SolrParams
PHP Manual

SolrParams::getPreparedParams

(PECL solr >= 0.9.2)

SolrParams::getPreparedParams — Returns an array of URL-encoded parameters

Opis

final public array SolrParams::getPreparedParams ( void )

Returns an array on URL-encoded parameters

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on URL-encoded parameters

SolrParams::getParams
SolrParams::serialize
SolrParams


Used for custom serialization

SolrParams::getPreparedParams
SolrParams::set
SolrParams
PHP Manual

SolrParams::serialize

(PECL solr >= 0.9.2)

SolrParams::serialize — Used for custom serialization

Opis

final public string SolrParams::serialize ( void )

Used for custom serialization

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Used for custom serialization

SolrParams::getPreparedParams
SolrParams::set
SolrParams


An alias of SolrParams::setParam

SolrParams::serialize
SolrParams::setParam
SolrParams
PHP Manual

SolrParams::set

(PECL solr >= 0.9.2)

SolrParams::set — An alias of SolrParams::setParam

Opis

final public void SolrParams::set ( string $name , string $value )

An alias of SolrParams::setParam

Parametry

name

Then name of the parameter

value

The parameter value

Zwracane wartości

Returns an instance of the SolrParams object on success

SolrParams::serialize
SolrParams::setParam
SolrParams


Sets the parameter to the specified value

SolrParams::set
SolrParams::toString
SolrParams
PHP Manual

SolrParams::setParam

(PECL solr >= 0.9.2)

SolrParams::setParam — Sets the parameter to the specified value

Opis

public SolrParams SolrParams::setParam ( string $name , string $value )

Sets the query parameter to the specified value. This is used for parameters that can only be specified once. Subsequent calls with the same parameter name will override the existing value

Parametry

name

Name of the parameter

value

Value of the parameter

Zwracane wartości

Returns a SolrParam object on success and FALSE on value.

Przykłady

Przykład #1 SolrParams::setParam() example

<?php

$param = new SolrParam();

$param->setParam('q', 'solr')->setParam('rows', 2);

?>

Powyższy przykład wyświetli coś podobnego do:

SolrParams::set
SolrParams::toString
SolrParams


Returns all the name-value pair parameters in the object

SolrParams::setParam
SolrParams::unserialize
SolrParams
PHP Manual

SolrParams::toString

(PECL solr >= 0.9.2)

SolrParams::toString — Returns all the name-value pair parameters in the object

Opis

final public string SolrParams::toString ([ bool $url_encode = false ] )

Returns all the name-value pair parameters in the object

Parametry

url_encode

Whether to return URL-encoded values

Zwracane wartości

Returns a string on success and FALSE on failure.

SolrParams::setParam
SolrParams::unserialize
SolrParams


Used for custom serialization

SolrParams::toString
SolrModifiableParams
SolrParams
PHP Manual

SolrParams::unserialize

(PECL solr >= 0.9.2)

SolrParams::unserialize — Used for custom serialization

Opis

final public void SolrParams::unserialize ( string $serialized )

Used for custom serialization

Parametry

serialized

The serialized representation of the object

Zwracane wartości

None

SolrParams::toString
SolrModifiableParams
SolrParams


The SolrModifiableParams class

(No version information available, might only be in SVN)

Wstęp

Represents a collection of name-value pairs sent to the Solr server during a request.

Krótki opis klasy

SolrModifiableParams extends SolrParams implements Serializable {
/* Metody */
public __construct ( void )
public void __destruct ( void )
/* Metody dziedziczone */
final public SolrParams SolrParams::add ( string $name , string $value )
public SolrParams SolrParams::addParam ( string $name , string $value )
final public mixed SolrParams::get ( string $param_name )
final public mixed SolrParams::getParam ([ string $param_name ] )
final public array SolrParams::getParams ( void )
final public array SolrParams::getPreparedParams ( void )
final public string SolrParams::serialize ( void )
final public void SolrParams::set ( string $name , string $value )
public SolrParams SolrParams::setParam ( string $name , string $value )
final public string SolrParams::toString ([ bool $url_encode = false ] )
final public void SolrParams::unserialize ( string $serialized )
}

Spis treści

  • SolrModifiableParams::__construct — Constructor
  • SolrModifiableParams::__destruct — Destructor
SolrParams::unserialize
SolrModifiableParams::__construct
Solr


Constructor

SolrModifiableParams
SolrModifiableParams::__destruct
SolrModifiableParams
PHP Manual

SolrModifiableParams::__construct

(PECL solr >= 0.9.2)

SolrModifiableParams::__construct — Constructor

Opis

public SolrModifiableParams::__construct ( void )

Constructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrModifiableParams
SolrModifiableParams::__destruct
SolrModifiableParams


Destructor

SolrModifiableParams::__construct
SolrQuery
SolrModifiableParams
PHP Manual

SolrModifiableParams::__destruct

(PECL solr >= 0.9.2)

SolrModifiableParams::__destruct — Destructor

Opis

public void SolrModifiableParams::__destruct ( void )

Destructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None

SolrModifiableParams::__construct
SolrQuery
SolrModifiableParams


The SolrQuery class

(No version information available, might only be in SVN)

Wstęp

Represents a collection of name-value pairs sent to the Solr server during a request.

Krótki opis klasy

SolrQuery extends SolrModifiableParams implements Serializable {
/* Stałe */
const integer ORDER_ASC = 0 ;
const integer ORDER_DESC = 1 ;
const integer FACET_SORT_INDEX = 0 ;
const integer FACET_SORT_COUNT = 1 ;
const integer TERMS_SORT_INDEX = 0 ;
const integer TERMS_SORT_COUNT = 1 ;
/* Właściwości */
/* Metody */
public SolrQuery addFacetDateField ( string $dateField )
public SolrQuery addFacetDateOther ( string $value [, string $field_override ] )
public SolrQuery addFacetField ( string $field )
public SolrQuery addFacetQuery ( string $facetQuery )
public SolrQuery addField ( string $field )
public SolrQuery addFilterQuery ( string $fq )
public SolrQuery addHighlightField ( string $field )
public SolrQuery addMltField ( string $field )
public SolrQuery addMltQueryField ( string $field , float $boost )
public SolrQuery addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] )
public SolrQuery addStatsFacet ( string $field )
public SolrQuery addStatsField ( string $field )
public __construct ([ string $q ] )
public void __destruct ( void )
public bool getFacet ( void )
public string getFacetDateEnd ([ string $field_override ] )
public array getFacetDateFields ( void )
public string getFacetDateGap ([ string $field_override ] )
public string getFacetDateHardEnd ([ string $field_override ] )
public array getFacetDateOther ([ string $field_override ] )
public string getFacetDateStart ([ string $field_override ] )
public array getFacetFields ( void )
public int getFacetLimit ([ string $field_override ] )
public string getFacetMethod ([ string $field_override ] )
public int getFacetMinCount ([ string $field_override ] )
public bool getFacetMissing ([ string $field_override ] )
public int getFacetOffset ([ string $field_override ] )
public string getFacetPrefix ([ string $field_override ] )
public array getFacetQueries ( void )
public int getFacetSort ([ string $field_override ] )
public array getFields ( void )
public array getFilterQueries ( void )
public bool getHighlight ( void )
public string getHighlightAlternateField ([ string $field_override ] )
public array getHighlightFields ( void )
public string getHighlightFormatter ([ string $field_override ] )
public string getHighlightFragmenter ([ string $field_override ] )
public int getHighlightFragsize ([ string $field_override ] )
public bool getHighlightHighlightMultiTerm ( void )
public int getHighlightMaxAlternateFieldLength ([ string $field_override ] )
public int getHighlightMaxAnalyzedChars ( void )
public bool getHighlightMergeContiguous ([ string $field_override ] )
public int getHighlightRegexMaxAnalyzedChars ( void )
public string getHighlightRegexPattern ( void )
public float getHighlightRegexSlop ( void )
public bool getHighlightRequireFieldMatch ( void )
public string getHighlightSimplePost ([ string $field_override ] )
public string getHighlightSimplePre ([ string $field_override ] )
public int getHighlightSnippets ([ string $field_override ] )
public bool getHighlightUsePhraseHighlighter ( void )
public bool getMlt ( void )
public bool getMltBoost ( void )
public int getMltCount ( void )
public array getMltFields ( void )
public int getMltMaxNumQueryTerms ( void )
public int getMltMaxNumTokens ( void )
public int getMltMaxWordLength ( void )
public int getMltMinDocFrequency ( void )
public int getMltMinTermFrequency ( void )
public int getMltMinWordLength ( void )
public array getMltQueryFields ( void )
public string getQuery ( void )
public int getRows ( void )
public array getSortFields ( void )
public int getStart ( void )
public bool getStats ( void )
public array getStatsFacets ( void )
public array getStatsFields ( void )
public bool getTerms ( void )
public string getTermsField ( void )
public bool getTermsIncludeLowerBound ( void )
public bool getTermsIncludeUpperBound ( void )
public int getTermsLimit ( void )
public string getTermsLowerBound ( void )
public int getTermsMaxCount ( void )
public int getTermsMinCount ( void )
public string getTermsPrefix ( void )
public bool getTermsReturnRaw ( void )
public int getTermsSort ( void )
public string getTermsUpperBound ( void )
public int getTimeAllowed ( void )
public SolrQuery removeFacetDateField ( string $field )
public SolrQuery removeFacetDateOther ( string $value [, string $field_override ] )
public SolrQuery removeFacetField ( string $field )
public SolrQuery removeFacetQuery ( string $value )
public SolrQuery removeField ( string $field )
public SolrQuery removeFilterQuery ( string $fq )
public SolrQuery removeHighlightField ( string $field )
public SolrQuery removeMltField ( string $field )
public SolrQuery removeMltQueryField ( string $queryField )
public SolrQuery removeSortField ( string $field )
public SolrQuery removeStatsFacet ( string $value )
public SolrQuery removeStatsField ( string $field )
public SolrQuery setEchoHandler ( bool $flag )
public SolrQuery setEchoParams ( string $type )
public SolrQuery setExplainOther ( string $query )
public SolrQuery setFacet ( bool $flag )
public SolrQuery setFacetDateEnd ( string $value [, string $field_override ] )
public SolrQuery setFacetDateGap ( string $value [, string $field_override ] )
public SolrQuery setFacetDateHardEnd ( bool $value [, string $field_override ] )
public SolrQuery setFacetDateStart ( string $value [, string $field_override ] )
public SolrQuery setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] )
public SolrQuery setFacetLimit ( int $limit [, string $field_override ] )
public SolrQuery setFacetMethod ( string $method [, string $field_override ] )
public SolrQuery setFacetMinCount ( int $mincount [, string $field_override ] )
public SolrQuery setFacetMissing ( bool $flag [, string $field_override ] )
public SolrQuery setFacetOffset ( int $offset [, string $field_override ] )
public SolrQuery setFacetPrefix ( string $prefix [, string $field_override ] )
public SolrQuery setFacetSort ( int $facetSort [, string $field_override ] )
public SolrQuery setHighlight ( bool $flag )
public SolrQuery setHighlightAlternateField ( string $field [, string $field_override ] )
public SolrQuery setHighlightFormatter ( string $formatter [, string $field_override ] )
public SolrQuery setHighlightFragmenter ( string $fragmenter [, string $field_override ] )
public SolrQuery setHighlightFragsize ( int $size [, string $field_override ] )
public SolrQuery setHighlightHighlightMultiTerm ( bool $flag )
public SolrQuery setHighlightMaxAlternateFieldLength ( int $fieldLength [, string $field_override ] )
public SolrQuery setHighlightMaxAnalyzedChars ( int $value )
public SolrQuery setHighlightMergeContiguous ( bool $flag [, string $field_override ] )
public SolrQuery setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars )
public SolrQuery setHighlightRegexPattern ( string $value )
public SolrQuery setHighlightRegexSlop ( float $factor )
public SolrQuery setHighlightRequireFieldMatch ( bool $flag )
public SolrQuery setHighlightSimplePost ( string $simplePost [, string $field_override ] )
public SolrQuery setHighlightSimplePre ( string $simplePre [, string $field_override ] )
public SolrQuery setHighlightSnippets ( int $value [, string $field_override ] )
public SolrQuery setHighlightUsePhraseHighlighter ( bool $flag )
public SolrQuery setMlt ( bool $flag )
public SolrQuery setMltBoost ( bool $flag )
public SolrQuery setMltCount ( int $count )
public SolrQuery setMltMaxNumQueryTerms ( int $value )
public SolrQuery setMltMaxNumTokens ( int $value )
public SolrQuery setMltMaxWordLength ( int $maxWordLength )
public SolrQuery setMltMinDocFrequency ( int $minDocFrequency )
public SolrQuery setMltMinTermFrequency ( int $minTermFrequency )
public SolrQuery setMltMinWordLength ( int $minWordLength )
public SolrQuery setOmitHeader ( bool $flag )
public SolrQuery setQuery ( string $query )
public SolrQuery setRows ( int $rows )
public SolrQuery setShowDebugInfo ( bool $flag )
public SolrQuery setStart ( int $start )
public SolrQuery setStats ( bool $flag )
public SolrQuery setTerms ( bool $flag )
public SolrQuery setTermsField ( string $fieldname )
public SolrQuery setTermsIncludeLowerBound ( bool $flag )
public SolrQuery setTermsIncludeUpperBound ( bool $flag )
public SolrQuery setTermsLimit ( int $limit )
public SolrQuery setTermsLowerBound ( string $lowerBound )
public SolrQuery setTermsMaxCount ( int $frequency )
public SolrQuery setTermsMinCount ( int $frequency )
public SolrQuery setTermsPrefix ( string $prefix )
public SolrQuery setTermsReturnRaw ( bool $flag )
public SolrQuery setTermsSort ( int $sortType )
public SolrQuery setTermsUpperBound ( string $upperBound )
public SolrQuery setTimeAllowed ( int $timeAllowed )
/* Metody dziedziczone */
public SolrModifiableParams::__construct ( void )
public void SolrModifiableParams::__destruct ( void )
}

Stałe predefiniowane

SolrQuery::ORDER_ASC

Used to specify that the sorting should be in acending order

SolrQuery::ORDER_DESC

Used to specify that the sorting should be in descending order

SolrQuery::FACET_SORT_INDEX

Used to specify that the facet should sort by index

SolrQuery::FACET_SORT_COUNT

Used to specify that the facet should sort by count

SolrQuery::TERMS_SORT_INDEX

Used in the TermsComponent

SolrQuery::TERMS_SORT_COUNT

Used in the TermsComponent

Spis treści

  • SolrQuery::addFacetDateField — Maps to facet.date
  • SolrQuery::addFacetDateOther — Adds another facet.date.other parameter
  • SolrQuery::addFacetField — Adds another field to the facet
  • SolrQuery::addFacetQuery — Adds a facet query
  • SolrQuery::addField — Specifies which fields to return in the result
  • SolrQuery::addFilterQuery — Specifies a filter query
  • SolrQuery::addHighlightField — Maps to hl.fl
  • SolrQuery::addMltField — Sets a field to use for similarity
  • SolrQuery::addMltQueryField — Maps to mlt.qf
  • SolrQuery::addSortField — Used to control how the results should be sorted
  • SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
  • SolrQuery::addStatsField — Maps to stats.field parameter
  • SolrQuery::__construct — Constructor
  • SolrQuery::__destruct — Destructor
  • SolrQuery::getFacet — Returns the value of the facet parameter
  • SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter
  • SolrQuery::getFacetDateFields — Returns all the facet.date fields
  • SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter
  • SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter
  • SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter
  • SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field
  • SolrQuery::getFacetFields — Returns all the facet fields
  • SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields
  • SolrQuery::getFacetMethod — Returns the value of the facet.method parameter
  • SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response
  • SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter
  • SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination
  • SolrQuery::getFacetPrefix — Returns the facet prefix
  • SolrQuery::getFacetQueries — Returns all the facet queries
  • SolrQuery::getFacetSort — Returns the facet sort type
  • SolrQuery::getFields — Returns the list of fields that will be returned in the response
  • SolrQuery::getFilterQueries — Returns an array of filter queries
  • SolrQuery::getHighlight — Returns the state of the hl parameter
  • SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default
  • SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for
  • SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output
  • SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text
  • SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
  • SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
  • SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return
  • SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets
  • SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment
  • SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter
  • SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
  • SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
  • SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field
  • SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term
  • SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term
  • SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
  • SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter
  • SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled
  • SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance
  • SolrQuery::getMltCount — Returns the number of similar documents to return for each result
  • SolrQuery::getMltFields — Returns all the fields to use for similarity
  • SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query
  • SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
  • SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored
  • SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
  • SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document
  • SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored
  • SolrQuery::getMltQueryFields — Returns the query fields and their boosts
  • SolrQuery::getQuery — Returns the main query
  • SolrQuery::getRows — Returns the maximum number of documents
  • SolrQuery::getSortFields — Returns all the sort fields
  • SolrQuery::getStart — Returns the offset in the complete result set
  • SolrQuery::getStats — Returns whether or not stats is enabled
  • SolrQuery::getStatsFacets — Returns all the stats facets that were set
  • SolrQuery::getStatsFields — Returns all the statistics fields
  • SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled
  • SolrQuery::getTermsField — Returns the field from which the terms are retrieved
  • SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set
  • SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set
  • SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return
  • SolrQuery::getTermsLowerBound — Returns the term to start at
  • SolrQuery::getTermsMaxCount — Returns the maximum document frequency
  • SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included
  • SolrQuery::getTermsPrefix — Returns the term prefix
  • SolrQuery::getTermsReturnRaw — Whether or not to return raw characters
  • SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted
  • SolrQuery::getTermsUpperBound — Returns the term to stop at
  • SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish
  • SolrQuery::removeFacetDateField — Removes one of the facet date fields
  • SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters
  • SolrQuery::removeFacetField — Removes one of the facet.date parameters
  • SolrQuery::removeFacetQuery — Removes one of the facet.query parameters
  • SolrQuery::removeField — Removes a field from the list of fields
  • SolrQuery::removeFilterQuery — Removes a filter query
  • SolrQuery::removeHighlightField — Removes one of the fields used for highlighting
  • SolrQuery::removeMltField — Removes one of the moreLikeThis fields
  • SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields
  • SolrQuery::removeSortField — Removes one of the sort fields
  • SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters
  • SolrQuery::removeStatsField — Removes one of the stats.field parameters
  • SolrQuery::setEchoHandler — Toggles the echoHandler parameter
  • SolrQuery::setEchoParams — Determines what kind of parameters to include in the response
  • SolrQuery::setExplainOther — Sets the explainOther common query parameter
  • SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting
  • SolrQuery::setFacetDateEnd — Maps to facet.date.end
  • SolrQuery::setFacetDateGap — Maps to facet.date.gap
  • SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend
  • SolrQuery::setFacetDateStart — Maps to facet.date.start
  • SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count
  • SolrQuery::setFacetLimit — Maps to facet.limit
  • SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field
  • SolrQuery::setFacetMinCount — Maps to facet.mincount
  • SolrQuery::setFacetMissing — Maps to facet.missing
  • SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination
  • SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet
  • SolrQuery::setFacetSort — Determines the ordering of the facet field constraints
  • SolrQuery::setHighlight — Enables or disables highlighting
  • SolrQuery::setHighlightAlternateField — Specifies the backup field to use
  • SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output
  • SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text
  • SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting
  • SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms
  • SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return
  • SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets
  • SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment
  • SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze
  • SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting
  • SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size
  • SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting
  • SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term
  • SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term
  • SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field
  • SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase
  • SolrQuery::setMlt — Enables or disables moreLikeThis
  • SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance
  • SolrQuery::setMltCount — Set the number of similar documents to return for each result
  • SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
  • SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse
  • SolrQuery::setMltMaxWordLength — Sets the maximum word length
  • SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency
  • SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs
  • SolrQuery::setMltMinWordLength — Sets the minimum word length
  • SolrQuery::setOmitHeader — Exclude the header from the returned results
  • SolrQuery::setQuery — Sets the search query
  • SolrQuery::setRows — Specifies the maximum number of rows to return in the result
  • SolrQuery::setShowDebugInfo — Flag to show debug information
  • SolrQuery::setStart — Specifies the number of rows to skip
  • SolrQuery::setStats — Enables or disables the Stats component
  • SolrQuery::setTerms — Enables or disables the TermsComponent
  • SolrQuery::setTermsField — Sets the name of the field to get the Terms from
  • SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set
  • SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set
  • SolrQuery::setTermsLimit — Sets the maximum number of terms to return
  • SolrQuery::setTermsLowerBound — Specifies the Term to start from
  • SolrQuery::setTermsMaxCount — Sets the maximum document frequency
  • SolrQuery::setTermsMinCount — Sets the minimum document frequency
  • SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix
  • SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term
  • SolrQuery::setTermsSort — Specifies how to sort the returned terms
  • SolrQuery::setTermsUpperBound — Sets the term to stop at
  • SolrQuery::setTimeAllowed — The time allowed for search to finish
SolrModifiableParams::__destruct
SolrQuery::addFacetDateField
Solr


Maps to facet.date

SolrQuery
SolrQuery::addFacetDateOther
SolrQuery
PHP Manual

SolrQuery::addFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateField — Maps to facet.date

Opis

public SolrQuery SolrQuery::addFacetDateField ( string $dateField )

This method allows you to specify a field which should be treated as a facet.

It can be used multiple times with different field names to indicate multiple facet fields

Parametry

dateField

The name of the date field.

Zwracane wartości

Returns a SolrQuery object.

SolrQuery
SolrQuery::addFacetDateOther
SolrQuery


Adds another facet.date.other parameter

SolrQuery::addFacetDateField
SolrQuery::addFacetField
SolrQuery
PHP Manual

SolrQuery::addFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateOther — Adds another facet.date.other parameter

Opis

public SolrQuery SolrQuery::addFacetDateOther ( string $value [, string $field_override ] )

Sets the facet.date.other parameter. Accepts an optional field override

Parametry

value

The value to use.

field_override

The field name for the override.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addFacetDateField
SolrQuery::addFacetField
SolrQuery


Adds another field to the facet

SolrQuery::addFacetDateOther
SolrQuery::addFacetQuery
SolrQuery
PHP Manual

SolrQuery::addFacetField

(PECL solr >= 0.9.2)

SolrQuery::addFacetField — Adds another field to the facet

Opis

public SolrQuery SolrQuery::addFacetField ( string $field )

Adds another field to the facet

Parametry

field

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addFacetDateOther
SolrQuery::addFacetQuery
SolrQuery


Adds a facet query

SolrQuery::addFacetField
SolrQuery::addField
SolrQuery
PHP Manual

SolrQuery::addFacetQuery

(PECL solr >= 0.9.2)

SolrQuery::addFacetQuery — Adds a facet query

Opis

public SolrQuery SolrQuery::addFacetQuery ( string $facetQuery )

Adds a facet query

Parametry

facetQuery

The facet query

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addFacetField
SolrQuery::addField
SolrQuery


Specifies which fields to return in the result

SolrQuery::addFacetQuery
SolrQuery::addFilterQuery
SolrQuery
PHP Manual

SolrQuery::addField

(PECL solr >= 0.9.2)

SolrQuery::addField — Specifies which fields to return in the result

Opis

public SolrQuery SolrQuery::addField ( string $field )

This method is used to used to specify a set of fields to return, thereby restricting the amount of data returned in the response.

It should be called multiple time, once for each field name.

Parametry

field

The name of the field

Zwracane wartości

Returns the current SolrQuery object

SolrQuery::addFacetQuery
SolrQuery::addFilterQuery
SolrQuery


Specifies a filter query

SolrQuery::addField
SolrQuery::addHighlightField
SolrQuery
PHP Manual

SolrQuery::addFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::addFilterQuery — Specifies a filter query

Opis

public SolrQuery SolrQuery::addFilterQuery ( string $fq )

Specifies a filter query

Parametry

fq

The filter query

Zwracane wartości

Returns the current SolrQuery object.

SolrQuery::addField
SolrQuery::addHighlightField
SolrQuery


Maps to hl.fl

SolrQuery::addFilterQuery
SolrQuery::addMltField
SolrQuery
PHP Manual

SolrQuery::addHighlightField

(PECL solr >= 0.9.2)

SolrQuery::addHighlightField — Maps to hl.fl

Opis

public SolrQuery SolrQuery::addHighlightField ( string $field )

Maps to hl.fl. This is used to specify that highlighted snippets should be generated for a particular field

Parametry

field

Name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addFilterQuery
SolrQuery::addMltField
SolrQuery


Sets a field to use for similarity

SolrQuery::addHighlightField
SolrQuery::addMltQueryField
SolrQuery
PHP Manual

SolrQuery::addMltField

(PECL solr >= 0.9.2)

SolrQuery::addMltField — Sets a field to use for similarity

Opis

public SolrQuery SolrQuery::addMltField ( string $field )

Maps to mlt.fl. It specifies that a field should be used for similarity.

Parametry

field

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addHighlightField
SolrQuery::addMltQueryField
SolrQuery


Maps to mlt.qf

SolrQuery::addMltField
SolrQuery::addSortField
SolrQuery
PHP Manual

SolrQuery::addMltQueryField

(PECL solr >= 0.9.2)

SolrQuery::addMltQueryField — Maps to mlt.qf

Opis

public SolrQuery SolrQuery::addMltQueryField ( string $field , float $boost )

Maps to mlt.qf. It is used to specify query fields and their boosts

Parametry

field

The name of the field

boost

Its boost value

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addMltField
SolrQuery::addSortField
SolrQuery


Used to control how the results should be sorted

SolrQuery::addMltQueryField
SolrQuery::addStatsFacet
SolrQuery
PHP Manual

SolrQuery::addSortField

(PECL solr >= 0.9.2)

SolrQuery::addSortField — Used to control how the results should be sorted

Opis

public SolrQuery SolrQuery::addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] )

Used to control how the results should be sorted.

Parametry

field

The name of the field

order

The sort direction. This should be either SolrQuery::ORDER_ASC or SolrQuery::ORDER_DESC.

Zwracane wartości

Returns the current SolrQuery object.

SolrQuery::addMltQueryField
SolrQuery::addStatsFacet
SolrQuery


Requests a return of sub results for values within the given facet

SolrQuery::addSortField
SolrQuery::addStatsField
SolrQuery
PHP Manual

SolrQuery::addStatsFacet

(PECL solr >= 0.9.2)

SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet

Opis

public SolrQuery SolrQuery::addStatsFacet ( string $field )

Requests a return of sub results for values within the given facet. Maps to the stats.facet field

Parametry

field

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addSortField
SolrQuery::addStatsField
SolrQuery


Maps to stats.field parameter

SolrQuery::addStatsFacet
SolrQuery::__construct
SolrQuery
PHP Manual

SolrQuery::addStatsField

(PECL solr >= 0.9.2)

SolrQuery::addStatsField — Maps to stats.field parameter

Opis

public SolrQuery SolrQuery::addStatsField ( string $field )

Maps to stats.field parameter This methods adds another stats.field parameter.

Parametry

field

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::addStatsFacet
SolrQuery::__construct
SolrQuery


Constructor

SolrQuery::addStatsField
SolrQuery::__destruct
SolrQuery
PHP Manual

SolrQuery::__construct

(PECL solr >= 0.9.2)

SolrQuery::__construct — Constructor

Opis

public SolrQuery::__construct ([ string $q ] )

Constructor.

Parametry

q

Optional search query

Zwracane wartości

None

SolrQuery::addStatsField
SolrQuery::__destruct
SolrQuery


Destructor

SolrQuery::__construct
SolrQuery::getFacet
SolrQuery
PHP Manual

SolrQuery::__destruct

(PECL solr >= 0.9.2)

SolrQuery::__destruct — Destructor

Opis

public void SolrQuery::__destruct ( void )

Destructor

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

None.

SolrQuery::__construct
SolrQuery::getFacet
SolrQuery


Returns the value of the facet parameter

SolrQuery::__destruct
SolrQuery::getFacetDateEnd
SolrQuery
PHP Manual

SolrQuery::getFacet

(PECL solr >= 0.9.2)

SolrQuery::getFacet — Returns the value of the facet parameter

Opis

public bool SolrQuery::getFacet ( void )

Returns the value of the facet parameter.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set

SolrQuery::__destruct
SolrQuery::getFacetDateEnd
SolrQuery


Returns the value for the facet.date.end parameter

SolrQuery::getFacet
SolrQuery::getFacetDateFields
SolrQuery
PHP Manual

SolrQuery::getFacetDateEnd

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter

Opis

public string SolrQuery::getFacetDateEnd ([ string $field_override ] )

Returns the value for the facet.date.end parameter. This method accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set

SolrQuery::getFacet
SolrQuery::getFacetDateFields
SolrQuery


Returns all the facet.date fields

SolrQuery::getFacetDateEnd
SolrQuery::getFacetDateGap
SolrQuery
PHP Manual

SolrQuery::getFacetDateFields

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateFields — Returns all the facet.date fields

Opis

public array SolrQuery::getFacetDateFields ( void )

Returns all the facet.date fields

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns all the facet.date fields as an array or NULL if none was set

SolrQuery::getFacetDateEnd
SolrQuery::getFacetDateGap
SolrQuery


Returns the value of the facet.date.gap parameter

SolrQuery::getFacetDateFields
SolrQuery::getFacetDateHardEnd
SolrQuery
PHP Manual

SolrQuery::getFacetDateGap

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter

Opis

public string SolrQuery::getFacetDateGap ([ string $field_override ] )

Returns the value of the facet.date.gap parameter. It accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set

SolrQuery::getFacetDateFields
SolrQuery::getFacetDateHardEnd
SolrQuery


Returns the value of the facet.date.hardend parameter

SolrQuery::getFacetDateGap
SolrQuery::getFacetDateOther
SolrQuery
PHP Manual

SolrQuery::getFacetDateHardEnd

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter

Opis

public string SolrQuery::getFacetDateHardEnd ([ string $field_override ] )

Returns the value of the facet.date.hardend parameter. Accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set

SolrQuery::getFacetDateGap
SolrQuery::getFacetDateOther
SolrQuery


Returns the value for the facet.date.other parameter

SolrQuery::getFacetDateHardEnd
SolrQuery::getFacetDateStart
SolrQuery
PHP Manual

SolrQuery::getFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter

Opis

public array SolrQuery::getFacetDateOther ([ string $field_override ] )

Returns the value for the facet.date.other parameter. This method accepts an optional field override.

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getFacetDateHardEnd
SolrQuery::getFacetDateStart
SolrQuery


Returns the lower bound for the first date range for all date faceting on this field

SolrQuery::getFacetDateOther
SolrQuery::getFacetFields
SolrQuery
PHP Manual

SolrQuery::getFacetDateStart

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field

Opis

public string SolrQuery::getFacetDateStart ([ string $field_override ] )

Returns the lower bound for the first date range for all date faceting on this field. Accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set

SolrQuery::getFacetDateOther
SolrQuery::getFacetFields
SolrQuery


Returns all the facet fields

SolrQuery::getFacetDateStart
SolrQuery::getFacetLimit
SolrQuery
PHP Manual

SolrQuery::getFacetFields

(PECL solr >= 0.9.2)

SolrQuery::getFacetFields — Returns all the facet fields

Opis

public array SolrQuery::getFacetFields ( void )

Returns all the facet fields

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array of all the fields and NULL if none was set

SolrQuery::getFacetDateStart
SolrQuery::getFacetLimit
SolrQuery


Returns the maximum number of constraint counts that should be returned for the facet fields

SolrQuery::getFacetFields
SolrQuery::getFacetMethod
SolrQuery
PHP Manual

SolrQuery::getFacetLimit

(PECL solr >= 0.9.2)

SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields

Opis

public int SolrQuery::getFacetLimit ([ string $field_override ] )

Returns the maximum number of constraint counts that should be returned for the facet fields. This method accepts an optional field override

Parametry

field_override

The name of the field to override for

Zwracane wartości

Returns an integer on success and NULL if not set

SolrQuery::getFacetFields
SolrQuery::getFacetMethod
SolrQuery


Returns the value of the facet.method parameter

SolrQuery::getFacetLimit
SolrQuery::getFacetMinCount
SolrQuery
PHP Manual

SolrQuery::getFacetMethod

(PECL solr >= 0.9.2)

SolrQuery::getFacetMethod — Returns the value of the facet.method parameter

Opis

public string SolrQuery::getFacetMethod ([ string $field_override ] )

Returns the value of the facet.method parameter. This accepts an optional field override.

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set

SolrQuery::getFacetLimit
SolrQuery::getFacetMinCount
SolrQuery


Returns the minimum counts for facet fields should be included in the response

SolrQuery::getFacetMethod
SolrQuery::getFacetMissing
SolrQuery
PHP Manual

SolrQuery::getFacetMinCount

(PECL solr >= 0.9.2)

SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response

Opis

public int SolrQuery::getFacetMinCount ([ string $field_override ] )

Returns the minimum counts for facet fields should be included in the response. It accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns an integer on success and NULL if not set

SolrQuery::getFacetMethod
SolrQuery::getFacetMissing
SolrQuery


Returns the current state of the facet.missing parameter

SolrQuery::getFacetMinCount
SolrQuery::getFacetOffset
SolrQuery
PHP Manual

SolrQuery::getFacetMissing

(PECL solr >= 0.9.2)

SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter

Opis

public bool SolrQuery::getFacetMissing ([ string $field_override ] )

Returns the current state of the facet.missing parameter. This accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns a boolean on success and NULL if not set

SolrQuery::getFacetMinCount
SolrQuery::getFacetOffset
SolrQuery


Returns an offset into the list of constraints to be used for pagination

SolrQuery::getFacetMissing
SolrQuery::getFacetPrefix
SolrQuery
PHP Manual

SolrQuery::getFacetOffset

(PECL solr >= 0.9.2)

SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination

Opis

public int SolrQuery::getFacetOffset ([ string $field_override ] )

Returns an offset into the list of constraints to be used for pagination. Accepts an optional field override

Parametry

field_override

The name of the field to override for.

Zwracane wartości

Returns an integer on success and NULL if not set

SolrQuery::getFacetMissing
SolrQuery::getFacetPrefix
SolrQuery


Returns the facet prefix

SolrQuery::getFacetOffset
SolrQuery::getFacetQueries
SolrQuery
PHP Manual

SolrQuery::getFacetPrefix

(PECL solr >= 0.9.2)

SolrQuery::getFacetPrefix — Returns the facet prefix

Opis

public string SolrQuery::getFacetPrefix ([ string $field_override ] )

Returns the facet prefix

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getFacetOffset
SolrQuery::getFacetQueries
SolrQuery


Returns all the facet queries

SolrQuery::getFacetPrefix
SolrQuery::getFacetSort
SolrQuery
PHP Manual

SolrQuery::getFacetQueries

(PECL solr >= 0.9.2)

SolrQuery::getFacetQueries — Returns all the facet queries

Opis

public array SolrQuery::getFacetQueries ( void )

Returns all the facet queries

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if not set.

SolrQuery::getFacetPrefix
SolrQuery::getFacetSort
SolrQuery


Returns the facet sort type

SolrQuery::getFacetQueries
SolrQuery::getFields
SolrQuery
PHP Manual

SolrQuery::getFacetSort

(PECL solr >= 0.9.2)

SolrQuery::getFacetSort — Returns the facet sort type

Opis

public int SolrQuery::getFacetSort ([ string $field_override ] )

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT)

Parametry

field_override

The name of the field

Zwracane wartości

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT) on success or NULL if not set.

SolrQuery::getFacetQueries
SolrQuery::getFields
SolrQuery


Returns the list of fields that will be returned in the response

SolrQuery::getFacetSort
SolrQuery::getFilterQueries
SolrQuery
PHP Manual

SolrQuery::getFields

(PECL solr >= 0.9.2)

SolrQuery::getFields — Returns the list of fields that will be returned in the response

Opis

public array SolrQuery::getFields ( void )

Returns the list of fields that will be returned in the response

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if not set.

SolrQuery::getFacetSort
SolrQuery::getFilterQueries
SolrQuery


Returns an array of filter queries

SolrQuery::getFields
SolrQuery::getHighlight
SolrQuery
PHP Manual

SolrQuery::getFilterQueries

(PECL solr >= 0.9.2)

SolrQuery::getFilterQueries — Returns an array of filter queries

Opis

public array SolrQuery::getFilterQueries ( void )

Returns an array of filter queries. These are queries that can be used to restrict the super set of documents that can be returned, without influencing score

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if not set.

SolrQuery::getFields
SolrQuery::getHighlight
SolrQuery


Returns the state of the hl parameter

SolrQuery::getFilterQueries
SolrQuery::getHighlightAlternateField
SolrQuery
PHP Manual

SolrQuery::getHighlight

(PECL solr >= 0.9.2)

SolrQuery::getHighlight — Returns the state of the hl parameter

Opis

public bool SolrQuery::getHighlight ( void )

Returns a boolean indicating whether or not to enable highlighted snippets to be generated in the query response.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getFilterQueries
SolrQuery::getHighlightAlternateField
SolrQuery


Returns the highlight field to use as backup or default

SolrQuery::getHighlight
SolrQuery::getHighlightFields
SolrQuery
PHP Manual

SolrQuery::getHighlightAlternateField

(PECL solr >= 0.9.2)

SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default

Opis

public string SolrQuery::getHighlightAlternateField ([ string $field_override ] )

Returns the highlight field to use as backup or default. It accepts an optional override.

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getHighlight
SolrQuery::getHighlightFields
SolrQuery


Returns all the fields that Solr should generate highlighted snippets for

SolrQuery::getHighlightAlternateField
SolrQuery::getHighlightFormatter
SolrQuery
PHP Manual

SolrQuery::getHighlightFields

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for

Opis

public array SolrQuery::getHighlightFields ( void )

Returns all the fields that Solr should generate highlighted snippets for

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if not set.

SolrQuery::getHighlightAlternateField
SolrQuery::getHighlightFormatter
SolrQuery


Returns the formatter for the highlighted output

SolrQuery::getHighlightFields
SolrQuery::getHighlightFragmenter
SolrQuery
PHP Manual

SolrQuery::getHighlightFormatter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output

Opis

public string SolrQuery::getHighlightFormatter ([ string $field_override ] )

Returns the formatter for the highlighted output

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getHighlightFields
SolrQuery::getHighlightFragmenter
SolrQuery


Returns the text snippet generator for highlighted text

SolrQuery::getHighlightFormatter
SolrQuery::getHighlightFragsize
SolrQuery
PHP Manual

SolrQuery::getHighlightFragmenter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text

Opis

public string SolrQuery::getHighlightFragmenter ([ string $field_override ] )

Returns the text snippet generator for highlighted text. Accepts an optional field override.

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getHighlightFormatter
SolrQuery::getHighlightFragsize
SolrQuery


Returns the number of characters of fragments to consider for highlighting

SolrQuery::getHighlightFragmenter
SolrQuery::getHighlightHighlightMultiTerm
SolrQuery
PHP Manual

SolrQuery::getHighlightFragsize

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting

Opis

public int SolrQuery::getHighlightFragsize ([ string $field_override ] )

Returns the number of characters of fragments to consider for highlighting. Zero implies no fragmenting. The entire field should be used.

Parametry

field_override

The name of the field

Zwracane wartości

Returns an integer on success or NULL if not set.

SolrQuery::getHighlightFragmenter
SolrQuery::getHighlightHighlightMultiTerm
SolrQuery


Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

SolrQuery::getHighlightFragsize
SolrQuery::getHighlightMaxAlternateFieldLength
SolrQuery
PHP Manual

SolrQuery::getHighlightHighlightMultiTerm

(PECL solr >= 0.9.2)

SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

Opis

public bool SolrQuery::getHighlightHighlightMultiTerm ( void )

Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getHighlightFragsize
SolrQuery::getHighlightMaxAlternateFieldLength
SolrQuery


Returns the maximum number of characters of the field to return

SolrQuery::getHighlightHighlightMultiTerm
SolrQuery::getHighlightMaxAnalyzedChars
SolrQuery
PHP Manual

SolrQuery::getHighlightMaxAlternateFieldLength

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return

Opis

public int SolrQuery::getHighlightMaxAlternateFieldLength ([ string $field_override ] )

Returns the maximum number of characters of the field to return

Parametry

field_override

The name of the field

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getHighlightHighlightMultiTerm
SolrQuery::getHighlightMaxAnalyzedChars
SolrQuery


Returns the maximum number of characters into a document to look for suitable snippets

SolrQuery::getHighlightMaxAlternateFieldLength
SolrQuery::getHighlightMergeContiguous
SolrQuery
PHP Manual

SolrQuery::getHighlightMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets

Opis

public int SolrQuery::getHighlightMaxAnalyzedChars ( void )

Returns the maximum number of characters into a document to look for suitable snippets

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getHighlightMaxAlternateFieldLength
SolrQuery::getHighlightMergeContiguous
SolrQuery


Returns whether or not the collapse contiguous fragments into a single fragment

SolrQuery::getHighlightMaxAnalyzedChars
SolrQuery::getHighlightRegexMaxAnalyzedChars
SolrQuery
PHP Manual

SolrQuery::getHighlightMergeContiguous

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment

Opis

public bool SolrQuery::getHighlightMergeContiguous ([ string $field_override ] )

Returns whether or not the collapse contiguous fragments into a single fragment. Accepts an optional field override.

Parametry

field_override

The name of the field

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getHighlightMaxAnalyzedChars
SolrQuery::getHighlightRegexMaxAnalyzedChars
SolrQuery


Returns the maximum number of characters from a field when using the regex fragmenter

SolrQuery::getHighlightMergeContiguous
SolrQuery::getHighlightRegexPattern
SolrQuery
PHP Manual

SolrQuery::getHighlightRegexMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter

Opis

public int SolrQuery::getHighlightRegexMaxAnalyzedChars ( void )

Returns the maximum number of characters from a field when using the regex fragmenter

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getHighlightMergeContiguous
SolrQuery::getHighlightRegexPattern
SolrQuery


Returns the regular expression for fragmenting

SolrQuery::getHighlightRegexMaxAnalyzedChars
SolrQuery::getHighlightRegexSlop
SolrQuery
PHP Manual

SolrQuery::getHighlightRegexPattern

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting

Opis

public string SolrQuery::getHighlightRegexPattern ( void )

Returns the regular expression used for fragmenting

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getHighlightRegexMaxAnalyzedChars
SolrQuery::getHighlightRegexSlop
SolrQuery


Returns the deviation factor from the ideal fragment size

SolrQuery::getHighlightRegexPattern
SolrQuery::getHighlightRequireFieldMatch
SolrQuery
PHP Manual

SolrQuery::getHighlightRegexSlop

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size

Opis

public float SolrQuery::getHighlightRegexSlop ( void )

Returns the factor by which the regex fragmenter can deviate from the ideal fragment size to accomodate the regular expression

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a double on success and NULL if not set.

SolrQuery::getHighlightRegexPattern
SolrQuery::getHighlightRequireFieldMatch
SolrQuery


Returns if a field will only be highlighted if the query matched in this particular field

SolrQuery::getHighlightRegexSlop
SolrQuery::getHighlightSimplePost
SolrQuery
PHP Manual

SolrQuery::getHighlightRequireFieldMatch

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field

Opis

public bool SolrQuery::getHighlightRequireFieldMatch ( void )

Returns if a field will only be highlighted if the query matched in this particular field.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getHighlightRegexSlop
SolrQuery::getHighlightSimplePost
SolrQuery


Returns the text which appears after a highlighted term

SolrQuery::getHighlightRequireFieldMatch
SolrQuery::getHighlightSimplePre
SolrQuery
PHP Manual

SolrQuery::getHighlightSimplePost

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term

Opis

public string SolrQuery::getHighlightSimplePost ([ string $field_override ] )

Returns the text which appears after a highlighted term. Accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getHighlightRequireFieldMatch
SolrQuery::getHighlightSimplePre
SolrQuery


Returns the text which appears before a highlighted term

SolrQuery::getHighlightSimplePost
SolrQuery::getHighlightSnippets
SolrQuery
PHP Manual

SolrQuery::getHighlightSimplePre

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term

Opis

public string SolrQuery::getHighlightSimplePre ([ string $field_override ] )

Returns the text which appears before a highlighted term. Accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getHighlightSimplePost
SolrQuery::getHighlightSnippets
SolrQuery


Returns the maximum number of highlighted snippets to generate per field

SolrQuery::getHighlightSimplePre
SolrQuery::getHighlightUsePhraseHighlighter
SolrQuery
PHP Manual

SolrQuery::getHighlightSnippets

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field

Opis

public int SolrQuery::getHighlightSnippets ([ string $field_override ] )

Returns the maximum number of highlighted snippets to generate per field. Accepts an optional field override

Parametry

field_override

The name of the field

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getHighlightSimplePre
SolrQuery::getHighlightUsePhraseHighlighter
SolrQuery


Returns the state of the hl.usePhraseHighlighter parameter

SolrQuery::getHighlightSnippets
SolrQuery::getMlt
SolrQuery
PHP Manual

SolrQuery::getHighlightUsePhraseHighlighter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter

Opis

public bool SolrQuery::getHighlightUsePhraseHighlighter ( void )

Returns whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getHighlightSnippets
SolrQuery::getMlt
SolrQuery


Returns whether or not MoreLikeThis results should be enabled

SolrQuery::getHighlightUsePhraseHighlighter
SolrQuery::getMltBoost
SolrQuery
PHP Manual

SolrQuery::getMlt

(PECL solr >= 0.9.2)

SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled

Opis

public bool SolrQuery::getMlt ( void )

Returns whether or not MoreLikeThis results should be enabled

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getHighlightUsePhraseHighlighter
SolrQuery::getMltBoost
SolrQuery


Returns whether or not the query will be boosted by the interesting term relevance

SolrQuery::getMlt
SolrQuery::getMltCount
SolrQuery
PHP Manual

SolrQuery::getMltBoost

(PECL solr >= 0.9.2)

SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance

Opis

public bool SolrQuery::getMltBoost ( void )

Returns whether or not the query will be boosted by the interesting term relevance

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getMlt
SolrQuery::getMltCount
SolrQuery


Returns the number of similar documents to return for each result

SolrQuery::getMltBoost
SolrQuery::getMltFields
SolrQuery
PHP Manual

SolrQuery::getMltCount

(PECL solr >= 0.9.2)

SolrQuery::getMltCount — Returns the number of similar documents to return for each result

Opis

public int SolrQuery::getMltCount ( void )

Returns the number of similar documents to return for each result

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getMltBoost
SolrQuery::getMltFields
SolrQuery


Returns all the fields to use for similarity

SolrQuery::getMltCount
SolrQuery::getMltMaxNumQueryTerms
SolrQuery
PHP Manual

SolrQuery::getMltFields

(PECL solr >= 0.9.2)

SolrQuery::getMltFields — Returns all the fields to use for similarity

Opis

public array SolrQuery::getMltFields ( void )

Returns all the fields to use for similarity

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if not set.

SolrQuery::getMltCount
SolrQuery::getMltMaxNumQueryTerms
SolrQuery


Returns the maximum number of query terms that will be included in any generated query

SolrQuery::getMltFields
SolrQuery::getMltMaxNumTokens
SolrQuery
PHP Manual

SolrQuery::getMltMaxNumQueryTerms

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query

Opis

public int SolrQuery::getMltMaxNumQueryTerms ( void )

Returns the maximum number of query terms that will be included in any generated query

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getMltFields
SolrQuery::getMltMaxNumTokens
SolrQuery


Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

SolrQuery::getMltMaxNumQueryTerms
SolrQuery::getMltMaxWordLength
SolrQuery
PHP Manual

SolrQuery::getMltMaxNumTokens

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

Opis

public int SolrQuery::getMltMaxNumTokens ( void )

Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getMltMaxNumQueryTerms
SolrQuery::getMltMaxWordLength
SolrQuery


Returns the maximum word length above which words will be ignored

SolrQuery::getMltMaxNumTokens
SolrQuery::getMltMinDocFrequency
SolrQuery
PHP Manual

SolrQuery::getMltMaxWordLength

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored

Opis

public int SolrQuery::getMltMaxWordLength ( void )

Returns the maximum word length above which words will be ignored

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getMltMaxNumTokens
SolrQuery::getMltMinDocFrequency
SolrQuery


Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

SolrQuery::getMltMaxWordLength
SolrQuery::getMltMinTermFrequency
SolrQuery
PHP Manual

SolrQuery::getMltMinDocFrequency

(PECL solr >= 0.9.2)

SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

Opis

public int SolrQuery::getMltMinDocFrequency ( void )

Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getMltMaxWordLength
SolrQuery::getMltMinTermFrequency
SolrQuery


Returns the frequency below which terms will be ignored in the source document

SolrQuery::getMltMinDocFrequency
SolrQuery::getMltMinWordLength
SolrQuery
PHP Manual

SolrQuery::getMltMinTermFrequency

(PECL solr >= 0.9.2)

SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document

Opis

public int SolrQuery::getMltMinTermFrequency ( void )

Returns the frequency below which terms will be ignored in the source document

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getMltMinDocFrequency
SolrQuery::getMltMinWordLength
SolrQuery


Returns the minimum word length below which words will be ignored

SolrQuery::getMltMinTermFrequency
SolrQuery::getMltQueryFields
SolrQuery
PHP Manual

SolrQuery::getMltMinWordLength

(PECL solr >= 0.9.2)

SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored

Opis

public int SolrQuery::getMltMinWordLength ( void )

Returns the minimum word length below which words will be ignored

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getMltMinTermFrequency
SolrQuery::getMltQueryFields
SolrQuery


Returns the query fields and their boosts

SolrQuery::getMltMinWordLength
SolrQuery::getQuery
SolrQuery
PHP Manual

SolrQuery::getMltQueryFields

(PECL solr >= 0.9.2)

SolrQuery::getMltQueryFields — Returns the query fields and their boosts

Opis

public array SolrQuery::getMltQueryFields ( void )

Returns the query fields and their boosts

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if not set.

SolrQuery::getMltMinWordLength
SolrQuery::getQuery
SolrQuery


Returns the main query

SolrQuery::getMltQueryFields
SolrQuery::getRows
SolrQuery
PHP Manual

SolrQuery::getQuery

(PECL solr >= 0.9.2)

SolrQuery::getQuery — Returns the main query

Opis

public string SolrQuery::getQuery ( void )

Returns the main search query

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getMltQueryFields
SolrQuery::getRows
SolrQuery


Returns the maximum number of documents

SolrQuery::getQuery
SolrQuery::getSortFields
SolrQuery
PHP Manual

SolrQuery::getRows

(PECL solr >= 0.9.2)

SolrQuery::getRows — Returns the maximum number of documents

Opis

public int SolrQuery::getRows ( void )

Returns the maximum number of documents from the complete result set to return to the client for every request

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getQuery
SolrQuery::getSortFields
SolrQuery


Returns all the sort fields

SolrQuery::getRows
SolrQuery::getStart
SolrQuery
PHP Manual

SolrQuery::getSortFields

(PECL solr >= 0.9.2)

SolrQuery::getSortFields — Returns all the sort fields

Opis

public array SolrQuery::getSortFields ( void )

Returns all the sort fields

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if none of the parameters was set.

SolrQuery::getRows
SolrQuery::getStart
SolrQuery


Returns the offset in the complete result set

SolrQuery::getSortFields
SolrQuery::getStats
SolrQuery
PHP Manual

SolrQuery::getStart

(PECL solr >= 0.9.2)

SolrQuery::getStart — Returns the offset in the complete result set

Opis

public int SolrQuery::getStart ( void )

Returns the offset in the complete result set for the queries where the set of returned documents should begin.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getSortFields
SolrQuery::getStats
SolrQuery


Returns whether or not stats is enabled

SolrQuery::getStart
SolrQuery::getStatsFacets
SolrQuery
PHP Manual

SolrQuery::getStats

(PECL solr >= 0.9.2)

SolrQuery::getStats — Returns whether or not stats is enabled

Opis

public bool SolrQuery::getStats ( void )

Returns whether or not stats is enabled

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getStart
SolrQuery::getStatsFacets
SolrQuery


Returns all the stats facets that were set

SolrQuery::getStats
SolrQuery::getStatsFields
SolrQuery
PHP Manual

SolrQuery::getStatsFacets

(PECL solr >= 0.9.2)

SolrQuery::getStatsFacets — Returns all the stats facets that were set

Opis

public array SolrQuery::getStatsFacets ( void )

Returns all the stats facets that were set

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if not set.

SolrQuery::getStats
SolrQuery::getStatsFields
SolrQuery


Returns all the statistics fields

SolrQuery::getStatsFacets
SolrQuery::getTerms
SolrQuery
PHP Manual

SolrQuery::getStatsFields

(PECL solr >= 0.9.2)

SolrQuery::getStatsFields — Returns all the statistics fields

Opis

public array SolrQuery::getStatsFields ( void )

Returns all the statistics fields

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array on success and NULL if not set.

SolrQuery::getStatsFacets
SolrQuery::getTerms
SolrQuery


Returns whether or not the TermsComponent is enabled

SolrQuery::getStatsFields
SolrQuery::getTermsField
SolrQuery
PHP Manual

SolrQuery::getTerms

(PECL solr >= 0.9.2)

SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled

Opis

public bool SolrQuery::getTerms ( void )

Returns whether or not the TermsComponent is enabled

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getStatsFields
SolrQuery::getTermsField
SolrQuery


Returns the field from which the terms are retrieved

SolrQuery::getTerms
SolrQuery::getTermsIncludeLowerBound
SolrQuery
PHP Manual

SolrQuery::getTermsField

(PECL solr >= 0.9.2)

SolrQuery::getTermsField — Returns the field from which the terms are retrieved

Opis

public string SolrQuery::getTermsField ( void )

Returns the field from which the terms are retrieved

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getTerms
SolrQuery::getTermsIncludeLowerBound
SolrQuery


Returns whether or not to include the lower bound in the result set

SolrQuery::getTermsField
SolrQuery::getTermsIncludeUpperBound
SolrQuery
PHP Manual

SolrQuery::getTermsIncludeLowerBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set

Opis

public bool SolrQuery::getTermsIncludeLowerBound ( void )

Returns whether or not to include the lower bound in the result set

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getTermsField
SolrQuery::getTermsIncludeUpperBound
SolrQuery


Returns whether or not to include the upper bound term in the result set

SolrQuery::getTermsIncludeLowerBound
SolrQuery::getTermsLimit
SolrQuery
PHP Manual

SolrQuery::getTermsIncludeUpperBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set

Opis

public bool SolrQuery::getTermsIncludeUpperBound ( void )

Returns whether or not to include the upper bound term in the result set

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getTermsIncludeLowerBound
SolrQuery::getTermsLimit
SolrQuery


Returns the maximum number of terms Solr should return

SolrQuery::getTermsIncludeUpperBound
SolrQuery::getTermsLowerBound
SolrQuery
PHP Manual

SolrQuery::getTermsLimit

(PECL solr >= 0.9.2)

SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return

Opis

public int SolrQuery::getTermsLimit ( void )

Returns the maximum number of terms Solr should return

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getTermsIncludeUpperBound
SolrQuery::getTermsLowerBound
SolrQuery


Returns the term to start at

SolrQuery::getTermsLimit
SolrQuery::getTermsMaxCount
SolrQuery
PHP Manual

SolrQuery::getTermsLowerBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsLowerBound — Returns the term to start at

Opis

public string SolrQuery::getTermsLowerBound ( void )

Returns the term to start at

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getTermsLimit
SolrQuery::getTermsMaxCount
SolrQuery


Returns the maximum document frequency

SolrQuery::getTermsLowerBound
SolrQuery::getTermsMinCount
SolrQuery
PHP Manual

SolrQuery::getTermsMaxCount

(PECL solr >= 0.9.2)

SolrQuery::getTermsMaxCount — Returns the maximum document frequency

Opis

public int SolrQuery::getTermsMaxCount ( void )

Returns the maximum document frequency

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getTermsLowerBound
SolrQuery::getTermsMinCount
SolrQuery


Returns the minimum document frequency to return in order to be included

SolrQuery::getTermsMaxCount
SolrQuery::getTermsPrefix
SolrQuery
PHP Manual

SolrQuery::getTermsMinCount

(PECL solr >= 0.9.2)

SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included

Opis

public int SolrQuery::getTermsMinCount ( void )

Returns the minimum document frequency to return in order to be included

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getTermsMaxCount
SolrQuery::getTermsPrefix
SolrQuery


Returns the term prefix

SolrQuery::getTermsMinCount
SolrQuery::getTermsReturnRaw
SolrQuery
PHP Manual

SolrQuery::getTermsPrefix

(PECL solr >= 0.9.2)

SolrQuery::getTermsPrefix — Returns the term prefix

Opis

public string SolrQuery::getTermsPrefix ( void )

Returns the prefix to which matching terms must be restricted. This will restrict matches to only terms that start with the prefix

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getTermsMinCount
SolrQuery::getTermsReturnRaw
SolrQuery


Whether or not to return raw characters

SolrQuery::getTermsPrefix
SolrQuery::getTermsSort
SolrQuery
PHP Manual

SolrQuery::getTermsReturnRaw

(PECL solr >= 0.9.2)

SolrQuery::getTermsReturnRaw — Whether or not to return raw characters

Opis

public bool SolrQuery::getTermsReturnRaw ( void )

Returns a boolean indicating whether or not to return the raw characters of the indexed term, regardless of if it is human readable

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a boolean on success and NULL if not set.

SolrQuery::getTermsPrefix
SolrQuery::getTermsSort
SolrQuery


Returns an integer indicating how terms are sorted

SolrQuery::getTermsReturnRaw
SolrQuery::getTermsUpperBound
SolrQuery
PHP Manual

SolrQuery::getTermsSort

(PECL solr >= 0.9.2)

SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted

Opis

public int SolrQuery::getTermsSort ( void )

SolrQuery::TERMS_SORT_INDEX indicates that the terms are returned by index order. SolrQuery::TERMS_SORT_COUNT implies that the terms are sorted by term frequency (highest count first)

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an integer on success and NULL if not set.

SolrQuery::getTermsReturnRaw
SolrQuery::getTermsUpperBound
SolrQuery


Returns the term to stop at

SolrQuery::getTermsSort
SolrQuery::getTimeAllowed
SolrQuery
PHP Manual

SolrQuery::getTermsUpperBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsUpperBound — Returns the term to stop at

Opis

public string SolrQuery::getTermsUpperBound ( void )

Returns the term to stop at

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string on success and NULL if not set.

SolrQuery::getTermsSort
SolrQuery::getTimeAllowed
SolrQuery


Returns the time in milliseconds allowed for the query to finish

SolrQuery::getTermsUpperBound
SolrQuery::removeFacetDateField
SolrQuery
PHP Manual

SolrQuery::getTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish

Opis

public int SolrQuery::getTimeAllowed ( void )

Returns the time in milliseconds allowed for the query to finish.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns and integer on success and NULL if it is not set.

SolrQuery::getTermsUpperBound
SolrQuery::removeFacetDateField
SolrQuery


Removes one of the facet date fields

SolrQuery::getTimeAllowed
SolrQuery::removeFacetDateOther
SolrQuery
PHP Manual

SolrQuery::removeFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateField — Removes one of the facet date fields

Opis

public SolrQuery SolrQuery::removeFacetDateField ( string $field )

The name of the field

Parametry

field

The name of the date field to remove

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::getTimeAllowed
SolrQuery::removeFacetDateOther
SolrQuery


Removes one of the facet.date.other parameters

SolrQuery::removeFacetDateField
SolrQuery::removeFacetField
SolrQuery
PHP Manual

SolrQuery::removeFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters

Opis

public SolrQuery SolrQuery::removeFacetDateOther ( string $value [, string $field_override ] )

Removes one of the facet.date.other parameters

Parametry

value

The value

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeFacetDateField
SolrQuery::removeFacetField
SolrQuery


Removes one of the facet.date parameters

SolrQuery::removeFacetDateOther
SolrQuery::removeFacetQuery
SolrQuery
PHP Manual

SolrQuery::removeFacetField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetField — Removes one of the facet.date parameters

Opis

public SolrQuery SolrQuery::removeFacetField ( string $field )

Removes one of the facet.date parameters

Parametry

field

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeFacetDateOther
SolrQuery::removeFacetQuery
SolrQuery


Removes one of the facet.query parameters

SolrQuery::removeFacetField
SolrQuery::removeField
SolrQuery
PHP Manual

SolrQuery::removeFacetQuery

(PECL solr >= 0.9.2)

SolrQuery::removeFacetQuery — Removes one of the facet.query parameters

Opis

public SolrQuery SolrQuery::removeFacetQuery ( string $value )

Removes one of the facet.query parameters.

Parametry

value

The value

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeFacetField
SolrQuery::removeField
SolrQuery


Removes a field from the list of fields

SolrQuery::removeFacetQuery
SolrQuery::removeFilterQuery
SolrQuery
PHP Manual

SolrQuery::removeField

(PECL solr >= 0.9.2)

SolrQuery::removeField — Removes a field from the list of fields

Opis

public SolrQuery SolrQuery::removeField ( string $field )

Removes a field from the list of fields

Parametry

field

Name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeFacetQuery
SolrQuery::removeFilterQuery
SolrQuery


Removes a filter query

SolrQuery::removeField
SolrQuery::removeHighlightField
SolrQuery
PHP Manual

SolrQuery::removeFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::removeFilterQuery — Removes a filter query

Opis

public SolrQuery SolrQuery::removeFilterQuery ( string $fq )

Removes a filter query.

Parametry

fq

The filter query to remove

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeField
SolrQuery::removeHighlightField
SolrQuery


Removes one of the fields used for highlighting

SolrQuery::removeFilterQuery
SolrQuery::removeMltField
SolrQuery
PHP Manual

SolrQuery::removeHighlightField

(PECL solr >= 0.9.2)

SolrQuery::removeHighlightField — Removes one of the fields used for highlighting

Opis

public SolrQuery SolrQuery::removeHighlightField ( string $field )

Removes one of the fields used for highlighting.

Parametry

field

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeFilterQuery
SolrQuery::removeMltField
SolrQuery


Removes one of the moreLikeThis fields

SolrQuery::removeHighlightField
SolrQuery::removeMltQueryField
SolrQuery
PHP Manual

SolrQuery::removeMltField

(PECL solr >= 0.9.2)

SolrQuery::removeMltField — Removes one of the moreLikeThis fields

Opis

public SolrQuery SolrQuery::removeMltField ( string $field )

Removes one of the moreLikeThis fields.

Parametry

field

Name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeHighlightField
SolrQuery::removeMltQueryField
SolrQuery


Removes one of the moreLikeThis query fields

SolrQuery::removeMltField
SolrQuery::removeSortField
SolrQuery
PHP Manual

SolrQuery::removeMltQueryField

(PECL solr >= 0.9.2)

SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields

Opis

public SolrQuery SolrQuery::removeMltQueryField ( string $queryField )

Removes one of the moreLikeThis query fields.

Parametry

queryField

The query field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeMltField
SolrQuery::removeSortField
SolrQuery


Removes one of the sort fields

SolrQuery::removeMltQueryField
SolrQuery::removeStatsFacet
SolrQuery
PHP Manual

SolrQuery::removeSortField

(PECL solr >= 0.9.2)

SolrQuery::removeSortField — Removes one of the sort fields

Opis

public SolrQuery SolrQuery::removeSortField ( string $field )

Removes one of the sort fields

Parametry

field

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeMltQueryField
SolrQuery::removeStatsFacet
SolrQuery


Removes one of the stats.facet parameters

SolrQuery::removeSortField
SolrQuery::removeStatsField
SolrQuery
PHP Manual

SolrQuery::removeStatsFacet

(PECL solr >= 0.9.2)

SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters

Opis

public SolrQuery SolrQuery::removeStatsFacet ( string $value )

Removes one of the stats.facet parameters

Parametry

value

The value

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeSortField
SolrQuery::removeStatsField
SolrQuery


Removes one of the stats.field parameters

SolrQuery::removeStatsFacet
SolrQuery::setEchoHandler
SolrQuery
PHP Manual

SolrQuery::removeStatsField

(PECL solr >= 0.9.2)

SolrQuery::removeStatsField — Removes one of the stats.field parameters

Opis

public SolrQuery SolrQuery::removeStatsField ( string $field )

Removes one of the stats.field parameters

Parametry

field

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeStatsFacet
SolrQuery::setEchoHandler
SolrQuery


Toggles the echoHandler parameter

SolrQuery::removeStatsField
SolrQuery::setEchoParams
SolrQuery
PHP Manual

SolrQuery::setEchoHandler

(PECL solr >= 0.9.2)

SolrQuery::setEchoHandler — Toggles the echoHandler parameter

Opis

public SolrQuery SolrQuery::setEchoHandler ( bool $flag )

If set to true, Solr places the name of the handle used in the response to the client for debugging purposes.

Parametry

flag

TRUE or FALSE

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::removeStatsField
SolrQuery::setEchoParams
SolrQuery


Determines what kind of parameters to include in the response

SolrQuery::setEchoHandler
SolrQuery::setExplainOther
SolrQuery
PHP Manual

SolrQuery::setEchoParams

(PECL solr >= 0.9.2)

SolrQuery::setEchoParams — Determines what kind of parameters to include in the response

Opis

public SolrQuery SolrQuery::setEchoParams ( string $type )

Instructs Solr what kinds of Request parameters should be included in the response for debugging purposes, legal values include:

- none - don't include any request parameters for debugging
- explicit - include the parameters explicitly specified by the client in the request
- all - include all parameters involved in this request, either specified explicitly by the client, or implicit because of the request handler configuration.

Parametry

type

The type of parameters to include

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setEchoHandler
SolrQuery::setExplainOther
SolrQuery


Sets the explainOther common query parameter

SolrQuery::setEchoParams
SolrQuery::setFacet
SolrQuery
PHP Manual

SolrQuery::setExplainOther

(PECL solr >= 0.9.2)

SolrQuery::setExplainOther — Sets the explainOther common query parameter

Opis

public SolrQuery SolrQuery::setExplainOther ( string $query )

Sets the explainOther common query parameter

Parametry

query

The Lucene query to identify a set of documents

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setEchoParams
SolrQuery::setFacet
SolrQuery


Maps to the facet parameter. Enables or disables facetting

SolrQuery::setExplainOther
SolrQuery::setFacetDateEnd
SolrQuery
PHP Manual

SolrQuery::setFacet

(PECL solr >= 0.9.2)

SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting

Opis

public SolrQuery SolrQuery::setFacet ( bool $flag )

Enables or disables faceting.

Parametry

value

TRUE enables faceting and FALSE disables it.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setExplainOther
SolrQuery::setFacetDateEnd
SolrQuery


Maps to facet.date.end

SolrQuery::setFacet
SolrQuery::setFacetDateGap
SolrQuery
PHP Manual

SolrQuery::setFacetDateEnd

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateEnd — Maps to facet.date.end

Opis

public SolrQuery SolrQuery::setFacetDateEnd ( string $value [, string $field_override ] )

Maps to facet.date.end

Parametry

value

See facet.date.end

field_override

Name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacet
SolrQuery::setFacetDateGap
SolrQuery


Maps to facet.date.gap

SolrQuery::setFacetDateEnd
SolrQuery::setFacetDateHardEnd
SolrQuery
PHP Manual

SolrQuery::setFacetDateGap

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateGap — Maps to facet.date.gap

Opis

public SolrQuery SolrQuery::setFacetDateGap ( string $value [, string $field_override ] )

Maps to facet.date.gap

Parametry

value

See facet.date.gap

field_override

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetDateEnd
SolrQuery::setFacetDateHardEnd
SolrQuery


Maps to facet.date.hardend

SolrQuery::setFacetDateGap
SolrQuery::setFacetDateStart
SolrQuery
PHP Manual

SolrQuery::setFacetDateHardEnd

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend

Opis

public SolrQuery SolrQuery::setFacetDateHardEnd ( bool $value [, string $field_override ] )

Maps to facet.date.hardend

Parametry

value

See facet.date.hardend

field_override

The name of the field

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetDateGap
SolrQuery::setFacetDateStart
SolrQuery


Maps to facet.date.start

SolrQuery::setFacetDateHardEnd
SolrQuery::setFacetEnumCacheMinDefaultFrequency
SolrQuery
PHP Manual

SolrQuery::setFacetDateStart

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateStart — Maps to facet.date.start

Opis

public SolrQuery SolrQuery::setFacetDateStart ( string $value [, string $field_override ] )

Maps to facet.date.start

Parametry

value

See facet.date.start

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetDateHardEnd
SolrQuery::setFacetEnumCacheMinDefaultFrequency
SolrQuery


Sets the minimum document frequency used for determining term count

SolrQuery::setFacetDateStart
SolrQuery::setFacetLimit
SolrQuery
PHP Manual

SolrQuery::setFacetEnumCacheMinDefaultFrequency

(PECL solr >= 0.9.2)

SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count

Opis

public SolrQuery SolrQuery::setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] )

Sets the minimum document frequency used for determining term count

Parametry

value

The minimum frequency

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetDateStart
SolrQuery::setFacetLimit
SolrQuery


Maps to facet.limit

SolrQuery::setFacetEnumCacheMinDefaultFrequency
SolrQuery::setFacetMethod
SolrQuery
PHP Manual

SolrQuery::setFacetLimit

(PECL solr >= 0.9.2)

SolrQuery::setFacetLimit — Maps to facet.limit

Opis

public SolrQuery SolrQuery::setFacetLimit ( int $limit [, string $field_override ] )

Maps to facet.limit. Sets the maximum number of constraint counts that should be returned for the facet fields.

Parametry

limit

The maximum number of constraint counts

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetEnumCacheMinDefaultFrequency
SolrQuery::setFacetMethod
SolrQuery


Specifies the type of algorithm to use when faceting a field

SolrQuery::setFacetLimit
SolrQuery::setFacetMinCount
SolrQuery
PHP Manual

SolrQuery::setFacetMethod

(PECL solr >= 0.9.2)

SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field

Opis

public SolrQuery SolrQuery::setFacetMethod ( string $method [, string $field_override ] )

Specifies the type of algorithm to use when faceting a field. This method accepts optional field override.

Parametry

method

The method to use.

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetLimit
SolrQuery::setFacetMinCount
SolrQuery


Maps to facet.mincount

SolrQuery::setFacetMethod
SolrQuery::setFacetMissing
SolrQuery
PHP Manual

SolrQuery::setFacetMinCount

(PECL solr >= 0.9.2)

SolrQuery::setFacetMinCount — Maps to facet.mincount

Opis

public SolrQuery SolrQuery::setFacetMinCount ( int $mincount [, string $field_override ] )

Sets the minimum counts for facet fields that should be included in the response

Parametry

mincount

The minimum count

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetMethod
SolrQuery::setFacetMissing
SolrQuery


Maps to facet.missing

SolrQuery::setFacetMinCount
SolrQuery::setFacetOffset
SolrQuery
PHP Manual

SolrQuery::setFacetMissing

(PECL solr >= 0.9.2)

SolrQuery::setFacetMissing — Maps to facet.missing

Opis

public SolrQuery SolrQuery::setFacetMissing ( bool $flag [, string $field_override ] )

Used to indicate that in addition to the Term-based constraints of a facet field, a count of all matching results which have no value for the field should be computed

Parametry

flag

TRUE turns this feature on. FALSE disables it.

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetMinCount
SolrQuery::setFacetOffset
SolrQuery


Sets the offset into the list of constraints to allow for pagination

SolrQuery::setFacetMissing
SolrQuery::setFacetPrefix
SolrQuery
PHP Manual

SolrQuery::setFacetOffset

(PECL solr >= 0.9.2)

SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination

Opis

public SolrQuery SolrQuery::setFacetOffset ( int $offset [, string $field_override ] )

Sets the offset into the list of constraints to allow for pagination.

Parametry

offset

The offset

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetMissing
SolrQuery::setFacetPrefix
SolrQuery


Specifies a string prefix with which to limits the terms on which to facet

SolrQuery::setFacetOffset
SolrQuery::setFacetSort
SolrQuery
PHP Manual

SolrQuery::setFacetPrefix

(PECL solr >= 0.9.2)

SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet

Opis

public SolrQuery SolrQuery::setFacetPrefix ( string $prefix [, string $field_override ] )

Specifies a string prefix with which to limits the terms on which to facet.

Parametry

prefix

The prefix string

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetOffset
SolrQuery::setFacetSort
SolrQuery


Determines the ordering of the facet field constraints

SolrQuery::setFacetPrefix
SolrQuery::setHighlight
SolrQuery
PHP Manual

SolrQuery::setFacetSort

(PECL solr >= 0.9.2)

SolrQuery::setFacetSort — Determines the ordering of the facet field constraints

Opis

public SolrQuery SolrQuery::setFacetSort ( int $facetSort [, string $field_override ] )

Determines the ordering of the facet field constraints

Parametry

facetSort

Use SolrQuery::FACET_SORT_INDEX for sorting by index order or SolrQuery::FACET_SORT_COUNT for sorting by count.

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetPrefix
SolrQuery::setHighlight
SolrQuery


Enables or disables highlighting

SolrQuery::setFacetSort
SolrQuery::setHighlightAlternateField
SolrQuery
PHP Manual

SolrQuery::setHighlight

(PECL solr >= 0.9.2)

SolrQuery::setHighlight — Enables or disables highlighting

Opis

public SolrQuery SolrQuery::setHighlight ( bool $flag )

Setting it to TRUE enables highlighted snippets to be generated in the query response.

Setting it to FALSE disables highlighting

Parametry

flag

Enable or disable highlighting

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setFacetSort
SolrQuery::setHighlightAlternateField
SolrQuery


Specifies the backup field to use

SolrQuery::setHighlight
SolrQuery::setHighlightFormatter
SolrQuery
PHP Manual

SolrQuery::setHighlightAlternateField

(PECL solr >= 0.9.2)

SolrQuery::setHighlightAlternateField — Specifies the backup field to use

Opis

public SolrQuery SolrQuery::setHighlightAlternateField ( string $field [, string $field_override ] )

If a snippet cannot be generated because there were no matching terms, one can specify a field to use as the backup or default summary

Parametry

field

The name of the backup field

field_override

The name of the field we are overriding this setting for.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlight
SolrQuery::setHighlightFormatter
SolrQuery


Specify a formatter for the highlight output

SolrQuery::setHighlightAlternateField
SolrQuery::setHighlightFragmenter
SolrQuery
PHP Manual

SolrQuery::setHighlightFormatter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output

Opis

public SolrQuery SolrQuery::setHighlightFormatter ( string $formatter [, string $field_override ] )

Specify a formatter for the highlight output.

Parametry

formatter

Currently the only legal value is "simple"

field_override

The name of the field.

SolrQuery::setHighlightAlternateField
SolrQuery::setHighlightFragmenter
SolrQuery


Sets a text snippet generator for highlighted text

SolrQuery::setHighlightFormatter
SolrQuery::setHighlightFragsize
SolrQuery
PHP Manual

SolrQuery::setHighlightFragmenter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text

Opis

public SolrQuery SolrQuery::setHighlightFragmenter ( string $fragmenter [, string $field_override ] )

Specify a text snippet generator for highlighted text.

Parametry

fragmenter

The standard fragmenter is gap. Another option is regex, which tries to create fragments that resembles a certain regular expression

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightFormatter
SolrQuery::setHighlightFragsize
SolrQuery


The size of fragments to consider for highlighting

SolrQuery::setHighlightFragmenter
SolrQuery::setHighlightHighlightMultiTerm
SolrQuery
PHP Manual

SolrQuery::setHighlightFragsize

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting

Opis

public SolrQuery SolrQuery::setHighlightFragsize ( int $size [, string $field_override ] )

Sets the size, in characters, of fragments to consider for highlighting. "0" indicates that the whole field value should be used (no fragmenting).

Parametry

size

The size, in characters, of fragments to consider for highlighting

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightFragmenter
SolrQuery::setHighlightHighlightMultiTerm
SolrQuery


Use SpanScorer to highlight phrase terms

SolrQuery::setHighlightFragsize
SolrQuery::setHighlightMaxAlternateFieldLength
SolrQuery
PHP Manual

SolrQuery::setHighlightHighlightMultiTerm

(PECL solr >= 0.9.2)

SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms

Opis

public SolrQuery SolrQuery::setHighlightHighlightMultiTerm ( bool $flag )

Use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Parametry

flag

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightFragsize
SolrQuery::setHighlightMaxAlternateFieldLength
SolrQuery


Sets the maximum number of characters of the field to return

SolrQuery::setHighlightHighlightMultiTerm
SolrQuery::setHighlightMaxAnalyzedChars
SolrQuery
PHP Manual

SolrQuery::setHighlightMaxAlternateFieldLength

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return

Opis

public SolrQuery SolrQuery::setHighlightMaxAlternateFieldLength ( int $fieldLength [, string $field_override ] )

If SolrQuery::setHighlightAlternateField() was passed the value TRUE, this parameter specifies the maximum number of characters of the field to return

Any value less than or equal to 0 means unlimited.

Parametry

fieldLength

The length of the field

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightHighlightMultiTerm
SolrQuery::setHighlightMaxAnalyzedChars
SolrQuery


Specifies the number of characters into a document to look for suitable snippets

SolrQuery::setHighlightMaxAlternateFieldLength
SolrQuery::setHighlightMergeContiguous
SolrQuery
PHP Manual

SolrQuery::setHighlightMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets

Opis

public SolrQuery SolrQuery::setHighlightMaxAnalyzedChars ( int $value )

Specifies the number of characters into a document to look for suitable snippets

Parametry

value

The number of characters into a document to look for suitable snippets

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightMaxAlternateFieldLength
SolrQuery::setHighlightMergeContiguous
SolrQuery


Whether or not to collapse contiguous fragments into a single fragment

SolrQuery::setHighlightMaxAnalyzedChars
SolrQuery::setHighlightRegexMaxAnalyzedChars
SolrQuery
PHP Manual

SolrQuery::setHighlightMergeContiguous

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment

Opis

public SolrQuery SolrQuery::setHighlightMergeContiguous ( bool $flag [, string $field_override ] )

Whether or not to collapse contiguous fragments into a single fragment

Parametry

value

Whether or not to collapse contiguous fragments into a single fragment

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightMaxAnalyzedChars
SolrQuery::setHighlightRegexMaxAnalyzedChars
SolrQuery


Specify the maximum number of characters to analyze

SolrQuery::setHighlightMergeContiguous
SolrQuery::setHighlightRegexPattern
SolrQuery
PHP Manual

SolrQuery::setHighlightRegexMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze

Opis

public SolrQuery SolrQuery::setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars )

Specify the maximum number of characters to analyze from a field when using the regex fragmenter

Parametry

maxAnalyzedChars

The maximum number of characters to analyze from a field when using the regex fragmenter

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightMergeContiguous
SolrQuery::setHighlightRegexPattern
SolrQuery


Specify the regular expression for fragmenting

SolrQuery::setHighlightRegexMaxAnalyzedChars
SolrQuery::setHighlightRegexSlop
SolrQuery
PHP Manual

SolrQuery::setHighlightRegexPattern

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting

Opis

public SolrQuery SolrQuery::setHighlightRegexPattern ( string $value )

Specifies the regular expression for fragmenting. This could be used to extract sentences

Parametry

value

The regular expression for fragmenting. This could be used to extract sentences

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightRegexMaxAnalyzedChars
SolrQuery::setHighlightRegexSlop
SolrQuery


Sets the factor by which the regex fragmenter can stray from the ideal fragment size

SolrQuery::setHighlightRegexPattern
SolrQuery::setHighlightRequireFieldMatch
SolrQuery
PHP Manual

SolrQuery::setHighlightRegexSlop

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size

Opis

public SolrQuery SolrQuery::setHighlightRegexSlop ( float $factor )

The factor by which the regex fragmenter can stray from the ideal fragment size ( specfied by SolrQuery::setHighlightFragsize )to accomodate the regular expression

Parametry

factor

The factor by which the regex fragmenter can stray from the ideal fragment size

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightRegexPattern
SolrQuery::setHighlightRequireFieldMatch
SolrQuery


Require field matching during highlighting

SolrQuery::setHighlightRegexSlop
SolrQuery::setHighlightSimplePost
SolrQuery
PHP Manual

SolrQuery::setHighlightRequireFieldMatch

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting

Opis

public SolrQuery SolrQuery::setHighlightRequireFieldMatch ( bool $flag )

If TRUE, then a field will only be highlighted if the query matched in this particular field.

This will only work if SolrQuery::setHighlightUsePhraseHighlighter() was set to TRUE

Parametry

flag

TRUE or FALSE

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightRegexSlop
SolrQuery::setHighlightSimplePost
SolrQuery


Sets the text which appears after a highlighted term

SolrQuery::setHighlightRequireFieldMatch
SolrQuery::setHighlightSimplePre
SolrQuery
PHP Manual

SolrQuery::setHighlightSimplePost

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term

Opis

public SolrQuery SolrQuery::setHighlightSimplePost ( string $simplePost [, string $field_override ] )

Sets the text which appears before a highlighted term

Parametry

simplePost

Sets the text which appears after a highlighted term

The default is </em>

field_override

The name of the field.

SolrQuery::setHighlightRequireFieldMatch
SolrQuery::setHighlightSimplePre
SolrQuery


Sets the text which appears before a highlighted term

SolrQuery::setHighlightSimplePost
SolrQuery::setHighlightSnippets
SolrQuery
PHP Manual

SolrQuery::setHighlightSimplePre

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term

Opis

public SolrQuery SolrQuery::setHighlightSimplePre ( string $simplePre [, string $field_override ] )

Sets the text which appears before a highlighted term

The default is <em>

Parametry

simplePre

The text which appears before a highlighted term

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightSimplePost
SolrQuery::setHighlightSnippets
SolrQuery


Sets the maximum number of highlighted snippets to generate per field

SolrQuery::setHighlightSimplePre
SolrQuery::setHighlightUsePhraseHighlighter
SolrQuery
PHP Manual

SolrQuery::setHighlightSnippets

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field

Opis

public SolrQuery SolrQuery::setHighlightSnippets ( int $value [, string $field_override ] )

Sets the maximum number of highlighted snippets to generate per field

Parametry

value

The maximum number of highlighted snippets to generate per field

field_override

The name of the field.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightSimplePre
SolrQuery::setHighlightUsePhraseHighlighter
SolrQuery


Whether to highlight phrase terms only when they appear within the query phrase

SolrQuery::setHighlightSnippets
SolrQuery::setMlt
SolrQuery
PHP Manual

SolrQuery::setHighlightUsePhraseHighlighter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase

Opis

public SolrQuery SolrQuery::setHighlightUsePhraseHighlighter ( bool $flag )

Sets whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

Parametry

value

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightSnippets
SolrQuery::setMlt
SolrQuery


Enables or disables moreLikeThis

SolrQuery::setHighlightUsePhraseHighlighter
SolrQuery::setMltBoost
SolrQuery
PHP Manual

SolrQuery::setMlt

(PECL solr >= 0.9.2)

SolrQuery::setMlt — Enables or disables moreLikeThis

Opis

public SolrQuery SolrQuery::setMlt ( bool $flag )

Enables or disables moreLikeThis

Parametry

flag

TRUE enables it and FALSE turns it off.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setHighlightUsePhraseHighlighter
SolrQuery::setMltBoost
SolrQuery


Set if the query will be boosted by the interesting term relevance

SolrQuery::setMlt
SolrQuery::setMltCount
SolrQuery
PHP Manual

SolrQuery::setMltBoost

(PECL solr >= 0.9.2)

SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance

Opis

public SolrQuery SolrQuery::setMltBoost ( bool $flag )

Set if the query will be boosted by the interesting term relevance

Parametry

value

Sets to TRUE or FALSE

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMlt
SolrQuery::setMltCount
SolrQuery


Set the number of similar documents to return for each result

SolrQuery::setMltBoost
SolrQuery::setMltMaxNumQueryTerms
SolrQuery
PHP Manual

SolrQuery::setMltCount

(PECL solr >= 0.9.2)

SolrQuery::setMltCount — Set the number of similar documents to return for each result

Opis

public SolrQuery SolrQuery::setMltCount ( int $count )

Set the number of similar documents to return for each result

Parametry

count

The number of similar documents to return for each result

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMltBoost
SolrQuery::setMltMaxNumQueryTerms
SolrQuery


Sets the maximum number of query terms included

SolrQuery::setMltCount
SolrQuery::setMltMaxNumTokens
SolrQuery
PHP Manual

SolrQuery::setMltMaxNumQueryTerms

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included

Opis

public SolrQuery SolrQuery::setMltMaxNumQueryTerms ( int $value )

Sets the maximum number of query terms that will be included in any generated query.

Parametry

value

The maximum number of query terms that will be included in any generated query

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMltCount
SolrQuery::setMltMaxNumTokens
SolrQuery


Specifies the maximum number of tokens to parse

SolrQuery::setMltMaxNumQueryTerms
SolrQuery::setMltMaxWordLength
SolrQuery
PHP Manual

SolrQuery::setMltMaxNumTokens

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse

Opis

public SolrQuery SolrQuery::setMltMaxNumTokens ( int $value )

Specifies the maximum number of tokens to parse in each example doc field that is not stored with TermVector support.

Parametry

value

The maximum number of tokens to parse

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMltMaxNumQueryTerms
SolrQuery::setMltMaxWordLength
SolrQuery


Sets the maximum word length

SolrQuery::setMltMaxNumTokens
SolrQuery::setMltMinDocFrequency
SolrQuery
PHP Manual

SolrQuery::setMltMaxWordLength

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxWordLength — Sets the maximum word length

Opis

public SolrQuery SolrQuery::setMltMaxWordLength ( int $maxWordLength )

Sets the maximum word length above which words will be ignored.

Parametry

maxWordLength

The maximum word length above which words will be ignored

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMltMaxNumTokens
SolrQuery::setMltMinDocFrequency
SolrQuery


Sets the mltMinDoc frequency

SolrQuery::setMltMaxWordLength
SolrQuery::setMltMinTermFrequency
SolrQuery
PHP Manual

SolrQuery::setMltMinDocFrequency

(PECL solr >= 0.9.2)

SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency

Opis

public SolrQuery SolrQuery::setMltMinDocFrequency ( int $minDocFrequency )

The frequency at which words will be ignored which do not occur in at least this many docs.

Parametry

minDocFrequency

Sets the frequency at which words will be ignored which do not occur in at least this many docs.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMltMaxWordLength
SolrQuery::setMltMinTermFrequency
SolrQuery


Sets the frequency below which terms will be ignored in the source docs

SolrQuery::setMltMinDocFrequency
SolrQuery::setMltMinWordLength
SolrQuery
PHP Manual

SolrQuery::setMltMinTermFrequency

(PECL solr >= 0.9.2)

SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs

Opis

public SolrQuery SolrQuery::setMltMinTermFrequency ( int $minTermFrequency )

Sets the frequency below which terms will be ignored in the source docs

Parametry

minTermFrequency

The frequency below which terms will be ignored in the source docs

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMltMinDocFrequency
SolrQuery::setMltMinWordLength
SolrQuery


Sets the minimum word length

SolrQuery::setMltMinTermFrequency
SolrQuery::setOmitHeader
SolrQuery
PHP Manual

SolrQuery::setMltMinWordLength

(PECL solr >= 0.9.2)

SolrQuery::setMltMinWordLength — Sets the minimum word length

Opis

public SolrQuery SolrQuery::setMltMinWordLength ( int $minWordLength )

Sets the minimum word length below which words will be ignored.

Parametry

minWordLength

The minimum word length below which words will be ignored

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMltMinTermFrequency
SolrQuery::setOmitHeader
SolrQuery


Exclude the header from the returned results

SolrQuery::setMltMinWordLength
SolrQuery::setQuery
SolrQuery
PHP Manual

SolrQuery::setOmitHeader

(PECL solr >= 0.9.2)

SolrQuery::setOmitHeader — Exclude the header from the returned results

Opis

public SolrQuery SolrQuery::setOmitHeader ( bool $flag )

Exclude the header from the returned results.

Parametry

flag

TRUE excludes the header from the result.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setMltMinWordLength
SolrQuery::setQuery
SolrQuery


Sets the search query

SolrQuery::setOmitHeader
SolrQuery::setRows
SolrQuery
PHP Manual

SolrQuery::setQuery

(PECL solr >= 0.9.2)

SolrQuery::setQuery — Sets the search query

Opis

public SolrQuery SolrQuery::setQuery ( string $query )

Sets the search query.

Parametry

query

The search query

Zwracane wartości

Returns the current SolrQuery object

SolrQuery::setOmitHeader
SolrQuery::setRows
SolrQuery


Specifies the maximum number of rows to return in the result

SolrQuery::setQuery
SolrQuery::setShowDebugInfo
SolrQuery
PHP Manual

SolrQuery::setRows

(PECL solr >= 0.9.2)

SolrQuery::setRows — Specifies the maximum number of rows to return in the result

Opis

public SolrQuery SolrQuery::setRows ( int $rows )

Specifies the maximum number of rows to return in the result

Parametry

rows

The maximum number of rows to return

Zwracane wartości

Returns the current SolrQuery object.

SolrQuery::setQuery
SolrQuery::setShowDebugInfo
SolrQuery


Flag to show debug information

SolrQuery::setRows
SolrQuery::setStart
SolrQuery
PHP Manual

SolrQuery::setShowDebugInfo

(PECL solr >= 0.9.2)

SolrQuery::setShowDebugInfo — Flag to show debug information

Opis

public SolrQuery SolrQuery::setShowDebugInfo ( bool $flag )

Whether to show debug info

Parametry

flag

Whether to show debug info. TRUE or FALSE

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setRows
SolrQuery::setStart
SolrQuery


Specifies the number of rows to skip

SolrQuery::setShowDebugInfo
SolrQuery::setStats
SolrQuery
PHP Manual

SolrQuery::setStart

(PECL solr >= 0.9.2)

SolrQuery::setStart — Specifies the number of rows to skip

Opis

public SolrQuery SolrQuery::setStart ( int $start )

Specifies the number of rows to skip. Useful in pagination of results.

Parametry

start

The number of rows to skip.

Zwracane wartości

Returns the current SolrQuery object.

SolrQuery::setShowDebugInfo
SolrQuery::setStats
SolrQuery


Enables or disables the Stats component

SolrQuery::setStart
SolrQuery::setTerms
SolrQuery
PHP Manual

SolrQuery::setStats

(PECL solr >= 0.9.2)

SolrQuery::setStats — Enables or disables the Stats component

Opis

public SolrQuery SolrQuery::setStats ( bool $flag )

Enables or disables the Stats component.

Parametry

flag

TRUE turns on the stats component and FALSE disables it.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setStart
SolrQuery::setTerms
SolrQuery


Enables or disables the TermsComponent

SolrQuery::setStats
SolrQuery::setTermsField
SolrQuery
PHP Manual

SolrQuery::setTerms

(PECL solr >= 0.9.2)

SolrQuery::setTerms — Enables or disables the TermsComponent

Opis

public SolrQuery SolrQuery::setTerms ( bool $flag )

Enables or disables the TermsComponent

Parametry

flag

TRUE enables it. FALSE turns it off

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setStats
SolrQuery::setTermsField
SolrQuery


Sets the name of the field to get the Terms from

SolrQuery::setTerms
SolrQuery::setTermsIncludeLowerBound
SolrQuery
PHP Manual

SolrQuery::setTermsField

(PECL solr >= 0.9.2)

SolrQuery::setTermsField — Sets the name of the field to get the Terms from

Opis

public SolrQuery SolrQuery::setTermsField ( string $fieldname )

Sets the name of the field to get the terms from

Parametry

fieldname

The field name

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTerms
SolrQuery::setTermsIncludeLowerBound
SolrQuery


Include the lower bound term in the result set

SolrQuery::setTermsField
SolrQuery::setTermsIncludeUpperBound
SolrQuery
PHP Manual

SolrQuery::setTermsIncludeLowerBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set

Opis

public SolrQuery SolrQuery::setTermsIncludeLowerBound ( bool $flag )

Include the lower bound term in the result set.

Parametry

flag

Include the lower bound term in the result set

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsField
SolrQuery::setTermsIncludeUpperBound
SolrQuery


Include the upper bound term in the result set

SolrQuery::setTermsIncludeLowerBound
SolrQuery::setTermsLimit
SolrQuery
PHP Manual

SolrQuery::setTermsIncludeUpperBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set

Opis

public SolrQuery SolrQuery::setTermsIncludeUpperBound ( bool $flag )

Include the upper bound term in the result set.

Parametry

flag

TRUE or FALSE

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsIncludeLowerBound
SolrQuery::setTermsLimit
SolrQuery


Sets the maximum number of terms to return

SolrQuery::setTermsIncludeUpperBound
SolrQuery::setTermsLowerBound
SolrQuery
PHP Manual

SolrQuery::setTermsLimit

(PECL solr >= 0.9.2)

SolrQuery::setTermsLimit — Sets the maximum number of terms to return

Opis

public SolrQuery SolrQuery::setTermsLimit ( int $limit )

Sets the maximum number of terms to return

Parametry

limit

The maximum number of terms to return. All the terms will be returned if the limit is negative.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsIncludeUpperBound
SolrQuery::setTermsLowerBound
SolrQuery


Specifies the Term to start from

SolrQuery::setTermsLimit
SolrQuery::setTermsMaxCount
SolrQuery
PHP Manual

SolrQuery::setTermsLowerBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsLowerBound — Specifies the Term to start from

Opis

public SolrQuery SolrQuery::setTermsLowerBound ( string $lowerBound )

Specifies the Term to start from

Parametry

lowerBound

The lower bound Term

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsLimit
SolrQuery::setTermsMaxCount
SolrQuery


Sets the maximum document frequency

SolrQuery::setTermsLowerBound
SolrQuery::setTermsMinCount
SolrQuery
PHP Manual

SolrQuery::setTermsMaxCount

(PECL solr >= 0.9.2)

SolrQuery::setTermsMaxCount — Sets the maximum document frequency

Opis

public SolrQuery SolrQuery::setTermsMaxCount ( int $frequency )

Sets the maximum document frequency.

Parametry

frequency

The maximum document frequency.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsLowerBound
SolrQuery::setTermsMinCount
SolrQuery


Sets the minimum document frequency

SolrQuery::setTermsMaxCount
SolrQuery::setTermsPrefix
SolrQuery
PHP Manual

SolrQuery::setTermsMinCount

(PECL solr >= 0.9.2)

SolrQuery::setTermsMinCount — Sets the minimum document frequency

Opis

public SolrQuery SolrQuery::setTermsMinCount ( int $frequency )

Sets the minimum doc frequency to return in order to be included

Parametry

frequency

The minimum frequency

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsMaxCount
SolrQuery::setTermsPrefix
SolrQuery


Restrict matches to terms that start with the prefix

SolrQuery::setTermsMinCount
SolrQuery::setTermsReturnRaw
SolrQuery
PHP Manual

SolrQuery::setTermsPrefix

(PECL solr >= 0.9.2)

SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix

Opis

public SolrQuery SolrQuery::setTermsPrefix ( string $prefix )

Restrict matches to terms that start with the prefix

Parametry

prefix

Restrict matches to terms that start with the prefix

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsMinCount
SolrQuery::setTermsReturnRaw
SolrQuery


Return the raw characters of the indexed term

SolrQuery::setTermsPrefix
SolrQuery::setTermsSort
SolrQuery
PHP Manual

SolrQuery::setTermsReturnRaw

(PECL solr >= 0.9.2)

SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term

Opis

public SolrQuery SolrQuery::setTermsReturnRaw ( bool $flag )

If true, return the raw characters of the indexed term, regardless of if it is human readable

Parametry

value

TRUE or FALSE

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsPrefix
SolrQuery::setTermsSort
SolrQuery


Specifies how to sort the returned terms

SolrQuery::setTermsReturnRaw
SolrQuery::setTermsUpperBound
SolrQuery
PHP Manual

SolrQuery::setTermsSort

(PECL solr >= 0.9.2)

SolrQuery::setTermsSort — Specifies how to sort the returned terms

Opis

public SolrQuery SolrQuery::setTermsSort ( int $sortType )

If SolrQuery::TERMS_SORT_COUNT, sorts the terms by the term frequency (highest count first). If SolrQuery::TERMS_SORT_INDEX, returns the terms in index order

Parametry

sortType

SolrQuery::TERMS_SORT_INDEX or SolrQuery::TERMS_SORT_COUNT

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsReturnRaw
SolrQuery::setTermsUpperBound
SolrQuery


Sets the term to stop at

SolrQuery::setTermsSort
SolrQuery::setTimeAllowed
SolrQuery
PHP Manual

SolrQuery::setTermsUpperBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsUpperBound — Sets the term to stop at

Opis

public SolrQuery SolrQuery::setTermsUpperBound ( string $upperBound )

Sets the term to stop at

Parametry

upperBound

The term to stop at

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsSort
SolrQuery::setTimeAllowed
SolrQuery


The time allowed for search to finish

SolrQuery::setTermsUpperBound
SolrException
SolrQuery
PHP Manual

SolrQuery::setTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::setTimeAllowed — The time allowed for search to finish

Opis

public SolrQuery SolrQuery::setTimeAllowed ( int $timeAllowed )

The time allowed for a search to finish. This value only applies to the search and not to requests in general. Time is in milliseconds. Values less than or equal to zero implies no time restriction. Partial results may be returned, if there are any.

Parametry

timeAllowed

The time allowed for a search to finish.

Zwracane wartości

Returns the current SolrQuery object, if the return value is used.

SolrQuery::setTermsUpperBound
SolrException
SolrQuery


The SolrException class

(No version information available, might only be in SVN)

Wstęp

This is the base class for all exception thrown by the Solr extension classes.

Krótki opis klasy

SolrException extends Exception {
/* Właściwości */
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Metody */
public array getInternalInfo ( 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

message

The error message

code

The error code

file

The userspace php source file where exception was generated

line

The line in userspace php source file where exception was generated

sourceline

The line in c-space source file where exception was generated

sourcefile

The c-space source file where exception was generated

zif_name

The c-space function where exception was generated

Spis treści

  • SolrException::getInternalInfo — Returns internal information where the Exception was thrown
SolrQuery::setTimeAllowed
SolrException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrException
SolrClientException
SolrException
PHP Manual

SolrException::getInternalInfo

(PECL solr >= 0.9.2)

SolrException::getInternalInfo — Returns internal information where the Exception was thrown

Opis

public array SolrException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrException
SolrClientException
SolrException


The SolrClientException class

(No version information available, might only be in SVN)

Wstęp

An exception thrown when there is an error while making a request to the server from the client.

Krótki opis klasy

SolrClientException extends SolrException {
/* Właściwości */
/* Metody */
public array getInternalInfo ( void )
/* Metody dziedziczone */
public array SolrException::getInternalInfo ( void )
}

Właściwości

message

The error message

code

The error code

file

The userspace php source file where exception was generated

line

The line in userspace php source file where exception was generated

sourceline

The line in c-space source file where exception was generated

sourcefile

The c-space source file where exception was generated

zif_name

The c-space function where exception was generated

Spis treści

  • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown
SolrException::getInternalInfo
SolrClientException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrClientException
SolrIllegalArgumentException
SolrClientException
PHP Manual

SolrClientException::getInternalInfo

(PECL solr >= 0.9.2)

SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown

Opis

public array SolrClientException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrClientException
SolrIllegalArgumentException
SolrClientException


The SolrIllegalArgumentException class

(No version information available, might only be in SVN)

Wstęp

This object is thrown when an illeglal or invalid argument is passed to a method.

Krótki opis klasy

SolrIllegalArgumentException extends SolrException {
/* Właściwości */
/* Metody */
public array getInternalInfo ( void )
/* Metody dziedziczone */
public array SolrException::getInternalInfo ( void )
}

Właściwości

message

The error message

code

The error code

file

The userspace php source file where exception was generated

line

The line in userspace php source file where exception was generated

sourceline

The line in c-space source file where exception was generated

sourcefile

The c-space source file where exception was generated

zif_name

The c-space function where exception was generated

Spis treści

  • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown
SolrClientException::getInternalInfo
SolrIllegalArgumentException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrIllegalArgumentException
SolrIllegalOperationException
SolrIllegalArgumentException
PHP Manual

SolrIllegalArgumentException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown

Opis

public array SolrIllegalArgumentException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

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

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrIllegalArgumentException
SolrIllegalOperationException
SolrIllegalArgumentException


The SolrIllegalOperationException class

(No version information available, might only be in SVN)

Wstęp

This object is thrown when an illegal or unsupported operation is performed on an object.

Krótki opis klasy

SolrIllegalOperationException extends SolrException {
/* Właściwości */
/* Metody */
public array getInternalInfo ( void )
/* Metody dziedziczone */
public array SolrException::getInternalInfo ( void )
}

Właściwości

message

The error message

code

The error code

file

The userspace php source file where exception was generated

line

The line in userspace php source file where exception was generated

sourceline

The line in c-space source file where exception was generated

sourcefile

The c-space source file where exception was generated

zif_name

The c-space function where exception was generated

Spis treści

  • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown
SolrIllegalArgumentException::getInternalInfo
SolrIllegalOperationException::getInternalInfo
Solr


Returns internal information where the Exception was thrown

SolrIllegalOperationException
Sphinx
SolrIllegalOperationException
PHP Manual

SolrIllegalOperationException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

Opis

public array SolrIllegalOperationException::getInternalInfo ( void )

Returns internal information where the Exception was thrown.

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

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

SolrIllegalOperationException
Sphinx
SolrIllegalOperationException


Sphinx Client

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • SphinxClient — The SphinxClient class
    • SphinxClient::addQuery — Add query to multi-query batch
    • SphinxClient::buildExcerpts — Build text snippets
    • SphinxClient::buildKeywords — Extract keywords from query
    • SphinxClient::close — Closes previously opened persistent connection
    • SphinxClient::__construct — Create a new SphinxClient object
    • SphinxClient::escapeString — Escape special characters
    • SphinxClient::getLastError — Get the last error message
    • SphinxClient::getLastWarning — Get the last warning
    • SphinxClient::open — Opens persistent connection to the server
    • SphinxClient::query — Execute search query
    • SphinxClient::resetFilters — Clear all filters
    • SphinxClient::resetGroupBy — Clear all group-by settings
    • SphinxClient::runQueries — Run a batch of search queries
    • SphinxClient::setArrayResult — Change the format of result set array
    • SphinxClient::setConnectTimeout — Set connection timeout
    • SphinxClient::setFieldWeights — Set field weights
    • SphinxClient::setFilter — Add new integer values set filter
    • SphinxClient::setFilterFloatRange — Add new float range filter
    • SphinxClient::setFilterRange — Add new integer range filter
    • SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations
    • SphinxClient::setGroupBy — Set grouping attribute
    • SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations
    • SphinxClient::setIDRange — Set a range of accepted document IDs
    • SphinxClient::setIndexWeights — Set per-index weights
    • SphinxClient::setLimits — Set offset and limit of the result set
    • SphinxClient::setMatchMode — Set full-text query matching mode
    • SphinxClient::setMaxQueryTime — Set maximum query time
    • SphinxClient::setOverride — Sets temporary per-document attribute value overrides
    • SphinxClient::setRankingMode — Set ranking mode
    • SphinxClient::setRetries — Set retry count and delay
    • SphinxClient::setSelect — Set select clause
    • SphinxClient::setServer — Set searchd host and port
    • SphinxClient::setSortMode — Set matches sorting mode
    • SphinxClient::status — Queries searchd status
    • SphinxClient::updateAttributes — Update document attributes
SolrIllegalOperationException::getInternalInfo
Wstęp
Systemy wyszukiwania informacji


Wstęp

This extension provides bindings for Sphinx search client library. Sphinx is a standalone search engine meant to provide fast, size-efficient and relevant fulltext search functions to other applications. Sphinx was specially designed to integrate well with SQL databases and scripting languages. Both Sphinx and its client library can be obtained from the » official site

Sphinx
Instalacja/Konfiguracja
Sphinx


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Sphinx


Wymagania

PECL/sphinx requires PHP 5.2.2 or newer.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/sphinx.

If the ./configure script generated by phpize is having trouble finding the libsphinxclient files (for example, it was installed into a custom prefix directory), use ./configure --with-sphinx=$PREFIX, where $PREFIX is installation prefix of libsphinxclient.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

SEARCHD_OK (integer)
SEARCHD_ERROR (integer)
SEARCHD_RETRY (integer)
SEARCHD_WARNING (integer)
SPH_MATCH_ALL (integer)
SPH_MATCH_ANY (integer)
SPH_MATCH_PHRASE (integer)
SPH_MATCH_BOOLEAN (integer)
SPH_MATCH_EXTENDED (integer)
SPH_MATCH_FULLSCAN (integer)
SPH_MATCH_EXTENDED2 (integer)
SPH_RANK_PROXIMITY_BM25 (integer)
SPH_RANK_BM25 (integer)
SPH_RANK_NONE (integer)
SPH_RANK_WORDCOUNT (integer)
SPH_SORT_RELEVANCE (integer)
SPH_SORT_ATTR_DESC (integer)
SPH_SORT_ATTR_ASC (integer)
SPH_SORT_TIME_SEGMENTS (integer)
SPH_SORT_EXTENDED (integer)
SPH_SORT_EXPR (integer)
SPH_FILTER_VALUES (integer)
SPH_FILTER_RANGE (integer)
SPH_FILTER_FLOATRANGE (integer)
SPH_ATTR_INTEGER (integer)
SPH_ATTR_TIMESTAMP (integer)
SPH_ATTR_ORDINAL (integer)
SPH_ATTR_BOOL (integer)
SPH_ATTR_FLOAT (integer)
SPH_ATTR_MULTI (integer)
SPH_GROUPBY_DAY (integer)
SPH_GROUPBY_WEEK (integer)
SPH_GROUPBY_MONTH (integer)
SPH_GROUPBY_YEAR (integer)
SPH_GROUPBY_ATTR (integer)
SPH_GROUPBY_ATTRPAIR (integer)

Typy zasobów
Przykłady
Sphinx


Przykłady

Przykład #1 Basic usage example

<?php

$s = new SphinxClient;
$s->setServer("localhost", 6712);
$s->setMatchMode(SPH_MATCH_ANY);
$s->setMaxQueryTime(3);

$result = $s->query("test");

var_dump($result);

?>

Powyższy przykład wyświetli coś podobnego do:

array(10) {
  ["error"]=>
  string(0) ""
  ["warning"]=>
  string(0) ""
  ["status"]=>
  int(0)
  ["fields"]=>
  array(3) {
    [0]=>
    string(7) "subject"
    [1]=>
    string(4) "body"
    [2]=>
    string(6) "author"
  }
  ["attrs"]=>
  array(0) {
  }
  ["matches"]=>
  array(1) {
    [3]=>
    array(2) {
      ["weight"]=>
      int(1)
      ["attrs"]=>
      array(0) {
      }
    }
  }
  ["total"]=>
  int(1)
  ["total_found"]=>
  int(1)
  ["time"]=>
  float(0)
  ["words"]=>
  array(1) {
    ["to"]=>
    array(2) {
      ["docs"]=>
      int(1)
      ["hits"]=>
      int(1)
    }
  }
}
Stałe predefiniowane
SphinxClient
Sphinx


The SphinxClient class

(No version information available, might only be in SVN)

Wstęp

The SphinxClient class provides object-oriented interface to Sphinx.

Krótki opis klasy

SphinxClient {
/* Metody */
public int addQuery ( string $query [, string $index = "*" [, string $comment = "" ]] )
public array buildExcerpts ( array $docs , string $index , string $words [, array $opts ] )
public array buildKeywords ( string $query , string $index , bool $hits )
public bool close ( void )
public __construct ( void )
public string escapeString ( string $string )
public string getLastError ( void )
public string getLastWarning ( void )
public bool open ( void )
public array query ( string $query [, string $index = "*" [, string $comment = "" ]] )
public void resetFilters ( void )
public void resetGroupBy ( void )
public array runQueries ( void )
public bool setArrayResult ( bool $array_result = false )
public bool setConnectTimeout ( float $timeout )
public bool setFieldWeights ( array $weights )
public bool setFilter ( string $attribute , array $values [, bool $exclude = false ] )
public bool setFilterFloatRange ( string $attribute , float $min , float $max [, bool $exclude = false ] )
public bool setFilterRange ( string $attribute , int $min , int $max [, bool $exclude = false ] )
public bool setGeoAnchor ( string $attrlat , string $attrlong , float $latitude , float $longitude )
public bool setGroupBy ( string $attribute , int $func [, string $groupsort = "@group desc" ] )
public bool setGroupDistinct ( string $attribute )
public bool setIDRange ( int $min , int $max )
public bool setIndexWeights ( array $weights )
public bool setLimits ( int $offset , int $limit [, int $max_matches = 0 [, int $cutoff = 0 ]] )
public bool setMatchMode ( int $mode )
public bool setMaxQueryTime ( int $qtime )
public bool setOverride ( string $attribute , int $type , array $values )
public bool setRankingMode ( int $ranker )
public bool setRetries ( int $count [, int $delay = 0 ] )
public bool setSelect ( string $clause )
public bool setServer ( string $server , int $port )
public bool setSortMode ( int $mode [, string $sortby ] )
public array status ( void )
public int updateAttributes ( string $index , array $attributes , array $values [, bool $mva = false ] )
}

Spis treści

  • SphinxClient::addQuery — Add query to multi-query batch
  • SphinxClient::buildExcerpts — Build text snippets
  • SphinxClient::buildKeywords — Extract keywords from query
  • SphinxClient::close — Closes previously opened persistent connection
  • SphinxClient::__construct — Create a new SphinxClient object
  • SphinxClient::escapeString — Escape special characters
  • SphinxClient::getLastError — Get the last error message
  • SphinxClient::getLastWarning — Get the last warning
  • SphinxClient::open — Opens persistent connection to the server
  • SphinxClient::query — Execute search query
  • SphinxClient::resetFilters — Clear all filters
  • SphinxClient::resetGroupBy — Clear all group-by settings
  • SphinxClient::runQueries — Run a batch of search queries
  • SphinxClient::setArrayResult — Change the format of result set array
  • SphinxClient::setConnectTimeout — Set connection timeout
  • SphinxClient::setFieldWeights — Set field weights
  • SphinxClient::setFilter — Add new integer values set filter
  • SphinxClient::setFilterFloatRange — Add new float range filter
  • SphinxClient::setFilterRange — Add new integer range filter
  • SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations
  • SphinxClient::setGroupBy — Set grouping attribute
  • SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations
  • SphinxClient::setIDRange — Set a range of accepted document IDs
  • SphinxClient::setIndexWeights — Set per-index weights
  • SphinxClient::setLimits — Set offset and limit of the result set
  • SphinxClient::setMatchMode — Set full-text query matching mode
  • SphinxClient::setMaxQueryTime — Set maximum query time
  • SphinxClient::setOverride — Sets temporary per-document attribute value overrides
  • SphinxClient::setRankingMode — Set ranking mode
  • SphinxClient::setRetries — Set retry count and delay
  • SphinxClient::setSelect — Set select clause
  • SphinxClient::setServer — Set searchd host and port
  • SphinxClient::setSortMode — Set matches sorting mode
  • SphinxClient::status — Queries searchd status
  • SphinxClient::updateAttributes — Update document attributes
Przykłady
SphinxClient::addQuery
Sphinx


Add query to multi-query batch

SphinxClient
SphinxClient::buildExcerpts
SphinxClient
PHP Manual

SphinxClient::addQuery

(PECL sphinx >= 0.1.0)

SphinxClient::addQuery — Add query to multi-query batch

Opis

public int SphinxClient::addQuery ( string $query [, string $index = "*" [, string $comment = "" ]] )

Adds query with the current settings to multi-query batch. This method doesn't affect current settings (sorting, filtering, grouping etc.) in any way.

Parametry

query

Query string.

index

An index name (or names).

comment

Zwracane wartości

Returns an index in an array of results that will be returned by SphinxClient::runQueries call or false on error.

Zobacz też:

  • SphinxClient::runQueries
  • SphinxClient::query

SphinxClient
SphinxClient::buildExcerpts
SphinxClient


Build text snippets

SphinxClient::addQuery
SphinxClient::buildKeywords
SphinxClient
PHP Manual

SphinxClient::buildExcerpts

(PECL sphinx >= 0.1.0)

SphinxClient::buildExcerpts — Build text snippets

Opis

public array SphinxClient::buildExcerpts ( array $docs , string $index , string $words [, array $opts ] )

Connects to searchd, requests it to generate excerpts (snippets) from the given documents, and returns the results.

Parametry

docs

Array of strings with documents' contents.

index

Index name.

words

Keywords to highlight.

opts

Associative array of additional highlighting options (see below).

Highlighting options
Option | Description
"before_match" | A string to insert before a keyword match. Default is "<b>".
"after_match" | A string to insert after a keyword match. Default is "</b>".
"chunk_separator" | A string to insert between snippet chunks (passages). Default is " ... ".
"limit" | Maximum snippet size, in symbols (codepoints). Integer, default is 256.
"around" | How much words to pick around each matching keywords block. Integer, default is 5.
"exact_phrase" | Whether to highlight exact query phrase matches only instead of individual keywords. Boolean, default is FALSE.
"single_passage" | Whether to extract single best passage only. Boolean, default is FALSE.

Zwracane wartości

Returns array of snippets on success lub FALSE w przypadku niepowodzenia.

SphinxClient::addQuery
SphinxClient::buildKeywords
SphinxClient


Extract keywords from query

SphinxClient::buildExcerpts
SphinxClient::close
SphinxClient
PHP Manual

SphinxClient::buildKeywords

(PECL sphinx >= 0.1.0)

SphinxClient::buildKeywords — Extract keywords from query

Opis

public array SphinxClient::buildKeywords ( string $query , string $index , bool $hits )

Extracts keywords from query using tokenizer settings for the given index, optionally with per-keyword occurrence statistics.

Parametry

query

A query to extract keywords from.

index

An index to get tokenizing settings and keyword occurrence statistics from.

hits

A boolean flag to enable/disable keyword statistics generation.

Zwracane wartości

Returns an array of associative arrays with per-keyword information.

SphinxClient::buildExcerpts
SphinxClient::close
SphinxClient


Closes previously opened persistent connection

SphinxClient::buildKeywords
SphinxClient::__construct
SphinxClient
PHP Manual

SphinxClient::close

(PECL sphinx >= 1.0.3)

SphinxClient::close — Closes previously opened persistent connection

Opis

public bool SphinxClient::close ( void )

Closes previously opened persistent connection.

Parametry

Ta funkcja nie posiada parametrów.

Rejestr zmian

PECL/sphinx Wersja | Opis
1.0.3 | Added SphinxClient::close(), available only if compiled with libsphinxclient >= 0.9.9.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::open

SphinxClient::buildKeywords
SphinxClient::__construct
SphinxClient


Create a new SphinxClient object

SphinxClient::close
SphinxClient::escapeString
SphinxClient
PHP Manual

SphinxClient::__construct

(PECL sphinx >= 0.1.0)

SphinxClient::__construct — Create a new SphinxClient object

Opis

public SphinxClient::__construct ( void )

Creates a new SphinxClient object.

Parametry

Ta funkcja nie posiada parametrów.

SphinxClient::close
SphinxClient::escapeString
SphinxClient


Escape special characters

SphinxClient::__construct
SphinxClient::getLastError
SphinxClient
PHP Manual

SphinxClient::escapeString

(PECL sphinx >= 0.1.0)

SphinxClient::escapeString — Escape special characters

Opis

public string SphinxClient::escapeString ( string $string )

Escapes characters that are treated as special operators by the query language parser.

Parametry

string

String to escape.

Zwracane wartości

Returns escaped string.

SphinxClient::__construct
SphinxClient::getLastError
SphinxClient


Get the last error message

SphinxClient::escapeString
SphinxClient::getLastWarning
SphinxClient
PHP Manual

SphinxClient::getLastError

(PECL sphinx >= 0.1.0)

SphinxClient::getLastError — Get the last error message

Opis

public string SphinxClient::getLastError ( void )

Returns string with the last error message. If there were no errors during the previous API call, empty string is returned. This method doesn't reset the error message, so you can safely call it several times.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the last error message or an empty string if there were no errors.

Zobacz też:

  • SphinxClient::getLastWarning

SphinxClient::escapeString
SphinxClient::getLastWarning
SphinxClient


Get the last warning

SphinxClient::getLastError
SphinxClient::open
SphinxClient
PHP Manual

SphinxClient::getLastWarning

(PECL sphinx >= 0.1.0)

SphinxClient::getLastWarning — Get the last warning

Opis

public string SphinxClient::getLastWarning ( void )

Returns last warning message. If there were no warnings during the previous API call, empty string is returned. This method doesn't reset the warning, so you can safely call it several times.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the last warning message or an empty string if there were no warnings.

Zobacz też:

  • SphinxClient::getLastError

SphinxClient::getLastError
SphinxClient::open
SphinxClient


Opens persistent connection to the server

SphinxClient::getLastWarning
SphinxClient::query
SphinxClient
PHP Manual

SphinxClient::open

(PECL sphinx >= 1.0.3)

SphinxClient::open — Opens persistent connection to the server

Opis

public bool SphinxClient::open ( void )

Opens persistent connection to the server.

Parametry

Ta funkcja nie posiada parametrów.

Rejestr zmian

PECL/sphinx Wersja | Opis
1.0.3 | Added SphinxClient::open(), available only if compiled with libsphinxclient >= 0.9.9.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::close

SphinxClient::getLastWarning
SphinxClient::query
SphinxClient


Execute search query

SphinxClient::open
SphinxClient::resetFilters
SphinxClient
PHP Manual

SphinxClient::query

(PECL sphinx >= 0.1.0)

SphinxClient::query — Execute search query

Opis

public array SphinxClient::query ( string $query [, string $index = "*" [, string $comment = "" ]] )

Connects to searchd server, runs the given search query with the current settings, obtains and returns the result set.

Parametry

query

Query string.

index

An index name (or names).

comment

Zwracane wartości

On success, SphinxClient::query() returns a list of found matches and additional per-query statistics. The result set is a hash utilize other structures instead of hash) with the following keys and values:

Result set structure
Key | Value description
"matches" | An array with found document IDs as keys and their weight and attributes values as values
"total" | Total number of matches found and retrieved (depends on your settings)
"total_found" | Total number of found documents matching the query
"words" | An array with words (case-folded and stemmed) as keys and per-word statistics as values
"error" | Query error message reported by searchd
"warning" | Query warning reported by searchd

Zobacz też:

  • SphinxClient::runQueries
  • SphinxClient::addQuery

SphinxClient::open
SphinxClient::resetFilters
SphinxClient


Clear all filters

SphinxClient::query
SphinxClient::resetGroupBy
SphinxClient
PHP Manual

SphinxClient::resetFilters

(PECL sphinx >= 0.1.0)

SphinxClient::resetFilters — Clear all filters

Opis

public void SphinxClient::resetFilters ( void )

Clears all currently set filters. This call is normally required when using multi-queries. You might want to set different filters for different queries in the batch. To do that, you should call SphinxClient::resetFilters() and add new filters using the respective calls.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SphinxClient::resetGroupBy

SphinxClient::query
SphinxClient::resetGroupBy
SphinxClient


Clear all group-by settings

SphinxClient::resetFilters
SphinxClient::runQueries
SphinxClient
PHP Manual

SphinxClient::resetGroupBy

(PECL sphinx >= 0.1.0)

SphinxClient::resetGroupBy — Clear all group-by settings

Opis

public void SphinxClient::resetGroupBy ( void )

Clears all currently group-by settings, and disables group-by. This call is normally required only when using multi-queries.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SphinxClient::resetGroupBy

SphinxClient::resetFilters
SphinxClient::runQueries
SphinxClient


Run a batch of search queries

SphinxClient::resetGroupBy
SphinxClient::setArrayResult
SphinxClient
PHP Manual

SphinxClient::runQueries

(PECL sphinx >= 0.1.0)

SphinxClient::runQueries — Run a batch of search queries

Opis

public array SphinxClient::runQueries ( void )

Connects to searchd, runs a batch of all queries added using SphinxClient::addQuery, obtains and returns the result sets.

Zwracane wartości

Returns FALSE on failure and array of result sets on success.

Zobacz też:

  • SphinxClient::addQuery
  • SphinxClient::query

SphinxClient::resetGroupBy
SphinxClient::setArrayResult
SphinxClient


Change the format of result set array

SphinxClient::runQueries
SphinxClient::setConnectTimeout
SphinxClient
PHP Manual

SphinxClient::setArrayResult

(PECL sphinx >= 0.1.0)

SphinxClient::setArrayResult — Change the format of result set array

Opis

public bool SphinxClient::setArrayResult ( bool $array_result = false )

Controls the format of search results set arrays (whether matches should be returned as an array or a hash).

Parametry

array_result

If array_result is FALSE, matches are returned as a hash with document IDs as keys, and other information (weight, attributes) as values. If array_result is TRUE, matches are returned as a plain array with complete per-match information including document IDs.

Zwracane wartości

Always returns TRUE.

SphinxClient::runQueries
SphinxClient::setConnectTimeout
SphinxClient


Set connection timeout

SphinxClient::setArrayResult
SphinxClient::setFieldWeights
SphinxClient
PHP Manual

SphinxClient::setConnectTimeout

(PECL sphinx >= 0.1.0)

SphinxClient::setConnectTimeout — Set connection timeout

Opis

public bool SphinxClient::setConnectTimeout ( float $timeout )

Sets connection timeout (in seconds) for searchd connection.

Parametry

timeout

Timeout in seconds.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setMaxQueryTime

SphinxClient::setArrayResult
SphinxClient::setFieldWeights
SphinxClient


Set field weights

SphinxClient::setConnectTimeout
SphinxClient::setFilter
SphinxClient
PHP Manual

SphinxClient::setFieldWeights

(PECL sphinx >= 0.1.0)

SphinxClient::setFieldWeights — Set field weights

Opis

public bool SphinxClient::setFieldWeights ( array $weights )

Binds per-field weights by name.

Match ranking can be affected by per-field weights. See » Sphinx documentation for an explanation on how phrase proximity ranking is affected. This call lets you specify non-default weights for full-text fields.

The weights must be positive 32-bit integers, so be careful not to hit 32-bit integer maximum. The final weight is a 32-bit integer too. Default weight value is 1. Unknown field names are silently ignored.

Parametry

weights

Associative array of field names and field weights.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setIndexWeights

SphinxClient::setConnectTimeout
SphinxClient::setFilter
SphinxClient


Add new integer values set filter

SphinxClient::setFieldWeights
SphinxClient::setFilterFloatRange
SphinxClient
PHP Manual

SphinxClient::setFilter

(PECL sphinx >= 0.1.0)

SphinxClient::setFilter — Add new integer values set filter

Opis

public bool SphinxClient::setFilter ( string $attribute , array $values [, bool $exclude = false ] )

Adds new integer values set filter to the existing list of filters.

Parametry

attribute

An attribute name.

values

Plain array of integer values.

exclude

If set to TRUE, matching documents are excluded from the result set.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilterRange
  • SphinxClient::resetFilters

SphinxClient::setFieldWeights
SphinxClient::setFilterFloatRange
SphinxClient


Add new float range filter

SphinxClient::setFilter
SphinxClient::setFilterRange
SphinxClient
PHP Manual

SphinxClient::setFilterFloatRange

(PECL sphinx >= 0.1.0)

SphinxClient::setFilterFloatRange — Add new float range filter

Opis

public bool SphinxClient::setFilterFloatRange ( string $attribute , float $min , float $max [, bool $exclude = false ] )

Adds new float range filter to the existing list of filters. Only those documents which have attribute value stored in the index between min and max (including values that are exactly equal to min or max) will be matched (or rejected, if exclude is TRUE).

Parametry

attribute

An attribute name.

min

Minimum value.

max

Maximum value.

exclude

If set to TRUE, matching documents are excluded from the result set.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setFilterRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters

SphinxClient::setFilter
SphinxClient::setFilterRange
SphinxClient


Add new integer range filter

SphinxClient::setFilterFloatRange
SphinxClient::setGeoAnchor
SphinxClient
PHP Manual

SphinxClient::setFilterRange

(PECL sphinx >= 0.1.0)

SphinxClient::setFilterRange — Add new integer range filter

Opis

public bool SphinxClient::setFilterRange ( string $attribute , int $min , int $max [, bool $exclude = false ] )

Adds new integer range filter to the existing list of filters. Only those documents which have attribute value stored in the index between min and max (including values that are exactly equal to min or max) will be matched (or rejected, if exclude is TRUE).

Parametry

attribute

An attribute name.

min

Minimum value.

max

Maximum value.

exclude

If set to TRUE, matching documents are excluded from the result set.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters

SphinxClient::setFilterFloatRange
SphinxClient::setGeoAnchor
SphinxClient


Set anchor point for a geosphere distance calculations

SphinxClient::setFilterRange
SphinxClient::setGroupBy
SphinxClient
PHP Manual

SphinxClient::setGeoAnchor

(PECL sphinx >= 0.1.0)

SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations

Opis

public bool SphinxClient::setGeoAnchor ( string $attrlat , string $attrlong , float $latitude , float $longitude )

Sets anchor point for a geosphere distance (geodistance) calculations and enables them.

Once an anchor point is set, you can use magic "@geodist" attribute name in your filters and/or sorting expressions.

Parametry

attrlat

Name of a latitude attribute.

attrlong

Name of a longitude attribute.

latitude

Anchor latitude in radians.

longitude

Anchor longitude in radians.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilterRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters

SphinxClient::setFilterRange
SphinxClient::setGroupBy
SphinxClient


Set grouping attribute

SphinxClient::setGeoAnchor
SphinxClient::setGroupDistinct
SphinxClient
PHP Manual

SphinxClient::setGroupBy

(PECL sphinx >= 0.1.0)

SphinxClient::setGroupBy — Set grouping attribute

Opis

public bool SphinxClient::setGroupBy ( string $attribute , int $func [, string $groupsort = "@group desc" ] )

Sets grouping attribute, function, and group sorting mode, and enables grouping.

Grouping feature is very similar to GROUP BY clause in SQL. Results produced by this function call are going to be the same as produced by the following pseudo code: SELECT ... GROUP BY $func($attribute) ORDER BY $groupsort.

Parametry

attribute

A string containing group-by attribute name.

func

Constant, which sets a function applied to the attribute value in order to compute group-by key.

groupsort

An optional clause controlling how the groups are sorted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::resetGroupBy
  • SphinxClient::setSortMode
  • SphinxClient::setGroupDistinct

SphinxClient::setGeoAnchor
SphinxClient::setGroupDistinct
SphinxClient


Set attribute name for per-group distinct values count calculations

SphinxClient::setGroupBy
SphinxClient::setIDRange
SphinxClient
PHP Manual

SphinxClient::setGroupDistinct

(PECL sphinx >= 0.1.0)

SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations

Opis

public bool SphinxClient::setGroupDistinct ( string $attribute )

Sets attribute name for per-group distinct values count calculations. Only available for grouping queries. For each group, all values of attribute will be stored, then the amount of distinct values will be calculated and returned to the client. This feature is similar to COUNT(DISTINCT) clause in SQL.

Parametry

attribute

A string containing group-by attribute name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setSortMode
  • SphinxClient::setGroupBy
  • SphinxClient::resetGroupBy

SphinxClient::setGroupBy
SphinxClient::setIDRange
SphinxClient


Set a range of accepted document IDs

SphinxClient::setGroupDistinct
SphinxClient::setIndexWeights
SphinxClient
PHP Manual

SphinxClient::setIDRange

(PECL sphinx >= 0.1.0)

SphinxClient::setIDRange — Set a range of accepted document IDs

Opis

public bool SphinxClient::setIDRange ( int $min , int $max )

Sets an accepted range of document IDs. Default range is from 0 to 0, i.e. no limit. Only those records that have document ID between min and max (including IDs exactly equal to min or max) will be matched.

Parametry

min

Minimum ID value.

max

Maximum ID value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SphinxClient::setGroupDistinct
SphinxClient::setIndexWeights
SphinxClient


Set per-index weights

SphinxClient::setIDRange
SphinxClient::setLimits
SphinxClient
PHP Manual

SphinxClient::setIndexWeights

(PECL sphinx >= 0.1.0)

SphinxClient::setIndexWeights — Set per-index weights

Opis

public bool SphinxClient::setIndexWeights ( array $weights )

Sets per-index weights and enables weighted summing of match weights across different indexes.

Parametry

weights

An associative array mapping string index names to integer weights. Default is empty array, i.e. weighting summing is disabled.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SphinxClient::setIDRange
SphinxClient::setLimits
SphinxClient


Set offset and limit of the result set

SphinxClient::setIndexWeights
SphinxClient::setMatchMode
SphinxClient
PHP Manual

SphinxClient::setLimits

(PECL sphinx >= 0.1.0)

SphinxClient::setLimits — Set offset and limit of the result set

Opis

public bool SphinxClient::setLimits ( int $offset , int $limit [, int $max_matches = 0 [, int $cutoff = 0 ]] )

Sets offset into server-side result set and amount of matches to return to client starting from that offset (limit). Can additionally control maximum server-side result set size for current query (max_matches) and the threshold amount of matches to stop searching at (cutoff).

Parametry

offset

Result set offset.

limit

Amount of matches to return.

max_matches

Controls how much matches searchd will keep in RAM while searching.

cutoff

Used for advanced performance control. It tells searchd to forcibly stop search query once cutoff matches have been found and processed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SphinxClient::setIndexWeights
SphinxClient::setMatchMode
SphinxClient


Set full-text query matching mode

SphinxClient::setLimits
SphinxClient::setMaxQueryTime
SphinxClient
PHP Manual

SphinxClient::setMatchMode

(PECL sphinx >= 0.1.0)

SphinxClient::setMatchMode — Set full-text query matching mode

Opis

public bool SphinxClient::setMatchMode ( int $mode )

Sets full-text query matching mode. mode is one of the constants listed below.

Match modes
Constant | Description
SPH_MATCH_ALL | Match all query words (default mode).
SPH_MATCH_ANY | Match any of query words.
SPH_MATCH_PHRASE | Match query as a phrase, requiring perfect match.
SPH_MATCH_BOOLEAN | Match query as a boolean expression.
SPH_MATCH_EXTENDED | Match query as an expression in Sphinx internal query language.
SPH_MATCH_FULLSCAN | Enables fullscan.
SPH_MATCH_EXTENDED2 | The same as SPH_MATCH_EXTENDED plus ranking and quorum searching support.

Parametry

mode

Matching mode.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setRankingMode
  • SphinxClient::setSortMode

SphinxClient::setLimits
SphinxClient::setMaxQueryTime
SphinxClient


Set maximum query time

SphinxClient::setMatchMode
SphinxClient::setOverride
SphinxClient
PHP Manual

SphinxClient::setMaxQueryTime

(PECL sphinx >= 0.1.0)

SphinxClient::setMaxQueryTime — Set maximum query time

Opis

public bool SphinxClient::setMaxQueryTime ( int $qtime )

Sets maximum search query time.

Parametry

qtime

Maximum query time, in milliseconds. It must be a non-negative integer. Default value is 0, i.e. no limit.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SphinxClient::setMatchMode
SphinxClient::setOverride
SphinxClient


Sets temporary per-document attribute value overrides

SphinxClient::setMaxQueryTime
SphinxClient::setRankingMode
SphinxClient
PHP Manual

SphinxClient::setOverride

(PECL sphinx >= 1.0.3)

SphinxClient::setOverride — Sets temporary per-document attribute value overrides

Opis

public bool SphinxClient::setOverride ( string $attribute , int $type , array $values )

Sets temporary (per-query) per-document attribute value overrides. Override feature lets you "temporary" update attribute values for some documents within a single query, leaving all other queries unaffected. This might be useful for personalized data

Parametry

attribute

An attribute name.

type

An attribute type. Only supports scalar attributes.

values

Array of attribute values that maps document IDs to overridden attribute values.

Rejestr zmian

PECL/sphinx Wersja | Opis
1.0.3 | Added SphinxClient::setOverride(), available only if compiled with libsphinxclient >= 0.9.9.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SphinxClient::setMaxQueryTime
SphinxClient::setRankingMode
SphinxClient


Set ranking mode

SphinxClient::setOverride
SphinxClient::setRetries
SphinxClient
PHP Manual

SphinxClient::setRankingMode

(PECL sphinx >= 0.1.0)

SphinxClient::setRankingMode — Set ranking mode

Opis

public bool SphinxClient::setRankingMode ( int $ranker )

Sets ranking mode. Only available in SPH_MATCH_EXTENDED2 matching mode.

Ranking modes
Constant | Description
SPH_RANK_PROXIMITY_BM25 | Default ranking mode which uses both proximity and BM25 ranking.
SPH_RANK_BM25 | Statistical ranking mode which uses BM25 ranking only (similar to most of other full-text engines). This mode is faster, but may result in worse quality on queries which contain more than 1 keyword.
SPH_RANK_NONE | Disables ranking. This mode is the fastest. It is essentially equivalent to boolean searching, a weight of 1 is assigned to all matches.

Parametry

ranker

Ranking mode.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setMatchMode

SphinxClient::setOverride
SphinxClient::setRetries
SphinxClient


Set retry count and delay

SphinxClient::setRankingMode
SphinxClient::setSelect
SphinxClient
PHP Manual

SphinxClient::setRetries

(PECL sphinx >= 0.1.0)

SphinxClient::setRetries — Set retry count and delay

Opis

public bool SphinxClient::setRetries ( int $count [, int $delay = 0 ] )

Sets distributed retry count and delay.

On temporary failures searchd will attempt up to count retries per agent. delay is the delay between the retries, in milliseconds. Retries are disabled by default. Note that this call will not make the API itself retry on temporary failure; it only tells searchd to do so.

Parametry

count

Number of retries.

delay

Delay between retries, in milliseconds.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SphinxClient::setRankingMode
SphinxClient::setSelect
SphinxClient


Set select clause

SphinxClient::setRetries
SphinxClient::setServer
SphinxClient
PHP Manual

SphinxClient::setSelect

(PECL sphinx >= 1.0.1)

SphinxClient::setSelect — Set select clause

Opis

public bool SphinxClient::setSelect ( string $clause )

Sets the select clause, listing specific attributes to fetch, and expressions to compute and fetch.

Parametry

clause

SQL-like clause.

Rejestr zmian

PECL/sphinx Wersja | Opis
1.0.1 | Added SphinxClient::setSelect(), available only if compiled with libsphinxclient >= 0.9.9.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SphinxClient::setRetries
SphinxClient::setServer
SphinxClient


Set searchd host and port

SphinxClient::setSelect
SphinxClient::setSortMode
SphinxClient
PHP Manual

SphinxClient::setServer

(PECL sphinx >= 0.1.0)

SphinxClient::setServer — Set searchd host and port

Opis

public bool SphinxClient::setServer ( string $server , int $port )

Sets searchd host name and TCP port. All subsequent requests will use the new host and port settings. Default host and port are 'localhost' and 3312, respectively.

Parametry

server

IP or hostname.

port

Port number.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

SphinxClient::setSelect
SphinxClient::setSortMode
SphinxClient


Set matches sorting mode

SphinxClient::setServer
SphinxClient::status
SphinxClient
PHP Manual

SphinxClient::setSortMode

(PECL sphinx >= 0.1.0)

SphinxClient::setSortMode — Set matches sorting mode

Opis

public bool SphinxClient::setSortMode ( int $mode [, string $sortby ] )

Sets matches sorting mode. See available modes below.

Sorting modes
Constant | Description
SPH_SORT_RELEVANCE | Sort by relevance in descending order (best matches first).
SPH_SORT_ATTR_DESC | Sort by an attribute in descending order (bigger attribute values first).
SPH_SORT_ATTR_ASC | Sort by an attribute in ascending order (smaller attribute values first).
SPH_SORT_TIME_SEGMENTS | Sort by time segments (last hour/day/week/month) in descending order, and then by relevance in descending order.
SPH_SORT_EXTENDED | Sort by SQL-like combination of columns in ASC/DESC order.
SPH_SORT_EXPR | Sort by an arithmetic expression.

Parametry

mode

Sorting mode.

sortby

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • SphinxClient::setMatchMode
  • SphinxClient::setSortMode

SphinxClient::setServer
SphinxClient::status
SphinxClient


Queries searchd status

SphinxClient::setSortMode
SphinxClient::updateAttributes
SphinxClient
PHP Manual

SphinxClient::status

(PECL sphinx >= 1.0.3)

SphinxClient::status — Queries searchd status

Opis

public array SphinxClient::status ( void )

Queries searchd status, and returns an array of status variable name and value pairs.

Parametry

Ta funkcja nie posiada parametrów.

Rejestr zmian

PECL/sphinx Wersja | Opis
1.0.3 | Added SphinxClient::status(), available only if compiled with libsphinxclient >= 0.9.9.

Zwracane wartości

Returns an associative array of search server statistics lub FALSE w przypadku niepowodzenia.

SphinxClient::setSortMode
SphinxClient::updateAttributes
SphinxClient


Update document attributes

SphinxClient::status
Swish
SphinxClient
PHP Manual

SphinxClient::updateAttributes

(PECL sphinx >= 0.1.0)

SphinxClient::updateAttributes — Update document attributes

Opis

public int SphinxClient::updateAttributes ( string $index , array $attributes , array $values [, bool $mva = false ] )

Instantly updates given attribute values in given documents.

Parametry

index

Name of the index (or indexes) to be updated.

attributes

Array of attribute names, listing attributes that are updated.

values

Associative array containing document IDs as keys and array of attribute values as values.

Zwracane wartości

Returns number of actually updated documents (0 or more) on success, or FALSE on failure.

SphinxClient::status
Swish
SphinxClient


Swish Indexing

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
  • Swish Funkcje
    • Swish::__construct — Construct a Swish object
    • Swish::getMetaList — Get the list of meta entries for the index
    • Swish::getPropertyList — Get the list of properties for the index
    • Swish::prepare — Prepare a search query
    • Swish::query — Execute a query and return results object
    • SwishResult::getMetaList — Get a list of meta entries
    • SwishResult::stem — Stems the given word
    • SwishResults::getParsedWords — Get an array of parsed words
    • SwishResults::getRemovedStopwords — Get an array of stopwords removed from the query
    • SwishResults::nextResult — Get the next search result
    • SwishResults::seekResult — Set current seek pointer to the given position
    • SwishSearch::execute — Execute the search and get the results
    • SwishSearch::resetLimit — Reset the search limits
    • SwishSearch::setLimit — Set the search limits
    • SwishSearch::setPhraseDelimiter — Set the phrase delimiter
    • SwishSearch::setSort — Set the sort order
    • SwishSearch::setStructure — Set the structure flag in the search object
SphinxClient::updateAttributes
Wstęp
Systemy wyszukiwania informacji


Wstęp

The swish extension provides the bindings for Swish-e API. Swish-e stands for "Simple Web Indexing System for Humans - Enhanced" and is an open source system for indexing and search. Swish-e itself is licensed under GPL license, but uses a clause that allows applications to link against the library if every copy of the combined work is accompanied by the URL to Swish-e source code. Here it is: » http://swish-e.org.

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.

Swish
Instalacja/Konfiguracja
Swish


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Swish


Wymagania

PECL/swish requires PHP 5.1.3 or newer.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/swish.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Swish::META_TYPE_UNDEF (integer)
Swish::META_TYPE_STRING (integer)
Swish::META_TYPE_ULONG (integer)
Swish::META_TYPE_DATE (integer)
Swish::IN_FILE_BIT (integer)
Swish::IN_TITLE_BIT (integer)
Swish::IN_HEAD_BIT (integer)
Swish::IN_BODY_BIT (integer)
Swish::IN_COMMENTS_BIT (integer)
Swish::IN_HEADER_BIT (integer)
Swish::IN_EMPHASIZED_BIT (integer)
Swish::IN_META_BIT (integer)
Swish::IN_FILE (integer)
Swish::IN_TITLE (integer)
Swish::IN_HEAD (integer)
Swish::IN_BODY (integer)
Swish::IN_COMMENTS (integer)
Swish::IN_HEADER (integer)
Swish::IN_EMPHASIZED (integer)
Swish::IN_META (integer)
Swish::IN_ALL (integer)
Typy zasobów
Przykłady
Swish


Przykłady

Spis treści

  • Basic usage
Stałe predefiniowane
Basic usage
Swish


Basic usage

Przykład #1 Basic search query

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("test OR text");

    echo "Found ", $results->hits, " results\n";
    while ($result = $results->nextResult()) {
        var_dump($result);
        break; //break after the first result
    }

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

Found 9 results
object(SwishResult)#3 (8) {
  ["swishreccount"]=>
  int(1)
  ["swishrank"]=>
  int(1000)
  ["swishfilenum"]=>
  int(10)
  ["swishdbfile"]=>
  string(13) "index.swish-e"
  ["swishdocpath"]=>
  string(23) "README.SUBMITTING_PATCH"
  ["swishtitle"]=>
  NULL
  ["swishdocsize"]=>
  int(4557)
  ["swishlastmodified"]=>
  int(1072136752)
}
Przykłady
Swish Funkcje
Przykłady


Swish Funkcje

Spis treści

  • Swish::__construct — Construct a Swish object
  • Swish::getMetaList — Get the list of meta entries for the index
  • Swish::getPropertyList — Get the list of properties for the index
  • Swish::prepare — Prepare a search query
  • Swish::query — Execute a query and return results object
  • SwishResult::getMetaList — Get a list of meta entries
  • SwishResult::stem — Stems the given word
  • SwishResults::getParsedWords — Get an array of parsed words
  • SwishResults::getRemovedStopwords — Get an array of stopwords removed from the query
  • SwishResults::nextResult — Get the next search result
  • SwishResults::seekResult — Set current seek pointer to the given position
  • SwishSearch::execute — Execute the search and get the results
  • SwishSearch::resetLimit — Reset the search limits
  • SwishSearch::setLimit — Set the search limits
  • SwishSearch::setPhraseDelimiter — Set the phrase delimiter
  • SwishSearch::setSort — Set the sort order
  • SwishSearch::setStructure — Set the structure flag in the search object
Basic usage
Swish::__construct
Swish


Construct a Swish object

Swish Funkcje
Swish::getMetaList
Swish Funkcje
PHP Manual

Swish::__construct

(PECL swish >= 0.1.0)

Swish::__construct — Construct a Swish object

Opis

void Swish::__construct ( string $index_names )
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

index_names

The list of index files separated by spaces.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws SwishException on error.

Przykłady

Przykład #1 A Swish::__construct() example

<?php

try {
    $swish = new Swish("index1 index2");
} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

foreach ($swish->indexes as $index) {
    var_dump($index["name"]);
    var_dump($index["headers"]["Total Words"]);
}

?>

Powyższy przykład wyświetli coś podobnego do:

string(6) "index1"
int(1888)
string(6) "index2"
int(2429)

Swish Funkcje
Swish::getMetaList
Swish Funkcje


Get the list of meta entries for the index

Swish::__construct
Swish::getPropertyList
Swish Funkcje
PHP Manual

Swish::getMetaList

(PECL swish >= 0.1.0)

Swish::getMetaList — Get the list of meta entries for the index

Opis

array Swish::getMetaList ( string $index_name )
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

index_name

The name of the index file.

Zwracane wartości

Returns an array of meta entries for the given index.

Przykłady

Przykład #1 Basic Swish::getMetaList() example

<?php

try {

    $swish = new Swish("index.swish-e");
    var_dump($swish->getMetaList("index.swish-e"));

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

array(1) {
  [0]=>
  array(3) {
    ["Name"]=>
    string(12) "swishdefault"
    ["Type"]=>
    int(0)
    ["ID"]=>
    int(1)
  }
}

Swish::__construct
Swish::getPropertyList
Swish Funkcje


Get the list of properties for the index

Swish::getMetaList
Swish::prepare
Swish Funkcje
PHP Manual

Swish::getPropertyList

(PECL swish >= 0.1.0)

Swish::getPropertyList — Get the list of properties for the index

Opis

array Swish::getPropertyList ( string $index_name )
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

index_name

The name of the index file.

Zwracane wartości

Returns an array of properties for the given index.

Przykłady

Przykład #1 Basic Swish::getPropertyList() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $properties = $swish->getPropertyList("index.swish-e");
    foreach ($properties as $prop) {
        echo $prop["Name"],"\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

swishreccount
swishrank
swishfilenum
swishdbfile
swishdocpath
swishtitle
swishdocsize
swishlastmodified

Swish::getMetaList
Swish::prepare
Swish Funkcje


Prepare a search query

Swish::getPropertyList
Swish::query
Swish Funkcje
PHP Manual

Swish::prepare

(PECL swish >= 0.1.0)

Swish::prepare — Prepare a search query

Opis

object Swish::prepare ([ string $query ] )
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.

Prepare and return a search object, which you can later use for unlimited number of queries.

Parametry

query

Optional query string. The query can be also set using SwishSearch::execute() method.

Zwracane wartości

Returns SwishSearch object.

Błędy/Wyjątki

Throws SwishException on error.

Przykłady

Przykład #1 Basic Swish::prepare() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare("search query");
    $results = $search->execute();
    echo "Found: ", $results->hits, " hits\n";

    $results = $search->execute("new search");

    echo "Found: ", $results->hits, " hits\n";
} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

Found: 2 hits
Found: 5 hits

Swish::getPropertyList
Swish::query
Swish Funkcje


Execute a query and return results object

Swish::prepare
SwishResult::getMetaList
Swish Funkcje
PHP Manual

Swish::query

(PECL swish >= 0.1.0)

Swish::query — Execute a query and return results object

Opis

object Swish::query ( string $query )
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.

A quick method to execute a search with default parameters.

Parametry

query

Query string.

Zwracane wartości

Returns SwishResults object.

Błędy/Wyjątki

Throws SwishException on error.

Przykłady

Przykład #1 Basic Swish::query() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("test query");

    echo "Found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

Found: 1 hits

Swish::prepare
SwishResult::getMetaList
Swish Funkcje


Get a list of meta entries

Swish::query
SwishResult::stem
Swish Funkcje
PHP Manual

SwishResult::getMetaList

(PECL swish >= 0.1.0)

SwishResult::getMetaList — Get a list of meta entries

Opis

array SwishResult::getMetaList ( 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.

Zwracane wartości

Returns the same array as swish::getmetalist(), but uses the index file from the result handle.

Swish::query
SwishResult::stem
Swish Funkcje


Stems the given word

SwishResult::getMetaList
SwishResults::getParsedWords
Swish Funkcje
PHP Manual

SwishResult::stem

(PECL swish >= 0.1.0)

SwishResult::stem — Stems the given word

Opis

array SwishResult::stem ( string $word )
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.

Stems the word based on the fuzzy mode used during indexing. Each result object is linked with its index, so the results are based on this index.

Parametry

word

The word to stem.

Zwracane wartości

Returns array containing the stemmed word variants (usually just one).

Błędy/Wyjątki

Throws SwishException on error.

Przykłady

Przykład #1 Basic SwishResult::stem() example

<?php

try {

    $swish = new Swish("ext/swish/tests/index.swish-e");
    $results = $swish->query("testing OR others");

    if ($result = $results->nextResult()) {
        var_dump($result->stem("testing")); //the results fully depend on the stemmer used in the index
        var_dump($result->stem("others"));
    }

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

array(1) {
  [0]=>
  string(4) "test"
}
array(1) {
  [0]=>
  string(5) "other"
}

SwishResult::getMetaList
SwishResults::getParsedWords
Swish Funkcje


Get an array of parsed words

SwishResult::stem
SwishResults::getRemovedStopwords
Swish Funkcje
PHP Manual

SwishResults::getParsedWords

(PECL swish >= 0.1.0)

SwishResults::getParsedWords — Get an array of parsed words

Opis

array SwishResults::getParsedWords ( string $index_name )
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

indexi_name

The name of the index used to initialize Swish object.

Zwracane wartości

An array of parsed words with stopwords removed. The list of parsed words may be useful for highlighting search terms in the results.

Przykłady

Przykład #1 Basic SwishResults::getParsedWords() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("'some characters' and numbers");

    var_dump($results->getParsedWords("index.swish-e"));
    var_dump($results->indexes[0]['parsed_words']); //same result in a different way

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

array(4) {
  [0]=>
  string(4) "some"
  [1]=>
  string(10) "characters"
  [2]=>
  string(3) "and"
  [3]=>
  string(7) "numbers"
}
array(4) {
  [0]=>
  string(4) "some"
  [1]=>
  string(10) "characters"
  [2]=>
  string(3) "and"
  [3]=>
  string(7) "numbers"
}

SwishResult::stem
SwishResults::getRemovedStopwords
Swish Funkcje


Get an array of stopwords removed from the query

SwishResults::getParsedWords
SwishResults::nextResult
Swish Funkcje
PHP Manual

SwishResults::getRemovedStopwords

(PECL swish >= 0.1.0)

SwishResults::getRemovedStopwords — Get an array of stopwords removed from the query

Opis

array SwishResults::getRemovedStopwords ( string $index_name )
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

index_name

The name of the index used to initialize Swish object.

Zwracane wartości

Returns array of stopwords removed from the query.

SwishResults::getParsedWords
SwishResults::nextResult
Swish Funkcje


Get the next search result

SwishResults::getRemovedStopwords
SwishResults::seekResult
Swish Funkcje
PHP Manual

SwishResults::nextResult

(PECL swish >= 0.1.0)

SwishResults::nextResult — Get the next search result

Opis

object SwishResults::nextResult ( 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.

Zwracane wartości

Returns the next SwishResult object in the result set or FALSE if there are no more results available.

Przykłady

Przykład #1 Basic SwishResults::nextResult() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("lost");
    while($result = $results->nextResult()) {
        /* do something with the result object */
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

SwishResults::getRemovedStopwords
SwishResults::seekResult
Swish Funkcje


Set current seek pointer to the given position

SwishResults::nextResult
SwishSearch::execute
Swish Funkcje
PHP Manual

SwishResults::seekResult

(PECL swish >= 0.1.0)

SwishResults::seekResult — Set current seek pointer to the given position

Opis

int SwishResults::seekResult ( int $position )
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

position

Zero-based position number. Cannot be less than zero.

Zwracane wartości

Returns new position value on success.

Błędy/Wyjątki

Throws SwishException on error.

Przykłady

Przykład #1 Basic SwishResults::seekResult() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("lost");

    var_dump($results->seekResult(0)); //this will succeed
    var_dump($results->seekResult(100)); //this will fail

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

int(0)
Error: No more results

SwishResults::nextResult
SwishSearch::execute
Swish Funkcje


Execute the search and get the results

SwishResults::seekResult
SwishSearch::resetLimit
Swish Funkcje
PHP Manual

SwishSearch::execute

(PECL swish >= 0.1.0)

SwishSearch::execute — Execute the search and get the results

Opis

object SwishSearch::execute ([ string $query ] )
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.

Searches the index file(s) based on the parameters set in the search object.

Parametry

query

The query string is an optional parameter, it can be also set using Swish::prepare() method. The query string is preserved between executions, so you can set it once, but execute the search multiple times.

Zwracane wartości

Returns SwishResults object.

Błędy/Wyjątki

Throws SwishException on error.

Przykłady

Przykład #1 Basic SwishSearch::execute() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("query");
    echo "First query found: ", $results->hits, " hits\n";

    $results = $search->execute("new OR query");
    echo "Second query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

First query found: 2 hits
Second query found: 12 hits

SwishResults::seekResult
SwishSearch::resetLimit
Swish Funkcje


Reset the search limits

SwishSearch::execute
SwishSearch::setLimit
Swish Funkcje
PHP Manual

SwishSearch::resetLimit

(PECL swish >= 0.1.0)

SwishSearch::resetLimit — Reset the search limits

Opis

void SwishSearch::resetLimit ( 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.

Reset the search limits previous set by SwishSearch::setLimit.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Basic SwishSearch::resetLimit() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $search->setLimit("swishdocsize", "3000", "6000"); //limit by document size, from 3000 to 6000 bytes
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $search->resetLimit();
    $results = $search->execute("time");
    echo "Third query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

First query found: 5 hits
Second query found: 2 hits
Third query found: 5 hits

SwishSearch::execute
SwishSearch::setLimit
Swish Funkcje


Set the search limits

SwishSearch::resetLimit
SwishSearch::setPhraseDelimiter
Swish Funkcje
PHP Manual

SwishSearch::setLimit

(PECL swish >= 0.1.0)

SwishSearch::setLimit — Set the search limits

Opis

void SwishSearch::setLimit ( string $property , string $low , string $high )
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

property

Search result property name.

low

The lowest value of the property.

high

The highest value of the property.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws SwishException on error.

Przykłady

Przykład #1 Basic SwishSearch::setLimit() example

<?php
try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

    $search->setLimit("swishdocsize", "3000", "6000"); //limit by document size, from 3000 to 6000 bytes
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

First query found: 5 hits
Hit #1 - 4261 bytes
Hit #2 - 37937 bytes
Hit #3 - 7126 bytes
Hit #4 - 15427 bytes
Hit #5 - 4768 bytes
Second query found: 2 hits
Hit #1 - 4261 bytes
Hit #2 - 4768 bytes

SwishSearch::resetLimit
SwishSearch::setPhraseDelimiter
Swish Funkcje


Set the phrase delimiter

SwishSearch::setLimit
SwishSearch::setSort
Swish Funkcje
PHP Manual

SwishSearch::setPhraseDelimiter

(PECL swish >= 0.1.0)

SwishSearch::setPhraseDelimiter — Set the phrase delimiter

Opis

void SwishSearch::setPhraseDelimiter ( string $delimiter )
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

delimiter

Phrase delimiter character. The default delimiter is double-quotes.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Basic SwishSearch::setPhraseDelimiter() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute('"every time"'); //looking for "every time"
    echo "First query found: ", $results->hits, " hits\n";

    $search->setPhraseDelimiter("'");
    $results = $search->execute("'every time'"); //the same query, but using different delimiter
    echo "Second query found: ", $results->hits, " hits\n";

    $search->setPhraseDelimiter('"');
    $results = $search->execute("'every time'"); //looking for "every" and "time"
    echo "Third query found: ", $results->hits, " hits\n";

    //let's look at parsed words
    var_dump($results->getParsedWords("index.swish-e"));

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

First query found: 1 hits
Second query found: 1 hits
Third query found: 2 hits
array(2) {
  [0]=>
  string(5) "every"
  [1]=>
  string(4) "time"
}

SwishSearch::setLimit
SwishSearch::setSort
Swish Funkcje


Set the sort order

SwishSearch::setPhraseDelimiter
SwishSearch::setStructure
Swish Funkcje
PHP Manual

SwishSearch::setSort

(PECL swish >= 0.1.0)

SwishSearch::setSort — Set the sort order

Opis

void SwishSearch::setSort ( string $sort )
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

sort

Sort order of the results is a string containing name of a result property combined with sort direction ("asc" or "desc"). Examples: "swishrank desc", "swishdocpath asc", "swishtitle asc", "swishdocsize desc", "swishlastmodified desc" etc.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Basic SwishSearch::setSort() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

    $search->setSort("swishdocsize desc"); //sort by document size
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

First query found: 5 hits
Hit #1 - 4261 bytes
Hit #2 - 37937 bytes
Hit #3 - 7126 bytes
Hit #4 - 15427 bytes
Hit #5 - 4768 bytes
Second query found: 5 hits
Hit #1 - 37937 bytes
Hit #2 - 15427 bytes
Hit #3 - 7126 bytes
Hit #4 - 4768 bytes
Hit #5 - 4261 bytes

SwishSearch::setPhraseDelimiter
SwishSearch::setStructure
Swish Funkcje


Set the structure flag in the search object

SwishSearch::setSort
Rozszerzenia przeznaczone dla serwera
Swish Funkcje
PHP Manual

SwishSearch::setStructure

(PECL swish >= 0.1.0)

SwishSearch::setStructure — Set the structure flag in the search object

Opis

void SwishSearch::setStructure ( int $structure )
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

structure

The structure flag a bitmask is used to limit search to certain parts of HTML documents (like title, meta, body etc.). Its possible values are listed below. To combine several values use bitwise OR operator, see example below.

  • Swish::IN_FILE

  • Swish::IN_TITLE

  • Swish::IN_HEAD

  • Swish::IN_BODY

  • Swish::IN_COMMENTS

  • Swish::IN_HEADER

  • Swish::IN_EMPHASIZED

  • Swish::IN_META

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Basic SwishSearch::setStructure() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $search->setStructure(Swish::IN_TITLE|Swish::IN_HEAD); //search in title and head
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $search->setStructure(Swish::IN_ALL); //search in whole document, the default value
    $results = $search->execute("time");
    echo "Third query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

First query found: 5 hits
Second query found: 0 hits
Third query found: 5 hits

SwishSearch::setSort
Rozszerzenia przeznaczone dla serwera
Swish Funkcje


Rozszerzenia przeznaczone dla serwera

  • Apache
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje Apache
  • IIS — IIS Administration
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • IIS Funkcje
  • NSAPI
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • NSAPI Funkcje
SwishSearch::setStructure
Apache
Opis funkcji


Apache

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje Apache
    • apache_child_terminate — Zakańcza proces Apache'a po zakończeniu tego zapytania
    • apache_get_modules — Get a list of loaded Apache modules
    • apache_get_version — Fetch Apache version
    • apache_getenv — Get an Apache subprocess_env variable
    • apache_lookup_uri — Wywołuje wewnętrzne żądanie dla określonego URI i zwraca całą informację o nim
    • apache_note — Pobiera lub ustawia noty odpowiedzi Apache'a
    • apache_request_headers — Fetch all HTTP request headers
    • apache_reset_timeout — Reset the Apache write timer
    • apache_response_headers — Pobiera wszystkie nagłówki HTTP odpowiedzi serwera
    • apache_setenv — Ustawia zmienną Apache'a subprocess_env
    • getallheaders — Odczytuje wszystkie nagłówki HTTP z aktualnego zapytania
    • virtual — Wykonuje zapytanie do Apache'a
Rozszerzenia przeznaczone dla serwera
Wstęp
Rozszerzenia przeznaczone dla serwera


Wstęp

These functions are only available when running PHP as an Apache module.

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.

Apache
Instalacja/Konfiguracja
Apache


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Apache


Instalacja

For PHP installation on Apache see the installation chapter.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

The behaviour of the Apache PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by php_flag settings in the server configuration file or local .htaccess files.

Przykład #1 Turning off PHP parsing for a directory using .htaccess

php_flag engine off

Apache configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
engine | "1" | PHP_INI_ALL | Available since PHP 4.0.5.
child_terminate | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
last_modified | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
xbithack | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
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.

engine boolean

Turns PHP parsing on or off. This directive is really only useful in the Apache module version of PHP. It is used by sites that would like to turn PHP parsing on and off on a per-directory or per-virtual server basis. By putting engine off in the appropriate places in the httpd.conf file, PHP can be enabled or disabled.

child_terminate boolean

Specify whether PHP scripts may request child process termination on end of request, see also apache_child_terminate().

last_modified boolean

Send PHP scripts modification date as Last-Modified: header for this request.

xbithack boolean

Parse files with executable bit set as PHP regardless of their file ending.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Funkcje Apache
Apache


Funkcje Apache

Spis treści

  • apache_child_terminate — Zakańcza proces Apache'a po zakończeniu tego zapytania
  • apache_get_modules — Get a list of loaded Apache modules
  • apache_get_version — Fetch Apache version
  • apache_getenv — Get an Apache subprocess_env variable
  • apache_lookup_uri — Wywołuje wewnętrzne żądanie dla określonego URI i zwraca całą informację o nim
  • apache_note — Pobiera lub ustawia noty odpowiedzi Apache'a
  • apache_request_headers — Fetch all HTTP request headers
  • apache_reset_timeout — Reset the Apache write timer
  • apache_response_headers — Pobiera wszystkie nagłówki HTTP odpowiedzi serwera
  • apache_setenv — Ustawia zmienną Apache'a subprocess_env
  • getallheaders — Odczytuje wszystkie nagłówki HTTP z aktualnego zapytania
  • virtual — Wykonuje zapytanie do Apache'a
Stałe predefiniowane
apache_child_terminate
Apache


Zakańcza proces Apache'a po zakończeniu tego zapytania

Funkcje Apache
apache_get_modules
Funkcje Apache
PHP Manual

apache_child_terminate

(PHP 4 >= 4.0.5, PHP 5)

apache_child_terminate — Zakańcza proces Apache'a po zakończeniu tego zapytania

Opis

bool apache_child_terminate ( void )

apache_child_terminate() zarejestruje proces Apache'a, wykonujący aktualne zapytanie, do zakończenia, jak tylko zakończy się wykonywanie kodu PHP. Można tego używać do zakończenia procesu po uruchomieniu skryptu o dużych zapotrzebowaniach na pamięć, gdyż zwykle pamięć zostaje zwolniona wewnętrznie, ale nie zwrócona systemowi operacyjnemu.

Informacja: Dostępność tego mechanizmu jest kontrolowana przez dyrektywę child_terminate , zawartą w php.ini, która domyślnie ustawiona jest na off. Funkcja ta jest tylko dostępna w nie wielowątkowych wersjach Apache 1, z PHP działającym jako moduł Apache'a.

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Patrz także: exit().

Funkcje Apache
apache_get_modules
Funkcje Apache


Get a list of loaded Apache modules

apache_child_terminate
apache_get_version
Funkcje Apache
PHP Manual

apache_get_modules

(PHP 4 >= 4.3.2, PHP 5)

apache_get_modules — Get a list of loaded Apache modules

Opis

array apache_get_modules ( void )

Get a list of loaded Apache modules.

Zwracane wartości

An array of loaded Apache modules.

Rejestr zmian

Wersja | Opis
5.0.0 | Became available when using Apache 1, or the PHP Apache 2 filter API. Before this time, it was only available when using the Apache 2 handler API.

Przykłady

Przykład #1 apache_get_modules() example

<?php
print_r(apache_get_modules());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)

apache_child_terminate
apache_get_version
Funkcje Apache


Fetch Apache version

apache_get_modules
apache_getenv
Funkcje Apache
PHP Manual

apache_get_version

(PHP 4 >= 4.3.2, PHP 5)

apache_get_version — Fetch Apache version

Opis

string apache_get_version ( void )

Fetch the Apache version.

Zwracane wartości

Returns the Apache version on success lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja | Opis
4.3.4 | Became available with Apache 1.
5.0.0 | Became available with the Apache 2 filter API.

Przykłady

Przykład #1 apache_get_version() example

<?php
$version = apache_get_version();
echo "$version\n";
?>

Powyższy przykład wyświetli coś podobnego do:

Apache/1.3.29 (Unix) PHP/4.3.4

Zobacz też:

  • phpinfo() - Outputs information about PHP's configuration

apache_get_modules
apache_getenv
Funkcje Apache


Get an Apache subprocess_env variable

apache_get_version
apache_lookup_uri
Funkcje Apache
PHP Manual

apache_getenv

(PHP 4 >= 4.3.0, PHP 5)

apache_getenv — Get an Apache subprocess_env variable

Opis

string apache_getenv ( string $variable [, bool $walk_to_top ] )

Get an Apache environment variable as specified by variable.

This function requires Apache 2 otherwise it's undefined.

Parametry

variable

The Apache environment variable

walk_to_top

Whether to get the top-level variable available to all Apache layers.

Zwracane wartości

The value of the Apache environment variable on success, or FALSE on failure

Przykłady

Przykład #1 apache_getenv() example

The example above shows how to retrieve the value of the Apache environment variable SERVER_ADDR.

<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>

Powyższy przykład wyświetli coś podobnego do:

42.24.42.240

Zobacz też:

  • apache_setenv() - Ustawia zmienną Apache'a subprocess_env
  • getenv() - Gets the value of an environment variable
  • Superglobals

apache_get_version
apache_lookup_uri
Funkcje Apache


Wywołuje wewnętrzne żądanie dla określonego URI i zwraca całą informację o nim

apache_getenv
apache_note
Funkcje Apache
PHP Manual

apache_lookup_uri

(PHP 4, PHP 5)

apache_lookup_uri — Wywołuje wewnętrzne żądanie dla określonego URI i zwraca całą informację o nim

Opis

object apache_lookup_uri ( string $nazwa_pliku )

Ta funkcja wywołuje wewnętrzne żądanie dla określonego URI. Funkcja zbiera wszystkie istotne informacje odnośnie podanego zasobu.

Funkcja ta jest dostępna tylko jeśli PHP jest zaistalowane jako moduł serwera Apache.

Parametry

nazwa_pliku

Nazwa rządanego pliku (URI).

Zwracane wartości

Obiekt powiązany z informacjami URI. Własności tego obiektu to:

  • status
  • the_request
  • status_line
  • method
  • content_type
  • handler
  • uri
  • filename
  • path_info
  • args
  • boundary
  • no_cache
  • no_local_copy
  • allowed
  • send_bodyct
  • bytes_sent
  • byterange
  • clength
  • unparsed_uri
  • mtime
  • request_time

Przykłady

Przykład #1 apache_lookup_uri() przykład

<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
  echo 'plik istnieje!';
}
?>

Powyższy przykład wyświetli coś podobnego do:

stdClass Object
(
      [status] => 200
      [the_request] => GET /katalog/plik.php HTTP/1.1
      [method] => GET
      [mtime] => 0
      [clength] => 0
      [chunked] => 0
      [content_type] => application/x-httpd-php
      [no_cache] => 0
      [no_local_copy] => 1
      [unparsed_uri] => /katalog/index.php?var=value
      [uri] => /katalog/index.php
      [filename] => /home/htdocs/katalog/index.php
      [args] => var=value
      [allowed] => 0
      [sent_bodyct] => 0
      [bytes_sent] => 0
      [request_time] => 1074282764
)
file exists!

apache_getenv
apache_note
Funkcje Apache


Pobiera lub ustawia noty odpowiedzi Apache'a

apache_lookup_uri
apache_request_headers
Funkcje Apache
PHP Manual

apache_note

(PHP 4, PHP 5)

apache_note — Pobiera lub ustawia noty odpowiedzi Apache'a

Opis

string apache_note ( string $nazwa_noty [, string $wartość_noty ] )

apache_note() jest funkcją dotyczącą jedynie serwera Apache, która pobiera lub ustawia wartości not w odpowiedzi http. Jeśli wywołana z jednym argumentem, funkcja zwraca aktualną wartość noty nazwa_noty. Jeśli wywołana z dwoma argumentami, ustawi wartość noty nazwa_noty na wartość_noty i zwróci poprzednią wartość noty nazwa_noty.

apache_lookup_uri
apache_request_headers
Funkcje Apache


Fetch all HTTP request headers

apache_note
apache_reset_timeout
Funkcje Apache
PHP Manual

apache_request_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_request_headers — Fetch all HTTP request headers

Opis

array apache_request_headers ( void )

Fetches all HTTP request headers from the current request.

Zwracane wartości

An associative array of all the HTTP headers in the current request, or FALSE on failure.

Rejestr zmian

Wersja | Opis
5.4.0 | This function became available under FastCGI. Previously, it was supported only when PHP was installed as an Apache module.
4.3.3

Informacja:

Od PHP 4.3.3 możliwe jest użycie tej funkcji przy pracy w trybie modułu NSAPI serwera także w serwerach Netscape/iPlanet/SunONE.

Przykłady

Przykład #1 apache_request_headers() example

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

Notatki

Informacja:

You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the available environment variables.

Zobacz też:

  • apache_response_headers() - Pobiera wszystkie nagłówki HTTP odpowiedzi serwera

apache_note
apache_reset_timeout
Funkcje Apache


Reset the Apache write timer

apache_request_headers
apache_response_headers
Funkcje Apache
PHP Manual

apache_reset_timeout

(PHP 5 >= 5.1.0)

apache_reset_timeout — Reset the Apache write timer

Opis

bool apache_reset_timeout ( void )

apache_reset_timeout() resets the Apache write timer, which defaults to 300 seconds. With set_time_limit(0); ignore_user_abort(true) and periodic apache_reset_timeout() calls, Apache can theoretically run forever.

This function requires Apache 1.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja: Ta funkcja jest niedostępna jeśli PHP działa w trybie bezpiecznym

Zobacz też:

  • set_time_limit() - Limits the maximum execution time
  • ignore_user_abort() - Set whether a client disconnect should abort script execution

apache_request_headers
apache_response_headers
Funkcje Apache


Pobiera wszystkie nagłówki HTTP odpowiedzi serwera

apache_reset_timeout
apache_setenv
Funkcje Apache
PHP Manual

apache_response_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_response_headers — Pobiera wszystkie nagłówki HTTP odpowiedzi serwera

Opis

array apache_response_headers ( void )

Pobiera wszystkie nagłówki HTTP odpowiedzi serwera

Zwracane wartości

Tablica wszystkich nagłówków odpowiedzi serwera Apache w przypadku powodzenia lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja | Opis
5.4.0 | Ta funkcja stała się również dostępna w FastCGI. Poprzednio była ona obsługiwana tylko przez PHP zainstalowany jako moduł serwera Apache.
4.3.3

Informacja:

Od PHP 4.3.3 możliwe jest użycie tej funkcji przy pracy w trybie modułu NSAPI serwera także w serwerach Netscape/iPlanet/SunONE.

Przykłady

Przykład #1 Przykład apache_response_headers()

<?php
print_r(apache_response_headers());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [Accept-Ranges] => bytes
    [X-Powered-By] => PHP/4.3.8
)

Zobacz też:

  • apache_request_headers() - Fetch all HTTP request headers
  • headers_sent() - Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło
  • headers_list() - Returns a list of response headers sent (or ready to send)

apache_reset_timeout
apache_setenv
Funkcje Apache


Ustawia zmienną Apache'a subprocess_env

apache_response_headers
getallheaders
Funkcje Apache
PHP Manual

apache_setenv

(PHP 4 >= 4.2.0, PHP 5)

apache_setenv — Ustawia zmienną Apache'a subprocess_env

Opis

int apache_setenv ( string $nazwa_zmiennej , string $wartość [, bool $nadrzędność ] )

apache_setenv() ustawia wartość zmiennej środowiskowej Apaches podanej w nazwa_zmiennej.

Informacja:

Kiedy zmieniasz zmienną środowiskową Apache, odpowiadająca jej zmienna $SERVER nie jest zmieniana.

Przykład #1 Ustawianie zmiennej środowiskowej Apache używając apache_setenv()

<?php
  apache_setenv("EXAMPLE_VAR", "Przykładowa Wartość");
  ?>

apache_setenv() może być połączone z apache_getenv() poprzez oddzielne strony lub dla ustawienia zmiennych do przekazania do Server Side Includes (.shtml), które zostały dołączone do skryptu PHP.

Patrz także: apache_getenv().

apache_response_headers
getallheaders
Funkcje Apache


Odczytuje wszystkie nagłówki HTTP z aktualnego zapytania

apache_setenv
virtual
Funkcje Apache
PHP Manual

getallheaders

(PHP 4, PHP 5)

getallheaders — Odczytuje wszystkie nagłówki HTTP z aktualnego zapytania

Opis

array getallheaders ( void )

getallheaders() jest aliasem funkcji apache_request_headers(). Zwraca tablicę asocjacyjną wszystkich nagłówków HTTP wysłanych w aktualnym zapytaniu. Więcej na ten temat w dokumentacji funkcji apache_request_headers().

Informacja:

W PHP 4.3.0 getallheaders() stała się aliasem funkcji apache_request_headers(). Dokładnie rzecz biorąc, nadano jej nową nazwę, zgodną z kanonem nazw PHP, ponieważ funkcja ta działa tylko wtedy, kiedy PHP jest skompilowane jako moduł Apache'a.

Informacja:

Od PHP 4.3.3 możliwe jest użycie tej funkcji przy pracy w trybie modułu NSAPI serwera także w serwerach Netscape/iPlanet/SunONE.

Patrz także: apache_request_headers().

apache_setenv
virtual
Funkcje Apache


Wykonuje zapytanie do Apache'a

getallheaders
IIS
Funkcje Apache
PHP Manual

virtual

(PHP 4, PHP 5)

virtual — Wykonuje zapytanie do Apache'a

Opis

int virtual ( string $nazwa_pliku )

virtual() jest funkcją właściwą jedynie Apache'owi, która jest odpowiednikiem <!--#include virtual...--> w mod_include. Funkcja wywołuje wewnętrzne żądanie Apache'a. Przydaje się do dołączania (inkludowania) skryptów CGI lub plików .shtml, lub czegokolwiek innego, co jest przetwarzane przez serwer Apache. Zwróć uwagę przy skrypcie CGI, że musi on generować poprawne nagłówki CGI, przynajmniej nagłówek Content-type.

Zanim zostanie uruchomione wewnętrzne żądanie Apache'a, najpierw zostaną wysłane oczekujące na wysłanie nagłówki HTTP a następnie wszystkie bufory wyjścia zostaną opróżnione do przeglądarki.

Ostrzeżenie

Funkcja działa tylko jeśli PHP jest skompilowane w postaci modułu Apache, ponieważ używa API Apache do tworzenia pod żądań. Łańcuch zapytań (query string) może zostać przekazany do dołączanego pliku ale $_GET jest kopiowana ze skryptu rodzica i tylko $_SERVER['QUERY_STRING'] jest wypełniana przetwarzanym łańcuchem zapytań. Łańcuch zapytań może być przekazany tylko jeśli uzywasz Apache 2. Żądany plik nie zostanie wyszczególniony w dzienniku dostępu Apache.

Począwszy od PHP 4.0.6, można używać virtual() do dołączania plików PHP, jednak w typowych sytuacjach bardziej sprawdzają się funkcje include() lub require().

Informacja:

Od PHP 4.3.3 możliwe jest użycie tej funkcji przy pracy w trybie modułu NSAPI serwera także w serwerach Netscape/iPlanet/SunONE.

getallheaders
IIS
Funkcje Apache


IIS Administration

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • IIS Funkcje
    • iis_add_server — Creates a new virtual web server
    • iis_get_dir_security — Gets Directory Security
    • iis_get_script_map — Gets script mapping on a virtual directory for a specific extension
    • iis_get_server_by_comment — Return the instance number associated with the Comment
    • iis_get_server_by_path — Return the instance number associated with the Path
    • iis_get_server_rights — Gets server rights
    • iis_get_service_state — Returns the state for the service defined by ServiceId
    • iis_remove_server — Removes the virtual web server indicated by ServerInstance
    • iis_set_app_settings — Creates application scope for a virtual directory
    • iis_set_dir_security — Sets Directory Security
    • iis_set_script_map — Sets script mapping on a virtual directory
    • iis_set_server_rights — Sets server rights
    • iis_start_server — Starts the virtual web server
    • iis_start_service — Starts the service defined by ServiceId
    • iis_stop_server — Stops the virtual web server
    • iis_stop_service — Stops the service defined by ServiceId
virtual
Wstęp
Rozszerzenia przeznaczone dla serwera


Wstęp

This extension is available for Win32 only. It provides functions to administrate Microsoft Internet Information Server (IIS). The extension includes function to create web sites and virtual directories as well as configuring security and script mapping.

IIS
Instalacja/Konfiguracja
IIS


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
IIS


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/iisfunc.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

IIS_READ (integer)
IIS_WRITE (integer)
IIS_EXECUTE (integer)
IIS_SCRIPT (integer)
IIS_ANONYMOUS (integer)
IIS_BASIC (integer)
IIS_NTLM (integer)
IIS_STARTING (integer)
IIS_STOPPED (integer)
IIS_PAUSED (integer)
IIS_RUNNING (integer)
Typy zasobów
IIS Funkcje
IIS


IIS Funkcje

Spis treści

  • iis_add_server — Creates a new virtual web server
  • iis_get_dir_security — Gets Directory Security
  • iis_get_script_map — Gets script mapping on a virtual directory for a specific extension
  • iis_get_server_by_comment — Return the instance number associated with the Comment
  • iis_get_server_by_path — Return the instance number associated with the Path
  • iis_get_server_rights — Gets server rights
  • iis_get_service_state — Returns the state for the service defined by ServiceId
  • iis_remove_server — Removes the virtual web server indicated by ServerInstance
  • iis_set_app_settings — Creates application scope for a virtual directory
  • iis_set_dir_security — Sets Directory Security
  • iis_set_script_map — Sets script mapping on a virtual directory
  • iis_set_server_rights — Sets server rights
  • iis_start_server — Starts the virtual web server
  • iis_start_service — Starts the service defined by ServiceId
  • iis_stop_server — Stops the virtual web server
  • iis_stop_service — Stops the service defined by ServiceId
Stałe predefiniowane
iis_add_server
IIS


Creates a new virtual web server

IIS Funkcje
iis_get_dir_security
IIS Funkcje
PHP Manual

iis_add_server

(PECL iisfunc SVN)

iis_add_server — Creates a new virtual web server

Opis

int iis_add_server ( string $path , string $comment , string $server_ip , int $port , string $host_name , int $rights , int $start_server )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

IIS Funkcje
iis_get_dir_security
IIS Funkcje


Gets Directory Security

iis_add_server
iis_get_script_map
IIS Funkcje
PHP Manual

iis_get_dir_security

(PECL iisfunc SVN)

iis_get_dir_security — Gets Directory Security

Opis

int iis_get_dir_security ( int $server_instance , string $virtual_path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_add_server
iis_get_script_map
IIS Funkcje


Gets script mapping on a virtual directory for a specific extension

iis_get_dir_security
iis_get_server_by_comment
IIS Funkcje
PHP Manual

iis_get_script_map

(PECL iisfunc SVN)

iis_get_script_map — Gets script mapping on a virtual directory for a specific extension

Opis

string iis_get_script_map ( int $server_instance , string $virtual_path , string $script_extension )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_get_dir_security
iis_get_server_by_comment
IIS Funkcje


Return the instance number associated with the Comment

iis_get_script_map
iis_get_server_by_path
IIS Funkcje
PHP Manual

iis_get_server_by_comment

(PECL iisfunc SVN)

iis_get_server_by_comment — Return the instance number associated with the Comment

Opis

int iis_get_server_by_comment ( string $comment )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_get_script_map
iis_get_server_by_path
IIS Funkcje


Return the instance number associated with the Path

iis_get_server_by_comment
iis_get_server_rights
IIS Funkcje
PHP Manual

iis_get_server_by_path

(PECL iisfunc SVN)

iis_get_server_by_path — Return the instance number associated with the Path

Opis

int iis_get_server_by_path ( string $path )

Each virtual server in IIS is associated with an instance number. iis_get_server_by_path() finds the instance number from the actual path to the root directory.

Parametry

path

The path to the root directory

Zwracane wartości

Returns the server instance number.

iis_get_server_by_comment
iis_get_server_rights
IIS Funkcje


Gets server rights

iis_get_server_by_path
iis_get_service_state
IIS Funkcje
PHP Manual

iis_get_server_rights

(PECL iisfunc SVN)

iis_get_server_rights — Gets server rights

Opis

int iis_get_server_rights ( int $server_instance , string $virtual_path )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_get_server_by_path
iis_get_service_state
IIS Funkcje


Returns the state for the service defined by ServiceId

iis_get_server_rights
iis_remove_server
IIS Funkcje
PHP Manual

iis_get_service_state

(PECL iisfunc SVN)

iis_get_service_state — Returns the state for the service defined by ServiceId

Opis

int iis_get_service_state ( string $service_id )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_get_server_rights
iis_remove_server
IIS Funkcje


Removes the virtual web server indicated by ServerInstance

iis_get_service_state
iis_set_app_settings
IIS Funkcje
PHP Manual

iis_remove_server

(PECL iisfunc SVN)

iis_remove_server — Removes the virtual web server indicated by ServerInstance

Opis

int iis_remove_server ( int $server_instance )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_get_service_state
iis_set_app_settings
IIS Funkcje


Creates application scope for a virtual directory

iis_remove_server
iis_set_dir_security
IIS Funkcje
PHP Manual

iis_set_app_settings

(PECL iisfunc SVN)

iis_set_app_settings — Creates application scope for a virtual directory

Opis

int iis_set_app_settings ( int $server_instance , string $virtual_path , string $application_scope )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_remove_server
iis_set_dir_security
IIS Funkcje


Sets Directory Security

iis_set_app_settings
iis_set_script_map
IIS Funkcje
PHP Manual

iis_set_dir_security

(PECL iisfunc SVN)

iis_set_dir_security — Sets Directory Security

Opis

int iis_set_dir_security ( int $server_instance , string $virtual_path , int $directory_flags )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_set_app_settings
iis_set_script_map
IIS Funkcje


Sets script mapping on a virtual directory

iis_set_dir_security
iis_set_server_rights
IIS Funkcje
PHP Manual

iis_set_script_map

(PECL iisfunc SVN)

iis_set_script_map — Sets script mapping on a virtual directory

Opis

int iis_set_script_map ( int $server_instance , string $virtual_path , string $script_extension , string $engine_path , int $allow_scripting )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_set_dir_security
iis_set_server_rights
IIS Funkcje


Sets server rights

iis_set_script_map
iis_start_server
IIS Funkcje
PHP Manual

iis_set_server_rights

(PECL iisfunc SVN)

iis_set_server_rights — Sets server rights

Opis

int iis_set_server_rights ( int $server_instance , string $virtual_path , int $directory_flags )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_set_script_map
iis_start_server
IIS Funkcje


Starts the virtual web server

iis_set_server_rights
iis_start_service
IIS Funkcje
PHP Manual

iis_start_server

(PECL iisfunc SVN)

iis_start_server — Starts the virtual web server

Opis

int iis_start_server ( int $server_instance )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_set_server_rights
iis_start_service
IIS Funkcje


Starts the service defined by ServiceId

iis_start_server
iis_stop_server
IIS Funkcje
PHP Manual

iis_start_service

(PECL iisfunc SVN)

iis_start_service — Starts the service defined by ServiceId

Opis

int iis_start_service ( string $service_id )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_start_server
iis_stop_server
IIS Funkcje


Stops the virtual web server

iis_start_service
iis_stop_service
IIS Funkcje
PHP Manual

iis_stop_server

(PECL iisfunc SVN)

iis_stop_server — Stops the virtual web server

Opis

int iis_stop_server ( int $server_instance )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_start_service
iis_stop_service
IIS Funkcje


Stops the service defined by ServiceId

iis_stop_server
NSAPI
IIS Funkcje
PHP Manual

iis_stop_service

(PECL iisfunc SVN)

iis_stop_service — Stops the service defined by ServiceId

Opis

int iis_stop_service ( string $service_id )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

iis_stop_server
NSAPI
IIS Funkcje


NSAPI

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • NSAPI Funkcje
    • nsapi_request_headers — Fetch all HTTP request headers
    • nsapi_response_headers — Fetch all HTTP response headers
    • nsapi_virtual — Perform an NSAPI sub-request
iis_stop_service
Wstęp
Rozszerzenia przeznaczone dla serwera


Wstęp

These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/Sun webservers.

NSAPI
Instalacja/Konfiguracja
NSAPI


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
NSAPI


Instalacja

For PHP installation on Netscape/iPlanet/Sun webservers see the NSAPI section (UNIX, Windows) in the installation chapter.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

The behaviour of the NSAPI PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by additional parameters to the php4_execute call in obj.conf

NSAPI configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
nsapi.read_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.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.

nsapi.read_timeout integer

Sets the time in seconds the plugin is waiting for POST data from the client.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
NSAPI Funkcje
NSAPI


NSAPI Funkcje

Zobacz też:

NSAPI implements a subset of the functions from the Apache module for maximum compatibility.

Apache functions implemented by NSAPI
Apache function (only as alias) | NSAPI function | Description
apache_request_headers() | nsapi_request_headers() | Fetch all HTTP request headers
apache_response_headers() | nsapi_response_headers() | Fetch all HTTP response headers
getallheaders() | nsapi_request_headers() | Fetch all HTTP request headers
virtual() | nsapi_virtual() | Make NSAPI sub-request

Spis treści

  • nsapi_request_headers — Fetch all HTTP request headers
  • nsapi_response_headers — Fetch all HTTP response headers
  • nsapi_virtual — Perform an NSAPI sub-request
Stałe predefiniowane
nsapi_request_headers
NSAPI


Fetch all HTTP request headers

NSAPI Funkcje
nsapi_response_headers
NSAPI Funkcje
PHP Manual

nsapi_request_headers

(PHP 4 >= 4.3.3, PHP 5)

nsapi_request_headers — Fetch all HTTP request headers

Opis

array nsapi_request_headers ( void )

nsapi_request_headers() gets all the HTTP headers in the current request. This is only supported when PHP runs as a NSAPI module.

Informacja:

Prior to PHP 4.3.3, getallheaders() was only available for the Apache servers. After PHP 4.3.3, getallheaders() is an alias for nsapi_request_headers() if you use the NSAPI module.

Informacja:

You can also get at the value of the common CGI variables by reading them from the $_SERVER superglobal, which works whether or not you are using PHP as a NSAPI module.

Zwracane wartości

Returns an associative array with all the HTTP headers.

Przykłady

Przykład #1 nsapi_request_headers() example

<?php
$headers = nsapi_request_headers();

foreach ($headers as $header => $value) {
  echo "$header: $value <br />\n";
}
?>

NSAPI Funkcje
nsapi_response_headers
NSAPI Funkcje


Fetch all HTTP response headers

nsapi_request_headers
nsapi_virtual
NSAPI Funkcje
PHP Manual

nsapi_response_headers

(PHP 4 >= 4.3.3, PHP 5)

nsapi_response_headers — Fetch all HTTP response headers

Opis

array nsapi_response_headers ( void )

Gets all the NSAPI response headers.

Zwracane wartości

Returns an associative array with all the NSAPI response headers.

Zobacz też:

  • nsapi_request_headers() - Fetch all HTTP request headers
  • headers_sent() - Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło

nsapi_request_headers
nsapi_virtual
NSAPI Funkcje


Perform an NSAPI sub-request

nsapi_response_headers
Rozszerzenia sesji
NSAPI Funkcje
PHP Manual

nsapi_virtual

(PHP 4 >= 4.3.3, PHP 5)

nsapi_virtual — Perform an NSAPI sub-request

Opis

bool nsapi_virtual ( string $uri )

nsapi_virtual() is an NSAPI-specific function which is equivalent to <!--#include virtual...--> in SSI (.shtml files). It does an NSAPI sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you'd parse through webserver.

To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.

You cannot make recursive requests with this function to other PHP scripts. If you want to include PHP scripts, use include() or require().

Informacja:

This function depends on a undocumented feature of the Netscape/iPlanet/Sun webservers. Use phpinfo() to determine if it is available. In the Unix environment it should always work, in Windows it depends on the name of a ns-httpdXX.dll file.

Read the note about subrequests in the NSAPI section (UNIX, Windows) if you experience this problem.

Parametry

uri

The URI of the script.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

nsapi_response_headers
Rozszerzenia sesji
NSAPI Funkcje


Rozszerzenia sesji

  • Msession — Mohawk Software Session Handler Functions
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Msession Funkcje
  • Sessions — Session Handling
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Session Upload Progress
    • Sessions and security
    • Session Funkcje
    • SessionHandler — The SessionHandler class
  • Session PgSQL — PostgreSQL Session Save Handler
    • Wstęp
    • Instalacja/Konfiguracja
    • Table definitions
    • Stałe predefiniowane
    • Session PgSQL Funkcje
nsapi_virtual
Msession
Opis funkcji


Mohawk Software Session Handler Functions

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Msession Funkcje
    • msession_connect — Connect to msession server
    • msession_count — Get session count
    • msession_create — Create a session
    • msession_destroy — Destroy a session
    • msession_disconnect — Close connection to msession server
    • msession_find — Find all sessions with name and value
    • msession_get_array — Get array of msession variables
    • msession_get_data — Get data session unstructured data
    • msession_get — Get value from session
    • msession_inc — Increment value in session
    • msession_list — List all sessions
    • msession_listvar — List sessions with variable
    • msession_lock — Lock a session
    • msession_plugin — Call an escape function within the msession personality plugin
    • msession_randstr — Get random string
    • msession_set_array — Set msession variables from an array
    • msession_set_data — Set data session unstructured data
    • msession_set — Set value in session
    • msession_timeout — Set/get session timeout
    • msession_uniq — Get unique id
    • msession_unlock — Unlock a session
Rozszerzenia sesji
Wstęp
Rozszerzenia sesji


Wstęp

msession is an interface to a high speed session daemon which can run either locally or remotely. It is designed to provide consistent session management for a PHP web farm. More Information about msession and the session server software itself can be found at » http://www.mohawksoft.org/?q=node/8.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.3.

Msession
Instalacja/Konfiguracja
Msession


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Msession


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/msession.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.3

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Msession Funkcje
Msession


Msession Funkcje

Spis treści

  • msession_connect — Connect to msession server
  • msession_count — Get session count
  • msession_create — Create a session
  • msession_destroy — Destroy a session
  • msession_disconnect — Close connection to msession server
  • msession_find — Find all sessions with name and value
  • msession_get_array — Get array of msession variables
  • msession_get_data — Get data session unstructured data
  • msession_get — Get value from session
  • msession_inc — Increment value in session
  • msession_list — List all sessions
  • msession_listvar — List sessions with variable
  • msession_lock — Lock a session
  • msession_plugin — Call an escape function within the msession personality plugin
  • msession_randstr — Get random string
  • msession_set_array — Set msession variables from an array
  • msession_set_data — Set data session unstructured data
  • msession_set — Set value in session
  • msession_timeout — Set/get session timeout
  • msession_uniq — Get unique id
  • msession_unlock — Unlock a session
Stałe predefiniowane
msession_connect
Msession


Connect to msession server

Msession Funkcje
msession_count
Msession Funkcje
PHP Manual

msession_connect

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_connect — Connect to msession server

Opis

bool msession_connect ( string $host , string $port )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Msession Funkcje
msession_count
Msession Funkcje


Get session count

msession_connect
msession_create
Msession Funkcje
PHP Manual

msession_count

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_count — Get session count

Opis

int msession_count ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_connect
msession_create
Msession Funkcje


Create a session

msession_count
msession_destroy
Msession Funkcje
PHP Manual

msession_create

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_create — Create a session

Opis

bool msession_create ( string $session [, string $classname [, string $data ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_count
msession_destroy
Msession Funkcje


Destroy a session

msession_create
msession_disconnect
Msession Funkcje
PHP Manual

msession_destroy

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_destroy — Destroy a session

Opis

bool msession_destroy ( string $name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_create
msession_disconnect
Msession Funkcje


Close connection to msession server

msession_destroy
msession_find
Msession Funkcje
PHP Manual

msession_disconnect

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_disconnect — Close connection to msession server

Opis

void msession_disconnect ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_destroy
msession_find
Msession Funkcje


Find all sessions with name and value

msession_disconnect
msession_get_array
Msession Funkcje
PHP Manual

msession_find

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_find — Find all sessions with name and value

Opis

array msession_find ( string $name , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_disconnect
msession_get_array
Msession Funkcje


Get array of msession variables

msession_find
msession_get_data
Msession Funkcje
PHP Manual

msession_get_array

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get_array — Get array of msession variables

Opis

array msession_get_array ( string $session )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_find
msession_get_data
Msession Funkcje


Get data session unstructured data

msession_get_array
msession_get
Msession Funkcje
PHP Manual

msession_get_data

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get_data — Get data session unstructured data

Opis

string msession_get_data ( string $session )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_get_array
msession_get
Msession Funkcje


Get value from session

msession_get_data
msession_inc
Msession Funkcje
PHP Manual

msession_get

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_get — Get value from session

Opis

string msession_get ( string $session , string $name , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_get_data
msession_inc
Msession Funkcje


Increment value in session

msession_get
msession_list
Msession Funkcje
PHP Manual

msession_inc

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_inc — Increment value in session

Opis

string msession_inc ( string $session , string $name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_get
msession_list
Msession Funkcje


List all sessions

msession_inc
msession_listvar
Msession Funkcje
PHP Manual

msession_list

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_list — List all sessions

Opis

array msession_list ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_inc
msession_listvar
Msession Funkcje


List sessions with variable

msession_list
msession_lock
Msession Funkcje
PHP Manual

msession_listvar

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_listvar — List sessions with variable

Opis

array msession_listvar ( string $name )

Used for searching sessions with common attributes.

Parametry

name

The name being searched.

Zwracane wartości

Returns an associative array of value/session for all sessions with a variable named name.

msession_list
msession_lock
Msession Funkcje


Lock a session

msession_listvar
msession_plugin
Msession Funkcje
PHP Manual

msession_lock

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_lock — Lock a session

Opis

int msession_lock ( string $name )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_listvar
msession_plugin
Msession Funkcje


Call an escape function within the msession personality plugin

msession_lock
msession_randstr
Msession Funkcje
PHP Manual

msession_plugin

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_plugin — Call an escape function within the msession personality plugin

Opis

string msession_plugin ( string $session , string $val [, string $param ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_lock
msession_randstr
Msession Funkcje


Get random string

msession_plugin
msession_set_array
Msession Funkcje
PHP Manual

msession_randstr

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_randstr — Get random string

Opis

string msession_randstr ( int $param )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_plugin
msession_set_array
Msession Funkcje


Set msession variables from an array

msession_randstr
msession_set_data
Msession Funkcje
PHP Manual

msession_set_array

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_set_array — Set msession variables from an array

Opis

void msession_set_array ( string $session , array $tuples )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_randstr
msession_set_data
Msession Funkcje


Set data session unstructured data

msession_set_array
msession_set
Msession Funkcje
PHP Manual

msession_set_data

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_set_data — Set data session unstructured data

Opis

bool msession_set_data ( string $session , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_set_array
msession_set
Msession Funkcje


Set value in session

msession_set_data
msession_timeout
Msession Funkcje
PHP Manual

msession_set

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_set — Set value in session

Opis

bool msession_set ( string $session , string $name , string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_set_data
msession_timeout
Msession Funkcje


Set/get session timeout

msession_set
msession_uniq
Msession Funkcje
PHP Manual

msession_timeout

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_timeout — Set/get session timeout

Opis

int msession_timeout ( string $session [, int $param ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_set
msession_uniq
Msession Funkcje


Get unique id

msession_timeout
msession_unlock
Msession Funkcje
PHP Manual

msession_uniq

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_uniq — Get unique id

Opis

string msession_uniq ( int $param [, string $classname [, string $data ]] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_timeout
msession_unlock
Msession Funkcje


Unlock a session

msession_uniq
Sessions
Msession Funkcje
PHP Manual

msession_unlock

(PHP 4 >= 4.2.0, PHP 5 <= 5.1.2)

msession_unlock — Unlock a session

Opis

int msession_unlock ( string $session , int $key )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

msession_uniq
Sessions
Msession Funkcje


Session Handling

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic usage
    • Passing the Session ID
    • Custom Session Handlers
  • Session Upload Progress
  • Sessions and security
  • Session Funkcje
    • session_cache_expire — Zwróć bieżący czas przedawnienia pamięci podręcznej
    • session_cache_limiter — Pobierz i/lub ustaw bieżący ogranicznik pamięci podręcznej
    • session_commit — Alias dla session_write_close
    • session_decode — Dekoduje dane sesji ze stringu
    • session_destroy — Niszczy wszystkie dane zarejestrowane w sesji
    • session_encode — Koduje dane bieżącej sesji do postaci ciągu tekstowego
    • session_get_cookie_params — Pobierz parametry ciasteczka sesyjnego
    • session_id — Pobierz i/lub ustaw identyfikator bieżącej sesji
    • session_is_registered — Sprawdź czy globalna zmienna jest zarejestrowana w sesji
    • session_module_name — Pobierz i/lub ustaw moduł bieżącej sesji
    • session_name — Pobierz i/lub ustaw nazwę bieżącej sesji
    • session_regenerate_id — Zmienia bieżący identyfikator sesji na nowy, automatycznie wygenerowany
    • session_register_shutdown — Session shutdown function
    • session_register — Zarejestruj jedną lub więcej zmiennych globalnych w bieżącej sesji
    • session_save_path — Pobierz i/lub ustaw ścieżkę zapisu bieżącej sesji
    • session_set_cookie_params — Ustaw parametry ciasteczka sesyjnego
    • session_set_save_handler — Ustawia funkcje użytkownika do przechowywania sesji
    • session_start — Inicjalizuj dane sesji
    • session_status — Returns the current session status
    • session_unregister — Wyrejestruj zmienną globalną z bieżącej sesji
    • session_unset — Zwolnij wszystkie zmienne sesyjne
    • session_write_close — Zapisz dane i zakończ sesję
  • SessionHandler — The SessionHandler class
    • SessionHandler::close — Close the session
    • SessionHandler::destroy — Destroy a session
    • SessionHandler::gc — Cleanup old sessions
    • SessionHandler::open — Initialize session
    • SessionHandler::read — Read session data
    • SessionHandler::write — The write purpose
msession_unlock
Wstęp
Rozszerzenia sesji


Wstęp

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.

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

The session support allows you to store data between requests in the $_SESSION superglobal array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Uwaga

If you turn on session.auto_start then the only way to put objects into your sessions is to load its class definition using auto_prepend_file in which you load the class definition else you will have to serialize() your object and unserialize() it afterwards.

$_SESSION (and all registered variables) are serialized after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later.

Ostrzeżenie

Because session data is serialized, resource variables cannot be stored in the session.

Informacja:

Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function.

Informacja:

PHP 5.2.2 introduced an undocumented feature to store session files in "/tmp" even if open_basedir was enabled and "/tmp" is not explicitly added to the allowed paths list. This feature has been removed from PHP as of PHP 5.3.0.

Sessions
Instalacja/Konfiguracja
Sessions


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Sessions


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.

Informacja:

Optionally you can use shared memory allocation (mm), developed by Ralf S. Engelschall, for session storage. You have to download » mm and install it. This option is not available for Windows platforms. Note that the session storage module for mm does not guarantee that concurrent accesses to the same session are properly locked. It might be more appropriate to use a shared memory based filesystem (such as tmpfs on Solaris/Linux, or /dev/md on BSD) to store sessions in files, because they are properly locked. Session data is stored in memory thus web server restart deletes it.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Obsługa sesji jest domyślnie włączona. Aby zbudować PHP bez obsługi sesji, należy podać opcję --disable-session do wywołania configure. Aby użyć pamięci współdzielonej do przechowywania sesji, należy podać opcję --with-mm[=DIR] .

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:

Domyślnie, wszystkie dane związane z poszczególnymi sesjami będą przechowywane w plikach w katalogu określonym przez opcję session.save_path. Plik dla każdej sesji (niezależnie od tego, czy do sesji przypisane są jakiekolwiek dane) zostanie stworzony. Wiąże się to z faktem, że sesja jest otwierana (plik jest tworzony) ale nie są zapisywane żadne dane. To zachowanie ma efekt uboczny poprzez ograniczenia systemu plików i możliwe jest, że inny system obsługi sesji (na przykład taki, który używa bazy danych) nie śledzi sesji, które nie zawierają danych.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Session configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
session.save_path | "" | PHP_INI_ALL |
session.name | "PHPSESSID" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.auto_start | "0" | PHP_INI_ALL |
session.gc_probability | "1" | PHP_INI_ALL |
session.gc_divisor | "100" | PHP_INI_ALL | Available since PHP 4.3.2.
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL | Available since PHP 4.0.4.
session.cookie_httponly | "" | PHP_INI_ALL | Available since PHP 5.2.0.
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.referer_check | "" | PHP_INI_ALL |
session.entropy_file | "" | PHP_INI_ALL |
session.entropy_length | "0" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cache_expire | "180" | PHP_INI_ALL |
session.use_trans_sid | "0" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3.
session.bug_compat_42 | "1" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.4.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.4.0.
session.hash_function | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
session.hash_bits_per_character | "4" | PHP_INI_ALL | Available since PHP 5.0.0.
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | Available since PHP 4.0.4.
session.upload_progress.enabled | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.cleanup | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.freq | "1%" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR | Available since 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.

The session management system supports a number of configuration options which you can place in your php.ini file. We will give a short overview.

session.save_handler string
session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files. Note that individual extensions may register their own save_handlers; registered handlers can be obtained on a per-installation basis by referring to phpinfo(). See also session_set_save_handler().
session.save_path string
session.save_path defines the argument which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. See also session_save_path().

There is an optional N argument to this directive that determines the number of directory levels your session files will be spread around in. For example, setting to '5;/tmp' may end up creating a session file and location like /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . In order to use N you must create all of these directories before use. A small shell script exists in ext/session to do this, it's called mod_files.sh, with a Windows version called mod_files.bat. Also note that if N is used and greater than 0 then automatic garbage collection will not be performed, see a copy of php.ini for further information. Also, if you use N, be sure to surround session.save_path in "quotes" because the separator (;) is also used for comments in php.ini.

Ostrzeżenie

If you leave this set to a world-readable directory, such as /tmp (the default), other users on the server may be able to hijack sessions by getting the list of files in that directory.

Informacja: Prior to PHP 4.3.6, Windows users had to change this variable in order to use PHP's session functions. A valid path must be specified, e.g.: c:/temp.

session.name string
session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID. See also session_name().
session.auto_start boolean
session.auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).
session.serialize_handler string
session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. Currently, a PHP internal format (name php or php_binary) and WDDX are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. Defaults to php.
session.gc_probability integer
session.gc_probability in conjunction with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is started. Defaults to 1. See session.gc_divisor for details.
session.gc_divisor integer
session.gc_divisor coupled with session.gc_probability defines the probability that the gc (garbage collection) process is started on every session initialization. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request. session.gc_divisor defaults to 100.
session.gc_maxlifetime integer
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor).

Informacja:

If different scripts have different values of session.gc_maxlifetime but share the same place for storing the session data then the script with the minimum value will be cleaning the data. In this case, use this directive together with session.save_path.

Informacja: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.

session.referer_check string
session.referer_check contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string.
session.entropy_file string
session.entropy_file gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process. Examples are /dev/random or /dev/urandom which are available on many Unix systems. This feature is supported on Windows since PHP 5.3.3. Setting session.entropy_length to a non zero value will make PHP use the Windows Random API as entropy source.
session.entropy_length integer
session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 0 (disabled).
session.use_cookies boolean
session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).
session.use_only_cookies boolean
session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0. Defaults to 1 (enabled) since PHP 5.3.0.
session.cookie_lifetime integer
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0. See also session_get_cookie_params() and session_set_cookie_params().

Informacja:

The expiration timestamp is set relative to the server time, which is not necessarily the same as the time in the client's browser.

session.cookie_path string
session.cookie_path specifies path to set in the session cookie. Defaults to /. See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_domain string
session.cookie_domain specifies the domain to set in the session cookie. Default is none at all meaning the host name of the server which generated the cookie according to cookies specification. See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_secure boolean
session.cookie_secure specifies whether cookies should only be sent over secure connections. Defaults to off. This setting was added in PHP 4.0.4. See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_httponly boolean
Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).
session.cache_limiter string
session.cache_limiter specifies the cache control method used for session pages. It may be one of the following values: nocache, private, private_no_expire, or public. Defaults to nocache. See also the session_cache_limiter() documentation for information about what these values mean.
session.cache_expire integer
session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180. See also session_cache_expire().
session.use_trans_sid boolean
session.use_trans_sid whether transparent sid support is enabled or not. Defaults to 0 (disabled).

Informacja: For PHP 4.1.2 or less, it is enabled by compiling with --enable-trans-sid. From PHP 4.2.0, trans-sid feature is always compiled. URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example.

session.bug_compat_42 boolean
PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled. This feature/bug can be disabled by disabling this directive.
session.bug_compat_warn boolean
PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling both session.bug_compat_42 and session.bug_compat_warn.
session.hash_function mixed
session.hash_function allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits).

Since PHP 5.3.0 it is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function.

Informacja:

This setting was introduced in PHP 5.

session.hash_bits_per_character integer
session.hash_bits_per_character allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").

Informacja:

This was introduced in PHP 5.

url_rewriter.tags string
url_rewriter.tags specifies which HTML tags are rewritten to include session id if transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form=fakeentry,fieldset=

Informacja: If you want HTML/XHTML strict conformity, remove the form entry and use the <fieldset> tags around your form fields.

session.upload_progress.enabled boolean
Enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled.
session.upload_progress.cleanup boolean
Cleanup the progress information as soon as all POST data has been read (i.e. upload completed). Defaults to 1, enabled.

Informacja: It is highly recommended to keep this feature enabled.

session.upload_progress.prefix string
A prefix used for the upload progress key in the $_SESSION. This key will be concatenated with the value of $_POST[ini_get("session.upload_progress.name")] to provide a unique index. Defaults to "upload_progress_".
session.upload_progress.name string
The name of the key to be used in $_SESSION storing the progress information. See also session.upload_progress.prefix. If $_POST[ini_get("session.upload_progress.name")] is not passed or available, upload progressing will not be recorded. Defaults to "PHP_SESSION_UPLOAD_PROGRESS".
session.upload_progress.freq mixed
Defines how often the upload progress information should be updated. This can be defined in bytes (i.e. "update progress information after every 100 bytes"), or in percentages (i.e. "update progress information after receiving every 1% of the whole filesize). Defaults to "1%".
session.upload_progress.min-freq integer
The minimum delay between updates, in seconds. Defaults to "1" (one second).

The track_vars and register_globals configuration settings influence how the session variables get stored and restored.

Upload progress will not be registered unless session.upload_progress.enabled is enabled, and the $_POST[ini_get("session.upload_progress.name")] variable is set. See Session Upload Progress for mor details on this functionality.

Informacja:

As of PHP 4.0.3, track_vars is always turned on.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

SID (string)
Stała zawierająca nazwę sesji i jej identyfikator w postaci "name=ID" lub pusty ciąg tekstowy, jeśli identyfikator sesji został ustawiony przez prawidłowe ciasteczko sesyjne. Jest to ten sam ID, który zwraca funkcja session_id().
Typy zasobów
Przykłady
Sessions


Przykłady

Spis treści

  • Basic usage
  • Passing the Session ID
  • Custom Session Handlers
Stałe predefiniowane
Basic usage
Sessions


Basic usage

Informacja:

As of PHP 4.1.0, $_SESSION is available as a global variable just like $_POST, $_GET, $_REQUEST and so on. Unlike $HTTP_SESSION_VARS, $_SESSION is always global. Therefore, you do not need to use the global keyword for $_SESSION. Please note that this documentation has been changed to use $_SESSION everywhere. You can substitute $HTTP_SESSION_VARS for $_SESSION, if you prefer the former. Also note that you must start your session using session_start() before use of $_SESSION becomes available.

The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.

If register_globals is disabled, only members of the global associative array $_SESSION can be registered as session variables. The restored session variables will only be available in the array $_SESSION.

Use of $_SESSION (or $HTTP_SESSION_VARS with PHP 4.0.6 or less) is recommended for improved security and code readability. With $_SESSION, there is no need to use the session_register(), session_unregister(), session_is_registered() functions. Session variables are accessible like any other variables.

Przykład #1 Registering a variable with $_SESSION.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
  $_SESSION['count']++;
}
?>

Przykład #2 Unregistering a variable with $_SESSION and register_globals disabled.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?>

Uwaga

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Ostrzeżenie

You can't use references in session variables as there is no feasible way to restore a reference to another variable.

If register_globals is enabled, then each global variable can be registered as session variable. Upon a restart of a session, these variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users need to register variables with session_register() function. You can avoid this by simply setting entries in $_SESSION.

Uwaga

Before PHP 4.3.0, if you are using $_SESSION and you have disabled register_globals, don't use session_register(), session_is_registered() or session_unregister(). Disabling register_globals is recommended for both security and performance reasons.

If register_globals is enabled, then the global variables and the $_SESSION entries will automatically reference the same values which were registered in the prior session instance. However, if the variable is registered by $_SESSION then the global variable is available since the next request.

There is a defect in PHP 4.2.3 and earlier. If you register a new session variable by using session_register(), the entry in the global scope and the $_SESSION entry will not reference the same value until the next session_start(). I.e. a modification to the newly registered global variable will not be reflected by the $_SESSION entry. This has been corrected in PHP 4.3.0.

Przykłady
Passing the Session ID
Przykłady


Passing the Session ID

There are two methods to propagate a session id:

  • Cookies
  • URL parameter

The session module supports both methods. Cookies are optimal, but because they are not always available, we also provide an alternative way. The second method embeds the session id directly into URLs.

PHP is capable of transforming links transparently. Unless you are using PHP 4.2.0 or later, you need to enable it manually when building PHP. Under Unix, pass --enable-trans-sid to configure. If this build option and the run-time option session.use_trans_sid are enabled, relative URIs will be changed to contain the session id automatically.

Informacja:

The arg_separator.output php.ini directive allows to customize the argument seperator. For full XHTML conformance, specify &amp; there.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

Przykład #1 Counting the number of hits of a single user

<?php

session_start();

if (empty($_SESSION['count'])) {
 $_SESSION['count'] = 1;
} else {
 $_SESSION['count']++;
}
?>

<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>

<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click
here</a>.
</p>

The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

Printing the SID, like shown above, is not necessary if --enable-trans-sid was used to compile PHP.

Informacja:

Non-relative URLs are assumed to point to external sites and hence don't append the SID, as it would be a security risk to leak the SID to a different server.

Basic usage
Custom Session Handlers
Przykłady


Custom Session Handlers

To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions.

Passing the Session ID
Session Upload Progress
Przykłady


Session Upload Progress

When the session.upload_progress.enabled INI option is enabled, PHP will be able to track the upload progress of individual files being uploaded. This information isn't particularly useful for the actual upload request itself, but during the file upload an application can send an POST request to a separate endpoint (via XHR for example) to check the status.

The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.

<?php
$key = ini_get("session.upload_progress.prefix") . ini_get("session.upload-progress.name");
var_dump($_SESSION[$key]);
?>

It is also possible to cancel the currently in-progress file upload, by setting the $_SESSION[$key]["cancel_upload"] key to TRUE. When uploading multiple files in the same request, this will only cancel the currently in-progress file upload, and pending file uploads, but will not remove successfully completed uploads. When a upload is cancelled like this, the error key in $_FILES array will be set to UPLOAD_ERR_EXTENSION.

The session.upload_progress.freq and session.upload_progress.min_freq INI options control how frequent the upload progress information should be recalculated. With a reasonable amount for these two settings, the overhead of this feature is almost non-existent.

Przykład #1 Example information

Example of the structure of progress upload array.

<form action="upload.php" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
 <input type="file" name="file1" />
 <input type="file" name="file2" />
 <input type="submit" />
</form>

The data stored in the session will look like this:

<?php
$_SESSION["upload_progress_123"] = array(
 "start_time" => 1234567890,   // The request time
 "content_length" => 57343257, // POST content length
 "bytes_processed" => 453489,  // Amount of bytes received and processed
 "done" => false,              // true when the POST handler has finished, successfully or not
 "files" => array(
  0 => array(
   "field_name" => "file1",       // Name of the <input/> field
   // The following 3 elements equals those in $_FILES
   "name" => "foo.avi",
   "tmp_name" => "/tmp/phpxxxxxx",
   "error" => 0,
   "done" => true,                // True when the POST handler has finished handling this file
   "start_time" => 1234567890,    // When this file has started to be processed
   "bytes_processed" => 57343250, // Amount of bytes received and processed for this file
  ),
  // An other file, not finished uploading, in the same request
  1 => array(
   "field_name" => "file2",
   "name" => "bar.avi",
   "tmp_name" => NULL,
   "error" => 0,
   "done" => false,
   "start_time" => 1234567899,
   "bytes_processed" => 54554,
  ),
 )
);

Custom Session Handlers
Sessions and security
Sessions


Sessions and security

External links: » Session fixation

The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session. You need to take additional measures to actively protect the integrity of the session, depending on the value associated with it.

Assess the importance of the data carried by your sessions and deploy additional protections -- this usually comes at a price, reduced convenience for the user. For example, if you want to protect users from simple social engineering tactics, you need to enable session.use_only_cookies. In that case, cookies must be enabled unconditionally on the user side, or sessions will not work.

There are several ways to leak an existing session id to third parties. A leaked session id enables the third party to access all resources which are associated with a specific id. First, URLs carrying session ids. If you link to an external site, the URL including the session id might be stored in the external site's referrer logs. Second, a more active attacker might listen to your network traffic. If it is not encrypted, session ids will flow in plain text over the network. The solution here is to implement SSL on your server and make it mandatory for users.

Session Upload Progress
Session Funkcje
Sessions


Session Funkcje

Spis treści

  • session_cache_expire — Zwróć bieżący czas przedawnienia pamięci podręcznej
  • session_cache_limiter — Pobierz i/lub ustaw bieżący ogranicznik pamięci podręcznej
  • session_commit — Alias dla session_write_close
  • session_decode — Dekoduje dane sesji ze stringu
  • session_destroy — Niszczy wszystkie dane zarejestrowane w sesji
  • session_encode — Koduje dane bieżącej sesji do postaci ciągu tekstowego
  • session_get_cookie_params — Pobierz parametry ciasteczka sesyjnego
  • session_id — Pobierz i/lub ustaw identyfikator bieżącej sesji
  • session_is_registered — Sprawdź czy globalna zmienna jest zarejestrowana w sesji
  • session_module_name — Pobierz i/lub ustaw moduł bieżącej sesji
  • session_name — Pobierz i/lub ustaw nazwę bieżącej sesji
  • session_regenerate_id — Zmienia bieżący identyfikator sesji na nowy, automatycznie wygenerowany
  • session_register_shutdown — Session shutdown function
  • session_register — Zarejestruj jedną lub więcej zmiennych globalnych w bieżącej sesji
  • session_save_path — Pobierz i/lub ustaw ścieżkę zapisu bieżącej sesji
  • session_set_cookie_params — Ustaw parametry ciasteczka sesyjnego
  • session_set_save_handler — Ustawia funkcje użytkownika do przechowywania sesji
  • session_start — Inicjalizuj dane sesji
  • session_status — Returns the current session status
  • session_unregister — Wyrejestruj zmienną globalną z bieżącej sesji
  • session_unset — Zwolnij wszystkie zmienne sesyjne
  • session_write_close — Zapisz dane i zakończ sesję
Sessions and security
session_cache_expire
Sessions


Zwróć bieżący czas przedawnienia pamięci podręcznej

Session Funkcje
session_cache_limiter
Session Funkcje
PHP Manual

session_cache_expire

(PHP 4 >= 4.2.0, PHP 5)

session_cache_expire — Zwróć bieżący czas przedawnienia pamięci podręcznej

Opis

int session_cache_expire ([ int $nowy_czas ] )

session_cache_expire() zwraca bieżące ustawienie session.cache_expire. Zwrócona wartość podana jest w minutach. Jeśli podany zostanie parametr nowy_czas, bieżący czas przedawnienia zostanie zamieniony na nowy_czas.

Czas przedawnienia jest ustawiany na wartość 180 przechowywaną w session.cache_limiter w momencie startu. W związku z tym niezbędne jest wywołanie session_cache_expire() dla każdego żądania pobrania strony (zanim zostanie wywołane session_start()).

Przykład #1 Przykład użycia session_cache_expire()

<?php

/* ustaw ogranicznik pamięci podręcznej na 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

/* ustaw czas przedawnienia pamięci podręcznej na 30 minut */
session_cache_expire(30);
$cache_expire = session_cache_expire();

/* rozpocznij sesję */

session_start();

echo "Ogranicznik pamięci podręcznej to $cache_limiter<br />";
echo "Znajdujące się w pamięci podręcznej strony sesyjne przedawnią się " .
   "po $cache_expire minutach";
?>

Informacja: Ustawienie nowy_czas ma efekt tylko jeśli session.cache_limiter ma wartość różną od nocache.

Patrz także: session.cache_expire, session.cache_limiter i session_cache_limiter().

Session Funkcje
session_cache_limiter
Session Funkcje


Pobierz i/lub ustaw bieżący ogranicznik pamięci podręcznej

session_cache_expire
session_commit
Session Funkcje
PHP Manual

session_cache_limiter

(PHP 4 >= 4.0.3, PHP 5)

session_cache_limiter — Pobierz i/lub ustaw bieżący ogranicznik pamięci podręcznej

Opis

string session_cache_limiter ([ string $ogranicznik ] )

session_cache_limiter() zwraca nazwę bieżącego ogranicznika pamięci podręcznej. Jeśli podany został parametr ogranicznik, nazwa bieżącego ogranicznego zostanie zmieniona na nową wartość.

Ogranicznik pamięci podręcznej kontroluje nagłówki HTTP wysyłane do klienta. Nagłówki te ustalają zasady, według których zawartość strony może być przechowywana w pamięci podręcznej przeglądarki. Ustawiając ogranicznik pamięci podręcznej na nocache zabronimy jakiekolwiek zachowywanie strony po stronie klienta. Wartość public pozwoli na takie przechywanie. Ogranicznikiem może być też private, który jest troszkę bardziej restrykcyjny niż public.

W trybie private nagłówek Expire, który jest wysyłany do klienta, może spowodować nieoczekiwane działanie niektórych przeglądarek, między innymi Mozilli. Możesz uniknąć tego problemu używając trybu private_no_expire. Nagłówek Expire nie jest w tym wypadku wysyłany do klienta.

Informacja:

private_no_expire zostało dodane w PHP 4.2.0.

Ogranicznik pamięci podręcznej w momencie wywołania skryptu jest zerowany do wartości domyślnej przechowywanej w session.cache_limiter. W związku z tym niezbędne jest wywołanie session_cache_limiter() dla każdego wywołania skryptu (i przed wywołaniem session_start()).

Przykład #1 Przykłady session_cache_limiter()

<?php

/* Ustaw ogranicznik pamięci podręcznej na 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "Ogranicznikiem pamięci podręcznej jest teraz $cache_limiter<br />";
?>

Patrz także: session.cache_limiter.

session_cache_expire
session_commit
Session Funkcje


Alias dla session_write_close

session_cache_limiter
session_decode
Session Funkcje
PHP Manual

session_commit

(PHP 4 >= 4.4.0, PHP 5)

session_commit — Alias dla session_write_close()

Opis

Ta funkcja jest aliasem dla: session_write_close().

session_cache_limiter
session_decode
Session Funkcje


Dekoduje dane sesji ze stringu

session_commit
session_destroy
Session Funkcje
PHP Manual

session_decode

(PHP 4, PHP 5)

session_decode — Dekoduje dane sesji ze stringu

Opis

bool session_decode ( string $dane )

session_decode() dekofuje dane sesji zawarte w parametrze dane, ustawiając zmienne zachowane w sesji.

Patrz także: session_encode().

session_commit
session_destroy
Session Funkcje


Niszczy wszystkie dane zarejestrowane w sesji

session_decode
session_encode
Session Funkcje
PHP Manual

session_destroy

(PHP 4, PHP 5)

session_destroy — Niszczy wszystkie dane zarejestrowane w sesji

Opis

bool session_destroy ( void )

session_destroy() niszczy wszystkie dane skojarzone z bieżącą sesją. Nie usuwa żadnych globalnych zmiennych związanych z sesją. Nie usuwa też ciasteczka sesyjnego.

Aby "zabić" całość sesji, na przykład aby wylogować użytwkonika, należy także usunąć identyfikator sesji. Jeśli do propagowania identyfikatora sesji jużyte było ciasteczko, to usunięte musi być ciasteczko sesyjne. Można do tego użyć funkcji setcookie().

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Niszczenie sesji przy użyciu $_SESSION

<?php
// Inicjalizuj sesję
// Jeśli używasz sesion_name("cośtam"), nie zapomnij o tym teraz!
session_start();
// Usuń wszystkie zmienne sesyjne
$_SESSION = array();

// Jeśli pożądane jest zabicie sesji, usuń także ciasteczko sesyjne.
// Uwaga: to usunie sesję, nie tylko dane sesji
if (isset($_COOKIE[session_name()])) {
   setcookie(session_name(), '', time()-42000, '/');
}

// Na koniec zniszcz sesję
session_destroy();

Informacja:

session_unset() należy używać dla starszego kodu, który nie korzysta z $_SESSION.

Patrz także: unset() i setcookie().

session_decode
session_encode
Session Funkcje


Koduje dane bieżącej sesji do postaci ciągu tekstowego

session_destroy
session_get_cookie_params
Session Funkcje
PHP Manual

session_encode

(PHP 4, PHP 5)

session_encode — Koduje dane bieżącej sesji do postaci ciągu tekstowego

Opis

string session_encode ( void )

session_encode() zwraca ciąg tekstowy zawierający zakodowane dane bieżącej sesji.

Patrz także: session_decode().

session_destroy
session_get_cookie_params
Session Funkcje


Pobierz parametry ciasteczka sesyjnego

session_encode
session_id
Session Funkcje
PHP Manual

session_get_cookie_params

(PHP 4, PHP 5)

session_get_cookie_params — Pobierz parametry ciasteczka sesyjnego

Opis

array session_get_cookie_params ( void )

Funkcja session_get_cookie_params() zwraca tablicę zawierającą informacje o bieżącym ciasteczku sesyjnym. Tablica zawiera poniższe informacje:

  • "lifetime" - Czas życia ciasteczka w sekundach
  • "path" - Ścieżka na której przechowywane są informacje.
  • "domain" - Domena ciasteczka.
  • "secure" - Ciasteczko powinno być przesłane tylko przez bezpieczne połączenie. (Ten element został dodany w PHP 4.0.4.)

Patrz także: session.cookie_lifetime, session.cookie_path, session.cookie_domain, session.cookie_secure i session_set_cookie_params().

session_encode
session_id
Session Funkcje


Pobierz i/lub ustaw identyfikator bieżącej sesji

session_get_cookie_params
session_is_registered
Session Funkcje
PHP Manual

session_id

(PHP 4, PHP 5)

session_id — Pobierz i/lub ustaw identyfikator bieżącej sesji

Opis

string session_id ([ string $id ] )

Funkcja session_id() jest używana do pobierania i ustawiania identyfikatora dla bieżącej sesji.

Do pobrania nazwy i identyfikatora bieżącej sesji moża być użyta także stała SID, która zawiera string odpowiedni do dodawania go do URLi. Przeczytaj także rozdział Obsługa sesji

Parametry

id

Jeśli podany został parametr id, zostanie on użyty do zmiany identyfikatora bieżącej sesji. Przy takim użyciu session_id() musi być wywołane przed session_start(). Zależnie od funkcji obsługi sesji, nie wszystkie znaki są dozwolone wewnątrz identyfikatora sesji. Na przykład, funkcje obsługi sesji oparte na plikach pozwalają tylko na znaki z przedziału a-z, A-Z i 0-9.

Informacja: Używając ciasteczek sesyjnych, podanie parametru id funkcji session_id() spowoduje wysłanie nowego ciasteczka przy wywołaniu funkcji session_start(), niezależnie od tego czy bieżący identyfikator sesji jest identyczny z tym, który ma być ustawiony.

Zwracane wartości

session_id() zwraca identyfikator bieżącej sesji lub pusty ciąg ("") jeśli nie ma bieżącej sesji (nie istnieje bieżący identyfikator sesji).

Zobacz też:

  • session_regenerate_id() - Zmienia bieżący identyfikator sesji na nowy, automatycznie wygenerowany
  • session_start() - Inicjalizuj dane sesji
  • session_set_save_handler() - Ustawia funkcje użytkownika do przechowywania sesji
  • session.save_handler

session_get_cookie_params
session_is_registered
Session Funkcje


Sprawdź czy globalna zmienna jest zarejestrowana w sesji

session_id
session_module_name
Session Funkcje
PHP Manual

session_is_registered

(PHP 4, PHP 5)

session_is_registered — Sprawdź czy globalna zmienna jest zarejestrowana w sesji

Opis

bool session_is_registered ( string $nazwa )

session_is_registered() zwraca wartość TRUE jeśli w bieżącej sesji zarejestrowana jest globalna zmienna o nazwie nazwa.

Informacja:

Jeśli użyta została tablica $_SESSION (lub $HTTP_SESSION_VARS dla PHP 4.0.6 lub starszych), do sprawdzenia czy zmienna została zarejestrowana w sesji należy użyć funkcji isset() na tablicy $_SESSION.

Uwaga

Przy użyciu
$_SESSION (lub $HTTP_SESSION_VARS),
nie należy używać session_register(),
session_is_registered() i
session_unregister().

session_id
session_module_name
Session Funkcje


Pobierz i/lub ustaw moduł bieżącej sesji

session_is_registered
session_name
Session Funkcje
PHP Manual

session_module_name

(PHP 4, PHP 5)

session_module_name — Pobierz i/lub ustaw moduł bieżącej sesji

Opis

string session_module_name ([ string $moduł ] )

session_module_name() zwraca nazwę bieżącego modułu sesji. Jeśli podany został parametr moduł, użyty zostanie nowo podany moduł.

session_is_registered
session_name
Session Funkcje


Pobierz i/lub ustaw nazwę bieżącej sesji

session_module_name
session_regenerate_id
Session Funkcje
PHP Manual

session_name

(PHP 4, PHP 5)

session_name — Pobierz i/lub ustaw nazwę bieżącej sesji

Opis

string session_name ([ string $nazwa ] )

session_name() zwraca nazwę bieżącej sesji. Jeśli podano parametr name, nazwa bieżącej sesji zostanie zmieniona na tą wartość.

Nazwa sesji jest używana w identyfikatorze sesji w ciasteczkach i URLach. Powinna zawierać tylko znaki alfanumeryczne; powinna być krótka i treściwa (np. dla użytkowników z włączonymi ostrzeżeniami o ciasteczkach). Nazwa sesji jest przywracana do domyślnej wartości określonej w session.name na początku wywołania strony, a więc musisz wywołać session_name() dla każdej strony (przed wywołaniem w niej session_start() i session_register()).

Ostrzeżenie

Nazwa sesji nie może składać się tylko z cyfr - musi zawierać przynajmniej jedną literę. W przeciwnym przypadku za każdym odwołaniem generowana będzie nowa sesja.

Przykład #1 Przykłady session_name()

<?php

/* ustaw nazwę sesji na WebsiteID */

$poprzednia_nazwa = session_name ("WebsiteID");

echo "Poprzednią nazwą sesji było $poprzednia_nazwa<br />";
?>

Zobacz także opis dyrektywy konfiguracji session.name.

session_module_name
session_regenerate_id
Session Funkcje


Zmienia bieżący identyfikator sesji na nowy, automatycznie wygenerowany

session_name
session_register_shutdown
Session Funkcje
PHP Manual

session_regenerate_id

(PHP 4 >= 4.3.2, PHP 5)

session_regenerate_id — Zmienia bieżący identyfikator sesji na nowy, automatycznie wygenerowany

Opis

bool session_regenerate_id ([ bool $usunięcie_starej_sesji = false ] )

session_regenerate_id() zastępuje bieżący identyfikator sesji nowym, i zachowuje w nowej sesji wszystkie aktualne informacje.

Parametry

usunięcie_starej_sesji

Określa czy stary identyfikator sesji ma zostać usunięty, czy też nie.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
4.3.3 | Od tej wersji PHP, jeśli ciasteczka sesji są aktywne, wywołanie session_regenerate_id() utworzy nowe ciasteczko sesji z nowym identyfikatorem sesji.
5.1.0 | Dodano parametr usunięcie_starej_sesji.

Przykłady

Przykład #1 Przykład session_regenerate_id()

<?php
session_start();

$old_sessionid = session_id();

session_regenerate_id();

$new_sessionid = session_id();

echo "Stara sesja: $old_sessionid<br />";
echo "Nowa sesja: $new_sessionid<br />";

print_r($_SESSION);
?>

Zobacz też:

  • session_id() - Pobierz i/lub ustaw identyfikator bieżącej sesji
  • session_start() - Inicjalizuj dane sesji
  • session_name() - Pobierz i/lub ustaw nazwę bieżącej sesji

session_name
session_register_shutdown
Session Funkcje


Session shutdown function

session_regenerate_id
session_register
Session Funkcje
PHP Manual

session_register_shutdown

(PHP >=5.4.0)

session_register_shutdown — Session shutdown function

Opis

void session_register_shutdown ( void )

Registers session_write_close() as a shutdown function.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Emits E_WARNING if registering the shutdown function fails.

session_regenerate_id
session_register
Session Funkcje


Zarejestruj jedną lub więcej zmiennych globalnych w bieżącej sesji

session_register_shutdown
session_save_path
Session Funkcje
PHP Manual

session_register

(PHP 4, PHP 5)

session_register — Zarejestruj jedną lub więcej zmiennych globalnych w bieżącej sesji

Opis

bool session_register ( mixed $nazwa [, mixed $... ] )

session_register() jest funkcją o zmiennej liczbie argumentów, z których każdy może być albo stringiem zawierającym nazwę zmiennej lub tablicą zawierającą nazwy zmiennych lub inne tablice. Dla każdej napotkanej nazwy zmiennej, session_register() rejestruje w bieżącej sesji globalną zmienną o danej nazwie.

Uwaga

Jeśli skrypt ma działać niezależnie od ustawienia register_globals, niezbędne jest użycie tablicy $_SESSION, jako że elementy $_SESSION są atomatycznie rejestrowane. Jeśli skrypt korzysta z session_register(), nie będzie on działać w środowisku z wyłączoną dyrektywą register_globals.

Informacja: register_globals: ważna uwaga

Od PHP 4.2.0 domyślną wartością dyrektywy register_globals jest off. Społeczność PHP zaleca programistom, aby nie stosowali tej dyrektywy, i zamiast niej używali innych sposobów, takich jak superglobals.

Uwaga

Funkcja ta rejestruje globalną zmienną. Jeśli zachodzi konieczność zarejestrowania zmiennej sesyjnej z wnętrza funkcji, należy uczynić ją globalną poprzez użycie instrukcji global, przez tablicę $GLOBALS[] lub prez użycie specjalnych tablic opisanych poniżej.

Uwaga

Przy korzystaniu z tablicy $_SESSION
(lub $HTTP_SESSION_VARS) nie nalezy korzystać z
funkcji session_register(),
session_is_registered() i
session_unregister().

Funkcja ta zwraca wartość TRUE jeśli wszystkie zmienne zostały pomyślnie zarejestrowane w sesji.

Jeśli przed wywołaniem tej funkcji nie wywołano session_start(), dokonane zostanie niejawne wywołanie session_start() bez żadnych parametrów. Tablica $_SESSION nie naśladuje tego zachowania i wymaga wywołania session_start() przed korzystaniem z niej.

Możesz tworzyć zmienne sesyjne po prostu przez dopisywanie odpowiednich wpisów do tablic $_SESSION lub $HTTP_SESSION_VARS (PHP < 4.1.0).

<?php
// Nie powinno się już używać session_register()
$barney = "Duży fioletowy dinozaur.";
session_register("barney");

// Od PHP 4.1.0 Preferowane jest użycie $_SESSION
$_SESSION["zim"] = "Najeźdźca z innej planety.";

// Stara metoda opiera się o $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "Ma kwadratowe spodnie.";
?>

Informacja:

W chwili obecnej niemożliwe jest zarejestrowanie w sesji zmiennych zawierających zasoby. Na przykład, nie możesz stworzyć połączenia do bazy danych i zachować identyfikator połączenia jako zmienną sesyjną i oczekować, że połączenie ciągle będzie aktywne po odtworzeniu danych sesji. Funkcję PHP, która zwraca zasoby, identyfikuje się przez zwracanie typu resource w definicji funkcji. Listę funkcji, które zwracają zasoby, można znaleźć w załączniku typy zasobów.

Jeśli użyta jest tablica $_SESSION (lub $HTTP_SESSION_VARS dla PHP 4.0.6 i starszych), przypisz vartość do $_SESSION, na przykład $_SESSION['var'] = 'ABC';

Patrz także: session_is_registered(), session_unregister() i $_SESSION.

session_register_shutdown
session_save_path
Session Funkcje


Pobierz i/lub ustaw ścieżkę zapisu bieżącej sesji

session_register
session_set_cookie_params
Session Funkcje
PHP Manual

session_save_path

(PHP 4, PHP 5)

session_save_path — Pobierz i/lub ustaw ścieżkę zapisu bieżącej sesji

Opis

string session_save_path ([ string $ścieżka ] )

session_save_path() zwraca ścieżkę do katalogu, który aktualnie jest używany do zapisu danych sesji. Jeśli podany został parametr ścieżka, zmieniona zostanie ścieżka zapisu danych. W tym celu funkcja session_save_path() musi być wywołana przed session_start().

Informacja:

Na niektórych systemach operacyjnych możesz chciać podać ścieżkę do systemu plików, który lepiej obsługuje duże ilości małych plików. Na przykład na Linuksie reiserfs w takich warunkach ma lepszą wydajność niż ext2fs.

Zobacz także opis dyrektywy konfiguracji session.save_path.

session_register
session_set_cookie_params
Session Funkcje


Ustaw parametry ciasteczka sesyjnego

session_save_path
session_set_save_handler
Session Funkcje
PHP Manual

session_set_cookie_params

(PHP 4, PHP 5)

session_set_cookie_params — Ustaw parametry ciasteczka sesyjnego

Opis

void session_set_cookie_params ( int $czas_życia [, string $ścieżka [, string $domena [, bool $bezpieczne ]]] )

Ustaw parametry ciasteczka pierwotnie zdefiniowane w pliku php.ini. Efekt działania tej funkcji widoczny jest tylko do końca działania skryptu. W związku z tym, niezbędne jest wywołanie session_set_cookie_params() dla każdego żądania pobrania strony, przed wywołaniem session_start().

Informacja:

Parametr bezpieczne został dodany w PHP 4.0.4.

Zobacz także opisy dyrektyw konfiguracyjnych session.cookie_lifetime, session.cookie_path, session.cookie_domain, session.cookie_secure i session_get_cookie_params().

session_save_path
session_set_save_handler
Session Funkcje


Ustawia funkcje użytkownika do przechowywania sesji

session_set_cookie_params
session_start
Session Funkcje
PHP Manual

session_set_save_handler

(PHP 4, PHP 5)

session_set_save_handler — Ustawia funkcje użytkownika do przechowywania sesji

Opis

bool session_set_save_handler ( callback $otwórz , callback $zamknij , callback $czytaj , callback $zapisz , callback $niszcz , callback $gc )

session_set_save_handler() ustawia funkcje użytkownika do obsługi przechowywania sesji, które używane sa do zapisywania i odtwarzania danych skojarzonych z sesją. Jest to bardzo przydatne jeśli preferowany jest sposób przechowywania sesji inny niż ten, który jest dostarczany z PHP, np. przechowywanie danych sesji w lokalnej bazie danych. Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja:

Procedura obsługi "zapisz" nie będzie wywołana dopóki strumień wyjściowy jest otwarty. W związku z tym, wyjście instrukcji debugowania zawartych w procedurze "zapisz" nigdy nie będzie widoczne w oknie przeglądarki. Jeśli konieczne jest wyjście debugowania, sugerowane jest zapisanie tego wyjścia do pliku.

Poniższy przykład opisuje metodę przechowywania danych sesyjnych w plikach, podobną do tej obsługiwanej wewnętrznie przez PHP. Przykład ten może być łatwo rozszerzony aby móc użyć go z twoją ulubioną bazą danych obsługiwaną przez PHP.

Funkcja czytająca zawsze musi zwracać ciąg aby procedura obsługi działała zgodnie z przewidywaniami. Zwróć pusty ciąg jeśli nie ma żadnych danych do odczytania. Wartości zwracane przez inne procedury obsługi są konwertowane na wyrażenia logiczne. TRUE dla sukcesu, FALSE dla niepowodzenia.

Ostrzeżenie

Od wersji PHP 5.0.5, funkcje obsługi zapisu i zamykania wywoływane są po zniszczeniu obiektów. W związku z tym, destruktory mogą używać sesji, ale nie mogą używać obiektów. W wersjach wcześniejszych, wywoływane były w odwrotnej koljeności. Możliwe jest wywołanie session_write_close() z destruktora aby rozwiązać ten problem kury i jajka.

Przykład #1 Przykład session_set_save_handler()

<?php

function open ($save_path, $session_name)
{
  global $sess_save_path, $sess_session_name;

  $sess_save_path = $save_path;
  $sess_session_name = $session_name;
  return(true);
}

function close()
{
  return(true);
}

function read ($id)
{
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "r")) {
    $sess_data = fread($fp, filesize($sess_file));
    return($sess_data);
  } else {
  return(""); // Zawsze musi zwracać ""
  }

}

function write ($id, $sess_data)
{
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
    return(fwrite($fp, $sess_data));
  } else {
    return(false);
  }

}

function destroy ($id)
{
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  return(@unlink($sess_file));
}

/*********************************************
 * UWAGA: Musisz sam zaimplementować obsługę *
 * zbierania śmieci (gc)                     *
 *********************************************/
 function gc ($maxlifetime)
 {
  return true;
}

session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");

session_start();

// dalej normalnie używaj sesji

?>

Zobacz także opis dyrektywy konfiguracji session.save_handler.

session_set_cookie_params
session_start
Session Funkcje


Inicjalizuj dane sesji

session_set_save_handler
session_status
Session Funkcje
PHP Manual

session_start

(PHP 4, PHP 5)

session_start — Inicjalizuj dane sesji

Opis

bool session_start ( void )

session_start() tworzy sesję lub wznawia bieżącą na podstawie aktualnego identyfikatora sesji przekazanego przy wywołaniu, poprzez metodę GET, POST lub ciasteczko.

Jeśli chcesz, aby sesja była nazwana, przed wywołaniem session_start() musisz wywołać session_name().

Ta funkcja zawsze zwraca wartość TRUE.

Informacja:

Jeśli używasz sesji opartych o ciasteczka, to session_start() musi być wywołane przed wysłaniem jakichkolwiek danych do przeglądarki.

Przykład #1 Przykład sesji: page1.php

<?php
// page1.php

session_start();

echo 'Witaj na stronie #1';

$_SESSION['kolor']     = 'zielony';
$_SESSION['zwierze']   = 'kot';
$_SESSION['czas']      = time();

// Działa jeśli ciasteczko sesyjne zostało zaakceptowane
echo '<br /><a href="page2.php">strona 2</a>';

// Lub może przekaż ciasteczko sesyjne, jeśli to konieczne
echo '<br /><a href="page2.php?' . SID . '">strona 2</a>';
?>

Po odwiedzeniu strony page1.php, druga strona, page2.php będzie magicznie zawierała dane sesji. W rozdziale Sesje znajduje się więcej informacji na temat propagowania identyfikatora sesji, gdzie można znaleźć na przykład wytłumaczenie co zawiera stała SID.

Przykład #2 Przykład sesji: page2.php

<?php
// page2.php

session_start();

echo 'Witaj na stronie #2<br />';

echo $_SESSION['kolor']; // zielony
echo $_SESSION['zwierze'];   // not
echo date('Y m d H:i:s', $_SESSION['time']);

// Tu można wstawić SID, podobnie jak to był na page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

W celu stworzenia nazwanej sesji, niezbędne jest wywołanie funkcji session_name() przed wywołaniem session_start().

session_start() zarejestruje wewnętrzny uchwyt obsługi wyjścia dla przepisywania URLi jeśli włączona jest opcja trans-sid. Jeśli użytkownik używa ob_gzhandler lub podobne z ob_start(), kolejność uchwytów obsługi wyjścia jest ważna dla prawidłowego wyjścia. Na przykład, użytkownik musi zarejestrować ob_gzhandler przed rozpoczęciem sesji.

Informacja: Wskazane jest użycie zlib.output_compression zamiast ob_gzhandler

Informacja:

Od PHP 4.3.3, wywołanie session_start() podczas gdy sesja już została rozpoczęta, spowoduje błąd poziomu E_NOTICE. Drugie rozpoczęcie sesji zostanie zignorowane.

Patrz także: $_SESSION, session.auto_start i session_id().

session_set_save_handler
session_status
Session Funkcje


Returns the current session status

session_start
session_unregister
Session Funkcje
PHP Manual

session_status

(PHP >=5.4.0)

session_status — Returns the current session status

Opis

int session_status ( void )

session_status() is used to return the current session status.

Zwracane wartości

  • PHP_SESSION_DISABLED if sessions are disabled.
  • PHP_SESSION_NONE if sessions are enabled, but none exists.
  • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

Zobacz też:

  • session_start() - Inicjalizuj dane sesji
session_start
session_unregister
Session Funkcje


Wyrejestruj zmienną globalną z bieżącej sesji

session_status
session_unset
Session Funkcje
PHP Manual

session_unregister

(PHP 4, PHP 5)

session_unregister — Wyrejestruj zmienną globalną z bieżącej sesji

Opis

bool session_unregister ( string $nazwa )

session_unregister() wyrejestrowuje globalną zmienną o nazwie nazwa z bieżącej sesji.

Funkcja ta zwraca wartość TRUE jeśli zmienna została pomyślnie wyrejestrowana z sesji.

Informacja:

Jeśli użyta została tablica $_SESSION (lub $HTTP_SESSION_VARS dla PHP 4.0.6 i starszych), użyj unset() aby wyrejestrować zmienną z sesji. Nie należy usuwać całej zmiennej $_SESSION poprzez wywołanie unset($_SESSION), ponieważ uniemożliwi to rejestrację zmiennych sesyjnych poprzez zmienną superglobalną $_SESSION.

Uwaga

Ta funkcja nie usuwa zmiennej globalnej o nazwie nazwa, a jedynie zapobiega zapisaniu tej zmiennej jako części sesji. Jeśli chcesz usunąć odpowiednią zmienną globalną, musisz użyć funkcji unset().

Uwaga

Jeśli używasz
$_SESSION (lub $HTTP_SESSION_VARS),
nie używaj session_register(),
session_is_registered() i
session_unregister().

session_status
session_unset
Session Funkcje


Zwolnij wszystkie zmienne sesyjne

session_unregister
session_write_close
Session Funkcje
PHP Manual

session_unset

(PHP 4, PHP 5)

session_unset — Zwolnij wszystkie zmienne sesyjne

Opis

void session_unset ( void )

Funkcja session_unset() zwalnia wszystkie zmienne sesyjne, które są aktualnie zarejestrowane.

Informacja:

Jeśli użyta została tablica $_SESSION (lub $HTTP_SESSION_VARS dla PHP 4.0.6 i starszych), aby wyrejestrować zmienną z sesji należy użyć unset(), na przykład unset ($_SESSION['varname']);.

Uwaga

Nie należy usuwać całej zmiennej $_SESSION poprzez wywołanie unset($_SESSION), ponieważ uniemożliwi to rejestrację zmiennych sesyjnych poprzez zmienną superglobalną $_SESSION.

session_unregister
session_write_close
Session Funkcje


Zapisz dane i zakończ sesję

session_unset
SessionHandler
Session Funkcje
PHP Manual

session_write_close

(PHP 4 >= 4.0.4, PHP 5)

session_write_close — Zapisz dane i zakończ sesję

Opis

void session_write_close ( void )

Zakończ bieżącą sesję i zachowaj dane sesji.

Dane sesji są zazwyczaj przechowywane do czasu zakończenie działania skryptu bez konieczności wywołania session_write_close (), ale ponieważ dane sesji są blokowane w celu zapobieżenia równoległym zapisom, tylko jeden skrypt może operować na sesji w danej chwili. Używając ramek HTMLowych razem z sesjami napotkasz problemy związane z jednoczesnym korzystaniem z jednej sesji przez kilka skryptów. Możesz zmniejszyć czas niezbędny do wczytania wszystkich ramek przez kończenie sesji jak tylko wykonane są wszystkie zmiany w zmiennych sesyjnych.

session_unset
SessionHandler
Session Funkcje


The SessionHandler class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

SessionHandler {
/* Metody */
public int close ( void )
public int destroy ( string $sessionid )
public int gc ( int $maxlifetime )
public int open ( string $save_path , string $sessionid )
public string read ( string $sessionid )
public int write ( string $sessionid , string $sessiondata )
}

Spis treści

  • SessionHandler::close — Close the session
  • SessionHandler::destroy — Destroy a session
  • SessionHandler::gc — Cleanup old sessions
  • SessionHandler::open — Initialize session
  • SessionHandler::read — Read session data
  • SessionHandler::write — The write purpose
session_write_close
SessionHandler::close
Sessions


Close the session

SessionHandler
SessionHandler::destroy
SessionHandler
PHP Manual

SessionHandler::close

(PHP 5 >= 5.4.0)

SessionHandler::close — Close the session

Opis

public int SessionHandler::close ( void )

Closes the current session. This function is automaticaly executed when closing the session, or explicitly via session_write_close().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The return value of the session storage (usually 0 on success, 1 on failure).

SessionHandler
SessionHandler::destroy
SessionHandler


Destroy a session

SessionHandler::close
SessionHandler::gc
SessionHandler
PHP Manual

SessionHandler::destroy

(PHP 5 >= 5.4.0)

SessionHandler::destroy — Destroy a session

Opis

public int SessionHandler::destroy ( string $sessionid )

Destroys a session. Called by session_regenerate_id(), session_destroy() and when session_decode() fails.

Parametry

sessionid

The session ID being destroyed.

Zwracane wartości

The return value of the session storage (usually 0 on success, 1 on failure).

SessionHandler::close
SessionHandler::gc
SessionHandler


Cleanup old sessions

SessionHandler::destroy
SessionHandler::open
SessionHandler
PHP Manual

SessionHandler::gc

(PHP 5 >= 5.4.0)

SessionHandler::gc — Cleanup old sessions

Opis

public int SessionHandler::gc ( int $maxlifetime )

Cleans up expired sessions. Called by session_start(), based on session.gc_divisor and session.gc_probability settings.

Parametry

maxlifetime

Sessions that have not updated for the last maxlifetime seconds will be removed.

Zwracane wartości

The return value of the session storage (usually 0 on success, 1 on failure).

SessionHandler::destroy
SessionHandler::open
SessionHandler


Initialize session

SessionHandler::gc
SessionHandler::read
SessionHandler
PHP Manual

SessionHandler::open

(PHP 5 >= 5.4.0)

SessionHandler::open — Initialize session

Opis

public int SessionHandler::open ( string $save_path , string $sessionid )

Re-initialize existing session, or creates a new one. Called from session_start().

Parametry

save_path

The path where to store/retrieve the session.

sessionid

The session id.

Zwracane wartości

The return value of the session storage (usually 0 on success, 1 on failure).

SessionHandler::gc
SessionHandler::read
SessionHandler


Read session data

SessionHandler::open
SessionHandler::write
SessionHandler
PHP Manual

SessionHandler::read

(PHP 5 >= 5.4.0)

SessionHandler::read — Read session data

Opis

public string SessionHandler::read ( string $sessionid )

Reads the session data from the session storage, and returns the results. Called right after session_start().

Parametry

sessionid

The session id to read data for.

Zwracane wartości

Returns the read data.

SessionHandler::open
SessionHandler::write
SessionHandler


The write purpose

SessionHandler::read
Session PgSQL
SessionHandler
PHP Manual

SessionHandler::write

(PHP 5 >= 5.4.0)

SessionHandler::write — The write purpose

Opis

public int SessionHandler::write ( string $sessionid , string $sessiondata )

Writes the session data to the session storage. Called by session_write_close(), when session_register_shutdown() fails, and during request shutdown.

Parametry

sessionid

The session id.

val

The (session_encode()d) session data.

Zwracane wartości

The return value of the session storage (usually 0 on success, 1 on failure).

SessionHandler::read
Session PgSQL
SessionHandler


PostgreSQL Session Save Handler

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Table definitions
  • Stałe predefiniowane
  • Session PgSQL Funkcje
    • session_pgsql_add_error — Increments error counts and sets last error message
    • session_pgsql_get_error — Returns number of errors and last error message
    • session_pgsql_get_field — Get custom field value
    • session_pgsql_reset — Reset connection to session database servers
    • session_pgsql_set_field — Set custom field value
    • session_pgsql_status — Get current save handler status
SessionHandler::write
Wstęp
Rozszerzenia sesji


Wstęp

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

This module provides an additional session save handler for the session module using » PostgreSQL as a storage system. A user-level session storage function may also be used - session_set_save_handler(), but this module is written in C and therefore could be twice as fast, compared to a session save handler written in PHP.

Session PgSQL is designed to scale any size of web sites and offers some advanced features:

  • session tables are created automatically
  • automatic session table vacuum
  • better garbage collection
  • multiple PostgreSQL servers support
  • automatic database server failover (switching)
  • automatic database server load balancing if there are multiple PostgreSQL servers.
  • short circuit UPDATE

Session PgSQL
Instalacja/Konfiguracja
Session PgSQL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Session PgSQL


Wymagania

You need at least PHP >= 4.3.0, and PostgreSQL >=7.2.0 as database server. libpq that comes with PostgreSQL 7.2.0 or later (and header files to build) and » libmm (and header files).

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/session_pgsql.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

PostgreSQL session save handler is still under development. Refer to the README file in the source distribution for configuration details.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
Table definitions
Instalacja/Konfiguracja


Table definitions

Session table definition

CREATE TABLE php_session (
 sess_id            text,
 sess_name          text,
 sess_data          text,
 sess_created       integer,
 sess_modified      integer,
 sess_expire        integer,
 sess_addr_created  text,
 sess_addr_modified text,
 sess_counter       integer,
 sess_error         integer,
 sess_warning       integer,
 sess_notice        integer,
 sess_err_message   text,
 sess_custom        text
);

CREATE INDEX php_session_idx ON php_session USING BTREE (sess_id);

Ostrzeżenie

If you use HASH for INDEX, you'll have a deadlock problem when the server load is very high. Even if it's unlikely to have a deadlock under normal operation, it can occur. Do not use HASH for INDEX.

You may change the session table as long as all fields are defined.

Application variables table definition

CREATE TABLE php_app_vars (
 app_modified       integer,
 app_name           text,
 app_vars           text
);

Typy zasobów
Stałe predefiniowane
Session PgSQL


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Table definitions
Session PgSQL Funkcje
Session PgSQL


Session PgSQL Funkcje

Contact Information

I have at the moment not very much time to further develop this extension. I will implement more and more features in the near future.

If you have comments, bug fixes, enhancements or want to help developing this, you can drop me a mail at » yohgaki@php.net. Any help is very welcome.

Spis treści

  • session_pgsql_add_error — Increments error counts and sets last error message
  • session_pgsql_get_error — Returns number of errors and last error message
  • session_pgsql_get_field — Get custom field value
  • session_pgsql_reset — Reset connection to session database servers
  • session_pgsql_set_field — Set custom field value
  • session_pgsql_status — Get current save handler status
Stałe predefiniowane
session_pgsql_add_error
Session PgSQL


Increments error counts and sets last error message

Session PgSQL Funkcje
session_pgsql_get_error
Session PgSQL Funkcje
PHP Manual

session_pgsql_add_error

(PECL session_pgsql SVN)

session_pgsql_add_error — Increments error counts and sets last error message

Opis

bool session_pgsql_add_error ( int $error_level [, string $error_message ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

error_level

error_message

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • session_pgsql_get_error() - Returns number of errors and last error message

Session PgSQL Funkcje
session_pgsql_get_error
Session PgSQL Funkcje


Returns number of errors and last error message

session_pgsql_add_error
session_pgsql_get_field
Session PgSQL Funkcje
PHP Manual

session_pgsql_get_error

(PECL session_pgsql SVN)

session_pgsql_get_error — Returns number of errors and last error message

Opis

array session_pgsql_get_error ([ bool $with_error_message = false ] )

Get the number of errors and optional the error messages.

Parametry

with_error_message

Set to TRUE the literal error message for each error is also returned.

Zwracane wartości

The number of errors are returned as array.

Zobacz też:

  • session_pgsql_add_error() - Increments error counts and sets last error message

session_pgsql_add_error
session_pgsql_get_field
Session PgSQL Funkcje


Get custom field value

session_pgsql_get_error
session_pgsql_reset
Session PgSQL Funkcje
PHP Manual

session_pgsql_get_field

(PECL session_pgsql SVN)

session_pgsql_get_field — Get custom field value

Opis

string session_pgsql_get_field ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Zobacz też:

  • session_pgsql_set_field() - Set custom field value

session_pgsql_get_error
session_pgsql_reset
Session PgSQL Funkcje


Reset connection to session database servers

session_pgsql_get_field
session_pgsql_set_field
Session PgSQL Funkcje
PHP Manual

session_pgsql_reset

(PECL session_pgsql SVN)

session_pgsql_reset — Reset connection to session database servers

Opis

bool session_pgsql_reset ( void )

Reset the connection to the session database servers.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

session_pgsql_get_field
session_pgsql_set_field
Session PgSQL Funkcje


Set custom field value

session_pgsql_reset
session_pgsql_status
Session PgSQL Funkcje
PHP Manual

session_pgsql_set_field

(PECL session_pgsql SVN)

session_pgsql_set_field — Set custom field value

Opis

bool session_pgsql_set_field ( string $value )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

value

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • session_pgsql_get_field() - Get custom field value

session_pgsql_reset
session_pgsql_status
Session PgSQL Funkcje


Get current save handler status

session_pgsql_set_field
Przetwarzanie tekstu
Session PgSQL Funkcje
PHP Manual

session_pgsql_status

(PECL session_pgsql SVN)

session_pgsql_status — Get current save handler status

Opis

array session_pgsql_status ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

session_pgsql_set_field
Przetwarzanie tekstu
Session PgSQL Funkcje


Przetwarzanie tekstu

  • BBCode — Funkcje BBCode
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje BBCode
  • PCRE — Regular Expressions (Perl-Compatible)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • PCRE Patterns
    • PCRE Funkcje
  • POSIX Regex — Regular Expression (POSIX Extended)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • POSIX Regex Funkcje
  • ssdeep — ssdeep Fuzzy Hashing
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • ssdeep Funkcje
  • Strings
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • String Funkcje
session_pgsql_status
BBCode
Opis funkcji


Funkcje BBCode

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje BBCode
    • bbcode_add_element — Adds a bbcode element
    • bbcode_add_smiley — Adds a smiley to the parser
    • bbcode_create — Create a BBCode Resource
    • bbcode_destroy — Close BBCode_container resource
    • bbcode_parse — Parse a string following a given rule set
    • bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing
    • bbcode_set_flags — Set or alter parser options
Przetwarzanie tekstu
Wstęp
Przetwarzanie tekstu


Wstęp

Zadaniem tego rozszerzenia jest pomoc w przetwarzaniu tekstu BBCode w celu przekształcania go na HTML lub inne języki znaczników. Używa ono jednego przebiegu przetwarzania i zapewnia znaczną poprawę szybkości, niż przy zwykłej metodzie opartej na wyrażeniach regularnych. Co więcej, pomaga dostarczać prawidłowy kod HTML poprzez uporządkowanie otwierających / zamykających i automatycznie zamykanie niedomkniętych znaczników.

Od wersji 0.10.1 obsługuje parametr cytowania za pomocą cudzysłowu pojedyńczego, cudzysłowu podwójnego, i cudzysłowu prostego HTML.

BBCode
Instalacja/Konfiguracja
BBCode


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
BBCode


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/bbcode

Alternatywnym rozwiązaniem jest napisany w PHP pakiet PEAR » HTML_BBCodeParser.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

W rozszerzeniu BBCode używany jest jeden zasób: BBCode_Container zwracany przez bbcode_create().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

BBCODE_TYPE_NOARG (integer)
This BBCode tag does not accept any arguments.
BBCODE_TYPE_SINGLE (integer)
This BBCode tag does not have a corresponding close tag.
BBCODE_TYPE_ARG (integer)
This BBCode tag need an argument.
BBCODE_TYPE_OPTARG (integer)
This BBCode tag accept an optional argument.
BBCODE_TYPE_ROOT (integer)
This BBCode tag is the special tag root (nesting level 0).
BBCODE_FLAGS_ARG_PARSING (integer)
This BBCode tag require argument sub-parsing (the argument is also parsed by the BBCode extension). As Of 0.10.2 another parser can be used as argument parser.
BBCODE_FLAGS_CDATA_NOT_ALLOWED (integer)
This BBCode Tag does not accept content (it voids it automatically).
BBCODE_FLAGS_SMILEYS_ON (integer) - since 0.10.2
This BBCode Tag accepts smileys.
BBCODE_FLAGS_SMILEYS_OFF (integer) - since 0.10.2
This BBCode Tag does not accept smileys.
BBCODE_FLAGS_ONE_OPEN_PER_LEVEL (integer) - since 0.10.2
This BBCode Tag automatically closes if another tag of the same type is found at the same nesting level.
BBCODE_FLAGS_REMOVE_IF_EMPTY (integer) - since 0.10.2
This BBCode Tag is automatically removed if content is empty it allows to produce lighter HTML.
BBCODE_FLAGS_DENY_REOPEN_CHILD (integer) - since 0.10.3
This BBCode Tag does not allow unclosed children to reopen when automatically closed.
BBCODE_ARG_DOUBLE_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with double quotes (")
BBCODE_ARG_SINGLE_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with single quotes (')
BBCODE_ARG_HTML_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with HTML version of double quotes (&quot;)
BBCODE_ARG_QUOTE_ESCAPING (integer) - since 1.0.2
This is a parser option allowing argument quotes to be escaped this permit the quote delimiter to be found in the string escaping character is \ it can escape any quoting character or itself, if found in front of a non escapable character, it will be dropped. Default behaviour is not to use escaping.
BBCODE_AUTO_CORRECT (integer) - since 0.10.2
This is a parser option changing the way errors are treated. It automatically closes tag in the order they are opened. And treat tags with only an open tag as if there were a close tag present.
BBCODE_CORRECT_REOPEN_TAGS (integer) - since 0.10.2
This is a parser option changing the way errors are treated. It automatically reopens tag if close tags are not in the good order.
BBCODE_DISABLE_TREE_BUILD (integer) - since 0.10.2
This is a parser option disabling the BBCode parsing it can be useful if only the "smiley" replacement must be used.
BBCODE_DEFAULT_SMILEYS_ON (integer) - since 0.10.2
This is a parser option setting smileys to ON if no flag is given at tag level.
BBCODE_DEFAULT_SMILEYS_OFF (integer) - since 0.10.2
This is a parser option setting smileys to OFF if no flag is given at tag level.
BBCODE_FORCE_SMILEYS_OFF (integer) - since 0.10.2
This is a parser option disabling completely the smileys parsing.
BBCODE_SMILEYS_CASE_INSENSITIVE (integer) - since 0.10.3
Use a case insensitive Detection for smileys instead of a simple binary search.
BBCODE_SET_FLAGS_SET (integer) - since 0.10.2
This permits to SET the complete flag set on a parser.
BBCODE_SET_FLAGS_ADD (integer) - since 0.10.2
This permits to switch a flag set ON on a parser.
BBCODE_SET_FLAGS_REMOVE (integer) - since 0.10.2
This permits to switch a flag set OFF on a parser.
Typy zasobów
Funkcje BBCode
BBCode


Funkcje BBCode

Spis treści

  • bbcode_add_element — Adds a bbcode element
  • bbcode_add_smiley — Adds a smiley to the parser
  • bbcode_create — Create a BBCode Resource
  • bbcode_destroy — Close BBCode_container resource
  • bbcode_parse — Parse a string following a given rule set
  • bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing
  • bbcode_set_flags — Set or alter parser options
Stałe predefiniowane
bbcode_add_element
BBCode


Adds a bbcode element

Funkcje BBCode
bbcode_add_smiley
Funkcje BBCode
PHP Manual

bbcode_add_element

(PECL bbcode >= 0.9.0)

bbcode_add_element — Adds a bbcode element

Opis

bool bbcode_add_element ( resource $bbcode_container , string $tag_name , array $tag_rules )

Adds a tag to an existing BBCode_Container tag_set using tag_rules.

Parametry

bbcode_container

BBCode_Container resource, returned by bbcode_create().

tag_name

The new tag to add to the BBCode_Container tag_set.

tag_rules

An associative array containing the parsing rules; see bbcode_create() for the available keys.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Funkcje BBCode
bbcode_add_smiley
Funkcje BBCode


Adds a smiley to the parser

bbcode_add_element
bbcode_create
Funkcje BBCode
PHP Manual

bbcode_add_smiley

(PECL bbcode >= 0.10.2)

bbcode_add_smiley — Adds a smiley to the parser

Opis

bool bbcode_add_smiley ( resource $bbcode_container , string $smiley , string $replace_by )

Adds a smiley to the parser

Parametry

bbcode_container

BBCode_Container resource, returned by bbcode_create().

smiley

The string that will be replaced when found.

replace_by

The string that replace smiley when found.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bbcode_add_smiley() usage example

<?php
/*
 * Prepare the rule set
 */
$arrayBBCode=array(
    ''=>         array('type'=>BBCODE_TYPE_ROOT,
                       'childs'=>'!i'),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>',
                       'close_tag'=>'</b>'),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>',
                       'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>',
                       'close_tag'=>'</i>',
                       'childs'=>'b'),
);
/*
 * Parsed Text
 */
$text=<<<EOF
[i] No parse Test [/i] :)
[b] Parsed, with smiley :( [/b]
[u] Parsed, with no smiley :D [/u]
EOF;
/*
 * Init the parser
 */
$BBHandler=bbcode_create($arrayBBCode);
/*
 * Add Smiley rules to parser
 */
bbcode_add_smiley($BBHandler, ":)", "<img src=\"smiley.gif\" alt=\":)\" />");
bbcode_add_smiley($BBHandler, ":(", "<img src=\"sad.gif\" alt=\":(\" />");
bbcode_add_smiley($BBHandler, ":D", "<img src=\"happy.gif\" alt=\":D\" />");
bbcode_add_smiley($BBHandler, ":p", "<img src=\"tong.gif\" alt=\":p\" />");
bbcode_add_smiley($BBHandler, ":|", "<img src=\"special.gif\" alt=\":|\" />");
bbcode_add_smiley($BBHandler, ":6:", "<img src=\"six.gif\" alt=\":6:\" />");
/*
 * Parse the text
 */
echo bbcode_parse($BBHandler,$text);
?>

Powyższy przykład wyświetli:

<i> No parse Test </i> <img src="smiley.gif" alt=":)" />
<b> Parsed, with smiley <img src="sad.gif" alt=":(" /> </b>
<u> Parsed, with no smiley :D </u>

bbcode_add_element
bbcode_create
Funkcje BBCode


Create a BBCode Resource

bbcode_add_smiley
bbcode_destroy
Funkcje BBCode
PHP Manual

bbcode_create

(PECL bbcode >= 0.9.0)

bbcode_create — Create a BBCode Resource

Opis

resource bbcode_create ([ array $bbcode_initial_tags ] )

This function returns a new BBCode Resource used to parse BBCode strings.

Parametry

bbcode_initial_tags

An associative array containing the tag names as keys and parameters required to correctly parse BBCode as their value. The following key/value pairs are supported:

  • flags optional - a flag set based on the BBCODE_FLAGS_* constants.
  • type required - an int indicating the type of tag. Use the BBCODE_TYPE_* constants.
  • open_tag required - the HTML replacement string for the open tag.
  • close_tag required - the HTML replacement string for the close tag.
  • default_arg optional - use this value as the default argument if none is provided and tag_type is of type OPTARG.
  • content_handling optional - Gives the callback used for modification of the content. Object Oriented Notation supported only since 0.10.1 callback prototype is string name(string $content, string $argument)
  • param_handling optional - Gives the callback used for modification of the argument. Object Oriented Notation supported only since 0.10.1 callback prototype is string name(string $content, string $argument)
  • childs optional - List of accepted children for the tag. The format of the list is a comma separated string. If the list starts with ! it will be the list of rejected children for the tag.
  • parent optional - List of accepted parents for the tag. The format of the list is a comma separated string.

Zwracane wartości

Returns a BBCode_Container

Przykłady

Przykład #1 bbcode_create() example

<?php
$arrayBBCode=array(
    ''=>         array('type'=>BBCODE_TYPE_ROOT,  'childs'=>'!i'),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG, 'open_tag'=>'<i>',
                    'close_tag'=>'</i>', 'childs'=>'b'),
    'url'=>      array('type'=>BBCODE_TYPE_OPTARG,
                    'open_tag'=>'<a href="{PARAM}">', 'close_tag'=>'</a>',
                    'default_arg'=>'{CONTENT}',
                    'childs'=>'b,i'),
    'img'=>      array('type'=>BBCODE_TYPE_NOARG,
                    'open_tag'=>'<img src="', 'close_tag'=>'" />',
                    'childs'=>''),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG, 'open_tag'=>'<b>',
                    'close_tag'=>'</b>'),
);
$text=<<<EOF
[b]Bold Text[/b]
[i]Italic Text[/i]
[url]http://www.php.net/[/url]
[url=http://pecl.php.net/][b]Content Text[/b][/url]
[img]http://static.php.net/www.php.net/images/php.gif[/img]
[url=http://www.php.net/]
[img]http://static.php.net/www.php.net/images/php.gif[/img]
[/url]
EOF;
$BBHandler=bbcode_create($arrayBBCode);
echo bbcode_parse($BBHandler,$text);
?>

Powyższy przykład wyświetli:

<b>Bold Text</b>
[i]Italic Text[/i]
<a href="http://www.php.net/">http://www.php.net/</a>
<a href="http://pecl.php.net/"><b>Content Text</b></a>
<img src="http://static.php.net/www.php.net/images/php.gif" />
<a href="http://www.php.net/">
[img]http://static.php.net/www.php.net/images/php.gif[/img]
</a>

bbcode_add_smiley
bbcode_destroy
Funkcje BBCode


Close BBCode_container resource

bbcode_create
bbcode_parse
Funkcje BBCode
PHP Manual

bbcode_destroy

(PECL bbcode >= 0.9.0)

bbcode_destroy — Close BBCode_container resource

Opis

bool bbcode_destroy ( resource $bbcode_container )

This function closes the resource opened by bbcode_create().

Parametry

bbcode_container

BBCode_Container resource returned by bbcode_create().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

bbcode_create
bbcode_parse
Funkcje BBCode


Parse a string following a given rule set

bbcode_destroy
bbcode_set_arg_parser
Funkcje BBCode
PHP Manual

bbcode_parse

(PECL bbcode >= 0.9.0)

bbcode_parse — Parse a string following a given rule set

Opis

string bbcode_parse ( resource $bbcode_container , string $to_parse )

This function parse the string to_parse following the rules in the bbcode_container created by bbcode_create()

Parametry

bbcode_container

BBCode_Container resource returned by bbcode_create().

to_parse

The string we need to parse.

Zwracane wartości

Returns the parsed string, lub FALSE w przypadku niepowodzenia.

bbcode_destroy
bbcode_set_arg_parser
Funkcje BBCode


Attach another parser in order to use another rule set for argument parsing

bbcode_parse
bbcode_set_flags
Funkcje BBCode
PHP Manual

bbcode_set_arg_parser

(PECL bbcode >= 0.10.2)

bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing

Opis

bool bbcode_set_arg_parser ( resource $bbcode_container , resource $bbcode_arg_parser )

Attaches another parser to the bbcode_container. This parser is used only when arguments must be parsed. If this function is not used, the default argument parser is the parser itself.

Parametry

bbcode_container

BBCode_Container resource, returned by bbcode_create().

bbcode_arg_parser

BBCode_Container resource, returned by bbcode_create(). It will be used only for parsed arguments

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bbcode_set_arg_parser() usage example

<?php
/*
 * Generating bbcode ruleset for main parser
 */
$arrayBBCode=array(
    'quote'=>    array('type'=>BBCODE_TYPE_ARG,
                       'open_tag'=>'<quote><h4>Source: {PARAM}</h4>',
                       'close_tag'=>'</quote>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY|BBCODE_FLAGS_ARG_PARSING),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>', 'close_tag'=>'</b>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF | BBCODE_FLAGS_REMOVE_IF_EMPTY | BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
);
/*
 * Generating bbcode ruleset for argument parser
 */
$arrayBBCode_arg=array(
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b class="sub">', 'close_tag'=>'</b>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF | BBCODE_FLAGS_REMOVE_IF_EMPTY | BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
);
/*
 * Text we are going to parse
 */
$text=<<<EOF
[quote="[b]Test[/b]"]
Foo :)
[/quote]
[b]Bar example :)[/b] :)
EOF;
/*
 * Init the two parsers
 */
$BBHandler=bbcode_create($arrayBBCode);
$BBArgHandler=bbcode_create($arrayBBCode_arg);
/*
 * Setting Flags on the parsers
 */
bbcode_set_flags($BBHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_DEFAULT_SMILEYS_ON|BBCODE_ARG_DOUBLE_QUOTE|
                 BBCODE_ARG_SINGLE_QUOTE|BBCODE_ARG_HTML_QUOTE,BBCODE_SET_FLAGS_SET);
bbcode_set_flags($BBArgHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_DEFAULT_SMILEYS_ON|BBCODE_ARG_DOUBLE_QUOTE|
                 BBCODE_ARG_SINGLE_QUOTE|BBCODE_ARG_HTML_QUOTE,BBCODE_SET_FLAGS_SET);
/*
 * Setting $BBArgHandler as the BBHandler argument parser
 */
bbcode_set_arg_parser($BBHandler,$BBArgHandler);
/*
 * Adding Smileys handling rules to Main parser
 */
bbcode_add_smiley($BBHandler, ":)", "<img src=\"smiley.gif\" alt=\":)\" />");
/*
 * Use the main parser to parse text
 */
echo bbcode_parse($BBHandler,$text);
?>

Powyższy przykład wyświetli:

<quote><h4>Source: <b class="sub">Test</b></h4>
Foo <img src="smiley.gif" alt=":)" />
</quote>
<b>Bar example :)</b> <img src="smiley.gif" alt=":)" />

bbcode_parse
bbcode_set_flags
Funkcje BBCode


Set or alter parser options

bbcode_set_arg_parser
PCRE
Funkcje BBCode
PHP Manual

bbcode_set_flags

(PECL bbcode >= 0.10.2)

bbcode_set_flags — Set or alter parser options

Opis

bool bbcode_set_flags ( resource $bbcode_container , int $flags [, int $mode = BBCODE_SET_FLAGS_SET ] )

Set or alter parser options

Parametry

bbcode_container

BBCode_Container resource, returned by bbcode_create().

flags

The flag set that must be applied to the bbcode_container options

mode

One of the BBCODE_SET_FLAGS_* constant to set, unset a specific flag set or to replace the flag set by flags.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 bbcode_set_flags() usage example

<?php
/*
 * Preparing RuleSet
 */
$arrayBBCode=array(
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>', 'close_tag'=>'</b>'),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>'),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>'),
);
/*
 * Paired incorrectly nested BBCode
 */
$text="[i] Parser [b] Auto Correction [/i] at work [/b]\n";
$BBHandler=bbcode_create($arrayBBCode);
echo bbcode_parse($BBHandler,$text);
// Enabling reopening of automaticaly closed elements
bbcode_set_flags($BBHandler,BBCODE_CORRECT_REOPEN_TAGS,
                 BBCODE_SET_FLAGS_SET);
echo bbcode_parse($BBHandler,$text);

/*
 * Unpaired incorrectly nested BBCode
 */
$text="[i] Parser [b] Auto Correction [/i] at work\n";
echo bbcode_parse($BBHandler,$text);
// Enabling automatic close of pending tags
bbcode_set_flags($BBHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_AUTO_CORRECT,
                 BBCODE_SET_FLAGS_SET);
echo bbcode_parse($BBHandler,$text);
?>

Powyższy przykład wyświetli:

<i> Parser <b> Auto Correction </b></i> at work
<i> Parser <b> Auto Correction </b></i><b> at work </b>
<i> Parser [b] Auto Correction </i> at work
<i> Parser <b> Auto Correction </b></i><b> at work
</b>

bbcode_set_arg_parser
PCRE
Funkcje BBCode


Regular Expressions (Perl-Compatible)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • PCRE Patterns
    • PCRE regex syntax — Pattern Syntax
    • Possible modifiers in regex patterns — Pattern Modifiers
    • Differences From Perl — Perl Differences
    • Differences from POSIX regex
  • PCRE Funkcje
    • preg_filter — Perform a regular expression search and replace
    • preg_grep — Return array entries that match the pattern
    • preg_last_error — Returns the error code of the last PCRE regex execution
    • preg_match_all — Perform a global regular expression match
    • preg_match — Perform a regular expression match
    • preg_quote — Quote regular expression characters
    • preg_replace_callback — Perform a regular expression search and replace using a callback
    • preg_replace — Perform a regular expression search and replace
    • preg_split — Split string by a regular expression
bbcode_set_flags
Wstęp
Przetwarzanie tekstu


Wstęp

The syntax for patterns used in these functions closely resembles Perl. The expression must be enclosed in the delimiters, a forward slash (/), for example. Delimiters can be any non-alphanumeric, non-whitespace ASCII character except the backslash (\) and the null byte. If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style (), {}, [], and <> matching delimiters. See Pattern Syntax for detailed explanation.

The ending delimiter may be followed by various modifiers that affect the matching. See Pattern Modifiers.

PHP also supports regular expressions using a POSIX-extended syntax using the POSIX-extended regex functions.

Informacja:

This extension maintains a global per-thread cache of compiled regular expressions (up to 4096).

Ostrzeżenie

You should be aware of some limitations of PCRE. Read » http://www.pcre.org/pcre.txt for more info.

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5, with just a few differences (see below). The current implementation corresponds to Perl 5.005.

PCRE
Instalacja/Konfiguracja
PCRE


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
PCRE


Instalacja

Beginning with PHP 4.2.0 these functions are enabled by default. You can disable the pcre functions with --without-pcre-regex . Use --with-pcre-regex=DIR to specify DIR where PCRE's include and library files are located, if not using bundled library. For older versions you have to configure and compile PHP with --with-pcre-regex[=DIR] in order to use these functions.

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:

As of PHP 5.3.0 this extension cannot be disabled and is therefore always present.

It is still possible to build against an external PCRE library by using --with-pcre-regex=DIR

PCRE is an active project and as it changes so does the PHP functionality that relies upon it. It is possible that certain parts of the PHP documentation is outdated, in that it may not cover the newest features that PCRE provides. For a list of changes, see the » PCRE library changelog and also the following bundled PCRE history:

Upgrade history of the bundled PCRE library
PHP Wersja | Updated PCRE Wersja | Notes
5.3.6 | 8.11 |
5.3.4 | 8.10 |
5.3.3 | 8.02 |
5.3.2 | 8.00 |
5.3.0 | 7.9 |
5.2.7 | 7.8 |
5.2.6 | 7.6 |
5.2.5 | 7.3 |
5.2.4 | 7.2 |
5.2.2 | 7.0 |
5.2.0 | 6.7 |
5.1.0 | 6.2 |
5.0.5 | 5.0 |
5.0.0 | 4.5 |
4.4.7 | 7.7 |

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

PCRE Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
pcre.backtrack_limit | "1000000" | PHP_INI_ALL | Available since PHP 5.2.0.
pcre.recursion_limit | "100000" | PHP_INI_ALL | Available since PHP 5.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.

pcre.backtrack_limit integer

PCRE's backtracking limit. Defaults to 100000 for PHP < 5.3.7.

pcre.recursion_limit integer

PCRE's recursion limit. Please note that if you set this value to a high number you may consume all the available process stack and eventually crash PHP (due to reaching the stack size limit imposed by the Operating System).

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

PREG constants
constant | description | since
PREG_PATTERN_ORDER | Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. This flag is only used with preg_match_all(). |
PREG_SET_ORDER | Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. This flag is only used with preg_match_all(). |
PREG_OFFSET_CAPTURE | See the description of PREG_SPLIT_OFFSET_CAPTURE. | 4.3.0
PREG_SPLIT_NO_EMPTY | This flag tells preg_split() to return only non-empty pieces. |
PREG_SPLIT_DELIM_CAPTURE | This flag tells preg_split() to capture parenthesized expression in the delimiter pattern as well. | 4.0.5
PREG_SPLIT_OFFSET_CAPTURE | If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return values in an array where every element is an array consisting of the matched string at offset 0 and its string offset within subject at offset 1. This flag is only used for preg_split(). | 4.3.0
PREG_NO_ERROR | Returned by preg_last_error() if there were no errors. | 5.2.0
PREG_INTERNAL_ERROR | Returned by preg_last_error() if there was an internal PCRE error. | 5.2.0
PREG_BACKTRACK_LIMIT_ERROR | Returned by preg_last_error() if backtrack limit was exhausted. | 5.2.0
PREG_RECURSION_LIMIT_ERROR | Returned by preg_last_error() if recursion limit was exhausted. | 5.2.0
PREG_BAD_UTF8_ERROR | Returned by preg_last_error() if the last error was caused by malformed UTF-8 data (only when running a regex in UTF-8 mode). | 5.2.0
PREG_BAD_UTF8_OFFSET_ERROR | Returned by preg_last_error() if the offset didn't correspond to the begin of a valid UTF-8 code point (only when running a regex in UTF-8 mode). | 5.3.0
PCRE_VERSION | PCRE version and release date (e.g. "7.0 18-Dec-2006"). | 5.2.4
Typy zasobów
Przykłady
PCRE


Przykłady

Przykład #1 Examples of valid patterns

  • /<\/\w+>/
  • |(\d{3})-\d+|Sm
  • /^(?i)php[34]/
  • {^\s+(\s+)?$}

Przykład #2 Examples of invalid patterns

  • /href='(.*)' - missing ending delimiter
  • /\w+\s*\w+/J - unknown modifier 'J'
  • 1-\d3-\d3-\d4| - missing starting delimiter

Stałe predefiniowane
PCRE Patterns
PCRE


PCRE Patterns

Spis treści

  • PCRE regex syntax
  • Possible modifiers in regex patterns
  • Differences From Perl
  • Differences from POSIX regex
Przykłady
PCRE regex syntax
PCRE


Pattern Syntax

Spis treści

  • Introduction
  • Delimiters
  • Meta-characters
  • Escape sequences
  • Unicode character properties
  • Anchors
  • Dot
  • Character classes
  • Alternation
  • Internal option setting
  • Subpatterns
  • Repetition
  • Back references
  • Assertions
  • Once-only subpatterns
  • Conditional subpatterns
  • Comments
  • Recursive patterns
  • Performance
PCRE Patterns
Introduction
PCRE Patterns


Introduction

The syntax and semantics of the regular expressions supported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description here is intended as reference documentation.

A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern The quick brown fox matches a portion of a subject string that is identical to itself.

PCRE regex syntax
Delimiters
PCRE regex syntax


Delimiters

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

/foo bar/
#^[^0-9]$#
+php+
%[a-zA-Z0-9_-]%

If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.

/http:\/\//
#http://#
The preg_quote() function may be used to escape a string for injection into a pattern and its optional second parameter may be used to specify the delimiter to be escaped.

In addition to the aforementioned delimiters, it is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively.

{this is a pattern}

You may add pattern modifiers after the ending delimiter. The following is an example of case-insensitive matching:

#[a-z]#i

Introduction
Meta-characters
PCRE regex syntax


Meta-characters

The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of meta-characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

\
general escape character with several uses
^
assert start of subject (or line, in multiline mode)
$
assert end of subject (or line, in multiline mode)
.
match any character except newline (by default)
[
start character class definition
]
end character class definition
|
start of alternative branch
(
start subpattern
)
end subpattern
?
extends the meaning of (, also 0 or 1 quantifier, also makes greedy quantifiers lazy (see repetition)
*
0 or more quantifier
+
1 or more quantifier
{
start min/max quantifier
}
end min/max quantifier
Part of a pattern that is in square brackets is called a "character class". In a character class the only meta-characters are:
\
general escape character
^
negate the class, but only if the first character
-
indicates character range
]
terminates the character class
The following sections describe the use of each of the meta-characters.

Delimiters
Escape sequences
PCRE regex syntax


Escape sequences

The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the following character would otherwise be interpreted as a meta-character, so it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself. In particular, if you want to match a backslash, you write "\\".

Informacja:

Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.

If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.

A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

\a
alarm, that is, the BEL character (hex 07)
\cx
"control-x", where x is any character
\e
escape (hex 1B)
\f
formfeed (hex 0C)
\n
newline (hex 0A)
\p{xx}
a character with the xx property, see unicode properties for more info
\P{xx}
a character without the xx property, see unicode properties for more info
\r
carriage return (hex 0D)
\t
tab (hex 09)
\xhh
character with hex code hh
\ddd
character with octal code ddd, or backreference

The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.

After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, "\x{...}" is allowed, where the contents of the braces is a string of hexadecimal digits. It is interpreted as a UTF-8 character whose code number is the given hexadecimal number. The original hexadecimal escape sequence, \xhh, matches a two-byte UTF-8 character if the value is greater than 127.

After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

\040
is another way of writing a space
\40
is the same, provided there are fewer than 40 previous capturing subpatterns
\7
is always a back reference
\11
might be a back reference, or another way of writing a tab
\011
is always a tab
\0113
is a tab followed by the character "3"
\113
is the character with octal code 113 (since there can be no more than 99 back references)
\377
is a byte consisting entirely of 1 bits
\81
is either a back reference, or a binary zero followed by the two characters "8" and "1"

Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic character types:

\d
any decimal digit
\D
any character that is not a decimal digit
\h
any horizontal whitespace character (since PHP 5.2.4)
\H
any character that is not a horizontal whitespace character (since PHP 5.2.4)
\s
any whitespace character
\S
any character that is not a whitespace character
\v
any vertical whitespace character (since PHP 5.2.4)
\V
any character that is not a vertical whitespace character (since PHP 5.2.4)
\w
any "word" character
\W
any "non-word" character

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

\b
word boundary
\B
not a word boundary
\A
start of subject (independent of multiline mode)
\Z
end of subject or newline at end (independent of multiline mode)
\z
end of subject (independent of multiline mode)
\G
first matching position in subject

These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_MULTILINE or PCRE_DOLLAR_ENDONLY options. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

The \G assertion is true only when the current matching position is at the start point of the match, as specified by the offset argument of preg_match(). It differs from \A when the value of offset is non-zero.

\Q and \E can be used to ignore regexp metacharacters in the pattern. For example: \w+\Q.$.\E$ will match one or more word characters, followed by literals .$. and anchored at the end of the string.

\K can be used to reset the match start since PHP 5.2.4. For example, the pattern foo\Kbar matches "foobar", but reports that it has matched "bar". The use of \K does not interfere with the setting of captured substrings. For example, when the pattern (foo)\Kbar matches "foobar", the first substring is still set to "foo".

Meta-characters
Unicode character properties
PCRE regex syntax


Unicode character properties

Since 5.1.0, three additional escape sequences to match generic character types are available when UTF-8 mode is selected. They are:

\p{xx}
a character with the xx property
\P{xx}
a character without the xx property
\X
an extended Unicode sequence

The property names represented by xx above are limited to the Unicode general category properties. Each character has exactly one such property, specified by a two-letter abbreviation. For compatibility with Perl, negation can be specified by including a circumflex between the opening brace and the property name. For example, \p{^Lu} is the same as \P{Lu}.

If only one letter is specified with \p or \P, it includes all the properties that start with that letter. In this case, in the absence of negation, the curly brackets in the escape sequence are optional; these two examples have the same effect:

\p{L}
\pL

Supported property codes
Property | Matches | Notes
C | Other |
Cc | Control |
Cf | Format |
Cn | Unassigned |
Co | Private use |
Cs | Surrogate |
L | Letter | Includes the following properties: Ll, Lm, Lo, Lt and Lu.
Ll | Lower case letter |
Lm | Modifier letter |
Lo | Other letter |
Lt | Title case letter |
Lu | Upper case letter |
M | Mark |
Mc | Spacing mark |
Me | Enclosing mark |
Mn | Non-spacing mark |
N | Number |
Nd | Decimal number |
Nl | Letter number |
No | Other number |
P | Punctuation |
Pc | Connector punctuation |
Pd | Dash punctuation |
Pe | Close punctuation |
Pf | Final punctuation |
Pi | Initial punctuation |
Po | Other punctuation |
Ps | Open punctuation |
S | Symbol |
Sc | Currency symbol |
Sk | Modifier symbol |
Sm | Mathematical symbol |
So | Other symbol |
Z | Separator |
Zl | Line separator |
Zp | Paragraph separator |
Zs | Space separator |

Extended properties such as "Greek" or "InMusicalSymbols" are not supported by PCRE.

Specifying case-insensitive (caseless) matching does not affect these escape sequences. For example, \p{Lu} always matches only upper case letters.

The \X escape matches any number of Unicode characters that form an extended Unicode sequence. \X is equivalent to (?>\PM\pM*).

That is, it matches a character without the "mark" property, followed by zero or more characters with the "mark" property, and treats the sequence as an atomic group (see below). Characters with the "mark" property are typically accents that affect the preceding character.

Matching characters by Unicode property is not fast, because PCRE has to search a structure that contains data for over fifteen thousand characters. That is why the traditional escape sequences such as \d and \w do not use Unicode properties in PCRE.

Escape sequences
Anchors
PCRE regex syntax


Anchors

Outside a character class, in the default matching mode, the circumflex character (^) is an assertion which is true only if the current matching point is at the start of the subject string. Inside a character class, circumflex (^) has an entirely different meaning (see below).

Circumflex (^) need not be the first character of the pattern if a number of alternatives are involved, but it should be the first thing in each alternative in which it appears if the pattern is ever to match that branch. If all possible alternatives start with a circumflex (^), that is, if the pattern is constrained to match only at the start of the subject, it is said to be an "anchored" pattern. (There are also other constructs that can cause a pattern to be anchored.)

A dollar character ($) is an assertion which is TRUE only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). Dollar ($) need not be the last character of the pattern if a number of alternatives are involved, but it should be the last item in any branch in which it appears. Dollar has no special meaning in a character class.

The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching time. This does not affect the \Z assertion.

The meanings of the circumflex and dollar characters are changed if the PCRE_MULTILINE option is set. When this is the case, they match immediately after and immediately before an internal "\n" character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern /^abc$/ matches the subject string "def\nabc" in multiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode because all branches start with "^" are not anchored in multiline mode. The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set.

Note that the sequences \A, \Z, and \z can be used to match the start and end of the subject in both modes, and if all branches of a pattern start with \A is it always anchored, whether PCRE_MULTILINE is set or not.

Unicode character properties
Dot
PCRE regex syntax


Dot

Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. If the PCRE_DOTALL option is set, then dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class.

\C can be used to match single byte. It makes sense in UTF-8 mode where full stop matches the whole character which can consist of multiple bytes.

Anchors
Character classes
PCRE regex syntax


Character classes

An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash.

A character class matches a single character in the subject; the character must be in the set of characters defined by the class, unless the first character in the class is a circumflex, in which case the subject character must not be in the set defined by the class. If a circumflex is actually required as a member of the class, ensure it is not the first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower case vowel, while [^aeiou] matches any character that is not a lower case vowel. Note that a circumflex is just a convenient notation for specifying the characters which are in the class by enumerating those that are not. It is not an assertion: it still consumes a character from the subject string, and fails if the current pointer is at the end of the string.

When case-insensitive (caseless) matching is set, any letters in a class represent both their upper case and lower case versions, so for example, an insensitive [aeiou] matches "A" as well as "a", and an insensitive [^aeiou] does not match "A", whereas a sensitive (caseful) version would.

The newline character is never treated in any special way in character classes, whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class such as [^a] will always match a newline.

The minus (hyphen) character can be used to specify a range of characters in a character class. For example, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class.

It is not possible to have the literal character "]" as the end character of a range. A pattern such as [W-]46] is interpreted as a class of two characters ("W" and "-") followed by a literal string "46]", so it would match "W46]" or "-46]". However, if the "]" is escaped with a backslash it is interpreted as the end of range, so [W-\]46] is interpreted as a single class containing a range followed by two separate characters. The octal or hexadecimal representation of "]" can also be used to end a range.

Ranges operate in ASCII collating sequence. They can also be used for characters specified numerically, for example [\000-\037]. If a range that includes letters is used when case-insensitive (caseless) matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\^_`wxyzabc], matched case-insensitively, and if character tables for the "fr" locale are in use, [\xc8-\xcb] matches accented E characters in both cases.

The character types \d, \D, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can conveniently be used with the upper case character types to specify a more restricted set of characters than the matching lower case type. For example, the class [^\W_] matches any letter or digit, but not underscore.

All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped. The pattern terminator is always special and must be escaped when used within an expression.

Perl supports the POSIX notation for character classes. This uses names enclosed by [: and :] within the enclosing square brackets. PCRE also supports this notation. For example, [01[:alpha:]%] matches "0", "1", any alphabetic character, or "%". The supported class names are:

Character classes
alnum | letters and digits
alpha | letters
ascii | character codes 0 - 127
blank | space or tab only
cntrl | control characters
digit | decimal digits (same as \d)
graph | printing characters, excluding space
lower | lower case letters
print | printing characters, including space
punct | printing characters, excluding letters and digits
space | white space (not quite the same as \s)
upper | upper case letters
word | "word" characters (same as \w)
xdigit | hexadecimal digits
The space characters are HT (9), LF (10), VT (11), FF (12), CR (13), and space (32). Notice that this list includes the VT character (code 11). This makes "space" different to \s, which does not include VT (for Perl compatibility).

The name word is a Perl extension, and blank is a GNU extension from Perl 5.8. Another Perl extension is negation, which is indicated by a ^ character after the colon. For example, [12[:^digit:]] matches "1", "2", or any non-digit.

In UTF-8 mode, characters with values greater than 128 do not match any of the POSIX character classes.

Dot
Alternation
PCRE regex syntax


Alternation

Vertical bar characters are used to separate alternative patterns. For example, the pattern gilbert|sullivan matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alternative is permitted (matching the empty string). The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern.

Character classes
Internal option setting
PCRE regex syntax


Internal option setting

The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, PCRE_UNGREEDY, PCRE_EXTRA, PCRE_EXTENDED and PCRE_DUPNAMES can be changed from within the pattern by a sequence of Perl option letters enclosed between "(?" and ")". The option letters are:

Internal option letters
i | for PCRE_CASELESS
m | for PCRE_MULTILINE
s | for PCRE_DOTALL
x | for PCRE_EXTENDED
U | for PCRE_UNGREEDY
X | for PCRE_EXTRA
J | for PCRE_INFO_JCHANGED

For example, (?im) sets case-insensitive (caseless), multiline matching. It is also possible to unset these options by preceding the letter with a hyphen, and a combined setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also permitted. If a letter appears both before and after the hyphen, the option is unset.

When an option change occurs at top level (that is, not inside subpattern parentheses), the change applies to the remainder of the pattern that follows. So /ab(?i)c/ matches only "abc" and "abC".

If an option change occurs inside a subpattern, the effect is different. This is a change of behaviour in Perl 5.005. An option change inside a subpattern affects only that part of the subpattern that follows it, so (a(?i)b)c matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used). By this means, options can be made to have different settings in different parts of the pattern. Any changes made in one alternative do carry on into subsequent branches within the same subpattern. For example, (a(?i)b|c) matches "ab", "aB", "c", and "C", even though when matching "C" the first branch is abandoned before the option setting. This is because the effects of option settings happen at compile time. There would be some very weird behaviour otherwise.

The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the same way as the Perl-compatible options by using the characters U and X respectively. The (?X) flag setting is special in that it must always occur earlier in the pattern than any of the additional features it turns on, even when it is at top level. It is best put at the start.

Alternation
Subpatterns
PCRE regex syntax


Subpatterns

Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things:

  1. It localizes a set of alternatives. For example, the pattern cat(aract|erpillar|) matches one of the words "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpillar" or the empty string.

  2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the ovector argument of pcre_exec(). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns.

For example, if the string "the red king" is matched against the pattern the ((red|white) (king|queen)) the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3.

The fact that plain parentheses fulfill two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern the ((?:red|white) (king|queen)) the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of captured substrings is 99, and the maximum number of all subpatterns, both capturing and non-capturing, is 200.

As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns

(?i:saturday|sunday)
(?:(?i)saturday|sunday)

match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday".

It is possible to name a subpattern using the syntax (?P<name>pattern). This subpattern will then be indexed in the matches array by its normal numeric position and also by name. PHP 5.2.2 introduced two alternative syntaxes (?<name>pattern) and (?'name'pattern).

Sometimes it is necessary to have multiple matching, but alternating subgroups in a regular expression. Normally, each of these would be given their own backreference number even though only one of them would ever possibly match. To overcome this, the (?| syntax allows having duplicate numbers. Consider the following regex matched against the string Sunday:

(?:(Sat)ur|(Sun))day

Here Sun is stored in backreference 2, while backreference 1 is empty. Matching yields Sat in backreference 1 while backreference 2 does not exist. Changing the pattern to use the (?| fixes this problem:

(?|(Sat)ur|(Sun))day

Using this pattern, both Sun and Sat would be stored in backreference 1.

Internal option setting
Repetition
PCRE regex syntax


Repetition

Repetition is specified by quantifiers, which can follow any of the following items:

  • a single character, possibly escaped
  • the . metacharacter
  • a character class
  • a back reference (see next section)
  • a parenthesized subpattern (unless it is an assertion - see below)

The general repetition quantifier specifies a minimum and maximum number of permitted matches, by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be less than 65536, and the first must be less than or equal to the second. For example: z{2,4} matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special character. If the second number is omitted, but the comma is present, there is no upper limit; if the second number and the comma are both omitted, the quantifier specifies an exact number of required matches. Thus [aeiou]{3,} matches at least 3 successive vowels, but may match many more, while \d{8} matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier is not allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. For example, {,6} is not a quantifier, but a literal string of four characters.

The quantifier {0} is permitted, causing the expression to behave as if the previous item and the quantifier were not present.

For convenience (and historical compatibility) the three most common quantifiers have single-character abbreviations:

Single-character quantifiers
* | equivalent to {0,}
+ | equivalent to {1,}
? | equivalent to {0,1}

It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example: (a?)*

Earlier versions of Perl and PCRE used to give an error at compile time for such patterns. However, because there are cases where this can be useful, such patterns are now accepted, but if any repetition of the subpattern does in fact match no characters, the loop is forcibly broken.

By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between the sequences /* and */ and within the sequence, individual * and / characters may appear. An attempt to match C comments by applying the pattern /\*.*\*/ to the string /* first comment */ not comment /* second comment */ fails, because it matches the entire string due to the greediness of the .* item.

However, if a quantifier is followed by a question mark, then it becomes lazy, and instead matches the minimum number of times possible, so the pattern /\*.*?\*/ does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in \d??\d which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

If the PCRE_UNGREEDY option is set (an option which is not available in Perl) then the quantifiers are not greedy by default, but individual ones can be made greedy by following them with a question mark. In other words, it inverts the default behaviour.

Quantifiers followed by + are "possessive". They eat as many characters as possible and don't return to match the rest of the pattern. Thus .*abc matches "aabc" but .*+abc doesn't because .*+ eats the whole string. Possessive quantifiers can be used to speed up processing.

When a parenthesized subpattern is quantified with a minimum repeat count that is greater than 1 or with a limited maximum, more store is required for the compiled pattern, in proportion to the size of the minimum or maximum.

If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent to Perl's /s) is set, thus allowing the . to match newlines, then the pattern is implicitly anchored, because whatever follows will be tried against every character position in the subject string, so there is no point in retrying the overall match at any position after the first. PCRE treats such a pattern as though it were preceded by \A. In cases where it is known that the subject string contains no newlines, it is worth setting PCRE_DOTALL when the pattern begins with .* in order to obtain this optimization, or alternatively using ^ to indicate anchoring explicitly.

When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example, after (tweedle[dume]{3}\s*)+ has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee". However, if there are nested capturing subpatterns, the corresponding captured values may have been set in previous iterations. For example, after /(a|(b))+/ matches "aba" the value of the second captured substring is "b".

Subpatterns
Back references
PCRE regex syntax


Back references

Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) is a back reference to a capturing subpattern earlier (i.e. to its left) in the pattern, provided there have been that many previous capturing left parentheses.

However, if the decimal number following the backslash is less than 10, it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pattern. In other words, the parentheses that are referenced need not be to the left of the reference for numbers less than 10. A "forward back reference" can make sense when a repetition is involved and the subpattern to the right has participated in an earlier iteration. See the section entitled "Backslash" above for further details of the handling of digits following a backslash.

A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself. So the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If case-sensitive (caseful) matching is in force at the time of the back reference, then the case of letters is relevant. For example, ((?i)rah)\s+\1 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched case-insensitively (caselessly).

There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, then any back references to it always fail. For example, the pattern (a|(bc))\2 always fails if it starts to match "a" rather than "bc". Because there may be up to 99 back references, all digits following the backslash are taken as part of a potential back reference number. If the pattern continues with a digit character, then some delimiter must be used to terminate the back reference. If the PCRE_EXTENDED option is set, this can be whitespace. Otherwise an empty comment can be used.

A back reference that occurs inside the parentheses to which it refers fails when the subpattern is first used, so, for example, (a\1) never matches. However, such references can be useful inside repeated subpatterns. For example, the pattern (a|b\1)+ matches any number of "a"s and also "aba", "ababba" etc. At each iteration of the subpattern, the back reference matches the character string corresponding to the previous iteration. In order for this to work, the pattern must be such that the first iteration does not need to match the back reference. This can be done using alternation, as in the example above, or by a quantifier with a minimum of zero.

As of PHP 5.2.2, the \g escape sequence can be used for absolute and relative referencing of subpatterns. This escape sequence must be followed by an unsigned number or a negative number, optionally enclosed in braces. The sequences \1, \g1 and \g{1} are synonymous with one another. The use of this pattern with an unsigned number can help remove the ambiguity inherent when using digits following a backslash. The sequence helps to distinguish back references from octal characters and also makes it easier to have a back reference followed by a literal number, e.g. \g{2}1.

The use of the \g sequence with a negative number signifies a relative reference. For example, (foo)(bar)\g{-1} would match the sequence "foobarbar" and (foo)(bar)\g{-2} matches "foobarfoo". This can be useful in long patterns as an alternative to keeping track of the number of subpatterns in order to reference a specific previous subpattern.

Back references to the named subpatterns can be achieved by (?P=name) or, since PHP 5.2.2, also by \k<name> or \k'name'. Additionally PHP 5.2.4 added support for \k{name} and \g{name}.

Repetition
Assertions
PCRE regex syntax


Assertions

An assertion is a test on the characters following or preceding the current matching point that does not actually consume any characters. The simple assertions coded as \b, \B, \A, \Z, \z, ^ and $ are described above. More complicated assertions are coded as subpatterns. There are two kinds: those that look ahead of the current position in the subject string, and those that look behind it.

An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed. Lookahead assertions start with (?= for positive assertions and (?! for negative assertions. For example, \w+(?=;) matches a word followed by a semicolon, but does not include the semicolon in the match, and foo(?!bar) matches any occurrence of "foo" that is not followed by "bar". Note that the apparently similar pattern (?!foo)bar does not find an occurrence of "bar" that is preceded by something other than "foo"; it finds any occurrence of "bar" whatsoever, because the assertion (?!foo) is always TRUE when the next three characters are "bar". A lookbehind assertion is needed to achieve this effect.

Lookbehind assertions start with (?<= for positive assertions and (?<! for negative assertions. For example, (?<!foo)bar does find an occurrence of "bar" that is not preceded by "foo". The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. However, if there are several alternatives, they do not all have to have the same fixed length. Thus (?<=bullock|donkey) is permitted, but (?<!dogs?|cats?) causes an error at compile time. Branches that match different length strings are permitted only at the top level of a lookbehind assertion. This is an extension compared with Perl 5.005, which requires all branches to match the same length of string. An assertion such as (?<=ab(c|de)) is not permitted, because its single top-level branch can match two different lengths, but it is acceptable if rewritten to use two top-level branches: (?<=abc|abde) The implementation of lookbehind assertions is, for each alternative, to temporarily move the current position back by the fixed width and then try to match. If there are insufficient characters before the current position, the match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns can be particularly useful for matching at the ends of strings; an example is given at the end of the section on once-only subpatterns.

Several assertions (of any sort) may occur in succession. For example, (?<=\d{3})(?<!999)foo matches "foo" preceded by three digits that are not "999". Notice that each of the assertions is applied independently at the same point in the subject string. First there is a check that the previous three characters are all digits, then there is a check that the same three characters are not "999". This pattern does not match "foo" preceded by six characters, the first of which are digits and the last three of which are not "999". For example, it doesn't match "123abcfoo". A pattern to do that is (?<=\d{3}...)(?<!999)foo

This time the first assertion looks at the preceding six characters, checking that the first three are digits, and then the second assertion checks that the preceding three characters are not "999".

Assertions can be nested in any combination. For example, (?<=(?<!foo)bar)baz matches an occurrence of "baz" that is preceded by "bar" which in turn is not preceded by "foo", while (?<=\d{3}...(?<!999))foo is another pattern which matches "foo" preceded by three digits and any three characters that are not "999".

Assertion subpatterns are not capturing subpatterns, and may not be repeated, because it makes no sense to assert the same thing several times. If any kind of assertion contains capturing subpatterns within it, these are counted for the purposes of numbering the capturing subpatterns in the whole pattern. However, substring capturing is carried out only for positive assertions, because it does not make sense for negative assertions.

Assertions count towards the maximum of 200 parenthesized subpatterns.

Back references
Once-only subpatterns
PCRE regex syntax


Once-only subpatterns

With both maximizing and minimizing repetition, failure of what follows normally causes the repeated item to be re-evaluated to see if a different number of repeats allows the rest of the pattern to match. Sometimes it is useful to prevent this, either to change the nature of the match, or to cause it fail earlier than it otherwise might, when the author of the pattern knows there is no point in carrying on.

Consider, for example, the pattern \d+foo when applied to the subject line 123456bar

After matching all 6 digits and then failing to match "foo", the normal action of the matcher is to try again with only 5 digits matching the \d+ item, and then with 4, and so on, before ultimately failing. Once-only subpatterns provide the means for specifying that once a portion of the pattern has matched, it is not to be re-evaluated in this way, so the matcher would give up immediately on failing to match "foo" the first time. The notation is another kind of special parenthesis, starting with (?> as in this example: (?>\d+)bar

This kind of parenthesis "locks up" the part of the pattern it contains once it has matched, and a failure further into the pattern is prevented from backtracking into it. Backtracking past it to previous items, however, works as normal.

An alternative description is that a subpattern of this type matches the string of characters that an identical standalone pattern would match, if anchored at the current point in the subject string.

Once-only subpatterns are not capturing subpatterns. Simple cases such as the above example can be thought of as a maximizing repeat that must swallow everything it can. So, while both \d+ and \d+? are prepared to adjust the number of digits they match in order to make the rest of the pattern match, (?>\d+) can only match an entire sequence of digits.

This construction can of course contain arbitrarily complicated subpatterns, and it can be nested.

Once-only subpatterns can be used in conjunction with lookbehind assertions to specify efficient matching at the end of the subject string. Consider a simple pattern such as abcd$ when applied to a long string which does not match. Because matching proceeds from left to right, PCRE will look for each "a" in the subject and then see if what follows matches the rest of the pattern. If the pattern is specified as ^.*abcd$ then the initial .* matches the entire string at first, but when this fails (because there is no following "a"), it backtracks to match all but the last character, then all but the last two characters, and so on. Once again the search for "a" covers the entire string, from right to left, so we are no better off. However, if the pattern is written as ^(?>.*)(?<=abcd) then there can be no backtracking for the .* item; it can match only the entire string. The subsequent lookbehind assertion does a single test on the last four characters. If it fails, the match fails immediately. For long strings, this approach makes a significant difference to the processing time.

When a pattern contains an unlimited repeat inside a subpattern that can itself be repeated an unlimited number of times, the use of a once-only subpattern is the only way to avoid some failing matches taking a very long time indeed. The pattern (\D+|<\d+>)*[!?] matches an unlimited number of substrings that either consist of non-digits, or digits enclosed in <>, followed by either ! or ?. When it matches, it runs quickly. However, if it is applied to aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa it takes a long time before reporting failure. This is because the string can be divided between the two repeats in a large number of ways, and all have to be tried. (The example used [!?] rather than a single character at the end, because both PCRE and Perl have an optimization that allows for fast failure when a single character is used. They remember the last single character that is required for a match, and fail early if it is not present in the string.) If the pattern is changed to ((?>\D+)|<\d+>)*[!?] sequences of non-digits cannot be broken, and failure happens quickly.

Assertions
Conditional subpatterns
PCRE regex syntax


Conditional subpatterns

It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are

(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)

If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs.

There are two kinds of condition. If the text between the parentheses consists of a sequence of digits, then the condition is satisfied if the capturing subpattern of that number has previously matched. Consider the following pattern, which contains non-significant white space to make it more readable (assume the PCRE_EXTENDED option) and to divide it into three parts for ease of discussion: ( \( )? [^()]+ (?(1) \) )

The first part matches an optional opening parenthesis, and if that character is present, sets it as the first captured substring. The second part matches one or more characters that are not parentheses. The third part is a conditional subpattern that tests whether the first set of parentheses matched or not. If they did, that is, if subject started with an opening parenthesis, the condition is TRUE, and so the yes-pattern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, optionally enclosed in parentheses.

If the condition is the string (R), it is satisfied if a recursive call to the pattern or subpattern has been made. At "top level", the condition is false.

If the condition is not a sequence of digits or (R), it must be an assertion. This may be a positive or negative lookahead or lookbehind assertion. Consider this pattern, again containing non-significant white space, and with the two alternatives on the second line:

(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )

The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter. In other words, it tests for the presence of at least one letter in the subject. If a letter is found, the subject is matched against the first alternative; otherwise it is matched against the second. This pattern matches strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.

Once-only subpatterns
Comments
PCRE regex syntax


Comments

The sequence (?# marks the start of a comment which continues up to the next closing parenthesis. Nested parentheses are not permitted. The characters that make up a comment play no part in the pattern matching at all.

If the PCRE_EXTENDED option is set, an unescaped # character outside a character class introduces a comment that continues up to the next newline character in the pattern.

Conditional subpatterns
Recursive patterns
PCRE regex syntax


Recursive patterns

Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an experimental facility that allows regular expressions to recurse (among other things). The special item (?R) is provided for the specific case of recursion. This PCRE pattern solves the parentheses problem (assume the PCRE_EXTENDED option is set so that white space is ignored): \( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (i.e. a correctly parenthesized substring). Finally there is a closing parenthesis.

This particular example pattern contains nested unlimited repeats, and so the use of a once-only subpattern for matching strings of non-parentheses is important when applying the pattern to strings that do not match. For example, when it is applied to (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() it yields "no match" quickly. However, if a once-only subpattern is not used, the match runs for a very long time indeed because there are so many different ways the + and * repeats can carve up the subject, and all have to be tested before failure can be reported.

The values set for any capturing subpatterns are those from the outermost level of the recursion at which the subpattern value is set. If the pattern above is matched against (ab(cd)ef) the value for the capturing parentheses is "ef", which is the last value taken on at the top level. If additional parentheses are added, giving \( ( ( (?>[^()]+) | (?R) )* ) \) then the string they capture is "ab(cd)ef", the contents of the top level parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE has to obtain extra memory to store data during a recursion, which it does by using pcre_malloc, freeing it via pcre_free afterwards. If no memory can be obtained, it saves data for the first 15 capturing parentheses only, as there is no way to give an out-of-memory error from within a recursion.

(?1), (?2) and so on can be used for recursive subpatterns too. It is also possible to use named subpatterns: (?P>name) or (?P&name).

If the syntax for a recursive subpattern reference (either by number or by name) is used outside the parentheses to which it refers, it operates like a subroutine in a programming language. An earlier example pointed out that the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If instead the pattern (sens|respons)e and (?1)ibility is used, it does match "sense and responsibility" as well as the other two strings. Such references must, however, follow the subpattern to which they refer.

The maximum length of a subject string is the largest positive number that an integer variable can hold. However, PCRE uses recursion to handle subpatterns and indefinite repetition. This means that the available stack space may limit the size of a subject string that can be processed by certain patterns.

Comments
Performance
PCRE regex syntax


Performance

Certain items that may appear in patterns are more efficient than others. It is more efficient to use a character class like [aeiou] than a set of alternatives such as (a|e|i|o|u). In general, the simplest construction that provides the required behaviour is usually the most efficient. Jeffrey Friedl's book contains a lot of discussion about optimizing regular expressions for efficient performance.

When a pattern begins with .* and the PCRE_DOTALL option is set, the pattern is implicitly anchored by PCRE, since it can match only at the start of a subject string. However, if PCRE_DOTALL is not set, PCRE cannot make this optimization, because the . metacharacter does not then match a newline, and if the subject string contains newlines, the pattern may match from the character immediately following one of them instead of from the very start. For example, the pattern (.*) second matches the subject "first\nand second" (where \n stands for a newline character) with the first captured substring being "and". In order to do this, PCRE has to retry the match starting after every newline in the subject.

If you are using such a pattern with subject strings that do not contain newlines, the best performance is obtained by setting PCRE_DOTALL, or starting the pattern with ^.* to indicate explicit anchoring. That saves PCRE from having to scan along the subject looking for a newline to restart at.

Beware of patterns that contain nested indefinite repeats. These can take a long time to run when applied to a string that does not match. Consider the pattern fragment (a+)*

This can match "aaaa" in 33 different ways, and this number increases very rapidly as the string gets longer. (The * repeat can match 0, 1, 2, 3, or 4 times, and for each of those cases other than 0, the + repeats can match different numbers of times.) When the remainder of the pattern is such that the entire match is going to fail, PCRE has in principle to try every possible variation, and this can take an extremely long time.

An optimization catches some of the more simple cases such as (a+)*b where a literal character follows. Before embarking on the standard matching procedure, PCRE checks that there is a "b" later in the subject string, and if there is not, it fails the match immediately. However, when there is no following literal this optimization cannot be used. You can see the difference by comparing the behaviour of (a+)*\d with the pattern above. The former gives a failure almost instantly when applied to a whole line of "a" characters, whereas the latter takes an appreciable time with strings longer than about 20 characters.

Recursive patterns
Possible modifiers in regex patterns
PCRE regex syntax


Pattern Modifiers

The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers. Spaces and newlines are ignored in modifiers, other characters cause error.

i (PCRE_CASELESS)
If this modifier is set, letters in the pattern match both upper and lower case letters.
m (PCRE_MULTILINE)
By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl. When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.
s (PCRE_DOTALL)
If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
x (PCRE_EXTENDED)
If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.
e (PREG_REPLACE_EVAL)
If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes (\) and NULL chars will be escaped by backslashes in substituted backreferences.
Uwaga

The addslashes() function is run on each matched backreference before the substitution takes place. As such, when the backreference is used as a quoted string, escaped characters will be converted to literals. However, characters which are escaped, which would normally not be converted, will retain their slashes. This makes use of this modifier very complicated.

Uwaga

Make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().

Informacja:

Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

A (PCRE_ANCHORED)
If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
D (PCRE_DOLLAR_ENDONLY)
If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.
S
When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.
U (PCRE_UNGREEDY)
This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by ?. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).

Informacja:

It is usually not possible to match more than pcre.backtrack_limit characters in ungreedy mode.

X (PCRE_EXTRA)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier.
J (PCRE_INFO_JCHANGED)
The (?J) internal option setting changes the local PCRE_DUPNAMES option. Allow duplicate names for subpatterns.
u (PCRE8)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8. This modifier is available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32. UTF-8 validity of the pattern is checked since PHP 4.3.5.

Performance
Differences From Perl
PCRE Patterns


Perl Differences

The differences described here are with respect to Perl 5.005.

  1. By default, a whitespace character is any character that the C library function isspace() recognizes, though it is possible to compile PCRE with alternative character type tables. Normally isspace() matches space, formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5 no longer includes vertical tab in its set of whitespace characters. The \v escape that was in the Perl documentation for a long time was never in fact recognized. However, the character itself was treated as whitespace at least up to 5.002. In 5.004 and 5.005 it does not match \s.
  2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits them, but they do not mean what you might think. For example, (?!a){3} does not assert that the next three characters are not "a". It just asserts that the next character is not "a" three times.
  3. Capturing subpatterns that occur inside negative lookahead assertions are counted, but their entries in the offsets vector are never set. Perl sets its numerical variables from any such patterns that are matched before the assertion fails to match something (thereby succeeding), but only if the negative lookahead assertion contains just one branch.
  4. Though binary zero characters are supported in the subject string, they are not allowed in a pattern string because it is passed as a normal C string, terminated by zero. The escape sequence "\x00" can be used in the pattern to represent a binary zero.
  5. The following Perl escape sequences are not supported: \l, \u, \L, \U. In fact these are implemented by Perl's general string-handling and are not part of its pattern matching engine.
  6. The Perl \G assertion is not supported as it is not relevant to single pattern matches.
  7. Fairly obviously, PCRE does not support the (?{code}) and (??{code}) construction. However, there is support for recursive patterns.
  8. There are at the time of writing some oddities in Perl 5.005_02 concerned with the settings of captured strings when part of a pattern is repeated. For example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set. In Perl 5.004 $2 is set in both cases, and that is also TRUE of PCRE. If in the future Perl changes to a consistent state that is different, PCRE may change to follow.
  9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not. However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.

  10. PCRE provides some extensions to the Perl regular expression facilities:

    1. Although lookbehind assertions must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl 5.005 requires them all to have the same length.
    2. If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta-character matches only at the very end of the string.
    3. If PCRE_EXTRA is set, a backslash followed by a letter with no special meaning is faulted.
    4. If PCRE_UNGREEDY is set, the greediness of the repetition quantifiers is inverted, that is, by default they are not greedy, but if followed by a question mark they are.

Possible modifiers in regex patterns
Differences from POSIX regex
PCRE Patterns


Differences from POSIX regex

As of PHP 5.3.0, the POSIX Regex extension is deprecated. There are a number of differences between POSIX regex and PCRE regex. This page lists the most notable ones that are necessary to know when converting to PCRE.

  1. The PCRE functions require that the pattern is enclosed by delimiters.
  2. Unlike POSIX, the PCRE extension does not have dedicated functions for case-insensitive matching. Instead, this is supported using the i (PCRE_CASELESS) pattern modifier. Other pattern modifiers are also available for changing the matching strategy.
  3. The POSIX functions find the longest of the leftmost match, but PCRE stops on the first valid match. If the string doesn't match at all it makes no difference, but if it matches it may have dramatic effects on both the resulting match and the matching speed. To illustrate this difference, consider the following example from "Mastering Regular Expressions" by Jeffrey Friedl. Using the pattern one(self)?(selfsufficient)? on the string oneselfsufficient with PCRE will result in matching oneself, but using POSIX the result will be the full string oneselfsufficient. Both (sub)strings match the original string, but POSIX requires that the longest be the result.

Function replacements
POSIX | PCRE
ereg_replace() | preg_replace()
ereg() | preg_match()
eregi_replace() | preg_replace()
eregi() | preg_match()
split() | preg_split()
spliti() | preg_split()
sql_regcase() | No equivalent

Differences From Perl
PCRE Funkcje
PCRE Patterns


PCRE Funkcje

Spis treści

  • preg_filter — Perform a regular expression search and replace
  • preg_grep — Return array entries that match the pattern
  • preg_last_error — Returns the error code of the last PCRE regex execution
  • preg_match_all — Perform a global regular expression match
  • preg_match — Perform a regular expression match
  • preg_quote — Quote regular expression characters
  • preg_replace_callback — Perform a regular expression search and replace using a callback
  • preg_replace — Perform a regular expression search and replace
  • preg_split — Split string by a regular expression
Differences from POSIX regex
preg_filter
PCRE


Perform a regular expression search and replace

PCRE Funkcje
preg_grep
PCRE Funkcje
PHP Manual

preg_filter

(PHP 5 >= 5.3.0)

preg_filter — Perform a regular expression search and replace

Opis

mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

preg_filter() is identical to preg_replace() except it only returns the (possibly transformed) subjects where there was a match. For details about how this function works, read the preg_replace() documentation.

Zwracane wartości

Returns an array if the subject parameter is an array, or a string otherwise.

If no matches are found or an error occurred, an empty array is returned when subject is an array or NULL otherwise.

Przykłady

Przykład #1 Example comparing preg_filter() with preg_replace()

<?php
$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$pattern = array('/\d/', '/[a-z]/', '/[1a]/');
$replace = array('A:$0', 'B:$0', 'C:$0');

echo "preg_filter returns\n";
print_r(preg_filter($pattern, $replace, $subject));

echo "preg_replace returns\n";
print_r(preg_replace($pattern, $replace, $subject));
?>

Powyższy przykład wyświetli:

preg_filter returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [7] => A:4
)
preg_replace returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [5] => A
    [6] => B
    [7] => A:4
)

Zobacz też:

  • PCRE Patterns
  • preg_replace() - Perform a regular expression search and replace
  • preg_replace_callback() - Perform a regular expression search and replace using a callback
  • preg_grep() - Return array entries that match the pattern
  • preg_last_error() - Returns the error code of the last PCRE regex execution

PCRE Funkcje
preg_grep
PCRE Funkcje


Return array entries that match the pattern

preg_filter
preg_last_error
PCRE Funkcje
PHP Manual

preg_grep

(PHP 4, PHP 5)

preg_grep — Return array entries that match the pattern

Opis

array preg_grep ( string $pattern , array $input [, int $flags = 0 ] )

Returns the array consisting of the elements of the input array that match the given pattern.

Parametry

pattern

The pattern to search for, as a string.

input

The input array.

flags

If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern.

Zwracane wartości

Returns an array indexed using the keys from the input array.

Rejestr zmian

Wersja | Opis
4.2.0 | The flags parameter was added.
4.0.4

Prior to this version, the returned array was indexed regardless of the keys of the input array.

If you want to reproduce this old behavior, use array_values() on the returned array to reindex the values.

Przykłady

Przykład #1 preg_grep() example

<?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>

Zobacz też:

  • PCRE Patterns
  • preg_match_all() - Perform a global regular expression match
  • preg_filter() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution

preg_filter
preg_last_error
PCRE Funkcje


Returns the error code of the last PCRE regex execution

preg_grep
preg_match_all
PCRE Funkcje
PHP Manual

preg_last_error

(PHP 5 >= 5.2.0)

preg_last_error — Returns the error code of the last PCRE regex execution

Opis

int preg_last_error ( void )

Returns the error code of the last PCRE regex execution.

Przykład #1 preg_last_error() example

<?php

preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');

if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
    print 'Backtrack limit was exhausted!';
}

?>

Powyższy przykład wyświetli:

Backtrack limit was exhausted!

Zwracane wartości

Returns one of the following constants (explained on their own page):

  • PREG_NO_ERROR
  • PREG_INTERNAL_ERROR
  • PREG_BACKTRACK_LIMIT_ERROR (see also pcre.backtrack_limit)
  • PREG_RECURSION_LIMIT_ERROR (see also pcre.recursion_limit)
  • PREG_BAD_UTF8_ERROR
  • PREG_BAD_UTF8_OFFSET_ERROR (since PHP 5.3.0)

preg_grep
preg_match_all
PCRE Funkcje


Perform a global regular expression match

preg_last_error
preg_match
PCRE Funkcje
PHP Manual

preg_match_all

(PHP 4, PHP 5)

preg_match_all — Perform a global regular expression match

Opis

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.

After the first match is found, the subsequent searches are continued on from end of the last match.

Parametry

pattern

The pattern to search for, as a string.

subject

The input string.

matches

Array of all matches in multi-dimensional array ordered according to flags.

flags

Can be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER):

PREG_PATTERN_ORDER

Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>

Powyższy przykład wyświetli:

<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test

So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags.

PREG_SET_ORDER

Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=\"left\">this is a test</div>",
    $out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>

Powyższy przykład wyświetli:

<b>example: </b>, example:
<div align="left">this is a test</div>, this is a test

PREG_OFFSET_CAPTURE

If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

If no order flag is given, PREG_PATTERN_ORDER is assumed.

offset

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).

Informacja:

Using offset is not equivalent to passing substr($subject, $offset) to preg_match_all() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). See preg_match() for examples.

Zwracane wartości

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

Rejestr zmian

Wersja | Opis
5.4.0 | The matches parameter became optional.
5.3.6 | Returns FALSE if offset is higher than subject length.
5.2.2 | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).
4.3.3 | The offset parameter was added
4.3.0 | The PREG_OFFSET_CAPTURE flag was added

Przykłady

Przykład #1 Getting all phone numbers out of some text.

<?php
preg_match_all("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Call 555-1212 or 1-800-555-1212", $phones);
?>

Przykład #2 Find matching HTML tags (greedy)

<?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "matched: " . $val[0] . "\n";
    echo "part 1: " . $val[1] . "\n";
    echo "part 2: " . $val[2] . "\n";
    echo "part 3: " . $val[3] . "\n";
    echo "part 4: " . $val[4] . "\n\n";
}
?>

Powyższy przykład wyświetli:

matched: <b>bold text</b>
part 1: <b>
part 2: b
part 3: bold text
part 4: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: a
part 3: click me
part 4: </a>

Przykład #3 Using named subpattern

<?php

$str = <<<FOO
a: 1
b: 2
c: 3
FOO;

preg_match_all('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however
 * the above form is recommended for backwards compatibility */
// preg_match_all('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

Powyższy przykład wyświetli:

Array
(
    [0] => Array
        (
            [0] => a: 1
            [1] => b: 2
            [2] => c: 3
        )

    [name] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [digit] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)

Zobacz też:

  • PCRE Patterns
  • preg_match() - Perform a regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution

preg_last_error
preg_match
PCRE Funkcje


Perform a regular expression match

preg_match_all
preg_quote
PCRE Funkcje
PHP Manual

preg_match

(PHP 4, PHP 5)

preg_match — Perform a regular expression match

Opis

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

Searches subject for a match to the regular expression given in pattern.

Parametry

pattern

The pattern to search for, as a string.

subject

The input string.

matches

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

flags

flags can be the following flag:

PREG_OFFSET_CAPTURE
If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

offset

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).

Informacja:

Using offset is not equivalent to passing substr($subject, $offset) to preg_match() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). Compare:

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>

Powyższy przykład wyświetli:

Array
(
)

while this example

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

will produce

Array
(
    [0] => Array
        (
            [0] => def
            [1] => 0
        )

)

Zwracane wartości

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

Rejestr zmian

Wersja | Opis
5.3.6 | Returns FALSE if offset is higher than subject length.
5.2.2 | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).
4.3.3 | The offset parameter was added
4.3.0 | The PREG_OFFSET_CAPTURE flag was added
4.3.0 | The flags parameter was added

Przykłady

Przykład #1 Find the string of text "php"

<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

Przykład #2 Find the word "web"

<?php
/* The \b in the pattern indicates a word boundary, so only the distinct
 * word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

Przykład #3 Getting the domain name out of a URL

<?php
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i',
    "http://www.php.net/index.html", $matches);
$host = $matches[1];

// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>

Powyższy przykład wyświetli:

domain name is: php.net

Przykład #4 Using named subpattern

<?php

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however
 * the above form is recommended for backwards compatibility */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

Powyższy przykład wyświetli:

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

Notatki

Wskazówka

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

Zobacz też:

  • PCRE Patterns
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution

preg_match_all
preg_quote
PCRE Funkcje


Quote regular expression characters

preg_match
preg_replace_callback
PCRE Funkcje
PHP Manual

preg_quote

(PHP 4, PHP 5)

preg_quote — Quote regular expression characters

Opis

string preg_quote ( string $str [, string $delimiter = NULL ] )

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Parametry

str

The input string.

delimiter

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

Zwracane wartości

Returns the quoted string.

Rejestr zmian

Wersja | Opis
5.3.0 | The - character is now quoted

Przykłady

Przykład #1 preg_quote() example

<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns \$40 for a g3\/400
?>

Przykład #2 Italicizing a word within some text

<?php
// In this example, preg_quote($word) is used to keep the
// asterisks from having special meaning to the regular
// expression.

$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word) . "/",
                          "<i>" . $word . "</i>",
                          $textbody);
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

preg_match
preg_replace_callback
PCRE Funkcje


Perform a regular expression search and replace using a callback

preg_quote
preg_replace
PCRE Funkcje
PHP Manual

preg_replace_callback

(PHP 4 >= 4.0.5, PHP 5)

preg_replace_callback — Perform a regular expression search and replace using a callback

Opis

mixed preg_replace_callback ( mixed $pattern , callback $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )

The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback.

Parametry

pattern

The pattern to search for. It can be either a string or an array with strings.

callback

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string.

You'll often need the callback function for a preg_replace_callback() in just one place. In this case you can use an anonymous function (since PHP 5.3.0) or create_function() to declare an anonymous function as callback within the call to preg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else.

Przykład #1 preg_replace_callback() and create_function()

<?php
/* a unix-style command line filter to convert uppercase
 * letters at the beginning of paragraphs to lowercase */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
    $line = fgets($fp);
    $line = preg_replace_callback(
        '|<p>\s*\w|',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$matches',
            'return strtolower($matches[0]);'
        ),
        $line
    );
    echo $line;
}
fclose($fp);
?>

subject

The string or an array with strings to search and replace.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

Zwracane wartości

preg_replace_callback() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is NULL

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

Rejestr zmian

Wersja | Opis
5.1.0 | The count parameter was added

Przykłady

Przykład #2 preg_replace_callback() example

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
  // as usual: $matches[0] is the complete match
  // $matches[1] the match for the first subpattern
  // enclosed in '(...)' and so on
  return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
            "|(\d{2}/\d{2}/)(\d{4})|",
            "next_year",
            $text);

?>

Powyższy przykład wyświetli:

April fools day is 04/01/2003
Last christmas was 12/24/2002

Przykład #3 preg_replace_callback() using recursive structure to handle encapsulated BB code

<?php
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";

function parseTagsRecursive($input)
{

    $regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';

    if (is_array($input)) {
        $input = '<div style="margin-left: 10px">'.$input[1].'</div>';
    }

    return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}

$output = parseTagsRecursive($input);

echo $output;
?>

Zobacz też:

  • PCRE Patterns
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution
  • create_function() - Create an anonymous (lambda-style) function
  • Anonymous functions
  • informacje o typie callback

preg_quote
preg_replace
PCRE Funkcje


Perform a regular expression search and replace

preg_replace_callback
preg_split
PCRE Funkcje
PHP Manual

preg_replace

(PHP 4, PHP 5)

preg_replace — Perform a regular expression search and replace

Opis

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

Searches subject for matches to pattern and replaces them with replacement.

Parametry

pattern

The pattern to search for. It can be either a string or an array with strings.

Several PCRE modifiers are also available, including 'e' (PREG_REPLACE_EVAL), which is specific to this function.

replacement

The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.

replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. To use backslash in replacement, it must be doubled ("\\\\" PHP string).

When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \\1 notation for your backreference. \\11, for example, would confuse preg_replace() since it does not know whether you want the \\1 backreference followed by a literal 1, or the \\11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

When using the e modifier, this function escapes some characters (namely ', ", \ and NULL) in the strings that replace the backreferences. This is done to ensure that no syntax errors arise from backreference usage with either single or double quotes (e.g. 'strlen(\'$1\')+strlen("$2")'). Make sure you are aware of PHP's string syntax to know exactly how the interpreted string will look.

subject

The string or an array with strings to search and replace.

If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

Zwracane wartości

preg_replace() returns an array if the subject parameter is an array, or a string otherwise.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the count parameter
4.0.4 | Added the '$n' form for the replacement parameter
4.0.2 | Added the limit parameter

Przykłady

Przykład #1 Using backreferences followed by numeric literals

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>

Powyższy przykład wyświetli:

April1,2003

Przykład #2 Using indexed arrays with preg_replace()

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

Powyższy przykład wyświetli:

The bear black slow jumped over the lazy dog.

By ksorting patterns and replacements, we should get what we wanted.

<?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>

Powyższy przykład wyświetli:

The slow black bear jumped over the lazy dog.

Przykład #3 Replacing several values

<?php
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
                   '/^\s*{(\w+)}\s*=/');
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?>

Powyższy przykład wyświetli:

$startDate = 5/27/1999

Przykład #4 Strip whitespace

This example strips excess whitespace from a string.

<?php
$str = 'foo   o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>

Przykład #5 Using the count parameter

<?php
$count = 0;

echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3
?>

Powyższy przykład wyświetli:

xp***to
3

Notatki

Informacja:

When using arrays with pattern and replacement, the keys are processed in the order they appear in the array. This is not necessarily the same as the numerical index order. If you use indexes to identify which pattern should be replaced by which replacement, you should perform a ksort() on each array prior to calling preg_replace().

Zobacz też:

  • PCRE Patterns
  • preg_filter() - Perform a regular expression search and replace
  • preg_match() - Perform a regular expression match
  • preg_replace_callback() - Perform a regular expression search and replace using a callback
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution

preg_replace_callback
preg_split
PCRE Funkcje


Split string by a regular expression

preg_replace
POSIX Regex
PCRE Funkcje
PHP Manual

preg_split

(PHP 4, PHP 5)

preg_split — Split string by a regular expression

Opis

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

Split the given string by a regular expression.

Parametry

pattern

The pattern to search for, as a string.

subject

The input string.

limit

If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1, 0 or NULL means "no limit" and, as is standard across PHP, you can use NULL to skip to the flags parameter.

flags

flags can be any combination of the following flags (combined with the | bitwise operator):

PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by preg_split().
PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
PREG_SPLIT_OFFSET_CAPTURE

If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

Zwracane wartości

Returns an array containing substrings of subject split along boundaries matched by pattern.

Rejestr zmian

Wersja | Opis
4.3.0 | The PREG_SPLIT_OFFSET_CAPTURE was added
4.0.5 | The PREG_SPLIT_DELIM_CAPTURE was added

Przykłady

Przykład #1 preg_split() example : Get the parts of a search string

<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
?>

Przykład #2 Splitting a string into component characters

<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

Przykład #3 Splitting a string into matches and their offsets

<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

Notatki

Wskazówka

If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split().

Zobacz też:

  • PCRE Patterns
  • implode() - Join array elements with a string
  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution

preg_replace
POSIX Regex
PCRE Funkcje


Regular Expression (POSIX Extended)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • POSIX Regex Funkcje
    • ereg_replace — Replace regular expression
    • ereg — Regular expression match
    • eregi_replace — Replace regular expression case insensitive
    • eregi — Case insensitive regular expression match
    • split — Split string into array by regular expression
    • spliti — Split string into array by regular expression case insensitive
    • sql_regcase — Make regular expression for case insensitive match
preg_split
Wstęp
Przetwarzanie tekstu


Wstęp

Wskazówka

PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.

Ostrzeżenie

These regular expression functions are not binary-safe. The PCRE functions are.

Informacja:

As of PHP 5.3.0 this extension is deprecated, calling any function provided by this extension will issue an E_DEPRECATED notice.

Regular expressions are used for complex string manipulation. PHP uses the POSIX extended regular expressions as defined by POSIX 1003.2. For a full description of POSIX regular expressions see the » regex man pages included in the regex directory in the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

POSIX Regex
Instalacja/Konfiguracja
POSIX Regex


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
POSIX Regex


Instalacja

Ostrzeżenie

Do not change the TYPE unless you know what you are doing.

To enable regexp support configure PHP --with-regex[=TYPE] . TYPE can be one of system, apache, php. The default value is php.

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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
POSIX Regex


Przykłady

Przykład #1 Regular Expression Examples

<?php
// Returns true if "abc" is found anywhere in $string.
ereg("abc", $string);

// Returns true if "abc" is found at the beginning of $string.
ereg("^abc", $string);

// Returns true if "abc" is found at the end of $string.
ereg("abc$", $string);

// Returns true if client browser is Netscape 2, 3 or MSIE 3.
eregi("(ozilla.[23]|MSIE.3)", $_SERVER["HTTP_USER_AGENT"]);

// Places three space separated words into $regs[1], $regs[2] and $regs[3].
ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)", $string, $regs);

// Put a <br /> tag at the beginning of $string.
$string = ereg_replace("^", "<br />", $string);

// Put a <br /> tag at the end of $string.
$string = ereg_replace("$", "<br />", $string);

// Get rid of any newline characters in $string.
$string = ereg_replace("\n", "", $string);
?>

Stałe predefiniowane
POSIX Regex Funkcje
POSIX Regex


POSIX Regex Funkcje

Zobacz też:

For regular expressions in Perl-compatible syntax have a look at the PCRE functions. The simpler shell style wildcard pattern matching is provided by fnmatch().

Spis treści

  • ereg_replace — Replace regular expression
  • ereg — Regular expression match
  • eregi_replace — Replace regular expression case insensitive
  • eregi — Case insensitive regular expression match
  • split — Split string into array by regular expression
  • spliti — Split string into array by regular expression case insensitive
  • sql_regcase — Make regular expression for case insensitive match
Przykłady
ereg_replace
POSIX Regex


Replace regular expression

POSIX Regex Funkcje
ereg
POSIX Regex Funkcje
PHP Manual

ereg_replace

(PHP 4, PHP 5)

ereg_replace — Replace regular expression

Opis

string ereg_replace ( string $pattern , string $replacement , string $string )

This function scans string for matches to pattern, then replaces the matched text with replacement.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Parametry

pattern

A POSIX extended regular expression.

replacement

If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

string

The input string.

Zwracane wartości

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Przykłady

For example, the following code snippet prints "This was a test" three times:

Przykład #1 ereg_replace() example

<?php

$string = "This is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "\\1was", $string);
echo ereg_replace("(( )is)", "\\2was", $string);

?>

One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that. For instance:

Przykład #2 ereg_replace() example

<?php
/* This will not work as expected. */
$num = 4;
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has   words.' */

/* This will work. */
$num = '4';
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has 4 words.' */
?>

Przykład #3 Replace URLs with links

<?php
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     "<a href=\"\\0\">\\0</a>", $text);
?>

Notatki

Informacja:

Od PHP 5.3.0 rozszerzenie regex jest przestarzałe. Zamiast niego należy używać rozszerzenia PCRE. Wywołanie tych funkcji spowoduje wygenerowanie ostrzeżenia E_DEPRECATED. Zobacz listę różnic aby uzyskać pomoc w migracji do PCRE.

Wskazówka

preg_replace(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg_replace().

Zobacz też:

  • ereg() - Regular expression match
  • eregi() - Case insensitive regular expression match
  • eregi_replace() - Replace regular expression case insensitive
  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace

POSIX Regex Funkcje
ereg
POSIX Regex Funkcje


Regular expression match

ereg_replace
eregi_replace
POSIX Regex Funkcje
PHP Manual

ereg

(PHP 4, PHP 5)

ereg — Regular expression match

Opis

int ereg ( string $pattern , string $string [, array &$regs ] )

Searches a string for matches to the regular expression given in pattern in a case-sensitive way.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Parametry

pattern

Case sensitive regular expression.

string

The input string.

regs

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs.

$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

Zwracane wartości

Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

Rejestr zmian

Wersja | Opis
4.1.0 | Up to (and including) PHP 4.1.0 $regs will be filled with exactly ten elements, even though more or fewer than ten parenthesized substrings may actually have matched. This has no effect on ereg()'s ability to match more substrings. If no matches are found, $regs will not be altered by ereg().

Przykłady

Przykład #1 ereg() example

The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:

<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
    echo "$regs[3].$regs[2].$regs[1]";
} else {
    echo "Invalid date format: $date";
}
?>

Notatki

Informacja:

Od PHP 5.3.0 rozszerzenie regex jest przestarzałe. Zamiast niego należy używać rozszerzenia PCRE. Wywołanie tych funkcji spowoduje wygenerowanie ostrzeżenia E_DEPRECATED. Zobacz listę różnic aby uzyskać pomoc w migracji do PCRE.

Informacja:

preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().

Zobacz też:

  • eregi() - Case insensitive regular expression match
  • ereg_replace() - Replace regular expression
  • eregi_replace() - Replace regular expression case insensitive
  • preg_match() - Perform a regular expression match
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strstr() - Find the first occurrence of a string
  • quotemeta() - Quote meta characters

ereg_replace
eregi_replace
POSIX Regex Funkcje


Replace regular expression case insensitive

ereg
eregi
POSIX Regex Funkcje
PHP Manual

eregi_replace

(PHP 4, PHP 5)

eregi_replace — Replace regular expression case insensitive

Opis

string eregi_replace ( string $pattern , string $replacement , string $string )

This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Parametry

pattern

A POSIX extended regular expression.

replacement

If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

string

The input string.

Zwracane wartości

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Przykłady

Przykład #1 Highlight search results

<?php
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>

Notatki

Informacja:

Od PHP 5.3.0 rozszerzenie regex jest przestarzałe. Zamiast niego należy używać rozszerzenia PCRE. Wywołanie tych funkcji spowoduje wygenerowanie ostrzeżenia E_DEPRECATED. Zobacz listę różnic aby uzyskać pomoc w migracji do PCRE.

Zobacz też:

  • ereg() - Regular expression match
  • eregi() - Case insensitive regular expression match
  • ereg_replace() - Replace regular expression
  • preg_replace() - Perform a regular expression search and replace

ereg
eregi
POSIX Regex Funkcje


Case insensitive regular expression match

eregi_replace
split
POSIX Regex Funkcje
PHP Manual

eregi

(PHP 4, PHP 5)

eregi — Case insensitive regular expression match

Opis

int eregi ( string $pattern , string $string [, array &$regs ] )

This function is identical to ereg() except that it ignores case distinction when matching alphabetic characters.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Parametry

pattern

Case insensitive regular expression.

string

The input string.

regs

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs.

$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

Zwracane wartości

Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

Przykłady

Przykład #1 eregi() example

<?php
$string = 'XYZ';
if (eregi('z', $string)) {
    echo "'$string' contains a 'z' or 'Z'!";
}
?>

Notatki

Informacja:

Od PHP 5.3.0 rozszerzenie regex jest przestarzałe. Zamiast niego należy używać rozszerzenia PCRE. Wywołanie tych funkcji spowoduje wygenerowanie ostrzeżenia E_DEPRECATED. Zobacz listę różnic aby uzyskać pomoc w migracji do PCRE.

Zobacz też:

  • ereg() - Regular expression match
  • ereg_replace() - Replace regular expression
  • eregi_replace() - Replace regular expression case insensitive
  • preg_match() - Perform a regular expression match
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • stristr() - Case-insensitive strstr

eregi_replace
split
POSIX Regex Funkcje


Split string into array by regular expression

eregi
spliti
POSIX Regex Funkcje
PHP Manual

split

(PHP 4, PHP 5)

split — Split string into array by regular expression

Opis

array split ( string $pattern , string $string [, int $limit = -1 ] )

Splits a string into array by regular expression.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Parametry

pattern

Case sensitive regular expression.

If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think split() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

string

The input string.

limit

If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string.

Zwracane wartości

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case-sensitive regular expression pattern.

If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty. If an error occurs, split() returns FALSE.

Przykłady

Przykład #1 split() example

To split off the first four fields from a line from /etc/passwd:

<?php
list($user, $pass, $uid, $gid, $extra) =
    split(":", $passwd_line, 5);
?>

Przykład #2 split() example

To parse a date which may be delimited with slashes, dots, or hyphens:

<?php
// Delimiters may be slash, dot, or hyphen
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>

Notatki

Informacja:

Od PHP 5.3.0 rozszerzenie regex jest przestarzałe. Zamiast niego należy używać rozszerzenia PCRE. Wywołanie tych funkcji spowoduje wygenerowanie ostrzeżenia E_DEPRECATED. Zobacz listę różnic aby uzyskać pomoc w migracji do PCRE.

Wskazówka

preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split(). If you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.

Wskazówka

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split() or str_split().

Zobacz też:

  • preg_split() - Split string by a regular expression
  • spliti() - Split string into array by regular expression case insensitive
  • str_split() - Convert a string to an array
  • explode() - Split a string by string
  • implode() - Join array elements with a string
  • chunk_split() - Split a string into smaller chunks
  • wordwrap() - Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.

eregi
spliti
POSIX Regex Funkcje


Split string into array by regular expression case insensitive

split
sql_regcase
POSIX Regex Funkcje
PHP Manual

spliti

(PHP 4 >= 4.0.1, PHP 5)

spliti — Split string into array by regular expression case insensitive

Opis

array spliti ( string $pattern , string $string [, int $limit = -1 ] )

Splits a string into array by regular expression.

This function is identical to split() except that this ignores case distinction when matching alphabetic characters.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Parametry

pattern

Case insensitive regular expression.

If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think spliti() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

string

The input string.

limit

If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string.

Zwracane wartości

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case insensitive regular expression pattern.

If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty. If an error occurs, spliti() returns FALSE.

Przykłady

This example splits a string using 'a' as the separator :

Przykład #1 spliti() example

<?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?>

Powyższy przykład wyświetli:

Array
(
  [0] =>
  [1] => BBB
  [2] => CCC
  [3] => DDD
  [4] => EEEaGGGA
)

Notatki

Informacja:

Od PHP 5.3.0 rozszerzenie regex jest przestarzałe. Zamiast niego należy używać rozszerzenia PCRE. Wywołanie tych funkcji spowoduje wygenerowanie ostrzeżenia E_DEPRECATED. Zobacz listę różnic aby uzyskać pomoc w migracji do PCRE.

Zobacz też:

  • preg_split() - Split string by a regular expression
  • split() - Split string into array by regular expression
  • explode() - Split a string by string
  • implode() - Join array elements with a string

split
sql_regcase
POSIX Regex Funkcje


Make regular expression for case insensitive match

spliti
ssdeep
POSIX Regex Funkcje
PHP Manual

sql_regcase

(PHP 4, PHP 5)

sql_regcase — Make regular expression for case insensitive match

Opis

string sql_regcase ( string $string )

Creates a regular expression for a case insensitive match.

Ostrzeżenie

Ta funkcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej funkcji nie jest zalecane.

Parametry

string

The input string.

Zwracane wartości

Returns a valid regular expression which will match string, ignoring case. This expression is string with each alphabetic character converted to a bracket expression; this bracket expression contains that character's uppercase and lowercase form. Other characters remain unchanged.

Przykłady

Przykład #1 sql_regcase() example

<?php
echo sql_regcase("Foo - bar.");
?>

Powyższy przykład wyświetli:

[Ff][Oo][Oo] - [Bb][Aa][Rr].

This can be used to achieve case insensitive pattern matching in products which support only case sensitive regular expressions.

Notatki

Informacja:

Od PHP 5.3.0 rozszerzenie regex jest przestarzałe. Zamiast niego należy używać rozszerzenia PCRE. Wywołanie tych funkcji spowoduje wygenerowanie ostrzeżenia E_DEPRECATED. Zobacz listę różnic aby uzyskać pomoc w migracji do PCRE.

spliti
ssdeep
POSIX Regex Funkcje


ssdeep Fuzzy Hashing

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • ssdeep Funkcje
    • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
    • ssdeep_fuzzy_hash — Create a fuzzy hash from a string
sql_regcase
Wstęp
Przetwarzanie tekstu


Wstęp

ssdeep is a utility for creating and comparing fuzzy hashes or » context-triggered piecewise hashing.

Fuzzy hashing can match signatures which have "...sequences of identical bytes in the same order, although bytes in between these sequences may be different in both content and length". (» ssdeep project page)

This extension provides functions for creating and comparing fuzzy hashes.

ssdeep
Instalacja/Konfiguracja
ssdeep


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
ssdeep


Wymagania

This extension requires the » ssdeep library.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/ssdeep.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
ssdeep Funkcje
ssdeep


ssdeep Funkcje

Spis treści

  • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
  • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
  • ssdeep_fuzzy_hash — Create a fuzzy hash from a string
Stałe predefiniowane
ssdeep_fuzzy_compare
ssdeep


Calculates the match score between two fuzzy hash signatures

ssdeep Funkcje
ssdeep_fuzzy_hash_filename
ssdeep Funkcje
PHP Manual

ssdeep_fuzzy_compare

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures

Opis

int ssdeep_fuzzy_compare ( string $signature1 , string $signature2 )

Calculates the match score between signature1 and signature2 using » context-triggered piecewise hashing, and returns the match score.

Parametry

signature1

The first fuzzy hash signature string.

signature2

The second fuzzy hash signature string.

Zwracane wartości

Returns an integer from 0 to 100 on success, FALSE otherwise.

ssdeep Funkcje
ssdeep_fuzzy_hash_filename
ssdeep Funkcje


Create a fuzzy hash from a file

ssdeep_fuzzy_compare
ssdeep_fuzzy_hash
ssdeep Funkcje
PHP Manual

ssdeep_fuzzy_hash_filename

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file

Opis

string ssdeep_fuzzy_hash_filename ( string $file_name )

ssdeep_fuzzy_hash_filename() calculates the hash of the file specified by file_name using » context-triggered piecewise hashing, and returns that hash.

Parametry

file_name

The filename of the file to hash.

Zwracane wartości

Returns a string on success, FALSE otherwise.

ssdeep_fuzzy_compare
ssdeep_fuzzy_hash
ssdeep Funkcje


Create a fuzzy hash from a string

ssdeep_fuzzy_hash_filename
Strings
ssdeep Funkcje
PHP Manual

ssdeep_fuzzy_hash

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash — Create a fuzzy hash from a string

Opis

string ssdeep_fuzzy_hash ( string $to_hash )

ssdeep_fuzzy_hash() calculates the hash of to_hash using » context-triggered piecewise hashing, and returns that hash.

Parametry

to_hash

The input string.

Zwracane wartości

Returns a string on success, FALSE otherwise.

ssdeep_fuzzy_hash_filename
Strings
ssdeep Funkcje


Strings

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • String Funkcje
    • addcslashes — Quote string with slashes in a C style
    • addslashes — Quote string with slashes
    • bin2hex — Convert binary data into hexadecimal representation
    • chop — Alias dla rtrim
    • chr — Return a specific character
    • chunk_split — Split a string into smaller chunks
    • convert_cyr_string — Convert from one Cyrillic character set to another
    • convert_uudecode — Decode a uuencoded string
    • convert_uuencode — Uuencode a string
    • count_chars — Return information about characters used in a string
    • crc32 — Calculates the crc32 polynomial of a string
    • crypt — One-way string hashing
    • echo — Output one or more strings
    • explode — Split a string by string
    • fprintf — Write a formatted string to a stream
    • get_html_translation_table — Returns the translation table used by htmlspecialchars and htmlentities
    • hebrev — Convert logical Hebrew text to visual text
    • hebrevc — Convert logical Hebrew text to visual text with newline conversion
    • hex2bin — Convert hex to binary
    • html_entity_decode — Convert all HTML entities to their applicable characters
    • htmlentities — Convert all applicable characters to HTML entities
    • htmlspecialchars_decode — Convert special HTML entities back to characters
    • htmlspecialchars — Convert special characters to HTML entities
    • implode — Join array elements with a string
    • join — Alias dla implode
    • lcfirst — Make a string's first character lowercase
    • levenshtein — Calculate Levenshtein distance between two strings
    • localeconv — Get numeric formatting information
    • ltrim — Strip whitespace (or other characters) from the beginning of a string
    • md5_file — Calculates the md5 hash of a given file
    • md5 — Calculate the md5 hash of a string
    • metaphone — Calculate the metaphone key of a string
    • money_format — Formats a number as a currency string
    • nl_langinfo — Query language and locale information
    • nl2br — Inserts HTML line breaks before all newlines in a string
    • number_format — Formatuje liczbę według szablonu
    • ord — Return ASCII value of character
    • parse_str — Parses the string into variables
    • print — Output a string
    • printf — Output a formatted string
    • quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
    • quoted_printable_encode — Convert a 8 bit string to a quoted-printable string
    • quotemeta — Quote meta characters
    • rtrim — Strip whitespace (or other characters) from the end of a string
    • setlocale — Set locale information
    • sha1_file — Calculate the sha1 hash of a file
    • sha1 — Calculate the sha1 hash of a string
    • similar_text — Calculate the similarity between two strings
    • soundex — Calculate the soundex key of a string
    • sprintf — Return a formatted string
    • sscanf — Parses input from a string according to a format
    • str_getcsv — Parse a CSV string into an array
    • str_ireplace — Case-insensitive version of str_replace.
    • str_pad — Pad a string to a certain length with another string
    • str_repeat — Repeat a string
    • str_replace — Replace all occurrences of the search string with the replacement string
    • str_rot13 — Perform the rot13 transform on a string
    • str_shuffle — Randomly shuffles a string
    • str_split — Convert a string to an array
    • str_word_count — Return information about words used in a string
    • strcasecmp — Binary safe case-insensitive string comparison
    • strchr — Alias dla strstr
    • strcmp — Binary safe string comparison
    • strcoll — Locale based string comparison
    • strcspn — Find length of initial segment not matching mask
    • strip_tags — Strip HTML and PHP tags from a string
    • stripcslashes — Un-quote string quoted with addcslashes
    • stripos — Find the position of the first occurrence of a case-insensitive substring in a string
    • stripslashes — Un-quotes a quoted string
    • stristr — Case-insensitive strstr
    • strlen — Get string length
    • strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
    • strnatcmp — String comparisons using a "natural order" algorithm
    • strncasecmp — Binary safe case-insensitive string comparison of the first n characters
    • strncmp — Binary safe string comparison of the first n characters
    • strpbrk — Search a string for any of a set of characters
    • strpos — Find the position of the first occurrence of a substring in a string
    • strrchr — Znajduje ostatnie występowanie znaku w łańcuchu znaków
    • strrev — Odwraca ciąg znaków
    • strripos — Find the position of the last occurrence of a case-insensitive substring in a string
    • strrpos — Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków
    • strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.
    • strstr — Find the first occurrence of a string
    • strtok — Tokenize string
    • strtolower — Zmienia wszystkie litery w łańcuchu na małe
    • strtoupper — Zmienia wszystkie litery w łańcuchu na duże
    • strtr — Translate characters or replace substrings
    • substr_compare — Binary safe comparison of two strings from an offset, up to length characters
    • substr_count — Count the number of substring occurrences
    • substr_replace — Zastępuje tekst wewnątrz części łańcucha
    • substr — Return part of a string
    • trim — Strip whitespace (or other characters) from the beginning and end of a string
    • ucfirst — Make a string's first character uppercase
    • ucwords — Uppercase the first character of each word in a string
    • vfprintf — Write a formatted string to a stream
    • vprintf — Output a formatted string
    • vsprintf — Return a formatted string
    • wordwrap — Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.
ssdeep_fuzzy_hash
Wstęp
Przetwarzanie tekstu


Wstęp

These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.

For information on how strings behave, especially with regard to usage of single quotes, double quotes, and escape sequences, see the Strings entry in the Types section of the manual.

Strings
Instalacja/Konfiguracja
Strings


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Strings


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.

CRYPT_SALT_LENGTH integer
CRYPT_STD_DES integer
CRYPT_EXT_DES integer
CRYPT_MD5 integer
CRYPT_BLOWFISH integer
HTML_SPECIALCHARS (integer)
HTML_ENTITIES (integer)
ENT_COMPAT (integer)
ENT_QUOTES (integer)
ENT_NOQUOTES (integer)
CHAR_MAX (integer)
LC_CTYPE (integer)
LC_NUMERIC (integer)
LC_TIME (integer)
LC_COLLATE (integer)
LC_MONETARY (integer)
LC_ALL (integer)
LC_MESSAGES (integer)
STR_PAD_LEFT (integer)
STR_PAD_RIGHT (integer)
STR_PAD_BOTH (integer)
Typy zasobów
String Funkcje
Strings


String Funkcje

Zobacz też:

For even more powerful string handling and manipulating functions take a look at the POSIX regular expression functions and the Perl compatible regular expression functions.

Spis treści

  • addcslashes — Quote string with slashes in a C style
  • addslashes — Quote string with slashes
  • bin2hex — Convert binary data into hexadecimal representation
  • chop — Alias dla rtrim
  • chr — Return a specific character
  • chunk_split — Split a string into smaller chunks
  • convert_cyr_string — Convert from one Cyrillic character set to another
  • convert_uudecode — Decode a uuencoded string
  • convert_uuencode — Uuencode a string
  • count_chars — Return information about characters used in a string
  • crc32 — Calculates the crc32 polynomial of a string
  • crypt — One-way string hashing
  • echo — Output one or more strings
  • explode — Split a string by string
  • fprintf — Write a formatted string to a stream
  • get_html_translation_table — Returns the translation table used by htmlspecialchars and htmlentities
  • hebrev — Convert logical Hebrew text to visual text
  • hebrevc — Convert logical Hebrew text to visual text with newline conversion
  • hex2bin — Convert hex to binary
  • html_entity_decode — Convert all HTML entities to their applicable characters
  • htmlentities — Convert all applicable characters to HTML entities
  • htmlspecialchars_decode — Convert special HTML entities back to characters
  • htmlspecialchars — Convert special characters to HTML entities
  • implode — Join array elements with a string
  • join — Alias dla implode
  • lcfirst — Make a string's first character lowercase
  • levenshtein — Calculate Levenshtein distance between two strings
  • localeconv — Get numeric formatting information
  • ltrim — Strip whitespace (or other characters) from the beginning of a string
  • md5_file — Calculates the md5 hash of a given file
  • md5 — Calculate the md5 hash of a string
  • metaphone — Calculate the metaphone key of a string
  • money_format — Formats a number as a currency string
  • nl_langinfo — Query language and locale information
  • nl2br — Inserts HTML line breaks before all newlines in a string
  • number_format — Formatuje liczbę według szablonu
  • ord — Return ASCII value of character
  • parse_str — Parses the string into variables
  • print — Output a string
  • printf — Output a formatted string
  • quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
  • quoted_printable_encode — Convert a 8 bit string to a quoted-printable string
  • quotemeta — Quote meta characters
  • rtrim — Strip whitespace (or other characters) from the end of a string
  • setlocale — Set locale information
  • sha1_file — Calculate the sha1 hash of a file
  • sha1 — Calculate the sha1 hash of a string
  • similar_text — Calculate the similarity between two strings
  • soundex — Calculate the soundex key of a string
  • sprintf — Return a formatted string
  • sscanf — Parses input from a string according to a format
  • str_getcsv — Parse a CSV string into an array
  • str_ireplace — Case-insensitive version of str_replace.
  • str_pad — Pad a string to a certain length with another string
  • str_repeat — Repeat a string
  • str_replace — Replace all occurrences of the search string with the replacement string
  • str_rot13 — Perform the rot13 transform on a string
  • str_shuffle — Randomly shuffles a string
  • str_split — Convert a string to an array
  • str_word_count — Return information about words used in a string
  • strcasecmp — Binary safe case-insensitive string comparison
  • strchr — Alias dla strstr
  • strcmp — Binary safe string comparison
  • strcoll — Locale based string comparison
  • strcspn — Find length of initial segment not matching mask
  • strip_tags — Strip HTML and PHP tags from a string
  • stripcslashes — Un-quote string quoted with addcslashes
  • stripos — Find the position of the first occurrence of a case-insensitive substring in a string
  • stripslashes — Un-quotes a quoted string
  • stristr — Case-insensitive strstr
  • strlen — Get string length
  • strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
  • strnatcmp — String comparisons using a "natural order" algorithm
  • strncasecmp — Binary safe case-insensitive string comparison of the first n characters
  • strncmp — Binary safe string comparison of the first n characters
  • strpbrk — Search a string for any of a set of characters
  • strpos — Find the position of the first occurrence of a substring in a string
  • strrchr — Znajduje ostatnie występowanie znaku w łańcuchu znaków
  • strrev — Odwraca ciąg znaków
  • strripos — Find the position of the last occurrence of a case-insensitive substring in a string
  • strrpos — Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków
  • strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.
  • strstr — Find the first occurrence of a string
  • strtok — Tokenize string
  • strtolower — Zmienia wszystkie litery w łańcuchu na małe
  • strtoupper — Zmienia wszystkie litery w łańcuchu na duże
  • strtr — Translate characters or replace substrings
  • substr_compare — Binary safe comparison of two strings from an offset, up to length characters
  • substr_count — Count the number of substring occurrences
  • substr_replace — Zastępuje tekst wewnątrz części łańcucha
  • substr — Return part of a string
  • trim — Strip whitespace (or other characters) from the beginning and end of a string
  • ucfirst — Make a string's first character uppercase
  • ucwords — Uppercase the first character of each word in a string
  • vfprintf — Write a formatted string to a stream
  • vprintf — Output a formatted string
  • vsprintf — Return a formatted string
  • wordwrap — Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.
Stałe predefiniowane
addcslashes
Strings


Quote string with slashes in a C style

String Funkcje
addslashes
String Funkcje
PHP Manual

addcslashes

(PHP 4, PHP 5)

addcslashes — Quote string with slashes in a C style

Opis

string addcslashes ( string $str , string $charlist )

Returns a string with backslashes before characters that are listed in charlist parameter.

Parametry

str

The string to be escaped.

charlist

A list of characters to be escaped. If charlist contains characters \n, \r etc., they are converted in C-like style, while other non-alphanumeric characters with ASCII codes lower than 32 and higher than 126 converted to octal representation.

When you define a sequence of characters in the charlist argument make sure that you know what characters come between the characters that you set as the start and end of the range.

<?php
echo addcslashes('foo[ ]', 'A..z');
// output:  \f\o\o\[ \]
// All upper and lower-case letters will be escaped
// ... but so will the [\]^_`
?>
Also, if the first character in a range has a higher ASCII value than the second character in the range, no range will be constructed. Only the start, end and period characters will be escaped. Use the ord() function to find the ASCII value for a character.
<?php
echo addcslashes("zoo['.']", 'z..A');
// output:  \zoo['\.']
?>

Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v. In PHP \0 (NULL), \r (carriage return), \n (newline), \f (form feed), \v (vertical tab) and \t (tab) are predefined escape sequences, while in C all of these are predefined escape sequences.

Zwracane wartości

Returns the escaped string.

Rejestr zmian

Wersja | Opis
5.2.5 | The escape sequences \v and \f were added.

Przykłady

charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.

Przykład #1 addcslashes() example

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

Zobacz też:

  • stripcslashes() - Un-quote string quoted with addcslashes
  • stripslashes() - Un-quotes a quoted string
  • addslashes() - Quote string with slashes
  • htmlspecialchars() - Convert special characters to HTML entities
  • quotemeta() - Quote meta characters

String Funkcje
addslashes
String Funkcje


Quote string with slashes

addcslashes
bin2hex
String Funkcje
PHP Manual

addslashes

(PHP 4, PHP 5)

addslashes — Quote string with slashes

Opis

string addslashes ( string $str )

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. It's highly recommended to use DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_string() for PostgreSQL), but if the DBMS you're using doesn't have an escape function and the DBMS uses \ to escape special chars, you can use this function. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '.

The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.

Parametry

str

The string to be escaped.

Zwracane wartości

Returns the escaped string.

Przykłady

Przykład #1 An addslashes() example

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

Zobacz też:

  • stripcslashes() - Un-quote string quoted with addcslashes
  • stripslashes() - Un-quotes a quoted string
  • addcslashes() - Quote string with slashes in a C style
  • htmlspecialchars() - Convert special characters to HTML entities
  • quotemeta() - Quote meta characters
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc

addcslashes
bin2hex
String Funkcje


Convert binary data into hexadecimal representation

addslashes
chop
String Funkcje
PHP Manual

bin2hex

(PHP 4, PHP 5)

bin2hex — Convert binary data into hexadecimal representation

Opis

string bin2hex ( string $str )

Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first.

Parametry

str

A string.

Zwracane wartości

Returns the hexadecimal representation of the given string.

Zobacz też:

  • hex2bin() - Convert hex to binary
  • pack() - Pack data into binary string

addslashes
chop
String Funkcje


Alias dla rtrim

bin2hex
chr
String Funkcje
PHP Manual

chop

(PHP 4, PHP 5)

chop — Alias dla rtrim()

Opis

Ta funkcja jest aliasem dla: rtrim().

Notatki

Informacja:

chop() is different than the Perl chop() function, which removes the last character in the string.

bin2hex
chr
String Funkcje


Return a specific character

chop
chunk_split
String Funkcje
PHP Manual

chr

(PHP 4, PHP 5)

chr — Return a specific character

Opis

string chr ( int $ascii )

Returns a one-character string containing the character specified by ascii.

This function complements ord().

Parametry

ascii

The ascii code.

Zwracane wartości

Returns the specified character.

Przykłady

Przykład #1 chr() example

<?php
$str = "The string ends in escape: ";
$str .= chr(27); /* add an escape character at the end of $str */

/* Often this is more useful */

$str = sprintf("The string ends in escape: %c", 27);
?>

Zobacz też:

  • sprintf() - Return a formatted string with a format string of %c
  • ord()
  • An » ASCII-table

chop
chunk_split
String Funkcje


Split a string into smaller chunks

chr
convert_cyr_string
String Funkcje
PHP Manual

chunk_split

(PHP 4, PHP 5)

chunk_split — Split a string into smaller chunks

Opis

string chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] )

Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode() output to match RFC 2045 semantics. It inserts end every chunklen characters.

Parametry

body

The string to be chunked.

chunklen

The chunk length.

end

The line ending sequence.

Zwracane wartości

Returns the chunked string.

Przykłady

Przykład #1 chunk_split() example

<?php
// format $data using RFC 2045 semantics
$new_string = chunk_split(base64_encode($data));
?>

Zobacz też:

  • str_split() - Convert a string to an array
  • explode() - Split a string by string
  • split() - Split string into array by regular expression
  • wordwrap() - Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.
  • » RFC 2045

chr
convert_cyr_string
String Funkcje


Convert from one Cyrillic character set to another

chunk_split
convert_uudecode
String Funkcje
PHP Manual

convert_cyr_string

(PHP 4, PHP 5)

convert_cyr_string — Convert from one Cyrillic character set to another

Opis

string convert_cyr_string ( string $str , string $from , string $to )

Converts from one Cyrillic character set to another.

Parametry

str

The string to be converted.

from

The source Cyrillic character set, as a single character.

to

The target Cyrillic character set, as a single character.

Supported characters are:

  • k - koi8-r
  • w - windows-1251
  • i - iso8859-5
  • a - x-cp866
  • d - x-cp866
  • m - x-mac-cyrillic

Zwracane wartości

Returns the converted string.

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

chunk_split
convert_uudecode
String Funkcje


Decode a uuencoded string

convert_cyr_string
convert_uuencode
String Funkcje
PHP Manual

convert_uudecode

(PHP 5)

convert_uudecode — Decode a uuencoded string

Opis

string convert_uudecode ( string $data )

convert_uudecode() decodes a uuencoded string.

Parametry

data

The uuencoded data.

Zwracane wartości

Returns the decoded data as a string.

Przykłady

Przykład #1 convert_uudecode() example

<?php
/* Can you imagine what this will print? :) */
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>

Zobacz też:

  • convert_uuencode() - Uuencode a string

convert_cyr_string
convert_uuencode
String Funkcje


Uuencode a string

convert_uudecode
count_chars
String Funkcje
PHP Manual

convert_uuencode

(PHP 5)

convert_uuencode — Uuencode a string

Opis

string convert_uuencode ( string $data )

convert_uuencode() encodes a string using the uuencode algorithm.

Uuencode translates all strings (including binary's ones) into printable characters, making them safe for network transmissions. Uuencoded data is about 35% larger than the original.

Parametry

data

The data to be encoded.

Zwracane wartości

Returns the uuencoded data.

Przykłady

Przykład #1 convert_uuencode() example

<?php
$some_string = "test\ntext text\r\n";

echo convert_uuencode($some_string);
?>

Zobacz też:

  • convert_uudecode() - Decode a uuencoded string
  • base64_encode() - Koduje dane za pomocą algorytmu MIME base64

convert_uudecode
count_chars
String Funkcje


Return information about characters used in a string

convert_uuencode
crc32
String Funkcje
PHP Manual

count_chars

(PHP 4, PHP 5)

count_chars — Return information about characters used in a string

Opis

mixed count_chars ( string $string [, int $mode = 0 ] )

Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways.

Parametry

string

The examined string.

mode

See return values.

Zwracane wartości

Depending on mode count_chars() returns one of the following:

  • 0 - an array with the byte-value as key and the frequency of every byte as value.
  • 1 - same as 0 but only byte-values with a frequency greater than zero are listed.
  • 2 - same as 0 but only byte-values with a frequency equal to zero are listed.
  • 3 - a string containing all unique characters is returned.
  • 4 - a string containing all not used characters is returned.

Przykłady

Przykład #1 count_chars() example

<?php
$data = "Two Ts and one F.";

foreach (count_chars($data, 1) as $i => $val) {
   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>

Powyższy przykład wyświetli:

There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.

Zobacz też:

  • strpos() - Find the position of the first occurrence of a substring in a string
  • substr_count() - Count the number of substring occurrences

convert_uuencode
crc32
String Funkcje


Calculates the crc32 polynomial of a string

count_chars
crypt
String Funkcje
PHP Manual

crc32

(PHP 4 >= 4.0.1, PHP 5)

crc32 — Calculates the crc32 polynomial of a string

Opis

int crc32 ( string $str )

Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.

Because PHP's integer type is signed, and many crc32 checksums will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32 checksum.

Parametry

str

The data.

Zwracane wartości

Returns the crc32 checksum of str as an integer.

Przykłady

Przykład #1 Displaying a crc32 checksum

This example shows how to print a converted checksum with the printf() function:

<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?>

Zobacz też:

  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string

count_chars
crypt
String Funkcje


One-way string hashing

crc32
echo
String Funkcje
PHP Manual

crypt

(PHP 4, PHP 5)

crypt — One-way string hashing

Opis

string crypt ( string $str [, string $salt ] )

crypt() will return a hashed string using the standard Unix DES-based algorithm or alternative algorithms that may be available on the system.

Some operating systems support more than one type of hash. In fact, sometimes the standard DES-based algorithm is replaced by an MD5-based algorithm. The hash type is triggered by the salt argument. Prior to 5.3, PHP would determine the available algorithms at install-time based on the system's crypt(). If no salt is provided, PHP will auto-generate either a standard two character (DES) salt, or a twelve character (MD5), depending on the availability of MD5 crypt(). PHP sets a constant named CRYPT_SALT_LENGTH which indicates the longest valid salt allowed by the available hashes.

The standard DES-based crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).

On systems where the crypt() function supports multiple hash types, the following constants are set to 0 or 1 depending on whether the given type is available:

  • CRYPT_STD_DES - Standard DES-based hash with a two character salt from the alphabet "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
  • CRYPT_EXT_DES - Extended DES-based hash. The "salt" is a 9-character string consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt. These are encoded as printable characters, 6 bits per character, least significant character first. The values 0 to 63 are encoded as "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
  • CRYPT_MD5 - MD5 hashing with a twelve character salt starting with $1$
  • CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: "$2a$", a two digit cost parameter, "$", and 22 digits from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithmeter and must be in range 04-31, values outside this range will cause crypt() to fail.
  • CRYPT_SHA256 - SHA-256 hash with a sixteen character salt prefixed with $5$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
  • CRYPT_SHA512 - SHA-512 hash with a sixteen character salt prefixed with $6$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.

Informacja:

As of PHP 5.3.0, PHP contains its own implementation and will use that if the system lacks of support for one or more of the algorithms.

Parametry

str

The string to be hashed.

salt

An optional salt string to base the hashing on. If not provided, the behaviour is defined by the algorithm implementation and can lead to unexpected results.

Zwracane wartości

Returns the hashed string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure.

Rejestr zmian

Wersja | Opis
5.3.2 | Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's » implementation.
5.3.2 | Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.
5.3.0 | PHP now contains its own implementation for the MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms.

Przykłady

Przykład #1 crypt() examples

<?php
$password = crypt('mypassword'); // let the salt be automatically generated

/* You should pass the entire results of crypt() as the salt for comparing a
   password, to avoid problems when different hashing algorithms are used. (As
   it says above, standard DES-based password hashing uses a 2-character salt,
   but MD5-based hashing uses 12.) */
if (crypt($user_input, $password) == $password) {
   echo "Password verified!";
}
?>

Przykład #2 Using crypt() with htpasswd

<?php
// Set the password
$password = 'mypassword';

// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
?>

Przykład #3 Using crypt() with different hash types

<?php
if (CRYPT_STD_DES == 1) {
    echo 'Standard DES: ' . crypt('rasmuslerdorf', 'rl') . "\n";
}

if (CRYPT_EXT_DES == 1) {
    echo 'Extended DES: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
}

if (CRYPT_MD5 == 1) {
    echo 'MD5:          ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
}

if (CRYPT_BLOWFISH == 1) {
    echo 'Blowfish:     ' . crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA256 == 1) {
    echo 'SHA-256:      ' . crypt('rasmuslerdorf', '$5$rounds=5000$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA512 == 1) {
    echo 'SHA-512:      ' . crypt('rasmuslerdorf', '$6$rounds=5000$usesomesillystringforsalt$') . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:          $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish:     $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256:      $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512:      $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21

Notatki

Informacja: There is no decrypt function, since crypt() uses a one-way algorithm.

Zobacz też:

  • md5() - Calculate the md5 hash of a string
  • The Mcrypt extension
  • The Unix man page for your crypt function for more information

crc32
echo
String Funkcje


Output one or more strings

crypt
explode
String Funkcje
PHP Manual

echo

(PHP 4, PHP 5)

echo — Output one or more strings

Opis

void echo ( string $arg1 [, string $... ] )

Outputs all parameters.

echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.

echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.

I have <?=$foo?> foo.

Parametry

arg1

The parameter to output.

...

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 echo() examples

<?php
echo "Hello World";

echo "This spans
multiple lines. The newlines will be
output as well";

echo "This spans\nmultiple lines. The newlines will be\noutput as well.";

echo "Escaping characters is done \"Like this\".";

// You can use variables inside of an echo statement
$foo = "foobar";
$bar = "barbaz";

echo "foo is $foo"; // foo is foobar

// You can also use arrays
$baz = array("value" => "foo");

echo "this is {$baz['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just echo variables
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

// Some people prefer passing multiple parameters to echo over concatenation.
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";

echo <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
END;

// Because echo does not behave like a function, the following code is invalid.
($some_var) ? echo 'true' : echo 'false';

// However, the following examples will work:
($some_var) ? print 'true' : print 'false'; // print is also a construct, but
                                            // it behaves like a function, so
                                            // it may be used in this context.
echo $some_var ? 'true': 'false'; // changing the statement around
?>

Notatki

Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Zobacz też:

  • print() - Output a string
  • printf() - Output a formatted string
  • flush() - Flush the output buffer
  • Heredoc syntax

crypt
explode
String Funkcje


Split a string by string

echo
fprintf
String Funkcje
PHP Manual

explode

(PHP 4, PHP 5)

explode — Split a string by string

Opis

array explode ( string $delimiter , string $string [, int $limit ] )

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

Parametry

delimiter

The boundary string.

string

The input string.

limit

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If the limit parameter is negative, all components except the last -limit are returned.

If the limit parameter is zero, then this is treated as 1.

Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the delimiter argument comes before the string argument.

Zwracane wartości

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

Rejestr zmian

Wersja | Opis
5.1.0 | Support for negative limits was added
4.0.1 | The limit parameter was added

Przykłady

Przykład #1 explode() examples

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

Przykład #2 limit parameter examples

<?php
$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?>

Powyższy przykład wyświetli:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • preg_split() - Split string by a regular expression
  • str_split() - Convert a string to an array
  • mb_split() - Split multibyte string using regular expression
  • str_word_count() - Return information about words used in a string
  • strtok() - Tokenize string
  • implode() - Join array elements with a string

echo
fprintf
String Funkcje


Write a formatted string to a stream

explode
get_html_translation_table
String Funkcje
PHP Manual

fprintf

(PHP 5)

fprintf — Write a formatted string to a stream

Opis

int fprintf ( resource $handle , string $format [, mixed $args [, mixed $... ]] )

Write a string produced according to format to the stream resource specified by handle.

Parametry

handle

Wskaźnik do systemu plików typu resource jest zazwyczaj tworzony poprzez funkcję fopen().

format

See sprintf() for a description of format.

args

...

Zwracane wartości

Returns the length of the string written.

Przykłady

Przykład #1 fprintf(): zero-padded integers

<?php
if (!($fp = fopen('date.txt', 'w'))) {
    return;
}

fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
// will write the formatted ISO date to date.txt
?>

Przykład #2 fprintf(): formatting currency

<?php
if (!($fp = fopen('currency.txt', 'w'))) {
    return;
}

$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$len = fprintf($fp, '%01.2f', $money);
// will write "123.10" to currency.txt

echo "wrote $len bytes to currency.txt";
// use the return value of fprintf to determine how many bytes we wrote
?>

Zobacz też:

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Przetwarza dane z pliku według formatu
  • vsprintf() - Return a formatted string
  • number_format() - Formatuje liczbę według szablonu

explode
get_html_translation_table
String Funkcje


Returns the translation table used by htmlspecialchars and htmlentities

fprintf
hebrev
String Funkcje
PHP Manual

get_html_translation_table

(PHP 4, PHP 5)

get_html_translation_table — Returns the translation table used by htmlspecialchars() and htmlentities()

Opis

array get_html_translation_table ([ int $table = HTML_SPECIALCHARS [, int $quote_style = ENT_COMPAT [, string $charset_hint ]]] )

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities() with the default charset.

Informacja:

Special characters can be encoded in several ways. E.g. " can be encoded as &quot;, &#34; or &#x22. get_html_translation_table() returns only the form used by htmlspecialchars() and htmlentities().

Parametry

table

There are two new constants (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want.

quote_style

Like the htmlspecialchars() and htmlentities() functions you can optionally specify the quote_style you are working with. See the description of these modes in htmlspecialchars().

charset_hint

Like htmlentities(), it takes an optional third argument charset which defines character set used in conversion. Presently, the ISO-8859-1 character set is used as the default.

Following character sets are supported in PHP 4.3.0 and later.

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Informacja: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

Zwracane wartości

Returns the translation table as an array.

Rejestr zmian

Wersja | Opis
5.3.4 | The charset_hint parameter was added.

Przykłady

Przykład #1 Translation Table Example

<?php
$trans = get_html_translation_table(HTML_ENTITIES);
$str = "Hallo & <Frau> & Krämer";
$encoded = strtr($str, $trans);

echo $encoded;
?>

Powyższy przykład wyświetli:

Hallo &amp; &lt;Frau&gt; &amp; Kr&auml;mer

Zobacz też:

  • htmlspecialchars() - Convert special characters to HTML entities
  • htmlentities() - Convert all applicable characters to HTML entities
  • html_entity_decode() - Convert all HTML entities to their applicable characters

fprintf
hebrev
String Funkcje


Convert logical Hebrew text to visual text

get_html_translation_table
hebrevc
String Funkcje
PHP Manual

hebrev

(PHP 4, PHP 5)

hebrev — Convert logical Hebrew text to visual text

Opis

string hebrev ( string $hebrew_text [, int $max_chars_per_line = 0 ] )

Converts logical Hebrew text to visual text.

The function tries to avoid breaking words.

Parametry

hebrew_text

A Hebrew input string.

max_chars_per_line

This optional parameter indicates maximum number of characters per line that will be returned.

Zwracane wartości

Returns the visual string.

Zobacz też:

  • hebrevc() - Convert logical Hebrew text to visual text with newline conversion

get_html_translation_table
hebrevc
String Funkcje


Convert logical Hebrew text to visual text with newline conversion

hebrev
hex2bin
String Funkcje
PHP Manual

hebrevc

(PHP 4, PHP 5)

hebrevc — Convert logical Hebrew text to visual text with newline conversion

Opis

string hebrevc ( string $hebrew_text [, int $max_chars_per_line = 0 ] )

This function is similar to hebrev() with the difference that it converts newlines (\n) to "<br>\n".

The function tries to avoid breaking words.

Parametry

hebrew_text

A Hebrew input string.

max_chars_per_line

This optional parameter indicates maximum number of characters per line that will be returned.

Zwracane wartości

Returns the visual string.

Zobacz też:

  • hebrev() - Convert logical Hebrew text to visual text

hebrev
hex2bin
String Funkcje


Convert hex to binary

hebrevc
html_entity_decode
String Funkcje
PHP Manual

hex2bin

(No version information available, might only be in SVN)

hex2bin — Convert hex to binary

Opis

string hex2bin ( string $data )

Converts the hex representation of data to binary

Parametry

data

Hexadecimal representation of data.

Zwracane wartości

Returns the binary representation of the given data.

Przykłady

Przykład #1 hex2bin() example

<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>

Powyższy przykład wyświetli coś podobnego do:

string(16) "example hex data"

Zobacz też:

  • bin2hex() - Convert binary data into hexadecimal representation
  • unpack() - Unpack data from binary string

hebrevc
html_entity_decode
String Funkcje


Convert all HTML entities to their applicable characters

hex2bin
htmlentities
String Funkcje
PHP Manual

html_entity_decode

(PHP 4 >= 4.3.0, PHP 5)

html_entity_decode — Convert all HTML entities to their applicable characters

Opis

string html_entity_decode ( string $string [, int $quote_style = ENT_COMPAT [, string $charset = 'UTF-8' ]] )

html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities to their applicable characters from string.

Parametry

string

The input string.

quote_style

The optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants:

Available quote_style constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.

charset

This defines the character set used in conversion. Using an empty string will activate automatic detection based on mbstring's internal encoding and current locale.

Following character sets are supported in PHP 4.3.0 and later.

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Informacja: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

Zwracane wartości

Returns the decoded string.

Rejestr zmian

Wersja | Opis
5.4.0 | Default charset changed from ISO-8859-1 to UTF-8.
5.0.0 | Support for multi-byte character sets was added.

Przykłady

Przykład #1 Decoding HTML entities

<?php
$orig = "I'll \"walk\" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

echo $b; // I'll "walk" the <b>dog</b> now

// For users prior to PHP 4.3.0 you may do this:
function unhtmlentities($string)
{
    // replace numeric entities
    $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
    $string = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $string);
    // replace literal entities
    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
    $trans_tbl = array_flip($trans_tbl);
    return strtr($string, $trans_tbl);
}

$c = unhtmlentities($a);

echo $c; // I'll "walk" the <b>dog</b> now

?>

Notatki

Informacja:

You might wonder why trim(html_entity_decode('&nbsp;')); doesn't reduce the string to an empty string, that's because the '&nbsp;' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 characterset.

Zobacz też:

  • htmlentities() - Convert all applicable characters to HTML entities
  • htmlspecialchars() - Convert special characters to HTML entities
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • urldecode() - Dekoduje łańcuchy zakodowane metodą kodowania URL'i

hex2bin
htmlentities
String Funkcje


Convert all applicable characters to HTML entities

html_entity_decode
htmlspecialchars_decode
String Funkcje
PHP Manual

htmlentities

(PHP 4, PHP 5)

htmlentities — Convert all applicable characters to HTML entities

Opis

string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $charset [, bool $double_encode = true ]]] )

This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

If you're wanting to decode instead (the reverse) you can use html_entity_decode().

Parametry

string

The input string.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_IGNORE | Silently discard invalid code unit sequences instead of returning an empty string. This is provided for backwards compatibility; avoid using it as it may have security implications.
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED | Replace code unit sequences, which are invalid in the specified document type, with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise).
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

charset

Like htmlspecialchars(), it takes an optional third argument charset which defines character set used in conversion. Presently, the ISO-8859-1 character set is used as the default. However, this default is very likely to change in future versions of PHP; the programmer is highly encouraged to specify a value.

Following character sets are supported in PHP 4.3.0 and later.

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Informacja: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

double_encode

When double_encode is turned off PHP will not encode existing html entities. The default is to convert everything.

Zwracane wartości

Returns the encoded string.

Rejestr zmian

Wersja | Opis
5.4.0 | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.0 | The constant ENT_IGNORE was added.
5.2.3 | The double_encode parameter was added.
4.1.0 | The charset parameter was added.
4.0.3 | The flags parameter was added.

Przykłady

Przykład #1 A htmlentities() example

<?php
$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

Przykład #2 Usage of ENT_IGNORE

<?php
$str = "\x8F!!!";

// Outputs an empty string
echo htmlentities($str, ENT_QUOTES, "UTF-8");

// Outputs "!!!"
echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>

Zobacz też:

  • html_entity_decode() - Convert all HTML entities to their applicable characters
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • htmlspecialchars() - Convert special characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • urlencode() - Koduje łańcuch metodą kodowania URLi

html_entity_decode
htmlspecialchars_decode
String Funkcje


Convert special HTML entities back to characters

htmlentities
htmlspecialchars
String Funkcje
PHP Manual

htmlspecialchars_decode

(PHP 5 >= 5.1.0)

htmlspecialchars_decode — Convert special HTML entities back to characters

Opis

string htmlspecialchars_decode ( string $string [, int $quote_style = ENT_COMPAT ] )

This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.

The converted entities are: &amp;, &quot; (when ENT_NOQUOTES is not set), &#039; (when ENT_QUOTES is set), &lt; and &gt;.

Parametry

string

The string to decode

quote_style

The quote style. One of the following constants:

quote_style constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone (default)
ENT_QUOTES | Will convert both double and single quotes
ENT_NOQUOTES | Will leave both double and single quotes unconverted

Zwracane wartości

Returns the decoded string.

Przykłady

Przykład #1 A htmlspecialchars_decode() example

<?php
$str = '<p>this -&gt; &quot;</p>';

echo htmlspecialchars_decode($str);

// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>

Powyższy przykład wyświetli:

<p>this -> "</p>
<p>this -> &quot;</p>

Zobacz też:

  • htmlspecialchars() - Convert special characters to HTML entities
  • html_entity_decode() - Convert all HTML entities to their applicable characters
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities

htmlentities
htmlspecialchars
String Funkcje


Convert special characters to HTML entities

htmlspecialchars_decode
implode
String Funkcje
PHP Manual

htmlspecialchars

(PHP 4, PHP 5)

htmlspecialchars — Convert special characters to HTML entities

Opis

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $charset [, bool $double_encode = true ]]] )

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.

The translations performed are:

  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes '&#039;' only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'

Parametry

string

The string being converted.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_IGNORE | Silently discard invalid code unit sequences instead of returning an empty string. This is provided for backwards compatibility; avoid using it as it may have security implications.
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED | Replace code unit sequences, which are invalid in the specified document type, with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise).
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

charset

Defines character set used in conversion. The default character set is ISO-8859-1.

For the purposes of this function, the charsets ISO-8859-1, ISO-8859-15, UTF-8, cp866, cp1251, cp1252, and KOI8-R are effectively equivalent, provided the string itself is valid for the character set, as the characters affected by htmlspecialchars() occupy the same positions in all of these charsets.

Following character sets are supported in PHP 4.3.0 and later.

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. This charset is supported in 4.3.2.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian. This charset is supported in 4.3.2.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, 932 | Japanese
EUC-JP | EUCJP | Japanese
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Informacja: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

double_encode

When double_encode is turned off PHP will not encode existing html entities, the default is to convert everything.

Zwracane wartości

The converted string.

If the input string contains an invalid code unit sequence within the given charset and the ENT_IGNORE flag is not set, then htmlspecialchars() will return an empty string.

Rejestr zmian

Wersja | Opis
5.4.0 | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.0 | The constant ENT_IGNORE was added.
5.2.3 | The double_encode parameter was added.
4.1.0 | The charset parameter was added.

Przykłady

Przykład #1 htmlspecialchars() example

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Notatki

Informacja:

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities().

Zobacz też:

  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • htmlspecialchars_decode() - Convert special HTML entities back to characters
  • strip_tags() - Strip HTML and PHP tags from a string
  • htmlentities() - Convert all applicable characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string

htmlspecialchars_decode
implode
String Funkcje


Join array elements with a string

htmlspecialchars
join
String Funkcje
PHP Manual

implode

(PHP 4, PHP 5)

implode — Join array elements with a string

Opis

string implode ( string $glue , array $pieces )
string implode ( array $pieces )

Join array elements with a glue string.

Informacja:

implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

Parametry

glue

Defaults to an empty string. This is not the preferred usage of implode() as glue would be the second parameter and thus, the bad prototype would be used.

pieces

The array of strings to implode.

Zwracane wartości

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Rejestr zmian

Wersja | Opis
4.3.0 | The glue parameter became optional.

Przykłady

Przykład #1 implode() example

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • explode() - Split a string by string
  • preg_split() - Split string by a regular expression

htmlspecialchars
join
String Funkcje


Alias dla implode

implode
lcfirst
String Funkcje
PHP Manual

join

(PHP 4, PHP 5)

join — Alias dla implode()

Opis

Ta funkcja jest aliasem dla: implode().

implode
lcfirst
String Funkcje


Make a string's first character lowercase

join
levenshtein
String Funkcje
PHP Manual

lcfirst

(PHP 5 >= 5.3.0)

lcfirst — Make a string's first character lowercase

Opis

string lcfirst ( string $str )

Returns a string with the first character of str , lowercased if that character is alphabetic.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Parametry

str

The input string.

Zwracane wartości

Returns the resulting string.

Przykłady

Przykład #1 lcfirst() example

<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo);             // helloWorld

$bar = 'HELLO WORLD!';
$bar = lcfirst($bar);             // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>

Zobacz też:

  • ucfirst() - Make a string's first character uppercase
  • strtolower() - Zmienia wszystkie litery w łańcuchu na małe
  • strtoupper() - Zmienia wszystkie litery w łańcuchu na duże
  • ucwords() - Uppercase the first character of each word in a string

join
levenshtein
String Funkcje


Calculate Levenshtein distance between two strings

lcfirst
localeconv
String Funkcje
PHP Manual

levenshtein

(PHP 4 >= 4.0.1, PHP 5)

levenshtein — Calculate Levenshtein distance between two strings

Opis

int levenshtein ( string $str1 , string $str2 )
int levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del )

The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).

In its simplest form the function will take only the two strings as parameter and will calculate just the number of insert, replace and delete operations needed to transform str1 into str2.

A second variant will take three additional parameters that define the cost of insert, replace and delete operations. This is more general and adaptive than variant one, but not as efficient.

Parametry

str1

One of the strings being evaluated for Levenshtein distance.

str2

One of the strings being evaluated for Levenshtein distance.

cost_ins

Defines the cost of insertion.

cost_rep

Defines the cost of replacement.

cost_del

Defines the cost of deletion.

Zwracane wartości

This function returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters.

Przykłady

Przykład #1 levenshtein() example

<?php
// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // check for an exact match
    if ($lev == 0) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

?>

Powyższy przykład wyświetli:

Input word: carrrot
Did you mean: carrot?

Zobacz też:

  • soundex() - Calculate the soundex key of a string
  • similar_text() - Calculate the similarity between two strings
  • metaphone() - Calculate the metaphone key of a string

lcfirst
localeconv
String Funkcje


Get numeric formatting information

levenshtein
ltrim
String Funkcje
PHP Manual

localeconv

(PHP 4 >= 4.0.5, PHP 5)

localeconv — Get numeric formatting information

Opis

array localeconv ( void )

Returns an associative array containing localized numeric and monetary formatting information.

Zwracane wartości

localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:

Array element | Description
decimal_point | Decimal point character
thousands_sep | Thousands separator
grouping | Array containing numeric groupings
int_curr_symbol | International currency symbol (i.e. USD)
currency_symbol | Local currency symbol (i.e. $)
mon_decimal_point | Monetary decimal point character
mon_thousands_sep | Monetary thousands separator
mon_grouping | Array containing monetary groupings
positive_sign | Sign for positive values
negative_sign | Sign for negative values
int_frac_digits | International fractional digits
frac_digits | Local fractional digits
p_cs_precedes | TRUE if currency_symbol precedes a positive value, FALSE if it succeeds one
p_sep_by_space | TRUE if a space separates currency_symbol from a positive value, FALSE otherwise
n_cs_precedes | TRUE if currency_symbol precedes a negative value, FALSE if it succeeds one
n_sep_by_space | TRUE if a space separates currency_symbol from a negative value, FALSE otherwise
p_sign_posn
  • 0 - Parentheses surround the quantity and currency_symbol
  • 1 - The sign string precedes the quantity and currency_symbol
  • 2 - The sign string succeeds the quantity and currency_symbol
  • 3 - The sign string immediately precedes the currency_symbol
  • 4 - The sign string immediately succeeds the currency_symbol
n_sign_posn
  • 0 - Parentheses surround the quantity and currency_symbol
  • 1 - The sign string precedes the quantity and currency_symbol
  • 2 - The sign string succeeds the quantity and currency_symbol
  • 3 - The sign string immediately precedes the currency_symbol
  • 4 - The sign string immediately succeeds the currency_symbol

The p_sign_posn, and n_sign_posn contain a string of formatting options. Each number representing one of the above listed conditions.

The grouping fields contain arrays that define the way numbers should be grouped. For example, the monetary grouping field for the nl_NL locale (in UTF-8 mode with the euro sign), would contain a 2 item array with the values 3 and 3. The higher the index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further grouping is done. If an array element is equal to 0, the previous element should be used.

Przykłady

Przykład #1 localeconv() example

<?php
if (false !== setlocale(LC_ALL, 'nl_NL.UTF-8@euro')) {
    $locale_info = localeconv();
    print_r($locale_info);
}
?>

Powyższy przykład wyświetli:

Array
(
    [decimal_point] => .
    [thousands_sep] =>
    [int_curr_symbol] => EUR
    [currency_symbol] => €
    [mon_decimal_point] => ,
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] => -
    [int_frac_digits] => 2
    [frac_digits] => 2
    [p_cs_precedes] => 1
    [p_sep_by_space] => 1
    [n_cs_precedes] => 1
    [n_sep_by_space] => 1
    [p_sign_posn] => 1
    [n_sign_posn] => 2
    [grouping] => Array
        (
        )

    [mon_grouping] => Array
        (
            [0] => 3
            [1] => 3
        )

)

Zobacz też:

  • setlocale() - Set locale information

levenshtein
ltrim
String Funkcje


Strip whitespace (or other characters) from the beginning of a string

localeconv
md5_file
String Funkcje
PHP Manual

ltrim

(PHP 4, PHP 5)

ltrim — Strip whitespace (or other characters) from the beginning of a string

Opis

string ltrim ( string $str [, string $charlist ] )

Strip whitespace (or other characters) from the beginning of a string.

Parametry

str

The input string.

charlist

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Zwracane wartości

This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Rejestr zmian

Wersja | Opis
4.1.0 | The charlist parameter was added.

Przykłady

Przykład #1 Usage example of ltrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = ltrim($text);
var_dump($trimmed);

$trimmed = ltrim($text, " \t.");
var_dump($trimmed);

$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the beginning of $binary
// (from 0 to 31 inclusive)
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);

?>

Powyższy przykład wyświetli:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "These are a few words :) ...  "
string(30) "These are a few words :) ...  "
string(7) "o World"
string(15) "Example string
"

Zobacz też:

  • trim() - Strip whitespace (or other characters) from the beginning and end of a string
  • rtrim() - Strip whitespace (or other characters) from the end of a string

localeconv
md5_file
String Funkcje


Calculates the md5 hash of a given file

ltrim
md5
String Funkcje
PHP Manual

md5_file

(PHP 4 >= 4.2.0, PHP 5)

md5_file — Calculates the md5 hash of a given file

Opis

string md5_file ( string $filename [, bool $raw_output = false ] )

Calculates the MD5 hash of the file specified by the filename parameter using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number.

Parametry

filename

The filename

raw_output

When TRUE, returns the digest in raw binary format with a length of 16.

Zwracane wartości

Returns a string on success, FALSE otherwise.

Rejestr zmian

Wersja | Opis
5.0.0 | Added the raw_output parameter
5.1.0 | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')

Przykłady

Przykład #1 Usage example of md5_file()

<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';

echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
?>

Zobacz też:

  • md5() - Calculate the md5 hash of a string
  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string

ltrim
md5
String Funkcje


Calculate the md5 hash of a string

md5_file
metaphone
String Funkcje
PHP Manual

md5

(PHP 4, PHP 5)

md5 — Calculate the md5 hash of a string

Opis

string md5 ( string $str [, bool $raw_output = false ] )

Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.

Parametry

str

The string.

raw_output

If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

Zwracane wartości

Returns the hash as a 32-character hexadecimal number.

Rejestr zmian

Wersja | Opis
5.0.0 | The raw_output parameter was added.

Przykłady

Przykład #1 A md5() example

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
}
?>

Notatki

Informacja: Secure password hashing

It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See here for details.

Zobacz też:

  • md5_file() - Calculates the md5 hash of a given file
  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string
  • sha1() - Calculate the sha1 hash of a string
  • hash() - Generate a hash value (message digest)

md5_file
metaphone
String Funkcje


Calculate the metaphone key of a string

md5
money_format
String Funkcje
PHP Manual

metaphone

(PHP 4, PHP 5)

metaphone — Calculate the metaphone key of a string

Opis

string metaphone ( string $str [, int $phonemes = 0 ] )

Calculates the metaphone key of str.

Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.

Metaphone was developed by Lawrence Philips <lphilips at verity dot com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

Parametry

str

The input string.

phonemes

This parameter restricts the returned metaphone key to phonemes characters in length. The default value of 0 means no restriction.

Zwracane wartości

Returns the metaphone key as a string, lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 metaphone() basic example

<?php
var_dump(metaphone('programming'));
var_dump(metaphone('programmer'));
?>

Powyższy przykład wyświetli coś podobnego do:

string(7) "PRKRMNK"
string(6) "PRKRMR"

Przykład #2 Using the phonemes parameter

<?php
var_dump(metaphone('programming', 5));
var_dump(metaphone('programmer', 5));
?>

Powyższy przykład wyświetli coś podobnego do:

string(5) "PRKRM"
string(5) "PRKRM"

md5
money_format
String Funkcje


Formats a number as a currency string

metaphone
nl_langinfo
String Funkcje
PHP Manual

money_format

(PHP 4 >= 4.3.0, PHP 5)

money_format — Formats a number as a currency string

Opis

string money_format ( string $format , float $number )

money_format() returns a formatted version of number. This function wraps the C library function strfmon(), with the difference that this implementation converts only one number at a time.

Parametry

format

The format specification consists of the following sequence:

  • a % character

  • optional flags

  • optional field width

  • optional left precision

  • optional right precision

  • a required conversion character

Flags

One or more of the optional flags below can be used:

=f

The character = followed by a (single byte) character f to be used as the numeric fill character. The default fill character is space.

^

Disable the use of grouping characters (as defined by the current locale).

+ or (

Specify the formatting style for positive and negative numbers. If + is used, the locale's equivalent for + and - will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +.

!

Suppress the currency symbol from the output string.

-

If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left).

Field width

w

A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag - is used. Default value is 0 (zero).

Left precision

#n

The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored.

If grouping has not been suppressed using the ^ flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit.

To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length.

Right precision

.p

A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current local in use. The amount being formatted is rounded to the specified number of digits prior to formatting.

Conversion characters

i

The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56).

n

The number is formatted according to the locale's national currency format (e.g. for the de_DE locale: EU1.234,56).

%

Returns the % character.

number

The number to be formatted.

Zwracane wartości

Returns the formatted string. Characters before and after the formatting string will be returned unchanged. Non-numeric number causes returning NULL and emitting E_WARNING.

Notatki

Informacja:

The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.

Informacja:

The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.

Przykłady

Przykład #1 money_format() Example

We will use different locales and format specifications to illustrate the use of this function.

<?php

$number = 1234.56;

// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56

// Italian national format with 2 decimals`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// Eu 1.234,56

// Using a negative number
$number = -1234.5672;

// US national format, using () for negative numbers
// and 10 digits for left precision
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($        1,234.57)

// Similar format as above, adding the use of 2 digits of right
// precision and '*' as a fill character
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)

// Let's justify to the left, with 14 positions of width, 8 digits of
// left precision, 2 of right precision, withouth grouping character
// and using the international format for the de_DE locale.
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// Eu 1234,56****

// Let's add some blurb before and after the conversion specification
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'The final value is %i (after a 10%% discount)';
echo money_format($fmt, 1234.56) . "\n";
// The final value is  GBP 1,234.56 (after a 10% discount)

?>

Zobacz też:

  • setlocale() - Set locale information
  • sscanf() - Parses input from a string according to a format
  • sprintf() - Return a formatted string
  • printf() - Output a formatted string
  • number_format() - Formatuje liczbę według szablonu

metaphone
nl_langinfo
String Funkcje


Query language and locale information

money_format
nl2br
String Funkcje
PHP Manual

nl_langinfo

(PHP 4 >= 4.1.0, PHP 5)

nl_langinfo — Query language and locale information

Opis

string nl_langinfo ( int $item )

nl_langinfo() is used to access individual elements of the locale categories. Unlike localeconv(), which returns all of the elements, nl_langinfo() allows you to select any specific element.

Parametry

item

item may be an integer value of the element or the constant name of the element. The following is a list of constant names for item that may be used and their description. Some of these constants may not be defined or hold no value for certain locales.

nl_langinfo Constants
Constant | Description
LC_TIME Category Constants
ABDAY_(1-7) | Abbreviated name of n-th day of the week.
DAY_(1-7) | Name of the n-th day of the week (DAY_1 = Sunday).
ABMON_(1-12) | Abbreviated name of the n-th month of the year.
MON_(1-12) | Name of the n-th month of the year.
AM_STR | String for Ante meridian.
PM_STR | String for Post meridian.
D_T_FMT | String that can be used as the format string for strftime() to represent time and date.
D_FMT | String that can be used as the format string for strftime() to represent date.
T_FMT | String that can be used as the format string for strftime() to represent time.
T_FMT_AMPM | String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian.
ERA | Alternate era.
ERA_YEAR | Year in alternate era format.
ERA_D_T_FMT | Date and time in alternate era format (string can be used in strftime()).
ERA_D_FMT | Date in alternate era format (string can be used in strftime()).
ERA_T_FMT | Time in alternate era format (string can be used in strftime()).
LC_MONETARY Category Constants
INT_CURR_SYMBOL | International currency symbol.
CURRENCY_SYMBOL | Local currency symbol.
CRNCYSTR | Same value as CURRENCY_SYMBOL.
MON_DECIMAL_POINT | Decimal point character.
MON_THOUSANDS_SEP | Thousands separator (groups of three digits).
MON_GROUPING | Like "grouping" element.
POSITIVE_SIGN | Sign for positive values.
NEGATIVE_SIGN | Sign for negative values.
INT_FRAC_DIGITS | International fractional digits.
FRAC_DIGITS | Local fractional digits.
P_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a positive value.
P_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a positive value.
N_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a negative value.
N_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a negative value.
P_SIGN_POSN
  • Returns 0 if parentheses surround the quantity and CURRENCY_SYMBOL.
  • Returns 1 if the sign string precedes the quantity and CURRENCY_SYMBOL.
  • Returns 2 if the sign string follows the quantity and CURRENCY_SYMBOL.
  • Returns 3 if the sign string immediately precedes the CURRENCY_SYMBOL.
  • Returns 4 if the sign string immediately follows the CURRENCY_SYMBOL.
N_SIGN_POSN
LC_NUMERIC Category Constants
DECIMAL_POINT | Decimal point character.
RADIXCHAR | Same value as DECIMAL_POINT.
THOUSANDS_SEP | Separator character for thousands (groups of three digits).
THOUSEP | Same value as THOUSANDS_SEP.
GROUPING
LC_MESSAGES Category Constants
YESEXPR | Regex string for matching "yes" input.
NOEXPR | Regex string for matching "no" input.
YESSTR | Output string for "yes".
NOSTR | Output string for "no".
LC_CTYPE Category Constants
CODESET | Return a string with the name of the character encoding.

Zwracane wartości

Returns the element as a string, or FALSE if item is not valid.

Notatki

Informacja: Ta funkcja nie jest dostępna na platformie Windows.

Zobacz też:

  • setlocale() - Set locale information
  • localeconv() - Get numeric formatting information

money_format
nl2br
String Funkcje


Inserts HTML line breaks before all newlines in a string

nl_langinfo
number_format
String Funkcje
PHP Manual

nl2br

(PHP 4, PHP 5)

nl2br — Inserts HTML line breaks before all newlines in a string

Opis

string nl2br ( string $string [, bool $is_xhtml = true ] )

Returns string with '<br />' or '<br>' inserted before all newlines (\r\n, \n\r, \n and \r).

Parametry

string

The input string.

is_xhtml

Whenever to use XHTML compatible line breaks or not.

Zwracane wartości

Returns the altered string.

Przykłady

Przykład #1 Using nl2br()

<?php
echo nl2br("foo isn't\n bar");
?>

Powyższy przykład wyświetli:

foo isn't<br />
 bar

Przykład #2 Generating valid HTML markup using the is_xhtml parameter

<?php
echo nl2br("Welcome\r\nThis is my HTML document", false);
?>

Powyższy przykład wyświetli:

Welcome<br>
This is my HTML document

Przykład #3 Various newline separators

<?php
$string = "This\r\nis\n\ra\nstring\r";
echo nl2br($string);
?>

Powyższy przykład wyświetli:

This<br />
is<br />
a<br />
string<br />

Rejestr zmian

Wersja | Opis
5.3.0 | Added the optional is_xhtml parameter.
4.0.5 | nl2br() is now XHTML compliant. All older versions will return string with '<br>' inserted before newlines instead of '<br />'.

Zobacz też:

  • htmlspecialchars() - Convert special characters to HTML entities
  • htmlentities() - Convert all applicable characters to HTML entities
  • wordwrap() - Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.
  • str_replace() - Replace all occurrences of the search string with the replacement string

nl_langinfo
number_format
String Funkcje


Formatuje liczbę według szablonu

nl2br
ord
String Funkcje
PHP Manual

number_format

(PHP 4, PHP 5)

number_format — Formatuje liczbę według szablonu

Opis

string number_format ( float $liczba [, int $miejsc_dziesiętnych [, string $przecinek_dziesiętny ]], string $separator_tysięcy )

Funkcja number_format() zwraca sformatowaną liczbę liczba według podanych argumentów. Ta funkcja przyjmuje jeden, dwa lub cztery argumenty (nie trzy):

Jeśli podany jest tylko jeden argument, liczba zostanie sformatowana bez miejsc dziesiętnych ale z przecinkiem (",") pomiędzy każdą grupą tysięcy.

Jeśli podane są dwa argumenty, liczba będzie sformatowana z miejsc_dziesiętnych, z kropką (".") w charakterze przecinka dziesiętnego i przecinkiem (",") pomiędzy każdą grupą tysięcy.

Kiedy wszystkie cztery parametry są podane, liczba będzie sformatowana z miejsc_dziesiętnych, z przecinek_dziesiętny zamiast kropki (".") i separator_tysięcy pomiędzy każdą grupą tysięcy.

Informacja:

Tylko pierwszy znak z separator_tysięcy jest wykorzystywany. Na przykład, jeśli użyjesz foo jako separatora, to z liczby 1000 funkcja zwróci 1f000.

Przykład #1 number_format() - przykłady

W polskiej notacji liczbowej używa się przecinka (",") jako przecinka dziesiętnego i spacji (" ") jako separatora tysięcy. W PHP można to zrobić tak:

<?php

    $liczba = 1234.56;

    // notacja angielska (domyślna)
    $notacja_angielska = number_format($liczba);
    // 1,234.56

    // notacja polska
    $notacja_polska = number_format($liczba, 2, ',', ' ');
    // 1 234,56

    $number = 1234.5678;

    // notacja angielska bez separatora tysięcy
    $notacja_angielska = number_format($liczba, 2, '.', '');
    // 1234.57

?>

Patrz także: money_format(), sprintf(), printf() i sscanf().

nl2br
ord
String Funkcje


Return ASCII value of character

number_format
parse_str
String Funkcje
PHP Manual

ord

(PHP 4, PHP 5)

ord — Return ASCII value of character

Opis

int ord ( string $string )

Returns the ASCII value of the first character of string.

This function complements chr().

Parametry

string

A character.

Zwracane wartości

Returns the ASCII value as an integer.

Przykłady

Przykład #1 ord() example

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}
?>

Zobacz też:

  • chr() - Return a specific character
  • An » ASCII-table

number_format
parse_str
String Funkcje


Parses the string into variables

ord
print
String Funkcje
PHP Manual

parse_str

(PHP 4, PHP 5)

parse_str — Parses the string into variables

Opis

void parse_str ( string $str [, array &$arr ] )

Parses str as if it were the query string passed via a URL and sets variables in the current scope.

Informacja:

To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from external sources.

Informacja:

The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.

Parametry

str

The input string.

arr

If the second parameter arr is present, variables are stored in this variable as array elements instead.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
4.0.3 | The arr parameter was added

Przykłady

Przykład #1 Using parse_str()

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

Zobacz też:

  • parse_url() - Przetwarza adres URL i zwraca jego składowe
  • pathinfo() - Zwraca informacje o ścieżce do pliku
  • http_build_query() - Generate URL-encoded query string
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • urldecode() - Dekoduje łańcuchy zakodowane metodą kodowania URL'i

ord
print
String Funkcje


Output a string

parse_str
printf
String Funkcje
PHP Manual

print

(PHP 4, PHP 5)

print — Output a string

Opis

int print ( string $arg )

Outputs arg.

print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.

Parametry

arg

The input data.

Zwracane wartości

Returns 1, always.

Przykłady

Przykład #1 print() examples

<?php
print("Hello World");

print "print() also works without parentheses.";

print "This spans
multiple lines. The newlines will be
output as well";

print "This spans\nmultiple lines. The newlines will be\noutput as well.";

print "escaping characters is done \"Like this\".";

// You can use variables inside a print statement
$foo = "foobar";
$bar = "barbaz";

print "foo is $foo"; // foo is foobar

// You can also use arrays
$bar = array("value" => "foo");

print "this is {$bar['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
print 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just print variables
print $foo;          // foobar

print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
?>

Notatki

Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Zobacz też:

  • echo() - Output one or more strings
  • printf() - Output a formatted string
  • flush() - Flush the output buffer
  • Heredoc syntax

parse_str
printf
String Funkcje


Output a formatted string

print
quoted_printable_decode
String Funkcje
PHP Manual

printf

(PHP 4, PHP 5)

printf — Output a formatted string

Opis

int printf ( string $format [, mixed $args [, mixed $... ]] )

Produces output according to format.

Parametry

format

See sprintf() for a description of format.

args

...

Zwracane wartości

Returns the length of the outputted string.

Zobacz też:

  • print() - Output a string
  • sprintf() - Return a formatted string
  • vprintf() - Output a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Przetwarza dane z pliku według formatu
  • flush() - Flush the output buffer

print
quoted_printable_decode
String Funkcje


Convert a quoted-printable string to an 8 bit string

printf
quoted_printable_encode
String Funkcje
PHP Manual

quoted_printable_decode

(PHP 4, PHP 5)

quoted_printable_decode — Convert a quoted-printable string to an 8 bit string

Opis

string quoted_printable_decode ( string $str )

This function returns an 8-bit binary string corresponding to the decoded quoted printable string (according to » RFC2045, section 6.7, not » RFC2821, section 4.5.2, so additional periods are not stripped from the beginning of line).

This function is similar to imap_qprint(), except this one does not require the IMAP module to work.

Parametry

str

The input string.

Zwracane wartości

Returns the 8-bit binary string.

Zobacz też:

  • quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string

printf
quoted_printable_encode
String Funkcje


Convert a 8 bit string to a quoted-printable string

quoted_printable_decode
quotemeta
String Funkcje
PHP Manual

quoted_printable_encode

(PHP 5 >= 5.3.0)

quoted_printable_encode — Convert a 8 bit string to a quoted-printable string

Opis

string quoted_printable_encode ( string $str )

Returns a quoted printable string created according to » RFC2045, section 6.7.

This function is similar to imap_8bit(), except this one does not require the IMAP module to work.

Parametry

str

The input string.

Zwracane wartości

Returns the encoded string.

Zobacz też:

  • quoted_printable_decode() - Convert a quoted-printable string to an 8 bit string
  • iconv_mime_encode() - Composes a MIME header field

quoted_printable_decode
quotemeta
String Funkcje


Quote meta characters

quoted_printable_encode
rtrim
String Funkcje
PHP Manual

quotemeta

(PHP 4, PHP 5)

quotemeta — Quote meta characters

Opis

string quotemeta ( string $str )

Returns a version of str with a backslash character (\) before every character that is among these:

. \ + * ? [ ^ ] ( $ )

Parametry

str

The input string.

Zwracane wartości

Returns the string with meta characters quoted, or FALSE if an empty string is given as str.

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • addslashes() - Quote string with slashes
  • addcslashes() - Quote string with slashes in a C style
  • htmlentities() - Convert all applicable characters to HTML entities
  • htmlspecialchars() - Convert special characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • stripslashes() - Un-quotes a quoted string
  • stripcslashes() - Un-quote string quoted with addcslashes
  • preg_match() - Perform a regular expression match
  • preg_quote() - Quote regular expression characters

quoted_printable_encode
rtrim
String Funkcje


Strip whitespace (or other characters) from the end of a string

quotemeta
setlocale
String Funkcje
PHP Manual

rtrim

(PHP 4, PHP 5)

rtrim — Strip whitespace (or other characters) from the end of a string

Opis

string rtrim ( string $str [, string $charlist ] )

This function returns a string with whitespace stripped from the end of str.

Without the second parameter, rtrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parametry

str

The input string.

charlist

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Zwracane wartości

Returns the modified string.

Rejestr zmian

Wersja | Opis
4.1.0 | The charlist parameter was added.

Przykłady

Przykład #1 Usage example of rtrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = rtrim($text);
var_dump($trimmed);

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the end of $binary
// (from 0 to 31 inclusive)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);

?>

Powyższy przykład wyświetli:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "        These are a few words :) ..."
string(26) "        These are a few words :)"
string(9) "Hello Wor"
string(15) "    Example string"

Zobacz też:

  • trim() - Strip whitespace (or other characters) from the beginning and end of a string
  • ltrim() - Strip whitespace (or other characters) from the beginning of a string

quotemeta
setlocale
String Funkcje


Set locale information

rtrim
sha1_file
String Funkcje
PHP Manual

setlocale

(PHP 4, PHP 5)

setlocale — Set locale information

Opis

string setlocale ( int $category , string $locale [, string $... ] )
string setlocale ( int $category , array $locale )

Sets locale information.

Parametry

category

category is a named constant specifying the category of the functions affected by the locale setting:

  • LC_ALL for all of the below
  • LC_COLLATE for string comparison, see strcoll()
  • LC_CTYPE for character classification and conversion, for example strtoupper()
  • LC_MONETARY for localeconv()
  • LC_NUMERIC for decimal separator (See also localeconv())
  • LC_TIME for date and time formatting with strftime()
  • LC_MESSAGES for system responses (available if PHP was compiled with libintl)

locale

If locale is NULL or the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".

If locale is "0", the locale setting is not affected, only the current setting is returned.

If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.

...

(Optional string or array parameters to try as locale settings until success.)

Informacja:

On Windows, setlocale(LC_ALL, '') sets the locale names from the system's regional/language settings (accessible via Control Panel).

Zwracane wartości

Returns the new current locale, or FALSE if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid.

An invalid category name also causes a warning message. Category/locale names can be found in » RFC 1766 and » ISO 639. Different systems have different naming schemes for locales.

Informacja:

The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns.

Rejestr zmian

Wersja | Opis
5.3.0 | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.
4.3.0 | Passing multiple locales became possible.
4.2.0 | Passing category as a string is now deprecated, use the above constants instead. Passing them as a string (within quotes) will result in a warning message.

Przykłady

Przykład #1 setlocale() Examples

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german as of PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Przykład #2 setlocale() Examples for Windows

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nld_nld');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german as of PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Notatki

Ostrzeżenie

The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS or Apache on Windows, you may experience sudden changes in locale settings while a script is running, though the script itself never called setlocale(). This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using setlocale().

Wskazówka

Windows users will find useful information about locale strings at Microsoft's MSDN website. Supported language strings can be found at » http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp and supported country/region strings at » http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp.

rtrim
sha1_file
String Funkcje


Calculate the sha1 hash of a file

setlocale
sha1
String Funkcje
PHP Manual

sha1_file

(PHP 4 >= 4.3.0, PHP 5)

sha1_file — Calculate the sha1 hash of a file

Opis

string sha1_file ( string $filename [, bool $raw_output = false ] )

Calculates the sha1 hash of the file specified by filename using the » US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number.

Parametry

filename

The filename of the file to hash.

raw_output

When TRUE, returns the digest in raw binary format with a length of 20.

Zwracane wartości

Returns a string on success, FALSE otherwise.

Przykłady

Przykład #1 sha1_file() example

<?php
foreach(glob('/home/Kalle/myproject/*.php') as $ent)
{
    if(is_dir($ent))
    {
        continue;
    }

    echo $ent . ' (SHA1: ' . sha1_file($ent) . ')', PHP_EOL;
}
?>

Rejestr zmian

Wersja | Opis
5.1.0 | Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')
5.0.0 | Added the raw_output parameter

Zobacz też:

  • sha1() - Calculate the sha1 hash of a string
  • md5_file() - Calculates the md5 hash of a given file
  • crc32() - Calculates the crc32 polynomial of a string

setlocale
sha1
String Funkcje


Calculate the sha1 hash of a string

sha1_file
similar_text
String Funkcje
PHP Manual

sha1

(PHP 4 >= 4.3.0, PHP 5)

sha1 — Calculate the sha1 hash of a string

Opis

string sha1 ( string $str [, bool $raw_output = false ] )

Calculates the sha1 hash of str using the » US Secure Hash Algorithm 1.

Parametry

str

The input string.

raw_output

If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number.

Zwracane wartości

Returns the sha1 hash as a string.

Rejestr zmian

Wersja | Opis
5.0.0 | The raw_output parameter was added.

Przykłady

Przykład #1 A sha1() example

<?php
$str = 'apple';

if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo "Would you like a green or red apple?";
}
?>

Notatki

Informacja: Secure password hashing

It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See here for details.

Zobacz też:

  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string
  • md5() - Calculate the md5 hash of a string
  • hash() - Generate a hash value (message digest)

sha1_file
similar_text
String Funkcje


Calculate the similarity between two strings

sha1
soundex
String Funkcje
PHP Manual

similar_text

(PHP 4, PHP 5)

similar_text — Calculate the similarity between two strings

Opis

int similar_text ( string $first , string $second [, float &$percent ] )

This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

Parametry

first

The first string.

second

The second string.

percent

By passing a reference as third argument, similar_text() will calculate the similarity in percent for you.

Zwracane wartości

Returns the number of matching chars in both strings.

Zobacz też:

  • levenshtein() - Calculate Levenshtein distance between two strings
  • soundex() - Calculate the soundex key of a string

sha1
soundex
String Funkcje


Calculate the soundex key of a string

similar_text
sprintf
String Funkcje
PHP Manual

soundex

(PHP 4, PHP 5)

soundex — Calculate the soundex key of a string

Opis

string soundex ( string $str )

Calculates the soundex key of str.

Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.

This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.

Parametry

str

The input string.

Zwracane wartości

Returns the soundex key as a string.

Przykłady

Przykład #1 Soundex Examples

<?php
soundex("Euler")       == soundex("Ellery");    // E460
soundex("Gauss")       == soundex("Ghosh");     // G200
soundex("Hilbert")     == soundex("Heilbronn"); // H416
soundex("Knuth")       == soundex("Kant");      // K530
soundex("Lloyd")       == soundex("Ladd");      // L300
soundex("Lukasiewicz") == soundex("Lissajous"); // L222
?>

Zobacz też:

  • levenshtein() - Calculate Levenshtein distance between two strings
  • metaphone() - Calculate the metaphone key of a string
  • similar_text() - Calculate the similarity between two strings

similar_text
sprintf
String Funkcje


Return a formatted string

soundex
sscanf
String Funkcje
PHP Manual

sprintf

(PHP 4, PHP 5)

sprintf — Return a formatted string

Opis

string sprintf ( string $format [, mixed $args [, mixed $... ]] )

Returns a string produced according to the formatting string format.

Parametry

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

  1. An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.
  2. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
  3. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
  4. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
  5. An optional precision specifier in the form of a period (`.') followed by an optional decimal digit string that says how many decimal digits should be displayed for floating-point numbers. When using this specifier on a string, it acts as a cutoff point, setting a maximum character limit to the string.

  6. A type specifier that says what type the argument data should be treated as. Possible types:

    • % - a literal percent character. No argument is required.
    • b - the argument is treated as an integer, and presented as a binary number.
    • c - the argument is treated as an integer, and presented as the character with that ASCII value.
    • d - the argument is treated as an integer, and presented as a (signed) decimal number.
    • e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
    • E - like %e but uses uppercase letter (e.g. 1.2E+2).
    • u - the argument is treated as an integer, and presented as an unsigned decimal number.
    • f - the argument is treated as a float, and presented as a floating-point number (locale aware).
    • F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
    • g - shorter of %e and %f.
    • G - shorter of %E and %f.
    • o - the argument is treated as an integer, and presented as an octal number.
    • s - the argument is treated as and presented as a string.
    • x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    • X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

The format string supports argument numbering/swapping. Here is an example:

Przykład #1 Argument swapping

<?php
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
printf($format, $num, $location);
?>
This will output "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:

Przykład #2 Argument swapping

<?php
$format = 'The %s contains %d monkeys';
printf($format, $num, $location);
?>
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

Przykład #3 Argument swapping

<?php
$format = 'The %2$s contains %1$d monkeys';
printf($format, $num, $location);
?>
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:

Przykład #4 Argument swapping

<?php
$format = 'The %2$s contains %1$d monkeys.
           That\'s a nice %2$s full of %1$d monkeys.';
printf($format, $num, $location);
?>
When using argument swapping, the n$ position specifier must come immediately after the percent sign (%), before any other specifiers, as shown in the example below.

Przykład #5 Position specifier with other specifiers

<?php
$format= 'The %2$s contains %1$04d monkeys';
printf($format, $num, $location);
?>

Powyższy przykład wyświetli:

The tree contains 0005 monkeys

args

...

Zwracane wartości

Returns a string produced according to the formatting string format.

Rejestr zmian

Wersja | Opis
4.0.6 | Support for argument numbering/swapping was added

Przykłady

Przykład #6 printf(): various examples

<?php
$n =  43951789;
$u = -43951789;
$c = 65; // ASCII 65 is 'A'

// notice the double %%, this prints a literal '%' character
printf("%%b = '%b'\n", $n); // binary representation
printf("%%c = '%c'\n", $c); // print the ascii character, same as chr() function
printf("%%d = '%d'\n", $n); // standard integer representation
printf("%%e = '%e'\n", $n); // scientific notation
printf("%%u = '%u'\n", $n); // unsigned integer representation of a positive integer
printf("%%u = '%u'\n", $u); // unsigned integer representation of a negative integer
printf("%%f = '%f'\n", $n); // floating point representation
printf("%%o = '%o'\n", $n); // octal representation
printf("%%s = '%s'\n", $n); // string representation
printf("%%x = '%x'\n", $n); // hexadecimal representation (lower-case)
printf("%%X = '%X'\n", $n); // hexadecimal representation (upper-case)

printf("%%+d = '%+d'\n", $n); // sign specifier on a positive integer
printf("%%+d = '%+d'\n", $u); // sign specifier on a negative integer
?>

Powyższy przykład wyświetli:

%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'

Przykład #7 printf(): string specifiers

<?php
$s = 'monkey';
$t = 'many monkeys';

printf("[%s]\n",      $s); // standard string output
printf("[%10s]\n",    $s); // right-justification with spaces
printf("[%-10s]\n",   $s); // left-justification with spaces
printf("[%010s]\n",   $s); // zero-padding works on strings too
printf("[%'#10s]\n",  $s); // use the custom padding character '#'
printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters
?>

Powyższy przykład wyświetli:

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[many monke]

Przykład #8 sprintf(): zero-padded integers

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Przykład #9 sprintf(): formatting currency

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
?>

Przykład #10 sprintf(): scientific notation

<?php
$number = 362525200;

echo sprintf("%.3e", $number); // outputs 3.625e+8
?>

Zobacz też:

  • printf() - Output a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Przetwarza dane z pliku według formatu
  • vsprintf() - Return a formatted string
  • number_format() - Formatuje liczbę według szablonu

soundex
sscanf
String Funkcje


Parses input from a string according to a format

sprintf
str_getcsv
String Funkcje
PHP Manual

sscanf

(PHP 4 >= 4.0.1, PHP 5)

sscanf — Parses input from a string according to a format

Opis

mixed sscanf ( string $str , string $format [, mixed &$... ] )

The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format, which is described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the input string. This means that even a tab \t in the format string can match a single space character in the input string.

Parametry

str

The input string being parsed.

format

The interpreted format for str, which is described in the documentation for sprintf() with following differences:

  • Function is not locale-aware.
  • F, g, G and b are not supported.
  • D stands for decimal number.
  • i stands for integer with base detection.
  • n stands for number of characters processed so far.

...

Optionally pass in variables by reference that will contain the parsed values.

Zwracane wartości

If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Przykłady

Przykład #1 sscanf() Example

<?php
// getting the serial number
list($serial) = sscanf("SN/2350001", "SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
?>

If optional parameters are passed, the function will return the number of assigned values.

Przykład #2 sscanf() - using optional parameters

<?php
// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo "<author id='$id'>
    <firstname>$first</firstname>
    <surname>$last</surname>
</author>\n";
?>

Zobacz też:

  • fscanf() - Przetwarza dane z pliku według formatu
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string

sprintf
str_getcsv
String Funkcje


Parse a CSV string into an array

sscanf
str_ireplace
String Funkcje
PHP Manual

str_getcsv

(PHP 5 >= 5.3.0)

str_getcsv — Parse a CSV string into an array

Opis

array str_getcsv ( string $input [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]] )

Parses a string input for fields in CSV format and returns an array containing the fields read.

Parametry

input

The string to parse.

delimiter

Set the field delimiter (one character only).

enclosure

Set the field enclosure character (one character only).

escape

Set the escape character (one character only). Defaults as a backslash (\)

Zwracane wartości

Returns an indexed array containing the fields read.

Zobacz też:

  • fgetcsv() - Pobiera linię ze wskanika pliku i przetwarza na pola CSV

sscanf
str_ireplace
String Funkcje


Case-insensitive version of str_replace.

str_getcsv
str_pad
String Funkcje
PHP Manual

str_ireplace

(PHP 5)

str_ireplace — Case-insensitive version of str_replace().

Opis

mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value. If you don't need fancy replacing rules, you should generally use this function instead of preg_replace() with the i modifier.

Parametry

If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

If search or replace are arrays, their elements are processed first to last.

search

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace

The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject

The string or array being searched and replaced on, otherwise known as the haystack.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

count

If passed, this will be set to the number of replacements performed.

Zwracane wartości

Returns a string or an array of replacements.

Rejestr zmian

Wersja | Opis
5.0.0 | The count parameter was added.

Przykłady

Przykład #1 str_ireplace() example

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Uwaga

Replacement order gotcha

Because str_ireplace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. Example #2 in the str_replace() documentation demonstrates how this may affect you in practice.

Zobacz też:

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace
  • strtr() - Translate characters or replace substrings

str_getcsv
str_pad
String Funkcje


Pad a string to a certain length with another string

str_ireplace
str_repeat
String Funkcje
PHP Manual

str_pad

(PHP 4 >= 4.0.1, PHP 5)

str_pad — Pad a string to a certain length with another string

Opis

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Parametry

input

The input string.

pad_length

If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place.

pad_string

Informacja:

The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.

pad_type

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

Zwracane wartości

Returns the padded string.

Przykłady

Przykład #1 str_pad() example

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>

str_ireplace
str_repeat
String Funkcje


Repeat a string

str_pad
str_replace
String Funkcje
PHP Manual

str_repeat

(PHP 4, PHP 5)

str_repeat — Repeat a string

Opis

string str_repeat ( string $input , int $multiplier )

Returns input repeated multiplier times.

Parametry

input

The string to be repeated.

multiplier

Number of time the input string should be repeated.

multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.

Zwracane wartości

Returns the repeated string.

Przykłady

Przykład #1 str_repeat() example

<?php
echo str_repeat("-=", 10);
?>

Powyższy przykład wyświetli:

-=-=-=-=-=-=-=-=-=-=

Zobacz też:

  • for
  • str_pad() - Pad a string to a certain length with another string
  • substr_count() - Count the number of substring occurrences

str_pad
str_replace
String Funkcje


Replace all occurrences of the search string with the replacement string

str_repeat
str_rot13
String Funkcje
PHP Manual

str_replace

(PHP 4, PHP 5)

str_replace — Replace all occurrences of the search string with the replacement string

Opis

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().

Parametry

If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

If search or replace are arrays, their elements are processed first to last.

search

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace

The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject

The string or array being searched and replaced on, otherwise known as the haystack.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

count

If passed, this will be set to the number of replacements performed.

Zwracane wartości

This function returns a string or an array with the replaced values.

Rejestr zmian

Wersja | Opis
5.0.0 | The count parameter was added.
4.3.3 | The behaviour of this function changed. In older versions a bug existed when using arrays as both search and replace parameters which caused empty search indexes to be skipped without advancing the internal pointer on the replace array. This has been corrected in PHP 4.3.3, any scripts which relied on this bug should remove empty search values prior to calling this function in order to mimic the original behavior.
4.0.5 | Most parameters can now be an array.

Przykłady

Przykład #1 Basic str_replace() examples

<?php
// Provides: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

// Provides: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>

Przykład #2 Examples of potential str_replace() gotchas

<?php
// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';

// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output;
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Uwaga

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

Informacja:

This function is case-sensitive. Use str_ireplace() for case-insensitive replace.

Zobacz też:

  • str_ireplace() - Case-insensitive version of str_replace.
  • substr_replace() - Zastępuje tekst wewnątrz części łańcucha
  • preg_replace() - Perform a regular expression search and replace
  • strtr() - Translate characters or replace substrings

str_repeat
str_rot13
String Funkcje


Perform the rot13 transform on a string

str_replace
str_shuffle
String Funkcje
PHP Manual

str_rot13

(PHP 4 >= 4.2.0, PHP 5)

str_rot13 — Perform the rot13 transform on a string

Opis

string str_rot13 ( string $str )

Performs the ROT13 encoding on the str argument and returns the resulting string.

The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version.

Parametry

str

The input string.

Zwracane wartości

Returns the ROT13 version of the given string.

Przykłady

Przykład #1 str_rot13() example

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>

Rejestr zmian

Wersja | Opis
4.3.0 | The behaviour of this function was fixed. Before this fix, the str was also modified, as if it was passed by reference.

str_replace
str_shuffle
String Funkcje


Randomly shuffles a string

str_rot13
str_split
String Funkcje
PHP Manual

str_shuffle

(PHP 4 >= 4.3.0, PHP 5)

str_shuffle — Randomly shuffles a string

Opis

string str_shuffle ( string $str )

str_shuffle() shuffles a string. One permutation of all possible is created.

Parametry

str

The input string.

Zwracane wartości

Returns the shuffled string.

Przykłady

Przykład #1 str_shuffle() example

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// This will echo something like: bfdaec
echo $shuffled;
?>

Zobacz też:

  • shuffle() - Przetasuj tablicę
  • rand() - Generuje losową liczbę stałoprzecinkową

str_rot13
str_split
String Funkcje


Convert a string to an array

str_shuffle
str_word_count
String Funkcje
PHP Manual

str_split

(PHP 5)

str_split — Convert a string to an array

Opis

array str_split ( string $string [, int $split_length = 1 ] )

Converts a string to an array.

Parametry

string

The input string.

split_length

Maximum length of the chunk.

Zwracane wartości

If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length.

FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element.

Przykłady

Przykład #1 Example uses of str_split()

<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

Powyższy przykład wyświetli:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

Zobacz też:

  • chunk_split() - Split a string into smaller chunks
  • preg_split() - Split string by a regular expression
  • explode() - Split a string by string
  • count_chars() - Return information about characters used in a string
  • str_word_count() - Return information about words used in a string
  • for

str_shuffle
str_word_count
String Funkcje


Return information about words used in a string

str_split
strcasecmp
String Funkcje
PHP Manual

str_word_count

(PHP 4 >= 4.3.0, PHP 5)

str_word_count — Return information about words used in a string

Opis

mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )

Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.

For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.

Parametry

string

The string

format

Specify the return value of this function. The current supported values are:

  • 0 - returns the number of words found
  • 1 - returns an array containing all the words found inside the string
  • 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself

charlist

A list of additional characters which will be considered as 'word'

Zwracane wartości

Returns an array or an integer, depending on the format chosen.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the charlist parameter

Przykłady

Przykład #1 A str_word_count() example

<?php

$str = "Hello fri3nd, you're
       looking          good today!";

print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));

echo str_word_count($str);

?>

Powyższy przykład wyświetli:

Array
(
    [0] => Hello
    [1] => fri
    [2] => nd
    [3] => you're
    [4] => looking
    [5] => good
    [6] => today
)

Array
(
    [0] => Hello
    [6] => fri
    [10] => nd
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

7

Zobacz też:

  • explode() - Split a string by string
  • preg_split() - Split string by a regular expression
  • split() - Split string into array by regular expression
  • count_chars() - Return information about characters used in a string
  • substr_count() - Count the number of substring occurrences

str_split
strcasecmp
String Funkcje


Binary safe case-insensitive string comparison

str_word_count
strchr
String Funkcje
PHP Manual

strcasecmp

(PHP 4, PHP 5)

strcasecmp — Binary safe case-insensitive string comparison

Opis

int strcasecmp ( string $str1 , string $str2 )

Binary safe case-insensitive string comparison.

Parametry

str1

The first string

str2

The second string

Zwracane wartości

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Przykłady

Przykład #1 strcasecmp() example

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
    echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>

Zobacz też:

  • strcmp() - Binary safe string comparison
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string

str_word_count
strchr
String Funkcje


Alias dla strstr

strcasecmp
strcmp
String Funkcje
PHP Manual

strchr

(PHP 4, PHP 5)

strchr — Alias dla strstr()

Opis

Ta funkcja jest aliasem dla: strstr().

strcasecmp
strcmp
String Funkcje


Binary safe string comparison

strchr
strcoll
String Funkcje
PHP Manual

strcmp

(PHP 4, PHP 5)

strcmp — Binary safe string comparison

Opis

int strcmp ( string $str1 , string $str2 )

Note that this comparison is case sensitive.

Parametry

str1

The first string.

str2

The second string.

Zwracane wartości

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Zobacz też:

  • strcasecmp() - Binary safe case-insensitive string comparison
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • substr() - Return part of a string

strchr
strcoll
String Funkcje


Locale based string comparison

strcmp
strcspn
String Funkcje
PHP Manual

strcoll

(PHP 4 >= 4.0.5, PHP 5)

strcoll — Locale based string comparison

Opis

int strcoll ( string $str1 , string $str2 )

Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.

strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp().

Parametry

str1

The first string.

str2

The second string.

Zwracane wartości

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Rejestr zmian

Wersja | Opis
4.2.3 | This function now works on win32.

Zobacz też:

  • preg_match() - Perform a regular expression match
  • strcmp() - Binary safe string comparison
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • setlocale() - Set locale information

strcmp
strcspn
String Funkcje


Find length of initial segment not matching mask

strcoll
strip_tags
String Funkcje
PHP Manual

strcspn

(PHP 4, PHP 5)

strcspn — Find length of initial segment not matching mask

Opis

int strcspn ( string $str1 , string $str2 [, int $start [, int $length ]] )

Returns the length of the initial segment of str1 which does not contain any of the characters in str2.

Parametry

str1

The first string.

str2

The second string.

start

The start position of the string to examine.

length

The length of the string to examine.

Zwracane wartości

Returns the length of the segment as an integer.

Rejestr zmian

Wersja | Opis
4.3.0 | The start and length were added

Przykłady

Przykład #1 strcspn() example

<?php
$a = strcspn('abcd',  'apple');
$b = strcspn('abcd',  'banana');
$c = strcspn('hello', 'l');
$d = strcspn('hello', 'world');

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>

Powyższy przykład wyświetli:

int(0)
int(0)
int(2)
int(2)

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • strspn() - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

strcoll
strip_tags
String Funkcje


Strip HTML and PHP tags from a string

strcspn
stripcslashes
String Funkcje
PHP Manual

strip_tags

(PHP 4, PHP 5)

strip_tags — Strip HTML and PHP tags from a string

Opis

string strip_tags ( string $str [, string $allowable_tags ] )

This function tries to return a string with all NUL bytes, HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function.

Parametry

str

The input string.

allowable_tags

You can use the optional second parameter to specify tags which should not be stripped.

Informacja:

HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags.

Informacja:

This parameter should not contain whitespace. strip_tags() sees a tag as a case-insensitive string between < and the first whitespace or >. It means that strip_tags("<br/>", "<br>") returns an empty string.

Zwracane wartości

Returns the stripped string.

Rejestr zmian

Wersja | Opis
5.0.0 | strip_tags() is now binary safe
4.3.0 | HTML comments are now always stripped

Przykłady

Przykład #1 strip_tags() example

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>

Powyższy przykład wyświetli:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

Notatki

Ostrzeżenie

Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.

Ostrzeżenie

This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users.

Zobacz też:

  • htmlspecialchars() - Convert special characters to HTML entities

strcspn
stripcslashes
String Funkcje


Un-quote string quoted with addcslashes

strip_tags
stripos
String Funkcje
PHP Manual

stripcslashes

(PHP 4, PHP 5)

stripcslashes — Un-quote string quoted with addcslashes()

Opis

string stripcslashes ( string $str )

Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.

Parametry

str

The string to be unescaped.

Zwracane wartości

Returns the unescaped string.

Zobacz też:

  • addcslashes() - Quote string with slashes in a C style

strip_tags
stripos
String Funkcje


Find the position of the first occurrence of a case-insensitive substring in a string

stripcslashes
stripslashes
String Funkcje
PHP Manual

stripos

(PHP 5)

stripos — Find the position of the first occurrence of a case-insensitive substring in a string

Opis

int stripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find the numeric position of the first occurrence of needle in the haystack string.

Unlike the strpos(), stripos() is case-insensitive.

Parametry

haystack

The string to search in.

needle

Note that the needle may be a string of one or more characters.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset

If specified, search will start this number of characters counted from the beginning of the string. Unlike strrpos() and strripos(), the offset cannot be negative.

Zwracane wartości

Returns the position of where the needle exists relative to the beginnning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 stripos() examples

<?php
$findme    = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';

$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);

// Nope, 'a' is certainly not in 'xyz'
if ($pos1 === false) {
    echo "The string '$findme' was not found in the string '$mystring1'";
}

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' is the 0th (first) character.
if ($pos2 !== false) {
    echo "We found '$findme' in '$mystring2' at position $pos2";
}
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • strpos() - Find the position of the first occurrence of a substring in a string
  • strrpos() - Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string
  • str_ireplace() - Case-insensitive version of str_replace.

stripcslashes
stripslashes
String Funkcje


Un-quotes a quoted string

stripos
stristr
String Funkcje
PHP Manual

stripslashes

(PHP 4, PHP 5)

stripslashes — Un-quotes a quoted string

Opis

string stripslashes ( string $str )

Un-quotes a quoted string.

Informacja:

If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead.

An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.

Parametry

str

The input string.

Zwracane wartości

Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

Przykłady

Przykład #1 A stripslashes() example

<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

Informacja:

stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function.

Przykład #2 Using stripslashes() on an array

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}

// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);

// Output
print_r($array);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

Zobacz też:

  • addslashes() - Quote string with slashes
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc

stripos
stristr
String Funkcje


Case-insensitive strstr

stripslashes
strlen
String Funkcje
PHP Manual

stristr

(PHP 4, PHP 5)

stristr — Case-insensitive strstr()

Opis

string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Returns all of haystack from the first occurrence of needle to the end.

Parametry

haystack

The string to search in

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

before_needle

If TRUE, stristr() returns the part of the haystack before the first occurrence of the needle.

needle and haystack are examined in a case-insensitive manner.

Zwracane wartości

Returns the matched substring. If needle is not found, returns FALSE.

Rejestr zmian

Wersja | Opis
5.3.0 | Added the optional parameter before_needle.
4.3.0 | stristr() was made binary safe.

Przykłady

Przykład #1 stristr() example

<?php
  $email = 'USER@EXAMPLE.com';
  echo stristr($email, 'e'); // outputs ER@EXAMPLE.com
  echo stristr($email, 'e', true); // As of PHP 5.3.0, outputs US
?>

Przykład #2 Testing if a string is found or not

<?php
  $string = 'Hello World!';
  if(stristr($string, 'earth') === FALSE) {
    echo '"earth" not found in string';
  }
// outputs: "earth" not found in string
?>

Przykład #3 Using a non "string" needle

<?php
  $string = 'APPLE';
  echo stristr($string, 97); // 97 = lowercase a
// outputs: APPLE
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • strstr() - Find the first occurrence of a string
  • strrchr() - Znajduje ostatnie występowanie znaku w łańcuchu znaków
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strpbrk() - Search a string for any of a set of characters
  • preg_match() - Perform a regular expression match

stripslashes
strlen
String Funkcje


Get string length

stristr
strnatcasecmp
String Funkcje
PHP Manual

strlen

(PHP 4, PHP 5)

strlen — Get string length

Opis

int strlen ( string $string )

Returns the length of the given string.

Parametry

string

The string being measured for length.

Zwracane wartości

The length of the string on success, and 0 if the string is empty.

Rejestr zmian

Wersja | Opis
5.3.0 | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.

Przykłady

Przykład #1 A strlen() example

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

Notatki

Informacja:

strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.

Zobacz też:

  • count() - Zlicza ilość elementów w tablicy lub pól obiektu
  • mb_strlen() - Get string length

stristr
strnatcasecmp
String Funkcje


Case insensitive string comparisons using a "natural order" algorithm

strlen
strnatcmp
String Funkcje
PHP Manual

strnatcasecmp

(PHP 4, PHP 5)

strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm

Opis

int strnatcasecmp ( string $str1 , string $str2 )

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. The behaviour of this function is similar to strnatcmp(), except that the comparison is not case sensitive. For more information see: Martin Pool's » Natural Order String Comparison page.

Parametry

str1

The first string.

str2

The second string.

Zwracane wartości

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2 > 0 if str1 is greater than str2, and 0 if they are equal.

Zobacz też:

  • preg_match() - Perform a regular expression match
  • strcmp() - Binary safe string comparison
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • setlocale() - Set locale information

strlen
strnatcmp
String Funkcje


String comparisons using a "natural order" algorithm

strnatcasecmp
strncasecmp
String Funkcje
PHP Manual

strnatcmp

(PHP 4, PHP 5)

strnatcmp — String comparisons using a "natural order" algorithm

Opis

int strnatcmp ( string $str1 , string $str2 )

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering". Note that this comparison is case sensitive.

Parametry

str1

The first string.

str2

The second string.

Zwracane wartości

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Przykłady

An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:

<?php
$arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png");
echo "Standard string comparison\n";
usort($arr1, "strcmp");
print_r($arr1);
echo "\nNatural order string comparison\n";
usort($arr2, "strnatcmp");
print_r($arr2);
?>

Powyższy przykład wyświetli:

Standard string comparison
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order string comparison
Array
(
    [0] => img1.png
    [1] => img2.png
    [2] => img10.png
    [3] => img12.png
)
For more information see: Martin Pool's » Natural Order String Comparison page.

Zobacz też:

  • preg_match() - Perform a regular expression match
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strcmp() - Binary safe string comparison
  • strncmp() - Binary safe string comparison of the first n characters
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm
  • strstr() - Find the first occurrence of a string
  • natsort() - Sortuj tablicę używając algortmu "porządek naturalny"
  • natcasesort() - Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków

strnatcasecmp
strncasecmp
String Funkcje


Binary safe case-insensitive string comparison of the first n characters

strnatcmp
strncmp
String Funkcje
PHP Manual

strncasecmp

(PHP 4 >= 4.0.2, PHP 5)

strncasecmp — Binary safe case-insensitive string comparison of the first n characters

Opis

int strncasecmp ( string $str1 , string $str2 , int $len )

This function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.

Parametry

str1

The first string.

str2

The second string.

len

The length of strings to be used in the comparison.

Zwracane wartości

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Zobacz też:

  • strncmp() - Binary safe string comparison of the first n characters
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strcasecmp() - Binary safe case-insensitive string comparison
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string

strnatcmp
strncmp
String Funkcje


Binary safe string comparison of the first n characters

strncasecmp
strpbrk
String Funkcje
PHP Manual

strncmp

(PHP 4, PHP 5)

strncmp — Binary safe string comparison of the first n characters

Opis

int strncmp ( string $str1 , string $str2 , int $len )

This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.

Note that this comparison is case sensitive.

Parametry

str1

The first string.

str2

The second string.

len

Number of characters to use in the comparison.

Zwracane wartości

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Zobacz też:

  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strcmp() - Binary safe string comparison
  • strstr() - Find the first occurrence of a string
  • substr() - Return part of a string

strncasecmp
strpbrk
String Funkcje


Search a string for any of a set of characters

strncmp
strpos
String Funkcje
PHP Manual

strpbrk

(PHP 5)

strpbrk — Search a string for any of a set of characters

Opis

string strpbrk ( string $haystack , string $char_list )

strpbrk() searches the haystack string for a char_list.

Parametry

haystack

The string where char_list is looked for.

char_list

This parameter is case sensitive.

Zwracane wartości

Returns a string starting from the character found, or FALSE if it is not found.

Przykłady

Przykład #1 strpbrk() example

<?php

$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>

Zobacz też:

  • strpos() - Find the position of the first occurrence of a substring in a string
  • strstr() - Find the first occurrence of a string
  • preg_match() - Perform a regular expression match

strncmp
strpos
String Funkcje


Find the position of the first occurrence of a substring in a string

strpbrk
strrchr
String Funkcje
PHP Manual

strpos

(PHP 4, PHP 5)

strpos — Find the position of the first occurrence of a substring in a string

Opis

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

Find the numeric position of the first occurrence of needle in the haystack string.

Parametry

haystack

The string to search in.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset

If specified, search will start this number of characters counted from the beginning of the string. Unlike strrpos() and strripos(), the offset cannot be negative.

Zwracane wartości

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 Using ===

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

Przykład #2 Using !==

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// The !== operator can also be used.  Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
} else {
     echo "The string '$findme' was not found in the string '$mystring'";
}
?>

Przykład #3 Using an offset

<?php
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strstr() - Find the first occurrence of a string
  • strpbrk() - Search a string for any of a set of characters
  • substr() - Return part of a string
  • preg_match() - Perform a regular expression match

strpbrk
strrchr
String Funkcje


Znajduje ostatnie występowanie znaku w łańcuchu znaków

strpos
strrev
String Funkcje
PHP Manual

strrchr

(PHP 4, PHP 5)

strrchr — Znajduje ostatnie występowanie znaku w łańcuchu znaków

Opis

string strrchr ( string $stóg siana , string $igła )

Ta funkcja zwraca część stogu siana zaczynającą się od ostatniego występowaniaigłyaż do końca stogu siana.

Zwraca FALSE jeżeli igła nie jest znaleziona.

Jeżeli igła zawiera więcej niż jeden znak, tylko pierwszy jest użyty. To zachowanie jest inne od zachowania strchr().

Jeżeli igła nie jest ciągiem znaków, jest konwertowana na liczbę całkowitą i stosowana jako porządkowa wartość znaku.

Przykład #1 strrchr() przykład

<?php
// otrzymano ostatni katalog w $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// otrzymano wszystko po ostatniej nowej linii
$text = "Lina 1\nLinia 2\nLinia 3";
$last = substr(strrchr($text, 10), 1 );
?>

strrchr() jest bezpieczna dla danych binarnych od wersji PHP 4.3.0

Patrz także strstr(), substr(), i stristr().

strpos
strrev
String Funkcje


Odwraca ciąg znaków

strrchr
strripos
String Funkcje
PHP Manual

strrev

(PHP 4, PHP 5)

strrev — Odwraca ciąg znaków

Opis

string strrev ( string $string )

Zwraca odwrócony string.

Przykład #1 Odwracanie ciągu znaków przez strrev()

<?php
echo strrev("Witaj świecie!"); // wyświetla "!eiceiwś jatiW"
?>

strrchr
strripos
String Funkcje


Find the position of the last occurrence of a case-insensitive substring in a string

strrev
strrpos
String Funkcje
PHP Manual

strripos

(PHP 5)

strripos — Find the position of the last occurrence of a case-insensitive substring in a string

Opis

int strripos ( string $haystack , string $needle [, int $offset = 0 ] )

Find the numeric position of the last occurrence of needle in the haystack string.

Unlike the strrpos(), strripos() is case-insensitive.

Parametry

haystack

The string to search in.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset

If specified, search will start this number of characters counted from the beginning of the string. If the value is negative, search will instead start from that many characters from the end of the string, searching backwards.

Zwracane wartości

Returns the position where the needle exists relative to the beginnning of the haystack string (independent of search direction or offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Przykłady

Przykład #1 A simple strripos() example

<?php
$haystack = 'ababcd';
$needle   = 'aB';

$pos      = strripos($haystack, $needle);

if ($pos === false) {
    echo "Sorry, we did not find ($needle) in ($haystack)";
} else {
    echo "Congratulations!\n";
    echo "We found the last ($needle) in ($haystack) at position ($pos)";
}
?>

Powyższy przykład wyświetli:

   Congratulations!
   We found the last (aB) in (ababcd) at position (2)

Zobacz też:

  • strpos() - Find the position of the first occurrence of a substring in a string
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków
  • strrchr() - Znajduje ostatnie występowanie znaku w łańcuchu znaków
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string

strrev
strrpos
String Funkcje


Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków

strripos
strspn
String Funkcje
PHP Manual

strrpos

(PHP 4, PHP 5)

strrpos — Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków

Opis

int strrpos ( string $stóg siana , string $igła [, int $offset ] )

Zwraca liczbową pozycję ostatniego wystąpienia igła w łańcuchu stóg siana. Zauważ to, że i w tym przypadku igła może być tylko pojedynczym znakiem w PHP 4. Jeżeli jako igła podany jest łańcuch znaków, tylko pierwszy znak tego łańcucha będzie użyty.

Jeżeli igła nie zostanie znaleziona, zwróci FALSE.

Można łatwo pomylić zwracane wartości np. "znak znaleziony na pozycji 0" i "znak nie znaleziony". Poniżej jest napisane jak odróżnić tą różnicę:

<?php

// w PHP 4.0.0 i nowszych:
$pos = strrpos($mystring, "b");
if ($pos === false) { // notatka: trzy jednakowe znaki
    // nie znaleziono...
}

// w wersjach starszych od 4.0.0 :
$pos = strrpos($mystring, "b");
if (is_bool($pos) && !$pos) {
    // nie znaleziono...
}
?>

Jeżeli igła nie jest ciągiem znaków, jest konwertowana na liczbę całkowitą i stosowana jako porządkowa wartość znaku.

Informacja: Od wersji PHP 5.0.0 offset może być określony do rozpoczęcia wyszukiwania po ustalonej liczbie znaków w łańcuchu. Ujemne wartości zatrzymają wyszukiwanie w umownym punkcie przed końcem łańcucha.

Informacja: Parametr igła może być łańcuchem znaków zawierającym więcej niż jeden znak od wersji PHP 5.0.0.

Patrz także strpos(),
strripos(),
strrchr(),
substr(),
stristr(), i
strstr().

strripos
strspn
String Funkcje


Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

strrpos
strstr
String Funkcje
PHP Manual

strspn

(PHP 4, PHP 5)

strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.

Opis

int strspn ( string $subject , string $mask [, int $start [, int $length ]] )

Finds the length of the initial segment of subject that contains only characters from mask.

If start and length are omitted, then all of subject will be examined. If they are included, then the effect will be the same as calling strspn(substr($subject, $start, $length), $mask) (see substr for more information).

The line of code:

<?php
$var = strspn("42 is the answer to the 128th question.", "1234567890");
?>
will assign 2 to $var, because the string "42" is the initial segment of subject that consists only of characters contained within "1234567890".

Parametry

subject

The string to examine.

mask

The list of allowable characters.

start

The position in subject to start searching.

If start is given and is non-negative, then strspn() will begin examining subject at the start'th position. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If start is given and is negative, then strspn() will begin examining subject at the start'th position from the end of subject.

length

The length of the segment from subject to examine.

If length is given and is non-negative, then subject will be examined for length characters after the starting position.

If lengthis given and is negative, then subject will be examined from the starting position up to length characters from the end of subject.

Zwracane wartości

Returns the length of the initial segment of subject which consists entirely of characters in mask.

Rejestr zmian

Wersja | Opis
4.3.0 | The start and length parameters were added

Przykłady

Przykład #1 strspn() example

<?php
// subject does not start with any characters from mask
var_dump(strspn("foo", "o"));

// examine two characters from subject starting at offset 1
var_dump(strspn("foo", "o", 1, 2));

// examine one character from subject starting at offset 1
var_dump(strspn("foo", "o", 1, 1));
?>

Powyższy przykład wyświetli:

int(0)
int(2)
int(1)

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • strcspn() - Find length of initial segment not matching mask

strrpos
strstr
String Funkcje


Find the first occurrence of a string

strspn
strtok
String Funkcje
PHP Manual

strstr

(PHP 4, PHP 5)

strstr — Find the first occurrence of a string

Opis

string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

Returns part of haystack string from the first occurrence of needle to the end of haystack.

Informacja:

This function is case-sensitive. For case-insensitive searches, use stristr().

Informacja:

If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

Parametry

haystack

The input string.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

before_needle

If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle.

Zwracane wartości

Returns the portion of string, or FALSE if needle is not found.

Rejestr zmian

Wersja | Opis
5.3.0 | Added the optional parameter before_needle.
4.3.0 | strstr() was made binary safe.

Przykłady

Przykład #1 strstr() example

<?php
$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

Zobacz też:

  • stristr() - Case-insensitive strstr
  • strrchr() - Znajduje ostatnie występowanie znaku w łańcuchu znaków
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strpbrk() - Search a string for any of a set of characters
  • preg_match() - Perform a regular expression match

strspn
strtok
String Funkcje


Tokenize string

strstr
strtolower
String Funkcje
PHP Manual

strtok

(PHP 4, PHP 5)

strtok — Tokenize string

Opis

string strtok ( string $str , string $token )
string strtok ( string $token )

strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.

Parametry

str

The string being split up into smaller strings (tokens).

token

The delimiter used when splitting up str.

Zwracane wartości

A string token.

Przykłady

Przykład #1 strtok() example

<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string, " \n\t");

while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:

Przykład #2 Old strtok() behavior

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Powyższy przykład wyświetli:

    string(0) ""
    string(9) "something"

Przykład #3 New strtok() behavior

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Powyższy przykład wyświetli:

    string(9) "something"
    bool(false)

Notatki

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Zobacz też:

  • split() - Split string into array by regular expression
  • explode() - Split a string by string

strstr
strtolower
String Funkcje


Zmienia wszystkie litery w łańcuchu na małe

strtok
strtoupper
String Funkcje
PHP Manual

strtolower

(PHP 4, PHP 5)

strtolower — Zmienia wszystkie litery w łańcuchu na małe

Opis

string strtolower ( string $str )

Zwraca string z wszystkimi literami alfabetu przekonwertowanymi na małe.

Zauważ, że 'alfabet' jest określany przez obecny język lokalny. To znaczy, że w domyślnym, lokalnym "C" , takie znaki jak umlaut-A (Ä) nie będą konwertowane.

Przykład #1 strtolower() przykład

<?php
$str = "Marysia Ma Małego Baranka , Którego Bardzo KOCHA";
$str = strtolower($str);
echo $str; // Wyświetli marysia ma małego baranka, ktorego bardzo kocha
?>

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Patrz również strtoupper(), ucfirst(), ucwords() and mb_strtolower().

strtok
strtoupper
String Funkcje


Zmienia wszystkie litery w łańcuchu na duże

strtolower
strtr
String Funkcje
PHP Manual

strtoupper

(PHP 4, PHP 5)

strtoupper — Zmienia wszystkie litery w łańcuchu na duże

Opis

string strtoupper ( string $string )

Zwraca string z wszystkimi literami alfabetu przekonwertowanymi na duże.

Zauważ, że 'alfabet' jest określany przez obecny język lokalny. Na przykład, w domyślnym, lokalnym "C" takie znaki jak umlaut-a (ä) nie będą konwertowane.

Przykład #1 strtoupper() przykład

<?php
$str = "Marysia Ma Małego Baranka , Którego Bardzo KOCHA";
$str = strtoupper($str);
echo $str; // Wyświetli MARYSIA MA MAŁEGO BARANKA, KTÓREGO BARDZO KOCHA
?>

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Patrz również strtolower(), ucfirst(), ucwords() and mb_strtoupper().

strtolower
strtr
String Funkcje


Translate characters or replace substrings

strtoupper
substr_compare
String Funkcje
PHP Manual

strtr

(PHP 4, PHP 5)

strtr — Translate characters or replace substrings

Opis

string strtr ( string $str , string $from , string $to )
string strtr ( string $str , array $replace_pairs )

If given three arguments, this function returns a copy of str where all occurrences of each (single-byte) character in from have been translated to the corresponding character in to, i.e., every occurrence of $from[$n] has been replaced with $to[$n], where $n is a valid offset in both arguments.

If from and to have different lengths, the extra characters in the longer of the two are ignored. The length of str will be the same as the return value's.

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

In this case, the keys and the values may have any length, provided that there is no empty key; additionaly, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size.

Parametry

str

The string being translated.

from

The string being translated to to.

to

The string replacing from.

replace_pairs

The replace_pairs parameter may be used instead of to and from, in which case it's an array in the form array('from' => 'to', ...).

Zwracane wartości

Returns the translated string.

If replace_pairs contains a key which is an empty string (""), FALSE will be returned.

Przykłady

Przykład #1 strtr() example

<?php
//In this form, strtr() does byte-by-byte translation
//Therefore, we are assuming a single-byte encoding here:
$addr = strtr($addr, "äåö", "aao");
?>

The next example shows the behavior of strtr() when called with only two arguments. Note the preference of the replacements ("h" is not picked because there are longer matches) and how replaced text was not searched again.

Przykład #2 strtr() example with two arguments

<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

Powyższy przykład wyświetli:

hello all, I said hi

The two modes of behavior are substantially different. With three arguments, strtr() will replace bytes; with two, it may replace longer substrings.

Przykład #3 strtr() behavior comparison

<?php
echo strtr("baab", "ab", "01"),"\n";

$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>

Powyższy przykład wyświetli:

1001
ba01

Zobacz też:

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace

strtoupper
substr_compare
String Funkcje


Binary safe comparison of two strings from an offset, up to length characters

strtr
substr_count
String Funkcje
PHP Manual

substr_compare

(PHP 5)

substr_compare — Binary safe comparison of two strings from an offset, up to length characters

Opis

int substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = false ]] )

substr_compare() compares main_str from position offset with str up to length characters.

Parametry

main_str

The main string being compared.

str

The secondary string being compared.

offset

The start position for the comparison. If negative, it starts counting from the end of the string.

length

The length of the comparison. The default value is the largest of the length of the str compared to the length of main_str less the offset.

case_insensitivity

If case_insensitivity is TRUE, comparison is case insensitive.

Zwracane wartości

Returns < 0 if main_str from position offset is less than str, > 0 if it is greater than str, and 0 if they are equal. If offset is equal to or greater than the length of main_str or length is set and is less than 1, substr_compare() prints a warning and returns FALSE.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the possibility to use a negative offset.

Przykłady

Przykład #1 A substr_compare() example

<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>

strtr
substr_count
String Funkcje


Count the number of substring occurrences

substr_compare
substr_replace
String Funkcje
PHP Manual

substr_count

(PHP 4, PHP 5)

substr_count — Count the number of substring occurrences

Opis

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.

Informacja:

This function doesn't count overlapped substrings. See the example below!

Parametry

haystack

The string to search in

needle

The substring to search for

offset

The offset where to start counting

length

The maximum length after the specified offset to search for the substring. It outputs a warning if the offset plus the length is greater than the haystack length.

Zwracane wartości

This function returns an integer.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the offset and the length parameters

Przykłady

Przykład #1 A substr_count() example

<?php
$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

// the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3);

// the text is reduced to 's i', so it prints 0
echo substr_count($text, 'is', 3, 3);

// generates a warning because 5+10 > 14
echo substr_count($text, 'is', 5, 10);

// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>

Zobacz też:

  • count_chars() - Return information about characters used in a string
  • strpos() - Find the position of the first occurrence of a substring in a string
  • substr() - Return part of a string
  • strstr() - Find the first occurrence of a string

substr_compare
substr_replace
String Funkcje


Zastępuje tekst wewnątrz części łańcucha

substr_count
substr
String Funkcje
PHP Manual

substr_replace

(PHP 4, PHP 5)

substr_replace — Zastępuje tekst wewnątrz części łańcucha

Opis

mixed substr_replace ( mixed $string , string $replacement , int $start [, int $długość ] )

substr_replace() zastępuje kopię string ograniczoną przez parametry start i (opcjonalnie) długość do łańcucha podanym w replacement. W rezultacie zwracany jest łańcuch. Jeżeli string jest tablicą, wtedy zwracana jest tablica.

Jeżeli start jest dodatni, zastąpienie będzie zaczynać się od start znaku w string.

Jeżelistart jest ujemny, zastąpienie będzie zaczynać się odstart znaku od końcastring.

Jeślidługość jest podana i jest dodatnia, stanowi długość części string która będzie zastąpiona. Jeśli jest ujemna, stanowi liczbę znaków od końca string po których ma być zatrzymane zastępowanie. Jeśli nie jest podana, wtedy domyślnie wynosi strlen( string ); tj. koniec zastąpienia na końcustring. Oczywiście, jeśli długość jest zerem wtedy funkcja będzie powodowała efekt wstawienia replacement w string w określonym przez start miejscu.

Przykład #1 substr_replace() przykłady

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";

/* Te dwa przykłady zastępują całość $var ciągiem 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Wstawia 'bob' odpowiednio na początku $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* Następne zastępują  'MNRPQR' w $var ciągiem 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/*Usuwa 'MNRPQR' z $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Patrz również str_replace() i substr().

substr_count
substr
String Funkcje


Return part of a string

substr_replace
trim
String Funkcje
PHP Manual

substr

(PHP 4, PHP 5)

substr — Return part of a string

Opis

string substr ( string $string , int $start [, int $length ] )

Returns the portion of string specified by the start and length parameters.

Parametry

string

The input string. Must be one character or longer.

start

If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If start is negative, the returned string will start at the start'th character from the end of string.

If string is less than or equal to start characters long, FALSE will be returned.

Przykład #1 Using a negative start

<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

length

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string).

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, false will be returned.

If length is given and is 0, FALSE or NULL an empty string will be returned.

If length is omitted, the substring starting from start until the end of the string will be returned.

Przykład #2 Using a negative length

<?php
$rest = substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns false
$rest = substr("abcdef", -3, -1); // returns "de"
?>

Zwracane wartości

Returns the extracted part of string, lub FALSE w przypadku niepowodzenia or an empty string.

Rejestr zmian

Wersja | Opis
5.2.2 - 5.2.6 | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.

Przykłady

Przykład #3 Basic substr() usage

<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

Przykład #4 substr() casting behaviour

<?php
class apple {
    public function __toString() {
        return "green";
    }
}

echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL;
echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL;
echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL;
echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL;
echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL;
echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL;
?>

Powyższy przykład wyświetli:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'

Błędy/Wyjątki

Returns FALSE on error.

<?php
var_dump(substr('a', 1)); // bool(false)
?>

Zobacz też:

  • strrchr() - Znajduje ostatnie występowanie znaku w łańcuchu znaków
  • substr_replace() - Zastępuje tekst wewnątrz części łańcucha
  • preg_match() - Perform a regular expression match
  • trim() - Strip whitespace (or other characters) from the beginning and end of a string
  • mb_substr() - Get part of string
  • wordwrap() - Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.
  • String access and modification by character

substr_replace
trim
String Funkcje


Strip whitespace (or other characters) from the beginning and end of a string

substr
ucfirst
String Funkcje
PHP Manual

trim

(PHP 4, PHP 5)

trim — Strip whitespace (or other characters) from the beginning and end of a string

Opis

string trim ( string $str [, string $charlist ] )

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parametry

str

The string that will be trimmed.

charlist

Optionally, the stripped characters can also be specified using the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Zwracane wartości

The trimmed string.

Rejestr zmian

Wersja | Opis
4.1.0 | The optional charlist parameter was added.

Przykłady

Przykład #1 Usage example of trim()

<?php

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

$trimmed = trim($hello, 'HdWr');
var_dump($trimmed);

// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

?>

Powyższy przykład wyświetli:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(9) "ello Worl"
string(14) "Example string"

Przykład #2 Trimming array values with trim()

<?php
function trim_value(&$value)
{
    $value = trim($value);
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(7) "banana "
  [2]=>
  string(11) " cranberry "
}
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(9) "cranberry"
}

Notatki

Informacja: Possible gotcha: removing middle characters

Because trim() trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to also be trimmed. So, this is why it "works" whereas trim('abc', 'b') seemingly does not.

Zobacz też:

  • ltrim() - Strip whitespace (or other characters) from the beginning of a string
  • rtrim() - Strip whitespace (or other characters) from the end of a string
  • str_replace() - Replace all occurrences of the search string with the replacement string

substr
ucfirst
String Funkcje


Make a string's first character uppercase

trim
ucwords
String Funkcje
PHP Manual

ucfirst

(PHP 4, PHP 5)

ucfirst — Make a string's first character uppercase

Opis

string ucfirst ( string $str )

Returns a string with the first character of str capitalized, if that character is alphabetic.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Parametry

str

The input string.

Zwracane wartości

Returns the resulting string.

Przykłady

Przykład #1 ucfirst() example

<?php
$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>

Zobacz też:

  • lcfirst() - Make a string's first character lowercase
  • strtolower() - Zmienia wszystkie litery w łańcuchu na małe
  • strtoupper() - Zmienia wszystkie litery w łańcuchu na duże
  • ucwords() - Uppercase the first character of each word in a string

trim
ucwords
String Funkcje


Uppercase the first character of each word in a string

ucfirst
vfprintf
String Funkcje
PHP Manual

ucwords

(PHP 4, PHP 5)

ucwords — Uppercase the first character of each word in a string

Opis

string ucwords ( string $str )

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Parametry

str

The input string.

Zwracane wartości

Returns the modified string.

Przykłady

Przykład #1 ucwords() example

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

Notatki

Informacja: Ta funkcja jest bezpieczna dla danych binarnych.

Zobacz też:

  • strtoupper() - Zmienia wszystkie litery w łańcuchu na duże
  • strtolower() - Zmienia wszystkie litery w łańcuchu na małe
  • ucfirst() - Make a string's first character uppercase
  • mb_convert_case() - Perform case folding on a string

ucfirst
vfprintf
String Funkcje


Write a formatted string to a stream

ucwords
vprintf
String Funkcje
PHP Manual

vfprintf

(PHP 5)

vfprintf — Write a formatted string to a stream

Opis

int vfprintf ( resource $handle , string $format , array $args )

Write a string produced according to format to the stream resource specified by handle.

Operates as fprintf() but accepts an array of arguments, rather than a variable number of arguments.

Parametry

handle

format

See sprintf() for a description of format.

args

Zwracane wartości

Returns the length of the outputted string.

Przykłady

Przykład #1 vfprintf(): zero-padded integers

<?php
if (!($fp = fopen('date.txt', 'w')))
    return;

vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));
// will write the formatted ISO date to date.txt
?>

Zobacz też:

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Przetwarza dane z pliku według formatu
  • vsprintf() - Return a formatted string
  • number_format() - Formatuje liczbę według szablonu

ucwords
vprintf
String Funkcje


Output a formatted string

vfprintf
vsprintf
String Funkcje
PHP Manual

vprintf

(PHP 4 >= 4.1.0, PHP 5)

vprintf — Output a formatted string

Opis

int vprintf ( string $format , array $args )

Display array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.

Parametry

format

See sprintf() for a description of format.

args

Zwracane wartości

Returns the length of the outputted string.

Przykłady

Przykład #1 vprintf(): zero-padded integers

<?php
vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>

Zobacz też:

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • vsprintf() - Return a formatted string

vfprintf
vsprintf
String Funkcje


Return a formatted string

vprintf
wordwrap
String Funkcje
PHP Manual

vsprintf

(PHP 4 >= 4.1.0, PHP 5)

vsprintf — Return a formatted string

Opis

string vsprintf ( string $format , array $args )

Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

Parametry

format

See sprintf() for a description of format.

args

Zwracane wartości

Return array values as a formatted string according to format (which is described in the documentation for sprintf()).

Przykłady

Przykład #1 vsprintf(): zero-padded integers

<?php
print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>

Zobacz też:

  • sprintf() - Return a formatted string
  • vprintf() - Output a formatted string

vprintf
wordwrap
String Funkcje


Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.

vsprintf
Zmienne i typy powiązanych rozszerzeń
String Funkcje
PHP Manual

wordwrap

(PHP 4 >= 4.0.2, PHP 5)

wordwrap — Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.

Opis

string wordwrap ( string $str [, int $szerokość [, string $break [, bool $cut ]]] )

Zwraca łańcuch str zawinięty w kolumny o odpowiedniej ilości znaków określonej przez opcjonalny parametr szerokość. Linia jest łamana przy użyciu (opcjonalnego)parametru break .

wordwrap() będzie automatycznie zawijał kolumny co 75 znaków używając '\n' (nowa linia) jeżeli szerokość lubbreak nie zostaną podane.

Jeżeli cut jest ustawiony na TRUE, łańcuch jest zawsze łamany w określonej szerkości. Gdy mamy wyraz, który jest dłuższy od podanej szerokości, zostanie on przełamany. (Zobacz drugi przykład).

Informacja:

Parametr opcjonalny cut został dodany w PHP 4.0.3

Przykład #1 wordwrap() przykład

<?php
$tekst = "Szybki, brązowy lis przeskoczył nad leniwym psem.";
$nowytekst = wordwrap($tekst, 20, "<br />\n");

echo $nowytekst;
?>

Ten przykład powinien wyświetlić:

Szybki, brązowy lis <br />
przeskoczył nad <br />
leniwym psem

Przykład #2 wordwrap() przykład

<?php
$tekst = "Bardzo długie słooooooooooowo.";
$nowytekst = wordwrap($tekst, 8, "\n", true);

echo "$newtext\n";
?>

Ten przykład powinien wyświetlić:

Bardzo
długie
słoooooo
ooooowo.

Patrz również nl2br() i chunk_split().

vsprintf
Zmienne i typy powiązanych rozszerzeń
String Funkcje


Zmienne i typy powiązanych rozszerzeń

  • Tablice
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Sorting Arrays
    • Funkcje Tablic
  • Klasy/Obiekty — Informacje o klasach i obiektach
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Funkcje Klasy/Obiekty
  • Classkit
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Classkit Funkcje
  • Ctype — Character type checking
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Ctype Funkcje
  • Filter — Data Filtering
    • Wstęp
    • Instalacja/Konfiguracja
    • Types of filters
    • Stałe predefiniowane
    • Przykłady
    • Filter Funkcje
  • Function Handling
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Function handling Funkcje
  • Object Aggregation — Object Aggregation/Composition [PHP 4]
    • Wstęp
    • Przykłady
    • Object Aggregation Funkcje
  • Quickhash
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashIntStringHash — The QuickHashIntStringHash class
  • Reflection
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Extending
    • Reflection — The Reflection class
    • ReflectionClass — The ReflectionClass class
    • ReflectionZendExtension — The ReflectionZendExtension class
    • ReflectionExtension — The ReflectionExtension class
    • ReflectionFunction — The ReflectionFunction class
    • ReflectionFunctionAbstract — The ReflectionFunctionAbstract class
    • ReflectionMethod — The ReflectionMethod class
    • ReflectionObject — The ReflectionObject class
    • ReflectionParameter — The ReflectionParameter class
    • ReflectionProperty — The ReflectionProperty class
    • Reflector — The Reflector interface
    • ReflectionException — The ReflectionException class
  • Variable handling
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Variable handling Funkcje
wordwrap
Tablice
Opis funkcji


Tablice

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Sorting Arrays
  • Funkcje Tablic
    • array_change_key_case — Zwraca tablicę ze wszystkimi kluczami tekstowymi zamienionymi na wyłącznie małe lub wyłącznie duże litery
    • array_chunk — Podziel tablicę na kawałki
    • array_combine — Tworzy tablicę używając wartości jednej tablicy jako kluczy a drugiej jako wartości
    • array_count_values — Zlicza wszystkie wartości w tablicy
    • array_diff_assoc — Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
    • array_diff_key — Oblicza różnicę tablic używając kluczy do porównań
    • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey — Oblicza różnicę tablic używając funkcji zwrotnej do porównywania kluczy
    • array_diff — Zwraca różnice pomiędzy tablicami
    • array_fill_keys — Fill an array with values, specifying keys
    • array_fill — Wypełnij tablicę podanymi wartościami
    • array_filter — Filtruje elementy przy użyciu funkcji zwrotnej
    • array_flip — Wymienia wszystkie klucze z przypisanymi do nich wartościami w tablicy
    • array_intersect_assoc — Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
    • array_intersect_key — Computes the intersection of arrays using keys for comparison
    • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
    • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
    • array_intersect — Zwraca przecięcie tablic
    • array_key_exists — Sprawdza czy podany klucz lub indeks istnieje w tablicy
    • array_keys — Zwraca wszystkie klucze z tablicy
    • array_map — Wykonuje funkcję zwrotną na elementach podanej tablicy
    • array_merge_recursive — Łączy dwie lub więcej tablic rekurencyjnie
    • array_merge — Łączy jedną lub więcej tablic
    • array_multisort — Sortuje wiele tablic lub wielowymiarowe tablice
    • array_pad — Dopełnij tablicę do podanej długości podanymi wartościami
    • array_pop — Zdejmij element z końca tablicy
    • array_product — Calculate the product of values in an array
    • array_push — Wstaw jeden lub więcej elementów na koniec tablicy
    • array_rand — Wybierz jeden lub więcej losowych elementów z tablicy
    • array_reduce — Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji zwrotnej
    • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
    • array_replace — Replaces elements from passed arrays into the first array
    • array_reverse — Zwraca tablicę z elementami ustawionymi w porządku odwrotnym
    • array_search — Przeszukuje tablicę pod kątem podanej wartości i w przypadku sukcesu zwraca odpowiedni klucz
    • array_shift — Usuń element z początku tablicy
    • array_slice — Wytnij kawałek tablicy
    • array_splice — Usuń część tablicy i zamień ją na coś innego
    • array_sum — Oblicza sumę wartości w tablicy
    • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
    • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
    • array_udiff — Computes the difference of arrays by using a callback function for data comparison
    • array_uintersect_assoc — Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
    • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
    • array_uintersect — Computes the intersection of arrays, compares data by a callback function
    • array_unique — Usuwa duplikaty wartości z tablicy
    • array_unshift — Wstaw jeden lub więcej elementów na początek tablicy
    • array_values — Zwraca wszystkie wartości z tablicy
    • array_walk_recursive — Apply a user function recursively to every member of an array
    • array_walk — Zastosuj funkcję użytkownika do każdego elementu tablicy
    • array — Stwórz tablicę
    • arsort — Sortuje tablicę w porządku odwrotnym z zachowaniem skojarzenia kluczy
    • asort — Posortuj tablicę zachowując skojarzenia kluczy
    • compact — Stwórz tablicę zawierającą zmienne i ich wartości
    • count — Zlicza ilość elementów w tablicy lub pól obiektu
    • current — Zwraca bieżący element tablicy
    • each — Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicy
    • end — Ustawia wewnętrzny wskaźnik tablicy na ostatnim elemencie
    • extract — Importuj zmienne do bieżącej tablicy symboli z tablicy
    • in_array — Sprawdza czy wartość istnieje w tablicy
    • key — Pobiera klucz z tablicy asocjacyjnej
    • krsort — Sortuj tablicę według kluczy w porządku odwrotnym
    • ksort — Sortuj tablicę według klucza
    • list — Przypisz zmienne tak jakby były tablicą
    • natcasesort — Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków
    • natsort — Sortuj tablicę używając algortmu "porządek naturalny"
    • next — Przesuń do przodu wewnętrzny wskaźnik tablicy
    • pos — Alias dla current
    • prev — Cofnij wewnętrzny wskaźnik tablicy
    • range — Stwórz tablicę zawierającą przedział elementów
    • reset — Ustaw wewnętrzny wskaźnik tablicy na jej pierwszy element
    • rsort — Sortuj tablicę w porządku odwrotnym
    • shuffle — Przetasuj tablicę
    • sizeof — Alias dla count
    • sort — Sortuje tablicę
    • uasort — Sortuj tablicę korzystając ze zdefiniowanej przez użytkownika funkcji porównującej i zachowując skojarzenia kluczy
    • uksort — Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez użytkownika funkcji porównującej
    • usort — Sortuje tablicę według wartości korzystając ze zdefiniowanej przez użytkownika funkcji porównującej
Zmienne i typy powiązanych rozszerzeń
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

Funkcje te pozwalają na operowanie i manipulowanie tablicami na wiele różnych sposobów. Tablice są kluczowymi elementami przechowywania, zarządzania i operowania na zbiorach zmiennych.

Obsługiwane są proste i wielowymiarowane tablice, które mogą być stworzone przez użytkownika lub przez funkcję. Istnieją specjalne funkcje obsługi baz danych odpowiedzialne za wypełnianie tablic danymi z zapytań do baz danych, a także kilka innych funkcji zwracających tablice.

Zobacz rozdział podręcznika Tablice aby uzyskać dokładne wyjaśnienie, jak tablice zostały zaimplementowane i jak się ich używa w PHP. Inne metody przetwarzania tablic zostały opisane w rozdziale operatory tablicowe.

Tablice
Instalacja/Konfiguracja
Tablice


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Tablice


Stałe predefiniowane

Poniższe stałe są częścią jądra PHP a więc są zawsze widoczne.

CASE_LOWER (integer)
CASE_LOWER jest używana w funkcji array_change_key_case() do konwersji kluczy tablicy do samych małych liter. Jest to także domyślny przypadek dla array_change_key_case().
CASE_UPPER (integer)
CASE_UPPER jest używana w funkcji array_change_key_case() do konwersji kluczy tablicy do samych dużych liter.

Flagi kolejności sortowania:

SORT_ASC (integer)
SORT_ASC używana jest w połączeniu z array_multisort() do sortowania w porządku rosnącym.
SORT_DESC (integer)
SORT_DESC używana jest w połączeniu z array_multisort() do sortowania w porządku rosnącym.

Flagi typu sortowania - używane przez różne funkcje sortujące

SORT_REGULAR (integer)
SORT_REGULAR używana jest do porównywania elementów w normalny sposób.
SORT_NUMERIC (integer)
SORT_NUMERIC używana jest do porównywania elementów liczbowo.
SORT_STRING (integer)
SORT_STRING używana jest do porównywania elementów jako ciągi tekstowe.
SORT_LOCALE_STRING (integer)
SORT_LOCALE_STRING używana jest do porównywania elementów jako ciągi tekstowe w oparciu o bieżące ustawienia locale. Dodane w PHP 4.4.0 i 5.0.2.

COUNT_NORMAL (integer)
COUNT_RECURSIVE (integer)
EXTR_OVERWRITE (integer)
EXTR_SKIP (integer)
EXTR_PREFIX_SAME (integer)
EXTR_PREFIX_ALL (integer)
EXTR_PREFIX_INVALID (integer)
EXTR_PREFIX_IF_EXISTS (integer)
EXTR_IF_EXISTS (integer)
EXTR_REFS (integer)
Typy zasobów
Sorting Arrays
Tablice


Sorting Arrays

PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out.

The main differences are:

  • Some sort based on the array keys, whereas others by the values: $array['key'] = 'value';
  • Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 ...)
  • The order of the sort: alphabetical, low to high (ascending), high to low (descending), numerical, natural, random, or user defined
  • Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array
  • If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

Sorting function attributes
Function name | Sorts by | Maintains key association | Order of sort | Related functions
array_multisort() | value | associative yes, numeric no | first array or sort options | array_walk()
asort() | value | yes | low to high | arsort()
arsort() | value | yes | high to low | asort()
krsort() | key | yes | high to low | ksort()
ksort() | key | yes | low to high | asort()
natcasesort() | value | yes | natural, case insensitive | natsort()
natsort() | value | yes | natural | natcasesort()
rsort() | value | no | high to low | sort()
shuffle() | value | no | random | array_rand()
sort() | value | no | low to high | rsort()
uasort() | value | yes | user defined | uksort()
uksort() | key | yes | user defined | uasort()
usort() | value | no | user defined | uasort()

Stałe predefiniowane
Funkcje Tablic
Tablice


Funkcje Tablic

Zobacz też:

Patrz także: is_array(), explode(),
implode(), split(),
preg_split(), i unset().

Spis treści

  • array_change_key_case — Zwraca tablicę ze wszystkimi kluczami tekstowymi zamienionymi na wyłącznie małe lub wyłącznie duże litery
  • array_chunk — Podziel tablicę na kawałki
  • array_combine — Tworzy tablicę używając wartości jednej tablicy jako kluczy a drugiej jako wartości
  • array_count_values — Zlicza wszystkie wartości w tablicy
  • array_diff_assoc — Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
  • array_diff_key — Oblicza różnicę tablic używając kluczy do porównań
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Oblicza różnicę tablic używając funkcji zwrotnej do porównywania kluczy
  • array_diff — Zwraca różnice pomiędzy tablicami
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — Wypełnij tablicę podanymi wartościami
  • array_filter — Filtruje elementy przy użyciu funkcji zwrotnej
  • array_flip — Wymienia wszystkie klucze z przypisanymi do nich wartościami w tablicy
  • array_intersect_assoc — Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect — Zwraca przecięcie tablic
  • array_key_exists — Sprawdza czy podany klucz lub indeks istnieje w tablicy
  • array_keys — Zwraca wszystkie klucze z tablicy
  • array_map — Wykonuje funkcję zwrotną na elementach podanej tablicy
  • array_merge_recursive — Łączy dwie lub więcej tablic rekurencyjnie
  • array_merge — Łączy jedną lub więcej tablic
  • array_multisort — Sortuje wiele tablic lub wielowymiarowe tablice
  • array_pad — Dopełnij tablicę do podanej długości podanymi wartościami
  • array_pop — Zdejmij element z końca tablicy
  • array_product — Calculate the product of values in an array
  • array_push — Wstaw jeden lub więcej elementów na koniec tablicy
  • array_rand — Wybierz jeden lub więcej losowych elementów z tablicy
  • array_reduce — Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji zwrotnej
  • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
  • array_replace — Replaces elements from passed arrays into the first array
  • array_reverse — Zwraca tablicę z elementami ustawionymi w porządku odwrotnym
  • array_search — Przeszukuje tablicę pod kątem podanej wartości i w przypadku sukcesu zwraca odpowiedni klucz
  • array_shift — Usuń element z początku tablicy
  • array_slice — Wytnij kawałek tablicy
  • array_splice — Usuń część tablicy i zamień ją na coś innego
  • array_sum — Oblicza sumę wartości w tablicy
  • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_udiff — Computes the difference of arrays by using a callback function for data comparison
  • array_uintersect_assoc — Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
  • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
  • array_uintersect — Computes the intersection of arrays, compares data by a callback function
  • array_unique — Usuwa duplikaty wartości z tablicy
  • array_unshift — Wstaw jeden lub więcej elementów na początek tablicy
  • array_values — Zwraca wszystkie wartości z tablicy
  • array_walk_recursive — Apply a user function recursively to every member of an array
  • array_walk — Zastosuj funkcję użytkownika do każdego elementu tablicy
  • array — Stwórz tablicę
  • arsort — Sortuje tablicę w porządku odwrotnym z zachowaniem skojarzenia kluczy
  • asort — Posortuj tablicę zachowując skojarzenia kluczy
  • compact — Stwórz tablicę zawierającą zmienne i ich wartości
  • count — Zlicza ilość elementów w tablicy lub pól obiektu
  • current — Zwraca bieżący element tablicy
  • each — Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicy
  • end — Ustawia wewnętrzny wskaźnik tablicy na ostatnim elemencie
  • extract — Importuj zmienne do bieżącej tablicy symboli z tablicy
  • in_array — Sprawdza czy wartość istnieje w tablicy
  • key — Pobiera klucz z tablicy asocjacyjnej
  • krsort — Sortuj tablicę według kluczy w porządku odwrotnym
  • ksort — Sortuj tablicę według klucza
  • list — Przypisz zmienne tak jakby były tablicą
  • natcasesort — Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków
  • natsort — Sortuj tablicę używając algortmu "porządek naturalny"
  • next — Przesuń do przodu wewnętrzny wskaźnik tablicy
  • pos — Alias dla current
  • prev — Cofnij wewnętrzny wskaźnik tablicy
  • range — Stwórz tablicę zawierającą przedział elementów
  • reset — Ustaw wewnętrzny wskaźnik tablicy na jej pierwszy element
  • rsort — Sortuj tablicę w porządku odwrotnym
  • shuffle — Przetasuj tablicę
  • sizeof — Alias dla count
  • sort — Sortuje tablicę
  • uasort — Sortuj tablicę korzystając ze zdefiniowanej przez użytkownika funkcji porównującej i zachowując skojarzenia kluczy
  • uksort — Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez użytkownika funkcji porównującej
  • usort — Sortuje tablicę według wartości korzystając ze zdefiniowanej przez użytkownika funkcji porównującej
Sorting Arrays
array_change_key_case
Tablice


Zwraca tablicę ze wszystkimi kluczami tekstowymi zamienionymi na wyłącznie małe lub wyłącznie duże litery

Funkcje Tablic
array_chunk
Funkcje Tablic
PHP Manual

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case — Zwraca tablicę ze wszystkimi kluczami tekstowymi zamienionymi na wyłącznie małe lub wyłącznie duże litery

Opis

array array_change_key_case ( array $wejście [, int $wielkość ] )

array_change_key_case() zmienia klucze w tablicy wejście aby były pisane tylko dużymi lub tylko małymi literami. Zmiana zależy od ostatniego opcjonalnego parametru case. Można do niego przekazać jedną z dwóch stałych: CASE_UPPER lub CASE_LOWER. Domyślną wartością jest CASE_LOWER. Indeksy liczbowe będą pozostawione takie jakie są.

Przykład #1 Przykład użycia array_change_key_case()

<?php
$wejscie = array("PierWszy" => 1, "DruGi" => 4);
print_r(array_change_key_case($wejscie, CASE_UPPER));
?>

Powyższy przykład wyświetli:

Array
(
    [PIERWSZY] => 1
    [DRUGI] => 4
)

Jeśli tablica ma indeksy które będą się powtarzały po wykonaniu tej funkcji (np. "klucZ" i "kLUCZ"), wartość tego elementu który jest dalej w tablicy nadpisze pozostałe indeksy.

Funkcje Tablic
array_chunk
Funkcje Tablic


Podziel tablicę na kawałki

array_change_key_case
array_combine
Funkcje Tablic
PHP Manual

array_chunk

(PHP 4 >= 4.2.0, PHP 5)

array_chunk — Podziel tablicę na kawałki

Description

array array_chunk ( array $wejście , int $rozmiar [, bool $zachowaj_klucze ] )

array_chunk() dzieli tablicę na kilka mniejszych, każda po rozmiar elementów. Istnieje możliwość, że ostatnia tablica będzie mniejsza. Otrzymujesz tablice jako elementy wielowymiarowej tablicy indeksowanej przez liczby zaczynając od zera.

Ustawiając opcjonalny parametr zachowaj_klucze na TRUE możesz zmusić PHP do zachowywania orginalnych kluczy z tablicy wejściowej. Jeśli podasz w tym miejscu FALSE, to w każdej nowej tablicy użyte będą nowe indeksy liczbowe zaczynające się od zera. Domyślną wartością jest FALSE.

Przykład #1 Przykład użycia array_chunk()

<?php
$tablica_wejsciowa = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($tablica_wejsciowa, 2));
print_r(array_chunk($tablica_wejsciowa, 2, true));
?>

Powyższy przykład wyświetli:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)
array_change_key_case
array_combine
Funkcje Tablic


Tworzy tablicę używając wartości jednej tablicy jako kluczy a drugiej jako wartości

array_chunk
array_count_values
Funkcje Tablic
PHP Manual

array_combine

(PHP 5)

array_combine — Tworzy tablicę używając wartości jednej tablicy jako kluczy a drugiej jako wartości

Opis

array array_combine ( array $klucze , array $wartości )

Zwraca tablicę stworzoną poprzez użycie wartości z tablicy klucze jako kluczy i wartości z tablicy wartości jako odpowiadających im wartości.

Zwraca FALSE jeśli liczba elementów tablic wejściowych nie są równe, lub jeśli jedna lub obie z tablic są puste.

Przykład #1 Przykład użycia array_combine()

<?php
$a = array('zielony', 'czerwony', 'żółty');
$b = array('awokado', 'jabłko', 'banan');
$c = array_combine($a, $b);

print_r($c);
?>

Powyższy przykład wyświetli:

Array
(
    [zielony]  => awokado
    [czerwony] => jabłko
    [żółty]    => banan
)

Patrz także: array_merge(),
array_walk() i
array_values().

array_chunk
array_count_values
Funkcje Tablic


Zlicza wszystkie wartości w tablicy

array_combine
array_diff_assoc
Funkcje Tablic
PHP Manual

array_count_values

(PHP 4, PHP 5)

array_count_values — Zlicza wszystkie wartości w tablicy

Opis

array array_count_values ( array $wejście )

array_count_values() zwraca tablicę zawierającą wartości tablicy wejście jako klucze i częstość ich występowania w tablicy wejście jako wartości.

Przykład #1 Przykład użycia array_count_values()

<?php
$tablica = array (1, "witaj", 1, "świecie", "witaj");
print_r(array_count_values ($tablica));
?>

Powyższy przykład wyświetli:

Array
(
   [1] => 2
   [hello] => 2
   [world] => 1
)

Patrz także: count(),
array_unique(),
array_values() i
count_chars().

array_combine
array_diff_assoc
Funkcje Tablic


Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy

array_count_values
array_diff_key
Funkcje Tablic
PHP Manual

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_diff_assoc — Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy

Opis

array array_diff_assoc ( array $tablica1 , array $tablica2 [, array $ ... ] )

array_diff_assoc() zwraca tablicę zawierającą wszystkie wartości z array1, które nie są obecne w żadnym z innych argumentów. Przy porównaniu, w przeciwieństwie do funkcji array_diff(), używane są także klucze.

Przykład #1 Przykład użycia array_diff_assoc()

<?php
$tablica1 = array("a" => "zielony", "b" => "brązowy", "c" => "niebieski", "czerwony");
$tablica2 = array("a" => "zielony", "żółty", "czerwony");
$wynik = array_diff_assoc($tablica1, $tablica2);
print_r($wynik);
?>

Powyższy przykład wyświetli:

Array
(
    [b] => brązowy
    [c] => niebieski
    [0] => czerwony
)

W powyższym przykładzie para "a" => "zielony" występuje w obu tablicach, i w związku z tym nie jest dodawana do wyniku działania funkcji. Para 0 => "czerwony" znajduje się w tablicy wynikowej, ponieważ w drugim argumencie "czerwony" ma klucz 1.

Dwie wartości z par klucz => wartość są uznawane za równe tylko jeśli (string) $element1 === (string) $element2 . Inaczej mówiąc, zachodzi ścisłe sprawdzanie, a więc reprezentacje tekstowe muszą być takie same.

Informacja: Funkcja ta sprawdza tylko jeden wymiar n-wymiarowej tablicy. Można sprawdzać głębsze wymiary przez użycie, na przykład array_diff_assoc($tablica1[0], $tablica2[0]);.

Patrz także: array_diff(),
array_intersect() i
array_intersect_assoc().

array_count_values
array_diff_key
Funkcje Tablic


Oblicza różnicę tablic używając kluczy do porównań

array_diff_assoc
array_diff_uassoc
Funkcje Tablic
PHP Manual

array_diff_key

(PHP 5 >= 5.1.0)

array_diff_key — Oblicza różnicę tablic używając kluczy do porównań

Opis

array array_diff_key ( array $tablica1 , array $tablica2 [, array $ ... ] )

array_diff_key() zwraca wszystkie wartości z tablica1, które nie są obecne w żadnym z pozostałych argumentów. Asocjacje są zachowywane. Ta funkcja jest podobna do array_diff(), z tym, że do porównania używane są klucze tablicy zamiast ich wartości.

Przykład #1 Przykład użycia array_diff_key()

<?php
$tablica1 = array('niebieski'  => 1, 'czerwony'  => 2, 'zielony'  => 3, 'purpurowy' => 4);
$tablica2 = array('zielony' => 5, 'niebieski' => 6, 'żółty' => 7, 'cyan'   => 8);

var_dump(array_diff_key($tablica1, $tablica2));
?>

Powyższy przykład wyświetli:

array(2) {
  ["czerwony"]=>
  int(2)
  ["purpurowy"]=>
  int(4)
}

Dwa klucze z par klucz => wartość są uznawane za równe tylko jeśli (string) $klucz1 === (string) $klucz2 . Inaczej mówiąc, zachodzi ścisłe sprawdzanie, a więc reprezentacje tekstowe muszą być takie same.

Informacja: Funkcja ta sprawdza tylko jeden wymiar n-wymiarowej tablicy. Można sprawdzać głębsze wymiary przez użycie, na przykład array_diff_assoc($tablica1[0], $tablica2[0]);.

Patrz także: array_diff(),
array_udiff()
array_diff_assoc(),
array_diff_uassoc(),
array_udiff_assoc(),
array_udiff_uassoc(),
array_diff_ukey(),
array_intersect(),
array_intersect_assoc(),
array_intersect_uassoc(),
array_intersect_key() i
array_intersect_ukey().

array_diff_assoc
array_diff_uassoc
Funkcje Tablic


Computes the difference of arrays with additional index check which is performed by a user supplied callback function

array_diff_key
array_diff_ukey
Funkcje Tablic
PHP Manual

array_diff_uassoc

(PHP 5)

array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function

Opis

array array_diff_uassoc ( array $tablica1 , array $tablica2 [, array $... ], callback $key_compare_func )

array_diff_uassoc() zwraca tablicę zawierającą wszystkie wartości z tablica1 które nie są obecne w żadnym z pozostałych argumentów. Do porównania, w przeciwieństwie do funkcji array_diff(), używane sa klucze tablic.

Porównanie jest dokonywane przy pomocy podanej funkcji zwrotnej. Musi ona zwracać liczbę całkowitą mniejszą, równą lub większą od zera jeśli pierwszy klucz jest uznawany za mniejszy, równy lub większy drugiego. Jest to zachowanie inne niż w funkcji array_diff_assoc(), gdzie do porównań kluczy używana jest wewnętrzna funkcja.

Przykład #1 Przykład użycia array_diff_uassoc()

<?php
function funk_porownujaca($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$tablica1 = array("a" => "zielony", "b" => "brązowy", "c" => "niebieski", "czerwony");
$tablica2 = array("a" => "zielony", "żółty", "czerwony");
$wynik = array_diff_uassoc($tablica1, $tablica2, "funk_porownujaca");
print_r($wynik);
?>

Powyższy przykład wyświetli:

Array
(
    [b] => brązowy
    [c] => niebieski
    [0] => czerwony
)

W powyższym przykładzie para "a" => "zielony" jest obecna w obu tablicach, w związku z tym nie jest zwracana przez funkcję. Z kolei para 0 => "czerwony" jest zawarta w wyniku działania funkcji, ponieważ w drugim argumencie wartość "czerwony" ma klucz 1.

Równość dwóch indeksów jest sprawdzana przez podaną przez użytkownika funkcję.

Informacja: Funkcja ta sprawdza tylko jeden wymiar n-wymiarowej tablicy. Można sprawdzać głębsze wymiary przez użycie, na przykład array_diff_uassoc($tablica1[0], $tablica2[0], 'funkcja_zwrotna');.

Patrz także:
array_diff(),
array_diff_assoc(),
array_udiff(),
array_udiff_assoc(),
array_udiff_uassoc(),
array_intersect(),
array_intersect_assoc(),
array_uintersect(),
array_uintersect_assoc() i
array_uintersect_uassoc().

array_diff_key
array_diff_ukey
Funkcje Tablic


Oblicza różnicę tablic używając funkcji zwrotnej do porównywania kluczy

array_diff_uassoc
array_diff
Funkcje Tablic
PHP Manual

array_diff_ukey

(PHP 5 >= 5.1.0)

array_diff_ukey — Oblicza różnicę tablic używając funkcji zwrotnej do porównywania kluczy

Opis

array array_diff_ukey ( array $tablica1 , array $tablica2 [, array $ ... ], callback $funk_porównania_kluczy )

array_diff_ukey() zwraca tablicę zawierającą wszystkie wartości z tablica1 których klucze nie są obecne w żadnym z innych argumentów. Asocjacje są zachowywane. Funkcja ta jest podobna do array_diff(), z tym że porównywane są klucze a nie wartości.

Porównanie jest dokonywane przy pomocy podanej funkcji zwrotnej. Musi ona zwracać liczbę całkowitą mniejszą, równą lub większą od zera jeśli pierwszy klucz jest uznawany za mniejszy, równy lub większy drugiego.

Przykład #1 Przykład użycia funkcji array_diff_ukey()

<?php
function porownaj_klucze($klucz1, $klucz2)
{
    if ($klucz1 == $klucz2)
        return 0;
    else if ($klucz1 > $klucz2)
        return 1;
    else
        return -1;
}

$tablica1 = tablica('niebieski'  => 1, 'czerwony'  => 2, 'zielony'  => 3, 'purpurowy' => 4);
$tablica2 = tablica('zielony' => 5, 'niebieski' => 6, 'żółty' => 7, 'cyan'   => 8);

var_dump(array_diff_ukey($tablica1, $tablica2, 'porownaj_klucze'));
?>

Powyższy przykład wyświetli:

array(2) {
  ["czerwony"]=>
  int(2)
  ["purpurowy"]=>
  int(4)
}

Informacja: Funkcja ta sprawdza tylko jeden wymiar n-wymiarowej tablicy. Można sprawdzać głębsze wymiary przez użycie, na przykład array_diff_assoc($tablica1[0], $tablica2[0], 'funkcja_zwrotna');.

Patrz także: array_diff(),
array_udiff()
array_diff_assoc(),
array_diff_uassoc(),
array_udiff_assoc(),
array_udiff_uassoc(),
array_diff_key(),
array_intersect(),
array_intersect_assoc(),
array_intersect_uassoc(),
array_intersect_key() i
array_intersect_ukey().

array_diff_uassoc
array_diff
Funkcje Tablic


Zwraca różnice pomiędzy tablicami

array_diff_ukey
array_fill_keys
Funkcje Tablic
PHP Manual

array_diff

(PHP 4 >= 4.0.1, PHP 5)

array_diff — Zwraca różnice pomiędzy tablicami

Opis

array array_diff ( array $tablica1 , array $tablica2 [, array $ ... ] )

array_diff() zwraca tablicę zawierającą wszystkie wartości tablicy tablica1 które nie są obecne w innych tablicach-argumentach. Zauważ, że zachowywane są klucze.

Przykład #1 Przykład użycia array_diff()

<?php
$tablica1 = array ("a" => "zielony", "czerwony", "niebieski", "czerwony");
$tablica2 = array ("b" => "zielony", "żółty", "czerwony");
$wynik = array_diff ($tablica1, $tablica2);

print_r($wynik);
?>

Wielokrotne wystąpienia w $tablica1 są traktowane w ten sam sposób. Powyższy przykład wyświetli:

Array
(
    [1] => niebieski
)

Informacja: Dwa elementy tablicy uważane są za identyczne wtedy i tylko wtedy jeśli (string) $element1 === (string) $element2. Słownie: kiedy reprezentacje elementów w postaci stringów są identyczne.

Informacja: Zauważ, że funkcja ta sprawdza tylko jest wymiar n-wymiarowej tablicy. Oczywiście można sprawdzić głębsze wymiary wywołując array_diff($array1[0], $array2[0]);.

Ostrzeżenie

Ta funkcja była zepsuta w PHP 4.0.4!

Patrz także: array_diff_assoc(),
array_intersect() i
array_intersect_assoc().

array_diff_ukey
array_fill_keys
Funkcje Tablic


Fill an array with values, specifying keys

array_diff
array_fill
Funkcje Tablic
PHP Manual

array_fill_keys

(PHP 5 >= 5.2.0)

array_fill_keys — Fill an array with values, specifying keys

Opis

array array_fill_keys ( array $keys , mixed $value )

Fills an array with the value of the value parameter, using the values of the keys array as keys.

Parametry

keys

Array of values that will be used as keys. Illegal values for key will be converted to string.

value

Value to use for filling

Zwracane wartości

Returns the filled array

Przykłady

Przykład #1 array_fill_keys() example

<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

Powyższy przykład wyświetli:

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

Zobacz też:

  • array_fill() - Wypełnij tablicę podanymi wartościami
  • array_combine() - Tworzy tablicę używając wartości jednej tablicy jako kluczy a drugiej jako wartości

array_diff
array_fill
Funkcje Tablic


Wypełnij tablicę podanymi wartościami

array_fill_keys
array_filter
Funkcje Tablic
PHP Manual

array_fill

(PHP 4 >= 4.2.0, PHP 5)

array_fill — Wypełnij tablicę podanymi wartościami

Opis

array array_fill ( int $indeks_początkowy , int $num , mixed $wartość )

array_fill() wypełni tablicę wartością value, począwszy od indeksu indeks_początkowy przez num kolejnych elementów tablicy. Zauważ, że num musi być liczbą większą od zera. W przeciwnym przypadku PHP zwróci ostrzeżenie.

Przykład #1 Przykład użycia array_fill()

<?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?>

$a zawiera teraz:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

Patrz także: str_repeat() i range().

array_fill_keys
array_filter
Funkcje Tablic


Filtruje elementy przy użyciu funkcji zwrotnej

array_fill
array_flip
Funkcje Tablic
PHP Manual

array_filter

(PHP 4 >= 4.0.6, PHP 5)

array_filter — Filtruje elementy przy użyciu funkcji zwrotnej

Opis

array array_filter ( array $wejście [, callback $funkcja_zwrotna ] )

array_filter() wykonuje iterację dla każdej wartości z tablicy wejście, przekazując tą wartość jako parametr funkcji funkcja_zwrotna. Jeśli funkcja_zwrotna zwróci wartość true, bieżąca wartość zostanie wstawiona do tablicy wynikowej. Klucze tablicy zostają zachowane.

Przykład #1 Przykład użycia array_filter()

<?php
function nieparzysta($var)
{
    return($var & 1);
}

function parzysta($var)
{
    return(!($var & 1));
}

$tablica1 = array ("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$tablica2 = array (6, 7, 8, 9, 10, 11, 12);

echo "Nieparzyste:\n";
print_r(array_filter($tablica1, "nieparzysta"));
echo "Parzyste:\n";
print_r(array_filter($tablica2, "parzyste"));
?>

Powyższy przykład wyświetli:

Nieparzyste:
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Parzyste:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

Użytkownicy nie mogą zmieniać filtrowanej tablicy z wnętrza funkcji zwrotnej. Jeśli tablica zostanie zmieniona, zachowanie tej funkcji array_filter() pozostaje nieokreślone.

Jeśli funkcja funkcja_zwrotna nie zostanie podana, array_filter() usunie wszystkie elementy z tablicy wejście, które odpowiadają FALSE. Zobacz will remove all the entries of konwertowanie do typu logicznego aby uzyskać więcej informacji.

Przykład #2 array_filter() bez parametru funkcja_zwrotna

<?php

$tablica = array(
               0 => 'foo',
                  1 => false,
                  2 => -1,
                  3 => null,
                  4 => ''
               );

print_r(array_filter($tablica));
?>

Powyższy przykład wyświetli:

Array
(
    [0] => foo
    [2] => -1
)

Patrz także: array_map(), array_reduce() i array_walk().

array_fill
array_flip
Funkcje Tablic


Wymienia wszystkie klucze z przypisanymi do nich wartościami w tablicy

array_filter
array_intersect_assoc
Funkcje Tablic
PHP Manual

array_flip

(PHP 4, PHP 5)

array_flip — Wymienia wszystkie klucze z przypisanymi do nich wartościami w tablicy

Opis

array array_flip ( array $trans )

array_flip() zwraca tablicę w odwróconym porządku, tzn. klucze z tablicy trans stają się wartościami a wartości trans stają się kluczami.

Zauważ, że wszystkie wartości tablicy trans muszą mieć poprawne klucze, tzn. muszą być albo typu integer lub string. Jeśli wartość nie ma prawidłego typu, wyświetlone zostanie ostrzeżenie, a para klucz/wartość nie będzie odwrócona.

Jeśli wartość występuje wielokrotnie, ostatni klucz będzie użyty jako jej wartość po odwróceniu, a wszystkie inne zostaną stracone.

array_flip() zwraca FALSE jeśli nie powiedzie się odwracanie tablicy.

Przykład #1 Przykład użycia array_flip()

<?php
$trans = array_flip ($trans);
$original = strtr ($str, $trans);
?>

Przykład #2 Przykład użycia array_flip() : kolizja

<?php
$trans = array ("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip ($trans);
print_r($trans);
?>

Powyższy przykład wyświetli:

Array
   [1] => b
   [2] => c

Patrz także: array_values(),
array_keys() i
array_reverse().

array_filter
array_intersect_assoc
Funkcje Tablic


Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów

array_flip
array_intersect_key
Funkcje Tablic
PHP Manual

array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_intersect_assoc — Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów

Opis

array array_intersect_assoc ( array $tablica1 , array $tablica2 [, array $ ... ] )

array_intersect_assoc() zwraca tablicę zawierającą wszystkie wartości z tablica1, które są obecne także we wszystkich pozostałych argumentach. Należy pamiętać, że w przeciwieństwie do funkcji array_intersect(), tutaj w brane są pod uwagę także klucze.

Przykład #1 Przykład użycia array_intersect_assoc()

<?php
$tablica1 = array("a" => "zielony", "b" => "brązowy", "c" => "niebieski", "czerwony");
$tablica2 = array("a" => "zielony", "żółty", "czerwony");
$tablica_wynikowa = array_intersect_assoc($tablica1, $tablica2);
print_r($tablica_wynikowa);
?>

Powyższy przykład wyświetli:

Array
(
    [a] => zielony
)

W powyższym przykładzie, tylko jedna para, "a" => "zielony, jest obecna w obu tablicach wejściowych, a więc tylko ta zostanie zwrócona. Wartość "red" nie jest zwracana, ponieważ w tablicy $tablica1 jej klucz to 0, a w $tablica2 - 1.

Dwie wartości z pary klucz => wartość są uważane za równe tylko jeśli (string) $element1 === (string) $element2. Innymi słowy, dokonywane jest ścisłe porównywanie typów, tak więc reprezentacje znakowe muszą być takie same.

Patrz także: array_intersect(),
array_uintersect_assoc(),
array_intersect_uassoc(),
array_uintersect_uassoc(),
array_diff() i
array_diff_assoc().

array_flip
array_intersect_key
Funkcje Tablic


Computes the intersection of arrays using keys for comparison

array_intersect_assoc
array_intersect_uassoc
Funkcje Tablic
PHP Manual

array_intersect_key

(PHP 5 >= 5.1.0)

array_intersect_key — Computes the intersection of arrays using keys for comparison

Opis

array array_intersect_key ( array $array1 , array $array2 [, array $ ... ] )

array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.

Parametry

array1

The array with master keys to check.

array2

An array to compare keys against.

array

A variable list of arrays to compare.

Zwracane wartości

Returns an associative array containing all the entries of array1 which have keys that are present in all arguments.

Przykłady

Przykład #1 array_intersect_key() example

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_key($array1, $array2));
?>

Powyższy przykład wyświetli:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

Zobacz też:

  • array_diff() - Zwraca różnice pomiędzy tablicami
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_diff_key() - Oblicza różnicę tablic używając kluczy do porównań
  • array_diff_ukey() - Oblicza różnicę tablic używając funkcji zwrotnej do porównywania kluczy
  • array_intersect() - Zwraca przecięcie tablic
  • array_intersect_assoc() - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison

array_intersect_assoc
array_intersect_uassoc
Funkcje Tablic


Computes the intersection of arrays with additional index check, compares indexes by a callback function

array_intersect_key
array_intersect_ukey
Funkcje Tablic
PHP Manual

array_intersect_uassoc

(PHP 5)

array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function

Opis

array array_intersect_uassoc ( array $array1 , array $array2 [, array $ ... ], callback $key_compare_func )

array_intersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

The index comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Parametry

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

array

Variable list of array arguments to compare values against.

key_compare_func

User supplied callback function to do the comparison.

Zwracane wartości

Returns the values of array1 whose values exist in all of the arguments.

Przykłady

Przykład #1 array_intersect_uassoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?>

Powyższy przykład wyświetli:

Array
(
    [b] => brown
)

Zobacz też:

  • array_intersect() - Zwraca przecięcie tablic
  • array_intersect_assoc() - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_uintersect_assoc() - Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison

array_intersect_key
array_intersect_ukey
Funkcje Tablic


Computes the intersection of arrays using a callback function on the keys for comparison

array_intersect_uassoc
array_intersect
Funkcje Tablic
PHP Manual

array_intersect_ukey

(PHP 5 >= 5.1.0)

array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison

Opis

array array_intersect_ukey ( array $array1 , array $array2 [, array $... ], callback $key_compare_func )

array_intersect_ukey() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.

Parametry

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

array

Variable list of array arguments to compare keys against.

key_compare_func

User supplied callback function to do the comparison.

Zwracane wartości

Returns the values of array1 whose keys exist in all the arguments.

Przykłady

Przykład #1 array_intersect_ukey() example

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?>

Powyższy przykład wyświetli:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

Zobacz też:

  • array_diff() - Zwraca różnice pomiędzy tablicami
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_diff_key() - Oblicza różnicę tablic używając kluczy do porównań
  • array_diff_ukey() - Oblicza różnicę tablic używając funkcji zwrotnej do porównywania kluczy
  • array_intersect() - Zwraca przecięcie tablic
  • array_intersect_assoc() - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison

array_intersect_uassoc
array_intersect
Funkcje Tablic


Zwraca przecięcie tablic

array_intersect_ukey
array_key_exists
Funkcje Tablic
PHP Manual

array_intersect

(PHP 4 >= 4.0.1, PHP 5)

array_intersect — Zwraca przecięcie tablic

Opis

array array_intersect ( array $tablica1 , array $tablica2 [, array $ ... ] )

array_intersect() zwraca tablicę zawierającą wszystkie wartości tablicy tablica1 które istnieją we wszystkich argumentach. Zauważ, ża zachowywane są przypisania kluczy.

Przykład #1 Przykład użycia array_intersect()

<?php
$tablica1 = array ("a" => "zielony", "czerwony", "niebieski");
$tablica2 = array ("b" => "zielony", "żółty", "czerwony");
$wynik = array_intersect ($tablica1, $tablica2);
print_r($wynik);
?>

Powyższy przykład wyświetli:

Array
(
    [a] => zielony
    [0] => czerwony
)

Informacja: Dwa elementy tablicy uważane są za identyczne wtedy i tylko wtedy jeśli (string) $element1 === (string) $element2. Słownie: kiedy reprezentacje elementów w postaci stringów są identyczne.

Patrz także: array_intersect_assoc(), array_diff() i array_diff_assoc().

array_intersect_ukey
array_key_exists
Funkcje Tablic


Sprawdza czy podany klucz lub indeks istnieje w tablicy

array_intersect
array_keys
Funkcje Tablic
PHP Manual

array_key_exists

(PHP 4 >= 4.0.7, PHP 5)

array_key_exists — Sprawdza czy podany klucz lub indeks istnieje w tablicy

Description

bool array_key_exists ( mixed $igła , array $stóg_siana )

array_key_exists() zwraca TRUE jeśli igła jest ustawiona w tablicy stóg_siana. igła może być dowolną wartością możliwą dla indeksu tablicy. array_key_exists() działa także na obiektach.

Przykład #1 Przykład użycia array_key_exists()

<?php
$stog_siana = array('pierwszy' => 1, 'drugi' => 4);
if (array_key_exists('pierwszy', $stog_siana)) {
    echo "'Pierwszy' element istnieje w tablicy";
}
?>

Informacja: W PHP 4.0.6 ta funkcja nazywa się key_exists().

Przykład #2 array_key_exists() a isset()

isset(), w przeciwieństwie do array_key_exists(), nie zwraca wartości TRUE dla kluczy tablicy, którym przypisana jest wartość NULL.

<?php
$tablica = array('pierwszy' => null, 'drugi' => 4);

// zwraca false
isset($tablica['pierwszy']);

// zwraca true
array_key_exists('pierwszy', $tablica);
?>

Patrz także: isset(), array_keys(), i in_array().

array_intersect
array_keys
Funkcje Tablic


Zwraca wszystkie klucze z tablicy

array_key_exists
array_map
Funkcje Tablic
PHP Manual

array_keys

(PHP 4, PHP 5)

array_keys — Zwraca wszystkie klucze z tablicy

Opis

array array_keys ( array $wejście [, mixed $szukana_wartość [, bool $ścisłe_porównanie ]] )

array_keys() zwraca klucze, liczbowe i tekstowe, z tablicy wejście.

Jeśli podany został opcjonalny parameter szukana_wartość, zwracane są tylko klucze dla danej, do których przypisana jest podana wartość. W przeciwnym przypadku zwracane są wszystkie klucze z tablicy wejście. Od PHP 5 można użyć opcjonalnego parametru ścisłe_porównanie dla porównania z uwzględnieniem typu (===).

Parametry

wejście

Tablica, której klucze zostaną zwrócone.

szukana_wartość

Jeśli jest podana, wówczas zwracane są tylko te klucze, które wskazują w tablicy na szukaną wartość.

ścisłe_porównanie

Od PHP 5 ten parametr określa, czy porównywanie wartości powinno być ścisłe (===).

Zwracane wartości

Zwraca tablicę zawierającą wszystkie klucze tablicy wejście.

Przykłady

Przykład #1 Przykład array_keys()

<?php
$tablica = array(0 => 100, "kolor" => "czerwony");
print_r(array_keys($tablica));

$tablica = array("niebieski", "czerwony", "zielony", "niebieski", "niebieski");
print_r(array_keys($tablica, "niebieski"));

$tablica = array("kolor" => array("niebieski", "czerwony", "zielony"),
                  "rozmiar" => array("mały", "średni", "duży"));
print_r(array_keys($tablica));
?>

Powyższy przykład wyświetli:

Array
(
    [0] => 0
    [1] => kolor
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => kolor
    [1] => rozmiar
)

Zobacz też:

  • array_values() - Zwraca wszystkie wartości z tablicy
  • array_key_exists() - Sprawdza czy podany klucz lub indeks istnieje w tablicy

array_key_exists
array_map
Funkcje Tablic


Wykonuje funkcję zwrotną na elementach podanej tablicy

array_keys
array_merge_recursive
Funkcje Tablic
PHP Manual

array_map

(PHP 4 >= 4.0.6, PHP 5)

array_map — Wykonuje funkcję zwrotną na elementach podanej tablicy

Opis

array array_map ( callback $funkcja_zwrotna , array $tbl1 [, array $tbl2... ] )

array_map() zwraca tablicę zawierającą wszystkie elementy tablicy tbl1 po użyciu na każdej z nich funkcji zwrotnej. Liczba parametrów funkcji zwrotnej powinna być równa liczbie tablic przekazanych do funkcji array_map().

Przykład #1 Przykład użycia array_map()

function szescian($n)
{
    return $n*$n*$n;
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("szescian", $a);
print_r($b);
?>

Zmienna $b będzie zawierała:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Przykład #2 array_map() - używanie większej ilości tablic

function pokaz_po_Hiszpansku($n, $m)
{
    return "Po Hiszpańsku liczba $n to $m";
}

function mapuj_na_Hiszpanski($n, $m)
{
    return array ($n => $m);
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("pokaz_po_Hiszpansku", $a, $b);
print_r($c);

$d = array_map("mapuj_po_Hiszpansku", $a , $b);
print_r($d);
?>

Powyższy przykład wyświetli:

// Zmienna $c
Array
(
    [0] => Po Hiszpańsku liczba 1 to uno
    [1] => Po Hiszpańsku liczba 2 to dos
    [2] => Po Hiszpańsku liczba 3 to tres
    [3] => Po Hiszpańsku liczba 4 to cuatro
    [4] => Po Hiszpańsku liczba 5 to cinco
)

// Zmienna $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Zazwyczaj używając dwóch lub więcej tablic, powinny one być równej długości, ponieważ funkcja zwrotna jest wykonywana na odpowiadających sobie elementach tablic. Jeśli tablice są różnych długości, krótsze będą rozszerzane używając pustych elementów.

Interesującym sposobem użycia tej funkcji jest kontruowanie tablicy tablic, co może być łatwo przeprowadzone przez podanie NULL jako nazwy funkcji zwrotnej.

Przykład #3 Tworzenie tablicy tablic

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");
$d = array("jeden", "dwa", "trzy", "cztery", "pięć");

$e = array_map(null, $a, $b, $c, $d);
print_r($e);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
            [3] => jeden
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
            [3] => dwa
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
            [3] => trzy
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
            [3] => cztery
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
            [3] => pięć
        )

)

Patrz także: array_filter(),
array_reduce(), array_walk(),
create_function() i informacje o typie callback.

array_keys
array_merge_recursive
Funkcje Tablic


Łączy dwie lub więcej tablic rekurencyjnie

array_map
array_merge
Funkcje Tablic
PHP Manual

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5)

array_merge_recursive — Łączy dwie lub więcej tablic rekurencyjnie

Opis

array array_merge_recursive ( array $tablica1 [, array $... ] )

array_merge_recursive() łączy elementy jednej lub więcej tablic tak, że wartości jednej tablicy są dopisywane na koniec poprzedniej. Zwracana jest tablica wynikowa.

Jeśli wejściowe tablice mają jakieś klucze tekstowe, to wartości dla tych kluczy są łączone w tablicę, co jest robione rekurencyjnie, a więc jeśli jedną z wartości jest tablica, funkcja połączy ją z odpowiadającą jej wartością z innej tablicy. Jednakże jeśli tablice mają takie same klucze liczbowe, późniejsza wartość nie nadpisze początkowej wartości, lecz zostanie dopisana na koniec.

Przykład #1 Przykład użycia array_merge_recursive()

<?php
$tbl1 = array ("kolor" => array ("ulubiony" => "czerwony"), 5);
$tbl2 = array (10, "kolor" => array ("ulubiony" => "zielony", "niebieski"));
$wynik = array_merge_recursive($tbl1, $tbl2);
print_r($wynik);
?>

Powyższy przykład wyświetli:

Array
(
    [kolor] => Array
        (
            [ulubiony] => Array
                (
                    [0] => czerwony
                    [1] => zielony
                )

            [0] => niebieski
        )

    [0] => 5
    [1] => 10
)

Patrz także: array_merge().

array_map
array_merge
Funkcje Tablic


Łączy jedną lub więcej tablic

array_merge_recursive
array_multisort
Funkcje Tablic
PHP Manual

array_merge

(PHP 4, PHP 5)

array_merge — Łączy jedną lub więcej tablic

Opis

array array_merge ( array $tablica1 [, array $tablica2 [, array $... ]] )

array_merge() łączy elementy jednej lub więcej tablic razem, tak że wartości jednej tablicy są wstawiane na koniec poprzedniej tablicy. Funkcja ta zwraca tablicę wynikową.

Jeśli tablice wejściowe mają takie same klucze tekstowe, najnowsza wartość nadpisze starszą. Jednakże jeśli tablice będą miały takie same klucze liczbowe, późniejsza wartość nie nadpisze starszej, lecz zostanie dopisana na koniec tablicy.

Jeśli podana zostanie tylko jedna tablica i jest ona indeksowana numerycznie, to klucze tablicy zostaną przeindeksowane w sposób ciągły.

Przykład #1 Przykład użycia array_merge()

<?php
$tablica1 = array("kolor" => "czerwony", 2, 4);
$tablica2 = array("a", "b", "kolor" => "zielony", "kształt" => "trapezoid", 4);
$wynik = array_merge($tablica1, $tablica2));
print_r($wynik);
?>

Powyższy przykład wyświetli:

Array
(
    [kolor] => zielony
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [kształt] => trapezoid
    [4] => 4
)

Przykład #2 Prosty przykład użycia array_merge()

<?php
$tablica1 = array();
$tablica2 = array(1 => "dane");
$wynik    = array_merge($tablica1, $tablica2);
?>

Nie zapomnij że klucze numeryczne będą przenumerowane!

Array
(
[0] => dane
)

Jeśli chcesz całkowicie zachować tablice i tylko dodać jedną na końcu drugiej, użyj operatora +:

<?php
$tablica1 = array();
$tablica2 = array(1 => "dane");
$wynik = $tablica1 + $tablica2;
?>

Klucze numeryczne pozostaną zachowane a co za tym idzie asocjacje zostaną niezmienione.

Array
(
    [1] => dane
)

Ostrzeżenie

Zachowanie array_merge() zostało zmienione w PHP 5. Inaczej niż w PHP 4, array_merge() akceptuje teraz tylko parametry typu array. Jednakże można użyć rzutowania typów aby łączyć zmienne innych typów. Ilustruje to poniższy przykład.

Przykład #3 Przykład użycia array_merge() w PHP 5

<?php
 $poczatek = 'foo';
 $koniec = array(1 => 'bar');
 $wynik = array_merge((array)$poczatek, (array)$koniec);
 print_r($wynik);
 ?>

Powyższy przykład wyświetli:

 Array
 (
     [0] => foo
     [1] => bar
 )

Patrz także: array_merge_recursive(), array_combine() i operatory tablic.

array_merge_recursive
array_multisort
Funkcje Tablic


Sortuje wiele tablic lub wielowymiarowe tablice

array_merge
array_pad
Funkcje Tablic
PHP Manual

array_multisort

(PHP 4, PHP 5)

array_multisort — Sortuje wiele tablic lub wielowymiarowe tablice

Opis

bool array_multisort ( array $tbl1 [, mixed $arg [, mixed $... [, array $... ]]] )

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

array_multisort() może być użyta do sortowania kilku tablic na raz lub wielowymiarowej tablicy na podstawie jednego z większej liczby wymiarów.

Klucze asocjacyjne są zachowywane, a indeksy numeryczne są przenumerowywane.

Tablice wejściowe są traktowane jak kolumy tablicy, które mają być posortowane wierszami - odpowiada to funkcjonalności warunku SQL ORDER BY. Pierwsza tablica jest tablicą priorytetową do sortowania. Wiersze (wartości) w tej tablicą które są takie sane sortowane są według następnej tablicy wejściowej i tak dalej.

Struktura argumentów tej funkcji nie jest zwyczajna, ale jest ona elastyczna. Pierwszy argument musi być tablicą. Każdy następny argument musi być tablicą lub flagą oznaczającą porządek sortowania - jeden z poniższych.

Flagi porządku sortowania:

  • SORT_ASC - sortuj w porządku rosnącym
  • SORT_DESC - sortuj w porządku malejącym

Flagi typu sortowania:

  • SORT_REGULAR - porównuj elementy normalnie
  • SORT_NUMERIC - porównuj elementy numerycznie
  • SORT_STRING - porówuj elementy jak stringi

Nie można podać żadnych dwóch flag tego samego typu dla jednej tablicy. Flagi sortowania podane po argumencie-tablicy dotyczą tylko tej tablicy - są one zerowane do domyślnych wartośći SORT_ASC i SORT_REGULAR po każdym argumencie tablicowym.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Sortowanie wielu tablic

<?php
$tbl1 = array (10, 100, 100, 0);
$tbl2 = array (1, 3, 2, 4);
array_multisort ($tbl1, $tbl2);

var_dump($tbl1);
var_dump($tbl2);
?>

W tym przypadku, po sortowaniu, pierwsza tablica będzie zawierać 0, 10, 100, 100, a druga 4, 1, 2, 3. Elementy drugiej tablicy odpowiadające identycznym elementom pierwszej tablicy (100 i 100) także zostały posortowane.

array(4) {
  [0]=> int(0)
  [1]=> int(10)
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(4)
  [1]=> int(1)
  [2]=> int(2)
  [3]=> int(3)
}

Przykład #2 Sortowanie wielowymiarowych tablic

$tbl = array (
      array ("10", 100, 100, "a"),
      array (1, 3, "2", 1)
   );
array_multisort ($tbl[0], SORT_ASC, SORT_STRING,
         $tbl[1], SORT_NUMERIC, SORT_DESC);
var_dump($tbl);
?>

W tym przykładzie, po posortowaniu, pierwsza tablica przekształci się do postaci "10", 100, 100, 11, "a" (została posortowana jako ciągi znakowe w porządku rosnącym). Druga tablica będzie zawierała elementy 1, 3, "2", 2, 1 (sortowanie liczbowe w porządku malejącym).

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

Przykład #3 Sortowanie wyników zapytań do baz danych

Dla tego przykładu, każdy element tablicy dane reprezentuje pojedynczy wiersz z tabeli. Ten typ danych jest typowy dla rekordów baz danych.

Przykładowe dane:

Numer | edycja
-------+--------
   67 |      2
   86 |      1
   85 |      6
   98 |      2
   86 |      6
   67 |      7

Dane zawarte są w tablicy o nazwie dane. Efekt ten można uzyskać, na przykład, poprzez wywołując w pętli funkcję mysql_fetch_assoc().

<?php
$dane[] = array('numer' => 67, 'edycja' => 2);
$dane[] = array('numer' => 86, 'edycja' => 1);
$dane[] = array('numer' => 85, 'edycja' => 6);
$dane[] = array('numer' => 98, 'edycja' => 2);
$dane[] = array('numer' => 86, 'edycja' => 6);
$dane[] = array('numer' => 67, 'edycja' => 7);
?>

W tym przykładzie, dane zostaną posortowane według pola numer malejąco, oraz względem pola edycja rosnąco.

W zmiennej znajduje się tablica wierszy, lecz array_multisort() wymaga tablicy kolumn, tak więc należy zastosować poniższy kod aby uzyskać kolumny, a następnie przeprowadzić sortowanie.

<?php
// Pobierz listę kolumn
foreach ($dane as $klucz => $wiersz) {
    $numer[$klucz]  = $wiersz['numer'];
    $edycja[$klucz] = $wiersz['edycja'];
}

// Posortuj dane według numeru malejąco i edycji rosnąco
// Należy podać $dane jako ostatni parametr aby posortować według wspólnego
// klucza
array_multisort($numer, SORT_DESC, $edycja, SORT_ASC, $dane);
?>

Zbiór danych jest teraz posortowany. Wygląda on tak:

numer | edycja
------+--------
   98 |      2
   86 |      1
   86 |      6
   85 |      6
   67 |      2
   67 |      7

Przykład #4 Sortowanie z ignorowaniem wielkości znaków

Obie opcje, SORT_STRING i SORT_REGULAR, powodują sortowanie z rozróżnianiem wielkości znaków. Ciągi zaczynające się od dużej litery staną się ciągami zaczynającymi się od litery małej.

Aby przeprowadzić sortowanie ignorujące wielkość znaków, należy wymusić, aby porządek sortowania był określany przez kopię oryginalnej tablicy, w której wszystkie znaki zostaną zmienione na małe.

<?php
$tablica = array('Alfa', 'atomowy', 'Beta', 'bank');
$tablica_male = array_map('strtolower', $tablica);

array_multisort($tablica_male, SORT_ASC, SORT_STRING, $tablica);

print_r($tablica);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => Alfa
    [1] => atomowy
    [2] => bank
    [3] => Beta
)

array_merge
array_pad
Funkcje Tablic


Dopełnij tablicę do podanej długości podanymi wartościami

array_multisort
array_pop
Funkcje Tablic
PHP Manual

array_pad

(PHP 4, PHP 5)

array_pad — Dopełnij tablicę do podanej długości podanymi wartościami

Opis

array array_pad ( array $wejście , int $rozmiar , mixed $wartość )

array_pad() zwraca kopię tablicy wejście dopełnioną do rozmiaru określonego przez rozmiar wartością wartość. Jeśli rozmiar jest wartością dodatnią, to tablica jest dopełniana z prawej strony, jeśli ujemna to z lewej. Jeśli wartość bezwzględna parametru rozmiar jest mniejsza lub równa długości tablicy wejście, to tablica nie jest dopełniana. Możliwe jest dodanie co najwyżej 1048576 elementów za jednym wywołaniem funkcji.

Parametry

wejście

Początkowa tablica, której wartości mają być dopełnione.

rozmiar

Nowy rozmiar tablicy.

wartość

Wartość, której należy użyć do dopełniania jeśli tablica wejście jest mniejsza niż rozmiar.

Zwracane wartości

Zwraca kopię tablicy wejście dopełnioną do rozmiaru określonego przez rozmiar wartością wartość. Jeśli rozmiar jest wartością dodatnią, to tablica jest dopełniana z prawej strony, jeśli ujemna to z lewej. Jeśli wartość bezwzględna parametru rozmiar jest mniejsza lub równa długości tablicy wejście, to tablica nie jest dopełniana.

Przykłady

Przykład #1 Przykład użycia array_pad()

<?php
$wejscie = array(12, 10, 9);

$wynik = array_pad($wejscie, 5, 0);
// wynik to array(12, 10, 9, 0, 0)

$wynik = array_pad($wejscie, -7, -1);
// wynik to array(-1, -1, -1, -1, 12, 10, 9)

$wynik = array_pad($wejscie, 2, "noop");
// nie ma dopełniania
?>

Zobacz też:

  • array_fill() - Wypełnij tablicę podanymi wartościami
  • range() - Stwórz tablicę zawierającą przedział elementów

array_multisort
array_pop
Funkcje Tablic


Zdejmij element z końca tablicy

array_pad
array_product
Funkcje Tablic
PHP Manual

array_pop

(PHP 4, PHP 5)

array_pop — Zdejmij element z końca tablicy

Opis

mixed array_pop ( array &$tablica )

array_pop() zdejmuje i zwraca ostatnią wartość tablicy tablica, skracając tą tablicę o jeden element. Jeśli tablica jest pusta (lub nie jest tablicą), zwracana jest wartość NULL.

Informacja: Ta funkcja zresetuje() wskaźnik tablicy po swoim wykonaniu.

Parametry

array

Tablica, z której będą pobierane wartości.

Zwracane wartości

Zwraca ostatnią wartość z tablica. Jeśli tablica jest pusta (lub nie jest tablicą), zwracana jest wartość NULL.

Przykłady

Przykład #1 Przykład użycia array_pop()

<?php
$stos = array("pomarańcza", "banan", "jabłko", "malina");
$owoc = array_pop($stos);
print_r($stos);
?>

Po wykonaniu powyższego kodu $stos będzie miał tylko trzy elementy:

Array
(
    [0] => pomarańcza
    [1] => banan
    [2] => jabłko
)
a malina będzie przypisana do zmiennej $owoc.

Patrz także: array_push(),
array_shift() i
array_unshift().

array_pad
array_product
Funkcje Tablic


Calculate the product of values in an array

array_pop
array_push
Funkcje Tablic
PHP Manual

array_product

(PHP 5 >= 5.1.0)

array_product — Calculate the product of values in an array

Opis

number array_product ( array $array )

array_product() returns the product of values in an array.

Parametry

array

The array.

Zwracane wartości

Returns the product as an integer or float.

Przykłady

Przykład #1 array_product() examples

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";
echo "product(array()) = " . array_product(array()) . "\n";

?>

Powyższy przykład wyświetli:

product(a) = 384
product(array()) = 1

array_pop
array_push
Funkcje Tablic


Wstaw jeden lub więcej elementów na koniec tablicy

array_product
array_rand
Funkcje Tablic
PHP Manual

array_push

(PHP 4, PHP 5)

array_push — Wstaw jeden lub więcej elementów na koniec tablicy

Opis

int array_push ( array &$tablica , mixed $wartosc [, mixed $... ] )

array_push() traktuje zmienną tablica jako stos i wstawia przekazane parametry na koniec podanej tablicy. Długość parametru tablica zwiększa się o liczbę przekazanych wartości. Ma to taki sam efekt jak kod:

<?php
$tablica[] = $wartosc;
?>
powtórzony dla każdego parametru wartosc.

Funkcja zwraca nową liczbę elementów tablicy.

Przykład #1 Przykład użycia array_push()

<?php
$stos = array("pomarańcza", "banan");
array_push($stos, "jabłko", "malina");
print_r($stos);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => pomarańcza
    [1] => banan
    [2] => jabłko
    [3] => malina
)

Informacja: Jeśli funkcja array_push() ma być użyta do dodania tylko jednego elementu do tablicy, lepiej jest użyć składni $tablica[] = , ponieważ nie powoduje to narzutu przez konieczność wywołanie funkcji.

Informacja: array_push() wygeneruje ostrzeżenie, jeśli pierwszy argument nie jest tablicą. Różni się to od zachowania dla $var[], kiedy to tworzona jest nowa tablica.

Patrz także: array_pop(),
array_shift() i
array_unshift().

array_product
array_rand
Funkcje Tablic


Wybierz jeden lub więcej losowych elementów z tablicy

array_push
array_reduce
Funkcje Tablic
PHP Manual

array_rand

(PHP 4, PHP 5)

array_rand — Wybierz jeden lub więcej losowych elementów z tablicy

Opis

mixed array_rand ( array $wejście [, int $ilość ] )

Funkcja array_rand() jest przydatna jeśli chcesz wyciągnąć jeden lub więcej losowych elementów z tablicy. Jako parametry pobiera tablicę wejście i opcjonalny parameter ilość który określa ile elementów tablicy chcesz wyciągnąć - jeśli nie podano, przymowana jest domyślna wartość 1.

Jeśli wyciągasz tylko jeden element, array_rand() zwraca klucz losowego wpisu. W przeciwnym przypadku zwracana jest tablica zawierająca klucze losowych wpisów. Dzieje się tak, żeby można było wyciągnąć jednocześnie klucze i wartości losowych elementów tablicy.

Informacja: Od PHP 4.2.0 nie ma potrzeby inicjalizować generatora liczb losowych funkcją srand() lub mt_srand(), ponieważ dzieje się to automatycznie.

Przykład #1 Przykład użycia array_rand()

<?php
srand((float) microtime() * 10000000);
$wejscie = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$losowe_klucze = array_rand ($wejscie, 2);
echo $wejscie[$losowe_klucze[0]] . "\n";
echo $wejscie[$losowe_klucze[1]] . "\n";
?>

Patrz także: shuffle().

array_push
array_reduce
Funkcje Tablic


Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji zwrotnej

array_rand
array_replace_recursive
Funkcje Tablic
PHP Manual

array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce — Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji zwrotnej

Opis

mixed array_reduce ( array $wejście , callback $funkcja_zwrotna [, int $początek ] )

array_reduce() iteracyjnie stosuje funkcję funkcja_zwrotna na każdym elemencie tablicy wejście aby zredukować tablicę to pojedyńczej wartości. Jeśli podany został opcjonalny parametr początek , będzie on użyty na początku procesu, lub jako zwracana wartość jeśli tablica jest pusta. Jeśli tablica jest pusta, a parametr początek nie zostanie przekazany, array_reduce() zwraca NULL.

Przykład #1 Przykład użycia array_reduce()

<?php
function rsum($v, $w)
{
    $v += $w;
    return $v;
}

function rmul($v, $w)
{
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
?>

Po wykonaniu powyższego kodu zmienna $b będzie zawierała 15, $c 1200 (= 10*1*2*3*4*5) a $d containing 1.

Patrz także: array_filter(),
array_map(), array_unique() i
array_count_values().

array_rand
array_replace_recursive
Funkcje Tablic


Replaces elements from passed arrays into the first array recursively

array_reduce
array_replace
Funkcje Tablic
PHP Manual

array_replace_recursive

(PHP 5 >= 5.3.0)

array_replace_recursive — Replaces elements from passed arrays into the first array recursively

Opis

array array_replace_recursive ( array &$array , array &$array1 [, array &$... ] )

array_replace_recursive() replaces the values of the first array with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values.

array_replace_recursive() is recursive : it will recurse into arrays and apply the same process to the inner value.

When the value in array is scalar, it will be replaced by the value in array1, may it be scalar or array. When the value in array and array1 are both arrays, array_replace_recursive() will replace their respective value recursively.

Parametry

array

The array in which elements are replaced.

array1

The array from which elements will be extracted.

...

Optional. More arrays from which elements will be extracted.

Zwracane wartości

Returns an array, or NULL if an error occurs.

Przykłady

Przykład #1 array_replace_recursive() example

<?php
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));

$basket = array_replace_recursive($base, $replacements);
print_r($basket);

$basket = array_replace($base, $replacements);
print_r($basket);
?>

Powyższy przykład wyświetli:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

)
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
        )

)

Przykład #2 array_replace_recursive() and recursive behavior

<?php
$base = array('citrus' => array("orange") , 'berries' => array("blackberry", "raspberry"), 'others' => 'banana' );
$replacements = array('citrus' => 'pineapple', 'berries' => array('blueberry'), 'others' => array('litchis'));
$replacements2 = array('citrus' => array('pineapple'), 'berries' => array('blueberry'), 'others' => 'litchis');

$basket = array_replace_recursive($base, $replacements, $replacements2);
print_r($basket);

?>

Powyższy przykład wyświetli:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

    [others] => litchis
)

Zobacz też:

  • array_replace() - Replaces elements from passed arrays into the first array

array_reduce
array_replace
Funkcje Tablic


Replaces elements from passed arrays into the first array

array_replace_recursive
array_reverse
Funkcje Tablic
PHP Manual

array_replace

(PHP 5 >= 5.3.0)

array_replace — Replaces elements from passed arrays into the first array

Opis

array array_replace ( array &$array , array &$array1 [, array &$... ] )

array_replace() replaces the values of the first array with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.

array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array.

Parametry

array

The array in which elements are replaced.

array1

The array from which elements will be extracted.

...

More arrays from which elements will be extracted. Values from later arrays overwrite the previous values.

Zwracane wartości

Returns an array, or NULL if an error occurs.

Przykłady

Przykład #1 array_replace() example

<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

Zobacz też:

  • array_replace_recursive() - Replaces elements from passed arrays into the first array recursively

array_replace_recursive
array_reverse
Funkcje Tablic


Zwraca tablicę z elementami ustawionymi w porządku odwrotnym

array_replace
array_search
Funkcje Tablic
PHP Manual

array_reverse

(PHP 4, PHP 5)

array_reverse — Zwraca tablicę z elementami ustawionymi w porządku odwrotnym

Opis

array array_reverse ( array $wejście [, bool $zachowaj_klucze ] )

array_reverse() pobiera tablicę wejście i zwraca nową tablicę z odwróconym porządkiem występowania elementów, zachowując klucze tylko jeśli wartość parametru zachowaj_klucze to TRUE.

Przykład #1 Przykład użycia array_reverse()

<?php
$wejscie = array("php", 4.0, array ("zielony", "czerwony"));
$wynik   = array_reverse($wejscie);
$wynik_kluczowany = array_reverse($input, true);
?>

W tym przykładzie i $wynik i $wynik_kluczowny będą zawierały te same elementy, ale trzeba zauważyć różnicę w kluczach. Tablice te będą wyglądały następująco:

Array
(
    [0] => Array
        (
            [0] => zielony
            [1] => czerwony
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => zielony
            [1] => czerwony
        )

    [1] => 4
    [0] => php
)

Informacja:

Drugi parametr został dodany w PHP 4.0.3.

Patrz także: array_flip().

array_replace
array_search
Funkcje Tablic


Przeszukuje tablicę pod kątem podanej wartości i w przypadku sukcesu zwraca odpowiedni klucz

array_reverse
array_shift
Funkcje Tablic
PHP Manual

array_search

(PHP 4 >= 4.0.5, PHP 5)

array_search — Przeszukuje tablicę pod kątem podanej wartości i w przypadku sukcesu zwraca odpowiedni klucz

Opis

mixed array_search ( mixed $igła , array $stóg_siana [, bool $ścisły ] )

Przeszukuje stóg_siana w poszukiwaniu parametru igła i zwraca odpowiedni klucz jeśli został on znaleziony lub FALSE w przeciwnym przypadku.

Informacja:

Jeśli igła jest ciągiem tekstowym, to porówywanie jest dokonywane z uwzględnieniem wielkości znaków.

Informacja:

Począwszy od PHP 4.2.0, zamiast FALSE, array_search() zwraca NULL w przypadku niepowodzenia.

Jeśli trzeci parametr ścisły jest ustawiony na TRUE to array_search() porówna także typy parametru igła z tymi z parametru stóg_siana.

Jeśli igła zostanie znaleziona w stóg_sianawięcej niż raz, to zwracany zostanie klucz pierwszego pasującego elementu. Aby uzyskać klucze wszystkich pasujących wartości należy zastosować funkcję array_keys() z opcjonalnym parametrem szukana_wartość.

Przykład #1 Przykład użycia array_search()

<?php
$tablica = array(0 => 'niebieski', 1 => 'czerwony', 2 => 'zielony', 3 => 'czerwony');

$klucz = array_search('zielony',  $tablica); // $klucz = 2;
$klucz = array_search('czerwony', $tablica); // $klucz = 1;
?>

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Patrz także: array_keys(),
array_values(), array_key_exists()
i in_array().

array_reverse
array_shift
Funkcje Tablic


Usuń element z początku tablicy

array_search
array_slice
Funkcje Tablic
PHP Manual

array_shift

(PHP 4, PHP 5)

array_shift — Usuń element z początku tablicy

Opis

mixed array_shift ( array &$tablica )

array_shift() usuwa pierwszą wartość parametru tablica i zwraca go skracając tą tablicę o jeden element przesuwając wszystkie pozostałe elementy w dół. Wszystkie klucze liczbowe zostaną zmodyfikowane tak, aby ich wartości zaczynały się od zera, podczas gdy klucze znakowe nie zostaną zmienione. Jeśli tablica jest pusta (lub nie jest tablicą), zwracana jest wartość NULL.

Informacja: Ta funkcja zresetuje() wskaźnik tablicy po swoim wykonaniu.

Przykład #1 Przykład użycia array_shift()

<?php
$stos = array ("pomarańcza", "banan", "jabłko", "malina");
$owoc = array_shift ($stos);
?>

Zmienna $stos będzie miała 3 elementy:

Array
(
    [0] => banan
    [1] => jabłko
    [2] => malina
)

a pomarańcza będzie przypisana do zmiennej $owoc

Patrz także: array_unshift(),
array_push() i
array_pop().

array_search
array_slice
Funkcje Tablic


Wytnij kawałek tablicy

array_shift
array_splice
Funkcje Tablic
PHP Manual

array_slice

(PHP 4, PHP 5)

array_slice — Wytnij kawałek tablicy

Opis

array array_slice ( array $tablica , int $przesunięcie [, int $długość [, bool $zachowaj_klucze ]] )

array_slice() zwraca sekwencję elementów z tablicy tablica określony przez parametry przesunięcie i długość.

Jeśli przesunięcie jest nieujemne, sekwencja zacznie się od miejsca wskazanego w tym parametrze. Jeśli przesunięcie jest ujemne, sekwencja zacznie się o tyle elementów od końca tablicy tablica.

Jeśli podany jest parametr długość i jest on dodatni, to sekwencja będzie miała tyle elementów ile podano w tym parameterz. Jeśli długość jest ujemna, to sekwencja skończy się o tyle elementów od końca tablicy. Jeśli został pominięty, to sekwencja będzie zawierać wszystko od przesunięcie do końca parametru tablica.

Należy pamiętać, że array_slice() domyślnie przenumeruje i zresetuje indeksy tablicy. Od wersji PHP 5.0.2 możliwa jest zmiana tego zachowania poprzez ustawienie wartości argumentu zachowaj_klucze na TRUE.

Przykład #1 Przykład użycia array_slice()

<?php
$wejscie = array ("a", "b", "c", "d", "e");

$wyjscie = array_slice ($wejscie, 2);      // zwraca "c", "d" i "e"
$wyjscie = array_slice ($wejscie, -2, 1);  // zwraca "d"
$wyjscie = array_slice ($wejscie, 0, 3);   // zwraca "a", "b" i "c"

// zauważ różnicę w kluczach tablicy
print_r(array_slice($wejscie, 2, -1));
print_r(array_slice($wejscie, 2, -1, true));

?>

Powyższy przykład wyświetli:

Array
(
    [0] => c
    [1] => d
)

Array
(
    [2] => c
    [3] => d
)

Patrz także: array_splice() i unset().

array_shift
array_splice
Funkcje Tablic


Usuń część tablicy i zamień ją na coś innego

array_slice
array_sum
Funkcje Tablic
PHP Manual

array_splice

(PHP 4, PHP 5)

array_splice — Usuń część tablicy i zamień ją na coś innego

Opis

array array_splice ( array &$wejście , int $przesunięcie [, int $długość [, array $zamiennik ]] )

array_splice() usuwa z tablicy wejście elementy określone przez parametry przesunięcie i długość, i zamienia je przez elementy tablicy zamiennik, jeśli została ona podana. Funkcja zwraca tablice zawierającą usunięte elementy. Liczbowe klucze tablicy wejście nie są zachowywane.

Jeśli przesunięcie jest dodatnie, to początek usuwanej części tablicy wejście znajduje się w miejscu określonym przez ten parametr. Jeśli przesunięcie jest ujemne, to wycinanie zaczyna się o tyle elementów od końca tablicy wejście.

Jeśli długość została pominięta, to usunięte jest wszystko od przesunięcie do końca tablicy. Jeśli długość jest podana i dodatnia, to tyle elementów zostanie usuniętych. Jeśli długość jest podana i jest ujemna, to koniec usuwanego kawałka tablicy będzie się znajdował o tyle elementów od końca tablicy. Wskazówka: aby usunąć wszystko od przesunięcie do końca tablicy podając także parametr zamiennik, użyj count($wejście) jako długość.

Jeśli podana została tablica zamiennik, to wszystkie usunięte elementy są zamieniane na elementy z tej tablicy. Jeśli przesunięcie i długość zostały podane tak, że żadne elementy nie zostaną usunięte, to elementy z tablicy zamiennik są wstawiane w miejsce określone przez przesunięcie. Klucze w zamienniku nie są zachowywane. Jeśli zamiennik to tylko jeden element, to nie trzeba go wstawiać do array(), chyba że element jest właśnie tablicą.

Poniższe wyrażenia zmieniają wartość tablicy $wejscie w ten sam sposób:

Równoważności array_splice()
array_push($wejscie, $x, $y) | array_splice($wejscie, count($wejscie), 0, array($x, $y))
array_pop($wejscie) | array_splice($wejscie, -1)
array_shift($wejscie) | array_splice($wejscie, 0, 1)
array_unshift($wejscie, $x, $y) | array_splice($wejscie, 0, 0, array($x, $y))
$wejscie[$x] = $y // dla tablic gdzie klucz jest równy przesunięciu | array_splice($wejscie, $x, 1, $y)

Funkcja zwraca tablicę zawierającą usunięte elementy.

Przykład #1 Przykład użycia array_splice()

<?php
$wejscie = array ("czerwony", "zielony", "niebieski", "żółty");
array_splice ($wejscie, 2);
// $wejscie to teraz array ("czerwony", "zielony")

$wejscie = array ("czerwony", "zielony", "niebieski", "żółty");
array_splice ($wejscie, 1, -1);
// $wejscie to teraz array ("czerwony", "żółty")

$wejscie = array ("czerwony", "zielony", "niebieski", "żółty");
array_splice ($wejscie, 1, count($wejscie), "pomarańczowy");
// $wejscie to teraz array ("czerwony", "pomarańczowy")

$wejscie = array ("czerwony", "zielony", "niebieski", "żółty");
array_splice ($wejscie, -1, 1, array("czarny", "kasztanowy"));
// $wejscie to teraz array ("czerwony", "zielony",
//          "niebieski", "czarny", "kasztanowy")

$wejscie = array("czerwony", "zielony", "niebieski", "żółty");
array_splice($wejscie, 3, 0, "fioletowy");
// $wejscie to teraz array("czerwony", "zielony",
//          "niebieski", "fioletowy", "żółty");
?>

Patrz także: array_slice(), unset() i array_merge().

array_slice
array_sum
Funkcje Tablic


Oblicza sumę wartości w tablicy

array_splice
array_udiff_assoc
Funkcje Tablic
PHP Manual

array_sum

(PHP 4 >= 4.0.4, PHP 5)

array_sum — Oblicza sumę wartości w tablicy

Opis

liczba array_sum ( array $tablica )

array_sum() zwraca sumę wszystkich wartości w tablicy jako liczbę całkowitą lub rzeczywistą.

Przykład #1 Przykład użycia array_sum()

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

Powyższy przykład wyświetli:

sum(a) = 20
sum(b) = 6.9

Informacja:

PHP w wersjach wcześniejszych niż 4.2.1 modyfikowało przetwarzaną tablicę i konwertowało ciągi na liczby (większość z nich była konwertowana na wartość zero, zależnie od zawartości).

array_splice
array_udiff_assoc
Funkcje Tablic


Computes the difference of arrays with additional index check, compares data by a callback function

array_sum
array_udiff_uassoc
Funkcje Tablic
PHP Manual

array_udiff_assoc

(PHP 5)

array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function

Opis

array array_udiff_assoc ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )

Computes the difference of arrays with additional index check, compares data by a callback function.

Informacja: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.

Parametry

array1

The first array.

array2

The second array.

data_compare_func

The callback comparison function.

The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Zwracane wartości

array_udiff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.

Przykłady

Przykład #1 array_udiff_assoc() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

Powyższy przykład wyświetli:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the output from the function.

Zobacz też:

  • array_diff() - Zwraca różnice pomiędzy tablicami
  • array_diff_assoc() - Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_intersect() - Zwraca przecięcie tablic
  • array_intersect_assoc() - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

array_sum
array_udiff_uassoc
Funkcje Tablic


Computes the difference of arrays with additional index check, compares data and indexes by a callback function

array_udiff_assoc
array_udiff
Funkcje Tablic
PHP Manual

array_udiff_uassoc

(PHP 5)

array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function

Opis

array array_udiff_uassoc ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func , callback $key_compare_func )

Computes the difference of arrays with additional index check, compares data and indexes by a callback function.

Note that the keys are used in the comparison unlike array_diff() and array_udiff().

Parametry

array1

The first array.

array2

The second array.

data_compare_func

The callback comparison function.

The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The comparison of arrays' data is performed by using an user-supplied callback : data_compare_func. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.

key_compare_func

The comparison of keys (indices) is done also by the callback function key_compare_func. This behaviour is unlike what array_udiff_assoc() does, since the latter compares the indices by using an internal function.

Zwracane wartości

Returns an array containing all the values from array1 that are not present in any of the other arguments.

Przykłady

Przykład #1 array_udiff_uassoc() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }

    static function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>

Powyższy przykład wyświetli:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the output from the function. Keep in mind that you have to supply 2 callback functions.

Notatki

Informacja: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.

Zobacz też:

  • array_diff() - Zwraca różnice pomiędzy tablicami
  • array_diff_assoc() - Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_intersect() - Zwraca przecięcie tablic
  • array_intersect_assoc() - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

array_udiff_assoc
array_udiff
Funkcje Tablic


Computes the difference of arrays by using a callback function for data comparison

array_udiff_uassoc
array_uintersect_assoc
Funkcje Tablic
PHP Manual

array_udiff

(PHP 5)

array_udiff — Computes the difference of arrays by using a callback function for data comparison

Opis

array array_udiff ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )

Computes the difference of arrays by using a callback function for data comparison. This is unlike array_diff() which uses an internal function for comparing the data.

Parametry

array1

The first array.

array2

The second array.

data_compare_func

The callback comparison function.

The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Zwracane wartości

Returns an array containing all the values of array1 that are not present in any of the other arguments.

Przykłady

Przykład #1 array_udiff() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

Powyższy przykład wyświetli:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

Notatki

Informacja: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_udiff($array1[0], $array2[0], "data_compare_func");.

Zobacz też:

  • array_diff() - Zwraca różnice pomiędzy tablicami
  • array_diff_assoc() - Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_intersect() - Zwraca przecięcie tablic
  • array_intersect_assoc() - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

array_udiff_uassoc
array_uintersect_assoc
Funkcje Tablic


Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną

array_udiff
array_uintersect_uassoc
Funkcje Tablic
PHP Manual

array_uintersect_assoc

(PHP 5)

array_uintersect_assoc — Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną

Opis

array array_uintersect_assoc ( array $tablica1 , array $tablica2 [, array $ ... ], callback $funk_porównująca )

array_uintersect_assoc() zwraca tablicę zawierającą wszystkie wartości z tablica1 które występują we wszystkich pozostałych argumentach. Do porównywania, w przeciwieństwie do funkcji array_uintersect(), używane są klucze tablic. Do porównywania danych używana jest funkcja zwrotna.

Przykład #1 Przykład użycia array_uintersect_assoc()

<?php
$tablica1 = array("a" => "zielony", "b" => "brązowy", "c" => "niebieski", "czerwony");
$tablica2 = array("a" => "ZIELONY", "B" => "brązowy", "żółty", "czerwony");

print_r(array_uintersect_assoc($tablica1, $tablica2, "strcasecmp"));
?>

Powyższy przykład wyświetli:

Array
(
    [a] => zielony
)

Porównanie jest dokonywane przy pomocy podanej funkcji zwrotnej. Musi ona zwracać liczbę całkowitą mniejszą, równą lub większą od zera jeśli pierwszy klucz jest uznawany za mniejszy, równy lub większy drugiego.

Patrz także: array_uintersect(),
array_intersect_assoc(),
array_intersect_uassoc() i
array_uintersect_uassoc().

array_udiff
array_uintersect_uassoc
Funkcje Tablic


Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

array_uintersect_assoc
array_uintersect
Funkcje Tablic
PHP Manual

array_uintersect_uassoc

(PHP 5)

array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

Opis

array array_uintersect_uassoc ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func , callback $key_compare_func )

Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions Note that the keys are used in the comparison unlike in array_uintersect(). Both the data and the indexes are compared by using separate callback functions.

Parametry

array1

The first array.

array2

The second array.

data_compare_func

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

key_compare_func

Key comparison callback function.

Zwracane wartości

Returns an array containing all the values of array1 that are present in all the arguments.

Przykłady

Przykład #1 array_uintersect_uassoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>

Powyższy przykład wyświetli:

Array
(
    [a] => green
    [b] => brown
)

Zobacz też:

  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_intersect_assoc() - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_assoc() - Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną

array_uintersect_assoc
array_uintersect
Funkcje Tablic


Computes the intersection of arrays, compares data by a callback function

array_uintersect_uassoc
array_unique
Funkcje Tablic
PHP Manual

array_uintersect

(PHP 5)

array_uintersect — Computes the intersection of arrays, compares data by a callback function

Opis

array array_uintersect ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )

Computes the intersection of arrays, compares data by a callback function.

Parametry

array1

The first array.

array2

The second array.

data_compare_func

The callback comparison function.

The user supplied callback function is used for comparison. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Zwracane wartości

Returns an array containing all the values of array1 that are present in all the arguments.

Przykłady

Przykład #1 array_uintersect() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?>

Powyższy przykład wyświetli:

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

Zobacz też:

  • array_intersect() - Zwraca przecięcie tablic
  • array_intersect_assoc() - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
  • array_uintersect_assoc() - Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

array_uintersect_uassoc
array_unique
Funkcje Tablic


Usuwa duplikaty wartości z tablicy

array_uintersect
array_unshift
Funkcje Tablic
PHP Manual

array_unique

(PHP 4 >= 4.0.1, PHP 5)

array_unique — Usuwa duplikaty wartości z tablicy

Opis

array array_unique ( array $tablica [, int $opcje_sortowania = SORT_STRING ] )

Pobiera parametr tablica i zwraca nową tablicę bez duplikatów wartości.

Zauważ, że klucze są zachowywane. array_unique() najpierw sortuje wartości skonwertowane na ciągi a później zachowuje pierwszy napotkany klucz dla każdej wartości ignorując wszystkie pozostałe klucze. Nie oznacza to, że klucz pierwszej związanej wartości z nieposortowanej tablicy będzie zachowany.

Informacja: Dwa elementy tablicy są uważane za równe wtedy i tylko wtedy jeśli (string) $elem1 === (string) $elem2, czyli jeśli reprezentacje wartości w postaci stringów są takie same. Używany będzie pierwszy element.

Parametry

tablica

Tablica wejściowa.

opcje_sortowania

Drugi, opcjonalny parametr opcje_sortowania może być użyty do zmiany zachowania podczas sortowania za pomocą następujących wartości:

Opcje sortowania:

  • SORT_REGULAR - porównuje pozycje normalnie (nie zmienia typów)
  • SORT_NUMERIC - porównuje pozycje numerycznie
  • SORT_STRING - porównuje pozycje jako łańcuchy znaków
  • SORT_LOCALE_STRING - porównuje pozycje jako łańcuchy znaków, w uwzględniając bieżące kodowanie znaków.

Zwracane wartości

Zwraca posortowaną tablicę.

Rejestr zmian

Wersja | Opis
5.2.10 | Zmiana domyślnej wartości opcje_sortowania ponowanie na SORT_STRING.
5.2.9 | Dodano nową domyślną opcje_sortowania SORT_REGULAR. Przed PHP 5.2.9, ta funkcja była używana wewnętrznie do sortowania tablic z opcją SORT_STRING.

Przykłady

Przykład #1 Przykład użycia array_unique()

<?php
$wejscie = array ("a" => "zielony", "czerwony", "b" => "zielony", "niebieski", "czerwony");
$wynik = array_unique ($wejscie);
print_r($wynik);
?>

Powyższy przykład wyświetli:

Array
(
    [a] => zielony
    [0] => czerwony
    [1] => niebieski
)

Przykład #2 array_unique() i typy

<?php
$wejscie = array(4, "4", "3", 4, 3, "3");
$wynik = array_unique($wejscie);
var_dump($wynik);
?>

Powyższy przykład wyświetli:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

Zobacz też:

  • array_count_values() - Zlicza wszystkie wartości w tablicy

Notatki

Informacja: Zauważ, że funkcja array_unique() nie jest przeznaczona do pracy na wielowymiarowych tablicach.

array_uintersect
array_unshift
Funkcje Tablic


Wstaw jeden lub więcej elementów na początek tablicy

array_unique
array_values
Funkcje Tablic
PHP Manual

array_unshift

(PHP 4, PHP 5)

array_unshift — Wstaw jeden lub więcej elementów na początek tablicy

Opis

int array_unshift ( array &$tablica , mixed $wartość [, mixed $... ] )

array_unshift() wstawia jeden lub więcej przekazanych jako parametry elementów na początek tablicy tablica. Zauważ, że lista elementów wstawiana jako całość, więc elementy zostają w takim samym porządku. Wszystkie klucze liczbowe zostaną zmodyfikowane tak, aby ich wartości zaczynały się od zera, podczas gdy klucze znakowe nie zostaną zmienione.

Funkcja zwraca nową liczbę elementów w tablicy tablica.

Przykład #1 Przykład użycia array_unshift()

<?php
$kolejka = array ("pomarańcza", "banan");
array_unshift ($kolejka, "jabłko", "malina");
print_r($kolejka);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => jabłko
    [1] => malina
    [2] => pomarańcza
    [3] => banan
)

Patrz także: array_shift(),
array_push() i
array_pop().

array_unique
array_values
Funkcje Tablic


Zwraca wszystkie wartości z tablicy

array_unshift
array_walk_recursive
Funkcje Tablic
PHP Manual

array_values

(PHP 4, PHP 5)

array_values — Zwraca wszystkie wartości z tablicy

Opis

array array_values ( array $wejście )

array_values() zwraca wszystkie wartości z tablicy wejście i indeksuje tablicę liczbowo.

Przykład #1 Przykład użycia array_values()

$tablica = array ("rozmiar" => "XL", "kolor" => "złoty");
print_r(array_values ($tablica));

Powyższy przykład wyświetli:

+Array
(
    [0] => XL
    [1] => złoty
)

Patrz także: array_keys().

array_unshift
array_walk_recursive
Funkcje Tablic


Apply a user function recursively to every member of an array

array_values
array_walk
Funkcje Tablic
PHP Manual

array_walk_recursive

(PHP 5)

array_walk_recursive — Apply a user function recursively to every member of an array

Opis

bool array_walk_recursive ( array &$input , callback $funcname [, mixed $userdata ] )

Applies the user-defined function funcname to each element of the input array. This function will recurse into deeper arrays.

Parametry

input

The input array.

funcname

Typically, funcname takes on two parameters. The input parameter's value being the first, and the key/index second.

Informacja:

If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.

userdata

If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 array_walk_recursive() example

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

Powyższy przykład wyświetli:

a holds apple
b holds banana
sour holds lemon

You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function.

Zobacz też:

  • array_walk() - Zastosuj funkcję użytkownika do każdego elementu tablicy
  • informacje o typie callback

array_values
array_walk
Funkcje Tablic


Zastosuj funkcję użytkownika do każdego elementu tablicy

array_walk_recursive
array
Funkcje Tablic
PHP Manual

array_walk

(PHP 4, PHP 5)

array_walk — Zastosuj funkcję użytkownika do każdego elementu tablicy

Opis

bool array_walk ( array &$tablica , callback $nazwa_funkcji [, mixed $dane ] )

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Wykonuje zdefiniowaną przez użytkownika funkcję nazwa_funkcji na każdym elemencie tablicy tablica. Zazwyczaj nazwa_funkcji przyjmuje dwa argumenty. Pierwszym jest element tablicy tablica, natomiast drugim klucz lub numer indeksu tego elementu. Jeśli do funkcji array_walk() podany zostanie trzeci element, dane, będzie on przekazany do nazwa_funkcji jako jej trzeci argument.

Jeśli nazwa_funkcji wymaga więcej parametrów niż zostało jej przekazanych, wygenerowany zostanie błąd poziomu E_WARNING dla każdego wywołania funkcji podanej jako parametr. Ostrzeżenia te mogą być wyciszone poprzez skorzystanie z operatora kontroli błędów @ przed wywołaniem array_walk(), lub też poprzez użycie funkcji error_reporting().

Informacja:

Jeśli nazwa_funkcji ma zmieniać wartości tablicy, należy określić pierwszy argument nazwa_funkcji jako referencję. W tym przypadku wszystkie zmiany dokonane przez tą funkcję będą dokonywane bezpośrednio na oryginalnej tablicy.

Informacja:

Przekazywanie klucza i danych użytkownika do nazwa_funkcji zostało dodane w PHP 4.0.0.

Na działanie array_walk() nie wpływa pozycja wewnętrznego wskaźnika tablicy. array_walk() przetworzy wszystkie elementy argumentu tablica, niezależnie odpozycji jej wewnętrznego wskaźnika.

Użytkownicy nie mogą zmieniać samej tablicy z wnętrza funkcji zwrotnej, to jest dodawać/usuwać elementy, usuwać elementy tablicy na której jest wywoływana funkcja array_walk(). Jeśli ta tablica zostanie zmieniona, funkcja może się zachowywać w sposób nieokreślony i nieprzewidywalny..

Przykład #1 Przykład użycia array_walk()

<?php
$owoce = array ("d"=>"cytryna", "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");

function test_zmiana (&$element1, $klucz, $prefiks)
{
    $element1 = "$prefiks: $element1";
}

function test_wyswietlanie ($element2, $klucz)
{
    echo "$klucz. $element2<br />\n";
}

echo "Przed ...:\n";
array_walk ($owoce, 'test_wyswietlanie');

array_walk ($owoce, 'test_zmiana', 'owoc');
echo "... i po:\n";

array_walk ($owoce, 'test_wyswietlanie');
?>

Powyższy przykład wyświetli:

Przed ...:
d. cytryna
a. pomarańcza
b. banan
c. jabłko
... i po:
d. owoc: cytryna
a. owoc: pomarańcza
b. owoc: banan
c. owoc: jabłko

Patrz także:
array_walk_recursive(),
create_function(),
list(),
foreach,
each(),
call_user_func_array(), and
array_map() i
informacje o typie callback.

array_walk_recursive
array
Funkcje Tablic


Stwórz tablicę

array_walk
arsort
Funkcje Tablic
PHP Manual

array

(PHP 4, PHP 5)

array — Stwórz tablicę

Opis

array array ([ mixed $... ] )

Zwraca tablicę stworzoną z podanych parametrów. Parametry mogą być indeksowane przy pomocy operatora => operator. Więcej informacji o tym czym są tablice można znaleźć w rodziale o typie tablicowym.

Informacja:

array() jest składnią języka używaną do tekstowej reprezentacji tablic, a nie zwykłą funkcją.

Składnia "index => wartości", oddzielona przecinkami, definiuje pary indeksów i wartości. Indeks może być ciągiem tekstowym lub liczbą stałoprzecinkową. Jeśli indeks zostanie pominięty, automatycznie wygenerowany zostanie indeks będący liczbą całkowitą, poczynając od 0. Jeśli indeks jest liczbą całkowitą, następny wygenerowany indeks będzie miał wartość "największy indeks + 1". Zauważ, że jeśli pojawią się dwie wartości o tym samym indeksie, ostatnia nadpisze wcześniejsze.

Przecinek po ostatniej podanej wartości, mimo że jest niespotykany, jest poprawny składniowo.

Poniższy przykład demonstruje jak stworzyć wielowymiarową tablicę, jak określić klucze w tablicy asocjacyjnej i jak pominąć-i-kontynuować liczbowe indeksy w normalnych tablicach.

Przykład #1 Przykład użycia array()

<?php
$owoce = array (
   "owoce"  => array("a"=&gt;"pomarańcza", "b"=&gt;"banan", "c"=&gt;"jabłko"),
   "liczby" => array(1, 2, 3, 4, 5, 6),
   "dziury" => array("pierwszy", 5 =&gt; "drugi", "trzeci")
);
?>

Przykład #2 Automatyczne indeksowanie w funkcji array()

<?php
$array = array( 1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Zauważ, że indeks '3' jest zdefiniowany dwa razy i przchowuje on końcową wartość 13. Indeks 4 jest zdefiniowany po indeksie 8, a następnym wygenerowanym indeksem (dla wartości 19) jest 9, ponieważ największym poprzednim indeksem było 8.

Ten przykład tworzy tablicę o początku 1.

Przykład #3 Indeksowanie od 1 w array()

<?php
$pierwszy_kwartal  = array(1 => 'Styczeń', 'Luty', 'Marzec');
print_r($pierwszy_kwartal);
?>

Powyższy przykład wyświetli:

Array
(
    [1] => Styczeń
    [2] => Luty
    [3] => Marzec
)

Podobnie jak w Perlu, wartość z tablicy można uzyskać wewnątrz cudzysłowów. Jednakże w PHP niezbędne jest zawarcie zmiennej wewnątrz nawiasów klamrowych.

Przykład #4 Odczytywanie elementu tablicy wewnątrz cudzysłowów

<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>

Patrz także: array_pad(), list(), count(), foreach i range().

array_walk
arsort
Funkcje Tablic


Sortuje tablicę w porządku odwrotnym z zachowaniem skojarzenia kluczy

array
asort
Funkcje Tablic
PHP Manual

arsort

(PHP 4, PHP 5)

arsort — Sortuje tablicę w porządku odwrotnym z zachowaniem skojarzenia kluczy

Opis

bool arsort ( array &$tablica [, int $flagi ] )

Ta funkcja sortuje tablicę w taki sposób, że klucze zachowują przypisanie do odpowiednich wartości. Ten sposób sortowania jest używany głównie przy sortowaniu tablic asocjacyjnych, gdzie znacząca jest kolejność występowania elementów w tablicy.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia arsort()

<?php
$owoce = array("d" => "cytryna", "a" => "pomarańcza", "b" => "banan", "c" => "jabłko");
arsort($owoce);
foreach ($owoce as $key => $val) {
    echo "$key = $val\n";
}
?>

Powyższy przykład wyświetli:

a = pomarańcza
c = jabłko
d = cytryna
b = banan

Owoce zostały posortowane w odwrotnym porządku alfabetycznym a skojarzenia kluczy dla każdego elementu zostały zachowane.

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także: asort(), rsort(), ksort() i sort().

array
asort
Funkcje Tablic


Posortuj tablicę zachowując skojarzenia kluczy

arsort
compact
Funkcje Tablic
PHP Manual

asort

(PHP 4, PHP 5)

asort — Posortuj tablicę zachowując skojarzenia kluczy

Opis

bool asort ( array &$tablica [, int $flagi ] )

Funkcja ta sortuje tablicę w taki sposób, że klucze zachowują przypisanie do odpowiednich wartości. Ten sposób sortowania jest używany głównie przy sortowaniu tablic asocjacyjnych, gdzie znacząca jest kolejność występowania elementów w tablicy.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia asort()

<?php
$owoce = array ("d"=>"cytryna", "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");
asort ($owoce);
foreach ($owoce as $key => $val) {
    echo "$key = $val\n";
}
?>

Powyższy przykład wyświetli:

b = banan
d = cytryna
c = jabłko
a = pomarańcza

Owoce zostały posortowane w porządku alfabetycznym a skojarzenia kluczy dla każdego elementu zostały zachowane.

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także: arsort(), rsort(), ksort() i sort().

arsort
compact
Funkcje Tablic


Stwórz tablicę zawierającą zmienne i ich wartości

asort
count
Funkcje Tablic
PHP Manual

compact

(PHP 4, PHP 5)

compact — Stwórz tablicę zawierającą zmienne i ich wartości

Opis

array compact ( mixed $nazwa_zmiennej [, mixed $... ] )

compact() pobiera zmienną liczbę parametrów. Każdy parametr może być albo stringiem zawierającym nazwę zmiennej lub tablicę nazw zmiennych. Tablica może zaierać w sobie inne tablice nazw zmiennych; compact() obsłuży je rekurencyjnie.

Dla każdej z nich compact() sprawdza zmienną o nazwie określnej przez bieżący symbol w tablicy i dodaje ją do tablicy wyjściowej tak, że nazwa zmiennej staje się kluczem z zawartość zmiennej wartością dla tego klucza. W skrócie, funkcja ta jest przeciwnością extract(). Zwraca ona tablicę zawierającą zmienne do niej dodane.

Dowolne ciągi tekstowe, które nie są ustawione, poprostu będą pominięte.

Informacja:

Ponieważ zmienne zmienne nie mogą być używane w połączeniu z tablicami superglobalnymi wewnątrz funkcji, tablice superglobalne nie mogą być przekazywane do funkcji compact().

Przykład #1 Przykład użycia compact()

<?php
$miasto = "San Francisco";
$stan = "CA";
$wydarzenie = "SIGGRAPH";

$zmienne_lokalizacyjne = array("miasto", "stan");

$wynik = compact("wydarzenie", "nic", $zmienne_lokalizacyjne);
print_r($wynik);

Powyższy przykład wyświetli:

+Array
(
    [wydarzenie] => SIGGRAPH
    [miasto] => San Francisco
    [stan] => CA
)

Patrz także: extract().

asort
count
Funkcje Tablic


Zlicza ilość elementów w tablicy lub pól obiektu

compact
current
Funkcje Tablic
PHP Manual

count

(PHP 4, PHP 5)

count — Zlicza ilość elementów w tablicy lub pól obiektu

Opis

int count ( mixed $zmienna [, int $tryb ] )

Zwraca ilość elementów w parametrze zmienna, która zazwyczaj będzie tablicą, jako że wszystko inne będzie miało jeden element.

Dla obiektów, jeśli zainstalowane zostało rozszerzenie SPL, możliwe jest podłączenie do count() poprzez zaimplementowanie interfejsu Countable. Interfejs ten posiada dokładnie jedną metodę, count(), która zwraca wartość, którą ma zwrócić funkcja count().

Jeśli zmienna nie jest tablicą ani obiektem z zaimplementowanym interfejsem Countable, to zwracana będzie wartość 1. Istnieje jeden wyjątek - jeśli zmienna będzie miała wartość NULL, zwrócona zostanie wartość 0.

Informacja: Opcjonalny argument tryb dostępny jest od wersji PHP 4.2.0.

Jeśli opcjonalny argument tryb ustawiony jest na COUNT_RECURSIVE (lub 1), count() będzie zliczał elementy rekurencyjnie. Jest to przydatne przy zliczaniu ilości wszystkich elementów tablicy wielowymiarowej. Domyślna wartość argumentu tryb to 0. count() nie wykrywa nieskończonej rekurencji.

Uwaga

count() może zwrócić 0 dla zmiennej, która nie została zainicjalizowana, ale możę zwrócić także 0 dla zmiennej która została zainicjalizowana pustą tablicą. Użyj isset() aby sprawdzić czy zmienna została ustawiona.

Więcej informacji na temat sposobu implementacji tablic w PHP można znaleźć w rozdziale Tablice.

Przykład #1 Przykład użycia count()

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$wynik = count ($a);
// $wynik == 3

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$wynik = count ($b);
// $wynik == 3

$wynik = count(null);
// $wynik == 0

$wynik = count(false);
// $wynik = 1

?>

Przykład #2 Przykład rekurencyjnego przetwarzania przez count() (PHP >= 4.2.0)

<?php
$jedzenie = array('owoce' => array('pomarańcza', 'banan', 'jabłko'),
                'warzywa' => array('marchewka', 'kukurydza', 'groszek'));

// zliczanie rekurencyjne
echo count($jedzenie, COUNT_RECURSIVE); // wyświetli 8

// normal count
echo count($jedzenie); // wyświetli 2

?>

Patrz także: is_array(),
isset() i
strlen().

compact
current
Funkcje Tablic


Zwraca bieżący element tablicy

count
each
Funkcje Tablic
PHP Manual

current

(PHP 4, PHP 5)

current — Zwraca bieżący element tablicy

Opis

mixed current ( array &$tablica )

Każda tablica ma wewnętrzny wskaźnik bo swojego "bieżącego" elementu, który jest inicjalizowany do pierwszego elementu wstawionego do tablicy.

Funkcja current() po prostu zwraca wartość elementu tablicy, na który aktualnie wskazuje wewnętrzny wskaźnik. Nie przesuwa ona wskaźnika. Jeśli wewnętrzny wskaźnik jest poza końcem listy elementów, current() zwraca FALSE.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Informacja: Nie będziesz mógł odróznić końca tablicy od elementu FALSE typu bool'owskiego. Aby poprawnie przejść przez tablicę, która może zawierać elementy FALSE, zobacz funkcję each().

Przykład #1 Przykład użycia funkcji current() i innych podobnych

<?php
$transport = array('stopy', 'rower', 'samochód', 'samolot');
$tryb = current($transport); // $tryb = 'stopy';
$tryb = next($transport);    // $tryb = 'rower';
$tryb = current($transport); // $tryb = 'rower';
$tryb = prev($transport);    // $tryb = 'stopy';
$tryb = end($transport);     // $tryb = 'samolot';
$tryb = current($transport); // $tryb = 'samolot';
?>

Patrz także: end(), key(),
next(), prev() i
reset() i each().

count
each
Funkcje Tablic


Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicy

current
end
Funkcje Tablic
PHP Manual

each

(PHP 4, PHP 5)

each — Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicy

Opis

array each ( array $tablica )

Zwraca bieżącą parę klucza i wartości z tablicy tablica i przesuwa wewnętrzny wskaźnik tablicy do przodu o jeden element. Para ta jest zwracana jako czteroelementowa tablica, z kluczami 0, 1, key i value. Elementy 0 i key zawierają nazwę klucza elementu tablicy, a 1 i value zawierają wartość elementu tablicy.

Jeśli wewnętrzny wskaźnik tablicy wskazuje na miejsce poza końcem zawartości tablicy, each() zwraca FALSE.

Przykład #1 Przykłady użycia each()

<?php
$foo = array ("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each ($foo);
print_r($bar);
?>

$bar zawiera teraz następujące pary klucz/wartość:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo = array ("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each ($foo);
print_r($bar);
?>

$bar zawiera teraz następujące pary klucz/wartość:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() jest zazwyczaj używana w połączeniu z list() aby przejść przez tablicę. Oto przykład takiego zastosowania:

Przykład #2 Przechodzenie przez zmienną korzystając z funkcji each()

<?php
$owoce = array('a' => 'jabłko', 'b' => 'banan', 'c' => 'truskawka');
reset ($owoce);
while (list ($klucz, $wartosc) = each ($owoce)) {
   echo "$klucz => $wartosc\n";
}
?>

Powyższy przykład wyświetli:

a => jabłko
b => banan
c => truskawka

Po wykonaniu each(), wewnętrzny wskaźnik tablicy będzie pozostawiony na następnym elementcie tablicy, lub za ostatnim elementem jeśli dojdzie ona do końca tablicy. Musisz użyć reset() jeśli chcesz przejść przez tablicę jeszcze raz korzystając z funkcji each.

Uwaga

Jako że przypisywanie tablicy do innej zmiennej zeruje wskaźnik tablicy, powyższy przykład wszedłby w nieskończoną pętle, jeśli tablica $owoce zostałaby przypisana do innej zmiennej wewnątrz pętli.

Patrz także: key(), list(),
current(), reset(),
next(), prev() i
foreach.

current
end
Funkcje Tablic


Ustawia wewnętrzny wskaźnik tablicy na ostatnim elemencie

each
extract
Funkcje Tablic
PHP Manual

end

(PHP 4, PHP 5)

end — Ustawia wewnętrzny wskaźnik tablicy na ostatnim elemencie

Opis

mixed end ( array &$tablica )

end() przesuwa wewnętrzny wskaźnik tablicy tablica na ostatnim elemencie i zwraca jego wartość.

Przykład #1 Prosty przykład użycia funkcji end()

<?php
$owoce = array('jabłko', 'banan', 'malina');
print end($owoce); // malina
?>

Patrz także: current(),
each(),
next() i reset().

each
extract
Funkcje Tablic


Importuj zmienne do bieżącej tablicy symboli z tablicy

end
in_array
Funkcje Tablic
PHP Manual

extract

(PHP 4, PHP 5)

extract — Importuj zmienne do bieżącej tablicy symboli z tablicy

Opis

int extract ( array $tablica_zmiennych [, int $typ_ekstrakcji [, string $prefiks ]] )

Ta funkcja służy do importowania zmiennych z tablicy do bieżącej tablicy symboli. Pobiera jako parametr tablicę asocjacyjną tablica_zmiennych i traktuje klucze jako nazwy zmiennych a wartości jako wartości tych zmiennych. Dla każdej pary klucz/wartość w bieżącej tablicy symboli będzie stworzona zmienna, zależna od parametrów typ_ekstrakcji i prefiks.

Informacja:

Od wersji 4.0.5 ta funkcja zwraca liczbę wyekstrahowanych zmiennych.

Informacja:

Stałe EXTR_IF_EXISTS i EXTR_PREFIX_IF_EXISTS zostały dodane w PHP 4.2.0.

Informacja:

Stała EXTR_REFS została dodana w PHP 4.3.0.

extract() sprawdza każdy klucz aby sprawdzić, czy zawiera prawidłową nazwę zmiennej a także czy istnieją kolizje z zmiennymi istniejącymi w tablicy symboli. Sposób traktowania złych nazw zmiennych i kolizji jest określony przez parametr typ_ekstrakcji. Może być jedną z poniższych wartości:

EXTR_OVERWRITE
Jeśli istnieje kolizja, nadpisz istniejącą zmienną.
EXTR_SKIP
Jeśli istnieje kolizja, nie nadpisuj istniejącej zmiennej.
EXTR_PREFIX_SAME
Jeśli istnieje kolizja, na początek nazwy zmiennej wstaw prefiks.
EXTR_PREFIX_ALL
Na początek każdej nazwy zmiennej wstaw prefiks. Od PHP 4.0.5 dotyczy to także nazw numerycznych.
EXTR_PREFIX_INVALID
Wstaw prefiks na początek złych/numerycznych nazw. Ta flaga została dodana w PHP 4.0.5.
EXTR_IF_EXISTS
Nadpisz tylko zmienną już istniejącą w bieżącej tablicy symboli. Jest to przydatne do definiowania listy poprawnych zmiennych i ekstrahuj tylko te zmienne które zdefiniowano na przykład w $_REQUEST. Flaga ta została dodana w PHP 4.2.0.
EXTR_PREFIX_IF_EXISTS
Przedrostek zostanie dodany tylko do zmiennych których odpowiedniki bez przedrostka już istnieją w bieżącej tablicy symboli. Flaga ta została dodana w PHP 4.2.0.
EXTR_REFS
Ekstraktuje zmienne jako referencje. Oznacza to, że wartości zaimportowanych zmiennych ciągle odnoszą się do wartości parametru tablica_zmiennych. Flaga ta może być użyta sama lub w połączaniu z innymi flagami poprzez użycie operacji OR na parametrze typ_ekstrakcji. Została ona dodana w PHP 4.3.0.

Jeśli typ_ekstrakcji nie został podany, to zakładana jest opcja EXTR_OVERWRITE.

Zauważ, że parametr prefiks jest wymagany tylko jeśli typ_ekstrakcji to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID lub EXTR_PREFIX_IF_EXISTS. Jeśli nazwa zmiennej po dodaniu prefiksu nie jest prawidłową nazwą zmiennej, nie jest importowana do tablicy symboli. Prefiksy są automatycznie oddzielane od kluczy tablicy poprzez znak "_".

extract() zwraca liczbę zmiennych szczęśliwie zaimportowanych do tablicy symboli.

Ostrzeżenie

Nie należy używać funkcji extract() na niepewnych danych, jak na przykład danych odebranych od użytkownika ($_GET, ...). Można tak zrobić na przykład w celu tymczasowego uruchomienia starych skryptów, które zależne są od ustawienia register_globals. Należy jednak użyć nie nadpisującego parametru typ_ekstrakcji, jak na przykład EXTR_SKIP. Trzeba też pamiętać aby ekstrahować zmienne w kolejności określonej przez opcję variables_order pliku php.ini.

Możliwa jest ekstrakcja zmiennych zawartych w tablicy asocjacyjnej zwróconej przez wddx_deserialize().

Przykład #1 Przykład użycia extract()

<?php

/* Załóżmy, że $tablica_zmiennych jest tablicą zwróconą przez
   wddx_deserialize */

$rozmiar = "duży";
$tablica_zmiennych = array("kolor"    => "niebieski",
                           "rozmiar"  => "średni",
                           "ksztalt"  => "kulisty");
extract($tablica_zmiennych, EXTR_PREFIX_SAME, "wddx");

echo "$kolor, $rozmiar, $ksztalt, $wddx_rozmiar\n";

?>
niebieski, duży, kulisty, średni

$rozmiar nie został nadpisany, ponieważ podany został parametr EXTR_PREFIX_SAME, przez co stworzona został zmienna $wddx_rozmiar. Jeśli podana by była flaga EXTR_SKIP, to zmienna $wddx_rozmiar nie zostałaby stworzona. Flaga EXTR_OVERWRITE spowodowałaby, że zmienna $rozmiar miałaby wartość "średni", a EXTR_PREFIX_ALL spowodowałaby że wszystkie nowe zmienne zostałyby nazwane $wddx_kolor, $wddx_rozmiar, and $wddx_ksztalt.

Musisz użyć tablic asocjacyjnych. Tablica indeksowana liczbowo nie da żadnych efektów, chyba że zostanie użyta flaga EXTR_PREFIX_ALL lub EXTR_PREFIX_INVALID.

Patrz także: compact().

end
in_array
Funkcje Tablic


Sprawdza czy wartość istnieje w tablicy

extract
key
Funkcje Tablic
PHP Manual

in_array

(PHP 4, PHP 5)

in_array — Sprawdza czy wartość istnieje w tablicy

Opis

bool in_array ( mixed $igła , array $stóg_siana [, bool $ścisłe ] )

Przeszukuje stóg_siana w poszukiwaniu parametru igła i zwraca TRUE jeśli wartość została znaleziona lub FALSE w przeciwnym przypadku.

Jeśli trzeci parametr ścisły jest ustawiony na TRUE to in_array() porówna także typy parametru igła z tymi z parametru stóg_siana.

Informacja:

Jeśli igła jest ciągiem to porównywanie jest dokonywane z uwzględnieniem wielkości znaków.

Informacja:

W wersjach PHP starszych niż 4.2.0 igła nie mogła być tablicą.

Przykład #1 Przykład użycia in_array()

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Znaleziono Irix";
}
if (in_array("mac", $os)) {
    echo "Znaleziono mac";
}

Drugi warunek nie zostaje spełniony ponieważ funkcja in_array() uwzględnia wielkość znaków, tak więc powyższy przykład wyświetli:

Znaleziono Irix

Przykład #2 Przykład użycia in_array() z parametrem strict

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' znalezione ze ścisłym sprawdzaniem\n";
}

if (in_array(1.13, $a, true)) {
    echo "1.13 znalezione ze ścisłym sprawdzaniem\n";
}
?>

Powyższy przykład wyświetli:

1.13 znalezione ze ścisłym sprawdzaniem

Przykład #3 in_array() z tablicą jako igła

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array ('p', 'h'), $a)) {
    echo "znaleziono 'ph'\n";
}

if (in_array(array ('f', 'i'), $a)) {
    echo "znaleziono 'fi'\n";
}

if (in_array('o', $a)) {
    echo "znaleziono 'o'\n";
}
?>

Powyższy przykład wyświetli:

znaleziono 'ph'
znaleziono 'o'

Patrz także: array_search(), array_key_exists() i isset().

extract
key
Funkcje Tablic


Pobiera klucz z tablicy asocjacyjnej

in_array
krsort
Funkcje Tablic
PHP Manual

key

(PHP 4, PHP 5)

key — Pobiera klucz z tablicy asocjacyjnej

Opis

mixed key ( array &$tablica )

key() zwraza klucz bieżącego elementu z tablicy asocjacyjnej.

Przykład #1 Przykład użycia funkcji key()

<?php
$tablica = array(
    'owoc1' => 'jabłko',
    'owoc2' => 'pomarańcza',
    'owoc3' => 'winogrono',
    'owoc4' => 'jabłko',
    'owoc5' => 'jabłko');

// poniższa pętla wyświetla wszystkie klucze w tablicy asocjacyjnej, gdzie
// wartość jest równa "jabłko"
while ($nazwa_owocu = current($tablica)) {
    if ($nazwa_owocu == 'jabłko') {
        echo key($tablica).'<br />';
    }
    next($tablica);
}
?>

Patrz także: current() i next().

in_array
krsort
Funkcje Tablic


Sortuj tablicę według kluczy w porządku odwrotnym

key
ksort
Funkcje Tablic
PHP Manual

krsort

(PHP 4, PHP 5)

krsort — Sortuj tablicę według kluczy w porządku odwrotnym

Opis

bool krsort ( array &$tablica [, int $flagi ] )

Sortuje trablicę według klucza w porządku odwrotnym utrzymując skojarzenia kluczy z danymi. Jest to przydatne głównie w przypadku tablic asocjacyjnych.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia krsort()

<?php
$owoce = array("d"=>"cytryna", "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");
krsort($owoce);
foreach ($owoce as $key => $val) {
    echo "$key = $val\n";
}
?>

Powyższy przykład wyświetli:

d = cytryna
c = jabłko
b = banan
a = pomarańcza

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także: asort(), arsort(),
ksort() sort(),
natsort() i rsort().

key
ksort
Funkcje Tablic


Sortuj tablicę według klucza

krsort
list
Funkcje Tablic
PHP Manual

ksort

(PHP 4, PHP 5)

ksort — Sortuj tablicę według klucza

Opis

bool ksort ( array &$tablica [, int $flagi ] )

Sortuje tablicę według klucza zachowując skojarzenia kluczy z danymi. Jest to przydatne głównie w przypadku tablic asocjacyjnych.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia ksort()

<?php
$owoce = array("d"=>"cytryna", "a"=>"pomarańcza", "b"=>"banan", "c"=>"jabłko");
ksort($owoce);
foreach ($owoce as $key => $val) {
    echo "$key = $val\n";
}
?>

Powyższy przykład wyświetli:

a = pomarańcza
b = banan
c = jabłko
d = cytryna

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także: asort(), arsort(),
krsort(), uksort(),
sort(), natsort() i
rsort().

Informacja:

Drugi parametr został dodany w PHP 4.

krsort
list
Funkcje Tablic


Przypisz zmienne tak jakby były tablicą

ksort
natcasesort
Funkcje Tablic
PHP Manual

list

(PHP 4, PHP 5)

list — Przypisz zmienne tak jakby były tablicą

Opis

void list ( mixed $zmienna , mixed $... )

Podobnie jak array(), nie jest na prawdę funkcją, ale elementem składni języka. Instrukcja list() jest używana do przypisywania listy zmiennych w jednej operacji.

Informacja:

list() działa tylko z tablicami o indeksach liczbowych zakładając że indeksy zaczynają się od 0.

Przykład #1 Przykłady użycia list()

<?php

$info = array('kawa', 'brązowa', 'kofeina');

// Listowanie wszystkich zmiennych
list($napój, $kolor, $składnik) = $info;
echo "$napój jest $kolor a $składnik czyni ją wyjątkową.\n";

// Listowanie niektórych elementów
list($napój, , $składnik) = $info;
echo "$napój zawiera $składnik.\n";

// Albo przeskoczmy od razu do trzeciego
list( , , $składnik) = $info;
echo "Potrzebna jest mi $składnik!\n";

// list() nie działa z łańcuchami znaków
list($bar) = "abcde";
var_dump($bar); // NULL

?>

Przykład #2 Przykład użycia list()

<table>
 <tr>
  <th>Nazwisko pracownika</th>
  <th>Pensja</th>
 </tr>

<?php

$wynik = mysql_query("SELECT id, nazwisko, pensja FROM pracownicy", $conn);
while (list($id, $nazwisko, $pensja) = mysql_fetch_row($wynik)) {
   echo " <tr>\n" .
        "  <td><a href=\"info.php?id=$id\">$nazwisko</a></td>\n" .
        "  <td>$pensja</td>\n" .
        " </tr>\n";
}
?>

</table>

Ostrzeżenie

list() Przypisuje wartości zaczynając parametru znajdującego się po prawej. Przy używaniu zwykłych zmiennych nie ma się o co martwić. Ale używając tablic z indeksami, zazwyczaj oczekuje się, że kolejność indeksów w tablicy będzie taka sama jak zapis wywołania list(), od lewej do prawej. Otóż tak nie jest. Zmienne są przypisywane w odwrotnej kolejności.

Przykład #3 Przykład użycia list() z indeksowaną tablicą

<?php

$info = array('kawa', 'brązowa', 'kofeina');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Przykład ten wyświetli co następuje (zauważ kolejność elementów porównując ją do tej, w której były one zapisane w wywołaniu funkcji list()):

array(3) {
[2]=>
string(8) "kofeina"
[1]=>
string(5) "brązowa"
[0]=>
string(6) "kawa"
}

Patrz także: each() array() i extract().

ksort
natcasesort
Funkcje Tablic


Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków

list
natsort
Funkcje Tablic
PHP Manual

natcasesort

(PHP 4, PHP 5)

natcasesort — Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków

Opis

bool natcasesort ( array &$tablica )

Ta funkcja implementuje algorytm sortowania który porządkuje stringi alfanumeryczne tak, jak zrobiłby to człowiek, zachowując przypisanie kluczy do wartości. Jest on określany jako "porządkowanie naturalne".

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

natcasesort() jest wersją funkcji natsort() ignorującą wielkość znaków. Zobacz natsort() aby zobaczyć różnicę między tym algorytmem a zwykłymi komputerowymi algorytmami sortowania stringów.

Przykład #1 natcasesort() example

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standardowe sortowanie\n";
print_r($array1);

natcasesort($array2);
echo "\nPorządkowanie naturalne (ignorowana wielkośc znaków)\n";
print_r($array2);
?>

Powyższy przykład wyświetli:

Standarowe sortowanie
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Porządkowanie naturalne (ignorowana wielkośc znaków)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

Aby uzyskać więcej informacji zobacz stronę Martina Poola » Natural Order String Comparison.

Patrz także: sort(),
natsort(),
strnatcmp() i
strnatcasecmp().

list
natsort
Funkcje Tablic


Sortuj tablicę używając algortmu "porządek naturalny"

natcasesort
next
Funkcje Tablic
PHP Manual

natsort

(PHP 4, PHP 5)

natsort — Sortuj tablicę używając algortmu "porządek naturalny"

Opis

bool natsort ( array &$tablica )

Funkcja ta implementuje algorytm sortowania, który sortuje stringi alfanumeryczne tak, jak posortowałby je człowiek, zachowując przypisania klucz-wartość. Jest on określany jako "porządkowanie naturalne". Przykład różnicy między tym algorytmem a zwykłymi komputerowymi algorytmami sortowania stringów (używanymi w funkcji sort()) można zobaczyć poniżej:

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia natsort()

<?php
$tablica1 = $tablica2 = array("img12.png", "img10.png", "img2.png", "img1.png");

sort($tablica1);
echo "Standardowe sortowanie\n";
print_r($tablica1);

natsort($tablica2);
echo "\nSortowanie w porządku naturalnym\n";
print_r($tablica2);
?>

Powyższy przykład wyświetli:

Standardowe sortowanie
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Sortowanie w porządku naturalnym
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Aby uzyskać więcej informacji zobacz stronę Martina Poola » Natural Order String Comparison.

Patrz także: natcasesort(),
strnatcmp() i
strnatcasecmp().

natcasesort
next
Funkcje Tablic


Przesuń do przodu wewnętrzny wskaźnik tablicy

natsort
pos
Funkcje Tablic
PHP Manual

next

(PHP 4, PHP 5)

next — Przesuń do przodu wewnętrzny wskaźnik tablicy

Opis

mixed next ( array &$tablica )

Przesuwa wewnętrzny wskaźnik tablicy i jedną pozycję do przodu i zwraca element tablicy aktualnie wskazywany przez wskaźnik, lub FALSE jeśli nie ma już więcej elementów.

next() zachowuje się jak current(), ale z jedną różnicą. Przesuwa wewnętrzny wskaźnik tablicy o jeden element do przodu przed zwróceniem wartości elementu. Oznacza to, że zwraca następny element tablicy i przesuwa wewnętrzny wskaźnik tablicy o jeden element do przodu. Jeśli przesunięcie wewnętrznego wskaźnika tablicy powoduje przesunięcie poza koniec listy elementów, next() zwraca FALSE.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Informacja: Nie będziesz mógł odróznić końca tablicy od elementu FALSE typu bool'owskiego. Aby poprawnie przejść przez tablicę, która może zawierać elementy FALSE, zobacz funkcję each().

Przykład #1 Przykład użycia funkcji next() i podobnych

<?php
$transport = array('stopa', 'rower', 'samochód', 'samolot');
$tryb = current($transport); // $tryb = 'stopa';
$tryb = next($transport);    // $tryb = 'rower';
$tryb = next($transport);    // $tryb = 'samochód';
$tryb = prev($transport);    // $tryb = 'rower';
$tryb = end($transport);     // $tryb = 'samolot';
?>

Patrz także: current(), end(),
prev(), reset()
i each().

natsort
pos
Funkcje Tablic


Alias dla current

next
prev
Funkcje Tablic
PHP Manual

pos

(PHP 4, PHP 5)

pos — Alias dla current()

Opis

Ta funkcja jest aliasem dla: current()

next
prev
Funkcje Tablic


Cofnij wewnętrzny wskaźnik tablicy

pos
range
Funkcje Tablic
PHP Manual

prev

(PHP 4, PHP 5)

prev — Cofnij wewnętrzny wskaźnik tablicy

Opis

mixed prev ( array &$tablica )

Zwraca wartość z tablicy z miejsca poprzedniego od tego na które wskazywał wewnętrzny wskaźnik pliku, lub FALSE jeśli nie ma już więcej elementów.

Ostrzeżenie

Ta funkcja może zwrócić Boolean FALSE, ale może też zwrócić wartość innego typu niż Boolean, która oznacza wartość FALSE, takie jak 0 lub "". Aby uzyskać więcej informacji proszę zapoznać się z rozdziałem Typy logiczne. Można używać operatora === do testowania zwracanych wartości przez tę funkcję.

Informacja: Nie będziesz mógł odróznić początku tablicy od elementu FALSE typu bool'owskiego. Aby poprawnie przejść przez tablicę, która może zawierać elementy FALSE, zobacz funkcję each().

prev() zachowuje się tak jak next(), z tym że cofa wewnętrzny wskaźnik tablicy o jeden element do tyłu, zamiast przesuwać go do przodu.

Przykład #1 Przykład użycia funkcji prev() i podobnych

<?php
$transport = array('stopa', 'rower', 'samochód', 'samolot');
$tryb = current($transport); // $tryb = 'stopa';
$tryb = next($transport);    // $tryb = 'rower';
$tryb = next($transport);    // $tryb = 'samochód';
$tryb = prev($transport);    // $tryb = 'rower';
$tryb = end($transport);     // $tryb = 'samolot';
?>

Patrz także: current(), end(),
next(), reset()
i each().

pos
range
Funkcje Tablic


Stwórz tablicę zawierającą przedział elementów

prev
reset
Funkcje Tablic
PHP Manual

range

(PHP 4, PHP 5)

range — Stwórz tablicę zawierającą przedział elementów

Opis

array range ( mixed $dolny , mixed $górny [, number $krok ] )

range() zwraca tablicę elementów od dolny do górny, włącznie. Jeśli dolny > górny, to sekwencja będzie od górnego do dolnego.

Informacja: Nowy parametr
Parametr opcjonalny krok został dodany w PHP 5.0.0.

Jeśli podany zostanie parametr krok, zostanie on użyty jako różnica pomiędzy elementami w sekwencji. krok powinien być liczbą dodatnią. Jeśli nie zostanie on podany, krok przyjmie domyślną wartość 1.

Przykład #1 Przykłady użycia funkcji range()

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $liczba) {
    echo $liczba;
}

// Parametr kroku został wprowadzony w 5.0.0
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $liczba) {
    echo $liczba;
}

// Użycie sekwencji znakowych wprowadzono w 4.1.0
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $litera) {
    echo $litera;
}

// array('c', 'b', 'a');
foreach (range('c', 'a') as $litera) {
    echo $litera;
}
?>

Informacja:

W wersjach wcześniejszych od PHP 4.1.0 funkcja range() generowała tylko rosnące tablice liczbowe. Obsługa sekwencji znakowych i tablic malejących została wprowadzona w PHP 4.1.0. Wartości sekwencji znakowych są ograniczone do długości jednego znaku. Jeśli wprowadzony zostanie ciąg długości większej niż jeden, użyty zostanie tylko pierwszy znak.

Uwaga

W wersjach PHP od 4.1.0 do 4.3.2 funkcja range() rozpoznawała ciągi numeryczne jako ciągi, a nie jako liczby. W związku z tym będą one użyte do generowania sekwencji znakowych. Na przykład "4242" będzie traktowane jako "4".

Patrz także: shuffle(), array_fill() i foreach.

prev
reset
Funkcje Tablic


Ustaw wewnętrzny wskaźnik tablicy na jej pierwszy element

range
rsort
Funkcje Tablic
PHP Manual

reset

(PHP 4, PHP 5)

reset — Ustaw wewnętrzny wskaźnik tablicy na jej pierwszy element

Opis

mixed reset ( array &$tablica )

reset() przewija wewnętrzny wskaźnik tablicy parametru tablica na jego pierwszy element i zwraca jego wartość, lub FALSE jeśli tablica jest pusta.

Przykład #1 Przykład użycia funkcji reset()

<?php

$tablica = array('krok pierwszy', 'krok drugi', 'krok trzeci', 'krok czwarty');

// domyślnie, wskażnik jest na pierwszym elemencie
echo current($tablica) . "<br />\n"; // "krok pierwszy"

// przeskocz dwa kroki
next($tablica);
next($tablica);
echo current($tablica) . "<br />\n"; // "krok trzeci"

// zresetuj wskaźnik, zacznik od nowa na pierwszym kroku
reset($tablica);
echo current($tablica) . "<br />\n"; // "krok pierwszy"

?>

Patrz także: current(),
each(), end()
next() i prev().

range
rsort
Funkcje Tablic


Sortuj tablicę w porządku odwrotnym

reset
shuffle
Funkcje Tablic
PHP Manual

rsort

(PHP 4, PHP 5)

rsort — Sortuj tablicę w porządku odwrotnym

Opis

void rsort ( array &$tablica [, int $flagi ] )

Ta funkcja sortuje tablicę w porządku odwrotnym (od największego do najmniejszego).

Informacja: Ta funkcja przypisuje nowe klucze dla elementów argumentu tablica. Wszystkie istniejące klucze zostaną usunięte.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia rsort()

<?php
$owoce = array("cytryna", "pomarańcza", "banan", "jabłko");
rsort($owoce);
foreach ($owoce as $key => $val) {
    echo "$key = $val\n";
}
?>

Powyższy przykład wyświetli:

0 = pomarańcza
1 = jabłko
2 = cytryna
3 = banan

Owoce zostały posortowane w odwrotnym porządku alfabetycznym.

Możesz zmodyfikować zachowanie sortowania przez użycie opcjonalnego parametru flagi. Aby uzyskać szczegóły zobacz sort().

Patrz także: arsort(),
asort(), ksort(),
krsort(), sort() i
usort().

reset
shuffle
Funkcje Tablic


Przetasuj tablicę

rsort
sizeof
Funkcje Tablic
PHP Manual

shuffle

(PHP 4, PHP 5)

shuffle — Przetasuj tablicę

Opis

bool shuffle ( array &$tablica )

Ta funkcja tasuje tablicę (losuje kolejność elementów w niej).

Informacja: Ta funkcja przypisuje nowe klucze dla elementów argumentu tablica. Wszystkie istniejące klucze zostaną usunięte.

Przykład #1 Przykład użycia shuffle()

<?php
$liczby = range(1,20);
srand((float)microtime()*1000000);
shuffle($liczby);
foreach ($numbers as $number) {
while (list(, $liczba) = each($liczby)) {
    echo "$liczba ";
}
?>

Informacja: Od PHP 4.2.0 nie ma potrzeby inicjalizować generatora liczb losowych funkcją srand() lub mt_srand(), ponieważ dzieje się to automatycznie.

Patrz także: arsort(), asort(),
ksort(), rsort(),
sort() i usort().

rsort
sizeof
Funkcje Tablic


Alias dla count

shuffle
sort
Funkcje Tablic
PHP Manual

sizeof

(PHP 4, PHP 5)

sizeof — Alias dla count()

Opis

Ta funkcja jest aliasem dla: count().

shuffle
sort
Funkcje Tablic


Sortuje tablicę

sizeof
uasort
Funkcje Tablic
PHP Manual

sort

(PHP 4, PHP 5)

sort — Sortuje tablicę

Opis

bool sort ( array &$tablica [, int $flagi ] )

Funkcja ta sortuje tablicę. Po zakończeniu działania funkcji elementy będą ułożone od najmniejszego do najwiekszego.

Informacja: Ta funkcja przypisuje nowe klucze dla elementów argumentu tablica. Wszystkie istniejące klucze zostaną usunięte.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia sort()

<?php

$owoce = array("cytryna", "pomarańcza", "banan", "jabłko");
sort($owoce);
foreach ($owoce as $key => $val) {
    echo "owoce[" . $key . "] = " . $val . "\n";
}
?>

Powyższy przykład wyświetli:

owoce[0] = banan
owoce[1] = cytryna
owoce[2] = jabłko
owoce[3] = pomarańcza

Owoce zostały posortowane w porządku alfabetycznym.

Opcjonalny drugi parametr flagi może być użyty do zmiany zachowania sortowania przy pomocy tych wartości:

Flagi typu sortowania:

  • SORT_REGULAR - porównuj elementy normalnie (nie zmienia typów)
  • SORT_NUMERIC - porównuj elementy jako liczby
  • SORT_STRING - porównuj elementy jako ciągi tekstowe
  • SORT_LOCALE_STRING - porównuj elementy jako ciągi tekstowe, uwzględniając ustawienia Locale. Dodane w PHP 4.4.0 i PHP 5.0.2. W wersjach wcześniejszych niż PHP 6, używane jest locale systemowe, które może być zmienione poprzez zastosowanie funkcji setlocale(). Od PHP w wersji 6 niezbędne jest użycie funkcji i18n_loc_set_default().

Informacja:

Drugi parametr został dodany w PHP 4.

Ostrzeżenie

Należy zachować ostrożność przy sortowaniu funkcją sort() tablic o różnych typach elementów, ponieważ może to doprowadzić do nieprzewidzianych wyników.

Patrz także: arsort(),
asort(), ksort(),
krsort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort() i
uksort().

sizeof
uasort
Funkcje Tablic


Sortuj tablicę korzystając ze zdefiniowanej przez użytkownika funkcji porównującej i zachowując skojarzenia kluczy

sort
uksort
Funkcje Tablic
PHP Manual

uasort

(PHP 4, PHP 5)

uasort — Sortuj tablicę korzystając ze zdefiniowanej przez użytkownika funkcji porównującej i zachowując skojarzenia kluczy

Opis

void uasort ( array &$tablica , callback $funkcja )

Funkcja ta sortuje tablicę w taki sposób, że klucze zachowują przypisanie do odpowiednich wartości. Jest to używane głównie przy sortowaniu tablic asocjacyjnych, gdzie znacząca jest kolejność elementów. Funkcja porównująca jest zdefiniowana przez użytkownika.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Informacja:

Zobacz usort() i uksort() aby zobaczyć przykłady zdefiniowanych przez użytkownika funkcji porównujących.

Patrz także: usort(), uksort(),
sort(), asort(),
arsort(), ksort() i
rsort().

sort
uksort
Funkcje Tablic


Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez użytkownika funkcji porównującej

uasort
usort
Funkcje Tablic
PHP Manual

uksort

(PHP 4, PHP 5)

uksort — Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez użytkownika funkcji porównującej

Opis

bool uksort ( array &$tablica , callback $funkcja_porównująca )

uksort() sortuje tablicę według kluczy korzystając z podanej przez użytkownika funkcji porównującej. Jeśli chcesz posortować tablicę według skomplikowanych kryteriów, to powinieneś użyć tej funkcji.

Funkcja funkcja_porównująca powinna przyjmować dwa parametry, którymi będą pary kluczy tablicy podanej jako pierwszy parametr funkcji uksort(). Funkcja porównująca musi zwracać liczbę całkowitą, mniejszą, równą lub większą od zera jeśli pierwszy parametr jest odpowiednio mniejszy, równy lub większy niż drugi.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia uksort()

<?php
function cmp($a, $b)
{
    $a = ereg_replace('^(a|an|the) ', '', $a);
    $b = ereg_replace('^(a|an|the) ', '', $b);
    return strcasecmp($a, $b);
}

$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);

uksort($a, "cmp");

foreach ($a as $key => $val) {
    echo "$key: $value\n";
}
?>

Powyższy przykład wyświetli:

an apple: 3
a banana: 4
the Earth: 2
John: 1

Patrz także: usort(), uasort(),
sort(), asort(),
arsort(), ksort(),
natsort() i rsort().

uasort
usort
Funkcje Tablic


Sortuje tablicę według wartości korzystając ze zdefiniowanej przez użytkownika funkcji porównującej

uksort
Klasy/Obiekty
Funkcje Tablic
PHP Manual

usort

(PHP 4, PHP 5)

usort — Sortuje tablicę według wartości korzystając ze zdefiniowanej przez użytkownika funkcji porównującej

Opis

void usort ( array &$tablica , callback $funkcja_porównująca )

Funkcja ta posortuje tablicę według jej wartości korzystając z podanej przez użytkownika funkcji porównującej. Jeśli chcesz posortować tablicę według skomplikowanych kryteriów, to powinieneś użyć tej funkcji.

Funkcja porównująca musi zwracać liczbę całkowitą mniejszą, równą lub większą od zera jeśli pierwszy argument jest odpowiednio mniejszy, równy lub większy niż drugi.

Informacja:

Jeśli wynikiem porównania dwóch elementów tablicy jest równość, ich kolejność w posortowanej tablicy pozostaje niezdefiniowana. Od PHP 4.0.6 funkcje zdefiniowane przez użytkownika mogły utrzymywać początkową kolejność tych elementów, lecz nowy algorytm sortowania wprowadzony w PHP 4.1.0 czyni to uniemożliwym i nie ma wydajnego sposobu na rozwiązanie tego problemu.

Informacja: Ta funkcja przypisuje nowe klucze dla elementów argumentu tablica. Wszystkie istniejące klucze zostaną usunięte.

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykład #1 Przykład użycia usort()

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $val) {
    echo "$key: $value\n";
}
?>

Powyższy przykład wyświetli:

0: 6
1: 5
2: 3
3: 2
4: 1

Informacja:

Oczywiście w tym prostym przykładzie lepiej jest skorzystać z funkcji sort().

Przykład #2 Przykład użycia usort() do sortowania wielowymiarowych tablic

<?php
function cmp($a, $b)
{
    return strcmp($a["owoc"], $b["owoc"]);
}

$owoce[0]["owoc"] = "cytryny";
$owoce[1]["owoc"] = "jabłka";
$owoce[2]["owoc"] = "winogrona";

usort($owoce, "cmp");

while (list($key, $value) = each($owoce)) {
    echo "\$owoce[$key]: " . $value["owoc"] . "\n";
}

Sortując tablicę wielowymiarową, $a i $b zawierają referencję do pierwszego indeksu tablicy.

Powyższy przykład wyświetli:

$owoce[0]: cytryny
$owoce[1]: jabłka
$owoce[2]: winogrona

Przykład #3 Przykład użycia usort() używając funkcji składowej obiektu

<?php
class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* Statyczna funkcja porównująca */
    function cmp_obj($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

uasort($a, array("TestObj", "cmp_obj"));

foreach ($a as $item) {
    print $item->name . "\n";
}

Powyższy przykład wyświetli:

b
c
d

Patrz także: uasort(),
uksort(), sort(),
asort(),
arsort(),ksort(),
natsort() i rsort().

uksort
Klasy/Obiekty
Funkcje Tablic


Informacje o klasach i obiektach

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Funkcje Klasy/Obiekty
    • __autoload — Attempt to load undefined class
    • call_user_method_array — Wywołuje metodę użytkownika zadaną z tablicą parametrów [przestarzałe]
    • call_user_method — Wywołuje metodę użytkownika na zadanym obiekcie [przestarzałe]
    • class_alias — Creates an alias for a class
    • class_exists — Sprawdza, czy klasa została zdefiniowana
    • get_called_class — the "Late Static Binding" class name
    • get_class_methods — Zwraca tablicę nazw metod danej klasy
    • get_class_vars — Zwraca tablicę domyślnych właściwości klasy
    • get_class — Zwraca nazwę klasy zadanego obiektu
    • get_declared_classes — Zwraca tablicę z nazwami zdefiniowanych klas
    • get_declared_interfaces — Returns an array of all declared interfaces
    • get_declared_traits — Returns an array of all declared traits
    • get_object_vars — Zwraca tablicę asocjacyjną właściwości obiektu
    • get_parent_class — Pobiera nazwę klasy przodka dla obiektu lub klasy
    • interface_exists — Checks if the interface has been defined
    • is_a — Zwraca TRUE jeżeli obiekt jest tej klasy, lub ta klasa jest jednym z jego przodków
    • is_subclass_of — Zwraca TRUE jeżeli klasa jest jednym z przodków obiektu
    • method_exists — Sprawdza czy metoda klasy istnieje
    • property_exists — Checks if the object or class has a property
    • trait_exists — Checks if the trait exists
usort
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

Te funkcje pozwalają uzyskać informacje o klasach i ich egzemplarzach, obiektach. Możesz uzyskać informację o nazwie klasy do jakiej należy obiekt, a także jej właściwości i metody. Używając tych funkcji możesz dowiedzieć się nie tylko do jakiej klasy należy obiekt, ale także ustalić jego przodków (np. jaką klasę rozszerza klasa tego obiektu).

Klasy/Obiekty
Instalacja/Konfiguracja
Klasy/Obiekty


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Klasy/Obiekty


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
Klasy/Obiekty


Przykłady

W tym przykładzie najpierw zdefiniujemy bazową klasę i jej rozszerzenie. Klasa bazowa opisuje normalne warzywo, czy jest jadalne czy nie oraz jego kolor. Podklasa Szpinak dodaje metodę pozwalającą go ugotować, i drugą, która pozwala dowiedzieć się, czy jest ugotowany.

Przykład #1 classes.inc

<?php

// klasa bazowa wraz z jej właściwościami i metodami
class Warzywo {

    var $jadalne;
    var $kolor;

    function Warzywo($jadalne, $kolor="zielony") {
        $this->jadalne = $jadalne;
        $this->kolor = $kolor;
    }

    function czy_jadalne() {
        return $this->jadalne;
    }

    function jaki_kolor() {
        return $this->kolor;
    }

} // koniec klasy Warzywo

// rozrzesza klasę bazową
class Szpinak extends Warzywo {

    var $ugotowane = false;

    function Szpinak() {
        $this->Warzywo(true, "zielone");
    }

    function ugotuj() {
        $this->ugotowane = true;
    }

    function czy_ugotowane() {
        return $this->ugotowane;
    }

} // koniec klasy Szpinak

?>

Teraz możemy stworzyć dwa egzemplarze tych klas i wydrukować informacje o nich, włączając w to informacje o przodkach. Zdefiniujemy także kilka użytecznych funkcji, głównie po to, by uzyskać ładny wydruk zmiennych.

Przykład #2 test_script.php

<pre>
<?php

include "classes.inc";

// funkcje użytkowe

function drukuj_wlasciwosci($obj) {
    foreach (get_object_vars($obj) as $wlasc => $wart) {
        echo "\t$wlasc = $wart\n";
    }
}

function drukuj_metody($obj) {
    $tab = get_class_methods(get_class($obj));
    foreach ($tab as $metoda) {
        echo "\tfunkcja $metoda()\n";
    }
}

function przodkowie_klasy($obj, $klasa) {
    global $$obj;
    if (is_subclass_of($GLOBALS[$obj], $klasa)) {
        echo "Obiekt $obj należy do klasy ".get_class($$obj);
        echo ", podklasy $klasa\n";
    } else {
        echo "Obiekt $obj nie należy do podklasy $klass\n";
    }
}

// tworzymy 2 egzemplarze obiektów

$warzywko = new Warzywo(true, "niebieski");
$lisciaste = new Szpinak();

// wydrukujemy informację o obiektach
echo "warzywko: KLASA ".get_class($warzywko)."\n";
echo "lisciaste: KLASA ".get_class($lisciaste);
echo ", PRZODEK ".get_parent_class($lisciaste)."\n";

// pokażmy właściwości warzywka
echo "\nwarzywko: Właściwości\n";
drukuj_wlasciwosci($warzywko);

// i metody liściastego
echo "\nlisciaste: Metody\n";
drukuj_metody($lisciaste);

echo "\nPrzodkowie:\n";
przodkowie_klasy("lisciaste", "Szpinak");
przodkowie_klasy("lisciaste", "Warzywo");
?>
</pre>

Wartą odnotowania rzeczą w powyższym przykładzie jest to, że obiekt $lisciaste jest egzemplarzem klasy Szpinak która to jest podklasą klasy Warzywo, i tak ostatnia część powyższego skryptu pokaże na wyjściu:

       [...]
Przodkowie:
Obiekt lisciasty nie należy do podklasy Szpinak
Obiekt lisciasty należy do klasy Szpinak, podklasy Warzywo

Stałe predefiniowane
Funkcje Klasy/Obiekty
Klasy/Obiekty


Funkcje Klasy/Obiekty

Spis treści

  • __autoload — Attempt to load undefined class
  • call_user_method_array — Wywołuje metodę użytkownika zadaną z tablicą parametrów [przestarzałe]
  • call_user_method — Wywołuje metodę użytkownika na zadanym obiekcie [przestarzałe]
  • class_alias — Creates an alias for a class
  • class_exists — Sprawdza, czy klasa została zdefiniowana
  • get_called_class — the "Late Static Binding" class name
  • get_class_methods — Zwraca tablicę nazw metod danej klasy
  • get_class_vars — Zwraca tablicę domyślnych właściwości klasy
  • get_class — Zwraca nazwę klasy zadanego obiektu
  • get_declared_classes — Zwraca tablicę z nazwami zdefiniowanych klas
  • get_declared_interfaces — Returns an array of all declared interfaces
  • get_declared_traits — Returns an array of all declared traits
  • get_object_vars — Zwraca tablicę asocjacyjną właściwości obiektu
  • get_parent_class — Pobiera nazwę klasy przodka dla obiektu lub klasy
  • interface_exists — Checks if the interface has been defined
  • is_a — Zwraca TRUE jeżeli obiekt jest tej klasy, lub ta klasa jest jednym z jego przodków
  • is_subclass_of — Zwraca TRUE jeżeli klasa jest jednym z przodków obiektu
  • method_exists — Sprawdza czy metoda klasy istnieje
  • property_exists — Checks if the object or class has a property
  • trait_exists — Checks if the trait exists
Przykłady
__autoload
Klasy/Obiekty


Attempt to load undefined class

Funkcje Klasy/Obiekty
call_user_method_array
Funkcje Klasy/Obiekty
PHP Manual

__autoload

(No version information available, might only be in SVN)

__autoload — Attempt to load undefined class

Opis

void __autoload ( string $class )

You can define this function to enable classes autoloading.

Parametry

class

Name of the class to load

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • spl_autoload_register() - Register given function as __autoload() implementation

Funkcje Klasy/Obiekty
call_user_method_array
Funkcje Klasy/Obiekty


Wywołuje metodę użytkownika zadaną z tablicą parametrów [przestarzałe]

__autoload
call_user_method
Funkcje Klasy/Obiekty
PHP Manual

call_user_method_array

(PHP 4 >= 4.0.5, PHP 5)

call_user_method_array — Wywołuje metodę użytkownika zadaną z tablicą parametrów [przestarzałe]

Opis

mixed call_user_method_array ( string $nazwa_metody , object &$obiekt , array $parametry )
Ostrzeżenie

Funkcja ccall_user_method_array() jest od PHP 4.1.0 przestarzała.

Parametry

nazwa_metody

Nazwa wywoływanej metody.

obiekt

obiekt, w którym wywoływana jest nazwa_metody.

parametry

Tablica zawierająca parametry.

Przykłady

Przykład #1 Alternatywa dla call_user_method_array()

<?php
call_user_func_array(array($obiekt, $nazwa_metody), $parametry);
call_user_func_array(array(&$obiekt, $nazwa_metody), $parametry); // PHP 4
?>

Zobacz też:

  • call_user_func_array() - Call a callback with an array of parameters
  • call_user_func() - Call the callback given by the first parameter

__autoload
call_user_method
Funkcje Klasy/Obiekty


Wywołuje metodę użytkownika na zadanym obiekcie [przestarzałe]

call_user_method_array
class_alias
Funkcje Klasy/Obiekty
PHP Manual

call_user_method

(PHP 4, PHP 5)

call_user_method — Wywołuje metodę użytkownika na zadanym obiekcie [przestarzałe]

Opis

mixed call_user_method ( string $nazwa_metody , object &$obiekt [, mixed $parametr [, mixed $... ]] )
Ostrzeżenie

Funkcja call_user_method() jest od PHP 4.1.0 przestarzała.

Parametry

nazwa_metody

Nazwa wywoływanej metody.

obiekt

obiekt, w którym wywoływana jest nazwa_metody.

parametr ...

Opcjonalne parametry.

Przykłady

Przykład #1 Alternatywa dla call_user_method()

<?php
call_user_func(array($obiekt, $nazwa_metody), $parametr /* , ... */);
call_user_func(array(&$obiekt, $nazwa_metody), $parametr /* , ... */); // PHP 4
?>

Zobacz też:

  • call_user_func_array() - Call a callback with an array of parameters
  • call_user_func() - Call the callback given by the first parameter

call_user_method_array
class_alias
Funkcje Klasy/Obiekty


Creates an alias for a class

call_user_method
class_exists
Funkcje Klasy/Obiekty
PHP Manual

class_alias

(PHP 5 >= 5.3.0)

class_alias — Creates an alias for a class

Opis

bool class_alias ([ string $original [, string $alias ]] )

Creates an alias named alias based on the defined class original. The aliased class is exactly the same as the original class.

Parametry

original

The original class.

alias

The alias name for the class.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 class_alias() example

<?php

class foo { }

class_alias('foo', 'bar');

$a = new foo;
$b = new bar;

// the objects are the same
var_dump($a == $b, $a === $b);
var_dump($a instanceof $b);

// the classes are the same
var_dump($a instanceof foo);
var_dump($a instanceof bar);

var_dump($b instanceof foo);
var_dump($b instanceof bar);

?>

Powyższy przykład wyświetli:

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Zobacz też:

  • get_parent_class() - Pobiera nazwę klasy przodka dla obiektu lub klasy
  • is_subclass_of() - Zwraca TRUE jeżeli klasa jest jednym z przodków obiektu

call_user_method
class_exists
Funkcje Klasy/Obiekty


Sprawdza, czy klasa została zdefiniowana

class_alias
get_called_class
Funkcje Klasy/Obiekty
PHP Manual

class_exists

(PHP 4, PHP 5)

class_exists — Sprawdza, czy klasa została zdefiniowana

Opis

bool class_exists ( string $nazwa_klasy [, bool $autoload = true ] )

Funkcja sprawdza, czy podana klasa została zdefiniowana.

Parametry

nazwa_klasy

Nazwa klasy. Wielkość liter w nazwie klasy nie ma znaczenia.

autoload

Czy wywołać domyślnie __autoload.

Zwracane wartości

Zwraca TRUE jeśli nazwa_klasy jest klasą, w przeciwnym przypadku zwraca FALSE.

Rejestr zmian

Wersja | Opis
5.0.2 | Nie zwraca już TRUE dla zdefiniowanych interfejsów. W przypadku interfesów należy używać interface_exists().
5.0.0 | Dodano parametr autoload.

Przykłady

Przykład #1 Przykład class_exists()

<?php
// Sprawdź czy klasa istnieje przed próbą jej użycia
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Przykład #2 Przykład z parametrem autoload

<?php
function __autoload($class)
{
    include($class . '.php');

    // Sprawdź czy w dołączanym pliku była deklaracja klasy
    if (!class_exists($class, false)) {
        trigger_error("Nie można załadować klasy: $class", E_USER_WARNING);
    }
}

if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Zobacz też:

  • function_exists() - Return TRUE if the given function has been defined
  • interface_exists() - Checks if the interface has been defined
  • get_declared_classes() - Zwraca tablicę z nazwami zdefiniowanych klas

class_alias
get_called_class
Funkcje Klasy/Obiekty


the "Late Static Binding" class name

class_exists
get_class_methods
Funkcje Klasy/Obiekty
PHP Manual

get_called_class

(PHP 5 >= 5.3.0)

get_called_class — the "Late Static Binding" class name

Opis

string get_called_class ( void )

Gets the name of the class the static method is called in.

Zwracane wartości

Returns the class name. Returns FALSE if called from outside a class.

Przykłady

Przykład #1 Using get_called_class()

<?php

class foo {
    static public function test() {
        var_dump(get_called_class());
    }
}

class bar extends foo {
}

foo::test();
bar::test();

?>

Powyższy przykład wyświetli:

string(3) "foo"
string(3) "bar"

Zobacz też:

  • get_parent_class() - Pobiera nazwę klasy przodka dla obiektu lub klasy
  • get_class() - Zwraca nazwę klasy zadanego obiektu
  • is_subclass_of() - Zwraca TRUE jeżeli klasa jest jednym z przodków obiektu

class_exists
get_class_methods
Funkcje Klasy/Obiekty


Zwraca tablicę nazw metod danej klasy

get_called_class
get_class_vars
Funkcje Klasy/Obiekty
PHP Manual

get_class_methods

(PHP 4, PHP 5)

get_class_methods — Zwraca tablicę nazw metod danej klasy

Opis

array get_class_methods ( mixed $nazwa_klasy )

Funkcja ta zwraca tablicę nazw metod zdefiniowanych dla klasy określonej przez parametr nazwa_klasy. W przypadku błędy zwracana jest wartośc NULL.

Informacja:

Od PHP 4.0.6, możesz określić obiekt przez jego samego, zamiast przez parametr nazwa_klasy. Dla przykładu:

<?php
$metody_klasy = get_class_methods($moj_obiekt); // zobacz poniższy pełny przykład
?>

Przykład #1 Przykład użycia get_class_methods()

<?php

class mojaklasa {
    // konstruktor
    function mojaklasa() {
        return(true);
    }

    // metoda 1
    function mojafun1() {
        return(true);
    }

    // metoda 2
    function mojafun2() {
        return(true);
    }
}

$metody_klasy = get_class_methods('mojaklasa');
// lub
$metody_klasy = get_class_methods(new mojaklasa());

foreach ($metody_klasy as $nazwa_metody) {
    echo "$nazwa_metody\n";
}

?>

Powyższy przykład wyświetli:

mojaklasa
mojafun1
mojafun2

Ostrzeżenie

Od PHP 5, funkcja zwraca nazwy metod tak jak zostały zadeklarowane (z uwzględnieniem wielkości liter). W PHP 4 były one zmieniane na małe litery.

Patrz także:
get_class(),
get_class_vars(),
get_object_vars().

get_called_class
get_class_vars
Funkcje Klasy/Obiekty


Zwraca tablicę domyślnych właściwości klasy

get_class_methods
get_class
Funkcje Klasy/Obiekty
PHP Manual

get_class_vars

(PHP 4, PHP 5)

get_class_vars — Zwraca tablicę domyślnych właściwości klasy

Opis

array get_class_vars ( string $nazwa_klasy )

Funkcja ta zwróci tablicę asocjacyjną domyślnych publicznych właściwości klasy. Elementy wynikowej tablicy są w formie nazwa_właściwości => wartość

Informacja:

W PHP w wersjach do 4.2.0 niezainicjalizowane zmienne klasy nie będą raportowane przez funkcję get_class_vars().

Przykład #1 Przykład użycia get_class_vars()

<?php

class mojaklasa {

    var $zm1; // ta nie ma domyślnej wartości...
    var $zm2 = "xyz";
    var $zm3 = 100;
    private $zm4; // PHP 5

    // konstruktor
    function mojaklasa() {
        // zmieńmy trochę właściwości
        $this->zm1 = "foo";
        $this->zm2 = "bar";
        return true;
    }

}

$moja_klasa = new mojaklasa();

$wlasciwosci_klasy = get_class_vars(get_class($moja_klasa));

foreach ($wlasciwosci_klasy as $nazwa => $wartosc) {
    echo "$nazwa : $wartosc\n";
}

?>

Powyższy przykład wyświetli:

// Przed PHP 4.2.0
zm2 : xyz
zm3 : 100

// PHP 4.2.0 i późniejsze wersje
zm1 :
zm2 : xyz
zm3 : 100

Patrz także: get_class_methods(), get_object_vars()

get_class_methods
get_class
Funkcje Klasy/Obiekty


Zwraca nazwę klasy zadanego obiektu

get_class_vars
get_declared_classes
Funkcje Klasy/Obiekty
PHP Manual

get_class

(PHP 4, PHP 5)

get_class — Zwraca nazwę klasy zadanego obiektu

Opis

string get_class ([ object $obiekt ] )

Funkcja ta zwraca nazwę klasy, której obiekt jest egzemplarzem. Zwraca FALSE jeżeli obiekt nie jest obiektem.

Informacja: Klasa zdefiniowana w rozszerzeniu PHP zwracana jest w oryginalnej notacji. W PHP 4, get_class() zwraca nazwę klasy zdefiniowanej przez użytkownika małymi literami, ale w PHP 5 nazwa klasy zostanie zwrócona również w oryginalnej notacji, tak jak nazwy klas z rozszerzeń PHP.

Informacja:

Od PHP 5, argument obiekt jest opcjonalny, jeśli funkcja została wywołana z wnętrza metody obiektu.

Przykład #1 Przykład użycia get_class()

<?php

class foo {
    function foo()
    {
    // implementacja pewnej logiki...
    }

    function nazwa()
    {
        echo "Nazywam się " , get_class($this) , "\n";
    }
}

// tworzymy obiekt
$bar = new foo();

// zewnętrzne wołanie
echo "Jego nazwa to " , get_class($bar) , "\n";

// wewnętrzne wołanie
$bar->nazwa();

?>

Powyższy przykład wyświetli:

Jego nazwa to foo
Nazywam się foo

Patrz także: get_parent_class(),
gettype(),
is_subclass_of().

get_class_vars
get_declared_classes
Funkcje Klasy/Obiekty


Zwraca tablicę z nazwami zdefiniowanych klas

get_class
get_declared_interfaces
Funkcje Klasy/Obiekty
PHP Manual

get_declared_classes

(PHP 4, PHP 5)

get_declared_classes — Zwraca tablicę z nazwami zdefiniowanych klas

Opis

array get_declared_classes ( void )

Funkcja ta zwraca tablicę nazw klas zdefiniowanych w bieżącym skrypcie.

Informacja:

W PHP 4.0.1pl2, zwracane są trzy dodatkowe klasy na początku tablicy: stdClass (zdefiniowana w Zend/zend.c), OverloadedTestClass (zdefiniowana w ext/standard/basic_functions.c) oraz Directory (zdfiniowana w ext/standard/dir.c).

Warto zauważyć, że zależnie od tego jakie biblioteki zostały dodane do PHP, mogą pojawić się dodatkowe klasy. To znaczy, że nie będzie można zdefiniować własnych klas używając tych nazw. Istnieje lista predefiniowanych klas w sekcji Predefined Classes w dodatkach.

Przykład #1 get_declared_classes() przykład

<?php
  print_r(get_declared_classes());
  ?>

Powyższy przykład wyświetli coś podobnego do:

  Array
  (
      [0] => stdClass
      [1] => __PHP_Incomplete_Class
      [2] => Directory
  )

Patrz także: class_exists() i get_declared_interfaces().

get_class
get_declared_interfaces
Funkcje Klasy/Obiekty


Returns an array of all declared interfaces

get_declared_classes
get_declared_traits
Funkcje Klasy/Obiekty
PHP Manual

get_declared_interfaces

(PHP 5)

get_declared_interfaces — Returns an array of all declared interfaces

Opis

array get_declared_interfaces ( void )

Gets the declared interfaces.

Zwracane wartości

Returns an array of the names of the declared interfaces in the current script.

Przykłady

Przykład #1 get_declared_interfaces() example

<?php
print_r(get_declared_interfaces());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

Zobacz też:

  • get_declared_classes() - Zwraca tablicę z nazwami zdefiniowanych klas
  • class_implements() - Return the interfaces which are implemented by the given class

get_declared_classes
get_declared_traits
Funkcje Klasy/Obiekty


Returns an array of all declared traits

get_declared_interfaces
get_object_vars
Funkcje Klasy/Obiekty
PHP Manual

get_declared_traits

(No version information available, might only be in SVN)

get_declared_traits — Returns an array of all declared traits

Opis

array get_declared_traits ( void )

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array with names of all declared traits in values. Returns NULL in case of a failure.

Zobacz też:

  • class_uses() - Return the traits used by the given class

get_declared_interfaces
get_object_vars
Funkcje Klasy/Obiekty


Zwraca tablicę asocjacyjną właściwości obiektu

get_declared_traits
get_parent_class
Funkcje Klasy/Obiekty
PHP Manual

get_object_vars

(PHP 4, PHP 5)

get_object_vars — Zwraca tablicę asocjacyjną właściwości obiektu

Opis

array get_object_vars ( object $obiekt )

Funkcja ta zwraca tablicę asocjacyjną zdfiniowanych właściwości określonego obiektu obiekt.

Informacja:

W wersjach PHP wcześniejszych niż 4.2.0, jeżeli zmienne zadeklarowane w klasie której obiekt jest egzemplarzem, nie mają przypisanej wartości, to te nie będą zwrócone w tablicy. W wersjach późniejszych tablica będzie zawierała klucz z przypisaną wartością NULL.

Przykład #1 Przykład użycia get_object_vars()

<?php
class Punkt2D {
    var $x, $y;
    var $opis;

    function Punkt2D($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    function ustawOpis($opis) {
        $this->opis = $opis;
    }

    function pobierzPunkt() {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "opis" => $this->opis);
    }
}

// "$opis" jest zadeklarowany lecz niezdefiniowany
$p1 = new Punkt2D(1.233, 3.445);
print_r(get_object_vars($p1));

$p1->ustawOpis("punkt #1");
print_r(get_object_vars($p1));

?>

Powyższy przykład wyświetli:

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] =>
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [opis] => punkt #1
 )

Patrz także: get_class_methods(), get_class_vars().

get_declared_traits
get_parent_class
Funkcje Klasy/Obiekty


Pobiera nazwę klasy przodka dla obiektu lub klasy

get_object_vars
interface_exists
Funkcje Klasy/Obiekty
PHP Manual

get_parent_class

(PHP 4, PHP 5)

get_parent_class — Pobiera nazwę klasy przodka dla obiektu lub klasy

Opis

string get_parent_class ([ mixed $obiekt ] )

Jeżeli obiekt jest obiektem, zwraca nazwę klasy przodka klasy której obiekt jest egzemplarzem.

Jeżeli obiekt jest ciągiem znakowym, zwraca nazwę klasy przodka klasy o tej nazwie. Ta funkcjonalność została dodana w PHP 4.0.5.

Informacja:

Od PHP 5, argument obiekt jest opcjonalny, jeśli funkcja została wywołana z wnętrza metody obiektu. Jeśli zostanie wywołana bez argumentu spoza metody, zwrócona zostanie wartość FALSE (lub NULL razem z ostrzeżeniem w wersjach starszych niż PHP 5.1.0).

Przykład #1 Przykład użycia get_parent_class()

<?php

class tata {
    function tata()
    {
    // implementacja jakiejś logiki...
    }
}

class dziecko extends tata {
    function dziecko()
    {
        echo "Moim prodkiem jest " , get_parent_class($this) , "\n";
    }
}

class dziecko2 extends tata {
    function dziecko2()
    {
        echo "Moim przodkiem także jest " , get_parent_class('dziecko2') , "\n";
    }
}

$foo = new dzicko();
$bar = new dziecko2();

?>

Powyższy przykład wyświetli:

Moim przodkiem jest tata
Moim przodkiem także jest tata

Patrz także: get_class(), is_subclass_of()

get_object_vars
interface_exists
Funkcje Klasy/Obiekty


Checks if the interface has been defined

get_parent_class
is_a
Funkcje Klasy/Obiekty
PHP Manual

interface_exists

(PHP 5 >= 5.0.2)

interface_exists — Checks if the interface has been defined

Opis

bool interface_exists ( string $interface_name [, bool $autoload = true ] )

Checks if the given interface has been defined.

Parametry

interface_name

The interface name

autoload

Whether to call __autoload or not by default.

Zwracane wartości

Returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.

Przykłady

Przykład #1 interface_exists() example

<?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Methods
    }
}

?>

Zobacz też:

  • class_exists() - Sprawdza, czy klasa została zdefiniowana

get_parent_class
is_a
Funkcje Klasy/Obiekty


Zwraca TRUE jeżeli obiekt jest tej klasy, lub ta klasa jest jednym z jego przodków

interface_exists
is_subclass_of
Funkcje Klasy/Obiekty
PHP Manual

is_a

(PHP 4 >= 4.2.0, PHP 5)

is_a — Zwraca TRUE jeżeli obiekt jest tej klasy, lub ta klasa jest jednym z jego przodków

Opis

bool is_a ( object $obiekt , string $nazwa_klasy )

Funkcja ta zwraca TRUE jeżeli obiekt jest tej klasy, lub ta klasa jest jednym z jego przodków, FALSE w przeciwnym przypadku.

Przykład #1 is_a() przykład

<?php
// definicja klasy
class WidgetFactory
{
  var $oink = 'moo';
}

// tworzenie nowego obiektu
$WF = new WidgetFactory();

if (is_a($WF, 'WidgetFactory')) {
  echo "tak, \$WF jest ciągle WidgetFactory\n";
}
?>

Funkcja is_a() w PHP 5 jest przestarzała, na korzyść operatora typu instanceof. W powyższym przyładzie w PHP 5 moglibyśmy użyć następującej konstrukcji:

Przykład #2 Użycie operatora instanceof w PHP 5

<?php
if ($WF instanceof WidgetFactory) {
    echo 'Tak, $WF jest WidgetFactory';
}
?>

Patrz także: get_class(),
get_parent_class(),
is_subclass_of().

interface_exists
is_subclass_of
Funkcje Klasy/Obiekty


Zwraca TRUE jeżeli klasa jest jednym z przodków obiektu

is_a
method_exists
Funkcje Klasy/Obiekty
PHP Manual

is_subclass_of

(PHP 4, PHP 5)

is_subclass_of — Zwraca TRUE jeżeli klasa jest jednym z przodków obiektu

Opis

bool is_subclass_of ( mixed $obiekt , string $nazwa_klasy )

Funkcja ta zwraca TRUE jeżeli obiekt obiekt należy do klasy która jest podklasą klasy nazwa_klasy, FALSE w przeciwnym przypadku.

Informacja:

Od PHP 5.0.3 możesz określić parametr object także jako łańcuch znaków (nazwę klasy).

Przykład #1 is_subclass_of() przykład

<?php
// definicja klasy
class WidgetFactory
{
  var $oink = 'moo';
}

// definicja klasy potomnej
class WidgetFactory_Child extends WidgetFactory
{
  var $oink = 'oink';
}

// tworzenie nowego obiektu
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();

if (is_subclass_of($WFC, 'WidgetFactory')) {
  echo "tak, \$WFC jest pod klasą WidgetFactory\n";
} else {
  echo "nie, \$WFC nie jest pod klasą WidgetFactory\n";
}

if (is_subclass_of($WF, 'WidgetFactory')) {
  echo "tak, \$WF jest pod klasą WidgetFactory\n";
} else {
  echo "nie, \$WF nie jest pod klasą WidgetFactory\n";
}

// użyteczne dopiero od PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
  echo "tak, WidgetFactory_Child jest pod klasą WidgetFactory\n";
} else {
  echo "nie, WidgetFactory_Child nie jest pod klasą WidgetFactory\n";
}
?>

Powyższy przykład wyświetli:

tak, $WFC jest pod klasą WidgetFactory
nie, $WF nie jest pod klasą WidgetFactory
tak, WidgetFactory_Child jest pod klasą WidgetFactory

Patrz także: get_class(),
get_parent_class(),
is_a().

is_a
method_exists
Funkcje Klasy/Obiekty


Sprawdza czy metoda klasy istnieje

is_subclass_of
property_exists
Funkcje Klasy/Obiekty
PHP Manual

method_exists

(PHP 4, PHP 5)

method_exists — Sprawdza czy metoda klasy istnieje

Opis

bool method_exists ( object $obiekt , string $nazwa_metody )

Funkcja ta zwraca TRUE jeżeli metoda określona przez parametr nazwa_metody została zdefiniowany dla obiektu object, FALSE w przeciwnym przypadku.

Przykład #1 method_exists() przykład

<?php
  $directory = new Directory('.');
  var_dump(method_exists($directory,'read'));
  ?>

Powyższy przykład wyświetli:

  bool(true)

Patrz także: function_exists() i is_callable().

is_subclass_of
property_exists
Funkcje Klasy/Obiekty


Checks if the object or class has a property

method_exists
trait_exists
Funkcje Klasy/Obiekty
PHP Manual

property_exists

(PHP 5 >= 5.1.0)

property_exists — Checks if the object or class has a property

Opis

bool property_exists ( mixed $class , string $property )

This function checks if the given property exists in the specified class.

Informacja:

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

Parametry

class

The class name or an object of the class to test for

property

The name of the property

Zwracane wartości

Returns TRUE if the property exists, FALSE if it doesn't exist or NULL in case of an error.

Notatki

Informacja:

Using this function will use any registered autoloaders if the class is not already known.

Informacja:

The property_exists() function cannot detect properties that are magically accessible using the __get magic method.

Rejestr zmian

Wersja | Opis
5.3.0 | This function checks the existence of a property independent of accessibility.

Przykłady

Przykład #1 A property_exists() example

<?php

class myClass {
    public $mine;
    private $xpto;
    static protected $test;

    static function test() {
        var_dump(property_exists('myClass', 'xpto')); //true
    }
}

var_dump(property_exists('myClass', 'mine'));   //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto'));   //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'bar'));    //false
var_dump(property_exists('myClass', 'test'));   //true, as of PHP 5.3.0
myClass::test();

?>

Zobacz też:

  • method_exists() - Sprawdza czy metoda klasy istnieje

method_exists
trait_exists
Funkcje Klasy/Obiekty


Checks if the trait exists

property_exists
Classkit
Funkcje Klasy/Obiekty
PHP Manual

trait_exists

(No version information available, might only be in SVN)

trait_exists — Checks if the trait exists

Opis

bool trait_exists ( string $traitname [, bool $autoload ] )

Parametry

traitname

Name of the trait to check

autoload

Whether to autoload if not already loaded.

Zwracane wartości

Returns TRUE if trait exists, FALSE if not, NULL in case of an error.

property_exists
Classkit
Funkcje Klasy/Obiekty


Classkit

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Classkit Funkcje
    • classkit_import — Import new class method definitions from a file
    • classkit_method_add — Dynamically adds a new method to a given class
    • classkit_method_copy — Copies a method from class to another
    • classkit_method_redefine — Dynamically changes the code of the given method
    • classkit_method_remove — Dynamically removes the given method
    • classkit_method_rename — Dynamically changes the name of the given method
trait_exists
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

These functions allow the dynamic manipulation of PHP classes, at runtime.

Informacja:

This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.

Classkit
Instalacja/Konfiguracja
Classkit


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Classkit


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/classkit.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

CLASSKIT_ACC_PRIVATE (int)
Marks the method private
CLASSKIT_ACC_PROTECTED (int)
Marks the method protected
CLASSKIT_ACC_PUBLIC (int)
Marks the method public

Typy zasobów
Classkit Funkcje
Classkit


Classkit Funkcje

Spis treści

  • classkit_import — Import new class method definitions from a file
  • classkit_method_add — Dynamically adds a new method to a given class
  • classkit_method_copy — Copies a method from class to another
  • classkit_method_redefine — Dynamically changes the code of the given method
  • classkit_method_remove — Dynamically removes the given method
  • classkit_method_rename — Dynamically changes the name of the given method
Stałe predefiniowane
classkit_import
Classkit


Import new class method definitions from a file

Classkit Funkcje
classkit_method_add
Classkit Funkcje
PHP Manual

classkit_import

(PECL classkit >= 0.3)

classkit_import — Import new class method definitions from a file

Opis

array classkit_import ( string $filename )

Informacja: Ta funkcja nie może być użyta do manipulowania aktualnie wykonywaną metodą.

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

filename

The filename of the class method definitions to import

Zwracane wartości

Associative array of imported methods

Przykłady

Przykład #1 classkit_import() example

<?php
// file: newclass.php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?>
<?php
// requires newclass.php (see above)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// output original
echo $e->foo();

// import replacement method
classkit_import('newclass.php');

// output imported
echo $e->foo();

?>

Powyższy przykład wyświetli:

foo!
bar!

Zobacz też:

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another

Classkit Funkcje
classkit_method_add
Classkit Funkcje


Dynamically adds a new method to a given class

classkit_import
classkit_method_copy
Classkit Funkcje
PHP Manual

classkit_method_add

(PECL classkit >= 0.1)

classkit_method_add — Dynamically adds a new method to a given class

Opis

bool classkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_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 CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_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 classkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
classkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

Powyższy przykład wyświetli:

16

Zobacz też:

  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method
  • create_function() - Create an anonymous (lambda-style) function

classkit_import
classkit_method_copy
Classkit Funkcje


Copies a method from class to another

classkit_method_add
classkit_method_redefine
Classkit Funkcje
PHP Manual

classkit_method_copy

(PECL classkit >= 0.2)

classkit_method_copy — Copies a method from class to another

Opis

bool classkit_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 classkit_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()
classkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

Powyższy przykład wyświetli:

foo!

Zobacz też:

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method

classkit_method_add
classkit_method_redefine
Classkit Funkcje


Dynamically changes the code of the given method

classkit_method_copy
classkit_method_remove
Classkit Funkcje
PHP Manual

classkit_method_redefine

(PECL classkit >= 0.1)

classkit_method_redefine — Dynamically changes the code of the given method

Opis

bool classkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_ACC_PUBLIC ] )

Informacja: Ta funkcja nie może być użyta do manipulowania aktualnie wykonywaną metodą.

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 CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_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 classkit_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
classkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

Powyższy przykład wyświetli:

Before: foo!
After: bar!

Zobacz też:

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method

classkit_method_copy
classkit_method_remove
Classkit Funkcje


Dynamically removes the given method

classkit_method_redefine
classkit_method_rename
Classkit Funkcje
PHP Manual

classkit_method_remove

(PECL classkit >= 0.1)

classkit_method_remove — Dynamically removes the given method

Opis

bool classkit_method_remove ( string $classname , string $methodname )

Informacja: Ta funkcja nie może być użyta do manipulowania aktualnie wykonywaną metodą.

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 classkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
classkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

Powyższy przykład wyświetli:

bar

Zobacz też:

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_rename() - Dynamically changes the name of the given method

classkit_method_redefine
classkit_method_rename
Classkit Funkcje


Dynamically changes the name of the given method

classkit_method_remove
Ctype
Classkit Funkcje
PHP Manual

classkit_method_rename

(PECL classkit >= 0.1)

classkit_method_rename — Dynamically changes the name of the given method

Opis

bool classkit_method_rename ( string $classname , string $methodname , string $newname )

Informacja: Ta funkcja nie może być użyta do manipulowania aktualnie wykonywaną metodą.

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 classkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
classkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

Powyższy przykład wyświetli:

foo!

Zobacz też:

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method

classkit_method_remove
Ctype
Classkit Funkcje


Character type checking

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Ctype Funkcje
    • ctype_alnum — Check for alphanumeric character(s)
    • ctype_alpha — Check for alphabetic character(s)
    • ctype_cntrl — Check for control character(s)
    • ctype_digit — Check for numeric character(s)
    • ctype_graph — Check for any printable character(s) except space
    • ctype_lower — Check for lowercase character(s)
    • ctype_print — Check for printable character(s)
    • ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
    • ctype_space — Check for whitespace character(s)
    • ctype_upper — Check for uppercase character(s)
    • ctype_xdigit — Check for character(s) representing a hexadecimal digit
classkit_method_rename
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale (see also setlocale()).

When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 and -1 inclusive then 256 will be added and the check will be done on that.

When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE in PHP < 5.1 and FALSE since 5.1.

Passing anything else but a string or integer will return FALSE immediately.

It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent str_* and is_* functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.

Ctype
Instalacja/Konfiguracja
Ctype


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Ctype


Wymagania

None besides functions from the standard C library which are always available.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype . You can disable ctype support with --disable-ctype .

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: Builtin support for ctype is available with PHP 4.3.0.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Ctype Funkcje
Ctype


Ctype Funkcje

Spis treści

  • ctype_alnum — Check for alphanumeric character(s)
  • ctype_alpha — Check for alphabetic character(s)
  • ctype_cntrl — Check for control character(s)
  • ctype_digit — Check for numeric character(s)
  • ctype_graph — Check for any printable character(s) except space
  • ctype_lower — Check for lowercase character(s)
  • ctype_print — Check for printable character(s)
  • ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
  • ctype_space — Check for whitespace character(s)
  • ctype_upper — Check for uppercase character(s)
  • ctype_xdigit — Check for character(s) representing a hexadecimal digit
Stałe predefiniowane
ctype_alnum
Ctype


Check for alphanumeric character(s)

Ctype Funkcje
ctype_alpha
Ctype Funkcje
PHP Manual

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5)

ctype_alnum — Check for alphanumeric character(s)

Opis

bool ctype_alnum ( string $text )

Checks if all of the characters in the provided string, text, are alphanumeric. In the standard C locale letters are just [A-Za-z].

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.

Przykłady

Przykład #1 A ctype_alnum() example (using the default locale)

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_digit() - Check for numeric character(s)
  • setlocale() - Set locale information

Ctype Funkcje
ctype_alpha
Ctype Funkcje


Check for alphabetic character(s)

ctype_alnum
ctype_cntrl
Ctype Funkcje
PHP Manual

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5)

ctype_alpha — Check for alphabetic character(s)

Opis

bool ctype_alpha ( string $text )

Checks if all of the characters in the provided string, text, are alphabetic. In the standard C locale letters are just [A-Za-z] and ctype_alpha() is equivalent to (ctype_upper($text) || ctype_lower($text)) if $text is just a single character, but other languages have letters that are considered neither upper nor lower case.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise.

Przykłady

Przykład #1 A ctype_alpha() example (using the default locale)

<?php
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
    if (ctype_alpha($testcase)) {
        echo "The string $testcase consists of all letters.\n";
    } else {
        echo "The string $testcase does not consist of all letters.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string KjgWZC consists of all letters.
The string arf12 does not consist of all letters.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_upper() - Check for uppercase character(s)
  • ctype_lower() - Check for lowercase character(s)
  • setlocale() - Set locale information

ctype_alnum
ctype_cntrl
Ctype Funkcje


Check for control character(s)

ctype_alpha
ctype_digit
Ctype Funkcje
PHP Manual

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5)

ctype_cntrl — Check for control character(s)

Opis

bool ctype_cntrl ( string $text )

Checks if all of the characters in the provided string, text, are control characters. Control characters are e.g. line feed, tab, escape.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.

Przykłady

Przykład #1 A ctype_cntrl() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
    if (ctype_cntrl($testcase)) {
        echo "The string '$name' consists of all control characters.\n";
    } else {
        echo "The string '$name' does not consist of all control characters.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string 'string1' consists of all control characters.
The string 'string2' does not consist of all control characters.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_print() - Check for printable character(s)

ctype_alpha
ctype_digit
Ctype Funkcje


Check for numeric character(s)

ctype_cntrl
ctype_graph
Ctype Funkcje
PHP Manual

ctype_digit

(PHP 4 >= 4.0.4, PHP 5)

ctype_digit — Check for numeric character(s)

Opis

bool ctype_digit ( string $text )

Checks if all of the characters in the provided string, text, are numerical.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.

Rejestr zmian

Wersja | Opis
5.1.0 | Before PHP 5.1.0, this function returned TRUE when text was an empty string.

Przykłady

Przykład #1 A ctype_digit() example

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string 1820.20 does not consist of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consist of all digits.

Przykład #2 A ctype_digit() example comparing strings with integers

<?php

$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 is the * character)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

Notatki

Informacja:

This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual.

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_alnum() - Check for alphanumeric character(s)
  • ctype_xdigit() - Check for character(s) representing a hexadecimal digit
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string

ctype_cntrl
ctype_graph
Ctype Funkcje


Check for any printable character(s) except space

ctype_digit
ctype_lower
Ctype Funkcje
PHP Manual

ctype_graph

(PHP 4 >= 4.0.4, PHP 5)

ctype_graph — Check for any printable character(s) except space

Opis

bool ctype_graph ( string $text )

Checks if all of the characters in the provided string, text, creates visible output.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

Przykłady

Przykład #1 A ctype_graph() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_graph($testcase)) {
        echo "The string '$name' consists of all (visibly) printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all (visibly) printable characters.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string 'string1' does not consist of all (visibly) printable characters.
The string 'string2' consists of all (visibly) printable characters.
The string 'string3' consists of all (visibly) printable characters.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_alnum() - Check for alphanumeric character(s)
  • ctype_print() - Check for printable character(s)
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character

ctype_digit
ctype_lower
Ctype Funkcje


Check for lowercase character(s)

ctype_graph
ctype_print
Ctype Funkcje
PHP Manual

ctype_lower

(PHP 4 >= 4.0.4, PHP 5)

ctype_lower — Check for lowercase character(s)

Opis

bool ctype_lower ( string $text )

Checks if all of the characters in the provided string, text, are lowercase letters.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text is a lowercase letter in the current locale.

Przykłady

Przykład #1 A ctype_lower() example (using the default locale)

<?php
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
    if (ctype_lower($testcase)) {
        echo "The string $testcase consists of all lowercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all lowercase letters.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string aac123 does not consist of all lowercase letters.
The string qiutoas consists of all lowercase letters.
The string QASsdks does not consist of all lowercase letters.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_upper() - Check for uppercase character(s)
  • setlocale() - Set locale information

ctype_graph
ctype_print
Ctype Funkcje


Check for printable character(s)

ctype_lower
ctype_punct
Ctype Funkcje
PHP Manual

ctype_print

(PHP 4 >= 4.0.4, PHP 5)

ctype_print — Check for printable character(s)

Opis

bool ctype_print ( string $text )

Checks if all of the characters in the provided string, text, are printable.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.

Przykłady

Przykład #1 A ctype_print() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_print($testcase)) {
        echo "The string '$name' consists of all printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all printable characters.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string 'string1' does not consist of all printable characters.
The string 'string2' consists of all printable characters.
The string 'string3' consists of all printable characters.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character

ctype_lower
ctype_punct
Ctype Funkcje


Check for any printable character which is not whitespace or an alphanumeric character

ctype_print
ctype_space
Ctype Funkcje
PHP Manual

ctype_punct

(PHP 4 >= 4.0.4, PHP 5)

ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character

Opis

bool ctype_punct ( string $text )

Checks if all of the characters in the provided string, text, are punctuation character.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

Przykłady

Przykład #1 A ctype_punct() example

<?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
    if (ctype_punct($testcase)) {
        echo "The string $testcase consists of all punctuation.\n";
    } else {
        echo "The string $testcase does not consist of all punctuation.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string ABasdk!@!$# does not consist of all punctuation.
The string !@ # $ does not consist of all punctuation.
The string *&$() consists of all punctuation.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space

ctype_print
ctype_space
Ctype Funkcje


Check for whitespace character(s)

ctype_punct
ctype_upper
Ctype Funkcje
PHP Manual

ctype_space

(PHP 4 >= 4.0.4, PHP 5)

ctype_space — Check for whitespace character(s)

Opis

bool ctype_space ( string $text )

Checks if all of the characters in the provided string, text, creates whitespace.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.

Przykłady

Przykład #1 A ctype_space() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => "\narf12", 'string3' => '\n\r\t');
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "The string '$name' consists of all whitespace characters.\n";
    } else {
        echo "The string '$name' does not consist of all whitespace characters.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string 'string1' consists of all whitespace characters.
The string 'string2' does not consist of all whitespace characters.
The string 'string3' does not consist of all whitespace characters.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character

ctype_punct
ctype_upper
Ctype Funkcje


Check for uppercase character(s)

ctype_space
ctype_xdigit
Ctype Funkcje
PHP Manual

ctype_upper

(PHP 4 >= 4.0.4, PHP 5)

ctype_upper — Check for uppercase character(s)

Opis

bool ctype_upper ( string $text )

Checks if all of the characters in the provided string, text, are uppercase characters.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text is an uppercase letter in the current locale.

Przykłady

Przykład #1 A ctype_upper() example (using the default locale)

<?php
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
    if (ctype_upper($testcase)) {
        echo "The string $testcase consists of all uppercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all uppercase letters.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string AKLWC139 does not consist of all uppercase letters.
The string LMNSDO consists of all uppercase letters.
The string akwSKWsm does not consist of all uppercase letters.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_lower() - Check for lowercase character(s)
  • setlocale() - Set locale information

ctype_space
ctype_xdigit
Ctype Funkcje


Check for character(s) representing a hexadecimal digit

ctype_upper
Filter
Ctype Funkcje
PHP Manual

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5)

ctype_xdigit — Check for character(s) representing a hexadecimal digit

Opis

bool ctype_xdigit ( string $text )

Checks if all of the characters in the provided string, text, are hexadecimal 'digits'.

Parametry

text

The tested string.

Zwracane wartości

Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.

Przykłady

Przykład #1 A ctype_xdigit() example

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "The string $testcase consists of all hexadecimal digits.\n";
    } else {
        echo "The string $testcase does not consist of all hexadecimal digits.\n";
    }
}
?>

Powyższy przykład wyświetli:

The string AB10BC99 consists of all hexadecimal digits.
The string AR1012 does not consist of all hexadecimal digits.
The string ab12bc99 consists of all hexadecimal digits.

Notatki

Informacja:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

Zobacz też:

  • ctype_digit() - Check for numeric character(s)

ctype_upper
Filter
Ctype Funkcje


Data Filtering

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Types of filters
    • Validate filters
    • Sanitize filters
    • Other filters
    • Filter flags
  • Stałe predefiniowane
  • Przykłady
    • Validation
    • Sanitization
  • Filter Funkcje
    • filter_has_var — Checks if variable of specified type exists
    • filter_id — Returns the filter ID belonging to a named filter
    • filter_input_array — Gets external variables and optionally filters them
    • filter_input — Gets a specific external variable by name and optionally filters it
    • filter_list — Returns a list of all supported filters
    • filter_var_array — Gets multiple variables and optionally filters them
    • filter_var — Filters a variable with a specified filter
ctype_xdigit
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

This extension filters data by either validating or sanitizing it. This is especially useful when the data source contains unknown (or foreign) data, like user supplied input. For example, this data may come from an HTML form.

There are two main types of filtering: validation and sanitization.

Validation is used to validate or check if the data meets certain qualifications. For example, passing in FILTER_VALIDATE_EMAIL will determine if the data is a valid email address, but will not change the data itself.

Sanitization will sanitize the data, so it may alter it by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain. That said, it does not validate the data.

Flags are optionally used with both validation and sanitization to tweak behaviour according to need. For example, passing in FILTER_FLAG_PATH_REQUIRED while filtering an URL will require a path (like /foo in http://example.org/foo) to be present.

Filter
Instalacja/Konfiguracja
Filter


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Filter


Instalacja

The filter extension is enabled by default as of PHP 5.2.0. Before this time an experimental PECL extension was used, however, the PECL version is no longer recommended or updated.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Filter Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.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.

filter.default string

Filter all $_GET, $_POST, $_COOKIE, $_REQUEST and $_SERVER data by this filter. Original data can be accessed through filter_input().

Accepts the name of the filter you like to use by default. See the existing filter list for the list of the filter names.

filter.default_flags integer

Default flags. See the existing flag list for the list of the flag names.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
Types of filters
Instalacja/Konfiguracja


Types of filters

Spis treści

  • Validate filters
  • Sanitize filters
  • Other filters
  • Filter flags
Typy zasobów
Validate filters
Filter


Validate filters

Listing of filters for validation
ID | Name | Options | Flags | Description
FILTER_VALIDATE_BOOLEAN | "boolean" |  | FILTER_NULL_ON_FAILURE | Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise. If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.
FILTER_VALIDATE_EMAIL | "validate_email" |  |  | Validates value as e-mail.
FILTER_VALIDATE_FLOAT | "float" | decimal | FILTER_FLAG_ALLOW_THOUSAND | Validates value as float.
FILTER_VALIDATE_INT | "int" | min_range, max_range | FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX | Validates value as integer, optionally from the specified range.
FILTER_VALIDATE_IP | "validate_ip" |  | FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE | Validates value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges.
FILTER_VALIDATE_REGEXP | "validate_regexp" | regexp |  | Validates value against regexp, a Perl-compatible regular expression.
FILTER_VALIDATE_URL | "validate_url" |  | FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED | Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.

Informacja:

Numbers +0 and -0 are not valid integers but validate as floats.

Types of filters
Sanitize filters
Types of filters


Sanitize filters

List of filters for sanitization
ID | Name | Options | Flags | Description
FILTER_SANITIZE_EMAIL | "email" |  |  | Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
FILTER_SANITIZE_ENCODED | "encoded" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH | URL-encode string, optionally strip or encode special characters.
FILTER_SANITIZE_MAGIC_QUOTES | "magic_quotes" |  |  | Apply addslashes().
FILTER_SANITIZE_NUMBER_FLOAT | "number_float" |  | FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, FILTER_FLAG_ALLOW_SCIENTIFIC | Remove all characters except digits, +- and optionally .,eE.
FILTER_SANITIZE_NUMBER_INT | "number_int" |  |  | Remove all characters except digits, plus and minus sign.
FILTER_SANITIZE_SPECIAL_CHARS | "special_chars" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_HIGH | HTML-escape '"<>& and characters with ASCII value less than 32, optionally strip or encode other special characters.
FILTER_SANITIZE_FULL_SPECIAL_CHARS | "full_special_chars" |  | FILTER_FLAG_NO_ENCODE_QUOTES, | Equivalent to calling htmlspecialchars() with ENT_QUOTES set. Encoding quotes can be disabled by setting FILTER_FLAG_NO_ENCODE_QUOTES. Like htmlspecialchars(), this filter is aware of the default_charset and if a sequence of bytes is detected that makes up an invalid character in the current character set then the entire string is rejected resulting in a 0-length string.
FILTER_SANITIZE_STRING | "string" |  | FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Strip tags, optionally strip or encode special characters.
FILTER_SANITIZE_STRIPPED | "stripped" |  |  | Alias of "string" filter.
FILTER_SANITIZE_URL | "url" |  |  | Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.
FILTER_UNSAFE_RAW | "unsafe_raw" |  | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Do nothing, optionally strip or encode special characters.

Validate filters
Other filters
Types of filters


Other filters

List of miscellaneous filters
ID | Name | Options | Flags | Description
FILTER_CALLBACK | "callback" | callback function or method |  | Call user-defined function to filter data.

Sanitize filters
Filter flags
Types of filters


Filter flags

List of filter flags
ID | Used with | Description
FILTER_FLAG_STRIP_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that has a numerical value <32.
FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that has a numerical value >127.
FILTER_FLAG_ALLOW_FRACTION | FILTER_SANITIZE_NUMBER_FLOAT | Allows a period (.) as a fractional separator in numbers.
FILTER_FLAG_ALLOW_THOUSAND | FILTER_SANITIZE_NUMBER_FLOAT, FILTER_VALIDATE_FLOAT | Allows a comma (,) as a thousands separator in numbers.
FILTER_FLAG_ALLOW_SCIENTIFIC | FILTER_SANITIZE_NUMBER_FLOAT | Allows an e or E for scientific notation in numbers.
FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_SANITIZE_STRING | If this flag is present, single (') and double (") quotes will not be encoded.
FILTER_FLAG_ENCODE_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes all characters with a numerical value <32.
FILTER_FLAG_ENCODE_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes all characters with a numerical value >127.
FILTER_FLAG_ENCODE_AMP | FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes ampersands (&).
FILTER_NULL_ON_FAILURE | FILTER_VALIDATE_BOOLEAN | Returns NULL for unrecognized boolean values.
FILTER_FLAG_ALLOW_OCTAL | FILTER_VALIDATE_INT | Regards inputs starting with a zero (0) as octal numbers. This only allows the succeeding digits to be 0-7.
FILTER_FLAG_ALLOW_HEX | FILTER_VALIDATE_INT | Regards inputs starting with 0x or 0X as hexadecimal numbers. This only allows succeeding characters to be a-fA-F0-9.
FILTER_FLAG_IPV4 | FILTER_VALIDATE_IP | Allows the IP address to be in IPv4 format.
FILTER_FLAG_IPV6 | FILTER_VALIDATE_IP | Allows the IP address to be in IPv6 format.
FILTER_FLAG_NO_PRIV_RANGE | FILTER_VALIDATE_IP | Fails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Fails validation for the IPv6 addresses starting with FD or FC.
FILTER_FLAG_NO_RES_RANGE | FILTER_VALIDATE_IP | Fails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24 and 224.0.0.0/4. This flag does not apply to IPv6 addresses.
FILTER_FLAG_PATH_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a path part.
FILTER_FLAG_QUERY_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a query string.

Other filters
Stałe predefiniowane
Types of filters


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.

INPUT_POST (integer)
POST variables.
INPUT_GET (integer)
GET variables.
INPUT_COOKIE (integer)
COOKIE variables.
INPUT_ENV (integer)
ENV variables.
INPUT_SERVER (integer)
SERVER variables.
INPUT_SESSION (integer)
SESSION variables. (not implemented yet)
INPUT_REQUEST (integer)
REQUEST variables. (not implemented yet)
FILTER_FLAG_NONE (integer)
No flags.
FILTER_REQUIRE_SCALAR (integer)
Flag used to require scalar as input
FILTER_REQUIRE_ARRAY (integer)
Require an array as input.
FILTER_FORCE_ARRAY (integer)
Always returns an array.
FILTER_NULL_ON_FAILURE (integer)
Use NULL instead of FALSE on failure.
FILTER_VALIDATE_INT (integer)
ID of "int" filter.
FILTER_VALIDATE_BOOLEAN (integer)
ID of "boolean" filter.
FILTER_VALIDATE_FLOAT (integer)
ID of "float" filter.
FILTER_VALIDATE_REGEXP (integer)
ID of "validate_regexp" filter.
FILTER_VALIDATE_URL (integer)
ID of "validate_url" filter.
FILTER_VALIDATE_EMAIL (integer)
ID of "validate_email" filter.
FILTER_VALIDATE_IP (integer)
ID of "validate_ip" filter.
FILTER_DEFAULT (integer)
ID of default ("string") filter.
FILTER_UNSAFE_RAW (integer)
ID of "unsafe_raw" filter.
FILTER_SANITIZE_STRING (integer)
ID of "string" filter.
FILTER_SANITIZE_STRIPPED (integer)
ID of "stripped" filter.
FILTER_SANITIZE_ENCODED (integer)
ID of "encoded" filter.
FILTER_SANITIZE_SPECIAL_CHARS (integer)
ID of "special_chars" filter.
FILTER_SANITIZE_EMAIL (integer)
ID of "email" filter.
FILTER_SANITIZE_URL (integer)
ID of "url" filter.
FILTER_SANITIZE_NUMBER_INT (integer)
ID of "number_int" filter.
FILTER_SANITIZE_NUMBER_FLOAT (integer)
ID of "number_float" filter.
FILTER_SANITIZE_MAGIC_QUOTES (integer)
ID of "magic_quotes" filter.
FILTER_CALLBACK (integer)
ID of "callback" filter.
FILTER_FLAG_ALLOW_OCTAL (integer)
Allow octal notation (0[0-7]+) in "int" filter.
FILTER_FLAG_ALLOW_HEX (integer)
Allow hex notation (0x[0-9a-fA-F]+) in "int" filter.
FILTER_FLAG_STRIP_LOW (integer)
Strip characters with ASCII value less than 32.
FILTER_FLAG_STRIP_HIGH (integer)
Strip characters with ASCII value greater than 127.
FILTER_FLAG_ENCODE_LOW (integer)
Encode characters with ASCII value less than 32.
FILTER_FLAG_ENCODE_HIGH (integer)
Encode characters with ASCII value greater than 127.
FILTER_FLAG_ENCODE_AMP (integer)
Encode &.
FILTER_FLAG_NO_ENCODE_QUOTES (integer)
Don't encode ' and ".
FILTER_FLAG_EMPTY_STRING_NULL (integer)
(No use for now.)
FILTER_FLAG_ALLOW_FRACTION (integer)
Allow fractional part in "number_float" filter.
FILTER_FLAG_ALLOW_THOUSAND (integer)
Allow thousand separator (,) in "number_float" filter.
FILTER_FLAG_ALLOW_SCIENTIFIC (integer)
Allow scientific notation (e, E) in "number_float" filter.
FILTER_FLAG_PATH_REQUIRED (integer)
Require path in "validate_url" filter.
FILTER_FLAG_QUERY_REQUIRED (integer)
Require query in "validate_url" filter.
FILTER_FLAG_IPV4 (integer)
Allow only IPv4 address in "validate_ip" filter.
FILTER_FLAG_IPV6 (integer)
Allow only IPv6 address in "validate_ip" filter.
FILTER_FLAG_NO_RES_RANGE (integer)
Deny reserved addresses in "validate_ip" filter.
FILTER_FLAG_NO_PRIV_RANGE (integer)
Deny private addresses in "validate_ip" filter.
Filter flags
Przykłady
Filter


Przykłady

Spis treści

  • Validation
  • Sanitization
Stałe predefiniowane
Validation
Filter


Validation

Przykład #1 Validating email addresses with filter_var()

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_b) email address is considered valid.";
}
?>

Powyższy przykład wyświetli:

This (email_a) email address is considered valid.

Przykład #2 Validating IP addresses with filter_var()

<?php
$ip_a = '127.0.0.1';
$ip_b = '42.42';

if (filter_var($ip_a, FILTER_VALIDATE_IP)) {
    echo "This (ip_a) IP address is considered valid.";
}
if (filter_var($ip_b, FILTER_VALIDATE_IP)) {
    echo "This (ip_b) IP address is considered valid.";
}
?>

Powyższy przykład wyświetli:

This (ip_a) IP address is considered valid.

Przykład #3 Passing options to filter_var()

<?php
$int_a = '1';
$int_b = '-1';
$int_c = '4';
$options = array(
    'options' => array(
                      'min_range' => 0,
                      'max_range' => 3,
                      )
);
if (filter_var($int_a, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "This (int_a) integer is considered valid (between 0 and 3).\n";
}
if (filter_var($int_b, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "This (int_b) integer is considered valid (between 0 and 3).\n";
}
if (filter_var($int_c, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "This (int_c) integer is considered valid (between 0 and 3).\n";
}

$options['options']['default'] = 1;
if (($int_c = filter_var($int_c, FILTER_VALIDATE_INT, $options)) !== FALSE) {
    echo "This (int_c) integer is considered valid (between 0 and 3) and is $int_c.";
}
?>

Powyższy przykład wyświetli:

This (int_a) integer is considered valid (between 0 and 3).
This (int_c) integer is considered valid (between 0 and 3) and is 1.

Przykłady
Sanitization
Przykłady


Sanitization

Przykład #1 Sanitizing and validating email addresses

<?php
$a = 'joe@example.org';
$b = 'bogus - at - example dot org';
$c = '(bogus@example.org)';

$sanitized_a = filter_var($a, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (a) sanitized email address is considered valid.\n";
}

$sanitized_b = filter_var($b, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_b, FILTER_VALIDATE_EMAIL)) {
    echo "This sanitized email address is considered valid.";
} else {
    echo "This (b) sanitized email address is considered invalid.\n";
}

$sanitized_c = filter_var($c, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_c, FILTER_VALIDATE_EMAIL)) {
    echo "This (c) sanitized email address is considered valid.\n";
    echo "Before: $c\n";
    echo "After:  $sanitized_c\n";
}
?>

Powyższy przykład wyświetli:

This (a) sanitized email address is considered valid.
This (b) sanitized email address is considered invalid.
This (c) sanitized email address is considered valid.
Before: (bogus@example.org)
After: bogus@example.org

Validation
Filter Funkcje
Przykłady


Filter Funkcje

Spis treści

  • filter_has_var — Checks if variable of specified type exists
  • filter_id — Returns the filter ID belonging to a named filter
  • filter_input_array — Gets external variables and optionally filters them
  • filter_input — Gets a specific external variable by name and optionally filters it
  • filter_list — Returns a list of all supported filters
  • filter_var_array — Gets multiple variables and optionally filters them
  • filter_var — Filters a variable with a specified filter
Sanitization
filter_has_var
Filter


Checks if variable of specified type exists

Filter Funkcje
filter_id
Filter Funkcje
PHP Manual

filter_has_var

(PHP 5 >= 5.2.0)

filter_has_var — Checks if variable of specified type exists

Opis

bool filter_has_var ( int $type , string $variable_name )

Parametry

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

variable_name

Name of a variable to check.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Filter Funkcje
filter_id
Filter Funkcje


Returns the filter ID belonging to a named filter

filter_has_var
filter_input_array
Filter Funkcje
PHP Manual

filter_id

(PHP 5 >= 5.2.0)

filter_id — Returns the filter ID belonging to a named filter

Opis

int filter_id ( string $filtername )

Parametry

filtername

Name of a filter to get.

Zwracane wartości

ID of a filter on success or FALSE if filter doesn't exist.

Zobacz też:

  • filter_list() - Returns a list of all supported filters

filter_has_var
filter_input_array
Filter Funkcje


Gets external variables and optionally filters them

filter_id
filter_input
Filter Funkcje
PHP Manual

filter_input_array

(PHP 5 >= 5.2.0)

filter_input_array — Gets external variables and optionally filters them

Opis

mixed filter_input_array ( int $type [, mixed $definition ] )

This function is useful for retrieving many values without repetitively calling filter_input().

Parametry

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

definition

An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are filter which specifies the filter type, flags which specifies any flags that apply to the filter, and options which specifies any options that apply to the filter. See the example below for a better understanding.

This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

Zwracane wartości

An array containing the values of the requested variables on success, or FALSE on failure. An array value will be FALSE if the filter fails, or NULL if the variable is not set. Or if the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Przykłady

Przykład #1 A filter_input_array() example

<?php
error_reporting(E_ALL | E_STRICT);
/* data actually came from POST
$_POST = array(
    'product_id'    => 'libgd<script>',
    'component'     => '10',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',
);
*/

$args = array(
    'product_id'   => FILTER_SANITIZE_ENCODED,
    'component'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_REQUIRE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'versions'     => FILTER_SANITIZE_ENCODED,
    'doesnotexist' => FILTER_VALIDATE_INT,
    'testscalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_ARRAY,
                           )

);

$myinputs = filter_input_array(INPUT_POST, $args);

var_dump($myinputs);
echo "\n";
?>

Powyższy przykład wyświetli:

array(6) {
  ["product_id"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Notatki

Informacja:

There is no REQUEST_TIME key in INPUT_SERVER array because it is inserted into the $_SERVER later.

Zobacz też:

  • filter_input() - Gets a specific external variable by name and optionally filters it
  • filter_var_array() - Gets multiple variables and optionally filters them
  • Types of filters

filter_id
filter_input
Filter Funkcje


Gets a specific external variable by name and optionally filters it

filter_input_array
filter_list
Filter Funkcje
PHP Manual

filter_input

(PHP 5 >= 5.2.0)

filter_input — Gets a specific external variable by name and optionally filters it

Opis

mixed filter_input ( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Parametry

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

variable_name

Name of a variable to get.

filter

The ID of the filter to apply. The Types of filters manual page lists the available filters.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array.

Zwracane wartości

Value of the requested variable on success, FALSE if the filter fails, or NULL if the variable_name variable is not set. If the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Przykłady

Przykład #1 A filter_input() example

<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

Powyższy przykład wyświetli coś podobnego do:

You have searched for Me &#38; son.
<a href='?search=Me%20%26%20son'>Search again.</a>

Zobacz też:

  • filter_var() - Filters a variable with a specified filter
  • filter_input_array() - Gets external variables and optionally filters them
  • filter_var_array() - Gets multiple variables and optionally filters them
  • Types of filters

filter_input_array
filter_list
Filter Funkcje


Returns a list of all supported filters

filter_input
filter_var_array
Filter Funkcje
PHP Manual

filter_list

(PHP 5 >= 5.2.0)

filter_list — Returns a list of all supported filters

Opis

array filter_list ( void )

Zwracane wartości

Returns an array of names of all supported filters, empty array if there are no such filters. Indexes of this array are not filter IDs, they can be obtained with filter_id() from a name instead.

Przykłady

Przykład #1 A filter_list() example

<?php
print_r(filter_list());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => int
    [1] => boolean
    [2] => float
    [3] => validate_regexp
    [4] => validate_url
    [5] => validate_email
    [6] => validate_ip
    [7] => string
    [8] => stripped
    [9] => encoded
    [10] => special_chars
    [11] => unsafe_raw
    [12] => email
    [13] => url
    [14] => number_int
    [15] => number_float
    [16] => magic_quotes
    [17] => callback
)

filter_input
filter_var_array
Filter Funkcje


Gets multiple variables and optionally filters them

filter_list
filter_var
Filter Funkcje
PHP Manual

filter_var_array

(PHP 5 >= 5.2.0)

filter_var_array — Gets multiple variables and optionally filters them

Opis

mixed filter_var_array ( array $data [, mixed $definition ] )

This function is useful for retrieving many values without repetitively calling filter_var().

Parametry

data

An array with string keys containing the data to filter.

definition

An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are filter which specifies the filter type, flags which specifies any flags that apply to the filter, and options which specifies any options that apply to the filter. See the example below for a better understanding.

This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

Zwracane wartości

An array containing the values of the requested variables on success, or FALSE on failure. An array value will be FALSE if the filter fails, or NULL if the variable is not set.

Przykłady

Przykład #1 A filter_var_array() example

<?php
error_reporting(E_ALL | E_STRICT);
$data = array(
    'product_id'    => 'libgd<script>',
    'component'     => '10',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',
);

$args = array(
    'product_id'   => FILTER_SANITIZE_ENCODED,
    'component'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_FORCE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'versions'     => FILTER_SANITIZE_ENCODED,
    'doesnotexist' => FILTER_VALIDATE_INT,
    'testscalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_FORCE_ARRAY,
                           )

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);
echo "\n";
?>

Powyższy przykład wyświetli:

array(6) {
  ["product_id"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Zobacz też:

  • filter_input_array() - Gets external variables and optionally filters them
  • filter_var() - Filters a variable with a specified filter
  • filter_input() - Gets a specific external variable by name and optionally filters it
  • Types of filters

filter_list
filter_var
Filter Funkcje


Filters a variable with a specified filter

filter_var_array
Function Handling
Filter Funkcje
PHP Manual

filter_var

(PHP 5 >= 5.2.0)

filter_var — Filters a variable with a specified filter

Opis

mixed filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Parametry

variable

Value to filter.

filter

The ID of the filter to apply. The Types of filters manual page lists the available filters.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.

<?php
// for filters that accept options, use this format
$options = array(
    'options' => array(
        'default' => 3, // value to return if the filter fails
        // other options here
        'min_range' => 0
    ),
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
);
$var = filter_var('0755', FILTER_VALIDATE_INT, $options);

// for filter that only accept flags, you can pass them directly
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

// for filter that only accept flags, you can also pass as an array
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
                  array('flags' => FILTER_NULL_ON_FAILURE));

// callback validate filter
function foo($value)
{
    // Expected format: Surname, GivenNames
    if (strpos($value, ", ") === false) return false;
    list($surname, $givennames) = explode(", ", $value, 2);
    $empty = (empty($surname) || empty($givennames));
    $notstrings = (!is_string($surname) || !is_string($givennames));
    if ($empty || $notstrings) {
        return false;
    } else {
        return $value;
    }
}
$var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
?>

Zwracane wartości

Returns the filtered data, or FALSE if the filter fails.

Przykłady

Przykład #1 A filter_var() example

<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
?>

Powyższy przykład wyświetli:

string(15) "bob@example.com"
bool(false)

Zobacz też:

  • filter_var_array() - Gets multiple variables and optionally filters them
  • filter_input() - Gets a specific external variable by name and optionally filters it
  • filter_input_array() - Gets external variables and optionally filters them
  • Types of filters
  • informacje o typie callback

filter_var_array
Function Handling
Filter Funkcje


Function Handling

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Function handling Funkcje
    • call_user_func_array — Call a callback with an array of parameters
    • call_user_func — Call the callback given by the first parameter
    • create_function — Create an anonymous (lambda-style) function
    • forward_static_call_array — Call a static method and pass the arguments as array
    • forward_static_call — Call a static method
    • func_get_arg — Return an item from the argument list
    • func_get_args — Returns an array comprising a function's argument list
    • func_num_args — Returns the number of arguments passed to the function
    • function_exists — Return TRUE if the given function has been defined
    • get_defined_functions — Returns an array of all defined functions
    • register_shutdown_function — Register a function for execution on shutdown
    • register_tick_function — Register a function for execution on each tick
    • unregister_tick_function — De-register a function for execution on each tick
filter_var
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

These functions all handle various operations involved in working with functions.

Function Handling
Instalacja/Konfiguracja
Function Handling


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Function Handling


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Function handling Funkcje
Function Handling


Function handling Funkcje

Spis treści

  • call_user_func_array — Call a callback with an array of parameters
  • call_user_func — Call the callback given by the first parameter
  • create_function — Create an anonymous (lambda-style) function
  • forward_static_call_array — Call a static method and pass the arguments as array
  • forward_static_call — Call a static method
  • func_get_arg — Return an item from the argument list
  • func_get_args — Returns an array comprising a function's argument list
  • func_num_args — Returns the number of arguments passed to the function
  • function_exists — Return TRUE if the given function has been defined
  • get_defined_functions — Returns an array of all defined functions
  • register_shutdown_function — Register a function for execution on shutdown
  • register_tick_function — Register a function for execution on each tick
  • unregister_tick_function — De-register a function for execution on each tick
Stałe predefiniowane
call_user_func_array
Function Handling


Call a callback with an array of parameters

Function handling Funkcje
call_user_func
Function handling Funkcje
PHP Manual

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5)

call_user_func_array — Call a callback with an array of parameters

Opis

mixed call_user_func_array ( callback $callback , array $param_arr )

Calls the callback given by the first parameter with the parameters in param_arr.

Parametry

callback

The callback to be called.

param_arr

The parameters to be passed to the callback, as an indexed array.

Zwracane wartości

Returns the return value of the callback, or FALSE on error.

Rejestr zmian

Wersja | Opis
5.3.0 | The interpretation of object oriented keywords like parent and self has changed. Previously, calling them using the double colon syntax would emit an E_STRICT warning because they were interpreted as static.

Przykłady

Przykład #1 call_user_func_array() example

<?php
function foobar($arg, $arg2) {
    echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
    function bar($arg, $arg2) {
        echo __METHOD__, " got $arg and $arg2\n";
    }
}

// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two"));

// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>

Powyższy przykład wyświetli coś podobnego do:

foobar got one and two
foo::bar got three and four

Przykład #2 call_user_func_array() using namespace name

<?php

namespace Foobar;

class Foo {
    static public function test($name) {
        print "Hello {$name}!\n";
    }
}

// As of PHP 5.3.0
call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes'));

// As of PHP 5.3.0
call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip'));

?>

Powyższy przykład wyświetli coś podobnego do:

Hello Hannes!
Hello Philip!

Przykład #3 Using lambda function

<?php

$func = function($arg1, $arg2) {
    return $arg1 * $arg2;
};

var_dump(call_user_func_array($func, array(2, 4))); /* As of PHP 5.3.0 */

?>

Powyższy przykład wyświetli:

int(8)

Notatki

Informacja:

Referenced variables in param_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference does not emit a deprecation notice, but it is nonetheless deprecated, and will most likely be removed in the next version of PHP. Furthermore, this does not apply to internal functions, for which the function signature is honored. Passing by value when the function expects a parameter by reference results in a warning and having call_user_func() return FALSE (does not apply if the passed value has a reference count = 1).

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.

Zobacz też:

  • call_user_func() - Call the callback given by the first parameter
  • informacje o typie callback
  • ReflectionFunction::invokeArgs() - Invokes function args
  • ReflectionMethod::invokeArgs() - Invoke args

Function handling Funkcje
call_user_func
Function handling Funkcje


Call the callback given by the first parameter

call_user_func_array
create_function
Function handling Funkcje
PHP Manual

call_user_func

(PHP 4, PHP 5)

call_user_func — Call the callback given by the first parameter

Opis

mixed call_user_func ( callback $callback [, mixed $parameter [, mixed $... ]] )

Calls the callback given by the first parameter and passes the remaining parameters as arguments.

Parametry

callback

The callback to be called.

parameter

Zero or more parameters to be passed to the callback.

Informacja:

Note that the parameters for call_user_func() are not passed by reference.

Przykład #1 call_user_func() example and references

<?php
error_reporting(E_ALL);
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

call_user_func_array('increment', array(&$a)); // You can use this instead before PHP 5.3
echo $a."\n";
?>

Powyższy przykład wyświetli:

0
1

Zwracane wartości

Returns the return value of the callback, or FALSE on error.

Rejestr zmian

Wersja | Opis
5.3.0 | The interpretation of object oriented keywords like parent and self has changed. Previously, calling them using the double colon syntax would emit an E_STRICT warning because they were interpreted as static.

Przykłady

Przykład #2 call_user_func() example

<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

Powyższy przykład wyświetli:

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

Przykład #3 call_user_func() using namespace name

<?php

namespace Foobar;

class Foo {
    static public function test() {
        print "Hello world!\n";
    }
}

call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0

?>

Powyższy przykład wyświetli:

Hello world!
Hello world!

Przykład #4 Using a class method with call_user_func()

<?php

class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));

?>

Powyższy przykład wyświetli:

Hello!
Hello!
Hello!

Przykład #5 Using lambda function with call_user_func()

<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>

Powyższy przykład wyświetli:

[test]

Notatki

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.

Zobacz też:

  • call_user_func_array() - Call a callback with an array of parameters
  • is_callable() - Verify that the contents of a variable can be called as a function
  • informacje o typie callback
  • ReflectionFunction::invoke() - Invokes function
  • ReflectionMethod::invoke() - Invoke

call_user_func_array
create_function
Function handling Funkcje


Create an anonymous (lambda-style) function

call_user_func
forward_static_call_array
Function handling Funkcje
PHP Manual

create_function

(PHP 4 >= 4.0.1, PHP 5)

create_function — Create an anonymous (lambda-style) function

Opis

string create_function ( string $args , string $code )

Creates an anonymous function from the parameters passed, and returns a unique name for it.

Parametry

Usually these parameters will be passed as single quote delimited strings. 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. \$avar.

args

The function arguments.

code

The function code.

Zwracane wartości

Returns a unique function name as a string, or FALSE on error.

Przykłady

Przykład #1 Creating an anonymous function with create_function()

You can use this function, to (for example) create a function from information gathered at run time:

<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>

Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:

Przykład #2 Making a general processing function with create_function()

<?php
function process($var1, $var2, $farr)
{
    foreach ($farr as $f) {
        echo $f($var1, $var2) . "\n";
    }
}

// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// now make a bunch of string processing functions
$garr = array(
    create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
    'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
    create_function('$a,$b', '; return "CRCs: " . crc32($a) . ", ".crc32($b);'),
    create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>

Powyższy przykład wyświetli:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a)/b = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282, 342550513
similar(a,b) = 11(45.833333333333%)

But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()

Przykład #3 Using anonymous functions as callback functions

<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
print_r($av);
?>

Powyższy przykład wyświetli:

Array
(
  [0] => the mango
  [1] => a mango
  [2] => that mango
  [3] => this mango
)

an array of strings ordered from shorter to longer

<?php

$sv = array("small", "larger", "a big string", "it is a string thing");
print_r($sv);

?>

Powyższy przykład wyświetli:

Array
(
  [0] => small
  [1] => larger
  [2] => a big string
  [3] => it is a string thing
)

sort it from longer to shorter

<?php

usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);

?>

Powyższy przykład wyświetli:

Array
(
  [0] => it is a string thing
  [1] => a big string
  [2] => larger
  [3] => small
)

Zobacz też:

  • Anonymous functions

call_user_func
forward_static_call_array
Function handling Funkcje


Call a static method and pass the arguments as array

create_function
forward_static_call
Function handling Funkcje
PHP Manual

forward_static_call_array

(PHP 5 >= 5.3.0)

forward_static_call_array — Call a static method and pass the arguments as array

Opis

mixed forward_static_call_array ( callback $function , array $parameters )

Calls a user defined function or method given by the function parameter. This function must be called within a method context, it can't be used outside a class. It uses the late static binding. All arguments of the forwarded method are passed as values, and as an array, similarly to call_user_func_array().

Parametry

function

The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name.

parameter

One parameter, gathering all the method parameter in one array.

Informacja:

Note that the parameters for forward_static_call_array() are not passed by reference.

Zwracane wartości

Returns the function result, or FALSE on error.

Przykłady

Przykład #1 forward_static_call_array() example

<?php

class A
{
    const NAME = 'A';
    public static function test() {
        $args = func_get_args();
        echo static::NAME, " ".join(',', $args)." \n";
    }
}

class B extends A
{
    const NAME = 'B';

    public static function test() {
        echo self::NAME, "\n";
        forward_static_call_array(array('A', 'test'), array('more', 'args'));
        forward_static_call_array( 'test', array('other', 'args'));
    }
}

B::test('foo');

function test() {
        $args = func_get_args();
        echo "C ".join(',', $args)." \n";
    }

?>

Powyższy przykład wyświetli:

B
B more,args
C other,args

Zobacz też:

  • forward_static_call() - Call a static method
  • call_user_func() - Call the callback given by the first parameter
  • call_user_func_array() - Call a callback with an array of parameters
  • is_callable() - Verify that the contents of a variable can be called as a function
  • informacje o typie callback

create_function
forward_static_call
Function handling Funkcje


Call a static method

forward_static_call_array
func_get_arg
Function handling Funkcje
PHP Manual

forward_static_call

(PHP 5 >= 5.3.0)

forward_static_call — Call a static method

Opis

mixed forward_static_call ( callback $function [, mixed $parameter [, mixed $... ]] )

Calls a user defined function or method given by the function parameter, with the following arguments. This function must be called within a method context, it can't be used outside a class. It uses the late static binding.

Parametry

function

The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name.

parameter

Zero or more parameters to be passed to the function.

Zwracane wartości

Returns the function result, or FALSE on error.

Przykłady

Przykład #1 forward_static_call() example

<?php

class A
{
    const NAME = 'A';
    public static function test() {
        $args = func_get_args();
        echo static::NAME, " ".join(',', $args)." \n";
    }
}

class B extends A
{
    const NAME = 'B';

    public static function test() {
        echo self::NAME, "\n";
        forward_static_call(array('A', 'test'), 'more', 'args');
        forward_static_call( 'test', 'other', 'args');
    }
}

B::test('foo');

function test() {
        $args = func_get_args();
        echo "C ".join(',', $args)." \n";
    }

?>

Powyższy przykład wyświetli:

B
B more,args
C other,args

Zobacz też:

  • forward_static_call_array() - Call a static method and pass the arguments as array
  • call_user_func_array() - Call a callback with an array of parameters
  • call_user_func() - Call the callback given by the first parameter
  • is_callable() - Verify that the contents of a variable can be called as a function
  • informacje o typie callback

forward_static_call_array
func_get_arg
Function handling Funkcje


Return an item from the argument list

forward_static_call
func_get_args
Function handling Funkcje
PHP Manual

func_get_arg

(PHP 4, PHP 5)

func_get_arg — Return an item from the argument list

Opis

mixed func_get_arg ( int $arg_num )

Gets the specified argument from a user-defined function's argument list.

This function may be used in conjunction with func_get_args() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

Parametry

arg_num

The argument offset. Function arguments are counted starting from zero.

Zwracane wartości

Returns the specified argument, or FALSE on error.

Rejestr zmian

Wersja | Opis
5.3.0 | This function can now be used in parameter lists.
5.3.0 | If this function is called from the outermost scope of a file which has been included by calling include() or require() from within a function in the calling file, it now generates a warning and returns FALSE.

Błędy/Wyjątki

Generates a warning if called from outside of a user-defined function, or if arg_num is greater than the number of arguments actually passed.

Przykłady

Przykład #1 func_get_arg() example

<?php
function foo()
{
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br />\n";
     if ($numargs >= 2) {
         echo "Second argument is: " . func_get_arg(1) . "<br />\n";
     }
}

foo (1, 2, 3);
?>

Przykład #2 func_get_arg() example before and after PHP 5.3

test.php
<?php
function foo() {
    include './fga.inc';
}

foo('First arg', 'Second arg');
?>

fga.php
<?php

$arg = func_get_arg(1);
var_export($arg);

?>

Output previous to PHP 5.3:

'Second arg'

Output in PHP 5.3 and later:

Warning: func_get_arg():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Przykład #3 func_get_arg() example of byref and byval arguments

<?php
function byVal($arg) {
    echo 'As passed     : ', var_export(func_get_arg(0)), PHP_EOL;
    $arg = 'baz';
    echo 'After change  : ', var_export(func_get_arg(0)), PHP_EOL;
}

function byRef(&$arg) {
    echo 'As passed     : ', var_export(func_get_arg(0)), PHP_EOL;
    $arg = 'baz';
    echo 'After change  : ', var_export(func_get_arg(0)), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

Powyższy przykład wyświetli:

As passed : 'bar'
After change : 'bar'
As passed : 'bar'
After change : 'baz'

Notatki

Informacja:

Jako że działanie tej funkcji zależy od aktualnego zasięgu, nie może ona być użyta jako parametr funkcji w wersjach przed PHP 5.3.0. Jeśli konieczne jest przekazanie tej wartości, należy przypisać wynik działania tej funkcji do zmiennej, a następnie przekazać tę zmienną jako parametr.

Informacja:

Jeśli argumenty są przekazane przez referencję, wszystkie zmiany na argumentach będą miały odzwierciedlenie w wartościach zwracanych przez tę funkcję

Informacja: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

Zobacz też:

  • func_get_args() - Returns an array comprising a function's argument list
  • func_num_args() - Returns the number of arguments passed to the function

forward_static_call
func_get_args
Function handling Funkcje


Returns an array comprising a function's argument list

func_get_arg
func_num_args
Function handling Funkcje
PHP Manual

func_get_args

(PHP 4, PHP 5)

func_get_args — Returns an array comprising a function's argument list

Opis

array func_get_args ( void )

Gets an array of the function's argument list.

This function may be used in conjunction with func_get_arg() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

Zwracane wartości

Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list.

Rejestr zmian

Wersja | Opis
5.3.0 | This function can now be used in parameter lists.
5.3.0 | If this function is called from the outermost scope of a file which has been included by calling include() or require() from within a function in the calling file, it now generates a warning and returns FALSE.

Błędy/Wyjątki

Generates a warning if called from outside of a user-defined function.

Przykłady

Przykład #1 func_get_args() example

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}

foo(1, 2, 3);
?>

Powyższy przykład wyświetli:

Number of arguments: 3<br />
Second argument is: 2<br />
Argument 0 is: 1<br />
Argument 1 is: 2<br />
Argument 2 is: 3<br />

Przykład #2 func_get_args() example before and after PHP 5.3

test.php
<?php
function foo() {
    include './fga.inc';
}

foo('First arg', 'Second arg');
?>

fga.inc
<?php

$args = func_get_args();
var_export($args);

?>

Output previous to PHP 5.3:

array (
  0 => 'First arg',
  1 => 'Second arg',
)

Output in PHP 5.3 and later:

Warning: func_get_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Przykład #3 func_get_args() example of byref and byval arguments

<?php
function byVal($arg) {
    echo 'As passed     : ', var_export(func_get_args()), PHP_EOL;
    $arg = 'baz';
    echo 'After change  : ', var_export(func_get_args()), PHP_EOL;
}

function byRef(&$arg) {
    echo 'As passed     : ', var_export(func_get_args()), PHP_EOL;
    $arg = 'baz';
    echo 'After change  : ', var_export(func_get_args()), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

Powyższy przykład wyświetli:

As passed : array (
0 => 'bar',
)
After change : array (
0 => 'bar',
)
As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)

Notatki

Informacja:

Jako że działanie tej funkcji zależy od aktualnego zasięgu, nie może ona być użyta jako parametr funkcji w wersjach przed PHP 5.3.0. Jeśli konieczne jest przekazanie tej wartości, należy przypisać wynik działania tej funkcji do zmiennej, a następnie przekazać tę zmienną jako parametr.

Informacja:

Jeśli argumenty są przekazane przez referencję, wszystkie zmiany na argumentach będą miały odzwierciedlenie w wartościach zwracanych przez tę funkcję

Informacja: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

Zobacz też:

  • func_get_arg() - Return an item from the argument list
  • func_num_args() - Returns the number of arguments passed to the function
  • ReflectionFunctionAbstract::getParameters() - Gets parameters

func_get_arg
func_num_args
Function handling Funkcje


Returns the number of arguments passed to the function

func_get_args
function_exists
Function handling Funkcje
PHP Manual

func_num_args

(PHP 4, PHP 5)

func_num_args — Returns the number of arguments passed to the function

Opis

int func_num_args ( void )

Gets the number of arguments passed to the function.

This function may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

Zwracane wartości

Returns the number of arguments passed into the current user-defined function.

Rejestr zmian

Wersja | Opis
5.3.0 | This function can now be used in parameter lists.
5.3.0 | If this function is called from the outermost scope of a file which has been included by calling include() or require() from within a function in the calling file, it now generates a warning and returns -1.

Błędy/Wyjątki

Generates a warning if called from outside of a user-defined function.

Przykłady

Przykład #1 func_num_args() example

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
}

foo(1, 2, 3);
?>

Powyższy przykład wyświetli:

Number of arguments: 3

Przykład #2 func_num_args() example before and after PHP 5.3

test.php
<?php
function foo() {
    include './fna.php';
}

foo('First arg', 'Second arg');
?>

fna.php
<?php

$num_args = func_num_args();
var_export($num_args);

?>

Output previous to PHP 5.3:

2

Output in PHP 5.3 and later will be something similar to:

Warning: func_num_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fna.php on line 3
-1

Notatki

Informacja:

Jako że działanie tej funkcji zależy od aktualnego zasięgu, nie może ona być użyta jako parametr funkcji w wersjach przed PHP 5.3.0. Jeśli konieczne jest przekazanie tej wartości, należy przypisać wynik działania tej funkcji do zmiennej, a następnie przekazać tę zmienną jako parametr.

Zobacz też:

  • func_get_arg() - Return an item from the argument list
  • func_get_args() - Returns an array comprising a function's argument list
  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters

func_get_args
function_exists
Function handling Funkcje


Return TRUE if the given function has been defined

func_num_args
get_defined_functions
Function handling Funkcje
PHP Manual

function_exists

(PHP 4, PHP 5)

function_exists — Return TRUE if the given function has been defined

Opis

bool function_exists ( string $function_name )

Checks the list of defined functions, both built-in (internal) and user-defined, for function_name.

Parametry

function_name

The function name, as a string.

Zwracane wartości

Returns TRUE if function_name exists and is a function, FALSE otherwise.

Informacja:

This function will return FALSE for constructs, such as include_once() and echo().

Przykłady

Przykład #1 function_exists() example

<?php
if (function_exists('imap_open')) {
    echo "IMAP functions are available.<br />\n";
} else {
    echo "IMAP functions are not available.<br />\n";
}
?>

Notatki

Informacja:

A function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example).

Zobacz też:

  • method_exists() - Sprawdza czy metoda klasy istnieje
  • is_callable() - Verify that the contents of a variable can be called as a function
  • get_defined_functions() - Returns an array of all defined functions
  • class_exists() - Sprawdza, czy klasa została zdefiniowana
  • extension_loaded() - Find out whether an extension is loaded

func_num_args
get_defined_functions
Function handling Funkcje


Returns an array of all defined functions

function_exists
register_shutdown_function
Function handling Funkcje
PHP Manual

get_defined_functions

(PHP 4 >= 4.0.4, PHP 5)

get_defined_functions — Returns an array of all defined functions

Opis

array get_defined_functions ( void )

Gets an array of all defined functions.

Zwracane wartości

Returns an multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).

Przykłady

Przykład #1 get_defined_functions() example

<?php
function myrow($id, $data)
{
    return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
            [2] => func_get_arg
            [3] => func_get_args
            [4] => strlen
            [5] => strcmp
            [6] => strncmp
            ...
            [750] => bcscale
            [751] => bccomp
        )

    [user] => Array
        (
            [0] => myrow
        )

)

Zobacz też:

  • function_exists() - Return TRUE if the given function has been defined
  • get_defined_vars() - Returns an array of all defined variables
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values
  • get_declared_classes() - Zwraca tablicę z nazwami zdefiniowanych klas

function_exists
register_shutdown_function
Function handling Funkcje


Register a function for execution on shutdown

get_defined_functions
register_tick_function
Function handling Funkcje
PHP Manual

register_shutdown_function

(PHP 4, PHP 5)

register_shutdown_function — Register a function for execution on shutdown

Opis

void register_shutdown_function ( callback $callback [, mixed $parameter [, mixed $... ]] )

Registers a callback to be executed after script execution finishes or exit() is called.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

Parametry

callback

The shutdown callback to register.

The shutdown callbacks are executed as the part of the request, so it's possible to send output from them and access output buffers.

parameter

It is possible to pass parameters to the shutdown function by passing additional parameters.

...

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

If the passed callback is not callable a E_WARNING level error will be generated.

Rejestr zmian

Wersja | Opis
4.1.0 | The shutdown functions are now called as a part of the request. In earlier versions under Apache, the registered shutdown functions were called after the request has been completed (including sending any output buffers), so it was not possible to send output to the browser using echo() or print(), or retrieve the contents of any output buffers using ob_get_contents(). Headers were also always already sent.

Przykłady

Przykład #1 register_shutdown_function() example

<?php
function shutdown()
{
    // This is our shutdown function, in
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>

Notatki

Informacja:

Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.

Zobacz też:

  • auto_append_file
  • exit() - Output a message and terminate the current script
  • The section on connection handling

get_defined_functions
register_tick_function
Function handling Funkcje


Register a function for execution on each tick

register_shutdown_function
unregister_tick_function
Function handling Funkcje
PHP Manual

register_tick_function

(PHP 4 >= 4.0.3, PHP 5)

register_tick_function — Register a function for execution on each tick

Opis

bool register_tick_function ( callback $function [, mixed $arg [, mixed $... ]] )

Registers the given function to be executed when a tick is called.

Parametry

function

The function name as a string, or an array consisting of an object and a method.

arg

...

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 register_tick_function() example

<?php
declare(ticks=1);

// using a function as the callback
register_tick_function('my_function', true);

// using an object->method
$object = new my_class();
register_tick_function(array(&$object, 'my_method'), true);
?>

Rejestr zmian

Wersja | Opis
5.3.0 | Ticks are now supported on threaded web server modules.

Notatki

Ostrzeżenie

register_tick_function() should not be used with threaded web server modules with PHP 5.2 or lower.

Zobacz też:

  • declare
  • unregister_tick_function() - De-register a function for execution on each tick

register_shutdown_function
unregister_tick_function
Function handling Funkcje


De-register a function for execution on each tick

register_tick_function
Object Aggregation
Function handling Funkcje
PHP Manual

unregister_tick_function

(PHP 4 >= 4.0.3, PHP 5)

unregister_tick_function — De-register a function for execution on each tick

Opis

void unregister_tick_function ( string $function_name )

De-registers the function named by function_name so it is no longer executed when a tick is called.

Parametry

function_name

The function name, as a string.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • register_tick_function() - Register a function for execution on each tick

register_tick_function
Object Aggregation
Function handling Funkcje


Object Aggregation/Composition [PHP 4]

  • Wstęp
  • Przykłady
    • Object Aggregation examples
    • Przykłady
  • Object Aggregation Funkcje
    • aggregate_info — Gets aggregation information for a given object
    • aggregate_methods_by_list — Selective dynamic class methods aggregation to an object
    • aggregate_methods_by_regexp — Selective class methods aggregation to an object using a regular expression
    • aggregate_methods — Dynamic class and object aggregation of methods
    • aggregate_properties_by_list — Selective dynamic class properties aggregation to an object
    • aggregate_properties_by_regexp — Selective class properties aggregation to an object using a regular expression
    • aggregate_properties — Dynamic aggregation of class properties to an object
    • aggregate — Dynamic class and object aggregation of methods and properties
    • aggregation_info — Alias dla aggregate_info
    • deaggregate — Removes the aggregated methods and properties from an object
unregister_tick_function
Wstęp
Zmienne i typy powiązanych rozszerzeń


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.

In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierarchies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.

Object Aggregation
Przykłady
Object Aggregation


Przykłady

Spis treści

  • Object Aggregation examples
  • Przykłady
Wstęp
Object Aggregation examples
Object Aggregation


Object Aggregation examples

An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:

Przykład #1 Class association

<?php
class MyDateTime {

  function MyDateTime()
  {
      // empty constructor
  }

  function now()
  {
      return date("Y-m-d H:i:s");
  }
}

class Report {
  var $_dt;
  // more properties ...

  function Report()
  {
      $this->_dt = new MyDateTime();
      // initialization code ...
  }

  function generateReport()
  {
      $dateTime = $this->_dt->now();
      // more code ...
  }

  // more methods ...
}

$rep = new Report();
?>
We can also associate instances at runtime by passing a reference in a constructor (or any other method), which allow us to dynamically change the association relationship between objects. We will modify the example above to illustrate this point:

Przykład #2 Object association

<?php
class MyDateTime {
  // same as previous example
}

class MyDateTimePlus {
  var $_format;

  function MyDateTimePlus($format="Y-m-d H:i:s")
  {
      $this->_format = $format;
  }

  function now()
  {
      return date($this->_format);
  }
}

class Report {
  var $_dt;    // we'll keep the reference to MyDateTime here
  // more properties ...

  function Report()
  {
      // do some initialization
  }

  function setMyDateTime(&$dt)
  {
      $this->_dt =& $dt;
  }

  function generateReport()
  {
      $dateTime = $this->_dt->now();
      // more code ...
  }

  // more methods ...
}

$rep = new Report();
$dt = new MyDateTime();
$dtp = new MyDateTimePlus("l, F j, Y (h:i:s a, T)");

// generate report with simple date for web display
$rep->setMyDateTime($dt);
echo $rep->generateReport();

// later on in the code ...

// generate report with fancy date
$rep->setMyDateTime($dtp);
$output = $rep->generateReport();
// save $output in database
// ... etc ...
?>

Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.

Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.

Przykłady
Przykłady
Przykłady


Przykłady
PHP Manual

Przykłady

We define 3 classes, each implementing a different storage method:

Przykład #1 storage_classes.inc

<?php
class FileStorage {
   var $data;

   function FileStorage($data)
   {
       $this->data = $data;
   }

   function write($name)
   {
       $fp = fopen(name, "w");
       fwrite($fp, $this->data);
       fclose($data);
   }
}

class WDDXStorage {
   var $data;
   var $version = "1.0";
   var $_id; // "private" variable

   function WDDXStorage($data)
   {
       $this->data = $data;
       $this->_id = $this->_genID();
   }

   function store()
   {
       if ($this->_id) {
           $pid = wddx_packet_start($this->_id);
           wddx_add_vars($pid, "this->data");
           $packet = wddx_packet_end($pid);
       } else {
           $packet = wddx_serialize_value($this->data);
       }
       $dbh = dba_open("varstore", "w", "gdbm");
       dba_insert(md5(uniqid("", true)), $packet, $dbh);
       dba_close($dbh);
   }

   // a private method
   function _genID()
   {
       return md5(uniqid(rand(), true));
   }
}

class DBStorage {
   var $data;
   var $dbtype = "mysql";

   function DBStorage($data)
   {
       $this->data = $data;
   }

   function save()
   {
       $dbh = mysql_connect();
       mysql_select_db("storage", $dbh);
       $serdata = serialize($this->data);
       mysql_query("insert into vars ('$serdata',now())", $dbh);
       mysql_close($dbh);
   }
}

?>

We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:

Przykład #2 test_aggregation.php

<?php
include "storageclasses.inc";

// some utilty functions

function p_arr($arr)
{
   foreach ($arr as $k => $v)
       $out[] = "\t$k => $v";
   return implode("\n", $out);
}

function object_info($obj)
{
   $out[] = "Class: " . get_class($obj);
   foreach (get_object_vars($obj) as $var=>$val) {
       if (is_array($val)) {
           $out[] = "property: $var (array)\n" . p_arr($val);
       } else {
           $out[] = "property: $var = $val";
       }
   }
   foreach (get_class_methods($obj) as $method) {
       $out[] = "method: $method";
   }
   return implode("\n", $out);
}

$data = array(M_PI, "kludge != cruft");

// we create some basic objects
$fs = new FileStorage($data);
$ws = new WDDXStorage($data);

// print information on the objects
echo "\$fs object\n";
echo object_info($fs) . "\n";
echo "\n\$ws object\n";
echo object_info($ws) . "\n";

// do some aggregation

echo "\nLet's aggregate \$fs to the WDDXStorage class\n";
aggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nNow let us aggregate it to the DBStorage class\n";
aggregate($fs, "DBStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

echo "\nAnd finally deaggregate WDDXStorage\n";
deaggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs) . "\n";

?>

We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.

$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
method: filestorage
method: write

$ws object
Class: wddxstorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
property: _id = ID::9bb2b640764d4370eb04808af8b076a5
method: wddxstorage
method: store
method: _genid

We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.

Let's aggregate $fs to the WDDXStorage class
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
method: filestorage
method: write
method: store

The process of aggregation is cumulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.

Now let us aggregate it to the DBStorage class
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
property: dbtype = mysql
method: filestorage
method: write
method: store
method: save

Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:

And deaggregate the WDDXStorage methods and properties
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: dbtype = mysql
method: filestorage
method: write
method: save

One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.

Object Aggregation examples
Object Aggregation Funkcje
Przykłady
PHP Manual


Object Aggregation Funkcje

Spis treści

  • aggregate_info — Gets aggregation information for a given object
  • aggregate_methods_by_list — Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp — Selective class methods aggregation to an object using a regular expression
  • aggregate_methods — Dynamic class and object aggregation of methods
  • aggregate_properties_by_list — Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp — Selective class properties aggregation to an object using a regular expression
  • aggregate_properties — Dynamic aggregation of class properties to an object
  • aggregate — Dynamic class and object aggregation of methods and properties
  • aggregation_info — Alias dla aggregate_info
  • deaggregate — Removes the aggregated methods and properties from an object
Przykłady
aggregate_info
Object Aggregation


Gets aggregation information for a given object

Object Aggregation Funkcje
aggregate_methods_by_list
Object Aggregation Funkcje
PHP Manual

aggregate_info

(PHP 4 >= 4.3.0)

aggregate_info — Gets aggregation information for a given object

Opis

array aggregate_info ( object $object )

Gets the aggregation information for the given object.

Parametry

object

Zwracane wartości

Returns the aggregation information as an associative array of arrays of methods and properties. The key for the main array is the name of the aggregated class.

Przykłady

Przykład #1 Using aggregate_info()

<?php

class Slicer {
    var $vegetable;

    function Slicer($vegetable)
    {
        $this->vegetable = $vegetable;
    }

    function slice_it($num_cuts)
    {
        echo "Doing some simple slicing\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some slicing
        }
    }
}

class Dicer {
    var $vegetable;
    var $rotation_angle = 90;   // degrees

    function Dicer($vegetable)
    {
        $this->vegetable = $vegetable;
    }

    function dice_it($num_cuts)
    {
        echo "Cutting in one direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some cutting
        }
        $this->rotate($this->rotation_angle);
        echo "Cutting in a second direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some more cutting
        }
    }

    function rotate($deg)
    {
        echo "Now rotating {$this->vegetable} {$deg} degrees\n";
    }

    function _secret_super_dicing($num_cuts)
    {
        // so secret we cannot show you ;-)
    }
}

$obj = new Slicer('onion');
aggregate($obj, 'Dicer');
print_r(aggregate_info($obj));
?>

Powyższy przykład wyświetli:

Array
(
    [dicer] => Array
        (
            [methods] => Array
                (
                    [0] => dice_it
                    [1] => rotate
                )

            [properties] => Array
                (
                    [0] => rotation_angle
                )

        )

)
As you can see, all properties and methods of the Dicer class have been aggregated into our new object, with the exception of the class constructor and the method _secret_super_dicing()

Zobacz też:

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

Object Aggregation Funkcje
aggregate_methods_by_list
Object Aggregation Funkcje


Selective dynamic class methods aggregation to an object

aggregate_info
aggregate_methods_by_regexp
Object Aggregation Funkcje
PHP Manual

aggregate_methods_by_list

(PHP 4 >= 4.2.0)

aggregate_methods_by_list — Selective dynamic class methods aggregation to an object

Opis

void aggregate_methods_by_list ( object $object , string $class_name , array $methods_list [, bool $exclude = false ] )

Aggregates methods from a class to an existing object using a list of method names.

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

Parametry

object

class_name

methods_list

exclude

The optional parameter exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE), or to exclude from the aggregation (exclude is TRUE).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_info() - Gets aggregation information for a given object
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

aggregate_info
aggregate_methods_by_regexp
Object Aggregation Funkcje


Selective class methods aggregation to an object using a regular expression

aggregate_methods_by_list
aggregate_methods
Object Aggregation Funkcje
PHP Manual

aggregate_methods_by_regexp

(PHP 4 >= 4.2.0)

aggregate_methods_by_regexp — Selective class methods aggregation to an object using a regular expression

Opis

void aggregate_methods_by_regexp ( object $object , string $class_name , string $regexp [, bool $exclude = false ] )

Aggregates methods from a class to an existing object using a regular expression to match method names.

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

Parametry

object

class_name

regexp

exclude

The optional parameter exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE), or to exclude from the aggregation (exclude is TRUE).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_info() - Gets aggregation information for a given object
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

aggregate_methods_by_list
aggregate_methods
Object Aggregation Funkcje


Dynamic class and object aggregation of methods

aggregate_methods_by_regexp
aggregate_properties_by_list
Object Aggregation Funkcje
PHP Manual

aggregate_methods

(PHP 4 >= 4.2.0)

aggregate_methods — Dynamic class and object aggregation of methods

Opis

void aggregate_methods ( object $object , string $class_name )

Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.

Parametry

object

class_name

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_info() - Gets aggregation information for a given object
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

aggregate_methods_by_regexp
aggregate_properties_by_list
Object Aggregation Funkcje


Selective dynamic class properties aggregation to an object

aggregate_methods
aggregate_properties_by_regexp
Object Aggregation Funkcje
PHP Manual

aggregate_properties_by_list

(PHP 4 >= 4.2.0)

aggregate_properties_by_list — Selective dynamic class properties aggregation to an object

Opis

void aggregate_properties_by_list ( object $object , string $class_name , array $properties_list [, bool $exclude = false ] )

Aggregates properties from a class to an existing object using a list of property names.

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

Parametry

object

class_name

properties_list

exclude

The optional parameter exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE), or to exclude from the aggregation (exclude is TRUE).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • aggregate_info() - Gets aggregation information for a given object
  • deaggregate() - Removes the aggregated methods and properties from an object

aggregate_methods
aggregate_properties_by_regexp
Object Aggregation Funkcje


Selective class properties aggregation to an object using a regular expression

aggregate_properties_by_list
aggregate_properties
Object Aggregation Funkcje
PHP Manual

aggregate_properties_by_regexp

(PHP 4 >= 4.2.0)

aggregate_properties_by_regexp — Selective class properties aggregation to an object using a regular expression

Opis

void aggregate_properties_by_regexp ( object $object , string $class_name , string $regexp [, bool $exclude = false ] )

Aggregates properties from a class to an existing object using a regular expression to match their names.

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

Parametry

object

class_name

regexp

exclude

The optional parameter exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE), or to exclude from the aggregation (exclude is TRUE).

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_info() - Gets aggregation information for a given object
  • deaggregate() - Removes the aggregated methods and properties from an object

aggregate_properties_by_list
aggregate_properties
Object Aggregation Funkcje


Dynamic aggregation of class properties to an object

aggregate_properties_by_regexp
aggregate
Object Aggregation Funkcje
PHP Manual

aggregate_properties

(PHP 4 >= 4.2.0)

aggregate_properties — Dynamic aggregation of class properties to an object

Opis

void aggregate_properties ( object $object , string $class_name )

Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.

Parametry

object

class_name

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties()
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

aggregate_properties_by_regexp
aggregate
Object Aggregation Funkcje


Dynamic class and object aggregation of methods and properties

aggregate_properties
aggregation_info
Object Aggregation Funkcje
PHP Manual

aggregate

(PHP 4 >= 4.2.0)

aggregate — Dynamic class and object aggregation of methods and properties

Opis

void aggregate ( object $object , string $class_name )

Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.

Parametry

object

class_name

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • aggregate_info() - Gets aggregation information for a given object
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate() - Removes the aggregated methods and properties from an object

aggregate_properties
aggregation_info
Object Aggregation Funkcje


Alias dla aggregate_info

aggregate
deaggregate
Object Aggregation Funkcje
PHP Manual

aggregation_info

(PHP 4 >= 4.2.0 and < 4.3.0)

aggregation_info — Alias dla aggregate_info()

Opis

Ta funkcja jest aliasem dla: aggregate_info().

aggregate
deaggregate
Object Aggregation Funkcje


Removes the aggregated methods and properties from an object

aggregation_info
Quickhash
Object Aggregation Funkcje
PHP Manual

deaggregate

(PHP 4 >= 4.2.0)

deaggregate — Removes the aggregated methods and properties from an object

Opis

void deaggregate ( object $object [, string $class_name ] )

Removes the methods and properties from classes that were aggregated to an object.

Parametry

object

class_name

If the optional class_name parameters is passed, only those methods and properties defined in that class are removed, otherwise all aggregated methods and properties are eliminated.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • aggregate() - Dynamic class and object aggregation of methods and properties
  • aggregate_methods() - Dynamic class and object aggregation of methods
  • aggregate_methods_by_list() - Selective dynamic class methods aggregation to an object
  • aggregate_methods_by_regexp() - Selective class methods aggregation to an object using a regular expression
  • aggregate_properties() - Dynamic aggregation of class properties to an object
  • aggregate_properties_by_list() - Selective dynamic class properties aggregation to an object
  • aggregate_properties_by_regexp() - Selective class properties aggregation to an object using a regular expression
  • deaggregate()

aggregation_info
Quickhash
Object Aggregation Funkcje


Quickhash

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
  • Stałe predefiniowane
  • Przykłady
  • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntSet::add — This method adds a new entry to the set
    • QuickHashIntSet::__construct — Creates a new QuickHashIntSet object
    • QuickHashIntSet::delete — This method deletes an entry from the set
    • QuickHashIntSet::exists — This method checks whether a key is part of the set
    • QuickHashIntSet::getSize — Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile — This factory method creates a set from a file
    • QuickHashIntSet::loadFromString — This factory method creates a set from a string
    • QuickHashIntSet::saveToFile — This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString — This method returns a serialized version of the set
  • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashIntHash::add — This method adds a new entry to the hash
    • QuickHashIntHash::__construct — Creates a new QuickHashIntHash object
    • QuickHashIntHash::delete — This method deletes am entry from the hash
    • QuickHashIntHash::exists — This method checks whether a key is part of the hash
    • QuickHashIntHash::get — This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize — Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString — This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString — This method returns a serialized version of the hash
    • QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update — This method updates an entry in the hash with a new value
  • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashStringIntHash::add — This method adds a new entry to the hash
    • QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object
    • QuickHashStringIntHash::delete — This method deletes am entry from the hash
    • QuickHashStringIntHash::exists — This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize — Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash
    • QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update — This method updates an entry in the hash with a new value
  • QuickHashIntStringHash — The QuickHashIntStringHash class
    • QuickHashIntStringHash::add — This method adds a new entry to the hash
    • QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object
    • QuickHashIntStringHash::delete — This method deletes am entry from the hash
    • QuickHashIntStringHash::exists — This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get — This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize — Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash
    • QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update — This method updates an entry in the hash with a new value
deaggregate
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

The quickhash extension contains a set of specific strongly-typed classes to deal with specific set and hash implementations.

Quickhash
Instalacja/Konfiguracja
Quickhash


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
Wstęp
Wymagania
Quickhash


Wymagania

This extension requires no additional libraries.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/quickhash

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Konfiguracja wykonawcza
Przykłady
Quickhash


Przykłady

Przykład #1 Quickhash Example

<?php
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
$set->add( 1 );
$set->add( 3 );

var_dump( $set->exists( 3 ) );
var_dump( $set->exists( 4 ) );

$set->saveToFile( "/tmp/test-set.set" );

$newSet = QuickHashIntSet::loadFromFile(
    "/tmp/test-set.set"
);

var_dump( $newSet->exists( 3 ) );
var_dump( $newSet->exists( 4 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(false)
bool(true)
bool(false)

Przykład #2 Quickhash ArrayAccess Example

<?php
$hash = new QuickHashIntHash( 64 );

// Adding and updating hash entries.
$hash[3] = 145926;
$hash[3] = 1415926;
$hash[2] = 72;

// Checking if keys exist
var_dump( isset( $hash[3] ) );

// Removing hash entries
unset( $hash[2] );

// Retrieving the value stored for a hash
echo $hash[3], "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
1415926

Przykład #3 Quickhash Iterator Example

<?php
$hash = new QuickHashIntHash( 64 );

// Adding hash entries.
$hash[1] = 145926;
$hash[2] = 1415926;
$hash[3] = 72;
$hash[4] = 712314;
$hash[5] = -4234;

foreach( $hash as $key => $value )
{
    echo $key, ' => ', $value, "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

5 => -4234
4 => 712314
1 => 145926
2 => 1415926
3 => 72

Przykład #4 Quickhash String Values Example

<?php
$hash = new QuickHashIntStringHash( 64 );

// Adding hash entries.
$hash[1] = "one million four hundred fifteen thousand nine hundred twenty six";
$hash->add( 2, "one more" );1415926;

foreach( $hash as $key => $value )
{
    echo $key, ' => ', $value, "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

1 => one million four hundred fifteen thousand nine hundred twenty six
2 => one more
Stałe predefiniowane
QuickHashIntSet
Quickhash


The QuickHashIntSet class

(No version information available, might only be in SVN)

Wstęp

This class wraps around a set containing integer numbers.

Sets can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Krótki opis klasy

QuickHashIntSet {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public bool add ( int $key )
public __construct ( int $size [, int $options ] )
public bool delete ( int $key )
public bool exists ( int $key )
publicint getSize ( void )
public static QuickHashIntSet loadFromFile ( string $filename [, int $size [, int $options ]] )
public static QuickHashIntSet loadFromString ( string $contents [, int $size [, int $options ]] )
public void saveToFile ( string $filename )
public string saveToString ( void )
}

Stałe predefiniowane

QuickHashIntSet::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntSet::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntSet::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntSet::HASHER_JENKINS2

Selects a variant hashing algorithm.

Spis treści

  • QuickHashIntSet::add — This method adds a new entry to the set
  • QuickHashIntSet::__construct — Creates a new QuickHashIntSet object
  • QuickHashIntSet::delete — This method deletes an entry from the set
  • QuickHashIntSet::exists — This method checks whether a key is part of the set
  • QuickHashIntSet::getSize — Returns the number of elements in the set
  • QuickHashIntSet::loadFromFile — This factory method creates a set from a file
  • QuickHashIntSet::loadFromString — This factory method creates a set from a string
  • QuickHashIntSet::saveToFile — This method stores an in-memory set to disk
  • QuickHashIntSet::saveToString — This method returns a serialized version of the set
Przykłady
QuickHashIntSet::add
Quickhash


This method adds a new entry to the set

QuickHashIntSet
QuickHashIntSet::__construct
QuickHashIntSet
PHP Manual

QuickHashIntSet::add

(PECL quickhash >= Unknown)

QuickHashIntSet::add — This method adds a new entry to the set

Opis

public bool QuickHashIntSet::add ( int $key )

This method adds a new entry to the set, and returns whether the entry was added. Entries are by default always added unless QuickHashIntSet::CHECK_FOR_DUPES has been passed when the set was created.

Parametry

key

The key of the entry to add.

Zwracane wartości

TRUE when the entry was added, and FALSE if the entry was not added.

Przykłady

Przykład #1 QuickHashIntSet::add() example

<?php
echo "without dupe checking\n";
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

echo "\nwith dupe checking\n";
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

without dupe checking
bool(false)
bool(true)
bool(true)
bool(true)

with dupe checking
bool(false)
bool(true)
bool(true)
bool(false)

QuickHashIntSet
QuickHashIntSet::__construct
QuickHashIntSet


Creates a new QuickHashIntSet object

QuickHashIntSet::add
QuickHashIntSet::delete
QuickHashIntSet
PHP Manual

QuickHashIntSet::__construct

(PECL quickhash >= Unknown)

QuickHashIntSet::__construct — Creates a new QuickHashIntSet object

Opis

public QuickHashIntSet::__construct ( int $size [, int $options ] )

This constructor creates a new QuickHashIntSet. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Parametry

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The options that you can pass in are: QuickHashIntSet::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the set; QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntSet::HASHER_NO_HASH, QuickHashIntSet::HASHER_JENKINS1 or QuickHashIntSet::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Zwracane wartości

Returns a new QuickHashIntSet object.

Przykłady

Przykład #1 QuickHashIntSet::__construct() example

<?php
var_dump( new QuickHashIntSet( 1024 ) );
var_dump( new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntSet(
        1024,
        QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC | QuickHashIntSet::HASHER_JENKINS2
    )
);
?>

QuickHashIntSet::add
QuickHashIntSet::delete
QuickHashIntSet


This method deletes an entry from the set

QuickHashIntSet::__construct
QuickHashIntSet::exists
QuickHashIntSet
PHP Manual

QuickHashIntSet::delete

(PECL quickhash >= Unknown)

QuickHashIntSet::delete — This method deletes an entry from the set

Opis

public bool QuickHashIntSet::delete ( int $key )

This method deletes an entry from the set, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the set itself is freed.

Parametry

key

The key of the entry to delete.

Zwracane wartości

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Przykłady

Przykład #1 QuickHashIntSet::delete() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->delete( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->delete( 4 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

QuickHashIntSet::__construct
QuickHashIntSet::exists
QuickHashIntSet


This method checks whether a key is part of the set

QuickHashIntSet::delete
QuickHashIntSet::getSize
QuickHashIntSet
PHP Manual

QuickHashIntSet::exists

(PECL quickhash >= Unknown)

QuickHashIntSet::exists — This method checks whether a key is part of the set

Opis

public bool QuickHashIntSet::exists ( int $key )

This method checks whether an entry with the provided key exists in the set.

Parametry

key

The key of the entry to check for whether it exists in the set.

Zwracane wartości

Returns TRUE when the entry was found, or FALSE when the entry is not found.

Przykłady

Przykład #1 QuickHashIntSet::exists() example

<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating set: ", microtime( true ), "\n";
$set = new QuickHashIntSet( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
     $set->add( $key );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
     $foundCount += $set->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

Creating set: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897

QuickHashIntSet::delete
QuickHashIntSet::getSize
QuickHashIntSet


Returns the number of elements in the set

QuickHashIntSet::exists
QuickHashIntSet::loadFromFile
QuickHashIntSet
PHP Manual

QuickHashIntSet::getSize

(PECL quickhash >= Unknown)

QuickHashIntSet::getSize — Returns the number of elements in the set

Opis

publicint QuickHashIntSet::getSize ( void )

Returns the number of elements in the set.

Parametry

key

The key of the entry to add.

Zwracane wartości

The number of elements in the set.

Przykłady

Przykład #1 QuickHashIntSet::getSize() example

<?php
$set = new QuickHashIntSet( 8 );
var_dump( $set->add( 2 ) );
var_dump( $set->add( 3 ) );
var_dump( $set->getSize() );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
int(2)

QuickHashIntSet::exists
QuickHashIntSet::loadFromFile
QuickHashIntSet


This factory method creates a set from a file

QuickHashIntSet::getSize
QuickHashIntSet::loadFromString
QuickHashIntSet
PHP Manual

QuickHashIntSet::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromFile — This factory method creates a set from a file

Opis

public static QuickHashIntSet QuickHashIntSet::loadFromFile ( string $filename [, int $size [, int $options ]] )

This factory method creates a new set from a definition file on disk. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses.

Parametry

filename

The filename of the file to read the set from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the set, rounded up to the nearest power of two with a maximum limit of 4194304.

Zwracane wartości

Returns a new QuickHashIntSet.

Przykłady

Przykład #1 QuickHashIntSet::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.set";
$set = QuickHashIntSet::loadFromFile(
    $file,
    QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $set->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Powyższy przykład wyświetli coś podobnego do:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

QuickHashIntSet::getSize
QuickHashIntSet::loadFromString
QuickHashIntSet


This factory method creates a set from a string

QuickHashIntSet::loadFromFile
QuickHashIntSet::saveToFile
QuickHashIntSet
PHP Manual

QuickHashIntSet::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromString — This factory method creates a set from a string

Opis

public static QuickHashIntSet QuickHashIntSet::loadFromString ( string $contents [, int $size [, int $options ]] )

This factory method creates a new set from a definition in a string. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses.

Parametry

contents

The string containing a serialized format of the set.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the set, rounded up to the nearest power of two automatically limited from 64 to 4194304.

Zwracane wartości

Returns a new QuickHashIntSet.

Przykłady

Przykład #1 QuickHashIntSet::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.set" );
$set = QuickHashIntSet::loadFromString(
    $contents,
    QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $set->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Powyższy przykład wyświetli coś podobnego do:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

QuickHashIntSet::loadFromFile
QuickHashIntSet::saveToFile
QuickHashIntSet


This method stores an in-memory set to disk

QuickHashIntSet::loadFromString
QuickHashIntSet::saveToString
QuickHashIntSet
PHP Manual

QuickHashIntSet::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToFile — This method stores an in-memory set to disk

Opis

public void QuickHashIntSet::saveToFile ( string $filename )

This method stores an existing set to a file on disk, in the same format that loadFromFile() can read.

Parametry

filename

The filename of the file to store the hash in.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 QuickHashIntSet::saveToFile() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

$set->saveToFile( '/tmp/test.set' );
?>

QuickHashIntSet::loadFromString
QuickHashIntSet::saveToString
QuickHashIntSet


This method returns a serialized version of the set

QuickHashIntSet::saveToFile
QuickHashIntHash
QuickHashIntSet
PHP Manual

QuickHashIntSet::saveToString

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToString — This method returns a serialized version of the set

Opis

public string QuickHashIntSet::saveToString ( void )

This method returns a serialized version of the set in the same format that loadFromString() can read.

Zwracane wartości

This method returns a string containing a serialized format of the set. Each element is stored as a four byte value in the Endianness that the current system uses.

Przykłady

Przykład #1 QuickHashIntSet::saveToString() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

var_dump( $set->saveToString() );
?>

QuickHashIntSet::saveToFile
QuickHashIntHash
QuickHashIntSet


The QuickHashIntHash class

(No version information available, might only be in SVN)

Wstęp

This class wraps around a hash containing integer numbers, where the values are also integer numbers. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Krótki opis klasy

QuickHashIntHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public bool add ( int $key [, int $value ] )
public __construct ( int $size [, int $options ] )
public bool delete ( int $key )
public bool exists ( int $key )
public int get ( int $key )
public int getSize ( void )
public static QuickHashIntHash loadFromFile ( string $filename [, int $options ] )
public static QuickHashIntHash loadFromString ( string $contents [, int $options ] )
public void saveToFile ( string $filename )
public string saveToString ( void )
public bool set ( int $key , int $value )
public bool update ( int $key , int $value )
}

Stałe predefiniowane

QuickHashIntHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntHash::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntHash::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntHash::HASHER_JENKINS2

Selects a variant hashing algorithm.

Spis treści

  • QuickHashIntHash::add — This method adds a new entry to the hash
  • QuickHashIntHash::__construct — Creates a new QuickHashIntHash object
  • QuickHashIntHash::delete — This method deletes am entry from the hash
  • QuickHashIntHash::exists — This method checks whether a key is part of the hash
  • QuickHashIntHash::get — This method retrieves a value from the hash by its key
  • QuickHashIntHash::getSize — Returns the number of elements in the hash
  • QuickHashIntHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashIntHash::loadFromString — This factory method creates a hash from a string
  • QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashIntHash::saveToString — This method returns a serialized version of the hash
  • QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashIntHash::update — This method updates an entry in the hash with a new value
QuickHashIntSet::saveToString
QuickHashIntHash::add
Quickhash


This method adds a new entry to the hash

QuickHashIntHash
QuickHashIntHash::__construct
QuickHashIntHash
PHP Manual

QuickHashIntHash::add

(PECL quickhash >= Unknown)

QuickHashIntHash::add — This method adds a new entry to the hash

Opis

public bool QuickHashIntHash::add ( int $key [, int $value ] )

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashIntHash::CHECK_FOR_DUPES has been passed when the hash was created.

Parametry

key

The key of the entry to add.

value

The optional value of the entry to add. If no value is specified, 1 will be used.

Zwracane wartości

TRUE when the entry was added, and FALSE if the entry was not added.

Przykłady

Przykład #1 QuickHashIntHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 22 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 12 ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 78 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 9 ) );

echo "\ndefault value\n";
var_dump( $hash->add( 5 ) );
var_dump( $hash->get( 5 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

without dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

with dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

default value
bool(true)
int(1)

QuickHashIntHash
QuickHashIntHash::__construct
QuickHashIntHash


Creates a new QuickHashIntHash object

QuickHashIntHash::add
QuickHashIntHash::delete
QuickHashIntHash
PHP Manual

QuickHashIntHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntHash::__construct — Creates a new QuickHashIntHash object

Opis

public QuickHashIntHash::__construct ( int $size [, int $options ] )

This constructor creates a new QuickHashIntHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Parametry

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashIntHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash; QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntHash::HASHER_NO_HASH, QuickHashIntHash::HASHER_JENKINS1 or QuickHashIntHash::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Zwracane wartości

Returns a new QuickHashIntHash object.

Przykłady

Przykład #1 QuickHashIntHash::__construct() example

<?php
var_dump( new QuickHashIntHash( 1024 ) );
var_dump( new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntHash(
        1024,
        QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntHash::HASHER_JENKINS2
    )
);
?>

QuickHashIntHash::add
QuickHashIntHash::delete
QuickHashIntHash


This method deletes am entry from the hash

QuickHashIntHash::__construct
QuickHashIntHash::exists
QuickHashIntHash
PHP Manual

QuickHashIntHash::delete

(PECL quickhash >= Unknown)

QuickHashIntHash::delete — This method deletes am entry from the hash

Opis

public bool QuickHashIntHash::delete ( int $key )

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Parametry

key

The key of the entry to delete.

Zwracane wartości

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Przykłady

Przykład #1 QuickHashIntHash::delete() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 5 ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

QuickHashIntHash::__construct
QuickHashIntHash::exists
QuickHashIntHash


This method checks whether a key is part of the hash

QuickHashIntHash::delete
QuickHashIntHash::get
QuickHashIntHash
PHP Manual

QuickHashIntHash::exists

(PECL quickhash >= Unknown)

QuickHashIntHash::exists — This method checks whether a key is part of the hash

Opis

public bool QuickHashIntHash::exists ( int $key )

This method checks whether an entry with the provided key exists in the hash.

Parametry

key

The key of the entry to check for whether it exists in the hash.

Zwracane wartości

Returns TRUE when the entry was found, or FALSE when the entry is not found.

Przykłady

Przykład #1 QuickHashIntHash::exists() example

<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating hash: ", microtime( true ), "\n";
$hash = new QuickHashIntHash( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
     $hash->add( $key, 56 );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
     $foundCount += $hash->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

Creating hash: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897

QuickHashIntHash::delete
QuickHashIntHash::get
QuickHashIntHash


This method retrieves a value from the hash by its key

QuickHashIntHash::exists
QuickHashIntHash::getSize
QuickHashIntHash
PHP Manual

QuickHashIntHash::get

(PECL quickhash >= Unknown)

QuickHashIntHash::get — This method retrieves a value from the hash by its key

Opis

public int QuickHashIntHash::get ( int $key )

This method retrieves a value from the hash by its key.

Parametry

key

The key of the entry to add.

Zwracane wartości

The value if the key exists, or NULL if the key wasn't part of the hash.

Przykłady

Przykład #1 QuickHashIntHash::get() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2 ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)
int(1)
bool(true)
int(5)

QuickHashIntHash::exists
QuickHashIntHash::getSize
QuickHashIntHash


Returns the number of elements in the hash

QuickHashIntHash::get
QuickHashIntHash::loadFromFile
QuickHashIntHash
PHP Manual

QuickHashIntHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntHash::getSize — Returns the number of elements in the hash

Opis

public int QuickHashIntHash::getSize ( void )

Returns the number of elements in the hash.

Parametry

key

The key of the entry to add.

Zwracane wartości

The number of elements in the hash.

Przykłady

Przykład #1 QuickHashIntHash::getSize() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->add( 2 ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
int(2)

QuickHashIntHash::get
QuickHashIntHash::loadFromFile
QuickHashIntHash


This factory method creates a hash from a file

QuickHashIntHash::getSize
QuickHashIntHash::loadFromString
QuickHashIntHash
PHP Manual

QuickHashIntHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromFile — This factory method creates a hash from a file

Opis

public static QuickHashIntHash QuickHashIntHash::loadFromFile ( string $filename [, int $options ] )

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x11\0', the number of elements as a 32 bit signed integer in system Endianness, followed by 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each hash element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key. An example could be:

Przykład #1 QuickHash IntHash file format

00000000  51 48 11 00 02 00 00 00  01 00 00 00 01 00 00 00  |QH..............|
00000010  03 00 00 00 09 00 00 00                           |........|
00000018

Przykład #2 QuickHash IntHash file format

header signature ('QH'; key type: 1; value type: 1; filler: \0x00)
00000000  51 48 11 00

number of elements:
00000004  02 00 00 00

data string:
00000000  01 00 00 00 01 00 00 00  03 00 00 00 09 00 00 00

key/value 1 (key = 1, value = 1)
01 00 00 00  01 00 00 00

key/value 2 (key = 3, value = 9)
03 00 00 00  09 00 00 00

Parametry

filename

The filename of the file to read the hash from.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Zwracane wartości

Returns a new QuickHashIntHash.

Przykłady

Przykład #3 QuickHashIntHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.hash";
$hash = QuickHashIntHash::loadFromFile(
    $file,
    QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Powyższy przykład wyświetli coś podobnego do:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

QuickHashIntHash::getSize
QuickHashIntHash::loadFromString
QuickHashIntHash


This factory method creates a hash from a string

QuickHashIntHash::loadFromFile
QuickHashIntHash::saveToFile
QuickHashIntHash
PHP Manual

QuickHashIntHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromString — This factory method creates a hash from a string

Opis

public static QuickHashIntHash QuickHashIntHash::loadFromString ( string $contents [, int $options ] )

This factory method creates a new hash from a definition in a string. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key.

Parametry

contents

The string containing a serialized format of the hash.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Zwracane wartości

Returns a new QuickHashIntHash.

Przykłady

Przykład #1 QuickHashIntHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntHash::loadFromString(
    $contents,
    QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Powyższy przykład wyświetli coś podobnego do:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

QuickHashIntHash::loadFromFile
QuickHashIntHash::saveToFile
QuickHashIntHash


This method stores an in-memory hash to disk

QuickHashIntHash::loadFromString
QuickHashIntHash::saveToString
QuickHashIntHash
PHP Manual

QuickHashIntHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk

Opis

public void QuickHashIntHash::saveToFile ( string $filename )

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Parametry

filename

The filename of the file to store the hash in.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 QuickHashIntHash::saveToFile() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 43 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 52 ) );

$hash->saveToFile( '/tmp/test.hash' );
?>

QuickHashIntHash::loadFromString
QuickHashIntHash::saveToString
QuickHashIntHash


This method returns a serialized version of the hash

QuickHashIntHash::saveToFile
QuickHashIntHash::set
QuickHashIntHash
PHP Manual

QuickHashIntHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToString — This method returns a serialized version of the hash

Opis

public string QuickHashIntHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Zwracane wartości

This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses.

Przykłady

Przykład #1 QuickHashIntHash::saveToString() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 34 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 55 ) );

var_dump( $hash->saveToString() );
?>

QuickHashIntHash::saveToFile
QuickHashIntHash::set
QuickHashIntHash


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashIntHash::saveToString
QuickHashIntHash::update
QuickHashIntHash
PHP Manual

QuickHashIntHash::set

(PECL quickhash >= Unknown)

QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Opis

public bool QuickHashIntHash::set ( int $key , int $value )

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parametry

key

The key of the entry to add or update.

value

The new value to set the entry with.

Zwracane wartości

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Przykłady

Przykład #1 QuickHashIntHash::set() example

<?php
$hash = new QuickHashIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, 16091 ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, 29906 ) );
var_dump( $hash->get( 46692 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)

QuickHashIntHash::saveToString
QuickHashIntHash::update
QuickHashIntHash


This method updates an entry in the hash with a new value

QuickHashIntHash::set
QuickHashStringIntHash
QuickHashIntHash
PHP Manual

QuickHashIntHash::update

(PECL quickhash >= Unknown)

QuickHashIntHash::update — This method updates an entry in the hash with a new value

Opis

public bool QuickHashIntHash::update ( int $key , int $value )

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parametry

key

The key of the entry to add.

value

The new value to update the entry with.

Zwracane wartości

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Przykłady

Przykład #1 QuickHashIntHash::update() example

<?php
$hash = new QuickHashIntHash( 1024 );

var_dump( $hash->add( 141421, 173205 ) );
var_dump( $hash->update( 141421, 223606 ) );
var_dump( $hash->get( 141421 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
int(223606)

QuickHashIntHash::set
QuickHashStringIntHash
QuickHashIntHash


The QuickHashStringIntHash class

(No version information available, might only be in SVN)

Wstęp

This class wraps around a hash containing strings, where the values are integer numbers. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Krótki opis klasy

QuickHashStringIntHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
/* Methods */
public bool add ( string $key , int $value )
public __construct ( int $size [, int $options = 0 ] )
public bool delete ( string $key )
public bool exists ( string $key )
public mixed get ( string $key )
public int getSize ( void )
public static QuickHashStringIntHash loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] )
public static QuickHashStringIntHash loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] )
public void saveToFile ( string $filename )
public string saveToString ( void )
public int set ( string $key , int $value )
public bool update ( string $key , int $value )
}

Stałe predefiniowane

QuickHashStringIntHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

Spis treści

  • QuickHashStringIntHash::add — This method adds a new entry to the hash
  • QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object
  • QuickHashStringIntHash::delete — This method deletes am entry from the hash
  • QuickHashStringIntHash::exists — This method checks whether a key is part of the hash
  • QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
  • QuickHashStringIntHash::getSize — Returns the number of elements in the hash
  • QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string
  • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash
  • QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashStringIntHash::update — This method updates an entry in the hash with a new value
QuickHashIntHash::update
QuickHashStringIntHash::add
Quickhash


This method adds a new entry to the hash

QuickHashStringIntHash
QuickHashStringIntHash::__construct
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::add

(No version information available, might only be in SVN)

QuickHashStringIntHash::add — This method adds a new entry to the hash

Opis

public bool QuickHashStringIntHash::add ( string $key , int $value )

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashStringIntHash::CHECK_FOR_DUPES has been passed when the hash was created.

Parametry

key

The key of the entry to add.

value

The value of the entry to add.

Zwracane wartości

TRUE when the entry was added, and FALSE if the entry was not added.

Przykłady

Przykład #1 QuickHashStringIntHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 22 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 12 ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 78 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 9 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

without dupe checking
object(QuickHashStringIntHash)#1 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

with dupe checking
object(QuickHashStringIntHash)#2 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

QuickHashStringIntHash
QuickHashStringIntHash::__construct
QuickHashStringIntHash


Creates a new QuickHashStringIntHash object

QuickHashStringIntHash::add
QuickHashStringIntHash::delete
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::__construct

(No version information available, might only be in SVN)

QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object

Opis

public QuickHashStringIntHash::__construct ( int $size [, int $options = 0 ] )

This constructor creates a new QuickHashStringIntHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Parametry

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashStringIntHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash and QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager.

Zwracane wartości

Returns a new QuickHashStringIntHash object.

Przykłady

Przykład #1 QuickHashStringIntHash::__construct() example

<?php
var_dump( new QuickHashStringIntHash( 1024 ) );
var_dump( new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES ) );
?>

QuickHashStringIntHash::add
QuickHashStringIntHash::delete
QuickHashStringIntHash


This method deletes am entry from the hash

QuickHashStringIntHash::__construct
QuickHashStringIntHash::exists
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::delete

(No version information available, might only be in SVN)

QuickHashStringIntHash::delete — This method deletes am entry from the hash

Opis

public bool QuickHashStringIntHash::delete ( string $key )

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Parametry

key

The key of the entry to delete.

Zwracane wartości

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Przykłady

Przykład #1 QuickHashStringIntHash::delete() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->add( 'four', 5 ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)
int(5)
bool(true)
bool(false)
bool(false)
bool(false)

QuickHashStringIntHash::__construct
QuickHashStringIntHash::exists
QuickHashStringIntHash


This method checks whether a key is part of the hash

QuickHashStringIntHash::delete
QuickHashStringIntHash::get
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::exists

(No version information available, might only be in SVN)

QuickHashStringIntHash::exists — This method checks whether a key is part of the hash

Opis

public bool QuickHashStringIntHash::exists ( string $key )

This method checks whether an entry with the provided key exists in the hash.

Parametry

key

The key of the entry to check for whether it exists in the hash.

Zwracane wartości

Returns TRUE when the entry was found, or FALSE when the entry is not found.

QuickHashStringIntHash::delete
QuickHashStringIntHash::get
QuickHashStringIntHash


This method retrieves a value from the hash by its key

QuickHashStringIntHash::exists
QuickHashStringIntHash::getSize
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::get

(No version information available, might only be in SVN)

QuickHashStringIntHash::get — This method retrieves a value from the hash by its key

Opis

public mixed QuickHashStringIntHash::get ( string $key )

This method retrieves a value from the hash by its key.

Parametry

key

The key of the entry to add.

Zwracane wartości

The value if the key exists, or NULL if the key wasn't part of the hash.

Przykłady

Przykład #1 QuickHashStringIntHash::get() example

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->get( "one" ) );

var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->get( "two" ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)
int(2)

QuickHashStringIntHash::exists
QuickHashStringIntHash::getSize
QuickHashStringIntHash


Returns the number of elements in the hash

QuickHashStringIntHash::get
QuickHashStringIntHash::loadFromFile
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::getSize

(No version information available, might only be in SVN)

QuickHashStringIntHash::getSize — Returns the number of elements in the hash

Opis

public int QuickHashStringIntHash::getSize ( void )

Returns the number of elements in the hash.

Parametry

key

The key of the entry to add.

Zwracane wartości

The number of elements in the hash.

Przykłady

Przykład #1 QuickHashStringIntHash::getSize() example

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->add( "three", 5 ) );
var_dump( $hash->getSize() );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
int(2)

QuickHashStringIntHash::get
QuickHashStringIntHash::loadFromFile
QuickHashStringIntHash


This factory method creates a hash from a file

QuickHashStringIntHash::getSize
QuickHashStringIntHash::loadFromString
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::loadFromFile

(No version information available, might only be in SVN)

QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file

Opis

public static QuickHashStringIntHash QuickHashStringIntHash::loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] )

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x21\0', the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. The follows another signed 32 bit integer containing the number of bucket lists. After the header and the strings, the elements follow. They are ordered by bucket list so that the keys don't have to be hashed in order to restore the hash. For each bucket list, the following information is stored (all as 32 bit integers): the bucket list index, the number of elements in that list, and then in pairs of two unsigned 32 bit integers the elements, where the first one is the index into the string list containing the keys, and the second one the value. An example could be:

Przykład #1 QuickHash StringIntHash file format

00000000  51 48 21 00 02 00 00 00  09 00 00 00 40 00 00 00  |QH!.........@...|
00000010  4f 4e 45 00 4e 49 4e 45  00 07 00 00 00 01 00 00  |ONE.NINE........|
00000020  00 00 00 00 00 01 00 00  00 2f 00 00 00 01 00 00  |........./......|
00000030  00 04 00 00 00 03 00 00  00                       |.........|
00000039

Przykład #2 QuickHash IntHash file format

header signature ('QH'; key type: 2; value type: 1; filler: \0x00)
00000000  51 48 21 00

number of elements:
00000004  02 00 00 00

length of string values (9 characters):
00000008  09 00 00 00

number of hash bucket lists (this is configured for hashes as argument to the
constructor normally, 64 in this case):
0000000C  40 00 00 00

string values:
00000010  4f 4e 45 00 4e 49 4e 45  00

bucket lists:
  bucket list 1 (with key 7, and 1 element):
    header:
    07 00 00 00 01 00 00 00
    elements (key index: 0 ('ONE'), value = 0):
    00 00 00 00 01 00 00 00
  bucket list 2 (with key 0x2f, and 1 element):
    header:
    2f 00 00 00 01 00 00 00
    elements (key index: 4 ('NINE'), value = 3):
    04 00 00 00 03 00 00 00

Parametry

filename

The filename of the file to read the hash from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is read from the file format (unlike the QuickHashIntHash and QuickHashIntStringHash classes, where it is automatically calculated from the number of entries in the hash.)

Zwracane wartości

Returns a new QuickHashStringIntHash.

Przykłady

Przykład #3 QuickHashStringIntHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.hash.string";
$hash = QuickHashStringIntHash::loadFromFile(
    $file,
    QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    $i = 48712 + $key * 1631;
    $k = base_convert( $i, 10, 36 );
    echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177

QuickHashStringIntHash::getSize
QuickHashStringIntHash::loadFromString
QuickHashStringIntHash


This factory method creates a hash from a string

QuickHashStringIntHash::loadFromFile
QuickHashStringIntHash::saveToFile
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::loadFromString

(No version information available, might only be in SVN)

QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string

Opis

public static QuickHashStringIntHash QuickHashStringIntHash::loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] )

This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile".

Parametry

contents

The string containing a serialized format of the hash.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Zwracane wartości

Returns a new QuickHashStringIntHash.

Przykłady

Przykład #1 QuickHashStringIntHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash.string" );
$hash = QuickHashStringIntHash::loadFromString(
    $contents,
    QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    $i = 48712 + $key * 1631;
    $k = base_convert( $i, 10, 36 );
    echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177

QuickHashStringIntHash::loadFromFile
QuickHashStringIntHash::saveToFile
QuickHashStringIntHash


This method stores an in-memory hash to disk

QuickHashStringIntHash::loadFromString
QuickHashStringIntHash::saveToString
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::saveToFile

(No version information available, might only be in SVN)

QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk

Opis

public void QuickHashStringIntHash::saveToFile ( string $filename )

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Parametry

filename

The filename of the file to store the hash in.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 QuickHashStringIntHash::saveToFile() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "fourty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

$hash->saveToFile( '/tmp/test.hash.string' );
?>

QuickHashStringIntHash::loadFromString
QuickHashStringIntHash::saveToString
QuickHashStringIntHash


This method returns a serialized version of the hash

QuickHashStringIntHash::saveToFile
QuickHashStringIntHash::set
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::saveToString

(No version information available, might only be in SVN)

QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash

Opis

public string QuickHashStringIntHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Zwracane wartości

This method returns a serialized format of an existing hash, in the same format that loadFromString() can read.

Przykłady

Przykład #1 QuickHashStringIntHash::saveToString() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "fourty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

var_dump( $hash->saveToString() );
?>

QuickHashStringIntHash::saveToFile
QuickHashStringIntHash::set
QuickHashStringIntHash


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashStringIntHash::saveToString
QuickHashStringIntHash::update
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::set

(No version information available, might only be in SVN)

QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Opis

public int QuickHashStringIntHash::set ( string $key , int $value )

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parametry

key

The key of the entry to add or update.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Zwracane wartości

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Przykłady

Przykład #1 QuickHashStringIntHash::set() example

<?php
$hash = new QuickHashStringIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );
var_dump( $hash->set( "fourty six thousand six hundred ninety two", 16091 ) );
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );

echo "Set->Update\n";
var_dump( $hash->set( "fourty six thousand six hundred ninety two", 29906 ) );
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );
?>

Powyższy przykład wyświetli coś podobnego do:

Set->Add
bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)

QuickHashStringIntHash::saveToString
QuickHashStringIntHash::update
QuickHashStringIntHash


This method updates an entry in the hash with a new value

QuickHashStringIntHash::set
QuickHashIntStringHash
QuickHashStringIntHash
PHP Manual

QuickHashStringIntHash::update

(No version information available, might only be in SVN)

QuickHashStringIntHash::update — This method updates an entry in the hash with a new value

Opis

public bool QuickHashStringIntHash::update ( string $key , int $value )

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parametry

key

The key of the entry to add.

value

The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible.

Zwracane wartości

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Przykłady

Przykład #1 QuickHashStringIntHash::update() example

<?php
$hash = new QuickHashStringIntHash( 1024 );

$hash->add( 'six', 314159265 );
$hash->add( "a lot", 314159265 );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";

var_dump( $hash->update( 'a lot', 314159266 ) );
var_dump( $hash->update( "a lot plus one", 314159999 ) );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

314159265
314159265
bool(true)
bool(false)
314159265
314159266

QuickHashStringIntHash::set
QuickHashIntStringHash
QuickHashStringIntHash


The QuickHashIntStringHash class

(No version information available, might only be in SVN)

Wstęp

This class wraps around a hash containing integer numbers, where the values are strings. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Krótki opis klasy

QuickHashIntStringHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public bool add ( int $key , string $value )
public __construct ( int $size [, int $options = 0 ] )
public bool delete ( int $key )
public bool exists ( int $key )
public mixed get ( int $key )
public int getSize ( void )
public static QuickHashIntStringHash loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] )
public static QuickHashIntStringHash loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] )
public void saveToFile ( string $filename )
public string saveToString ( void )
public int set ( int $key , string $value )
public bool update ( int $key , string $value )
}

Stałe predefiniowane

QuickHashIntStringHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntStringHash::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntStringHash::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntStringHash::HASHER_JENKINS2

Selects a variant hashing algorithm.

Spis treści

  • QuickHashIntStringHash::add — This method adds a new entry to the hash
  • QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object
  • QuickHashIntStringHash::delete — This method deletes am entry from the hash
  • QuickHashIntStringHash::exists — This method checks whether a key is part of the hash
  • QuickHashIntStringHash::get — This method retrieves a value from the hash by its key
  • QuickHashIntStringHash::getSize — Returns the number of elements in the hash
  • QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string
  • QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash
  • QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashIntStringHash::update — This method updates an entry in the hash with a new value
QuickHashStringIntHash::update
QuickHashIntStringHash::add
Quickhash


This method adds a new entry to the hash

QuickHashIntStringHash
QuickHashIntStringHash::__construct
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::add

(PECL quickhash >= Unknown)

QuickHashIntStringHash::add — This method adds a new entry to the hash

Opis

public bool QuickHashIntStringHash::add ( int $key , string $value )

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashIntStringHash::CHECK_FOR_DUPES has been passed when the hash was created.

Parametry

key

The key of the entry to add.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Zwracane wartości

TRUE when the entry was added, and FALSE if the entry was not added.

Przykłady

Przykład #1 QuickHashIntStringHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twenty two" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twelve" ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "seventy eight" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "nine" ) );
?>

Powyższy przykład wyświetli coś podobnego do:

without dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
string(10) "twenty two"
bool(true)

with dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
string(13) "seventy eight"
bool(false)

QuickHashIntStringHash
QuickHashIntStringHash::__construct
QuickHashIntStringHash


Creates a new QuickHashIntStringHash object

QuickHashIntStringHash::add
QuickHashIntStringHash::delete
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object

Opis

public QuickHashIntStringHash::__construct ( int $size [, int $options = 0 ] )

This constructor creates a new QuickHashIntStringHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Parametry

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashIntStringHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash; QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntStringHash::HASHER_NO_HASH, QuickHashIntStringHash::HASHER_JENKINS1 or QuickHashIntStringHash::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Zwracane wartości

Returns a new QuickHashIntStringHash object.

Przykłady

Przykład #1 QuickHashIntStringHash::__construct() example

<?php
var_dump( new QuickHashIntStringHash( 1024 ) );
var_dump( new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntStringHash(
        1024,
        QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntStringHash::HASHER_JENKINS2
    )
);
?>

QuickHashIntStringHash::add
QuickHashIntStringHash::delete
QuickHashIntStringHash


This method deletes am entry from the hash

QuickHashIntStringHash::__construct
QuickHashIntStringHash::exists
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::delete

(PECL quickhash >= Unknown)

QuickHashIntStringHash::delete — This method deletes am entry from the hash

Opis

public bool QuickHashIntStringHash::delete ( int $key )

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Parametry

key

The key of the entry to delete.

Zwracane wartości

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Przykłady

Przykład #1 QuickHashIntStringHash::delete() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "five" ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

QuickHashIntStringHash::__construct
QuickHashIntStringHash::exists
QuickHashIntStringHash


This method checks whether a key is part of the hash

QuickHashIntStringHash::delete
QuickHashIntStringHash::get
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::exists

(PECL quickhash >= Unknown)

QuickHashIntStringHash::exists — This method checks whether a key is part of the hash

Opis

public bool QuickHashIntStringHash::exists ( int $key )

This method checks whether an entry with the provided key exists in the hash.

Parametry

key

The key of the entry to check for whether it exists in the hash.

Zwracane wartości

Returns TRUE when the entry was found, or FALSE when the entry is not found.

QuickHashIntStringHash::delete
QuickHashIntStringHash::get
QuickHashIntStringHash


This method retrieves a value from the hash by its key

QuickHashIntStringHash::exists
QuickHashIntStringHash::getSize
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::get

(PECL quickhash >= Unknown)

QuickHashIntStringHash::get — This method retrieves a value from the hash by its key

Opis

public mixed QuickHashIntStringHash::get ( int $key )

This method retrieves a value from the hash by its key.

Parametry

key

The key of the entry to add.

Zwracane wartości

The value if the key exists, or NULL if the key wasn't part of the hash.

Przykłady

Przykład #1 QuickHashIntStringHash::get() example

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)
bool(true)
string(3) "two"
bool(true)
string(1) "5"

QuickHashIntStringHash::exists
QuickHashIntStringHash::getSize
QuickHashIntStringHash


Returns the number of elements in the hash

QuickHashIntStringHash::get
QuickHashIntStringHash::loadFromFile
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntStringHash::getSize — Returns the number of elements in the hash

Opis

public int QuickHashIntStringHash::getSize ( void )

Returns the number of elements in the hash.

Zwracane wartości

The number of elements in the hash.

Przykłady

Przykład #1 QuickHashIntStringHash::getSize() example

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
int(2)

QuickHashIntStringHash::get
QuickHashIntStringHash::loadFromFile
QuickHashIntStringHash


This factory method creates a hash from a file

QuickHashIntStringHash::getSize
QuickHashIntStringHash::loadFromString
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file

Opis

public static QuickHashIntStringHash QuickHashIntStringHash::loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] )

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x12\0', the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. After the header and the strings, the elements follow in pairs of two unsigned 32 bit integers where the first one is the key, and the second one the index in the the element data string. An example could be:

Przykład #1 QuickHash IntString file format

00000000  51 48 12 00 02 00 00 00  09 00 00 00 4f 4e 45 00  |QH..........ONE.|
00000010  4e 49 4e 45 00 01 00 00  00 00 00 00 00 03 00 00  |NINE............|
00000020  00 04 00 00 00                                    |.....|
00000025

Przykład #2 QuickHash IntString file format

header signature ('QH'; key type: 1; value type: 2; filler: \0x00)
00000000  51 48 12 00

number of elements:
00000004  02 00 00 00

length of string values (9 characters):
00000008  09 00 00 00

string values:
0000000C  4f 4e 45 00 4e 49 4e 45  00

data string:
00000015  01 00 00 00 00 00 00 00  03 00 00 00 04 00 00 00

key/value 1 (key = 1, string index = 0 ("ONE")):
01 00 00 00  00 00 00 00

key/value 2 (key = 3, string index = 4 ("NINE")):
03 00 00 00  04 00 00 00

Parametry

filename

The filename of the file to read the hash from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Zwracane wartości

Returns a new QuickHashIntStringHash.

Przykłady

Przykład #3 QuickHashIntStringHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.string.hash";
$hash = QuickHashIntStringHash::loadFromFile(
    $file,
    QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Powyższy przykład wyświetli coś podobnego do:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

QuickHashIntStringHash::getSize
QuickHashIntStringHash::loadFromString
QuickHashIntStringHash


This factory method creates a hash from a string

QuickHashIntStringHash::loadFromFile
QuickHashIntStringHash::saveToFile
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string

Opis

public static QuickHashIntStringHash QuickHashIntStringHash::loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] )

This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile".

Parametry

contents

The string containing a serialized format of the hash.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Zwracane wartości

Returns a new QuickHashIntStringHash.

Przykłady

Przykład #1 QuickHashIntStringHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntStringHash::loadFromString(
    $contents,
    QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

Powyższy przykład wyświetli coś podobnego do:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

QuickHashIntStringHash::loadFromFile
QuickHashIntStringHash::saveToFile
QuickHashIntStringHash


This method stores an in-memory hash to disk

QuickHashIntStringHash::loadFromString
QuickHashIntStringHash::saveToString
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk

Opis

public void QuickHashIntStringHash::saveToFile ( string $filename )

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Parametry

filename

The filename of the file to store the hash in.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 QuickHashIntStringHash::saveToFile() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fourty three" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fifty two" ) );

$hash->saveToFile( '/tmp/test.string.hash' );
?>

QuickHashIntStringHash::loadFromString
QuickHashIntStringHash::saveToString
QuickHashIntStringHash


This method returns a serialized version of the hash

QuickHashIntStringHash::saveToFile
QuickHashIntStringHash::set
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash

Opis

public string QuickHashIntStringHash::saveToString ( void )

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Zwracane wartości

This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses.

Przykłady

Przykład #1 QuickHashIntStringHash::saveToString() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "thirty four" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 5, "fifty five" ) );

var_dump( $hash->saveToString() );
?>

QuickHashIntStringHash::saveToFile
QuickHashIntStringHash::set
QuickHashIntStringHash


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashIntStringHash::saveToString
QuickHashIntStringHash::update
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::set

(PECL quickhash >= Unknown)

QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Opis

public int QuickHashIntStringHash::set ( int $key , string $value )

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parametry

key

The key of the entry to add or update.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Zwracane wartości

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Przykłady

Przykład #1 QuickHashIntStringHash::set() example

<?php
$hash = new QuickHashIntStringHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, "sixteen thousand ninety one" ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, "twenty nine thousand nine hundred six" ) );
var_dump( $hash->get( 46692 ) );
?>

Powyższy przykład wyświetli coś podobnego do:

Set->Add
bool(false)
int(2)
string(27) "sixteen thousand ninety one"
Set->Update
int(1)
string(37) "twenty nine thousand nine hundred six"

QuickHashIntStringHash::saveToString
QuickHashIntStringHash::update
QuickHashIntStringHash


This method updates an entry in the hash with a new value

QuickHashIntStringHash::set
Reflection
QuickHashIntStringHash
PHP Manual

QuickHashIntStringHash::update

(PECL quickhash >= Unknown)

QuickHashIntStringHash::update — This method updates an entry in the hash with a new value

Opis

public bool QuickHashIntStringHash::update ( int $key , string $value )

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parametry

key

The key of the entry to add.

value

The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible.

Zwracane wartości

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Przykłady

Przykład #1 QuickHashIntStringHash::update() example

<?php
$hash->add( 161803398, "--" );
$hash->add( 314159265, "a lot" );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";

var_dump( $hash->update( 314159265, "a lot plus one" ) );
var_dump( $hash->update( 314159999, "a lot plus one" ) );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

--
a lot
bool(true)
bool(false)
--
a lot plus one

QuickHashIntStringHash::set
Reflection
QuickHashIntStringHash


Reflection

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • Extending
  • Reflection — The Reflection class
    • Reflection::export — Exports
    • Reflection::getModifierNames — Gets modifier names
  • ReflectionClass — The ReflectionClass class
    • ReflectionClass::__clone — Clones object
    • ReflectionClass::__construct — Constructs a ReflectionClass
    • ReflectionClass::export — Exports a class
    • ReflectionClass::getConstant — Gets defined constant
    • ReflectionClass::getConstants — Gets constants
    • ReflectionClass::getConstructor — Gets constructor
    • ReflectionClass::getDefaultProperties — Gets default properties
    • ReflectionClass::getDocComment — Gets doc comments
    • ReflectionClass::getEndLine — Gets end line
    • ReflectionClass::getExtension — Gets extension info
    • ReflectionClass::getExtensionName — Gets an extensions name
    • ReflectionClass::getFileName — Gets the filename of the file in which the class has been defined
    • ReflectionClass::getInterfaceNames — Gets the interface names
    • ReflectionClass::getInterfaces — Gets the interfaces
    • ReflectionClass::getMethod — Gets a ReflectionMethod
    • ReflectionClass::getMethods — Gets a list of methods
    • ReflectionClass::getModifiers — Gets modifiers
    • ReflectionClass::getName — Gets class name
    • ReflectionClass::getNamespaceName — Gets namespace name
    • ReflectionClass::getParentClass — Gets parent class
    • ReflectionClass::getProperties — Gets properties
    • ReflectionClass::getProperty — Gets property
    • ReflectionClass::getShortName — Gets short name
    • ReflectionClass::getStartLine — Gets starting line number
    • ReflectionClass::getStaticProperties — Gets static properties
    • ReflectionClass::getStaticPropertyValue — Gets static property value
    • ReflectionClass::getTraitAliases — Returns an array of trait aliases
    • ReflectionClass::getTraitNames — Returns an array of names of traits used by this class
    • ReflectionClass::getTraits — Returns an array of traits used by this class
    • ReflectionClass::hasConstant — Checks if constant is defined
    • ReflectionClass::hasMethod — Checks if method is defined
    • ReflectionClass::hasProperty — Checks if property is defined
    • ReflectionClass::implementsInterface — Implements interface
    • ReflectionClass::inNamespace — Checks if in namespace
    • ReflectionClass::isAbstract — Checks if class is abstract
    • ReflectionClass::isCloneable — Returns whether this class is cloneable
    • ReflectionClass::isFinal — Checks if class is final
    • ReflectionClass::isInstance — Checks class for instance
    • ReflectionClass::isInstantiable — Checks if instantiable
    • ReflectionClass::isInterface — Checks if interface
    • ReflectionClass::isInternal — Checks if internal
    • ReflectionClass::isIterateable — Checks if iterateable
    • ReflectionClass::isSubclassOf — Checks if a subclass
    • ReflectionClass::isTrait — Returns whether this is a trait
    • ReflectionClass::isUserDefined — Checks if user defined
    • ReflectionClass::newInstance — Creates a new class instance from given arguments.
    • ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments.
    • ReflectionClass::newInstanceWithoutConstructor — Creates a new class instance without invoking the constructor.
    • ReflectionClass::setStaticPropertyValue — Sets static property value
    • ReflectionClass::__toString — Returns the string representation of the ReflectionClass object.
  • ReflectionZendExtension — The ReflectionZendExtension class
    • ReflectionZendExtension::__clone — Clone handler
    • ReflectionZendExtension::__construct — Constructor
    • ReflectionZendExtension::export — Export
    • ReflectionZendExtension::getAuthor — Gets author
    • ReflectionZendExtension::getCopyright — Gets copyright
    • ReflectionZendExtension::getName — Gets name
    • ReflectionZendExtension::getURL — Gets URL
    • ReflectionZendExtension::getVersion — Gets version
    • ReflectionZendExtension::__toString — To string handler
  • ReflectionExtension — The ReflectionExtension class
    • ReflectionExtension::__clone — Clones
    • ReflectionExtension::__construct — Constructs a ReflectionExtension
    • ReflectionExtension::export — Export
    • ReflectionExtension::getClasses — Gets classes
    • ReflectionExtension::getClassNames — Gets class names
    • ReflectionExtension::getConstants — Gets constants
    • ReflectionExtension::getDependencies — Gets dependencies
    • ReflectionExtension::getFunctions — Gets extension functions
    • ReflectionExtension::getINIEntries — Gets extension ini entries
    • ReflectionExtension::getName — Gets extension name
    • ReflectionExtension::getVersion — Gets extension version
    • ReflectionExtension::info — Print extension info
    • ReflectionExtension::isPersistent — Returns whether this extension is persistent
    • ReflectionExtension::isTemporary — Returns whether this extension is temporary
    • ReflectionExtension::__toString — To string
  • ReflectionFunction — The ReflectionFunction class
    • ReflectionFunction::__construct — Constructs a ReflectionFunction object
    • ReflectionFunction::export — Exports function
    • ReflectionFunction::getClosure — Returns a dynamically created closure for the function
    • ReflectionFunction::invoke — Invokes function
    • ReflectionFunction::invokeArgs — Invokes function args
    • ReflectionFunction::isDisabled — Checks if function is disabled
    • ReflectionFunction::__toString — To string
  • ReflectionFunctionAbstract — The ReflectionFunctionAbstract class
    • ReflectionFunctionAbstract::__clone — Clones function
    • ReflectionFunctionAbstract::getClosureThis — Returns this pointer bound to closure
    • ReflectionFunctionAbstract::getDocComment — Gets doc comment
    • ReflectionFunctionAbstract::getEndLine — Gets end line number
    • ReflectionFunctionAbstract::getExtension — Gets extension info
    • ReflectionFunctionAbstract::getExtensionName — Gets extension name
    • ReflectionFunctionAbstract::getFileName — Gets file name
    • ReflectionFunctionAbstract::getName — Gets function name
    • ReflectionFunctionAbstract::getNamespaceName — Gets namespace name
    • ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters
    • ReflectionFunctionAbstract::getParameters — Gets parameters
    • ReflectionFunctionAbstract::getShortName — Gets function short name
    • ReflectionFunctionAbstract::getStartLine — Gets starting line number
    • ReflectionFunctionAbstract::getStaticVariables — Gets static variables
    • ReflectionFunctionAbstract::inNamespace — Checks if function in namespace
    • ReflectionFunctionAbstract::isClosure — Checks if closure
    • ReflectionFunctionAbstract::isDeprecated — Checks if deprecated
    • ReflectionFunctionAbstract::isInternal — Checks if is internal
    • ReflectionFunctionAbstract::isUserDefined — Checks if user defined
    • ReflectionFunctionAbstract::returnsReference — Checks if returns reference
    • ReflectionFunctionAbstract::__toString — To string
  • ReflectionMethod — The ReflectionMethod class
    • ReflectionMethod::__construct — Constructs a ReflectionMethod
    • ReflectionMethod::export — Export a reflection method.
    • ReflectionMethod::getClosure — Returns a dynamically created closure for the method
    • ReflectionMethod::getDeclaringClass — Gets declaring class for the reflected method.
    • ReflectionMethod::getModifiers — Gets the method modifiers
    • ReflectionMethod::getPrototype — Gets the method prototype (if there is one).
    • ReflectionMethod::invoke — Invoke
    • ReflectionMethod::invokeArgs — Invoke args
    • ReflectionMethod::isAbstract — Checks if method is abstract
    • ReflectionMethod::isConstructor — Checks if method is a constructor
    • ReflectionMethod::isDestructor — Checks if method is a destructor
    • ReflectionMethod::isFinal — Checks if method is final
    • ReflectionMethod::isPrivate — Checks if method is private
    • ReflectionMethod::isProtected — Checks if method is protected
    • ReflectionMethod::isPublic — Checks if method is public
    • ReflectionMethod::isStatic — Checks if method is static
    • ReflectionMethod::setAccessible — Set method accessibility
    • ReflectionMethod::__toString — Returns the string representation of the Reflection method object.
  • ReflectionObject — The ReflectionObject class
    • ReflectionObject::__construct — Constructs a ReflectionObject
    • ReflectionObject::export — Export
  • ReflectionParameter — The ReflectionParameter class
    • ReflectionParameter::allowsNull — Checks if null is allowed
    • ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value
    • ReflectionParameter::__clone — Clone
    • ReflectionParameter::__construct — Construct
    • ReflectionParameter::export — Exports
    • ReflectionParameter::getClass — Get class
    • ReflectionParameter::getDeclaringClass — Gets declaring class
    • ReflectionParameter::getDeclaringFunction — Gets declaring function
    • ReflectionParameter::getDefaultValue — Gets default parameter value
    • ReflectionParameter::getName — Gets parameter name
    • ReflectionParameter::getPosition — Gets parameter position
    • ReflectionParameter::isArray — Checks if parameter expects an array
    • ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available
    • ReflectionParameter::isOptional — Checks if optional
    • ReflectionParameter::isPassedByReference — Checks if passed by reference
    • ReflectionParameter::__toString — To string
  • ReflectionProperty — The ReflectionProperty class
    • ReflectionProperty::__clone — Clone
    • ReflectionProperty::__construct — Construct a ReflectionProperty object
    • ReflectionProperty::export — Export
    • ReflectionProperty::getDeclaringClass — Gets declaring class
    • ReflectionProperty::getDocComment — Gets doc comment
    • ReflectionProperty::getModifiers — Gets modifiers
    • ReflectionProperty::getName — Gets property name
    • ReflectionProperty::getValue — Gets value
    • ReflectionProperty::isDefault — Checks if default value
    • ReflectionProperty::isPrivate — Checks if property is private
    • ReflectionProperty::isProtected — Checks if property is protected
    • ReflectionProperty::isPublic — Checks if property is public
    • ReflectionProperty::isStatic — Checks if property is static
    • ReflectionProperty::setAccessible — Set property accessibility
    • ReflectionProperty::setValue — Set property value
    • ReflectionProperty::__toString — To string
  • Reflector — The Reflector interface
    • Reflector::export — Exports
    • Reflector::__toString — To string
  • ReflectionException — The ReflectionException class
QuickHashIntStringHash::update
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. Additionally, the reflection API offers ways to retrieve doc comments for functions, classes and methods.

Please note that certain parts of the internal API are missing the necessary code to work with the Reflection extension. E.g., an internal PHP class might be missing reflection data for properties. These few cases are considered bugs, however, so they should be discovered and fixed.

Reflection
Instalacja/Konfiguracja
Reflection


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Reflection


Stałe predefiniowane

Each class describes its own constants.

Typy zasobów
Przykłady
Reflection


Przykłady

Many examples exist within the Reflection documentation, typically within the __construct documentation for each class.

Przykład #1 Reflection Example from Shell (a Terminal)

$ php --rf strlen
$ php --rc finfo
$ php --re json
$ php --ri dom

Powyższy przykład wyświetli coś podobnego do:

Function [ <internal:Core> function strlen ] {

  - Parameters [1] {
    Parameter #0 [ <required> $str ]
  }
}

Class [ <internal:fileinfo> class finfo ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [4] {
    Method [ <internal:fileinfo, ctor> public method finfo ] {

      - Parameters [2] {
        Parameter #0 [ <optional> $options ]
        Parameter #1 [ <optional> $arg ]
      }
    }

    Method [ <internal:fileinfo> public method set_flags ] {

      - Parameters [1] {
        Parameter #0 [ <required> $options ]
      }
    }

    Method [ <internal:fileinfo> public method file ] {

      - Parameters [3] {
        Parameter #0 [ <required> $filename ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }

    Method [ <internal:fileinfo> public method buffer ] {

      - Parameters [3] {
        Parameter #0 [ <required> $string ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }
  }
}

Extension [ <persistent> extension #23 json version 1.2.1 ] {

  - Constants [10] {
    Constant [ integer JSON_HEX_TAG ] { 1 }
    Constant [ integer JSON_HEX_AMP ] { 2 }
    Constant [ integer JSON_HEX_APOS ] { 4 }
    Constant [ integer JSON_HEX_QUOT ] { 8 }
    Constant [ integer JSON_FORCE_OBJECT ] { 16 }
    Constant [ integer JSON_ERROR_NONE ] { 0 }
    Constant [ integer JSON_ERROR_DEPTH ] { 1 }
    Constant [ integer JSON_ERROR_STATE_MISMATCH ] { 2 }
    Constant [ integer JSON_ERROR_CTRL_CHAR ] { 3 }
    Constant [ integer JSON_ERROR_SYNTAX ] { 4 }
  }

  - Functions {
    Function [ <internal:json> function json_encode ] {

      - Parameters [2] {
        Parameter #0 [ <required> $value ]
        Parameter #1 [ <optional> $options ]
      }
    }
    Function [ <internal:json> function json_decode ] {

      - Parameters [3] {
        Parameter #0 [ <required> $json ]
        Parameter #1 [ <optional> $assoc ]
        Parameter #2 [ <optional> $depth ]
      }
    }
    Function [ <internal:json> function json_last_error ] {

      - Parameters [0] {
      }
    }
  }
}

dom

DOM/XML => enabled
DOM/XML API Version => 20031129
libxml Version => 2.7.3
HTML Support => enabled
XPath Support => enabled
XPointer Support => enabled
Schema Support => enabled
RelaxNG Support => enabled
Stałe predefiniowane
Extending
Reflection


Extending

If you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.

Przykład #1 Extending the built-in classes

<?php
/**
 * My Reflection_Method class
 */
class My_Reflection_Method extends ReflectionMethod
{
    public $visibility = array();

    public function __construct($o, $m)
    {
        parent::__construct($o, $m);
        $this->visibility = Reflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Demo class #1
 *
 */
class T {
    protected function x() {}
}

/**
 * Demo class #2
 *
 */
class U extends T {
    function x() {}
}

// Print out information
var_dump(new My_Reflection_Method('U', 'x'));
?>

Powyższy przykład wyświetli coś podobnego do:

object(My_Reflection_Method)#1 (3) {
  ["visibility"]=>
  array(1) {
    [0]=>
    string(6) "public"
  }
  ["name"]=>
  string(1) "x"
  ["class"]=>
  string(1) "U"
}
Uwaga

If you're overwriting the constructor, remember to call the parent's constructor before any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object

Przykłady
Reflection
Reflection


The Reflection class

(PHP 5)

Wstęp

The reflection class.

Krótki opis klasy

Reflection {
/* Metody */
public static string export ( Reflector $reflector [, bool $return = false ] )
public static array getModifierNames ( int $modifiers )
}

Spis treści

  • Reflection::export — Exports
  • Reflection::getModifierNames — Gets modifier names
Extending
Reflection::export
Reflection


Exports

Reflection
Reflection::getModifierNames
Reflection
PHP Manual

Reflection::export

(PHP 5)

Reflection::export — Exports

Opis

public static string Reflection::export ( Reflector $reflector [, bool $return = false ] )

Exports a reflection.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

reflector

Refleksja do eksportu.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Zwracane wartości

Jeśli parametr return jest ustawiony na TRUE, eksport jest zwracany jako string, w przeciwnym przypadku jako NULL.

Zobacz też:

  • Reflection::getModifierNames() - Gets modifier names

Reflection
Reflection::getModifierNames
Reflection


Gets modifier names

Reflection::export
ReflectionClass
Reflection
PHP Manual

Reflection::getModifierNames

(PHP 5)

Reflection::getModifierNames — Gets modifier names

Opis

public static array Reflection::getModifierNames ( int $modifiers )

Gets modifier names.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

modifiers

The modifiers to get, which is from a numeric value.

Zwracane wartości

An array of modifier names.

Zobacz też:

  • Reflection::export() - Exports

Reflection::export
ReflectionClass
Reflection


The ReflectionClass class

(PHP 5)

Wstęp

The ReflectionClass class reports information about a class.

Krótki opis klasy

ReflectionClass implements Reflector {
/* Stałe */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* Właściwości */
public $name ;
/* Metody */
final private void __clone ( void )
__construct ( mixed $argument )
public static string export ( mixed $argument [, bool $return = false ] )
public mixed getConstant ( string $name )
public array getConstants ( void )
public object getConstructor ( void )
public array getDefaultProperties ( void )
public string getDocComment ( void )
public int getEndLine ( void )
public ReflectionExtension getExtension ( void )
public string getExtensionName ( void )
public string getFileName ( void )
public array getInterfaceNames ( void )
public array getInterfaces ( void )
public ReflectionMethod getMethod ( string $name )
public array getMethods ([ string $filter ] )
public int getModifiers ( void )
public string getName ( void )
public string getNamespaceName ( void )
public object getParentClass ( void )
public array getProperties ([ int $filter ] )
public ReflectionProperty getProperty ( string $name )
public string getShortName ( void )
public int getStartLine ( void )
public array getStaticProperties ( void )
public mixed getStaticPropertyValue ( string $name [, string $default ] )
public array getTraitAliases ( void )
public array getTraitNames ( void )
public array getTraits ( void )
public bool hasConstant ( string $name )
public bool hasMethod ( string $name )
public bool hasProperty ( string $name )
public bool implementsInterface ( string $interface )
public bool inNamespace ( void )
public bool isAbstract ( void )
public bool isCloneable ( void )
public bool isFinal ( void )
public bool isInstance ( object $object )
public bool isInstantiable ( void )
public bool isInterface ( void )
public bool isInternal ( void )
public bool isIterateable ( void )
public bool isSubclassOf ( string $class )
public bool isTrait ( void )
public bool isUserDefined ( void )
public object newInstance ( mixed $args [, mixed $... ] )
public object newInstanceArgs ([ array $args ] )
public object newInstanceWithoutConstructor ( void )
public void setStaticPropertyValue ( string $name , string $value )
public string __toString ( void )
}

Właściwości

name

Name of the class. Read-only, throws ReflectionException in attempt to write.

Stałe predefiniowane

ReflectionClass Modifiers

ReflectionClass::IS_IMPLICIT_ABSTRACT

Indicates class that is abstract because it has some abstract methods.

ReflectionClass::IS_EXPLICIT_ABSTRACT

Indicates class that is abstract because of its definition.

ReflectionClass::IS_FINAL

Indicates final class.

Spis treści

  • ReflectionClass::__clone — Clones object
  • ReflectionClass::__construct — Constructs a ReflectionClass
  • ReflectionClass::export — Exports a class
  • ReflectionClass::getConstant — Gets defined constant
  • ReflectionClass::getConstants — Gets constants
  • ReflectionClass::getConstructor — Gets constructor
  • ReflectionClass::getDefaultProperties — Gets default properties
  • ReflectionClass::getDocComment — Gets doc comments
  • ReflectionClass::getEndLine — Gets end line
  • ReflectionClass::getExtension — Gets extension info
  • ReflectionClass::getExtensionName — Gets an extensions name
  • ReflectionClass::getFileName — Gets the filename of the file in which the class has been defined
  • ReflectionClass::getInterfaceNames — Gets the interface names
  • ReflectionClass::getInterfaces — Gets the interfaces
  • ReflectionClass::getMethod — Gets a ReflectionMethod
  • ReflectionClass::getMethods — Gets a list of methods
  • ReflectionClass::getModifiers — Gets modifiers
  • ReflectionClass::getName — Gets class name
  • ReflectionClass::getNamespaceName — Gets namespace name
  • ReflectionClass::getParentClass — Gets parent class
  • ReflectionClass::getProperties — Gets properties
  • ReflectionClass::getProperty — Gets property
  • ReflectionClass::getShortName — Gets short name
  • ReflectionClass::getStartLine — Gets starting line number
  • ReflectionClass::getStaticProperties — Gets static properties
  • ReflectionClass::getStaticPropertyValue — Gets static property value
  • ReflectionClass::getTraitAliases — Returns an array of trait aliases
  • ReflectionClass::getTraitNames — Returns an array of names of traits used by this class
  • ReflectionClass::getTraits — Returns an array of traits used by this class
  • ReflectionClass::hasConstant — Checks if constant is defined
  • ReflectionClass::hasMethod — Checks if method is defined
  • ReflectionClass::hasProperty — Checks if property is defined
  • ReflectionClass::implementsInterface — Implements interface
  • ReflectionClass::inNamespace — Checks if in namespace
  • ReflectionClass::isAbstract — Checks if class is abstract
  • ReflectionClass::isCloneable — Returns whether this class is cloneable
  • ReflectionClass::isFinal — Checks if class is final
  • ReflectionClass::isInstance — Checks class for instance
  • ReflectionClass::isInstantiable — Checks if instantiable
  • ReflectionClass::isInterface — Checks if interface
  • ReflectionClass::isInternal — Checks if internal
  • ReflectionClass::isIterateable — Checks if iterateable
  • ReflectionClass::isSubclassOf — Checks if a subclass
  • ReflectionClass::isTrait — Returns whether this is a trait
  • ReflectionClass::isUserDefined — Checks if user defined
  • ReflectionClass::newInstance — Creates a new class instance from given arguments.
  • ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments.
  • ReflectionClass::newInstanceWithoutConstructor — Creates a new class instance without invoking the constructor.
  • ReflectionClass::setStaticPropertyValue — Sets static property value
  • ReflectionClass::__toString — Returns the string representation of the ReflectionClass object.
Reflection::getModifierNames
ReflectionClass::__clone
Reflection


Clones object

ReflectionClass
ReflectionClass::__construct
ReflectionClass
PHP Manual

ReflectionClass::__clone

(PHP 5)

ReflectionClass::__clone — Clones object

Opis

final private void ReflectionClass::__clone ( void )

Clones.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • ReflectionClass::__tostring() - Returns the string representation of the ReflectionClass object.
  • Object cloning

ReflectionClass
ReflectionClass::__construct
ReflectionClass


Constructs a ReflectionClass

ReflectionClass::__clone
ReflectionClass::export
ReflectionClass
PHP Manual

ReflectionClass::__construct

(PHP 5)

ReflectionClass::__construct — Constructs a ReflectionClass

Opis

ReflectionClass::__construct ( mixed $argument )

Constructs a new ReflectionClass object.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

argument

Either a string containing the name of the class to reflect, or an object.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Basic usage ReflectionClass

<?php
Reflection::export(new ReflectionClass('Exception'));
?>

Powyższy przykład wyświetli coś podobnego do:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

Zobacz też:

  • ReflectionObject::__construct() - Constructs a ReflectionObject
  • Constructors

ReflectionClass::__clone
ReflectionClass::export
ReflectionClass


Exports a class

ReflectionClass::__construct
ReflectionClass::getConstant
ReflectionClass
PHP Manual

ReflectionClass::export

(PHP 5)

ReflectionClass::export — Exports a class

Opis

public static string ReflectionClass::export ( mixed $argument [, bool $return = false ] )

Exports a reflected class.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

argument

Refleksja do eksportu.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Zwracane wartości

Jeśli parametr return jest ustawiony na TRUE, eksport jest zwracany jako string, w przeciwnym przypadku jako NULL.

Zobacz też:

  • ReflectionClass::getName() - Gets class name

ReflectionClass::__construct
ReflectionClass::getConstant
ReflectionClass


Gets defined constant

ReflectionClass::export
ReflectionClass::getConstants
ReflectionClass
PHP Manual

ReflectionClass::getConstant

(PHP 5)

ReflectionClass::getConstant — Gets defined constant

Opis

public mixed ReflectionClass::getConstant ( string $name )

Gets the defined constant.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Name of the constant.

Zwracane wartości

Value of the constant.

Zobacz też:

  • ReflectionClass::getConstants() - Gets constants

ReflectionClass::export
ReflectionClass::getConstants
ReflectionClass


Gets constants

ReflectionClass::getConstant
ReflectionClass::getConstructor
ReflectionClass
PHP Manual

ReflectionClass::getConstants

(PHP 5)

ReflectionClass::getConstants — Gets constants

Opis

public array ReflectionClass::getConstants ( void )

Gets defined constants from a class.

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 constants. Constant name in key, constant value in value.

Zobacz też:

  • ReflectionClass::getConstant() - Gets defined constant

ReflectionClass::getConstant
ReflectionClass::getConstructor
ReflectionClass


Gets constructor

ReflectionClass::getConstants
ReflectionClass::getDefaultProperties
ReflectionClass
PHP Manual

ReflectionClass::getConstructor

(PHP 5)

ReflectionClass::getConstructor — Gets constructor

Opis

public object ReflectionClass::getConstructor ( void )

Gets the constructor from a class.

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

A ReflectionMethod object.

Zobacz też:

  • ReflectionClass::getName() - Gets class name

ReflectionClass::getConstants
ReflectionClass::getDefaultProperties
ReflectionClass


Gets default properties

ReflectionClass::getConstructor
ReflectionClass::getDocComment
ReflectionClass
PHP Manual

ReflectionClass::getDefaultProperties

(PHP 5)

ReflectionClass::getDefaultProperties — Gets default properties

Opis

public array ReflectionClass::getDefaultProperties ( void )

Gets default properties from a class (including inherited properties).

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of default properties, with the key being the name of the property and the value being the default value of the property or NULL if the property doesn't have a default value. The function does not distinguish between static and non static properties and does not take visibility modifiers into account.

Przykłady

Przykład #1 ReflectionClass::getDefaultProperties() example

<?php
class Bar {
    protected $inheritedProperty = 'inheritedDefault';
}

class Foo extends Bar {
    public $property = 'propertyDefault';
    private $privateProperty = 'privatePropertyDefault';
    public static $staticProperty = 'staticProperty';
    public $defaultlessProperty;
}

$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
?>

Powyższy przykład wyświetli:

array(5) {
   ["staticProperty"]=>
   string(14) "staticProperty"
   ["property"]=>
   string(15) "propertyDefault"
   ["privateProperty"]=>
   string(22) "privatePropertyDefault"
   ["defaultlessProperty"]=>
   NULL
   ["inheritedProperty"]=>
   string(16) "inheritedDefault"
}

Zobacz też:

  • ReflectionClass::getProperties() - Gets properties
  • ReflectionClass::getStaticProperties() - Gets static properties
  • ReflectionClass::getProperty() - Gets property

ReflectionClass::getConstructor
ReflectionClass::getDocComment
ReflectionClass


Gets doc comments

ReflectionClass::getDefaultProperties
ReflectionClass::getEndLine
ReflectionClass
PHP Manual

ReflectionClass::getDocComment

(PHP 5 >= 5.1.0)

ReflectionClass::getDocComment — Gets doc comments

Opis

public string ReflectionClass::getDocComment ( void )

Gets doc comments from a class.

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 doc comment if it exists, otherwise FALSE

Przykłady

Przykład #1 ReflectionClass::getDocComment() example

<?php
/**
* A test class
*
* @param  foo bar
* @return baz
*/
class TestClass { }

$rc = new ReflectionClass('TestClass');
var_dump($rc->getDocComment())
?>

Powyższy przykład wyświetli:

string(55) "/**
* A test class
*
* @param  foo bar
* @return baz
*/"

Zobacz też:

  • ReflectionClass::getName() - Gets class name

ReflectionClass::getDefaultProperties
ReflectionClass::getEndLine
ReflectionClass


Gets end line

ReflectionClass::getDocComment
ReflectionClass::getExtension
ReflectionClass
PHP Manual

ReflectionClass::getEndLine

(PHP 5)

ReflectionClass::getEndLine — Gets end line

Opis

public int ReflectionClass::getEndLine ( void )

Gets end line number from a user-defined class definition.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The ending line number of the user defined class, or FALSE if unknown.

Przykłady

Przykład #1 ReflectionClass::getEndLine() example

<?php
// Test Class
class TestClass { }

$rc = new ReflectionClass('TestClass');

echo $rc->getEndLine();
?>

Powyższy przykład wyświetli:

3

Zobacz też:

  • ReflectionClass::getStartLine() - Gets starting line number

ReflectionClass::getDocComment
ReflectionClass::getExtension
ReflectionClass


Gets extension info

ReflectionClass::getEndLine
ReflectionClass::getExtensionName
ReflectionClass
PHP Manual

ReflectionClass::getExtension

(PHP 5)

ReflectionClass::getExtension — Gets extension info

Opis

public ReflectionExtension ReflectionClass::getExtension ( void )

Gets an extensions ReflectionExtension object.

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

A ReflectionExtension object.

Zobacz też:

  • ReflectionClass::getExtensionName() - Gets an extensions name

ReflectionClass::getEndLine
ReflectionClass::getExtensionName
ReflectionClass


Gets an extensions name

ReflectionClass::getExtension
ReflectionClass::getFileName
ReflectionClass
PHP Manual

ReflectionClass::getExtensionName

(PHP 5)

ReflectionClass::getExtensionName — Gets an extensions name

Opis

public string ReflectionClass::getExtensionName ( void )

Gets an extensions name.

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 extensions name.

Zobacz też:

  • ReflectionClass::getExtension() - Gets extension info

ReflectionClass::getExtension
ReflectionClass::getFileName
ReflectionClass


Gets the filename of the file in which the class has been defined

ReflectionClass::getExtensionName
ReflectionClass::getInterfaceNames
ReflectionClass
PHP Manual

ReflectionClass::getFileName

(PHP 5)

ReflectionClass::getFileName — Gets the filename of the file in which the class has been defined

Opis

public string ReflectionClass::getFileName ( void )

Gets the filename of the file in which the class has been defined.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the filename of the file in which the class has been defined. If the class is defined in the PHP core or in a PHP extension, FALSE is returned.

Zobacz też:

  • ReflectionClass::getExtensionName() - Gets an extensions name

ReflectionClass::getExtensionName
ReflectionClass::getInterfaceNames
ReflectionClass


Gets the interface names

ReflectionClass::getFileName
ReflectionClass::getInterfaces
ReflectionClass
PHP Manual

ReflectionClass::getInterfaceNames

(PHP 5 >= 5.2.0)

ReflectionClass::getInterfaceNames — Gets the interface names

Opis

public array ReflectionClass::getInterfaceNames ( void )

Get the interface names.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A numerical array with interface names as the values.

Przykłady

Przykład #1 ReflectionClass::getInterfaceNames() example

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaceNames());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => Foo
    [1] => Bar
)

Zobacz też:

  • ReflectionClass::getInterfaces() - Gets the interfaces

ReflectionClass::getFileName
ReflectionClass::getInterfaces
ReflectionClass


Gets the interfaces

ReflectionClass::getInterfaceNames
ReflectionClass::getMethod
ReflectionClass
PHP Manual

ReflectionClass::getInterfaces

(PHP 5)

ReflectionClass::getInterfaces — Gets the interfaces

Opis

public array ReflectionClass::getInterfaces ( void )

Gets the interfaces.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An associative array of interfaces, with keys as interface names and the array values as ReflectionClass objects.

Przykłady

Przykład #1 ReflectionClass::getInterfaces() example

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaces());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [Foo] => ReflectionClass Object
        (
            [name] => Foo
        )

    [Bar] => ReflectionClass Object
        (
            [name] => Bar
        )

)

Zobacz też:

  • ReflectionClass::getInterfaceNames() - Gets the interface names

ReflectionClass::getInterfaceNames
ReflectionClass::getMethod
ReflectionClass


Gets a ReflectionMethod

ReflectionClass::getInterfaces
ReflectionClass::getMethods
ReflectionClass
PHP Manual

ReflectionClass::getMethod

(PHP 5)

ReflectionClass::getMethod — Gets a ReflectionMethod

Opis

public ReflectionMethod ReflectionClass::getMethod ( string $name )

Gets a ReflectionMethod about a method.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

The method name to reflect.

Zwracane wartości

A ReflectionMethod.

Zobacz też:

  • ReflectionClass::getMethod()

ReflectionClass::getInterfaces
ReflectionClass::getMethods
ReflectionClass


Gets a list of methods

ReflectionClass::getMethod
ReflectionClass::getModifiers
ReflectionClass
PHP Manual

ReflectionClass::getMethods

(PHP 5)

ReflectionClass::getMethods — Gets a list of methods

Opis

public array ReflectionClass::getMethods ([ string $filter ] )

Gets a list of methods.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

filter

Any combination of ReflectionMethod::IS_STATIC,
ReflectionMethod::IS_PUBLIC,
ReflectionMethod::IS_PROTECTED,
ReflectionMethod::IS_PRIVATE,
ReflectionMethod::IS_ABSTRACT,
ReflectionMethod::IS_FINAL.

Zwracane wartości

An array of methods.

Zobacz też:

  • ReflectionClass::getMethod() - Gets a ReflectionMethod

ReflectionClass::getMethod
ReflectionClass::getModifiers
ReflectionClass


Gets modifiers

ReflectionClass::getMethods
ReflectionClass::getName
ReflectionClass
PHP Manual

ReflectionClass::getModifiers

(PHP 5)

ReflectionClass::getModifiers — Gets modifiers

Opis

public int ReflectionClass::getModifiers ( void )

Returns a bitfield of the access modifiers for this class.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns bitmask of modifier constants.

Zobacz też:

  • ReflectionClass::getProperties() - Gets properties

ReflectionClass::getMethods
ReflectionClass::getName
ReflectionClass


Gets class name

ReflectionClass::getModifiers
ReflectionClass::getNamespaceName
ReflectionClass
PHP Manual

ReflectionClass::getName

(PHP 5)

ReflectionClass::getName — Gets class name

Opis

public string ReflectionClass::getName ( void )

Gets the class name.

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 class name.

Przykłady

Przykład #1 ReflectionClass::getName() example

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

Powyższy przykład wyświetli:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Zobacz też:

  • ReflectionClass::getNamespaceName() - Gets namespace name

ReflectionClass::getModifiers
ReflectionClass::getNamespaceName
ReflectionClass


Gets namespace name

ReflectionClass::getName
ReflectionClass::getParentClass
ReflectionClass
PHP Manual

ReflectionClass::getNamespaceName

(PHP 5 >= 5.3.0)

ReflectionClass::getNamespaceName — Gets namespace name

Opis

public string ReflectionClass::getNamespaceName ( void )

Gets the namespace name.

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 namespace name.

Przykłady

Przykład #1 ReflectionClass::getNamespaceName() example

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

Powyższy przykład wyświetli:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Zobacz też:

  • ReflectionClass::getParentClass() - Gets parent class
  • namespaces

ReflectionClass::getName
ReflectionClass::getParentClass
ReflectionClass


Gets parent class

ReflectionClass::getNamespaceName
ReflectionClass::getProperties
ReflectionClass
PHP Manual

ReflectionClass::getParentClass

(PHP 5)

ReflectionClass::getParentClass — Gets parent class

Opis

public object ReflectionClass::getParentClass ( 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

A ReflectionClass.

Zobacz też:

  • ReflectionClass::__construct() - Constructs a ReflectionClass

ReflectionClass::getNamespaceName
ReflectionClass::getProperties
ReflectionClass


Gets properties

ReflectionClass::getParentClass
ReflectionClass::getProperty
ReflectionClass
PHP Manual

ReflectionClass::getProperties

(PHP 5)

ReflectionClass::getProperties — Gets properties

Opis

public array ReflectionClass::getProperties ([ int $filter ] )

Retrieves reflected properties.

Parametry

filter

The optional filter, for filtering desired property types. It's configured using the ReflectionProperty constants, and defaults to all property types.

Zwracane wartości

An array of ReflectionProperty objects.

Przykłady

Przykład #1 ReflectionClass::getProperties() filtering example

This example demonstrates usage of the optional filter parameter, where it essentially skips private properties.

<?php
class Foo {
    public    $foo  = 1;
    protected $bar  = 2;
    private   $baz  = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

foreach ($props as $prop) {
    print $prop->getName() . "\n";
}

var_dump($props);

?>

Powyższy przykład wyświetli coś podobnego do:

foo
bar
array(2) {
  [0]=>
  object(ReflectionProperty)#3 (2) {
    ["name"]=>
    string(3) "foo"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  object(ReflectionProperty)#4 (2) {
    ["name"]=>
    string(3) "bar"
    ["class"]=>
    string(3) "Foo"
  }
}

Zobacz też:

  • ReflectionClass::getProperty() - Gets property
  • ReflectionProperty
  • ReflectionProperty modifier constants

ReflectionClass::getParentClass
ReflectionClass::getProperty
ReflectionClass


Gets property

ReflectionClass::getProperties
ReflectionClass::getShortName
ReflectionClass
PHP Manual

ReflectionClass::getProperty

(PHP 5)

ReflectionClass::getProperty — Gets property

Opis

public ReflectionProperty ReflectionClass::getProperty ( string $name )

Gets a property.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

The property name.

Zwracane wartości

A ReflectionProperty.

Zobacz też:

  • ReflectionClass::getProperties() - Gets properties

ReflectionClass::getProperties
ReflectionClass::getShortName
ReflectionClass


Gets short name

ReflectionClass::getProperty
ReflectionClass::getStartLine
ReflectionClass
PHP Manual

ReflectionClass::getShortName

(PHP 5 >= 5.3.0)

ReflectionClass::getShortName — Gets short name

Opis

public string ReflectionClass::getShortName ( void )

Gets the short name of the class, the part without the namespace.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The class short name.

Przykłady

Przykład #1 ReflectionClass::getShortName() example

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

Powyższy przykład wyświetli:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Zobacz też:

  • ReflectionClass::getName() - Gets class name

ReflectionClass::getProperty
ReflectionClass::getStartLine
ReflectionClass


Gets starting line number

ReflectionClass::getShortName
ReflectionClass::getStaticProperties
ReflectionClass
PHP Manual

ReflectionClass::getStartLine

(PHP 5)

ReflectionClass::getStartLine — Gets starting line number

Opis

public int ReflectionClass::getStartLine ( void )

Get the starting line number.

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 starting line number, as an integer.

Zobacz też:

  • ReflectionClass::getEndLine() - Gets end line

ReflectionClass::getShortName
ReflectionClass::getStaticProperties
ReflectionClass


Gets static properties

ReflectionClass::getStartLine
ReflectionClass::getStaticPropertyValue
ReflectionClass
PHP Manual

ReflectionClass::getStaticProperties

(PHP 5)

ReflectionClass::getStaticProperties — Gets static properties

Opis

public array ReflectionClass::getStaticProperties ( void )

Get the static properties.

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 static properties, as an array.

Zobacz też:

  • ReflectionClass::getStaticPropertyValue() - Gets static property value
  • ReflectionClass::setStaticPropertyValue() - Sets static property value

ReflectionClass::getStartLine
ReflectionClass::getStaticPropertyValue
ReflectionClass


Gets static property value

ReflectionClass::getStaticProperties
ReflectionClass::getTraitAliases
ReflectionClass
PHP Manual

ReflectionClass::getStaticPropertyValue

(PHP 5 >= 5.1.0)

ReflectionClass::getStaticPropertyValue — Gets static property value

Opis

public mixed ReflectionClass::getStaticPropertyValue ( string $name [, string $default ] )

Gets the static property values.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

default

Zwracane wartości

Zobacz też:

  • ReflectionClass::getStaticProperties() - Gets static properties
  • ReflectionClass::setStaticPropertyValue() - Sets static property value

ReflectionClass::getStaticProperties
ReflectionClass::getTraitAliases
ReflectionClass


Returns an array of trait aliases

ReflectionClass::getStaticPropertyValue
ReflectionClass::getTraitNames
ReflectionClass
PHP Manual

ReflectionClass::getTraitAliases

(PHP > 5.4.0)

ReflectionClass::getTraitAliases — Returns an array of trait aliases

Opis

public array ReflectionClass::getTraitAliases ( 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

Returns an array with new method names in keys and original names (in the format "TraitName::original") in values. Returns NULL in case of an error.

ReflectionClass::getStaticPropertyValue
ReflectionClass::getTraitNames
ReflectionClass


Returns an array of names of traits used by this class

ReflectionClass::getTraitAliases
ReflectionClass::getTraits
ReflectionClass
PHP Manual

ReflectionClass::getTraitNames

(PHP > 5.4.0)

ReflectionClass::getTraitNames — Returns an array of names of traits used by this class

Opis

public array ReflectionClass::getTraitNames ( 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

Returns an array with trait names in values. Returns NULL in case of an error.

ReflectionClass::getTraitAliases
ReflectionClass::getTraits
ReflectionClass


Returns an array of traits used by this class

ReflectionClass::getTraitNames
ReflectionClass::hasConstant
ReflectionClass
PHP Manual

ReflectionClass::getTraits

(PHP > 5.4.0)

ReflectionClass::getTraits — Returns an array of traits used by this class

Opis

public array ReflectionClass::getTraits ( 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

Returns an array with trait names in keys and instances of trait's ReflectionClass in values. Returns NULL in case of an error.

ReflectionClass::getTraitNames
ReflectionClass::hasConstant
ReflectionClass


Checks if constant is defined

ReflectionClass::getTraits
ReflectionClass::hasMethod
ReflectionClass
PHP Manual

ReflectionClass::hasConstant

(PHP 5 >= 5.1.0)

ReflectionClass::hasConstant — Checks if constant is defined

Opis

public bool ReflectionClass::hasConstant ( string $name )

Checks whether the class has a specific constant defined or not.

Parametry

name

The name of the constant being checked for.

Zwracane wartości

TRUE if the constant is defined, otherwise FALSE.

Przykłady

Przykład #1 ReflectionClass::hasConstant() example

<?php
class Foo {
    const c1 = 1;
}

$class = new ReflectionClass("Foo");

var_dump($class->hasConstant("c1"));
var_dump($class->hasConstant("c2"));
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(false)

Zobacz też:

  • ReflectionClass::hasMethod() - Checks if method is defined
  • ReflectionClass::hasProperty() - Checks if property is defined

ReflectionClass::getTraits
ReflectionClass::hasMethod
ReflectionClass


Checks if method is defined

ReflectionClass::hasConstant
ReflectionClass::hasProperty
ReflectionClass
PHP Manual

ReflectionClass::hasMethod

(PHP 5 >= 5.1.0)

ReflectionClass::hasMethod — Checks if method is defined

Opis

public bool ReflectionClass::hasMethod ( string $name )

Checks whether a specific method is defined in a class.

Parametry

name

Name of the method being checked for.

Zwracane wartości

TRUE if it has the method, otherwise FALSE

Przykłady

Przykład #1 ReflectionClass::hasMethod() example

<?php
Class C {
    public function publicFoo() {
        return true;
    }

    protected function protectedFoo() {
        return true;
    }

    private function privateFoo() {
        return true;
    }

    static function staticFoo() {
        return true;
    }
}

$rc = new ReflectionClass("C");

var_dump($rc->hasMethod('publicFoo'));

var_dump($rc->hasMethod('protectedFoo'));

var_dump($rc->hasMethod('privateFoo'));

var_dump($rc->hasMethod('staticFoo'));

// C should not have method bar
var_dump($rc->hasMethod('bar'));

// Method names are case insensitive
var_dump($rc->hasMethod('PUBLICfOO'));
?>

Powyższy przykład wyświetli:

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)

Zobacz też:

  • ReflectionClass::hasConstant() - Checks if constant is defined
  • ReflectionClass::hasProperty() - Checks if property is defined

ReflectionClass::hasConstant
ReflectionClass::hasProperty
ReflectionClass


Checks if property is defined

ReflectionClass::hasMethod
ReflectionClass::implementsInterface
ReflectionClass
PHP Manual

ReflectionClass::hasProperty

(PHP 5 >= 5.1.0)

ReflectionClass::hasProperty — Checks if property is defined

Opis

public bool ReflectionClass::hasProperty ( string $name )

Checks whether the specified property is defined.

Parametry

name

Name of the property being checked for.

Zwracane wartości

TRUE if it has the property, otherwise FALSE

Przykłady

Przykład #1 ReflectionClass::hasProperty() example

<?php
class Foo {
    public    $p1;
    protected $p2;
    private   $p3;

}

$obj = new ReflectionObject(new Foo());

var_dump($obj->hasProperty("p1"));
var_dump($obj->hasProperty("p2"));
var_dump($obj->hasProperty("p3"));
var_dump($obj->hasProperty("p4"));
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
bool(true)
bool(true)
bool(false)

Zobacz też:

  • ReflectionClass::hasConstant() - Checks if constant is defined
  • ReflectionClass::hasMethod() - Checks if method is defined

ReflectionClass::hasMethod
ReflectionClass::implementsInterface
ReflectionClass


Implements interface

ReflectionClass::hasProperty
ReflectionClass::inNamespace
ReflectionClass
PHP Manual

ReflectionClass::implementsInterface

(PHP 5)

ReflectionClass::implementsInterface — Implements interface

Opis

public bool ReflectionClass::implementsInterface ( string $interface )

Checks whether it implements an interface.

Parametry

interface

The interface name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ReflectionClass::isInterface() - Checks if interface
  • interface_exists() - Checks if the interface has been defined
  • Object Interfaces

ReflectionClass::hasProperty
ReflectionClass::inNamespace
ReflectionClass


Checks if in namespace

ReflectionClass::implementsInterface
ReflectionClass::isAbstract
ReflectionClass
PHP Manual

ReflectionClass::inNamespace

(PHP 5 >= 5.3.0)

ReflectionClass::inNamespace — Checks if in namespace

Opis

public bool ReflectionClass::inNamespace ( void )

Checks if this class is defined in a namespace.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 ReflectionClass::inNamespace() example

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

Powyższy przykład wyświetli:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

Zobacz też:

  • ReflectionClass::getNamespaceName() - Gets namespace name
  • PHP Namespaces

ReflectionClass::implementsInterface
ReflectionClass::isAbstract
ReflectionClass


Checks if class is abstract

ReflectionClass::inNamespace
ReflectionClass::isCloneable
ReflectionClass
PHP Manual

ReflectionClass::isAbstract

(PHP 5)

ReflectionClass::isAbstract — Checks if class is abstract

Opis

public bool ReflectionClass::isAbstract ( void )

Checks if the class is abstract.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 ReflectionClass::isAbstract() example

<?php
class          TestClass { }
abstract class TestAbstractClass { }

$testClass     = new ReflectionClass('TestClass');
$abstractClass = new ReflectionClass('TestAbstractClass');

var_dump($testClass->isAbstract());
var_dump($abstractClass->isAbstract());
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:

  • ReflectionClass::isInterface() - Checks if interface
  • Class Abstraction

ReflectionClass::inNamespace
ReflectionClass::isCloneable
ReflectionClass


Returns whether this class is cloneable

ReflectionClass::isAbstract
ReflectionClass::isFinal
ReflectionClass
PHP Manual

ReflectionClass::isCloneable

(PHP > 5.4.0)

ReflectionClass::isCloneable — Returns whether this class is cloneable

Opis

public bool ReflectionClass::isCloneable ( 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

Returns TRUE if the class is cloneable, FALSE otherwise.

ReflectionClass::isAbstract
ReflectionClass::isFinal
ReflectionClass


Checks if class is final

ReflectionClass::isCloneable
ReflectionClass::isInstance
ReflectionClass
PHP Manual

ReflectionClass::isFinal

(PHP 5)

ReflectionClass::isFinal — Checks if class is final

Opis

public bool ReflectionClass::isFinal ( void )

Checks if a class is final.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 ReflectionClass::isAbstract() example

<?php
class       TestClass { }
final class TestFinalClass { }

$normalClass = new ReflectionClass('TestClass');
$finalClass  = new ReflectionClass('TestFinalClass');

var_dump($normalClass->isFinal());
var_dump($finalClass->isFinal());

?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:

  • ReflectionClass::isAbstract() - Checks if class is abstract
  • Final Keyword

ReflectionClass::isCloneable
ReflectionClass::isInstance
ReflectionClass


Checks class for instance

ReflectionClass::isFinal
ReflectionClass::isInstantiable
ReflectionClass
PHP Manual

ReflectionClass::isInstance

(PHP 5)

ReflectionClass::isInstance — Checks class for instance

Opis

public bool ReflectionClass::isInstance ( object $object )

Checks if an object is an instance of a class.

Parametry

object

The object being compared to.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 ReflectionClass::isInstance() related examples

<?php
// Example usage
$class = new ReflectionClass('Foo');

if ($class->isInstance($arg)) {
    echo "Yes";
}

// Equivalent to
if ($arg instanceof Foo) {
    echo "Yes";
}

// Equivalent to
if (is_a($arg, 'Foo')) {
    echo "Yes";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Yes
Yes
Yes

Zobacz też:

  • ReflectionClass::isInterface() - Checks if interface
  • Type operators (instanceof)
  • Object Interfaces
  • is_a() - Zwraca TRUE jeżeli obiekt jest tej klasy, lub ta klasa jest jednym z jego przodków

ReflectionClass::isFinal
ReflectionClass::isInstantiable
ReflectionClass


Checks if instantiable

ReflectionClass::isInstance
ReflectionClass::isInterface
ReflectionClass
PHP Manual

ReflectionClass::isInstantiable

(PHP 5)

ReflectionClass::isInstantiable — Checks if instantiable

Opis

public bool ReflectionClass::isInstantiable ( void )

Checks if the class is instanciable.

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

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 ReflectionClass::isInstantiable() example

<?php
class C { }

interface iface {
    function f1();
}

class ifaceImpl implements iface {
    function f1() {}
}

abstract class abstractClass {
    function f1() { }
    abstract function f2();
}

class D extends abstractClass {
    function f2() { }
}

$classes = array("C", "iface", "ifaceImpl", "abstractClass", "D");

foreach($classes  as $class ) {
    $reflectionClass = new ReflectionClass($class);
    echo "Is $class instantiable?  ";
    var_dump($reflectionClass->IsInstantiable());
}

?>

Powyższy przykład wyświetli:

Is C instantiable?  bool(true)
Is iface instantiable?  bool(false)
Is ifaceImpl instantiable?  bool(true)
Is abstractClass instantiable?  bool(false)
Is D instantiable?  bool(true)

Zobacz też:

  • ReflectionClass::isInstance() - Checks class for instance

ReflectionClass::isInstance
ReflectionClass::isInterface
ReflectionClass


Checks if interface

ReflectionClass::isInstantiable
ReflectionClass::isInternal
ReflectionClass
PHP Manual

ReflectionClass::isInterface

(PHP 5)

ReflectionClass::isInterface — Checks if interface

Opis

public bool ReflectionClass::isInterface ( void )

Checks whether the class is an interface.

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

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ReflectionClass::isInstance() - Checks class for instance

ReflectionClass::isInstantiable
ReflectionClass::isInternal
ReflectionClass


Checks if internal

ReflectionClass::isInterface
ReflectionClass::isIterateable
ReflectionClass
PHP Manual

ReflectionClass::isInternal

(PHP 5)

ReflectionClass::isInternal — Checks if internal

Opis

public bool ReflectionClass::isInternal ( void )

Checks whether the class is internal, as opposed to user-defined.

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

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ReflectionClass::isUserDefined() - Checks if user defined

ReflectionClass::isInterface
ReflectionClass::isIterateable
ReflectionClass


Checks if iterateable

ReflectionClass::isInternal
ReflectionClass::isSubclassOf
ReflectionClass
PHP Manual

ReflectionClass::isIterateable

(PHP 5)

ReflectionClass::isIterateable — Checks if iterateable

Opis

public bool ReflectionClass::isIterateable ( void )

Checks whether the class is iterateable.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 ReflectionClass::isIterateable() example

<?php

class IteratorClass implements Iterator {
    public function __construct() { }
    public function key() { }
    public function current() { }
    function next() { }
    function valid() { }
    function rewind() { }
}
class DerivedClass extends IteratorClass { }
class NonIterator { }

function dump_iterateable($class) {
    $reflection = new ReflectionClass($class);
    var_dump($reflection->isIterateable());
}

$classes = array("ArrayObject", "IteratorClass", "DerivedClass", "NonIterator");

foreach ($classes as $class) {
    echo "Is $class iterateable? ";
    dump_iterateable($class);
}
?>

Powyższy przykład wyświetli:

Is ArrayObject iterateable? bool(true)
Is IteratorClass iterateable? bool(true)
Is DerivedClass iterateable? bool(true)
Is NonIterator iterateable? bool(false)

Zobacz też:

  • ReflectionClass::__construct() - Constructs a ReflectionClass

ReflectionClass::isInternal
ReflectionClass::isSubclassOf
ReflectionClass


Checks if a subclass

ReflectionClass::isIterateable
ReflectionClass::isTrait
ReflectionClass
PHP Manual

ReflectionClass::isSubclassOf

(PHP 5)

ReflectionClass::isSubclassOf — Checks if a subclass

Opis

public bool ReflectionClass::isSubclassOf ( string $class )

Checks if the class is a subclass of a specified class.

Parametry

class

The class name being checked against.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ReflectionClass::isInterface() - Checks if interface
  • is_subclass_of() - Zwraca TRUE jeżeli klasa jest jednym z przodków obiektu
  • get_parent_class() - Pobiera nazwę klasy przodka dla obiektu lub klasy

ReflectionClass::isIterateable
ReflectionClass::isTrait
ReflectionClass


Returns whether this is a trait

ReflectionClass::isSubclassOf
ReflectionClass::isUserDefined
ReflectionClass
PHP Manual

ReflectionClass::isTrait

(PHP > 5.4.0)

ReflectionClass::isTrait — Returns whether this is a trait

Opis

public bool ReflectionClass::isTrait ( 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

Returns TRUE if this is a trait, FALSE otherwise. Returns NULL in case of an error.

ReflectionClass::isSubclassOf
ReflectionClass::isUserDefined
ReflectionClass


Checks if user defined

ReflectionClass::isTrait
ReflectionClass::newInstance
ReflectionClass
PHP Manual

ReflectionClass::isUserDefined

(PHP 5)

ReflectionClass::isUserDefined — Checks if user defined

Opis

public bool ReflectionClass::isUserDefined ( void )

Checks whether the class is user-defined, as opposed to internal.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • ReflectionClass::isInternal() - Checks if internal

ReflectionClass::isTrait
ReflectionClass::newInstance
ReflectionClass


Creates a new class instance from given arguments.

ReflectionClass::isUserDefined
ReflectionClass::newInstanceArgs
ReflectionClass
PHP Manual

ReflectionClass::newInstance

(PHP 5)

ReflectionClass::newInstance — Creates a new class instance from given arguments.

Opis

public object ReflectionClass::newInstance ( mixed $args [, mixed $... ] )

Creates a new instance of the class. The given arguments are passed to the class constructor.

Parametry

args

Accepts a variable number of arguments which are passed to the class constructor, much like call_user_func().

Zwracane wartości

Błędy/Wyjątki

A ReflectionException if the class constructor is not public.

A ReflectionException if the class does not have a constructor and the args parameter contains one or more parameters.

Zobacz też:

  • ReflectionClass::newInstanceArgs() - Creates a new class instance from given arguments.
  • ReflectionClass::newInstanceWithoutConstructor() - Creates a new class instance without invoking the constructor.

ReflectionClass::isUserDefined
ReflectionClass::newInstanceArgs
ReflectionClass


Creates a new class instance from given arguments.

ReflectionClass::newInstance
ReflectionClass::newInstanceWithoutConstructor
ReflectionClass
PHP Manual

ReflectionClass::newInstanceArgs

(PHP 5 >= 5.1.3)

ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments.

Opis

public object ReflectionClass::newInstanceArgs ([ array $args ] )

Creates a new instance of the class, the given arguments are passed to the class constructor.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

args

The parameters to be passed to the class constructor as an array.

Zwracane wartości

Returns a new instance of the class.

Błędy/Wyjątki

A ReflectionException if the class constructor is not public.

A ReflectionException if the class does not have a constructor and the args parameter contains one or more parameters.

Zobacz też:

  • ReflectionClass::newInstance() - Creates a new class instance from given arguments.
  • ReflectionClass::newInstanceWithoutConstructor() - Creates a new class instance without invoking the constructor.

ReflectionClass::newInstance
ReflectionClass::newInstanceWithoutConstructor
ReflectionClass


Creates a new class instance without invoking the constructor.

ReflectionClass::newInstanceArgs
ReflectionClass::setStaticPropertyValue
ReflectionClass
PHP Manual

ReflectionClass::newInstanceWithoutConstructor

(PHP > 5.4.0)

ReflectionClass::newInstanceWithoutConstructor — Creates a new class instance without invoking the constructor.

Opis

public object ReflectionClass::newInstanceWithoutConstructor ( void )

Creates a new instance of the class without invoking the constructor.

Parametry

Zwracane wartości

Błędy/Wyjątki

A ReflectionException if the class is an internal class that cannot be instantiated without invoking the constructor.

Zobacz też:

  • ReflectionClass::newInstance() - Creates a new class instance from given arguments.
  • ReflectionClass::newInstanceArgs() - Creates a new class instance from given arguments.

ReflectionClass::newInstanceArgs
ReflectionClass::setStaticPropertyValue
ReflectionClass


Sets static property value

ReflectionClass::newInstanceWithoutConstructor
ReflectionClass::__toString
ReflectionClass
PHP Manual

ReflectionClass::setStaticPropertyValue

(PHP 5 >= 5.1.0)

ReflectionClass::setStaticPropertyValue — Sets static property value

Opis

public void ReflectionClass::setStaticPropertyValue ( string $name , string $value )

Sets static property value.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Property name.

value

New property value.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ReflectionClass::getStaticPropertyValue() - Gets static property value

ReflectionClass::newInstanceWithoutConstructor
ReflectionClass::__toString
ReflectionClass


Returns the string representation of the ReflectionClass object.

ReflectionClass::setStaticPropertyValue
ReflectionZendExtension
ReflectionClass
PHP Manual

ReflectionClass::__toString

(PHP 5)

ReflectionClass::__toString — Returns the string representation of the ReflectionClass object.

Opis

public string ReflectionClass::__toString ( void )

Returns the string representation of the ReflectionClass object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A string representation of this ReflectionClass instance.

Przykłady

Przykład #1 ReflectionClass::__toString() example

<?php
$reflectionClass = new ReflectionClass('Exception');
echo $reflectionClass->__toString();
?>

Powyższy przykład wyświetli:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

Zobacz też:

  • ReflectionClass::export() - Exports a class
  • __toString()

ReflectionClass::setStaticPropertyValue
ReflectionZendExtension
ReflectionClass


The ReflectionZendExtension class

(PHP > 5.4.0)

Wstęp

Krótki opis klasy

ReflectionZendExtension implements Reflector {
/* Właściwości */
public $name ;
/* Metody */
final private void __clone ( void )
__construct ( string $name )
public static string export ( string $name [, string $return ] )
public string getAuthor ( void )
public string getCopyright ( void )
public string getName ( void )
public string getURL ( void )
public string getVersion ( void )
public string __toString ( void )
}

Właściwości

name

Name of the extension. Read-only, throws ReflectionException in attempt to write.

Spis treści

  • ReflectionZendExtension::__clone — Clone handler
  • ReflectionZendExtension::__construct — Constructor
  • ReflectionZendExtension::export — Export
  • ReflectionZendExtension::getAuthor — Gets author
  • ReflectionZendExtension::getCopyright — Gets copyright
  • ReflectionZendExtension::getName — Gets name
  • ReflectionZendExtension::getURL — Gets URL
  • ReflectionZendExtension::getVersion — Gets version
  • ReflectionZendExtension::__toString — To string handler
ReflectionClass::__toString
ReflectionZendExtension::__clone
Reflection


Clone handler

ReflectionZendExtension
ReflectionZendExtension::__construct
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::__clone

(PHP > 5.4.0)

ReflectionZendExtension::__clone — Clone handler

Opis

final private void ReflectionZendExtension::__clone ( 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

ReflectionZendExtension
ReflectionZendExtension::__construct
ReflectionZendExtension


Constructor

ReflectionZendExtension::__clone
ReflectionZendExtension::export
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::__construct

(PHP > 5.4.0)

ReflectionZendExtension::__construct — Constructor

Opis

ReflectionZendExtension::__construct ( string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

Zwracane wartości

ReflectionZendExtension::__clone
ReflectionZendExtension::export
ReflectionZendExtension


Export

ReflectionZendExtension::__construct
ReflectionZendExtension::getAuthor
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::export

(PHP > 5.4.0)

ReflectionZendExtension::export — Export

Opis

public static string ReflectionZendExtension::export ( string $name [, string $return ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

name

return

Zwracane wartości

ReflectionZendExtension::__construct
ReflectionZendExtension::getAuthor
ReflectionZendExtension


Gets author

ReflectionZendExtension::export
ReflectionZendExtension::getCopyright
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getAuthor

(PHP > 5.4.0)

ReflectionZendExtension::getAuthor — Gets author

Opis

public string ReflectionZendExtension::getAuthor ( 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

ReflectionZendExtension::export
ReflectionZendExtension::getCopyright
ReflectionZendExtension


Gets copyright

ReflectionZendExtension::getAuthor
ReflectionZendExtension::getName
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getCopyright

(PHP > 5.4.0)

ReflectionZendExtension::getCopyright — Gets copyright

Opis

public string ReflectionZendExtension::getCopyright ( 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

ReflectionZendExtension::getAuthor
ReflectionZendExtension::getName
ReflectionZendExtension


Gets name

ReflectionZendExtension::getCopyright
ReflectionZendExtension::getURL
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getName

(PHP > 5.4.0)

ReflectionZendExtension::getName — Gets name

Opis

public string ReflectionZendExtension::getName ( 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

ReflectionZendExtension::getCopyright
ReflectionZendExtension::getURL
ReflectionZendExtension


Gets URL

ReflectionZendExtension::getName
ReflectionZendExtension::getVersion
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getURL

(PHP > 5.4.0)

ReflectionZendExtension::getURL — Gets URL

Opis

public string ReflectionZendExtension::getURL ( 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

ReflectionZendExtension::getName
ReflectionZendExtension::getVersion
ReflectionZendExtension


Gets version

ReflectionZendExtension::getURL
ReflectionZendExtension::__toString
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::getVersion

(PHP > 5.4.0)

ReflectionZendExtension::getVersion — Gets version

Opis

public string ReflectionZendExtension::getVersion ( 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

ReflectionZendExtension::getURL
ReflectionZendExtension::__toString
ReflectionZendExtension


To string handler

ReflectionZendExtension::getVersion
ReflectionExtension
ReflectionZendExtension
PHP Manual

ReflectionZendExtension::__toString

(PHP > 5.4.0)

ReflectionZendExtension::__toString — To string handler

Opis

public string ReflectionZendExtension::__toString ( 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

ReflectionZendExtension::getVersion
ReflectionExtension
ReflectionZendExtension


The ReflectionExtension class

(PHP 5)

Wstęp

The ReflectionExtension class reports information about an extension.

Krótki opis klasy

ReflectionExtension implements Reflector {
/* Właściwości */
public $name ;
/* Metody */
final private void __clone ( void )
__construct ( string $name )
public static string export ( string $name [, string $return = false ] )
public array getClasses ( void )
public array getClassNames ( void )
public array getConstants ( void )
public array getDependencies ( void )
public array getFunctions ( void )
public array getINIEntries ( void )
public string getName ( void )
public string getVersion ( void )
public void info ( void )
public void isPersistent ( void )
public void isTemporary ( void )
public string __toString ( void )
}

Właściwości

name

Name of the extension, same as calling the ReflectionExtension::getName() method.

Spis treści

  • ReflectionExtension::__clone — Clones
  • ReflectionExtension::__construct — Constructs a ReflectionExtension
  • ReflectionExtension::export — Export
  • ReflectionExtension::getClasses — Gets classes
  • ReflectionExtension::getClassNames — Gets class names
  • ReflectionExtension::getConstants — Gets constants
  • ReflectionExtension::getDependencies — Gets dependencies
  • ReflectionExtension::getFunctions — Gets extension functions
  • ReflectionExtension::getINIEntries — Gets extension ini entries
  • ReflectionExtension::getName — Gets extension name
  • ReflectionExtension::getVersion — Gets extension version
  • ReflectionExtension::info — Print extension info
  • ReflectionExtension::isPersistent — Returns whether this extension is persistent
  • ReflectionExtension::isTemporary — Returns whether this extension is temporary
  • ReflectionExtension::__toString — To string
ReflectionZendExtension::__toString
ReflectionExtension::__clone
Reflection


Clones

ReflectionExtension
ReflectionExtension::__construct
ReflectionExtension
PHP Manual

ReflectionExtension::__clone

(PHP 5)

ReflectionExtension::__clone — Clones

Opis

final private void ReflectionExtension::__clone ( void )

The clone method prevents an object from being cloned. Reflection objects cannot be cloned.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

No value is returned, if called a fatal error will occur.

Zobacz też:

  • ReflectionExtension::__construct() - Constructs a ReflectionExtension
  • Object cloning

ReflectionExtension
ReflectionExtension::__construct
ReflectionExtension


Constructs a ReflectionExtension

ReflectionExtension::__clone
ReflectionExtension::export
ReflectionExtension
PHP Manual

ReflectionExtension::__construct

(PHP 5)

ReflectionExtension::__construct — Constructs a ReflectionExtension

Opis

ReflectionExtension::__construct ( string $name )

Construct a ReflectionExtension object.

Parametry

name

Name of the extension.

Zwracane wartości

A ReflectionExtension object.

Przykłady

Przykład #1 ReflectionExtension example

<?php
$ext = new ReflectionExtension('Reflection');

printf('Extension: %s (version: %s)', $ext->getName(), $ext->getVersion());
?>

Powyższy przykład wyświetli coś podobnego do:

Extension: Reflection (version: $Revision: 299908 $)

Zobacz też:

  • ReflectionExtension::info() - Print extension info
  • Constructors

ReflectionExtension::__clone
ReflectionExtension::export
ReflectionExtension


Export

ReflectionExtension::__construct
ReflectionExtension::getClasses
ReflectionExtension
PHP Manual

ReflectionExtension::export

(PHP 5)

ReflectionExtension::export — Export

Opis

public static string ReflectionExtension::export ( string $name [, string $return = false ] )

Exports a reflected extension. The output format of this function is the same as the CLI argument --re [extension].

Parametry

name

Refleksja do eksportu.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Zwracane wartości

Jeśli parametr return jest ustawiony na TRUE, eksport jest zwracany jako string, w przeciwnym przypadku jako NULL.

Zobacz też:

  • ReflectionExtension::info() - Print extension info

ReflectionExtension::__construct
ReflectionExtension::getClasses
ReflectionExtension


Gets classes

ReflectionExtension::export
ReflectionExtension::getClassNames
ReflectionExtension
PHP Manual

ReflectionExtension::getClasses

(PHP 5)

ReflectionExtension::getClasses — Gets classes

Opis

public array ReflectionExtension::getClasses ( void )

Gets a list of classes from an extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of ReflectionClass objects, one for each class within the extension. If no classes are defined, an empty array is returned.

Przykłady

Przykład #1 ReflectionExtension::getClasses() example

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClasses());
?>

Powyższy przykład wyświetli coś podobnego do:

array(1) {
  ["XMLWriter"]=>
  &object(ReflectionClass)#2 (1) {
    ["name"]=>
    string(9) "XMLWriter"
  }
}

Zobacz też:

  • ReflectionExtension::getClassNames() - Gets class names

ReflectionExtension::export
ReflectionExtension::getClassNames
ReflectionExtension


Gets class names

ReflectionExtension::getClasses
ReflectionExtension::getConstants
ReflectionExtension
PHP Manual

ReflectionExtension::getClassNames

(PHP 5)

ReflectionExtension::getClassNames — Gets class names

Opis

public array ReflectionExtension::getClassNames ( void )

Gets a listing of class names as defined in the extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of class names, as defined in the extension. If no classes are defined, an empty array is returned.

Przykłady

Przykład #1 ReflectionExtension::getClassNames() example

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClassNames());
?>

Powyższy przykład wyświetli coś podobnego do:

array(1) {
  [0]=>
  string(9) "XMLWriter"
}

Zobacz też:

  • ReflectionExtension::getClasses() - Gets classes
  • ReflectionExtension::getName() - Gets extension name

ReflectionExtension::getClasses
ReflectionExtension::getConstants
ReflectionExtension


Gets constants

ReflectionExtension::getClassNames
ReflectionExtension::getDependencies
ReflectionExtension
PHP Manual

ReflectionExtension::getConstants

(PHP 5)

ReflectionExtension::getConstants — Gets constants

Opis

public array ReflectionExtension::getConstants ( void )

Get defined constants from an extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An associative array with constant names as keys.

Przykłady

Przykład #1 ReflectionExtension::getConstants() example

<?php
$ext = new ReflectionExtension('DOM');

print_r($ext->getConstants());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [XML_ELEMENT_NODE] => 1
    [XML_ATTRIBUTE_NODE] => 2
    [XML_TEXT_NODE] => 3
    [XML_CDATA_SECTION_NODE] => 4
    [XML_ENTITY_REF_NODE] => 5
    [XML_ENTITY_NODE] => 6
    [XML_PI_NODE] => 7
    [XML_COMMENT_NODE] => 8
    [XML_DOCUMENT_NODE] => 9
    [XML_DOCUMENT_TYPE_NODE] => 10
    [XML_DOCUMENT_FRAG_NODE] => 11
    [XML_NOTATION_NODE] => 12
    [XML_HTML_DOCUMENT_NODE] => 13
    [XML_DTD_NODE] => 14
    [XML_ELEMENT_DECL_NODE] => 15
    [XML_ATTRIBUTE_DECL_NODE] => 16
    [XML_ENTITY_DECL_NODE] => 17
    [XML_NAMESPACE_DECL_NODE] => 18
    [XML_LOCAL_NAMESPACE] => 18
    [XML_ATTRIBUTE_CDATA] => 1
    [XML_ATTRIBUTE_ID] => 2
    [XML_ATTRIBUTE_IDREF] => 3
    [XML_ATTRIBUTE_IDREFS] => 4
    [XML_ATTRIBUTE_ENTITY] => 6
    [XML_ATTRIBUTE_NMTOKEN] => 7
    [XML_ATTRIBUTE_NMTOKENS] => 8
    [XML_ATTRIBUTE_ENUMERATION] => 9
    [XML_ATTRIBUTE_NOTATION] => 10
    [DOM_PHP_ERR] => 0
    [DOM_INDEX_SIZE_ERR] => 1
    [DOMSTRING_SIZE_ERR] => 2
    [DOM_HIERARCHY_REQUEST_ERR] => 3
    [DOM_WRONG_DOCUMENT_ERR] => 4
    [DOM_INVALID_CHARACTER_ERR] => 5
    [DOM_NO_DATA_ALLOWED_ERR] => 6
    [DOM_NO_MODIFICATION_ALLOWED_ERR] => 7
    [DOM_NOT_FOUND_ERR] => 8
    [DOM_NOT_SUPPORTED_ERR] => 9
    [DOM_INUSE_ATTRIBUTE_ERR] => 10
    [DOM_INVALID_STATE_ERR] => 11
    [DOM_SYNTAX_ERR] => 12
    [DOM_INVALID_MODIFICATION_ERR] => 13
    [DOM_NAMESPACE_ERR] => 14
    [DOM_INVALID_ACCESS_ERR] => 15
    [DOM_VALIDATION_ERR] => 16
)

Zobacz też:

  • ReflectionExtension::getINIEntries() - Gets extension ini entries

ReflectionExtension::getClassNames
ReflectionExtension::getDependencies
ReflectionExtension


Gets dependencies

ReflectionExtension::getConstants
ReflectionExtension::getFunctions
ReflectionExtension
PHP Manual

ReflectionExtension::getDependencies

(PHP 5)

ReflectionExtension::getDependencies — Gets dependencies

Opis

public array ReflectionExtension::getDependencies ( void )

Gets dependencies, by listing both required and conflicting dependencies.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An associative array with dependencies as keys and either Required, Optional or Conflicts as the values.

Przykłady

Przykład #1 ReflectionExtension::getDependencies() example

<?php
$dom = new ReflectionExtension('dom');

print_r($dom->getDependencies());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [libxml] => Required
    [domxml] => Conflicts
)

Zobacz też:

  • ReflectionClass::getVersion()

ReflectionExtension::getConstants
ReflectionExtension::getFunctions
ReflectionExtension


Gets extension functions

ReflectionExtension::getDependencies
ReflectionExtension::getINIEntries
ReflectionExtension
PHP Manual

ReflectionExtension::getFunctions

(PHP 5)

ReflectionExtension::getFunctions — Gets extension functions

Opis

public array ReflectionExtension::getFunctions ( void )

Get defined functions from an extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An associative array of ReflectionFunction objects, for each function defined in the extension with the keys being the function names. If no function are defined, an empty array is returned.

Przykłady

Przykład #1 ReflectionExtension::getFunctions() example

<?php
$dom = new ReflectionExtension('SimpleXML');

print_r($dom->getFunctions());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [simplexml_load_file] => ReflectionFunction Object
        (
            [name] => simplexml_load_file
        )

    [simplexml_load_string] => ReflectionFunction Object
        (
            [name] => simplexml_load_string
        )

    [simplexml_import_dom] => ReflectionFunction Object
        (
            [name] => simplexml_import_dom
        )

)

Zobacz też:

  • ReflectionExtension::getClasses() - Gets classes

ReflectionExtension::getDependencies
ReflectionExtension::getINIEntries
ReflectionExtension


Gets extension ini entries

ReflectionExtension::getFunctions
ReflectionExtension::getName
ReflectionExtension
PHP Manual

ReflectionExtension::getINIEntries

(PHP 5)

ReflectionExtension::getINIEntries — Gets extension ini entries

Opis

public array ReflectionExtension::getINIEntries ( void )

Get the ini entries for an extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An associative array with the ini entries as keys, with their defined values as values.

Przykłady

Przykład #1 ReflectionExtension::getINIEntries() example

<?php
$ext = new ReflectionExtension('mysql');

print_r($ext->getINIEntries());
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [mysql.allow_persistent] => 1
    [mysql.max_persistent] => -1
    [mysql.max_links] => -1
    [mysql.default_host] =>
    [mysql.default_user] =>
    [mysql.default_password] =>
    [mysql.default_port] =>
    [mysql.default_socket] =>
    [mysql.connect_timeout] => 60
    [mysql.trace_mode] =>
    [mysql.allow_local_infile] => 1
    [mysql.cache_size] => 2000
)

Zobacz też:

  • ReflectionExtension::getConstants() - Gets constants

ReflectionExtension::getFunctions
ReflectionExtension::getName
ReflectionExtension


Gets extension name

ReflectionExtension::getINIEntries
ReflectionExtension::getVersion
ReflectionExtension
PHP Manual

ReflectionExtension::getName

(PHP 5)

ReflectionExtension::getName — Gets extension name

Opis

public string ReflectionExtension::getName ( void )

Gets the extensions name.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The extensions name.

Przykłady

Przykład #1 ReflectionExtension::getName() example

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getName());
?>

Powyższy przykład wyświetli coś podobnego do:

string(6) "mysqli"

Zobacz też:

  • ReflectionExtension::getClassNames() - Gets class names

ReflectionExtension::getINIEntries
ReflectionExtension::getVersion
ReflectionExtension


Gets extension version

ReflectionExtension::getName
ReflectionExtension::info
ReflectionExtension
PHP Manual

ReflectionExtension::getVersion

(PHP 5)

ReflectionExtension::getVersion — Gets extension version

Opis

public string ReflectionExtension::getVersion ( void )

Gets the version of the extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The version of the extension.

Przykłady

Przykład #1 ReflectionExtension::getVersion() example

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getVersion());
?>

Powyższy przykład wyświetli coś podobnego do:

string(3) "0.1"

Zobacz też:

  • ReflectionExtension::info() - Print extension info

ReflectionExtension::getName
ReflectionExtension::info
ReflectionExtension


Print extension info

ReflectionExtension::getVersion
ReflectionExtension::isPersistent
ReflectionExtension
PHP Manual

ReflectionExtension::info

(PHP 5)

ReflectionExtension::info — Print extension info

Opis

public void ReflectionExtension::info ( void )

Prints out the "phpinfo()" snippet for the given extension.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Information about the extension.

Przykłady

Przykład #1 ReflectionExtension::info() example

<?php
$ext = new ReflectionExtension('mysqli');
$ext->info();
?>

Powyższy przykład wyświetli coś podobnego do:

mysqli

MysqlI Support => enabled
Client API library version => mysqlnd 5.0.5-dev - 081106 - $Revision: 315808 $
Active Persistent Links => 0
Inactive Persistent Links => 0
Active Links => 0
Persistent cache => enabled
put_hits => 0
put_misses => 0
get_hits => 0
get_misses => 0
size => 2000
free_items => 2000
references => 2

Directive => Local Value => Master Value
mysqli.max_links => Unlimited => Unlimited
mysqli.max_persistent => Unlimited => Unlimited
mysqli.allow_persistent => On => On
mysqli.default_host => no value => no value
mysqli.default_user => no value => no value
mysqli.default_pw => no value => no value
mysqli.default_port => 3306 => 3306
mysqli.default_socket => no value => no value
mysqli.reconnect => Off => Off
mysqli.allow_local_infile => On => On
mysqli.cache_size => 2000 => 2000

Zobacz też:

  • ReflectionExtension::getName() - Gets extension name
  • phpinfo() - Outputs information about PHP's configuration

ReflectionExtension::getVersion
ReflectionExtension::isPersistent
ReflectionExtension


Returns whether this extension is persistent

ReflectionExtension::info
ReflectionExtension::isTemporary
ReflectionExtension
PHP Manual

ReflectionExtension::isPersistent

(PHP > 5.4.0)

ReflectionExtension::isPersistent — Returns whether this extension is persistent

Opis

public void ReflectionExtension::isPersistent ( 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

Returns TRUE for extensions loaded by extension, FALSE otherwise.

Zobacz też:

  • ReflectionExtension::isTemporary() - Returns whether this extension is temporary

ReflectionExtension::info
ReflectionExtension::isTemporary
ReflectionExtension


Returns whether this extension is temporary

ReflectionExtension::isPersistent
ReflectionExtension::__toString
ReflectionExtension
PHP Manual

ReflectionExtension::isTemporary

(PHP > 5.4.0)

ReflectionExtension::isTemporary — Returns whether this extension is temporary

Opis

public void ReflectionExtension::isTemporary ( 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

Returns TRUE for extensions loaded by dl(), FALSE otherwise.

Zobacz też:

  • ReflectionExtension::isPersistent() - Returns whether this extension is persistent

ReflectionExtension::isPersistent
ReflectionExtension::__toString
ReflectionExtension


To string

ReflectionExtension::isTemporary
ReflectionFunction
ReflectionExtension
PHP Manual

ReflectionExtension::__toString

(PHP 5)

ReflectionExtension::__toString — To string

Opis

public string ReflectionExtension::__toString ( void )

Exports a reflected extension and returns it as a string. This is the same as the ReflectionExtension::export() with the return set to TRUE.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the exported extension as a string, in the same way as the ReflectionExtension::export().

Zobacz też:

  • ReflectionExtension::__construct() - Constructs a ReflectionExtension
  • ReflectionExtension::export() - Export
  • __toString()

ReflectionExtension::isTemporary
ReflectionFunction
ReflectionExtension


The ReflectionFunction class

(PHP 5)

Wstęp

The ReflectionFunction class reports information about a function.

Krótki opis klasy

ReflectionFunction extends ReflectionFunctionAbstract implements Reflector {
/* Stałe */
const integer IS_DEPRECATED = 262144 ;
/* Właściwości */
public $name ;
/* Metody */
public __construct ( mixed $name )
public static string export ( string $name [, string $return ] )
public Closure getClosure ( void )
public mixed invoke ([ mixed $parameter [, mixed $... ]] )
public mixed invokeArgs ( array $args )
public bool isDisabled ( void )
public string __toString ( void )
/* Metody dziedziczone */
final private void ReflectionFunctionAbstract::__clone ( void )
public object ReflectionFunctionAbstract::getClosureThis ( void )
public string ReflectionFunctionAbstract::getDocComment ( void )
public int ReflectionFunctionAbstract::getEndLine ( void )
public ReflectionExtension ReflectionFunctionAbstract::getExtension ( void )
public string ReflectionFunctionAbstract::getExtensionName ( void )
public string ReflectionFunctionAbstract::getFileName ( void )
public string ReflectionFunctionAbstract::getName ( void )
public string ReflectionFunctionAbstract::getNamespaceName ( void )
public int ReflectionFunctionAbstract::getNumberOfParameters ( void )
public int ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void )
public array ReflectionFunctionAbstract::getParameters ( void )
public string ReflectionFunctionAbstract::getShortName ( void )
public int ReflectionFunctionAbstract::getStartLine ( void )
public array ReflectionFunctionAbstract::getStaticVariables ( void )
public bool ReflectionFunctionAbstract::inNamespace ( void )
public bool ReflectionFunctionAbstract::isClosure ( void )
public bool ReflectionFunctionAbstract::isDeprecated ( void )
public bool ReflectionFunctionAbstract::isInternal ( void )
public bool ReflectionFunctionAbstract::isUserDefined ( void )
public bool ReflectionFunctionAbstract::returnsReference ( void )
abstract public void ReflectionFunctionAbstract::__toString ( void )
}

Właściwości

name

Name of the function. Read-only, throws ReflectionException in attempt to write.

Stałe predefiniowane

ReflectionFunction Modifiers

ReflectionFunction::IS_DEPRECATED

Indicates deprecated functions.

Spis treści

  • ReflectionFunction::__construct — Constructs a ReflectionFunction object
  • ReflectionFunction::export — Exports function
  • ReflectionFunction::getClosure — Returns a dynamically created closure for the function
  • ReflectionFunction::invoke — Invokes function
  • ReflectionFunction::invokeArgs — Invokes function args
  • ReflectionFunction::isDisabled — Checks if function is disabled
  • ReflectionFunction::__toString — To string
ReflectionExtension::__toString
ReflectionFunction::__construct
Reflection


Constructs a ReflectionFunction object

ReflectionFunction
ReflectionFunction::export
ReflectionFunction
PHP Manual

ReflectionFunction::__construct

(PHP 5)

ReflectionFunction::__construct — Constructs a ReflectionFunction object

Opis

public ReflectionFunction::__construct ( mixed $name )

Constructs a ReflectionFunction object.

Parametry

name

The name of the function to reflect or a closure.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

A ReflectionException if the name parameter does not contain a valid function.

Rejestr zmian

Wersja | Opis
5.3.0 | name can now be a closure.

Przykłady

Przykład #1 ReflectionFunction::__construct() example

<?php
/**
 * A simple counter
 *
 * @return    int
 */
function counter1()
{
    static $c = 0;
    return ++$c;
}

/**
 * Another simple counter
 *
 * @return    int
 */
$counter2 = function()
{
    static $d = 0;
    return ++$d;

};

function dumpReflectionFunction($func)
{
    // Print out basic information
    printf(
        "\n\n===> The %s function '%s'\n".
        "     declared in %s\n".
        "     lines %d to %d\n",
        $func->isInternal() ? 'internal' : 'user-defined',
        $func->getName(),
        $func->getFileName(),
        $func->getStartLine(),
        $func->getEndline()
    );

    // Print documentation comment
    printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));

    // Print static variables if existant
    if ($statics = $func->getStaticVariables())
    {
        printf("---> Static variables: %s\n", var_export($statics, 1));
    }
}

// Create an instance of the ReflectionFunction class
dumpReflectionFunction(new ReflectionFunction('counter1'));
dumpReflectionFunction(new ReflectionFunction($counter2));
?>

Powyższy przykład wyświetli coś podobnego do:

===> The user-defined function 'counter1'
     declared in Z:\reflectcounter.php
     lines 7 to 11
---> Documentation:
 '/**
 * A simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'c' => 0,
)

===> The user-defined function '{closure}'
     declared in Z:\reflectcounter.php
     lines 18 to 23
---> Documentation:
 '/**
 * Another simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'd' => 0,
)

Zobacz też:

  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • Constructors

ReflectionFunction
ReflectionFunction::export
ReflectionFunction


Exports function

ReflectionFunction::__construct
ReflectionFunction::getClosure
ReflectionFunction
PHP Manual

ReflectionFunction::export

(PHP 5)

ReflectionFunction::export — Exports function

Opis

public static string ReflectionFunction::export ( string $name [, string $return ] )

Exports a Reflected function.

Parametry

name

Refleksja do eksportu.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Zwracane wartości

Jeśli parametr return jest ustawiony na TRUE, eksport jest zwracany jako string, w przeciwnym przypadku jako NULL.

Zobacz też:

  • ReflectionFunction::invoke() - Invokes function

ReflectionFunction::__construct
ReflectionFunction::getClosure
ReflectionFunction


Returns a dynamically created closure for the function

ReflectionFunction::export
ReflectionFunction::invoke
ReflectionFunction
PHP Manual

ReflectionFunction::getClosure

(No version information available, might only be in SVN)

ReflectionFunction::getClosure — Returns a dynamically created closure for the function

Opis

public Closure ReflectionFunction::getClosure ( 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

Returns Closure. Returns NULL in case of an error.

ReflectionFunction::export
ReflectionFunction::invoke
ReflectionFunction


Invokes function

ReflectionFunction::getClosure
ReflectionFunction::invokeArgs
ReflectionFunction
PHP Manual

ReflectionFunction::invoke

(PHP 5)

ReflectionFunction::invoke — Invokes function

Opis

public mixed ReflectionFunction::invoke ([ mixed $parameter [, mixed $... ]] )

Invokes a reflected function.

Parametry

args

The passed in argument list. It accepts a variable number of arguments which are passed to the function much like call_user_func() is.

Zwracane wartości

Returns the result of the invoked function call.

Przykłady

Przykład #1 ReflectionFunction::invoke() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invoke('Dr', 'Phil');
?>

Powyższy przykład wyświetli:

Dr. Phil

Notatki

Informacja:

If the function has arguments that need to be references, then they must be references in the passed argument list.

Zobacz też:

  • ReflectionFunction::export() - Exports function
  • __invoke()
  • call_user_func() - Call the callback given by the first parameter

ReflectionFunction::getClosure
ReflectionFunction::invokeArgs
ReflectionFunction


Invokes function args

ReflectionFunction::invoke
ReflectionFunction::isDisabled
ReflectionFunction
PHP Manual

ReflectionFunction::invokeArgs

(PHP 5 >= 5.1.0)

ReflectionFunction::invokeArgs — Invokes function args

Opis

public mixed ReflectionFunction::invokeArgs ( array $args )

Invokes the function and pass its arguments as array.

Parametry

args

The passed arguments to the function as an array, much like call_user_func_array() works.

Zwracane wartości

Returns the result of the invoked function

Przykłady

Przykład #1 ReflectionFunction::invokeArgs() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invokeArgs(array('Dr', 'Phil'));
?>

Powyższy przykład wyświetli:

Dr. Phil

Przykład #2 ReflectionFunction::invokeArgs() with references example

<?php
function get_false_conditions(array $conditions, array &$false_conditions)
{
    foreach ($conditions as $condition) {
        if (!$condition) {
            $false_conditions[] = $condition;
        }
    }
}

$function_ref     = new ReflectionFunction('get_false_conditions');

$conditions       = array(true, false, -1, 0, 1);
$false_conditions = array();

$function_ref->invokeArgs(array($conditions, &$false_conditions));

var_dump($false_conditions);
?>

Powyższy przykład wyświetli:

array(2) {
  [0]=>
  bool(false)
  [1]=>
  int(0)
}

Notatki

Informacja:

If the function has arguments that need to be references, then they must be references in the passed argument list.

Zobacz też:

  • ReflectionFunction::invoke() - Invokes function
  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters
  • __invoke()
  • call_user_func_array() - Call a callback with an array of parameters

ReflectionFunction::invoke
ReflectionFunction::isDisabled
ReflectionFunction


Checks if function is disabled

ReflectionFunction::invokeArgs
ReflectionFunction::__toString
ReflectionFunction
PHP Manual

ReflectionFunction::isDisabled

(PHP 5)

ReflectionFunction::isDisabled — Checks if function is disabled

Opis

public bool ReflectionFunction::isDisabled ( void )

Checks if the function is disabled, via the disable_functions directive.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if it's disable, otherwise FALSE

Zobacz też:

  • ReflectionFunctionAbstract::isUserDefined() - Checks if user defined
  • disable_functions directive

ReflectionFunction::invokeArgs
ReflectionFunction::__toString
ReflectionFunction


To string

ReflectionFunction::isDisabled
ReflectionFunctionAbstract
ReflectionFunction
PHP Manual

ReflectionFunction::__toString

(PHP 5)

ReflectionFunction::__toString — To string

Opis

public string ReflectionFunction::__toString ( void )

To string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns ReflectionFunction::export()-like output for the function.

Przykłady

Przykład #1 ReflectionFunction::__toString() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo new ReflectionFunction('title');
?>

Powyższy przykład wyświetli coś podobnego do:

Function [ <user> function person ] {
  @@ Command line code 1 - 1

  - Parameters [2] {
    Parameter #0 [ <required> $prefix ]
    Parameter #1 [ <required> $name ]
  }
}

Zobacz też:

  • ReflectionFunction::export() - Exports function
  • ReflectionClass::clone()
  • __toString()

ReflectionFunction::isDisabled
ReflectionFunctionAbstract
ReflectionFunction


The ReflectionFunctionAbstract class

(PHP 5)

Wstęp

A parent class to ReflectionFunction, read its description for details.

Krótki opis klasy

ReflectionFunctionAbstract implements Reflector {
/* Właściwości */
public $name ;
/* Metody */
final private void __clone ( void )
public object getClosureThis ( void )
public string getDocComment ( void )
public int getEndLine ( void )
public ReflectionExtension getExtension ( void )
public string getExtensionName ( void )
public string getFileName ( void )
public string getName ( void )
public string getNamespaceName ( void )
public int getNumberOfParameters ( void )
public int getNumberOfRequiredParameters ( void )
public array getParameters ( void )
public string getShortName ( void )
public int getStartLine ( void )
public array getStaticVariables ( void )
public bool inNamespace ( void )
public bool isClosure ( void )
public bool isDeprecated ( void )
public bool isInternal ( void )
public bool isUserDefined ( void )
public bool returnsReference ( void )
abstract public void __toString ( void )
}

Właściwości

name

Name of the function. Read-only, throws ReflectionException in attempt to write.

Spis treści

  • ReflectionFunctionAbstract::__clone — Clones function
  • ReflectionFunctionAbstract::getClosureThis — Returns this pointer bound to closure
  • ReflectionFunctionAbstract::getDocComment — Gets doc comment
  • ReflectionFunctionAbstract::getEndLine — Gets end line number
  • ReflectionFunctionAbstract::getExtension — Gets extension info
  • ReflectionFunctionAbstract::getExtensionName — Gets extension name
  • ReflectionFunctionAbstract::getFileName — Gets file name
  • ReflectionFunctionAbstract::getName — Gets function name
  • ReflectionFunctionAbstract::getNamespaceName — Gets namespace name
  • ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters
  • ReflectionFunctionAbstract::getParameters — Gets parameters
  • ReflectionFunctionAbstract::getShortName — Gets function short name
  • ReflectionFunctionAbstract::getStartLine — Gets starting line number
  • ReflectionFunctionAbstract::getStaticVariables — Gets static variables
  • ReflectionFunctionAbstract::inNamespace — Checks if function in namespace
  • ReflectionFunctionAbstract::isClosure — Checks if closure
  • ReflectionFunctionAbstract::isDeprecated — Checks if deprecated
  • ReflectionFunctionAbstract::isInternal — Checks if is internal
  • ReflectionFunctionAbstract::isUserDefined — Checks if user defined
  • ReflectionFunctionAbstract::returnsReference — Checks if returns reference
  • ReflectionFunctionAbstract::__toString — To string
ReflectionFunction::__toString
ReflectionFunctionAbstract::__clone
Reflection


Clones function

ReflectionFunctionAbstract
ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::__clone

(PHP 5)

ReflectionFunctionAbstract::__clone — Clones function

Opis

final private void ReflectionFunctionAbstract::__clone ( void )

Clones a function.

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

Zobacz też:

  • Object cloning

ReflectionFunctionAbstract
ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract


Returns this pointer bound to closure

ReflectionFunctionAbstract::__clone
ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getClosureThis

(No version information available, might only be in SVN)

ReflectionFunctionAbstract::getClosureThis — Returns this pointer bound to closure

Opis

public object ReflectionFunctionAbstract::getClosureThis ( 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

Returns $this pointer. Returns NULL in case of an error.

ReflectionFunctionAbstract::__clone
ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract


Gets doc comment

ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getDocComment

(PHP 5 >= 5.1.0)

ReflectionFunctionAbstract::getDocComment — Gets doc comment

Opis

public string ReflectionFunctionAbstract::getDocComment ( void )

Get a Doc comment from a function.

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 doc comment if it exists, otherwise FALSE

Zobacz też:

  • ReflectionFunctionAbstract::getStartLine() - Gets starting line number

ReflectionFunctionAbstract::getClosureThis
ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract


Gets end line number

ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getEndLine

(PHP 5)

ReflectionFunctionAbstract::getEndLine — Gets end line number

Opis

public int ReflectionFunctionAbstract::getEndLine ( void )

Get the ending line number.

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 ending line number of the user defined function, or FALSE if unknown.

Zobacz też:

  • ReflectionFunctionAbstract::getStartLine() - Gets starting line number

ReflectionFunctionAbstract::getDocComment
ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract


Gets extension info

ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getExtension

(PHP 5)

ReflectionFunctionAbstract::getExtension — Gets extension info

Opis

public ReflectionExtension ReflectionFunctionAbstract::getExtension ( void )

Get the extension information of a function.

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 extension information, as a ReflectionExtension object.

Zobacz też:

  • ReflectionFunctionAbstract::getExtensionName() - Gets extension name

ReflectionFunctionAbstract::getEndLine
ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract


Gets extension name

ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getExtensionName

(PHP 5)

ReflectionFunctionAbstract::getExtensionName — Gets extension name

Opis

public string ReflectionFunctionAbstract::getExtensionName ( void )

Get the extensions name.

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 extensions name.

Zobacz też:

  • ReflectionFunctionAbstract::getExtension() - Gets extension info

ReflectionFunctionAbstract::getExtension
ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract


Gets file name

ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getFileName

(PHP 5)

ReflectionFunctionAbstract::getFileName — Gets file name

Opis

public string ReflectionFunctionAbstract::getFileName ( void )

Gets the file name from a user-defined function.

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 file name.

Zobacz też:

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name

ReflectionFunctionAbstract::getExtensionName
ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract


Gets function name

ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getName

(PHP 5)

ReflectionFunctionAbstract::getName — Gets function name

Opis

public string ReflectionFunctionAbstract::getName ( void )

Get the name of the function.

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 name of the function.

Zobacz też:

  • ReflectionFunctionAbstract::getExtensionName() - Gets extension name
  • ReflectionFunctionAbstract::isUserDefined() - Checks if user defined

ReflectionFunctionAbstract::getFileName
ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract


Gets namespace name

ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getNamespaceName

(PHP 5 >= 5.3.0)

ReflectionFunctionAbstract::getNamespaceName — Gets namespace name

Opis

public string ReflectionFunctionAbstract::getNamespaceName ( void )

Get the namespace name where the class is defined.

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 namespace name.

Zobacz też:

  • ReflectionFunctionAbstract::getFileName() - Gets file name
  • namespaces

ReflectionFunctionAbstract::getName
ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract


Gets number of parameters

ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getNumberOfParameters

(PHP 5 >= 5.0.3)

ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters

Opis

public int ReflectionFunctionAbstract::getNumberOfParameters ( void )

Get the number of parameters that a function defines, both optional and required.

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 parameters.

Zobacz też:

  • ReflectionFunctionAbstract::getNumberOfRequiredParameters() - Gets number of required parameters
  • func_num_args() - Returns the number of arguments passed to the function

ReflectionFunctionAbstract::getNamespaceName
ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract


Gets number of required parameters

ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getNumberOfRequiredParameters

(PHP 5 >= 5.0.3)

ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters

Opis

public int ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void )

Get the number of required parameters that a function defines.

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 required parameters.

Zobacz też:

  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters

ReflectionFunctionAbstract::getNumberOfParameters
ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract


Gets parameters

ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getParameters

(PHP 5)

ReflectionFunctionAbstract::getParameters — Gets parameters

Opis

public array ReflectionFunctionAbstract::getParameters ( void )

Get the parameters as an array of ReflectionParameter.

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 parameters, as a ReflectionParameter object.

Zobacz też:

  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters
  • func_get_args() - Returns an array comprising a function's argument list

ReflectionFunctionAbstract::getNumberOfRequiredParameters
ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract


Gets function short name

ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getShortName

(PHP 5 >= 5.3.0)

ReflectionFunctionAbstract::getShortName — Gets function short name

Opis

public string ReflectionFunctionAbstract::getShortName ( void )

Get the short name of the function (without the namespace part).

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 short name of the function.

Zobacz też:

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name
  • namespaces

ReflectionFunctionAbstract::getParameters
ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract


Gets starting line number

ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getStartLine

(PHP 5)

ReflectionFunctionAbstract::getStartLine — Gets starting line number

Opis

public int ReflectionFunctionAbstract::getStartLine ( void )

Gets the starting line number of the function.

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 starting line number.

Zobacz też:

  • ReflectionFunctionAbstract::getEndLine() - Gets end line number

ReflectionFunctionAbstract::getShortName
ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract


Gets static variables

ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::getStaticVariables

(PHP 5)

ReflectionFunctionAbstract::getStaticVariables — Gets static variables

Opis

public array ReflectionFunctionAbstract::getStaticVariables ( void )

Get the static variables.

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 static variables.

Zobacz też:

  • ReflectionFunctionAbstract::getParameters() - Gets parameters

ReflectionFunctionAbstract::getStartLine
ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract


Checks if function in namespace

ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::inNamespace

(PHP 5 >= 5.3.0)

ReflectionFunctionAbstract::inNamespace — Checks if function in namespace

Opis

public bool ReflectionFunctionAbstract::inNamespace ( void )

Checks whether a function is defined in a namespace.

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

TRUE if it's in a namespace, otherwise FALSE

Zobacz też:

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name
  • namespaces

ReflectionFunctionAbstract::getStaticVariables
ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract


Checks if closure

ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isClosure

(PHP 5 >= 5.3.0)

ReflectionFunctionAbstract::isClosure — Checks if closure

Opis

public bool ReflectionFunctionAbstract::isClosure ( void )

Checks whether it's a closure.

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

TRUE if it's a closure, otherwise FALSE

Zobacz też:

  • ReflectionFunctionAbstract::()

ReflectionFunctionAbstract::inNamespace
ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract


Checks if deprecated

ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isDeprecated

(PHP 5)

ReflectionFunctionAbstract::isDeprecated — Checks if deprecated

Opis

public bool ReflectionFunctionAbstract::isDeprecated ( void )

Checks whether the function is deprecated.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if it's deprecated, otherwise FALSE

Przykłady

Przykład #1 ReflectionFunctionAbstract::isDeprecated() example

<?php
$rf = new ReflectionFunction('ereg');
var_dump($rf->isDeprecated());
?>

Powyższy przykład wyświetli:

bool(true)

Zobacz też:

  • ReflectionFunctionAbstract::getDocComment() - Gets doc comment

ReflectionFunctionAbstract::isClosure
ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract


Checks if is internal

ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isInternal

(PHP 5)

ReflectionFunctionAbstract::isInternal — Checks if is internal

Opis

public bool ReflectionFunctionAbstract::isInternal ( void )

Checks whether the function is internal, as opposed to user-defined.

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

TRUE if it's internal, otherwise FALSE

Zobacz też:

  • ReflectionFunctionAbstract::isUserDefined() - Checks if user defined

ReflectionFunctionAbstract::isDeprecated
ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract


Checks if user defined

ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract::returnsReference
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::isUserDefined

(PHP 5)

ReflectionFunctionAbstract::isUserDefined — Checks if user defined

Opis

public bool ReflectionFunctionAbstract::isUserDefined ( void )

Checks whether the function is user-defined, as opposed to internal.

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

TRUE if it's user-defined, otherwise false;

Zobacz też:

  • ReflectionFunctionAbstract::isInternal() - Checks if is internal

ReflectionFunctionAbstract::isInternal
ReflectionFunctionAbstract::returnsReference
ReflectionFunctionAbstract


Checks if returns reference

ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract::__toString
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::returnsReference

(PHP 5)

ReflectionFunctionAbstract::returnsReference — Checks if returns reference

Opis

public bool ReflectionFunctionAbstract::returnsReference ( void )

Checks whether the function returns a reference.

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

TRUE if it returns a reference, otherwise FALSE

Zobacz też:

  • ReflectionFunctionAbstract::isClosure() - Checks if closure

ReflectionFunctionAbstract::isUserDefined
ReflectionFunctionAbstract::__toString
ReflectionFunctionAbstract


To string

ReflectionFunctionAbstract::returnsReference
ReflectionMethod
ReflectionFunctionAbstract
PHP Manual

ReflectionFunctionAbstract::__toString

(PHP 5)

ReflectionFunctionAbstract::__toString — To string

Opis

abstract public void ReflectionFunctionAbstract::__toString ( void )

To string.

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 string.

Zobacz też:

  • ReflectionClass::clone()
  • __toString()

ReflectionFunctionAbstract::returnsReference
ReflectionMethod
ReflectionFunctionAbstract


The ReflectionMethod class

(PHP 5)

Wstęp

The ReflectionMethod class reports information about a method.

Krótki opis klasy

ReflectionMethod extends ReflectionFunctionAbstract implements Reflector {
/* Stałe */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
const integer IS_ABSTRACT = 2 ;
const integer IS_FINAL = 4 ;
/* Właściwości */
public $name ;
public $class ;
/* Metody */
public __construct ( mixed $class , string $name )
public static string export ( string $class , string $name [, bool $return = false ] )
public Closure getClosure ( string $object )
public ReflectionClass getDeclaringClass ( void )
public int getModifiers ( void )
public ReflectionMethod getPrototype ( void )
public mixed invoke ( object $object [, mixed $parameter [, mixed $... ]] )
public mixed invokeArgs ( object $object , array $args )
public bool isAbstract ( void )
public bool isConstructor ( void )
public bool isDestructor ( void )
public bool isFinal ( void )
public bool isPrivate ( void )
public bool isProtected ( void )
public bool isPublic ( void )
public bool isStatic ( void )
public void setAccessible ( bool $accessible )
public string __toString ( void )
/* Metody dziedziczone */
final private void ReflectionFunctionAbstract::__clone ( void )
public object ReflectionFunctionAbstract::getClosureThis ( void )
public string ReflectionFunctionAbstract::getDocComment ( void )
public int ReflectionFunctionAbstract::getEndLine ( void )
public ReflectionExtension ReflectionFunctionAbstract::getExtension ( void )
public string ReflectionFunctionAbstract::getExtensionName ( void )
public string ReflectionFunctionAbstract::getFileName ( void )
public string ReflectionFunctionAbstract::getName ( void )
public string ReflectionFunctionAbstract::getNamespaceName ( void )
public int ReflectionFunctionAbstract::getNumberOfParameters ( void )
public int ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void )
public array ReflectionFunctionAbstract::getParameters ( void )
public string ReflectionFunctionAbstract::getShortName ( void )
public int ReflectionFunctionAbstract::getStartLine ( void )
public array ReflectionFunctionAbstract::getStaticVariables ( void )
public bool ReflectionFunctionAbstract::inNamespace ( void )
public bool ReflectionFunctionAbstract::isClosure ( void )
public bool ReflectionFunctionAbstract::isDeprecated ( void )
public bool ReflectionFunctionAbstract::isInternal ( void )
public bool ReflectionFunctionAbstract::isUserDefined ( void )
public bool ReflectionFunctionAbstract::returnsReference ( void )
abstract public void ReflectionFunctionAbstract::__toString ( void )
}

Właściwości

name

Method name

class

Class name

Stałe predefiniowane

ReflectionMethod Modifiers

ReflectionMethod::IS_STATIC

Indicates that the method is static.

ReflectionMethod::IS_PUBLIC

Indicates that the method is public.

ReflectionMethod::IS_PROTECTED

Indicates that the method is protected.

ReflectionMethod::IS_PRIVATE

Indicates that the method is private.

ReflectionMethod::IS_ABSTRACT

Indicates that the method is abstract.

ReflectionMethod::IS_FINAL

Indicates that the method is final.

Spis treści

  • ReflectionMethod::__construct — Constructs a ReflectionMethod
  • ReflectionMethod::export — Export a reflection method.
  • ReflectionMethod::getClosure — Returns a dynamically created closure for the method
  • ReflectionMethod::getDeclaringClass — Gets declaring class for the reflected method.
  • ReflectionMethod::getModifiers — Gets the method modifiers
  • ReflectionMethod::getPrototype — Gets the method prototype (if there is one).
  • ReflectionMethod::invoke — Invoke
  • ReflectionMethod::invokeArgs — Invoke args
  • ReflectionMethod::isAbstract — Checks if method is abstract
  • ReflectionMethod::isConstructor — Checks if method is a constructor
  • ReflectionMethod::isDestructor — Checks if method is a destructor
  • ReflectionMethod::isFinal — Checks if method is final
  • ReflectionMethod::isPrivate — Checks if method is private
  • ReflectionMethod::isProtected — Checks if method is protected
  • ReflectionMethod::isPublic — Checks if method is public
  • ReflectionMethod::isStatic — Checks if method is static
  • ReflectionMethod::setAccessible — Set method accessibility
  • ReflectionMethod::__toString — Returns the string representation of the Reflection method object.
ReflectionFunctionAbstract::__toString
ReflectionMethod::__construct
Reflection


Constructs a ReflectionMethod

ReflectionMethod
ReflectionMethod::export
ReflectionMethod
PHP Manual

ReflectionMethod::__construct

(PHP 5)

ReflectionMethod::__construct — Constructs a ReflectionMethod

Opis

public ReflectionMethod::__construct ( mixed $class , string $name )

Constructs a new ReflectionMethod.

Parametry

class

Classname or object (instance of the class) that contains the method.

name

Name of the method.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

A ReflectionException is thrown if the given method does not exist.

Przykłady

Przykład #1 ReflectionMethod::__construct() example

<?php
class Counter
{
    private static $c = 0;

    /**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    final public static function increment()
    {
        return ++self::$c;
    }
}

// Create an instance of the ReflectionMethod class
$method = new ReflectionMethod('Counter', 'increment');

// Print out basic information
printf(
    "===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d[%s]\n",
        $method->isInternal() ? 'internal' : 'user-defined',
        $method->isAbstract() ? ' abstract' : '',
        $method->isFinal() ? ' final' : '',
        $method->isPublic() ? ' public' : '',
        $method->isPrivate() ? ' private' : '',
        $method->isProtected() ? ' protected' : '',
        $method->isStatic() ? ' static' : '',
        $method->getName(),
        $method->isConstructor() ? 'the constructor' : 'a regular method',
        $method->getFileName(),
        $method->getStartLine(),
        $method->getEndline(),
        $method->getModifiers(),
        implode(' ', Reflection::getModifierNames($method->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1));

// Print static variables if existant
if ($statics= $method->getStaticVariables()) {
    printf("---> Static variables: %s\n", var_export($statics, 1));
}

// Invoke the method
printf("---> Invocation results in: ");
var_dump($method->invoke(NULL));
?>

Powyższy przykład wyświetli coś podobnego do:

===> The user-defined final public static method 'increment' (which is a regular method)
     declared in /Users/philip/cvs/phpdoc/test.php
     lines 14 to 17
     having the modifiers 261[final public static]
---> Documentation:
 '/**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */'
---> Invocation results in: int(1)

Zobacz też:

  • ReflectionMethod::export() - Export a reflection method.
  • Constructors

ReflectionMethod
ReflectionMethod::export
ReflectionMethod


Export a reflection method.

ReflectionMethod::__construct
ReflectionMethod::getClosure
ReflectionMethod
PHP Manual

ReflectionMethod::export

(PHP 5)

ReflectionMethod::export — Export a reflection method.

Opis

public static string ReflectionMethod::export ( string $class , string $name [, bool $return = false ] )

Exports a ReflectionMethod.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

class

The class name.

name

The name of the method.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Zwracane wartości

Jeśli parametr return jest ustawiony na TRUE, eksport jest zwracany jako string, w przeciwnym przypadku jako NULL.

Zobacz też:

  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • ReflectionMethod::__toString() - Returns the string representation of the Reflection method object.

ReflectionMethod::__construct
ReflectionMethod::getClosure
ReflectionMethod


Returns a dynamically created closure for the method

ReflectionMethod::export
ReflectionMethod::getDeclaringClass
ReflectionMethod
PHP Manual

ReflectionMethod::getClosure

(PHP > 5.4.0)

ReflectionMethod::getClosure — Returns a dynamically created closure for the method

Opis

public Closure ReflectionMethod::getClosure ( string $object )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

object

Forbidden for static methods, required for other methods.

Zwracane wartości

Returns Closure. Returns NULL in case of an error.

ReflectionMethod::export
ReflectionMethod::getDeclaringClass
ReflectionMethod


Gets declaring class for the reflected method.

ReflectionMethod::getClosure
ReflectionMethod::getModifiers
ReflectionMethod
PHP Manual

ReflectionMethod::getDeclaringClass

(PHP 5)

ReflectionMethod::getDeclaringClass — Gets declaring class for the reflected method.

Opis

public ReflectionClass ReflectionMethod::getDeclaringClass ( void )

Gets the declaring class for the reflected method.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A ReflectionClass object of the class that the reflected method is part of.

Przykłady

Przykład #1 ReflectionMethod::getDeclaringClass() example

<?php
class HelloWorld {

    protected function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
var_dump($reflectionMethod->getDeclaringClass());
?>

Powyższy przykład wyświetli:

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(10) "HelloWorld"
}

Zobacz też:

  • ReflectionMethod::isAbstract() - Checks if method is abstract

ReflectionMethod::getClosure
ReflectionMethod::getModifiers
ReflectionMethod


Gets the method modifiers

ReflectionMethod::getDeclaringClass
ReflectionMethod::getPrototype
ReflectionMethod
PHP Manual

ReflectionMethod::getModifiers

(PHP 5)

ReflectionMethod::getModifiers — Gets the method modifiers

Opis

public int ReflectionMethod::getModifiers ( void )

Returns a bitfield of the access modifiers for this method.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A numeric representation of the modifiers. The modifiers are listed below. The actual meanings of these modifiers are described in the predefined constants.

Przykłady

Przykład #1 ReflectionMethod::getModifiers() example

<?php
class Testing
{
    final public static function foo()
    {
        return;
    }
    public function bar()
    {
        return;
    }
}

$foo = new ReflectionMethod('Testing', 'foo');

echo "Modifiers for method foo():\n";
echo $foo->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($foo->getModifiers())) . "\n";

$bar = new ReflectionMethod('Testing', 'bar');

echo "Modifiers for method bar():\n";
echo $bar->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($bar->getModifiers()));
?>

Powyższy przykład wyświetli coś podobnego do:

Modifiers for method foo():
261
final public static
Modifiers for method bar():
65792
public

Zobacz też:

  • Reflection::getModifierNames() - Gets modifier names

ReflectionMethod::getDeclaringClass
ReflectionMethod::getPrototype
ReflectionMethod


Gets the method prototype (if there is one).

ReflectionMethod::getModifiers
ReflectionMethod::invoke
ReflectionMethod
PHP Manual

ReflectionMethod::getPrototype

(PHP 5)

ReflectionMethod::getPrototype — Gets the method prototype (if there is one).

Opis

public ReflectionMethod ReflectionMethod::getPrototype ( void )

Returns the methods prototype.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A ReflectionMethod instance of the method prototype.

Błędy/Wyjątki

A ReflectionException exception is thrown if the method does not have a prototype.

Przykłady

Przykład #1 ReflectionMethod::getPrototype() example

<?php
class Hello {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}
class HelloWorld extends Hello {

    public function sayHelloTo($name) {
        return 'Hello world: ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
var_dump($reflectionMethod->getPrototype());
?>

Powyższy przykład wyświetli:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(10) "sayHelloTo"
  ["class"]=>
  string(5) "Hello"
}

Zobacz też:

  • ReflectionMethod::getModifiers() - Gets the method modifiers

ReflectionMethod::getModifiers
ReflectionMethod::invoke
ReflectionMethod


Invoke

ReflectionMethod::getPrototype
ReflectionMethod::invokeArgs
ReflectionMethod
PHP Manual

ReflectionMethod::invoke

(PHP 5)

ReflectionMethod::invoke — Invoke

Opis

public mixed ReflectionMethod::invoke ( object $object [, mixed $parameter [, mixed $... ]] )

Invokes a reflected method.

Parametry

object

The object to invoke the method on. For static methods, pass null to this parameter.

parameter

Zero or more parameters to be passed to the method. It accepts a variable number of parameters which are passed to the method.

Zwracane wartości

Returns the method result.

Błędy/Wyjątki

A ReflectionException if the object parameter does not contain an instance of the class that this method was declared in.

A ReflectionException if the method invocation failed.

Przykłady

Przykład #1 ReflectionMethod::invoke() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invoke(new HelloWorld(), 'Mike');
?>

Powyższy przykład wyświetli:

Hello Mike

Notatki

Informacja:

If the function has arguments that need to be references, then they must be references in the passed argument list.

Zobacz też:

  • ReflectionMethod::invokeArgs() - Invoke args
  • __invoke()
  • call_user_func() - Call the callback given by the first parameter

ReflectionMethod::getPrototype
ReflectionMethod::invokeArgs
ReflectionMethod


Invoke args

ReflectionMethod::invoke
ReflectionMethod::isAbstract
ReflectionMethod
PHP Manual

ReflectionMethod::invokeArgs

(PHP 5 >= 5.1.0)

ReflectionMethod::invokeArgs — Invoke args

Opis

public mixed ReflectionMethod::invokeArgs ( object $object , array $args )

Invokes the reflected method and pass its arguments as array.

Parametry

object

The object to invoke the method on. In case of static methods, you can pass null to this parameter.

args

The parameters to be passed to the function, as an array.

Zwracane wartości

Returns the method result.

Błędy/Wyjątki

A ReflectionException if the object parameter does not contain an instance of the class that this method was declared in.

A ReflectionException if the method invocation failed.

Przykłady

Przykład #1 ReflectionMethod::invokeArgs() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invokeArgs(new HelloWorld(), array('Mike'));
?>

Powyższy przykład wyświetli:

Hello Mike

Notatki

Informacja:

If the function has arguments that need to be references, then they must be references in the passed argument list.

Zobacz też:

  • ReflectionMethod::invoke() - Invoke
  • __invoke()
  • call_user_func_array() - Call a callback with an array of parameters

ReflectionMethod::invoke
ReflectionMethod::isAbstract
ReflectionMethod


Checks if method is abstract

ReflectionMethod::invokeArgs
ReflectionMethod::isConstructor
ReflectionMethod
PHP Manual

ReflectionMethod::isAbstract

(PHP 5)

ReflectionMethod::isAbstract — Checks if method is abstract

Opis

public bool ReflectionMethod::isAbstract ( void )

Checks if the method is abstract.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the method is abstract, otherwise FALSE

Zobacz też:

  • ReflectionMethod::getDeclaringClass() - Gets declaring class for the reflected method.

ReflectionMethod::invokeArgs
ReflectionMethod::isConstructor
ReflectionMethod


Checks if method is a constructor

ReflectionMethod::isAbstract
ReflectionMethod::isDestructor
ReflectionMethod
PHP Manual

ReflectionMethod::isConstructor

(PHP 5)

ReflectionMethod::isConstructor — Checks if method is a constructor

Opis

public bool ReflectionMethod::isConstructor ( void )

Checks if the method is a constructor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the method is a constructor, otherwise FALSE

Zobacz też:

  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • ReflectionMethod::isAbstract() - Checks if method is abstract
  • ReflectionMethod::isDestructor() - Checks if method is a destructor

ReflectionMethod::isAbstract
ReflectionMethod::isDestructor
ReflectionMethod


Checks if method is a destructor

ReflectionMethod::isConstructor
ReflectionMethod::isFinal
ReflectionMethod
PHP Manual

ReflectionMethod::isDestructor

(PHP 5)

ReflectionMethod::isDestructor — Checks if method is a destructor

Opis

public bool ReflectionMethod::isDestructor ( void )

Checks if the method is a destructor.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the method is a destructor, otherwise FALSE

Zobacz też:

  • ReflectionMethod::isConstructor() - Checks if method is a constructor

ReflectionMethod::isConstructor
ReflectionMethod::isFinal
ReflectionMethod


Checks if method is final

ReflectionMethod::isDestructor
ReflectionMethod::isPrivate
ReflectionMethod
PHP Manual

ReflectionMethod::isFinal

(PHP 5)

ReflectionMethod::isFinal — Checks if method is final

Opis

public bool ReflectionMethod::isFinal ( void )

Checks if the method is final.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the method is final, otherwise FALSE

Zobacz też:

  • ReflectionMethod::isStatic() - Checks if method is static

ReflectionMethod::isDestructor
ReflectionMethod::isPrivate
ReflectionMethod


Checks if method is private

ReflectionMethod::isFinal
ReflectionMethod::isProtected
ReflectionMethod
PHP Manual

ReflectionMethod::isPrivate

(PHP 5)

ReflectionMethod::isPrivate — Checks if method is private

Opis

public bool ReflectionMethod::isPrivate ( void )

Checks if the method is private.

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

TRUE if the method is private, otherwise FALSE

Zobacz też:

  • ReflectionMethod::isPublic() - Checks if method is public

ReflectionMethod::isFinal
ReflectionMethod::isProtected
ReflectionMethod


Checks if method is protected

ReflectionMethod::isPrivate
ReflectionMethod::isPublic
ReflectionMethod
PHP Manual

ReflectionMethod::isProtected

(PHP 5)

ReflectionMethod::isProtected — Checks if method is protected

Opis

public bool ReflectionMethod::isProtected ( void )

Checks if the method is protected.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the method is protected, otherwise FALSE

Zobacz też:

  • ReflectionMethod::isPrivate() - Checks if method is private

ReflectionMethod::isPrivate
ReflectionMethod::isPublic
ReflectionMethod


Checks if method is public

ReflectionMethod::isProtected
ReflectionMethod::isStatic
ReflectionMethod
PHP Manual

ReflectionMethod::isPublic

(PHP 5)

ReflectionMethod::isPublic — Checks if method is public

Opis

public bool ReflectionMethod::isPublic ( void )

Checks if the method is public.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the method is public, otherwise FALSE

Zobacz też:

  • ReflectionMethod::isPrivate() - Checks if method is private

ReflectionMethod::isProtected
ReflectionMethod::isStatic
ReflectionMethod


Checks if method is static

ReflectionMethod::isPublic
ReflectionMethod::setAccessible
ReflectionMethod
PHP Manual

ReflectionMethod::isStatic

(PHP 5)

ReflectionMethod::isStatic — Checks if method is static

Opis

public bool ReflectionMethod::isStatic ( void )

Checks if the method is static.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the method is static, otherwise FALSE

Zobacz też:

  • ReflectionMethod::isFinal() - Checks if method is final

ReflectionMethod::isPublic
ReflectionMethod::setAccessible
ReflectionMethod


Set method accessibility

ReflectionMethod::isStatic
ReflectionMethod::__toString
ReflectionMethod
PHP Manual

ReflectionMethod::setAccessible

(PHP 5 >= 5.3.2)

ReflectionMethod::setAccessible — Set method accessibility

Opis

public void ReflectionMethod::setAccessible ( bool $accessible )

Sets a method to be accessible. For example, it may allow protected and private methods to be invoked.

Parametry

accessible

TRUE to allow accessibility, or FALSE.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ReflectionMethod::isPrivate() - Checks if method is private
  • ReflectionMethod::isProtected() - Checks if method is protected

ReflectionMethod::isStatic
ReflectionMethod::__toString
ReflectionMethod


Returns the string representation of the Reflection method object.

ReflectionMethod::setAccessible
ReflectionObject
ReflectionMethod
PHP Manual

ReflectionMethod::__toString

(PHP 5)

ReflectionMethod::__toString — Returns the string representation of the Reflection method object.

Opis

public string ReflectionMethod::__toString ( void )

Returns the string representation of the Reflection method object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A string representation of this ReflectionMethod instance.

Przykłady

Przykład #1 ReflectionMethod::__toString() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
echo $reflectionMethod;
?>

Powyższy przykład wyświetli:

Method [ <user> public method sayHelloTo ] {
  @@ /var/www/examples/reflection.php 16 - 18

  - Parameters [1] {
    Parameter #0 [ <required> $name ]
  }
}

Zobacz też:

  • ReflectionMethod::export() - Export a reflection method.
  • __toString()

ReflectionMethod::setAccessible
ReflectionObject
ReflectionMethod


The ReflectionObject class

(PHP 5)

Wstęp

The ReflectionObject class reports information about an object.

Krótki opis klasy

ReflectionObject extends ReflectionClass implements Reflector {
/* Stałe */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* Właściwości */
/* Metody */
public __construct ( object $argument )
public static string export ( string $argument [, bool $return ] )
/* Metody dziedziczone */
final private void ReflectionClass::__clone ( void )
ReflectionClass::__construct ( mixed $argument )
public static string ReflectionClass::export ( mixed $argument [, bool $return = false ] )
public mixed ReflectionClass::getConstant ( string $name )
public array ReflectionClass::getConstants ( void )
public object ReflectionClass::getConstructor ( void )
public array ReflectionClass::getDefaultProperties ( void )
public string ReflectionClass::getDocComment ( void )
public int ReflectionClass::getEndLine ( void )
public ReflectionExtension ReflectionClass::getExtension ( void )
public string ReflectionClass::getExtensionName ( void )
public string ReflectionClass::getFileName ( void )
public array ReflectionClass::getInterfaceNames ( void )
public array ReflectionClass::getInterfaces ( void )
public ReflectionMethod ReflectionClass::getMethod ( string $name )
public array ReflectionClass::getMethods ([ string $filter ] )
public int ReflectionClass::getModifiers ( void )
public string ReflectionClass::getName ( void )
public string ReflectionClass::getNamespaceName ( void )
public object ReflectionClass::getParentClass ( void )
public array ReflectionClass::getProperties ([ int $filter ] )
public ReflectionProperty ReflectionClass::getProperty ( string $name )
public string ReflectionClass::getShortName ( void )
public int ReflectionClass::getStartLine ( void )
public array ReflectionClass::getStaticProperties ( void )
public mixed ReflectionClass::getStaticPropertyValue ( string $name [, string $default ] )
public array ReflectionClass::getTraitAliases ( void )
public array ReflectionClass::getTraitNames ( void )
public array ReflectionClass::getTraits ( void )
public bool ReflectionClass::hasConstant ( string $name )
public bool ReflectionClass::hasMethod ( string $name )
public bool ReflectionClass::hasProperty ( string $name )
public bool ReflectionClass::implementsInterface ( string $interface )
public bool ReflectionClass::inNamespace ( void )
public bool ReflectionClass::isAbstract ( void )
public bool ReflectionClass::isCloneable ( void )
public bool ReflectionClass::isFinal ( void )
public bool ReflectionClass::isInstance ( object $object )
public bool ReflectionClass::isInstantiable ( void )
public bool ReflectionClass::isInterface ( void )
public bool ReflectionClass::isInternal ( void )
public bool ReflectionClass::isIterateable ( void )
public bool ReflectionClass::isSubclassOf ( string $class )
public bool ReflectionClass::isTrait ( void )
public bool ReflectionClass::isUserDefined ( void )
public object ReflectionClass::newInstance ( mixed $args [, mixed $... ] )
public object ReflectionClass::newInstanceArgs ([ array $args ] )
public object ReflectionClass::newInstanceWithoutConstructor ( void )
public void ReflectionClass::setStaticPropertyValue ( string $name , string $value )
public string ReflectionClass::__toString ( void )
}

Właściwości

name

Name of the object's class. Read-only, throws ReflectionException in attempt to write.

Spis treści

  • ReflectionObject::__construct — Constructs a ReflectionObject
  • ReflectionObject::export — Export
ReflectionMethod::__toString
ReflectionObject::__construct
Reflection


Constructs a ReflectionObject

ReflectionObject
ReflectionObject::export
ReflectionObject
PHP Manual

ReflectionObject::__construct

(PHP 5)

ReflectionObject::__construct — Constructs a ReflectionObject

Opis

public ReflectionObject::__construct ( object $argument )

Constructs a ReflectionObject.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

argument

An object instance.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ReflectionObject::export() - Export
  • Constructors

ReflectionObject
ReflectionObject::export
ReflectionObject


Export

ReflectionObject::__construct
ReflectionParameter
ReflectionObject
PHP Manual

ReflectionObject::export

(PHP 5)

ReflectionObject::export — Export

Opis

public static string ReflectionObject::export ( string $argument [, bool $return ] )

Exports a reflection.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

argument

Refleksja do eksportu.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Zwracane wartości

Jeśli parametr return jest ustawiony na TRUE, eksport jest zwracany jako string, w przeciwnym przypadku jako NULL.

Zobacz też:

  • ReflectionObject::__construct() - Constructs a ReflectionObject

ReflectionObject::__construct
ReflectionParameter
ReflectionObject


The ReflectionParameter class

(PHP 5)

Wstęp

The ReflectionParameter class retrieves information about function's or method's parameters.

To introspect function parameters, first create an instance of the ReflectionFunction or ReflectionMethod classes and then use their ReflectionFunctionAbstract::getParameters() method to retrieve an array of parameters.

Krótki opis klasy

ReflectionParameter implements Reflector {
/* Właściwości */
public $name ;
/* Metody */
public bool allowsNull ( void )
public bool canBePassedByValue ( void )
final private void __clone ( void )
public __construct ( string $function , string $parameter )
public static string export ( string $function , string $parameter [, bool $return ] )
public ReflectionClass getClass ( void )
public ReflectionClass getDeclaringClass ( void )
public ReflectionFunction getDeclaringFunction ( void )
public mixed getDefaultValue ( void )
public string getName ( void )
public int getPosition ( void )
public bool isArray ( void )
public bool isDefaultValueAvailable ( void )
public bool isOptional ( void )
public bool isPassedByReference ( void )
public string __toString ( void )
}

Właściwości

name

Name of the parameter. Read-only, throws ReflectionException in attempt to write.

Spis treści

  • ReflectionParameter::allowsNull — Checks if null is allowed
  • ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value
  • ReflectionParameter::__clone — Clone
  • ReflectionParameter::__construct — Construct
  • ReflectionParameter::export — Exports
  • ReflectionParameter::getClass — Get class
  • ReflectionParameter::getDeclaringClass — Gets declaring class
  • ReflectionParameter::getDeclaringFunction — Gets declaring function
  • ReflectionParameter::getDefaultValue — Gets default parameter value
  • ReflectionParameter::getName — Gets parameter name
  • ReflectionParameter::getPosition — Gets parameter position
  • ReflectionParameter::isArray — Checks if parameter expects an array
  • ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available
  • ReflectionParameter::isOptional — Checks if optional
  • ReflectionParameter::isPassedByReference — Checks if passed by reference
  • ReflectionParameter::__toString — To string
ReflectionObject::export
ReflectionParameter::allowsNull
Reflection


Checks if null is allowed

ReflectionParameter
ReflectionParameter::canBePassedByValue
ReflectionParameter
PHP Manual

ReflectionParameter::allowsNull

(PHP 5)

ReflectionParameter::allowsNull — Checks if null is allowed

Opis

public bool ReflectionParameter::allowsNull ( void )

Checks whether the parameter allows NULL.

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

TRUE if NULL is allowed, otherwise FALSE

Zobacz też:

  • ReflectionParameter::isOptional() - Checks if optional

ReflectionParameter
ReflectionParameter::canBePassedByValue
ReflectionParameter


Returns whether this parameter can be passed by value

ReflectionParameter::allowsNull
ReflectionParameter::__clone
ReflectionParameter
PHP Manual

ReflectionParameter::canBePassedByValue

(PHP > 5.4.0)

ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value

Opis

public bool ReflectionParameter::canBePassedByValue ( 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

Returns TRUE if the parameter can be passed by value, FALSE otherwise. Returns NULL in case of an error.

ReflectionParameter::allowsNull
ReflectionParameter::__clone
ReflectionParameter


Clone

ReflectionParameter::canBePassedByValue
ReflectionParameter::__construct
ReflectionParameter
PHP Manual

ReflectionParameter::__clone

(PHP 5)

ReflectionParameter::__clone — Clone

Opis

final private void ReflectionParameter::__clone ( void )

Clones.

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

Zobacz też:

  • ReflectionParameter::toString()
  • Object cloning

ReflectionParameter::canBePassedByValue
ReflectionParameter::__construct
ReflectionParameter


Construct

ReflectionParameter::__clone
ReflectionParameter::export
ReflectionParameter
PHP Manual

ReflectionParameter::__construct

(PHP 5)

ReflectionParameter::__construct — Construct

Opis

public ReflectionParameter::__construct ( string $function , string $parameter )

Constructs a ReflectionParameter class.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

function

The function to reflect parameters from.

parameter

The parameter.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Using the ReflectionParameter class

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

$reflect = new ReflectionFunction('foo');

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
    printf(
        "-- Parameter #%d: %s {\n".
        "   Class: %s\n".
        "   Allows NULL: %s\n".
        "   Passed to by reference: %s\n".
        "   Is optional?: %s\n".
        "}\n",
        $i, // $param->getPosition() can be used from PHP 5.2.3
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),
        $param->isOptional() ? 'yes' : 'no'
    );
}
?>

Powyższy przykład wyświetli coś podobnego do:

Function [ <user> function foo ] {
  @@ /Users/philip/cvs/phpdoc/a 2 - 2

  - Parameters [3] {
    Parameter #0 [ <required> $a ]
    Parameter #1 [ <required> $b ]
    Parameter #2 [ <required> $c ]
  }
}
-- Parameter #0: a {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #1: b {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #2: c {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}

Zobacz też:

  • ReflectionFunction::__construct() - Constructs a ReflectionFunction object
  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • Constructors

ReflectionParameter::__clone
ReflectionParameter::export
ReflectionParameter


Exports

ReflectionParameter::__construct
ReflectionParameter::getClass
ReflectionParameter
PHP Manual

ReflectionParameter::export

(PHP 5)

ReflectionParameter::export — Exports

Opis

public static string ReflectionParameter::export ( string $function , string $parameter [, bool $return ] )

Exports.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

function

The function name.

parameter

The parameter name.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Zwracane wartości

The exported reflection.

Zobacz też:

  • ReflectionParameter::toString()

ReflectionParameter::__construct
ReflectionParameter::getClass
ReflectionParameter


Get class

ReflectionParameter::export
ReflectionParameter::getDeclaringClass
ReflectionParameter
PHP Manual

ReflectionParameter::getClass

(PHP 5)

ReflectionParameter::getClass — Get class

Opis

public ReflectionClass ReflectionParameter::getClass ( void )

Gets a class.

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

A ReflectionClass object.

Zobacz też:

  • ReflectionParameter::getDeclaringClass() - Gets declaring class

ReflectionParameter::export
ReflectionParameter::getDeclaringClass
ReflectionParameter


Gets declaring class

ReflectionParameter::getClass
ReflectionParameter::getDeclaringFunction
ReflectionParameter
PHP Manual

ReflectionParameter::getDeclaringClass

(PHP 5)

ReflectionParameter::getDeclaringClass — Gets declaring class

Opis

public ReflectionClass ReflectionParameter::getDeclaringClass ( void )

Gets the declaring class.

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

A ReflectionClass object.

Zobacz też:

  • ReflectionParameter::getClass() - Get class

ReflectionParameter::getClass
ReflectionParameter::getDeclaringFunction
ReflectionParameter


Gets declaring function

ReflectionParameter::getDeclaringClass
ReflectionParameter::getDefaultValue
ReflectionParameter
PHP Manual

ReflectionParameter::getDeclaringFunction

(PHP 5 >= 5.2.3)

ReflectionParameter::getDeclaringFunction — Gets declaring function

Opis

public ReflectionFunction ReflectionParameter::getDeclaringFunction ( void )

Gets the declaring function.

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

A ReflectionFunction object.

Zobacz też:

  • ReflectionParameter::getDeclaringClass() - Gets declaring class

ReflectionParameter::getDeclaringClass
ReflectionParameter::getDefaultValue
ReflectionParameter


Gets default parameter value

ReflectionParameter::getDeclaringFunction
ReflectionParameter::getName
ReflectionParameter
PHP Manual

ReflectionParameter::getDefaultValue

(PHP 5 >= 5.0.3)

ReflectionParameter::getDefaultValue — Gets default parameter value

Opis

public mixed ReflectionParameter::getDefaultValue ( void )

Gets the default value of the parameter for a user-defined function or method. If the parameter is not optional a ReflectionException will be thrown.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The parameters default value.

Przykłady

Przykład #1 Getting

<?php
function foo($test, $bar = 'baz')
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Name: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Default value: ' . $param->getDefaultValue() . PHP_EOL;
    }
    echo PHP_EOL;
}
?>

Powyższy przykład wyświetli:

Name: test

Name: bar
Default value: baz

Notatki

Informacja:

Due to implementation details, it is not possible to get the default value of built-in functions or methods of built-in classes. Trying to do this will result a ReflectionException being thrown.

Zobacz też:

  • ReflectionParameter::isOptional() - Checks if optional
  • ReflectionParameter::isPassedByReference() - Checks if passed by reference

ReflectionParameter::getDeclaringFunction
ReflectionParameter::getName
ReflectionParameter


Gets parameter name

ReflectionParameter::getDefaultValue
ReflectionParameter::getPosition
ReflectionParameter
PHP Manual

ReflectionParameter::getName

(PHP 5)

ReflectionParameter::getName — Gets parameter name

Opis

public string ReflectionParameter::getName ( void )

Gets the name of the parameter.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The name of the reflected parameter.

Zobacz też:

  • ReflectionParameter::getValue()

ReflectionParameter::getDefaultValue
ReflectionParameter::getPosition
ReflectionParameter


Gets parameter position

ReflectionParameter::getName
ReflectionParameter::isArray
ReflectionParameter
PHP Manual

ReflectionParameter::getPosition

(PHP 5 >= 5.2.3)

ReflectionParameter::getPosition — Gets parameter position

Opis

public int ReflectionParameter::getPosition ( void )

Gets the position of the parameter.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The position of the parameter, left to right, starting at position #0.

Zobacz też:

  • ReflectionParameter::getName() - Gets parameter name

ReflectionParameter::getName
ReflectionParameter::isArray
ReflectionParameter


Checks if parameter expects an array

ReflectionParameter::getPosition
ReflectionParameter::isDefaultValueAvailable
ReflectionParameter
PHP Manual

ReflectionParameter::isArray

(PHP 5 >= 5.1.0)

ReflectionParameter::isArray — Checks if parameter expects an array

Opis

public bool ReflectionParameter::isArray ( void )

Checks if the parameter expects an array.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if an array is expected, FALSE otherwise.

Zobacz też:

  • ReflectionParameter::isOptional() - Checks if optional

ReflectionParameter::getPosition
ReflectionParameter::isDefaultValueAvailable
ReflectionParameter


Checks if a default value is available

ReflectionParameter::isArray
ReflectionParameter::isOptional
ReflectionParameter
PHP Manual

ReflectionParameter::isDefaultValueAvailable

(PHP 5 >= 5.0.3)

ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available

Opis

public bool ReflectionParameter::isDefaultValueAvailable ( void )

Checks if a default value for the parameter is available.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if a default value is available, otherwise FALSE

Zobacz też:

  • ReflectionParameter::getDefaultValue() - Gets default parameter value
  • ReflectionParameter::getName() - Gets parameter name

ReflectionParameter::isArray
ReflectionParameter::isOptional
ReflectionParameter


Checks if optional

ReflectionParameter::isDefaultValueAvailable
ReflectionParameter::isPassedByReference
ReflectionParameter
PHP Manual

ReflectionParameter::isOptional

(PHP 5 >= 5.0.3)

ReflectionParameter::isOptional — Checks if optional

Opis

public bool ReflectionParameter::isOptional ( void )

Checks if the parameter is optional.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the parameter is optional, otherwise FALSE

Zobacz też:

  • ReflectionParameter::getName() - Gets parameter name

ReflectionParameter::isDefaultValueAvailable
ReflectionParameter::isPassedByReference
ReflectionParameter


Checks if passed by reference

ReflectionParameter::isOptional
ReflectionParameter::__toString
ReflectionParameter
PHP Manual

ReflectionParameter::isPassedByReference

(PHP 5)

ReflectionParameter::isPassedByReference — Checks if passed by reference

Opis

public bool ReflectionParameter::isPassedByReference ( void )

Checks if the parameter is passed in by reference.

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

TRUE if the parameter is passed in by reference, otherwise FALSE

Zobacz też:

  • ReflectionParameter::getName() - Gets parameter name

ReflectionParameter::isOptional
ReflectionParameter::__toString
ReflectionParameter


To string

ReflectionParameter::isPassedByReference
ReflectionProperty
ReflectionParameter
PHP Manual

ReflectionParameter::__toString

(PHP 5)

ReflectionParameter::__toString — To string

Opis

public string ReflectionParameter::__toString ( void )

To string.

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

Zobacz też:

  • ReflectionParameter::export() - Exports
  • __toString()

ReflectionParameter::isPassedByReference
ReflectionProperty
ReflectionParameter


The ReflectionProperty class

(PHP 5)

Wstęp

The ReflectionProperty class reports information about classes properties.

Krótki opis klasy

ReflectionProperty implements Reflector {
/* Stałe */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
/* Właściwości */
public $name ;
public $class ;
/* Metody */
final private void __clone ( void )
__construct ( mixed $class , string $name )
public static string export ( mixed $class , string $name [, bool $return ] )
public ReflectionClass getDeclaringClass ( void )
public string getDocComment ( void )
public int getModifiers ( void )
public string getName ( void )
public mixed getValue ( object $object )
public bool isDefault ( void )
public bool isPrivate ( void )
public bool isProtected ( void )
public bool isPublic ( void )
public bool isStatic ( void )
public void setAccessible ( bool $accessible )
public void setValue ( object $object , mixed $value )
public string __toString ( void )
}

Właściwości

name

Name of the property. Read-only, throws ReflectionException in attempt to write.

class

Name of the class where the property is defined. Read-only, throws ReflectionException in attempt to write.

Stałe predefiniowane

ReflectionProperty Modifiers

ReflectionProperty::IS_STATIC

Indicates static properties.

ReflectionProperty::IS_PUBLIC

Indicates public properties.

ReflectionProperty::IS_PROTECTED

Indicates protected properties.

ReflectionProperty::IS_PRIVATE

Indicates private properties.

Spis treści

  • ReflectionProperty::__clone — Clone
  • ReflectionProperty::__construct — Construct a ReflectionProperty object
  • ReflectionProperty::export — Export
  • ReflectionProperty::getDeclaringClass — Gets declaring class
  • ReflectionProperty::getDocComment — Gets doc comment
  • ReflectionProperty::getModifiers — Gets modifiers
  • ReflectionProperty::getName — Gets property name
  • ReflectionProperty::getValue — Gets value
  • ReflectionProperty::isDefault — Checks if default value
  • ReflectionProperty::isPrivate — Checks if property is private
  • ReflectionProperty::isProtected — Checks if property is protected
  • ReflectionProperty::isPublic — Checks if property is public
  • ReflectionProperty::isStatic — Checks if property is static
  • ReflectionProperty::setAccessible — Set property accessibility
  • ReflectionProperty::setValue — Set property value
  • ReflectionProperty::__toString — To string
ReflectionParameter::__toString
ReflectionProperty::__clone
Reflection


Clone

ReflectionProperty
ReflectionProperty::__construct
ReflectionProperty
PHP Manual

ReflectionProperty::__clone

(PHP 5)

ReflectionProperty::__clone — Clone

Opis

final private void ReflectionProperty::__clone ( void )

Clones.

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

Zobacz też:

  • ReflectionProperty::export() - Export
  • Object cloning

ReflectionProperty
ReflectionProperty::__construct
ReflectionProperty


Construct a ReflectionProperty object

ReflectionProperty::__clone
ReflectionProperty::export
ReflectionProperty
PHP Manual

ReflectionProperty::__construct

(PHP 5)

ReflectionProperty::__construct — Construct a ReflectionProperty object

Opis

ReflectionProperty::__construct ( mixed $class , string $name )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

class

The class name, that contains the property.

name

The name of the property being reflected.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Trying to get or set private or protected class property's values will result in an exception being thrown.

Przykłady

Przykład #1 ReflectionProperty::__construct() example

<?php
class String
{
    public $length  = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('String', 'length');

// Print out basic information
printf(
    "===> The%s%s%s%s property '%s' (which was %s)\n" .
    "     having the modifiers %s\n",
        $prop->isPublic() ? ' public' : '',
        $prop->isPrivate() ? ' private' : '',
        $prop->isProtected() ? ' protected' : '',
        $prop->isStatic() ? ' static' : '',
        $prop->getName(),
        $prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
        var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Create an instance of String
$obj= new String();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

Powyższy przykład wyświetli coś podobnego do:

===> The public property 'length' (which was declared at compile-time)
     having the modifiers array (
  0 => 'public',
)
---> Value is: int(5)
---> Setting value to 10, new value is: int(10)
object(String)#2 (1) {
  ["length"]=>
  int(10)
}

Przykład #2 Getting value from private and protected properties using ReflectionProperty class

<?php

class Foo {
    public $x = 1;
    protected $y = 2;
    private $z = 3;
}

$obj = new Foo;

$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

?>

Powyższy przykład wyświetli coś podobnego do:

int(2)
int(3)

Zobacz też:

  • ReflectionProperty::getName() - Gets property name
  • Constructors

ReflectionProperty::__clone
ReflectionProperty::export
ReflectionProperty


Export

ReflectionProperty::__construct
ReflectionProperty::getDeclaringClass
ReflectionProperty
PHP Manual

ReflectionProperty::export

(PHP 5)

ReflectionProperty::export — Export

Opis

public static string ReflectionProperty::export ( mixed $class , string $name [, bool $return ] )

Exports a reflection.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

argument

Refleksja do eksportu.

name

The property name.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Zwracane wartości

Zobacz też:

  • ReflectionProperty::toString()

ReflectionProperty::__construct
ReflectionProperty::getDeclaringClass
ReflectionProperty


Gets declaring class

ReflectionProperty::export
ReflectionProperty::getDocComment
ReflectionProperty
PHP Manual

ReflectionProperty::getDeclaringClass

(PHP 5)

ReflectionProperty::getDeclaringClass — Gets declaring class

Opis

public ReflectionClass ReflectionProperty::getDeclaringClass ( void )

Gets the declaring class.

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

A ReflectionClass object.

Zobacz też:

  • ReflectionProperty::getName() - Gets property name

ReflectionProperty::export
ReflectionProperty::getDocComment
ReflectionProperty


Gets doc comment

ReflectionProperty::getDeclaringClass
ReflectionProperty::getModifiers
ReflectionProperty
PHP Manual

ReflectionProperty::getDocComment

(PHP 5 >= 5.1.0)

ReflectionProperty::getDocComment — Gets doc comment

Opis

public string ReflectionProperty::getDocComment ( void )

Gets the doc comment.

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 doc comment.

Zobacz też:

  • ReflectionProperty::export() - Export

ReflectionProperty::getDeclaringClass
ReflectionProperty::getModifiers
ReflectionProperty


Gets modifiers

ReflectionProperty::getDocComment
ReflectionProperty::getName
ReflectionProperty
PHP Manual

ReflectionProperty::getModifiers

(PHP 5)

ReflectionProperty::getModifiers — Gets modifiers

Opis

public int ReflectionProperty::getModifiers ( void )

Gets the modifiers.

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

A numeric representation of the modifiers.

Zobacz też:

  • ReflectionProperty::isPrivate() - Checks if property is private
  • Reflection::getModifierNames() - Gets modifier names

ReflectionProperty::getDocComment
ReflectionProperty::getName
ReflectionProperty


Gets property name

ReflectionProperty::getModifiers
ReflectionProperty::getValue
ReflectionProperty
PHP Manual

ReflectionProperty::getName

(PHP 5)

ReflectionProperty::getName — Gets property name

Opis

public string ReflectionProperty::getName ( void )

Gets the properties name.

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 name of the reflected property.

Zobacz też:

  • ReflectionProperty::getValue() - Gets value

ReflectionProperty::getModifiers
ReflectionProperty::getValue
ReflectionProperty


Gets value

ReflectionProperty::getName
ReflectionProperty::isDefault
ReflectionProperty
PHP Manual

ReflectionProperty::getValue

(PHP 5)

ReflectionProperty::getValue — Gets value

Opis

public mixed ReflectionProperty::getValue ( object $object )
public mixed ReflectionProperty::getValue ( void )

Gets the properties value.

Parametry

object

If the property is non-static an object must be provided to fetch the property from. If you want to fetch the default property without providing an object use ReflectionClass::getDefaultProperties() instead.

Zwracane wartości

The current value of the property.

Błędy/Wyjątki

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

Przykłady

Przykład #1 ReflectionProperty::getValue() example

<?php
class Foo {
    public static $staticProperty = 'foobar';

    public $property = 'barfoo';
    protected $privateProperty = 'foofoo';
}

$reflectionClass = new ReflectionClass('Foo');

var_dump($reflectionClass->getProperty('staticProperty')->getValue());
var_dump($reflectionClass->getProperty('property')->getValue(new Foo));

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
var_dump($reflectionProperty->getValue(new Foo));
?>

Powyższy przykład wyświetli:

string(6) "foobar"
string(6) "barfoo"
string(6) "foofoo"

Zobacz też:

  • ReflectionProperty::setValue() - Set property value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::getDefaultProperties() - Gets default properties
  • ReflectionClass::getStaticPropertyValue() - Gets static property value

ReflectionProperty::getName
ReflectionProperty::isDefault
ReflectionProperty


Checks if default value

ReflectionProperty::getValue
ReflectionProperty::isPrivate
ReflectionProperty
PHP Manual

ReflectionProperty::isDefault

(PHP 5)

ReflectionProperty::isDefault — Checks if default value

Opis

public bool ReflectionProperty::isDefault ( void )

Checks whether the property is the default.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the property was declared at compile-time, or FALSE if it was created at run-time.

Zobacz też:

  • ReflectionProperty::getValue() - Gets value

ReflectionProperty::getValue
ReflectionProperty::isPrivate
ReflectionProperty


Checks if property is private

ReflectionProperty::isDefault
ReflectionProperty::isProtected
ReflectionProperty
PHP Manual

ReflectionProperty::isPrivate

(PHP 5)

ReflectionProperty::isPrivate — Checks if property is private

Opis

public bool ReflectionProperty::isPrivate ( void )

Checks whether the property is private.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the property is private, FALSE otherwise.

Zobacz też:

  • ReflectionProperty::isPublic() - Checks if property is public

ReflectionProperty::isDefault
ReflectionProperty::isProtected
ReflectionProperty


Checks if property is protected

ReflectionProperty::isPrivate
ReflectionProperty::isPublic
ReflectionProperty
PHP Manual

ReflectionProperty::isProtected

(PHP 5)

ReflectionProperty::isProtected — Checks if property is protected

Opis

public bool ReflectionProperty::isProtected ( void )

Checks whether the property is protected.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the property is protected, FALSE otherwise.

Zobacz też:

  • ReflectionProperty::isPrivate() - Checks if property is private

ReflectionProperty::isPrivate
ReflectionProperty::isPublic
ReflectionProperty


Checks if property is public

ReflectionProperty::isProtected
ReflectionProperty::isStatic
ReflectionProperty
PHP Manual

ReflectionProperty::isPublic

(PHP 5)

ReflectionProperty::isPublic — Checks if property is public

Opis

public bool ReflectionProperty::isPublic ( void )

Checks whether the property is public.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the property is public, FALSE otherwise.

Zobacz też:

  • ReflectionProperty::isPrivate() - Checks if property is private

ReflectionProperty::isProtected
ReflectionProperty::isStatic
ReflectionProperty


Checks if property is static

ReflectionProperty::isPublic
ReflectionProperty::setAccessible
ReflectionProperty
PHP Manual

ReflectionProperty::isStatic

(PHP 5)

ReflectionProperty::isStatic — Checks if property is static

Opis

public bool ReflectionProperty::isStatic ( void )

Checks whether the property is static.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the property is static, FALSE otherwise.

Zobacz też:

  • ReflectionProperty::isPrivate() - Checks if property is private

ReflectionProperty::isPublic
ReflectionProperty::setAccessible
ReflectionProperty


Set property accessibility

ReflectionProperty::isStatic
ReflectionProperty::setValue
ReflectionProperty
PHP Manual

ReflectionProperty::setAccessible

(PHP 5 >= 5.3.0)

ReflectionProperty::setAccessible — Set property accessibility

Opis

public void ReflectionProperty::setAccessible ( bool $accessible )

Sets a property to be accessible. For example, it may allow protected and private properties to be accessed.

Parametry

accessible

TRUE to allow accessibility, or FALSE.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isProtected() - Checks if property is protected

ReflectionProperty::isStatic
ReflectionProperty::setValue
ReflectionProperty


Set property value

ReflectionProperty::setAccessible
ReflectionProperty::__toString
ReflectionProperty
PHP Manual

ReflectionProperty::setValue

(PHP 5)

ReflectionProperty::setValue — Set property value

Opis

public void ReflectionProperty::setValue ( object $object , mixed $value )
public void ReflectionProperty::setValue ( mixed $value )

Sets (changes) the property's value.

Parametry

object

If the property is non-static an object must be provided to change the property on. If the property is static this parameter is left out and only value needs to be provided.

value

The new value.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

Przykłady

Przykład #1 ReflectionProperty::setValue() example

<?php
class Foo {
    public static $staticProperty;

    public $property;
    protected $privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

$reflectionClass->getProperty('staticProperty')->setValue('foo');
var_dump(Foo::$staticProperty);

$foo = new Foo;

$reflectionClass->getProperty('property')->setValue($foo, 'bar');
var_dump($foo->property);

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

Powyższy przykład wyświetli:

string(3) "foo"
string(3) "bar"
string(6) "foobar"

Zobacz też:

  • ReflectionProperty::getValue() - Gets value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::setStaticPropertyValue() - Sets static property value

ReflectionProperty::setAccessible
ReflectionProperty::__toString
ReflectionProperty


To string

ReflectionProperty::setValue
Reflector
ReflectionProperty
PHP Manual

ReflectionProperty::__toString

(PHP 5)

ReflectionProperty::__toString — To string

Opis

public string ReflectionProperty::__toString ( void )

To string.

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

Zobacz też:

  • ReflectionProperty::()
  • __toString()

ReflectionProperty::setValue
Reflector
ReflectionProperty


The Reflector interface

(PHP 5)

Wstęp

Reflector is an interface implemented by all exportable Reflection classes.

Krótki opis klasy

Reflector {
/* Metody */
abstract public static string export ( void )
abstract public string __toString ( void )
}

Spis treści

  • Reflector::export — Exports
  • Reflector::__toString — To string
ReflectionProperty::__toString
Reflector::export
Reflection


Exports

Reflector
Reflector::__toString
Reflector
PHP Manual

Reflector::export

(PHP 5)

Reflector::export — Exports

Opis

abstract public static string Reflector::export ( void )

Exports.

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

Zobacz też:

  • Reflection::__toString()

Reflector
Reflector::__toString
Reflector


To string

Reflector::export
ReflectionException
Reflector
PHP Manual

Reflector::__toString

(PHP 5)

Reflector::__toString — To string

Opis

abstract public string Reflector::__toString ( void )

To string.

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

Zobacz też:

  • ReflectionProperty::export() - Export
  • __toString()

Reflector::export
ReflectionException
Reflector


The ReflectionException class

(PHP 5)

Wstęp

The ReflectionException class.

Krótki opis klasy

ReflectionException extends Exception {
/* Właściwości */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 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 )
}
Reflector::__toString
Variable handling
Reflection


Variable handling

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Variable handling Funkcje
    • debug_zval_dump — Dumps a string representation of an internal zend value to output
    • doubleval — Alias dla floatval
    • empty — Determine whether a variable is empty
    • floatval — Get float value of a variable
    • get_defined_vars — Returns an array of all defined variables
    • get_resource_type — Returns the resource type
    • gettype — Get the type of a variable
    • import_request_variables — Import GET/POST/Cookie variables into the global scope
    • intval — Get the integer value of a variable
    • is_array — Finds whether a variable is an array
    • is_bool — Finds out whether a variable is a boolean
    • is_callable — Verify that the contents of a variable can be called as a function
    • is_double — Alias dla is_float
    • is_float — Finds whether the type of a variable is float
    • is_int — Find whether the type of a variable is integer
    • is_integer — Alias dla is_int
    • is_long — Alias dla is_int
    • is_null — Finds whether a variable is NULL
    • is_numeric — Finds whether a variable is a number or a numeric string
    • is_object — Finds whether a variable is an object
    • is_real — Alias dla is_float
    • is_resource — Finds whether a variable is a resource
    • is_scalar — Finds whether a variable is a scalar
    • is_string — Find whether the type of a variable is string
    • isset — Determine if a variable is set and is not NULL
    • print_r — Prints human-readable information about a variable
    • serialize — Generates a storable representation of a value
    • settype — Set the type of a variable
    • strval — Get string value of a variable
    • unserialize — Creates a PHP value from a stored representation
    • unset — Unset a given variable
    • var_dump — Dumps information about a variable
    • var_export — Outputs or returns a parsable string representation of a variable
ReflectionException
Wstęp
Zmienne i typy powiązanych rozszerzeń


Wstęp

For information on how variables behave, see the Variables entry in the Language Reference section of the manual.

Variable handling
Instalacja/Konfiguracja
Variable handling


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Variable handling


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Variables Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
unserialize_callback_func | NULL | PHP_INI_ALL | Available since PHP 4.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.

unserialize_callback_func string

The callback specified is called when unserialize() attempts to use an undefined class. A warning appears if the specified callback function is not defined, or if the callback function fails to define the missing class.

See also unserialize() and Autoloading Objects.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Variable handling Funkcje
Variable handling


Variable handling Funkcje

Spis treści

  • debug_zval_dump — Dumps a string representation of an internal zend value to output
  • doubleval — Alias dla floatval
  • empty — Determine whether a variable is empty
  • floatval — Get float value of a variable
  • get_defined_vars — Returns an array of all defined variables
  • get_resource_type — Returns the resource type
  • gettype — Get the type of a variable
  • import_request_variables — Import GET/POST/Cookie variables into the global scope
  • intval — Get the integer value of a variable
  • is_array — Finds whether a variable is an array
  • is_bool — Finds out whether a variable is a boolean
  • is_callable — Verify that the contents of a variable can be called as a function
  • is_double — Alias dla is_float
  • is_float — Finds whether the type of a variable is float
  • is_int — Find whether the type of a variable is integer
  • is_integer — Alias dla is_int
  • is_long — Alias dla is_int
  • is_null — Finds whether a variable is NULL
  • is_numeric — Finds whether a variable is a number or a numeric string
  • is_object — Finds whether a variable is an object
  • is_real — Alias dla is_float
  • is_resource — Finds whether a variable is a resource
  • is_scalar — Finds whether a variable is a scalar
  • is_string — Find whether the type of a variable is string
  • isset — Determine if a variable is set and is not NULL
  • print_r — Prints human-readable information about a variable
  • serialize — Generates a storable representation of a value
  • settype — Set the type of a variable
  • strval — Get string value of a variable
  • unserialize — Creates a PHP value from a stored representation
  • unset — Unset a given variable
  • var_dump — Dumps information about a variable
  • var_export — Outputs or returns a parsable string representation of a variable
Stałe predefiniowane
debug_zval_dump
Variable handling


Dumps a string representation of an internal zend value to output

Variable handling Funkcje
doubleval
Variable handling Funkcje
PHP Manual

debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5)

debug_zval_dump — Dumps a string representation of an internal zend value to output

Opis

void debug_zval_dump ( mixed $variable )

Dumps a string representation of an internal zend value to output.

Parametry

variable

The variable being evaluated.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 debug_zval_dump() example

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump(&$var1);
?>

Powyższy przykład wyświetli:

&string(11) "Hello World" refcount(3)

Informacja: Beware the refcount

The refcount value returned by this function is non-obvious in certain circumstances. For example, a developer might expect the above example to indicate a refcount of 2. The third reference is created when actually calling debug_zval_dump().

This behavior is further compounded when a variable is not passed to debug_zval_dump() by reference. To illustrate, consider a slightly modified version of the above example:

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump($var1); // not passed by reference, this time
?>

Powyższy przykład wyświetli:

string(11) "Hello World" refcount(1)

Why refcount(1)? Because a copy of $var1 is being made, when the function is called.

This function becomes even more confusing when a variable with a refcount of 1 is passed (by copy/value):

<?php
$var1 = 'Hello World';

debug_zval_dump($var1);
?>

Powyższy przykład wyświetli:

string(11) "Hello World" refcount(2)

A refcount of 2, here, is extremely non-obvious. Especially considering the above examples. So what's happening?

When a variable has a single reference (as did $var1 before it was used as an argument to debug_zval_dump()), PHP's engine optimizes the manner in which it is passed to a function. Internally, PHP treats $var1 like a reference (in that the refcount is increased for the scope of this function), with the caveat that if the passed reference happens to be written to, a copy is made, but only at the moment of writing. This is known as "copy on write."

So, if debug_zval_dump() happened to write to its sole parameter (and it doesn't), then a copy would be made. Until then, the parameter remains a reference, causing the refcount to be incremented to 2 for the scope of the function call.

Zobacz też:

  • var_dump() - Dumps information about a variable
  • debug_backtrace() - Generates a backtrace
  • References Explained
  • » References Explained (by Derick Rethans)

Variable handling Funkcje
doubleval
Variable handling Funkcje


Alias dla floatval

debug_zval_dump
empty
Variable handling Funkcje
PHP Manual

doubleval

(PHP 4, PHP 5)

doubleval — Alias dla floatval()

Opis

Ta funkcja jest aliasem dla: floatval().

Rejestr zmian

Wersja | Opis
4.2.0 | doubleval() została aliasem dla floatval(). Wcześniej istniała tylko doubleval().

debug_zval_dump
empty
Variable handling Funkcje


Determine whether a variable is empty

doubleval
floatval
Variable handling Funkcje
PHP Manual

empty

(PHP 4, PHP 5)

empty — Determine whether a variable is empty

Opis

bool empty ( mixed $var )

Determine whether a variable is considered to be empty.

Parametry

var

Variable to be checked

Informacja:

empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

Zwracane wartości

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

Rejestr zmian

Wersja | Opis
5.4.0 | Checking non-numeric offsets of strings returns TRUE.
5.0.0 | Objects with no properties are no longer considered empty.

Przykłady

Przykład #1 A simple empty() / isset() comparison.

<?php
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>

Przykład #2 empty() on String Offsets

PHP 5.4 changes how empty() behaves when passed string offsets.

<?php
$expected_array_got_string = 'somestring';
var_dump(empty($expected_array_got_string['some_key']));
var_dump(empty($expected_array_got_string[0]));
var_dump(empty($expected_array_got_string['0']));
var_dump(empty($expected_array_got_string[0.5]));
var_dump(empty($expected_array_got_string['0.5']));
var_dump(empty($expected_array_got_string['0 Mostel']));
?>

Output of the above example in PHP 5.3:

bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

Output of the above example in PHP 5.4:

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)

Notatki

Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Informacja:

When using empty() on inaccessible object properties, the __isset() overloading method will be called, if declared.

Zobacz też:

  • isset() - Determine if a variable is set and is not NULL
  • __isset()
  • unset() - Unset a given variable
  • array_key_exists() - Sprawdza czy podany klucz lub indeks istnieje w tablicy
  • count() - Zlicza ilość elementów w tablicy lub pól obiektu
  • strlen() - Get string length
  • The type comparison tables

doubleval
floatval
Variable handling Funkcje


Get float value of a variable

empty
get_defined_vars
Variable handling Funkcje
PHP Manual

floatval

(PHP 4 >= 4.2.0, PHP 5)

floatval — Get float value of a variable

Opis

float floatval ( mixed $var )

Gets the float value of var.

Parametry

var

May be any scalar type. floatval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.

Zwracane wartości

The float value of the given variable. Empty arrays return 0, non-empty arrays return 1.

Przykłady

Przykład #1 floatval() Example

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

Zobacz też:

  • intval() - Get the integer value of a variable
  • strval() - Get string value of a variable
  • settype() - Set the type of a variable
  • Type juggling

empty
get_defined_vars
Variable handling Funkcje


Returns an array of all defined variables

floatval
get_resource_type
Variable handling Funkcje
PHP Manual

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5)

get_defined_vars — Returns an array of all defined variables

Opis

array get_defined_vars ( void )

This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.

Zwracane wartości

A multidimensional array with all the variables.

Przykłady

Przykład #1 get_defined_vars() Example

<?php
$b = array(1, 1, 2, 3, 5, 8);

$arr = get_defined_vars();

// print $b
print_r($arr["b"]);

/* print path to the PHP interpreter (if used as a CGI)
 * e.g. /usr/local/bin/php */
echo $arr["_"];

// print the command-line parameters if any
print_r($arr["argv"]);

// print all the server vars
print_r($arr["_SERVER"]);

// print all the available keys for the arrays of variables
print_r(array_keys(get_defined_vars()));
?>

Rejestr zmian

Wersja | Opis
5.0.0 | The $GLOBALS variable is included in the results of the array returned.

Zobacz też:

  • isset() - Determine if a variable is set and is not NULL
  • get_defined_functions() - Returns an array of all defined functions
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values

floatval
get_resource_type
Variable handling Funkcje


Returns the resource type

get_defined_vars
gettype
Variable handling Funkcje
PHP Manual

get_resource_type

(PHP 4 >= 4.0.2, PHP 5)

get_resource_type — Returns the resource type

Opis

string get_resource_type ( resource $handle )

This function gets the type of the given resource.

Parametry

handle

The evaluated resource handle.

Zwracane wartości

If the given handle is a resource, this function will return a string representing its type. If the type is not identified by this function, the return value will be the string Unknown.

This function will return FALSE and generate an error if handle is not a resource.

Przykłady

Przykład #1 get_resource_type() example

<?php
// prints: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// prints: file
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// prints: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";
?>

get_defined_vars
gettype
Variable handling Funkcje


Get the type of a variable

get_resource_type
import_request_variables
Variable handling Funkcje
PHP Manual

gettype

(PHP 4, PHP 5)

gettype — Get the type of a variable

Opis

string gettype ( mixed $var )

Returns the type of the PHP variable var.

Ostrzeżenie

Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparison.

Instead, use the is_* functions.

Parametry

var

The variable being type checked.

Zwracane wartości

Possibles values for the returned string are:

  • "boolean"
  • "integer"
  • "double" (for historical reasons "double" is returned in case of a float, and not simply "float")
  • "string"
  • "array"
  • "object"
  • "resource"
  • "NULL"
  • "unknown type"

Przykłady

Przykład #1 gettype() example

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

integer
double
NULL
object
string

Zobacz też:

  • settype() - Set the type of a variable
  • get_class() - Zwraca nazwę klasy zadanego obiektu
  • is_array() - Finds whether a variable is an array
  • is_bool() - Finds out whether a variable is a boolean
  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_null() - Finds whether a variable is NULL
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_object() - Finds whether a variable is an object
  • is_resource() - Finds whether a variable is a resource
  • is_scalar() - Finds whether a variable is a scalar
  • is_string() - Find whether the type of a variable is string
  • function_exists() - Return TRUE if the given function has been defined
  • method_exists() - Sprawdza czy metoda klasy istnieje

get_resource_type
import_request_variables
Variable handling Funkcje


Import GET/POST/Cookie variables into the global scope

gettype
intval
Variable handling Funkcje
PHP Manual

import_request_variables

(PHP 4 >= 4.1.0, PHP 5)

import_request_variables — Import GET/POST/Cookie variables into the global scope

Opis

bool import_request_variables ( string $types [, string $prefix ] )

Imports GET/POST/Cookie variables into the global scope. It is useful if you disabled register_globals, but would like to see some variables in the global scope.

If you're interested in importing other variables into the global scope, such as $_SERVER, consider using extract().

Parametry

types

Using the types parameter, you can specify which request variables to import. You can use 'G', 'P' and 'C' characters respectively for GET, POST and Cookie. These characters are not case sensitive, so you can also use any combination of 'g', 'p' and 'c'. POST includes the POST uploaded file information.

Informacja:

Note that the order of the letters matters, as when using "GP", the POST variables will overwrite GET variables with the same name. Any other letters than GPC are discarded.

prefix

Variable name prefix, prepended before all variable's name imported into the global scope. So if you have a GET value named "userid", and provide a prefix "pref_", then you'll get a global variable named $pref_userid.

Informacja:

Although the prefix parameter is optional, you will get an E_NOTICE level error if you specify no prefix, or specify an empty string as a prefix. This is a possible security hazard. Notice level errors are not displayed using the default error reporting level.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 import_request_variables() example

<?php
// This will import GET and POST vars
// with an "rvar_" prefix
import_request_variables("gp", "rvar_");

echo $rvar_foo;
?>

Zobacz też:

  • $_REQUEST
  • register_globals
  • Predefined Variables
  • extract() - Importuj zmienne do bieżącej tablicy symboli z tablicy

gettype
intval
Variable handling Funkcje


Get the integer value of a variable

import_request_variables
is_array
Variable handling Funkcje
PHP Manual

intval

(PHP 4, PHP 5)

intval — Get the integer value of a variable

Opis

int intval ( mixed $var [, int $base = 10 ] )

Returns the integer value of var, using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.

Parametry

var

The scalar value being converted to an integer

base

The base for the conversion

Zwracane wartości

The integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1.

The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.

Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.

Przykłady

Przykład #1 intval() examples

The following examples are based on a 32 bit system.

<?php
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
echo intval('+42');                   // 42
echo intval('-42');                   // -42
echo intval(042);                     // 34
echo intval('042');                   // 42
echo intval(1e10);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
echo intval(array());                 // 0
echo intval(array('foo', 'bar'));     // 1
?>

Notatki

Informacja:

The base parameter has no effect unless the var parameter is a string.

Rejestr zmian

Wersja | Opis
5.1.0 | Throws E_NOTICE and returns 1, when an object is passed to var.

Zobacz też:

  • floatval() - Get float value of a variable
  • strval() - Get string value of a variable
  • settype() - Set the type of a variable
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • Type juggling
  • BCMath Arbitrary Precision Mathematics Functions

import_request_variables
is_array
Variable handling Funkcje


Finds whether a variable is an array

intval
is_bool
Variable handling Funkcje
PHP Manual

is_array

(PHP 4, PHP 5)

is_array — Finds whether a variable is an array

Opis

bool is_array ( mixed $var )

Finds whether the given variable is an array.

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is an array, FALSE otherwise.

Przykłady

Przykład #1 Check that variable is an array

<?php
$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";

$no = 'this is a string';

echo is_array($no) ? 'Array' : 'not an Array';
?>

Powyższy przykład wyświetli:

Array
not an Array

Zobacz też:

  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object

intval
is_bool
Variable handling Funkcje


Finds out whether a variable is a boolean

is_array
is_callable
Variable handling Funkcje
PHP Manual

is_bool

(PHP 4, PHP 5)

is_bool — Finds out whether a variable is a boolean

Opis

bool is_bool ( mixed $var )

Finds whether the given variable is a boolean.

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is a boolean, FALSE otherwise.

Przykłady

Przykład #1 is_bool() examples

<?php
$a = false;
$b = 0;

// Since $a is a boolean, it will return true
if (is_bool($a) === true) {
    echo "Yes, this is a boolean";
}

// Since $b is not a boolean, it will return false
if (is_bool($b) === false) {
    echo "No, this is not a boolean";
}
?>

Zobacz też:

  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array

is_array
is_callable
Variable handling Funkcje


Verify that the contents of a variable can be called as a function

is_bool
is_double
Variable handling Funkcje
PHP Manual

is_callable

(PHP 4 >= 4.0.6, PHP 5)

is_callable — Verify that the contents of a variable can be called as a function

Opis

bool is_callable ( callback $name [, bool $syntax_only = false [, string &$callable_name ]] )

Verify that the contents of a variable can be called as a function. This can check that a simple variable contains the name of a valid function, or that an array contains a properly encoded object and function name.

Parametry

name

The callback function to check

syntax_only

If set to TRUE the function only verifies that name might be a function or method. It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback. The valid ones are supposed to have only 2 entries, the first of which is an object or a string, and the second a string.

callable_name

Receives the "callable name". In the example below it is "someClass::someMethod". Note, however, that despite the implication that someClass::SomeMethod() is a callable static method, this is not the case.

Zwracane wartości

Returns TRUE if name is callable, FALSE otherwise.

Przykłady

Przykład #1 is_callable() example

<?php
//  How to check a variable to see if it can be called
//  as a function.

//
//  Simple variable containing a function
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name));  // bool(true)

echo $callable_name, "\n";  // someFunction

//
//  Array containing a method
//

class someClass {

  function someMethod()
  {
  }

}

$anObject = new someClass();

$methodVariable = array($anObject, 'someMethod');

var_dump(is_callable($methodVariable, true, $callable_name));  //  bool(true)

echo $callable_name, "\n";  //  someClass::someMethod

?>

Zobacz też:

  • function_exists() - Return TRUE if the given function has been defined
  • method_exists() - Sprawdza czy metoda klasy istnieje

is_bool
is_double
Variable handling Funkcje


Alias dla is_float

is_callable
is_float
Variable handling Funkcje
PHP Manual

is_double

(PHP 4, PHP 5)

is_double — Alias dla is_float()

Opis

Ta funkcja jest aliasem dla: is_float().

is_callable
is_float
Variable handling Funkcje


Finds whether the type of a variable is float

is_double
is_int
Variable handling Funkcje
PHP Manual

is_float

(PHP 4, PHP 5)

is_float — Finds whether the type of a variable is float

Opis

bool is_float ( mixed $var )

Finds whether the type of the given variable is float.

Informacja:

To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is a float, FALSE otherwise.

Przykłady

Przykład #1 is_float() example

<?php
if (is_float(27.25)) {
    echo "is float\n";
} else {
    echo "is not float\n";
}
var_dump(is_float('abc'));
var_dump(is_float(23));
var_dump(is_float(23.5));
var_dump(is_float(1e7));  //Scientific Notation
var_dump(is_float(true));
?>

Powyższy przykład wyświetli:

is float
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)

Zobacz też:

  • is_bool() - Finds out whether a variable is a boolean
  • is_int() - Find whether the type of a variable is integer
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_string() - Find whether the type of a variable is string
  • is_array() - Finds whether a variable is an array
  • is_object() - Finds whether a variable is an object

is_double
is_int
Variable handling Funkcje


Find whether the type of a variable is integer

is_float
is_integer
Variable handling Funkcje
PHP Manual

is_int

(PHP 4, PHP 5)

is_int — Find whether the type of a variable is integer

Opis

bool is_int ( mixed $var )

Finds whether the type of the given variable is integer.

Informacja:

To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is an integer, FALSE otherwise.

Przykłady

Przykład #1 is_int() example

<?php
if (is_int(23)) {
    echo "is integer\n";
} else {
    echo "is not an integer\n";
}
var_dump(is_int(23));
var_dump(is_int("23"));
var_dump(is_int(23.5));
var_dump(is_int(true));
?>

Powyższy przykład wyświetli:

is integer
bool(true)
bool(false)
bool(false)
bool(false)

Zobacz też:

  • is_bool() - Finds out whether a variable is a boolean
  • is_float() - Finds whether the type of a variable is float
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_string() - Find whether the type of a variable is string
  • is_array() - Finds whether a variable is an array
  • is_object() - Finds whether a variable is an object

is_float
is_integer
Variable handling Funkcje


Alias dla is_int

is_int
is_long
Variable handling Funkcje
PHP Manual

is_integer

(PHP 4, PHP 5)

is_integer — Alias dla is_int()

Opis

Ta funkcja jest aliasem dla: is_int().

is_int
is_long
Variable handling Funkcje


Alias dla is_int

is_integer
is_null
Variable handling Funkcje
PHP Manual

is_long

(PHP 4, PHP 5)

is_long — Alias dla is_int()

Opis

Ta funkcja jest aliasem dla: is_int().

is_integer
is_null
Variable handling Funkcje


Finds whether a variable is NULL

is_long
is_numeric
Variable handling Funkcje
PHP Manual

is_null

(PHP 4 >= 4.0.4, PHP 5)

is_null — Finds whether a variable is NULL

Opis

bool is_null ( mixed $var )

Finds whether the given variable is NULL.

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is null, FALSE otherwise.

Przykłady

Przykład #1 is_null() example

<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

?>
Notice: Undefined variable: inexistent in ...
bool(true)
bool(true)

Zobacz też:

  • The NULL type
  • isset() - Determine if a variable is set and is not NULL
  • is_bool() - Finds out whether a variable is a boolean
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array

is_long
is_numeric
Variable handling Funkcje


Finds whether a variable is a number or a numeric string

is_null
is_object
Variable handling Funkcje
PHP Manual

is_numeric

(PHP 4, PHP 5)

is_numeric — Finds whether a variable is a number or a numeric string

Opis

bool is_numeric ( mixed $var )

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is a number or a numeric string, FALSE otherwise.

Przykłady

Przykład #1 is_numeric() examples

<?php
$tests = array(
    "42",
    1337,
    "1e4",
    "not numeric",
    array(),
    9.1
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo "'{$element}' is numeric", PHP_EOL;
    } else {
        echo "'{$element}' is NOT numeric", PHP_EOL;
    }
}
?>

Powyższy przykład wyświetli:

'42' is numeric
'1337' is numeric
'1e4' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric

Zobacz też:

  • ctype_digit() - Check for numeric character(s)
  • is_bool() - Finds out whether a variable is a boolean
  • is_null() - Finds whether a variable is NULL
  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array

is_null
is_object
Variable handling Funkcje


Finds whether a variable is an object

is_numeric
is_real
Variable handling Funkcje
PHP Manual

is_object

(PHP 4, PHP 5)

is_object — Finds whether a variable is an object

Opis

bool is_object ( mixed $var )

Finds whether the given variable is an object.

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is an object, FALSE otherwise.

Przykłady

Przykład #1 is_object() example

<?php
// Declare a simple function to return an
// array from our object
function get_students($obj)
{
    if (!is_object($obj)) {
        return false;
    }

    return $obj->students;
}

// Declare a new class instance and fill up
// some values
$obj = new stdClass();
$obj->students = array('Kalle', 'Ross', 'Felipe');

var_dump(get_students(null));
var_dump(get_students($obj));
?>

Notatki

Informacja:

This function will return FALSE if used on an unserialized object where the class definition is not present (even though gettype() returns object).

Zobacz też:

  • is_bool() - Finds out whether a variable is a boolean
  • is_int() - Find whether the type of a variable is integer
  • is_float() - Finds whether the type of a variable is float
  • is_string() - Find whether the type of a variable is string
  • is_array() - Finds whether a variable is an array

is_numeric
is_real
Variable handling Funkcje


Alias dla is_float

is_object
is_resource
Variable handling Funkcje
PHP Manual

is_real

(PHP 4, PHP 5)

is_real — Alias dla is_float()

Opis

Ta funkcja jest aliasem dla: is_float().

is_object
is_resource
Variable handling Funkcje


Finds whether a variable is a resource

is_real
is_scalar
Variable handling Funkcje
PHP Manual

is_resource

(PHP 4, PHP 5)

is_resource — Finds whether a variable is a resource

Opis

bool is_resource ( mixed $var )

Finds whether the given variable is a resource.

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is a resource, FALSE otherwise.

Przykłady

Przykład #1 is_resource() example

<?php

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!is_resource($db_link)) {
    die('Can\'t connect : ' . mysql_error());
}

?>

Zobacz też:

  • The resource-type documentation
  • get_resource_type() - Returns the resource type

is_real
is_scalar
Variable handling Funkcje


Finds whether a variable is a scalar

is_resource
is_string
Variable handling Funkcje
PHP Manual

is_scalar

(PHP 4 >= 4.0.5, PHP 5)

is_scalar — Finds whether a variable is a scalar

Opis

bool is_scalar ( mixed $var )

Finds whether the given variable is a scalar.

Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource are not scalar.

Informacja:

is_scalar() does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers. This implementation detail should not be relied upon, as it may change.

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is a scalar FALSE otherwise.

Przykłady

Przykład #1 is_scalar() example

<?php
function show_var($var)
{
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

show_var($pi);
show_var($proteins)

?>

Powyższy przykład wyświetli:

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobin"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(10) "ferredoxin"
}

Zobacz też:

  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_real() - Alias dla is_float
  • is_string() - Find whether the type of a variable is string
  • is_bool() - Finds out whether a variable is a boolean
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array

is_resource
is_string
Variable handling Funkcje


Find whether the type of a variable is string

is_scalar
isset
Variable handling Funkcje
PHP Manual

is_string

(PHP 4, PHP 5)

is_string — Find whether the type of a variable is string

Opis

bool is_string ( mixed $var )

Finds whether the type given variable is string.

Parametry

var

The variable being evaluated.

Zwracane wartości

Returns TRUE if var is of type string, FALSE otherwise.

Przykłady

Przykład #1 is_string() example

<?php
if (is_string("23")) {
    echo "is string\n";
} else {
    echo "is not a string\n";
}
var_dump(is_string('abc'));
var_dump(is_string("23"));
var_dump(is_string(23.5));
var_dump(is_string(true));
?>

Powyższy przykład wyświetli:

is string
bool(true)
bool(true)
bool(false)
bool(false)

Zobacz też:

  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_bool() - Finds out whether a variable is a boolean
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array

is_scalar
isset
Variable handling Funkcje


Determine if a variable is set and is not NULL

is_string
print_r
Variable handling Funkcje
PHP Manual

isset

(PHP 4, PHP 5)

isset — Determine if a variable is set and is not NULL

Opis

bool isset ( mixed $var [, mixed $... ] )

Determine if a variable is set and is not NULL.

If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.

If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

Parametry

var

The variable to be checked.

...

Another variable ...

Zwracane wartości

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

Rejestr zmian

Wersja | Opis
5.4.0 | Checking non-numeric offsets of strings now returns FALSE.

Przykłady

Przykład #1 isset() Examples

<?php

$var = '';

// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
    echo "This var is set so I will print.";
}

// In the next examples we'll use var_dump to output
// the return value of isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

?>

This also work for elements in arrays:

<?php

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try:
var_dump(array_key_exists('hello', $a)); // TRUE

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

?>

Przykład #2 isset() on String Offsets

PHP 5.4 changes how isset() behaves when passed string offsets.

<?php
$expected_array_got_string = 'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0 Mostel']));
?>

Output of the above example in PHP 5.3:

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Output of the above example in PHP 5.4:

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)

Notatki

Ostrzeżenie

isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Informacja:

When using isset() on inaccessible object properties, the __isset() overloading method will be called, if declared.

Zobacz też:

  • empty() - Determine whether a variable is empty
  • __isset()
  • unset() - Unset a given variable
  • defined() - Checks whether a given named constant exists
  • the type comparison tables
  • array_key_exists() - Sprawdza czy podany klucz lub indeks istnieje w tablicy
  • is_null() - Finds whether a variable is NULL
  • the error control @ operator

is_string
print_r
Variable handling Funkcje


Prints human-readable information about a variable

isset
serialize
Variable handling Funkcje
PHP Manual

print_r

(PHP 4, PHP 5)

print_r — Prints human-readable information about a variable

Opis

mixed print_r ( mixed $expression [, bool $return = false ] )

print_r() displays information about a variable in a way that's readable by humans.

print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown.

Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.

Parametry

expression

The expression to be printed.

return

If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it.

Zwracane wartości

If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.

When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.

Notatki

Informacja:

Ta funkcja używa wewnętrznie buforowania wyjścia, więc nie może być użyta wewnątrz funkcji callback podanej w wywołaniu ob_start().

Rejestr zmian

Wersja | Opis
4.3.0 | The return parameter was added. If you need to capture the output of print_r() with an older version of PHP prior, use the output-control functions.
4.0.4 | Prior to PHP 4.0.4, print_r() will continue forever if given an array or object that contains a direct or indirect reference to itself. An example is print_r($GLOBALS) because $GLOBALS is itself a global variable that contains a reference to itself.

Przykłady

Przykład #1 print_r() example

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

Powyższy przykład wyświetli:

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Przykład #2 return parameter example

<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r
?>

Zobacz też:

  • ob_start() - Turn on output buffering
  • var_dump() - Dumps information about a variable
  • var_export() - Outputs or returns a parsable string representation of a variable

isset
serialize
Variable handling Funkcje


Generates a storable representation of a value

print_r
settype
Variable handling Funkcje
PHP Manual

serialize

(PHP 4, PHP 5)

serialize — Generates a storable representation of a value

Opis

string serialize ( mixed $value )

Generates a storable representation of a value

This is useful for storing or passing PHP values around without losing their type and structure.

To make the serialized string into a PHP value again, use unserialize().

Parametry

value

The value to be serialized. serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. Circular references inside the array/object you are serializing will also be stored. Any other reference will be lost.

When serializing objects, PHP will attempt to call the member function __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using unserialize() the __wakeup() member function is called.

Informacja:

Object's private members have the class name prepended to the member name; protected members have a '*' prepended to the member name. These prepended values have null bytes on either side.

Zwracane wartości

Returns a string containing a byte-stream representation of value that can be stored anywhere.

Przykłady

Przykład #1 serialize() example

<?php
// $session_data contains a multi-dimensional array with session
// information for the current user.  We use serialize() to store
// it in a database at the end of the request.

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
      "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO sessions (id, data) VALUES(?, ?)");
    if (!odbc_execute($stmt, $sqldata)) {
        /* Something went wrong.. */
    }
}
?>

Rejestr zmian

Wersja | Opis
4.0.7 | The object serialization process was fixed.

Notatki

Informacja:

Note that many built-in PHP objects cannot be serialized. However, those with this ability either implement the Serializable interface or the magic __sleep() and __wakeup() methods. If an internal class does not fulfill any of those requirements, it cannot reliably be serialized.

There are some historical exceptions to the above rule, where some internal objects could be serialized without implementing the interface or exposing the methods. Notably, the ArrayObject prior to PHP 5.2.0.

Zobacz też:

  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects
  • __sleep()
  • __wakeup()

print_r
settype
Variable handling Funkcje


Set the type of a variable

serialize
strval
Variable handling Funkcje
PHP Manual

settype

(PHP 4, PHP 5)

settype — Set the type of a variable

Opis

bool settype ( mixed &$var , string $type )

Set the type of variable var to type.

Parametry

var

The variable being converted.

type

Possibles values of type are:

  • "boolean" (or, since PHP 4.2.0, "bool")
  • "integer" (or, since PHP 4.2.0, "int")
  • "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")
  • "string"
  • "array"
  • "object"
  • "null" (since PHP 4.2.0)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 settype() example

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)
?>

Notatki

Informacja:

Maximum value for "int" is PHP_INT_MAX.

Zobacz też:

  • gettype() - Get the type of a variable
  • type-casting
  • type-juggling

serialize
strval
Variable handling Funkcje


Get string value of a variable

settype
unserialize
Variable handling Funkcje
PHP Manual

strval

(PHP 4, PHP 5)

strval — Get string value of a variable

Opis

string strval ( mixed $var )

Get the string value of a variable. See the documentation on string for more information on converting to string.

This function performs no formatting on the returned value. If you are looking for a way to format a numeric value as a string, please see sprintf() or number_format().

Parametry

var

The variable that is being converted to a string.

var may be any scalar type or an object that implements the __toString() method. You cannot use strval() on arrays or on objects that do not implement the __toString() method.

Zwracane wartości

The string value of var.

Przykłady

Przykład #1 strval() example using PHP 5's magic __toString() method.

<?php
class StrValTest
{
    public function __toString()
    {
        return __CLASS__;
    }
}

// Prints 'StrValTest'
echo strval(new StrValTest);
?>

Zobacz też:

  • floatval() - Get float value of a variable
  • intval() - Get the integer value of a variable
  • settype() - Set the type of a variable
  • sprintf() - Return a formatted string
  • number_format() - Formatuje liczbę według szablonu
  • Type juggling
  • __toString()

settype
unserialize
Variable handling Funkcje


Creates a PHP value from a stored representation

strval
unset
Variable handling Funkcje
PHP Manual

unserialize

(PHP 4, PHP 5)

unserialize — Creates a PHP value from a stored representation

Opis

mixed unserialize ( string $str )

unserialize() takes a single serialized variable and converts it back into a PHP value.

Parametry

str

The serialized string.

If the variable being unserialized is an object, after successfully reconstructing the object PHP will automatically attempt to call the __wakeup() member function (if it exists).

Informacja: unserialize_callback_func directive

It's possible to set a callback-function which will be called, if an undefined class should be instantiated during unserializing. (to prevent getting an incomplete object "__PHP_Incomplete_Class".) Use your php.ini, ini_set() or .htaccess to define 'unserialize_callback_func'. Everytime an undefined class should be instantiated, it'll be called. To disable this feature just empty this setting.

Zwracane wartości

The converted value is returned, and can be a boolean, integer, float, string, array or object.

In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued.

Rejestr zmian

Wersja | Opis
4.2.0 | The directive unserialize_callback_func became available.

Przykłady

Przykład #1 unserialize() example

<?php
// Here, we use unserialize() to load session data to the
// $session_data array from the string selected from a database.
// This example complements the one described with serialize().

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array($_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata) || !odbc_fetch_into($stmt, $tmp)) {
    // if the execute or fetch fails, initialize to empty array
    $session_data = array();
} else {
    // we should now have the serialized data in $tmp[0].
    $session_data = unserialize($tmp[0]);
    if (!is_array($session_data)) {
        // something went wrong, initialize to empty array
        $session_data = array();
    }
}
?>

Przykład #2 unserialize_callback_func example

<?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

// unserialize_callback_func directive available as of PHP 4.2.0
ini_set('unserialize_callback_func', 'mycallback'); // set your callback_function

function mycallback($classname)
{
    // just include a file containing your classdefinition
    // you get $classname to figure out which classdefinition is required
}
?>

Notatki

Ostrzeżenie

FALSE is returned both in the case of an error and if unserializing the serialized FALSE value. It is possible to catch this special case by comparing str with serialize(false) or by catching the issued E_NOTICE.

Zobacz też:

  • serialize() - Generates a storable representation of a value
  • Autoloading Objects
  • unserialize_callback_func
  • __wakeup()

strval
unset
Variable handling Funkcje


Unset a given variable

unserialize
var_dump
Variable handling Funkcje
PHP Manual

unset

(PHP 4, PHP 5)

unset — Unset a given variable

Opis

void unset ( mixed $var [, mixed $... ] )

unset() destroys the specified variables.

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

<?php
function destroy_foo()
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

Powyższy przykład wyświetli:

bar

To unset() a global variable inside of a function, then use the $GLOBALS array to do so:

<?php
function foo()
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>

If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

<?php
function foo(&$bar)
{
    unset($bar);
    $bar = "blah";
}

$bar = 'something';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?>

Powyższy przykład wyświetli:

something
something

If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.

<?php
function foo()
{
    static $bar;
    $bar++;
    echo "Before unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "after unset: $bar\n";
}

foo();
foo();
foo();
?>

Powyższy przykład wyświetli:

Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23

Parametry

var

The variable to be unset.

...

Another variable ...

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
4.0.1 | Added support for multiple arguments.

Przykłady

Przykład #1 unset() example

<?php
// destroy a single variable
unset($foo);

// destroy a single element of an array
unset($bar['quux']);

// destroy more than one variable
unset($foo1, $foo2, $foo3);
?>

Przykład #2 Using (unset) casting

(unset) casting is often confused with the unset() function. (unset) casting serves only as a NULL-type cast, for completeness. It does not alter the variable it's casting.

<?php
$name = 'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

Powyższy przykład wyświetli:

NULL
string(6) "Felipe"

Notatki

Informacja: Ponieważ jest to element składni języka a nie funkcja, nie może być on wywoływany używając zmiennych funkcji

Informacja:

It is possible to unset even object properties visible in current context.

Informacja:

It is not possible to unset $this inside an object method since PHP 5.

Informacja:

When using unset() on inaccessible object properties, the __unset() overloading method will be called, if declared.

Zobacz też:

  • isset() - Determine if a variable is set and is not NULL
  • empty() - Determine whether a variable is empty
  • __unset()
  • array_splice() - Usuń część tablicy i zamień ją na coś innego

unserialize
var_dump
Variable handling Funkcje


Dumps information about a variable

unset
var_export
Variable handling Funkcje
PHP Manual

var_dump

(PHP 4, PHP 5)

var_dump — Dumps information about a variable

Opis

void var_dump ( mixed $expression [, mixed $... ] )

This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

In PHP 5 all public, private and protected properties of objects will be returned in the output.

Wskazówka

Ze wszystkim, co wysyła dane bezpośrednio do przeglądarki, możesz używać funkcji kontroli wyjścia aby przejąć wyjście tej funkcji i zapisać je w zmiennej tekstowej (na przykład).

Parametry

expression

The variable you want to dump.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 var_dump() example

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

Powyższy przykład wyświetli:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
<?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?>

Powyższy przykład wyświetli:

float(3.1)
bool(true)

Zobacz też:

  • var_export() - Outputs or returns a parsable string representation of a variable
  • print_r() - Prints human-readable information about a variable

unset
var_export
Variable handling Funkcje


Outputs or returns a parsable string representation of a variable

var_dump
Usługi sieciowe
Variable handling Funkcje
PHP Manual

var_export

(PHP 4 >= 4.2.0, PHP 5)

var_export — Outputs or returns a parsable string representation of a variable

Opis

mixed var_export ( mixed $expression [, bool $return = false ] )

var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.

Parametry

expression

The variable you want to export.

return

If used and set to TRUE, var_export() will return the variable representation instead of outputing it.

Zwracane wartości

Returns the variable representation when the return parameter is used and evaluates to TRUE. Otherwise, this function will return NULL.

Notatki

Informacja:

Ta funkcja używa wewnętrznie buforowania wyjścia, więc nie może być użyta wewnątrz funkcji callback podanej w wywołaniu ob_start().

Rejestr zmian

Wersja | Opis
5.1.0 | Possibility to export classes and arrays containing classes using the __set_state() magic method.

Przykłady

Przykład #1 var_export() Examples

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

Powyższy przykład wyświetli:

array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php

$b = 3.1;
$v = var_export($b, true);
echo $v;

?>

Powyższy przykład wyświetli:

3.1

Przykład #2 Exporting classes since PHP 5.1.0

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>

Powyższy przykład wyświetli:

A::__set_state(array(
   'var' => 5,
))

Przykład #3 Using __set_state() (since PHP 5.1.0)

<?php
class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);
?>

Powyższy przykład wyświetli:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

Notatki

Informacja:

Variables of type resource couldn't be exported by this function.

Informacja:

var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialize().

Zobacz też:

  • print_r() - Prints human-readable information about a variable
  • serialize() - Generates a storable representation of a value
  • var_dump() - Dumps information about a variable

var_dump
Usługi sieciowe
Variable handling Funkcje


Usługi sieciowe

  • OAuth
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • OAuth Funkcje
    • OAuth — The OAuth class
    • OAuthProvider — The OAuthProvider class
    • OAuthException — OAuthException class
  • SCA
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • SCA Funkcje
  • SOAP
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • SOAP Funkcje
    • SoapClient — The SoapClient class
    • SoapServer — The SoapServer class
    • SoapFault — The SoapFault class
    • SoapHeader — The SoapHeader class
    • SoapParam — The SoapParam class
    • SoapVar — The SoapVar class
  • XML-RPC
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • XML-RPC Funkcje
var_export
OAuth
Opis funkcji


OAuth

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • FireEagle
  • OAuth Funkcje
    • oauth_get_sbs — Generate a Signature Base String
    • oauth_urlencode — Encode a URI to RFC 3986
  • OAuth — The OAuth class
    • OAuth::__construct — Create a new OAuth object
    • OAuth::__destruct — The destructor
    • OAuth::disableDebug — Turn off verbose debugging
    • OAuth::disableRedirects — Turn off redirects
    • OAuth::disableSSLChecks — Turn off SSL checks
    • OAuth::enableDebug — Turn on verbose debugging
    • OAuth::enableRedirects — Turn on redirects
    • OAuth::enableSSLChecks — Turn on SSL checks
    • OAuth::fetch — Fetch an OAuth protected resource
    • OAuth::generateSignature — Generate a signature
    • OAuth::getAccessToken — Fetch an access token
    • OAuth::getCAPath — Gets CA information
    • OAuth::getLastResponse — Get the last response
    • OAuth::getLastResponseHeaders — Get headers for last response
    • OAuth::getLastResponseInfo — Get HTTP information about the last response
    • OAuth::getRequestHeader — Generate OAuth header string signature
    • OAuth::getRequestToken — Fetch a request token
    • OAuth::setAuthType — Set authorization type
    • OAuth::setCAPath — Set CA path and info
    • OAuth::setNonce — Set the nonce for subsequent requests
    • OAuth::setRequestEngine — The setRequestEngine purpose
    • OAuth::setRSACertificate — Set the RSA certificate
    • OAuth::setSSLChecks — Tweak specific SSL checks for requests.
    • OAuth::setTimestamp — Set the timestamp
    • OAuth::setToken — Sets the token and secret
    • OAuth::setVersion — Set the OAuth version
  • OAuthProvider — The OAuthProvider class
    • OAuthProvider::addRequiredParameter — Add required parameters
    • OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback
    • OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback
    • OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback
    • OAuthProvider::checkOAuthRequest — Check an oauth request
    • OAuthProvider::__construct — Constructs a new OAuthProvider object
    • OAuthProvider::consumerHandler — Set the consumerHandler handler callback
    • OAuthProvider::generateToken — Generate a random token
    • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter — Remove a required parameter
    • OAuthProvider::reportProblem — Report a problem
    • OAuthProvider::setParam — Set a parameter
    • OAuthProvider::setRequestTokenPath — Set request token path
    • OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback
    • OAuthProvider::tokenHandler — Set the tokenHandler handler callback
  • OAuthException — OAuthException class
Usługi sieciowe
Wstęp
Usługi sieciowe


Wstęp

This extension provides OAuth consumer and provider bindings. OAuth is an authorization protocol built on top of HTTP which allows applications to securely access data without having to store usernames and passwords.

OAuth
Instalacja/Konfiguracja
OAuth


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
OAuth


Wymagania

PECL/oauth requires PHP 5.1 or newer, ext/hash and ext/pcre.

PECL/oauth may optionally require libcurl if selected at build time. If configured with libcurl, it must be built with HTTPS support.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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://pear.php.net/package/oauth

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

Most of these constants involve problems, which are also described within the official OAuth » Problem Reporting documentation. Note however, that these constant names are specific to PHP, although the naming scheme is similar.

OAUTH_SIG_METHOD_RSASHA1 (string)
OAuth RSA-SHA1 signature method.
OAUTH_SIG_METHOD_HMACSHA1 (string)

OAuth HMAC-SHA1 signature method.

OAUTH_SIG_METHOD_HMACSHA256 (string)
OAuth HMAC-SHA256 signature method.
OAUTH_AUTH_TYPE_AUTHORIZATION (string)

This constant represents putting OAuth parameters in the Authorization header.

OAUTH_AUTH_TYPE_NONE (string)

This constant indicates a NoAuth OAuth request.

OAUTH_AUTH_TYPE_URI (string)

This constant represents putting OAuth parameters in the request URI.

OAUTH_AUTH_TYPE_FORM (string)

This constant represents putting OAuth parameters as part of the HTTP POST body.

OAUTH_HTTP_METHOD_GET (string)

Use the GET method for the OAuth request.

OAUTH_HTTP_METHOD_POST (string)

Use the POST method for the OAuth request.

OAUTH_HTTP_METHOD_PUT (string)

Use the PUT method for the OAuth request.

OAUTH_HTTP_METHOD_HEAD (string)

Use the HEAD method for the OAuth request.

OAUTH_HTTP_METHOD_DELETE (string)
Use the DELETE method for the OAuth request.
OAUTH_REQENGINE_STREAMS (integer)
Used by OAuth::setRequestEngine() to set the engine to PHP streams, as opposed to OAUTH_REQENGINE_CURL for Curl.
OAUTH_REQENGINE_CURL (integer)
Used by OAuth::setRequestEngine() to set the engine to Curl, as opposed to OAUTH_REQENGINE_STREAMS for PHP streams.
OAUTH_OK (integer)
Life is good.
OAUTH_BAD_NONCE (integer)
The oauth_nonce value was used in a previous request, therefore it cannot be used now.
OAUTH_BAD_TIMESTAMP (integer)
The oauth_timestamp value was not accepted by the service provider. In this case, the response should also contain the oauth_acceptable_timestamps parameter.
OAUTH_CONSUMER_KEY_UNKNOWN (integer)
The oauth_consumer_key is temporarily unacceptable to the service provider. For example, the service provider may be throttling the consumer.
OAUTH_CONSUMER_KEY_REFUSED (integer)
The consumer key was refused.
OAUTH_INVALID_SIGNATURE (integer)
The oauth_signature is invalid, as it does not match the signature computed by the service provider.
OAUTH_TOKEN_USED (integer)
The oauth_token has been consumed. It can no longer be used because it has already been used in the previous request(s).
OAUTH_TOKEN_EXPIRED (integer)
The oauth_token has expired.
OAUTH_TOKEN_REVOKED (integer)
The oauth_token has been revoked, and will never be accepted.
OAUTH_TOKEN_REJECTED (integer)
The oauth_token was not accepted by the service provider. The reason is not known, but it might be because the token was never issued, already consumed, expired, and/or forgotten by the service provider.
OAUTH_VERIFIER_INVALID (integer)
The oauth_verifier is incorrect.
OAUTH_PARAMETER_ABSENT (integer)
A required parameter was not received. In this case, the response should also contain the oauth_parameters_absent parameter.
OAUTH_SIGNATURE_METHOD_REJECTED (integer)
The oauth_signature_method was not accepted by service provider.

Typy zasobów
Przykłady
OAuth


Przykłady

Spis treści

  • FireEagle
Stałe predefiniowane
FireEagle
OAuth


FireEagle

<?php
$req_url = 'https://fireeagle.yahooapis.com/oauth/request_token';
$authurl = 'https://fireeagle.yahoo.net/oauth/authorize';
$acc_url = 'https://fireeagle.yahooapis.com/oauth/access_token';
$api_url = 'https://fireeagle.yahooapis.com/api/0.1';
$conskey = 'your_consumer_key';
$conssec = 'your_consumer_secret';

session_start();

// In state=1 the next request should include an oauth_token.
// If it doesn't go back to 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
  $oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
  $oauth->enableDebug();
  if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
    $request_token_info = $oauth->getRequestToken($req_url);
    $_SESSION['secret'] = $request_token_info['oauth_token_secret'];
    $_SESSION['state'] = 1;
    header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
    exit;
  } else if($_SESSION['state']==1) {
    $oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
    $access_token_info = $oauth->getAccessToken($acc_url);
    $_SESSION['state'] = 2;
    $_SESSION['token'] = $access_token_info['oauth_token'];
    $_SESSION['secret'] = $access_token_info['oauth_token_secret'];
  }
  $oauth->setToken($_SESSION['token'],$_SESSION['secret']);
  $oauth->fetch("$api_url/user.json");
  $json = json_decode($oauth->getLastResponse());
  print_r($json);
} catch(OAuthException $E) {
  print_r($E);
}
?>

Przykłady
OAuth Funkcje
Przykłady


OAuth Funkcje

Spis treści

  • oauth_get_sbs — Generate a Signature Base String
  • oauth_urlencode — Encode a URI to RFC 3986
FireEagle
oauth_get_sbs
OAuth


Generate a Signature Base String

OAuth Funkcje
oauth_urlencode
OAuth Funkcje
PHP Manual

oauth_get_sbs

(PECL OAuth >=0.99.7)

oauth_get_sbs — Generate a Signature Base String

Opis

string oauth_get_sbs ( string $http_method , string $uri [, array $request_parameters ] )

Generates a Signature Base String according to pecl/oauth.

Parametry

http_method

The HTTP method.

uri

URI to encode.

request_parameters

Array of request parameters.

Zwracane wartości

Returns a Signature Base String.

OAuth Funkcje
oauth_urlencode
OAuth Funkcje


Encode a URI to RFC 3986

oauth_get_sbs
OAuth
OAuth Funkcje
PHP Manual

oauth_urlencode

(PECL OAuth >=0.99.2)

oauth_urlencode — Encode a URI to RFC 3986

Opis

string oauth_urlencode ( string $uri )

Encodes a URI to » RFC 3986.

Parametry

uri

URI to encode.

Zwracane wartości

Returns an » RFC 3986 encoded string.

oauth_get_sbs
OAuth
OAuth Funkcje


The OAuth class

(No version information available, might only be in SVN)

Wstęp

The OAuth extension provides a simple interface to interact with data providers using the OAuth HTTP specification to protect private resources.

Krótki opis klasy

OAuth {
/* Properties */
public $debug ;
public $sslChecks ;
public $debugInfo ;
/* Metody */
public __construct ( string $consumer_key , string $consumer_secret [, string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 [, int $auth_type = 0 ]] )
public void __destruct ( void )
public bool disableDebug ( void )
public bool disableRedirects ( void )
public bool disableSSLChecks ( void )
public bool enableDebug ( void )
public bool enableRedirects ( void )
public bool enableSSLChecks ( void )
public mixed fetch ( string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]] )
public string generateSignature ( string $http_method , string $url [, mixed $extra_parameters ] )
public array getAccessToken ( string $access_token_url [, string $auth_session_handle [, string $verifier_token ]] )
public array getCAPath ( void )
public string getLastResponse ( void )
public string getLastResponseHeaders ( void )
public array getLastResponseInfo ( void )
public string getRequestHeader ( string $http_method , string $url [, mixed $extra_parameters ] )
public array getRequestToken ( string $request_token_url [, string $callback_url ] )
public mixed setAuthType ( int $auth_type )
public mixed setCAPath ([ string $ca_path [, string $ca_info ]] )
public mixed setNonce ( string $nonce )
public void setRequestEngine ( int $reqengine )
public mixed setRSACertificate ( string $cert )
public bool setSSLChecks ( int $sslcheck )
public mixed setTimestamp ( string $timestamp )
public bool setToken ( string $token , string $token_secret )
public bool setVersion ( string $version )
}

Właściwości

debug

sslChecks

debugInfo

Spis treści

  • OAuth::__construct — Create a new OAuth object
  • OAuth::__destruct — The destructor
  • OAuth::disableDebug — Turn off verbose debugging
  • OAuth::disableRedirects — Turn off redirects
  • OAuth::disableSSLChecks — Turn off SSL checks
  • OAuth::enableDebug — Turn on verbose debugging
  • OAuth::enableRedirects — Turn on redirects
  • OAuth::enableSSLChecks — Turn on SSL checks
  • OAuth::fetch — Fetch an OAuth protected resource
  • OAuth::generateSignature — Generate a signature
  • OAuth::getAccessToken — Fetch an access token
  • OAuth::getCAPath — Gets CA information
  • OAuth::getLastResponse — Get the last response
  • OAuth::getLastResponseHeaders — Get headers for last response
  • OAuth::getLastResponseInfo — Get HTTP information about the last response
  • OAuth::getRequestHeader — Generate OAuth header string signature
  • OAuth::getRequestToken — Fetch a request token
  • OAuth::setAuthType — Set authorization type
  • OAuth::setCAPath — Set CA path and info
  • OAuth::setNonce — Set the nonce for subsequent requests
  • OAuth::setRequestEngine — The setRequestEngine purpose
  • OAuth::setRSACertificate — Set the RSA certificate
  • OAuth::setSSLChecks — Tweak specific SSL checks for requests.
  • OAuth::setTimestamp — Set the timestamp
  • OAuth::setToken — Sets the token and secret
  • OAuth::setVersion — Set the OAuth version
oauth_urlencode
OAuth::__construct
OAuth


Create a new OAuth object

OAuth
OAuth::__destruct
OAuth
PHP Manual

OAuth::__construct

(PECL OAuth >= 0.99.1)

OAuth::__construct — Create a new OAuth object

Opis

public OAuth::__construct ( string $consumer_key , string $consumer_secret [, string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 [, int $auth_type = 0 ]] )

Creates a new OAuth object

Parametry

consumer_key

The consumer key provided by the service provider.

consumer_secret

The consumer secret provided by the service provider.

signature_method

This optional parameter defines which signature method to use, by default it is OAUTH_SIG_METHOD_HMACSHA1 (HMAC-SHA1).

auth_type

This optional parameter defines how to pass the OAuth parameters to a consumer, by default it is OAUTH_AUTH_TYPE_AUTHORIZATION (in the Authorization header).

OAuth
OAuth::__destruct
OAuth


The destructor

OAuth::__construct
OAuth::disableDebug
OAuth
PHP Manual

OAuth::__destruct

(PECL OAuth >= 0.99.9)

OAuth::__destruct — The destructor

Opis

public void OAuth::__destruct ( void )

The destructor.

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

Nie jest zwracana żadna wartość.

Zobacz też:

  • OAuth::__construct() - Create a new OAuth object
OAuth::__construct
OAuth::disableDebug
OAuth


Turn off verbose debugging

OAuth::__destruct
OAuth::disableRedirects
OAuth
PHP Manual

OAuth::disableDebug

(PECL OAuth >= 0.99.3)

OAuth::disableDebug — Turn off verbose debugging

Opis

public bool OAuth::disableDebug ( void )

Turns off verbose request information (off by default). Alternatively, the debug property can be set to a FALSE value to turn debug off.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE

Rejestr zmian

Wersja | Opis
0.99.8 | The related debug property was added.

Zobacz też:

  • OAuth::enableDebug() - Turn on verbose debugging

OAuth::__destruct
OAuth::disableRedirects
OAuth


Turn off redirects

OAuth::disableDebug
OAuth::disableSSLChecks
OAuth
PHP Manual

OAuth::disableRedirects

(PECL OAuth >= 0.99.9)

OAuth::disableRedirects — Turn off redirects

Opis

public bool OAuth::disableRedirects ( void )

Disable redirects from being followed automatically, thus allowing the request to be manually redirected.

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

TRUE

Zobacz też:

  • OAuth::enableRedirects() - Turn on redirects
OAuth::disableDebug
OAuth::disableSSLChecks
OAuth


Turn off SSL checks

OAuth::disableRedirects
OAuth::enableDebug
OAuth
PHP Manual

OAuth::disableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::disableSSLChecks — Turn off SSL checks

Opis

public bool OAuth::disableSSLChecks ( void )

Turns off the usual SSL peer certificate and host checks, this is not for production environments. Alternatively, the sslChecks member can be set to FALSE to turn SSL checks off.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE

Rejestr zmian

Wersja | Opis
0.99.8 | The sslChecks member was added

Zobacz też:

  • OAuth::enableSSLChecks() - Turn on SSL checks

OAuth::disableRedirects
OAuth::enableDebug
OAuth


Turn on verbose debugging

OAuth::disableSSLChecks
OAuth::enableRedirects
OAuth
PHP Manual

OAuth::enableDebug

(PECL OAuth >= 0.99.3)

OAuth::enableDebug — Turn on verbose debugging

Opis

public bool OAuth::enableDebug ( void )

Turns on verbose request information useful for debugging, the debug information is stored in the debugInfo member. Alternatively, the debug member can be set to a non-FALSE value to turn debug on.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE

Rejestr zmian

Wersja | Opis
0.99.8 | The debug and debugInfo members were added

Zobacz też:

  • OAuth::disableDebug() - Turn off verbose debugging

OAuth::disableSSLChecks
OAuth::enableRedirects
OAuth


Turn on redirects

OAuth::enableDebug
OAuth::enableSSLChecks
OAuth
PHP Manual

OAuth::enableRedirects

(PECL OAuth >= 0.99.9)

OAuth::enableRedirects — Turn on redirects

Opis

public bool OAuth::enableRedirects ( void )

Follow and sign redirects automatically, which is enabled by default.

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

TRUE

Zobacz też:

  • OAuth::disableRedirects() - Turn off redirects
OAuth::enableDebug
OAuth::enableSSLChecks
OAuth


Turn on SSL checks

OAuth::enableRedirects
OAuth::fetch
OAuth
PHP Manual

OAuth::enableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::enableSSLChecks — Turn on SSL checks

Opis

public bool OAuth::enableSSLChecks ( void )

Turns on the usual SSL peer certificate and host checks (enabled by default). Alternatively, the sslChecks member can be set to a non-FALSE value to turn SSL checks off.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE

Rejestr zmian

Wersja | Opis
0.99.8 | The sslChecks member was added

Zobacz też:

  • OAuth::disableSSLChecks() - Turn off SSL checks

OAuth::enableRedirects
OAuth::fetch
OAuth


Fetch an OAuth protected resource

OAuth::enableSSLChecks
OAuth::generateSignature
OAuth
PHP Manual

OAuth::fetch

(PECL OAuth >= 0.99.1)

OAuth::fetch — Fetch an OAuth protected resource

Opis

public mixed OAuth::fetch ( string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]] )

Fetch a resource.

Parametry

protected_resource_url

URL to the OAuth protected resource.

extra_parameters

Extra parameters to send with the request for the resource.

http_method

One of the OAUTH_HTTP_METHOD_* OAUTH constants, which includes GET, POST, PUT, HEAD, or DELETE.

HEAD (OAUTH_HTTP_METHOD_HEAD) can be useful for discovering information prior to the request (if OAuth credentials are in the Authorization header).

http_headers

HTTP client headers (such as User-Agent, Accept, etc.)

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
1.0.0 | Poprzednio zwrócony NULL w przypadku niepowodzenia, w miejsce FALSE.
0.99.5 | The http_method parameter was added
0.99.8 | The http_headers parameter was added

Przykłady

Przykład #1 OAuth::fetch() example

<?php
try {
    $oauth = new OAuth("consumer_key","consumer_secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauth->setToken("access_token","access_token_secret");

    $oauth->fetch("http://photos.example.net/photo?file=vacation.jpg");

    $response_info = $oauth->getLastResponseInfo();
    header("Content-Type: {$response_info["content_type"]}");
    echo $oauth->getLastResponse();
} catch(OAuthException $E) {
    echo "Exception caught!\n";
    echo "Response: ". $E->lastResponse . "\n";
}
?>

Zobacz też:

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::setToken() - Sets the token and secret

OAuth::enableSSLChecks
OAuth::generateSignature
OAuth


Generate a signature

OAuth::fetch
OAuth::getAccessToken
OAuth
PHP Manual

OAuth::generateSignature

(No version information available, might only be in SVN)

OAuth::generateSignature — Generate a signature

Opis

public string OAuth::generateSignature ( string $http_method , string $url [, mixed $extra_parameters ] )

Generate a signature based on the final HTTP method, URL and a string/array of parameters.

Parametry

http_method

HTTP method for request

url

URL for request

extra_parameters

String or array of additional parameters.

Zwracane wartości

A string containing the generated signature lub FALSE w przypadku niepowodzenia

OAuth::fetch
OAuth::getAccessToken
OAuth


Fetch an access token

OAuth::generateSignature
OAuth::getCAPath
OAuth
PHP Manual

OAuth::getAccessToken

(PECL OAuth >= 0.99.1)

OAuth::getAccessToken — Fetch an access token

Opis

public array OAuth::getAccessToken ( string $access_token_url [, string $auth_session_handle [, string $verifier_token ]] )

Fetch an access token, secret and any additional response parameters from the service provider.

Parametry

access_token_url

URL to the access token API.

auth_session_handle

Authorization session handle, this parameter does not have any citation in the core OAuth 1.0 specification but may be implemented by large providers. » See ScalableOAuth for more information.

verifier_token

For service providers which support 1.0a, a verifier_token must be passed while exchanging the request token for the access token. If the verifier_token is present in $_GET or $_POST it is passed automatically and the caller does not need to specify a verifier_token (usually if the access token is exchanged at the oauth_callback URL). » See ScalableOAuth for more information.

Zwracane wartości

Returns an array containing the parsed OAuth response on success or FALSE on failure.

Rejestr zmian

Wersja | Opis
1.0.0 | Poprzednio zwrócony NULL w przypadku niepowodzenia, w miejsce FALSE.
0.99.9 | The verifier_token parameter was added

Przykłady

Przykład #1 OAuth::getAccessToken() example

<?php
try {
    $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    $oauth->setToken($request_token,$request_token_secret);
    $access_token_info = $oauth->getAccessToken("https://example.com/oauth/access_token");
    if(!empty($access_token_info)) {
        print_r($access_token_info);
    } else {
        print "Failed fetching access token, response was: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Response: ". $E->lastResponse . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

Zobacz też:

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::setToken() - Sets the token and secret

OAuth::generateSignature
OAuth::getCAPath
OAuth


Gets CA information

OAuth::getAccessToken
OAuth::getLastResponse
OAuth
PHP Manual

OAuth::getCAPath

(PECL OAuth >= 0.99.8)

OAuth::getCAPath — Gets CA information

Opis

public array OAuth::getCAPath ( void )

Gets the Certificate Authority information, which includes the ca_path and ca_info set by OAuth::setCaPath().

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 Certificate Authority information, specifically as ca_path and ca_info keys within the returned associative array.

Zobacz też:

  • OAuth::setCAPath() - Set CA path and info
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
OAuth::getAccessToken
OAuth::getLastResponse
OAuth


Get the last response

OAuth::getCAPath
OAuth::getLastResponseHeaders
OAuth
PHP Manual

OAuth::getLastResponse

(PECL OAuth >= 0.99.1)

OAuth::getLastResponse — Get the last response

Opis

public string OAuth::getLastResponse ( void )

Get the raw response of the most recent request.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string containing the last response.

Zobacz też:

  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::fetch() - Fetch an OAuth protected resource

OAuth::getCAPath
OAuth::getLastResponseHeaders
OAuth


Get headers for last response

OAuth::getLastResponse
OAuth::getLastResponseInfo
OAuth
PHP Manual

OAuth::getLastResponseHeaders

(No version information available, might only be in SVN)

OAuth::getLastResponseHeaders — Get headers for last response

Opis

public string OAuth::getLastResponseHeaders ( void )

Get headers for last response.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A string containing the last response's headers lub FALSE w przypadku niepowodzenia

OAuth::getLastResponse
OAuth::getLastResponseInfo
OAuth


Get HTTP information about the last response

OAuth::getLastResponseHeaders
OAuth::getRequestHeader
OAuth
PHP Manual

OAuth::getLastResponseInfo

(PECL OAuth >= 0.99.1)

OAuth::getLastResponseInfo — Get HTTP information about the last response

Opis

public array OAuth::getLastResponseInfo ( void )

Get HTTP information about the last response.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns an array containing the response information for the last request. Constants from curl_getinfo() may be used.

Zobacz też:

  • OAuth::fetch() - Fetch an OAuth protected resource
  • OAuth::getLastResponse() - Get the last response

OAuth::getLastResponseHeaders
OAuth::getRequestHeader
OAuth


Generate OAuth header string signature

OAuth::getLastResponseInfo
OAuth::getRequestToken
OAuth
PHP Manual

OAuth::getRequestHeader

(No version information available, might only be in SVN)

OAuth::getRequestHeader — Generate OAuth header string signature

Opis

public string OAuth::getRequestHeader ( string $http_method , string $url [, mixed $extra_parameters ] )

Generate OAuth header string signature based on the final HTTP method, URL and a string/array of parameters

Parametry

http_method

HTTP method for request.

url

URL for request.

extra_parameters

String or array of additional parameters.

Zwracane wartości

A string containing the generated request header lub FALSE w przypadku niepowodzenia

OAuth::getLastResponseInfo
OAuth::getRequestToken
OAuth


Fetch a request token

OAuth::getRequestHeader
OAuth::setAuthType
OAuth
PHP Manual

OAuth::getRequestToken

(PECL OAuth >= 0.99.1)

OAuth::getRequestToken — Fetch a request token

Opis

public array OAuth::getRequestToken ( string $request_token_url [, string $callback_url ] )

Fetch a request token, secret and any additional response parameters from the service provider.

Parametry

request_token_url

URL to the request token API.

callback_url

OAuth callback URL. If callback_url is passed and is an empty value, it is set to "oob" to address the OAuth 2009.1 advisory.

Zwracane wartości

Returns an array containing the parsed OAuth response on success or FALSE on failure.

Rejestr zmian

Wersja | Opis
1.0.0 | Poprzednio zwrócony NULL w przypadku niepowodzenia, w miejsce FALSE.
0.99.9 | The callback_url parameter was added

Przykłady

Przykład #1 OAuth::getRequestToken() example

<?php
try {
    $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    $request_token_info = $oauth->getRequestToken("https://example.com/oauth/request_token");
    if(!empty($request_token_info)) {
        print_r($request_token_info);
    } else {
        print "Failed fetching request token, response was: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Response: ". $E->lastResponse . "\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

Zobacz też:

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response

OAuth::getRequestHeader
OAuth::setAuthType
OAuth


Set authorization type

OAuth::getRequestToken
OAuth::setCAPath
OAuth
PHP Manual

OAuth::setAuthType

(PECL OAuth >= 0.99.1)

OAuth::setAuthType — Set authorization type

Opis

public mixed OAuth::setAuthType ( int $auth_type )

Set where the OAuth parameters should be passed.

Parametry

auth_type

auth_type can be one of the following flags (in order of decreasing preference as per OAuth 1.0 section 5.2):

OAUTH_AUTH_TYPE_AUTHORIZATION
Pass the OAuth parameters in the HTTP Authorization header.
OAUTH_AUTH_TYPE_FORM
Append the OAuth parameters to the HTTP POST request body.
OAUTH_AUTH_TYPE_URI
Append the OAuth parameters to the request URI.
OAUTH_AUTH_TYPE_NONE
None.

Zwracane wartości

Returns TRUE if a parameter is correctly set, otherwise FALSE (e.g., if an invalid auth_type is passed in.)

Rejestr zmian

Wersja | Opis
1.0.0 | Poprzednio zwrócony NULL w przypadku niepowodzenia, w miejsce FALSE.

OAuth::getRequestToken
OAuth::setCAPath
OAuth


Set CA path and info

OAuth::setAuthType
OAuth::setNonce
OAuth
PHP Manual

OAuth::setCAPath

(PECL OAuth >= 0.99.8)

OAuth::setCAPath — Set CA path and info

Opis

public mixed OAuth::setCAPath ([ string $ca_path [, string $ca_info ]] )

Sets the Certificate Authority (CA), both for path and info.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

ca_path

The CA Path being set.

ca_info

The CA Info being set.

Zwracane wartości

Returns TRUE on success, or FALSE if either ca_path or ca_info are considered invalid.

Rejestr zmian

Wersja | Opis
1.0.0 | Poprzednio zwrócony NULL w przypadku niepowodzenia, w miejsce FALSE.

Zobacz też:

  • OAuth::getCaPath() - Gets CA information
OAuth::setAuthType
OAuth::setNonce
OAuth


Set the nonce for subsequent requests

OAuth::setCAPath
OAuth::setRequestEngine
OAuth
PHP Manual

OAuth::setNonce

(PECL OAuth >= 0.99.1)

OAuth::setNonce — Set the nonce for subsequent requests

Opis

public mixed OAuth::setNonce ( string $nonce )

Sets the nonce for all subsequent requests.

Parametry

nonce

The value for oauth_nonce.

Zwracane wartości

Returns TRUE on success, or FALSE if the nonce is considered invalid.

Rejestr zmian

Wersja | Opis
1.0.0 | Poprzednio zwrócony NULL w przypadku niepowodzenia, w miejsce FALSE.

Zobacz też:

  • OAuth::setToken() - Sets the token and secret
  • OAuth::setAuthType() - Set authorization type
  • OAuth::setVersion() - Set the OAuth version

OAuth::setCAPath
OAuth::setRequestEngine
OAuth


The setRequestEngine purpose

OAuth::setNonce
OAuth::setRSACertificate
OAuth
PHP Manual

OAuth::setRequestEngine

(PECL OAuth >= 1.0.0)

OAuth::setRequestEngine — The setRequestEngine purpose

Opis

public void OAuth::setRequestEngine ( int $reqengine )

Sets the Request Engine, that will be sending the HTTP requests.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

reqengine

The desired request engine. Set to OAUTH_REQENGINE_STREAMS to use PHP Streams, or OAUTH_REQENGINE_CURL to use Curl.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Emits an OAuthException exception if an invalid request engine is chosen.

Przykłady

Przykład #1 OAuth::setRequestEngine() example

<?php
$consumer = new OAuth();

$consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS);
?>

Zobacz też:

  • Curl
  • PHP streams
  • OAuthException
OAuth::setNonce
OAuth::setRSACertificate
OAuth


Set the RSA certificate

OAuth::setRequestEngine
OAuth::setSSLChecks
OAuth
PHP Manual

OAuth::setRSACertificate

(PECL OAuth >= 1.0.0)

OAuth::setRSACertificate — Set the RSA certificate

Opis

public mixed OAuth::setRSACertificate ( string $cert )

Sets the RSA certificate.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

cert

The RSA certificate.

Zwracane wartości

Returns TRUE on success, or FALSE on failure (e.g., the RSA certificate cannot be parsed.)

Rejestr zmian

Wersja | Opis
1.0.0 | Poprzednio zwrócony NULL w przypadku niepowodzenia, w miejsce FALSE.

Przykłady

Przykład #1 An OAuth::setRsaCertificate() example

<?php
$consume = new OAuth('1234', '', OAUTH_SIG_METHOD_RSASHA1);

$consume->setRSACertificate(file_get_contents('test.pem'));
?>

Zobacz też:

  • OAuth::setCaPath() - Set CA path and info
OAuth::setRequestEngine
OAuth::setSSLChecks
OAuth


Tweak specific SSL checks for requests.

OAuth::setRSACertificate
OAuth::setTimestamp
OAuth
PHP Manual

OAuth::setSSLChecks

(No version information available, might only be in SVN)

OAuth::setSSLChecks — Tweak specific SSL checks for requests.

Opis

public bool OAuth::setSSLChecks ( int $sslcheck )

Tweak specific SSL checks for requests.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

sslcheck

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

OAuth::setRSACertificate
OAuth::setTimestamp
OAuth


Set the timestamp

OAuth::setSSLChecks
OAuth::setToken
OAuth
PHP Manual

OAuth::setTimestamp

(PECL OAuth >= 1.0.0)

OAuth::setTimestamp — Set the timestamp

Opis

public mixed OAuth::setTimestamp ( string $timestamp )

Sets the OAuth timestamp for subsequent requests.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

timestamp

The timestamp.

Zwracane wartości

Returns TRUE, unless the timestamp is invalid, in which case FALSE is returned.

Rejestr zmian

Wersja | Opis
1.0.0 | Poprzednio zwrócony NULL w przypadku niepowodzenia, w miejsce FALSE.

Zobacz też:

  • OAuth::setNonce() - Set the nonce for subsequent requests
OAuth::setSSLChecks
OAuth::setToken
OAuth


Sets the token and secret

OAuth::setTimestamp
OAuth::setVersion
OAuth
PHP Manual

OAuth::setToken

(PECL OAuth >= 0.99.1)

OAuth::setToken — Sets the token and secret

Opis

public bool OAuth::setToken ( string $token , string $token_secret )

Set the token and secret for subsequent requests.

Parametry

token

The OAuth token.

token_secret

The OAuth token secret.

Zwracane wartości

TRUE

Przykłady

Przykład #1 OAuth::setToken() example

<?php
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
$oauth->setToken("token","token-secret");
?>

OAuth::setTimestamp
OAuth::setVersion
OAuth


Set the OAuth version

OAuth::setToken
OAuthProvider
OAuth
PHP Manual

OAuth::setVersion

(PECL OAuth >= 0.99.1)

OAuth::setVersion — Set the OAuth version

Opis

public bool OAuth::setVersion ( string $version )

Sets the OAuth version for subsequent requests

Parametry

version

OAuth version, default value is always "1.0"

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

OAuth::setToken
OAuthProvider
OAuth


The OAuthProvider class

(No version information available, might only be in SVN)

Wstęp

Manages an OAuth provider class.

See also an external in-depth tutorial titled » Writing an OAuth Provider Service, which takes a hands-on approach to providing this service. There are also » OAuth provider examples within the OAuth extensions sources.

Krótki opis klasy

OAuthProvider {
/* Methods */
final public bool addRequiredParameter ( string $req_params )
public void callconsumerHandler ( void )
public void callTimestampNonceHandler ( void )
public void calltokenHandler ( void )
public void checkOAuthRequest ([ string $uri [, string $method ]] )
public __construct ([ array $params_array ] )
public void consumerHandler ( callback $callback_function )
final public static string generateToken ( int $size [, bool $strong = false ] )
public void is2LeggedEndpoint ( mixed $params_array )
public void isRequestTokenEndpoint ( bool $will_issue_request_token )
final public bool removeRequiredParameter ( string $req_params )
final public static string reportProblem ( string $oauthexception [, bool $send_headers = true ] )
final public bool setParam ( string $param_key [, mixed $param_val ] )
final public bool setRequestTokenPath ( string $path )
public void timestampNonceHandler ( callback $callback_function )
public void tokenHandler ( callback $callback_function )
}

Spis treści

  • OAuthProvider::addRequiredParameter — Add required parameters
  • OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback
  • OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback
  • OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback
  • OAuthProvider::checkOAuthRequest — Check an oauth request
  • OAuthProvider::__construct — Constructs a new OAuthProvider object
  • OAuthProvider::consumerHandler — Set the consumerHandler handler callback
  • OAuthProvider::generateToken — Generate a random token
  • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
  • OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint
  • OAuthProvider::removeRequiredParameter — Remove a required parameter
  • OAuthProvider::reportProblem — Report a problem
  • OAuthProvider::setParam — Set a parameter
  • OAuthProvider::setRequestTokenPath — Set request token path
  • OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback
  • OAuthProvider::tokenHandler — Set the tokenHandler handler callback
OAuth::setVersion
OAuthProvider::addRequiredParameter
OAuth


Add required parameters

OAuthProvider
OAuthProvider::callconsumerHandler
OAuthProvider
PHP Manual

OAuthProvider::addRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::addRequiredParameter — Add required parameters

Opis

final public bool OAuthProvider::addRequiredParameter ( string $req_params )

Add required oauth provider parameters.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

req_params

The required parameters.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OAuthProvider::removeRequiredParameter() - Remove a required parameter
OAuthProvider
OAuthProvider::callconsumerHandler
OAuthProvider


Calls the consumerNonceHandler callback

OAuthProvider::addRequiredParameter
OAuthProvider::callTimestampNonceHandler
OAuthProvider
PHP Manual

OAuthProvider::callconsumerHandler

(No version information available, might only be in SVN)

OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback

Opis

public void OAuthProvider::callconsumerHandler ( void )

Calls the registered consumer handler callback function, which is set with OAuthProvider::consumerHandler().

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

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Zgłasza błąd E_ERROR jeśli funkcja zwrotna nie może zostać wywołana, lub gdy nie jest określona.

Zobacz też:

  • OAuthProvider::consumerHandler() - Set the consumerHandler handler callback
OAuthProvider::addRequiredParameter
OAuthProvider::callTimestampNonceHandler
OAuthProvider


Calls the timestampNonceHandler callback

OAuthProvider::callconsumerHandler
OAuthProvider::calltokenHandler
OAuthProvider
PHP Manual

OAuthProvider::callTimestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback

Opis

public void OAuthProvider::callTimestampNonceHandler ( void )

Calls the registered timestamp handler callback function, which is set with OAuthProvider::timestampNonceHandler().

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

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Zgłasza błąd E_ERROR jeśli funkcja zwrotna nie może zostać wywołana, lub gdy nie jest określona.

Zobacz też:

  • OAuthProvider::timestampNonceHandler() - Set the timestampNonceHandler handler callback
OAuthProvider::callconsumerHandler
OAuthProvider::calltokenHandler
OAuthProvider


Calls the tokenNonceHandler callback

OAuthProvider::callTimestampNonceHandler
OAuthProvider::checkOAuthRequest
OAuthProvider
PHP Manual

OAuthProvider::calltokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback

Opis

public void OAuthProvider::calltokenHandler ( void )

Calls the registered token handler callback function, which is set with OAuthProvider::tokenHandler().

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

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Zgłasza błąd E_ERROR jeśli funkcja zwrotna nie może zostać wywołana, lub gdy nie jest określona.

Zobacz też:

  • OAuthProvider::tokenHandler() - Set the tokenHandler handler callback
OAuthProvider::callTimestampNonceHandler
OAuthProvider::checkOAuthRequest
OAuthProvider


Check an oauth request

OAuthProvider::calltokenHandler
OAuthProvider::__construct
OAuthProvider
PHP Manual

OAuthProvider::checkOAuthRequest

(PECL OAuth >= 1.0.0)

OAuthProvider::checkOAuthRequest — Check an oauth request

Opis

public void OAuthProvider::checkOAuthRequest ([ string $uri [, string $method ]] )

Checks an OAuth request.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

uri

The optional URI, or endpoint.

method

The HTTP method. Optionally pass in one of the OAUTH_HTTP_METHOD_* OAuth constants.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Emits an E_ERROR level error if the HTTP method cannot be detected.

Zobacz też:

  • OAuthProvider::reportProblem() - Report a problem
OAuthProvider::calltokenHandler
OAuthProvider::__construct
OAuthProvider


Constructs a new OAuthProvider object

OAuthProvider::checkOAuthRequest
OAuthProvider::consumerHandler
OAuthProvider
PHP Manual

OAuthProvider::__construct

(PECL OAuth >= 1.0.0)

OAuthProvider::__construct — Constructs a new OAuthProvider object

Opis

public OAuthProvider::__construct ([ array $params_array ] )

Initiates a new OAuthProvider object.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

params_array

Setting these optional parameters is limited to the CLI SAPI.

Zwracane wartości

An OAuthProvider object.

Przykłady

Przykład #1 OAuthProvider::__construct() example

<?php
try {

    $op = new OAuthProvider();

    // Uses user-defined callback functions
    $op->consumerHandler(array($this, 'lookupConsumer'));
    $op->timestampNonceHandler(array($this, 'timestampNonceChecker'));
    $op->tokenHandler(array($this, 'myTokenHandler'));

    // Ignore the foo_uri parameter
    $op->setParam('foo_uri', NULL);

    // No token needed for this end point
    $op->setRequestTokenPath('/v1/oauth/request_token');

    $op->checkOAuthRequest();

} catch (OAuthException $e) {

    echo OAuthProvider::reportProblem($e);
}
?>

Zobacz też:

  • OAuthProvider::setParam() - Set a parameter
OAuthProvider::checkOAuthRequest
OAuthProvider::consumerHandler
OAuthProvider


Set the consumerHandler handler callback

OAuthProvider::__construct
OAuthProvider::generateToken
OAuthProvider
PHP Manual

OAuthProvider::consumerHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::consumerHandler — Set the consumerHandler handler callback

Opis

public void OAuthProvider::consumerHandler ( callback $callback_function )

Sets the consumer handler callback, which will later be called with OAuthProvider::callConsumerHandler().

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

callback_function

The callback functions name.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Example OAuthProvider::consumerHandler() callback

<?php
function lookupConsumer($provider) {

    if ($provider->consumer_key === 'unknown') {
        return OAUTH_CONSUMER_KEY_UNKNOWN;
    } else if($provider->consumer_key == 'blacklisted' || $provider->consumer_key === 'throttled') {
        return OAUTH_CONSUMER_KEY_REFUSED;
    }

    $provider->consumer_secret = "the_consumers_secret";

    return OAUTH_OK;
}
?>

Zobacz też:

  • OAuthProvider::callConsumerHandler() - Calls the consumerNonceHandler callback
OAuthProvider::__construct
OAuthProvider::generateToken
OAuthProvider


Generate a random token

OAuthProvider::consumerHandler
OAuthProvider::is2LeggedEndpoint
OAuthProvider
PHP Manual

OAuthProvider::generateToken

(PECL OAuth >= 1.0.0)

OAuthProvider::generateToken — Generate a random token

Opis

final public static string OAuthProvider::generateToken ( int $size [, bool $strong = false ] )

Generates a string of pseudo-random bytes.

Parametry

size

The desired token length, in terms of bytes.

strong

Setting to TRUE means /dev/random will be used for entropy, as otherwise the non-blocking /dev/urandom is used. This parameter is ignored on Windows.

Zwracane wartości

The generated token, as a string of bytes.

Błędy/Wyjątki

If the strong parameter is TRUE, then an E_WARNING level error will be emitted when the fallback rand() implementation is used to fill the remaining random bytes (e.g., when not enough random data was found, initially).

Przykłady

Przykład #1 OAuthProvider::generateToken() example

<?php
$p = new OAuthProvider();

$t = $p->generateToken(4);

echo strlen($t),  PHP_EOL;
echo bin2hex($t), PHP_EOL;

?>

Powyższy przykład wyświetli coś podobnego do:

4
b6a82c27

Notatki

Informacja:

When not enough random data is available to the system, this function will fill the remaining random bytes using the internal PHP rand() implementation.

Zobacz też:

  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • mcrypt_create_iv() - Creates an initialization vector (IV) from a random source
OAuthProvider::consumerHandler
OAuthProvider::is2LeggedEndpoint
OAuthProvider


is2LeggedEndpoint

OAuthProvider::generateToken
OAuthProvider::isRequestTokenEndpoint
OAuthProvider
PHP Manual

OAuthProvider::is2LeggedEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint

Opis

public void OAuthProvider::is2LeggedEndpoint ( mixed $params_array )

The 2-legged flow, or request signing. It does not require a token.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

params_array

Zwracane wartości

An OAuthProvider object.

Przykłady

Przykład #1 OAuthProvider::is2LeggedEndpoint() example

<?php

$provider = new OAuthProvider();

$provider->is2LeggedEndpoint(true);

?>

Zobacz też:

  • OAuthProvider::__construct() - Constructs a new OAuthProvider object
OAuthProvider::generateToken
OAuthProvider::isRequestTokenEndpoint
OAuthProvider


Sets isRequestTokenEndpoint

OAuthProvider::is2LeggedEndpoint
OAuthProvider::removeRequiredParameter
OAuthProvider
PHP Manual

OAuthProvider::isRequestTokenEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint

Opis

public void OAuthProvider::isRequestTokenEndpoint ( bool $will_issue_request_token )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

will_issue_request_token

Sets whether or not it will issue a request token, thus determining if OAuthProvider::tokenHandler() needs to be called.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • OAuthProvider::setRequestTokenPath() - Set request token path
  • OAuthProvider::reportProblem() - Report a problem
OAuthProvider::is2LeggedEndpoint
OAuthProvider::removeRequiredParameter
OAuthProvider


Remove a required parameter

OAuthProvider::isRequestTokenEndpoint
OAuthProvider::reportProblem
OAuthProvider
PHP Manual

OAuthProvider::removeRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::removeRequiredParameter — Remove a required parameter

Opis

final public bool OAuthProvider::removeRequiredParameter ( string $req_params )

Removes a required parameter.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

req_params

The required parameter to be removed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OAuthProvider::setParam() - Set a parameter
  • OAuthProvider::addRequiredParameter() - Add required parameters
OAuthProvider::isRequestTokenEndpoint
OAuthProvider::reportProblem
OAuthProvider


Report a problem

OAuthProvider::removeRequiredParameter
OAuthProvider::setParam
OAuthProvider
PHP Manual

OAuthProvider::reportProblem

(PECL OAuth >= 1.0.0)

OAuthProvider::reportProblem — Report a problem

Opis

final public static string OAuthProvider::reportProblem ( string $oauthexception [, bool $send_headers = true ] )

Pass in a problem as an OAuthException, with possible problems listed in the OAuth constants section.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

oauthexception

The OAuthException.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • OAuthProvider::checkOAuthRequest() - Check an oauth request
  • OAuthProvider::isRequestTokenEndpoint() - Sets isRequestTokenEndpoint
OAuthProvider::removeRequiredParameter
OAuthProvider::setParam
OAuthProvider


Set a parameter

OAuthProvider::reportProblem
OAuthProvider::setRequestTokenPath
OAuthProvider
PHP Manual

OAuthProvider::setParam

(PECL OAuth >= 1.0.0)

OAuthProvider::setParam — Set a parameter

Opis

final public bool OAuthProvider::setParam ( string $param_key [, mixed $param_val ] )

Sets a parameter.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

param_key

The parameter key.

param_val

The optional parameter value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • OAuthProvider::addRequiredParameter() - Add required parameters
OAuthProvider::reportProblem
OAuthProvider::setRequestTokenPath
OAuthProvider


Set request token path

OAuthProvider::setParam
OAuthProvider::timestampNonceHandler
OAuthProvider
PHP Manual

OAuthProvider::setRequestTokenPath

(PECL OAuth >= 1.0.0)

OAuthProvider::setRequestTokenPath — Set request token path

Opis

final public bool OAuthProvider::setRequestTokenPath ( string $path )

Sets the request tokens path.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

path

The path.

Zwracane wartości

TRUE

Zobacz też:

  • OAuthProvider::tokenHandler() - Set the tokenHandler handler callback
OAuthProvider::setParam
OAuthProvider::timestampNonceHandler
OAuthProvider


Set the timestampNonceHandler handler callback

OAuthProvider::setRequestTokenPath
OAuthProvider::tokenHandler
OAuthProvider
PHP Manual

OAuthProvider::timestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback

Opis

public void OAuthProvider::timestampNonceHandler ( callback $callback_function )

Sets the timestamp nonce handler callback, which will later be called with OAuthProvider::callTimestampNonceHandler(). Errors related to timestamp/nonce are thrown to this callback.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

callback_function

The callback functions name.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Example OAuthProvider::timestampNonceHandler() callback

<?php
function timestampNonceChecker($provider) {

    if ($provider->nonce === 'bad') {
        return OAUTH_BAD_NONCE;
    } elseif ($provider->timestamp == '0') {
        return OAUTH_BAD_TIMESTAMP;
    }

    return OAUTH_OK;
}
?>

Zobacz też:

  • OAuthProvider::callTimestampNonceHandler() - Calls the timestampNonceHandler callback
OAuthProvider::setRequestTokenPath
OAuthProvider::tokenHandler
OAuthProvider


Set the tokenHandler handler callback

OAuthProvider::timestampNonceHandler
OAuthException
OAuthProvider
PHP Manual

OAuthProvider::tokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::tokenHandler — Set the tokenHandler handler callback

Opis

public void OAuthProvider::tokenHandler ( callback $callback_function )

Sets the token handler callback, which will later be called with OAuthProvider::callTokenHandler().

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

callback_function

The callback functions name.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Example OAuthProvider::tokenHandler() callback

<?php
function tokenHandler($provider) {

    if ($provider->token === 'rejected') {
        return OAUTH_TOKEN_REJECTED;
    } elseif ($provider->token === 'revoked') {
        return OAUTH_TOKEN_REVOKED;
    }

    $provider->token_secret = "the_tokens_secret";
    return OAUTH_OK;
}
?>

Zobacz też:

  • OAuthProvider::callTokenHandler() - Calls the tokenNonceHandler callback
OAuthProvider::timestampNonceHandler
OAuthException
OAuthProvider


OAuthException class

(No version information available, might only be in SVN)

Wstęp

This exception is thrown when exceptional errors occur while using the OAuth extension and contains useful debugging information.

Krótki opis klasy

OAuthException extends Exception {
/* Właściwości */
public $lastResponse ;
public $debugInfo ;
/* 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

message

A human readable message about what went wrong

code

Exception code

file

File where exception was thrown

line

File where exception was thrown

lastResponse

The response of the exception which occurred, if any

debugInfo

OAuthProvider::tokenHandler
SCA
OAuth


SCA

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • The structure of a Service Component
    • Obtaining a proxy for another Service Component
    • Calling another Service Component
    • Locating and calling services from a script which is not an SCA Component
    • Exposing a Service Component as a Web service
    • Deploying an SCA component
    • Obtaining the WSDL for an SCA component offering a Service as a Web service
    • Understanding how the WSDL is generated
    • Working with Data Structures
    • Error handling
  • SCA Funkcje
    • SCA::createDataObject — create an SDO
    • SCA::getService — Obtain a proxy for a service
    • SCA_LocalProxy::createDataObject — create an SDO
    • SCA_SoapProxy::createDataObject — create an SDO
OAuthException
Wstęp
Usługi sieciowe


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.

SCA for PHP makes it possible for a PHP programmer to write reusable components, which can be called in a variety of ways, with an identical interface and with a minimum of fuss. At present components can call each other either locally or via Web services, but in the future it is expected that other ways will be possible. It provides the programmer with a way of doing this which will look as natural as possible in PHP.

SCA components use phpDocumentor-style (see http://www.phpdoc.org/) annotations to declare dependencies on other SCA components or Web services. The SCA for PHP runtime resolves these dependencies at runtime on behalf of the components, and thus allows the PHP programmer to focus on the business logic rather than on locating and obtaining references to dependencies.

The SCA for PHP programming model can be extended to support a number of service types, such as REST and Atompub. However, Web services (more accurately, WSDL defined, SOAP/HTTP services), are the only type currently specified.

Components also use annotations to define the interface which they expose as a service. The SCA for PHP runtime will automatically generate WSDL from these annotations, so that an SCA component is easily exposed as a web service. These annotations are a natural extension to those provided by phpDocumentor. Deploying a Web service can be as simple as placing a PHP component under the document root of a web server.

Components also use annotations to specify data structures (expressed using XML schema complex types) which are then handled using Service Data Objects (SDOs).

A PHP script which is not an SCA component and which contains no annotations can use the services of an SCA component. A PHP script or component can make calls to a web service that is not an SCA component, but using the same system of calls or annotations to obtain a reference.

First we show a single SCA component, ConvertedStockQuote which illustrates many of the features of SCA for PHP. It has one method, getQuote(), which given a stock "ticker" obtains a price quote for that stock, converted to a given currency. We shall be using this example as a basis for explaining the SCA for PHP throughout the rest of this document.

Przykład #1 A sample SCA component

<?php

include "SCA/SCA.php";

/**
 * Calculate a stock price for a given ticker symbol in a given currency.
 *
 * @service
 * @binding.soap
 */
class ConvertedStockQuote {

    /**
     * The currency exchange rate service to use.
     *
     * @reference
     * @binding.php ../ExchangeRate/ExchangeRate.php
     */
    public $exchange_rate;

    /**
     * The stock quote service to use.
     *
     * @reference
     * @binding.soap ../StockQuote/StockQuote.wsdl
     */
    public $stock_quote;

    /**
     * Get a stock quote for a given ticker symbol in a given currency.
     *
     * @param string $ticker The ticker symbol.
     * @param string $currency What currency to convert the value to.
     * @return float The stock value is the target currency.
     */
    function getQuote($ticker, $currency)
    {
        $quote  = $this->stock_quote->getQuote($ticker);
        $rate   = $this->exchange_rate->getRate($currency);
        return  $rate * $quote;
    }
}
?>

In this example, we see that an SCA component is implemented by a script containing a PHP class and includes SCA.php. The class contains a mixture of business logic and references to other components or services. In the illustrated getQuote() method there is only business logic, but it relies on the instance variables $stock_quote and $exchange_rate having been initialized. These refer to two other components and will be initialized by the SCA runtime with proxies for these two services, whenever this component executes. The annotations for these two services show one to be a local component, which will be called within the same PHP runtime, and one to be a remote component which will be called via a SOAP request. This component also exposes the getQuote() method both locally and as a web service, so it in turn can be called either locally or remotely.

SCA
Instalacja/Konfiguracja
SCA


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SCA


Wymagania

If you want to use SCA to consume or produce Web services then you need PHP 5.2.0 or later, built with the soap extension enabled. If you just want to use local components, and do not wish to use the Web service bindings, then this version of SCA for PHP will also run with PHP 5.1.6.

SCA is packaged along with SDO in one combined package on PECL. See http://www.php.net/sdo#sdo.installation for installing the SCA_SDO package from PECL. The SCA code must be on the include path of your PHP installation, for example if it is installed as /usr/local/lib/php/SCA, the include_path directive must include /usr/local/lib/php

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/sca.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
SCA


Przykłady

Spis treści

  • The structure of a Service Component
  • Obtaining a proxy for another Service Component
  • Calling another Service Component
  • Locating and calling services from a script which is not an SCA Component
  • Exposing a Service Component as a Web service
  • Deploying an SCA component
  • Obtaining the WSDL for an SCA component offering a Service as a Web service
  • Understanding how the WSDL is generated
  • Working with Data Structures
  • Error handling

The examples in the subsequent sections illustrate the following aspects of PHP for SCA:

  • How PHP annotations are used to define PHP classes as SCA components, and how annotations are used to define the services.

  • How an SCA component can be exposed as a Web service

  • How an SCA component can consume a Web service, whether provided by another SCA component or by some other service which knows nothing of SCA

  • How an SCA component can call another SCA component locally (within the same process and on the same call stack)

  • How a client script which is not an SCA component can use the getService call to obtain a proxy for an SCA component.

  • How data structures such as Addresses, or Puchase Orders, are represented as Service Data Objects, and handled.

  • How SCA components are deployed, and in particular how and when WSDL is generated for a service.

  • How parameters are always passed by value (and not by reference) between components, even when the calls are local. This ensures that the semantics of a call do not change depending on the location of a component.

  • How positional parameters to a service are supported, even when the underlying WSDL is document literal wrapped, and naturally supports only named parameters.

  • How business and runtime exceptions are handled.

Stałe predefiniowane
The structure of a Service Component
SCA


The structure of a Service Component

A service component is implemented by a class. To identify it as a service component, it contains an @service annotation. The SCA runtime will use the file name of the script to determine the component name, by convention. The class and script file must therefore share the same name.

PHP SCA components always expose a service, and there is no way for a component to be invoked other than to be called as a result of a Web service request, or called directly from another component or from a script. For this reason a valid PHP SCA component will always contain an @service annotation and at least one public method.

Each SCA Component requires that the SCA.php script is included. As well as containing the definition of the SCA class, this script contains executable PHP code that will run whenever the script is called, and which will be responsible for making the component behave as needed.

Uwaga

It is very important that if your file contains other includes, they come before the include for SCA.php. If there are includes after the include for SCA.php, they will not have been processed when the SCA runtime runs your class.

The example below illustrates this overall structure

Przykład #1 The structure of an SCA for PHP component

<?php

// any includes

include "SCA/SCA.php";

/**
 * @service
 */

class ConvertedStockQuote {

       // instance variables, business logic, including at least one public method

}
?>

Przykłady
Obtaining a proxy for another Service Component
Przykłady


Obtaining a proxy for another Service Component

One SCA component can call the service provided by another SCA component. The service a component provides is made up of all of its public methods. SCA for PHP currently provides two ways for one component to call another: either locally (i.e. within the same PHP run-time, and on the same call stack) or remotely if the called component exposes a Web service binding.

In order for one component to call another, the calling component needs a proxy for the called component. This proxy is usually provided as an instance variable in the calling component, though proxies can also be obtained with the SCA::getService() call, as we shall see later. When a component is constructed, proxies are constructed for any instance variable which refer to another component, and these proxies are "injected" into the instance variables. Proxies are always used, whether the component is local or remote, in order to provide identical calling behavior between remote and local calls (for example, local calls are made to always pass data by-value). The proxies know how to locate the required component and to pass the calls made on to them.

Instance variables which are intended to hold proxies for services are indicated by the two PHPDocumentor-style annotations, @reference and @binding. Both annotations are placed in the documentation section for a class instance variable, as shown by the code below.

The @reference annotation before an instance variable indicates that the instance variable is to be initialized with a proxy to a component.

The @binding annotation has two forms @binding.php and @binding.soap, and indicates that the proxy is either for a local component or for a Web service respectively. For both @binding.php and @binding.soap, the annotation gives a target URI.

At the moment, with the annotation-based method of specifying dependencies, the only way to alter the intended target of a reference is to alter the annotation within the component.

In our ConvertedStockQuote example, the $exchange_rate instance variable will be initialized with a proxy to the local ExchangeRate component whenever an instance of the ConvertedStockQuote is constructed.

Przykład #1 Obtaining a proxy for a local PHP class

<?php
   /**
     * The currency exchange rate service to use.
     *
     * @reference
     * @binding.php ../ExchangeRate/ExchangeRate.php
     */
    public $exchange_rate;
?>

For @binding.php, the URI identifies the location of the script containing the implementation of the component. The component will be called locally. The service provided is the set of public methods of the component. The URI must be a simple pathname, either absolute or relative. The component will be loaded with the PHP include directive, after testing to see if it is already loaded with class_exists(). If the URI is a relative path, it is resolved relative to the component containing the annotation. Note that this is different from the normal PHP behaviour where scripts would be looked for along the PHP include_path, This is intended to provide some location-independence for cross-component references.

If this ExchangeRate service were remote and to be called as a Web service, only the @binding line changes. Instead of giving the location of a PHP class, it gives the location of the WSDL describing the web service. In our example component, this is illustrated by the second reference:

Przykład #2 Obtaining a proxy for a web service

<?php
/**
     * The stock quote service to use.
     *
     * @reference
     * @binding.soap ../StockQuote/StockQuote.wsdl
     */
    public $stock_quote;
?>

The StockQuote component will be called via a Web service request. In this case the URI for the WSDL can be a simple pathname, or may contain a PHP wrapper and begin, for example, with file:// or http://. In the event that it is a simple pathname, it can be absolute or relative, and if relative will be resolved relative to the component containing the annotation. Note that this is like the behaviour for @binding.php, and different from the normal PHP behaviour where the file would be looked for relative to the PHP current working directory, which would usually be the location of the first script to be called. This behaviour is intended to give consistency across the different bindings and to provide some location-independence for references between components.

The structure of a Service Component
Calling another Service Component
Przykłady


Calling another Service Component

The ConvertedStockQuote example also calls the proxies for the two components to which it refers.

Przykład #1 Calling services

<?php
$quote  = $this->stock_quote->getQuote($ticker);
$rate   = $this->exchange_rate->getRate($currency);
?>

The call to the StockQuote service is a call to a local service; the call to the ExchangeRate service is a call to a remote service. Note that the way the call is made looks the same regardless of whether the call is to a local service or a remote one.

The proxies which have been injected ensure that the way calls to components look and behave are the same way regardless of whether they are to a local or remote service, so that components are not sensitive to whether a call is to a local or a remote service. For example, the proxy for a local service takes copies of the arguments and passes only those copies, to ensure that calls are made to be pass-by-value, as they would be for a remote call. Also, the proxy for a remote service takes the arguments from a positional parameter list and ensures they are packaged properly in a SOAP request and converted back to a positional parameter list at the far end.

In the example above, the $ticker and $currency are clearly PHP scalar types. Components can pass the PHP scalar types string, integer, float and boolean, but data structures on service calls are always passed as Service Data Objects (SDOs). A later section describes how a component can create an SDO to pass on a local or Web service call, or how a component can create an SDO to return. The PHP SDO project documentation describes how to work with the SDO APIs (see the SDO pages).

Obtaining a proxy for another Service Component
Locating and calling services from a script which is not an SCA Component
Przykłady


Locating and calling services from a script which is not an SCA Component

SCA components obtain proxies for other components or services as instance variables annotated with @reference, but this is not possible for a script that is not itself also a component. A client script which is not a component must use the SCA::getService() static method to obtain a proxy for a service, whether local or remote. The getService() method takes a URI as the argument. Typically this is the location of a local PHP script containing a component, or of a wsdl file, and is used in exactly the same way as the targets of the @binding annotations described in the previous section: that is, relative URIs are resolved against the location of the client script and not against the PHP include_path or current working directory.

For example, a script that needed to obtain proxies for the ExchangeRate and StockQuote services but was not a component would use the getService() method as follows:

Przykład #1 Obtaining a proxy using getService

<?php
$exchange_rate = SCA::getService('../ExchangeRate/ExchangeRate.php');
$stock_quote   = SCA::getService('../StockQuote/StockQuote.wsdl');
?>

Methods on services can then be called on the returned proxy, just as they can in a component.

Przykład #2 Making calls on the proxy

<?php
$quote  = $stock_quote->getQuote($ticker);
$rate   = $exchange_rate->getRate($currency);
?>

Calling another Service Component
Exposing a Service Component as a Web service
Przykłady


Exposing a Service Component as a Web service

SCA for PHP can generate WSDL from the annotations within a service component, so that it can be easily deployed and exposed as a Web service. To provide SCA with the information it needs to generate the WSDL, it is necessary to add the annotation @binding.soap under the @service annotation and to specify the parameters and return values of the methods using the @param and @return annotations. These annotations will be read when WSDL is generated, and the order and types of the parameters determine the contents of the <schema> section of the WSDL.

SCA for PHP always generates document/literal wrapped WSDL for components that are exposing a Web service. Note that this does not stop components from consuming Web services which are not SCA components and which are documented with WSDL written in a different style.

The scalar types which can be used in the @param annotation are the four common PHP scalar types: boolean, integer, float and string. These are simply mapped to the XML schema types of the same name in the WSDL. The example below, which is a trivial implementation of the StockQuote service that the ConvertedStockQuote component calls, illustrates string and float types.

Przykład #1 StockQuote Service

<?php

include "SCA/SCA.php";

/**
 * Scaffold implementation for a remote StockQuote Web service.
 *
 * @service
 * @binding.soap
 *
 */
class StockQuote {

    /**
     * Get a stock quote for a given ticker symbol.
     *
     * @param string $ticker The ticker symbol.
     * @return float The stock quote.
     */
    function getQuote($ticker) {
        return 80.9;
  }
}
?>

WSDL much like the following (though with a service location other than 'localhost', probably) would be generated from this service:

Przykład #2 Generated WSDL

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xsi:type="tDefinitions"
    xmlns:tns2="http://StockQuote" xmlns:tns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:tns3="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" targetNamespace="http://StockQuote">
  <types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://StockQuote">
      <xs:element name="getQuote">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ticker" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="getQuoteResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="getQuoteReturn" type="xs:float"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
  </types>

  <message name="getQuoteRequest">
    <part name="getQuoteRequest" element="tns2:getQuote"/>
  </message>
  <message name="getQuoteResponse">
    <part name="return" element="tns2:getQuoteResponse"/>
  </message>
  <portType name="StockQuotePortType">
    <operation name="getQuote">
      <input message="tns2:getQuoteRequest"/>
      <output message="tns2:getQuoteResponse"/>
    </operation>
  </portType>
  <binding name="StockQuoteBinding" type="tns2:StockQuotePortType">
    <operation name="getQuote">
      <input>
        <tns3:body xsi:type="tBody" use="literal"/>
      </input>
      <output>
        <tns3:body xsi:type="tBody" use="literal"/>
      </output>
      <tns3:operation xsi:type="tOperation" soapAction=""/>
    </operation>
    <tns3:binding xsi:type="tBinding" transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
  </binding>
  <service name="StockQuoteService">
    <port name="StockQuotePort" binding="tns2:StockQuoteBinding">
      <tns3:address xsi:type="tAddress" location="http://localhost/StockQuote/StockQuote.php"/>
    </port>
  </service>
</definitions>

<!-- this line identifies this file as WSDL generated by SCA for PHP. Do not remove -->

Locating and calling services from a script which is not an SCA Component
Deploying an SCA component
Przykłady


Deploying an SCA component

There are no special steps needed to deploy a PHP SCA component. It is sufficient to place the component PHP script in its proper place under the web server document root, just like any other PHP script. It is the SCA::initComponent() executable line within each component that will be executed whenever the script is called, and which will be responsible for making the component respond appropriately to Web service calls, local calls, or requests for WSDL.

Exposing a Service Component as a Web service
Obtaining the WSDL for an SCA component offering a Service as a Web service
Przykłady


Obtaining the WSDL for an SCA component offering a Service as a Web service

SCA components that expose a Web service interface (i.e. have an @binding.soap annotation) will return their WSDL definition in response to an HTTP request with a get parameter of "wsdl". The usual way to obtain this is with "?wsdl" on the end of a URL. The example below uses file_get_contents() to obtain WSDL from a service and writes it to a temporary file before then obtaining a proxy for the service in the usual way. You could of course also obtain the WSDL in a browser, or by some other means, and save the file yourself.

Przykład #1 Generated WSDL

<?php
$wsdl = file_get_contents('http://www.example.com/Services/Example.php?wsdl');
file_put_contents("service.wsdl",$wsdl); //write the wsdl to a file
$service = SCA::getService('service.wsdl');
?>

NOTE: If the wsdl requires imported xsds, these will need to be fetched separately.

Deploying an SCA component
Understanding how the WSDL is generated
Przykłady


Understanding how the WSDL is generated

SCA for PHP generates WSDL for components which contain an @binding.soap annotation after the @service annotation. To generate WSDL, the SCA runtime reflects on the component and examines the @param and @return annotations for each public method, as well as any @types annotations within the component. The information from the @param and @return annotations is used to build the <types> section of the WSDL. Any @types annotations which specify a separate schema file will result in an <import> element for that schema within the WSDL.

Location attribute of the <service> element

At the bottom of the WSDL is the <service> element which uses the location attribute to identify the URL of the service. For example this might look as follows:

Przykład #1 location attribute

<service name="ConvertedStockQuote"
...
location="http://localhost/ConvertedStockQuote/ConvertedStockQuote.php"/>

Note that this location is relative to the document root of the web server, and cannot be worked out in advance. It can only be worked out once the component is in its proper place under a running web server, when the hostname and port can be known and placed in the WSDL. Detail from the URL that requests the WSDL is used, so for example if the WSDL is generated in response to a request to http://www.example.com:1111/ConvertedStockQuote/ConvertedStockQuote.php?wsdl, a location of http://www.example.com:1111/ConvertedStockQuote/ConvertedStockQuote.php is what will be inserted into the location attribute in the WSDL.

Document/literal wrapped WSDL and positional parameters

SCA for PHP generates WSDL in the document/literal wrapped style. This style encloses the parameters and return types of a method in 'wrappers' which are named after the corresponding method. The <types> element at the top of the WSDL defines each of these wrappers. If we consider the getQuote() method of the ConvertedStockQuote example:

Przykład #2 method with two arguments

<?php
   /**
     * Get a stock quote for a given ticker symbol in a given currency.
     *
     * @param string $ticker The ticker symbol.
     * @param string $currency What currency to convert the value to.
     * @return float The stock value is the target currency.
     */
    function getQuote($ticker, $currency)
    {
        $quote  = $this->stock_quote->getQuote($ticker);
        $rate   = $this->exchange_rate->getRate($currency);
        return  $rate * $quote;
    }
?>

The WSDL generated to define this method will name both the method and the parameters, and give an XML schema type for the parameters. The types section of the WSDL looks like this:

Przykład #3 types section illustrating named parameters

<types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://ConvertedStockQuote">
      <xs:element name="getQuote">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ticker" type="xs:string"/>
            <xs:element name="currency" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="getQuoteResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="getQuoteReturn" type="xs:float"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
  </types>

The SCA run-time has special processing to handle how positional parameter lists in the interface are converted to XML containing named parameters in the soap request, and then back to positional parameter lists again. To see why this matters, consider how a PHP script which used a different interface to make a SOAP call would need to construct the parameter list. A PHP script using the PHP SoapClient, for example, would need to pass the SoapClient a single parameter giving the values for "ticker" and "currency", perhaps as an associative array. To insist that SCA components construct parameter lists to make Web service calls in this way would be to make local and remote calls look different, so a different approach is needed.

When SCA generates WSDL for an SCA component it includes a comment in the WSDL which marks that WSDL as being the interface for an SCA component. In this case, when one SCA component calls another through a Web service, the SCA runtime on the calling end takes the positional parameter list from the call and assigns the values one by one to the named elements in the soap message. For example a call to the getQuote() method defined above that passes the values 'IBM' and 'USD' and looks like this:

<?php
  $quote = $remote_service->getQuote('IBM','USD');
?>

will result in a soap message containing the following:

<getQuote>
  <ticker>IBM</ticker>
  <currency>USD</currency>
</getQuote>

On the service-providing end, the SCA run-time takes the parameters one by one from the soap message and forms a positional parameter list from them, re-forming the argument list ('IBM','USD').

Uwaga

At both ends the SCA runtime relies on the order in which the parameters appear in the soap message being the same as that in the target method's parameter list. This is ultimately determined by the order of the @param annotations: this determines the order in which the parameters appear in the WSDL and thereby the order in which they appear in the soap message. Therefore it is essential that the order of the @param annotations matches that of the parameters in the method's parameter list.

Obtaining the WSDL for an SCA component offering a Service as a Web service
Working with Data Structures
Przykłady


Working with Data Structures

SCA components can pass and return the four PHP scalar types boolean, integer, float and string, but to pass or return data structures, SCA components use Service Data Objects (SDOs). SDOs are described in much more detail in the SDO pages of this manual. Readers familiar with SDOs will know that they are suitable for representing the sort of structured and semi-structured data that is frequently modeled in XML, and that they serialize very naturally for passing between remote components, or in Web services. SDOs are presently the only supported way to pass and return data structures. It is not possible to pass or return PHP objects, or PHP arrays.

The SCA runtime always assures data is passed by-value, even for local calls. To do this, the SCA runtime copies any SDOs in the parameter list before passing them on, just as it does for scalar types.

How data structures are defined to SCA components

Currently the only mechanism for specifying the location of a data structure definition is by specifying the types in an XML schema file. However, in the future it may be possible to define types in other ways, such as based on PHP classes or interfaces, or based on definitions expressed as associative arrays.

To illustrate the use of SDOs we introduce a new component. The PortfolioMangement service below returns an SDO representing a stock portfolio for a given customer.

Przykład #1 A Component that uses Data Structures

<?php

include "SCA/SCA.php";

/**
 * Manage the portfolio for a customer.
 *
 * @service
 * @binding.soap
 *
 * @types http://www.example.org/Portfolio PortfolioTypes.xsd
 *
 */
class PortfolioManagement {

    /**
     * Get the stock portfolio for a given customer.
     *
     * @param integer $customer_id The id for the customer
     * @return Portfolio http://www.example.org/Portfolio The stock portfolio (symbols and quantities)
     */
    function getPortfolio($customer_id) {
        // Pretend we just got this from a database
        $portfolio = SCA::createDataObject('http://www.example.org/Portfolio', 'Portfolio');
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'AAPL';
        $holding->number = 100.5;
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'INTL';
        $holding->number = 100.5;
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'IBM';
        $holding->number = 100.5;
        return $portfolio;
    }

}
?>

The @types annotation:

<?php
@types http://www.example.org/Portfolio PortfolioTypes.xsd
?>

indicates that types in the namespace http://www.example.org/Portfolio will be found in the schema file located by the URI PortfolioTypes.xsd. The generated WSDL would reproduce this information with an import statement as follows:

<xs:import schemaLocation="PortfolioTypes.xsd"
                      namespace="http://www.example.org/Portfolio"/>

so the URI, absolute or relative, must be one that can be resolved when included in the schemaLocation attribute.

Creating SDOs

Readers familiar with SDOs will know that they are always created according to a description of the permitted structure (sometimes referred to as the 'schema' or 'model') and that, rather than creating them directly using 'new', some form of data factory is needed. Often, an existing data object can be used as the data factory, but sometimes, and especially in order to get the first data object, something else must act as the data factory.

In SCA, either the SCA runtime class or the proxies for services, whether local or remote, can act as the data factories for SDOs. The choice of which to use, and when, is described in the next two sections.

We switch to a new example in order to illustrate the creation of SDOs, both to pass to a service, and to be returned from a service.

Creating an SDO to pass to a service

A caller of a service which requires a data structure to be passed in to it uses the proxy to the service as the data factory for the corresponding SDOs. For example, suppose a component makes use of a proxy for a service provided by a local AddressBook component.

<?php
/**
 * @reference
 * @binding.local AddressBook.php
 */
$address_book;
?>

The AddressBook component that it wishes to call is defined as follows:

<?php
/**
* @service
* @binding.soap
* @types http://addressbook ../AddressBook/AddressBook.xsd
*/
class AddressBook {

    /**
     * @param personType $person http://addressbook (a person object)
     * @return addressType http://addressbook (the address object for the person object)
     */
    function lookupAddress($person)  {
        ...
    }
}
?>

The AddressBook component provides a service method called lookupAddress() which uses types from the http://addressbook namespace. The lookupAddress method takes a personType data structure and returns an addressType. Both types are defined in the schema file addressbook.xsd.

Once the component that wishes to use the AddressBook component has been constructed, so that the $address_book instance variable contains a proxy for the service, the calling component can use the proxy in $address_book to create the person SDO, as shown below:

<?php
$william_shakespeare        = $address_book->createDataObject('http://addressbook','personType');
$william_shakespeare ->name = "William Shakespeare";
$address                    = $address_book->lookupAddress($william_shakespeare);
?>

Note, the use of the proxy as the means to create the SDO is not limited to SCA components. If a service is being called from a general PHP script, and the proxy was obtained with getService() then the same approach is used.

<?php
$address_book = SCA::getService('AddressBook.php');
$william_shakespeare = $address_book->createDataObject('http://addressbook','personType');
?>

Creating an SDO to return from a component

A component that needs to create a data object for return to a caller will not have a proxy to use as a data object, In this case it uses the createDataObject() static method on SCA.php. Hence if the AddressBook component described above needed to create an object of type addressType within the namespace http://addressbook, it might do so as follows:

<?php
$address = SCA::createDataObject('http://addressbook','addressType');
?>

Understanding how the WSDL is generated
Error handling
Przykłady


Error handling

This section describes how errors are handled. There are two types of errors:

  • SCA runtime exceptions are those that signal problems in the management of the execution of components, and in the interaction with remote services. These might occur due to network or configuration problems.

  • Business exceptions are those that are defined by the programmer. They extend the PHP Exception class, and are thrown and caught deliberately as part of the business logic.

Handling of Runtime exceptions

There are two types of SCA runtime exception:

  • SCA_RuntimeException - signals a problem found by or perhaps occurring within the SCA runtime. This can be thrown for a variety of reasons, many of which can occur regardless of whether a connection is being made to a local or a remote service: an error in one of the annotations within a component, a missing WSDL or php file, and so on. In the case of Web services, an SCA_RuntimeException can also be thrown if a SoapFault is received from a remote Web service and the fault code in the SoapFault indicates that a retry is unlikely to be successful.

  • SCA_ServiceUnavailableException - this is a subclass of SCA_RuntimeException and signals a problem in connecting to or using a remote service, but one which might succeed if retried. In the case of Web services, this exception is thrown if a SoapFault is received with a fault code that indicates that a retry might be successful.

Handling of Business exceptions

Business exceptions may be defined and thrown by a component in the normal way, regardless of whether the component has been called locally or remotely. The SCA runtime does not catch business exceptions that have been thrown by a component called locally, so they will be returned to a caller in the normal way. If a component has been called via a Web service, on the other hand, the SCA runtime on the service providing end does catch business exceptions, and will ensure these are passed back to the calling end and re-thrown. Assuming that the calling end has a definition of the exception (that is, is able to include a file containing the PHP class defining the exception) the re-thrown exception will contain the same details as the original, so that the getLine() and getFile() methods for example will contain the location where the exception was thrown within the business logic. The exception will be passed in the detail field of a soap fault with a fault code of "Client".

Working with Data Structures
SCA Funkcje
Przykłady


Error handling
SCA::createDataObject
SCA
PHP Manual

SCA Funkcje

Klasy predefiniowane

Most of the interface to SCA is through the annotations within SCA components so there are few public classes and methods. The only SCA classes that scripts or components can call are the SCA class itself, and the proxy classes SCA_LocalProxy and SCA_SoapProxy.

SCA

Much of the work of the SCA class is performed when the file SCA.php is included within an SCA component. However, a PHP script may include SCA.php and call the getService() method on the SCA class in order to obtain a proxy for a service. A component will not need to do this as proxies are obtained instead by defining an instance variable with the @reference annotation.

Components that need to create an SDO to return to a caller will need a data factory to call. For this purpose the SCA class supports the createDataObject() method, which will create an SDO according to the model defined by the component's @types annotations. The arguments to createDataObject() are the same as those to SDO's XML Data Access Service.

Metody

  • getService - obtain a proxy for a service

  • createDataObject - create an SDO

SCA_LocalProxy

When getService() is called with the target of a local PHP component, a local proxy is returned. A local proxy is also injected into the instance variables of a component that are defined with an @reference and an @binding.php anotation. When the script or component makes calls on the local proxy, they are passed on to the target component itself.

Components that need to create an SDO to pass to a component will need a data factory to call. For this purpose the SCA_LocalProxy class supports the createDataObject() method, which will create an SDO according to the model defined by the components' @types annotations. The arguments to the createDataObject() are the same as those to SDO's XML Data Access Service.

Metody

  • createDataObject - create an SDO

SCA_SoapProxy

When getService() is called with the target of a WSDL file, a SOAP proxy is returned. A SOAP proxy is also injected into the instance variables of a component that are defined with an @reference and an @binding.soap anotations. When the script or component makes calls on the SOAP proxy, they are formed into Web service SOAP requests and passed on to the target component, with the help of the PHP Soap extension.

Components that need to create an SDO to pass to a component will need a data factory to call. For this purpose the SCA_SoapProxy class supports the createDataObject() method, which will create an SDO according to the model defined within the target WSDL. The arguments to the createDataObject() are the same as those to SDO's XML Data Access Service.

Metody

  • createDataObject - create an SDO

Spis treści

  • SCA::createDataObject — create an SDO
  • SCA::getService — Obtain a proxy for a service
  • SCA_LocalProxy::createDataObject — create an SDO
  • SCA_SoapProxy::createDataObject — create an SDO
Error handling
SCA::createDataObject
SCA
PHP Manual


create an SDO

SCA Funkcje
SCA::getService
SCA Funkcje
PHP Manual

SCA::createDataObject

(PECL SDO >= 0.5.0)

SCA::createDataObject — create an SDO

Opis

SDO_DataObject SCA::createDataObject ( string $type_namespace_uri , string $type_name )
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.

This method is used inside an SCA component that needs to create an SDO to return. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in one of the schema files which are specified on the @types annotation within the component.

Parametry

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Zwracane wartości

Returns the newly created SDO_DataObject.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type in any of the schema files specified in the @types annotations.

SCA Funkcje
SCA::getService
SCA Funkcje


Obtain a proxy for a service

SCA::createDataObject
SCA_LocalProxy::createDataObject
SCA Funkcje
PHP Manual

SCA::getService

(PECL SDO >= 0.5.0)

SCA::getService — Obtain a proxy for a service

Opis

mixed SCA::getService ( string $target [, string $binding [, array $config ]] )
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.

Examine the target and initialize and return a proxy of the appropriate sort. If the target is for a local PHP component the returned proxy will be an SCA_LocalProxy. If the target is for a WSDL file, the returned proxy will be a SCA_SoapProxy.

Parametry

target

An absolute or relative path to the target service or service description (e.g. a URL to a json-rpc service description, a PHP component, a WSDL file, and so on.). A relative path, if specified, is resolved relative to the location of the script issuing the getService() call, and not against the include_path or current working directory.

binding

The binding (i.e. protocol) to use to communicate with the service (e.g binding.jsonrpc for a json-rpc service). Note, some service types can be deduced from the target parameter (e.g. if the target parameter ends in .wsdl then SCA will assume binding.soap). Any binding which can be specified in an annotation can be specified here. For example 'binding.soap' is equivalent to the '@binding.soap' annotation.

config

Any additional configuration properties for the binding (e.g. array('location' => 'http://example.org')). Any binding configuration which can be specified in an annotation can be specified here. For example, 'location' is equivalent to the '@location' annotation to configure the location of a target soap service.

Zwracane wartości

The SCA_LocalProxy or SCA_SoapProxy.

Przykłady

Przykład #1 An SCA::getService() example

This example shows how to get a proxy to an email soap service described by EmailService.wsdl and located at http://example.org.

<?php
include 'SCA/SCA.php';
$service = SCA::getService('EmailService.wsdl', 'binding.soap', array('location' => 'http://example.org'));
$service->send(...);
?>

Powyższy przykład wyświetli:

SCA::createDataObject
SCA_LocalProxy::createDataObject
SCA Funkcje


create an SDO

SCA::getService
SCA_SoapProxy::createDataObject
SCA Funkcje
PHP Manual

SCA_LocalProxy::createDataObject

(PECL SDO >= 0.5.0)

SCA_LocalProxy::createDataObject — create an SDO

Opis

SDO_DataObject SCA_LocalProxy::createDataObject ( string $type_namespace_uri , string $type_name )
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.

This method is used inside either an ordinary PHP script or an SCA component that needs to create an SDO to pass to a local service. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in the interface of the component that is to be called, so the namespace and type must be defined in one of the schema files which are specified on the @types annotation within the component for which the SCA_LocalProxy object is a proxy.

Parametry

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Zwracane wartości

Returns the newly created SDO_DataObject.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type in any of the schema files specified in the @types annotations within the component for which the SCA_LocalProxy object is a proxy..

SCA::getService
SCA_SoapProxy::createDataObject
SCA Funkcje


create an SDO

SCA_LocalProxy::createDataObject
SOAP
SCA Funkcje
PHP Manual

SCA_SoapProxy::createDataObject

(PECL SDO >= 0.5.0)

SCA_SoapProxy::createDataObject — create an SDO

Opis

SDO_DataObject SCA_SoapProxy::createDataObject ( string $type_namespace_uri , string $type_name )
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.

This method is used inside either an ordinary PHP script or an SCA component that needs to create an SDO to pass to a web service. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in the interface of the component that is to be called, so the namespace and type must be defined within the WSDL for the web service. If the web service is also an SCA component then the types will have been defined within one of the schema files which are specified on the @types annotation within the component for which the SCA_SoapProxy object is a proxy.

Parametry

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Zwracane wartości

Returns the newly created SDO_DataObject.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type found in the WSDL that was used to initialise this SCA_SoapProxy.

SCA_LocalProxy::createDataObject
SOAP
SCA Funkcje


SOAP

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • SOAP Funkcje
    • is_soap_fault — Checks if a SOAP call has failed
    • use_soap_error_handler — Set whether to use the SOAP error handler
  • SoapClient — The SoapClient class
    • SoapClient::__call — Calls a SOAP function (deprecated)
    • SoapClient::__construct — SoapClient constructor
    • SoapClient::__doRequest — Performs a SOAP request
    • SoapClient::__getFunctions — Returns list of available SOAP functions
    • SoapClient::__getLastRequest — Returns last SOAP request
    • SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse — Returns last SOAP response
    • SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response
    • SoapClient::__getTypes — Returns a list of SOAP types
    • SoapClient::__setCookie — The __setCookie purpose
    • SoapClient::__setLocation — Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall — Calls a SOAP function
    • SoapClient::SoapClient — SoapClient constructor
  • SoapServer — The SoapServer class
    • SoapServer::addFunction — Adds one or more functions to handle SOAP requests
    • SoapServer::addSoapHeader — Add a SOAP header to the response
    • SoapServer::__construct — SoapServer constructor
    • SoapServer::fault — Issue SoapServer fault indicating an error
    • SoapServer::getFunctions — Returns list of defined functions
    • SoapServer::handle — Handles a SOAP request
    • SoapServer::setClass — Sets the class which handles SOAP requests
    • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence — Sets SoapServer persistence mode
    • SoapServer::SoapServer — SoapServer constructor
  • SoapFault — The SoapFault class
    • SoapFault::__construct — SoapFault constructor
    • SoapFault::SoapFault — SoapFault constructor
    • SoapFault::__toString — Obtain a string representation of a SoapFault
  • SoapHeader — The SoapHeader class
    • SoapHeader::__construct — SoapHeader constructor
    • SoapHeader::SoapHeader — SoapHeader constructor
  • SoapParam — The SoapParam class
    • SoapParam::__construct — SoapParam constructor
    • SoapParam::SoapParam — SoapParam constructor
  • SoapVar — The SoapVar class
    • SoapVar::__construct — SoapVar constructor
    • SoapVar::SoapVar — SoapVar constructor
SCA_SoapProxy::createDataObject
Wstęp
Usługi sieciowe


Wstęp

The SOAP extension can be used to write SOAP Servers and Clients. It supports subsets of » SOAP 1.1, » SOAP 1.2 and » WSDL 1.1 specifications.

SOAP
Instalacja/Konfiguracja
SOAP


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SOAP


Wymagania

To rozszerzenie wymaga rozszerzenia PHP libxml. To oznacza, że należy podać dyrektywę konfiguracyjną --enable-libxml podczas kompilacji, pomimo tego, że pośrednio jest to spełnione, ponieważ libxml jest domyślnie włączone.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To enable SOAP support, configure PHP with --enable-soap .

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

SOAP Opcje konfiguracyjne
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

soap.wsdl_cache_enabled integer

Enables or disables the WSDL caching feature.

soap.wsdl_cache_dir string

Sets the directory name where the SOAP extension will put cache files.

soap.wsdl_cache_ttl integer

Sets the number of seconds (time to live) that cached files will be used instead of the originals.

soap.wsdl_cache integer

If soap.wsdl_cache_enabled is on, this setting determines the type of caching. It can be any of: WSDL_CACHE_NONE (0), WSDL_CACHE_DISK (1), WSDL_CACHE_MEMORY (2) or WSDL_CACHE_BOTH (3). This can also be set via the options array in the SoapClient or SoapServer constructor.

soap.wsdl_cache_limit integer

Maximum number of in-memory cached WSDL files. Adding further files into a full memory cache will delete the oldest files from it.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

SOAP constants
Constant | Value | Description
SOAP_1_1 (integer) | 1 |
SOAP_1_2 (integer) | 2 |
SOAP_PERSISTENCE_SESSION (integer) | 1 |
SOAP_PERSISTENCE_REQUEST (integer) | 2 |
SOAP_FUNCTIONS_ALL (integer) | 999 |
SOAP_ENCODED (integer) | 1 |
SOAP_LITERAL (integer) | 2 |
SOAP_RPC (integer) | 1 |
SOAP_DOCUMENT (integer) | 2 |
SOAP_ACTOR_NEXT (integer) | 1 |
SOAP_ACTOR_NONE (integer) | 2 |
SOAP_ACTOR_UNLIMATERECEIVER (integer) | 3 |
SOAP_COMPRESSION_ACCEPT (integer) | 32 |
SOAP_COMPRESSION_GZIP (integer) | 0 |
SOAP_COMPRESSION_DEFLATE (integer) | 16 |
SOAP_AUTHENTICATION_BASIC (integer) | 0 |
SOAP_AUTHENTICATION_DIGEST (integer) | 1 |
UNKNOWN_TYPE (integer) | 999998 |
XSD_STRING (integer) | 101 |
XSD_BOOLEAN (integer) | 102 |
XSD_DECIMAL (integer) | 103 |
XSD_FLOAT (integer) | 104 |
XSD_DOUBLE (integer) | 105 |
XSD_DURATION (integer) | 106 |
XSD_DATETIME (integer) | 107 |
XSD_TIME (integer) | 108 |
XSD_DATE (integer) | 109 |
XSD_GYEARMONTH (integer) | 110 |
XSD_GYEAR (integer) | 111 |
XSD_GMONTHDAY (integer) | 112 |
XSD_GDAY (integer) | 113 |
XSD_GMONTH (integer) | 114 |
XSD_HEXBINARY (integer) | 115 |
XSD_BASE64BINARY (integer) | 116 |
XSD_ANYURI (integer) | 117 |
XSD_QNAME (integer) | 118 |
XSD_NOTATION (integer) | 119 |
XSD_NORMALIZEDSTRING (integer) | 120 |
XSD_TOKEN (integer) | 121 |
XSD_LANGUAGE (integer) | 122 |
XSD_NMTOKEN (integer) | 123 |
XSD_NAME (integer) | 124 |
XSD_NCNAME (integer) | 125 |
XSD_ID (integer) | 126 |
XSD_IDREF (integer) | 127 |
XSD_IDREFS (integer) | 128 |
XSD_ENTITY (integer) | 129 |
XSD_ENTITIES (integer) | 130 |
XSD_INTEGER (integer) | 131 |
XSD_NONPOSITIVEINTEGER (integer) | 132 |
XSD_NEGATIVEINTEGER (integer) | 133 |
XSD_LONG (integer) | 134 |
XSD_INT (integer) | 135 |
XSD_SHORT (integer) | 136 |
XSD_BYTE (integer) | 137 |
XSD_NONNEGATIVEINTEGER (integer) | 138 |
XSD_UNSIGNEDLONG (integer) | 139 |
XSD_UNSIGNEDINT (integer) | 140 |
XSD_UNSIGNEDSHORT (integer) | 141 |
XSD_UNSIGNEDBYTE (integer) | 142 |
XSD_POSITIVEINTEGER (integer) | 143 |
XSD_NMTOKENS (integer) | 144 |
XSD_ANYTYPE (integer) | 145 |
XSD_ANYXML (integer) | 147 |
APACHE_MAP (integer) | 200 |
SOAP_ENC_OBJECT (integer) | 301 |
SOAP_ENC_ARRAY (integer) | 300 |
XSD_1999_TIMEINSTANT (integer) | 401 |
XSD_NAMESPACE (integer) | http://www.w3.org/2001/XMLSchema |
XSD_1999_NAMESPACE (integer) | http://www.w3.org/1999/XMLSchema |
SOAP_SINGLE_ELEMENT_ARRAYS (integer) | 1 |
SOAP_WAIT_ONE_WAY_CALLS (integer) | 2 |
SOAP_USE_XSI_ARRAY_TYPE (integer) | 4 |
WSDL_CACHE_NONE (integer) | 0 |
WSDL_CACHE_DISK (integer) | 1 |
WSDL_CACHE_MEMORY (integer) | 2 |
WSDL_CACHE_BOTH (integer) | 3 |
Typy zasobów
SOAP Funkcje
SOAP


SOAP Funkcje

Spis treści

  • is_soap_fault — Checks if a SOAP call has failed
  • use_soap_error_handler — Set whether to use the SOAP error handler
Stałe predefiniowane
is_soap_fault
SOAP


Checks if a SOAP call has failed

SOAP Funkcje
use_soap_error_handler
SOAP Funkcje
PHP Manual

is_soap_fault

(Unknown)

is_soap_fault — Checks if a SOAP call has failed

Opis

bool is_soap_fault ( mixed $object )

This function is useful to check if the SOAP call failed, but without using exceptions. To use it, create a SoapClient object with the exceptions option set to zero or FALSE. In this case, the SOAP method will return a special SoapFault object which encapsulates the fault details (faultcode, faultstring, faultactor and faultdetails).

If exceptions is not set then SOAP call will throw an exception on error. is_soap_fault() checks if the given parameter is a SoapFault object.

Parametry

object

The object to test.

Zwracane wartości

This will return TRUE on error, and FALSE otherwise.

Przykłady

Przykład #1 is_soap_fault() example

<?php
$client = new SoapClient("some.wsdl", array('exceptions' => 0));
$result = $client->SomeFunction();
if (is_soap_fault($result)) {
    trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
}
?>

Przykład #2 SOAP's standard method for error reporting is exceptions

<?php
try {
    $client = new SoapClient("some.wsdl");
    $result = $client->SomeFunction(/* ... */);
} catch (SoapFault $fault) {
    trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
}
?>

Zobacz też:

  • SoapClient::SoapClient() - SoapClient constructor
  • SoapFault::SoapFault() - SoapFault constructor

SOAP Funkcje
use_soap_error_handler
SOAP Funkcje


Set whether to use the SOAP error handler

is_soap_fault
SoapClient
SOAP Funkcje
PHP Manual

use_soap_error_handler

(Unknown)

use_soap_error_handler — Set whether to use the SOAP error handler

Opis

bool use_soap_error_handler ([ bool $handler = true ] )

This function sets whether or not to use the SOAP error handler in the SOAP server. It will return the previous value. If set to TRUE, details of errors in a SoapServer application will be sent to the clients. If FALSE, no information will be sent.

Parametry

handler

Set to TRUE to send error details to clients.

Zwracane wartości

Returns the original value.

Zobacz też:

  • set_error_handler() - Sets a user-defined error handler function
  • set_exception_handler() - Sets a user-defined exception handler function

is_soap_fault
SoapClient
SOAP Funkcje


The SoapClient class

(No version information available, might only be in SVN)

Wstęp

The SoapClient class provides a client for » SOAP 1.1, » SOAP 1.2 servers. It can be used in WSDL or non-WSDL mode.

Krótki opis klasy

SoapClient {
/* Metody */
public mixed __call ( string $function_name , string $arguments )
public SoapClient ( mixed $wsdl [, array $options ] )
public string __doRequest ( string $request , string $location , string $action , int $version [, int $one_way = 0 ] )
public array __getFunctions ( void )
public string __getLastRequest ( void )
public string __getLastRequestHeaders ( void )
public string __getLastResponse ( void )
public string __getLastResponseHeaders ( void )
public array __getTypes ( void )
public void __setCookie ( string $name [, string $value ] )
public string __setLocation ([ string $new_location ] )
public bool __setSoapHeaders ([ mixed $soapheaders ] )
public mixed __soapCall ( string $function_name , array $arguments [, array $options [, mixed $input_headers [, array &$output_headers ]]] )
public SoapClient ( mixed $wsdl [, array $options ] )
}

Spis treści

  • SoapClient::__call — Calls a SOAP function (deprecated)
  • SoapClient::__construct — SoapClient constructor
  • SoapClient::__doRequest — Performs a SOAP request
  • SoapClient::__getFunctions — Returns list of available SOAP functions
  • SoapClient::__getLastRequest — Returns last SOAP request
  • SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request
  • SoapClient::__getLastResponse — Returns last SOAP response
  • SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response
  • SoapClient::__getTypes — Returns a list of SOAP types
  • SoapClient::__setCookie — The __setCookie purpose
  • SoapClient::__setLocation — Sets the location of the Web service to use
  • SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls
  • SoapClient::__soapCall — Calls a SOAP function
  • SoapClient::SoapClient — SoapClient constructor
use_soap_error_handler
SoapClient::__call
SOAP


Calls a SOAP function (deprecated)

SoapClient
SoapClient::__construct
SoapClient
PHP Manual

SoapClient::__call

(PHP 5 >= 5.0.1)

SoapClient::__call — Calls a SOAP function (deprecated)

Opis

public mixed SoapClient::__call ( string $function_name , string $arguments )

This method is deprecated. Use SoapClient::__soapCall instead of it.

SoapClient
SoapClient::__construct
SoapClient


SoapClient constructor

SoapClient::__call
SoapClient::__doRequest
SoapClient
PHP Manual

SoapClient::__construct

(PHP 5 >= 5.0.1)

SoapClient::__construct — SoapClient constructor

Opis

public SoapClient::SoapClient ( mixed $wsdl [, array $options ] )

Ta funkcja jest aliasem dla: SoapClient::SoapClient()

SoapClient::__call
SoapClient::__doRequest
SoapClient


Performs a SOAP request

SoapClient::__construct
SoapClient::__getFunctions
SoapClient
PHP Manual

SoapClient::__doRequest

(PHP 5 >= 5.0.1)

SoapClient::__doRequest — Performs a SOAP request

Opis

public string SoapClient::__doRequest ( string $request , string $location , string $action , int $version [, int $one_way = 0 ] )

Performs SOAP request over HTTP.

This method can be overridden in subclasses to implement different transport layers, perform additional XML processing or other purpose.

Parametry

request

The XML SOAP request.

location

The URL to request.

action

The SOAP action.

version

The SOAP version.

one_way

If one_way is set to 1, this method returns nothing. Use this where a response is not expected.

Zwracane wartości

The XML SOAP response.

Rejestr zmian

Wersja | Opis
5.1.3 | The one_way parameter was added.

Przykłady

Przykład #1 SoapClient::__doRequest() example

<?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this->server = new SoapServer($wsdl, $options);
    $this->server->addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version, $one_way = 0) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
                                   'uri'=>'http://testuri.org'));
var_dump($x->Add(3,4));
?>

SoapClient::__construct
SoapClient::__getFunctions
SoapClient


Returns list of available SOAP functions

SoapClient::__doRequest
SoapClient::__getLastRequest
SoapClient
PHP Manual

SoapClient::__getFunctions

(PHP 5 >= 5.0.1)

SoapClient::__getFunctions — Returns list of available SOAP functions

Opis

public array SoapClient::__getFunctions ( void )

Returns an array of functions described in the WSDL for the Web service.

Informacja:

Ta funkcja działa tylko w trybie WSDL.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The array of SOAP function prototypes, detailing the return type, the function name and type-hinted paramaters.

Przykłady

Przykład #1 SoapClient::__getFunctions() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getFunctions());
?>

Powyższy przykład wyświetli:

array(26) {
  [0]=>
  string(70) "ProductInfo KeywordSearchRequest(KeywordRequest $KeywordSearchRequest)"
  [1]=>
  string(79) "ProductInfo TextStreamSearchRequest(TextStreamRequest $TextStreamSearchRequest)"
  [2]=>
  string(64) "ProductInfo PowerSearchRequest(PowerRequest $PowerSearchRequest)"
...
  [23]=>
  string(107) "ShoppingCart RemoveShoppingCartItemsRequest(RemoveShoppingCartItemsRequest $RemoveShoppingCartItemsRequest)"
  [24]=>
  string(107) "ShoppingCart ModifyShoppingCartItemsRequest(ModifyShoppingCartItemsRequest $ModifyShoppingCartItemsRequest)"
  [25]=>
  string(118) "GetTransactionDetailsResponse GetTransactionDetailsRequest(GetTransactionDetailsRequest $GetTransactionDetailsRequest)"
}

Zobacz też:

  • SoapClient::SoapClient() - SoapClient constructor

SoapClient::__doRequest
SoapClient::__getLastRequest
SoapClient


Returns last SOAP request

SoapClient::__getFunctions
SoapClient::__getLastRequestHeaders
SoapClient
PHP Manual

SoapClient::__getLastRequest

(PHP 5 >= 5.0.1)

SoapClient::__getLastRequest — Returns last SOAP request

Opis

public string SoapClient::__getLastRequest ( void )

Returns the XML sent in the last SOAP request.

Informacja:

This method works only if the SoapClient object was created with the trace option set to TRUE.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The last SOAP request, as an XML string.

Przykłady

Przykład #1 SoapClient::__getLastRequest() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

Zobacz też:

  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request
  • SoapClient::__getLastResponse() - Returns last SOAP response
  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response

SoapClient::__getFunctions
SoapClient::__getLastRequestHeaders
SoapClient


Returns the SOAP headers from the last request

SoapClient::__getLastRequest
SoapClient::__getLastResponse
SoapClient
PHP Manual

SoapClient::__getLastRequestHeaders

(PHP 5 >= 5.0.1)

SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request

Opis

public string SoapClient::__getLastRequestHeaders ( void )

Returns the SOAP headers from the last request.

Informacja:

This function only works if the SoapClient object was created with the trace option set to TRUE.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The last SOAP request headers.

Przykłady

Przykład #1 SoapClient::__getLastRequest() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
?>

Zobacz też:

  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastResponse() - Returns last SOAP response

SoapClient::__getLastRequest
SoapClient::__getLastResponse
SoapClient


Returns last SOAP response

SoapClient::__getLastRequestHeaders
SoapClient::__getLastResponseHeaders
SoapClient
PHP Manual

SoapClient::__getLastResponse

(PHP 5 >= 5.0.1)

SoapClient::__getLastResponse — Returns last SOAP response

Opis

public string SoapClient::__getLastResponse ( void )

Returns the XML received in the last SOAP response.

Informacja:

This method works only if the SoapClient object was created with the trace option set to TRUE.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The last SOAP response, as an XML string.

Przykłady

Przykład #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "Response:\n" . $client->__getLastResponse() . "\n";
?>

Zobacz też:

  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request

SoapClient::__getLastRequestHeaders
SoapClient::__getLastResponseHeaders
SoapClient


Returns the SOAP headers from the last response

SoapClient::__getLastResponse
SoapClient::__getTypes
SoapClient
PHP Manual

SoapClient::__getLastResponseHeaders

(PHP 5 >= 5.0.1)

SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response

Opis

public string SoapClient::__getLastResponseHeaders ( void )

Returns the SOAP headers from the last response.

Informacja:

This function only works if the SoapClient object was created with the trace option set to TRUE.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The last SOAP response headers.

Przykłady

Przykład #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "RESPONSE HEADERS:\n" . $client->__getLastResponseHeaders() . "\n";
?>

Zobacz też:

  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastResponse() - Returns last SOAP response

SoapClient::__getLastResponse
SoapClient::__getTypes
SoapClient


Returns a list of SOAP types

SoapClient::__getLastResponseHeaders
SoapClient::__setCookie
SoapClient
PHP Manual

SoapClient::__getTypes

(PHP 5 >= 5.0.1)

SoapClient::__getTypes — Returns a list of SOAP types

Opis

public array SoapClient::__getTypes ( void )

Returns an array of types described in the WSDL for the Web service.

Informacja:

Ta funkcja działa tylko w trybie WSDL.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The array of SOAP types, detailing all structures and types.

Przykłady

Przykład #1 SoapClient::__getTypes() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getTypes());
?>

Powyższy przykład wyświetli:

array(88) {
  [0]=>
  string(30) "ProductLine ProductLineArray[]"
  [1]=>
  string(85) "struct ProductLine {
 string Mode;
 string RelevanceRank;
 ProductInfo ProductInfo;
}"
  [2]=>
  string(105) "struct ProductInfo {
 string TotalResults;
 string TotalPages;
 string ListName;
 DetailsArray Details;
}"
...
  [85]=>
  string(32) "ShortSummary ShortSummaryArray[]"
  [86]=>
  string(121) "struct GetTransactionDetailsRequest {
 string tag;
 string devtag;
 string key;
 OrderIdArray OrderIds;
 string locale;
}"
  [87]=>
  string(75) "struct GetTransactionDetailsResponse {
 ShortSummaryArray ShortSummaries;
}"
}

Zobacz też:

  • SoapClient::SoapClient() - SoapClient constructor

SoapClient::__getLastResponseHeaders
SoapClient::__setCookie
SoapClient


The __setCookie purpose

SoapClient::__getTypes
SoapClient::__setLocation
SoapClient
PHP Manual

SoapClient::__setCookie

(PHP 5 >= 5.0.4)

SoapClient::__setCookie — The __setCookie purpose

Opis

public void SoapClient::__setCookie ( string $name [, string $value ] )

Defines a cookie to be sent along with the SOAP requests.

Informacja:

Calling this method will affect all following calls to SoapClient methods.

Parametry

name

The name of the cookie.

value

The value of the cookie. If not specified, the cookie will be deleted.

Zwracane wartości

Nie jest zwracana żadna wartość.

SoapClient::__getTypes
SoapClient::__setLocation
SoapClient


Sets the location of the Web service to use

SoapClient::__setCookie
SoapClient::__setSoapHeaders
SoapClient
PHP Manual

SoapClient::__setLocation

(PHP 5 >= 5.0.1)

SoapClient::__setLocation — Sets the location of the Web service to use

Opis

public string SoapClient::__setLocation ([ string $new_location ] )

Sets the endpoint URL that will be touched by following SOAP requests. This is equivalent to specifying the location option when constructing the SoapClient.

Informacja:

Calling this method is optional. The SoapClient uses the endpoint from the WSDL file by default.

Parametry

new_location

The new endpoint URL.

Zwracane wartości

The old endpoint URL.

Przykłady

Przykład #1 SoapClient::__setLocation() example

<?php
$client = new SoapClient('http://example.com/webservice.php?wsdl');

$client->__setLocation('http://www.somethirdparty.com');

$old_location = $client->__setLocation(); // unsets the location option

echo $old_location;

?>

Powyższy przykład wyświetli coś podobnego do:

http://www.somethirdparty.com

Zobacz też:

  • SoapClient::SoapClient() - SoapClient constructor

SoapClient::__setCookie
SoapClient::__setSoapHeaders
SoapClient


Sets SOAP headers for subsequent calls

SoapClient::__setLocation
SoapClient::__soapCall
SoapClient
PHP Manual

SoapClient::__setSoapHeaders

(PHP 5 >= 5.0.5)

SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls

Opis

public bool SoapClient::__setSoapHeaders ([ mixed $soapheaders ] )

Defines headers to be sent along with the SOAP requests.

Informacja:

Calling this method will replace any previous values.

Parametry

soapheaders

The headers to be set. It could be SoapHeader object or array of SoapHeader objects. If not specified or set to NULL, the headers will be deleted.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 SoapClient::__setSoapHeaders() example

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$header = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world');

$client->__setSoapHeaders($header);

$client->__soapCall("echoVoid", null);
?>

Przykład #2 Set Multiple Headers

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$headers = array();

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world');

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world again');

$client->__setSoapHeaders($headers);

$client->__soapCall("echoVoid", null);
?>

SoapClient::__setLocation
SoapClient::__soapCall
SoapClient


Calls a SOAP function

SoapClient::__setSoapHeaders
SoapClient::SoapClient
SoapClient
PHP Manual

SoapClient::__soapCall

(PHP 5 >= 5.0.1)

SoapClient::__soapCall — Calls a SOAP function

Opis

public mixed SoapClient::__soapCall ( string $function_name , array $arguments [, array $options [, mixed $input_headers [, array &$output_headers ]]] )

This is a low level API function that is used to make a SOAP call. Usually, in WSDL mode, SOAP functions can be called as methods of the SoapClient object. This method is useful in non-WSDL mode when soapaction is unknown, uri differs from the default or when sending and/or receiving SOAP Headers.

On error, a call to a SOAP function can cause PHP to throw exceptions or return a SoapFault object if exceptions are disabled. To check if the function call failed to catch the SoapFault exceptions, check the result with is_soap_fault().

Parametry

function_name

The name of the SOAP function to call.

arguments

An array of the arguments to pass to the function. This can be either an ordered or an associative array.

options

An associative array of options to pass to the client.

The location option is the URL of the remote Web service.

The uri option is the target namespace of the SOAP service.

The soapaction option is the action to call.

input_headers

An array of headers to be sent along with the SOAP request.

output_headers

If supplied, this array will be filled with the headers from the SOAP response.

Zwracane wartości

SOAP functions may return one, or multiple values. If only one value is returned by the SOAP function, the return value of __soapCall will be a simple value (e.g. an integer, a string, etc). If multiple values are returned, __soapCall will return an associative array of named output parameters.

On error, if the SoapClient object was constructed with the trace option set to FALSE, a SoapFault object will be returned.

Przykłady

Przykład #1 SoapClient::__soapCall() example

<?php

$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);

$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c), NULL,
                    new SoapHeader(), $output_headers);

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->SomeFunction($a, $b, $c);
$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c),
                    array('soapaction' => 'some_action',
                          'uri'        => 'some_uri'));
?>

Zobacz też:

  • SoapClient::SoapClient() - SoapClient constructor
  • SoapParam::SoapParam() - SoapParam constructor
  • SoapVar::SoapVar() - SoapVar constructor
  • SoapHeader::SoapHeader() - SoapHeader constructor
  • SoapFault::SoapFault() - SoapFault constructor
  • is_soap_fault() - Checks if a SOAP call has failed

SoapClient::__setSoapHeaders
SoapClient::SoapClient
SoapClient


SoapClient constructor

SoapClient::__soapCall
SoapServer
SoapClient
PHP Manual

SoapClient::SoapClient

(PHP 5 >= 5.0.1)

SoapClient::SoapClient — SoapClient constructor

Opis

public SoapClient::SoapClient ( mixed $wsdl [, array $options ] )

This constructor creates SoapClient objects in WSDL or non-WSDL mode.

Parametry

wsdl

URI of the WSDL file or NULL if working in non-WSDL mode.

Informacja:

During development, WSDL caching may be disabled by the use of the soap.wsdl_cache_ttl php.ini setting otherwise changes made to the WSDL file will have no effect until soap.wsdl_cache_ttl is expired.

options

An array of options. If working in WSDL mode, this parameter is optional. If working in non-WSDL mode, the location and uri options must be set, where location is the URL of the SOAP server to send the request to, and uri is the target namespace of the SOAP service.

The style and use options only work in non-WSDL mode. In WSDL mode, they come from the WSDL file.

The soap_version option specifies whether to use SOAP 1.1 (default), or SOAP 1.2 client.

For HTTP authentication, the login and password options can be used to supply credentials. For making an HTTP connection through a proxy server, the options proxy_host, proxy_port, proxy_login and proxy_password are also available. For HTTPS client certificate authentication use local_cert and passphrase options. An authentication may be supplied in the authentication option. The authentication method may be either SOAP_AUTHENTICATION_BASIC (default) or SOAP_AUTHENTICATION_DIGEST.

The compression option allows to use compression of HTTP SOAP requests and responses.

The encoding option defines internal character encoding. This option does not change the encoding of SOAP requests (it is always utf-8), but converts strings into it.

The trace option enables tracing of request so faults can be backtraced. This defaults to FALSE

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

Setting the boolean trace option enables use of the
methods
SoapClient->__getLastRequest,

SoapClient->__getLastRequestHeaders,

SoapClient->__getLastResponse and

SoapClient->__getLastResponseHeaders.

The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault.

The connection_timeout option defines a timeout in seconds for the connection to the SOAP service. This option does not define a timeout for services with slow responses. To limit the time to wait for calls to finish the default_socket_timeout setting is available.

The typemap option is an array of type mappings. Type mapping is an array with keys type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).

The cache_wsdl option is one of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

The user_agent option specifies string to use in User-Agent header.

The stream_context option is a resource for context.

The features option is a bitmask of SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE, SOAP_WAIT_ONE_WAY_CALLS.

The keep_alive option is a boolean value defining whether to send the Connection: Keep-Alive header or Connection: close .

Rejestr zmian

Wersja | Opis
5.4.0 | New keep_alive option.

Przykłady

Przykład #1 SoapClient::SoapClient() example

<?php

$client = new SoapClient("some.wsdl");

$client = new SoapClient("some.wsdl", array('soap_version'   => SOAP_1_2));

$client = new SoapClient("some.wsdl", array('login'          => "some_name",
                                            'password'       => "some_password"));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080,
                                            'proxy_login'    => "some_name",
                                            'proxy_password' => "some_password"));

$client = new SoapClient("some.wsdl", array('local_cert'     => "cert_key.pem"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/",
                                     'style'    => SOAP_DOCUMENT,
                                     'use'      => SOAP_LITERAL));

$client = new SoapClient("some.wsdl",
  array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));

$server = new SoapClient("some.wsdl", array('encoding'=>'ISO-8859-1'));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapClient("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

SoapClient::__soapCall
SoapServer
SoapClient


The SoapServer class

(No version information available, might only be in SVN)

Wstęp

The SoapServer class provides a server for the » SOAP 1.1 and » SOAP 1.2 protocols. It can be used with or without a WSDL service description.

Krótki opis klasy

SoapServer {
/* Metody */
public void addFunction ( mixed $functions )
public void addSoapHeader ( SoapHeader $object )
public __construct ( mixed $wsdl [, array $options ] )
public void fault ( string $code , string $string [, string $actor [, string $details [, string $name ]]] )
public array getFunctions ( void )
public void handle ([ string $soap_request ] )
public void setClass ( string $class_name [, mixed $args [, mixed $... ]] )
public void setObject ( object $object )
public void setPersistence ( int $mode )
public SoapServer ( mixed $wsdl [, array $options ] )
}

Spis treści

  • SoapServer::addFunction — Adds one or more functions to handle SOAP requests
  • SoapServer::addSoapHeader — Add a SOAP header to the response
  • SoapServer::__construct — SoapServer constructor
  • SoapServer::fault — Issue SoapServer fault indicating an error
  • SoapServer::getFunctions — Returns list of defined functions
  • SoapServer::handle — Handles a SOAP request
  • SoapServer::setClass — Sets the class which handles SOAP requests
  • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
  • SoapServer::setPersistence — Sets SoapServer persistence mode
  • SoapServer::SoapServer — SoapServer constructor
SoapClient::SoapClient
SoapServer::addFunction
SOAP


Adds one or more functions to handle SOAP requests

SoapServer
SoapServer::addSoapHeader
SoapServer
PHP Manual

SoapServer::addFunction

(PHP 5 >= 5.0.1)

SoapServer::addFunction — Adds one or more functions to handle SOAP requests

Opis

public void SoapServer::addFunction ( mixed $functions )

Exports one or more functions for remote clients

Parametry

functions

To export one function, pass the function name into this parameter as a string.

To export several functions, pass an array of function names.

To export all the functions, pass a special constant SOAP_FUNCTIONS_ALL.

Informacja:

functions must receive all input arguments in the same order as defined in the WSDL file (They should not receive any output parameters as arguments) and return one or more values. To return several values they must return an array with named output parameters.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SoapServer::addFunction() example

<?php

function echoString($inputString)
{
    return $inputString;
}

$server->addFunction("echoString");

function echoTwoStrings($inputString1, $inputString2)
{
    return array("outputString1" => $inputString1,
                 "outputString2" => $inputString2);
}
$server->addFunction(array("echoString", "echoTwoStrings"));

$server->addFunction(SOAP_FUNCTIONS_ALL);

?>

Zobacz też:

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::setClass() - Sets the class which handles SOAP requests

SoapServer
SoapServer::addSoapHeader
SoapServer


Add a SOAP header to the response

SoapServer::addFunction
SoapServer::__construct
SoapServer
PHP Manual

SoapServer::addSoapHeader

(PHP 5 >= 5.0.1)

SoapServer::addSoapHeader — Add a SOAP header to the response

Opis

public void SoapServer::addSoapHeader ( SoapHeader $object )

Adds a SOAP header to be returned with the response to the current request.

Parametry

object

The header to be returned.

Zwracane wartości

Nie jest zwracana żadna wartość.

SoapServer::addFunction
SoapServer::__construct
SoapServer


SoapServer constructor

SoapServer::addSoapHeader
SoapServer::fault
SoapServer
PHP Manual

SoapServer::__construct

(PHP 5 >= 5.0.1)

SoapServer::__construct — SoapServer constructor

Opis

public SoapServer::__construct ( mixed $wsdl [, array $options ] )

Ta funkcja jest aliasem dla: SoapServer::SoapServer()

SoapServer::addSoapHeader
SoapServer::fault
SoapServer


Issue SoapServer fault indicating an error

SoapServer::__construct
SoapServer::getFunctions
SoapServer
PHP Manual

SoapServer::fault

(PHP 5 >= 5.0.1)

SoapServer::fault — Issue SoapServer fault indicating an error

Opis

public void SoapServer::fault ( string $code , string $string [, string $actor [, string $details [, string $name ]]] )

Sends a response to the client of the current request indicating an error.

Informacja:

This can only be called when handling a request.

Parametry

code

The error code to return

string

A brief description of the error

actor

A string identifying the actor that caused the fault.

details

More details of the fault

name

The name of the fault. This can be used to select a name from a WSDL file.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SoapFault::SoapFault() - SoapFault constructor

SoapServer::__construct
SoapServer::getFunctions
SoapServer


Returns list of defined functions

SoapServer::fault
SoapServer::handle
SoapServer
PHP Manual

SoapServer::getFunctions

(PHP 5 >= 5.0.1)

SoapServer::getFunctions — Returns list of defined functions

Opis

public array SoapServer::getFunctions ( void )

Returns a list of the defined functions in the SoapServer object. This method returns the list of all functions added by SoapServer::addFunction() or SoapServer::setClass().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of the defined functions.

Przykłady

Przykład #1 SoapServer::getFunctions() example

<?php
$server = new SoapServer(NULL, array("uri" => "http://test-uri"));
$server->addFunction(SOAP_FUNCTIONS_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $server->handle();
} else {
  echo "This SOAP server can handle following functions: ";
  $functions = $server->getFunctions();
  foreach($functions as $func) {
    echo $func . "\n";
  }
}
?>

Zobacz też:

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::addFunction() - Adds one or more functions to handle SOAP requests
  • SoapServer::setClass() - Sets the class which handles SOAP requests

SoapServer::fault
SoapServer::handle
SoapServer


Handles a SOAP request

SoapServer::getFunctions
SoapServer::setClass
SoapServer
PHP Manual

SoapServer::handle

(PHP 5 >= 5.0.1)

SoapServer::handle — Handles a SOAP request

Opis

public void SoapServer::handle ([ string $soap_request ] )

Processes a SOAP request, calls necessary functions, and sends a response back.

Parametry

soap_request

The SOAP request. If this argument is omitted, the request is assumed to be in the raw POST data of the HTTP request.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SoapServer::handle() example

<?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

Zobacz też:

  • SoapServer::SoapServer() - SoapServer constructor

SoapServer::getFunctions
SoapServer::setClass
SoapServer


Sets the class which handles SOAP requests

SoapServer::handle
SoapServer::setObject
SoapServer
PHP Manual

SoapServer::setClass

(PHP 5 >= 5.0.1)

SoapServer::setClass — Sets the class which handles SOAP requests

Opis

public void SoapServer::setClass ( string $class_name [, mixed $args [, mixed $... ]] )

Exports all methods from specified class.

The object can be made persistent across request for a given PHP session with the SoapServer::setPersistence() method.

Parametry

class_name

The name of the exported class.

args

These optional parameters will be passed to the default class constructor during object creation.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::addFunction() - Adds one or more functions to handle SOAP requests
  • SoapServer::setPersistence() - Sets SoapServer persistence mode

SoapServer::handle
SoapServer::setObject
SoapServer


Sets the object which will be used to handle SOAP requests

SoapServer::setClass
SoapServer::setPersistence
SoapServer
PHP Manual

SoapServer::setObject

(PHP 5 >= 5.2.0)

SoapServer::setObject — Sets the object which will be used to handle SOAP requests

Opis

public void SoapServer::setObject ( object $object )

This sets a specific object as the handler for SOAP requests, rather than just a class as in SoapServer::setClass().

Parametry

object

The object to handle the requests.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • SoapServer::setClass() - Sets the class which handles SOAP requests

SoapServer::setClass
SoapServer::setPersistence
SoapServer


Sets SoapServer persistence mode

SoapServer::setObject
SoapServer::SoapServer
SoapServer
PHP Manual

SoapServer::setPersistence

(PHP 5 >= 5.1.2)

SoapServer::setPersistence — Sets SoapServer persistence mode

Opis

public void SoapServer::setPersistence ( int $mode )

This function allows changing the persistence state of a SoapServer object between requests. This function allows saving data between requests utilizing PHP sessions. This method only has an affect on a SoapServer after it has exported functions utilizing SoapServer::setClass().

Informacja:

The persistence of SOAP_PERSISTENCE_SESSION makes only objects of the given class persistent, but not the class static data. In this case, use $this->bar instead of self::$bar.

Informacja:

SOAP_PERSISTENCE_SESSION serializes data on the class object between requests. In order to properly utilize resources (e.g. PDO), __wakeup() and __sleep() magic methods should be utilized.

Parametry

mode

One of the SOAP_PERSISTENCE_XXX constants.

SOAP_PERSISTENCE_REQUEST - SoapServer data does not persist between requests. This is the default behavior of any SoapServer object after setClass is called.

SOAP_PERSISTENCE_SESSION - SoapServer data does persists between requests. This is accomplished by serializing the SoapServer class data into $_SESSION['_bogus_session_name'], because of this session_start() must be called before this persistence mode is set.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 SoapServer::setPersistence() example

<?php
 class MyFirstPersistentSoapServer {
     private $resource; // (Such as PDO, mysqli, etc..)
     public $myvar1;
     public $myvar2;

     public function __construct() {
         $this->__wakeup(); // We're calling our wakeup to handle starting our resource
     }

     public function __wakeup() {
         $this->resource = CodeToStartOurResourceUp();
     }

     public function __sleep() {
         // We make sure to leave out $resource here, so our session data remains persistent
         // Failure to do so will result in the failure during the unserialization of data
         // on the next request; thus, our SoapObject would not be persistent across requests.
         return array('myvar1','myvar2');
     }
 }

 try {
     session_start();
     $server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
     $server->setClass('MyFirstPersistentSoapServer');
     // setPersistence MUST be called after setClass, because setClass's
     // behavior sets SESSION_PERSISTENCE_REQUEST upon enacting the method.
     $server->setPersistence(SOAP_PERSISTENCE_SESSION);
     $server->handle();
 } catch(SoapFault $e) {
     error_log("SOAP ERROR: ". $e->getMessage());
 }
?>

Zobacz też:

  • SoapServer::setClass() - Sets the class which handles SOAP requests

SoapServer::setObject
SoapServer::SoapServer
SoapServer


SoapServer constructor

SoapServer::setPersistence
SoapFault
SoapServer
PHP Manual

SoapServer::SoapServer

(PHP 5 >= 5.0.1)

SoapServer::SoapServer — SoapServer constructor

Opis

public SoapServer::SoapServer ( mixed $wsdl [, array $options ] )

This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.

Parametry

wsdl

To use the SoapServer in WSDL mode, pass the URI of a WSDL file. Otherwise, pass NULL and set the uri option to the target namespace for the server.

options

Allow setting a default SOAP version (soap_version), internal character encoding (encoding), and actor URI (actor).

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

The typemap option is an array of type mappings. Type mapping is an array with keys type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).

The cache_wsdl option is one of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

There is also a features option which can be set to SOAP_WAIT_ONE_WAY_CALLS, SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE.

Przykłady

Przykład #1 SoapServer::SoapServer() example

<?php

$server = new SoapServer("some.wsdl");

$server = new SoapServer("some.wsdl", array('soap_version' => SOAP_1_2));

$server = new SoapServer("some.wsdl", array('actor' => "http://example.org/ts-tests/C"));

$server = new SoapServer("some.wsdl", array('encoding'=>'ISO-8859-1'));

$server = new SoapServer(null, array('uri' => "http://test-uri/"));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapServer("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

Rejestr zmian

Wersja | Opis
5.2.0 | Added the typemap option.

Zobacz też:

  • SoapClient::SoapClient() - SoapClient constructor

SoapServer::setPersistence
SoapFault
SoapServer


The SoapFault class

(No version information available, might only be in SVN)

Wstęp

Represents a SOAP fault.

Krótki opis klasy

SoapFault extends Exception {
/* Właściwości */
/* Metody */
__construct ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )
SoapFault ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )
public string __toString ( 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

message

Prop description

code

Prop description

file

Prop description

line

Prop description

Spis treści

  • SoapFault::__construct — SoapFault constructor
  • SoapFault::SoapFault — SoapFault constructor
  • SoapFault::__toString — Obtain a string representation of a SoapFault
SoapServer::SoapServer
SoapFault::__construct
SOAP


SoapFault constructor

SoapFault
SoapFault::SoapFault
SoapFault
PHP Manual

SoapFault::__construct

(PHP 5 >= 5.0.1)

SoapFault::__construct — SoapFault constructor

Opis

SoapFault::__construct ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )

Ta funkcja jest aliasem dla: SoapFault::SoapFault()

SoapFault
SoapFault::SoapFault
SoapFault


SoapFault constructor

SoapFault::__construct
SoapFault::__toString
SoapFault
PHP Manual

SoapFault::SoapFault

(PHP 5 >= 5.0.1)

SoapFault::SoapFault — SoapFault constructor

Opis

SoapFault::SoapFault ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )

This class is used to send SOAP fault responses from the PHP handler. faultcode, faultstring, faultactor and detail are standard elements of a SOAP Fault.

Parametry

faultcode

The error code of the SoapFault.

faultstring

The error message of the SoapFault.

faultactor

A string identifying the actor that caused the error.

detail

More details about the cause of the error.

faultname

Can be used to select the proper fault encoding from WSDL.

headerfault

Can be used during SOAP header handling to report an error in the response header.

Przykłady

Przykład #1 Some examples

<?php
function test($x)
{
    return new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

It is possible to use PHP exception mechanism to throw SOAP Fault.

Przykład #2 Some examples

<?php
function test($x)
{
    throw new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

Zobacz też:

  • SoapServer::fault() - Issue SoapServer fault indicating an error
  • is_soap_fault() - Checks if a SOAP call has failed

SoapFault::__construct
SoapFault::__toString
SoapFault


Obtain a string representation of a SoapFault

SoapFault::SoapFault
SoapHeader
SoapFault
PHP Manual

SoapFault::__toString

(PHP 5 >= 5.0.1)

SoapFault::__toString — Obtain a string representation of a SoapFault

Opis

public string SoapFault::__toString ( void )

Returns a string representation of the SoapFault.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A string describing the SoapFault.

SoapFault::SoapFault
SoapHeader
SoapFault


The SoapHeader class

(No version information available, might only be in SVN)

Wstęp

Represents a SOAP header.

Krótki opis klasy

SoapHeader {
/* Metody */
__construct ( string $namespace , string $name [, mixed $data [, bool $mustunderstand [, string $actor ]]] )
SoapHeader ( string $namespace , string $name [, mixed $data [, bool $mustunderstand = false [, string $actor ]]] )
}

Spis treści

  • SoapHeader::__construct — SoapHeader constructor
  • SoapHeader::SoapHeader — SoapHeader constructor
SoapFault::__toString
SoapHeader::__construct
SOAP


SoapHeader constructor

SoapHeader
SoapHeader::SoapHeader
SoapHeader
PHP Manual

SoapHeader::__construct

(PHP 5 >= 5.0.1)

SoapHeader::__construct — SoapHeader constructor

Opis

SoapHeader::__construct ( string $namespace , string $name [, mixed $data [, bool $mustunderstand [, string $actor ]]] )

Ta funkcja jest aliasem dla: SoapHeader::SoapHeader()

SoapHeader
SoapHeader::SoapHeader
SoapHeader


SoapHeader constructor

SoapHeader::__construct
SoapParam
SoapHeader
PHP Manual

SoapHeader::SoapHeader

(PHP 5 >= 5.0.1)

SoapHeader::SoapHeader — SoapHeader constructor

Opis

SoapHeader::SoapHeader ( string $namespace , string $name [, mixed $data [, bool $mustunderstand = false [, string $actor ]]] )

Constructs a new SoapHeader object.

Parametry

namespace

The namespace of the SOAP header element.

name

The name of the SoapHeader object.

data

A SOAP header's content. It can be a PHP value or a SoapVar object.

mustUnderstand

Value of the mustUnderstand attribute of the SOAP header element.

actor

Value of the actor attribute of the SOAP header element.

Przykłady

Przykład #1 SoapHeader::SoapHeader() example

<?php
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->__soapCall("echoVoid", null, null,
                new SoapHeader('http://soapinterop.org/echoheader/',
                               'echoMeStringRequest',
                               'hello world'));
?>

Zobacz też:

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::SoapVar() - SoapVar constructor
  • SoapParam::SoapParam() - SoapParam constructor
  • SoapServer::addSoapHeader() - Add a SOAP header to the response

SoapHeader::__construct
SoapParam
SoapHeader


The SoapParam class

(No version information available, might only be in SVN)

Wstęp

Represents parameter to a SOAP call.

Krótki opis klasy

SoapParam {
/* Metody */
__construct ( mixed $data , string $name )
SoapParam ( mixed $data , string $name )
}

Spis treści

  • SoapParam::__construct — SoapParam constructor
  • SoapParam::SoapParam — SoapParam constructor
SoapHeader::SoapHeader
SoapParam::__construct
SOAP


SoapParam constructor

SoapParam
SoapParam::SoapParam
SoapParam
PHP Manual

SoapParam::__construct

(PHP 5 >= 5.0.1)

SoapParam::__construct — SoapParam constructor

Opis

SoapParam::__construct ( mixed $data , string $name )

Ta funkcja jest aliasem dla: SoapParam::SoapParam()

SoapParam
SoapParam::SoapParam
SoapParam


SoapParam constructor

SoapParam::__construct
SoapVar
SoapParam
PHP Manual

SoapParam::SoapParam

(PHP 5 >= 5.0.1)

SoapParam::SoapParam — SoapParam constructor

Opis

SoapParam::SoapParam ( mixed $data , string $name )

Constructs a new SoapParam object.

Parametry

data

The data to pass or return. This parameter can be passed directly as PHP value, but in this case it will be named as paramN and the SOAP service may not understand it.

name

The parameter name.

Przykłady

Przykład #1 SoapParam::SoapParam() example

<?php
$client = new SoapClient(null,array('location' => "http://localhost/soap.php",
                                    'uri'      => "http://test-uri/"));
$client->SomeFunction(new SoapParam($a, "a"),
                      new SoapParam($b, "b"),
                      new SoapParam($c, "c"));
?>

Zobacz też:

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::SoapVar() - SoapVar constructor

SoapParam::__construct
SoapVar
SoapParam


The SoapVar class

(No version information available, might only be in SVN)

Wstęp

A class representing a variable or object for use with SOAP services.

Krótki opis klasy

SoapVar {
/* Metody */
__construct ( string $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )
SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )
}

Spis treści

  • SoapVar::__construct — SoapVar constructor
  • SoapVar::SoapVar — SoapVar constructor
SoapParam::SoapParam
SoapVar::__construct
SOAP


SoapVar constructor

SoapVar
SoapVar::SoapVar
SoapVar
PHP Manual

SoapVar::__construct

(PHP 5 >= 5.0.1)

SoapVar::__construct — SoapVar constructor

Opis

SoapVar::__construct ( string $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )

Ta funkcja jest aliasem dla: SoapVar::SoapVar()

SoapVar
SoapVar::SoapVar
SoapVar


SoapVar constructor

SoapVar::__construct
XML-RPC
SoapVar
PHP Manual

SoapVar::SoapVar

(PHP 5 >= 5.0.1)

SoapVar::SoapVar — SoapVar constructor

Opis

SoapVar::SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )

Constructs a new SoapVar object.

Parametry

data

The data to pass or return.

encoding

The encoding ID, one of the XSD_... constants.

type_name

The type name.

type_namespace

The type namespace.

node_name

The XML node name.

node_namespace

The XML node namespace.

Przykłady

Przykład #1 SoapVar::SoapVar() example

<?php
class SOAPStruct {
    function SOAPStruct($s, $i, $f)
    {
        $this->varString = $s;
        $this->varInt = $i;
        $this->varFloat = $f;
    }
}
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client->echoStruct(new SoapParam($soapstruct, "inputStruct"));
?>

Zobacz też:

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapParam::SoapParam() - SoapParam constructor

SoapVar::__construct
XML-RPC
SoapVar


XML-RPC

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • XML-RPC Funkcje
    • xmlrpc_decode_request — Decodes XML into native PHP types
    • xmlrpc_decode — Decodes XML into native PHP types
    • xmlrpc_encode_request — Generates XML for a method request
    • xmlrpc_encode — Generates XML for a PHP value
    • xmlrpc_get_type — Gets xmlrpc type for a PHP value
    • xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
    • xmlrpc_parse_method_descriptions — Decodes XML into a list of method descriptions
    • xmlrpc_server_add_introspection_data — Adds introspection documentation
    • xmlrpc_server_call_method — Parses XML requests and call methods
    • xmlrpc_server_create — Creates an xmlrpc server
    • xmlrpc_server_destroy — Destroys server resources
    • xmlrpc_server_register_introspection_callback — Register a PHP function to generate documentation
    • xmlrpc_server_register_method — Register a PHP function to resource method matching method_name
    • xmlrpc_set_type — Sets xmlrpc type, base64 or datetime, for a PHP string value
SoapVar::SoapVar
Wstęp
Usługi sieciowe


Wstęp

These functions can be used to write XML-RPC servers and clients. You can find more information about XML-RPC at » http://www.xmlrpc.com/, and more documentation on this extension and its functions at » http://xmlrpc-epi.sourceforge.net/.

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.

XML-RPC
Instalacja/Konfiguracja
XML-RPC


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
XML-RPC


Instalacja

XML-RPC support in PHP is not enabled by default. You will need to use the --with-xmlrpc[=DIR] configuration option when compiling PHP to enable XML-RPC support. This extension is bundled into PHP as of 4.1.0.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines a XML-RPC server resource returned by xmlrpc_server_create().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
XML-RPC Funkcje
XML-RPC


XML-RPC Funkcje

Spis treści

  • xmlrpc_decode_request — Decodes XML into native PHP types
  • xmlrpc_decode — Decodes XML into native PHP types
  • xmlrpc_encode_request — Generates XML for a method request
  • xmlrpc_encode — Generates XML for a PHP value
  • xmlrpc_get_type — Gets xmlrpc type for a PHP value
  • xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
  • xmlrpc_parse_method_descriptions — Decodes XML into a list of method descriptions
  • xmlrpc_server_add_introspection_data — Adds introspection documentation
  • xmlrpc_server_call_method — Parses XML requests and call methods
  • xmlrpc_server_create — Creates an xmlrpc server
  • xmlrpc_server_destroy — Destroys server resources
  • xmlrpc_server_register_introspection_callback — Register a PHP function to generate documentation
  • xmlrpc_server_register_method — Register a PHP function to resource method matching method_name
  • xmlrpc_set_type — Sets xmlrpc type, base64 or datetime, for a PHP string value
Stałe predefiniowane
xmlrpc_decode_request
XML-RPC


Decodes XML into native PHP types

XML-RPC Funkcje
xmlrpc_decode
XML-RPC Funkcje
PHP Manual

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_decode_request — Decodes XML into native PHP types

Opis

mixed xmlrpc_decode_request ( string $xml , string &$method [, string $encoding ] )
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.

XML-RPC Funkcje
xmlrpc_decode
XML-RPC Funkcje


Decodes XML into native PHP types

xmlrpc_decode_request
xmlrpc_encode_request
XML-RPC Funkcje
PHP Manual

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_decode — Decodes XML into native PHP types

Opis

mixed xmlrpc_decode ( string $xml [, string $encoding = "iso-8859-1" ] )
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

xml

XML response returned by XMLRPC method.

encoding

Input encoding supported by iconv.

Zwracane wartości

Returns either an array, or an integer, or a string, or a boolean according to the response returned by the XMLRPC method.

Przykłady

See example by xmlrpc_encode_request().

Zobacz też:

  • xmlrpc_encode_request() - Generates XML for a method request
  • xmlrpc_is_fault() - Determines if an array value represents an XMLRPC fault

xmlrpc_decode_request
xmlrpc_encode_request
XML-RPC Funkcje


Generates XML for a method request

xmlrpc_decode
xmlrpc_encode
XML-RPC Funkcje
PHP Manual

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_encode_request — Generates XML for a method request

Opis

string xmlrpc_encode_request ( string $method , mixed $params [, array $output_options ] )
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

method

Name of the method to call.

params

Method parameters compatible with method signature.

output_options

Array specifying output options may contain (default values are emphasised):

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (may be a string with one value or an array with multiple values)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, other character set supported by iconv

Zwracane wartości

Returns a string containing the XML representation of the request.

Przykłady

Przykład #1 XMLRPC client functions example

<?php
$request = xmlrpc_encode_request("method", array(1, 2, 3));
$context = stream_context_create(array('http' => array(
    'method' => "POST",
    'header' => "Content-Type: text/xml",
    'content' => $request
)));
$file = file_get_contents("http://www.example.com/xmlrpc", false, $context);
$response = xmlrpc_decode($file);
if ($response && xmlrpc_is_fault($response)) {
    trigger_error("xmlrpc: $response[faultString] ($response[faultCode])");
} else {
    print_r($response);
}
?>

Zobacz też:

  • stream_context_create() - Create a streams context
  • file_get_contents() - Reads entire file into a string
  • xmlrpc_decode() - Decodes XML into native PHP types

xmlrpc_decode
xmlrpc_encode
XML-RPC Funkcje


Generates XML for a PHP value

xmlrpc_encode_request
xmlrpc_get_type
XML-RPC Funkcje
PHP Manual

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_encode — Generates XML for a PHP value

Opis

string xmlrpc_encode ( mixed $value )
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.

xmlrpc_encode_request
xmlrpc_get_type
XML-RPC Funkcje


Gets xmlrpc type for a PHP value

xmlrpc_encode
xmlrpc_is_fault
XML-RPC Funkcje
PHP Manual

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_get_type — Gets xmlrpc type for a PHP value

Opis

string xmlrpc_get_type ( mixed $value )
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.

This function is especially useful for base64 and datetime strings.

Parametry

value

PHP value

Zwracane wartości

Returns the XML-RPC type.

Przykłady

Przykład #1 XML-RPC type example

<?php
echo xmlrpc_get_type(null) . "\n"; // base64
echo xmlrpc_get_type(false) . "\n"; // boolean
echo xmlrpc_get_type(1) . "\n"; // int
echo xmlrpc_get_type(1.0) . "\n"; // double
echo xmlrpc_get_type("") . "\n"; // string
echo xmlrpc_get_type(array()) . "\n"; // array
echo xmlrpc_get_type(new stdClass) . "\n"; // array
echo xmlrpc_get_type(STDIN) . "\n"; // int
?>

Zobacz też:

  • xmlrpc_set_type() - Sets xmlrpc type, base64 or datetime, for a PHP string value

xmlrpc_encode
xmlrpc_is_fault
XML-RPC Funkcje


Determines if an array value represents an XMLRPC fault

xmlrpc_get_type
xmlrpc_parse_method_descriptions
XML-RPC Funkcje
PHP Manual

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5)

xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault

Opis

bool xmlrpc_is_fault ( array $arg )
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

arg

Array returned by xmlrpc_decode().

Zwracane wartości

Returns TRUE if the argument means fault, FALSE otherwise. Fault description is available in $arg["faultString"], fault code is in $arg["faultCode"].

Przykłady

See example by xmlrpc_encode_request().

Zobacz też:

  • xmlrpc_decode() - Decodes XML into native PHP types

xmlrpc_get_type
xmlrpc_parse_method_descriptions
XML-RPC Funkcje


Decodes XML into a list of method descriptions

xmlrpc_is_fault
xmlrpc_server_add_introspection_data
XML-RPC Funkcje
PHP Manual

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_parse_method_descriptions — Decodes XML into a list of method descriptions

Opis

array xmlrpc_parse_method_descriptions ( string $xml )
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.

xmlrpc_is_fault
xmlrpc_server_add_introspection_data
XML-RPC Funkcje


Adds introspection documentation

xmlrpc_parse_method_descriptions
xmlrpc_server_call_method
XML-RPC Funkcje
PHP Manual

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_add_introspection_data — Adds introspection documentation

Opis

int xmlrpc_server_add_introspection_data ( resource $server , array $desc )
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.

xmlrpc_parse_method_descriptions
xmlrpc_server_call_method
XML-RPC Funkcje


Parses XML requests and call methods

xmlrpc_server_add_introspection_data
xmlrpc_server_create
XML-RPC Funkcje
PHP Manual

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_call_method — Parses XML requests and call methods

Opis

string xmlrpc_server_call_method ( resource $server , string $xml , mixed $user_data [, array $output_options ] )
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.

xmlrpc_server_add_introspection_data
xmlrpc_server_create
XML-RPC Funkcje


Creates an xmlrpc server

xmlrpc_server_call_method
xmlrpc_server_destroy
XML-RPC Funkcje
PHP Manual

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_create — Creates an xmlrpc server

Opis

resource xmlrpc_server_create ( 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.

xmlrpc_server_call_method
xmlrpc_server_destroy
XML-RPC Funkcje


Destroys server resources

xmlrpc_server_create
xmlrpc_server_register_introspection_callback
XML-RPC Funkcje
PHP Manual

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_destroy — Destroys server resources

Opis

int xmlrpc_server_destroy ( resource $server )
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.

xmlrpc_server_create
xmlrpc_server_register_introspection_callback
XML-RPC Funkcje


Register a PHP function to generate documentation

xmlrpc_server_destroy
xmlrpc_server_register_method
XML-RPC Funkcje
PHP Manual

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_register_introspection_callback — Register a PHP function to generate documentation

Opis

bool xmlrpc_server_register_introspection_callback ( resource $server , string $function )
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.

xmlrpc_server_destroy
xmlrpc_server_register_method
XML-RPC Funkcje


Register a PHP function to resource method matching method_name

xmlrpc_server_register_introspection_callback
xmlrpc_set_type
XML-RPC Funkcje
PHP Manual

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_server_register_method — Register a PHP function to resource method matching method_name

Opis

bool xmlrpc_server_register_method ( resource $server , string $method_name , string $function )
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.

xmlrpc_server_register_introspection_callback
xmlrpc_set_type
XML-RPC Funkcje


Sets xmlrpc type, base64 or datetime, for a PHP string value

xmlrpc_server_register_method
Rozszerzenia przeznaczone dla Windows
XML-RPC Funkcje
PHP Manual

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5)

xmlrpc_set_type — Sets xmlrpc type, base64 or datetime, for a PHP string value

Opis

bool xmlrpc_set_type ( string &$value , string $type )

Sets xmlrpc type, base64 or datetime, for a PHP string value.

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

value

Value to set the type

type

'base64' or 'datetime'

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If successful, value is converted to an object.

Przykłady

Przykład #1 A xmlrpc_set_type() example

<?php

$params = date("Ymd\TH:i:s", time());
xmlrpc_set_type($params, 'datetime');
echo xmlrpc_encode($params);

?>

Powyższy przykład wyświetli coś podobnego do:

<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601>
 </value>
</param>
</params>

Błędy/Wyjątki

Issues E_WARNING with type unsupported by XMLRPC.

xmlrpc_server_register_method
Rozszerzenia przeznaczone dla Windows
XML-RPC Funkcje


Rozszerzenia przeznaczone dla Windows

  • .NET
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Funkcje .NET
  • COM — COM and .Net (Windows)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Errors and error handling
    • Przykłady
    • COM — The COM class
    • DOTNET — The DOTNET class
    • VARIANT — VARIANT class
    • COM Funkcje
  • Printer
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Printer Funkcje
  • W32api
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • W32api Funkcje
  • win32ps
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • win32ps Funkcje
  • win32service
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • win32service Funkcje
xmlrpc_set_type
.NET
Opis funkcji


.NET

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Funkcje .NET
    • dotnet_load — Wczytuje moduł DOTNET
Rozszerzenia przeznaczone dla Windows
Wstęp
Rozszerzenia przeznaczone dla Windows


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.

.NET
Instalacja/Konfiguracja
.NET


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
.NET


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Funkcje .NET
.NET


Funkcje .NET

Spis treści

  • dotnet_load — Wczytuje moduł DOTNET
Stałe predefiniowane
dotnet_load
.NET


Wczytuje moduł DOTNET

Funkcje .NET
COM
Funkcje .NET
PHP Manual

dotnet_load

(PHP 4)

dotnet_load — Wczytuje moduł DOTNET

Opis

int dotnet_load ( string $nazwa_asemblacji [, string $nazwa_typu_danych [, int $strona_kodowa ]] )
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.

Rejestr zmian

Wersja | Opis
4.1.0 | Dodano parametr strona_kodowa

Funkcje .NET
COM
Funkcje .NET


COM and .Net (Windows)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Errors and error handling
  • Przykłady
    • For Each
    • Arrays and Array-style COM properties
  • COM — The COM class
  • DOTNET — The DOTNET class
  • VARIANT — VARIANT class
  • COM Funkcje
    • com_addref — Increases the components reference counter [deprecated]
    • com_create_guid — Generate a globally unique identifier (GUID)
    • com_event_sink — Connect events from a COM object to a PHP object
    • com_get_active_object — Returns a handle to an already running instance of a COM object
    • com_get — Gets the value of a COM Component's property [deprecated]
    • com_invoke — Calls a COM component's method [deprecated]
    • com_isenum — Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
    • com_load_typelib — Loads a Typelib
    • com_load — Creates a new reference to a COM component [deprecated]
    • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
    • com_propget — Alias dla com_get
    • com_propput — Alias dla com_set
    • com_propset — Alias dla com_set
    • com_release — Decreases the components reference counter [deprecated]
    • com_set — Assigns a value to a COM component's property
    • variant_abs — Returns the absolute value of a variant
    • variant_add — "Adds" two variant values together and returns the result
    • variant_and — Performs a bitwise AND operation between two variants
    • variant_cast — Convert a variant into a new variant object of another type
    • variant_cat — concatenates two variant values together and returns the result
    • variant_cmp — Compares two variants
    • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
    • variant_div — Returns the result from dividing two variants
    • variant_eqv — Performs a bitwise equivalence on two variants
    • variant_fix — Returns the integer portion of a variant
    • variant_get_type — Returns the type of a variant object
    • variant_idiv — Converts variants to integers and then returns the result from dividing them
    • variant_imp — Performs a bitwise implication on two variants
    • variant_int — Returns the integer portion of a variant
    • variant_mod — Divides two variants and returns only the remainder
    • variant_mul — Multiplies the values of the two variants
    • variant_neg — Performs logical negation on a variant
    • variant_not — Performs bitwise not negation on a variant
    • variant_or — Performs a logical disjunction on two variants
    • variant_pow — Returns the result of performing the power function with two variants
    • variant_round — Rounds a variant to the specified number of decimal places
    • variant_set_type — Convert a variant into another type "in-place"
    • variant_set — Assigns a new value for a variant object
    • variant_sub — Subtracts the value of the right variant from the left variant value
    • variant_xor — Performs a logical exclusion on two variants
dotnet_load
Wstęp
Rozszerzenia przeznaczone dla Windows


Wstęp

COM is an acronym for Component Object Model; it is an object orientated layer (and associated services) on top of DCE RPC (an open standard) and defines a common calling convention that enables code written in any language to call and interoperate with code written in any other language (provided those languages are COM aware). Not only can the code be written in any language, but it need not even be part of the same executable; the code can be loaded from a DLL, be found in another process running on the same machine, or, with DCOM (Distributed COM), be found in another process on a remote machine, all without your code even needing to know where a component resides.

There is a subset of COM known as OLE Automation which comprises a set of COM interfaces that allow loose binding to COM objects, so that they can be introspected and called at run-time without compile-time knowledge of how the object works. The PHP COM extension utilizes the OLE Automation interfaces to allow you to create and call compatible objects from your scripts. Technically speaking, this should really be called the "OLE Automation Extension for PHP", since not all COM objects are OLE compatible.

Now, why would or should you use COM? COM is one of the main ways to glue applications and components together on the Windows platform; using COM you can launch Microsoft Word, fill in a document template and save the result as a Word document and send it to a visitor of your web site. You can also use COM to perform administrative tasks for your network and to configure your IIS; these are just the most common uses; you can do much more with COM.

Starting with PHP 5, this extension (and this documentation) was rewritten from scratch and much of the old confusing and bogus cruft has be removed. Additionally, we support the instantiation and creation of .Net assemblies using the COM interoperability layer provided by Microsoft.

Please read » this article for an overview of the changes in this extension in PHP 5.

COM
Instalacja/Konfiguracja
COM


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
COM


Wymagania

COM functions are only available for the Windows version of PHP.

.Net support requires PHP 5 and the .Net runtime.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

By używać tych funkcji, nie trzeba niczego instalować. Są one częścią jądra PHP.

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.

You are responsible for installing support for the various COM objects that you intend to use (such as MS Word); we don't and can't bundle all of those with PHP.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Com configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
com.allow_dcom | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.code_page | "" | PHP_INI_ALL | Available since PHP 5.0.0.
com.typelib_file | "" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
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.

com.allow_dcom

When this is turned on, PHP will be allowed to operate as a D-COM (Distributed COM) client and will allow the PHP script to instantiate COM objects on a remote server.

com.autoregister_typelib

When this is turned on, PHP will attempt to register constants from the typelibrary of objects that it instantiates, if those objects implement the interfaces required to obtain that information. The case sensitivity of the constants it registers is controlled by the configuration directive.

com.autoregister_verbose

When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.

com.autoregister_casesensitive

When this is turned on (the default), constants found in auto-loaded type libraries will be registered case sensitively. See com_load_typelib() for more details.

com.code_page

It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.

If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.

Informacja: This configuration directive was introduced with PHP 5.

com.typelib_file

When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines a reference to a COM component returned by deprecated com_load() (this function does not exist in PHP 5; use the COM class instead).

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

COM constants
Constant | Value | Description | Notes
CLSCTX_INPROC_SERVER (integer) | 1 | The code that creates and manages objects of this class is a DLL that runs in the same process as the caller of the function specifying the class context. |
CLSCTX_INPROC_HANDLER (integer) | 2 | The code that manages objects of this class is an in-process handler. This is a DLL that runs in the client process and implements client-side structures of this class when instances of the class are accessed remotely. |
CLSCTX_LOCAL_SERVER (integer) | 4 | The EXE code that creates and manages objects of this class runs on same machine but is loaded in a separate process space. |
CLSCTX_REMOTE_SERVER (integer) | 16 | A remote context. The code that creates and manages objects of this class is run on a different computer. |
CLSCTX_SERVER (integer) | 21 | Indicates server code, whether in-process, local, or remote. This definition ORs CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER, and CLSCTX_REMOTE_SERVER. |
CLSCTX_ALL (integer) | 23 | Indicates all class contexts. This definition ORs CLSCTX_INPROC_HANDLER and CLSCTX_SERVER. |
VT_NULL (integer) | 1 | NULL pointer reference. |
VT_EMPTY (integer) | 0 | A property with a type indicator of VT_EMPTY has no data associated with it; that is, the size of the value is zero. |
VT_UI1 (integer) | 17 | 1-byte unsigned integer. |
VT_I2 (integer) | 2 | Two bytes representing a 2-byte signed integer value. |
VT_I4 (integer) | 3 | 4-byte signed integer value. |
VT_R4 (integer) | 4 | 32-bit IEEE floating point value. |
VT_R8 (integer) | 5 | 64-bit IEEE floating point value. |
VT_BOOL (integer) | 11 | Boolean value. |
VT_ERROR (integer) | 10 | Error code; containing the status code associated with the error. |
VT_CY (integer) | 6 | 8-byte two's complement integer (scaled by 10,000). |
VT_DATE (integer) | 7 | A 64-bit floating point number representing the number of days (not seconds) since December 31, 1899. For example, January 1, 1900, is 2.0, January 2, 1900, is 3.0, and so on). This is stored in the same representation as VT_R8. |
VT_BSTR (integer) | 8 | Pointer to a null-terminated Unicode string. |
VT_DECIMAL (integer) | 14 | A decimal structure. |
VT_UNKNOWN (integer) | 13 | A pointer to an object that implements the IUnknown interface. |
VT_DISPATCH (integer) | 9 | A pointer to a pointer to an object was specified. |
VT_VARIANT (integer) | 12 | A type indicator followed by the corresponding value. VT_VARIANT can be used only with VT_BYREF. |
VT_I1 (integer) | 16 | 1-byte signed integer. |
VT_UI2 (integer) | 18 | 2-byte unsigned integer. |
VT_UI4 (integer) | 19 | 4-byte unsigned integer. |
VT_INT (integer) | 22 | 4-byte signed integer value (equivalent to VT_I4). |
VT_UINT (integer) | 23 | 4-byte unsigned integer (equivalent to VT_UI4). |
VT_ARRAY (integer) | 8192 | If the type indicator is combined with VT_ARRAY by an OR operator, the value is a pointer to a SAFEARRAY. VT_ARRAY can use the OR with the following data types: VT_I1, VT_UI1, VT_I2, VT_UI2, VT_I4, VT_UI4, VT_INT, VT_UINT, VT_R4, VT_R8, VT_BOOL, VT_DECIMAL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DISPATCH, VT_UNKNOWN and VT_VARIANT. |
VT_BYREF (integer) | 16384 | If the type indicator is combined with VT_BYREF by an OR operator, the value is a reference. Reference types are interpreted as a reference to data, similar to the reference type in C++. |
CP_ACP (integer) | 0 | Default to ANSI code page. |
CP_MACCP (integer) | 2 | Macintosh code page. |
CP_OEMCP (integer) | 1 | Default to OEM code page. |
CP_UTF7 (integer) | 65000 | Unicode (UTF-7). |
CP_UTF8 (integer) | 65001 | Unicode (UTF-8). |
CP_SYMBOL (integer) | 42 | SYMBOL translations. |
CP_THREAD_ACP (integer) | 3 | Current thread's ANSI code page |
VARCMP_LT (integer) | 0 | The left bstr is less than right bstr. |
VARCMP_EQ (integer) | 1 | The two parameters are equal. |
VARCMP_GT (integer) | 2 | The left bstr is greater than right bstr. |
VARCMP_NULL (integer) | 3 | Either expression is NULL. |
NORM_IGNORECASE (integer) | 1 | Ignore case sensitivity. |
NORM_IGNORENONSPACE (integer) | 2 | Ignore nonspacing characters. |
NORM_IGNORESYMBOLS (integer) | 4 | Ignore symbols. |
NORM_IGNOREWIDTH (integer) | 131072 | Ignore string width. |
NORM_IGNOREKANATYPE (integer) | 65536 | Ignore Kana type. |
NORM_IGNOREKASHIDA (integer) | 262144 | Ignore Arabic kashida characters. | Availability is dependent upon under lying library.
DISP_E_DIVBYZERO (integer) | -2147352558 | A return error that indicates a divide by zero error. |
DISP_E_OVERFLOW (integer) | -2147352566 | An error that indicates that a value could not be coerced to its expected representation. |
MK_E_UNAVAILABLE (integer) | -2147221021 | iMoniker COM status code, return on errors where the function call failed due to unavailability. |
Typy zasobów
Errors and error handling
COM


Errors and error handling

Exceptions (PHP 5)

This extension will throw instances of the class com_exception whenever there is a potentially fatal error reported by COM. All COM exceptions have a well-defined code property that corresponds to the HRESULT return value from the various COM operations. You may use this code to make programmatic decisions on how to handle the exception.

Stałe predefiniowane
Przykłady
COM


Przykłady

Spis treści

  • For Each
  • Arrays and Array-style COM properties
Errors and error handling
For Each
COM


For Each

Starting with PHP 5, you may use PHP's own foreach statement to iterate over the contents of a standard COM/OLE IEnumVariant. In layman's terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.

Przykład #1 For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Przykład #2 while() ... Next() in PHP 4

<?php
$domainObject = new COM("WinNT://Domain");
while ($obj = $domainObject->Next()) {
   echo $obj->Name . "<br />";
}
?>

Przykład #3 foreach in PHP 5

<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
   echo $obj->Name . "<br />";
}
?>

Przykłady
Arrays and Array-style COM properties
Przykłady


Arrays and Array-style COM properties

Many COM objects expose their properties as arrays, or using array-style access. In PHP 4, you may use PHP array syntax to read/write such a property, but only a single dimension is allowed. If you want to read a multi-dimensional property, you could instead make the property access into a function call, with each parameter representing each dimension of the array access, but there is no way to write to such a property.

PHP 5 introduces the following new features to make your life easier:

  • Access multi-dimensional arrays, or COM properties that require multiple parameters using PHP array syntax. You can also write or set properties using this technique.

  • Iterate SafeArrays ("true" arrays) using the foreach control structure. This works because SafeArrays include information about their size. If an array-style property implements IEnumVariant then you can also use foreach for that property too; take a look at For Each for more information on this topic.

For Each
COM
Przykłady


The COM class

(PHP 4 >= 4.1.0, PHP 5)

Description

The COM class allows you to instantiate an OLE compatible COM object and call its methods and access its properties.

$obj = new COM("Application.ID")

Methods

COM::COM ( string $module_name [, mixed $server_name [, int $codepage [, string $typelib ]]] )

COM class constructor. The parameters have the following meanings:

module_name
Can be a ProgID, Class ID or Moniker that names the component to load. A ProgID is typically the application or DLL name, followed by a period, followed by the object name. e.g: Word.Application. A Class ID is the UUID that uniquely identifies a given class. A Moniker is a special form of naming, similar in concept to a URL scheme, that identifies a resource and specifies how it should be loaded. As an example, you could load up Word and get an object representing a word document by specifying the full path to the word document as the module name, or you can use LDAP: as a moniker to use the ADSI interface to LDAP.
server_name
The name of the DCOM server on which the component should be loaded and run. If NULL, the object is run using the default for the application. The default is typically to run it on the local machine, although the administrator might have configured the application to launch on a different machine. If you specify a non-NULL value for server, PHP will refuse to load the object unless the configuration option is set to TRUE.

If server_name is an array, it should contain the following elements (case sensitive!). Note that they are all optional (although you need to specify both Username and Password together); if you omit the Server setting, the default server will be used (as mentioned above), and the instantiation of the object will not be affected by the directive.

DCOM server name
server_name key | type | description
Server | string | The name of the server.
Username | string | The username to connect as.
Password | string | The password for Username.
Flags | integer | One or more of the following constants, logically OR'd together: CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER and CLSCTX_ALL. The default value if not specified here is CLSCTX_SERVER if you also omit Server, or CLSCTX_REMOTE_SERVER if you do specify a server. You should consult the Microsoft documentation for CoCreateInstance for more information on the meaning of these constants; you will typically never have to use them.

codepage
Specifies the codepage that is used to convert strings to unicode-strings and vice versa. The conversion is applied whenever a PHP string is passed as a parameter or returned from a method of this COM object. The code page is sticky in PHP 5, which means that it will propagate to objects and variants returned from the object. Possible values are CP_ACP (use system default ANSI code page - the default if this parameter is omitted), CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP (use codepage/locale set for the current executing thread), CP_UTF7 and CP_UTF8. You may also use the number for a given codepage; consult the Microsoft documentation for more details on codepages and their numeric values.

Overloaded Methods

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM.

Starting with PHP 5, PHP will automatically detect methods that accept parameters by reference, and will automatically convert regular PHP variables to a form that can be passed by reference. This means that you can call the method very naturally; you needn't go to any extra effort in your code.

In PHP 4, to pass parameters by reference you need to create an instance of the VARIANT class to wrap the byref parameters.

Pseudo Methods

In PHP versions prior to 5, a number of not very pleasant hacks meant that the following method names were not passed through to COM and were handled directly by PHP. PHP 5 eliminates these things; read the details below to determine how to fix your scripts. These magic method names are case insensitive.

void COM::AddRef ( void )

Artificially adds a reference count to the COM object.

Ostrzeżenie

You should never need to use this method. It exists as a logical complement to the Release() method below.

void COM::Release ( void )

Artificially removes a reference count from the COM object.

Ostrzeżenie

You should never need to use this method. Its existence in PHP is a bug designed to work around a bug that keeps COM objects running longer than they should.

Pseudo Methods for Iterating

These pseudo methods are only available if com_isenum() returns TRUE, in which case, they hide any methods with the same names that might otherwise be provided by the COM object. These methods have all been eliminated in PHP 5, and you should use For Each instead.

variant COM::All ( void )

Returns a variant representing a SafeArray that has 10 elements; each element will be an empty/null variant. This function was supposed to return an array containing all the elements from the iterator, but was never completed. Do not use.

variant COM::Next ( void )

Returns a variant representing the next element available from the iterator, or FALSE when there are no more elements.

variant COM::Prev ( void )

Returns a variant representing the previous element available from the iterator, or FALSE when there are no more elements.

void COM::Reset ( void )

Rewinds the iterator back to the start.

COM examples

Przykład #1 COM example (1)

<?php
// starting word
$word = new COM("word.application") or die("Unable to instantiate Word");
echo "Loaded Word, version {$word->Version}\n";

//bring it to front
$word->Visible = 1;

//open an empty document
$word->Documents->Add();

//do some weird stuff
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

//closing word
$word->Quit();

//free the object
$word = null;
?>

Przykład #2 COM example (2)

<?php

$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // Recordset

$num_columns = $rs->Fields->Count();
echo $num_columns . "\n";

for ($i=0; $i < $num_columns; $i++) {
    $fld[$i] = $rs->Fields($i);
}

$rowcount = 0;
while (!$rs->EOF) {
    for ($i=0; $i < $num_columns; $i++) {
        echo $fld[$i]->value . "\t";
    }
    echo "\n";
    $rowcount++;            // increments rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs = null;
$conn = null;

?>

Arrays and Array-style COM properties
DOTNET
COM


The DOTNET class

(PHP 4 >= 4.1.0, PHP 5)

Description

The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.

$obj = new DOTNET("assembly", "classname")

Methods

DOTNET::DOTNET ( string $assembly_name , string $class_name [, int $codepage ] )

DOTNET class constructor. assembly_name specifies which assembly should be loaded, and class_name specifices which class in that assembly to instantiate. You may optionally specify a codepage to use for unicode string transformations; see the COM class for more details on code pages.

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.

Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.

Przykład #1 DOTNET example

<?php
 $stack = new DOTNET("mscorlib", "System.Collections.Stack");
 $stack->Push(".Net");
 $stack->Push("Hello ");
 echo $stack->Pop() . $stack->Pop();
?>

Informacja:

You need to install the .Net runtime on your web server to take advantage of this feature.

COM
VARIANT
COM


VARIANT class

(PHP 4 >= 4.1.0, PHP 5)

Description

The VARIANT is COM's equivalent of the PHP zval; it is a structure that can contain a value with a range of different possible types. The VARIANT class provided by the COM extension allows you to have more control over the way that PHP passes values to and from COM.

$vVar = new VARIANT($var)

Methods

VARIANT::VARIANT ([ mixed $value [, int $type [, int $codepage ]]] )

VARIANT class constructor. Parameters:

value
initial value. if omitted, or set to NULL an VT_EMPTY object is created.
type
specifies the content type of the VARIANT object. Possible values are one of the VT_XXX Stałe predefiniowane. In PHP versions prior to PHP 5, you could force PHP to pass a variant object by reference by OR'ing VT_BYREF with the type. In PHP 5, this hack is not supported; instead, PHP 5 can detect parameters passed by reference automatically; they do not even need to be passed as VARIANT objects. Consult the MSDN library for additional information on the VARIANT type.
codepage
specifies the codepage that is used to convert strings to unicode. See the parameter of the same name in the COM class for more information.

PHP versions prior to PHP 5 define a number of (undocumented) virtual properties for instances of the VARIANT class; these properties have all been removed in PHP 5 in favour of its more natural syntax; these differences are best highlighted by example:

Przykład #1 Variant example, PHP 4.x style

<?php
$v = new VARIANT(42);
print "The type is " . $v->type . "<br/>";
print "The value is " . $v->value . "<br/>";
?>

Przykład #2 Variant example, PHP 5 style

<?php
$v = new VARIANT(42);
print "The type is " . variant_get_type($v) . "<br/>";
print "The value is " . $v . "<br/>";
?>

The reason for the change is that, internally, the COM extension sees VARIANT, COM and DOTNET classes as the same thing, and the design philosophy for these classes is that all property and member accesses are passed through to COM with no interference. The new syntax is more natural and less effort, and most of the removed virtual properties didn't make any sense in a PHP context in any case.

Informacja:

PHP 5 takes a much simpler approach to handling VARIANTs; when returning a value or fetching a variant property, the variant is converted to a PHP value only when there is a direct mapping between the types that would not result in a loss of information. In all other cases, the result is returned as an instance of the VARIANT class. You can force PHP to convert or evaluate the variant as a PHP native type by using a casting operator explicitly, or implicitly casting to a string by print()ing it. You may use the wide range of variant functions to perform arithmetic operations on variants without forcing a conversion or risking a loss of data.

See also variant_get_type().

DOTNET
COM Funkcje
COM


COM Funkcje

Zobacz też:

For further information on COM read the » COM specification or perhaps take a look at Don Box's » Yet Another COM Library (YACL). You might find some additional useful information in our FAQ for PHP and COM. If you're thinking of using MS Office applications on the server side, you should read the information here: » Considerations for Server-Side Automation of Office.

Spis treści

  • com_addref — Increases the components reference counter [deprecated]
  • com_create_guid — Generate a globally unique identifier (GUID)
  • com_event_sink — Connect events from a COM object to a PHP object
  • com_get_active_object — Returns a handle to an already running instance of a COM object
  • com_get — Gets the value of a COM Component's property [deprecated]
  • com_invoke — Calls a COM component's method [deprecated]
  • com_isenum — Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
  • com_load_typelib — Loads a Typelib
  • com_load — Creates a new reference to a COM component [deprecated]
  • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
  • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
  • com_propget — Alias dla com_get
  • com_propput — Alias dla com_set
  • com_propset — Alias dla com_set
  • com_release — Decreases the components reference counter [deprecated]
  • com_set — Assigns a value to a COM component's property
  • variant_abs — Returns the absolute value of a variant
  • variant_add — "Adds" two variant values together and returns the result
  • variant_and — Performs a bitwise AND operation between two variants
  • variant_cast — Convert a variant into a new variant object of another type
  • variant_cat — concatenates two variant values together and returns the result
  • variant_cmp — Compares two variants
  • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
  • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
  • variant_div — Returns the result from dividing two variants
  • variant_eqv — Performs a bitwise equivalence on two variants
  • variant_fix — Returns the integer portion of a variant
  • variant_get_type — Returns the type of a variant object
  • variant_idiv — Converts variants to integers and then returns the result from dividing them
  • variant_imp — Performs a bitwise implication on two variants
  • variant_int — Returns the integer portion of a variant
  • variant_mod — Divides two variants and returns only the remainder
  • variant_mul — Multiplies the values of the two variants
  • variant_neg — Performs logical negation on a variant
  • variant_not — Performs bitwise not negation on a variant
  • variant_or — Performs a logical disjunction on two variants
  • variant_pow — Returns the result of performing the power function with two variants
  • variant_round — Rounds a variant to the specified number of decimal places
  • variant_set_type — Convert a variant into another type "in-place"
  • variant_set — Assigns a new value for a variant object
  • variant_sub — Subtracts the value of the right variant from the left variant value
  • variant_xor — Performs a logical exclusion on two variants
VARIANT
com_addref
COM


Increases the components reference counter [deprecated]

COM Funkcje
com_create_guid
COM Funkcje
PHP Manual

com_addref

(PHP 4 >= 4.1.0)

com_addref — Increases the components reference counter [deprecated]

Opis

void com_addref ( void )

Increases the components reference counter.

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Ostrzeżenie

You should never need to use this function.

COM Funkcje
com_create_guid
COM Funkcje


Generate a globally unique identifier (GUID)

com_addref
com_event_sink
COM Funkcje
PHP Manual

com_create_guid

(PHP 5)

com_create_guid — Generate a globally unique identifier (GUID)

Opis

string com_create_guid ( void )

Generates a Globally Unique Identifier (GUID).

A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.

Zwracane wartości

Returns the GUID as a string.

Zobacz też:

  • uuid_create() in the PECL uuid extension

com_addref
com_event_sink
COM Funkcje


Connect events from a COM object to a PHP object

com_create_guid
com_get_active_object
COM Funkcje
PHP Manual

com_event_sink

(PHP 4 >= 4.2.0, PHP 5)

com_event_sink — Connect events from a COM object to a PHP object

Opis

bool com_event_sink ( variant $comobject , object $sinkobject [, mixed $sinkinterface ] )

Instructs COM to sink events generated by comobject into the PHP object sinkobject.

Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.

Parametry

comobject

sinkobject

sinkobject should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.

sinkinterface

PHP will attempt to use the default dispinterface type specified by the typelibrary associated with comobject, but you may override this choice by setting sinkinterface to the name of the dispinterface that you want to use.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 COM event sink example

<?php
class IEEventSinker {
    var $terminated = false;

   function ProgressChange($progress, $progressmax) {
      echo "Download progress: $progress / $progressmax\n";
    }

    function DocumentComplete(&$dom, $url) {
      echo "Document $url complete\n";
    }

    function OnQuit() {
      echo "Quit!\n";
      $this->terminated = true;
    }
}
$ie = new COM("InternetExplorer.Application");
// note that you don't need the & for PHP 5!
$sink = new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.example.org");
while(!$sink->terminated) {
  com_message_pump(4000);
}
$ie = null;
?>

Zobacz też:

  • com_print_typeinfo() - Print out a PHP class definition for a dispatchable interface
  • com_message_pump() - Process COM messages, sleeping for up to timeoutms milliseconds

com_create_guid
com_get_active_object
COM Funkcje


Returns a handle to an already running instance of a COM object

com_event_sink
com_get
COM Funkcje
PHP Manual

com_get_active_object

(PHP 5)

com_get_active_object — Returns a handle to an already running instance of a COM object

Opis

variant com_get_active_object ( string $progid [, int $code_page ] )

com_get_active_object() is similar to creating a new instance of a COM object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the Running Object Table to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.

Parametry

progid

progid must be either the ProgID or CLSID for the object that you want to access (for example Word.Application).

code_page

Acts in precisely the same way that it does for the COM class.

Zwracane wartości

If the requested object is running, it will be returned to your script just like any other COM object.

Błędy/Wyjątki

There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.

Notatki

Ostrzeżenie

Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read » Considerations for Server-Side Automation of Office for more information on the general issues involved.

com_event_sink
com_get
COM Funkcje


Gets the value of a COM Component's property [deprecated]

com_get_active_object
com_invoke
COM Funkcje
PHP Manual

com_get

(PHP 4)

com_get — Gets the value of a COM Component's property [deprecated]

Opis

Deprecated, use the OO syntax instead.

Przykład #1 OO syntax

<?php
// do this
$var = $obj->property;
// instead of this:
$var = com_get($obj, 'property');
?>

Notatki

Informacja: Ta funkcja nie istnieje w PHP 5; zamiast niej użyj składni obiektowej aby uzyskać dostęp do właściwości, lub aby wywołać metody.

com_get_active_object
com_invoke
COM Funkcje


Calls a COM component's method [deprecated]

com_get
com_isenum
COM Funkcje
PHP Manual

com_invoke

(PHP 4)

com_invoke — Calls a COM component's method [deprecated]

Description

mixed com_invoke ( resource $com_object , string $function_name [, mixed $function_parameters ] )

com_invoke() invokes the method named function_name of the COM component referenced by com_object. com_invoke() returns FALSE on error, returns the function_name's return value on success. All the extra parameters function_parameters are passed to the method function_name.

Przykład #1 Don't use com_invoke(), use OO syntax instead

<?php
// do this
$val = $obj->method($one, $two);
// instead of this:
$val = com_invoke($obj, 'method', $one, $two);
?>

Informacja: Ta funkcja nie istnieje w PHP 5; zamiast niej użyj składni obiektowej aby uzyskać dostęp do właściwości, lub aby wywołać metody.

com_get
com_isenum
COM Funkcje


Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]

com_invoke
com_load_typelib
COM Funkcje
PHP Manual

com_isenum

(PHP 4 >= 4.1.0)

com_isenum — Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]

Opis

bool com_isenum ( variant $com_module )

Checks to see if a COM object can be enumerated using the Next() method hack. See COM class for more details on these methods.

Parametry

com_module

The COM object.

Zwracane wartości

Returns TRUE if the object can be enumerated, FALSE otherwise.

Notatki

Informacja:

This function does not exist in PHP 5; use the more natural foreach statement to iterate over the contents of COM objects. See For Each for more details.

com_invoke
com_load_typelib
COM Funkcje


Loads a Typelib

com_isenum
com_load
COM Funkcje
PHP Manual

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5)

com_load_typelib — Loads a Typelib

Opis

bool com_load_typelib ( string $typelib_name [, bool $case_insensitive = true ] )

Loads a type-library and registers its constants in the engine, as though they were defined using define().

Note that it is much more efficient to use the configuration setting to pre-load and register the constants, although not so flexible.

If you have turned on , then PHP will attempt to automatically register the constants associated with a COM object when you instantiate it. This depends on the interfaces provided by the COM object itself, and may not always be possible.

Parametry

typelib_name

typelib_name can be one of the following:

  • The filename of a .tlb file or the executable module that contains the type library.

  • The type library GUID, followed by its version number, for example {00000200-0000-0010-8000-00AA006D2EA4},2,0.

  • The type library name, e.g. Microsoft OLE DB ActiveX Data Objects 1.0 Library.

PHP will attempt to resolve the type library in this order, as the process gets more and more expensive as you progress down the list; searching for the type library by name is handled by physically enumerating the registry until we find a match.

case_insensitive

The case_insensitive behaves in the same way as the parameter with the same name in the define() function.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

com_isenum
com_load
COM Funkcje


Creates a new reference to a COM component [deprecated]

com_load_typelib
com_message_pump
COM Funkcje
PHP Manual

com_load

(PHP 4)

com_load — Creates a new reference to a COM component [deprecated]

Opis

Deprecated, use the OO syntax instead.

Przykład #1 OO syntax

<?php
// do this
$obj = new COM($module);
// instead of this:
$obj = com_load($module);
?>

Notatki

Informacja: Ta funkcja nie istnieje w PHP 5; zamiast niej użyj składni obiektowej aby uzyskać dostęp do właściwości, lub aby wywołać metody.

com_load_typelib
com_message_pump
COM Funkcje


Process COM messages, sleeping for up to timeoutms milliseconds

com_load
com_print_typeinfo
COM Funkcje
PHP Manual

com_message_pump

(PHP 4 >= 4.2.0, PHP 5)

com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds

Opis

bool com_message_pump ([ int $timeoutms = 0 ] )

This function will sleep for up to timeoutms milliseconds, or until a message arrives in the queue.

The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.

Parametry

timeoutms

The timeout, in milliseconds.

If you do not specify a value for timeoutms, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return FALSE immediately without sleeping.

Zwracane wartości

If a message or messages arrives before the timeout, they will be dispatched, and the function will return TRUE. If the timeout occurs and no messages were processed, the return value will be FALSE.

com_load
com_print_typeinfo
COM Funkcje


Print out a PHP class definition for a dispatchable interface

com_message_pump
com_propget
COM Funkcje
PHP Manual

com_print_typeinfo

(PHP 4 >= 4.2.0, PHP 5)

com_print_typeinfo — Print out a PHP class definition for a dispatchable interface

Opis

bool com_print_typeinfo ( object $comobject [, string $dispinterface [, bool $wantsink = false ]] )

The purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.

Parametry

comobject

comobject should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()).

dispinterface

The name of an IDispatch descendant interface that you want to display.

wantsink

If set to TRUE, the corresponding sink interface will be displayed instead.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • com_event_sink() - Connect events from a COM object to a PHP object
  • com_load_typelib() - Loads a Typelib

com_message_pump
com_propget
COM Funkcje


Alias dla com_get

com_print_typeinfo
com_propput
COM Funkcje
PHP Manual

com_propget

(PHP 4)

com_propget — Alias dla com_get()

Opis

Ta funkcja jest aliasem dla: com_get().

Informacja: Ta funkcja nie istnieje w PHP 5; zamiast niej użyj składni obiektowej aby uzyskać dostęp do właściwości, lub aby wywołać metody.

com_print_typeinfo
com_propput
COM Funkcje


Alias dla com_set

com_propget
com_propset
COM Funkcje
PHP Manual

com_propput

(PHP 4)

com_propput — Alias dla com_set()

Opis

Ta funkcja jest aliasem dla: com_set().

Informacja: Ta funkcja nie istnieje w PHP 5; zamiast niej użyj składni obiektowej aby uzyskać dostęp do właściwości, lub aby wywołać metody.

com_propget
com_propset
COM Funkcje


Alias dla com_set

com_propput
com_release
COM Funkcje
PHP Manual

com_propset

(PHP 4)

com_propset — Alias dla com_set()

Opis

Ta funkcja jest aliasem dla: com_set().

Informacja: Ta funkcja nie istnieje w PHP 5; zamiast niej użyj składni obiektowej aby uzyskać dostęp do właściwości, lub aby wywołać metody.

com_propput
com_release
COM Funkcje


Decreases the components reference counter [deprecated]

com_propset
com_set
COM Funkcje
PHP Manual

com_release

(PHP 4 >= 4.1.0)

com_release — Decreases the components reference counter [deprecated]

Opis

void com_release ( void )

Decreases the components reference counter.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
5.0.0 | This function was removed.

Notatki

Ostrzeżenie

You should never need to use this function.

com_propset
com_set
COM Funkcje


Assigns a value to a COM component's property

com_release
variant_abs
COM Funkcje
PHP Manual

com_set

(PHP 4)

com_set — Assigns a value to a COM component's property

Opis

Deprecated, use the OO syntax instead.

Przykład #1 OO syntax

<?php
// do this
$obj->property = $value;
// instead of this:
com_set($obj, 'property', $value);
?>

Notatki

Informacja: Ta funkcja nie istnieje w PHP 5; zamiast niej użyj składni obiektowej aby uzyskać dostęp do właściwości, lub aby wywołać metody.

com_release
variant_abs
COM Funkcje


Returns the absolute value of a variant

com_set
variant_add
COM Funkcje
PHP Manual

variant_abs

(PHP 5)

variant_abs — Returns the absolute value of a variant

Opis

mixed variant_abs ( mixed $val )

Returns the absolute value of a variant.

Parametry

val

The variant.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns the absolute value of val.

Zobacz też:

  • abs() - Wartość bezwględna (moduł z liczby)

com_set
variant_add
COM Funkcje


"Adds" two variant values together and returns the result

variant_abs
variant_and
COM Funkcje
PHP Manual

variant_add

(PHP 5)

variant_add — "Adds" two variant values together and returns the result

Opis

mixed variant_add ( mixed $left , mixed $right )

Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:

Variant Addition Rules
If | Then
Both expressions are of the string type | Concatenation
One expression is a string type and the other a character | Addition
One expression is numeric and the other is a string | Addition
Both expressions are numeric | Addition
Either expression is NULL | NULL is returned
Both expressions are empty | Integer subtype is returned

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns the result.

Zobacz też:

  • variant_sub() - Subtracts the value of the right variant from the left variant value

variant_abs
variant_and
COM Funkcje


Performs a bitwise AND operation between two variants

variant_add
variant_cast
COM Funkcje
PHP Manual

variant_and

(PHP 5)

variant_and — Performs a bitwise AND operation between two variants

Opis

mixed variant_and ( mixed $left , mixed $right )

Performs a bitwise AND operation. Note that this is slightly different from a regular AND operation.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Variant AND Rules
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | FALSE
TRUE | NULL | NULL
FALSE | TRUE | FALSE
FALSE | FALSE | FALSE
FALSE | NULL | FALSE
NULL | TRUE | NULL
NULL | FALSE | FALSE
NULL | NULL | NULL

Zobacz też:

  • variant_or() - Performs a logical disjunction on two variants

variant_add
variant_cast
COM Funkcje


Convert a variant into a new variant object of another type

variant_and
variant_cat
COM Funkcje
PHP Manual

variant_cast

(PHP 5)

variant_cast — Convert a variant into a new variant object of another type

Opis

variant variant_cast ( variant $variant , int $type )

This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type.

This function wraps VariantChangeType() in the COM library; consult MSDN for more information.

Parametry

variant

The variant.

type

type should be one of the VT_XXX constants.

Zwracane wartości

Returns a VT_DATE variant.

Zobacz też:

  • variant_set_type() - Convert a variant into another type "in-place"

variant_and
variant_cat
COM Funkcje


concatenates two variant values together and returns the result

variant_cast
variant_cmp
COM Funkcje
PHP Manual

variant_cat

(PHP 5)

variant_cat — concatenates two variant values together and returns the result

Opis

mixed variant_cat ( mixed $left , mixed $right )

Concatenates left with right and returns the result.

This function is notionally equivalent to $left . $right.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns the result of the concatenation.

Zobacz też:

  • String Operators for the string concatenation operator

variant_cast
variant_cmp
COM Funkcje


Compares two variants

variant_cat
variant_date_from_timestamp
COM Funkcje
PHP Manual

variant_cmp

(PHP 5)

variant_cmp — Compares two variants

Opis

int variant_cmp ( mixed $left , mixed $right [, int $lcid [, int $flags ]] )

Compares left with right.

This function will only compare scalar values, not arrays or variant records.

Parametry

left

The left operand.

right

The right operand.

lcid

A valid Locale Identifier to use when comparing strings (this affects string collation).

flags

flags can be one or more of the following values OR'd together, and affects string comparisons:

Variant Comparision Flags
value | meaning
NORM_IGNORECASE | Compare case insensitively
NORM_IGNORENONSPACE | Ignore nonspacing characters
NORM_IGNORESYMBOLS | Ignore symbols
NORM_IGNOREWIDTH | Ignore string width
NORM_IGNOREKANATYPE | Ignore Kana type
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns one of the following:

Variant Comparision Results
value | meaning
VARCMP_LT | left is less than right
VARCMP_EQ | left is equal to right
VARCMP_GT | left is greater than right
VARCMP_NULL | Either left, right or both are NULL

variant_cat
variant_date_from_timestamp
COM Funkcje


Returns a variant date representation of a Unix timestamp

variant_cmp
variant_date_to_timestamp
COM Funkcje
PHP Manual

variant_date_from_timestamp

(PHP 5)

variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp

Opis

variant variant_date_from_timestamp ( int $timestamp )

Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.

Parametry

timestamp

A unix timestamp.

Zwracane wartości

Returns a VT_DATE variant.

Zobacz też:

  • variant_date_to_timestamp() - Converts a variant date/time value to Unix timestamp
  • mktime() - Oblicza uniksowy znacznik czasu dla podanej daty
  • time() - Zwraca aktualny uniksowy znacznik czasu

variant_cmp
variant_date_to_timestamp
COM Funkcje


Converts a variant date/time value to Unix timestamp

variant_date_from_timestamp
variant_div
COM Funkcje
PHP Manual

variant_date_to_timestamp

(PHP 5)

variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp

Opis

int variant_date_to_timestamp ( variant $variant )

Converts variant from a VT_DATE (or similar) value into a Unix timestamp. This allows easier interopability between the Unix-ish parts of PHP and COM.

Parametry

variant

The variant.

Zwracane wartości

Returns a unix timestamp.

Zobacz też:

  • variant_date_from_timestamp() - Returns a variant date representation of a Unix timestamp
  • date() - Formatuje lokalny czas/datę
  • strftime() - Formatuje lokalną datę/czas zgodnie z lokalizacją

variant_date_from_timestamp
variant_div
COM Funkcje


Returns the result from dividing two variants

variant_date_to_timestamp
variant_eqv
COM Funkcje
PHP Manual

variant_div

(PHP 5)

variant_div — Returns the result from dividing two variants

Opis

mixed variant_div ( mixed $left , mixed $right )

Divides left by right and returns the result.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Variant Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Double is returned
One expression is a string type and the other a character | Division and a double is returned
One expression is numeric and the other is a string | Division and a double is returned.
Both expressions are numeric | Division and a double is returned
Either expression is NULL | NULL is returned
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty. | 0 as type double is returned
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown

Zobacz też:

  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

variant_date_to_timestamp
variant_eqv
COM Funkcje


Performs a bitwise equivalence on two variants

variant_div
variant_fix
COM Funkcje
PHP Manual

variant_eqv

(PHP 5)

variant_eqv — Performs a bitwise equivalence on two variants

Opis

mixed variant_eqv ( mixed $left , mixed $right )

Performs a bitwise equivalence on two variants.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

If each bit in left is equal to the corresponding bit in right then TRUE is returned, otherwise FALSE is returned.

variant_div
variant_fix
COM Funkcje


Returns the integer portion of a variant

variant_eqv
variant_get_type
COM Funkcje
PHP Manual

variant_fix

(PHP 5)

variant_fix — Returns the integer portion of a variant

Opis

mixed variant_fix ( mixed $variant )

Gets the integer portion of a variant.

Parametry

variant

The variant.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

Notatki

Ostrzeżenie

This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation.

Zobacz też:

  • variant_int() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Zaokrągla ułamki w dół
  • ceil() - Zaokrągla ułamki w górę
  • round() - Zaokrągla liczbę zmiennoprzecinkową

variant_eqv
variant_get_type
COM Funkcje


Returns the type of a variant object

variant_fix
variant_idiv
COM Funkcje
PHP Manual

variant_get_type

(PHP 5)

variant_get_type — Returns the type of a variant object

Opis

int variant_get_type ( variant $variant )

Returns the type of a variant object.

Parametry

variant

The variant object.

Zwracane wartości

This function returns an integer value that indicates the type of variant, which can be an instance of COM, DOTNET or VARIANT classes. The return value can be compared to one of the VT_XXX constants.

The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.

In PHP versions prior to 5, you could obtain this information from instances of the VARIANT class ONLY, by reading a fake type property. See the VARIANT class for more information on this.

variant_fix
variant_idiv
COM Funkcje


Converts variants to integers and then returns the result from dividing them

variant_get_type
variant_imp
COM Funkcje
PHP Manual

variant_idiv

(PHP 5)

variant_idiv — Converts variants to integers and then returns the result from dividing them

Opis

mixed variant_idiv ( mixed $left , mixed $right )

Converts left and right to integer values, and then performs integer division.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Variant Integer Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Division and integer is returned
One expression is a string type and the other a character | Division
One expression is numeric and the other is a string | Division
Both expressions are numeric | Division
Either expression is NULL | NULL is returned
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown

Zobacz też:

  • variant_div() - Returns the result from dividing two variants

variant_get_type
variant_imp
COM Funkcje


Performs a bitwise implication on two variants

variant_idiv
variant_int
COM Funkcje
PHP Manual

variant_imp

(PHP 5)

variant_imp — Performs a bitwise implication on two variants

Opis

mixed variant_imp ( mixed $left , mixed $right )

Performs a bitwise implication operation.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Variant Implication Table
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | TRUE
TRUE | NULL | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | TRUE
FALSE | NULL | TRUE
NULL | TRUE | TRUE
NULL | FALSE | NULL
NULL | NULL | NULL

variant_idiv
variant_int
COM Funkcje


Returns the integer portion of a variant

variant_imp
variant_mod
COM Funkcje
PHP Manual

variant_int

(PHP 5)

variant_int — Returns the integer portion of a variant

Opis

mixed variant_int ( mixed $variant )

Gets the integer portion of a variant.

Parametry

variant

The variant.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

Zobacz też:

  • variant_fix() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Zaokrągla ułamki w dół
  • ceil() - Zaokrągla ułamki w górę
  • round() - Zaokrągla liczbę zmiennoprzecinkową

variant_imp
variant_mod
COM Funkcje


Divides two variants and returns only the remainder

variant_int
variant_mul
COM Funkcje
PHP Manual

variant_mod

(PHP 5)

variant_mod — Divides two variants and returns only the remainder

Opis

mixed variant_mod ( mixed $left , mixed $right )

Divides left by right and returns the remainder.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns the remainder of the division.

Zobacz też:

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

variant_int
variant_mul
COM Funkcje


Multiplies the values of the two variants

variant_mod
variant_neg
COM Funkcje
PHP Manual

variant_mul

(PHP 5)

variant_mul — Multiplies the values of the two variants

Opis

mixed variant_mul ( mixed $left , mixed $right )

Multiplies left by right.

Parametry

left

The left operand.

right

The right operand.

Boolean values are converted to -1 for FALSE and 0 for TRUE.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Variant Multiplication Rules
If | Then
Both expressions are of the string, date, character, boolean type | Multiplication
One expression is a string type and the other a character | Multiplication
One expression is numeric and the other is a string | Multiplication
Both expressions are numeric | Multiplication
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Zobacz też:

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

variant_mod
variant_neg
COM Funkcje


Performs logical negation on a variant

variant_mul
variant_not
COM Funkcje
PHP Manual

variant_neg

(PHP 5)

variant_neg — Performs logical negation on a variant

Opis

mixed variant_neg ( mixed $variant )

Performs logical negation of variant.

Parametry

variant

The variant.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns the result of the logical negation.

variant_mul
variant_not
COM Funkcje


Performs bitwise not negation on a variant

variant_neg
variant_or
COM Funkcje
PHP Manual

variant_not

(PHP 5)

variant_not — Performs bitwise not negation on a variant

Opis

mixed variant_not ( mixed $variant )

Performs bitwise not negation on variant and returns the result.

Parametry

variant

The variant.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns the bitwise not negation. If variant is NULL, the result will also be NULL.

variant_neg
variant_or
COM Funkcje


Performs a logical disjunction on two variants

variant_not
variant_pow
COM Funkcje
PHP Manual

variant_or

(PHP 5)

variant_or — Performs a logical disjunction on two variants

Opis

mixed variant_or ( mixed $left , mixed $right )

Performs a bitwise OR operation. Note that this is slightly different from a regular OR operation.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Variant OR Rules
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | TRUE
TRUE | NULL | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | FALSE
FALSE | NULL | NULL
NULL | TRUE | TRUE
NULL | FALSE | NULL
NULL | NULL | NULL

Zobacz też:

  • variant_and() - Performs a bitwise AND operation between two variants
  • variant_xor() - Performs a logical exclusion on two variants

variant_not
variant_pow
COM Funkcje


Returns the result of performing the power function with two variants

variant_or
variant_round
COM Funkcje
PHP Manual

variant_pow

(PHP 5)

variant_pow — Returns the result of performing the power function with two variants

Opis

mixed variant_pow ( mixed $left , mixed $right )

Returns the result of left to the power of right.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns the result of left to the power of right.

Zobacz też:

  • pow() - Potęgowanie

variant_or
variant_round
COM Funkcje


Rounds a variant to the specified number of decimal places

variant_pow
variant_set_type
COM Funkcje
PHP Manual

variant_round

(PHP 5)

variant_round — Rounds a variant to the specified number of decimal places

Opis

mixed variant_round ( mixed $variant , int $decimals )

Returns the value of variant rounded to decimals decimal places.

Parametry

variant

The variant.

decimals

Number of decimal places.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Returns the rounded value.

Zobacz też:

  • round() - Zaokrągla liczbę zmiennoprzecinkową

variant_pow
variant_set_type
COM Funkcje


Convert a variant into another type "in-place"

variant_round
variant_set
COM Funkcje
PHP Manual

variant_set_type

(PHP 5)

variant_set_type — Convert a variant into another type "in-place"

Opis

void variant_set_type ( variant $variant , int $type )

This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().

Parametry

variant

The variant.

type

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • variant_cast() - Convert a variant into a new variant object of another type

variant_round
variant_set
COM Funkcje


Assigns a new value for a variant object

variant_set_type
variant_sub
COM Funkcje
PHP Manual

variant_set

(PHP 5)

variant_set — Assigns a new value for a variant object

Opis

void variant_set ( variant $variant , mixed $value )

Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.

Parametry

variant

The variant.

value

Zwracane wartości

Nie jest zwracana żadna wartość.

variant_set_type
variant_sub
COM Funkcje


Subtracts the value of the right variant from the left variant value

variant_set
variant_xor
COM Funkcje
PHP Manual

variant_sub

(PHP 5)

variant_sub — Subtracts the value of the right variant from the left variant value

Opis

mixed variant_sub ( mixed $left , mixed $right )

Subtracts right from left.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Variant Subtraction Rules
If | Then
Both expressions are of the string type | Subtraction
One expression is a string type and the other a character | Subtraction
One expression is numeric and the other is a string | Subtraction.
Both expressions are numeric | Subtraction
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Zobacz też:

  • variant_add() - "Adds" two variant values together and returns the result

variant_set
variant_xor
COM Funkcje


Performs a logical exclusion on two variants

variant_sub
Printer
COM Funkcje
PHP Manual

variant_xor

(PHP 5)

variant_xor — Performs a logical exclusion on two variants

Opis

mixed variant_xor ( mixed $left , mixed $right )

Performs a logical exclusion.

Parametry

left

The left operand.

right

The right operand.

Informacja:

Wszystkie arytmetyczne funkcje wariantowe przyjmują jako parametry albo rdzenne typy PHP (integer, string, floating point, boolean lub NULL), albo instancje klas COM, VARINAT lub DOTNET. Rdzenne typy PHP są konwertowane do wariantowych przy użyciu tych samych reguł, które znajdują się w klasie konstruktora VARIANT. Obiekty COM i DOTNET powinny mieć wartości swoich domyślnych właściwości pobierane i używane jako wartości wariantowe.

Arytmetyczne funkcje wariantowe są nakładkami na podobnie nazwane funkcje w bibliotece COM; aby uzyskac więcej informacji o tych funkcjach odwiedź witrynę biblioteki MSDN. Funkcje PHP są nazwane nieco inaczej. Na przykład funkcji variant_add() w PHP odpowiada VarAdd() w dokumentacji MSDN.

Zwracane wartości

Variant XOR Rules
If left is | If right is | then the result is
TRUE | TRUE | FALSE
TRUE | FALSE | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | FALSE
NULL | NULL | NULL

Zobacz też:

  • variant_or() - Performs a logical disjunction on two variants
  • variant_and() - Performs a bitwise AND operation between two variants

variant_sub
Printer
COM Funkcje


Printer

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Printer Funkcje
    • printer_abort — Deletes the printer's spool file
    • printer_close — Close an open printer connection
    • printer_create_brush — Create a new brush
    • printer_create_dc — Create a new device context
    • printer_create_font — Create a new font
    • printer_create_pen — Create a new pen
    • printer_delete_brush — Delete a brush
    • printer_delete_dc — Delete a device context
    • printer_delete_font — Delete a font
    • printer_delete_pen — Delete a pen
    • printer_draw_bmp — Draw a bmp
    • printer_draw_chord — Draw a chord
    • printer_draw_elipse — Draw an ellipse
    • printer_draw_line — Draw a line
    • printer_draw_pie — Draw a pie
    • printer_draw_rectangle — Draw a rectangle
    • printer_draw_roundrect — Draw a rectangle with rounded corners
    • printer_draw_text — Draw text
    • printer_end_doc — Close document
    • printer_end_page — Close active page
    • printer_get_option — Retrieve printer configuration data
    • printer_list — Return an array of printers attached to the server
    • printer_logical_fontheight — Get logical font height
    • printer_open — Opens a connection to a printer
    • printer_select_brush — Select a brush
    • printer_select_font — Select a font
    • printer_select_pen — Select a pen
    • printer_set_option — Configure the printer connection
    • printer_start_doc — Start a new document
    • printer_start_page — Start a new page
    • printer_write — Write data to the printer
variant_xor
Wstęp
Rozszerzenia przeznaczone dla Windows


Wstęp

These functions are only available under Windows 9.x, ME, NT4 and 2000. They have been added in PHP 4.0.4.

Printer
Instalacja/Konfiguracja
Printer


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
Printer


Instalacja

This » PECL extension is not bundled with PHP.

Windows users must enable php_printer.dll inside of php.ini in order to use these functions. Nie dołączone rozszerzenia PECL można pobrać z: » http://pecl4win.php.net/

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Printer configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
printer.default_printer | "" | PHP_INI_ALL | Available since PHP 4.0.6. Removed in PHP 4.1.1.
Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

This extension defines handles to a printer connection, to a brush, to a font and to a pen.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

PRINTER_COPIES (integer)
PRINTER_MODE (integer)
PRINTER_TITLE (integer)
PRINTER_DEVICENAME (integer)
PRINTER_DRIVERVERSION (integer)
PRINTER_OUTPUT_FILE (integer)
PRINTER_RESOLUTION_Y (integer)
PRINTER_RESOLUTION_X (integer)
PRINTER_SCALE (integer)
PRINTER_BACKGROUND_COLOR (integer)
PRINTER_PAPER_LENGTH (integer)
PRINTER_PAPER_WIDTH (integer)
PRINTER_PAPER_FORMAT (integer)
PRINTER_FORMAT_CUSTOM (integer)
PRINTER_FORMAT_LETTER (integer)
PRINTER_FORMAT_LEGAL (integer)
PRINTER_FORMAT_A3 (integer)
PRINTER_FORMAT_A4 (integer)
PRINTER_FORMAT_A5 (integer)
PRINTER_FORMAT_B4 (integer)
PRINTER_FORMAT_B5 (integer)
PRINTER_FORMAT_FOLIO (integer)
PRINTER_ORIENTATION (integer)
PRINTER_ORIENTATION_PORTRAIT (integer)
PRINTER_ORIENTATION_LANDSCAPE (integer)
PRINTER_TEXT_COLOR (integer)
PRINTER_TEXT_ALIGN (integer)
PRINTER_TA_BASELINE (integer)
PRINTER_TA_BOTTOM (integer)
PRINTER_TA_TOP (integer)
PRINTER_TA_CENTER (integer)
PRINTER_TA_LEFT (integer)
PRINTER_TA_RIGHT (integer)
PRINTER_PEN_SOLID (integer)
PRINTER_PEN_DASH (integer)
PRINTER_PEN_DOT (integer)
PRINTER_PEN_DASHDOT (integer)
PRINTER_PEN_DASHDOTDOT (integer)
PRINTER_PEN_INVISIBLE (integer)
PRINTER_BRUSH_SOLID (integer)
PRINTER_BRUSH_CUSTOM (integer)
PRINTER_BRUSH_DIAGONAL (integer)
PRINTER_BRUSH_CROSS (integer)
PRINTER_BRUSH_DIAGCROSS (integer)
PRINTER_BRUSH_FDIAGONAL (integer)
PRINTER_BRUSH_HORIZONTAL (integer)
PRINTER_BRUSH_VERTICAL (integer)
PRINTER_FW_THIN (integer)
PRINTER_FW_ULTRALIGHT (integer)
PRINTER_FW_LIGHT (integer)
PRINTER_FW_NORMAL (integer)
PRINTER_FW_MEDIUM (integer)
PRINTER_FW_BOLD (integer)
PRINTER_FW_ULTRABOLD (integer)
PRINTER_FW_HEAVY (integer)
PRINTER_ENUM_LOCAL (integer)
PRINTER_ENUM_NAME (integer)
PRINTER_ENUM_SHARED (integer)
PRINTER_ENUM_DEFAULT (integer)
PRINTER_ENUM_CONNECTIONS (integer)
PRINTER_ENUM_NETWORK (integer)
PRINTER_ENUM_REMOTE (integer)
Typy zasobów
Printer Funkcje
Printer


Printer Funkcje

Spis treści

  • printer_abort — Deletes the printer's spool file
  • printer_close — Close an open printer connection
  • printer_create_brush — Create a new brush
  • printer_create_dc — Create a new device context
  • printer_create_font — Create a new font
  • printer_create_pen — Create a new pen
  • printer_delete_brush — Delete a brush
  • printer_delete_dc — Delete a device context
  • printer_delete_font — Delete a font
  • printer_delete_pen — Delete a pen
  • printer_draw_bmp — Draw a bmp
  • printer_draw_chord — Draw a chord
  • printer_draw_elipse — Draw an ellipse
  • printer_draw_line — Draw a line
  • printer_draw_pie — Draw a pie
  • printer_draw_rectangle — Draw a rectangle
  • printer_draw_roundrect — Draw a rectangle with rounded corners
  • printer_draw_text — Draw text
  • printer_end_doc — Close document
  • printer_end_page — Close active page
  • printer_get_option — Retrieve printer configuration data
  • printer_list — Return an array of printers attached to the server
  • printer_logical_fontheight — Get logical font height
  • printer_open — Opens a connection to a printer
  • printer_select_brush — Select a brush
  • printer_select_font — Select a font
  • printer_select_pen — Select a pen
  • printer_set_option — Configure the printer connection
  • printer_start_doc — Start a new document
  • printer_start_page — Start a new page
  • printer_write — Write data to the printer
Stałe predefiniowane
printer_abort
Printer


Deletes the printer's spool file

Printer Funkcje
printer_close
Printer Funkcje
PHP Manual

printer_abort

(PECL printer SVN)

printer_abort — Deletes the printer's spool file

Opis

void printer_abort ( resource $printer_handle )

This function deletes the printers spool file.

Parametry

printer_handle

printer_handle must be a valid handle to a printer.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_abort() example

<?php
$handle = printer_open();
printer_abort($handle);
printer_close($handle);
?>

Printer Funkcje
printer_close
Printer Funkcje


Close an open printer connection

printer_abort
printer_create_brush
Printer Funkcje
PHP Manual

printer_close

(PECL printer SVN)

printer_close — Close an open printer connection

Opis

void printer_close ( resource $printer_handle )

This function closes the printer connection. printer_close() also closes the active device context.

Parametry

printer_handle

printer_handle must be a valid handle to a printer.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_close() example

<?php
$handle = printer_open();
printer_close($handle);
?>

printer_abort
printer_create_brush
Printer Funkcje


Create a new brush

printer_close
printer_create_dc
Printer Funkcje
PHP Manual

printer_create_brush

(PECL printer SVN)

printer_create_brush — Create a new brush

Opis

resource printer_create_brush ( int $style , string $color )

The function creates a new brush and returns a handle to it. A brush is used to fill shapes. For an example see printer_select_brush().

Parametry

style

style must be one of the following constants:

  • PRINTER_BRUSH_SOLID: creates a brush with a solid color.
  • PRINTER_BRUSH_DIAGONAL: creates a brush with a 45-degree upward left-to-right hatch ( / ).
  • PRINTER_BRUSH_CROSS: creates a brush with a cross hatch ( + ).
  • PRINTER_BRUSH_DIAGCROSS: creates a brush with a 45 cross hatch ( x ).
  • PRINTER_BRUSH_FDIAGONAL: creates a brush with a 45-degree downward left-to-right hatch ( \ ).
  • PRINTER_BRUSH_HORIZONTAL: creates a brush with a horizontal hatch ( - ).
  • PRINTER_BRUSH_VERTICAL: creates a brush with a vertical hatch ( | ).
  • PRINTER_BRUSH_CUSTOM: creates a custom brush from an BMP file. The second parameter is used to specify the BMP instead of the RGB color code.

color

color must be a color in RGB hex format, i.e. "000000" for black.

Zwracane wartości

Returns a brush handle or FALSE on error.

printer_close
printer_create_dc
Printer Funkcje


Create a new device context

printer_create_brush
printer_create_font
Printer Funkcje
PHP Manual

printer_create_dc

(PECL printer SVN)

printer_create_dc — Create a new device context

Opis

void printer_create_dc ( resource $printer_handle )

The function creates a new device context. A device context is used to customize the graphic objects of the document.

Parametry

printer_handle

printer_handle must be a valid printer handle.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_create_dc() example

<?php
$handle = printer_open();
printer_start_doc($handle);
printer_start_page($handle);

printer_create_dc($handle);
/* do some stuff with the dc */
printer_set_option($handle, PRINTER_TEXT_COLOR, "333333");
printer_draw_text($handle, 1, 1, "text");
printer_delete_dc($handle);

/* create another dc */
printer_create_dc($handle);
printer_set_option($handle, PRINTER_TEXT_COLOR, "000000");
printer_draw_text($handle, 1, 1, "text");
/* do some stuff with the dc */

printer_delete_dc($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_create_brush
printer_create_font
Printer Funkcje


Create a new font

printer_create_dc
printer_create_pen
Printer Funkcje
PHP Manual

printer_create_font

(PECL printer SVN)

printer_create_font — Create a new font

Opis

resource printer_create_font ( string $face , int $height , int $width , int $font_weight , bool $italic , bool $underline , bool $strikeout , int $orientation )

The function creates a new font and returns a handle to it. A font is used to draw text. For an example see printer_select_font().

Parametry

face

face must be a string specifying the font face.

height

height specifies the font height.

width

width specifies the font width.

font_weight

The font_weight specifies the font weight (400 is normal), and can be one of the following predefined constants.

  • PRINTER_FW_THIN: sets the font weight to thin (100).
  • PRINTER_FW_ULTRALIGHT: sets the font weight to ultra light (200).
  • PRINTER_FW_LIGHT: sets the font weight to light (300).
  • PRINTER_FW_NORMAL: sets the font weight to normal (400).
  • PRINTER_FW_MEDIUM: sets the font weight to medium (500).
  • PRINTER_FW_BOLD: sets the font weight to bold (700).
  • PRINTER_FW_ULTRABOLD: sets the font weight to ultra bold (800).
  • PRINTER_FW_HEAVY: sets the font weight to heavy (900).

italic

italic can be TRUE or FALSE, and sets whether the font should be italic.

underline

underline can be TRUE or FALSE, and sets whether the font should be underlined.

strikeout

strikeout can be TRUE or FALSE, and sets whether the font should be stroked out.

orientaton

orientation specifies a rotation.

Zwracane wartości

Returns a font handle on success or FALSE on error.

printer_create_dc
printer_create_pen
Printer Funkcje


Create a new pen

printer_create_font
printer_delete_brush
Printer Funkcje
PHP Manual

printer_create_pen

(PECL printer SVN)

printer_create_pen — Create a new pen

Opis

resource printer_create_pen ( int $style , int $width , string $color )

The function creates a new pen and returns a handle to it. A pen is used to draw lines and curves. For an example see printer_select_pen().

Parametry

style

style must be one of the following constants:

  • PRINTER_PEN_SOLID: creates a solid pen.
  • PRINTER_PEN_DASH: creates a dashed pen.
  • PRINTER_PEN_DOT: creates a dotted pen.
  • PRINTER_PEN_DASHDOT: creates a pen with dashes and dots.
  • PRINTER_PEN_DASHDOTDOT: creates a pen with dashes and double dots.
  • PRINTER_PEN_INVISIBLE: creates an invisible pen.

width

width specifies the width of the pen.

color

color must be a color in RGB hex format, i.e. "000000" for black.

Zwracane wartości

Returns a pen handle or FALSE on error.

printer_create_font
printer_delete_brush
Printer Funkcje


Delete a brush

printer_create_pen
printer_delete_dc
Printer Funkcje
PHP Manual

printer_delete_brush

(PECL printer SVN)

printer_delete_brush — Delete a brush

Opis

void printer_delete_brush ( resource $brush_handle )

The function deletes the selected brush. For an example see printer_select_brush().

Parametry

brush_handle

brush_handle must be a valid handle to a brush.

Zwracane wartości

Nie jest zwracana żadna wartość.

printer_create_pen
printer_delete_dc
Printer Funkcje


Delete a device context

printer_delete_brush
printer_delete_font
Printer Funkcje
PHP Manual

printer_delete_dc

(PECL printer SVN)

printer_delete_dc — Delete a device context

Opis

bool printer_delete_dc ( resource $printer_handle )

The function deletes the device context. For an example see printer_create_dc().

Parametry

printer_handle

printer_handle must be a valid printer handle.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

printer_delete_brush
printer_delete_font
Printer Funkcje


Delete a font

printer_delete_dc
printer_delete_pen
Printer Funkcje
PHP Manual

printer_delete_font

(PECL printer SVN)

printer_delete_font — Delete a font

Opis

void printer_delete_font ( resource $font_handle )

The function deletes the selected font. For an example see printer_select_font().

Parametry

font_handle

font_handle must be a valid handle to a font.

Zwracane wartości

Nie jest zwracana żadna wartość.

printer_delete_dc
printer_delete_pen
Printer Funkcje


Delete a pen

printer_delete_font
printer_draw_bmp
Printer Funkcje
PHP Manual

printer_delete_pen

(PECL printer SVN)

printer_delete_pen — Delete a pen

Opis

void printer_delete_pen ( resource $pen_handle )

The function deletes the selected pen. For an example see printer_select_pen().

Parametry

pen_handle

pen_handle must be a valid pen handle.

Zwracane wartości

Nie jest zwracana żadna wartość.

printer_delete_font
printer_draw_bmp
Printer Funkcje


Draw a bmp

printer_delete_pen
printer_draw_chord
Printer Funkcje
PHP Manual

printer_draw_bmp

(PECL printer SVN)

printer_draw_bmp — Draw a bmp

Opis

bool printer_draw_bmp ( resource $printer_handle , string $filename , int $x , int $y [, int $width ], int $height )

The function draws an bmp.

Parametry

printer_handle

printer_handle must be a valid printer handle.

filename

Path to the bitmap.

x

x is the upper left x coordinate of the bitmap.

y

y is the upper left y coordinate of the bitmap.

width

The bitmap width.

height

The bitmap height.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 printer_draw_bmp() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_draw_bmp($handle, "c:\\image.bmp", 1, 1);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_delete_pen
printer_draw_chord
Printer Funkcje


Draw a chord

printer_draw_bmp
printer_draw_elipse
Printer Funkcje
PHP Manual

printer_draw_chord

(PECL printer SVN)

printer_draw_chord — Draw a chord

Opis

void printer_draw_chord ( resource $printer_handle , int $rec_x , int $rec_y , int $rec_x1 , int $rec_y1 , int $rad_x , int $rad_y , int $rad_x1 , int $rad_y1 )

The function simply draws an chord.

Parametry

printer_handle

printer_handle must be a valid printer handle.

rec_x

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad_x

rad_x is x coordinate of the radial defining the beginning of the chord.

rad_y

rad_y is y coordinate of the radial defining the beginning of the chord.

rad_x1

rad_x1 is x coordinate of the radial defining the end of the chord.

rad_y1

rad_y1 is y coordinate of the radial defining the end of the chord.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_draw_chord() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_chord($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_bmp
printer_draw_elipse
Printer Funkcje


Draw an ellipse

printer_draw_chord
printer_draw_line
Printer Funkcje
PHP Manual

printer_draw_elipse

(PECL printer SVN)

printer_draw_elipse — Draw an ellipse

Opis

void printer_draw_elipse ( resource $printer_handle , int $ul_x , int $ul_y , int $lr_x , int $lr_y )

The function draws an ellipse.

Parametry

printer_handle

printer_handle must be a valid printer handle.

ul_x

ul_x is the upper left x coordinate of the ellipse.

ul_y

ul_y is the upper left y coordinate of the ellipse.

lr_x

lr_x is the lower right x coordinate of the ellipse.

lr_y

lr_y is the lower right y coordinate of the ellipse.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_draw_elipse() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_elipse($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_chord
printer_draw_line
Printer Funkcje


Draw a line

printer_draw_elipse
printer_draw_pie
Printer Funkcje
PHP Manual

printer_draw_line

(PECL printer SVN)

printer_draw_line — Draw a line

Opis

void printer_draw_line ( resource $printer_handle , int $from_x , int $from_y , int $to_x , int $to_y )

The function draws a line using the selected pen.

Parametry

printer_handle

printer_handle must be a valid printer handle.

from_x

from_x is the x coordinate of the origin point.

from_y

from_y is the y coordinate of the origin point.

to_x

to_x is the x coordinate of the destination point.

to_y

to_y is the y coordinate of the destination point.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_draw_line() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "000000");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 10, 1000, 10);
printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_elipse
printer_draw_pie
Printer Funkcje


Draw a pie

printer_draw_line
printer_draw_rectangle
Printer Funkcje
PHP Manual

printer_draw_pie

(PECL printer SVN)

printer_draw_pie — Draw a pie

Opis

void printer_draw_pie ( resource $printer_handle , int $rec_x , int $rec_y , int $rec_x1 , int $rec_y1 , int $rad1_x , int $rad1_y , int $rad2_x , int $rad2_y )

The function draws an pie.

Parametry

printer_handle

printer_handle must be a valid printer handle.

rec_x

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad1_x

rad1_x is x coordinate of the first radial's ending.

rad1_y

rad1_y is y coordinate of the first radial's ending.

rad2_x

rad2_x is x coordinate of the second radial's ending.

rad2_y

rad2_y is y coordinate of the second radial's ending.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_draw_pie() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_pie($handle, 1, 1, 500, 500, 1, 1, 500, 1);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_line
printer_draw_rectangle
Printer Funkcje


Draw a rectangle

printer_draw_pie
printer_draw_roundrect
Printer Funkcje
PHP Manual

printer_draw_rectangle

(PECL printer SVN)

printer_draw_rectangle — Draw a rectangle

Opis

void printer_draw_rectangle ( resource $printer_handle , int $ul_x , int $ul_y , int $lr_x , int $lr_y )

The function draws a rectangle.

Parametry

printer_handle

printer_handle must be a valid printer handle.

ul_x

ul_x is the upper left x coordinate of the rectangle.

ul_y

ul_y is the upper left y coordinate of the rectangle.

lr_x

lr_x is the lower right x coordinate of the rectangle.

lr_y

lr_y is the lower right y coordinate of the rectangle.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_draw_rectangle() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_pie
printer_draw_roundrect
Printer Funkcje


Draw a rectangle with rounded corners

printer_draw_rectangle
printer_draw_text
Printer Funkcje
PHP Manual

printer_draw_roundrect

(PECL printer SVN)

printer_draw_roundrect — Draw a rectangle with rounded corners

Opis

void printer_draw_roundrect ( resource $printer_handle , int $ul_x , int $ul_y , int $lr_x , int $lr_y , int $width , int $height )

The function draws a rectangle with rounded corners.

Parametry

printer_handle

printer_handle must be a valid printer handle.

ul_x

ul_x is the upper left x coordinate of the rectangle.

ul_y

ul_y is the upper left y coordinate of the rectangle.

lr_x

lr_x is the lower right x coordinate of the rectangle.

lr_y

lr_y is the lower right y coordinate of the rectangle.

width

width is the width of the ellipse.

height

height is the height of the ellipse.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_draw_roundrect() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "2222FF");
printer_select_brush($handle, $brush);

printer_draw_roundrect($handle, 1, 1, 500, 500, 200, 200);

printer_delete_brush($brush);
printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_rectangle
printer_draw_text
Printer Funkcje


Draw text

printer_draw_roundrect
printer_end_doc
Printer Funkcje
PHP Manual

printer_draw_text

(PECL printer SVN)

printer_draw_text — Draw text

Opis

void printer_draw_text ( resource $printer_handle , string $text , int $x , int $y )

The function draws text at position x, y using the selected font.

Parametry

printer_handle

printer_handle must be a valid handle to a printer.

text

The text to be written.

x

x is the x coordinate of the position.

y

y is the y coordinate of the position.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_draw_text() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 72, 48, 400, false, false, false, 0);
printer_select_font($handle, $font);
printer_draw_text($handle, "test", 10, 10);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_draw_roundrect
printer_end_doc
Printer Funkcje


Close document

printer_draw_text
printer_end_page
Printer Funkcje
PHP Manual

printer_end_doc

(PECL printer SVN)

printer_end_doc — Close document

Opis

bool printer_end_doc ( resource $printer_handle )

Closes a new document in the printer spooler. The document is now ready for printing. For an example see printer_start_doc().

Parametry

printer_handle

printer_handle must be a valid handle to a printer.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

printer_draw_text
printer_end_page
Printer Funkcje


Close active page

printer_end_doc
printer_get_option
Printer Funkcje
PHP Manual

printer_end_page

(PECL printer SVN)

printer_end_page — Close active page

Opis

bool printer_end_page ( resource $printer_handle )

The function closes the active page in the active document. For an example see printer_start_doc().

Parametry

printer_handle

printer_handle must be a valid handle to a printer.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

printer_end_doc
printer_get_option
Printer Funkcje


Retrieve printer configuration data

printer_end_page
printer_list
Printer Funkcje
PHP Manual

printer_get_option

(PECL printer SVN)

printer_get_option — Retrieve printer configuration data

Opis

mixed printer_get_option ( resource $printer_handle , string $option )

The function retrieves the configuration setting of option.

Parametry

printer_handle

printer_handle must be a valid handle to a printer.

option

Take a look at printer_set_option() for the settings that can be retrieved, additionally the following settings can be retrieved:

  • PRINTER_DEVICENAME returns the devicename of the printer.
  • PRINTER_DRIVERVERSION returns the printer driver version.

Zwracane wartości

Returns the value of option.

Przykłady

Przykład #1 printer_get_option() example

<?php
$handle = printer_open();
echo printer_get_option($handle, PRINTER_DRIVERVERSION);
printer_close($handle);
?>

printer_end_page
printer_list
Printer Funkcje


Return an array of printers attached to the server

printer_get_option
printer_logical_fontheight
Printer Funkcje
PHP Manual

printer_list

(PECL printer SVN)

printer_list — Return an array of printers attached to the server

Opis

array printer_list ( int $enumtype [, string $name [, int $level ]] )

The function enumerates available printers and their capabilities.

Parametry

enumtype

enumtype must be one of the following predefined constants:

  • PRINTER_ENUM_LOCAL: enumerates the locally installed printers.
  • PRINTER_ENUM_NAME: enumerates the printer of name, can be a server, domain or print provider.
  • PRINTER_ENUM_SHARED: this parameter can't be used alone, it has to be OR'ed with other parameters, i.e. PRINTER_ENUM_LOCAL to detect the locally shared printers.
  • PRINTER_ENUM_DEFAULT: (Win9.x only) enumerates the default printer.
  • PRINTER_ENUM_CONNECTIONS: (WinNT/2000 only) enumerates the printers to which the user has made connections.
  • PRINTER_ENUM_NETWORK: (WinNT/2000 only) enumerates network printers in the computer's domain. Only valid if level is 1.
  • PRINTER_ENUM_REMOTE: (WinNT/2000 only) enumerates network printers and print servers in the computer's domain. Only valid if level is 1.

name

Used with PRINTER_ENUM_NAME.

level

level sets the level of information request. Can be 1,2,4 or 5.

Zwracane wartości

Return an array of printers.

Przykłady

Przykład #1 printer_list() example

<?php
/* detect locally shared printer */
var_dump(printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED));
?>

printer_get_option
printer_logical_fontheight
Printer Funkcje


Get logical font height

printer_list
printer_open
Printer Funkcje
PHP Manual

printer_logical_fontheight

(PECL printer SVN)

printer_logical_fontheight — Get logical font height

Opis

int printer_logical_fontheight ( resource $printer_handle , int $height )

The function calculates the logical font height of height.

Parametry

printer_handle

printer_handle must be a valid printer handle.

height

The font height.

Zwracane wartości

Returns the logical font height lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 printer_logical_fontheight() example

<?php
$handle = printer_open();
echo printer_logical_fontheight($handle, 72);
printer_close($handle);
?>

printer_list
printer_open
Printer Funkcje


Opens a connection to a printer

printer_logical_fontheight
printer_select_brush
Printer Funkcje
PHP Manual

printer_open

(PECL printer SVN)

printer_open — Opens a connection to a printer

Opis

resource printer_open ([ string $printername ] )

This function tries to open a connection to the given printer.

printer_open() also starts a device context.

Parametry

printername

The printer name. If no parameter was given it tries to open a connection to the default printer (if not specified in php.ini as printer.default_printer, PHP tries to detect it).

Zwracane wartości

Returns a printer handle on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 printer_open() example

<?php
$handle = printer_open("HP Deskjet 930c");
$handle = printer_open();
?>

printer_logical_fontheight
printer_select_brush
Printer Funkcje


Select a brush

printer_open
printer_select_font
Printer Funkcje
PHP Manual

printer_select_brush

(PECL printer SVN)

printer_select_brush — Select a brush

Opis

void printer_select_brush ( resource $printer_handle , resource $brush_handle )

The function selects a brush as the active drawing object of the actual device context. A brush is used to fill shapes. If you draw an rectangle the brush is used to draw the shapes, while the pen is used to draw the border.

If you haven't selected a brush before drawing shapes, the shape won't be filled.

Parametry

printer_handle

printer_handle must be a valid printer handle.

brush_handle

brush_handle must be a valid brush handle.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_select_brush() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 2, "000000");
printer_select_pen($handle, $pen);
$brush = printer_create_brush(PRINTER_BRUSH_CUSTOM, "c:\\brush.bmp");
printer_select_brush($handle, $brush);

printer_draw_rectangle($handle, 1, 1, 500, 500);

printer_delete_brush($brush);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "000000");
printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1, 501, 500, 1001);
printer_delete_brush($brush);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_open
printer_select_font
Printer Funkcje


Select a font

printer_select_brush
printer_select_pen
Printer Funkcje
PHP Manual

printer_select_font

(PECL printer SVN)

printer_select_font — Select a font

Opis

void printer_select_font ( resource $printer_handle , resource $font_handle )

The function selects a font to draw text.

Parametry

printer_handle

printer_handle must be a valid printer handle.

font_handle

font_handle must be a valid font handle.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_select_font() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$font = printer_create_font("Arial", 148, 76, PRINTER_FW_MEDIUM, false, false, false, -50);
printer_select_font($handle, $font);
printer_draw_text($handle, "PHP is simply cool", 40, 40);
printer_delete_font($font);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_select_brush
printer_select_pen
Printer Funkcje


Select a pen

printer_select_font
printer_set_option
Printer Funkcje
PHP Manual

printer_select_pen

(PECL printer SVN)

printer_select_pen — Select a pen

Opis

void printer_select_pen ( resource $printer_handle , resource $pen_handle )

The function selects a pen as the active drawing object of the actual device context. A pen is used to draw lines and curves. I.e. if you draw a single line the pen is used. If you draw an rectangle the pen is used to draw the borders, while the brush is used to fill the shape. If you haven't selected a pen before drawing shapes, the shape won't be outlined.

Parametry

printer_handle

printer_handle must be a valid printer handle.

pen_handle

pen_handle must be a valid pen handle.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 printer_select_pen() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "2222FF");
printer_select_pen($handle, $pen);

printer_draw_line($handle, 1, 60, 500, 60);

printer_delete_pen($pen);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_select_font
printer_set_option
Printer Funkcje


Configure the printer connection

printer_select_pen
printer_start_doc
Printer Funkcje
PHP Manual

printer_set_option

(PECL printer SVN)

printer_set_option — Configure the printer connection

Opis

bool printer_set_option ( resource $printer_handle , int $option , mixed $value )

The function sets options for the current connection.

Parametry

printer_handle

printer_handle must be a valid printer handle.

option

Option can be one of the following constants:

  • PRINTER_COPIES: sets how many copies should be printed, value must be an integer.
  • PRINTER_MODE: specifies the type of data (text, raw or emf), value must be a string.
  • PRINTER_TITLE: specifies the name of the document, value must be a string.
  • PRINTER_ORIENTATION: specifies the orientation of the paper, value can be either PRINTER_ORIENTATION_PORTRAIT or PRINTER_ORIENTATION_LANDSCAPE
  • PRINTER_RESOLUTION_Y: specifies the y-resolution in DPI, value must be an integer.
  • PRINTER_RESOLUTION_X: specifies the x-resolution in DPI, value must be an integer.
  • PRINTER_PAPER_FORMAT: specifies a predefined paper format, set value to PRINTER_FORMAT_CUSTOM if you want to specify a custom format with PRINTER_PAPER_WIDTH and PRINTER_PAPER_LENGTH. value can be one of the following constants.
    • PRINTER_FORMAT_CUSTOM: let's you specify a custom paper format.
    • PRINTER_FORMAT_LETTER: specifies standard letter format (8 1/2- by 11-inches).
    • PRINTER_FORMAT_LEGAL: specifies standard legal format (8 1/2- by 14-inches).
    • PRINTER_FORMAT_A3: specifies standard A3 format (297- by 420-millimeters).
    • PRINTER_FORMAT_A4: specifies standard A4 format (210- by 297-millimeters).
    • PRINTER_FORMAT_A5: specifies standard A5 format (148- by 210-millimeters).
    • PRINTER_FORMAT_B4: specifies standard B4 format (250- by 354-millimeters).
    • PRINTER_FORMAT_B5: specifies standard B5 format (182- by 257-millimeter).
    • PRINTER_FORMAT_FOLIO: specifies standard FOLIO format (8 1/2- by 13-inch).
  • PRINTER_PAPER_LENGTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifies a custom paper length in mm, value must be an integer.
  • PRINTER_PAPER_WIDTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifies a custom paper width in mm, value must be an integer.
  • PRINTER_SCALE: specifies the factor by which the printed output is to be scaled. the page size is scaled from the physical page size by a factor of scale/100. for example if you set the scale to 50, the output would be half of its original size. value must be an integer.
  • PRINTER_BACKGROUND_COLOR: specifies the background color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".
  • PRINTER_TEXT_COLOR: specifies the text color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".
  • PRINTER_TEXT_ALIGN: specifies the text alignment for the actual device context, value can be combined through OR'ing the following constants:
    • PRINTER_TA_BASELINE: text will be aligned at the base line.
    • PRINTER_TA_BOTTOM: text will be aligned at the bottom.
    • PRINTER_TA_TOP: text will be aligned at the top.
    • PRINTER_TA_CENTER: text will be aligned at the center.
    • PRINTER_TA_LEFT: text will be aligned at the left.
    • PRINTER_TA_RIGHT: text will be aligned at the right.

value

The option value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 printer_set_option() example

<?php
$handle = printer_open();
printer_set_option($handle, PRINTER_SCALE, 75);
printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
printer_close($handle);
?>

printer_select_pen
printer_start_doc
Printer Funkcje


Start a new document

printer_set_option
printer_start_page
Printer Funkcje
PHP Manual

printer_start_doc

(PECL printer SVN)

printer_start_doc — Start a new document

Opis

bool printer_start_doc ( resource $printer_handle [, string $document ] )

The function creates a new document in the printer spooler. A document can contain multiple pages, it's used to schedule the print job in the spooler.

Parametry

printer_handle

printer_handle must be a valid printer handle.

document

The optional parameter document can be used to set an alternative document name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 printer_start_doc() example

<?php
$handle = printer_open();
printer_start_doc($handle, "My Document");
printer_start_page($handle);

printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>

printer_set_option
printer_start_page
Printer Funkcje


Start a new page

printer_start_doc
printer_write
Printer Funkcje
PHP Manual

printer_start_page

(PECL printer SVN)

printer_start_page — Start a new page

Opis

bool printer_start_page ( resource $printer_handle )

The function creates a new page in the active document. For an example see printer_start_doc().

Parametry

printer_handle

printer_handle must be a valid printer handle.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

printer_start_doc
printer_write
Printer Funkcje


Write data to the printer

printer_start_page
W32api
Printer Funkcje
PHP Manual

printer_write

(PECL printer SVN)

printer_write — Write data to the printer

Opis

bool printer_write ( resource $printer_handle , string $content )

Writes content directly to the printer.

Parametry

printer_handle

printer_handle must be a valid printer handle.

content

The data to be written.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 printer_write() example

<?php
$handle = printer_open();
printer_write($handle, "Text to print");
printer_close($handle);
?>

printer_start_page
W32api
Printer Funkcje


W32api

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • w32api examples
  • W32api Funkcje
    • w32api_deftype — Defines a type for use with other w32api_functions
    • w32api_init_dtype — Creates an instance of the data type typename and fills it with the values passed
    • w32api_invoke_function — Invokes function funcname with the arguments passed after the function name
    • w32api_register_function — Registers function function_name from library with PHP
    • w32api_set_call_method — Sets the calling method used
printer_write
Wstęp
Rozszerzenia przeznaczone dla Windows


Wstęp

This extension is a generic extension API to DLLs. This was originally written to allow access to the Win32 API from PHP, although you can also access other functions exported via other DLLs.

Currently supported types are generic PHP types (strings, booleans, floats, integers and nulls) and types you define with w32api_deftype().

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0.

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.

W32api
Instalacja/Konfiguracja
W32api


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
W32api


Wymagania

This extension will only work on Windows systems.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/w32api.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.1.0

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines one resource type, used for user defined types. The name of this resource is "dynaparm".

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

DC_MICROSOFT (integer)
DC_BORLAND (integer)
DC_CALL_CDECL (integer)
DC_CALL_STD (integer)
DC_RETVAL_MATH4 (integer)
DC_RETVAL_MATH8 (integer)
DC_CALL_STD_BO (integer)
DC_CALL_STD_MS (integer)
DC_CALL_STD_M8 (integer)
DC_FLAG_ARGPTR (integer)
Typy zasobów
Przykłady
W32api


Przykłady

Spis treści

  • w32api examples
Stałe predefiniowane
w32api examples
W32api


w32api examples

This example gets the amount of time the system has been running and displays it in a message box.

Przykład #1 Get the uptime and display it in a message box

<?php
// Define constants needed, taken from
// Visual Studio/Tools/Winapi/WIN32API.txt
define("MB_OK", 0);

// Load the extension in
dl("php_w32api.dll");

// Register the GetTickCount function from kernel32.dll
w32api_register_function("kernel32.dll",
                         "GetTickCount",
                         "long");

// Register the MessageBoxA function from User32.dll
w32api_register_function("User32.dll",
                         "MessageBoxA",
                         "long");

// Get uptime information
$ticks = GetTickCount();

// Convert it to a nicely displayable text
$secs  = floor($ticks / 1000);
$mins  = floor($secs / 60);
$hours = floor($mins / 60);

$str = sprintf("You have been using your computer for:" .
                "\r\n %d Milliseconds, or \r\n %d Seconds" .
                "or \r\n %d mins or\r\n %d hours %d mins.",
                $ticks,
                $secs,
                $mins,
                $hours,
                $mins - ($hours*60));

// Display a message box with only an OK button and the uptime text
MessageBoxA(NULL,
            $str,
            "Uptime Information",
            MB_OK);
?>
Przykłady
W32api Funkcje
Przykłady


W32api Funkcje

Spis treści

  • w32api_deftype — Defines a type for use with other w32api_functions
  • w32api_init_dtype — Creates an instance of the data type typename and fills it with the values passed
  • w32api_invoke_function — Invokes function funcname with the arguments passed after the function name
  • w32api_register_function — Registers function function_name from library with PHP
  • w32api_set_call_method — Sets the calling method used
w32api examples
w32api_deftype
W32api


Defines a type for use with other w32api_functions

W32api Funkcje
w32api_init_dtype
W32api Funkcje
PHP Manual

w32api_deftype

(PHP 4 >= 4.2.0)

w32api_deftype — Defines a type for use with other w32api_functions

Opis

bool w32api_deftype ( string $typename , string $member1_type , string $member1_name [, string $... [, string $... ]] )

You need to call this function if you would like to define a type for a w32api call.

Parametry

typename

The name of the type.

member1_type

A member type can be a user defined type. All the type names are case sensitive. Built in type names should be provided in lowercase.

member1_name

The member name of member1_type.

...

...

This function takes 2n+1 arguments, where n is the number of members the type has. After that is the type of the member followed by the members name (in pairs).

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.

W32api Funkcje
w32api_init_dtype
W32api Funkcje


Creates an instance of the data type typename and fills it with the values passed

w32api_deftype
w32api_invoke_function
W32api Funkcje
PHP Manual

w32api_init_dtype

(PHP 4 >= 4.2.0)

w32api_init_dtype — Creates an instance of the data type typename and fills it with the values passed

Opis

resource w32api_init_dtype ( string $typename , mixed $value [, mixed $... ] )

This function creates an instance of the data type named typename, filling in the values of the data type.

Parametry

typename

The typename parameter is case sensitive.

value

You should give the values in the same order as you defined the data type with w32api_deftype().

...

Zwracane wartości

Returns a dynaparm resource.

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.

w32api_deftype
w32api_invoke_function
W32api Funkcje


Invokes function funcname with the arguments passed after the function name

w32api_init_dtype
w32api_register_function
W32api Funkcje
PHP Manual

w32api_invoke_function

(PHP 4 >= 4.2.0)

w32api_invoke_function — Invokes function funcname with the arguments passed after the function name

Opis

mixed w32api_invoke_function ( string $funcname , mixed $argument [, mixed $... ] )

w32api_invoke_function() tries to find the previously registered function, passing the parameters you provided.

Parametry

funcname

The function name.

argument

Any of the arguments can be of any PHP type or w32api_deftype() defined type, as needed.

...

Zwracane wartości

The return type is the one you set when you registered the function, the value is the one returned by the function itself.

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.

w32api_init_dtype
w32api_register_function
W32api Funkcje


Registers function function_name from library with PHP

w32api_invoke_function
w32api_set_call_method
W32api Funkcje
PHP Manual

w32api_register_function

(PHP 4 >= 4.2.0)

w32api_register_function — Registers function function_name from library with PHP

Opis

bool w32api_register_function ( string $library , string $function_name , string $return_type )

This function tries to find the function_name function in library, and tries to import it into PHP.

Parametry

library

The library name, as a string.

function_name

The function name, as a string.

return_type

The function will be registered with the given return_type. This type can be a generic PHP type, or a type defined with w32api_deftype(). All type names are case sensitive. Built in type names should be provided in lowercase.

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.

w32api_invoke_function
w32api_set_call_method
W32api Funkcje


Sets the calling method used

w32api_register_function
win32ps
W32api Funkcje
PHP Manual

w32api_set_call_method

(PHP 4 >= 4.2.0)

w32api_set_call_method — Sets the calling method used

Opis

void w32api_set_call_method ( int $method )

This function sets the method call type.

Parametry

method

Can be one of DC_CALL_CDECL or DC_CALL_STD (the extension default).

Zwracane wartości

Nie jest zwracana żadna wartość.

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.

w32api_register_function
win32ps
W32api Funkcje


win32ps

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Win32ps examples
  • win32ps Funkcje
    • win32_ps_list_procs — List running processes
    • win32_ps_stat_mem — Stat memory utilization
    • win32_ps_stat_proc — Stat process
w32api_set_call_method
Wstęp
Rozszerzenia przeznaczone dla Windows


Wstęp

The win32ps extension is a Windows specific extension that allows PHP retrieve statistics about process and memory utilization.

win32ps
Instalacja/Konfiguracja
win32ps


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
win32ps


Wymagania

Windows NT, Windows 2000, Windows XP or Windows Server 2003. Any version of Windows derived from Windows NT should be compatible.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/win32ps.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
win32ps


Przykłady

Spis treści

  • Win32ps examples
Stałe predefiniowane
Win32ps examples
win32ps


Win32ps examples

Przykład #1 Statistics about the current PHP process

<?php
print_r(win32_ps_stat_proc());
/*
    Array
    (
        [pid] => 936
        [exe] => D:\Daten\Source\php-5.1\Debug_TS\php.exe
        [mem] => Array
            (
                [page_fault_count] => 2062
                [peak_working_set_size] => 8396800
                [working_set_size] => 8396800
                [quota_peak_paged_pool_usage] => 32080
                [quota_paged_pool_usage] => 31876
                [quota_peak_non_paged_pool_usage] => 4240
                [quota_non_paged_pool_usage] => 3888
                [pagefile_usage] => 5865472
                [peak_pagefile_usage] => 5865472
            )

        [tms] => Array
            (
                [created] => 0.093
                [kernel] => 0.015
                [user] => 0.062
            )

    )
*/
?>

Przykład #2 Statistics about global memory utilization

<?php
print_r(win32_ps_stat_mem());
/*
    Array
    (
        [load] => 37
        [unit] => 1024
        [total_phys] => 1048096
        [avail_phys] => 649960
        [total_pagefile] => 2521368
        [avail_pagefile] => 2237940
        [total_virtual] => 2097024
        [avail_virtual] => 2057848
    )
*/
?>

Przykłady
win32ps Funkcje
Przykłady


win32ps Funkcje

Spis treści

  • win32_ps_list_procs — List running processes
  • win32_ps_stat_mem — Stat memory utilization
  • win32_ps_stat_proc — Stat process
Win32ps examples
win32_ps_list_procs
win32ps


List running processes

win32ps Funkcje
win32_ps_stat_mem
win32ps Funkcje
PHP Manual

win32_ps_list_procs

(PECL win32ps >= 1.0.1)

win32_ps_list_procs — List running processes

Opis

array win32_ps_list_procs ( void )

Retrieves statistics about all running processes.

Zwracane wartości

Returns FALSE on failure, or an array consisting of process statistics like win32_ps_stat_proc() returns for all running processes on success.

Zobacz też:

  • win32_ps_stat_proc() - Stat process

win32ps Funkcje
win32_ps_stat_mem
win32ps Funkcje


Stat memory utilization

win32_ps_list_procs
win32_ps_stat_proc
win32ps Funkcje
PHP Manual

win32_ps_stat_mem

(PECL win32ps >= 1.0.1)

win32_ps_stat_mem — Stat memory utilization

Opis

array win32_ps_stat_mem ( void )

Retrieves statistics about the global memory utilization.

Zwracane wartości

Returns FALSE on failure, or an array consisting of the following information on success:

load

The current memory load in percent of physical memory.

unit

This is always 1024, and indicates that the following values are the count of 1024 bytes.

total_phys

The amount of total physical memory.

avail_phys

The amount of still available physical memory.

total_pagefile

The amount of total pageable memory (physical memory + paging file).

avail_pagefile

The amount of still available pageable memory (physical memory + paging file).

total_virtual

The amount of total virtual memory for a process.

avail_virtual

The amount of still available virtual memory for a process.

win32_ps_list_procs
win32_ps_stat_proc
win32ps Funkcje


Stat process

win32_ps_stat_mem
win32service
win32ps Funkcje
PHP Manual

win32_ps_stat_proc

(PECL win32ps >= 1.0.1)

win32_ps_stat_proc — Stat process

Opis

array win32_ps_stat_proc ([ int $pid = 0 ] )

Retrieves statistics about the process with the process id pid.

Parametry

pid

The process id of the process to stat. If omitted, the id of the current process.

Zwracane wartości

Returns FALSE on failure, or an array consisting of the following information on success:

pid

The process id.

exe

The path to the executable image.

mem

An array containing information about the following memory utilization indicators: page_fault_count, peak_working_set_size, working_set_size, quota_peak_paged_pool_usage, quota_paged_pool_usage, quota_peak_non_paged_pool_usage, quota_non_paged_pool_usage, pagefile_usage and peak_pagefile_usage.

tms

An array containing information about the following CPU time utilization indicators: created, kernel and user.

Zobacz też:

  • win32_ps_list_procs() - List running processes

win32_ps_stat_mem
win32service
win32ps Funkcje


win32service

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
    • Win32Service Service Type Bitmasks
    • Win32Service Service Status Constants
    • Win32Service Service Control Message Constants
    • Win32Service Service Control Message Accepted Bitmasks
    • Win32Service Service Start Type Constants
    • Win32Service Service Error Control Constants
    • Win32Service Service Flag Constants
    • Win32 Error Codes
    • Win32 Base Priority Classes
  • Przykłady
  • win32service Funkcje
    • win32_continue_service — Resumes a paused service
    • win32_create_service — Creates a new service entry in the SCM database
    • win32_delete_service — Deletes a service entry from the SCM database
    • win32_get_last_control_message — Returns the last control message that was sent to this service
    • win32_pause_service — Pauses a service
    • win32_query_service_status — Queries the status of a service
    • win32_set_service_status — Update the service status
    • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
    • win32_start_service — Starts a service
    • win32_stop_service — Stops a service
win32_ps_stat_proc
Wstęp
Rozszerzenia przeznaczone dla Windows


Wstęp

The win32service extension is a Windows specific extension that allows PHP to communicate with the Service Control Manager to start, stop, register and unregister services, and even allows your PHP scripts to run as a service.

win32service
Instalacja/Konfiguracja
win32service


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
win32service


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/win32service

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

Spis treści

  • Win32Service Service Type Bitmasks
  • Win32Service Service Status Constants
  • Win32Service Service Control Message Constants
  • Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Start Type Constants
  • Win32Service Service Error Control Constants
  • Win32Service Service Flag Constants
  • Win32 Error Codes
  • Win32 Base Priority Classes

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.

Typy zasobów
Win32Service Service Type Bitmasks
win32service


Win32Service Service Type Bitmasks

Stałe predefiniowane
Win32Service Service Status Constants
Stałe predefiniowane
PHP Manual
Win32Service Service Type Bitmasks
Constant | Value | Description
WIN32_SERVICE_WIN32_OWN_PROCESS | 0x00000010 | The service runs in its own process.
WIN32_SERVICE_INTERACTIVE_PROCESS | 0x00000100 | The service can interact with the desktop. This option is not available on Windows Vista or later.
WIN32_SERVICE_WIN32_OWN_PROCESS_INTERACTIVE | 0x00000110 | The service runs in its own process and can interact with the desktop. This option is not available on Windows Vista or later.
Stałe predefiniowane
Win32Service Service Status Constants
Stałe predefiniowane


Win32Service Service Status Constants

Win32Service Service Type Bitmasks
Win32Service Service Control Message Constants
Stałe predefiniowane
PHP Manual
Win32Service Service Status Constants
Constant | Value | Description
WIN32_SERVICE_CONTINUE_PENDING | 0x00000005 | The service continue is pending.
WIN32_SERVICE_PAUSE_PENDING | 0x00000006 | The service pause is pending.
WIN32_SERVICE_PAUSED | 0x00000007 | The service is paused.
WIN32_SERVICE_RUNNING | 0x00000004 | The service is running.
WIN32_SERVICE_START_PENDING | 0x00000002 | The service is starting.
WIN32_SERVICE_STOP_PENDING | 0x00000003 | The service is stopping.
WIN32_SERVICE_STOPPED | 0x00000001 | The service is not running.
Win32Service Service Type Bitmasks
Win32Service Service Control Message Constants
Stałe predefiniowane


Win32Service Service Control Message Constants

Win32Service Service Status Constants
Win32Service Service Control Message Accepted Bitmasks
Stałe predefiniowane
PHP Manual
Win32Service Service Control Message Constants
Constant | Value | Description
WIN32_SERVICE_CONTROL_CONTINUE | 0x00000003 | Notifies a paused service that it should resume.
WIN32_SERVICE_CONTROL_INTERROGATE | 0x00000004 | Notifies a service that it should report its current status information to the service control manager.
WIN32_SERVICE_CONTROL_PAUSE | 0x00000002 | Notifies a service that it should pause.
WIN32_SERVICE_CONTROL_PRESHUTDOWN | 0x0000000F | Notifies a service that the system will be shutting down. A service that handles this notification blocks system shutdown until the service stops or the preshutdown time-out interval expires. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_CONTROL_SHUTDOWN | 0x00000005 | Notifies a service that the system is shutting down so the service can perform cleanup tasks. If a service accepts this control code, it must stop after it performs its cleanup tasks. After the SCM sends this control code, it will not send other control codes to the service.
WIN32_SERVICE_CONTROL_STOP | 0x00000001 | Notifies a service that it should stop.
Win32Service Service Status Constants
Win32Service Service Control Message Accepted Bitmasks
Stałe predefiniowane


Win32Service Service Control Message Accepted Bitmasks

Win32Service Service Control Message Constants
Win32Service Service Start Type Constants
Stałe predefiniowane
PHP Manual
Win32Service Service Control Message Accepted Bitmasks
Constant | Value | Description
WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE | 0x00000002 | The service can be paused and continued. This control code allows the service to receive WIN32_SERVICE_CONTROL_PAUSE and WIN32_SERVICE_CONTROL_CONTINUE notifications.
WIN32_SERVICE_ACCEPT_PRESHUTDOWN | 0x00000100 | The service can perform preshutdown tasks. This control code enables the service to receive WIN32_SERVICE_CONTROL_PRESHUTDOWN notifications. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_ACCEPT_SHUTDOWN | 0x00000004 | The service is notified when system shutdown occurs. This control code allows the service to receive WIN32_SERVICE_CONTROL_SHUTDOWN notifications.
WIN32_SERVICE_ACCEPT_STOP | 0x00000001 | The service can be stopped. This control code allows the service to receive WIN32_SERVICE_CONTROL_STOP notifications.
Win32Service Service Control Message Constants
Win32Service Service Start Type Constants
Stałe predefiniowane


Win32Service Service Start Type Constants

Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Error Control Constants
Stałe predefiniowane
PHP Manual
Win32Service Service Start Type Constants
Constant | Value | Description
WIN32_SERVICE_AUTO_START | 0x00000002 | A service started automatically by the service control manager during system startup.
WIN32_SERVICE_DEMAND_START | 0x00000003 | A service started by the service control manager when a process calls the StartService function.
WIN32_SERVICE_DISABLED | 0x00000004 | A service that cannot be started. Attempts to start the service result in the error code WIN32_ERROR_SERVICE_DISABLED.
Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Error Control Constants
Stałe predefiniowane


Win32Service Service Error Control Constants

Win32Service Service Start Type Constants
Win32Service Service Flag Constants
Stałe predefiniowane
PHP Manual
Win32Service Service Error Control Constants
Constant | Value | Description
WIN32_SERVICE_ERROR_IGNORE | 0x00000000 | The startup program ignores the error and continues the startup operation.
WIN32_SERVICE_ERROR_NORMAL | 0x00000001 | The startup program logs the error in the event log but continues the startup operation.
Win32Service Service Start Type Constants
Win32Service Service Flag Constants
Stałe predefiniowane


Win32Service Service Flag Constants

Win32Service Service Error Control Constants
Win32 Error Codes
Stałe predefiniowane
PHP Manual
Win32Service Service Flag Constants
Constant | Value | Description
WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS | 0x00000001 | The service runs in a system process that must always be running.
Win32Service Service Error Control Constants
Win32 Error Codes
Stałe predefiniowane


Win32 Error Codes

Win32Service Service Flag Constants
Win32 Base Priority Classes
Stałe predefiniowane
PHP Manual
Win32 Error Codes
Constant | Value | Description
WIN32_ERROR_ACCESS_DENIED | 0x00000005 | The handle to the SCM database does not have the appropriate access rights.
WIN32_ERROR_CIRCULAR_DEPENDENCY | 0x00000423 | A circular service dependency was specified.
WIN32_ERROR_DATABASE_DOES_NOT_EXIST | 0x00000429 | The specified database does not exist.
WIN32_ERROR_DEPENDENT_SERVICES_RUNNING | 0x0000041B | The service cannot be stopped because other running services are dependent on it.
WIN32_ERROR_DUPLICATE_SERVICE_NAME | 0x00000436 | The display name already exists in the service control manager database either as a service name or as another display name.
WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT | 0x00000427 | This error is returned if the program is being run as a console application rather than as a service. If the program will be run as a console application for debugging purposes, structure it such that service-specific code is not called.
WIN32_ERROR_INSUFFICIENT_BUFFER | 0x0000007A | The buffer is too small for the service status structure. Nothing was written to the structure.
WIN32_ERROR_INVALID_DATA | 0x0000000D | The specified service status structure is invalid.
WIN32_ERROR_INVALID_HANDLE | 0x00000006 | The handle to the specified service control manager database is invalid.
WIN32_ERROR_INVALID_LEVEL | 0x0000007C | The InfoLevel parameter contains an unsupported value.
WIN32_ERROR_INVALID_NAME | 0x0000007B | The specified service name is invalid.
WIN32_ERROR_INVALID_PARAMETER | 0x00000057 | A parameter that was specified is invalid.
WIN32_ERROR_INVALID_SERVICE_ACCOUNT | 0x00000421 | The user account name specified in the user parameter does not exist. See win32_create_service().
WIN32_ERROR_INVALID_SERVICE_CONTROL | 0x0000041C | The requested control code is not valid, or it is unacceptable to the service.
WIN32_ERROR_PATH_NOT_FOUND | 0x00000003 | The service binary file could not be found.
WIN32_ERROR_SERVICE_ALREADY_RUNNING | 0x00000420 | An instance of the service is already running.
WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL | 0x00000425 | The requested control code cannot be sent to the service because the state of the service is WIN32_SERVICE_STOPPED, WIN32_SERVICE_START_PENDING, or WIN32_SERVICE_STOP_PENDING.
WIN32_ERROR_SERVICE_DATABASE_LOCKED | 0x0000041F | The database is locked.
WIN32_ERROR_SERVICE_DEPENDENCY_DELETED | 0x00000433 | The service depends on a service that does not exist or has been marked for deletion.
WIN32_ERROR_SERVICE_DEPENDENCY_FAIL | 0x0000042C | The service depends on another service that has failed to start.
WIN32_ERROR_SERVICE_DISABLED | 0x00000422 | The service has been disabled.
WIN32_ERROR_SERVICE_DOES_NOT_EXIST | 0x00000424 | The specified service does not exist as an installed service.
WIN32_ERROR_SERVICE_EXISTS | 0x00000431 | The specified service already exists in this database.
WIN32_ERROR_SERVICE_LOGON_FAILED | 0x0000042D | The service did not start due to a logon failure. This error occurs if the service is configured to run under an account that does not have the "Log on as a service" right.
WIN32_ERROR_SERVICE_MARKED_FOR_DELETE | 0x00000430 | The specified service has already been marked for deletion.
WIN32_ERROR_SERVICE_NO_THREAD | 0x0000041E | A thread could not be created for the service.
WIN32_ERROR_SERVICE_NOT_ACTIVE | 0x00000426 | The service has not been started.
WIN32_ERROR_SERVICE_REQUEST_TIMEOUT | 0x0000041D | The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.
WIN32_ERROR_SHUTDOWN_IN_PROGRESS | 0x0000045B | The system is shutting down; this function cannot be called.
WIN32_NO_ERROR | 0x00000000 | No error.
Win32Service Service Flag Constants
Win32 Base Priority Classes
Stałe predefiniowane


Win32 Base Priority Classes

Win32 Error Codes
Przykłady
Stałe predefiniowane
PHP Manual
Win32 Base Priority Classes
Constant | Value | Description
WIN32_ABOVE_NORMAL_PRIORITY_CLASS | 0x00008000 | Process that has priority above WIN32_NORMAL_PRIORITY_CLASS but below WIN32_HIGH_PRIORITY_CLASS.
WIN32_BELOW_NORMAL_PRIORITY_CLASS | 0x00004000 | Process that has priority above WIN32_IDLE_PRIORITY_CLASS but below WIN32_NORMAL_PRIORITY_CLASS.
WIN32_HIGH_PRIORITY_CLASS | 0x00000080 | Process that performs time-critical tasks that must be executed immediately. The threads of the process preempt the threads of normal or idle priority class processes. An example is the Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class application can use nearly all available CPU time.
WIN32_IDLE_PRIORITY_CLASS | 0x00000040 | Process whose threads run only when the system is idle. The threads of the process are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle-priority class is inherited by child processes.
WIN32_NORMAL_PRIORITY_CLASS | 0x00000020 | Process with no special scheduling needs.
WIN32_REALTIME_PRIORITY_CLASS | 0x00000100 | Process that has the highest possible priority. The threads of the process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.
Win32 Error Codes
Przykłady
Stałe predefiniowane


Przykłady

Przykład #1 Registering a PHP script to run as a service

<?php
win32_create_service(array(
    'service'     => 'dummyphp',                                           # the name of your service
    'display'     => 'sample dummy PHP service',                           # short description
    'description' => 'This is a dummy Windows service created using PHP.', # long description
    'params'      => '"' . __FILE__ . '"  run',                            # path to the script and parameters
));
?>

Przykład #2 Unregistering a service

<?php
win32_delete_service('dummyphp');
?>

Przykład #3 Running as a service

<?php
if ($argv[1] == 'run') {
  win32_start_service_ctrl_dispatcher('dummyphp');

  while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
    # do your work here.
    # try not to take up more than 30 seconds before going around the loop
    # again
  }
}
?>

Win32 Base Priority Classes
win32service Funkcje
win32service


win32service Funkcje

Spis treści

  • win32_continue_service — Resumes a paused service
  • win32_create_service — Creates a new service entry in the SCM database
  • win32_delete_service — Deletes a service entry from the SCM database
  • win32_get_last_control_message — Returns the last control message that was sent to this service
  • win32_pause_service — Pauses a service
  • win32_query_service_status — Queries the status of a service
  • win32_set_service_status — Update the service status
  • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
  • win32_start_service — Starts a service
  • win32_stop_service — Stops a service
Przykłady
win32_continue_service
win32service


Resumes a paused service

win32service Funkcje
win32_create_service
win32service Funkcje
PHP Manual

win32_continue_service

(PECL win32service SVN)

win32_continue_service — Resumes a paused service

Opis

int win32_continue_service ( string $servicename [, string $machine ] )

Resumes a paused, named service. Requires administrative privileges.

Parametry

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Zwracane wartości

Zwraca WIN32_NO_ERROR w przypadku powodzenia , FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

Zobacz też:

  • win32_start_service() - Starts a service
  • Win32 Error Codes

win32service Funkcje
win32_create_service
win32service Funkcje


Creates a new service entry in the SCM database

win32_continue_service
win32_delete_service
win32service Funkcje
PHP Manual

win32_create_service

(PECL win32service SVN)

win32_create_service — Creates a new service entry in the SCM database

Opis

mixed win32_create_service ( array $details [, string $machine ] )

Parametry

details

An array of service details:

service

The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.

display

The display name of the service. This is the name that you will see in the Services Applet.

description

The long description of the service. This is the description that you will see in the Services Applet.

user

The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.

password

The password that corresponds to the user.

path

The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.

params

Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run. If the script name or path contains spaces, then wrap the full path to the PHP script with ".

load_order

Controls the load_order. This is not yet fully supported.

svc_type

Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.

start_type

Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the service will be launched when the machine starts up.

error_control

Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.

delayed_start

If delayed_start is set to TRUE, then this will inform the SCM that this service should be started after other auto-start services are started plus a short delay.

Any service can be marked as a delayed auto-start service; however, this setting has no effect unless the service's start_type is WIN32_SERVICE_AUTO_START.

This setting is only applicable on Windows Vista and Windows Server 2008 or greater.

base_priority

To reduce the impact on processor utilisation, it may be necessary to set a base priority lower than normal.

The base_priority can be set to one of the constants define in Win32 Base Priority Classes.

machine

The optional machine name on which you want to create a service. If omitted, it will use the local machine.

Zwracane wartości

Zwraca WIN32_NO_ERROR w przypadku powodzenia , FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

Przykłady

Przykład #1 A win32_create_service() example

Create a service with the short name 'dummyphp'.

<?php
$x = win32_create_service(array(
    'service'     => 'dummyphp',                                           # the name of your service
    'display'     => 'sample dummy PHP service',                           # short description
    'description' => 'This is a dummy Windows service created using PHP.', # long description
    'params'      => '"' . __FILE__ . '"  run',                            # path to the script and parameters
));
debug_zval_dump($x);
?>

Zobacz też:

  • win32_delete_service() - Deletes a service entry from the SCM database
  • Win32 Base Priority Classes
  • Win32 Error Codes

win32_continue_service
win32_delete_service
win32service Funkcje


Deletes a service entry from the SCM database

win32_create_service
win32_get_last_control_message
win32service Funkcje
PHP Manual

win32_delete_service

(PECL win32service SVN)

win32_delete_service — Deletes a service entry from the SCM database

Opis

mixed win32_delete_service ( string $servicename [, string $machine ] )

Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.

This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.

Parametry

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Zwracane wartości

Zwraca WIN32_NO_ERROR w przypadku powodzenia , FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

Przykłady

Przykład #1 A win32_delete_service() example

Deletes the dummyphp service.

<?php
win32_delete_service('dummyphp');
?>

Zobacz też:

  • win32_create_service() - Creates a new service entry in the SCM database
  • Win32 Error Codes

win32_create_service
win32_get_last_control_message
win32service Funkcje


Returns the last control message that was sent to this service

win32_delete_service
win32_pause_service
win32service Funkcje
PHP Manual

win32_get_last_control_message

(PECL win32service SVN)

win32_get_last_control_message — Returns the last control message that was sent to this service

Opis

int win32_get_last_control_message ( void )

Returns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.

Zwracane wartości

Returns a control constant which will be one of the Win32Service Service Control Message Constants: WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_PRESHUTDOWN, WIN32_SERVICE_CONTROL_SHUTDOWN, WIN32_SERVICE_CONTROL_STOP.

Zobacz też:

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • Win32Service Service Control Message Constants

win32_delete_service
win32_pause_service
win32service Funkcje


Pauses a service

win32_get_last_control_message
win32_query_service_status
win32service Funkcje
PHP Manual

win32_pause_service

(PECL win32service SVN)

win32_pause_service — Pauses a service

Opis

int win32_pause_service ( string $servicename [, string $machine ] )

Pauses a named service. Requires administrative privileges.

Parametry

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Zwracane wartości

Zwraca WIN32_NO_ERROR w przypadku powodzenia , FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

Zobacz też:

  • win32_start_service() - Starts a service
  • Win32 Error Codes

win32_get_last_control_message
win32_query_service_status
win32service Funkcje


Queries the status of a service

win32_pause_service
win32_set_service_status
win32service Funkcje
PHP Manual

win32_query_service_status

(PECL win32service SVN)

win32_query_service_status — Queries the status of a service

Opis

mixed win32_query_service_status ( string $servicename [, string $machine ] )

Queries the current status for a service, returning an array of information.

Parametry

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Zwracane wartości

Returns an array consisting of the following information on success, FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

ServiceType

The dwServiceType. See Win32Service Service Type Bitmasks.

CurrentState

The dwCurrentState. See Win32Service Service Status Constants.

ControlsAccepted

Which service controls are accepted by the service. See Win32Service Service Control Message Accepted Bitmasks.

Win32ExitCode

If the service exited, the return code from the process.

ServiceSpecificExitCode

If the service exited with an error condition, the service specific code that is logged in the event log is visible here.

CheckPoint

If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.

WaitHint

If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.

ProcessId

The Windows process identifier. If 0, the process is not running.

ServiceFlags

The dwServiceFlags. See Win32Service Service Service Flag Constants.

Zobacz też:

  • Win32Service Predefined Constants

win32_pause_service
win32_set_service_status
win32service Funkcje


Update the service status

win32_query_service_status
win32_start_service_ctrl_dispatcher
win32service Funkcje
PHP Manual

win32_set_service_status

(PECL win32service SVN)

win32_set_service_status — Update the service status

Opis

bool win32_set_service_status ( int $status [, int $checkpoint = 0 ] )

Informs the SCM of the current status of a running service. This call is only valid for a running service process.

Parametry

status

The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.

checkpoint

The checkpoint value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up.

The checkpoint is only valid when the status is one of WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING or WIN32_SERVICE_PAUSE_PENDING.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia , FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

Zobacz też:

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • Win32Service Service Status Constants

win32_query_service_status
win32_start_service_ctrl_dispatcher
win32service Funkcje


Registers the script with the SCM, so that it can act as the service with the given name

win32_set_service_status
win32_start_service
win32service Funkcje
PHP Manual

win32_start_service_ctrl_dispatcher

(PECL win32service SVN)

win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name

Opis

mixed win32_start_service_ctrl_dispatcher ( string $name )

When launched via the Service Control Manager, a service process is required to "check-in" with it to establish service monitoring and communication facilities. This function performs the check-in by spawning a thread to handle the lower-level communication with the service control manager.

Once started, the service process should do 2 things. The first is to tell the Service Control Manager that the service is running. This is achieved by calling win32_set_service_status() with the WIN32_SERVICE_RUNNING constant. If you need to perform some lengthy process before the service is actually running, then you can use the WIN32_SERVICE_START_PENDING constant. The second is to continue to check-in with the service control manager so that it can determine if it should terminate. This is achieved by periodically calling win32_get_last_control_message() and handling the return code appropriately.

Parametry

name

The short-name of the service, as registered by win32_create_service().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia , FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

Przykłady

Przykład #1 A win32_start_service_ctrl_dispatcher() example

Check if the service is runnig under the SCM.

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
  die("I'm probably not running under the service control manager");
}

win32_set_service_status(WIN32_SERVICE_START_PENDING);

// Some lengthy process to get this service up and running.

win32_set_service_status(WIN32_SERVICE_RUNNING);

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
  # do some work here, trying not to take more than around 30 seconds
  # before coming back into the loop again
}
?>

Zobacz też:

  • win32_set_service_status() - Update the service status
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • Win32 Error Codes

win32_set_service_status
win32_start_service
win32service Funkcje


Starts a service

win32_start_service_ctrl_dispatcher
win32_stop_service
win32service Funkcje
PHP Manual

win32_start_service

(PECL win32service SVN)

win32_start_service — Starts a service

Opis

int win32_start_service ( string $servicename [, string $machine ] )

Attempts to start the named service. Usually requires administrative privileges.

Parametry

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Zwracane wartości

Zwraca WIN32_NO_ERROR w przypadku powodzenia , FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

Zobacz też:

  • win32_stop_service() - Stops a service
  • Win32 Error Codes

win32_start_service_ctrl_dispatcher
win32_stop_service
win32service Funkcje


Stops a service

win32_start_service
Przetwarzanie XML
win32service Funkcje
PHP Manual

win32_stop_service

(PECL win32service SVN)

win32_stop_service — Stops a service

Opis

int win32_stop_service ( string $servicename [, string $machine ] )

Stops a named service. Requires administrative privileges.

Parametry

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Zwracane wartości

Zwraca WIN32_NO_ERROR w przypadku powodzenia , FALSE jeśli występuje problem z parametrami lub Kod Błędu Win32 w przypadku niepowodzenia.

Zobacz też:

  • win32_start_service() - Starts a service
  • Win32 Error Codes

win32_start_service
Przetwarzanie XML
win32service Funkcje


Przetwarzanie XML

  • DOM — Document Object Model
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • DOMAttr — The DOMAttr class
    • DOMCdataSection — The DOMCdataSection class
    • DOMCharacterData — The DOMCharacterData class
    • DOMComment — The DOMComment class
    • DOMDocument — The DOMDocument class
    • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentType — The DOMDocumentType class
    • DOMElement — The DOMElement class
    • DOMEntity — The DOMEntity class
    • DOMEntityReference — The DOMEntityReference class
    • DOMException — The DOMException class
    • DOMImplementation — The DOMImplementation class
    • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNode — The DOMNode class
    • DOMNodeList — The DOMNodeList class
    • DOMNotation — The DOMNotation class
    • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMText — The DOMText class
    • DOMXPath — The DOMXPath class
    • DOM Funkcje
  • DOM XML (PHP 4)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • DOM XML (PHP 4) Funkcje
  • libxml
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • libXMLError — The libXMLError class
    • libxml Funkcje
  • qtdom
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • qtdom Funkcje
  • SDO — Service Data Objects
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Limitations
    • Przykłady
    • SDO Funkcje
  • SDO-DAS-Relational — SDO Relational Data Access Service
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Limitations
    • SDO-DAS-Relational Funkcje
  • SDO DAS XML — SDO XML Data Access Service
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • SDO DAS XML Funkcje
  • SimpleXML
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLIterator — The SimpleXMLIterator class
    • SimpleXML Funkcje
  • WDDX
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • WDDX Funkcje
  • XML Parser
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Event Handlers
    • Case Folding
    • Error Codes
    • Character Encoding
    • Przykłady
    • XML Parser Funkcje
  • XMLReader
    • Wstęp
    • Instalacja/Konfiguracja
    • XMLReader — The XMLReader class
  • XMLWriter
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • XMLWriter Funkcje
  • XSL
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • XSLTProcessor — The XSLTProcessor class
  • XSLT (PHP 4)
    • Wstęp
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • XSLT (PHP 4) Funkcje
win32_stop_service
DOM
Opis funkcji


Document Object Model

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • DOMAttr — The DOMAttr class
    • DOMAttr::__construct — Creates a new DOMAttr object
    • DOMAttr::isId — Checks if attribute is a defined ID
  • DOMCdataSection — The DOMCdataSection class
    • DOMCdataSection::__construct — Constructs a new DOMCdataSection object
  • DOMCharacterData — The DOMCharacterData class
    • DOMCharacterData::appendData — Append the string to the end of the character data of the node
    • DOMCharacterData::deleteData — Remove a range of characters from the node
    • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
    • DOMCharacterData::substringData — Extracts a range of data from the node
  • DOMComment — The DOMComment class
    • DOMComment::__construct — Creates a new DOMComment object
  • DOMDocument — The DOMDocument class
    • DOMDocument::__construct — Creates a new DOMDocument object
    • DOMDocument::createAttribute — Create new attribute
    • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection — Create new cdata node
    • DOMDocument::createComment — Create new comment node
    • DOMDocument::createDocumentFragment — Create new document fragment
    • DOMDocument::createElement — Create new element node
    • DOMDocument::createElementNS — Create new element node with an associated namespace
    • DOMDocument::createEntityReference — Create new entity reference node
    • DOMDocument::createProcessingInstruction — Creates new PI node
    • DOMDocument::createTextNode — Create new text node
    • DOMDocument::getElementById — Searches for an element with a certain id
    • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode — Import node into current document
    • DOMDocument::load — Load XML from a file
    • DOMDocument::loadHTML — Load HTML from a string
    • DOMDocument::loadHTMLFile — Load HTML from a file
    • DOMDocument::loadXML — Load XML from a string
    • DOMDocument::normalizeDocument — Normalizes the document
    • DOMDocument::registerNodeClass — Register extended class used to create base node type
    • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
    • DOMDocument::save — Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML — Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate — Validates a document based on a schema
    • DOMDocument::schemaValidateSource — Validates a document based on a schema
    • DOMDocument::validate — Validates the document based on its DTD
    • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object
  • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentFragment::appendXML — Append raw XML data
  • DOMDocumentType — The DOMDocumentType class
  • DOMElement — The DOMElement class
    • DOMElement::__construct — Creates a new DOMElement object
    • DOMElement::getAttribute — Returns value of attribute
    • DOMElement::getAttributeNode — Returns attribute node
    • DOMElement::getAttributeNodeNS — Returns attribute node
    • DOMElement::getAttributeNS — Returns value of attribute
    • DOMElement::getElementsByTagName — Gets elements by tagname
    • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
    • DOMElement::hasAttribute — Checks to see if attribute exists
    • DOMElement::hasAttributeNS — Checks to see if attribute exists
    • DOMElement::removeAttribute — Removes attribute
    • DOMElement::removeAttributeNode — Removes attribute
    • DOMElement::removeAttributeNS — Removes attribute
    • DOMElement::setAttribute — Adds new attribute
    • DOMElement::setAttributeNode — Adds new attribute node to element
    • DOMElement::setAttributeNodeNS — Adds new attribute node to element
    • DOMElement::setAttributeNS — Adds new attribute
    • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID
  • DOMEntity — The DOMEntity class
  • DOMEntityReference — The DOMEntityReference class
    • DOMEntityReference::__construct — Creates a new DOMEntityReference object
  • DOMException — The DOMException class
  • DOMImplementation — The DOMImplementation class
    • DOMImplementation::__construct — Creates a new DOMImplementation object
    • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature
  • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item — Retrieves a node specified by index
  • DOMNode — The DOMNode class
    • DOMNode::appendChild — Adds new child at the end of the children
    • DOMNode::C14N — Canonicalize nodes to a string
    • DOMNode::C14NFile — Canonicalize nodes to a file
    • DOMNode::cloneNode — Clones a node
    • DOMNode::getLineNo — Get line number for a node
    • DOMNode::getNodePath — Get an XPath for a node
    • DOMNode::hasAttributes — Checks if node has attributes
    • DOMNode::hasChildNodes — Checks if node has children
    • DOMNode::insertBefore — Adds a new child before a reference node
    • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isSameNode — Indicates if two nodes are the same node
    • DOMNode::isSupported — Checks if feature is supported for specified version
    • DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
    • DOMNode::normalize — Normalizes the node
    • DOMNode::removeChild — Removes child from list of children
    • DOMNode::replaceChild — Replaces a child
  • DOMNodeList — The DOMNodeList class
    • DOMNodelist::item — Retrieves a node specified by index
  • DOMNotation — The DOMNotation class
  • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object
  • DOMText — The DOMText class
    • DOMText::__construct — Creates a new DOMText object
    • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
    • DOMText::splitText — Breaks this node into two nodes at the specified offset
  • DOMXPath — The DOMXPath class
    • DOMXPath::__construct — Creates a new DOMXPath object
    • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query — Evaluates the given XPath expression
    • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions
  • DOM Funkcje
    • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object
Przetwarzanie XML
Wstęp
Przetwarzanie XML


Wstęp

The DOM extension allows you to operate on XML documents through the DOM API with PHP 5.

For PHP 4, use DOM XML.

Informacja:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or Iconv for other encodings.

DOM
Instalacja/Konfiguracja
DOM


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
DOM


Instalacja

To rozszerzenie jest domyślnie włączone. Może być ono wyłączone za pomocą następującej opcji w czasie kompilacji: --disable-dom

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

XML constants
Constant | Value | Description
XML_ELEMENT_NODE (integer) | 1 | Node is a DOMElement
XML_ATTRIBUTE_NODE (integer) | 2 | Node is a DOMAttr
XML_TEXT_NODE (integer) | 3 | Node is a DOMText
XML_CDATA_SECTION_NODE (integer) | 4 | Node is a DOMCharacterData
XML_ENTITY_REF_NODE (integer) | 5 | Node is a DOMEntityReference
XML_ENTITY_NODE (integer) | 6 | Node is a DOMEntity
XML_PI_NODE (integer) | 7 | Node is a DOMProcessingInstruction
XML_COMMENT_NODE (integer) | 8 | Node is a DOMComment
XML_DOCUMENT_NODE (integer) | 9 | Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) | 10 | Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) | 11 | Node is a DOMDocumentFragment
XML_NOTATION_NODE (integer) | 12 | Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (integer) | 13 |
XML_DTD_NODE (integer) | 14 |
XML_ELEMENT_DECL_NODE (integer) | 15 |
XML_ATTRIBUTE_DECL_NODE (integer) | 16 |
XML_ENTITY_DECL_NODE (integer) | 17 |
XML_NAMESPACE_DECL_NODE (integer) | 18 |
XML_ATTRIBUTE_CDATA (integer) | 1 |
XML_ATTRIBUTE_ID (integer) | 2 |
XML_ATTRIBUTE_IDREF (integer) | 3 |
XML_ATTRIBUTE_IDREFS (integer) | 4 |
XML_ATTRIBUTE_ENTITY (integer) | 5 |
XML_ATTRIBUTE_NMTOKEN (integer) | 7 |
XML_ATTRIBUTE_NMTOKENS (integer) | 8 |
XML_ATTRIBUTE_ENUMERATION (integer) | 9 |
XML_ATTRIBUTE_NOTATION (integer) | 10 |
DOMException constants
Constant | Value | Description
DOM_PHP_ERR (integer) | 0 | Error code not part of the DOM specification. Meant for PHP errors.
DOM_INDEX_SIZE_ERR (integer) | 1 | If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (integer) | 2 | If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (integer) | 3 | If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (integer) | 4 | If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (integer) | 5 | If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (integer) | 6 | If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) | 7 | If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (integer) | 8 | If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (integer) | 9 | If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (integer) | 10 | If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (integer) | 11 | If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (integer) | 12 | If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (integer) | 13 | If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (integer) | 14 | If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (integer) | 15 | If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (integer) | 16 | If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.
Typy zasobów
DOMAttr
DOM


The DOMAttr class

(PHP 5)

Wstęp

DOMAttr represents an attribute in the DOMElement object.

Krótki opis klasy

DOMAttr extends DOMNode {
/* Właściwości */
public readonly string $name ;
public readonly DOMElement $ownerElement ;
public readonly bool $schemaTypeInfo ;
public readonly bool $specified ;
public string $value ;
/* Metody */
__construct ( string $name [, string $value ] )
bool isId ( void )
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

name

The name of the attribute

ownerElement

The element which contains the attribute

schemaTypeInfo

Not implemented yet, always is NULL

specified

Not implemented yet, always is NULL

value

The value of the attribute

Zobacz też:

  • » W3C specification of Attr

Spis treści

  • DOMAttr::__construct — Creates a new DOMAttr object
  • DOMAttr::isId — Checks if attribute is a defined ID
Stałe predefiniowane
DOMAttr::__construct
DOM


Creates a new DOMAttr object

DOMAttr
DOMAttr::isId
DOMAttr
PHP Manual

DOMAttr::__construct

(PHP 5)

DOMAttr::__construct — Creates a new DOMAttr object

Opis

DOMAttr::__construct ( string $name [, string $value ] )

Creates a new DOMAttr object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writable node, use DOMDocument::createAttribute.

Parametry

name

The tag name of the attribute.

value

The value of the attribute.

Przykłady

Przykład #1 Creating a new DOMAttr object

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML();

?>

Powyższy przykład wyświetli:

<?xml version="1.0" encoding="utf-8"?>
<root attr="attrvalue" />

Zobacz też:

  • DOMDocument::createAttribute() - Create new attribute

DOMAttr
DOMAttr::isId
DOMAttr


Checks if attribute is a defined ID

DOMAttr::__construct
DOMCdataSection
DOMAttr
PHP Manual

DOMAttr::isId

(PHP 5)

DOMAttr::isId — Checks if attribute is a defined ID

Opis

bool DOMAttr::isId ( void )

This function checks if the attribute is a defined ID.

According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument::validate or DOMDocument::validateOnParse before using this function.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 DOMAttr::isId() Example

<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// We retrieve the attribute named id of the chapter element
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>

DOMAttr::__construct
DOMCdataSection
DOMAttr


The DOMCdataSection class

(PHP 5)

Wstęp

The DOMCdataSection inherits from DOMText for textural representation of CData constructs.

Krótki opis klasy

DOMCdataSection extends DOMText {
/* Methods */
public __construct ( string $value )
/* Inherited methods */
public bool DOMText::isWhitespaceInElementContent ( void )
public DOMText DOMText::splitText ( int $offset )
}

Spis treści

  • DOMCdataSection::__construct — Constructs a new DOMCdataSection object
DOMAttr::isId
DOMCdataSection::__construct
DOM


Constructs a new DOMCdataSection object

DOMCdataSection
DOMCharacterData
DOMCdataSection
PHP Manual

DOMCdataSection::__construct

(PHP 5)

DOMCdataSection::__construct — Constructs a new DOMCdataSection object

Opis

public DOMCdataSection::__construct() ( string $value )

Constructs a new CDATA node. This works like the DOMText class.

Parametry

value

The value of the CDATA node. If not supplied, an empty CDATA node is created.

Przykłady

Przykład #1 Creating a new DOMCdataSection object

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMCdataSection('root value'));
echo $dom->saveXML();

?>

Powyższy przykład wyświetli:

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

Zobacz też:

  • DOMText::__construct() - Creates a new DOMText object
  • DOMDocument::createTextNode() - Create new text node

DOMCdataSection
DOMCharacterData
DOMCdataSection


The DOMCharacterData class

(PHP 5)

Wstęp

Represents nodes with character data. No nodes directly correspond to this class, but other nodes do inherit from it.

Krótki opis klasy

DOMCharacterData extends DOMNode {
/* Właściwości */
public string $data ;
readonly public int $length ;
/* Metody */
void appendData ( string $data )
void deleteData ( int $offset , int $count )
void insertData ( int $offset , string $data )
void replaceData ( int $offset , int $count , string $data )
string substringData ( int $offset , int $count )
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

data

The contents of the node.

length

The length of the contents.

Zobacz też:

  • » W3C specification of CharacterData

Spis treści

  • DOMCharacterData::appendData — Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData — Remove a range of characters from the node
  • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData — Extracts a range of data from the node
DOMCdataSection::__construct
DOMCharacterData::appendData
DOM


Append the string to the end of the character data of the node

DOMCharacterData
DOMCharacterData::deleteData
DOMCharacterData
PHP Manual

DOMCharacterData::appendData

(PHP 5)

DOMCharacterData::appendData — Append the string to the end of the character data of the node

Opis

void DOMCharacterData::appendData ( string $data )

Append the string data to the end of the character data of the node.

Parametry

data

The string to append.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

DOMCharacterData
DOMCharacterData::deleteData
DOMCharacterData


Remove a range of characters from the node

DOMCharacterData::appendData
DOMCharacterData::insertData
DOMCharacterData
PHP Manual

DOMCharacterData::deleteData

(PHP 5)

DOMCharacterData::deleteData — Remove a range of characters from the node

Opis

void DOMCharacterData::deleteData ( int $offset , int $count )

Deletes count characters starting from position offset.

Parametry

offset

The offset from which to start removing.

count

The number of characters to delete. If the sum of offset and count exceeds the length, then all characters to the end of the data are deleted.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

Zobacz też:

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

DOMCharacterData::appendData
DOMCharacterData::insertData
DOMCharacterData


Insert a string at the specified 16-bit unit offset

DOMCharacterData::deleteData
DOMCharacterData::replaceData
DOMCharacterData
PHP Manual

DOMCharacterData::insertData

(PHP 5)

DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset

Opis

void DOMCharacterData::insertData ( int $offset , string $data )

Inserts string data at position offset.

Parametry

offset

The character offset at which to insert.

data

The string to insert.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data.

Zobacz też:

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

DOMCharacterData::deleteData
DOMCharacterData::replaceData
DOMCharacterData


Replace a substring within the DOMCharacterData node

DOMCharacterData::insertData
DOMCharacterData::substringData
DOMCharacterData
PHP Manual

DOMCharacterData::replaceData

(PHP 5)

DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node

Opis

void DOMCharacterData::replaceData ( int $offset , int $count , string $data )

Replace count characters starting from position offset with data.

Parametry

offset

The offset from which to start replacing.

count

The number of characters to replace. If the sum of offset and count exceeds the length, then all characters to the end of the data are replaced.

data

The string with which the range must be replaced.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

Zobacz też:

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::substringData() - Extracts a range of data from the node

DOMCharacterData::insertData
DOMCharacterData::substringData
DOMCharacterData


Extracts a range of data from the node

DOMCharacterData::replaceData
DOMComment
DOMCharacterData
PHP Manual

DOMCharacterData::substringData

(PHP 5)

DOMCharacterData::substringData — Extracts a range of data from the node

Opis

string DOMCharacterData::substringData ( int $offset , int $count )

Returns the specified substring.

Parametry

offset

Start offset of substring to extract.

count

The number of characters to extract.

Zwracane wartości

The specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.

Błędy/Wyjątki

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

Zobacz też:

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node

DOMCharacterData::replaceData
DOMComment
DOMCharacterData


The DOMComment class

(PHP 5)

Wstęp

Represents comment nodes, characters delimited by <!-- and -->.

Krótki opis klasy

DOMComment extends DOMCharacterData {
/* Metody */
__construct ([ string $value ] )
/* Metody dziedziczone */
void DOMCharacterData::appendData ( string $data )
void DOMCharacterData::deleteData ( int $offset , int $count )
void DOMCharacterData::insertData ( int $offset , string $data )
void DOMCharacterData::replaceData ( int $offset , int $count , string $data )
string DOMCharacterData::substringData ( int $offset , int $count )
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Zobacz też:

  • » W3C specification of Comment

Spis treści

  • DOMComment::__construct — Creates a new DOMComment object
DOMCharacterData::substringData
DOMComment::__construct
DOM


Creates a new DOMComment object

DOMComment
DOMDocument
DOMComment
PHP Manual

DOMComment::__construct

(PHP 5)

DOMComment::__construct — Creates a new DOMComment object

Opis

DOMComment::__construct ([ string $value ] )

Creates a new DOMComment object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createComment.

Parametry

value

The value of the comment.

Przykłady

Przykład #1 Creating a new DOMComment

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$comment = $element->appendChild(new DOMComment('root comment'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root><!--root comment--></root> */

?>

Zobacz też:

  • DOMDocument::createComment() - Create new comment node

DOMComment
DOMDocument
DOMComment


The DOMDocument class

(PHP 5)

Wstęp

Represents an entire HTML or XML document; serves as the root of the document tree.

Krótki opis klasy

DOMDocument extends DOMNode {
/* Właściwości */
readonly public string $actualEncoding ;
readonly public DOMConfiguration $config ;
readonly public DOMDocumentType $doctype ;
readonly public DOMElement $documentElement ;
public string $documentURI ;
public string $encoding ;
public bool $formatOutput ;
readonly public DOMImplementation $implementation ;
public bool $preserveWhiteSpace = true ;
public bool $recover ;
public bool $resolveExternals ;
public bool $standalone ;
public bool $strictErrorChecking = true ;
public bool $substituteEntities ;
public bool $validateOnParse = false ;
public string $version ;
readonly public string $xmlEncoding ;
public bool $xmlStandalone ;
public string $xmlVersion ;
/* Metody */
__construct ([ string $version [, string $encoding ]] )
DOMAttr createAttribute ( string $name )
DOMAttr createAttributeNS ( string $namespaceURI , string $qualifiedName )
DOMCDATASection createCDATASection ( string $data )
DOMComment createComment ( string $data )
DOMDocumentFragment createDocumentFragment ( void )
DOMElement createElement ( string $name [, string $value ] )
DOMElement createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] )
DOMEntityReference createEntityReference ( string $name )
DOMProcessingInstruction createProcessingInstruction ( string $target [, string $data ] )
DOMText createTextNode ( string $content )
DOMElement getElementById ( string $elementId )
DOMNodeList getElementsByTagName ( string $name )
DOMNodeList getElementsByTagNameNS ( string $namespaceURI , string $localName )
DOMNode importNode ( DOMNode $importedNode [, bool $deep ] )
mixed load ( string $filename [, int $options = 0 ] )
bool loadHTML ( string $source )
bool loadHTMLFile ( string $filename )
mixed loadXML ( string $source [, int $options = 0 ] )
void normalizeDocument ( void )
bool registerNodeClass ( string $baseclass , string $extendedclass )
bool relaxNGValidate ( string $filename )
bool relaxNGValidateSource ( string $source )
int save ( string $filename [, int $options ] )
string saveHTML ([ DOMNode $node = NULL ] )
int saveHTMLFile ( string $filename )
string saveXML ([ DOMNode $node [, int $options ]] )
bool schemaValidate ( string $filename )
bool schemaValidateSource ( string $source )
bool validate ( void )
int xinclude ([ int $options ] )
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

actualEncoding

Deprecated. Actual encoding of the document, is a readonly equivalent to encoding.

config

Deprecated. Configuration used when DOMDocument::normalizeDocument() is invoked.

doctype

The Document Type Declaration associated with this document.

documentElement

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

documentURI

The location of the document or NULL if undefined.

encoding

Encoding of the document, as specified by the XML declaration. This attribute is not present in the final DOM Level 3 specification, but is the only way of manipulating XML document encoding in this implementation.

formatOutput

Nicely formats output with indentation and extra space.

implementation

The DOMImplementation object that handles this document.

preserveWhiteSpace

Do not remove redundant white space. Default to TRUE.

recover

Proprietary. Enables recovery mode, i.e. trying to parse non-well formed documents. This attribute is not part of the DOM specification and is specific to libxml.

resolveExternals

Set it to TRUE to load external entities from a doctype declaration. This is useful for including character entities in your XML document.

standalone

Deprecated. Whether or not the document is standalone, as specified by the XML declaration, corresponds to xmlStandalone.

strictErrorChecking

Throws DOMException on errors. Default to TRUE.

substituteEntities

Proprietary. Whether or not to substitute entities. This attribute is not part of the DOM specification and is specific to libxml.

validateOnParse

Loads and validates against the DTD. Default to FALSE.

version

Deprecated. Version of XML, corresponds to xmlVersion.

xmlEncoding

An attribute specifying, as part of the XML declaration, the encoding of this document. This is NULL when unspecified or when it is not known, such as when the Document was created in memory.

xmlStandalone

An attribute specifying, as part of the XML declaration, whether this document is standalone. This is FALSE when unspecified.

xmlVersion

An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

Notatki

Informacja:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or Iconv for other encodings.

Zobacz też:

  • » W3C specification for Document

Spis treści

  • DOMDocument::__construct — Creates a new DOMDocument object
  • DOMDocument::createAttribute — Create new attribute
  • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection — Create new cdata node
  • DOMDocument::createComment — Create new comment node
  • DOMDocument::createDocumentFragment — Create new document fragment
  • DOMDocument::createElement — Create new element node
  • DOMDocument::createElementNS — Create new element node with an associated namespace
  • DOMDocument::createEntityReference — Create new entity reference node
  • DOMDocument::createProcessingInstruction — Creates new PI node
  • DOMDocument::createTextNode — Create new text node
  • DOMDocument::getElementById — Searches for an element with a certain id
  • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
  • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
  • DOMDocument::importNode — Import node into current document
  • DOMDocument::load — Load XML from a file
  • DOMDocument::loadHTML — Load HTML from a string
  • DOMDocument::loadHTMLFile — Load HTML from a file
  • DOMDocument::loadXML — Load XML from a string
  • DOMDocument::normalizeDocument — Normalizes the document
  • DOMDocument::registerNodeClass — Register extended class used to create base node type
  • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
  • DOMDocument::save — Dumps the internal XML tree back into a file
  • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
  • DOMDocument::saveXML — Dumps the internal XML tree back into a string
  • DOMDocument::schemaValidate — Validates a document based on a schema
  • DOMDocument::schemaValidateSource — Validates a document based on a schema
  • DOMDocument::validate — Validates the document based on its DTD
  • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object
DOMComment::__construct
DOMDocument::__construct
DOM


Creates a new DOMDocument object

DOMDocument
DOMDocument::createAttribute
DOMDocument
PHP Manual

DOMDocument::__construct

(PHP 5)

DOMDocument::__construct — Creates a new DOMDocument object

Opis

DOMDocument::__construct ([ string $version [, string $encoding ]] )

Creates a new DOMDocument object.

Parametry

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

Przykłady

Przykład #1 Creating a new DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

Zobacz też:

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element

DOMDocument
DOMDocument::createAttribute
DOMDocument


Create new attribute

DOMDocument::__construct
DOMDocument::createAttributeNS
DOMDocument
PHP Manual

DOMDocument::createAttribute

(PHP 5)

DOMDocument::createAttribute — Create new attribute

Opis

DOMAttr DOMDocument::createAttribute ( string $name )

This function creates a new instance of class DOMAttr. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

name

The name of the attribute.

Zwracane wartości

The new DOMAttr or FALSE if an error occured.

Błędy/Wyjątki

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::__construct
DOMDocument::createAttributeNS
DOMDocument


Create new attribute node with an associated namespace

DOMDocument::createAttribute
DOMDocument::createCDATASection
DOMDocument
PHP Manual

DOMDocument::createAttributeNS

(PHP 5)

DOMDocument::createAttributeNS — Create new attribute node with an associated namespace

Opis

DOMAttr DOMDocument::createAttributeNS ( string $namespaceURI , string $qualifiedName )

This function creates a new instance of class DOMAttr. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

namespaceURI

The URI of the namespace.

qualifiedName

The tag name and prefix of the attribute, as prefix:tagname.

Zwracane wartości

The new DOMAttr or FALSE if an error occured.

Błędy/Wyjątki

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::createAttribute
DOMDocument::createCDATASection
DOMDocument


Create new cdata node

DOMDocument::createAttributeNS
DOMDocument::createComment
DOMDocument
PHP Manual

DOMDocument::createCDATASection

(PHP 5)

DOMDocument::createCDATASection — Create new cdata node

Opis

DOMCDATASection DOMDocument::createCDATASection ( string $data )

This function creates a new instance of class DOMCDATASection. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

data

The content of the cdata.

Zwracane wartości

The new DOMCDATASection or FALSE if an error occured.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::createAttributeNS
DOMDocument::createComment
DOMDocument


Create new comment node

DOMDocument::createCDATASection
DOMDocument::createDocumentFragment
DOMDocument
PHP Manual

DOMDocument::createComment

(PHP 5)

DOMDocument::createComment — Create new comment node

Opis

DOMComment DOMDocument::createComment ( string $data )

This function creates a new instance of class DOMComment. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

data

The content of the comment.

Zwracane wartości

The new DOMComment or FALSE if an error occured.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::createCDATASection
DOMDocument::createDocumentFragment
DOMDocument


Create new document fragment

DOMDocument::createComment
DOMDocument::createElement
DOMDocument
PHP Manual

DOMDocument::createDocumentFragment

(PHP 5)

DOMDocument::createDocumentFragment — Create new document fragment

Opis

DOMDocumentFragment DOMDocument::createDocumentFragment ( void )

This function creates a new instance of class DOMDocumentFragment. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Zwracane wartości

The new DOMDocumentFragment or FALSE if an error occured.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::createComment
DOMDocument::createElement
DOMDocument


Create new element node

DOMDocument::createDocumentFragment
DOMDocument::createElementNS
DOMDocument
PHP Manual

DOMDocument::createElement

(PHP 5)

DOMDocument::createElement — Create new element node

Opis

DOMElement DOMDocument::createElement ( string $name [, string $value ] )

This function creates a new instance of class DOMElement. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

name

The tag name of the element.

value

The value of the element. By default, an empty element will be created. The value can also be set later with DOMElement::$nodeValue.

Zwracane wartości

Returns a new instance of class DOMElement or FALSE if an error occured.

Błędy/Wyjątki

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Przykłady

Przykład #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

Powyższy przykład wyświetli:

<?xml version="1.0" encoding="utf-8"?>
<test>This is the root element!</test>

Notatki

Informacja:

The value will not be escaped. Use DOMDocument::createTextNode() to create a text node with escaping support.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::createDocumentFragment
DOMDocument::createElementNS
DOMDocument


Create new element node with an associated namespace

DOMDocument::createElement
DOMDocument::createEntityReference
DOMDocument
PHP Manual

DOMDocument::createElementNS

(PHP 5)

DOMDocument::createElementNS — Create new element node with an associated namespace

Opis

DOMElement DOMDocument::createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] )

This function creates a new element node with an associated namespace. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

namespaceURI

The URI of the namespace.

qualifiedName

The qualified name of the element, as prefix:tagname.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement::$nodeValue.

Zwracane wartości

The new DOMElement or FALSE if an error occured.

Błędy/Wyjątki

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a maformed qualified name.

Przykłady

Przykład #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

Powyższy przykład wyświetli:

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

Przykład #2 A namespace prefix example

<?php
$doc  = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);

echo $doc->saveXML(), "\n";

echo $item->namespaceURI, "\n"; // Outputs: http://base.google.com/ns/1.0
echo $item->prefix, "\n";       // Outputs: g
echo $item->localName, "\n";    // Outputs: item_type
?>

Powyższy przykład wyświetli:

<?xml version="1.0" encoding="utf-8"?>
<element xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
  <g:item_type>house</g:item_type>
</element>

http://base.google.com/ns/1.0
g
item_type

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::createElement
DOMDocument::createEntityReference
DOMDocument


Create new entity reference node

DOMDocument::createElementNS
DOMDocument::createProcessingInstruction
DOMDocument
PHP Manual

DOMDocument::createEntityReference

(PHP 5)

DOMDocument::createEntityReference — Create new entity reference node

Opis

DOMEntityReference DOMDocument::createEntityReference ( string $name )

This function creates a new instance of class DOMEntityReference. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

Zwracane wartości

The new DOMEntityReference or FALSE if an error occured.

Błędy/Wyjątki

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::createElementNS
DOMDocument::createProcessingInstruction
DOMDocument


Creates new PI node

DOMDocument::createEntityReference
DOMDocument::createTextNode
DOMDocument
PHP Manual

DOMDocument::createProcessingInstruction

(PHP 5)

DOMDocument::createProcessingInstruction — Creates new PI node

Opis

DOMProcessingInstruction DOMDocument::createProcessingInstruction ( string $target [, string $data ] )

This function creates a new instance of class DOMProcessingInstruction. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

target

The target of the processing instruction.

data

The content of the processing instruction.

Zwracane wartości

The new DOMProcessingInstruction or FALSE if an error occured.

Błędy/Wyjątki

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createTextNode() - Create new text node

DOMDocument::createEntityReference
DOMDocument::createTextNode
DOMDocument


Create new text node

DOMDocument::createProcessingInstruction
DOMDocument::getElementById
DOMDocument
PHP Manual

DOMDocument::createTextNode

(PHP 5)

DOMDocument::createTextNode — Create new text node

Opis

DOMText DOMDocument::createTextNode ( string $content )

This function creates a new instance of class DOMText. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. metodą DOMNode->appendChild().

Parametry

content

The content of the text.

Zwracane wartości

The new DOMText or FALSE if an error occured.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node

DOMDocument::createProcessingInstruction
DOMDocument::getElementById
DOMDocument


Searches for an element with a certain id

DOMDocument::createTextNode
DOMDocument::getElementsByTagName
DOMDocument
PHP Manual

DOMDocument::getElementById

(PHP 5)

DOMDocument::getElementById — Searches for an element with a certain id

Opis

DOMElement DOMDocument::getElementById ( string $elementId )

This function is similar to DOMDocument::getElementsByTagName but searches for an element with a given id.

For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.

Parametry

elementId

The unique id value for an element.

Zwracane wartości

Returns the DOMElement or NULL if the element is not found.

Przykłady

Przykład #1 DOMDocument::getElementById() Example

<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is books is: " . $doc->getElementById('books')->tagName . "\n";

?>

Powyższy przykład wyświetli:

The element whose id is books is: chapter

Zobacz też:

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name

DOMDocument::createTextNode
DOMDocument::getElementsByTagName
DOMDocument


Searches for all elements with given local tag name

DOMDocument::getElementById
DOMDocument::getElementsByTagNameNS
DOMDocument
PHP Manual

DOMDocument::getElementsByTagName

(PHP 5)

DOMDocument::getElementsByTagName — Searches for all elements with given local tag name

Opis

DOMNodeList DOMDocument::getElementsByTagName ( string $name )

This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.

Parametry

name

The local name (without namespace) of the tag to match on. The special value * matches all tags.

Zwracane wartości

A new DOMNodeList object containing all the matched elements.

Przykłady

Przykład #1 Basic Usage Example

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
 <book>Patterns of Enterprise Application Architecture</book>
 <book>Design Patterns: Elements of Reusable Software Design</book>
 <book>Clean Code</book>
</books>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
    echo $book->nodeValue, PHP_EOL;
}
?>

Powyższy przykład wyświetli:

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

Zobacz też:

  • DOMDocument::getElementsByTagNameNS() - Searches for all elements with given tag name in specified namespace

DOMDocument::getElementById
DOMDocument::getElementsByTagNameNS
DOMDocument


Searches for all elements with given tag name in specified namespace

DOMDocument::getElementsByTagName
DOMDocument::importNode
DOMDocument
PHP Manual

DOMDocument::getElementsByTagNameNS

(PHP 5)

DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace

Opis

DOMNodeList DOMDocument::getElementsByTagNameNS ( string $namespaceURI , string $localName )

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

Parametry

namespaceURI

The namespace URI of the elements to match on. The special value * matches all namespaces.

localName

The local name of the elements to match on. The special value * matches all local names.

Zwracane wartości

A new DOMNodeList object containing all the matched elements.

Przykłady

Przykład #1 Get all the XInclude elements

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
 <xi:include href="book.xml">
  <xi:fallback>
   <error>xinclude: book.xml not found</error>
  </xi:fallback>
 </xi:include>
 <include>
  This is another namespace
 </include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// load the XML string defined above
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
    echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

Powyższy przykład wyświetli:

local name: include, prefix: xi
local name: fallback, prefix: xi

Zobacz też:

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name

DOMDocument::getElementsByTagName
DOMDocument::importNode
DOMDocument


Import node into current document

DOMDocument::getElementsByTagNameNS
DOMDocument::load
DOMDocument
PHP Manual

DOMDocument::importNode

(PHP 5)

DOMDocument::importNode — Import node into current document

Opis

DOMNode DOMDocument::importNode ( DOMNode $importedNode [, bool $deep ] )

This function returns a copy of the node to import and associates it with the current document.

Parametry

importedNode

The node to import.

deep

If set to TRUE, this method will recursively import the subtree under the importedNode.

Informacja:

To copy the nodes attributes deep needs to be set to TRUE

Zwracane wartości

The copied node or FALSE, if it cannot be copied.

Błędy/Wyjątki

DOMException is thrown if node cannot be imported.

Przykłady

Przykład #1 DOMDocument::importNode() example

Copying nodes between documents.

<?php

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");

// The node we want to import to a new document
$node = $orgdoc->getElementsByTagName("element")->item(0);

// Create a new document
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;

// Add some markup
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

echo "The 'new document' before copying nodes into it:\n";
echo $newdoc->saveXML();

// Import the node, and all its children, to the document
$node = $newdoc->importNode($node, true);
// And then append it to the "<root>" node
$newdoc->documentElement->appendChild($node);

echo "\nThe 'new document' after copying the nodes into it:\n";
echo $newdoc->saveXML();
?>

Powyższy przykład wyświetli:

The 'new document' before copying nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
</root>

The 'new document' after copying the nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
  <element>
    <child>text in child</child>
  </element>
</root>

DOMDocument::getElementsByTagNameNS
DOMDocument::load
DOMDocument


Load XML from a file

DOMDocument::importNode
DOMDocument::loadHTML
DOMDocument
PHP Manual

DOMDocument::load

(PHP 5)

DOMDocument::load — Load XML from a file

Opis

mixed DOMDocument::load ( string $filename [, int $options = 0 ] )

Loads an XML document from a file.

Ostrzeżenie

Unix style paths with forward slashes can cause significant performance degradation on Windows systems; be sure to call realpath() in such a case.

Parametry

filename

The path to the XML document.

options

Bitwise OR of the libxml option constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If called statically, returns a DOMDocument lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

Przykłady

Przykład #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

Zobacz też:

  • DOMDocument::loadXML() - Load XML from a string
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string

DOMDocument::importNode
DOMDocument::loadHTML
DOMDocument


Load HTML from a string

DOMDocument::load
DOMDocument::loadHTMLFile
DOMDocument
PHP Manual

DOMDocument::loadHTML

(PHP 5)

DOMDocument::loadHTML — Load HTML from a string

Opis

bool DOMDocument::loadHTML ( string $source )

The function parses the HTML contained in the string source. Unlike loading XML, HTML does not have to be well-formed to load. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Parametry

source

The HTML string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If called statically, returns a DOMDocument lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

While malformed HTML should load successfully, this function may generate E_WARNING errors when it encounters bad markup. libxml's error handling functions may be used to handle these errors.

Przykłady

Przykład #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

Zobacz też:

  • DOMDocument::loadHTMLFile() - Load HTML from a file
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting

DOMDocument::load
DOMDocument::loadHTMLFile
DOMDocument


Load HTML from a file

DOMDocument::loadHTML
DOMDocument::loadXML
DOMDocument
PHP Manual

DOMDocument::loadHTMLFile

(PHP 5)

DOMDocument::loadHTMLFile — Load HTML from a file

Opis

bool DOMDocument::loadHTMLFile ( string $filename )

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.

Parametry

filename

The path to the HTML file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If called statically, returns a DOMDocument lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

While malformed HTML should load successfully, this function may generate E_WARNING errors when it encounters bad markup. libxml's error handling functions may be used to handle these errors.

Przykłady

Przykład #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

Zobacz też:

  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting

DOMDocument::loadHTML
DOMDocument::loadXML
DOMDocument


Load XML from a string

DOMDocument::loadHTMLFile
DOMDocument::normalizeDocument
DOMDocument
PHP Manual

DOMDocument::loadXML

(PHP 5)

DOMDocument::loadXML — Load XML from a string

Opis

mixed DOMDocument::loadXML ( string $source [, int $options = 0 ] )

Loads an XML document from a string.

Parametry

source

The string containing the XML.

options

Bitwise OR of the libxml option constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If called statically, returns a DOMDocument lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

Przykłady

Przykład #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Przykład #2 Static invocation of loadXML

<?php
// Issues an E_STRICT error
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Zobacz też:

  • DOMDocument::load() - Load XML from a file
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string

DOMDocument::loadHTMLFile
DOMDocument::normalizeDocument
DOMDocument


Normalizes the document

DOMDocument::loadXML
DOMDocument::registerNodeClass
DOMDocument
PHP Manual

DOMDocument::normalizeDocument

(PHP 5)

DOMDocument::normalizeDocument — Normalizes the document

Opis

void DOMDocument::normalizeDocument ( void )

This method acts as if you saved and then loaded the document, putting the document in a "normal" form.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • » The DOM Specification
  • DOMNode::normalize() - Normalizes the node

DOMDocument::loadXML
DOMDocument::registerNodeClass
DOMDocument


Register extended class used to create base node type

DOMDocument::normalizeDocument
DOMDocument::relaxNGValidate
DOMDocument
PHP Manual

DOMDocument::registerNodeClass

(PHP 5 >= 5.2.0)

DOMDocument::registerNodeClass — Register extended class used to create base node type

Opis

bool DOMDocument::registerNodeClass ( string $baseclass , string $extendedclass )

This method allows you to register your own extended DOM class to be used afterward by the PHP DOM extension.

This method is not part of the DOM standard.

Parametry

baseclass

The DOM class that you want to extend. You can find a list of these classes in the chapter introduction.

extendedclass

Your extended class name. If NULL is provided, any previously registered class extending baseclass will be removed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
PHP 5.2.2 | Prior to 5.2.2, a previously registered extendedclass had to be unregistered before being able to register a new class extending the same baseclass.

Przykłady

Przykład #1 Adding a new method to DOMElement to ease our code

<?php

class myElement extends DOMElement {
   function appendElement($name) {
      return $this->appendChild(new myElement($name));
   }
}

class myDocument extends DOMDocument {
   function setRoot($name) {
      return $this->appendChild(new myElement($name));
   }
}

$doc = new myDocument();
$doc->registerNodeClass('DOMElement', 'myElement');

// From now on, adding an element to another costs only one method call !
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');

echo $doc->saveXML();

?>

Powyższy przykład wyświetli:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Przykład #2 Retrieving elements as custom class

<?php
class myElement extends DOMElement {
    public function __toString() {
        return $this->nodeValue;
    }
}

$doc = new DOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");

$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));

// And take advantage of the __toString method..
echo $element;
?>

Powyższy przykład wyświetli:

string(9) "myElement"
text in child

Przykład #3 Retrieving owner document

When instantiating a custom DOMDocument the ownerDocument property will refer to the instantiated class, meaning there is no need (and in fact not possible) to use DOMDocument::registerNodeClass() with DOMDocument

<?php
class myDOMDocument extends DOMDocument {
}

class myOtherDOMDocument extends DOMDocument {
}

// Create myDOMDocument with some XML
$doc = new myDOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");

$child = $doc->getElementsByTagName("child")->item(0);

// The current owner of the node is myDOMDocument
var_dump(get_class($child->ownerDocument));

// Import a node from myDOMDocument
$newdoc = new myOtherDOMDocument;
$child = $newdoc->importNode($child);

// The new owner of the node has changed to myOtherDOMDocument
var_dump(get_class($child->ownerDocument));
?>

Powyższy przykład wyświetli:

string(13) "myDOMDocument"
string(18) "myOtherDOMDocument"

DOMDocument::normalizeDocument
DOMDocument::relaxNGValidate
DOMDocument


Performs relaxNG validation on the document

DOMDocument::registerNodeClass
DOMDocument::relaxNGValidateSource
DOMDocument
PHP Manual

DOMDocument::relaxNGValidate

(PHP 5)

DOMDocument::relaxNGValidate — Performs relaxNG validation on the document

Opis

bool DOMDocument::relaxNGValidate ( string $filename )

Performs » relaxNG validation on the document based on the given RNG schema.

Parametry

filename

The RNG file.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD

DOMDocument::registerNodeClass
DOMDocument::relaxNGValidateSource
DOMDocument


Performs relaxNG validation on the document

DOMDocument::relaxNGValidate
DOMDocument::save
DOMDocument
PHP Manual

DOMDocument::relaxNGValidateSource

(PHP 5)

DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document

Opis

bool DOMDocument::relaxNGValidateSource ( string $source )

Performs » relaxNG validation on the document based on the given RNG source.

Parametry

source

A string containing the RNG schema.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD

DOMDocument::relaxNGValidate
DOMDocument::save
DOMDocument


Dumps the internal XML tree back into a file

DOMDocument::relaxNGValidateSource
DOMDocument::saveHTML
DOMDocument
PHP Manual

DOMDocument::save

(PHP 5)

DOMDocument::save — Dumps the internal XML tree back into a file

Opis

int DOMDocument::save ( string $filename [, int $options ] )

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parametry

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Zwracane wartości

Returns the number of bytes written or FALSE if an error occurred.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the options parameter

Przykłady

Przykład #1 Saving a DOM tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes

?>

Zobacz też:

  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string

DOMDocument::relaxNGValidateSource
DOMDocument::saveHTML
DOMDocument


Dumps the internal document into a string using HTML formatting

DOMDocument::save
DOMDocument::saveHTMLFile
DOMDocument
PHP Manual

DOMDocument::saveHTML

(PHP 5)

DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting

Opis

string DOMDocument::saveHTML ([ DOMNode $node = NULL ] )

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parametry

node

Optional parameter to output a subset of the document.

Zwracane wartości

Returns the HTML, or FALSE if an error occurred.

Rejestr zmian

Wersja | Opis
5.3.6 | The node parameter was added.

Przykłady

Przykład #1 Saving a HTML tree into a string

<?php

$doc = new DOMDocument('1.0');

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

Zobacz też:

  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file

DOMDocument::save
DOMDocument::saveHTMLFile
DOMDocument


Dumps the internal document into a file using HTML formatting

DOMDocument::saveHTML
DOMDocument::saveXML
DOMDocument
PHP Manual

DOMDocument::saveHTMLFile

(PHP 5)

DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting

Opis

int DOMDocument::saveHTMLFile ( string $filename )

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parametry

filename

The path to the saved HTML document.

Zwracane wartości

Returns the number of bytes written or FALSE if an error occurred.

Przykłady

Przykład #1 Saving a HTML tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Wrote: 129 bytes

?>

Zobacz też:

  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file

DOMDocument::saveHTML
DOMDocument::saveXML
DOMDocument


Dumps the internal XML tree back into a string

DOMDocument::saveHTMLFile
DOMDocument::schemaValidate
DOMDocument
PHP Manual

DOMDocument::saveXML

(PHP 5)

DOMDocument::saveXML — Dumps the internal XML tree back into a string

Opis

string DOMDocument::saveXML ([ DOMNode $node [, int $options ]] )

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parametry

node

Use this parameter to output only a specific node without XML declaration rather than the entire document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Zwracane wartości

Returns the XML, or FALSE if an error occurred.

Błędy/Wyjątki

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

Rejestr zmian

Wersja | Opis
5.1.0 | Added the options parameter

Przykłady

Przykład #1 Saving a DOM tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Saving only the title part:\n";
echo $doc->saveXML($title);

?>

Powyższy przykład wyświetli:

Saving all the document:
<?xml version="1.0"?>
<book>
  <title>This is the title</title>
</book>

Saving only the title part:
<title>This is the title</title>

Zobacz też:

  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string

DOMDocument::saveHTMLFile
DOMDocument::schemaValidate
DOMDocument


Validates a document based on a schema

DOMDocument::saveXML
DOMDocument::schemaValidateSource
DOMDocument
PHP Manual

DOMDocument::schemaValidate

(PHP 5)

DOMDocument::schemaValidate — Validates a document based on a schema

Opis

bool DOMDocument::schemaValidate ( string $filename )

Validates a document based on the given schema file.

Parametry

filename

The path to the schema.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD

DOMDocument::saveXML
DOMDocument::schemaValidateSource
DOMDocument


Validates a document based on a schema

DOMDocument::schemaValidate
DOMDocument::validate
DOMDocument
PHP Manual

DOMDocument::schemaValidateSource

(PHP 5)

DOMDocument::schemaValidateSource — Validates a document based on a schema

Opis

bool DOMDocument::schemaValidateSource ( string $source )

Validates a document based on a schema defined in the given string.

Parametry

source

A string containing the schema.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMDocument::schemaValidate() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD

DOMDocument::schemaValidate
DOMDocument::validate
DOMDocument


Validates the document based on its DTD

DOMDocument::schemaValidateSource
DOMDocument::xinclude
DOMDocument
PHP Manual

DOMDocument::validate

(PHP 5)

DOMDocument::validate — Validates the document based on its DTD

Opis

bool DOMDocument::validate ( void )

Validates the document based on its DTD.

You can also use the validateOnParse property of DOMDocument to make a DTD validation.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If the document have no DTD attached, this method will return FALSE.

Przykłady

Przykład #1 Example of DTD validation

<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
    echo "This document is valid!\n";
}
?>

You can also validate your XML file while loading it:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->Load('book.xml');
?>

Zobacz też:

  • DOMDocument::schemaValidate() - Validates a document based on a schema
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document

DOMDocument::schemaValidateSource
DOMDocument::xinclude
DOMDocument


Substitutes XIncludes in a DOMDocument Object

DOMDocument::validate
DOMDocumentFragment
DOMDocument
PHP Manual

DOMDocument::xinclude

(PHP 5)

DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

Opis

int DOMDocument::xinclude ([ int $options ] )

This method substitutes » XIncludes in a DOMDocument object.

Informacja:

Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

Parametry

options

libxml parameters. Available since PHP 5.1.0 and Libxml 2.6.7.

Zwracane wartości

Returns the number of XIncludes in the document, -1 if some processing failed, or FALSE if there were no substitutions.

Przykłady

Przykład #1 DOMDocument::xinclude() example

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
 <title>Books of the other guy..</title>
 <para>
  <xi:include href="book.xml">
   <xi:fallback>
    <error>xinclude: book.xml not found</error>
   </xi:fallback>
  </xi:include>
 </para>
</chapter>
EOD;

$dom = new DOMDocument;

// let's have a nice output
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// load the XML string defined above
$dom->loadXML($xml);

// substitute xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

Powyższy przykład wyświetli coś podobnego do:

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>

DOMDocument::validate
DOMDocumentFragment
DOMDocument


The DOMDocumentFragment class

(PHP 5)

Krótki opis klasy

DOMDocumentFragment extends DOMNode {
/* Właściwości */
/* Metody */
bool appendXML ( string $data )
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Spis treści

  • DOMDocumentFragment::appendXML — Append raw XML data
DOMDocument::xinclude
DOMDocumentFragment::appendXML
DOM


Append raw XML data

DOMDocumentFragment
DOMDocumentType
DOMDocumentFragment
PHP Manual

DOMDocumentFragment::appendXML

(PHP 5 >= 5.1.0)

DOMDocumentFragment::appendXML — Append raw XML data

Opis

bool DOMDocumentFragment::appendXML ( string $data )

Appends raw XML data to a DOMDocumentFragment.

This method is not part of the DOM standard. It was created as a simpler approach for appending an XML DocumentFragment in a DOMDocument.

If you want to stick to the standards, you will have to create a temporary DOMDocument with a dummy root and then loop through the child nodes of the root of your XML data to append them.

Parametry

data

XML to append.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Appending XML data to your document

<?php
$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML();
?>

Powyższy przykład wyświetli:

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

DOMDocumentFragment
DOMDocumentType
DOMDocumentFragment


The DOMDocumentType class

(PHP 5)

Wstęp

Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.

Krótki opis klasy

DOMDocumentType extends DOMNode {
/* Właściwości */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $name ;
readonly public DOMNamedNodeMap $entities ;
readonly public DOMNamedNodeMap $notations ;
readonly public string $internalSubset ;
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

publicId

The public identifier of the external subset.

systemId

The system identifier of the external subset. This may be an absolute URI or not.

name

The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

entities

A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.

notations

A DOMNamedNodeMap containing the notations declared in the DTD.

internalSubset

The internal subset as a string, or null if there is none. This is does not contain the delimiting square brackets.

DOMDocumentFragment::appendXML
DOMElement
DOM


The DOMElement class

(PHP 5)

Krótki opis klasy

DOMElement extends DOMNode {
/* Właściwości */
readonly public bool $schemaTypeInfo ;
readonly public string $tagName ;
/* Metody */
__construct ( string $name [, string $value [, string $namespaceURI ]] )
string getAttribute ( string $name )
DOMAttr getAttributeNode ( string $name )
DOMAttr getAttributeNodeNS ( string $namespaceURI , string $localName )
string getAttributeNS ( string $namespaceURI , string $localName )
DOMNodeList getElementsByTagName ( string $name )
DOMNodeList getElementsByTagNameNS ( string $namespaceURI , string $localName )
bool hasAttribute ( string $name )
bool hasAttributeNS ( string $namespaceURI , string $localName )
bool removeAttribute ( string $name )
bool removeAttributeNode ( DOMAttr $oldnode )
bool removeAttributeNS ( string $namespaceURI , string $localName )
DOMAttr setAttribute ( string $name , string $value )
DOMAttr setAttributeNode ( DOMAttr $attr )
DOMAttr setAttributeNodeNS ( DOMAttr $attr )
void setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value )
void setIdAttribute ( string $name , bool $isId )
void setIdAttributeNode ( DOMAttr $attr , bool $isId )
void setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId )
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

schemaTypeInfo

Not implemented yet, always return NULL

tagName

The element name

Notatki

Informacja:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or Iconv for other encodings.

Spis treści

  • DOMElement::__construct — Creates a new DOMElement object
  • DOMElement::getAttribute — Returns value of attribute
  • DOMElement::getAttributeNode — Returns attribute node
  • DOMElement::getAttributeNodeNS — Returns attribute node
  • DOMElement::getAttributeNS — Returns value of attribute
  • DOMElement::getElementsByTagName — Gets elements by tagname
  • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
  • DOMElement::hasAttribute — Checks to see if attribute exists
  • DOMElement::hasAttributeNS — Checks to see if attribute exists
  • DOMElement::removeAttribute — Removes attribute
  • DOMElement::removeAttributeNode — Removes attribute
  • DOMElement::removeAttributeNS — Removes attribute
  • DOMElement::setAttribute — Adds new attribute
  • DOMElement::setAttributeNode — Adds new attribute node to element
  • DOMElement::setAttributeNodeNS — Adds new attribute node to element
  • DOMElement::setAttributeNS — Adds new attribute
  • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID
DOMDocumentType
DOMElement::__construct
DOM


Creates a new DOMElement object

DOMElement
DOMElement::getAttribute
DOMElement
PHP Manual

DOMElement::__construct

(PHP 5)

DOMElement::__construct — Creates a new DOMElement object

Opis

DOMElement::__construct ( string $name [, string $value [, string $namespaceURI ]] )

Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createElement or DOMDocument::createElementNS.

Parametry

name

The tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.

value

The value of the element.

namespaceURI

A namespace URI to create the element within a specific namespace.

Przykłady

Przykład #1 Creating a new DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="utf-8"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

Zobacz też:

  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace

DOMElement
DOMElement::getAttribute
DOMElement


Returns value of attribute

DOMElement::__construct
DOMElement::getAttributeNode
DOMElement
PHP Manual

DOMElement::getAttribute

(PHP 5)

DOMElement::getAttribute — Returns value of attribute

Opis

string DOMElement::getAttribute ( string $name )

Gets the value of the attribute with name name for the current node.

Parametry

name

The name of the attribute.

Zwracane wartości

The value of the attribute, or an empty string if no attribute with the given name is found.

Zobacz też:

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttribute() - Adds new attribute
  • DOMElement::removeAttribute() - Removes attribute

DOMElement::__construct
DOMElement::getAttributeNode
DOMElement


Returns attribute node

DOMElement::getAttribute
DOMElement::getAttributeNodeNS
DOMElement
PHP Manual

DOMElement::getAttributeNode

(PHP 5)

DOMElement::getAttributeNode — Returns attribute node

Opis

DOMAttr DOMElement::getAttributeNode ( string $name )

Returns the attribute node with name name for the current element.

Parametry

name

The name of the attribute.

Zwracane wartości

The attribute node.

Zobacz też:

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttributeNode() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute

DOMElement::getAttribute
DOMElement::getAttributeNodeNS
DOMElement


Returns attribute node

DOMElement::getAttributeNode
DOMElement::getAttributeNS
DOMElement
PHP Manual

DOMElement::getAttributeNodeNS

(PHP 5)

DOMElement::getAttributeNodeNS — Returns attribute node

Opis

DOMAttr DOMElement::getAttributeNodeNS ( string $namespaceURI , string $localName )

Returns the attribute node in namespace namespaceURI with local name localName for the current node.

Parametry

namespaceURI

The namespace URI.

localName

The local name.

Zwracane wartości

The attribute node.

Zobacz też:

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNodeNS() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute

DOMElement::getAttributeNode
DOMElement::getAttributeNS
DOMElement


Returns value of attribute

DOMElement::getAttributeNodeNS
DOMElement::getElementsByTagName
DOMElement
PHP Manual

DOMElement::getAttributeNS

(PHP 5)

DOMElement::getAttributeNS — Returns value of attribute

Opis

string DOMElement::getAttributeNS ( string $namespaceURI , string $localName )

Gets the value of the attribute in namespace namespaceURI with local name localName for the current node.

Parametry

namespaceURI

The namespace URI.

localName

The local name.

Zwracane wartości

The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found.

Zobacz też:

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute

DOMElement::getAttributeNodeNS
DOMElement::getElementsByTagName
DOMElement


Gets elements by tagname

DOMElement::getAttributeNS
DOMElement::getElementsByTagNameNS
DOMElement
PHP Manual

DOMElement::getElementsByTagName

(PHP 5)

DOMElement::getElementsByTagName — Gets elements by tagname

Opis

DOMNodeList DOMElement::getElementsByTagName ( string $name )

This function returns a new instance of the class DOMNodeList of all descendant elements with a given tag name, in the order in which they are encountered in a preorder traversal of this element tree.

Parametry

name

The tag name. Use * to return all elements within the element tree.

Zwracane wartości

This function returns a new instance of the class DOMNodeList of all matched elements.

Zobacz też:

  • DOMElement::getElementsByTagNameNS() - Get elements by namespaceURI and localName

DOMElement::getAttributeNS
DOMElement::getElementsByTagNameNS
DOMElement


Get elements by namespaceURI and localName

DOMElement::getElementsByTagName
DOMElement::hasAttribute
DOMElement
PHP Manual

DOMElement::getElementsByTagNameNS

(PHP 5)

DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName

Opis

DOMNodeList DOMElement::getElementsByTagNameNS ( string $namespaceURI , string $localName )

This function fetch all the descendant elements with a given localName and namespaceURI.

Parametry

namespaceURI

The namespace URI.

localName

The local name. Use * to return all elements within the element tree.

Zwracane wartości

This function returns a new instance of the class DOMNodeList of all matched elements in the order in which they are encountered in a preorder traversal of this element tree.

Zobacz też:

  • DOMElement::getElementsByTagName() - Gets elements by tagname

DOMElement::getElementsByTagName
DOMElement::hasAttribute
DOMElement


Checks to see if attribute exists

DOMElement::getElementsByTagNameNS
DOMElement::hasAttributeNS
DOMElement
PHP Manual

DOMElement::hasAttribute

(PHP 5)

DOMElement::hasAttribute — Checks to see if attribute exists

Opis

bool DOMElement::hasAttribute ( string $name )

Indicates whether attribute named name exists as a member of the element.

Parametry

name

The attribute name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new attribute
  • DOMElement::removeAttribute() - Removes attribute

DOMElement::getElementsByTagNameNS
DOMElement::hasAttributeNS
DOMElement


Checks to see if attribute exists

DOMElement::hasAttribute
DOMElement::removeAttribute
DOMElement
PHP Manual

DOMElement::hasAttributeNS

(PHP 5)

DOMElement::hasAttributeNS — Checks to see if attribute exists

Opis

bool DOMElement::hasAttributeNS ( string $namespaceURI , string $localName )

Indicates whether attribute in namespace namespaceURI named localName exists as a member of the element.

Parametry

namespaceURI

The namespace URI.

localName

The local name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute

DOMElement::hasAttribute
DOMElement::removeAttribute
DOMElement


Removes attribute

DOMElement::hasAttributeNS
DOMElement::removeAttributeNode
DOMElement
PHP Manual

DOMElement::removeAttribute

(PHP 5)

DOMElement::removeAttribute — Removes attribute

Opis

bool DOMElement::removeAttribute ( string $name )

Removes attribute named name from the element.

Parametry

name

The name of the attribute.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Zobacz też:

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new attribute

DOMElement::hasAttributeNS
DOMElement::removeAttributeNode
DOMElement


Removes attribute

DOMElement::removeAttribute
DOMElement::removeAttributeNS
DOMElement
PHP Manual

DOMElement::removeAttributeNode

(PHP 5)

DOMElement::removeAttributeNode — Removes attribute

Opis

bool DOMElement::removeAttributeNode ( DOMAttr $oldnode )

Removes attribute oldnode from the element.

Parametry

oldnode

The attribute node.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND_ERROR

Raised if oldnode is not an attribute of the element.

Zobacz też:

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::setAttributeNode() - Adds new attribute node to element

DOMElement::removeAttribute
DOMElement::removeAttributeNS
DOMElement


Removes attribute

DOMElement::removeAttributeNode
DOMElement::setAttribute
DOMElement
PHP Manual

DOMElement::removeAttributeNS

(PHP 5)

DOMElement::removeAttributeNS — Removes attribute

Opis

bool DOMElement::removeAttributeNS ( string $namespaceURI , string $localName )

Removes attribute is namespace namespaceURI named localName from the element.

Parametry

namespaceURI

The namespace URI.

localName

The local name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Zobacz też:

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute

DOMElement::removeAttributeNode
DOMElement::setAttribute
DOMElement


Adds new attribute

DOMElement::removeAttributeNS
DOMElement::setAttributeNode
DOMElement
PHP Manual

DOMElement::setAttribute

(PHP 5)

DOMElement::setAttribute — Adds new attribute

Opis

DOMAttr DOMElement::setAttribute ( string $name , string $value )

Sets an attribute with name name to the given value. If the attribute does not exist, it will be created.

Parametry

name

The name of the attribute.

value

The value of the attribute.

Zwracane wartości

The new DOMAttr or FALSE if an error occured.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Przykłady

Przykład #1 Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

Zobacz też:

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::removeAttribute() - Removes attribute

DOMElement::removeAttributeNS
DOMElement::setAttributeNode
DOMElement


Adds new attribute node to element

DOMElement::setAttribute
DOMElement::setAttributeNodeNS
DOMElement
PHP Manual

DOMElement::setAttributeNode

(PHP 5)

DOMElement::setAttributeNode — Adds new attribute node to element

Opis

DOMAttr DOMElement::setAttributeNode ( DOMAttr $attr )

Adds new attribute node attr to element.

Parametry

attr

The attribute node.

Zwracane wartości

Returns old node if the attribute has been replaced or NULL.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Zobacz też:

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute

DOMElement::setAttribute
DOMElement::setAttributeNodeNS
DOMElement


Adds new attribute node to element

DOMElement::setAttributeNode
DOMElement::setAttributeNS
DOMElement
PHP Manual

DOMElement::setAttributeNodeNS

(PHP 5)

DOMElement::setAttributeNodeNS — Adds new attribute node to element

Opis

DOMAttr DOMElement::setAttributeNodeNS ( DOMAttr $attr )

Adds new attribute node attr to element.

Parametry

attr

The attribute node.

Zwracane wartości

Returns the old node if the attribute has been replaced.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Zobacz też:

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNodeNS() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute

DOMElement::setAttributeNode
DOMElement::setAttributeNS
DOMElement


Adds new attribute

DOMElement::setAttributeNodeNS
DOMElement::setIdAttribute
DOMElement
PHP Manual

DOMElement::setAttributeNS

(PHP 5)

DOMElement::setAttributeNS — Adds new attribute

Opis

void DOMElement::setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value )

Sets an attribute with namespace namespaceURI and name name to the given value. If the attribute does not exist, it will be created.

Parametry

namespaceURI

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.

Zobacz też:

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::removeAttributeNS() - Removes attribute

DOMElement::setAttributeNodeNS
DOMElement::setIdAttribute
DOMElement


Declares the attribute specified by name to be of type ID

DOMElement::setAttributeNS
DOMElement::setIdAttributeNode
DOMElement
PHP Manual

DOMElement::setIdAttribute

(PHP 5)

DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID

Opis

void DOMElement::setIdAttribute ( string $name , bool $isId )

Declares the attribute name to be of type ID.

Parametry

name

The name of the attribute.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

Zobacz też:

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID

DOMElement::setAttributeNS
DOMElement::setIdAttributeNode
DOMElement


Declares the attribute specified by node to be of type ID

DOMElement::setIdAttribute
DOMElement::setIdAttributeNS
DOMElement
PHP Manual

DOMElement::setIdAttributeNode

(PHP 5)

DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID

Opis

void DOMElement::setIdAttributeNode ( DOMAttr $attr , bool $isId )

Declares the attribute specified by attr to be of type ID.

Parametry

attr

The attribute node.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

Zobacz też:

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID

DOMElement::setIdAttribute
DOMElement::setIdAttributeNS
DOMElement


Declares the attribute specified by local name and namespace URI to be of type ID

DOMElement::setIdAttributeNode
DOMEntity
DOMElement
PHP Manual

DOMElement::setIdAttributeNS

(PHP 5)

DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID

Opis

void DOMElement::setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId )

Declares the attribute specified by localName and namespaceURI to be of type ID.

Parametry

namespaceURI

The namespace URI of the attribute.

localName

The local name of the attribute, as prefix:tagname.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

Zobacz też:

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID

DOMElement::setIdAttributeNode
DOMEntity
DOMElement


The DOMEntity class

(PHP 5)

Wstęp

This interface represents a known entity, either parsed or unparsed, in an XML document.

Krótki opis klasy

DOMEntity extends DOMNode {
/* Właściwości */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $notationName ;
public string $actualEncoding ;
readonly public string $encoding ;
readonly public string $version ;
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

publicId

The public identifier associated with the entity if specified, and NULL otherwise.

systemId

The system identifier associated with the entity if specified, and NULL otherwise. This may be an absolute URI or not.

notationName

For unparsed entities, the name of the notation for the entity. For parsed entities, this is NULL.

actualEncoding

An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is NULL if it an entity from the internal subset or if it is not known.

encoding

An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is NULL otherwise.

version

An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is NULL otherwise.

DOMElement::setIdAttributeNS
DOMEntityReference
DOM


The DOMEntityReference class

(PHP 5)

Krótki opis klasy

DOMEntityReference extends DOMNode {
/* Właściwości */
/* Metody */
__construct ( string $name )
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Spis treści

  • DOMEntityReference::__construct — Creates a new DOMEntityReference object
DOMEntity
DOMEntityReference::__construct
DOM


Creates a new DOMEntityReference object

DOMEntityReference
DOMException
DOMEntityReference
PHP Manual

DOMEntityReference::__construct

(PHP 5)

DOMEntityReference::__construct — Creates a new DOMEntityReference object

Opis

DOMEntityReference::__construct ( string $name )

Creates a new DOMEntityReference object.

Parametry

name

The name of the entity reference.

Przykłady

Przykład #1 Creating a new DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>&nbsp;</root> */

?>

Zobacz też:

  • DOMDocument::createEntityReference() - Create new entity reference node

DOMEntityReference
DOMException
DOMEntityReference


The DOMException class

(PHP 5)

Wstęp

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also Exceptions.

Krótki opis klasy

DOMException extends Exception {
/* Właściwości */
readonly public int $code ;
/* 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

code

An integer indicating the type of error generated

DOMEntityReference::__construct
DOMImplementation
DOM


The DOMImplementation class

(PHP 5)

Wstęp

The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Krótki opis klasy

DOMImplementation {
/* Właściwości */
/* Metody */
__construct ( void )
DOMDocument createDocument ([ string $namespaceURI = NULL [, string $qualifiedName = NULL [, DOMDocumentType $doctype = NULL ]]] )
DOMDocumentType createDocumentType ([ string $qualifiedName = NULL [, string $publicId = NULL [, string $systemId = NULL ]]] )
bool hasFeature ( string $feature , string $version )
}

Spis treści

  • DOMImplementation::__construct — Creates a new DOMImplementation object
  • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
  • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
  • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature
DOMException
DOMImplementation::__construct
DOM


Creates a new DOMImplementation object

DOMImplementation
DOMImplementation::createDocument
DOMImplementation
PHP Manual

DOMImplementation::__construct

(PHP 5)

DOMImplementation::__construct — Creates a new DOMImplementation object

Opis

DOMImplementation::__construct ( void )

Creates a new DOMImplementation object.

DOMImplementation
DOMImplementation::createDocument
DOMImplementation


Creates a DOMDocument object of the specified type with its document element

DOMImplementation::__construct
DOMImplementation::createDocumentType
DOMImplementation
PHP Manual

DOMImplementation::createDocument

(PHP 5)

DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element

Opis

DOMDocument DOMImplementation::createDocument ([ string $namespaceURI = NULL [, string $qualifiedName = NULL [, DOMDocumentType $doctype = NULL ]]] )

Creates a DOMDocument object of the specified type with its document element.

Parametry

namespaceURI

The namespace URI of the document element to create.

qualifiedName

The qualified name of the document element to create.

doctype

The type of document to create or NULL.

Zwracane wartości

A new DOMDocument object. If namespaceURI, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

Błędy/Wyjątki

DOM_WRONG_DOCUMENT_ERR

Raised if doctype has already been used with a different document or was created from a different implementation.

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by namespaceURI and qualifiedName.

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

Zobacz też:

  • DOMDocument::__construct() - Creates a new DOMDocument object
  • DOMImplementation::createDocumentType() - Creates an empty DOMDocumentType object

DOMImplementation::__construct
DOMImplementation::createDocumentType
DOMImplementation


Creates an empty DOMDocumentType object

DOMImplementation::createDocument
DOMImplementation::hasFeature
DOMImplementation
PHP Manual

DOMImplementation::createDocumentType

(PHP 5)

DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object

Opis

DOMDocumentType DOMImplementation::createDocumentType ([ string $qualifiedName = NULL [, string $publicId = NULL [, string $systemId = NULL ]]] )

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

Parametry

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Zwracane wartości

A new DOMDocumentType node with its ownerDocument set to NULL.

Błędy/Wyjątki

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

Przykłady

Przykład #1 Creating a document with an attached DTD

<?php

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp->createDocument("", "", $dtd);

// Set other properties
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Create an empty element
$element = $dom->createElement('graph');

// Append the element
$dom->appendChild($element);

// Retrieve and print the document
echo $dom->saveXML();

?>

Powyższy przykład wyświetli:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

Zobacz też:

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element

DOMImplementation::createDocument
DOMImplementation::hasFeature
DOMImplementation


Test if the DOM implementation implements a specific feature

DOMImplementation::createDocumentType
DOMNamedNodeMap
DOMImplementation
PHP Manual

DOMImplementation::hasFeature

(PHP 5)

DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

Opis

bool DOMImplementation::hasFeature ( string $feature , string $version )

Test if the DOM implementation implements a specific feature.

You can find a list of all features in the » Conformance section of the DOM specification.

Parametry

feature

The feature to test.

version

The version number of the feature to test. In level 2, this can be either 2.0 or 1.0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

Przykłady

Przykład #1 Testing your DOM Implementation

<?php

$features = array(
  'Core'           => 'Core module',
  'XML'            => 'XML module',
  'HTML'           => 'HTML module',
  'Views'          => 'Views module',
  'Stylesheets'    => 'Style Sheets module',
  'CSS'            => 'CSS module',
  'CSS2'           => 'CSS2 module',
  'Events'         => 'Events module',
  'UIEvents'       => 'User interface Events module',
  'MouseEvents'    => 'Mouse Events module',
  'MutationEvents' => 'Mutation Events module',
  'HTMLEvents'     => 'HTML Events module',
  'Range'          => 'Range module',
  'Traversal'      => 'Traversal module'
);

foreach ($features as $key => $name) {
  if (DOMImplementation::hasFeature($key, '2.0')) {
    echo "Has feature $name\n";
  } else {
    echo "Missing feature $name\n";
  }
}

?>

Zobacz też:

  • DOMNode::isSupported() - Checks if feature is supported for specified version

DOMImplementation::createDocumentType
DOMNamedNodeMap
DOMImplementation


The DOMNamedNodeMap class

(PHP 5)

Krótki opis klasy

DOMNamedNodeMap {
/* Właściwości */
readonly public int $length ;
/* Metody */
DOMNode getNamedItem ( string $name )
DOMNode getNamedItemNS ( string $namespaceURI , string $localName )
DOMNode item ( int $index )
}

Właściwości

length

The number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.

Spis treści

  • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
  • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
  • DOMNamedNodeMap::item — Retrieves a node specified by index
DOMImplementation::hasFeature
DOMNamedNodeMap::getNamedItem
DOM


Retrieves a node specified by name

DOMNamedNodeMap
DOMNamedNodeMap::getNamedItemNS
DOMNamedNodeMap
PHP Manual

DOMNamedNodeMap::getNamedItem

(PHP 5)

DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name

Opis

DOMNode DOMNamedNodeMap::getNamedItem ( string $name )

Retrieves a node specified by its nodeName.

Parametry

name

The nodeName of the node to retrieve.

Zwracane wartości

A node (of any type) with the specified nodeName, or NULL if no node is found.

Zobacz też:

  • DOMNamedNodeMap::getNamedItemNS() - Retrieves a node specified by local name and namespace URI

DOMNamedNodeMap
DOMNamedNodeMap::getNamedItemNS
DOMNamedNodeMap


Retrieves a node specified by local name and namespace URI

DOMNamedNodeMap::getNamedItem
DOMNamedNodeMap::item
DOMNamedNodeMap
PHP Manual

DOMNamedNodeMap::getNamedItemNS

(PHP 5)

DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI

Opis

DOMNode DOMNamedNodeMap::getNamedItemNS ( string $namespaceURI , string $localName )

Retrieves a node specified by localName and namespaceURI.

Parametry

namespaceURI

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

Zwracane wartości

A node (of any type) with the specified local name and namespace URI, or NULL if no node is found.

Zobacz też:

  • DOMNamedNodeMap::getNamedItem() - Retrieves a node specified by name

DOMNamedNodeMap::getNamedItem
DOMNamedNodeMap::item
DOMNamedNodeMap


Retrieves a node specified by index

DOMNamedNodeMap::getNamedItemNS
DOMNode
DOMNamedNodeMap
PHP Manual

DOMNamedNodeMap::item

(PHP 5)

DOMNamedNodeMap::item — Retrieves a node specified by index

Opis

DOMNode DOMNamedNodeMap::item ( int $index )

Retrieves a node specified by index within the DOMNamedNodeMap object.

Parametry

index

Index into this map.

Zwracane wartości

The node at the indexth position in the map, or NULL if that is not a valid index (greater than or equal to the number of nodes in this map).

DOMNamedNodeMap::getNamedItemNS
DOMNode
DOMNamedNodeMap


The DOMNode class

(PHP 5)

Krótki opis klasy

DOMNode {
/* Właściwości */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Metody */
public DOMNode appendChild ( DOMNode $newnode )
public string C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode cloneNode ([ bool $deep ] )
public int getLineNo ( void )
public string getNodePath ( void )
public bool hasAttributes ( void )
public bool hasChildNodes ( void )
public DOMNode insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool isDefaultNamespace ( string $namespaceURI )
public bool isSameNode ( DOMNode $node )
public bool isSupported ( string $feature , string $version )
public string lookupNamespaceURI ( string $prefix )
public string lookupPrefix ( string $namespaceURI )
public void normalize ( void )
public DOMNode removeChild ( DOMNode $oldnode )
public DOMNode replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

nodeName

Returns the most accurate name for the current node type

nodeValue

The value of this node, depending on its type

nodeType

Gets the type of the node. One of the predefined XML_xxx_NODE constants

parentNode

The parent of this node

childNodes

A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.

firstChild

The first child of this node. If there is no such node, this returns NULL.

lastChild

The last child of this node. If there is no such node, this returns NULL.

previousSibling

The node immediately preceding this node. If there is no such node, this returns NULL.

nextSibling

The node immediately following this node. If there is no such node, this returns NULL.

attributes

A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or NULL otherwise.

ownerDocument

The DOMDocument object associated with this node.

namespaceURI

The namespace URI of this node, or NULL if it is unspecified.

prefix

The namespace prefix of this node, or NULL if it is unspecified.

localName

Returns the local part of the qualified name of this node.

baseURI

The absolute base URI of this node or NULL if the implementation wasn't able to obtain an absolute URI.

textContent

This attribute returns the text content of this node and its descendants.

Notatki

Informacja:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or Iconv for other encodings.

Zobacz też:

  • » W3C specification of Node

Spis treści

  • DOMNode::appendChild — Adds new child at the end of the children
  • DOMNode::C14N — Canonicalize nodes to a string
  • DOMNode::C14NFile — Canonicalize nodes to a file
  • DOMNode::cloneNode — Clones a node
  • DOMNode::getLineNo — Get line number for a node
  • DOMNode::getNodePath — Get an XPath for a node
  • DOMNode::hasAttributes — Checks if node has attributes
  • DOMNode::hasChildNodes — Checks if node has children
  • DOMNode::insertBefore — Adds a new child before a reference node
  • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
  • DOMNode::isSameNode — Indicates if two nodes are the same node
  • DOMNode::isSupported — Checks if feature is supported for specified version
  • DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix
  • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
  • DOMNode::normalize — Normalizes the node
  • DOMNode::removeChild — Removes child from list of children
  • DOMNode::replaceChild — Replaces a child
DOMNamedNodeMap::item
DOMNode::appendChild
DOM


Adds new child at the end of the children

DOMNode
DOMNode::C14N
DOMNode
PHP Manual

DOMNode::appendChild

(PHP 5)

DOMNode::appendChild — Adds new child at the end of the children

Opis

public DOMNode DOMNode::appendChild ( DOMNode $newnode )

This function appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument::createElement(), DOMDocument::createTextNode() etc. or simply by using any other node.

Parametry

newnode

The appended child.

Zwracane wartości

The node added.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

Przykłady

The following example will add a new element node to a fresh document.

Przykład #1 Adding a child

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Zobacz też:

  • DOMNode::removeChild() - Removes child from list of children
  • DOMNode::replaceChild() - Replaces a child

DOMNode
DOMNode::C14N
DOMNode


Canonicalize nodes to a string

DOMNode::appendChild
DOMNode::C14NFile
DOMNode
PHP Manual

DOMNode::C14N

(PHP 5 >= 5.2.0)

DOMNode::C14N — Canonicalize nodes to a string

Opis

public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )

Canonicalize nodes to a string

Parametry

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

with_comments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

ns_prefixes

An array of namespace prefixes to filter the nodes by.

Zwracane wartości

Returns canonicalized nodes as a string lub FALSE w przypadku niepowodzenia

Zobacz też:

  • DOMNode::C14NFile() - Canonicalize nodes to a file

DOMNode::appendChild
DOMNode::C14NFile
DOMNode


Canonicalize nodes to a file

DOMNode::C14N
DOMNode::cloneNode
DOMNode
PHP Manual

DOMNode::C14NFile

(PHP 5 >= 5.2.0)

DOMNode::C14NFile — Canonicalize nodes to a file

Opis

public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )

Canonicalize nodes to a file.

Parametry

uri

Path to write the output to.

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

with_comments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

ns_prefixes

An array of namespace prefixes to filter the nodes by.

Zwracane wartości

Number of bytes written lub FALSE w przypadku niepowodzenia

Zobacz też:

  • DOMNode::C14N() - Canonicalize nodes to a string

DOMNode::C14N
DOMNode::cloneNode
DOMNode


Clones a node

DOMNode::C14NFile
DOMNode::getLineNo
DOMNode
PHP Manual

DOMNode::cloneNode

(PHP 5)

DOMNode::cloneNode — Clones a node

Opis

public DOMNode DOMNode::cloneNode ([ bool $deep ] )

Creates a copy of the node.

Parametry

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to FALSE.

Zwracane wartości

The cloned node.

DOMNode::C14NFile
DOMNode::getLineNo
DOMNode


Get line number for a node

DOMNode::cloneNode
DOMNode::getNodePath
DOMNode
PHP Manual

DOMNode::getLineNo

(PHP 5 >= 5.3.0)

DOMNode::getLineNo — Get line number for a node

Opis

public int DOMNode::getLineNo ( void )

Gets line number for where the node is defined.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Always returns the line number where the node was defined in.

Przykłady

Przykład #1 DOMNode::getLineNo() example

<?php
// XML dump for below example
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node />
</root>
XML;

// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML($xml);

// Print where the line where the 'node' element was defined in
printf('The <node> tag is defined on line %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

Powyższy przykład wyświetli:

The <node> tag is defined in line 3

DOMNode::cloneNode
DOMNode::getNodePath
DOMNode


Get an XPath for a node

DOMNode::getLineNo
DOMNode::hasAttributes
DOMNode
PHP Manual

DOMNode::getNodePath

(PHP 5 >= 5.2.0)

DOMNode::getNodePath — Get an XPath for a node

Opis

public string DOMNode::getNodePath ( void )

Gets an XPath location path for the node.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a string containing the XPath, or NULL in case of an error.

Przykłady

Przykład #1 DOMNode::getNodePath() example

<?php
// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML('
<fruits>
 <apples>
  <apple>braeburn</apple>
  <apple>granny smith</apple>
 </apples>
 <pears>
  <pear>conference</pear>
 </pears>
</fruits>
');

// Print XPath for each element
foreach ($dom->getElementsByTagName('*') as $node) {
    echo $node->getNodePath() . "\n";
}
?>

Powyższy przykład wyświetli:

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

Zobacz też:

  • DOMXPath

DOMNode::getLineNo
DOMNode::hasAttributes
DOMNode


Checks if node has attributes

DOMNode::getNodePath
DOMNode::hasChildNodes
DOMNode
PHP Manual

DOMNode::hasAttributes

(PHP 5)

DOMNode::hasAttributes — Checks if node has attributes

Opis

public bool DOMNode::hasAttributes ( void )

This method checks if the node has attributes. The tested node has to be an XML_ELEMENT_NODE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMNode::hasChildNodes() - Checks if node has children

DOMNode::getNodePath
DOMNode::hasChildNodes
DOMNode


Checks if node has children

DOMNode::hasAttributes
DOMNode::insertBefore
DOMNode
PHP Manual

DOMNode::hasChildNodes

(PHP 5)

DOMNode::hasChildNodes — Checks if node has children

Opis

public bool DOMNode::hasChildNodes ( void )

This function checks if the node has children.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMNode::hasAttributes() - Checks if node has attributes

DOMNode::hasAttributes
DOMNode::insertBefore
DOMNode


Adds a new child before a reference node

DOMNode::hasChildNodes
DOMNode::isDefaultNamespace
DOMNode
PHP Manual

DOMNode::insertBefore

(PHP 5)

DOMNode::insertBefore — Adds a new child before a reference node

Opis

public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )

This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.

Parametry

newnode

The new node.

refnode

The reference node. If not supplied, newnode is appended to the children.

Zwracane wartości

The inserted node.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if refnode is not a child of this node.

DOMNode::hasChildNodes
DOMNode::isDefaultNamespace
DOMNode


Checks if the specified namespaceURI is the default namespace or not

DOMNode::insertBefore
DOMNode::isSameNode
DOMNode
PHP Manual

DOMNode::isDefaultNamespace

(PHP 5)

DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not

Opis

public bool DOMNode::isDefaultNamespace ( string $namespaceURI )

Tells whether namespaceURI is the default namespace.

Parametry

namespaceURI

The namespace URI to look for.

Zwracane wartości

Return TRUE if namespaceURI is the default namespace, FALSE otherwise.

DOMNode::insertBefore
DOMNode::isSameNode
DOMNode


Indicates if two nodes are the same node

DOMNode::isDefaultNamespace
DOMNode::isSupported
DOMNode
PHP Manual

DOMNode::isSameNode

(PHP 5)

DOMNode::isSameNode — Indicates if two nodes are the same node

Opis

public bool DOMNode::isSameNode ( DOMNode $node )

This function indicates if two nodes are the same node. The comparison is not based on content

Parametry

node

The compared node.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

DOMNode::isDefaultNamespace
DOMNode::isSupported
DOMNode


Checks if feature is supported for specified version

DOMNode::isSameNode
DOMNode::lookupNamespaceURI
DOMNode
PHP Manual

DOMNode::isSupported

(PHP 5)

DOMNode::isSupported — Checks if feature is supported for specified version

Opis

public bool DOMNode::isSupported ( string $feature , string $version )

Checks if the asked feature is supported for the specified version.

Parametry

feature

The feature to test. See the example of DOMImplementation::hasFeature() for a list of features.

version

The version number of the feature to test.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • DOMImplementation::hasFeature() - Test if the DOM implementation implements a specific feature

DOMNode::isSameNode
DOMNode::lookupNamespaceURI
DOMNode


Gets the namespace URI of the node based on the prefix

DOMNode::isSupported
DOMNode::lookupPrefix
DOMNode
PHP Manual

DOMNode::lookupNamespaceURI

(PHP 5)

DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix

Opis

public string DOMNode::lookupNamespaceURI ( string $prefix )

Gets the namespace URI of the node based on the prefix.

Parametry

prefix

The prefix of the namespace.

Zwracane wartości

The namespace URI of the node.

Zobacz też:

  • DOMNode::lookupPrefix() - Gets the namespace prefix of the node based on the namespace URI

DOMNode::isSupported
DOMNode::lookupPrefix
DOMNode


Gets the namespace prefix of the node based on the namespace URI

DOMNode::lookupNamespaceURI
DOMNode::normalize
DOMNode
PHP Manual

DOMNode::lookupPrefix

(PHP 5)

DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI

Opis

public string DOMNode::lookupPrefix ( string $namespaceURI )

Gets the namespace prefix of the node based on the namespace URI.

Parametry

namespaceURI

The namespace URI.

Zwracane wartości

The prefix of the namespace.

Zobacz też:

  • DOMNode::lookupNamespaceURI() - Gets the namespace URI of the node based on the prefix

DOMNode::lookupNamespaceURI
DOMNode::normalize
DOMNode


Normalizes the node

DOMNode::lookupPrefix
DOMNode::removeChild
DOMNode
PHP Manual

DOMNode::normalize

(PHP 5)

DOMNode::normalize — Normalizes the node

Opis

public void DOMNode::normalize ( void )

Normalizes the node.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • » The DOM Specification
  • DOMDocument::normalizeDocument() - Normalizes the document

DOMNode::lookupPrefix
DOMNode::removeChild
DOMNode


Removes child from list of children

DOMNode::normalize
DOMNode::replaceChild
DOMNode
PHP Manual

DOMNode::removeChild

(PHP 5)

DOMNode::removeChild — Removes child from list of children

Opis

public DOMNode DOMNode::removeChild ( DOMNode $oldnode )

This functions removes a child from a list of children.

Parametry

oldnode

The removed child.

Zwracane wartości

If the child could be removed the function returns the old child.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

Przykłady

The following example will delete the chapter element of our XML document.

Przykład #1 Removing a child

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

Powyższy przykład wyświetli:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>

</book>

Przykład #2 Preserving the parent node's namespace URI

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);

// copy the namespace URI
$nsuri = $book->namespaceURI;

// Delete the child node
$book->removeChild($chapter);

// paste the namespace URI back into the parent node
$book->namespaceURI = $nsuri;
?>

Notatki

Informacja:

After calling this method, the DOMNode::$namespaceURI property on the parent node will be reset to NULL. Above example shows how to work around it.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::replaceChild() - Replaces a child

DOMNode::normalize
DOMNode::replaceChild
DOMNode


Replaces a child

DOMNode::removeChild
DOMNodeList
DOMNode
PHP Manual

DOMNode::replaceChild

(PHP 5)

DOMNode::replaceChild — Replaces a child

Opis

public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )

This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

Parametry

newnode

The new node. It must be a member of the target document, i.e. created by one of the DOMDocument->createXXX() methods or imported in the document by DOMDocument::importNode.

oldnode

The old node.

Zwracane wartości

The old node or FALSE if an error occur.

Błędy/Wyjątki

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

Zobacz też:

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::removeChild() - Removes child from list of children

DOMNode::removeChild
DOMNodeList
DOMNode


The DOMNodeList class

(PHP 5)

Krótki opis klasy

Traversable
DOMNodeList {
/* Właściwości */
readonly public int $length ;
/* Metody */
DOMNode DOMNodelist::item ( int $index )
}

Właściwości

length

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

Spis treści

  • DOMNodelist::item — Retrieves a node specified by index
DOMNode::replaceChild
DOMNodelist::item
DOM


Retrieves a node specified by index

DOMNodeList
DOMNotation
DOMNodeList
PHP Manual

DOMNodelist::item

(PHP 5)

DOMNodelist::item — Retrieves a node specified by index

Opis

DOMNode DOMNodelist::item ( int $index )

Retrieves a node specified by index within the DOMNodeList object.

Wskazówka

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

Parametry

index

Index of the node into the collection.

Zwracane wartości

The node at the indexth position in the DOMNodeList, or NULL if that is not a valid index.

Przykłady

Przykład #1 Traversing all the entries of the table

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}

?>

Alternatively, you can use foreach, which is a much more convenient way:

<?php

foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}

?>

Powyższy przykład wyświetli:

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

DOMNodeList
DOMNotation
DOMNodeList


The DOMNotation class

(PHP 5)

Krótki opis klasy

DOMNotation extends DOMNode {
/* Właściwości */
readonly public string $publicId ;
readonly public string $systemId ;
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

publicId

Prop description

systemId

Prop description

DOMNodelist::item
DOMProcessingInstruction
DOM


The DOMProcessingInstruction class

(PHP 5)

Krótki opis klasy

DOMProcessingInstruction extends DOMNode {
/* Właściwości */
readonly public string $target ;
public string $data ;
/* Metody */
__construct ( string $name [, string $value ] )
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

target

Prop description

data

Prop description

Spis treści

  • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object
DOMNotation
DOMProcessingInstruction::__construct
DOM


Creates a new DOMProcessingInstruction object

DOMProcessingInstruction
DOMText
DOMProcessingInstruction
PHP Manual

DOMProcessingInstruction::__construct

(PHP 5)

DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

Opis

DOMProcessingInstruction::__construct ( string $name [, string $value ] )

Creates a new DOMProcessingInstruction object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createProcessingInstruction.

Parametry

name

The tag name of the processing instruction.

value

The value of the processing instruction.

Przykłady

Przykład #1 Creating a new DOMProcessingInstruction object

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML();

?>

Powyższy przykład wyświetli:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

Zobacz też:

  • DOMDocument::createProcessingInstruction() - Creates new PI node

DOMProcessingInstruction
DOMText
DOMProcessingInstruction


The DOMText class

(PHP 5)

Wstęp

The DOMText class inherits from DOMCharacterData and represents the textual content of a DOMElement or DOMAttr.

Krótki opis klasy

DOMText extends DOMCharacterData {
/* Właściwości */
readonly public string $wholeText ;
/* Metody */
public __construct ([ string $value ] )
public bool isWhitespaceInElementContent ( void )
public DOMText splitText ( int $offset )
/* Metody dziedziczone */
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

Właściwości

wholeText

Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes.

Spis treści

  • DOMText::__construct — Creates a new DOMText object
  • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
  • DOMText::splitText — Breaks this node into two nodes at the specified offset
DOMProcessingInstruction::__construct
DOMText::__construct
DOM


Creates a new DOMText object

DOMText
DOMText::isWhitespaceInElementContent
DOMText
PHP Manual

DOMText::__construct

(PHP 5)

DOMText::__construct — Creates a new DOMText object

Opis

public DOMText::__construct() ([ string $value ] )

Creates a new DOMText object.

Parametry

value

The value of the text node. If not supplied an empty text node is created.

Przykłady

Przykład #1 Creating a new DOMText

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMText('root value'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */

?>

Zobacz też:

  • DOMDocument::createTextNode() - Create new text node

DOMText
DOMText::isWhitespaceInElementContent
DOMText


Indicates whether this text node contains whitespace

DOMText::__construct
DOMText::splitText
DOMText
PHP Manual

DOMText::isWhitespaceInElementContent

(PHP 5)

DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace

Opis

public bool DOMText::isWhitespaceInElementContent ( void )

Indicates whether this text node contains whitespace. The text node is determined to contain whitespace in element content during the load of the document.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

DOMText::__construct
DOMText::splitText
DOMText


Breaks this node into two nodes at the specified offset

DOMText::isWhitespaceInElementContent
DOMXPath
DOMText
PHP Manual

DOMText::splitText

(PHP 5)

DOMText::splitText — Breaks this node into two nodes at the specified offset

Opis

public DOMText DOMText::splitText ( int $offset )

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

After being split, this node will contain all the content up to the offset. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

Parametry

offset

The offset at which to split, starting from 0.

Zwracane wartości

The new node of the same type, which contains all the content at and after the offset.

DOMText::isWhitespaceInElementContent
DOMXPath
DOMText


The DOMXPath class

(PHP 5)

Wstęp

Supports XPath 1.0

Krótki opis klasy

DOMXPath {
/* Właściwości */
public DOMDocument $document ;
/* Metody */
public __construct ( DOMDocument $doc )
public mixed evaluate ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )
public DOMNodeList query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )
public bool registerNamespace ( string $prefix , string $namespaceURI )
public void registerPhpFunctions ([ mixed $restrict ] )
}

Właściwości

document

Prop description

Spis treści

  • DOMXPath::__construct — Creates a new DOMXPath object
  • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
  • DOMXPath::query — Evaluates the given XPath expression
  • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
  • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions
DOMText::splitText
DOMXPath::__construct
DOM


Creates a new DOMXPath object

DOMXPath
DOMXPath::evaluate
DOMXPath
PHP Manual

DOMXPath::__construct

(PHP 5)

DOMXPath::__construct — Creates a new DOMXPath object

Opis

public DOMXPath::__construct ( DOMDocument $doc )

Creates a new DOMXPath object.

Parametry

doc

The DOMDocument associated with the DOMXPath.

DOMXPath
DOMXPath::evaluate
DOMXPath


Evaluates the given XPath expression and returns a typed result if possible

DOMXPath::__construct
DOMXPath::query
DOMXPath
PHP Manual

DOMXPath::evaluate

(PHP 5 >= 5.1.0)

DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible

Opis

public mixed DOMXPath::evaluate ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )

Executes the given XPath expression and returns a typed result if possible.

Parametry

expression

The XPath expression to execute.

contextnode

The optional contextnode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

Zwracane wartości

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.

If the expression is malformed or the contextnode is invalid, DOMXPath::evaluate() returns FALSE.

Rejestr zmian

Wersja | Opis
5.3.3 | The registerNodeNS parameter was added.

Przykłady

Przykład #1 Getting the count of all the english books

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "There are $entries english books\n";

?>

Powyższy przykład wyświetli:

There are 2 english books

Zobacz też:

  • DOMXPath::query() - Evaluates the given XPath expression

DOMXPath::__construct
DOMXPath::query
DOMXPath


Evaluates the given XPath expression

DOMXPath::evaluate
DOMXPath::registerNamespace
DOMXPath
PHP Manual

DOMXPath::query

(PHP 5)

DOMXPath::query — Evaluates the given XPath expression

Opis

public DOMNodeList DOMXPath::query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )

Executes the given XPath expression.

Parametry

expression

The XPath expression to execute.

contextnode

The optional contextnode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

Zwracane wartości

Returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which does not return nodes will return an empty DOMNodeList.

If the expression is malformed or the contextnode is invalid, DOMXPath::query() returns FALSE.

Rejestr zmian

Wersja | Opis
5.3.3 | The registerNodeNS parameter was added.

Przykłady

Przykład #1 Getting all the english books

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->Load('book.xml');

$xpath = new DOMXPath($doc);

// We starts from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

Powyższy przykład wyświetli:

Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck

We can also use the contextnode parameter to shorten our expression:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

Zobacz też:

  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible

DOMXPath::evaluate
DOMXPath::registerNamespace
DOMXPath


Registers the namespace with the DOMXPath object

DOMXPath::query
DOMXPath::registerPhpFunctions
DOMXPath
PHP Manual

DOMXPath::registerNamespace

(PHP 5)

DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object

Opis

public bool DOMXPath::registerNamespace ( string $prefix , string $namespaceURI )

Registers the namespaceURI and prefix with the DOMXPath object.

Parametry

prefix

The prefix.

namespaceURI

The URI of the namespace.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

DOMXPath::query
DOMXPath::registerPhpFunctions
DOMXPath


Register PHP functions as XPath functions

DOMXPath::registerNamespace
DOM Funkcje
DOMXPath
PHP Manual

DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0)

DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

Opis

public void DOMXPath::registerPhpFunctions ([ mixed $restrict ] )

This method enables the ability to use PHP functions within XPath expressions.

Parametry

restrict

Use this parameter to only allow certain functions to be called from XPath.

This parameter can be either a string (a function name) or an array of function names.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

The following examples use book.xml which contains the following:

Przykład #1 book.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
 <book>
  <title>PHP Basics</title>
  <author>Jim Smith</author>
  <author>Jane Smith</author>
 </book>
 <book>
  <title>PHP Secrets</title>
  <author>Jenny Smythe</author>
 </book>
 <book>
  <title>XML basics</title>
  <author>Joe Black</author>
 </book>
</books>

Przykład #2 DOMXPath::registerPHPFunctions() with php:functionString

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();

// Call substr function on the book title
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');

echo "Found {$nodes->length} books starting with 'PHP':\n";
foreach ($nodes as $node) {
    $title  = $node->getElementsByTagName("title")->item(0)->nodeValue;
    $author = $node->getElementsByTagName("author")->item(0)->nodeValue;
    echo "$title by $author\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

Przykład #3 DOMXPath::registerPHPFunctions() with php:function

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (has_multiple only)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodes) {
    // Return true if more than one author
    return count($nodes) > 1;
}
// Filter books with multiple authors
$books = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Books with multiple authors:\n";
foreach ($books as $book) {
    echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

Powyższy przykład wyświetli coś podobnego do:

Books with multiple authors:
PHP Basics

Zobacz też:

  • DOMXPath::registerNamespace() - Registers the namespace with the DOMXPath object
  • DOMXPath::query() - Evaluates the given XPath expression
  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible

DOMXPath::registerNamespace
DOM Funkcje
DOMXPath


DOM Funkcje

Spis treści

  • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object
DOMXPath::registerPhpFunctions
dom_import_simplexml
DOM


Gets a DOMElement object from a SimpleXMLElement object

DOM Funkcje
DOM XML (PHP 4)
DOM Funkcje
PHP Manual

dom_import_simplexml

(PHP 5)

dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

Opis

DOMElement dom_import_simplexml ( SimpleXMLElement $node )

This function takes the node node of class SimpleXML and makes it into a DOMElement node. This new object can then be used as a native DOMElement node.

Parametry

node

The SimpleXMLElement node.

Zwracane wartości

The DOMElement node added or FALSE if any errors occur.

Przykłady

Przykład #1 Import SimpleXML into DOM with dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
    echo 'Error while parsing the document';
    exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Error while converting XML';
    exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

Zobacz też:

  • simplexml_import_dom() - Get a SimpleXMLElement object from a DOM node.

DOM Funkcje
DOM XML (PHP 4)
DOM Funkcje


DOM XML (PHP 4)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • DOM XML (PHP 4) Funkcje
    • DomAttribute::name — Returns the name of attribute
    • DomAttribute::set_value — Sets the value of an attribute
    • DomAttribute::specified — Checks if attribute is specified
    • DomAttribute::value — Returns value of attribute
    • DomDocument::add_root — Adds a root node [deprecated]
    • DomDocument::create_attribute — Create new attribute
    • DomDocument::create_cdata_section — Create new cdata node
    • DomDocument::create_comment — Create new comment node
    • DomDocument::create_element_ns — Create new element node with an associated namespace
    • DomDocument::create_element — Create new element node
    • DomDocument::create_entity_reference — Create an entity reference
    • DomDocument::create_processing_instruction — Creates new PI node
    • DomDocument::create_text_node — Create new text node
    • DomDocument::doctype — Returns the document type
    • DomDocument::document_element — Returns root element node
    • DomDocument::dump_file — Dumps the internal XML tree back into a file
    • DomDocument::dump_mem — Dumps the internal XML tree back into a string
    • DomDocument::get_element_by_id — Searches for an element with a certain id
    • DomDocument::get_elements_by_tagname — Returns array with nodes with given tagname in document or empty array, if not found
    • DomDocument::html_dump_mem — Dumps the internal XML tree back into a string as HTML
    • DomDocument::xinclude — Substitutes XIncludes in a DomDocument Object
    • DomDocumentType::entities — Returns list of entities
    • DomDocumentType::internal_subset — Returns internal subset
    • DomDocumentType::name — Returns name of document type
    • DomDocumentType::notations — Returns list of notations
    • DomDocumentType::public_id — Returns public id of document type
    • DomDocumentType::system_id — Returns the system id of document type
    • DomElement::get_attribute_node — Returns the node of the given attribute
    • DomElement::get_attribute — Returns the value of the given attribute
    • DomElement::get_elements_by_tagname — Gets elements by tagname
    • DomElement::has_attribute — Checks to see if an attribute exists in the current node
    • DomElement::remove_attribute — Removes attribute
    • DomElement::set_attribute_node — Adds new attribute
    • DomElement::set_attribute — Sets the value of an attribute
    • DomElement::tagname — Returns the name of the current element
    • DomNode::add_namespace — Adds a namespace declaration to a node
    • DomNode::append_child — Adds a new child at the end of the children
    • DomNode::append_sibling — Adds new sibling to a node
    • DomNode::attributes — Returns list of attributes
    • DomNode::child_nodes — Returns children of node
    • DomNode::clone_node — Clones a node
    • DomNode::dump_node — Dumps a single node
    • DomNode::first_child — Returns first child of node
    • DomNode::get_content — Gets content of node
    • DomNode::has_attributes — Checks if node has attributes
    • DomNode::has_child_nodes — Checks if node has children
    • DomNode::insert_before — Inserts new node as child
    • DomNode::is_blank_node — Checks if node is blank
    • DomNode::last_child — Returns last child of node
    • DomNode::next_sibling — Returns the next sibling of node
    • DomNode::node_name — Returns name of node
    • DomNode::node_type — Returns type of node
    • DomNode::node_value — Returns value of a node
    • DomNode::owner_document — Returns the document this node belongs to
    • DomNode::parent_node — Returns the parent of the node
    • DomNode::prefix — Returns name space prefix of node
    • DomNode::previous_sibling — Returns the previous sibling of node
    • DomNode::remove_child — Removes child from list of children
    • DomNode::replace_child — Replaces a child
    • DomNode::replace_node — Replaces node
    • DomNode::set_content — Sets content of node
    • DomNode::set_name — Sets name of node
    • DomNode::set_namespace — Sets namespace of a node
    • DomNode::unlink_node — Deletes node
    • DomProcessingInstruction::data — Returns the data of ProcessingInstruction node
    • DomProcessingInstruction::target — Returns the target of a ProcessingInstruction node
    • DomXsltStylesheet::process — Applies the XSLT-Transformation on a DomDocument Object
    • DomXsltStylesheet::result_dump_file — Dumps the result from a XSLT-Transformation into a file
    • DomXsltStylesheet::result_dump_mem — Dumps the result from a XSLT-Transformation back into a string
    • domxml_new_doc — Creates new empty XML document
    • domxml_open_file — Creates a DOM object from an XML file
    • domxml_open_mem — Creates a DOM object of an XML document
    • domxml_version — Gets the XML library version
    • domxml_xmltree — Creates a tree of PHP objects from an XML document
    • domxml_xslt_stylesheet_doc — Creates a DomXsltStylesheet Object from a DomDocument Object
    • domxml_xslt_stylesheet_file — Creates a DomXsltStylesheet Object from an XSL document in a file
    • domxml_xslt_stylesheet — Creates a DomXsltStylesheet object from an XSL document in a string
    • domxml_xslt_version — Gets the XSLT library version
    • xpath_eval_expression — Evaluates the XPath Location Path in the given string
    • xpath_eval — Evaluates the XPath Location Path in the given string
    • xpath_new_context — Creates new xpath context
    • xpath_register_ns_auto — Register the given namespace in the passed XPath context
    • xpath_register_ns — Register the given namespace in the passed XPath context
    • xptr_eval — Evaluate the XPtr Location Path in the given string
    • xptr_new_context — Create new XPath Context
dom_import_simplexml
Wstęp
Przetwarzanie XML


Wstęp

The DOM XML extension has been overhauled in PHP 4.3.0 to better comply with the DOM standard. The extension still contains many old functions, but they should no longer be used. In particular, functions that are not object-oriented should be avoided.

The extension allows you to operate on an XML document with the DOM API. It also provides a function domxml_xmltree() to turn the complete XML document into a tree of PHP objects. Currently, this tree should be considered read-only - you can modify it, but this would not make any sense since DomDocument_dump_mem() cannot be applied to it. Therefore, if you want to read an XML file and write a modified version, use DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), etc. and finally the DomDocument_dump_mem() function.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0.

Informacja: This extension is no longer marked experimental. It will, however, never be released with PHP 5, and will only be distributed with PHP 4. If you need DOM XML support with PHP 5 you can use the DOM extension. This domxml extension is not compatible with the DOM extension.

DOM XML (PHP 4)
Instalacja/Konfiguracja
DOM XML (PHP 4)


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
DOM XML (PHP 4)


Wymagania

This extension makes use of the » GNOME XML library. Download and install this library. You will need at least libxml-2.4.14. To use DOM XSLT features you can use the » libxslt library and EXSLT enhancements from » http://www.exslt.org/. Download and install these libraries if you plan to use (enhanced) XSLT features. You will need at least libxslt-1.0.18.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/domxml.

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. This extension is only available if PHP was configured with --with-dom[=DIR] . Add --with-dom-xslt[=DIR] to include DOM XSLT support. DIR is the libxslt install directory. Add --with-dom-exslt[=DIR] to include DOM EXSLT support, where DIR is the libexslt install directory.

Windows users will enable php_domxml.dll inside of php.ini in order to use these functions. W PHP 4 ten DLL znajduje się w podkatalogu extensions/ binarnej dystrybucji PHP dla Windows. DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/ Also, there is one additional DLL that must be made available to your system's PATH in order for this extension to work. In PHP 4 this is in the dlls/ directory. It's name: For PHP <= 4.2.0, it's libxml2.dll. For PHP >= 4.3.0, it's iconv.dll. And as of PHP 5.0.0, iconv is compiled into your Windows PHP binaries by default so no extra DLL is needed.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

XML constants
Constant | Value | Description
XML_ELEMENT_NODE (integer) | 1 | Node is an element
XML_ATTRIBUTE_NODE (integer) | 2 | Node is an attribute
XML_TEXT_NODE (integer) | 3 | Node is a piece of text
XML_CDATA_SECTION_NODE (integer) | 4 |
XML_ENTITY_REF_NODE (integer) | 5 |
XML_ENTITY_NODE (integer) | 6 | Node is an entity like &nbsp;
XML_PI_NODE (integer) | 7 | Node is a processing instruction
XML_COMMENT_NODE (integer) | 8 | Node is a comment
XML_DOCUMENT_NODE (integer) | 9 | Node is a document
XML_DOCUMENT_TYPE_NODE (integer) | 10 |
XML_DOCUMENT_FRAG_NODE (integer) | 11 |
XML_NOTATION_NODE (integer) | 12 |
XML_GLOBAL_NAMESPACE (integer) | 1 |
XML_LOCAL_NAMESPACE (integer) | 2 |
XML_HTML_DOCUMENT_NODE (integer) |  |
XML_DTD_NODE (integer) |  |
XML_ELEMENT_DECL_NODE (integer) |  |
XML_ATTRIBUTE_DECL_NODE (integer) |  |
XML_ENTITY_DECL_NODE (integer) |  |
XML_NAMESPACE_DECL_NODE (integer) |  |
XML_ATTRIBUTE_CDATA (integer) |  |
XML_ATTRIBUTE_ID (integer) |  |
XML_ATTRIBUTE_IDREF (integer) |  |
XML_ATTRIBUTE_IDREFS (integer) |  |
XML_ATTRIBUTE_ENTITY (integer) |  |
XML_ATTRIBUTE_NMTOKEN (integer) |  |
XML_ATTRIBUTE_NMTOKENS (integer) |  |
XML_ATTRIBUTE_ENUMERATION (integer) |  |
XML_ATTRIBUTE_NOTATION (integer) |  |
XPATH_UNDEFINED (integer) |  |
XPATH_NODESET (integer) |  |
XPATH_BOOLEAN (integer) |  |
XPATH_NUMBER (integer) |  |
XPATH_STRING (integer) |  |
XPATH_POINT (integer) |  |
XPATH_RANGE (integer) |  |
XPATH_LOCATIONSET (integer) |  |
XPATH_USERS (integer) |  |
XPATH_NUMBER (integer) |  |
Typy zasobów
DOM XML (PHP 4) Funkcje
DOM XML (PHP 4)


DOM XML (PHP 4) Funkcje

Deprecated functions

There are quite a few functions that do not fit into the DOM standard and should no longer be used. These functions are listed in the following table. The function DomNode_append_child() has changed its behaviour. It now adds a child and not a sibling. If this breaks your application, use the non-DOM function DomNode_append_sibling().

Deprecated functions and their replacements
Old function | New function
xmldoc | domxml_open_mem()
xmldocfile | domxml_open_file()
domxml_new_xmldoc | domxml_new_doc()
domxml_dump_mem | DomDocument_dump_mem()
domxml_dump_mem_file | DomDocument_dump_file()
DomDocument_dump_mem_file | DomDocument_dump_file()
DomDocument_add_root | DomDocument_create_element() followed by DomNode_append_child()
DomDocument_dtd | DomDocument_doctype()
DomDocument_root | DomDocument_document_element()
DomDocument_children | DomNode_child_nodes()
DomDocument_imported_node | No replacement.
DomNode_add_child | Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_children | DomNode_child_nodes()
DomNode_parent | DomNode_parent_node()
DomNode_new_child | Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_set_content | Create a new node with e.g. DomDocument_create_text_node() and add it with DomNode_append_child().
DomNode_get_content | Content is just a text node and can be accessed with DomNode_child_nodes().
DomNode_set_content | Content is just a text node and can be added with DomNode_append_child().

Classes

The API of the module follows the DOM Level 2 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module. Though the API is object-oriented, there are many functions which can be called in a non-object-oriented way by passing the object to operate on as the first argument. These functions are mainly to retain compatibility to older versions of the extension, and should not be used when creating new scripts.

This API differs from the official DOM API in two ways. First, all class attributes are implemented as functions with the same name. Secondly, the function names follow the PHP naming convention. This means that a DOM function lastChild() will be written as last_child().

This module defines a number of classes, which are listed - including their method - in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.

List of classes
Class name | Parent classes
DomAttribute | DomNode
DomCData | DomNode
DomComment | DomCData : DomNode
DomDocument | DomNode
DomDocumentType | DomNode
DomElement | DomNode
DomEntity | DomNode
DomEntityReference | DomNode
DomProcessingInstruction | DomNode
DomText | DomCData : DomNode
Parser | Currently still called DomParser
XPathContext |

DomDocument class (DomDocument : DomNode)
Method name | Function name | Remark
doctype | DomDocument_doctype() |
document_element | DomDocument_document_element() |
create_element | DomDocument_create_element() |
create_text_node | DomDocument_create_text_node() |
create_comment | DomDocument_create_comment() |
create_cdata_section | DomDocument_create_cdata_section() |
create_processing_instruction | DomDocument_create_processing_instruction() |
create_attribute | DomDocument_create_attribute() |
create_entity_reference | DomDocument_create_entity_reference() |
get_elements_by_tagname | DomDocument_get_elements_by_tagname() |
get_element_by_id | DomDocument_get_element_by_id() |
dump_mem | DomDocument_dump_mem() | not DOM standard
dump_file | DomDocument_dump_file() | not DOM standard
html_dump_mem | DomDocument_html_dump_mem() | not DOM standard
xpath_init | xpath_init | not DOM standard
xpath_new_context | xpath_new_context | not DOM standard
xptr_new_context | xptr_new_context | not DOM standard

DomElement class (DomElement : DomNode)
Method name | Function name | Remark
tagname | DomElement_tagname() |
get_attribute | DomElement_get_attribute() |
set_attribute | DomElement_set_attribute() |
remove_attribute | DomElement_remove_attribute() |
get_attribute_node | DomElement_get_attribute_node() |
set_attribute_node | DomElement_set_attribute_node() |
get_elements_by_tagname | DomElement_get_elements_by_tagname() |
has_attribute | DomElement_has_attribute() |

DomNode class
Method name | Remark
DomNode_node_name() |
DomNode_node_value() |
DomNode_node_type() |
DomNode_last_child() |
DomNode_first_child() |
DomNode_child_nodes() |
DomNode_previous_sibling() |
DomNode_next_sibling() |
DomNode_parent_node() |
DomNode_owner_document() |
DomNode_insert_before() |
DomNode_append_child() |
DomNode_append_sibling() | Not in DOM standard. This function emulates the former behaviour of DomNode_append_child().
DomNode_remove_child() |
DomNode_has_child_nodes() |
DomNode_has_attributes() |
DomNode_clone_node() |
DomNode_attributes() |
DomNode_unlink_node() | Not in DOM standard
DomNode_replace_node() | Not in DOM standard
DomNode_set_content() | Not in DOM standard, deprecated
DomNode_get_content() | Not in DOM standard, deprecated
DomNode_dump_node() | Not in DOM standard
DomNode_is_blank_node() | Not in DOM standard

DomAttribute class (DomAttribute : DomNode)
Method name |  | Remark
name | DomAttribute_name() |
value | DomAttribute_value() |
specified | DomAttribute_specified() |

DomProcessingInstruction class (DomProcessingInstruction : DomNode)
Method name | Function name | Remark
target | DomProcessingInstruction_target() |
data | DomProcessingInstruction_data() |

Parser class
Method name | Function name | Remark
add_chunk | Parser_add_chunk() |
end | Parser_end() |

XPathContext class
Method name | Function name | Remark
eval | XPathContext_eval() |
eval_expression | XPathContext_eval_expression() |
register_ns | XPathContext_register_ns() |

DomDocumentType class (DomDocumentType : DomNode)
Method name | Function name | Remark
name | DomDocumentType_name() |
entities | DomDocumentType_entities() |
notations | DomDocumentType_notations() |
public_id | DomDocumentType_public_id() |
system_id | DomDocumentType_system_id() |
internal_subset | DomDocumentType_internal_subset() |

The classes DomDtd is derived from DomNode. DomComment is derived from DomCData.

Przykłady

Many examples in this reference require an XML string. Instead of repeating this string in every example, it will be put into a file which will be included by each example. This include file is shown in the following example section. Alternatively, you could create an XML document and read it with DomDocument_open_file().

Przykład #1 Include file example.inc with XML string

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  &sp;
  <!-- comment -->
  <informaltable ID='findme' language='&sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";
?>

Spis treści

  • DomAttribute::name — Returns the name of attribute
  • DomAttribute::set_value — Sets the value of an attribute
  • DomAttribute::specified — Checks if attribute is specified
  • DomAttribute::value — Returns value of attribute
  • DomDocument::add_root — Adds a root node [deprecated]
  • DomDocument::create_attribute — Create new attribute
  • DomDocument::create_cdata_section — Create new cdata node
  • DomDocument::create_comment — Create new comment node
  • DomDocument::create_element_ns — Create new element node with an associated namespace
  • DomDocument::create_element — Create new element node
  • DomDocument::create_entity_reference — Create an entity reference
  • DomDocument::create_processing_instruction — Creates new PI node
  • DomDocument::create_text_node — Create new text node
  • DomDocument::doctype — Returns the document type
  • DomDocument::document_element — Returns root element node
  • DomDocument::dump_file — Dumps the internal XML tree back into a file
  • DomDocument::dump_mem — Dumps the internal XML tree back into a string
  • DomDocument::get_element_by_id — Searches for an element with a certain id
  • DomDocument::get_elements_by_tagname — Returns array with nodes with given tagname in document or empty array, if not found
  • DomDocument::html_dump_mem — Dumps the internal XML tree back into a string as HTML
  • DomDocument::xinclude — Substitutes XIncludes in a DomDocument Object
  • DomDocumentType::entities — Returns list of entities
  • DomDocumentType::internal_subset — Returns internal subset
  • DomDocumentType::name — Returns name of document type
  • DomDocumentType::notations — Returns list of notations
  • DomDocumentType::public_id — Returns public id of document type
  • DomDocumentType::system_id — Returns the system id of document type
  • DomElement::get_attribute_node — Returns the node of the given attribute
  • DomElement::get_attribute — Returns the value of the given attribute
  • DomElement::get_elements_by_tagname — Gets elements by tagname
  • DomElement::has_attribute — Checks to see if an attribute exists in the current node
  • DomElement::remove_attribute — Removes attribute
  • DomElement::set_attribute_node — Adds new attribute
  • DomElement::set_attribute — Sets the value of an attribute
  • DomElement::tagname — Returns the name of the current element
  • DomNode::add_namespace — Adds a namespace declaration to a node
  • DomNode::append_child — Adds a new child at the end of the children
  • DomNode::append_sibling — Adds new sibling to a node
  • DomNode::attributes — Returns list of attributes
  • DomNode::child_nodes — Returns children of node
  • DomNode::clone_node — Clones a node
  • DomNode::dump_node — Dumps a single node
  • DomNode::first_child — Returns first child of node
  • DomNode::get_content — Gets content of node
  • DomNode::has_attributes — Checks if node has attributes
  • DomNode::has_child_nodes — Checks if node has children
  • DomNode::insert_before — Inserts new node as child
  • DomNode::is_blank_node — Checks if node is blank
  • DomNode::last_child — Returns last child of node
  • DomNode::next_sibling — Returns the next sibling of node
  • DomNode::node_name — Returns name of node
  • DomNode::node_type — Returns type of node
  • DomNode::node_value — Returns value of a node
  • DomNode::owner_document — Returns the document this node belongs to
  • DomNode::parent_node — Returns the parent of the node
  • DomNode::prefix — Returns name space prefix of node
  • DomNode::previous_sibling — Returns the previous sibling of node
  • DomNode::remove_child — Removes child from list of children
  • DomNode::replace_child — Replaces a child
  • DomNode::replace_node — Replaces node
  • DomNode::set_content — Sets content of node
  • DomNode::set_name — Sets name of node
  • DomNode::set_namespace — Sets namespace of a node
  • DomNode::unlink_node — Deletes node
  • DomProcessingInstruction::data — Returns the data of ProcessingInstruction node
  • DomProcessingInstruction::target — Returns the target of a ProcessingInstruction node
  • DomXsltStylesheet::process — Applies the XSLT-Transformation on a DomDocument Object
  • DomXsltStylesheet::result_dump_file — Dumps the result from a XSLT-Transformation into a file
  • DomXsltStylesheet::result_dump_mem — Dumps the result from a XSLT-Transformation back into a string
  • domxml_new_doc — Creates new empty XML document
  • domxml_open_file — Creates a DOM object from an XML file
  • domxml_open_mem — Creates a DOM object of an XML document
  • domxml_version — Gets the XML library version
  • domxml_xmltree — Creates a tree of PHP objects from an XML document
  • domxml_xslt_stylesheet_doc — Creates a DomXsltStylesheet Object from a DomDocument Object
  • domxml_xslt_stylesheet_file — Creates a DomXsltStylesheet Object from an XSL document in a file
  • domxml_xslt_stylesheet — Creates a DomXsltStylesheet object from an XSL document in a string
  • domxml_xslt_version — Gets the XSLT library version
  • xpath_eval_expression — Evaluates the XPath Location Path in the given string
  • xpath_eval — Evaluates the XPath Location Path in the given string
  • xpath_new_context — Creates new xpath context
  • xpath_register_ns_auto — Register the given namespace in the passed XPath context
  • xpath_register_ns — Register the given namespace in the passed XPath context
  • xptr_eval — Evaluate the XPtr Location Path in the given string
  • xptr_new_context — Create new XPath Context
Stałe predefiniowane
DomAttribute::name
DOM XML (PHP 4)


Returns the name of attribute

DOM XML (PHP 4) Funkcje
DomAttribute::set_value
DOM XML (PHP 4) Funkcje
PHP Manual

DomAttribute::name

(PHP 4 >= 4.1.0)

DomAttribute::name — Returns the name of attribute

Opis

string DomAttribute::name ( void )

Gets the name of the attribute.

Zwracane wartości

Returns the name of the attribute.

Migrating to PHP 5

Use the name property of DOMAttr.

Zobacz też:

  • DomAttribute::value for an example

DOM XML (PHP 4) Funkcje
DomAttribute::set_value
DOM XML (PHP 4) Funkcje


Sets the value of an attribute

DomAttribute::name
DomAttribute::specified
DOM XML (PHP 4) Funkcje
PHP Manual

DomAttribute::set_value

(PHP 4 >= 4.1.0)

DomAttribute::set_value — Sets the value of an attribute

Opis

bool DomAttribute::set_value ( string $content )

This function sets the value of an attribute.

Parametry

content

The new value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Migrating to PHP 5

Set the value property of DOMAttr.

Zobacz też:

  • DomAttribute::value

DomAttribute::name
DomAttribute::specified
DOM XML (PHP 4) Funkcje


Checks if attribute is specified

DomAttribute::set_value
DomAttribute::value
DOM XML (PHP 4) Funkcje
PHP Manual

DomAttribute::specified

(PHP 4 >= 4.1.0)

DomAttribute::specified — Checks if attribute is specified

Opis

bool DomAttribute::specified ( void )

Checks if the attribute was explicitly given a value in the original document.

Informacja:

This method is not implemented yet.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • The definition of » specified in the DOM Recommendations

DomAttribute::set_value
DomAttribute::value
DOM XML (PHP 4) Funkcje


Returns value of attribute

DomAttribute::specified
DomDocument::add_root
DOM XML (PHP 4) Funkcje
PHP Manual

DomAttribute::value

(PHP 4 >= 4.1.0)

DomAttribute::value — Returns value of attribute

Opis

string DomAttribute::value ( void )

This function returns the value of the attribute.

Przykłady

Przykład #1 Getting all the attributes of a node

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
     echo "Error while parsing the document\n";
     exit;
}

$root = $dom->document_element();
$attrs = $root->attributes();

echo 'Attributes of ' . $root->node_name() . "\n";
foreach ($attrs as $attribute) {
     echo ' - ' . $attribute->name . ' : ' . $attribute->value . "\n";
}

?>

Powyższy przykład wyświetli:

Attributes of chapter
 - language : en

Zwracane wartości

Returns the value of the attribute.

Migrating to PHP 5

Use the value property of DOMAttr.

Zobacz też:

  • DomAttribute::set_value
  • DomAttribute::name

DomAttribute::specified
DomDocument::add_root
DOM XML (PHP 4) Funkcje


Adds a root node [deprecated]

DomAttribute::value
DomDocument::create_attribute
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::add_root

(PHP 4 >= 4.1.0)

DomDocument::add_root — Adds a root node [deprecated]

Opis

domelement DomDocument::add_root ( string $name )

Adds a root element node to a dom document and returns the new node. The element name is given in the passed parameter.

Przykład #1 Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->add_root("html");
$head = $root->new_child("head", "");
$head->new_child("title", "Hier der Titel");
echo htmlentities($doc->dump_mem());
?>

DomAttribute::value
DomDocument::create_attribute
DOM XML (PHP 4) Funkcje


Create new attribute

DomDocument::add_root
DomDocument::create_cdata_section
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::create_attribute

(PHP 4 >= 4.1.0)

DomDocument::create_attribute — Create new attribute

Opis

domattribute DomDocument::create_attribute ( string $name , string $value )

This function returns a new instance of class DomAttribute. The name of the attribute is the value of the first parameter. The value of the attribute is the value of the second parameter. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. funkcją domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_cdata_section(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference(), and
domnode_insert_before().

DomDocument::add_root
DomDocument::create_cdata_section
DOM XML (PHP 4) Funkcje


Create new cdata node

DomDocument::create_attribute
DomDocument::create_comment
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::create_cdata_section

(PHP 4 >= 4.1.0)

DomDocument::create_cdata_section — Create new cdata node

Opis

domcdata DomDocument::create_cdata_section ( string $content )

This function returns a new instance of class DomCData. The content of the cdata is the value of the passed parameter. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. funkcją domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference(), and
domnode_insert_before().

DomDocument::create_attribute
DomDocument::create_comment
DOM XML (PHP 4) Funkcje


Create new comment node

DomDocument::create_cdata_section
DomDocument::create_element_ns
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::create_comment

(PHP 4 >= 4.1.0)

DomDocument::create_comment — Create new comment node

Opis

domcomment DomDocument::create_comment ( string $content )

This function returns a new instance of class DomComment. The content of the comment is the value of the passed parameter. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. funkcją domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference(), and
domnode_insert_before().

DomDocument::create_cdata_section
DomDocument::create_element_ns
DOM XML (PHP 4) Funkcje


Create new element node with an associated namespace

DomDocument::create_comment
DomDocument::create_element
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::create_element_ns

(PHP 4 >= 4.1.0)

DomDocument::create_element_ns — Create new element node with an associated namespace

Opis

domelement DomDocument::create_element_ns ( string $uri , string $name [, string $prefix ] )

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter name. The URI of the namespace is the value of the passed parameter uri. If there is already a namespace declaration with the same uri in the root-node of the document, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. funkcją domnode_append_child().

The return value is FALSE if an error occurred.

See also domdocument_create_element_ns(),
domnode_add_namespace(),
domnode_set_namespace(),
domnode_append_child(),
domdocument_create_text(),
domdocument_create_comment(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference(), and
domnode_insert_before().

DomDocument::create_comment
DomDocument::create_element
DOM XML (PHP 4) Funkcje


Create new element node

DomDocument::create_element_ns
DomDocument::create_entity_reference
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::create_element

(PHP 4 >= 4.1.0)

DomDocument::create_element — Create new element node

Opis

domelement DomDocument::create_element ( string $name )

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. funkcją domnode_append_child().

The return value is FALSE if an error occurred.

See also domdocument_create_element_ns(),
domnode_append_child(),
domdocument_create_text(),
domdocument_create_comment(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference(), and
domnode_insert_before().

DomDocument::create_element_ns
DomDocument::create_entity_reference
DOM XML (PHP 4) Funkcje


Create an entity reference

DomDocument::create_element
DomDocument::create_processing_instruction
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::create_entity_reference

(PHP 4 >= 4.1.0)

DomDocument::create_entity_reference — Create an entity reference

Opis

domentityreference DomDocument::create_entity_reference ( string $content )

This function returns a new instance of class DomEntityReference. The content of the entity reference is the value of the passed parameter. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. funkcją domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_cdata_section(),
domdocument_create_processing_instruction(),
domdocument_create_attribute(), and
domnode_insert_before().

DomDocument::create_element
DomDocument::create_processing_instruction
DOM XML (PHP 4) Funkcje


Creates new PI node

DomDocument::create_entity_reference
DomDocument::create_text_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::create_processing_instruction

(PHP 4 >= 4.1.0)

DomDocument::create_processing_instruction — Creates new PI node

Opis

domprocessinginstruction DomDocument::create_processing_instruction ( string $content )

This function returns a new instance of class DomCData. The content of the pi is the value of the passed parameter. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. funkcją domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(),
domdocument_create_element(),
domdocument_create_text(),
domdocument_create_cdata_section(),
domdocument_create_attribute(),
domdocument_create_entity_reference(), and
domnode_insert_before().

DomDocument::create_entity_reference
DomDocument::create_text_node
DOM XML (PHP 4) Funkcje


Create new text node

DomDocument::create_processing_instruction
DomDocument::doctype
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::create_text_node

(PHP 4 >= 4.1.0)

DomDocument::create_text_node — Create new text node

Opis

domtext DomDocument::create_text_node ( string $content )

This function returns a new instance of class DomText. The content of the text is the value of the passed parameter. Ten węzeł nie pojawi się w dokumencie dopóki nie zostanie wstawiony, np. funkcją domnode_append_child().

The return value is FALSE if an error occurred.

See also domnode_append_child(),
domdocument_create_element(),
domdocument_create_comment(),
domdocument_create_text(),
domdocument_create_attribute(),
domdocument_create_processing_instruction(),
domdocument_create_entity_reference(), and
domnode_insert_before().

DomDocument::create_processing_instruction
DomDocument::doctype
DOM XML (PHP 4) Funkcje


Returns the document type

DomDocument::create_text_node
DomDocument::document_element
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::doctype

(PHP 4 >= 4.1.0)

DomDocument::doctype — Returns the document type

Opis

domdocumenttype DomDocument::doctype ( void )

This function returns an object of class DomDocumentType. In versions of PHP before 4.3 this has been the class Dtd, but the DOM Standard does not know such a class.

See also the methods of class DomDocumentType.

DomDocument::create_text_node
DomDocument::document_element
DOM XML (PHP 4) Funkcje


Returns root element node

DomDocument::doctype
DomDocument::dump_file
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::document_element

(PHP 4 >= 4.1.0)

DomDocument::document_element — Returns root element node

Opis

domelement DomDocument::document_element ( void )

This function returns the root element node of a document.

The following example returns just the element with name CHAPTER and prints it. The other node -- the comment -- is not returned.

Przykład #1 Retrieving root element

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
print_r($root);
?>

Powyższy przykład wyświetli:

domelement Object
(
    [type] => 1
    [tagname] => chapter
    [0] => 6
    [1] => 137960648
)

DomDocument::doctype
DomDocument::dump_file
DOM XML (PHP 4) Funkcje


Dumps the internal XML tree back into a file

DomDocument::document_element
DomDocument::dump_mem
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::dump_file

(PHP 4 >= 4.1.0)

DomDocument::dump_file — Dumps the internal XML tree back into a file

Opis

string DomDocument::dump_file ( string $filename [, bool $compressionmode [, bool $format ]] )

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not. The first parameter specifies the name of the filename and the second parameter, whether it should be compressed or not.

Przykład #1 Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", false, true);
?>

See also domdocument_dump_mem(), and domdocument_html_dump_mem().

DomDocument::document_element
DomDocument::dump_mem
DOM XML (PHP 4) Funkcje


Dumps the internal XML tree back into a string

DomDocument::dump_file
DomDocument::get_element_by_id
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::dump_mem

(PHP 4 >= 4.1.0)

DomDocument::dump_mem — Dumps the internal XML tree back into a string

Opis

string DomDocument::dump_mem ([ bool $format [, string $encoding ]] )

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not.

Przykład #1 Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>

Informacja:

The first parameter was added in PHP 4.3.0.

See also domdocument_dump_file(), and domdocument_html_dump_mem().

DomDocument::dump_file
DomDocument::get_element_by_id
DOM XML (PHP 4) Funkcje


Searches for an element with a certain id

DomDocument::dump_mem
DomDocument::get_elements_by_tagname
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::get_element_by_id

(PHP 4 >= 4.1.0)

DomDocument::get_element_by_id — Searches for an element with a certain id

Opis

domelement DomDocument::get_element_by_id ( string $id )

This function is similar to domdocument_get_elements_by_tagname() but searches for an element with a given id. According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID, though the current implementation simply does an xpath search for "//*[@ID = '%s']". This does not comply to the DOM standard which requires to return null if it is not known which attribute is of type id. This behaviour is likely to be fixed, so do not rely on the current behaviour.

See also domdocument_get_elements_by_tagname()

DomDocument::dump_mem
DomDocument::get_elements_by_tagname
DOM XML (PHP 4) Funkcje


Returns array with nodes with given tagname in document or empty array, if not found

DomDocument::get_element_by_id
DomDocument::html_dump_mem
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::get_elements_by_tagname

(PHP 4 >= 4.1.0)

DomDocument::get_elements_by_tagname — Returns array with nodes with given tagname in document or empty array, if not found

Opis

array DomDocument::get_elements_by_tagname ( string $name )

See also domdocument_add_root()

DomDocument::get_element_by_id
DomDocument::html_dump_mem
DOM XML (PHP 4) Funkcje


Dumps the internal XML tree back into a string as HTML

DomDocument::get_elements_by_tagname
DomDocument::xinclude
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::html_dump_mem

(PHP 4 >= 4.1.0)

DomDocument::html_dump_mem — Dumps the internal XML tree back into a string as HTML

Opis

string DomDocument::html_dump_mem ( void )

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

Przykład #1 Creating a simple HTML document header

<?php

// Creates the document
$doc = domxml_new_doc("1.0");

$root = $doc->create_element("html");
$root = $doc->append_child($root);

$head = $doc->create_element("head");
$head = $root->append_child($head);

$title = $doc->create_element("title");
$title = $head->append_child($title);

$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);

echo $doc->html_dump_mem();
?>

Powyższy przykład wyświetli:

<html><head><title>This is the title</title></head></html>

See also domdocument_dump_file(), and domdocument_html_dump_mem().

DomDocument::get_elements_by_tagname
DomDocument::xinclude
DOM XML (PHP 4) Funkcje


Substitutes XIncludes in a DomDocument Object

DomDocument::html_dump_mem
DomDocumentType::entities
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocument::xinclude

(PHP 5)

DomDocument::xinclude — Substitutes XIncludes in a DomDocument Object

Opis

int DomDocument::xinclude ( void )

This function substitutes » XIncludes in a DomDocument object.

Przykład #1 Substituting Xincludes

<?php

// include.xml contains :
// <child>test</child>

$xml = '<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="include.xml">
    <xi:fallback>
      <error>xinclude: include.xml not found</error>
    </xi:fallback>
  </xi:include>
</root>';

$domxml = domxml_open_mem($xml);
$domxml->xinclude();

echo $domxml->dump_mem();

?>

Powyższy przykład wyświetli:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <child>test</child>
</root>

If include.xml doesn't exist, you'll see:

<?xml version="1.0"?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <error>xinclude:dom.xml not found</error>
</root>

DomDocument::html_dump_mem
DomDocumentType::entities
DOM XML (PHP 4) Funkcje


Returns list of entities

DomDocument::xinclude
DomDocumentType::internal_subset
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocumentType::entities

(PHP 4 >= 4.1.0)

DomDocumentType::entities — Returns list of entities

Opis

array DomDocumentType::entities ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Migrating to PHP 5

Use the entities property of the DOMDocumentType object.

DomDocument::xinclude
DomDocumentType::internal_subset
DOM XML (PHP 4) Funkcje


Returns internal subset

DomDocumentType::entities
DomDocumentType::name
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocumentType::internal_subset

(PHP 4 >= 4.1.0)

DomDocumentType::internal_subset — Returns internal subset

Opis

bool DomDocumentType::internal_subset ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Migrating to PHP 5

Use the internalSubset property of the DOMDocumentType object.

DomDocumentType::entities
DomDocumentType::name
DOM XML (PHP 4) Funkcje


Returns name of document type

DomDocumentType::internal_subset
DomDocumentType::notations
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocumentType::name

(PHP 4 >= 4.1.0)

DomDocumentType::name — Returns name of document type

Opis

string DomDocumentType::name ( void )

This function returns the name of the document type.

Zwracane wartości

Returns the name of the DomDocumentType, as a string.

Przykłady

Przykład #1 Getting the document type's name

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$doctype = $dom->doctype();
echo $doctype->name(); // chapter

?>

Migrating to PHP 5

Use the name property of the DOMDocumentType object.

DomDocumentType::internal_subset
DomDocumentType::notations
DOM XML (PHP 4) Funkcje


Returns list of notations

DomDocumentType::name
DomDocumentType::public_id
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocumentType::notations

(PHP 4 >= 4.1.0)

DomDocumentType::notations — Returns list of notations

Opis

array DomDocumentType::notations ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Migrating to PHP 5

Use the notations property of the DOMDocumentType object.

DomDocumentType::name
DomDocumentType::public_id
DOM XML (PHP 4) Funkcje


Returns public id of document type

DomDocumentType::notations
DomDocumentType::system_id
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocumentType::public_id

(PHP 4 >= 4.1.0)

DomDocumentType::public_id — Returns public id of document type

Opis

string DomDocumentType::public_id ( void )

This function returns the public id of the document type.

Zwracane wartości

Returns the public id of the DomDocumentType, as a string.

Przykłady

The following example echos nothing.

Przykład #1 Retrieving the public id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->public_id();
?>

Migrating to PHP 5

Use the publicId property of the DOMDocumentType object.

DomDocumentType::notations
DomDocumentType::system_id
DOM XML (PHP 4) Funkcje


Returns the system id of document type

DomDocumentType::public_id
DomElement::get_attribute_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomDocumentType::system_id

(PHP 4 >= 4.1.0)

DomDocumentType::system_id — Returns the system id of document type

Opis

string DomDocumentType::system_id ( void )

Returns the system id of the document type.

Zwracane wartości

Returns the system id of the DomDocumentType, as a string.

Przykłady

Przykład #1 Retrieving the system id

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->system_id();
?>

Powyższy przykład wyświetli:

/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd

Migrating to PHP 5

Use the systemId property of the DOMDocumentType object.

DomDocumentType::public_id
DomElement::get_attribute_node
DOM XML (PHP 4) Funkcje


Returns the node of the given attribute

DomDocumentType::system_id
DomElement::get_attribute
DOM XML (PHP 4) Funkcje
PHP Manual

DomElement::get_attribute_node

(PHP 4 >= 4.1.0)

DomElement::get_attribute_node — Returns the node of the given attribute

Opis

DomAttribute DomElement::get_attribute_node ( string $name )

Returns the node of the given attribute in the current element.

Parametry

name

The name of the seeked attribute. This parameter is case sensitive.

Zwracane wartości

Returns the node of the attribute as a DomAttribute or FALSE if no attribute with the given name is found.

Przykłady

Przykład #1 Getting an attribute node

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();
if ($attribute = $root->get_attribute_node('language')) {
    echo 'Language is: ' . $attribute->value() . "\n";
}

?>

Migrating to PHP 5

Use DOMElement::getAttributeNode.

Zobacz też:

  • DomElement::get_attribute
  • DomElement::set_attribute

DomDocumentType::system_id
DomElement::get_attribute
DOM XML (PHP 4) Funkcje


Returns the value of the given attribute

DomElement::get_attribute_node
DomElement::get_elements_by_tagname
DOM XML (PHP 4) Funkcje
PHP Manual

DomElement::get_attribute

(PHP 4 >= 4.1.0)

DomElement::get_attribute — Returns the value of the given attribute

Opis

string DomElement::get_attribute ( string $name )

Returns the value of the given attribute in the current element.

Since PHP 4.3, if no attribute with given name is found, an empty string is returned.

Parametry

name

The name of the seeked attribute. This parameter is case sensitive.

Zwracane wartości

Returns the value of the attribute as a string or an empty string if no attribute with the given name is found.

Przykłady

Przykład #1 Getting the value of an attribute

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

// get chapter
$root = $dom->document_element();
echo $root->get_attribute('language'); // en

?>

Migrating to PHP 5

Use DOMElement::getAttribute.

Zobacz też:

  • DomElement::get_attribute_node
  • DomElement::set_attribute

DomElement::get_attribute_node
DomElement::get_elements_by_tagname
DOM XML (PHP 4) Funkcje


Gets elements by tagname

DomElement::get_attribute
DomElement::has_attribute
DOM XML (PHP 4) Funkcje
PHP Manual

DomElement::get_elements_by_tagname

(PHP 4 >= 4.1.0)

DomElement::get_elements_by_tagname — Gets elements by tagname

Opis

array DomElement::get_elements_by_tagname ( string $name )

Gets all the sub elements with the specific name within the current element.

Parametry

name

The name of the seeked element.

Zwracane wartości

Returns an array of DomElement objects.

Przykłady

Przykład #1 Getting a content

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname('element');

foreach ($node_array as $node) {
    echo ' - ' . $node->get_content() . "\n";
}

?>

Migrating to PHP 5

Use DOMElement::getElementsByTagName.

DomElement::get_attribute
DomElement::has_attribute
DOM XML (PHP 4) Funkcje


Checks to see if an attribute exists in the current node

DomElement::get_elements_by_tagname
DomElement::remove_attribute
DOM XML (PHP 4) Funkcje
PHP Manual

DomElement::has_attribute

(PHP 4 >= 4.1.0)

DomElement::has_attribute — Checks to see if an attribute exists in the current node

Opis

bool DomElement::has_attribute ( string $name )

This functions checks to see if an attribute named name exists in the current node.

Parametry

name

The name of the tested attribute.

Zwracane wartości

Returns TRUE if the asked attribute exists, FALSE otherwise.

Przykłady

Przykład #1 Testing the existence of an attribute

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();

$buffer = '<html';
if ($root->has_attribute('language')) {
    $buffer .= 'lang="' . $root->get_attribute('language') . '"';
}
$buffer .= '>';

?>

Migrating to PHP 5

Use DOMElement::hasAttribute.

DomElement::get_elements_by_tagname
DomElement::remove_attribute
DOM XML (PHP 4) Funkcje


Removes attribute

DomElement::has_attribute
DomElement::set_attribute_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomElement::remove_attribute

(PHP 4 >= 4.1.0)

DomElement::remove_attribute — Removes attribute

Opis

bool DomElement::remove_attribute ( string $name )

Removes an attribute from the current DomElement node.

Parametry

name

The name of the attribute to remove.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Migrating to PHP 5

Use DOMElement::removeAttribute.

DomElement::has_attribute
DomElement::set_attribute_node
DOM XML (PHP 4) Funkcje


Adds new attribute

DomElement::remove_attribute
DomElement::set_attribute
DOM XML (PHP 4) Funkcje
PHP Manual

DomElement::set_attribute_node

(PHP 4 >= 4.1.0)

DomElement::set_attribute_node — Adds new attribute

Opis

DomNode DomElement::set_attribute_node ( DomNode $attr )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

DomElement::remove_attribute
DomElement::set_attribute
DOM XML (PHP 4) Funkcje


Sets the value of an attribute

DomElement::set_attribute_node
DomElement::tagname
DOM XML (PHP 4) Funkcje
PHP Manual

DomElement::set_attribute

(PHP 4 >= 4.1.0)

DomElement::set_attribute — Sets the value of an attribute

Opis

DomAttribute DomElement::set_attribute ( string $name , string $value )

Sets an attribute with name name to the given value.

Parametry

name

The name of the attribute. If this attribute doesn't exist, it will be created.

value

The value of the attribute.

Zwracane wartości

Returns the old DomAttribute node, or the new one if you are creating the attribute for the first time.

Przykłady

Przykład #1 Setting an attribute

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

Migrating to PHP 5

Use DOMElement::setAttribute.

Zobacz też:

  • DomElement::get_attribute_node
  • DomElement::get_attribute

DomElement::set_attribute_node
DomElement::tagname
DOM XML (PHP 4) Funkcje


Returns the name of the current element

DomElement::set_attribute
DomNode::add_namespace
DOM XML (PHP 4) Funkcje
PHP Manual

DomElement::tagname

(PHP 4 >= 4.1.0)

DomElement::tagname — Returns the name of the current element

Opis

string DomElement::tagname ( void )

Returns the name of the current node. Calling this function is the same as accessing the tagname property, or calling DomNode::node_name on the current node.

Zwracane wartości

Returns the name of the current DomElement node.

Przykłady

Przykład #1 Getting the node name

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$root = $dom->document_element();
echo $root->tagname();   // chapter
echo $root->tagname;     // chapter
echo $root->node_name(); // chapter

?>

Migrating to PHP 5

Use the tagName property of the DOMElement object.

DomElement::set_attribute
DomNode::add_namespace
DOM XML (PHP 4) Funkcje


Adds a namespace declaration to a node

DomElement::tagname
DomNode::append_child
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::add_namespace

(PHP 4 >= 4.3.0)

DomNode::add_namespace — Adds a namespace declaration to a node

Opis

bool DOMNode::add_namespace ( string $uri , string $prefix )

This method adds a namespace declaration to a node.

Informacja:

This method is not part of the DOM specification.

Parametry

uri

The namespace URI of the node.

prefix

The namespace prefix of the node.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Migrating to PHP 5

You can set the namespace URI and prefix of a DOMElement or a DOMAttr at creation time by using DOMDocument::createElementNS or DOMDocument::createAttributeNS.

Informacja:

Remember the an attribute does not inherit its namespace from the element it is attached to.

Zobacz też:

  • DomDocument::create_element_ns
  • DomNode::set_namespace

DomElement::tagname
DomNode::append_child
DOM XML (PHP 4) Funkcje


Adds a new child at the end of the children

DomNode::add_namespace
DomNode::append_sibling
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::append_child

(PHP 4 >= 4.1.0)

DomNode::append_child — Adds a new child at the end of the children

Opis

DOMNode DOMNode::append_child ( DOMNode $newnode )

This functions appends a child to an existing list of children or creates a new list of children.

Parametry

newnode

The node being appended. It can be created with e.g. DomDocument::create_element, DomDocument::create_text_node etc. or simply by using any other node.

Informacja:

You can not append a DOMAttribute using this method. Use DomElement::set_attribute instead.

Zwracane wartości

Returns the appended node on success lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja | Opis
4.3.0 | You are not allowed anymore to insert a node from another document.
4.3.0 | Prior to PHP 4.3.0, the new child is duplicated before being appended. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the appended child. If you plan to do further modifications on the appended child you must use the returned node.
4.3.0 and 4.3.1 | The new child newnode is first unlinked from its existing context, if it's already a child of DomNode. Therefore the newnode is moved and not copies anymore. This is the behaviour according to the W3C specifications. If you need the old behaviour, use DomNode::clone_node before appending.
4.3.2 | The new child newnode is first unlinked from its existing context, if it's already in the tree. Same rules apply.

Przykłady

The following example adds a new element node to a fresh document and sets the attribute align to left.

Przykład #1 Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

The above example could also be written as the following:

Przykład #2 Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node->set_attribute("align", "left");
$newnode = $doc->append_child($node);
?>

A more complex example is the one below. It first searches for a certain element, duplicates it including its children and adds it as a sibling. Finally a new attribute is added to one of the children of the new sibling and the whole document is dumped.

Przykład #3 Adding a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element->parent_node();
$newnode = $parent->append_child($element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
?>

The above example could also be done with DomNode::insert_before instead of DomNode::append_child.

Migrating to PHP 5

You should use DOMNode::appendChild.

Zobacz też:

  • DomNode::insert_before
  • DomNode::clone_node

DomNode::add_namespace
DomNode::append_sibling
DOM XML (PHP 4) Funkcje


Adds new sibling to a node

DomNode::append_child
DomNode::attributes
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::append_sibling

(PHP 4 >= 4.2.0)

DomNode::append_sibling — Adds new sibling to a node

Opis

domelement DomNode::append_sibling ( domelement $newnode )

This functions appends a sibling to an existing node. The child can be created with e.g. domdocument_create_element(), domdocument_create_text() etc. or simply by using any other node.

Before a new sibling is added it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of an XML document. The return value is the added sibling. If you plan to do further modifications on the added sibling you must use the returned node.

This function has been added to provide the behaviour of domnode_append_child() as it works till PHP 4.2.

See also domnode_append_before().

DomNode::append_child
DomNode::attributes
DOM XML (PHP 4) Funkcje


Returns list of attributes

DomNode::append_sibling
DomNode::child_nodes
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::attributes

(PHP 4 >= 4.1.0)

DomNode::attributes — Returns list of attributes

Opis

array DomNode::attributes ( void )

This function only returns an array of attributes if the node is of type XML_ELEMENT_NODE.

(PHP >= 4.3 only) If no attributes are found, NULL is returned.

DomNode::append_sibling
DomNode::child_nodes
DOM XML (PHP 4) Funkcje


Returns children of node

DomNode::attributes
DomNode::clone_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::child_nodes

(PHP 4 >= 4.1.0)

DomNode::child_nodes — Returns children of node

Opis

array DomNode::child_nodes ( void )

Returns all children of the node.

See also domnode_next_sibling(), and domnode_previous_sibling().

DomNode::attributes
DomNode::clone_node
DOM XML (PHP 4) Funkcje


Clones a node

DomNode::child_nodes
DomNode::dump_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::clone_node

(PHP 4 >= 4.1.0)

DomNode::clone_node — Clones a node

Opis

domelement DomNode::clone_node ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

DomNode::child_nodes
DomNode::dump_node
DOM XML (PHP 4) Funkcje


Dumps a single node

DomNode::clone_node
DomNode::first_child
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::dump_node

(PHP 4 >= 4.1.0)

DomNode::dump_node — Dumps a single node

Opis

string DomNode::dump_node ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

See also domdocument_dump_mem().

DomNode::clone_node
DomNode::first_child
DOM XML (PHP 4) Funkcje


Returns first child of node

DomNode::dump_node
DomNode::get_content
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::first_child

(PHP 4 >= 4.1.0)

DomNode::first_child — Returns first child of node

Opis

domelement DomNode::first_child ( void )

Returns the first child of the node.

(PHP >= 4.3 only) If no first child is found, NULL is returned.

See also domnode_last_child(), and
domnode_next_sibling(),
domnode_previous_sibling().

DomNode::dump_node
DomNode::get_content
DOM XML (PHP 4) Funkcje


Gets content of node

DomNode::first_child
DomNode::has_attributes
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::get_content

(PHP 4 >= 4.2.0)

DomNode::get_content — Gets content of node

Opis

string DomNode::get_content ( void )

This function returns the content of the actual node.

Przykład #1 Getting a content

<?php
if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();

$node_array = $root->get_elements_by_tagname("element");

for ($i = 0; $i<count($node_array); $i++) {
    $node = $node_array[$i];
    echo "The element[$i] is: " . $node->get_content();
}

?>

DomNode::first_child
DomNode::has_attributes
DOM XML (PHP 4) Funkcje


Checks if node has attributes

DomNode::get_content
DomNode::has_child_nodes
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::has_attributes

(PHP 4 >= 4.1.0)

DomNode::has_attributes — Checks if node has attributes

Opis

bool DomNode::has_attributes ( void )

This function checks if the node has attributes.

See also domnode_has_child_nodes().

DomNode::get_content
DomNode::has_child_nodes
DOM XML (PHP 4) Funkcje


Checks if node has children

DomNode::has_attributes
DomNode::insert_before
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::has_child_nodes

(PHP 4 >= 4.1.0)

DomNode::has_child_nodes — Checks if node has children

Opis

bool DomNode::has_child_nodes ( void )

This function checks if the node has children.

See also domnode_child_nodes().

DomNode::has_attributes
DomNode::insert_before
DOM XML (PHP 4) Funkcje


Inserts new node as child

DomNode::has_child_nodes
DomNode::is_blank_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::insert_before

(PHP 4 >= 4.1.0)

DomNode::insert_before — Inserts new node as child

Opis

domelement DomNode::insert_before ( domelement $newnode , domelement $refnode )

This function inserts the new node newnode right before the node refnode. The return value is the inserted node. If you plan to do further modifications on the appended child you must use the returned node.

(PHP >= 4.3 only) If newnode already is part of a document, it will be first unlinked from its existing context. If refnode is NULL, then newnode will be inserted at the end of the list of children.

domnode_insert_before() is very similar to domnode_append_child() as the following example shows which does the same as the example at domnode_append_child().

Przykład #1 Adding a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element->insert_before($element, $element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<pre>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</pre>";
?>

See also domnode_append_child().

DomNode::has_child_nodes
DomNode::is_blank_node
DOM XML (PHP 4) Funkcje


Checks if node is blank

DomNode::insert_before
DomNode::last_child
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::is_blank_node

(PHP 4 >= 4.1.0)

DomNode::is_blank_node — Checks if node is blank

Opis

bool DomNode::is_blank_node ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

DomNode::insert_before
DomNode::last_child
DOM XML (PHP 4) Funkcje


Returns last child of node

DomNode::is_blank_node
DomNode::next_sibling
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::last_child

(PHP 4 >= 4.1.0)

DomNode::last_child — Returns last child of node

Opis

domelement DomNode::last_child ( void )

Returns the last child of the node.

(PHP >= 4.3 only) If no last child is found, NULL is returned.

See also domnode_first_child(), and
domnode_next_sibling(),
domnode_previous_sibling().

DomNode::is_blank_node
DomNode::next_sibling
DOM XML (PHP 4) Funkcje


Returns the next sibling of node

DomNode::last_child
DomNode::node_name
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::next_sibling

(PHP 4 >= 4.1.0)

DomNode::next_sibling — Returns the next sibling of node

Opis

domelement DomNode::next_sibling ( void )

This function returns the next sibling of the current node. If there is no next sibling it returns FALSE (< 4.3) or null (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

Przykład #1 Iterate over children

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element->first_child();

while ($child) {
   print_r($child);
   $child = $child->next_sibling();
}
?>

See also domnode_previous_sibling().

DomNode::last_child
DomNode::node_name
DOM XML (PHP 4) Funkcje


Returns name of node

DomNode::next_sibling
DomNode::node_type
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::node_name

(PHP 4 >= 4.1.0)

DomNode::node_name — Returns name of node

Opis

string DomNode::node_name ( void )

Returns name of the node. The name has different meanings for the different types of nodes as illustrated in the following table.

Meaning of value
Type | Meaning
DomAttribute | value of attribute
DomAttribute |
DomCDataSection | #cdata-section
DomComment | #comment
DomDocument | #document
DomDocumentType | document type name
DomElement | tag name
DomEntity | name of entity
DomEntityReference | name of entity reference
DomNotation | notation name
DomProcessingInstruction | target
DomText | #text

DomNode::next_sibling
DomNode::node_type
DOM XML (PHP 4) Funkcje


Returns type of node

DomNode::node_name
DomNode::node_value
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::node_type

(PHP 4 >= 4.1.0)

DomNode::node_type — Returns type of node

Opis

int DomNode::node_type ( void )

Returns the type of the node. All possible types are listed in the table in the introduction.

<?php

include 'example.inc';

$dom = domxml_open_mem($xmlstr);

$chapter = $dom->document_element();

// Let's see the elements contained in chapter
foreach($chapter->child_nodes() as $node) {
  if ($node->node_type() == XML_ELEMENT_NODE) {
    echo $node->node_name() . "\n";
  }
}

?>

Powyższy przykład wyświetli:

title
para
DomNode::node_name
DomNode::node_value
DOM XML (PHP 4) Funkcje


Returns value of a node

DomNode::node_type
DomNode::owner_document
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::node_value

(PHP 4 >= 4.1.0)

DomNode::node_value — Returns value of a node

Opis

string DomNode::node_value ( void )

Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.

Meaning of value
Type | Meaning
DomAttribute | value of attribute
DomAttribute |
DomCDataSection | content
DomComment | content of comment
DomDocument | null
DomDocumentType | null
DomElement | null
DomEntity | null
DomEntityReference | null
DomNotation | null
DomProcessingInstruction | entire content without target
DomText | content of text

DomNode::node_type
DomNode::owner_document
DOM XML (PHP 4) Funkcje


Returns the document this node belongs to

DomNode::node_value
DomNode::parent_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::owner_document

(PHP 4 >= 4.1.0)

DomNode::owner_document — Returns the document this node belongs to

Opis

domdocument DomNode::owner_document ( void )

This function returns the document the current node belongs to.

The following example will create two identical lists of children.

Przykład #1 Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->owner_document();
$children = $doc2->children();
print_r($children);
?>

See also domnode_insert_before().

DomNode::node_value
DomNode::parent_node
DOM XML (PHP 4) Funkcje


Returns the parent of the node

DomNode::owner_document
DomNode::prefix
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::parent_node

(PHP 4 >= 4.1.0)

DomNode::parent_node — Returns the parent of the node

Opis

domnode DomNode::parent_node ( void )

This function returns the parent node.

(PHP >= 4.3 only) If no parent is found, NULL is returned.

The following example will show two identical lists of children.

Przykład #1 Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->parent_node();
$children = $doc2->children();
print_r($children);
?>

DomNode::owner_document
DomNode::prefix
DOM XML (PHP 4) Funkcje


Returns name space prefix of node

DomNode::parent_node
DomNode::previous_sibling
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::prefix

(PHP 4 >= 4.1.0)

DomNode::prefix — Returns name space prefix of node

Opis

string DomNode::prefix ( void )

Returns the name space prefix of the node.

DomNode::parent_node
DomNode::previous_sibling
DOM XML (PHP 4) Funkcje


Returns the previous sibling of node

DomNode::prefix
DomNode::remove_child
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::previous_sibling

(PHP 4 >= 4.1.0)

DomNode::previous_sibling — Returns the previous sibling of node

Opis

domelement DomNode::previous_sibling ( void )

This function returns the previous sibling of the current node. If there is no previous sibling it returns FALSE (< 4.3) or NULL (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

See also domnode_next_sibling().

DomNode::prefix
DomNode::remove_child
DOM XML (PHP 4) Funkcje


Removes child from list of children

DomNode::previous_sibling
DomNode::replace_child
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::remove_child

(PHP 4 >= 4.2.0)

DomNode::remove_child — Removes child from list of children

Opis

domtext DomNode::remove_child ( domtext $oldchild )

This functions removes a child from a list of children. If child cannot be removed or is not a child the function will return FALSE. If the child could be removed the functions returns the old child.

Przykład #1 Removing a child

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element->child_nodes();
$child = $element->remove_child($children[0]);

echo "<PRE>";
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
echo "</PRE>";
?>

See also domnode_append_child().

DomNode::previous_sibling
DomNode::replace_child
DOM XML (PHP 4) Funkcje


Replaces a child

DomNode::remove_child
DomNode::replace_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::replace_child

(PHP 4 >= 4.2.0)

DomNode::replace_child — Replaces a child

Opis

domelement DomNode::replace_child ( domelement $newnode , domelement $oldnode )

(PHP 4.2) This function replaces the child oldnode with the passed new node. If the new node is already a child it will not be added a second time. If the old node cannot be found the function returns FALSE. If the replacement succeeds the old node is returned.

(PHP 4.3) This function replaces the child oldnode with the passed newnode, even if the new node already is a child of the DomNode. If newnode was already inserted in the document it is first unlinked from its existing context. If the old node cannot be found the function returns FALSE. If the replacement succeeds the old node is returned. (This behaviour is according to the W3C specs).

See also domnode_append_child()

DomNode::remove_child
DomNode::replace_node
DOM XML (PHP 4) Funkcje


Replaces node

DomNode::replace_child
DomNode::set_content
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::replace_node

(PHP 4 >= 4.2.0)

DomNode::replace_node — Replaces node

Opis

domelement DomNode::replace_node ( domelement $newnode )

(PHP 4.2) This function replaces an existing node with the passed new node. Before the replacement newnode is copied if it has a parent to make sure a node which is already in the document will not be inserted a second time. This behaviour enforces doing all modifications on the node before the replacement or to refetch the inserted node afterwards with functions like domnode_first_child(), domnode_child_nodes() etc..

(PHP 4.3) This function replaces an existing node with the passed new node. It is not copied anymore. If newnode was already inserted in the document it is first unlinked from its existing context. If the replacement succeeds the old node is returned.

See also domnode_append_child()

DomNode::replace_child
DomNode::set_content
DOM XML (PHP 4) Funkcje


Sets content of node

DomNode::replace_node
DomNode::set_name
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::set_content

(PHP 4 >= 4.1.0)

DomNode::set_content — Sets content of node

Opis

bool DomNode::set_content ( string $content )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

DomNode::replace_node
DomNode::set_name
DOM XML (PHP 4) Funkcje


Sets name of node

DomNode::set_content
DomNode::set_namespace
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::set_name

(PHP 4 >= 4.1.0)

DomNode::set_name — Sets name of node

Opis

bool DomNode::set_name ( void )

Sets name of node.

See also domnode_node_name().

DomNode::set_content
DomNode::set_namespace
DOM XML (PHP 4) Funkcje


Sets namespace of a node

DomNode::set_name
DomNode::unlink_node
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::set_namespace

(PHP 4 >= 4.3.0)

DomNode::set_namespace — Sets namespace of a node

Opis

void DomNode::set_namespace ( string $uri [, string $prefix ] )

Sets the namespace of a node to uri. If there is already a namespace declaration with the same uri in one of the parent nodes of the node, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one.

See also domdocument_create_element_ns(), and domnode_add_namespace()

DomNode::set_name
DomNode::unlink_node
DOM XML (PHP 4) Funkcje


Deletes node

DomNode::set_namespace
DomProcessingInstruction::data
DOM XML (PHP 4) Funkcje
PHP Manual

DomNode::unlink_node

(PHP 4 >= 4.1.0)

DomNode::unlink_node — Deletes node

Opis

void DomNode::unlink_node ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

DomNode::set_namespace
DomProcessingInstruction::data
DOM XML (PHP 4) Funkcje


Returns the data of ProcessingInstruction node

DomNode::unlink_node
DomProcessingInstruction::target
DOM XML (PHP 4) Funkcje
PHP Manual

DomProcessingInstruction::data

(PHP 4 >= 4.1.0)

DomProcessingInstruction::data — Returns the data of ProcessingInstruction node

Opis

string DomProcessingInstruction::data ( void )

This method gets the data of the ProcessingInstruction node.

Zwracane wartości

Returns the data of the Processing Instruction.

Migrating to PHP 5

Use the data property of DOMProcessingInstruction.

DomNode::unlink_node
DomProcessingInstruction::target
DOM XML (PHP 4) Funkcje


Returns the target of a ProcessingInstruction node

DomProcessingInstruction::data
DomXsltStylesheet::process
DOM XML (PHP 4) Funkcje
PHP Manual

DomProcessingInstruction::target

(PHP 4 >= 4.1.0)

DomProcessingInstruction::target — Returns the target of a ProcessingInstruction node

Opis

string DomProcessingInstruction::target ( void )

This method gets the target of the ProcessingInstruction node.

Zwracane wartości

Returns the target of the Processing Instruction.

Migrating to PHP 5

Use the target property of DOMProcessingInstruction.

DomProcessingInstruction::data
DomXsltStylesheet::process
DOM XML (PHP 4) Funkcje


Applies the XSLT-Transformation on a DomDocument Object

DomProcessingInstruction::target
DomXsltStylesheet::result_dump_file
DOM XML (PHP 4) Funkcje
PHP Manual

DomXsltStylesheet::process

(PHP 4 >= 4.1.0)

DomXsltStylesheet::process — Applies the XSLT-Transformation on a DomDocument Object

Opis

DomDocument DomXsltStylesheet::process ( DomDocument $xml_doc [, array $xslt_params [, bool $is_xpath_param [, string $profile_filename ]]] )

Applies an XSLT Transformation on the given DomDocument object.

Parametry

xml_doc

The XML document being transformed, as a DomDocument object.

xslt_params

An associative array that takes pairs of parameter names and values.

is_xpath_param

If set to FALSE the values of the xslt_params will be quoted. This is the default behavior. It allows you to pass the values as PHP strings.

Informacja:

If your strings contains both single and double quotes, you must take care of quoting all the values by yourself and set this parameter to TRUE.

profile_filename

Set this to the path of a filename, if you want profiling information.

Zwracane wartości

Returns the result of the processing, as a DomDocument object.

Migrating to PHP 5

Use XSLTProcessor::setParameter() and XSLTProcessor::transform-to-doc().

Rejestr zmian

Wersja | Opis
4.3.0 | The profile_filename parameter was added.

Zobacz też:

  • domxml_xslt_stylesheet() - Creates a DomXsltStylesheet object from an XSL document in a string
  • domxml_xslt_stylesheet_file() - Creates a DomXsltStylesheet Object from an XSL document in a file
  • domxml_xslt_stylesheet_doc() - Creates a DomXsltStylesheet Object from a DomDocument Object

DomProcessingInstruction::target
DomXsltStylesheet::result_dump_file
DOM XML (PHP 4) Funkcje


Dumps the result from a XSLT-Transformation into a file

DomXsltStylesheet::process
DomXsltStylesheet::result_dump_mem
DOM XML (PHP 4) Funkcje
PHP Manual

DomXsltStylesheet::result_dump_file

(PHP 4 >= 4.1.0)

DomXsltStylesheet::result_dump_file — Dumps the result from a XSLT-Transformation into a file

Opis

string DomXsltStylesheet::result_dump_file ( DomDocument $xmldoc , string $filename )

Since DomXsltStylesheet::process always returns a well-formed XML DomDocument, no matter what output method was declared in

<xsl:output>
and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data.

This function on the contrary honors

<xsl:output method="html|text">
and other output control directives. See the example for instruction on how to use it.

Przykłady

Przykład #1 Saving the result of a XSLT transformation in a file

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_file($result, "filename");
?>

Zobacz też:

  • DomXsltStylesheet::result_dump_mem
  • DomXsltStylesheet::process

DomXsltStylesheet::process
DomXsltStylesheet::result_dump_mem
DOM XML (PHP 4) Funkcje


Dumps the result from a XSLT-Transformation back into a string

DomXsltStylesheet::result_dump_file
domxml_new_doc
DOM XML (PHP 4) Funkcje
PHP Manual

DomXsltStylesheet::result_dump_mem

(PHP 4 >= 4.1.0)

DomXsltStylesheet::result_dump_mem — Dumps the result from a XSLT-Transformation back into a string

Opis

string DomXsltStylesheet::result_dump_mem ( DomDocument $xmldoc )

Since DomXsltStylesheet::process always returns a well-formed XML DomDocument, no matter what output method was declared in

<xsl:output>
and similar attributes/elements, it's of not much use, if you want to output HTML 4 or text data.

This function on the contrary honors

<xsl:output method="html|text">
and other output control directives. See the example for instruction on how to use it.

Przykłady

Przykład #1 Outputting the result of a XSLT transformation

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
echo $xsldoc->result_dump_mem($result);
?>

Zobacz też:

  • DomXsltStylesheet::result_dump_file
  • DomXsltStylesheet::process

DomXsltStylesheet::result_dump_file
domxml_new_doc
DOM XML (PHP 4) Funkcje


Creates new empty XML document

DomXsltStylesheet::result_dump_mem
domxml_open_file
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_new_doc

(PHP 4 >= 4.2.0)

domxml_new_doc — Creates new empty XML document

Opis

DomDocument domxml_new_doc ( string $version )

Creates a new Dom document from scratch and returns it.

Parametry

version

The XML version number of the document.

Zwracane wartości

Returns a new DomDocument instance.

DomXsltStylesheet::result_dump_mem
domxml_open_file
DOM XML (PHP 4) Funkcje


Creates a DOM object from an XML file

domxml_new_doc
domxml_open_mem
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_open_file

(PHP 4 >= 4.2.0)

domxml_open_file — Creates a DOM object from an XML file

Opis

DomDocument domxml_open_file ( string $filename [, int $mode = DOMXML_LOAD_PARSING [, array &$error ]] )

The function parses the XML document in the given file.

Parametry

filename

The path to the XML file. The file is accessed in read-only mode.

mode

This optional parameter can be used to change the behavior of this function.

You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. You can add to it also DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES and DOMXML_LOAD_COMPLETE_ATTRS by bitwise or.

error

If used, it will contain the error messages. error must be passed in by reference.

Zwracane wartości

Returns a DomDocument instance of the given file.

Przykłady

Przykład #1 Opening an XML document from a file

<?php

if (!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

Rejestr zmian

Wersja | Opis
4.3.0 | The parameters mode and error were added.

Zobacz też:

  • domxml_open_mem() - Creates a DOM object of an XML document
  • domxml_new_doc() - Creates new empty XML document

domxml_new_doc
domxml_open_mem
DOM XML (PHP 4) Funkcje


Creates a DOM object of an XML document

domxml_open_file
domxml_version
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_open_mem

(PHP 4 >= 4.2.0)

domxml_open_mem — Creates a DOM object of an XML document

Opis

DomDocument domxml_open_mem ( string $str [, int $mode [, array &$error ]] )

The function parses the XML document in the given string.

Parametry

str

The contents of the XML file.

mode

This optional parameter can be used to change the behavior of this function.

You can use one of the following constants for it: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING or DOMXML_LOAD_RECOVERING. You can add to it also DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES and DOMXML_LOAD_COMPLETE_ATTRS by bitwise or.

error

If used, it will contain the error messages. error must be passed in by reference.

Zwracane wartości

Returns a DomDocument instance of the given XML contents.

Rejestr zmian

Wersja | Opis
4.3.0 | The mode and error parameters were added.

Przykłady

Przykład #1 Opening an XML document in a string

<?php
include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

Zobacz też:

  • domxml_open_file() - Creates a DOM object from an XML file
  • domxml_new_doc() - Creates new empty XML document

domxml_open_file
domxml_version
DOM XML (PHP 4) Funkcje


Gets the XML library version

domxml_open_mem
domxml_xmltree
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_version

(PHP 4 >= 4.1.0)

domxml_version — Gets the XML library version

Opis

string domxml_version ( void )

Gets the version of the XML library currently used.

Zwracane wartości

The version of the XML library, as a string.

Przykłady

Przykład #1 domxml_version() Example

<?php

echo domxml_version();

?>

Powyższy przykład wyświetli coś podobnego do:

20607

domxml_open_mem
domxml_xmltree
DOM XML (PHP 4) Funkcje


Creates a tree of PHP objects from an XML document

domxml_version
domxml_xslt_stylesheet_doc
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_xmltree

(PHP 4 >= 4.2.0)

domxml_xmltree — Creates a tree of PHP objects from an XML document

Opis

DomDocument domxml_xmltree ( string $str )

The function parses the XML document in str and returns a tree PHP objects as the parsed document.

This function is isolated from the other functions, which means you cannot access the tree with any of the other functions. Modifying it, for example by adding nodes, makes no sense since there is currently no way to dump it as an XML file.

However this function may be valuable if you want to read a file and investigate the content.

Parametry

str

The contents of the XML file.

Zwracane wartości

Returns a tree of Dom objects starting by a DomDocument.

domxml_version
domxml_xslt_stylesheet_doc
DOM XML (PHP 4) Funkcje


Creates a DomXsltStylesheet Object from a DomDocument Object

domxml_xmltree
domxml_xslt_stylesheet_file
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_xslt_stylesheet_doc

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_doc — Creates a DomXsltStylesheet Object from a DomDocument Object

Opis

DomXsltStylesheet domxml_xslt_stylesheet_doc ( DomDocument $xsl_doc )

Creates a DomXsltStylesheet object from the given XSL document.

Parametry

xsl_doc

The XSL document, as a DomDocument object.

Zwracane wartości

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor::importStylesheet() with the xsl_doc parameter.

Zobacz też:

  • DomXsltStylesheet::process
  • domxml_xslt_stylesheet() - Creates a DomXsltStylesheet object from an XSL document in a string
  • domxml_xslt_stylesheet_file() - Creates a DomXsltStylesheet Object from an XSL document in a file

domxml_xmltree
domxml_xslt_stylesheet_file
DOM XML (PHP 4) Funkcje


Creates a DomXsltStylesheet Object from an XSL document in a file

domxml_xslt_stylesheet_doc
domxml_xslt_stylesheet
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_xslt_stylesheet_file

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_file — Creates a DomXsltStylesheet Object from an XSL document in a file

Opis

DomXsltStylesheet domxml_xslt_stylesheet_file ( string $xsl_file )

Creates a DomXsltStylesheet object from the given XSL file.

Parametry

xsl_file

The path to the XSL document, as a string.

Zwracane wartości

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor::importStylesheet() with DOMDocument::load($xsl_file) as parameter.

Zobacz też:

  • DomXsltStylesheet::process
  • domxml_xslt_stylesheet() - Creates a DomXsltStylesheet object from an XSL document in a string
  • domxml_xslt_stylesheet_doc() - Creates a DomXsltStylesheet Object from a DomDocument Object

domxml_xslt_stylesheet_doc
domxml_xslt_stylesheet
DOM XML (PHP 4) Funkcje


Creates a DomXsltStylesheet object from an XSL document in a string

domxml_xslt_stylesheet_file
domxml_xslt_version
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_xslt_stylesheet

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet — Creates a DomXsltStylesheet object from an XSL document in a string

Opis

DomXsltStylesheet domxml_xslt_stylesheet ( string $xsl_buf )

Creates a DomXsltStylesheet object from the given XSL buffer.

Parametry

xsl_buf

The XSL document, as a string.

Zwracane wartości

Returns a new instance of DomXsltStylesheet.

Migrating to PHP 5

Call XSLTProcessor::importStylesheet() with DOMDocument::loadXML($xsl_buf) as parameter.

Zobacz też:

  • DomXsltStylesheet::process
  • domxml_xslt_stylesheet_file() - Creates a DomXsltStylesheet Object from an XSL document in a file
  • domxml_xslt_stylesheet_doc() - Creates a DomXsltStylesheet Object from a DomDocument Object

domxml_xslt_stylesheet_file
domxml_xslt_version
DOM XML (PHP 4) Funkcje


Gets the XSLT library version

domxml_xslt_stylesheet
xpath_eval_expression
DOM XML (PHP 4) Funkcje
PHP Manual

domxml_xslt_version

(PHP 4 >= 4.2.0)

domxml_xslt_version — Gets the XSLT library version

Opis

int domxml_xslt_version ( void )

Gets the XSLT library version.

Zwracane wartości

Returns the version number of the XSLT library, as an integer.

Przykłady

Przykład #1 domxml_xslt_version() Example

<?php

echo domxml_xslt_version();

?>

Powyższy przykład wyświetli coś podobnego do:

10112

Zobacz też:

  • domxml_version() - Gets the XML library version

domxml_xslt_stylesheet
xpath_eval_expression
DOM XML (PHP 4) Funkcje


Evaluates the XPath Location Path in the given string

domxml_xslt_version
xpath_eval
DOM XML (PHP 4) Funkcje
PHP Manual

xpath_eval_expression

(PHP 4)

xpath_eval_expression — Evaluates the XPath Location Path in the given string

Opis

XPathObject XPathContext::xpath_eval_expression ( string $expression [, domnode $contextnode ] )
XPathObject xpath_eval_expression ( XPathContext $xpath_context , string $expression [, domnode $contextnode ] )

Przykład #1 xpath_eval_expression() Example

<?php

include("example.inc");

if (!$dom = domxml_open_mem($xmlstr)) {
    echo "Error while parsing the document\n";
    exit;
}

$xpath = xpath_new_context($dom);
var_dump(xpath_eval_expression($xpath, '/chapter/@language'));

?>

Powyższy przykład wyświetli:

object(XPathObject)(2) {
   ["type"]=>
   int(1)
   ["nodeset"]=>
   array(1) {
     [0]=>
     object(domattribute)(5) {
       ["type"]=>
       int(2)
       ["name"]=>
       string(8) "language"
       ["value"]=>
       string(2) "en"
       [0]=>
       int(7)
       [1]=>
       int(138004256)
     }
  }
}

See also xpath_eval().

domxml_xslt_version
xpath_eval
DOM XML (PHP 4) Funkcje


Evaluates the XPath Location Path in the given string

xpath_eval_expression
xpath_new_context
DOM XML (PHP 4) Funkcje
PHP Manual

xpath_eval

(PHP 4)

xpath_eval — Evaluates the XPath Location Path in the given string

Opis

XPathObject XPathContext::xpath_eval ( string $xpath_expression [, domnode $contextnode ] )
XPathObject xpath_eval ( XPathContext $xpath_context , string $xpath_expression [, domnode $contextnode ] )

The optional contextnode can be specified for doing relative XPath queries.

See also xpath_new_context().

xpath_eval_expression
xpath_new_context
DOM XML (PHP 4) Funkcje


Creates new xpath context

xpath_eval
xpath_register_ns_auto
DOM XML (PHP 4) Funkcje
PHP Manual

xpath_new_context

(PHP 4)

xpath_new_context — Creates new xpath context

Opis

XPathContext xpath_new_context ( domdocument $dom_document )

Creates a new xpath context.

Zobacz też:

  • xpath_eval() - Evaluates the XPath Location Path in the given string

xpath_eval
xpath_register_ns_auto
DOM XML (PHP 4) Funkcje


Register the given namespace in the passed XPath context

xpath_new_context
xpath_register_ns
DOM XML (PHP 4) Funkcje
PHP Manual

xpath_register_ns_auto

(PHP 4 >= 4.3.0)

xpath_register_ns_auto — Register the given namespace in the passed XPath context

Opis

bool xpath_register_ns_auto ( XPathContext $xpath_context [, object $context_node ] )
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ż:

  • xpath_register_ns() - Register the given namespace in the passed XPath context

xpath_new_context
xpath_register_ns
DOM XML (PHP 4) Funkcje


Register the given namespace in the passed XPath context

xpath_register_ns_auto
xptr_eval
DOM XML (PHP 4) Funkcje
PHP Manual

xpath_register_ns

(PHP 4 >= 4.2.0)

xpath_register_ns — Register the given namespace in the passed XPath context

Opis

bool xpath_register_ns ( XPathContext $xpath_context , string $prefix , string $uri )
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ż:

  • xpath_register_ns_auto() - Register the given namespace in the passed XPath context

xpath_register_ns_auto
xptr_eval
DOM XML (PHP 4) Funkcje


Evaluate the XPtr Location Path in the given string

xpath_register_ns
xptr_new_context
DOM XML (PHP 4) Funkcje
PHP Manual

xptr_eval

(PHP 4)

xptr_eval — Evaluate the XPtr Location Path in the given string

Opis

int XPathContext::xptr_eval ( string $eval_str [, domnode $contextnode ] )
int xptr_eval ( XPathContext $xpath_context , string $eval_str [, domnode $contextnode ] )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

xpath_register_ns
xptr_new_context
DOM XML (PHP 4) Funkcje


Create new XPath Context

xptr_eval
libxml
DOM XML (PHP 4) Funkcje
PHP Manual

xptr_new_context

(PHP 4)

xptr_new_context — Create new XPath Context

Opis

XPathContext xptr_new_context ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

xptr_eval
libxml
DOM XML (PHP 4) Funkcje


libxml

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • libXMLError — The libXMLError class
  • libxml Funkcje
    • libxml_clear_errors — Clear libxml error buffer
    • libxml_disable_entity_loader — Disable the ability to load external entities
    • libxml_get_errors — Retrieve array of errors
    • libxml_get_last_error — Retrieve last error from libxml
    • libxml_set_streams_context — Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed
xptr_new_context
Wstęp
Przetwarzanie XML


Wstęp

These functions/constants are available as of PHP 5.1.0, and the following core extensions rely on this libxml extension: DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XSLT, XML, XMLReader, XMLRPC i XMLWriter.

libxml
Instalacja/Konfiguracja
libxml


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
libxml


Wymagania

This extension requires » libxml >= 2.6.0.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

The libxml extension is enabled by default, although it may be disabled with --disable-libxml .

The optional --with-libxml-dir directive is used to specify the location of libxml on the system that PHP is being compiled on, otherwise only the default locations are scanned. The configure process checks for libxml (specifically, xml2-config) in the following order:

  1. The location ([DIR]) specified with --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

If configure cannot find xml2-config in the directory specified by --with-libxml-dir , then it'll continue on and check the default locations.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

LIBXML_COMPACT (integer)
Activate small nodes allocation optimization. This may speed up your application without needing to change the code.

Informacja:

Only available in Libxml >= 2.6.21

LIBXML_DTDATTR (integer)
Default DTD attributes
LIBXML_DTDLOAD (integer)
Load the external subset
LIBXML_DTDVALID (integer)
Validate with the DTD
LIBXML_NOBLANKS (integer)
Remove blank nodes
LIBXML_NOCDATA (integer)
Merge CDATA as text nodes
LIBXML_NOEMPTYTAG (integer)
Expand empty tags (e.g. <br/> to <br></br>)

Informacja:

This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.

LIBXML_NOENT (integer)
Substitute entities
LIBXML_NOERROR (integer)
Suppress error reports
LIBXML_NONET (integer)
Disable network access when loading documents
LIBXML_NOWARNING (integer)
Suppress warning reports
LIBXML_NOXMLDECL (integer)
Drop the XML declaration when saving a document

Informacja:

Only available in Libxml >= 2.6.21

LIBXML_NSCLEAN (integer)
Remove redundant namespaces declarations
LIBXML_PARSEHUGE (integer)
Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document or the entity recursion, as well as limits of the size of text nodes.

Informacja:

Only available in Libxml >= 2.7.0 (as of PHP >= 5.3.2 and PHP >= 5.2.12)

LIBXML_XINCLUDE (integer)
Implement XInclude substitution
LIBXML_ERR_ERROR (integer)
A recoverable error
LIBXML_ERR_FATAL (integer)
A fatal error
LIBXML_ERR_NONE (integer)
No errors
LIBXML_ERR_WARNING (integer)
A simple warning
LIBXML_VERSION (integer)
libxml version like 20605 or 20617
LIBXML_DOTTED_VERSION (string)
libxml version like 2.6.5 or 2.6.17
Typy zasobów
libXMLError
libxml


The libXMLError class

(No version information available, might only be in SVN)

Wstęp

Contains various information about errors thrown by libxml. The error codes are described within the official » xmlError API documentation.

Krótki opis klasy

libXMLError {
/* Właściwości */
public int $level ;
public int $code ;
public int $column ;
public string $message ;
public string $file ;
public int $line ;
}

Właściwości

level

the severity of the error (one of the following constants: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR or LIBXML_ERR_FATAL)

code

The error's code.

column

The column where the error occurred.

Informacja:

This property isn't entirely implemented in libxml and therefore 0 is often returned.

message

The error message, if any.

file

The filename, or empty if the XML was loaded from a string.

line

The line where the error occurred.

Stałe predefiniowane
libxml Funkcje
libxml


libxml Funkcje

Spis treści

  • libxml_clear_errors — Clear libxml error buffer
  • libxml_disable_entity_loader — Disable the ability to load external entities
  • libxml_get_errors — Retrieve array of errors
  • libxml_get_last_error — Retrieve last error from libxml
  • libxml_set_streams_context — Set the streams context for the next libxml document load or write
  • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed
libXMLError
libxml_clear_errors
libxml


Clear libxml error buffer

libxml Funkcje
libxml_disable_entity_loader
libxml Funkcje
PHP Manual

libxml_clear_errors

(PHP 5 >= 5.1.0)

libxml_clear_errors — Clear libxml error buffer

Opis

void libxml_clear_errors ( void )

libxml_clear_errors() clears the libxml error buffer.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • libxml_get_errors() - Retrieve array of errors
  • libxml_get_last_error() - Retrieve last error from libxml

libxml Funkcje
libxml_disable_entity_loader
libxml Funkcje


Disable the ability to load external entities

libxml_clear_errors
libxml_get_errors
libxml Funkcje
PHP Manual

libxml_disable_entity_loader

(PHP 5 >= 5.2.11)

libxml_disable_entity_loader — Disable the ability to load external entities

Opis

bool libxml_disable_entity_loader ([ bool $disable = true ] )

Disable/enable the ability to load external entities.

Parametry

disable

Disable (TRUE) or enable (FALSE) libxml extensions (such as DOM, XMLWriter and XMLReader) to load external entities.

Zwracane wartości

Returns the previous value.

Zobacz też:

  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • The LIBXML_NONET constant

libxml_clear_errors
libxml_get_errors
libxml Funkcje


Retrieve array of errors

libxml_disable_entity_loader
libxml_get_last_error
libxml Funkcje
PHP Manual

libxml_get_errors

(PHP 5 >= 5.1.0)

libxml_get_errors — Retrieve array of errors

Opis

array libxml_get_errors ( void )

Retrieve array of errors.

Zwracane wartości

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

Przykłady

Przykład #1 A libxml_get_errors() example

This example demonstrates how to build a simple libxml error handler.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <titles>PHP: Behind the Parser</title>
 </movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if (!$doc) {
    $errors = libxml_get_errors();

    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }

    libxml_clear_errors();
}

function display_xml_error($error, $xml)
{
    $return  = $xml[$error->line - 1] . "\n";
    $return .= str_repeat('-', $error->column) . "^\n";

    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "Warning $error->code: ";
            break;
         case LIBXML_ERR_ERROR:
            $return .= "Error $error->code: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "Fatal Error $error->code: ";
            break;
    }

    $return .= trim($error->message) .
               "\n  Line: $error->line" .
               "\n  Column: $error->column";

    if ($error->file) {
        $return .= "\n  File: $error->file";
    }

    return "$return\n\n--------------------------------------------\n\n";
}

?>

Powyższy przykład wyświetli:

  <titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

--------------------------------------------

Zobacz też:

  • libxml_get_last_error() - Retrieve last error from libxml
  • libxml_clear_errors() - Clear libxml error buffer

libxml_disable_entity_loader
libxml_get_last_error
libxml Funkcje


Retrieve last error from libxml

libxml_get_errors
libxml_set_streams_context
libxml Funkcje
PHP Manual

libxml_get_last_error

(PHP 5 >= 5.1.0)

libxml_get_last_error — Retrieve last error from libxml

Opis

LibXMLError libxml_get_last_error ( void )

Retrieve last error from libxml.

Zwracane wartości

Returns a LibXMLError object if there is any error in the buffer, FALSE otherwise.

Zobacz też:

  • libxml_get_errors() - Retrieve array of errors
  • libxml_clear_errors() - Clear libxml error buffer

libxml_get_errors
libxml_set_streams_context
libxml Funkcje


Set the streams context for the next libxml document load or write

libxml_get_last_error
libxml_use_internal_errors
libxml Funkcje
PHP Manual

libxml_set_streams_context

(PHP 5)

libxml_set_streams_context — Set the streams context for the next libxml document load or write

Opis

void libxml_set_streams_context ( resource $streams_context )

Sets the streams context for the next libxml document load or write.

Parametry

streams_context

The stream context resource (created with stream_context_create())

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A libxml_set_streams_context() example

<?php

$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

Zobacz też:

  • stream_context_create() - Create a streams context

libxml_get_last_error
libxml_use_internal_errors
libxml Funkcje


Disable libxml errors and allow user to fetch error information as needed

libxml_set_streams_context
qtdom
libxml Funkcje
PHP Manual

libxml_use_internal_errors

(PHP 5 >= 5.1.0)

libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

Opis

bool libxml_use_internal_errors ([ bool $use_errors = false ] )

libxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.

Parametry

use_errors

Enable (TRUE) user error handling or disable (FALSE) user error handling. Disabling will also clear any existing libxml errors.

Zwracane wartości

This function returns the previous value of use_errors.

Przykłady

Przykład #1 A libxml_use_internal_errors() example

This example demonstrates the basic usage of libxml errors and the value returned by this function.

<?php

// enable user error handling
var_dump(libxml_use_internal_errors(true));

// load the document
$doc = new DOMDocument;

if (!$doc->load('file.xml')) {
    foreach (libxml_get_errors() as $error) {
        // handle errors here
    }

    libxml_clear_errors();
}

?>

Powyższy przykład wyświetli:

bool(false)

Zobacz też:

  • libxml_clear_errors() - Clear libxml error buffer
  • libxml_get_errors() - Retrieve array of errors

libxml_set_streams_context
qtdom
libxml Funkcje


qtdom

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • qtdom Funkcje
    • qdom_error — Returns the error string from the last QDOM operation or FALSE if no errors occurred
    • qdom_tree — Creates a tree of an XML string
libxml_use_internal_errors
Wstęp
Przetwarzanie XML


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.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0.

qtdom
Instalacja/Konfiguracja
qtdom


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
qtdom


Wymagania

You need the Qt-library >=2.2.0

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

Uznaje się, że to rozszerzenie jest nieprowadzone i nieużywane. Jednakże kod źródłowy tego rozszerzenia jest nadal dostępny w repozytorium PECL i można go pobrać za pomocą SVN: » http://svn.php.net/viewvc/pecl/qtdom.

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
qtdom Funkcje
qtdom


qtdom Funkcje

Spis treści

  • qdom_error — Returns the error string from the last QDOM operation or FALSE if no errors occurred
  • qdom_tree — Creates a tree of an XML string
Stałe predefiniowane
qdom_error
qtdom


Returns the error string from the last QDOM operation or FALSE if no errors occurred

qtdom Funkcje
qdom_tree
qtdom Funkcje
PHP Manual

qdom_error

(PHP 4 >= 4.0.5)

qdom_error — Returns the error string from the last QDOM operation or FALSE if no errors occurred

Opis

string qdom_error ( 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.

qtdom Funkcje
qdom_tree
qtdom Funkcje


Creates a tree of an XML string

qdom_error
SDO
qtdom Funkcje
PHP Manual

qdom_tree

(PHP 4 >= 4.0.4)

qdom_tree — Creates a tree of an XML string

Opis

QDomDocument qdom_tree ( string $doc )
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.

qdom_error
SDO
qtdom Funkcje


Service Data Objects

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Limitations
  • Przykłady
    • Basic usage
    • Setting and Getting Property Values
    • Working with Sequenced Data Objects
    • Reflecting on Service Data Objects
  • SDO Funkcje
    • SDO_DAS_ChangeSummary::beginLogging — Begin change logging
    • SDO_DAS_ChangeSummary::endLogging — End change logging
    • SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject
    • SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary
    • SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject
    • SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on
    • SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type
    • SDO_DAS_DataFactory::addType — Add a new type to a model
    • SDO_DAS_DataFactory::getDataFactory — Get a data factory instance
    • SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary
    • SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property
    • SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property
    • SDO_DAS_Setting::getPropertyName — Get the property name for a changed property
    • SDO_DAS_Setting::getValue — Get the old value for the changed property
    • SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified
    • SDO_DataFactory::create — Create an SDO_DataObject
    • SDO_DataObject::clear — Clear an SDO_DataObject's properties
    • SDO_DataObject::createDataObject — Create a child SDO_DataObject
    • SDO_DataObject::getContainer — Get a data object's container
    • SDO_DataObject::getSequence — Get the sequence for a data object
    • SDO_DataObject::getTypeName — Return the name of the type for a data object.
    • SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object.
    • SDO_Exception::getCause — Get the cause of the exception.
    • SDO_List::insert — Insert into a list
    • SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property
    • SDO_Model_Property::getDefault — Get the default value for the property
    • SDO_Model_Property::getName — Get the name of the SDO_Model_Property
    • SDO_Model_Property::getType — Get the SDO_Model_Type of the property
    • SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship
    • SDO_Model_Property::isMany — Test to see if the property is many-valued
    • SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject
    • SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject.
    • SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object
    • SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject
    • SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject
    • SDO_Model_Type::getBaseType — Get the base type for this type
    • SDO_Model_Type::getName — Get the name of the type
    • SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type
    • SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type
    • SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type
    • SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type
    • SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type
    • SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type
    • SDO_Model_Type::isOpenType — Test to see if this type is an open type
    • SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type
    • SDO_Sequence::getProperty — Return the property for the specified sequence index.
    • SDO_Sequence::insert — Insert into a sequence
    • SDO_Sequence::move — Move an item to another sequence position
qdom_tree
Wstęp
Przetwarzanie XML


Wstęp

Service Data Objects (SDOs) enable PHP applications to work with data from different sources (like a database query, an XML file, and a spreadsheet) using a single interface.

Each different kind of data source requires a Data Access Service (DAS) to provide access to the data in the data source. In your PHP application, you use a DAS to create an SDO instance that represents some data in the data source. You can then set and get values in the SDO instance using the standard SDO interface. Finally, you use a DAS to write the modified data back to a data source, typically the same one.

See the list of Data Access Services for details on those currently available. In addition to the provided DASs, SDO also provides interfaces to enable others to be implemented (see the section on SDO Data Access Services Interface for more details).

This extension is derived from concepts taken from the » Service Data Objects specification. It includes a version of the » Apache Tuscany SDO for C++ project.

The Structure of a Service Data Object

A Service Data Object instance is made up of a tree of data objects. The tree is defined by containment relationships between the data objects. For example, a Company data object might consist of a number of Department data objects and therefore the Company would have a containment relationship to the Departments.

An SDO may also have non-containment references between data objects in the tree. For example, one Employee data object might reference another Employee to identify a career mentor.

As well as data objects referencing each other, they can also have primitive properties. For example, the Company data object might have a property called "name" of type string, for holding the name of the company (for example, "Acme").

Each of these properties of a data object - containment relationships, non-containment references, or primitive properties - may be many-valued or single-valued. In the above examples, Departments is many-valued and the Company name is single-valued.

In PHP, each SDO data object is represented as a PHP object. The properties of the data object can be accessed using either object syntax or associative array syntax. We'll see some examples of this later.

SDO
Instalacja/Konfiguracja
SDO


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SDO


Wymagania

The SDO extension requires PHP 5.1.0 or higher. It also requires the libxml2 library. Normally libxml2 will already be installed, but if not, it can be downloaded from » http://www.xmlsoft.org/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


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/sca_sdo.

Informacja:

Earlier versions of the SDO extension required a separate shared library for the XML DAS. This is now obsolete and any references to php_sdo_das_xml.dll or sdo_das_xml.so should be removed from your php.ini.

Unix systems

  1. The three SDO components - the SDO core, the XML DAS and the Relational DAS - are packaged together with Service Component Architecture (SCA) into one PECL project, SCA_SDO, so you can download SCA and all three parts of SDO with the command:

    pecl install SCA_SDO

    This command will build the SDO shared library as well as installing the PHP files that make up SCA and the SDO Relational DAS.

    If you want to use the latest beta version, then instead run:

    pecl install SCA_SDO-beta

  2. The pecl command automatically installs the SDO module into your PHP extensions directory. To enable the SDO extension you must add the following line to php.ini:

    extension=sdo.so

    For more information about building PECL packages, consult the PECL installation section of the manual.

Building SDO on Linux

This section describes how to build the SDO core and XML DAS on Linux. You would only need to know how to do this if you wish to build a recent version that you have checked out of SVN.

  1. Change to the main extension directory: cd < wherever your sdo code is >

  2. Run phpize, which will set up the environment to compile SDO.

  3. Next, run ./configure; make; make install. Please note, you may need to login as root to install the extension.

  4. Make sure that the module is loaded by PHP, by adding extension=sdo.so to your php.ini file.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

SDO_DAS_ChangeSummary::NONE=0 (integer)
Represents a change type of 'none'.
SDO_DAS_ChangeSummary::MODIFICATION=1 (integer)
Represents a change type of 'modification'.
SDO_DAS_ChangeSummary::ADDITION=2 (integer)
Represents a change type of 'addition'.
SDO_DAS_ChangeSummary::DELETION=3 (integer)
Represents a change type of 'deletion'.
Typy zasobów
Limitations
SDO


Limitations

Implementation Limitations

The following are limitations in the current SDO implementation:

  1. There is no support for multi-byte character sets. This will be considered, depending on community requirements, in a Unicode-enabled version of PHP.

SDO Limitations

The following SDO 2.0 concepts are not supported in the current PHP implementation. It is not necessarily the case that these will all be added over time. Their inclusion will depend on community requirements.

  1. Bi-directional relationships.

  2. Type and property alias names.

  3. Read-only properties.

  4. The Helper classes defined in SDO 2.0 are not directly implemented. However equivalent function is provided in a more natural way for PHP. For example the function of CopyHelper::copy() is provided by applying the PHP clone keyword to a data object.

Stałe predefiniowane
Przykłady
SDO


Przykłady

Spis treści

  • Basic usage
  • Setting and Getting Property Values
  • Working with Sequenced Data Objects
  • Reflecting on Service Data Objects
Limitations
Basic usage
SDO


Basic usage

The examples below assume an SDO created with the schema and instance information shown below, using the XML Data Access Service.

The instance document below describes a single company, called 'MegaCorp', which contains a single department, called 'Advanced Technologies'. The Advanced Technologies department contains three employees. The company employeeOfTheMonth is referencing the second employee, 'Jane Doe'.

<?xml version="1.0" encoding="UTF-8" ?>
<company xmlns="companyNS" name="MegaCorp"
  employeeOfTheMonth="E0003">
  <departments name="Advanced Technologies" location="NY" number="123">
    <employees name="John Jones" SN="E0001"/>
    <employees name="Jane Doe" SN="E0003"/>
    <employees name="Al Smith" SN="E0004" manager="true"/>
  </departments>
</company>

The root element of the schema is a company. The company contains departments, and each department contains employees. Each element has a number of attributes to store things like name, serial number, and so on. Finally, the company also has an IDREF attribute which identifies one of the employees as the 'employeeOfTheMonth'.

<xsd:schema
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:sdo="commonj.sdo"
  xmlns:sdoxml="commonj.sdo/xml"
  xmlns:company="companyNS"
  targetNamespace="companyNS">
  <xsd:element name="company" type="company:CompanyType"/>
  <xsd:complexType name="CompanyType">
    <xsd:sequence>
      <xsd:element name="departments" type="company:DepartmentType"
        maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="employeeOfTheMonth" type="xsd:IDREF"
      sdoxml:propertyType="company:EmployeeType"/>
  </xsd:complexType>
  <xsd:complexType name="DepartmentType">
    <xsd:sequence>
      <xsd:element name="employees" type="company:EmployeeType"
        maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="location" type="xsd:string"/>
    <xsd:attribute name="number" type="xsd:int"/>
  </xsd:complexType>
  <xsd:complexType name="EmployeeType">
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="SN" type="xsd:ID"/>
    <xsd:attribute name="manager" type="xsd:boolean"/>
  </xsd:complexType>
</xsd:schema>

The XML Data Access Service maps the schema to an SDO. Attributes such as "name" become primitive properties, the sequence of employees becomes a many-valued containment relationship, and so on. Note that the containment relationships are expressed as one complex type within another, whereas non-containment references are expressed in terms of ID and IDREF, with a special sdoxml:propertyType attribute specifying the type of the non-containment reference.

Przykłady
Setting and Getting Property Values
Przykłady


Setting and Getting Property Values

The following examples assume $company is the root of a tree of data objects created from the schema and instance document shown above.

Przykład #1 Access via property name

Data object properties can be accessed using the object property access syntax. The following sets the company name to 'Acme'.

<?php
$company->name = 'Acme';
?>

Przykład #2 Access via property name as array index

We can also access properties using associative array syntax. The simplest form of this uses the property name as the array index. For example, the following sets the company name and gets the employeeOfTheMonth.

<?php
$company['name'] = 'UltraCorp';
$eotm = $company['employeeOfTheMonth'];
?>

Przykład #3 Data Object iteration

We can iterate over the properties of a data object using foreach. The following iterates over the properties of the employee of the month.

<?php
  $eotm = $company->employeeOfTheMonth;
  foreach ($eotm as $name => $value) {
      echo "$name: $value\n";
  }
?>

which will output:

name: Jane Doe
SN: E0003

The 'manager' property is not output, because it has not been set.

Przykład #4 Access many-valued property by name

Many-valued data object properties can also be accessed using the object property name syntax. The following gets the list of departments.

<?php
$departments = $company->departments;
?>

Przykład #5 Many-valued element access

We can access individual elements of many-valued properties using array syntax. The following accesses the first department in the company.

<?php
$ad_tech_dept = $company->departments[0];
?>

Przykład #6 Many-valued property iteration

Many-valued properties can also be iterated over using foreach. The following iterates over the company's departments.

<?php
  foreach ($company->departments as $department) {
    // ...
  }
?>

Each iteration will assign the next department in the list to the variable $department.

Przykład #7 Chained property access

We can chain property references on a single line. The following sets and gets the name of the first department.

<?php
  $company->departments[0]->name = 'Emerging Technologies';
  $dept_name = $company->departments[0]->name;
?>

Using the associative array syntax, this is equivalent to

<?php
  $company['departments'][0]['name'] = 'Emerging Technologies';
  $dept_name = $company['departments'][0]['name'];
?>

In either case, the dept_name variable is set to 'Emerging Technologies'.

Przykład #8 XPath navigation

The associative array index can be an XPath-like expression. Valid expressions are defined by an augmented sub-set of XPath.

Two forms of indexing into many-valued properties are supported. The first is the standard XPath array syntax with the indexing starting at one, the second is an SDO extension to XPath with an index starting at zero. The standard syntax is:

<?php
  $jane_doe = $company["departments[1]/employees[2]"];
?>

and the SDO XPath extension syntax is:

<?php
  $jane_doe = $company["departments.0/employees.1"];
?>

Both these examples get the second employee from the first department.

Przykład #9 XPath querying

We can use XPath to query and identify parts of a data object based on instance data. The following retrieves the manager from the 'Advanced Technologies' department.

<?php
 $ad_tech_mgr =
  $company["departments[name='Advanced Technologies']/employees[manager=true]"];
?>

Przykład #10 Creating child data objects

A data object can be a factory for its child data objects. A child data object is automatically part of the data graph. The following add a new employee to the 'Advanced Technologies' department.

<?php
  $ad_tech_dept = $company["departments[name='Advanced Technologies']"];
  $new_hire = $ad_tech_dept->createDataObject('employees');
  $new_hire->name = 'John Johnson';
  $new_hire->SN = 'E0005';
  $new_hire->manager = false;
?>

Przykład #11 Unset a primitive property

We can use the isset() and unset() functions to test and remove items from the data object.

The following clears the name of the first department.

<?php
  unset($company->departments[0]->name);
?>

Przykład #12 Unset a data object

unset can also be used to remove a data object from the tree. The following example shows John Jones leaving the company.

<?php
  unset($company->departments[0]->employees[0]);
?>

Przykład #13 Unset a referenced data object

The following removes the 'employeeOfTheMonth' from the company. If this were a containment relationship then the employee would be removed from the company (probably not a good idea to sack your best employee each month!), but since this is a non-containment reference, the employee being referenced will remain in the department in the company, but will no longer be accessible via the employeeOfTheMonth property.

<?php
  if (isset($company->employeeOfTheMonth)) {
    unset($company->employeeOfTheMonth);
  }
?>

Przykład #14 Access via property index

Data object properties can be accessed via their property index using array syntax. The property index is the position at which the property's definition appears in the model (in this case the xml schema). We can see from the schema listing above that the company name attribute is the second company property (the SDO interface makes no distinction between XML attributes and elements). The following sets the company name to 'Acme', with the same result as Access via property name

<?php
  $company[1] = 'Acme';
?>

Using the index directly in this way is likely to be fragile. Normally the property name syntax should be preferred, but the property index may be required in special cases.

Basic usage
Working with Sequenced Data Objects
Przykłady


Working with Sequenced Data Objects

Sequenced data objects are SDOs which can track property ordering across the properties of a data object. They can also contain unstructured text elements (text element which do not belong to any of the SDO's properties). Sequenced data objects are useful for working with XML documents which allow unstructured text (i.e. mixed=true) or if the elements can be interleaved (

<A/><B/><A/>
). This can occur for example when the schema defines maxOccurs>1 on a element which is a complexType with a choice order indicator.

The examples below assume an SDO created with the following schema and instance information, using the XML Data Access Service.

The schema below describes the format of a letter. The letter can optionally contain three properties; date, firstName, and lastName. The schema states mixed="true" which means that unstructured text can be interspersed between the three properties.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

The following is an instance letter document. It contains the three letter properties; date, firstName and lastName, and has unstructured text elements for the address and letter body.

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

When loaded, the letter data object will have the sequence and property indices shown in the table below:

Sequence Index | Property Index:Name | Value
0 | 0:date | March 1, 2005
1 | - | Mutual of Omaha
2 | - | Wild Kingdom, USA
3 | - | Dear
4 | 1:firstName | Casy
5 | 2:lastName | Crocodile
6 | - | Please buy more shark repellent.
7 | - | Your premium is past due.

To ensure sequence indices are maintained, sequenced data objects should be manipulated through the SDO_Sequence interface. This allows the data object's instance data to be manipulated in terms of the sequence index as opposed to the property index (shown in the table above). The following examples assume the letter instance has been loaded into a data object referenced by the variable $letter.

Przykład #1 Getting the SDO_Sequence interface

We obtain a data object's sequence using the getSequence() method. The follow gets the sequence for the letter data object.

<?php
  $letter_seq = $letter->getSequence();
?>

All subsequent examples assume that the $letter_seq variable has been assigned the sequence for the letter data object.

Przykład #2 Get/set sequence values

We can get and set individual values (including unstructured text) using the sequence index. The following sets the firstName to 'Snappy' and gets the last sequence values (the unstructured text, 'Your premium is past due.').

<?php
  $letter_seq[4] = 'Snappy';
  $text = $letter_seq[count($letter_seq) - 1];
?>

Przykład #3 Sequence iteration

We can iterate through the individual sequence values using foreach. The following runs through the individual values in sequence order.

<?php
foreach ($letter->getSequence() as $value) {
    // ...
}
?>

Przykład #4 Sequence versus Data Object

Setting values through the data object interface may result in the value not being part of the sequence. A value set through the data object will only be accessible through the sequence if the property was already part of the sequence. The following example sets the lastName through the data object and gets it through the sequence. This is fine because lastName already exists in the sequence. If it had not previously been set, then lastName would be set to 'Smith', but would not be part of the sequence.

<?php
  $letter[2] = 'Smith';
  $last_name = $letter_seq[5];
?>

Przykład #5 Adding to a sequence

We can add new values to a sequence using the SDO_Sequence::insert() method. The following examples assume that the 'firstName' and 'lastName' properties are initially unset.

<?php
  // Append a firstName value to the sequence
  // value: 'Smith'
  // sequence index: NULL (append)
  // propertyIdentifier: 1 (firtName property index)
  $letter_seq->insert('Smith', NULL, 1);

  // Append a lastName value to the sequence
  // value: 'Jones'
  // sequence index: NULL (append)
  // propertyIdentifier: 'lastName' (lastName property name)
  $letter_seq->insert('Jones', NULL, 'lastName');

  // Append unstructured text
  // value: 'Cancel Subscription.'
  // sequence index: absent (append)
  // propertyIdentifier: absent (unstructured text)
  $letter_seq->insert('Cancel Subscription.');

  // Insert new unstructured text.  Subsequent sequence values
  // are shifted up.
  // value: 'Care of:'
  // sequence index: 1 (insert as second element)
  // propertyIdentifier: absent (unstructured text)
  $letter_seq->insert('Care of:', 1);
?>

Przykład #6 Removing from a sequence

We can use the isset() and unset() functions to test and remove items from the sequence (Note: unset() currently leaves the values in the data object, but this behaviour is likely to change to also remove the data from the data object). A sequence behaves like a contiguous list; therefore, removing items from the middle will shift entries at higher indices down. The following example tests to see if the first sequence element is set and unsets it if is.

<?php
  if (isset($letter_seq[0])) {
    unset($letter_seq[0]);
  }
?>

Setting and Getting Property Values
Reflecting on Service Data Objects
Przykłady


Reflecting on Service Data Objects

SDOs have a knowledge of the structure they have been created to represent (the model). For example, a Company SDO created using the Company XML schema above would only be permitted to contain DepartmentType data objects which in turn could only contain EmployeeType data objects.

Sometimes it is useful to be able to access this model information at runtime. For example, this could be used to automatically generate a user interface for populating a data object. The model information is accessed using reflection.

Przykład #1 Reflecting on a Data Object

The following example shows how we can reflect on an empty Employee data object.

<?php
  // Create the employee data object (e.g. from an XML Data Access Service)
  $employee = ...;
  $reflection = new SDO_Model_ReflectionDataObject($employee);
  print($reflection);
?>

Powyższy przykład wyświetli:

object(SDO_Model_ReflectionDataObject)#4 { - ROOT OBJECT - Type {
companyNS:EmployeeType[3] { commonj.sdo:String $name;
commonj.sdo:String $SN; commonj.sdo:Boolean $manager; } }

Using print on the SDO_Model_ReflectionDataObject writes out the data object's model. We can see from the output how the type companyNS:EmployeeType has three properties and we can see the names of the properties along with their types. Note, the primitive types are listed as SDO types (e.g. commonj.sdo namespace, String type). It is worth noting that this is the SDO model and when these are surfaced to an application they can be treated as the PHP equivalent types (e.g. string and boolean).

Przykład #2 Accessing the type information

We can query the type information of a data object using reflection. The following example checks the type corresponds to a data object rather than a primitive and then iterates through the properties of the type, writing out the name of each property ($type and $property are SDO_Model_Type and SDO_Model_Property objects, respectively).

<?php
    // Create the employee data object (e.g. from an XML Data Access Service)
    $employee = ...;
    $reflection = new SDO_Model_ReflectionDataObject($employee);
    $type = $reflection->getType();
    if (! $type->isDataType()) {
        foreach ($type->getProperties() as $property) {
            print $property->getName() . "\n";
        }
    }
?>

Powyższy przykład wyświetli:

name
SN
manager

Working with Sequenced Data Objects
SDO Funkcje
Przykłady


SDO Funkcje

Data Access Services

The table below lists the currently provided SDO Data Access Services:

DAS Name | Description
SDO_DAS_XML | An XML Data Access Service supporting reading/writing SDOs as XML documents.
SDO_DAS_Relational | A PDO-based Data Access Service supporting reading/writing SDO to relational databases. Implements an optimistic concurrency policy for updates.

Klasy predefiniowane

SDO consists of three sets of interfaces. The first set covers those interfaces for use by typical SDO applications. These are identified by the package prefix 'SDO_'. The second set is those used to reflect on, and work with, the model of a data object. These are identified by the package prefix 'SDO_Model_'. Finally, the third set are those use by Data Access Service implementations and are identified by the package prefix 'SDO_DAS_'. The majority of SDO users will not need to use or understand the 'SDO_Model_' and 'SDO_DAS_' interfaces.

SDO Application Programmer Interface

SDO_DataObject

The main interface through which data objects are manipulated. In addition to the methods below, SDO_DataObject extends the ArrayAccess, SDO_PropertyAccess (defines __get() / __set() methods for property access overloading), Iterator, and Countable interfaces.

Metody

  • getSequence - get the sequence for the data object

  • createDataObject - create a child data object

  • clear - unset the properties of a data object

  • getContainer - get the container (also known as 'parent') of this data object

  • getTypeName - get the name of the type for this data object

  • getTypeNamespaceURI - get the namespace URI of the type for this data object

SDO_Sequence

The interface through which sequenced data objects can be accessed to preserve ordering across a data object's properties and to allow unstructured text. SDO_Sequence preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down. In addition to the methods below, SDO_Sequence extends the ArrayAccess, Iterator and Countable interface.

Metody

  • getProperty - get the property for a given sequence index

  • move - move an element from one property index to another

  • insert - insert a new value into the sequence

SDO_List

The interface through which many-valued properties are manipulated. In addition to the method defined below, SDO_List extends ArrayAccess, Iterator and Countable. SDO_List preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down.

Metody

  • insert - insert a new value into the list

SDO_DataFactory

The interface through which data objects can be created. A Data Access Service is responsible for populating the model (i.e. configuring the data factory with the type and structure information for the data objects it can create.) for the factory and can then optionally return an instance of, or implement, the SDO_DataFactory interface.

Metody

  • create - create a new data object

SDO_Exception

An SDO_Exception is thrown when the caller's request cannot be completed. The subclasses of SDO_Exception are:

  • SDO_PropertyNotSetException - the property specified exists but has not been set or does not have a default value

  • SDO_PropertyNotFoundException - the property specified is not part of the data object's type

  • SDO_TypeNotFoundException - the specified namespace URI or type name is unknown

  • SDO_InvalidConversionException - conversion between the types of the assignment is not possible

  • SDO_IndexOutOfBoundsException - the numeric index into a data object, sequence or list is not in the valid range

  • SDO_UnsupportedOperationException - the request cannot be completed because it is not allowed, for example an attempt to set a read-only property.

Metody

One method is added to those inherited from the built in Exception class:

  • getCause - get the cause of this SDO_Exception

SDO Reflection Application Programmer Interfaces

SDO_Model_ReflectionDataObject

The main interface used to reflect on a data object instance to obtain its model type and property information. It is designed to follow the reflection pattern introduced in PHP 5.

Konstruktor

  • __construct - construct a new SDO_Model_ReflectionDataObject.

Metody

  • export - get a string describing the data object.

  • getType - get the SDO_Model_Type for the data object.

  • getInstanceProperties - get the instance properties of the data object.

  • getContainmentProperty - get the property which defines the containment relationship to the data object.

SDO_Model_Type

The interface through which a data object's type information can be retrieved. This interface can be used to find out the type name and namespace URI of the type, whether the type allow open content, and so on.

Metody

  • getName - get the name of the type.

  • getNamespaceURI - get the namespace URI of the type.

  • isInstance - test for a data object being an instance of the type.

  • getProperties - get the properties of the type.

  • getProperty - get a property of the type.

  • isDataType - test to see if this type is a primitive scalar type.

  • isSequencedType - test to see if this is a sequenced type.

  • isOpenType - test to see if this is an open type.

  • isAbstractType - test to see if this is an abstract type.

  • getBaseType - get the base type of this type (if one exists).

SDO_Model_Property

The interface through which a data object's property information can be retrieved. This interface can be used to find out the type of a property, whether a property has a default value, whether the property is contained or reference by its parent, its cardinality, and so on.

Metody

  • getName - get the name of the property.

  • getType - get the type of the property.

  • isMany - test to see if the property is many-valued.

  • isContainment - test to see if the property describes a containment relationship.

  • getContainingType - get the type which contains this property.

  • getDefault - get the default value for a property.

SDO Data Access Service Developer Interfaces

SDO_DAS_DataObject

The interface through which a Data Access Service can access a data object's SDO_DAS_ChangeSummary. The change summary is used by the Data Access Service to check for conflicts when applying changes back to a data source.

Metody

  • getChangeSummary - get the change summary for a data object

SDO_DAS_ChangeSummary

The interface through which the change history of a data object is accessed. The change summary holds information for any modifications on a data object which occurred since logging was activated. In the case of deletions and modifications, the old values are also held in the change summary.

If logging is no longer active then the change summary only holds changes made up to the point when logging was deactivated. Reactivating logging clears the change summary. This is useful when a set of changes have been written out by a DAS and the data object is to be reused.

Metody

  • beginLogging - begin logging changes made to a data object

  • endLogging - end logging changes made to a data object

  • isLogging - test to see if change logging is on

  • getChangedDataObjects - get a list of the data objects which have been changed

  • getChangeType - get the type of change which has been made to a data object

  • getOldValues - get a list of old values for a data object

  • getOldContainer - get the old container data object for a deleted data object

SDO_DAS_Setting

The interface through which the old value for a property is accessed. A list of settings is returned by the change summary method getOldValues.

Metody

  • getPropertyIndex - get the property index for the changed property

  • getPropertyName - get the property name for the changed property

  • getValue - get the old value for the changed property

  • getListIndex - get the list index for the old value if it was part of a many-valued property

  • isSet - test to see if the property was set prior to being modified

SDO_DAS_DataFactory

The interface for constructing the model for an SDO_DataObject. The SDO_DAS_DataFactory is an abstract class providing a static method which returns a concrete data factory implementation. The implementation is used by Data Access Services to create an SDO model from their model. For example, a Relational Data Access Service might create and populate an SDO_DAS_DataFactory model based on a schema for a relational database.

Metody

  • getDataFactory - static methods for getting a concrete data factory instance

  • addType - add a new type to the SDO model

  • addPropertyToType - add a new property to a type definition in the SDO model

Spis treści

  • SDO_DAS_ChangeSummary::beginLogging — Begin change logging
  • SDO_DAS_ChangeSummary::endLogging — End change logging
  • SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject
  • SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary
  • SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject
  • SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject
  • SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on
  • SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type
  • SDO_DAS_DataFactory::addType — Add a new type to a model
  • SDO_DAS_DataFactory::getDataFactory — Get a data factory instance
  • SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary
  • SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property
  • SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property
  • SDO_DAS_Setting::getPropertyName — Get the property name for a changed property
  • SDO_DAS_Setting::getValue — Get the old value for the changed property
  • SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified
  • SDO_DataFactory::create — Create an SDO_DataObject
  • SDO_DataObject::clear — Clear an SDO_DataObject's properties
  • SDO_DataObject::createDataObject — Create a child SDO_DataObject
  • SDO_DataObject::getContainer — Get a data object's container
  • SDO_DataObject::getSequence — Get the sequence for a data object
  • SDO_DataObject::getTypeName — Return the name of the type for a data object.
  • SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object.
  • SDO_Exception::getCause — Get the cause of the exception.
  • SDO_List::insert — Insert into a list
  • SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property
  • SDO_Model_Property::getDefault — Get the default value for the property
  • SDO_Model_Property::getName — Get the name of the SDO_Model_Property
  • SDO_Model_Property::getType — Get the SDO_Model_Type of the property
  • SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship
  • SDO_Model_Property::isMany — Test to see if the property is many-valued
  • SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject
  • SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject.
  • SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object
  • SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject
  • SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject
  • SDO_Model_Type::getBaseType — Get the base type for this type
  • SDO_Model_Type::getName — Get the name of the type
  • SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type
  • SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type
  • SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type
  • SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type
  • SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type
  • SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type
  • SDO_Model_Type::isOpenType — Test to see if this type is an open type
  • SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type
  • SDO_Sequence::getProperty — Return the property for the specified sequence index.
  • SDO_Sequence::insert — Insert into a sequence
  • SDO_Sequence::move — Move an item to another sequence position
Reflecting on Service Data Objects
SDO_DAS_ChangeSummary::beginLogging
SDO


Begin change logging

SDO Funkcje
SDO_DAS_ChangeSummary::endLogging
SDO Funkcje
PHP Manual

SDO_DAS_ChangeSummary::beginLogging

(^)

SDO_DAS_ChangeSummary::beginLogging — Begin change logging

Opis

void SDO_DAS_ChangeSummary::beginLogging ( 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.

Begin logging changes made to the SDO_DataObject.

Parametry

None.

Zwracane wartości

None.

SDO Funkcje
SDO_DAS_ChangeSummary::endLogging
SDO Funkcje


End change logging

SDO_DAS_ChangeSummary::beginLogging
SDO_DAS_ChangeSummary::getChangeType
SDO Funkcje
PHP Manual

SDO_DAS_ChangeSummary::endLogging

(^)

SDO_DAS_ChangeSummary::endLogging — End change logging

Opis

void SDO_DAS_ChangeSummary::endLogging ( 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.

End logging changes made to an SDO_DataObject.

Parametry

None.

Zwracane wartości

None.

SDO_DAS_ChangeSummary::beginLogging
SDO_DAS_ChangeSummary::getChangeType
SDO Funkcje


Get the type of change made to an SDO_DataObject

SDO_DAS_ChangeSummary::endLogging
SDO_DAS_ChangeSummary::getChangedDataObjects
SDO Funkcje
PHP Manual

SDO_DAS_ChangeSummary::getChangeType

(^)

SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject

Opis

int SDO_DAS_ChangeSummary::getChangeType ( SDO_DataObject $dataObject )
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.

Get the type of change which has been made to the supplied SDO_DataObject.

Parametry

dataObject

The SDO_DataObject which has been changed.

Zwracane wartości

The type of change which has been made. The change type is expressed as an enumeration and will be one of the following four values:

  • SDO_DAS_ChangeSummary::NONE

  • SDO_DAS_ChangeSummary::MODIFICATION

  • SDO_DAS_ChangeSummary::ADDITION

  • SDO_DAS_ChangeSummary::DELETION

SDO_DAS_ChangeSummary::endLogging
SDO_DAS_ChangeSummary::getChangedDataObjects
SDO Funkcje


Get the changed data objects from a change summary

SDO_DAS_ChangeSummary::getChangeType
SDO_DAS_ChangeSummary::getOldContainer
SDO Funkcje
PHP Manual

SDO_DAS_ChangeSummary::getChangedDataObjects

(^)

SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary

Opis

SDO_List SDO_DAS_ChangeSummary::getChangedDataObjects ( 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.

Get an SDO_List of the SDO_DataObjects which have been changed. These data objects can then be used to identify the types of change made to each, along with the old values.

Parametry

None.

Zwracane wartości

Returns an SDO_List of SDO_DataObjects.

SDO_DAS_ChangeSummary::getChangeType
SDO_DAS_ChangeSummary::getOldContainer
SDO Funkcje


Get the old container for a deleted SDO_DataObject

SDO_DAS_ChangeSummary::getChangedDataObjects
SDO_DAS_ChangeSummary::getOldValues
SDO Funkcje
PHP Manual

SDO_DAS_ChangeSummary::getOldContainer

(^)

SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject

Opis

SDO_DataObject SDO_DAS_ChangeSummary::getOldContainer ( SDO_DataObject $data_object )
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.

Get the old container (SDO_DataObject) for a deleted SDO_DataObject.

Parametry

data_object

The SDO_DataObject which has been deleted and whose container we wish to identify.

Zwracane wartości

The old containing data object of the deleted SDO_DataObject.

SDO_DAS_ChangeSummary::getChangedDataObjects
SDO_DAS_ChangeSummary::getOldValues
SDO Funkcje


Get the old values for a given changed SDO_DataObject

SDO_DAS_ChangeSummary::getOldContainer
SDO_DAS_ChangeSummary::isLogging
SDO Funkcje
PHP Manual

SDO_DAS_ChangeSummary::getOldValues

(^)

SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject

Opis

SDO_List SDO_DAS_ChangeSummary::getOldValues ( SDO_DataObject $data_object )
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.

Get a list of the old values for a given changed SDO_DataObject. Returns a list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject.

Parametry

data_object

The data object which has been changed.

Zwracane wartości

A list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject. If the change type is SDO_DAS_ChangeSummary::ADDITION, this list is empty.

SDO_DAS_ChangeSummary::getOldContainer
SDO_DAS_ChangeSummary::isLogging
SDO Funkcje


Test to see whether change logging is switched on

SDO_DAS_ChangeSummary::getOldValues
SDO_DAS_DataFactory::addPropertyToType
SDO Funkcje
PHP Manual

SDO_DAS_ChangeSummary::isLogging

(^)

SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on

Opis

bool SDO_DAS_ChangeSummary::isLogging ( 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.

Test to see whether change logging is switched on.

Parametry

None.

Zwracane wartości

Returns TRUE if change logging is on, otherwise returns FALSE.

SDO_DAS_ChangeSummary::getOldValues
SDO_DAS_DataFactory::addPropertyToType
SDO Funkcje


Adds a property to a type

SDO_DAS_ChangeSummary::isLogging
SDO_DAS_DataFactory::addType
SDO Funkcje
PHP Manual

SDO_DAS_DataFactory::addPropertyToType

(^)

SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type

Opis

void SDO_DAS_DataFactory::addPropertyToType ( string $parent_type_namespace_uri , string $parent_type_name , string $property_name , string $type_namespace_uri , string $type_name [, array $options ] )
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.

Adds a property to a type. The type must already be known to the SDO_DAS_DataFactory (i.e. have been added using addType()). The property becomes a property of the type. This is how the graph model for the structure of an SDO_DataObject is built.

Parametry

parent_type_namespace_uri

The namespace URI for the parent type.

parent_type_name

The type name for the parent type.

property_name

The name by which the property will be known in the parent type.

type_namespace_uri

The namespace URI for the type of the property.

type_name

The type name for the type of the property

options

This array holds one or more key=>value pairs to set attribute values for the property. The optional keywords are:

many

A flag to say whether the property is many-valued. A value of 'true' adds the property as a many-valued property (default is 'false').

readOnly

A flag to say whether the property is read-only. A value of 'true' means the property value cannot be modified through the SDO application APIs (default is 'false').

containment

A flag to say whether the property is contained by the parent. A value of 'true' means the property is contained by the parent. A value of 'false' results in a non-containment reference (default is 'true'). This flag is only interpreted when adding properties which are data object types, otherwise it is ignored.

default

A default value for the property. Omitting this key means that the property does not have a default value. A property can only have a default value if it is a single-valued data type (primitive).

Zwracane wartości

None.

Rejestr zmian

Wersja | Opis
0.5.2 | Optional parameters many, readOnly, and containment deprecated in favour of the options array.

Przykłady

Przykład #1 A SDO_DAS_DataFactory::addPropertyToType() example

The following adds an 'addressline' property to a Person type. The person type is identified by its namespace, 'PersonNS', and type name, 'PersonType'. The type of the 'addressline' property is a many-valued SDO data type (primitive) with namespace 'commonj.sdo' and type name 'String'.

<?php
  $df->addPropertyToType('PersonNS', 'PersonType',
    'addressline', 'commonj.sdo', 'String', array('many'=>true));
?>

SDO_DAS_ChangeSummary::isLogging
SDO_DAS_DataFactory::addType
SDO Funkcje


Add a new type to a model

SDO_DAS_DataFactory::addPropertyToType
SDO_DAS_DataFactory::getDataFactory
SDO Funkcje
PHP Manual

SDO_DAS_DataFactory::addType

(^)

SDO_DAS_DataFactory::addType — Add a new type to a model

Opis

void SDO_DAS_DataFactory::addType ( string $type_namespace_uri , string $type_name [, array $options ] )
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.

Add a new type to the SDO_DAS_DataFactory, defined by its namespace and type name. The type becomes part of the model of data objects that the data factory can create.

Parametry

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

options

This array holds one or more key=>value pairs to set attribute values for the type. The optional keywords are:

open

A flag to say whether the type is open. An SDO_DataObject whose type is open can have properties added to them which are not described by the type. This capability is used to support working with XML documents whose schema support open content such as that described by an <xsd:any> element. The default value is 'false'.

sequenced

A flag to say whether the type is sequenced. Sequenced types can have the ordering across properties preserved and can contain unstructured text. The default value is 'false'. For more information on sequenced types see the section on Working with Sequenced Data Objects.

basetype

If specified, an array of namespace URI and type name strings for the type from which this type is derived. An example of the use of base types is when a type derived in an XML schema inherits from another type by using <extension base="...">.

Zwracane wartości

None.

Przykłady

Przykład #1 A SDO_DAS_DataFactory::addType() example

The following adds a new data object type of 'CompanyType' where that type belongs to the namespace 'CompanyNS'.

<?php
  $df->addType('CompanyNS', 'CompanyType');
?>

SDO_DAS_DataFactory::addPropertyToType
SDO_DAS_DataFactory::getDataFactory
SDO Funkcje


Get a data factory instance

SDO_DAS_DataFactory::addType
SDO_DAS_DataObject::getChangeSummary
SDO Funkcje
PHP Manual

SDO_DAS_DataFactory::getDataFactory

(^)

SDO_DAS_DataFactory::getDataFactory — Get a data factory instance

Opis

SDO_DAS_DataFactory SDO_DAS_DataFactory::getDataFactory ( 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.

Static method to get an instance of an SDO_DAS_DataFactory. This instance is initially only configured with the basic SDO types. A Data Access Service is responsible for populating the data factory model and then allowing PHP applications to create SDOs based on the model through the SDO_DataFactory interface. PHP applications should always obtain a data factory from a configured Data Access Service, not through this interface.

Parametry

None.

Zwracane wartości

Returns an SDO_DAS_DataFactory.

SDO_DAS_DataFactory::addType
SDO_DAS_DataObject::getChangeSummary
SDO Funkcje


Get a data object's change summary

SDO_DAS_DataFactory::getDataFactory
SDO_DAS_Setting::getListIndex
SDO Funkcje
PHP Manual

SDO_DAS_DataObject::getChangeSummary

(^)

SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary

Opis

SDO_DAS_ChangeSummary SDO_DAS_DataObject::getChangeSummary ( 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.

Get the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

Parametry

None.

Zwracane wartości

Returns the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

SDO_DAS_DataFactory::getDataFactory
SDO_DAS_Setting::getListIndex
SDO Funkcje


Get the list index for a changed many-valued property

SDO_DAS_DataObject::getChangeSummary
SDO_DAS_Setting::getPropertyIndex
SDO Funkcje
PHP Manual

SDO_DAS_Setting::getListIndex

(^)

SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property

Opis

int SDO_DAS_Setting::getListIndex ( 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.

Get the list index for a modification made to an element of a many-valued property. For example, if we modified the third element of a many-valued property we could obtain an SDO_DAS_Setting from the change summary corresponding to that modification. A call to getListIndex() on that setting would return the value 2 (lists are indexed from zero).

Parametry

None.

Zwracane wartości

The list index for the element of the many-valued property which has been changed.

SDO_DAS_DataObject::getChangeSummary
SDO_DAS_Setting::getPropertyIndex
SDO Funkcje


Get the property index for a changed property

SDO_DAS_Setting::getListIndex
SDO_DAS_Setting::getPropertyName
SDO Funkcje
PHP Manual

SDO_DAS_Setting::getPropertyIndex

(^)

SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property

Opis

int SDO_DAS_Setting::getPropertyIndex ( 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 property index for the changed property. This index identifies the property which was modified in data object.

Parametry

None.

Zwracane wartości

The property index for a changed property.

SDO_DAS_Setting::getListIndex
SDO_DAS_Setting::getPropertyName
SDO Funkcje


Get the property name for a changed property

SDO_DAS_Setting::getPropertyIndex
SDO_DAS_Setting::getValue
SDO Funkcje
PHP Manual

SDO_DAS_Setting::getPropertyName

(^)

SDO_DAS_Setting::getPropertyName — Get the property name for a changed property

Opis

string SDO_DAS_Setting::getPropertyName ( 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 property name for the changed property. This name identifies the property which was modified in data object.

Parametry

None.

Zwracane wartości

The property name for a changed property.

SDO_DAS_Setting::getPropertyIndex
SDO_DAS_Setting::getValue
SDO Funkcje


Get the old value for the changed property

SDO_DAS_Setting::getPropertyName
SDO_DAS_Setting::isSet
SDO Funkcje
PHP Manual

SDO_DAS_Setting::getValue

(^)

SDO_DAS_Setting::getValue — Get the old value for the changed property

Opis

mixed SDO_DAS_Setting::getValue ( 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 old value for the changed property. This can be used by a Data Access Service when writing updates to a data source. The DAS uses the old value to detect conflicts by comparing it with the current value in the data source. If they do not match, then the data source has been updated since the data object was originally populated, and therefore writing any new updates risks compromising the integrity of the data.

Parametry

None.

Zwracane wartości

Returns the old value of the changed property.

SDO_DAS_Setting::getPropertyName
SDO_DAS_Setting::isSet
SDO Funkcje


Test whether a property was set prior to being modified

SDO_DAS_Setting::getValue
SDO_DataFactory::create
SDO Funkcje
PHP Manual

SDO_DAS_Setting::isSet

(^)

SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified

Opis

bool SDO_DAS_Setting::isSet ( 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.

Test whether a property was set prior to being modified. If it was set prior to being modified then the SDO_DAS_Setting will also contain the old value.

Parametry

None.

Zwracane wartości

Returns TRUE if the property was set prior to being modified, otherwise returns FALSE.

SDO_DAS_Setting::getValue
SDO_DataFactory::create
SDO Funkcje


Create an SDO_DataObject

SDO_DAS_Setting::isSet
SDO_DataObject::clear
SDO Funkcje
PHP Manual

SDO_DataFactory::create

(^)

SDO_DataFactory::create — Create an SDO_DataObject

Opis

void SDO_DataFactory::create ( string $type_namespace_uri , string $type_name )
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.

Create a new SDO_DataObject given the data object's namespace URI and type name.

Parametry

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Zwracane wartości

Returns the newly created SDO_DataObject.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type known to this data factory.

SDO_DAS_Setting::isSet
SDO_DataObject::clear
SDO Funkcje


Clear an SDO_DataObject's properties

SDO_DataFactory::create
SDO_DataObject::createDataObject
SDO Funkcje
PHP Manual

SDO_DataObject::clear

(^)

SDO_DataObject::clear — Clear an SDO_DataObject's properties

Opis

void SDO_DataObject::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.

Clear an SDO_DataObject's properties. Read-only properties are unaffected. Subsequent calls to isset() for the data object will return FALSE.

Parametry

None.

Zwracane wartości

No return values.

SDO_DataFactory::create
SDO_DataObject::createDataObject
SDO Funkcje


Create a child SDO_DataObject

SDO_DataObject::clear
SDO_DataObject::getContainer
SDO Funkcje
PHP Manual

SDO_DataObject::createDataObject

(^)

SDO_DataObject::createDataObject — Create a child SDO_DataObject

Opis

SDO_DataObject SDO_DataObject::createDataObject ( mixed $identifier )
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.

Create a child SDO_DataObject of the default type for the property identified. The data object is automatically inserted into the tree and a reference to it is returned.

Parametry

identifier

Identifies the property for the data object type to be created. Can be either a property name (string), a property index (int), or an SDO_Model_Property.

Zwracane wartości

Returns the newly created SDO_DataObject.

Błędy/Wyjątki

SDO_PropertyNotFoundException

Thrown if the identifier does not correspond to a property of the data object.

SDO_DataObject::clear
SDO_DataObject::getContainer
SDO Funkcje


Get a data object's container

SDO_DataObject::createDataObject
SDO_DataObject::getSequence
SDO Funkcje
PHP Manual

SDO_DataObject::getContainer

(^)

SDO_DataObject::getContainer — Get a data object's container

Opis

SDO_DataObject SDO_DataObject::getContainer ( 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.

Get the data object which contains this data object.

Parametry

None.

Zwracane wartości

Returns the SDO_DataObject which contains this SDO_DataObject, or returns NULL if this is a root SDO_DataObject (i.e. it has no container).

SDO_DataObject::createDataObject
SDO_DataObject::getSequence
SDO Funkcje


Get the sequence for a data object

SDO_DataObject::getContainer
SDO_DataObject::getTypeName
SDO Funkcje
PHP Manual

SDO_DataObject::getSequence

(^)

SDO_DataObject::getSequence — Get the sequence for a data object

Opis

SDO_Sequence SDO_DataObject::getSequence ( 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.

Return the SDO_Sequence for this SDO_DataObject. Accessing the SDO_DataObject through the SDO_Sequence interface acts on the same SDO_DataObject instance data, but preserves ordering across properties.

Parametry

None.

Zwracane wartości

The SDO_Sequence for this SDO_DataObject, or returns NULL if the SDO_DataObject is not of a type which can have a sequence.

SDO_DataObject::getContainer
SDO_DataObject::getTypeName
SDO Funkcje


Return the name of the type for a data object.

SDO_DataObject::getSequence
SDO_DataObject::getTypeNamespaceURI
SDO Funkcje
PHP Manual

SDO_DataObject::getTypeName

(^)

SDO_DataObject::getTypeName — Return the name of the type for a data object.

Opis

string SDO_DataObject::getTypeName ( 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.

Return the name of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getName().

Parametry

None.

Zwracane wartości

The name of the type for the data object.

SDO_DataObject::getSequence
SDO_DataObject::getTypeNamespaceURI
SDO Funkcje


Return the namespace URI of the type for a data object.

SDO_DataObject::getTypeName
SDO_Exception::getCause
SDO Funkcje
PHP Manual

SDO_DataObject::getTypeNamespaceURI

(^)

SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object.

Opis

string SDO_DataObject::getTypeNamespaceURI ( 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.

Return the namespace URI of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getNamespaceURI().

Parametry

None.

Zwracane wartości

The namespace URI of the type for the data object.

SDO_DataObject::getTypeName
SDO_Exception::getCause
SDO Funkcje


Get the cause of the exception.

SDO_DataObject::getTypeNamespaceURI
SDO_List::insert
SDO Funkcje
PHP Manual

SDO_Exception::getCause

(^)

SDO_Exception::getCause — Get the cause of the exception.

Opis

mixed SDO_Exception::getCause ( 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 cause of this exception or NULL if the cause is nonexistent or unknown. Typically the cause will be an SDO_CPPException object, which may be used to obtain additional diagnostic information.

Parametry

None.

Zwracane wartości

Returns the cause of this exception or NULL if the cause is nonexistent or unknown.

SDO_DataObject::getTypeNamespaceURI
SDO_List::insert
SDO Funkcje


Insert into a list

SDO_Exception::getCause
SDO_Model_Property::getContainingType
SDO Funkcje
PHP Manual

SDO_List::insert

(^)

SDO_List::insert — Insert into a list

Opis

void SDO_List::insert ( mixed $value [, int $index ] )
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.

Insert a new element at a specified position in the list. All subsequent list items are moved up.

Parametry

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

index

The position at which to insert the new element. If this argument is not specified then the new value will be appended.

Zwracane wartości

None.

Błędy/Wyjątki

SDO_IndexOutOfBoundsException

Thrown if the list index is less than zero or greater than the size of the list.

SDO_InvalidConversionException

Thrown if the type of the new value does not match the type for the list (e.g. the type of the many-valued property that the list represents).

SDO_Exception::getCause
SDO_Model_Property::getContainingType
SDO Funkcje


Get the SDO_Model_Type which contains this property

SDO_List::insert
SDO_Model_Property::getDefault
SDO Funkcje
PHP Manual

SDO_Model_Property::getContainingType

(^)

SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property

Opis

SDO_Model_Type SDO_Model_Property::getContainingType ( 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 SDO_Model_Type which contains this property.

Parametry

None.

Zwracane wartości

Returns the SDO_Model_Type which contains this property.

SDO_List::insert
SDO_Model_Property::getDefault
SDO Funkcje


Get the default value for the property

SDO_Model_Property::getContainingType
SDO_Model_Property::getName
SDO Funkcje
PHP Manual

SDO_Model_Property::getDefault

(^)

SDO_Model_Property::getDefault — Get the default value for the property

Opis

mixed SDO_Model_Property::getDefault ( 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 default value for the property. Only primitive data type properties can have default values.

Parametry

None.

Zwracane wartości

Returns the default value for the property.

SDO_Model_Property::getContainingType
SDO_Model_Property::getName
SDO Funkcje


Get the name of the SDO_Model_Property

SDO_Model_Property::getDefault
SDO_Model_Property::getType
SDO Funkcje
PHP Manual

SDO_Model_Property::getName

(^)

SDO_Model_Property::getName — Get the name of the SDO_Model_Property

Opis

string SDO_Model_Property::getName ( 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 name of the SDO_Model_Property.

Parametry

None.

Zwracane wartości

Returns the name of the SDO_Model_Property.

SDO_Model_Property::getDefault
SDO_Model_Property::getType
SDO Funkcje


Get the SDO_Model_Type of the property

SDO_Model_Property::getName
SDO_Model_Property::isContainment
SDO Funkcje
PHP Manual

SDO_Model_Property::getType

(^)

SDO_Model_Property::getType — Get the SDO_Model_Type of the property

Opis

SDO_Model_Type SDO_Model_Property::getType ( 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.

Get the SDO_Model_Type of the property. The SDO_Model_Type describes the type information for the property, such as its type name, namespace URI, whether it is a primitive data type, and so on.

Parametry

None.

Zwracane wartości

Returns the SDO_Model_Type describing the property's type information.

SDO_Model_Property::getName
SDO_Model_Property::isContainment
SDO Funkcje


Test to see if the property defines a containment relationship

SDO_Model_Property::getType
SDO_Model_Property::isMany
SDO Funkcje
PHP Manual

SDO_Model_Property::isContainment

(^)

SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship

Opis

bool SDO_Model_Property::isContainment ( 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.

Test to see if the property corresponds to a containment relationship. Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.

Parametry

None.

Zwracane wartości

Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.

SDO_Model_Property::getType
SDO_Model_Property::isMany
SDO Funkcje


Test to see if the property is many-valued

SDO_Model_Property::isContainment
SDO_Model_ReflectionDataObject::__construct
SDO Funkcje
PHP Manual

SDO_Model_Property::isMany

(^)

SDO_Model_Property::isMany — Test to see if the property is many-valued

Opis

bool SDO_Model_Property::isMany ( 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.

Test to see if the property is many-valued. Returns TRUE if this is a many-valued property, otherwise returns FALSE.

Parametry

None.

Zwracane wartości

Returns TRUE if this is a many-valued property, otherwise returns FALSE.

SDO_Model_Property::isContainment
SDO_Model_ReflectionDataObject::__construct
SDO Funkcje


Construct an SDO_Model_ReflectionDataObject

SDO_Model_Property::isMany
SDO_Model_ReflectionDataObject::export
SDO Funkcje
PHP Manual

SDO_Model_ReflectionDataObject::__construct

(^)

SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject

Opis

SDO_Model_ReflectionDataObject::__construct ( SDO_DataObject $data_object )
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.

Construct an SDO_Model_ReflectionDataObject to reflect on an SDO_DataObject. Reflecting on an SDO_DataObject gives access to information about its model. The model contains information such as the data object's type, and whether that type is sequenced (preserves ordering across properties) or open (each instance can have its model extended). The model also holds information about the data object's properties, any default values they may have, and so on.

Parametry

data_object

The SDO_DataObject being reflected upon.

Zwracane wartości

None.

SDO_Model_Property::isMany
SDO_Model_ReflectionDataObject::export
SDO Funkcje


Get a string describing the SDO_DataObject.

SDO_Model_ReflectionDataObject::__construct
SDO_Model_ReflectionDataObject::getContainmentProperty
SDO Funkcje
PHP Manual

SDO_Model_ReflectionDataObject::export

(^)

SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject.

Opis

mixed SDO_Model_ReflectionDataObject::export ( SDO_Model_ReflectionDataObject $rdo [, bool $return ] )
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.

Get a string describing the SDO_DataObject. The default behaviour is to print the output, but if TRUE is specified for return, it is returned as a string.

Parametry

rdo

An SDO_Model_ReflectionDataObject.

return

If TRUE, return the output as a string, otherwise print it.

Zwracane wartości

Returns the output if TRUE is specified for return, otherwise NULL.

SDO_Model_ReflectionDataObject::__construct
SDO_Model_ReflectionDataObject::getContainmentProperty
SDO Funkcje


Get the property which defines the containment relationship to the data object

SDO_Model_ReflectionDataObject::export
SDO_Model_ReflectionDataObject::getInstanceProperties
SDO Funkcje
PHP Manual

SDO_Model_ReflectionDataObject::getContainmentProperty

(^)

SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object

Opis

SDO_Model_Property SDO_Model_ReflectionDataObject::getContainmentProperty ( 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.

Get the SDO_Model_Property that contains the SDO_DataObject. This method is used to navigate up to the parent's property which contains the data object which has been reflected upon.

Parametry

None.

Zwracane wartości

Returns the container's SDO_Model_Property which references the SDO_DataObject, or NULL if it is a root SDO_DataObject.

SDO_Model_ReflectionDataObject::export
SDO_Model_ReflectionDataObject::getInstanceProperties
SDO Funkcje


Get the instance properties of the SDO_DataObject

SDO_Model_ReflectionDataObject::getContainmentProperty
SDO_Model_ReflectionDataObject::getType
SDO Funkcje
PHP Manual

SDO_Model_ReflectionDataObject::getInstanceProperties

(^)

SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject

Opis

array SDO_Model_ReflectionDataObject::getInstanceProperties ( 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.

Get the instance properties for the SDO_DataObject. The instance properties consist of all the properties defined on the data object's type, plus any instance properties from open content (if the data object is an open type).

Parametry

None.

Zwracane wartości

An array of SDO_Model_Property objects.

SDO_Model_ReflectionDataObject::getContainmentProperty
SDO_Model_ReflectionDataObject::getType
SDO Funkcje


Get the SDO_Model_Type for the SDO_DataObject

SDO_Model_ReflectionDataObject::getInstanceProperties
SDO_Model_Type::getBaseType
SDO Funkcje
PHP Manual

SDO_Model_ReflectionDataObject::getType

(^)

SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject

Opis

SDO_Model_Type SDO_Model_ReflectionDataObject::getType ( 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 SDO_Model_Type for the SDO_DataObject. The SDO_Model_Type holds all the information about the data object's type, such as namespace URI, type name, whether it is a primitive data type, and so on.

Parametry

None.

Zwracane wartości

Returns the SDO_Model_Type for the SDO_DataObject.

SDO_Model_ReflectionDataObject::getInstanceProperties
SDO_Model_Type::getBaseType
SDO Funkcje


Get the base type for this type

SDO_Model_ReflectionDataObject::getType
SDO_Model_Type::getName
SDO Funkcje
PHP Manual

SDO_Model_Type::getBaseType

(^)

SDO_Model_Type::getBaseType — Get the base type for this type

Opis

SDO_Model_Type SDO_Model_Type::getBaseType ( 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.

Get the base type for this type. Returns the SDO_Model_Type for the base type if this type inherits from another, otherwise returns NULL. An example of when base types occur is when a type defined in XML schema inherits from another type by using

<extension base="...">
.

Parametry

None.

Zwracane wartości

Returns the SDO_Model_Type for the base type if this type inherits from another, otherwise returns NULL.

SDO_Model_ReflectionDataObject::getType
SDO_Model_Type::getName
SDO Funkcje


Get the name of the type

SDO_Model_Type::getBaseType
SDO_Model_Type::getNamespaceURI
SDO Funkcje
PHP Manual

SDO_Model_Type::getName

(^)

SDO_Model_Type::getName — Get the name of the type

Opis

string SDO_Model_Type::getName ( 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 name of the type. The combination of type name and namespace URI is used to uniquely identify the type.

Parametry

None.

Zwracane wartości

Returns the name of the type.

SDO_Model_Type::getBaseType
SDO_Model_Type::getNamespaceURI
SDO Funkcje


Get the namespace URI of the type

SDO_Model_Type::getName
SDO_Model_Type::getProperties
SDO Funkcje
PHP Manual

SDO_Model_Type::getNamespaceURI

(^)

SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type

Opis

string SDO_Model_Type::getNamespaceURI ( 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 namespace URI of the type. The combination of namespace URI and type name is used to uniquely identify the type.

Parametry

None.

Zwracane wartości

Returns the namespace URI of the type.

SDO_Model_Type::getName
SDO_Model_Type::getProperties
SDO Funkcje


Get the SDO_Model_Property objects defined for the type

SDO_Model_Type::getNamespaceURI
SDO_Model_Type::getProperty
SDO Funkcje
PHP Manual

SDO_Model_Type::getProperties

(^)

SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type

Opis

array SDO_Model_Type::getProperties ( 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.

Get an array of SDO_Model_Property objects describing the properties defined for the SDO_Model_Type. Each SDO_Model_Property holds information such as the property name, default value, and so on.

Parametry

None.

Zwracane wartości

Returns an array of SDO_Model_Property objects.

SDO_Model_Type::getNamespaceURI
SDO_Model_Type::getProperty
SDO Funkcje


Get an SDO_Model_Property of the type

SDO_Model_Type::getProperties
SDO_Model_Type::isAbstractType
SDO Funkcje
PHP Manual

SDO_Model_Type::getProperty

(^)

SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type

Opis

SDO_Model_Property SDO_Model_Type::getProperty ( mixed $identifier )
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.

Get an SDO_Model_Property of the type, identified by its property index or property name.

Parametry

identifier

The property index or property name.

Zwracane wartości

Returns the SDO_Model_Property.

SDO_Model_Type::getProperties
SDO_Model_Type::isAbstractType
SDO Funkcje


Test to see if this SDO_Model_Type is an abstract data type

SDO_Model_Type::getProperty
SDO_Model_Type::isDataType
SDO Funkcje
PHP Manual

SDO_Model_Type::isAbstractType

(^)

SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type

Opis

bool SDO_Model_Type::isAbstractType ( 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.

Test to see if this SDO_Model_Type is an abstract data type. Returns TRUE if this type is abstract, that is, no SDO_DataObject of this type can be instantiated, though other types may inherit from it.

Parametry

None.

Zwracane wartości

Returns TRUE if this type is an abstract data type, otherwise returns FALSE.

SDO_Model_Type::getProperty
SDO_Model_Type::isDataType
SDO Funkcje


Test to see if this SDO_Model_Type is a primitive data type

SDO_Model_Type::isAbstractType
SDO_Model_Type::isInstance
SDO Funkcje
PHP Manual

SDO_Model_Type::isDataType

(^)

SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type

Opis

bool SDO_Model_Type::isDataType ( 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.

Test to see if this SDO_Model_Type is a primitive data type. Returns TRUE if this type is a primitive data type, otherwise returns FALSE.

Parametry

None.

Zwracane wartości

Returns TRUE if this type is a primitive data type, otherwise returns FALSE.

SDO_Model_Type::isAbstractType
SDO_Model_Type::isInstance
SDO Funkcje


Test for an SDO_DataObject being an instance of this SDO_Model_Type

SDO_Model_Type::isDataType
SDO_Model_Type::isOpenType
SDO Funkcje
PHP Manual

SDO_Model_Type::isInstance

(^)

SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type

Opis

bool SDO_Model_Type::isInstance ( SDO_DataObject $data_object )
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.

Test for an SDO_DataObject being an instance of this SDO_Model_Type. Returns TRUE if the SDO_DataObject provided is an instance of this SDO_Model_Type, or a derived type, otherwise returns FALSE.

Parametry

data_object

The SDO_DataObject to be tested.

Zwracane wartości

Returns TRUE if the SDO_DataObject provided is an instance of this SDO_Model_Type, or a derived type, otherwise returns FALSE.

SDO_Model_Type::isDataType
SDO_Model_Type::isOpenType
SDO Funkcje


Test to see if this type is an open type

SDO_Model_Type::isInstance
SDO_Model_Type::isSequencedType
SDO Funkcje
PHP Manual

SDO_Model_Type::isOpenType

(^)

SDO_Model_Type::isOpenType — Test to see if this type is an open type

Opis

bool SDO_Model_Type::isOpenType ( 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.

Test to see if this type is open. Returns TRUE if this type is open, otherwise returns FALSE. An SDO_DataObject whose type is open can have properties added to them which are not described by the type. This capability is used to support working with XML documents whose schema support open content, such as that defined by an

<xsd:any>
element.

Parametry

None.

Zwracane wartości

Returns TRUE if this type is open, otherwise returns FALSE.

SDO_Model_Type::isInstance
SDO_Model_Type::isSequencedType
SDO Funkcje


Test to see if this is a sequenced type

SDO_Model_Type::isOpenType
SDO_Sequence::getProperty
SDO Funkcje
PHP Manual

SDO_Model_Type::isSequencedType

(^)

SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type

Opis

bool SDO_Model_Type::isSequencedType ( 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.

Test to see if this is a sequenced type. Returns TRUE if this type is sequence, otherwise returns FALSE. Sequenced types can have the ordering across properties preserved and can contain unstructured text. For more information on sequenced types see the section on Working with Sequenced Data Objects.

Parametry

None.

Zwracane wartości

Returns TRUE if this type is sequence, otherwise return FALSE.

SDO_Model_Type::isOpenType
SDO_Sequence::getProperty
SDO Funkcje


Return the property for the specified sequence index.

SDO_Model_Type::isSequencedType
SDO_Sequence::insert
SDO Funkcje
PHP Manual

SDO_Sequence::getProperty

(^)

SDO_Sequence::getProperty — Return the property for the specified sequence index.

Opis

SDO_Model_Property SDO_Sequence::getProperty ( int $sequence_index )
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.

Return the property for the specified sequence index.

Parametry

sequence_index

The position of the element in the sequence.

Zwracane wartości

An SDO_Model_Property. A return value of NULL means the sequence element does not belong to a property and must therefore be unstructured text.

Błędy/Wyjątki

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

SDO_Model_Type::isSequencedType
SDO_Sequence::insert
SDO Funkcje


Insert into a sequence

SDO_Sequence::getProperty
SDO_Sequence::move
SDO Funkcje
PHP Manual

SDO_Sequence::insert

(^)

SDO_Sequence::insert — Insert into a sequence

Opis

void SDO_Sequence::insert ( mixed $value [, int $sequenceIndex [, mixed $propertyIdentifier ]] )
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.

Insert a new element at a specified position in the sequence. All subsequent sequence items are moved up.

Parametry

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

sequenceIndex

The position at which to insert the new element. Default is NULL, which results in the new value being appended to the sequence.

propertyIdentifier

Either a property index, a property name, or an SDO_Model_Property, used to identify a property in the sequence's corresponding SDO_DataObject. A value of NULL signifies unstructured text.

Zwracane wartości

None.

Błędy/Wyjątki

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

SDO_InvalidConversionException

Thrown if the type of the new value cannot be juggled to match the type for the specified data object property.

SDO_Sequence::getProperty
SDO_Sequence::move
SDO Funkcje


Move an item to another sequence position

SDO_Sequence::insert
SDO-DAS-Relational
SDO Funkcje
PHP Manual

SDO_Sequence::move

(^)

SDO_Sequence::move — Move an item to another sequence position

Opis

void SDO_Sequence::move ( int $toIndex, int $fromIndex )
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.

Modify the position of the item in the sequence, without altering the value of the property in the SDO_DataObject.

Parametry

toIndex

The destination sequence index. If this index is less than zero or greater than the size of the sequence then the value is appended.

fromIndex

The source sequence index.

Zwracane wartości

None.

Błędy/Wyjątki

SDO_IndexOutOfBoundsException

Thrown if the fromIndex sequence index is less than zero or greater than the size of the sequence.

SDO_Sequence::insert
SDO-DAS-Relational
SDO Funkcje


SDO Relational Data Access Service

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Creating, retrieving, updating and deleting data
    • Specifying the metadata
    • One-table examples
    • Two-table examples
    • Three-table example
  • Limitations
  • SDO-DAS-Relational Funkcje
    • SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database.
    • SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service
    • SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.
    • SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.
    • SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph.
SDO_Sequence::move
Wstęp
Przetwarzanie XML


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.

In order to use the Relational Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, the disconnected way of working, the change summary, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO. In addition, the Relational DAS makes use of the PDO extension to isolate itself from specifics of different back-end relational databases. In order to use the Relational DAS you will need to be able to create and pass a PDO database connection; for this reason you might also want to take a look at the section on PDO.

The job of the Relational DAS is to move data between the application and a relational database. In order to do this it needs to be told the mapping between the database entities - tables, columns, primary keys and foreign keys - and the elements of the SDO model - types, properties, containment relationships and so on. You specify this information as metadata when you construct the Relational DAS.

Overview of Operation

  1. The first step is to call the Relational DAS's constructor, passing the metadata that defines the mapping between database and SDO model. There are examples of this below.

  2. The next step might be to call the executeQuery() or executePreparedQuery() methods on the Relational DAS, passing either a literal SQL statement for the DAS to prepare and execute, or a prepared statement with placeholders and a list of values to be inserted. You may also need to specify a small amount of metadata about the query itself, so that the Relational DAS knows exactly what columns will be returned from the database and in what order. You will also need to pass a PDO database connection.

    The return value from executeQuery() or executePreparedQuery() is a normalised data graph containing all the data from the result set. For a query that returns data obtained from a number of tables, this graph will contain a number of data objects, linked by SDO containment relationships. There may also be SDO non-containment references within the data.

    Once the query has been executed and the data graph constructed, there is no need for either that instance of the Relational DAS or the database connection. There are no locks held on the database. Both the Relational DAS and the PDO database connection can be garbage collected.

  3. Quite possibly the data in the data graph will go through a number of modifications. The data graph can be serialised into the PHP session and so may have a lifetime beyond just one client-server interaction. Data objects can be created and added to the graph, the data objects already in the graph can be deleted, and data objects in the graph can be modified.

  4. Finally, the changes made to the data graph can be applied back to the database using the applyChanges() method of the Relational DAS. For this, another instance of the Relational DAS must be constructed, using the same metadata, and another connection to the database obtained. The connection and the data graph are passed to applyChanges(). At this point the Relational DAS examines the change summary and generates the necessary INSERT, UPDATE and DELETE SQL statements to apply the changes. Any UPDATE and DELETE statements are qualified with the original values of the data so that should the data have changed in the database in the meantime this will be detected. Assuming no such collisions have occurred the changes will be committed to the database. The application can then continue to work with the data graph, make more changes and apply them, or can discard it.

There are other ways of working with the data in the database: it is possible to just create data objects and write them to the database without a preliminary call to executeQuery(), for example. This scenario and others are explored in the Examples section below.

SDO-DAS-Relational
Instalacja/Konfiguracja
SDO-DAS-Relational


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SDO-DAS-Relational


Wymagania

The Relational DAS requires that the SDO extension be installed. The SDO extension requires a version of PHP 5.1, and the Relational DAS requires a recent version that contains an important fix for PDO. The most up-to-date information about required levels of PHP should be found in the changelog for the package on PECL. At the time of writing, though, the Relational DAS requires the most recent beta level of PHP 5.1, that is PHP 5.1.0.

The Relational DAS uses PDO to access the relational database, and so should run with a variety of different relational databases. At the time of writing it has been tested in the following configurations

  • MySQL 4.1.14, on Windows. The Relational DAS operates correctly with the php_pdo_mysql driver that comes with the pre-built binaries for PHP 5.1.0.

  • MySQL 4.1.13, on Linux. It is necessary to have the most up-to-date PDO driver for MySQL, which comes built in to PHP 5.1.0. It may be necessary to uninstall the usual driver that would have come from PECL using pear uninstall pdo_mysql. You will need to configure PHP with the --with-pdo-mysql option.

  • DB2 8.2 Personal Edition, on Windows. The Relational DAS operates correctly with the php_pdo_odbc driver that comes with the pre-built binaries for PHP 5.1.0.

  • DB2 8.2 Personal Developer's Edition, on Linux. The Developer's Edition is needed because it contains the include files needed when PHP is configured and built. You will need to configure PHP with the --with-pdo-odbc=ibm-db2 option.

The Relational DAS applies changes to the database within a user-delimited transaction: that is, it issues a call to PDO::beginTransaction() before beginning to apply changes, and PDO::commit() or PDO::rollback() on completion. Whichever database is chosen, the database and the PDO driver for the database must support these calls.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

The installation instructions for all the SDO components are in the SDO install section of the SDO documentation.

In any case, the essential facts are that the Relational DAS is written in PHP and it should be placed somewhere on the PHP include_path.

Your application will of course need to include the Relational DAS with a statement like this:

<?php
require_once 'SDO/DAS/Relational.php';
?>

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.

Tracing

You may be interested in seeing the SQL statements that are generated in order to apply changes back to the database. At the top of the SDO/DAS/Relational.php you will find a number of constants which control whether the process of constructing and executing the SQL statements is to be traced. Try setting DEBUG_EXECUTE_PLAN to TRUE to see the generated SQL statements.

Instalacja
Typy zasobów
Instalacja/Konfiguracja


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.

The Relational DAS introduces no predefined constants.

Typy zasobów
Przykłady
SDO-DAS-Relational


Przykłady

Spis treści

  • Creating, retrieving, updating and deleting data
  • Specifying the metadata
  • One-table examples
  • Two-table examples
  • Three-table example
Stałe predefiniowane
Creating, retrieving, updating and deleting data
SDO-DAS-Relational


Creating, retrieving, updating and deleting data

This section illustrates how the Relational DAS can be used to create, retrieve, update and delete data in a relational database. Many of the examples are illustrated with a three-table database that contains companies, departments within those companies, and employees that work in those departments. This example is used in a number of places within the SDO literature. See the examples section of the » Service Data Objects specification or the Examples section of the documentation for the SDO extension.

The Relational DAS is constructed with metadata that defines the relational database and how it should be mapped to SDO. The long section that follows describes this metadata and how to construct the Relational DAS. The examples that follow it all assume that this metadata is in an included php file.

The examples below and others can all be found in the Scenarios directory in the Relational DAS package.

The Relational DAS throws exceptions in the event that it finds errors in the metadata or errors when executing SQL statements against the database. For brevity the examples below all omit the use of try/catch blocks around the calls to the Relational DAS.

These examples all differ from the expected use of SDO in two important respects.

First, they show all interactions with the database completed within one script. In this respect these scenarios are not realistic but are chosen to illustrate just the use of the Relational DAS. It is expected that interactions with the database will be separated in time and the data graph serialized and deserialized into the PHP session one or more times as the application interacts with an end user.

Second, all queries executed against the database use hard-coded queries with no variables substituted. In this case it is safe to use the simple executeQuery() call, and this is what the examples illustrate. In practice, though, it is unlikely that the SQL statement is known entirely ahead of time. In order to allow variables to be safely substituted into the SQL queries, without running the risk of injecting SQL with unknown effects, it is safer to use the executePreparedQuery() which takes a prepared SQL statement containing placeholders and a list of values to be substituted.

Przykłady
Specifying the metadata
Przykłady


Specifying the metadata

This first long section describes in detail how the metadata describing the database and the required SDO model is supplied to the Relational DAS.

When the constructor for the Relational DAS is invoked, it needs to be passed several pieces of information. The bulk of the information, passed as an associative array in the first argument to the constructor, tells the Relational DAS what it needs to know about the relational database. It describes the names of the tables, columns, primary keys and foreign keys. It should be fairly easy to understand what is required, and once written it can be placed in a php file and included when needed. The remainder of the information, passed in the second and third arguments to the constructor, tells the Relational DAS what it needs to know about the relationships between objects and the shape of the data graph; it ultimately determines how the data from the database is to be normalized into a graph.

Database metadata

The first argument to the constructor describes the target relational database.

Each table is described by an associative array with up to four keys.

Key | Value
name | The name of the table.
columns | An array listing the names of the columns, in any order.
PK | The name of the column containing the primary key.
FK | An array with two entries, 'from' and 'to', which define a column containing a foreign key, and a table to which the foreign key points. If there are no foreign keys in the table then the 'FK' entry does not need to be specified. Only one foreign key can be specified. Only a foreign key pointing to the primary key of a table can be specified.

<?php
/*****************************************************************
* METADATA DEFINING THE DATABASE
******************************************************************/
$company_table = array (
  'name' => 'company',
  'columns' => array('id', 'name',  'employee_of_the_month'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'employee_of_the_month',
      'to' => 'employee',
      ),
  );
$department_table = array (
  'name' => 'department',
  'columns' => array('id', 'name', 'location', 'number', 'co_id'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'co_id',
      'to' => 'company',
      )
  );
$employee_table = array (
  'name' => 'employee',
  'columns' => array('id', 'name', 'SN', 'manager', 'dept_id'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'dept_id',
      'to' => 'department',
      )
  );
$database_metadata = array($company_table, $department_table, $employee_table);
?>

This metadata corresponds to a relational database that might have been defined to MySQL as:

create table company (
 id integer auto_increment,
 name char(20),
 employee_of_the_month integer,
 primary key(id)
);
create table department (
 id integer auto_increment,
 name char(20),
 location char(10),
 number integer(3),
 co_id integer,
 primary key(id)
);
create table employee (
 id integer auto_increment,
 name char(20),
 SN char(4),
 manager tinyint(1),
 dept_id integer,
 primary key(id)
);

or to DB2 as:

create table company ( \
  id integer not null generated by default as identity,  \
  name varchar(20), \
  employee_of_the_month integer, \
  primary key(id) )
create table department ( \
  id integer not null generated by default as identity, \
  name varchar(20), \
  location varchar(10), \
  number integer, \
  co_id integer, \
  primary key(id) )
create table employee ( \
  id integer not null generated by default as identity, \
  name varchar(20), \
  SN char(4), \
  manager smallint, \
  dept_id integer, \
  primary key(id) )

Note that although in this example there are no foreign keys specified to the database and so the database is not expected to enforce referential integrity, the intention behind the co_id column on the department table and the dept_id column on the employee table is they should contain the primary key of their containing company or department record, respectively. So these two columns are acting as foreign keys.

There is a third foreign key in this example, that from the employee_of_the_month column of the company record to a single row of the employee table. Note the difference in intent between this foreign key and the other two. The employee_of_the_month column represents a single-valued relationship: there can be only one employee of the month for a given company. The co_id and dept_id columns represent multi-valued relationships: a company can contain many departments and a department can contain many employees. This distinction will become evident when the remainder of the metadata picks out the company-department and department-employee relationships as containment relationships.

There are a few simple rules to be followed when constructing the database metadata:

  • All tables must have primary keys, and the primary keys must be specified in the metadata. Without primary keys it is not possible to keep track of object identities. As you can see from the SQL statements that create the tables, primary keys can be auto-generated, that is, generated and assigned by the database when a record is inserted. In this case the auto-generated primary key is obtained from the database and inserted into the data object immediately after the row is inserted into the database.

  • It is not necessary to specify in the metadata all the columns that exist in the database, only those that will be used. For example, if the company table had another column that the application did not want to access with SDO, this need not be specified in the metadata. On the other hand it would have done no harm to specify it: if specified in the metadata but never retrieved, or assigned to by the application, then the unused column will not affect anything.

  • In the database metadata note that the foreign key definitions identify not the destination column in the table which is pointed to, but the table name itself. Strictly, the relational model permits the destination of a foreign key to be a non-primary key. Only foreign keys that point to a primary key are useful for constructing the SDO model, so the metadata specifies the table name. It is understood that the foreign key points to the primary key of the given table.

Given these rules, and given the SQL statements that define the database, the database metadata should be easy to construct.

What the Relational DAS does with the metadata

The Relational DAS uses the database metadata to form most of the SDO model. For each table in the database metadata, an SDO type is defined. Each column which can represent a primitive value (columns which are not defined as foreign keys) are added as properties to the SDO type.

All primitive properties are given a type of string in the SDO model, regardless of their SQL type. When writing values back to the database the Relational DAS will create SQL statements that treat the values as strings, and the database will convert them to the appropriate type.

Foreign keys are interpreted in one of two ways, depending on the metadata in the third argument to the constructor that defines the SDO containment relationships. A discussion of this is therefore deferred until the section on SDO containment relationships below.

Specifying the application root type

The second argument to the constructor is the application root type. The true root of each data graph is an object of a special root type and all application data objects come somewhere below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, the application root type can be inferred, and this argument can be omitted.

Specifying the SDO containment relationships

The third argument to the constructor defines how the types in the model are to be linked together to form a graph. It identifies the parent-child relationships between the types which collectively form a graph. The relationships need to be supported by foreign keys to be found in the data, in a way shortly to be described.

The metadata is an array containing one or more associative arrays, each of which identifies a parent and a child. The example below shows a parent-child relationship from company to department, and another from department to employee. Each of these will become an SDO property defining a multi-valued containment relationship in the SDO model.

<?php
$department_containment = array( 'parent' => 'company', 'child' => 'department');
$employee_containment = array( 'parent' => 'department', 'child' => 'employee');

$SDO_containment_metadata = array($department_containment, $employee_containment);
?>

Foreign keys in the database metadata are interpreted as properties with either multi-valued containment relationships or single-valued non-containment references, depending on whether they have a corresponding SDO containment relationship specified in the metadata. In the example here, the foreign keys from department to company (the co_id column in the department table) and from employee to department (the dept_id column in the employee table) are interpreted as supporting the SDO containment relationships. Each containment relationship mentioned in the SDO containment relationships metadata must have a corresponding foreign key present in the database and defined in the database metadata. The values of the foreign key columns for containment relationships do not appear in the data objects, instead each is represented by a containment relationship from the parent to the child. So the co_id column in the department row in the database, for example, does not appear as a property on the department type, but instead as a containment relationship called department on the company type. Note that the foreign key and the parent-child relationship appear to have opposite senses: the foreign key points from the department to the company, but the parent-child relationship points from company to department.

The third foreign key in this example, the employee_of_the_month , is handled differently. This is not mentioned in the SDO containment relationships metadata. As a consequence this is interpreted in the second way: it becomes a single-valued non-containment reference on the company object, to which can be assigned references to SDO data objects of the employee type. It does appear as a property on the company type. The way to assign a value to it in the SDO data graph is to have a graph that contains an employee object through the containment relationships, and to assign the object to it. This is illustrated in the later examples below.

Creating, retrieving, updating and deleting data
One-table examples
Przykłady


One-table examples

The following set of examples all use the Relational DAS to work with a data graph containing just one application data object, a single company and the data just to be found the company table. These examples do not exercise the power of SDO or the Relational DAS and of course the same result could be achieved more economically with direct SQL statements but they are intended to illustrate how to work with the Relational DAS.

For this very simple scenario it would be possible to simplify the database metadata to include just the company table - if that were done the second and third arguments to the constructor and the column specifier used in the query example would become optional.

Przykład #1 Creating a data object

The simplest example is that of creating a single data object and writing it to the database. In this example a single company object is created, its name is set to 'Acme', and the Relational DAS is called to write the changes to the database. The company name is set here using the property name method. See the Examples section on the SDO extension for other ways of accessing the properties of an object.

Data objects can only be created when you have a data object to start with, however. It is for that reason that the first call to the Relational DAS here is to obtain a root object. This is in effect how to ask for an empty data graph - the special root object is the true root of the tree. The company data object is then created with a call to createDataObject() on the root object. This creates the company data object and inserts it in the graph by inserting into a multi-valued containment property on the root object called 'company'.

When the Relational DAS is called to apply the changes a simple insert statement 'INSERT INTO company (name) VALUES ("Acme");' will be constructed and executed. The auto-generated primary key will be set into the data object and the change summary will be reset, so that it would be possible to continue working with the same data object, modify it, and apply the newer changes a second time.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Obtain a root object and create a company object underneath.
* Make a simple change to the data object.
***************************************************************/
$root = $das  -> createRootDataObject();
$acme = $root -> createDataObject('company');

$acme->name = "Acme";

/**************************************************************
* Get a database connection and write the object to the database
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das -> applyChanges($dbh, $root);
?>

Przykład #2 Retrieving a data object

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

In this example the third argument to executeQuery(), the column specifier is needed as there are other tables in the metadata with column names of name and id. If there were no possible ambiguity it could be omitted.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
         'select name, id from company where name="Acme"',
          array('company.name', 'company.id') );

/**************************************************************
* Echo name and id
***************************************************************/
foreach ($root['company'] as $company) {
  echo "Company obtained from the database has name = " .
  $company['name'] . " and id " . $company['id'] . "\n";
}
?>

Przykład #3 Updating a data object

This example combines the previous two, in the sense that in order to be updated the object must first be retrieved. The application code reverses the company name (so 'Acme' becomes 'emcA') and then the changes are written back to the database in the same way that they were when the object was created. Because the query searches for the name both ways round the program can be run repeatedly to find the company and reverse its name each time.

In this example the same instance of the Relational DAS is reused for the applyChanges(), as is the PDO database handle. This is quite alright; it also alright to allow the previous instances to be garbage collected and to obtain new instances. No state data regarding the graph is held the Relational DAS once it has returned a data graph to the application. All necessary data is either within the graph itself, or can be reconstructed from the metadata.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
  'select name, id from company where name="Acme" or name="emcA"',
  array('company.name', 'company.id') );

/**************************************************************
* Alter the name of just the first company
***************************************************************/
$company = $root['company'][0];
echo "obtained a company with name of " . $company->name . "\n";
$company->name = strrev($company->name);

/**************************************************************
* Write the change back
***************************************************************/
$das->applyChanges($dbh,$root);
?>

Przykład #4 Deleting a data object

Any companies called 'Acme' or its reverse 'emcA' are retrieved. They are then all deleted from the graph with unset.

In this example they are all deleted in one go by unsetting the containing property (the property defining the containment relationship). It is also possible to delete them individually.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
  'select name, id from company where name="Acme" or name="emcA"',
  array('company.name', 'company.id') );

/**************************************************************
* Delete any companies found from the data graph
***************************************************************/
unset($root['company']);

/**************************************************************
* Write the change(s) back
***************************************************************/
$das->applyChanges($dbh,$root);
?>

Specifying the metadata
Two-table examples
Przykłady


Two-table examples

The following set of examples all use two tables from the company database: the company and department tables. These examples exercise more of the function of the Relational DAS.

In this series of examples a company and department are created, retrieved, updated, and finally deleted. This illustrates the lifecycle for a data graph containing more than one object. Note that this example clears out the company and department tables at the start so that the exact results of the queries can be known.

You can find these examples combined into one script called 1cd-CRUD in the Scenarios directory in the Relational DAS package.

Przykład #1 One company, one department - Create

As in the earlier example of creating just one company data object, the first action after constructing the Relational DAS is to call createRootDataObject() to obtain the special root object of the otherwise empty data graph. The company object is then created as a child of the root object, and the department object as a child of the company object.

When it comes to applying the changes, the Relational DAS has to perform special processing to maintain the foreign keys that support the containment relationships, especially if auto-generated primary keys are involved. In this example, the relationship between the auto-generated primary key id in the company table and the co_id column in the department table must be maintained. When inserting a company and department for the first time the Relational DAS has to first insert the company row, then call PDO's getLastInsertId() method to obtain the auto-generated primary key, then add that as the value of the co_id column when inserting the department row.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the two tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh->prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt->execute();

/**************************************************************
* Create a company with name Acme and one department, the Shoe department
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das -> createRootDataObject();

$acme = $root -> createDataObject('company');
$acme -> name = "Acme";

$shoe = $acme->createDataObject('department');
$shoe->name = 'Shoe';

$das -> applyChanges($dbh, $root);

?>

Przykład #2 One company, one department - Retrieve and Update

In this case the SQL query passed to executeQuery() performs an inner join to join the data from the company and department tables. Primary keys for both the company and department tables must be included in the query. The result set is re-normalised to form a normalised data graph. Note that a column specifier is passed as the third argument to the executeQuery() call enabling the Relational DAS to know which column is which in the result set.

Note that the co_id column although used in the query is not needed in the result set. In order to understand what the Relational DAS is doing when it builds the data graph it may be helpful to visualise what the result set looks like. Although the data in the database is normalised, so that multiple department rows can point through their foreign key to one company row, the data in the result set is non-normalised: that is, if there is one company and multiple departments, the values for the company are repeated in each row. The Relational DAS has to reverse this process and turn the result set back into a normalised data graph, with just one company object.

In this example the Relational DAS will examine the result set and column specifier, find data for both the company and department tables, find primary keys for both, and interpret each row as containing data for a department and its parent company. If it has not seen data for that company before (it uses the primary key to check) it creates a company object and then a department object underneath it. If it has seen data for that company before and has already created the company object it just creates the department object underneath.

In this way the Relational DAS can retrieve and renormalise data for multiple companies and multiple departments underneath them.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Retrieve the company and Shoe department, then delete Shoe and add IT
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das->executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];            // get the first company - will be 'Acme'
$shoe = $acme['department'][0];         // get the first department underneath - will be 'Shoe'

unset($acme['department'][0]);

$it = $acme->createDataObject('department');
$it->name = 'IT';

$das -> applyChanges($dbh, $root);
?>

Przykład #3 One company, two departments - Retrieve and Delete

In this example the company and department are retrieved and then deleted. It is not necessary to delete them individually (although that would be possible) - deleting the company object from the data graph also deletes any departments underneath it.

Note the way that the company object is actually deleted using the PHP unset call. The unset has to be performed on the containing property which in this case is the company property on the special root object. You must use:

<?php
unset($root['company'][0]);
?>
and not:
<?php
unset($acme); //WRONG
?>
Simply unsetting $acme would destroy the variable but leave the data in the data graph untouched.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Retrieve the company and IT department, then delete the whole company
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das->executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];
$it = $acme['department'][0];

unset($root['company'][0]);

$das -> applyChanges($dbh, $root);

?>

One-table examples
Three-table example
Przykłady


Three-table example

The following examples use all three tables from the company database: the company, department, and employee tables. These introduce the final piece of function not exercised by the examples above: the non-containment reference employee_of_the_month.

Like the examples above for company and department, this set of examples is intended to illustrate the full lifecycle of such a data graph.

Przykład #1 One company, one department, one employee - Create

In this example a company is created containing one department and just one employee. Note that this example clears out all three tables at the start so that the exact results of the queries can be known.

Note how once the company, department and employee have been created, the employee_of_the_month property of the company can be made to point at the new employee. As this is a non-containment reference, this cannot be done until the employee object has been created within the graph. Non-containment references need to be managed carefully. For example if the employee were now deleted from under the department, it would not be correct to try to save the graph without first clearing or re-assigning the employee_of_the_month property. The closure rule for SDO data graphs requires that any object pointed at by a non-containment reference must also be reachable by containment relationships.

When it comes to inserting the graph into the database, the procedure is similar to the example of inserting the company and department, but employee_of_the_month introduces an extra complexity. The Relational DAS needs to insert the objects working down the tree formed by containment relationships, so company, then department, then employee. This is necessary so that it always has the auto-generated primary key of a parent on hand to include in a child row. But when the company row is inserted the employee who is employee of the month has not yet been inserted and the primary key is not known. The procedure is that after the employee record is inserted and its primary key known, a final step is performed in which the company record is updated with the employee's primary key.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the three tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh->prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM EMPLOYEE;');
$rows_affected = $pdo_stmt->execute();

/*************************************************************************************
* Create a tiny but complete company.
* The company name is Acme.
* There is one department, Shoe.
* There is one employee, Sue.
* The employee of the month is Sue.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root             = $das  -> createRootDataObject();
$acme             = $root -> createDataObject('company');
$acme -> name     = "Acme";
$shoe             = $acme -> createDataObject('department');
$shoe -> name     = 'Shoe';
$shoe -> location = 'A-block';
$sue              = $shoe -> createDataObject('employee');
$sue -> name      = 'Sue';
$acme -> employee_of_the_month = $sue;

$das -> applyChanges($dbh, $root);

echo "Wrote back Acme with one department and one employee\n";
?>

Przykład #2 One company, one department, one employee - Retrieve and update

The SQL statement passed to the Relational DAS is this time an inner join that retrieves data from all three tables. Otherwise this example introduces nothing that has not appeared in a previous example.

The graph is updated by the addition of a new department and employee and some alterations to the name properties of the existing objects in the graph. The combined changes are then written back. The Relational DAS will process and apply an arbitrary mixture of additions, modifications and deletions to and from the data graph.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Find the company again and change various aspects.
* Change the name of the company, department and employee.
* Add a second department and a new employee.
* Change the employee of the month.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das->executeQuery($dbh,
  "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
  "from company c, department d, employee e " .
  "where e.dept_id = d.id and d.co_id = c.id and c.name='Acme'",
   array('company.id','company.name','company.employee_of_the_month',
   'department.id','department.name','employee.id','employee.name'));
$acme         = $root['company'][0];

$shoe         = $acme->department[0];
$sue          = $shoe -> employee[0];

$it           = $acme->createDataObject('department');
$it->name     = 'IT';
$it->location = 'G-block';
$billy        = $it->createDataObject('employee');
$billy->name  = 'Billy';

$acme->name   = 'MegaCorp';
$shoe->name   = 'Footwear';
$sue->name    = 'Susan';

$acme->employee_of_the_month = $billy;
$das -> applyChanges($dbh, $root);
echo "Wrote back company with extra department and employee and all the names changed (Megacorp/Footwear/Susan)\n";

?>

Przykład #3 One company, two departments, two employees - Retrieve and delete

The company is retrieved as a complete data graph containing five data objects - the company, two departments and two employees. They are all deleted by deleting the company object. Deleting an object from the graph deletes all the object beneath it in the graph. Five SQL DELETE statements will be generated and executed. As always they will be qualified with a WHERE clause that contains all of the fields that were retrieved, so that any updates to the data in the database in the meantime by another process will be detected.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Now read it one more time and delete it.
* You can delete part, apply the changes, then carry on working with the same graph but
* care is needed to keep closure - you cannot delete the employee who is eotm without
* reassigning. For safety here we delete the company all in one go.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das->executeQuery($dbh,
  "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
  "from company c, department d, employee e " .
  "where e.dept_id = d.id and d.co_id = c.id and c.name='MegaCorp';",
   array('company.id','company.name','company.employee_of_the_month',
   'department.id','department.name','employee.id','employee.name'));
$megacorp = $root['company'][0];

unset($root['company']);
$das -> applyChanges($dbh, $root);

echo "Deleted the company, departments and employees all in one go.\n";

?>

Two-table examples
Limitations
Przykłady


Limitations

There are the following limitations in the current release of the Relational DAS:

  • No support for nulls. There is no support for SQL NULL type. It is not legal to assign PHP NULL to a data object property and the Relational DAS will not write that back as a NULL to the database. If nulls are found in the database on a query, the property will remain unset.

  • Only two types of SDO relationship. The metadata described below allows the Relational DAS to model just two types of SDO relationship: multi-valued containment relationships and single-valued non-containment references. In SDO, whether a property describes a single- or multi-valued relationship, and whether it is containment or non-containment, are independent. The full range of possibilities that SDO allows cannot all be defined. There may be relationships that it would be useful to model but which the current implementation cannot manage. One example is a single-valued containment relationship.

  • No support for the full range of SDO data types. The Relational DAS defines all primitive properties in the SDO model as being of type string. SDO defines a richer set of types containing various integer, float, boolean and data and time types. String is adequate for the purposes of the Relational DAS since the combination of PHP, PDO and the database will ensure that values passed as strings will be converted to the proper type before being put in the database. This does affect some scenarios in which the Relational DAS has to work with a data graph that has come from or will go to a different DAS.

  • Only one foreign key per table. The metadata only provides the means to specify one foreign key per table. This foreign key may be mapped to one of the two types of SDO relationship supported. Obviously there are some scenarios that cannot be described under this limitation - it is not possible to have two non-containment references from one table to another for example.

Three-table example
SDO-DAS-Relational Funkcje
SDO-DAS-Relational


SDO-DAS-Relational Funkcje

Klasy predefiniowane

The Relational DAS provides two classes: the Relational DAS itself and the subclass of Exception that can be thrown. The Relational DAS has four publicly useful calls: the constructor, the createRootDataObject() call to obtain the root object of an empty data graph, the executeQuery() call to obtain a data graph containing data from a relational database, and the applyChanges() call to write changes made to a data graph back to the relational database.

SDO_DAS_Relational

The only object other than an SDO_DAS_Relational_Exception with which the application is expected to interact.

Metody

  • __construct - construct the Relational DAS with a model derived from the passed metadata

  • createRootDataObject - obtain an otherwise empty data graph containing just the special root object

  • executeQuery - execute an SQL query passed as a literal string and return the results as a normalised data graph

  • executePreparedQuery - execute an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph

  • applyChanges - examine the change summary in the data graph and apply those changes back to the database, subject to an assumption of optimistic concurrency

SDO_DAS_Relational_Exception

Is a subclass of PHP's Exception. It adds no behaviour to Exception. Thrown, with useful descriptive text, to signal errors in the metadata or unexpected failures to perform SQL operations.

Spis treści

  • SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database.
  • SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service
  • SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.
  • SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.
  • SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph.
Limitations
SDO_DAS_Relational::applyChanges
SDO-DAS-Relational


Applies the changes made to a data graph back to the database.

SDO-DAS-Relational Funkcje
SDO_DAS_Relational::__construct
SDO-DAS-Relational Funkcje
PHP Manual

SDO_DAS_Relational::applyChanges

(^)

SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database.

Opis

void SDO_DAS_Relational::applyChanges ( PDO $database_handle , SDODataObject $root_data_object )
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.

Given a PDO database handle and the special root object of a data graph, examine the change summary in the datagraph and applies the changes to the database. The changes that it can apply can be creations of data objects, deletes of data objects, and modifications to properties of data objects.

Parametry

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

root_data_object

The special root object which is at the top of every SDO data graph.

Zwracane wartości

None. Note however that the datagraph that was passed is still intact and usable. Furthermore, if data objects were created and written back to a table with autogenerated primary keys, then those primary keys will now be set in the data objects. If the changes were successfully written, then the change summary associated with the datagraph will have been cleared, so that it is possible to now make further changes to the data graph and apply those changes in turn. In this way it is possible to work with the same data graph and apply changes repeatedly.

Błędy/Wyjątki

SDO_DAS_Relational::applyChanges() can throw an SDO_DAS_Relational_Exception if it is unable to apply all the changes correctly.

The Relational DAS starts a database transaction before beginning to apply the changes and will commit the transaction only if they are all successful. The Relational DAS generates qualified update and delete statements which contain a where clause that specifies that the row to be updated or deleted must contain the same values that it did when the data was first retrieved. This is how the optimistic concurrency is implemented. If any of the qualified update or delete statements fails to update or delete their target row, it may be because the data has been altered in the database in the meantime. In any event, if any update fails for any reason, the transaction is rolled back and an exception thrown. The exception will contain the generated SQL statement that failed.

The Relational DAS also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Przykłady

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method. Please see also the section on Tracing to see how you can see what SQL statements are generated by the Relational DAS.

SDO-DAS-Relational Funkcje
SDO_DAS_Relational::__construct
SDO-DAS-Relational Funkcje


Creates an instance of a Relational Data Access Service

SDO_DAS_Relational::applyChanges
SDO_DAS_Relational::createRootDataObject
SDO-DAS-Relational Funkcje
PHP Manual

SDO_DAS_Relational::__construct

(^)

SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service

Opis

SDO_DAS_Relational::__construct ( array $database_metadata [, string $application_root_type [, array $SDO_containment_references_metadata ]] )
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.

Constructs an instance of a Relational Data Access Service from the passed metadata.

Parametry

database_metadata

An array containing one or more table definitions, each of which is an associative array containing the keys name, columns, PK, and optionally, FK. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

application_root_type

The root of each data graph is an object of a special root type and the application data objects come below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, so the application root type can be inferred, this argument can be omitted.

SDO_containment_references_metadata

An array containing one or more definitions of a containment relation, each of which is an associative array containing the keys parent and child. The containment relations describe how the types in the model are connected to form a tree. The type specified as the application root type must be present as one of the parent types in the containment references. If the application only needs to work with one table at a time, and there are no containment relations in the model, this argument can be omitted. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

Zwracane wartości

Returns an SDO_DAS_Relational object on success.

Błędy/Wyjątki

SDO_DAS_Relational::__construct() throws a SDO_DAS_Relational_Exception if any problems are found in the metadata.

Przykłady

For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

SDO_DAS_Relational::applyChanges
SDO_DAS_Relational::createRootDataObject
SDO-DAS-Relational Funkcje


Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.

SDO_DAS_Relational::__construct
SDO_DAS_Relational::executePreparedQuery
SDO-DAS-Relational Funkcje
PHP Manual

SDO_DAS_Relational::createRootDataObject

(^)

SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.

Opis

SDODataObject SDO_DAS_Relational::createRootDataObject ( 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 special root object at the top of an otherwise empty data graph. This call is used when the application wants to create a data graph from scratch, without having called executeQuery() to create a data graph.

The special root object has one multi-valued containment property, with a name of the application root type that was passed when the Relational DAS was constructed. The property can take values of only that type. The only thing that the application can usefully do with the root type is to call createDataObject() on it, passing the name of the application root type, in order to create a data object of their own application type.

Parametry

None.

Zwracane wartości

The root object.

Błędy/Wyjątki

None.

Przykłady

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.

SDO_DAS_Relational::__construct
SDO_DAS_Relational::executePreparedQuery
SDO-DAS-Relational Funkcje


Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.

SDO_DAS_Relational::createRootDataObject
SDO_DAS_Relational::executeQuery
SDO-DAS-Relational Funkcje
PHP Manual

SDO_DAS_Relational::executePreparedQuery

(^)

SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.

Opis

SDODataObject SDO_DAS_Relational::executePreparedQuery ( PDO $database_handle , PDOStatement $prepared_statement , array $value_list [, array $column_specifier ] )
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.

Executes a given query against the relational database, using the supplied PDO database handle. Differs from the simpler executeQuery() in that it takes a prepared statement and a list of values. This is the appropriate call to use either when the statement is to executed a number of times with different arguments, and there is therefore a performance benefit to be had from preparing the statement only once, or when the SQL statement is to contain varying values taken from a source that cannot be completely trusted. In this latter case it may be unsafe to construct the SQL statement by simply concatenating the parts of the statement together, since the values may contain pieces of SQL. To guard against this, a so-called SQL injection attack, it is safer to prepare the SQL statement with placeholders (also known as parameter markers, denoted by '?') and supply a list of the values to be substituted as a separate argument. Otherwise this function is the same as executeQuery() in that it uses the model that it built from the metadata to interpret the result set and returns a data graph.

Parametry

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

prepared_statement

A prepared SQL statement to be executed against the database. This will have been prepared by PDO's prepare() method.

value_list

An array of the values to be substituted into the SQL statement in place of the placeholders. In the event that there are no placeholders or parameter markers in the SQL statement then this argument can be specified as NULL or as an empty array;

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata, For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Zwracane wartości

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Błędy/Wyjątki

SDO_DAS_Relational::executePreparedQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Przykłady

Przykład #1 Retrieving a data object using executePreparedQuery()

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

Other examples of the use of executePreparedQuery() can be found in the example code supplied in sdo/DAS/Relational/Scenarios.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 * Use a prepared query with a placeholder.
 ***************************************************************/
$name = 'Acme';
$pdo_stmt = $dbh->prepare('select name, id from company where name=?');
$root = $das->executePreparedQuery(
    $dbh,
    $pdo_stmt,
    array($name),
    array('company.name', 'company.id'));

/**************************************************************
 * Echo name and id
 ***************************************************************/
foreach ($root['company'] as $company) {
    echo "Company obtained from the database has name = " .
    $company['name'] . " and id " . $company['id'] . "\n";
}
?>

SDO_DAS_Relational::createRootDataObject
SDO_DAS_Relational::executeQuery
SDO-DAS-Relational Funkcje


Executes a given SQL query against a relational database and returns the results as a normalised data graph.

SDO_DAS_Relational::executePreparedQuery
SDO DAS XML
SDO-DAS-Relational Funkcje
PHP Manual

SDO_DAS_Relational::executeQuery

(^)

SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph.

Opis

SDODataObject SDO_DAS_Relational::executeQuery ( PDO $database_handle , string $SQL_statement [, array $column_specifier ] )
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.

Executes a given query against the relational database, using the supplied PDO database handle. Uses the model that it built from the metadata to interpret the result set. Returns a data graph.

Parametry

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

SQL_statement

The SQL statement to be executed against the database.

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata. For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Zwracane wartości

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Błędy/Wyjątki

SDO_DAS_Relational::executeQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Przykłady

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.

SDO_DAS_Relational::executePreparedQuery
SDO DAS XML
SDO-DAS-Relational Funkcje


SDO XML Data Access Service

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
  • SDO DAS XML Funkcje
    • SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object
    • SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file
    • SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name
    • SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string.
    • SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document
    • SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string
    • SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file
    • SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string
    • SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject
    • SDO_DAS_XML_Document::getRootElementName — Returns root element's name
    • SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string
    • SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding
    • SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration
    • SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version
SDO_DAS_Relational::executeQuery
Wstęp
Przetwarzanie XML


Wstęp

In order to use the XML Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO.

The job of the XML DAS is to move data between the application and an XML data source, which can be either a file or a URL. SDOs are always created and maintained according to a model which defines type names and what property names each type may have. For data which is from XML, this SDO model is built from a schema file written in XML schema language (an xsd file). This schema file is usually passed to the create method when the XMLDAS is initialised. The » SDO 2.0 specification defines the mapping between XML types and SDO types. There are a number of small limitations in the PHP support - not everything which is in the specification can be done - and these limitations are summarised in a later section.

SDO DAS XML
Instalacja/Konfiguracja
SDO DAS XML


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SDO DAS XML


Wymagania

The SDO XML Data Access Service requires PHP 5.1.0 or higher. It is packaged with the SDO extension and requires SDO to have been installed. See the SDO installation instructions for the details of how to do this.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

The XML Data Access Service is packaged and installed as part of the SDO extension. Please Refer SDO installation instructions.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
SDO DAS XML


Przykłady

Several of the following examples are based on the letter example described in the SDO documentation. The examples assume the XML Schema for the letter is contained in a file letter.xsd and the letter instance is in the file letter.xml. These two files are reproduced here:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

Przykład #1 Loading, altering, and saving an XML document

The following example shows how an XML document can be loaded from a file, altered, and written back.

<?php
/**
 * Load, update, and save an XML document
 */
try {
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   $document = $xmldas->loadFile("letter.xml");
   $root_data_object = $document->getRootDataObject();
   $root_data_object->date = "September 03, 2004";
   $root_data_object->firstName = "Anantoju";
   $root_data_object->lastName = "Madhu";
   $xmldas->saveFile($document, "letter-out.xml");
   echo "New file has been written:\n";
   print file_get_contents("letter-out.xml");
} catch (SDO_Exception $e) {
   print($e->getMessage());
}
?>

An instance of the XML DAS is first obtained from the SDO_DAS_XML::create() method, which is a static method of the SDO_DAS_XML class. The location of the xsd is passed as a parameter. Once we have an instance of the XML DAS initialised with a given schema, we can use it to load the instance document using the loadFile() method. There is also a loadString() method if you want to load an XML instance document from a string. If the instance document loads successfully, you will be returned an object of type SDO_DAS_XML_Document, on which you can call the getRootDataObject() method to get the SDO data object which is the root of the SDO data graph. You can then use SDO operations to change the graph. In this example we alter the date, firstName, and lastName properties. Then we use the saveFile() method to write the changed document back to the file system. The saveFile method has an optional extra integer argument which if specified will cause the XML DAS to format the XML, using the integer as the amount to indent by at each change in level on the document.

This will write the following to letter-out.xml.

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <date>September 03, 2004</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Anantoju</firstName>
  <lastName>Madhu</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</FormLetter>

Przykład #2 Creating a new XML document

The previous example loaded the document from a file. This example shows how to create an SDO data graph in memory. In this example it is then saved to an XML string. Furthermore, because the letter contains both structured and unstructured content, it uses the Sequence API as well assignments to properties to construct the data graph.

<?php
/**
 * Create an XML document from scratch
 */
try {
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   try {
       $doc = $xmldas->createDocument();
       $rdo = $doc->getRootDataObject();
       $seq = $rdo->getSequence();
       $seq->insert("April 09, 2005", NULL, 'date');
       $seq->insert("Acme Inc. ", NULL, NULL);
       $seq->insert("United Kingdom. ");
       $seq->insert("Dear", NULL, NULL);
       $seq->insert("Tarun", NULL, "firstName");
       $seq->insert("Nayaraaa", NULL, "lastName");
       $rdo->lastName = "Nayar";
       $seq->insert("Please note that your order number ");
       $seq->insert(12345);
       $seq->insert(" has been dispatched today. Thanks for your business with us.");
       print($xmldas->saveString($doc));
   } catch (SDO_Exception $e) {
       print($e);
   }
} catch (SDO_Exception $e) {
   print("Problem creating an XML document: " . $e->getMessage());
}
?>

The createDocument() method on the XML DAS returns a document object with a single root data object corresponding to an empty document element. The element name of the document element is known from the schema file. If there is any ambiguity about what the document element is, as there can be when more than one schema has been loaded into the same XML DAS, the element name and the namespace URI can be passed to the createDocument() method.

This will emit the following output (line breaks have been inserted for readability):

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date>April 09, 2005</date>
Acme Inc. United Kingdom.
Dear
<firstName>Tarun</firstName>
<lastName>Nayar</lastName>
Please note that your order number 12345 has been
dispatched today. Thanks for your business with us.
</FormLetter>

Przykład #3 Setting XML document properties

This third example shows you how to set the XML version and encoding on the document object. These will be used when the XML is written out. If no XML declaration is wanted at all (perhaps you want to generate the XML as a string to embed in something) then you can use the setXMLDeclaration() method to suppress it.

<?php
/**
 * Illustrate the calls that control the XML declaration
 */
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   $document = $xmldas->loadFile("letter.xml");
   $document->setXMLVersion("1.1");
   $document->setEncoding("ISO-8859-1");
   print($xmldas->saveString($document));
?>

The XML version and encoding are set in the XML declaration at the top of the XML document.

<?xml version="1.1" encoding="utf-8"?>
.../...

Przykład #4 Using an open type

This fourth example illustrates the use of an SDO open type and the use of the createDataObject() method. For this example we use the following two schema:

<schema
  xmlns="http://www.w3.org/2001/XMLSchema">

  <element name="jungle">
    <complexType>
      <sequence>
        <any minOccurs="0" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>

</schema>

Note the presence of the any element in the definition. This first schema defines the jungle complex type as containing a sequence of any other type. The other types that the example will use are defined in a second schema file:

<schema xmlns= "http://www.w3.org/2001/XMLSchema">

   <complexType name="snakeType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "length" type="positiveInteger" />
     </sequence>
   </complexType>

   <complexType name="bearType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "weight" type="positiveInteger" />
     </sequence>
   </complexType>

   <complexType name="pantherType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "colour" type="string" />
     </sequence>
   </complexType>

</schema>

Here is the example PHP code that uses these two schema files:

<?php

/**
 * Illustrate open types and the use of the addTypes() method
 */

$xmldas = SDO_DAS_XML::create();
$xmldas->addTypes("jungle.xsd"); // this is an open type i.e. the xsd specifies it can contain "any" type
$xmldas->addTypes('animalTypes.xsd');

$baloo            = $xmldas->createDataObject('','bearType');
$baloo->name      = "Baloo";
$baloo->weight    = 800;

$bagheera         = $xmldas->createDataObject('','pantherType');
$bagheera->name   = "Bagheera";
$bagheera->colour = 'inky black';

$kaa              = $xmldas->createDataObject('','snakeType');
$kaa->name        = "Kaa";
$kaa->length      = 25;

$document         = $xmldas->createDocument();
$do               = $document->getRootDataObject();
$do->bear         = $baloo;
$do->panther      = $bagheera;
$do->snake        = $kaa;

print($xmldas->saveString($document,2));

?>

These two schema files are loaded into the XML DAS with first the create() and addTypes() methods. The createDataObject() method is used to create three separate data objects. In each case the namespaceURI and typename of the type are passed to the createDataObject() method: in this example the namespace URI is blank because no namespace is used in the schema. Once the three data objects - representing a bear, a panther and a snake - have been created, a document object is created with the createDocument() method. In this case there is no ambiguity about what the document element of the document should be - as the second schema file only defines complex types, the document element can only be the global jungle element defined in the first schema. This document will have a single root data object corresponding to an empty document element jungle. As this is an open type, properties can be added at will. When the first assignment is made to $do->bear, a property bear is added to the root data object: likewise for the next two assignments. When the document is written out by the saveString() method, the resulting document is:

<?xml version="1.0" encoding="UTF-8"?>
<jungle xsi:type="jungle" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <bear xsi:type="bearType">
    <name>Baloo</name>
    <weight>800</weight>
  </bear>
  <panther xsi:type="pantherType">
    <name>Bagheera</name>
    <colour>inky black</colour>
  </panther>
  <snake xsi:type="snakeType">
    <name>Kaa</name>
    <length>25</length>
  </snake>
</jungle>

Przykład #5 Finding out what you can from the document

This example is intended to illustrate how you can find the element name and namespace of the document element from the XML Document object, and the SDO type and namespace from the root data object of the XML data object, and how they relate to one another. This can be difficult to understand because there are four method calls: two can be made against the Document object, and two that can be made against any data object including the root data object. Because of the rules that define how the SDO model is derived from the XML model, when the data object concerned is the root object that represents the document object for the document, only three possible values can come back from these four method calls.

The two method calls that can be made against the document are getRootElementName() and getRootEelementURI(). These return the element name and namespace of the document element, respectively.

The two method calls that can be made against any data object are getTypeName() and getTypeNamespaceURI(). These return the SDO type name and type namespace of the data object, respectively.

Always, calling getRootElementURI() on the document object will return the same value as calling getNamespaceURI() on the root data object. Essentially, the information is all derived from the first few lines of the schema file, where there are three distinct pieces of information. For illustration, here again are the first few lines of the letter.xsd that we used above.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:letter="http://letterSchema"
            targetNamespace="http://letterSchema">

  <xsd:element name="letters" type="letter:FormLetter"/>

  <xsd:complexType name="FormLetter" mixed="true">
    .../...

The three important values are:

  • letters, the name of the document element

  • FormLetter, the name of the complex type of the document element. This is also the name of the SDO type of the root data object.

  • http://letterSchema, the namespace to which the document element belongs. This is also the namespaceURI of the SDO type of the root data object.

It is part of the XML-SDO mapping rules that when the SDO model is built from the schema file, the typename and namespaceURI of the SDO types for the root element are taken from those of the complex type of the document element, where it exists. Hence in this example the typename of the root data object is FormLetter. In the event that there is no separate complex type definition for the document element, when the type is defined inline and is anonymous, the SDO type name will be the same as the element name.

The following program loads the letter document and checks the return values from each of the four calls.

<?php
/**
 * Finding out what you can about the document and document element
 * This can be quite hard to understand because there are four calls
 * Two calls are made against the document
 * Two calls are made against the root data object and its model
 * Because of the SDO-XML mapping rules and how the SDO model is derived
 * from the XML model, only three possible values can come back from these four calls.
 * Always, $document->getRootElementURI() == (type of root data object)->namespaceURI
 * Essentially, it all comes form the first few lines of the xsd:
 * <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 *   xmlns:letter="http://letterSchema"
 *   targetNamespace="http://letterSchema">
 *   <xsd:element name="letters" type="letter:FormLetter"/>
 */

$xmldas = SDO_DAS_XML::create("letter.xsd");
$document = $xmldas->loadFile("letter.xml");
$root_do = $document->getRootDataObject();

/**
 * The "root element name" is the element name of the document element
 * in this case 'letters'
 * This matches the 'name' attribute of the document element in the xsd and matches
 * the element name from the xml
 */
echo "The document element name is " . $document->getRootElementName() . "\n";
assert($document->getRootElementName() == 'letters'); // a property of the document

/**
 * The "root element URI" is the namespace part of the element name of the document element
 * in this case 'http://letterSchema' since 'letters' is in that namespace
 * This is taken from the xsd and matches the namespace picked up from the xml
 */
echo "The document element is in the namespace " . $document->getRootElementURI() . "\n";
assert($document->getRootElementURI() == 'http://letterSchema'); // a property of the document

/**
 * The type name is taken from the SDO model
 * The XML-SDO mapping rules make this either:
 *   The name of the complexType if there is one (in this case there is)
 *   The document element name if there no complexType
 * This is taken from the xsd
 */
echo "The type name of the root data object is " . $root_do->getTypeName() . "\n";
assert($root_do->getTypeName() == 'FormLetter');

/**
 * The type's namespaceURI is taken from the SDO model
 * The XML-SDO mapping rules ensure that this will always be the same as
 * the namepace URI of the document element
 */
echo "The namespaceURI of the root data object is " . $root_do->getTypeNamespaceURI() . "\n";
assert($root_do->getTypeNamespaceURI() == 'http://letterSchema');

?>

The output from this program is as follows:

The document element name is letters
The document element is in the namespace http://letterSchema
The type name of the root data object is FormLetter
The namespaceURI of the root data object is http://letterSchema

Przykład #6 Printing the SDO model

The XML DAS provides a simple means to see what types and properties have been loaded. The php "print" or "echo" instruction will print out the types and properties.

<?php
/**
 * Illustrate printing out the model
 */

$xmldas = SDO_DAS_XML::create("letter.xsd");
print $xmldas;

?>

The output from this program is as follows:

object(SDO_XML_DAS)#1 {
18 types have been defined. The types and their properties are::
1. commonj.sdo:BigDecimal
2. commonj.sdo:BigInteger
3. commonj.sdo:Boolean
4. commonj.sdo:Byte
5. commonj.sdo:Bytes
6. commonj.sdo:ChangeSummary
7. commonj.sdo:Character
8. commonj.sdo:DataObject
9. commonj.sdo:Date
10. commonj.sdo:Double
11. commonj.sdo:Float
12. commonj.sdo:Integer
13. commonj.sdo:Long
14. commonj.sdo:Short
15. commonj.sdo:String
16. commonj.sdo:URI
17. http://letterSchema:FormLetter
    - date (commonj.sdo:String)
    - firstName (commonj.sdo:String)
    - lastName (commonj.sdo:String)
18. http://letterSchema:RootType
    - letters (http://letterSchema:FormLetter)
Stałe predefiniowane
SDO DAS XML Funkcje
SDO DAS XML


SDO DAS XML Funkcje

Klasy predefiniowane

The XML DAS provides two main classes. The first is SDO_DAS_XML which is the main class used to fetch the data from the XML source and used to write the data back. The second is the SDO_DAS_XML_Document class, which represents the data in the XML document.

There are also some exception classes which can be thrown if errors are found when looking for or parsing the xsd or xml files.

SDO_DAS_XML

This is the main class of the XML DAS, which is used fetch the data from the xml source and also used to write the data back. Other than the methods to load and save xml files,

Metody

  • create This is a static method available in the SDO_DAS_XML class. Used to construct an SDO_DAS_XML object.

  • addTypes Works in much the same way as create() but used to add the contents of a second or subsequent schema file to an XML DAS that has already been created.

  • createDataObject Can be used to construct an SDO data object of a given type.

  • createDocument Can be used to construct an XML Document object from scratch.

  • loadFile Loads the xml instance document from a file. This file can be at local file system or it can be on a remote host.

  • loadString same as the above method. Loads the xml instance which is available as string.

  • saveFile save SDO_DAS_XML_Document object as a xml file.

  • saveString save SDO_DAS_XML_Document object as a xml string.

SDO_DAS_XML_Document

This class can be used to get to the name and namespace of the document element, and to get to the root data object of the document. Lastly, it can also be used to set the XML version and encoding of a document on output.

Metody

  • getRootDataObject gets the root DataObject.

  • getRootElementName gets the root DataObject's name.

  • getRootElementURI gets the root DataObject's URI.

  • setEncoding sets the encoding string with the given value.

  • setXMLDeclaraion to set/unset the xml declaration.

  • setXMLVersion sets the xml version with the given value.

SDO_DAS_XML_ParserException

Is a subclass of SDO_Exception. Thrown for any parser errors while loading the xsd/xml file.

SDO_DAS_XML_FileException

Is a subclass of SDO_Exception. Thrown by any of the methods that load data from a file, when the file cannot be found.

Limitations compared with SDO 2.0 specification

The » SDO 2.0 specification defines the mapping between XML types and SDO types. With Java SDO, this mapping is implemented by the XMLHelper. With SDO for PHP, this mapping is implemented by the XML Data Access Service. The XML DAS implements the mapping described in the SDO 2.0 specification with some restrictions. A detailed list is of the limitations is:

XML Simple Types

  1. Simple Type with sdoJava:instanceClass - no PHP equivalent provided.

  2. Simple Type with sdoJava:extendedInstanceClass - no PHP equivalent provided.

  3. Simple Type with list of itemType.

  4. Simple Type with union.

XML Complex Types

  1. Complex Type with sdo:aliasName - no PHP support for SDO Type aliases.

XSD Attribute

  1. Attribute with sdo:aliasName - no PHP support for SDO property aliases.

  2. Attribute with default value - no PHP support for SDO property defaults.

  3. Attribute with fixed value - no PHP support for SDO read-only properties or default values.

  4. Attribute referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="...".

  5. Attribute with bi-directional property to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

XSD Elements

  1. Element with sdo:aliasName - no PHP support for SDO property aliases.

  2. Element with substitution group.

XSD Elements with Simple Type

  1. Element of SimpleType with default - no PHP support for SDO defaults

  2. Element of SimpleType with fixed value - no PHP support for SDO read-only properties or default values.

  3. Element of SimpleType with sdo:string - no support for sdo:string="true".

  4. Element referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="..."

  5. Element with bi-directional reference to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

Spis treści

  • SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object
  • SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file
  • SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name
  • SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string.
  • SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document
  • SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string
  • SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file
  • SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string
  • SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject
  • SDO_DAS_XML_Document::getRootElementName — Returns root element's name
  • SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string
  • SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding
  • SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration
  • SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version
Przykłady
SDO_DAS_XML::addTypes
SDO DAS XML


To load a second or subsequent schema file to a SDO_DAS_XML object

SDO DAS XML Funkcje
SDO_DAS_XML::create
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML::addTypes

(^)

SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object

Opis

void SDO_DAS_XML::addTypes ( string $xsd_file )

Load a second or subsequent schema file to an XML DAS that has already been created with the static method create(). Although the file may be any valid schema file, a likely reason for using this method is to add a schema file containing definitions of extra complex types, hence the name. See Example 4 of the parent document for an example.

Parametry

xsd_file

Path to XSD Schema file.

Zwracane wartości

None if successful, otherwise throws an exception as described below.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

SDO DAS XML Funkcje
SDO_DAS_XML::create
SDO DAS XML Funkcje


To create SDO_DAS_XML object for a given schema file

SDO_DAS_XML::addTypes
SDO_DAS_XML::createDataObject
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML::create

(^)

SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file

Opis

SDO_DAS_XML SDO_DAS_XML::create ([ mixed $xsd_file [, string $key ]] )

This is the only static method of SDO_DAS_XML class. Used to instantiate SDO_DAS_XML object.

Parametry

xsd_file

Path to XSD Schema file. This is optional. If omitted a DAS will be created that only has the SDO base types defined. Schema files can then be loaded with the addTypes() method. Can be string or array of values.

key

Zwracane wartości

Returns SDO_DAS_XML object on success otherwise throws an exception as described below.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

SDO_DAS_XML::addTypes
SDO_DAS_XML::createDataObject
SDO DAS XML Funkcje


Creates SDO_DataObject for a given namespace URI and type name

SDO_DAS_XML::create
SDO_DAS_XML::createDocument
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML::createDataObject

(^)

SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name

Opis

SDO_DataObject SDO_DAS_XML::createDataObject ( string $namespace_uri , string $type_name )

Creates SDO_DataObject for a given namespace URI and type name. The type should be defined in the underlying model otherwise SDO_TypeNotFoundException will be thrown.

Parametry

namespace_uri

Namespace URI of the type name.

type_name

Type Name.

Zwracane wartości

Returns SDO_DataObject on success.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML::create
SDO_DAS_XML::createDocument
SDO DAS XML Funkcje


Creates an XML Document object from scratch, without the need to load a document from a file or string.

SDO_DAS_XML::createDataObject
SDO_DAS_XML::loadFile
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML::createDocument

(^)

SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string.

Opis

SDO_DAS_XML_Document SDO_DAS_XML::createDocument ([ string $document_element_name ] )
SDO_DAS_XML_Document SDO_DAS_XML::createDocument ( string $document_element_namespace_URI , string $document_element_name [, SDO_DataObject $dataobject ] )

Creates an XML Document object. This will contain just one empty root element on which none of the properties will have been set. The purpose of this call is to allow an application to create an XML document from scratch without the need to load a document from a file or string. The document that is created will be as if a document had been loaded that contained just a single empty document element with no attributes set or elements within it.

createDocument() may need to be told what the document element is. This will not be necessary in simple cases. When there is no ambiguity then no parameter need be passed to the method. However it is possible to load more than one schema file into the same XML DAS and in this case there may be more than one possible document element defined: furthermore it is even possible that there are two possible document elements that differ only in the namespace. To cope with these cases it is possible to specify either the document element name, or both the document element name and namespace to the method.

Parametry

document_element_name

The name of the document element. Only needed if there is more than one possibility.

document_element_namespace_URI

The namespace part of the document element name. Only needed if there is more than one possible document element with the same name.

dataobject

Zwracane wartości

Returns an SDO_XML_DAS_Document object on success.

Błędy/Wyjątki

SDO_UnsupportedOperationException

Thrown if an element name or element name and namespace URI is passed, but not found in the underlying model.

SDO_DAS_XML::createDataObject
SDO_DAS_XML::loadFile
SDO DAS XML Funkcje


Returns SDO_DAS_XML_Document object for a given path to xml instance document

SDO_DAS_XML::createDocument
SDO_DAS_XML::loadString
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML::loadFile

(^)

SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document

Opis

SDO_XMLDocument SDO_DAS_XML::loadFile ( string $xml_file )

Constructs the tree of SDO_DataObjects from the given address to xml instance document. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Parametry

xml_file

Path to Instance document. This can be a path to a local file or it can be a URL.

Zwracane wartości

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

SDO_DAS_XML::createDocument
SDO_DAS_XML::loadString
SDO DAS XML Funkcje


Returns SDO_DAS_XML_Document for a given xml instance string

SDO_DAS_XML::loadFile
SDO_DAS_XML::saveFile
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML::loadString

(^)

SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string

Opis

SDO_DAS_XML_Document SDO_DAS_XML::loadString ( string $xml_string )

Constructs the tree of SDO_DataObjects from the given xml instance string. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Parametry

xml_string

xml string.

Zwracane wartości

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Błędy/Wyjątki

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if the a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML::loadFile
SDO_DAS_XML::saveFile
SDO DAS XML Funkcje


Saves the SDO_DAS_XML_Document object to a file

SDO_DAS_XML::loadString
SDO_DAS_XML::saveString
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML::saveFile

(^)

SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file

Opis

void SDO_DAS_XML::saveFile ( SDO_XMLDocument $xdoc , string $xml_file [, int $indent ] )

Saves the SDO_DAS_XML_Document object to a file.

Parametry

xdoc

SDO_DAS_XML_Document object.

xml_file

xml file.

indent

Optional argument to specify that the xml should be formatted. A non-negative integer is the amount to indent each level of the xml. So, the integer 2, for example, will indent the xml so that each contained element is two spaces further to the right than its containing element. The integer 0 will cause the xml to be completely left-aligned. The integer -1 means no formatting - the xml will come out on one long line.

Zwracane wartości

None.

Błędy/Wyjątki

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.

SDO_DAS_XML::loadString
SDO_DAS_XML::saveString
SDO DAS XML Funkcje


Saves the SDO_DAS_XML_Document object to a string

SDO_DAS_XML::saveFile
SDO_DAS_XML_Document::getRootDataObject
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML::saveString

(^)

SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string

Opis

string SDO_DAS_XML::saveString ( SDO_XMLDocument $xdoc [, int $indent ] )

Saves the SDO_DAS_XML_Document object to string.

Parametry

xdoc

SDO_DAS_XML_Document object.

indent

Optional argument to specify that the xml should be formatted. A non-negative integer is the amount to indent each level of the xml. So, the integer 2, for example, will indent the xml so that each contained element is two spaces further to the right than its containing element. The integer 0 will cause the xml to be completely left-aligned. The integer -1 means no formatting - the xml will come out on one long line.

Zwracane wartości

xml string.

SDO_DAS_XML::saveFile
SDO_DAS_XML_Document::getRootDataObject
SDO DAS XML Funkcje


Returns the root SDO_DataObject

SDO_DAS_XML::saveString
SDO_DAS_XML_Document::getRootElementName
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML_Document::getRootDataObject

(^)

SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject

Opis

SDO_DataObject SDO_DAS_XML_Document::getRootDataObject ( void )

Returns the root SDO_DataObject.

Parametry

Zwracane wartości

Returns the root SDO_DataObject.

SDO_DAS_XML::saveString
SDO_DAS_XML_Document::getRootElementName
SDO DAS XML Funkcje


Returns root element's name

SDO_DAS_XML_Document::getRootDataObject
SDO_DAS_XML_Document::getRootElementURI
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML_Document::getRootElementName

(^)

SDO_DAS_XML_Document::getRootElementName — Returns root element's name

Opis

string SDO_DAS_XML_Document::getRootElementName ( void )

Returns root element's name.

Parametry

Zwracane wartości

Returns root element's name.

SDO_DAS_XML_Document::getRootDataObject
SDO_DAS_XML_Document::getRootElementURI
SDO DAS XML Funkcje


Returns root element's URI string

SDO_DAS_XML_Document::getRootElementName
SDO_DAS_XML_Document::setEncoding
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML_Document::getRootElementURI

(^)

SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string

Opis

string SDO_DAS_XML_Document::getRootElementURI ( void )

Returns root element's URI string.

Parametry

Zwracane wartości

Returns root element's URI string.

SDO_DAS_XML_Document::getRootElementName
SDO_DAS_XML_Document::setEncoding
SDO DAS XML Funkcje


Sets the given string as encoding

SDO_DAS_XML_Document::getRootElementURI
SDO_DAS_XML_Document::setXMLDeclaration
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML_Document::setEncoding

(^)

SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding

Opis

void SDO_DAS_XML_Document::setEncoding ( string $encoding )

Sets the given string as encoding.

Parametry

encoding

Encoding string.

Zwracane wartości

None.

SDO_DAS_XML_Document::getRootElementURI
SDO_DAS_XML_Document::setXMLDeclaration
SDO DAS XML Funkcje


Sets the xml declaration

SDO_DAS_XML_Document::setEncoding
SDO_DAS_XML_Document::setXMLVersion
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML_Document::setXMLDeclaration

(^)

SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration

Opis

void SDO_DAS_XML_Document::setXMLDeclaration ( bool $xmlDeclatation )

Controls whether an XML declaration will be generated at the start of the XML document. Set to TRUE to generate the XML declaration, or FALSE to suppress it.

Parametry

xmlDeclatation

Boolean value to set the XML declaration.

Zwracane wartości

None.

SDO_DAS_XML_Document::setEncoding
SDO_DAS_XML_Document::setXMLVersion
SDO DAS XML Funkcje


Sets the given string as xml version

SDO_DAS_XML_Document::setXMLDeclaration
SimpleXML
SDO DAS XML Funkcje
PHP Manual

SDO_DAS_XML_Document::setXMLVersion

(^)

SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version

Opis

void SDO_DAS_XML_Document::setXMLVersion ( string $xmlVersion )

Sets the given string as xml version.

Parametry

xmlVersion

xml version string.

Zwracane wartości

None.

SDO_DAS_XML_Document::setXMLDeclaration
SimpleXML
SDO DAS XML Funkcje


SimpleXML

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Basic SimpleXML usage
    • Dealing with XML errors
  • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild — Adds a child element to the XML node
    • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes — Identifies an element's attributes
    • SimpleXMLElement::children — Finds children of given node
    • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
    • SimpleXMLElement::count — Counts the children of an element
    • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
    • SimpleXMLElement::getName — Gets the name of the XML element
    • SimpleXMLElement::getNamespaces — Returns namespaces used in document
    • SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::saveXML — Alias dla SimpleXMLElement::asXML
    • SimpleXMLElement::xpath — Runs XPath query on XML data
  • SimpleXMLIterator — The SimpleXMLIterator class
    • SimpleXMLIterator::current — Returns the current element
    • SimpleXMLIterator::getChildren — Returns the sub-elements of the current element
    • SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements.
    • SimpleXMLIterator::key — Return current key
    • SimpleXMLIterator::next — Move to next element
    • SimpleXMLIterator::rewind — Rewind to the first element
    • SimpleXMLIterator::valid — Check whether the current element is valid
  • SimpleXML Funkcje
    • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node.
    • simplexml_load_file — Interprets an XML file into an object
    • simplexml_load_string — Interprets a string of XML into an object
SDO_DAS_XML_Document::setXMLVersion
Wstęp
Przetwarzanie XML


Wstęp

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.

SimpleXML
Instalacja/Konfiguracja
SimpleXML


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
SimpleXML


Wymagania

To rozszerzenie wymaga rozszerzenia PHP libxml. To oznacza, że należy podać dyrektywę konfiguracyjną --enable-libxml podczas kompilacji, pomimo tego, że pośrednio jest to spełnione, ponieważ libxml jest domyślnie włączone.

The SimpleXML extension requires PHP 5.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To rozszerzenie jest domyślnie włączone. Może być ono wyłączone za pomocą następującej opcji w czasie kompilacji: --disable-simplexml

Note: Before PHP 5.1.2, --enable-simplexml is required to enable this extension.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
SimpleXML


Przykłady

Spis treści

  • Basic SimpleXML usage
  • Dealing with XML errors
Stałe predefiniowane
Basic SimpleXML usage
SimpleXML


Basic SimpleXML usage

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

Przykład #1 Include file example.php with XML string

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Przykład #2 Getting <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

Powyższy przykład wyświetli:

   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.

Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

Przykład #3 Getting <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

Powyższy przykład wyświetli:

PHP solves all my web problems

Przykład #4 Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* For each <character> node, we echo a separate <name>. */
foreach ($movies->movie->characters->character as $character) {
   echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

?>

Powyższy przykład wyświetli:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Informacja:

Properties ($xml->movie in previous example) are not arrays. They are iterable and accessible objects.

Przykład #5 Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Access the <rating> nodes of the first movie.
 * Output the rating scale, too. */
foreach ($movies->movie[0]->rating as $rating) {
    switch((string) $rating['type']) { // Get attributes as element indices
    case 'thumbs':
        echo $rating, ' thumbs up';
        break;
    case 'stars':
        echo $rating, ' stars';
        break;
    }
}
?>

Powyższy przykład wyświetli:

7 thumbs up5 stars

Przykład #6 Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
    print 'My favorite movie.';
}

echo htmlentities((string) $movies->movie->title);
?>

Powyższy przykład wyświetli:

My favorite movie.PHP: Behind the Parser

Przykład #7 Comparing Two Elements

Two SimpleXMLElements are considered different even if they point to the same element since PHP 5.2.0.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2); // false since PHP 5.2.0
?>

Powyższy przykład wyświetli:

bool(false)

Przykład #8 Using XPath

SimpleXML includes built-in XPath support. To find all <character> elements:

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
    echo $character->name, 'played by ', $character->actor, PHP_EOL;
}
?>

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

Powyższy przykład wyświetli:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Przykład #9 Setting values

Data in SimpleXML doesn't have to be constant. The object allows for manipulation of all of its elements.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

Powyższy przykład wyświetli:

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Miss Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>

Przykład #10 Adding elements and attributes

Since PHP 5.1.3, SimpleXML has had the ability to easily add children and attributes.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $xml->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();
?>

Powyższy przykład wyświetli:

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  <character><name>Mr. Parser</name><actor>John Doe</actor></character></characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 <rating type="mpaa">PG</rating></movie>
</movies>

Przykład #11 DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

Powyższy przykład wyświetli:

blah

Przykłady
Dealing with XML errors
Przykłady


Dealing with XML errors

Dealing with XML errors when loading documents is a very simple task. Using the libxml functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The libXMLError object, returned by libxml_get_errors(), contains several properties including the message, line and column (position) of the error.

Przykład #1 Loading broken XML string

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (!$sxe) {
    echo "Failed loading XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}
?>

Powyższy przykład wyświetli:

Failed loading XML
    Blank needed here
    parsing XML declaration: '?>' expected
    Opening and ending tag mismatch: xml line 1 and broken
    Premature end of data in tag broken line 1

Zobacz też:

  • libxml_use_internal_errors()
  • libxml_get_errors()
  • libXMLError

Basic SimpleXML usage
SimpleXMLElement
Przykłady


The SimpleXMLElement class

(No version information available, might only be in SVN)

Wstęp

Represents an element in an XML document.

Krótki opis klasy

SimpleXMLElement implements Traversable {
/* Metody */
final public __construct ( string $data [, int $options = 0 [, bool $data_is_url = false [, string $ns = "" [, bool $is_prefix = false ]]]] )
public void addAttribute ( string $name [, string $value [, string $namespace ]] )
public SimpleXMLElement addChild ( string $name [, string $value [, string $namespace ]] )
public mixed asXML ([ string $filename ] )
public SimpleXMLElement attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )
public SimpleXMLElement children ([ string $ns [, bool $is_prefix = false ]] )
public int count ( void )
public array getDocNamespaces ([ bool $recursive = false ] )
public string getName ( void )
public array getNamespaces ([ bool $recursive = false ] )
public bool registerXPathNamespace ( string $prefix , string $ns )
public array xpath ( string $path )
}

Spis treści

  • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
  • SimpleXMLElement::addChild — Adds a child element to the XML node
  • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
  • SimpleXMLElement::attributes — Identifies an element's attributes
  • SimpleXMLElement::children — Finds children of given node
  • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
  • SimpleXMLElement::count — Counts the children of an element
  • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
  • SimpleXMLElement::getName — Gets the name of the XML element
  • SimpleXMLElement::getNamespaces — Returns namespaces used in document
  • SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::saveXML — Alias dla SimpleXMLElement::asXML
  • SimpleXMLElement::xpath — Runs XPath query on XML data
Dealing with XML errors
SimpleXMLElement::addAttribute
SimpleXML


Adds an attribute to the SimpleXML element

SimpleXMLElement
SimpleXMLElement::addChild
SimpleXMLElement
PHP Manual

SimpleXMLElement::addAttribute

(PHP 5 >= 5.1.3)

SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element

Opis

public void SimpleXMLElement::addAttribute ( string $name [, string $value [, string $namespace ]] )

Adds an attribute to the SimpleXML element.

Parametry

name

The name of the attribute to add.

value

The value of the attribute.

namespace

If specified, the namespace to which the attribute belongs.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Informacja:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Przykład #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

Powyższy przykład wyświetli coś podobnego do:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

Zobacz też:

  • SimpleXMLElement::addChild() - Adds a child element to the XML node
  • Basic SimpleXML usage

SimpleXMLElement
SimpleXMLElement::addChild
SimpleXMLElement


Adds a child element to the XML node

SimpleXMLElement::addAttribute
SimpleXMLElement::asXML
SimpleXMLElement
PHP Manual

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3)

SimpleXMLElement::addChild — Adds a child element to the XML node

Opis

public SimpleXMLElement SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] )

Adds a child element to the node and returns a SimpleXMLElement of the child.

Parametry

name

The name of the child element to add.

value

If specified, the value of the child element.

namespace

If specified, the namespace to which the child element belongs.

Zwracane wartości

The addChild method returns a SimpleXMLElement object representing the child added to the XML node.

Przykłady

Informacja:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Przykład #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

Powyższy przykład wyświetli coś podobnego do:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

Zobacz też:

  • SimpleXMLElement::addAttribute() - Adds an attribute to the SimpleXML element
  • Basic SimpleXML usage

SimpleXMLElement::addAttribute
SimpleXMLElement::asXML
SimpleXMLElement


Return a well-formed XML string based on SimpleXML element

SimpleXMLElement::addChild
SimpleXMLElement::attributes
SimpleXMLElement
PHP Manual

SimpleXMLElement::asXML

(PHP 5 >= 5.0.1)

SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element

Opis

public mixed SimpleXMLElement::asXML ([ string $filename ] )

The asXML method formats the parent object's data in XML version 1.0.

Parametry

filename

If specified, the function writes the data to the file rather than returning it.

Zwracane wartości

If the filename isn't specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.

Przykłady

Przykład #1 Get XML

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML();

?>

Powyższy przykład wyświetli:

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

asXML also works on Xpath results:

Przykład #2 Using asXML() on SimpleXMLElement::xpath() results

<?php
// Continued from example XML above.

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo $node->asXML();
}
?>

Powyższy przykład wyświetli:

<c>text</c><c>stuff</c>

Zobacz też:

  • Basic SimpleXML usage

SimpleXMLElement::addChild
SimpleXMLElement::attributes
SimpleXMLElement


Identifies an element's attributes

SimpleXMLElement::asXML
SimpleXMLElement::children
SimpleXMLElement
PHP Manual

SimpleXMLElement::attributes

(PHP 5 >= 5.0.1)

SimpleXMLElement::attributes — Identifies an element's attributes

Opis

public SimpleXMLElement SimpleXMLElement::attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )

This function provides the attributes and values defined within an xml tag.

Informacja: W SimpleXML wprowadzono zasadę dodawania pól iteracyjnych dla większości metod. Nie mogą być one przeglądane przez var_dump() ani przez nic innego co bada obiekty.

Parametry

ns

An optional namespace for the retrieved attributes

is_prefix

Default to FALSE

Zwracane wartości

Returns a SimpleXMLElement object that can be iterated over to loop through the attributes on the tag.

Returns NULL if called on a SimpleXMLElement object that already represents an attribute and not a tag.

Przykłady

Przykład #1 Interpret an XML string

<?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>

Powyższy przykład wyświetli:

name="one"
game="lonely"

Zobacz też:

  • Basic SimpleXML usage

SimpleXMLElement::asXML
SimpleXMLElement::children
SimpleXMLElement


Finds children of given node

SimpleXMLElement::attributes
SimpleXMLElement::__construct
SimpleXMLElement
PHP Manual

SimpleXMLElement::children

(PHP 5 >= 5.0.1)

SimpleXMLElement::children — Finds children of given node

Opis

public SimpleXMLElement SimpleXMLElement::children ([ string $ns [, bool $is_prefix = false ]] )

This method finds the children of an element. The result follows normal iteration rules.

Informacja: W SimpleXML wprowadzono zasadę dodawania pól iteracyjnych dla większości metod. Nie mogą być one przeglądane przez var_dump() ani przez nic innego co bada obiekty.

Parametry

ns

An XML namespace.

is_prefix

If is_prefix is TRUE, ns will be regarded as a prefix. If FALSE, ns will be regarded as a namespace URL.

Zwracane wartości

Returns a SimpleXMLElement element, whether the node has children or not.

Rejestr zmian

Wersja | Opis
5.2.0 | The optional parameter is_prefix was added.

Przykłady

Przykład #1 Traversing a children() pseudo-array

<?php
$xml = new SimpleXMLElement(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>');

foreach ($xml->children() as $second_gen) {
    echo ' The person begot a ' . $second_gen['role'];

    foreach ($second_gen->children() as $third_gen) {
        echo ' who begot a ' . $third_gen['role'] . ';';

        foreach ($third_gen->children() as $fourth_gen) {
            echo ' and that ' . $third_gen['role'] .
                ' begot a ' . $fourth_gen['role'];
        }
    }
}
?>

Powyższy przykład wyświetli:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Przykład #2 Using namespaces

<?php
$xml = '<example xmlns:foo="my.foo.urn">
  <foo:a>Apple</foo:a>
  <foo:b>Banana</foo:b>
  <c>Cherry</c>
</example>';

$sxe = new SimpleXMLElement($xml);

$kids = $sxe->children('foo');
var_dump(count($kids));

$kids = $sxe->children('foo', TRUE);
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn');
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn', TRUE);
var_dump(count($kids));

$kids = $sxe->children();
var_dump(count($kids));
?>
int(0)
int(2)
int(2)
int(0)
int(1)

Notatki

SimpleXMLElement::children() returns a node object no matter if the current node has children or not. Use count() on the return value to see if there are any children. As of PHP 5.3.0, SimpleXMLElement::count() may be used instead.

Zobacz też:

  • SimpleXMLElement::count() - Counts the children of an element
  • count() - Zlicza ilość elementów w tablicy lub pól obiektu

SimpleXMLElement::attributes
SimpleXMLElement::__construct
SimpleXMLElement


Creates a new SimpleXMLElement object

SimpleXMLElement::children
SimpleXMLElement::count
SimpleXMLElement
PHP Manual

SimpleXMLElement::__construct

(PHP 5 >= 5.0.1)

SimpleXMLElement::__construct — Creates a new SimpleXMLElement object

Opis

final public SimpleXMLElement::__construct() ( string $data [, int $options = 0 [, bool $data_is_url = false [, string $ns = "" [, bool $is_prefix = false ]]]] )

Creates a new SimpleXMLElement object.

Parametry

data

A well-formed XML string or the path or URL to an XML document if data_is_url is TRUE.

options

Optionally used to specify additional Libxml parameters.

data_is_url

By default, data_is_url is FALSE. Use TRUE to specify that data is a path or URL to an XML document instead of string data.

ns

Namespace prefix or URI.

is_prefix

TRUE if ns is a prefix, FALSE if it's a URI; defaults to FALSE.

Zwracane wartości

Returns a SimpleXMLElement object representing data.

Błędy/Wyjątki

Produces an E_WARNING error message for each error found in the XML data and additionally throws an Exception if the XML data could not be parsed.

Wskazówka

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Przykłady

Informacja:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Przykład #1 Create a SimpleXMLElement object

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

Powyższy przykład wyświetli:

PHP: Behind the Parser

Przykład #2 Create a SimpleXMLElement object from a URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

Zobacz też:

  • Basic SimpleXML usage
  • simplexml_load_string() - Interprets a string of XML into an object
  • simplexml_load_file() - Interprets an XML file into an object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed

SimpleXMLElement::children
SimpleXMLElement::count
SimpleXMLElement


Counts the children of an element

SimpleXMLElement::__construct
SimpleXMLElement::getDocNamespaces
SimpleXMLElement
PHP Manual

SimpleXMLElement::count

(PHP 5 >= 5.3.0)

SimpleXMLElement::count — Counts the children of an element

Opis

public int SimpleXMLElement::count ( void )

This method counts the number of children of an element.

Zwracane wartości

Returns the number of elements of an element.

Przykłady

Przykład #1 Counting the number of children

<?php
$xml = <<<EOF
<people>
 <person name="Person 1">
  <child/>
  <child/>
  <child/>
 </person>
 <person name="Person 2">
  <child/>
  <child/>
  <child/>
  <child/>
  <child/>
 </person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach ($elem as $person) {
    printf("%s has got %d children.\n", $person['name'], $person->count());
}
?>

Powyższy przykład wyświetli:

Person 1 has got 3 children.
Person 2 has got 5 children.

Zobacz też:

  • SimpleXMLElement::children() - Finds children of given node

SimpleXMLElement::__construct
SimpleXMLElement::getDocNamespaces
SimpleXMLElement


Returns namespaces declared in document

SimpleXMLElement::count
SimpleXMLElement::getName
SimpleXMLElement
PHP Manual

SimpleXMLElement::getDocNamespaces

(PHP 5 >= 5.1.2)

SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document

Opis

public array SimpleXMLElement::getDocNamespaces ([ bool $recursive = false ] )

Returns namespaces declared in document

Parametry

recursive

If specified, returns all namespaces declared in parent and child nodes. Otherwise, returns only namespaces declared in root node.

Zwracane wartości

The getDocNamespaces method returns an array of namespace names with their associated URIs.

Przykłady

Przykład #1 Get document namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces();
var_dump($namespaces);

?>

Powyższy przykład wyświetli:

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Przykład #2 Working with multiple namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person t:id="1">John Doe</p:person>
    <p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
        Susie Q. Public
    </p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(TRUE);
var_dump($namespaces);

?>

Powyższy przykład wyświetli:

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

Zobacz też:

  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query

SimpleXMLElement::count
SimpleXMLElement::getName
SimpleXMLElement


Gets the name of the XML element

SimpleXMLElement::getDocNamespaces
SimpleXMLElement::getNamespaces
SimpleXMLElement
PHP Manual

SimpleXMLElement::getName

(PHP 5 >= 5.1.3)

SimpleXMLElement::getName — Gets the name of the XML element

Opis

public string SimpleXMLElement::getName ( void )

Gets the name of the XML element.

Zwracane wartości

The getName method returns as a string the name of the XML tag referenced by the SimpleXMLElement object.

Przykłady

Informacja:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Przykład #1 Get XML element names

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
    echo $child->getName() . "\n";
}

?>

Powyższy przykład wyświetli:

movies
movie

SimpleXMLElement::getDocNamespaces
SimpleXMLElement::getNamespaces
SimpleXMLElement


Returns namespaces used in document

SimpleXMLElement::getName
SimpleXMLElement::registerXPathNamespace
SimpleXMLElement
PHP Manual

SimpleXMLElement::getNamespaces

(PHP 5 >= 5.1.2)

SimpleXMLElement::getNamespaces — Returns namespaces used in document

Opis

public array SimpleXMLElement::getNamespaces ([ bool $recursive = false ] )

Returns namespaces used in document

Parametry

recursive

If specified, returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

Zwracane wartości

The getNamespaces method returns an array of namespace names with their associated URIs.

Przykłady

Przykład #1 Get document namespaces in use

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

Powyższy przykład wyświetli:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

Zobacz też:

  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query

SimpleXMLElement::getName
SimpleXMLElement::registerXPathNamespace
SimpleXMLElement


Creates a prefix/ns context for the next XPath query

SimpleXMLElement::getNamespaces
SimpleXMLElement::saveXML
SimpleXMLElement
PHP Manual

SimpleXMLElement::registerXPathNamespace

(PHP 5 >= 5.2.0)

SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query

Opis

public bool SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns )

Creates a prefix/ns context for the next XPath query. In particular, this is helpful if the provider of the given XML document alters the namespace prefixes. registerXPathNamespace will create a prefix for the associated namespace, allowing one to access nodes in that namespace without the need to change code to allow for the new prefixes dictated by the provider.

Parametry

prefix

The namespace prefix to use in the XPath query for the namespace given in ns.

ns

The namespace to use for the XPath query. This must match a namespace in use by the XML document or the XPath query using prefix will not return any results.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Setting a namespace prefix to use in an XPath query

<?php

$xml = <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
    <title>My Book</title>
    <chapter id="1">
        <chap:title>Chapter 1</chap:title>
        <para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
            In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
            Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
            ultricies id, mauris.</para>
    </chapter>
    <chapter id="2">
        <chap:title>Chapter 2</chap:title>
        <para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
            gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
            vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
            tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
    </chapter>
</book>
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');

foreach ($result as $title) {
  echo $title . "\n";
}

?>

Powyższy przykład wyświetli:

Chapter 1
Chapter 2

Notice how the XML document shown in the example sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of c in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using registerXPathNamespace avoids future modification of the query even if the provider changes the namespace prefix.

Zobacz też:

  • SimpleXMLElement::xpath() - Runs XPath query on XML data
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document

SimpleXMLElement::getNamespaces
SimpleXMLElement::saveXML
SimpleXMLElement


Alias dla SimpleXMLElement::asXML

SimpleXMLElement::registerXPathNamespace
SimpleXMLElement::xpath
SimpleXMLElement
PHP Manual

SimpleXMLElement::saveXML

(PHP 5 >= 5.2.0)

SimpleXMLElement::saveXML — Alias dla SimpleXMLElement::asXML()

Opis

Ta metoda jest aliasem dla: SimpleXMLElement::asXML()

SimpleXMLElement::registerXPathNamespace
SimpleXMLElement::xpath
SimpleXMLElement


Runs XPath query on XML data

SimpleXMLElement::saveXML
SimpleXMLIterator
SimpleXMLElement
PHP Manual

SimpleXMLElement::xpath

(PHP 5 >= 5.2.0)

SimpleXMLElement::xpath — Runs XPath query on XML data

Opis

public array SimpleXMLElement::xpath ( string $path )

The xpath method searches the SimpleXML node for children matching the XPath path.

Parametry

path

An XPath path

Zwracane wartości

Returns an array of SimpleXMLElement objects or FALSE in case of an error.

Przykłady

Przykład #1 Xpath

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml->xpath('b/c');

while(list( , $node) = each($result)) {
    echo 'b/c: ',$node,"\n";
}
?>

Powyższy przykład wyświetli:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

Zobacz też:

  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • Basic SimpleXML usage

SimpleXMLElement::saveXML
SimpleXMLIterator
SimpleXMLElement


The SimpleXMLIterator class

(PHP 5 >= 5.1.0)

Wstęp

The SimpleXMLIterator provides recursive iteration over all nodes of a SimpleXMLElement object.

Krótki opis klasy

SimpleXMLIterator extends SimpleXMLElement implements RecursiveIterator , Traversable , Iterator , Countable {
/* Metody */
public mixed current ( void )
SimpleXMLIterator getChildren ( void )
bool hasChildren ( void )
mixed key ( void )
void next ( void )
void rewind ( void )
bool valid ( void )
/* Metody dziedziczone */
final public SimpleXMLElement::__construct ( string $data [, int $options = 0 [, bool $data_is_url = false [, string $ns = "" [, bool $is_prefix = false ]]]] )
public void SimpleXMLElement::addAttribute ( string $name [, string $value [, string $namespace ]] )
public SimpleXMLElement SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] )
public mixed SimpleXMLElement::asXML ([ string $filename ] )
public SimpleXMLElement SimpleXMLElement::attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )
public SimpleXMLElement SimpleXMLElement::children ([ string $ns [, bool $is_prefix = false ]] )
public int SimpleXMLElement::count ( void )
public array SimpleXMLElement::getDocNamespaces ([ bool $recursive = false ] )
public string SimpleXMLElement::getName ( void )
public array SimpleXMLElement::getNamespaces ([ bool $recursive = false ] )
public bool SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns )
public array SimpleXMLElement::xpath ( string $path )
}

Spis treści

  • SimpleXMLIterator::current — Returns the current element
  • SimpleXMLIterator::getChildren — Returns the sub-elements of the current element
  • SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements.
  • SimpleXMLIterator::key — Return current key
  • SimpleXMLIterator::next — Move to next element
  • SimpleXMLIterator::rewind — Rewind to the first element
  • SimpleXMLIterator::valid — Check whether the current element is valid
SimpleXMLElement::xpath
SimpleXMLIterator::current
SimpleXML


Returns the current element

SimpleXMLIterator
SimpleXMLIterator::getChildren
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::current

(PHP 5 >= 5.1.0)

SimpleXMLIterator::current — Returns the current element

Opis

public mixed SimpleXMLIterator::current ( void )

This method returns the current element as a SimpleXMLIterator object or NULL.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current element as a SimpleXMLIterator object or NULL on failure.

Przykłady

Przykład #1 Return the current element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP basics</book><book>XML basics</book></books>');
var_dump($xmlIterator->current());

$xmlIterator->rewind(); // rewind to first element
var_dump($xmlIterator->current());
?>

Powyższy przykład wyświetli:

NULL
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

Zobacz też:

  • SimpleXMLIterator::key() - Return current key
  • SimpleXMLIterator::next() - Move to next element
  • SimpleXMLIterator::rewind() - Rewind to the first element
  • SimpleXMLIterator::valid() - Check whether the current element is valid
  • SimpleXMLElement

SimpleXMLIterator
SimpleXMLIterator::getChildren
SimpleXMLIterator


Returns the sub-elements of the current element

SimpleXMLIterator::current
SimpleXMLIterator::hasChildren
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::getChildren

(PHP 5 >= 5.1.0)

SimpleXMLIterator::getChildren — Returns the sub-elements of the current element

Opis

SimpleXMLIterator SimpleXMLIterator::getChildren ( void )

This method returns a SimpleXMLIterator object containing sub-elements of the current SimpleXMLIterator element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns a SimpleXMLIterator object containing the sub-elements of the current element.

Przykłady

Przykład #1 Return the sub-elements of the current element

<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Basics</title>
        <author>Jim Smith</author>
    </book>
    <book>XML basics</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator($xml);
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    foreach($xmlIterator->getChildren() as $name => $data) {
    echo "The $name is '$data' from the class " . get_class($data) . "\n";
    }
}
?>

Powyższy przykład wyświetli:

The title is 'PHP Basics' from the class SimpleXMLIterator
The author is 'Jim Smith' from the class SimpleXMLIterator

SimpleXMLIterator::current
SimpleXMLIterator::hasChildren
SimpleXMLIterator


Checks whether the current element has sub elements.

SimpleXMLIterator::getChildren
SimpleXMLIterator::key
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::hasChildren

(PHP 5 >= 5.1.0)

SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements.

Opis

bool SimpleXMLIterator::hasChildren ( void )

This method checks whether the current SimpleXMLIterator element has sub-elements.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

TRUE if the current element has sub-elements, otherwise FALSE

Przykłady

Przykład #1 Check whether the current element has sub-elements

<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Basics</title>
        <author>Jim Smith</author>
    </book>
    <book>XML basics</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator( $xml );
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    if($xmlIterator->hasChildren()) {
        var_dump($xmlIterator->current());
    }
}
?>

Powyższy przykład wyświetli:

object(SimpleXMLIterator)#2 (2) {
  ["title"]=>
  string(10) "PHP Basics"
  ["author"]=>
  string(9) "Jim Smith"
}

SimpleXMLIterator::getChildren
SimpleXMLIterator::key
SimpleXMLIterator


Return current key

SimpleXMLIterator::hasChildren
SimpleXMLIterator::next
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::key

(PHP 5 >= 5.1.0)

SimpleXMLIterator::key — Return current key

Opis

mixed SimpleXMLIterator::key ( void )

This method gets the XML tag name of the current element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the XML tag name of the element referenced by the current SimpleXMLIterator object or FALSE

Przykłady

Przykład #1 Get the current XML tag key

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP basics</book><book>XML basics</book></books>');

echo var_dump($xmlIterator->key());
$xmlIterator->rewind(); // rewind to the first element
echo var_dump($xmlIterator->key());

?>

Powyższy przykład wyświetli:

bool(false)
string(4) "book"

SimpleXMLIterator::hasChildren
SimpleXMLIterator::next
SimpleXMLIterator


Move to next element

SimpleXMLIterator::key
SimpleXMLIterator::rewind
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::next

(PHP 5 >= 5.1.0)

SimpleXMLIterator::next — Move to next element

Opis

void SimpleXMLIterator::next ( void )

This method moves the SimpleXMLIterator to the next element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Move to the next element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP Basics</book><book>XML basics</book></books>');
$xmlIterator->rewind(); // rewind to the first element
$xmlIterator->next();

var_dump($xmlIterator->current());
?>

Powyższy przykład wyświetli:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "XML basics"
}

SimpleXMLIterator::key
SimpleXMLIterator::rewind
SimpleXMLIterator


Rewind to the first element

SimpleXMLIterator::next
SimpleXMLIterator::valid
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::rewind

(PHP 5 >= 5.1.0)

SimpleXMLIterator::rewind — Rewind to the first element

Opis

void SimpleXMLIterator::rewind ( void )

This method rewinds the SimpleXMLIterator to the first element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Rewind to the first element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP Basics</book><book>XML Basics</book></books>');
$xmlIterator->rewind();

var_dump($xmlIterator->current());
?>

Powyższy przykład wyświetli:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

SimpleXMLIterator::next
SimpleXMLIterator::valid
SimpleXMLIterator


Check whether the current element is valid

SimpleXMLIterator::rewind
SimpleXML Funkcje
SimpleXMLIterator
PHP Manual

SimpleXMLIterator::valid

(PHP 5 >= 5.1.0)

SimpleXMLIterator::valid — Check whether the current element is valid

Opis

bool SimpleXMLIterator::valid ( void )

This method checks if the current element is valid after calls to SimpleXMLIterator::rewind() or SimpleXMLIterator::next().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the current element is valid, otherwise FALSE

Przykłady

Przykład #1 Check whether the current element is valid

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>SQL Basics</book></books>');

$xmlIterator->rewind(); // rewind to the first element
echo var_dump($xmlIterator->valid()); // bool(true)

$xmlIterator->next(); // advance to the next element
echo var_dump($xmlIterator->valid()); // bool(false) because there is only one element
?>

SimpleXMLIterator::rewind
SimpleXML Funkcje
SimpleXMLIterator


SimpleXML Funkcje

Spis treści

  • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node.
  • simplexml_load_file — Interprets an XML file into an object
  • simplexml_load_string — Interprets a string of XML into an object
SimpleXMLIterator::valid
simplexml_import_dom
SimpleXML


Get a SimpleXMLElement object from a DOM node.

SimpleXML Funkcje
simplexml_load_file
SimpleXML Funkcje
PHP Manual

simplexml_import_dom

(PHP 5)

simplexml_import_dom — Get a SimpleXMLElement object from a DOM node.

Opis

SimpleXMLElement simplexml_import_dom ( DOMNode $node [, string $class_name = "SimpleXMLElement" ] )

This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.

Parametry

node

A DOM Element node

class_name

You may use this optional parameter so that simplexml_import_dom() will return an object of the specified class. That class should extend the SimpleXMLElement class.

Zwracane wartości

Returns a SimpleXMLElement lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Importing DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

Powyższy przykład wyświetli:

blah

Zobacz też:

  • dom_import_simplexml() - Gets a DOMElement object from a SimpleXMLElement object
  • Basic SimpleXML usage

SimpleXML Funkcje
simplexml_load_file
SimpleXML Funkcje


Interprets an XML file into an object

simplexml_import_dom
simplexml_load_string
SimpleXML Funkcje
PHP Manual

simplexml_load_file

(PHP 5)

simplexml_load_file — Interprets an XML file into an object

Opis

SimpleXMLElement simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )

Convert the well-formed XML document in the given file to an object.

Parametry

filename

Path to the XML file

Informacja:

Libxml 2 unescapes the URI, so if you want to pass e.g. b&c as the URI parameter a, you have to call simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Since PHP 5.1.0 you don't need to do this because PHP will do it for you.

class_name

You may use this optional parameter so that simplexml_load_file() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

Namespace prefix or URI.

is_prefix

TRUE if ns is a prefix, FALSE if it's a URI; defaults to FALSE.

Zwracane wartości

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document, lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Produces an E_WARNING error message for each error found in the XML data.

Wskazówka

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Przykłady

Przykład #1 Interpret an XML document

<?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.

if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');

    print_r($xml);
} else {
    exit('Failed to open test.xml.');
}
?>

This script will display, on success:

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

At this point, you can go about using $xml->title and any other elements.

Zobacz też:

  • simplexml_load_string() - Interprets a string of XML into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage

simplexml_import_dom
simplexml_load_string
SimpleXML Funkcje


Interprets a string of XML into an object

simplexml_load_file
WDDX
SimpleXML Funkcje
PHP Manual

simplexml_load_string

(PHP 5)

simplexml_load_string — Interprets a string of XML into an object

Opis

SimpleXMLElement simplexml_load_string ( string $data [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )

Takes a well-formed XML string and returns it as an object.

Parametry

data

A well-formed XML string

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

Namespace prefix or URI.

is_prefix

TRUE if ns is a prefix, FALSE if it's a URI; defaults to FALSE.

Zwracane wartości

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Produces an E_WARNING error message for each error found in the XML data.

Wskazówka

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Przykłady

Przykład #1 Interpret an XML string

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

Powyższy przykład wyświetli:

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

At this point, you can go about using $xml->body and such.

Zobacz też:

  • simplexml_load_file() - Interprets an XML file into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage

simplexml_load_file
WDDX
SimpleXML Funkcje


WDDX

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • wddx examples
  • WDDX Funkcje
    • wddx_add_vars — Add variables to a WDDX packet with the specified ID
    • wddx_deserialize — Unserializes a WDDX packet
    • wddx_packet_end — Ends a WDDX packet with the specified ID
    • wddx_packet_start — Starts a new WDDX packet with structure inside it
    • wddx_serialize_value — Serialize a single value into a WDDX packet
    • wddx_serialize_vars — Serialize variables into a WDDX packet
simplexml_load_string
Wstęp
Przetwarzanie XML


Wstęp

These functions are intended for work with » WDDX.

WDDX
Instalacja/Konfiguracja
WDDX


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
WDDX


Wymagania

To rozszerzenie wymaga rozszerzenia PHP libxml. To oznacza, że należy podać dyrektywę konfiguracyjną --enable-libxml podczas kompilacji, pomimo tego, że pośrednio jest to spełnione, ponieważ libxml jest domyślnie włączone.

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

After installing the required expat library, compile PHP with --enable-wddx , and use --with-libexpat-dir for expat.

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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines a WDDX packet identifier returned by wddx_packet_start().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
Przykłady
WDDX


Przykłady

Spis treści

  • wddx examples
Stałe predefiniowane
wddx examples
WDDX


wddx examples

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

Przykład #1 Serializing a single value with WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Przykład #2 Using incremental packets with WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Informacja:

If you want to serialize non-ASCII characters you have to convert your data to UTF-8 first (see utf8_encode() and iconv()).

Przykłady
WDDX Funkcje
Przykłady


WDDX Funkcje

Spis treści

  • wddx_add_vars — Add variables to a WDDX packet with the specified ID
  • wddx_deserialize — Unserializes a WDDX packet
  • wddx_packet_end — Ends a WDDX packet with the specified ID
  • wddx_packet_start — Starts a new WDDX packet with structure inside it
  • wddx_serialize_value — Serialize a single value into a WDDX packet
  • wddx_serialize_vars — Serialize variables into a WDDX packet
wddx examples
wddx_add_vars
WDDX


Add variables to a WDDX packet with the specified ID

WDDX Funkcje
wddx_deserialize
WDDX Funkcje
PHP Manual

wddx_add_vars

(PHP 4, PHP 5)

wddx_add_vars — Add variables to a WDDX packet with the specified ID

Opis

bool wddx_add_vars ( resource $packet_id , mixed $var_name [, mixed $... ] )

Serializes the passed variables and add the result to the given packet.

Parametry

This function takes a variable number of parameters.

packet_id

A WDDX packet, returned by wddx_packet_start().

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

...

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

WDDX Funkcje
wddx_deserialize
WDDX Funkcje


Unserializes a WDDX packet

wddx_add_vars
wddx_packet_end
WDDX Funkcje
PHP Manual

wddx_deserialize

(PHP 4, PHP 5)

wddx_deserialize — Unserializes a WDDX packet

Opis

mixed wddx_deserialize ( string $packet )

Unserializes a WDDX packet.

Parametry

packet

A WDDX packet, as a string or stream.

Zwracane wartości

Returns the deserialized value which can be a string, a number or an array. Note that structures are deserialized into associative arrays.

wddx_add_vars
wddx_packet_end
WDDX Funkcje


Ends a WDDX packet with the specified ID

wddx_deserialize
wddx_packet_start
WDDX Funkcje
PHP Manual

wddx_packet_end

(PHP 4, PHP 5)

wddx_packet_end — Ends a WDDX packet with the specified ID

Opis

string wddx_packet_end ( resource $packet_id )

Ends and returns the given WDDX packet.

Parametry

packet_id

A WDDX packet, returned by wddx_packet_start().

Zwracane wartości

Returns the string containing the WDDX packet.

wddx_deserialize
wddx_packet_start
WDDX Funkcje


Starts a new WDDX packet with structure inside it

wddx_packet_end
wddx_serialize_value
WDDX Funkcje
PHP Manual

wddx_packet_start

(PHP 4, PHP 5)

wddx_packet_start — Starts a new WDDX packet with structure inside it

Opis

resource wddx_packet_start ([ string $comment ] )

Start a new WDDX packet for incremental addition of variables. It automatically creates a structure definition inside the packet to contain the variables.

Parametry

comment

An optional comment string.

Zwracane wartości

Returns a packet ID for use in later functions, or FALSE on error.

wddx_packet_end
wddx_serialize_value
WDDX Funkcje


Serialize a single value into a WDDX packet

wddx_packet_start
wddx_serialize_vars
WDDX Funkcje
PHP Manual

wddx_serialize_value

(PHP 4, PHP 5)

wddx_serialize_value — Serialize a single value into a WDDX packet

Opis

string wddx_serialize_value ( mixed $var [, string $comment ] )

Creates a WDDX packet from a single given value.

Parametry

var

The value to be serialized

comment

An optional comment string that appears in the packet header.

Zwracane wartości

Returns the WDDX packet, or FALSE on error.

wddx_packet_start
wddx_serialize_vars
WDDX Funkcje


Serialize variables into a WDDX packet

wddx_serialize_value
XML Parser
WDDX Funkcje
PHP Manual

wddx_serialize_vars

(PHP 4, PHP 5)

wddx_serialize_vars — Serialize variables into a WDDX packet

Opis

string wddx_serialize_vars ( mixed $var_name [, mixed $... ] )

Creates a WDDX packet with a structure that contains the serialized representation of the passed variables.

Parametry

This function takes a variable number of parameters.

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

...

Zwracane wartości

Returns the WDDX packet, or FALSE on error.

Przykłady

Przykład #1 wddx_serialize_vars() example

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

Powyższy przykład wyświetli:

<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>

wddx_serialize_value
XML Parser
WDDX Funkcje


XML Parser

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Event Handlers
  • Case Folding
  • Error Codes
  • Character Encoding
  • Przykłady
    • XML Element Structure Example
    • XML Tag Mapping Example
    • XML External Entity Example
  • XML Parser Funkcje
    • utf8_decode — Konwertuje ciąg znaków w ISO-8859-1 zakodowany w UTF-8 do jednobajtowego ISO-8859-1
    • utf8_encode — Koduje ciąg znaków w ISO-8859-1 do UTF-8
    • xml_error_string — Pobiera łańcuch znaków zawierający błąd parsera XML
    • xml_get_current_byte_index — Pobiera aktualny indeks bajtu parsera XML
    • xml_get_current_column_number — Pobiera aktualny numer kolumny dla parsera XML
    • xml_get_current_line_number — Pobiera aktualny numer linii dla parsera XML
    • xml_get_error_code — Pobiera kod błędu parsera XML
    • xml_parse_into_struct — Parse XML data into an array structure
    • xml_parse — Rozpoczyna parsowanie dokumentu XML
    • xml_parser_create_ns — Create an XML parser with namespace support
    • xml_parser_create — Tworzy parser XML
    • xml_parser_free — Zwalnia parser XML
    • xml_parser_get_option — Get options from an XML parser
    • xml_parser_set_option — Set options in an XML parser
    • xml_set_character_data_handler — Set up character data handler
    • xml_set_default_handler — Set up default handler
    • xml_set_element_handler — Ustawia początkową i końcową procedurę obsługi elementu
    • xml_set_end_namespace_decl_handler — Set up end namespace declaration handler
    • xml_set_external_entity_ref_handler — Set up external entity reference handler
    • xml_set_notation_decl_handler — Set up notation declaration handler
    • xml_set_object — Use XML Parser within an object
    • xml_set_processing_instruction_handler — Set up processing instruction (PI) handler
    • xml_set_start_namespace_decl_handler — Set up start namespace declaration handler
    • xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler
wddx_serialize_vars
Wstęp
Przetwarzanie XML


Wstęp

XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C). Information about XML and related technologies can be found at » http://www.w3.org/XML/.

This PHP extension implements support for James Clark's expat in PHP. This toolkit lets you parse, but not validate, XML documents. It supports three source character encodings also provided by PHP: US-ASCII, ISO-8859-1 and UTF-8. UTF-16 is not supported.

This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.

XML Parser
Instalacja/Konfiguracja
XML Parser


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
XML Parser


Wymagania

To rozszerzenie wymaga rozszerzenia PHP libxml. To oznacza, że należy podać dyrektywę konfiguracyjną --enable-libxml podczas kompilacji, pomimo tego, że pośrednio jest to spełnione, ponieważ libxml jest domyślnie włączone.

This extension uses an expat compat layer by default. It can use also expat, which can be found at » http://www.jclark.com/xml/expat.html. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
A source RPM package of expat can be found at » http://sourceforge.net/projects/expat/.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

To rozszerzenie jest domyślnie włączone. Może być ono wyłączone za pomocą następującej opcji w czasie kompilacji: --disable-xml

Te funkcje są domyślnie włączone i używają dołączonej biblioteki expat. Możemy wyłączyć obsługę XML podczas kompilacji dodając opcję --disable-xml . Jeśli kompilujemy PHP jako moduł do Apache w wersji 1.3.9 lub późniejszej, wówczas PHP automatycznie użyje biblioteki expat dołączonej do Apache. W przypadku gdy nie chcemy używać dołączonej wersji biblioteki expat, to powinniśmy skonfigurować PHP z opcją --with-expat-dir=KATALOG gdzie KATALOG powinien wskazywać na katalog, w którym zainstalowano expat.

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.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

The xml resource as returned by xml_parser_create() and xml_parser_create_ns() references an xml parser instance to be used with the functions provided by this extension.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

XML_ERROR_NONE (integer)
XML_ERROR_NO_MEMORY (integer)
XML_ERROR_SYNTAX (integer)
XML_ERROR_NO_ELEMENTS (integer)
XML_ERROR_INVALID_TOKEN (integer)
XML_ERROR_UNCLOSED_TOKEN (integer)
XML_ERROR_PARTIAL_CHAR (integer)
XML_ERROR_TAG_MISMATCH (integer)
XML_ERROR_DUPLICATE_ATTRIBUTE (integer)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)
XML_ERROR_PARAM_ENTITY_REF (integer)
XML_ERROR_UNDEFINED_ENTITY (integer)
XML_ERROR_RECURSIVE_ENTITY_REF (integer)
XML_ERROR_ASYNC_ENTITY (integer)
XML_ERROR_BAD_CHAR_REF (integer)
XML_ERROR_BINARY_ENTITY_REF (integer)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)
XML_ERROR_MISPLACED_XML_PI (integer)
XML_ERROR_UNKNOWN_ENCODING (integer)
XML_ERROR_INCORRECT_ENCODING (integer)
XML_ERROR_UNCLOSED_CDATA_SECTION (integer)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)
XML_OPTION_CASE_FOLDING (integer)
XML_OPTION_TARGET_ENCODING (integer)
XML_OPTION_SKIP_TAGSTART (integer)
XML_OPTION_SKIP_WHITE (integer)
XML_SAX_IMPL (string)
Holds the SAX implementation method. Can be libxml or expat.
Typy zasobów
Event Handlers
XML Parser


Event Handlers

The XML event handlers defined are:

Supported XML handlers
PHP function to set handler | Event description
xml_set_element_handler() | Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags.
xml_set_character_data_handler() | Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant.
xml_set_processing_instruction_handler() | PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where php is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved.
xml_set_default_handler() | What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler.
xml_set_unparsed_entity_decl_handler() | This handler will be called for declaration of an unparsed (NDATA) entity.
xml_set_notation_decl_handler() | This handler is called for declaration of a notation.
xml_set_external_entity_ref_handler() | This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration.
xml_set_start_namespace_decl_handler() | This handler is called for the start of a namespace declaration.
xml_set_end_namespace_decl_handler() | This handler is called for the end of a namespace declaration. Note that this event is NOT under LibXML.

Stałe predefiniowane
Case Folding
XML Parser


Case Folding

The element handler functions may get their element names case-folded. Case-folding is defined as "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents". In other words, when it comes to XML, case-folding simply means uppercasing.

By default, all the element names that are passed to the handler functions are case-folded. This behaviour can be queried and controlled per XML parser with the xml_parser_get_option() and xml_parser_set_option() functions, respectively.

Event Handlers
Error Codes
XML Parser


Error Codes

The following constants are defined for XML error codes (as returned by xml_parse()):

  • XML_ERROR_NONE
  • XML_ERROR_NO_MEMORY
  • XML_ERROR_SYNTAX
  • XML_ERROR_NO_ELEMENTS
  • XML_ERROR_INVALID_TOKEN
  • XML_ERROR_UNCLOSED_TOKEN
  • XML_ERROR_PARTIAL_CHAR
  • XML_ERROR_TAG_MISMATCH
  • XML_ERROR_DUPLICATE_ATTRIBUTE
  • XML_ERROR_JUNK_AFTER_DOC_ELEMENT
  • XML_ERROR_PARAM_ENTITY_REF
  • XML_ERROR_UNDEFINED_ENTITY
  • XML_ERROR_RECURSIVE_ENTITY_REF
  • XML_ERROR_ASYNC_ENTITY
  • XML_ERROR_BAD_CHAR_REF
  • XML_ERROR_BINARY_ENTITY_REF
  • XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
  • XML_ERROR_MISPLACED_XML_PI
  • XML_ERROR_UNKNOWN_ENCODING
  • XML_ERROR_INCORRECT_ENCODING
  • XML_ERROR_UNCLOSED_CDATA_SECTION
  • XML_ERROR_EXTERNAL_ENTITY_HANDLING

Case Folding
Character Encoding
XML Parser


Character Encoding

PHP's XML extension supports the » Unicode character set through different character encodings. There are two types of character encodings, source encoding and target encoding. PHP's internal representation of the document is always encoded with UTF-8.

Source encoding is done when an XML document is parsed. Upon creating an XML parser, a source encoding can be specified (this encoding can not be changed later in the XML parser's lifetime). The supported source encodings are ISO-8859-1, US-ASCII and UTF-8. The former two are single-byte encodings, which means that each character is represented by a single byte. UTF-8 can encode characters composed by a variable number of bits (up to 21) in one to four bytes. The default source encoding used by PHP is ISO-8859-1.

Target encoding is done when PHP passes data to XML handler functions. When an XML parser is created, the target encoding is set to the same as the source encoding, but this may be changed at any point. The target encoding will affect character data as well as tag names and processing instruction targets.

If the XML parser encounters characters outside the range that its source encoding is capable of representing, it will return an error.

If PHP encounters characters in the parsed XML document that can not be represented in the chosen target encoding, the problem characters will be "demoted". Currently, this means that such characters are replaced by a question mark.

Error Codes
Przykłady
XML Parser


Przykłady

Spis treści

  • XML Element Structure Example
  • XML Tag Mapping Example
  • XML External Entity Example
Character Encoding
XML Element Structure Example
XML Parser


XML Element Structure Example

This first example displays the structure of the start elements in a document with indentation.

Przykład #1 Show XML Element Structure

<?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs)
{
    global $depth;
    for ($i = 0; $i < $depth[$parser]; $i++) {
        echo "  ";
    }
    echo "$name\n";
    $depth[$parser]++;
}

function endElement($parser, $name)
{
    global $depth;
    $depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>

Przykłady
XML Tag Mapping Example
Przykłady


XML Tag Mapping Example

Przykład #1 Map XML to HTML

This example maps tags in an XML document directly to HTML tags. Elements not found in the "map array" are ignored. Of course, this example will only work with a specific XML document type.

<?php
$file = "data.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "<$map_array[$name]>";
    }
}

function endElement($parser, $name)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "</$map_array[$name]>";
    }
}

function characterData($parser, $data)
{
    echo $data;
}

$xml_parser = xml_parser_create();
// use case-folding so we are sure to find the tag in $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>

XML Element Structure Example
XML External Entity Example
Przykłady


XML External Entity Example

This example highlights XML code. It illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.

XML documents that can be used for this example are found below the example (xmltest.xml and xmltest2.xml.)

Przykład #1 External Entity Example

<?php
$file = "xmltest.xml";

function trustedFile($file)
{
    // only trust local files owned by ourselves
    if (!preg_match("@^([a-z]+)\:\/\/@i", $file)
        && fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs)
{
    echo "&lt;<font color=\"#0000cc\">$name</font>";
    if (count($attribs)) {
        foreach ($attribs as $k => $v) {
            echo " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    echo "&gt;";
}

function endElement($parser, $name)
{
    echo "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data)
{
    echo "<b>$data</b>";
}

function PIHandler($parser, $target, $data)
{
    switch (strtolower($target)) {
        case "php":
            global $parser_file;
            // If the parsed document is "trusted", we say it is safe
            // to execute PHP code inside it.  If not, display the code
            // instead.
            if (trustedFile($parser_file[$parser])) {
                eval($data);
            } else {
                printf("Untrusted PHP code: <i>%s</i>",
                        htmlspecialchars($data));
            }
            break;
    }
}

function defaultHandler($parser, $data)
{
    if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
        printf('<font color="#aa00aa">%s</font>',
                htmlspecialchars($data));
    } else {
        printf('<font size="-1">%s</font>',
                htmlspecialchars($data));
    }
}

function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,
                                  $publicId) {
    if ($systemId) {
        if (!list($parser, $fp) = new_xml_parser($systemId)) {
            printf("Could not open entity %s at %s\n", $openEntityNames,
                   $systemId);
            return false;
        }
        while ($data = fread($fp, 4096)) {
            if (!xml_parse($parser, $data, feof($fp))) {
                printf("XML error: %s at line %d while parsing entity %s\n",
                       xml_error_string(xml_get_error_code($parser)),
                       xml_get_current_line_number($parser), $openEntityNames);
                xml_parser_free($parser);
                return false;
            }
        }
        xml_parser_free($parser);
        return true;
    }
    return false;
}

function new_xml_parser($file)
{
    global $parser_file;

    $xml_parser = xml_parser_create();
    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
    xml_set_element_handler($xml_parser, "startElement", "endElement");
    xml_set_character_data_handler($xml_parser, "characterData");
    xml_set_processing_instruction_handler($xml_parser, "PIHandler");
    xml_set_default_handler($xml_parser, "defaultHandler");
    xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");

    if (!($fp = @fopen($file, "r"))) {
        return false;
    }
    if (!is_array($parser_file)) {
        settype($parser_file, "array");
    }
    $parser_file[$xml_parser] = $file;
    return array($xml_parser, $fp);
}

if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
    die("could not open XML input");
}

echo "<pre>";
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d\n",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
echo "</pre>";
echo "parse complete\n";
xml_parser_free($xml_parser);

?>

Przykład #2 xmltest.xml

<?xml version='1.0'?>
<!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
<!ENTITY plainEntity "FOO entity">
<!ENTITY systemEntity SYSTEM "xmltest2.xml">
]>
<chapter>
 <TITLE>Title &plainEntity;</TITLE>
 <para>
  <informaltable>
   <tgroup cols="3">
    <tbody>
     <row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
     <row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
 &systemEntity;
 <section id="about">
  <title>About this Document</title>
  <para>
   <!-- this is a comment -->
   <?php echo 'Hi!  This is PHP version ' . phpversion(); ?>
  </para>
 </section>
</chapter>

This file is included from xmltest.xml:

Przykład #3 xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "This is some more PHP code being executed."; ?>
</foo>

XML Tag Mapping Example
XML Parser Funkcje
Przykłady


XML Parser Funkcje

Spis treści

  • utf8_decode — Konwertuje ciąg znaków w ISO-8859-1 zakodowany w UTF-8 do jednobajtowego ISO-8859-1
  • utf8_encode — Koduje ciąg znaków w ISO-8859-1 do UTF-8
  • xml_error_string — Pobiera łańcuch znaków zawierający błąd parsera XML
  • xml_get_current_byte_index — Pobiera aktualny indeks bajtu parsera XML
  • xml_get_current_column_number — Pobiera aktualny numer kolumny dla parsera XML
  • xml_get_current_line_number — Pobiera aktualny numer linii dla parsera XML
  • xml_get_error_code — Pobiera kod błędu parsera XML
  • xml_parse_into_struct — Parse XML data into an array structure
  • xml_parse — Rozpoczyna parsowanie dokumentu XML
  • xml_parser_create_ns — Create an XML parser with namespace support
  • xml_parser_create — Tworzy parser XML
  • xml_parser_free — Zwalnia parser XML
  • xml_parser_get_option — Get options from an XML parser
  • xml_parser_set_option — Set options in an XML parser
  • xml_set_character_data_handler — Set up character data handler
  • xml_set_default_handler — Set up default handler
  • xml_set_element_handler — Ustawia początkową i końcową procedurę obsługi elementu
  • xml_set_end_namespace_decl_handler — Set up end namespace declaration handler
  • xml_set_external_entity_ref_handler — Set up external entity reference handler
  • xml_set_notation_decl_handler — Set up notation declaration handler
  • xml_set_object — Use XML Parser within an object
  • xml_set_processing_instruction_handler — Set up processing instruction (PI) handler
  • xml_set_start_namespace_decl_handler — Set up start namespace declaration handler
  • xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler
XML External Entity Example
utf8_decode
XML Parser


Konwertuje ciąg znaków w ISO-8859-1 zakodowany w UTF-8 do jednobajtowego ISO-8859-1

XML Parser Funkcje
utf8_encode
XML Parser Funkcje
PHP Manual

utf8_decode

(PHP 4, PHP 5)

utf8_decode — Konwertuje ciąg znaków w ISO-8859-1 zakodowany w UTF-8 do jednobajtowego ISO-8859-1

Opis

string utf8_decode ( string $dane )

Ta funkcja dekoduje dane, przy założeniu że są zakodowane w UTF-8, do ISO-8859-1.

Parametry

dane

Łańcuch znaków zakodowany w UTF-8.

Zwracane wartości

Zwraca dane przekonwertowane do ISO-8859-1 .

Zobacz też:

  • utf8_encode() - Koduje ciąg znaków w ISO-8859-1 do UTF-8 (zawiera wyjaśnienia dotyczące kodowania UTF-8)

XML Parser Funkcje
utf8_encode
XML Parser Funkcje


Koduje ciąg znaków w ISO-8859-1 do UTF-8

utf8_decode
xml_error_string
XML Parser Funkcje
PHP Manual

utf8_encode

(PHP 4, PHP 5)

utf8_encode — Koduje ciąg znaków w ISO-8859-1 do UTF-8

Opis

string utf8_encode ( string $dane )

Ta funkcja koduje dane do UTF-8, po czym zwraca je zakodowane. UTF-8 jest standardowym mechanizmem używanym przez Unicode do kodowania wartości rozszerzonych znaków w ciąg bajtów. UTF-8 jest przeźroczyste dla znaków w czystym ASCII, samozsynchronizowane (w znaczeniu posiadania możliwości aby program mógł znaleźć gdzie w ciągu bajtów zaczynają się znaki) jak również może być używane w normalnym porównywaniu znaków na potrzeby sortowania itp. PHP koduje znaki UTF-8 do maksymalnie czterech bajtów, w podany poniżej sposób:

Kodowanie UTF-8
bajty | bity | reprezentacja
1 | 7 | 0bbbbbbb
2 | 11 | 110bbbbb 10bbbbbb
3 | 16 | 1110bbbb 10bbbbbb 10bbbbbb
4 | 21 | 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
Każde b reprezentuje bit, który może być używany do przechowywanie danych znakowych.

Parametry

dane

Łańcuch znaków zakodowany w ISO-8859-1.

Zwracane wartości

Zwraca dane przekorwentowane do UTF-8 .

utf8_decode
xml_error_string
XML Parser Funkcje


Pobiera łańcuch znaków zawierający błąd parsera XML

utf8_encode
xml_get_current_byte_index
XML Parser Funkcje
PHP Manual

xml_error_string

(PHP 4, PHP 5)

xml_error_string — Pobiera łańcuch znaków zawierający błąd parsera XML

Opis

string xml_error_string ( int $kod )

Pobiera łańcuch znaków zawierający błąd parsera XML skojarzony z podanym kodem.

Parametry

kod

Kod błędu z funkcji xml_get_error_code().

Zwracane wartości

Zwraca ciąg znaków z tekstowym opisem kodu błędu lub FALSE, jeśli opis nie został znaleziony.

Zobacz też:

  • xml_get_error_kod()

utf8_encode
xml_get_current_byte_index
XML Parser Funkcje


Pobiera aktualny indeks bajtu parsera XML

xml_error_string
xml_get_current_column_number
XML Parser Funkcje
PHP Manual

xml_get_current_byte_index

(PHP 4, PHP 5)

xml_get_current_byte_index — Pobiera aktualny indeks bajtu parsera XML

Opis

int xml_get_current_byte_index ( resource $parser )

Pobiera aktualny indeks bajtu podanego parsera XML.

Parametry

parser

Referencja do parsera XML, poprzez którą pobierany jest indeks bajtu.

Zwracane wartości

Ta funkcja zwraca FALSE jeżeli parser nie odnosi się do prawidłowego parsera. W przeciwnym razie zwraca indeks bajtu, na którym znajduje się aktualnie parser w swoim buforze danych (zaczynając od 0).

Notatki

Ostrzeżenie

Funkcja zwraca indeks bajtu zgodnie z tekstem zakodowanym w UTF-8 pomijając przypadek, gdy wejście jest w innym kodowaniu.

Zobacz też:

  • xml_get_current_column_number() - Pobiera aktualny numer kolumny dla parsera XML
  • xml_get_current_line_number() - Pobiera aktualny numer linii dla parsera XML

xml_error_string
xml_get_current_column_number
XML Parser Funkcje


Pobiera aktualny numer kolumny dla parsera XML

xml_get_current_byte_index
xml_get_current_line_number
XML Parser Funkcje
PHP Manual

xml_get_current_column_number

(PHP 4, PHP 5)

xml_get_current_column_number — Pobiera aktualny numer kolumny dla parsera XML

Opis

int xml_get_current_column_number ( resource $parser )

Pobiera aktualny numer kolumny dla podanego parsera XML.

Parametry

parser

Referencja do parsera XML poprzez którą pobierany jest numer kolumny.

Zwracane wartości

Ta funkcja zwraca FALSE jeżeli parser nie odnosi się do prawidłowego parsera. W innym przypadku zwraca numer kolumny w aktualnej linii (którą zwraca funkcja xml_get_current_line_number()), na której znajduje się aktualnie parser.

Zobacz też:

  • xml_get_current_byte_index() - Pobiera aktualny indeks bajtu parsera XML
  • xml_get_current_line_number() - Pobiera aktualny numer linii dla parsera XML

xml_get_current_byte_index
xml_get_current_line_number
XML Parser Funkcje


Pobiera aktualny numer linii dla parsera XML

xml_get_current_column_number
xml_get_error_code
XML Parser Funkcje
PHP Manual

xml_get_current_line_number

(PHP 4, PHP 5)

xml_get_current_line_number — Pobiera aktualny numer linii dla parsera XML

Opis

int xml_get_current_line_number ( resource $parser )

Pobiera aktualny numer linii dla podanego parsera XML.

Parametry

parser

Referencja do parsera XML, poprzez którą pobierany jest numer linii.

Zwracane wartości

Ta funkcja zwraca FALSE jeśli parser nie odnosi się do prawidłowego parsera. W przeciwnym razie zwraca numer linii, na której znajduje się aktualnie parser w buforze danych.

Zobacz też:

  • xml_get_current_column_number() - Pobiera aktualny numer kolumny dla parsera XML
  • xml_get_current_byte_index() - Pobiera aktualny indeks bajtu parsera XML

xml_get_current_column_number
xml_get_error_code
XML Parser Funkcje


Pobiera kod błędu parsera XML

xml_get_current_line_number
xml_parse_into_struct
XML Parser Funkcje
PHP Manual

xml_get_error_code

(PHP 4, PHP 5)

xml_get_error_code — Pobiera kod błędu parsera XML

Opis

int xml_get_error_code ( resource $parser )

Pobiera kod błędu parsera XML.

Parametry

parser

Referencja do parsera XML, poprzez którą pobierany jest kod błędu.

Zwracane wartości

Ta funkcja zwraca FALSE jeżeli parser nie odnosi się do prawidłowego parsera. W przeciwym razie zwraca jeden z kodów błędów opisanych w sekcji kody błędów.

Zobacz też:

  • xml_error_string() - Pobiera łańcuch znaków zawierający błąd parsera XML

xml_get_current_line_number
xml_parse_into_struct
XML Parser Funkcje


Parse XML data into an array structure

xml_get_error_code
xml_parse
XML Parser Funkcje
PHP Manual

xml_parse_into_struct

(PHP 4, PHP 5)

xml_parse_into_struct — Parse XML data into an array structure

Opis

int xml_parse_into_struct ( resource $parser , string $data , array &$values [, array &$index ] )

This function parses an XML string into 2 parallel array structures, one (index) containing pointers to the location of the appropriate values in the values array. These last two parameters must be passed by reference.

Parametry

parser

A reference to the XML parser.

data

A string containing the XML data.

values

An array containing the values of the XML data

index

An array containing pointers to the location of the appropriate values in the $values.

Zwracane wartości

xml_parse_into_struct() returns 0 for failure and 1 for success. This is not the same as FALSE and TRUE, be careful with operators such as ===.

Przykłady

Below is an example that illustrates the internal structure of the arrays being generated by the function. We use a simple note tag embedded inside a para tag, and then we parse this and print out the structures generated:

Przykład #1 xml_parse_into_struct() example

<?php
$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);
?>

When we run that code, the output will be:

Index array
Array
(
    [PARA] => Array
        (
            [0] => 0
            [1] => 2
        )

    [NOTE] => Array
        (
            [0] => 1
        )

)

Vals array
Array
(
    [0] => Array
        (
            [tag] => PARA
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => NOTE
            [type] => complete
            [level] => 2
            [value] => simple note
        )

    [2] => Array
        (
            [tag] => PARA
            [type] => close
            [level] => 1
        )

)

Event-driven parsing (based on the expat library) can get complicated when you have an XML document that is complex. This function does not produce a DOM style object, but it generates structures amenable of being transversed in a tree fashion. Thus, we can create objects representing the data in the XML file easily. Let's consider the following XML file representing a small database of aminoacids information:

Przykład #2 moldb.xml - small database of molecular information

<?xml version="1.0"?>
<moldb>

  <molecule>
      <name>Alanine</name>
      <symbol>ala</symbol>
      <code>A</code>
      <type>hydrophobic</type>
  </molecule>

  <molecule>
      <name>Lysine</name>
      <symbol>lys</symbol>
      <code>K</code>
      <type>charged</type>
  </molecule>

</moldb>
And some code to parse the document and generate the appropriate objects:

Przykład #3 parsemoldb.php - parses moldb.xml into an array of molecular objects

<?php

class AminoAcid {
    var $name;  // aa name
    var $symbol;    // three letter symbol
    var $code;  // one letter code
    var $type;  // hydrophobic, charged or neutral

    function AminoAcid ($aa)
    {
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}

function readDatabase($filename)
{
    // read the XML database of aminoacids
    $data = implode("", file($filename));
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);

    // loop through the structures
    foreach ($tags as $key=>$val) {
        if ($key == "molecule") {
            $molranges = $val;
            // each contiguous pair of array entries are the
            // lower and upper range for each molecule definition
            for ($i=0; $i < count($molranges); $i+=2) {
                $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}

function parseMol($mvalues)
{
    for ($i=0; $i < count($mvalues); $i++) {
        $mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    }
    return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** Database of AminoAcid objects:\n";
print_r($db);

?>
After executing parsemoldb.php, the variable $db contains an array of AminoAcid objects, and the output of the script confirms that:
** Database of AminoAcid objects:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

xml_get_error_code
xml_parse
XML Parser Funkcje


Rozpoczyna parsowanie dokumentu XML

xml_parse_into_struct
xml_parser_create_ns
XML Parser Funkcje
PHP Manual

xml_parse

(PHP 4, PHP 5)

xml_parse — Rozpoczyna parsowanie dokumentu XML

Opis

int xml_parse ( resource $parser , string $dane [, bool $ostatni = false ] )

xml_parse() parsuje dokument XML. Uchwyty dla skonfigurowanych zdarzeń są wywoływane odpowiednią ilość razy.

Parametry

parser

Referencja do parsera XML, który ma zostać użyty.

dane

Fragment danych do parsowania. Dokument może być prawidłowo parsowany po kawałku za pomocą wielokrotnego wywoływania xml_parse() z nowymi danymi, dopóki podany jest parametr ostatni i posiada on wartość logiczną TRUE podczas parsowania ostatniej porcji danych.

ostatni

Jeśli jest podany i posiada wartość logiczną TRUE, dane są ostatnim kawałkiem wysłanych danych podczas tego parsowania.

Zwracane wartości

Zwraca 1 w przypadku powodzenia lub 0 w przypadku błędu.

Dla parsowań zakończonych niepomyślnie można uzyskać informację o błędach
za pomocą xml_get_error_code(),
xml_error_string(),
xml_get_current_line_number(),
xml_get_current_column_number() i
xml_get_current_byte_index().

Informacja:

Błędy encji są raportowane po zakończeniu przetwarzania danych, a więc tylko wtedy gdy ustawiony jest parametr ostatni i posiada on wartość TRUE.

xml_parse_into_struct
xml_parser_create_ns
XML Parser Funkcje


Create an XML parser with namespace support

xml_parse
xml_parser_create
XML Parser Funkcje
PHP Manual

xml_parser_create_ns

(PHP 4 >= 4.0.5, PHP 5)

xml_parser_create_ns — Create an XML parser with namespace support

Opis

resource xml_parser_create_ns ([ string $encoding [, string $separator = ':' ]] )

xml_parser_create_ns() creates a new XML parser with XML namespace support and returns a resource handle referencing it to be used by the other XML functions.

Parametry

encoding

The optional encoding specifies the character encoding for the input/output in PHP 4. Starting from PHP 5, the input encoding is automatically detected, so that the encoding parameter specifies only the output encoding. In PHP 4, the default output encoding is the same as the input charset. In PHP 5.0.0 and 5.0.1, the default output charset is ISO-8859-1, while in PHP 5.0.2 and upper is UTF-8. The supported encodings are ISO-8859-1, UTF-8 and US-ASCII.

separator

With a namespace aware parser tag parameters passed to the various handler functions will consist of namespace and tag name separated by the string specified in seperator.

Zwracane wartości

Returns a resource handle for the new XML parser.

Zobacz też:

  • xml_parser_create() - Tworzy parser XML
  • xml_parser_free() - Zwalnia parser XML

xml_parse
xml_parser_create
XML Parser Funkcje


Tworzy parser XML

xml_parser_create_ns
xml_parser_free
XML Parser Funkcje
PHP Manual

xml_parser_create

(PHP 4, PHP 5)

xml_parser_create — Tworzy parser XML

Opis

resource xml_parser_create ([ string $kodowanie ] )

xml_parser_create() tworzy nowy parser XML i zwraca uchwyt zasobów umożliwiający użycie go przez inne funkcje XML.

Parametry

kodowanie

Opcjonalny parametr kodowanie określa w PHP 4 kodowanie znaków wejścia/wyjścia. Od PHP 5 kodowanie danych wejściowych jest automatycznie wykrywane, więc parametr kodowanie określa tylko kodowanie na wyjściu. W PHP 4 domyślne kodowanie wyjściowe jest takie same jak i wejściowe. Jeśli podany został pusty ciąg znaków, wówczas parser próbuje zidentyfikować kodowanie znaków dokumentu sprawdzając jego pierwsze 3 lub 4 bajty. W PHP 5.0.0 oraz 5.0.1 domyślnym kodowaniem znaków na wyjściu jest ISO-8859-1, podczas gdy w PHP 5.0.2 i wyżej UTF-8. Obsługiwanymi kodowaniami są ISO-8859-1, UTF-8 oraz US-ASCII.

Zwracane wartości

Zwraca uchwyt zasobów dla nowego parsera XML.

Zobacz też:

  • xml_parser_create_ns() - Create an XML parser with namespace support
  • xml_parser_free() - Zwalnia parser XML

xml_parser_create_ns
xml_parser_free
XML Parser Funkcje


Zwalnia parser XML

xml_parser_create
xml_parser_get_option
XML Parser Funkcje
PHP Manual

xml_parser_free

(PHP 4, PHP 5)

xml_parser_free — Zwalnia parser XML

Opis

bool xml_parser_free ( resource $parser )

Zwalnia podany parser XML.

Parametry

parser
Referencja do parsera XML, który ma zostać zwolniony.

Zwracane wartości

Ta funkcja zwraca FALSE jeśli parser nie odnosi się do prawidłowego parsera, lub zwalnia parser i zwraca TRUE.

xml_parser_create
xml_parser_get_option
XML Parser Funkcje


Get options from an XML parser

xml_parser_free
xml_parser_set_option
XML Parser Funkcje
PHP Manual

xml_parser_get_option

(PHP 4, PHP 5)

xml_parser_get_option — Get options from an XML parser

Opis

mixed xml_parser_get_option ( resource $parser , int $option )

Gets an option value from an XML parser.

Parametry

parser
A reference to the XML parser to get an option from.
option
Which option to fetch. XML_OPTION_CASE_FOLDING and XML_OPTION_TARGET_ENCODING are available. See xml_parser_set_option() for their description.

Zwracane wartości

This function returns FALSE if parser does not refer to a valid parser or if option isn't valid (generates also a E_WARNING). Else the option's value is returned.

xml_parser_free
xml_parser_set_option
XML Parser Funkcje


Set options in an XML parser

xml_parser_get_option
xml_set_character_data_handler
XML Parser Funkcje
PHP Manual

xml_parser_set_option

(PHP 4, PHP 5)

xml_parser_set_option — Set options in an XML parser

Opis

bool xml_parser_set_option ( resource $parser , int $option , mixed $value )

Sets an option in an XML parser.

Parametry

parser

A reference to the XML parser to set an option in.

option

Which option to set. See below.

The following options are available:

XML parser options
Option constant | Data type | Description
XML_OPTION_CASE_FOLDING | integer | Controls whether case-folding is enabled for this XML parser. Enabled by default.
XML_OPTION_SKIP_TAGSTART | integer | Specify how many characters should be skipped in the beginning of a tag name.
XML_OPTION_SKIP_WHITE | integer | Whether to skip values consisting of whitespace characters.
XML_OPTION_TARGET_ENCODING | string | Sets which target encoding to use in this XML parser.By default, it is set to the same as the source encoding used by xml_parser_create(). Supported target encodings are ISO-8859-1, US-ASCII and UTF-8.

value

The option's new value.

Zwracane wartości

This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and TRUE is returned.

xml_parser_get_option
xml_set_character_data_handler
XML Parser Funkcje


Set up character data handler

xml_parser_set_option
xml_set_default_handler
XML Parser Funkcje
PHP Manual

xml_set_character_data_handler

(PHP 4, PHP 5)

xml_set_character_data_handler — Set up character data handler

Opis

bool xml_set_character_data_handler ( resource $parser , callback $handler )

Sets the character data handler function for the XML parser parser.

Parametry

parser

A reference to the XML parser to set up character data handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters:

handler ( resource $parser , string $data )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
data
The second parameter, data, contains the character data as a string.

Character data handler is called for every piece of a text in the XML document. It can be called multiple times inside each fragment (e.g. for non-ASCII strings).

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

xml_parser_set_option
xml_set_default_handler
XML Parser Funkcje


Set up default handler

xml_set_character_data_handler
xml_set_element_handler
XML Parser Funkcje
PHP Manual

xml_set_default_handler

(PHP 4, PHP 5)

xml_set_default_handler — Set up default handler

Opis

bool xml_set_default_handler ( resource $parser , callback $handler )

Sets the default handler function for the XML parser parser.

Parametry

parser

A reference to the XML parser to set up default handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters:

handler ( resource $parser , string $data )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
data
The second parameter, data, contains the character data.This may be the XML declaration, document type declaration, entities or other data for which no other handler exists.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

xml_set_character_data_handler
xml_set_element_handler
XML Parser Funkcje


Ustawia początkową i końcową procedurę obsługi elementu

xml_set_default_handler
xml_set_end_namespace_decl_handler
XML Parser Funkcje
PHP Manual

xml_set_element_handler

(PHP 4, PHP 5)

xml_set_element_handler — Ustawia początkową i końcową procedurę obsługi elementu

Opis

bool xml_set_element_handler ( resource $parser , callback $początkowa_procedura_obsługi_elementu , callback $końcowa_procedura_obsługi_elementu )

Ustawia funkcje procedury obsługi elementu dla parser XML. początkowa_procedura_obsługi_elementu i końcowa_procedura_obsługi_elementu są ciągami znaków zawierającymi nazwy funkcji, które muszą istnieć podczas wywołania xml_parse() dla parser.

Parametry

parser

Referencja do parsera XML do ustawiania obsługi funkcji początku i końca elementu.

początkowa_procedura_obsługi_elementu

Funkcja nazwana przez początkowa_procedura_obsługi_elementu musi przyjmować trzy parametry:

początkowa_procedura_obsługi_elementu ( resource $parser , string $nazwa , array $atrybuty )
parser
Pierwszy parametr, parser, jest referencją do parsera XML wywołującego procedurę obsługi.
nazwa
Drugi parametr, nazwa, zawiera nazwę elementu dla którego procedura obsługi została wywołana. Jeśli dla tego parsera włączony jest case-folding, wówczas nazwa elementu będzie zamieniona na duże litery.
atrybuty
Trzeci parametr, atrybuty, zawiera tablicę asocjacyjną z atrybutami elementów (jeśli jakiekolwiek są). Kluczami tych tablic są nazwy atrybutów a wartościami wartości artybutów. Nazwy atrybutów są zamieniane na duże litery za pomocą opcji case-folding na tej samej zasadzie jak nazwy elementów. Wartości atrybutów opcja case-folded nie dotyczy. Oryginalna kolejność atrybutów może być odzyskana za pomocą normalnego przejścia przez atrybuty używając each(). Pierwszy klucz w tablicy był pierwszym atrybutem itd.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

końcowa_procedura_obsługi_elementu

Funkcja nazwana przez końcowa_procedura_obsługi_elementu musi przyjmować dwa parametry:

końcowa_procedura_obsługi_elementu ( resource $parser , string $nazwa )
parser
Pierwszy parametr, parser, jest referencją do parsera XML wywołującego procedurę obsługi.
nazwa
Drugi parametr, nazwa, zawiera nazwę elementu dla którego procedura obsługi została wywołana. Jeśli dla tego parsera włączony jest case-folding, wówczas nazwa elementu będzie zamieniona na duże litery.

Jeśli funkcja procedury obsługi jest podana jako pusty ciąg znaków lub FALSE, wówczas procedura obsługi w zapytaniu jest wyłączona.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

xml_set_default_handler
xml_set_end_namespace_decl_handler
XML Parser Funkcje


Set up end namespace declaration handler

xml_set_element_handler
xml_set_external_entity_ref_handler
XML Parser Funkcje
PHP Manual

xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5)

xml_set_end_namespace_decl_handler — Set up end namespace declaration handler

Opis

bool xml_set_end_namespace_decl_handler ( resource $parser , callback $handler )

Set a handler to be called when leaving the scope of a namespace declaration. This will be called, for each namespace declaration, after the handler for the end tag of the element in which the namespace was declared.

Parametry

parser

A reference to the XML parser.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters, and should return an integer value. If the value returned from the handler is FALSE (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
prefix
The prefix is a string used to reference the namespace within an XML object.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Notatki

Informacja:

This event is not supported under LibXML.

Zobacz też:

  • xml_set_start_namespace_decl_handler() - Set up start namespace declaration handler

xml_set_element_handler
xml_set_external_entity_ref_handler
XML Parser Funkcje


Set up external entity reference handler

xml_set_end_namespace_decl_handler
xml_set_notation_decl_handler
XML Parser Funkcje
PHP Manual

xml_set_external_entity_ref_handler

(PHP 4, PHP 5)

xml_set_external_entity_ref_handler — Set up external entity reference handler

Opis

bool xml_set_external_entity_ref_handler ( resource $parser , callback $handler )

Sets the external entity reference handler function for the XML parser parser.

Parametry

parser

A reference to the XML parser to set up external entity reference handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept five parameters, and should return an integer value.If the value returned from the handler is FALSE (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $open_entity_names , string $base , string $system_id , string $public_id )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
open_entity_names
The second parameter, open_entity_names, is a space-separated list of the names of the entities that are open for the parse of this entity (including the name of the referenced entity).
base
This is the base for resolving the system identifier (system_id) of the external entity.Currently this parameter will always be set to an empty string.
system_id
The fourth parameter, system_id, is the system identifier as specified in the entity declaration.
public_id
The fifth parameter, public_id, is the public identifier as specified in the entity declaration, or an empty string if none was specified; the whitespace in the public identifier will have been normalized as required by the XML spec.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

xml_set_end_namespace_decl_handler
xml_set_notation_decl_handler
XML Parser Funkcje


Set up notation declaration handler

xml_set_external_entity_ref_handler
xml_set_object
XML Parser Funkcje
PHP Manual

xml_set_notation_decl_handler

(PHP 4, PHP 5)

xml_set_notation_decl_handler — Set up notation declaration handler

Opis

bool xml_set_notation_decl_handler ( resource $parser , callback $handler )

Sets the notation declaration handler function for the XML parser parser.

A notation declaration is part of the document's DTD and has the following format:

<!NOTATION <parameter>name</parameter>
{ <parameter>systemId</parameter> | <parameter>publicId</parameter>?>
See » section 4.7 of the XML 1.0 spec for the definition of notation declarations.

Parametry

parser

A reference to the XML parser to set up notation declaration handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept five parameters:

handler ( resource $parser , string $notation_name , string $base , string $system_id , string $public_id )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
notation_name
This is the notation's name, as per the notation format described above.
base
This is the base for resolving the system identifier (system_id) of the notation declaration. Currently this parameter will always be set to an empty string.
system_id
System identifier of the external notation declaration.
public_id
Public identifier of the external notation declaration.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

xml_set_external_entity_ref_handler
xml_set_object
XML Parser Funkcje


Use XML Parser within an object

xml_set_notation_decl_handler
xml_set_processing_instruction_handler
XML Parser Funkcje
PHP Manual

xml_set_object

(PHP 4, PHP 5)

xml_set_object — Use XML Parser within an object

Opis

bool xml_set_object ( resource $parser , object &$object )

This function allows to use parser inside object. All callback functions could be set with xml_set_element_handler() etc and assumed to be methods of object.

Parametry

parser

A reference to the XML parser to use inside the object.

object

The object where to use the XML parser.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 xml_set_object() example

<?php
class xml  {
    var $parser;

    function xml()
    {
        $this->parser = xml_parser_create();

        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
    }

    function parse($data)
    {
        xml_parse($this->parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    {
        var_dump($parser, $tag, $attributes);
    }

    function cdata($parser, $cdata)
    {
        var_dump($parser, $cdata);
    }

    function tag_close($parser, $tag)
    {
        var_dump($parser, $tag);
    }

} // end of class xml

$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

xml_set_notation_decl_handler
xml_set_processing_instruction_handler
XML Parser Funkcje


Set up processing instruction (PI) handler

xml_set_object
xml_set_start_namespace_decl_handler
XML Parser Funkcje
PHP Manual

xml_set_processing_instruction_handler

(PHP 4, PHP 5)

xml_set_processing_instruction_handler — Set up processing instruction (PI) handler

Opis

bool xml_set_processing_instruction_handler ( resource $parser , callback $handler )

Sets the processing instruction (PI) handler function for the XML parser parser.

A processing instruction has the following format:

<?
target data
?>
You can put PHP code into such a tag, but be aware of one limitation: in an XML PI, the PI end tag (?>) can not be quoted, so this character sequence should not appear in the PHP code you embed with PIs in XML documents.If it does, the rest of the PHP code, as well as the "real" PI end tag, will be treated as character data.

Parametry

parser

A reference to the XML parser to set up processing instruction (PI) handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept three parameters:

handler ( resource $parser , string $target , string $data )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
target
The second parameter, target, contains the PI target.
data
The third parameter, data, contains the PI data.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

xml_set_object
xml_set_start_namespace_decl_handler
XML Parser Funkcje


Set up start namespace declaration handler

xml_set_processing_instruction_handler
xml_set_unparsed_entity_decl_handler
XML Parser Funkcje
PHP Manual

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5)

xml_set_start_namespace_decl_handler — Set up start namespace declaration handler

Opis

bool xml_set_start_namespace_decl_handler ( resource $parser , callback $handler )

Set a handler to be called when a namespace is declared. Namespace declarations occur inside start tags. But the namespace declaration start handler is called before the start tag handler for each namespace declared in that start tag.

Parametry

parser

A reference to the XML parser.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept three parameters, and should return an integer value. If the value returned from the handler is FALSE (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix , string $uri )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
prefix
The prefix is a string used to reference the namespace within an XML object.
uri
Uniform Resource Identifier (URI) of namespace.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • xml_set_end_namespace_decl_handler() - Set up end namespace declaration handler

xml_set_processing_instruction_handler
xml_set_unparsed_entity_decl_handler
XML Parser Funkcje


Set up unparsed entity declaration handler

xml_set_start_namespace_decl_handler
XMLReader
XML Parser Funkcje
PHP Manual

xml_set_unparsed_entity_decl_handler

(PHP 4, PHP 5)

xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler

Opis

bool xml_set_unparsed_entity_decl_handler ( resource $parser , callback $handler )

Sets the unparsed entity declaration handler function for the XML parser parser.

The handler will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following:

<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>}
        NDATA <parameter>notationName</parameter>

See » section 4.2.2 of the XML 1.0 spec for the definition of notation declared external entities.

Parametry

parser

A reference to the XML parser to set up unparsed entity declaration handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept six parameters:

handler ( resource $parser , string $entity_name , string $base , string $system_id , string $public_id , string $notation_name )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
entity_name
The name of the entity that is about to be defined.
base
This is the base for resolving the system identifier (systemId) of the external entity.Currently this parameter will always be set to an empty string.
system_id
System identifier for the external entity.
public_id
Public identifier for the external entity.
notation_name
Name of the notation of this entity (see xml_set_notation_decl_handler()).

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Informacja: Zamiast nazwy funkcji może zostać przekazana tablica zawierająca referencję do obiektu i nazwę metody

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

xml_set_start_namespace_decl_handler
XMLReader
XML Parser Funkcje


XMLReader

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • XMLReader — The XMLReader class
    • XMLReader::close — Close the XMLReader input
    • XMLReader::expand — Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute — Get the value of a named attribute
    • XMLReader::getAttributeNo — Get the value of an attribute by index
    • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty — Indicates if specified property has been set
    • XMLReader::isValid — Indicates if the parsed document is valid
    • XMLReader::lookupNamespace — Lookup namespace for a prefix
    • XMLReader::moveToAttribute — Move cursor to a named attribute
    • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs — Move cursor to a named attribute
    • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
    • XMLReader::next — Move cursor to next node skipping all subtrees
    • XMLReader::open — Set the URI containing the XML to parse
    • XMLReader::read — Move to next node in document
    • XMLReader::readInnerXML — Retrieve XML from current node
    • XMLReader::readOuterXML — Retrieve XML from current node, including it self
    • XMLReader::readString — Reads the contents of the current node as a string
    • XMLReader::setParserProperty — Set parser options
    • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
    • XMLReader::setSchema — Validate document against XSD
    • XMLReader::XML — Set the data containing the XML to parse
xml_set_unparsed_entity_decl_handler
Wstęp
Przetwarzanie XML


Wstęp

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Kodowanie znaków

It is important to note that internally, libxml uses the UTF-8 encoding and as such, the encoding of the retrieved contents will always be in UTF-8 encoding.

XMLReader
Instalacja/Konfiguracja
XMLReader


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
XMLReader


Instalacja

The XMLReader extension is available in PECL as of PHP 5.0.0 and is included and enabled as of PHP 5.1.0 by default. It can be enabled by adding the argument --enable-xmlreader (or --with-xmlreader before 5.1.0) to the configure line.

To rozszerzenie jest domyślnie włączone. Może być ono wyłączone za pomocą następującej opcji w czasie kompilacji: --disable-xmlreader

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Konfiguracja wykonawcza
XMLReader
Instalacja/Konfiguracja


The XMLReader class

(No version information available, might only be in SVN)

Wstęp

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Krótki opis klasy

XMLReader {
/* Stałe */
const int NONE = 0 ;
const int ELEMENT = 1 ;
const int ATTRIBUTE = 2 ;
const int TEXT = 3 ;
const int CDATA = 4 ;
const int ENTITY_REF = 5 ;
const int ENTITY = 6 ;
const int PI = 7 ;
const int COMMENT = 8 ;
const int DOC = 9 ;
const int DOC_TYPE = 10 ;
const int DOC_FRAGMENT = 11 ;
const int NOTATION = 12 ;
const int WHITESPACE = 13 ;
const int SIGNIFICANT_WHITESPACE = 14 ;
const int END_ELEMENT = 15 ;
const int END_ENTITY = 16 ;
const int XML_DECLARATION = 17 ;
const int LOADDTD = 1 ;
const int DEFAULTATTRS = 2 ;
const int VALIDATE = 3 ;
const int SUBST_ENTITIES = 4 ;
/* Właściwości */
public readonly int $attributeCount ;
public readonly string $baseURI ;
public readonly int $depth ;
public readonly bool $hasAttributes ;
public readonly bool $hasValue ;
public readonly bool $isDefault ;
public readonly bool $isEmptyElement ;
public readonly string $localName ;
public readonly string $name ;
public readonly string $namespaceURI ;
public readonly int $nodeType ;
public readonly string $prefix ;
public readonly string $value ;
public readonly string $xmlLang ;
/* Metody */
bool close ( void )
DOMNode expand ([ DOMNode $basenode ] )
string getAttribute ( string $name )
string getAttributeNo ( int $index )
string getAttributeNs ( string $localName , string $namespaceURI )
bool getParserProperty ( int $property )
bool isValid ( void )
bool lookupNamespace ( string $prefix )
bool moveToAttribute ( string $name )
bool moveToAttributeNo ( int $index )
bool moveToAttributeNs ( string $localName , string $namespaceURI )
bool moveToElement ( void )
bool moveToFirstAttribute ( void )
bool moveToNextAttribute ( void )
bool next ([ string $localname ] )
bool open ( string $URI [, string $encoding [, int $options = 0 ]] )
bool read ( void )
string readInnerXML ( void )
string readOuterXML ( void )
string readString ( void )
bool setParserProperty ( int $property , bool $value )
bool setRelaxNGSchema ( string $filename )
bool setRelaxNGSchemaSource ( string $source )
bool setSchema ( string $filename )
bool xml ( string $source [, string $encoding [, int $options = 0 ]] )
}

Właściwości

attributeCount

The number of attributes on the node

baseURI

The base URI of the node

depth

Depth of the node in the tree, starting at 0

hasAttributes

Indicates if node has attributes

hasValue

Indicates if node has a text value

isDefault

Indicates if attribute is defaulted from DTD

isEmptyElement

Indicates if node is an empty element tag

localName

The local name of the node

name

The qualified name of the node

namespaceURI

The URI of the namespace associated with the node

nodeType

The node type for the node

prefix

The prefix of the namespace associated with the node

value

The text value of the node

xmlLang

The xml:lang scope which the node resides

Stałe predefiniowane

XMLReader Node Types

XMLReader::NONE

No node type

XMLReader::ELEMENT

Start element

XMLReader::ATTRIBUTE

Attribute node

XMLReader::TEXT

Text node

XMLReader::CDATA

CDATA node

XMLReader::ENTITY_REF

Entity Reference node

XMLReader::ENTITY

Entity Declaration node

XMLReader::PI

Processing Instruction node

XMLReader::COMMENT

Comment node

XMLReader::DOC

Document node

XMLReader::DOC_TYPE

Document Type node

XMLReader::DOC_FRAGMENT

Document Fragment node

XMLReader::NOTATION

Notation node

XMLReader::WHITESPACE

Whitespace node

XMLReader::SIGNIFICANT_WHITESPACE

Significant Whitespace node

XMLReader::END_ELEMENT

End Element

XMLReader::END_ENTITY

End Entity

XMLReader::XML_DECLARATION

XML Declaration node

XMLReader Parser Options

XMLReader::LOADDTD

Load DTD but do not validate

XMLReader::DEFAULTATTRS

Load DTD and default attributes but do not validate

XMLReader::VALIDATE

Load DTD and validate while parsing

XMLReader::SUBST_ENTITIES

Substitute entities and expand references

Spis treści

  • XMLReader::close — Close the XMLReader input
  • XMLReader::expand — Returns a copy of the current node as a DOM object
  • XMLReader::getAttribute — Get the value of a named attribute
  • XMLReader::getAttributeNo — Get the value of an attribute by index
  • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
  • XMLReader::getParserProperty — Indicates if specified property has been set
  • XMLReader::isValid — Indicates if the parsed document is valid
  • XMLReader::lookupNamespace — Lookup namespace for a prefix
  • XMLReader::moveToAttribute — Move cursor to a named attribute
  • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs — Move cursor to a named attribute
  • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
  • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
  • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
  • XMLReader::next — Move cursor to next node skipping all subtrees
  • XMLReader::open — Set the URI containing the XML to parse
  • XMLReader::read — Move to next node in document
  • XMLReader::readInnerXML — Retrieve XML from current node
  • XMLReader::readOuterXML — Retrieve XML from current node, including it self
  • XMLReader::readString — Reads the contents of the current node as a string
  • XMLReader::setParserProperty — Set parser options
  • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
  • XMLReader::setSchema — Validate document against XSD
  • XMLReader::XML — Set the data containing the XML to parse
Typy zasobów
XMLReader::close
XMLReader


Close the XMLReader input

XMLReader
XMLReader::expand
XMLReader
PHP Manual

XMLReader::close

(PHP 5 >= 5.1.2)

XMLReader::close — Close the XMLReader input

Opis

bool XMLReader::close ( void )

Closes the input the XMLReader object is currently parsing.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::xml() - Set the data containing the XML to parse

XMLReader
XMLReader::expand
XMLReader


Returns a copy of the current node as a DOM object

XMLReader::close
XMLReader::getAttribute
XMLReader
PHP Manual

XMLReader::expand

(PHP 5 >= 5.1.2)

XMLReader::expand — Returns a copy of the current node as a DOM object

Opis

DOMNode XMLReader::expand ([ DOMNode $basenode ] )

This method copies the current node and returns the appropriate DOM object.

Zwracane wartości

The resulting DOMNode or FALSE on error.

XMLReader::close
XMLReader::getAttribute
XMLReader


Get the value of a named attribute

XMLReader::expand
XMLReader::getAttributeNo
XMLReader
PHP Manual

XMLReader::getAttribute

(PHP 5 >= 5.1.2)

XMLReader::getAttribute — Get the value of a named attribute

Opis

string XMLReader::getAttribute ( string $name )

Returns the value of a named attribute or NULL if the attribute does not exist or not positioned on an element node.

Parametry

name

The name of the attribute.

Zwracane wartości

The value of the attribute, or NULL if no attribute with the given name is found or not positioned on an element node.

Rejestr zmian

Wersja | Opis
5.1.3 | Return NULL if no attribute found. Previously, returned an empty string.

Zobacz też:

  • XMLReader::getAttributeNo() - Get the value of an attribute by index
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI

XMLReader::expand
XMLReader::getAttributeNo
XMLReader


Get the value of an attribute by index

XMLReader::getAttribute
XMLReader::getAttributeNs
XMLReader
PHP Manual

XMLReader::getAttributeNo

(PHP 5 >= 5.1.2)

XMLReader::getAttributeNo — Get the value of an attribute by index

Opis

string XMLReader::getAttributeNo ( int $index )

Returns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node.

Parametry

index

The position of the attribute.

Zwracane wartości

The value of the attribute, or an empty string if no attribute exists at index or not positioned of element.

Zobacz też:

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI

XMLReader::getAttribute
XMLReader::getAttributeNs
XMLReader


Get the value of an attribute by localname and URI

XMLReader::getAttributeNo
XMLReader::getParserProperty
XMLReader
PHP Manual

XMLReader::getAttributeNs

(PHP 5 >= 5.1.2)

XMLReader::getAttributeNs — Get the value of an attribute by localname and URI

Opis

string XMLReader::getAttributeNs ( string $localName , string $namespaceURI )

Returns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.

Parametry

localName

The local name.

namespaceURI

The namespace URI.

Zwracane wartości

The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found or not positioned of element.

Zobacz też:

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNo() - Get the value of an attribute by index

XMLReader::getAttributeNo
XMLReader::getParserProperty
XMLReader


Indicates if specified property has been set

XMLReader::getAttributeNs
XMLReader::isValid
XMLReader
PHP Manual

XMLReader::getParserProperty

(PHP 5 >= 5.1.2)

XMLReader::getParserProperty — Indicates if specified property has been set

Opis

bool XMLReader::getParserProperty ( int $property )

Indicates if specified property has been set.

Parametry

property

One of the parser option constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::setParserProperty() - Set parser options

XMLReader::getAttributeNs
XMLReader::isValid
XMLReader


Indicates if the parsed document is valid

XMLReader::getParserProperty
XMLReader::lookupNamespace
XMLReader
PHP Manual

XMLReader::isValid

(PHP 5 >= 5.1.2)

XMLReader::isValid — Indicates if the parsed document is valid

Opis

bool XMLReader::isValid ( void )

Returns a boolean indicating if the document being parsed is currently valid.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Validating XML

<?php
$xml = XMLReader::open('test.xml');

// You must to use it
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Zobacz też:

  • XMLReader::setParserProperty() - Set parser options
  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD

XMLReader::getParserProperty
XMLReader::lookupNamespace
XMLReader


Lookup namespace for a prefix

XMLReader::isValid
XMLReader::moveToAttribute
XMLReader
PHP Manual

XMLReader::lookupNamespace

(PHP 5 >= 5.1.2)

XMLReader::lookupNamespace — Lookup namespace for a prefix

Opis

bool XMLReader::lookupNamespace ( string $prefix )

Lookup in scope namespace for a given prefix.

Parametry

prefix

String containing the prefix.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

XMLReader::isValid
XMLReader::moveToAttribute
XMLReader


Move cursor to a named attribute

XMLReader::lookupNamespace
XMLReader::moveToAttributeNo
XMLReader
PHP Manual

XMLReader::moveToAttribute

(PHP 5 >= 5.1.2)

XMLReader::moveToAttribute — Move cursor to a named attribute

Opis

bool XMLReader::moveToAttribute ( string $name )

Positions cursor on the named attribute.

Parametry

name

The name of the attribute.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

XMLReader::lookupNamespace
XMLReader::moveToAttributeNo
XMLReader


Move cursor to an attribute by index

XMLReader::moveToAttribute
XMLReader::moveToAttributeNs
XMLReader
PHP Manual

XMLReader::moveToAttributeNo

(PHP 5 >= 5.1.2)

XMLReader::moveToAttributeNo — Move cursor to an attribute by index

Opis

bool XMLReader::moveToAttributeNo ( int $index )

Positions cursor on attribute based on its position.

Parametry

index

The position of the attribute.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

XMLReader::moveToAttribute
XMLReader::moveToAttributeNs
XMLReader


Move cursor to a named attribute

XMLReader::moveToAttributeNo
XMLReader::moveToElement
XMLReader
PHP Manual

XMLReader::moveToAttributeNs

(PHP 5 >= 5.1.2)

XMLReader::moveToAttributeNs — Move cursor to a named attribute

Opis

bool XMLReader::moveToAttributeNs ( string $localName , string $namespaceURI )

Positions cursor on the named attribute in specified namespace.

Parametry

localName

The local name.

namespaceURI

The namespace URI.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

XMLReader::moveToAttributeNo
XMLReader::moveToElement
XMLReader


Position cursor on the parent Element of current Attribute

XMLReader::moveToAttributeNs
XMLReader::moveToFirstAttribute
XMLReader
PHP Manual

XMLReader::moveToElement

(PHP 5 >= 5.1.2)

XMLReader::moveToElement — Position cursor on the parent Element of current Attribute

Opis

bool XMLReader::moveToElement ( void )

Moves cursor to the parent Element of current Attribute.

Zwracane wartości

Returns TRUE if successful and FALSE if it fails or not positioned on Attribute when this method is called.

Zobacz też:

  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

XMLReader::moveToAttributeNs
XMLReader::moveToFirstAttribute
XMLReader


Position cursor on the first Attribute

XMLReader::moveToElement
XMLReader::moveToNextAttribute
XMLReader
PHP Manual

XMLReader::moveToFirstAttribute

(PHP 5 >= 5.1.2)

XMLReader::moveToFirstAttribute — Position cursor on the first Attribute

Opis

bool XMLReader::moveToFirstAttribute ( void )

Moves cursor to the first Attribute.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute

XMLReader::moveToElement
XMLReader::moveToNextAttribute
XMLReader


Position cursor on the next Attribute

XMLReader::moveToFirstAttribute
XMLReader::next
XMLReader
PHP Manual

XMLReader::moveToNextAttribute

(PHP 5 >= 5.1.2)

XMLReader::moveToNextAttribute — Position cursor on the next Attribute

Opis

bool XMLReader::moveToNextAttribute ( void )

Moves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

XMLReader::moveToFirstAttribute
XMLReader::next
XMLReader


Move cursor to next node skipping all subtrees

XMLReader::moveToNextAttribute
XMLReader::open
XMLReader
PHP Manual

XMLReader::next

(PHP 5 >= 5.1.2)

XMLReader::next — Move cursor to next node skipping all subtrees

Opis

bool XMLReader::next ([ string $localname ] )

Positions cursor on the next node skipping all subtrees.

Parametry

localname

The name of the next node to move to.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute
  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute

XMLReader::moveToNextAttribute
XMLReader::open
XMLReader


Set the URI containing the XML to parse

XMLReader::next
XMLReader::read
XMLReader
PHP Manual

XMLReader::open

(PHP 5 >= 5.1.2)

XMLReader::open — Set the URI containing the XML to parse

Opis

bool XMLReader::open ( string $URI [, string $encoding [, int $options = 0 ]] )

Set the URI containing the XML document to be parsed.

Parametry

URI

URI pointing to the document.

encoding

The document encoding or NULL.

options

A bitmask of the LIBXML_* constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If called statically, returns an XMLReader lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

Rejestr zmian

Wersja | Opis
5.2.0 | encoding and options were added.

Zobacz też:

  • XMLReader::xml() - Set the data containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

XMLReader::next
XMLReader::read
XMLReader


Move to next node in document

XMLReader::open
XMLReader::readInnerXML
XMLReader
PHP Manual

XMLReader::read

(PHP 5 >= 5.1.2)

XMLReader::read — Move to next node in document

Opis

bool XMLReader::read ( void )

Moves cursor to the next node in the document.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::next() - Move cursor to next node skipping all subtrees

XMLReader::open
XMLReader::readInnerXML
XMLReader


Retrieve XML from current node

XMLReader::read
XMLReader::readOuterXML
XMLReader
PHP Manual

XMLReader::readInnerXML

(PHP 5 >= 5.2.0)

XMLReader::readInnerXML — Retrieve XML from current node

Opis

string XMLReader::readInnerXML ( void )

Reads the contents of the current node, including child nodes and markup.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the contents of the current node as a string. Empty string on failure.

Notatki

Uwaga

Ta funkcja jest dostępna tylko wtedy, gdy PHP zostało skompilowane z biblioteką libxml 20620 lub nowszą.

Zobacz też:

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readOuterXML() - Retrieve XML from current node, including it self
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

XMLReader::read
XMLReader::readOuterXML
XMLReader


Retrieve XML from current node, including it self

XMLReader::readInnerXML
XMLReader::readString
XMLReader
PHP Manual

XMLReader::readOuterXML

(PHP 5 >= 5.2.0)

XMLReader::readOuterXML — Retrieve XML from current node, including it self

Opis

string XMLReader::readOuterXML ( void )

Reads the contents of the current node, including the node itself.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the contents of current node, including itself, as a string. Empty string on failure.

Notatki

Uwaga

Ta funkcja jest dostępna tylko wtedy, gdy PHP zostało skompilowane z biblioteką libxml 20620 lub nowszą.

Zobacz też:

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readInnerXML() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

XMLReader::readInnerXML
XMLReader::readString
XMLReader


Reads the contents of the current node as a string

XMLReader::readOuterXML
XMLReader::setParserProperty
XMLReader
PHP Manual

XMLReader::readString

(PHP 5 >= 5.2.0)

XMLReader::readString — Reads the contents of the current node as a string

Opis

string XMLReader::readString ( void )

Reads the contents of the current node as a string.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the content of the current node as a string. Empty string on failure.

Notatki

Uwaga

Ta funkcja jest dostępna tylko wtedy, gdy PHP zostało skompilowane z biblioteką libxml 20620 lub nowszą.

Zobacz też:

  • XMLReader::readOuterXML() - Retrieve XML from current node, including it self
  • XMLReader::readInnerXML() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

XMLReader::readOuterXML
XMLReader::setParserProperty
XMLReader


Set parser options

XMLReader::readString
XMLReader::setRelaxNGSchema
XMLReader
PHP Manual

XMLReader::setParserProperty

(PHP 5 >= 5.1.2)

XMLReader::setParserProperty — Set parser options

Opis

bool XMLReader::setParserProperty ( int $property , bool $value )

Set parser options. The options must be set after
 XMLReader::open() or
 XMLReader::xml() are called and before
the first  XMLReader::read() call.

Parametry

property

One of the parser option constants.

value

If set to TRUE the option will be enabled otherwise will be disabled.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

XMLReader::readString
XMLReader::setRelaxNGSchema
XMLReader


Set the filename or URI for a RelaxNG Schema

XMLReader::setParserProperty
XMLReader::setRelaxNGSchemaSource
XMLReader
PHP Manual

XMLReader::setRelaxNGSchema

(PHP 5 >= 5.2.0)

XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema

Opis

bool XMLReader::setRelaxNGSchema ( string $filename )

Set the filename or URI for the RelaxNG Schema to use for validation.

Parametry

filename

filename or URI pointing to a RelaxNG Schema.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid

XMLReader::setParserProperty
XMLReader::setRelaxNGSchemaSource
XMLReader


Set the data containing a RelaxNG Schema

XMLReader::setRelaxNGSchema
XMLReader::setSchema
XMLReader
PHP Manual

XMLReader::setRelaxNGSchemaSource

(PHP 5 >= 5.1.2)

XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema

Opis

bool XMLReader::setRelaxNGSchemaSource ( string $source )

Set the data containing a RelaxNG Schema to use for validation.

Parametry

source

String containing the RelaxNG Schema.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid

XMLReader::setRelaxNGSchema
XMLReader::setSchema
XMLReader


Validate document against XSD

XMLReader::setRelaxNGSchemaSource
XMLReader::XML
XMLReader
PHP Manual

XMLReader::setSchema

(PHP 5 >= 5.2.0)

XMLReader::setSchema — Validate document against XSD

Opis

bool XMLReader::setSchema ( string $filename )

Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read().

Parametry

filename

The filename of the XSD schema.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Issues E_WARNING if libxml was built without schema support, the schema contains errors or if XMLReader::read() has already been called.

Notatki

Uwaga

Ta funkcja jest dostępna tylko wtedy, gdy PHP zostało skompilowane z biblioteką libxml 20620 lub nowszą.

Zobacz też:

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::isValid() - Indicates if the parsed document is valid

XMLReader::setRelaxNGSchemaSource
XMLReader::XML
XMLReader


Set the data containing the XML to parse

XMLReader::setSchema
XMLWriter
XMLReader
PHP Manual

XMLReader::XML

(PHP 5 >= 5.1.2)

XMLReader::XML — Set the data containing the XML to parse

Opis

bool XMLReader::xml ( string $source [, string $encoding [, int $options = 0 ]] )

Set the data containing the XML to parse.

Parametry

source

String containing the XML to be parsed.

encoding

The document encoding or NULL.

options

A bitmask of the LIBXML_* constants.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If called statically, returns an XMLReader lub FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Ta metoda może być wywoływana statycznie, ale spowoduje błąd E_STRICT.

Rejestr zmian

Wersja | Opis
5.2.0 | encoding and options were added.

Zobacz też:

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

XMLReader::setSchema
XMLWriter
XMLReader


XMLWriter

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • XMLWriter Funkcje
    • XMLWriter::endAttribute — End attribute
    • XMLWriter::endCData — End current CDATA
    • XMLWriter::endComment — Create end comment
    • XMLWriter::endDocument — End current document
    • XMLWriter::endDTDAttlist — End current DTD AttList
    • XMLWriter::endDTDElement — End current DTD element
    • XMLWriter::endDTDEntity — End current DTD Entity
    • XMLWriter::endDTD — End current DTD
    • XMLWriter::endElement — End current element
    • XMLWriter::endPI — End current PI
    • XMLWriter::flush — Flush current buffer
    • XMLWriter::fullEndElement — End current element
    • XMLWriter::openMemory — Create new xmlwriter using memory for string output
    • XMLWriter::openURI — Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory — Returns current buffer
    • XMLWriter::setIndentString — Set string used for indenting
    • XMLWriter::setIndent — Toggle indentation on/off
    • XMLWriter::startAttributeNS — Create start namespaced attribute
    • XMLWriter::startAttribute — Create start attribute
    • XMLWriter::startCData — Create start CDATA tag
    • XMLWriter::startComment — Create start comment
    • XMLWriter::startDocument — Create document tag
    • XMLWriter::startDTDAttlist — Create start DTD AttList
    • XMLWriter::startDTDElement — Create start DTD element
    • XMLWriter::startDTDEntity — Create start DTD Entity
    • XMLWriter::startDTD — Create start DTD tag
    • XMLWriter::startElementNS — Create start namespaced element tag
    • XMLWriter::startElement — Create start element tag
    • XMLWriter::startPI — Create start PI tag
    • XMLWriter::text — Write text
    • XMLWriter::writeAttributeNS — Write full namespaced attribute
    • XMLWriter::writeAttribute — Write full attribute
    • XMLWriter::writeCData — Write full CDATA tag
    • XMLWriter::writeComment — Write full comment tag
    • XMLWriter::writeDTDAttlist — Write full DTD AttList tag
    • XMLWriter::writeDTDElement — Write full DTD element tag
    • XMLWriter::writeDTDEntity — Write full DTD Entity tag
    • XMLWriter::writeDTD — Write full DTD tag
    • XMLWriter::writeElementNS — Write full namespaced element tag
    • XMLWriter::writeElement — Write full element tag
    • XMLWriter::writePI — Writes a PI
    • XMLWriter::writeRaw — Write a raw XML text
XMLReader::XML
Wstęp
Przetwarzanie XML


Wstęp

This is the XMLWriter extension. It wraps the libxml xmlWriter API.

This extension represents a writer that provides a non-cached, forward-only means of generating streams or files containing XML data.

This extension can be used in an object oriented style or a procedural one. Every method documented describes the alternative procedural call.

XMLWriter
Instalacja/Konfiguracja
XMLWriter


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
XMLWriter


Instalacja

To rozszerzenie jest domyślnie włączone. Może być ono wyłączone za pomocą następującej opcji w czasie kompilacji: --disable-xmlwriter

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

There is one resource used by the procedural version of the XMLWriter extension: returned by xmlwriter_open_memory() or xmlwriter_open_uri().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.

Typy zasobów
XMLWriter Funkcje
XMLWriter


XMLWriter Funkcje

Spis treści

  • XMLWriter::endAttribute — End attribute
  • XMLWriter::endCData — End current CDATA
  • XMLWriter::endComment — Create end comment
  • XMLWriter::endDocument — End current document
  • XMLWriter::endDTDAttlist — End current DTD AttList
  • XMLWriter::endDTDElement — End current DTD element
  • XMLWriter::endDTDEntity — End current DTD Entity
  • XMLWriter::endDTD — End current DTD
  • XMLWriter::endElement — End current element
  • XMLWriter::endPI — End current PI
  • XMLWriter::flush — Flush current buffer
  • XMLWriter::fullEndElement — End current element
  • XMLWriter::openMemory — Create new xmlwriter using memory for string output
  • XMLWriter::openURI — Create new xmlwriter using source uri for output
  • XMLWriter::outputMemory — Returns current buffer
  • XMLWriter::setIndentString — Set string used for indenting
  • XMLWriter::setIndent — Toggle indentation on/off
  • XMLWriter::startAttributeNS — Create start namespaced attribute
  • XMLWriter::startAttribute — Create start attribute
  • XMLWriter::startCData — Create start CDATA tag
  • XMLWriter::startComment — Create start comment
  • XMLWriter::startDocument — Create document tag
  • XMLWriter::startDTDAttlist — Create start DTD AttList
  • XMLWriter::startDTDElement — Create start DTD element
  • XMLWriter::startDTDEntity — Create start DTD Entity
  • XMLWriter::startDTD — Create start DTD tag
  • XMLWriter::startElementNS — Create start namespaced element tag
  • XMLWriter::startElement — Create start element tag
  • XMLWriter::startPI — Create start PI tag
  • XMLWriter::text — Write text
  • XMLWriter::writeAttributeNS — Write full namespaced attribute
  • XMLWriter::writeAttribute — Write full attribute
  • XMLWriter::writeCData — Write full CDATA tag
  • XMLWriter::writeComment — Write full comment tag
  • XMLWriter::writeDTDAttlist — Write full DTD AttList tag
  • XMLWriter::writeDTDElement — Write full DTD element tag
  • XMLWriter::writeDTDEntity — Write full DTD Entity tag
  • XMLWriter::writeDTD — Write full DTD tag
  • XMLWriter::writeElementNS — Write full namespaced element tag
  • XMLWriter::writeElement — Write full element tag
  • XMLWriter::writePI — Writes a PI
  • XMLWriter::writeRaw — Write a raw XML text
Stałe predefiniowane
XMLWriter::endAttribute
XMLWriter


End attribute

XMLWriter Funkcje
XMLWriter::endCData
XMLWriter Funkcje
PHP Manual

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — End attribute

Opis

Styl obiektowy

bool XMLWriter::endAttribute ( void )

Styl proceduralny

bool xmlwriter_end_attribute ( resource $xmlwriter )

Ends the current attribute.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNS() - Create start namespaced attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNS() - Write full namespaced attribute

XMLWriter Funkcje
XMLWriter::endCData
XMLWriter Funkcje


End current CDATA

XMLWriter::endAttribute
XMLWriter::endComment
XMLWriter Funkcje
PHP Manual

XMLWriter::endCData

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endCData -- xmlwriter_end_cdata — End current CDATA

Opis

Styl obiektowy

bool XMLWriter::endCData ( void )

Styl proceduralny

bool xmlwriter_end_cdata ( resource $xmlwriter )

Ends the current CDATA section.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startCData() - Create start CDATA tag
  • XMLWriter::writeCData() - Write full CDATA tag

XMLWriter::endAttribute
XMLWriter::endComment
XMLWriter Funkcje


Create end comment

XMLWriter::endCData
XMLWriter::endDocument
XMLWriter Funkcje
PHP Manual

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Create end comment

Opis

Styl obiektowy

bool XMLWriter::endComment ( void )

Styl proceduralny

bool xmlwriter_end_comment ( resource $xmlwriter )

Ends the current comment.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::writeComment() - Write full comment tag

XMLWriter::endCData
XMLWriter::endDocument
XMLWriter Funkcje


End current document

XMLWriter::endComment
XMLWriter::endDTDAttlist
XMLWriter Funkcje
PHP Manual

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — End current document

Opis

Styl obiektowy

bool XMLWriter::endDocument ( void )

Styl proceduralny

bool xmlwriter_end_document ( resource $xmlwriter )

Ends the current document.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDocument() - Create document tag

XMLWriter::endComment
XMLWriter::endDTDAttlist
XMLWriter Funkcje


End current DTD AttList

XMLWriter::endDocument
XMLWriter::endDTDElement
XMLWriter Funkcje
PHP Manual

XMLWriter::endDTDAttlist

xmlwriter_end_dtd_attlist

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDAttlist -- xmlwriter_end_dtd_attlist — End current DTD AttList

Opis

Styl obiektowy

bool XMLWriter::endDTDAttlist ( void )

Styl proceduralny

bool xmlwriter_end_dtd_attlist ( resource $xmlwriter )

Ends the current DTD attribute list.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDTDAttlist() - Create start DTD AttList
  • XMLWriter::writeDTDAttlist() - Write full DTD AttList tag

XMLWriter::endDocument
XMLWriter::endDTDElement
XMLWriter Funkcje


End current DTD element

XMLWriter::endDTDAttlist
XMLWriter::endDTDEntity
XMLWriter Funkcje
PHP Manual

XMLWriter::endDTDElement

xmlwriter_end_dtd_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDElement -- xmlwriter_end_dtd_element — End current DTD element

Opis

Styl obiektowy

bool XMLWriter::endDTDElement ( void )

Styl proceduralny

bool xmlwriter_end_dtd_element ( resource $xmlwriter )

Ends the current DTD element.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDTDElement() - Create start DTD element
  • XMLWriter::writeDTDElement() - Write full DTD element tag

XMLWriter::endDTDAttlist
XMLWriter::endDTDEntity
XMLWriter Funkcje


End current DTD Entity

XMLWriter::endDTDElement
XMLWriter::endDTD
XMLWriter Funkcje
PHP Manual

XMLWriter::endDTDEntity

xmlwriter_end_dtd_entity

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTDEntity -- xmlwriter_end_dtd_entity — End current DTD Entity

Opis

Styl obiektowy

bool XMLWriter::endDTDEntity ( void )

Styl proceduralny

bool xmlwriter_end_dtd_entity ( resource $xmlwriter )

Ends the current DTD entity.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDTDEntity() - Create start DTD Entity
  • XMLWriter::writeDTDEntity() - Write full DTD Entity tag

XMLWriter::endDTDElement
XMLWriter::endDTD
XMLWriter Funkcje


End current DTD

XMLWriter::endDTDEntity
XMLWriter::endElement
XMLWriter Funkcje
PHP Manual

XMLWriter::endDTD

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endDTD -- xmlwriter_end_dtd — End current DTD

Opis

Styl obiektowy

bool XMLWriter::endDTD ( void )

Styl proceduralny

bool xmlwriter_end_dtd ( resource $xmlwriter )

Ends the DTD of the document.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDTD() - Create start DTD tag
  • XMLWriter::writeDTD() - Write full DTD tag

XMLWriter::endDTDEntity
XMLWriter::endElement
XMLWriter Funkcje


End current element

XMLWriter::endDTD
XMLWriter::endPI
XMLWriter Funkcje
PHP Manual

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — End current element

Opis

Styl obiektowy

bool XMLWriter::endElement ( void )

Styl proceduralny

bool xmlwriter_end_element ( resource $xmlwriter )

Ends the current element.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::writeElement() - Write full element tag

XMLWriter::endDTD
XMLWriter::endPI
XMLWriter Funkcje


End current PI

XMLWriter::endElement
XMLWriter::flush
XMLWriter Funkcje
PHP Manual

XMLWriter::endPI

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::endPI -- xmlwriter_end_pi — End current PI

Opis

Styl obiektowy

bool XMLWriter::endPI ( void )

Styl proceduralny

bool xmlwriter_end_pi ( resource $xmlwriter )

Ends the current processing instruction.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startPI() - Create start PI tag
  • XMLWriter::writePI() - Writes a PI

XMLWriter::endElement
XMLWriter::flush
XMLWriter Funkcje


Flush current buffer

XMLWriter::endPI
XMLWriter::fullEndElement
XMLWriter Funkcje
PHP Manual

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Flush current buffer

Opis

Styl obiektowy

mixed XMLWriter::flush ([ bool $empty = true ] )

Styl proceduralny

mixed xmlwriter_flush ( resource $xmlwriter [, bool $empty = true ] )

Flushes the current buffer.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

empty

Whether to empty the buffer or not. Default is TRUE.

Zwracane wartości

If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes.

XMLWriter::endPI
XMLWriter::fullEndElement
XMLWriter Funkcje


End current element

XMLWriter::flush
XMLWriter::openMemory
XMLWriter Funkcje
PHP Manual

XMLWriter::fullEndElement

xmlwriter_full_end_element

(PHP 5 >= 5.2.0, PECL xmlwriter >= 2.0.4)

XMLWriter::fullEndElement -- xmlwriter_full_end_element — End current element

Opis

Styl obiektowy

bool XMLWriter::fullEndElement ( void )

Styl proceduralny

bool xmlwriter_full_end_element ( resource $xmlwriter )

End the current xml element. Writes an end tag even if the element is empty.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endElement() - End current element

XMLWriter::flush
XMLWriter::openMemory
XMLWriter Funkcje


Create new xmlwriter using memory for string output

XMLWriter::fullEndElement
XMLWriter::openURI
XMLWriter Funkcje
PHP Manual

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Create new xmlwriter using memory for string output

Opis

Styl obiektowy

bool XMLWriter::openMemory ( void )

Styl proceduralny

resource xmlwriter_open_memory ( void )

Creates a new XMLWriter using memory for string output.

Parametry

Zwracane wartości

Styl obiektowy: Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Styl proceduralny: Returns a new xmlwriter zasób for later use with the xmlwriter functions on success, FALSE on error.

Zobacz też:

  • XMLWriter::openURI() - Create new xmlwriter using source uri for output

XMLWriter::fullEndElement
XMLWriter::openURI
XMLWriter Funkcje


Create new xmlwriter using source uri for output

XMLWriter::openMemory
XMLWriter::outputMemory
XMLWriter Funkcje
PHP Manual

XMLWriter::openURI

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::openURI -- xmlwriter_open_uri — Create new xmlwriter using source uri for output

Opis

Styl obiektowy

bool XMLWriter::openURI ( string $uri )

Styl proceduralny

resource xmlwriter_open_uri ( string $uri )

Creates a new XMLWriter using uri for the output.

Parametry

uri

The URI of the resource for the output.

Zwracane wartości

Styl obiektowy: Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Styl proceduralny: Returns a new xmlwriter zasób for later use with the xmlwriter functions on success, FALSE on error.

Zobacz też:

  • XMLWriter::openMemory() - Create new xmlwriter using memory for string output

XMLWriter::openMemory
XMLWriter::outputMemory
XMLWriter Funkcje


Returns current buffer

XMLWriter::openURI
XMLWriter::setIndentString
XMLWriter Funkcje
PHP Manual

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Returns current buffer

Opis

Styl obiektowy

string XMLWriter::outputMemory ([ bool $flush = true ] )

Styl proceduralny

string xmlwriter_output_memory ( resource $xmlwriter [, bool $flush = true ] )

Returns the current buffer.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

flush

Whether to flush the output buffer or not. Default is TRUE.

Zwracane wartości

Returns the current buffer as a string.

Zobacz też:

  • XMLWriter::flush() - Flush current buffer

XMLWriter::openURI
XMLWriter::setIndentString
XMLWriter Funkcje


Set string used for indenting

XMLWriter::outputMemory
XMLWriter::setIndent
XMLWriter Funkcje
PHP Manual

XMLWriter::setIndentString

xmlwriter_set_indent_string

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndentString -- xmlwriter_set_indent_string — Set string used for indenting

Opis

Styl obiektowy

bool XMLWriter::setIndentString ( string $indentString )

Styl proceduralny

bool xmlwriter_set_indent_string ( resource $xmlwriter , string $indentString )

Sets the string which will be used to indent each element/attribute of the resulting xml.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

indentString

The indentation string.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::setIndent() - Toggle indentation on/off

XMLWriter::outputMemory
XMLWriter::setIndent
XMLWriter Funkcje


Toggle indentation on/off

XMLWriter::setIndentString
XMLWriter::startAttributeNS
XMLWriter Funkcje
PHP Manual

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Toggle indentation on/off

Opis

Styl obiektowy

bool XMLWriter::setIndent ( bool $indent )

Styl proceduralny

bool xmlwriter_set_indent ( resource $xmlwriter , bool $indent )

Toggles indentation on or off.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

indent

Whether indentation is enabled.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::setIndentString() - Set string used for indenting

XMLWriter::setIndentString
XMLWriter::startAttributeNS
XMLWriter Funkcje


Create start namespaced attribute

XMLWriter::setIndent
XMLWriter::startAttribute
XMLWriter Funkcje
PHP Manual

XMLWriter::startAttributeNS

xmlwriter_start_attribute_ns

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttributeNS -- xmlwriter_start_attribute_ns — Create start namespaced attribute

Opis

Styl obiektowy

bool XMLWriter::startAttributeNS ( string $prefix , string $name , string $uri )

Styl proceduralny

bool xmlwriter_start_attribute_ns ( resource $xmlwriter , string $prefix , string $name , string $uri )

Starts a namespaced attribute.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

uri

The namespace URI.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNS() - Write full namespaced attribute

XMLWriter::setIndent
XMLWriter::startAttribute
XMLWriter Funkcje


Create start attribute

XMLWriter::startAttributeNS
XMLWriter::startCData
XMLWriter Funkcje
PHP Manual

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Create start attribute

Opis

Styl obiektowy

bool XMLWriter::startAttribute ( string $name )

Styl proceduralny

bool xmlwriter_start_attribute ( resource $xmlwriter , string $name )

Starts an attribute.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The attribute name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startAttributeNS() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNS() - Write full namespaced attribute

XMLWriter::startAttributeNS
XMLWriter::startCData
XMLWriter Funkcje


Create start CDATA tag

XMLWriter::startAttribute
XMLWriter::startComment
XMLWriter Funkcje
PHP Manual

XMLWriter::startCData

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startCData -- xmlwriter_start_cdata — Create start CDATA tag

Opis

Styl obiektowy

bool XMLWriter::startCData ( void )

Styl proceduralny

bool xmlwriter_start_cdata ( resource $xmlwriter )

Starts a CDATA.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endCData() - End current CDATA
  • XMLWriter::writeCData() - Write full CDATA tag

XMLWriter::startAttribute
XMLWriter::startComment
XMLWriter Funkcje


Create start comment

XMLWriter::startCData
XMLWriter::startDocument
XMLWriter Funkcje
PHP Manual

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Create start comment

Opis

Styl obiektowy

bool XMLWriter::startComment ( void )

Styl proceduralny

bool xmlwriter_start_comment ( resource $xmlwriter )

Starts a comment.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endComment() - Create end comment
  • XMLWriter::writeComment() - Write full comment tag

XMLWriter::startCData
XMLWriter::startDocument
XMLWriter Funkcje


Create document tag

XMLWriter::startComment
XMLWriter::startDTDAttlist
XMLWriter Funkcje
PHP Manual

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Create document tag

Opis

Styl obiektowy

bool XMLWriter::startDocument ([ string $version [, string $encoding [, string $standalone ]]] )

Styl proceduralny

bool xmlwriter_start_document ( resource $xmlwriter [, string $version [, string $encoding [, string $standalone = NULL ]]] )

Starts a document.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

version

The version number of the document as part of the XML declaration. Defaults to 1.0.

encoding

The encoding of the document as part of the XML declaration. NULL by default.

standalone

yes or no.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endDocument() - End current document

XMLWriter::startComment
XMLWriter::startDTDAttlist
XMLWriter Funkcje


Create start DTD AttList

XMLWriter::startDocument
XMLWriter::startDTDElement
XMLWriter Funkcje
PHP Manual

XMLWriter::startDTDAttlist

xmlwriter_start_dtd_attlist

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDAttlist -- xmlwriter_start_dtd_attlist — Create start DTD AttList

Opis

Styl obiektowy

bool XMLWriter::startDTDAttlist ( string $name )

Styl proceduralny

bool xmlwriter_start_dtd_attlist ( resource $xmlwriter , string $name )

Starts a DTD attribute list.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The attribute list name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endDTDAttlist() - End current DTD AttList
  • XMLWriter::writeDTDAttlist() - Write full DTD AttList tag

XMLWriter::startDocument
XMLWriter::startDTDElement
XMLWriter Funkcje


Create start DTD element

XMLWriter::startDTDAttlist
XMLWriter::startDTDEntity
XMLWriter Funkcje
PHP Manual

XMLWriter::startDTDElement

xmlwriter_start_dtd_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDElement -- xmlwriter_start_dtd_element — Create start DTD element

Opis

Styl obiektowy

bool XMLWriter::startDTDElement ( string $qualifiedName )

Styl proceduralny

bool xmlwriter_start_dtd_element ( resource $xmlwriter , string $qualifiedName )

Starts a DTD element.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endDTDElement() - End current DTD element
  • XMLWriter::writeDTDElement() - Write full DTD element tag

XMLWriter::startDTDAttlist
XMLWriter::startDTDEntity
XMLWriter Funkcje


Create start DTD Entity

XMLWriter::startDTDElement
XMLWriter::startDTD
XMLWriter Funkcje
PHP Manual

XMLWriter::startDTDEntity

xmlwriter_start_dtd_entity

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTDEntity -- xmlwriter_start_dtd_entity — Create start DTD Entity

Opis

Styl obiektowy

bool XMLWriter::startDTDEntity ( string $name , bool $isparam )

Styl proceduralny

bool xmlwriter_start_dtd_entity ( resource $xmlwriter , string $name , bool $isparam )

Starts a DTD entity.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The name of the entity.

isparam

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endDTDEntity() - End current DTD Entity
  • XMLWriter::writeDTDEntity() - Write full DTD Entity tag

XMLWriter::startDTDElement
XMLWriter::startDTD
XMLWriter Funkcje


Create start DTD tag

XMLWriter::startDTDEntity
XMLWriter::startElementNS
XMLWriter Funkcje
PHP Manual

XMLWriter::startDTD

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startDTD -- xmlwriter_start_dtd — Create start DTD tag

Opis

Styl obiektowy

bool XMLWriter::startDTD ( string $qualifiedName [, string $publicId [, string $systemId ]] )

Styl proceduralny

bool xmlwriter_start_dtd ( resource $xmlwriter , string $qualifiedName [, string $publicId [, string $systemId ]] )

Starts a DTD.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endDTD() - End current DTD
  • XMLWriter::writeDTD() - Write full DTD tag

XMLWriter::startDTDEntity
XMLWriter::startElementNS
XMLWriter Funkcje


Create start namespaced element tag

XMLWriter::startDTD
XMLWriter::startElement
XMLWriter Funkcje
PHP Manual

XMLWriter::startElementNS

xmlwriter_start_element_ns

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startElementNS -- xmlwriter_start_element_ns — Create start namespaced element tag

Opis

Styl obiektowy

bool XMLWriter::startElementNS ( string $prefix , string $name , string $uri )

Styl proceduralny

bool xmlwriter_start_element_ns ( resource $xmlwriter , string $prefix , string $name , string $uri )

Starts a namespaced element.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

prefix

The namespace prefix.

name

The element name.

uri

The namespace URI.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNS() - Write full namespaced element tag

XMLWriter::startDTD
XMLWriter::startElement
XMLWriter Funkcje


Create start element tag

XMLWriter::startElementNS
XMLWriter::startPI
XMLWriter Funkcje
PHP Manual

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Create start element tag

Opis

Styl obiektowy

bool XMLWriter::startElement ( string $name )

Styl proceduralny

bool xmlwriter_start_element ( resource $xmlwriter , string $name )

Starts an element.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The element name.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

XMLWriter::startElementNS
XMLWriter::startPI
XMLWriter Funkcje


Create start PI tag

XMLWriter::startElement
XMLWriter::text
XMLWriter Funkcje
PHP Manual

XMLWriter::startPI

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::startPI -- xmlwriter_start_pi — Create start PI tag

Opis

Styl obiektowy

bool XMLWriter::startPI ( string $target )

Styl proceduralny

bool xmlwriter_start_pi ( resource $xmlwriter , string $target )

Starts a processing instruction tag.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

target

The target of the processing instruction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::endPI() - End current PI
  • XMLWriter::writePI() - Writes a PI

XMLWriter::startElement
XMLWriter::text
XMLWriter Funkcje


Write text

XMLWriter::startPI
XMLWriter::writeAttributeNS
XMLWriter Funkcje
PHP Manual

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Write text

Opis

Styl obiektowy

bool XMLWriter::text ( string $content )

Styl proceduralny

bool xmlwriter_text ( resource $xmlwriter , string $content )

Writes a text.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

content

The contents of the text.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

XMLWriter::startPI
XMLWriter::writeAttributeNS
XMLWriter Funkcje


Write full namespaced attribute

XMLWriter::text
XMLWriter::writeAttribute
XMLWriter Funkcje
PHP Manual

XMLWriter::writeAttributeNS

xmlwriter_write_attribute_ns

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttributeNS -- xmlwriter_write_attribute_ns — Write full namespaced attribute

Opis

Styl obiektowy

bool XMLWriter::writeAttributeNS ( string $prefix , string $name , string $uri , string $content )

Styl proceduralny

bool xmlwriter_write_attribute_ns ( resource $xmlwriter , string $prefix , string $name , string $uri , string $content )

Writes a full namespaced attribute.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

uri

The namespace URI.

content

The attribute value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNS() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

XMLWriter::text
XMLWriter::writeAttribute
XMLWriter Funkcje


Write full attribute

XMLWriter::writeAttributeNS
XMLWriter::writeCData
XMLWriter Funkcje
PHP Manual

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Write full attribute

Opis

Styl obiektowy

bool XMLWriter::writeAttribute ( string $name , string $value )

Styl proceduralny

bool xmlwriter_write_attribute ( resource $xmlwriter , string $name , string $value )

Writes a full attribute.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The name of the attribute.

value

The value of the attribute.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::writeAttributeNS() - Write full namespaced attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNS() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

XMLWriter::writeAttributeNS
XMLWriter::writeCData
XMLWriter Funkcje


Write full CDATA tag

XMLWriter::writeAttribute
XMLWriter::writeComment
XMLWriter Funkcje
PHP Manual

XMLWriter::writeCData

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCData -- xmlwriter_write_cdata — Write full CDATA tag

Opis

Styl obiektowy

bool XMLWriter::writeCData ( string $content )

Styl proceduralny

bool xmlwriter_write_cdata ( resource $xmlwriter , string $content )

Writes a full CDATA.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

content

The contents of the CDATA.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startCData() - Create start CDATA tag
  • XMLWriter::endCData() - End current CDATA

XMLWriter::writeAttribute
XMLWriter::writeComment
XMLWriter Funkcje


Write full comment tag

XMLWriter::writeCData
XMLWriter::writeDTDAttlist
XMLWriter Funkcje
PHP Manual

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Write full comment tag

Opis

Styl obiektowy

bool XMLWriter::writeComment ( string $content )

Styl proceduralny

bool xmlwriter_write_comment ( resource $xmlwriter , string $content )

Writes a full comment.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

content

The contents of the comment.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::endComment() - Create end comment

XMLWriter::writeCData
XMLWriter::writeDTDAttlist
XMLWriter Funkcje


Write full DTD AttList tag

XMLWriter::writeComment
XMLWriter::writeDTDElement
XMLWriter Funkcje
PHP Manual

XMLWriter::writeDTDAttlist

xmlwriter_write_dtd_attlist

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDAttlist -- xmlwriter_write_dtd_attlist — Write full DTD AttList tag

Opis

Styl obiektowy

bool XMLWriter::writeDTDAttlist ( string $name , string $content )

Styl proceduralny

bool xmlwriter_write_dtd_attlist ( resource $xmlwriter , string $name , string $content )

Writes a DTD attribute list.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The name of the DTD attribute list.

content

The content of the DTD attribute list.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDTDAttlist() - Create start DTD AttList
  • XMLWriter::endDTDAttlist() - End current DTD AttList

XMLWriter::writeComment
XMLWriter::writeDTDElement
XMLWriter Funkcje


Write full DTD element tag

XMLWriter::writeDTDAttlist
XMLWriter::writeDTDEntity
XMLWriter Funkcje
PHP Manual

XMLWriter::writeDTDElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDElement -- xmlwriter_write_dtd_element — Write full DTD element tag

Opis

Styl obiektowy

bool XMLWriter::writeDTDElement ( string $name , string $content )

Styl proceduralny

bool xmlwriter_write_dtd_element ( resource $xmlwriter , string $name , string $content )

Writes a full DTD element.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The name of the DTD element.

content

The content of the element.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDTDElement() - Create start DTD element
  • XMLWriter::endDTDElement() - End current DTD element

XMLWriter::writeDTDAttlist
XMLWriter::writeDTDEntity
XMLWriter Funkcje


Write full DTD Entity tag

XMLWriter::writeDTDElement
XMLWriter::writeDTD
XMLWriter Funkcje
PHP Manual

XMLWriter::writeDTDEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTDEntity -- xmlwriter_write_dtd_entity — Write full DTD Entity tag

Opis

Styl obiektowy

bool XMLWriter::writeDTDEntity ( string $name , string $content , bool $pe , string $pubid , string $sysid , string $ndataid )

Styl proceduralny

bool xmlwriter_write_dtd_entity ( resource $xmlwriter , string $name , string $content , bool $pe , string $pubid , string $sysid , string $ndataid )

Writes a full DTD entity.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The name of the entity.

content

The content of the entity.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDTDEntity() - Create start DTD Entity
  • XMLWriter::endDTDEntity() - End current DTD Entity

XMLWriter::writeDTDElement
XMLWriter::writeDTD
XMLWriter Funkcje


Write full DTD tag

XMLWriter::writeDTDEntity
XMLWriter::writeElementNS
XMLWriter Funkcje
PHP Manual

XMLWriter::writeDTD

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDTD -- xmlwriter_write_dtd — Write full DTD tag

Opis

Styl obiektowy

bool XMLWriter::writeDTD ( string $name [, string $publicId [, string $systemId [, string $subset ]]] )

Styl proceduralny

bool xmlwriter_write_dtd ( resource $xmlwriter , string $name [, string $publicId [, string $systemId [, string $subset ]]] )

Writes a full DTD.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The DTD name.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

subset

The content of the DTD.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startDTD() - Create start DTD tag
  • XMLWriter::endDTD() - End current DTD

XMLWriter::writeDTDEntity
XMLWriter::writeElementNS
XMLWriter Funkcje


Write full namespaced element tag

XMLWriter::writeDTD
XMLWriter::writeElement
XMLWriter Funkcje
PHP Manual

XMLWriter::writeElementNS

xmlwriter_write_element_ns

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElementNS -- xmlwriter_write_element_ns — Write full namespaced element tag

Opis

Styl obiektowy

bool XMLWriter::writeElementNS ( string $prefix , string $name , string $uri [, string $content ] )

Styl proceduralny

bool xmlwriter_write_element_ns ( resource $xmlwriter , string $prefix , string $name , string $uri [, string $content ] )

Writes a full namespaced element tag.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

prefix

The namespace prefix.

name

The element name.

uri

The namespace URI.

content

The element contents.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
PHP 5.2.3 | The content parameter became optional.

Zobacz też:

  • XMLWriter::startElementNS() - Create start namespaced element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

XMLWriter::writeDTD
XMLWriter::writeElement
XMLWriter Funkcje


Write full element tag

XMLWriter::writeElementNS
XMLWriter::writePI
XMLWriter Funkcje
PHP Manual

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Write full element tag

Opis

Styl obiektowy

bool XMLWriter::writeElement ( string $name [, string $content ] )

Styl proceduralny

bool xmlwriter_write_element ( resource $xmlwriter , string $name [, string $content ] )

Writes a full element tag.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

name

The element name.

content

The element contents.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja | Opis
PHP 5.2.3 | The content parameter became optional.

Zobacz też:

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNS() - Write full namespaced element tag

XMLWriter::writeElementNS
XMLWriter::writePI
XMLWriter Funkcje


Writes a PI

XMLWriter::writeElement
XMLWriter::writeRaw
XMLWriter Funkcje
PHP Manual

XMLWriter::writePI

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PECL xmlwriter >= 0.1.0)

XMLWriter::writePI -- xmlwriter_write_pi — Writes a PI

Opis

Styl obiektowy

bool XMLWriter::writePI ( string $target , string $content )

Styl proceduralny

bool xmlwriter_write_pi ( resource $xmlwriter , string $target , string $content )

Writes a processing instruction.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

target

The target of the processing instruction.

content

The content of the processing instruction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::startPI() - Create start PI tag
  • XMLWriter::endPI() - End current PI

XMLWriter::writeElement
XMLWriter::writeRaw
XMLWriter Funkcje


Write a raw XML text

XMLWriter::writePI
XSL
XMLWriter Funkcje
PHP Manual

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Write a raw XML text

Opis

Styl obiektowy

bool XMLWriter::writeRaw ( string $content )

Styl proceduralny

bool xmlwriter_write_raw ( resource $xmlwriter , string $content )

Writes a raw xml text.

Parametry

xmlwriter

Jedynie dla wywołań proceduralnych. Zasób XMLWriter, który jest modfikowany. Ten zasób pochodzi, z wywołania funkcji xmlwriter_open_uri() lub xmlwriter_open_memory().

content

The text string to write.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XMLWriter::text() - Write text

XMLWriter::writePI
XSL
XMLWriter Funkcje


XSL

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • Przykłady
    • Example collection.xml and collection.xsl files
  • XSLTProcessor — The XSLTProcessor class
    • XSLTProcessor::__construct — Creates a new XSLTProcessor object
    • XSLTProcessor::getParameter — Get value of a parameter
    • XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
    • XSLTProcessor::importStylesheet — Import stylesheet
    • XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
    • XSLTProcessor::removeParameter — Remove parameter
    • XSLTProcessor::setParameter — Set value for a parameter
    • XSLTProcessor::setProfiling — Sets profiling output file
    • XSLTProcessor::transformToDoc — Transform to a DOMDocument
    • XSLTProcessor::transformToUri — Transform to URI
    • XSLTProcessor::transformToXML — Transform to XML
XMLWriter::writeRaw
Wstęp
Przetwarzanie XML


Wstęp

The XSL extension implements the XSL standard, performing » XSLT transformations using the » libxslt library

XSL
Instalacja/Konfiguracja
XSL


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
XSL


Wymagania

To rozszerzenie wymaga rozszerzenia PHP libxml. To oznacza, że należy podać dyrektywę konfiguracyjną --enable-libxml podczas kompilacji, pomimo tego, że pośrednio jest to spełnione, ponieważ libxml jest domyślnie włączone.

This extension uses libxslt which can be found at » http://xmlsoft.org/XSLT/. libxslt version 1.1.0 or greater is required.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

PHP 5 includes the XSL extension by default and can be enabled by adding the argument --with-xsl[=DIR] to your configure line. DIR is the libxslt installation directory.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


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.

XSL_CLONE_AUTO (integer)
XSL_CLONE_NEVER (integer)
XSL_CLONE_ALWAYS (integer)
LIBXSLT_VERSION (integer)
libxslt version like 10117. Available as of PHP 5.1.2.
LIBXSLT_DOTTED_VERSION (string)
libxslt version like 1.1.17. Available as of PHP 5.1.2.
LIBEXSLT_VERSION (integer)
libexslt version like 813. Available as of PHP 5.1.2.
LIBEXSLT_DOTTED_VERSION (string)
libexslt version like 1.1.17. Available as of PHP 5.1.2.
Typy zasobów
Przykłady
XSL


Przykłady

Spis treści

  • Example collection.xml and collection.xsl files
Stałe predefiniowane
Example collection.xml and collection.xsl files
XSL


Example collection.xml and collection.xsl files

Many examples in this reference require both an XML and an XSL file. We will use collection.xml and collection.xsl that contains the following:

Przykład #1 collection.xml

<collection>
 <cd>
  <title>Fight for your mind</title>
  <artist>Ben Harper</artist>
  <year>1995</year>
 </cd>
 <cd>
  <title>Electric Ladyland</title>
  <artist>Jimi Hendrix</artist>
  <year>1997</year>
 </cd>
</collection>

Przykład #2 collection.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
 <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
 <xsl:template match="collection">
  Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection!
  <xsl:apply-templates/>
 </xsl:template>
 <xsl:template match="cd">
  <h1><xsl:value-of select="title"/></h1>
  <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
  <hr />
 </xsl:template>
</xsl:stylesheet>

Przykłady
XSLTProcessor
Przykłady


The XSLTProcessor class

(No version information available, might only be in SVN)

Wstęp

Krótki opis klasy

XSLTProcessor {
/* Metody */
string getParameter ( string $namespaceURI , string $localName )
bool hasExsltSupport ( void )
void importStylesheet ( object $stylesheet )
void registerPHPFunctions ([ mixed $restrict ] )
bool removeParameter ( string $namespaceURI , string $localName )
bool setParameter ( string $namespace , string $name , string $value )
bool setProfiling ( string $filename )
DOMDocument transformToDoc ( DOMNode $doc )
int transformToURI ( DOMDocument $doc , string $uri )
string transformToXML ( DOMDocument $doc )
}

Spis treści

  • XSLTProcessor::__construct — Creates a new XSLTProcessor object
  • XSLTProcessor::getParameter — Get value of a parameter
  • XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
  • XSLTProcessor::importStylesheet — Import stylesheet
  • XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
  • XSLTProcessor::removeParameter — Remove parameter
  • XSLTProcessor::setParameter — Set value for a parameter
  • XSLTProcessor::setProfiling — Sets profiling output file
  • XSLTProcessor::transformToDoc — Transform to a DOMDocument
  • XSLTProcessor::transformToUri — Transform to URI
  • XSLTProcessor::transformToXML — Transform to XML
Example collection.xml and collection.xsl files
XSLTProcessor::__construct
XSL


Creates a new XSLTProcessor object

XSLTProcessor
XSLTProcessor::getParameter
XSLTProcessor
PHP Manual

XSLTProcessor::__construct

(PHP 5)

XSLTProcessor::__construct — Creates a new XSLTProcessor object

Opis

XSLTProcessor::__construct() ( void )

Creates a new XSLTProcessor object.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Creating an XSLTProcessor

<?php

$doc = new DOMDocument();
$xsl = new XSLTProcessor();

$doc->load($xsl_filename);
$xsl->importStyleSheet($doc);

$doc->load($xml_filename);
echo $xsl->transformToXML($doc);

?>

XSLTProcessor
XSLTProcessor::getParameter
XSLTProcessor


Get value of a parameter

XSLTProcessor::__construct
XSLTProcessor::hasExsltSupport
XSLTProcessor
PHP Manual

XSLTProcessor::getParameter

(PHP 5)

XSLTProcessor::getParameter — Get value of a parameter

Opis

string XSLTProcessor::getParameter ( string $namespaceURI , string $localName )

Gets a parameter if previously set by XSLTProcessor::setParameter().

Parametry

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Zwracane wartości

The value of the parameter or NULL if it's not set.

Zobacz też:

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::removeParameter() - Remove parameter

XSLTProcessor::__construct
XSLTProcessor::hasExsltSupport
XSLTProcessor


Determine if PHP has EXSLT support

XSLTProcessor::getParameter
XSLTProcessor::importStylesheet
XSLTProcessor
PHP Manual

XSLTProcessor::hasExsltSupport

(PHP 5 >= 5.0.4)

XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support

Opis

bool XSLTProcessor::hasExsltSupport ( void )

This method determines if PHP was built with the » EXSLT library.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Testing EXSLT support

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
    die('EXSLT support not available');
}

// do EXSLT stuff here ..

?>

XSLTProcessor::getParameter
XSLTProcessor::importStylesheet
XSLTProcessor


Import stylesheet

XSLTProcessor::hasExsltSupport
XSLTProcessor::registerPHPFunctions
XSLTProcessor
PHP Manual

XSLTProcessor::importStylesheet

(PHP 5)

XSLTProcessor::importStylesheet — Import stylesheet

Opis

void XSLTProcessor::importStylesheet ( object $stylesheet )

This method imports the stylesheet into the XSLTProcessor for transformations.

Parametry

stylesheet

The imported style sheet as a DOMDocument or SimpleXMLElement object.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
5.2.8 | Accepts SimpleXMLElement again which was broken since PHP 5.2.6.

XSLTProcessor::hasExsltSupport
XSLTProcessor::registerPHPFunctions
XSLTProcessor


Enables the ability to use PHP functions as XSLT functions

XSLTProcessor::importStylesheet
XSLTProcessor::removeParameter
XSLTProcessor
PHP Manual

XSLTProcessor::registerPHPFunctions

(PHP 5 >= 5.0.4)

XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions

Opis

void XSLTProcessor::registerPHPFunctions ([ mixed $restrict ] )

This method enables the ability to use PHP functions as XSLT functions within XSL stylesheets.

Parametry

restrict

Use this parameter to only allow certain functions to be called from XSLT.

This parameter can be either a string (a function name) or an array of functions.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Simple PHP Function call from a stylesheet

<?php
$xml = <<<EOB
<allusers>
 <user>
  <uid>bob</uid>
 </user>
 <user>
  <uid>joe</uid>
 </user>
</allusers>
EOB;
$xsl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:php="http://php.net/xsl">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
 <xsl:template match="allusers">
  <html><body>
    <h2>Users</h2>
    <table>
    <xsl:for-each select="user">
      <tr><td>
        <xsl:value-of
             select="php:function('ucfirst',string(uid))"/>
      </td></tr>
    </xsl:for-each>
    </table>
  </body></html>
 </xsl:template>
</xsl:stylesheet>
EOB;
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);

$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
?>

Rejestr zmian

Wersja | Opis
5.1.0 | The restrict parameter was added.

XSLTProcessor::importStylesheet
XSLTProcessor::removeParameter
XSLTProcessor


Remove parameter

XSLTProcessor::registerPHPFunctions
XSLTProcessor::setParameter
XSLTProcessor
PHP Manual

XSLTProcessor::removeParameter

(PHP 5)

XSLTProcessor::removeParameter — Remove parameter

Opis

bool XSLTProcessor::removeParameter ( string $namespaceURI , string $localName )

Removes a parameter, if set. This will make the processor use the default value for the parameter as specified in the stylesheet.

Parametry

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::getParameter() - Get value of a parameter

XSLTProcessor::registerPHPFunctions
XSLTProcessor::setParameter
XSLTProcessor


Set value for a parameter

XSLTProcessor::removeParameter
XSLTProcessor::setProfiling
XSLTProcessor
PHP Manual

XSLTProcessor::setParameter

(PHP 5)

XSLTProcessor::setParameter — Set value for a parameter

Opis

bool XSLTProcessor::setParameter ( string $namespace , string $name , string $value )
bool XSLTProcessor::setParameter ( string $namespace , array $options )

Sets the value of one or more parameters to be used in subsequent transformations with XSLTProcessor. If the parameter doesn't exist in the stylesheet it will be ignored.

Parametry

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

value

The new value of the XSLT parameter.

options

An array of name => value pairs. This syntax is available since PHP 5.1.0.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Changing the owner before the transformation

<?php

$collections = array(
    'Marc Rutkowski' => 'marc',
    'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

foreach ($collections as $name => $file) {
    // Load the XML source
    $xml = new DOMDocument;
    $xml->load('collection_' . $file . '.xml');

    $proc->setParameter('', 'owner', $name);
    $proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

Zobacz też:

  • XSLTProcessor::getParameter() - Get value of a parameter
  • XSLTProcessor::removeParameter() - Remove parameter

XSLTProcessor::removeParameter
XSLTProcessor::setProfiling
XSLTProcessor


Sets profiling output file

XSLTProcessor::setParameter
XSLTProcessor::transformToDoc
XSLTProcessor
PHP Manual

XSLTProcessor::setProfiling

(PHP >= 5.3.0)

XSLTProcessor::setProfiling — Sets profiling output file

Opis

bool XSLTProcessor::setProfiling ( string $filename )

Sets the file to output profiling information when processing a stylesheet.

Parametry

filename

Path to the file to dump profiling information.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Example profiling output

<?php
// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

The above code will produce the following information in the profiling file:

number               match                name      mode  Calls Tot 100us Avg

    0                   cd                                    2      3      1
    1           collection                                    1      1      1

                         Total                                3      4

XSLTProcessor::setParameter
XSLTProcessor::transformToDoc
XSLTProcessor


Transform to a DOMDocument

XSLTProcessor::setProfiling
XSLTProcessor::transformToUri
XSLTProcessor
PHP Manual

XSLTProcessor::transformToDoc

(PHP 5)

XSLTProcessor::transformToDoc — Transform to a DOMDocument

Opis

DOMDocument XSLTProcessor::transformToDoc ( DOMNode $doc )

Transforms the source node to a DOMDocument applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

Parametry

doc

The node to be transformed.

Zwracane wartości

The resulting DOMDocument or FALSE on error.

Przykłady

Przykład #1 Transforming to a DOMDocument

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

Powyższy przykład wyświetli:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

Zobacz też:

  • XSLTProcessor::transformToUri() - Transform to URI
  • XSLTProcessor::transformToXml() - Transform to XML

XSLTProcessor::setProfiling
XSLTProcessor::transformToUri
XSLTProcessor


Transform to URI

XSLTProcessor::transformToDoc
XSLTProcessor::transformToXML
XSLTProcessor
PHP Manual

XSLTProcessor::transformToUri

(PHP 5)

XSLTProcessor::transformToUri — Transform to URI

Opis

int XSLTProcessor::transformToURI ( DOMDocument $doc , string $uri )

Transforms the source node to an URI applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

Parametry

doc

The document to transform.

uri

The target URI for the transformation.

Zwracane wartości

Returns the number of bytes written or FALSE if an error occurred.

Przykłady

Przykład #1 Transforming to a HTML file

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

Zobacz też:

  • XSLTProcessor::transformToDoc() - Transform to a DOMDocument
  • XSLTProcessor::transformToXml() - Transform to XML

XSLTProcessor::transformToDoc
XSLTProcessor::transformToXML
XSLTProcessor


Transform to XML

XSLTProcessor::transformToUri
XSLT (PHP 4)
XSLTProcessor
PHP Manual

XSLTProcessor::transformToXML

(PHP 5)

XSLTProcessor::transformToXML — Transform to XML

Opis

string XSLTProcessor::transformToXML ( DOMDocument $doc )

Transforms the source node to a string applying the stylesheet given by the xsltprocessor::importStylesheet() method.

Parametry

doc

The transformed document.

Zwracane wartości

The result of the transformation as a string or FALSE on error.

Przykłady

Przykład #1 Transforming to a string

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo $proc->transformToXML($xml);

?>

Powyższy przykład wyświetli:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

<h1>Fight for your mind</h1><h2>by Ben Harper - 1995</h2><hr>
<h1>Electric Ladyland</h1><h2>by Jimi Hendrix - 1997</h2><hr>

Zobacz też:

  • XSLTProcessor::transformToDoc() - Transform to a DOMDocument
  • XSLTProcessor::transformToUri() - Transform to URI

XSLTProcessor::transformToUri
XSLT (PHP 4)
XSLTProcessor


XSLT (PHP 4)

  • Wstęp
  • Instalacja/Konfiguracja
    • Wymagania
    • Instalacja
    • Konfiguracja wykonawcza
    • Typy zasobów
  • Stałe predefiniowane
  • XSLT (PHP 4) Funkcje
    • xslt_backend_info — Returns the information on the compilation settings of the backend
    • xslt_backend_name — Returns the name of the backend
    • xslt_backend_version — Returns the version number of Sablotron
    • xslt_create — Create a new XSLT processor
    • xslt_errno — Returns an error number
    • xslt_error — Returns an error string
    • xslt_free — Free XSLT processor
    • xslt_getopt — Get options on a given xsl processor
    • xslt_process — Perform an XSLT transformation
    • xslt_set_base — Set the base URI for all XSLT transformations
    • xslt_set_encoding — Set the encoding for the parsing of XML documents
    • xslt_set_error_handler — Set an error handler for a XSLT processor
    • xslt_set_log — Set the log file to write log messages to
    • xslt_set_object — Sets the object in which to resolve callback functions
    • xslt_set_sax_handler — Set SAX handlers for a XSLT processor
    • xslt_set_sax_handlers — Set the SAX handlers to be called when the XML document gets processed
    • xslt_set_scheme_handler — Set Scheme handlers for a XSLT processor
    • xslt_set_scheme_handlers — Set the scheme handlers for the XSLT processor
    • xslt_setopt — Set options on a given XSLT processor
XSLTProcessor::transformToXML
Wstęp
Przetwarzanie XML


Wstęp

This PHP extension provides a processor independent API to XSLT transformations. Currently this extension only supports the Sablotron library from the Ginger Alliance. Support is planned for other libraries, such as the Xalan library or the libxslt library.

XSLT (Extensible Stylesheet Language (XSL) Transformations) is a language for transforming XML documents into other XML documents. It is a standard defined by The World Wide Web Consortium (W3C). Information about XSLT and related technologies can be found at » http://www.w3.org/TR/xslt.

Informacja: This extension is different than the sablotron extension distributed with versions of PHP prior to PHP 4.1.0, currently only the new XSLT extension in PHP 4.1.0 is supported. If you need support for the old extension, please ask your questions on the PHP mailing lists.

Informacja:

To rozszerzenie zostało przeniesione do repozytorium » PECL i nie jest rozprowadzane z PHP od wersji 5.0.0.

Informacja: If you need xslt support with PHP 5 you can use the XSL extension.

XSLT (PHP 4)
Instalacja/Konfiguracja
XSLT (PHP 4)


Instalacja/Konfiguracja

Spis treści

  • Wymagania
  • Instalacja
  • Konfiguracja wykonawcza
  • Typy zasobów
Wstęp
Wymagania
XSLT (PHP 4)


Wymagania

To rozszerzenie wymaga rozszerzenia PHP libxml. To oznacza, że należy podać dyrektywę konfiguracyjną --enable-libxml podczas kompilacji, pomimo tego, że pośrednio jest to spełnione, ponieważ libxml jest domyślnie włączone.

This extension uses Sablotron and expat, which can both be found at » http://freshmeat.net/projects/sablotron/. Binaries are provided as well as source.

Enable by using the --with-xslt option with PHP 4.

Instalacja/Konfiguracja
Instalacja
Instalacja/Konfiguracja


Instalacja

On Unix, run configure with the --enable-xslt --with-xslt-sablot options. The Sablotron library should be installed somewhere your compiler can find it.

Make sure you have the same libraries linked to the Sablotron library as those, which are linked with PHP. The configuration options: --with-expat-dir=DIR --with-iconv-dir=DIR are there to help you specify them. When asking for support, always mention these directives, and whether there are other versions of those libraries installed on your system somewhere. Naturally, provide all the version numbers.

Uwaga

Be sure your Sablotron library is linked to -lstdc++ as otherwise your configure will fail, or PHP will fail to run or load.

Informacja: JavaScript E-XSLT support
If you compiled Sablotron with JavaScript support, you must specify the option: --with-sablot-js=DIR .

Informacja: Note to Win32 Users

Aby poprawnie działało rozszerzenie, pliki DLL muszą znajdować się w miejscu wskazanym przez PATH systemu Windows. Aby uzyskać więcej informacji zobacz FAQ zatytułowane "Jak mam dodać mój katalog PHP do PATH w Windows". Chociaż skopiowanie plików DLL z folderu PHP do systemowego katalogu Windows także zadziała (ponieważ katalog systemowy jest domyślnie w PATH systemu), ale nie jest to wymagane. To rozszerzenie wymaga następujących plików znajdujących się w PATH: sablot.dll, expat.dll, and iconv.dll

For PHP <= 4.2.0, the file iconv.dll is not required.

Wymagania
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Typy zasobów

This extension defines a XSLT processor resource returned by xslt_create().

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

XSLT_OPT_SILENT (integer)
Drop all logging and error reporting. This is a generic option for all backends that may be added in the future.
XSLT_SABOPT_PARSE_PUBLIC_ENTITIES (integer)

Tell Sablotron to parse public entities. By default this has been turned off.

XSLT_SABOPT_DISABLE_ADDING_META (integer)

Do not add the meta tag "Content-Type" for HTML output. The default is set during compilation of Sablotron.

XSLT_SABOPT_DISABLE_STRIPPING (integer)
Suppress the whitespace stripping (on data files only).
XSLT_SABOPT_IGNORE_DOC_NOT_FOUND (integer)
Consider unresolved documents (the document() function) non-lethal.
XSLT_SABOPT_FILES_TO_HANDLER (integer)
XSLT_ERR_UNSUPPORTED_SCHEME (integer)
Error return code, for scheme handlers.
Typy zasobów
XSLT (PHP 4) Funkcje
XSLT (PHP 4)


XSLT (PHP 4) Funkcje

Spis treści

  • xslt_backend_info — Returns the information on the compilation settings of the backend
  • xslt_backend_name — Returns the name of the backend
  • xslt_backend_version — Returns the version number of Sablotron
  • xslt_create — Create a new XSLT processor
  • xslt_errno — Returns an error number
  • xslt_error — Returns an error string
  • xslt_free — Free XSLT processor
  • xslt_getopt — Get options on a given xsl processor
  • xslt_process — Perform an XSLT transformation
  • xslt_set_base — Set the base URI for all XSLT transformations
  • xslt_set_encoding — Set the encoding for the parsing of XML documents
  • xslt_set_error_handler — Set an error handler for a XSLT processor
  • xslt_set_log — Set the log file to write log messages to
  • xslt_set_object — Sets the object in which to resolve callback functions
  • xslt_set_sax_handler — Set SAX handlers for a XSLT processor
  • xslt_set_sax_handlers — Set the SAX handlers to be called when the XML document gets processed
  • xslt_set_scheme_handler — Set Scheme handlers for a XSLT processor
  • xslt_set_scheme_handlers — Set the scheme handlers for the XSLT processor
  • xslt_setopt — Set options on a given XSLT processor
Stałe predefiniowane
xslt_backend_info
XSLT (PHP 4)


Returns the information on the compilation settings of the backend

XSLT (PHP 4) Funkcje
xslt_backend_name
XSLT (PHP 4) Funkcje
PHP Manual

xslt_backend_info

(PHP 4 >= 4.3.0)

xslt_backend_info — Returns the information on the compilation settings of the backend

Opis

string xslt_backend_info ( void )

xslt_backend_info() gets information about the compilation settings of the backend.

Zwracane wartości

Returns a string with information about the compilation setting of the backend or an error string when no information available.

Zobacz też:

  • xslt_backend_name() - Returns the name of the backend
  • xslt_backend_version() - Returns the version number of Sablotron

XSLT (PHP 4) Funkcje
xslt_backend_name
XSLT (PHP 4) Funkcje


Returns the name of the backend

xslt_backend_info
xslt_backend_version
XSLT (PHP 4) Funkcje
PHP Manual

xslt_backend_name

(PHP 4 >= 4.3.0)

xslt_backend_name — Returns the name of the backend

Opis

string xslt_backend_name ( void )

xslt_backend_name() gets the name of the backend.

Zwracane wartości

Returns Sablotron.

Przykłady

Przykład #1 xslt_backend_name() example

<?php

echo xslt_backend_name(); // Sablotron

?>

Zobacz też:

  • xslt_backend_info() - Returns the information on the compilation settings of the backend
  • xslt_backend_version() - Returns the version number of Sablotron

xslt_backend_info
xslt_backend_version
XSLT (PHP 4) Funkcje


Returns the version number of Sablotron

xslt_backend_name
xslt_create
XSLT (PHP 4) Funkcje
PHP Manual

xslt_backend_version

(PHP 4 >= 4.3.0)

xslt_backend_version — Returns the version number of Sablotron

Opis

string xslt_backend_version ( void )

xslt_backend_version() gets the version number of Sablotron.

Zwracane wartości

Returns the version number, or FALSE if not available.

Przykłady

Przykład #1 xslt_backend_version() example

<?php

echo xslt_backend_version(); // 0.98 for example

?>

Zobacz też:

  • xslt_backend_info() - Returns the information on the compilation settings of the backend
  • xslt_backend_name() - Returns the name of the backend

xslt_backend_name
xslt_create
XSLT (PHP 4) Funkcje


Create a new XSLT processor

xslt_backend_version
xslt_errno
XSLT (PHP 4) Funkcje
PHP Manual

xslt_create

(PHP 4 >= 4.0.3)

xslt_create — Create a new XSLT processor

Opis

resource xslt_create ( void )

Create and return a new XSLT processor resource for manipulation by the other XSLT functions.

Zwracane wartości

Returns an XSLT processor link identifier on success, or FALSE on error.

Przykłady

Przykład #1 xslt_create() example

<?php
function xml2html($xmldata, $xsl)
{
    /* $xmldata -> your XML */
    /* $xsl -> XSLT file */

    $path = 'include';
    $arguments = array('/_xml' => $xmldata);
    $xsltproc = xslt_create();
    xslt_set_encoding($xsltproc, 'ISO-8859-1');
    $html =
        xslt_process($xsltproc, 'arg:/_xml', "$path/$xsl", NULL, $arguments);

    if (empty($html)) {
       die('XSLT processing error: '. xslt_error($xsltproc));
    }
    xslt_free($xsltproc);
    return $html;
}
?>

Zobacz też:

  • xslt_free() - Free XSLT processor

xslt_backend_version
xslt_errno
XSLT (PHP 4) Funkcje


Returns an error number

xslt_create
xslt_error
XSLT (PHP 4) Funkcje
PHP Manual

xslt_errno

(PHP 4 >= 4.0.3)

xslt_errno — Returns an error number

Opis

int xslt_errno ( resource $xh )

Returns an error code describing the last error that occurred on the passed XSLT processor.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

Zwracane wartości

Returns the error code, as an integer.

Zobacz też:

  • xslt_error() - Returns an error string

xslt_create
xslt_error
XSLT (PHP 4) Funkcje


Returns an error string

xslt_errno
xslt_free
XSLT (PHP 4) Funkcje
PHP Manual

xslt_error

(PHP 4 >= 4.0.3)

xslt_error — Returns an error string

Opis

string xslt_error ( resource $xh )

Returns a string describing the last error that occurred on the passed XSLT processor.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

Zwracane wartości

Returns the error message, as a string.

Przykłady

Przykład #1 Handling errors using the xslt_error() and xslt_errno() functions.

<?php

$xh = xslt_create();
$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
if (!$result) {
    die(sprintf("Cannot process XSLT document [%d]: %s",
                xslt_errno($xh), xslt_error($xh)));
}

echo $result;

xslt_free($xh);
?>

Zobacz też:

  • xslt_errno() - Returns an error number

xslt_errno
xslt_free
XSLT (PHP 4) Funkcje


Free XSLT processor

xslt_error
xslt_getopt
XSLT (PHP 4) Funkcje
PHP Manual

xslt_free

(PHP 4 >= 4.0.3)

xslt_free — Free XSLT processor

Opis

void xslt_free ( resource $xh )

Free the XSLT processor identified by the given handle.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:

  • xslt_create() - Create a new XSLT processor

xslt_error
xslt_getopt
XSLT (PHP 4) Funkcje


Get options on a given xsl processor

xslt_free
xslt_process
XSLT (PHP 4) Funkcje
PHP Manual

xslt_getopt

(PHP 4 >= 4.3.0)

xslt_getopt — Get options on a given xsl processor

Opis

int xslt_getopt ( resource $processor )

xslt_getopt() returns the options on the given processor.

Parametry

processor

The XSLT processor link identifier, created with xslt_create().

Zwracane wartości

Returns the options, a bitmask constructed with the XSLT_SABOPT_XXX constants.

Zobacz też:

  • xslt_setopt() - Set options on a given XSLT processor

xslt_free
xslt_process
XSLT (PHP 4) Funkcje


Perform an XSLT transformation

xslt_getopt
xslt_set_base
XSLT (PHP 4) Funkcje
PHP Manual

xslt_process

(PHP 4 >= 4.0.3)

xslt_process — Perform an XSLT transformation

Opis

mixed xslt_process ( resource $xh , string $xmlcontainer , string $xslcontainer [, string $resultcontainer [, array $arguments [, array $parameters ]]] )

The xslt_process() function is the crux of the XSLT extension. It allows you to perform an XSLT transformation using almost any type of input source - the containers. This is accomplished through the use of argument buffers -- a concept taken from the Sablotron XSLT processor (currently the only XSLT processor this extension supports). The input containers default to a filename 'containing' the document to be processed.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

xmlcontainer

Path to XML file or placeholder for the XML argument.

xslcontainer

Path to XSL file or placeholder for the XML argument.

resultcontainer

The result container defaults to a filename for the transformed document. If the result container is not specified - i.e. NULL - than the result is returned.

arguments

Instead of files as the XML and XSLT arguments to the xslt_process() function, you can specify "argument place holders" which are then substituted by values given in the arguments array.

parameters

An array for any top-level parameters that will be passed to the XSLT document. These parameters can then be accessed within your XSL files using the <xsl:param name="parameter_name"> instruction. The parameters must be UTF-8 encoded and their values will be interpreted as strings by the Sablotron processor. In other words - you cannot pass node-sets as parameters to the XSLT document.

Containers can also be set via the arguments array (see below).

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. If the result container is not specified - i.e. NULL - than the result is returned.

Rejestr zmian

Wersja | Opis
4.0.6 | This function no longer takes XML strings in xmlcontainer or xslcontainer. Passing a string containing XML to either of these parameters will result in a segmentation fault in Sablotron versions up to and including version 0.95.

Przykłady

The simplest type of transformation with the xslt_process() function is the transformation of an XML file with an XSLT file, placing the result in a third file containing the new XML (or HTML) document. Doing this with Sablotron is really quite easy...

Przykład #1 Using the xslt_process() to transform an XML file and a XSL file to a new XML file

<?php

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document
if (xslt_process($xh, 'sample.xml', 'sample.xsl', 'result.xml')) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into result.xml";
    echo ", result.xml has the following contents\n<br />\n";
    echo "<pre>\n";
    readfile('result.xml');
    echo "</pre>\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  result.xml the reason is that " . xslt_error($xh) . " and the ";
    echo "error code is " . xslt_errno($xh);
}

xslt_free($xh);

?>

While this functionality is great, many times, especially in a web environment, you want to be able to print out your results directly. Therefore, if you omit the third argument to the xslt_process() function (or provide a NULL value for the argument), it will automatically return the value of the XSLT transformation, instead of writing it to a file...

Przykład #2 Using the xslt_process() to transform an XML file and a XSL file to a variable containing the resulting XML data

<?php

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document, returning the result into the $result variable
$result = xslt_process($xh, 'sample.xml', 'sample.xsl');
if ($result) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    echo " variable, the \$result variable has the following contents\n<br />\n";
    echo "<pre>\n";
    echo $result;
    echo "</pre>\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  the \$result variable the reason is that " . xslt_error($xh);
    echo " and the error code is " . xslt_errno($xh);
}

xslt_free($xh);

?>

The above two cases are the two simplest cases there are when it comes to XSLT transformation and I'd dare say that they are the most common cases, however, sometimes you get your XML and XSLT code from external sources, such as a database or a socket. In these cases you'll have the XML and/or XSLT data in a variable -- and in production applications the overhead of dumping these to file may be too much. This is where XSLT's "argument" syntax, comes to the rescue. Instead of files as the XML and XSLT arguments to the xslt_process() function, you can specify "argument place holders" which are then substituted by values given in the arguments array (5th parameter to the xslt_process() function). The following is an example of processing XML and XSLT into a result variable without the use of files at all.

Przykład #3 Using the xslt_process() to transform a variable containing XML data and a variable containing XSL data into a variable containing the resulting XML data

<?php
// $xml and $xsl contain the XML and XSL data

$arguments = array(
     '/_xml' => $xml,
     '/_xsl' => $xsl
);

// Allocate a new XSLT processor
$xh = xslt_create();

// Process the document
$result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments);
if ($result) {
    echo "SUCCESS, sample.xml was transformed by sample.xsl into the \$result";
    echo " variable, the \$result variable has the following contents\n<br />\n";
    echo "<pre>\n";
    echo $result;
    echo "</pre>\n";
} else {
    echo "Sorry, sample.xml could not be transformed by sample.xsl into";
    echo "  the \$result variable the reason is that " . xslt_error($xh);
    echo " and the error code is " . xslt_errno($xh);
}
xslt_free($xh);
?>

Przykład #4 Passing PHP variables to XSL files

<?php

// XML string
$xml = '<?xml version="1.0"?>
<para>
 change me
</para>';

// XSL string
$xsl = '
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="ISO-8859-1" indent="no"
 omit-xml-declaration="yes"  media-type="text/html"/>
 <xsl:param name="myvar"/>
 <xsl:param name="mynode"/>
 <xsl:template match="/">
My PHP variable : <xsl:value-of select="$myvar"/><br />
My node set : <xsl:value-of select="$mynode"/>
 </xsl:template>
</xsl:stylesheet>';

$xh = xslt_create();

// the second parameter will be interpreted as a string
$parameters = array (
  'myvar' => 'test',
  'mynode' => '<foo>bar</foo>'
);

$arguments = array (
  '/_xml' => $xml,
  '/_xsl' => $xsl
);

echo xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments, $parameters);

?>

Powyższy przykład wyświetli:

My PHP variable : test<br>
My node set : &lt;foo&gt;bar&lt;/foo&gt;

Notatki

Informacja:

Zauważ, że należy podać file:// na początku ścieżki przy pracy pod systemem Windows.

xslt_getopt
xslt_set_base
XSLT (PHP 4) Funkcje


Set the base URI for all XSLT transformations

xslt_process
xslt_set_encoding
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_base

(PHP 4 >= 4.0.5)

xslt_set_base — Set the base URI for all XSLT transformations

Opis

void xslt_set_base ( resource $xh , string $uri )

Sets the base URI for all XSLT transformations, the base URI is used with Xpath instructions to resolve document() and other commands which access external resources. It is also used to resolve URIs for the <xsl:include> and <xsl:import> elements.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

uri

The base URI to be used.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja | Opis
4.3.0 | As of PHP 4.3.0, the default base URI is the directory of the executing script. In effect, it is the directory name value of the __FILE__ constant. The default base URI is less predictable with older versions.

Notatki

Informacja:

Zauważ, że należy podać file:// na początku ścieżki przy pracy pod systemem Windows.

xslt_process
xslt_set_encoding
XSLT (PHP 4) Funkcje


Set the encoding for the parsing of XML documents

xslt_set_base
xslt_set_error_handler
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_encoding

(PHP 4 >= 4.0.5)

xslt_set_encoding — Set the encoding for the parsing of XML documents

Opis

void xslt_set_encoding ( resource $xh , string $encoding )

Set the output encoding for the XSLT transformations. When using the Sablotron backend, this option is only available when you compile Sablotron with encoding support.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

encoding

An output encoding, e.g iso-8859-1.

Zwracane wartości

Nie jest zwracana żadna wartość.

xslt_set_base
xslt_set_error_handler
XSLT (PHP 4) Funkcje


Set an error handler for a XSLT processor

xslt_set_encoding
xslt_set_log
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_error_handler

(PHP 4 >= 4.0.4)

xslt_set_error_handler — Set an error handler for a XSLT processor

Opis

void xslt_set_error_handler ( resource $xh , mixed $handler )

Set an error handler function for the XSLT processor given by xh, this function will be called whenever an error occurs in the XSLT transformation (this function is also called for notices).

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

handler

The user function needs to accept four parameters: the XSLT processor, the error level, the error code and an array of messages. The function can be shown as:

error_handler ( resource $xh , int $error_level , int $error_code , array $messages )

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 xslt_set_error_handler() Example

<?php

// Our XSLT error handler
function xslt_error_handler($handler, $errno, $level, $info)
{
  // for now, let's just see the arguments
  var_dump(func_get_args());
}

// XML content :
$xml='<?xml version="1.0"?>
<para>
 oops, I misspelled the closing tag
</pata>';

// XSL content :
$xsl='<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
   <strong><xsl:value-of select="para"/></strong>
</xsl:template>
</xsl:stylesheet>';

$xh = xslt_create();

xslt_set_error_handler($xh, "xslt_error_handler");

echo xslt_process($xh, 'arg:/_xml', 'arg:/_xsl',
                  NULL, array("/_xml" => $xml, "/_xsl" => $xsl));

?>

Powyższy przykład wyświetli coś podobnego do:

array(4) {
  [0]=>
  resource(1) of type (XSLT Processor)
  [1]=>
  int(3)
  [2]=>
  int(0)
  [3]=>
  array(6) {
    ["msgtype"]=>
    string(5) "error"
    ["code"]=>
    string(1) "2"
    ["module"]=>
    string(9) "Sablotron"
    ["URI"]=>
    string(9) "arg:/_xml"
    ["line"]=>
    string(1) "4"
    ["msg"]=>
    string(34) "XML parser error 7: mismatched tag"
  }
}

Zobacz też:

  • xslt_set_object() - Sets the object in which to resolve callback functions if you want to use an object method as handler

xslt_set_encoding
xslt_set_log
XSLT (PHP 4) Funkcje


Set the log file to write log messages to

xslt_set_error_handler
xslt_set_object
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_log

(PHP 4 >= 4.0.6)

xslt_set_log — Set the log file to write log messages to

Opis

void xslt_set_log ( resource $xh [, mixed $log ] )

This function allows you to set the file in which you want XSLT log messages to, XSLT log messages are different than error messages, in that log messages are not actually error messages but rather messages related to the state of the XSLT processor. They are useful for debugging XSLT, when something goes wrong.

By default logging is disabled, in order to enable logging you must first call xslt_set_log() with a boolean parameter which enables logging, then if you want to set the log file to debug to, you must then pass it a string containing the filename.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

log

This parameter is either a boolean value which toggles logging on and off, or a string containing the logfile in which log errors too.

Zwracane wartości

Nie jest zwracana żadna wartość.

Notatki

Informacja:

Zauważ, że należy podać file:// na początku ścieżki przy pracy pod systemem Windows.

Przykłady

Przykład #1 Using the XSLT Logging features

<?php

$xh = xslt_create();
xslt_set_log($xh, true);
xslt_set_log($xh, getcwd() . '/myfile.log');

$result = xslt_process($xh, 'dog.xml', 'pets.xsl');
echo $result;

xslt_free($xh);
?>

xslt_set_error_handler
xslt_set_object
XSLT (PHP 4) Funkcje


Sets the object in which to resolve callback functions

xslt_set_log
xslt_set_sax_handler
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_object

(PHP 4 >= 4.3.0)

xslt_set_object — Sets the object in which to resolve callback functions

Opis

bool xslt_set_object ( resource $processor , object &$obj )

This function allows to use the processor inside an object and to resolve all callback functions in it.

The callback functions can be declared with xslt_set_sax_handlers(), xslt_set_scheme_handlers() or xslt_set_error_handler() and are assumed to be methods of object.

Parametry

processor

The XSLT processor link identifier, created with xslt_create().

obj

An object.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using your own error handler as a method

<?php

class my_xslt_processor {

    var $_xh; // our XSLT processor

    function my_xslt_processor()
    {
        $this->_xh = xslt_create();

        // Make $this object the callback resolver
        xslt_set_object($this->_xh, $this);

        // Let's handle the errors
        xslt_set_error_handler($this->_xh, "my_xslt_error_handler");
    }

    function my_xslt_error_handler($handler, $errno, $level, $info)
    {
        // for now, let's just see the arguments
        var_dump(func_get_args());
    }
}

?>
xslt_set_log
xslt_set_sax_handler
XSLT (PHP 4) Funkcje


Set SAX handlers for a XSLT processor

xslt_set_object
xslt_set_sax_handlers
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_sax_handler

(PHP 4 >= 4.0.3)

xslt_set_sax_handler — Set SAX handlers for a XSLT processor

Opis

void xslt_set_sax_handler ( resource $xh , array $handlers )

Set SAX handlers on the resource handle given by xh.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

handlers

SAX handlers should be a two dimensional array with the format (all top level elements are optional):

array(
[document] =>
    array(
        start document handler,
        end document handler
    ),
[element] =>
    array(
        start element handler,
        end element handler
    ),
[namespace] =>
    array(
        start namespace handler,
        end namespace handler
    ),
[comment] => comment handler,
[pi] => processing instruction handler,
[character] => character data handler
)

Zwracane wartości

Nie jest zwracana żadna wartość.

xslt_set_object
xslt_set_sax_handlers
XSLT (PHP 4) Funkcje


Set the SAX handlers to be called when the XML document gets processed

xslt_set_sax_handler
xslt_set_scheme_handler
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_sax_handlers

(PHP 4 >= 4.0.6)

xslt_set_sax_handlers — Set the SAX handlers to be called when the XML document gets processed

Opis

void xslt_set_sax_handlers ( resource $processor , array $handlers )

xslt_set_sax_handlers() registers the SAX handlers for the document, given a XSLT processor resource.

Using xslt_set_sax_handlers() doesn't look very different than running a SAX parser like xml_parse() on the result of an xslt_process() transformation.

Parametry

processor

The XSLT processor link identifier, created with xslt_create().

handlers

handlers should be an array in the following format:

<?php

$handlers = array(

  "document" => array(
    "start_doc",
    "end_doc"),

  "element"  => array(
    "start_element",
    "end_element"),

  "namespace" => array(
    "start_namespace",
    "end_namespace"),

  "comment"   => "comment",

  "pi"        => "pi",

  "character" => "characters"

);
?>
Where the functions follow the syntax described for the scheme handler functions.

Informacja:

The given array does not need to contain all of the different sax handler elements (although it can), but it only needs to conform to "handler" => "function" format described above.

Each of the individual SAX handler functions are in the format below:

  • start_doc ( resource $processor )

  • end_doc ( resource $processor )

  • start_element ( resource $processor , string $name , array $attributes )

  • end_element ( resource $processor , string $name )

  • start_namespace ( resource $processor , string $prefix , string $uri )

  • end_namespace ( resource $processor , string $prefix )

  • comment ( resource $processor , string $contents )

  • pi ( resource $processor , string $target , string $contents )

  • characters ( resource $processor , string $contents )

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 xslt_set_sax_handlers() Example

<?php
// From ohlesbeauxjours at yahoo dot fr
// Here's a simple example that applies strtoupper() on
// the content of every <auteur> tag and then displays the
// resulting XML tree:

$xml='<?xml version="1.0"?>
<books>
 <book>
  <title>Mme Bovary</title>
  <author>Gustave Flaubert</author>
 </book>
 <book>
  <title>Mrs Dalloway</title>
  <author>Virginia Woolf</author>
 </book>
</books>';

$xsl='<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="ISO-8859-1" indent="no" omit-xml-declaration="yes"/>
<xsl:template match="/">
 <xsl:for-each select="books/book">
  <livre>
   <auteur><xsl:value-of select="author/text()"/></auteur>
  </livre>
 </xsl:for-each>
</xsl:template>
</xsl:stylesheet>';

// Handlers :
function start_document()
{
  // start reading the document
}

function end_document()
{
  // end reading the document
}

function start_element($parser, $name, $attributes)
{
  global $result,$tag;
  $result .= "<". $name . ">";
  $tag = $name;
}

function end_element($parser, $name)
{
  global $result;
  $result .= "</" . $name . ">";
}

function characters($parser, $data)
{
  global $result,$tag;
  if ($tag == "auteur" ) {
    $data = strtoupper($data);
  }
  $result .= $data;
}

// Transformation :
$xh = xslt_create();
$handlers = array("document" => array("start_document","end_document"),
   "element" => array("start_element","end_element"),
   "character" => "characters");

xslt_set_sax_handlers($xh, $handlers);
xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, array("/_xml"=>$xml, "/_xsl"=>$xsl));
xslt_free($xh);
?>

You can also use xslt_set_object() if you want to implement your handlers in an object.

Przykład #2 Object oriented handler

<?php
// This is the object oriented version of the previous example
class data_sax_handler {

  var $buffer, $tag, $attrs;

  var $_xh;

  function data_sax_handler($xml, $xsl)
  {
      // our xslt resource
      $this->_xh = xslt_create();

      xslt_set_object($this->_xs, $this);

      // configure sax handlers
      $handlers = array(
        "document" => array('start_document', 'end_document'),
        "element" => array('start_element', 'end_element'),
        "character" => 'characters'
      );

      xslt_set_sax_handlers($this->_xh, $handlers);

      xslt_process($this->_xh, 'arg:/_xml', 'arg:/_xsl', NULL, array("/_xml"=>$xml, "/_xsl"=>$xsl));
      xslt_free($this->_xh);

  }

  function start_document()
  {
        // start reading the document
  }

  function end_document() {
        // complete reading the document
  }

  function start_element($parser, $name, $attributes) {
        $this->tag = $name;
        $this->buffer .= "<" . $name . ">";
        $this->attrs = $attributes;
  }

  function end_element($parser, $name)
  {
        $this->tag = '';
        $this->buffer .= "</" . $name . ">";
  }

  function characters($parser, $data)
  {
    if ($this->tag == 'auteur') {
          $data = strtoupper($data);
    }
    $this->buffer .= $data;
  }

  function get_buffer() {
    return $this->buffer;
  }

}

$exec = new data_sax_handler($xml, $xsl);

?>

Both examples will output:

<livre>
   <auteur>GUSTAVE FLAUBERT</auteur>
</livre>
<livre>
   <auteur>VIRGINIA WOOLF</auteur>
</livre>
xslt_set_sax_handler
xslt_set_scheme_handler
XSLT (PHP 4) Funkcje


Set Scheme handlers for a XSLT processor

xslt_set_sax_handlers
xslt_set_scheme_handlers
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_scheme_handler

(PHP 4 >= 4.0.5)

xslt_set_scheme_handler — Set Scheme handlers for a XSLT processor

Opis

void xslt_set_scheme_handler ( resource $xh , array $handlers )

Set Scheme handlers on the resource handle given by xh.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

handlers

Scheme handlers should be an array with the format (all elements are optional):

array(
[get_all] => get all handler,
[open] => open handler,
[get] => get handler,
[put] => put handler,
[close] => close handler
)

Zwracane wartości

Nie jest zwracana żadna wartość.

xslt_set_sax_handlers
xslt_set_scheme_handlers
XSLT (PHP 4) Funkcje


Set the scheme handlers for the XSLT processor

xslt_set_scheme_handler
xslt_setopt
XSLT (PHP 4) Funkcje
PHP Manual

xslt_set_scheme_handlers

(PHP 4 >= 4.0.6)

xslt_set_scheme_handlers — Set the scheme handlers for the XSLT processor

Opis

void xslt_set_scheme_handlers ( resource $xh , array $handlers )

Registers the scheme handlers (XPath handlers) for the document.

Parametry

xh

The XSLT processor link identifier, created with xslt_create().

handlers

An array with the following keys: "get_all", "open", "get", "put", and "close".

Every entry must be a function name or an array in the following format: array($obj, "method").

Note that the given array does not need to contain all of the different scheme handler elements (although it can), but it only needs to conform to the "handler" => "fonction" format described above.

Each of the individual scheme handler functions called are in the formats below:

string   get_all(resource processor, string scheme, string rest)
resource open(resource processor, string scheme, string rest)
int      get(resource processor, resource fp, string &data)
int      put(resource processor, resource fp, string data)
void     close(resource processor, resource fp)

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 xslt_set_scheme_handlers() example

For example, here is an implementation of the "file_exists()" PHP function.

<?php

// Definition of the handler
function mySchemeHandler($processor, $scheme, $rest)
{
    $rest = substr($rest,1);    // to remove the first / automatically added by the engine
    if ($scheme == 'file_exists') {
        // result is embedded in a small xml string
        return '<?xml version="1.0" encoding="UTF-8"?><root>' . (file_exists($rest) ? 'true' : 'false') . '</root>';
    }
}

$SchemeHandlerArray = array('get_all' => 'mySchemeHandler');

// Start the engine
$params = array();
$xh = xslt_create();

xslt_set_scheme_handlers($xh, $SchemeHandlerArray);

$result = xslt_process($xh, "myFile.xml", "myFile.xsl", NULL, array(), $params);
xslt_free($xh);

echo $result;

?>

Then, inside the stylesheet, you can test whether a certain file exists with:

<xsl:if test="document('file_exists:anotherXMLfile.xml')/root='true'">
 <!-- The file exist -->
</xsl:if>

Zobacz też:

  • xslt_set_scheme_handler() - Set Scheme handlers for a XSLT processor

xslt_set_scheme_handler
xslt_setopt
XSLT (PHP 4) Funkcje


Set options on a given XSLT processor

xslt_set_scheme_handlers
Rdzeń PHP: Poradnik hackerów o Zend Engine
XSLT (PHP 4) Funkcje
PHP Manual

xslt_setopt

(PHP 4 >= 4.3.0)

xslt_setopt — Set options on a given XSLT processor

Opis

mixed xslt_setopt ( resource $processor , int $newmask )

xslt_setopt() sets the options specified by newmask on the given processor.

Parametry

processor

The XSLT processor link identifier, created with xslt_create().

newmask

newmask is a bitmask constructed with the following constants:

  • XSLT_SABOPT_PARSE_PUBLIC_ENTITIES - Tell the processor to parse public entities. By default this has been turned off.

  • XSLT_SABOPT_DISABLE_ADDING_META - Do not add the meta tag "Content-Type" for HTML output. The default is set during the compilation of the processor.

  • XSLT_SABOPT_DISABLE_STRIPPING - Suppress the whitespace stripping (on data files only).

  • XSLT_SABOPT_IGNORE_DOC_NOT_FOUND - Consider unresolved documents (the document() function) non-lethal.

Zwracane wartości

Returns the number of previous mask is possible, TRUE otherwise, FALSE in case of an error.

Przykłady

Przykład #1 xslt_setopt() Example

<?php

$xh = xslt_create();

// Tell Sablotron to process public entities
xslt_setopt($xh, XSLT_SABOPT_PARSE_PUBLIC_ENTITIES);

// Let's also ask him to suppress whitespace stripping
xslt_setopt($xh, xslt_getopt($xh) | XSLT_SABOPT_DISABLE_STRIPPING);

?>

Zobacz też:

  • xslt_getopt() - Get options on a given xsl processor

xslt_set_scheme_handlers
Rdzeń PHP: Poradnik hackerów o Zend Engine
XSLT (PHP 4) Funkcje


Rdzeń PHP: Poradnik hackerów o Zend Engine

  • Preface
  • The "counter" Extension - A Continuing Example
    • Instalacja/Konfiguracja
    • Stałe predefiniowane
    • Przykłady
    • Counter — The Counter class
    • Basic — The basic interface
    • Extended — The extended interface
  • The PHP 5 build system
    • Building PHP for extension development
    • The ext_skel script
    • Talking to the UNIX build system: config.m4
    • Talking to the Windows build system: config.w32
  • Extension structure
    • Files which make up an extension
    • Basic constructs
    • The zend_module structure
    • Extension globals
    • Life cycle of an extension
    • Testing an extension
  • Memory management
    • Basic memory management
    • Data persistence
    • Thread-Safe Resource Manager
  • Working with variables
    • Intro
    • Creating variables and setting values
  • Writing functions
  • Working with classes and objects
  • Working with resources
  • Working with INI settings
  • Working with streams
  • PDO Driver How-To
    • Prerequisites
    • Preparation and Housekeeping
    • Fleshing out your skeleton
    • Building
    • Testing
    • Packaging and distribution
    • pdo_dbh_t definition
    • pdo_stmt_t definition
    • Constants
    • Error handling
  • Extension FAQs
  • Zend Engine 2 API reference
  • Zend Engine 2 opcode list
    • Opcodes
  • Zend Engine 1
    • Old introduction
    • Streams API for PHP Extension Authors
    • Zend API: Hackowanie rdzenia PHP
    • TSRM API
xslt_setopt
Preface
Podręcznik PHP


Preface

The Zend API has evolved considerably over time, as PHP has become a more robust and widespread language. With the introduction of PHP 5 came the Zend Engine 2 (ZE2). ZE2 came with an almost entirely new Object-Oriented Programming (OOP) model and a number of improvements in the API.

Ostrzeżenie

This documentation is still under heavy development. The original Zend documentation is preserved in its entirety in the Zend Engine 1 section for those who need it before this documentation is completed.

This section of the manual is devoted to ZE2. The differences in how extensions are written in ZE1 are small; a short reference to them is given in an appendix to this section.

The documentation in this section is current as of PHP 5.3.3, the most recent stable release of PHP 5.3 at the time of this writing. Notable differences in the minor PHP 5 releases (5.0 through 5.3) are given as appropriate.

Rdzeń PHP: Poradnik hackerów o Zend Engine
The "counter" Extension - A Continuing Example
Rdzeń PHP: Poradnik hackerów o Zend Engine


Preface
Instalacja/Konfiguracja
Rdzeń PHP: Poradnik hackerów o Zend Engine
PHP Manual

The "counter" Extension - A Continuing Example

Spis treści

  • Instalacja/Konfiguracja
  • Stałe predefiniowane
  • Przykłady
  • Counter
  • Basic
  • Extended

Preface

Throughout this Zend documentation, references are made to an example module in order to illustrate various concepts. The "counter" extension is this example, a fictional yet functional Zend module which strives to use as much of the Zend API as is reasonably possible. This short chapter describes the userland interface to the completed extension.

Informacja: "counter" serves no practical purpose whatsoever, as the functionality it provides is far more effectively implemented by appropriate userland code.

Preface
Instalacja/Konfiguracja
Rdzeń PHP: Poradnik hackerów o Zend Engine


Instalacja/Konfiguracja

Spis treści

  • Wstęp
  • Konfiguracja wykonawcza
  • Typy zasobów
The "counter" Extension - A Continuing Example
Wstęp
The "counter" Extension - A Continuing Example


Wstęp

The "counter" extension provides any number of counters to PHP code using it which reset at times determined by the caller.

There are three interfaces to "counter": basic, extended, and objective. The basic interface provides a single counter controlled by INI settings and function calls. The extended interface provides an arbitrary number of named counter resources which may optionally persist beyond the lifetime of a single PHP request. The objective interface combines both the basic and extended interfaces into a Counter class.

Instalacja/Konfiguracja
Konfiguracja wykonawcza
Instalacja/Konfiguracja


Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Counter configuration options
Name | Default | Changeable | Changelog
counter.reset_time | COUNTER_RESET_PER_REQUEST | PHP_INI_ALL |
counter.save_path | "" | PHP_INI_ALL |
counter.initial_value | "0" | PHP_INI_ALL |

Szczegóły i definicje dotyczące działania PHP_INI_* znajdują się w rozdziale Where a configuration setting may be set.

counter.reset_time integer
counter.reset_time tells "counter" to reset the counter used by the basic interface. It may be any of the COUNTER_RESET_* constants (see below).
counter.save_path string
Tells "counter" where to save data that has to persist between invocations of PHP (i.e. any counter that has COUNTER_RESET_NEVER or COUNTER_FLAG_SAVE). A file will be created at this path, which must be readable and writable to whatever user PHP is running as.
counter.initial_value integer
Sets the initial value of the counter used by the basic interface whenever it is reset.
Wstęp
Typy zasobów
Instalacja/Konfiguracja


Typy zasobów

The "counter" extension defines one resource type: a counter.

Konfiguracja wykonawcza
Stałe predefiniowane
Instalacja/Konfiguracja


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.

COUNTER_FLAG_PERSIST (integer)
A counter with this flag will be created as a persistent resource.
COUNTER_FLAG_SAVE (integer)
A counter with this flag will be saved between invocations of PHP.
COUNTER_FLAG_NO_OVERWRITE (integer)
This flag causes counter_create() to avoid overwriting an existing named counter with a new one.
COUNTER_META_NAME (string)
Pass this constant to get the name of a counter resource or object.
COUNTER_META_IS_PERISTENT (string)
Pass this constant to determine whether a counter resource or object is persistent (has the COUNTER_FLAG_PERSIST flag).
COUNTER_RESET_NEVER (integer)
The counter will never be reset.
COUNTER_RESET_PER_LOAD (integer)
The counter will be reset on each invocation of PHP.
COUNTER_RESET_PER_REQUEST (integer)
The counter will be reset on each request.
Typy zasobów
Przykłady
The "counter" Extension - A Continuing Example


Przykłady

Spis treści

  • Basic interface
  • Extended interface
  • Objective interface
Stałe predefiniowane
Basic interface
The "counter" Extension - A Continuing Example


Basic interface

The basic interface provides three simple functions, illustrated here:

Przykład #1 "counter"'s basic interface

<?php
$starting_counter_value = counter_get();
counter_bump(1);
$second_counter_value = counter_get();
counter_reset();
$final_counter_value = counter_get();
printf("%3d %3d %3d", $starting_counter_value, $second_counter_value, $final_counter_value);
?>

Powyższy przykład wyświetli:

  0   1   0

The basic interface also provides a number of INI settings.

Przykłady
Extended interface
Przykłady


Extended interface

The extended interface provides a small suite of functions that allow the user to define an arbitrary number of named counters with unique settings. The basic interface can be used in parallel with the extended interface.

Przykład #1 "counter"'s extended interface

<?php
function print_counter_info($counter)
{
    if (is_resource($counter)) {
        printf("Counter's name is '%s' and is%s persistent. Its current value is %d.\n",
            counter_get_meta($counter, COUNTER_META_NAME),
            counter_get_meta($counter, COUNTER_META_IS_PERSISTENT) ? '' : ' not',
            counter_get_value($counter));
    } else {
      print "Not a valid counter!\n";
    }
}

if (($counter_one = counter_get_named("one")) === NULL) {
    $counter_one = counter_create("one", 0, COUNTER_FLAG_PERSIST);
}
counter_bump_value($counter_one, 2);
$counter_two = counter_create("two", 5);
$counter_three = counter_get_named("three");
$counter_four = counter_create("four", 2, COUNTER_FLAG_PERSIST | COUNTER_FLAG_SAVE | COUNTER_FLAG_NO_OVERWRITE);
counter_bump_value($counter_four, 1);

print_counter_info($counter_one);
print_counter_info($counter_two);
print_counter_info($counter_three);
print_counter_info($counter_four);
?>

When run once, the above example outputs:

Counter's name is 'one' and is persistent. Its current value is 2.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 3.

If run a second time within the same instance of PHP, it outputs:

Counter's name is 'one' and is persistent. Its current value is 4.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 4.

If then run a third time in a different instance of PHP, it outputs:

Counter's name is 'one' and is persistent. Its current value is 2.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 5.
Basic interface
Objective interface
Przykłady


Objective interface

The objective interface provides an object-oriented way to access the extended interfaces. The following example shows how the above one would be implemented using the objective interface. The output of this example is exactly the same, except that instead of printing "Not a valid counter!", this will instead issue a PHP warning that the variable $counter_three is not an object. This example shows that it is possible to subclass the Counter class defined by the extension, as well as that the counter's value is maintained using an instance variable rather than method access.

Przykład #1 "counter"'s objective interface

<?php
class MyCounter extends Counter
{
    public function printCounterInfo() {
        printf("Counter's name is '%s' and is%s persistent. Its current value is %d.\n",
            $this->getMeta(COUNTER_META_NAME),
            $this->getMeta(COUNTER_META_IS_PERSISTENT) ? '' : ' not',
            $this->value);
    }
}

Counter::setCounterClass("MyCounter");
if (($counter_one = Counter::getNamed("one")) === NULL) {
    $counter_one = new Counter("one", 0, COUNTER_FLAG_PERSIST);
}
$counter_one->bumpValue(2); // we aren't allowed to "set" the value directly
$counter_two = new Counter("two", 5);
$counter_three = Counter::getNamed("three");
$counter_four = new Counter("four", 2, COUNTER_FLAG_PERSIST | COUNTER_FLAG_SAVE | COUNTER_FLAG_NO_OVERWRITE);
$counter_four->bumpValue(1);

$counter_one->printCounterInfo();
$counter_two->printCounterInfo();
$counter_three->printCounterInfo();
$counter_four->printCounterInfo();
?>
Extended interface
Counter
Przykłady


The Counter class

Wstęp

Represents a single counter object.

Krótki opis klasy

Counter {
__construct ( string $name [, integer $initial_value [, integer $flags ]] )
integer getValue ( void )
bumpValue ( integer $offset )
void resetValue ( void )
mixed getMeta ( integer $attribute )
static Counter getNamed ( string $name )
static void setCounterClass ( string $name )
}

Spis treści

  • Counter::__construct — Creates an instance of a Counter which maintains a single numeric value.
  • Counter::getValue — Get the current value of a counter.
  • Counter::bumpValue — Change the current value of a counter.
  • Counter::resetValue — Reset the current value of a counter.
  • Counter::getMeta — Return a piece of metainformation about a counter.
  • Counter::getNamed — Retrieve an existing named counter.
  • Counter::setCounterClass — Set the class returned by Counter::getNamed.
Objective interface
Counter::__construct
The "counter" Extension - A Continuing Example


Creates an instance of a Counter which maintains a single numeric value.

Counter
Counter::getValue
Counter
PHP Manual

Counter::__construct

Counter::__construct — Creates an instance of a Counter which maintains a single numeric value.

Opis

Counter::__construct() ( string $name [, integer $initial_value [, integer $flags ]] )

Creates an instance of a Counter which maintains a single numeric value.

Parametry

name
The new counter's name.
initial_value
The initial value of the counter. Defaults to zero (0).
flags
Flags for the new counter, chosen from the COUNTER_FLAG_* constants.

Zwracane wartości

Returns a Counter object on success.

Błędy/Wyjątki

Counter::__construct() throws an Exception if something goes wrong.

Counter
Counter::getValue
Counter


Get the current value of a counter.

Counter::__construct
Counter::bumpValue
Counter
PHP Manual

Counter::getValue

Counter::getValue — Get the current value of a counter.

Opis

integer Counter::getValue ( void )

Counter::getValue() returns the current value of a counter.

Zwracane wartości

Counter::getValue() returns an integer.

Zobacz też:

  • Counter::bumpValue() - Change the current value of a counter.
  • Counter::resetValue() - Reset the current value of a counter.
Counter::__construct
Counter::bumpValue
Counter


Change the current value of a counter.

Counter::getValue
Counter::resetValue
Counter
PHP Manual

Counter::bumpValue

Counter::bumpValue — Change the current value of a counter.

Opis

Counter::bumpValue ( integer $offset )

Counter::bumpValue() updates the current value of a counter.

Parametry

offset
The amount by which to change the counter's value. Can be negative.

Zobacz też:

  • Counter::getValue() - Get the current value of a counter.
  • Counter::resetValue() - Reset the current value of a counter.
Counter::getValue
Counter::resetValue
Counter


Reset the current value of a counter.

Counter::bumpValue
Counter::getMeta
Counter
PHP Manual

Counter::resetValue

Counter::resetValue — Reset the current value of a counter.

Opis

void Counter::resetValue ( void )

Counter::resetValue() resets the current value of a counter to its original initial value.

Zobacz też:

  • Counter::getValue() - Get the current value of a counter.
  • Counter::bumpValue() - Change the current value of a counter.
Counter::bumpValue
Counter::getMeta
Counter


Return a piece of metainformation about a counter.

Counter::resetValue
Counter::getNamed
Counter
PHP Manual

Counter::getMeta

Counter::getMeta — Return a piece of metainformation about a counter.

Opis

mixed Counter::getMeta ( integer $attribute )

Counter::getMeta() returns metainformation about a counter.

Parametry

attribute
The metainformation to retrieve.

Zwracane wartości

Counter::getMeta() returns values of varying types based on which metainformation was requested.

Counter::resetValue
Counter::getNamed
Counter


Retrieve an existing named counter.

Counter::getMeta
Counter::setCounterClass
Counter
PHP Manual

Counter::getNamed

Counter::getNamed — Retrieve an existing named counter.

Opis

static Counter Counter::getNamed ( string $name )

Counter::getNamed() returns an existing counter by name if that name exists, or NULL otherwise. This is a static function.

Parametry

name
The counter name to search for.

Zwracane wartości

Counter::getNamed() returns an existing counter by name if that name exists, or NULL otherwise.

Counter::getMeta
Counter::setCounterClass
Counter


Set the class returned by Counter::getNamed.

Counter::getNamed
Basic
Counter
PHP Manual

Counter::setCounterClass

Counter::setCounterClass — Set the class returned by Counter::getNamed().

Opis

static void Counter::setCounterClass ( string $name )

Counter::setCounterClass() changes the class of objects returned by Counter::getNamed(). The class being set must not have a public constructor and must be a subclass of Counter. If these conditions are not met, a fatal error is raised. This is a static function.

Parametry

name
The name of the class to use.
Counter::getNamed
Basic
Counter


The basic interface

Spis treści

  • counter_get — Get the current value of the basic counter.
  • counter_bump — Update the current value of the basic counter.
  • counter_reset — Reset the current value of the basic counter.
Counter::setCounterClass
counter_get
The "counter" Extension - A Continuing Example


Get the current value of the basic counter.

Basic
counter_bump
Basic
PHP Manual

counter_get

counter_get — Get the current value of the basic counter.

Opis

integer counter_get ( void )

counter_get() returns the current value of the basic interface's counter.

Zwracane wartości

counter_get() returns an integer.

Zobacz też:

  • counter_bump() - Update the current value of the basic counter.
  • counter_reset() - Reset the current value of the basic counter.
Basic
counter_bump
Basic


Update the current value of the basic counter.

counter_get
counter_reset
Basic
PHP Manual

counter_bump

counter_bump — Update the current value of the basic counter.

Opis

void counter_bump ( integer $offset )

counter_bump() updates the current value of the basic interface's counter.

Parametry

offset
The amount by which to change the counter's value. Can be negative.

Zobacz też:

  • counter_get() - Get the current value of the basic counter.
  • counter_reset() - Reset the current value of the basic counter.
counter_get
counter_reset
Basic


Reset the current value of the basic counter.

counter_bump
Extended
Basic
PHP Manual

counter_reset

counter_reset — Reset the current value of the basic counter.

Opis

void counter_reset ( void )

counter_reset() resets the current value of the basic interface's counter to its original initial value.

Zobacz też:

  • counter_get() - Get the current value of the basic counter.
  • counter_bump() - Update the current value of the basic counter.
counter_bump
Extended
Basic


The extended interface

Spis treści

  • counter_create — Creates a counter which maintains a single numeric value.
  • counter_get_value — Get the current value of a counter resource.
  • counter_bump_value — Change the current value of a counter resource.
  • counter_reset_value — Reset the current value of a counter resource.
  • counter_get_meta — Return a piece of metainformation about a counter resource.
  • counter_get_named — Retrieve an existing named counter as a resource.
counter_reset
counter_create
The "counter" Extension - A Continuing Example


Creates a counter which maintains a single numeric value.

Extended
counter_get_value
Extended
PHP Manual

counter_create

counter_create — Creates a counter which maintains a single numeric value.

Opis

resource counter_create ( string $name [, integer $initial_value [, integer $flags ]] )

Creates a counter which maintains a single numeric value.

Parametry

name
The new counter's name.
initial_value
The initial value of the counter. Defaults to zero (0).
flags
Flags for the new counter, chosen from the COUNTER_FLAG_* constants.

Zwracane wartości

Returns a counter resource.

Extended
counter_get_value
Extended


Get the current value of a counter resource.

counter_create
counter_bump_value
Extended
PHP Manual

counter_get_value

counter_get_value — Get the current value of a counter resource.

Opis

integer counter_get_value ( resource $counter )

counter_get_value() returns the current value of a counter resource.

Parametry

counter
The counter resource to operate on.

Zwracane wartości

counter_get_value() returns an integer.

Zobacz też:

  • counter_bump_value() - Change the current value of a counter resource.
  • counter_reset_value() - Reset the current value of a counter resource.
counter_create
counter_bump_value
Extended


Change the current value of a counter resource.

counter_get_value
counter_reset_value
Extended
PHP Manual

counter_bump_value

counter_bump_value — Change the current value of a counter resource.

Opis

void counter_bump_value ( resource $counter , integer $offset )

counter_bump_value() updates the current value of a counter resource.

Parametry

counter
The counter resource to operate on.
offset
The amount by which to change the counter's value. Can be negative.

Zobacz też:

  • counter_get_value() - Get the current value of a counter resource.
  • counter_reset_value() - Reset the current value of a counter resource.
counter_get_value
counter_reset_value
Extended


Reset the current value of a counter resource.

counter_bump_value
counter_get_meta
Extended
PHP Manual

counter_reset_value

counter_reset_value — Reset the current value of a counter resource.

Opis

void counter_reset_value ( resource $counter )

counter_reset_value() resets the current value of a counter resource to its original initial value.

Parametry

counter
The counter resource to operate on.

Zobacz też:

  • counter_get_value() - Get the current value of a counter resource.
  • counter_bump_value() - Change the current value of a counter resource.
counter_bump_value
counter_get_meta
Extended


Return a piece of metainformation about a counter resource.

counter_reset_value
counter_get_named
Extended
PHP Manual

counter_get_meta

counter_get_meta — Return a piece of metainformation about a counter resource.

Opis

mixed counter_get_meta ( resource $counter , integer $attribute )

counter_get_meta() returns metainformation about a counter resource.

Parametry

counter
The counter resource to operate on.
attribute
The metainformation to retrieve.

Zwracane wartości

counter_get_meta() returns values of varying types based on which metainformation was requested.

counter_reset_value
counter_get_named
Extended


Retrieve an existing named counter as a resource.

counter_get_meta
The PHP 5 build system
Extended
PHP Manual

counter_get_named

counter_get_named — Retrieve an existing named counter as a resource.

Opis

resource Counter::getNamed ( string $name )

counter_get_named() returns an existing counter by name if that name exists, or NULL otherwise.

Parametry

name
The counter name to search for.

Zwracane wartości

counter_get_name() returns an existing counter by name if that name exists, or NULL otherwise.

counter_get_meta
The PHP 5 build system
Extended


The PHP 5 build system

Spis treści

  • Building PHP for extension development
  • The ext_skel script
  • Talking to the UNIX build system: config.m4
  • Talking to the Windows build system: config.w32

With all the functionality and flexibility available in PHP 5, it is no surprise that it consists of several thousand files and over one million lines of source code. Equally unsurprising is the necessity of a build system to manage so much data. This section describes how to set PHP up for extension development, the layout of an extension within the PHP source tree, and how to interface your extension with the build system.

counter_get_named
Building PHP for extension development
Rdzeń PHP: Poradnik hackerów o Zend Engine


Building PHP for extension development

In a typical PHP installation, the need for high performance almost always results in optimization at the cost of debugging facilities. This is a reasonable tradeoff for production use, but when developing an extension it falls short. What we need is a build of PHP which will give us some hints what has gone wrong when something does.

The Zend Engine provides a memory manager which is capable of tracking memory leaks in extensions and providing detailed debugging information. This tracking is disabled by default, as is thread-safety. To turn them on, pass the --enable-debug and --enable-maintainer-zts options to configure, along with whatever options you typically use. For instructions on building PHP from source, see the instructions at Ogólnie o instalacji. A typical configure line might look like this:

$ ./configure --prefix=/where/to/install/php --enable-debug --enable-maintainer-zts --enable-cgi --enable-cli --with-mysql=/path/to/mysql

The PHP 5 build system
The ext_skel script
The PHP 5 build system


The ext_skel script

A PHP extension is composed of several files common to all extensions. As the details of many of those files are similar from extension to extension, it can be laborious to duplicate the content for each one. Fortunately, there is a script which can do all of the initial setup for you. It's called ext_skel, and it's been distributed with PHP since 4.0.

Running ext_skel with no parameters produces this output in PHP 5.2.2:

php-5.2.2/ext$ ./ext_skel
./ext_skel --extname=module [--proto=file] [--stubs=file] [--xml[=file]]
           [--skel=dir] [--full-xml] [--no-help]

  --extname=module   module is the name of your extension
  --proto=file       file contains prototypes of functions to create
  --stubs=file       generate only function stubs in file
  --xml              generate xml documentation to be added to phpdoc-cvs
  --skel=dir         path to the skeleton directory
  --full-xml         generate xml documentation for a self-contained extension
                     (not yet implemented)
  --no-help          don't try to be nice and create comments in the code
                     and helper functions to test if the module compiled
Generally, when developing a new extension the only parameters you will be interested in are --extname and --no-help. Unless you are already experienced with the structure of an extension, you will not want to use --no-help; specifying it causes ext_skel to leave out many helpful comments in the files it generates.

This leaves you with --extname, which tells ext_skel what the name of your extension is. This "name" is an all-lowercase identifier containing only letters and underscores which is unique among everything in the ext/ folder of your PHP distribution.

The --proto option is intended to allow the developer to specify a header file from which a set of PHP functions will be created, ostensibly for the purpose of developing an extension based on a library, but it often functions poorly with most modern header files. A test run on the zlib.h header resulted in a very large number of empty and nonsense prototypes in the ext_skel output files. The --xml and --full-xml options are entirely nonfunctional thus far. The --skel option can be used to specify a modified set of skeleton files to work from, a topic which is beyond the scope of this section.

Building PHP for extension development
Talking to the UNIX build system: config.m4
The PHP 5 build system


Talking to the UNIX build system: config.m4

The config.m4 file for an extension tells the UNIX build system what configure options your extension supports, what external libraries and includes you require, and what source files are to be compiled as part of it. A reference to all the commonly used autoconf macros, both PHP-specific and those built into autoconf, is given in the Zend Engine 2 API reference section.

Wskazówka

When developing a PHP extension, it is strongly recommended that autoconf version 2.13 be installed, despite the newer releases which are available. Version 2.13 is recognized as a common denominator of autoconf availability, usability, and user base. Using later versions will sometimes produce cosmetic differences from the expected output of configure.

Przykład #1 An example config.m4 file

dnl $Id$
dnl config.m4 for extension example
PHP_ARG_WITH(example, for example support,
[  --with-example[=FILE]       Include example support. File is the optional path to example-config])
PHP_ARG_ENABLE(example-debug, whether to enable debugging support in example,
[  --enable-example-debug        example: Enable debugging support in example], no, no)
PHP_ARG_WITH(example-extra, for extra libraries for example,
[  --with-example-extra=DIR      example: Location of extra libraries for example], no, no)

dnl Check whether the extension is enabled at all
if test "$PHP_EXAMPLE" != "no"; then

  dnl Check for example-config. First try any path that was given to us, then look in $PATH
  AC_MSG_CHECKING([for example-config])
  EXAMPLE_CONFIG="example-config"
  if test "$PHP_EXAMPLE" != "yes"; then
    EXAMPLE_PATH=$PHP_EXAMPLE
  else
    EXAMPLE_PATH=`$php_shtool path $EXAMPLE_CONFIG`
  fi

  dnl If a usable example-config was found, use it
  if test -f "$EXAMPLE_PATH" && test -x "$EXAMPLE_PATH" && $EXAMPLE_PATH --version > /dev/null 2>&1; then
    AC_MSG_RESULT([$EXAMPLE_PATH])
    EXAMPLE_LIB_NAME=`$EXAMPLE_PATH --libname`
    EXAMPLE_INCDIRS=`$EXAMPLE_PATH --incdirs`
    EXAMPLE_LIBS=`$EXAMPLE_PATH --libs`

    dnl Check that the library works properly
    PHP_CHECK_LIBRARY($EXAMPLE_LIB_NAME, example_critical_function,
    [
      dnl Add the necessary include dirs
      PHP_EVAL_INCLINE($EXAMPLE_INCDIRS)
      dnl Add the necessary libraries and library dirs
      PHP_EVAL_LIBLINE($EXAMPLE_LIBS, EXAMPLE_SHARED_LIBADD)
    ],[
      dnl Bail out
      AC_MSG_ERROR([example library not found. Check config.log for more information.])
    ],[$EXAMPLE_LIBS]
    )
  else
    dnl No usable example-config, bail
    AC_MSG_RESULT([not found])
    AC_MSG_ERROR([Please check your example installation.])
  fi

  dnl Check whether to enable debugging
  if test "$PHP_EXAMPLE_DEBUG" != "no"; then
    dnl Yes, so set the C macro
    AC_DEFINE(USE_EXAMPLE_DEBUG,1,[Include debugging support in example])
  fi

  dnl Check for the extra support
  if test "$PHP_EXAMPLE_EXTRA" != "no"; then
    if test "$PHP_EXAMPLE_EXTRA" == "yes"; then
      AC_MSG_ERROR([You must specify a path when using --with-example-extra])
    fi

    PHP_CHECK_LIBRARY(example-extra, example_critical_extra_function,
    [
      dnl Add the neccessary paths
      PHP_ADD_INCLUDE($PHP_EXAMPLE_EXTRA/include)
      PHP_ADD_LIBRARY_WITH_PATH(example-extra, $PHP_EXAMPLE_EXTRA/lib, EXAMPLE_SHARED_LIBADD)
      AC_DEFINE(HAVE_EXAMPLEEXTRALIB,1,[Whether example-extra support is present and requested])
      EXAMPLE_SOURCES="$EXAMPLE_SOURCES example_extra.c"
    ],[
      AC_MSG_ERROR([example-extra lib not found. See config.log for more information.])
    ],[-L$PHP_EXAMPLE_EXTRA/lib]
    )
  fi

  dnl Finally, tell the build system about the extension and what files are needed
  PHP_NEW_EXTENSION(example, example.c $EXAMPLE_SOURCES, $ext_shared)
  PHP_SUBST(EXAMPLE_SHARED_LIBADD)
fi

A short introduction to autoconf syntax

config.m4 files are written using the GNU autoconf syntax. It can be described in a nutshell as shell scripting augmented by a powerful macro language. Comments are delimited by the string dnl, and strings are quoted using left and right brackets (e.g. [ and ]). Quoting of strings can be nested as many times as needed. A full reference to the syntax can be found in the autoconf manual at » http://www.gnu.org/software/autoconf/manual/.

PHP_ARG_*: Giving users the option

The very first thing seen in the example config.m4 above, aside from a couple of comments, are three lines using PHP_ARG_WITH() and PHP_ARG_ENABLE(). These provide configure with the options and help text seen when running ./configure --help. As the names suggest, the difference between the two is whether they create a --with-* option or an --enable-* option. Every extension should provide at least one or the other with the extension name, so that users can choose whether or not to build the extension into PHP. By convention, PHP_ARG_WITH() is used for an option which takes a parameter, such as the location of a library or program required by an extension, while PHP_ARG_ENABLE() is used for an option which represents a simple flag.

Przykład #2 Sample configure output

$ ./configure --help
...
  --with-example[=FILE]       Include example support. FILE is the optional path to example-config
  --enable-example-debug        example: Enable debugging support in example
  --with-example-extra=DIR      example: Location of extra libraries for example
...

$ ./configure --with-example=/some/library/path/example-config --disable-example-debug --with-example-extra=/another/library/path
...
checking for example support... yes
checking whether to enable debugging support in example... no
checking for extra libraries for example... /another/library/path
...

Informacja:

Regardless of the order in which options are specified on the command line when configure is called, the checks will be run in the order they are specified in config.m4.

Processing the user's choices

Now that config.m4 can provide the user with some choices of what to do, it's time to act upon those choices. In the example above, the obvious default for all three options, if any of them are unspecified, is "no". As a matter of convention, it is best to use this as the default for the option which enables the extension, as it will be overridden by phpize for extensions built separately, and should not clutter the extension space by default when being built into PHP. The code to process the three options is by far the most complicated.

Handling the --with-example[=FILE] option

The first check made of the --with-example[=FILE] option is whether it was set at all. As this option controls the inclusion of the entire extension, if it was unspecified, given in the negative form (--without-example ), or given the value "no", nothing else is done at all. In the example above, it is specified with the value /some/library/path/example-config, so the first test succeeds.

Next, the code calls AC_MSG_CHECKING(), an autoconf macro which outputs a standard "checking for something" line, and checks whether the user gave an explicit path to the fictional example-config. In this example, PHP_EXAMPLE got the value /some/library/path/example-config, which is now copied into the EXAMPLE_PATH variable. Had the user specified only --with-example , the code would have executed $php_shtool path $EXAMPLE_CONFIG, which would try to guess the location of example-config using the user's current PATH. Either way, the next step is to check whether the chosen EXAMPLE_PATH is a regular file, is executable, and can be run successfully. If so, AC_MSG_RESULT() is called, which completes the output line started by AC_MSG_CHECKING(). Otherwise, AC_MSG_ERROR() is called, which prints the given message and halts configure immediately.

The code now determines some site-specific configuration information by running example-config several times. The next call is to PHP_CHECK_LIBRARY(), a macro provided by the PHP buildsystem as a wrapper around autoconf's AC_CHECK_LIB(). PHP_CHECK_LIBRARY() attempts to compile, link, and run a program which calls the symbol specified by the second parameter in the library specified by the first, using the string given in the fifth as extra linker options. If the attempt succeeds, the script given in the third parameter is run. This script tells the PHP buildsystem to extract include paths, library paths, and library names from the raw option strings example-config provided. If the attempt fails, the script in the fourth parameter is run instead. In this case, AC_MSG_ERROR() is called to stop processing.

Handling the --enable-example-debug option

Processing the --enable-example-debug is much simpler. A simple check for its truth value is performed. If that check succeeds, AC_DEFINE() is called to make the C macro USE_EXAMPLE_DEBUG available to the source of the extension. The third parameter is a comment string for config.h; it is safe to leave this empty, and often is.

Handling the --with-example-extra=DIR option

For the sake of this example, the fictional "extra" functionality requested by the --with-example-extra=DIR option does not share the fictional example-config program, nor does it have any default paths to search. Therefore, the user is required to provide the installation prefix of the necessary library. This setup is somewhat unlikely in a real-world extension, but is considered illustrative.

The code begins in a now-familiar way by checking the truth value of PHP_EXAMPLE_EXTRA. If a negative form was provided, no further processing is done; the user did not request extra functionality. If a positive form was provided without a parameter, AC_MSG_ERROR() is called to halt processing. The next step is another invocation of PHP_CHECK_LIBRARY(). This time, since there is no set of predefined compiler options provided, PHP_ADD_INCLUDE() and PHP_ADD_LIBRARY_WITH_PATH() are used to construct the necessary include paths, library paths, and library flags for the extra functionality. AC_DEFINE() is also called to indicate to the code that the extra functionality was both requested and available, and a variable is set to tell later code that there are extra source files to build. If the check fails, the familiar AC_MSG_ERROR() is called. A different way to handle the failure would have been to call AC_MSG_WARNING() instead, e.g.:

AC_MSG_WARNING([example-extra lib not found. example will be built without extra functionality.])

In this case, configure would print a warning message rather than an error, and continue processing. Which way such failures are handled is a design decision left to the extension developer.

Telling the buildsystem what was decided

With all the necessary includes and libraries specified, with all the options processed and macros defined, one more thing remains to be done: The build system must be told to build the extension itself, and which files are to be used for that. To do this, the PHP_NEW_EXTENSION() macro is called. The first parameter is the name of the extension, which is the same as the name of the directory containing it. The second parameter is the list of all source files which are part of the extension. See PHP_ADD_BUILD_DIR() for information about adding source files in subdirectories to the build process. The third parameter should always be $ext_shared, a value which was determined by configure when PHP_ARG_WITH() was called for --with-example[=FILE] . The fourth parameter specifies a "SAPI class", and is only useful for extensions which require the CGI or CLI SAPIs specifically. It should be left empty in all other cases. The fifth parameter specifies a list of flags to be added to CFLAGS while building the extension; the sixth is a boolean value which, if "yes", will force the entire extension to be built using $CXX instead of $CC. All parameters after the third are optional. Finally, PHP_SUBST() is called to enable shared builds of the extension. See Extension FAQs for more information on disabling support for building an extension in shared mode.

The counter extension's config.m4 file

The counter extension previously documented has a much simpler config.m4 file than that described above, as it doesn't make use of many buildsystem features. This is a preferred method of operation for any extension that doesn't use an external or bundled library.

Przykład #3 counter's config.m4 file

dnl
$
Id$
dnl config.m4 for extension counter

PHP_ARG_ENABLE(counter, for counter support,
[  --enable-counter            Include counter support])

dnl Check whether the extension is enabled at all
if test "$PHP_COUNTER" != "no"; then
  dnl Finally, tell the build system about the extension and what files are needed
  PHP_NEW_EXTENSION(counter, counter.c counter_util.c, $ext_shared)
  PHP_SUBST(COUNTER_SHARED_LIBADD)
fi
The ext_skel script
Talking to the Windows build system: config.w32
The PHP 5 build system


Talking to the Windows build system: config.w32

An extension's config.w32 file is similar in usage to the config.m4 file, with two critical differences: first, it is used for Windows builds, and second, it is written in JavaScript. This section makes no attempt to cover JavaScript syntax. For the moment, this section is incomplete in lieu of a Win32 testbed, and an experimental-only port of the example config.m4 is the only example provided.

Przykład #1 An example config.w32 file

// $Id$
// vim:ft=javascript
ARG_WITH("example", "for example support", "no");
ARG_ENABLE("example-debug", "for debugging support in example", "no")
ARG_WITH("example-extra", "for extra functionality in example", "no")
if (PHP_EXAMPLE != "no") {
    if (CHECK_LIB("libexample.lib", "example", PHP_EXAMPLE) &&
        CHECK_HEADER_ADD_INCLUDE("example.h", "CFLAGS_EXAMPLE", PHP_EXAMPLE + "\\include")) {

        if (PHP_EXAMPLE_DEBUG != "no") {
            AC_DEFINE('USE_EXAMPLE_DEBUG', 1, 'Debug support in example');
        }

        if (PHP_EXAMPLE_EXTRA != "no" &&
            CHECK_LIB("libexample-extra.lib", "example", PHP_EXAMPLE) &&
            CHECK_HEADER_ADD_INCLUDE("example-extra.h", "CFLAGS_EXAMPLE", PHP_EXAMPLE + ";" + PHP_PHP_BUILD + "\\include") {
            AC_DEFINE('HAVE_EXAMPLEEXTRA', 1, 'Extra functionality in example');
            HAVE_EXTRA = 1;
        } else {
            WARNING( "extra example functionality not enabled, lib not found" );
        }

        EXTENSION("example", "example.c");
        if (HAVE_EXTRA == 1) {
            ADD_SOURCES("example-extra.c");
        }
    } else {
        WARNING( "example not enabled; libraries not found" );
    }
}

The counter extension's config.w32 file

The counter extension previously documented has a much simpler config.w32 file than that described above, as it doesn't make use of many buildsystem features.

Przykład #2 counter's config.w32 file

// $Id$
// vim:ft=javascript
ARG_ENABLE("counter", "for counter support", "no");
if (PHP_COUNTER != "no") {
    EXTENSION("counter", "counter.c");
    ADD_SOURCE("counter-util.c");
}
Talking to the UNIX build system: config.m4
Extension structure
The PHP 5 build system


Extension structure

Spis treści

  • Files which make up an extension
  • Basic constructs
  • The zend_module structure
  • Extension globals
  • Life cycle of an extension
  • Testing an extension

Many extension-writing guides focus on simple examples first and ignore the requirements of more complex implementations until later. Often such guides must repeat themselves over and over in order to describe these new features. This section describes extension structure from the perspective of a mature, practical implementation, in order to prepare users for needs and issues they will almost always encounter in the process of extension development.

Talking to the Windows build system: config.w32
Files which make up an extension
Rdzeń PHP: Poradnik hackerów o Zend Engine


Files which make up an extension

Whether created by hand, using ext_skel, or by an alternate extension generator, such as » CodeGen, all extensions will have at least four files:

config.m4

UNIX build system configuration (see Talking to the UNIX build system: config.m4)

config.w32

Windows buildsystem configuration (see Talking to the Windows build system: config.w32)

php_counter.h

When building an extension as static module into the PHP binary the build system expects a header file with php_ prepended to the extension name which includes a declaration for a pointer to the extension's module structure. This file usually contains additional macros, prototypes, and globals, just like any header.

counter.c

Main extension source file. By convention, the name of this file is the extension name, but this is not a requirement. This file contains the module structure declaration, INI entries, management functions, userspace functions, and other requirements of an extension.

The buildsystem files are discussed elsewhere; this section concentrates on the rest. These four files make up the bare minimum for an extension, which may also contain any number of headers, source files, unit tests, and other support files. The list of files in the counter extension might look like this:

Przykład #1 Files in the counter extension, in no particular order

ext/
 counter/
  .svnignore
  config.m4
  config.w32
  counter_util.h
  counter_util.c
  php_counter.h
  counter.c
  package.xml
  CREDITS
  tests/
   critical_function_001.phpt
   critical_function_002.phpt
   optional_function_001.phpt
   optional_function_002.phpt

Non-source files

The .svnignore file is used for extensions which are checked into the PHP Subversion repository (usually » PECL); the one generated by ext_skel contains:

.deps
*.lo
*.la

These lines tell Subversion to ignore interim files generated by the PHP buildsystem. This is only a convenience, and can be omitted completely without ill effect.

The CREDITS file lists the contributors and/or maintainers of the extension in plain text format. The main purpose of this file is generating the credits information for bundled extensions as used by phpcredits(). By convention the first line of the file should hold the name of the extension, the second a comma separated list of contributors. The contributors are usually ordered by the chronological order of their contributions. In a » PECL package, this information is already maintained in package.xml, for example. This is another file which can be omitted without ill effect.

The package.xml file is specific to » PECL-based extensions; it is a metainformation file which gives details about an extension's dependencies, authors, installation requirements, and other tidbits. In an extension not being hosted in » PECL, this file is extraneous.

Extension structure
Basic constructs
Extension structure


Basic constructs

C is a very low-level language by modern definitions. This means that it has no built-in support for many features that PHP takes for granted, such as reflection, dynamic module loading, bounds checking, threadsafe data management and various useful data structures including linked lists and hash tables. At the same time, C is a common denominator of language support and functionality. Given enough work, none of these concepts are impossible; the Zend Engine uses them all.

A lot of effort has gone into making the Zend API both extensible and understandable, but C forces certain necessary declarations upon any extension that to an inexperienced eye seem redundant or plain unnecessary. All of those constructs, detailed in this section, are "write once and forget" in Zend Engine 2 and 3. Here are some excerpts from the pre-generated php_counter.h and counter.c files created by PHP 5.3's ext_skel, showing the pre-generated declarations:

Informacja: The astute reader will notice that there are several declarations in the real files that aren't shown here. Those declarations are specific to various Zend subsystems and are discussed elsewhere as appropriate.

extern zend_module_entry counter_module_entry;
#define phpext_counter_ptr &counter_module_entry

#ifdef PHP_WIN32
#    define PHP_COUNTER_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
#    define PHP_COUNTER_API __attribute__ ((visibility("default")))
#else
#    define PHP_COUNTER_API
#endif

#ifdef ZTS
#include "TSRM.h"
#endif

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_counter.h"

/* ... */

#ifdef COMPILE_DL_COUNTER
ZEND_GET_MODULE(counter)
#endif
  • The lines concerning counter_module_entry declare a global variable, and a macroed pointer to it, which contains the zend_module_entry for the extension. Despite the later discussion regarding the drawbacks of "true" globals, this usage is intentional; Zend takes precautions to avoid misusing this variable.
  • PHP_COUNTER_API is declared for use by non-PHP functions the module intends to export for the use of other modules. The counter extension doesn't declare any of these, and in the final version of the header file, this macro has been removed. The PHPAPI macro is declared identically elsewhere and is used by the standard extension to make the phpinfo() utility functions available to other extensions.
  • The include of TSRM.h is skipped if PHP, or the extension, isn't being compiled with thread-safety, since in that case TSRM isn't used.
  • A standard list of includes, especially the extension's own php_counter.h, is given. config.h gives the extension access to determinations made by configure. php.h is the gateway to the entire PHP and Zend APIs. php_ini.h adds the APIs for runtime configuration (INI) entries. Not all extensions will use this. Finally, ext/standard/info.h imports the aforementioned phpinfo() utility API.
  • COMPILE_DL_COUNTER will only be defined by configure if the counter extension is both enabled and wants to be built as a dynamically loadable module instead of being statically linked into PHP. ZEND_GET_MODULE defines a tiny function which Zend can use to get the extension's zend_module_entry at runtime.

    Informacja: The astute reader who has peeked into main/php_config.h after trying to build with the counter module enabled statically may have noticed that there is also a HAVE_COUNTER constant defined that the source code doesn't check for. There's a simple reason this check isn't done: It's unnecessary. If the extension isn't enabled, the source file will never be compiled.

Files which make up an extension
The zend_module structure
Extension structure


The zend_module structure

The main source file of a PHP extension contains several new constructs for a C programmer. The most important of these, the one touched first when starting a new extension, is the zend_module structure. This structure contains a wealth of information that tells the Zend Engine about the extension's dependencies, version, callbacks, and other critical data. The structure has mutated considerably over time; this section will focus on the structure as it has appeared since PHP 5.2, and will identify the very few parts which have changed in PHP 5.3.

The zend_module declaration from counter.c looks like this before any code has been written. The example file was generated by ext_skel --extname=counter, with some obsolete constructs removed:

Przykład #1 zend_module declaration in the counter extension

/* {{{ counter_module_entry
 */
zend_module_entry counter_module_entry = {
    STANDARD_MODULE_HEADER,
    "counter",
    counter_functions,
    PHP_MINIT(counter),
    PHP_MSHUTDOWN(counter),
    PHP_RINIT(counter),        /* Replace with NULL if there's nothing to do at request start */
    PHP_RSHUTDOWN(counter),    /* Replace with NULL if there's nothing to do at request end */
    PHP_MINFO(counter),
    "0.1", /* Replace with version number for your extension */
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

This may look a bit daunting at first glance, but most of it is very simple to understand. Here's the declaration of zend_module from zend_modules.h in PHP 5.3:

Przykład #2 zend_module definition in PHP 5.3

struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    const struct _zend_ini_entry *ini_entry;
    const struct _zend_module_dep *deps;
    const char *name;
    const struct _zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    const char *version;
    size_t globals_size;
#ifdef ZTS
    ts_rsrc_id* globals_id_ptr;
#else
    void* globals_ptr;
#endif
    void (*globals_ctor)(void *global TSRMLS_DC);
    void (*globals_dtor)(void *global TSRMLS_DC);
    int (*post_deactivate_func)(void);
    int module_started;
    unsigned char type;
    void *handle;
    int module_number;
};

Many of these fields will never be touched by an extension writer. There are a number of standard macros that set them to their proper values automatically. The macro STANDARD_MODULE_HEADER fills in everything up to the deps field. Alternatively, the STANDARD_MODULE_HEADER_EX will leave the deps field empty for the developer's use. The developer is always responsible for everything from name to version. After that, the STANDARD_MODULE_PROPERTIES macro will fill in the rest of the structure, or the STANDARD_MODULE_PROPERTIES_EX macro can be used to leave the extension globals and post-deactivation function fields unfilled. Most modern extensions will make use of module globals.

Informacja:

This table gives the values that each field would have if the developer were to fill in the structure entirely by hand, without recourse to any of the shortcut macros. This is not recommended. The "correct" values for many fields may change. Use the macros whenever possible.

Module structure field values
Field | Value | Description
size [1] [2] [3] | sizeof(zend_module_entry) | The size in bytes of the structure.
zend_api [1] [2] [3] | ZEND_MODULE_API_NO | The version of the Zend API this module was compiled against.
zend_debug [1] [2] [3] | ZEND_DEBUG | A flag indicating whether the module was compiled with debugging turned on.
zts [1] [2] [3] | USING_ZTS | A flag indicating whether the module was compiled with ZTS (TSRM) enabled (see Memory management).
ini_entry [1] [3] | NULL | This pointer is used internally by Zend to keep a non-local reference to any INI entries declared for the module.
deps [3] | NULL | A pointer to a list of dependencies for the module.
name | "mymodule" | The name of the module. This is the short name, such as "spl" or "standard".
functions | mymodule_functions | A pointer to the module's function table, which Zend uses to expose functions in the module to user space.
module_startup_func | PHP_MINIT(mymodule) | A callback function that Zend will call the first time a module is loaded into a particular instance of PHP.
module_shutdown_func | PHP_MSHUTDOWN(mymodule) | A callback function that Zend will call the when a module is unloaded from a particular instance of PHP, typically during final shutdown.
request_startup_func | PHP_RINIT(mymodule) | A callback function that Zend will call at the beginning of each request. This should be as short as possible or NULL as calling this has costs on every request.
request_shutdown_func | PHP_RSHUTDOWN(mymodule) | A callback function that Zend will call at the end of each request. This should be as short as possible or NULL as calling this has costs on every request.
info_func | PHP_MINFO(mymodule) | A callback function that Zend will call when the phpinfo() function is called.
version | NO_VERSION_YET | A string giving the version of the module, as specified by the module developer. It is recommended that the version number be either in the format expected by version_compare() (e.g. "1.0.5-dev"), or a CVS or SVN revision number (e.g. "$Rev: 322138 $").
globals_size [1] [4] [5] [6] | sizeof(zend_mymodule_globals) | The size of the data structure containing the module's globals, if any.
globals_id_ptr [1] [4] [5] [6] [7] | &mymodule_globals_id | Only one of these two fields will exist, depending upon whether the USING_ZTS constant is TRUE. The former is an index into TSRM's allocation table for the module's globals, and the latter is a pointer directly to the globals.
globals_ptr [1] [4] [5] [6] [8] | &mymodule_globals
globals_ctor [4] [5] [6] | PHP_GINIT(mymodule) | This funtion is called to initialize a module's globals before any module_startup_func.
globals_dtor [4] [5] [6] | PHP_GSHUTDOWN(mymodule) | This funtion is called to deallocate a module's globals after any module_shutdown_func.
post_deactivate_func [4] | ZEND_MODULE_POST_ZEND_DEACTIVATE_N(mymodule) | This function is called by Zend after request shutdown. It is rarely used.
module_started [1] [9] [4] | 0 | These fields are used for Zend's internal tracking information.
type [1] [9] [4] | 0
handle [1] [9] [4] | NULL
module_number [1] [9] [4] | 0
[1] This field is not intended for use by module developers. [2] This field is filled in by STANDARD_MODULE_HEADER_EX. [3] This field is filled in by STANDARD_MODULE_HEADER. [4] This field is filled in by STANDARD_MODULE_PROPERTIES. [5] This field is filled in by NO_MODULE_GLOBALS. [6] This field is filled in by PHP_MODULE_GLOBALS. [7] This field only exists when USING_ZTS is TRUE. [8] This field only exists when USING_ZTS is FALSE. [9] This field is filled in by STANDARD_MODULE_PROPERTIES_EX.

Filling in the structure in a practical situation

With all these fields to play with, it can be confusing to know which to use for what purpose. Here is the zend_module definition from the "counter" example extension after updating it to its final form.

Przykład #3 Counter extension module definition

/* {{{ counter_module_entry
 */
zend_module_entry counter_module_entry = {
    STANDARD_MODULE_HEADER,
    "counter",
    counter_functions,
    PHP_MINIT(counter),
    PHP_MSHUTDOWN(counter),
    PHP_RINIT(counter),
    PHP_RSHUTDOWN(counter),
    PHP_MINFO(counter),
    NO_VERSION_YET,
    PHP_MODULE_GLOBALS(counter),
    PHP_GINIT(counter),
    PHP_GSHUTDOWN(counter),
    NULL,
    STANDARD_MODULE_PROPERTIES_EX
};
/* }}} */
  • STANDARD_MODULE_HEADER is used since this module doesn't define any dependencies.
  • "counter" is the extension's name, and is used to define the various callback functions the module passes to Zend. "counter" uses module, globals, and request functions at startup and shutdown times, and provides information to phpinfo(), so all seven callbacks are defined.
  • It is assumed that there is a variable of type zend_function_entry * named counter_functions earlier in the file that contains the module definition, listing the functions the module exports to userspace.
  • NO_VERSION_YET is a particularly nice way of telling Zend the module doesn't have a version. It might have been more correct to place "1.0" here instead in a real module.
  • "counter" uses per-module globals, so PHP_MODULE_GLOBALS is used
  • This module has no post-deactivate function, so NULL is used.
  • Since this module does use globals, STANDARD_MODULE_PROPERTIES_EX is used to finish the structure.

What's changed between 5.2 and 5.3?

Nothing. The only differences in the zend_module structure between PHP 5.2 and PHP 5.3 are a few const keywords.

Basic constructs
Extension globals
Extension structure


Extension globals

Introduction to globals in a PHP extension

In a language such as C, a "global" variable is a variable that can be accessed from any function without any extra declaration. These traditional globals have a few drawbacks:

  • Barring any special options passed to the compiler, a global variable can be accessed and changed by any piece of code anywhere in the program, whether or not that code should be doing so.
  • A typical global variable is not thread safe.
  • The names of global variables are as global as the variables themselves.

A PHP extension's globals are more properly called the "extension state", since most modules must remember what they're doing between function calls. The "counter" extension is a perfect example of this need: The basic interface calls for a counter with a persistent value. A programmer new to Zend and PHP might do something like this in counter.c to store that value:

Przykład #1 The wrong way to store the basic counter interface's value

/* ... */
static long basic_counter_value;

/* ... */

PHP_FUNCTION(counter_get)
{
    RETURN_LONG(basic_counter_value);
}

On the surface this appears a viable solution, and indeed in a simple test it would function correctly. However, there are a number of situations in which more than one copy of PHP is running in the same thread, which means more than one instance of the counter module. Suddenly these multiple threads are sharing the same counter value, which is clearly undesirable. Another problem shows itself when considering that another extension might someday happen to have a global with the same name, and due to the rules of C scoping, this has the potential to cause a compile failure, or worse, a runtime error. Something more elaborate is needed, and so exists Zend's support for thread-safe per-module globals.

Declaring module globals

Whether a module uses only a single global or dozens, they must be defined in a structure, and that structure must be declared. There are some macros that assist with doing so in a way that avoids name conflicts between modules: ZEND_BEGIN_MODULE_GLOBALS(), ZEND_END_MODULE_GLOBALS(), and ZEND_DECLARE_MODULE_GLOBALS(). All three take as a parameter the short name of the module, which in the case of the counter module is simply "counter". Here is the global structure declaration from php_counter.h:

Przykład #2 The counter module's globals

ZEND_BEGIN_MODULE_GLOBALS(counter)
    long        basic_counter_value;
ZEND_END_MODULE_GLOBALS(counter)

And this is the declaration from counter.c:

Przykład #3 The counter module's global structure declaration

ZEND_DECLARE_MODULE_GLOBALS(counter)

Accessing module globals

As discussed above, per-module globals are declared inside a C structure whose name is obscured by Zend macros. As a result, the ideal way to access members of this structure is by the use of further macros. Accordingly, most if not all extensions which have globals have a declaration like this somewhere in their header file:

Przykład #4 Accessor macros for per-module globals

#ifdef ZTS
#define COUNTER_G(v) TSRMG(counter_globals_id, zend_counter_globals *, v)
#else
#define COUNTER_G(v) (counter_globals.v)
#endif

Informacja: This could have been generalized into a macro of its own by the Zend API, but as of PHP 5.3 (and PHP 6 at the time of this writing), that hasn't happened. The global accessor construct is written into the header by ext_skel and thus is generally left alone by extension writers, unless they wish to change the name of the accessor macro.

Informacja: COUNTER_G was the name given to the macro by ext_skel, but it's not necessary for it to have that name and could just as easily be called FOO instead.

Any code in the counter extension that accesses a global must thus wrap it in the macro COUNTER_G.

Ostrzeżenie

Any function which accesses globals must either be declared by Zend macros, have TSRMLS_DC as its last argument, or call the macro TSRMLS_FETCH before accessing the globals. See the TSRM documentation for more information.

So with all of that in mind, here is our new version of the counter_get():

Przykład #5 The right way to store the basic counter interface's value

/* php_counter.h */
ZEND_BEGIN_MODULE_GLOBALS(counter)
    long        basic_counter_value;
ZEND_END_MODULE_GLOBALS(counter)

#ifdef ZTS
#define COUNTER_G(v) TSRMG(counter_globals_id, zend_counter_globals *, v)
#else
#define COUNTER_G(v) (counter_globals.v)
#endif

/* counter.c */
ZEND_DECLARE_MODULE_GLOBALS(counter)

/* ... */

PHP_FUNCTION(counter_get)
{
    RETURN_LONG(COUNTER_G(basic_counter_value));
}

This is a correct implementation. It is not, however, a complete one. The section Life cycle of an extension explains why.

The zend_module structure
Life cycle of an extension
Extension structure


Life cycle of an extension

A PHP extension goes through several phases during its lifetime. All of these phases are opportunities for the developer to perform various initialization, termination, or informational functions. The Zend API allows for hooks into five separate phases of an extension's existence, apart from calls by PHP functions.

Loading, unloading, and requests

As the Zend engine runs, it processes one or more "requests" from its client. In the traditional CGI implementation, this corresponds to one execution of a process. However, many other implementations, most notably the Apache module, can map many requests onto a single PHP process. A PHP extension may thus see many requests in its lifetime.

Overview

  • In the Zend API, a module is loaded into memory only once when the associated PHP process starts up. Each module receives a call to the "module initialization" function specified in its zend_module structure as it is loaded.
  • Whenever the associated PHP process starts to handle a request from its client - i.e. whenever the PHP interpreter is told to start working - each module receives a call to the "request initialization" function specified in its zend_module structure.
  • Whenever the associated PHP process is done handling a request, each module receives a call to the "request termination" function specified in its zend_module structure.
  • A given module is unloaded from memory when its associated PHP process is shut down in an orderly manner. The module receives a call to the "module termination" function specified in its zend_module structure at this time.

What to do, and when to do it

There are many tasks that might be performed at any of these four points. This table details where many common initialization and termination tasks belong.

What to do, and when to do it
Module initialization/termination | Request initialization/termination
Allocate/deallocate and initialize module global variables | Allocate/deallocate and initialize request-specific variables
Register/unregister class entries |
Register/unregister INI entries |
Register constants |

The phpinfo() callback

Aside from globals initialization and certain rarely-used callbacks, there is one more part of a module's lifecycle to examine: A call to phpinfo(). The output a user sees from this call, whether text or HTML or anything else, is generated by each individual extension that is loaded into the PHP interpreter at the time the call is made.

To provide for format-neutral output, the header "ext/standard/info.h" provides an array of functions to produce standardized display elements. Specifically, several functions which create the familiar tables exist:

php_info_print_table_start()
Open a table in phpinfo() output. Takes no parameters.
php_info_print_table_header()
Print a table header in phpinfo() output. Takes one parameter, the number of columns, plus the same number of char * parameters which are the texts for each column heading.
php_info_print_table_row()
Print a table row in phpinfo() output. Takes one parameter, the number of columns, plus the same number of char * parameters which are the texts for each column content.
php_info_print_table_end()
Close a table formerly opened by php_info_print_table_start(). Takes no parameters.

Using these four functions, it is possible to produce status information for nearly any combination of features in an extension. Here is the information callback from the counter extension:

Przykład #1 counter's PHP_MINFO function

/* {{{ PHP_MINFO(counter) */
PHP_MINFO_FUNCTION(counter)
{
    char        buf[10];

    php_info_print_table_start();
    php_info_print_table_row(2, "counter support", "enabled");
    snprintf(buf, sizeof(buf), "%ld", COUNTER_G(basic_counter_value));
    php_info_print_table_row(2, "Basic counter value", buf);
    php_info_print_table_end();
}
/* }}} */
Extension globals
Testing an extension
Extension structure


Testing an extension

One of the accepted requirements of good programming is testing. PHP provides a test harness for unit regression tests, in the form of a script called run-tests.php.

Tests for a particular module are stored in the tests/ subdirectory of the module's folder, and have a .phpt extension. For details of the PHPT format, see » http://qa.php.net/.

Life cycle of an extension
Memory management
Extension structure


Memory management

Spis treści

  • Basic memory management
  • Data persistence
  • Thread-Safe Resource Manager

Memory management in the Zend Engine is deceptively simple. There are some APIs to learn, and some concepts behind them to understand, but that's about all.

Testing an extension
Basic memory management
Rdzeń PHP: Poradnik hackerów o Zend Engine


Basic memory management

When programming in the C programming language the developer has to manually care about memory management. As PHP is usually used as a web server module memory management is from special relevance in order to prevent memory leaks. Additionally you should be aware that PHP might be used in threaded environments which means that global variables might lead to race conditions. For information about dealing with thread-global data please refer to the documentation on the Thread-Safe Resource Manager, which serves as thread-isolation facility.

Additionally to these requirements the Zend Engine is faced with a quite special usage pattern where, within a relatively short time, many memory blocks of the size of a zval structure or other small memory blocks are requested and freed again. Memory management in PHP has also to respect the memory_limit.

For fulfilling the above requirements the Zend Engine provides a special memory manager for handling request-bound data. Request-bound data is data that is needed only for serving a single request and which will be freed at the request's end at latest. Extension authors will mostly only have contact with the routines listed in the table below. Although they are implemented as macros for providing some convenience features this documentation will treat them like functions.

Main memory APIs
Prototype | Description
void *emalloc(size_t size) | Allocate size bytes of memory.
void *ecalloc(size_t nmemb, size_t size) | Allocate a buffer for nmemb elements of size bytes and makes sure it is initialized with zeros.
void *erealloc(void *ptr, size_t size) | Resize the buffer ptr, which was allocated using emalloc to hold size bytes of memory.
void efree(void *ptr) | Free the buffer pointed by ptr. The buffer had to be allocated by emalloc.
void *safe_emalloc(size_t nmemb, size_t size, size_t offset) | Allocate a buffer for holding nmemb blocks of each size bytes and an additional offset bytes. This is similar to emalloc(nmemb * size + offset) but adds a special protection against overflows.
char *estrdup(const char *s) | Allocate a buffer that can hold the NULL-terminated string s and copy the s into that buffer.
char *estrndup(const char *s, unsigned int length) | Similar to estrdup while the length of the NULL-terminated string is already known.

Informacja: Unlike their C standard library's counterparts the Zend Engine's memory management functions won't return NULL in case of an problem while allocating the requested memory but bail out and terminate the current request.

As said above it is an essential part of the memory management to avoid having memory leaks and therefore free all memory you've allocated as soon as possible. As a safety net the Zend Engine will free all memory, which had been allocated using above mentioned APIs at the end of a request. If PHP was built using the --enable-debug configuration option this will lead to a warning.

Przykład #1 PHP's leak warnings

ZEND_FUNCTION(leak)
{
    long leakbytes = 3;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &leakbytes) == FAILURE) {
        return;
    }

    emalloc(leakbytes);
}

Powyższy przykład wyświetli coś podobnego do:

[Thu Oct 22 02:14:57 2009]  Script:  '-'
/home/johannes/src/PHP_5_3/Zend/zend_builtin_functions.c(1377) :  Freeing 0x088888D4 (3 bytes), script=-
=== Total 1 memory leaks detected ===

Informacja: When dealing with PHP variables you have to make sure the variable's memory is allocated using emalloc and take care of the reference count. Details can be found in Working with variables.

Informacja: This leak detection can only find leaks caused by blocks allocated by emalloc. You're advised to use a memory checker like valgrind or libumem for deeper analysis. To simplify the analysis PHP's memory manager can be disabled by setting the environment variable USE_ZEND_ALLOC=0 before starting PHP.

Memory management
Data persistence
Memory management


Data persistence

Basic memory management
Thread-Safe Resource Manager
Memory management


Thread-Safe Resource Manager

Data persistence
Working with variables
Memory management


Working with variables

Spis treści

  • Intro
  • Creating variables and setting values
Thread-Safe Resource Manager
Intro
Rdzeń PHP: Poradnik hackerów o Zend Engine


Intro

For working with variables in PHP's core you have to learn about different fundamental concepts used in PHP. Firstly PHP is a dynamic and weak typed language. Secondly PHP uses a copy on write mechanism with reference counting for memory handling. Please check the Reference Counting Basics chapter for details how reference counting and references work.

PHP variables, in general, consist out of two things: The label, which might, for instance, be an entry in a symbol table, and the actual variable container. For the most parts of this manual we will focus on the variable container.

The variable container, in code called zval, is holding all data needed to handle the variable. This includes not only the actual value but also the current type, a counter counting the number of labels pointing to this container and a flag whether these labels should be treated as references or copies. In PHP 5.3 the relevant structures, which you can find in Zend/zend.h, look like this:

typedef struct _zval_struct zval;

typedef union _zvalue_value {
    long lval;                 /* long value */
    double dval;               /* double value */
    struct {                   /* string type */
        char *val;
        int len;
    } str;
    HashTable *ht;             /* hash table value */
    zend_object_value obj;
} zvalue_value;

struct _zval_struct {
    /* Variable information */
    zvalue_value value;        /* value */
    zend_uint refcount__gc;
    zend_uchar type;           /* active type */
    zend_uchar is_ref__gc;
};

In the zvalue_value one can find the internal representation for the different types the fields used should be clear from the names and comments - especially if one knows that PHP's arrays are infact hash tables. Nonetheless, knowing PHP's types one might miss a few: NULL, boolean and resources. For NULL we need no value, as NULL is the value of that type. For boolean and resource values PHP re-uses the value field. In the case of a boolean it holds either 0 for false or 1 for true. For resource-typed variables it holds the resource id.

Now the good message is that you don't have to know these things in detail as there are - like always in PHP - acces macros. The bad news is that there are many of them: There are macros to access any aspect of the zval and then, as one often deals with pointers to zvals and even pointers to pointers to zvals, for most of them there are shortcuts dereferencing these pointers. These macros are spread over Zend/zend.h, Zend/zend_operators.h and Zend/zend_API.h.

Working with variables
Creating variables and setting values
Working with variables


Creating variables and setting values

Intro
Writing functions
Working with variables


Writing functions

One core element of an extension are functions which are exported to the PHP userland. Even when you're planning to write object-oriented extensions you are advised to read this chapter as most of the information is valid for methods, too.

When adding a function to an extension, for instance after using the ext_skel script to create the raw infrastructure, you can create a function by implementing it as a C function and then providing an entry for the extension's function table. The function entry can contain a pointer to an argument information structure. Providing this information ins not strictly necessary, unless you plan to accept parameters by reference or want to return a reference, but provides information that can be accessed via PHP's Reflection API. As you will see below the parameters aren't passed as direct function parameters to the implementation but passed on a stack, which is checked by the function's implementation which can't directly serve as source for this information.

Przykład #1 Minimal PHP extension with one function

/* {{{ proto void hello_world()
       Do nothing */
PHP_FUNCTION(hello_world)
{
}
/* }}} */

/* {{{ arginfo_hello_world */
ZEND_BEGIN_ARG_INFO(arginfo_hello_world, 0)
ZEND_END_ARG_INFO()
/* }}} */

/* {{{ demo_functions */
function_entry demo_functions[] = {
    PHP_FE(hello_world, arginfo_hello_world)
    {NULL, NULL, NULL}
}
/* }}} */

/* {{{ demo_module_enry */
zend_module_entry demo_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    "demo",
    demo_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
#if ZEND_MODULE_API_NO >= 20010901
    "1.0.0",
#en
    STANDARD_MODULE_PROPERTIES
}
/* }}} */

In this example you can see the above discussed elements and the module structure; if you don't remember this structure go back to The zend_module structure.

The first part of this extension is the actual implementation. As a convention each exported function is preceded by a two line comment describing the function's userland prototype and a short one line comment.

For providing source code compatibility between different versions of PHP the functions declaration is wrapped into the PHP_FUNCTION macro. The compiler's preprocessor will, when using PHP 5.3 transform this into a function like this:

void zif_hello_world(int ht, zval *return_value, zval **return_value_ptr,
                     zval *this_ptr, int return_value_used TSRMLS_DC)
{
}

For preventing a naming conflict between a function exported to userland and another C function with the same name the C symbol of the exported function is prefixed with the prefix zif_. You can also see that this prototype doesn't reference the argument stack. Accessing parameters passed from PHP is described below. The following table lists the C level parameters which are also defined in the INTERNAL_FUNCTION_PARAMETERS macro. Mind that these parameters might change between PHP versions and you should use the provide macros.

INTERNAL_FUNCTION_PARAMETERS
Name and type | Description | Access macros
int ht | Number of actual parameters passed by user | ZEND_NUM_ARGS()
zval *return_value | Pointer to a PHP variable that can be filled with the return value passed to the user. The default type is IS_NULL. | RETVAL_*, RETURN_*
zval **return_value_ptr | When returning references to PHP set this to a pointer to your variable. It is not suggested to return references. |
zval *this_ptr | If this is a method call, points to the PHP variable holding the $this object. | getThis()
int return_value_used | Flag indicating whether the returned value will be used by the caller. |

As said the function shown above will simply return NULL to the user and do nothing else. The function can be called, from the PHP userland, with an arbitrary number of parameters. A more useful function consists of four parts in general:

  1. Declaration of local variables. In C we have to declare locale vars, so we do this at the functions top.

  2. Parameter parsing. PHP passes parameters on a special stack: we have to read them from there, verify the types, cast them if needed and bail out if something goes wrong.

  3. Actual logic. Do whatever is needed.

  4. Set the return value, cleanup, return.

In some cases the exact order of these steps may change. Especially the last two steps are often mixed up, but it's a good idea to stay in that order.

Przykład #2 A simple function

/* {{{ proto void hello_world(string name)
   Greets a user */
PHP_FUNCTION(hello_world)
{
    char *name;
    int name_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) {
        return;
    }

    php_printf("Hello %s!", name);

    RETURN_TRUE;
}
/* }}} */

The function above shows these parts. Let's start the analysis with the last lines: php_printf is - as one can guess easily - PHP's version of standard C's printf. Unlike printf it doesn't print to the process's STDOUT channel but to the current output stream, which might be buffered by the user. It should be noted that php_printf, unlike most parts of PHP's API is not binary safe, so if name contains a NULL-byte the rest would be ignored. For a binary safe output PHPWRITE should be used.

Informacja: In general it is considered to directly print data to the output stream, it is suggested to return data as string to the user instead so the user can decide what to do. Exceptions to this rule might be functions dealing with binary data like images while your API should provide a way to access the data even there.

The RETURN_TRUE macro in the last line does three things: It sets the type of the variable we got as return_value pointer to IS_BOOLEAN and the value to a true value. Then it returns from the C function. So when using this macro you're housekeeping for memory and other resources has to be completed as further code of this function won't be executed.

The zend_parse_parameters() function is responsible for reading the parameters passed by the user from the argument stack and putting it with proper casting in local C variables. If the user doesn't pass the wrong number of parameters or types that can't be casted the function will emit a verbose error and return FAILURE. In that case we simply return from the function - by not changing the return_value the default return value of NULL will be returned to the user.

Informacja: Please mind that FAILURE is represented by a -1 and SUCCESS by 0. To make the code clear you should always use the named constants for comparing the value.

The first parameter to zend_parse_parameters() is the number of parameters that have actually been passed to the function by the user. The number is passed as ht parameter to our function but, as discussed above, this should be considered as an implementation detail and ZEND_NUM_ARGS() should be used.

For compatibility with PHP's thread-isolation, the thread-safe resource manager, we also have to pass the thread context using TSRMLS_CC. Unlike in other functions this can't be the last parameter as zend_parse_parameters expects a variable number of parameters - depending on the number of user-parameters to read.

Following the thread context the expected parameters are declared. Each parameter is represented by a character in the string describing the type. In our case we expect one parameter as a string so our type specification is simply "s".

Lastly one has to pass one or more pointers to C variables which should be filled with the variable's value or provide more details. In the case of a string we get the actual string, which will always be NULL-terminated, as a char* and its length, excluding the NULL-byte, as int.

A documentation of all type specifiers and the corresponding additional C types can be found in the file » README.PARAMETER_PARSING_API which is part of the source distribution. The most important types can be found in the table below.

zend_parse_parameters() type specifiers
Modifier | Additional parameter types | Description
b | zend_bool | Boolean value
l | long | A integer (long) value
d | double | A float (double) value
s | char*, int | A binary safe string
h | HashTable* | An array's hash table
Creating variables and setting values
Working with classes and objects
Rdzeń PHP: Poradnik hackerów o Zend Engine


Working with classes and objects

Writing functions
Working with resources
Rdzeń PHP: Poradnik hackerów o Zend Engine


Working with resources

Working with classes and objects
Working with INI settings
Rdzeń PHP: Poradnik hackerów o Zend Engine


Working with INI settings

Working with resources
Working with streams
Rdzeń PHP: Poradnik hackerów o Zend Engine


Working with streams

Informacja:

Information on using streams within the PHP source code can be found in the Streams API for PHP Extension Authors reference.

Working with INI settings
PDO Driver How-To
Rdzeń PHP: Poradnik hackerów o Zend Engine


PDO Driver How-To

Spis treści

  • Prerequisites
  • Preparation and Housekeeping
  • Fleshing out your skeleton
  • Building
  • Testing
  • Packaging and distribution
  • pdo_dbh_t definition
  • pdo_stmt_t definition
  • Constants
  • Error handling

The purpose of this How-To is to provide a basic understanding of the steps required to write a database driver that interfaces with the PDO layer. Please note that this is still an evolving API and as such, subject to change. This document was prepared based on version 0.3 of PDO. The learning curve is steep; expect to spend a lot of time on the prerequisites.

Working with streams
Prerequisites
Rdzeń PHP: Poradnik hackerów o Zend Engine


Prerequisites

The following is list of prerequisites and assumptions needed for writing a PDO database driver:

  1. A working target database, examples, demos, etc. working as per vendor specifications;

  2. A working development environment:

    1. Linux: standard development tools, gcc, ld, make, autoconf, automake, etc., versions dependent on distribution;

    2. Other Unix: standard development tools supplied by vendor plus the GNU development tool set;

    3. Win32: Visual Studio compiler suite;

  3. A working PHP environment version 5.0.3 or higher with a working PEAR extension version 1.3.5 or higher;

  4. A working PDO environment (can be installed using 'sudo pecl install PDO'), including the headers which will be needed to access the PDO type definitions and function declarations;

  5. A good working knowledge of the C programming language;

  6. A good working knowledge of the way to write a PHP extension; George Schlossnagle's Advanced PHP Programming (published by Developer's Library, chapters 21 and 22) is recommended;

  7. Finally, a familiarity with the Zend API that forms the heart of PHP, in particular paying attention to the memory management aspects.

PDO Driver How-To
Preparation and Housekeeping
PDO Driver How-To


Preparation and Housekeeping

Source directory layout

The source directory for a typical PDO driver is laid out as follows, where SKEL represents a shortened form of the name of the database that the driver is going to connect to. Even though SKEL is presented here in uppercase (for clarity), the convention is to use lowercase characters.

pdo_SKEL/
  config.m4                  # unix build script
  config.w32                 # win32 build script
  CREDITS
  package.xml                # meta information about the package
  pdo_SKEL.c                 # standard PHP extension glue
  php_pdo_SKEL.h
  php_pdo_SKEL_int.h         # driver private header
  SKEL_dbh.c                 # contains the implementation of the PDO driver interface
  SKEL_stmt.c                # contains the implementation of the PDO statement interface
  tests/

The contents of these files are defined later in this document.

Creating a skeleton

The easiest way to get started is to use the ext_skel shell script found in the PHP build tree in the ext directory. This will build a skeleton directory containing a lot of the files listed above. It can be build by executing the following command from within the ext directory:

./ext_skel --extname=pdo_SKEL

This will generate a directory called pdo_SKEL containing the skeleton files that you can then modify. This directory should then be moved out of the php extension directory. PDO is a PECL extension and should not be included in the standard extension directory. As long as you have PHP and PDO installed, you should be able to build from any directory.

Standard Includes

Build Specific Headers

The header file config.h is generated by the configure process for the platform for the which the driver is being built. If this header is present, the HAVE_CONFIG_H compiler variable is set. This variable should be tested for and if set, the file config.h should be included in the compilation unit.

PHP Headers

The following standard public php headers should be included in each source module:

  1. php.h

  2. php_ini.h

  3. ext/standard/info.h

PDO Interface Headers

The following standard public PDO header files are also included in each source module:

pdo/php_pdo.h

This header file contains definitions of the initialization and shutdown functions in the main driver as well as definitions of global PDO variables.

pdo/php_pdo_driver.h

This header contains the types and API contracts that are used to write a PDO driver. It also contains method signature for calling back into the PDO layer and registering/unregistering your driver with PDO. Most importantly, this header file contains the type definitions for PDO database handles and statements. The two main structures a driver has to deal with, pdo_dbh_t and pdo_stmt_t, are described in more detail in Appendix A and B.

Driver Specific Headers

The typical PDO driver has two header files that are specific to the database implementation. This does not preclude the use of more depending on the implementation. The following two headers are, by convention, standard:

php_pdo_SKEL.h

This header file is virtually an exact duplicate in functionality and content of the previously defined pdo/php_pdo.h that has been specifically tailored for your database. If your driver requires the use of global variables they should be defined using the ZEND_BEGIN_MODULE_GLOBALS and ZEND_END_MODULE_GLOBALS macros. Macros are then used to access these variables. This macro is usually named PDO_SKEL_G(v) where v is global variable to be accessed. Consult the Zend programmer documentation for more information.

php_pdo_SKEL_int.h

This header file typically contains type definitions and function declarations specific to the driver implementation. It also should contain the db specific definitions of a pdo_SKEL_handle and pdo_SKEL_stmt structures. These are the names of the private data structures that are then referenced by the driver_data members of the handle and statement structures.

Optional Headers

Depending on the implementation details for a particular driver it may be necessary to include the following header:

#include <zend_exceptions.h>
Prerequisites
Fleshing out your skeleton
PDO Driver How-To


Fleshing out your skeleton

Major Structures and Attributes

The major structures, pdo_dbh_t and pdo_stmt_t are defined and explained in Appendix A and B respectively. Database and Statement attributes are defined in Appendix C. Error handling is explained in Appendix D.

pdo_SKEL.c: PHP extension glue

function entries

static function_entry pdo_SKEL_functions[] = {
  { NULL, NULL, NULL }
};

This structure is used to register functions into the global php function namespace. PDO drivers should try to avoid doing this, so it is recommended that you leave this structure initialized to NULL, as shown in the synopsis above.

Module entry

/* {{{ pdo_SKEL_module_entry */
#if ZEND_EXTENSION_API_NO >= 220050617
static zend_module_dep pdo_SKEL_deps[] = {
    ZEND_MOD_REQUIRED("pdo")
    {NULL, NULL, NULL}
};
#endif
/* }}} */

zend_module_entry pdo_SKEL_module_entry = {
#if ZEND_EXTENSION_API_NO >= 220050617
    STANDARD_MODULE_HEADER_EX, NULL,
    pdo_SKEL_deps,
#else
    STANDARD_MODULE_HEADER,
#endif
    "pdo_SKEL",
    pdo_SKEL_functions,
    PHP_MINIT(pdo_SKEL),
    PHP_MSHUTDOWN(pdo_SKEL),
    NULL,
    NULL,
    PHP_MINFO(pdo_SKEL),
    PHP_PDO_<DB>_MODULE_VERSION,
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_PDO_<DB>
ZEND_GET_MODULE(pdo_db)
#endif

A structure of type zend_module_entry called pdo_SKEL_module_entry must be declared and should include reference to the pdo_SKEL_functions table defined previously.

Standard PHP Module Extension Functions

PHP_MINIT_FUNCTION
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(pdo_SKEL)
{
    return php_pdo_register_driver(&pdo_SKEL_driver);
}
/* }}} */

This standard PHP extension function should be used to register your driver with the PDO layer. This is done by calling the php_pdo_register_driver() function passing a pointer to a structure of type pdo_driver_t typically named pdo_SKEL_driver. A pdo_driver_t contains a header that is generated using the PDO_DRIVER_HEADER(SKEL) macro and pdo_SKEL_handle_factory() function pointer. The actual function is described during the discussion of the SKEL_dbh.c unit.

PHP_MSHUTDOWN_FUNCTION
/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(pdo_SKEL)
{
    php_pdo_unregister_driver(&pdo_SKEL_driver);
    return SUCCESS;
}
/* }}} */

This standard PHP extension function is used to unregister your driver from the PDO layer. This is done by calling the php_pdo_unregister_driver() function, passing the same pdo_SKEL_driver structure that was passed in the init function above.

PHP_MINFO_FUNCTION

This is again a standard PHP extension function. Its purpose is to display information regarding the module when the phpinfo() is called from a script. The convention is to display the version of the module and also what version of the db you are dependent on, along with any other configuration style information that might be relevant.

SKEL_driver.c: Driver implementation

This unit implements all of the database handling methods that support the PDO database handle object. It also contains the error fetching routines. All of these functions will typically need to access the global variable pool. Therefore, it is necessary to use the Zend macro TSRMLS_DC macro at the end of each of these statements. Consult the Zend programmer documentation for more information on this macro.

pdo_SKEL_error

static int pdo_SKEL_error(pdo_dbh_t *dbh,
  pdo_stmt_t *stmt, const char *file, int line TSRMLS_DC)

The purpose of this function is to be used as a generic error handling function within the driver. It is called by the driver when an error occurs within the driver. If an error occurs that is not related to SQLSTATE, the driver should set either dbh->error_code or stmt->error_code to an SQLSTATE that most closely matches the error or the generic SQLSTATE error "HY000". The file pdo_sqlstate.c in the PDO source contains a table of commonly used SQLSTATE codes that the PDO code explicitly recognizes. This setting of the error code should be done prior to calling this function.; This function should set the global pdo_err variable to the error found in either the dbh or the stmt (if the variable stmt is not NULL).

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the current statement or NULL. If NULL, the error is derived by error code found in the dbh.

file

The source file where the error occurred or NULL if not available.

line

The line number within the source file if available.

If the dbh member methods is NULL (which implies that the error is being raised from within the PDO constructor), this function should call the zend_throw_exception_ex() function otherwise it should return the error code. This function is usually called using a helper macro that customizes the calling sequence for either database handling errors or statement handling errors.

Przykład #1 Example macros for invoking pdo_SKEL_error

#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)
#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)

For more info on error handling, see Error handling.

Informacja:

Despite being documented here, the PDO driver interface does not specify that this function be present; it is merely a convenient way to handle errors, and it just happens to be equally convenient for the majority of database client library APIs to structure your driver implementation in this way.

pdo_SKEL_fetch_error_func

static int pdo_SKEL_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt,
    zval *info TSRMLS_DC)

The purpose of this function is to obtain additional information about the last error that was triggered. This includes the driver specific error code and a human readable string. It may also include additional information if appropriate. This function is called as a result of the PHP script calling the PDO::errorInfo() method.

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the most current statement or NULL. If NULL, the error translated is derived by error code found in the dbh.

info

A hash table containing error codes and messages.

The error_func should return two pieces of information as successive array elements. The first item is expected to be a numeric error code, the second item is a descriptive string. The best way to set this item is by using add_next_index. Note that the type of the first argument need not be long; use whichever type most closely matches the error code returned by the underlying database API.

/* now add the error information. */
/* These need to be added in a specific order */
add_next_index_long(info, error_code);   /* driver specific error code */
add_next_index_string(info, message, 0); /* readable error message */

This function should return 1 if information is available, 0 if the driver does not have additional info.

SKEL_handle_closer

static int SKEL_handle_closer(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to close an open database.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to close the open database. PDO ignores the return value from this function.

SKEL_handle_preparer

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)

This function will be called by PDO in response to PDO::query() and PDO::prepare() calls from the PHP script. The purpose of the function is to prepare raw SQL for execution, storing whatever state is appropriate into the stmt that is passed in.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

Stmt

Pointer to the returned statement or NULL if an error occurs.

driver_options

Any driver specific/defined options.

This function is essentially the constructor for a stmt object. This function is responsible for processing statement options, and setting driver-specific option fields in the pdo_stmt_t structure.

PDO does not process any statement options on the driver's behalf before calling the preparer function. It is your responsibility to process them before you return, raising an error for any unknown options that are passed.

One very important responsibility of this function is the processing of SQL statement parameters. At the time of this call, PDO does not know if your driver supports binding parameters into prepared statements, nor does it know if it supports named or positional parameter naming conventions.

Your driver is responsible for setting stmt->supports_placeholders as appropriate for the underlying database. This may involve some run-time determination on the part of your driver, if this setting depends on the version of the database server to which it is connected. If your driver doesn't directly support both named and positional parameter conventions, you should use the pdo_parse_params() API to have PDO rewrite the query to take advantage of the support provided by your database.

Przykład #2 Using pdo_parse_params

int ret;
    char *nsql = NULL;
    int nsql_len = 0;

    /* before we prepare, we need to peek at the query; if it uses named parameters,
     * we want PDO to rewrite them for us */
    stmt->supports_placeholders = PDO_PLACEHOLDER_POSITIONAL;
    ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);

    if (ret == 1) {
        /* query was re-written */
        sql = nsql;
    } else if (ret == -1) {
        /* couldn't grok it */
        strcpy(dbh->error_code, stmt->error_code);
        return 0;
    }

    /* now proceed to prepare the query in "sql" */

Possible values for supports_placeholders are: PDO_PLACEHOLDER_NAMED, PDO_PLACEHOLDER_POSITIONAL and PDO_PLACEHOLDER_NONE. If the driver doesn't support prepare statements at all, then this function should simply allocate any state that it might need, and then return:

Przykład #3 Implementing preparer for drivers that don't support native prepared statements

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
    long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
{
    pdo_SKEL_db_handle *H = (pdo_SKEL_db_handle *)dbh->driver_data;
    pdo_SKEL_stmt *S = ecalloc(1, sizeof(pdo_SKEL_stmt));

    S->H = H;
    stmt->driver_data = S;
    stmt->methods = &SKEL_stmt_methods;
    stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;

    return 1;
}

This function returns 1 on success or 0 on failure.

SKEL_handle_doer

static long SKEL_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)

This function will be called by PDO to execute a raw SQL statement. No pdo_stmt_t is created.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

This function returns 1 on success or 0 on failure.

SKEL_handle_quoter

static int SKEL_handle_quoter(pdo_dbh_t *dbh, const char *unquoted,
  int unquoted_len, char **quoted, int quoted_len, enum pdo_param_type param_type TSRMLS_DC)

This function will be called by PDO to turn an unquoted string into a quoted string for use in a query.

dbh

Pointer to the database handle initialized by the handle factory

unquoted

Pointer to a character string containing the string to be quoted.

unquoted_len

The length of the string to be quoted.

quoted

Pointer to the address where a pointer to the newly quoted string will be returned.

quoted_len

The length of the new string.

param_type

A driver specific hint for driver that have alternate quoting styles

This function is called in response to a call to PDO::quote() or when the driver has set supports_placeholder to PDO_PLACEHOLDER_NONE. The purpose is to quote a parameter when building SQL statements.

If your driver does not support native prepared statements, implementation of this function is required.

This function returns 1 if the quoting process reformatted the string, and 0 if it was not necessary to change the string. The original string will be used unchanged with a 0 return.

SKEL_handle_begin

static int SKEL_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to begin a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to begin a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_commit

static int SKEL_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to end a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to commit a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_rollback

static int SKEL_handle_rollback( pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to rollback a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to rollback a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_get_attribute

static int SKEL_handle_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)

This function will be called by PDO to retrieve a database attribute.

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

return_value

The returned value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to supply this function. PDO driver handles the PDO_ATTR_PERSISTENT, PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.

SKEL_handle_set_attribute

static int SKEL_handle_set_attribute(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to set a database attribute, usually in response to a script calling PDO::setAttribute().

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

val

The new value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to provide this function if it does not need to support additional attributes. The PDO driver handles the PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.

SKEL_handle_last_id

static char * SKEL_handle_last_id(pdo_dbh_t *dbh, const char *name, unsigned int len TSRMLS_DC)

This function will be called by PDO to retrieve the ID of the last inserted row.

dbh

Pointer to the database handle initialized by the handle factory

name

string representing a table or sequence name.

len

the length of the name parameter.

This function returns a character string containing the id of the last inserted row on success or NULL on failure. This is an optional function.

SKEL_check_liveness

static int SKEL_check_liveness(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to test whether or not a persistent connection to a database is alive and ready for use.

dbh

Pointer to the database handle initialized by the handle factory

This function returns 1 if the database connection is alive and ready for use, otherwise it should return 0 to indicate failure or lack of support.

Informacja:

This is an optional function.

SKEL_get_driver_methods

static function_entry *SKEL_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)

This function will be called by PDO in response to a call to any method that is not a part of either the PDO or PDOStatement classes. It's purpose is to allow the driver to provide additional driver specific methods to those classes.

dbh

Pointer to the database handle initialized by the handle factory

kind

One of the following:

PDO_DBH_DRIVER_METHOD_KIND_DBH

Set when the method call was attempted on an instance of the PDO class. The driver should return a pointer a function_entry table for any methods it wants to add to that class, or NULL if there are none.

PDO_DBH_DRIVER_METHOD_KIND_STMT

Set when the method call was attempted on an instance of the PDOStatement class. The driver should return a pointer to a function_entry table for any methods it wants to add to that class, or NULL if there are none.

This function returns a pointer to the function_entry table requested, or NULL there are no driver specific methods.

SKEL_handle_factory

static int SKEL_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC)

This function will be called by PDO to create a database handle. For most databases this involves establishing a connection to the database. In some cases, a persistent connection may be requested, in other cases connection pooling may be requested. All of these are database/driver dependent.

dbh

Pointer to the database handle initialized by the handle factory

driver_options

An array of driver options, keyed by integer option number. See Database and Statement Attributes Table for a list of possible attributes.

This function should fill in the passed database handle structure with its driver specific information on success and return 1, otherwise it should return 0 to indicate failure.

PDO processes the AUTOCOMMIT and PERSISTENT driver options before calling the handle_factory. It is the handle factory's responsibility to process other options.

Driver method table

A static structure of type pdo_dbh_methods named SKEL_methods must be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.

pdo_SKEL_driver

A structure of type pdo_driver_t named pdo_SKEL_driver should be declared. The PDO_DRIVER_HEADER(SKEL) macro should be used to declare the header and the function pointer to the handle factory function should set.

SKEL_statement.c: Statement implementation

This unit implements all of the database statement handling methods that support the PDO statement object.

SKEL_stmt_dtor

static int SKEL_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to destroy a previously constructed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This should do whatever is necessary to free up any driver specific storage allocated for the statement. The return value from this function is ignored.

SKEL_stmt_execute

static int SKEL_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to execute the prepared SQL statement in the passed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_fetch

static int SKEL_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori,
   long offset TSRMLS_DC)

This function will be called by PDO to fetch a row from a previously executed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

ori

One of PDO_FETCH_ORI_xxx which will determine which row will be fetched.

offset

If ori is set to PDO_FETCH_ORI_ABS or PDO_FETCH_ORI_REL, offset represents the row desired or the row relative to the current position, respectively. Otherwise, this value is ignored.

The results of this fetch are driver dependent and the data is usually stored in the driver_data member of the pdo_stmt_t object. The ori and offset parameters are only meaningful if the statement represents a scrollable cursor. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_param_hook

static int SKEL_stmt_param_hook(pdo_stmt_t *stmt,
  struct pdo_bound_param_data *param, enum pdo_param_event event_type TSRMLS_DC)

This function will be called by PDO for handling of both bound parameters and bound columns.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

param

The structure describing either a statement parameter or a bound column.

event_type

The type of event to occur for this parameter, one of the following:

PDO_PARAM_EVT_ALLOC

Called when PDO allocates the binding. Occurs as part of PDOStatement::bindParam(), PDOStatement::bindValue() or as part of an implicit bind when calling PDOStatement::execute(). This is your opportunity to take some action at this point; drivers that implement native prepared statements will typically want to query the parameter information, reconcile the type with that requested by the script, allocate an appropriately sized buffer and then bind the parameter to that buffer. You should not rely on the type or value of the zval at param->parameter at this point in time.

PDO_PARAM_EVT_FREE

Called once per parameter as part of cleanup. You should release any resources associated with that parameter now.

PDO_PARAM_EXEC_PRE

Called once for each parameter immediately before calling SKEL_stmt_execute; take this opportunity to make any final adjustments ready for execution. In particular, you should note that variables bound via PDOStatement::bindParam() are only legal to touch now, and not any sooner.

PDO_PARAM_EXEC_POST

Called once for each parameter immediately after calling SKEL_stmt_execute; take this opportunity to make any post-execution actions that might be required by your driver.

PDO_PARAM_FETCH_PRE

Called once for each parameter immediately prior to calling SKEL_stmt_fetch.

PDO_PARAM_FETCH_POST

Called once for each parameter immediately after calling SKEL_stmt_fetch.

This hook will be called for each bound parameter and bound column in the statement. For ALLOC and FREE events, a single call will be made for each parameter or column. The param structure contains a driver_data field that the driver can use to store implementation specific information about each of the parameters.

For all other events, PDO may call you multiple times as the script issues PDOStatement::execute() and PDOStatement::fetch() calls.

If this is a bound parameter, the is_param flag in the param structure is set, otherwise the param structure refers to a bound column.

This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_describe_col

static int SKEL_stmt_describe_col(pdo_stmt_t *stmt, int colno TSRMLS_DC)

This function will be called by PDO to query information about a particular column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

The driver should populate the pdo_stmt_t member columns(colno) with the appropriate information. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_get_col_data

static int SKEL_stmt_get_col_data(pdo_stmt_t *stmt, int colno,
  char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC)

This function will be called by PDO to retrieve data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

ptr

Pointer to the retrieved data.

len

The length of the data pointed to by ptr.

caller_frees

If set, ptr should point to emalloc'd memory and the main PDO driver will free it as soon as it is done with it. Otherwise, it will be the responsibility of the driver to free any allocated memory as a result of this call.

The driver should return the resultant data and length of that data in the ptr and len variables respectively. It should be noted that the main PDO driver expects the driver to manage the lifetime of the data. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_set_attr

static int SKEL_stmt_set_attr(pdo_stmt_t *stmt, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to allow the setting of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

val

The new value for the attribute.

This function is driver dependent and allows the driver the capability to set database specific attributes for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional settable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.

SKEL_stmt_get_attr

static int SKEL_stmt_get_attr(pdo_stmt_t *stmt, long attr, zval
   *return_value TSRMLS_DC)

This function will be called by PDO to allow the retrieval of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

return_value

The returned value for the attribute.

This function is driver dependent and allows the driver the capability to retrieve a previously set database specific attribute for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional gettable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.

SKEL_stmt_get_col_meta

static int SKEL_stmt_get_col_meta(pdo_stmt_t *stmt, int colno,
   zval *return_value TSRMLS_DC)
Ostrzeżenie

This function is not well defined and is subject to change.

This function will be called by PDO to retrieve meta data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number for which data is to be retrieved.

return_value

Holds the returned meta data.

The driver author should consult the documentation for this function that can be found in the php_pdo_driver.h header as this will be the most current. This function returns 1 for success or 0 in the event of failure. The database driver does not need to provide this function.

Statement handling method table

A static structure of type pdo_stmt_methods named SKEL_stmt_methods should be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.

Preparation and Housekeeping
Building
PDO Driver How-To


Building

The build process is designed to work with PEAR (see » http://pear.php.net/ for more information about PEAR). There are two files that are used to assist in configuring your package for building. The first is config.m4 which is the autoconf configuration file for all platforms except Win32. The second is config.w32 which is a build configuration file for use on Win32. Skeleton files for these are built for you when you first set up your project. You then need to customize them to fit the needs of your project. Once you've customized your config files, you can build your driver using the following sequence of commands:

Before first build:

$ sudo pecl install PDO

For each build:

$ cd pdo_SKEL
$ phpize
$ ./configure
$ make
$ sudo make install

The process can then be repeated as necessary during the development process.

Fleshing out your skeleton
Testing
PDO Driver How-To


Testing

PDO has a set of "core" tests that all drivers should pass before being released. They're designed to run from the PHP source distribution, so running the tests for your driver requires moving things around a bit. The suggested procedure is to obtain the latest PHP 5.1 snapshot and perform the following step:

$ cp -r pdo_SKEL /path/to/php-5.1/ext

This will allow the test harness to run your tests. The next thing you need to do is create a test that will redirect into the PDO common core tests. The convention is to name this file common.phpt; it should be placed in the tests subdirectory that was created by ext_skel when you created your extension skeleton. The content of this file should look something like the following:

--TEST--
SKEL
--SKIPIF--
<?php # vim:ft=php
if (!extension_loaded('pdo_SKEL')) print 'skip'; ?>
--REDIRECTTEST--
if (false !== getenv('PDO_SKEL_TEST_DSN')) {
# user set them from their shell
   $config['ENV']['PDOTEST_DSN'] = getenv('PDO_SKEL_TEST_DSN');
   $config['ENV']['PDOTEST_USER'] = getenv('PDO_SKEL_TEST_USER');
   $config['ENV']['PDOTEST_PASS'] = getenv('PDO_SKEL_TEST_PASS');
   if (false !== getenv('PDO_SKEL_TEST_ATTR')) {
      $config['ENV']['PDOTEST_ATTR'] = getenv('PDO_SKEL_TEST_ATTR');
   }
   return $config;
}
return array(
   'ENV' => array(
           'PDOTEST_DSN' => 'SKEL:dsn',
           'PDOTEST_USER' => 'username',
           'PDOTEST_PASS' => 'password'
       ),
   'TESTS' => 'ext/pdo/tests'
   );

This will cause the common core tests to be run, passing the values of PDOTEST_DSN, PDOTEST_USER and PDOTEST_PASS to the PDO constructor as the dsn, username and password parameters. It will first check the environment, so that appropriate values can be passed in when the test harness is run, rather than hard-coding the database credentials into the test file.

The test harness can be invoked as follows:

$ cd /path/to/php-5.1
$ make TESTS=ext/pdo_SKEL/tests PDO_SKEL_TEST_DSN="skel:dsn" \
 PDO_SKEL_TEST_USER=user PDO_SKEL_TEST_PASS=pass test
Building
Packaging and distribution
PDO Driver How-To


Packaging and distribution

Creating a package

PDO drivers are released via PECL; all the usual rules for PECL extensions apply. Packaging is accomplished by creating a valid package.xml file and then running:

$ pecl package

This will create a tarball named PDO_SKEL-X.Y.Z.tgz.

Before releasing the package, you should test that it builds correctly; if you've made a mistake in your config.m4 or package.xml files, the package may not function correctly. You can test the build, without installing anything, using the following invocation:

$ pecl build package.xml

Once this is proven to work, you can test installation:

$ pecl package
$ sudo pecl install PDO_SKEL-X.Y.X.tgz

Full details about package.xml can be found in the PEAR Programmer's documentation (» http://pear.php.net/manual/).

Releasing the package

A PDO driver is released via the PHP Extension Community Library (PECL). Information about PECL can be found at » http://pecl.php.net/.

Testing
pdo_dbh_t definition
PDO Driver How-To


pdo_dbh_t definition

All fields should be treated as read-only by the driver, unless explicitly stated otherwise.

pdo_dbh_t

/* represents a connection to a database */
struct _pdo_dbh_t {
    /* driver specific methods */
    struct pdo_dbh_methods *methods;
*
/* driver specific data */
    void *driver_data;
**
/* credentials */
    char *username, *password;
***
/* if true, then data stored and pointed at by this handle must all be
     * persistently allocated */
    unsigned is_persistent:1;
****
/* if true, driver should act as though a COMMIT were executed between
     * each executed statement; otherwise, COMMIT must be carried out manually
     * */
    unsigned auto_commit:1;
*****
/* if true, the driver requires that memory be allocated explicitly for
     * the columns that are returned */
    unsigned alloc_own_columns:1;
******
/* if true, commit or rollBack is allowed to be called */
    unsigned in_txn:1;

    /* max length a single character can become after correct quoting */
    unsigned max_escaped_char_length:3;
*******
/* data source string used to open this handle */
    const char *data_source;
********
unsigned long data_source_len;

    /* the global error code. */
    pdo_error_type error_code;
*********
enum pdo_case_conversion native_case
**********
, desired_case;
};
*

The driver must set this during SKEL_handle_factory().

**

This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.

***

The username and password that were passed into the PDO constructor. The driver should use these values when it initiates a connection to the database.

****

If this is set to 1, then any data that is referenced by the dbh, including whatever structure your driver allocates, MUST be allocated persistently. This is easy to achieve; rather than using the usual emalloc() simply use pemalloc() and pass the value of this flag as the last parameter. Failure to use the appropriate kind of memory can lead to serious memory faults, resulting (in the best case) a hard crash, and in the worst case, an exploitable memory problem.

If, for whatever reason, your driver is not suitable to run persistently, you MUST check this flag in your SKEL_handle_factory() and raise an appropriate error.

*****

You should check this value in your SKEL_handle_doer() and SKEL_stmt_execute() functions; if it evaluates to true, you must attempt to commit the query now. Most database implementations offer an auto-commit mode that handles this automatically.

******

If your database client library API operates by fetching data into a caller-supplied buffer, you should set this flag to 1 during your SKEL_handle_factory(). When set, PDO will call your SKEL_stmt_describer() earlier than it would otherwise. This early call allows you to determine those buffer sizes and issue appropriate calls to the database client library.

If your database client library API simply returns pointers to its own internal buffers for you to copy after each fetch call, you should leave this value set to 0.

*******

If your driver doesn't support native prepared statements (supports_placeholders is set to PDO_PLACEHOLDER_NONE), you must set this value to the maximum length that can be taken up by a single character when it is quoted by your SKEL_handle_quoter() function. This value is used to calculate the amount of buffer space required when PDO executes the statement.

********

This holds the value of the DSN that was passed into the PDO constructor. If your driver implementation needed to modify the DSN for whatever reason, it should update this member during SKEL_handle_factory(). Modifying this member should be avoided. If you do change it, you must ensure that data_source_len is also correct.

*********

Whenever an error occurs during a call to one of your driver methods, you should set this member to the SQLSTATE code that best describes the error and return an error. In this HOW-TO, the suggested practice is to call SKEL_handle_error() when an error is detected, and have it set the error code.

**********

Your driver should set this during SKEL_handle_factory(); the value should reflect how the database returns the names of the columns in result sets. If the name matches the case that was used in the query, set it to PDO_CASE_NATURAL (this is actually the default). If the column names are always returned in upper case, set it to PDO_CASE_UPPER. If the column names are always returned in lower case, set it to PDO_CASE_LOWER. The value you set is used to determine if PDO should perform case folding when the user sets the PDO_ATTR_CASE attribute.

Packaging and distribution
pdo_stmt_t definition
PDO Driver How-To


pdo_stmt_t definition

All fields should be treated as read-only unless explicitly stated otherwise.

pdo_stmt_t

/* represents a prepared statement */
struct _pdo_stmt_t {
    /* driver specifics */
    struct pdo_stmt_methods *methods;
*
void *driver_data;
**
/* if true, we've already successfully executed this statement at least
     * once */
    unsigned executed:1;
***
/* if true, the statement supports placeholders and can implement
     * bindParam() for its prepared statements, if false, PDO should
     * emulate prepare and bind on its behalf */
    unsigned supports_placeholders:2;
****
/* the number of columns in the result set; not valid until after
     * the statement has been executed at least once.  In some cases, might
     * not be valid until fetch (at the driver level) has been called at least once.
     * */
    int column_count;
*****
struct pdo_column_data *columns;
******
/* points at the dbh that this statement was prepared on */
    pdo_dbh_t *dbh;

    /* keep track of bound input parameters.  Some drivers support
     * input/output parameters, but you can't rely on that working */
    HashTable *bound_params;
    /* When rewriting from named to positional, this maps positions to names */
    HashTable *bound_param_map;
    /* keep track of PHP variables bound to named (or positional) columns
     * in the result set */
    HashTable *bound_columns;

    /* not always meaningful */
    long row_count;

    /* used to hold the statement's current query */
    char *query_string;
    int query_stringlen;

    /* the copy of the query with expanded binds ONLY for emulated-prepare drivers */
    char *active_query_string;
    int active_query_stringlen;

    /* the cursor specific error code. */
    pdo_error_type error_code;

    /* used by the query parser for driver specific
     * parameter naming (see pgsql driver for example) */
    const char *named_rewrite_template;
};
* | The driver must set this during SKEL_handle_preparer().
** | This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.
*** | This is set by PDO after the statement has been executed for the first time. Your driver can inspect this value to determine if it can skip one-time actions as an optimization.
**** | Discussed in more detail in SKEL_handle_preparer.
***** | Your driver is responsible for setting this field to the number of columns available in a result set. This is usually set during SKEL_stmt_execute() but with some database implementations, the column count may not be available until SKEL_stmt_fetch() has been called at least once. Drivers that implement SKEL_stmt_next_rowset() should update the column count when a new rowset is available.
****** | PDO will allocate this field based on the value that you set for the column count. You are responsible for populating each column during SKEL_stmt_describe(). You must set the precision, maxlen, name, namelen and param_type members for each column. The name is expected to be allocated using emalloc(); PDO will call efree() at the appropriate time.
pdo_dbh_t definition
Constants
PDO Driver How-To


Constants

Database and Statement Attributes Table

Attribute

Valid value(s)

PDO_ATTR_AUTOCOMMIT

BOOL

TRUE if autocommit is set, FALSE otherwise.

dbh->auto_commit contains value. Processed by PDO directly.

PDO_ATTR_PREFETCH

LONG

Value of the prefetch size in drivers that support it.

PDO_ATTR_TIMEOUT

LONG

How long to wait for a db operation before timing out.

PDO_ATTR_ERRMODE

LONG

Processed and handled by PDO

PDO_ATTR_SERVER_VERSION

STRING

The "human-readable" string representing the Server/Version this driver is currently connected to.

PDO_ATTR_CLIENT_VERSION

STRING

The "human-readable" string representing the Client/Version this driver supports.

PDO_ATTR_SERVER_INFO

STRING

The "human-readable" description of the Server.

PDO_ATTR_CONNECTION_STATUS

LONG

Values not yet defined

PDO_ATTR_CASE

LONG

Processed and handled by PDO.

PDO_ATTR_CURSOR_NAME

STRING

String representing the name for a database cursor for use in "where current in <name>" SQL statements.

PDO_ATTR_CURSOR

LONG

PDO_CURSOR_FWDONLY

Forward only cursor

PDO_CURSOR_SCROLL

Scrollable cursor

The values for the attributes above are all defined in terms of the Zend API. The Zend API contains macros that can be used to convert a *zval to a value. These macros are defined in the Zend header file, zend_API.h in the Zend directory of your PHP build directory. Some of these attributes can be used with the statement attribute handlers such as the PDO_ATTR_CURSOR and PDO_ATTR_CURSOR_NAME. See the statement attribute handling functions for more information.

pdo_stmt_t definition
Error handling
PDO Driver How-To


Error handling

Error handling is implemented using a hand-shaking protocol between PDO and the database driver code. The database driver code signals PDO that an error has occurred via a failure (0) return from any of the interface functions. If a zero is returned, set the field error_code in the control block appropriate to the context (either the pdo_dbh_t or pdo_stmt_t block). In practice, it is probably a good idea to set the field in both blocks to the same value to ensure the correct one is getting used.

The error_mode field is a six-byte field containing a 5 character ASCIIZ SQLSTATE identifier code. This code drives the error message process. The SQLSTATE code is used to look up an error message in the internal PDO error message table (see pdo_sqlstate.c for a list of error codes and their messages). If the code is not known to PDO, a default "Unknown Message" value will be used.

In addition to the SQLSTATE code and error message, PDO will call the driver-specific fetch_err() routine to obtain supplemental data for the particular error condition. This routine is passed an array into which the driver may place additional information. This array has slot positions assigned to particular types of supplemental info:

  1. A native error code. This will frequently be an error code obtained from the database API.

  2. A descriptive string. This string can contain any additional information related to the failure. Database drivers typically include information such as an error message, code location of the failure, and any additional descriptive information the driver developer feels worthy of inclusion. It is generally a good idea to include all diagnostic information obtainable from the database interface at the time of the failure. For driver-detected errors (such as memory allocation problems), the driver developer can define whatever error information that seems appropriate.

Constants
Extension FAQs
PDO Driver How-To


Extension FAQs

Error handling
Zend Engine 2 API reference
Rdzeń PHP: Poradnik hackerów o Zend Engine


Zend Engine 2 API reference

Extension FAQs
Zend Engine 2 opcode list
Rdzeń PHP: Poradnik hackerów o Zend Engine


Zend Engine 2 API reference
Opcodes
Rdzeń PHP: Poradnik hackerów o Zend Engine
PHP Manual

Zend Engine 2 opcode list

Spis treści

  • Opcodes

Opcodes

This page lists and partially documents all the opcodes generated by Zend Engine 2 when it parses PHP files. Opcodes may be dumped for a given PHP file using the vld extension (see » http://pecl.php.net/package/vld).

Zend Engine 2 API reference
Opcodes
Rdzeń PHP: Poradnik hackerów o Zend Engine


Opcodes

Spis treści

  • Opcode list
  • ADD
  • ADD_ARRAY_ELEMENT
  • ADD_CHAR
  • ADD_INTERFACE
  • ADD_STRING
  • ADD_VAR
  • ASSIGN
  • ASSIGN_ADD
  • ASSIGN_BW_AND
  • ASSIGN_BW_OR
  • ASSIGN_BW_XOR
  • ASSIGN_CONCAT
  • ASSIGN_DIM
  • ASSIGN_DIV
  • ASSIGN_MOD
  • ASSIGN_MUL
  • ASSIGN_OBJ
  • ASSIGN_REF
  • ASSIGN_SL
  • ASSIGN_SR
  • ASSIGN_SUB
  • BEGIN_SILENCE
  • BOOL
  • BOOL_NOT
  • BOOL_XOR
  • BRK
  • BW_AND
  • BW_NOT
  • BW_OR
  • BW_XOR
  • CASE
  • CAST
  • CATCH
  • CLONE
  • CONCAT
  • DECLARE_CLASS
  • DECLARE_FUNCTION
  • DECLARE_INHERITED_CLASS
  • DIV
  • DO_FCALL
  • DO_FCALL_BY_NAME
  • ECHO
  • END_SILENCE
  • EXIT
  • EXT_FCALL_BEGIN
  • EXT_FCALL_END
  • EXT_NOP
  • EXT_STMT
  • FETCH_CLASS
  • FETCH_CONSTANT
  • FETCH_DIM_FUNC_ARG
  • FETCH_DIM_IS
  • FETCH_DIM_R
  • FETCH_DIM_RW
  • FETCH_DIM_TMP_VAR
  • FETCH_DIM_UNSET
  • FETCH_DIM_W
  • FETCH_FUNC_ARG
  • FETCH_IS
  • FETCH_OBJ_FUNC_ARG
  • FETCH_OBJ_IS
  • FETCH_OBJ_R
  • FETCH_OBJ_RW
  • FETCH_OBJ_UNSET
  • FETCH_OBJ_W
  • FETCH_R
  • FETCH_RW
  • FETCH_UNSET
  • FETCH_W
  • FE_FETCH
  • FE_RESET
  • FREE
  • HANDLE_EXCEPTION
  • INCLUDE_OR_EVAL
  • INIT_ARRAY
  • INIT_FCALL_BY_NAME
  • INIT_METHOD_CALL
  • INIT_STATIC_METHOD_CALL
  • INIT_STRING
  • INSTANCEOF
  • ISSET_ISEMPTY_DIM_OBJ
  • ISSET_ISEMPTY_PROP_OBJ
  • ISSET_ISEMPTY_VAR
  • IS_EQUAL
  • IS_IDENTICAL
  • IS_NOT_EQUAL
  • IS_NOT_IDENTICAL
  • IS_SMALLER
  • IS_SMALLER_OR_EQUAL
  • JMPNZ
  • JMPNZ_EX
  • JMPZ
  • JMPZNZ
  • JMPZ_EX
  • MOD
  • MUL
  • NEW
  • NOP
  • POST_DEC
  • POST_DEC_OBJ
  • POST_INC
  • POST_INC_OBJ
  • PRE_DEC
  • PRE_DEC_OBJ
  • PRE_INC
  • PRE_INC_OBJ
  • PRINT
  • QM_ASSIGN
  • RAISE_ABSTRACT_ERROR
  • RECV
  • RECV_INIT
  • RETURN
  • SEND_REF
  • SEND_VAL
  • SEND_VAR
  • SEND_VAR_NO_REF
  • SL
  • SR
  • SUB
  • SWITCH_FREE
  • THROW
  • TICKS
  • UNSET_DIM
  • UNSET_OBJ
  • UNSET_VAR
  • USER_OPCODE
  • VERIFY_ABSTRACT_CLASS
Zend Engine 2 opcode list
Opcode list
Zend Engine 2 opcode list


Opcode list

Opcode list
Number | Name | Has sample code?
0 | NOP | yes
1 | ADD | yes
2 | SUB | yes
3 | MUL | yes
4 | DIV | yes
5 | MOD | yes
6 | SL | yes
7 | SR | yes
8 | CONCAT | yes
9 | BW_OR | yes
10 | BW_AND | yes
11 | BW_XOR | yes
12 | BW_NOT | yes
13 | BOOL_NOT | yes
14 | BOOL_XOR | yes
15 | IS_IDENTICAL | yes
16 | IS_NOT_IDENTICAL | yes
17 | IS_EQUAL | yes
18 | IS_NOT_EQUAL | yes
19 | IS_SMALLER | yes
20 | IS_SMALLER_OR_EQUAL | yes
21 | CAST | yes
22 | QM_ASSIGN | yes
23 | ASSIGN_ADD | yes
24 | ASSIGN_SUB | yes
25 | ASSIGN_MUL | yes
26 | ASSIGN_DIV | yes
27 | ASSIGN_MOD | yes
28 | ASSIGN_SL | yes
29 | ASSIGN_SR | yes
30 | ASSIGN_CONCAT | yes
31 | ASSIGN_BW_OR | yes
32 | ASSIGN_BW_AND | yes
33 | ASSIGN_BW_XOR | yes
34 | PRE_INC | yes
35 | PRE_DEC | yes
36 | POST_INC | yes
37 | POST_DEC | yes
38 | ASSIGN | yes
39 | ASSIGN_REF | yes
40 | ECHO | yes
41 | PRINT | yes
42 | not documented | no
43 | JMPZ | yes
44 | JMPNZ | yes
45 | JMPZNZ | yes
46 | JMPZ_EX | yes
47 | JMPNZ_EX | yes
48 | CASE | yes
49 | SWITCH_FREE | yes
50 | BRK | yes
51 | not documented | no
52 | BOOL | yes
53 | INIT_STRING | yes
54 | ADD_CHAR | yes
55 | ADD_STRING | yes
56 | ADD_VAR | yes
57 | BEGIN_SILENCE | yes
58 | END_SILENCE | yes
59 | INIT_FCALL_BY_NAME | yes
60 | DO_FCALL | yes
61 | DO_FCALL_BY_NAME | yes
62 | RETURN | yes
63 | RECV | yes
64 | RECV_INIT | yes
65 | SEND_VAL | yes
66 | SEND_VAR | yes
67 | SEND_REF | yes
68 | NEW | yes
69 | not documented | no
70 | FREE | yes
71 | INIT_ARRAY | yes
72 | ADD_ARRAY_ELEMENT | yes
73 | INCLUDE_OR_EVAL | yes
74 | UNSET_VAR | yes
75 | UNSET_DIM | yes
76 | UNSET_OBJ | yes
77 | FE_RESET | yes
78 | FE_FETCH | yes
79 | EXIT | yes
80 | FETCH_R | yes
81 | FETCH_DIM_R | yes
82 | FETCH_OBJ_R | yes
83 | FETCH_W | yes
84 | FETCH_DIM_W | yes
85 | FETCH_OBJ_W | yes
86 | FETCH_RW | yes
87 | FETCH_DIM_RW | yes
88 | FETCH_OBJ_RW | yes
89 | FETCH_IS | yes
90 | FETCH_DIM_IS | no
91 | FETCH_OBJ_IS | no
92 | FETCH_FUNC_ARG | yes
93 | FETCH_DIM_FUNC_ARG | yes
94 | FETCH_OBJ_FUNC_ARG | yes
95 | FETCH_UNSET | no
96 | FETCH_DIM_UNSET | no
97 | FETCH_OBJ_UNSET | no
98 | FETCH_DIM_TMP_VAR | yes
99 | FETCH_CONSTANT | yes
100 | not documented | no
101 | EXT_STMT | no
102 | EXT_FCALL_BEGIN | no
103 | EXT_FCALL_END | no
104 | EXT_NOP | no
105 | TICKS | yes
106 | SEND_VAR_NO_REF | no
107 | CATCH | yes
108 | THROW | yes
109 | FETCH_CLASS | yes
110 | CLONE | yes
111 | not documented | no
112 | INIT_METHOD_CALL | yes
113 | INIT_STATIC_METHOD_CALL | yes
114 | ISSET_ISEMPTY_VAR | yes
115 | ISSET_ISEMPTY_DIM_OBJ | yes
116 | not documented | no
117 | not documented | no
118 | not documented | no
119 | not documented | no
120 | not documented | no
121 | not documented | no
122 | not documented | no
123 | not documented | no
124 | not documented | no
125 | not documented | no
126 | not documented | no
127 | not documented | no
128 | not documented | no
129 | not documented | no
130 | not documented | no
131 | not documented | no
132 | PRE_INC_OBJ | yes
133 | PRE_DEC_OBJ | yes
134 | POST_INC_OBJ | yes
135 | POST_DEC_OBJ | yes
136 | ASSIGN_OBJ | yes
137 | not documented | no
138 | INSTANCEOF | yes
139 | DECLARE_CLASS | yes
140 | DECLARE_INHERITED_CLASS | yes
141 | DECLARE_FUNCTION | yes
142 | RAISE_ABSTRACT_ERROR | yes
143 | not documented | no
144 | ADD_INTERFACE | no
145 | not documented | no
146 | VERIFY_ABSTRACT_CLASS | no
147 | ASSIGN_DIM | yes
148 | ISSET_ISEMPTY_PROP_OBJ | yes
149 | HANDLE_EXCEPTION | yes
150 | USER_OPCODE | no
152 | ZEND_JMP_SET | no
153 | ZEND_DECLARE_LAMBDA_FUNCTION | no
Opcodes
ADD
Opcodes


ADD

PHP code

<?php
/*
 * Adds "value1" to "value2" and stores the result into "result".
 * opcode number: 1
 */
echo 1 + 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | ADD |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
Opcode list
ADD_ARRAY_ELEMENT
Opcodes


ADD_ARRAY_ELEMENT

PHP code

<?php
/*
 * Add elem-value as an element to array-value
 * opcode number: 72
 */
$a = array(1,2,3);
print_r($a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'print_r'
8 | 6 | RETURN |  |  |  | 1
ADD
ADD_CHAR
Opcodes


ADD_CHAR

PHP code

<?php
/*
 * add character value2 to string value1 and store in result
 * opcode number: 54
 */
echo "hello\ world";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | ECHO |  |  |  | 'hello%5C+world'
7 | 1 | RETURN |  |  |  | 1
ADD_ARRAY_ELEMENT
ADD_INTERFACE
Opcodes


ADD_INTERFACE

PHP code

<?php
/*
 *
 * opcode number: 144
 * No sample PHP yet */
?>
ADD_CHAR
ADD_STRING
Opcodes


ADD_STRING

PHP code

<?php
/*
 * add string value2 to string value2 and store in result
 * opcode number: 55
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1
ADD_INTERFACE
ADD_VAR
Opcodes


ADD_VAR

PHP code

<?php
/*
 * add contents of variable in value2 to string value1 and store in result
 * opcode number: 56
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1
ADD_STRING
ASSIGN
Opcodes


ASSIGN

PHP code

<?php
/*
 * assigns value1 to result
 * opcode number: 38
 */
$a=1;
$a='a';
$a=new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !0,'a'
8 | 2 | ZEND_FETCH_CLASS |  |  | :2 | 'A'
 | 3 | NEW |  |  | $3 | :2
 | 4 | DO_FCALL_BY_NAME |  | 0 |  |
 | 5 | ASSIGN |  |  |  | !0,$3
9 | 6 | RETURN |  |  |  | 1
ADD_VAR
ASSIGN_ADD
Opcodes


ASSIGN_ADD

PHP code

<?php
/*
 * Add value1 to value2 and store in variable indicated by value1
 * opcode number: 23
 */
$a+=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_ADD |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1
ASSIGN
ASSIGN_BW_AND
Opcodes


ASSIGN_BW_AND

PHP code

<?php
/*
 * Performs binary AND on result and value1 and stores in variable indicated by result.
 * opcode number: 32
 */
$a &= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_AND |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1
ASSIGN_ADD
ASSIGN_BW_OR
Opcodes


ASSIGN_BW_OR

PHP code

<?php
/*
 * Performs binary OR on result and value1 and stores in variable indicated by result.
 * opcode number: 31
 */
$a |= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_OR |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1
ASSIGN_BW_AND
ASSIGN_BW_XOR
Opcodes


ASSIGN_BW_XOR

PHP code

<?php
/*
 * Performs binary XOR on result and value1and stores in variable indicated by result.
 * opcode number: 33
 */
$a ^= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_XOR |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1
ASSIGN_BW_OR
ASSIGN_CONCAT
Opcodes


ASSIGN_CONCAT

PHP code

<?php
/*
 * Concats string values result and value1 and store in variable indicated by result
 * opcode number: 30
 */
$a .= 'z';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_CONCAT |  |  |  | !0,'z'
7 | 1 | RETURN |  |  |  | 1
ASSIGN_BW_XOR
ASSIGN_DIM
Opcodes


ASSIGN_DIM

PHP code

<?php
/*
 *
 * opcode number: 147
 */
$b = 1;
$a[1][2] = $b;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$b, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | FETCH_DIM_W |  |  | $1 | !1,1
 | 2 | ZEND_ASSIGN_DIM |  |  |  | $1,2
 | 3 | ZEND_OP_DATA |  |  |  | !0,$3
8 | 4 | RETURN |  |  |  | 1
ASSIGN_CONCAT
ASSIGN_DIV
Opcodes


ASSIGN_DIV

PHP code

<?php
/*
 * Divide result by value1and store in variable indicated by result.
 * opcode number: 26
 */
$a/=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_DIV |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1
ASSIGN_DIM
ASSIGN_MOD
Opcodes


ASSIGN_MOD

PHP code

<?php
/*
 * Perform result mod value1 and store in variable indicated by result
 * opcode number: 27
 */
$a %= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_MOD |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1
ASSIGN_DIV
ASSIGN_MUL
Opcodes


ASSIGN_MUL

PHP code

<?php
/*
 * Multiply result by value1 and store in variable indicated by result
 * opcode number: 25
 */
$a*=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_MUL |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1
ASSIGN_MOD
ASSIGN_OBJ
Opcodes


ASSIGN_OBJ

PHP code

<?php
/*
 *
 * opcode number: 136
 */
$obj->a = $otherobj;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj, !1=$otherobj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ASSIGN_OBJ |  |  |  | !0,'a'
 | 1 | ZEND_OP_DATA |  |  |  | !1
7 | 2 | RETURN |  |  |  | 1
ASSIGN_MUL
ASSIGN_REF
Opcodes


ASSIGN_REF

PHP code

<?php
/*
 * indicates that variable indicated by value1 is to be treated in the global scope for the remainder of the current scope.
 * opcode number: 39
 */
global $a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | FETCH_W | globallock |  | $0 | 'a'
 | 1 | ASSIGN_REF |  |  |  | !0,$0
7 | 2 | RETURN |  |  |  | 1
ASSIGN_OBJ
ASSIGN_SL
Opcodes


ASSIGN_SL

PHP code

<?php
/*
 * Shift result by value1 bits to left and store in variable indicated by result
 * opcode number: 28
 */
$a <<= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SL |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1
ASSIGN_REF
ASSIGN_SR
Opcodes


ASSIGN_SR

PHP code

<?php
/*
 * Shift result by value1 bits to right and store in variable indicated by result
 * opcode number: 29
 */
$a >>= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SR |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1
ASSIGN_SL
ASSIGN_SUB
Opcodes


ASSIGN_SUB

PHP code

<?php
/*
 * Subtract value1 from value2 and store in variable indicated by value1
 * opcode number: 24
 */
$a-=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SUB |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1
ASSIGN_SR
BEGIN_SILENCE
Opcodes


BEGIN_SILENCE

PHP code

<?php
/*
 * prepare to perform function call without displaying error messages
 * opcode number: 57
 */
/* Intentional file error */
$my_file = @file ('non_existent_file') or
   die ("error:'$php_errormsg'");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$my_file, !1=$php_errormsg

line | # | op | fetch | ext | return | operands
7 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | SEND_VAL |  |  |  | 'non_existent_file'
 | 2 | DO_FCALL |  | 1 |  | 'file'
 | 3 | END_SILENCE |  |  |  | ~0
 | 4 | ASSIGN |  |  | $2 | !0,$1
 | 5 | JMPNZ_EX |  |  | ~3 | $2,->11
8 | 6 | ADD_STRING |  |  | ~4 | 'error%3A%27'
 | 7 | ADD_VAR |  |  | ~4 | ~4,!1
 | 8 | ADD_CHAR |  |  | ~4 | ~4,39
 | 9 | EXIT |  |  |  | ~4
 | 10 | BOOL |  |  | ~3 | true
 | 11 | FREE |  |  |  | ~3
9 | 12 | RETURN |  |  |  | 1
ASSIGN_SUB
BOOL
Opcodes


BOOL

PHP code

<?php
/*
 * convert value1 to boolean and store in result??????????
 * opcode number: 52
 */
if (1 || 2 || 1) echo "foo";
//$a = true;
//if($a) echo "foo";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | JMPNZ_EX |  |  | ~0 | 1,->2
 | 1 | BOOL |  |  | ~0 | 2
 | 2 | JMPNZ_EX |  |  | ~0 | ~0,->4
 | 3 | BOOL |  |  | ~0 | 1
 | 4 | JMPZ |  |  |  | ~0,->7
 | 5 | ECHO |  |  |  | 'foo'
 | 6 | JMP |  |  |  | ->7
9 | 7 | RETURN |  |  |  | 1
BEGIN_SILENCE
BOOL_NOT
Opcodes


BOOL_NOT

PHP code

<?php
/*
 * Boolean (logical) not of "value"
 * opcode number: 13
 */
echo !1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BOOL_NOT |  |  | ~0 | 1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
BOOL
BOOL_XOR
Opcodes


BOOL_XOR

PHP code

<?php
/*
 * Boolean (logical) xor of value1
 * opcode number: 14
 */
echo 1 xor 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BOOL_XOR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
BOOL_NOT
BRK
Opcodes


BRK

PHP code

<?php
/*
 * ???  End of a case block exists the current switch block.  Followed by JMP?
 * opcode number: 50
 */
$x = 0;
while(1) {
    if($x == 0) break;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
7 | 1 | JMPZ |  |  |  | 1,->7
8 | 2 | IS_EQUAL |  |  | ~1 | !0,0
 | 3 | JMPZ |  |  |  | ~1,->6
 | 4 | BRK |  |  |  | 1
 | 5 | JMP |  |  |  | ->6
9 | 6 | JMP |  |  |  | ->1
10 | 7 | RETURN |  |  |  | 1
BOOL_XOR
BW_AND
Opcodes


BW_AND

PHP code

<?php
/*
 * Bit-wise and of value1 and value2
 * opcode number: 10
 */
echo 1&2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_AND |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
BRK
BW_NOT
Opcodes


BW_NOT

PHP code

<?php
/*
 * Bit-wise not of "value"
 * opcode number: 12
 */
echo ~15;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_NOT |  |  | ~0 | 15
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
BW_AND
BW_OR
Opcodes


BW_OR

PHP code

<?php
/*
 * Bit-wise or of value1 and value2
 * opcode number: 9
 */
echo 1|2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_OR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
BW_NOT
BW_XOR
Opcodes


BW_XOR

PHP code

<?php
/*
 * Bit-wise xor of value1 and value2
 * opcode number: 11
 */
echo 1^2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_XOR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
BW_OR
CASE
Opcodes


CASE

PHP code

<?php
/*
 * Set result to true if value1 equals value2.  The value2 must be a constant value?
 * opcode number: 48
 */
$i=0;
switch ($i) {
   case 0:
         echo "i=0";
         break;
   case 1:
         echo "i=1";
         break;
   case 2:
         echo "i=2";
         break;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
8 | 1 | CASE |  |  | ~1 | !0,0
 | 2 | JMPZ |  |  |  | ~1,->6
9 | 3 | ECHO |  |  |  | 'i%3D0'
10 | 4 | BRK |  |  |  | 1
11 | 5 | JMP |  |  |  | ->8
 | 6 | CASE |  |  | ~1 | !0,1
 | 7 | JMPZ |  |  |  | ~1,->11
12 | 8 | ECHO |  |  |  | 'i%3D1'
13 | 9 | BRK |  |  |  | 1
14 | 10 | JMP |  |  |  | ->13
 | 11 | CASE |  |  | ~1 | !0,2
 | 12 | JMPZ |  |  |  | ~1,->16
15 | 13 | ECHO |  |  |  | 'i%3D2'
16 | 14 | BRK |  |  |  | 1
17 | 15 | JMP |  |  |  | ->16
18 | 16 | RETURN |  |  |  | 1
BW_XOR
CAST
Opcodes


CAST

PHP code

<?php
/*
 * casts value1 as type value2 (?? Not certain about arguments ??)
 * opcode number: 21
 */
echo (int)1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | CAST |  |  | ~0 | 1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
CASE
CATCH
Opcodes


CATCH

PHP code

<?php
/*
 *
 * opcode number: 107
 */
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$error, !1=$e

line | # | op | fetch | ext | return | operands
7 | 0 | ASSIGN |  |  |  | !0,'Always+throw+this+error'
8 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'Exception'
 | 2 | NEW |  |  | $2 | :1
 | 3 | SEND_VAR |  |  |  | !0
 | 4 | DO_FCALL_BY_NAME |  | 1 |  |
 | 5 | ZEND_THROW |  | 0 |  | $2
11 | 6 | ECHO |  |  |  | 'Never+executed'
13 | 7 | JMP |  |  |  | ->15
 | 8 | ZEND_FETCH_CLASS |  |  | :4 | 'Exception'
 | 9 | ZEND_CATCH |  | 15 |  | $4,!1
14 | 10 | ECHO |  |  |  | 'Caught+exception%3A+'
 | 11 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'getMessage'
 | 12 | DO_FCALL_BY_NAME |  | 0 |  |
 | 13 | ECHO |  |  |  | $6
 | 14 | ECHO |  |  |  | '%0A'
18 | 15 | ECHO |  |  |  | 'Hello+World'
19 | 16 | RETURN |  |  |  | 1
CAST
CLONE
Opcodes


CLONE

PHP code

<?php
/*
 *
 * opcode number: 110
 */
$obj = new A();
$copy = clone $obj;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj, !1=$copy

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_CLONE |  |  | $4 | !0
 | 5 | ASSIGN |  |  |  | !1,$4
8 | 6 | RETURN |  |  |  | 1
CATCH
CONCAT
Opcodes


CONCAT

PHP code

<?php
/*
 * Concats string values string1 and string2
 * opcode number: 8
 */
echo "hello" . "world";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | CONCAT |  |  | ~0 | 'hello','world'
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
CLONE
DECLARE_CLASS
Opcodes


DECLARE_CLASS

PHP code

<?php
/*
 * Declare a class with the name of class-name as the implementation specified by ID.
 * opcode number: 139
 */
class A {
    function methodA(){
        echo "hello world";
    }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
11 | 1 | RETURN |  |  |  | 1

Function name: methodA

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ECHO |  |  |  | 'hello+world'
9 | 1 | RETURN |  |  |  | null
CONCAT
DECLARE_FUNCTION
Opcodes


DECLARE_FUNCTION

PHP code

<?php
/*
 *
 * opcode number: 141
 */
class A{
 function funcA(){
 }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | RETURN |  |  |  | 1

Function name: funcA

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | RETURN |  |  |  | null
DECLARE_CLASS
DECLARE_INHERITED_CLASS
Opcodes


DECLARE_INHERITED_CLASS

PHP code

<?php
/*
 *
 * opcode number: 140
 */
 if($b){
 class Foo {
  public static $my_static = 'foo';
  public function staticValue() {
    return self::$my_static;
  }
 }

 class Bar extends Foo {
  public function fooStatic() {
     echo parent::$my_static;
  }
 }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$b

line | # | op | fetch | ext | return | operands
6 | 0 | JMPZ |  |  |  | !0,->5
7 | 1 | ZEND_DECLARE_CLASS |  |  | $0 | '%00foo%2Fmnt%2Fworkspace%2Fws_phpscripts%2FPHPopcodes%2Fphpsamples%2FDECLARE_INHERITED_CLASS.php0xb7be503b','foo'
14 | 2 | ZEND_FETCH_CLASS |  |  | :1 | 'Foo'
 | 3 | ZEND_DECLARE_INHERITED_CLASS |  |  | $2 | '%00bar%2Fmnt%2Fworkspace%2Fws_phpscripts%2FPHPopcodes%2Fphpsamples%2FDECLARE_INHERITED_CLASS.php0xb7be50bc','bar'
19 | 4 | JMP |  |  |  | ->5
20 | 5 | RETURN |  |  |  | 1

Function name: staticValue

Compiled variables: !0=$my_static

line | # | op | fetch | ext | return | operands
10 | 0 | ZEND_FETCH_CLASS |  |  |  |
 | 1 | FETCH_R | staticmember |  | $1 | 'my_static'
 | 2 | RETURN |  |  |  | $1
11 | 3 | RETURN |  |  |  | null

Function name: fooStatic

Compiled variables: !0=$my_static

line | # | op | fetch | ext | return | operands
16 | 0 | ZEND_FETCH_CLASS |  |  | :0 |
 | 1 | FETCH_R | staticmember |  | $1 | 'my_static'
 | 2 | ECHO |  |  |  | $1
17 | 3 | RETURN |  |  |  | null
DECLARE_FUNCTION
DIV
Opcodes


DIV

PHP code

<?php
/*
 * Divides "value1" by "value2" and stores the result into "result".
 * opcode number: 4
 */
echo 6/3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | DIV |  |  | ~0 | 6,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
DECLARE_INHERITED_CLASS
DO_FCALL
Opcodes


DO_FCALL

PHP code

<?php
/*
 * Call a function.  Following multiple SEND_VAL, SEND_VAR or SEND_REF.
 * opcode number: 60
 */
$a = phpinfo();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | DO_FCALL |  | 0 |  | 'phpinfo'
 | 1 | ASSIGN |  |  |  | !0,$0
7 | 2 | RETURN |  |  |  | 1
DIV
DO_FCALL_BY_NAME
Opcodes


DO_FCALL_BY_NAME

PHP code

<?php
/*
 * Call a function by name.  Following INIT_FCALL_BY_NAME and multiple SEND_VAL, SEND_VAR or SEND_REF.
 * opcode number: 61
 */
$x = 'phpinfo';
$a = $x();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,'phpinfo'
7 | 1 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !1,$1
8 | 4 | RETURN |  |  |  | 1
DO_FCALL
ECHO
Opcodes


ECHO

PHP code

<?php
/*
 * Dump text
 * opcode number: 40
 */
echo "hello world";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | ECHO |  |  |  | 'hello+world'
7 | 1 | RETURN |  |  |  | 1
DO_FCALL_BY_NAME
END_SILENCE
Opcodes


END_SILENCE

PHP code

<?php
/*
 * no longer surpress error messages
 * opcode number: 58
 */
$my_file = @file ('non_existent_file') or
   die ("error:'$php_errormsg'");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$my_file, !1=$php_errormsg

line | # | op | fetch | ext | return | operands
6 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | SEND_VAL |  |  |  | 'non_existent_file'
 | 2 | DO_FCALL |  | 1 |  | 'file'
 | 3 | END_SILENCE |  |  |  | ~0
 | 4 | ASSIGN |  |  | $2 | !0,$1
 | 5 | JMPNZ_EX |  |  | ~3 | $2,->11
7 | 6 | ADD_STRING |  |  | ~4 | 'error%3A%27'
 | 7 | ADD_VAR |  |  | ~4 | ~4,!1
 | 8 | ADD_CHAR |  |  | ~4 | ~4,39
 | 9 | EXIT |  |  |  | ~4
 | 10 | BOOL |  |  | ~3 | true
 | 11 | FREE |  |  |  | ~3
8 | 12 | RETURN |  |  |  | 1
ECHO
EXIT
Opcodes


EXIT

PHP code

<?php
/*
 * Exit running after dumping "message".
 * opcode number: 79
 */
die("foobar");
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | EXIT |  |  |  | 'foobar'
7 | 1 | RETURN |  |  |  | 1
END_SILENCE
EXT_FCALL_BEGIN
Opcodes


EXT_FCALL_BEGIN

PHP code

<?php
/*
 *
 * opcode number: 102
 * No sample PHP yet */
?>
EXIT
EXT_FCALL_END
Opcodes


EXT_FCALL_END

PHP code

<?php
/*
 *
 * opcode number: 103
 * No sample PHP yet */
?>
EXT_FCALL_BEGIN
EXT_NOP
Opcodes


EXT_NOP

PHP code

<?php
/*
 *
 * opcode number: 104
 * No sample PHP yet */
?>
EXT_FCALL_END
EXT_STMT
Opcodes


EXT_STMT

PHP code

<?php
/*
 *
 * opcode number: 101
 * No sample PHP yet */
?>
EXT_NOP
FETCH_CLASS
Opcodes


FETCH_CLASS

PHP code

<?php
/*
 *
 * opcode number: 109
 */
$obj = new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | RETURN |  |  |  | 1
EXT_STMT
FETCH_CONSTANT
Opcodes


FETCH_CONSTANT

PHP code

<?php
/*
 * Fetch the constant value bound to the specified name (name) and stores it into a variable (result).
 * opcode number: 99
 */
define("FOO", "something");
echo FOO;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SEND_VAL |  |  |  | 'FOO'
 | 1 | SEND_VAL |  |  |  | 'something'
 | 2 | DO_FCALL |  | 2 |  | 'define'
7 | 3 | FETCH_CONSTANT |  |  | ~1 | 'FOO'
 | 4 | ECHO |  |  |  | ~1
8 | 5 | RETURN |  |  |  | 1
FETCH_CLASS
FETCH_DIM_FUNC_ARG
Opcodes


FETCH_DIM_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 93
 */

function foo(&$x)
{
  print($x);
}

$x = array(0, 1, 2, 3, 4, 5);
$z = "foo";

$z($x[0]);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$z

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
12 | 1 | INIT_ARRAY |  |  | ~0 | 0
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 1
 | 3 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 4 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 5 | ADD_ARRAY_ELEMENT |  |  | ~0 | 4
 | 6 | ADD_ARRAY_ELEMENT |  |  | ~0 | 5
 | 7 | ASSIGN |  |  |  | !0,~0
13 | 8 | ASSIGN |  |  |  | !1,'foo'
15 | 9 | INIT_FCALL_BY_NAME |  |  |  | !1
 | 10 | FETCH_DIM_FUNC_ARG |  |  | $3 | !0,0
 | 11 | SEND_VAR |  |  |  | $3
 | 12 | DO_FCALL_BY_NAME |  | 1 |  |
17 | 13 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
7 | 0 | RECV |  |  |  | 1
9 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
10 | 3 | RETURN |  |  |  | null
FETCH_CONSTANT
FETCH_DIM_IS
Opcodes


FETCH_DIM_IS

PHP code

<?php
/*
 *
 * opcode number: 90
 * No sample PHP yet */
?>
FETCH_DIM_FUNC_ARG
FETCH_DIM_R
Opcodes


FETCH_DIM_R

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".  Read-only?
 * opcode number: 81
 */
$x = array(1,2,3);
$a = 'x';
echo $$a[0];
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_DIM_R |  |  | $3 | !1,0
 | 6 | FETCH_R | local |  | $4 | $3
 | 7 | ECHO |  |  |  | $4
9 | 8 | RETURN |  |  |  | 1
FETCH_DIM_IS
FETCH_DIM_RW
Opcodes


FETCH_DIM_RW

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".
 * opcode number: 87
 */
$x = array(1,2,3);
$a = 'x';
$$a[0]++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_DIM_R |  |  | $3 | !1,0
 | 6 | FETCH_RW | local |  | $4 | $3
 | 7 | POST_INC |  |  | ~5 | $4
 | 8 | FREE |  |  |  | ~5
9 | 9 | RETURN |  |  |  | 1
FETCH_DIM_R
FETCH_DIM_TMP_VAR
Opcodes


FETCH_DIM_TMP_VAR

PHP code

<?php
/*
 * Fetch an entry of an array from a temporal variable?
 * opcode number: 98
 */
list($x) = array("X");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 'X'
 | 1 | FETCH_DIM_TMP_VAR |  |  | $1 | ~0,0
 | 2 | ASSIGN |  |  |  | !0,$1
 | 3 | FREE |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1
FETCH_DIM_RW
FETCH_DIM_UNSET
Opcodes


FETCH_DIM_UNSET

PHP code

<?php
/*
 * Fetch an entry of an array variable for the purpose of unset() operation.
 * opcode number: 96
 * No sample PHP yet */
?>
FETCH_DIM_TMP_VAR
FETCH_DIM_W
Opcodes


FETCH_DIM_W

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".  Write-only?
 * opcode number: 84
 */
$a = 1;
while($a > 0){
    $a = 0;
}
/*$input =array(1,2,3);
while (list($var,) = @each($input)){
    unset($$var);
}*/
/*$a = array(1,2,3);
$x = 'a';
$$x[0] = 1;*/

/*while ($b = each($a)) {
  print $b;
}*/

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | IS_SMALLER |  |  | ~1 | 0,!0
 | 2 | JMPZ |  |  |  | ~1,->5
8 | 3 | ASSIGN |  |  |  | !0,0
9 | 4 | JMP |  |  |  | ->1
23 | 5 | RETURN |  |  |  | 1
FETCH_DIM_UNSET
FETCH_FUNC_ARG
Opcodes


FETCH_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 92
 */
function foo($x)
{
}

$x = 1;
$y = "x";
$z = "foo";

$z($$y);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$y, !2=$z

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | ASSIGN |  |  |  | !0,1
11 | 2 | ASSIGN |  |  |  | !1,'x'
12 | 3 | ASSIGN |  |  |  | !2,'foo'
14 | 4 | INIT_FCALL_BY_NAME |  |  |  | !2
 | 5 | FETCH_FUNC_ARG | local |  | $3 | !1
 | 6 | SEND_VAR |  |  |  | $3
 | 7 | DO_FCALL_BY_NAME |  | 1 |  |
16 | 8 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
8 | 1 | RETURN |  |  |  | null
FETCH_DIM_W
FETCH_IS
Opcodes


FETCH_IS

PHP code

<?php
/*
 * Fetch the value from variable which is to be used to test if it is set or not, through isset()/isempty().
 * opcode number: 89
 */
echo isset($_SESSION['userid']);
echo isset($_SESSION['userid'][1]);
echo isset($_SESSION->prop->prop);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | FETCH_IS |  |  | $0 | '_SESSION'
 | 1 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~1 | $0,'userid'
 | 2 | ECHO |  |  |  | ~1
7 | 3 | FETCH_IS |  |  | $2 | '_SESSION'
 | 4 | FETCH_DIM_IS |  |  | $3 | $2,'userid'
 | 5 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~4 | $3,1
 | 6 | ECHO |  |  |  | ~4
8 | 7 | FETCH_IS |  |  | $5 | '_SESSION'
 | 8 | FETCH_OBJ_IS |  |  | $6 | $5,'prop'
 | 9 | ZEND_ISSET_ISEMPTY_PROP_OBJ |  |  | ~7 | $6,'prop'
 | 10 | ECHO |  |  |  | ~7
9 | 11 | RETURN |  |  |  | 1
FETCH_FUNC_ARG
FETCH_OBJ_FUNC_ARG
Opcodes


FETCH_OBJ_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 94
 */
include './classA.php';

function foo(&$x)
{
  print($x);
}

$z = "foo";

$obj = new A();
print $obj->num;
$z($obj->num);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$z, !1=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | INCLUDE_OR_EVAL |  |  |  | '.%2FclassA.php',INCLUDE
8 | 1 | NOP |  |  |  |
13 | 2 | ASSIGN |  |  |  | !0,'foo'
15 | 3 | ZEND_FETCH_CLASS |  |  | :2 | 'A'
 | 4 | NEW |  |  | $3 | :2
 | 5 | DO_FCALL_BY_NAME |  | 0 |  |
 | 6 | ASSIGN |  |  |  | !1,$3
16 | 7 | FETCH_OBJ_R |  |  | $6 | !1,'num'
 | 8 | PRINT |  |  | ~7 | $6
 | 9 | FREE |  |  |  | ~7
17 | 10 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 11 | FETCH_OBJ_FUNC_ARG |  |  | $8 | !1,'num'
 | 12 | SEND_VAR |  |  |  | $8
 | 13 | DO_FCALL_BY_NAME |  | 1 |  |
19 | 14 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
8 | 0 | RECV |  |  |  | 1
10 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
11 | 3 | RETURN |  |  |  | null

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
8 | 0 | RECV |  |  |  | 1
10 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
11 | 3 | RETURN |  |  |  | null
FETCH_IS
FETCH_OBJ_IS
Opcodes


FETCH_OBJ_IS

PHP code

<?php
/*
 *
 * opcode number: 91
 * No sample PHP yet */
?>
FETCH_OBJ_FUNC_ARG
FETCH_OBJ_R
Opcodes


FETCH_OBJ_R

PHP code

<?php
/*
 * Fetch the "prop-name" property value of this object.  Read-only?
 * opcode number: 82
 */
$x = new A();
$a = 'x';
echo $$a->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_R | local |  | $5 | !1
 | 6 | FETCH_OBJ_R |  |  | $6 | $5,'num'
 | 7 | ECHO |  |  |  | $6
9 | 8 | RETURN |  |  |  | 1
FETCH_OBJ_IS
FETCH_OBJ_RW
Opcodes


FETCH_OBJ_RW

PHP code

<?php
/*
 * Fetch the "prop-name" property value of this object.
 * opcode number: 88
 */
$x = new A();
$a = 'x';
$$a->num++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_RW | local |  | $5 | !1
 | 6 | ZEND_POST_INC_OBJ |  |  | ~7 | $5,'num'
 | 7 | FREE |  |  |  | ~7
9 | 8 | RETURN |  |  |  | 1
FETCH_OBJ_R
FETCH_OBJ_UNSET
Opcodes


FETCH_OBJ_UNSET

PHP code

<?php
/*
 * Fetch a property of an object variable for the purpose of unset() operation.
 * opcode number: 97
 * No sample PHP yet */
?>
FETCH_OBJ_RW
FETCH_OBJ_W
Opcodes


FETCH_OBJ_W

PHP code

<?php
/*
 * Fetch the "prop-name" property value of this object.  Write-only?
 * opcode number: 85
 */
$x = new A();
$a = 'x';
$$a->num = 1;;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_W | local |  | $5 | !1
 | 6 | ZEND_ASSIGN_OBJ |  |  |  | $5,'num'
 | 7 | ZEND_OP_DATA |  |  |  | 1
9 | 8 | RETURN |  |  |  | 1
FETCH_OBJ_UNSET
FETCH_R
Opcodes


FETCH_R

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?  Read-only?
 * opcode number: 80
 */
$x = 1;
$a = 'x';
echo $$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_R | local |  | $2 | !1
 | 3 | ECHO |  |  |  | $2
9 | 4 | RETURN |  |  |  | 1
FETCH_OBJ_W
FETCH_RW
Opcodes


FETCH_RW

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?
 * opcode number: 86
 */
$x = 1;
$a = 'x';
$$a++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_RW | local |  | $2 | !1
 | 3 | POST_INC |  |  | ~3 | $2
 | 4 | FREE |  |  |  | ~3
9 | 5 | RETURN |  |  |  | 1
FETCH_R
FETCH_UNSET
Opcodes


FETCH_UNSET

PHP code

<?php
/*
 * Fetch a variable for the purpose of unset() operation.
 * opcode number: 95
 * No sample PHP yet */
?>
FETCH_RW
FETCH_W
Opcodes


FETCH_W

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?  Write-only?
 * opcode number: 83
 */
$x = 1;
$a = 'x';
$$a = 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_W | local |  | $2 | !1
 | 3 | ASSIGN |  |  |  | $2,2
9 | 4 | RETURN |  |  |  | 1
FETCH_UNSET
FE_FETCH
Opcodes


FE_FETCH

PHP code

<?php
/*
 * Fetch an element from iterator.  If no element is available, jump to address.  Followed by OP_DATA?
 * opcode number: 78
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1
FETCH_W
FE_RESET
Opcodes


FE_RESET

PHP code

<?php
/*
 * Initialize an iterator on array-value.  If the array is empty, jump to address.  Followed by FE_FETCH.
 * opcode number: 77
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1
FE_FETCH
FREE
Opcodes


FREE

PHP code

<?php
/*
 * Release the allocated space of the value.
 * opcode number: 70
 */
 print "Hello World";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | PRINT |  |  | ~0 | 'Hello+World'
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
FE_RESET
HANDLE_EXCEPTION
Opcodes


HANDLE_EXCEPTION

PHP code

<?php
/*
 *
 * opcode number: 149
 */
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | 1
FREE
INCLUDE_OR_EVAL
Opcodes


INCLUDE_OR_EVAL

PHP code

<?php
/*
 * Include the file specified by filename and eval it.
 * opcode number: 73
 */
include("test.php");
eval("test.php");
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | INCLUDE_OR_EVAL |  |  |  | 'test.php',INCLUDE
7 | 1 | INCLUDE_OR_EVAL |  |  |  | 'test.php',EVAL
8 | 2 | RETURN |  |  |  | 1

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
2 | 0 | DO_FCALL |  | 0 |  | 'phpinfo'
3 | 1 | RETURN |  |  |  | 1
HANDLE_EXCEPTION
INIT_ARRAY
Opcodes


INIT_ARRAY

PHP code

<?php
/*
 * Allocate a new array with elem-value as the first element of the array.  Followed by ADD_ARRAY_ELEMENT.
 * opcode number: 71
 */
$a = array(1,2,3);
print_r($a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'print_r'
8 | 6 | RETURN |  |  |  | 1
INCLUDE_OR_EVAL
INIT_FCALL_BY_NAME
Opcodes


INIT_FCALL_BY_NAME

PHP code

<?php
/*
 * prepare for a function call to function value1
 * opcode number: 59
 */
$x = 'phpinfo';
$a = $x();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,'phpinfo'
7 | 1 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !1,$1
8 | 4 | RETURN |  |  |  | 1
INIT_ARRAY
INIT_METHOD_CALL
Opcodes


INIT_METHOD_CALL

PHP code

<?php
/*
 * Prepare for a method call.  Followed by DO_FCALL.
 * opcode number: 112
 */
class A {
  var $num;
    function incrementNum(){
    $num++;
  }
}

$obj = new A();
$obj->incrementNum();

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
13 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'A'
 | 2 | NEW |  |  | $2 | :1
 | 3 | DO_FCALL_BY_NAME |  | 0 |  |
 | 4 | ASSIGN |  |  |  | !0,$2
14 | 5 | ZEND_INIT_METHOD_CALL |  |  |  | !0,'incrementNum'
 | 6 | DO_FCALL_BY_NAME |  | 0 |  |
16 | 7 | RETURN |  |  |  | 1

Function name: incrementNum

Compiled variables: !0=$num

line | # | op | fetch | ext | return | operands
9 | 0 | POST_INC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
10 | 2 | RETURN |  |  |  | null
INIT_FCALL_BY_NAME
INIT_STATIC_METHOD_CALL
Opcodes


INIT_STATIC_METHOD_CALL

PHP code

<?php
/*
 *
 * opcode number: 113
 */
class Foo {
    public static function aStaticMethod() {
            echo "hello world\n";
    }
}

Foo::aStaticMethod();
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
12 | 1 | ZEND_INIT_STATIC_METHOD_CALL |  |  |  | 'Foo','aStaticMethod'
 | 2 | ZEND_OP_DATA |  |  |  | 'foo%3A%3Aastaticmethod'
 | 3 | DO_FCALL_BY_NAME |  | 0 |  |
13 | 4 | RETURN |  |  |  | 1

Function name: aStaticMethod

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ECHO |  |  |  | 'hello+world%0A'
9 | 1 | RETURN |  |  |  | null
INIT_METHOD_CALL
INIT_STRING
Opcodes


INIT_STRING

PHP code

<?php
/*
 * appears to create a string variable in result
 * opcode number: 53
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1
INIT_STATIC_METHOD_CALL
INSTANCEOF
Opcodes


INSTANCEOF

PHP code

<?php
/*
 *
 * opcode number: 138
 */
$obj = new A();

if ($obj instanceof A) {
   echo 'A';
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
8 | 4 | ZEND_FETCH_CLASS |  |  | :4 | 'A'
 | 5 | ZEND_INSTANCEOF |  |  | ~5 | !0,$4
 | 6 | JMPZ |  |  |  | ~5,->9
9 | 7 | ECHO |  |  |  | 'A'
10 | 8 | JMP |  |  |  | ->9
11 | 9 | RETURN |  |  |  | 1
INIT_STRING
ISSET_ISEMPTY_DIM_OBJ
Opcodes


ISSET_ISEMPTY_DIM_OBJ

PHP code

<?php
/*
 * Tests if the entry of an array is set or not.
 * opcode number: 115
 */
if(isset($a[0])) return 0;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~0 | !0,0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | 0
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1
INSTANCEOF
ISSET_ISEMPTY_PROP_OBJ
Opcodes


ISSET_ISEMPTY_PROP_OBJ

PHP code

<?php
/*
 *
 * opcode number: 148
 */
$obj = new A();
if(empty($obj->num)) return 0;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_ISSET_ISEMPTY_PROP_OBJ |  |  | ~4 | !0,'num'
 | 5 | JMPZ |  |  |  | ~4,->8
 | 6 | RETURN |  |  |  | 0
 | 7 | JMP |  |  |  | ->8
8 | 8 | RETURN |  |  |  | 1
ISSET_ISEMPTY_DIM_OBJ
ISSET_ISEMPTY_VAR
Opcodes


ISSET_ISEMPTY_VAR

PHP code

<?php
/*
 * Tests if the value of a variable is set or not.
 * opcode number: 114
 */
if(isset($a)){ return 0;}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ISSET_ISEMPTY_VAR |  | 5 | ~0 | !0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | 0
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1
ISSET_ISEMPTY_PROP_OBJ
IS_EQUAL
Opcodes


IS_EQUAL

PHP code

<?php
/*
 * compares if value1 and value2 are equal
 * opcode number: 17
 */
echo (1 == 1);
echo (1 == 'c');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_EQUAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | IS_EQUAL |  |  | ~1 | 1,'c'
 | 3 | ECHO |  |  |  | ~1
8 | 4 | RETURN |  |  |  | 1
ISSET_ISEMPTY_VAR
IS_IDENTICAL
Opcodes


IS_IDENTICAL

PHP code

<?php
/*
 * Compares value1 and value2 to see if they are equal AND have the same type
 * opcode number: 15
 */
echo (1===1);
echo (1==='a');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_IDENTICAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | IS_IDENTICAL |  |  | ~1 | 1,'a'
 | 3 | ECHO |  |  |  | ~1
8 | 4 | RETURN |  |  |  | 1
IS_EQUAL
IS_NOT_EQUAL
Opcodes


IS_NOT_EQUAL

PHP code

<?php
/*
 * compares if value1 and value2 are not equal
 * opcode number: 18
 */
echo (1 != 1);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_EQUAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
IS_IDENTICAL
IS_NOT_IDENTICAL
Opcodes


IS_NOT_IDENTICAL

PHP code

<?php
/*
 * compares value1 and value2 to see if they are unequal or of different types
 * opcode number: 16
 */
echo (1 !== 1);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_IDENTICAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
IS_NOT_EQUAL
IS_SMALLER
Opcodes


IS_SMALLER

PHP code

<?php
/*
 * compares if value1 is less than value2
 * opcode number: 19
 */
echo (1 < 2);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_SMALLER |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
IS_NOT_IDENTICAL
IS_SMALLER_OR_EQUAL
Opcodes


IS_SMALLER_OR_EQUAL

PHP code

<?php
/*
 * compares if value1 is less than or equal to value2
 * opcode number: 20
 */
echo (1 >= 2);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_SMALLER_OR_EQUAL |  |  | ~0 | 2,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
IS_SMALLER
JMPNZ
Opcodes


JMPNZ

PHP code

<?php
/*
 * Jump to the address if the value is not zero
 * opcode number: 44
 */
for($i=0; $i<3; $i++){
    echo "hi";
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
 | 1 | IS_SMALLER |  |  | ~1 | !0,3
 | 2 | JMPZNZ |  | 6 |  | ~1,->8
 | 3 | POST_INC |  |  | ~2 | !0
 | 4 | FREE |  |  |  | ~2
 | 5 | JMP |  |  |  | ->1
7 | 6 | ECHO |  |  |  | 'hi'
8 | 7 | JMP |  |  |  | ->3
9 | 8 | RETURN |  |  |  | 1
IS_SMALLER_OR_EQUAL
JMPNZ_EX
Opcodes


JMPNZ_EX

PHP code

<?php
/*
 * Jump to the address if the xor of value1 and value2 is zero .. ???
 * opcode number: 47
 */
if(1^2) return;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_XOR |  |  | ~0 | 1,2
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | null
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1
JMPNZ
JMPZ
Opcodes


JMPZ

PHP code

<?php
/*
 * Jump to the address if the value is zero
 * opcode number: 43
 */
if($a != 0) echo "foo";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_EQUAL |  |  | ~0 | !0,0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | ECHO |  |  |  | 'foo'
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1
JMPNZ_EX
JMPZNZ
Opcodes


JMPZNZ

PHP code

<?php
/*
 * Jump to the address if the value is .. ???
 * opcode number: 45
 */
for($i=0; $i<3; $i++){
    echo "hi";
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
 | 1 | IS_SMALLER |  |  | ~1 | !0,3
 | 2 | JMPZNZ |  | 6 |  | ~1,->8
 | 3 | POST_INC |  |  | ~2 | !0
 | 4 | FREE |  |  |  | ~2
 | 5 | JMP |  |  |  | ->1
7 | 6 | ECHO |  |  |  | 'hi'
8 | 7 | JMP |  |  |  | ->3
9 | 8 | RETURN |  |  |  | 1
JMPZ
JMPZ_EX
Opcodes


JMPZ_EX

PHP code

<?php
/*
 * Jump to the address if the xor of value1 and value2 is zero .. ???
 * opcode number: 46
 */

?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
7 | 0 | RETURN |  |  |  | 1
JMPZNZ
MOD
Opcodes


MOD

PHP code

<?php
/*
 * Makes the value of "result" congruent to "value1" modulo "value2".
 * opcode number: 5
 */
echo 6 % 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | MOD |  |  | ~0 | 6,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
JMPZ_EX
MUL
Opcodes


MUL

PHP code

<?php
/*
 * Multiplys "value1" by "value2" and stores the result into "result".
 * opcode number: 3
 */
echo 2*3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | MUL |  |  | ~0 | 2,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
MOD
NEW
Opcodes


NEW

PHP code

<?php
/*
 * Construct an instance of "type" and store the reference to the object into "result".
 * opcode number: 68
 */
$obj = new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | RETURN |  |  |  | 1
MUL
NOP
Opcodes


NOP

PHP code

<?php
/*
 * no operation
 * opcode number: 0
 */
function A(){};
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: A

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | null
NEW
POST_DEC
Opcodes


POST_DEC

PHP code

<?php
/*
 * decrements variable indicated by value1 by 1 (after performing other operations) and stores in result
 * opcode number: 37
 */
$a--;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | POST_DEC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
NOP
POST_DEC_OBJ
Opcodes


POST_DEC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 135
 */
$obj = new A();
$obj->num--;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_POST_DEC_OBJ |  |  | ~5 | !0,'num'
 | 5 | FREE |  |  |  | ~5
8 | 6 | RETURN |  |  |  | 1
POST_DEC
POST_INC
Opcodes


POST_INC

PHP code

<?php
/*
 * increments variable indicated by value1 by 1 (after performing other operations) and stores in result
 * opcode number: 36
 */
$a++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | POST_INC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
POST_DEC_OBJ
POST_INC_OBJ
Opcodes


POST_INC_OBJ

PHP code

<?php
/*
 * Increment the property value specified by prop-name and store the original value into result.
 * opcode number: 134
 */
$obj = new A();
$obj->num++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_POST_INC_OBJ |  |  | ~5 | !0,'num'
 | 5 | FREE |  |  |  | ~5
8 | 6 | RETURN |  |  |  | 1
POST_INC
PRE_DEC
Opcodes


PRE_DEC

PHP code

<?php
/*
 * decrements variable indicated by value1 by 1 (before performing other operations) and stores in results
 * opcode number: 35
 */
--$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | PRE_DEC |  |  |  | !0
7 | 1 | RETURN |  |  |  | 1
POST_INC_OBJ
PRE_DEC_OBJ
Opcodes


PRE_DEC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 133
 */
$obj = new A();
--$obj->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_PRE_DEC_OBJ |  |  |  | !0,'num'
8 | 5 | RETURN |  |  |  | 1
PRE_DEC
PRE_INC
Opcodes


PRE_INC

PHP code

<?php
/*
 * increments variable indicated by value1 by 1 (before performing other operations) and stores in result
 * opcode number: 34
 */
++$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | PRE_INC |  |  |  | !0
7 | 1 | RETURN |  |  |  | 1
PRE_DEC_OBJ
PRE_INC_OBJ
Opcodes


PRE_INC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 132
 */
$obj = new A();
++$obj->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_PRE_INC_OBJ |  |  |  | !0,'num'
8 | 5 | RETURN |  |  |  | 1
PRE_INC
PRINT
Opcodes


PRINT

PHP code

<?php
/*
 *
 * opcode number: 41
 */
print "Hello World";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | PRINT |  |  | ~0 | 'Hello+World'
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
PRE_INC_OBJ
QM_ASSIGN
Opcodes


QM_ASSIGN

PHP code

<?php
/*
 * Question Mark Assign, used twice inside a question mark assign to temporarily assign result as value1  (this is followed up with an ASSIGN bytecode)
 * opcode number: 22
 */
function A(){
 echo 1?2:3;
}

function B(){
 $b = 0;
 $a = $b > 1 ? 10: 11;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | NOP |  |  |  |
14 | 2 | RETURN |  |  |  | 1

Function name: A

Compiled variables: none

line | # | op | fetch | ext | return | operands
7 | 0 | JMPZ |  |  |  | 1,->3
 | 1 | QM_ASSIGN |  |  | ~0 | 2
 | 2 | JMP |  |  |  | ->4
 | 3 | QM_ASSIGN |  |  | ~0 | 3
 | 4 | ECHO |  |  |  | ~0
8 | 5 | RETURN |  |  |  | null

Function name: B

Compiled variables: !0=$b, !1=$a

line | # | op | fetch | ext | return | operands
11 | 0 | ASSIGN |  |  |  | !0,0
12 | 1 | IS_SMALLER |  |  | ~1 | 1,!0
 | 2 | JMPZ |  |  |  | ~1,->5
 | 3 | QM_ASSIGN |  |  | ~2 | 10
 | 4 | JMP |  |  |  | ->6
 | 5 | QM_ASSIGN |  |  | ~2 | 11
 | 6 | ASSIGN |  |  |  | !1,~2
13 | 7 | RETURN |  |  |  | null
PRINT
RAISE_ABSTRACT_ERROR
Opcodes


RAISE_ABSTRACT_ERROR

PHP code

<?php
/*
 *
 * opcode number: 142
 */

abstract class fail {
    abstract function show();
}

class pass extends fail {
    function show() {
        echo "Call to function show()\n";
    }
}

$t2 = new pass();
$t2->show();

$t = new fail();
$t->show();

echo "Done\n"; // shouldn't be displayed
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$t2, !1=$t

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
11 | 1 | NOP |  |  |  |
 | 2 | NOP |  |  |  |
17 | 3 | ZEND_FETCH_CLASS |  |  | :3 | 'pass'
 | 4 | NEW |  |  | $4 | :3
 | 5 | DO_FCALL_BY_NAME |  | 0 |  |
 | 6 | ASSIGN |  |  |  | !0,$4
18 | 7 | ZEND_INIT_METHOD_CALL |  |  |  | !0,'show'
 | 8 | DO_FCALL_BY_NAME |  | 0 |  |
20 | 9 | ZEND_FETCH_CLASS |  |  | :9 | 'fail'
 | 10 | NEW |  |  | $10 | :9
 | 11 | DO_FCALL_BY_NAME |  | 0 |  |
 | 12 | ASSIGN |  |  |  | !1,$10
21 | 13 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'show'
 | 14 | DO_FCALL_BY_NAME |  | 0 |  |
23 | 15 | ECHO |  |  |  | 'Done%0A'
24 | 16 | RETURN |  |  |  | 1

Function name: show

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ZEND_RAISE_ABSTRACT_ERROR |  |  |  |
 | 1 | RETURN |  |  |  | null

Function name: show

Compiled variables: none

line | # | op | fetch | ext | return | operands
13 | 0 | ECHO |  |  |  | 'Call+to+function+show%28%29%0A'
14 | 1 | RETURN |  |  |  | null
QM_ASSIGN
RECV
Opcodes


RECV

PHP code

<?php
/*
 * Receive a functoin argument of "argument-number" and store the argument value into a variable of "argument-number".  (e.g. $1 for 1)
 * opcode number: 63
 */
function hello($a){}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: hello

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
 | 1 | RETURN |  |  |  | null
RAISE_ABSTRACT_ERROR
RECV_INIT
Opcodes


RECV_INIT

PHP code

<?php
/*
 * Initialize a function argument with "value" if not received from caller.  Otherwise same as RECV.
 * opcode number: 64
 */
function hello($a=5){}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: hello

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | RECV_INIT |  |  |  | 1,5
 | 1 | RETURN |  |  |  | null
RECV
RETURN
Opcodes


RETURN

PHP code

<?php
/*
 * Return value from a funciton.
 * opcode number: 62
 */
return 1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | 1
7 | 1 | RETURN |  |  |  | 1
RECV_INIT
SEND_REF
Opcodes


SEND_REF

PHP code

<?php
/*
 * Pass the reference value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 67
 */
@each($input);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | FETCH_W | local |  | $1 | 'input'
 | 2 | SEND_REF |  |  |  | $1
 | 3 | DO_FCALL |  | 1 |  | 'each'
 | 4 | END_SILENCE |  |  |  | ~0
7 | 5 | RETURN |  |  |  | 1
RETURN
SEND_VAL
Opcodes


SEND_VAL

PHP code

<?php
/*
 * Pass the constant value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 65
 */
function funcA($msg){
    print $msg;
}

funcA('HELLO');

defined('IN_PHPBB');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | SEND_VAL |  |  |  | 'HELLO'
 | 2 | DO_FCALL |  | 1 |  | 'funca'
12 | 3 | SEND_VAL |  |  |  | 'IN_PHPBB'
 | 4 | DO_FCALL |  | 1 |  | 'defined'
13 | 5 | RETURN |  |  |  | 1

Function name: funcA

Compiled variables: !0=$msg

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
7 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
8 | 3 | RETURN |  |  |  | null
SEND_REF
SEND_VAR
Opcodes


SEND_VAR

PHP code

<?php
/*
 * Pass the variable value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 66
 */
$a = array(1,2,3);
if(is_array($a)){ return 0; }
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'is_array'
 | 6 | JMPZ |  |  |  | $2,->9
 | 7 | RETURN |  |  |  | 0
 | 8 | JMP |  |  |  | ->9
8 | 9 | RETURN |  |  |  | 1
SEND_VAL
SEND_VAR_NO_REF
Opcodes


SEND_VAR_NO_REF

PHP code

<?php
/*
 *
 * opcode number: 106
 * No sample PHP yet */
?>
SEND_VAR
SL
Opcodes


SL

PHP code

<?php
/*
 * Shift value1 by balue2 bits to left
 * opcode number: 6
 */
echo 8 << 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SL |  |  | ~0 | 8,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
SEND_VAR_NO_REF
SR
Opcodes


SR

PHP code

<?php
/*
 * Shift bits to right
 * opcode number: 7
 */
echo 8 >> 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SR |  |  | ~0 | 8,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
SL
SUB
Opcodes


SUB

PHP code

<?php
/*
 * Subtracts "value2" from "value1" and stores the result into "result".
 * opcode number: 2
 */
echo 1-2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SUB |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1
SR
SWITCH_FREE
Opcodes


SWITCH_FREE

PHP code

<?php
/*
 * Release the allocated space of "value"?
 * opcode number: 49
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1
SUB
THROW
Opcodes


THROW

PHP code

<?php
/*
 *
 * opcode number: 108
 */
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$error, !1=$e

line | # | op | fetch | ext | return | operands
7 | 0 | ASSIGN |  |  |  | !0,'Always+throw+this+error'
8 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'Exception'
 | 2 | NEW |  |  | $2 | :1
 | 3 | SEND_VAR |  |  |  | !0
 | 4 | DO_FCALL_BY_NAME |  | 1 |  |
 | 5 | ZEND_THROW |  | 0 |  | $2
11 | 6 | ECHO |  |  |  | 'Never+executed'
13 | 7 | JMP |  |  |  | ->15
 | 8 | ZEND_FETCH_CLASS |  |  | :4 | 'Exception'
 | 9 | ZEND_CATCH |  | 15 |  | $4,!1
14 | 10 | ECHO |  |  |  | 'Caught+exception%3A+'
 | 11 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'getMessage'
 | 12 | DO_FCALL_BY_NAME |  | 0 |  |
 | 13 | ECHO |  |  |  | $6
 | 14 | ECHO |  |  |  | '%0A'
18 | 15 | ECHO |  |  |  | 'Hello+World'
19 | 16 | RETURN |  |  |  | 1
SWITCH_FREE
TICKS
Opcodes


TICKS

PHP code

<?php
/*
 *
 * opcode number: 105
 */
// A function that records the time when it is called
function profile()
{
   echo "profile function is called\n";
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
   for ($x = 0; $x < 10; ++$x) {
         echo "hello world\n";
   }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
13 | 1 | SEND_VAL |  |  |  | 'profile'
 | 2 | DO_FCALL |  | 1 |  | 'register_tick_function'
16 | 3 | DO_FCALL |  | 0 |  | 'profile'
20 | 4 | ASSIGN |  |  |  | !0,0
 | 5 | IS_SMALLER |  |  | ~3 | !0,10
 | 6 | JMPZNZ |  | 9 |  | ~3,->13
 | 7 | PRE_INC |  |  |  | !0
 | 8 | JMP |  |  |  | ->5
21 | 9 | ECHO |  |  |  | 'hello+world%0A'
 | 10 | TICKS |  |  |  | 2
22 | 11 | TICKS |  |  |  | 2
 | 12 | JMP |  |  |  | ->7
 | 13 | TICKS |  |  |  | 2
23 | 14 | TICKS |  |  |  | 2
24 | 15 | RETURN |  |  |  | 1

Function name: profile

Compiled variables: none

line | # | op | fetch | ext | return | operands
9 | 0 | ECHO |  |  |  | 'profile+function+is+called%0A'
10 | 1 | RETURN |  |  |  | null
THROW
UNSET_DIM
Opcodes


UNSET_DIM

PHP code

<?php
/*
 * Unset the entry of array-value, which is specified by index, and store the original element value into "result".
 * opcode number: 75
 */
$a = array(1,2,3);
unset($a[0]);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | UNSET_DIM |  |  | $2 | !0,0
8 | 5 | RETURN |  |  |  | 1
TICKS
UNSET_OBJ
Opcodes


UNSET_OBJ

PHP code

<?php
/*
 * Unset the property of the current object (this) and store the original value into "result".
 * opcode number: 76
 */
$obj = new A();
unset($obj->num);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | UNSET_OBJ |  |  | $4 | !0,'num'
8 | 5 | RETURN |  |  |  | 1
UNSET_DIM
UNSET_VAR
Opcodes


UNSET_VAR

PHP code

<?php
/*
 * Unset the variable and store the original value into "result".
 * opcode number: 74
 */
$x = 1;
$a='x';
unset($$a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | UNSET_VAR |  |  | $2 | !1
9 | 3 | RETURN |  |  |  | 1
UNSET_OBJ
USER_OPCODE
Opcodes


USER_OPCODE

PHP code

<?php
/*
 *
 * opcode number: 150
 * No sample PHP yet */
?>
UNSET_VAR
VERIFY_ABSTRACT_CLASS
Opcodes


VERIFY_ABSTRACT_CLASS

PHP code

<?php
/*
 *
 * opcode number: 146
 * No sample PHP yet */
?>
USER_OPCODE
Zend Engine 1
Opcodes


Zend Engine 1

Spis treści

  • Old introduction
  • Streams API for PHP Extension Authors
  • Zend API: Hackowanie rdzenia PHP
  • TSRM API

Zend Engine 1 is the internal engine used by PHP for the entire version 4 release line. It is no longer considered active, but PHP 4 is still in widespread use, so the old ZE1 documentation is preserved here exactly as it was.

VERIFY_ABSTRACT_CLASS
Old introduction
Rdzeń PHP: Poradnik hackerów o Zend Engine


Old introduction

If you are about to begin developing PHP or Zend extensions, you need to prepare yourself for the programming environment provided by the various APIs. This part of the documentation tries to introduce the APIs provided by the different PHP and Zend Engine versions available. Since most of the information available here is somewhat outdated, you'll want to read various files found in the PHP source, files such as README.SELF-CONTAINED-EXTENSIONS and README.EXT_SKEL in addition to the manual.

Zend Engine 1
Streams API for PHP Extension Authors
Zend Engine 1


Streams API for PHP Extension Authors

Informacja:

The functions in this chapter are for use in the PHP source code and are not PHP functions. Information on userland stream functions can be found in the Stream Reference.

Overview

The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams.

The aim of the Streams API is to make it comfortable for developers to open files, URLs and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams.

The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs. An additional context parameter, accepted by most stream creation functions, is passed to the wrapper's stream_opener method to fine-tune the behavior of the wrapper.

Any stream, once opened, can also have any number of filters applied to it, which process data as it is read from/written to the stream.

Streams can be cast (converted) into other types of file-handles, so that they can be used with third-party libraries without a great deal of trouble. This allows those libraries to access data directly from URL sources. If your system has the fopencookie() or funopen() function, you can even pass any PHP stream to any library that uses ANSI stdio!

Streams Basics

Using streams is very much like using ANSI stdio functions. The main difference is in how you obtain the stream handle to begin with. In most cases, you will use php_stream_open_wrapper() to obtain the stream handle. This function works very much like fopen, as can be seen from the example below:

Przykład #1 simple stream example that displays the PHP home page

php_stream * stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);
if (stream) {
    while(!php_stream_eof(stream)) {
        char buf[1024];

        if (php_stream_gets(stream, buf, sizeof(buf))) {
            printf(buf);
        } else {
            break;
        }
    }
    php_stream_close(stream);
}

The table below shows the Streams equivalents of the more common ANSI stdio functions. Unless noted otherwise, the semantics of the functions are identical.

ANSI stdio equivalent functions in the Streams API
ANSI Stdio Function | PHP Streams Function | Notes
fopen | php_stream_open_wrapper | Streams includes additional parameters
fclose | php_stream_close |
fgets | php_stream_gets |
fread | php_stream_read | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2)
fwrite | php_stream_write | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2)
fseek | php_stream_seek |
ftell | php_stream_tell |
rewind | php_stream_rewind |
feof | php_stream_eof |
fgetc | php_stream_getc |
fputc | php_stream_putc |
fflush | php_stream_flush |
puts | php_stream_puts | Same semantics as puts, NOT fputs
fstat | php_stream_stat | Streams has a richer stat structure

Streams as Resources

All streams are registered as resources when they are created. This ensures that they will be properly cleaned up even if there is some fatal error. All of the filesystem functions in PHP operate on streams resources - that means that your extensions can accept regular PHP file pointers as parameters to, and return streams from their functions. The streams API makes this process as painless as possible:

Przykład #2 How to accept a stream as a parameter

PHP_FUNCTION(example_write_hello)
{
    zval *zstream;
    php_stream *stream;

    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstream))
        return;

    php_stream_from_zval(stream, &zstream);

    /* you can now use the stream.  However, you do not "own" the
        stream, the script does.  That means you MUST NOT close the
        stream, because it will cause PHP to crash! */

    php_stream_write(stream, "hello\n");

    RETURN_TRUE();
}

Przykład #3 How to return a stream from a function

PHP_FUNCTION(example_open_php_home_page)
{
    php_stream *stream;

    stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);

    php_stream_to_zval(stream, return_value);

    /* after this point, the stream is "owned" by the script.
        If you close it now, you will crash PHP! */
}

Since streams are automatically cleaned up, it's tempting to think that we can get away with being sloppy programmers and not bother to close the streams when we are done with them. Although such an approach might work, it is not a good idea for a number of reasons: streams hold locks on system resources while they are open, so leaving a file open after you have finished with it could prevent other processes from accessing it. If a script deals with a large number of files, the accumulation of the resources used, both in terms of memory and the sheer number of open files, can cause web server requests to fail. Sounds bad, doesn't it? The streams API includes some magic that helps you to keep your code clean - if a stream is not closed by your code when it should be, you will find some helpful debugging information in you web server error log.

Informacja: Always use a debug build of PHP when developing an extension (--enable-debug when running configure), as a lot of effort has been made to warn you about memory and stream leaks.

In some cases, it is useful to keep a stream open for the duration of a request, to act as a log or trace file for example. Writing the code to safely clean up such a stream is not difficult, but it's several lines of code that are not strictly needed. To save yourself the trouble of writing the code, you can mark a stream as being OK for auto cleanup. What this means is that the streams API will not emit a warning when it is time to auto-cleanup a stream. To do this, you can use php_stream_auto_cleanup().

Streams open options

These constants affect the operation of stream factory functions.

IGNORE_PATH
This is the default option for streams; it requests that the include_path is not to be searched for the requested file.
USE_PATH
Requests that the include_path is to be searched for the requested file.
IGNORE_URL
Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default.
IGNORE_URL_WIN
On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect.
ENFORCE_SAFE_MODE
Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access.
REPORT_ERRORS
If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser.
STREAM_MUST_SEEK
This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested.

Informacja: If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded.

STREAM_WILL_CAST
If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use php_stream_cast() to retrieve the FILE* or file descriptor that the library requires. The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream. Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it.

Old introduction
Zend API: Hackowanie rdzenia PHP
Zend Engine 1


Zend API: Hackowanie rdzenia PHP

Introduction

Those who know don't talk.

Those who talk don't know.

Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.

As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.

Ostrzeżenie

This information is currently rather outdated, parts of it only cover early stages of the ZendEngine 1.0 API as it was used in early versions of PHP 4.

More recent information may be found in the various README files that come with the PHP source and the » Internals section on the Zend website.

Overview

"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.

Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.

What Is Zend? and What Is PHP?

The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated ( see below). To implement a Web script interpreter, you need three parts:

  1. The interpreter part analyzes the input code, translates it, and executes it.

  2. The functionality part implements the functionality of the language (its functions, etc.).

  3. The interface part talks to the Web server, etc.

Zend takes part 1 completely and a bit of part 2; PHP takes parts 2 and 3. Together they form the complete PHP package. Zend itself really forms only the language core, implementing PHP at its very basics with some predefined functions. PHP contains all the modules that actually create the language's outstanding capabilities.
The internal structure of PHP.

The following sections discuss where PHP can be extended and how it's done.

Extension Possibilities

As shown above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.

External Modules

External modules can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
External modules don't require recompiling of PHP. | The shared objects need to be loaded every time a script is being executed (every hit), which is very slow.
The size of PHP remains small by "outsourcing" certain functionality. | External additional files clutter up the disk.
 |  | Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution).
To sum up, external modules are great for third-party products, small additions to PHP that are rarely used, or just for testing purposes. To develop additional functionality quickly, external modules provide the best results. For frequent usage, larger implementations, and complex code, the disadvantages outweigh the advantages.

Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.

Built-in Modules

Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
No need to load the module specifically; the functionality is instantly available. | Changes to built-in modules require recompiling of PHP.
No external files clutter up the disk; everything resides in the PHP binary. | The PHP binary grows and consumes more memory.
Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.

The Zend Engine

Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.

Source Layout

Informacja:

Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at » http://httpd.apache.org/) and, of course, with PHP (available at » http://www.php.net/ - does it need to be said?).

Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.

Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.

The following table describes the contents of the major directories.

Directory | Contents
php-src | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory.
php-src/ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it).
php-src/main | This directory contains the main php macros and definitions. (important)
php-src/pear | Directory for the PHP Extension and Application Repository. This directory contains core PEAR files.
php-src/sapi | Contains the code for the different server abstraction layers.
TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
ZendEngine2 | Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important).

Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:

  • php-src/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.

  • php-src/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.

  • php-src/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.

You should also follow some sub-inclusions from these files; for example, the ones relating to the Zend executor, the PHP initialization file support, and such. After reading these files, take the time to navigate around the package a little to see the interdependencies of all files and modules - how they relate to each other and especially how they make use of each other. This also helps you to adapt to the coding style in which PHP is authored. To extend PHP, you should quickly adapt to this style.

Extension Conventions

Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.

Macros

For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)

Memory Management

Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:

Function | Description
emalloc() | Serves as replacement for malloc().
efree() | Serves as replacement for free().
estrdup() | Serves as replacement for strdup().
estrndup() | Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it.
ecalloc() | Serves as replacement for calloc().
erealloc() | Serves as replacement for realloc().
emalloc(), estrdup(), estrndup(), ecalloc(), and erealloc() allocate internal memory; efree() frees these previously allocated blocks. Memory handled by the e*() functions is considered local to the current process and is discarded as soon as the script executed by this process is terminated.
Ostrzeżenie

To allocate resident memory that survives termination of the current script, you can use malloc() and free(). This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks.

Zend also features a thread-safe resource manager to provide better native support for multithreaded Web servers. This requires you to allocate local structures for all of your global variables to allow concurrent threads to be run. Because the thread-safe mode of Zend was not finished back when this was written, it is not yet extensively covered here.

Directory and File Functions

The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level.

Zend Function | Regular C Function
V_GETCWD() | getcwd()
V_FOPEN() | fopen()
V_OPEN() | open()
V_CHDIR() | chdir()
V_GETWD() | getwd()
V_CHDIR_FILE() | Takes a file path as an argument and changes the current working directory to that file's directory.
V_STAT() | stat()
V_LSTAT() | lstat()

String Handling

Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)

Complex Types

Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.

Informacja:

To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.

PHP's Automatic Build System

PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see » http://www.gnu.org/software/m4/)

All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.

Step by step, the process looks like this:

:~/cvs/php4/ext:> ./ext_skel --extname=my_module
Creating directory my_module
Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/my_module/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-my_module
5.  $ make
6.  $ ./php -f ext/my_module/my_module.php
7.  $ vi ext/my_module/my_module.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
This instruction creates the aforementioned files. To include the new module in the automatic configuration and build process, you have to run buildconf, which regenerates the configure script by searching through the ext directory and including all found config.m4 files.

The default config.m4 shown in The default config.m4. is a bit more complex:

Przykład #1 The default config.m4.

dnl $Id: build.xml 297078 2010-03-29 16:25:51Z degeberg $
dnl config.m4 for extension my_module

dnl Comments in this file start with the string 'dnl'.
dnl Remove where necessary. This file will not work
dnl without editing.

dnl If your extension references something external, use with:

dnl PHP_ARG_WITH(my_module, for my_module support,
dnl Make sure that the comment is aligned:
dnl [  --with-my_module             Include my_module support])

dnl Otherwise use enable:

dnl PHP_ARG_ENABLE(my_module, whether to enable my_module support,
dnl Make sure that the comment is aligned:
dnl [  --enable-my_module           Enable my_module support])

if test "$PHP_MY_MODULE" != "no"; then
  dnl Write more examples of tests here...

  dnl # --with-my_module -> check with-path
  dnl SEARCH_PATH="/usr/local /usr"     # you might want to change this
  dnl SEARCH_FOR="/include/my_module.h"  # you most likely want to change this
  dnl if test -r $PHP_MY_MODULE/; then # path given as parameter
  dnl   MY_MODULE_DIR=$PHP_MY_MODULE
  dnl else # search default path list
  dnl   AC_MSG_CHECKING([for my_module files in default path])
  dnl   for i in $SEARCH_PATH ; do
  dnl     if test -r $i/$SEARCH_FOR; then
  dnl       MY_MODULE_DIR=$i
  dnl       AC_MSG_RESULT(found in $i)
  dnl     fi
  dnl   done
  dnl fi
  dnl
  dnl if test -z "$MY_MODULE_DIR"; then
  dnl   AC_MSG_RESULT([not found])
  dnl   AC_MSG_ERROR([Please reinstall the my_module distribution])
  dnl fi

  dnl # --with-my_module -> add include path
  dnl PHP_ADD_INCLUDE($MY_MODULE_DIR/include)

  dnl # --with-my_module -> chech for lib and symbol presence
  dnl LIBNAME=my_module # you may want to change this
  dnl LIBSYMBOL=my_module # you most likely want to change this

  dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
  dnl [
  dnl   PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $MY_MODULE_DIR/lib, MY_MODULE_SHARED_LIBADD)
  dnl   AC_DEFINE(HAVE_MY_MODULELIB,1,[ ])
  dnl ],[
  dnl   AC_MSG_ERROR([wrong my_module lib version or lib not found])
  dnl ],[
  dnl   -L$MY_MODULE_DIR/lib -lm -ldl
  dnl ])
  dnl
  dnl PHP_SUBST(MY_MODULE_SHARED_LIBADD)

  PHP_NEW_EXTENSION(my_module, my_module.c, $ext_shared)
fi

If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.

Note: Everything prefixed with dnl is treated as a comment and is not parsed.

The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.

The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.

By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":

if test "$PHP_MY_MODULE" == "yes"; then dnl
    Action.. PHP_EXTENSION(my_module, $ext_shared)
    fi
This would require you to use --enable-my_module each time when reconfiguring and recompiling PHP.

Note: Be sure to run buildconf every time you change config.m4!

We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files.

Creating Extensions

We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. A simple extension. shows the source.

Przykład #2 A simple extension.

/* include standard header */
#include "php.h"

/* declaration of functions to be exported */
ZEND_FUNCTION(first_module);

/* compiled function list so Zend knows what's in this module */
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};

/* compiled module information */
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */
#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
#endif

/* implement function that is meant to be made available to PHP */
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}

This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)

Informacja:

The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions.

Compiling Modules

There are basically two ways to compile modules:

  • Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.

  • Compile the sources manually.

The first method should definitely be favored, since, as of PHP 4.0, this has been standardized into a sophisticated build process. The fact that it is so sophisticated is also its drawback, unfortunately - it's hard to understand at first. We'll provide a more detailed introduction to this later in the chapter, but first let's work with the default files.

The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.

Compiling Using Make

To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an updated configure script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.

After you run buildconf, configure --help shows the following additional modules:

  --enable-array_experiments   BOOK: Enables array experiments
  --enable-call_userland       BOOK: Enables userland module
  --enable-cross_conversion    BOOK: Enables cross-conversion module
  --enable-first_module        BOOK: Enables first module
  --enable-infoprint           BOOK: Enables infoprint module
  --enable-reference_test      BOOK: Enables reference test module
  --enable-resource_test       BOOK: Enables resource test module
  --enable-variable_creation   BOOK: Enables variable-creation module

The module shown earlier in A simple extension. can be enabled with --enable-first_module or --enable-first_module=yes.

Compiling Manually

To compile your modules manually, you need the following commands:

Action | Command
Compiling | cc -fpic -DCOMPILE_DL_FIRST_MODULE=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
Linking | cc -shared -L/usr/local/lib -rdynamic -o <your_module_file> <your_object_file(s)>
The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL_FIRST_MODULE to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.

Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.

The link command is also a plain vanilla command instructing linkage as a dynamic module.

You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).

Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)

Using Extensions

Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in A test file for first_module.so.. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.

Ostrzeżenie

For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments.

Przykład #3 A test file for first_module.so.

<?php

// remove next comment if necessary
// dl("first_module.so");

$param = 2;
$return = first_module($param);

print("We sent '$param' and got '$return'");

?>

Calling this PHP file should output the following:

We sent '2' and got '2'

If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.

If you've gotten this far, congratulations! You just built your first extension to PHP.

Troubleshooting

Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation.

PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.

Source Discussion

Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.

Module Structure

All PHP modules follow a common structure:

  • Header file inclusions (to include all required macros, API definitions, etc.)

  • C declaration of exported functions (required to declare the Zend function block)

  • Declaration of the Zend function block

  • Declaration of the Zend module block

  • Implementation of get_module()

  • Implementation of all exported functions

Header File Inclusions

The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.

Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h. If you created your module using ext_skel you already have such a header file prepared.

Declaring Exported Functions

To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:

ZEND_FUNCTION ( my_function );

ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:

void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS );
Expanding INTERNAL_FUNCTION_PARAMETERS results in the following:
void zif_my_function( int ht
                    , zval * return_value
                    , zval * this_ptr
                    , int return_value_used
                    , zend_executor_globals * executor_globals
                    );

Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.

The parameter list of this declaration is very important; you should keep these parameters in mind (see Zend's Parameters to Functions Called from PHP for descriptions).

Zend's Parameters to Functions Called from PHP
Parameter | Description
ht | The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value.
return_value | This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below.
this_ptr | Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer.
return_value_used | This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this).
executor_globals | This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro TSRMLS_FETCH().

Declaration of the Zend Function Block

Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Internal declaration of zend_function_entry..

Przykład #4 Internal declaration of zend_function_entry.

typedef struct _zend_function_entry {
    char *fname;
    void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
    unsigned char *func_arg_types;
} zend_function_entry;
Entry | Description
fname | Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, first_module).
handler | Pointer to the C function responsible for handling calls to this function. For example, see the standard macro INTERNAL_FUNCTION_PARAMETERS discussed earlier.
func_arg_types | Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL.
In the example above, the declaration looks like this:
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    {NULL, NULL, NULL}
};
You can see that the last entry in the list always has to be {NULL, NULL, NULL}. This marker has to be set for Zend to know when the end of the list of exported functions is reached.

Informacja:

You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!

The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.

Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.

Macros for Defining Functions shows a list of all the macros that you can use to define functions.

Macros for Defining Functions
Macro Name | Description
ZEND_FE(name, arg_types) | Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION.
ZEND_NAMED_FE(php_name, name, arg_types) | Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION.
ZEND_FALIAS(name, alias, arg_types) | Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead.
PHP_FE(name, arg_types) | Old PHP API equivalent of ZEND_FE.
PHP_NAMED_FE(runtime_name, name, arg_types) | Old PHP API equivalent of ZEND_NAMED_FE.

Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.

Declaration of the Zend Module Block

This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Internal declaration of zend_module_entry..

Przykład #5 Internal declaration of zend_module_entry.

typedef struct _zend_module_entry zend_module_entry;

    struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    char *name;
    zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    char *version;

[ Rest of the structure is not interesting here ]

};
Entry | Description
size, zend_api, zend_debug and zts | Usually filled with the "STANDARD_MODULE_HEADER", which fills these four members with the size of the whole zend_module_entry, the ZEND_MODULE_API_NO, whether it is a debug build or normal build (ZEND_DEBUG) and if ZTS is enabled (USING_ZTS).
name | Contains the module name (for example, "File functions", "Socket functions", "Crypt", etc.). This name will show up in phpinfo(), in the section "Additional Modules."
functions | Points to the Zend function block, discussed in the preceding section.
module_startup_func | This function is called once upon module initialization and can be used to do one-time initialization steps (such as initial memory allocation, etc.). To indicate a failure during initialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINIT.
module_shutdown_func | This function is called once upon module shutdown and can be used to do one-time deinitialization steps (such as memory deallocation). This is the counterpart to module_startup_func(). To indicate a failure during deinitialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MSHUTDOWN.
request_startup_func | This function is called once upon every page request and can be used to do one-time initialization steps that are required to process a request. To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request startup function is called right after the module startup function (both initialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RINIT.
request_shutdown_func | This function is called once after every page request and works as counterpart to request_startup_func(). To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request shutdown function is immediately followed by a call to the module shutdown handler (both deinitialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RSHUTDOWN.
info_func | When phpinfo() is called in a script, Zend cycles through all loaded modules and calls this function. Every module then has the chance to print its own "footprint" into the output page. Generally this is used to dump environmental or statistical information. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINFO.
version | The version of the module. You can use NO_VERSION_YET if you don't want to give the module a version number yet, but we really recommend that you add a version string here. Such a version string can look like this (in chronological order): "2.5-dev", "2.5RC1", "2.5" or "2.5pl3".
Remaining structure elements | These are used internally and can be prefilled by using the macro STANDARD_MODULE_PROPERTIES_EX. You should not assign any values to them. Use STANDARD_MODULE_PROPERTIES_EX only if you use global startup and shutdown functions; otherwise, use STANDARD_MODULE_PROPERTIES directly.

In our example, this structure is implemented as follows:

zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES,
};
This is basically the easiest and most minimal set of values you could ever use. The module name is set to First Module, then the function list is referenced, after which all startup and shutdown functions are marked as being unused.

For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in Macros to Declare Startup and Shutdown Functions. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.

Macros to Declare Startup and Shutdown Functions
Macro | Description
ZEND_MINIT(module) | Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION.
ZEND_MSHUTDOWN(module) | Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION.
ZEND_RINIT(module) | Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION.
ZEND_RSHUTDOWN(module) | Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION.
ZEND_MINFO(module) | Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION.

Creation of get_module()

This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:

#if COMPILE_DL_FIRSTMOD
     ZEND_GET_MODULE(firstmod)
#endif

The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.

get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.

If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.

Implementation of All Exported Functions

Implementing the exported functions is the final step. The example function in first_module looks like this:

ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}
The function declaration is done using ZEND_FUNCTION, which corresponds to ZEND_FE in the function entry table (discussed earlier).

After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).

Summary

That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.

Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.

Accepting Arguments

One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice.

PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.

Determining the Number of Arguments

Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.

The following code checks for the correct number of arguments:

if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT;
If the function is not called with two arguments, it exits with an error message. The code snippet above makes use of the tool macro WRONG_PARAM_COUNT, which can be used to generate a standard error message like:
"Warning: Wrong parameter count for firstmodule() in /home/www/htdocs/firstmod.php on line 5"

This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:

ZEND_API void wrong_param_count(void);

#define WRONG_PARAM_COUNT { wrong_param_count(); return; }
As you can see, it calls an internal function named wrong_param_count() that's responsible for printing the warning. For details on generating customized error messages, see the later section "Printing Information."

Retrieving Arguments

Informacja: New parameter parsing API

This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0.

Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameters, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.

The prototype for parameter parsing function looks like this:

int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);
The first argument to this function is supposed to be the number of actual parameters passed to your function, so ZEND_NUM_ARGS() can be used for that. The second parameter should always be TSRMLS_CC macro. The third argument is a string that specifies the number and types of arguments your function is expecting, similar to how printf format string specifies the number and format of the output values it should operate on. And finally the rest of the arguments are pointers to variables which should receive the values from the parameters.

zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.

If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.

Here are some sample error messages:

Warning - ini_get_all() requires at most 1 parameter, 2 given
Warning - wddx_deserialize() expects parameter 1 to be string, array given
Of course each error message is accompanied by the filename and line number on which it occurs.

Here is the full list of type specifiers:

  • l - long

  • d - double

  • s - string (with possible null bytes) and its length

  • b - boolean

  • r - resource, stored in zval*

  • a - array, stored in zval*

  • o - object (of any class), stored in zval*

  • O - object (of class specified by class entry), stored in zval*

  • z - the actual zval*

The following characters also have a meaning in the specifier string:

  • | - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.

  • / - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.

  • ! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.

The best way to illustrate the usage of this function is through examples:

/* Gets a long, a string and its length, and a zval. */
long l;
char *s;
int s_len;
zval *param;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "lsz", &l, &s, &s_len, &param) == FAILURE) {
    return;
}

/* Gets an object of class specified by my_ce, and an optional double. */
zval *obj;
double d = 0.5;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "O|d", &obj, my_ce, &d) == FAILURE) {
    return;
}

/* Gets an object or null, and an array.
   If null is passed for object, obj will be set to NULL. */
zval *obj;
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) {
    return;
}

/* Gets a separated array. */
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) {
    return;
}

/* Get only the first three parameters (useful for varargs functions). */
zval *z;
zend_bool b;
zval *r;
if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) {
    return;
}

Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.

The parsing function has an extended version that allows for an additional flags argument that controls its actions.

int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);

The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.

For example, here is how you would get either a set of three longs or a string:

long l1, l2, l3;
char *s;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                             ZEND_NUM_ARGS() TSRMLS_CC,
                             "lll", &l1, &l2, &l3) == SUCCESS) {
    /* manipulate longs */
} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                                    ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) {
    /* manipulate string */
} else {
    php_error(E_WARNING, "%s() takes either three long values or a string as argument",
              get_active_function_name(TSRMLS_C));
    return;
}

With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.

Old way of retrieving arguments (deprecated)

Informacja: Deprecated parameter parsing API

This API is deprecated and superseded by the new ZEND parameter parsing API.

After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():

zval **parameter;

if(zend_get_parameters_ex(1, &parameter) != SUCCESS)
  WRONG_PARAM_COUNT;
All arguments are stored in a zval container, which needs to be pointed to twice. The snippet above tries to retrieve one argument and make it available to us via the parameter pointer.

zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.

The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.

To retrieve more than one argument, you can use a similar snippet:

zval **param1, **param2, **param3, **param4;

if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS)
    WRONG_PARAM_COUNT;

zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.

Dealing with a Variable Number of Arguments/Optional Parameters

If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.

For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:

zval **parameter_array[4];

/* get the number of arguments */
argument_count = ZEND_NUM_ARGS();

/* see if it satisfies our minimal request (2 arguments) */
/* and our maximal acceptance (4 arguments) */
if(argument_count < 2 || argument_count > 4)
    WRONG_PARAM_COUNT;

/* argument count is correct, now retrieve arguments */
if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS)
    WRONG_PARAM_COUNT;
First, the number of arguments is checked to make sure that it's in the accepted range. After that, zend_get_parameters_array_ex() is used to fill parameter_array with valid pointers to the argument values.

A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in PHP's implementation of variable arguments in fsockopen().. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.

Przykład #6 PHP's implementation of variable arguments in fsockopen().

pval **args[5];
int *sock=emalloc(sizeof(int));
int *sockp;
int arg_count=ARG_COUNT(ht);
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
unsigned short portno;
unsigned long conv;
char *key = NULL;
FLS_FETCH();

if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE) {
    CLOSE_SOCK(1);
    WRONG_PARAM_COUNT;
}

switch(arg_count) {
    case 5:
        convert_to_double_ex(args[4]);
        conv = (unsigned long) (Z_DVAL_PP(args[4]) * 1000000.0);
        timeout.tv_sec = conv / 1000000;
        timeout.tv_usec = conv % 1000000;
        /* fall-through */
    case 4:
        if (!PZVAL_IS_REF(*args[3])) {
            php_error(E_WARNING,"error string argument to fsockopen not passed by reference");
        }
        pval_copy_constructor(*args[3]);
        ZVAL_EMPTY_STRING(*args[3]);
        /* fall-through */
    case 3:
        if (!PZVAL_IS_REF(*args[2])) {
            php_error(E_WARNING,"error argument to fsockopen not passed by reference");
            return;
        }
        ZVAL_LONG(*args[2], 0);
        break;
}

convert_to_string_ex(args[0]);
convert_to_long_ex(args[1]);
portno = (unsigned short) Z_LVAL_P(args[1]);

key = emalloc(Z_STRLEN_P(args[0]) + 10);

fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.

This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.

Accessing Arguments

To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.

To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Argument Conversion Functions).

Note: All conversion functions expect a **zval as parameter.

Argument Conversion Functions
Function | Description
convert_to_boolean_ex() | Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE).
convert_to_long_ex() | Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise.
convert_to_double_ex() | Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise.
convert_to_string_ex() | Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object".
convert_to_array_ex(value) | Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0.
convert_to_object_ex(value) | Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content.
convert_to_null_ex(value) | Forces the type to become a NULL value, meaning empty.

Informacja:

You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM.

Cross-conversion behavior of PHP.

Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.

Following is a quote from the sample module discussed previously, which makes use of the conversion functions:

zval **parameter;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &parameter) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

convert_to_long_ex(parameter);

RETURN_LONG(Z_LVAL_P(parameter));
After retrieving the parameter pointer, the parameter value is converted to a long (an integer), which also forms the return value of this function. Understanding access to the contents of the value requires a short discussion of the zval type, whose definition is shown in PHP/Zend zval type definition..

Przykład #7 PHP/Zend zval type definition.

typedef pval zval;

typedef struct _zval_struct zval;

typedef union _zvalue_value {
    long lval;                 /* long value */
    double dval;               /* double value */
    struct {
        char *val;
        int len;
    } str;
    HashTable *ht;             /* hash table value */
    struct {
        zend_class_entry *ce;
        HashTable *properties;
    } obj;
} zvalue_value;

struct _zval_struct {
    /* Variable information */
    zvalue_value value;        /* value */
    unsigned char type;        /* active type */
    unsigned char is_ref;
    short refcount;
};

Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Zend zval Structure, Zend zvalue_value Structure and Zend Variable Type Constants.

Zend zval Structure
Entry | Description
value | Union containing this variable's contents. See Zend zvalue_value Structure for a description.
type | Contains this variable's type. For a list of available types, see Zend Variable Type Constants.
is_ref | 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable.
refcount | The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value.
Zend zvalue_value Structure
Entry | Description
lval | Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE.
dval | Use this property if the variable is of the type IS_DOUBLE.
str | This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00.
ht | This entry points to the variable's hash table entry if the variable is an array.
obj | Use this property if the variable is of the type IS_OBJECT.
Zend Variable Type Constants
Constant | Description
IS_NULL | Denotes a NULL (empty) value.
IS_LONG | A long (integer) value.
IS_DOUBLE | A double (floating point) value.
IS_STRING | A string.
IS_ARRAY | Denotes an array.
IS_OBJECT | An object.
IS_BOOL | A Boolean value.
IS_RESOURCE | A resource (for a discussion of resources, see the appropriate section below).
IS_CONSTANT | A constant (defined) value.

To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.

Accessing arrays and objects is a bit more complicated and is discussed later.

Dealing with Arguments Passed by Reference

If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.

What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!

We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.

Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).

zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.

This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.

To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:

my_function(&$parameter);

But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.

This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Testing for referenced parameter passing..

Przykład #8 Testing for referenced parameter passing.

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
    return;

/* check for parameter being passed by reference */
if (!PZVAL_IS_REF(parameter)) {
{
    zend_error(E_WARNING, "Parameter wasn't passed by reference");
    RETURN_NULL();
}

/* make changes to the parameter */
ZVAL_LONG(parameter, 10);
Testing for referenced parameter passing

Assuring Write Safety for Other Parameters

You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:

zval **parameter;

/* retrieve parameter */
zend_get_parameters_ex(1, &parameter);

/* at this stage, <parameter> still is connected */
/* to Zend's internal data buffers */

/* make <parameter> write-safe */
SEPARATE_ZVAL(parameter);

/* now we can safely modify <parameter> */
/* without implying global changes */
SEPARATE_ZVAL uses emalloc() to allocate the new zval container, which means that even if you don't deallocate this memory yourself, it will be destroyed automatically upon script termination. However, doing a lot of calls to this macro without freeing the resulting containers will clutter up your RAM.

Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.

Creating Variables

When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.

Overview

To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:

zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable);

/* the variable is now accessible to the script by using $new_variable_name */

The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.

ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.

Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.

If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():

zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
zend_hash_update(
    EG(active_symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
This is actually the standard method used in most modules.

The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:

zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable);
The macro ZEND_SET_SYMBOL is now being called with a reference to the main, global symbol table by referring EG(symbol_table).

Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.

Similarly, to get a more efficient version, you can hardcode the symbol table update:

zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
zend_hash_update(
    &EG(symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
Creating variables with different scopes. shows a sample source that creates two variables - local_variable with a local scope and global_variable with a global scope (see Figure 9.7). The full example can be found on the CD-ROM.

Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.

Przykład #9 Creating variables with different scopes.

ZEND_FUNCTION(variable_creation)
{
    zval *new_var1, *new_var2;

    MAKE_STD_ZVAL(new_var1);
    MAKE_STD_ZVAL(new_var2);

    ZVAL_LONG(new_var1, 10);
    ZVAL_LONG(new_var2, 5);

    ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1);
    ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2);

    RETURN_NULL();

}
Creating variables with different scopes

Longs (Integers)

Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Creation of a long.).

Przykład #10 Creation of a long.

zval *new_long;

MAKE_STD_ZVAL(new_long);

new_long-&gt;type = IS_LONG;
new_long-&gt;value.lval = 10;
Alternatively, you can use the macro ZVAL_LONG:
zval *new_long;

MAKE_STD_ZVAL(new_long);
ZVAL_LONG(new_long, 10);

Doubles (Floats)

Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.

zval *new_double;

MAKE_STD_ZVAL(new_double);

new_double-&gt;type = IS_DOUBLE;
new_double-&gt;value.dval = 3.45;
Alternatively, you can use the macro ZVAL_DOUBLE:
zval *new_double;

MAKE_STD_ZVAL(new_double);
ZVAL_DOUBLE(new_double, 3.45);

Strings

Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:

zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);

new_string-&gt;type = IS_STRING;
new_string-&gt;value.str.len = strlen(string_contents);
new_string-&gt;value.str.val = estrdup(string_contents);
Note the usage of Zend's estrdup() here. Of course, you can also use the predefined macro ZVAL_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);
ZVAL_STRING(new_string, string_contents, 1);
ZVAL_STRING accepts a third parameter that indicates whether the supplied string contents should be duplicated (using estrdup()). Setting this parameter to 1 causes the string to be duplicated; 0 simply uses the supplied pointer for the variable contents. This is most useful if you want to create a new variable referring to a string that's already allocated in Zend internal memory.

If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.

To create empty strings, set the string length to 0 and use empty_string as contents:

new_string-&gt;type = IS_STRING;
new_string-&gt;value.str.len = 0;
new_string-&gt;value.str.val = empty_string;
Of course, there's a macro for this as well (ZVAL_EMPTY_STRING):
MAKE_STD_ZVAL(new_string);
ZVAL_EMPTY_STRING(new_string);

Booleans

Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:

zval *new_bool;

MAKE_STD_ZVAL(new_bool);

new_bool-&gt;type = IS_BOOL;
new_bool-&gt;value.lval = 1;
The corresponding macros for this type are ZVAL_BOOL (allowing specification of the value) as well as ZVAL_TRUE and ZVAL_FALSE (which explicitly set the value to TRUE and FALSE, respectively).

Arrays

Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.

There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().

zval *new_array;

MAKE_STD_ZVAL(new_array);

array_init(new_array);
array_init() always returns SUCCESS.

To add new elements to the array, you can use numerous functions, depending on what you want to do. Zend's API for Associative Arrays, Zend's API for Indexed Arrays, Part 1 and Zend's API for Indexed Arrays, Part 2 describe these functions. All functions return FAILURE on failure and SUCCESS on success.

Zend's API for Associative Arrays
Function | Description
add_assoc_long(zval *array, char *key, long n);() | Adds an element of type long.
add_assoc_unset(zval *array, char *key);() | Adds an unset element.
add_assoc_bool(zval *array, char *key, int b);() | Adds a Boolean element.
add_assoc_resource(zval *array, char *key, int r);() | Adds a resource to the array.
add_assoc_double(zval *array, char *key, double d);() | Adds a floating-point value.
add_assoc_string(zval *array, char *key, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); () | Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string().
add_assoc_zval(zval *array, char *key, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...
Zend's API for Indexed Arrays, Part 1
Function | Description
add_index_long(zval *array, uint idx, long n);() | Adds an element of type long.
add_index_unset(zval *array, uint idx);() | Adds an unset element.
add_index_bool(zval *array, uint idx, int b);() | Adds a Boolean element.
add_index_resource(zval *array, uint idx, int r);() | Adds a resource to the array.
add_index_double(zval *array, uint idx, double d);() | Adds a floating-point value.
add_index_string(zval *array, uint idx, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string().
add_index_zval(zval *array, uint idx, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...
Zend's API for Indexed Arrays, Part 2
Function | Description
add_next_index_long(zval *array, long n);() | Adds an element of type long.
add_next_index_unset(zval *array);() | Adds an unset element.
add_next_index_bool(zval *array, int b);() | Adds a Boolean element.
add_next_index_resource(zval *array, int r);() | Adds a resource to the array.
add_next_index_double(zval *array, double d);() | Adds a floating-point value.
add_next_index_string(zval *array, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string().
add_next_index_zval(zval *array, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update() for associative arrays (see Adding an element to an associative array.) and zend_hash_index_update() for indexed arrays (see Adding an element to an indexed array.):

Przykład #11 Adding an element to an associative array.

zval *new_array, *new_element;
char *key = "element_key";

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_update(new_array-&gt;value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

Przykład #12 Adding an element to an indexed array.

zval *new_array, *new_element;
int key = 2;

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_index_update(new_array-&gt;value.ht, key, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

To emulate the functionality of add_next_index_*(), you can use this:

zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL)

Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.

Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.

Objects

Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.

To initialize an object, you use the function object_init():

zval *new_object;

MAKE_STD_ZVAL(new_object);

if(object_init(new_object) != SUCCESS)
{
    // do error handling here
}
You can use the functions described in Zend's API for Object Creation to add members to your object.

Zend's API for Object Creation
Function | Description
add_property_long(zval *object, char *key, long l);() | Adds a long to the object.
add_property_unset(zval *object, char *key);() | Adds an unset property to the object.
add_property_bool(zval *object, char *key, int b);() | Adds a Boolean to the object.
add_property_resource(zval *object, char *key, long r);() | Adds a resource to the object.
add_property_double(zval *object, char *key, double d);() | Adds a double to the object.
add_property_string(zval *object, char *key, char *str, int duplicate);() | Adds a string to the object.
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() | Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe.
add_property_zval(zval *obect, char *key, zval *container):() | Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects.

Resources

Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.

For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.

Informacja:

In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.

To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.

The Zend function to register your resource handler is defined as:

ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number);

There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.

zend_register_list_destructors_ex() accepts the following parameters:

ld | Normal resource destruction handler callback
pld | Pesistent resource destruction handler callback
type_name | A string specifying the name of your resource. It's always a good thing to specify a unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource.
module_number | The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over.
The return value is a unique integer ID for your resource type.

The resource destruction handler (either normal or persistent resources) has the following prototype:

void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);
The passed rsrc is a pointer to the following structure:
typedef struct _zend_rsrc_list_entry {

    void *ptr;
    int type;
    int refcount;

} zend_rsrc_list_entry;
The member void *ptr is the actual pointer to your resource.

Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:

typedef struct {

    int resource_link;
    int resource_type;

} my_resource;
Our resource destruction handler is probably going to look something like this:
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

    // You most likely cast the void pointer to your structure type

    my_resource *my_rsrc = (my_resource *) rsrc->ptr;

    // Now do whatever needs to be done with you resource. Closing
    // Files, Sockets, freeing additional memory, etc.
    // Also, don't forget to actually free the memory for your resource too!

    do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
}

Informacja:

One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!

Now that we have defined

  1. what our resource is and

  2. our resource destruction handler

we can go on and do the rest of the steps:

  1. create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it

  2. define the resource name

  3. write the resource destruction handler

  4. and finally register the handler

// Somewhere in your extension, define the variable for your registered resources.
    // If you wondered what 'le' stands for: it simply means 'list entry'.
    static int le_myresource;

    // It's nice to define your resource name somewhere
    #define le_myresource_name  "My type of resource"

    [...]

    // Now actually define our resource destruction handler
    void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

        my_resource *my_rsrc = (my_resource *) rsrc->ptr;
        do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
    }

    [...]

    PHP_MINIT_FUNCTION(my_extension) {

        // Note that 'module_number' is already provided through the
        // PHP_MINIT_FUNCTION() function definition.

        le_myresource = zend_register_list_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number);

        // You can register additional resources, initialize
        // your global vars, constants, whatever.
    }

To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h. Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:

int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);
rsrc_result | This is an already initialized zval * container.
rsrc_pointer | Your resource pointer you want to store.
rsrc_type | The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource.
The return value is a unique integer identifier for that resource.

What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:

rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type);

    if (rsrc_result) {
        rsrc_result->value.lval = rsrc_id;
        rsrc_result->type = IS_RESOURCE;
    }

    return rsrc_id;
The returned rsrc_id uniquely identifies the newly registered resource. You can use the macro RETURN_RESOURE to return it to the user:
    RETURN_RESOURCE(rsrc_id)

Informacja:

It is common practice that if you want to return the resource immediately to the user you specify the return_value as the zval * container.

Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.

Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:

ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type)
rsrc | This is your pointer which will point to your previously registered resource.
rsrc_type | This is the typecast argument for your pointer, e.g. myresource *.
rsrc_id | This is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given.
default_rsrc_id | This integer specifies the default resource ID if no resource could be fetched or -1.
resource_type_name | This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message.
resource_type | The resource_type you got back when registering the resource destruction handler. In our example this was le_myresource.
This macro has no return value. It is for the developers convenience and takes care of TSRMLS arguments passing and also does check if the resource could be fetched. It throws a warning message and returns the current PHP function with NULL if there was a problem retrieving the resource.

To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.

Macros for Automatic Global Variable Creation

In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table Macros for Global Variable Creation describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.

Macros for Global Variable Creation
Macro | Description
SET_VAR_STRING(name, value) | Creates a new string.
SET_VAR_STRINGL(name, value, length) | Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe.
SET_VAR_LONG(name, value) | Creates a new long.
SET_VAR_DOUBLE(name, value) | Creates a new double.

Creating Constants

Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.

To create your own constants, you can use the macros in Macros for Creating Constants. All the macros create a constant with the specified name and value.

You can also specify flags for each constant:

  • CONST_CS - This constant's name is to be treated as case sensitive.

  • CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.

To use the flags, combine them using a inary OR:
 // register a new constant of type "long"
     REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS |
     CONST_PERSISTENT);
There are two types of macros - REGISTER_*_CONSTANT andREGISTER_MAIN_*_CONSTANT. The first type creates constants bound to the current module. These constants are dumped from the symbol table as soon as the module that registered the constant is unloaded from memory. The second type creates constants that remain in the symbol table independently of the module.

Macros for Creating Constants
Macro | Description
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) | Registers a new constant of type long.
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) | Registers a new constant of type double.
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) | Registers a new constant of type string. The specified string must reside in Zend's internal memory.
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) | Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory.

Duplicating Variable Contents: The Copy Constructor

Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).

To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the rvalue (result of the evaluation of the right side of the operator) to the lvalue (same for the left side).

Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).

This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.

Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).

A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
   return;
}

// do modifications to the parameter here

// now we want to return the modified container:
*return_value = *parameter;
zval_copy_ctor(return_value);

The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.

If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.

The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.

Returning Values

Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.

To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in Predefined Macros for Returning Values from a Function and Predefined Macros for Setting the Return Value of a Function.

Informacja:

The macros in Predefined Macros for Returning Values from a Function automatically return from your function, those in Predefined Macros for Setting the Return Value of a Function only set the return value; they don't return from your function.

Predefined Macros for Returning Values from a Function
Macro | Description
RETURN_RESOURCE(resource) | Returns a resource.
RETURN_BOOL(bool) | Returns a Boolean.
RETURN_NULL() | Returns nothing (a NULL value).
RETURN_LONG(long) | Returns a long.
RETURN_DOUBLE(double) | Returns a double.
RETURN_STRING(string, duplicate) | Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup().
RETURN_STRINGL(string, length, duplicate) | Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however.
RETURN_EMPTY_STRING() | Returns an empty string.
RETURN_FALSE | Returns Boolean false.
RETURN_TRUE | Returns Boolean true.
Predefined Macros for Setting the Return Value of a Function
Macro | Description
RETVAL_RESOURCE(resource) | Sets the return value to the specified resource.
RETVAL_BOOL(bool) | Sets the return value to the specified Boolean value.
RETVAL_NULL | Sets the return value to NULL.
RETVAL_LONG(long) | Sets the return value to the specified long.
RETVAL_DOUBLE(double) | Sets the return value to the specified double.
RETVAL_STRING(string, duplicate) | Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING).
RETVAL_STRINGL(string, length, duplicate) | Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known.
RETVAL_EMPTY_STRING | Sets the return value to an empty string.
RETVAL_FALSE | Sets the return value to Boolean false.
RETVAL_TRUE | Sets the return value to Boolean true.

Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.

Printing Information

Often it's necessary to print messages to the output stream from your module, just as print() would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.

zend_printf()

zend_printf() works like the standard printf(), except that it prints to Zend's output stream.

zend_error()

zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.

zend_error(E_WARNING, "This function has been called with empty arguments");
Zend's Predefined Error Messages. shows a list of possible values (see below). These values are also referred to in php.ini. Depending on which error type you choose, your messages will be logged.
Zend's Predefined Error Messages.
Error | Description
E_ERROR | Signals an error and terminates execution of the script immediately.
E_WARNING | Signals a generic warning. Execution continues.
E_PARSE | Signals a parser error. Execution continues.
E_NOTICE | Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini.
E_CORE_ERROR | Internal error by the core; shouldn't be used by user-written modules.
E_COMPILE_ERROR | Internal error by the compiler; shouldn't be used by user-written modules.
E_COMPILE_WARNING | Internal warning by the compiler; shouldn't be used by user-written modules.
Display of warning messages in the browser.

Including Output in phpinfo()

After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().

PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.

Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). Source code and screenshot for output in phpinfo. shows a source example and its output. To print the table footer, use php_info_print_table_end().

Przykład #13 Source code and screenshot for output in phpinfo().

php_info_print_table_start();
php_info_print_table_header(2, "First column", "Second column");
php_info_print_table_row(2, "Entry in first row", "Another entry");
php_info_print_table_row(2, "Just to fill", "another row here");
php_info_print_table_end();
Output of phpinfo()

Execution Information

You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the TSRMLS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro TSRMLS_FETCH() once in that function; this will introduce them to your local scope.

Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Printing execution information..

Przykład #14 Printing execution information.

zend_printf("The name of the current function is %s&lt;br&gt;", get_active_function_name(TSRMLS_C));
zend_printf("The file currently executed is %s&lt;br&gt;", zend_get_executed_filename(TSRMLS_C));
zend_printf("The current line being executed is %i&lt;br&gt;", zend_get_executed_lineno(TSRMLS_C));
Printing execution information

Startup and Shutdown Functions

Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are module, and request startup and shutdown events.

The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).

For dynamic extensions, module and request startup/shutdown events happen at the same time.

Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.

Calling User Functions

You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.

User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.

ZEND_API int call_user_function_ex(HashTable *function_table, zval *object,
zval *function_name, zval **retval_ptr_ptr,
int param_count, zval **params[],
int no_separation);

Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.

Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro TSRMLS_FETCH once.

The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.

The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!

Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.

Calling user functions. shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.

Przykład #15 Calling user functions.

zval **function_name;
zval *retval;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

if((*function_name)->type != IS_STRING)
{
    zend_error(E_ERROR, "Function requires string argument");
}

TSRMSLS_FETCH();

if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != SUCCESS)
{
    zend_error(E_ERROR, "Function call failed");
}

zend_printf("We have %i as type\n", retval->type);

*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&retval);

<?php

dl("call_userland.so");

function test_function()
{
    echo "We are in the test function!\n";
    return 'hello';
}

$return_value = call_userland("test_function");

echo "Return value: '$return_value'";
?>

Powyższy przykład wyświetli:

We are in the test function!
We have 3 as type
Return value: 'hello'

Initialization File Support

PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.

To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.

PHP_INI_BEGIN()
PHP_INI_ENTRY("first_ini_entry",  "has_string_value", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("second_ini_entry", "2",                PHP_INI_SYSTEM, OnChangeSecond)
PHP_INI_ENTRY("third_ini_entry",  "xyz",              PHP_INI_USER, NULL)
PHP_INI_END()
The PHP_INI_ENTRY() macro accepts four parameters: the entry name, the entry value, its change permissions, and a pointer to a change-notification handler. Both entry name and value must be specified as strings, regardless of whether they really are strings or integers.

The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.

The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:

PHP_INI_MH(OnChangeSecond);             // handler for ini-entry "second_ini_entry"

// specify ini-entries here

PHP_INI_MH(OnChangeSecond)
{

    zend_printf("Message caught, our ini entry has been changed to %s&lt;br&gt;", new_value);

    return(SUCCESS);

}
The new value is given to the change handler as string in the variable new_value. When looking at the definition of PHP_INI_MH, you actually have a few parameters to use:
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value,
                                  uint new_value_length, void *mh_arg1,
                                  void *mh_arg2, void *mh_arg3)
All these definitions can be found in php_ini.h. Your message handler will have access to a structure that contains the full entry, the new value, its length, and three optional arguments. These optional arguments can be specified with the additional macros PHP_INI_ENTRY1 (allowing one additional argument), PHP_INI_ENTRY2 (allowing two additional arguments), and PHP_INI_ENTRY3 (allowing three additional arguments).

The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.

Access to initialization entries can also be handled with the macros shown in Macros to Access Initialization Entries in PHP.

Macros to Access Initialization Entries in PHP
Macro | Description
INI_INT(name) | Returns the current value of entry name as integer (long).
INI_FLT(name) | Returns the current value of entry name as float (double).
INI_STR(name) | Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_BOOL(name) | Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).
INI_ORIG_INT(name) | Returns the original value of entry name as integer (long).
INI_ORIG_FLT(name) | Returns the original value of entry name as float (double).
INI_ORIG_STR(name) | Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_ORIG_BOOL(name) | Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).

Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():

ZEND_MINIT_FUNCTION(mymodule)
{

    REGISTER_INI_ENTRIES();

}

ZEND_MSHUTDOWN_FUNCTION(mymodule)
{

    UNREGISTER_INI_ENTRIES();

}

Where to Go from Here

You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.

Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.

Reference: Some Configuration Macros

config.m4

The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in M4 Macros for config.m4.

M4 Macros for config.m4
Macro | Description
AC_MSG_CHECKING(message) | Prints a "checking <message>" text during configure.
AC_MSG_RESULT(value) | Gives the result to AC_MSG_CHECKING; should specify either yes or no as value.
AC_MSG_ERROR(message) | Prints message as error message during configure and aborts the script.
AC_DEFINE(name,value,description) | Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module).
AC_ADD_INCLUDE(path) | Adds a compiler include path; for example, used if the module needs to add search paths for header files.
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) | Specifies an additional library to link.
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) | Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest.
PHP_EXTENSION(modulename, [shared]) | This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>.

API Macros

A set of macros was introduced into Zend's API that simplify access to zval containers (see API Macros for Accessing zval Containers).

API Macros for Accessing zval Containers
Macro | Refers to
Z_LVAL(zval) | (zval).value.lval
Z_DVAL(zval) | (zval).value.dval
Z_STRVAL(zval) | (zval).value.str.val
Z_STRLEN(zval) | (zval).value.str.len
Z_ARRVAL(zval) | (zval).value.ht
Z_LVAL_P(zval) | (*zval).value.lval
Z_DVAL_P(zval) | (*zval).value.dval
Z_STRVAL_P(zval_p) | (*zval).value.str.val
Z_STRLEN_P(zval_p) | (*zval).value.str.len
Z_ARRVAL_P(zval_p) | (*zval).value.ht
Z_LVAL_PP(zval_pp) | (**zval).value.lval
Z_DVAL_PP(zval_pp) | (**zval).value.dval
Z_STRVAL_PP(zval_pp) | (**zval).value.str.val
Z_STRLEN_PP(zval_pp) | (**zval).value.str.len
Z_ARRVAL_PP(zval_pp) | (**zval).value.ht
Streams API for PHP Extension Authors
TSRM API
Zend Engine 1


TSRM API

Zend API: Hackowanie rdzenia PHP
FAQ
Zend Engine 1


FAQ: Często zadawane pytania

  • General Information
  • Mailing lists
  • Obtaining PHP
  • Database issues
  • Installation
  • Build Problems
  • Using PHP
  • Password Hashing — Safe Password Hashing
  • PHP and HTML
  • PHP and COM
  • PHP i inne języki
  • Migrating from PHP 4 to PHP 5
  • Miscellaneous Questions
TSRM API
General Information
Podręcznik PHP


General Information

This section holds the most general questions about PHP: what it is and what it does.

  1. What is PHP?
  2. What does PHP stand for?
  3. What is the relation between the versions?
  4. Can I run several versions of PHP at the same time?
  5. What are the differences between PHP 4 and PHP 5?
  6. I think I found a bug! Who should I tell?
What is PHP?

From the preface of the manual:

PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

What does PHP stand for?

PHP stands for PHP: Hypertext Preprocessor. This confuses many people because the first word of the acronym is the acronym. This type of acronym is called a recursive acronym. For more information, the curious can visit » Free On-Line Dictionary of Computing or the » Wikipedia entry on recursive acronyms.

What is the relation between the versions?

PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 5 is the current generation of PHP, which uses the » Zend engine 2 which, among other things, offers many additional OOP features.

Can I run several versions of PHP at the same time?

Yes. See the INSTALL file that is included in the PHP source distribution.

What are the differences between PHP 4 and PHP 5?

While PHP 5 was purposely designed to be as compatible as possible with previous versions, there are some significant changes. Some of these changes include:

  • A new OOP model based on the Zend Engine 2.0
  • A new extension for improved MySQL support
  • Built-in native support for SQLite
  • A new error reporting constant, E_STRICT, for run-time code suggestions
  • A host of new functions to simplify code authoring (and reduce the need to write your own functions for many common procedures)
For more detailed information, please view the section on Migrating from PHP 4 to PHP 5 and the section on Backwards Incompatible Changes.

I think I found a bug! Who should I tell?

You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at » http://bugs.php.net/.

FAQ
Mailing lists
FAQ


Mailing lists

This section holds questions about how to get in touch with the PHP community. The best way is the mailing lists.

  1. Are there any PHP mailing lists?
  2. Are there any other communities?
  3. Can I start my own PHP mailing list?
  4. Help! I can't seem to subscribe to/unsubscribe from one of the mailing lists!
  5. Is there an archive of the mailing lists anywhere?
  6. What can I ask the mailing list?
  7. What information should I include when posting to the mailing list?
Are there any PHP mailing lists?

Of course! There are many mailing lists for several subjects. The most common community mailing lists can be found on our » mailing list page.

The most general mailing list is php-general. To subscribe, send a blank email message to » php-general-subscribe@lists.php.net. To unsubscribe, send a blank email to » php-general-unsubscribe@lists.php.net.

You can also subscribe and unsubscribe using the web interface on our » mailing list page, and unsubscribe instructions are included in the footer of every mailing list message.

Are there any other communities?

There are countless PHP-centric communities around the world, and we have links to some of these resources (and information on how to learn more) on our » Support page.

Can I start my own PHP mailing list?

Absolutely! In fact, we not only freely allow it, we encourage it! Helping others by sharing your knowledge and experience with PHP helps to foster the growth and development of the global PHP community and the language itself.

Help! I can't seem to subscribe to/unsubscribe from one of the mailing lists!

If you have problems subscribing to or unsubscribing from a mailing list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address is joeblow@example.com, and you are trying to subscribe to php-general, you can send your subscription request to php-general-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php-general-unsubscribe-joeblow=example.com@lists.php.net. Use similar addresses for the other mailing lists.

The most common reason folks have a hard time unsubscribing from our mailing lists is due to the use of mail forwarders. For example, if your email address is danbrown@example.com, but you subscribed to the mailing list with the forwarder php-lists@example.com and forward that to danbrown@example.com, attempting to unsubscribe danbrown@example.com will not work, as that address is not even known to our systems. Instead, you will need to unsubscribe the address to which the mail is being sent - in this example, php-lists@example.com.

Is there an archive of the mailing lists anywhere?

Yes, you will find links to some of the archive sites on the » mailing list page. You will also find dozens of sites that archive and/or syndicate our mailing list content by using your favorite Internet search engine and searching for "php mailing list archives".

All mailing list articles are also archived as news messages. You can access the news server at » news://news.php.net/ with a news client. There is also an experimental web interface for the news server at » http://news.php.net/

What can I ask the mailing list?

Since PHP is growing more and more popular by the day, the traffic on the php-general mailing list can be very heavy, ranging from 75 to 200 or more posts per day. Because of this, it is in everyone's interest that you use the list as a last resort, when you have exhausted all other avenues.

Before you post to the list please have a look in this FAQ and the manual to see if you can find the help there. If there is nothing to be found there try out the mailing list archives (see above). If you're having problem with installing or configuring PHP, please read through all included documentation and README's. If you still can't find any information that helps you out, you're more than welcome to use the appropriate mailing list.

To ensure that you receive the best responses (and to reduce the likelihood of frustrating your fellow developers), please be sure to post your question to the appropriate list. For example, if you are having difficulties installing PHP, you should send your question to the php-install mailing list. A caveat: some lists have similar names and completely different uses; a question regarding PHP scripts on Windows should be directed to the Windows PHP users list, not to the Windows Internals list.

Before asking questions, you may want to read the paper on » How To Ask Questions The Smart Way as this is a good idea for everyone.

What information should I include when posting to the mailing list?

Posts like "I can't get PHP up and running! Help me! What is wrong?" are of absolutely no use to anyone. If you're having problems getting PHP up and running you must include the operating system being used, the version of PHP you're trying to use, how you got it (pre-compiled, SVN, RPM, and so on), what you have done so far, and the exact error message or present result.

This goes for any other problem as well: you must include an explanation of what you have done, what you're trying to do, and any error messages encountered in the process. If you're having problems with your source code, you should include the part of the code that isn't working, indicating which line is the problem by an appropriately-placed code comment. Do not include more code than necessary though! It makes the post difficult to read, causing many to ignore your request. If you're unsure about how much information should be included, post what you believe is immediately relevant to your present issue, and be prepared to provide more information upon request.

Another important thing to remember is to summarize your problem on the subject line. A subject like "HELP MEEEE!!!" or "What is the problem here?" will be ignored by the majority of the readers.

And lastly, you're encouraged to read the paper on » How To Ask Questions The Smart Way as this will be a great help for everyone, especially yourself.

General Information
Obtaining PHP
FAQ


Obtaining PHP

This section has details about PHP download locations, and OS issues.

  1. Where can I obtain PHP?
  2. Are pre-compiled binary versions available?
  3. Where can I get libraries needed to compile some of the optional PHP extensions?
  4. How do I get these libraries to work?
  5. I got the latest version of the PHP source code from the SVN repository on my Windows machine, what do I need to compile it?
  6. Where do I find the Browser Capabilities File?
  7. What does thread safety mean when downloading PHP?
Where can I obtain PHP?

You can download PHP from any of the members of the PHP network of sites. These can be found at » http://www.php.net/. You can also use anonymous SVN to get the absolute latest version of the source. For more information, go to » http://php.net/svn.php.

Are pre-compiled binary versions available?

We only distribute precompiled binaries for Windows systems, as we are not able to compile PHP for every major Linux/Unix platform with every extension combination. Also note, that many Linux distributions come with PHP built in these days. Windows binaries can be downloaded from our » Downloads page, for Linux binaries, please visit your distribution's website.

Where can I get libraries needed to compile some of the optional PHP extensions?

Informacja: Those marked with * are not thread-safe libraries, and should not be used with PHP as a server module in the multi-threaded Windows web servers (IIS, Netscape). This does not matter in Unix environments, yet.

  • » LDAP (Unix).
  • » LDAP (Unix/Win) : Mozilla Directory (LDAP) SDK
  • » free LDAP server.
  • » Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
  • » SNMP* (Unix): .
  • » GD* (Unix/Win).
  • » mSQL* (Unix).
  • » PostgreSQL (Unix).
  • » IMAP* (Win/Unix).
  • » Sybase-CT* (Linux, libc5) : Available locally.
  • » FreeType (libttf):.
  • » ZLib (Unix/Win32).
  • » expat XML parser (Unix/Win32).
  • » PDFLib.
  • » mcrypt.
  • » mhash.
  • » t1lib.
  • » dmalloc.
  • » aspell.
  • » readline.

How do I get these libraries to work?

You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.

I got the latest version of the PHP source code from the SVN repository on my Windows machine, what do I need to compile it?

See the manual section about building PHP from source on Windows.

Where do I find the Browser Capabilities File?

You can find a browscap.ini file at » http://browsers.garykeith.com/downloads.asp.

What does thread safety mean when downloading PHP?

Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.

So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.

Mailing lists
Database issues
FAQ


Database issues

This section holds common questions about relation between PHP and databases. Yes, PHP can access virtually any database available today.

  1. I heard it's possible to access Microsoft SQL Server from PHP. How?
  2. Can I access Microsoft Access databases?
  3. PHP 5 no longer bundles MySQL client libraries, what does this mean to me? Can I still use MySQL with PHP? I try to use MySQL and get "function undefined" errors, what gives?
  4. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?
  5. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>"?
I heard it's possible to access Microsoft SQL Server from PHP. How?

On Windows machines, you can simply use the included ODBC support and the correct ODBC driver.

On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a » free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question.

Can I access Microsoft Access databases?

Yes. You already have all the tools you need if you are running entirely under Windows 9x/Me, or NT/2000, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.

If you are running PHP on a Unix box and want to talk to MS Access on a Windows box you will need Unix ODBC drivers. » OpenLink Software has Unix-based ODBC drivers that can do this.

Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat files or dBase databases. On this point Tim Hayes from OpenLink software writes:

Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other Unix platforms. Please visit our » website for a free download.

One option that has proved successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:

  • Install MySQL on your platform according to instructions with MySQL. Latest available from » http://www.mysql.com/ No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.
  • Download the MyODBC for Windows driver from the MySQL site. Install it on your Windows machine. You can test the operation with the utilities included with this program.
  • Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.
  • Install Access with a full install, this makes sure you get the proper add-ins... at the least you will need ODBC support and the linked table manager.
  • Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press OK, and presto! You can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.

Tips and Tricks:

  • You can construct your tables in Access and export them to MySQL, then link them back in. That makes table creation quick.
  • When creating tables in Access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access
  • If you change a table in MySQL, you have to re-link it in Access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing OK.

PHP 5 no longer bundles MySQL client libraries, what does this mean to me? Can I still use MySQL with PHP? I try to use MySQL and get "function undefined" errors, what gives?

Yes. There will always be MySQL support in PHP of one kind or another. The only change in PHP 5 is that we are no longer bundling the client library itself. Some reasons in no particular order:

  • Most systems these days already have the client library installed.

  • Given the above, having multiple versions of the library can get messy. For example, if you link mod_auth_mysql against one version and PHP against another, and then enable both in Apache, you get a nice fat crash. Also, the bundled library didn't always play well with the installed server version. The most obvious symptom of this being disagreement over where to find the mysql.socket Unix domain socket file.

  • Maintenance was somewhat lax and it was falling further and further behind the released version.

  • Future versions of the library are under the GPL and thus we don't have an upgrade path since we cannot bundle a GPL'ed library in a BSD/Apache-style licensed project. A clean break in PHP 5 seemed like the best option.

This won't actually affect that many people. Unix users, at least the ones who know what they are doing, tend to always build PHP against their system's libmysqlclient library simply by adding the --with-mysql=/usr option when building PHP. Windows users may enable the extension php_mysql.dll inside php.ini. For more details, see the MySQL Reference for installation instructions. Also, be sure libmysql.dll is available to the systems PATH. For more details on how, read the FAQ on setting up the Windows systems PATH. Because libmysql.dll (and many other PHP related files) exist in the PHP folder, you'll want to add the PHP folder to your systems PATH.

After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?

If your MySQL libs are linked against pthreads this will happen. Check using ldd. If they are, grab the MySQL tarball and compile from source, or recompile from the source rpm and remove the switch in the spec file that turns on the threaded client code. Either of these suggestions will fix this. Then recompile PHP with the new MySQL libs.

Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>"?

You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:

<?php

$result = mysql_query("SELECT * FROM tables_priv");
if (!$result) {
    echo mysql_error();
    exit;
}
?>
or
<?php

$result = mysql_query("SELECT * FROM tables_priv")
    or die("Bad query: " . mysql_error());
?>

Obtaining PHP
Installation
FAQ


Installation

This section holds common questions about the way to install PHP. PHP is available for almost any OS (except maybe for MacOS before OSX), and almost any web server.

To install PHP, follow the instructions in Instalacja i konfiguracja.

  1. Why shouldn't I use Apache2 with a threaded MPM in a production environment?
  2. Unix/Windows: Where should my php.ini file be located?
  3. Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
  4. Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
  5. Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?
  6. Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.
  7. Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.
  8. Some operating systems: I have installed PHP without errors, but when I try to start Apache I get undefined symbol errors: [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get the error: cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows: I've followed all the instructions, but still can't get PHP and IIS to work together!
  11. When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..
  12. How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.
  13. How do I add my PHP directory to the PATH on Windows?
  14. How do I make the php.ini file available to PHP on windows?
  15. Is it possible to use Apache content negotiation (MultiViews option) with PHP?
  16. Is PHP limited to process GET and POST request methods only?
Why shouldn't I use Apache2 with a threaded MPM in a production environment?

PHP is glue. It is the glue used to build cool web applications by sticking dozens of 3rd-party libraries together and making it all appear as one coherent entity through an intuitive and easy to learn language interface. The flexibility and power of PHP relies on the stability and robustness of the underlying platform. It needs a working OS, a working web server and working 3rd-party libraries to glue together. When any of these stop working PHP needs ways to identify the problems and fix them quickly. When you make the underlying framework more complex by not having completely separate execution threads, completely separate memory segments and a strong sandbox for each request to play in, further weaknesses are introduced into PHP's system.

If you want to use a threaded MPM, look at a FastCGI configuration where PHP is running in its own memory space.

Unix/Windows: Where should my php.ini file be located?

By default on Unix it should be in /usr/local/lib which is <install-path>/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it with something like:

--with-config-file-path=/etc
And then you would copy php.ini-development from the distribution to /etc/php.ini and edit it to make any local changes you want.

--with-config-file-scan-dir=PATH

On Windows the default path for the php.ini file is the Windows directory. If you're using the Apache webserver, php.ini is first searched in the Apaches install directory, e.g. c:\program files\apache group\apache. This way you can have different php.ini files for different versions of Apache on the same machine.

See also the chapter about the configuration file.

Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?

This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:

  • Stop your httpd processes

  • gdb httpd

  • Stop your httpd processes

  • > run -X -f /path/to/httpd.conf

  • Then fetch the URL causing the problem with your browser

  • > run -X -f /path/to/httpd.conf

  • If you are getting a core dump, gdb should inform you of this now

  • type: bt

  • You should include your backtrace in your bug report. This should be submitted to » http://bugs.php.net/

If your script uses the regular expression functions (preg_match() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. This should happen automatically with PHP and Apache 1.3.x

Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?

Assuming you installed both Apache and PHP from RPM packages, you need to uncomment or add some or all of the following lines in your httpd.conf file:

# Extra Modules
AddModule mod_php.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so
And add:
AddType application/x-httpd-php .php
... to the global properties, or to the properties of the VirtualDomain you want to have PHP support added to.

Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?

No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.

Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.

Do a 'view source' in the web browser and you will probably find that you can see the source code of your PHP script. This means that the web server did not send the script to PHP for interpretation. Something is wrong with the server configuration - double check the server configuration against the PHP installation instructions.

Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.

Something went wrong when the server tried to run PHP. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of HTML codes (the output of the phpinfo() function) then PHP is working, and your problem may be related to your server configuration which you should double check.

Some operating systems: I have installed PHP without errors, but when I try to start Apache I get undefined symbol errors:
[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

This has actually nothing to do with PHP, but with the MySQL client libraries. Some need --with-zlib , others do not. This is also covered in the MySQL FAQ.

Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get the error:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

This error message means that PHP failed to output anything at all. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of HTML codes (the output of the phpinfo() function) then PHP is working.

Once PHP is working at the command line, try accessing the script via the browser again. If it still fails then it could be one of the following:

  • File permissions on your PHP script, php.exe, php5ts.dll, php.ini or any PHP extensions you are trying to load are such that the anonymous internet user ISUR_<machinename> cannot access them.
  • The script file does not exist (or possibly isn't where you think it is relative to your web root directory). Note that for IIS you can trap this error by ticking the 'check file exists' box when setting up the script mappings in the Internet Services Manager. If a script file does not exist then the server will return a 404 error instead. There is also the additional benefit that IIS will do any authentication required for you based on the NTLanMan permissions on your script file.
Windows: I've followed all the instructions, but still can't get PHP and IIS to work together!

Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine. Also, you will want to read this faq.

When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..

You must set the cgi.force_redirect directive to 0. It defaults to 1 so be sure the directive isn't commented out (with a ;). Like all directives, this is set in php.ini

Because the default is 1, it's critical that you're 100% sure that the correct php.ini file is being read. Read this faq for details.

How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.

To be sure your php.ini is being read by PHP, make a call to phpinfo(). Near the top, there will be a listing called Configuration File (php.ini). This will tell you where PHP is looking for php.ini and whether or not it's being read. If just a directory PATH exists, then it's not being read, and you should put your php.ini in that directory. If php.ini is included within the PATH, it is being read.

If php.ini is being read and you're running PHP as a module, then be sure to restart your web server after making changes to php.ini

See also php_ini_loaded_file().

How do I add my PHP directory to the PATH on Windows?

On Windows NT+ and Windows Server 2000+:

  • Go to Control Panel and open the System icon (Start -> Settings -> Control Panel -> System, or just Start -> Control Panel -> System for Windows XP/2003+)

  • Go to the Advanced tab

  • Click on the 'Environment Variables' button

  • Look into the 'System Variables' pane

  • Find the Path entry (you may need to scroll to find it)

  • Double click on the Path entry

  • Enter your PHP directory at the end, including ';' before (e.g. ;C:\php)

  • Press OK

On Windows 98/Me you need to edit the autoexec.bat file:

  • Open the Notepad (Start -> Run and enter notepad)

  • Open the C:\autoexec.bat file

  • Locate the line with PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;..... and add: ;C:\php to the end of the line

  • Save the file and restart your computer

Informacja: Be sure to reboot after following the steps above to ensure that the PATH changes are applied.

The PHP manual used to promote the copying of files into the Windows system directory, this is because this directory (C:\Windows, C:\WINNT, etc.) is by default in the systems PATH. Copying files into the Windows system directory has long since been deprecated and may cause problems.

How do I make the php.ini file available to PHP on windows?

There are several ways of doing this. If you are using Apache, read their installation specific instructions (Apache 1, Apache 2), otherwise you must set the PHPRC environment variable:

On Windows NT, 2000, XP and 2003:

  • Go to Control Panel and open the System icon (Start -> Settings -> Control Panel -> System, or just Start -> Control Panel -> System for Windows XP/2003)

  • Go to the Advanced tab

  • Click on the 'Environment Variables' button

  • Look into the 'System variables' pane

  • Click on 'New' and enter 'PHPRC' as the variable name and the directory where php.ini is located as the variable value (e.g. C:\php)

  • Press OK and restart your computer

On Windows 98/Me you need to edit the autoexec.bat file:

  • Open the Notepad (Start -> Run and enter notepad)

  • Open the C:\autoexec.bat file

  • Add a new line to the end of the file: set PHPRC=C:\php (replace C:\php with the directory where php.ini is located). Please note that the path cannot contain spaces. For instance, if you have installed PHP in C:\Program Files\PHP, you would enter C:\PROGRA~1\PHP instead.

  • Save the file and restart your computer

Is it possible to use Apache content negotiation (MultiViews option) with PHP?

If links to PHP files include extension, everything works perfect. This FAQ is only for the case when links to PHP files don't include extension and you want to use content negotiation to choose PHP files from URL with no extension. In this case, replace the line AddType application/x-httpd-php .php with:

AddHandler php5-script php
AddType text/html php
This solution doesn't work for Apache 1 as PHP module doesn't catch php-script.

Is PHP limited to process GET and POST request methods only?

No, it is possible to handle any request method, e.g. CONNECT. Proper response status can be sent with header(). If only GET and POST methods should be handled, it can be achieved with this Apache configuration:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

Database issues
Build Problems
FAQ


Build Problems

This section gathers most common errors that occur at build time.

  1. I got the latest version of PHP using the anonymous SVN service, but there's no configure script!
  2. I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!
  3. While configuring PHP (./configure), you come across an error similar to the following: checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. When I try to start Apache, I get the following message: fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
  6. When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.
  7. When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
  8. When linking PHP, it complains about a number of undefined references.
  9. I can't figure out how to build PHP with Apache 1.3.
  10. I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.
  11. It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?
  12. When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.
  13. When I try to build PHP using --with-apxs I get strange error messages.
  14. During make, I get errors in microtime, and a lot of RUSAGE_ stuff.
  15. When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', what's wrong?
  16. I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?
  17. When building PHP with the GD library it either gives strange compile errors or segfaults on execution.
  18. When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.
I got the latest version of PHP using the anonymous SVN service, but there's no configure script!

You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run ./buildconf in the top-level directory after getting the sources from the SVN server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.)

I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!

You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify --with-apache=/path/to/apache and not --with-apache=/path/to/apache/src .

While configuring PHP (./configure), you come across an error similar to the following:

checking lex output file root... ./configure: lex: command not found
configure: error: cannot find output from lex; giving up

Be sure to read the installation instructions carefully and note that you need both flex and bison installed to compile PHP. Depending on your setup you will install bison and flex from either source or a package, such as a RPM.

When I try to start Apache, I get the following message:

fatal: relocation error: file /path/to/libphp4.so:
symbol ap_block_alarms: referenced symbol not found

This error usually comes up when one compiles the Apache core program as a DSO library for shared usage. Try to reconfigure apache, making sure to use at least the following flags:

--enable-shared=max --enable-rule=SHARED_CORE

For more information, read the top-level Apache INSTALL file or the Apache » DSO manual page.

When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!

You can make the configure script look for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
If you're using a csh-variant for your login shell (why?), it would be:
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.

You need to update your version of Bison. You can find the latest version at » http://www.gnu.org/software/bison/bison.html.

When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.

Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running cp *.o functions and then re-running make to see if that helps. If it does, you should really upgrade to a recent version of GNU make.

When linking PHP, it complains about a number of undefined references.

Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.

Some people have also reported that they had to add '-ldl' immediately following libphp4.a when linking with Apache.

I can't figure out how to build PHP with Apache 1.3.

This is actually quite easy. Follow these steps carefully:

  • Grab the latest Apache 1.3 distribution from » http://httpd.apache.org/download.cgi.
  • Ungzip and untar it somewhere, for example /usr/local/src/apache-1.3.
  • Compile PHP by first running ./configure --with-apache=/<path>/apache-1.3 (substitute <path> for the actual path to your apache-1.3 directory).
  • Type make followed by make install to build PHP and copy the necessary files to the Apache distribution tree.
  • Change directories into to your /<path>/apache-1.3/src directory and edit the Configuration file. Add to the file: AddModule modules/php4/libphp4.a.
  • Type: ./configure followed by make.
  • You should now have a PHP-enabled httpd binary!

Note: You can also use the new Apache ./configure script. See the instructions in the README.configure file which is part of your Apache distribution. Also have a look at the INSTALL file in the PHP distribution.

I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.

This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:

  • Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l If you don't see mod_php4.c listed then you are not running the right binary. Find and install the correct binary.
  • Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php .php Also make sure that this AddType line is not hidden away inside a <Virtualhost> or <Directory> block which would prevent it from applying to the location of your test script.
  • Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read correctly.

It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?

Note that the libphp4.a file is not supposed to exist. The apache process will create it!

When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.

This is a misleading error message from Apache that has been fixed in more recent versions.

When I try to build PHP using --with-apxs I get strange error messages.

There are three things to check here. First, for some reason when Apache builds the apxs Perl script, it sometimes ends up getting built without the proper compiler and flags variables. Find your apxs script (try the command which apxs), it's sometimes found in /usr/local/apache/bin/apxs or /usr/sbin/apxs. Open it and check for lines similar to these:

my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
If this is what you see, you have found your problem. They may contain just spaces or other incorrect values, such as 'q()'. Change these lines to say:
my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = 'gcc';                   # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = q(-shared);              # substituted via Makefile.tmpl
The second possible problem should only be an issue on Red Hat 6.1 and 6.2. The apxs script Red Hat ships is broken. Look for this line:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
If you see the above line, change it to this:
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Last, if you reconfigure/reinstall Apache, add a make clean to the process after ./configure and before make.

During make, I get errors in microtime, and a lot of RUSAGE_ stuff.

During the make portion of installation, if you encounter problems that look similar to this:

microtime.c: In function `php_if_getrusage':
microtime.c:94: storage size of `usg' isn't known
microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function)
microtime.c:97: (Each undeclared identifier is reported only once
microtime.c:97: for each function it appears in.)
microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function)
make[3]: *** [microtime.lo] Error 1
make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/master/php-4.0.1/ext'
make: *** [all-recursive] Error 1

Your system is broken. You need to fix your /usr/include files by installing a glibc-devel package that matches your glibc. This has absolutely nothing to do with PHP. To prove this to yourself, try this simple test:

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
If that spews out errors, you know your include files are messed up.

When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', what's wrong?

First, it's important to realize that this is a Warning and not a fatal error. Because this is often the last output seen during make, it may seem like a fatal error but it's not. Of course, if you set your compiler to die on Warnings, it will. Also keep in mind that MySQL support is enabled by default.

Informacja:

As of PHP 4.3.2, you'll also see the following text after the build (make) completes:

Build complete.
(It is safe to ignore warnings about tempnam and tmpnam).

I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?

Either you look at config.nice file, in the source tree of your current PHP installation or, if this is not available, you simply run a

<?php phpinfo(); ?>
script. On top of the output the ./configure line, that was used to build this PHP installation is shown.

When building PHP with the GD library it either gives strange compile errors or segfaults on execution.

Make sure your GD library and PHP are linked against the same depending libraries (e.g. libpng).

When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.

Using non-GNU utilities while compiling PHP may cause problems. Be sure to use GNU tools in order to be certain that compiling PHP will work. For example, on Solaris, using either the SunOS BSD-compatible or Solaris versions of sed will not work, but using the GNU or Sun POSIX (xpg4) versions of sed will work. Links: » GNU sed, » GNU flex, and » GNU bison.

Installation
Using PHP
FAQ


Using PHP

This section gathers many common errors that you may face while writing PHP scripts.

  1. I cannot remember the parameter order of PHP functions, are they random?
  2. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
  3. I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.
  4. All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?
  5. How does the PHP directive register_globals affect me?
  6. When I do the following, the output is printed in the wrong order: <?php function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); ?> what's going on?
  7. Hey, what happened to my newlines? <pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre>
  8. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.
  9. I need to access information in the request header directly. How can I do this?
  10. When I try to use authentication with IIS I get 'No Input file specified'.
  11. Windows: I can't access files shared on another computer using IIS
  12. How am I supposed to mix XML and PHP? It complains about my <?xml tags!
  13. Where can I find a complete list of variables are available to me in PHP?
  14. How can I generate PDF files without using the non-free and commercial libraries like PDFLib? I'd like something that's free and doesn't require external PDF libraries.
  15. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
  16. A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options? And can I use these outside of php.ini?
  17. Windows: I keep getting connection timeouts when using localhost, whereas "127.0.0.1" works?
I cannot remember the parameter order of PHP functions, are they random?

PHP is a glue that brings together hundreds of external libraries, so sometimes this gets messy. However, a simple rule of thumb is as follows:

Array function parameters are ordered as "needle, haystack" whereas String functions are the opposite, so "haystack, needle".

I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?

PHP offers many predefined variables, like the superglobal $_POST. You may loop through $_POST as it's an associate array of all POSTed values. For example, let's simply loop through it with foreach, check for empty() values, and print them out.

<?php
$empty = $post = array();
foreach ($_POST as $varname => $varvalue) {
    if (empty($varvalue)) {
        $empty[$varname] = $varvalue;
    } else {
        $post[$varname] = $varvalue;
    }
}

print "<pre>";
if (empty($empty)) {
    print "None of the POSTed values are empty, posted:\n";
    var_dump($post);
} else {
    print "We have " . count($empty) . " empty values\n";
    print "Posted:\n"; var_dump($post);
    print "Empty:\n";  var_dump($empty);
    exit;
}
?>

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

I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.

Assuming this is for a database, use the escaping mechanism that comes with the database. For example, use mysql_real_escape_string() with MySQL and pg_escape_string() with PostgreSQL. There is also the generic addslashes() and stripslashes() functions, that are more common with older PHP code.

Informacja: uwaga na temat dyrektywy: magic_quotes_gpc

Domyślną wartością dyrektywy konfiguracji PHP magic_quotes_gpc jest on. Powoduje ona wykonywanie funkcji addslashes() na wszystkich danych GET, POST i COOKIE. Można użyć funkcji stripslashes() aby usunąć dodane znaki slash.

All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?

Most likely the backslashes magically exist because the PHP directive magic_quotes_gpc is on. This is an old feature of PHP, and should be disabled and not relied upon. Also, the PHP function stripslashes() may be used to strip the backslashes from the string.

Informacja: uwaga na temat dyrektywy: magic_quotes_gpc

Domyślną wartością dyrektywy konfiguracji PHP magic_quotes_gpc jest on. Powoduje ona wykonywanie funkcji addslashes() na wszystkich danych GET, POST i COOKIE. Można użyć funkcji stripslashes() aby usunąć dodane znaki slash.

How does the PHP directive register_globals affect me?

First, an explanation about what this ini setting does. Let's say the following URL is used: http://example.com/foo.php?animal=cat and in foo.php we might have the following PHP code:

<?php
// Using $_GET here is preferred
echo $_GET['animal'];

// For $animal to exist, register_globals must be on
// DO NOT DO THIS
echo $animal;

// This applies to all variables, so $_SERVER too
echo $_SERVER['PHP_SELF'];

// Again, for $PHP_SELF to exist, register_globals must be on
// DO NOT DO THIS
echo $PHP_SELF;
?>

The code above demonstrates how register_globals creates a lot of variables. For years this type of coding has been frowned upon, and for years it's been disabled by default. Note that PHP will eventually remove this deprecated feature. So although most web hosts disable register_globals, there are still outdated articles, tutorials, and books that require it to be on. Plan accordingly.

See also the following resources for additional information:

  • The register_globals directive
  • The security chapter about register globals
  • Handling external variables
  • Use superglobals instead

Informacja:

In the example above, we used an URL that contained a QUERY_STRING. Passing information like this is done through a GET HTTP Request, so this is why the superglobal $_GET was used.

When I do the following, the output is printed in the wrong order:
<?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
what's going on?

To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return() the value, not echo() it.

Hey, what happened to my newlines?
<pre>
<?php echo "This should be the first line."; ?>
<?php echo "This should show up after the new line above."; ?>
</pre>

In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). So in the example above, the echoed sentences will be on one line, because PHP omits the newlines after the block ending. This means that you need to insert an extra newline after each block of PHP code to make it print out one newline.

Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.

I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.

The functions header(), setcookie(), and the session functions need to add headers to the output stream but headers can only be sent before all other content. There can be no output before using these functions, output such as HTML. The function headers_sent() will check if your script has already sent headers and see also the Output Control functions.

I need to access information in the request header directly. How can I do this?

The getallheaders() function will do this if you are running PHP as an Apache module. So, the following bit of code will show you all the request headers:

<?php
$headers = getallheaders();
foreach ($headers as $name => $content) {
    echo "headers[$name] = $content<br />\n";
}
?>

See also
apache_lookup_uri(),
apache_response_headers(), and
fsockopen()

When I try to use authentication with IIS I get 'No Input file specified'.

The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. With the ISAPI module, this is not a problem. This should not effect other NT web servers. For more information, see: » http://support.microsoft.com/kb/q160422/ and the manual section on HTTP Authentication .

Windows: I can't access files shared on another computer using IIS

You have to change the Go to Internet Information Services. Locate your PHP file and go to its properties. Go to the File Security tab, Edit -< Anonymous access and authentication control.

You can fix the problem either by unticking Anonymous Access and leaving Integrated Window Authentication ticked, or, by ticking Anonymous Access and editing the user as he may not have the access right.

How am I supposed to mix XML and PHP? It complains about my <?xml tags!

In order to embed <?xml straight into your PHP code, you'll have to turn off short tags by having the PHP directive short_open_tags set to 0. You cannot set this directive with ini_set(). Regardless of short_open_tags being on or off, you can do something like: <?php echo '<?xml'; ?>. The default for this directive is On.

Where can I find a complete list of variables are available to me in PHP?

Read the manual page on predefined variables as it includes a partial list of predefined variables available to your script. A complete list of available variables (and much more information) can be seen by calling the phpinfo() function. Be sure to read the manual section on variables from outside of PHP as it describes common scenarios for external variables, like from a HTML form, a Cookie, and the URL.

Informacja: register_globals: ważna uwaga

Od PHP 4.2.0 domyślną wartością dyrektywy register_globals jest off. Społeczność PHP zaleca programistom, aby nie stosowali tej dyrektywy, i zamiast niej używali innych sposobów, takich jak superglobals.

How can I generate PDF files without using the non-free and commercial libraries like PDFLib? I'd like something that's free and doesn't require external PDF libraries.

There are a few alternatives written in PHP such as » FPDF and » TCPDF.

There is also the Haru extension that uses the free libHaru external library.

I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?

It's important to realize that the PHP directive register_globals also affects server and environment variables. When register_globals = off (the default is off since PHP 4.2.0), $DOCUMENT_ROOT will not exist. Instead, use $_SERVER['DOCUMENT_ROOT'] . If register_globals = on then the variables $DOCUMENT_ROOT and $GLOBALS['DOCUMENT_ROOT'] will also exist.

If you're sure register_globals = on and wonder why $DOCUMENT_ROOT isn't available inside functions, it's because these are like any other variables and would require global $DOCUMENT_ROOT inside the function. See also the manual page on variable scope. It's preferred to code with register_globals = off.

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

A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options? And can I use these outside of php.ini?

The available options are K (for Kilobytes), M (for Megabytes) and G (for Gigabytes; available since PHP 5.1.0), these are case insensitive. Anything else assumes bytes. 1M equals one Megabyte or 1048576 bytes. 1K equals one Kilobyte or 1024 bytes. You may not use these shorthand notations outside of php.ini, instead use an integer value of bytes. See the ini_get() documentation for an example on how to convert these values.

Informacja: kilobyte versus kibibyte

The PHP notation describes one kilobyte as equalling 1024 bytes, whereas the IEC standard considers this to be a kibibyte instead. Summary: k and K = 1024 bytes.

Windows: I keep getting connection timeouts when using localhost, whereas "127.0.0.1" works?

Prior to PHP 5.3.4, there was a bug in the network resolving code inside PHP that caused localhost in all stream related situations to fail if IPv6 was enabled. To work around this issue you can either use "127.0.0.1" or disable IPv6 resolving in the hosts file.

Build Problems
Password Hashing
FAQ


Safe Password Hashing

This section explains the reasons behind using hashing functions to secure passwords, as well as how to do so effectively.

  1. Why should I hash passwords supplied by users of my application?
  2. Why are common hashing functions such as md5 and sha1 unsuitable for passwords?
  3. How should I hash my passwords, if the common hash functions are not suitable?
  4. What is a salt?
Why should I hash passwords supplied by users of my application?

Password hashing is one of the most basic security considerations that must be made when designing any application that accepts passwords from users. Without hashing, any passwords that are stored in your application's database can be stolen if the database is compromised, and then immediately used to compromise not only your application, but also the accounts of your users on other services, if they do not use unique passwords.

By applying a hashing algorithm to your user's passwords before storing them in your database, you make it implausible for any attacker to determine the original password, while still being able to compare the resulting hash to the original password in the future.

It is important to note, however, that hashing passwords only protects them from being compromised in your data store, but does not necessarily protect them from being intercepted by malicious code injected into your application itself.

Why are common hashing functions such as md5() and sha1() unsuitable for passwords?

Hashing algorithms such as MD5, SHA1 and SHA256 are designed to be very fast and efficient. With modern techniques and computer equipment, it has become trivial to "brute force" the output of these algorithms, in order to determine the original input.

Because of how quickly a modern computer can "reverse" these hashing algorithms, many security professionals strongly suggest against their use for password hashing.

How should I hash my passwords, if the common hash functions are not suitable?

When hashing passwords, the two most important considerations are the computational expense, and the salt. The more computationally expensive the hashing algorithm, the longer it will take to brute force its output.

There are two functions that are bundled with PHP that can perform hashing using a specified algorithm.

The first hashing function is crypt(), which natively supports several hashing algorithms. When using this function, you are guaranteed that the algorithm you select is available, as PHP contains native implementations of each supported algorithm, in case one or more are not supported by your system.

The second hashing function is hash(), which supports many more algorithms and variants than crypt(), but does not support some algorithms that crypt() does. The Hash extension is bundled with PHP, but can be disabled during compile-time, so it is not guaranteed to be available, while crypt() is, being in the PHP core.

The suggested algorithm to use when hashing passwords is Blowfish, as it is significantly more computationally expensive than MD5 or SHA1, while still being scalable.

What is a salt?

A cryptographic salt is data which is applied during the hashing process in order to eliminate the possibility of the output being looked up in a list of pre-calculated pairs of hashes and their input, known as a rainbow table.

In more simple terms, a salt is a bit of additional data which makes your hashes significantly more difficult to crack. There are a number of services online which provide extensive lists of pre-computed hashes, as well as the original input for those hashes. The use of a salt makes it implausible or impossible to find the resulting hash in one of these lists.

Using PHP
PHP and HTML
FAQ


PHP and HTML

PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it's important you learn how to retrieve variables from external sources. The manual page on this topic includes many examples as well. Pay close attention to what register_globals means to you too.

  1. What encoding/decoding do I need when I pass a value through a form/URL?
  2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
  3. How do I create arrays in a HTML <form>?
  4. How do I get all the results from a select multiple HTML tag?
  5. How can I pass a variable from Javascript to PHP?
What encoding/decoding do I need when I pass a value through a form/URL?

There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages:

  • HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.

  • URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode().

Przykład #1 A hidden HTML form element

<?php
    echo "<input type='hidden' value='" . htmlspecialchars($data) . "' />\n";
?>

Informacja: It is wrong to urlencode() $data, because it's the browsers responsibility to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You'll only notice this in case of GET request though, because POST requests are usually hidden.

Przykład #2 Data to be edited by the user

<?php
    echo "<textarea name='mydata'>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>

Informacja: The data is shown in the browser as intended, because the browser will interpret the HTML escaped symbols. Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don't need to do any urlencoding/urldecoding yourself, everything is handled automagically.

Przykład #3 In a URL

<?php
    echo "<a href='" . htmlspecialchars("/nextpage.php?stage=23&data=" .
        urlencode($data)) . "'>\n";
?>

Informacja: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.

Informacja: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un-htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correctly, because you urlencode()d the data. You'll notice that the & in the URL is replaced by &amp;. Although most browsers will recover if you forget this, this isn't always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.

I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

<input type="image" src="image.gif" name="foo" />
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.

Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y. That is, the periods are replaced with underscores. So, you'd access these variables like any other described within the section on retrieving variables from external sources. For example, $_GET['foo_x'].

Informacja:

Spaces in request variable names are converted to underscores.

How do I create arrays in a HTML <form>?

To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:

<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It's also possible to assign specific keys to your arrays:
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
The AnotherArray array will now contain the keys 0, 1, email and phone.

Informacja:

Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.

See also Array Functions and Variables From External Sources.

How do I get all the results from a select multiple HTML tag?

The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.

<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's "array from form element" feature. The following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:

variable = documents.forms[0].elements['var[]'];

How can I pass a variable from Javascript to PHP?

Since Javascript is (usually) a client-side technology, and PHP is (usually) a server-side technology, and since HTTP is a "stateless" protocol, the two languages cannot directly share variables.

It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this -- it allows PHP code to capture screen height and width, something that is normally only possible on the client side.

Przykład #4 Generating Javascript with PHP

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo "Screen width is: ". $_GET['width'] ."<br />\n";
  echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   -- post variables will need to handled differently)

  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
  echo "</script>\n";
  exit();
}
?>

Password Hashing
PHP and COM
FAQ


PHP and COM

PHP can be used to access COM and DCOM objects on Win32 platforms.

  1. I have built a DLL to calculate something. Is there any way to run this DLL under PHP ?
  2. What does 'Unsupported variant type: xxxx (0xxxxx)' mean ?
  3. Is it possible manipulate visual objects in PHP ?
  4. Can I store a COM object in a session ?
  5. How can I trap COM errors ?
  6. Can I generate DLL files from PHP scripts like I can in Perl ?
  7. What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?
  8. How can I run COM object from remote server ?
  9. I get 'DCOM is disabled in C:\path...\scriptname.php on line 6', what can I do ?
  10. Is it possible to load/manipulate an ActiveX object in a page with PHP ?
  11. Is it possible to get a running instance of a component ?
  12. Is there a way to handle an event sent from COM object ?
  13. I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?
  14. So PHP works with COM, how about COM+ ?
  15. If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?
I have built a DLL to calculate something. Is there any way to run this DLL under PHP ?

If this is a simple DLL there is no way yet to run it from PHP. If the DLL contains a COM server you may be able to access it if it implements the IDispatch interface.

What does 'Unsupported variant type: xxxx (0xxxxx)' mean ?

There are dozens of VARIANT types and combinations of them. Most of them are already supported but a few still have to be implemented. Arrays are not completely supported. Only single dimensional indexed only arrays can be passed between PHP and COM. If you find other types that aren't supported, please report them as a bug (if not already reported) and provide as much information as available.

Is it possible manipulate visual objects in PHP ?

Generally it is, but as PHP is mostly used as a web scripting language it runs in the web servers context, thus visual objects will never appear on the servers desktop. If you use PHP for application scripting e.g. in conjunction with PHP-GTK there is no limitation in accessing and manipulating visual objects through COM.

Can I store a COM object in a session ?

No, you can't. COM instances are treated as resources and therefore they are only available in a single script's context.

How can I trap COM errors ?

In PHP 5, the COM extension throws com_exception exceptions, which you can catch and then inspect the code member to determine what to do next.

In PHP 4 it's not possible to trap COM errors beside the ways provided by PHP itself (@, track_errors, ..).

Can I generate DLL files from PHP scripts like I can in Perl ?

No, unfortunately there is no such tool available for PHP.

What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?

This error can have multiple reasons:

  • the CLSID is wrong
  • the requested DLL is missing
  • the requested component doesn't implement the IDispatch interface

How can I run COM object from remote server ?

Exactly like you run local objects. You only have to pass the IP of the remote machine as second parameter to the COM constructor.

Make sure that you have set com.allow_dcom =TRUE in your php.ini.

I get 'DCOM is disabled in C:\path...\scriptname.php on line 6', what can I do ?

Edit your php.ini and set com.allow_dcom =TRUE.

Is it possible to load/manipulate an ActiveX object in a page with PHP ?

This has nothing to do with PHP. ActiveX objects are loaded on client side if they are requested by the HTML document. There is no relation to the PHP script and therefore there is no direct server side interaction possible.

Is it possible to get a running instance of a component ?

This is possible with the help of monikers. If you want to get multiple references to the same word instance you can create that instance like shown:

<?php
$word = new COM("C:\docs\word.doc");
?>

This will create a new instance if there is no running instance available or it will return a handle to the running instance, if available.

Is there a way to handle an event sent from COM object ?

You can define an event sink and bind it using com_event_sink(). You can use com_print_typeinfo() to have PHP generate a skeleton for the event sink class.

I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?

The answer is as simple as unsatisfying. I don't know exactly but i think you can do nothing. If someone has specific information about this, please let » me know :)

So PHP works with COM, how about COM+ ?

COM+ extends COM by a framework for managing components through MTS and MSMQ but there is nothing special that PHP has to support to use such components.

If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?

PHP itself doesn't handle transactions yet. Thus if an error occurs no rollback is initiated. If you use components that support transactions you will have to implement the transaction management yourself.

PHP and HTML
PHP i inne języki
FAQ


PHP i inne języki

PHP jest najlepszym językiem do zastosowań sieciowych, ale co z innymi językami?

  1. PHP vs. ASP?
  2. Czy można skonwertować ASP na PHP?
  3. PHP vs. Cold Fusion?
  4. PHP vs. Perl?
PHP vs. ASP?

ASP nie jest tak naprawdę językiem programowania, ale skrótem od Active Server Pages. W rzeczywistości ASP programuje się przy użyciu języków Visual Basic oraz JScript. Największą wadą ASP jest fakt, że działa on wyłącznie na serwerach Internet Information Server(IIS) firmy Microsoft. Ogranicza to możliwość zastosowania ASP wyłącznie do serwerów bazujących na systemie Win32. Istnieje kilka projektów, których celem jest umożliwienie uruchamiania ASP w innych środowiskach i na innych serwerach: » InstantASP firmy » Halcyon (komercyjny), Chili!Soft ASP firmy » Chili!Soft (komercyjny). Przez wielu ASP określany jest jako wolniejszy, mniej wygodny oraz nie tak stabilny jak PHP. Do zalet ASP można zaliczyć fakt, że używa on języka VBScript, którego osoba umiejąca już programować w Visual Basic jest w stanie bardzo szybko się nauczyć. Serwery IIS mają domyślnie włączoną obsługę ASP co znacznie ułatwia jego instalację oraz użtkowanie. Ilość komponentów napisanych w ASP jest bardzo ograniczona, co oznacza, że jeśli będziesz chciał używać "zaawansowanych" funkcji takich jak np. współpraca z serwerami FTP będziesz musiał dokupić dodatkowe komponenty.

Czy można skonwertować ASP na PHP?

Tak. Do najczęściej wymienianych narzędzi tego typu należą działający po stronie serwera » asp2php oraz » to rozwiązanie działające po stronie klienta.

PHP vs. Cold Fusion?

Przez wielu ludzi PHP jest uważany za znacznie szybszy i wydajniejszy. Bardzo dobrze nadaje się do tworzenia złożonych projektów oraz do wypróbowywania nowych pomysłów. Do jego zalet można zaliczyć również większa stabilność oraz mniejsze zużycie zasobów. Mocną stroną Cold Fusion jest lepsza obsługa błędów, abstrakcja baz danych oraz parsowanie daty. Jeśli chodzi o abstrakcję baz danych poświęcono jej więcej uwagi w PHP 4. Zaletą Cold Fusion jest bardzo dobry silnik wyszukiwarki. Nie jest to jednak ważna różnica, bo niewiele osób oczekuje implementacji takiej funkcji w języku skryptowym. PHP jest obsługuiwany przez praktycznie wszystkie platformy, podczas gdy Cold Fusion działa wyłącznie na systemach Win32, Solaris, Linux oraz HP/UX. Cold Fusion ma bardzo dobre zintegrowane środowisko programowania (IDE) co umożliwia programowanie przy jego użyciu nawet początkującym użytkownikom. Z kolei PHP już od samego początku wymaga od użytkownika pewnej wiedzy o programowaniu i nie został stworzony z myślą o ludziach stawiających dopiero pierwsze kroki na tym polu.

Michael J Sheldon wysłał bardzo ciekawy artykuł na ten temat na listę dyskusyjną PHP. Jego kopię znajdziesz tutaj » http://marc.theaimsgroup.com/?l=php-general&m=95602167412542&w=1.

PHP vs. Perl?

Największą przewagą PHP nad językiem Perl jest fakt, że PHP został stworzony wyłącznie z myślą o zastosowaniach sieciowych. Natomiast Perl ma dużo więcej zastosowań i właśnie ta ogromna ilość funkcji może niektórym sprawiać trudności. Z jednej strony elastyczność / kompleksowość Perla ułatwia pisanie w nim kodu, z drugiej jednak strony inny autor / programista może mieć problemy z jego odczytaniem. PHP jest równie elastyczny, a rygorystyczna składnia czyni kod bardziej przejrzystym. PHP łatwiej niż Perl daje się wkomponowanać w istniejący dokument HTML. PHP zawiera wszystkie 'użyteczne' funkcje Perl: budowę, składnię, itd., przy czym ich używanie zostało w PHP znacznie uproszczone. Perl jest językiem sprawdzonym, używanym od końca lat 80. PHP jest jeszcze dosyć młodym językiem, ale bardzo szybko dojrzewa.

PHP and COM
Migrating from PHP 4 to PHP 5
FAQ


Migrating from PHP 4 to PHP 5

This faq section will help you migrate from PHP 4 to PHP 5.

  1. Migrating from PHP 4 to PHP 5
  2. Does MySQL work in PHP 5? It seemed to have disappeared.
  3. I hear PHP 5 has an entirely new OOP model, will my existing OOP code work? Where do I find information on these new OOP features?
  4. So besides the new OOP model, what else has changed in PHP 5? Also, is there a PHP 5 specific version of the PHP manual?
Migrating from PHP 4 to PHP 5

Although PHP 5 offers many new features, it's designed to be as compatible with earlier versions of PHP as possible with little functionality being broken in the process.

Be sure to read the appropriate PHP 5 migration appendix of this manual as it contains even more information on the topic of migrating to PHP 5.

Does MySQL work in PHP 5? It seemed to have disappeared.

MySQL is supported with the only change being that MySQL support is no longer enabled by default in PHP 5. This essentially means that PHP doesn't include the --with-mysql option in the configure line so that you must now manually do this when compiling PHP. Windows users will edit php.ini and enable the php_mysql.dll DLL as in PHP 4 no such DLL existed, it was simply built into your Windows PHP binaries.

Also, the MySQL client libraries are no longer bundled with PHP. More details on this topic are covered in the following FAQ and be sure to read the MySQL section for details on installing MySQL. An example configure line would be --with-mysql=/usr while Windows users will need the libmySQL.dll available to the system.

I hear PHP 5 has an entirely new OOP model, will my existing OOP code work? Where do I find information on these new OOP features?

The main change in PHP 5 is to the OOP model as PHP 5 now uses the Zend Engine 2.0. The zend.ze1_compatibility_mode directive enables compatability with the Zend Engine 1.0 (PHP 4).

The new OOP model is documented in the OOP language reference and OOP migration appendix sections.

So besides the new OOP model, what else has changed in PHP 5? Also, is there a PHP 5 specific version of the PHP manual?

Few other changes exist, see the migration 5 appendix for details. There won't be a PHP 5 specific version of the manual as the bulk of PHP remains the same.

PHP i inne języki
Miscellaneous Questions
FAQ


Miscellaneous Questions

There can be some questions we can't put into other categories. Here you can find them.

  1. How can I handle the bz2 compressed manuals on Windows?
  2. What does & beside argument mean in function declaration of e.g. asort?
  3. How do I deal with register_globals?
How can I handle the bz2 compressed manuals on Windows?

If you don't have an archiver-tool to handle bz2 files » download the command line tool from Redhat (please find further information below).

If you would not like to use a command line tool, you can try free tools like » Stuffit Expander, » UltimateZip, » 7-Zip, or » Quick Zip. If you have tools like » WinRAR or » Power Archiver, you can easily decompress the bz2 files with it. If you use Total Commander (formerly Windows Commander), a bz2 plugin for that program is available freely from the » Total Commander site.

The bzip2 command line tool from Redhat:

Win2k Sp2 users grab the latest version 1.0.2, all other Windows user should grab version 1.00. After downloading rename the executable to bzip2.exe. For convenience put it into a directory in your path, e.g. C:\Windows where C represents your Windows installation drive.

Note: lang stands for your language and x for the desired format, e.g.: pdf. To uncompress the php_manual_lang.x.bz2 follow these simple instructions:

  • open a command prompt window
  • cd to the folder where you stored the downloaded php_manual_lang.x.bz2
  • invoke bzip2 -d php_manual_lang.x.bz2, extracting php_manual_lang.x in the same folder

In case you downloaded the php_manual_lang.tar.bz2 with many html-files in it, the procedure is the same. The only difference is that you got a file php_manual_lang.tar. The tar format is known to be treated with most common archivers on Windows like e.g. » WinZip.

What does & beside argument mean in function declaration of e.g. asort()?

It means that the argument is passed by reference and the function will likely modify it corresponding to the documentation. You can pass only variables this way and you don't need to pass them with & in function call (it's even deprecated).

How do I deal with register_globals?

For information about the security implications of register_globals, read the security chapter on Using register_globals.

It's preferred to use superglobals, rather than relying upon register_globals being on.

If you are on a shared host with register_globals turned off and need to use some legacy applications, which require this option to be turned on, or you are on some hosting server, where this feature is turned on, but you would like to eliminate security risks, you might need to emulate the opposite setting with PHP. It is always a good idea to first ask if it would be possible to change the option somehow in PHP's configuration, but if it is not possible, then you can use these compatibility snippets.

Przykład #1 Emulating Register Globals

This will emulate register_globals On. If you altered your variables_order directive, consider changing the $superglobals accordingly.

<?php
// Emulate register_globals on
if (!ini_get('register_globals')) {
    $superglobals = array($_SERVER, $_ENV,
        $_FILES, $_COOKIE, $_POST, $_GET);
    if (isset($_SESSION)) {
        array_unshift($superglobals, $_SESSION);
    }
    foreach ($superglobals as $superglobal) {
        extract($superglobal, EXTR_SKIP);
    }
}
?>

This will emulate register_globals Off. Keep in mind, that this code should be called at the very beginning of your script, or after session_start() if you use it to start your session.

<?php
// Emulate register_globals off
function unregister_GLOBALS()
{
    if (!ini_get('register_globals')) {
        return;
    }

    // Might want to change this perhaps to a nicer error
    if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
        die('GLOBALS overwrite attempt detected');
    }

    // Variables that shouldn't be unset
    $noUnset = array('GLOBALS',  '_GET',
                     '_POST',    '_COOKIE',
                     '_REQUEST', '_SERVER',
                     '_ENV',     '_FILES');

    $input = array_merge($_GET,    $_POST,
                         $_COOKIE, $_SERVER,
                         $_ENV,    $_FILES,
                         isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());

    foreach ($input as $k => $v) {
        if (!in_array($k, $noUnset) && isset($GLOBALS[$k])) {
            unset($GLOBALS[$k]);
        }
    }
}

unregister_GLOBALS();

?>

Migrating from PHP 4 to PHP 5
Dodatki
FAQ


Dodatki

  • History of PHP and Related Projects
    • History of PHP
    • History of PHP related projects
    • Books about PHP
    • Publications about PHP
  • Migrating from PHP 5.3.x to PHP 5.4.x
    • What has changed in PHP 5.4.x
    • Backward Incompatible Changes
    • New features
    • Changes made to Windows support
    • Changes in SAPI modules
    • Deprecated features in PHP 5.4.x
    • New Parameters
    • New Functions
    • New stream wrappers
    • New stream filters
    • New Class Constants
    • New Methods
    • New Extensions
    • Removed Extensions
    • Other changes to extensions
    • New Classes
    • New Global Constants
    • Changes to INI file handling
    • Other changes
  • Migrating from PHP 5.2.x to PHP 5.3.x
    • What has changed in PHP 5.3.x
    • Backward Incompatible Changes
    • New features
    • Changes made to Windows support
    • Changes in SAPI modules
    • Deprecated features in PHP 5.3.x
    • Undeprecated features in PHP 5.3.x
    • New Parameters
    • New Functions
    • New stream wrappers
    • New stream filters
    • New Class Constants
    • New Methods
    • New Extensions
    • Removed Extensions
    • Other changes to extensions
    • New Classes
    • New Global Constants
    • Changes to INI file handling
    • Other changes
  • Migrating from PHP 5.1.x to PHP 5.2.x
    • What has changed in PHP 5.2.x
    • Backward Incompatible Changes
    • New Error Messages
    • Changes in PHP datetime support
    • New Parameters
    • New Functions
    • New Methods
    • Removed Extensions
    • New Extensions
    • New Classes
    • New Global Constants
    • New Class Constants
    • New INI Configuration Directives
    • Error Reporting
    • Other Enhancements
  • Migrating from PHP 5.0.x to PHP 5.1.x
    • Key PHP 5.1.x features
    • Changes in reference handling
    • Reading []
    • Integer values in function parameters
    • Class and object changes
    • Extensions
    • Date/time support
    • Changes in database support
    • Checking for E_STRICT
  • Migrating from PHP 4 to PHP 5.0.x
    • What has changed in PHP 5.0.x
    • Backward Incompatible Changes
    • CLI and CGI
    • Migrating Configuration Files
    • New Functions
    • New Directives
    • Databases
    • New Object Model
    • Error Reporting
  • Classes and Objects (PHP 4)
    • class
    • extends
    • Constructors
    • Scope Resolution Operator (::)
    • parent
    • Serializing objects - objects in sessions
    • The magic functions __sleep and __wakeup
    • References inside the constructor
    • Comparing objects
  • Debugging in PHP
    • About debugging in PHP
  • Configure options
    • List of core configure options
  • php.ini directives
    • List of php.ini directives
    • List of php.ini sections
    • Description of core php.ini directives
  • Wykaz i klasyfikacja rozszerzeń
    • Spis alfabetyczny
    • Przynależność
    • Stan
  • Lista aliasów funkcji
  • List of Reserved Words
    • List of Keywords
    • Predefined Classes
    • Predefiniowane stałe
  • Lista Rodzajów Zasobów
  • List of Available Filters
    • String Filters
    • Conversion Filters
    • Compression Filters
    • Encryption Filters
  • List of Supported Socket Transports
    • Internet Domain: TCP, UDP, SSL, and TLS
    • Unix Domain: Unix and UDG
  • Tabele porównań typów PHP
  • List of Parser Tokens
  • Userland Naming Guide
    • Global Namespace
    • Rules
    • Tips
  • About the manual
    • Formats
    • About user notes
    • How to read a function definition (prototype)
    • PHP versions documented in this manual
    • How to find more information about PHP
    • How to help improve the documentation
    • How we generate the formats
    • Translations
  • Creative Commons Attribution 3.0
  • Indeks
    • Wykaz funkcji i metod
    • Wykaz przykładów
Miscellaneous Questions
History of PHP and Related Projects
Podręcznik PHP


History of PHP and Related Projects

Spis treści

  • History of PHP
  • History of PHP related projects
  • Books about PHP
  • Publications about PHP

PHP has come a long way since its birth in the mid-1990's. From humble beginnings to becoming one of the most prominent languages powering the web, the evolution of PHP is a geek's faerie tale. Mind you, such explosive growth was no easy task. Those of you interested in briefly seeing how PHP grew to become what it is today, read on. If you'd like to touch a piece of Internet history, you can find old releases of PHP in the » PHP Museum.

Dodatki
History of PHP
Dodatki


History of PHP

PHP Tools, FI, Construction Kit, and PHP/FI

PHP as it's known today is actually the successor to a product named PHP/FI. Created in 1994 by Rasmus Lerdorf, the very first incarnation of PHP was a simple set of Common Gateway Interface (CGI) binaries written in the C programming language. Originally used for tracking visits to his online resume, he named the suite of scripts "Personal Home Page Tools," more frequently referenced as "PHP Tools." Over time, more functionality was desired, and Rasmus rewrote PHP Tools, producing a much larger and richer implementation. This new model was capable of database interaction and more, providing a framework upon which users could develop simple dynamic web applications such as guestbooks. In June of 1995, Rasmus » released the source code for PHP Tools to the public, which allowed developers to use it as they saw fit. This also permitted - and encouraged - users to provide fixes for bugs in the code, and to generally improve upon it.

In September of that year, Rasmus expanded upon PHP and - for a short time - actually dropped the PHP name. Now referring to the tools as FI (short for "Forms Interpreter"), the new implementation included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables, and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent. In fact, to embed the code into an HTML file, developers had to use HTML comments. Though this method was not entirely well-received, FI continued to enjoy growth and acceptance as a CGI tool --- but still not quite as a language. However, this began to change the following month; in October, 1995, Rasmus released a complete rewrite of the code. Bringing back the PHP name, it was now (briefly) named "Personal Home Page Construction Kit," and was the first release to boast what was, at the time, considered an advanced scripting interface. The language was deliberately designed to resemble C in structure, making it an easy adoption for developers familiar with C, Perl, and similar languages. Having been thus far limited to UNIX and POSIX-compliant systems, the potential for a Windows NT implementation was being explored.

The code got another complete makeover, and in April of 1996, combining the names of past releases, Rasmus introduced PHP/FI. This second-generation implementation began to truly evolve PHP from a suite of tools into a programming language in its own right. It included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support, and much more. That June, PHP/FI was given a version 2.0 status. An interesting fact about this, however, is that there was only one single full version of PHP 2.0. When it finally graduated from beta status in November, 1997, the underlying parsing engine was already being entirely rewritten.

Though it lived a short development life, it continued to enjoy a growing popularity in still-young world of web development. In 1997 and 1998, PHP/FI had a cult of several thousand users around the world. A Netcraft survey as of May, 1998, indicated that nearly 60,000 domains domains reported having headers containing "PHP," indicating that the host server did indeed have it installed. This number equated to approximately 1% of all domains on the Internet at the time. Despite these impressive figures, the maturation of PHP/FI was doomed to limitations; while there were several minor contributors, it was still primarily developed by an individual.

Przykład #1 Example PHP/FI Code

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, you are using Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Sorry, that record does not exist<p>
<!--endif exit-->
  Welcome <!--$user-->!<p>
  You have <!--$index:0--> credits left in your account.<p>

<!--include /text/footer.html-->

PHP 3

PHP 3.0 was the first version that closely resembles PHP as it exists today. Finding PHP/FI 2.0 still inefficient and lacking features they needed to power an eCommerce application they were developing for a university project, Andi Gutmans and Zeev Suraski of Tel Aviv, Israel, began yet another complete rewrite of the underlying parser in 1997. Approaching Rasmus online, they discussed various aspects of the current implementation and their redevelopment of PHP. In an effort to improve the engine and start building upon PHP/FI's existing user base, Andi, Rasmus, and Zeev decided to collaborate in the development of a new, independent programming language. This entirely new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was renamed simply 'PHP', with the meaning becoming a recursive acronym - PHP: Hypertext Preprocessor.

One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a mature interface for multiple databases, protocols, and APIs, the ease of extending the language itself attracted dozens of developers who submitted a variety of modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 included object-oriented programming support and a far more powerful and consistent language syntax.

In June, 1998, with many new developers from around the world joining the effort, PHP 3.0 was announced by the new PHP Development Team as the official successor to PHP/FI 2.0. Active development of PHP/FI 2.0, which had all-but ceased as of November of the previous year, was now officially ended. After roughly nine months of open public testing, when the announcement of the official release of PHP 3.0 came, it was already installed on over 70,000 domains around the world, and was no longer limited to POSIX-compliant operating systems. A relatively small share of the domains reporting PHP as installed were hosted on servers running Windows 95, 98, and NT, and Macintosh. At its peak, PHP 3.0 was installed on approximately 10% of the web servers on the Internet.

PHP 4

By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.

PHP 5

PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features.

PHP's development team includes dozens of developers, as well as dozens others working on PHP-related and supporting projects, such as PEAR, PECL, and documentation, and an underlying network infrastructure of well over one-hundred individual web servers on six of the seven continents of the world. Though only an estimate based upon statistics from previous years, it is safe to presume PHP is now installed on tens or even perhaps hundreds of millions of domains around the world.

History of PHP and Related Projects
History of PHP related projects
History of PHP and Related Projects


History of PHP related projects

PEAR

» PEAR, the PHP Extension and Application Repository (originally, PHP Extension and Add-on Repository) is PHP's version of foundation classes, and may grow in the future to be one of the key ways to distribute PHP extensions among developers.

PEAR was born in discussions held in the PHP Developers' Meeting (PDM) held in January 2000 in Tel Aviv. It was created by Stig S. Bakken, and is dedicated to his first-born daughter, Malin Bakken.

Since early 2000, PEAR has grown to be a big, significant project with a large number of developers working on implementing common, reusable functionality for the benefit of the entire PHP community. PEAR today includes a wide variety of infrastructure foundation classes for database access, content caching, mathematical calculations, eCommerce and much more.

More information about PEAR can be found in » the manual.

PHP Quality Assurance Initiative

The » PHP Quality Assurance Initiative was set up in the summer of 2000 in response to criticism that PHP releases were not being tested well enough for production environments. The team now consists of a core group of developers with a good understanding of the PHP code base. These developers spend a lot of their time localizing and fixing bugs within PHP. In addition there are many other team members who test and provide feedback on these fixes using a wide variety of platforms.

PHP-GTK

» PHP-GTK is the PHP solution for writing client side GUI applications. Andrei Zmievski remembers the planing and creation process of PHP-GTK:

GUI programming has always been of my interests, and I found that Gtk+ is a very nice toolkit, except that programming with it in C is somewhat tedious. After witnessing PyGtk and GTK-Perl implementations, I decided to see if PHP could be made to interface with Gtk+, even minimally. Starting in August of 2000, I began to have a bit more free time so that is when I started experimenting. My main guideline was the PyGtk implementation as it was fairly feature complete and had a nice object-oriented interface. James Henstridge, the author of PyGtk, provided very helpful advice during those initial stages.

Hand-writing the interfaces to all the Gtk+ functions was out of the question, so I seized upon the idea of code-generator, similar to how PyGtk did it. The code generator is a PHP program that reads a set of .defs file containing the Gtk+ classes, constants, and methods information and generates C code that interfaces PHP with them. What cannot be generated automatically can be written by hand in .overrides file.

Working on the code generator and the infrastructure took some time, because I could spend little time on PHP-GTK during the fall of 2000. After I showed PHP-GTK to Frank Kromann, he got interested and started helping me out with code generator work and Win32 implementation. When we wrote the first Hello World program and fired it up, it was extremely exciting. It took a couple more months to get the project to a presentable condition and the initial version was released on March 1, 2001. The story promptly hit SlashDot.

Sensing that PHP-GTK might be extensive, I set up separate mailing lists and CVS repositories for it, as well as the gtk.php.net website with the help of Colin Viebrock. The documentation would also need to be done and James Moore came in to help with that.

Since its release PHP-GTK has been gaining popularity. We have our own documentation team, the manual keeps improving, people start writing extensions for PHP-GTK, and more and more exciting applications with it.

History of PHP
Books about PHP
History of PHP and Related Projects


Books about PHP

As PHP grew, it began to be recognized as a world-wide popular development platform. One of the most interesting ways of seeing this trend was by observing the books about PHP that came out throughout the years.

To the best of our knowledge, the first book dedicated to PHP was 'PHP - tvorba interaktivních internetových aplikací' (PHP - Creating Interactive Internet Applications) - a Czech book published in April 1999, authored by Jirka Kosek. Next month followed a German book authored by Egon Schmid, Christian Cartus and Richard Blume. The first book in English about PHP was published shortly afterwards, and was 'Core PHP Programming' by Leon Atkinson. These books covered PHP 3.0.

While these books were the first of their kind - they were followed by a large number of books from a host of authors and publishers. There are over 400 books in English, over 100 books in German, and over 50 books in French or Spanish! In addition, you can find books about PHP in many other languages, including Korean, Japanese and Hebrew.

Clearly, this large number of books, written by different authors, published by many publishers, and their availability in so many languages - are a strong testimony for PHP's world-wide success.

History of PHP related projects
Publications about PHP
History of PHP and Related Projects


Publications about PHP

To the best of our knowledge, the first article about PHP in a hard-copy magazine was published in the Czech mutation of Computerworld in the spring of 1998, and covered PHP 3.0. As with books, this was the first in a series of many articles published about PHP in various prominent magazines.

Articles about PHP appeared in Dr. Dobbs, Linux Enterprise, Linux Magazine and many more. Articles about migrating ASP-based applications to PHP under Windows even appear on Microsoft's very own MSDN!

Books about PHP
Migrating from PHP 5.3.x to PHP 5.4.x
History of PHP and Related Projects


Migrating from PHP 5.3.x to PHP 5.4.x

Spis treści

  • What has changed in PHP 5.4.x
  • Backward Incompatible Changes
  • New features
  • Changes made to Windows support
  • Changes in SAPI modules
  • Deprecated features in PHP 5.4.x
  • New Parameters
  • New Functions
  • New stream wrappers
  • New stream filters
  • New Class Constants
  • New Methods
  • New Extensions
  • Removed Extensions
  • Other changes to extensions
  • New Classes
  • New Global Constants
  • Changes to INI file handling
  • Other changes

Zobacz także instrukcję migracji na nowsze wersje PHP 5.0.x, 5.1.x, 5.2.x and 5.3.x.

Publications about PHP
What has changed in PHP 5.4.x
Dodatki


What has changed in PHP 5.4.x

Ostrzeżenie

This list is incomplete and is undergoing constant changes until PHP 5.4 is is about to be released.

For systems being upgraded from an older version of PHP, the relevant documentation is available at:

  • Upgrade Notes for PHP 5.3.x.
  • Upgrade Notes for PHP 5.2.x.
  • Upgrade Notes for PHP 5.1.x.
  • Migrating from PHP 4 to PHP 5.
Migrating from PHP 5.3.x to PHP 5.4.x
Backward Incompatible Changes
Migrating from PHP 5.3.x to PHP 5.4.x


Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

The following keyword(s) are now reserved and may not be used in function, class, etc. names.

  • trait
What has changed in PHP 5.4.x
New features
Migrating from PHP 5.3.x to PHP 5.4.x


New features

PHP 5.4.0 offers a wide range of new features:

  • Support for traits has been added.
Backward Incompatible Changes
Changes made to Windows support
Migrating from PHP 5.3.x to PHP 5.4.x


Changes made to Windows support

Changes to the Windows releases:

Windows support has been added for the following functions:

Other changes:

New features
Changes in SAPI modules
Migrating from PHP 5.3.x to PHP 5.4.x


Changes in SAPI modules

  • A new SAPI module named cli-server is now available.
Changes made to Windows support
Deprecated features in PHP 5.4.x
Migrating from PHP 5.3.x to PHP 5.4.x


Deprecated features in PHP 5.4.x

The following is a list of deprecated INI directives. Use of any of these INI directives will cause an E_DEPRECATED error to be thrown at startup.

Deprecated functions:

Deprecated features:

Changes in SAPI modules
New Parameters
Migrating from PHP 5.3.x to PHP 5.4.x


New Parameters

Several functions were given new, optional parameters in PHP 5.4:

PHP Core:

New method parameters in PHP 5.4.0:

PHP Core:

Deprecated features in PHP 5.4.x
New Functions
Migrating from PHP 5.3.x to PHP 5.4.x


New Functions

PHP 5.4 introduced some new functions:

PHP Core:

The following functions are now natively implemented, making them available on all operating systems which can run PHP:

New Parameters
New stream wrappers
Migrating from PHP 5.3.x to PHP 5.4.x


New stream wrappers

The following stream wrappers were introduced in 5.4.0:

New Functions
New stream filters
Migrating from PHP 5.3.x to PHP 5.4.x


New stream filters

The following stream filters were introduced in 5.4.0:

New stream wrappers
New Class Constants
Migrating from PHP 5.3.x to PHP 5.4.x


New Class Constants

Several new class constants were introduced in 5.4.0:

New stream filters
New Methods
Migrating from PHP 5.3.x to PHP 5.4.x


New Methods

Several new methods were introduced in 5.4.0:

New Class Constants
New Extensions
Migrating from PHP 5.3.x to PHP 5.4.x


New Extensions

The following new extensions are added (by default) as of PHP 5.4.0:

New Methods
Removed Extensions
Migrating from PHP 5.3.x to PHP 5.4.x


Removed Extensions

These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package versions of these extensions will be created according to user demand.

New Extensions
Other changes to extensions
Migrating from PHP 5.3.x to PHP 5.4.x


Other changes to extensions

The following extensions can no longer be disabled during build configuration:

Changes in extension behaviour, and new features:

  • mysqli_result now implements Traversable.
Removed Extensions
New Classes
Migrating from PHP 5.3.x to PHP 5.4.x


New Classes

The following classes were introduced in PHP 5.4.0:

Other changes to extensions
New Global Constants
Migrating from PHP 5.3.x to PHP 5.4.x


New Global Constants

PHP Core:

New Classes
Changes to INI file handling
Migrating from PHP 5.3.x to PHP 5.4.x


Changes to INI file handling

The following ini directives have new default values:

New Global Constants
Other changes
Migrating from PHP 5.3.x to PHP 5.4.x


Other changes

  • E_ALL now includes E_STRICT.
Changes to INI file handling
Migrating from PHP 5.2.x to PHP 5.3.x
Migrating from PHP 5.3.x to PHP 5.4.x


Migrating from PHP 5.2.x to PHP 5.3.x

Spis treści

  • What has changed in PHP 5.3.x
  • Backward Incompatible Changes
  • New features
  • Changes made to Windows support
  • Changes in SAPI modules
  • Deprecated features in PHP 5.3.x
  • Undeprecated features in PHP 5.3.x
  • New Parameters
  • New Functions
  • New stream wrappers
  • New stream filters
  • New Class Constants
  • New Methods
  • New Extensions
  • Removed Extensions
  • Other changes to extensions
  • New Classes
  • New Global Constants
  • Changes to INI file handling
  • Other changes

Zobacz także instrukcję migracji na nowsze wersje PHP 5.0.x, 5.1.x and 5.2.x.

Other changes
What has changed in PHP 5.3.x
Dodatki


What has changed in PHP 5.3.x

Most improvements in PHP 5.3.x have no impact on existing code. There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

For systems being upgraded from an older version of PHP, the relevant documentation is available at:

  • Upgrade Notes for PHP 5.2.x.
  • Upgrade Notes for PHP 5.1.x.
  • Migrating from PHP 4 to PHP 5.
Migrating from PHP 5.2.x to PHP 5.3.x
Backward Incompatible Changes
Migrating from PHP 5.2.x to PHP 5.3.x


Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

  • The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error.
  • clearstatcache() no longer clears the realpath cache by default.
  • realpath() is now fully platform-independent. Consequence of this is that invalid relative paths such as __FILE__ . "/../x" do not work anymore.
  • The call_user_func() family of functions now propagate $this even if the callee is a parent class.
  • The array functions natsort(),
natcasesort(), usort(),
uasort(), uksort(),
array_flip(), and array_unique() no
longer accept objects passed as arguments. To apply these functions to an
object, cast the object to an array first.
  • The behaviour of functions with by-reference parameters called by value has changed. Where previously the function would accept the by-value argument, a fatal error is now emitted. Any previous code passing constants or literals to functions expecting references, will need altering to assign the value to a variable before calling the function.
  • The new mysqlnd library necessitates the use of MySQL 4.1's newer 41-byte password format. Continued use of the old 16-byte passwords will cause mysql_connect() and similar functions to emit the error, "mysqlnd cannot connect to MySQL 4.1+ using old authentication."
  • The new mysqlnd library does not read mysql configuration files (my.cnf/my.ini), as the older libmysql library does. If your code relies on settings in the configuration file, you can load it explicitly with the mysqli_options() function. Note that this means the PDO specific constants PDO::MYSQL_ATTR_READ_DEFAULT_FILE and PDO::MYSQL_ATTR_READ_DEFAULT_GROUP are not defined if MySQL support in PDO is compiled with mysqlnd.
  • The trailing / has been removed from the SplFileInfo class and other related directory classes.
  • The __toString() magic method can no longer accept arguments.
  • The magic methods
__get(),
__set(),
__isset(),
__unset(), and
__call() must always
be public and can no longer be static. Method signatures are now enforced.
  • The __call() magic method is now invoked on access to private and protected methods.
  • func_get_arg(), func_get_args() and func_num_args() can no longer be called from the outermost scope of a file that has been included by calling include() or require() from within a function in the calling file.
  • An emulation layer for the MHASH extension to wrap around the Hash extension have been added. However not all the algorithms are covered, notable the s2k hashing algorithm. This means that s2k hashing is no longer available as of PHP 5.3.0.

The following keywords are now reserved and may not be used in function, class, etc. names.

  • goto
  • namespace
What has changed in PHP 5.3.x
New features
Migrating from PHP 5.2.x to PHP 5.3.x


New features

PHP 5.3.0 offers a wide range of new features:

  • Support for namespaces has been added.
  • Support for Late Static Bindings has been added.
  • Support for jump labels (limited goto) has been added.
  • Support for native Closures (Lambda/Anonymous functions) has been added.
  • There are two new magic methods, __callStatic() and __invoke().
  • Nowdoc syntax is now supported, similar to Heredoc syntax, but with single quotes.
  • It is now possible to use Heredocs to initialize static variables and class properties/constants.
  • Heredocs may now be declared using double quotes, complementing the Nowdoc syntax.
  • Constants can now be declared outside a class using the const keyword.
  • The ternary operator now has a shorthand form: ?:.
  • The HTTP stream wrapper now considers all status codes from 200 to 399 to be successful.
  • Dynamic access to static methods is now possible.
  • Exceptions can now be nested.
  • A garbage collector for circular references has been added, and is enabled by default.
  • The mail() function now supports logging of sent email. (Note: This only applies to email sent through this function.)
Backward Incompatible Changes
Changes made to Windows support
Migrating from PHP 5.2.x to PHP 5.3.x


Changes made to Windows support

Changes to the Windows releases:

  • The minimum Windows version is now Windows XP SP3; Windows 98, ME, 2000 and NT4 are no longer supported.
  • Windows binaries now target i586 and later. i386 and i486 are not supported.
  • There is now experimental support for x64 versions of PHP on Windows.
  • There is now compiler support for Visual C++ 9 (VC9), using Visual Studio 2008. Snapshots and releases will now also be available for VC9. Old binaries using VC6 are still supported and released in the line with VC9.
  • The PDO_OCI php_pdo_oci8.dll library (for use with Oracle version 8 client libraries) is no longer being built. Instead, use php_pdo_oci.dll (note no '8') with Oracle 10 or 11 client libraries. Connection to other database versions is still supported.
  • For the OCI8 extension, a new library php_oci8_11g.dll is available in addition to php_oci8.dll. Only one can be enabled at any time. Use php_oci8.dll with Oracle 10.2 client libraries. Use php_oci8_11g.dll with Oracle 11 client libraries. Connection to other database versions is still supported.

Windows support has been added for the following functions:

  • checkdnsrr()
  • dns_get_record()
  • fnmatch()
  • getmxrr()
  • getopt()
  • imagecolorclosesthwb()
  • inet_ntop()
  • inet_pton()
  • link()
  • linkinfo()
  • mcrypt_create_iv()
  • readlink()
  • socket_create_pair() - This function was previously available on Windows, but was disabled as of PHP 4.3.0 due to a bug.
  • stream_socket_pair()
  • symlink()
  • time_nanosleep()
  • time_sleep_until()

Other changes:

  • Improved portability of the stat(), touch(), filemtime(), filesize() functions, and other related functions (100% portable for the available data).
  • It is now possible to create hard links on Windows using the link() function, and symbolic links using the symlink() function. Hard links are available as of Windows 2000, and symbolic links as of Windows Vista.
  • The Windows version of PHP now exposes a set of constants prefixed PHP_WINDOWS_*. A list of these constants and their usage can be found at Stałe predefiniowane.
Ostrzeżenie

Support for the ISAPI module has been dropped. Use the improved FastCGI SAPI module instead.

Informacja: A new dedicated site for PHP on Windows is now available, including downloads, release candidates, and snapshots in various flavors (thread-safe/not-thread-safe, VC6/VC9, x86/x64). The URL of this site is » http://windows.php.net/.

New features
Changes in SAPI modules
Migrating from PHP 5.2.x to PHP 5.3.x


Changes in SAPI modules

  • A new SAPI module named litespeed is now available.
  • FastCGI support in the CGI SAPI is now always enabled and can not be disabled. See sapi/cgi/CHANGES for more details.
  • A new CGI SAPI option, -T, can be used to measure repeated execution time of a script.
  • CGI/FastCGI now has support for .htaccess-style user-defined php.ini files.
  • The dl() function is now disabled by default, and is now available only under the CLI, CGI, and embed SAPIs.
Changes made to Windows support
Deprecated features in PHP 5.3.x
Migrating from PHP 5.2.x to PHP 5.3.x


Deprecated features in PHP 5.3.x

PHP 5.3.0 introduces two new error levels: E_DEPRECATED and E_USER_DEPRECATED. The E_DEPRECATED error level is used to indicate that a function or feature has been deprecated. The E_USER_DEPRECATED level is intended for indicating deprecated features in user code, similarly to the E_USER_ERROR and E_USER_WARNING levels.

The following is a list of deprecated INI directives. Use of any of these INI directives will cause an E_DEPRECATED error to be thrown at startup.

  • define_syslog_variables
  • register_globals
  • register_long_arrays
  • safe_mode
  • magic_quotes_gpc
  • magic_quotes_runtime
  • magic_quotes_sybase
  • Comments starting with '#' are now deprecated in .INI files.

Deprecated functions:

  • call_user_method() (use call_user_func() instead)
  • call_user_method_array() (use call_user_func_array() instead)
  • define_syslog_variables()
  • dl()
  • ereg() (use preg_match() instead)
  • ereg_replace() (use preg_replace() instead)
  • eregi() (use preg_match() with the 'i' modifier instead)
  • eregi_replace() (use preg_replace() with the 'i' modifier instead)
  • set_magic_quotes_runtime() and its alias, magic_quotes_runtime()
  • session_register() (use the $_SESSION superglobal instead)
  • session_unregister() (use the $_SESSION superglobal instead)
  • session_is_registered() (use the $_SESSION superglobal instead)
  • set_socket_blocking() (use stream_set_blocking() instead)
  • split() (use preg_split() instead)
  • spliti() (use preg_split() with the 'i' modifier instead)
  • sql_regcase()
  • mysql_db_query() (use mysql_select_db() and mysql_query() instead)
  • mysql_escape_string() (use mysql_real_escape_string() instead)
  • Passing locale category names as strings is now deprecated. Use the LC_* family of constants instead.
  • The is_dst parameter to mktime(). Use the new timezone handling functions instead.

Deprecated features:

  • Assigning the return value of new by reference is now deprecated.
  • Call-time pass-by-reference is now deprecated.
Changes in SAPI modules
Undeprecated features in PHP 5.3.x
Migrating from PHP 5.2.x to PHP 5.3.x


Undeprecated features in PHP 5.3.x

The is_a() function has been undeprecated by popular request; it will no longer issue an E_STRICT error.

Deprecated features in PHP 5.3.x
New Parameters
Migrating from PHP 5.2.x to PHP 5.3.x


New Parameters

Several functions were given new, optional parameters in PHP 5.3:

PHP Core:

  • clearstatcache() - Added clear_realpath_cache and filename.
  • copy() - Added a stream context parameter, context.
  • fgetcsv() - Added escape.
  • ini_get_all() - Added details.
  • nl2br() - Added is_xhtml.
  • parse_ini_file() - Added scanner_mode.
  • round() - Added mode.
  • stream_context_create() - Added params.
  • strstr() and stristr() - Added before_needle.

json:

  • json_encode() - Added options.
  • json_decode() - Added depth.

Streams:

  • stream_select(),
stream_set_blocking(),
stream_set_timeout(), and
stream_set_write_buffer() now work with user-space
stream wrappers.

sybase_ct:

  • sybase_connect() - Added new.

New method parameters in PHP 5.3.0:

PHP Core:

  • Exception::__construct() - Added previous.
Undeprecated features in PHP 5.3.x
New Functions
Migrating from PHP 5.2.x to PHP 5.3.x


New Functions

PHP 5.3 introduced some new functions:

PHP Core:

  • array_replace() - Replaces elements from passed arrays into one array.
  • array_replace_recursive() - Recursively replaces elements from passed arrays into one array.
  • class_alias() - Creates an alias for a user defined class.
  • forward_static_call() - Call a user function from a method context.
  • forward_static_call_array() - Call a user function from a method context, with the arguments contained in an array.
  • gc_collect_cycles() - Forces collection of any existing garbage cycles.
  • gc_disable() - Deactivates the circular reference collector.
  • gc_enable() - Activates the circular reference collector.
  • gc_enabled() - Returns the status of the circular reference collector.
  • get_called_class() - Return the name of the class a static method is called in.
  • gethostname() - Return the current host name for the local machine.
  • header_remove() - Removes an HTTP header previously set using the header() function.
  • lcfirst() - Make a string's first character lowercase.
  • parse_ini_string() - Parse a configuration string.
  • quoted_printable_encode() - Convert an 8 bit string to a quoted-printable string.
  • str_getcsv() - Parse a CSV string into an array.
  • stream_context_set_default() - Set the default stream context.
  • stream_supports_lock() - Return TRUE if the stream supports locking.
  • stream_context_get_params() - Retrieve parameters from a stream context.
  • streamWrapper::stream_cast() - Retrieve the underlying stream resource.
  • streamWrapper::stream_set_option() - Change stream options

Date/Time:

  • date_add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object.
  • date_create_from_format() - Returns a new DateTime object formatted according to the given format.
  • date_diff() - Returns the difference between two DateTime objects.
  • date_get_last_errors() - Returns the warnings and errors from the last date/time operation.
  • date_parse_from_format() - Get infoformation about a given date.
  • date_sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object.
  • timezone_version_get() - Returns the version of the timezonedb.

GMP:

  • gmp_testbit() - Tests whether a bit is set.

Hash:

  • hash_copy() - Copy hashing context.

IMAP:

  • imap_gc() - Clears IMAP cache.
  • imap_utf8_to_mutf7() - Encode a UTF-8 string to modified UTF-7.
  • imap_mutf7_to_utf8() - Decode a modified UTF-7 string to UTF-8.

JSON:

  • json_last_error() - Returns the last JSON error that occurred.

MySQL Improved:

  • mysqli_fetch_all() - Fetches all result rows as an associative array, a numeric array, or both.
  • mysqli_get_connection_stats() - Returns statistics about the client connection.
  • mysqli_poll() - Poll connections.
  • mysqli_reap_async_query() - Get result from async query.

OpenSSL:

  • openssl_random_pseudo_bytes() - Returns a string of the given length specified, filled with pseudo-random bytes.

PCNTL:

  • pcntl_signal_dispatch() - Calls signal handlers for pending signals.
  • pcntl_sigprocmask() - Sets and retrieves blocked signals.
  • pcntl_sigtimedwait() - Wait for signals with a timeout.
  • pcntl_sigwaitinfo() - Wait for signals.

PCRE:

  • preg_filter() - Perform a regular expression search and replace, returning only results which matched the pattern.

Semaphore:

  • msg_queue_exists() - Check whether a message queue exists.
  • shm_has_var() - Checks whether a specific key exists inside a shared memory segment.

The following functions are now natively implemented, making them available on all operating systems which can run PHP:

  • acosh()
  • asinh()
  • atanh()
  • expm1()
  • log1p()
New Parameters
New stream wrappers
Migrating from PHP 5.2.x to PHP 5.3.x


New stream wrappers

The following stream wrappers were introduced in 5.3.0:

  • glob://
  • phar://
New Functions
New stream filters
Migrating from PHP 5.2.x to PHP 5.3.x


New stream filters

The following stream filters were introduced in 5.3.0:

  • dechunk (reverses HTTP chunked encoding)
  • The bz2.decompress filter now supports concatenation.
New stream wrappers
New Class Constants
Migrating from PHP 5.2.x to PHP 5.3.x


New Class Constants

Several new class constants were introduced in 5.3.0:

PDO_FIREBIRD:

  • PDO::FB_ATTR_DATE_FORMAT - Sets the format for dates.
  • PDO::FB_ATTR_TIME_FORMAT - Sets the format for time.
  • PDO::FB_ATTR_TIMESTAMP_FORMAT - Sets the format for timestamps.
New stream filters
New Methods
Migrating from PHP 5.2.x to PHP 5.3.x


New Methods

Several new methods were introduced in 5.3.0:

Date/Time:

  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object.
  • DateTime::createFromFormat() - Returns a new DateTime object formatted according to the given format.
  • DateTime::diff() - Returns the difference between two DateTime objects.
  • DateTime::getLastErrors() - Returns the warnings and errors from the last date/time operation.
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object.

Exception:

  • Exception::getPrevious() - Retrieves the previous exception.

DOM:

  • DOMNode::getLineNo() - Get the line number of a parsed node.

PDO_FIREBIRD:

  • PDO::setAttribute() - Sets an attribute.

Reflection:

  • ReflectionClass::getNamespaceName() - Returns the name of namespace where this class is defined.
  • ReflectionClass::getShortName() - Returns the short name of this class (without namespace part).
  • ReflectionClass::inNamespace() - Returns whether this class is defined in a namespace.
  • ReflectionFunction::getNamespaceName() - Returns the name of namespace where this function is defined.
  • ReflectionFunction::getShortName() - Returns the short name of the function (without namespace part).
  • ReflectionFunction::inNamespace() - Returns whether this function is defined in a namespace.
  • ReflectionProperty::setAccessible() - Sets whether non-public properties can be requested.

SPL:

  • SplObjectStorage::addAll() - Add all elements from another SplObjectStorage object.
  • SplObjectStorage::removeAll() - Remove all elements from another SplObjectStorage object.

XSL:

  • XSLTProcessor::setProfiling() - Sets the profiling output file.
New Class Constants
New Extensions
Migrating from PHP 5.2.x to PHP 5.3.x


New Extensions

The following new extensions are added (by default) as of PHP 5.3.0:

  • Enchant - An abstraction layer above various spelling libraries
  • Fileinfo - An improved and more solid replacement, featuring full BC, for the Mimetype extension, which has been removed.
  • INTL - Internationalization extension. INTL is a wrapper around the » ICU library.
  • Phar - Implementation of PHP-Archive files.
  • SQLite3 - Support for SQLite version 3 databases.

mysqlnd is a new core library shipped with PHP. It is a PHP-specific replacement for libmysql. mysqlnd will be used to build the mysql, mysqli and PDO_MySQL extensions if libmysql isnt found on the system. It may also be used instead of libmysql even when libmysql is present. mysqlnd is recommended for all PHP installations for performance reasons.

New Methods
Removed Extensions
Migrating from PHP 5.2.x to PHP 5.3.x


Removed Extensions

These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package versions of these extensions will be created according to user demand.

  • dbase - No longer maintained
  • fbsql - No longer maintained
  • fdf - Maintained
  • ming - Maintained
  • msql - No longer maintained
  • ncurses - Maintained
  • sybase - Discontinued; use the sybase_ct extension instead
  • mhash - Discontinued; use the hash extension instead. hash has full mhash compatibility; all existing applications using the old functions will continue to work.
New Extensions
Other changes to extensions
Migrating from PHP 5.2.x to PHP 5.3.x


Other changes to extensions

The following extensions can no longer be disabled during build configuration:

  • PCRE
  • Reflection
  • SPL

Changes in extension behaviour, and new features:

  • Date and Time - The TZ environment variable is no longer used to guess the timezone
  • cURL - cURL now supports SSH
  • Network - dns_check_record() now returns an extra "entries" index, containing the TXT elements.
  • Hash - The SHA-224 and salsa hash algorithms are now supported.
  • mbstring - Now supports CP850 encoding.
  • OCI8 - A call to oci_close() on a persistent connection, or a variable referencing a persistent connection going out of scope, will now roll back any uncommitted transaction. To avoid unexpected behavior, explicitly issue a commit or roll back as needed. The old behavior can be enabled with the INI directive oci8.old_oci_close_semantics. Database Resident Connection Pooling (DRCP) and Fast Application Notification (FAN) are now supported. Oracle External Authentication is now supported (except on Windows). The oci_bind_by_name() function now supports SQLT_AFC (aka the CHAR datatype).
  • OpenSSL - OpenSSL digest and cipher functions are now supported. It is also now possible to access the internal values of DSA, RSA and DH keys.
  • Session - Sessions will no longer store session-files in "/tmp" when open_basedir restrictions apply, unless "/tmp" is explicitly added to the list of allowed paths.
  • SOAP Now supports sending user supplied HTTP headers.
  • MySQLi Now supports persistent connections, by prepending the hostname with "p:".
  • Image Processing and GD The "JPG Support" index returned from gd_info() has been renamed to "JPEG Support".
Removed Extensions
New Classes
Migrating from PHP 5.2.x to PHP 5.3.x


New Classes

The following classes were introduced in PHP 5.3.0:

Date/Time:

  • DateInterval
  • DatePeriod

Phar:

  • Phar
  • PharData
  • PharException
  • PharFileInfo

SPL:

  • FilesystemIterator
  • GlobIterator
  • MultipleIterator
  • RecursiveTreeIterator
  • SplDoublyLinkedList
  • SplFixedArray
  • SplHeap
  • SplMaxHeap
  • SplMinHeap
  • SplPriorityQueue
  • SplQueue
  • SplStack
Other changes to extensions
New Global Constants
Migrating from PHP 5.2.x to PHP 5.3.x


New Global Constants

PHP Core:

  • __DIR__
  • __NAMESPACE__
  • E_DEPRECATED
  • E_USER_DEPRECATED
  • INI_SCANNER_NORMAL
  • INI_SCANNER_RAW
  • PHP_MAXPATHLEN
  • PHP_WINDOWS_NT_DOMAIN_CONTROLLER
  • PHP_WINDOWS_NT_SERVER
  • PHP_WINDOWS_NT_WORKSTATION
  • PHP_WINDOWS_VERSION_BUILD
  • PHP_WINDOWS_VERSION_MAJOR
  • PHP_WINDOWS_VERSION_MINOR
  • PHP_WINDOWS_VERSION_PLATFORM
  • PHP_WINDOWS_VERSION_PRODUCTTYPE
  • PHP_WINDOWS_VERSION_SP_MAJOR
  • PHP_WINDOWS_VERSION_SP_MINOR
  • PHP_WINDOWS_VERSION_SUITEMASK

cURL:

  • CURLOPT_PROGRESSFUNCTION

GD:

  • IMG_FILTER_PIXELATE

JSON:

  • JSON_ERROR_CTRL_CHAR
  • JSON_ERROR_DEPTH
  • JSON_ERROR_NONE
  • JSON_ERROR_STATE_MISMATCH
  • JSON_ERROR_SYNTAX
  • JSON_FORCE_OBJECT
  • JSON_HEX_TAG
  • JSON_HEX_AMP
  • JSON_HEX_APOS
  • JSON_HEX_QUOT

LDAP:

  • LDAP_OPT_NETWORK_TIMEOUT

libxml:

  • LIBXML_LOADED_VERSION

PCRE:

  • PREG_BAD_UTF8_OFFSET_ERROR

PCNTL:

  • BUS_ADRALN
  • BUS_ADRERR
  • BUS_OBJERR
  • CLD_CONTIUNED
  • CLD_DUMPED
  • CLD_EXITED
  • CLD_KILLED
  • CLD_STOPPED
  • CLD_TRAPPED
  • FPE_FLTDIV
  • FPE_FLTINV
  • FPE_FLTOVF
  • FPE_FLTRES
  • FPE_FLTSUB
  • FPE_FLTUND
  • FPE_INTDIV
  • FPE_INTOVF
  • ILL_BADSTK
  • ILL_COPROC
  • ILL_ILLADR
  • ILL_ILLOPC
  • ILL_ILLOPN
  • ILL_ILLTRP
  • ILL_PRVOPC
  • ILL_PRVREG
  • POLL_ERR
  • POLL_HUP
  • POLL_IN
  • POLL_MSG
  • POLL_OUT
  • POLL_PRI
  • SEGV_ACCERR
  • SEGV_MAPERR
  • SI_ASYNCIO
  • SI_KERNEL
  • SI_MESGQ
  • SI_NOINFO
  • SI_QUEUE
  • SI_SIGIO
  • SI_TIMER
  • SI_TKILL
  • SI_USER
  • SIG_BLOCK
  • SIG_SETMASK
  • SIG_UNBLOCK
  • TRAP_BRKPT
  • TRAP_TRACE
New Classes
Changes to INI file handling
Migrating from PHP 5.2.x to PHP 5.3.x


Changes to INI file handling

PHP 5.3.0 has significantly improved performance and parsing of INI files, and adds several new syntax features.

  • The standard php.ini files have been re-organized and renamed. php.ini-development contains settings recommded for use in development environments. php.ini-production contains settings recommended for use in production environments.
  • There is now support for two special sections: [PATH=/opt/httpd/www.example.com/] and [HOST=www.example.com]. Directives set in these sections cannot be overridden by user-defined INI files or at runtime. More information about these sections can be found here.
  • zend_extension_debug and zend_extension_ts have been removed. Use the zend_extension directive to load all Zend Extensions.
  • zend.ze1_compatibility_mode has been removed. If this INI directive is set to On, an E_ERROR error is emitted at startup.
  • It is now possible to use the full path to load modules using the "extension" directive.
  • "ini-variables" can now be used almost anywhere in a php.ini file.
  • Runtime tightening of open_basedir restrictions is now possible.
  • It is now possible to use alphanumeric or variable indices in INI option arrays.
  • get_cfg_var() is now able to return "array" INI options.
  • A new directive, mail.add_x_header, has been added.
  • user_ini.filename is new
  • user_ini.cache_ttl is also new
  • exit_on_timeout is new too
  • open_basedir is now PHP_INI_ALL

The following new ini directives have been added:

  • user_ini.filename and user_ini.cache_ttl for the new .htaccess-style user INI file mechanism.
  • Added mbstring.http_output_conv_mimetype. This directive specifies the regex pattern of content types for which mb_output_handler() is activated.
  • Added request_order. Allows controlling which external variables will be available in $_REQUEST.

The following ini directives have new default values:

  • session.use_only_cookies is now set to "1" (enabled) by default.
  • oci8.default_prefetch has changed from "10" to "100".
New Global Constants
Other changes
Migrating from PHP 5.2.x to PHP 5.3.x


Other changes

  • SplFileInfo::getpathinfo() now returns information about the path name.
  • SplObjectStorage now has ArrayAccess support. It is now also possible to store associative information with objects in SplObjectStorage.
  • In the GD extension, there is now pixelation support available through the imagefilter() function.
  • var_dump() output now includes private object properties.
  • session_start() now returns FALSE when session startup fails.
  • property_exists() now checks the existence of a property independent of accessibility (like method_exists()).
  • Stream wrappers can now be used by include_path.
  • The initial parameter for array_reduce() can now be of any type.
  • The directory functions opendir(), scandir(), and dir() now use the default stream context if no explicit context is passed.
  • crypt() now has Blowfish and extended DES support, and crypt() features are now 100% portable. PHP has its own internal crypt implementation which drops into place when support for crypt or crypt_r is not found.
  • getopt() now accepts "long options" on all platforms. Optional values and = as a separator for short options are now supported.
  • fopen() has a new mode option (n), which passes O_NONBLOCK to the underlying open() system call. Note that this mode is not currently supported on Windows.
  • getimagesize() now supports icon files (.ico).
  • The mhash extension have moved to PECL, but the Hash extension have been modified to support mhash if PHP is compiled with --with-mhash. Note that the Hash extension does not require the mhash library to be available whether or not the mhash emulation is enabled.
Changes to INI file handling
Migrating from PHP 5.1.x to PHP 5.2.x
Migrating from PHP 5.2.x to PHP 5.3.x


Migrating from PHP 5.1.x to PHP 5.2.x

Spis treści

  • What has changed in PHP 5.2.x
  • Backward Incompatible Changes
  • New Error Messages
  • Changes in PHP datetime support
  • New Parameters
  • New Functions
  • New Methods
  • Removed Extensions
  • New Extensions
  • New Classes
  • New Global Constants
  • New Class Constants
  • New INI Configuration Directives
  • Error Reporting
  • Other Enhancements

Zobacz także instrukcję migracji na nowsze wersje PHP 5.0.x, 5.1.x and 5.3.x.

Other changes
What has changed in PHP 5.2.x
Dodatki


What has changed in PHP 5.2.x

Most improvements in PHP 5.2.x have no impact on existing code. There are a few incompatibilities and new error messages that should be considered, and code should be tested before switching PHP versions in production environments.

If the system is being upgraded from PHP 5.0.x, the manual section titled Upgrade Notes for PHP 5.1.x should also be read.

Similarly, if the system is being upgraded from PHP 4, the manual section titled Migrating from PHP 4 to PHP 5 should be read as well.

Migrating from PHP 5.1.x to PHP 5.2.x
Backward Incompatible Changes
Migrating from PHP 5.1.x to PHP 5.2.x


Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, you should pay attention to the following backward incompatible changes:

  • getrusage() returns NULL when passed incompatible arguments as of PHP 5.2.1.
  • ZipArchive::setCommentName() returns TRUE on success as of PHP 5.2.1.
  • ZipArchive::setCommentIndex() returns TRUE on success as of PHP 5.2.1.
  • SplFileObject::getFilename() returns the filename, not relative/path/to/file, as of PHP 5.2.1.
  • Changed priority of PHPRC environment variable on Win32 The PHPRC environment variable now takes priority over the path stored in the Windows registry.
  • CLI SAPI no longer checks cwd for php.ini or the php-cli.ini file In PHP 5.1.x an undocumented feature was added that made the CLI binary check the current working directory for a PHP configuration file, potentially leading to unpredictable behavior if an unexpected configuration file were read. This functionality was removed in 5.2.0, and PHP will no longer search CWD for the presence of php.ini or php-cli.ini files. See also the command line section of the manual.
  • Added a warning when performing modulus 0 operations In earlier versions of PHP, performing integer % 0 did not emit any warning messages, instead returning an unexpected return value of FALSE. As of PHP 5.2.0, this operation will emit an E_WARNING, as is the case in all other instances where division by zero is performed.
    <?php
    print 10 % 0;
    /* Warning:  Division by zero in filename on line n */
    ?>
  • Changed __toString() to be called wherever applicable. The magic method __toString() will now be called in a string context, that is, anywhere an object is used as a string. The fallback of returning a string that contains the object identifier was dropped in PHP 5.2.0. It became problematic because an object identifier cannot be considered unique. This change will mean that your application is flawed if you have relied on the object identifier as a return value. An attempt to use that value as a string will now result in a catchable fatal error.
    <?php
    class foo {}
    $foo = new foo;
    print     $foo;
    /* Catchable fatal error:  Object of class foo could
       not be converted to string in filename on line n */
    ?>
    Even with __toString(), objects cannot be used as array indices or keys. We may add built-in hash support for this at a later date, but as of PHP 5.2.x you will need to either provide your own hashing or use the new SPL function spl_object_hash(). Exceptions can not be thrown from __toString() methods.
    <?php
    class foo {
        public function     __toString() {
            throw new     Exception;
        }
    }

    try {
        print new     foo;
            /* Fatal error:  Method foo::__toString() must
           not throw an exception in filename on line n */
    } catch(Exception $e) {}
    ?>
  • Dropped abstract static class functions. Due to an oversight, PHP 5.0.x and 5.1.x allowed abstract static functions in classes. As of PHP 5.2.x, only interfaces can have them.
    <?php
    abstract class foo {
        abstract static function     bar();
            /* Strict Standards:  Static function foo::bar()
           should not be abstract in filename on line n */
    }
    ?>
  • Oracle extension requires at least Oracle 10 on Windows.
  • Added RFC2397 (data: stream) support. The introduction of the 'data' URL scheme has the potential to lead to a change of behavior under Windows. If you are working with a NTFS file system and making use of meta streams in your application, and if you just happen to be using a file with the name 'data:' that is accessed without any path information - it won't work any more. The fix is to use the 'file:' protocol when accessing it. See also » RFC 2397
    <?php
    /* when allow_url_include is OFF (default) */
    include "data:;base64,PD9waHAgcGhwaW5mbygpOz8+";
    /* Warning:  include(): URL file-access is disabled
       in the server configuration in filename on line n */
    ?>
  • Regression in glob() patterns In version 5.2.4 a security fix caused a regression for patterns of the form "/foo/*/bar/*". Since version 5.2.5 instead of raising a warning the glob() function will return FALSE when openbase_dir restrictions are violated.
What has changed in PHP 5.2.x
New Error Messages
Migrating from PHP 5.1.x to PHP 5.2.x


New Error Messages

Below are the new error messages that have not been discussed elsewhere in this document.

Przykład #1 In PHP Core

<?php
echo " ";
session_regenerate_id();
/*  Warning:  session_regenerate_id(): Cannot regenerate
    session id - headers already sent in filename on line n */

str_word_count("string", 4);
/* Warning:  str_word_count(): Invalid format value 4
   in filename on line n */

strripos("foo", "f", 4);
/* Notice:  strripos(): Offset is greater than the
   length of haystack string in filename on line n */

strrpos("foo", "f", 4);
/* Notice:  strrpos(): Offset is greater than the
   length of haystack string in filename on line n */

/* As of PHP 5.2.1, when allow_url_include is OFF (default) */
include "php://input";
/* Warning:  include(): URL file-access is disabled
   in the server configuration in filename on line n */
?>

Przykład #2 Object Oriented Code in PHP Core

<?php
interface foo {
}
class bar implements foo, foo {
}
/* Fatal error: Class bar cannot implement previously
   implemented interface foo in filename on line n */

class foo {
    public $bar;
    function __get($var)
    {
        return $this->bar;
    }
}

$foo = new foo;
$bar =& $foo->prop;
/* Notice: Indirect modification of overloaded property
   foo::$prop has no effect in filename on line n */

class foo implements iterator {
    public function current() {
    }
    public function next() {
    }
    public function key() {
    }
    public function valid() {
    }
    public function rewind() {
    }
}

$foo = new foo();
foreach($foo as &$ref) {}
/* Fatal error: An iterator cannot be used with foreach
   by reference in filename on line n */

class foo {
    private function __construct() {
    }
}
class bar extends foo {
    public function __construct() {
        parent::__construct();
        /* Fatal error:  Cannot call private
           foo::__construct() in filename on line n */
    }
}
new bar;

stream_filter_register("", "class");
/* Warning:  stream_filter_register(): Filter name
   cannot be empty in filename on line n */

stream_filter_register("filter", "");
/* Warning:  stream_filter_register(): Class name
   cannot be empty in filename on line n */
?>

Przykład #3 In the bzip2 Extension

<?php
bzopen("", "w");
/* Warning:  bzopen(): filename cannot be empty
   in filename on line n */

bzopen("foo", "a");
/* Warning:  bzopen(): 'a' is not a valid mode for
   bzopen(). Only 'w' and 'r' are supported in
   filename on line n */

$fp = fopen("foo", "w");
bzopen($fp, "r");
/* Warning:  bzopen(): cannot read from a stream
   opened in write only mode in filename on line n */
?>

Przykład #4 In the datetime Extension

<?php
strtotime("today", "now");
/* Warning:  strtotime() expects parameter 2 to be
   long, string given in filename on line n */

/* As of PHP 5.2.1 */
new DateTime(new stdclass);
/* Fatal error: Uncaught exception 'Exception' with
   message 'DateTime::__construct() expects parameter
   1 to be string, object given' in filename:n */
?>

Przykład #5 In the dBase Extension

<?php
dbase_open("foo", -1);
/* Warning: Invalid access mode -1 in filename on line n */

/* As of PHP 5.2.1 */
dbase_open("foo", null);
/* Warning: The filename cannot be empty in filename on line n */
?>

Przykład #6 In the mcrypt Extension

<?php
$key = "this is a secret key";
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td),
                        MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, "");
/* Warning: mcrypt_generic(): An empty string was
   passed in filename on line n */
?>

Przykład #7 In the oci8 Extension

<?php
oci_connect("user", "pass", "db", "bogus_charset");
/* Warning: Invalid character set name:
   bogus_charset in filename on line n */

$oci = oci_connect("user", "pass", "db");
oci_password_change($oci, "", "old", "new");
/* Warning: username cannot be empty in filename
   on line n */

oci_password_change($oci, "user", "", "new");
/* Warning: old password cannot be empty in filename
   on line n */

oci_password_change($oci, "user", "old", "");
/* Warning: new password cannot be empty in filename
   on line n */
?>

Przykład #8 In the SPL Extension

<?php
$obj = new SplFileObject(__FILE__);
$obj->fgetcsv("foo");
/* Warning:  SplFileObject::fgetcsv(): delimiter must
   be a character in filename on line n */

$obj->fgetcsv(",", "foo");
/* Warning:  SplFileObject::fgetcsv(): enclosure must
   be a character in filename on line n */
?>

Przykład #9 In the Semaphore (sysvmsg) extension

<?php
/* Warning:  maximum size of the message has to be
   greater then zero in filename on line n */
?>

Przykład #10 A 5.2.1+ Zip Example

<?php
$obj = new ZipArchive();
$obj->open('archive.zip');
$obj->setCommentName('', 'comment');
/* Notice:  ZipArchive::setCommentName(): Empty string
   as entry name in filename on line n */

/* As of PHP 5.2.1 */
$obj->getCommentName('');
/* Notice:  ZipArchive::getCommentName(): Empty string
   as entry name in filename on line n */
?>

Backward Incompatible Changes
Changes in PHP datetime support
Migrating from PHP 5.1.x to PHP 5.2.x


Changes in PHP datetime support

Since PHP 5.1.0, there has been an extension named date in the PHP core. This is the new implementation of PHP's datetime support. Although it will attempt to guess your system's timezone setting, you should set the timezone manually. You can do this in any of three ways:

  • in your php.ini using the date.timezone INI directive
  • on your system using the TZ environmental variable
  • from your script using the convenience function date_default_timezone_set()

All supported timezones are listed in the PHP Manual.

With the advent of PHP 5.2.x, there are object representations of the date and timezone, named DateTime and DateTimeZone respectively. The methods map to existing procedural date functions.

New Error Messages
New Parameters
Migrating from PHP 5.1.x to PHP 5.2.x


New Parameters

Some functions were given new, optional, parameters in PHP 5.2.x:

PHP Core:

  • htmlentities() - added double_encode in PHP 5.2.3.
  • htmlspecialchars() - added double_encode in PHP 5.2.3.
  • base64_decode() - added strict
  • setcookie() - added httponly
  • setrawcookie() - added httponly
  • session_set_cookie_params() - added httponly
  • memory_get_usage() - added real_usage
  • get_loaded_extensions() - added zend_extensions in PHP 5.2.4

curl:

  • curl_multi_info_read() - added msgs_in_queue

datetime

  • date() - added "u" (milliseconds) format character in PHP 5.2.2

imap:

  • imap_open() - added n_retries
  • imap_reopen() - added n_retries

mbstring:

  • mb_strrpos() - added offset
    Ostrzeżenie

    The offset parameter was put in the position the encoding parameter used to be. Backward compatibility has been provided by allowing encoding to be specified as the third parameter. Using this backward compatibility mode is not recommended because it will be removed in a future release of PHP.

ming:

  • SWFMovie::streamMP3() - added skip in PHP 5.2.1

openssl:

  • openssl_verify() - added signature_algo

pgsql:

  • pg_escape_bytea() - added connection
  • pg_escape_string() - added connection

simplexml:

  • SimpleXMLElement::__construct() - added is_prefix
  • SimpleXMLElement::attributes() - added is_prefix
  • SimpleXMLElement::children() - added is_prefix
  • simplexml_load_file() - added is_prefix
  • simplexml_load_string() - added is_prefix

spl:

  • array iterator_to_array(Traversable it [, bool use_keys = true]) - added use_keys in PHP 5.2.1

xmlreader:

  • XMLReader::open() - added encoding and options
  • XMLReader::XML() - added encoding and options

XMLWriter:

  • xmlwriter_write_element() - the content became optional in PHP 5.2.3
  • xmlwriter_write_element_ns() - the content became optional in PHP 5.2.3
Changes in PHP datetime support
New Functions
Migrating from PHP 5.1.x to PHP 5.2.x


New Functions

PHP 5.2.x introduced some new functions:

PHP Core:

  • array_fill_keys() - Create an array using the elements of the first parameter as keys, each initialized to val
  • error_get_last() - Get the last occurred error as associative array. Returns NULL if there hasn't been an error yet
  • image_type_to_extension() - Get file extension for image-type returned by getimagesize(), exif_read_data(), exif_thumbnail(), exif_imagetype()
  • memory_get_peak_usage() - Returns the peak allocated by PHP memory
  • sys_get_temp_dir() - Returns directory path used for temporary files. (Added in 5.2.1)
  • timezone_abbreviations_list() - Returns associative array containing DST, offset and the timezone name
  • timezone_identifiers_list() - Returns numerically indexed array with all timezone identifiers
  • timezone_name_from_abbr() - Returns the timezone name from abbreviation
  • stream_socket_shutdown() - Causes all or part of a full-duplex connection on the socket associated with stream to be shut down. As of PHP 5.2.1.

Image:

  • imagegrabscreen() - Grabs a screenshot of the whole screen. As of PHP 5.2.2.
  • imagegrabwindow() - Captures a window. As of PHP 5.2.2.

libXML:

  • libxml_disable_entity_loader() - Disable the ability to load external entities. As of PHP 5.2.11.

mbstring:

  • mb_stripos() - Finds position of first occurrence of a string within another, case insensitive
  • mb_stristr() - Finds first occurrence of a string within another, case insensitive
  • mb_strrchr() - Finds the last occurrence of a character in a string within another
  • mb_strrichr() - Finds the last occurrence of a character in a string within another, case insensitive
  • mb_strripos() - Finds position of last occurrence of a string within another, case insensitive
  • mb_strstr() - Finds first occurrence of a string within another

ming (As of PHP 5.2.1):

  • void ming_setSWFCompression(int num) - Sets output compression
  • void swfmovie::namedanchor(string name) - Creates anchor
  • void swfmovie::protect([string password]) - Protects

openssl:

  • openssl_csr_get_public_key() - Extracts public key from a CERT and prepares it for use
  • openssl_csr_get_subject() - Returns the subject of a CERT
  • openssl_pkey_get_details() - Returns an array with the key details (bits, pkey, type)

spl:

  • spl_object_hash() - Return hash id for given object
  • int iterator_apply(Traversable it, mixed function [, mixed params]) - Calls a function for every element in an iterator

pcre:

  • preg_last_error() - Returns the error code of the last regex execution

pgsql:

  • pg_field_table() - Returns the name of the table field belongs to, or table's oid if oid_only is TRUE

posix:

  • posix_initgroups() - Calculate the group access list for the user specified in name

gmp:

  • gmp_nextprime() - Finds next prime number

xmlwriter:

  • xmlwriter_full_end_element() - End current element - returns FALSE on error
  • xmlwriter_write_raw() - Write text - returns FALSE on error
  • xmlwriter_start_dtd_entity() - Create start DTD Entity - returns FALSE on error
  • xmlwriter_end_dtd_entity() - End current DTD Entity - returns FALSE on error
  • xmlwriter_write_dtd_entity() - Write full DTD Entity tag - returns FALSE on error
New Parameters
New Methods
Migrating from PHP 5.1.x to PHP 5.2.x


New Methods

New methods were introduced in 5.2.0:

dom:

  • DOMDocument::registerNodeClass() - Register extended class used to create base node type
  • DOMElement::setIDAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIDAttributeNode() - Declares the attribute specified by node to be of type ID
  • DOMElement::setIDAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID
  • DOMNode::C14N()([bool exclusive [, bool with_comments [, array xpath [, array ns_prefixes]]]]) - Canonicalize nodes to a string
  • DOMNode::C14NFile()(string uri [, bool exclusive [, bool with_comments [, array xpath [, array ns_prefixes]]]]) - Canonicalize nodes to a file
  • DOMNode::getNodePath()() - Gets an xpath for a node

soap:

  • SoapServer::setObject()(object obj) - Sets object which will handle SOAP requests

spl:

  • int ArrayObject::asort()(void) - Sort the entries by values
  • int ArrayObject::ksort()(void) - Sort the entries by key
  • int ArrayObject::natcasesort()(void) - Sort the entries by key using case insensitive "natural order" algorithm.
  • int ArrayObject::natsort()(void) - Sort the entries by values using "natural order" algorithm.
  • int ArrayObject::uasort()(callback cmp_function) - Sort the entries by values using a user defined function
  • int ArrayObject::uksort()(callback cmp_function) - Sort the entries by key using a user defined function.
  • ArrayIterator AppendIterator::getArrayIterator()() - Get access to inner ArrayIterator
  • int AppendIterator::getIteratorIndex()() - Get index of iterator
  • bool CachingIterator::getCache()() - Return the cache
  • int CachingIterator::getFlags()() - Return the internal flags
  • bool CachingIterator::offsetExists()(mixed index) - Returns TRUE if the requested index exists
  • string CachingIterator::offsetGet()(mixed index) - Return the internal cache if used
  • void CachingIterator::offsetSet()(mixed index, mixed newval) - Set given index in cache
  • void CachingIterator::offsetUnset()(mixed index) - Unset given index in cache
  • void CachingIterator::setFlags()() - Set the internal flags
  • array("delimiter" =>, "enclosure" =>) SplFileObject::getCsvControl()(void) - Get the delimiter and enclosure character used in fgetcsv()
  • void SplFileObject::setCsvControl()([string delimiter = ',' [, string enclosure = '"']]) - Set the delimiter and enclosure character used in fgetcsv()

Tidy

  • tidyNode tidyNode::getParent()() - Returns the parent node of the current node (Added in PHP 5.2.2)

XMLReader

  • boolean XMLReader::setSchema() - Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first XMLReader::read()

zip:

  • ZipArchive::addEmptyDir()() - Creates an empty directory in the archive
New Functions
Removed Extensions
Migrating from PHP 5.1.x to PHP 5.2.x


Removed Extensions

These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package version of these extensions will be created according to user demand.

  • filePro
  • Hyperwave API
New Methods
New Extensions
Migrating from PHP 5.1.x to PHP 5.2.x


New Extensions

The following are new extensions added (by default) as of PHP 5.2.0:

  • Filter - validates and filters data, and is designed for use with insecure data such as user input. This extension is enabled by default; the default mode RAW does not impact input data in any way.
  • JSON - implements the JavaScript Object Notation (JSON) data interchange format. This extension is enabled by default.
  • Zip - enables you to transparently read or write ZIP compressed archives and the files inside them.
Removed Extensions
New Classes
Migrating from PHP 5.1.x to PHP 5.2.x


New Classes

The following classes were introduced in PHP 5.2.0:

  • DateTime
  • DateTimeZone
  • RegexIterator - extends FilterIterator; implements Iterator, Traversable, OuterIterator Constants:
    • RegexIterator::ALL_MATCHES
    • RegexIterator::GET_MATCH
    • RegexIterator::MATCH
    • RegexIterator::REPLACE
    • RegexIterator::SPLIT
    • RegexIterator::USE_KEY
    Properties:
    • public replacement
    Methods:
    • RegexIterator::__construct(Iterator it, string regex [, int mode [, int flags [, int preg_flags]]]) - Create an RegexIterator from another iterator and a regular expression
    • bool RegexIterator::accept() - Match (string)current() against regular expression
    • bool RegexIterator::getFlags() - Returns current operation flags
    • bool RegexIterator::getMode() - Returns current operation mode
    • bool RegexIterator::getPregFlags() - Returns current PREG flags (if in use or NULL)
    • bool RegexIterator::setFlags(int new_flags) - Set operation flags
    • bool RegexIterator::setMode(int new_mode) - Set new operation mode
    • bool RegexIterator::setPregFlags(int new_flags) - Set PREG flags
  • RecursiveRegexIterator Constants:
    • RecursiveRegexIterator::ALL_MATCHES
    • RecursiveRegexIterator::GET_MATCH
    • RecursiveRegexIterator::MATCH
    • RecursiveRegexIterator::REPLACE
    • RecursiveRegexIterator::SPLIT
    • RecursiveRegexIterator::USE_KEY
    Methods:
    • RecursiveRegexIterator::__construct(RecursiveIterator it, string regex [, int mode [, int flags [, int preg_flags]]]) - Create an RecursiveRegexIterator from another recursive iterator and a regular expression
    • RecursiveRegexIterator RecursiveRegexIterator::getChildren() - Return the inner iterator's children contained in a RecursiveRegexIterator
    • bool RecursiveRegexIterator::hasChildren() - Check whether the inner iterator's current element has children
New Extensions
New Global Constants
Migrating from PHP 5.1.x to PHP 5.2.x


New Global Constants

PHP Core:

  • M_EULER
  • M_LNPI
  • M_SQRT3
  • M_SQRTPI
  • PATHINFO_FILENAME
  • PREG_BACKTRACK_LIMIT_ERROR
  • PREG_BAD_UTF8_ERROR
  • PREG_INTERNAL_ERROR
  • PREG_NO_ERROR
  • PREG_RECURSION_LIMIT_ERROR
  • UPLOAD_ERR_EXTENSION
  • STREAM_SHUT_RD
  • STREAM_SHUT_WR
  • STREAM_SHUT_RDWR

curl:

  • CURLE_FILESIZE_EXCEEDED
  • CURLE_FTP_SSL_FAILED
  • CURLE_LDAP_INVALID_URL
  • CURLFTPAUTH_DEFAULT
  • CURLFTPAUTH_SSL
  • CURLFTPAUTH_TLS
  • CURLFTPSSL_ALL
  • CURLFTPSSL_CONTROL
  • CURLFTPSSL_NONE
  • CURLFTPSSL_TRY
  • CURLOPT_FTP_SSL
  • CURLOPT_FTPSSLAUTH
  • CURLOPT_TCP_NODELAY Added in PHP 5.2.1.
  • CURLOPT_TIMEOUT_MS Added in PHP 5.2.3
  • CURLOPT_CONNECTTIMEOUT_MS Added in PHP 5.2.3

GMP:

  • GMP_VERSION Added in PHP 5.2.2.

ming:

  • SWFTEXTFIELD_USEFONT
  • SWFTEXTFIELD_AUTOSIZE
  • SWF_SOUND_NOT_COMPRESSED
  • SWF_SOUND_ADPCM_COMPRESSED
  • SWF_SOUND_MP3_COMPRESSED
  • SWF_SOUND_NOT_COMPRESSED_LE
  • SWF_SOUND_NELLY_COMPRESSED
  • SWF_SOUND_5KHZ
  • SWF_SOUND_11KHZ
  • SWF_SOUND_22KHZ
  • SWF_SOUND_44KHZ
  • SWF_SOUND_8BITS
  • SWF_SOUND_16BITS
  • SWF_SOUND_MONO
  • SWF_SOUND_STEREO

openssl:

  • OPENSSL_VERSION_NUMBER
  • OPENSSL_VERSION_TEXT

snmp:

  • SNMP_OID_OUTPUT_FULL
  • SNMP_OID_OUTPUT_NUMERIC

Semaphore:

  • MSG_EAGAIN
  • MSG_ENOMSG
New Classes
New Class Constants
Migrating from PHP 5.1.x to PHP 5.2.x


New Class Constants

pdo:

  • PDO::ATTR_DEFAULT_FETCH_MODE
  • PDO::FETCH_PROPS_LATE
  • PDO::FETCH_KEY_PAIR Fetches a 2 column result set into an associated array. (Added in PHP 5.2.3)

spl:

  • CachingIterator::FULL_CACHE
  • CachingIterator::TOSTRING_USE_INNER
  • SplFileObject::READ_AHEAD
  • SplFileObject::READ_CSV
  • SplFileObject::SKIP_EMPTY
New Global Constants
New INI Configuration Directives
Migrating from PHP 5.1.x to PHP 5.2.x


New INI Configuration Directives

New php.ini directives introduced in PHP 5.2.0:

  • allow_url_include This useful option makes it possible to differentiate between standard file operations on remote files, and the inclusion of remote files. While the former is usually desirable, the latter can be a security risk if used naively. Starting with PHP 5.2.0, you can allow remote file operations while disallowing the inclusion of remote files in local scripts. In fact, this is the default configuration.
  • pcre.backtrack_limit PCRE's backtracking limit.
  • pcre.recursion_limit PCRE's recursion limit. Please note that if you set this value to a high number you may consume all the available process stack and eventually crash PHP (due to reaching the stack size limit imposed by the Operating System).
  • session.cookie_httponly Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).

New directives in PHP 5.2.2:

  • max_input_nesting_level Limits how deep input variables can be nested, default is 64.
New Class Constants
Error Reporting
Migrating from PHP 5.1.x to PHP 5.2.x


Error Reporting

Some of the existing E_ERROR conditions have been converted to something that can be caught with a user-defined error handler. If an E_RECOVERABLE_ERROR is not handled, it will behave in the same way as E_ERROR behaves in all versions of PHP. Errors of this type are logged as Catchable fatal error.

This change means that the value of the E_ALL error_reporting constant is now 6143, where the previous value was 2047. Because PHP constants have no meaning outside of PHP, in some cases the integer value is used instead so these will need to be adjusted. So for example by setting the error_reporting mode from either the httpd.conf or the .htaccess files, the value has to be changed accordingly. The same applies when the numeric values are used rather than the constants in PHP scripts.

As a side-effect of a change made to prevent duplicate error messages when track_errors is On, it is now necessary to return FALSE from user defined error handlers in order to populate $php_errormsg. This provides a fine-grain control over the levels of messages stored.

New INI Configuration Directives
Other Enhancements
Migrating from PHP 5.1.x to PHP 5.2.x


Other Enhancements

  • Improved memory manager and increased default memory limit. The new memory manager allocates less memory and works faster than the previous incarnation. It allocates memory from the system in large blocks, and then manages the heap by itself. The memory_limit value in php.ini is checked, not for each emalloc() call (as before), but for actual blocks requested from the system. This means that memory_limit is far more accurate than it used to be, since the old memory manager didn't calculate all the memory overhead used by the malloc library. Thanks to this new-found accuracy memory usage may appear to have increased, although actually it has not. To accommodate this apparent increase, the default memory_limit setting was also increased - from 8 to 16 megabytes.
  • Added support for constructors in interfaces to force constructor signature checks in implementations. Starting with PHP 5.2.0, interfaces can have constructors. However, if you choose to declare a constructor in an interface, each class implementing that interface MUST include a constructor with a signature matching that of the base interface constructor. By 'signature' we mean the parameter and return type definitions, including any type hints and including whether the data is passed by reference or by value.
Error Reporting
Migrating from PHP 5.0.x to PHP 5.1.x
Migrating from PHP 5.1.x to PHP 5.2.x


Migrating from PHP 5.0.x to PHP 5.1.x

Spis treści

  • Key PHP 5.1.x features
  • Changes in reference handling
  • Reading []
  • Integer values in function parameters
  • Class and object changes
  • Extensions
  • Date/time support
  • Changes in database support
  • Checking for E_STRICT

Zobacz także instrukcję migracji na nowsze wersje PHP 5.0.x, 5.2.x and 5.3.x.

Other Enhancements
Key PHP 5.1.x features
Dodatki


Key PHP 5.1.x features

Some of the key features of PHP 5.1.x include:

  • A complete rewrite of date handling code, with improved timezone support.

  • Significant performance improvements compared to PHP 5.0.X.

  • PDO extension is now enabled by default.

  • Over 30 new functions in various extensions and built-in functionality.

  • Over 400 various bug fixes.

Migrating from PHP 5.0.x to PHP 5.1.x
Changes in reference handling
Migrating from PHP 5.0.x to PHP 5.1.x


Changes in reference handling

  • Overview

  • Code that worked under PHP 4.3.x, but now fails

  • Code that worked under PHP 4.3.x, but now throws an error

  • Code that failed under PHP 4.3.x, but now works

  • Code that should have worked under PHP 5.0.x

  • Warnings that came and went

Overview

From the PHP script writer's point of view, the change most likely to impact legacy code is in the way that references are handled in all PHP versions post-dating the PHP 4.4.0 release.

Until and including PHP 4.3, it was possible to send, assign or return variables by reference that should really be returned by value, such as a constant, a temporary value (e.g. the result of an expression), or the result of a function that had itself been returned by value, as here:

<?php
$foo = "123";

function return_value() {
    global $foo;
    return $foo;
}

$bar = &return_value();
?>

Although this code would usually work as expected under PHP 4.3, in the general case the result is undefined. The Zend Engine could not act correctly on these values as references. This bug could and did lead to various hard-to-reproduce memory corruption problems, particularly where the code base was large.

In PHP 4.4.0, PHP 5.0.4 and all subsequent PHP releases, the Engine was fixed to 'know' when the reference operation is being used on a value that should not be referenced. The actual value is now used in such cases, and a warning is emitted. The warning takes the form of an E_NOTICE in PHP 4.4.0 and up, and E_STRICT in PHP 5.0.4 and up.

Code that could potentially produce memory corruption can no longer do so. However, some legacy code might work differently as a result.

Code that worked under PHP 4.3, but now fails

<?php
function func(&$arraykey) {
    return $arraykey; // function returns by value!
}

$array = array('a', 'b', 'c');
foreach (array_keys($array) as $key) {
    $y = &func($array[$key]);
    $z[] =& $y;
}

var_dump($z);
?>
<

Running the above script under any version of PHP that pre-dates the reference fix would produce this output:

array(3) {
  [0]=>
  &string(1) "a"
  [1]=>
  &string(1) "b"
  [2]=>
  &string(1) "c"
}

Following the reference fix, the same code would result in:

array(3) {
  [0]=>
  &string(1) "c"
  [1]=>
  &string(1) "c"
  [2]=>
  &string(1) "c"
}

This is because, following the changes, func() assigns by value. The value of $y is re-assigned, and reference-binding is preserved from $z. Prior to the fix, the value was assigned by reference, leading $y to be re-bound on each assignment. The attempt to bind to a temporary value by reference was the cause of the memory corruption.

Such code can be made to work identically in both the pre-fix and the post-fix PHP versions. The signature of func() can be altered to return by reference, or the reference assignment can be removed from the result of func().

<?php
function func() {
    return 'function return';
}

$x = 'original value';
$y =& $x;
$y = &func();
echo $x;
?>

In PHP 4.3 $x would be 'original value', whereas after the changes it would be 'function return' - remember that where the function does not return by reference, the reference assignment is converted to a regular assignment. Again, this can be brought to a common base, either by forcing func() to return by reference or by eliminating the by-reference assignment.

Code that worked under PHP 4.3.x, but now throws an error

<?php
class Foo {

    function getThis() {
        return $this;
    }

    function destroyThis() {
        $baz =& $this->getThis();
    }
}

$bar = new Foo();
$bar->destroyThis();
var_dump($bar);
?>

In PHP 5.0.3, $bar evaluated to NULL instead of returning an object. That happened because getThis() returns by value, but the value here is assigned by reference. Although it now works in the expected way, this is actually invalid code which will throw an E_NOTICE under PHP 4.4 or an E_STRICT under PHP 5.0.4 and up.

Code that failed under PHP 4.3.x, but now works

<?php
function &f() {
    $x = "foo";
    var_dump($x);
    print "$x\n";
    return($a);
}

for ($i = 0; $i < 3; $i++) {
    $h = &f();
}
?>

In PHP 4.3 the third call to var_dump() produces NULL, due to the memory corruption caused by returning an uninitialized value by reference. This is valid code in PHP 5.0.4 and up, but threw errors in earlier releases of PHP.

<?php
$arr = array('a1' => array('alfa' => 'ok'));
$arr =& $arr['a1'];
echo '-'.$arr['alfa']."-\n";
?>

Until PHP 5.0.5, it wasn't possible to assign an array element by reference in this way. It now is.

Code that should have worked under PHP 5.0.x

There are a couple of instances of bugs reported under PHP 5.0 prior to the reference fixes which now 'work'. However, in both cases errors are thrown by PHP 5.1.x, because the code was invalid in the first place. Returning values by reference using self:: now works in the general case but throws an E_STRICT warning, and although your mileage may vary when assigning by reference to an overloaded object, you will still see an E_ERROR when you try it, even where the assignment itself appears to work.

Warnings that came and went

Nested calls to functions returning by reference are valid code under both PHP 4.3.x and PHP 5.1.x, but threw an unwarranted E_NOTICE or E_STRICT under the intervening PHP releases.

<?php
function & foo() {
    $var = 'ok';
    return $var;
}

function & bar() {
    return foo();
}

$a =& bar();
echo "$a\n";
?>
Key PHP 5.1.x features
Reading []
Migrating from PHP 5.0.x to PHP 5.1.x


Reading []

<?php
class XmlTest {

    function test_ref(&$test) {
        $test = "ok";
    }

    function test($test) { }

    function run() {
        $ar = array();
        $this->test_ref($ar[]);
        var_dump($ar);
        $this->test($ar[]);
    }
}

$o = new XmlTest();
$o->run();
?>

This should always have thrown a fatal E_ERROR, because [] cannot be used for reading in PHP. It is invalid code in PHP 4.4.2 and PHP 5.0.5 upward.

Changes in reference handling
Integer values in function parameters
Migrating from PHP 5.0.x to PHP 5.1.x


Integer values in function parameters

With the advent of PHP 5.0.x, a new parameter parsing API was introduced which is used by a large number of PHP functions. In all versions of PHP between 5.0.x and 5.1.x, the handling of integer values was very strict and would reject non-well formed numeric values when a PHP function expected an integer. These checks have now been relaxed to support non-well formed numeric strings such as " 123" and "123 ", and will no longer fail as they did under PHP 5.0.x. However, to promote code safety and input validation, PHP functions will now emit an E_NOTICE when such strings are passed as integers.

Reading []
Class and object changes
Migrating from PHP 5.0.x to PHP 5.1.x


Class and object changes

  • instanceof, is_a(), is_subclass_of() and catch

  • Abstract private methods

  • Access modifiers in interfaces

  • Changes in inheritance rules

  • Class constants

instanceof, is_a(), is_subclass_of() and catch

In PHP 5.0, is_a() was deprecated and replaced by the instanceof operator. There were some issues with the initial implementation of instanceof, which relied on __autoload() to search for missing classes. If the class was not present, instanceof would throw a fatal E_ERROR due to the failure of __autoload() to discover that class. The same behaviour occurred in the catch operator and the is_subclass_of() function, for the same reason.

None of these functions or operators call __autoload() in PHP 5.1.x, and the class_exists() workarounds used in code written for PHP 5.0.x, while not problematic in any way, are no longer necessary.

Abstract private methods

Abstract private methods were supported between PHP 5.0.0 and PHP 5.0.4, but were then disallowed on the grounds that the behaviours of private and abstract are mutually exclusive.

Access modifiers in interfaces

Under PHP 5.0, function declarations in interfaces were treated in exactly the same way as function declarations in classes. This has not been the case since October 2004, at which point only the public access modifier was allowed in interface function declarations. Since April 2005 - which pre-dates the PHP 5.0b1 release - the static modifier has also been allowed. However, the protected and private modifiers will now throw an E_ERROR, as will abstract. Note that this change should not affect your existing code, as none of these modifiers makes sense in the context of interfaces anyway.

Changes in inheritance rules

Under PHP 5.0, it was possible to have a function declaration in a derived class that did not match the declaration of the same function in the base class, e.g.

This code will cause an E_STRICT error to be emitted under PHP 5.1.x.

<?php
class Base {
    function &return_by_ref() {
        $r = 1;
        return $r;
    }
}

class Derived extends Base {
    function return_by_ref() {
        return 1;
    }
}
?>

Class constants

Under PHP 5.0.x, the following code was valid:

Under PHP 5.1.x, redefinition of a class constant will throw a fatal E_ERROR.

<?php
class test {
    const foobar = 'foo';
    const foobar = 'bar';
}

?>
Integer values in function parameters
Extensions
Migrating from PHP 5.0.x to PHP 5.1.x


Extensions

  • Extensions that are gone from the PHP core

  • Class constants in new PHP 5.1.x extensions

Extensions that are gone from the PHP core

One of the first things you're likely to notice when you download PHP 5.1.x is that several of the older extensions have disappeared. Those extensions that are still actively maintained are available in the PHP Extension Community Library (PECL), at » http://pecl.php.net/.

Removed extensions
Extension | Alternative/Status
ext/cpdf | pecl/pdflib
ext/dbx | pecl/dbx
ext/dio | pecl/dio
ext/fam | Not actively maintained
ext/ingres_ii | pecl/ingres
ext/ircg | Not actively maintained
ext/mcve | pecl/mcve
ext/mnogosearch | Not actively maintained
ext/oracle | ext/oci8 or ext/pdo_oci
ext/ovrimos | Not actively maintained
ext/pfpro | Not actively maintained
ext/w32api | » pecl/ffi
ext/yp | Not actively maintained
ext/activescript | » pecl/activescript

Modules in PECL that are not actively maintained (i.e. have not been supported for some time, have no active maintainer working on them currently, and do not have any PECL package releases), are still available in SVN at » http://svn.php.net/viewvc/pecl. However, unreleased PHP modules are by their nature unsupported, and your mileage may vary when attempting to install or use them.

Class constants in new PHP 5.1.x extensions

The Zend Engine 2.1 API allows extension developers to declare class constants in object oriented extensions. New extensions written for PHP 5.1.x, including SPL, PDO, XMLReader and date, have their constants in the format PDO::CLASS_CONSTANT rather than in the C format PDO_CLASS_CONSTANT in order to minimise pollution of the global namespace in PHP.

Class and object changes
Date/time support
Migrating from PHP 5.0.x to PHP 5.1.x


Date/time support

Date/time support has been fully rewritten in PHP 5.1.x, and no longer uses the system settings to 'know' the timezone in operation. It will instead utilize, in the following order:

  • The timezone set using the date_default_timezone_set() function (if any)

  • The TZ environment variable (if non empty)

  • "magical" guess (if the operating system supports it)

  • If none of the above options succeeds, UTC

To ensure accuracy (and avoid an E_STRICT warning), you will need to define your timezone in your php.ini using the following format:

date.timezone = Europe/London

The supported timezones are listed, in this format, in the timezones appendix.

Also note that strtotime() now returns FALSE on failure, instead of -1.

Extensions
Changes in database support
Migrating from PHP 5.0.x to PHP 5.1.x


Changes in database support

  • PDO overview

  • Changes in MySQL support

  • Changes in SQLite support

PDO overview

PHP Data Objects (PDO) were introduced as a PECL extension under PHP 5.0, and became part of the core PHP distribution in PHP 5.1.x. The PDO extension provides a consistent interface for database access, and is used alongside database-specific PDO drivers. Each driver may also have database-specific functions of its own, but basic data access functionality such as issuing queries and fetching data is covered by PDO functions, using the driver named in PDO::__construct().

Note that the PDO extension, and its drivers, are intended to be built as shared extensions. This will enable straightforward driver upgrades from PECL, without forcing you to rebuild all of PHP.

At the point of the PHP 5.1.x release, PDO is more than ready for widespread testing and could be adopted in most situations. However, it is important to understand that PDO and its drivers are comparatively young and may be missing certain database-specific features; evaluate PDO carefully before you use it in new projects.

Legacy code will generally rely on the pre-existing database extensions, which are still maintained.

Changes in MySQL support

In PHP 4, MySQL 3 support was built-in. With the release of PHP 5.0 there were two MySQL extensions, named 'mysql' and 'mysqli', which were designed to support MySQL < 4.1 and MySQL 4.1 and up, respectively. With the introduction of PDO, which provides a very fast interface to all the database APIs supported by PHP, the PDO_MYSQL driver can support any of the current versions (MySQL 3, 4 or 5) in PHP code written for PDO, depending on the MySQL library version used during compilation. The older MySQL extensions remain in place for reasons of back compatibility, but are not enabled by default.

Changes in SQLite support

In PHP 5.0.x, SQLite 2 support was provided by the built-in sqlite extension, which was also available as a PECL extension in PHP 4.3 and PHP 4.4. With the introduction of PDO, the sqlite extension doubles up to act as a 'sqlite2' driver for PDO; it is due to this that the sqlite extension in PHP 5.1.x has a dependency upon the PDO extension.

PHP 5.1.x ships with a number of alternative interfaces to sqlite:

The sqlite extension provides the "classic" sqlite procedural/OO API that you may have used in prior versions of PHP. It also provides the PDO 'sqlite2' driver, which allows you to access legacy SQLite 2 databases using the PDO API.

PDO_SQLITE provides the 'sqlite' version 3 driver. SQLite version 3 is vastly superior to SQLite version 2, but the file formats of the two versions are not compatible.

If your SQLite-based project is already written and working against earlier PHP versions, then you can continue to use ext/sqlite without problems, but will need to explicitly enable both PDO and sqlite. New projects should use PDO and the 'sqlite' (version 3) driver, as this is faster than SQLite 2, has improved locking concurrency, and supports both prepared statements and binary columns natively.

You must enable PDO to use the SQLite extension. If you want to build the PDO extension as a shared extension, then the SQLite extension must also be built shared. The same holds true for any extension that provides a PDO driver

Date/time support
Checking for E_STRICT
Migrating from PHP 5.0.x to PHP 5.1.x


Checking for E_STRICT

If you only have a single script to check, you can pick up E_STRICT errors using PHP's commandline lint facility:

php -d error_reporting=4095 -l script_to_check.php

For larger projects, the shell script below will achieve the same task:

#!/bin/sh

directory=$1

shift

# These extensions are checked
extensions="php inc"

check_file ()
{
  echo -ne "Doing PHP syntax check on $1 ..."

  # Options:
  ERRORS=`/www/php/bin/php -d display_errors=1 -d html_errors=0 -d error_prepend_string=" " -d error_append_string=" " -d error_reporting=4095 -l $1 | grep -v "No syntax errors detected"`

  if test -z "$ERRORS"; then
    echo -ne "OK."
  else
    echo -e "Errors found!\n$ERRORS"
  fi

  echo
}

# loop over remaining file args
for FILE in "$@" ; do
  for ext in $extensions; do
     if echo $FILE | grep "\.$ext$" > /dev/null; then
       if test -f $FILE; then
         check_file "$FILE"
       fi
     fi
  done
done
Changes in database support
Migrating from PHP 4 to PHP 5.0.x
Migrating from PHP 5.0.x to PHP 5.1.x


Migrating from PHP 4 to PHP 5.0.x

Spis treści

  • What has changed in PHP 5.0.x
  • Backward Incompatible Changes
  • CLI and CGI
  • Migrating Configuration Files
  • New Functions
  • New Directives
  • Databases
  • New Object Model
  • Error Reporting

Zobacz także instrukcję migracji na nowsze wersje PHP 5.1.x, 5.2.x and 5.3.x.

Checking for E_STRICT
What has changed in PHP 5.0.x
Dodatki


What has changed in PHP 5.0.x

PHP 5 and the integrated Zend Engine 2 have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 4 to 5 should be very easy. Most existing PHP 4 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments.

Migrating from PHP 4 to PHP 5.0.x
Backward Incompatible Changes
Migrating from PHP 4 to PHP 5.0.x


Backward Incompatible Changes

Although most existing PHP 4 code should work without changes, you should pay attention to the following backward incompatible changes:

  • There are some new reserved keywords.
  • strrpos() and strripos() now use the entire string as a needle.
  • Illegal use of string offsets causes E_ERROR instead of E_WARNING. An example illegal use is: $str = 'abc'; unset($str[0]);.
  • array_merge() was changed to accept only arrays. If a non-array variable is passed, a E_WARNING will be thrown for every such parameter. Be careful because your code may start emitting E_WARNING out of the blue.
  • PATH_TRANSLATED server variable is no longer set implicitly under Apache2 SAPI in contrast to the situation in PHP 4, where it is set to the same value as the SCRIPT_FILENAME server variable when it is not populated by Apache. This change was made to comply with the » CGI/1.1 specification. Please refer to » bug #23610 for further information, and see also the $_SERVER['PATH_TRANSLATED'] description in the manual. This issue also affects PHP versions >= 4.3.2.
  • The T_ML_COMMENT constant is no longer defined by the Tokenizer extension. If error_reporting is set to E_ALL, PHP will generate a notice. Although the T_ML_COMMENT was never used at all, it was defined in PHP 4. In both PHP 4 and PHP 5 // and /* */ are resolved as the T_COMMENT constant. However the PHPDoc style comments /** */, which starting PHP 5 are parsed by PHP, are recognized as T_DOC_COMMENT.
  • $_SERVER should be populated with argc and argv if variables_order includes "S". If you have specifically configured your system to not create $_SERVER, then of course it shouldn't be there. The change was to always make argc and argv available in the CLI version regardless of the variables_order setting. As in, the CLI version will now always populate the global $argc and $argv variables.
  • An object with no properties is no longer considered "empty".
  • In some cases classes must be declared before use. It only happens if some of the new features of PHP 5 (such as interfaces) are used. Otherwise the behaviour is the old.
  • get_class(), get_parent_class() and get_class_methods() now return the name of the classes/methods as they were declared (case-sensitive) which may lead to problems in older scripts that rely on the previous behaviour (the class/method name was always returned lowercased). A possible solution is to search for those functions in all your scripts and use strtolower(). This case sensitivity change also applies to the magical predefined constants __CLASS__, __METHOD__, and __FUNCTION__. The values are returned exactly as they're declared (case-sensitive).
  • ip2long() now returns FALSE when an invalid IP address is passed as argument to the function, and no longer -1.
  • 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 it. It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.
  • include_once() and require_once() first normalize the path of included file on Windows so that including A.php and a.php include the file just once.
  • Passing an array to a function by value no longer resets the array's internal pointer for array accesses made within the function. In other words, in PHP 4 when you passed an array to a function, its internal pointer inside the function would be reset, while in PHP 5, when you pass an array to a function, its array pointer within the function will be wherever it was when the array was passed to the function.

Przykład #1 strrpos() and strripos() now use the entire string as a needle

<?php
var_dump(strrpos('ABCDEF','DEF')); //int(3)

var_dump(strrpos('ABCDEF','DAF')); //bool(false)
?>

Przykład #2 An object with no properties is no longer considered "empty"

<?php
class test { }
$t = new test();

var_dump(empty($t)); // echo bool(false)

if ($t) {
    // Will be executed
}
?>

Przykład #3 In some cases classes must be declared before used

<?php

//works with no errors:
$a = new a();
class a {
}

//throws an error:
$a = new b();

interface c{
}
class b implements c {
}

?>

What has changed in PHP 5.0.x
CLI and CGI
Migrating from PHP 4 to PHP 5.0.x


CLI and CGI

In PHP 5 there were some changes in CLI and CGI filenames. In PHP 5, the CGI version was renamed to php-cgi.exe (previously php.exe) and the CLI version now sits in the main directory (previously cli/php.exe).

In PHP 5 it was also introduced a new mode: php-win.exe. This is equal to the CLI version, except that php-win doesn't output anything and thus provides no console (no "dos box" appears on the screen). This behavior is similar to php-gtk.

In PHP 5, the CLI version will always populate the global $argv and $argc variables regardless of any php.ini directive setting. Even having register_argc_argv set to off will have no affect in CLI.

See also the command line reference.

Backward Incompatible Changes
Migrating Configuration Files
Migrating from PHP 4 to PHP 5.0.x


Migrating Configuration Files

Since the ISAPI modules changed their names, from php4xxx to php5xxx, you need to make some changes in the configuration files. There were also changes in the CLI and CGI filenames. Please refer to the corresponding section for more information.

Migrating the Apache configuration is extremely easy. See the example below to check the change you need to do:

Przykład #1 Migrating Apache configuration files for PHP 5

# change this line:
LoadModule php4_module /php/sapi/php4apache2.dll

# with this one:
LoadModule php5_module /php/php5apache2.dll

If your web server is running PHP in CGI mode, you should note that the CGI version has changed its name from php.exe to php-cgi.exe. In Apache, you should do something like this:

Przykład #2 Migrating Apache configuration files for PHP 5, CGI mode

# change this line:
Action application/x-httpd-php "/php/php.exe"

# with this one:
Action application/x-httpd-php "/php/php-cgi.exe"

In other web servers you need to change either the CGI or the ISAPI module filenames.

CLI and CGI
New Functions
Migrating from PHP 4 to PHP 5.0.x


New Functions

In PHP 5 there are some new functions. Here is the list of them:

Arrays:

  • array_combine() - Creates an array by using one array for keys and another for its values
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_udiff_assoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also
  • array_walk_recursive() - Apply a user function recursively to every member of an array
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check. The data is compared by using a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check. Both the data and the indexes are compared by using separate callback functions
  • array_uintersect() - Computes the intersection of arrays. The data is compared by using a callback function

InterBase:

  • ibase_affected_rows() - Return the number of rows that were affected by the previous query
  • ibase_backup() - Initiates a backup task in the service manager and returns immediately
  • ibase_commit_ret() - Commit a transaction without closing it
  • ibase_db_info() - Request statistics about a database
  • ibase_drop_db() - Drops a database
  • ibase_errcode() - Return an error code
  • ibase_free_event_handler() - Cancels a registered event handler
  • ibase_gen_id() - Increments the named generator and returns its new value
  • ibase_maintain_db() - Execute a maintenance command on the database server
  • ibase_name_result() - Assigns a name to a result set
  • ibase_num_params() - Return the number of parameters in a prepared query
  • ibase_param_info() - Return information about a parameter in a prepared query
  • ibase_restore() - Initiates a restore task in the service manager and returns immediately
  • ibase_rollback_ret() - Rollback transaction and retain the transaction context
  • ibase_server_info() - Request statistics about a database server
  • ibase_service_attach() - Connect to the service manager
  • ibase_service_detach() - Disconnect from the service manager
  • ibase_set_event_handler() - Register a callback function to be called when events are posted
  • ibase_wait_event() - Wait for an event to be posted by the database

iconv:

  • iconv_mime_decode() - Decodes a MIME header field
  • iconv_mime_decode_headers() - Decodes multiple MIME header fields at once
  • iconv_mime_encode() - Composes a MIME header field
  • iconv_strlen() - Returns the character count of string
  • iconv_strpos() - Finds position of first occurrence of a needle within a haystack
  • iconv_strrpos() - Finds the last occurrence of a needle within a haystack
  • iconv_substr() - Cut out part of a string

Streams:

  • stream_copy_to_stream() - Copies data from one stream to another
  • stream_get_line() - Gets line from stream resource up to a given delimiter
  • stream_socket_accept() - Accept a connection on a socket created by stream_socket_server()
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_get_name() - Retrieve the name of the local or remote sockets
  • stream_socket_recvfrom() - Receives data from a socket, connected or not
  • stream_socket_sendto() - Sends a message to a socket, whether it is connected or not
  • stream_socket_server() - Create an Internet or Unix domain server socket

Date and time related:

  • idate() - Format a local time/date as integer
  • date_sunset() - Time of sunset for a given day and location
  • date_sunrise() - Time of sunrise for a given day and location
  • time_nanosleep() - Delay for a number of seconds and nanoseconds

Strings:

  • str_split() - Convert a string to an array
  • strpbrk() - Search a string for any of a set of characters
  • substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters

Other:

  • convert_uudecode() - decode a uuencoded string
  • convert_uuencode() - uuencode a string
  • curl_copy_handle() - Copy a cURL handle along with all of its preferences
  • dba_key_split() - Splits a key in string representation into array representation
  • dbase_get_header_info() - Get the header info of a dBase database
  • dbx_fetch_row() - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
  • fbsql_set_password() - Change the password for a given user
  • file_put_contents() - Write a string to a file
  • ftp_alloc() - Allocates space for a file to be uploaded
  • get_declared_interfaces() - Returns an array of all declared interfaces
  • get_headers() - Fetches all the headers sent by the server in response to a HTTP request
  • headers_list() - Returns a list of response headers sent (or ready to send)
  • http_build_query() - Generate URL-encoded query string
  • image_type_to_extension() - Get file extension for
image-type returned by getimagesize(),
exif_read_data(),
exif_thumbnail(),
exif_imagetype()
  • imagefilter() - Applies a filter to an image using custom arguments
  • imap_getacl() - Gets the ACL for a given mailbox
  • ldap_sasl_bind() - Bind to LDAP directory using SASL
  • mb_list_encodings() - Returns an array of all supported encodings
  • pcntl_getpriority() - Get the priority of any process
  • pcntl_wait() - Waits on or returns the status of a forked child as defined by the waitpid() system call
  • pg_version() - Returns an array with client, protocol and server version (when available)
  • php_check_syntax() - Check the syntax of the specified file
  • php_strip_whitespace() - Return source with stripped comments and whitespace
  • proc_nice() - Change the priority of the current process
  • pspell_config_data_dir() - Change location of language data files
  • pspell_config_dict_dir() - Change location of the main word list
  • setrawcookie() - Send a cookie without URL-encoding the value
  • scandir() - List files and directories inside the specified path
  • snmp_read_mib() - Reads and parses a MIB file into the active MIB tree
  • sqlite_fetch_column_types() - Return an array of column types from a particular table

Informacja:

The Tidy extension has also changed its API completely.

Migrating Configuration Files
New Directives
Migrating from PHP 4 to PHP 5.0.x


New Directives

There were some new php.ini directives introduced in PHP 5. Here is a list of them:

  • mail.force_extra_parameters - Force the addition of the specified parameters to be passed as extra parameters to the sendmail binary. These parameters will always replace the value of the 5th parameter to mail(), even in safe mode
  • register_long_arrays - allow/disallow PHP to register the deprecated long $HTTP_*_VARS
  • session.hash_function - select a hash function (MD5 or SHA-1)
  • session.hash_bits_per_character - define how many bits are stored in each character when converting the binary hash data to something readable (from 4 to 6)
  • zend.ze1_compatibility_mode - Enable compatibility mode with Zend Engine 1 (PHP 4)
New Functions
Databases
Migrating from PHP 4 to PHP 5.0.x


Databases

There were some changes in PHP 5 regarding databases (MySQL and SQLite).

In PHP 5 the MySQL client libraries are not bundled, because of license problems and some others. For more information, read the FAQ entry.

There is also a new extension, MySQLi (Improved MySQL), which is designed to work with MySQL 4.1 and above.

Since PHP 5, the SQLite extension is built-in PHP. SQLite is an embeddable SQL database engine and is not a client library used to connect to a big database server (like MySQL or PostgreSQL). The SQLite library reads and writes directly to and from the database files on disk.

New Directives
New Object Model
Migrating from PHP 4 to PHP 5.0.x


New Object Model

In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

Many PHP programmers aren't even aware of the copying quirks of the old object model and, therefore, the majority of PHP applications will work out of the box, or with very few modifications.

The new Object Model is documented at the Language Reference.

In PHP 5, function with the name of a class is called as a constructor only if defined in the same class. In PHP 4, it is called also if defined in the parent class.

See also the zend.ze1_compatibility_mode directive for compatability with PHP 4.

Databases
Error Reporting
Migrating from PHP 4 to PHP 5.0.x


Error Reporting

As of PHP 5 the error reporting constant E_STRICT is available, with the value 2048. When enabled, messages will be issued to warn you about code usage which is deprecated or which may not be future-proof.

Informacja: E_ALL does not include E_STRICT, so it's not enabled by default. You must explicitly set the error reporting level to include E_STRICT in order to see these messages.

See Predefined Constants for more information.

New Object Model
Classes and Objects (PHP 4)
Migrating from PHP 4 to PHP 5.0.x


Classes and Objects (PHP 4)

Spis treści

  • class
  • extends
  • Constructors
  • Scope Resolution Operator (::)
  • parent
  • Serializing objects - objects in sessions
  • The magic functions __sleep and __wakeup
  • References inside the constructor
  • Comparing objects
Error Reporting
class
Dodatki


class

A class is a collection of variables and functions working with these variables. Variables are defined by var and functions by function. A class is defined using the following syntax:

<?php
class Cart {
    var $items;  // Items in our shopping cart

    // Add $num articles of $artnr to the cart

    function add_item($artnr, $num) {
        $this->items[$artnr] += $num;
    }

    // Take $num articles of $artnr out of the cart

    function remove_item($artnr, $num) {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } elseif ($this->items[$artnr] == $num) {
            unset($this->items[$artnr]);
            return true;
        } else {
            return false;
        }
    }
}
?>

This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.

Ostrzeżenie

You can NOT break up a class definition into multiple files. You also can NOT break a class definition into multiple PHP blocks, unless the break is within a method declaration. The following will not work:

<?php
class test {
?>
<?php
    function test() {
        print 'OK';
    }
}
?>

However, the following is allowed:

<?php
class test {
    function test() {
        ?>
        <?php
        print 'OK';
    }
}
?>

The following cautionary notes are valid for PHP 4.

Uwaga

The name stdClass is used internally by Zend and is reserved. You cannot have a class named stdClass in PHP.

Uwaga

The function names __sleep and __wakeup 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. See below for more information.

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.

In PHP 4, only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function which is called automatically when an object is being constructed from the class. Such a function is called a constructor (see below).

<?php
class Cart {
    /* None of these will work in PHP 4. */
    var $todays_date = date("Y-m-d");
    var $name = $firstname;
    var $owner = 'Fred ' . 'Jones';
    /* Arrays containing constant values will, though. */
    var $items = array("VCR", "TV");
}

/* This is how it should be done. */
class Cart {
    var $todays_date;
    var $name;
    var $owner;
    var $items = array("VCR", "TV");

    function Cart() {
        $this->todays_date = date("Y-m-d");
        $this->name = $GLOBALS['firstname'];
        /* etc. . . */
    }
}
?>

Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.

<?php
$cart = new Cart;
$cart->add_item("10", 1);

$another_cart = new Cart;
$another_cart->add_item("0815", 3);
?>

This creates the objects $cart and $another_cart, both of the class Cart. The function add_idem() of the $cart object is being called to add 1 item of article number 10 to the $cart. 3 items of article number 0815 are being added to $another_cart.

Both, $cart and $another_cart, have functions add_item(), remove_item() and a variable items. These are distinct functions and variables. You can think of the objects as something similar to directories in a filesystem. In a filesystem you can have two different files README.TXT, as long as they are in different directories. Just like with directories where you'll have to type the full pathname in order to reach each file from the toplevel directory, you have to specify the complete name of the function you want to call: in PHP terms, the toplevel directory would be the global namespace, and the pathname separator would be ->. Thus, the names $cart->items and $another_cart->items name two different variables. Note that the variable is named $cart->items, not $cart->$items, that is, a variable name in PHP has only a single dollar sign ($).

<?php
// correct, single $
$cart->items = array("10" => 1);

// invalid, because $cart->$items becomes $cart->""
$cart->$items = array("10" => 1);

// correct, but may or may not be what was intended:
// $cart->$myvar becomes $cart->items
$myvar = 'items';
$cart->$myvar = array("10" => 1);
?>

Within a class definition, you do not know under which name the object will be accessible in your program: at the time the Cart class was written, it was unknown whether the object would be named $cart, $another_cart, or something else later. Thus, you cannot write $cart->items within the Cart class itself. Instead, in order to be able to access its own functions and variables from within a class, one can use the pseudo-variable $this which can be read as 'my own' or 'current object'. Thus, '$this->items[$artnr] += $num' can be read as 'add $num to the $artnr counter of my own items array' or 'add $num to the $artnr counter of the items array within the current object'.

Informacja:

The $this pseudo-variable is not usually defined if the method in which it is hosted is called statically. This is not, however, a strict rule: $this is defined if a method is called statically from within another object. In this case, the value of $this is that of the calling object. This is illustrated in the following example:

<?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()
    {
        A::foo();
    }
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

Powyższy przykład wyświetli:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

Informacja:

There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Classes and Objects (PHP 4)
extends
Classes and Objects (PHP 4)


extends

Often you need classes with similar variables and functions to another existing class. In fact, it is good practice to define a generic class which can be used in all your projects and adapt this class for the needs of each of your specific projects. To facilitate this, classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class (this is called 'inheritance' despite the fact that nobody died) and what you add in the extended definition. It is not possible to subtract from a class, that is, to undefine any existing functions or variables. An extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'.

<?php
class Named_Cart extends Cart {
    var $owner;

    function set_owner ($name) {
        $this->owner = $name;
    }
}
?>

This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the carts owner. You can still use normal cart functions on named carts:

<?php
$ncart = new Named_Cart;    // Create a named cart
$ncart->set_owner("kris");  // Name that cart
print $ncart->owner;        // print the cart owners name
$ncart->add_item("10", 1);  // (inherited functionality from cart)
?>

This is also called a "parent-child" relationship. You create a class, parent, and use extends to create a new class based on the parent class: the child class. You can even use this new child class and create another class based on this child class.

Informacja:

Classes must be defined before they are used! If you want the class Named_Cart to extend the class Cart, you will have to define the class Cart first. If you want to create another class called Yellow_named_cart based on the class Named_Cart you have to define Named_Cart first. To make it short: the order in which the classes are defined is important.

class
Constructors
Classes and Objects (PHP 4)


Constructors

Constructors are functions in a class that are automatically called when you create a new instance of a class with new. A function becomes a constructor, when it has the same name as the class. If a class has no constructor, the constructor of the base class will be called, if it exists.

<?php
class Auto_Cart extends Cart {
    function Auto_Cart() {
        $this->add_item("10", 1);
    }
}
?>

This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can take arguments and these arguments can be optional, which makes them much more useful. To be able to still use the class without parameters, all parameters to constructors should be made optional by providing default values.

<?php
class Constructor_Cart extends Cart {
    function Constructor_Cart($item = "10", $num = 1) {
        $this->add_item ($item, $num);
    }
}

// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;

// Shop for real...
$different_cart = new Constructor_Cart("20", 17);
?>

You also can use the @ operator to mute errors occurring in the constructor, e.g. @new.

<?php
class A
{
    function A()
    {
        echo "I am the constructor of A.<br />\n";
    }

    function B()
    {
        echo "I am a regular function named B in class A.<br />\n";
        echo "I am not a constructor in A.<br />\n";
    }
}

class B extends A
{
}

// This will call B() as a constructor
$b = new B;
?>

The function B() in class A will suddenly become a constructor in class B, although it was never intended to be. PHP 4 does not care if the function is being defined in class B, or if it has been inherited.

Uwaga

PHP doesn't call constructors of the base class automatically from a constructor of a derived class. It is your responsibility to propagate the call to constructors upstream where appropriate.

Destructors are functions that are called automatically when an object is destroyed, either with unset() or by simply going out of scope. There are no destructors in PHP. You may use register_shutdown_function() instead to simulate most effects of destructors.

extends
Scope Resolution Operator (::)
Classes and Objects (PHP 4)


Scope Resolution Operator (::)

Uwaga

The following is valid for PHP 4 and later only.

Sometimes it is useful to refer to functions and variables in base classes or to refer to functions in classes that have not yet any instances. The :: operator is being used for this.

<?php
class A {
    function example() {
        echo "I am the original function A::example().<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am the redefined function B::example().<br />\n";
        A::example();
    }
}

// there is no object of class A.
// this will print
//   I am the original function A::example().<br />
A::example();

// create an object of class B.
$b = new B;

// this will print
//   I am the redefined function B::example().<br />
//   I am the original function A::example().<br />
$b->example();
?>

The above example calls the function example() in class A, but there is no object of class A, so that we cannot write $a->example() or similar. Instead we call example() as a 'class function', that is, as a function of the class itself, not any object of that class.

There are class functions, but there are no class variables. In fact, there is no object at all at the time of the call. Thus, a class function may not use any object variables (but it can use local and global variables), and it may not use $this at all.

In the above example, class B redefines the function example(). The original definition in class A is shadowed and no longer available, unless you are referring specifically to the implementation of example() in class A using the ::-operator. Write A::example() to do this (in fact, you should be writing parent::example(), as shown in the next section).

In this context, there is a current object and it may have object variables. Thus, when used from WITHIN an object function, you may use $this and object variables.

Constructors
parent
Classes and Objects (PHP 4)


parent

You may find yourself writing code that refers to variables and functions in base classes. This is particularly true if your derived class is a refinement or specialisation of code in your base class.

Instead of using the literal name of the base class in your code, you should be using the special name parent, which refers to the name of your base class as given in the extends declaration of your class. By doing this, you avoid using the name of your base class in more than one place. Should your inheritance tree change during implementation, the change is easily made by simply changing the extends declaration of your class.

<?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>
Scope Resolution Operator (::)
Serializing objects - objects in sessions
Classes and Objects (PHP 4)


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 functions 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 $a of class A on page1.php and serialize this, you'll get a string that refers to class A and contains all values of variabled contained in $a. If you want to be able to unserialize this on page2.php, recreating $a of class A, the definition of class A must be present in page2.php. This can be done for example by storing the class definition of class A in an include file and including this file in both page1.php and page2.php.

<?php
// classa.inc:

  class A {
      var $one = 1;

      function show_one() {
          echo $this->one;
      }
  }

// page1.php:

  include("classa.inc");

  $a = new A;
  $s = serialize($a);
  // store $s somewhere where page2.php can find it.
  $fp = fopen("store", "w");
  fwrite($fp, $s);
  fclose($fp);

// page2.php:

  // this is needed for the unserialize to work properly.
  include("classa.inc");

  $s = implode("", @file("store"));
  $a = unserialize($s);

  // now use the function show_one() of the $a object.
  $a->show_one();
?>

If you are using sessions and use 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 basically means that these objects can show up on any of your pages once they become part of your session.

It is strongly recommended that you include the class definitions of all such registered objects on all of your pages, even if you do not actually use these classes on all of your pages. If you don't and an object is being unserialized without its class definition being present, it will lose its class association and become an object of class __PHP_Incomplete_Class_Name without any functions available at all, that is, it will become quite 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.

parent
The magic functions __sleep and __wakeup
Classes and Objects (PHP 4)


The magic functions __sleep and __wakeup

serialize() checks if your class has a function with the magic name __sleep. If so, that function is being run prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

The intended use of __sleep is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which need not 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 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.

Serializing objects - objects in sessions
References inside the constructor
Classes and Objects (PHP 4)


References inside the constructor

Creating references within the constructor can lead to confusing results. This tutorial-like section helps you to avoid problems.

<?php
class Foo {
    function Foo($name) {
        // create a reference inside the global array $globalref
        global $globalref;
        $globalref[] = &$this;
        // set name to passed value
        $this->setName($name);
        // and put it out
        $this->echoName();
    }

    function echoName() {
        echo "<br />", $this->name;
    }

    function setName($name) {
        $this->name = $name;
    }
}
?>

Let us check out if there is a difference between $bar1 which has been created using the copy = operator and $bar2 which has been created using the reference =& operator...

<?php
$bar1 = new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */

$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */
?>

Apparently there is no difference, but in fact there is a very significant one: $bar1 and $globalref[0] are _NOT_ referenced, they are NOT the same variable. This is because "new" does not return a reference by default, instead it returns a copy.

Informacja: There is no performance loss (since PHP 4 and up use reference counting) returning copies instead of references. On the contrary it is most often better to simply work with copies instead of references, because creating references takes some time where creating copies virtually takes no time (unless none of them is a large array or object and one of them gets changed and the other(s) one(s) subsequently, then it would be wise to use references to change them all concurrently).

To prove what is written above let us watch the code below.
<?php
// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1->setName('set from outside');

// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set from outside
set in constructor */

// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');

// luckily they are not only equal, they are the same variable
// thus $bar2->name and $globalref[1]->name are the same too
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set from outside
set from outside */
?>

Another final example, try to understand it.

<?php
class A {
    function A($i) {
        $this->value = $i;
        // try to figure out why we do not need a reference here
        $this->b = new B($this);
    }

    function createRef() {
        $this->c = new B($this);
    }

    function echoValue() {
        echo "<br />","class ",get_class($this),': ',$this->value;
    }
}

class B {
    function B(&$a) {
        $this->a = &$a;
    }

    function echoValue() {
        echo "<br />","class ",get_class($this),': ',$this->a->value;
    }
}

// try to understand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =& new A(10);
$a->createRef();

$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();

$a->value = 11;

$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();

?>

Powyższy przykład wyświetli:

class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11

The magic functions __sleep and __wakeup
Comparing objects
Classes and Objects (PHP 4)


Comparing objects

In PHP 4, objects are compared in a very simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. Similar rules are applied when comparing two objects using the identity operator (===).

If we were to execute the code in the example below:

Przykład #1 Example of object comparison in PHP 4

<?php
function bool2str($bool) {
    if ($bool === false) {
            return 'FALSE';
    } else {
            return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2) {
    echo 'o1 == o2 : '.bool2str($o1 == $o2)."\n";
    echo 'o1 != o2 : '.bool2str($o1 != $o2)."\n";
    echo 'o1 === o2 : '.bool2str($o1 === $o2)."\n";
    echo 'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}

class Flag {
    var $flag;

    function Flag($flag=true) {
            $this->flag = $flag;
    }
}

class SwitchableFlag extends Flag {

    function turnOn() {
        $this->flag = true;
    }

    function turnOff() {
        $this->flag = false;
    }
}

$o = new Flag();
$p = new Flag(false);
$q = new Flag();

$r = new SwitchableFlag();

echo "Compare instances created with the same parameters\n";
compareObjects($o, $q);

echo "\nCompare instances created with different parameters\n";
compareObjects($o, $p);

echo "\nCompare an instance of a parent class with one from a subclass\n";
compareObjects($o, $r);
?>

Powyższy przykład wyświetli:

Compare instances created with the same parameters
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Compare instances created with different parameters
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Compare an instance of a parent class with one from a subclass
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Which is the output we will expect to obtain given the comparison rules above. Only instances with the same values for their attributes and from the same class are considered equal and identical.

Even in the cases where we have object composition, the same comparison rules apply. In the example below we create a container class that stores an associative array of Flag objects.

Przykład #2 Compound object comparisons in PHP 4

<?php
class FlagSet {
    var $set;

    function FlagSet($flagArr = array()) {
        $this->set = $flagArr;
    }

    function addFlag($name, $flag) {
        $this->set[$name] = $flag;
    }

    function removeFlag($name) {
        if (array_key_exists($name, $this->set)) {
            unset($this->set[$name]);
        }
    }
}

$u = new FlagSet();
$u->addFlag('flag1', $o);
$u->addFlag('flag2', $p);
$v = new FlagSet(array('flag1'=>$q, 'flag2'=>$p));
$w = new FlagSet(array('flag1'=>$q));

echo "\nComposite objects u(o,p) and v(q,p)\n";
compareObjects($u, $v);

echo "\nu(o,p) and w(q)\n";
compareObjects($u, $w);
?>

Powyższy przykład wyświetli:

Composite objects u(o,p) and v(q,p)
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

u(o,p) and w(q)
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

References inside the constructor
Debugging in PHP
Classes and Objects (PHP 4)


Debugging in PHP

Spis treści

  • About debugging in PHP
Comparing objects
About debugging in PHP
Dodatki


About debugging in PHP

PHP does not have an internal debugging facility. You can use one of the external debuggers though. The » Zend IDE includes a debugger, and there are also some free debugger extensions like DBG at » http://www.php-debugger.com/dbg/, the » Advanced PHP Debugger (APD) or » Xdebug.

Debugging in PHP
Configure options
Debugging in PHP


Configure options

Spis treści

  • List of core configure options
About debugging in PHP
List of core configure options
Dodatki


List of core configure options

Below is a partial list of configure options used by the PHP configure scripts when compiling in Unix-like environments. Most configure options are listed in their appropriate locations on the extension reference pages and not here. For a complete up-to-date list of configure options, run ./configure --help in your PHP source directory after running autoconf (see also the Installation chapter). You may also be interested in reading the » GNU configure documentation for information on additional configure options such as --prefix=PREFIX.

Informacja:

These are only used at compile time. If you want to alter PHP's runtime configuration, please see the chapter on Runtime Configuration.

  • Miscellaneous
  • PHP Behaviour
  • Server

Configure Options in PHP

Informacja:

These options are only used in PHP as of PHP 4.1.0, although some are available in older versions too. If you want to compile an older version, some options will probably not be available.

Misc options

--enable-debug

Compile with debugging symbols.

--with-layout=TYPE

Sets how installed files will be laid out. Type is one of PHP (default) or GNU.

--with-pear=DIR

Install PEAR in DIR (default PREFIX/lib/php).

--without-pear

Do not install PEAR.

--enable-sigchild

Enable PHP's own SIGCHLD handler.

--disable-rpath

Disable passing additional runtime library search paths.

--enable-libgcc

Enable explicitly linking against libgcc.

--enable-php-streams

Include experimental PHP streams. Do not use unless you are testing the code!

--with-zlib-dir[=DIR]

Define the location of zlib install directory.

--enable-trans-sid

Enable transparent session id propagation. Only valid for PHP 4.1.2 or less. From PHP 4.2.0, trans-sid feature is always compiled.

--with-tsrm-pthreads

Use POSIX threads (default).

--enable-shared[=PKGS]

Build shared libraries [default=yes].

--enable-static[=PKGS]

Build static libraries [default=yes].

--enable-fast-install[=PKGS]

Optimize for fast installation [default=yes].

--with-gnu-ld

Assume the C compiler uses GNU ld [default=no].

--disable-libtool-lock

Avoid locking (might break parallel builds).

--with-pic

Try to use only PIC/non-PIC objects [default=use both].

--enable-memory-limit

Compile with memory limit support. (not available since PHP 5.2.1 - always enabled)

--disable-url-fopen-wrapper

Disable the URL-aware fopen wrapper that allows accessing files via HTTP or FTP. (not available since PHP 5.2.5)

--enable-versioning

Export only required symbols. See INSTALL for more information.

PHP options

--enable-maintainer-mode

Enable make rules and dependencies not useful (and sometimes confusing) to the casual installer.

--with-config-file-path=PATH

Sets the path in which to look for php.ini, defaults to PREFIX/lib.

--enable-safe-mode

Enable safe mode by default.

--with-exec-dir[=DIR]

Only allow executables in DIR when in safe mode defaults to /usr/local/php/bin.

--enable-magic-quotes

Enable magic quotes by default.

--disable-short-tags

Disable the short-form <? start tag by default.

--enable-zend-multibyte

Enables multibyte code in the language parser and scanner to be executed. When PHP is compiled with this option, it also enables the encoding directive in the declare construct.

--with-libdir

Specifies the directory where the libraries to build PHP exists on a Unix system. For 64bit systems, its needed to specify this argument to the lib64 directory like: --with-libdir=lib64.

SAPI options

The following list contains the available SAPI&s (Server Application Programming Interface) for PHP.

--with-aolserver=DIR

Specify path to the installed AOLserver.

--with-apxs[=FILE]

Build shared Apache module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs. Make sure you specify the version of apxs that is actually installed on your system and NOT the one that is in the apache source tarball.

--with-apache[=DIR]

Build a static Apache module. DIR is the top-level Apache build directory, defaults to /usr/local/apache.

--with-mod_charset

Enable transfer tables for mod_charset (Russian Apache).

--with-apxs2[=FILE]

Build shared Apache 2.0 module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs.

--with-caudium=DIR

Build PHP as a Pike module for use with Caudium. DIR is the Caudium server dir, with the default value /usr/local/caudium/server.

--disable-cli

Available with PHP 4.3.0. Disable building the CLI version of PHP (this forces --without-pear). More information is available in the section about Using PHP from the command line.

--enable-embed[=TYPE]

Enable building of the embedded SAPI library. TYPE is either shared or static, which defaults to shared. Available with PHP 4.3.0.

--with-fhttpd[=DIR]

Build fhttpd module. DIR is the fhttpd sources directory, defaults to /usr/local/src/fhttpd. No longer available as of PHP 4.3.0.

--with-isapi=DIR

Build PHP as an ISAPI module for use with Zeus.

--with-nsapi=DIR

Specify path to the installed Netscape/iPlanet/SunONE Webserver.

--with-phttpd=DIR

No information yet.

--with-pi3web=DIR

Build PHP as a module for use with Pi3Web.

--with-roxen=DIR

Build PHP as a Pike module. DIR is the base Roxen directory, normally /usr/local/roxen/server.

--enable-roxen-zts

Build the Roxen module using Zend Thread Safety.

--with-servlet[=DIR]

Include servlet support. DIR is the base install directory for the JSDK. This SAPI requires the java extension must be built as a shared dl.

--with-thttpd=SRCDIR

Build PHP as thttpd module.

--with-tux=MODULEDIR

Build PHP as a TUX module (Linux only).

--with-webjames=SRCDIR

Build PHP as a WebJames module (RISC OS only)

--disable-cgi

Disable building CGI version of PHP. Available with PHP 4.3.0.

As of PHP 5.3.0 this argument enables FastCGI which previously had to be enabled using --enable-fastcgi.

--enable-force-cgi-redirect

Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.

As of PHP 5.3.0 this argument is enabled by default and no longer exists. To disable this, the cgi.force_redirect ini directive should be set to 0.

--enable-discard-path

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.

As of PHP 5.3.0 this argument is disabled by default and no longer exists. To enable this feature the cgi.discard_path ini directive must be set to 1.

--with-fastcgi

Build PHP as FastCGI application. No longer available as of PHP 4.3.0, instead you should use --enable-fastcgi .

--enable-fastcgi

If this is enabled, the CGI module will be built with support for FastCGI also. Available since PHP 4.3.0

As of PHP 5.3.0 this argument no longer exists and is enabled by --enable-cgi instead.

--disable-path-info-check

If this is disabled, paths such as /info.php/test?a=b will fail to work. Available since PHP 4.3.0. For more information see the » Apache Manual.

Configure options
php.ini directives
Configure options


php.ini directives

Spis treści

  • List of php.ini directives
  • List of php.ini sections
  • Description of core php.ini directives
List of core configure options
List of php.ini directives
Dodatki


List of php.ini directives

This list includes the php.ini directives you can set to configure your PHP setup.

The "Changeable" column shows the modes determining when and where a directive may be set. See the Changeable mode values section for their definitions.

Configuration options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP 4.0.0. Removed in PHP 5.4.0.
allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.3.4.
allow_url_include | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 5. Available since PHP 5.2.0.
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Available since PHP 4.1.0.
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0.
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12.
apc.enable_cli | "0" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.file_update_protection | "2" | PHP_INI_SYSTEM | Available since APC 3.0.6.
apc.filters | NULL | PHP_INI_SYSTEM |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.include_once_override | "0" | PHP_INI_SYSTEM | Available since APC 3.0.12.
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.max_file_size | "1M" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.num_files_hint | "1000" | PHP_INI_SYSTEM |
apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13.
apc.report_autofilter | "0" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apc.rfc1867 | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.rfc1867_freq | "0" | PHP_INI_SYSTEM |
apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM |
apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM |
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "30" | PHP_INI_SYSTEM |
apc.slam_defense | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.stat | "1" | PHP_INI_SYSTEM | Available since APC 3.0.10.
apc.stat_ctime | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.user_ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.write_lock | "1" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apd.bitmask | "0" | PHP_INI_ALL | Removed in apd 0.9.
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL | Available since apd 0.9.
arg_separator | "&" | PHP_INI_ALL | Removed in PHP 4.0.6.
arg_separator.input | "&" | PHP_INI_PERDIR | Available since PHP 4.0.5.
arg_separator.output | "&" | PHP_INI_ALL | Available since PHP 4.0.5.
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP 4.0.0.
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
async_send | "0" | PHP_INI_ALL | Available since PHP 4.2.0. Removed in PHP 4.3.0.
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
auto_detect_line_endings | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
auto_globals_jit | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0.
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
axis2.client_home | "~/work/axisc/c/deply" | PHP_INI_ALL |
axis2.enable_exception | "1" | PHP_INI_ALL |
axis2.enable_trace | "1" | PHP_INI_ALL |
axis2.log_path | "/tmp" | PHP_INI_ALL |
bcmath.scale | "0" | PHP_INI_ALL |
bcompiler.enabled | "1" | PHP_INI_ALL | Available since bcompiler 0.8.
birdstep.max_links | "-1" | PHP_INI_ALL | Available since PHP 4.2.0.
blenc.key_file | "/usr/local/etc/blenckeys" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.1.
cgi.discard_path | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0. Available since PHP 4.3.0.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0. Available since PHP 4.2.0.
cgi.nph | "0" | PHP_INI_ALL | Available since PHP 4.3.5.
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0. Available since PHP 4.2.0.
cgi.rfc2616_headers | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
child_terminate | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
cli.pager | "" | PHP_INI_ALL | Available since PHP 5.4.0.
cli.prompt | "\\b \\> " | PHP_INI_ALL | Available since PHP 5.4.0.
coin_acceptor.autoreset | "On" | PHP_INI_ALL | Removed in coin_acceptor 0.2.
coin_acceptor.auto_initialize | "Off" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.auto_reset | "On" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.command_function | "Off" | PHP_INI_ALL | Available since coin_acceptor 0.3.
coin_acceptor.delay | "53132" | PHP_INI_ALL | Removed in coin_acceptor 0.2.
coin_acceptor.delay_coins | "53132" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.delay_prom | "55748" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.device | "/dev/ttyS1" | PHP_INI_ALL | Removed in coin_acceptor 0.2.
coin_acceptor.lock_on_close | "Off" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.start_unlocked | "On" | PHP_INI_ALL | Available since coin_acceptor 0.2.
com.allow_dcom | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0.
com.code_page | "" | PHP_INI_ALL | Available since PHP 5.0.0.
com.typelib_file | "" | PHP_INI_SYSTEM | Available since PHP 4.0.5.
crack.default_dictionary | NULL | PHP_INI_PERDIR | PHP_INI_SYSTEM in crack <= 0.2. Available since PHP 4.0.5. Removed in PHP 5.0.0.
daffodildb.default_host | "localhost" | PHP_INI_ALL |
daffodildb.default_password | "daffodil" | PHP_INI_ALL |
daffodildb.default_socket | NULL | PHP_INI_ALL |
daffodildb.default_user | "DAFFODIL" | PHP_INI_ALL |
daffodildb.port | "3456" | PHP_INI_ALL |
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.
dba.default_handler | "" | PHP_INI_ALL | Available since PHP 4.3.3.
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. Removed in PHP 5.1.0.
default_charset | "" | PHP_INI_ALL |
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.0.
define_syslog_variables | "0" | PHP_INI_ALL | Removed in PHP 5.4.0.
detect_unicode | "1" | PHP_INI_ALL | Available since PHP 5.1.0. Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
disable_classes | "" | php.ini only | Available since PHP 4.3.2.
disable_functions | "" | php.ini only | Available since PHP 4.0.1.
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL | Available since PHP 4.0.3.
docref_ext | "" | PHP_INI_ALL | Available since PHP 4.3.2.
docref_root | "" | PHP_INI_ALL | Available since PHP 4.3.0.
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
engine | "1" | PHP_INI_ALL | Available since PHP 4.0.5.
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_reporting | NULL | PHP_INI_ALL |
etpan.default.charset | "utf-8" | PHP_INI_ALL |
etpan.default.protocol | "imap" | PHP_INI_ALL |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.encode_jis | "" | PHP_INI_ALL | Available since PHP 4.3.0.
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Available since PHP 4.3.0.
expect.logfile | "" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.timeout | "10" | PHP_INI_ALL |
expose_php | "1" | php.ini only |
extension | NULL | php.ini only |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0. Available since PHP 4.3.0.
fastcgi.logging | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0. Available since PHP 4.4.0.
fbsql.allow_persistant | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.6. Removed in PHP 4.2.0.
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.batchSize | "1000" | PHP_INI_SYSTEM | Available since PHP 4.2.0. Removed in PHP 5.1.0.
fbsql.batchsize | "1000" | PHP_INI_ALL | Available since PHP 5.1.0.
fbsql.default_database | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_database_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_host | NULL | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_password | "" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_links | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.max_results | "128" | PHP_INI_SYSTEM | Available since PHP 4.0.6.
fbsql.mbatchSize | "1000" | PHP_INI_SYSTEM | Available since PHP 4.0.6. Removed in PHP 4.2.0.
fbsql.show_timestamp_decimals | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.5.
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.2.3. Available since PHP 4.0.3.
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "0" | PHP_INI_ALL | Available since PHP 5.1.3.
geoip.custom_directory | NULL | PHP_INI_ALL | Available since geoip 1.0.1.
geoip.database_standard | "GeoIP.dat" | PHP_INI_ALL | Removed in geoip 1.0.1.
gpc_order | "GPC" | PHP_INI_ALL | Removed in PHP 5.0.0.
hidef.ini_path | (char*)default_ini_path | PHP_INI_SYSTEM |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | Removed in PHP 5.4.0.
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.2.
htscanner.config_file | ".htaccess" | PHP_INI_SYSTEM |
htscanner.default_docroot | "/" | PHP_INI_SYSTEM |
htscanner.default_ttl | "300" | PHP_INI_SYSTEM | Available since htscanner 0.6.0.
htscanner.stop_on_error | "0" | PHP_INI_SYSTEM | Available since htscanner 0.7.0.
http.allowed_methods | "" | PHP_INI_ALL | Available since pecl_http 0.4.0. Removed in pecl_http 1.0.0.
http.allowed_methods_log | "" | PHP_INI_ALL | Available since pecl_http 0.12.0. Removed in pecl_http 1.0.0.
http.cache_log | "" | PHP_INI_ALL | Available since pecl_http 0.8.0. Removed in pecl_http 1.0.0.
http.composite_log | "" | PHP_INI_ALL | Available since pecl_http 0.12.0. Removed in pecl_http 1.0.0.
http.etag.mode | "MD5" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.etag_mode | "MD5" | PHP_INI_ALL | Available since pecl_http 0.12.0. Removed in pecl_http 1.0.0.
http.force_exit | "1" | PHP_INI_ALL | Available since pecl_http 0.18.0.
http.log.allowed_methods | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.log.cache | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.log.composite | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.log.not_found | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.log.redirect | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.ob_deflate_auto | "0" | PHP_INI_PERDIR | Available since pecl_http 0.21.0. Removed in pecl_http 1.0.0.
http.ob_deflate_flags | "0" | PHP_INI_ALL | Available since pecl_http 0.21.0. Removed in pecl_http 1.0.0.
http.ob_inflate_auto | "0" | PHP_INI_PERDIR | Available since pecl_http 0.21.0. Removed in pecl_http 1.0.0.
http.ob_inflate_flags | "0" | PHP_INI_ALL | Available since pecl_http 0.21.0. Removed in pecl_http 1.0.0.
http.only_exceptions | "0" | PHP_INI_ALL | Available since pecl_http 0.11.0.
http.persistent.handles.ident | "GLOBAL" | PHP_INI_ALL | Available since pecl_http 1.5.0.
http.persistent.handles.limit | "-1" | PHP_INI_SYSTEM | Available since pecl_http 1.5.0.
http.redirect_log | "" | PHP_INI_ALL | Available since pecl_http 0.12.0. Removed in pecl_http 1.0.0.
http.request.datashare.connect | "0" | PHP_INI_SYSTEM | Available since pecl_http 1.3.0.
http.request.datashare.cookie | "0" | PHP_INI_SYSTEM | Available since pecl_http 1.3.0.
http.request.datashare.dns | "1" | PHP_INI_SYSTEM | Available since pecl_http 1.3.0.
http.request.datashare.ssl | "0" | PHP_INI_SYSTEM | Available since pecl_http 1.3.0.
http.request.methods.allowed | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.request.methods.custom | "" | PHP_INI_PERDIR | Available since pecl_http 1.0.0.
http.send.deflate.start_auto | "0" | PHP_INI_PERDIR | Available since pecl_http 1.0.0.
http.send.deflate.start_flags | "0" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.send.inflate.start_auto | "0" | PHP_INI_PERDIR | Available since pecl_http 1.0.0.
http.send.inflate.start_flags | "0" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.send.not_found_404 | "1" | PHP_INI_ALL | Available since pecl_http 1.0.0.
hyerwave.allow_persistent | "0" | PHP_INI_SYSTEM | Removed in PHP 4.3.2.
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.2. Removed in PHP 5.0.0.
hyperwave.default_port | "418" | PHP_INI_ALL | Removed in PHP 5.0.0.
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
ibase.default_db | NULL | PHP_INI_SYSTEM | Available since PHP 5.0.0.
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Available since PHP 4.0.5.
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.blobinfile | "1" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.byteasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.charasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.default_host | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_password | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_user | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_links | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.nullformat | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.textasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
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.
ignore_user_abort | "0" | PHP_INI_ALL |
imlib2.font_cache_max_size | "524288" | PHP_INI_ALL |
imlib2.font_path | "/usr/share/php/fonts/" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3.
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. Removed in PHP 5.1.0.
ingres.array_index_start | "1" | PHP_INI_ALL | Available since ingres 1.4.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since ingres 1.1.
ingres.default_database | NULL | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
ingres.default_password | NULL | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
ingres.default_user | NULL | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. Removed in PHP 5.1.0.
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. Removed in PHP 5.1.0.
ingres.report_db_warnings | "1" | PHP_INI_ALL | Available since ingres 1.1.
ingres.timeout | "-1" | PHP_INI_ALL | Available since ingres 1.4.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Available since ingres 1.2.1.
ircg.control_user | "nobody" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 5.1.0.
ircg.keep_alive_interval | "60" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 5.1.0.
ircg.max_format_message_sets | "12" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 5.1.0.
ircg.shared_mem_size | "6000000" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 5.1.0.
ircg.work_dir | "/tmp/ircg" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 5.1.0.
last_modified | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
ldap.base_dn | NULL | PHP_INI_ALL | Removed in PHP 4.2.0.
ldap.max_links | "-1" | PHP_INI_SYSTEM |
log.dbm_dir | "" | PHP_INI_ALL | Removed in PHP 4.0.1.
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL | Available since PHP 4.3.0.
magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Deprecated in PHP 5.3.0. 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.
magic_quotes_sybase | "0" | PHP_INI_ALL | Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
mail.add_x_header | "0" | PHP_INI_PERDIR | Available since PHP 5.3.0.
mail.force_extra_parameters | NULL | php.ini only | Available since PHP 5.0.0.
mail.log | "" | PHP_INI_ALL | Available since PHP 5.3.0.
mailparse.def_charset | "us-ascii" | PHP_INI_ALL | Available since PHP 4.1.0. Removed in PHP 4.2.0.
maxdb.default_db | NULL | PHP_INI_ALL |
maxdb.default_host | NULL | PHP_INI_ALL |
maxdb.default_pw | NULL | PHP_INI_ALL |
maxdb.default_user | NULL | PHP_INI_ALL |
maxdb.long_readlen | "200" | PHP_INI_ALL |
max_execution_time | "30" | PHP_INI_ALL |
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.
max_input_time | "-1" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.detect_order | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Available since PHP 4.3.0.
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP <= 4.2.3; PHP_INI_SYSTEM | PHP_INI_PERDIR from PHP 4.3 through 5.2.6. Available since PHP 4.2.0.
mbstring.http_input | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mbstring.language | "neutral" | PHP_INI_ALL | Available since PHP 4.3.0.; PHP_INI_PERDIR in PHP <= 5.2.6
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Available since PHP 5.1.2.
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6.
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
mcrypt.modes_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2.
memcache.allow_failover | "1" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since memcache 2.1.0.
memory_limit | "128M" | PHP_INI_ALL |
mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_links | "-1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
mssql.allow_persistent | "1" | PHP_INI_SYSTEM |
mssql.batchsize | "0" | PHP_INI_ALL | Available since PHP 4.0.4.
mssql.charset | "" | PHP_INI_ALL | Available since PHP 5.1.2.
mssql.compatability_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.datetimeconvert | "1" | PHP_INI_ALL | Available since PHP 4.2.0.
mssql.max_links | "-1" | PHP_INI_SYSTEM |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM |
mssql.max_procs | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
mssql.min_error_severity | "10" | PHP_INI_ALL |
mssql.min_message_severity | "10" | PHP_INI_ALL |
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL | Available since PHP 4.1.0.
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.connect_timeout | "60" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.3.2. Available since PHP 4.3.0.
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Available since PHP 4.0.1.
mysql.default_user | NULL | PHP_INI_ALL |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
mysqli.default_host | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Available since PHP 5.0.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
namazu.debugmode | "0" | PHP_INI_ALL |
namazu.lang | NULL | PHP_INI_ALL |
namazu.loggingmode | "0" | PHP_INI_ALL |
namazu.sortmethod | NULL | PHP_INI_ALL |
namazu.sortorder | NULL | PHP_INI_ALL |
nsapi.read_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.3.
oci8.default_prefetch | "10" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.old_oci_close_semantics | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.privileged_connect | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.default_db | NULL | PHP_INI_ALL |
odbc.default_pw | NULL | PHP_INI_ALL |
odbc.default_user | NULL | PHP_INI_ALL |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbtp.datetime_format | "object" | PHP_INI_ALL |
odbtp.detach_default_queries | "0" | PHP_INI_ALL |
odbtp.guid_format | "string" | PHP_INI_ALL | Available since odbtp 1.1.3.
odbtp.interface_file | "/usr/local/share/odbtp.conf" | PHP_INI_ALL |
odbtp.truncation_errors | "1" | PHP_INI_ALL |
opendirectory.default_separator | "/" | PHP_INI_ALL | Removed in opendirectory 0.2.2.
opendirectory.max_refs | "-1" | PHP_INI_ALL |
opendirectory.separator | "/" | PHP_INI_ALL | Available since opendirectory 0.2.2.
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM in PHP < 5.2.3.
oracle.allow_persistent | "-1" | PHP_INI_ALL | Removed in PHP 5.1.0.
oracle.max_links | "-1" | PHP_INI_ALL | Removed in PHP 5.1.0.
oracle.max_persistent | "-1" | PHP_INI_ALL | Removed in PHP 5.1.0.
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR | Available since PHP 4.0.4.
pam.servicename | "php" | PHP_INI_ALL |
pcre.backtrack_limit | "1000000" | PHP_INI_ALL | Available since PHP 5.2.0.
pcre.recursion_limit | "100000" | PHP_INI_ALL | Available since PHP 5.2.0.
pdo.dsn.* |  | php.ini only | Available since PHP 5.1.0.
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Available since PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Available since PHP 5.1.1. Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
pfpro.defaultport | "443" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
pfpro.defaulttimeout | "30" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
pfpro.proxyaddress | "" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
pfpro.proxylogon | "" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
pfpro.proxypassword | "" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
pfpro.proxyport | "" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 5.1.0.
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
pgsql.ignore_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
pgsql.log_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
phar.extract_list | "" | PHP_INI_ALL | Available since phar 1.1.0.
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
enable_post_data_reading | On | PHP_INI_PERDIR | Available since PHP 5.4.0.
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.3.
precision | "14" | PHP_INI_ALL |
printer.default_printer | "" | PHP_INI_ALL | Available since PHP 4.0.6. Removed in PHP 4.1.1.
python.append_path | "" | PHP_INI_ALL |
python.prepend_path | "." | PHP_INI_ALL |
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Available since PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Available since PHP 5.1.0.
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
register_long_arrays | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0. Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
report_memleaks | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
report_zend_debug | "1" | PHP_INI_ALL | Available since PHP 5.0.0.
request_order | "" | PHP_INI_PERDIR | Added in PHP 5.3.0
runkit.internal_override | "0" | PHP_INI_SYSTEM |
runkit.superglobal | "" | PHP_INI_PERDIR |
safe_mode | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_gid | "0" | PHP_INI_SYSTEM | Available since PHP 4.1.0. Removed in PHP 5.4.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Available since PHP 4.1.0. Removed in PHP 5.4.0.
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
serialize_precision | "17" | PHP_INI_ALL | Available since PHP 4.3.2. Until PHP 5.3.5, the default value was 100.
session.auto_start | "0" | PHP_INI_ALL |
session.bug_compat_42 | "1" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.4.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.4.0.
session.cache_expire | "180" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_httponly | "" | PHP_INI_ALL | Available since PHP 5.2.0.
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL | Available since PHP 4.0.4.
session.entropy_file | "" | PHP_INI_ALL |
session.entropy_length | "0" | PHP_INI_ALL |
session.gc_dividend | "100" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 4.3.2.
session.gc_divisor | "100" | PHP_INI_ALL | Available since PHP 4.3.2.
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.gc_probability | "1" | PHP_INI_ALL |
session.hash_bits_per_character | "4" | PHP_INI_ALL | Available since PHP 5.0.0.
session.hash_function | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
session.name | "PHPSESSID" | PHP_INI_ALL |
session.referer_check | "" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.save_path | "" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL | Available since PHP 4.3.0.
session.use_trans_sid | "0" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3.
session_pgsql.create_table | "1" | PHP_INI_SYSTEM |
session_pgsql.db | "host=localhost dbname=php_session user=nobody" | PHP_INI_SYSTEM |
session_pgsql.disable | "0" | PHP_INI_SYSTEM |
session_pgsql.failover_mode | "0" | PHP_INI_SYSTEM |
session_pgsql.gc_interval | "3600" | PHP_INI_SYSTEM |
session_pgsql.keep_expired | "0" | PHP_INI_SYSTEM |
session_pgsql.sem_file_name | "/tmp/php_session_pgsql" | PHP_INI_SYSTEM |
session_pgsql.serializable | "0" | PHP_INI_SYSTEM |
session_pgsql.short_circuit | "0" | PHP_INI_SYSTEM |
session_pgsql.use_app_vars | "0" | PHP_INI_SYSTEM |
session_pgsql.vacuum_interval | "21600" | PHP_INI_SYSTEM |
short_open_tag | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP 4.0.0. PHP_INI_PERDIR in PHP < 5.3.0
simple_cvs.authMethod | "0" | PHP_INI_ALL |
simple_cvs.compressionLevel | "0" | PHP_INI_ALL |
simple_cvs.cvsRoot | "0" | PHP_INI_ALL |
simple_cvs.host | "0" | PHP_INI_ALL |
simple_cvs.moduleName | "0" | PHP_INI_ALL |
simple_cvs.userName | "0" | PHP_INI_ALL |
simple_cvs.workingDir | "0" | PHP_INI_ALL |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL | Available since PHP 4.3.0.
soap.wsdl_cache | "1" | PHP_INI_ALL | Available since PHP 5.1.5.
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL | Available since PHP 5.0.0.
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL | Available since PHP 5.0.0.
soap.wsdl_cache_limit | "5" | PHP_INI_ALL | Available since PHP 5.1.5.
soap.wsdl_cache_ttl | "86400" | PHP_INI_ALL | Available since PHP 5.0.0.
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite.assoc_case | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.hostname | NULL | PHP_INI_ALL | Removed in PHP 4.0.2.
sybase.interface_file | "" | PHP_INI_ALL |
sybase.login_timeout | "0" | PHP_INI_ALL | Removed in PHP 4.0.2.
sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.min_client_severity | "10" | PHP_INI_ALL | Removed in PHP 4.0.2.
sybase.min_error_severity | "10" | PHP_INI_ALL |
sybase.min_message_severity | "10" | PHP_INI_ALL |
sybase.min_server_severity | "10" | PHP_INI_ALL | Removed in PHP 4.0.2.
sybase.timeout | "0" | PHP_INI_ALL | Removed in PHP 4.0.2.
sybct.allow_persistent | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
sybct.hostname | NULL | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.login_timeout | "-1" | PHP_INI_ALL | Available since PHP 4.0.2.
sybct.max_links | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.0.2. Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.min_client_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.min_server_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.2. Removed in PHP 4.0.3.
sybct.packet_size | "0" | PHP_INI_ALL | Available since PHP 4.3.5.
sybct.timeout | "0" | PHP_INI_ALL | Available since PHP 4.0.2.
sysvshm.init_mem | "10000" | PHP_INI_ALL |
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR in PHP 5. Available since PHP 5.0.0.
tidy.default_config | "" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
track_errors | "0" | PHP_INI_ALL |
track_vars | "1" | PHP_INI_ALL | Removed in PHP 4.0.3.
unserialize_callback_func | NULL | PHP_INI_ALL | Available since PHP 4.2.0.
uploadprogress.file.filename_template | "/tmp/upt_%s.txt" | PHP_INI_ALL |
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
max_file_uploads | 20 | PHP_INI_SYSTEM | Available since PHP 5.2.12.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | Available since PHP 4.0.4.
user_agent | NULL | PHP_INI_ALL | Available since PHP 4.3.0.
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
valkyrie.auto_validate | "0" | PHP_INI_ALL |
valkyrie.config_path | NULL | PHP_INI_ALL |
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 5.0.5.
velocis.max_links | "-1" | PHP_INI_ALL | Removed in PHP 4.2.0.
vld.active | "0" | PHP_INI_SYSTEM |
vld.execute | "1" | PHP_INI_SYSTEM | Available since vld 0.8.0.
vld.skip_append | "0" | PHP_INI_SYSTEM | Available since vld 0.8.0.
vld.skip_prepend | "0" | PHP_INI_SYSTEM | Available since vld 0.8.0.
xbithack | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
xdebug.auto_profile | "0" | PHP_INI_ALL | Removed in Xdebug 2.0.0.
xdebug.auto_profile_mode | "0" | PHP_INI_ALL | Removed in Xdebug 2.0.0.
xdebug.auto_trace | "0" | PHP_INI_ALL |
xdebug.collect_includes | "1" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.collect_params | "0" | PHP_INI_ALL |
xdebug.collect_return | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.collect_vars | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.default_enable | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in Xdebug 1.
xdebug.dump.COOKIE | NULL | PHP_INI_ALL |
xdebug.dump.ENV | NULL | PHP_INI_ALL |
xdebug.dump.FILES | NULL | PHP_INI_ALL |
xdebug.dump.GET | NULL | PHP_INI_ALL |
xdebug.dump.POST | NULL | PHP_INI_ALL |
xdebug.dump.REQUEST | NULL | PHP_INI_ALL |
xdebug.dump.SERVER | NULL | PHP_INI_ALL |
xdebug.dump.SESSION | NULL | PHP_INI_ALL |
xdebug.dump_globals | "1" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.dump_once | "1" | PHP_INI_ALL |
xdebug.dump_undefined | "0" | PHP_INI_ALL |
xdebug.extended_info | "1" | PHP_INI_SYSTEM | Available since Xdebug 2.0.0.
xdebug.idekey | "" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.manual_url | "http://www.php.net" | PHP_INI_ALL |
xdebug.max_nesting_level | "100" | PHP_INI_ALL |
xdebug.output_dir | "/tmp" | PHP_INI_PERDIR | PHP_INI_SYSTEM in Xdebug <= 1.2.0. Removed in Xdebug 2.0.0.
xdebug.profiler_aggregate | "0" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_append | "0" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_enable | "0" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_enable_trigger | "0" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_output_dir | "/tmp" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_output_name | "cachegrind.out.%p" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.remote_autostart | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.remote_enable | "0" | PHP_INI_PERDIR |
xdebug.remote_handler | "dbgp" | PHP_INI_ALL |
xdebug.remote_host | "localhost" | PHP_INI_ALL |
xdebug.remote_log | "" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.remote_mode | "req" | PHP_INI_ALL |
xdebug.remote_port | "9000" | PHP_INI_ALL |
xdebug.show_exception_trace | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.show_local_vars | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.show_mem_delta | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.trace_format | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.trace_options | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.trace_output_dir | "/tmp" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.trace_output_name | "trace.%c" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.var_display_max_children | "128" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.var_display_max_data | "512" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.var_display_max_depth | "3" | PHP_INI_ALL | Available since Xdebug 2.0.0.
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.
xmms.path | "/usr/bin/xmms" | PHP_INI_ALL |
xmms.session | "0" | PHP_INI_ALL |
y2k_compliance | "1" | PHP_INI_ALL |
yami.response.timeout | "5" | PHP_INI_ALL | Available since yami 1.0.1.
yaz.keepalive | "120" | PHP_INI_ALL |
yaz.log_file | NULL | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.0.0.
yaz.log_mask | NULL | PHP_INI_ALL | Available since yaz 1.0.3.
yaz.max_links | "100" | PHP_INI_ALL | Available since PHP 4.3.0. Removed in PHP 5.0.0.
zend.enable_gc | "1" | PHP_INI_ALL | Available since PHP 5.3.0.
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 5.3.0.
zend.multibyte | "0" | PHP_INI_PERDIR | Available since PHP 5.4.0.
zend_extension | NULL | php.ini only |
zend_extension_debug | NULL | php.ini only |
zend_extension_debug_ts | NULL | php.ini only |
zend_extension_ts | NULL | php.ini only |
zlib.output_compression | "0" | PHP_INI_ALL | Available since PHP 4.0.5.
zlib.output_compression_level | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
zlib.output_handler | "" | PHP_INI_ALL | Available since PHP 4.3.0.

php.ini directives
List of php.ini sections
php.ini directives


List of php.ini sections

This list includes the php.ini sections you can set to configure your PHP setup on a per Host or Path basis. These sections are optional.

These sections don't directly affect PHP. They are used to group other php.ini directives together and to get them to act upon a particular host or on a particular path.

These sections are used only in CGI/FastCGI mode and they can not set extension and zend_extension directives.

Sections
Nazwa | Możliwość zmian | Rejestr zmian
[HOST=] | PHP_INI_SYSTEM | Added in PHP 5.3.0.
[PATH=] | PHP_INI_SYSTEM | Added in PHP 5.3.0.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

[HOST=<host>]

This section allows you to define a set of php.ini directives that will take effect on the named host.

Przykład #1 Activate full on-screen error reporting for dev. domain

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

This section allows you to define a set of php.ini directives that will take effect when a script runs from the named path.

Przykład #2 Add security script for protected areas

[PATH=/home/site/public/secure]
auto_prepend_file=security.php

List of php.ini directives
Description of core php.ini directives
php.ini directives


Description of core php.ini directives

This list includes the core php.ini directives you can set to configure your PHP setup. Directives handled by extensions are listed and detailed at the extension documentation pages respectively; Information on the session directives for example can be found at the sessions page.

Httpd Options

Httpd Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
async_send | "0" | PHP_INI_ALL |

Language Options

Language and Misc Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
short_open_tag | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP 4.0.0. PHP_INI_PERDIR in PHP < 5.3.0
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP 4.0.0.
precision | "14" | PHP_INI_ALL |
serialize_precision | "17" | PHP_INI_ALL | Available since PHP 4.3.2. Until PHP 5.3.5, the default value was 100.
y2k_compliance | "1" | PHP_INI_ALL |
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP 4.0.0.
disable_functions | "" | php.ini only | Available since PHP 4.0.1.
disable_classes | "" | php.ini only | Available since PHP 4.3.2.
expose_php | "1" | php.ini only |
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 5.3.0
zend.multibyte | "0" | PHP_INI_ALL | Available since PHP 5.4.0
detect_unicode | "1" | PHP_INI_ALL | Available since PHP 5.1.0. Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

short_open_tag boolean

Tells PHP whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"?>'; ?>. Also, if disabled, you must use the long form of the PHP open tag (<?php ?>).

Informacja:

This directive also affected the shorthand <?= before PHP 5.4.0, which is identical to <? echo. Use of this shortcut required short_open_tag to be on. Since PHP 5.4.0, <?= is always available.

asp_tags boolean
Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes the variable-value printing shorthand of <%= $value %>. For more information, see Escaping from HTML.
precision integer
The number of significant digits displayed in floating point numbers.
serialize_precision integer
The number of significant digits stored while serializing floating point numbers.
y2k_compliance boolean
Enforce year 2000 compliance (will cause problems with non-compliant browsers)
allow_call_time_pass_reference boolean

Whether to warn when arguments are passed by reference at function call time. The encouraged method of specifying which arguments should be passed by reference is in the function declaration. You're encouraged to try and turn this option Off and make sure your scripts work properly with it in order to ensure they will work with future versions of the language (you will receive a warning each time you use this feature).

Passing arguments by reference at function call time was deprecated for code-cleanliness reasons. A function can modify its arguments in an undocumented way if it didn't declare that the argument shall be passed by reference. To prevent side-effects it's better to specify which arguments are passed by reference in the function declaration only.

In PHP 5, allow_call_time_pass_reference is deprecated, in versions prior to PHP 5.3.0, use of this feature will emit an E_COMPILE_WARNING, and in PHP 5.3.0+, the warning is a E_DEPRECATED notice.

See also References Explained.

expose_php boolean

Exposes to the world that PHP is installed on the server, which includes the PHP version within the HTTP header (e.g., X-Powered-By: PHP/5.3.7). The PHP logo guids are also exposed, thus appending them to the URL of a PHP enabled site will display the appropriate logo (e.g., » http://www.php.net/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). This also affects the output of phpinfo(), as when disabled, the PHP logo and credits information will not be displayed.

See also php_logo_guid() and phpcredits().

disable_functions string

This directive allows you to disable certain functions for security reasons. It takes on a comma-delimited list of function names. disable_functions is not affected by Safe Mode.

Only internal functions can be disabled using this directive. User-defined functions are unaffected.

This directive must be set in php.ini For example, you cannot set this in httpd.conf.

disable_classes string
This directive allows you to disable certain classes for security reasons. It takes on a comma-delimited list of class names. disable_classes is not affected by Safe Mode. This directive must be set in php.ini For example, you cannot set this in httpd.conf.

Informacja: Availability note
This directive became available in PHP 4.3.2

zend.ze1_compatibility_mode boolean

Enable compatibility mode with Zend Engine 1 (PHP 4). It affects the cloning, casting (objects with no properties cast to FALSE or 0), and comparing of objects. In this mode, objects are passed by value instead of reference by default.

See also the section titled Migrating from PHP 4 to PHP 5.

Ostrzeżenie

This feature has been DEPRECATED and REMOVED as of PHP 5.3.0.

zend.multibyte boolean

Enables parsing of source files in multibyte encodings.

detect_unicode boolean

Check for BOM (Byte Order Mark) and see if the file contains valid multibyte characters. This detection is performed before processing of __halt_compiler(). Available only in Zend Multibyte mode.

Resource Limits

Resource Limits
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
memory_limit | "128M" | PHP_INI_ALL | "8M" before PHP 5.2.0, "16M" in PHP 5.2.0

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

memory_limit integer

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1.

Prior to PHP 5.2.1, in order to use this directive it had to be enabled at compile time by using --enable-memory-limit in the configure line. This compile-time flag was also required to define the functions memory_get_usage() and memory_get_peak_usage() prior to 5.2.1.

Jeśli użyty zostanie typ integer, wartość zostanie liczona w bajtach. Można także użyć notacji skrótowej opisanej w FAQ.

See also: max_execution_time.

Performance Tuning

Performance Tuning
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Available since PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Available since PHP 5.1.0.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

realpath_cache_size integer

Determines the size of the realpath cache to be used by PHP. This value should be increased on systems where PHP opens many files, to reflect the quantity of the file operations performed.

realpath_cache_ttl integer

Duration of time (in seconds) for which to cache realpath information for a given file or directory. For systems with rarely changing files, consider increasing the value.

Data Handling

Data Handling Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
track_vars | "On" | PHP_INI_?? |
arg_separator.output | "&" | PHP_INI_ALL | Available since PHP 4.0.5.
arg_separator.input | "&" | PHP_INI_PERDIR | Available since PHP 4.0.5.
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 5.0.5.
request_order | "" | PHP_INI_PERDIR | Available since PHP 5.3.0
auto_globals_jit | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0.
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
register_long_arrays | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0. Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.0.3.
gpc_order | "GPC" | PHP_INI_ALL |
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "" | PHP_INI_ALL |
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Available since PHP 4.1.0.
allow_webdav_methods | "0" | PHP_INI_PERDIR |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

track_vars boolean

If enabled, then Environment, GET, POST, Cookie, and Server variables can be found in the global associative arrays $_ENV, $_GET, $_POST, $_COOKIE, and $_SERVER.

Note that as of PHP 4.0.3, track_vars is always turned on.

arg_separator.output string

The separator used in PHP generated URLs to separate arguments.

arg_separator.input string

List of separator(s) used by PHP to parse input URLs into variables.

Informacja:

Every character in this directive is considered as separator!

variables_order string

Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable parsing. For example, if variables_order is set to "SP" then PHP will create the superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting to "" means no superglobals will be set.

If the deprecated register_globals directive is on, then variables_order also configures the order the ENV, GET, POST, COOKIE and SERVER variables are populated in global scope. So for example if variables_order is set to "EGPCS", register_globals is enabled, and both $_GET['action'] and $_POST['action'] are set, then $action will contain the value of $_POST['action'] as P comes after G in our example directive value.

Ostrzeżenie

In both the CGI and FastCGI SAPIs, $_SERVER is also populated by values from the environment; S is always equivalent to ES regardless of the placement of E elsewhere in this directive.

Informacja:

The content and order of $_REQUEST is also affected by this directive.

request_order string

This directive describes the order in which PHP registers GET, POST and Cookie variables into the _REQUEST array. Registration is done from left to right, newer values override older values.

If this directive is not set, variables_order is used for $_REQUEST contents.

Note that the default distribution php.ini files does not contain the 'C' for cookies, due to security concerns.

auto_globals_jit boolean

When enabled, the SERVER and ENV variables are created when they're first used (Just In Time) instead of when the script starts. If these variables are not used within a script, having this directive on will result in a performance gain.

The PHP directives register_globals, register_long_arrays, and register_argc_argv must be disabled for this directive to have any affect. Since PHP 5.1.3 it is not necessary to have register_argc_argv disabled.

Ostrzeżenie

Usage of SERVER and ENV variables is checked during the compile time so using them through e.g. variable variables will not cause their initialization.

register_globals boolean

Whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables.

As of » PHP 4.2.0, this directive defaults to off.

Please read the security chapter on Using register_globals for related information.

Please note that register_globals cannot be set at runtime (ini_set()). Although, you can use .htaccess if your host allows it as described above. An example .htaccess entry: php_flag register_globals off.

Informacja:

register_globals is affected by the variables_order directive.

Ostrzeżenie

Ta opcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej opcji nie jest zalecane.

register_argc_argv boolean
Tells PHP whether to declare the argv & argc variables (that would contain the GET information). See also command line.
register_long_arrays boolean
Tells PHP whether or not to register the deprecated long $HTTP_*_VARS type predefined variables. When On (default), long predefined PHP variables like $HTTP_GET_VARS will be defined. If you're not using them, it's recommended to turn them off, for performance reasons. Instead, use the superglobal arrays, like $_GET. This directive became available in PHP 5.0.0.
Ostrzeżenie

Ta opcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej opcji nie jest zalecane.

enable_post_data_reading boolean
Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. This can be useful to proxy requests or to process the POST data in a memory efficient fashion.
post_max_size integer
Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size. Jeśli użyty zostanie typ integer, wartość zostanie liczona w bajtach. Można także użyć notacji skrótowej opisanej w FAQ. If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. <form action="edit.php?processed=1">, and then checking if $_GET['processed'] is set.

Informacja:

PHP allows shortcuts for bit values, including K (kilo), M (mega) and G (giga). PHP will do the conversions automatically if you use any of these. Be careful not to exceed the 32 bit signed integer limit (if you're using 32bit versions) as it will cause your script to fail.

gpc_order string

Set the order of GET/POST/COOKIE variable parsing. The default setting of this directive is "GPC". Setting this to "GP", for example, will cause PHP to completely ignore cookies and to overwrite any GET method variables with POST-method variables of the same name.

Informacja:

This option is not available in PHP 4. Use variables_order instead.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require() function, so include_path is used.

The special value none disables auto-prepending.

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the require() function, so include_path is used.

The special value none disables auto-appending.

Informacja: If the script is terminated with exit(), auto-append will not occur.

default_mimetype string

default_charset string

PHP always outputs a character encoding by default in the Content-type: header. To disable sending of the charset, simply set it to be empty.

always_populate_raw_post_data boolean

Always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only with unrecognized MIME type of the data. However, the preferred method for accessing the raw POST data is php://input. $HTTP_RAW_POST_DATA is not available with enctype="multipart/form-data".

allow_webdav_methods boolean

Allow handling of WebDAV http requests within PHP scripts (eg. PROPFIND, PROPPATCH, MOVE, COPY, etc.). This directive does not exist as of PHP 4.3.2. If you want to get the post data of those requests, you have to set always_populate_raw_post_data as well.

See also: magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase.

Paths and Directories

Paths and Directories Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM in PHP < 5.3.0
doc_root | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
extension | NULL | php.ini only |
zend_extension | NULL | php.ini only |
zend_extension_debug | NULL | php.ini only |
zend_extension_debug_ts | NULL | php.ini only |
zend_extension_ts | NULL | php.ini only |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | Available since PHP 4.3.0. PHP_INI_ALL prior to PHP 5.2.1.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | Available since PHP 4.2.0. PHP_INI_ALL prior to PHP 5.2.1.
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | Available since PHP 4.2.0. PHP_INI_ALL prior to PHP 5.2.1.
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.0. PHP_INI_ALL prior to PHP 5.2.1.
fastcgi.logging | "1" | PHP_INI_SYSTEM | Available since PHP 4.3.0. PHP_INI_ALL prior to PHP 5.2.1.
cgi.rfc2616_headers | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

include_path string

Specifies a list of directories where the require(), include(), fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it doesn't find it, check the next path, until it either locates the included file or returns with a warning or an error. You may modify or set your include path at runtime using set_include_path().

Przykład #1 Unix include_path

include_path=".:/php/includes"

Przykład #2 Windows include_path

include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory. However, it is more efficient to explicitly use include './file' than having PHP always check the current directory for every include.

open_basedir string

Limit the files that can be opened by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.

When a script tries to open a file with, for example, fopen() or gzopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to open it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink. If the file doesn't exist then the symlink couldn't be resolved and the filename is compared to (a resolved) open_basedir .

The special value . indicates that the working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir().

In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none".

Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.

The restriction specified with open_basedir is a directory name since PHP 5.2.16 and 5.3.4. Previous versions used it as a prefix. This means that "open_basedir = /dir/incl" also allowed access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: open_basedir = /dir/incl/

The default is to allow all files to be opened.

Informacja:

As of PHP 5.3.0 open_basedir can be tightened at run-time. This means that if open_basedir is set to /www/ in php.ini a script can tighten the configuration to /www/tmp/ at run-time with ini_set(). When listing several directories, you can use the PATH_SEPARATOR constant as a separator regardless of the operating system.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with tryb bezpieczny, no files outside this directory are served. If PHP was not compiled with FORCE_REDIRECT, you should set doc_root if you are running PHP as a CGI under any web server (other than IIS). The alternative is to use the cgi.force_redirect configuration below.

user_dir string

The base name of the directory used on a user's home directory for PHP files, for example public_html .

extension_dir string

In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl().

extension string

Which dynamically loadable extensions to load when PHP starts up.

zend_extension string

Absolute path to dynamically loadable Zend extension (for example APD) to load when PHP starts up.

zend_extension_debug string

Variant of zend_extension for extensions compiled with debug info.

zend_extension_debug_ts string

Variant of zend_extension for extensions compiled with debug info and thread safety.

zend_extension_ts string

Variant of zend_extension for extensions compiled with thread safety.

cgi.check_shebang_line boolean

Controls whether CGI PHP checks for line starting with #! (shebang) at the top of the running script. This line might be needed if the script support running both as stand-alone script and via PHP CGI. PHP in CGI mode skips this line and ignores its content if this directive is turned on.

cgi.fix_pathinfo boolean

Provides real PATH_INFO/ PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the CGI specs. Setting this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting of zero causes PHP to behave as before. It is turned on by default. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk.

Informacja:

Windows Users: When using IIS this option must be turned off. For OmniHTTPD or Xitami the same applies.

cgi.redirect_status_env string

If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution.

Informacja:

Setting this variable may cause security issues, know what you are doing first.

fastcgi.impersonate string

FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.

fastcgi.logging boolean

Turns on SAPI logging when using FastCGI. Default is to enable logging.

cgi.rfc2616_headers int

Tells PHP what type of headers to use when sending HTTP response code. If it's set 0, PHP sends a Status: header that is supported by Apache and other web servers. When this option is set to 1, PHP will send » RFC 2616 compliant headers. Leave it set to 0 unless you know what you're doing.

File Uploads

File Uploads Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.2.3. Available since PHP 4.0.3.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR | Available since PHP 5.3.9.
max_input_vars | 1000 | PHP_INI_PERDIR | Available since PHP 5.3.9.
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3.
max_file_uploads | 20 | PHP_INI_SYSTEM | Available since PHP 5.2.12.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

file_uploads boolean or integer

Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.

Jeśli użyty zostanie typ integer, wartość zostanie liczona w bajtach. Można także użyć notacji skrótowej opisanej w FAQ.
upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default.

If the directory specified here is not writable, PHP falls back to the system default temporary directory. If open_basedir is on, then the system default directory must be allowed for an upload to succeed.

upload_max_filesize integer

The maximum size of an uploaded file.

Jeśli użyty zostanie typ integer, wartość zostanie liczona w bajtach. Można także użyć notacji skrótowej opisanej w FAQ.
max_file_uploads integer

The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.

General SQL

General SQL Configuration Options
Nazwa | Domyślnie | Możliwość zmian | Rejestr zmian
sql.safe_mode | "0" | PHP_INI_SYSTEM |

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

sql.safe_mode boolean

If turned on, database connect functions that specify default values will use those values in place of supplied arguments. For default values see connect function documentation for the relevant database.

List of php.ini sections
Wykaz i klasyfikacja rozszerzeń
php.ini directives


Wykaz i klasyfikacja rozszerzeń

Spis treści

  • Spis alfabetyczny
  • Przynależność
  • Stan

Ten dodatek klasyfikuje za pomocą kilku kryteriów ponad 150 rozszerzeń udokumentowanych w podręczniku PHP.

Description of core php.ini directives
Spis alfabetyczny
Dodatki


Spis alfabetyczny

  • AMQP
  • Apache
  • APC
  • APD
  • Tablice
  • BBCode
  • BC Math
  • bcompiler
  • Bzip2
  • Cairo
  • Calendar
  • chdb
  • Classkit
  • Klasy/Obiekty
  • COM
  • Crack
  • Ctype
  • CUBRID
  • cURL
  • Cyrus
  • data/czas
  • DBA
  • dBase
  • DB++
  • dbx
  • Direct IO
  • Directories
  • DOM
  • DOM XML (PHP 4)
  • .NET
  • Eio
  • Enchant
  • Error Handling
  • Program execution
  • Exif
  • Expect
  • FAM
  • FrontBase
  • FDF
  • Fileinfo
  • filePro
  • Filesystem
  • Filter
  • FriBiDi
  • FTP
  • Function Handling
  • Gearman
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Gupnp
  • haru
  • Hash
  • htscanner
  • HTTP
  • Hyperwave
  • Hyperwave API
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • ID3
  • Informix
  • IIS
  • GD
  • ImageMagick
  • IMAP
  • inclued
  • PHP Options/Info
  • Ingres
  • Inotify
  • intl
  • Java
  • JSON
  • Judy
  • KADM5
  • KTaglib
  • LDAP
  • Libevent
  • libxml
  • LZF
  • Mail
  • Mailparse
  • Math
  • MaxDB
  • Multibyte String
  • Mcrypt
  • MCVE
  • Memcache
  • Memcached
  • Memtrack
  • Mhash
  • Mimetype
  • Ming
  • Misc.
  • mnoGoSearch
  • Mongo
  • mqseries
  • Msession
  • mSQL
  • Mssql
  • Mysql
  • Mysqli
  • Mysqlnd
  • mysqlnd_ms
  • mysqlnd_qc
  • Ncurses
  • Gopher
  • Network
  • Newt
  • YP/NIS
  • Lotus Notes
  • NSAPI
  • OAuth
  • Object Aggregation
  • OCI8
  • oggvorbis
  • OpenAL
  • OpenSSL
  • Output Control
  • Object overloading
  • Ovrimos SQL
  • Paradox
  • Parsekit
  • PCNTL
  • PCRE
  • PDF
  • PDO
  • 4D (PDO)
  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird/Interbase (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • MS SQL Server (PDO)
  • PostgreSQL
  • Phar
  • POSIX
  • Printer
  • Proctitle
  • PS
  • Pspell
  • qtdom
  • Radius
  • Rar
  • Readline
  • Recode
  • Reflection
  • POSIX Regex
  • RPM Reader
  • RRD
  • runkit
  • SAM
  • SCA
  • scream
  • SDO
  • SDO DAS XML
  • SDO-DAS-Relational
  • Semaphore
  • Sessions
  • Session PgSQL
  • Shared Memory
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Solr
  • Sphinx
  • SPL
  • SPL Types
  • SPPLUS
  • SQLite
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Statistics
  • Stomp
  • Streams
  • Strings
  • SVM
  • SVN
  • SWF
  • Swish
  • Sybase
  • TCP
  • Tidy
  • Tokenizer
  • tokyo_tyrant
  • ODBC
  • URL Funkcje
  • V8js
  • Variable handling
  • vpopmail
  • W32api
  • WDDX
  • Weakref
  • win32ps
  • win32service
  • WinCache
  • xattr
  • xdiff
  • Xhprof
  • XML Parser
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • XSLT (PHP 4)
  • Yaml
  • YAZ
  • Zip
  • Zlib
Wykaz i klasyfikacja rozszerzeń
Przynależność
Wykaz i klasyfikacja rozszerzeń


Przynależność

Rozszerzenia rdzenia

Aktualnie to nie są rozszerzenia. One są częscią rdzenia PHP i nie mogą być pominięte w plikach binarnych PHP za pomocą opcji kompilacji.

  • Tablice

  • Klasy/Obiekty

  • data/czas

  • Directories

  • Error Handling

  • Program execution

  • Filesystem

  • Filter

  • Function Handling

  • PHP Options/Info

  • Mail

  • Math

  • Misc.

  • Network

  • Output Control

  • Reflection

  • POSIX Regex

  • Sessions

  • SPL

  • Streams

  • Strings

  • Tokenizer

  • URL Funkcje

  • Variable handling

Wbudowane rozszerzenia

Te rozszerzenia są wbudowane w PHP.

  • Apache

  • BC Math

  • Bzip2

  • Calendar

  • COM

  • Ctype

  • cURL

  • DBA

  • dBase

  • DOM

  • .NET

  • Exif

  • FrontBase

  • FDF

  • FTP

  • Gettext

  • GMP

  • Hash

  • Firebird/InterBase

  • iconv

  • Informix

  • GD

  • IMAP

  • JSON

  • LDAP

  • libxml

  • Multibyte String

  • Mcrypt

  • Mhash

  • Mimetype

  • Ming

  • mSQL

  • Mssql

  • Mysql

  • Mysqli

  • Mysqlnd

  • Ncurses

  • NSAPI

  • Object Aggregation

  • OCI8

  • OpenSSL

  • PCNTL

  • PCRE

  • PDO

  • 4D (PDO)

  • CUBRID (PDO)

  • MS SQL Server (PDO)

  • Firebird/Interbase (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • MS SQL Server (PDO)

  • PostgreSQL

  • POSIX

  • Pspell

  • Readline

  • Recode

  • Semaphore

  • Shared Memory

  • SimpleXML

  • SNMP

  • SOAP

  • Sockets

  • SQLite

  • SQLite3

  • SVN

  • Sybase

  • Tidy

  • ODBC

  • WDDX

  • XML Parser

  • XMLReader

  • XML-RPC

  • XMLWriter

  • XSL

  • XSLT (PHP 4)

  • Yaml

  • Zip

  • Zlib

Zewnętrzne rozszerzenia

Aby skompilować te rozszerzenia w pierwszej kolejności wymagana jest instalacja dodatkowych, zewnętrznych bibliotek.

  • BBCode

  • Bzip2

  • chdb

  • Crack

  • cURL

  • dBase

  • DB++

  • dbx

  • DOM

  • DOM XML (PHP 4)

  • Eio

  • Enchant

  • FAM

  • FrontBase

  • FDF

  • Fileinfo

  • FriBiDi

  • GeoIP

  • Gettext

  • GMP

  • haru

  • Hyperwave

  • Hyperwave API

  • Firebird/InterBase

  • IBM DB2

  • Informix

  • ImageMagick

  • IMAP

  • Ingres

  • Java

  • LDAP

  • Libevent

  • libxml

  • MaxDB

  • Mcrypt

  • Memcache

  • Mhash

  • Ming

  • mnoGoSearch

  • Msession

  • mSQL

  • Mssql

  • Mysql

  • Mysqli

  • Mysqlnd

  • Ncurses

  • Newt

  • OAuth

  • OCI8

  • oggvorbis

  • OpenAL

  • OpenSSL

  • Ovrimos SQL

  • Paradox

  • PDF

  • 4D (PDO)

  • CUBRID (PDO)

  • MS SQL Server (PDO)

  • Firebird/Interbase (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • MS SQL Server (PDO)

  • PostgreSQL

  • PS

  • Pspell

  • qtdom

  • Radius

  • Rar

  • Readline

  • Recode

  • RRD

  • Session PgSQL

  • SimpleXML

  • SNMP

  • SOAP

  • Sphinx

  • SSH2

  • SWF

  • Swish

  • Sybase

  • Tidy

  • ODBC

  • vpopmail

  • WDDX

  • xattr

  • xdiff

  • XML Parser

  • XMLReader

  • XMLWriter

  • XSL

  • XSLT (PHP 4)

  • YAZ

Rozszerzenia PECL

Te rozszerzenia są dostępne pod adresem » PECL. Istnieje więcej rozszerzeń PECL, jednak nie są one obecnie udokumentowane w podręczniku PHP.

  • APC

  • APD

  • BBCode

  • bcompiler

  • chdb

  • Classkit

  • Crack

  • Cyrus

  • DB++

  • dbx

  • Direct IO

  • DOM XML (PHP 4)

  • Eio

  • Enchant

  • Expect

  • FAM

  • Fileinfo

  • filePro

  • FriBiDi

  • GeoIP

  • GnuPG

  • haru

  • Hash

  • htscanner

  • HTTP

  • Hyperwave

  • Hyperwave API

  • IBM DB2

  • ID3

  • IIS

  • ImageMagick

  • inclued

  • Ingres

  • Inotify

  • Java

  • JSON

  • KADM5

  • KTaglib

  • Libevent

  • LZF

  • Mailparse

  • MaxDB

  • MCVE

  • Memcache

  • mnoGoSearch

  • Mongo

  • mqseries

  • Msession

  • mysqlnd_qc

  • Ncurses

  • Gopher

  • Newt

  • YP/NIS

  • Lotus Notes

  • OAuth

  • oggvorbis

  • OpenAL

  • Ovrimos SQL

  • Paradox

  • Parsekit

  • PDF

  • PDO

  • 4D (PDO)

  • CUBRID (PDO)

  • MS SQL Server (PDO)

  • Firebird/Interbase (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • MS SQL Server (PDO)

  • Phar

  • Printer

  • PS

  • qtdom

  • Radius

  • Rar

  • RPM Reader

  • RRD

  • runkit

  • SAM

  • SCA

  • scream

  • SDO

  • SDO DAS XML

  • SDO-DAS-Relational

  • Session PgSQL

  • Sphinx

  • SPPLUS

  • ssdeep

  • SSH2

  • Statistics

  • SVN

  • SWF

  • Swish

  • TCP

  • vpopmail

  • W32api

  • Weakref

  • win32ps

  • win32service

  • WinCache

  • xattr

  • xdiff

  • Yaml

  • YAZ

  • Zip

Spis alfabetyczny
Stan
Wykaz i klasyfikacja rozszerzeń


Stan

Ta część wykazanych rozszerzeń nie jest przeznaczona do zastosowań produkcyjnych - one są albo za "stare" (przestarzałe), albo za "nowe" (eksperymentalne).

Przestarzałe rozszerzenia

Te rozszerzenia są przestarzałe i zwykle zostają zastępowane przez inne, ulepszone rozszerzenia.

  • Memtrack

  • Mimetype

  • Object overloading

Eksperymentalne rozszerzenia

Zachowanie tych rozszerzeń - włączając w to nazwy ich funkcji i coś innego udokumentowanego o tych rozszerzeniach - może zostać zmienione bez ostrzeżenia w przyszłych wydaniach PHP. Używasz tych rozszerzeń na własne ryzyko.

  • bcompiler

  • DB++

  • .NET

  • haru

  • Hash

  • ImageMagick

  • Java

  • Ming

  • Ncurses

  • Newt

  • Lotus Notes

  • Object Aggregation

  • Paradox

  • MS SQL Server (PDO)

  • Firebird/Interbase (PDO)

  • Oracle (PDO)

  • PS

  • qtdom

  • SCA

  • SDO-DAS-Relational

  • Swish

  • vpopmail

  • W32api

  • XML-RPC

Przynależność
Lista aliasów funkcji
Wykaz i klasyfikacja rozszerzeń


Lista aliasów funkcji

W PHP jest wiele funkcji, które można wywołać poprzez więcej niż jedną nazwę. W niektórych przypadkach nie ma preferowanej nazwy, na przykład is_int() i is_integer() są sobie równoważne pod każdym względem. Jednakże istnieją także funkcje, których nazwy się zmieniły z powodu czyszczenia API lub kompatybilności wstecznej. Zazwyczaj źle jest używać takich aliasów, jako że może to prowadzić do uzależnienia funkcjonowania skryptu od wersji PHP. Ta lista przeznaczona jest dla osób, które chcą uaktualnić swoje stare skrypty do nowej składni.

Aliases
Alias | Główna funkcja | Rozszerzenie
_ | gettext() | Gettext
add | swfmovie_add() | Ming (flash)
add | swfsprite_add() | Ming (flash)
add_root | domxml_add_root() | DOM XML
addaction | swfbutton_addAction() | Ming (flash)
addcolor | swfdisplayitem_addColor() | Ming (flash)
addentry | swfgradient_addEntry() | Ming (flash)
addfill | swfshape_addfill() | Ming (flash)
addshape | swfbutton_addShape() | Ming (flash)
addstring | swftext_addString() | Ming (flash)
addstring | swftextfield_addString() | Ming (flash)
align | swftextfield_align() | Ming (flash)
attributes | domxml_attributes() | DOM XML
children | domxml_children() | DOM XML
chop | rtrim() | Podstawowa składnia
close | closedir() | Podstawowa składnia
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
die | exit() | Różne funkcje
dir | getdir() | Podstawowa składnia
diskfreespace | disk_free_space() | System plików
domxml_getattr | domxml_get_attribute() | DOM XML
domxml_setattr | domxml_set_attribute() | DOM XML
doubleval | floatval() | Podstawowa składnia
drawarc | swfshape_drawarc() | Ming (flash)
drawcircle | swfshape_drawcircle() | Ming (flash)
drawcubic | swfshape_drawcubic() | Ming (flash)
drawcubicto | swfshape_drawcubicto() | Ming (flash)
drawcurve | swfshape_drawcurve() | Ming (flash)
drawcurveto | swfshape_drawcurveto() | Ming (flash)
drawglyph | swfshape_drawglyph() | Ming (flash)
drawline | swfshape_drawline() | Ming (flash)
drawlineto | swfshape_drawlineto() | Ming (flash)
dtd | domxml_intdtd() | DOM XML
dumpmem | domxml_dumpmem() | DOM XML
fbsql | fbsql_db_query() | FrontBase
fputs | fwrite() | Podstawowa składnia
get_attribute | domxml_get_attribute() | DOM XML
getascent | swffont_getAscent() | Ming (flash)
getascent | swftext_getAscent() | Ming (flash)
getattr | domxml_get_attribute() | DOM XML
getdescent | swffont_getDescent() | Ming (flash)
getdescent | swftext_getDescent() | Ming (flash)
getheight | swfbitmap_getHeight() | Ming (flash)
getleading | swffont_getLeading() | Ming (flash)
getleading | swftext_getLeading() | Ming (flash)
getshape1 | swfmorph_getShape1() | Ming (flash)
getshape2 | swfmorph_getShape2() | Ming (flash)
getwidth | swfbitmap_getWidth() | Ming (flash)
getwidth | swffont_getWidth() | Ming (flash)
getwidth | swftext_getWidth() | Ming (flash)
gzputs | gzwrite() | Zlib
i18n_convert | mb_convert_encoding() | Wielobajtowe ciągi tekstowe
i18n_discover_encoding | mb_detect_encoding() | Wielobajtowe ciągi tekstowe
i18n_http_input | mb_http_input() | Wielobajtowe ciągi tekstowe
i18n_http_output | mb_http_output() | Wielobajtowe ciągi tekstowe
i18n_internal_encoding | mb_internal_encoding() | Wielobajtowe ciągi tekstowe
i18n_ja_jp_hantozen | mb_convert_kana() | Wielobajtowe ciągi tekstowe
i18n_mime_header_decode | mb_decode_mimeheader() | Wielobajtowe ciągi tekstowe
i18n_mime_header_encode | mb_encode_mimeheader() | Wielobajtowe ciągi tekstowe
imap_create | imap_createmailbox() | IMAP
imap_fetchtext | imap_body() | IMAP
imap_getmailboxes | imap_list_full() | IMAP
imap_getsubscribed | imap_lsub_full() | IMAP
imap_header | imap_headerinfo() | IMAP
imap_listmailbox | imap_list() | IMAP
imap_listsubscribed | imap_lsub() | IMAP
imap_rename | imap_renamemailbox() | IMAP
imap_scan | imap_listscan() | IMAP
imap_scanmailbox | imap_listscan() | IMAP
ini_alter | ini_set() | Podstawowa składnia
is_double | is_float() | Podstawowa składnia
is_integer | is_int() | Podstawowa składnia
is_long | is_int() | Podstawowa składnia
is_real | is_float() | Podstawowa składnia
is_writeable | is_writable() | Podstawowa składnia
join | implode() | Podstawowa składnia
key_exists | array_key_exists() | Podstawowa składnia
labelframe | swfmovie_labelFrame() | Ming (flash)
labelframe | swfsprite_labelFrame() | Ming (flash)
last_child | domxml_last_child() | DOM XML
lastchild | domxml_last_child() | DOM XML
ldap_close | ldap_unbind() | LDAP
magic_quotes_runtime | set_magic_quotes_runtime() | Podstawowa składnia
mbstrcut | mb_strcut() | Wielobajtowe ciągi tekstowe
mbstrlen | mb_strlen() | Wielobajtowe ciągi tekstowe
mbstrpos | mb_strpos() | Wielobajtowe ciągi tekstowe
mbstrrpos | mb_strrpos() | Wielobajtowe ciągi tekstowe
mbsubstr | mb_substr() | Wielobajtowe ciągi tekstowe
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash)
ming_setscale | ming_setScale() | Ming (flash)
move | swfdisplayitem_move() | Ming (flash)
movepen | swfshape_movepen() | Ming (flash)
movepento | swfshape_movepento() | Ming (flash)
moveto | swfdisplayitem_moveTo() | Ming (flash)
moveto | swffill_moveTo() | Ming (flash)
moveto | swftext_moveTo() | Ming (flash)
msql | msql_db_query() | mSQL
msql_createdb | msql_create_db() | mSQL
msql_dbname | msql_result() | mSQL
msql_dropdb | msql_drop_db() | mSQL
msql_fieldflags | msql_field_flags() | mSQL
msql_fieldlen | msql_field_len() | mSQL
msql_fieldname | msql_field_name() | mSQL
msql_fieldtable | msql_field_table() | mSQL
msql_fieldtype | msql_field_type() | mSQL
msql_freeresult | msql_free_result() | mSQL
msql_listdbs | msql_list_dbs() | mSQL
msql_listfields | msql_list_fields() | mSQL
msql_listtables | msql_list_tables() | mSQL
msql_numfields | msql_num_fields() | mSQL
msql_numrows | msql_num_rows() | mSQL
msql_regcase | sql_regcase() | mSQL
msql_selectdb | msql_select_db() | mSQL
msql_tablename | msql_result() | mSQL
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_close | sybase_close() | Sybase
mssql_close | sybase_close() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_min_client_severity | sybase_min_client_severity() | Sybase
mssql_min_error_severity | sybase_min_error_severity() | Sybase
mssql_min_message_severity | sybase_min_message_severity() | Sybase
mssql_min_server_severity | sybase_min_server_severity() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_query | sybase_query() | Sybase
mssql_query | sybase_query() | Sybase
mssql_result | sybase_result() | Sybase
mssql_result | sybase_result() | Sybase
mssql_select_db | sybase_select_db() | Sybase
mssql_select_db | sybase_select_db() | Sybase
multcolor | swfdisplayitem_multColor() | Ming (flash)
mysql | mysql_db_query() | MySQL
mysql_createdb | mysql_create_db() | MySQL
mysql_db_name | mysql_result() | MySQL
mysql_dbname | mysql_result() | MySQL
mysql_dropdb | mysql_drop_db() | MySQL
mysql_fieldflags | mysql_field_flags() | MySQL
mysql_fieldlen | mysql_field_len() | MySQL
mysql_fieldname | mysql_field_name() | MySQL
mysql_fieldtable | mysql_field_table() | MySQL
mysql_fieldtype | mysql_field_type() | MySQL
mysql_freeresult | mysql_free_result() | MySQL
mysql_listdbs | mysql_list_dbs() | MySQL
mysql_listfields | mysql_list_fields() | MySQL
mysql_listtables | mysql_list_tables() | MySQL
mysql_numfields | mysql_num_fields() | MySQL
mysql_numrows | mysql_num_rows() | MySQL
mysql_selectdb | mysql_select_db() | MySQL
mysql_tablename | mysql_result() | MySQL
name | domxml_attrname() | DOM XML
new_child | domxml_new_child() | DOM XML
new_xmldoc | domxml_new_xmldoc() | DOM XML
nextframe | swfmovie_nextFrame() | Ming (flash)
nextframe | swfsprite_nextFrame() | Ming (flash)
node | domxml_node() | DOM XML
oci8append | ocicollappend() | OCI8
oci8assign | ocicollassign() | OCI8
oci8assignelem | ocicollassignelem() | OCI8
oci8close | ocicloselob() | OCI8
oci8free | ocifreecoll() | OCI8
oci8free | ocifreedesc() | OCI8
oci8getelem | ocicollgetelem() | OCI8
oci8load | ociloadlob() | OCI8
oci8max | ocicollmax() | OCI8
oci8ocifreecursor | ocifreestatement() | OCI8
oci8save | ocisavelob() | OCI8
oci8savefile | ocisavelobfile() | OCI8
oci8size | ocicollsize() | OCI8
oci8trim | ocicolltrim() | OCI8
oci8writetemporary | ociwritetemporarylob() | OCI8
oci8writetofile | ociwritelobtofile() | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
output | swfmovie_output() | Ming (flash)
parent | domxml_parent() | DOM XML
pdf_add_outline | pdf_add_bookmark() | PDF
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | Podstawowa składnia
recode | recode_string() | Recode
remove | swfmovie_remove() | Ming (flash)
remove | swfsprite_remove() | Ming (flash)
rewind | rewinddir() | Podstawowa składnia
root | domxml_root() | DOM XML
rotate | swfdisplayitem_rotate() | Ming (flash)
rotateto | swfdisplayitem_rotateTo() | Ming (flash)
rotateto | swffill_rotateTo() | Ming (flash)
save | swfmovie_save() | Ming (flash)
savetofile | swfmovie_saveToFile() | Ming (flash)
scale | swfdisplayitem_scale() | Ming (flash)
scaleto | swfdisplayitem_scaleTo() | Ming (flash)
scaleto | swffill_scaleTo() | Ming (flash)
set_attribute | domxml_set_attribute() | DOM XML
set_content | domxml_set_content() | DOM XML
setaction | swfbutton_setAction() | Ming (flash)
setattr | domxml_set_attribute() | DOM XML
setbackground | swfmovie_setBackground() | Ming (flash)
setbounds | swftextfield_setBounds() | Ming (flash)
setcolor | swftext_setColor() | Ming (flash)
setcolor | swftextfield_setColor() | Ming (flash)
setdepth | swfdisplayitem_setDepth() | Ming (flash)
setdimension | swfmovie_setDimension() | Ming (flash)
setdown | swfbutton_setDown() | Ming (flash)
setfont | swftext_setFont() | Ming (flash)
setfont | swftextfield_setFont() | Ming (flash)
setframes | swfmovie_setFrames() | Ming (flash)
setframes | swfsprite_setFrames() | Ming (flash)
setheight | swftext_setHeight() | Ming (flash)
setheight | swftextfield_setHeight() | Ming (flash)
sethit | swfbutton_setHit() | Ming (flash)
setindentation | swftextfield_setIndentation() | Ming (flash)
setleftfill | swfshape_setleftfill() | Ming (flash)
setleftmargin | swftextfield_setLeftMargin() | Ming (flash)
setline | swfshape_setline() | Ming (flash)
setlinespacing | swftextfield_setLineSpacing() | Ming (flash)
setmargins | swftextfield_setMargins() | Ming (flash)
setmatrix | swfdisplayitem_setMatrix() | Ming (flash)
setname | swfdisplayitem_setName() | Ming (flash)
setname | swftextfield_setName() | Ming (flash)
setover | swfbutton_setOver() | Ming (flash)
setrate | swfmovie_setRate() | Ming (flash)
setratio | swfdisplayitem_setRatio() | Ming (flash)
setrightfill | swfshape_setrightfill() | Ming (flash)
setrightmargin | swftextfield_setRightMargin() | Ming (flash)
setspacing | swftext_setSpacing() | Ming (flash)
setup | swfbutton_setUp() | Ming (flash)
show_source | highlight_file() | Podstawowa składnia
sizeof | count() | Podstawowa składnia
skewx | swfdisplayitem_skewX() | Ming (flash)
skewxto | swfdisplayitem_skewXTo() | Ming (flash)
skewxto | swffill_skewXTo() | Ming (flash)
skewy | swfdisplayitem_skewY() | Ming (flash)
skewyto | swfdisplayitem_skewYTo() | Ming (flash)
skewyto | swffill_skewYTo() | Ming (flash)
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | Podstawowa składnia
streammp3 | swfmovie_streamMp3() | Ming (flash)
swfaction | swfaction_init() | Ming (flash)
swfbitmap | swfbitmap_init() | Ming (flash)
swfbutton | swfbutton_init() | Ming (flash)
swffill | swffill_init() | Ming (flash)
swffont | swffont_init() | Ming (flash)
swfgradient | swfgradient_init() | Ming (flash)
swfmorph | swfmorph_init() | Ming (flash)
swfmovie | swfmovie_init() | Ming (flash)
swfshape | swfshape_init() | Ming (flash)
swfsprite | swfsprite_init() | Ming (flash)
swftext | swftext_init() | Ming (flash)
swftextfield | swftextfield_init() | Ming (flash)
unlink | domxml_unlink_node() | DOM XML
xptr_new_context | xpath_new_context() | DOM XML

Stan
List of Reserved Words
Dodatki


List of Reserved Words

Spis treści

  • List of Keywords
  • Predefined Classes
  • Predefiniowane stałe

The following is a listing of predefined identifiers in PHP. None of the identifiers listed here should be used as identifiers in any of your scripts. These lists include keywords and predefined variable, constant, and class names. These lists are neither exhaustive or complete.

Lista aliasów funkcji
List of Keywords
Dodatki


List of Keywords

These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on--but they're not, really: they are language constructs. You cannot use any of the following words as constants, class names, function or method names. Using them as variable names is generally OK, but could lead to confusion.

PHP Keywords
abstract (as of PHP 5) | and | array() | as | break
case | catch (as of PHP 5) | cfunction (PHP 4 only) | class | clone (as of PHP 5)
const | continue | declare | default | do
else | elseif | enddeclare | endfor | endforeach
endif | endswitch | endwhile | extends | final (as of PHP 5)
for | foreach | function | global | goto (as of PHP 5.3)
if | implements (as of PHP 5) | interface (as of PHP 5) | instanceof (as of PHP 5)
namespace (as of PHP 5.3) | new | old_function (PHP 4 only) | or | private (as of PHP 5)
protected (as of PHP 5) | public (as of PHP 5) | static | switch | throw (as of PHP 5)
try (as of PHP 5) | use | var | while | xor
Compile-time constants
__CLASS__ | __DIR__ (as of PHP 5.3) | __FILE__ | __LINE__ | __FUNCTION__ | __METHOD__
__NAMESPACE__ (as of PHP 5.3) |  |  |  |
Language constructs
die() | echo() | empty() | exit() | eval()
include() | include_once() | isset() | list() | require()
require_once() | return() | print() | unset() | __halt_compiler()
List of Reserved Words
Predefined Classes
List of Reserved Words


Predefined Classes

This section lists standard predefined classes. Miscellaneous extensions define other classes which are described in their reference.

Standard Defined Classes

These classes are defined in the standard set of functions included in the PHP build.

Directory
Created by dir().
stdClass
Created by typecasting to object.
__PHP_Incomplete_Class
Possibly created by unserialize().

Predefined classes as of PHP 5

These additional predefined classes were introduced in PHP 5.0.0.

exception
php_user_filter

Closure

The predefined final class Closure was introduced in PHP 5.3.0. It is used for representing anonymous functions.

For more information, see its class page.

Special classes

Following identifiers may not be used as a class name as they have special purpose.

self
Current class.
static
Current class in runtime.
parent
Parent class.
List of Keywords
Predefiniowane stałe
List of Reserved Words


Predefiniowane stałe

Stałe zdefiniowane w rdzeniu PHP

Poniższe stałe są definiowane przez rdzeń PHP. Składa się na niego PHP, silnik Zend i moduły SAPI.

PHP_VERSION (string)
PHP_MAJOR_VERSION (integer)
Dostępna od PHP 5.2.7.
PHP_MINOR_VERSION (integer)
Dostępna od PHP 5.2.7.
PHP_RELEASE_VERSION (integer)
Dostępna od PHP 5.2.7.
PHP_VERSION_ID (integer)
Dostępna od PHP 5.2.7.
PHP_EXTRA_VERSION (string)
Dostępna od PHP 5.2.7.
PHP_ZTS (integer)
Dostępna od PHP 5.2.7.
PHP_DEBUG (integer)
Dostępna od PHP 5.2.7.
PHP_MAXPATHLEN (integer)
Dostępna od PHP 5.3.0.
PHP_OS (string)
PHP_SAPI (string)
Dostępna od PHP 4.2.0. Patrz także php_sapi_name().
PHP_EOL (string)
Dostępna od PHP 4.3.10 i PHP 5.0.2
PHP_INT_MAX (integer)
Dostępna od PHP 4.4.0 i PHP 5.0.5
PHP_INT_SIZE (integer)
Dostępna od PHP 4.4.0 i PHP 5.0.5
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
PHP_PREFIX (string)
Dostępna od PHP 4.3.0
PHP_BINDIR (string)
PHP_MANDIR (string)
Określa miejsce instalacji dokumentacji man. Dostępne od PHP 5.3.7.
PHP_LIBDIR (string)
PHP_DATADIR (string)
PHP_SYSCONFDIR (string)
PHP_LOCALSTATEDIR (string)
PHP_CONFIG_FILE_PATH (string)
PHP_CONFIG_FILE_SCAN_DIR (string)
PHP_SHLIB_SUFFIX (string)
Dostępna od PHP 4.3.0
PHP_OUTPUT_HANDLER_START (integer)
PHP_OUTPUT_HANDLER_CONT (integer)
PHP_OUTPUT_HANDLER_END (integer)
PHP_WINDOWS_VERSION_MAJOR (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_VERSION_MINOR (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_VERSION_BUILD (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_VERSION_PLATFORM (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_VERSION_SP_MAJOR (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_VERSION_SP_MINOR (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_VERSION_SUITEMASK (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_VERSION_PRODUCTTYPE (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_NT_DOMAIN_CONTROLLER (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_NT_SERVER (integer)
Dostępna od PHP 5.3.0
PHP_WINDOWS_NT_WORKSTATION (integer)
Dostępna od PHP 5.3.0
E_ERROR (integer)
E_WARNING (integer)
E_PARSE (integer)
E_NOTICE (integer)
E_CORE_ERROR (integer)
E_CORE_WARNING (integer)
E_COMPILE_ERROR (integer)
E_COMPILE_WARNING (integer)
E_USER_ERROR (integer)
E_USER_WARNING (integer)
E_USER_NOTICE (integer)
E_DEPRECATED (integer)
Dostępna od PHP 5.3.0
E_USER_DEPRECATED (integer)
Dostępna od PHP 5.3.0
E_ALL (integer)
E_STRICT (integer)
Dostępna od PHP 5.0.0
__COMPILER_HALT_OFFSET__ (integer)
Dostępna od PHP 5.1.0
TRUE (boolean)
Zobacz typy logiczne.
FALSE (boolean)
Zobacz typy logiczne.
NULL (boolean)
Zobacz Null.

Patrz także: Stałe magiczne.

Standardowe Predefiniowane Stałe

Poniższe stałe są zdefiowane w PHP domyślnie.

EXTR_OVERWRITE (integer)
EXTR_SKIP (integer)
EXTR_PREFIX_SAME (integer)
EXTR_PREFIX_ALL (integer)
EXTR_PREFIX_INVALID (integer)
EXTR_PREFIX_IF_EXISTS (integer)
EXTR_IF_EXISTS (integer)
SORT_ASC (integer)
SORT_DESC (integer)
SORT_REGULAR (integer)
SORT_NUMERIC (integer)
SORT_STRING (integer)
CASE_LOWER (integer)
CASE_UPPER (integer)
COUNT_NORMAL (integer)
COUNT_RECURSIVE (integer)
ASSERT_ACTIVE (integer)
ASSERT_CALLBACK (integer)
ASSERT_BAIL (integer)
ASSERT_WARNING (integer)
ASSERT_QUIET_EVAL (integer)
CONNECTION_ABORTED (integer)
CONNECTION_NORMAL (integer)
CONNECTION_TIMEOUT (integer)
INI_USER (integer)
INI_PERDIR (integer)
INI_SYSTEM (integer)
INI_ALL (integer)
M_E (float)
M_LOG2E (float)
M_LOG10E (float)
M_LN2 (float)
M_LN10 (float)
M_PI (float)
M_PI_2 (float)
M_PI_4 (float)
M_1_PI (float)
M_2_PI (float)
M_2_SQRTPI (float)
M_SQRT2 (float)
M_SQRT1_2 (float)
CRYPT_SALT_LENGTH (integer)
CRYPT_STD_DES (integer)
CRYPT_EXT_DES (integer)
CRYPT_MD5 (integer)
CRYPT_BLOWFISH (integer)
DIRECTORY_SEPARATOR (integer)
SEEK_SET (integer)
SEEK_CUR (integer)
SEEK_END (integer)
LOCK_SH (integer)
LOCK_EX (integer)
LOCK_UN (integer)
LOCK_NB (integer)
HTML_SPECIALCHARS (integer)
HTML_ENTITIES (integer)
ENT_COMPAT (integer)
ENT_QUOTES (integer)
ENT_NOQUOTES (integer)
INFO_GENERAL (integer)
INFO_CREDITS (integer)
INFO_CONFIGURATION (integer)
INFO_MODULES (integer)
INFO_ENVIRONMENT (integer)
INFO_VARIABLES (integer)
INFO_LICENSE (integer)
INFO_ALL (integer)
CREDITS_GROUP (integer)
CREDITS_GENERAL (integer)
CREDITS_SAPI (integer)
CREDITS_MODULES (integer)
CREDITS_DOCS (integer)
CREDITS_FULLPAGE (integer)
CREDITS_QA (integer)
CREDITS_ALL (integer)
STR_PAD_LEFT (integer)
STR_PAD_RIGHT (integer)
STR_PAD_BOTH (integer)
PATHINFO_DIRNAME (integer)
PATHINFO_BASENAME (integer)
PATHINFO_EXTENSION (integer)
CHAR_MAX (integer)
LC_CTYPE (integer)
LC_NUMERIC (integer)
LC_TIME (integer)
LC_COLLATE (integer)
LC_MONETARY (integer)
LC_ALL (integer)
LC_MESSAGES (integer)
ABDAY_1 (integer)
ABDAY_2 (integer)
ABDAY_3 (integer)
ABDAY_4 (integer)
ABDAY_5 (integer)
ABDAY_6 (integer)
ABDAY_7 (integer)
DAY_1 (integer)
DAY_2 (integer)
DAY_3 (integer)
DAY_4 (integer)
DAY_5 (integer)
DAY_6 (integer)
DAY_7 (integer)
ABMON_1 (integer)
ABMON_2 (integer)
ABMON_3 (integer)
ABMON_4 (integer)
ABMON_5 (integer)
ABMON_6 (integer)
ABMON_7 (integer)
ABMON_8 (integer)
ABMON_9 (integer)
ABMON_10 (integer)
ABMON_11 (integer)
ABMON_12 (integer)
MON_1 (integer)
MON_2 (integer)
MON_3 (integer)
MON_4 (integer)
MON_5 (integer)
MON_6 (integer)
MON_7 (integer)
MON_8 (integer)
MON_9 (integer)
MON_10 (integer)
MON_11 (integer)
MON_12 (integer)
AM_STR (integer)
PM_STR (integer)
D_T_FMT (integer)
D_FMT (integer)
T_FMT (integer)
T_FMT_AMPM (integer)
ERA (integer)
ERA_YEAR (integer)
ERA_D_T_FMT (integer)
ERA_D_FMT (integer)
ERA_T_FMT (integer)
ALT_DIGITS (integer)
INT_CURR_SYMBOL (integer)
CURRENCY_SYMBOL (integer)
CRNCYSTR (integer)
MON_DECIMAL_POINT (integer)
MON_THOUSANDS_SEP (integer)
MON_GROUPING (integer)
POSITIVE_SIGN (integer)
NEGATIVE_SIGN (integer)
INT_FRAC_DIGITS (integer)
FRAC_DIGITS (integer)
P_CS_PRECEDES (integer)
P_SEP_BY_SPACE (integer)
N_CS_PRECEDES (integer)
N_SEP_BY_SPACE (integer)
P_SIGN_POSN (integer)
N_SIGN_POSN (integer)
DECIMAL_POINT (integer)
RADIXCHAR (integer)
THOUSANDS_SEP (integer)
THOUSEP (integer)
GROUPING (integer)
YESEXPR (integer)
NOEXPR (integer)
YESSTR (integer)
NOSTR (integer)
CODESET (integer)
LOG_EMERG (integer)
LOG_ALERT (integer)
LOG_CRIT (integer)
LOG_ERR (integer)
LOG_WARNING (integer)
LOG_NOTICE (integer)
LOG_INFO (integer)
LOG_DEBUG (integer)
LOG_KERN (integer)
LOG_USER (integer)
LOG_MAIL (integer)
LOG_DAEMON (integer)
LOG_AUTH (integer)
LOG_SYSLOG (integer)
LOG_LPR (integer)
LOG_NEWS (integer)
LOG_UUCP (integer)
LOG_CRON (integer)
LOG_AUTHPRIV (integer)
LOG_LOCAL0 (integer)
LOG_LOCAL1 (integer)
LOG_LOCAL2 (integer)
LOG_LOCAL3 (integer)
LOG_LOCAL4 (integer)
LOG_LOCAL5 (integer)
LOG_LOCAL6 (integer)
LOG_LOCAL7 (integer)
LOG_PID (integer)
LOG_CONS (integer)
LOG_ODELAY (integer)
LOG_NDELAY (integer)
LOG_NOWAIT (integer)
LOG_PERROR (integer)
Predefined Classes
Lista Rodzajów Zasobów
List of Reserved Words


Lista Rodzajów Zasobów

Niniejszy rodział zawiera listę funkcji, które tworzą, wykorzystują lub są destruktorami zasobów PHP. Aby określić, czy dana zmienna jest identyfikatorem zasobów, używa się funkcji is_resource(), natomiast funkcją get_resource_type() można sprawdzić, do jakiego rodzaju zasobów należy dany identyfikator.

Rodzaje Zasobów
Nazwa Zasobu | Tworzony przez | Wykorzysytwany przez | Niszczony przez | Opis
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | Brak | Słownik Aspell
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Plik Bzip2
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | Brak | Odnośnik do obiektu COM
VARIANT
cpdf | cpdf_open() | cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() | cpdf_close() | Dokument PDF obsługiwany przez bibliotekę CPDF
cpdf outline
curl | curl_copy_handle(), curl_init() | curl_init(), curl_exec() | curl_close() | Sesja Curl
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Łącze do bazy danych DBM
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Łącze do bazy danych DBA
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | Brak | Trwałe łącze do bazy danych DBA
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Łącze do bazy danych Dbase
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | Połączenie dbx
dbx_result_object | dbx_query() | Brak | Wynik dbx
domxml attribute
domxml document
domxml node
xpath context
xpath object
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_blob_size(), fbsql_clob_size(), fbsql_commit(), fbsql_change_user(), fbsql_create_blob(), fbsql_create_db(), fbsql_create_clob(), fbsql_data_seek(), fbsql_database_password(), fbsql_database(), fbsql_db_query(), fbsql_db_status(), fbsql_drop_db(), fbsql_errno(), fbsql_error(), fbsql_get_autostart_info(), fbsql_hostname(), fbsql_insert_id(), fbsql_list_dbs(), fbsql_password(), fbsql_read_blob(), fbsql_read_clob(), fbsql_rollback(), fbsql_select_db(), fbsql_set_password(), fbsql_set_transaction(), fbsql_start_db(), fbsql_stop_db(), fbsql_username() | fbsql_close() | Łącze do bazy danych fbsql
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | Brak | Trwałe łącze do bazy danych fbsql
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | Wynik fbsql
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | Plik FDF
ftp | ftp_connect(), ftp_ssl_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site(), ftp_alloc(), ftp_chmod(), ftp_exec(), ftp_get_option(), ftp_nb_continue(), ftp_nb_fget(), ftp_nb_fput(), ftp_nb_get(), ftp_nb_put(), ftp_raw(), ftp_set_option() | ftp_close() | Strumień FTP
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatetruecolor() imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() | imagedestroy() | Biblioteka graficzna GD
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | Brak | Font dla biblioteki GD
gd PS encoding
Font gd PS | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | Font PS dla GD
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | Brak | Liczba GMP
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Obiekt Hyperwave
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Łącze do serwera Hyperwave
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | Brak | Trwałe łącze do serwera Hyperwave
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Łącze do serwera icap
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Łącze do serwerów IMAP, POP3
imap chain persistent
imap persistent
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Łącze do bazy danych ingresII
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | Brak | Trwałe łącze do bazy danych ingresII
interbase blob
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Łącze do bazy danych Interbase
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | Brak | Trwałe łącze do bazy danych Interbase
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Zapytanie Interbase
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Wynik Interbase
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Transakcja Interbase
java
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | Połączenie ldap
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | Wynik poszukiwania ldap
ldap result entry
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_Brak(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Łącze do serwera kalendarza
SWFAction
SWFBitmap
SWFButton
SWFDisplayItem
SWFFill
SWFFont
SWFGradient
SWFMorph
SWFMovie
SWFShape
SWFSprite
SWFText
SWFTextField
mnogosearch agent
mnogosearch result
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Łącze do bazy danych mSQL
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | Brak | Trwałe łącze do bazy danych mSQL
msql query | msql_db_query(), msql_list_dbs(), msql_list_fields(), msql_list_tables(), msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_field_seek(), msql_field_table(), msql_field_type(), msql_field_flags(), msql_field_len(), msql_field_type(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | Rezultat mSQL
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Łącze do bazy danych Microsoft SQL Server
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | Brak | Trwałe łącze do bazy danych Microsoft SQL Server
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Rezultat Microsoft SQL Server
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Łącze do bazy danych MySQL
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | Brak | Trwałe łącze do bazy danych MySQL
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_unbuffered_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | Rezultat MySQL
oci8 collection
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Łącze do bazy danych Oracle
oci8 descriptor
oci8 server
oci8 session
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Kursor Oracle
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Łącze do bazy danych ODBC
odbc link persistent | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | Brak | Trwałe łącze do bazy danych ODBC
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | Rezultat ODBC
birdstep link
birdstep result
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | Klucz OpenSSL
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Klucz Publiczny
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Kursor Oracle
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Łącze do bazy danych oracle
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | Brak | Trwałe łącze do bazy danych oracle
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_add_thumbnail(), pdf_arcn(), pdf_begin_pattern(), pdf_begin_template(), pdf_end_pattern(), pdf_end_template(), pdf_initgraphics(), pdf_makespotcolor(), pdf_set_info(), pdf_setcolor(), pdf_setmatrix(), pdf_open_memory_image() | pdf_close(), pdf_delete() | Dokument PDF
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Obrazek w pliku PDF
pdf object
pdf outline
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | Wielki Obiekt PostgreSQL
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Łącze do bazy danych PostgreSQL
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | Brak | Trwałe łącze do bazy danych PostgreSQL
pgsql result | pg_execute(), pg_query(), pg_query_params(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | Rezultat PostgreSQL
pgsql string
printer
printer brush
printer font
printer pen
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | Brak | Słownik pspell
pspell config | pspell_config_create() | pspell_new_config() | Brak | Konfiguracja pspell
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | Parser XSLT
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close()
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Gniazdo
sockets i/o vector
stream | opendir() | readdir(), rewinddir() | closedir() | Obsługa katalogów
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | Obsługa plików
stream | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Uchwyt procesów
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Uchwyt gnizada
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Łącze do bazy danych Sybase wykorzystujące bibliotekę DB
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | Brak | Trwałe łącze do bazy danych Sybase wykorzystujące bibliotekę DB
sybase-db result | sybase_query(), sybase_unbuffered_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Rezultat Sybase przy wykorzystaniu biblioteki DB
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Łącze do bazy danych Sybase przy wykorzystaniu biblioteki CT
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | Brak | Trwałe łącze do bazy danych Sybase przy wykorzystaniu biblioteki CT
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Rezultat Sybase przy wykorzystaniu biblioteki CT
sysvsem | sem_get() | sem_acquire() | sem_release() | Semafor System V
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | Pamięć współdzielona System V
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | Pakiet WDDX
xml | xml_parser_create(), xml_parser_create_ns() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | Parser XML
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | Plik skompresowany gz-compressed

Predefiniowane stałe
List of Available Filters
Dodatki


List of Available Filters

Spis treści

  • String Filters
  • Conversion Filters
  • Compression Filters
  • Encryption Filters

The following is a list of a few built-in stream filters for use with stream_filter_append(). Your version of PHP may have more filters (or fewer) than those listed here.

It is worth noting a slight asymmetry between stream_filter_append() and stream_filter_prepend(). Every PHP stream contains a small read buffer where it stores blocks of data retrieved from the filesystem or other resource in order to process data in the most efficient manner. As soon as data is pulled from the resource into the stream's internal buffer, it is immediately processed through any attached filters whether the PHP application is actually ready for the data or not. If data is sitting in the read buffer when a filter is appended, this data will be immediately processed through that filter making the fact that it was sitting in the buffer seem transparent. However, if data is sitting in the read buffer when a filter is prepended, this data will NOT be processed through that filter. It will instead wait until the next block of data is retrieved from the resource.

For a list of filters installed in your version of PHP use stream_get_filters().

Lista Rodzajów Zasobów
String Filters
Dodatki


String Filters

Each of these filters does precisely what their name implies and correspond to the behavior of a built-in php string handling function. For more information on a given filter, refer to the manual page for the corresponding function.

string.rot13 (since PHP 4.3.0) Use of this filter is equivalent to processing all stream data through the str_rot13() function.

Przykład #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Outputs:  Guvf vf n grfg.   */
?>

string.toupper (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strtoupper() function.

Przykład #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Outputs:  THIS IS A TEST.   */
?>

string.tolower (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strtolower() function.

Przykład #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Outputs:  this is a test.   */
?>

string.strip_tags (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strip_tags() function. It accepts parameters in one of two forms: Either as a string containing a list of tags similar to the second parameter of the strip_tags() function, or as an array of tag names.

Przykład #4 string.strip_tags

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<b><i><u>");
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs:  <b>bolded text</b> enlarged to a level 1 heading   */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs:  <b>bolded text</b> enlarged to a level 1 heading   */
?>
List of Available Filters
Conversion Filters
List of Available Filters


Conversion Filters

Like the string.* filters, the convert.* filters perform actions similar to their names. The convert filters were added with PHP 5.0.0. For more information on a given filter, refer to the manual page for the corresponding function.

convert.base64-encode and convert.base64-decode Use of these filters are equivalent to processing all stream data through the base64_encode() and base64_decode() functions respectively. convert.base64-encode supports parameters given as an associative array. If line-length is given, the base64 output will be split into chunks of line-length characters each. If line-break-chars is given, each chunk will be delimited by the characters given. These parameters give the same effect as using base64_encode() with chunk_split().

Przykład #1 convert.base64-encode & convert.base64-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBpcyBhIHRlc3QuCg==  */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBp
          :  cyBhIHRl
          :  c3QuCg==  */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Outputs:  This is a test.  */
?>

convert.quoted-printable-encode and convert.quoted-printable-decode Use of the decode version of this filter is equivalent to processing all stream data through the quoted_printable_decode() functions. There is no function equivalent to convert.quoted-printable-encode. convert.quoted-printable-encode supports parameters given as an associative array. In addition to the parameters supported by convert.base64-encode, convert.quoted-printable-encode also supports boolean arguments binary and force-encode-first. convert.base64-decode only supports the line-break-chars parameter as a type-hint for striping from the encoded payload.

Przykład #2 convert.quoted-printable-encode & convert.quoted-printable-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Outputs:  =This is a test.=0A  */
?>
String Filters
Compression Filters
List of Available Filters


Compression Filters

While the Compression Wrappers provide a way of creating gzip and bz2 compatible files on the local filesystem, they do not provide a means for generalized compression over network streams, nor do they provide a means to begin with a non-compressed stream and transition to a compressed one. For this, a compression filter may be applied to any stream resource at any time.

Informacja: Compression filters do not generate headers and trailers used by command line utilities such as gzip. They only compress and decompress the payload portions of compressed data streams.

zlib.deflate (compression) and zlib.inflate (decompression) are implementations of the compression methods described in » RFC 1951. The deflate filter takes up to three parameters passed as an associative array. level describes the compression strength to use (1-9). Higher numbers will generally yield smaller payloads at the cost of additional processing time. Two special compression levels also exist: 0 (for no compression at all), and -1 (zlib internal default -- currently 6). window is the base-2 log of the compression loopback window size. Higher values (up to 15 -- 32768 bytes) yield better compression at a cost of memory, while lower values (down to 9 -- 512 bytes) yield worse compression in a smaller memory footprint. Default window size is currently 15. memory is a scale indicating how much work memory should be allocated. Valid values range from 1 (minimal allocation) to 9 (maximum allocation). This memory allocation affects speed only and does not impact the size of the generated payload.

Informacja: Because compression level is the most commonly used parameter, it may be alternatively provided as a simple integer value (rather than an array element).

zlib.* compression filters are available with PHP as of version 5.1.0 if zlib support is enabled. They are also available as a backport in version 5.0.x by installing the » zlib_filter package from » PECL. These filters are not available for PHP 4.

Przykład #1 zlib.deflate and zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";
echo "The original text was:\n";
/* Use readfile and zlib.inflate to decompress on the fly */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.
The original text was:
This is a test.
This is only a test.
This is not an important string.

 */
?>

Przykład #2 zlib.deflate simple

<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
/* Here "6" indicates compression level 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.

 */
?>

bzip2.compress and bzip2.decompress work in the same manner as the zlib filters described above. The bzip2.compress filter accepts up to two parameters given as elements of an associative array: blocks is an integer value from 1 to 9 specifying the number of 100kbyte blocks of memory to allocate for workspace. work is also an integer value ranging from 0 to 250 indicating how much effort to expend using the normal compression method before falling back on a slower, but more reliable method. Tuning this parameter effects only compression speed. Neither size of compressed output nor memory usage are changed by this setting. A work factor of 0 instructs the bzip library to use an internal default. The bzip2.decompress filter only accepts one parameter, which can be passed as either an ordinary boolean value, or as the small element of an associative array. small, when set to a TRUE value, instructs the bzip library to perform decompression in a minimal memory footprint at the cost of speed.

bzip2.* compression filters are available with PHP as of version 5.1.0 if bz2 support is enabled. They are also available as a backport in version 5.0.x by installing the » bz2_filter package from » PECL. These filters are not available for PHP 4.

Przykład #3 bzip2.compress and bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "The original file is " . filesize('LICENSE') . " bytes long.\n";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "The compressed file is " . filesize('LICENSE.compressed') . " bytes long.\n";

/* Generates output:

The original text is 3288 characters long.
The compressed file is 1488 bytes long.

 */
?>
Conversion Filters
Encryption Filters
List of Available Filters


Encryption Filters

mcrypt.* and mdecrypt.* provide symmetric encryption and decryption using libmcrypt. Both sets of filters support the same algorithms available to mcrypt extension in the form of mcrypt.ciphername where ciphername is the name of the cipher as it would be passed to mcrypt_module_open(). The following five filter parameters are also available:

mcrypt filter parameters
Parameter | Required? | Default | Sample Values
mode | Optional | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Optional | ini_get('mcrypt.algorithms_dir') | Location of algorithms modules
modes_dir | Optional | ini_get('mcrypt.modes_dir') | Location of modes modules
iv | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher
key | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher

Przykład #1 Encrypting file output using 3DES

<?php
$passphrase = 'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) .
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);

$fp = fopen('secret-file.enc', 'wb');
stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'Secret secret secret data');
fclose($fp);
?>

Przykład #2 Reading an encrypted file

<?php
$passphrase = 'My secret';

/* Turn a human readable passphrase
 * into a reproducable iv/key pair
 */
$iv = substr(md5('iv'.$passphrase, true), 0, 8);
$key = substr(md5('pass1'.$passphrase, true) .
               md5('pass2'.$passphrase, true), 0, 24);
$opts = array('iv'=>$iv, 'key'=>$key);

$fp = fopen('secret-file.enc', 'rb');
stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);
$data = rtrim(stream_get_contents($fp));
fclose($fp);

echo $data;
?>
Compression Filters
List of Supported Socket Transports
List of Available Filters


List of Supported Socket Transports

Spis treści

  • Internet Domain: TCP, UDP, SSL, and TLS
  • Unix Domain: Unix and UDG

The following is a list of the various URL style socket transports that PHP has built-in for use with the streams based socket functions such as fsockopen(), and stream_socket_client(). These transports do not apply to the Sockets Extension.

For a list of transports installed in your version of PHP use stream_get_transports().

Encryption Filters
Internet Domain: TCP, UDP, SSL, and TLS
Dodatki


Internet Domain: TCP, UDP, SSL, and TLS

PHP 4, PHP 5. ssl:// & tls:// since PHP 4.3.0 sslv2:// & sslv3:// since PHP 5.0.2

Informacja: If no transport is specified, tcp:// will be assumed.

  • 127.0.0.1
  • fe80::1
  • www.example.com
  • tcp://127.0.0.1
  • tcp://fe80::1
  • tcp://www.example.com
  • udp://www.example.com
  • ssl://www.example.com
  • sslv2://www.example.com
  • sslv3://www.example.com
  • tls://www.example.com

Internet Domain sockets expect a port number in addition to a target address. In the case of fsockopen() this is specified in a second parameter and therefore does not impact the formatting of transport URL. With stream_socket_client() and related functions as with traditional URLs however, the port number is specified as a suffix of the transport URL delimited by a colon.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Informacja: IPv6 numeric addresses with port numbers
In the second example above, while the IPv4 and hostname examples are left untouched apart from the addition of their colon and portnumber, the IPv6 address is wrapped in square brackets: [fe80::1]. This is to distinguish between the colons used in an IPv6 address and the colon used to delimit the portnumber.

The ssl:// and tls:// transports (available only when openssl support is compiled into PHP) are extensions of the tcp:// transport which include SSL encryption. Since PHP 4.3.0 OpenSSL support must be statically compiled into PHP, since PHP 5.0.0 it may be compiled as a module or statically.

ssl:// will attempt to negotiate an SSL V2, or SSL V3 connection depending on the capabilities and preferences of the remote host. sslv2:// and sslv3:// will select the SSL V2 or SSL V3 protocol explicitly.

List of Supported Socket Transports
Unix Domain: Unix and UDG
List of Supported Socket Transports


Unix Domain: Unix and UDG

unix:// and udg:// (udg:// since PHP 5).

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix:// provides access to a socket stream connection in the Unix domain. udg:// provides an alternate transport to a Unix domain socket using the user datagram protocol.

Unix domain sockets, unlike Internet domain sockets, do not expect a port number. In the case of fsockopen() the portno parameter should be set to 0.

Internet Domain: TCP, UDP, SSL, and TLS
Tabele porównań typów PHP
List of Supported Socket Transports


Tabele porównań typów PHP

Poniższe tablice demonstrują zachowanie typów i operatorów porównania PHP, zarówno dla zwykłego i dokładnego porównania. Dodatek ten jest związany także z sekcją podręcznika dotyczącego żonglowania typami. Inspiracją do stworzenia takich tablic były komentarze użytkowników i praca w » BlueShoes.

Przed korzystaniem z tych tablic, niezbędne jest zrozumienie typów i ich znaczeń. Na przykład, "42" jest ciągiem znakowym (string), a 42 to liczba stałoprzecinkowa integer. FALSE jest typu boolean, "false" to string.

Informacja:

Formularze HTML nie przekazują zmiennych stałoprzecinkowych, zmiennoprzecinkowych czy typów logicznych. Zwracane są tylko stringi. Aby dowiedzieć się, czy string zawiera wartość liczbową, można skorzystać z funkcji is_numeric().

Informacja:

Proste wykonanie if ($x) w sytuacji, gdy zmienna $x jest niezdefiniowana, wygeneruje błąd poziomu E_NOTICE. Zamiast tego powinna być stosowana funkcja empty() lub isset(), i/lub zmienne powinny być inicjalizowane.

Porównanie zmiennej $x z funkcjami PHP
Wyrażenie | gettype() | empty() | is_null() | isset() | boolean : if($x)
$x = ""; | string | TRUE | FALSE | TRUE | FALSE
$x = null; | NULL | TRUE | TRUE | FALSE | FALSE
var $x; | NULL | TRUE | TRUE | FALSE | FALSE
$x jest niezdefiniowane | NULL | TRUE | TRUE | FALSE | FALSE
$x = array(); | array | TRUE | FALSE | TRUE | FALSE
$x = false; | boolean | TRUE | FALSE | TRUE | FALSE
$x = true; | boolean | FALSE | FALSE | TRUE | TRUE
$x = 1; | integer | FALSE | FALSE | TRUE | TRUE
$x = 42; | integer | FALSE | FALSE | TRUE | TRUE
$x = 0; | integer | TRUE | FALSE | TRUE | FALSE
$x = -1; | integer | FALSE | FALSE | TRUE | TRUE
$x = "1"; | string | FALSE | FALSE | TRUE | TRUE
$x = "0"; | string | TRUE | FALSE | TRUE | FALSE
$x = "-1"; | string | FALSE | FALSE | TRUE | TRUE
$x = "php"; | string | FALSE | FALSE | TRUE | TRUE
$x = "true"; | string | FALSE | FALSE | TRUE | TRUE
$x = "false"; | string | FALSE | FALSE | TRUE | TRUE

Porównania operatorem ==
 | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | ""
TRUE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE
FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE
1 | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
0 | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE
-1 | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
"1" | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"0" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE
"-1" | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
NULL | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | TRUE
array() | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | FALSE
"php" | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE
"" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE

Porównania operatorem ===
 | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | ""
TRUE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
1 | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
0 | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
-1 | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"1" | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"0" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE
"-1" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
NULL | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE
array() | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE
"php" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE
"" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE

Unix Domain: Unix and UDG
List of Parser Tokens
Dodatki


List of Parser Tokens

Various parts of the PHP language are represented internally by types like T_SR. PHP outputs identifiers like this one in parse errors, like "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."

You're supposed to know what T_SR means. For everybody who doesn't know that, here is a table with those identifiers, PHP-syntax and references to the appropriate places in the manual.

Informacja: Usage of T_* constants

All tokens listed below are also defined as PHP constants. Their value is automatically generated based on PHP's underlying parser infrastructure. This means that the concrete value of a token may change between two PHP versions. For example the T_FILE constant is 365 in PHP 5.3, while the same value refers now to T_TRAIT in PHP 5.4 and the value of T_FILE is 369. This means that your code should never rely directly on the original T_* values taken from PHP version X.Y.Z, to provide some compatibility across multiple PHP versions. Instead your code should utilize custom values (using big numbers like 10000) and an appropriate strategy that will work with both PHP versions and T_* values.

Tokens
Token | Syntax | Reference
T_ABSTRACT | abstract | Class Abstraction (available since PHP 5.0.0)
T_AND_EQUAL | &= | assignment operators
T_ARRAY | array() | array(), array syntax
T_ARRAY_CAST | (array) | type-casting
T_AS | as | foreach
T_BAD_CHARACTER |  | anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d)
T_BOOLEAN_AND | && | logical operators
T_BOOLEAN_OR | || | logical operators
T_BOOL_CAST | (bool) or (boolean) | type-casting
T_BREAK | break | break
T_CASE | case | switch
T_CATCH | catch | Exceptions (available since PHP 5.0.0)
T_CHARACTER |  | not used anymore
T_CLASS | class | classes and objects
T_CLASS_C | __CLASS__ | magic constants (available since PHP 4.3.0)
T_CLONE | clone | classes and objects (available since PHP 5.0.0)
T_CLOSE_TAG | ?> or %> | escaping from HTML
T_COMMENT | // or #, and /* */ in PHP 5 | comments
T_CONCAT_EQUAL | .= | assignment operators
T_CONST | const | class constants
T_CONSTANT_ENCAPSED_STRING | "foo" or 'bar' | string syntax
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | complex variable parsed syntax
T_DEC | -- | incrementing/decrementing operators
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIR | __DIR__ | magic constants (available since PHP 5.3.0)
T_DIV_EQUAL | /= | assignment operators
T_DNUMBER | 0.12, etc | floating point numbers
T_DOC_COMMENT | /** */ | PHPDoc style comments (available since PHP 5.0.0)
T_DO | do | do..while
T_DOLLAR_OPEN_CURLY_BRACES | ${ | complex variable parsed syntax
T_DOUBLE_ARROW | => | array syntax
T_DOUBLE_CAST | (real), (double) or (float) | type-casting
T_DOUBLE_COLON | :: | see T_PAAMAYIM_NEKUDOTAYIM below
T_ECHO | echo | echo()
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | constant part of string with variables
T_ENDDECLARE | enddeclare | declare, alternative syntax
T_ENDFOR | endfor | for, alternative syntax
T_ENDFOREACH | endforeach | foreach, alternative syntax
T_ENDIF | endif | if, alternative syntax
T_ENDSWITCH | endswitch | switch, alternative syntax
T_ENDWHILE | endwhile | while, alternative syntax
T_END_HEREDOC |  | heredoc syntax
T_EVAL | eval() | eval()
T_EXIT | exit or die | exit(), die()
T_EXTENDS | extends | extends, classes and objects
T_FILE | __FILE__ | magic constants
T_FINAL | final | Final Keyword (available since PHP 5.0.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function or cfunction | functions
T_FUNC_C | __FUNCTION__ | magic constants (available since PHP 4.3.0)
T_GLOBAL | global | variable scope
T_GOTO | goto | (available since PHP 5.3.0)
T_HALT_COMPILER | __halt_compiler() | __halt_compiler (available since PHP 5.1.0)
T_IF | if | if
T_IMPLEMENTS | implements | Object Interfaces (available since PHP 5.0.0)
T_INC | ++ | incrementing/decrementing operators
T_INCLUDE | include() | include()
T_INCLUDE_ONCE | include_once() | include_once()
T_INLINE_HTML |  | text outside PHP
T_INSTANCEOF | instanceof | type operators (available since PHP 5.0.0)
T_INT_CAST | (int) or (integer) | type-casting
T_INTERFACE | interface | Object Interfaces (available since PHP 5.0.0)
T_ISSET | isset() | isset()
T_IS_EQUAL | == | comparison operators
T_IS_GREATER_OR_EQUAL | >= | comparison operators
T_IS_IDENTICAL | === | comparison operators
T_IS_NOT_EQUAL | != or <> | comparison operators
T_IS_NOT_IDENTICAL | !== | comparison operators
T_IS_SMALLER_OR_EQUAL | <= | comparison operators
T_LINE | __LINE__ | magic constants
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc | integers
T_LOGICAL_AND | and | logical operators
T_LOGICAL_OR | or | logical operators
T_LOGICAL_XOR | xor | logical operators
T_METHOD_C | __METHOD__ | magic constants (available since PHP 5.0.0)
T_MINUS_EQUAL | -= | assignment operators
T_ML_COMMENT | /* and */ | comments (PHP 4 only)
T_MOD_EQUAL | %= | assignment operators
T_MUL_EQUAL | *= | assignment operators
T_NAMESPACE | namespace | namespaces (available since PHP 5.3.0)
T_NS_C | __NAMESPACE__ | namespaces (available since PHP 5.3.0)
T_NS_SEPARATOR | \ | namespaces (available since PHP 5.3.0)
T_NEW | new | classes and objects
T_NUM_STRING | "$a[0]" | numeric array index inside string
T_OBJECT_CAST | (object) | type-casting
T_OBJECT_OPERATOR | -> | classes and objects
T_OLD_FUNCTION | old_function | (PHP 4 only)
T_OPEN_TAG | <?php, <? or <% | escaping from HTML
T_OPEN_TAG_WITH_ECHO | <?= or <%= | escaping from HTML
T_OR_EQUAL | |= | assignment operators
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. Also defined as T_DOUBLE_COLON.
T_PLUS_EQUAL | += | assignment operators
T_PRINT | print() | print()
T_PRIVATE | private | classes and objects (available since PHP 5.0.0)
T_PUBLIC | public | classes and objects (available since PHP 5.0.0)
T_PROTECTED | protected | classes and objects (available since PHP 5.0.0)
T_REQUIRE | require() | require()
T_REQUIRE_ONCE | require_once() | require_once()
T_RETURN | return | returning values
T_SL | << | bitwise operators
T_SL_EQUAL | <<= | assignment operators
T_SR | >> | bitwise operators
T_SR_EQUAL | >>= | assignment operators
T_START_HEREDOC | <<< | heredoc syntax
T_STATIC | static | variable scope
T_STRING | "parent" | identifiers, e.g. strings, object oriented keywords like parent and self, functions, classes and more are matched.
T_STRING_CAST | (string) | type-casting
T_STRING_VARNAME | "${a | complex variable parsed syntax
T_SWITCH | switch | switch
T_THROW | throw | Exceptions (available since PHP 5.0.0)
T_TRY | try | Exceptions (available since PHP 5.0.0)
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | type-casting (available since PHP 5.0.0)
T_USE | use | namespaces (available since PHP 5.3.0; reserved since PHP 4.0.0)
T_VAR | var | classes and objects
T_VARIABLE | $foo | variables
T_WHILE | while | while, do..while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | assignment operators

See also token_name().

Tabele porównań typów PHP
Userland Naming Guide
Dodatki


Userland Naming Guide

Spis treści

  • Global Namespace
  • Rules
  • Tips

The following is a guide for how to best choose names for identifiers in userland PHP code. When choosing names for any code that creates symbols in the global namespace, it is important to take into account the following guidelines to prevent future versions of PHP from clashing with your symbols.

List of Parser Tokens
Global Namespace
Dodatki


Global Namespace

Here is an overview of code constructs that go into the global namespace:

  • functions

  • classes

  • interfaces

  • constants (not class constants)

  • variables defined outside of functions/methods

Userland Naming Guide
Rules
Userland Naming Guide


Rules

The following list gives an overview of which rights the PHP project reserves for itself, when choosing names for new internal identifiers. The definitive guide is the official » CODING STANDARDS:

  • PHP owns the top-level namespace but tries to find decent descriptive names and avoid any obvious clashes.

  • Function names use underscores between words, while class names use both the camelCase and PascalCase rules.

  • PHP will prefix any global symbols of an extension with the name of the extension. (In the past, there have been numerous exceptions to this rule.) Examples:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (example of a past mistake)

    • new SplFileObject()

  • Iterators and Exceptions are however simply postfixed with "Iterator" and "Exception." Examples:

    • ArrayIterator

    • LogicException

  • PHP reserves all symbols starting with __ as magical. It is recommended that you do not create symbols starting with __ in PHP unless you want to use documented magical functionality. Examples:

    • __get()

    • __autoload()

Global Namespace
Tips
Userland Naming Guide


Tips

In order to write future-proof code, it is recommended that you prefix (or suffix) anything that goes into the global namespace with an uncommon 3-4 letter prefix (or suffix) separated with an underscore. It is recommended that in order to prevent namespace clashes with other userland code that projects research existing prefixes (or suffixes) used in other projects and advertise their chosen prefix (or suffix) appropriately. Examples:

  • MyPx_someFunc()

  • Foo_Date

  • $asdf_dbh

Rules
About the manual
Userland Naming Guide


About the manual

Spis treści

  • Formats
  • About user notes
  • How to read a function definition (prototype)
  • PHP versions documented in this manual
  • How to find more information about PHP
  • How to help improve the documentation
  • How we generate the formats
  • Translations
Tips
Formats
Dodatki


Formats

The PHP manual is provided in several formats. These formats can be divided into two groups: online readable formats, and downloadable packages.

Informacja:

Some publishers have made available printed versions of this manual. We cannot recommend any of those, as they tend to become out-of-date very quickly.

The manual can be read online at the » PHP.net website, and on the numerous mirror sites. For best performance, choose the closest mirror. The online version of the PHP manual has currently two CSS stylesheets, web friendly and a printer-friendly stylesheet.

Two notable advantages of the online manual over most of the offline formats is the integration of user-contributed notes and the » URL shortcuts that may be used to get to the desired manual parts quickly. An obvious disadvantage is the requirement to be online to view this edition of the manual.

There are several offline formats of the manual, and the most appropriate format for depends on the operating system, and personal reading style. For information on how the manual is generated in so many formats, read the 'How we generate the formats' section of this appendix.

The most cross-platform format of the manual is the HTML version. This is provided both as a single HTML file and as a package of individual files for each section (which results in a collection of several thousand files). We provide these versions compressed, so a decompression utility is required to retrieve the files contained within the archives.

For Windows platforms, the Windows HTML Help version of the manual enhances the HTML format for use with the Windows HTML Help application. This version provides full-text search, a full index, and bookmarking. Many popular Windows PHP development environments also integrate with this version of the documentation to provide easy access. CHM viewers for Linux desktops are also available. Check out » xCHM or » GnoCHM.

There is also an » extended CHM version available, which is updated less frequently, but provides many additional features. It will only work on Microsoft Windows though, because of the technologies used to build the help pages.

About the manual
About user notes
About the manual


About user notes

The user-contributed notes play an important role in the development of this manual. By allowing readers of the manual to contribute examples, caveats, and further clarifications from their browser, we are able to incorporate that feedback into the main text of the manual. And until the notes have been incorporated, they may be viewed in their submitted form online, and in some of the offline formats.

Informacja:

The user-contributed notes are not moderated before they appear online, so the quality of the writing or code examples, and even the veracity of the contribution, cannot be guaranteed. (Not that there is any guarantee of the quality or accuracy of the manual text itself.)

Informacja:

For the purposes of license coverage the user-contributed notes are considered part of the PHP manual, and are therefore covered by the same license that covers this documentation (Creative Commons Attribution at the moment). For more details see the Manual's Copyright page.

Formats
How to read a function definition (prototype)
About the manual


How to read a function definition (prototype)

Each function in the manual is documented for quick reference. Knowing how to read and understand the text will make learning PHP much easier. Rather than relying on examples or cut/paste, everyone should know how to read function definitions (prototypes). Let's begin:

Informacja: Prerequisite: Basic understanding of types

Although PHP is a loosely typed language, it's important to have a basic understanding of types as they have important meaning.

Function definitions tell us what type of value is returned. Let's use the definition for strlen() as our first example:

strlen

(PHP 4, PHP 5)
strlen -- Get string length

Description
int strlen ( string $string )

Returns the length of given string.

Explanation of a function definition
Part | Description
strlen | The function name.
(PHP 4, PHP 5) | strlen() has been around in all versions of PHP 4 and PHP 5
int | Type of value this function returns, which is an integer (i.e. the length of a string is measured in numbers).
( string $string ) | The first (and in this case the only) parameter/argument for this function is named string, and it's a string.

We could rewrite the above function definition in a generic way:

      returned type    function name    ( parameter type   parameter name )

Many functions take on multiple parameters, such as in_array(). Its prototype is as follows:

      bool in_array ( mixed $needle, array $haystack [, bool $strict])

What does this mean? in_array() returns a boolean value, TRUE on success (if the needle was found in the haystack) lub FALSE w przypadku niepowodzenia (if the needle was not found in the haystack). The first parameter is named needle and it can be of many different types, so we call it "mixed". This mixed needle (what we're looking for) can be either a scalar value (string, integer, or float), or an array. haystack (the array we're searching in) is the second parameter. The third optional parameter is named strict. All optional parameters are seen in [ brackets ]. The manual states that the strict parameter defaults to boolean FALSE. See the manual page on each function for details on how they work.

There are also functions with more complex PHP version information. Take html_entity_decode() as an example:

(PHP 4 >= 4.3.0, PHP 5)

This means that this function has only been available in a released version since PHP 4.3.0.

About user notes
PHP versions documented in this manual
About the manual


PHP versions documented in this manual

The manual contains information about past, current, and future versions of PHP. Changes in behaviour are documented as notes, changelogs, and inline text within the manual pages. The earliest documented version is PHP 4.1.0, whereas the latest is PHP 5.x.x.

When documentation exists for the latest (unreleased) developmental versions of PHP, it will be labeled as either "available in SVN" or "development version." And while these changes should be planned for, in rare cases they may change.

All development takes place in Subversion (SVN) and may be checked out as described within the » anonymous SVN access page. Or, these same sources may be downloaded as » PHP snapshots, which are available for every active PHP branch.

And to clarify, the manual will refer to major, minor and point PHP releases. Using PHP 5.3.1 as an example, the 5 refers to the major version, 3 to minor, and 1 is the point release. Typically PHP only adds new features to major and minor releases, and fixes bugs in point releases. However, this convention is not always true.

Also note that the PHP manual is written in present tense, not future tense, even for documented features that are not yet available. The reason for this is so the manual can stand the test of time, thus not require tedious grammar updates with every PHP release.

Many times the PHP manual lists "Default Values" for PHP directives. These values are based on how PHP behaves without a php.ini configuration file, so this may differ from values found in the distributed php.ini-development and php.ini-production files. They also refer to the latest version of PHP, although changelog entries do mention past values. See the PHP directive appendix for details regarding these values and changes.

How to read a function definition (prototype)
How to find more information about PHP
About the manual


How to find more information about PHP

This manual does not attempt to provide instruction about general programming practices. First-time - or even just beginning - programmers may find it difficult to learn how to program in PHP using this manual exclusively. Instead, seek out a text more oriented towards beginners.

There are a number of active mailing lists for discussion on all aspects of programming with PHP. If stuck with a problem, consider using these lists. For support options, including mailing lists, view » the PHP.net support page. Furthermore, there is a list of websites devoted to PHP articles, forums, and code galleries at » the PHP.net links page.

PHP versions documented in this manual
How to help improve the documentation
About the manual


How to help improve the documentation

There are three ways everyone can help improve this documentation.

If an error is found in this manual, in any language, please report them using the bug system at » http://bugs.php.net/. Classify the bug as "Documentation Problem". All documentation related problems, including those about manual formats, should be submitted as bug reports.

Informacja:

Please don't abuse the bug system by submitting requests for help. Instead, use one of the many » support options.

By contributing notes, users may provide additional examples, caveats, and clarifications for other readers. But please do not submit bug reports using the annotation system. For details, see the section titled 'About user notes'.

The PHP manual is translated into many languages. Knowing English and a foreign language allows for another way to help improve the PHP manual by working with a translation team. For information about starting a new translation, or helping a currently translated version, please read » http://doc.php.net/php/dochowto/.

The PHP Documentation Project also has an IRC channel where many manual authors hang out. Stop by #php.doc on irc.efnet.org and discuss ways to improve the PHP documentation.

How to find more information about PHP
How we generate the formats
About the manual


How we generate the formats

This manual is written in XML using the » DocBook XML DTD, using » PhD (The [PH]P based [D]ocBook renderer) for maintenance and formatting.

Using XML as a source format gives the ability to generate many output formats from the source files, while only maintaining one source document for all formats. The tool used for formatting the online manual is » PhD. We use » Microsoft HTML Help Workshop to generate the Windows HTML Help format of the manual, and of course PHP itself to do some additional conversions and formatting.

The PHP manual is generated in various languages and formats, see » http://www.php.net/docs.php for additional details. The XML source code may be downloaded from SVN and viewed at » http://svn.php.net/viewvc/. The documentation is stored in the phpdoc module.

How to help improve the documentation
Translations
About the manual


Translations

The PHP manual is available not only in various formats, but also in various languages. The text of the manual is first written in English, then teams of people across the world take care of translating it to their native languages. If a translation for a specified function or chapter has not yet been made, the manual's build system falls back to the English version of it.

People involved in the translations start from the XML source code available from » http://svn.php.net/viewvc/ and from it they translate to their mother language. They do not use the generated versions (like HTML or plain text) as it's the build system that takes care of the conversions from XML to human readable formats.

Informacja:

To help translate the documentation, please get in touch with the translation/documentation team by subscribing to the phpdoc mailing list: send an empty mail to » phpdoc-subscribe@lists.php.net. The mailing list address is phpdoc@lists.php.net. State in the message an interest in translating the manual and someone will reply with feedback on moving forward by helping start a new language translation, or by contacting the existing team for the desired language.

At the moment the manual is available, partly or not, in over 10 languages.

They may all be downloaded here: » http://www.php.net/docs.php.

How we generate the formats
Creative Commons Attribution 3.0
About the manual


Creative Commons Attribution 3.0

THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  1. "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License.
  2. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined above) for the purposes of this License.
  3. "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership.
  4. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
  5. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work.
  6. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  7. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images.
  8. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium.

2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.

3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  1. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections;
  2. to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified.";
  3. to Distribute and Publicly Perform the Work including as incorporated in Collections; and,
  4. to Distribute and Publicly Perform Adaptations.

  5. For the avoidance of doubt:

    1. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License;
    2. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and,
    3. Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License.

The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved.

4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  1. You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(b), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(b), as requested.
  2. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Section 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4 (b) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.
  3. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination.

  1. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  2. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  1. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  2. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  3. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  4. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent
  5. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
  6. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law.
Translations
Indeks
Dodatki


Indeks

Spis treści

  • Wykaz funkcji i metod
  • Wykaz przykładów
Creative Commons Attribution 3.0
Wykaz funkcji i metod
Dodatki


Wykaz funkcji i metod

Lista wszystkich funkcji i metod zawartych w podręczniku PHP

  • a
    • abs - Wartość bezwględna (moduł z liczby)
    • acos - Oblicza arcus cosinus liczby
    • acosh - Area cosinus hiperboliczny
    • addcslashes - Quote string with slashes in a C style
    • addslashes - Quote string with slashes
    • aggregate - Dynamic class and object aggregation of methods and properties
    • aggregate_info - Gets aggregation information for a given object
    • aggregate_methods - Dynamic class and object aggregation of methods
    • aggregate_methods_by_list - Selective dynamic class methods aggregation to an object
    • aggregate_methods_by_regexp - Selective class methods aggregation to an object using a regular expression
    • aggregate_properties - Dynamic aggregation of class properties to an object
    • aggregate_properties_by_list - Selective dynamic class properties aggregation to an object
    • aggregate_properties_by_regexp - Selective class properties aggregation to an object using a regular expression
    • aggregation_info - Alias dla aggregate_info
    • AMQPConnection::connect - Establish a connection with the AMQP broker.
    • AMQPConnection::disconnect - Closes the connection with the AMQP broker.
    • AMQPConnection::isConnected - Determine if the AMQPConnection object is connected to the broker.
    • AMQPConnection::reconnect - Closes any open connection and creates a new connection with the AMQP broker.
    • AMQPConnection::setHost - Set the amqp host.
    • AMQPConnection::setLogin - Set the login.
    • AMQPConnection::setPassword - Set the password.
    • AMQPConnection::setPort - Set the port.
    • AMQPConnection::setVhost - Set the amqp virtual host
    • AMQPConnection::__construct - Create an instance of AMQPConnection
    • AMQPExchange::bind - The bind purpose
    • AMQPExchange::declare - Declare a new exchange on the broker.
    • AMQPExchange::delete - Delete the exchange from the broker.
    • AMQPExchange::publish - Publish a message to an exchange.
    • AMQPExchange::__construct - Create an instance of AMQPExchange
    • AMQPQueue::ack - Acknowledge the receipt of a message
    • AMQPQueue::bind - Bind the given queue to a routing key on an exchange.
    • AMQPQueue::cancel - Cancel a queue binding.
    • AMQPQueue::consume - The consume purpose
    • AMQPQueue::declare - Declare a new queue
    • AMQPQueue::delete - Delete a queue and its contents.
    • AMQPQueue::get - Retrieve the next message from the queue.
    • AMQPQueue::purge - Purge the contents of a queue
    • AMQPQueue::unbind - Unbind the queue from a routing key.
    • AMQPQueue::__construct - Create an instance of an AMQPQueue object.
    • apache_child_terminate - Zakańcza proces Apache'a po zakończeniu tego zapytania
    • apache_getenv - Get an Apache subprocess_env variable
    • apache_get_modules - Get a list of loaded Apache modules
    • apache_get_version - Fetch Apache version
    • apache_lookup_uri - Wywołuje wewnętrzne żądanie dla określonego URI i zwraca całą informację o nim
    • apache_note - Pobiera lub ustawia noty odpowiedzi Apache'a
    • apache_request_headers - Fetch all HTTP request headers
    • apache_reset_timeout - Reset the Apache write timer
    • apache_response_headers - Pobiera wszystkie nagłówki HTTP odpowiedzi serwera
    • apache_setenv - Ustawia zmienną Apache'a subprocess_env
    • APCIterator::current - Get current item
    • APCIterator::getTotalCount - Get total count
    • APCIterator::getTotalHits - Get total cache hits
    • APCIterator::getTotalSize - Get total cache size
    • APCIterator::key - Get iterator key
    • APCIterator::next - Move pointer to next item
    • APCIterator::rewind - Rewinds iterator
    • APCIterator::valid - Checks if current position is valid
    • APCIterator::__construct - Constructs an APCIterator iterator object
    • apc_add - Cache a variable in the data store
    • apc_bin_dump - Get a binary dump of the given files and user variables
    • apc_bin_dumpfile - Output a binary dump of cached files and user variables to a file
    • apc_bin_load - Load a binary dump into the APC file/user cache
    • apc_bin_loadfile - Load a binary dump from a file into the APC file/user cache
    • apc_cache_info - Retrieves cached information from APC's data store
    • apc_cas - Updates an old value with a new value
    • apc_clear_cache - Clears the APC cache
    • apc_compile_file - Stores a file in the bytecode cache, bypassing all filters.
    • apc_dec - Decrease a stored number
    • apc_define_constants - Defines a set of constants for retrieval and mass-definition
    • apc_delete - Removes a stored variable from the cache
    • apc_delete_file - Deletes files from the opcode cache
    • apc_exists - Checks if APC key exists
    • apc_fetch - Fetch a stored variable from the cache
    • apc_inc - Increase a stored number
    • apc_load_constants - Loads a set of constants from the cache
    • apc_sma_info - Retrieves APC's Shared Memory Allocation information
    • apc_store - Cache a variable in the data store
    • apd_breakpoint - Stops the interpreter and waits on a CR from the socket
    • apd_callstack - Returns the current call stack as an array
    • apd_clunk - Throw a warning and a callstack
    • apd_continue - Restarts the interpreter
    • apd_croak - Throw an error, a callstack and then exit
    • apd_dump_function_table - Outputs the current function table
    • apd_dump_persistent_resources - Return all persistent resources as an array
    • apd_dump_regular_resources - Return all current regular resources as an array
    • apd_echo - Echo to the debugging socket
    • apd_get_active_symbols - Get an array of the current variables names in the local scope
    • apd_set_pprof_trace - Starts the session debugging
    • apd_set_session - Changes or sets the current debugging level
    • apd_set_session_trace - Starts the session debugging
    • apd_set_session_trace_socket - Starts the remote session debugging
    • AppendIterator::append - Appends an iterator
    • AppendIterator::current - Gets the current value
    • AppendIterator::getArrayIterator - The getArrayIterator method
    • AppendIterator::getInnerIterator - Gets an inner iterator
    • AppendIterator::getIteratorIndex - Gets an index of iterators
    • AppendIterator::key - Gets the current key
    • AppendIterator::next - Moves to the next element
    • AppendIterator::rewind - Rewinds the Iterator
    • AppendIterator::valid - Checks validity of the current element
    • AppendIterator::__construct - Constructs an AppendIterator
    • array - Stwórz tablicę
    • ArrayAccess::offsetExists - Whether a offset exists
    • ArrayAccess::offsetGet - Offset to retrieve
    • ArrayAccess::offsetSet - Offset to set
    • ArrayAccess::offsetUnset - Offset to unset
    • ArrayIterator::append - Append an element
    • ArrayIterator::asort - Sort array by values
    • ArrayIterator::count - Count elements
    • ArrayIterator::current - Return current array entry
    • ArrayIterator::getArrayCopy - Get array copy
    • ArrayIterator::getFlags - Get flags
    • ArrayIterator::key - Return current array key
    • ArrayIterator::ksort - Sort array by keys
    • ArrayIterator::natcasesort - Sort an array naturally, case insensitive
    • ArrayIterator::natsort - Sort an array naturally
    • ArrayIterator::next - Move to next entry
    • ArrayIterator::offsetExists - Check if offset exists
    • ArrayIterator::offsetGet - Get value for an offset
    • ArrayIterator::offsetSet - Set value for an offset
    • ArrayIterator::offsetUnset - Unset value for an offset
    • ArrayIterator::rewind - Rewind array back to the start
    • ArrayIterator::seek - Seek to position
    • ArrayIterator::serialize - Serialize
    • ArrayIterator::setFlags - Set behaviour flags
    • ArrayIterator::uasort - User defined sort
    • ArrayIterator::uksort - User defined sort
    • ArrayIterator::unserialize - Unserialize
    • ArrayIterator::valid - Check whether array contains more entries
    • ArrayIterator::__construct - Construct an ArrayIterator
    • ArrayObject::append - Appends the value
    • ArrayObject::asort - Sort the entries by value
    • ArrayObject::count - Get the number of public properties in the ArrayObject
    • ArrayObject::exchangeArray - Exchange the array for another one.
    • ArrayObject::getArrayCopy - Creates a copy of the ArrayObject.
    • ArrayObject::getFlags - Gets the behavior flags.
    • ArrayObject::getIterator - Create a new iterator from an ArrayObject instance
    • ArrayObject::getIteratorClass - Gets the iterator classname for the ArrayObject.
    • ArrayObject::ksort - Sort the entries by key
    • ArrayObject::natcasesort - Sort an array using a case insensitive "natural order" algorithm
    • ArrayObject::natsort - Sort entries using a "natural order" algorithm
    • ArrayObject::offsetExists - Returns whether the requested index exists
    • ArrayObject::offsetGet - Returns the value at the specified index
    • ArrayObject::offsetSet - Sets the value at the specified index to newval
    • ArrayObject::offsetUnset - Unsets the value at the specified index
    • ArrayObject::serialize - Serialize an ArrayObject
    • ArrayObject::setFlags - Sets the behavior flags.
    • ArrayObject::setIteratorClass - Sets the iterator classname for the ArrayObject.
    • ArrayObject::uasort - Sort the entries with a user-defined comparison function and maintain key association
    • ArrayObject::uksort - Sort the entries by keys using a user-defined comparison function
    • ArrayObject::unserialize - Unserialize an ArrayObject
    • ArrayObject::__construct - Construct a new array object
    • array_change_key_case - Zwraca tablicę ze wszystkimi kluczami tekstowymi zamienionymi na wyłącznie małe lub wyłącznie duże litery
    • array_chunk - Podziel tablicę na kawałki
    • array_combine - Tworzy tablicę używając wartości jednej tablicy jako kluczy a drugiej jako wartości
    • array_count_values - Zlicza wszystkie wartości w tablicy
    • array_diff - Zwraca różnice pomiędzy tablicami
    • array_diff_assoc - Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
    • array_diff_key - Oblicza różnicę tablic używając kluczy do porównań
    • array_diff_uassoc - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey - Oblicza różnicę tablic używając funkcji zwrotnej do porównywania kluczy
    • array_fill - Wypełnij tablicę podanymi wartościami
    • array_fill_keys - Fill an array with values, specifying keys
    • array_filter - Filtruje elementy przy użyciu funkcji zwrotnej
    • array_flip - Wymienia wszystkie klucze z przypisanymi do nich wartościami w tablicy
    • array_intersect - Zwraca przecięcie tablic
    • array_intersect_assoc - Wylicza przecięcie tablic z dodatkowym sprawdzaniem indeksów
    • array_intersect_key - Computes the intersection of arrays using keys for comparison
    • array_intersect_uassoc - Computes the intersection of arrays with additional index check, compares indexes by a callback function
    • array_intersect_ukey - Computes the intersection of arrays using a callback function on the keys for comparison
    • array_keys - Zwraca wszystkie klucze z tablicy
    • array_key_exists - Sprawdza czy podany klucz lub indeks istnieje w tablicy
    • array_map - Wykonuje funkcję zwrotną na elementach podanej tablicy
    • array_merge - Łączy jedną lub więcej tablic
    • array_merge_recursive - Łączy dwie lub więcej tablic rekurencyjnie
    • array_multisort - Sortuje wiele tablic lub wielowymiarowe tablice
    • array_pad - Dopełnij tablicę do podanej długości podanymi wartościami
    • array_pop - Zdejmij element z końca tablicy
    • array_product - Calculate the product of values in an array
    • array_push - Wstaw jeden lub więcej elementów na koniec tablicy
    • array_rand - Wybierz jeden lub więcej losowych elementów z tablicy
    • array_reduce - Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji zwrotnej
    • array_replace - Replaces elements from passed arrays into the first array
    • array_replace_recursive - Replaces elements from passed arrays into the first array recursively
    • array_reverse - Zwraca tablicę z elementami ustawionymi w porządku odwrotnym
    • array_search - Przeszukuje tablicę pod kątem podanej wartości i w przypadku sukcesu zwraca odpowiedni klucz
    • array_shift - Usuń element z początku tablicy
    • array_slice - Wytnij kawałek tablicy
    • array_splice - Usuń część tablicy i zamień ją na coś innego
    • array_sum - Oblicza sumę wartości w tablicy
    • array_udiff - Computes the difference of arrays by using a callback function for data comparison
    • array_udiff_assoc - Computes the difference of arrays with additional index check, compares data by a callback function
    • array_udiff_uassoc - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
    • array_uintersect - Computes the intersection of arrays, compares data by a callback function
    • array_uintersect_assoc - Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
    • array_uintersect_uassoc - Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
    • array_unique - Usuwa duplikaty wartości z tablicy
    • array_unshift - Wstaw jeden lub więcej elementów na początek tablicy
    • array_values - Zwraca wszystkie wartości z tablicy
    • array_walk - Zastosuj funkcję użytkownika do każdego elementu tablicy
    • array_walk_recursive - Apply a user function recursively to every member of an array
    • arsort - Sortuje tablicę w porządku odwrotnym z zachowaniem skojarzenia kluczy
    • asin - Oblicza arcus sinus liczby
    • asinh - Area sinus hiperboliczny
    • asort - Posortuj tablicę zachowując skojarzenia kluczy
    • assert - Checks if assertion is FALSE
    • assert_options - Set/get the various assert flags
    • atan - Oblicza arcus tangens liczby
    • atan2 - Arcus tangens dwóch zmiennych
    • atanh - Area tangens hiperboliczny
  • b
    • base64_decode - Dekoduje dane zakodowane algorytmem MIME base64
    • base64_encode - Koduje dane za pomocą algorytmu MIME base64
    • basename - Zwraca nazwę pliku, będącego składową ścieżki
    • base_convert - Konwertuje liczbę pomiędzy różnymi systemami liczbowymi
    • bbcode_add_element - Adds a bbcode element
    • bbcode_add_smiley - Adds a smiley to the parser
    • bbcode_create - Create a BBCode Resource
    • bbcode_destroy - Close BBCode_container resource
    • bbcode_parse - Parse a string following a given rule set
    • bbcode_set_arg_parser - Attach another parser in order to use another rule set for argument parsing
    • bbcode_set_flags - Set or alter parser options
    • bcadd - Dodaje dwie liczby o dużej precyzji
    • bccomp - Porównuje dwie liczby o dużej precyzji
    • bcdiv - Dzieli dwie liczby o dużej precyzji
    • bcmod - Dzieli w module liczbę o dużej precyzji
    • bcmul - Mnoży dwie liczby o dużej precyzji
    • bcompiler_load - Reads and creates classes from a bz compressed file
    • bcompiler_load_exe - Reads and creates classes from a bcompiler exe file
    • bcompiler_parse_class - Reads the bytecodes of a class and calls back to a user function
    • bcompiler_read - Reads and creates classes from a filehandle
    • bcompiler_write_class - Writes an defined class as bytecodes
    • bcompiler_write_constant - Writes a defined constant as bytecodes
    • bcompiler_write_exe_footer - Writes the start pos, and sig to the end of a exe type file
    • bcompiler_write_file - Writes a php source file as bytecodes
    • bcompiler_write_footer - Writes the single character \x00 to indicate End of compiled data
    • bcompiler_write_function - Writes an defined function as bytecodes
    • bcompiler_write_functions_from_file - Writes all functions defined in a file as bytecodes
    • bcompiler_write_header - Writes the bcompiler header
    • bcompiler_write_included_filename - Writes an included file as bytecodes
    • bcpow - Podnosi liczbę o dużej precyzji do potęgi
    • bcpowmod - Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale - Ustala domyślną precyzję obliczeń BCMath
    • bcsqrt - Wyciąga pierwiastek kwadratowy z liczby o dużej precyzji
    • bcsub - Odejmuje jedną liczbę o dużej precyzji od drugiej
    • bin2hex - Convert binary data into hexadecimal representation
    • bindec - Konwertuje liczbę dwójkową na dziesiętną
    • bindtextdomain - Sets the path for a domain
    • bind_textdomain_codeset - Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
    • bson_decode - Deserializes a BSON object into a PHP array
    • bson_encode - Serializes a PHP variable into a BSON string
    • 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
  • c
    • CachingIterator::count - The number of elements in the iterator
    • CachingIterator::current - Return the current element
    • CachingIterator::getCache - The getCache purpose
    • CachingIterator::getFlags - Get flags used
    • CachingIterator::getInnerIterator - Returns the inner iterator
    • CachingIterator::hasNext - Check whether the inner iterator has a valid next element
    • CachingIterator::key - Return the key for the current element
    • CachingIterator::next - Move the iterator forward
    • CachingIterator::offsetExists - The offsetExists purpose
    • CachingIterator::offsetGet - The offsetGet purpose
    • CachingIterator::offsetSet - The offsetSet purpose
    • CachingIterator::offsetUnset - The offsetUnset purpose
    • CachingIterator::rewind - Rewind the iterator
    • CachingIterator::setFlags - The setFlags purpose
    • CachingIterator::valid - Check whether the current element is valid
    • CachingIterator::__construct - Construct a new CachingIterator object for the iterator.
    • CachingIterator::__toString - Return the string representation of the current element
    • Cairo::availableFonts - Retrieves the availables font types
    • Cairo::availableSurfaces - Retrieves all available surfaces
    • Cairo::statusToString - Retrieves the current status as string
    • Cairo::version - Retrives cairo's library version
    • Cairo::versionString - Retrieves cairo version as string
    • CairoContext::appendPath - Appends a path to current path
    • CairoContext::arc - Adds a circular arc
    • CairoContext::arcNegative - Adds a negative arc
    • CairoContext::clip - Establishes a new clip region
    • CairoContext::clipExtents - Computes the area inside the current clip
    • CairoContext::clipPreserve - Establishes a new clip region from the current clip
    • CairoContext::clipRectangleList - Retrieves the current clip as a list of rectangles
    • CairoContext::closePath - Closes the current path
    • CairoContext::copyPage - Emits the current page
    • CairoContext::copyPath - Creates a copy of the current path
    • CairoContext::copyPathFlat - Gets a flattened copy of the current path
    • CairoContext::curveTo - Adds a curve
    • CairoContext::deviceToUser - Transform a coordinate
    • CairoContext::deviceToUserDistance - Transform a distance
    • CairoContext::fill - Fills the current path
    • CairoContext::fillExtents - Computes the filled area
    • CairoContext::fillPreserve - Fills and preserve the current path
    • CairoContext::fontExtents - Get the font extents
    • CairoContext::getAntialias - Retrives the current antialias mode
    • CairoContext::getCurrentPoint - The getCurrentPoint purpose
    • CairoContext::getDash - The getDash purpose
    • CairoContext::getDashCount - The getDashCount purpose
    • CairoContext::getFillRule - The getFillRule purpose
    • CairoContext::getFontFace - The getFontFace purpose
    • CairoContext::getFontMatrix - The getFontMatrix purpose
    • CairoContext::getFontOptions - The getFontOptions purpose
    • CairoContext::getGroupTarget - The getGroupTarget purpose
    • CairoContext::getLineCap - The getLineCap purpose
    • CairoContext::getLineJoin - The getLineJoin purpose
    • CairoContext::getLineWidth - The getLineWidth purpose
    • CairoContext::getMatrix - The getMatrix purpose
    • CairoContext::getMiterLimit - The getMiterLimit purpose
    • CairoContext::getOperator - The getOperator purpose
    • CairoContext::getScaledFont - The getScaledFont purpose
    • CairoContext::getSource - The getSource purpose
    • CairoContext::getTarget - The getTarget purpose
    • CairoContext::getTolerance - The getTolerance purpose
    • CairoContext::glyphPath - The glyphPath purpose
    • CairoContext::hasCurrentPoint - The hasCurrentPoint purpose
    • CairoContext::identityMatrix - The identityMatrix purpose
    • CairoContext::inFill - The inFill purpose
    • CairoContext::inStroke - The inStroke purpose
    • CairoContext::lineTo - The lineTo purpose
    • CairoContext::mask - The mask purpose
    • CairoContext::maskSurface - The maskSurface purpose
    • CairoContext::moveTo - The moveTo purpose
    • CairoContext::newPath - The newPath purpose
    • CairoContext::newSubPath - The newSubPath purpose
    • CairoContext::paint - The paint purpose
    • CairoContext::paintWithAlpha - The paintWithAlpha purpose
    • CairoContext::pathExtents - The pathExtents purpose
    • CairoContext::popGroup - The popGroup purpose
    • CairoContext::popGroupToSource - The popGroupToSource purpose
    • CairoContext::pushGroup - The pushGroup purpose
    • CairoContext::pushGroupWithContent - The pushGroupWithContent purpose
    • CairoContext::rectangle - The rectangle purpose
    • CairoContext::relCurveTo - The relCurveTo purpose
    • CairoContext::relLineTo - The relLineTo purpose
    • CairoContext::relMoveTo - The relMoveTo purpose
    • CairoContext::resetClip - The resetClip purpose
    • CairoContext::restore - The restore purpose
    • CairoContext::rotate - The rotate purpose
    • CairoContext::save - The save purpose
    • CairoContext::scale - The scale purpose
    • CairoContext::selectFontFace - The selectFontFace purpose
    • CairoContext::setAntialias - The setAntialias purpose
    • CairoContext::setDash - The setDash purpose
    • CairoContext::setFillRule - The setFillRule purpose
    • CairoContext::setFontFace - The setFontFace purpose
    • CairoContext::setFontMatrix - The setFontMatrix purpose
    • CairoContext::setFontOptions - The setFontOptions purpose
    • CairoContext::setFontSize - The setFontSize purpose
    • CairoContext::setLineCap - The setLineCap purpose
    • CairoContext::setLineJoin - The setLineJoin purpose
    • CairoContext::setLineWidth - The setLineWidth purpose
    • CairoContext::setMatrix - The setMatrix purpose
    • CairoContext::setMiterLimit - The setMiterLimit purpose
    • CairoContext::setOperator - The setOperator purpose
    • CairoContext::setScaledFont - The setScaledFont purpose
    • CairoContext::setSource - The setSource purpose
    • CairoContext::setSourceRGB - The setSourceRGB purpose
    • CairoContext::setSourceRGBA - The setSourceRGBA purpose
    • CairoContext::setSourceSurface - The setSourceSurface purpose
    • CairoContext::setTolerance - The setTolerance purpose
    • CairoContext::showPage - The showPage purpose
    • CairoContext::showText - The showText purpose
    • CairoContext::status - The status purpose
    • CairoContext::stroke - The stroke purpose
    • CairoContext::strokeExtents - The strokeExtents purpose
    • CairoContext::strokePreserve - The strokePreserve purpose
    • CairoContext::textExtents - The textExtents purpose
    • CairoContext::textPath - The textPath purpose
    • CairoContext::transform - The transform purpose
    • CairoContext::translate - The translate purpose
    • CairoContext::userToDevice - The userToDevice purpose
    • CairoContext::userToDeviceDistance - The userToDeviceDistance purpose
    • CairoContext::__construct - Creates a new CairoContext
    • CairoFontFace::getType - Retrieves the font face type
    • CairoFontFace::status - Check for CairoFontFace errors
    • CairoFontFace::__construct - Creates a new CairoFontFace object
    • CairoFontOptions::equal - The equal purpose
    • CairoFontOptions::getAntialias - The getAntialias purpose
    • CairoFontOptions::getHintMetrics - The getHintMetrics purpose
    • CairoFontOptions::getHintStyle - The getHintStyle purpose
    • CairoFontOptions::getSubpixelOrder - The getSubpixelOrder purpose
    • CairoFontOptions::hash - The hash purpose
    • CairoFontOptions::merge - The merge purpose
    • CairoFontOptions::setAntialias - The setAntialias purpose
    • CairoFontOptions::setHintMetrics - The setHintMetrics purpose
    • CairoFontOptions::setHintStyle - The setHintStyle purpose
    • CairoFontOptions::setSubpixelOrder - The setSubpixelOrder purpose
    • CairoFontOptions::status - The status purpose
    • CairoFontOptions::__construct - The __construct purpose
    • CairoFormat::strideForWidth - Provides an appropiate stride to use
    • CairoGradientPattern::addColorStopRgb - The addColorStopRgb purpose
    • CairoGradientPattern::addColorStopRgba - The addColorStopRgba purpose
    • CairoGradientPattern::getColorStopCount - The getColorStopCount purpose
    • CairoGradientPattern::getColorStopRgba - The getColorStopRgba purpose
    • CairoGradientPattern::getExtend - The getExtend purpose
    • CairoGradientPattern::setExtend - The setExtend purpose
    • CairoImageSurface::createForData - The createForData purpose
    • CairoImageSurface::createFromPng - Creates a new CairoImageSurface form a png image file
    • CairoImageSurface::getData - Gets the image data as string
    • CairoImageSurface::getFormat - Get the image format
    • CairoImageSurface::getHeight - Retrieves the height of the CairoImageSurface
    • CairoImageSurface::getStride - The getStride purpose
    • CairoImageSurface::getWidth - Retrieves the width of the CairoImageSurface
    • CairoImageSurface::__construct - Creates a new CairoImageSurface
    • CairoLinearGradient::getPoints - The getPoints purpose
    • CairoLinearGradient::__construct - The __construct purpose
    • CairoMatrix::initIdentity - Creates a new identity matrix
    • CairoMatrix::initRotate - Creates a new rotated matrix
    • CairoMatrix::initScale - Creates a new scaling matrix
    • CairoMatrix::initTranslate - Creates a new translation matrix
    • CairoMatrix::invert - The invert purpose
    • CairoMatrix::multiply - The multiply purpose
    • CairoMatrix::rotate - The rotate purpose
    • CairoMatrix::scale - Applies scaling to a matrix
    • CairoMatrix::transformDistance - The transformDistance purpose
    • CairoMatrix::transformPoint - The transformPoint purpose
    • CairoMatrix::translate - The translate purpose
    • CairoMatrix::__construct - Creates a new CairoMatrix object
    • CairoPattern::getMatrix - The getMatrix purpose
    • CairoPattern::getType - The getType purpose
    • CairoPattern::setMatrix - The setMatrix purpose
    • CairoPattern::status - The status purpose
    • CairoPattern::__construct - The __construct purpose
    • CairoPdfSurface::setSize - The setSize purpose
    • CairoPdfSurface::__construct - The __construct purpose
    • CairoPsSurface::dscBeginPageSetup - The dscBeginPageSetup purpose
    • CairoPsSurface::dscBeginSetup - The dscBeginSetup purpose
    • CairoPsSurface::dscComment - The dscComment purpose
    • CairoPsSurface::getEps - The getEps purpose
    • CairoPsSurface::getLevels - The getLevels purpose
    • CairoPsSurface::levelToString - The levelToString purpose
    • CairoPsSurface::restrictToLevel - The restrictToLevel purpose
    • CairoPsSurface::setEps - The setEps purpose
    • CairoPsSurface::setSize - The setSize purpose
    • CairoPsSurface::__construct - The __construct purpose
    • CairoRadialGradient::getCircles - The getCircles purpose
    • CairoRadialGradient::__construct - The __construct purpose
    • CairoScaledFont::extents - The extents purpose
    • CairoScaledFont::getCtm - The getCtm purpose
    • CairoScaledFont::getFontFace - The getFontFace purpose
    • CairoScaledFont::getFontMatrix - The getFontMatrix purpose
    • CairoScaledFont::getFontOptions - The getFontOptions purpose
    • CairoScaledFont::getScaleMatrix - The getScaleMatrix purpose
    • CairoScaledFont::getType - The getType purpose
    • CairoScaledFont::glyphExtents - The glyphExtents purpose
    • CairoScaledFont::status - The status purpose
    • CairoScaledFont::textExtents - The textExtents purpose
    • CairoScaledFont::__construct - The __construct purpose
    • CairoSolidPattern::getRgba - The getRgba purpose
    • CairoSolidPattern::__construct - The __construct purpose
    • CairoSurface::copyPage - The copyPage purpose
    • CairoSurface::createSimilar - The createSimilar purpose
    • CairoSurface::finish - The finish purpose
    • CairoSurface::flush - The flush purpose
    • CairoSurface::getContent - The getContent purpose
    • CairoSurface::getDeviceOffset - The getDeviceOffset purpose
    • CairoSurface::getFontOptions - The getFontOptions purpose
    • CairoSurface::getType - The getType purpose
    • CairoSurface::markDirty - The markDirty purpose
    • CairoSurface::markDirtyRectangle - The markDirtyRectangle purpose
    • CairoSurface::setDeviceOffset - The setDeviceOffset purpose
    • CairoSurface::setFallbackResolution - The setFallbackResolution purpose
    • CairoSurface::showPage - The showPage purpose
    • CairoSurface::status - The status purpose
    • CairoSurface::writeToPng - The writeToPng purpose
    • CairoSurface::__construct - The __construct purpose
    • CairoSurfacePattern::getExtend - The getExtend purpose
    • CairoSurfacePattern::getFilter - The getFilter purpose
    • CairoSurfacePattern::getSurface - The getSurface purpose
    • CairoSurfacePattern::setExtend - The setExtend purpose
    • CairoSurfacePattern::setFilter - The setFilter purpose
    • CairoSurfacePattern::__construct - The __construct purpose
    • CairoSvgSurface::getVersions - Used to retrieve a list of supported SVG versions
    • CairoSvgSurface::restrictToVersion - The restrictToVersion purpose
    • CairoSvgSurface::versionToString - The versionToString purpose
    • CairoSvgSurface::__construct - The __construct purpose
    • cairo_create - Returns a new CairoContext object on the requested surface.
    • cairo_font_face_get_type - Description
    • cairo_font_options_create - Description
    • cairo_font_options_equal - Description
    • cairo_font_options_get_antialias - Description
    • cairo_font_options_get_hint_metrics - Description
    • cairo_font_options_get_hint_style - Description
    • cairo_font_options_get_subpixel_order - Description
    • cairo_font_options_hash - Description
    • cairo_font_options_merge - Description
    • cairo_font_options_set_antialias - Description
    • cairo_font_options_set_hint_metrics - Description
    • cairo_font_options_set_hint_style - Description
    • cairo_font_options_set_subpixel_order - Description
    • cairo_font_options_status - Description
    • cairo_format_stride_for_width - Description
    • cairo_image_surface_create - Description
    • cairo_image_surface_create_for_data - Description
    • cairo_image_surface_create_from_png - Description
    • cairo_image_surface_get_data - Description
    • cairo_image_surface_get_format - Description
    • cairo_image_surface_get_height - Description
    • cairo_image_surface_get_stride - Description
    • cairo_image_surface_get_width - Description
    • cairo_matrix_create_translate - Alias dla CairoMatrix::initTranslate
    • cairo_matrix_invert - Description
    • cairo_matrix_multiply - Description
    • cairo_matrix_rotate - Description
    • cairo_matrix_transform_distance - Description
    • cairo_matrix_transform_point - Description
    • cairo_matrix_translate - Description
    • cairo_pattern_add_color_stop_rgb - Description
    • cairo_pattern_add_color_stop_rgba - Description
    • cairo_pattern_create_for_surface - Description
    • cairo_pattern_create_linear - Description
    • cairo_pattern_create_radial - Description
    • cairo_pattern_create_rgb - Description
    • cairo_pattern_create_rgba - Description
    • cairo_pattern_get_color_stop_count - Description
    • cairo_pattern_get_color_stop_rgba - Description
    • cairo_pattern_get_extend - Description
    • cairo_pattern_get_filter - Description
    • cairo_pattern_get_linear_points - Description
    • cairo_pattern_get_matrix - Description
    • cairo_pattern_get_radial_circles - Description
    • cairo_pattern_get_rgba - Description
    • cairo_pattern_get_surface - Description
    • cairo_pattern_get_type - Description
    • cairo_pattern_set_extend - Description
    • cairo_pattern_set_filter - Description
    • cairo_pattern_set_matrix - Description
    • cairo_pattern_status - Description
    • cairo_pdf_surface_create - Description
    • cairo_pdf_surface_set_size - Description
    • cairo_ps_get_levels - Description
    • cairo_ps_level_to_string - Description
    • cairo_ps_surface_create - Description
    • cairo_ps_surface_dsc_begin_page_setup - Description
    • cairo_ps_surface_dsc_begin_setup - Description
    • cairo_ps_surface_dsc_comment - Description
    • cairo_ps_surface_get_eps - Description
    • cairo_ps_surface_restrict_to_level - Description
    • cairo_ps_surface_set_eps - Description
    • cairo_ps_surface_set_size - Description
    • cairo_scaled_font_create - Description
    • cairo_scaled_font_extents - Description
    • cairo_scaled_font_get_ctm - Description
    • cairo_scaled_font_get_font_face - Description
    • cairo_scaled_font_get_font_matrix - Description
    • cairo_scaled_font_get_font_options - Description
    • cairo_scaled_font_get_scale_matrix - Description
    • cairo_scaled_font_get_type - Description
    • cairo_scaled_font_glyph_extents - Description
    • cairo_scaled_font_status - Description
    • cairo_scaled_font_text_extents - Description
    • cairo_surface_copy_page - Description
    • cairo_surface_create_similar - Description
    • cairo_surface_finish - Description
    • cairo_surface_flush - Description
    • cairo_surface_get_content - Description
    • cairo_surface_get_device_offset - Description
    • cairo_surface_get_font_options - Description
    • cairo_surface_get_type - Description
    • cairo_surface_mark_dirty - Description
    • cairo_surface_mark_dirty_rectangle - Description
    • cairo_surface_set_device_offset - Description
    • cairo_surface_set_fallback_resolution - Description
    • cairo_surface_show_page - Description
    • cairo_surface_status - Description
    • cairo_surface_write_to_png - Description
    • cairo_svg_surface_create - Description
    • cairo_svg_surface_restrict_to_version - Description
    • cairo_svg_version_to_string - Description
    • calculhmac - Obtain a hmac key (needs 2 arguments)
    • calcul_hmac - Obtain a hmac key (needs 8 arguments)
    • CallbackFilterIterator::accept - Calls the callback with the current value, the current key and the inner iterator as arguments
    • CallbackFilterIterator::__construct - Create a filtered iterator from another iterator
    • call_user_func - Call the callback given by the first parameter
    • call_user_func_array - Call a callback with an array of parameters
    • call_user_method - Wywołuje metodę użytkownika na zadanym obiekcie [przestarzałe]
    • call_user_method_array - Wywołuje metodę użytkownika zadaną z tablicą parametrów [przestarzałe]
    • 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
    • ceil - Zaokrągla ułamki w górę
    • chdb::get - Gets the value associated with a key
    • chdb::__construct - Creates a chdb instance
    • chdb_create - Creates a chdb file
    • chdir - Zmienia bieżący katalog
    • checkdate - Waliduje datę gregoriańską
    • checkdnsrr - Check DNS records corresponding to a given Internet host name or IP address
    • chgrp - Zmienia grupę pliku
    • chmod - Zmienia prawa dostępu do pliku
    • chop - Alias dla rtrim
    • chown - Zmienia właściciela pliku
    • chr - Return a specific character
    • chroot - Zmienia główny katalog
    • chunk_split - Split a string into smaller chunks
    • classkit_import - Import new class method definitions from a file
    • classkit_method_add - Dynamically adds a new method to a given class
    • classkit_method_copy - Copies a method from class to another
    • classkit_method_redefine - Dynamically changes the code of the given method
    • classkit_method_remove - Dynamically removes the given method
    • classkit_method_rename - Dynamically changes the name of the given method
    • class_alias - Creates an alias for a class
    • class_exists - Sprawdza, czy klasa została zdefiniowana
    • class_implements - Return the interfaces which are implemented by the given class
    • class_parents - Return the parent classes of the given class
    • class_uses - Return the traits used by the given class
    • clearstatcache - Czyści bufor statusu pliku
    • closedir - Zamyka wskaźnik katalogu
    • closelog - Close connection to system logger
    • Closure::bind - Duplicates a closure with a specific bound object and class scope
    • Closure::bindTo - Duplicates the closure with a new bound object and class scope
    • Closure::__construct - Constructor that disallows instantiation
    • Collator::asort - Sort array maintaining index association
    • Collator::compare - Compare two Unicode strings
    • Collator::create - Create a collator
    • Collator::getAttribute - Get collation attribute value
    • Collator::getErrorCode - Get collator's last error code
    • Collator::getErrorMessage - Get text for collator's last error code
    • Collator::getLocale - Get the locale name of the collator
    • Collator::getSortKey - Get sorting key for a string
    • Collator::getStrength - Get current collation strength
    • Collator::setAttribute - Set collation attribute
    • Collator::setStrength - Set collation strength
    • Collator::sort - Sort array using specified collator
    • Collator::sortWithSortKeys - Sort array using specified collator and sort keys
    • Collator::__construct - Create a collator
    • compact - Stwórz tablicę zawierającą zmienne i ich wartości
    • com_addref - Increases the components reference counter [deprecated]
    • com_create_guid - Generate a globally unique identifier (GUID)
    • com_event_sink - Connect events from a COM object to a PHP object
    • com_get - Gets the value of a COM Component's property [deprecated]
    • com_get_active_object - Returns a handle to an already running instance of a COM object
    • com_invoke - Calls a COM component's method [deprecated]
    • com_isenum - Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
    • com_load - Creates a new reference to a COM component [deprecated]
    • com_load_typelib - Loads a Typelib
    • com_message_pump - Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo - Print out a PHP class definition for a dispatchable interface
    • com_propget - Alias dla com_get
    • com_propput - Alias dla com_set
    • com_propset - Alias dla com_set
    • com_release - Decreases the components reference counter [deprecated]
    • com_set - Assigns a value to a COM component's property
    • connection_aborted - Check whether client disconnected
    • connection_status - Returns connection status bitfield
    • connection_timeout - Check if the script timed out
    • constant - Returns the value of a constant
    • Constants for PDO_4D - Constants for PDO_4D
    • Context parameters - Context parameter listing
    • convert_cyr_string - Convert from one Cyrillic character set to another
    • convert_uudecode - Decode a uuencoded string
    • convert_uuencode - Uuencode a string
    • copy - Kopiuje plik
    • cos - Oblicza cosinus kąta
    • cosh - Cosinus hiperboliczny
    • count - Zlicza ilość elementów w tablicy lub pól obiektu
    • Countable::count - Count elements of an object
    • Counter::bumpValue - Change the current value of a counter.
    • Counter::getMeta - Return a piece of metainformation about a counter.
    • Counter::getNamed - Retrieve an existing named counter.
    • Counter::getValue - Get the current value of a counter.
    • Counter::resetValue - Reset the current value of a counter.
    • Counter::setCounterClass - Set the class returned by Counter::getNamed.
    • Counter::__construct - Creates an instance of a Counter which maintains a single numeric value.
    • counter_bump - Update the current value of the basic counter.
    • counter_bump_value - Change the current value of a counter resource.
    • counter_create - Creates a counter which maintains a single numeric value.
    • counter_get - Get the current value of the basic counter.
    • counter_get_meta - Return a piece of metainformation about a counter resource.
    • counter_get_named - Retrieve an existing named counter as a resource.
    • counter_get_value - Get the current value of a counter resource.
    • counter_reset - Reset the current value of the basic counter.
    • counter_reset_value - Reset the current value of a counter resource.
    • count_chars - Return information about characters used in a string
    • crack_check - Rozpoczyna sprawdzanie podanego hasła
    • crack_closedict - Zamyka otwarty słownik CrackLib
    • crack_getlastmessage - Zwraca wiadomość ostatniego wykonanego testu hasła
    • crack_opendict - Otwiera nowy słownik CrackLib
    • crc32 - Calculates the crc32 polynomial of a string
    • create_function - Create an anonymous (lambda-style) function
    • crypt - One-way string hashing
    • ctype_alnum - Check for alphanumeric character(s)
    • ctype_alpha - Check for alphabetic character(s)
    • ctype_cntrl - Check for control character(s)
    • ctype_digit - Check for numeric character(s)
    • ctype_graph - Check for any printable character(s) except space
    • ctype_lower - Check for lowercase character(s)
    • ctype_print - Check for printable character(s)
    • ctype_punct - Check for any printable character which is not whitespace or an alphanumeric character
    • ctype_space - Check for whitespace character(s)
    • ctype_upper - Check for uppercase character(s)
    • ctype_xdigit - Check for character(s) representing a hexadecimal digit
    • cubrid_affected_rows - Return the number of rows affected by the last SQL statement
    • cubrid_bind - Bind variables to a prepared statement as parameters
    • cubrid_client_encoding - Return the current CUBRID connection charset
    • cubrid_close - Close CUBRID connection
    • cubrid_close_prepare - Close the request handle
    • cubrid_close_request - Close the request handle
    • cubrid_column_names - Get the column names in result
    • cubrid_column_types - Get column types in result
    • cubrid_col_get - Get contents of collection type column using OID
    • cubrid_col_size - Get the number of elements in collection type column using OID
    • cubrid_commit - Commit a transaction
    • cubrid_connect - Open a connection to a CUBRID Server
    • cubrid_connect_with_url - Establish the environment for connecting to CUBRID server
    • cubrid_current_oid - Get OID of the current cursor location
    • cubrid_data_seek - Move the internal row pointer of the CUBRID result
    • cubrid_db_name - Get db name from results of cubrid_list_dbs
    • cubrid_disconnect - Close a database connection
    • cubrid_drop - Delete an instance using OID
    • cubrid_errno - Return the numerical value of the error message from previous CUBRID operation
    • cubrid_error - Get the error message
    • cubrid_error_code - Get error code for the most recent function call
    • cubrid_error_code_facility - Get the facility code of error
    • cubrid_error_msg - Get last error message for the most recent function call
    • cubrid_execute - Execute a prepared SQL statement
    • cubrid_fetch - Fetch the next row from a result set
    • cubrid_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • cubrid_fetch_assoc - Return the associative array that corresponds to the fetched row
    • cubrid_fetch_field - Get column information from a result and return as an object
    • cubrid_fetch_lengths - Return an array with the lengths of the values of each field from the current row
    • cubrid_fetch_object - Fetche the next row and returns it as an object
    • cubrid_fetch_row - Return a numerical array with the values of the current row
    • cubrid_field_flags - Return a string with the flags of the given field offset
    • cubrid_field_len - Get the maximum length of the specified field
    • cubrid_field_name - Return the name of the specified field index
    • cubrid_field_seek - Move the result set cursor to the specified field offset
    • cubrid_field_table - Return the name of the table of the specified field
    • cubrid_field_type - Return the type of the column corresponding to the given field offset
    • cubrid_free_result - Free the memory occupied by the result data
    • cubrid_get - Get a column using OID
    • cubrid_get_autocommit - Get auto-commit mode of the connection
    • cubrid_get_charset - Return the current CUBRID connection charset
    • cubrid_get_class_name - Get the class name using OID
    • cubrid_get_client_info - Return the client library version
    • cubrid_get_db_parameter - Returns the CUBRID database parameters
    • cubrid_get_query_timeout - Get the query timeout value of the request
    • cubrid_get_server_info - Return the CUBRID server version
    • cubrid_insert_id - Return the ID generated for the lastest updated AUTO_INCREMENT column
    • cubrid_is_instance - Check whether the instance pointed by OID exists
    • cubrid_list_dbs - Return an array with the list of all existing CUBRID databases
    • cubrid_load_from_glo - Read data from a GLO instance and save it in a file
    • cubrid_lob_close - Close BLOB/CLOB data
    • cubrid_lob_export - Export BLOB/CLOB data to file
    • cubrid_lob_get - Get BLOB/CLOB data
    • cubrid_lob_send - Read BLOB/CLOB data and send straight to browser
    • cubrid_lob_size - Get BLOB/CLOB data size
    • cubrid_lock_read - Set a read lock on the given OID
    • cubrid_lock_write - Set a write lock on the given OID
    • cubrid_move_cursor - Move the cursor in the result
    • cubrid_new_glo - Create a glo instance
    • cubrid_next_result - Get result of next query when executing multiple SQL statements
    • cubrid_num_cols - Return the number of columns in the result set
    • cubrid_num_fields - Return the number of columns in the result set
    • cubrid_num_rows - Get the number of rows in the result set
    • cubrid_pconnect - Open a persistent connection to a CUBRID server
    • cubrid_pconnect_with_url - Open a persistent connection to CUBRID server
    • cubrid_ping - Ping a server connection or reconnect if there is no connection
    • cubrid_prepare - Prepare an SQL statement for execution
    • cubrid_put - Update a column using OID
    • cubrid_query - Send a CUBRID query
    • cubrid_real_escape_string - Escape special characters in a string for use in an SQL statement
    • cubrid_result - Return the value of a specific field in a specific row
    • cubrid_rollback - Roll back a transaction
    • cubrid_save_to_glo - Save requested file in a GLO instance
    • cubrid_schema - Get the requested schema information
    • cubrid_send_glo - Read data from glo and send it to std output
    • cubrid_seq_drop - Delete an element from sequence type column using OID
    • cubrid_seq_insert - Insert an element to a sequence type column using OID
    • cubrid_seq_put - Update the element value of sequence type column using OID
    • cubrid_set_add - Insert a single element to set type column using OID
    • cubrid_set_autocommit - Set autocommit mode of the connection
    • cubrid_set_db_parameter - Sets the CUBRID database parameters
    • cubrid_set_drop - Delete an element from set type column using OID
    • cubrid_set_query_timeout - Set the timeout time of query execution
    • cubrid_unbuffered_query - Perform a query without fetching the results into memory
    • cubrid_version - Get the CUBRID PHP module's version
    • CURL context options - CURL context option listing
    • curl_close - Close a cURL session
    • curl_copy_handle - Copy a cURL handle along with all of its preferences
    • curl_errno - Return the last error number
    • curl_error - Return a string containing the last error for the current session
    • curl_exec - Perform a cURL session
    • curl_getinfo - Get information regarding a specific transfer
    • curl_init - Initialize a cURL session
    • curl_multi_add_handle - Add a normal cURL handle to a cURL multi handle
    • curl_multi_close - Close a set of cURL handles
    • curl_multi_exec - Run the sub-connections of the current cURL handle
    • curl_multi_getcontent - Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
    • curl_multi_info_read - Get information about the current transfers
    • curl_multi_init - Returns a new cURL multi handle
    • curl_multi_remove_handle - Remove a multi handle from a set of cURL handles
    • curl_multi_select - Wait for activity on any curl_multi connection
    • curl_setopt - Set an option for a cURL transfer
    • curl_setopt_array - Set multiple options for a cURL transfer
    • curl_version - Gets cURL version information
    • current - Zwraca bieżący element tablicy
    • cyrus_authenticate - Authenticate against a Cyrus IMAP server
    • cyrus_bind - Bind callbacks to a Cyrus IMAP connection
    • cyrus_close - Close connection to a Cyrus IMAP server
    • cyrus_connect - Connect to a Cyrus IMAP server
    • cyrus_query - Send a query to a Cyrus IMAP server
    • cyrus_unbind - Unbind ...
  • d
    • data:// - Data (RFC 2397)
    • date - Formatuje lokalny czas/datę
    • DateInterval::createFromDateString - Sets up a DateInterval from the relative parts of the string
    • DateInterval::format - Formats the interval
    • DateInterval::__construct - Creates new DateInterval object
    • DatePeriod::__construct - Creates new DatePeriod object
    • DateTime::add - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
    • DateTime::createFromFormat - Returns new DateTime object formatted according to the specified format
    • DateTime::diff - Returns the difference between two DateTime objects
    • DateTime::format - Returns date formatted according to given format
    • DateTime::getLastErrors - Returns the warnings and errors
    • DateTime::getOffset - Returns the timezone offset
    • DateTime::getTimestamp - Gets the Unix timestamp
    • DateTime::getTimezone - Return time zone relative to given DateTime
    • DateTime::modify - Alters the timestamp
    • DateTime::setDate - Sets the date
    • DateTime::setISODate - Sets the ISO date
    • DateTime::setTime - Sets the time
    • DateTime::setTimestamp - Sets the date and time based on an Unix timestamp
    • DateTime::setTimezone - Sets the time zone for the DateTime object
    • DateTime::sub - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
    • DateTime::__construct - Returns new DateTime object
    • DateTime::__set_state - The __set_state handler
    • DateTime::__wakeup - The __wakeup handler
    • DateTimeZone::getLocation - Returns location information for a timezone
    • DateTimeZone::getName - Returns the name of the timezone
    • DateTimeZone::getOffset - Returns the timezone offset from GMT
    • DateTimeZone::getTransitions - Returns all transitions for the timezone
    • DateTimeZone::listAbbreviations - Returns associative array containing dst, offset and the timezone name
    • DateTimeZone::listIdentifiers - Returns numerically index array with all timezone identifiers
    • DateTimeZone::__construct - Creates new DateTimeZone object
    • date_add - Alias dla DateTime::add
    • date_create - Alias dla DateTime::__construct
    • date_create_from_format - Alias dla DateTime::createFromFormat
    • date_date_set - Alias dla DateTime::setDate
    • date_default_timezone_get - Gets the default timezone used by all date/time functions in a script
    • date_default_timezone_set - Sets the default timezone used by all date/time functions in a script
    • date_diff - Alias dla DateTime::diff
    • date_format - Alias dla DateTime::format
    • date_get_last_errors - Alias dla DateTime::getLastErrors
    • date_interval_create_from_date_string - Alias dla DateInterval::createFromDateString
    • date_interval_format - Alias dla DateInterval::format
    • date_isodate_set - Alias dla DateTime::setISODate
    • date_modify - Alias dla DateTime::modify
    • date_offset_get - Alias dla DateTime::getOffset
    • date_parse - Returns associative array with detailed info about given date
    • date_parse_from_format - Get info about given date formatted according to the specified format
    • date_sub - Alias dla DateTime::sub
    • 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_sun_info - Returns an array with information about sunset/sunrise and twilight begin/end
    • date_timestamp_get - Alias dla DateTime::getTimestamp
    • date_timestamp_set - Alias dla DateTime::setTimestamp
    • date_timezone_get - Alias dla DateTime::getTimezone
    • date_timezone_set - Alias dla DateTime::setTimezone
    • date_time_set - Alias dla DateTime::setTime
    • db2_autocommit - Returns or sets the AUTOCOMMIT state for a database connection
    • db2_bind_param - Binds a PHP variable to an SQL statement parameter
    • db2_client_info - Returns an object with properties that describe the DB2 database client
    • db2_close - Closes a database connection
    • db2_columns - Returns a result set listing the columns and associated metadata for a table
    • db2_column_privileges - Returns a result set listing the columns and associated privileges for a table
    • db2_commit - Commits a transaction
    • db2_connect - Returns a connection to a database
    • db2_conn_error - Returns a string containing the SQLSTATE returned by the last connection attempt
    • db2_conn_errormsg - Returns the last connection error message and SQLCODE value
    • db2_cursor_type - Returns the cursor type used by a statement resource
    • db2_escape_string - Used to escape certain characters
    • db2_exec - Executes an SQL statement directly
    • db2_execute - Executes a prepared SQL statement
    • db2_fetch_array - Returns an array, indexed by column position, representing a row in a result set
    • db2_fetch_assoc - Returns an array, indexed by column name, representing a row in a result set
    • db2_fetch_both - Returns an array, indexed by both column name and position, representing a row in a result set
    • db2_fetch_object - Returns an object with properties representing columns in the fetched row
    • db2_fetch_row - Sets the result set pointer to the next row or requested row
    • db2_field_display_size - Returns the maximum number of bytes required to display a column
    • db2_field_name - Returns the name of the column in the result set
    • db2_field_num - Returns the position of the named column in a result set
    • db2_field_precision - Returns the precision of the indicated column in a result set
    • db2_field_scale - Returns the scale of the indicated column in a result set
    • db2_field_type - Returns the data type of the indicated column in a result set
    • db2_field_width - Returns the width of the current value of the indicated column in a result set
    • db2_foreign_keys - Returns a result set listing the foreign keys for a table
    • db2_free_result - Frees resources associated with a result set
    • db2_free_stmt - Frees resources associated with the indicated statement resource
    • db2_get_option - Retrieves an option value for a statement resource or a connection resource
    • db2_last_insert_id - Returns the auto generated ID of the last insert query that successfully executed on this connection
    • db2_lob_read - Gets a user defined size of LOB files with each invocation
    • db2_next_result - Requests the next result set from a stored procedure
    • db2_num_fields - Returns the number of fields contained in a result set
    • db2_num_rows - Returns the number of rows affected by an SQL statement
    • db2_pclose - Closes a persistent database connection
    • db2_pconnect - Returns a persistent connection to a database
    • db2_prepare - Prepares an SQL statement to be executed
    • db2_primary_keys - Returns a result set listing primary keys for a table
    • db2_procedures - Returns a result set listing the stored procedures registered in a database
    • db2_procedure_columns - Returns a result set listing stored procedure parameters
    • db2_result - Returns a single column from a row in the result set
    • db2_rollback - Rolls back a transaction
    • db2_server_info - Returns an object with properties that describe the DB2 database server
    • db2_set_option - Set options for connection or statement resources
    • db2_special_columns - Returns a result set listing the unique row identifier columns for a table
    • db2_statistics - Returns a result set listing the index and statistics for a table
    • db2_stmt_error - Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg - Returns a string containing the last SQL statement error message
    • db2_tables - Returns a result set listing the tables and associated metadata in a database
    • db2_table_privileges - Returns a result set listing the tables and associated privileges in a database
    • dbase_add_record - Adds a record to a database
    • dbase_close - Closes a database
    • dbase_create - Creates a database
    • dbase_delete_record - Deletes a record from a database
    • dbase_get_header_info - Gets the header info of a database
    • dbase_get_record - Gets a record from a database as an indexed array
    • dbase_get_record_with_names - Gets a record from a database as an associative array
    • dbase_numfields - Gets the number of fields of a database
    • dbase_numrecords - Gets the number of records in a database
    • dbase_open - Opens a database
    • dbase_pack - Packs a database
    • dbase_replace_record - Replaces a record in a database
    • dba_close - Close a DBA database
    • dba_delete - Delete DBA entry specified by key
    • dba_exists - Check whether key exists
    • dba_fetch - Fetch data specified by key
    • dba_firstkey - Fetch first key
    • dba_handlers - List all the handlers available
    • dba_insert - Insert entry
    • dba_key_split - Splits a key in string representation into array representation
    • dba_list - List all open database files
    • dba_nextkey - Fetch next key
    • dba_open - Open database
    • dba_optimize - Optimize database
    • dba_popen - Open database persistently
    • dba_replace - Replace or insert entry
    • dba_sync - Synchronize database
    • dbplus_add - Add a tuple to a relation
    • dbplus_aql - Perform AQL query
    • dbplus_chdir - Get/Set database virtual current directory
    • dbplus_close - Close a relation
    • dbplus_curr - Get current tuple from relation
    • dbplus_errcode - Get error string for given errorcode or last error
    • dbplus_errno - Get error code for last operation
    • dbplus_find - Set a constraint on a relation
    • dbplus_first - Get first tuple from relation
    • dbplus_flush - Flush all changes made on a relation
    • dbplus_freealllocks - Free all locks held by this client
    • dbplus_freelock - Release write lock on tuple
    • dbplus_freerlocks - Free all tuple locks on given relation
    • dbplus_getlock - Get a write lock on a tuple
    • dbplus_getunique - Get an id number unique to a relation
    • dbplus_info - Get information about a relation
    • dbplus_last - Get last tuple from relation
    • dbplus_lockrel - Request write lock on relation
    • dbplus_next - Get next tuple from relation
    • dbplus_open - Open relation file
    • dbplus_prev - Get previous tuple from relation
    • dbplus_rchperm - Change relation permissions
    • dbplus_rcreate - Creates a new DB++ relation
    • dbplus_rcrtexact - Creates an exact but empty copy of a relation including indices
    • dbplus_rcrtlike - Creates an empty copy of a relation with default indices
    • dbplus_resolve - Resolve host information for relation
    • dbplus_restorepos - Restore position
    • dbplus_rkeys - Specify new primary key for a relation
    • dbplus_ropen - Open relation file local
    • dbplus_rquery - Perform local (raw) AQL query
    • dbplus_rrename - Rename a relation
    • dbplus_rsecindex - Create a new secondary index for a relation
    • dbplus_runlink - Remove relation from filesystem
    • dbplus_rzap - Remove all tuples from relation
    • dbplus_savepos - Save position
    • dbplus_setindex - Set index
    • dbplus_setindexbynumber - Set index by number
    • dbplus_sql - Perform SQL query
    • dbplus_tcl - Execute TCL code on server side
    • dbplus_tremove - Remove tuple and return new current tuple
    • dbplus_undo - Undo
    • dbplus_undoprepare - Prepare undo
    • dbplus_unlockrel - Give up write lock on relation
    • dbplus_unselect - Remove a constraint from relation
    • dbplus_update - Update specified tuple in relation
    • dbplus_xlockrel - Request exclusive lock on relation
    • dbplus_xunlockrel - Free exclusive lock on relation
    • dbx_close - Close an open connection/database
    • dbx_compare - Compare two rows for sorting purposes
    • dbx_connect - Open a connection/database
    • dbx_error - Report the error message of the latest function call in the module
    • dbx_escape_string - Escape a string so it can safely be used in an sql-statement
    • dbx_fetch_row - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
    • dbx_query - Send a query and fetch all results (if any)
    • dbx_sort - Sort a result from a dbx_query by a custom sort function
    • dcgettext - Overrides the domain for a single lookup
    • dcngettext - Plural version of dcgettext
    • deaggregate - Removes the aggregated methods and properties from an object
    • debug_backtrace - Generates a backtrace
    • debug_print_backtrace - Prints a backtrace
    • debug_zval_dump - Dumps a string representation of an internal zend value to output
    • decbin - Konwertuje liczbę dziesiętną do dwójkowej
    • dechex - Konwersja liczby dziesiętnej do szesnastkowej
    • decoct - Konwersja liczby dziesiętnej do ósemkowej
    • define - Defines a named constant
    • defined - Checks whether a given named constant exists
    • define_syslog_variables - Initializes all syslog related variables
    • deg2rad - Przelicza stopnie na radiany
    • delete - Zobacz unlink lub unset
    • dgettext - Override the current domain
    • die - Equivalent to exit
    • dio_close - Closes the file descriptor given by fd
    • dio_fcntl - Performs a c library fcntl on fd
    • dio_open - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow.
    • dio_read - Reads bytes from a file descriptor
    • dio_seek - Seeks to pos on fd from whence
    • dio_stat - Gets stat information about the file descriptor fd
    • dio_tcsetattr - Sets terminal attributes and baud rate for a serial port
    • dio_truncate - Truncates file descriptor fd to offset bytes
    • dio_write - Writes data to fd with optional truncation at length
    • dir - Return an instance of the Directory class
    • Directory::close - Close directory handle
    • Directory::read - Read entry from directory handle
    • Directory::rewind - Rewind directory handle
    • DirectoryIterator::current - Return the current DirectoryIterator item.
    • DirectoryIterator::getATime - Get last access time of the current DirectoryIterator item
    • DirectoryIterator::getBasename - Get base name of current DirectoryIterator item.
    • DirectoryIterator::getCTime - Get inode change time of the current DirectoryIterator item
    • DirectoryIterator::getExtension - Returns the file extension component of path
    • DirectoryIterator::getFilename - Return file name of current DirectoryIterator item.
    • DirectoryIterator::getGroup - Get group for the current DirectoryIterator item
    • DirectoryIterator::getInode - Get inode for the current DirectoryIterator item
    • DirectoryIterator::getMTime - Get last modification time of current DirectoryIterator item
    • DirectoryIterator::getOwner - Get owner of current DirectoryIterator item
    • DirectoryIterator::getPath - Get path of current Iterator item without filename
    • DirectoryIterator::getPathname - Return path and file name of current DirectoryIterator item
    • DirectoryIterator::getPerms - Get the permissions of current DirectoryIterator item
    • DirectoryIterator::getSize - Get size of current DirectoryIterator item
    • DirectoryIterator::getType - Determine the type of the current DirectoryIterator item
    • DirectoryIterator::isDir - Determine if current DirectoryIterator item is a directory
    • DirectoryIterator::isDot - Determine if current DirectoryIterator item is '.' or '..'
    • DirectoryIterator::isExecutable - Determine if current DirectoryIterator item is executable
    • DirectoryIterator::isFile - Determine if current DirectoryIterator item is a regular file
    • DirectoryIterator::isLink - Determine if current DirectoryIterator item is a symbolic link
    • DirectoryIterator::isReadable - Determine if current DirectoryIterator item can be read
    • DirectoryIterator::isWritable - Determine if current DirectoryIterator item can be written to
    • DirectoryIterator::key - Return the key for the current DirectoryIterator item
    • DirectoryIterator::next - Move forward to next DirectoryIterator item
    • DirectoryIterator::rewind - Rewind the DirectoryIterator back to the start
    • DirectoryIterator::seek - Seek to a DirectoryIterator item
    • DirectoryIterator::valid - Check whether current DirectoryIterator position is a valid file
    • DirectoryIterator::__construct - Constructs a new directory iterator from a path
    • DirectoryIterator::__toString - Get file name as a string
    • dirname - Zwraca nazwę katalogu, będącego składową ścieżki
    • diskfreespace - Alias dla disk_free_space
    • disk_free_space - Zwraca ilość wolnego miejsca w systemie plików lub partycji dysku
    • disk_total_space - Zwraca całkowity rozmiar systemu plików lub partycji dysku
    • dl - Loads a PHP extension at runtime
    • dngettext - Plural version of dgettext
    • dns_check_record - Alias dla checkdnsrr
    • dns_get_mx - Alias dla getmxrr
    • dns_get_record - Fetch DNS Resource Records associated with a hostname
    • DOMAttr::isId - Checks if attribute is a defined ID
    • DOMAttr::__construct - Creates a new DOMAttr object
    • DomAttribute::name - Returns the name of attribute
    • DomAttribute::set_value - Sets the value of an attribute
    • DomAttribute::specified - Checks if attribute is specified
    • DomAttribute::value - Returns value of attribute
    • DOMCdataSection::__construct - Constructs a new DOMCdataSection object
    • DOMCharacterData::appendData - Append the string to the end of the character data of the node
    • DOMCharacterData::deleteData - Remove a range of characters from the node
    • DOMCharacterData::insertData - Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::replaceData - Replace a substring within the DOMCharacterData node
    • DOMCharacterData::substringData - Extracts a range of data from the node
    • DOMComment::__construct - Creates a new DOMComment object
    • DomDocument::add_root - Adds a root node [deprecated]
    • DOMDocument::createAttribute - Create new attribute
    • DOMDocument::createAttributeNS - Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection - Create new cdata node
    • DOMDocument::createComment - Create new comment node
    • DOMDocument::createDocumentFragment - Create new document fragment
    • DOMDocument::createElement - Create new element node
    • DOMDocument::createElementNS - Create new element node with an associated namespace
    • DOMDocument::createEntityReference - Create new entity reference node
    • DOMDocument::createProcessingInstruction - Creates new PI node
    • DOMDocument::createTextNode - Create new text node
    • DomDocument::create_attribute - Create new attribute
    • DomDocument::create_cdata_section - Create new cdata node
    • DomDocument::create_comment - Create new comment node
    • DomDocument::create_element - Create new element node
    • DomDocument::create_element_ns - Create new element node with an associated namespace
    • DomDocument::create_entity_reference - Create an entity reference
    • DomDocument::create_processing_instruction - Creates new PI node
    • DomDocument::create_text_node - Create new text node
    • DomDocument::doctype - Returns the document type
    • DomDocument::document_element - Returns root element node
    • DomDocument::dump_file - Dumps the internal XML tree back into a file
    • DomDocument::dump_mem - Dumps the internal XML tree back into a string
    • DOMDocument::getElementById - Searches for an element with a certain id
    • DOMDocument::getElementsByTagName - Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS - Searches for all elements with given tag name in specified namespace
    • DomDocument::get_elements_by_tagname - Returns array with nodes with given tagname in document or empty array, if not found
    • DomDocument::get_element_by_id - Searches for an element with a certain id
    • DomDocument::html_dump_mem - Dumps the internal XML tree back into a string as HTML
    • DOMDocument::importNode - Import node into current document
    • DOMDocument::load - Load XML from a file
    • DOMDocument::loadHTML - Load HTML from a string
    • DOMDocument::loadHTMLFile - Load HTML from a file
    • DOMDocument::loadXML - Load XML from a string
    • DOMDocument::normalizeDocument - Normalizes the document
    • DOMDocument::registerNodeClass - Register extended class used to create base node type
    • DOMDocument::relaxNGValidate - Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource - Performs relaxNG validation on the document
    • DOMDocument::save - Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML - Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile - Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML - Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate - Validates a document based on a schema
    • DOMDocument::schemaValidateSource - Validates a document based on a schema
    • DOMDocument::validate - Validates the document based on its DTD
    • DomDocument::xinclude - Substitutes XIncludes in a DomDocument Object
    • DOMDocument::__construct - Creates a new DOMDocument object
    • DOMDocumentFragment::appendXML - Append raw XML data
    • DomDocumentType::entities - Returns list of entities
    • DomDocumentType::internal_subset - Returns internal subset
    • DomDocumentType::name - Returns name of document type
    • DomDocumentType::notations - Returns list of notations
    • DomDocumentType::public_id - Returns public id of document type
    • DomDocumentType::system_id - Returns the system id of document type
    • DOMElement::getAttribute - Returns value of attribute
    • DOMElement::getAttributeNode - Returns attribute node
    • DOMElement::getAttributeNodeNS - Returns attribute node
    • DOMElement::getAttributeNS - Returns value of attribute
    • DOMElement::getElementsByTagName - Gets elements by tagname
    • DOMElement::getElementsByTagNameNS - Get elements by namespaceURI and localName
    • DomElement::get_attribute - Returns the value of the given attribute
    • DomElement::get_attribute_node - Returns the node of the given attribute
    • DomElement::get_elements_by_tagname - Gets elements by tagname
    • DOMElement::hasAttribute - Checks to see if attribute exists
    • DOMElement::hasAttributeNS - Checks to see if attribute exists
    • DomElement::has_attribute - Checks to see if an attribute exists in the current node
    • DOMElement::removeAttribute - Removes attribute
    • DOMElement::removeAttributeNode - Removes attribute
    • DOMElement::removeAttributeNS - Removes attribute
    • DomElement::remove_attribute - Removes attribute
    • DOMElement::setAttribute - Adds new attribute
    • DOMElement::setAttributeNode - Adds new attribute node to element
    • DOMElement::setAttributeNodeNS - Adds new attribute node to element
    • DOMElement::setAttributeNS - Adds new attribute
    • DOMElement::setIdAttribute - Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode - Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS - Declares the attribute specified by local name and namespace URI to be of type ID
    • DomElement::set_attribute - Sets the value of an attribute
    • DomElement::set_attribute_node - Adds new attribute
    • DomElement::tagname - Returns the name of the current element
    • DOMElement::__construct - Creates a new DOMElement object
    • DOMEntityReference::__construct - Creates a new DOMEntityReference object
    • DOMImplementation::createDocument - Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType - Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature - Test if the DOM implementation implements a specific feature
    • DOMImplementation::__construct - Creates a new DOMImplementation object
    • DOMNamedNodeMap::getNamedItem - Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS - Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item - Retrieves a node specified by index
    • DomNode::add_namespace - Adds a namespace declaration to a node
    • DOMNode::appendChild - Adds new child at the end of the children
    • DomNode::append_child - Adds a new child at the end of the children
    • DomNode::append_sibling - Adds new sibling to a node
    • DomNode::attributes - Returns list of attributes
    • DOMNode::C14N - Canonicalize nodes to a string
    • DOMNode::C14NFile - Canonicalize nodes to a file
    • DomNode::child_nodes - Returns children of node
    • DOMNode::cloneNode - Clones a node
    • DomNode::clone_node - Clones a node
    • DomNode::dump_node - Dumps a single node
    • DomNode::first_child - Returns first child of node
    • DOMNode::getLineNo - Get line number for a node
    • DOMNode::getNodePath - Get an XPath for a node
    • DomNode::get_content - Gets content of node
    • DOMNode::hasAttributes - Checks if node has attributes
    • DOMNode::hasChildNodes - Checks if node has children
    • DomNode::has_attributes - Checks if node has attributes
    • DomNode::has_child_nodes - Checks if node has children
    • DOMNode::insertBefore - Adds a new child before a reference node
    • DomNode::insert_before - Inserts new node as child
    • DOMNode::isDefaultNamespace - Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isSameNode - Indicates if two nodes are the same node
    • DOMNode::isSupported - Checks if feature is supported for specified version
    • DomNode::is_blank_node - Checks if node is blank
    • DomNode::last_child - Returns last child of node
    • DOMNode::lookupNamespaceURI - Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix - Gets the namespace prefix of the node based on the namespace URI
    • DomNode::next_sibling - Returns the next sibling of node
    • DomNode::node_name - Returns name of node
    • DomNode::node_type - Returns type of node
    • DomNode::node_value - Returns value of a node
    • DOMNode::normalize - Normalizes the node
    • DomNode::owner_document - Returns the document this node belongs to
    • DomNode::parent_node - Returns the parent of the node
    • DomNode::prefix - Returns name space prefix of node
    • DomNode::previous_sibling - Returns the previous sibling of node
    • DOMNode::removeChild - Removes child from list of children
    • DomNode::remove_child - Removes child from list of children
    • DOMNode::replaceChild - Replaces a child
    • DomNode::replace_child - Replaces a child
    • DomNode::replace_node - Replaces node
    • DomNode::set_content - Sets content of node
    • DomNode::set_name - Sets name of node
    • DomNode::set_namespace - Sets namespace of a node
    • DomNode::unlink_node - Deletes node
    • DOMNodelist::item - Retrieves a node specified by index
    • DomProcessingInstruction::data - Returns the data of ProcessingInstruction node
    • DomProcessingInstruction::target - Returns the target of a ProcessingInstruction node
    • DOMProcessingInstruction::__construct - Creates a new DOMProcessingInstruction object
    • DOMText::isWhitespaceInElementContent - Indicates whether this text node contains whitespace
    • DOMText::splitText - Breaks this node into two nodes at the specified offset
    • DOMText::__construct - Creates a new DOMText object
    • domxml_new_doc - Creates new empty XML document
    • domxml_open_file - Creates a DOM object from an XML file
    • domxml_open_mem - Creates a DOM object of an XML document
    • domxml_version - Gets the XML library version
    • domxml_xmltree - Creates a tree of PHP objects from an XML document
    • domxml_xslt_stylesheet - Creates a DomXsltStylesheet object from an XSL document in a string
    • domxml_xslt_stylesheet_doc - Creates a DomXsltStylesheet Object from a DomDocument Object
    • domxml_xslt_stylesheet_file - Creates a DomXsltStylesheet Object from an XSL document in a file
    • domxml_xslt_version - Gets the XSLT library version
    • DOMXPath::evaluate - Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query - Evaluates the given XPath expression
    • DOMXPath::registerNamespace - Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions - Register PHP functions as XPath functions
    • DOMXPath::__construct - Creates a new DOMXPath object
    • DomXsltStylesheet::process - Applies the XSLT-Transformation on a DomDocument Object
    • DomXsltStylesheet::result_dump_file - Dumps the result from a XSLT-Transformation into a file
    • DomXsltStylesheet::result_dump_mem - Dumps the result from a XSLT-Transformation back into a string
    • dom_import_simplexml - Gets a DOMElement object from a SimpleXMLElement object
    • dotnet_load - Wczytuje moduł DOTNET
    • doubleval - Alias dla floatval
  • e
    • each - Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicy
    • 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
    • echo - Output one or more strings
    • eio_busy - Artificially increase load. Could be useful in tests, benchmarking.
    • eio_cancel - Cancels a request
    • eio_chmod - Change file/direcrory permissions.
    • eio_chown - Change file/direcrory permissions.
    • eio_close - Close file
    • eio_custom - Execute custom request like any other eio_* call.
    • eio_dup2 - Duplicate a file descriptor
    • eio_event_loop - Polls libeio until all requests proceeded
    • eio_fallocate - Allows the caller to directly manipulate the allocated disk space for a file
    • eio_fchmod - Change file permissions.
    • eio_fchown - Change file ownership
    • eio_fdatasync - Synchronize a file's in-core state with storage device.
    • eio_fstat - Get file status
    • eio_fstatvfs - Get file system statistics
    • eio_fsync - Synchronize a file's in-core state with storage device
    • eio_ftruncate - Truncate a file
    • eio_futime - Change file last access and modification times
    • eio_get_event_stream - Get stream representing a variable used in internal communications with libeio.
    • eio_grp - Createsa request group.
    • eio_grp_add - Adds a request to the request group.
    • eio_grp_cancel - Cancels a request group
    • eio_grp_limit - Set group limit
    • eio_link - Create a hardlink for file
    • eio_lstat - Get file status
    • eio_mkdir - Create directory
    • eio_mknod - Create a special or ordinary file.
    • eio_nop - Does nothing, except go through the whole request cycle.
    • eio_npending - Returns number of finished, but unhandled requests
    • eio_nready - Returns number of not-yet handled requests
    • eio_nreqs - Returns number of requests to be processed
    • eio_nthreads - Returns number of threads currently in use
    • eio_open - Opens a file
    • eio_poll - Can be to be called whenever there are pending requests that need finishing.
    • eio_read - Read from a file descriptor at given offset.
    • eio_readahead - Perform file readahead into page cache
    • eio_readdir - Reads through a whole directory
    • eio_readlink - Read value of a symbolic link.
    • eio_realpath - Get the canonicalized absolute pathname.
    • eio_rename - Change the name or location of a file.
    • eio_rmdir - Remove a directory
    • eio_sendfile - Transfer data between file descriptors
    • eio_set_max_idle - Set maximum number of idle threads.
    • eio_set_max_parallel - Set maximum parallel threads
    • eio_set_max_poll_reqs - Set maximum number of requests processed in a poll.
    • eio_set_max_poll_time - Set maximum poll time
    • eio_set_min_parallel - Set minimum parallel thread number
    • eio_stat - Get file status
    • eio_statvfs - Get file system statistics
    • eio_symlink - Create a symbolic link
    • eio_sync - Commit buffer cache to disk
    • eio_syncfs - Calls Linux' syncfs syscall, if available
    • eio_sync_file_range - Sync a file segment with disk
    • eio_truncate - Truncate a file
    • eio_unlink - Delete a name and possibly the file it refers to
    • eio_utime - Change file last access and modification times.
    • eio_write - Write to file
    • empty - Determine whether a variable is empty
    • EmptyIterator::current - The current() method
    • EmptyIterator::key - The key() method
    • EmptyIterator::next - The next() method
    • EmptyIterator::rewind - The rewind() method
    • EmptyIterator::valid - The valid() method
    • enchant_broker_describe - Enumerates the Enchant providers
    • enchant_broker_dict_exists - Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free - Free the broker resource and its dictionnaries
    • enchant_broker_free_dict - Free a dictionary resource
    • enchant_broker_get_error - Returns the last error of the broker
    • enchant_broker_init - create a new broker object capable of requesting
    • enchant_broker_list_dicts - Returns a list of available dictionaries
    • enchant_broker_request_dict - create a new dictionary using a tag
    • enchant_broker_request_pwl_dict - creates a dictionary using a PWL file
    • enchant_broker_set_ordering - Declares a preference of dictionaries to use for the language
    • enchant_dict_add_to_personal - add a word to personal word list
    • enchant_dict_add_to_session - add 'word' to this spell-checking session
    • enchant_dict_check - Check whether a word is correctly spelled or not
    • enchant_dict_describe - Describes an individual dictionary
    • enchant_dict_get_error - Returns the last error of the current spelling-session
    • enchant_dict_is_in_session - whether or not 'word' exists in this spelling-session
    • enchant_dict_quick_check - Check the word is correctly spelled and provide suggestions
    • enchant_dict_store_replacement - Add a correction for a word
    • enchant_dict_suggest - Will return a list of values if any of those pre-conditions are not met
    • end - Ustawia wewnętrzny wskaźnik tablicy na ostatnim elemencie
    • ereg - Regular expression match
    • eregi - Case insensitive regular expression match
    • eregi_replace - Replace regular expression case insensitive
    • ereg_replace - Replace regular expression
    • ErrorException::getSeverity - Gets the exception severity
    • ErrorException::__construct - Constructs the exception
    • error_get_last - Get the last occurred error
    • error_log - Send an error message somewhere
    • error_reporting - Sets which PHP errors are reported
    • escapeshellarg - Escape a string to be used as a shell argument
    • escapeshellcmd - Escape shell metacharacters
    • eval - Evaluate a string as PHP code
    • event_add - Add an event to the set of monitored events
    • event_base_free - Destroy event base
    • event_base_loop - Handle events
    • event_base_loopbreak - Abort event loop
    • event_base_loopexit - Exit loop after a time
    • event_base_new - Create and initialize new event base
    • event_base_priority_init - Set the number of event priority levels
    • event_base_set - Associate event base with an event
    • event_buffer_base_set - Associate buffered event with an event base
    • event_buffer_disable - Disable a buffered event
    • event_buffer_enable - Enable a buffered event
    • event_buffer_fd_set - Change a buffered event file descriptor
    • event_buffer_free - Destroy buffered event
    • event_buffer_new - Create new buffered event
    • event_buffer_priority_set - Assign a priority to a buffered event
    • event_buffer_read - Read data from a buffered event
    • event_buffer_set_callback - Set or reset callbacks for a buffered event
    • event_buffer_timeout_set - Set read and write timeouts for a buffered event
    • event_buffer_watermark_set - Set the watermarks for read and write events
    • event_buffer_write - Write data to a buffered event
    • event_del - Remove an event from the set of monitored events
    • event_free - Free event resource
    • event_new - Create new event
    • event_set - Prepare an event
    • Examples with PDO_4D - Examples PDO_4D
    • Exception::getCode - Gets the Exception code
    • Exception::getFile - Gets the file in which the exception occurred
    • Exception::getLine - Gets the line in which the exception occurred
    • Exception::getMessage - Gets the Exception message
    • Exception::getPrevious - Returns previous Exception
    • Exception::getTrace - Gets the stack trace
    • Exception::getTraceAsString - Gets the stack trace as a string
    • Exception::__clone - Clone the exception
    • Exception::__construct - Construct the exception
    • Exception::__toString - String representation of the exception
    • exec - Execute an external program
    • exif_imagetype - Determine the type of an image
    • exif_read_data - Reads the EXIF headers from JPEG or TIFF
    • exif_tagname - Get the header name for an index
    • exif_thumbnail - Retrieve the embedded thumbnail of a TIFF or JPEG image
    • exit - Output a message and terminate the current script
    • exp - Oblicza eksponentę liczby e
    • expect:// - Process Interaction Streams
    • expect_expectl - Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen - Execute command via Bourne shell, and open the PTY stream to the process
    • explode - Split a string by string
    • expm1 - Zwraca exp(liczba) - 1, obliczoną w taki sposób, że wartość jest dokładna, nawet jeśli liczba jest bliska zeru
    • extension_loaded - Find out whether an extension is loaded
    • extract - Importuj zmienne do bieżącej tablicy symboli z tablicy
    • ezmlm_hash - Oblicza wartość hash potrzebną dla EZMLM
  • f
    • fam_cancel_monitor - Terminate monitoring
    • fam_close - Close FAM connection
    • fam_monitor_collection - Monitor a collection of files in a directory for changes
    • fam_monitor_directory - Monitor a directory for changes
    • fam_monitor_file - Monitor a regular file for changes
    • fam_next_event - Get next pending FAM event
    • fam_open - Open connection to FAM daemon
    • fam_pending - Check for pending FAM events
    • fam_resume_monitor - Resume suspended monitoring
    • fam_suspend_monitor - Temporarily suspend monitoring
    • fbsql_affected_rows - Get number of affected rows in previous FrontBase operation
    • fbsql_autocommit - Enable or disable autocommit
    • fbsql_blob_size - Get the size of a BLOB
    • fbsql_change_user - Change logged in user of the active connection
    • fbsql_clob_size - Get the size of a CLOB
    • fbsql_close - Zamyka połączenie z serwerem FrontBase
    • fbsql_commit - Commits a transaction to the database
    • fbsql_connect - Otwiera połączenie z serwerem FrontBase
    • fbsql_create_blob - Create a BLOB
    • fbsql_create_clob - Create a CLOB
    • fbsql_create_db - Create a FrontBase database
    • fbsql_database - Get or set the database name used with a connection
    • fbsql_database_password - Sets or retrieves the password for a FrontBase database
    • fbsql_data_seek - Move internal result pointer
    • fbsql_db_query - Send a FrontBase query
    • fbsql_db_status - Zwraca status dla podanej bazy danych
    • fbsql_drop_db - Drop (delete) a FrontBase database
    • fbsql_errno - Returns the error number from previous operation
    • fbsql_error - Returns the error message from previous operation
    • fbsql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • fbsql_fetch_assoc - Fetch a result row as an associative array
    • fbsql_fetch_field - Get column information from a result and return as an object
    • fbsql_fetch_lengths - Get the length of each output in a result
    • fbsql_fetch_object - Fetch a result row as an object
    • fbsql_fetch_row - Get a result row as an enumerated array
    • fbsql_field_flags - Get the flags associated with the specified field in a result
    • fbsql_field_len - Returns the length of the specified field
    • fbsql_field_name - Get the name of the specified field in a result
    • fbsql_field_seek - Set result pointer to a specified field offset
    • fbsql_field_table - Zwraca nazwę tabeli dla określonego pola
    • fbsql_field_type - Get the type of the specified field in a result
    • fbsql_free_result - Zwalnia pamięć zajmowaną przez wynik
    • fbsql_get_autostart_info - Pobiera informacje o bazach automatycznie uruchamianych podczas startu serwera
    • fbsql_hostname - Zraca lub ustawia nazwę hosta używaną w połączeniu
    • fbsql_insert_id - Get the id generated from the previous INSERT operation
    • fbsql_list_dbs - List databases available on a FrontBase server
    • fbsql_list_fields - List FrontBase result fields
    • fbsql_list_tables - List tables in a FrontBase database
    • fbsql_next_result - Move the internal result pointer to the next result
    • fbsql_num_fields - Get number of fields in result
    • fbsql_num_rows - Get number of rows in result
    • fbsql_password - Zwraca lub ustawia hasło użytkownika używane w połączeniu
    • fbsql_pconnect - Otwiera stałe połączenie z serwerem FrontBase
    • fbsql_query - Wysyła zapytanie do serwera FrontBase
    • fbsql_read_blob - Read a BLOB from the database
    • fbsql_read_clob - Read a CLOB from the database
    • fbsql_result - Get result data
    • fbsql_rollback - Rollback a transaction to the database
    • fbsql_rows_fetched - Get the number of rows affected by the last statement
    • fbsql_select_db - Select a FrontBase database
    • fbsql_set_characterset - Zmienia kodowanie znaków na wejściu/wyjściu
    • fbsql_set_lob_mode - Set the LOB retrieve mode for a FrontBase result set
    • fbsql_set_password - Change the password for a given user
    • fbsql_set_transaction - Set the transaction locking and isolation
    • fbsql_start_db - Uruchamia bazę danych na serwerze lokalnym lub zdalnym
    • fbsql_stop_db - Zatrzymuje bazę danych na serwerze lokalnym lub zdalnym
    • fbsql_tablename - Alias dla fbsql_table_name
    • fbsql_table_name - Get table name of field
    • fbsql_username - Zraca lub ustawia nazwę użytkownika używaną w połączeniu
    • fbsql_warnings - Enable or disable FrontBase warnings
    • fclose - Zamyka otwarty wskaźnik pliku
    • fdf_add_doc_javascript - Adds javascript code to the FDF document
    • fdf_add_template - Adds a template into the FDF document
    • fdf_close - Close an FDF document
    • fdf_create - Create a new FDF document
    • fdf_enum_values - Call a user defined function for each document value
    • fdf_errno - Return error code for last fdf operation
    • fdf_error - Return error description for FDF error code
    • fdf_get_ap - Get the appearance of a field
    • fdf_get_attachment - Extracts uploaded file embedded in the FDF
    • fdf_get_encoding - Get the value of the /Encoding key
    • fdf_get_file - Get the value of the /F key
    • fdf_get_flags - Gets the flags of a field
    • fdf_get_opt - Gets a value from the opt array of a field
    • fdf_get_status - Get the value of the /STATUS key
    • fdf_get_value - Get the value of a field
    • fdf_get_version - Gets version number for FDF API or file
    • fdf_header - Sets FDF-specific output headers
    • fdf_next_field_name - Get the next field name
    • fdf_open - Open a FDF document
    • fdf_open_string - Read a FDF document from a string
    • fdf_remove_item - Sets target frame for form
    • fdf_save - Save a FDF document
    • fdf_save_string - Returns the FDF document as a string
    • fdf_set_ap - Set the appearance of a field
    • fdf_set_encoding - Sets FDF character encoding
    • fdf_set_file - Set PDF document to display FDF data in
    • fdf_set_flags - Sets a flag of a field
    • fdf_set_javascript_action - Sets an javascript action of a field
    • fdf_set_on_import_javascript - Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt - Sets an option of a field
    • fdf_set_status - Set the value of the /STATUS key
    • fdf_set_submit_form_action - Sets a submit form action of a field
    • fdf_set_target_frame - Set target frame for form display
    • fdf_set_value - Set the value of a field
    • fdf_set_version - Sets version number for a FDF file
    • feof - Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
    • fflush - Przekierowuje wyjście do pliku
    • fgetc - Pobiera znak ze wskaźnika pliku
    • fgetcsv - Pobiera linię ze wskanika pliku i przetwarza na pola CSV
    • fgets - Pobiera linię ze wskaźnika pliku
    • fgetss - Pobiera linię ze wskaźnika pliku i usuwa znaczniki HTML
    • file - Czyta całą zawartość pliku do tablicy
    • file:// - Accessing local filesystem
    • fileatime - Pobiera ostatni czas dostępu do pliku
    • filectime - Pobiera i-węzłowy czas zmiany pliku
    • filegroup - Pobiera grupę pliku
    • fileinode - Pobiera i-węzeł pliku
    • filemtime - Pobiera czas ostatniej modyfikacji pliku
    • fileowner - Pobiera właściciela pliku
    • fileperms - Pobiera prawa dostępu pliku
    • filepro - Read and verify the map file
    • filepro_fieldcount - Find out how many fields are in a filePro database
    • filepro_fieldname - Gets the name of a field
    • filepro_fieldtype - Gets the type of a field
    • filepro_fieldwidth - Gets the width of a field
    • filepro_retrieve - Retrieves data from a filePro database
    • filepro_rowcount - Find out how many rows are in a filePro database
    • filesize - Pobiera rozmiar pliku
    • FilesystemIterator::current - The current file
    • FilesystemIterator::getFlags - Get the handling flags
    • FilesystemIterator::key - Retrieve the key for the current file
    • FilesystemIterator::next - Move to the next file
    • FilesystemIterator::rewind - Rewinds back to the beginning
    • FilesystemIterator::setFlags - Sets handling flags
    • FilesystemIterator::__construct - Constructs a new filesystem iterator
    • filetype - Pobiera typ pliku
    • file_exists - Sprawdza czy plik lub katalog istnieje
    • file_get_contents - Reads entire file into a string
    • file_put_contents - Write a string to a file
    • FilterIterator::accept - Check whether the current element of the iterator is acceptable
    • FilterIterator::current - Get the current element value
    • FilterIterator::getInnerIterator - Get the inner iterator
    • FilterIterator::key - Get the current key
    • FilterIterator::next - Move the iterator forward
    • FilterIterator::rewind - Rewind the iterator
    • FilterIterator::valid - Check whether the current element is valid
    • FilterIterator::__construct - Construct a filterIterator
    • filter_has_var - Checks if variable of specified type exists
    • filter_id - Returns the filter ID belonging to a named filter
    • filter_input - Gets a specific external variable by name and optionally filters it
    • filter_input_array - Gets external variables and optionally filters them
    • filter_list - Returns a list of all supported filters
    • filter_var - Filters a variable with a specified filter
    • filter_var_array - Gets multiple variables and optionally filters them
    • finfo_buffer - Return information about a string buffer
    • finfo_close - Close fileinfo resource
    • finfo_file - Return information about a file
    • finfo_open - Create a new fileinfo resource
    • finfo_set_flags - Set libmagic configuration options
    • floatval - Get float value of a variable
    • flock - Portable advisory file locking
    • floor - Zaokrągla ułamki w dół
    • flush - Flush the output buffer
    • fmod - Returns the floating point remainder (modulo) of the division of the arguments
    • fnmatch - Match filename against a pattern
    • fopen - Otwiera plik lub URL
    • forward_static_call - Call a static method
    • forward_static_call_array - Call a static method and pass the arguments as array
    • fpassthru - Output all remaining data on a file pointer
    • fprintf - Write a formatted string to a stream
    • fputcsv - Format line as CSV and write to file pointer
    • fputs - Alias dla fwrite
    • fread - Odczyt pliku binarnie bezpieczy
    • FrenchToJD - Converts a date from the French Republican Calendar to a Julian Day Count
    • fribidi_log2vis - Convert a logical string to a visual one
    • fscanf - Przetwarza dane z pliku według formatu
    • fseek - Seeks on a file pointer
    • fsockopen - Open Internet or Unix domain socket connection
    • fstat - Pobiera informacje o pliku używając otwartego wskaźnika pliku
    • ftell - Mówi o pozycji odczyt/zapis wskaźnika pliku
    • ftok - Convert a pathname and a project identifier to a System V IPC key
    • ftp:// - Accessing FTP(s) URLs
    • FTP context options - FTP context option listing
    • ftp_alloc - Allocates space for a file to be uploaded
    • ftp_cdup - Zmienia bieżący katalog na nadrzędny
    • ftp_chdir - Zmienia bieżący katalog na serwerze FTP
    • ftp_chmod - Set permissions on a file via FTP
    • ftp_close - Zamyka połączenie FTP
    • ftp_connect - Opens an FTP connection
    • ftp_delete - Usuwa plik na serwerze FTP
    • ftp_exec - Żąda wykonanie polecenia przez serwer FTP
    • ftp_fget - Pobiera plik z serwera FTP i zapisuje do otwartego pliku
    • ftp_fput - Wysyła dane z otwartego pliku na serwer FTP
    • ftp_get - Pobiera plik z serwera FTP
    • ftp_get_option - Pobiera ustawienia dotyczące strumienia FTP
    • ftp_login - Loguje się w ramach połączenia FTP
    • ftp_mdtm - Zwraca czas ostatniej modyfikacji podanego pliku
    • ftp_mkdir - Tworzy katalog
    • ftp_nb_continue - Continues retrieving/sending a file (non-blocking)
    • ftp_nb_fget - Retrieves a file from the FTP server and writes it to an open file (non-blocking)
    • ftp_nb_fput - Stores a file from an open file to the FTP server (non-blocking)
    • ftp_nb_get - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
    • ftp_nb_put - Stores a file on the FTP server (non-blocking)
    • ftp_nlist - Zwraca listę plików z podanego katalogu
    • ftp_pasv - Włącza lub wyłącza tryb pasywny
    • ftp_put - Przesyła plik na serwer FTP
    • ftp_pwd - Zwraca nazwę katalogu bieżącego
    • ftp_quit - Alias dla ftp_close
    • ftp_raw - Sends an arbitrary command to an FTP server
    • ftp_rawlist - Zwraca szczegółową listę plików z podanego katalogu
    • ftp_rename - Zmienia nazwę pliku lub katalogu na serwerze FTP
    • ftp_rmdir - Usuwa katalog
    • ftp_set_option - Set miscellaneous runtime FTP options
    • ftp_site - Wysyła polecenie SITE do serwera FTP
    • ftp_size - Zwraca rozmiar podanego pliku
    • ftp_ssl_connect - Opens an Secure SSL-FTP connection
    • ftp_systype - Zwraca identyfikator typu systemu dla zdalnego serwera FTP
    • ftruncate - Przycina plik do podanej długości
    • function_exists - Return TRUE if the given function has been defined
    • func_get_arg - Return an item from the argument list
    • func_get_args - Returns an array comprising a function's argument list
    • func_num_args - Returns the number of arguments passed to the function
    • fwrite - Zapis pliku binarnie bezpieczny
  • g
    • gc_collect_cycles - Forces collection of any existing garbage cycles
    • gc_disable - Deactivates the circular reference collector
    • gc_enable - Activates the circular reference collector
    • gc_enabled - Returns status of the circular reference collector
    • gd_info - Retrieve information about the currently installed GD library
    • GearmanClient::addOptions - Add client options
    • GearmanClient::addServer - Add a job server to the client
    • GearmanClient::addServers - Add a list of job servers to the client
    • GearmanClient::addTask - Add a task to be run in parallel
    • GearmanClient::addTaskBackground - Add a background task to be run in parallel
    • GearmanClient::addTaskHigh - Add a high priority task to run in parallel
    • GearmanClient::addTaskHighBackground - Add a high priority background task to be run in parallel
    • GearmanClient::addTaskLow - Add a low priority task to run in parallel
    • GearmanClient::addTaskLowBackground - Add a low priority background task to be run in parallel
    • GearmanClient::addTaskStatus - Add a task to get status
    • GearmanClient::clearCallbacks - Clear all task callback functions
    • GearmanClient::clone - Create a copy of a GearmanClient object
    • GearmanClient::context - Get the application context
    • GearmanClient::data - Get the application data (deprecated)
    • GearmanClient::do - Run a single task and return a result [deprecated]
    • GearmanClient::doBackground - Run a task in the background
    • GearmanClient::doHigh - Run a single high priority task
    • GearmanClient::doHighBackground - Run a high priority task in the background
    • GearmanClient::doJobHandle - Get the job handle for the running task
    • GearmanClient::doLow - Run a single low priority task
    • GearmanClient::doLowBackground - Run a low priority task in the background
    • GearmanClient::doNormal - Run a single task and return a result
    • GearmanClient::doStatus - Get the status for the running task
    • GearmanClient::echo - Send data to all job servers to see if they echo it back [deprecated]
    • GearmanClient::error - Returns an error string for the last error encountered.
    • GearmanClient::getErrno - Get an errno value
    • GearmanClient::jobStatus - Get the status of a background job
    • GearmanClient::ping - Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions - Remove client options
    • GearmanClient::returnCode - Get the last Gearman return code
    • GearmanClient::runTasks - Run a list of tasks in parallel
    • GearmanClient::setClientCallback - Callback function when there is a data packet for a task (deprecated)
    • GearmanClient::setCompleteCallback - Set a function to be called on task completion
    • GearmanClient::setContext - Set application context
    • GearmanClient::setCreatedCallback - Set a callback for when a task is queued
    • GearmanClient::setData - Set application data (deprecated)
    • GearmanClient::setDataCallback - Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback - Set a callback for worker exceptions
    • GearmanClient::setFailCallback - Set callback for job failure
    • GearmanClient::setOptions - Set client options
    • GearmanClient::setStatusCallback - Set a callback for collecting task status
    • GearmanClient::setTimeout - Set socket I/O activity timeout
    • GearmanClient::setWarningCallback - Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback - Set a callback for accepting incremental data updates
    • GearmanClient::timeout - Get current socket I/O activity timeout value
    • GearmanClient::__construct - Create a GearmanClient instance
    • GearmanJob::complete - Send the result and complete status (deprecated)
    • GearmanJob::data - Send data for a running job (deprecated)
    • GearmanJob::exception - Send exception for running job (deprecated)
    • GearmanJob::fail - Send fail status (deprecated)
    • GearmanJob::functionName - Get function name
    • GearmanJob::handle - Get the job handle
    • GearmanJob::returnCode - Get last return code
    • GearmanJob::sendComplete - Send the result and complete status
    • GearmanJob::sendData - Send data for a running job
    • GearmanJob::sendException - Send exception for running job (exception)
    • GearmanJob::sendFail - Send fail status
    • GearmanJob::sendStatus - Send status
    • GearmanJob::sendWarning - Send a warning
    • GearmanJob::setReturn - Set a return value
    • GearmanJob::status - Send status (deprecated)
    • GearmanJob::unique - Get the unique identifier
    • GearmanJob::warning - Send a warning (deprecated)
    • GearmanJob::workload - Get workload
    • GearmanJob::workloadSize - Get size of work load
    • GearmanJob::__construct - Create a GearmanJob instance
    • GearmanTask::create - Create a task (deprecated)
    • GearmanTask::data - Get data returned for a task
    • GearmanTask::dataSize - Get the size of returned data
    • GearmanTask::function - Get associated function name (deprecated)
    • GearmanTask::functionName - Get associated function name
    • GearmanTask::isKnown - Determine if task is known
    • GearmanTask::isRunning - Test whether the task is currently running
    • GearmanTask::jobHandle - Get the job handle
    • GearmanTask::recvData - Read work or result data into a buffer for a task
    • GearmanTask::returnCode - Get the last return code
    • GearmanTask::sendData - Send data for a task (deprecated)
    • GearmanTask::sendWorkload - Send data for a task
    • GearmanTask::taskDenominator - Get completion percentage denominator
    • GearmanTask::taskNumerator - Get completion percentage numerator
    • GearmanTask::unique - Get the unique identifier for a task
    • GearmanTask::uuid - Get the unique identifier for a task (deprecated)
    • GearmanTask::__construct - Create a GearmanTask instance
    • GearmanWorker::addFunction - Register and add callback function
    • GearmanWorker::addOptions - Add worker options
    • GearmanWorker::addServer - Add a job server
    • GearmanWorker::addServers - Add job servers
    • GearmanWorker::clone - Create a copy of the worker
    • GearmanWorker::echo - Test job server response
    • GearmanWorker::error - Get the last error encountered
    • GearmanWorker::getErrno - Get errno
    • GearmanWorker::options - Get worker options
    • GearmanWorker::register - Register a function with the job server
    • GearmanWorker::removeOptions - Remove worker options
    • GearmanWorker::returnCode - Get last Gearman return code
    • GearmanWorker::setOptions - Set worker options
    • GearmanWorker::setTimeout - Set socket I/O activity timeout
    • GearmanWorker::timeout - Get socket I/O activity timeout
    • GearmanWorker::unregister - Unregister a function name with the job servers
    • GearmanWorker::unregisterAll - Unregister all function names with the job servers
    • GearmanWorker::wait - Wait for activity from one of the job servers
    • GearmanWorker::work - Wait for and perform jobs
    • GearmanWorker::__construct - Create a GearmanWorker instance
    • geoip_continent_code_by_name - Get the two letter continent code
    • geoip_country_code3_by_name - Get the three letter country code
    • geoip_country_code_by_name - Get the two letter country code
    • geoip_country_name_by_name - Get the full country name
    • geoip_database_info - Get GeoIP Database information
    • geoip_db_avail - Determine if GeoIP Database is available
    • geoip_db_filename - Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info - Returns detailed information about all GeoIP database types
    • geoip_id_by_name - Get the Internet connection type
    • geoip_isp_by_name - Get the Internet Service Provider (ISP) name
    • geoip_org_by_name - Get the organization name
    • geoip_record_by_name - Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name - Get the country code and region
    • geoip_region_name_by_code - Returns the region name for some country and region code combo
    • geoip_time_zone_by_country_and_region - Returns the time zone for some country and region code combo
    • getallheaders - Odczytuje wszystkie nagłówki HTTP z aktualnego zapytania
    • getcwd - Wskazuje bieżący katalog roboczy
    • getdate - Pobiera informację o dacie/czasie
    • getenv - Gets the value of an environment variable
    • gethostbyaddr - Get the Internet host name corresponding to a given IP address
    • gethostbyname - Get the IPv4 address corresponding to a given Internet host name
    • gethostbynamel - Get a list of IPv4 addresses corresponding to a given Internet host name
    • gethostname - Gets the host name
    • getimagesize - Get the size of an image
    • getlastmod - Gets time of last page modification
    • getmxrr - Get MX records corresponding to a given Internet host name
    • getmygid - Get PHP script owner's GID
    • getmyinode - Gets the inode of the current script
    • getmypid - Gets PHP's process ID
    • getmyuid - Gets PHP script owner's UID
    • getopt - Gets options from the command line argument list
    • getprotobyname - Get protocol number associated with protocol name
    • getprotobynumber - Get protocol name associated with protocol number
    • getrandmax - Największa możliwa liczba losowa
    • getrusage - Gets the current resource usages
    • getservbyname - Get port number associated with an Internet service and protocol
    • getservbyport - Get Internet service which corresponds to port and protocol
    • gettext - Lookup a message in the current domain
    • gettimeofday - Pobiera aktualny czas
    • gettype - Get the type of a variable
    • get_browser - Tells what the user's browser is capable of
    • get_called_class - the "Late Static Binding" class name
    • get_cfg_var - Gets the value of a PHP configuration option
    • get_class - Zwraca nazwę klasy zadanego obiektu
    • get_class_methods - Zwraca tablicę nazw metod danej klasy
    • get_class_vars - Zwraca tablicę domyślnych właściwości klasy
    • get_current_user - Gets the name of the owner of the current PHP script
    • get_declared_classes - Zwraca tablicę z nazwami zdefiniowanych klas
    • get_declared_interfaces - Returns an array of all declared interfaces
    • get_declared_traits - Returns an array of all declared traits
    • get_defined_constants - Returns an associative array with the names of all the constants and their values
    • get_defined_functions - Returns an array of all defined functions
    • get_defined_vars - Returns an array of all defined variables
    • get_extension_funcs - Returns an array with the names of the functions of a module
    • get_headers - Fetches all the headers sent by the server in response to a HTTP request
    • get_html_translation_table - Returns the translation table used by htmlspecialchars and htmlentities
    • get_included_files - Returns an array with the names of included or required files
    • get_include_path - Gets the current include_path configuration option
    • get_loaded_extensions - Returns an array with the names of all modules compiled and loaded
    • get_magic_quotes_gpc - Gets the current configuration setting of magic_quotes_gpc
    • get_magic_quotes_runtime - Gets the current active configuration setting of magic_quotes_runtime
    • get_meta_tags - Extracts all meta tag content attributes from a file and returns an array
    • get_object_vars - Zwraca tablicę asocjacyjną właściwości obiektu
    • get_parent_class - Pobiera nazwę klasy przodka dla obiektu lub klasy
    • get_required_files - Alias dla get_included_files
    • get_resource_type - Returns the resource type
    • glob - Find pathnames matching a pattern
    • glob:// - Find pathnames matching pattern
    • GlobIterator::count - Get the number of directories and files
    • GlobIterator::__construct - Construct a directory using glob
    • Gmagick::addimage - Adds new image to Gmagick object image list
    • Gmagick::addnoiseimage - Adds random noise to the image
    • Gmagick::annotateimage - Annotates an image with text
    • Gmagick::blurimage - Adds blur filter to image
    • Gmagick::borderimage - Surrounds the image with a border
    • Gmagick::charcoalimage - Simulates a charcoal drawing
    • Gmagick::chopimage - Removes a region of an image and trims
    • Gmagick::clear - Clears all resources associated to Gmagick object
    • Gmagick::commentimage - Adds a comment to your image
    • Gmagick::compositeimage - Composite one image onto another
    • Gmagick::cropimage - Extracts a region of the image
    • Gmagick::cropthumbnailimage - Creates a crop thumbnail
    • Gmagick::current - The current purpose
    • Gmagick::cyclecolormapimage - Displaces an image's colormap
    • Gmagick::deconstructimages - Returns certain pixel differences between images
    • Gmagick::despeckleimage - The despeckleimage purpose
    • Gmagick::destroy - The destroy purpose
    • Gmagick::drawimage - Renders the GmagickDraw object on the current image
    • Gmagick::edgeimage - Enhance edges within the image
    • Gmagick::embossimage - Returns a grayscale image with a three-dimensional effect
    • Gmagick::enhanceimage - Improves the quality of a noisy image
    • Gmagick::equalizeimage - Equalizes the image histogram
    • Gmagick::flipimage - Creates a vertical mirror image
    • Gmagick::flopimage - The flopimage purpose
    • Gmagick::frameimage - Adds a simulated three-dimensional border
    • Gmagick::gammaimage - Gamma-corrects an image
    • Gmagick::getcopyright - Returns the GraphicsMagick API copyright as a string
    • Gmagick::getfilename - The filename associated with an image sequence
    • Gmagick::getimagebackgroundcolor - Returns the image background color
    • Gmagick::getimageblueprimary - Returns the chromaticy blue primary point
    • Gmagick::getimagebordercolor - Returns the image border color
    • Gmagick::getimagechanneldepth - Gets the depth for a particular image channel
    • Gmagick::getimagecolors - Returns the color of the specified colormap index
    • Gmagick::getimagecolorspace - Gets the image colorspace
    • Gmagick::getimagecompose - Returns the composite operator associated with the image
    • Gmagick::getimagedelay - Gets the image delay
    • Gmagick::getimagedepth - Gets the depth of the image
    • Gmagick::getimagedispose - Gets the image disposal method
    • Gmagick::getimageextrema - Gets the extrema for the image
    • Gmagick::getimagefilename - Returns the filename of a particular image in a sequence
    • Gmagick::getimageformat - Returns the format of a particular image in a sequence
    • Gmagick::getimagegamma - Gets the image gamma
    • Gmagick::getimagegreenprimary - Returns the chromaticy green primary point
    • Gmagick::getimageheight - Returns the image height
    • Gmagick::getimagehistogram - Gets the image histogram
    • Gmagick::getimageindex - Gets the index of the current active image
    • Gmagick::getimageinterlacescheme - Gets the image interlace scheme
    • Gmagick::getimageiterations - Gets the image iterations
    • Gmagick::getimagematte - Return if the image has a matte channel
    • Gmagick::getimagemattecolor - Returns the image matte color
    • Gmagick::getimageprofile - Returns the named image profile.
    • Gmagick::getimageredprimary - Returns the chromaticity red primary point
    • Gmagick::getimagerenderingintent - Gets the image rendering intent
    • Gmagick::getimageresolution - Gets the image X and Y resolution
    • Gmagick::getimagescene - Gets the image scene
    • Gmagick::getimagesignature - Generates an SHA-256 message digest
    • Gmagick::getimagetype - Gets the potential image type.
    • Gmagick::getimageunits - Gets the image units of resolution
    • Gmagick::getimagewhitepoint - Returns the chromaticity white point
    • Gmagick::getimagewidth - Returns the width of the image
    • Gmagick::getpackagename - Returns the GraphicsMagick package name.
    • Gmagick::getquantumdepth - Returns the Gmagick quantum depth as a string.
    • Gmagick::getreleasedate - Returns the GraphicsMagick release date as a string.
    • Gmagick::getsamplingfactors - Gets the horizontal and vertical sampling factor.
    • Gmagick::getsize - Returns the size associated with the Gmagick object
    • Gmagick::getversion - Returns the GraphicsMagick API version
    • Gmagick::hasnextimage - Checks if the object has more images
    • Gmagick::haspreviousimage - Checks if the object has a previous image
    • Gmagick::implodeimage - Creates a new image as a copy
    • Gmagick::labelimage - Adds a label to an image.
    • Gmagick::levelimage - Adjusts the levels of an image
    • Gmagick::magnifyimage - Scales an image proportionally 2x
    • Gmagick::mapimage - Replaces the colors of an image with the closest color from a reference image.
    • Gmagick::medianfilterimage - Applies a digital filter
    • Gmagick::minifyimage - Scales an image proportionally to half its size
    • Gmagick::modulateimage - Control the brightness, saturation, and hue
    • Gmagick::motionblurimage - Simulates motion blur
    • Gmagick::newimage - Creates a new image
    • Gmagick::nextimage - Moves to the next image
    • Gmagick::normalizeimage - Enhances the contrast of a color image
    • Gmagick::oilpaintimage - Simulates an oil painting
    • Gmagick::previousimage - Move to the previous image in the object
    • Gmagick::profileimage - Adds or removes a profile from an image
    • Gmagick::quantizeimage - Analyzes the colors within a reference image
    • Gmagick::quantizeimages - The quantizeimages purpose
    • Gmagick::queryfontmetrics - Returns an array representing the font metrics
    • Gmagick::queryfonts - Returns the configured fonts
    • Gmagick::queryformats - Returns formats supported by Gmagick.
    • Gmagick::radialblurimage - Radial blurs an image
    • Gmagick::raiseimage - Creates a simulated 3d button-like effect
    • Gmagick::read - Reads image from filename
    • Gmagick::readimage - Reads image from filename
    • Gmagick::readimageblob - Reads image from a binary string
    • Gmagick::readimagefile - The readimagefile purpose
    • Gmagick::reducenoiseimage - Smooths the contours of an image
    • Gmagick::removeimage - Removes an image from the image list
    • Gmagick::removeimageprofile - Removes the named image profile and returns it
    • Gmagick::resampleimage - Resample image to desired resolution
    • Gmagick::resizeimage - Scales an image
    • Gmagick::rollimage - Offsets an image
    • Gmagick::rotateimage - Rotates an image
    • Gmagick::scaleimage - Scales the size of an image
    • Gmagick::separateimagechannel - Separates a channel from the image
    • Gmagick::setfilename - Sets the filename before you read or write the image
    • Gmagick::setimagebackgroundcolor - Sets the image background color.
    • Gmagick::setimageblueprimary - Sets the image chromaticity blue primary point.
    • Gmagick::setimagebordercolor - Sets the image border color.
    • Gmagick::setimagechanneldepth - Sets the depth of a particular image channel
    • Gmagick::setimagecolorspace - Sets the image colorspace
    • Gmagick::setimagecompose - Sets the image composite operator
    • Gmagick::setimagedelay - Sets the image delay
    • Gmagick::setimagedepth - Sets the image depth
    • Gmagick::setimagedispose - Sets the image disposal method
    • Gmagick::setimagefilename - Sets the filename of a particular image in a sequence
    • Gmagick::setimageformat - Sets the format of a particular image
    • Gmagick::setimagegamma - Sets the image gamma
    • Gmagick::setimagegreenprimary - TSets the image chromaticity green primary point.
    • Gmagick::setimageindex - Set the iterator to the position in the image list specified with the index parameter
    • Gmagick::setimageinterlacescheme - Sets the interlace scheme of the image.
    • Gmagick::setimageiterations - Sets the image iterations.
    • Gmagick::setimageprofile - Adds a named profile to the Gmagick object
    • Gmagick::setimageredprimary - Sets the image chromaticity red primary point.
    • Gmagick::setimagerenderingintent - Sets the image rendering intent
    • Gmagick::setimageresolution - Sets the image resolution
    • Gmagick::setimagescene - Sets the image scene
    • Gmagick::setimagetype - Sets the image type
    • Gmagick::setimageunits - Sets the image units of resolution.
    • Gmagick::setimagewhitepoint - Sets the image chromaticity white point.
    • Gmagick::setsamplingfactors - Sets the image sampling factors.
    • Gmagick::setsize - Sets the size of the Gmagick object
    • Gmagick::shearimage - Creating a parallelogram
    • Gmagick::solarizeimage - Applies a solarizing effect to the image
    • Gmagick::spreadimage - Randomly displaces each pixel in a block
    • Gmagick::stripimage - Strips an image of all profiles and comments
    • Gmagick::swirlimage - Swirls the pixels about the center of the image
    • Gmagick::thumbnailimage - Changes the size of an image
    • Gmagick::trimimage - Remove edges from the image
    • Gmagick::write - Writes an image to the specified filename
    • Gmagick::writeimage - Writes an image to the specified filename
    • Gmagick::__construct - The Gmagick constructor
    • GmagickDraw::annotate - Draws text on the image
    • GmagickDraw::arc - Draws an arc
    • GmagickDraw::bezier - Draws a bezier curve
    • GmagickDraw::ellipse - Draws an ellipse on the image
    • GmagickDraw::getfillcolor - Returns the fill color
    • GmagickDraw::getfillopacity - Returns the opacity used when drawing
    • GmagickDraw::getfont - Returns the font
    • GmagickDraw::getfontsize - Returns the font pointsize
    • GmagickDraw::getfontstyle - Returns the font style
    • GmagickDraw::getfontweight - Returns the font weight
    • GmagickDraw::getstrokecolor - Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity - Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth - Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration - Returns the text decoration
    • GmagickDraw::gettextencoding - Returns the code set used for text annotations
    • GmagickDraw::line - The line purpose
    • GmagickDraw::point - Draws a point
    • GmagickDraw::polygon - Draws a polygon
    • GmagickDraw::polyline - Draws a polyline
    • GmagickDraw::rectangle - Draws a rectangle
    • GmagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle - Draws a rounded rectangle
    • GmagickDraw::scale - Adjusts the scaling factor
    • GmagickDraw::setfillcolor - Sets the fill color to be used for drawing filled objects.
    • GmagickDraw::setfillopacity - The setfillopacity purpose
    • GmagickDraw::setfont - Sets the fully-specified font to use when annotating with text.
    • GmagickDraw::setfontsize - Sets the font pointsize to use when annotating with text.
    • GmagickDraw::setfontstyle - Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight - Sets the font weight
    • GmagickDraw::setstrokecolor - Sets the color used for stroking object outlines.
    • GmagickDraw::setstrokeopacity - Specifies the opacity of stroked object outlines.
    • GmagickDraw::setstrokewidth - Sets the width of the stroke used to draw object outlines.
    • GmagickDraw::settextdecoration - Specifies a decoration
    • GmagickDraw::settextencoding - Specifies specifies the text code set
    • GmagickPixel::getcolor - Returns the color
    • GmagickPixel::getcolorcount - Returns the color count associated with this color
    • GmagickPixel::getcolorvalue - Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor - Sets the color
    • GmagickPixel::setcolorvalue - Sets the normalized value of one of the channels
    • GmagickPixel::__construct - The GmagickPixel constructor
    • gmdate - Formatuje datę/czas dla strefy GMT/UTC
    • gmmktime - Ustala uniksowy znacznik czasu dla daty ze strefy GMT
    • gmp_abs - Absolute value
    • gmp_add - Add numbers
    • gmp_and - Bitwise AND
    • gmp_clrbit - Clear bit
    • gmp_cmp - Compare numbers
    • gmp_com - Calculates one's complement
    • gmp_div - Alias dla gmp_div_q
    • gmp_divexact - Exact division of numbers
    • gmp_div_q - Divide numbers
    • gmp_div_qr - Divide numbers and get quotient and remainder
    • gmp_div_r - Remainder of the division of numbers
    • gmp_fact - Factorial
    • gmp_gcd - Calculate GCD
    • gmp_gcdext - Calculate GCD and multipliers
    • gmp_hamdist - Hamming distance
    • gmp_init - Create GMP number
    • gmp_intval - Convert GMP number to integer
    • gmp_invert - Inverse by modulo
    • gmp_jacobi - Jacobi symbol
    • gmp_legendre - Legendre symbol
    • gmp_mod - Modulo operation
    • gmp_mul - Multiply numbers
    • gmp_neg - Negate number
    • gmp_nextprime - Find next prime number
    • gmp_or - Bitwise OR
    • gmp_perfect_square - Perfect square check
    • gmp_popcount - Population count
    • gmp_pow - Raise number into power
    • gmp_powm - Raise number into power with modulo
    • gmp_prob_prime - Check if number is "probably prime"
    • gmp_random - Random number
    • gmp_scan0 - Scan for 0
    • gmp_scan1 - Scan for 1
    • gmp_setbit - Set bit
    • gmp_sign - Sign of number
    • gmp_sqrt - Calculate square root
    • gmp_sqrtrem - Square root with remainder
    • gmp_strval - Convert GMP number to string
    • gmp_sub - Subtract numbers
    • gmp_testbit - Tests if a bit is set
    • gmp_xor - Bitwise XOR
    • gmstrftime - Formatuje czas/datę ze strefy GMT/UTC zgodnie z lokalizacją
    • gnupg_adddecryptkey - Add a key for decryption
    • gnupg_addencryptkey - Add a key for encryption
    • gnupg_addsignkey - Add a key for signing
    • gnupg_cleardecryptkeys - Removes all keys which were set for decryption before
    • gnupg_clearencryptkeys - Removes all keys which were set for encryption before
    • gnupg_clearsignkeys - Removes all keys which were set for signing before
    • gnupg_decrypt - Decrypts a given text
    • gnupg_decryptverify - Decrypts and verifies a given text
    • gnupg_encrypt - Encrypts a given text
    • gnupg_encryptsign - Encrypts and signs a given text
    • gnupg_export - Exports a key
    • gnupg_geterror - Returns the errortext, if a function fails
    • gnupg_getprotocol - Returns the currently active protocol for all operations
    • gnupg_import - Imports a key
    • gnupg_init - Initialize a connection
    • gnupg_keyinfo - Returns an array with information about all keys that matches the given pattern
    • gnupg_setarmor - Toggle armored output
    • gnupg_seterrormode - Sets the mode for error_reporting
    • gnupg_setsignmode - Sets the mode for signing
    • gnupg_sign - Signs a given text
    • gnupg_verify - Verifies a signed text
    • gopher_parsedir - Translate a gopher formatted directory entry into an associative array.
    • grapheme_extract - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.
    • grapheme_stripos - Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack.
    • grapheme_strlen - Get string length in grapheme units
    • grapheme_strpos - Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos - Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos - Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr - Returns part of haystack string from the first occurrence of needle to the end of haystack.
    • grapheme_substr - Return part of a string
    • GregorianToJD - Converts a Gregorian date to Julian Day Count
    • gupnp_context_get_host_ip - Get the IP address
    • gupnp_context_get_port - Get the port
    • gupnp_context_get_subscription_timeout - Get the event subscription timeout
    • gupnp_context_host_path - Start hosting
    • gupnp_context_new - Create a new context
    • gupnp_context_set_subscription_timeout - Sets the event subscription timeout
    • gupnp_context_timeout_add - Sets a function to be called at regular intervals
    • gupnp_context_unhost_path - Stop hosting
    • gupnp_control_point_browse_start - Start browsing
    • gupnp_control_point_browse_stop - Stop browsing
    • gupnp_control_point_callback_set - Set control point callback
    • gupnp_control_point_new - Create a new control point
    • gupnp_device_action_callback_set - Set device callback function
    • gupnp_device_info_get - Get info of root device
    • gupnp_device_info_get_service - Get the service with type
    • gupnp_root_device_get_available - Check whether root device is available
    • gupnp_root_device_get_relative_location - Get the relative location of root device.
    • gupnp_root_device_new - Create a new root device
    • gupnp_root_device_set_available - Set whether or not root_device is available
    • gupnp_root_device_start - Start main loop
    • gupnp_root_device_stop - Stop main loop
    • gupnp_service_action_get - Retrieves the specified action arguments
    • gupnp_service_action_return - Return succesfully
    • gupnp_service_action_return_error - Return error code
    • gupnp_service_action_set - Sets the specified action return values
    • gupnp_service_freeze_notify - Freeze new notifications
    • gupnp_service_info_get - Get full info of service
    • gupnp_service_info_get_introspection - Get resource introspection of service
    • gupnp_service_introspection_get_state_variable - Returns the state variable data
    • gupnp_service_notify - Notifies listening clients
    • gupnp_service_proxy_action_get - Send action to the service and get value
    • gupnp_service_proxy_action_set - Send action to the service and set value
    • gupnp_service_proxy_add_notify - Sets up callback for variable change notification
    • gupnp_service_proxy_callback_set - Set service proxy callback for signal
    • gupnp_service_proxy_get_subscribed - Check whether subscription is valid to the service
    • gupnp_service_proxy_remove_notify - Cancels the variable change notification
    • gupnp_service_proxy_send_action - Send action with multiple parameters synchronously
    • gupnp_service_proxy_set_subscribed - (Un)subscribes to the service.
    • gupnp_service_thaw_notify - Sends out any pending notifications and stops queuing of new ones.
    • gzclose - Close an open gz-file pointer
    • gzcompress - Compress a string
    • gzdecode - Decodes a gzip compressed string
    • gzdeflate - Deflate a string
    • gzencode - Create a gzip compressed string
    • gzeof - Test for EOF on a gz-file pointer
    • gzfile - Read entire gz-file into an array
    • gzgetc - Get character from gz-file pointer
    • gzgets - Get line from file pointer
    • gzgetss - Get line from gz-file pointer and strip HTML tags
    • gzinflate - Inflate a deflated string
    • gzopen - Open gz-file
    • gzpassthru - Output all remaining data on a gz-file pointer
    • gzputs - Alias dla gzwrite
    • gzread - Binary-safe gz-file read
    • gzrewind - Rewind the position of a gz-file pointer
    • gzseek - Seek on a gz-file pointer
    • gztell - Tell gz-file pointer read/write position
    • gzuncompress - Uncompress a compressed string
    • gzwrite - Binary-safe gz-file write
  • h
    • HaruAnnotation::setBorderStyle - Set the border style of the annotation
    • HaruAnnotation::setHighlightMode - Set the highlighting mode of the annotation
    • HaruAnnotation::setIcon - Set the icon style of the annotation
    • HaruAnnotation::setOpened - Set the initial state of the annotation
    • HaruDestination::setFit - Set the appearance of the page to fit the window
    • HaruDestination::setFitB - Set the appearance of the page to fit the bounding box of the page within the window
    • HaruDestination::setFitBH - Set the appearance of the page to fit the width of the bounding box
    • HaruDestination::setFitBV - Set the appearance of the page to fit the height of the boudning box
    • HaruDestination::setFitH - Set the appearance of the page to fit the window width
    • HaruDestination::setFitR - Set the appearance of the page to fit the specified rectangle
    • HaruDestination::setFitV - Set the appearance of the page to fit the window height
    • HaruDestination::setXYZ - Set the appearance of the page
    • HaruDoc::addPage - Add new page to the document
    • HaruDoc::addPageLabel - Set the numbering style for the specified range of pages
    • HaruDoc::createOutline - Create a HaruOutline instance
    • HaruDoc::getCurrentEncoder - Get HaruEncoder currently used in the document
    • HaruDoc::getCurrentPage - Return current page of the document
    • HaruDoc::getEncoder - Get HaruEncoder instance for the specified encoding
    • HaruDoc::getFont - Get HaruFont instance
    • HaruDoc::getInfoAttr - Get current value of the specified document attribute
    • HaruDoc::getPageLayout - Get current page layout
    • HaruDoc::getPageMode - Get current page mode
    • HaruDoc::getStreamSize - Get the size of the temporary stream
    • HaruDoc::insertPage - Insert new page just before the specified page
    • HaruDoc::loadJPEG - Load a JPEG image
    • HaruDoc::loadPNG - Load PNG image and return HaruImage instance
    • HaruDoc::loadRaw - Load a RAW image
    • HaruDoc::loadTTC - Load the font with the specified index from TTC file
    • HaruDoc::loadTTF - Load TTF font file
    • HaruDoc::loadType1 - Load Type1 font
    • HaruDoc::output - Write the document data to the output buffer
    • HaruDoc::readFromStream - Read data from the temporary stream
    • HaruDoc::resetError - Reset error state of the document handle
    • HaruDoc::resetStream - Rewind the temporary stream
    • HaruDoc::save - Save the document into the specified file
    • HaruDoc::saveToStream - Save the document into a temporary stream
    • HaruDoc::setCompressionMode - Set compression mode for the document
    • HaruDoc::setCurrentEncoder - Set the current encoder for the document
    • HaruDoc::setEncryptionMode - Set encryption mode for the document
    • HaruDoc::setInfoAttr - Set the info attribute of the document
    • HaruDoc::setInfoDateAttr - Set the datetime info attributes of the document
    • HaruDoc::setOpenAction - Define which page is shown when the document is opened
    • HaruDoc::setPageLayout - Set how pages should be displayed
    • HaruDoc::setPageMode - Set how the document should be displayed
    • HaruDoc::setPagesConfiguration - Set the number of pages per set of pages
    • HaruDoc::setPassword - Set owner and user passwords for the document
    • HaruDoc::setPermission - Set permissions for the document
    • HaruDoc::useCNSEncodings - Enable Chinese simplified encodings
    • HaruDoc::useCNSFonts - Enable builtin Chinese simplified fonts
    • HaruDoc::useCNTEncodings - Enable Chinese traditional encodings
    • HaruDoc::useCNTFonts - Enable builtin Chinese traditional fonts
    • HaruDoc::useJPEncodings - Enable Japanese encodings
    • HaruDoc::useJPFonts - Enable builtin Japanese fonts
    • HaruDoc::useKREncodings - Enable Korean encodings
    • HaruDoc::useKRFonts - Enable builtin Korean fonts
    • HaruDoc::__construct - Construct new HaruDoc instance
    • HaruEncoder::getByteType - Get the type of the byte in the text
    • HaruEncoder::getType - Get the type of the encoder
    • HaruEncoder::getUnicode - Convert the specified character to unicode
    • HaruEncoder::getWritingMode - Get the writing mode of the encoder
    • HaruFont::getAscent - Get the vertical ascent of the font
    • HaruFont::getCapHeight - Get the distance from the baseline of uppercase letters
    • HaruFont::getDescent - Get the vertical descent of the font
    • HaruFont::getEncodingName - Get the name of the encoding
    • HaruFont::getFontName - Get the name of the font
    • HaruFont::getTextWidth - Get the total width of the text, number of characters, number of words and number of spaces
    • HaruFont::getUnicodeWidth - Get the width of the character in the font
    • HaruFont::getXHeight - Get the distance from the baseline of lowercase letters
    • HaruFont::measureText - Calculate the number of characters which can be included within the specified width
    • HaruImage::getBitsPerComponent - Get the number of bits used to describe each color component of the image
    • HaruImage::getColorSpace - Get the name of the color space
    • HaruImage::getHeight - Get the height of the image
    • HaruImage::getSize - Get size of the image
    • HaruImage::getWidth - Get the width of the image
    • HaruImage::setColorMask - Set the color mask of the image
    • HaruImage::setMaskImage - Set the image mask
    • HaruOutline::setDestination - Set the destination for the outline
    • HaruOutline::setOpened - Set the initial state of the outline
    • HaruPage::arc - Append an arc to the current path
    • HaruPage::beginText - Begin a text object and set the current text position to (0,0)
    • HaruPage::circle - Append a circle to the current path
    • HaruPage::closePath - Append a straight line from the current point to the start point of the path
    • HaruPage::concat - Concatenate current transformation matrix of the page and the specified matrix
    • HaruPage::createDestination - Create new HaruDestination instance
    • HaruPage::createLinkAnnotation - Create new HaruAnnotation instance
    • HaruPage::createTextAnnotation - Create new HaruAnnotation instance
    • HaruPage::createURLAnnotation - Create and return new HaruAnnotation instance
    • HaruPage::curveTo - Append a Bezier curve to the current path
    • HaruPage::curveTo2 - Append a Bezier curve to the current path
    • HaruPage::curveTo3 - Append a Bezier curve to the current path
    • HaruPage::drawImage - Show image at the page
    • HaruPage::ellipse - Append an ellipse to the current path
    • HaruPage::endPath - End current path object without filling and painting operations
    • HaruPage::endText - End current text object
    • HaruPage::eofill - Fill current path using even-odd rule
    • HaruPage::eoFillStroke - Fill current path using even-odd rule, then paint the path
    • HaruPage::fill - Fill current path using nonzero winding number rule
    • HaruPage::fillStroke - Fill current path using nonzero winding number rule, then paint the path
    • HaruPage::getCharSpace - Get the current value of character spacing
    • HaruPage::getCMYKFill - Get the current filling color
    • HaruPage::getCMYKStroke - Get the current stroking color
    • HaruPage::getCurrentFont - Get the currently used font
    • HaruPage::getCurrentFontSize - Get the current font size
    • HaruPage::getCurrentPos - Get the current position for path painting
    • HaruPage::getCurrentTextPos - Get the current position for text printing
    • HaruPage::getDash - Get the current dash pattern
    • HaruPage::getFillingColorSpace - Get the current filling color space
    • HaruPage::getFlatness - Get the flatness of the page
    • HaruPage::getGMode - Get the current graphics mode
    • HaruPage::getGrayFill - Get the current filling color
    • HaruPage::getGrayStroke - Get the current stroking color
    • HaruPage::getHeight - Get the height of the page
    • HaruPage::getHorizontalScaling - Get the current value of horizontal scaling
    • HaruPage::getLineCap - Get the current line cap style
    • HaruPage::getLineJoin - Get the current line join style
    • HaruPage::getLineWidth - Get the current line width
    • HaruPage::getMiterLimit - Get the value of miter limit
    • HaruPage::getRGBFill - Get the current filling color
    • HaruPage::getRGBStroke - Get the current stroking color
    • HaruPage::getStrokingColorSpace - Get the current stroking color space
    • HaruPage::getTextLeading - Get the current value of line spacing
    • HaruPage::getTextMatrix - Get the current text transformation matrix of the page
    • HaruPage::getTextRenderingMode - Get the current text rendering mode
    • HaruPage::getTextRise - Get the current value of text rising
    • HaruPage::getTextWidth - Get the width of the text using current fontsize, character spacing and word spacing
    • HaruPage::getTransMatrix - Get the current transformation matrix of the page
    • HaruPage::getWidth - Get the width of the page
    • HaruPage::getWordSpace - Get the current value of word spacing
    • HaruPage::lineTo - Draw a line from the current point to the specified point
    • HaruPage::measureText - Calculate the number of characters which can be included within the specified width
    • HaruPage::moveTextPos - Move text position to the specified offset
    • HaruPage::moveTo - Set starting point for new drawing path
    • HaruPage::moveToNextLine - Move text position to the start of the next line
    • HaruPage::rectangle - Append a rectangle to the current path
    • HaruPage::setCharSpace - Set character spacing for the page
    • HaruPage::setCMYKFill - Set filling color for the page
    • HaruPage::setCMYKStroke - Set stroking color for the page
    • HaruPage::setDash - Set the dash pattern for the page
    • HaruPage::setFlatness - Set flatness for the page
    • HaruPage::setFontAndSize - Set font and fontsize for the page
    • HaruPage::setGrayFill - Set filling color for the page
    • HaruPage::setGrayStroke - Sets stroking color for the page
    • HaruPage::setHeight - Set height of the page
    • HaruPage::setHorizontalScaling - Set horizontal scaling for the page
    • HaruPage::setLineCap - Set the shape to be used at the ends of lines
    • HaruPage::setLineJoin - Set line join style for the page
    • HaruPage::setLineWidth - Set line width for the page
    • HaruPage::setMiterLimit - Set the current value of the miter limit of the page
    • HaruPage::setRGBFill - Set filling color for the page
    • HaruPage::setRGBStroke - Set stroking color for the page
    • HaruPage::setRotate - Set rotation angle of the page
    • HaruPage::setSize - Set size and direction of the page
    • HaruPage::setSlideShow - Set transition style for the page
    • HaruPage::setTextLeading - Set text leading (line spacing) for the page
    • HaruPage::setTextMatrix - Set the current text transformation matrix of the page
    • HaruPage::setTextRenderingMode - Set text rendering mode for the page
    • HaruPage::setTextRise - Set the current value of text rising
    • HaruPage::setWidth - Set width of the page
    • HaruPage::setWordSpace - Set word spacing for the page
    • HaruPage::showText - Print text at the current position of the page
    • HaruPage::showTextNextLine - Move the current position to the start of the next line and print the text
    • HaruPage::stroke - Paint current path
    • HaruPage::textOut - Print the text on the specified position
    • HaruPage::textRect - Print the text inside the specified region
    • hash - Generate a hash value (message digest)
    • hash_algos - Return a list of registered hashing algorithms
    • hash_copy - Copy hashing context
    • hash_file - Generate a hash value using the contents of a given file
    • hash_final - Finalize an incremental hash and return resulting digest
    • hash_hmac - Generate a keyed hash value using the HMAC method
    • hash_hmac_file - Generate a keyed hash value using the HMAC method and the contents of a given file
    • hash_init - Initialize an incremental hashing context
    • hash_update - Pump data into an active hashing context
    • hash_update_file - Pump data into an active hashing context from a file
    • hash_update_stream - Pump data into an active hashing context from an open stream
    • header - Send a raw HTTP header
    • headers_list - Returns a list of response headers sent (or ready to send)
    • headers_sent - Sprawdza czy zostały wysłane nagłówki i gdzie to nastąpiło
    • header_register_callback - Call a header function
    • header_remove - Remove previously set headers
    • hebrev - Convert logical Hebrew text to visual text
    • hebrevc - Convert logical Hebrew text to visual text with newline conversion
    • hex2bin - Convert hex to binary
    • hexdec - Konwersja liczby szesnastkowej do dziesiętnej
    • highlight_file - Syntax highlighting of a file
    • highlight_string - Syntax highlighting of a string
    • htmlentities - Convert all applicable characters to HTML entities
    • htmlspecialchars - Convert special characters to HTML entities
    • htmlspecialchars_decode - Convert special HTML entities back to characters
    • html_entity_decode - Convert all HTML entities to their applicable characters
    • http:// - Accessing HTTP(s) URLs
    • HTTP context options - HTTP context option listing
    • HttpDeflateStream::factory - HttpDeflateStream class factory
    • HttpDeflateStream::finish - Finalize deflate stream
    • HttpDeflateStream::flush - Flush deflate stream
    • HttpDeflateStream::update - Update deflate stream
    • HttpDeflateStream::__construct - HttpDeflateStream class constructor
    • HttpInflateStream::factory - HttpInflateStream class factory
    • HttpInflateStream::finish - Finalize inflate stream
    • HttpInflateStream::flush - Flush inflate stream
    • HttpInflateStream::update - Update inflate stream
    • HttpInflateStream::__construct - HttpInflateStream class constructor
    • HttpMessage::addHeaders - Add headers
    • HttpMessage::detach - Detach HttpMessage
    • HttpMessage::factory - Create HttpMessage from string
    • HttpMessage::fromEnv - Create HttpMessage from environment
    • HttpMessage::fromString - Create HttpMessage from string
    • HttpMessage::getBody - Get message body
    • HttpMessage::getHeader - Get header
    • HttpMessage::getHeaders - Get message headers
    • HttpMessage::getHttpVersion - Get HTTP version
    • HttpMessage::getParentMessage - Get parent message
    • HttpMessage::getRequestMethod - Get request method
    • HttpMessage::getRequestUrl - Get request URL
    • HttpMessage::getResponseCode - Get response code
    • HttpMessage::getResponseStatus - Get response status
    • HttpMessage::getType - Get message type
    • HttpMessage::guessContentType - Guess content type
    • HttpMessage::prepend - Prepend message(s)
    • HttpMessage::reverse - Reverse message chain
    • HttpMessage::send - Send message
    • HttpMessage::setBody - Set message body
    • HttpMessage::setHeaders - Set headers
    • HttpMessage::setHttpVersion - Set HTTP version
    • HttpMessage::setRequestMethod - Set request method
    • HttpMessage::setRequestUrl - Set request URL
    • HttpMessage::setResponseCode - Set response code
    • HttpMessage::setResponseStatus - Set response status
    • HttpMessage::setType - Set message type
    • HttpMessage::toMessageTypeObject - Create HTTP object regarding message type
    • HttpMessage::toString - Get string representation
    • HttpMessage::__construct - HttpMessage constructor
    • HttpQueryString::get - Get (part of) query string
    • HttpQueryString::mod - Modifiy query string copy
    • HttpQueryString::set - Set query string params
    • HttpQueryString::singleton - HttpQueryString singleton
    • HttpQueryString::toArray - Get query string as array
    • HttpQueryString::toString - Get query string
    • HttpQueryString::xlate - Change query strings charset
    • HttpQueryString::__construct - HttpQueryString constructor
    • HttpRequest::addCookies - Add cookies
    • HttpRequest::addHeaders - Add headers
    • HttpRequest::addPostFields - Add post fields
    • HttpRequest::addPostFile - Add post file
    • HttpRequest::addPutData - Add put data
    • HttpRequest::addQueryData - Add query data
    • HttpRequest::addRawPostData - Add raw post data
    • HttpRequest::addSslOptions - Add ssl options
    • HttpRequest::clearHistory - Clear history
    • HttpRequest::enableCookies - Enable cookies
    • HttpRequest::getContentType - Get content type
    • HttpRequest::getCookies - Get cookies
    • HttpRequest::getHeaders - Get headers
    • HttpRequest::getHistory - Get history
    • HttpRequest::getMethod - Get method
    • HttpRequest::getOptions - Get options
    • HttpRequest::getPostFields - Get post fields
    • HttpRequest::getPostFiles - Get post files
    • HttpRequest::getPutData - Get put data
    • HttpRequest::getPutFile - Get put file
    • HttpRequest::getQueryData - Get query data
    • HttpRequest::getRawPostData - Get raw post data
    • HttpRequest::getRawRequestMessage - Get raw request message
    • HttpRequest::getRawResponseMessage - Get raw response message
    • HttpRequest::getRequestMessage - Get request message
    • HttpRequest::getResponseBody - Get response body
    • HttpRequest::getResponseCode - Get response code
    • HttpRequest::getResponseCookies - Get response cookie(s)
    • HttpRequest::getResponseData - Get response data
    • HttpRequest::getResponseHeader - Get response header(s)
    • HttpRequest::getResponseInfo - Get response info
    • HttpRequest::getResponseMessage - Get response message
    • HttpRequest::getResponseStatus - Get response status
    • HttpRequest::getSslOptions - Get ssl options
    • HttpRequest::getUrl - Get url
    • HttpRequest::resetCookies - Reset cookies
    • HttpRequest::send - Send request
    • HttpRequest::setBody - Set request body to send, overwriting previously set request body.
    • HttpRequest::setContentType - Set content type
    • HttpRequest::setCookies - Set cookies
    • HttpRequest::setHeaders - Set headers
    • HttpRequest::setMethod - Set method
    • HttpRequest::setOptions - Set options
    • HttpRequest::setPostFields - Set post fields
    • HttpRequest::setPostFiles - Set post files
    • HttpRequest::setPutData - Set put data
    • HttpRequest::setPutFile - Set put file
    • HttpRequest::setQueryData - Set query data
    • HttpRequest::setRawPostData - Set raw post data
    • HttpRequest::setSslOptions - Set ssl options
    • HttpRequest::setUrl - Set URL
    • HttpRequest::__construct - HttpRequest constructor
    • HttpRequestPool::attach - Attach HttpRequest
    • HttpRequestPool::detach - Detach HttpRequest
    • HttpRequestPool::getAttachedRequests - Get attached requests
    • HttpRequestPool::getFinishedRequests - Get finished requests
    • HttpRequestPool::reset - Reset request pool
    • HttpRequestPool::send - Send all requests
    • HttpRequestPool::socketPerform - Perform socket actions
    • HttpRequestPool::socketSelect - Perform socket select
    • HttpRequestPool::__construct - HttpRequestPool constructor
    • HttpRequestPool::__destruct - HttpRequestPool destructor
    • HttpResponse::capture - Capture script output
    • HttpResponse::getBufferSize - Get buffer size
    • HttpResponse::getCache - Get cache
    • HttpResponse::getCacheControl - Get cache control
    • HttpResponse::getContentDisposition - Get content disposition
    • HttpResponse::getContentType - Get content type
    • HttpResponse::getData - Get data
    • HttpResponse::getETag - Get ETag
    • HttpResponse::getFile - Get file
    • HttpResponse::getGzip - Get gzip
    • HttpResponse::getHeader - Get header
    • HttpResponse::getLastModified - Get last modified
    • HttpResponse::getRequestBody - Get request body
    • HttpResponse::getRequestBodyStream - Get request body stream
    • HttpResponse::getRequestHeaders - Get request headers
    • HttpResponse::getStream - Get Stream
    • HttpResponse::getThrottleDelay - Get throttle delay
    • HttpResponse::guessContentType - Guess content type
    • HttpResponse::redirect - Redirect
    • HttpResponse::send - Send response
    • HttpResponse::setBufferSize - Set buffer size
    • HttpResponse::setCache - Set cache
    • HttpResponse::setCacheControl - Set cache control
    • HttpResponse::setContentDisposition - Set content disposition
    • HttpResponse::setContentType - Set content type
    • HttpResponse::setData - Set data
    • HttpResponse::setETag - Set ETag
    • HttpResponse::setFile - Set file
    • HttpResponse::setGzip - Set gzip
    • HttpResponse::setHeader - Set header
    • HttpResponse::setLastModified - Set last modified
    • HttpResponse::setStream - Set stream
    • HttpResponse::setThrottleDelay - Set throttle delay
    • HttpResponse::status - Send HTTP response status
    • http_build_cookie - Build cookie string
    • http_build_query - Generate URL-encoded query string
    • http_build_str - Build query string
    • http_build_url - Build a URL
    • http_cache_etag - Caching by ETag
    • http_cache_last_modified - Caching by last modification
    • http_chunked_decode - Decode chunked-encoded data
    • http_date - Compose HTTP RFC compliant date
    • http_deflate - Deflate data
    • http_get - Perform GET request
    • http_get_request_body - Get request body as string
    • http_get_request_body_stream - Get request body as stream
    • http_get_request_headers - Get request headers as array
    • http_head - Perform HEAD request
    • http_inflate - Inflate data
    • http_match_etag - Match ETag
    • http_match_modified - Match last modification
    • http_match_request_header - Match any header
    • http_negotiate_charset - Negotiate clients preferred character set
    • http_negotiate_content_type - Negotiate clients preferred content type
    • http_negotiate_language - Negotiate clients preferred language
    • http_parse_cookie - Parse HTTP cookie
    • http_parse_headers - Parse HTTP headers
    • http_parse_message - Parse HTTP messages
    • http_parse_params - Parse parameter list
    • http_persistent_handles_clean - Clean up persistent handles
    • http_persistent_handles_count - Stat persistent handles
    • http_persistent_handles_ident - Get/set ident of persistent handles
    • http_post_data - Perform POST request with pre-encoded data
    • http_post_fields - Perform POST request with data to be encoded
    • http_put_data - Perform PUT request with data
    • http_put_file - Perform PUT request with file
    • http_put_stream - Perform PUT request with stream
    • http_redirect - Issue HTTP redirect
    • http_request - Perform custom request
    • http_request_body_encode - Encode request body
    • http_request_method_exists - Check whether request method exists
    • http_request_method_name - Get request method name
    • http_request_method_register - Register request method
    • http_request_method_unregister - Unregister request method
    • http_response_code - Get or Set the HTTP response code
    • http_send_content_disposition - Send Content-Disposition
    • http_send_content_type - Send Content-Type
    • http_send_data - Send arbitrary data
    • http_send_file - Send file
    • http_send_last_modified - Send Last-Modified
    • http_send_status - Send HTTP response status
    • http_send_stream - Send stream
    • http_support - Check built-in HTTP support
    • http_throttle - HTTP throttling
    • hwapi_attribute_new - Creates instance of class hw_api_attribute
    • hwapi_content_new - Create new instance of class hw_api_content
    • hwapi_hgcsp - Returns object of class hw_api
    • hwapi_object_new - Creates a new instance of class hwapi_object_new
    • hw_api::checkin - Checks in an object
    • hw_api::checkout - Checks out an object
    • hw_api::children - Returns children of an object
    • hw_api::content - Returns content of an object
    • hw_api::copy - Copies physically
    • hw_api::dbstat - Returns statistics about database server
    • hw_api::dcstat - Returns statistics about document cache server
    • hw_api::dstanchors - Returns a list of all destination anchors
    • hw_api::dstofsrcanchor - Returns destination of a source anchor
    • hw_api::find - Search for objects
    • hw_api::ftstat - Returns statistics about fulltext server
    • hw_api::hwstat - Returns statistics about Hyperwave server
    • hw_api::identify - Log into Hyperwave Server
    • hw_api::info - Returns information about server configuration
    • hw_api::insert - Inserts a new object
    • hw_api::insertanchor - Inserts a new object of type anchor
    • hw_api::insertcollection - Inserts a new object of type collection
    • hw_api::insertdocument - Inserts a new object of type document
    • hw_api::link - Creates a link to an object
    • hw_api::lock - Locks an object
    • hw_api::move - Moves object between collections
    • hw_api::object - Retrieve attribute information
    • hw_api::objectbyanchor - Returns the object an anchor belongs to
    • hw_api::parents - Returns parents of an object
    • hw_api::remove - Delete an object
    • hw_api::replace - Replaces an object
    • hw_api::setcommittedversion - Commits version other than last version
    • hw_api::srcanchors - Returns a list of all source anchors
    • hw_api::srcsofdst - Returns source of a destination object
    • hw_api::unlock - Unlocks a locked object
    • hw_api::user - Returns the own user object
    • hw_api::userlist - Returns a list of all logged in users
    • hw_api_attribute::key - Returns key of the attribute
    • hw_api_attribute::langdepvalue - Returns value for a given language
    • hw_api_attribute::value - Returns value of the attribute
    • hw_api_attribute::values - Returns all values of the attribute
    • hw_api_content::mimetype - Returns mimetype
    • hw_api_content::read - Read content
    • hw_api_error::count - Returns number of reasons
    • hw_api_error::reason - Returns reason of error
    • hw_api_object::assign - Clones object
    • hw_api_object::attreditable - Checks whether an attribute is editable
    • hw_api_object::count - Returns number of attributes
    • hw_api_object::insert - Inserts new attribute
    • hw_api_object::remove - Removes attribute
    • hw_api_object::title - Returns the title attribute
    • hw_api_object::value - Returns value of attribute
    • hw_api_reason::description - Returns description of reason
    • hw_api_reason::type - Returns type of reason
    • hw_Array2Objrec - Convert attributes from object array to object record
    • hw_changeobject - Changes attributes of an object (obsolete)
    • hw_Children - Object ids of children
    • hw_ChildrenObj - Object records of children
    • hw_Close - Closes the Hyperwave connection
    • hw_Connect - Opens a connection
    • hw_connection_info - Prints information about the connection to Hyperwave server
    • hw_cp - Copies objects
    • hw_Deleteobject - Deletes object
    • hw_DocByAnchor - Object id object belonging to anchor
    • hw_DocByAnchorObj - Object record object belonging to anchor
    • hw_Document_Attributes - Object record of hw_document
    • hw_Document_BodyTag - Body tag of hw_document
    • hw_Document_Content - Returns content of hw_document
    • hw_Document_SetContent - Sets/replaces content of hw_document
    • hw_Document_Size - Size of hw_document
    • hw_dummy - Hyperwave dummy function
    • hw_EditText - Retrieve text document
    • hw_Error - Error number
    • hw_ErrorMsg - Returns error message
    • hw_Free_Document - Frees hw_document
    • hw_GetAnchors - Object ids of anchors of document
    • hw_GetAnchorsObj - Object records of anchors of document
    • hw_GetAndLock - Return object record and lock object
    • hw_GetChildColl - Object ids of child collections
    • hw_GetChildCollObj - Object records of child collections
    • hw_GetChildDocColl - Object ids of child documents of collection
    • hw_GetChildDocCollObj - Object records of child documents of collection
    • hw_GetObject - Object record
    • hw_GetObjectByQuery - Search object
    • hw_GetObjectByQueryColl - Search object in collection
    • hw_GetObjectByQueryCollObj - Search object in collection
    • hw_GetObjectByQueryObj - Search object
    • hw_GetParents - Object ids of parents
    • hw_GetParentsObj - Object records of parents
    • hw_getrellink - Get link from source to dest relative to rootid
    • hw_GetRemote - Gets a remote document
    • hw_getremotechildren - Gets children of remote document
    • hw_GetSrcByDestObj - Returns anchors pointing at object
    • hw_GetText - Retrieve text document
    • hw_getusername - Name of currently logged in user
    • hw_Identify - Identifies as user
    • hw_InCollections - Check if object ids in collections
    • hw_Info - Info about connection
    • hw_InsColl - Insert collection
    • hw_InsDoc - Insert document
    • hw_insertanchors - Inserts only anchors into text
    • hw_InsertDocument - Upload any document
    • hw_InsertObject - Inserts an object record
    • hw_mapid - Maps global id on virtual local id
    • hw_Modifyobject - Modifies object record
    • hw_mv - Moves objects
    • hw_New_Document - Create new document
    • hw_objrec2array - Convert attributes from object record to object array
    • hw_Output_Document - Prints hw_document
    • hw_pConnect - Make a persistent database connection
    • hw_PipeDocument - Retrieve any document
    • hw_Root - Root object id
    • hw_setlinkroot - Set the id to which links are calculated
    • hw_stat - Returns status string
    • hw_Unlock - Unlock object
    • hw_Who - List of currently logged in users
    • hypot - Oblicza długość przeciwprostokątnej trójkąta prostokątnego
  • i
    • ibase_add_user - Dodaje użytkownika do bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)
    • ibase_affected_rows - Zwraca ilość wierszy przetworzonych przez ostatnie zapytanie
    • ibase_backup - Uruchamia zadanie wykonania kopii zapasowej w Menedżerze Usługi i natychmiast powraca
    • ibase_blob_add - Dodaje dane do nowo utworzonego BLOBa
    • ibase_blob_cancel - Odwołuje tworzenie BLOBa
    • ibase_blob_close - Zamyka BLOBa
    • ibase_blob_create - Tworzy nowego BLOBa w celu umieszczenia w nim danych
    • ibase_blob_echo - Wysyła zawartość BLOBa do przeglądarki
    • ibase_blob_get - Pobiera X bajtów danych z otwartego BLOBa
    • ibase_blob_import - Tworzy BLOBa, kopiuje do niego zawartość pliku i zamyka go.
    • ibase_blob_info - Zwraca długość i inne informacje dotyczące BLOBa
    • ibase_blob_open - Otwiera BLOBa w celu pobrania części danych
    • ibase_close - Zamyka połączenie z serwerem Firebird/InterBase
    • ibase_commit - Zatwierdza transakcję
    • ibase_commit_ret - Potwierdza transakcję bez zamykania jej
    • ibase_connect - Otwiera połączenie do serwera Firebird/InterBase
    • ibase_db_info - Pobiera szczegółowe informacje o bazie danych
    • ibase_delete_user - Usuwa użytkownika z bazy danych bezpieczeństwa (tylko dla IB6 i późniejszych)
    • ibase_drop_db - Usuwa bazę danych Firebird/InterBase
    • ibase_errcode - Zwraca kod błędu
    • ibase_errmsg - Zwraca tekst komunikatu błędu
    • ibase_execute - Wykonuje wcześniej przygotowane zapytanie
    • ibase_fetch_assoc - Pobiera wiersz wyniku zapytania w postaci tablicy asocjacyjnej
    • ibase_fetch_object - Pobiera wiersz wyniku zapytania w postaci obiektu
    • ibase_fetch_row - Pobiera wiersz wyniku zapytania w postaci tablicy numerycznej
    • ibase_field_info - Zwraca informację o polu
    • ibase_free_event_handler - Odwołuje funkcję zarejestrowaną do obsługiwania zdarzeń
    • ibase_free_query - Zwalnia pamięć zajmowaną przez przygotowane zapytanie
    • ibase_free_result - Zwalnia pamięć zajmowaną przez wynik
    • ibase_gen_id - Zwiększa generator i zwraca jego nową wartość
    • ibase_maintain_db - Uruchamia polecenie konserwacyjne na serwerze baz danych
    • ibase_modify_user - Modyfikuje użytkownika w bazie danych bezpieczeństwa (tylko dla IB6 i późniejszych)
    • ibase_name_result - Przypisuje nazwę do zbioru wynikowego
    • ibase_num_fields - Zwraca liczbę pól w zbiorze wynikowym
    • ibase_num_params - Zwraca liczbę parametrów w przygotowanym zapytaniu
    • ibase_param_info - Zwraca informację o parametrze w przygotowanym zapytaniu
    • ibase_pconnect - Otwiera stałe połączenie do serwera Firebird/InterBase
    • ibase_prepare - Przygotowuje zapytanie do późniejszego dowiązania parametrów w postaci zmiennych, i do wykonania
    • ibase_query - Wykonuje zapytanie w bazie danych Firebird/Interbase
    • ibase_restore - Uruchamia zadanie przywrócenia bazy danych z kopii zapasowej w Menedżerze Usługi i natychmiast powraca
    • ibase_rollback - Wycofuje transakcję
    • ibase_rollback_ret - Wycofuje transakcję bez zamykania jej
    • ibase_server_info - Pobiera informacje o serwerze baz danych
    • ibase_service_attach - Łączy się do Menedżera Usługi
    • ibase_service_detach - Odłącza się od Menedżera Usługi
    • ibase_set_event_handler - Rejestruje funkcję zwrotną, wywoływaną podczas występowania zadarzeń
    • ibase_timefmt - Ustawia format znacznika czasu, daty i czasu w typach kolum zwracanych przez zapytania
    • ibase_trans - Rozpoczyna transakcję
    • ibase_wait_event - Czeka na zdarzenie, które zostanie przesłane przez serwer
    • iconv - Konwertuje łańcuch znaków do innego zestawu znaków
    • iconv_get_encoding - Pobiera aktualne ustawienia dla konwersji zestawu znaków
    • iconv_mime_decode - Decodes a MIME header field
    • iconv_mime_decode_headers - Decodes multiple MIME header fields at once
    • iconv_mime_encode - Composes a MIME header field
    • iconv_set_encoding - Ustawia aktualne ustawienia dla konwersji zestawu znaków
    • iconv_strlen - Returns the character count of string
    • iconv_strpos - Finds position of first occurrence of a needle within a haystack
    • iconv_strrpos - Finds the last occurrence of a needle within a haystack
    • iconv_substr - Cut out part of a string
    • id3_get_frame_long_name - Get the long name of an ID3v2 frame
    • id3_get_frame_short_name - Get the short name of an ID3v2 frame
    • id3_get_genre_id - Get the id for a genre
    • id3_get_genre_list - Get all possible genre values
    • id3_get_genre_name - Get the name for a genre id
    • id3_get_tag - Get all information stored in an ID3 tag
    • id3_get_version - Get version of an ID3 tag
    • id3_remove_tag - Remove an existing ID3 tag
    • id3_set_tag - Update information stored in an ID3 tag
    • idate - Format a local time/date as integer
    • idn_to_ascii - Convert domain name to IDNA ASCII form.
    • idn_to_unicode - Alias dla idn_to_utf8
    • idn_to_utf8 - Convert domain name from IDNA ASCII to Unicode.
    • ifxus_close_slob - Deletes the slob object
    • ifxus_create_slob - Creates an slob object and opens it
    • ifxus_free_slob - Deletes the slob object
    • ifxus_open_slob - Opens an slob object
    • ifxus_read_slob - Reads nbytes of the slob object
    • ifxus_seek_slob - Sets the current file or seek position
    • ifxus_tell_slob - Returns the current file or seek position
    • ifxus_write_slob - Writes a string into the slob object
    • ifx_affected_rows - Get number of rows affected by a query
    • ifx_blobinfile_mode - Set the default blob mode for all select queries
    • ifx_byteasvarchar - Set the default byte mode
    • ifx_close - Close Informix connection
    • ifx_connect - Open Informix server connection
    • ifx_copy_blob - Duplicates the given blob object
    • ifx_create_blob - Creates an blob object
    • ifx_create_char - Creates an char object
    • ifx_do - Execute a previously prepared SQL-statement
    • ifx_error - Returns error code of last Informix call
    • ifx_errormsg - Returns error message of last Informix call
    • ifx_fetch_row - Get row as an associative array
    • ifx_fieldproperties - List of SQL fieldproperties
    • ifx_fieldtypes - List of Informix SQL fields
    • ifx_free_blob - Deletes the blob object
    • ifx_free_char - Deletes the char object
    • ifx_free_result - Releases resources for the query
    • ifx_getsqlca - Get the contents of sqlca.sqlerrd[0..5] after a query
    • ifx_get_blob - Return the content of a blob object
    • ifx_get_char - Return the content of the char object
    • ifx_htmltbl_result - Formats all rows of a query into a HTML table
    • ifx_nullformat - Sets the default return value on a fetch row
    • ifx_num_fields - Returns the number of columns in the query
    • ifx_num_rows - Count the rows already fetched from a query
    • ifx_pconnect - Open persistent Informix connection
    • ifx_prepare - Prepare an SQL-statement for execution
    • ifx_query - Send Informix query
    • ifx_textasvarchar - Set the default text mode
    • ifx_update_blob - Updates the content of the blob object
    • ifx_update_char - Updates the content of the char object
    • ignore_user_abort - Set whether a client disconnect should abort script execution
    • iis_add_server - Creates a new virtual web server
    • iis_get_dir_security - Gets Directory Security
    • iis_get_script_map - Gets script mapping on a virtual directory for a specific extension
    • iis_get_server_by_comment - Return the instance number associated with the Comment
    • iis_get_server_by_path - Return the instance number associated with the Path
    • iis_get_server_rights - Gets server rights
    • iis_get_service_state - Returns the state for the service defined by ServiceId
    • iis_remove_server - Removes the virtual web server indicated by ServerInstance
    • iis_set_app_settings - Creates application scope for a virtual directory
    • iis_set_dir_security - Sets Directory Security
    • iis_set_script_map - Sets script mapping on a virtual directory
    • iis_set_server_rights - Sets server rights
    • iis_start_server - Starts the virtual web server
    • iis_start_service - Starts the service defined by ServiceId
    • iis_stop_server - Stops the virtual web server
    • iis_stop_service - Stops the service defined by ServiceId
    • image2wbmp - Wysłanie obrazu do przeglądarki lub zapis do pliku
    • imagealphablending - Set the blending mode for an image
    • imageantialias - Should antialias functions be used or not
    • imagearc - Draws an arc
    • imagechar - Draw a character horizontally
    • imagecharup - Draw a character vertically
    • imagecolorallocate - Allocate a color for an image
    • imagecolorallocatealpha - Allocate a color for an image
    • imagecolorat - Get the index of the color of a pixel
    • imagecolorclosest - Get the index of the closest color to the specified color
    • imagecolorclosestalpha - Get the index of the closest color to the specified color + alpha
    • imagecolorclosesthwb - Get the index of the color which has the hue, white and blackness
    • imagecolordeallocate - De-allocate a color for an image
    • imagecolorexact - Get the index of the specified color
    • imagecolorexactalpha - Get the index of the specified color + alpha
    • imagecolormatch - Makes the colors of the palette version of an image more closely match the true color version
    • imagecolorresolve - Get the index of the specified color or its closest possible alternative
    • imagecolorresolvealpha - Get the index of the specified color + alpha or its closest possible alternative
    • imagecolorset - Set the color for the specified palette index
    • imagecolorsforindex - Get the colors for an index
    • imagecolorstotal - Find out the number of colors in an image's palette
    • imagecolortransparent - Define a color as transparent
    • imageconvolution - Apply a 3x3 convolution matrix, using coefficient and offset
    • imagecopy - Copy part of an image
    • imagecopymerge - Copy and merge part of an image
    • imagecopymergegray - Copy and merge part of an image with gray scale
    • imagecopyresampled - Copy and resize part of an image with resampling
    • imagecopyresized - Copy and resize part of an image
    • imagecreate - Create a new palette based image
    • imagecreatefromgd - Create a new image from GD file or URL
    • imagecreatefromgd2 - Create a new image from GD2 file or URL
    • imagecreatefromgd2part - Create a new image from a given part of GD2 file or URL
    • imagecreatefromgif - Tworzy nowy obraz z pliku lub URL
    • imagecreatefromjpeg - Tworzy nowy obraz z pliku lub URL
    • imagecreatefrompng - Tworzy nowy obraz z pliku lub URL
    • imagecreatefromstring - Create a new image from the image stream in the string
    • imagecreatefromwbmp - Tworzy nowy obraz z pliku lub URL
    • imagecreatefromxbm - Tworzy nowy obraz z pliku lub URL
    • imagecreatefromxpm - Tworzy nowy obraz z pliku lub URL
    • imagecreatetruecolor - Create a new true color image
    • imagedashedline - Draw a dashed line
    • imagedestroy - Destroy an image
    • imageellipse - Draw an ellipse
    • imagefill - Flood fill
    • imagefilledarc - Draw a partial arc and fill it
    • imagefilledellipse - Draw a filled ellipse
    • imagefilledpolygon - Draw a filled polygon
    • imagefilledrectangle - Draw a filled rectangle
    • imagefilltoborder - Flood fill to specific color
    • imagefilter - Applies a filter to an image
    • imagefontheight - Get font height
    • imagefontwidth - Get font width
    • imageftbbox - Give the bounding box of a text using fonts via freetype2
    • imagefttext - Write text to the image using fonts using FreeType 2
    • imagegammacorrect - Apply a gamma correction to a GD image
    • imagegd - Output GD image to browser or file
    • imagegd2 - Output GD2 image to browser or file
    • imagegif - Wysłanie obrazu do przeglądarki lub zapis do pliku
    • imagegrabscreen - Captures the whole screen
    • imagegrabwindow - Captures a window
    • imageinterlace - Enable or disable interlace
    • imageistruecolor - Finds whether an image is a truecolor image
    • imagejpeg - Wysłanie obrazu do przeglądarki lub zapis do pliku
    • imagelayereffect - Set the alpha blending flag to use the bundled libgd layering effects
    • imageline - Draw a line
    • imageloadfont - Load a new font
    • imagepalettecopy - Copy the palette from one image to another
    • imagepng - Output a PNG image to either the browser or a file
    • imagepolygon - Draws a polygon
    • imagepsbbox - Give the bounding box of a text rectangle using PostScript Type1 fonts
    • imagepsencodefont - Change the character encoding vector of a font
    • imagepsextendfont - Extend or condense a font
    • imagepsfreefont - Free memory used by a PostScript Type 1 font
    • imagepsloadfont - Load a PostScript Type 1 font from file
    • imagepsslantfont - Slant a font
    • imagepstext - Draws a text over an image using PostScript Type1 fonts
    • imagerectangle - Draw a rectangle
    • imagerotate - Rotate an image with a given angle
    • imagesavealpha - Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
    • imagesetbrush - Set the brush image for line drawing
    • imagesetpixel - Set a single pixel
    • imagesetstyle - Set the style for line drawing
    • imagesetthickness - Set the thickness for line drawing
    • imagesettile - Set the tile image for filling
    • imagestring - Draw a string horizontally
    • imagestringup - Draw a string vertically
    • imagesx - Get image width
    • imagesy - Get image height
    • imagetruecolortopalette - Convert a true color image to a palette image
    • imagettfbbox - Give the bounding box of a text using TrueType fonts
    • imagettftext - Write text to the image using TrueType fonts
    • imagetypes - Return the image types supported by this PHP build
    • imagewbmp - Wysłanie obrazu do przeglądarki lub zapis do pliku
    • imagexbm - Output XBM image to browser or file
    • image_type_to_extension - Get file extension for image type
    • image_type_to_mime_type - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
    • Imagick::adaptiveBlurImage - Adds adaptive blur filter to image
    • Imagick::adaptiveResizeImage - Adaptively resize image with data dependent triangulation
    • Imagick::adaptiveSharpenImage - Adaptively sharpen the image
    • Imagick::adaptiveThresholdImage - Selects a threshold for each pixel based on a range of intensity
    • Imagick::addImage - Adds new image to Imagick object image list
    • Imagick::addNoiseImage - Adds random noise to the image
    • Imagick::affineTransformImage - Transforms an image
    • Imagick::animateImages - Animates an image or images
    • Imagick::annotateImage - Annotates an image with text
    • Imagick::appendImages - Append a set of images
    • Imagick::averageImages - Average a set of images
    • Imagick::blackThresholdImage - Forces all pixels below the threshold into black
    • Imagick::blurImage - Adds blur filter to image
    • Imagick::borderImage - Surrounds the image with a border
    • Imagick::charcoalImage - Simulates a charcoal drawing
    • Imagick::chopImage - Removes a region of an image and trims
    • Imagick::clear - Clears all resources associated to Imagick object
    • Imagick::clipImage - Clips along the first path from the 8BIM profile
    • Imagick::clipPathImage - Clips along the named paths from the 8BIM profile
    • Imagick::clone - Makes an exact copy of the Imagick object
    • Imagick::clutImage - Replaces colors in the image
    • Imagick::coalesceImages - Composites a set of images
    • Imagick::colorFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::colorizeImage - Blends the fill color with the image
    • Imagick::combineImages - Combines one or more images into a single image
    • Imagick::commentImage - Adds a comment to your image
    • Imagick::compareImageChannels - Returns the difference in one or more images
    • Imagick::compareImageLayers - Returns the maximum bounding region between images
    • Imagick::compareImages - Compares an image to a reconstructed image
    • Imagick::compositeImage - Composite one image onto another
    • Imagick::contrastImage - Change the contrast of the image
    • Imagick::contrastStretchImage - Enhances the contrast of a color image
    • Imagick::convolveImage - Applies a custom convolution kernel to the image
    • Imagick::cropImage - Extracts a region of the image
    • Imagick::cropThumbnailImage - Creates a crop thumbnail
    • Imagick::current - Returns a reference to the current Imagick object
    • Imagick::cycleColormapImage - Displaces an image's colormap
    • Imagick::decipherImage - Deciphers an image
    • Imagick::deconstructImages - Returns certain pixel differences between images
    • Imagick::deleteImageArtifact - Delete image artifact
    • Imagick::deskewImage - Removes skew from the image
    • Imagick::despeckleImage - Reduces the speckle noise in an image
    • Imagick::destroy - Destroys the Imagick object
    • Imagick::displayImage - Displays an image
    • Imagick::displayImages - Displays an image or image sequence
    • Imagick::distortImage - Distorts an image using various distortion methods
    • Imagick::drawImage - Renders the ImagickDraw object on the current image
    • Imagick::edgeImage - Enhance edges within the image
    • Imagick::embossImage - Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage - Enciphers an image
    • Imagick::enhanceImage - Improves the quality of a noisy image
    • Imagick::equalizeImage - Equalizes the image histogram
    • Imagick::evaluateImage - Applies an expression to an image
    • Imagick::exportImagePixels - Exports raw image pixels
    • Imagick::extentImage - Set image size
    • Imagick::flattenImages - Merges a sequence of images
    • Imagick::flipImage - Creates a vertical mirror image
    • Imagick::floodFillPaintImage - Changes the color value of any pixel that matches target
    • Imagick::flopImage - Creates a horizontal mirror image
    • Imagick::frameImage - Adds a simulated three-dimensional border
    • Imagick::functionImage - Applies a function on the image
    • Imagick::fxImage - Evaluate expression for each pixel in the image
    • Imagick::gammaImage - Gamma-corrects an image
    • Imagick::gaussianBlurImage - Blurs an image
    • Imagick::getColorspace - Gets the colorspace
    • Imagick::getCompression - Gets the object compression type
    • Imagick::getCompressionQuality - Gets the object compression quality
    • Imagick::getCopyright - Returns the ImageMagick API copyright as a string
    • Imagick::getFilename - The filename associated with an image sequence
    • Imagick::getFont - Gets font
    • Imagick::getFormat - Returns the format of the Imagick object
    • Imagick::getGravity - Gets the gravity
    • Imagick::getHomeURL - Returns the ImageMagick home URL
    • Imagick::getImage - Returns a new Imagick object
    • Imagick::getImageAlphaChannel - Gets the image alpha channel
    • Imagick::getImageArtifact - Get image artifact
    • Imagick::getImageBackgroundColor - Returns the image background color
    • Imagick::getImageBlob - Returns the image sequence as a blob
    • Imagick::getImageBluePrimary - Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor - Returns the image border color
    • Imagick::getImageChannelDepth - Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion - Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions - Gets channel distortions
    • Imagick::getImageChannelExtrema - Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis - The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean - Gets the mean and standard deviation
    • Imagick::getImageChannelRange - Gets channel range
    • Imagick::getImageChannelStatistics - Returns statistics for each channel in the image
    • Imagick::getImageClipMask - Gets image clip mask
    • Imagick::getImageColormapColor - Returns the color of the specified colormap index
    • Imagick::getImageColors - Gets the number of unique colors in the image
    • Imagick::getImageColorspace - Gets the image colorspace
    • Imagick::getImageCompose - Returns the composite operator associated with the image
    • Imagick::getImageCompression - Gets the current image's compression type
    • Imagick::getImageCompressionQuality - Gets the current image's compression quality
    • Imagick::getImageDelay - Gets the image delay
    • Imagick::getImageDepth - Gets the image depth
    • Imagick::getImageDispose - Gets the image disposal method
    • Imagick::getImageDistortion - Compares an image to a reconstructed image
    • Imagick::getImageExtrema - Gets the extrema for the image
    • Imagick::getImageFilename - Returns the filename of a particular image in a sequence
    • Imagick::getImageFormat - Returns the format of a particular image in a sequence
    • Imagick::getImageGamma - Gets the image gamma
    • Imagick::getImageGeometry - Gets the width and height as an associative array
    • Imagick::getImageGravity - Gets the image gravity
    • Imagick::getImageGreenPrimary - Returns the chromaticy green primary point
    • Imagick::getImageHeight - Returns the image height
    • Imagick::getImageHistogram - Gets the image histogram
    • Imagick::getImageIndex - Gets the index of the current active image
    • Imagick::getImageInterlaceScheme - Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod - Returns the interpolation method
    • Imagick::getImageIterations - Gets the image iterations
    • Imagick::getImageLength - Returns the image length in bytes
    • Imagick::getImageMagickLicense - Returns a string containing the ImageMagick license
    • Imagick::getImageMatte - Return if the image has a matte channel
    • Imagick::getImageMatteColor - Returns the image matte color
    • Imagick::getImageOrientation - Gets the image orientation
    • Imagick::getImagePage - Returns the page geometry
    • Imagick::getImagePixelColor - Returns the color of the specified pixel
    • Imagick::getImageProfile - Returns the named image profile
    • Imagick::getImageProfiles - Returns the image profiles
    • Imagick::getImageProperties - Returns the image properties
    • Imagick::getImageProperty - Returns the named image property
    • Imagick::getImageRedPrimary - Returns the chromaticity red primary point
    • Imagick::getImageRegion - Extracts a region of the image
    • Imagick::getImageRenderingIntent - Gets the image rendering intent
    • Imagick::getImageResolution - Gets the image X and Y resolution
    • Imagick::getImagesBlob - Returns all image sequences as a blob
    • Imagick::getImageScene - Gets the image scene
    • Imagick::getImageSignature - Generates an SHA-256 message digest
    • Imagick::getImageSize - Returns the image length in bytes
    • Imagick::getImageTicksPerSecond - Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity - Gets the image total ink density
    • Imagick::getImageType - Gets the potential image type
    • Imagick::getImageUnits - Gets the image units of resolution
    • Imagick::getImageVirtualPixelMethod - Returns the virtual pixel method
    • Imagick::getImageWhitePoint - Returns the chromaticity white point
    • Imagick::getImageWidth - Returns the image width
    • Imagick::getInterlaceScheme - Gets the object interlace scheme
    • Imagick::getIteratorIndex - Gets the index of the current active image
    • Imagick::getNumberImages - Returns the number of images in the object
    • Imagick::getOption - Returns a value associated with the specified key
    • Imagick::getPackageName - Returns the ImageMagick package name
    • Imagick::getPage - Returns the page geometry
    • Imagick::getPixelIterator - Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator - Get an ImagickPixelIterator for an image section
    • Imagick::getPointSize - Gets point size
    • Imagick::getQuantumDepth - Gets the quantum depth
    • Imagick::getQuantumRange - Returns the Imagick quantum range
    • Imagick::getReleaseDate - Returns the ImageMagick release date
    • Imagick::getResource - Returns the specified resource's memory usage
    • Imagick::getResourceLimit - Returns the specified resource limit
    • Imagick::getSamplingFactors - Gets the horizontal and vertical sampling factor
    • Imagick::getSize - Returns the size associated with the Imagick object
    • Imagick::getSizeOffset - Returns the size offset
    • Imagick::getVersion - Returns the ImageMagick API version
    • Imagick::haldClutImage - Replaces colors in the image
    • Imagick::hasNextImage - Checks if the object has more images
    • Imagick::hasPreviousImage - Checks if the object has a previous image
    • Imagick::identifyImage - Identifies an image and fetches attributes
    • Imagick::implodeImage - Creates a new image as a copy
    • Imagick::importImagePixels - Imports image pixels
    • Imagick::labelImage - Adds a label to an image
    • Imagick::levelImage - Adjusts the levels of an image
    • Imagick::linearStretchImage - Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage - Animates an image or images
    • Imagick::magnifyImage - Scales an image proportionally 2x
    • Imagick::mapImage - Replaces the colors of an image with the closest color from a reference image.
    • Imagick::matteFloodfillImage - Changes the transparency value of a color
    • Imagick::medianFilterImage - Applies a digital filter
    • Imagick::mergeImageLayers - Merges image layers
    • Imagick::minifyImage - Scales an image proportionally to half its size
    • Imagick::modulateImage - Control the brightness, saturation, and hue
    • Imagick::montageImage - Creates a composite image
    • Imagick::morphImages - Method morphs a set of images
    • Imagick::mosaicImages - Forms a mosaic from images
    • Imagick::motionBlurImage - Simulates motion blur
    • Imagick::negateImage - Negates the colors in the reference image
    • Imagick::newImage - Creates a new image
    • Imagick::newPseudoImage - Creates a new image
    • Imagick::nextImage - Moves to the next image
    • Imagick::normalizeImage - Enhances the contrast of a color image
    • Imagick::oilPaintImage - Simulates an oil painting
    • Imagick::opaquePaintImage - Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers - Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage - Performs an ordered dither
    • Imagick::paintFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage - Change any pixel that matches color
    • Imagick::paintTransparentImage - Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage - Fetch basic attributes about the image
    • Imagick::pingImageBlob - Quickly fetch attributes
    • Imagick::pingImageFile - Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage - Simulates a Polaroid picture
    • Imagick::posterizeImage - Reduces the image to a limited number of color level
    • Imagick::previewImages - Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage - Move to the previous image in the object
    • Imagick::profileImage - Adds or removes a profile from an image
    • Imagick::quantizeImage - Analyzes the colors within a reference image
    • Imagick::quantizeImages - Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics - Returns an array representing the font metrics
    • Imagick::queryFonts - Returns the configured fonts
    • Imagick::queryFormats - Returns formats supported by Imagick
    • Imagick::radialBlurImage - Radial blurs an image
    • Imagick::raiseImage - Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage - Creates a high-contrast, two-color image
    • Imagick::readImage - Reads image from filename
    • Imagick::readImageBlob - Reads image from a binary string
    • Imagick::readImageFile - Reads image from open filehandle
    • Imagick::recolorImage - Recolors image
    • Imagick::reduceNoiseImage - Smooths the contours of an image
    • Imagick::remapImage - Remaps image colors
    • Imagick::removeImage - Removes an image from the image list
    • Imagick::removeImageProfile - Removes the named image profile and returns it
    • Imagick::render - Renders all preceding drawing commands
    • Imagick::resampleImage - Resample image to desired resolution
    • Imagick::resetImagePage - Reset image page
    • Imagick::resizeImage - Scales an image
    • Imagick::rollImage - Offsets an image
    • Imagick::rotateImage - Rotates an image
    • Imagick::roundCorners - Rounds image corners
    • Imagick::sampleImage - Scales an image with pixel sampling
    • Imagick::scaleImage - Scales the size of an image
    • Imagick::segmentImage - Segments an image
    • Imagick::separateImageChannel - Separates a channel from the image
    • Imagick::sepiaToneImage - Sepia tones an image
    • Imagick::setBackgroundColor - Sets the object's default background color
    • Imagick::setColorspace - Set colorspace
    • Imagick::setCompression - Sets the object's default compression type
    • Imagick::setCompressionQuality - Sets the object's default compression quality
    • Imagick::setFilename - Sets the filename before you read or write the image
    • Imagick::setFirstIterator - Sets the Imagick iterator to the first image
    • Imagick::setFont - Sets font
    • Imagick::setFormat - Sets the format of the Imagick object
    • Imagick::setGravity - Sets the gravity
    • Imagick::setImage - Replaces image in the object
    • Imagick::setImageAlphaChannel - Sets image alpha channel
    • Imagick::setImageArtifact - Set image artifact
    • Imagick::setImageBackgroundColor - Sets the image background color
    • Imagick::setImageBias - Sets the image bias for any method that convolves an image
    • Imagick::setImageBluePrimary - Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor - Sets the image border color
    • Imagick::setImageChannelDepth - Sets the depth of a particular image channel
    • Imagick::setImageClipMask - Sets image clip mask
    • Imagick::setImageColormapColor - Sets the color of the specified colormap index
    • Imagick::setImageColorspace - Sets the image colorspace
    • Imagick::setImageCompose - Sets the image composite operator
    • Imagick::setImageCompression - Sets the image compression
    • Imagick::setImageCompressionQuality - Sets the image compression quality
    • Imagick::setImageDelay - Sets the image delay
    • Imagick::setImageDepth - Sets the image depth
    • Imagick::setImageDispose - Sets the image disposal method
    • Imagick::setImageExtent - Sets the image size
    • Imagick::setImageFilename - Sets the filename of a particular image
    • Imagick::setImageFormat - Sets the format of a particular image
    • Imagick::setImageGamma - Sets the image gamma
    • Imagick::setImageGravity - Sets the image gravity
    • Imagick::setImageGreenPrimary - Sets the image chromaticity green primary point
    • Imagick::setImageIndex - Set the iterator position
    • Imagick::setImageInterlaceScheme - Sets the image compression
    • Imagick::setImageInterpolateMethod - Sets the image interpolate pixel method
    • Imagick::setImageIterations - Sets the image iterations
    • Imagick::setImageMatte - Sets the image matte channel
    • Imagick::setImageMatteColor - Sets the image matte color
    • Imagick::setImageOpacity - Sets the image opacity level
    • Imagick::setImageOrientation - Sets the image orientation
    • Imagick::setImagePage - Sets the page geometry of the image
    • Imagick::setImageProfile - Adds a named profile to the Imagick object
    • Imagick::setImageProperty - Sets an image property
    • Imagick::setImageRedPrimary - Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent - Sets the image rendering intent
    • Imagick::setImageResolution - Sets the image resolution
    • Imagick::setImageScene - Sets the image scene
    • Imagick::setImageTicksPerSecond - Sets the image ticks-per-second
    • Imagick::setImageType - Sets the image type
    • Imagick::setImageUnits - Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod - Sets the image virtual pixel method
    • Imagick::setImageWhitePoint - Sets the image chromaticity white point
    • Imagick::setInterlaceScheme - Sets the image compression
    • Imagick::setIteratorIndex - Set the iterator position
    • Imagick::setLastIterator - Sets the Imagick iterator to the last image
    • Imagick::setOption - Set an option
    • Imagick::setPage - Sets the page geometry of the Imagick object
    • Imagick::setPointSize - Sets point size
    • Imagick::setResolution - Sets the image resolution
    • Imagick::setResourceLimit - Sets the limit for a particular resource in megabytes
    • Imagick::setSamplingFactors - Sets the image sampling factors
    • Imagick::setSize - Sets the size of the Imagick object
    • Imagick::setSizeOffset - Sets the size and offset of the Imagick object
    • Imagick::setType - Sets the image type attribute
    • Imagick::shadeImage - Creates a 3D effect
    • Imagick::shadowImage - Simulates an image shadow
    • Imagick::sharpenImage - Sharpens an image
    • Imagick::shaveImage - Shaves pixels from the image edges
    • Imagick::shearImage - Creating a parallelogram
    • Imagick::sigmoidalContrastImage - Adjusts the contrast of an image
    • Imagick::sketchImage - Simulates a pencil sketch
    • Imagick::solarizeImage - Applies a solarizing effect to the image
    • Imagick::sparseColorImage - Interpolates colors
    • Imagick::spliceImage - Splices a solid color into the image
    • Imagick::spreadImage - Randomly displaces each pixel in a block
    • Imagick::steganoImage - Hides a digital watermark within the image
    • Imagick::stereoImage - Composites two images
    • Imagick::stripImage - Strips an image of all profiles and comments
    • Imagick::swirlImage - Swirls the pixels about the center of the image
    • Imagick::textureImage - Repeatedly tiles the texture image
    • Imagick::thresholdImage - Changes the value of individual pixels based on a threshold
    • Imagick::thumbnailImage - Changes the size of an image
    • Imagick::tintImage - Applies a color vector to each pixel in the image
    • Imagick::transformImage - Convenience method for setting crop size and the image geometry
    • Imagick::transparentPaintImage - Paints pixels transparent
    • Imagick::transposeImage - Creates a vertical mirror image
    • Imagick::transverseImage - Creates a horizontal mirror image
    • Imagick::trimImage - Remove edges from the image
    • Imagick::uniqueImageColors - Discards all but one of any pixel color
    • Imagick::unsharpMaskImage - Sharpens an image
    • Imagick::valid - Checks if the current item is valid
    • Imagick::vignetteImage - Adds vignette filter to the image
    • Imagick::waveImage - Applies wave filter to the image
    • Imagick::whiteThresholdImage - Force all pixels above the threshold into white
    • Imagick::writeImage - Writes an image to the specified filename
    • Imagick::writeImageFile - Writes an image to a filehandle
    • Imagick::writeImages - Writes an image or image sequence
    • Imagick::writeImagesFile - Writes frames to a filehandle
    • Imagick::__construct - The Imagick constructor
    • ImagickDraw::affine - Adjusts the current affine transformation matrix
    • ImagickDraw::annotation - Draws text on the image
    • ImagickDraw::arc - Draws an arc
    • ImagickDraw::bezier - Draws a bezier curve
    • ImagickDraw::circle - Draws a circle
    • ImagickDraw::clear - Clears the ImagickDraw
    • ImagickDraw::clone - Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color - Draws color on image
    • ImagickDraw::comment - Adds a comment
    • ImagickDraw::composite - Composites an image onto the current image
    • ImagickDraw::destroy - Frees all associated resources
    • ImagickDraw::ellipse - Draws an ellipse on the image
    • ImagickDraw::getClipPath - Obtains the current clipping path ID
    • ImagickDraw::getClipRule - Returns the current polygon fill rule
    • ImagickDraw::getClipUnits - Returns the interpretation of clip path units
    • ImagickDraw::getFillColor - Returns the fill color
    • ImagickDraw::getFillOpacity - Returns the opacity used when drawing
    • ImagickDraw::getFillRule - Returns the fill rule
    • ImagickDraw::getFont - Returns the font
    • ImagickDraw::getFontFamily - Returns the font family
    • ImagickDraw::getFontSize - Returns the font pointsize
    • ImagickDraw::getFontStyle - Returns the font style
    • ImagickDraw::getFontWeight - Returns the font weight
    • ImagickDraw::getGravity - Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias - Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor - Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray - Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset - Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap - Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin - Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit - Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity - Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth - Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment - Returns the text alignment
    • ImagickDraw::getTextAntialias - Returns the current text antialias setting
    • ImagickDraw::getTextDecoration - Returns the text decoration
    • ImagickDraw::getTextEncoding - Returns the code set used for text annotations
    • ImagickDraw::getTextUnderColor - Returns the text under color
    • ImagickDraw::getVectorGraphics - Returns a string containing vector graphics
    • ImagickDraw::line - Draws a line
    • ImagickDraw::matte - Paints on the image's opacity channel
    • ImagickDraw::pathClose - Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute - Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative - Draws an elliptical arc
    • ImagickDraw::pathFinish - Terminates the current path
    • ImagickDraw::pathLineToAbsolute - Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute - Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative - Draws a horizontal line
    • ImagickDraw::pathLineToRelative - Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute - Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative - Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute - Starts a new sub-path
    • ImagickDraw::pathMoveToRelative - Starts a new sub-path
    • ImagickDraw::pathStart - Declares the start of a path drawing list
    • ImagickDraw::point - Draws a point
    • ImagickDraw::polygon - Draws a polygon
    • ImagickDraw::polyline - Draws a polyline
    • ImagickDraw::pop - Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath - Terminates a clip path definition
    • ImagickDraw::popDefs - Terminates a definition list
    • ImagickDraw::popPattern - Terminates a pattern definition
    • ImagickDraw::push - Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath - Starts a clip path definition
    • ImagickDraw::pushDefs - Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern - Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle - Draws a rectangle
    • ImagickDraw::render - Renders all preceding drawing commands onto the image
    • ImagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle - Draws a rounded rectangle
    • ImagickDraw::scale - Adjusts the scaling factor
    • ImagickDraw::setClipPath - Associates a named clipping path with the image
    • ImagickDraw::setClipRule - Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits - Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor - Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL - Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule - Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont - Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily - Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize - Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch - Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle - Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight - Sets the font weight
    • ImagickDraw::setGravity - Sets the text placement gravity
    • ImagickDraw::setStrokeAlpha - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias - Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor - Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray - Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset - Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap - Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin - Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit - Specifies the miter limit
    • ImagickDraw::setStrokeOpacity - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL - Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth - Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment - Specifies a text alignment
    • ImagickDraw::setTextAntialias - Controls whether text is antialiased
    • ImagickDraw::setTextDecoration - Specifies a decoration
    • ImagickDraw::setTextEncoding - Specifies specifies the text code set
    • ImagickDraw::setTextUnderColor - Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics - Sets the vector graphics
    • ImagickDraw::setViewbox - Sets the overall canvas size
    • ImagickDraw::skewX - Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY - Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate - Applies a translation to the current coordinate system
    • ImagickDraw::__construct - The ImagickDraw constructor
    • ImagickPixel::clear - Clears resources associated with this object
    • ImagickPixel::destroy - Deallocates resources associated with this object
    • ImagickPixel::getColor - Returns the color
    • ImagickPixel::getColorAsString - Returns the color as a string
    • ImagickPixel::getColorCount - Returns the color count associated with this color
    • ImagickPixel::getColorValue - Gets the normalized value of the provided color channel
    • ImagickPixel::getHSL - Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::isSimilar - Check the distance between this color and another
    • ImagickPixel::setColor - Sets the color
    • ImagickPixel::setColorValue - Sets the normalized value of one of the channels
    • ImagickPixel::setHSL - Sets the normalized HSL color
    • ImagickPixel::__construct - The ImagickPixel constructor
    • ImagickPixelIterator::clear - Clear resources associated with a PixelIterator
    • ImagickPixelIterator::destroy - Deallocates resources associated with a PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow - Returns the current row of ImagickPixel objects
    • ImagickPixelIterator::getIteratorRow - Returns the current pixel iterator row
    • ImagickPixelIterator::getNextIteratorRow - Returns the next row of the pixel iterator
    • ImagickPixelIterator::getPreviousIteratorRow - Returns the previous row
    • ImagickPixelIterator::newPixelIterator - Returns a new pixel iterator
    • ImagickPixelIterator::newPixelRegionIterator - Returns a new pixel iterator
    • ImagickPixelIterator::resetIterator - Resets the pixel iterator
    • ImagickPixelIterator::setIteratorFirstRow - Sets the pixel iterator to the first pixel row
    • ImagickPixelIterator::setIteratorLastRow - Sets the pixel iterator to the last pixel row
    • ImagickPixelIterator::setIteratorRow - Set the pixel iterator row
    • ImagickPixelIterator::syncIterator - Syncs the pixel iterator
    • ImagickPixelIterator::__construct - The ImagickPixelIterator constructor
    • imap_8bit - Convert an 8bit string to a quoted-printable string
    • imap_alerts - Returns all IMAP alert messages that have occurred
    • imap_append - Append a string message to a specified mailbox
    • imap_base64 - Decode BASE64 encoded text
    • imap_binary - Convert an 8bit string to a base64 string
    • imap_body - Read the message body
    • imap_bodystruct - Read the structure of a specified body section of a specific message
    • imap_check - Check current mailbox
    • imap_clearflag_full - Clears flags on messages
    • imap_close - Close an IMAP stream
    • imap_create - Alias dla imap_createmailbox
    • imap_createmailbox - Create a new mailbox
    • imap_delete - Mark a message for deletion from current mailbox
    • imap_deletemailbox - Delete a mailbox
    • imap_errors - Returns all of the IMAP errors that have occured
    • imap_expunge - Delete all messages marked for deletion
    • imap_fetchbody - Fetch a particular section of the body of the message
    • imap_fetchheader - Returns header for a message
    • imap_fetchmime - Fetch MIME headers for a particular section of the message
    • imap_fetchstructure - Read the structure of a particular message
    • imap_fetchtext - Alias dla imap_body
    • imap_fetch_overview - Read an overview of the information in the headers of the given message
    • imap_gc - Clears IMAP cache
    • imap_getacl - Gets the ACL for a given mailbox
    • imap_getmailboxes - Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed - List all the subscribed mailboxes
    • imap_get_quota - Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot - Retrieve the quota settings per user
    • imap_header - Alias dla imap_headerinfo
    • imap_headerinfo - Read the header of the message
    • imap_headers - Returns headers for all messages in a mailbox
    • imap_last_error - Gets the last IMAP error that occurred during this page request
    • imap_list - Read the list of mailboxes
    • imap_listmailbox - Alias dla imap_list
    • imap_listscan - Returns the list of mailboxes that matches the given text
    • imap_listsubscribed - Alias dla imap_lsub
    • imap_lsub - List all the subscribed mailboxes
    • imap_mail - Send an email message
    • imap_mailboxmsginfo - Get information about the current mailbox
    • imap_mail_compose - Create a MIME message based on given envelope and body sections
    • imap_mail_copy - Copy specified messages to a mailbox
    • imap_mail_move - Move specified messages to a mailbox
    • imap_mime_header_decode - Decode MIME header elements
    • imap_msgno - Gets the message sequence number for the given UID
    • imap_num_msg - Gets the number of messages in the current mailbox
    • imap_num_recent - Gets the number of recent messages in current mailbox
    • imap_open - Open an IMAP stream to a mailbox
    • imap_ping - Check if the IMAP stream is still active
    • imap_qprint - Convert a quoted-printable string to an 8 bit string
    • imap_rename - Alias dla imap_renamemailbox
    • imap_renamemailbox - Rename an old mailbox to new mailbox
    • imap_reopen - Reopen IMAP stream to new mailbox
    • imap_rfc822_parse_adrlist - Parses an address string
    • imap_rfc822_parse_headers - Parse mail headers from a string
    • imap_rfc822_write_address - Returns a properly formatted email address given the mailbox, host, and personal info
    • imap_savebody - Save a specific body section to a file
    • imap_scan - Alias dla imap_listscan
    • imap_scanmailbox - Alias dla imap_listscan
    • imap_search - This function returns an array of messages matching the given search criteria
    • imap_setacl - Sets the ACL for a giving mailbox
    • imap_setflag_full - Sets flags on messages
    • imap_set_quota - Sets a quota for a given mailbox
    • imap_sort - Gets and sort messages
    • imap_status - Returns status information on a mailbox
    • imap_subscribe - Subscribe to a mailbox
    • imap_thread - Returns a tree of threaded message
    • imap_timeout - Set or fetch imap timeout
    • imap_uid - This function returns the UID for the given message sequence number
    • imap_undelete - Unmark the message which is marked deleted
    • imap_unsubscribe - Unsubscribe from a mailbox
    • imap_utf7_decode - Decodes a modified UTF-7 encoded string
    • imap_utf7_encode - Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 - Converts MIME-encoded text to UTF-8
    • implode - Join array elements with a string
    • import_request_variables - Import GET/POST/Cookie variables into the global scope
    • inclued_get_data - Get the inclued data
    • inet_ntop - Converts a packed internet address to a human readable representation
    • inet_pton - Converts a human readable IP address to its packed in_addr representation
    • InfiniteIterator::next - Moves the inner Iterator forward or rewinds it
    • InfiniteIterator::__construct - Constructs an InfiniteIterator
    • ingres_autocommit - Włącza lub wyłącza automatyczne zatwierdzanie
    • ingres_autocommit_state - Test if the connection is using autocommit
    • ingres_charset - Returns the installation character set
    • ingres_close - Zamyka połączenie z serwerem Ingres
    • ingres_commit - Zatwierdza transakcję
    • ingres_connect - Open a connection to an Ingres database
    • ingres_cursor - Get a cursor name for a given result resource
    • ingres_errno - Zwraca ostatnio wygenerowany numer błędu Ingres
    • ingres_error - Zwraca znaczący komunikat o ostatnio wygenerowanym błędzie
    • ingres_errsqlstate - Zwraca ostatnio wygenerowany kod błędu SQLSTATE
    • ingres_escape_string - Escape special characters for use in a query
    • ingres_execute - Execute a prepared query
    • ingres_fetch_array - Fetch a row of result into an array
    • ingres_fetch_assoc - Fetch a row of result into an associative array
    • ingres_fetch_object - Fetch a row of result into an object
    • ingres_fetch_proc_return - Get the return value from a procedure call
    • ingres_fetch_row - Fetch a row of result into an enumerated array
    • ingres_field_length - Get the length of a field
    • ingres_field_name - Zwraca nazwę pola z wyniku zapytania
    • ingres_field_nullable - Sprawdza czy pole może przyjmować wartość NULL
    • ingres_field_precision - Get the precision of a field
    • ingres_field_scale - Get the scale of a field
    • ingres_field_type - Get the type of a field in a query result
    • ingres_free_result - Free the resources associated with a result identifier
    • ingres_next_error - Get the next Ingres error
    • ingres_num_fields - Pobiera liczbę pól zwracanych przez ostatnie zapytanie
    • ingres_num_rows - Get the number of rows affected or returned by a query
    • ingres_pconnect - Open a persistent connection to an Ingres database
    • ingres_prepare - Prepare a query for later execution
    • ingres_query - Send an SQL query to Ingres
    • ingres_result_seek - Set the row position before fetching data
    • ingres_rollback - Wycofuje transakcję
    • ingres_set_environment - Set environment features controlling output options
    • ingres_unbuffered_query - Send an unbuffered SQL query to Ingres
    • ini_alter - Alias dla ini_set
    • ini_get - Gets the value of a configuration option
    • ini_get_all - Gets all configuration options
    • ini_restore - Restores the value of a configuration option
    • ini_set - Sets the value of a configuration option
    • inotify_add_watch - Add a watch to an initialized inotify instance
    • inotify_init - Initialize an inotify instance
    • inotify_queue_len - Return a number upper than zero if there are pending events
    • inotify_read - Read events from an inotify instance
    • inotify_rm_watch - Remove an existing watch from an inotify instance
    • interface_exists - Checks if the interface has been defined
    • IntlDateFormatter::create - Create a date formatter
    • IntlDateFormatter::format - Format the date/time value as a string
    • IntlDateFormatter::getCalendar - Get the calendar used for the IntlDateFormatter
    • IntlDateFormatter::getDateType - Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode - Get the error code from last operation
    • IntlDateFormatter::getErrorMessage - Get the error text from the last operation.
    • IntlDateFormatter::getLocale - Get the locale used by formatter
    • IntlDateFormatter::getPattern - Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType - Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZoneId - Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::isLenient - Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime - Parse string to a field-based time value
    • IntlDateFormatter::parse - Parse string to a timestamp value
    • IntlDateFormatter::setCalendar - sets the calendar used to the appropriate calendar, which must be
    • IntlDateFormatter::setLenient - Set the leniency of the parser
    • IntlDateFormatter::setPattern - Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZoneId - Sets the time zone to use
    • intl_error_name - Get symbolic name for a given error code
    • intl_get_error_code - Get the last error code
    • intl_get_error_message - Get description of the last error
    • intl_is_failure - Check whether the given error code indicates failure
    • intval - Get the integer value of a variable
    • in_array - Sprawdza czy wartość istnieje w tablicy
    • ip2long - Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
    • iptcembed - Embeds binary IPTC data into a JPEG image
    • iptcparse - Parse a binary IPTC block into single tags.
    • isset - Determine if a variable is set and is not NULL
    • is_a - Zwraca TRUE jeżeli obiekt jest tej klasy, lub ta klasa jest jednym z jego przodków
    • is_array - Finds whether a variable is an array
    • is_bool - Finds out whether a variable is a boolean
    • is_callable - Verify that the contents of a variable can be called as a function
    • is_dir - Mówi czy nazwa_pliku jest katalogiem
    • is_double - Alias dla is_float
    • is_executable - Mówi czy plik jest wykonywalny
    • is_file - Mówi czy nazwa_pliku jest zwykłym plikiem
    • is_finite - Sprawdza czy wartość jest prawidłową skończoną liczbą
    • is_float - Finds whether the type of a variable is float
    • is_infinite - Sprawdza czy wartość jest nieskończona
    • is_int - Find whether the type of a variable is integer
    • is_integer - Alias dla is_int
    • is_link - Mówi czy nazwa_pliku jest dowiązaniem symbolicznym
    • is_long - Alias dla is_int
    • is_nan - Sprawdza, czy wartość nie jest liczbą
    • is_null - Finds whether a variable is NULL
    • is_numeric - Finds whether a variable is a number or a numeric string
    • is_object - Finds whether a variable is an object
    • is_readable - Tells whether a file exists and is readable
    • is_real - Alias dla is_float
    • is_resource - Finds whether a variable is a resource
    • is_scalar - Finds whether a variable is a scalar
    • is_soap_fault - Checks if a SOAP call has failed
    • is_string - Find whether the type of a variable is string
    • is_subclass_of - Zwraca TRUE jeżeli klasa jest jednym z przodków obiektu
    • is_uploaded_file - Mówi czy plik został przysłany przez HTTP POST.
    • is_writable - Tells whether the filename is writable
    • is_writeable - Alias dla is_writable
    • Iterator::current - Return the current element
    • Iterator::key - Return the key of the current element
    • Iterator::next - Move forward to next element
    • Iterator::rewind - Rewind the Iterator to the first element
    • Iterator::valid - Checks if current position is valid
    • IteratorAggregate::getIterator - Retrieve an external iterator
    • IteratorIterator::current - Get the current value
    • IteratorIterator::getInnerIterator - Get the inner iterator
    • IteratorIterator::key - Get the key of the current element
    • IteratorIterator::next - Forward to the next element
    • IteratorIterator::rewind - Rewind to the first element
    • IteratorIterator::valid - Checks if the iterator is valid
    • IteratorIterator::__construct - Create an iterator from anything that is traversable
    • iterator_apply - Call a function for every element in an iterator
    • iterator_count - Count the elements in an iterator
    • iterator_to_array - Copy the iterator into an array
  • j
    • java_last_exception_clear - Clear last Java exception
    • java_last_exception_get - Get last Java exception
    • 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
    • join - Alias dla implode
    • jpeg2wbmp - Convert JPEG image file to WBMP image file
    • JsonSerializable::jsonSerialize - Specify data which should be serialized to JSON
    • json_decode - Dekoduje łańcuch JSON
    • json_encode - Zwraca JSON reprezentujący wartość
    • json_last_error - Zwraca ostatni błąd JSON
    • Judy::byCount - Locate the Nth index present in the Judy array
    • Judy::count - Count the number of elements in the Judy array
    • Judy::first - Search for the first index in the Judy array
    • Judy::firstEmpty - Search for the first absent index in the Judy array
    • Judy::free - Free the entire Judy array
    • Judy::getType - Return the type of the current Judy array
    • Judy::last - Search for the last index in the Judy array
    • Judy::lastEmpty - Search for the last absent index in the Judy array
    • Judy::memoryUsage - Return the memory used by the Judy array
    • Judy::next - Search for the next index in the Judy array
    • Judy::nextEmpty - Search for the next absent index in the Judy array
    • Judy::offsetExists - Whether a offset exists
    • Judy::offsetGet - Offset to retrieve
    • Judy::offsetSet - Offset to set
    • Judy::offsetUnset - Offset to unset
    • Judy::prev - Search for the previous index in the Judy array
    • Judy::prevEmpty - Search for the previous absent index in the Judy array
    • Judy::size - Return the size of the current Judy array
    • Judy::__construct - Construct a new Judy object
    • Judy::__destruct - Destruct a Judy object
    • judy_type - Return the type of a Judy array
    • judy_version - Return or print the current PHP Judy version
    • JulianToJD - Converts a Julian Calendar date to Julian Day Count
  • k
    • kadm5_chpass_principal - Changes the principal's password
    • kadm5_create_principal - Creates a kerberos principal with the given parameters
    • kadm5_delete_principal - Deletes a kerberos principal
    • kadm5_destroy - Closes the connection to the admin server and releases all related resources
    • kadm5_flush - Flush all changes to the Kerberos database
    • kadm5_get_policies - Gets all policies from the Kerberos database
    • kadm5_get_principal - Gets the principal's entries from the Kerberos database
    • kadm5_get_principals - Gets all principals from the Kerberos database
    • kadm5_init_with_password - Opens a connection to the KADM5 library
    • kadm5_modify_principal - Modifies a kerberos principal with the given parameters
    • key - Pobiera klucz z tablicy asocjacyjnej
    • krsort - Sortuj tablicę według kluczy w porządku odwrotnym
    • ksort - Sortuj tablicę według klucza
    • KTaglib_ID3v2_AttachedPictureFrame::getDescription - Returns a description for the picture in a picture frame
    • KTaglib_ID3v2_AttachedPictureFrame::getMimeType - Returns the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::getType - Returns the type of the image
    • KTaglib_ID3v2_AttachedPictureFrame::savePicture - Saves the picture to a file
    • KTaglib_ID3v2_AttachedPictureFrame::setMimeType - Set's the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::setPicture - Sets the frame picture to the given image
    • KTaglib_ID3v2_AttachedPictureFrame::setType - Set the type of the image
    • KTaglib_ID3v2_Frame::getSize - Returns the size of the frame in bytes
    • KTaglib_ID3v2_Frame::__toString - Returns a string representation of the frame
    • KTaglib_ID3v2_Tag::addFrame - Add a frame to the ID3v2 tag
    • KTaglib_ID3v2_Tag::getFrameList - Returns an array of ID3v2 frames, associated with the ID3v2 tag
    • KTaglib_MPEG_AudioProperties::getBitrate - Returns the bitrate of the MPEG file
    • KTaglib_MPEG_AudioProperties::getChannels - Returns the amount of channels of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLayer - Returns the layer of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLength - Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::getSampleBitrate - Returns the sample bitrate of a MPEG file
    • KTaglib_MPEG_AudioProperties::getVersion - Returns the version of a MPEG file
    • KTaglib_MPEG_AudioProperties::isCopyrighted - Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal - Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled - Returns the length of a MPEG file
    • KTaglib_MPEG_File::getAudioProperties - Returns an object that provides access to the audio properties
    • KTaglib_MPEG_File::getID3v1Tag - Returns an object representing an ID3v1 tag
    • KTaglib_MPEG_File::getID3v2Tag - Returns a ID3v2 object
    • KTaglib_MPEG_File::__construct - Opens a new file
    • KTaglib_Tag::getAlbum - Returns the title string from a ID3 tag
    • KTaglib_Tag::getArtist - Returns the artist string from a ID3 tag
    • KTaglib_Tag::getComment - Returns the comment from a ID3 tag
    • KTaglib_Tag::getGenre - Returns the genre from a ID3 tag
    • KTaglib_Tag::getTitle - Returns the title string from a ID3 tag
    • KTaglib_Tag::getTrack - Returns the track number from a ID3 tag
    • KTaglib_Tag::getYear - Returns the year from a ID3 tag
    • KTaglib_Tag::isEmpty - Returns true if the tag is empty
  • l
    • lcfirst - Make a string's first character lowercase
    • lcg_value - Złożony przystający generator liniowy
    • lchgrp - Changes group ownership of symlink
    • lchown - Changes user ownership of symlink
    • ldap_8859_to_t61 - Translate 8859 characters to t61 characters
    • ldap_add - Add entries to LDAP directory
    • ldap_bind - Bind to LDAP directory
    • ldap_close - Alias dla ldap_unbind
    • ldap_compare - Compare value of attribute found in entry specified with DN
    • ldap_connect - Connect to an LDAP server
    • ldap_count_entries - Count the number of entries in a search
    • ldap_delete - Delete an entry from a directory
    • ldap_dn2ufn - Convert DN to User Friendly Naming format
    • ldap_err2str - Convert LDAP error number into string error message
    • ldap_errno - Return the LDAP error number of the last LDAP command
    • ldap_error - Return the LDAP error message of the last LDAP command
    • ldap_explode_dn - Splits DN into its component parts
    • ldap_first_attribute - Return first attribute
    • ldap_first_entry - Return first result id
    • ldap_first_reference - Return first reference
    • ldap_free_result - Free result memory
    • ldap_get_attributes - Get attributes from a search result entry
    • ldap_get_dn - Get the DN of a result entry
    • ldap_get_entries - Get all result entries
    • ldap_get_option - Get the current value for given option
    • ldap_get_values - Get all values from a result entry
    • ldap_get_values_len - Get all binary values from a result entry
    • ldap_list - Single-level search
    • ldap_modify - Modify an LDAP entry
    • ldap_mod_add - Add attribute values to current attributes
    • ldap_mod_del - Delete attribute values from current attributes
    • ldap_mod_replace - Replace attribute values with new ones
    • ldap_next_attribute - Get the next attribute in result
    • ldap_next_entry - Get next result entry
    • ldap_next_reference - Get next reference
    • ldap_parse_reference - Extract information from reference entry
    • ldap_parse_result - Extract information from result
    • ldap_read - Read an entry
    • ldap_rename - Modify the name of an entry
    • ldap_sasl_bind - Bind to LDAP directory using SASL
    • ldap_search - Search LDAP tree
    • ldap_set_option - Set the value of the given option
    • ldap_set_rebind_proc - Set a callback function to do re-binds on referral chasing
    • ldap_sort - Sort LDAP result entries
    • ldap_start_tls - Start TLS
    • ldap_t61_to_8859 - Translate t61 characters to 8859 characters
    • ldap_unbind - Unbind from LDAP directory
    • levenshtein - Calculate Levenshtein distance between two strings
    • libxml_clear_errors - Clear libxml error buffer
    • libxml_disable_entity_loader - Disable the ability to load external entities
    • libxml_get_errors - Retrieve array of errors
    • libxml_get_last_error - Retrieve last error from libxml
    • libxml_set_streams_context - Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors - Disable libxml errors and allow user to fetch error information as needed
    • LimitIterator::current - Get current element
    • LimitIterator::getInnerIterator - Get inner iterator
    • LimitIterator::getPosition - Return the current position
    • LimitIterator::key - Get current key
    • LimitIterator::next - Move the iterator forward
    • LimitIterator::rewind - Rewind the iterator to the specified starting offset
    • LimitIterator::seek - Seek to the given position
    • LimitIterator::valid - Check whether the current element is valid
    • LimitIterator::__construct - Construct a LimitIterator
    • link - Tworzy dowiązanie twarde
    • linkinfo - Pobiera informacje o linku
    • list - Przypisz zmienne tak jakby były tablicą
    • Locale::acceptFromHttp - Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::composeLocale - Returns a correctly ordered and delimited locale ID
    • Locale::filterMatches - Checks if a language tag filter matches with locale
    • Locale::getAllVariants - Gets the variants for the input locale
    • Locale::getDefault - Gets the default locale value from the INTL global 'default_locale'
    • Locale::getDisplayLanguage - Returns an appropriately localized display name for language of the inputlocale
    • Locale::getDisplayName - Returns an appropriately localized display name for the input locale
    • Locale::getDisplayRegion - Returns an appropriately localized display name for region of the input locale
    • Locale::getDisplayScript - Returns an appropriately localized display name for script of the input locale
    • Locale::getDisplayVariant - Returns an appropriately localized display name for variants of the input locale
    • Locale::getKeywords - Gets the keywords for the input locale
    • Locale::getPrimaryLanguage - Gets the primary language for the input locale
    • Locale::getRegion - Gets the region for the input locale
    • Locale::getScript - Gets the script for the input locale
    • Locale::lookup - Searches the language tag list for the best match to the language
    • Locale::parseLocale - Returns a key-value array of locale ID subtag elements.
    • Locale::setDefault - sets the default runtime locale
    • localeconv - Get numeric formatting information
    • localtime - Pobiera czas lokalny
    • log - Logarytm naturalny
    • log1p - Zwraca log(1 + liczba), obliczony w taki sposób, że wartości są dokładne, nawet, jeśli liczba jest bliska zeru
    • log10 - Logarytm dziesiętny
    • long2ip - Converts an (IPv4) Internet network address into a string in Internet standard dotted format
    • lstat - Podaje informacje o pliku lub dowiązaniu symbolicznym
    • ltrim - Strip whitespace (or other characters) from the beginning of a string
    • Lua::assign - Assign a PHP variable to Lua
    • Lua::call - Call Lua functions
    • Lua::eval - Evaluate a string as Lua code
    • Lua::getVersion - The getversion purpose
    • Lua::include - Parse a Lua script file
    • Lua::registerCallback - Register a PHP function to Lua
    • Lua::__construct - Lua constructor
    • LuaClosure::__invoke - invoke luaclosure
    • lzf_compress - LZF compression
    • lzf_decompress - LZF decompression
    • lzf_optimized_for - Determines what LZF extension was optimized for
  • m
    • magic_quotes_runtime - Alias dla set_magic_quotes_runtime
    • mail - Wysyłanie poczty elektronicznej
    • mailparse_determine_best_xfer_encoding - Gets the best way of encoding
    • mailparse_msg_create - Create a mime mail resource
    • mailparse_msg_extract_part - Extracts/decodes a message section
    • mailparse_msg_extract_part_file - Extracts/decodes a message section
    • mailparse_msg_extract_whole_part_file - Extracts a message section including headers without decoding the transfer encoding
    • mailparse_msg_free - Frees a MIME resource
    • mailparse_msg_get_part - Returns a handle on a given section in a mimemessage
    • mailparse_msg_get_part_data - Returns an associative array of info about the message
    • mailparse_msg_get_structure - Returns an array of mime section names in the supplied message
    • mailparse_msg_parse - Incrementally parse data into buffer
    • mailparse_msg_parse_file - Parses a file
    • mailparse_rfc822_parse_addresses - Parse RFC 822 compliant addresses
    • mailparse_stream_encode - Streams data from source file pointer, apply encoding and write to destfp
    • mailparse_uudecode_all - Scans the data from fp and extract each embedded uuencoded file
    • main - Dummy for main
    • max - Znajduje największą liczbę
    • maxdb_affected_rows - Gets the number of affected rows in a previous MaxDB operation
    • maxdb_autocommit - Turns on or off auto-commiting database modifications
    • maxdb_bind_param - Alias dla maxdb_stmt_bind_param
    • maxdb_bind_result - Alias dla maxdb_stmt_bind_result
    • maxdb_change_user - Changes the user of the specified database connection
    • maxdb_character_set_name - Returns the default character set for the database connection
    • maxdb_client_encoding - Alias dla maxdb_character_set_name
    • maxdb_close - Closes a previously opened database connection
    • maxdb_close_long_data - Alias dla maxdb_stmt_close_long_data
    • maxdb_commit - Commits the current transaction
    • maxdb_connect - Open a new connection to the MaxDB server
    • maxdb_connect_errno - Returns the error code from last connect call
    • maxdb_connect_error - Returns a string description of the last connect error
    • maxdb_data_seek - Adjusts the result pointer to an arbitary row in the result
    • maxdb_debug - Performs debugging operations
    • maxdb_disable_reads_from_master - Disable reads from master
    • maxdb_disable_rpl_parse - Disable RPL parse
    • maxdb_dump_debug_info - Dump debugging information into the log
    • maxdb_embedded_connect - Open a connection to an embedded MaxDB server
    • maxdb_enable_reads_from_master - Enable reads from master
    • maxdb_enable_rpl_parse - Enable RPL parse
    • maxdb_errno - Returns the error code for the most recent function call
    • maxdb_error - Returns a string description of the last error
    • maxdb_escape_string - Alias dla maxdb_real_escape_string
    • maxdb_execute - Alias dla maxdb_stmt_execute
    • maxdb_fetch - Alias dla maxdb_stmt_fetch
    • maxdb_fetch_array - Fetch a result row as an associative, a numeric array, or both
    • maxdb_fetch_assoc - Fetch a result row as an associative array
    • maxdb_fetch_field - Returns the next field in the result set
    • maxdb_fetch_fields - Returns an array of resources representing the fields in a result set
    • maxdb_fetch_field_direct - Fetch meta-data for a single field
    • maxdb_fetch_lengths - Returns the lengths of the columns of the current row in the result set
    • maxdb_fetch_object - Returns the current row of a result set as an object
    • maxdb_fetch_row - Get a result row as an enumerated array
    • maxdb_field_count - Returns the number of columns for the most recent query
    • maxdb_field_seek - Set result pointer to a specified field offset
    • maxdb_field_tell - Get current field offset of a result pointer
    • maxdb_free_result - Frees the memory associated with a result
    • maxdb_get_client_info - Returns the MaxDB client version as a string
    • maxdb_get_client_version - Get MaxDB client info
    • maxdb_get_host_info - Returns a string representing the type of connection used
    • maxdb_get_metadata - Alias dla maxdb_stmt_result_metadata
    • maxdb_get_proto_info - Returns the version of the MaxDB protocol used
    • maxdb_get_server_info - Returns the version of the MaxDB server
    • maxdb_get_server_version - Returns the version of the MaxDB server as an integer
    • maxdb_info - Retrieves information about the most recently executed query
    • maxdb_init - Initializes MaxDB and returns an resource for use with maxdb_real_connect
    • maxdb_insert_id - Returns the auto generated id used in the last query
    • maxdb_kill - Disconnects from a MaxDB server
    • maxdb_master_query - Enforce execution of a query on the master in a master/slave setup
    • maxdb_more_results - Check if there any more query results from a multi query
    • maxdb_multi_query - Performs a query on the database
    • maxdb_next_result - Prepare next result from multi_query
    • maxdb_num_fields - Get the number of fields in a result
    • maxdb_num_rows - Gets the number of rows in a result
    • maxdb_options - Set options
    • maxdb_param_count - Alias dla maxdb_stmt_param_count
    • maxdb_ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • maxdb_prepare - Prepare an SQL statement for execution
    • maxdb_query - Performs a query on the database
    • maxdb_real_connect - Opens a connection to a MaxDB server
    • maxdb_real_escape_string - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • maxdb_real_query - Execute an SQL query
    • maxdb_report - Enables or disables internal report functions
    • maxdb_rollback - Rolls back current transaction
    • maxdb_rpl_parse_enabled - Check if RPL parse is enabled
    • maxdb_rpl_probe - RPL probe
    • maxdb_rpl_query_type - Returns RPL query type
    • maxdb_select_db - Selects the default database for database queries
    • maxdb_send_long_data - Alias dla maxdb_stmt_send_long_data
    • maxdb_send_query - Send the query and return
    • maxdb_server_end - Shut down the embedded server
    • maxdb_server_init - Initialize embedded server
    • maxdb_set_opt - Alias dla maxdb_options
    • maxdb_sqlstate - Returns the SQLSTATE error from previous MaxDB operation
    • maxdb_ssl_set - Used for establishing secure connections using SSL
    • maxdb_stat - Gets the current system status
    • maxdb_stmt_affected_rows - Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • maxdb_stmt_bind_param - Binds variables to a prepared statement as parameters
    • maxdb_stmt_bind_result - Binds variables to a prepared statement for result storage
    • maxdb_stmt_close - Closes a prepared statement
    • maxdb_stmt_close_long_data - Ends a sequence of maxdb_stmt_send_long_data
    • maxdb_stmt_data_seek - Seeks to an arbitray row in statement result set
    • maxdb_stmt_errno - Returns the error code for the most recent statement call
    • maxdb_stmt_error - Returns a string description for last statement error
    • maxdb_stmt_execute - Executes a prepared Query
    • maxdb_stmt_fetch - Fetch results from a prepared statement into the bound variables
    • maxdb_stmt_free_result - Frees stored result memory for the given statement handle
    • maxdb_stmt_init - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
    • maxdb_stmt_num_rows - Return the number of rows in statements result set
    • maxdb_stmt_param_count - Returns the number of parameter for the given statement
    • maxdb_stmt_prepare - Prepare an SQL statement for execution
    • maxdb_stmt_reset - Resets a prepared statement
    • maxdb_stmt_result_metadata - Returns result set metadata from a prepared statement
    • maxdb_stmt_send_long_data - Send data in blocks
    • maxdb_stmt_sqlstate - Returns SQLSTATE error from previous statement operation
    • maxdb_stmt_store_result - Transfers a result set from a prepared statement
    • maxdb_store_result - Transfers a result set from the last query
    • maxdb_thread_id - Returns the thread ID for the current connection
    • maxdb_thread_safe - Returns whether thread safety is given or not
    • maxdb_use_result - Initiate a result set retrieval
    • maxdb_warning_count - Returns the number of warnings from the last query for the given link
    • mb_check_encoding - Check if the string is valid for the specified encoding
    • mb_convert_case - Perform case folding on a string
    • mb_convert_encoding - Convert character encoding
    • mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
    • mb_convert_variables - Convert character code in variable(s)
    • mb_decode_mimeheader - Decode string in MIME header field
    • mb_decode_numericentity - Decode HTML numeric string reference to character
    • mb_detect_encoding - Detect character encoding
    • mb_detect_order - Set/Get character encoding detection order
    • mb_encode_mimeheader - Encode string for MIME header
    • mb_encode_numericentity - Encode character to HTML numeric string reference
    • mb_encoding_aliases - Get aliases of a known encoding type
    • mb_ereg - Regular expression match with multibyte support
    • mb_eregi - Regular expression match ignoring case with multibyte support
    • mb_eregi_replace - Replace regular expression with multibyte support ignoring case
    • mb_ereg_match - Regular expression match for multibyte string
    • mb_ereg_replace - Replace regular expression with multibyte support
    • mb_ereg_search - Multibyte regular expression match for predefined multibyte string
    • mb_ereg_search_getpos - Returns start point for next regular expression match
    • mb_ereg_search_getregs - Retrieve the result from the last multibyte regular expression match
    • mb_ereg_search_init - Setup string and regular expression for a multibyte regular expression match
    • mb_ereg_search_pos - Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
    • mb_ereg_search_regs - Returns the matched part of a multibyte regular expression
    • mb_ereg_search_setpos - Set start point of next regular expression match
    • mb_get_info - Get internal settings of mbstring
    • mb_http_input - Detect HTTP input character encoding
    • mb_http_output - Set/Get HTTP output character encoding
    • mb_internal_encoding - Set/Get internal character encoding
    • mb_language - Set/Get current language
    • mb_list_encodings - Returns an array of all supported encodings
    • mb_output_handler - Callback function converts character encoding in output buffer
    • mb_parse_str - Parse GET/POST/COOKIE data and set global variable
    • mb_preferred_mime_name - Get MIME charset string
    • mb_regex_encoding - Returns current encoding for multibyte regex as string
    • mb_regex_set_options - Set/Get the default options for mbregex functions
    • mb_send_mail - Send encoded mail
    • mb_split - Split multibyte string using regular expression
    • mb_strcut - Get part of string
    • mb_strimwidth - Get truncated string with specified width
    • mb_stripos - Finds position of first occurrence of a string within another, case insensitive
    • mb_stristr - Finds first occurrence of a string within another, case insensitive
    • mb_strlen - Get string length
    • mb_strpos - Find position of first occurrence of string in a string
    • mb_strrchr - Finds the last occurrence of a character in a string within another
    • mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive
    • mb_strripos - Finds position of last occurrence of a string within another, case insensitive
    • mb_strrpos - Find position of last occurrence of a string in a string
    • mb_strstr - Finds first occurrence of a string within another
    • mb_strtolower - Make a string lowercase
    • mb_strtoupper - Make a string uppercase
    • mb_strwidth - Return width of string
    • mb_substitute_character - Set/Get substitution character
    • mb_substr - Get part of string
    • mb_substr_count - Count the number of substring occurrences
    • mcrypt_cbc - Encrypts/decrypts data in CBC mode
    • mcrypt_cfb - Encrypts/decrypts data in CFB mode
    • mcrypt_create_iv - Creates an initialization vector (IV) from a random source
    • mcrypt_decrypt - Decrypts crypttext with given parameters
    • mcrypt_ecb - Deprecated: Encrypts/decrypts data in ECB mode
    • mcrypt_encrypt - Encrypts plaintext with given parameters
    • mcrypt_enc_get_algorithms_name - Returns the name of the opened algorithm
    • mcrypt_enc_get_block_size - Returns the blocksize of the opened algorithm
    • mcrypt_enc_get_iv_size - Returns the size of the IV of the opened algorithm
    • mcrypt_enc_get_key_size - Returns the maximum supported keysize of the opened mode
    • mcrypt_enc_get_modes_name - Returns the name of the opened mode
    • mcrypt_enc_get_supported_key_sizes - Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_enc_is_block_algorithm - Checks whether the algorithm of the opened mode is a block algorithm
    • mcrypt_enc_is_block_algorithm_mode - Checks whether the encryption of the opened mode works on blocks
    • mcrypt_enc_is_block_mode - Checks whether the opened mode outputs blocks
    • mcrypt_enc_self_test - Runs a self test on the opened module
    • mcrypt_generic - This function encrypts data
    • mcrypt_generic_deinit - This function deinitializes an encryption module
    • mcrypt_generic_end - This function terminates encryption
    • mcrypt_generic_init - This function initializes all buffers needed for encryption
    • mcrypt_get_block_size - Gets the block size of the specified cipher
    • mcrypt_get_cipher_name - Gets the name of the specified cipher
    • mcrypt_get_iv_size - Returns the size of the IV belonging to a specific cipher/mode combination
    • mcrypt_get_key_size - Gets the key size of the specified cipher
    • mcrypt_list_algorithms - Gets an array of all supported ciphers
    • mcrypt_list_modes - Gets an array of all supported modes
    • mcrypt_module_close - Closes the mcrypt module
    • mcrypt_module_get_algo_block_size - Returns the blocksize of the specified algorithm
    • mcrypt_module_get_algo_key_size - Returns the maximum supported keysize of the opened mode
    • mcrypt_module_get_supported_key_sizes - Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_module_is_block_algorithm - This function checks whether the specified algorithm is a block algorithm
    • mcrypt_module_is_block_algorithm_mode - Returns if the specified module is a block algorithm or not
    • mcrypt_module_is_block_mode - Returns if the specified mode outputs blocks or not
    • mcrypt_module_open - Opens the module of the algorithm and the mode to be used
    • mcrypt_module_self_test - This function runs a self test on the specified module
    • mcrypt_ofb - Encrypts/decrypts data in OFB mode
    • md5 - Calculate the md5 hash of a string
    • md5_file - Calculates the md5 hash of a given file
    • mdecrypt_generic - Decrypts data
    • Memcache::add - Add an item to the server
    • Memcache::addServer - Add a memcached server to connection pool
    • Memcache::close - Close memcached server connection
    • Memcache::connect - Open memcached server connection
    • Memcache::decrement - Decrement item's value
    • Memcache::delete - Delete item from the server
    • Memcache::flush - Flush all existing items at the server
    • Memcache::get - Retrieve item from the server
    • Memcache::getExtendedStats - Get statistics from all servers in pool
    • Memcache::getServerStatus - Returns server status
    • Memcache::getStats - Get statistics of the server
    • Memcache::getVersion - Return version of the server
    • Memcache::increment - Increment item's value
    • Memcache::pconnect - Open memcached server persistent connection
    • Memcache::replace - Replace value of the existing item
    • Memcache::set - Store data at the server
    • Memcache::setCompressThreshold - Enable automatic compression of large values
    • Memcache::setServerParams - Changes server parameters and status at runtime
    • Memcached::add - Add an item under a new key
    • Memcached::addByKey - Add an item under a new key on a specific server
    • Memcached::addServer - Add a server to the server pool
    • Memcached::addServers - Add multiple servers to the server pool
    • Memcached::append - Append data to an existing item
    • Memcached::appendByKey - Append data to an existing item on a specific server
    • Memcached::cas - Compare and swap an item
    • Memcached::casByKey - Compare and swap an item on a specific server
    • Memcached::decrement - Decrement numeric item's value
    • Memcached::delete - Delete an item
    • Memcached::deleteByKey - Delete an item from a specific server
    • Memcached::fetch - Fetch the next result
    • Memcached::fetchAll - Fetch all the remaining results
    • Memcached::flush - Invalidate all items in the cache
    • Memcached::get - Retrieve an item
    • Memcached::getByKey - Retrieve an item from a specific server
    • Memcached::getDelayed - Request multiple items
    • Memcached::getDelayedByKey - Request multiple items from a specific server
    • Memcached::getMulti - Retrieve multiple items
    • Memcached::getMultiByKey - Retrieve multiple items from a specific server
    • Memcached::getOption - Retrieve a Memcached option value
    • Memcached::getResultCode - Return the result code of the last operation
    • Memcached::getResultMessage - Return the message describing the result of the last operation
    • Memcached::getServerByKey - Map a key to a server
    • Memcached::getServerList - Get the list of the servers in the pool
    • Memcached::getStats - Get server pool statistics
    • Memcached::getVersion - Get server pool version info
    • Memcached::increment - Increment numeric item's value
    • Memcached::prepend - Prepend data to an existing item
    • Memcached::prependByKey - Prepend data to an existing item on a specific server
    • Memcached::replace - Replace the item under an existing key
    • Memcached::replaceByKey - Replace the item under an existing key on a specific server
    • Memcached::set - Store an item
    • Memcached::setByKey - Store an item on a specific server
    • Memcached::setMulti - Store multiple items
    • Memcached::setMultiByKey - Store multiple items on a specific server
    • Memcached::setOption - Set a Memcached option
    • Memcached::__construct - Create a Memcached instance
    • memcache_debug - Turn debug output on/off
    • memory_get_peak_usage - Returns the peak of memory allocated by PHP
    • memory_get_usage - Returns the amount of memory allocated to PHP
    • MessageFormatter::create - Constructs a new Message Formatter
    • MessageFormatter::format - Format the message
    • MessageFormatter::formatMessage - Quick format message
    • MessageFormatter::getErrorCode - Get the error code from last operation
    • MessageFormatter::getErrorMessage - Get the error text from the last operation
    • MessageFormatter::getLocale - Get the locale for which the formatter was created.
    • MessageFormatter::getPattern - Get the pattern used by the formatter
    • MessageFormatter::parse - Parse input string according to pattern
    • MessageFormatter::parseMessage - Quick parse input string
    • MessageFormatter::setPattern - Set the pattern used by the formatter
    • metaphone - Calculate the metaphone key of a string
    • method_exists - Sprawdza czy metoda klasy istnieje
    • mhash - Computes hash
    • mhash_count - Gets the highest available hash ID
    • mhash_get_block_size - Gets the block size of the specified hash
    • mhash_get_hash_name - Gets the name of the specified hash
    • mhash_keygen_s2k - Generates a key
    • microtime - Zwraca aktualny uniksowy znacznik czasu z mikrosekundami
    • mime_content_type - Detect MIME Content-type for a file (deprecated)
    • min - Znajduje najmniejszą wartość
    • ming_keypress - Returns the action flag for keyPress(char)
    • ming_setcubicthreshold - Set cubic threshold
    • ming_setscale - Set the global scaling factor.
    • ming_setswfcompression - Sets the SWF output compression
    • ming_useconstants - Use constant pool
    • ming_useswfversion - Sets the SWF version
    • mkdir - Tworzy katalog
    • mktime - Oblicza uniksowy znacznik czasu dla podanej daty
    • money_format - Formats a number as a currency string
    • Mongo::close - Closes this connection
    • Mongo::connect - Connects to a database server
    • Mongo::connectUtil - Connects with a database server
    • Mongo::dropDB - Drops a database [deprecated]
    • Mongo::getHosts - Updates status for all hosts associated with this
    • Mongo::getPoolSize - Get pool size for connection pools
    • Mongo::getSlave - Returns the address being used by this for slaveOkay reads
    • Mongo::getSlaveOkay - Get slaveOkay setting for this connection
    • Mongo::listDBs - Lists all of the databases available.
    • Mongo::poolDebug - Returns information about all connection pools.
    • Mongo::selectCollection - Gets a database collection
    • Mongo::selectDB - Gets a database
    • Mongo::setPoolSize - Set the size for future connection pools.
    • Mongo::setSlaveOkay - Change slaveOkay setting for this connection
    • Mongo::switchSlave - Choose a new slave for slaveOkay reads
    • Mongo::__construct - Creates a new database connection object
    • Mongo::__get - Gets a database
    • Mongo::__toString - String representation of this connection
    • MongoBinData::__construct - Creates a new binary data object.
    • MongoBinData::__toString - The string representation of this binary data object.
    • MongoCode::__construct - Creates a new code object
    • MongoCode::__toString - Returns this code as a string
    • MongoCollection::batchInsert - Inserts multiple documents into this collection
    • MongoCollection::count - Counts the number of documents in this collection
    • MongoCollection::createDBRef - Creates a database reference
    • MongoCollection::deleteIndex - Deletes an index from this collection
    • MongoCollection::deleteIndexes - Delete all indices for this collection
    • MongoCollection::drop - Drops this collection
    • MongoCollection::ensureIndex - Creates an index on the given field(s), or does nothing if the index already exists
    • MongoCollection::find - Querys this collection, returning a MongoCursor for the result set
    • MongoCollection::findOne - Querys this collection, returning a single element
    • MongoCollection::getDBRef - Fetches the document pointed to by a database reference
    • MongoCollection::getIndexInfo - Returns information about indexes on this collection
    • MongoCollection::getName - Returns this collection's name
    • MongoCollection::getSlaveOkay - Get slaveOkay setting for this collection
    • MongoCollection::group - Performs an operation similar to SQL's GROUP BY command
    • MongoCollection::insert - Inserts an array into the collection
    • MongoCollection::remove - Remove records from this collection
    • MongoCollection::save - Saves an object to this collection
    • MongoCollection::setSlaveOkay - Change slaveOkay setting for this collection
    • MongoCollection::toIndexString - Converts keys specifying an index to its identifying string
    • MongoCollection::update - Update records based on a given criteria
    • MongoCollection::validate - Validates this collection
    • MongoCollection::__construct - Creates a new collection
    • MongoCollection::__get - Gets a collection
    • MongoCollection::__toString - String representation of this collection
    • MongoCursor::addOption - Adds a top-level key/value pair to a query
    • MongoCursor::batchSize - Sets the number of results returned per result set
    • MongoCursor::count - Counts the number of results for this query
    • MongoCursor::current - Returns the current element
    • MongoCursor::dead - Checks if there are documents that have not been sent yet from the database for this cursor
    • MongoCursor::doQuery - Execute the query.
    • MongoCursor::explain - Return an explanation of the query, often useful for optimization and debugging
    • MongoCursor::fields - Sets the fields for a query
    • MongoCursor::getNext - Return the next object to which this cursor points, and advance the cursor
    • MongoCursor::hasNext - Checks if there are any more elements in this cursor
    • MongoCursor::hint - Gives the database a hint about the query
    • MongoCursor::immortal - Sets whether this cursor will timeout
    • MongoCursor::info - Gets the query, fields, limit, and skip for this cursor
    • MongoCursor::key - Returns the current result's _id
    • MongoCursor::limit - Limits the number of results returned
    • MongoCursor::next - Advances the cursor to the next result
    • MongoCursor::partial - If this query should fetch partial results from mongos if a shard is down
    • MongoCursor::reset - Clears the cursor
    • MongoCursor::rewind - Returns the cursor to the beginning of the result set
    • MongoCursor::skip - Skips a number of results
    • MongoCursor::slaveOkay - Sets whether this query can be done on a slave
    • MongoCursor::snapshot - Use snapshot mode for the query
    • MongoCursor::sort - Sorts the results by given fields
    • MongoCursor::tailable - Sets whether this cursor will be left open after fetching the last results
    • MongoCursor::timeout - Sets a client-side timeout for this query
    • MongoCursor::valid - Checks if the cursor is reading a valid result.
    • MongoCursor::__construct - Create a new cursor
    • MongoDate::__construct - Creates a new date.
    • MongoDate::__toString - Returns a string representation of this date
    • MongoDB::authenticate - Log in to this database
    • MongoDB::command - Execute a database command
    • MongoDB::createCollection - Creates a collection
    • MongoDB::createDBRef - Creates a database reference
    • MongoDB::drop - Drops this database
    • MongoDB::dropCollection - Drops a collection [deprecated]
    • MongoDB::execute - Runs JavaScript code on the database server.
    • MongoDB::forceError - Creates a database error
    • MongoDB::getDBRef - Fetches the document pointed to by a database reference
    • MongoDB::getGridFS - Fetches toolkit for dealing with files stored in this database
    • MongoDB::getProfilingLevel - Gets this database's profiling level
    • MongoDB::getSlaveOkay - Get slaveOkay setting for this database
    • MongoDB::lastError - Check if there was an error on the most recent db operation performed
    • MongoDB::listCollections - Get a list of collections in this database
    • MongoDB::prevError - Checks for the last error thrown during a database operation
    • MongoDB::repair - Repairs and compacts this database
    • MongoDB::resetError - Clears any flagged errors on the database
    • MongoDB::selectCollection - Gets a collection
    • MongoDB::setProfilingLevel - Sets this database's profiling level
    • MongoDB::setSlaveOkay - Change slaveOkay setting for this database
    • MongoDB::__construct - Creates a new database
    • MongoDB::__get - Gets a collection
    • MongoDB::__toString - The name of this database
    • MongoDBRef::create - Creates a new database reference
    • MongoDBRef::get - Fetches the object pointed to by a reference
    • MongoDBRef::isRef - Checks if an array is a database reference
    • MongoGridFS::delete - Delete a file from the database
    • MongoGridFS::drop - Drops the files and chunks collections
    • MongoGridFS::find - Queries for files
    • MongoGridFS::findOne - Returns a single file matching the criteria
    • MongoGridFS::get - Retrieve a file from the database
    • MongoGridFS::put - Stores a file in the database
    • MongoGridFS::remove - Removes files from the collections
    • MongoGridFS::storeBytes - Chunkifies and stores bytes in the database
    • MongoGridFS::storeFile - Stores a file in the database
    • MongoGridFS::storeUpload - Saves an uploaded file to the database
    • MongoGridFS::__construct - Creates new file collections
    • MongoGridFSCursor::current - Returns the current file
    • MongoGridFSCursor::getNext - Return the next file to which this cursor points, and advance the cursor
    • MongoGridFSCursor::key - Returns the current result's filename
    • MongoGridFSCursor::__construct - Create a new cursor
    • MongoGridFSFile::getBytes - Returns this file's contents as a string of bytes
    • MongoGridFSFile::getFilename - Returns this file's filename
    • MongoGridFSFile::getResource - Returns a resource that can be used to read the stored file
    • MongoGridFSFile::getSize - Returns this file's size
    • MongoGridFSFile::write - Writes this file to the filesystem
    • MongoGridfsFile::__construct - Create a new GridFS file
    • MongoId::getHostname - Gets the hostname being used for this machine's ids
    • MongoId::getInc - Gets the incremented value to create this id
    • MongoId::getPID - Gets the process id used to create this
    • MongoId::getTimestamp - Gets the number of seconds since the epoch that this id was created
    • MongoId::__construct - Creates a new id
    • MongoId::__set_state - Create a dummy MongoId
    • MongoId::__toString - Returns a hexidecimal representation of this id
    • MongoInt32::__construct - Creates a new 32-bit integer.
    • MongoInt32::__toString - Returns the string representation of this 32-bit integer.
    • MongoInt64::__construct - Creates a new 64-bit integer.
    • MongoInt64::__toString - Returns the string representation of this 64-bit integer.
    • MongoLog::getLevel - Gets the log level
    • MongoLog::getModule - Gets the modules currently being logged
    • MongoLog::setLevel - Sets logging level
    • MongoLog::setModule - Sets driver functionality to log
    • MongoPool::getSize - Get pool size for connection pools
    • MongoPool::info - Returns information about all connection pools.
    • MongoPool::setSize - Set the size for future connection pools.
    • MongoRegex::__construct - Creates a new regular expression
    • MongoRegex::__toString - A string representation of this regular expression
    • MongoTimestamp::__construct - Creates a new timestamp.
    • MongoTimestamp::__toString - Returns a string representation of this timestamp
    • move_uploaded_file - Przenieś uploadowany plik do innej lokalizacji
    • mqseries_back - MQSeries MQBACK
    • mqseries_begin - MQseries MQBEGIN
    • mqseries_close - MQSeries MQCLOSE
    • mqseries_cmit - MQSeries MQCMIT
    • mqseries_conn - MQSeries MQCONN
    • mqseries_connx - MQSeries MQCONNX
    • mqseries_disc - MQSeries MQDISC
    • mqseries_get - MQSeries MQGET
    • mqseries_inq - MQSeries MQINQ
    • mqseries_open - MQSeries MQOPEN
    • mqseries_put - MQSeries MQPUT
    • mqseries_put1 - MQSeries MQPUT1
    • mqseries_set - MQSeries MQSET
    • mqseries_strerror - Returns the error message corresponding to a result code (MQRC).
    • msession_connect - Connect to msession server
    • msession_count - Get session count
    • msession_create - Create a session
    • msession_destroy - Destroy a session
    • msession_disconnect - Close connection to msession server
    • msession_find - Find all sessions with name and value
    • msession_get - Get value from session
    • msession_get_array - Get array of msession variables
    • msession_get_data - Get data session unstructured data
    • msession_inc - Increment value in session
    • msession_list - List all sessions
    • msession_listvar - List sessions with variable
    • msession_lock - Lock a session
    • msession_plugin - Call an escape function within the msession personality plugin
    • msession_randstr - Get random string
    • msession_set - Set value in session
    • msession_set_array - Set msession variables from an array
    • msession_set_data - Set data session unstructured data
    • msession_timeout - Set/get session timeout
    • msession_uniq - Get unique id
    • msession_unlock - Unlock a session
    • msg_get_queue - Create or attach to a message queue
    • msg_queue_exists - Check whether a message queue exists
    • msg_receive - Receive a message from a message queue
    • msg_remove_queue - Destroy a message queue
    • msg_send - Send a message to a message queue
    • msg_set_queue - Set information in the message queue data structure
    • msg_stat_queue - Returns information from the message queue data structure
    • msql - Alias dla msql_db_query
    • msql_affected_rows - Returns number of affected rows
    • msql_close - Zamyka połączenie z serwerem mSQL
    • msql_connect - Otwiera połączenie z serwerem mSQL
    • msql_createdb - Alias dla msql_create_db
    • msql_create_db - Tworzy nową bazę danych na serwerze mSQL
    • msql_data_seek - Move internal row pointer
    • msql_dbname - Alias dla msql_result
    • msql_db_query - Send mSQL query
    • msql_drop_db - Usuwa bazę danych z serwera mSQL
    • msql_error - Returns error message of last msql call
    • msql_fetch_array - Fetch row as array
    • msql_fetch_field - Get field information
    • msql_fetch_object - Fetch row as object
    • msql_fetch_row - Get row as enumerated array
    • msql_fieldflags - Alias dla msql_field_flags
    • msql_fieldlen - Alias dla msql_field_len
    • msql_fieldname - Alias dla msql_field_name
    • msql_fieldtable - Alias dla msql_field_table
    • msql_fieldtype - Alias dla msql_field_type
    • msql_field_flags - Get field flags
    • msql_field_len - Get field length
    • msql_field_name - Get the name of the specified field in a result
    • msql_field_seek - Set field offset
    • msql_field_table - Get table name for field
    • msql_field_type - Get field type
    • msql_free_result - Free result memory
    • msql_list_dbs - List mSQL databases on server
    • msql_list_fields - List result fields
    • msql_list_tables - List tables in an mSQL database
    • msql_numfields - Alias dla msql_num_fields
    • msql_numrows - Alias dla msql_num_rows
    • msql_num_fields - Get number of fields in result
    • msql_num_rows - Get number of rows in result
    • msql_pconnect - Otwiera trwałe połączenie do serwera mSQL
    • msql_query - Send mSQL query
    • msql_regcase - Alias dla sql_regcase
    • msql_result - Get result data
    • msql_select_db - Select mSQL database
    • msql_tablename - Alias dla msql_result
    • mssql_bind - Adds a parameter to a stored procedure or a remote stored procedure
    • mssql_close - Zamyka połączenie z MS SQL Server
    • mssql_connect - Otwiera połączenie z serwerem MS SQL
    • mssql_data_seek - Moves internal row pointer
    • mssql_execute - Executes a stored procedure on a MS SQL server database
    • mssql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • mssql_fetch_assoc - Returns an associative array of the current row in the result
    • mssql_fetch_batch - Returns the next batch of records
    • mssql_fetch_field - Get field information
    • mssql_fetch_object - Fetch row as object
    • mssql_fetch_row - Get row as enumerated array
    • mssql_field_length - Get the length of a field
    • mssql_field_name - Get the name of a field
    • mssql_field_seek - Seeks to the specified field offset
    • mssql_field_type - Gets the type of a field
    • mssql_free_result - Free result memory
    • mssql_free_statement - Free statement memory
    • mssql_get_last_message - Zwraca ostatni komunikat z serwera
    • mssql_guid_string - Converts a 16 byte binary GUID to a string
    • mssql_init - Initializes a stored procedure or a remote stored procedure
    • mssql_min_error_severity - Ustawia poziom ważności zwracanych kodów błędów
    • mssql_min_message_severity - Ustawia poziom ważności zwracanych komunikatów o błędach
    • mssql_next_result - Move the internal result pointer to the next result
    • mssql_num_fields - Zwraca liczbę pól w zbiorze wynikowym
    • mssql_num_rows - Zwraca liczbę wierszy w zbiorze wynikowym
    • mssql_pconnect - Open persistent MS SQL connection
    • mssql_query - Wysyła zapytanie do serwera MS SQL
    • mssql_result - Get result data
    • mssql_rows_affected - Zwraca liczbę rekordów przetworzonych przez ostatnie zapytanie
    • mssql_select_db - Select MS SQL database
    • mt_getrandmax - Największa możliwa liczba losowa
    • mt_rand - Wygeneruj lepszą liczbę losową
    • mt_srand - Inicjuje generator Mersenne Twister
    • MultipleIterator::attachIterator - Attaches iterator information
    • MultipleIterator::containsIterator - Checks if an iterator is attached
    • MultipleIterator::countIterators - Gets the number of attached iterator instances
    • MultipleIterator::current - Gets the registered iterator instances
    • MultipleIterator::detachIterator - Detaches an iterator
    • MultipleIterator::getFlags - Gets the flag information
    • MultipleIterator::key - Gets the registered iterator instances
    • MultipleIterator::next - Moves all attached iterator instances forward
    • MultipleIterator::rewind - Rewinds all attached iterator instances
    • MultipleIterator::setFlags - Sets flags
    • MultipleIterator::valid - Checks the validity of sub iterators
    • MultipleIterator::__construct - Constructs a new MultipleIterator
    • mysqli::$affected_rows - Gets the number of affected rows in a previous MySQL operation
    • mysqli::$client_info - Returns the MySQL client version as a string
    • mysqli::$client_version - Get MySQL client info
    • mysqli::$connect_errno - Returns the error code from last connect call
    • mysqli::$connect_error - Returns a string description of the last connect error
    • mysqli::$errno - Returns the error code for the most recent function call
    • mysqli::$error - Returns a string description of the last error
    • mysqli::$field_count - Returns the number of columns for the most recent query
    • mysqli::$host_info - Returns a string representing the type of connection used
    • mysqli::$info - Retrieves information about the most recently executed query
    • mysqli::$insert_id - Returns the auto generated id used in the last query
    • mysqli::$protocol_version - Returns the version of the MySQL protocol used
    • mysqli::$server_info - Returns the version of the MySQL server
    • mysqli::$server_version - Returns the version of the MySQL server as an integer
    • mysqli::$sqlstate - Returns the SQLSTATE error from previous MySQL operation
    • mysqli::$thread_id - Returns the thread ID for the current connection
    • mysqli::$warning_count - Returns the number of warnings from the last query for the given link
    • mysqli::autocommit - Turns on or off auto-commiting database modifications
    • mysqli::change_user - Changes the user of the specified database connection
    • mysqli::character_set_name - Returns the default character set for the database connection
    • mysqli::close - Closes a previously opened database connection
    • mysqli::commit - Commits the current transaction
    • mysqli::debug - Performs debugging operations
    • mysqli::disable_reads_from_master - Disable reads from master
    • mysqli::dump_debug_info - Dump debugging information into the log
    • mysqli::get_charset - Returns a character set object
    • mysqli::get_client_info - Returns the MySQL client version as a string
    • mysqli::get_connection_stats - Returns statistics about the client connection
    • mysqli::get_warnings - Get result of SHOW WARNINGS
    • mysqli::init - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
    • mysqli::kill - Asks the server to kill a MySQL thread
    • mysqli::more_results - Check if there are any more query results from a multi query
    • mysqli::multi_query - Performs a query on the database
    • mysqli::next_result - Prepare next result from multi_query
    • mysqli::options - Set options
    • mysqli::ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • mysqli::poll - Poll connections
    • mysqli::prepare - Prepare an SQL statement for execution
    • mysqli::query - Performs a query on the database
    • mysqli::real_connect - Opens a connection to a mysql server
    • mysqli::real_escape_string - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • mysqli::real_query - Execute an SQL query
    • mysqli::reap_async_query - Get result from async query
    • mysqli::refresh - Refreshes
    • mysqli::rollback - Rolls back current transaction
    • mysqli::rpl_query_type - Returns RPL query type
    • mysqli::select_db - Selects the default database for database queries
    • mysqli::send_query - Send the query and return
    • mysqli::set_charset - Sets the default client character set
    • mysqli::set_local_infile_default - Unsets user defined handler for load local infile command
    • mysqli::set_local_infile_handler - Set callback function for LOAD DATA LOCAL INFILE command
    • mysqli::ssl_set - Used for establishing secure connections using SSL
    • mysqli::stat - Gets the current system status
    • mysqli::stmt_init - Initializes a statement and returns an object for use with mysqli_stmt_prepare
    • mysqli::store_result - Transfers a result set from the last query
    • mysqli::thread_safe - Returns whether thread safety is given or not
    • mysqli::use_result - Initiate a result set retrieval
    • mysqli::__construct - Open a new connection to the MySQL server
    • mysqli_bind_param - Alias for mysqli_stmt_bind_param
    • mysqli_bind_result - Alias for mysqli_stmt_bind_result
    • mysqli_client_encoding - Alias of mysqli_character_set_name
    • mysqli_connect - Alias dla mysqli::__construct
    • mysqli_disable_rpl_parse - Disable RPL parse
    • mysqli_driver::embedded_server_end - Stop embedded server
    • mysqli_driver::embedded_server_start - Initialize and start embedded server
    • mysqli_enable_reads_from_master - Enable reads from master
    • mysqli_enable_rpl_parse - Enable RPL parse
    • mysqli_escape_string - Alias dla mysqli_real_escape_string
    • mysqli_execute - Alias for mysqli_stmt_execute
    • mysqli_fetch - Alias for mysqli_stmt_fetch
    • mysqli_get_cache_stats - Returns client Zval cache statistics
    • mysqli_get_client_stats - Returns client per-process statistics
    • mysqli_get_metadata - Alias for mysqli_stmt_result_metadata
    • mysqli_master_query - Enforce execution of a query on the master in a master/slave setup
    • mysqli_param_count - Alias for mysqli_stmt_param_count
    • mysqli_report - Enables or disables internal report functions
    • mysqli_result::$current_field - Get current field offset of a result pointer
    • mysqli_result::$field_count - Get the number of fields in a result
    • mysqli_result::$lengths - Returns the lengths of the columns of the current row in the result set
    • mysqli_result::$num_rows - Gets the number of rows in a result
    • mysqli_result::data_seek - Adjusts the result pointer to an arbitary row in the result
    • mysqli_result::fetch_all - Fetches all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array - Fetch a result row as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc - Fetch a result row as an associative array
    • mysqli_result::fetch_field - Returns the next field in the result set
    • mysqli_result::fetch_fields - Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_field_direct - Fetch meta-data for a single field
    • mysqli_result::fetch_object - Returns the current row of a result set as an object
    • mysqli_result::fetch_row - Get a result row as an enumerated array
    • mysqli_result::field_seek - Set result pointer to a specified field offset
    • mysqli_result::free - Frees the memory associated with a result
    • mysqli_rpl_parse_enabled - Check if RPL parse is enabled
    • mysqli_rpl_probe - RPL probe
    • mysqli_send_long_data - Alias for mysqli_stmt_send_long_data
    • mysqli_set_opt - Alias of mysqli_options
    • mysqli_slave_query - Force execution of a query on a slave in a master/slave setup
    • mysqli_stmt::$affected_rows - Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • mysqli_stmt::$errno - Returns the error code for the most recent statement call
    • mysqli_stmt::$error - Returns a string description for last statement error
    • mysqli_stmt::$field_count - Returns the number of field in the given statement
    • mysqli_stmt::$insert_id - Get the ID generated from the previous INSERT operation
    • mysqli_stmt::$num_rows - Return the number of rows in statements result set
    • mysqli_stmt::$param_count - Returns the number of parameter for the given statement
    • mysqli_stmt::$sqlstate - Returns SQLSTATE error from previous statement operation
    • mysqli_stmt::attr_get - Used to get the current value of a statement attribute
    • mysqli_stmt::attr_set - Used to modify the behavior of a prepared statement
    • mysqli_stmt::bind_param - Binds variables to a prepared statement as parameters
    • mysqli_stmt::bind_result - Binds variables to a prepared statement for result storage
    • mysqli_stmt::close - Closes a prepared statement
    • mysqli_stmt::data_seek - Seeks to an arbitrary row in statement result set
    • mysqli_stmt::execute - Executes a prepared Query
    • mysqli_stmt::fetch - Fetch results from a prepared statement into the bound variables
    • mysqli_stmt::free_result - Frees stored result memory for the given statement handle
    • mysqli_stmt::get_result - Gets a result set from a prepared statement
    • mysqli_stmt::get_warnings - Get result of SHOW WARNINGS
    • mysqli_stmt::prepare - Prepare an SQL statement for execution
    • mysqli_stmt::reset - Resets a prepared statement
    • mysqli_stmt::result_metadata - Returns result set metadata from a prepared statement
    • mysqli_stmt::send_long_data - Send data in blocks
    • mysqli_stmt::store_result - Transfers a result set from a prepared statement
    • mysqli_warning::next - The next purpose
    • mysqli_warning::__construct - The __construct purpose
    • MysqlndUhConnection::changeUser - Changes the user of the specified mysqlnd database connection
    • MysqlndUhConnection::charsetName - Returns the default character set for the database connection
    • MysqlndUhConnection::close - Closes a previously opened database connection
    • MysqlndUhConnection::connect - Open a new connection to the MySQL server
    • MysqlndUhConnection::endPSession - End a persistent connection
    • MysqlndUhConnection::escapeString - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • MysqlndUhConnection::getAffectedRows - Gets the number of affected rows in a previous MySQL operation
    • MysqlndUhConnection::getErrorNumber - Returns the error code for the most recent function call
    • MysqlndUhConnection::getErrorString - Returns a string description of the last error
    • MysqlndUhConnection::getFieldCount - Returns the number of columns for the most recent query
    • MysqlndUhConnection::getHostInformation - Returns a string representing the type of connection used
    • MysqlndUhConnection::getLastInsertId - Returns the auto generated id used in the last query.
    • MysqlndUhConnection::getLastMessage - Retrieves information about the most recently executed query
    • MysqlndUhConnection::getProtocolInformation - Returns the version of the MySQL protocol used
    • MysqlndUhConnection::getServerInformation - Returns the version of the MySQL server
    • MysqlndUhConnection::getServerStatistics - Gets the current system status
    • MysqlndUhConnection::getServerVersion - Returns the version of the MySQL server as an integer
    • MysqlndUhConnection::getSqlstate - Returns the SQLSTATE error from previous MySQL operation
    • MysqlndUhConnection::getStatistics - Returns statistics about the client connection.
    • MysqlndUhConnection::getThreadId - Returns the thread ID for the current connection
    • MysqlndUhConnection::getWarningCount - Returns the number of warnings from the last query for the given link
    • MysqlndUhConnection::init - Initialize mysqlnd connection
    • MysqlndUhConnection::killConnection - Asks the server to kill a MySQL thread
    • MysqlndUhConnection::listFields - List MySQL table fields
    • MysqlndUhConnection::listMethod - Wrapper for assorted list commands
    • MysqlndUhConnection::moreResults - Check if there are any more query results from a multi query
    • MysqlndUhConnection::nextResult - Prepare next result from multi_query
    • MysqlndUhConnection::ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • MysqlndUhConnection::query - Performs a query on the database
    • MysqlndUhConnection::queryReadResultsetHeader - Read a result set header
    • MysqlndUhConnection::reapQuery - Get result from async query
    • MysqlndUhConnection::refreshServer - Flush or reset tables and caches
    • MysqlndUhConnection::restartPSession - Restart a persistent mysqlnd connection
    • MysqlndUhConnection::selectDb - Selects the default database for database queries
    • MysqlndUhConnection::sendClose - Sends a close command to MySQL
    • MysqlndUhConnection::sendQuery - Sends a query to MySQL
    • MysqlndUhConnection::serverDumpDebugInformation - Dump debugging information into the log for the MySQL server
    • MysqlndUhConnection::setAutocommit - Turns on or off auto-commiting database modifications
    • MysqlndUhConnection::setCharset - Sets the default client character set
    • MysqlndUhConnection::setClientOption - Sets a client option
    • MysqlndUhConnection::setServerOption - Sets a server option
    • MysqlndUhConnection::shutdownServer - The shutdownServer purpose
    • MysqlndUhConnection::simpleCommand - Sends a basic COM_* command
    • MysqlndUhConnection::simpleCommandHandleResponse - Process a response for a basic COM_* command send to the client
    • MysqlndUhConnection::sslSet - Used for establishing secure connections using SSL
    • MysqlndUhConnection::stmtInit - Initializes a statement and returns a resource for use with mysqli_statement::prepare
    • MysqlndUhConnection::storeResult - Transfers a result set from the last query
    • MysqlndUhConnection::txCommit - Commits the current transaction
    • MysqlndUhConnection::txRollback - Rolls back current transaction
    • MysqlndUhConnection::useResult - Initiate a result set retrieval
    • MysqlndUhConnection::__construct - The __construct purpose
    • MysqlndUhPreparedStatement::execute - Executes a prepared Query
    • MysqlndUhPreparedStatement::prepare - Prepare an SQL statement for execution
    • MysqlndUhPreparedStatement::__construct - The __construct purpose
    • mysqlnd_ms_get_last_gtid - Returns the latest global transaction ID
    • mysqlnd_ms_get_last_used_connection - Returns an array which describes the last used connection
    • mysqlnd_ms_get_stats - Returns query distribution and connection statistics
    • mysqlnd_ms_match_wild - Finds whether a table name matches a wildcard pattern or not
    • mysqlnd_ms_query_is_select - Find whether to send the query to the master, the slave or the last used MySQL server
    • mysqlnd_ms_set_qos - Sets the quality of service needed from the cluster
    • mysqlnd_ms_set_user_pick_server - Sets a callback for user-defined read/write splitting
    • mysqlnd_qc_clear_cache - Flush all cache contents
    • mysqlnd_qc_get_available_handlers - Returns a list of available storage handler
    • mysqlnd_qc_get_cache_info - Returns information on the current handler, the number of cache entries and cache entries, if available
    • mysqlnd_qc_get_core_stats - Statistics collected by the core of the query cache
    • mysqlnd_qc_get_normalized_query_trace_log - Returns a normalized query trace log for each query inspected by the query cache
    • mysqlnd_qc_get_query_trace_log - Returns a backtrace for each query inspected by the query cache
    • mysqlnd_qc_set_is_select - Installs a callback which decides whether a statement is cached
    • mysqlnd_qc_set_storage_handler - Change current storage handler
    • mysqlnd_qc_set_user_handlers - Sets the callback functions for a user-defined procedural storage handler
    • mysqlnd_uh_convert_to_mysqlnd - Converts a MySQL connection handle into a mysqlnd connection handle
    • mysqlnd_uh_set_connection_proxy - Installs a proxy for mysqlnd connections
    • mysqlnd_uh_set_statement_proxy - Installs a proxy for mysqlnd statements
    • mysql_affected_rows - Zwraca liczbę wierszy przetworzonych w poprzedniej operacji MySQL
    • mysql_client_encoding - Zwraca nazwę zestawu znaków
    • mysql_close - Zamyka połączenie MySQL
    • mysql_connect - Otwiera połączenie do serwera MySQL
    • mysql_create_db - Tworzy bazę MySQL
    • mysql_data_seek - Przesuwa wewnętrzny wskaźnik wyniku
    • mysql_db_name - Pobiera dane wynikowe
    • mysql_db_query - Wybiera bazę danych MySQL i wykonuje na niej zapytanie
    • mysql_drop_db - Usuwa bazę MySQL
    • mysql_errno - Zwraca liczbową wartość kodu błędu z poprzedniej operacji MySQL
    • mysql_error - Zwraca tekst komunikatu błędu z ostatniej operacji MySQL
    • mysql_escape_string - Dodaje znaki unikowe na użytek mysql_query
    • mysql_fetch_array - Zapisuje wiersz wyniku w tablicy asocjacyjnej, numerycznej lub w obu
    • mysql_fetch_assoc - Zapisuje wiersz wyniku w tablicy asocjacyjnej
    • mysql_fetch_field - Pobiera z wyniku informacje o kolumnie i zwraca jako obiekt
    • mysql_fetch_lengths - Pobiera długość każdego pola w wierszu wyniku
    • mysql_fetch_object - Zapisuje wiersz wyniku jako obiekt
    • mysql_fetch_row - Zapisuje wiersz wyniku w tablicy wyliczeniowej
    • mysql_field_flags - Pobiera flagi dla danego pola w wyniku
    • mysql_field_len - Zwraca długość danego pola
    • mysql_field_name - Podaje nazwę danego pola w wyniku
    • mysql_field_seek - Przesuwa wskaźnik wyniku do wybranego pola
    • mysql_field_table - Pobiera nazwę tabeli w której znajduje się dane pole
    • mysql_field_type - Pobiera typ podanego pola
    • mysql_free_result - Zwalnia pamięć zajmowaną przez wynik
    • mysql_get_client_info - Pobiera informacje o kliencie MySQL
    • mysql_get_host_info - Pobiera informacje o hoście MySQL
    • mysql_get_proto_info - Pobiera informacje o protokole MySQL
    • mysql_get_server_info - Pobiera informacje o serwerze MySQL
    • mysql_info - Pobiera informacje o ostatnim zapytaniu
    • mysql_insert_id - Podaje numer ID wygenerowany podczas ostatniej operacji INSERT
    • mysql_list_dbs - Pobiera nazwy baz dostępnych na serwerze MySQL
    • mysql_list_fields - Pobiera informacje o polach tabeli MySQL
    • mysql_list_processes - Zwraca listę procesów MySQL
    • mysql_list_tables - Pobiera listę tabel z bazy MySQL
    • mysql_num_fields - Zwraca liczbę pól w wyniku
    • mysql_num_rows - Zwraca liczbę wierszy w wyniku
    • mysql_pconnect - Otwiera stałe połączenie z serwerem MySQL
    • mysql_ping - Sprawdza połączenie z serwerem, lub nawiązuje połączenie, jeśli go nie było
    • mysql_query - Wysyła zapytanie do serwera MySQL
    • mysql_real_escape_string - Dodaje znaki unikowe w łańcuchu znaków do użycia w instrukcji SQL
    • mysql_result - Zwraca dane wynikowe
    • mysql_select_db - Wybiera bazę MySQL
    • mysql_set_charset - Sets the client character set
    • mysql_stat - Pobiera aktualny stan systemu
    • mysql_tablename - Zwraca nazwę tabeli
    • mysql_thread_id - Zwraca id bieżącego wątku
    • mysql_unbuffered_query - Wysyła zapytanie do serwera MySQL nie pobierając i nie buforując wyniku
    • m_checkstatus - Check to see if a transaction has completed
    • m_completeauthorizations - Number of complete authorizations in queue, returning an array of their identifiers
    • m_connect - Establish the connection to MCVE
    • m_connectionerror - Get a textual representation of why a connection failed
    • m_deletetrans - Delete specified transaction from MCVE_CONN structure
    • m_destroyconn - Destroy the connection and MCVE_CONN structure
    • m_destroyengine - Free memory associated with IP/SSL connectivity
    • m_getcell - Get a specific cell from a comma delimited response by column name
    • m_getcellbynum - Get a specific cell from a comma delimited response by column number
    • m_getcommadelimited - Get the RAW comma delimited data returned from MCVE
    • m_getheader - Get the name of the column in a comma-delimited response
    • m_initconn - Create and initialize an MCVE_CONN structure
    • m_initengine - Ready the client for IP/SSL Communication
    • m_iscommadelimited - Checks to see if response is comma delimited
    • m_maxconntimeout - The maximum amount of time the API will attempt a connection to MCVE
    • m_monitor - Perform communication with MCVE (send/receive data) Non-blocking
    • m_numcolumns - Number of columns returned in a comma delimited response
    • m_numrows - Number of rows returned in a comma delimited response
    • m_parsecommadelimited - Parse the comma delimited response so m_getcell, etc will work
    • m_responsekeys - Returns array of strings which represents the keys that can be used for response parameters on this transaction
    • m_responseparam - Get a custom response parameter
    • m_returnstatus - Check to see if the transaction was successful
    • m_setblocking - Set blocking/non-blocking mode for connection
    • m_setdropfile - Set the connection method to Drop-File
    • m_setip - Set the connection method to IP
    • m_setssl - Set the connection method to SSL
    • m_setssl_cafile - Set SSL CA (Certificate Authority) file for verification of server certificate
    • m_setssl_files - Set certificate key files and certificates if server requires client certificate verification
    • m_settimeout - Set maximum transaction time (per trans)
    • m_sslcert_gen_hash - Generate hash for SSL client certificate verification
    • m_transactionssent - Check to see if outgoing buffer is clear
    • m_transinqueue - Number of transactions in client-queue
    • m_transkeyval - Add key/value pair to a transaction. Replaces deprecated transparam()
    • m_transnew - Start a new transaction
    • m_transsend - Finalize and send the transaction
    • m_uwait - Wait x microsecs
    • m_validateidentifier - Whether or not to validate the passed identifier on any transaction it is passed to
    • m_verifyconnection - Set whether or not to PING upon connect to verify connection
    • m_verifysslcert - Set whether or not to verify the server ssl certificate
  • n
    • natcasesort - Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego wielkość znaków
    • natsort - Sortuj tablicę używając algortmu "porządek naturalny"
    • ncurses_addch - Add character at current position and advance cursor
    • ncurses_addchnstr - Add attributed string with specified length at current position
    • ncurses_addchstr - Add attributed string at current position
    • ncurses_addnstr - Add string with specified length at current position
    • ncurses_addstr - Output text at current position
    • ncurses_assume_default_colors - Define default colors for color 0
    • ncurses_attroff - Turn off the given attributes
    • ncurses_attron - Turn on the given attributes
    • ncurses_attrset - Set given attributes
    • ncurses_baudrate - Returns baudrate of terminal
    • ncurses_beep - Let the terminal beep
    • ncurses_bkgd - Set background property for terminal screen
    • ncurses_bkgdset - Control screen background
    • ncurses_border - Draw a border around the screen using attributed characters
    • ncurses_bottom_panel - Moves a visible panel to the bottom of the stack
    • ncurses_can_change_color - Checks if terminal color definitions can be changed
    • ncurses_cbreak - Switch of input buffering
    • ncurses_clear - Clear screen
    • ncurses_clrtobot - Clear screen from current position to bottom
    • ncurses_clrtoeol - Clear screen from current position to end of line
    • ncurses_color_content - Retrieves RGB components of a color
    • ncurses_color_set - Set active foreground and background colors
    • ncurses_curs_set - Set cursor state
    • ncurses_define_key - Define a keycode
    • ncurses_def_prog_mode - Saves terminals (program) mode
    • ncurses_def_shell_mode - Saves terminals (shell) mode
    • ncurses_delay_output - Delay output on terminal using padding characters
    • ncurses_delch - Delete character at current position, move rest of line left
    • ncurses_deleteln - Delete line at current position, move rest of screen up
    • ncurses_delwin - Delete a ncurses window
    • ncurses_del_panel - Remove panel from the stack and delete it (but not the associated window)
    • ncurses_doupdate - Write all prepared refreshes to terminal
    • ncurses_echo - Activate keyboard input echo
    • ncurses_echochar - Single character output including refresh
    • ncurses_end - Stop using ncurses, clean up the screen
    • ncurses_erase - Erase terminal screen
    • ncurses_erasechar - Returns current erase character
    • ncurses_filter - Set LINES for iniscr() and newterm() to 1
    • ncurses_flash - Flash terminal screen (visual bell)
    • ncurses_flushinp - Flush keyboard input buffer
    • ncurses_getch - Read a character from keyboard
    • ncurses_getmaxyx - Returns the size of a window
    • ncurses_getmouse - Reads mouse event
    • ncurses_getyx - Returns the current cursor position for a window
    • ncurses_halfdelay - Put terminal into halfdelay mode
    • ncurses_has_colors - Checks if terminal has color capabilities
    • ncurses_has_ic - Check for insert- and delete-capabilities
    • ncurses_has_il - Check for line insert- and delete-capabilities
    • ncurses_has_key - Check for presence of a function key on terminal keyboard
    • ncurses_hide_panel - Remove panel from the stack, making it invisible
    • ncurses_hline - Draw a horizontal line at current position using an attributed character and max. n characters long
    • ncurses_inch - Get character and attribute at current position
    • ncurses_init - Initialize ncurses
    • ncurses_init_color - Define a terminal color
    • ncurses_init_pair - Define a color pair
    • ncurses_insch - Insert character moving rest of line including character at current position
    • ncurses_insdelln - Insert lines before current line scrolling down (negative numbers delete and scroll up)
    • ncurses_insertln - Insert a line, move rest of screen down
    • ncurses_insstr - Insert string at current position, moving rest of line right
    • ncurses_instr - Reads string from terminal screen
    • ncurses_isendwin - Ncurses is in endwin mode, normal screen output may be performed
    • ncurses_keyok - Enable or disable a keycode
    • ncurses_keypad - Turns keypad on or off
    • ncurses_killchar - Returns current line kill character
    • ncurses_longname - Returns terminals description
    • ncurses_meta - Enables/Disable 8-bit meta key information
    • ncurses_mouseinterval - Set timeout for mouse button clicks
    • ncurses_mousemask - Sets mouse options
    • ncurses_mouse_trafo - Transforms coordinates
    • ncurses_move - Move output position
    • ncurses_move_panel - Moves a panel so that its upper-left corner is at [startx, starty]
    • ncurses_mvaddch - Move current position and add character
    • ncurses_mvaddchnstr - Move position and add attributed string with specified length
    • ncurses_mvaddchstr - Move position and add attributed string
    • ncurses_mvaddnstr - Move position and add string with specified length
    • ncurses_mvaddstr - Move position and add string
    • ncurses_mvcur - Move cursor immediately
    • ncurses_mvdelch - Move position and delete character, shift rest of line left
    • ncurses_mvgetch - Move position and get character at new position
    • ncurses_mvhline - Set new position and draw a horizontal line using an attributed character and max. n characters long
    • ncurses_mvinch - Move position and get attributed character at new position
    • ncurses_mvvline - Set new position and draw a vertical line using an attributed character and max. n characters long
    • ncurses_mvwaddstr - Add string at new position in window
    • ncurses_napms - Sleep
    • ncurses_newpad - Creates a new pad (window)
    • ncurses_newwin - Create a new window
    • ncurses_new_panel - Create a new panel and associate it with window
    • ncurses_nl - Translate newline and carriage return / line feed
    • ncurses_nocbreak - Switch terminal to cooked mode
    • ncurses_noecho - Switch off keyboard input echo
    • ncurses_nonl - Do not translate newline and carriage return / line feed
    • ncurses_noqiflush - Do not flush on signal characters
    • ncurses_noraw - Switch terminal out of raw mode
    • ncurses_pair_content - Retrieves foreground and background colors of a color pair
    • ncurses_panel_above - Returns the panel above panel
    • ncurses_panel_below - Returns the panel below panel
    • ncurses_panel_window - Returns the window associated with panel
    • ncurses_pnoutrefresh - Copies a region from a pad into the virtual screen
    • ncurses_prefresh - Copies a region from a pad into the virtual screen
    • ncurses_putp - Apply padding information to the string and output it
    • ncurses_qiflush - Flush on signal characters
    • ncurses_raw - Switch terminal into raw mode
    • ncurses_refresh - Refresh screen
    • ncurses_replace_panel - Replaces the window associated with panel
    • ncurses_resetty - Restores saved terminal state
    • ncurses_reset_prog_mode - Resets the prog mode saved by def_prog_mode
    • ncurses_reset_shell_mode - Resets the shell mode saved by def_shell_mode
    • ncurses_savetty - Saves terminal state
    • ncurses_scrl - Scroll window content up or down without changing current position
    • ncurses_scr_dump - Dump screen content to file
    • ncurses_scr_init - Initialize screen from file dump
    • ncurses_scr_restore - Restore screen from file dump
    • ncurses_scr_set - Inherit screen from file dump
    • ncurses_show_panel - Places an invisible panel on top of the stack, making it visible
    • ncurses_slk_attr - Returns current soft label key attribute
    • ncurses_slk_attroff - Turn off the given attributes for soft function-key labels
    • ncurses_slk_attron - Turn on the given attributes for soft function-key labels
    • ncurses_slk_attrset - Set given attributes for soft function-key labels
    • ncurses_slk_clear - Clears soft labels from screen
    • ncurses_slk_color - Sets color for soft label keys
    • ncurses_slk_init - Initializes soft label key functions
    • ncurses_slk_noutrefresh - Copies soft label keys to virtual screen
    • ncurses_slk_refresh - Copies soft label keys to screen
    • ncurses_slk_restore - Restores soft label keys
    • ncurses_slk_set - Sets function key labels
    • ncurses_slk_touch - Forces output when ncurses_slk_noutrefresh is performed
    • ncurses_standend - Stop using 'standout' attribute
    • ncurses_standout - Start using 'standout' attribute
    • ncurses_start_color - Initializes color functionality
    • ncurses_termattrs - Returns a logical OR of all attribute flags supported by terminal
    • ncurses_termname - Returns terminals (short)-name
    • ncurses_timeout - Set timeout for special key sequences
    • ncurses_top_panel - Moves a visible panel to the top of the stack
    • ncurses_typeahead - Specify different filedescriptor for typeahead checking
    • ncurses_ungetch - Put a character back into the input stream
    • ncurses_ungetmouse - Pushes mouse event to queue
    • ncurses_update_panels - Refreshes the virtual screen to reflect the relations between panels in the stack
    • ncurses_use_default_colors - Assign terminal default colors to color id -1
    • ncurses_use_env - Control use of environment information about terminal size
    • ncurses_use_extended_names - Control use of extended names in terminfo descriptions
    • ncurses_vidattr - Display the string on the terminal in the video attribute mode
    • ncurses_vline - Draw a vertical line at current position using an attributed character and max. n characters long
    • ncurses_waddch - Adds character at current position in a window and advance cursor
    • ncurses_waddstr - Outputs text at current postion in window
    • ncurses_wattroff - Turns off attributes for a window
    • ncurses_wattron - Turns on attributes for a window
    • ncurses_wattrset - Set the attributes for a window
    • ncurses_wborder - Draws a border around the window using attributed characters
    • ncurses_wclear - Clears window
    • ncurses_wcolor_set - Sets windows color pairings
    • ncurses_werase - Erase window contents
    • ncurses_wgetch - Reads a character from keyboard (window)
    • ncurses_whline - Draws a horizontal line in a window at current position using an attributed character and max. n characters long
    • ncurses_wmouse_trafo - Transforms window/stdscr coordinates
    • ncurses_wmove - Moves windows output position
    • ncurses_wnoutrefresh - Copies window to virtual screen
    • ncurses_wrefresh - Refresh window on terminal screen
    • ncurses_wstandend - End standout mode for a window
    • ncurses_wstandout - Enter standout mode for a window
    • ncurses_wvline - Draws a vertical line in a window at current position using an attributed character and max. n characters long
    • newt_bell - Send a beep to the terminal
    • newt_button - Create a new button
    • newt_button_bar - This function returns a grid containing the buttons created.
    • newt_centered_window - Open a centered window of the specified size
    • newt_checkbox - Opis
    • newt_checkbox_get_value - Retreives value of checkox resource
    • newt_checkbox_set_flags - Configures checkbox resource
    • newt_checkbox_set_value - Sets the value of the checkbox
    • newt_checkbox_tree - Opis
    • newt_checkbox_tree_add_item - Adds new item to the checkbox tree
    • newt_checkbox_tree_find_item - Finds an item in the checkbox tree
    • newt_checkbox_tree_get_current - Returns checkbox tree selected item
    • newt_checkbox_tree_get_entry_value - Opis
    • newt_checkbox_tree_get_multi_selection - Opis
    • newt_checkbox_tree_get_selection - Opis
    • newt_checkbox_tree_multi - Opis
    • newt_checkbox_tree_set_current - Opis
    • newt_checkbox_tree_set_entry - Opis
    • newt_checkbox_tree_set_entry_value - Opis
    • newt_checkbox_tree_set_width - Opis
    • newt_clear_key_buffer - Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls - Opis
    • newt_compact_button - Opis
    • newt_component_add_callback - Opis
    • newt_component_takes_focus - Opis
    • newt_create_grid - Opis
    • newt_cursor_off - Opis
    • newt_cursor_on - Opis
    • newt_delay - Opis
    • newt_draw_form - Opis
    • newt_draw_root_text - Displays the string text at the position indicated
    • newt_entry - Opis
    • newt_entry_get_value - Opis
    • newt_entry_set - Opis
    • newt_entry_set_filter - Opis
    • newt_entry_set_flags - Opis
    • newt_finished - Uninitializes newt interface
    • newt_form - Create a form
    • newt_form_add_component - Adds a single component to the form
    • newt_form_add_components - Add several components to the form
    • newt_form_add_hot_key - Opis
    • newt_form_destroy - Destroys a form
    • newt_form_get_current - Opis
    • newt_form_run - Runs a form
    • newt_form_set_background - Opis
    • newt_form_set_height - Opis
    • newt_form_set_size - Opis
    • newt_form_set_timer - Opis
    • newt_form_set_width - Opis
    • newt_form_watch_fd - Opis
    • newt_get_screen_size - Fills in the passed references with the current size of the terminal
    • newt_grid_add_components_to_form - Opis
    • newt_grid_basic_window - Opis
    • newt_grid_free - Opis
    • newt_grid_get_size - Opis
    • newt_grid_h_close_stacked - Opis
    • newt_grid_h_stacked - Opis
    • newt_grid_place - Opis
    • newt_grid_set_field - Opis
    • newt_grid_simple_window - Opis
    • newt_grid_v_close_stacked - Opis
    • newt_grid_v_stacked - Opis
    • newt_grid_wrapped_window - Opis
    • newt_grid_wrapped_window_at - Opis
    • newt_init - Initialize newt
    • newt_label - Opis
    • newt_label_set_text - Opis
    • newt_listbox - Opis
    • newt_listbox_append_entry - Opis
    • newt_listbox_clear - Opis
    • newt_listbox_clear_selection - Opis
    • newt_listbox_delete_entry - Opis
    • newt_listbox_get_current - Opis
    • newt_listbox_get_selection - Opis
    • newt_listbox_insert_entry - Opis
    • newt_listbox_item_count - Opis
    • newt_listbox_select_item - Opis
    • newt_listbox_set_current - Opis
    • newt_listbox_set_current_by_key - Opis
    • newt_listbox_set_data - Opis
    • newt_listbox_set_entry - Opis
    • newt_listbox_set_width - Opis
    • newt_listitem - Opis
    • newt_listitem_get_data - Opis
    • newt_listitem_set - Opis
    • newt_open_window - Open a window of the specified size and position
    • newt_pop_help_line - Replaces the current help line with the one from the stack
    • newt_pop_window - Removes the top window from the display
    • newt_push_help_line - Saves the current help line on a stack, and displays the new line
    • newt_radiobutton - Opis
    • newt_radio_get_current - Opis
    • newt_redraw_help_line - Opis
    • newt_reflow_text - Opis
    • newt_refresh - Updates modified portions of the screen
    • newt_resize_screen - Opis
    • newt_resume - Resume using the newt interface after calling newt_suspend
    • newt_run_form - Runs a form
    • newt_scale - Opis
    • newt_scale_set - Opis
    • newt_scrollbar_set - Opis
    • newt_set_help_callback - Opis
    • newt_set_suspend_callback - Set a callback function which gets invoked when user presses the suspend key
    • newt_suspend - Tells newt to return the terminal to its initial state
    • newt_textbox - Opis
    • newt_textbox_get_num_lines - Opis
    • newt_textbox_reflowed - Opis
    • newt_textbox_set_height - Opis
    • newt_textbox_set_text - Opis
    • newt_vertical_scrollbar - Opis
    • newt_wait_for_key - Doesn't return until a key has been pressed
    • newt_win_choice - Opis
    • newt_win_entries - Opis
    • newt_win_menu - Opis
    • newt_win_message - Opis
    • newt_win_messagev - Opis
    • newt_win_ternary - Opis
    • next - Przesuń do przodu wewnętrzny wskaźnik tablicy
    • ngettext - Plural version of gettext
    • nl2br - Inserts HTML line breaks before all newlines in a string
    • nl_langinfo - Query language and locale information
    • NoRewindIterator::current - Get the current value
    • NoRewindIterator::getInnerIterator - Get the inner iterator
    • NoRewindIterator::key - Get the current key
    • NoRewindIterator::next - Forward to the next element
    • NoRewindIterator::rewind - Prevents the rewind operation on the inner iterator.
    • NoRewindIterator::valid - Validates the iterator
    • NoRewindIterator::__construct - Construct a NoRewindIterator
    • Normalizer::isNormalized - Checks if the provided string is already in the specified normalization form.
    • Normalizer::normalize - Normalizes the input provided and returns the normalized string
    • notes_body - Open the message msg_number in the specified mailbox on the specified server (leave serv
    • notes_copy_db - Copy a Lotus Notes database
    • notes_create_db - Create a Lotus Notes database
    • notes_create_note - Create a note using form form_name
    • notes_drop_db - Drop a Lotus Notes database
    • notes_find_note - Returns a note id found in database_name
    • notes_header_info - Open the message msg_number in the specified mailbox on the specified server (leave serv
    • notes_list_msgs - Returns the notes from a selected database_name
    • notes_mark_read - Mark a note_id as read for the User user_name
    • notes_mark_unread - Mark a note_id as unread for the User user_name
    • notes_nav_create - Create a navigator name, in database_name
    • notes_search - Find notes that match keywords in database_name
    • notes_unread - Returns the unread note id's for the current User user_name
    • notes_version - Get the version Lotus Notes
    • nsapi_request_headers - Fetch all HTTP request headers
    • nsapi_response_headers - Fetch all HTTP response headers
    • nsapi_virtual - Perform an NSAPI sub-request
    • nthmac - Obtain a nthmac key (needs 2 arguments)
    • NumberFormatter::create - Create a number formatter
    • NumberFormatter::format - Format a number
    • NumberFormatter::formatCurrency - Format a currency value
    • NumberFormatter::getAttribute - Get an attribute
    • NumberFormatter::getErrorCode - Get formatter's last error code.
    • NumberFormatter::getErrorMessage - Get formatter's last error message.
    • NumberFormatter::getLocale - Get formatter locale
    • NumberFormatter::getPattern - Get formatter pattern
    • NumberFormatter::getSymbol - Get a symbol value
    • NumberFormatter::getTextAttribute - Get a text attribute
    • NumberFormatter::parse - Parse a number
    • NumberFormatter::parseCurrency - Parse a currency number
    • NumberFormatter::setAttribute - Set an attribute
    • NumberFormatter::setPattern - Set formatter pattern
    • NumberFormatter::setSymbol - Set a symbol value
    • NumberFormatter::setTextAttribute - Set a text attribute
    • number_format - Formatuje liczbę według szablonu
  • o
    • OAuth::disableDebug - Turn off verbose debugging
    • OAuth::disableRedirects - Turn off redirects
    • OAuth::disableSSLChecks - Turn off SSL checks
    • OAuth::enableDebug - Turn on verbose debugging
    • OAuth::enableRedirects - Turn on redirects
    • OAuth::enableSSLChecks - Turn on SSL checks
    • OAuth::fetch - Fetch an OAuth protected resource
    • OAuth::generateSignature - Generate a signature
    • OAuth::getAccessToken - Fetch an access token
    • OAuth::getCAPath - Gets CA information
    • OAuth::getLastResponse - Get the last response
    • OAuth::getLastResponseHeaders - Get headers for last response
    • OAuth::getLastResponseInfo - Get HTTP information about the last response
    • OAuth::getRequestHeader - Generate OAuth header string signature
    • OAuth::getRequestToken - Fetch a request token
    • OAuth::setAuthType - Set authorization type
    • OAuth::setCAPath - Set CA path and info
    • OAuth::setNonce - Set the nonce for subsequent requests
    • OAuth::setRequestEngine - The setRequestEngine purpose
    • OAuth::setRSACertificate - Set the RSA certificate
    • OAuth::setSSLChecks - Tweak specific SSL checks for requests.
    • OAuth::setTimestamp - Set the timestamp
    • OAuth::setToken - Sets the token and secret
    • OAuth::setVersion - Set the OAuth version
    • OAuth::__construct - Create a new OAuth object
    • OAuth::__destruct - The destructor
    • OAuthProvider::addRequiredParameter - Add required parameters
    • OAuthProvider::callconsumerHandler - Calls the consumerNonceHandler callback
    • OAuthProvider::callTimestampNonceHandler - Calls the timestampNonceHandler callback
    • OAuthProvider::calltokenHandler - Calls the tokenNonceHandler callback
    • OAuthProvider::checkOAuthRequest - Check an oauth request
    • OAuthProvider::consumerHandler - Set the consumerHandler handler callback
    • OAuthProvider::generateToken - Generate a random token
    • OAuthProvider::is2LeggedEndpoint - is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint - Sets isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter - Remove a required parameter
    • OAuthProvider::reportProblem - Report a problem
    • OAuthProvider::setParam - Set a parameter
    • OAuthProvider::setRequestTokenPath - Set request token path
    • OAuthProvider::timestampNonceHandler - Set the timestampNonceHandler handler callback
    • OAuthProvider::tokenHandler - Set the tokenHandler handler callback
    • OAuthProvider::__construct - Constructs a new OAuthProvider object
    • oauth_get_sbs - Generate a Signature Base String
    • oauth_urlencode - Encode a URI to RFC 3986
    • ob_clean - Clean (erase) the output buffer
    • ob_deflatehandler - Deflate output handler
    • 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_etaghandler - ETag output handler
    • ob_flush - Flush (send) the output buffer
    • ob_get_clean - Get current buffer contents and delete current output buffer
    • ob_get_contents - Return the contents of the output buffer
    • ob_get_flush - Flush the output buffer, return it as a string and turn off output buffering
    • ob_get_length - Return the length of the output buffer
    • ob_get_level - Return the nesting level of the output buffering mechanism
    • ob_get_status - Get status of output buffers
    • ob_gzhandler - ob_start callback function to gzip output buffer
    • ob_iconv_handler - Konwersja kodowania znaków jako uchwyt buforu wyjścia
    • ob_implicit_flush - Turn implicit flush on/off
    • ob_inflatehandler - Inflate output handler
    • ob_list_handlers - List all output handlers in use
    • ob_start - Turn on output buffering
    • ob_tidyhandler - Funkcja zwrotna do czyszczenia bufora wyjścia dla funkcji ob_start
    • OCI-Collection::append - Appends element to the collection
    • OCI-Collection::assign - Assigns a value to the collection from another existing collection
    • OCI-Collection::assignElem - Assigns a value to the element of the collection
    • OCI-Collection::free - Frees the resources associated with the collection object
    • OCI-Collection::getElem - Returns value of the element
    • OCI-Collection::max - Returns the maximum number of elements in the collection
    • OCI-Collection::size - Returns size of the collection
    • OCI-Collection::trim - Trims elements from the end of the collection
    • OCI-Lob::append - Appends data from the large object to another large object
    • OCI-Lob::close - Closes LOB descriptor
    • OCI-Lob::eof - Tests for end-of-file on a large object's descriptor
    • OCI-Lob::erase - Erases a specified portion of the internal LOB data
    • OCI-Lob::export - Exports LOB's contents to a file
    • OCI-Lob::flush - Flushes/writes buffer of the LOB to the server
    • OCI-Lob::free - Frees resources associated with the LOB descriptor
    • OCI-Lob::getBuffering - Returns current state of buffering for the large object
    • OCI-Lob::import - Imports file data to the LOB
    • OCI-Lob::load - Returns large object's contents
    • OCI-Lob::read - Reads part of the large object
    • OCI-Lob::rewind - Moves the internal pointer to the beginning of the large object
    • OCI-Lob::save - Saves data to the large object
    • OCI-Lob::saveFile - Alias dla OCI-Lob::import
    • OCI-Lob::seek - Sets the internal pointer of the large object
    • OCI-Lob::setBuffering - Changes current state of buffering for the large object
    • OCI-Lob::size - Returns size of large object
    • OCI-Lob::tell - Returns the current position of internal pointer of large object
    • OCI-Lob::truncate - Truncates large object
    • OCI-Lob::write - Writes data to the large object
    • OCI-Lob::writeTemporary - Writes a temporary large object
    • OCI-Lob::writeToFile - Alias dla OCI-Lob::export
    • ocibindbyname - Alias dla oci_bind_by_name
    • ocicancel - Alias dla oci_cancel
    • ocicloselob - Alias dla OCI-Lob::close
    • ocicollappend - Alias dla OCI-Collection::append
    • ocicollassign - Alias dla OCI-Collection::assign
    • ocicollassignelem - Alias dla OCI-Collection::assignElem
    • ocicollgetelem - Alias dla OCI-Collection::getElem
    • ocicollmax - Alias dla OCI-Collection::max
    • ocicollsize - Alias dla OCI-Collection::size
    • ocicolltrim - Alias dla OCI-Collection::trim
    • ocicolumnisnull - Alias dla oci_field_is_null
    • ocicolumnname - Alias dla oci_field_name
    • ocicolumnprecision - Alias dla oci_field_precision
    • ocicolumnscale - Alias dla oci_field_scale
    • ocicolumnsize - Alias dla oci_field_size
    • ocicolumntype - Alias dla oci_field_type
    • ocicolumntyperaw - Alias dla oci_field_type_raw
    • ocicommit - Alias dla oci_commit
    • ocidefinebyname - Alias dla oci_define_by_name
    • ocierror - Alias dla oci_error
    • ociexecute - Alias dla oci_execute
    • ocifetch - Alias dla oci_fetch
    • ocifetchinto - Fetches the next row into an array (deprecated)
    • ocifetchstatement - Alias dla oci_fetch_all
    • ocifreecollection - Alias dla OCI-Collection::free
    • ocifreecursor - Alias dla oci_free_statement
    • ocifreedesc - Alias dla OCI-Lob::free
    • ocifreestatement - Alias dla oci_free_statement
    • ociinternaldebug - Alias dla oci_internal_debug
    • ociloadlob - Alias dla OCI-Lob::load
    • ocilogoff - Alias dla oci_close
    • ocilogon - Alias dla oci_connect
    • ocinewcollection - Alias dla oci_new_collection
    • ocinewcursor - Alias dla oci_new_cursor
    • ocinewdescriptor - Alias dla oci_new_descriptor
    • ocinlogon - Alias dla oci_new_connect
    • ocinumcols - Alias dla oci_num_fields
    • ociparse - Alias dla oci_parse
    • ociplogon - Alias dla oci_pconnect
    • ociresult - Alias dla oci_result
    • ocirollback - Alias dla oci_rollback
    • ocirowcount - Alias dla oci_num_rows
    • ocisavelob - Alias dla OCI-Lob::save
    • ocisavelobfile - Alias dla OCI-Lob::import
    • ociserverversion - Alias dla oci_server_version
    • ocisetprefetch - Alias dla oci_set_prefetch
    • ocistatementtype - Alias dla oci_statement_type
    • ociwritelobtofile - Alias dla OCI-Lob::export
    • ociwritetemporarylob - Alias dla OCI-Lob::writeTemporary
    • oci_bind_array_by_name - Binds a PHP array to an Oracle PL/SQL array parameter
    • oci_bind_by_name - Binds a PHP variable to an Oracle placeholder
    • oci_cancel - Anuluje odczytywanie z kursora
    • oci_client_version - Returns the Oracle client library version
    • oci_close - Closes an Oracle connection
    • oci_commit - Commits the outstanding database transaction
    • oci_connect - Connect to an Oracle database
    • oci_define_by_name - Associates a PHP variable with a column for query fetches
    • oci_error - Returns the last error found
    • oci_execute - Executes a statement
    • oci_fetch - Fetches the next row from a query into internal buffers
    • oci_fetch_all - Fetches multiple rows from a query into a two-dimensional array
    • oci_fetch_array - Returns the next row from a query as an associative or numeric array
    • oci_fetch_assoc - Returns the next row from a query as an associative array
    • oci_fetch_object - Returns the next row from a query as an object
    • oci_fetch_row - Returns the next row from a query as a numeric array
    • oci_field_is_null - Checks if the field is NULL
    • oci_field_name - Returns the name of a field from the statement
    • oci_field_precision - Tell the precision of a field
    • oci_field_scale - Tell the scale of the field
    • oci_field_size - Returns field's size
    • oci_field_type - Returns field's data type
    • oci_field_type_raw - Tell the raw Oracle data type of the field
    • oci_free_statement - Frees all resources associated with statement or cursor
    • oci_internal_debug - Enables or disables internal debug output
    • oci_lob_copy - Copies large object
    • oci_lob_is_equal - Compares two LOB/FILE locators for equality
    • oci_new_collection - Allocates new collection object
    • oci_new_connect - Connect to the Oracle server using a unique connection
    • oci_new_cursor - Allocates and returns a new cursor (statement handle)
    • oci_new_descriptor - Initializes a new empty LOB or FILE descriptor
    • oci_num_fields - Returns the number of result columns in a statement
    • oci_num_rows - Returns number of rows affected during statement execution
    • oci_parse - Prepares an Oracle statement for execution
    • oci_password_change - Changes password of Oracle's user
    • oci_pconnect - Connect to an Oracle database using a persistent connection
    • oci_result - Returns field's value from the fetched row
    • oci_rollback - Rolls back the outstanding database transaction
    • oci_server_version - Returns the Oracle Database version
    • oci_set_action - Sets the action name
    • oci_set_client_identifier - Sets the client identifier
    • oci_set_client_info - Sets the client information
    • oci_set_edition - Sets the database edition
    • oci_set_module_name - Sets the module name
    • oci_set_prefetch - Sets number of rows to be prefetched by queries
    • oci_statement_type - Returns the type of a statement
    • octdec - Konwersja liczby ósemkowej do dziesiętnej
    • odbc_autocommit - Toggle autocommit behaviour
    • odbc_binmode - Handling of binary column data
    • odbc_close - Close an ODBC connection
    • odbc_close_all - Close all ODBC connections
    • odbc_columnprivileges - Lists columns and associated privileges for the given table
    • odbc_columns - Lists the column names in specified tables
    • odbc_commit - Commit an ODBC transaction
    • odbc_connect - Connect to a datasource
    • odbc_cursor - Get cursorname
    • odbc_data_source - Returns information about a current connection
    • odbc_do - Alias dla odbc_exec
    • odbc_error - Get the last error code
    • odbc_errormsg - Get the last error message
    • odbc_exec - Prepare and execute an SQL statement
    • odbc_execute - Execute a prepared statement
    • odbc_fetch_array - Fetch a result row as an associative array
    • odbc_fetch_into - Fetch one result row into array
    • odbc_fetch_object - Fetch a result row as an object
    • odbc_fetch_row - Fetch a row
    • odbc_field_len - Get the length (precision) of a field
    • odbc_field_name - Get the columnname
    • odbc_field_num - Return column number
    • odbc_field_precision - Alias dla odbc_field_len
    • odbc_field_scale - Get the scale of a field
    • odbc_field_type - Datatype of a field
    • odbc_foreignkeys - Retrieves a list of foreign keys
    • odbc_free_result - Free resources associated with a result
    • odbc_gettypeinfo - Retrieves information about data types supported by the data source
    • odbc_longreadlen - Handling of LONG columns
    • odbc_next_result - Checks if multiple results are available
    • odbc_num_fields - Number of columns in a result
    • odbc_num_rows - Number of rows in a result
    • odbc_pconnect - Open a persistent database connection
    • odbc_prepare - Prepares a statement for execution
    • odbc_primarykeys - Gets the primary keys for a table
    • odbc_procedurecolumns - Retrieve information about parameters to procedures
    • odbc_procedures - Get the list of procedures stored in a specific data source
    • odbc_result - Get result data
    • odbc_result_all - Print result as HTML table
    • odbc_rollback - Rollback a transaction
    • odbc_setoption - Adjust ODBC settings
    • odbc_specialcolumns - Retrieves special columns
    • odbc_statistics - Retrieve statistics about a table
    • odbc_tableprivileges - Lists tables and the privileges associated with each table
    • odbc_tables - Get the list of table names stored in a specific data source
    • ogg:// - Audio streams
    • openal_buffer_create - Generate OpenAL buffer
    • openal_buffer_data - Load a buffer with data
    • openal_buffer_destroy - Destroys an OpenAL buffer
    • openal_buffer_get - Retrieve an OpenAL buffer property
    • openal_buffer_loadwav - Load a .wav file into a buffer
    • openal_context_create - Create an audio processing context
    • openal_context_current - Make the specified context current
    • openal_context_destroy - Destroys a context
    • openal_context_process - Process the specified context
    • openal_context_suspend - Suspend the specified context
    • openal_device_close - Close an OpenAL device
    • openal_device_open - Initialize the OpenAL audio layer
    • openal_listener_get - Retrieve a listener property
    • openal_listener_set - Set a listener property
    • openal_source_create - Generate a source resource
    • openal_source_destroy - Destroy a source resource
    • openal_source_get - Retrieve an OpenAL source property
    • openal_source_pause - Pause the source
    • openal_source_play - Start playing the source
    • openal_source_rewind - Rewind the source
    • openal_source_set - Set source property
    • openal_source_stop - Stop playing the source
    • openal_stream - Begin streaming on a source
    • opendir - Otwiera katalog
    • openlog - Open connection to system logger
    • openssl_cipher_iv_length - Gets the cipher iv length
    • openssl_csr_export - Exports a CSR as a string
    • openssl_csr_export_to_file - Exports a CSR to a file
    • openssl_csr_get_public_key - Returns the public key of a CERT
    • openssl_csr_get_subject - Returns the subject of a CERT
    • openssl_csr_new - Generates a CSR
    • openssl_csr_sign - Sign a CSR with another certificate (or itself) and generate a certificate
    • openssl_decrypt - Decrypts data
    • openssl_dh_compute_key - Computes shared secret for public value of remote DH key and local DH key
    • openssl_digest - Computes a digest
    • openssl_encrypt - Encrypts data
    • openssl_error_string - Return openSSL error message
    • openssl_free_key - Free key resource
    • openssl_get_cipher_methods - Gets available cipher methods
    • openssl_get_md_methods - Gets available digest methods
    • openssl_get_privatekey - Alias dla openssl_pkey_get_private
    • openssl_get_publickey - Alias dla openssl_pkey_get_public
    • openssl_open - Open sealed data
    • openssl_pkcs7_decrypt - Decrypts an S/MIME encrypted message
    • openssl_pkcs7_encrypt - Encrypt an S/MIME message
    • openssl_pkcs7_sign - Sign an S/MIME message
    • openssl_pkcs7_verify - Verifies the signature of an S/MIME signed message
    • openssl_pkcs12_export - Exports a PKCS#12 Compatible Certificate Store File to variable.
    • openssl_pkcs12_export_to_file - Exports a PKCS#12 Compatible Certificate Store File
    • openssl_pkcs12_read - Parse a PKCS#12 Certificate Store into an array
    • openssl_pkey_export - Gets an exportable representation of a key into a string
    • openssl_pkey_export_to_file - Gets an exportable representation of a key into a file
    • openssl_pkey_free - Frees a private key
    • openssl_pkey_get_details - Returns an array with the key details
    • openssl_pkey_get_private - Get a private key
    • openssl_pkey_get_public - Extract public key from certificate and prepare it for use
    • openssl_pkey_new - Generates a new private key
    • openssl_private_decrypt - Decrypts data with private key
    • openssl_private_encrypt - Encrypts data with private key
    • openssl_public_decrypt - Decrypts data with public key
    • openssl_public_encrypt - Encrypts data with public key
    • openssl_random_pseudo_bytes - Generate a pseudo-random string of bytes
    • openssl_seal - Seal (encrypt) data
    • openssl_sign - Generate signature
    • openssl_verify - Verify signature
    • openssl_x509_checkpurpose - Verifies if a certificate can be used for a particular purpose
    • openssl_x509_check_private_key - Checks if a private key corresponds to a certificate
    • openssl_x509_export - Exports a certificate as a string
    • openssl_x509_export_to_file - Exports a certificate to file
    • openssl_x509_free - Free certificate resource
    • openssl_x509_parse - Parse an X509 certificate and return the information as an array
    • openssl_x509_read - Parse an X.509 certificate and return a resource identifier for it
    • ord - Return ASCII value of character
    • OuterIterator::getInnerIterator - Returns the inner iterator for the current entry.
    • output_add_rewrite_var - Add URL rewriter values
    • output_reset_rewrite_vars - Reset URL rewriter values
    • overload - Umożliwienie przeciążania właściwości i wołania metod dla klasy
    • override_function - Overrides built-in functions
    • ovrimos_close - Zamyka połączenie z serwerem Ovrimos
    • ovrimos_commit - Potwierdza transakcję
    • ovrimos_connect - Otwiera połączenie z określoną bazą danych
    • ovrimos_cursor - Zwraca nazwę kursora
    • ovrimos_exec - Wykonuje instrukcję SQL
    • ovrimos_execute - Wykonuje przygotowaną instrukcję SQL
    • ovrimos_fetch_into - Pobiera wiersz ze zbioru wyniku
    • ovrimos_fetch_row - Pobiera wiersz ze zbioru wyniku
    • ovrimos_field_len - Zwraca długość kolumny
    • ovrimos_field_name - Zwraca nazwę kolumny
    • ovrimos_field_num - Zwraca numer kolumny
    • ovrimos_field_type - Zwraca typ kolumny
    • ovrimos_free_result - Zwalnia pamięć zajmowaną przez określony wynik
    • ovrimos_longreadlen - Określa ile bajtów zostanie odczytanych z dużych typów danych
    • ovrimos_num_fields - Zwraca liczbę kolumn
    • ovrimos_num_rows - Pobiera liczbę wierszy użytych przez operacje aktualizacji
    • ovrimos_prepare - Przygotowuje instrukcję SQL
    • ovrimos_result - Odczytuje wartość kolumny
    • ovrimos_result_all - Wyświetla cały zbiór wyniku w postaci tabeli HTML
    • ovrimos_rollback - Wycofuje transakcję
  • p
    • pack - Pack data into binary string
    • ParentIterator::accept - Determines acceptability
    • ParentIterator::getChildren - Return the inner iterator's children contained in a ParentIterator
    • ParentIterator::hasChildren - Check whether the inner iterator's current element has children
    • ParentIterator::next - Move the iterator forward
    • ParentIterator::rewind - Rewind the iterator
    • ParentIterator::__construct - Constructs a ParentIterator
    • parsekit_compile_file - Compile a string of PHP code and return the resulting op array
    • parsekit_compile_string - Compile a string of PHP code and return the resulting op array
    • parsekit_func_arginfo - Return information regarding function argument(s)
    • parse_ini_file - Parse a configuration file
    • parse_ini_string - Parse a configuration string
    • parse_str - Parses the string into variables
    • parse_url - Przetwarza adres URL i zwraca jego składowe
    • passthru - Execute an external program and display raw output
    • pathinfo - Zwraca informacje o ścieżce do pliku
    • pclose - Zamyka wskaźnik pliku do procesu
    • pcntl_alarm - Set an alarm clock for delivery of a signal
    • pcntl_exec - Executes specified program in current process space
    • pcntl_fork - Forks the currently running process
    • pcntl_getpriority - Get the priority of any process
    • pcntl_setpriority - Change the priority of any process
    • pcntl_signal - Installs a signal handler
    • pcntl_signal_dispatch - Calls signal handlers for pending signals
    • pcntl_sigprocmask - Sets and retrieves blocked signals
    • pcntl_sigtimedwait - Waits for signals, with a timeout
    • pcntl_sigwaitinfo - Waits for signals
    • pcntl_wait - Waits on or returns the status of a forked child
    • pcntl_waitpid - Waits on or returns the status of a forked child
    • pcntl_wexitstatus - Returns the return code of a terminated child
    • pcntl_wifexited - Checks if status code represents a normal exit
    • pcntl_wifsignaled - Checks whether the status code represents a termination due to a signal
    • pcntl_wifstopped - Checks whether the child process is currently stopped
    • pcntl_wstopsig - Returns the signal which caused the child to stop
    • pcntl_wtermsig - Returns the signal which caused the child to terminate
    • PDF_activate_item - Activate structure element or other content item
    • PDF_add_annotation - Add annotation [deprecated]
    • PDF_add_bookmark - Add bookmark for current page [deprecated]
    • PDF_add_launchlink - Add launch annotation for current page [deprecated]
    • PDF_add_locallink - Add link annotation for current page [deprecated]
    • PDF_add_nameddest - Create named destination
    • PDF_add_note - Set annotation for current page [deprecated]
    • PDF_add_outline - Add bookmark for current page [deprecated]
    • PDF_add_pdflink - Add file link annotation for current page [deprecated]
    • PDF_add_table_cell - Add a cell to a new or existing table
    • PDF_add_textflow - Create Textflow or add text to existing Textflow
    • PDF_add_thumbnail - Add thumbnail for current page
    • PDF_add_weblink - Add weblink for current page [deprecated]
    • PDF_arc - Draw a counterclockwise circular arc segment
    • PDF_arcn - Draw a clockwise circular arc segment
    • PDF_attach_file - Add file attachment for current page [deprecated]
    • PDF_begin_document - Create new PDF file
    • PDF_begin_font - Start a Type 3 font definition
    • PDF_begin_glyph - Start glyph definition for Type 3 font
    • PDF_begin_item - Open structure element or other content item
    • PDF_begin_layer - Start layer
    • PDF_begin_page - Start new page [deprecated]
    • PDF_begin_page_ext - Start new page
    • PDF_begin_pattern - Start pattern definition
    • PDF_begin_template - Start template definition [deprecated]
    • PDF_begin_template_ext - Start template definition
    • PDF_circle - Draw a circle
    • PDF_clip - Clip to current path
    • PDF_close - Close pdf resource [deprecated]
    • PDF_closepath - Close current path
    • PDF_closepath_fill_stroke - Close, fill and stroke current path
    • PDF_closepath_stroke - Close and stroke path
    • PDF_close_image - Close image
    • PDF_close_pdi - Close the input PDF document [deprecated]
    • PDF_close_pdi_page - Close the page handle
    • PDF_concat - Concatenate a matrix to the CTM
    • PDF_continue_text - Output text in next line
    • PDF_create_3dview - Create 3D view
    • PDF_create_action - Create action for objects or events
    • PDF_create_annotation - Create rectangular annotation
    • PDF_create_bookmark - Create bookmark
    • PDF_create_field - Create form field
    • PDF_create_fieldgroup - Create form field group
    • PDF_create_gstate - Create graphics state object
    • PDF_create_pvf - Create PDFlib virtual file
    • PDF_create_textflow - Create textflow object
    • PDF_curveto - Draw Bezier curve
    • PDF_define_layer - Create layer definition
    • PDF_delete - Delete PDFlib object
    • PDF_delete_pvf - Delete PDFlib virtual file
    • PDF_delete_table - Delete table object
    • PDF_delete_textflow - Delete textflow object
    • PDF_encoding_set_char - Add glyph name and/or Unicode value
    • PDF_endpath - End current path
    • PDF_end_document - Close PDF file
    • PDF_end_font - Terminate Type 3 font definition
    • PDF_end_glyph - Terminate glyph definition for Type 3 font
    • PDF_end_item - Close structure element or other content item
    • PDF_end_layer - Deactivate all active layers
    • PDF_end_page - Finish page
    • PDF_end_page_ext - Finish page
    • PDF_end_pattern - Finish pattern
    • PDF_end_template - Finish template
    • PDF_fill - Fill current path
    • PDF_fill_imageblock - Fill image block with variable data
    • PDF_fill_pdfblock - Fill PDF block with variable data
    • PDF_fill_stroke - Fill and stroke path
    • PDF_fill_textblock - Fill text block with variable data
    • PDF_findfont - Prepare font for later use [deprecated]
    • PDF_fit_image - Place image or template
    • PDF_fit_pdi_page - Place imported PDF page
    • PDF_fit_table - Place table on page
    • PDF_fit_textflow - Format textflow in rectangular area
    • PDF_fit_textline - Place single line of text
    • PDF_get_apiname - Get name of unsuccessfull API function
    • PDF_get_buffer - Get PDF output buffer
    • PDF_get_errmsg - Get error text
    • PDF_get_errnum - Get error number
    • PDF_get_font - Get font [deprecated]
    • PDF_get_fontname - Get font name [deprecated]
    • PDF_get_fontsize - Font handling [deprecated]
    • PDF_get_image_height - Get image height [deprecated]
    • PDF_get_image_width - Get image width [deprecated]
    • PDF_get_majorversion - Get major version number [deprecated]
    • PDF_get_minorversion - Get minor version number [deprecated]
    • PDF_get_parameter - Get string parameter
    • PDF_get_pdi_parameter - Get PDI string parameter [deprecated]
    • PDF_get_pdi_value - Get PDI numerical parameter [deprecated]
    • PDF_get_value - Get numerical parameter
    • PDF_info_font - Query detailed information about a loaded font
    • PDF_info_matchbox - Query matchbox information
    • PDF_info_table - Retrieve table information
    • PDF_info_textflow - Query textflow state
    • PDF_info_textline - Perform textline formatting and query metrics
    • PDF_initgraphics - Reset graphic state
    • PDF_lineto - Draw a line
    • PDF_load_3ddata - Load 3D model
    • PDF_load_font - Search and prepare font
    • PDF_load_iccprofile - Search and prepare ICC profile
    • PDF_load_image - Open image file
    • PDF_makespotcolor - Make spot color
    • PDF_moveto - Set current point
    • PDF_new - Create PDFlib object
    • PDF_open_ccitt - Open raw CCITT image [deprecated]
    • PDF_open_file - Create PDF file [deprecated]
    • PDF_open_gif - Open GIF image [deprecated]
    • PDF_open_image - Use image data [deprecated]
    • PDF_open_image_file - Read image from file [deprecated]
    • PDF_open_jpeg - Open JPEG image [deprecated]
    • PDF_open_memory_image - Open image created with PHP's image functions [not supported]
    • PDF_open_pdi - Open PDF file [deprecated]
    • PDF_open_pdi_document - Prepare a pdi document
    • PDF_open_pdi_page - Prepare a page
    • PDF_open_tiff - Open TIFF image [deprecated]
    • PDF_pcos_get_number - Get value of pCOS path with type number or boolean
    • PDF_pcos_get_stream - Get contents of pCOS path with type stream, fstream, or string
    • PDF_pcos_get_string - Get value of pCOS path with type name, string, or boolean
    • PDF_place_image - Place image on the page [deprecated]
    • PDF_place_pdi_page - Place PDF page [deprecated]
    • PDF_process_pdi - Process imported PDF document
    • PDF_rect - Draw rectangle
    • PDF_restore - Restore graphics state
    • PDF_resume_page - Resume page
    • PDF_rotate - Rotate coordinate system
    • PDF_save - Save graphics state
    • PDF_scale - Scale coordinate system
    • PDF_setcolor - Set fill and stroke color
    • PDF_setdash - Set simple dash pattern
    • PDF_setdashpattern - Set dash pattern
    • PDF_setflat - Set flatness
    • PDF_setfont - Set font
    • PDF_setgray - Set color to gray [deprecated]
    • PDF_setgray_fill - Set fill color to gray [deprecated]
    • PDF_setgray_stroke - Set stroke color to gray [deprecated]
    • PDF_setlinecap - Set linecap parameter
    • PDF_setlinejoin - Set linejoin parameter
    • PDF_setlinewidth - Set line width
    • PDF_setmatrix - Set current transformation matrix
    • PDF_setmiterlimit - Set miter limit
    • PDF_setpolydash - Set complicated dash pattern [deprecated]
    • PDF_setrgbcolor - Set fill and stroke rgb color values [deprecated]
    • PDF_setrgbcolor_fill - Set fill rgb color values [deprecated]
    • PDF_setrgbcolor_stroke - Set stroke rgb color values [deprecated]
    • PDF_set_border_color - Set border color of annotations [deprecated]
    • PDF_set_border_dash - Set border dash style of annotations [deprecated]
    • PDF_set_border_style - Set border style of annotations [deprecated]
    • PDF_set_char_spacing - Set character spacing [deprecated]
    • PDF_set_duration - Set duration between pages [deprecated]
    • PDF_set_gstate - Activate graphics state object
    • PDF_set_horiz_scaling - Set horizontal text scaling [deprecated]
    • PDF_set_info - Fill document info field
    • PDF_set_info_author - Fill the author document info field [deprecated]
    • PDF_set_info_creator - Fill the creator document info field [deprecated]
    • PDF_set_info_keywords - Fill the keywords document info field [deprecated]
    • PDF_set_info_subject - Fill the subject document info field [deprecated]
    • PDF_set_info_title - Fill the title document info field [deprecated]
    • PDF_set_layer_dependency - Define relationships among layers
    • PDF_set_leading - Set distance between text lines [deprecated]
    • PDF_set_parameter - Set string parameter
    • PDF_set_text_matrix - Set text matrix [deprecated]
    • PDF_set_text_pos - Set text position
    • PDF_set_text_rendering - Determine text rendering [deprecated]
    • PDF_set_text_rise - Set text rise [deprecated]
    • PDF_set_value - Set numerical parameter
    • PDF_set_word_spacing - Set spacing between words [deprecated]
    • PDF_shading - Define blend
    • PDF_shading_pattern - Define shading pattern
    • PDF_shfill - Fill area with shading
    • PDF_show - Output text at current position
    • PDF_show_boxed - Output text in a box [deprecated]
    • PDF_show_xy - Output text at given position
    • PDF_skew - Skew the coordinate system
    • PDF_stringwidth - Return width of text
    • PDF_stroke - Stroke path
    • PDF_suspend_page - Suspend page
    • PDF_translate - Set origin of coordinate system
    • PDF_utf8_to_utf16 - Convert string from UTF-8 to UTF-16
    • PDF_utf16_to_utf8 - Convert string from UTF-16 to UTF-8
    • PDF_utf32_to_utf16 - Convert string from UTF-32 to UTF-16
    • PDO::beginTransaction - Initiates a transaction
    • PDO::commit - Commits a transaction
    • PDO::cubrid_schema - Get the requested schema information
    • PDO::errorCode - Fetch the SQLSTATE associated with the last operation on the database handle
    • PDO::errorInfo - Fetch extended error information associated with the last operation on the database handle
    • PDO::exec - Execute an SQL statement and return the number of affected rows
    • PDO::getAttribute - Retrieve a database connection attribute
    • PDO::getAvailableDrivers - Return an array of available PDO drivers
    • PDO::inTransaction - Checks if inside a transaction
    • PDO::lastInsertId - Returns the ID of the last inserted row or sequence value
    • PDO::pgsqlLOBCreate - Creates a new large object
    • PDO::pgsqlLOBOpen - Opens an existing large object stream
    • PDO::pgsqlLOBUnlink - Deletes the large object
    • PDO::prepare - Prepares a statement for execution and returns a statement object
    • PDO::query - Executes an SQL statement, returning a result set as a PDOStatement object
    • PDO::quote - Quotes a string for use in a query.
    • PDO::rollBack - Rolls back a transaction
    • PDO::setAttribute - Set an attribute
    • PDO::sqliteCreateAggregate - Registers an aggregating User Defined Function for use in SQL statements
    • PDO::sqliteCreateFunction - Registers a User Defined Function for use in SQL statements
    • PDO::__construct - Creates a PDO instance representing a connection to a database
    • PDOStatement::bindColumn - Bind a column to a PHP variable
    • PDOStatement::bindParam - Binds a parameter to the specified variable name
    • PDOStatement::bindValue - Binds a value to a parameter
    • PDOStatement::closeCursor - Closes the cursor, enabling the statement to be executed again.
    • PDOStatement::columnCount - Returns the number of columns in the result set
    • PDOStatement::debugDumpParams - Dump an SQL prepared command
    • PDOStatement::errorCode - Fetch the SQLSTATE associated with the last operation on the statement handle
    • PDOStatement::errorInfo - Fetch extended error information associated with the last operation on the statement handle
    • PDOStatement::execute - Executes a prepared statement
    • PDOStatement::fetch - Fetches the next row from a result set
    • PDOStatement::fetchAll - Returns an array containing all of the result set rows
    • PDOStatement::fetchColumn - Returns a single column from the next row of a result set
    • PDOStatement::fetchObject - Fetches the next row and returns it as an object.
    • PDOStatement::getAttribute - Retrieve a statement attribute
    • PDOStatement::getColumnMeta - Returns metadata for a column in a result set
    • PDOStatement::nextRowset - Advances to the next rowset in a multi-rowset statement handle
    • PDOStatement::rowCount - Returns the number of rows affected by the last SQL statement
    • PDOStatement::setAttribute - Set a statement attribute
    • PDOStatement::setFetchMode - Set the default fetch mode for this statement
    • PDO_4D DSN - Connecting to 4D SQL server
    • PDO_CUBRID DSN - Connecting to CUBRID databases
    • PDO_DBLIB DSN - Connecting to Microsoft SQL Server and Sybase databases
    • PDO_FIREBIRD DSN - Connecting to Firebird and Interbase databases
    • PDO_IBM DSN - Connecting to IBM databases
    • PDO_INFORMIX DSN - Connecting to Informix databases
    • PDO_MYSQL DSN - Connecting to MySQL databases
    • PDO_OCI DSN - Connecting to Oracle databases
    • PDO_ODBC DSN - Connecting to ODBC or DB2 databases
    • PDO_PGSQL DSN - Connecting to PostgreSQL databases
    • PDO_SQLITE DSN - Connecting to SQLite databases
    • PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
    • pfsockopen - Open persistent Internet or Unix domain socket connection
    • pg_affected_rows - Zwraca liczbę zmodyfikowanych wierszy
    • pg_cancel_query - Przerywa zapytanie asynchroniczne
    • pg_client_encoding - Zwraca stronę kodową klienta
    • pg_close - Zamyka połączenie z PostgreSQL
    • pg_connect - Otwiera tymczasowe połączenie do PostgreSQL-a
    • pg_connection_busy - Sprawdza czy połączenie jest zajęte czy wolne
    • pg_connection_reset - Restartuje połączenie
    • pg_connection_status - Zwraca stan połączenia
    • pg_convert - Konwertuje tablice asocjacyjne na postać użyteczną w zapytaniu SQL.
    • pg_copy_from - Wstawia wiersze do tabeli z tablicy
    • pg_copy_to - Kopiuje tabelę do tablicy
    • pg_dbname - Podaje nazwę bazy danych
    • pg_delete - Usuwa rekordy
    • pg_end_copy - Synchronizuje klienta z serwerem PostgreSQL.
    • pg_escape_bytea - Konwertuje łańcuch wstawiając sekwencje Escape dla typu bytea
    • pg_escape_identifier - Escape a identifier for insertion into a text field
    • pg_escape_literal - Escape a literal for insertion into a text field
    • pg_escape_string - Konwertuje łańcuch wpisywany do pola tekstowego, wstawiając sekwencje Escape
    • pg_execute - Sends a request to execute a prepared statement with given parameters, and waits for the result.
    • pg_fetch_all - Fetches all rows from a result as an array
    • pg_fetch_all_columns - Fetches all rows in a particular result column as an array
    • pg_fetch_array - Pobiera wiersz jako tablicę
    • pg_fetch_assoc - Fetch a row as an associative array
    • pg_fetch_object - Pobiera wiersz jako obiekt
    • pg_fetch_result - Pobiera dane z wyniku
    • pg_fetch_row - Pobiera wiersz jako tablicę z indeksami numerycznymi
    • pg_field_is_null - Sprawdza czy pole SQL zawiera NULL
    • pg_field_name - Zwraca nazwę kolumny
    • pg_field_num - Zwraza numer kolumny o podanej nazwie
    • pg_field_prtlen - Zwraca drukowalną długość
    • pg_field_size - Zwraca wewnętrzny rozmiar kolumny
    • pg_field_table - Returns the name or oid of the tables field
    • pg_field_type - Zwraca typ wskazanej kolumny
    • pg_field_type_oid - Returns the type ID (OID) for the corresponding field number
    • pg_free_result - Zwalnia pamięć wyniku
    • pg_get_notify - Gets SQL NOTIFY message
    • pg_get_pid - Gets the backend's process ID
    • pg_get_result - Pobiera wynik zapytania asynchroniczego
    • pg_host - Zwraca nazwę komputera związanego z połączeniem
    • pg_insert - Wstawia tablicę do tabeli
    • pg_last_error - Zwraca łańcuch ostatniego komunikatu błędu dla połączenia
    • pg_last_notice - Zwraca komunikaty informacyjne serwera PostgreSQL
    • pg_last_oid - Zwraca identyfikator OID ostatniego wiersza
    • pg_lo_close - Zamyka wielki obiekt (LO)
    • pg_lo_create - Tworzy wielki obiekt (Large Object - LO)
    • pg_lo_export - Eksportuje wielki obiekt (Large Object - LO) do pliku
    • pg_lo_import - Importuje wielki obiekt (Large Object - LO) z pliku
    • pg_lo_open - Otwiera wielki obiekt (Large Object - LO)
    • pg_lo_read - Odczytuje wielki obiekt (Large Object - LO)
    • pg_lo_read_all - Odczytuje wielki obiekt (Large Object - LO) i wysła go do przeglądarki
    • pg_lo_seek - Przemieszcza wskaźnik położenia w wielkim obiekcie (Large Object - LO)
    • pg_lo_tell - Zwraca wskaźnik położenia w wielkim obiekcie (Large Object - LO)
    • pg_lo_unlink - Usuwa wielki obiekt (Large Object - LO)
    • pg_lo_write - Zapisuje do wielkiego obiektu (Large Object - LO)
    • pg_meta_data - Pobiera informacje o tabeli
    • pg_num_fields - Zwraca liczbę kolumn
    • pg_num_rows - Zwraca liczbę wierszy
    • pg_options - Podaje opcje powiązane z połączenim
    • pg_parameter_status - Looks up a current parameter setting of the server.
    • pg_pconnect - Otwiera trwałe połączenie z serwerem PostgreSQL
    • pg_ping - Ping database connection
    • pg_port - Zwraca numer portu związany z połączeniem
    • pg_prepare - Submits a request to create a prepared statement with the given parameters, and waits for completion.
    • pg_put_line - Wysyła łańcuch zakończony znakiem NULL do serwera PostgreSQL
    • pg_query - Realizujezapytanie do bazy danych
    • pg_query_params - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
    • pg_result_error - Zwraca błąd związany z identyfikatorem wyniku
    • pg_result_error_field - Returns an individual field of an error report.
    • pg_result_seek - Set internal row offset in result resource
    • pg_result_status - Zwraca stan wyniku zapytania
    • pg_select - Wybiera wiersze
    • pg_send_execute - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
    • pg_send_prepare - Sends a request to create a prepared statement with the given parameters, without waiting for completion.
    • pg_send_query - Wysyła zapytanie asynchroniczne
    • pg_send_query_params - Submits a command and separate parameters to the server without waiting for the result(s).
    • pg_set_client_encoding - Ustawia stronę kodową klienta PostgreSQL-a
    • pg_set_error_verbosity - Determines the verbosity of messages returned by pg_last_error and pg_result_error.
    • pg_trace - Uruchamia śledzenie połączeń z PostgreSQL
    • pg_transaction_status - Returns the current in-transaction status of the server.
    • pg_tty - Zwraca nazwę konsoli tty związanej z połączeniem
    • pg_unescape_bytea - Unescape binary for bytea type
    • pg_untrace - Wyłącza śledzenie połączeń PostgreSQL-a
    • pg_update - Aktualizuje tabelę
    • pg_version - Returns an array with client, protocol and server version (when available)
    • phar:// - PHP Archive
    • Phar::addEmptyDir - Add an empty directory to the phar archive
    • Phar::addFile - Add a file from the filesystem to the phar archive
    • Phar::addFromString - Add a file from the filesystem to the phar archive
    • Phar::apiVersion - Returns the api version
    • Phar::buildFromDirectory - Construct a phar archive from the files within a directory.
    • Phar::buildFromIterator - Construct a phar archive from an iterator.
    • Phar::canCompress - Returns whether phar extension supports compression using either zlib or bzip2
    • Phar::canWrite - Returns whether phar extension supports writing and creating phars
    • Phar::compress - Compresses the entire Phar archive using Gzip or Bzip2 compression
    • Phar::compressAllFilesBZIP2 - Compresses all files in the current Phar archive using Bzip2 compression
    • Phar::compressAllFilesGZ - Compresses all files in the current Phar archive using Gzip compression
    • Phar::compressFiles - Compresses all files in the current Phar archive
    • Phar::convertToData - Convert a phar archive to a non-executable tar or zip file
    • Phar::convertToExecutable - Convert a phar archive to another executable phar archive file format
    • Phar::copy - Copy a file internal to the phar archive to another new file within the phar
    • Phar::count - Returns the number of entries (files) in the Phar archive
    • Phar::createDefaultStub - Create a phar-file format specific stub
    • Phar::decompress - Decompresses the entire Phar archive
    • Phar::decompressFiles - Decompresses all files in the current Phar archive
    • Phar::delete - Delete a file within a phar archive
    • Phar::delMetadata - Deletes the global metadata of the phar
    • Phar::extractTo - Extract the contents of a phar archive to a directory
    • Phar::getMetadata - Returns phar archive meta-data
    • Phar::getModified - Return whether phar was modified
    • Phar::getSignature - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
    • Phar::getStub - Return the PHP loader or bootstrap stub of a Phar archive
    • Phar::getSupportedCompression - Return array of supported compression algorithms
    • Phar::getSupportedSignatures - Return array of supported signature types
    • Phar::getVersion - Return version info of Phar archive
    • Phar::hasMetadata - Returns whether phar has global meta-data
    • Phar::interceptFileFuncs - instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
    • Phar::isBuffering - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
    • Phar::isCompressed - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
    • Phar::isFileFormat - Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
    • Phar::isValidPharFilename - Returns whether the given filename is a valid phar filename
    • Phar::isWritable - Returns true if the phar archive can be modified
    • Phar::loadPhar - Loads any phar archive with an alias
    • Phar::mapPhar - Reads the currently executed file (a phar) and registers its manifest
    • Phar::mount - Mount an external path or file to a virtual location within the phar archive
    • Phar::mungServer - Defines a list of up to 4 $_SERVER variables that should be modified for execution
    • Phar::offsetExists - determines whether a file exists in the phar
    • Phar::offsetGet - Gets a PharFileInfo object for a specific file
    • Phar::offsetSet - set the contents of an internal file to those of an external file
    • Phar::offsetUnset - remove a file from a phar
    • Phar::running - Returns the full path on disk or full phar URL to the currently executing Phar archive
    • Phar::setAlias - Set the alias for the Phar archive
    • Phar::setDefaultStub - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
    • Phar::setMetadata - Sets phar archive meta-data
    • Phar::setSignatureAlgorithm - set the signature algorithm for a phar and apply it. The
    • Phar::setStub - Used to set the PHP loader or bootstrap stub of a Phar archive
    • Phar::startBuffering - Start buffering Phar write operations, do not modify the Phar object on disk
    • Phar::stopBuffering - Stop buffering write requests to the Phar archive, and save changes to disk
    • Phar::uncompressAllFiles - Uncompresses all files in the current Phar archive
    • Phar::unlinkArchive - Completely remove a phar archive from disk and from memory
    • Phar::webPhar - mapPhar for web-based phars. front controller for web applications
    • Phar::__construct - Construct a Phar archive object
    • Phar context options - Phar context option listing
    • PharData::addEmptyDir - Add an empty directory to the tar/zip archive
    • PharData::addFile - Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString - Add a file from the filesystem to the tar/zip archive
    • PharData::buildFromDirectory - Construct a tar/zip archive from the files within a directory.
    • PharData::buildFromIterator - Construct a tar or zip archive from an iterator.
    • PharData::compress - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles - Compresses all files in the current tar/zip archive
    • PharData::convertToData - Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable - Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy - Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress - Decompresses the entire Phar archive
    • PharData::decompressFiles - Decompresses all files in the current zip archive
    • PharData::delete - Delete a file within a tar/zip archive
    • PharData::delMetadata - Deletes the global metadata of a zip archive
    • PharData::extractTo - Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable - Returns true if the tar/zip archive can be modified
    • PharData::offsetSet - set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset - remove a file from a tar/zip archive
    • PharData::setAlias - dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub - dummy function (Phar::setDefaultStub is not valid for PharData)
    • PharData::setStub - dummy function (Phar::setStub is not valid for PharData)
    • PharData::__construct - Construct a non-executable tar or zip archive object
    • PharException - The PharException class provides a phar-specific exception class for try/catch blocks.
    • PharFileInfo::chmod - Sets file-specific permission bits
    • PharFileInfo::compress - Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::decompress - Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata - Deletes the metadata of the entry
    • PharFileInfo::getCompressedSize - Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getCRC32 - Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getMetadata - Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags - Returns the Phar file entry flags
    • PharFileInfo::hasMetadata - Returns the metadata of the entry
    • PharFileInfo::isCompressed - Returns whether the entry is compressed
    • PharFileInfo::isCompressedBZIP2 - Returns whether the entry is compressed using bzip2
    • PharFileInfo::isCompressedGZ - Returns whether the entry is compressed using gz
    • PharFileInfo::isCRCChecked - Returns whether file entry has had its CRC verified
    • PharFileInfo::setCompressedBZIP2 - Compresses the current Phar entry within the phar using Bzip2 compression
    • PharFileInfo::setCompressedGZ - Compresses the current Phar entry within the phar using gz compression
    • PharFileInfo::setMetadata - Sets file-specific meta-data saved with a file
    • PharFileInfo::setUncompressed - Uncompresses the current Phar entry within the phar, if it is compressed
    • PharFileInfo::__construct - Construct a Phar entry object
    • php:// - Accessing various I/O streams
    • phpcredits - Prints out the credits for PHP
    • phpinfo - Outputs information about PHP's configuration
    • phpversion - Gets the current PHP version
    • php_check_syntax - Check the PHP syntax of (and execute) the specified file
    • php_ini_loaded_file - Retrieve a path to the loaded php.ini file
    • php_ini_scanned_files - Return a list of .ini files parsed from the additional ini dir
    • php_logo_guid - Gets the logo guid
    • php_sapi_name - Returns the type of interface between web server and PHP
    • php_strip_whitespace - Return source with stripped comments and whitespace
    • php_uname - Returns information about the operating system PHP is running on
    • pi - Wartość liczby Pi
    • png2wbmp - Convert PNG image file to WBMP image file
    • popen - Otwiera wskaźnik pliku do procesu
    • pos - Alias dla current
    • posix_access - Determine accessibility of a file
    • posix_ctermid - Get path name of controlling terminal
    • posix_errno - Alias dla posix_get_last_error
    • posix_getcwd - Pathname of current directory
    • posix_getegid - Return the effective group ID of the current process
    • posix_geteuid - Return the effective user ID of the current process
    • posix_getgid - Return the real group ID of the current process
    • posix_getgrgid - Return info about a group by group id
    • posix_getgrnam - Return info about a group by name
    • posix_getgroups - Return the group set of the current process
    • posix_getlogin - Return login name
    • posix_getpgid - Get process group id for job control
    • posix_getpgrp - Return the current process group identifier
    • posix_getpid - Return the current process identifier
    • posix_getppid - Return the parent process identifier
    • posix_getpwnam - Return info about a user by username
    • posix_getpwuid - Return info about a user by user id
    • posix_getrlimit - Return info about system resource limits
    • posix_getsid - Get the current sid of the process
    • posix_getuid - Return the real user ID of the current process
    • posix_get_last_error - Retrieve the error number set by the last posix function that failed
    • posix_initgroups - Calculate the group access list
    • posix_isatty - Determine if a file descriptor is an interactive terminal
    • posix_kill - Send a signal to a process
    • posix_mkfifo - Create a fifo special file (a named pipe)
    • posix_mknod - Create a special or ordinary file (POSIX.1)
    • posix_setegid - Set the effective GID of the current process
    • posix_seteuid - Set the effective UID of the current process
    • posix_setgid - Set the GID of the current process
    • posix_setpgid - Set process group id for job control
    • posix_setsid - Make the current process a session leader
    • posix_setuid - Set the UID of the current process
    • posix_strerror - Retrieve the system error message associated with the given errno
    • posix_times - Get process times
    • posix_ttyname - Determine terminal device name
    • posix_uname - Get system name
    • pow - Potęgowanie
    • preg_filter - Perform a regular expression search and replace
    • preg_grep - Return array entries that match the pattern
    • preg_last_error - Returns the error code of the last PCRE regex execution
    • preg_match - Perform a regular expression match
    • preg_match_all - Perform a global regular expression match
    • preg_quote - Quote regular expression characters
    • preg_replace - Perform a regular expression search and replace
    • preg_replace_callback - Perform a regular expression search and replace using a callback
    • preg_split - Split string by a regular expression
    • prev - Cofnij wewnętrzny wskaźnik tablicy
    • print - Output a string
    • printer_abort - Deletes the printer's spool file
    • printer_close - Close an open printer connection
    • printer_create_brush - Create a new brush
    • printer_create_dc - Create a new device context
    • printer_create_font - Create a new font
    • printer_create_pen - Create a new pen
    • printer_delete_brush - Delete a brush
    • printer_delete_dc - Delete a device context
    • printer_delete_font - Delete a font
    • printer_delete_pen - Delete a pen
    • printer_draw_bmp - Draw a bmp
    • printer_draw_chord - Draw a chord
    • printer_draw_elipse - Draw an ellipse
    • printer_draw_line - Draw a line
    • printer_draw_pie - Draw a pie
    • printer_draw_rectangle - Draw a rectangle
    • printer_draw_roundrect - Draw a rectangle with rounded corners
    • printer_draw_text - Draw text
    • printer_end_doc - Close document
    • printer_end_page - Close active page
    • printer_get_option - Retrieve printer configuration data
    • printer_list - Return an array of printers attached to the server
    • printer_logical_fontheight - Get logical font height
    • printer_open - Opens a connection to a printer
    • printer_select_brush - Select a brush
    • printer_select_font - Select a font
    • printer_select_pen - Select a pen
    • printer_set_option - Configure the printer connection
    • printer_start_doc - Start a new document
    • printer_start_page - Start a new page
    • printer_write - Write data to the printer
    • printf - Output a formatted string
    • print_r - Prints human-readable information about a variable
    • proc_close - Close a process opened by proc_open and return the exit code of that process
    • proc_get_status - Get information about a process opened by proc_open
    • proc_nice - Change the priority of the current process
    • proc_open - Execute a command and open file pointers for input/output
    • proc_terminate - Kills a process opened by proc_open
    • property_exists - Checks if the object or class has a property
    • pspell_add_to_personal - Add the word to a personal wordlist
    • pspell_add_to_session - Add the word to the wordlist in the current session
    • pspell_check - Check a word
    • pspell_clear_session - Clear the current session
    • pspell_config_create - Create a config used to open a dictionary
    • pspell_config_data_dir - location of language data files
    • pspell_config_dict_dir - Location of the main word list
    • pspell_config_ignore - Ignore words less than N characters long
    • pspell_config_mode - Change the mode number of suggestions returned
    • pspell_config_personal - Set a file that contains personal wordlist
    • pspell_config_repl - Set a file that contains replacement pairs
    • pspell_config_runtogether - Consider run-together words as valid compounds
    • pspell_config_save_repl - Determine whether to save a replacement pairs list along with the wordlist
    • pspell_new - Load a new dictionary
    • pspell_new_config - Load a new dictionary with settings based on a given config
    • pspell_new_personal - Load a new dictionary with personal wordlist
    • pspell_save_wordlist - Save the personal wordlist to a file
    • pspell_store_replacement - Store a replacement pair for a word
    • pspell_suggest - Suggest spellings of a word
    • ps_add_bookmark - Add bookmark to current page
    • ps_add_launchlink - Adds link which launches file
    • ps_add_locallink - Adds link to a page in the same document
    • ps_add_note - Adds note to current page
    • ps_add_pdflink - Adds link to a page in a second pdf document
    • ps_add_weblink - Adds link to a web location
    • ps_arc - Draws an arc counterclockwise
    • ps_arcn - Draws an arc clockwise
    • ps_begin_page - Start a new page
    • ps_begin_pattern - Start a new pattern
    • ps_begin_template - Start a new template
    • ps_circle - Draws a circle
    • ps_clip - Clips drawing to current path
    • ps_close - Closes a PostScript document
    • ps_closepath - Closes path
    • ps_closepath_stroke - Closes and strokes path
    • ps_close_image - Closes image and frees memory
    • ps_continue_text - Continue text in next line
    • ps_curveto - Draws a curve
    • ps_delete - Deletes all resources of a PostScript document
    • ps_end_page - End a page
    • ps_end_pattern - End a pattern
    • ps_end_template - End a template
    • ps_fill - Fills the current path
    • ps_fill_stroke - Fills and strokes the current path
    • ps_findfont - Loads a font
    • ps_get_buffer - Fetches the full buffer containig the generated PS data
    • ps_get_parameter - Gets certain parameters
    • ps_get_value - Gets certain values
    • ps_hyphenate - Hyphenates a word
    • ps_include_file - Reads an external file with raw PostScript code
    • ps_lineto - Draws a line
    • ps_makespotcolor - Create spot color
    • ps_moveto - Sets current point
    • ps_new - Creates a new PostScript document object
    • ps_open_file - Opens a file for output
    • ps_open_image - Reads an image for later placement
    • ps_open_image_file - Opens image from file
    • ps_open_memory_image - Takes an GD image and returns an image for placement in a PS document
    • ps_place_image - Places image on the page
    • ps_rect - Draws a rectangle
    • ps_restore - Restore previously save context
    • ps_rotate - Sets rotation factor
    • ps_save - Save current context
    • ps_scale - Sets scaling factor
    • ps_setcolor - Sets current color
    • ps_setdash - Sets appearance of a dashed line
    • ps_setflat - Sets flatness
    • ps_setfont - Sets font to use for following output
    • ps_setgray - Sets gray value
    • ps_setlinecap - Sets appearance of line ends
    • ps_setlinejoin - Sets how contected lines are joined
    • ps_setlinewidth - Sets width of a line
    • ps_setmiterlimit - Sets the miter limit
    • ps_setoverprintmode - Sets overprint mode
    • ps_setpolydash - Sets appearance of a dashed line
    • ps_set_border_color - Sets color of border for annotations
    • ps_set_border_dash - Sets length of dashes for border of annotations
    • ps_set_border_style - Sets border style of annotations
    • ps_set_info - Sets information fields of document
    • ps_set_parameter - Sets certain parameters
    • ps_set_text_pos - Sets position for text output
    • ps_set_value - Sets certain values
    • ps_shading - Creates a shading for later use
    • ps_shading_pattern - Creates a pattern based on a shading
    • ps_shfill - Fills an area with a shading
    • ps_show - Output text
    • ps_show2 - Output a text at current position
    • ps_show_boxed - Output text in a box
    • ps_show_xy - Output text at given position
    • ps_show_xy2 - Output text at position
    • ps_stringwidth - Gets width of a string
    • ps_string_geometry - Gets geometry of a string
    • ps_stroke - Draws the current path
    • ps_symbol - Output a glyph
    • ps_symbol_name - Gets name of a glyph
    • ps_symbol_width - Gets width of a glyph
    • ps_translate - Sets translation
    • putenv - Sets the value of an environment variable
    • px_close - Closes a paradox database
    • px_create_fp - Create a new paradox database
    • px_date2string - Converts a date into a string.
    • px_delete - Deletes resource of paradox database
    • px_delete_record - Deletes record from paradox database
    • px_get_field - Returns the specification of a single field
    • px_get_info - Return lots of information about a paradox file
    • px_get_parameter - Gets a parameter
    • px_get_record - Returns record of paradox database
    • px_get_schema - Returns the database schema
    • px_get_value - Gets a value
    • px_insert_record - Inserts record into paradox database
    • px_new - Create a new paradox object
    • px_numfields - Returns number of fields in a database
    • px_numrecords - Returns number of records in a database
    • px_open_fp - Open paradox database
    • px_put_record - Stores record into paradox database
    • px_retrieve_record - Returns record of paradox database
    • px_set_blob_file - Sets the file where blobs are read from
    • px_set_parameter - Sets a parameter
    • px_set_tablename - Sets the name of a table (deprecated)
    • px_set_targetencoding - Sets the encoding for character fields (deprecated)
    • px_set_value - Sets a value
    • px_timestamp2string - Converts the timestamp into a string.
    • px_update_record - Updates record in paradox database
  • q
    • qdom_error - Returns the error string from the last QDOM operation or FALSE if no errors occurred
    • qdom_tree - Creates a tree of an XML string
    • QuickHashIntHash::add - This method adds a new entry to the hash
    • QuickHashIntHash::delete - This method deletes am entry from the hash
    • QuickHashIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize - Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntHash::__construct - Creates a new QuickHashIntHash object
    • QuickHashIntSet::add - This method adds a new entry to the set
    • QuickHashIntSet::delete - This method deletes an entry from the set
    • QuickHashIntSet::exists - This method checks whether a key is part of the set
    • QuickHashIntSet::getSize - Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile - This factory method creates a set from a file
    • QuickHashIntSet::loadFromString - This factory method creates a set from a string
    • QuickHashIntSet::saveToFile - This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString - This method returns a serialized version of the set
    • QuickHashIntSet::__construct - Creates a new QuickHashIntSet object
    • QuickHashIntStringHash::add - This method adds a new entry to the hash
    • QuickHashIntStringHash::delete - This method deletes am entry from the hash
    • QuickHashIntStringHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize - Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntStringHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntStringHash::__construct - Creates a new QuickHashIntStringHash object
    • QuickHashStringIntHash::add - This method adds a new entry to the hash
    • QuickHashStringIntHash::delete - This method deletes am entry from the hash
    • QuickHashStringIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize - Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashStringIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashStringIntHash::__construct - Creates a new QuickHashStringIntHash object
    • quoted_printable_decode - Convert a quoted-printable string to an 8 bit string
    • quoted_printable_encode - Convert a 8 bit string to a quoted-printable string
    • quotemeta - Quote meta characters
  • r
    • rad2deg - Przelicza radiany na stopnie.
    • radius_acct_open - Creates a Radius handle for accounting
    • radius_add_server - Adds a server
    • radius_auth_open - Creates a Radius handle for authentication
    • radius_close - Frees all ressources
    • radius_config - Causes the library to read the given configuration file
    • radius_create_request - Create accounting or authentication request
    • radius_cvt_addr - Converts raw data to IP-Address
    • radius_cvt_int - Converts raw data to integer
    • radius_cvt_string - Converts raw data to string
    • radius_demangle - Demangles data
    • radius_demangle_mppe_key - Derives mppe-keys from mangled data
    • radius_get_attr - Extracts an attribute
    • radius_get_vendor_attr - Extracts a vendor specific attribute
    • radius_put_addr - Attaches an IP-Address attribute
    • radius_put_attr - Attaches a binary attribute
    • radius_put_int - Attaches an integer attribute
    • radius_put_string - Attaches a string attribute
    • radius_put_vendor_addr - Attaches a vendor specific IP-Address attribute
    • radius_put_vendor_attr - Attaches a vendor specific binary attribute
    • radius_put_vendor_int - Attaches a vendor specific integer attribute
    • radius_put_vendor_string - Attaches a vendor specific string attribute
    • radius_request_authenticator - Returns the request authenticator
    • radius_send_request - Sends the request and waites for a reply
    • radius_server_secret - Returns the shared secret
    • radius_strerror - Returns an error message
    • rand - Generuje losową liczbę stałoprzecinkową
    • range - Stwórz tablicę zawierającą przedział elementów
    • rar:// - RAR
    • RarArchive::close - Close RAR archive and free all resources
    • RarArchive::getComment - Get comment text from the RAR archive
    • RarArchive::getEntries - Get full list of entries from the RAR archive
    • RarArchive::getEntry - Get entry object from the RAR archive
    • RarArchive::isBroken - Test whether an archive is broken (incomplete)
    • RarArchive::isSolid - Check whether the RAR archive is solid
    • RarArchive::open - Open RAR archive
    • RarArchive::setAllowBroken - Whether opening broken archives is allowed
    • RarArchive::__toString - Get text representation
    • RarEntry::extract - Extract entry from the archive
    • RarEntry::getAttr - Get attributes of the entry
    • RarEntry::getCrc - Get CRC of the entry
    • RarEntry::getFileTime - Get entry last modification time
    • RarEntry::getHostOs - Get entry host OS
    • RarEntry::getMethod - Get pack method of the entry
    • RarEntry::getName - Get name of the entry
    • RarEntry::getPackedSize - Get packed size of the entry
    • RarEntry::getStream - Get file handler for entry
    • RarEntry::getUnpackedSize - Get unpacked size of the entry
    • RarEntry::getVersion - Get minimum version of RAR program required to unpack the entry
    • RarEntry::isDirectory - Test whether an entry represents a directory
    • RarEntry::isEncrypted - Test whether an entry is encrypted
    • RarEntry::__toString - Get text representation of entry
    • RarException::isUsingExceptions - Check whether error handling with exceptions is in use
    • RarException::setUsingExceptions - Activate and deactivate error handling with exceptions
    • rar_wrapper_cache_stats - Cache hits and misses for the URL wrapper
    • rawurldecode - Dekoduje łańcuchy zakodowane metodą kodowania URL'i
    • rawurlencode - Koduje URL'e zgodnie z RFC 1738
    • readdir - Czyta zawartość katalogu
    • readfile - Wyświetla plik
    • readgzfile - Output a gz-file
    • readline - Czyta linię
    • readline_add_history - Dodaje wiersz do historii
    • readline_callback_handler_install - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
    • readline_callback_handler_remove - Removes a previously installed callback handler and restores terminal settings
    • readline_callback_read_char - Reads a character and informs the readline callback interface when a line is received
    • readline_clear_history - Czyści historię
    • readline_completion_function - Rejestruje funkcję dopełniania
    • readline_info - Pobiera/ustawia różne wewnętrzne zmienne biblioteki readline
    • readline_list_history - Zwraca historię wiersza poleceń
    • readline_on_new_line - Inform readline that the cursor has moved to a new line
    • readline_read_history - Czyta historię
    • readline_redisplay - Redraws the display
    • readline_write_history - Zapisuje historię
    • readlink - Zwraca cel linku symbolicznego
    • read_exif_data - Alias dla exif_read_data
    • realpath - Returns canonicalized absolute pathname
    • realpath_cache_get - Get realpath cache entries
    • realpath_cache_size - Get realpath cache size
    • recode - Alias dla recode_string
    • recode_file - Recode from file to file according to recode request
    • recode_string - Recode a string according to a recode request
    • RecursiveArrayIterator::getChildren - Returns an iterator for the current entry if it is an array or an object.
    • RecursiveArrayIterator::hasChildren - Returns whether current entry is an array or an object.
    • RecursiveCachingIterator::getChildren - Return the inner iterator's children as a RecursiveCachingIterator
    • RecursiveCachingIterator::hasChildren - Check whether the current element of the inner iterator has children
    • RecursiveCachingIterator::__construct - Construct
    • RecursiveCallbackFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
    • RecursiveCallbackFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveCallbackFilterIterator::__construct - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
    • RecursiveDirectoryIterator::getChildren - Returns an iterator for the current entry if it is a directory
    • RecursiveDirectoryIterator::getSubPath - Get sub path
    • RecursiveDirectoryIterator::getSubPathname - Get sub path and name
    • RecursiveDirectoryIterator::hasChildren - Returns whether current entry is a directory and not '.' or '..'
    • RecursiveDirectoryIterator::key - Return path and filename of current dir entry
    • RecursiveDirectoryIterator::next - Move to next entry
    • RecursiveDirectoryIterator::rewind - Rewind dir back to the start
    • RecursiveDirectoryIterator::__construct - Constructs a RecursiveDirectoryIterator
    • RecursiveFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveFilterIterator
    • RecursiveFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveFilterIterator::__construct - Create a RecursiveFilterIterator from a RecursiveIterator
    • RecursiveIterator::getChildren - Returns an iterator for the current entry.
    • RecursiveIterator::hasChildren - Returns if an iterator can be created fot the current entry.
    • RecursiveIteratorIterator::beginChildren - Begin children
    • RecursiveIteratorIterator::beginIteration - Begin Iteration
    • RecursiveIteratorIterator::callGetChildren - Get children
    • RecursiveIteratorIterator::callHasChildren - Has children
    • RecursiveIteratorIterator::current - Access the current element value
    • RecursiveIteratorIterator::endChildren - End children
    • RecursiveIteratorIterator::endIteration - End Iteration
    • RecursiveIteratorIterator::getDepth - Get the current depth of the recursive iteration
    • RecursiveIteratorIterator::getInnerIterator - Get inner iterator
    • RecursiveIteratorIterator::getMaxDepth - Get max depth
    • RecursiveIteratorIterator::getSubIterator - The current active sub iterator
    • RecursiveIteratorIterator::key - Access the current key
    • RecursiveIteratorIterator::next - Move forward to the next element
    • RecursiveIteratorIterator::nextElement - Next element
    • RecursiveIteratorIterator::rewind - Rewind the iterator to the first element of the top level inner iterator
    • RecursiveIteratorIterator::setMaxDepth - Set max depth
    • RecursiveIteratorIterator::valid - Check whether the current position is valid
    • RecursiveIteratorIterator::__construct - Construct a RecursiveIteratorIterator
    • RecursiveRegexIterator::getChildren - Returns an iterator for the current entry.
    • RecursiveRegexIterator::hasChildren - Returns whether an iterator can be obtained for the current entry.
    • RecursiveRegexIterator::__construct - Creates a new RecursiveRegexIterator.
    • RecursiveTreeIterator::beginChildren - Begin children
    • RecursiveTreeIterator::beginIteration - Begin iteration
    • RecursiveTreeIterator::callGetChildren - Get children
    • RecursiveTreeIterator::callHasChildren - Has children
    • RecursiveTreeIterator::current - Get current element
    • RecursiveTreeIterator::endChildren - End children
    • RecursiveTreeIterator::endIteration - End iteration
    • RecursiveTreeIterator::getEntry - Get current entry
    • RecursiveTreeIterator::getPostfix - Get the postfix
    • RecursiveTreeIterator::getPrefix - Get the prefix
    • RecursiveTreeIterator::key - Get the key of the current element
    • RecursiveTreeIterator::next - Move to next element
    • RecursiveTreeIterator::nextElement - Next element
    • RecursiveTreeIterator::rewind - Rewind iterator
    • RecursiveTreeIterator::setPrefixPart - Set a part of the prefix
    • RecursiveTreeIterator::valid - Check validity
    • RecursiveTreeIterator::__construct - Construct a RecursiveTreeIterator
    • Reflection::export - Exports
    • Reflection::getModifierNames - Gets modifier names
    • ReflectionClass::export - Exports a class
    • ReflectionClass::getConstant - Gets defined constant
    • ReflectionClass::getConstants - Gets constants
    • ReflectionClass::getConstructor - Gets constructor
    • ReflectionClass::getDefaultProperties - Gets default properties
    • ReflectionClass::getDocComment - Gets doc comments
    • ReflectionClass::getEndLine - Gets end line
    • ReflectionClass::getExtension - Gets extension info
    • ReflectionClass::getExtensionName - Gets an extensions name
    • ReflectionClass::getFileName - Gets the filename of the file in which the class has been defined
    • ReflectionClass::getInterfaceNames - Gets the interface names
    • ReflectionClass::getInterfaces - Gets the interfaces
    • ReflectionClass::getMethod - Gets a ReflectionMethod
    • ReflectionClass::getMethods - Gets a list of methods
    • ReflectionClass::getModifiers - Gets modifiers
    • ReflectionClass::getName - Gets class name
    • ReflectionClass::getNamespaceName - Gets namespace name
    • ReflectionClass::getParentClass - Gets parent class
    • ReflectionClass::getProperties - Gets properties
    • ReflectionClass::getProperty - Gets property
    • ReflectionClass::getShortName - Gets short name
    • ReflectionClass::getStartLine - Gets starting line number
    • ReflectionClass::getStaticProperties - Gets static properties
    • ReflectionClass::getStaticPropertyValue - Gets static property value
    • ReflectionClass::getTraitAliases - Returns an array of trait aliases
    • ReflectionClass::getTraitNames - Returns an array of names of traits used by this class
    • ReflectionClass::getTraits - Returns an array of traits used by this class
    • ReflectionClass::hasConstant - Checks if constant is defined
    • ReflectionClass::hasMethod - Checks if method is defined
    • ReflectionClass::hasProperty - Checks if property is defined
    • ReflectionClass::implementsInterface - Implements interface
    • ReflectionClass::inNamespace - Checks if in namespace
    • ReflectionClass::isAbstract - Checks if class is abstract
    • ReflectionClass::isCloneable - Returns whether this class is cloneable
    • ReflectionClass::isFinal - Checks if class is final
    • ReflectionClass::isInstance - Checks class for instance
    • ReflectionClass::isInstantiable - Checks if instantiable
    • ReflectionClass::isInterface - Checks if interface
    • ReflectionClass::isInternal - Checks if internal
    • ReflectionClass::isIterateable - Checks if iterateable
    • ReflectionClass::isSubclassOf - Checks if a subclass
    • ReflectionClass::isTrait - Returns whether this is a trait
    • ReflectionClass::isUserDefined - Checks if user defined
    • ReflectionClass::newInstance - Creates a new class instance from given arguments.
    • ReflectionClass::newInstanceArgs - Creates a new class instance from given arguments.
    • ReflectionClass::newInstanceWithoutConstructor - Creates a new class instance without invoking the constructor.
    • ReflectionClass::setStaticPropertyValue - Sets static property value
    • ReflectionClass::__clone - Clones object
    • ReflectionClass::__construct - Constructs a ReflectionClass
    • ReflectionClass::__toString - Returns the string representation of the ReflectionClass object.
    • ReflectionExtension::export - Export
    • ReflectionExtension::getClasses - Gets classes
    • ReflectionExtension::getClassNames - Gets class names
    • ReflectionExtension::getConstants - Gets constants
    • ReflectionExtension::getDependencies - Gets dependencies
    • ReflectionExtension::getFunctions - Gets extension functions
    • ReflectionExtension::getINIEntries - Gets extension ini entries
    • ReflectionExtension::getName - Gets extension name
    • ReflectionExtension::getVersion - Gets extension version
    • ReflectionExtension::info - Print extension info
    • ReflectionExtension::isPersistent - Returns whether this extension is persistent
    • ReflectionExtension::isTemporary - Returns whether this extension is temporary
    • ReflectionExtension::__clone - Clones
    • ReflectionExtension::__construct - Constructs a ReflectionExtension
    • ReflectionExtension::__toString - To string
    • ReflectionFunction::export - Exports function
    • ReflectionFunction::getClosure - Returns a dynamically created closure for the function
    • ReflectionFunction::invoke - Invokes function
    • ReflectionFunction::invokeArgs - Invokes function args
    • ReflectionFunction::isDisabled - Checks if function is disabled
    • ReflectionFunction::__construct - Constructs a ReflectionFunction object
    • ReflectionFunction::__toString - To string
    • ReflectionFunctionAbstract::getClosureThis - Returns this pointer bound to closure
    • ReflectionFunctionAbstract::getDocComment - Gets doc comment
    • ReflectionFunctionAbstract::getEndLine - Gets end line number
    • ReflectionFunctionAbstract::getExtension - Gets extension info
    • ReflectionFunctionAbstract::getExtensionName - Gets extension name
    • ReflectionFunctionAbstract::getFileName - Gets file name
    • ReflectionFunctionAbstract::getName - Gets function name
    • ReflectionFunctionAbstract::getNamespaceName - Gets namespace name
    • ReflectionFunctionAbstract::getNumberOfParameters - Gets number of parameters
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters - Gets number of required parameters
    • ReflectionFunctionAbstract::getParameters - Gets parameters
    • ReflectionFunctionAbstract::getShortName - Gets function short name
    • ReflectionFunctionAbstract::getStartLine - Gets starting line number
    • ReflectionFunctionAbstract::getStaticVariables - Gets static variables
    • ReflectionFunctionAbstract::inNamespace - Checks if function in namespace
    • ReflectionFunctionAbstract::isClosure - Checks if closure
    • ReflectionFunctionAbstract::isDeprecated - Checks if deprecated
    • ReflectionFunctionAbstract::isInternal - Checks if is internal
    • ReflectionFunctionAbstract::isUserDefined - Checks if user defined
    • ReflectionFunctionAbstract::returnsReference - Checks if returns reference
    • ReflectionFunctionAbstract::__clone - Clones function
    • ReflectionFunctionAbstract::__toString - To string
    • ReflectionMethod::export - Export a reflection method.
    • ReflectionMethod::getClosure - Returns a dynamically created closure for the method
    • ReflectionMethod::getDeclaringClass - Gets declaring class for the reflected method.
    • ReflectionMethod::getModifiers - Gets the method modifiers
    • ReflectionMethod::getPrototype - Gets the method prototype (if there is one).
    • ReflectionMethod::invoke - Invoke
    • ReflectionMethod::invokeArgs - Invoke args
    • ReflectionMethod::isAbstract - Checks if method is abstract
    • ReflectionMethod::isConstructor - Checks if method is a constructor
    • ReflectionMethod::isDestructor - Checks if method is a destructor
    • ReflectionMethod::isFinal - Checks if method is final
    • ReflectionMethod::isPrivate - Checks if method is private
    • ReflectionMethod::isProtected - Checks if method is protected
    • ReflectionMethod::isPublic - Checks if method is public
    • ReflectionMethod::isStatic - Checks if method is static
    • ReflectionMethod::setAccessible - Set method accessibility
    • ReflectionMethod::__construct - Constructs a ReflectionMethod
    • ReflectionMethod::__toString - Returns the string representation of the Reflection method object.
    • ReflectionObject::export - Export
    • ReflectionObject::__construct - Constructs a ReflectionObject
    • ReflectionParameter::allowsNull - Checks if null is allowed
    • ReflectionParameter::canBePassedByValue - Returns whether this parameter can be passed by value
    • ReflectionParameter::export - Exports
    • ReflectionParameter::getClass - Get class
    • ReflectionParameter::getDeclaringClass - Gets declaring class
    • ReflectionParameter::getDeclaringFunction - Gets declaring function
    • ReflectionParameter::getDefaultValue - Gets default parameter value
    • ReflectionParameter::getName - Gets parameter name
    • ReflectionParameter::getPosition - Gets parameter position
    • ReflectionParameter::isArray - Checks if parameter expects an array
    • ReflectionParameter::isDefaultValueAvailable - Checks if a default value is available
    • ReflectionParameter::isOptional - Checks if optional
    • ReflectionParameter::isPassedByReference - Checks if passed by reference
    • ReflectionParameter::__clone - Clone
    • ReflectionParameter::__construct - Construct
    • ReflectionParameter::__toString - To string
    • ReflectionProperty::export - Export
    • ReflectionProperty::getDeclaringClass - Gets declaring class
    • ReflectionProperty::getDocComment - Gets doc comment
    • ReflectionProperty::getModifiers - Gets modifiers
    • ReflectionProperty::getName - Gets property name
    • ReflectionProperty::getValue - Gets value
    • ReflectionProperty::isDefault - Checks if default value
    • ReflectionProperty::isPrivate - Checks if property is private
    • ReflectionProperty::isProtected - Checks if property is protected
    • ReflectionProperty::isPublic - Checks if property is public
    • ReflectionProperty::isStatic - Checks if property is static
    • ReflectionProperty::setAccessible - Set property accessibility
    • ReflectionProperty::setValue - Set property value
    • ReflectionProperty::__clone - Clone
    • ReflectionProperty::__construct - Construct a ReflectionProperty object
    • ReflectionProperty::__toString - To string
    • ReflectionZendExtension::export - Export
    • ReflectionZendExtension::getAuthor - Gets author
    • ReflectionZendExtension::getCopyright - Gets copyright
    • ReflectionZendExtension::getName - Gets name
    • ReflectionZendExtension::getURL - Gets URL
    • ReflectionZendExtension::getVersion - Gets version
    • ReflectionZendExtension::__clone - Clone handler
    • ReflectionZendExtension::__construct - Constructor
    • ReflectionZendExtension::__toString - To string handler
    • Reflector::export - Exports
    • Reflector::__toString - To string
    • RegexIterator::accept - Get accept status
    • RegexIterator::getFlags - Get flags
    • RegexIterator::getMode - Returns operation mode.
    • RegexIterator::getPregFlags - Returns the regular expression flags.
    • RegexIterator::getRegex - Returns current regular expression
    • RegexIterator::setFlags - Sets the flags.
    • RegexIterator::setMode - Sets the operation mode.
    • RegexIterator::setPregFlags - Sets the regular expression flags.
    • RegexIterator::__construct - Create a new RegexIterator
    • register_shutdown_function - Register a function for execution on shutdown
    • register_tick_function - Register a function for execution on each tick
    • rename - Renames a file or directory
    • rename_function - Renames orig_name to new_name in the global function table
    • reset - Ustaw wewnętrzny wskaźnik tablicy na jej pierwszy element
    • ResourceBundle::count - Get number of elements in the bundle
    • ResourceBundle::create - Create a resource bundle
    • ResourceBundle::get - Get data from the bundle
    • ResourceBundle::getErrorCode - Get bundle's last error code.
    • ResourceBundle::getErrorMessage - Get bundle's last error message.
    • ResourceBundle::getLocales - Get supported locales
    • restore_error_handler - Restores the previous error handler function
    • restore_exception_handler - Restores the previously defined exception handler function
    • restore_include_path - Restores the value of the include_path configuration option
    • rewind - Rewind the position of a file pointer
    • rewinddir - Ustawia wskaźnik katalogu na początek
    • rmdir - Usuwanie katalogów
    • round - Zaokrągla liczbę zmiennoprzecinkową
    • rpm_close - Closes an RPM file
    • rpm_get_tag - Retrieves a header tag from an RPM file
    • rpm_is_valid - Tests a filename for validity as an RPM file
    • rpm_open - Opens an RPM file
    • rpm_version - Returns a string representing the current version of the rpmreader extension
    • RRDCreator::addArchive - Adds RRA - archive of data values for each data source.
    • RRDCreator::addDataSource - Adds data source definition for RRD database.
    • RRDCreator::save - Saves the RRD database to a file
    • RRDCreator::__construct - Creates new RRDCreator instance
    • RRDGraph::save - Saves the result of query into image
    • RRDGraph::saveVerbose - Saves the RRD database query into image and returns the verbose information about generated graph.
    • RRDGraph::setOptions - Sets the options for rrd graph export
    • RRDGraph::__construct - Creates new RRDGraph instance
    • RRDUpdater::update - Update the RRD database file
    • RRDUpdater::__construct - Creates new RRDUpdater instance
    • rrd_create - Creates rrd database file
    • rrd_error - Gets latest error message.
    • rrd_fetch - Fetch the data for graph as array.
    • rrd_first - Gets the timestamp of the first sample from rrd file.
    • rrd_graph - Creates image from a data.
    • rrd_info - Gets information about rrd file
    • rrd_last - Gets unix timestamp of the last sample.
    • rrd_lastupdate - Gets information about last updated data.
    • rrd_restore - Restores the RRD file from XML dump.
    • rrd_tune - Tunes some RRD database file header options.
    • rrd_update - Updates the RRD database.
    • rrd_version - Gets information about underlying rrdtool library
    • rrd_xport - Exports the information about RRD database.
    • rsort - Sortuj tablicę w porządku odwrotnym
    • rtrim - Strip whitespace (or other characters) from the end of a string
    • runkit_class_adopt - Convert a base class to an inherited class, add ancestral methods when appropriate
    • runkit_class_emancipate - Convert an inherited class to a base class, removes any method whose scope is ancestral
    • runkit_constant_add - Similar to define(), but allows defining in class definitions as well
    • runkit_constant_redefine - Redefine an already defined constant
    • runkit_constant_remove - Remove/Delete an already defined constant
    • runkit_function_add - Add a new function, similar to create_function
    • runkit_function_copy - Copy a function to a new function name
    • runkit_function_redefine - Replace a function definition with a new implementation
    • runkit_function_remove - Remove a function definition
    • runkit_function_rename - Change a function's name
    • runkit_import - Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit_lint - Check the PHP syntax of the specified php code
    • runkit_lint_file - Check the PHP syntax of the specified file
    • runkit_method_add - Dynamically adds a new method to a given class
    • runkit_method_copy - Copies a method from class to another
    • runkit_method_redefine - Dynamically changes the code of the given method
    • runkit_method_remove - Dynamically removes the given method
    • runkit_method_rename - Dynamically changes the name of the given method
    • runkit_return_value_used - Determines if the current functions return value will be used
    • Runkit_Sandbox - Runkit Sandbox Class -- PHP Virtual Machine
    • runkit_sandbox_output_handler - Specify a function to capture and/or process output from a runkit sandbox
    • Runkit_Sandbox_Parent - Runkit Anti-Sandbox Class
    • runkit_superglobals - Return numerically indexed array of registered superglobals
  • s
    • SAMConnection::commit - Commits (completes) the current unit of work.
    • SAMConnection::connect - Establishes a connection to a Messaging Server
    • SAMConnection::disconnect - Disconnects from a Messaging Server
    • SAMConnection::errno - Contains the unique numeric error code of the last executed SAM operation.
    • SAMConnection::error - Contains the text description of the last failed SAM operation.
    • SAMConnection::isConnected - Queries whether a connection is established to a Messaging Server
    • SAMConnection::peek - Read a message from a queue without removing it from the queue.
    • SAMConnection::peekAll - Read one or more messages from a queue without removing it from the queue.
    • SAMConnection::receive - Receive a message from a queue or subscription.
    • SAMConnection::remove - Remove a message from a queue.
    • SAMConnection::rollback - Cancels (rolls back) an in-flight unit of work.
    • SAMConnection::send - Send a message to a queue or publish an item to a topic.
    • SAMConnection::setDebug - Turn on or off additional debugging output.
    • SAMConnection::subscribe - Create a subscription to a specified topic.
    • SAMConnection::unsubscribe - Cancel a subscription to a specified topic.
    • SAMConnection::__construct - Creates a new connection to a Messaging Server
    • SAMMessage::body - The body of the message.
    • SAMMessage::header - The header properties of the message.
    • SAMMessage::__construct - Creates a new Message object
    • SCA::createDataObject - create an SDO
    • SCA::getService - Obtain a proxy for a service
    • scandir - Wypisze wszystkie pliki i katalogi z określonej lokalizacji
    • SCA_LocalProxy::createDataObject - create an SDO
    • SCA_SoapProxy::createDataObject - create an SDO
    • SDO_DAS_ChangeSummary::beginLogging - Begin change logging
    • SDO_DAS_ChangeSummary::endLogging - End change logging
    • SDO_DAS_ChangeSummary::getChangedDataObjects - Get the changed data objects from a change summary
    • SDO_DAS_ChangeSummary::getChangeType - Get the type of change made to an SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldContainer - Get the old container for a deleted SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldValues - Get the old values for a given changed SDO_DataObject
    • SDO_DAS_ChangeSummary::isLogging - Test to see whether change logging is switched on
    • SDO_DAS_DataFactory::addPropertyToType - Adds a property to a type
    • SDO_DAS_DataFactory::addType - Add a new type to a model
    • SDO_DAS_DataFactory::getDataFactory - Get a data factory instance
    • SDO_DAS_DataObject::getChangeSummary - Get a data object's change summary
    • SDO_DAS_Relational::applyChanges - Applies the changes made to a data graph back to the database.
    • SDO_DAS_Relational::createRootDataObject - Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.
    • SDO_DAS_Relational::executePreparedQuery - Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.
    • SDO_DAS_Relational::executeQuery - Executes a given SQL query against a relational database and returns the results as a normalised data graph.
    • SDO_DAS_Relational::__construct - Creates an instance of a Relational Data Access Service
    • SDO_DAS_Setting::getListIndex - Get the list index for a changed many-valued property
    • SDO_DAS_Setting::getPropertyIndex - Get the property index for a changed property
    • SDO_DAS_Setting::getPropertyName - Get the property name for a changed property
    • SDO_DAS_Setting::getValue - Get the old value for the changed property
    • SDO_DAS_Setting::isSet - Test whether a property was set prior to being modified
    • SDO_DAS_XML::addTypes - To load a second or subsequent schema file to a SDO_DAS_XML object
    • SDO_DAS_XML::create - To create SDO_DAS_XML object for a given schema file
    • SDO_DAS_XML::createDataObject - Creates SDO_DataObject for a given namespace URI and type name
    • SDO_DAS_XML::createDocument - Creates an XML Document object from scratch, without the need to load a document from a file or string.
    • SDO_DAS_XML::loadFile - Returns SDO_DAS_XML_Document object for a given path to xml instance document
    • SDO_DAS_XML::loadString - Returns SDO_DAS_XML_Document for a given xml instance string
    • SDO_DAS_XML::saveFile - Saves the SDO_DAS_XML_Document object to a file
    • SDO_DAS_XML::saveString - Saves the SDO_DAS_XML_Document object to a string
    • SDO_DAS_XML_Document::getRootDataObject - Returns the root SDO_DataObject
    • SDO_DAS_XML_Document::getRootElementName - Returns root element's name
    • SDO_DAS_XML_Document::getRootElementURI - Returns root element's URI string
    • SDO_DAS_XML_Document::setEncoding - Sets the given string as encoding
    • SDO_DAS_XML_Document::setXMLDeclaration - Sets the xml declaration
    • SDO_DAS_XML_Document::setXMLVersion - Sets the given string as xml version
    • SDO_DataFactory::create - Create an SDO_DataObject
    • SDO_DataObject::clear - Clear an SDO_DataObject's properties
    • SDO_DataObject::createDataObject - Create a child SDO_DataObject
    • SDO_DataObject::getContainer - Get a data object's container
    • SDO_DataObject::getSequence - Get the sequence for a data object
    • SDO_DataObject::getTypeName - Return the name of the type for a data object.
    • SDO_DataObject::getTypeNamespaceURI - Return the namespace URI of the type for a data object.
    • SDO_Exception::getCause - Get the cause of the exception.
    • SDO_List::insert - Insert into a list
    • SDO_Model_Property::getContainingType - Get the SDO_Model_Type which contains this property
    • SDO_Model_Property::getDefault - Get the default value for the property
    • SDO_Model_Property::getName - Get the name of the SDO_Model_Property
    • SDO_Model_Property::getType - Get the SDO_Model_Type of the property
    • SDO_Model_Property::isContainment - Test to see if the property defines a containment relationship
    • SDO_Model_Property::isMany - Test to see if the property is many-valued
    • SDO_Model_ReflectionDataObject::export - Get a string describing the SDO_DataObject.
    • SDO_Model_ReflectionDataObject::getContainmentProperty - Get the property which defines the containment relationship to the data object
    • SDO_Model_ReflectionDataObject::getInstanceProperties - Get the instance properties of the SDO_DataObject
    • SDO_Model_ReflectionDataObject::getType - Get the SDO_Model_Type for the SDO_DataObject
    • SDO_Model_ReflectionDataObject::__construct - Construct an SDO_Model_ReflectionDataObject
    • SDO_Model_Type::getBaseType - Get the base type for this type
    • SDO_Model_Type::getName - Get the name of the type
    • SDO_Model_Type::getNamespaceURI - Get the namespace URI of the type
    • SDO_Model_Type::getProperties - Get the SDO_Model_Property objects defined for the type
    • SDO_Model_Type::getProperty - Get an SDO_Model_Property of the type
    • SDO_Model_Type::isAbstractType - Test to see if this SDO_Model_Type is an abstract data type
    • SDO_Model_Type::isDataType - Test to see if this SDO_Model_Type is a primitive data type
    • SDO_Model_Type::isInstance - Test for an SDO_DataObject being an instance of this SDO_Model_Type
    • SDO_Model_Type::isOpenType - Test to see if this type is an open type
    • SDO_Model_Type::isSequencedType - Test to see if this is a sequenced type
    • SDO_Sequence::getProperty - Return the property for the specified sequence index.
    • SDO_Sequence::insert - Insert into a sequence
    • SDO_Sequence::move - Move an item to another sequence position
    • SeekableIterator::seek - Seeks to a position
    • sem_acquire - Acquire a semaphore
    • sem_get - Get a semaphore id
    • sem_release - Release a semaphore
    • sem_remove - Remove a semaphore
    • Serializable::serialize - String representation of object
    • Serializable::unserialize - Constructs the object
    • serialize - Generates a storable representation of a value
    • SessionHandler::close - Close the session
    • SessionHandler::destroy - Destroy a session
    • SessionHandler::gc - Cleanup old sessions
    • SessionHandler::open - Initialize session
    • SessionHandler::read - Read session data
    • SessionHandler::write - The write purpose
    • session_cache_expire - Zwróć bieżący czas przedawnienia pamięci podręcznej
    • session_cache_limiter - Pobierz i/lub ustaw bieżący ogranicznik pamięci podręcznej
    • session_commit - Alias dla session_write_close
    • session_decode - Dekoduje dane sesji ze stringu
    • session_destroy - Niszczy wszystkie dane zarejestrowane w sesji
    • session_encode - Koduje dane bieżącej sesji do postaci ciągu tekstowego
    • session_get_cookie_params - Pobierz parametry ciasteczka sesyjnego
    • session_id - Pobierz i/lub ustaw identyfikator bieżącej sesji
    • session_is_registered - Sprawdź czy globalna zmienna jest zarejestrowana w sesji
    • session_module_name - Pobierz i/lub ustaw moduł bieżącej sesji
    • session_name - Pobierz i/lub ustaw nazwę bieżącej sesji
    • session_pgsql_add_error - Increments error counts and sets last error message
    • session_pgsql_get_error - Returns number of errors and last error message
    • session_pgsql_get_field - Get custom field value
    • session_pgsql_reset - Reset connection to session database servers
    • session_pgsql_set_field - Set custom field value
    • session_pgsql_status - Get current save handler status
    • session_regenerate_id - Zmienia bieżący identyfikator sesji na nowy, automatycznie wygenerowany
    • session_register - Zarejestruj jedną lub więcej zmiennych globalnych w bieżącej sesji
    • session_register_shutdown - Session shutdown function
    • session_save_path - Pobierz i/lub ustaw ścieżkę zapisu bieżącej sesji
    • session_set_cookie_params - Ustaw parametry ciasteczka sesyjnego
    • session_set_save_handler - Ustawia funkcje użytkownika do przechowywania sesji
    • session_start - Inicjalizuj dane sesji
    • session_status - Returns the current session status
    • session_unregister - Wyrejestruj zmienną globalną z bieżącej sesji
    • session_unset - Zwolnij wszystkie zmienne sesyjne
    • session_write_close - Zapisz dane i zakończ sesję
    • setcookie - Send a cookie
    • setlocale - Set locale information
    • setproctitle - Set the process title
    • setrawcookie - Send a cookie without urlencoding the cookie value
    • setthreadtitle - Set the thread title
    • settype - Set the type of a variable
    • set_error_handler - Sets a user-defined error handler function
    • set_exception_handler - Sets a user-defined exception handler function
    • set_file_buffer - Alias dla stream_set_write_buffer
    • set_include_path - Sets the include_path configuration option
    • set_magic_quotes_runtime - Sets the current active configuration setting of magic_quotes_runtime
    • set_socket_blocking - Alias dla stream_set_blocking
    • set_time_limit - Limits the maximum execution time
    • sha1 - Calculate the sha1 hash of a string
    • sha1_file - Calculate the sha1 hash of a file
    • shell_exec - Execute command via shell and return the complete output as a string
    • shmop_close - Close shared memory block
    • shmop_delete - Delete shared memory block
    • shmop_open - Create or open shared memory block
    • shmop_read - Read data from shared memory block
    • shmop_size - Get size of shared memory block
    • shmop_write - Write data into shared memory block
    • shm_attach - Creates or open a shared memory segment
    • shm_detach - Disconnects from shared memory segment
    • shm_get_var - Returns a variable from shared memory
    • shm_has_var - Check whether a specific entry exists
    • shm_put_var - Inserts or updates a variable in shared memory
    • shm_remove - Removes shared memory from Unix systems
    • shm_remove_var - Removes a variable from shared memory
    • show_source - Alias dla highlight_file
    • shuffle - Przetasuj tablicę
    • signeurlpaiement - Obtain the payment url (needs 2 arguments)
    • similar_text - Calculate the similarity between two strings
    • SimpleXMLElement::addAttribute - Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild - Adds a child element to the XML node
    • SimpleXMLElement::asXML - Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes - Identifies an element's attributes
    • SimpleXMLElement::children - Finds children of given node
    • SimpleXMLElement::count - Counts the children of an element
    • SimpleXMLElement::getDocNamespaces - Returns namespaces declared in document
    • SimpleXMLElement::getName - Gets the name of the XML element
    • SimpleXMLElement::getNamespaces - Returns namespaces used in document
    • SimpleXMLElement::registerXPathNamespace - Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::saveXML - Alias dla SimpleXMLElement::asXML
    • SimpleXMLElement::xpath - Runs XPath query on XML data
    • SimpleXMLElement::__construct - Creates a new SimpleXMLElement object
    • SimpleXMLIterator::current - Returns the current element
    • SimpleXMLIterator::getChildren - Returns the sub-elements of the current element
    • SimpleXMLIterator::hasChildren - Checks whether the current element has sub elements.
    • SimpleXMLIterator::key - Return current key
    • SimpleXMLIterator::next - Move to next element
    • SimpleXMLIterator::rewind - Rewind to the first element
    • SimpleXMLIterator::valid - Check whether the current element is valid
    • simplexml_import_dom - Get a SimpleXMLElement object from a DOM node.
    • simplexml_load_file - Interprets an XML file into an object
    • simplexml_load_string - Interprets a string of XML into an object
    • sin - Oblicza sinus kąta
    • sinh - Sinus hiperboliczny
    • sizeof - Alias dla count
    • sleep - Delay execution
    • snmp2_get - Fetch an SNMP object
    • snmp2_getnext - Fetch the SNMP object which follows the given object id
    • snmp2_real_walk - Return all objects including their respective object ID within the specified one
    • snmp2_set - Set the value of an SNMP object
    • snmp2_walk - Fetch all the SNMP objects from an agent
    • snmp3_get - Fetch an SNMP object
    • snmp3_getnext - Fetch the SNMP object which follows the given object id
    • snmp3_real_walk - Return all objects including their respective object ID within the specified one
    • snmp3_set - Set the value of an SNMP object
    • snmp3_walk - Fetch all the SNMP objects from an agent
    • SNMP::close - Close SNMP session
    • SNMP::get - Fetch an SNMP object
    • SNMP::getErrno - Get last error code
    • SNMP::getError - Get last error message
    • SNMP::getnext - Fetch an SNMP object which follows the given object id
    • SNMP::set - Set the value of an SNMP object
    • SNMP::setSecurity - Configures security-related SNMPv3 session parameters
    • SNMP::walk - Fetch SNMP object subtree
    • SNMP::__construct - Creates SNMP instance representing session to remote SNMP agent
    • snmpget - Fetch an SNMP object
    • snmpgetnext - Fetch the SNMP object which follows the given object id
    • snmprealwalk - Return all objects including their respective object ID within the specified one
    • snmpset - Set the value of an SNMP object
    • snmpwalk - Fetch all the SNMP objects from an agent
    • snmpwalkoid - Query for a tree of information about a network entity
    • snmp_get_quick_print - Fetches the current value of the UCD library's quick_print setting
    • snmp_get_valueretrieval - Return the method how the SNMP values will be returned
    • snmp_read_mib - Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print - Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print - Return all objects including their respective object id within the specified one
    • snmp_set_oid_output_format - Set the OID output format
    • snmp_set_quick_print - Set the value of quick_print within the UCD SNMP library
    • snmp_set_valueretrieval - Specify the method how the SNMP values will be returned
    • SoapClient::SoapClient - SoapClient constructor
    • SoapClient::__call - Calls a SOAP function (deprecated)
    • SoapClient::__construct - SoapClient constructor
    • SoapClient::__doRequest - Performs a SOAP request
    • SoapClient::__getFunctions - Returns list of available SOAP functions
    • SoapClient::__getLastRequest - Returns last SOAP request
    • SoapClient::__getLastRequestHeaders - Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse - Returns last SOAP response
    • SoapClient::__getLastResponseHeaders - Returns the SOAP headers from the last response
    • SoapClient::__getTypes - Returns a list of SOAP types
    • SoapClient::__setCookie - The __setCookie purpose
    • SoapClient::__setLocation - Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders - Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall - Calls a SOAP function
    • SoapFault::SoapFault - SoapFault constructor
    • SoapFault::__construct - SoapFault constructor
    • SoapFault::__toString - Obtain a string representation of a SoapFault
    • SoapHeader::SoapHeader - SoapHeader constructor
    • SoapHeader::__construct - SoapHeader constructor
    • SoapParam::SoapParam - SoapParam constructor
    • SoapParam::__construct - SoapParam constructor
    • SoapServer::addFunction - Adds one or more functions to handle SOAP requests
    • SoapServer::addSoapHeader - Add a SOAP header to the response
    • SoapServer::fault - Issue SoapServer fault indicating an error
    • SoapServer::getFunctions - Returns list of defined functions
    • SoapServer::handle - Handles a SOAP request
    • SoapServer::setClass - Sets the class which handles SOAP requests
    • SoapServer::setObject - Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence - Sets SoapServer persistence mode
    • SoapServer::SoapServer - SoapServer constructor
    • SoapServer::__construct - SoapServer constructor
    • SoapVar::SoapVar - SoapVar constructor
    • SoapVar::__construct - SoapVar constructor
    • Socket context options - Socket context option listing
    • socket_accept - Accepts a connection on a socket
    • socket_bind - Binds a name to a socket
    • socket_clear_error - Clears the error on the socket or the last error code
    • socket_close - Closes a socket resource
    • socket_connect - Initiates a connection on a socket
    • socket_create - Create a socket (endpoint for communication)
    • socket_create_listen - Opens a socket on port to accept connections
    • socket_create_pair - Creates a pair of indistinguishable sockets and stores them in an array
    • socket_getpeername - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_get_option - Gets socket options for the socket
    • socket_get_status - Alias dla stream_get_meta_data
    • socket_last_error - Returns the last error on the socket
    • socket_listen - Listens for a connection on a socket
    • socket_read - Reads a maximum of length bytes from a socket
    • socket_recv - Receives data from a connected socket
    • socket_recvfrom - Receives data from a socket whether or not it is connection-oriented
    • socket_select - Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send - Sends data to a connected socket
    • socket_sendto - Sends a message to a socket, whether it is connected or not
    • socket_set_block - Sets blocking mode on a socket resource
    • socket_set_blocking - Alias dla stream_set_blocking
    • socket_set_nonblock - Sets nonblocking mode for file descriptor fd
    • socket_set_option - Sets socket options for the socket
    • socket_set_timeout - Alias dla stream_set_timeout
    • socket_shutdown - Shuts down a socket for receiving, sending, or both
    • socket_strerror - Return a string describing a socket error
    • socket_write - Write to a socket
    • SolrClient::addDocument - Adds a document to the index
    • SolrClient::addDocuments - Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit - Finalizes all add/deletes made to the index
    • SolrClient::deleteById - Delete by Id
    • SolrClient::deleteByIds - Deletes by Ids
    • SolrClient::deleteByQueries - Removes all documents matching any of the queries
    • SolrClient::deleteByQuery - Deletes all documents matching the given query
    • SolrClient::getDebug - Returns the debug data for the last connection attempt
    • SolrClient::getOptions - Returns the client options set internally
    • SolrClient::optimize - Defragments the index
    • SolrClient::ping - Checks if Solr server is still up
    • SolrClient::query - Sends a query to the server
    • SolrClient::request - Sends a raw update request
    • SolrClient::rollback - Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter - Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet - Changes the specified servlet type to a new value
    • SolrClient::threads - Checks the threads status
    • SolrClient::__construct - Constructor for the SolrClient object
    • SolrClient::__destruct - Destructor for SolrClient
    • SolrClientException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrDocument::addField - Adds a field to the document
    • SolrDocument::clear - Drops all the fields in the document
    • SolrDocument::current - Retrieves the current field
    • SolrDocument::deleteField - Removes a field from the document
    • SolrDocument::fieldExists - Checks if a field exists in the document
    • SolrDocument::getField - Retrieves a field by name
    • SolrDocument::getFieldCount - Returns the number of fields in this document
    • SolrDocument::getFieldNames - Returns an array of fields names in the document
    • SolrDocument::getInputDocument - Returns a SolrInputDocument equivalent of the object
    • SolrDocument::key - Retrieves the current key
    • SolrDocument::merge - Merges source to the current SolrDocument
    • SolrDocument::next - Moves the internal pointer to the next field
    • SolrDocument::offsetExists - Checks if a particular field exists
    • SolrDocument::offsetGet - Retrieves a field
    • SolrDocument::offsetSet - Adds a field to the document
    • SolrDocument::offsetUnset - Removes a field
    • SolrDocument::reset - This is an alias to SolrDocument::clear()
    • SolrDocument::rewind - Resets the internal pointer to the beginning
    • SolrDocument::serialize - Used for custom serialization
    • SolrDocument::sort - Sorts the fields in the document
    • SolrDocument::toArray - Returns an array representation of the document
    • SolrDocument::unserialize - Custom serialization of SolrDocument objects
    • SolrDocument::valid - Checks if the current position internally is still valid
    • SolrDocument::__clone - Creates a copy of a SolrDocument object
    • SolrDocument::__construct - Constructor
    • SolrDocument::__destruct - Destructor
    • SolrDocument::__get - Acess the field as a property
    • SolrDocument::__isset - Checks if a field exists
    • SolrDocument::__set - Adds another field to the document
    • SolrDocument::__unset - Removes a field from the document
    • SolrDocumentField::__construct - Constructor
    • SolrDocumentField::__destruct - Destructor
    • SolrException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrGenericResponse::__construct - Constructor
    • SolrGenericResponse::__destruct - Destructor
    • SolrIllegalArgumentException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrIllegalOperationException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrInputDocument::addField - Adds a field to the document
    • SolrInputDocument::clear - Resets the input document
    • SolrInputDocument::deleteField - Removes a field from the document
    • SolrInputDocument::fieldExists - Checks if a field exists
    • SolrInputDocument::getBoost - Retrieves the current boost value for the document
    • SolrInputDocument::getField - Retrieves a field by name
    • SolrInputDocument::getFieldBoost - Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount - Returns the number of fields in the document
    • SolrInputDocument::getFieldNames - Returns an array containing all the fields in the document
    • SolrInputDocument::merge - Merges one input document into another
    • SolrInputDocument::reset - This is an alias of SolrInputDocument::clear
    • SolrInputDocument::setBoost - Sets the boost value for this document
    • SolrInputDocument::setFieldBoost - Sets the index-time boost value for a field
    • SolrInputDocument::sort - Sorts the fields within the document
    • SolrInputDocument::toArray - Returns an array representation of the input document
    • SolrInputDocument::__clone - Creates a copy of a SolrDocument
    • SolrInputDocument::__construct - Constructor
    • SolrInputDocument::__destruct - Destructor
    • SolrModifiableParams::__construct - Constructor
    • SolrModifiableParams::__destruct - Destructor
    • SolrObject::getPropertyNames - Returns an array of all the names of the properties
    • SolrObject::offsetExists - Checks if the property exists
    • SolrObject::offsetGet - Used to retrieve a property
    • SolrObject::offsetSet - Sets the value for a property
    • SolrObject::offsetUnset - Sets the value for the property
    • SolrObject::__construct - Creates Solr object
    • SolrObject::__destruct - Destructor
    • SolrParams::add - This is an alias for SolrParams::addParam
    • SolrParams::addParam - Adds a parameter to the object
    • SolrParams::get - This is an alias for SolrParams::getParam
    • SolrParams::getParam - Returns a parameter value
    • SolrParams::getParams - Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams - Returns an array of URL-encoded parameters
    • SolrParams::serialize - Used for custom serialization
    • SolrParams::set - An alias of SolrParams::setParam
    • SolrParams::setParam - Sets the parameter to the specified value
    • SolrParams::toString - Returns all the name-value pair parameters in the object
    • SolrParams::unserialize - Used for custom serialization
    • SolrPingResponse::getResponse - Returns the response from the server
    • SolrPingResponse::__construct - Constructor
    • SolrPingResponse::__destruct - Destructor
    • SolrQuery::addFacetDateField - Maps to facet.date
    • SolrQuery::addFacetDateOther - Adds another facet.date.other parameter
    • SolrQuery::addFacetField - Adds another field to the facet
    • SolrQuery::addFacetQuery - Adds a facet query
    • SolrQuery::addField - Specifies which fields to return in the result
    • SolrQuery::addFilterQuery - Specifies a filter query
    • SolrQuery::addHighlightField - Maps to hl.fl
    • SolrQuery::addMltField - Sets a field to use for similarity
    • SolrQuery::addMltQueryField - Maps to mlt.qf
    • SolrQuery::addSortField - Used to control how the results should be sorted
    • SolrQuery::addStatsFacet - Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField - Maps to stats.field parameter
    • SolrQuery::getFacet - Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd - Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields - Returns all the facet.date fields
    • SolrQuery::getFacetDateGap - Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd - Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther - Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart - Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields - Returns all the facet fields
    • SolrQuery::getFacetLimit - Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod - Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount - Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing - Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset - Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix - Returns the facet prefix
    • SolrQuery::getFacetQueries - Returns all the facet queries
    • SolrQuery::getFacetSort - Returns the facet sort type
    • SolrQuery::getFields - Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries - Returns an array of filter queries
    • SolrQuery::getHighlight - Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField - Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields - Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter - Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter - Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize - Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm - Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength - Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars - Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous - Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars - Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern - Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop - Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch - Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost - Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre - Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets - Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter - Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt - Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost - Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount - Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields - Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms - Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens - Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength - Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency - Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency - Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength - Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields - Returns the query fields and their boosts
    • SolrQuery::getQuery - Returns the main query
    • SolrQuery::getRows - Returns the maximum number of documents
    • SolrQuery::getSortFields - Returns all the sort fields
    • SolrQuery::getStart - Returns the offset in the complete result set
    • SolrQuery::getStats - Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets - Returns all the stats facets that were set
    • SolrQuery::getStatsFields - Returns all the statistics fields
    • SolrQuery::getTerms - Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField - Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound - Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound - Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit - Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound - Returns the term to start at
    • SolrQuery::getTermsMaxCount - Returns the maximum document frequency
    • SolrQuery::getTermsMinCount - Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix - Returns the term prefix
    • SolrQuery::getTermsReturnRaw - Whether or not to return raw characters
    • SolrQuery::getTermsSort - Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound - Returns the term to stop at
    • SolrQuery::getTimeAllowed - Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeFacetDateField - Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther - Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField - Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery - Removes one of the facet.query parameters
    • SolrQuery::removeField - Removes a field from the list of fields
    • SolrQuery::removeFilterQuery - Removes a filter query
    • SolrQuery::removeHighlightField - Removes one of the fields used for highlighting
    • SolrQuery::removeMltField - Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField - Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField - Removes one of the sort fields
    • SolrQuery::removeStatsFacet - Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField - Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler - Toggles the echoHandler parameter
    • SolrQuery::setEchoParams - Determines what kind of parameters to include in the response
    • SolrQuery::setExplainOther - Sets the explainOther common query parameter
    • SolrQuery::setFacet - Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd - Maps to facet.date.end
    • SolrQuery::setFacetDateGap - Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd - Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart - Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency - Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit - Maps to facet.limit
    • SolrQuery::setFacetMethod - Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount - Maps to facet.mincount
    • SolrQuery::setFacetMissing - Maps to facet.missing
    • SolrQuery::setFacetOffset - Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix - Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort - Determines the ordering of the facet field constraints
    • SolrQuery::setHighlight - Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField - Specifies the backup field to use
    • SolrQuery::setHighlightFormatter - Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter - Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize - The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm - Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength - Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars - Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous - Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars - Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern - Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop - Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch - Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost - Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre - Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets - Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter - Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt - Enables or disables moreLikeThis
    • SolrQuery::setMltBoost - Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount - Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms - Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens - Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength - Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency - Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency - Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength - Sets the minimum word length
    • SolrQuery::setOmitHeader - Exclude the header from the returned results
    • SolrQuery::setQuery - Sets the search query
    • SolrQuery::setRows - Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo - Flag to show debug information
    • SolrQuery::setStart - Specifies the number of rows to skip
    • SolrQuery::setStats - Enables or disables the Stats component
    • SolrQuery::setTerms - Enables or disables the TermsComponent
    • SolrQuery::setTermsField - Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound - Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound - Include the upper bound term in the result set
    • SolrQuery::setTermsLimit - Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound - Specifies the Term to start from
    • SolrQuery::setTermsMaxCount - Sets the maximum document frequency
    • SolrQuery::setTermsMinCount - Sets the minimum document frequency
    • SolrQuery::setTermsPrefix - Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw - Return the raw characters of the indexed term
    • SolrQuery::setTermsSort - Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound - Sets the term to stop at
    • SolrQuery::setTimeAllowed - The time allowed for search to finish
    • SolrQuery::__construct - Constructor
    • SolrQuery::__destruct - Destructor
    • SolrQueryResponse::__construct - Constructor
    • SolrQueryResponse::__destruct - Destructor
    • SolrResponse::getDigestedResponse - Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus - Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage - Returns more details on the HTTP status
    • SolrResponse::getRawRequest - Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders - Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse - Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders - Returns the raw response headers from the server
    • SolrResponse::getRequestUrl - Returns the full URL the request was sent to
    • SolrResponse::getResponse - Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode - Sets the parse mode
    • SolrResponse::success - Was the request a success
    • SolrUpdateResponse::__construct - Constructor
    • SolrUpdateResponse::__destruct - Destructor
    • SolrUtils::digestXmlResponse - Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars - Escapes a lucene query string
    • SolrUtils::getSolrVersion - Returns the current version of the Solr extension
    • SolrUtils::queryPhrase - Prepares a phrase from an unescaped lucene string
    • solr_get_version - Returns the current version of the Apache Solr extension
    • sort - Sortuje tablicę
    • soundex - Calculate the soundex key of a string
    • SphinxClient::addQuery - Add query to multi-query batch
    • SphinxClient::buildExcerpts - Build text snippets
    • SphinxClient::buildKeywords - Extract keywords from query
    • SphinxClient::close - Closes previously opened persistent connection
    • SphinxClient::escapeString - Escape special characters
    • SphinxClient::getLastError - Get the last error message
    • SphinxClient::getLastWarning - Get the last warning
    • SphinxClient::open - Opens persistent connection to the server
    • SphinxClient::query - Execute search query
    • SphinxClient::resetFilters - Clear all filters
    • SphinxClient::resetGroupBy - Clear all group-by settings
    • SphinxClient::runQueries - Run a batch of search queries
    • SphinxClient::setArrayResult - Change the format of result set array
    • SphinxClient::setConnectTimeout - Set connection timeout
    • SphinxClient::setFieldWeights - Set field weights
    • SphinxClient::setFilter - Add new integer values set filter
    • SphinxClient::setFilterFloatRange - Add new float range filter
    • SphinxClient::setFilterRange - Add new integer range filter
    • SphinxClient::setGeoAnchor - Set anchor point for a geosphere distance calculations
    • SphinxClient::setGroupBy - Set grouping attribute
    • SphinxClient::setGroupDistinct - Set attribute name for per-group distinct values count calculations
    • SphinxClient::setIDRange - Set a range of accepted document IDs
    • SphinxClient::setIndexWeights - Set per-index weights
    • SphinxClient::setLimits - Set offset and limit of the result set
    • SphinxClient::setMatchMode - Set full-text query matching mode
    • SphinxClient::setMaxQueryTime - Set maximum query time
    • SphinxClient::setOverride - Sets temporary per-document attribute value overrides
    • SphinxClient::setRankingMode - Set ranking mode
    • SphinxClient::setRetries - Set retry count and delay
    • SphinxClient::setSelect - Set select clause
    • SphinxClient::setServer - Set searchd host and port
    • SphinxClient::setSortMode - Set matches sorting mode
    • SphinxClient::status - Queries searchd status
    • SphinxClient::updateAttributes - Update document attributes
    • SphinxClient::__construct - Create a new SphinxClient object
    • SplDoublyLinkedList::bottom - Peeks at the node from the beginning of the doubly linked list
    • SplDoublyLinkedList::count - Counts the number of elements in the doubly linked list.
    • SplDoublyLinkedList::current - Return current array entry
    • SplDoublyLinkedList::getIteratorMode - Returns the mode of iteration
    • SplDoublyLinkedList::isEmpty - Checks whether the doubly linked list is empty.
    • SplDoublyLinkedList::key - Return current node index
    • SplDoublyLinkedList::next - Move to next entry
    • SplDoublyLinkedList::offsetExists - Returns whether the requested $index exists
    • SplDoublyLinkedList::offsetGet - Returns the value at the specified $index
    • SplDoublyLinkedList::offsetSet - Sets the value at the specified $index to $newval
    • SplDoublyLinkedList::offsetUnset - Unsets the value at the specified $index
    • SplDoublyLinkedList::pop - Pops a node from the end of the doubly linked list
    • SplDoublyLinkedList::prev - Move to previous entry
    • SplDoublyLinkedList::push - Pushes an element at the end of the doubly linked list
    • SplDoublyLinkedList::rewind - Rewind iterator back to the start
    • SplDoublyLinkedList::setIteratorMode - Sets the mode of iteration
    • SplDoublyLinkedList::shift - Shifts a node from the beginning of the doubly linked list
    • SplDoublyLinkedList::top - Peeks at the node from the end of the doubly linked list
    • SplDoublyLinkedList::unshift - Prepends the doubly linked list with an element
    • SplDoublyLinkedList::valid - Check whether the doubly linked list contains more nodes
    • SplDoublyLinkedList::__construct - Constructs a new doubly linked list
    • SplEnum::getConstList - Returns all consts (possible values) as an array.
    • SplFileInfo::getATime - Gets last access time of the file
    • SplFileInfo::getBasename - Gets the base name of the file
    • SplFileInfo::getCTime - Gets the inode change time
    • SplFileInfo::getExtension - Gets the file extension
    • SplFileInfo::getFileInfo - Gets an SplFileInfo object for the file
    • SplFileInfo::getFilename - Gets the filename
    • SplFileInfo::getGroup - Gets the file group
    • SplFileInfo::getInode - Gets the inode for the file
    • SplFileInfo::getLinkTarget - Gets the target of a link
    • SplFileInfo::getMTime - Gets the last modified time
    • SplFileInfo::getOwner - Gets the owner of the file
    • SplFileInfo::getPath - Gets the path without filename
    • SplFileInfo::getPathInfo - Gets an SplFileInfo object for the path
    • SplFileInfo::getPathname - Gets the path to the file
    • SplFileInfo::getPerms - Gets file permissions
    • SplFileInfo::getRealPath - Gets absolute path to file
    • SplFileInfo::getSize - Gets file size
    • SplFileInfo::getType - Gets file type
    • SplFileInfo::isDir - Tells if the file is a directory
    • SplFileInfo::isExecutable - Tells if the file is executable
    • SplFileInfo::isFile - Tells if the object references a regular file
    • SplFileInfo::isLink - Tells if the file is a link
    • SplFileInfo::isReadable - Tells if file is readable
    • SplFileInfo::isWritable - Tells if the entry is writable
    • SplFileInfo::openFile - Gets an SplFileObject object for the file
    • SplFileInfo::setFileClass - Sets the class name used with SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Sets the class used with getFileInfo and getPathInfo
    • SplFileInfo::__construct - Construct a new SplFileInfo object
    • SplFileInfo::__toString - Returns the path to the file as a string
    • SplFileObject::current - Retrieve current line of file
    • SplFileObject::eof - Reached end of file
    • SplFileObject::fflush - Flushes the output to the file
    • SplFileObject::fgetc - Gets character from file
    • SplFileObject::fgetcsv - Gets line from file and parse as CSV fields
    • SplFileObject::fgets - Gets line from file
    • SplFileObject::fgetss - Gets line from file and strip HTML tags
    • SplFileObject::flock - Portable file locking
    • SplFileObject::fpassthru - Output all remaining data on a file pointer
    • SplFileObject::fputcsv - Output a field array as a CSV line
    • SplFileObject::fscanf - Parses input from file according to a format
    • SplFileObject::fseek - Seek to a position
    • SplFileObject::fstat - Gets information about the file
    • SplFileObject::ftell - Return current file position
    • SplFileObject::ftruncate - Truncates the file to a given length
    • SplFileObject::fwrite - Write to file
    • SplFileObject::getChildren - No purpose
    • SplFileObject::getCsvControl - Get the delimiter and enclosure character for CSV
    • SplFileObject::getCurrentLine - Alias of SplFileObject::fgets
    • SplFileObject::getFlags - Gets flags for the SplFileObject
    • SplFileObject::getMaxLineLen - Get maximum line length
    • SplFileObject::hasChildren - SplFileObject does not have children
    • SplFileObject::key - Get line number
    • SplFileObject::next - Read next line
    • SplFileObject::rewind - Rewind the file to the first line
    • SplFileObject::seek - Seek to specified line
    • SplFileObject::setCsvControl - Set the delimiter and enclosure character for CSV
    • SplFileObject::setFlags - Sets flags for the SplFileObject
    • SplFileObject::setMaxLineLen - Set maximum line length
    • SplFileObject::valid - Not at EOF
    • SplFileObject::__construct - Construct a new file object.
    • SplFileObject::__toString - Alias of SplFileObject::current
    • SplFixedArray::count - Returns the size of the array
    • SplFixedArray::current - Return current array entry
    • SplFixedArray::fromArray - Import a PHP array in a SplFixedArray instance
    • SplFixedArray::getSize - Gets the size of the array
    • SplFixedArray::key - Return current array index
    • SplFixedArray::next - Move to next entry
    • SplFixedArray::offsetExists - Returns whether the requested index exists
    • SplFixedArray::offsetGet - Returns the value at the specified index
    • SplFixedArray::offsetSet - Sets a new value at a specified index
    • SplFixedArray::offsetUnset - Unsets the value at the specified $index
    • SplFixedArray::rewind - Rewind iterator back to the start
    • SplFixedArray::setSize - Change the size of an array
    • SplFixedArray::toArray - Returns a PHP array from the fixed array
    • SplFixedArray::valid - Check whether the array contains more elements
    • SplFixedArray::__construct - Constructs a new fixed array
    • SplHeap::compare - Compare elements in order to place them correctly in the heap while sifting up.
    • SplHeap::count - Counts the number of elements in the heap.
    • SplHeap::current - Return current node pointed by the iterator
    • SplHeap::extract - Extracts a node from top of the heap and sift up.
    • SplHeap::insert - Inserts an element in the heap by sifting it up.
    • SplHeap::isEmpty - Checks whether the heap is empty.
    • SplHeap::key - Return current node index
    • SplHeap::next - Move to the next node
    • SplHeap::recoverFromCorruption - Recover from the corrupted state and allow further actions on the heap.
    • SplHeap::rewind - Rewind iterator back to the start (no-op)
    • SplHeap::top - Peeks at the node from the top of the heap
    • SplHeap::valid - Check whether the heap contains more nodes
    • SplHeap::__construct - Constructs a new empty heap
    • split - Split string into array by regular expression
    • spliti - Split string into array by regular expression case insensitive
    • SplMaxHeap::compare - Compare elements in order to place them correctly in the heap while sifting up.
    • SplMinHeap::compare - Compare elements in order to place them correctly in the heap while sifting up.
    • SplObjectStorage::addAll - Adds all objects from another storage
    • SplObjectStorage::attach - Adds an object in the storage
    • SplObjectStorage::contains - Checks if the storage contains a specific object
    • SplObjectStorage::count - Returns the number of objects in the storage
    • SplObjectStorage::current - Returns the current storage entry
    • SplObjectStorage::detach - Removes an object from the storage
    • SplObjectStorage::getHash - Calculate a unique identifier for the contained objects
    • SplObjectStorage::getInfo - Returns the data associated with the current iterator entry
    • SplObjectStorage::key - Returns the index at which the iterator currently is
    • SplObjectStorage::next - Move to the next entry
    • SplObjectStorage::offsetExists - Checks whether an object exists in the storage
    • SplObjectStorage::offsetGet - Returns the data associated with an object
    • SplObjectStorage::offsetSet - Associates data to an object in the storage
    • SplObjectStorage::offsetUnset - Removes an object from the storage
    • SplObjectStorage::removeAll - Removes objects contained in another storage from the current storage
    • SplObjectStorage::removeAllExcept - Removes all objects except for those contained in another storage from the current storage
    • SplObjectStorage::rewind - Rewind the iterator to the first storage element
    • SplObjectStorage::serialize - Serializes the storage
    • SplObjectStorage::setInfo - Sets the data associated with the current iterator entry
    • SplObjectStorage::unserialize - Unserializes a storage from its string representation
    • SplObjectStorage::valid - Returns if the current iterator entry is valid
    • SplObserver::update - Receive update from subject
    • SplPriorityQueue::compare - Compare priorities in order to place elements correctly in the heap while sifting up.
    • SplPriorityQueue::count - Counts the number of elements in the queue.
    • SplPriorityQueue::current - Return current node pointed by the iterator
    • SplPriorityQueue::extract - Extracts a node from top of the heap and sift up.
    • SplPriorityQueue::insert - Inserts an element in the queue by sifting it up.
    • SplPriorityQueue::isEmpty - Checks whether the queue is empty.
    • SplPriorityQueue::key - Return current node index
    • SplPriorityQueue::next - Move to the next node
    • SplPriorityQueue::recoverFromCorruption - Recover from the corrupted state and allow further actions on the queue.
    • SplPriorityQueue::rewind - Rewind iterator back to the start (no-op)
    • SplPriorityQueue::setExtractFlags - Sets the mode of extraction
    • SplPriorityQueue::top - Peeks at the node from the top of the queue
    • SplPriorityQueue::valid - Check whether the queue contains more nodes
    • SplPriorityQueue::__construct - Constructs a new empty queue
    • SplQueue::dequeue - Dequeues a node from the queue
    • SplQueue::enqueue - Adds an element to the queue.
    • SplQueue::setIteratorMode - Sets the mode of iteration
    • SplQueue::__construct - Constructs a new queue implemented using a doubly linked list
    • SplStack::setIteratorMode - Sets the mode of iteration
    • SplStack::__construct - Constructs a new stack implemented using a doubly linked list
    • SplSubject::attach - Attach an SplObserver
    • SplSubject::detach - Detach an observer
    • SplSubject::notify - Notify an observer
    • SplTempFileObject::__construct - Construct a new temporary file object
    • SplType::__construct - Creates a new value of some type
    • spl_autoload - Default implementation for __autoload()
    • spl_autoload_call - Try all registered __autoload() function to load the requested class
    • spl_autoload_extensions - Register and return default file extensions for spl_autoload
    • spl_autoload_functions - Return all registered __autoload() functions
    • spl_autoload_register - Register given function as __autoload() implementation
    • spl_autoload_unregister - Unregister given function as __autoload() implementation
    • spl_classes - Return available SPL classes
    • spl_object_hash - Return hash id for given object
    • Spoofchecker::areConfusable - Checks if a given text contains any confusable characters
    • Spoofchecker::isSuspicious - Checks if a given text contains any suspicious characters
    • Spoofchecker::setAllowedLocales - Locales to use when running checks
    • Spoofchecker::setChecks - Set the checks to run
    • Spoofchecker::__construct - Constructor
    • sprintf - Return a formatted string
    • SQL acceptable by 4D - PDO and SQL 4D
    • SQLite3::busyTimeout - Sets the busy connection handler
    • SQLite3::changes - Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close - Closes the database connection
    • SQLite3::createAggregate - Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createFunction - Registers a PHP function for use as an SQL scalar function
    • SQLite3::escapeString - Returns a string that has been properly escaped
    • SQLite3::exec - Executes a result-less query against a given database
    • SQLite3::lastErrorCode - Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg - Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID - Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension - Attempts to load an SQLite extension library
    • SQLite3::open - Opens an SQLite database
    • SQLite3::prepare - Prepares an SQL statement for execution
    • SQLite3::query - Executes an SQL query
    • SQLite3::querySingle - Executes a query and returns a single result
    • SQLite3::version - Returns the SQLite3 library version as a string constant and as a number
    • SQLite3::__construct - Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3Result::columnName - Returns the name of the nth column
    • SQLite3Result::columnType - Returns the type of the nth column
    • SQLite3Result::fetchArray - Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize - Closes the result set
    • SQLite3Result::numColumns - Returns the number of columns in the result set
    • SQLite3Result::reset - Resets the result set back to the first row
    • SQLite3Stmt::bindParam - Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue - Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear - Clears all current bound parameters
    • SQLite3Stmt::close - Closes the prepared statement
    • SQLite3Stmt::execute - Executes a prepared statement and returns a result set object
    • SQLite3Stmt::paramCount - Returns the number of parameters within the prepared statement
    • SQLite3Stmt::reset - Resets the prepared statement
    • sqlite_array_query - Execute a query against a given database and returns an array
    • sqlite_busy_timeout - Set busy timeout duration, or disable busy handlers
    • sqlite_changes - Returns the number of rows that were changed by the most recent SQL statement
    • sqlite_close - Closes an open SQLite database
    • sqlite_column - Fetches a column from the current row of a result set
    • sqlite_create_aggregate - Register an aggregating UDF for use in SQL statements
    • sqlite_create_function - Registers a "regular" User Defined Function for use in SQL statements
    • sqlite_current - Fetches the current row from a result set as an array
    • sqlite_error_string - Returns the textual description of an error code
    • sqlite_escape_string - Escapes a string for use as a query parameter
    • sqlite_exec - Executes a result-less query against a given database
    • sqlite_factory - Opens an SQLite database and returns an SQLiteDatabase object
    • sqlite_fetch_all - Fetches all rows from a result set as an array of arrays
    • sqlite_fetch_array - Fetches the next row from a result set as an array
    • sqlite_fetch_column_types - Return an array of column types from a particular table
    • sqlite_fetch_object - Fetches the next row from a result set as an object
    • sqlite_fetch_single - Fetches the first column of a result set as a string
    • sqlite_fetch_string - Alias dla sqlite_fetch_single
    • sqlite_field_name - Returns the name of a particular field
    • sqlite_has_more - Finds whether or not more rows are available
    • sqlite_has_prev - Returns whether or not a previous row is available
    • sqlite_key - Returns the current row index
    • sqlite_last_error - Returns the error code of the last error for a database
    • sqlite_last_insert_rowid - Returns the rowid of the most recently inserted row
    • sqlite_libencoding - Returns the encoding of the linked SQLite library
    • sqlite_libversion - Returns the version of the linked SQLite library
    • sqlite_next - Seek to the next row number
    • sqlite_num_fields - Returns the number of fields in a result set
    • sqlite_num_rows - Returns the number of rows in a buffered result set
    • sqlite_open - Opens an SQLite database and create the database if it does not exist
    • sqlite_popen - Opens a persistent handle to an SQLite database and create the database if it does not exist
    • sqlite_prev - Seek to the previous row number of a result set
    • sqlite_query - Executes a query against a given database and returns a result handle
    • sqlite_rewind - Seek to the first row number
    • sqlite_seek - Seek to a particular row number of a buffered result set
    • sqlite_single_query - Executes a query and returns either an array for one single column or the value of the first row
    • sqlite_udf_decode_binary - Decode binary data passed as parameters to an UDF
    • sqlite_udf_encode_binary - Encode binary data before returning it from an UDF
    • sqlite_unbuffered_query - Execute a query that does not prefetch and buffer all data
    • sqlite_valid - Returns whether more rows are available
    • sqlsrv_begin_transaction - Begins a database transaction
    • sqlsrv_cancel - Cancels a statement
    • sqlsrv_client_info - Returns information about the client and specified connection
    • sqlsrv_close - Closes an open connection and releases resourses associated with the connection
    • sqlsrv_commit - Commits a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_configure - Changes the driver error handling and logging configurations
    • sqlsrv_connect - Opens a connection to a Microsoft SQL Server database
    • sqlsrv_errors - Returns error and warning information about the last SQLSRV operation performed
    • sqlsrv_execute - Executes a statement prepared with sqlsrv_prepare
    • sqlsrv_fetch - Makes the next row in a result set available for reading
    • sqlsrv_fetch_array - Returns a row as an array
    • sqlsrv_fetch_object - Retrieves the next row of data in a result set as an object
    • sqlsrv_field_metadata - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
    • sqlsrv_free_stmt - Frees all resources for the specified statement
    • sqlsrv_get_config - Returns the value of the specified configuration setting
    • sqlsrv_get_field - Gets field data from the currently selected row
    • sqlsrv_has_rows - Indicates whether the specified statement has rows
    • sqlsrv_next_result - Makes the next result of the specified statement active
    • sqlsrv_num_fields - Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows - Retrieves the number of rows in a result set
    • sqlsrv_prepare - Prepares a query for execution
    • sqlsrv_query - Prepares and executes a query.
    • sqlsrv_rollback - Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data - Sends data from parameter streams to the server
    • sqlsrv_server_info - Returns information about the server
    • SQL types with PDO_4D and PHP - SQL types with PDO_4D and PHP
    • sql_regcase - Make regular expression for case insensitive match
    • sqrt - Pierwiastek kwadratowy
    • srand - Inicjuje generator liczb losowych
    • sscanf - Parses input from a string according to a format
    • ssdeep_fuzzy_compare - Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash - Create a fuzzy hash from a string
    • ssdeep_fuzzy_hash_filename - Create a fuzzy hash from a file
    • ssh2:// - Secure Shell 2
    • ssh2_auth_hostbased_file - Authenticate using a public hostkey
    • ssh2_auth_none - Authenticate as "none"
    • ssh2_auth_password - Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file - Authenticate using a public key
    • ssh2_connect - Connect to an SSH server
    • ssh2_exec - Execute a command on a remote server
    • ssh2_fetch_stream - Fetch an extended data stream
    • ssh2_fingerprint - Retrieve fingerprint of remote server
    • ssh2_methods_negotiated - Return list of negotiated methods
    • ssh2_publickey_add - Add an authorized publickey
    • ssh2_publickey_init - Initialize Publickey subsystem
    • ssh2_publickey_list - List currently authorized publickeys
    • ssh2_publickey_remove - Remove an authorized publickey
    • ssh2_scp_recv - Request a file via SCP
    • ssh2_scp_send - Send a file via SCP
    • ssh2_sftp - Initialize SFTP subsystem
    • ssh2_sftp_lstat - Stat a symbolic link
    • ssh2_sftp_mkdir - Create a directory
    • ssh2_sftp_readlink - Return the target of a symbolic link
    • ssh2_sftp_realpath - Resolve the realpath of a provided path string
    • ssh2_sftp_rename - Rename a remote file
    • ssh2_sftp_rmdir - Remove a directory
    • ssh2_sftp_stat - Stat a file on a remote filesystem
    • ssh2_sftp_symlink - Create a symlink
    • ssh2_sftp_unlink - Delete a file
    • ssh2_shell - Request an interactive shell
    • ssh2_tunnel - Open a tunnel through a remote server
    • SSL context options - SSL context option listing
    • stat - Gives information about a file
    • stats_absolute_deviation - Returns the absolute deviation of an array of values
    • stats_cdf_beta - CDF function for BETA Distribution. Calculates any one parameter of the beta distribution given values for the others.
    • stats_cdf_binomial - Calculates any one parameter of the binomial distribution given values for the others.
    • stats_cdf_cauchy - Not documented
    • stats_cdf_chisquare - Calculates any one parameter of the chi-square distribution given values for the others.
    • stats_cdf_exponential - Not documented
    • stats_cdf_f - Calculates any one parameter of the F distribution given values for the others.
    • stats_cdf_gamma - Calculates any one parameter of the gamma distribution given values for the others.
    • stats_cdf_laplace - Not documented
    • stats_cdf_logistic - Not documented
    • stats_cdf_negative_binomial - Calculates any one parameter of the negative binomial distribution given values for the others.
    • stats_cdf_noncentral_chisquare - Calculates any one parameter of the non-central chi-square distribution given values for the others.
    • stats_cdf_noncentral_f - Calculates any one parameter of the Non-central F distribution given values for the others.
    • stats_cdf_poisson - Calculates any one parameter of the Poisson distribution given values for the others.
    • stats_cdf_t - Calculates any one parameter of the T distribution given values for the others.
    • stats_cdf_uniform - Not documented
    • stats_cdf_weibull - Not documented
    • stats_covariance - Computes the covariance of two data sets
    • stats_dens_beta - Not documented
    • stats_dens_cauchy - Not documented
    • stats_dens_chisquare - Not documented
    • stats_dens_exponential - Not documented
    • stats_dens_f - Opis
    • stats_dens_gamma - Not documented
    • stats_dens_laplace - Not documented
    • stats_dens_logistic - Not documented
    • stats_dens_negative_binomial - Not documented
    • stats_dens_normal - Not documented
    • stats_dens_pmf_binomial - Not documented
    • stats_dens_pmf_hypergeometric - Opis
    • stats_dens_pmf_poisson - Not documented
    • stats_dens_t - Not documented
    • stats_dens_weibull - Not documented
    • stats_den_uniform - Not documented
    • stats_harmonic_mean - Returns the harmonic mean of an array of values
    • stats_kurtosis - Computes the kurtosis of the data in the array
    • stats_rand_gen_beta - Generates beta random deviate
    • stats_rand_gen_chisquare - Generates random deviate from the distribution of a chisquare with "df" degrees of freedom random variable.
    • stats_rand_gen_exponential - Generates a single random deviate from an exponential distribution with mean "av"
    • stats_rand_gen_f - Generates a random deviate
    • stats_rand_gen_funiform - Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma - Generates random deviates from a gamma distribution
    • stats_rand_gen_ibinomial - Generates a single random deviate from a binomial distribution whose number of trials is "n" (n >= 0) and whose probability of an event in each trial is "pp" ([0;1]). Method : algorithm BTPE
    • stats_rand_gen_ibinomial_negative - Generates a single random deviate from a negative binomial distribution. Arguments : n - the number of trials in the negative binomial distribution from which a random deviate is to be generated (n > 0), p - the probability of an event (0 < p < 1)).
    • stats_rand_gen_int - Generates random integer between 1 and 2147483562
    • stats_rand_gen_ipoisson - Generates a single random deviate from a Poisson distribution with mean "mu" (mu >= 0.0).
    • stats_rand_gen_iuniform - Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncenral_chisquare - Generates random deviate from the distribution of a noncentral chisquare with "df" degrees of freedom and noncentrality parameter "xnonc". d must be >= 1.0, xnonc must >= 0.0
    • stats_rand_gen_noncentral_f - Generates a random deviate from the noncentral F (variance ratio) distribution with "dfn" degrees of freedom in the numerator, and "dfd" degrees of freedom in the denominator, and noncentrality parameter "xnonc". Method : directly generates ratio of noncentral numerator chisquare variate to central denominator chisquare variate.
    • stats_rand_gen_noncentral_t - Generates a single random deviate from a noncentral T distribution
    • stats_rand_gen_normal - Generates a single random deviate from a normal distribution with mean, av, and standard deviation, sd (sd >= 0). Method : Renames SNORM from TOMS as slightly modified by BWB to use RANF instead of SUNIF.
    • stats_rand_gen_t - Generates a single random deviate from a T distribution
    • stats_rand_get_seeds - Not documented
    • stats_rand_phrase_to_seeds - generate two seeds for the RGN random number generator
    • stats_rand_ranf - Returns a random floating point number from a uniform distribution over 0 - 1 (endpoints of this interval are not returned) using the current generator
    • stats_rand_setall - Not documented
    • stats_skew - Computes the skewness of the data in the array
    • stats_standard_deviation - Returns the standard deviation
    • stats_stat_binomial_coef - Not documented
    • stats_stat_correlation - Not documented
    • stats_stat_gennch - Not documented
    • stats_stat_independent_t - Not documented
    • stats_stat_innerproduct - Opis
    • stats_stat_noncentral_t - Calculates any one parameter of the noncentral t distribution give values for the others.
    • stats_stat_paired_t - Not documented
    • stats_stat_percentile - Not documented
    • stats_stat_powersum - Not documented
    • stats_variance - Returns the population variance
    • Stomp::abort - Rolls back a transaction in progress
    • Stomp::ack - Acknowledges consumption of a message
    • Stomp::begin - Starts a transaction
    • Stomp::commit - Commits a transaction in progress
    • Stomp::error - Gets the last stomp error
    • Stomp::getReadTimeout - Gets read timeout
    • Stomp::getSessionId - Gets the current stomp session ID
    • Stomp::hasFrame - Indicates whether or not there is a frame ready to read
    • Stomp::readFrame - Reads the next frame
    • Stomp::send - Sends a message
    • Stomp::setReadTimeout - Sets read timeout
    • Stomp::subscribe - Registers to listen to a given destination
    • Stomp::unsubscribe - Removes an existing subscription
    • Stomp::__construct - Opens a connection
    • Stomp::__destruct - Closes stomp connection
    • StompException::getDetails - Get exception details
    • StompFrame::__construct - Constructor
    • stomp_connect_error - Returns a string description of the last connect error
    • stomp_version - Gets the current stomp extension version
    • strcasecmp - Binary safe case-insensitive string comparison
    • strchr - Alias dla strstr
    • strcmp - Binary safe string comparison
    • strcoll - Locale based string comparison
    • strcspn - Find length of initial segment not matching mask
    • streamWrapper::dir_closedir - Close directory handle
    • streamWrapper::dir_opendir - Open directory handle
    • streamWrapper::dir_readdir - Read entry from directory handle
    • streamWrapper::dir_rewinddir - Rewind directory handle
    • streamWrapper::mkdir - Create a directory
    • streamWrapper::rename - Renames a file or directory
    • streamWrapper::rmdir - Removes a directory
    • streamWrapper::stream_cast - Retrieve the underlaying resource
    • streamWrapper::stream_close - Close an resource
    • streamWrapper::stream_eof - Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush - Flushes the output
    • streamWrapper::stream_lock - Advisory file locking
    • streamWrapper::stream_metadata - Change stream options
    • streamWrapper::stream_open - Opens file or URL
    • streamWrapper::stream_read - Read from stream
    • streamWrapper::stream_seek - Seeks to specific location in a stream
    • streamWrapper::stream_set_option - Change stream options
    • streamWrapper::stream_stat - Retrieve information about a file resource
    • streamWrapper::stream_tell - Retrieve the current position of a stream
    • streamWrapper::stream_write - Write to stream
    • streamWrapper::unlink - Delete a file
    • streamWrapper::url_stat - Retrieve information about a file
    • streamWrapper::__construct - Constructs a new stream wrapper
    • streamWrapper::__destruct - Destructs an existing stream wrapper
    • stream_bucket_append - Append bucket to brigade
    • stream_bucket_make_writeable - Return a bucket object from the brigade for operating on
    • stream_bucket_new - Create a new bucket for use on the current stream
    • stream_bucket_prepend - Prepend bucket to brigade
    • stream_context_create - Create a streams context
    • stream_context_get_default - Retrieve the default streams context
    • stream_context_get_options - Retrieve options for a stream/wrapper/context
    • stream_context_get_params - Retrieves parameters from a context
    • stream_context_set_default - Set the default streams context
    • stream_context_set_option - Sets an option for a stream/wrapper/context
    • stream_context_set_params - Set parameters for a stream/wrapper/context
    • stream_copy_to_stream - Copies data from one stream to another
    • stream_encoding - Set character set for stream encoding
    • stream_filter_append - Attach a filter to a stream
    • stream_filter_prepend - Attach a filter to a stream
    • stream_filter_register - Register a user defined stream filter
    • stream_filter_remove - Remove a filter from a stream
    • stream_get_contents - Reads remainder of a stream into a string
    • stream_get_filters - Retrieve list of registered filters
    • stream_get_line - Gets line from stream resource up to a given delimiter
    • stream_get_meta_data - Retrieves header/meta data from streams/file pointers
    • stream_get_transports - Retrieve list of registered socket transports
    • stream_get_wrappers - Retrieve list of registered streams
    • stream_is_local - Checks if a stream is a local stream
    • stream_notification_callback - A callback function for the notification context paramater
    • stream_register_wrapper - Alias dla stream_wrapper_register
    • stream_resolve_include_path - Resolve filename against the include path
    • stream_select - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
    • stream_set_blocking - Set blocking/non-blocking mode on a stream
    • stream_set_read_buffer - Set read file buffering on the given stream
    • stream_set_timeout - Set timeout period on a stream
    • stream_set_write_buffer - Sets write file buffering on the given stream
    • stream_socket_accept - Accept a connection on a socket created by stream_socket_server
    • stream_socket_client - Open Internet or Unix domain socket connection
    • stream_socket_enable_crypto - Turns encryption on/off on an already connected socket
    • stream_socket_get_name - Retrieve the name of the local or remote sockets
    • stream_socket_pair - Creates a pair of connected, indistinguishable socket streams
    • stream_socket_recvfrom - Receives data from a socket, connected or not
    • stream_socket_sendto - Sends a message to a socket, whether it is connected or not
    • stream_socket_server - Create an Internet or Unix domain server socket
    • stream_socket_shutdown - Shutdown a full-duplex connection
    • stream_supports_lock - Tells whether the stream supports locking.
    • stream_wrapper_register - Register a URL wrapper implemented as a PHP class
    • stream_wrapper_restore - Restores a previously unregistered built-in wrapper
    • stream_wrapper_unregister - Unregister a URL wrapper
    • strftime - Formatuje lokalną datę/czas zgodnie z lokalizacją
    • stripcslashes - Un-quote string quoted with addcslashes
    • stripos - Find the position of the first occurrence of a case-insensitive substring in a string
    • stripslashes - Un-quotes a quoted string
    • strip_tags - Strip HTML and PHP tags from a string
    • stristr - Case-insensitive strstr
    • strlen - Get string length
    • strnatcasecmp - Case insensitive string comparisons using a "natural order" algorithm
    • strnatcmp - String comparisons using a "natural order" algorithm
    • strncasecmp - Binary safe case-insensitive string comparison of the first n characters
    • strncmp - Binary safe string comparison of the first n characters
    • strpbrk - Search a string for any of a set of characters
    • strpos - Find the position of the first occurrence of a substring in a string
    • strptime - Parse a time/date generated with strftime
    • strrchr - Znajduje ostatnie występowanie znaku w łańcuchu znaków
    • strrev - Odwraca ciąg znaków
    • strripos - Find the position of the last occurrence of a case-insensitive substring in a string
    • strrpos - Znajduje pozycję ostatniego wystąpienia znaku w ciągu znaków
    • strspn - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.
    • strstr - Find the first occurrence of a string
    • strtok - Tokenize string
    • strtolower - Zmienia wszystkie litery w łańcuchu na małe
    • strtotime - Parsuje większość angielskich tekstowych opisów daty i czasu do uniksowego znacznika czasu
    • strtoupper - Zmienia wszystkie litery w łańcuchu na duże
    • strtr - Translate characters or replace substrings
    • strval - Get string value of a variable
    • str_getcsv - Parse a CSV string into an array
    • str_ireplace - Case-insensitive version of str_replace.
    • str_pad - Pad a string to a certain length with another string
    • str_repeat - Repeat a string
    • str_replace - Replace all occurrences of the search string with the replacement string
    • str_rot13 - Perform the rot13 transform on a string
    • str_shuffle - Randomly shuffles a string
    • str_split - Convert a string to an array
    • str_word_count - Return information about words used in a string
    • substr - Return part of a string
    • substr_compare - Binary safe comparison of two strings from an offset, up to length characters
    • substr_count - Count the number of substring occurrences
    • substr_replace - Zastępuje tekst wewnątrz części łańcucha
    • SVM::crossvalidate - Test training params on subsets of the training data.
    • SVM::getOptions - Return the current training parameters
    • SVM::setOptions - Set training parameters
    • SVM::train - Create a SVMModel based on training data
    • SVM::__construct - Construct a new SVM object
    • SVMModel::checkProbabilityModel - Returns true if the model has probability information
    • SVMModel::getLabels - Get the labels the model was trained on
    • SVMModel::getNrClass - Returns the number of classes the model was trained with
    • SVMModel::getSvmType - Get the SVM type the model was trained with
    • SVMModel::getSvrProbability - Get the sigma value for regression types
    • SVMModel::load - Load a saved SVM Model
    • SVMModel::predict - Predict a value for previously unseen data
    • SVMModel::predict_probability - Return class probabilities for previous unseen data
    • SVMModel::save - Save a model to a file
    • SVMModel::__construct - Construct a new SVMModel
    • svn_add - Schedules the addition of an item in a working directory
    • svn_auth_get_parameter - Retrieves authentication parameter
    • svn_auth_set_parameter - Sets an authentication parameter
    • svn_blame - Get the SVN blame for a file
    • svn_cat - Returns the contents of a file in a repository
    • svn_checkout - Checks out a working copy from the repository
    • svn_cleanup - Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version - Returns the version of the SVN client libraries
    • svn_commit - Sends changes from the local working copy to the repository
    • svn_delete - Delete items from a working copy or repository.
    • svn_diff - Recursively diffs two paths
    • svn_export - Export the contents of a SVN directory
    • svn_fs_abort_txn - Abort a transaction, returns true if everything is okay, false otherwise
    • svn_fs_apply_text - Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 - Create a new transaction
    • svn_fs_change_node_prop - Return true if everything is ok, false otherwise
    • svn_fs_check_path - Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed - Return true if content is different, false otherwise
    • svn_fs_copy - Copies a file or a directory, returns true if all is ok, false otherwise
    • svn_fs_delete - Deletes a file or a directory, return true if all is ok, false otherwise
    • svn_fs_dir_entries - Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents - Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length - Returns the length of a file from a given version of the fs
    • svn_fs_is_dir - Return true if the path points to a directory, false otherwise
    • svn_fs_is_file - Return true if the path points to a file, false otherwise
    • svn_fs_make_dir - Creates a new empty directory, returns true if all is ok, false otherwise
    • svn_fs_make_file - Creates a new empty file, returns true if all is ok, false otherwise
    • svn_fs_node_created_rev - Returns the revision in which path under fsroot was created
    • svn_fs_node_prop - Returns the value of a property for a node
    • svn_fs_props_changed - Return true if props are different, false otherwise
    • svn_fs_revision_prop - Fetches the value of a named property
    • svn_fs_revision_root - Get a handle on a specific version of the repository root
    • svn_fs_txn_root - Creates and returns a transaction root
    • svn_fs_youngest_rev - Returns the number of the youngest revision in the filesystem
    • svn_import - Imports an unversioned path into a repository
    • svn_log - Returns the commit log messages of a repository URL
    • svn_ls - Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir - Creates a directory in a working copy or repository
    • svn_repos_create - Create a new subversion repository at path
    • svn_repos_fs - Gets a handle on the filesystem for a repository
    • svn_repos_fs_begin_txn_for_commit - Create a new transaction
    • svn_repos_fs_commit_txn - Commits a transaction and returns the new revision
    • svn_repos_hotcopy - Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open - Open a shared lock on a repository.
    • svn_repos_recover - Run recovery procedures on the repository located at path.
    • svn_revert - Revert changes to the working copy
    • svn_status - Returns the status of working copy files and directories
    • svn_update - Update working copy
    • SWFAction::__construct - Creates a new SWFAction
    • SWFBitmap::getHeight - Returns the bitmap's height
    • SWFBitmap::getWidth - Returns the bitmap's width
    • SWFBitmap::__construct - Loads Bitmap object
    • SWFButton::addAction - Adds an action
    • SWFButton::addASound - Associates a sound with a button transition
    • SWFButton::addShape - Adds a shape to a button
    • SWFButton::setAction - Sets the action
    • SWFButton::setDown - Alias for addShape(shape, SWFBUTTON_DOWN)
    • SWFButton::setHit - Alias for addShape(shape, SWFBUTTON_HIT)
    • SWFButton::setMenu - enable track as menu button behaviour
    • SWFButton::setOver - Alias for addShape(shape, SWFBUTTON_OVER)
    • SWFButton::setUp - Alias for addShape(shape, SWFBUTTON_UP)
    • SWFButton::__construct - Creates a new Button
    • SWFDisplayItem::addAction - Adds this SWFAction to the given SWFSprite instance
    • SWFDisplayItem::addColor - Adds the given color to this item's color transform
    • SWFDisplayItem::endMask - Another way of defining a MASK layer
    • SWFDisplayItem::getRot - Opis
    • SWFDisplayItem::getX - Opis
    • SWFDisplayItem::getXScale - Opis
    • SWFDisplayItem::getXSkew - Opis
    • SWFDisplayItem::getY - Opis
    • SWFDisplayItem::getYScale - Opis
    • SWFDisplayItem::getYSkew - Opis
    • SWFDisplayItem::move - Moves object in relative coordinates
    • SWFDisplayItem::moveTo - Moves object in global coordinates
    • SWFDisplayItem::multColor - Multiplies the item's color transform
    • SWFDisplayItem::remove - Removes the object from the movie
    • SWFDisplayItem::rotate - Rotates in relative coordinates
    • SWFDisplayItem::rotateTo - Rotates the object in global coordinates
    • SWFDisplayItem::scale - Scales the object in relative coordinates
    • SWFDisplayItem::scaleTo - Scales the object in global coordinates
    • SWFDisplayItem::setDepth - Sets z-order
    • SWFDisplayItem::setMaskLevel - Defines a MASK layer at level
    • SWFDisplayItem::setMatrix - Sets the item's transform matrix
    • SWFDisplayItem::setName - Sets the object's name
    • SWFDisplayItem::setRatio - Sets the object's ratio
    • SWFDisplayItem::skewX - Sets the X-skew
    • SWFDisplayItem::skewXTo - Sets the X-skew
    • SWFDisplayItem::skewY - Sets the Y-skew
    • SWFDisplayItem::skewYTo - Sets the Y-skew
    • SWFFill::moveTo - Moves fill origin
    • SWFFill::rotateTo - Sets fill's rotation
    • SWFFill::scaleTo - Sets fill's scale
    • SWFFill::skewXTo - Sets fill x-skew
    • SWFFill::skewYTo - Sets fill y-skew
    • SWFFont::getAscent - Returns the ascent of the font, or 0 if not available
    • SWFFont::getDescent - Returns the descent of the font, or 0 if not available
    • SWFFont::getLeading - Returns the leading of the font, or 0 if not available
    • SWFFont::getShape - Returns the glyph shape of a char as a text string
    • SWFFont::getUTF8Width - Calculates the width of the given string in this font at full height
    • SWFFont::getWidth - Returns the string's width
    • SWFFont::__construct - Loads a font definition
    • SWFFontChar::addChars - Adds characters to a font for exporting font
    • SWFFontChar::addUTF8Chars - Adds characters to a font for exporting font
    • SWFGradient::addEntry - Adds an entry to the gradient list
    • SWFGradient::__construct - Creates a gradient object
    • SWFMorph::getShape1 - Gets a handle to the starting shape
    • SWFMorph::getShape2 - Gets a handle to the ending shape
    • SWFMorph::__construct - Creates a new SWFMorph object
    • SWFMovie::add - Adds any type of data to a movie
    • SWFMovie::addExport - Opis
    • SWFMovie::addFont - Opis
    • SWFMovie::importChar - Opis
    • SWFMovie::importFont - Opis
    • SWFMovie::labelFrame - Labels a frame
    • SWFMovie::nextFrame - Moves to the next frame of the animation
    • SWFMovie::output - Dumps your lovingly prepared movie out
    • SWFMovie::remove - Removes the object instance from the display list
    • SWFMovie::save - Saves the SWF movie in a file
    • SWFMovie::saveToFile - Opis
    • SWFMovie::setbackground - Sets the background color
    • SWFMovie::setDimension - Sets the movie's width and height
    • SWFMovie::setFrames - Sets the total number of frames in the animation
    • SWFMovie::setRate - Sets the animation's frame rate
    • SWFMovie::startSound - Opis
    • SWFMovie::stopSound - Opis
    • SWFMovie::streamMP3 - Streams a MP3 file
    • SWFMovie::writeExports - Opis
    • SWFMovie::__construct - Creates a new movie object, representing an SWF version 4 movie
    • SWFPrebuiltClip::__construct - Returns a SWFPrebuiltClip object
    • SWFShape::addFill - Adds a solid fill to the shape
    • SWFShape::drawArc - Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
    • SWFShape::drawCircle - Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
    • SWFShape::drawCubic - Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCubicTo - Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCurve - Draws a curve (relative)
    • SWFShape::drawCurveTo - Draws a curve
    • SWFShape::drawGlyph - Draws the first character in the given string into the shape using the glyph definition from the given font
    • SWFShape::drawLine - Draws a line (relative)
    • SWFShape::drawLineTo - Draws a line
    • SWFShape::movePen - Moves the shape's pen (relative)
    • SWFShape::movePenTo - Moves the shape's pen
    • SWFShape::setLeftFill - Sets left rasterizing color
    • SWFShape::setLine - Sets the shape's line style
    • SWFShape::setRightFill - Sets right rasterizing color
    • SWFShape::__construct - Creates a new shape object
    • SWFSound::__construct - Returns a new SWFSound object from given file
    • SWFSoundInstance::loopCount - Opis
    • SWFSoundInstance::loopInPoint - Opis
    • SWFSoundInstance::loopOutPoint - Opis
    • SWFSoundInstance::noMultiple - Opis
    • SWFSprite::add - Adds an object to a sprite
    • SWFSprite::labelFrame - Labels frame
    • SWFSprite::nextFrame - Moves to the next frame of the animation
    • SWFSprite::remove - Removes an object to a sprite
    • SWFSprite::setFrames - Sets the total number of frames in the animation
    • SWFSprite::startSound - Opis
    • SWFSprite::stopSound - Opis
    • SWFSprite::__construct - Creates a movie clip (a sprite)
    • SWFText::addString - Draws a string
    • SWFText::addUTF8String - Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
    • SWFText::getAscent - Returns the ascent of the current font at its current size, or 0 if not available
    • SWFText::getDescent - Returns the descent of the current font at its current size, or 0 if not available
    • SWFText::getLeading - Returns the leading of the current font at its current size, or 0 if not available
    • SWFText::getUTF8Width - calculates the width of the given string in this text objects current font and size
    • SWFText::getWidth - Computes string's width
    • SWFText::moveTo - Moves the pen
    • SWFText::setColor - Sets the current text color
    • SWFText::setFont - Sets the current font
    • SWFText::setHeight - Sets the current font height
    • SWFText::setSpacing - Sets the current font spacing
    • SWFText::__construct - Creates a new SWFText object
    • SWFTextField::addChars - adds characters to a font that will be available within a textfield
    • SWFTextField::addString - Concatenates the given string to the text field
    • SWFTextField::align - Sets the text field alignment
    • SWFTextField::setBounds - Sets the text field width and height
    • SWFTextField::setColor - Sets the color of the text field
    • SWFTextField::setFont - Sets the text field font
    • SWFTextField::setHeight - Sets the font height of this text field font
    • SWFTextField::setIndentation - Sets the indentation of the first line
    • SWFTextField::setLeftMargin - Sets the left margin width of the text field
    • SWFTextField::setLineSpacing - Sets the line spacing of the text field
    • SWFTextField::setMargins - Sets the margins width of the text field
    • SWFTextField::setName - Sets the variable name
    • SWFTextField::setPadding - Sets the padding of this textfield
    • SWFTextField::setRightMargin - Sets the right margin width of the text field
    • SWFTextField::__construct - Creates a text field object
    • SWFVideoStream::getNumFrames - Returns the number of frames in the video
    • SWFVideoStream::setDimension - Sets video dimension
    • SWFVideoStream::__construct - Returns a SWFVideoStream object
    • swf_actiongeturl - Get a URL from a Shockwave Flash movie
    • swf_actiongotoframe - Play a frame and then stop
    • swf_actiongotolabel - Display a frame with the specified label
    • swf_actionnextframe - Go forward one frame
    • swf_actionplay - Start playing the flash movie from the current frame
    • swf_actionprevframe - Go backwards one frame
    • swf_actionsettarget - Set the context for actions
    • swf_actionstop - Stop playing the flash movie at the current frame
    • swf_actiontogglequality - Toggle between low and high quality
    • swf_actionwaitforframe - Skip actions if a frame has not been loaded
    • swf_addbuttonrecord - Controls location, appearance and active area of the current button
    • swf_addcolor - Set the global add color to the rgba value specified
    • swf_closefile - Close the current Shockwave Flash file
    • swf_definebitmap - Define a bitmap
    • swf_definefont - Defines a font
    • swf_defineline - Define a line
    • swf_definepoly - Define a polygon
    • swf_definerect - Define a rectangle
    • swf_definetext - Define a text string
    • swf_endbutton - End the definition of the current button
    • swf_enddoaction - End the current action
    • swf_endshape - Completes the definition of the current shape
    • swf_endsymbol - End the definition of a symbol
    • swf_fontsize - Change the font size
    • swf_fontslant - Set the font slant
    • swf_fonttracking - Set the current font tracking
    • swf_getbitmapinfo - Get information about a bitmap
    • swf_getfontinfo - Gets font information
    • swf_getframe - Get the frame number of the current frame
    • swf_labelframe - Label the current frame
    • swf_lookat - Define a viewing transformation
    • swf_modifyobject - Modify an object
    • swf_mulcolor - Sets the global multiply color to the rgba value specified
    • swf_nextid - Returns the next free object id
    • swf_oncondition - Describe a transition used to trigger an action list
    • swf_openfile - Open a new Shockwave Flash file
    • swf_ortho - Defines an orthographic mapping of user coordinates onto the current viewport
    • swf_ortho2 - Defines 2D orthographic mapping of user coordinates onto the current viewport
    • swf_perspective - Define a perspective projection transformation
    • swf_placeobject - Place an object onto the screen
    • swf_polarview - Define the viewer's position with polar coordinates
    • swf_popmatrix - Restore a previous transformation matrix
    • swf_posround - Enables or Disables the rounding of the translation when objects are placed or moved
    • swf_pushmatrix - Push the current transformation matrix back onto the stack
    • swf_removeobject - Remove an object
    • swf_rotate - Rotate the current transformation
    • swf_scale - Scale the current transformation
    • swf_setfont - Change the current font
    • swf_setframe - Switch to a specified frame
    • swf_shapearc - Draw a circular arc
    • swf_shapecurveto - Draw a quadratic bezier curve between two points
    • swf_shapecurveto3 - Draw a cubic bezier curve
    • swf_shapefillbitmapclip - Set current fill mode to clipped bitmap
    • swf_shapefillbitmaptile - Set current fill mode to tiled bitmap
    • swf_shapefilloff - Turns off filling
    • swf_shapefillsolid - Set the current fill style to the specified color
    • swf_shapelinesolid - Set the current line style
    • swf_shapelineto - Draw a line
    • swf_shapemoveto - Move the current position
    • swf_showframe - Display the current frame
    • swf_startbutton - Start the definition of a button
    • swf_startdoaction - Start a description of an action list for the current frame
    • swf_startshape - Start a complex shape
    • swf_startsymbol - Define a symbol
    • swf_textwidth - Get the width of a string
    • swf_translate - Translate the current transformations
    • swf_viewport - Select an area for future drawing
    • Swish::getMetaList - Get the list of meta entries for the index
    • Swish::getPropertyList - Get the list of properties for the index
    • Swish::prepare - Prepare a search query
    • Swish::query - Execute a query and return results object
    • Swish::__construct - Construct a Swish object
    • SwishResult::getMetaList - Get a list of meta entries
    • SwishResult::stem - Stems the given word
    • SwishResults::getParsedWords - Get an array of parsed words
    • SwishResults::getRemovedStopwords - Get an array of stopwords removed from the query
    • SwishResults::nextResult - Get the next search result
    • SwishResults::seekResult - Set current seek pointer to the given position
    • SwishSearch::execute - Execute the search and get the results
    • SwishSearch::resetLimit - Reset the search limits
    • SwishSearch::setLimit - Set the search limits
    • SwishSearch::setPhraseDelimiter - Set the phrase delimiter
    • SwishSearch::setSort - Set the sort order
    • SwishSearch::setStructure - Set the structure flag in the search object
    • sybase_affected_rows - Gets number of affected rows in last query
    • sybase_close - Closes a Sybase connection
    • sybase_connect - Opens a Sybase server connection
    • sybase_data_seek - Moves internal row pointer
    • sybase_deadlock_retry_count - Sets the deadlock retry count
    • sybase_fetch_array - Fetch row as array
    • sybase_fetch_assoc - Fetch a result row as an associative array
    • sybase_fetch_field - Get field information from a result
    • sybase_fetch_object - Fetch a row as an object
    • sybase_fetch_row - Get a result row as an enumerated array
    • sybase_field_seek - Sets field offset
    • sybase_free_result - Frees result memory
    • sybase_get_last_message - Returns the last message from the server
    • sybase_min_client_severity - Sets minimum client severity
    • sybase_min_error_severity - Sets minimum error severity
    • sybase_min_message_severity - Sets minimum message severity
    • sybase_min_server_severity - Sets minimum server severity
    • sybase_num_fields - Gets the number of fields in a result set
    • sybase_num_rows - Get number of rows in a result set
    • sybase_pconnect - Open persistent Sybase connection
    • sybase_query - Sends a Sybase query
    • sybase_result - Get result data
    • sybase_select_db - Selects a Sybase database
    • sybase_set_message_handler - Sets the handler called when a server message is raised
    • sybase_unbuffered_query - Send a Sybase query and do not block
    • symlink - Tworzy dowiązanie symboliczne
    • syslog - Generate a system log message
    • system - Execute an external program and display the output
    • sys_getloadavg - Gets system load average
    • sys_get_temp_dir - Returns directory path used for temporary files
  • t
    • tan - Oblicza tangens kąta
    • tanh - Tangens hiperboliczny
    • tcpwrap_check - Performs a tcpwrap check
    • tempnam - Create file with unique file name
    • textdomain - Sets the default domain
    • tidy::$errorBuffer - Return warnings and errors which occurred parsing the specified document
    • tidy::body - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
    • tidy::cleanRepair - Execute configured cleanup and repair operations on parsed markup
    • tidy::diagnose - Run configured diagnostics on parsed and repaired markup
    • tidy::getConfig - Get current Tidy configuration
    • tidy::getHtmlVer - Get the Detected HTML version for the specified document
    • tidy::getOpt - Returns the value of the specified configuration option for the tidy document
    • tidy::getoptdoc - Returns the documentation for the given option name
    • tidy::getRelease - Get release date (version) for Tidy library
    • tidy::getStatus - Get status of specified document
    • tidy::head - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
    • tidy::html - Returns a tidyNode object starting from the <html> tag of the tidy parse tree
    • tidy::isXhtml - Indicates if the document is a XHTML document
    • tidy::isXml - Indicates if the document is a generic (non HTML/XHTML) XML document
    • tidy::parseFile - Parse markup in file or URI
    • tidy::parseString - Parse a document stored in a string
    • tidy::repairFile - Repair a file and return it as a string
    • tidy::repairString - Repair a string using an optionally provided configuration file
    • tidy::root - Returns a tidyNode object representing the root of the tidy parse tree
    • tidy::__construct - Constructs a new tidy object
    • tidyNode::getParent - Zwraca rodzica bieżącego węzła
    • tidyNode::hasChildren - Sprawdza, czy węzeł posiada potomków
    • tidyNode::hasSiblings - Sprawdza, czy węzeł posiada sąsiadów
    • tidyNode::isAsp - Sprawdza, czy węzeł jest kodem ASP
    • tidyNode::isComment - Sprawdza, czy węzeł jest komentarzem
    • tidyNode::isHtml - Sprawdza, czy węzeł jest częścią dokumentu HTML
    • tidyNode::isJste - Sprawdza, czy węzeł jest kodem JSTE
    • tidyNode::isPhp - Sprawdza, czy węzeł jest kodem PHP
    • tidyNode::isText - Sprawdza, czy węzeł jest tekstem (nie jest znacznikiem)
    • tidy_access_count - Zwraca liczbę dostępnych ostrzeżeń napotkanych w określonym dokumencie
    • tidy_config_count - Zwraca liczbę błędów konfiguracji Tidy napotkanych w określonym dokumencie
    • tidy_error_count - Zwraca liczbę błędów Tidy znalezionych w określonym dokumencie
    • tidy_get_output - Zwraca łańcuch zawierający poprawiony przez Tidy kod HTML, XHTML lub XML
    • tidy_load_config - Wczytuje plik konfiguracyjny Tidy w formacie ASCII z określonym kodowaniem znaków narodowych
    • tidy_reset_config - Przywraca domyślne wartości konfiguracji Tidy
    • tidy_save_config - Zapisuje bieżące ustawienia konfiguracyjne Tidy we wskazanym pliku
    • tidy_setopt - Uaktualnia ustawienia konfiguracji dla określonego dokumentu tidy
    • tidy_set_encoding - Ustawia kodowanie znaków narodowych dla dokumentów wejściowych i wyjściowych
    • tidy_warning_count - Zwraca liczbę ostrzeżeń Tidy znalezionych w określonym dokumencie
    • time - Zwraca aktualny uniksowy znacznik czasu
    • timezone_abbreviations_list - Alias dla DateTimeZone::listAbbreviations
    • timezone_identifiers_list - Alias dla DateTimeZone::listIdentifiers
    • timezone_location_get - Alias dla DateTimeZone::getLocation
    • timezone_name_from_abbr - Returns the timezone name from abbreviation
    • timezone_name_get - Alias dla DateTimeZone::getName
    • timezone_offset_get - Alias dla DateTimeZone::getOffset
    • timezone_open - Alias dla DateTimeZone::__construct
    • timezone_transitions_get - Alias dla DateTimeZone::getTransitions
    • timezone_version_get - Gets the version of the timezonedb
    • time_nanosleep - Delay for a number of seconds and nanoseconds
    • time_sleep_until - Make the script sleep until the specified time
    • tmpfile - Tworzy plik tymczasowy
    • token_get_all - Dzieli zadane źródło na tokeny PHP
    • token_name - Zwraca symboliczną nazwę danego tokena PHP
    • TokyoTyrant::add - Adds to a numeric key
    • TokyoTyrant::connect - Connect to a database
    • TokyoTyrant::connectUri - Connects to a database
    • TokyoTyrant::copy - Copies the database
    • TokyoTyrant::ext - Execute a remote script
    • TokyoTyrant::fwmKeys - Returns the forward matching keys
    • TokyoTyrant::get - The get purpose
    • TokyoTyrant::getIterator - Get an iterator
    • TokyoTyrant::num - Number of records in the database
    • TokyoTyrant::out - Removes records
    • TokyoTyrant::put - Puts values
    • TokyoTyrant::putCat - Concatenates to a record
    • TokyoTyrant::putKeep - Puts a record
    • TokyoTyrant::putNr - Puts value
    • TokyoTyrant::putShl - Concatenates to a record
    • TokyoTyrant::restore - Restore the database
    • TokyoTyrant::setMaster - Set the replication master
    • TokyoTyrant::size - Returns the size of the value
    • TokyoTyrant::stat - Get statistics
    • TokyoTyrant::sync - Synchronize the database
    • TokyoTyrant::tune - Tunes connection values
    • TokyoTyrant::vanish - Empties the database
    • TokyoTyrant::__construct - Construct a new TokyoTyrant object
    • TokyoTyrantIterator::current - Get the current value
    • TokyoTyrantIterator::key - Returns the current key
    • TokyoTyrantIterator::next - Move to next key
    • TokyoTyrantIterator::rewind - Rewinds the iterator
    • TokyoTyrantIterator::valid - Rewinds the iterator
    • TokyoTyrantIterator::__construct - Construct an iterator
    • TokyoTyrantQuery::addCond - Adds a condition to the query
    • TokyoTyrantQuery::count - Counts records
    • TokyoTyrantQuery::current - Returns the current element
    • TokyoTyrantQuery::hint - Get the hint string of the query
    • TokyoTyrantQuery::key - Returns the current key
    • TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries
    • TokyoTyrantQuery::next - Moves the iterator to next entry
    • TokyoTyrantQuery::out - Removes records based on query
    • TokyoTyrantQuery::rewind - Rewinds the iterator
    • TokyoTyrantQuery::search - Searches records
    • TokyoTyrantQuery::setLimit - Limit results
    • TokyoTyrantQuery::setOrder - Orders results
    • TokyoTyrantQuery::valid - Checks the validity of current item
    • TokyoTyrantQuery::__construct - Construct a new query
    • TokyoTyrantTable::add - Adds a record
    • TokyoTyrantTable::genUid - Generate unique id
    • TokyoTyrantTable::get - Get a row
    • TokyoTyrantTable::getIterator - Get an iterator
    • TokyoTyrantTable::getQuery - Get a query object
    • TokyoTyrantTable::out - Remove records
    • TokyoTyrantTable::put - Store a row
    • TokyoTyrantTable::putCat - Concatenates to a row
    • TokyoTyrantTable::putKeep - Put a new record
    • TokyoTyrantTable::putNr - Puts value
    • TokyoTyrantTable::putShl - Concatenates to a record
    • TokyoTyrantTable::setIndex - Sets index
    • touch - Ustawia czas modyfikacji pliku
    • trait_exists - Checks if the trait exists
    • Transliterator::create - Create a transliterator
    • Transliterator::createFromRules - Create transliterator from rules
    • Transliterator::createInverse - Create an inverse transliterator
    • Transliterator::getErrorCode - Get last error code
    • Transliterator::getErrorMessage - Get last error message
    • Transliterator::listIDs - Get transliterator IDs
    • Transliterator::transliterate - Transliterate a string
    • Transliterator::__construct - Construct a Transliterator object
    • trigger_error - Generates a user-level error/warning/notice message
    • trim - Strip whitespace (or other characters) from the beginning and end of a string
  • u
    • uasort - Sortuj tablicę korzystając ze zdefiniowanej przez użytkownika funkcji porównującej i zachowując skojarzenia kluczy
    • ucfirst - Make a string's first character uppercase
    • ucwords - Uppercase the first character of each word in a string
    • udm_add_search_limit - Add various search limits
    • udm_alloc_agent - Allocate mnoGoSearch session
    • udm_alloc_agent_array - Allocate mnoGoSearch session
    • udm_api_version - Get mnoGoSearch API version
    • udm_cat_list - Get all the categories on the same level with the current one
    • udm_cat_path - Get the path to the current category
    • udm_check_charset - Check if the given charset is known to mnogosearch
    • udm_check_stored - Check connection to stored
    • udm_clear_search_limits - Clear all mnoGoSearch search restrictions
    • udm_close_stored - Close connection to stored
    • udm_crc32 - Return CRC32 checksum of given string
    • udm_errno - Get mnoGoSearch error number
    • udm_error - Get mnoGoSearch error message
    • udm_find - Perform search
    • udm_free_agent - Free mnoGoSearch session
    • udm_free_ispell_data - Free memory allocated for ispell data
    • udm_free_res - Free mnoGoSearch result
    • udm_get_doc_count - Get total number of documents in database
    • udm_get_res_field - Fetch a result field
    • udm_get_res_param - Get mnoGoSearch result parameters
    • udm_hash32 - Return Hash32 checksum of gived string
    • udm_load_ispell_data - Load ispell data
    • udm_open_stored - Open connection to stored
    • udm_set_agent_param - Set mnoGoSearch agent session parameters
    • uksort - Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez użytkownika funkcji porównującej
    • umask - Changes the current umask
    • uniqid - Generate a unique ID
    • unixtojd - Convert Unix timestamp to Julian Day
    • unlink - Kasowanie pliku
    • unpack - Unpack data from binary string
    • unregister_tick_function - De-register a function for execution on each tick
    • unserialize - Creates a PHP value from a stored representation
    • unset - Unset a given variable
    • urldecode - Dekoduje łańcuchy zakodowane metodą kodowania URL'i
    • urlencode - Koduje łańcuch metodą kodowania URLi
    • user_error - Alias of trigger_error
    • use_soap_error_handler - Set whether to use the SOAP error handler
    • usleep - Delay execution in microseconds
    • usort - Sortuje tablicę według wartości korzystając ze zdefiniowanej przez użytkownika funkcji porównującej
    • utf8_decode - Konwertuje ciąg znaków w ISO-8859-1 zakodowany w UTF-8 do jednobajtowego ISO-8859-1
    • utf8_encode - Koduje ciąg znaków w ISO-8859-1 do UTF-8
  • v
    • V8Js::executeString - Execute a string as Javascript code
    • V8Js::getExtensions - Return an array of registered extensions
    • V8Js::getPendingException - Return pending uncaught Javascript exception
    • V8Js::registerExtension - Register Javascript extensions for V8Js
    • V8Js::__construct - Construct a new V8Js object
    • V8JsException::getJsFileName - The getJsFileName purpose
    • V8JsException::getJsLineNumber - The getJsLineNumber purpose
    • V8JsException::getJsSourceLine - The getJsSourceLine purpose
    • V8JsException::getJsTrace - The getJsTrace purpose
    • variant_abs - Returns the absolute value of a variant
    • variant_add - "Adds" two variant values together and returns the result
    • variant_and - Performs a bitwise AND operation between two variants
    • variant_cast - Convert a variant into a new variant object of another type
    • variant_cat - concatenates two variant values together and returns the result
    • variant_cmp - Compares two variants
    • variant_date_from_timestamp - Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp - Converts a variant date/time value to Unix timestamp
    • variant_div - Returns the result from dividing two variants
    • variant_eqv - Performs a bitwise equivalence on two variants
    • variant_fix - Returns the integer portion of a variant
    • variant_get_type - Returns the type of a variant object
    • variant_idiv - Converts variants to integers and then returns the result from dividing them
    • variant_imp - Performs a bitwise implication on two variants
    • variant_int - Returns the integer portion of a variant
    • variant_mod - Divides two variants and returns only the remainder
    • variant_mul - Multiplies the values of the two variants
    • variant_neg - Performs logical negation on a variant
    • variant_not - Performs bitwise not negation on a variant
    • variant_or - Performs a logical disjunction on two variants
    • variant_pow - Returns the result of performing the power function with two variants
    • variant_round - Rounds a variant to the specified number of decimal places
    • variant_set - Assigns a new value for a variant object
    • variant_set_type - Convert a variant into another type "in-place"
    • variant_sub - Subtracts the value of the right variant from the left variant value
    • variant_xor - Performs a logical exclusion on two variants
    • VarnishAdmin::auth - Authenticate on a varnish instance
    • VarnishAdmin::ban - Ban URLs using a VCL expression
    • VarnishAdmin::banUrl - Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic - Clear varnish instance panic messages
    • VarnishAdmin::connect - Connect to a varnish instance administration interface
    • VarnishAdmin::getPanic - Get the last panic message on a varnish instance
    • VarnishAdmin::getParams - Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning - Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat - Set the class compat configuration param
    • VarnishAdmin::setHost - Set the class host configuration param
    • VarnishAdmin::setIdent - Set the class ident configuration param
    • VarnishAdmin::setParam - Set configuration param on the current varnish instance
    • VarnishAdmin::setPort - Set the class port configuration param
    • VarnishAdmin::setSecret - Set the class secret configuration param
    • VarnishAdmin::setTimeout - Set the class timeout configuration param
    • VarnishAdmin::start - Start varnish worker process
    • VarnishAdmin::stop - Stop varnish worker process
    • VarnishAdmin::__construct - VarnishAdmin constructor
    • VarnishLog::getLine - Get next log line
    • VarnishLog::getTagName - Get the log tag string representation by its index
    • VarnishLog::__construct - Varnishlog constructor
    • VarnishStat::getSnapshot - Get the current varnish instance statistics snapshot
    • VarnishStat::__construct - VarnishStat constructor
    • var_dump - Dumps information about a variable
    • var_export - Outputs or returns a parsable string representation of a variable
    • version_compare - Compares two "PHP-standardized" version number strings
    • vfprintf - Write a formatted string to a stream
    • virtual - Wykonuje zapytanie do Apache'a
    • vpopmail_add_alias_domain - Dodaje alias do domeny wirtualnej
    • vpopmail_add_alias_domain_ex - Dodaje alias do rzeczywistej domeny wirtualnej
    • vpopmail_add_domain - Dodaje nową domenę wirtualną
    • vpopmail_add_domain_ex - Dodaje nową rzeczywistą domenę wirtualną
    • vpopmail_add_user - Dodaje nowego użytkownika do podanej domeny wirtualnej
    • vpopmail_alias_add - Dodaje nowy alias do konta użytkownika
    • vpopmail_alias_del - Usuwa wszystkie wirtualne aliasy użytkownika
    • vpopmail_alias_del_domain - Usuwa wszystkie wirtualne aliasy domeny
    • vpopmail_alias_get - Zwraca tablicę z informacjami o aliasie dla domeny
    • vpopmail_alias_get_all - Zwraca tablicę z informacjami o aliasach dla domeny
    • vpopmail_auth_user - Sprawdza poprawność danych użytkownik/domena/hasło
    • vpopmail_del_domain - Usuwa domenę wirtualną
    • vpopmail_del_domain_ex - Usuwa rzeczywistą domenę wirtualną
    • vpopmail_del_user - Usuwa użytkownika z domeny wirtualnej
    • vpopmail_error - Pobiera komunikat tekstowy o ostatnim błędzie vpopmail
    • vpopmail_passwd - Zmienia hasło wirtualnego użytkownika
    • vpopmail_set_user_quota - Ustawia udział dyskowy dla wirtualnego użytkownika
    • vprintf - Output a formatted string
    • vsprintf - Return a formatted string
  • w
    • w32api_deftype - Defines a type for use with other w32api_functions
    • w32api_init_dtype - Creates an instance of the data type typename and fills it with the values passed
    • w32api_invoke_function - Invokes function funcname with the arguments passed after the function name
    • w32api_register_function - Registers function function_name from library with PHP
    • w32api_set_call_method - Sets the calling method used
    • wddx_add_vars - Add variables to a WDDX packet with the specified ID
    • wddx_deserialize - Unserializes a WDDX packet
    • wddx_packet_end - Ends a WDDX packet with the specified ID
    • wddx_packet_start - Starts a new WDDX packet with structure inside it
    • wddx_serialize_value - Serialize a single value into a WDDX packet
    • wddx_serialize_vars - Serialize variables into a WDDX packet
    • Weakref::acquire - Acquires a strong reference on that object
    • Weakref::get - Returns the object pointed to by the weak reference
    • Weakref::release - Releases a previously acquired reference
    • Weakref::valid - Checks whether the object referenced still exists
    • Weakref::__construct - Constructs a new weak reference
    • win32_continue_service - Resumes a paused service
    • win32_create_service - Creates a new service entry in the SCM database
    • win32_delete_service - Deletes a service entry from the SCM database
    • win32_get_last_control_message - Returns the last control message that was sent to this service
    • win32_pause_service - Pauses a service
    • win32_ps_list_procs - List running processes
    • win32_ps_stat_mem - Stat memory utilization
    • win32_ps_stat_proc - Stat process
    • win32_query_service_status - Queries the status of a service
    • win32_set_service_status - Update the service status
    • win32_start_service - Starts a service
    • win32_start_service_ctrl_dispatcher - Registers the script with the SCM, so that it can act as the service with the given name
    • win32_stop_service - Stops a service
    • wincache_fcache_fileinfo - Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo - Retrieves information about file cache memory usage
    • wincache_lock - Acquires an exclusive lock on a given key
    • wincache_ocache_fileinfo - Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo - Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed - Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo - Retrieves information about resolve file path cache
    • wincache_rplist_meminfo - Retrieves information about memory usage by the resolve file path cache
    • wincache_scache_info - Retrieves information about files cached in the session cache
    • wincache_scache_meminfo - Retrieves information about session cache memory usage
    • wincache_ucache_add - Adds a variable in user cache only if variable does not already exist in the cache
    • wincache_ucache_cas - Compares the variable with old value and assigns new value to it
    • wincache_ucache_clear - Deletes entire content of the user cache
    • wincache_ucache_dec - Decrements the value associated with the key
    • wincache_ucache_delete - Deletes variables from the user cache
    • wincache_ucache_exists - Checks if a variable exists in the user cache
    • wincache_ucache_get - Gets a variable stored in the user cache
    • wincache_ucache_inc - Increments the value associated with the key
    • wincache_ucache_info - Retrieves information about data stored in the user cache
    • wincache_ucache_meminfo - Retrieves information about user cache memory usage
    • wincache_ucache_set - Adds a variable in user cache and overwrites a variable if it already exists in the cache
    • wincache_unlock - Releases an exclusive lock on a given key
    • wordwrap - Zawija łańcuch znaków po podanej liczbie znaków używając znaku łamania łańcucha.
  • x
    • xattr_get - Get an extended attribute
    • xattr_list - Get a list of extended attributes
    • xattr_remove - Remove an extended attribute
    • xattr_set - Set an extended attribute
    • xattr_supported - Check if filesystem supports extended attributes
    • xdiff_file_bdiff - Make binary diff of two files
    • xdiff_file_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_file_bpatch - Patch a file with a binary diff
    • xdiff_file_diff - Make unified diff of two files
    • xdiff_file_diff_binary - Alias of xdiff_file_bdiff
    • xdiff_file_merge3 - Merge 3 files into one
    • xdiff_file_patch - Patch a file with an unified diff
    • xdiff_file_patch_binary - Alias of xdiff_file_bpatch
    • xdiff_file_rabdiff - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff - Make binary diff of two strings
    • xdiff_string_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_string_bpatch - Patch a string with a binary diff
    • xdiff_string_diff - Make unified diff of two strings
    • xdiff_string_diff_binary - Alias of xdiff_string_bdiff
    • xdiff_string_merge3 - Merge 3 strings into one
    • xdiff_string_patch - Patch a string with an unified diff
    • xdiff_string_patch_binary - Alias of xdiff_string_bpatch
    • xdiff_string_rabdiff - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
    • xhprof_disable - Stops xhprof profiler
    • xhprof_enable - Start xhprof profiler
    • xhprof_sample_disable - Stops xhprof sample profiler
    • xhprof_sample_enable - Description
    • XMLReader::close - Close the XMLReader input
    • XMLReader::expand - Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute - Get the value of a named attribute
    • XMLReader::getAttributeNo - Get the value of an attribute by index
    • XMLReader::getAttributeNs - Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty - Indicates if specified property has been set
    • XMLReader::isValid - Indicates if the parsed document is valid
    • XMLReader::lookupNamespace - Lookup namespace for a prefix
    • XMLReader::moveToAttribute - Move cursor to a named attribute
    • XMLReader::moveToAttributeNo - Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs - Move cursor to a named attribute
    • XMLReader::moveToElement - Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute - Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute - Position cursor on the next Attribute
    • XMLReader::next - Move cursor to next node skipping all subtrees
    • XMLReader::open - Set the URI containing the XML to parse
    • XMLReader::read - Move to next node in document
    • XMLReader::readInnerXML - Retrieve XML from current node
    • XMLReader::readOuterXML - Retrieve XML from current node, including it self
    • XMLReader::readString - Reads the contents of the current node as a string
    • XMLReader::setParserProperty - Set parser options
    • XMLReader::setRelaxNGSchema - Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource - Set the data containing a RelaxNG Schema
    • XMLReader::setSchema - Validate document against XSD
    • XMLReader::XML - Set the data containing the XML to parse
    • xmlrpc_decode - Decodes XML into native PHP types
    • xmlrpc_decode_request - Decodes XML into native PHP types
    • xmlrpc_encode - Generates XML for a PHP value
    • xmlrpc_encode_request - Generates XML for a method request
    • xmlrpc_get_type - Gets xmlrpc type for a PHP value
    • xmlrpc_is_fault - Determines if an array value represents an XMLRPC fault
    • xmlrpc_parse_method_descriptions - Decodes XML into a list of method descriptions
    • xmlrpc_server_add_introspection_data - Adds introspection documentation
    • xmlrpc_server_call_method - Parses XML requests and call methods
    • xmlrpc_server_create - Creates an xmlrpc server
    • xmlrpc_server_destroy - Destroys server resources
    • xmlrpc_server_register_introspection_callback - Register a PHP function to generate documentation
    • xmlrpc_server_register_method - Register a PHP function to resource method matching method_name
    • xmlrpc_set_type - Sets xmlrpc type, base64 or datetime, for a PHP string value
    • XMLWriter::endAttribute - End attribute
    • XMLWriter::endCData - End current CDATA
    • XMLWriter::endComment - Create end comment
    • XMLWriter::endDocument - End current document
    • XMLWriter::endDTD - End current DTD
    • XMLWriter::endDTDAttlist - End current DTD AttList
    • XMLWriter::endDTDElement - End current DTD element
    • XMLWriter::endDTDEntity - End current DTD Entity
    • XMLWriter::endElement - End current element
    • XMLWriter::endPI - End current PI
    • XMLWriter::flush - Flush current buffer
    • XMLWriter::fullEndElement - End current element
    • XMLWriter::openMemory - Create new xmlwriter using memory for string output
    • XMLWriter::openURI - Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory - Returns current buffer
    • XMLWriter::setIndent - Toggle indentation on/off
    • XMLWriter::setIndentString - Set string used for indenting
    • XMLWriter::startAttribute - Create start attribute
    • XMLWriter::startAttributeNS - Create start namespaced attribute
    • XMLWriter::startCData - Create start CDATA tag
    • XMLWriter::startComment - Create start comment
    • XMLWriter::startDocument - Create document tag
    • XMLWriter::startDTD - Create start DTD tag
    • XMLWriter::startDTDAttlist - Create start DTD AttList
    • XMLWriter::startDTDElement - Create start DTD element
    • XMLWriter::startDTDEntity - Create start DTD Entity
    • XMLWriter::startElement - Create start element tag
    • XMLWriter::startElementNS - Create start namespaced element tag
    • XMLWriter::startPI - Create start PI tag
    • XMLWriter::text - Write text
    • XMLWriter::writeAttribute - Write full attribute
    • XMLWriter::writeAttributeNS - Write full namespaced attribute
    • XMLWriter::writeCData - Write full CDATA tag
    • XMLWriter::writeComment - Write full comment tag
    • XMLWriter::writeDTD - Write full DTD tag
    • XMLWriter::writeDTDAttlist - Write full DTD AttList tag
    • XMLWriter::writeDTDElement - Write full DTD element tag
    • XMLWriter::writeDTDEntity - Write full DTD Entity tag
    • XMLWriter::writeElement - Write full element tag
    • XMLWriter::writeElementNS - Write full namespaced element tag
    • XMLWriter::writePI - Writes a PI
    • XMLWriter::writeRaw - Write a raw XML text
    • xml_error_string - Pobiera łańcuch znaków zawierający błąd parsera XML
    • xml_get_current_byte_index - Pobiera aktualny indeks bajtu parsera XML
    • xml_get_current_column_number - Pobiera aktualny numer kolumny dla parsera XML
    • xml_get_current_line_number - Pobiera aktualny numer linii dla parsera XML
    • xml_get_error_code - Pobiera kod błędu parsera XML
    • xml_parse - Rozpoczyna parsowanie dokumentu XML
    • xml_parser_create - Tworzy parser XML
    • xml_parser_create_ns - Create an XML parser with namespace support
    • xml_parser_free - Zwalnia parser XML
    • xml_parser_get_option - Get options from an XML parser
    • xml_parser_set_option - Set options in an XML parser
    • xml_parse_into_struct - Parse XML data into an array structure
    • xml_set_character_data_handler - Set up character data handler
    • xml_set_default_handler - Set up default handler
    • xml_set_element_handler - Ustawia początkową i końcową procedurę obsługi elementu
    • xml_set_end_namespace_decl_handler - Set up end namespace declaration handler
    • xml_set_external_entity_ref_handler - Set up external entity reference handler
    • xml_set_notation_decl_handler - Set up notation declaration handler
    • xml_set_object - Use XML Parser within an object
    • xml_set_processing_instruction_handler - Set up processing instruction (PI) handler
    • xml_set_start_namespace_decl_handler - Set up start namespace declaration handler
    • xml_set_unparsed_entity_decl_handler - Set up unparsed entity declaration handler
    • xpath_eval - Evaluates the XPath Location Path in the given string
    • xpath_eval_expression - Evaluates the XPath Location Path in the given string
    • xpath_new_context - Creates new xpath context
    • xpath_register_ns - Register the given namespace in the passed XPath context
    • xpath_register_ns_auto - Register the given namespace in the passed XPath context
    • xptr_eval - Evaluate the XPtr Location Path in the given string
    • xptr_new_context - Create new XPath Context
    • XSLTProcessor::getParameter - Get value of a parameter
    • XSLTProcessor::hasExsltSupport - Determine if PHP has EXSLT support
    • XSLTProcessor::importStylesheet - Import stylesheet
    • XSLTProcessor::registerPHPFunctions - Enables the ability to use PHP functions as XSLT functions
    • XSLTProcessor::removeParameter - Remove parameter
    • XSLTProcessor::setParameter - Set value for a parameter
    • XSLTProcessor::setProfiling - Sets profiling output file
    • XSLTProcessor::transformToDoc - Transform to a DOMDocument
    • XSLTProcessor::transformToUri - Transform to URI
    • XSLTProcessor::transformToXML - Transform to XML
    • XSLTProcessor::__construct - Creates a new XSLTProcessor object
    • xslt_backend_info - Returns the information on the compilation settings of the backend
    • xslt_backend_name - Returns the name of the backend
    • xslt_backend_version - Returns the version number of Sablotron
    • xslt_create - Create a new XSLT processor
    • xslt_errno - Returns an error number
    • xslt_error - Returns an error string
    • xslt_free - Free XSLT processor
    • xslt_getopt - Get options on a given xsl processor
    • xslt_process - Perform an XSLT transformation
    • xslt_setopt - Set options on a given XSLT processor
    • xslt_set_base - Set the base URI for all XSLT transformations
    • xslt_set_encoding - Set the encoding for the parsing of XML documents
    • xslt_set_error_handler - Set an error handler for a XSLT processor
    • xslt_set_log - Set the log file to write log messages to
    • xslt_set_object - Sets the object in which to resolve callback functions
    • xslt_set_sax_handler - Set SAX handlers for a XSLT processor
    • xslt_set_sax_handlers - Set the SAX handlers to be called when the XML document gets processed
    • xslt_set_scheme_handler - Set Scheme handlers for a XSLT processor
    • xslt_set_scheme_handlers - Set the scheme handlers for the XSLT processor
  • y
    • Yaf_Action_Abstract::execute - Execute the action
    • Yaf_Action_Abstract::getController - get controller instance
    • Yaf_Application::app - Retrive an Application instance
    • Yaf_Application::bootstrap - Call bootstrap
    • Yaf_Application::clearLastError - Clear the last error info
    • Yaf_Application::environ - Retrive environ
    • Yaf_Application::execute - Execute a callback
    • Yaf_Application::getAppDirectory - Get the application directory
    • Yaf_Application::getConfig - Retrive the config instance
    • Yaf_Application::getDispatcher - Get Yaf_Dispatcher instance
    • Yaf_Application::getLastErrorMsg - Get message of the last occurred error
    • Yaf_Application::getLastErrorNo - Get code of last occurred error
    • Yaf_Application::getModules - Get defined module names
    • Yaf_Application::run - Start Yaf_Application
    • Yaf_Application::setAppDirectory - Change the application directory
    • Yaf_Application::__clone - Yaf_Application can not be cloned
    • Yaf_Application::__construct - Yaf_Application constructor
    • Yaf_Application::__destruct - The __destruct purpose
    • Yaf_Application::__sleep - Yaf_Application can not be serialized
    • Yaf_Application::__wakeup - Yaf_Application can not be unserialized
    • Yaf_Config_Abstract::get - Getter
    • Yaf_Config_Abstract::readonly - Find a config whether readonly
    • Yaf_Config_Abstract::set - Setter
    • Yaf_Config_Abstract::toArray - Cast to array
    • Yaf_Config_Ini::count - The count purpose
    • Yaf_Config_Ini::current - The current purpose
    • Yaf_Config_Ini::key - The key purpose
    • Yaf_Config_Ini::next - The next purpose
    • Yaf_Config_Ini::offsetExists - The offsetExists purpose
    • Yaf_Config_Ini::offsetGet - The offsetGet purpose
    • Yaf_Config_Ini::offsetSet - The offsetSet purpose
    • Yaf_Config_Ini::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Ini::readonly - The readonly purpose
    • Yaf_Config_Ini::rewind - The rewind purpose
    • Yaf_Config_Ini::toArray - The toArray purpose
    • Yaf_Config_Ini::valid - The valid purpose
    • Yaf_Config_Ini::__construct - The __construct purpose
    • Yaf_Config_Ini::__get - The __get purpose
    • Yaf_Config_Ini::__isset - The __isset purpose
    • Yaf_Config_Ini::__set - The __set purpose
    • Yaf_Config_Simple::count - The count purpose
    • Yaf_Config_Simple::current - The current purpose
    • Yaf_Config_Simple::key - The key purpose
    • Yaf_Config_Simple::next - The next purpose
    • Yaf_Config_Simple::offsetExists - The offsetExists purpose
    • Yaf_Config_Simple::offsetGet - The offsetGet purpose
    • Yaf_Config_Simple::offsetSet - The offsetSet purpose
    • Yaf_Config_Simple::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Simple::readonly - The readonly purpose
    • Yaf_Config_Simple::rewind - The rewind purpose
    • Yaf_Config_Simple::toArray - The toArray purpose
    • Yaf_Config_Simple::valid - The valid purpose
    • Yaf_Config_Simple::__construct - The __construct purpose
    • Yaf_Config_Simple::__get - The __get purpose
    • Yaf_Config_Simple::__isset - The __isset purpose
    • Yaf_Config_Simple::__set - The __set purpose
    • Yaf_Controller_Abstract::display - The display purpose
    • Yaf_Controller_Abstract::forward - The forward purpose
    • Yaf_Controller_Abstract::getInvokeArg - The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs - The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName - The getModuleName purpose
    • Yaf_Controller_Abstract::getRequest - The getRequest purpose
    • Yaf_Controller_Abstract::getResponse - The getResponse purpose
    • Yaf_Controller_Abstract::getView - The getView purpose
    • Yaf_Controller_Abstract::getViewpath - The getViewpath purpose
    • Yaf_Controller_Abstract::initView - The initView purpose
    • Yaf_Controller_Abstract::redirect - The redirect purpose
    • Yaf_Controller_Abstract::render - The render purpose
    • Yaf_Controller_Abstract::setViewpath - The setViewpath purpose
    • Yaf_Controller_Abstract::__clone - Yaf_Controller_Abstract can not be cloned
    • Yaf_Controller_Abstract::__construct - Yaf_Controller_Abstract constructor
    • Yaf_Dispatcher::autoRender - Switch on/off autorendering
    • Yaf_Dispatcher::catchException - Switch on/off exception catching
    • Yaf_Dispatcher::disableView - Disable view rendering
    • Yaf_Dispatcher::dispatch - Dispatch a request
    • Yaf_Dispatcher::enableView - enable view rendering
    • Yaf_Dispatcher::flushInstantly - Switch on/off the instant flushing
    • Yaf_Dispatcher::getApplication - Retrive the application
    • Yaf_Dispatcher::getInstance - Retrive the dispatcher instance
    • Yaf_Dispatcher::getRequest - Retrive the request instance
    • Yaf_Dispatcher::getRouter - Retrive router instance
    • Yaf_Dispatcher::initView - Initialize view and return it
    • Yaf_Dispatcher::registerPlugin - Register a plugin
    • Yaf_Dispatcher::returnResponse - The returnResponse purpose
    • Yaf_Dispatcher::setAppDirectory - Change the application directory
    • Yaf_Dispatcher::setDefaultAction - Change default action name
    • Yaf_Dispatcher::setDefaultController - Change default controller name
    • Yaf_Dispatcher::setDefaultModule - Change default module name
    • Yaf_Dispatcher::setErrorHandler - The setErrorHandler purpose
    • Yaf_Dispatcher::setRequest - The setRequest purpose
    • Yaf_Dispatcher::setView - Set a custom view engine
    • Yaf_Dispatcher::throwException - Switch on/off exception throwing
    • Yaf_Dispatcher::__clone - Yaf_Dispatcher can not be cloned
    • Yaf_Dispatcher::__construct - Yaf_Dispatcher constructor
    • Yaf_Dispatcher::__sleep - Yaf_Dispatcher can not be serialized
    • Yaf_Dispatcher::__wakeup - Yaf_Dispatcher can not be unserialized
    • Yaf_Exception::getPrevious - The getPrevious purpose
    • Yaf_Exception::__construct - The __construct purpose
    • Yaf_Loader::autoload - The autoload purpose
    • Yaf_Loader::clearLocalNamespace - The clearLocalNamespace purpose
    • Yaf_Loader::getInstance - The getInstance purpose
    • Yaf_Loader::getLibraryPath - get the library path
    • Yaf_Loader::getLocalNamespace - The getLocalNamespace purpose
    • Yaf_Loader::import - The import purpose
    • Yaf_Loader::isLocalName - The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace - The registerLocalNamespace purpose
    • Yaf_Loader::setLibraryPath - Change the library path
    • Yaf_Loader::__clone - The __clone purpose
    • Yaf_Loader::__construct - The __construct purpose
    • Yaf_Loader::__sleep - The __sleep purpose
    • Yaf_Loader::__wakeup - The __wakeup purpose
    • Yaf_Plugin_Abstract::dispatchLoopShutdown - The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup - The dispatchLoopStartup purpose
    • Yaf_Plugin_Abstract::postDispatch - The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch - The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse - The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown - The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup - RouterStartup hook
    • Yaf_Registry::del - The del purpose
    • Yaf_Registry::get - The get purpose
    • Yaf_Registry::has - The has purpose
    • Yaf_Registry::set - The set purpose
    • Yaf_Registry::__clone - The __clone purpose
    • Yaf_Registry::__construct - The __construct purpose
    • Yaf_Request_Abstract::getActionName - The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri - The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName - The getControllerName purpose
    • Yaf_Request_Abstract::getEnv - The getEnv purpose
    • Yaf_Request_Abstract::getException - The getException purpose
    • Yaf_Request_Abstract::getLanguage - The getLanguage purpose
    • Yaf_Request_Abstract::getMethod - The getMethod purpose
    • Yaf_Request_Abstract::getModuleName - The getModuleName purpose
    • Yaf_Request_Abstract::getParam - The getParam purpose
    • Yaf_Request_Abstract::getParams - The getParams purpose
    • Yaf_Request_Abstract::getRequestUri - The getRequestUri purpose
    • Yaf_Request_Abstract::getServer - The getServer purpose
    • Yaf_Request_Abstract::isCli - The isCli purpose
    • Yaf_Request_Abstract::isDispatched - The isDispatched purpose
    • Yaf_Request_Abstract::isGet - The isGet purpose
    • Yaf_Request_Abstract::isHead - The isHead purpose
    • Yaf_Request_Abstract::isOptions - The isOptions purpose
    • Yaf_Request_Abstract::isPost - The isPost purpose
    • Yaf_Request_Abstract::isPut - The isPut purpose
    • Yaf_Request_Abstract::isRouted - The isRouted purpose
    • Yaf_Request_Abstract::isXmlHttpRequest - The isXmlHttpRequest purpose
    • Yaf_Request_Abstract::setActionName - The setActionName purpose
    • Yaf_Request_Abstract::setBaseUri - The setBaseUri purpose
    • Yaf_Request_Abstract::setControllerName - The setControllerName purpose
    • Yaf_Request_Abstract::setDispatched - The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName - The setModuleName purpose
    • Yaf_Request_Abstract::setParam - The setParam purpose
    • Yaf_Request_Abstract::setRequestUri - The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted - The setRouted purpose
    • Yaf_Request_Http::get - The get purpose
    • Yaf_Request_Http::getCookie - The getCookie purpose
    • Yaf_Request_Http::getFiles - The getFiles purpose
    • Yaf_Request_Http::getPost - The getPost purpose
    • Yaf_Request_Http::getQuery - fetch a query parameter
    • Yaf_Request_Http::getRequest - The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest - The isXmlHttpRequest purpose
    • Yaf_Request_Http::__clone - The __clone purpose
    • Yaf_Request_Http::__construct - The __construct purpose
    • Yaf_Request_Simple::get - The get purpose
    • Yaf_Request_Simple::getCookie - The getCookie purpose
    • Yaf_Request_Simple::getFiles - The getFiles purpose
    • Yaf_Request_Simple::getPost - The getPost purpose
    • Yaf_Request_Simple::getQuery - The getQuery purpose
    • Yaf_Request_Simple::getRequest - The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest - The isXmlHttpRequest purpose
    • Yaf_Request_Simple::__clone - The __clone purpose
    • Yaf_Request_Simple::__construct - The __construct purpose
    • Yaf_Response_Abstract::appendBody - The appendBody purpose
    • Yaf_Response_Abstract::clearBody - The clearBody purpose
    • Yaf_Response_Abstract::clearHeaders - The clearHeaders purpose
    • Yaf_Response_Abstract::getBody - The getBody purpose
    • Yaf_Response_Abstract::getHeader - The getHeader purpose
    • Yaf_Response_Abstract::prependBody - The prependBody purpose
    • Yaf_Response_Abstract::response - The response purpose
    • Yaf_Response_Abstract::setAllHeaders - The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody - The setBody purpose
    • Yaf_Response_Abstract::setHeader - The setHeader purpose
    • Yaf_Response_Abstract::setRedirect - The setRedirect purpose
    • Yaf_Response_Abstract::__clone - The __clone purpose
    • Yaf_Response_Abstract::__construct - The __construct purpose
    • Yaf_Response_Abstract::__destruct - The __destruct purpose
    • Yaf_Response_Abstract::__toString - The __toString purpose
    • Yaf_Router::addConfig - Add config-defined routes into Router
    • Yaf_Router::addRoute - Add new Route into Router
    • Yaf_Router::getCurrentRoute - Get the effective route name
    • Yaf_Router::getRoute - The getRoute purpose
    • Yaf_Router::getRoutes - The getRoutes purpose
    • Yaf_Router::route - The route purpose
    • Yaf_Router::__construct - Yaf_Router constructor
    • Yaf_Route_Interface::route - route a request
    • Yaf_Route_Map::route - The route purpose
    • Yaf_Route_Map::__construct - The __construct purpose
    • Yaf_Route_Regex::route - The route purpose
    • Yaf_Route_Regex::__construct - The __construct purpose
    • Yaf_Route_Rewrite::route - The route purpose
    • Yaf_Route_Rewrite::__construct - The __construct purpose
    • Yaf_Route_Simple::route - Route a request
    • Yaf_Route_Simple::__construct - Yaf_Route_Simple constructor
    • Yaf_Route_Static::match - The match purpose
    • Yaf_Route_Static::route - Route a request
    • Yaf_Route_Supervar::route - The route purpose
    • Yaf_Route_Supervar::__construct - The __construct purpose
    • Yaf_Session::count - The count purpose
    • Yaf_Session::current - The current purpose
    • Yaf_Session::del - The del purpose
    • Yaf_Session::getInstance - The getInstance purpose
    • Yaf_Session::has - The has purpose
    • Yaf_Session::key - The key purpose
    • Yaf_Session::next - The next purpose
    • Yaf_Session::offsetExists - The offsetExists purpose
    • Yaf_Session::offsetGet - The offsetGet purpose
    • Yaf_Session::offsetSet - The offsetSet purpose
    • Yaf_Session::offsetUnset - The offsetUnset purpose
    • Yaf_Session::rewind - The rewind purpose
    • Yaf_Session::start - The start purpose
    • Yaf_Session::valid - The valid purpose
    • Yaf_Session::__clone - The __clone purpose
    • Yaf_Session::__construct - The __construct purpose
    • Yaf_Session::__get - The __get purpose
    • Yaf_Session::__isset - The __isset purpose
    • Yaf_Session::__set - The __set purpose
    • Yaf_Session::__sleep - The __sleep purpose
    • Yaf_Session::__unset - The __unset purpose
    • Yaf_Session::__wakeup - The __wakeup purpose
    • Yaf_View_Interface::assign - Assign value to View engine
    • Yaf_View_Interface::display - Render and output a template
    • Yaf_View_Interface::getScriptPath - The getScriptPath purpose
    • Yaf_View_Interface::render - Render a template
    • Yaf_View_Interface::setScriptPath - The setScriptPath purpose
    • Yaf_View_Simple::assign - Assign values
    • Yaf_View_Simple::assignRef - The assignRef purpose
    • Yaf_View_Simple::display - Render and dispaly
    • Yaf_View_Simple::getScriptPath - Get template base directory
    • Yaf_View_Simple::render - Render template
    • Yaf_View_Simple::setScriptPath - Set tempalte base directory
    • Yaf_View_Simple::__construct - The __construct purpose
    • Yaf_View_Simple::__get - The __get purpose
    • Yaf_View_Simple::__isset - The __isset purpose
    • Yaf_View_Simple::__set - Set value to engine
    • yaml_emit - Returns the YAML representation of a value
    • yaml_emit_file - Send the YAML representation of a value to a file
    • yaml_parse - Parse a YAML stream
    • yaml_parse_file - Parse a YAML stream from a file
    • yaml_parse_url - Parse a Yaml stream from a URL
    • yaz_addinfo - Returns additional error information
    • yaz_ccl_conf - Configure CCL parser
    • yaz_ccl_parse - Invoke CCL Parser
    • yaz_close - Close YAZ connection
    • yaz_connect - Prepares for a connection to a Z39.50 server
    • yaz_database - Specifies the databases within a session
    • yaz_element - Specifies Element-Set Name for retrieval
    • yaz_errno - Returns error number
    • yaz_error - Returns error description
    • yaz_es - Prepares for an Extended Service Request
    • yaz_es_result - Inspects Extended Services Result
    • yaz_get_option - Returns value of option for connection
    • yaz_hits - Returns number of hits for last search
    • yaz_itemorder - Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present - Prepares for retrieval (Z39.50 present)
    • yaz_range - Specifies a range of records to retrieve
    • yaz_record - Returns a record
    • yaz_scan - Prepares for a scan
    • yaz_scan_result - Returns Scan Response result
    • yaz_schema - Specifies schema for retrieval
    • yaz_search - Prepares for a search
    • yaz_set_option - Sets one or more options for connection
    • yaz_sort - Sets sorting criteria
    • yaz_syntax - Specifies the preferred record syntax for retrieval
    • yaz_wait - Wait for Z39.50 requests to complete
    • yp_all - Traverse the map and call a function on each entry
    • yp_cat - Return an array containing the entire map
    • yp_errno - Returns the error code of the previous operation
    • yp_err_string - Returns the error string associated with the given error code
    • yp_first - Returns the first key-value pair from the named map
    • yp_get_default_domain - Fetches the machine's default NIS domain
    • yp_master - Returns the machine name of the master NIS server for a map
    • yp_match - Returns the matched line
    • yp_next - Returns the next key-value pair in the named map
    • yp_order - Returns the order number for a map
  • z
    • zend_logo_guid - Gets the Zend guid
    • zend_thread_id - Returns a unique identifier for the current thread
    • zend_version - Gets the version of the current Zend engine
    • ZipArchive::addEmptyDir - Add a new directory
    • ZipArchive::addFile - Adds a file to a ZIP archive from the given path
    • ZipArchive::addFromString - Add a file to a ZIP archive using its contents
    • ZipArchive::close - Close the active archive (opened or newly created)
    • ZipArchive::deleteIndex - delete an entry in the archive using its index
    • ZipArchive::deleteName - delete an entry in the archive using its name
    • ZipArchive::extractTo - Extract the archive contents
    • ZipArchive::getArchiveComment - Returns the Zip archive comment
    • ZipArchive::getCommentIndex - Returns the comment of an entry using the entry index
    • ZipArchive::getCommentName - Returns the comment of an entry using the entry name
    • ZipArchive::getFromIndex - Returns the entry contents using its index
    • ZipArchive::getFromName - Returns the entry contents using its name
    • ZipArchive::getNameIndex - Returns the name of an entry using its index
    • ZipArchive::getStatusString - Returns the status error message, system and/or zip messages
    • ZipArchive::getStream - Get a file handler to the entry defined by its name (read only).
    • ZipArchive::locateName - Returns the index of the entry in the archive
    • ZipArchive::open - Open a ZIP file archive
    • ZipArchive::renameIndex - Renames an entry defined by its index
    • ZipArchive::renameName - Renames an entry defined by its name
    • ZipArchive::setArchiveComment - Set the comment of a ZIP archive
    • ZipArchive::setCommentIndex - Set the comment of an entry defined by its index
    • ZipArchive::setCommentName - Set the comment of an entry defined by its name
    • ZipArchive::statIndex - Get the details of an entry defined by its index.
    • ZipArchive::statName - Get the details of an entry defined by its name.
    • ZipArchive::unchangeAll - Undo all changes done in the archive
    • ZipArchive::unchangeArchive - Revert all global changes done in the archive.
    • ZipArchive::unchangeIndex - Revert all changes done to an entry at the given index
    • ZipArchive::unchangeName - Revert all changes done to an entry with the given name.
    • zip_close - Close a ZIP file archive
    • zip_entry_close - Close a directory entry
    • zip_entry_compressedsize - Retrieve the compressed size of a directory entry
    • zip_entry_compressionmethod - Retrieve the compression method of a directory entry
    • zip_entry_filesize - Retrieve the actual file size of a directory entry
    • zip_entry_name - Retrieve the name of a directory entry
    • zip_entry_open - Open a directory entry for reading
    • zip_entry_read - Read from an open directory entry
    • zip_open - Open a ZIP file archive
    • zip_read - Read next entry in a ZIP file archive
    • zlib:// - Compression Streams
    • zlib_get_coding_type - Returns the coding type used for output compression
  • _
    • __autoload - Attempt to load undefined class
    • __halt_compiler - Halts the compiler execution
Indeks
Wykaz przykładów
Indeks


Wykaz przykładów

Lista wszystkich przykładów zawartych w podręczniku PHP

  • Example#0 - An introductory example
  • Example#1 - Our first PHP script: hello.php
  • Example#2 - Get system information from PHP
  • Example#3 - Printing a variable (Array element)
  • Example#4 - Example using control structures and functions
  • Example#5 - Mixing both HTML and PHP modes
  • Example#6 - A simple HTML form
  • Example#7 - Printing data from our form
  • Example#8 - Installation Instructions (Apache Shared Module Version) for PHP
  • Example#9 - Installation Instructions (Static Module Installation for Apache) for PHP
  • Example#10 - Example commands for restarting Apache
  • Example#11 -
  • Example#12 -
  • Example#13 -
  • Example#14 -
  • Example#15 -
  • Example#16 -
  • Example#17 -
  • Example#18 -
  • Example#19 -
  • Example#20 -
  • Example#21 -
  • Example#22 -
  • Example#23 -
  • Example#24 -
  • Example#25 -
  • Example#26 - Partial lighttpd.conf
  • Example#27 - Spawning FastCGI Responders
  • Example#28 - Connecting to remote php-fastcgi instances
  • Example#29 - OpenBSD Package Install Example
  • Example#30 - Debian Install Example with Apache 2
  • Example#31 - Stopping and starting Apache once PHP is installed
  • Example#32 - Methods for listing additional PHP 5 packages
  • Example#33 - Install PHP with MySQL, cURL
  • Example#34 - PHP 5 package structure
  • Example#35 - CGI and FastCGI settings in php.ini
  • Example#36 - Configuring FastCGI extension to handle PHP requests
  • Example#37 - Configuring file access permissions
  • Example#38 - Configuring FastCGI and PHP recycling
  • Example#39 - Configuring FastCGI timeout settings
  • Example#40 - Changing the location of php.ini file
  • Example#41 - CGI and FastCGI settings in php.ini
  • Example#42 - Creating IIS FastCGI process pool
  • Example#43 - Creating handler mapping for PHP requests
  • Example#44 - Determining the account used as IIS anonymous identity
  • Example#45 - Configuring file access permissions
  • Example#46 - Set index.php as a default document in IIS
  • Example#47 - Configuring FastCGI and PHP recycling
  • Example#48 - Configuring FastCGI timeout settings
  • Example#49 - Changing the location of php.ini file
  • Example#50 - PHP as an Apache 1.3.x module
  • Example#51 - PHP and Apache 1.3.x as CGI
  • Example#52 - PHP and Apache 2.x as handler
  • Example#53 -
  • Example#54 - PHP and Apache 2.x as CGI
  • Example#55 - Configure Apache to run PHP as FastCGI
  • Example#56 - ISAPI configuration of Sambar
  • Example#57 - Enable Bzip2 extension for PHP-Windows
  • Example#58 - Registry changes
  • Example#59 - Passing environment variables and PHP settings to a pool
  • Example#60 - phpinfo call
  • Example#61 - php.ini example
  • Example#62 - Apache configuration example
  • Example#63 - Zaawansowane wyskakiwanie
  • Example#64 - Znaczniki otwierające i zamykające PHP
  • Example#65 - Integer literals
  • Example#66 - Octal weirdness
  • Example#67 - Integer overflow on a 32-bit system
  • Example#68 - Integer overflow on a 64-bit system
  • Example#69 - Invalid example
  • Example#70 - Heredoc string quoting example
  • Example#71 - Heredoc in arguments example
  • Example#72 - Using Heredoc to initialize static values
  • Example#73 - Using double quotes in Heredoc
  • Example#74 - Nowdoc string quoting example
  • Example#75 - Static data example
  • Example#76 - Simple syntax example
  • Example#77 - Some string examples
  • Example#78 - Using array()
  • Example#79 - Collection
  • Example#80 - Changing element in the loop
  • Example#81 - One-based index
  • Example#82 - Filling an array
  • Example#83 - Sorting an array
  • Example#84 - Recursive and multi-dimensional arrays
  • Example#85 - Callback function examples
  • Example#86 - Callback example using a Closure
  • Example#87 - Domyślne wartości niezainicjowanych zmiennych
  • Example#88 - Używanie polecenia global
  • Example#89 - Używanie $GLOBALS zamiast polecenia global
  • Example#90 - Przykład demonstrujący superglobale i zasięg zmiennych
  • Example#91 - Przykład ukazujący przydatność zmiennych statycznych
  • Example#92 - Przykład użycia zmiennych statycznych
  • Example#93 - Zmienne statyczne w funkcjach rekurencyjnych
  • Example#94 - Deklaracja zmiennych statycznych
  • Example#95 - Prosty formularz HTML
  • Example#96 - Dostęp do informacji z prostego formularza HTML (wysłanego metodą POST)
  • Example#97 - Bardziej złożone zmienne w formularzach
  • Example#98 - Przykład użycia funkcji setcookie
  • Example#99 - Poprawne i niepoprawne nazwy stałych
  • Example#100 - Definiowanie stałych
  • Example#101 - Associativity
  • Example#102 - Assigning by reference
  • Example#103 - Bitwise AND, OR and XOR operations on integers
  • Example#104 - Bitwise XOR operations on strings
  • Example#105 - Bit shifting on integers
  • Example#106 - Transcription of standard array comparison
  • Example#107 - Assigning a default value
  • Example#108 - Non-obvious Ternary Behaviour
  • Example#109 - Arithmetic Operations on Character Variables
  • Example#110 - Logical operators illustrated
  • Example#111 - Comparing arrays
  • Example#112 - Using instanceof with classes
  • Example#113 - Using instanceof with inherited classes
  • Example#114 - Using instanceof to check if object is not an instanceof a class
  • Example#115 - Using instanceof for class
  • Example#116 - Using instanceof with other variables
  • Example#117 - Avoiding classname lookups and fatal errors with instanceof in PHP 5.0
  • Example#118 - switch structure
  • Example#119 - switch structure allows usage of strings
  • Example#120 - Tick usage example
  • Example#121 - Ticks usage example
  • Example#122 - Declaring an encoding for the script.
  • Example#123 - Basic include example
  • Example#124 - Including within functions
  • Example#125 - include through HTTP
  • Example#126 - Comparing return value of include
  • Example#127 - include and the return statement
  • Example#128 - Using output buffering to include a PHP file into a string
  • Example#129 - include_once with a case insensitive OS in PHP 4
  • Example#130 - goto example
  • Example#131 - goto loop example
  • Example#132 - This will not work
  • Example#133 - Pseudokod demonstrujący użycie funkcji
  • Example#134 - Funkcje zdefiniowane warunkowo
  • Example#135 - Funkcje wewnątrz funkcji
  • Example#136 - Funkcje rekurencyjne
  • Example#137 - Tablica jako argument funkcji
  • Example#138 - Podawanie parametrów funkcji przez referencję
  • Example#139 - Użycie domyślnych wartości argumentów w funkcji
  • Example#140 - Użycie nie-skalarnych typów jako domyślnych wartości
  • Example#141 - Niepoprawne użycie domyślnych wartości argumentów
  • Example#142 - Poprawne użycie domyślnych wartości argumentów
  • Example#143 - Użycie return
  • Example#144 - Zwracanie tablicy
  • Example#145 - Zwracanie referencji
  • Example#146 - Przykład funkcji zmiennych
  • Example#147 - Przykład metod zmiennych
  • Example#148 - Simple Class definition
  • Example#149 - Some examples of the $this pseudo-variable
  • Example#150 - Creating an instance
  • Example#151 - Object Assignment
  • Example#152 - Creating new objects
  • Example#153 - Simple Class Inheritance
  • Example#154 - property declarations
  • Example#155 - Example of using a nowdoc to initialize a property
  • Example#156 - Defining and using a constant
  • Example#157 - Static data example
  • Example#158 - Autoload example
  • Example#159 - Autoload other example
  • Example#160 - Autoloading with exception handling for 5.3.0+
  • Example#161 - Autoloading with exception handling for 5.3.0+ - Missing custom exception
  • Example#162 - using new unified constructors
  • Example#163 - Constructors in namespaced classes
  • Example#164 - Destructor Example
  • Example#165 - Property declaration
  • Example#166 - Method Declaration
  • Example#167 - Accessing private members of the same object type
  • Example#168 - Inheritance Example
  • Example#169 - :: from outside the class definition
  • Example#170 - :: from inside the class definition
  • Example#171 - Calling a parent's method
  • Example#172 - Static property example
  • Example#173 - Static method example
  • Example#174 - Abstract class example
  • Example#175 - Interface example
  • Example#176 - Extendable Interfaces
  • Example#177 - Multiple interface inheritance
  • Example#178 - Interfaces with constants
  • Example#179 - Trait example
  • Example#180 - Precedence Order Example
  • Example#181 - Alternate Precedence Order Example
  • Example#182 - Multiple Traits Usage
  • Example#183 - Conflict Resolution
  • Example#184 - Changing Method Visibility
  • Example#185 - Traits Composed from Traits
  • Example#186 - Express Requirements by Abstract Methods
  • Example#187 - Static Variables
  • Example#188 - Static Methods
  • Example#189 - Defining Properties
  • Example#190 - Conflict Resolution
  • Example#191 - Overloading properties via the __get(), __set(), __isset() and __unset() methods
  • Example#192 - Overloading methods via the __call() and __callStatic() methods
  • Example#193 - Simple Object Iteration
  • Example#194 - Object Iteration implementing Iterator
  • Example#195 - Object Iteration implementing IteratorAggregate
  • Example#196 - Parameterized Factory Method
  • Example#197 - Singleton example
  • Example#198 - Sleep and wakeup
  • Example#199 - Simple example
  • Example#200 - Using __invoke()
  • Example#201 - Using __set_state() (since PHP 5.1.0)
  • Example#202 - Final methods example
  • Example#203 - Final class example
  • Example#204 - Cloning an object
  • Example#205 - Example of object comparison in PHP 5
  • Example#206 - Type Hinting examples
  • Example#207 - self:: usage
  • Example#208 - static:: simple usage
  • Example#209 - static:: usage in a non-static context
  • Example#210 - Forwarding and non-forwarding calls
  • Example#211 - References and Objects
  • Example#212 - Namespace syntax example
  • Example#213 - Declaring a single namespace
  • Example#214 - Declaring a single namespace
  • Example#215 - Declaring a single namespace with hierarchy
  • Example#216 - Declaring multiple namespaces, simple combination syntax
  • Example#217 - Declaring multiple namespaces, bracketed syntax
  • Example#218 - Declaring multiple namespaces and unnamespaced code
  • Example#219 - Declaring multiple namespaces and unnamespaced code
  • Example#220 - Accessing global classes, functions and constants from within a namespace
  • Example#221 - Dynamically accessing elements
  • Example#222 - Dynamically accessing namespaced elements
  • Example#223 - __NAMESPACE__ example, namespaced code
  • Example#224 - __NAMESPACE__ example, global code
  • Example#225 - using __NAMESPACE__ for dynamic name construction
  • Example#226 - the namespace operator, inside a namespace
  • Example#227 - the namespace operator, in global code
  • Example#228 - importing/aliasing with the use operator
  • Example#229 - importing/aliasing with the use operator, multiple use statements combined
  • Example#230 - Importing and dynamic names
  • Example#231 - Importing and fully qualified names
  • Example#232 - Illegal importing rule
  • Example#233 - Using global space specification
  • Example#234 - Accessing global classes inside a namespace
  • Example#235 - global functions/constants fallback inside a namespace
  • Example#236 - Name resolutions illustrated
  • Example#237 - Accessing global classes outside a namespace
  • Example#238 - Accessing global classes outside a namespace
  • Example#239 - Accessing internal classes in namespaces
  • Example#240 - Accessing internal classes, functions or constants in namespaces
  • Example#241 - Fully Qualified names
  • Example#242 - Qualified names
  • Example#243 - Unqualified class names
  • Example#244 - Unqualified function or constant names
  • Example#245 - Dangers of using namespaced names inside a double-quoted string
  • Example#246 - Undefined constants
  • Example#247 - Undefined constants
  • Example#248 - Throwing an Exception
  • Example#249 - Nested Exception
  • Example#250 - The Built in Exception class
  • Example#251 - Extending the Exception class (PHP 5.3.0+)
  • Example#252 - $GLOBALS example
  • Example#253 - $_SERVER example
  • Example#254 - $_GET example
  • Example#255 - $_POST example
  • Example#256 - $_ENV example
  • Example#257 - $_COOKIE example
  • Example#258 - $php_errormsg example
  • Example#259 - $http_response_header example
  • Example#260 - $argc example
  • Example#261 - $argv example
  • Example#262 - Exception::getMessage example
  • Example#263 - Exception::getPrevious example
  • Example#264 - Exception::getCode example
  • Example#265 - Exception::getFile example
  • Example#266 - Exception::getLine example
  • Example#267 - Exception::getTrace example
  • Example#268 - Exception::getTraceAsString example
  • Example#269 - Exception::__toString example
  • Example#270 - Use set_error_handler to change error messages into ErrorException.
  • Example#271 - ErrorException::getSeverity example
  • Example#272 - Basic usage
  • Example#273 - Basic usage
  • Example#274 - Basic usage
  • Example#275 - ArrayAccess::offsetExists example
  • Example#276 - Basic usage
  • Example#277 - Closure::bind example
  • Example#278 - Closure::bindTo example
  • Example#279 - Basic bindto usage example
  • Example#280 - Fetch a page and send POST data
  • Example#281 - Ignore redirects but fetch headers and content
  • Example#282 - Fetch a page and send POST data
  • Example#283 - Detecting which URL we ended up on after redirects
  • Example#284 - Sending custom headers with an HTTP request
  • Example#285 - php://temp/maxmemory
  • Example#286 - php://filter/resource=<stream to be filtered>
  • Example#287 - php://filter/read=<filter list to apply to read chain>
  • Example#288 - php://filter/write=<filter list to apply to write chain>
  • Example#289 - Print data:// contents
  • Example#290 - Fetch the media type
  • Example#291 - Basic usage
  • Example#292 - Opening a stream from an active connection
  • Example#293 - Traversing a RAR archive
  • Example#294 - Opening an encrypted file (header encryption)
  • Example#295 - Poor variable checking leads to....
  • Example#296 - ... A filesystem attack
  • Example#297 - More secure file name checking
  • Example#298 - More secure file name checking
  • Example#299 - Script vulnerable to null bytes
  • Example#300 - Correctly validating the input
  • Example#301 - Using hashed password field
  • Example#302 - Splitting the result set into pages ... and making superusers (PostgreSQL)
  • Example#303 - Listing out articles ... and some passwords (any database server)
  • Example#304 - From resetting a password ... to gaining more privileges (any database server)
  • Example#305 - Attacking the database hosts operating system (MSSQL Server)
  • Example#306 - A more secure way to compose a query for paging
  • Example#307 - Attacking Variables with a custom HTML page
  • Example#308 - Exploiting common debugging variables
  • Example#309 - Finding dangerous variables with E_ALL
  • Example#310 - Example misuse with register_globals = on
  • Example#311 - Example use of sessions with register_globals on or off
  • Example#312 - Detecting simple variable poisoning
  • Example#313 - Dangerous Variable Usage
  • Example#314 - Disabling magic quotes server side
  • Example#315 - Disabling magic quotes at runtime
  • Example#316 - Hiding PHP as another language
  • Example#317 - Using unknown types for PHP extensions
  • Example#318 - Using HTML types for PHP extensions
  • Example#319 - Uwierzytelnianie Basic HTTP
  • Example#320 - Przykład uwierzytelnianie Digest HTTP
  • Example#321 - Uwierzytelnianie HTTP z wymuszeniem przelogowania
  • Example#322 - A simple XForms search form
  • Example#323 - Using an XForm to populate $_POST
  • Example#324 - File Upload Form
  • Example#325 - Validating file uploads
  • Example#326 - Uploading array of files
  • Example#327 - Uploading multiple files
  • Example#328 - Saving HTTP PUT files
  • Example#329 - Pobieranie tytułu zdalnej strony
  • Example#330 - Zapisywanie danych na zdalnym serwerze.
  • Example#331 - Example showing the difference to the CGI SAPI:
  • Example#332 -
  • Example#333 - Printing built in (and loaded) PHP and Zend modules
  • Example#334 - Getting a syntax error when using double quotes
  • Example#335 - Using single quotes to prevent the shell's variable substitution
  • Example#336 - Using the -B, -R and -E options to count the number of lines of a project.
  • Example#337 - Using -v to get the SAPI name and the version of PHP and Zend
  • Example#338 - --ini example
  • Example#339 - basic --rf usage
  • Example#340 - --rc example
  • Example#341 - --re example
  • Example#342 - --ri example
  • Example#343 - Execute PHP script as shell script
  • Example#344 - Script intended to be run from command line (script.php)
  • Example#345 - Batch file to run a command line PHP script (script.bat)
  • Example#346 - Executing code using the interactive shell
  • Example#347 - Tab completion
  • Example#348 - Setting php.ini settings in the interactive shell
  • Example#349 - Starting the web server
  • Example#350 - Starting with a specific document root directory
  • Example#351 - Using a Router Script
  • Example#352 - Creating a new zval container
  • Example#353 - Displaying zval information
  • Example#354 - Increasing refcount of a zval
  • Example#355 - Decreasing zval refcount
  • Example#356 - Creating a array zval
  • Example#357 - Adding already existing element to an array
  • Example#358 - Removing an element from an array
  • Example#359 - Adding the array itself as an element of it self
  • Example#360 - Unsetting $a
  • Example#361 - Memory usage example
  • Example#362 - GC performance influences
  • Example#363 - Running the above script
  • Example#364 - Recompiling PHP to enable GC benchmarking
  • Example#365 - GC statistics
  • Example#366 - An apc.rfc1867 example
  • Example#367 - A apc_add example
  • Example#368 - apc_bin_load example
  • Example#369 - A apc_cache_info example
  • Example#370 - apc_cas example
  • Example#371 - apc_dec example
  • Example#372 - apc_define_constants example
  • Example#373 - apc_delete_file example
  • Example#374 - A apc_delete example
  • Example#375 - apc_exists example
  • Example#376 - A apc_fetch example
  • Example#377 - apc_inc example
  • Example#378 - apc_load_constants example
  • Example#379 - A apc_sma_info example
  • Example#380 - A apc_store example
  • Example#381 - Typical session using tcplisten
  • Example#382 - apd_callstack example
  • Example#383 - apd_clunk example
  • Example#384 - apd_continue example
  • Example#385 - apd_croak example
  • Example#386 - apd_dump_function_table example
  • Example#387 - apd_dump_persistent_resources example
  • Example#388 - apd_dump_regular_resources example
  • Example#389 - apd_echo example
  • Example#390 - apd_get_active_symbols example
  • Example#391 - apd_set_pprof_trace example
  • Example#392 - apd_set_session_trace_socket example
  • Example#393 - apd_set_session_trace example
  • Example#394 - apd_set_session example
  • Example#395 - override_function example
  • Example#396 - rename_function example
  • Example#397 - bcompiler_load_exe example
  • Example#398 - bcompiler_load example
  • Example#399 - bcompiler_parse_class example
  • Example#400 - bcompiler_read example
  • Example#401 - bcompiler_write_class example
  • Example#402 - bcompiler_write_constant example
  • Example#403 - bcompiler_write_exe_footer example
  • Example#404 - bcompiler_write_file example
  • Example#405 - bcompiler_write_footer example
  • Example#406 - bcompiler_write_function example
  • Example#407 - bcompiler_write_functions_from_file example
  • Example#408 - bcompiler_write_header example
  • Example#409 - Using error handling in a script
  • Example#410 - debug_backtrace example
  • Example#411 - debug_print_backtrace example
  • Example#412 - An error_get_last example
  • Example#413 - error_log examples
  • Example#414 - error_reporting examples
  • Example#415 - restore_error_handler example
  • Example#416 - restore_exception_handler example
  • Example#417 - Error handling with set_error_handler and trigger_error
  • Example#418 - set_exception_handler example
  • Example#419 - trigger_error example
  • Example#420 - Getting the data within the PHP application itself (function)
  • Example#421 - Example use of gengraph.php
  • Example#422 - Listing data via inclued dumps (configuration)
  • Example#423 - inclued_get_data example
  • Example#424 - Creating large array in a function
  • Example#425 - Output Control example
  • Example#426 - ob_end_clean example
  • Example#427 - ob_end_flush example
  • Example#428 - A simple ob_get_clean example
  • Example#429 - A simple ob_get_contents example
  • Example#430 - ob_get_flush example
  • Example#431 - A simple ob_get_length example
  • Example#432 - ob_gzhandler example
  • Example#433 - ob_list_handlers example
  • Example#434 - User defined callback function example
  • Example#435 - output_add_rewrite_var example
  • Example#436 - output_reset_rewrite_vars example
  • Example#437 - Overloading a PHP class
  • Example#438 - assert_options example
  • Example#439 - Handle a failed assertion with a custom handler
  • Example#440 - dl examples
  • Example#441 - extension_loaded example
  • Example#442 - A gc_enabled example
  • Example#443 - get_current_user example
  • Example#444 - get_defined_constants Example
  • Example#445 - Prints the XML functions
  • Example#446 - get_include_path example
  • Example#447 - get_included_files example
  • Example#448 - get_loaded_extensions Example
  • Example#449 - get_magic_quotes_gpc example
  • Example#450 - get_magic_quotes_runtime example
  • Example#451 - getenv Example
  • Example#452 - getlastmod example
  • Example#453 - getopt example
  • Example#454 - getopt example#2
  • Example#455 - getopt example#3
  • Example#456 - getrusage example
  • Example#457 - ini_get_all examples
  • Example#458 - Disabling details
  • Example#459 - A few ini_get examples
  • Example#460 - ini_restore example
  • Example#461 - Setting an ini option
  • Example#462 - A memory_get_usage example
  • Example#463 - php_ini_loaded_file example
  • Example#464 - A simple example to list the returned ini files
  • Example#465 - php_logo_guid example
  • Example#466 - php_sapi_name example
  • Example#467 - Some php_uname examples
  • Example#468 - A few OS related constant examples
  • Example#469 - Prints the general credits
  • Example#470 - Prints the core developers and the documentation group
  • Example#471 - Printing all the credits
  • Example#472 - phpinfo Example
  • Example#473 - phpversion example
  • Example#474 - PHP_VERSION_ID example and usage
  • Example#475 - Setting an environment variable
  • Example#476 - restore_include_path example
  • Example#477 - set_include_path example
  • Example#478 - Adding to the include path
  • Example#479 - set_magic_quotes_runtime example
  • Example#480 - sys_get_temp_dir example
  • Example#481 - version_compare examples
  • Example#482 - zend_logo_guid example
  • Example#483 - zend_thread_id example
  • Example#484 - zend_version example
  • Example#485 - Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
  • Example#486 - Instantiating a restricted sandbox
  • Example#487 - Working with variables in a sandbox
  • Example#488 - Calling sandbox functions
  • Example#489 - Passing arguments to sandbox functions
  • Example#490 - Working with variables in a sandbox
  • Example#491 - Accessing parental variables
  • Example#492 - A runkit_class_adopt example
  • Example#493 - A runkit_class_emancipate example
  • Example#494 - A runkit_function_add example
  • Example#495 - A runkit_function_copy example
  • Example#496 - A runkit_function_redefine example
  • Example#497 - runkit_method_add example
  • Example#498 - runkit_method_copy example
  • Example#499 - runkit_method_redefine example
  • Example#500 - runkit_method_remove example
  • Example#501 - runkit_method_rename example
  • Example#502 - runkit_return_value_used example
  • Example#503 - Feeding output to a variable
  • Example#504 - Enabling and disabling scream at runtime
  • Example#505 - Weakref usage example
  • Example#506 - Weakref usage example
  • Example#507 - Weakref::acquire example
  • Example#508 - Nested acquire/release example
  • Example#509 - Weakref::__construct example
  • Example#510 - Weakref::release example
  • Example#511 - wincache.ignorelist example
  • Example#512 - Authentication configuration for wincache.php
  • Example#513 - Enabling WinCache session handler
  • Example#514 - Enabling WinCache functions reroutes
  • Example#515 - Reroute.ini file content
  • Example#516 - A wincache_fcache_fileinfo example
  • Example#517 - A wincache_fcache_meminfo example
  • Example#518 - Using wincache_lock
  • Example#519 - A wincache_ocache_fileinfo example
  • Example#520 - A wincache_ocache_meminfo example
  • Example#521 - A wincache_refresh_if_changed example
  • Example#522 - A wincache_rplist_fileinfo example
  • Example#523 - A wincache_rplist_meminfo example
  • Example#524 - A wincache_scache_info example
  • Example#525 - A wincache_scache_meminfo example
  • Example#526 - wincache_ucache_add with key as a string
  • Example#527 - wincache_ucache_add with key as an array
  • Example#528 - Using wincache_ucache_cas
  • Example#529 - using wincache_ucache_clear
  • Example#530 - Using wincache_ucache_dec
  • Example#531 - Using wincache_ucache_delete with key as a string
  • Example#532 - Usingwincache_ucache_delete with key as an array
  • Example#533 - Using wincache_ucache_delete with key as an array where some elements cannot be deleted
  • Example#534 - Using wincache_ucache_exists
  • Example#535 - wincache_ucache_get with key as a string
  • Example#536 - wincache_ucache_get with key as an array
  • Example#537 - Using wincache_ucache_inc
  • Example#538 - Using wincache_ucache_info
  • Example#539 - A wincache_ucache_meminfo example
  • Example#540 - wincache_ucache_set with key as a string
  • Example#541 - wincache_ucache_set with key as an array
  • Example#542 - Using wincache_unlock
  • Example#543 - Xhprof example with the optional GUI
  • Example#544 - xhprof_disable example
  • Example#545 - xhprof_enable examples
  • Example#546 - xhprof_sample_disable example
  • Example#547 - id3_get_frame_long_name example
  • Example#548 - id3_get_frame_short_name example
  • Example#549 - id3_get_genre_id example
  • Example#550 - id3_get_genre_list example
  • Example#551 - id3_get_genre_name example
  • Example#552 - id3_get_tag example
  • Example#553 - id3_get_tag example
  • Example#554 - id3_get_version example
  • Example#555 - id3_remove_tag example
  • Example#556 - id3_set_tag example
  • Example#557 - Opens a new MP3 file and read the title
  • Example#558 - Reading an OGG/Vorbis file
  • Example#559 - Encode an audio file to OGG/Vorbis
  • Example#560 - KADM5 extension overview example
  • Example#561 - Example of changing principal's password
  • Example#562 - Example of principal's creation
  • Example#563 - kadm5_delete_principal example
  • Example#564 - kadm5_get_policies example
  • Example#565 - kadm5_get_principal example
  • Example#566 - kadm5_get_principals example
  • Example#567 - KADM5 initialization example
  • Example#568 - Example of modifying principal
  • Example#569 - radius_acct_open example
  • Example#570 - radius_add_server example
  • Example#571 - radius_auth_open example
  • Example#572 - radius_create_request example
  • Example#573 - radius_cvt_addr example
  • Example#574 - radius_cvt_int example
  • Example#575 - radius_cvt_string example
  • Example#576 - radius_get_attr example
  • Example#577 - radius_get_vendor_attr example
  • Example#578 - radius_put_attr example
  • Example#579 - radius_put_int example
  • Example#580 - radius_put_string example
  • Example#581 - radius_put_vendor_attr example
  • Example#582 - cal_days_in_month example
  • Example#583 - cal_from_jd example
  • Example#584 - cal_info example
  • Example#585 - easter_date example
  • Example#586 - easter_days example
  • Example#587 - Calendar functions
  • Example#588 - jdtojewish Example
  • Example#589 - DateTime::add example
  • Example#590 - Further DateTime::add examples
  • Example#591 - Beware when adding months
  • Example#592 - DateTime::__construct example
  • Example#593 - Intricacies of DateTime::__construct
  • Example#594 - DateTime::createFromFormat example
  • Example#595 - Intricacies of DateTime::createFromFormat
  • Example#596 - DateTime::diff example
  • Example#597 - DateTime object comparison
  • Example#598 - DateTime::format example
  • Example#599 - DateTime::getLastErrors example
  • Example#600 - DateTime::getOffset example
  • Example#601 - DateTime::getTimestamp example
  • Example#602 - DateTime::getTimezone example
  • Example#603 - DateTime::modify example
  • Example#604 - Beware when adding or subtracting months
  • Example#605 - DateTime::setDate example
  • Example#606 - Values exceeding ranges are added to their parent values
  • Example#607 - DateTime::setISODate example
  • Example#608 - Values exceeding ranges are added to their parent values
  • Example#609 - Finding the month a week is in
  • Example#610 - DateTime::setTime example
  • Example#611 - Values exceeding ranges are added to their parent values
  • Example#612 - DateTime::setTimestamp example
  • Example#613 - DateTime::setTimestamp alternative in PHP 5.2
  • Example#614 - DateTime::setTimeZone example
  • Example#615 - DateTime::sub example
  • Example#616 - Further DateTime::sub examples
  • Example#617 - Beware when subtracting months
  • Example#618 - Catching errors when instantiating DateTimeZone
  • Example#619 - DateTimeZone::getLocation example
  • Example#620 - DateTimeZone::getOffset examples
  • Example#621 - A timezone_transitions_get example
  • Example#622 - A timezone_abbreviations_list example
  • Example#623 - A timezone_identifiers_list example
  • Example#624 - DateInterval example
  • Example#625 - DateInterval example
  • Example#626 - DateInterval and carry over points
  • Example#627 - DateInterval and DateTime::diff with the %a and %d modifiers
  • Example#628 - checkdate - przykład
  • Example#629 - Getting the default timezone
  • Example#630 - Getting the abbreviation of a timezone
  • Example#631 - Getting the default timezone
  • Example#632 - date_parse_from_format example
  • Example#633 - A date_parse example
  • Example#634 - A date_sun_info example
  • Example#635 - date_sunrise example
  • Example#636 - date_sunset example
  • Example#637 - Przykłady użycia funkcji date
  • Example#638 - Znaki ucieczki w funkcji date
  • Example#639 - Przykład użycia date i mktime
  • Example#640 - zastosowania date
  • Example#641 - Przykład getdate
  • Example#642 - przykład gmdate
  • Example#643 - przykład gmstrftime
  • Example#644 - idate example
  • Example#645 - time przykład
  • Example#646 - przykład microtime
  • Example#647 - przykład mktime
  • Example#648 - Ostatni dzień miesiąca
  • Example#649 - przykład strftime
  • Example#650 - strptime example
  • Example#651 - przykłady strtotime
  • Example#652 - Checking for failure
  • Example#653 - time przykład
  • Example#654 - A timezone_name_from_abbr example
  • Example#655 - Getting the timezonedb version
  • Example#656 - Writing a string with a specified color to the screen
  • Example#657 - ncurses_getmouse example
  • Example#658 - Writing a string with a specified color to the screen
  • Example#659 - Writing a string with a specified color to the screen
  • Example#660 - ncurses_mousemask example
  • Example#661 - Writing a string with a specified color to the screen
  • Example#662 - Newt Usage Example
  • Example#663 - A newt_button example
  • Example#664 - A newt_draw_root_text example
  • Example#665 - A newt_form_add_component example
  • Example#666 - A newt_form_add_components example
  • Example#667 - A newt_form example
  • Example#668 - A newt_get_screen_size example
  • Example#669 - A newt_win_entries example
  • Example#670 - Readline Callback Interface Example
  • Example#671 - readline
  • Example#672 - Przykład użycia bzip2
  • Example#673 - Compressing data
  • Example#674 - Decompressing a String
  • Example#675 - bzerror przykład
  • Example#676 - bzopen przykład
  • Example#677 - bzread przykład
  • Example#678 - bzwrite przykład
  • Example#679 - Using an external file
  • Example#680 - Using a file within a phar archive
  • Example#681 - Converting a phar archive from phar to tar file format
  • Example#682 - phar.extract_list usage example
  • Example#683 - phar.cache_list usage example
  • Example#684 - A Phar::addEmptyDir example
  • Example#685 - A Phar::addFile example
  • Example#686 - A Phar::addFromString example
  • Example#687 - A Phar::apiVersion example
  • Example#688 - A Phar::buildFromDirectory example
  • Example#689 - A Phar::buildFromIterator with SplFileInfo
  • Example#690 - A Phar::buildFromIterator with other iterators
  • Example#691 - A Phar::canCompress example
  • Example#692 - A Phar::canWrite example
  • Example#693 - A Phar::compress example
  • Example#694 - A Phar::compressAllFilesBZIP2 example
  • Example#695 - A Phar::compressAllFilesGZ example
  • Example#696 - A Phar::compressFiles example
  • Example#697 - A Phar::__construct example
  • Example#698 - A Phar::convertToData example
  • Example#699 - A Phar::convertToExecutable example
  • Example#700 - A Phar::copy example
  • Example#701 - A Phar::count example
  • Example#702 - A Phar::createDefaultStub example
  • Example#703 - A Phar::decompress example
  • Example#704 - A Phar::decompressFiles example
  • Example#705 - A Phar::delMetaData example
  • Example#706 - A Phar::delete example
  • Example#707 - A Phar::extractTo example
  • Example#708 - A Phar::getMetadata example
  • Example#709 - A Phar::getStub example
  • Example#710 - A Phar::hasMetadata example
  • Example#711 - A Phar::interceptFileFuncs example
  • Example#712 - A Phar::interceptFileFuncs example
  • Example#713 - A Phar::isBuffering example
  • Example#714 - A Phar::isCompressed example
  • Example#715 - A Phar::loadPhar example
  • Example#716 - A Phar::mapPhar example
  • Example#717 - A Phar::mount example
  • Example#718 - A Phar::mungServer example
  • Example#719 - A Phar::offsetExists example
  • Example#720 - Phar::offsetGet example
  • Example#721 - A Phar::offsetSet example
  • Example#722 - A Phar::offsetUnset example
  • Example#723 - A Phar::running example
  • Example#724 - A Phar::setAlias example
  • Example#725 - A Phar::setDefaultStub example
  • Example#726 - A Phar::setMetadata example
  • Example#727 - A Phar::setStub example
  • Example#728 - A Phar::startBuffering example
  • Example#729 - A Phar::stopBuffering example
  • Example#730 - A Phar::uncompressAllFiles example
  • Example#731 - A Phar::unlinkArchive example
  • Example#732 - A Phar::webPhar example
  • Example#733 - A PharData::addEmptyDir example
  • Example#734 - A PharData::addFile example
  • Example#735 - A PharData::addFromString example
  • Example#736 - A PharData::buildFromDirectory example
  • Example#737 - A PharData::buildFromIterator with SplFileInfo
  • Example#738 - A PharData::buildFromIterator with other iterators
  • Example#739 - A PharData::compress example
  • Example#740 - A PharData::compressFiles example
  • Example#741 - A PharData::__construct example
  • Example#742 - A PharData::convertToData example
  • Example#743 - A PharData::convertToExecutable example
  • Example#744 - A PharData::copy example
  • Example#745 - A PharData::decompress example
  • Example#746 - A PharData::decompressFiles example
  • Example#747 - A PharData::delMetaData example
  • Example#748 - A PharData::delete example
  • Example#749 - A PharData::extractTo example
  • Example#750 - A PharData::offsetSet example
  • Example#751 - A PharData::offsetUnset example
  • Example#752 - A Phar::setMetadata example
  • Example#753 - A PharFileInfo::chmod example
  • Example#754 - A PharFileInfo::compress example
  • Example#755 - A PharFileInfo::__construct example
  • Example#756 - A PharFileInfo::decompress example
  • Example#757 - A PharFileInfo::delMetaData example
  • Example#758 - A PharFileInfo::getCRC32 example
  • Example#759 - A PharFileInfo::getCompressedSize example
  • Example#760 - A PharFileInfo::getMetadata example
  • Example#761 - A PharFileInfo::getPharFlags example
  • Example#762 - A PharFileInfo::isCRCChecked example
  • Example#763 - A PharFileInfo::isCompressed example
  • Example#764 - A PharFileInfo::isCompressedBZIP2 example
  • Example#765 - A PharFileInfo::isCompressedGZ example
  • Example#766 - A PharFileInfo::setCompressedBZIP2 example
  • Example#767 - A PharFileInfo::setCompressedGZ example
  • Example#768 - A PharFileInfo::setMetadata example
  • Example#769 - A PharFileInfo::setUncompressed example
  • Example#770 - Rar installation
  • Example#771 - On-the-fly decompression
  • Example#772 - RAR extension filesystem extraction example
  • Example#773 - Styl obiektowy
  • Example#774 - Styl proceduralny
  • Example#775 - Styl obiektowy
  • Example#776 - Styl proceduralny
  • Example#777 - Styl obiektowy
  • Example#778 - Styl proceduralny
  • Example#779 - Styl obiektowy
  • Example#780 - Styl proceduralny
  • Example#781 - Styl obiektowy
  • Example#782 - Styl proceduralny
  • Example#783 - Styl obiektowy
  • Example#784 - Styl proceduralny
  • Example#785 - Styl obiektowy
  • Example#786 - Styl proceduralny
  • Example#787 - Volume Callback
  • Example#788 - Styl obiektowy
  • Example#789 - Styl proceduralny
  • Example#790 - RarArchive::__toString example
  • Example#791 - RarEntry::extract example
  • Example#792 - How to extract all files in archive:
  • Example#793 - RarEntry::getAttr example
  • Example#794 - RarEntry::getHostOs example (version >= 2.0.0)
  • Example#795 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#796 - RarEntry::getMethod example
  • Example#797 - RarEntry::getName example
  • Example#798 - RarEntry::getPackedSize example
  • Example#799 - RarEntry::getStream example
  • Example#800 - RarEntry::getUnpackedSize example
  • Example#801 - RarEntry::getVersion example
  • Example#802 - RarException::isUsingExceptions example
  • Example#803 - RarException::setUsingExceptions example
  • Example#804 - Create a Zip archive
  • Example#805 - Dump the archive details and listing
  • Example#806 - Zip stream wrapper, read an OpenOffice meta info
  • Example#807 - Zip Usage Example
  • Example#808 - Create a new directory in an archive
  • Example#809 - Open and extract
  • Example#810 - Add an entry to a new archive
  • Example#811 - Add file to a directory inside an archive
  • Example#812 - Delete file from archive using its index
  • Example#813 - Deleting a file and directory from an archive, using names
  • Example#814 - Extract all entries
  • Example#815 - Extract two entries
  • Example#816 - Dump an archive comment
  • Example#817 - Dump an entry comment
  • Example#818 - Dump an entry comment
  • Example#819 - Get the file contents
  • Example#820 - Get the file contents
  • Example#821 - Convert an image from a zip entry
  • Example#822 - getnameindex example
  • Example#823 - Get the entry contents with fread and store it
  • Example#824 - Same as the previous example but with fopen and the zip stream wrapper
  • Example#825 - Stream wrapper and image, can be used with the xml function as well
  • Example#826 - Create an archive and then use it with ZipArchive::locateName
  • Example#827 - Open and extract
  • Example#828 - Create an archive
  • Example#829 - Rename one entry
  • Example#830 - Rename one entry
  • Example#831 - Create an archive and set a comment
  • Example#832 - Open an archive and set a comment for an entry
  • Example#833 - Open an archive and set a comment for an entry
  • Example#834 - Dump the stat info of an entry
  • Example#835 - Dump the stat info of an entry
  • Example#836 - Small Zlib Example
  • Example#837 - gzclose example
  • Example#838 - gzcompress example
  • Example#839 - gzdeflate example
  • Example#840 - Creating a gzip file
  • Example#841 - gzeof example
  • Example#842 - gzfile example
  • Example#843 - gzgetc example
  • Example#844 - gzgets example
  • Example#845 - gzgetss example
  • Example#846 - gzinflate example
  • Example#847 - gzopen Example
  • Example#848 - gzpassthru example
  • Example#849 - gzread example
  • Example#850 - gzseek example
  • Example#851 - gzuncompress example
  • Example#852 - gzwrite example
  • Example#853 - CrackLib example
  • Example#854 - hash_algos example
  • Example#855 - hash_copy example
  • Example#856 - Using hash_file
  • Example#857 - hash_final example
  • Example#858 - hash_hmac_file example
  • Example#859 - hash_hmac example
  • Example#860 - Incremental hashing example
  • Example#861 - hash_update_stream example
  • Example#862 - A hash example
  • Example#863 - Encrypt an input value with TripleDES under 2.2.x in ECB mode
  • Example#864 - Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode
  • Example#865 - mcrypt_create_iv Example
  • Example#866 - mcrypt_enc_get_algorithms_name example
  • Example#867 - mcrypt_enc_get_modes_name example
  • Example#868 - mcrypt_enc_get_supported_key_sizes example
  • Example#869 - mcrypt_encrypt Example
  • Example#870 - mcrypt_get_block_size example
  • Example#871 - mcrypt_get_cipher_name Example
  • Example#872 - mcrypt_get_iv_size Example
  • Example#873 - mcrypt_get_key_size Example
  • Example#874 - mcrypt_list_algorithms Example
  • Example#875 - mcrypt_list_modes Example
  • Example#876 - mcrypt_module_open Examples
  • Example#877 - Using mcrypt_module_open in encryption
  • Example#878 - mcrypt_module_self_test example
  • Example#879 - mdecrypt_generic Example
  • Example#880 - Computes the MD5 digest and hmac and print it out as hex
  • Example#881 - Traversing all hashes
  • Example#882 - mhash_get_block_size Example
  • Example#883 - mhash_get_hash_name Example
  • Example#884 - openssl_cipher_iv_length example
  • Example#885 - Creating a self-signed-certificate
  • Example#886 - openssl_csr_sign example - signing a CSR (how to implement your own CA)
  • Example#887 - openssl_error_string example
  • Example#888 - openssl_get_cipher_methods example
  • Example#889 - openssl_get_md_methods example
  • Example#890 - openssl_open example
  • Example#891 - openssl_pkcs7_decrypt example
  • Example#892 - openssl_pkcs7_encrypt example
  • Example#893 - openssl_pkcs7_sign example
  • Example#894 - openssl_random_pseudo_bytes example
  • Example#895 - openssl_seal example
  • Example#896 - openssl_sign example
  • Example#897 - openssl_verify example
  • Example#898 - DBA example
  • Example#899 - Traversing a database
  • Example#900 - dba_handlers Example
  • Example#901 - dbx_close example
  • Example#902 - dbx_compare example
  • Example#903 - dbx_connect example
  • Example#904 - dbx_error example
  • Example#905 - dbx_escape_string example
  • Example#906 - How to handle the returned value
  • Example#907 - lists each field's name and type
  • Example#908 - outputs the content of data property into HTML table
  • Example#909 - How to handle UNBUFFERED queries
  • Example#910 - How to handle the returned value
  • Example#911 - dbx_sort example
  • Example#912 - DSN-less connections
  • Example#913 - odbc_execute and odbc_prepare example
  • Example#914 - odbc_fetch_into examples
  • Example#915 - odbc_next_result
  • Example#916 - odbc_execute and odbc_prepare example
  • Example#917 - odbc_result examples
  • Example#918 - odbc_setoption examples
  • Example#919 - using PDO::ATTR_DRIVER_NAME
  • Example#920 - Connecting to MySQL
  • Example#921 - Handling connection errors
  • Example#922 - Closing a connection
  • Example#923 - Persistent connections
  • Example#924 - Executing a batch in a transaction
  • Example#925 - Repeated inserts using prepared statements
  • Example#926 - Repeated inserts using prepared statements
  • Example#927 - Fetching data using prepared statements
  • Example#928 - Calling a stored procedure with an output parameter
  • Example#929 - Calling a stored procedure with an input/output parameter
  • Example#930 - Invalid use of placeholder
  • Example#931 - Create a PDO instance and set the error mode
  • Example#932 - Displaying an image from a database
  • Example#933 - Inserting an image into a database
  • Example#934 - Inserting an image into a database: Oracle
  • Example#935 - Roll back a transaction
  • Example#936 - Commit a transaction
  • Example#937 - Create a PDO instance via driver invocation
  • Example#938 - Create a PDO instance via URI invocation
  • Example#939 - Create a PDO instance using an alias
  • Example#940 - Retrieving an SQLSTATE code
  • Example#941 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#942 - Issuing a DELETE statement
  • Example#943 - Retrieving database connection attributes
  • Example#944 - A PDO::getAvailableDrivers example
  • Example#945 - Prepare an SQL statement with named parameters
  • Example#946 - Prepare an SQL statement with question mark parameters
  • Example#947 - Demonstrate PDO::query
  • Example#948 - Quoting a normal string
  • Example#949 - Quoting a dangerous string
  • Example#950 - Quoting a complex string
  • Example#951 - Roll back a transaction
  • Example#952 - Binding result set output to PHP variables
  • Example#953 - Execute a prepared statement with named placeholders
  • Example#954 - Execute a prepared statement with question mark placeholders
  • Example#955 - Call a stored procedure with an INOUT parameter
  • Example#956 - Execute a prepared statement with named placeholders
  • Example#957 - Execute a prepared statement with question mark placeholders
  • Example#958 - A PDOStatement::closeCursor example
  • Example#959 - Counting columns
  • Example#960 - PDOStatement::debugDumpParams example with named parameters
  • Example#961 - PDOStatement::debugDumpParams example with unnamed parameters
  • Example#962 - Retrieving an SQLSTATE code
  • Example#963 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#964 - Execute a prepared statement with bound variables
  • Example#965 - Execute a prepared statement with an array of insert values (named parameters)
  • Example#966 - Execute a prepared statement with an array of insert values (placeholders)
  • Example#967 - Execute a prepared statement with question mark placeholders
  • Example#968 - Fetching rows using different fetch styles
  • Example#969 - Fetching rows with a scrollable cursor
  • Example#970 - Fetch all remaining rows in a result set
  • Example#971 - Fetching all values of a single column from a result set
  • Example#972 - Grouping all values by a single column
  • Example#973 - Instantiating a class for each result
  • Example#974 - Calling a function for each result
  • Example#975 - Return first column of the next row
  • Example#976 - Retrieving column metadata
  • Example#977 - Fetching multiple rowsets returned from a stored procedure
  • Example#978 - Return the number of deleted rows
  • Example#979 - Counting rows returned by a SELECT statement
  • Example#980 - Setting the fetch mode
  • Example#981 - Insert LOBs in CUBRID PDO
  • Example#982 - Fetch LOBs in CUBRID PDO
  • Example#983 - PDO_CUBRID DSN examples
  • Example#984 - A PDO::cubrid_schema example
  • Example#985 - PDO_DBLIB DSN examples
  • Example#986 - PDO_FIREBIRD DSN examples
  • Example#987 - PDO_IBM DSN example using db2cli.ini
  • Example#988 - PDO_IBM DSN example using a connection string
  • Example#989 - PDO_INFORMIX DSN example using odbc.ini
  • Example#990 - PDO_INFORMIX DSN example using a connection string
  • Example#991 - Forcing queries to be buffered in mysql
  • Example#992 - Setting the connection character set to UTF-8 prior to PHP 5.3.6
  • Example#993 - PDO_MYSQL DSN examples
  • Example#994 - PDO_SQLSRV DSN examples
  • Example#995 - PDO_OCI DSN examples
  • Example#996 - PDO_ODBC DSN example (ODBC driver manager)
  • Example#997 - PDO_ODBC DSN example (IBM DB2 uncataloged connection)
  • Example#998 - PDO_ODBC DSN example (Microsoft Access uncataloged connection)
  • Example#999 - PDO_PGSQL DSN examples
  • Example#1000 - A PDO::pgsqlLOBCreate example
  • Example#1001 - A PDO::pgsqlLOBOpen example
  • Example#1002 - A PDO::pgsqlLOBUnlink example
  • Example#1003 - PDO_SQLITE DSN examples
  • Example#1004 - max_length aggregation function example
  • Example#1005 - PDO::sqliteCreateFunction example
  • Example#1006 - DSN examples for PDO_4D
  • Example#1007 - Basic example with PDO_4D
  • Example#1008 - Accessing 4D language from pdo_4d
  • Example#1009 - Escaping 4D table names
  • Example#1010 - Example of Data Retrieval
  • Example#1011 - Example of Data Insertion
  • Example#1012 - cubrid_affected_rows example
  • Example#1013 - cubrid_bind example
  • Example#1014 - cubrid_bind named parameter example
  • Example#1015 - cubrid_bind BLOB/CLOB example
  • Example#1016 - cubrid_bind BLOB/CLOB example
  • Example#1017 - cubrid_close_prepare example
  • Example#1018 - cubrid_close_request example
  • Example#1019 - cubrid_col_get example
  • Example#1020 - cubrid_col_size example
  • Example#1021 - cubrid_column_names example
  • Example#1022 - cubrid_column_types example
  • Example#1023 - cubrid_commit example
  • Example#1024 - cubrid_connect_with_url url without properties example
  • Example#1025 - cubrid_connect_with_url url with properties example
  • Example#1026 - cubrid_connect example
  • Example#1027 - cubrid_current_oid example
  • Example#1028 - cubrid_disconnect example
  • Example#1029 - cubrid_drop example
  • Example#1030 - cubrid_error_code_facility example
  • Example#1031 - cubrid_error_code example
  • Example#1032 - cubrid_error_msg example
  • Example#1033 - cubrid_execute example
  • Example#1034 - cubrid_fetch example
  • Example#1035 - cubrid_free_result example
  • Example#1036 - cubrid_get_charset example
  • Example#1037 - cubrid_get_class_name example
  • Example#1038 - cubrid_get_client_info example
  • Example#1039 - cubrid_get_db_parameter example
  • Example#1040 - cubrid_get_query_timeout example
  • Example#1041 - cubrid_get_server_info example
  • Example#1042 - cubrid_get example
  • Example#1043 - cubrid_insert_id example
  • Example#1044 - cubrid_is_instance example
  • Example#1045 - cubrid_lob_close example
  • Example#1046 - cubrid_lob_export example
  • Example#1047 - cubrid_lob_get example
  • Example#1048 - cubrid_lob_send example
  • Example#1049 - cubrid_lob_size example
  • Example#1050 - cubrid_lock_read example
  • Example#1051 - cubrid_lock_write example
  • Example#1052 - cubrid_move_cursor example
  • Example#1053 - cubrid_next_result example
  • Example#1054 - cubrid_num_cols example
  • Example#1055 - cubrid_num_rows example
  • Example#1056 - cubrid_connect_with_url url without properties example
  • Example#1057 - cubrid_connect_with_url url with properties example
  • Example#1058 - cubrid_connect example
  • Example#1059 - cubrid_prepare example
  • Example#1060 - cubrid_put example
  • Example#1061 - cubrid_rollback example
  • Example#1062 - cubrid_schema example
  • Example#1063 - cubrid_seq_drop example
  • Example#1064 - cubrid_seq_insert example
  • Example#1065 - cubrid_seq_put example
  • Example#1066 - cubrid_set_add example
  • Example#1067 - cubrid_get_db_parameter example
  • Example#1068 - cubrid_set_drop example
  • Example#1069 - cubrid_version example
  • Example#1070 - cubrid_client_encoding example
  • Example#1071 - cubrid_close example
  • Example#1072 - cubrid_data_seek example
  • Example#1073 - cubrid_db_name example
  • Example#1074 - cubrid_errno example
  • Example#1075 - cubrid_error example
  • Example#1076 - cubrid_fetch_array example
  • Example#1077 - cubrid_fetch_assoc example
  • Example#1078 - cubrid_fetch_field example
  • Example#1079 - cubrid_fetch_lengths example
  • Example#1080 - cubrid_fetch_object example
  • Example#1081 - cubrid_fetch_row example
  • Example#1082 - cubrid_field_flags example
  • Example#1083 - cubrid_field_len example
  • Example#1084 - cubrid_field_name example
  • Example#1085 - cubrid_field_seek example
  • Example#1086 - cubrid_field_table example
  • Example#1087 - cubrid_field_type example
  • Example#1088 - cubrid_list_dbs example
  • Example#1089 - cubrid_num_fields example
  • Example#1090 - cubrid_ping example
  • Example#1091 - Invalid Query
  • Example#1092 - Valid Query
  • Example#1093 - cubrid_real_escape_string example
  • Example#1094 - cubrid_result example
  • Example#1095 - cubrid_unbuffered_query example
  • Example#1096 - cubrid_load_from_glo example
  • Example#1097 - cubrid_new_glo example
  • Example#1098 - cubrid_save_to_glo example
  • Example#1099 - cubrid_send_glo example
  • Example#1100 - Inserting a record in a dBase database
  • Example#1101 - Closing a dBase database file
  • Example#1102 - Creating a dBase database file
  • Example#1103 - Showing header information for a dBase database file
  • Example#1104 - Listing all the registered members in the database
  • Example#1105 - dbase_numfields Example
  • Example#1106 - Looping over all the records of the database
  • Example#1107 - Opening a dBase database file
  • Example#1108 - Emptying a dBase database
  • Example#1109 - Updating a record in the database
  • Example#1110 - Przykład ibase_blob_get
  • Example#1111 - Przykład ibase_blob_import
  • Example#1112 - Przykład ibase_connect
  • Example#1113 - Przykład ibase_execute
  • Example#1114 - Przykład ibase_fetch_object
  • Example#1115 - Przykład ibase_field_info
  • Example#1116 - Przykład ibase_name_result
  • Example#1117 - Przykład ibase_num_fields
  • Example#1118 - Przykład ibase_query
  • Example#1119 - Przykład ibase_set_event_handler
  • Example#1120 - Przykład ibase_timefmt
  • Example#1121 - Przykład fbsql_close
  • Example#1122 - Przykład fbsql_connect
  • Example#1123 - fbsql_create_blob example
  • Example#1124 - fbsql_create_clob example
  • Example#1125 - fbsql_create_db example
  • Example#1126 - fbsql_data_seek example
  • Example#1127 - fbsql_create_clob example
  • Example#1128 - fbsql_errno Example
  • Example#1129 - fbsql_error Example
  • Example#1130 - fbsql_fetch_array example
  • Example#1131 - fbsql_fetch_assoc example
  • Example#1132 - fbsql_fetch_field example
  • Example#1133 - fbsql_fetch_object example
  • Example#1134 - fbsql_field_name example
  • Example#1135 - fbsql_field_type example
  • Example#1136 - fbsql_list_dbs example
  • Example#1137 - fbsql_list_fields example
  • Example#1138 - fbsql_next_result example
  • Example#1139 - fbsql_num_rows example
  • Example#1140 - Przykład fbsql_query
  • Example#1141 - Przykład fbsql_query
  • Example#1142 - fbsql_read_blob example
  • Example#1143 - fbsql_read_clob example
  • Example#1144 - fbsql_table_name example
  • Example#1145 - Retrieving the AUTOCOMMIT value for a connection
  • Example#1146 - Setting the AUTOCOMMIT value for a connection
  • Example#1147 - Binding PHP variables to a prepared statement
  • Example#1148 - Calling stored procedures with IN and OUT parameters
  • Example#1149 - Inserting a binary large object (BLOB) directly from a file
  • Example#1150 - A db2_client_info example
  • Example#1151 - Closing a connection
  • Example#1152 - Retrieving an SQLSTATE value for a failed connection attempt
  • Example#1153 - Retrieving the error message returned by a failed connection attempt
  • Example#1154 - Creating a cataloged connection
  • Example#1155 - Creating an uncataloged connection
  • Example#1156 - Creating a connection with autocommit off by default
  • Example#1157 - i5/OS best performance
  • Example#1158 - Using trusted context
  • Example#1159 - A db2_escape_string example
  • Example#1160 - Creating a table with db2_exec
  • Example#1161 - Executing a SELECT statement with a scrollable cursor
  • Example#1162 - Returning XML data as an SQL ResultSet
  • Example#1163 - Performing a "JOIN" with XML data
  • Example#1164 - Returning SQL data as part of a larger XML document
  • Example#1165 - Preparing and executing an SQL statement with parameter markers
  • Example#1166 - Calling a stored procedure with an OUT parameter
  • Example#1167 - Returning XML data as an SQL ResultSet
  • Example#1168 - Performing a "JOIN" with XML data
  • Example#1169 - Returning SQL data as part of a larger XML document
  • Example#1170 - Iterating through a forward-only cursor
  • Example#1171 - Retrieving specific rows with db2_fetch_array from a scrollable cursor
  • Example#1172 - Iterating through a forward-only cursor
  • Example#1173 - Retrieving specific rows with db2_fetch_assoc from a scrollable cursor
  • Example#1174 - Iterating through a forward-only cursor
  • Example#1175 - Retrieving specific rows with db2_fetch_both from a scrollable cursor
  • Example#1176 - A db2_fetch_object example
  • Example#1177 - Iterating through a result set
  • Example#1178 - i5/OS recommended alternatives to db2_fetch_row/db2_result
  • Example#1179 - Setting and retrieving parameters through a connection resource
  • Example#1180 - A db2_last_insert_id example
  • Example#1181 - Iterating through different types of data
  • Example#1182 - Calling a stored procedure that returns multiple result sets
  • Example#1183 - Retrieving the number of fields in a result set
  • Example#1184 - Closing a persistent connection
  • Example#1185 - A db2_pconnect example
  • Example#1186 - Using trusted context
  • Example#1187 - Preparing and executing an SQL statement with parameter markers
  • Example#1188 - A db2_result example
  • Example#1189 - Rolling back a DELETE statement
  • Example#1190 - A db2_server_info example
  • Example#1191 - Setting one parameter with a connection resource
  • Example#1192 - Setting multiple parameters with a connection resource
  • Example#1193 - Setting multiple parameters with an invalid key
  • Example#1194 - Setting multiple parameters with an invalid value
  • Example#1195 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1196 - Setting multiple parameters with the wrong resource
  • Example#1197 - Putting it all together
  • Example#1198 - i5/OS cursors are read-only
  • Example#1199 - Informix affected rows
  • Example#1200 - Closing a Informix connection
  • Example#1201 - Connect to a Informix database
  • Example#1202 - ifx_do Example
  • Example#1203 - ifx_errormsg example
  • Example#1204 - Informix fetch rows
  • Example#1205 - Informix SQL fieldproperties
  • Example#1206 - Fieldnames and SQL fieldtypes
  • Example#1207 - Retrieve Informix sqlca.sqlerrd[x] values
  • Example#1208 - Informix results as HTML table
  • Example#1209 - ifx_num_fields Example
  • Example#1210 - Show all rows of the "orders" table as a HTML table
  • Example#1211 - Insert some values into the "catalog" table
  • Example#1212 - Przykład użycia PassEnv dla Ingres
  • Example#1213 - Przykład połączenia z Ingres
  • Example#1214 - ingres_charset - Get the installation character set
  • Example#1215 - Open a connection to an Ingres database
  • Example#1216 - Get cursor name for a query resource
  • Example#1217 - Przykład obsługi ostatnio wygenerowanego kodu błędu Ingres
  • Example#1218 - Przykład obsługi ostatnio wygenerowanego komunikatu o błędzie
  • Example#1219 - Przykład pobrania ostatnio wygenerowanego kodu SQLSTATE
  • Example#1220 - Escape special characters for use in a query
  • Example#1221 - Fetch a row of result into an array
  • Example#1222 - Fetch a row into an associative array
  • Example#1223 - Fetch a row into an object
  • Example#1224 - Get the return value from a procedure call
  • Example#1225 - Fetch a row of result into an enumerated array
  • Example#1226 - Free a result resource
  • Example#1227 - Send a simple select
  • Example#1228 - Passing query parameters to ingres_query
  • Example#1229 - Inserting a BLOB with parameter types
  • Example#1230 - Position the cursor on the 3rd row
  • Example#1231 - Set date_format to ISO4
  • Example#1232 - Set timezone to HONG-KONG
  • Example#1233 - Issue a simple un-buffered select
  • Example#1234 - Passing query parameters to ingres_unbuffered_query
  • Example#1235 - Inserting a BLOB with parameter types
  • Example#1236 - MaxDB extension overview example
  • Example#1237 - Example for use of SELECT INTO statements
  • Example#1238 - Example fore using database procedures
  • Example#1239 - Styl obiektowy
  • Example#1240 - Styl proceduralny
  • Example#1241 - Styl obiektowy
  • Example#1242 - Styl proceduralny
  • Example#1243 - Styl obiektowy
  • Example#1244 - Styl proceduralny
  • Example#1245 - Styl obiektowy
  • Example#1246 - Styl proceduralny
  • Example#1247 - Styl obiektowy
  • Example#1248 - Styl proceduralny
  • Example#1249 - maxdb_connect_errno sample
  • Example#1250 - maxdb_connect_error sample
  • Example#1251 - Styl obiektowy
  • Example#1252 - Styl proceduralny
  • Example#1253 - Styl obiektowy
  • Example#1254 - Styl proceduralny
  • Example#1255 - Styl proceduralny
  • Example#1256 - Styl obiektowy
  • Example#1257 - Styl proceduralny
  • Example#1258 - Styl obiektowy
  • Example#1259 - Styl proceduralny
  • Example#1260 - Styl obiektowy
  • Example#1261 - Styl proceduralny
  • Example#1262 - Styl obiektowy
  • Example#1263 - Styl proceduralny
  • Example#1264 - Styl obiektowy
  • Example#1265 - Styl proceduralny
  • Example#1266 - Styl obiektowy
  • Example#1267 - Styl proceduralny
  • Example#1268 - Styl obiektowy
  • Example#1269 - Styl proceduralny
  • Example#1270 - Styl obiektowy
  • Example#1271 - Styl proceduralny
  • Example#1272 - Styl obiektowy
  • Example#1273 - Styl proceduralny
  • Example#1274 - Styl obiektowy
  • Example#1275 - Styl proceduralny
  • Example#1276 - Styl obiektowy
  • Example#1277 - Styl proceduralny
  • Example#1278 - Styl obiektowy
  • Example#1279 - Styl proceduralny
  • Example#1280 - Styl obiektowy
  • Example#1281 - Styl proceduralny
  • Example#1282 - maxdb_get_client_info
  • Example#1283 - maxdb_get_client_version
  • Example#1284 - Styl obiektowy
  • Example#1285 - Styl proceduralny
  • Example#1286 - Styl obiektowy
  • Example#1287 - Styl proceduralny
  • Example#1288 - Styl obiektowy
  • Example#1289 - Styl proceduralny
  • Example#1290 - Styl obiektowy
  • Example#1291 - Styl proceduralny
  • Example#1292 - Styl obiektowy
  • Example#1293 - Styl proceduralny
  • Example#1294 - Styl obiektowy
  • Example#1295 - Styl proceduralny
  • Example#1296 - Styl obiektowy
  • Example#1297 - Styl proceduralny
  • Example#1298 - Styl obiektowy
  • Example#1299 - Styl proceduralny
  • Example#1300 - Styl obiektowy
  • Example#1301 - Styl proceduralny
  • Example#1302 - Styl obiektowy
  • Example#1303 - Styl proceduralny
  • Example#1304 - Styl obiektowy
  • Example#1305 - Styl proceduralny
  • Example#1306 - Styl obiektowy
  • Example#1307 - Styl proceduralny
  • Example#1308 - Styl obiektowy
  • Example#1309 - Styl proceduralny
  • Example#1310 - Styl obiektowy
  • Example#1311 - Styl proceduralny
  • Example#1312 - Styl obiektowy
  • Example#1313 - Styl proceduralny
  • Example#1314 - Styl proceduralny
  • Example#1315 - Styl obiektowy
  • Example#1316 - Styl proceduralny
  • Example#1317 - Styl obiektowy
  • Example#1318 - Styl proceduralny
  • Example#1319 - Styl obiektowy
  • Example#1320 - Styl proceduralny
  • Example#1321 - Styl obiektowy
  • Example#1322 - Styl proceduralny
  • Example#1323 - Styl obiektowy
  • Example#1324 - Styl proceduralny
  • Example#1325 - Styl obiektowy
  • Example#1326 - Styl proceduralny
  • Example#1327 - Styl proceduralny (SELECT INTO)
  • Example#1328 - Styl proceduralny (DB procedure)
  • Example#1329 - Styl obiektowy (extended syntax)
  • Example#1330 - Styl obiektowy
  • Example#1331 - Styl proceduralny
  • Example#1332 - Styl obiektowy
  • Example#1333 - Styl proceduralny
  • Example#1334 - Styl obiektowy
  • Example#1335 - Styl proceduralny
  • Example#1336 - Styl obiektowy
  • Example#1337 - Styl proceduralny
  • Example#1338 - Styl obiektowy
  • Example#1339 - Styl proceduralny
  • Example#1340 - Styl obiektowy
  • Example#1341 - Styl proceduralny
  • Example#1342 - Styl obiektowy
  • Example#1343 - Styl proceduralny
  • Example#1344 - Styl obiektowy
  • Example#1345 - Styl proceduralny
  • Example#1346 - Styl obiektowy
  • Example#1347 - Styl proceduralny
  • Example#1348 - Styl obiektowy
  • Example#1349 - Styl proceduralny
  • Example#1350 - Styl obiektowy
  • Example#1351 - Styl proceduralny
  • Example#1352 - Styl obiektowy
  • Example#1353 - Styl proceduralny
  • Example#1354 - Styl obiektowy
  • Example#1355 - Styl proceduralny
  • Example#1356 - Styl obiektowy
  • Example#1357 - Styl proceduralny
  • Example#1358 - Styl obiektowy
  • Example#1359 - Styl proceduralny
  • Example#1360 - Mongo::__construct replica set example
  • Example#1361 - Connecting to a domain socket
  • Example#1362 - Mongo::__construct authentication example
  • Example#1363 - Changing pool size
  • Example#1364 - Mongo::listDBs example
  • Example#1365 - Mongo::selectCollection example
  • Example#1366 - Mongo::setPoolSize example
  • Example#1367 - MongoDB::command "distinct" example
  • Example#1368 - MongoDB::command "distinct" example
  • Example#1369 - MongoDB::command MapReduce example
  • Example#1370 - MongoDB::createCollection capped collection example
  • Example#1371 - MongoDB::createDBRef example
  • Example#1372 - MongoDB::createDBRef example
  • Example#1373 - MongoDB::drop example
  • Example#1374 - Simple MongoDB::execute example
  • Example#1375 - Parameter MongoDB::execute example
  • Example#1376 - Scope example
  • Example#1377 - MongoDB::getDBRef example
  • Example#1378 - MongoDB::getGridFS example
  • Example#1379 - MongoDB::lastError NULL error example
  • Example#1380 - MongoDB::lastError duplicate key example
  • Example#1381 - MongoDB::listCollections example
  • Example#1382 - MongoDB::repair example
  • Example#1383 - MongoCollection::batchInsert example
  • Example#1384 - MongoCollection::count example
  • Example#1385 - MongoCollection::createDBRef example
  • Example#1386 - MongoCollection::deleteIndex example
  • Example#1387 - MongoCollection::deleteIndexes example
  • Example#1388 - MongoCollection::drop example
  • Example#1389 - MongoCollection::ensureIndex example
  • Example#1390 - Drop duplicates example
  • Example#1391 - Geospatial Indexing
  • Example#1392 - MongoCollection::find example
  • Example#1393 - MongoCollection::find example using $where
  • Example#1394 - MongoCollection::find example using $in
  • Example#1395 - Getting results as an array
  • Example#1396 - MongoCollection::findOne document by its id.
  • Example#1397 - MongoCollection::findOne document by some condition.
  • Example#1398 - MongoCollection::getDBRef example
  • Example#1399 - MongoCollection::find example
  • Example#1400 - MongoCollection::getName example
  • Example#1401 - MongoCollection::group example
  • Example#1402 - MongoCollection::group example
  • Example#1403 - Passing a keys function
  • Example#1404 - MongoCollection::insert _id example
  • Example#1405 - MongoCollection::insert safe example
  • Example#1406 - MongoCollection::remove with justOne example
  • Example#1407 - MongoCollection::save example
  • Example#1408 - MongoCollection::toIndexString example
  • Example#1409 - MongoCollection::__toString example
  • Example#1410 - MongoCollection::update
  • Example#1411 - MongoCollection::update upsert example
  • Example#1412 - MongoCollection::update multiple example
  • Example#1413 - MongoCursor::addOption example
  • Example#1414 - MongoCursor::count example
  • Example#1415 - MongoCursor::doQuery example
  • Example#1416 - MongoCursor::explain example
  • Example#1417 - MongoCursor::info example
  • Example#1418 - MongoCursor::slaveOkay example
  • Example#1419 - MongoCursor::sort example
  • Example#1420 - MongoCursor::tailable example
  • Example#1421 - MongoCursor::timeout example
  • Example#1422 - MongoId::__construct example
  • Example#1423 - Parameter example
  • Example#1424 - MongoId::__toString example
  • Example#1425 - MongoCode::__construct example
  • Example#1426 - Using MongoCode with $where
  • Example#1427 - MongoCode::__toString example
  • Example#1428 - MongoDate::__construct example
  • Example#1429 - MongoRegex::__construct example
  • Example#1430 - MongoRegex::__toString example
  • Example#1431 - MongoDBRef::create example
  • Example#1432 - MongoCollection::createDBRef example
  • Example#1433 - MongoGridFS::findOne example
  • Example#1434 - MongoGridFSFile::getBytes example
  • Example#1435 - MongoGridFSFile::getResource example
  • Example#1436 - MongoGridFSFile::write example
  • Example#1437 - Changing pool size
  • Example#1438 - Mongo::setPoolSize example
  • Example#1439 - Przykład użycia mSQL
  • Example#1440 - msql_fetch_array example
  • Example#1441 - msql_fetch_object example
  • Example#1442 - msql_fetch_row example
  • Example#1443 - msql_query example
  • Example#1444 - mssql_bind example
  • Example#1445 - Przykład mssql_close
  • Example#1446 - mssql_connect example
  • Example#1447 - mssql_data_seek example
  • Example#1448 - mssql_execute example
  • Example#1449 - mssql_fetch_array example
  • Example#1450 - mssql_fetch_assoc example
  • Example#1451 - mssql_fetch_batch example
  • Example#1452 - mssql_fetch_field example
  • Example#1453 - mssql_fetch_object example
  • Example#1454 - mssql_fetch_row example
  • Example#1455 - mssql_field_length example
  • Example#1456 - mssql_field_name example
  • Example#1457 - Using mssql_field_seek on the example for mssql_fetch_field
  • Example#1458 - mssql_field_type example
  • Example#1459 - mssql_free_result example
  • Example#1460 - mssql_free_statement example
  • Example#1461 - Przykład mssql_get_last_message
  • Example#1462 - mssql_guid_string example
  • Example#1463 - mssql_init example
  • Example#1464 - Przykład mssql_min_error_severity
  • Example#1465 - Przykład mssql_min_message_severity
  • Example#1466 - mssql_next_result example
  • Example#1467 - Przykład mssql_num_fields
  • Example#1468 - Przykład mssql_num_rows
  • Example#1469 - mssql_pconnect using the new_link parameter
  • Example#1470 - Przykład mssql_query
  • Example#1471 - mssql_result example
  • Example#1472 - Faster alternative to above example
  • Example#1473 - Przykład mssql_rows_affected
  • Example#1474 - mssql_select_db example
  • Example#1475 - Escaping the database name with square brackets
  • Example#1476 - Comparing the three MySQL APIs
  • Example#1477 - Configure commands for using mysqlnd or libmysql
  • Example#1478 - MySQL extension overview example
  • Example#1479 - Przykład mysql_affected_rows
  • Example#1480 - Przykład mysql_affected_rows używający transakcję
  • Example#1481 - Przykład użycia mysql_client_encoding
  • Example#1482 - Przykład mysql_close
  • Example#1483 - Przykład mysql_connect
  • Example#1484 - Przykład mysql_connect z użyciem składni nazwa_hosta:port
  • Example#1485 - mysql_connect przykład użycia składni ":/ścieżka/do/gniazda"
  • Example#1486 - mysql_create_db przykład alternatywny
  • Example#1487 - Przykład mysql_data_seek
  • Example#1488 - mysql_db_name
  • Example#1489 - Przykład mysql_db_query
  • Example#1490 - Przykłady użycia mysql_errno
  • Example#1491 - Przykład użycia mysql_error
  • Example#1492 - przykład użycia mysql_escape_string
  • Example#1493 - Zapytanie z powtarzającymi się nazwami pól
  • Example#1494 - mysql_fetch_array z MYSQL_NUM
  • Example#1495 - mysql_fetch_array z MYSQL_ASSOC
  • Example#1496 - mysql_fetch_array z MYSQL_BOTH
  • Example#1497 - mysql_fetch_assoc
  • Example#1498 - mysql_fetch_field
  • Example#1499 - mysql_fetch_object
  • Example#1500 - Pobieranie jednego wiersza za pomocą mysql_fetch_row
  • Example#1501 - mysql_field_name
  • Example#1502 - Przykład użycia mysql_field_table
  • Example#1503 - Typy pól MySQL
  • Example#1504 - mysql_get_client_info
  • Example#1505 - mysql_get_host_info
  • Example#1506 - mysql_get_proto_info
  • Example#1507 - mysql_get_server_info
  • Example#1508 - Formaty zwracanych wartości
  • Example#1509 - Przykład użycia mysql_insert_id
  • Example#1510 - mysql_list_dbs
  • Example#1511 - mysql_list_fields
  • Example#1512 - przykład użycia mysql_list_processes
  • Example#1513 - Przykład użycia mysql_list_tables
  • Example#1514 - mysql_num_rows
  • Example#1515 - Przykład użycia mysql_ping
  • Example#1516 - mysql_query
  • Example#1517 - mysql_query
  • Example#1518 - Przykład użycia mysql_real_escape_string
  • Example#1519 - Przykład ataku SQL Injection
  • Example#1520 - Przykład użycia mysql_select_db
  • Example#1521 - przykład użycia mysql_stat
  • Example#1522 - Przykład użycia mysql_tablename
  • Example#1523 - przykład użycia mysql_list_processes
  • Example#1524 - Easy migration from the old mysql extension
  • Example#1525 - Object-oriented and procedural interface
  • Example#1526 - Bad coding style
  • Example#1527 - Special meaning of localhost
  • Example#1528 - Setting defaults
  • Example#1529 - Bad coding style
  • Example#1530 - Navigation through buffered results
  • Example#1531 - Navigation through buffered results
  • Example#1532 - Text protocol returns strings by default
  • Example#1533 - Native data types with mysqlnd and conneciton option
  • Example#1534 - First stage: prepare
  • Example#1535 - Second stage: bind and execute
  • Example#1536 - INSERT prepared once, executed multiple times
  • Example#1537 - Less round trips using multi-INSERT SQL
  • Example#1538 - Native datatypes
  • Example#1539 - Output variable binding
  • Example#1540 - Using mysqli_result to fetch results
  • Example#1541 - Buffered result set for flexible read out
  • Example#1542 - Calling a stored procedure
  • Example#1543 - Using session variables
  • Example#1544 - Fetching results from stored procedures
  • Example#1545 - Stored Procedures and Prepared Statements
  • Example#1546 - Stored Procedures and Prepared Statements using bind API
  • Example#1547 - Multiple Statements
  • Example#1548 - SQL ijnection
  • Example#1549 - Setting auto commit mode with SQL and through the API
  • Example#1550 - Commit and rollback
  • Example#1551 - Accessing result set meta data
  • Example#1552 - Prepared statements metadata
  • Example#1553 - $mysqli->affected_rows example
  • Example#1554 - mysqli::autocommit example
  • Example#1555 - mysqli::change_user example
  • Example#1556 - mysqli::character_set_name example
  • Example#1557 - mysqli_get_client_info
  • Example#1558 - mysqli_get_client_version
  • Example#1559 - mysqli::commit example
  • Example#1560 - $mysqli->connect_errno example
  • Example#1561 - $mysqli->connect_error example
  • Example#1562 - mysqli::__construct example
  • Example#1563 - Generating a Trace File
  • Example#1564 - $mysqli->errno example
  • Example#1565 - $mysqli->error example
  • Example#1566 - $mysqli->field_count example
  • Example#1567 - mysqli::get_charset example
  • Example#1568 - mysqli_get_client_info
  • Example#1569 - A mysqli_get_client_stats example
  • Example#1570 - mysqli_get_client_version
  • Example#1571 - A mysqli_get_connection_stats example
  • Example#1572 - $mysqli->host_info example
  • Example#1573 - $mysqli->protocol_version example
  • Example#1574 - $mysqli->server_info example
  • Example#1575 - $mysqli->server_version example
  • Example#1576 - $mysqli->info example
  • Example#1577 - $mysqli->insert_id example
  • Example#1578 - mysqli::kill example
  • Example#1579 - mysqli::multi_query example
  • Example#1580 - mysqli::ping example
  • Example#1581 - A mysqli_poll example
  • Example#1582 - mysqli::prepare example
  • Example#1583 - mysqli::query example
  • Example#1584 - mysqli::real_connect example
  • Example#1585 - mysqli::real_escape_string example
  • Example#1586 - mysqli::rollback example
  • Example#1587 - mysqli::select_db example
  • Example#1588 - mysqli::set_charset example
  • Example#1589 - mysqli::set_local_infile_handler example
  • Example#1590 - $mysqli->sqlstate example
  • Example#1591 - mysqli::stat example
  • Example#1592 - $mysqli->thread_id example
  • Example#1593 - mysqli::use_result example
  • Example#1594 - $mysqli->warning_count example
  • Example#1595 - Styl obiektowy
  • Example#1596 - Styl proceduralny
  • Example#1597 - Styl obiektowy
  • Example#1598 - Styl proceduralny
  • Example#1599 - Styl obiektowy
  • Example#1600 - Styl proceduralny
  • Example#1601 - Styl obiektowy
  • Example#1602 - Styl proceduralny
  • Example#1603 - Styl obiektowy
  • Example#1604 - Styl proceduralny
  • Example#1605 - Styl obiektowy
  • Example#1606 - Styl proceduralny
  • Example#1607 - Styl obiektowy
  • Example#1608 - Styl proceduralny
  • Example#1609 - Styl obiektowy
  • Example#1610 - Styl proceduralny
  • Example#1611 - Styl obiektowy
  • Example#1612 - Styl proceduralny
  • Example#1613 - Styl obiektowy
  • Example#1614 - Styl proceduralny
  • Example#1615 - Styl obiektowy
  • Example#1616 - Styl proceduralny
  • Example#1617 - Styl obiektowy
  • Example#1618 - Styl proceduralny
  • Example#1619 - Styl obiektowy
  • Example#1620 - Styl proceduralny
  • Example#1621 - Styl obiektowy
  • Example#1622 - Styl obiektowy
  • Example#1623 - Styl proceduralny
  • Example#1624 - Styl obiektowy
  • Example#1625 - Styl proceduralny
  • Example#1626 - Styl obiektowy
  • Example#1627 - Styl proceduralny
  • Example#1628 - Styl obiektowy
  • Example#1629 - Styl proceduralny
  • Example#1630 - Styl obiektowy
  • Example#1631 - Styl proceduralny
  • Example#1632 - Styl obiektowy
  • Example#1633 - Styl proceduralny
  • Example#1634 - A mysqli_result example comparing iterator usage
  • Example#1635 - Styl obiektowy
  • Example#1636 - Styl proceduralny
  • Example#1637 - Styl obiektowy
  • Example#1638 - Styl proceduralny
  • Example#1639 - Styl obiektowy
  • Example#1640 - Styl proceduralny
  • Example#1641 - Styl obiektowy
  • Example#1642 - Styl proceduralny
  • Example#1643 - Styl obiektowy
  • Example#1644 - Styl proceduralny
  • Example#1645 - Styl obiektowy
  • Example#1646 - Styl proceduralny
  • Example#1647 - Styl obiektowy
  • Example#1648 - Styl proceduralny
  • Example#1649 - Styl obiektowy
  • Example#1650 - Styl proceduralny
  • Example#1651 - Styl obiektowy
  • Example#1652 - Styl proceduralny
  • Example#1653 - A mysqli_get_cache_stats example
  • Example#1654 - Styl obiektowy
  • Example#1655 - Enabling the plugin (php.ini)
  • Example#1656 - Minimal plugin-specific configuration file (mysqlnd_ms_plugin.ini)
  • Example#1657 - Recommended minimal plugin-specific config (mysqlnd_ms_plugin.ini)
  • Example#1658 - Using one server as a master and as a slave (testing only!)
  • Example#1659 - Plugin specific configuration file (mysqlnd_ms_plugin.ini)
  • Example#1660 - Opening a load balanced connection
  • Example#1661 - Executing statements
  • Example#1662 - Plugin config with one slave and one master
  • Example#1663 - Pitfall: connection state and SQL user variables
  • Example#1664 - Plugin config with one slave and one master
  • Example#1665 - SQL hints to prevent connection switches
  • Example#1666 - Fighting replication lag
  • Example#1667 - Table creation on a slave
  • Example#1668 - Plugin config with one slave and one master
  • Example#1669 - Using SQL hints for transactions
  • Example#1670 - Transaction aware load balancing: trx_stickiness setting
  • Example#1671 - Transaction aware
  • Example#1672 - Session consistency: read your writes
  • Example#1673 - Requesting session consistency
  • Example#1674 - Maximum age/slave lag
  • Example#1675 - Limiting slave lag
  • Example#1676 - Fail over not set
  • Example#1677 - No slave within time limit
  • Example#1678 - Create counter table on master
  • Example#1679 - Plugin config: SQL for client-side GTID injection
  • Example#1680 - Transparent global transaction ID injection
  • Example#1681 - Plugin config: SQL for fetching GTID
  • Example#1682 - Obtaining GTID after injection
  • Example#1683 - Plugin config: Checking for a certain GTID
  • Example#1684 - Session consistency service level and GTID combined
  • Example#1685 - Provoking a connection error
  • Example#1686 - Connection error on query execution
  • Example#1687 - Provoking a connection error
  • Example#1688 - Most basic failover
  • Example#1689 - Converting a PHP array (hash) into JSON format
  • Example#1690 - Using section names example
  • Example#1691 - List of anonymous slaves
  • Example#1692 - Master list using symbolic names
  • Example#1693 - Keywords to configure a server
  • Example#1694 - New roundrobin filter, old functionality
  • Example#1695 - The user filter replaces mysqlnd_ms_set_user_pick_server
  • Example#1696 - Invalid filter sequence
  • Example#1697 - Random load balancing with random filter
  • Example#1698 - Random once load balancing with random filter
  • Example#1699 - roundrobin filter
  • Example#1700 - Setting a callback
  • Example#1701 - Using a callback
  • Example#1702 - Returning random masters and slaves
  • Example#1703 - Global limit on slave lag
  • Example#1704 - Optional master failover when failing to connect to slave
  • Example#1705 - Disabling lazy connection
  • Example#1706 - Master on write for consistent reads
  • Example#1707 - Using master to execute transactions
  • Example#1708 - Using section names example
  • Example#1709 - List-like syntax
  • Example#1710 - Verify plugin activity in a non-threaded deployment model
  • Example#1711 - Recording statistics during shutdown
  • Example#1712 -
  • Example#1713 - mysqlnd_ms_get_last_gtid example
  • Example#1714 - mysqlnd_ms_get_last_used_connection example
  • Example#1715 - mysqlnd_ms_get_stats example
  • Example#1716 - mysqlnd_ms_match_wild example
  • Example#1717 - mysqlnd_ms_query_is_select example
  • Example#1718 - mysqlnd_ms_set_qos example
  • Example#1719 - mysqlnd_ms_set_user_pick_server example
  • Example#1720 - Enabling the plugin (php.ini)
  • Example#1721 -
  • Example#1722 -
  • Example#1723 -
  • Example#1724 -
  • Example#1725 -
  • Example#1726 -
  • Example#1727 -
  • Example#1728 -
  • Example#1729 -
  • Example#1730 -
  • Example#1731 -
  • Example#1732 -
  • Example#1733 -
  • Example#1734 -
  • Example#1735 -
  • Example#1736 -
  • Example#1737 -
  • Example#1738 -
  • Example#1739 -
  • Example#1740 -
  • Example#1741 -
  • Example#1742 -
  • Example#1743 - Enabling the plugin (php.ini)
  • Example#1744 - Pseudo-code: what a built-in class does
  • Example#1745 - Installing a proxy
  • Example#1746 - Proxy registration, mysqlnd_uh.enable=1
  • Example#1747 - Proxy installation disabled
  • Example#1748 - Connection proxy
  • Example#1749 - Prepared statement proxy
  • Example#1750 - Basic Monitoring
  • Example#1751 - MysqlndUhConnection::changeUser example
  • Example#1752 - MysqlndUhConnection::charsetName example
  • Example#1753 - MysqlndUhConnection::close example
  • Example#1754 - MysqlndUhConnection::connect example
  • Example#1755 - MysqlndUhConnection::endPSession example
  • Example#1756 - MysqlndUhConnection::escapeString example
  • Example#1757 - MysqlndUhConnection::getAffectedRows example
  • Example#1758 - MysqlndUhConnection::getErrorNumber example
  • Example#1759 - MysqlndUhConnection::getErrorString example
  • Example#1760 - MysqlndUhConnection::getFieldCount example
  • Example#1761 - MysqlndUhConnection::getHostInformation example
  • Example#1762 - MysqlndUhConnection::getLastInsertId example
  • Example#1763 - MysqlndUhConnection::getLastMessage example
  • Example#1764 - MysqlndUhConnection::getProtocolInformation example
  • Example#1765 - MysqlndUhConnection::getServerInformation example
  • Example#1766 - MysqlndUhConnection::getServerStatistics example
  • Example#1767 - MysqlndUhConnection::getServerVersion example
  • Example#1768 - MysqlndUhConnection::getSqlstate example
  • Example#1769 - MysqlndUhConnection::getStatistics example
  • Example#1770 - MysqlndUhConnection::getThreadId example
  • Example#1771 - MysqlndUhConnection::getWarningCount example
  • Example#1772 - MysqlndUhConnection::init example
  • Example#1773 - MysqlndUhConnection::kill example
  • Example#1774 - MysqlndUhConnection::listFields example
  • Example#1775 - MysqlndUhConnection::listMethod example
  • Example#1776 - MysqlndUhConnection::moreResults example
  • Example#1777 - MysqlndUhConnection::nextResult example
  • Example#1778 - MysqlndUhConnection::ping example
  • Example#1779 - MysqlndUhConnection::query example
  • Example#1780 - MysqlndUhConnection::queryReadResultsetHeader example
  • Example#1781 - MysqlndUhConnection::reapQuery example
  • Example#1782 - MysqlndUhConnection::refreshServer example
  • Example#1783 - MysqlndUhConnection::restartPSession example
  • Example#1784 - MysqlndUhConnection::selectDb example
  • Example#1785 - MysqlndUhConnection::sendClose example
  • Example#1786 - MysqlndUhConnection::sendQuery example
  • Example#1787 - MysqlndUhConnection::serverDumpDebugInformation example
  • Example#1788 - MysqlndUhConnection::setAutocommit example
  • Example#1789 - MysqlndUhConnection::setCharset example
  • Example#1790 - MysqlndUhConnection::setClientOption example
  • Example#1791 - MysqlndUhConnection::setServerOption example
  • Example#1792 - MysqlndUhConnection::simpleCommand example
  • Example#1793 - MysqlndUhConnection::simpleCommandHandleResponse example
  • Example#1794 - MysqlndUhConnection::sslSet example
  • Example#1795 - MysqlndUhConnection::stmtInit example
  • Example#1796 - MysqlndUhConnection::storeResult example
  • Example#1797 - MysqlndUhConnection::txCommit example
  • Example#1798 - MysqlndUhConnection::txRollback example
  • Example#1799 - MysqlndUhConnection::useResult example
  • Example#1800 - MysqlndUhPreparedStatement::execute example
  • Example#1801 - MysqlndUhPreparedStatement::prepare example
  • Example#1802 - mysqlnd_uh_convert_to_mysqlnd example
  • Example#1803 - mysqlnd_uh_set_connection_proxy example
  • Example#1804 - Basic query
  • Example#1805 - Inserting with bind variables
  • Example#1806 - Inserting data into a CLOB column
  • Example#1807 - Using a PL/SQL stored function
  • Example#1808 - Using a PL/SQL stored procedure
  • Example#1809 - Calling a PL/SQL function that returns a REF CURSOR
  • Example#1810 - oci_bind_array_by_name example
  • Example#1811 - Inserting data with oci_bind_by_name
  • Example#1812 - Binding once for multiple executions
  • Example#1813 - Binding with a foreach loop
  • Example#1814 - Binding in a WHERE clause
  • Example#1815 - Binding with a LIKE clause
  • Example#1816 - Binding with REGEXP_LIKE
  • Example#1817 - Binding Multiple Values in an IN Clause
  • Example#1818 - Binding a ROWID returned by a query
  • Example#1819 - Binding a ROWID on INSERT
  • Example#1820 - Binding for a PL/SQL stored function
  • Example#1821 - Binding parameters for a PL/SQL stored procedure
  • Example#1822 - Binding a CLOB column
  • Example#1823 - oci_client_version example
  • Example#1824 - Closing a connection
  • Example#1825 - Database connections are not closed until all references are closed
  • Example#1826 - Closing a connection opened more than once
  • Example#1827 - Connections are closed when variables go out of scope
  • Example#1828 - oci_commit example
  • Example#1829 - Basic oci_connect using Easy Connect syntax
  • Example#1830 - Basic oci_connect using a Network Connect name
  • Example#1831 - oci_connect with an explicit character set
  • Example#1832 - Using multiple calls to oci_connect
  • Example#1833 - oci_define_by_name example
  • Example#1834 - oci_define_by_name with case sensitive column names
  • Example#1835 - oci_define_by_name with LOB columns
  • Example#1836 - oci_define_by_name with an explicit type
  • Example#1837 - Displaying the Oracle error message after a connection error
  • Example#1838 - Displaying the Oracle error message after a parsing error
  • Example#1839 - Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error
  • Example#1840 - oci_execute for queries
  • Example#1841 - oci_execute without specifying a mode example
  • Example#1842 - oci_execute with OCI_NO_AUTO_COMMIT example
  • Example#1843 - oci_execute with different commit modes example
  • Example#1844 - oci_execute with OCI_DESCRIBE_ONLY example
  • Example#1845 - oci_fetch_all example
  • Example#1846 - oci_fetch_all example with OCI_FETCHSTATEMENT_BY_ROW
  • Example#1847 - oci_fetch_all with OCI_NUM
  • Example#1848 - oci_fetch_array with OCI_BOTH
  • Example#1849 - oci_fetch_array with OCI_NUM
  • Example#1850 - oci_fetch_array with OCI_ASSOC
  • Example#1851 - oci_fetch_array with OCI_RETURN_NULLS
  • Example#1852 - oci_fetch_array with OCI_RETURN_LOBS
  • Example#1853 - oci_fetch_array with case sensitive column names
  • Example#1854 - oci_fetch_array with columns having duplicate names
  • Example#1855 - oci_fetch_array with DATE columns
  • Example#1856 - oci_fetch_array with REF CURSOR
  • Example#1857 - oci_fetch_array with a LIMIT-like query
  • Example#1858 - oci_fetch_object example
  • Example#1859 - oci_fetch_object with case sensitive column names
  • Example#1860 - oci_fetch_object with LOBs
  • Example#1861 - oci_fetch with defined variables
  • Example#1862 - oci_fetch with oci_result
  • Example#1863 - oci_field_name example
  • Example#1864 - oci_field_size example
  • Example#1865 - oci_field_type example
  • Example#1866 - oci_new_connect example
  • Example#1867 - Using REF CURSOR in an Oracle's stored procedure
  • Example#1868 - Using REF CURSOR in an Oracle's select statement
  • Example#1869 - oci_new_descriptor example
  • Example#1870 - oci_new_descriptor example
  • Example#1871 - oci_num_fields example
  • Example#1872 - oci_num_rows example
  • Example#1873 - oci_parse example for SQL statements
  • Example#1874 - oci_parse example for PL/SQL statements
  • Example#1875 - oci_rollback example
  • Example#1876 - Rolling back to a SAVEPOINT example
  • Example#1877 - oci_server_version example
  • Example#1878 - Setting the action
  • Example#1879 - Setting the client identifier to the application user
  • Example#1880 - Setting the client information
  • Example#1881 - Two scripts can use different versions of myfunc() at the same time
  • Example#1882 - Setting the module name
  • Example#1883 - Changing the default prefetch value for a query
  • Example#1884 - Changing the default prefetch for a REF CURSOR fetch
  • Example#1885 - Setting the prefetch value when passing a REF CURSOR back to Oracle
  • Example#1886 - oci_statement_type example
  • Example#1887 - Połączenie do Ovrimos SQL Server i pobranie danych z tabeli systemowej
  • Example#1888 - Przykład ovrimos_connect
  • Example#1889 - Przykład ovrimos_fetch_into
  • Example#1890 - Przykład ovrimos_fetch_row
  • Example#1891 - Przykład ovrimos_prepare
  • Example#1892 - Przygotowanie instrukcji, wykonanie, i wyświetlenie wyniku
  • Example#1893 - Przykład ovrimos_result_all z metadanymi
  • Example#1894 - Creating a Paradox database with two fields
  • Example#1895 - Turn a paradox date into a human readable form
  • Example#1896 - Set the date/time fields in a paradox database to the current date/time
  • Example#1897 - Opening a Paradox database
  • Example#1898 - Opening a Paradox database
  • Example#1899 - Turn a paradox timestamp into a human readable form
  • Example#1900 - Przykład działania rozszerzenia PostgreSQL
  • Example#1901 - pg_affected_rows przykład
  • Example#1902 - pg_cancel_query przykład
  • Example#1903 - pg_client_encoding przykład
  • Example#1904 - pg_close przykład
  • Example#1905 - Używanie pg_connect
  • Example#1906 - pg_connection_busy przykład
  • Example#1907 - pg_connection_reset przykład
  • Example#1908 - pg_connection_status przykład
  • Example#1909 - pg_convert - przykład
  • Example#1910 - pg_copy_from przykład
  • Example#1911 - pg_copy_to - przykład
  • Example#1912 - pg_dbname - przykład
  • Example#1913 - pg_delete - przykład
  • Example#1914 - pg_end_copy - przykład
  • Example#1915 - pg_escape_bytea - przykład
  • Example#1916 - pg_escape_identifier example
  • Example#1917 - pg_escape_literal example
  • Example#1918 - pg_escape_string - przykład
  • Example#1919 - Using pg_execute
  • Example#1920 - pg_fetch_all_columns example
  • Example#1921 - PostgreSQL fetch all
  • Example#1922 - pg_fetch_array - przykład
  • Example#1923 - pg_fetch_assoc example
  • Example#1924 - pg_fetch_object - przykład
  • Example#1925 - pg_fetch_result - przykład
  • Example#1926 - pg_fetch_row - przykład
  • Example#1927 - pg_field_is_null - przykład
  • Example#1928 - Pobieranie informacji o kolumnach
  • Example#1929 - Pobieranie informacji o polach
  • Example#1930 - Pobieranie informacji na temat pól
  • Example#1931 - Pobieranie informacji o polach
  • Example#1932 - Getting table information about a field
  • Example#1933 - Getting information about fields
  • Example#1934 - Pobieranie informacji o kolumnach
  • Example#1935 - pg_free_result - przykład
  • Example#1936 - PostgreSQL NOTIFY message
  • Example#1937 - PostgreSQL backend PID
  • Example#1938 - pg_get_result - przykład
  • Example#1939 - pg_host - przykład
  • Example#1940 - pg_insert - przykład
  • Example#1941 - pg_last_error - przykład
  • Example#1942 - pg_last_oid - przykład
  • Example#1943 - pg_lo_close - przykład
  • Example#1944 - pg_lo_export - przykład
  • Example#1945 - pg_lo_import - przykład
  • Example#1946 - Pobranie informacji o tabeli
  • Example#1947 - pg_parameter_status example
  • Example#1948 - Używanie pg_pconnect
  • Example#1949 - pg_ping example
  • Example#1950 - Using pg_prepare
  • Example#1951 - Szybkie wstawianie danych do tebeli
  • Example#1952 - Using pg_query_params
  • Example#1953 - pg_query - przykład
  • Example#1954 - Używanie pg_query z wieloma zapytaniami
  • Example#1955 - pg_result_error_field example
  • Example#1956 - pg_result_seek example
  • Example#1957 - pg_result_status - przykład
  • Example#1958 - pg_select example
  • Example#1959 - Using pg_send_execute
  • Example#1960 - Using pg_send_prepare
  • Example#1961 - Using pg_send_query_params
  • Example#1962 - Przykład pg_send_query
  • Example#1963 - pg_set_error_verbosity example
  • Example#1964 - pg_transaction_status example
  • Example#1965 - pg_unescape_bytea example
  • Example#1966 - pg_update - przykład
  • Example#1967 - pg_version example
  • Example#1968 - Styl proceduralny
  • Example#1969 - Object-oriented style
  • Example#1970 - Styl proceduralny
  • Example#1971 - Styl obiektowy
  • Example#1972 - Styl proceduralny
  • Example#1973 - Styl obiektowy
  • Example#1974 - sqlite_close example
  • Example#1975 - max_length aggregation function example
  • Example#1976 - sqlite_create_function example
  • Example#1977 - Example of using the PHP function
  • Example#1978 - Procedural example
  • Example#1979 - Object-oriented example
  • Example#1980 - sqlite_factory example
  • Example#1981 - Procedural example
  • Example#1982 - Object-oriented example
  • Example#1983 - Procedural example
  • Example#1984 - Object-oriented example
  • Example#1985 - Procedural example
  • Example#1986 - Object-oriented example
  • Example#1987 - A sqlite_fetch_single example
  • Example#1988 - Procedural example
  • Example#1989 - Object-oriented example
  • Example#1990 - sqlite_open example
  • Example#1991 - binary-safe max_length aggregation function example
  • Example#1992 - SQLite3::changes example
  • Example#1993 - SQLite3::close example
  • Example#1994 - SQLite3::__construct example
  • Example#1995 - SQLite3::createFunction example
  • Example#1996 - SQLite3::exec example
  • Example#1997 - SQLite3::loadExtension example
  • Example#1998 - SQLite3::open example
  • Example#1999 - SQLite3::prepare example
  • Example#2000 - SQLite3::query example
  • Example#2001 - SQLite3::querySingle example
  • Example#2002 - SQLite3::version example
  • Example#2003 - SQLite3Stmt::bindValue example
  • Example#2004 - sqlsrv_begin_transaction example
  • Example#2005 - sqlsrv_cancel example
  • Example#2006 - sqlsrv_client_info example
  • Example#2007 - sqlsrv_close example
  • Example#2008 - sqlsrv_commit example
  • Example#2009 - Connect using Windows Authentication.
  • Example#2010 - Connect by specifying a user name and password.
  • Example#2011 - Connect on a specifed port.
  • Example#2012 - functionname example
  • Example#2013 - sqlsrv_execute example
  • Example#2014 - Retrieving an associative array.
  • Example#2015 - Retrieving a numeric array.
  • Example#2016 - sqlsrv_fetch_object example
  • Example#2017 - sqlsrv_fetch example
  • Example#2018 - sqlsrv_field_metadata example
  • Example#2019 - sqlsrv_free_stmt example
  • Example#2020 - sqlsrv_get_field example
  • Example#2021 - sqlsrv_has_rows example
  • Example#2022 - sqlsrv_next_result example
  • Example#2023 - sqlsrv_num_fields example
  • Example#2024 - sqlsrv_num_rows example
  • Example#2025 - sqlsrv_prepare example
  • Example#2026 - sqlsrv_query example
  • Example#2027 - sqlsrv_rollback example
  • Example#2028 - sqlsrv_rows_affected example
  • Example#2029 - sqlsrv_send_stream_data example
  • Example#2030 - sqlsrv_server_info example
  • Example#2031 - Delete-Query
  • Example#2032 - sybase_connect example
  • Example#2033 - Identical fieldnames
  • Example#2034 - sybase_fetch_object return as Foo
  • Example#2035 - sybase_set_message_handler callback function
  • Example#2036 - sybase_set_message_handler callback to a class
  • Example#2037 - sybase_set_message_handler unhandled messages
  • Example#2038 - sybase_unbuffered_query example
  • Example#2039 - Putting and getting a key-value pair
  • Example#2040 - TokyoTyrant::add example
  • Example#2041 - TokyoTyrant::connect example
  • Example#2042 - TokyoTyrant::connectUri example
  • Example#2043 - TokyoTyrant::copy example
  • Example#2044 - TokyoTyrant::ext example
  • Example#2045 - TokyoTyrant::fwmKeys example
  • Example#2046 - TokyoTyrant::get example
  • Example#2047 - TokyoTyrant::getIterator example
  • Example#2048 - TokyoTyrant::num example
  • Example#2049 - TokyoTyrant::out example
  • Example#2050 - TokyoTyrant::put example
  • Example#2051 - TokyoTyrant::putCat example
  • Example#2052 - tokyotyrant::putKeep example
  • Example#2053 - TokyoTyrant::putNr example
  • Example#2054 - TokyoTyrant::putShl example
  • Example#2055 - TokyoTyrant::setMaster example
  • Example#2056 - TokyoTyrant::size example
  • Example#2057 - TokyoTyrant::stat example
  • Example#2058 - TokyoTyrant::vanish example
  • Example#2059 - TokyoTyrantTable::genUid example
  • Example#2060 - TokyoTyrantTable::get example
  • Example#2061 - TokyoTyrantTable::getIterator example
  • Example#2062 - TokyoTyrantTable::getQuery example
  • Example#2063 - TokyoTyrantTable::out example
  • Example#2064 - TokyoTyrantTable::put example
  • Example#2065 - TokyoTyrantTable::putCat example
  • Example#2066 - TokyoTyrantTable::putKeep example
  • Example#2067 - TokyoTyrantQuery::addCond example
  • Example#2068 - TokyoTyrantQuery::__construct example
  • Example#2069 - TokyoTyrantQuery::count example
  • Example#2070 - TokyoTyrantQuery iterator example
  • Example#2071 - TokyoTyrantQuery::hint example
  • Example#2072 - TokyoTyrantQuery iterator example
  • Example#2073 - TokyoTyrantQuery::metaSearch example
  • Example#2074 - TokyoTyrantQuery iterator example
  • Example#2075 - TokyoTyrantQuery::out example
  • Example#2076 - TokyoTyrantQuery iterator example
  • Example#2077 - TokyoTyrantQuery::search example
  • Example#2078 - TokyoTyrantQuery iterator example
  • Example#2079 - TokyoTyrantIterator::__construct example
  • Example#2080 - Closing an open file descriptor
  • Example#2081 - Setting and clearing a lock
  • Example#2082 - Opening a file descriptor
  • Example#2083 - Positioning in a file
  • Example#2084 - Setting the baud rate on a serial port
  • Example#2085 - Przykład użycia chdir
  • Example#2086 - Przykład closedir
  • Example#2087 - dir example
  • Example#2088 - Przykład użycia getcwd
  • Example#2089 - opendir example
  • Example#2090 - Lista wszystkich plików w katalogu
  • Example#2091 - Lista wszystkich plików w wskazanym katalogu oprócz . i ..
  • Example#2092 - Przykład użycia scandire
  • Example#2093 - Alternatywa dla scandir w PHP 4
  • Example#2094 - A finfo_buffer example
  • Example#2095 - A finfo_file example
  • Example#2096 - Styl obiektowy
  • Example#2097 - Styl proceduralny
  • Example#2098 - mime_content_type Example
  • Example#2099 - Przykład basename
  • Example#2100 - Zmiana grupy pliku
  • Example#2101 - Proste użycie chown
  • Example#2102 - Przykład clearstatcache
  • Example#2103 - copy przykład
  • Example#2104 - Przykład dirname
  • Example#2105 - Przykład disk_free_space
  • Example#2106 - Przykład disk_total_space
  • Example#2107 - Prosty przykład fclose
  • Example#2108 - Obsługa limitu czasu w feof
  • Example#2109 - feof przykład z nieprawidłowym wskaźnikiem pliku
  • Example#2110 - Przykład zapisu do pliku używając fflush
  • Example#2111 - Przykład fgetc
  • Example#2112 - fgetcsv przykład - Odczyt i wyświetlenie całej zawartości pliku CSV
  • Example#2113 - Oczyt pliku linia po linii
  • Example#2114 - Czytanie pliku PHP linia po linii
  • Example#2115 - Sprawdzanie czy plik istnieje
  • Example#2116 - Get and output the source of the homepage of a website
  • Example#2117 - Searching within the include_path
  • Example#2118 - Reading a section of a file
  • Example#2119 - Using stream contexts
  • Example#2120 - Simple usage example
  • Example#2121 - Using flags
  • Example#2122 - fileatime przykład
  • Example#2123 - filectime przykład
  • Example#2124 - filemtime przykład
  • Example#2125 - Wyświetlanie uprawnień w postaci ósemkowej
  • Example#2126 - Wyświetlanie wszystkich uprawnień
  • Example#2127 - filesize przykład
  • Example#2128 - filetype przykład
  • Example#2129 - flock example
  • Example#2130 - flock using the LOCK_NB option
  • Example#2131 - Checking a color name against a shell wildcard pattern
  • Example#2132 - fopen przykłady
  • Example#2133 - Using fpassthru with binary files
  • Example#2134 - fputcsv example
  • Example#2135 - fscanf Przykład
  • Example#2136 - Zawartość pliku users.txt
  • Example#2137 - fseek example
  • Example#2138 - fstat przykład
  • Example#2139 - ftell przykład
  • Example#2140 - Prosty przykład fwrite
  • Example#2141 - Convenient way how glob can replace opendir and friends.
  • Example#2142 - is_dir przykład
  • Example#2143 - is_executable przykład
  • Example#2144 - is_file przykład
  • Example#2145 - is_readable example
  • Example#2146 - is_uploaded_file przykład
  • Example#2147 - is_uploaded_file przykład dla PHP 4 < 4.0.3
  • Example#2148 - is_writable example
  • Example#2149 - Changing the group of a symbolic link
  • Example#2150 - Changing the owner of a symbolic link
  • Example#2151 - przykład linkinfo
  • Example#2152 - mkdir przykład
  • Example#2153 - Contents of sample.ini
  • Example#2154 - parse_ini_file example
  • Example#2155 - parse_ini_file parsing a php.ini file
  • Example#2156 - Przykład pathinfo
  • Example#2157 - popen przykład
  • Example#2158 - readlink przykład
  • Example#2159 - realpath_cache_get example
  • Example#2160 - realpath_cache_size example
  • Example#2161 - realpath example
  • Example#2162 - realpath on Windows
  • Example#2163 - Example with rename
  • Example#2164 - rewind overwriting example
  • Example#2165 - stat example
  • Example#2166 - Using stat information together with touch
  • Example#2167 - tempnam example
  • Example#2168 - tmpfile przykład
  • Example#2169 - touch przykład
  • Example#2170 - touch użycie parametru czas
  • Example#2171 - umask example
  • Example#2172 - Podstawowe użycie unlink
  • Example#2173 - Example usage of inotify
  • Example#2174 - Setting the path to magic.mime
  • Example#2175 - setproctitle example
  • Example#2176 - setthreadtitle example
  • Example#2177 - Checks if system administrator has signed the file
  • Example#2178 - Prints names of all extended attributes of file
  • Example#2179 - Removes all extended attributes of a file
  • Example#2180 - Sets extended attributes on .wav file
  • Example#2181 - xattr_supported example
  • Example#2182 - xdiff_file_bdiff_size example
  • Example#2183 - xdiff_file_bdiff example
  • Example#2184 - xdiff_file_bpatch example
  • Example#2185 - xdiff_file_diff_binary example
  • Example#2186 - xdiff_file_diff example
  • Example#2187 - xdiff_file_merge3 example
  • Example#2188 - xdiff_file_patch_binary example
  • Example#2189 - xdiff_file_patch example
  • Example#2190 - Patch reversing example
  • Example#2191 - xdiff_file_rabdiff example
  • Example#2192 - xdiff_string_bdiff_size example
  • Example#2193 - xdiff_string_diff example
  • Example#2194 - xdiff_string_patch example
  • Example#2195 - Enchant Usage Example
  • Example#2196 - List the backends provided by the given broker
  • Example#2197 - A enchant_broker_dict_exists example
  • Example#2198 - List all available dictionaries for one broker
  • Example#2199 - A enchant_broker_request_dict example
  • Example#2200 - A enchant_dict_describe example
  • Example#2201 - A enchant_dict_quick_check example
  • Example#2202 - A enchant_dict_suggest example
  • Example#2203 - bindtextdomain example
  • Example#2204 - gettext-check
  • Example#2205 - ngettext example
  • Example#2206 - iconv_mime_decode_headers example
  • Example#2207 - iconv_mime_decode example
  • Example#2208 - iconv_mime_encode example
  • Example#2209 - przykład iconv_set_encoding:
  • Example#2210 - przykład iconv:
  • Example#2211 - przykład ob_iconv_handler:
  • Example#2212 - Example of using the procedural API
  • Example#2213 - Example of using the object-oriented API
  • Example#2214 - FRENCH_COLLATION rules
  • Example#2215 - ALTERNATE_HANDLING rules
  • Example#2216 - CASE_FIRST rules
  • Example#2217 - CASE_LEVEL rules
  • Example#2218 - collator_asortexample
  • Example#2219 - collator_compareexample
  • Example#2220 - Collator::__construct example
  • Example#2221 - collator_create example
  • Example#2222 - collator_get_attribute example
  • Example#2223 - collator_get_error_code example
  • Example#2224 - collator_get_error_message example
  • Example#2225 - collator_get_locale example
  • Example#2226 - collator_get_sort_keyexample
  • Example#2227 - collator_get_strength example
  • Example#2228 - collator_set_attribute example
  • Example#2229 - collator_set_strength example
  • Example#2230 - collator_sort_with_sort_keys example
  • Example#2231 - collator_sort example
  • Example#2232 - numfmt_create example
  • Example#2233 - NumberFormatter::create example
  • Example#2234 - numfmt_format_currency example
  • Example#2235 - OO example
  • Example#2236 - numfmt_format example
  • Example#2237 - OO example
  • Example#2238 - numfmt_get_attribute example
  • Example#2239 - OO example
  • Example#2240 - numfmt_get_error_code example
  • Example#2241 - OO example
  • Example#2242 - numfmt_get_error_message example
  • Example#2243 - OO example
  • Example#2244 - numfmt_get_locale example
  • Example#2245 - numfmt_get_pattern example
  • Example#2246 - OO example
  • Example#2247 - numfmt_get_symbol example
  • Example#2248 - OO example
  • Example#2249 - numfmt_get_text_attribute example
  • Example#2250 - OO example
  • Example#2251 - numfmt_parse_currency example
  • Example#2252 - OO example
  • Example#2253 - numfmt_parse example
  • Example#2254 - OO example
  • Example#2255 - numfmt_set_attribute example
  • Example#2256 - OO example
  • Example#2257 - numfmt_set_pattern example
  • Example#2258 - OO example
  • Example#2259 - numfmt_set_symbol example
  • Example#2260 - OO example
  • Example#2261 - numfmt_set_text_attribute example
  • Example#2262 - OO example
  • Example#2263 - locale_accept_from_http example
  • Example#2264 - OO example
  • Example#2265 - locale_compose example
  • Example#2266 - OO example
  • Example#2267 - locale_filter_matches example
  • Example#2268 - OO example
  • Example#2269 - locale_get_all_variants example
  • Example#2270 - OO example
  • Example#2271 - locale_get_default example
  • Example#2272 - OO example
  • Example#2273 - locale_get_display_language example
  • Example#2274 - OO example
  • Example#2275 - locale_get_display_name example
  • Example#2276 - OO example
  • Example#2277 - locale_get_display_region example
  • Example#2278 - OO example
  • Example#2279 - locale_get_display_script example
  • Example#2280 - OO example
  • Example#2281 - locale_get_display_variant example
  • Example#2282 - OO example
  • Example#2283 - locale_get_keywords example
  • Example#2284 - OO example
  • Example#2285 - locale_get_primary_language example
  • Example#2286 - OO example
  • Example#2287 - locale_get_region example
  • Example#2288 - OO example
  • Example#2289 - locale_get_script example
  • Example#2290 - OO example
  • Example#2291 - locale_lookup example
  • Example#2292 - OO example
  • Example#2293 - locale_parse example
  • Example#2294 - OO example
  • Example#2295 - locale_set_default example
  • Example#2296 - OO example
  • Example#2297 - normalizer_is_normalized example
  • Example#2298 - OO example
  • Example#2299 - normalizer_normalize example
  • Example#2300 - OO example
  • Example#2301 - msgfmt_create example
  • Example#2302 - OO example
  • Example#2303 - msgfmt_format_message example
  • Example#2304 - OO example
  • Example#2305 - msgfmt_format example
  • Example#2306 - OO example
  • Example#2307 - msgfmt_get_error_code example
  • Example#2308 - OO example
  • Example#2309 - msgfmt_get_error_message example
  • Example#2310 - OO example
  • Example#2311 - msgfmt_get_locale example
  • Example#2312 - OO example
  • Example#2313 - msgfmt_get_pattern example
  • Example#2314 - OO example
  • Example#2315 - msgfmt_parse_message example
  • Example#2316 - OO example
  • Example#2317 - msgfmt_parse example
  • Example#2318 - OO example
  • Example#2319 - msgfmt_set_pattern example
  • Example#2320 - OO example
  • Example#2321 - datefmt_create example
  • Example#2322 - OO example
  • Example#2323 - datefmt_format example
  • Example#2324 - OO example
  • Example#2325 - datefmt_get_calendar example
  • Example#2326 - OO example
  • Example#2327 - datefmt_get_datetype example
  • Example#2328 - OO example
  • Example#2329 - datefmt_get_error_code example
  • Example#2330 - OO example
  • Example#2331 - datefmt_get_error_message example
  • Example#2332 - OO example
  • Example#2333 - datefmt_get_locale example
  • Example#2334 - OO example
  • Example#2335 - datefmt_get_pattern example
  • Example#2336 - OO example
  • Example#2337 - datefmt_get_timetype example
  • Example#2338 - OO example
  • Example#2339 - datefmt_get_timezone_id example
  • Example#2340 - OO example
  • Example#2341 - datefmt_is_lenient example
  • Example#2342 - OO example
  • Example#2343 - datefmt_localtime example
  • Example#2344 - OO example
  • Example#2345 - datefmt_parse example
  • Example#2346 - OO example
  • Example#2347 - datefmt_set_calendar example
  • Example#2348 - OO example
  • Example#2349 - datefmt_set_lenient example
  • Example#2350 - OO example
  • Example#2351 - datefmt_set_pattern example
  • Example#2352 - OO example
  • Example#2353 - datefmt_set_timezone_id example
  • Example#2354 - OO example
  • Example#2355 - resourcebundle_count example
  • Example#2356 - OO example
  • Example#2357 - resourcebundle_create example
  • Example#2358 - ResourceBundle::create example
  • Example#2359 - resourcebundle_get_error_code example
  • Example#2360 - OO example
  • Example#2361 - resourcebundle_get_error_message example
  • Example#2362 - OO example
  • Example#2363 - resourcebundle_get example
  • Example#2364 - OO example
  • Example#2365 - resourcebundle_locales example
  • Example#2366 - OO example
  • Example#2367 - Converting escaped UTF-16 code units
  • Example#2368 - grapheme_extract example
  • Example#2369 - grapheme_stripos example
  • Example#2370 - grapheme_stristr example
  • Example#2371 - grapheme_strlen example
  • Example#2372 - grapheme_strpos example
  • Example#2373 - grapheme_strripos example
  • Example#2374 - grapheme_strrpos example
  • Example#2375 - grapheme_strstr example
  • Example#2376 - grapheme_substr example
  • Example#2377 - idn_to_ascii example
  • Example#2378 - idn_to_utf8 example
  • Example#2379 - intl_error_name example
  • Example#2380 - intl_get_error_code example
  • Example#2381 - intl_get_error_message example
  • Example#2382 - intl_is_failure example
  • Example#2383 - php.ini setting examples
  • Example#2384 - php.ini setting for EUC-JP users
  • Example#2385 - php.ini setting for SJIS users
  • Example#2386 - Disable HTTP input conversion in php.ini
  • Example#2387 - php.ini setting example
  • Example#2388 - Script example
  • Example#2389 - mb_convert_case example
  • Example#2390 - mb_convert_case example with non-Latin UTF-8 text
  • Example#2391 - mb_convert_encoding example
  • Example#2392 - mb_convert_kana example
  • Example#2393 - mb_convert_variables example
  • Example#2394 - convmap example
  • Example#2395 - mb_detect_encoding example
  • Example#2396 - Useless detect order example
  • Example#2397 - mb_detect_order examples
  • Example#2398 - mb_encode_mimeheader example
  • Example#2399 - convmap example
  • Example#2400 - mb_encode_numericentity example
  • Example#2401 - mb_encoding_aliases example
  • Example#2402 - mb_internal_encoding example
  • Example#2403 - mb_list_encodings example
  • Example#2404 - mb_output_handler example
  • Example#2405 - mb_preferred_mime_name example
  • Example#2406 - mb_strimwidth example
  • Example#2407 - mb_strtolower example
  • Example#2408 - mb_strtolower example with non-Latin UTF-8 text
  • Example#2409 - mb_strtoupper example
  • Example#2410 - mb_strtoupper example with non-Latin UTF-8 text
  • Example#2411 - mb_substitute_character example
  • Example#2412 - mb_substr_count example
  • Example#2413 - pspell_add_to_personal
  • Example#2414 - pspell_check Example
  • Example#2415 - pspell_add_to_personal Example
  • Example#2416 - pspell_config_create
  • Example#2417 - pspell_config_ignore
  • Example#2418 - pspell_config_mode Example
  • Example#2419 - pspell_config_personal
  • Example#2420 - pspell_config_repl
  • Example#2421 - pspell_config_runtogether
  • Example#2422 - pspell_new_config
  • Example#2423 - pspell_new_personal
  • Example#2424 - pspell_new
  • Example#2425 - pspell_add_to_personal
  • Example#2426 - pspell_store_replacement
  • Example#2427 - pspell_suggest example
  • Example#2428 - Basic recode_file example
  • Example#2429 - Basic recode_string example
  • Example#2430 - Cairo Example
  • Example#2431 - cairo_create example
  • Example#2432 - cairo_font_face_get_type example
  • Example#2433 - cairo_font_face_status example
  • Example#2434 - cairo_font_options_create example
  • Example#2435 - cairo_font_options_equal example
  • Example#2436 - cairo_font_options_get_antialias example
  • Example#2437 - cairo_font_options_get_hint_metrics example
  • Example#2438 - cairo_font_options_get_hint_style example
  • Example#2439 - cairo_font_options_get_subpixel_order example
  • Example#2440 - cairo_font_options_hash example
  • Example#2441 - cairo_font_options_merge example
  • Example#2442 - cairo_font_options_set_antialias example
  • Example#2443 - cairo_font_options_set_hint_metrics example
  • Example#2444 - cairo_font_options_set_hint_style example
  • Example#2445 - cairo_font_options_set_subpixel_order example
  • Example#2446 - cairo_font_options_status example
  • Example#2447 - cairo_format_stride_for_width example
  • Example#2448 - cairo_image_surface_create_for_data example
  • Example#2449 - cairo_image_surface_create_from_png example
  • Example#2450 - cairo_image_surface_create example
  • Example#2451 - cairo_image_surface_get_data example
  • Example#2452 - cairo_image_surface_get_format example
  • Example#2453 - cairo_image_surface_get_height example
  • Example#2454 - cairo_image_surface_get_stride example
  • Example#2455 - cairo_image_surface_get_width example
  • Example#2456 - cairo_matrix_invert example
  • Example#2457 - cairo_matrix_multiply example
  • Example#2458 - cairo_matrix_rotate example
  • Example#2459 - cairo_matrix_transform_distance example
  • Example#2460 - cairo_matrix_transform_point example
  • Example#2461 - cairo_matrix_translate example
  • Example#2462 - cairo_pattern_add_color_stop_rgb example
  • Example#2463 - cairo_pattern_add_color_stop_rgba example
  • Example#2464 - cairo_pattern_create_for_surface example
  • Example#2465 - cairo_pattern_create_linear example
  • Example#2466 - cairo_pattern_create_radial example
  • Example#2467 - cairo_pattern_create_rgb example
  • Example#2468 - cairo_pattern_create_rgba example
  • Example#2469 - cairo_pattern_get_color_stop_count example
  • Example#2470 - cairo_pattern_get_color_stop_rgba example
  • Example#2471 - cairo_pattern_get_extend example
  • Example#2472 - cairo_pattern_get_filter example
  • Example#2473 - cairo_pattern_get_linear_points example
  • Example#2474 - cairo_pattern_get_matrix example
  • Example#2475 - cairo_pattern_get_radial_circles example
  • Example#2476 - cairo_pattern_get_rgba example
  • Example#2477 - cairo_pattern_get_surface example
  • Example#2478 - cairo_pattern_get_type example
  • Example#2479 - cairo_pattern_set_extend example
  • Example#2480 - cairo_pattern_set_filter example
  • Example#2481 - cairo_pattern_set_matrix example
  • Example#2482 - cairo_pattern_status example
  • Example#2483 - cairo_pdf_surface_create example
  • Example#2484 - cairo_pdf_surface_set_size example
  • Example#2485 - cairo_ps_get_levels example
  • Example#2486 - cairo_ps_level_to_string example
  • Example#2487 - cairo_ps_surface_create example
  • Example#2488 - cairo_ps_surface_dsc_begin_page_setup example
  • Example#2489 - cairo_ps_surface_dsc_begin_setup example
  • Example#2490 - cairo_ps_surface_dsc_comment example
  • Example#2491 - cairo_ps_surface_get_eps example
  • Example#2492 - cairo_ps_surface_restrict_to_level example
  • Example#2493 - cairo_ps_surface_set_eps example
  • Example#2494 - cairo_ps_surface_set_size example
  • Example#2495 - cairo_scaled_font_create example
  • Example#2496 - cairo_scaled_font_extents example
  • Example#2497 - cairo_scaled_font_get_ctm example
  • Example#2498 - cairo_scaled_font_get_font_face example
  • Example#2499 - cairo_scaled_font_get_font_matrix example
  • Example#2500 - cairo_scaled_font_get_font_options example
  • Example#2501 - cairo_scaled_font_get_scale_matrix example
  • Example#2502 - cairo_scaled_font_get_type example
  • Example#2503 - cairo_scaled_font_glyph_extents example
  • Example#2504 - cairo_scaled_font_status example
  • Example#2505 - cairo_scaled_font_text_extents example
  • Example#2506 - cairo_surface_copy_page example
  • Example#2507 - cairo_surface_create_similar example
  • Example#2508 - cairo_surface_finish example
  • Example#2509 - cairo_surface_flush example
  • Example#2510 - cairo_surface_get_content example
  • Example#2511 - cairo_surface_get_device_offset example
  • Example#2512 - cairo_surface_get_font_options example
  • Example#2513 - cairo_surface_get_type example
  • Example#2514 - cairo_surface_mark_dirty_rectangle example
  • Example#2515 - cairo_surface_mark_dirty example
  • Example#2516 - cairo_surface_set_device_offset example
  • Example#2517 - cairo_surface_set_fallback_resolution example
  • Example#2518 - cairo_surface_show_page example
  • Example#2519 - cairo_surface_status example
  • Example#2520 - cairo_surface_write_to_png example
  • Example#2521 - cairo_svg_surface_create example
  • Example#2522 - cairo_svg_surface_restrict_to_version example
  • Example#2523 - cairo_svg_version_to_string example
  • Example#2524 - Styl obiektowy
  • Example#2525 - Styl proceduralny
  • Example#2526 - Styl obiektowy
  • Example#2527 - Styl proceduralny
  • Example#2528 - Styl obiektowy
  • Example#2529 - Styl proceduralny
  • Example#2530 - Styl obiektowy
  • Example#2531 - Styl proceduralny
  • Example#2532 - Styl obiektowy
  • Example#2533 - Styl proceduralny
  • Example#2534 - Styl obiektowy
  • Example#2535 - Styl proceduralny
  • Example#2536 - Styl obiektowy
  • Example#2537 - Styl proceduralny
  • Example#2538 - Styl obiektowy
  • Example#2539 - Styl proceduralny
  • Example#2540 - Styl obiektowy
  • Example#2541 - Styl proceduralny
  • Example#2542 - Styl obiektowy
  • Example#2543 - Styl proceduralny
  • Example#2544 - Styl obiektowy
  • Example#2545 - Styl proceduralny
  • Example#2546 - Styl obiektowy
  • Example#2547 - Styl proceduralny
  • Example#2548 - Styl obiektowy
  • Example#2549 - Styl proceduralny
  • Example#2550 - CairoContext::__construct example
  • Example#2551 - Styl obiektowy
  • Example#2552 - Styl proceduralny
  • Example#2553 - Styl obiektowy
  • Example#2554 - Styl proceduralny
  • Example#2555 - Styl obiektowy
  • Example#2556 - Styl proceduralny
  • Example#2557 - Styl obiektowy
  • Example#2558 - Styl proceduralny
  • Example#2559 - Styl obiektowy
  • Example#2560 - Styl proceduralny
  • Example#2561 - Styl obiektowy
  • Example#2562 - Styl proceduralny
  • Example#2563 - Styl obiektowy
  • Example#2564 - Styl proceduralny
  • Example#2565 - Styl obiektowy
  • Example#2566 - Styl proceduralny
  • Example#2567 - Styl obiektowy
  • Example#2568 - Styl proceduralny
  • Example#2569 - Styl obiektowy
  • Example#2570 - Styl proceduralny
  • Example#2571 - Styl obiektowy
  • Example#2572 - Styl proceduralny
  • Example#2573 - Styl obiektowy
  • Example#2574 - Styl proceduralny
  • Example#2575 - Styl obiektowy
  • Example#2576 - Styl proceduralny
  • Example#2577 - Styl obiektowy
  • Example#2578 - Styl proceduralny
  • Example#2579 - Styl obiektowy
  • Example#2580 - Styl proceduralny
  • Example#2581 - Styl obiektowy
  • Example#2582 - Styl proceduralny
  • Example#2583 - Styl obiektowy
  • Example#2584 - Styl proceduralny
  • Example#2585 - Styl obiektowy
  • Example#2586 - Styl proceduralny
  • Example#2587 - Styl obiektowy
  • Example#2588 - Styl proceduralny
  • Example#2589 - Styl obiektowy
  • Example#2590 - Styl proceduralny
  • Example#2591 - Styl obiektowy
  • Example#2592 - Styl proceduralny
  • Example#2593 - Styl obiektowy
  • Example#2594 - Styl proceduralny
  • Example#2595 - Styl obiektowy
  • Example#2596 - Styl proceduralny
  • Example#2597 - Styl obiektowy
  • Example#2598 - Styl proceduralny
  • Example#2599 - Styl obiektowy
  • Example#2600 - Styl proceduralny
  • Example#2601 - Styl obiektowy
  • Example#2602 - Styl proceduralny
  • Example#2603 - Styl obiektowy
  • Example#2604 - Styl proceduralny
  • Example#2605 - Styl obiektowy
  • Example#2606 - Styl proceduralny
  • Example#2607 - Styl obiektowy
  • Example#2608 - Styl proceduralny
  • Example#2609 - Styl obiektowy
  • Example#2610 - Styl proceduralny
  • Example#2611 - Styl obiektowy
  • Example#2612 - Styl proceduralny
  • Example#2613 - Styl obiektowy
  • Example#2614 - Styl proceduralny
  • Example#2615 - Styl obiektowy
  • Example#2616 - Styl proceduralny
  • Example#2617 - Styl obiektowy
  • Example#2618 - Styl proceduralny
  • Example#2619 - Styl obiektowy
  • Example#2620 - Styl proceduralny
  • Example#2621 - Styl obiektowy
  • Example#2622 - Styl proceduralny
  • Example#2623 - Styl obiektowy
  • Example#2624 - Styl proceduralny
  • Example#2625 - Styl obiektowy
  • Example#2626 - Styl proceduralny
  • Example#2627 - Styl obiektowy
  • Example#2628 - Styl proceduralny
  • Example#2629 - Styl obiektowy
  • Example#2630 - Styl proceduralny
  • Example#2631 - Styl obiektowy
  • Example#2632 - Styl proceduralny
  • Example#2633 - Styl obiektowy
  • Example#2634 - Styl proceduralny
  • Example#2635 - Styl obiektowy
  • Example#2636 - Styl proceduralny
  • Example#2637 - Styl obiektowy
  • Example#2638 - Styl proceduralny
  • Example#2639 - Styl obiektowy
  • Example#2640 - Styl proceduralny
  • Example#2641 - Styl obiektowy
  • Example#2642 - Styl proceduralny
  • Example#2643 - Styl obiektowy
  • Example#2644 - Styl proceduralny
  • Example#2645 - Styl obiektowy
  • Example#2646 - Styl proceduralny
  • Example#2647 - Styl obiektowy
  • Example#2648 - Styl proceduralny
  • Example#2649 - Styl obiektowy
  • Example#2650 - Styl proceduralny
  • Example#2651 - Styl obiektowy
  • Example#2652 - Styl proceduralny
  • Example#2653 - Styl obiektowy
  • Example#2654 - Styl proceduralny
  • Example#2655 - Styl obiektowy
  • Example#2656 - Styl proceduralny
  • Example#2657 - Styl obiektowy
  • Example#2658 - Styl proceduralny
  • Example#2659 - Styl obiektowy
  • Example#2660 - Styl proceduralny
  • Example#2661 - Styl obiektowy
  • Example#2662 - Styl proceduralny
  • Example#2663 - Styl obiektowy
  • Example#2664 - Styl proceduralny
  • Example#2665 - Styl obiektowy
  • Example#2666 - Styl proceduralny
  • Example#2667 - Styl obiektowy
  • Example#2668 - Styl proceduralny
  • Example#2669 - Styl obiektowy
  • Example#2670 - Styl proceduralny
  • Example#2671 - Styl obiektowy
  • Example#2672 - Styl proceduralny
  • Example#2673 - Styl obiektowy
  • Example#2674 - Styl proceduralny
  • Example#2675 - Styl obiektowy
  • Example#2676 - Styl proceduralny
  • Example#2677 - Styl obiektowy
  • Example#2678 - Styl proceduralny
  • Example#2679 - Styl obiektowy
  • Example#2680 - Styl proceduralny
  • Example#2681 - Styl obiektowy
  • Example#2682 - Styl proceduralny
  • Example#2683 - Styl obiektowy
  • Example#2684 - Styl proceduralny
  • Example#2685 - Styl obiektowy
  • Example#2686 - Styl proceduralny
  • Example#2687 - Styl obiektowy
  • Example#2688 - Styl proceduralny
  • Example#2689 - Styl obiektowy
  • Example#2690 - Styl proceduralny
  • Example#2691 - Styl obiektowy
  • Example#2692 - Styl proceduralny
  • Example#2693 - Styl obiektowy
  • Example#2694 - Styl proceduralny
  • Example#2695 - Styl obiektowy
  • Example#2696 - Styl proceduralny
  • Example#2697 - Styl obiektowy
  • Example#2698 - Styl proceduralny
  • Example#2699 - Styl obiektowy
  • Example#2700 - Styl proceduralny
  • Example#2701 - Styl obiektowy
  • Example#2702 - Styl proceduralny
  • Example#2703 - Styl obiektowy
  • Example#2704 - Styl proceduralny
  • Example#2705 - Styl obiektowy
  • Example#2706 - Styl proceduralny
  • Example#2707 - Styl obiektowy
  • Example#2708 - Styl proceduralny
  • Example#2709 - Styl obiektowy
  • Example#2710 - Styl proceduralny
  • Example#2711 - Styl obiektowy
  • Example#2712 - Styl proceduralny
  • Example#2713 - Styl obiektowy
  • Example#2714 - Styl proceduralny
  • Example#2715 - Styl obiektowy
  • Example#2716 - Styl proceduralny
  • Example#2717 - Styl obiektowy
  • Example#2718 - Styl proceduralny
  • Example#2719 - Styl obiektowy
  • Example#2720 - Styl proceduralny
  • Example#2721 - Styl obiektowy
  • Example#2722 - Styl proceduralny
  • Example#2723 - Styl obiektowy
  • Example#2724 - Styl proceduralny
  • Example#2725 - CairoSurface::createSimilar example
  • Example#2726 - CairoSurface::finish example
  • Example#2727 - CairoSurface::flush example
  • Example#2728 - CairoSurface::getContent example
  • Example#2729 - CairoSurface::getDeviceOffset example
  • Example#2730 - Styl obiektowy
  • Example#2731 - Styl proceduralny
  • Example#2732 - CairoSurface::getType example
  • Example#2733 - CairoSurface::markDirty example
  • Example#2734 - CairoSurface::markDirtyRectangle example
  • Example#2735 - CairoSurface::setDeviceOffset example
  • Example#2736 - CairoSurface::setFallbackResolution example
  • Example#2737 - Styl obiektowy
  • Example#2738 - Styl proceduralny
  • Example#2739 - Styl obiektowy
  • Example#2740 - Styl proceduralny
  • Example#2741 - CairoSurface::writeToPng example
  • Example#2742 - CairoSvgSurface::__construct example
  • Example#2743 - CairoSvgSurface::getVersions example
  • Example#2744 - Styl proceduralny
  • Example#2745 - CairoSvgSurface::restrictToVersion example
  • Example#2746 - CairoSvgSurface::versionToString example
  • Example#2747 - CairoImageSurface::__construct example
  • Example#2748 - CairoImageSurface::createForData example
  • Example#2749 - CairoImageSurface::createFromPng example
  • Example#2750 - CairoImageSurface::getData example
  • Example#2751 - CairoImageSurface::getFormat example
  • Example#2752 - CairoImageSurface::getHeight example
  • Example#2753 - CairoImageSurface::getStride example
  • Example#2754 - CairoImageSurface::getWidth example
  • Example#2755 - CairoPdfSurface::__construct example
  • Example#2756 - CairoPdfSurface::setSize example
  • Example#2757 - CairoPsSurface::__construct example
  • Example#2758 - CairoPsSurface::dscBeginPageSetup example
  • Example#2759 - CairoPsSurface::dscBeginSetup example
  • Example#2760 - CairoPsSurface::dscComment example
  • Example#2761 - CairoPsSurface::getEps example
  • Example#2762 - CairoPsSurface::getLevels example
  • Example#2763 - CairoPsSurface::levelToString example
  • Example#2764 - CairoPsSurface::restrictToLevel example
  • Example#2765 - CairoPsSurface::setEps example
  • Example#2766 - CairoPsSurface::setSize example
  • Example#2767 - CairoFontFace::__construct example
  • Example#2768 - CairoFontFace::getType example
  • Example#2769 - Styl obiektowy
  • Example#2770 - Styl proceduralny
  • Example#2771 - CairoFontOptions::__construct example
  • Example#2772 - CairoFontOptions::equal example
  • Example#2773 - Styl obiektowy
  • Example#2774 - Styl proceduralny
  • Example#2775 - CairoFontOptions::getHintMetrics example
  • Example#2776 - CairoFontOptions::getHintStyle example
  • Example#2777 - CairoFontOptions::getSubpixelOrder example
  • Example#2778 - CairoFontOptions::hash example
  • Example#2779 - CairoFontOptions::merge example
  • Example#2780 - Styl obiektowy
  • Example#2781 - Styl proceduralny
  • Example#2782 - CairoFontOptions::setHintMetrics example
  • Example#2783 - CairoFontOptions::setHintStyle example
  • Example#2784 - CairoFontOptions::setSubpixelOrder example
  • Example#2785 - Styl obiektowy
  • Example#2786 - Styl proceduralny
  • Example#2787 - CairoScaledFont::__construct example
  • Example#2788 - CairoScaledFont::extents example
  • Example#2789 - CairoScaledFont::getCtm example
  • Example#2790 - Styl obiektowy
  • Example#2791 - Styl proceduralny
  • Example#2792 - Styl obiektowy
  • Example#2793 - Styl proceduralny
  • Example#2794 - Styl obiektowy
  • Example#2795 - Styl proceduralny
  • Example#2796 - CairoScaledFont::getScaleMatrix example
  • Example#2797 - CairoScaledFont::getType example
  • Example#2798 - CairoScaledFont::glyphExtents example
  • Example#2799 - Styl obiektowy
  • Example#2800 - Styl proceduralny
  • Example#2801 - Styl obiektowy
  • Example#2802 - Styl proceduralny
  • Example#2803 - CairoPattern::__construct example
  • Example#2804 - Styl obiektowy
  • Example#2805 - Styl proceduralny
  • Example#2806 - CairoPattern::getType example
  • Example#2807 - Styl obiektowy
  • Example#2808 - Styl proceduralny
  • Example#2809 - Styl obiektowy
  • Example#2810 - Styl proceduralny
  • Example#2811 - CairoGradientPattern::addColorStopRgb example
  • Example#2812 - CairoGradientPattern::addColorStopRgba example
  • Example#2813 - CairoGradientPattern::getColorStopCount example
  • Example#2814 - CairoGradientPattern::getColorStopRgba example
  • Example#2815 - CairoGradientPattern::getExtend example
  • Example#2816 - CairoGradientPattern::setExtend example
  • Example#2817 - CairoSolidPattern::__construct example
  • Example#2818 - CairoSolidPattern::getRgba example
  • Example#2819 - CairoSurfacePattern::__construct example
  • Example#2820 - CairoSurfacePattern::getExtend example
  • Example#2821 - CairoSurfacePattern::getFilter example
  • Example#2822 - CairoSurfacePattern::getSurface example
  • Example#2823 - CairoSurfacePattern::setExtend example
  • Example#2824 - CairoSurfacePattern::setFilter example
  • Example#2825 - CairoLinearGradient::__construct example
  • Example#2826 - CairoLinearGradient::getPoints example
  • Example#2827 - CairoRadialGradient::__construct example
  • Example#2828 - CairoRadialGradient::getCircles example
  • Example#2829 - CairoFormat::strideForWidth example
  • Example#2830 - Styl obiektowy
  • Example#2831 - Styl proceduralny
  • Example#2832 - Styl obiektowy
  • Example#2833 - Styl proceduralny
  • Example#2834 - Styl obiektowy
  • Example#2835 - Styl proceduralny
  • Example#2836 - Styl obiektowy
  • Example#2837 - Styl proceduralny
  • Example#2838 - Styl obiektowy
  • Example#2839 - Styl proceduralny
  • Example#2840 - CairoMatrix::invert example
  • Example#2841 - CairoMatrix::multiply example
  • Example#2842 - Styl obiektowy
  • Example#2843 - Styl proceduralny
  • Example#2844 - Styl obiektowy
  • Example#2845 - Styl proceduralny
  • Example#2846 - CairoMatrix::transformDistance example
  • Example#2847 - CairoMatrix::transformPoint example
  • Example#2848 - Styl obiektowy
  • Example#2849 - Styl proceduralny
  • Example#2850 - exif_imagetype example
  • Example#2851 - exif_read_data example
  • Example#2852 - exif_tagname example
  • Example#2853 - exif_thumbnail example
  • Example#2854 - PNG creation with PHP
  • Example#2855 - Adding watermarks to images using alpha channels
  • Example#2856 - Using imagecopymerge to create a translucent watermark
  • Example#2857 - Using gd_info
  • Example#2858 - getimagesize and MIME types
  • Example#2859 - getimagesize example
  • Example#2860 - getimagesize (URL)
  • Example#2861 - getimagesize() returning IPTC
  • Example#2862 - image_type_to_extension example
  • Example#2863 - image_type_to_mime_type example
  • Example#2864 - image2wbmp example
  • Example#2865 - imagealphablending usage example
  • Example#2866 - A comparison of two lines, one with anti-aliasing switched on
  • Example#2867 - Drawing a circle with imagearc
  • Example#2868 - imagechar example
  • Example#2869 - imagecharup example
  • Example#2870 - imagecolorallocate example
  • Example#2871 - Example of using imagecolorallocatealpha
  • Example#2872 - Access distinct RGB values
  • Example#2873 - Human-readable RGB values using imagecolorsforindex
  • Example#2874 - Search for a set of colors in an image
  • Example#2875 - Search for a set of colors in an image
  • Example#2876 - Example of using imagecolorclosesthwb
  • Example#2877 - Using imagecolordeallocate
  • Example#2878 - Get colors from the GD logo
  • Example#2879 - Get colors from the GD logo
  • Example#2880 - imagecolormatch example
  • Example#2881 - Using imagecoloresolve to get colors from an image
  • Example#2882 - Using imagecoloresolvealpha to get colors from an image
  • Example#2883 - imagecolorset example
  • Example#2884 - imagecolorsforindex example
  • Example#2885 - Getting total number of colors in an image using imagecolorstotal
  • Example#2886 - imagecolortransparent example
  • Example#2887 - Embossing the PHP.net logo
  • Example#2888 - Gaussian blur
  • Example#2889 - Cropping the PHP.net logo
  • Example#2890 - Merging two copies of the PHP.net logo with 75% transparency
  • Example#2891 - imagecopymergegray usage
  • Example#2892 - Simple example
  • Example#2893 - Resampling an image proportionally
  • Example#2894 - Resizing an image
  • Example#2895 - Creating a new GD image stream and outputting an image.
  • Example#2896 - imagecreatefromgd2 example
  • Example#2897 - imagecreatefromgd2part example
  • Example#2898 - imagecreatefromgd example
  • Example#2899 - Example to handle an error during loading of a GIF
  • Example#2900 - Example to handle an error during loading of a JPEG
  • Example#2901 - Example to handle an error during loading of a PNG
  • Example#2902 - imagecreatefromstring example
  • Example#2903 - Example to handle an error during loading of a WBMP
  • Example#2904 - Convert an XBM image to a png image using imagecreatefromxbm
  • Example#2905 - Creating an image instance using imagecreatefromxpm
  • Example#2906 - Creating a new GD image stream and outputting an image.
  • Example#2907 - imagedashedline example
  • Example#2908 - Alternative to imagedashedline
  • Example#2909 - Using imagedestroy example
  • Example#2910 - imageellipse example
  • Example#2911 - imagefill example
  • Example#2912 - Creating a 3D looking pie
  • Example#2913 - imagefilledellipse example
  • Example#2914 - imagefilledpolygon example
  • Example#2915 - imagefilledrectangle usage
  • Example#2916 - Filling an ellipse with a color
  • Example#2917 - imagefilter grayscale example
  • Example#2918 - imagefilter brightness example
  • Example#2919 - imagefilter colorize example
  • Example#2920 - imagefilter negate example
  • Example#2921 - imagefilter pixelate example
  • Example#2922 - Using imagefontheight on built-in fonts
  • Example#2923 - Using imagefontheight together with imageloadfont
  • Example#2924 - Using imagefontwidth on built-in fonts
  • Example#2925 - Using imagefontwidth together with imageloadfont
  • Example#2926 - imageftbbox example
  • Example#2927 - imagefttext example
  • Example#2928 - imagegammacorrect usage
  • Example#2929 - Outputting a GD2 image
  • Example#2930 - Saving a GD2 image
  • Example#2931 - Outputting a GD image
  • Example#2932 - Saving a GD image
  • Example#2933 - Outputting an image using imagegif
  • Example#2934 - Converting a PNG image to GIF using imagegif
  • Example#2935 - imagegrabscreen example
  • Example#2936 - imagegrabwindow example
  • Example#2937 - Turn on interlacing using imageinterlace
  • Example#2938 - Simple detection of true color image instances using imageistruecolor
  • Example#2939 - Outputting a JPEG image
  • Example#2940 - Saving a JPEG image
  • Example#2941 - Outputting the image at 75% quality
  • Example#2942 - imagelayereffect example
  • Example#2943 - Drawing a thick line
  • Example#2944 - imageloadfont usage example
  • Example#2945 - imagepalettecopy example
  • Example#2946 - imagepolygon example
  • Example#2947 - imagepsbbox usage
  • Example#2948 - imagepsencodefont example
  • Example#2949 - imagepsextendfont example
  • Example#2950 - imagepsfreefont example
  • Example#2951 - imagepsloadfont example
  • Example#2952 - imagepsslantfont example
  • Example#2953 - imagepstext usage
  • Example#2954 - Simple imagerectangle example
  • Example#2955 - Rotate an image 180 degrees
  • Example#2956 - imagesavealpha example
  • Example#2957 - imagesetbrush example
  • Example#2958 - imagesetpixel example
  • Example#2959 - imagesetstyle example
  • Example#2960 - imagesetthickness example
  • Example#2961 - imagesettile example
  • Example#2962 - imagestring example
  • Example#2963 - imagestringup example
  • Example#2964 - Using imagesx
  • Example#2965 - Using imagesy
  • Example#2966 - Converting a true color image to a palette-based image
  • Example#2967 - imagettfbbox example
  • Example#2968 - imagettftext example
  • Example#2969 - Checking for PNG support
  • Example#2970 - Outputting a WBMP image
  • Example#2971 - Saving the WBMP image
  • Example#2972 - Outputting the image with a different foreground
  • Example#2973 - Saving an XBM file
  • Example#2974 - Saving an XBM file with a different foreground color
  • Example#2975 - Embedding IPTC data into a JPEG
  • Example#2976 - iptcparse() used together with getimagesize
  • Example#2977 - jpeg2wbmp example
  • Example#2978 - png2wbmp example
  • Example#2979 - Gmagick Example
  • Example#2980 - Gmagick::despeckleimage example
  • Example#2981 - Creating a thumbnail in Imagick
  • Example#2982 - Make a thumbnail of all JPG files in a directory
  • Example#2983 - Creating a reflection of an image
  • Example#2984 - Filling text with gradient
  • Example#2985 - Read in GIF image and resize all frames
  • Example#2986 - Using Imagick::adaptiveBlurImage:
  • Example#2987 - Using Imagick::adaptiveResizeImage
  • Example#2988 - A Imagick::adaptiveSharpenImage example
  • Example#2989 - Using Imagick::annotateImage:
  • Example#2990 - Imagick::appendImages example
  • Example#2991 - Using Imagick::blurImage:
  • Example#2992 - Using Imagick::chopImage:
  • Example#2993 - Using Imagick::clutImage:
  • Example#2994 - Using Imagick::commentImage:
  • Example#2995 - Using Imagick::compareImageLayers
  • Example#2996 - Using Imagick::compareImages:
  • Example#2997 - Using Imagick::distortImage:
  • Example#2998 - Using Imagick::evaluateImage
  • Example#2999 - Using Imagick::exportImagePixels
  • Example#3000 - Imagick::floodfillPaintImage example
  • Example#3001 - Using Imagick::getImageLength:
  • Example#3002 - Using Imagick::getImageProperties:
  • Example#3003 - Using Imagick::getImageProperty:
  • Example#3004 - Using Imagick::getIteratorIndex:
  • Example#3005 - Imagick::importImagePixels example
  • Example#3006 - Using Imagick::newImage:
  • Example#3007 - Using Imagick::optimizeImageLayers
  • Example#3008 - Using Imagick::pingImageBlob
  • Example#3009 - Using Imagick::pingImageFile
  • Example#3010 - A Imagick::polaroidImage example
  • Example#3011 - Using Imagick::queryFontMetrics:
  • Example#3012 - Using Imagick::roundCorners:
  • Example#3013 - A Imagick::setFont example
  • Example#3014 - A Imagick::setImage example
  • Example#3015 - A Imagick::setImageOpacity example
  • Example#3016 - Using Imagick::setImageProperty:
  • Example#3017 - Using Imagick::setIteratorIndex:
  • Example#3018 - A Imagick::setPointSize example
  • Example#3019 - Using Imagick::transformImage:
  • Example#3020 - Using Imagick::trimImage:
  • Example#3021 - imap_append example
  • Example#3022 - imap_check example
  • Example#3023 - imap_createmailbox example
  • Example#3024 - imap_delete example
  • Example#3025 - imap_fetch_overview example
  • Example#3026 - imap_gc example
  • Example#3027 - imap_get_quota example
  • Example#3028 - imap_get_quota 4.3 or greater example
  • Example#3029 - imap_get_quotaroot example
  • Example#3030 - imap_getacl example
  • Example#3031 - imap_getmailboxes example
  • Example#3032 - imap_list example
  • Example#3033 - imap_mail_compose example
  • Example#3034 - imap_mailboxmsginfo example
  • Example#3035 - imap_mime_header_decode example
  • Example#3036 - Different use of imap_open
  • Example#3037 - imap_open example
  • Example#3038 - imap_ping Example
  • Example#3039 - imap_reopen example
  • Example#3040 - imap_rfc822_parse_adrlist example
  • Example#3041 - imap_rfc822_write_address example
  • Example#3042 - imap_search example
  • Example#3043 - imap_set_quota example
  • Example#3044 - imap_setflag_full example
  • Example#3045 - imap_status example
  • Example#3046 - imap_thread Example
  • Example#3047 - imap_timeout example
  • Example#3048 - Obliczenie wartości hash i dodanie nowego użytkownika
  • Example#3049 - Wysłanie e-maila.
  • Example#3050 - Wysłanie e-maila z dodatkowymi nagłówkami.
  • Example#3051 - Wysłanie e-maila z dodatkowym parametrem wiersza poleceń.
  • Example#3052 - Wysłanie e-maila w formacie HTML
  • Example#3053 - mailparse_determine_best_xfer_encoding example
  • Example#3054 - mailparse_rfc822_parse_addresses example
  • Example#3055 - mailparse_stream_encode example
  • Example#3056 - mailparse_uudecode_all example
  • Example#3057 - bcadd przykład
  • Example#3058 - bccomp przykład
  • Example#3059 - bcdiv przykład
  • Example#3060 - bcmod przykład
  • Example#3061 - bcmul przykład
  • Example#3062 - bcpow przykład
  • Example#3063 - bcscale przykład
  • Example#3064 - bcsqrt przykład
  • Example#3065 - bcsub przykład
  • Example#3066 - Factorial function using GMP
  • Example#3067 - gmp_abs example
  • Example#3068 - gmp_add example
  • Example#3069 - gmp_and example
  • Example#3070 - gmp_clrbit example
  • Example#3071 - gmp_cmp example
  • Example#3072 - gmp_com example
  • Example#3073 - gmp_div_q example
  • Example#3074 - Division of GMP numbers
  • Example#3075 - gmp_div_r example
  • Example#3076 - gmp_divexact example
  • Example#3077 - gmp_fact example
  • Example#3078 - gmp_gcd example
  • Example#3079 - Solving a linear Diophantine equation
  • Example#3080 - gmp_hamdist example
  • Example#3081 - Creating GMP number
  • Example#3082 - gmp_intval example
  • Example#3083 - gmp_invert example
  • Example#3084 - gmp_jacobi example
  • Example#3085 - gmp_legendre example
  • Example#3086 - gmp_mod example
  • Example#3087 - gmp_mul example
  • Example#3088 - gmp_neg example
  • Example#3089 - gmp_nextprime example
  • Example#3090 - gmp_or example
  • Example#3091 - gmp_perfect_square example
  • Example#3092 - gmp_popcount example
  • Example#3093 - gmp_pow example
  • Example#3094 - gmp_powm example
  • Example#3095 - gmp_prob_prime example
  • Example#3096 - gmp_random example
  • Example#3097 - gmp_scan0 example
  • Example#3098 - gmp_scan1 example
  • Example#3099 - gmp_setbit example
  • Example#3100 - gmp_sign example
  • Example#3101 - gmp_sqrt example
  • Example#3102 - gmp_sqrtrem example
  • Example#3103 - Converting a GMP number to a string
  • Example#3104 - gmp_sub example
  • Example#3105 - gmp_testbit example
  • Example#3106 - gmp_xor example
  • Example#3107 - Przykład abs
  • Example#3108 - base_convert przykład
  • Example#3109 - bindec przykład
  • Example#3110 - przykład ceil
  • Example#3111 - cos przykład
  • Example#3112 - decbin przykład
  • Example#3113 - dechex przykład
  • Example#3114 - decoct przykład
  • Example#3115 - deg2rad przykład
  • Example#3116 - Przykład użycia exp
  • Example#3117 - przykład zastosowania floor
  • Example#3118 - Using fmod
  • Example#3119 - Przykład zastosowania hexdec
  • Example#3120 - Przykłady użycia max
  • Example#3121 - Przykłady użycia min
  • Example#3122 - Przykład mt_rand
  • Example#3123 - mt_srand przykład
  • Example#3124 - octdec przykład
  • Example#3125 - pi przykład
  • Example#3126 - Parę przykładów z pow
  • Example#3127 - Przykład użycia rad2deg
  • Example#3128 - Przykład użycia rand
  • Example#3129 - Przykłady użycia round
  • Example#3130 - Przykład użycia sin
  • Example#3131 - Przykład użycia sqrt
  • Example#3132 - Przykład użycia srand
  • Example#3133 - Przykład użycia tan
  • Example#3134 - Evaluating a FDF document
  • Example#3135 - Adding JavaScript code to a FDF
  • Example#3136 - Populating a PDF document
  • Example#3137 - Storing an uploaded file
  • Example#3138 - Detecting all fieldnames in a FDF
  • Example#3139 - Accessing the form data
  • Example#3140 - Accessing the form data
  • Example#3141 - Retrieving FDF as a string
  • Example#3142 - Passing FDF data to a second form
  • Example#3143 - gnupg clearsign example (procedural)
  • Example#3144 - gnupg clearsign example (OO)
  • Example#3145 - keylistiterator
  • Example#3146 - Procedural gnupg_adddecryptkey example
  • Example#3147 - OO gnupg_adddecryptkey example
  • Example#3148 - Procedural gnupg_addencryptkey example
  • Example#3149 - OO gnupg_addencryptkey example
  • Example#3150 - Procedural gnupg_addsignkey example
  • Example#3151 - OO gnupg_addsignkey example
  • Example#3152 - Procedural gnupg_cleardecryptkeys example
  • Example#3153 - OO gnupg_cleardecryptkeys example
  • Example#3154 - Procedural gnupg_clearencryptkeys example
  • Example#3155 - OO gnupg_clearencryptkeys example
  • Example#3156 - Procedural gnupg_clearsignkeys example
  • Example#3157 - OO gnupg_clearsignkeys example
  • Example#3158 - Procedural gnupg_decrypt example
  • Example#3159 - OO gnupg_encrypt example
  • Example#3160 - Procedural gnupg_decryptverify example
  • Example#3161 - OO gnupg_decryptverify example
  • Example#3162 - Procedural gnupg_encrypt example
  • Example#3163 - OO gnupg_encrypt example
  • Example#3164 - Procedural gnupg_encryptsign example
  • Example#3165 - OO gnupg_encryptsign example
  • Example#3166 - Procedural gnupg_export example
  • Example#3167 - OO gnupg_export example
  • Example#3168 - Procedural gnupg_geterror example
  • Example#3169 - OO gnupg_geterror example
  • Example#3170 - Procedural gnupg_getprotocol example
  • Example#3171 - OO gnupg_getprotocol example
  • Example#3172 - Procedural gnupg_import example
  • Example#3173 - OO gnupg_import example
  • Example#3174 - Procedural gnupg_init example
  • Example#3175 - OO gnupg initializer example
  • Example#3176 - Procedural gnupg_keyinfo example
  • Example#3177 - OO gnupg_keyinfo example
  • Example#3178 - Procedural gnupg_setarmor example
  • Example#3179 - OO gnupg_setarmor example
  • Example#3180 - Procedural gnupg_seterrormode example
  • Example#3181 - OO gnupg_seterrormode example
  • Example#3182 - Procedural gnupg_setsignmode example
  • Example#3183 - OO gnupg_setsignmode example
  • Example#3184 - Procedural gnupg_sign example
  • Example#3185 - OO gnupg_sign example
  • Example#3186 - Procedural gnupg_verify example
  • Example#3187 - OO gnupg_verify example
  • Example#3188 - Fancy "Hello world"
  • Example#3189 - swfaction example
  • Example#3190 - swfaction example
  • Example#3191 - swfaction example
  • Example#3192 - swfsprite example
  • Example#3193 - ming_useswfversion example
  • Example#3194 - Importing a DBL file
  • Example#3195 - Using an alpha mask
  • Example#3196 - Usual interactions with buttons
  • Example#3197 - Drag example
  • Example#3198 - swfdisplayitem::multcolor example
  • Example#3199 - swfdisplayitem::rotateto example
  • Example#3200 - swfdisplayitem::setname example
  • Example#3201 - swfgradient example
  • Example#3202 - swfmorph example
  • Example#3203 - Displaying your $movie in a browser
  • Example#3204 - Streaming example
  • Example#3205 - SWFShape::addFill example
  • Example#3206 - swfshape example
  • Example#3207 - swfshape::setline example
  • Example#3208 - swftext example
  • Example#3209 - Hello World example from PDFlib distribution for PHP 4
  • Example#3210 - Hello World example from PDFlib distribution for PHP 5
  • Example#3211 - Creating and using a pattern
  • Example#3212 - Creating and using a template
  • Example#3213 - Hyphennate a text
  • Example#3214 - Drawing a rectangle
  • Example#3215 - Creating and using a spot color
  • Example#3216 - Rotation of the coordinate system
  • Example#3217 - Placing text at a given position
  • Example#3218 - Drawing a dashed line
  • Example#3219 - Translation of the coordinate system
  • Example#3220 - Basic RPMReader Example
  • Example#3221 - rpm_close example
  • Example#3222 - rpm_get_tag example
  • Example#3223 - rpm_is_valid example
  • Example#3224 - rpm_open example
  • Example#3225 - rpm_version example
  • Example#3226 - SWF example
  • Example#3227 - swf_addbuttonrecord example
  • Example#3228 - Creating a simple flash file based on user input and outputting it and saving it in a database
  • Example#3229 - Horizontal text example
  • Example#3230 - A simple 3D-rotation around a text
  • Example#3231 - Incorrect requests
  • Example#3232 - Calling request from a request callback
  • Example#3233 - Calling request from a request callback
  • Example#3234 - Using eio with libevent
  • Example#3235 - Cancelling a request
  • Example#3236 - Calling eio_chmod
  • Example#3237 - Making a custom request
  • Example#3238 - Grouping requests
  • Example#3239 - Using eio with libevent
  • Example#3240 - eio_cancel example
  • Example#3241 - eio_custom example
  • Example#3242 - eio_event_loop example
  • Example#3243 - eio_lstat example
  • Example#3244 - Using eio with libevent
  • Example#3245 - Grouping requests
  • Example#3246 - eio_grp example
  • Example#3247 - eio_link example
  • Example#3248 - eio_lstat example
  • Example#3249 - eio_mkdir example
  • Example#3250 - eio_mknod example
  • Example#3251 - eio_nreqs example
  • Example#3252 - eio_open example
  • Example#3253 - eio_poll example
  • Example#3254 - eio_read example
  • Example#3255 - eio_readdir example
  • Example#3256 - eio_readlink example
  • Example#3257 - eio_realpath example
  • Example#3258 - eio_rename example
  • Example#3259 - eio_rmdir example
  • Example#3260 - eio_stat example
  • Example#3261 - eio_statvfs example
  • Example#3262 - eio_symlink example
  • Example#3263 - Expect Usage Example
  • Example#3264 - Another Expect Usage Example
  • Example#3265 - expect_expectl example
  • Example#3266 - expect_popen example
  • Example#3267 - polling STDIN using basic API
  • Example#3268 - polling STDIN using buffered event API
  • Example#3269 - Process Control Example
  • Example#3270 - pcntl_fork example
  • Example#3271 - pcntl_signal_dispatch example
  • Example#3272 - pcntl_signal example
  • Example#3273 - pcntl_sigprocmask example
  • Example#3274 - pcntl_sigwaitinfo example
  • Example#3275 - posix_access example
  • Example#3276 - posix_ctermid example
  • Example#3277 - posix_get_last_error example
  • Example#3278 - posix_getcwd example
  • Example#3279 - posix_getegid example
  • Example#3280 - posix_geteuid example
  • Example#3281 - posix_getgid example
  • Example#3282 - Example use of posix_getgrgid
  • Example#3283 - Example use of posix_getgrnam
  • Example#3284 - Example use of posix_getgroups
  • Example#3285 - Example use of posix_getlogin
  • Example#3286 - Example use of posix_getpgid
  • Example#3287 - Example use of posix_getpid
  • Example#3288 - Example use of posix_getppid
  • Example#3289 - Example use of posix_getpwnam
  • Example#3290 - Example use of posix_getpwuid
  • Example#3291 - Example use of posix_getrlimit
  • Example#3292 - Example use of posix_getsid
  • Example#3293 - Example use of posix_getuid
  • Example#3294 - A posix_mknod example
  • Example#3295 - posix_setegid example
  • Example#3296 - posix_setgid example
  • Example#3297 - posix_setuid example
  • Example#3298 - posix_strerror example
  • Example#3299 - Example use of posix_times
  • Example#3300 - Example use of posix_uname
  • Example#3301 - escapeshellarg example
  • Example#3302 - escapeshellcmd example
  • Example#3303 - An exec example
  • Example#3304 - A proc_open example
  • Example#3305 - A shell_exec example
  • Example#3306 - system example
  • Example#3307 -
  • Example#3308 - Shared Memory Operations Overview
  • Example#3309 - Closing shared memory block
  • Example#3310 - Deleting shared memory block
  • Example#3311 - Create a new shared memory block
  • Example#3312 - Reading shared memory block
  • Example#3313 - Getting the size of the shared memory block
  • Example#3314 - Writing to shared memory block
  • Example#3315 - A geoip_continent_code_by_name example
  • Example#3316 - A geoip_country_code_by_name example
  • Example#3317 - A geoip_country_code3_by_name example
  • Example#3318 - A geoip_country_name_by_name example
  • Example#3319 - A geoip_region_by_name example
  • Example#3320 - A geoip_db_avail example
  • Example#3321 - A geoip_db_filename example
  • Example#3322 - A geoip_db_get_all_info example
  • Example#3323 - A geoip_db_get_all_info example
  • Example#3324 - A geoip_id_by_name example
  • Example#3325 - A geoip_isp_by_name example
  • Example#3326 - A geoip_org_by_name example
  • Example#3327 - A geoip_record_by_name example
  • Example#3328 - A geoip_region_by_name example
  • Example#3329 - A geoip_region_name_by_code example using region code for US/Canada
  • Example#3330 - A geoip_region_name_by_code example using FIPS codes
  • Example#3331 - A geoip_time_zone_by_country_and_region example using region code for US/Canada
  • Example#3332 - A geoip_time_zone_by_country_and_region example using FIPS codes
  • Example#3333 - Przykład json_decode
  • Example#3334 - Inny przykład
  • Example#3335 - Różne przykłady błędów json_decode
  • Example#3336 - Błędy - poziom zagłębienia
  • Example#3337 - Dekodowanie json_decode - large integers
  • Example#3338 - Przykład json_encode
  • Example#3339 - Przykład json_encode pokazuje zastosowanie parametru: opcje
  • Example#3340 - Przykład json_last_error
  • Example#3341 - Judy array example
  • Example#3342 - Lua::assignexample
  • Example#3343 - Lua::callexample
  • Example#3344 - Lua::evalexample
  • Example#3345 - Lua::registerCallbackexample
  • Example#3346 - LuaClosure::__invokeexample
  • Example#3347 - constant example
  • Example#3348 - Defining Constants
  • Example#3349 - Checking Constants
  • Example#3350 - eval example - simple text merge
  • Example#3351 - exit example
  • Example#3352 - exit status example
  • Example#3353 - Shutdown functions and destructors run regardless
  • Example#3354 - Listing all information about the users browser
  • Example#3355 - A __halt_compiler example
  • Example#3356 - highlight_string example
  • Example#3357 - A ignore_user_abort example
  • Example#3358 - pack example
  • Example#3359 - php_strip_whitespace example
  • Example#3360 - sleep example
  • Example#3361 - A sys_getloadavg example
  • Example#3362 - time_nanosleep example
  • Example#3363 - A time_sleep_until example
  • Example#3364 - uniqid Example
  • Example#3365 - unpack example
  • Example#3366 - unpack example with a repeater
  • Example#3367 - unpack example with unnamed keys
  • Example#3368 - usleep example
  • Example#3369 - parsekit_compile_file example
  • Example#3370 - parsekit_compile_string example
  • Example#3371 - parsekit_func_arginfo example
  • Example#3372 - SplDoublyLinkedList::__construct example
  • Example#3373 - SplStack::__construct example
  • Example#3374 - SplQueue::__construct example
  • Example#3375 - Efficiently handling tasks with SplQueue
  • Example#3376 - SplFixedArray usage example
  • Example#3377 - SplFixedArray::__construct example
  • Example#3378 - SplFixedArray::count example
  • Example#3379 - SplFixedArray::fromArray example
  • Example#3380 - SplFixedArray::getSize example
  • Example#3381 - SplFixedArray::setSize example
  • Example#3382 - SplFixedArray::toArray example
  • Example#3383 - SplObjectStorage as a set
  • Example#3384 - SplObjectStorage as a map
  • Example#3385 - SplObjectStorage::addAll example
  • Example#3386 - SplObjectStorage::attach example
  • Example#3387 - SplObjectStorage::contains example
  • Example#3388 - SplObjectStorage::count example
  • Example#3389 - SplObjectStorage::current example
  • Example#3390 - SplObjectStorage::detach example
  • Example#3391 - SplObjectStorage::getHash example
  • Example#3392 - SplObjectStorage::getInfo example
  • Example#3393 - SplObjectStorage::key example
  • Example#3394 - SplObjectStorage::next example
  • Example#3395 - SplObjectStorage::offsetExists example
  • Example#3396 - SplObjectStorage::offsetGet example
  • Example#3397 - SplObjectStorage::offsetSet example
  • Example#3398 - SplObjectStorage::offsetUnset example
  • Example#3399 - SplObjectStorage::removeAll example
  • Example#3400 - SplObjectStorage::removeAllExcept example
  • Example#3401 - SplObjectStorage::rewind example
  • Example#3402 - SplObjectStorage::serialize example
  • Example#3403 - SplObjectStorage::setInfo example
  • Example#3404 - SplObjectStorage::unserialize example
  • Example#3405 - SplObjectStorage::valid example
  • Example#3406 - Iterating AppendIterator with foreach
  • Example#3407 - Iterating AppendIterator with the AppendIterator API
  • Example#3408 - ArrayIterator::current example
  • Example#3409 - ArrayIterator::key example
  • Example#3410 - ArrayIterator::next example
  • Example#3411 - ArrayIterator::rewind example
  • Example#3412 - ArrayIterator::valid example
  • Example#3413 - Available callback arguments
  • Example#3414 - Callback basic examples
  • Example#3415 - A DirectoryIterator::__construct example
  • Example#3416 - A DirectoryIterator::current example
  • Example#3417 - A DirectoryIterator::getATime example
  • Example#3418 - A DirectoryIterator::getBasename example
  • Example#3419 - DirectoryIterator::getCTime example
  • Example#3420 - A DirectoryIterator::getFilename example
  • Example#3421 - DirectoryIterator::getGroup example
  • Example#3422 - DirectoryIterator::getInode example
  • Example#3423 - A DirectoryIterator::getMTime example
  • Example#3424 - DirectoryIterator::getOwner example
  • Example#3425 - DirectoryIterator::getPath example
  • Example#3426 - DirectoryIterator::getPathname example
  • Example#3427 - DirectoryIterator::getPerms example
  • Example#3428 - DirectoryIterator::getSize example
  • Example#3429 - DirectoryIterator::getType example
  • Example#3430 - DirectoryIterator::isDir example
  • Example#3431 - A DirectoryIterator::isDot example
  • Example#3432 - DirectoryIterator::isExecutable example
  • Example#3433 - DirectoryIterator::isFile example
  • Example#3434 - A DirectoryIterator::isLink example
  • Example#3435 - DirectoryIterator::isReadable example
  • Example#3436 - DirectoryIterator::isWritable example
  • Example#3437 - A DirectoryIterator::key example
  • Example#3438 - DirectoryIterator::next example
  • Example#3439 - DirectoryIterator::rewind example
  • Example#3440 - DirectoryIterator::seek example
  • Example#3441 - A DirectoryIterator::__toString example
  • Example#3442 - A DirectoryIterator::valid example
  • Example#3443 - FilesystemIterator::__construct example
  • Example#3444 - FilesystemIterator::current example
  • Example#3445 - FilesystemIterator::key example
  • Example#3446 - FilesystemIterator::next example
  • Example#3447 - FilesystemIterator::rewind example
  • Example#3448 - FilesystemIterator::key example
  • Example#3449 - FilterIterator::accept example
  • Example#3450 - GlobIterator example
  • Example#3451 - GlobIterator::count example
  • Example#3452 - InfiniteIterator::__construct example
  • Example#3453 - LimitIterator usage example
  • Example#3454 - LimitIterator::__construct example
  • Example#3455 - LimitIterator::getPosition example
  • Example#3456 - Iterating a MultipleIterator
  • Example#3457 - NoRewindIterator::__construct example
  • Example#3458 - NoRewindIterator::rewind example
  • Example#3459 - RecursiveArrayIterator::getChildren example
  • Example#3460 - RecursiveArrayIterator::hasChildren example
  • Example#3461 - Available callback arguments
  • Example#3462 - Recursive callback basic example
  • Example#3463 - RecursiveCallbackFilterIterator::hasChildren basic usage
  • Example#3464 - RecursiveDirectoryIterator example
  • Example#3465 - Basic RecursiveFilterIterator example
  • Example#3466 - RecursiveFilterIterator example
  • Example#3467 - Iterating a RecursiveIteratorIterator
  • Example#3468 - RecursiveRegexIterator::__construct example
  • Example#3469 - RecursiveRegexIterator::getChildren example
  • Example#3470 - RecursiveRegexIterator::hasChildren example
  • Example#3471 - RegexIterator::accept example
  • Example#3472 - RegexIterator::__construct example
  • Example#3473 - RegexIterator::getFlags example
  • Example#3474 - RegexIterator::getMode example
  • Example#3475 - RegexIterator::getPregFlags example
  • Example#3476 - RegexIterator::setFlags example
  • Example#3477 - RegexIterator::setMode example
  • Example#3478 - RegexIterator::setPregFlags example
  • Example#3479 - Countable::count example
  • Example#3480 - Basic usage
  • Example#3481 - SeekableIterator::seek example
  • Example#3482 - class_implements example
  • Example#3483 - class_parents example
  • Example#3484 - class_uses example
  • Example#3485 - iterator_apply example
  • Example#3486 - iterator_count example
  • Example#3487 - iterator_to_array example
  • Example#3488 - spl_autoload_register example
  • Example#3489 - spl_classes example
  • Example#3490 - A spl_object_hash example
  • Example#3491 - SplFileInfo::__construct example
  • Example#3492 - SplFileInfo::getBasename example
  • Example#3493 - SplFileInfo::getCTime example
  • Example#3494 - SplFileInfo::getExtension example
  • Example#3495 -
  • Example#3496 - SplFileInfo::getFilename example
  • Example#3497 - SplFileInfo::getGroup example
  • Example#3498 - SplFileInfo::getLinkTarget example
  • Example#3499 - SplFileInfo::getOwner example
  • Example#3500 - SplFileInfo::getPath example
  • Example#3501 - SplFileInfo::getPathInfo example
  • Example#3502 - SplFileInfo::getPathname example
  • Example#3503 - SplFileInfo::getPerms example
  • Example#3504 - SplFileInfo::getRealPath example
  • Example#3505 - SplFileInfo::getType example
  • Example#3506 - SplFileInfo::isDir example
  • Example#3507 - SplFileInfo::isExecutable example
  • Example#3508 - SplFileInfo::isFile example
  • Example#3509 - SplFileInfo::isLink example
  • Example#3510 - SplFileInfo::isReadable example
  • Example#3511 - SplFileInfo::openFile example
  • Example#3512 - SplFileInfo::setFileClass example
  • Example#3513 - SplFileInfo::setFileClass example
  • Example#3514 - SplFileInfo::__toString example
  • Example#3515 - SplFileObject::__construct example
  • Example#3516 - SplFileObject::current example
  • Example#3517 - SplFileObject::eof example
  • Example#3518 - SplFileObject::fflush example
  • Example#3519 - SplFileObject::fgetc example
  • Example#3520 - SplFileObject::fgetcsv example
  • Example#3521 - SplFileObject::READ_CSV example
  • Example#3522 - SplFileObject::fgets example
  • Example#3523 - SplFileObject::fgetss example
  • Example#3524 - SplFileObject::flock example
  • Example#3525 - SplFileObject::fpassthru example
  • Example#3526 - SplFileObject::fscanf example
  • Example#3527 - SplFileObject::fseek example
  • Example#3528 - SplFileObject::fstat example
  • Example#3529 - SplFileObject::ftell example
  • Example#3530 - SplFileObject::ftruncate example
  • Example#3531 - SplFileObject::fwrite example
  • Example#3532 - SplFileObject::getCsvControl example
  • Example#3533 - SplFileObject::getFlags example
  • Example#3534 - SplFileObject::getMaxLineLen example
  • Example#3535 - SplFileObject::key example
  • Example#3536 - SplFileObject::key example with SplFileObject::setMaxLineLen
  • Example#3537 - SplFileObject::next example
  • Example#3538 - SplFileObject::rewind example
  • Example#3539 - SplFileObject::seek example
  • Example#3540 - SplFileObject::setCsvControl example
  • Example#3541 - SplFileObject::setFlags example
  • Example#3542 - SplFileObject::setMaxLineLen example
  • Example#3543 - SplFileObject::valid example
  • Example#3544 - SplTempFileObject example
  • Example#3545 - ArrayObject::append example
  • Example#3546 - ArrayObject::asort example
  • Example#3547 - ArrayObject::__construct example
  • Example#3548 - ArrayObject::count example
  • Example#3549 - ArrayObject::exchangeArray example
  • Example#3550 - ArrayObject::getArrayCopy example
  • Example#3551 - ArrayObject::getFlags example
  • Example#3552 - ArrayObject::getIterator example
  • Example#3553 - ArrayObject::getIteratorClass example
  • Example#3554 - ArrayObject::ksort example
  • Example#3555 - ArrayObject::natcasesort example
  • Example#3556 - ArrayObject::natsort example
  • Example#3557 - ArrayObject::offsetExists example
  • Example#3558 - ArrayObject::offsetGet example
  • Example#3559 - ArrayObject::offsetSet example
  • Example#3560 - ArrayObject::offsetUnset example
  • Example#3561 - ArrayObject::serialize example
  • Example#3562 - ArrayObject::setFlags example
  • Example#3563 - ArrayObject::setIteratorClass example
  • Example#3564 - ArrayObject::uasort example
  • Example#3565 - ArrayObject::uksort example
  • Example#3566 - SplInt usage example
  • Example#3567 - SplFloat usage example
  • Example#3568 - SplEnum usage example
  • Example#3569 - SplEnum::getConstList example
  • Example#3570 - SplBool usage example
  • Example#3571 - SplString usage example
  • Example#3572 - Using file_get_contents to retrieve data from multiple sources
  • Example#3573 - Making a POST request to an https server
  • Example#3574 - Writing data to a compressed file
  • Example#3575 - A Stream for reading/writing global variables
  • Example#3576 - Listing files from tar archives
  • Example#3577 - Using stream_context_create
  • Example#3578 - Using stream_context_get_default
  • Example#3579 - stream_context_get_options example
  • Example#3580 - stream_context_get_params example
  • Example#3581 - stream_context_set_default example
  • Example#3582 - A stream_copy_to_stream example
  • Example#3583 - Controlling where filters are applied
  • Example#3584 - Filter for capitalizing characters on foo-bar.txt stream
  • Example#3585 - Registering a generic filter class to match multiple filter names.
  • Example#3586 - Dynamicly refiltering a stream
  • Example#3587 - stream_get_contents example
  • Example#3588 - Using stream_get_filters
  • Example#3589 - stream_get_meta_data example
  • Example#3590 - Using stream_get_transports
  • Example#3591 - stream_get_wrappers example
  • Example#3592 - Checking for the existence of a stream wrapper
  • Example#3593 - stream_is_local example
  • Example#3594 - stream_notification_callback example
  • Example#3595 - Simple progressbar for commandline download client
  • Example#3596 - stream_resolve_include_path example
  • Example#3597 - stream_select Example
  • Example#3598 - stream_set_timeout example
  • Example#3599 - stream_set_write_buffer example
  • Example#3600 - stream_socket_client example
  • Example#3601 - Using UDP connection
  • Example#3602 - stream_socket_enable_crypto example
  • Example#3603 - A stream_socket_pair example
  • Example#3604 - stream_socket_recvfrom example
  • Example#3605 - stream_socket_sendto Example
  • Example#3606 - Using TCP server sockets
  • Example#3607 - Using UDP server sockets
  • Example#3608 - A stream_socket_shutdown example
  • Example#3609 - How to register a stream wrapper
  • Example#3610 - Podstawowe użycie Tidy
  • Example#3611 - tidy::getBody example
  • Example#3612 - tidy::cleanrepair example
  • Example#3613 - tidy::__construct example
  • Example#3614 - tidy::diagnose example
  • Example#3615 - tidy_get_error_buffer example
  • Example#3616 - tidy::getConfig example
  • Example#3617 - tidy_getopt example
  • Example#3618 - Print all options along with their documentation and default value
  • Example#3619 - tidy::getStatus example
  • Example#3620 - tidy::head example
  • Example#3621 - tidy::html example
  • Example#3622 - tidy::parseFile example
  • Example#3623 - tidy::parseString example
  • Example#3624 - tidy::repairFile example
  • Example#3625 - tidy::repairString example
  • Example#3626 - tidy::root example
  • Example#3627 - Przykład tidyNode::hasChildren
  • Example#3628 - Przykład tidyNode::hasChildren
  • Example#3629 - Przykład tidyNode::hasSiblings
  • Example#3630 - Wyodrębnienie kodu ASP ze złożonego dokumentu HTML
  • Example#3631 - Wyodrębnienie komentarzy ze złożonego dokumentu HTML
  • Example#3632 - Wyodrębnienie kodu HTML ze złożonego dokumentu HTML
  • Example#3633 - Wyodrębnienie kodu JSTE ze złożonego dokumentu HTML
  • Example#3634 - Wyodrębnienie kodu PHP ze złożonego dokumentu HTML
  • Example#3635 - Wyodrębnienie tekstu ze złożonego dokumentu HTML
  • Example#3636 - Przykład ob_tidyhandler
  • Example#3637 - Przykład tidy_access_count
  • Example#3638 - Przykład tidy_config_count
  • Example#3639 - Przykład tidy_error_count
  • Example#3640 - Przykład tidy_get_output
  • Example#3641 - Przykład tidy_setopt
  • Example#3642 - Przykład tidy_warning_count
  • Example#3643 - Usuwanie komentarzy za pomocą tokenizera
  • Example#3644 - Przykłady użycia token_get_all
  • Example#3645 - Przykład token_name
  • Example#3646 - base64_decode przykład
  • Example#3647 - base64_encode przykład
  • Example#3648 - get_headers example
  • Example#3649 - get_headers using HEAD example
  • Example#3650 - What get_meta_tags parses
  • Example#3651 - What get_meta_tags returns
  • Example#3652 - Simple usage of http_build_query
  • Example#3653 - http_build_query with numerically index elements.
  • Example#3654 - http_build_query with complex arrays
  • Example#3655 - Using http_build_query with an object
  • Example#3656 - A parse_url przykład
  • Example#3657 - rawurldecode przykład
  • Example#3658 - rawurlencode przykład 1
  • Example#3659 - rawurlencode przykład 2
  • Example#3660 - urldecode przykład
  • Example#3661 - urlencode przykład
  • Example#3662 - urlencode i htmlentities przykład
  • Example#3663 - Basic Javascript execution
  • Example#3664 - Yaml Example
  • Example#3665 - yaml_emit example
  • Example#3666 - yaml_parse example
  • Example#3667 - A classic Application directory layout
  • Example#3668 - Entry
  • Example#3669 - Rewrite rule
  • Example#3670 - Application config
  • Example#3671 - Default controller
  • Example#3672 - Default view template
  • Example#3673 - Run the Applicatioin
  • Example#3674 - An array of yaf configuration example
  • Example#3675 - an ini file of yaf configuration example
  • Example#3676 - A Bootstrapexample
  • Example#3677 - Yaf_Application::bootstrapexample
  • Example#3678 - Yaf_Application::clearLastErrorexample
  • Example#3679 - A ini config file example
  • Example#3680 - Yaf_Application::__constructexample
  • Example#3681 - Yaf_Application::__constructexample
  • Example#3682 - Yaf_Application::environexample
  • Example#3683 - Yaf_Application::executeexample
  • Example#3684 - Yaf_Application::getConfigexample
  • Example#3685 - Yaf_Application::getDispatcherexample
  • Example#3686 - Yaf_Application::getLastErrorMsgexample
  • Example#3687 - Yaf_Application::getLastErrorNoexample
  • Example#3688 - Yaf_Application::getModulesexample
  • Example#3689 - Yaf_Dispatcher::autoRenderexample
  • Example#3690 - Yaf_Dispatcher::catchExceptionexample
  • Example#3691 - Yaf_Dispatcher::registerPluginexample
  • Example#3692 - A custom View engineexample
  • Example#3693 - Yaf_Dispatcher::setViewexample
  • Example#3694 - Yaf_Config_Iniexample
  • Example#3695 - define action in a separate file
  • Example#3696 - Dummy_action.php
  • Example#3697 - Yaf_Action_Abstract::executeexample
  • Example#3698 - Yaf_Action_Abstract::executeexample
  • Example#3699 - Yaf_View_Simple::assignexample
  • Example#3700 - templateexample
  • Example#3701 - Yaf_View_Simple::assignRefexample
  • Example#3702 - templateexample
  • Example#3703 - Yaf_View_Simple::__setexample
  • Example#3704 - Config example
  • Example#3705 - Register localnamespace
  • Example#3706 - Load class example
  • Example#3707 - Load namespace class example
  • Example#3708 - MVC class loading example
  • Example#3709 - MVC class distinctions
  • Example#3710 - MVC loading example
  • Example#3711 - Yaf_Plugin_Abstract::routerShutdownexample
  • Example#3712 - Yaf_Route_Mapexample
  • Example#3713 - Yaf_Route_Mapexample
  • Example#3714 - Yaf_Route_Regexexample
  • Example#3715 - Yaf_Route_Regexexample
  • Example#3716 - Yaf_Route_Rewriteexample
  • Example#3717 - Yaf_Route_Rewriteexample
  • Example#3718 - Rewrite rule for Apache
  • Example#3719 - Rewrite rule for Apache
  • Example#3720 - Rewrite rule for Lighttpd
  • Example#3721 - Rewrite rule for Nginx
  • Example#3722 - Yaf_Route_Static(default route)example
  • Example#3723 - application.iniexample
  • Example#3724 - Yaf_Dispatcher::autoConfigexample
  • Example#3725 - Yaf_Dispatcher::autoRenderexample
  • Example#3726 - Register some routes in Bootstrap
  • Example#3727 - plugin Dummy.php (under application.directory/plugins)
  • Example#3728 - Yaf_Route_Simple::routeexample
  • Example#3729 - Yaf_Route_Simple::routeexample
  • Example#3730 - Yaf_Route_Static::routeexample
  • Example#3731 - Yaf_Route_Supervarexample
  • Example#3732 - AMQP Example
  • Example#3733 - AMQPConnection::connect example
  • Example#3734 - AMQPConnection::__construct example
  • Example#3735 - AMQPConnection::disconnect example
  • Example#3736 - AMQPConnection::isConnected example
  • Example#3737 - AMQPConnection::reconnect example
  • Example#3738 - AMQPConnection::setHost example
  • Example#3739 - AMQPConnection::setLogin example
  • Example#3740 - AMQPConnection::setPassword example
  • Example#3741 - AMQPConnection::setPort example
  • Example#3742 - AMQPConnection::setVhost example
  • Example#3743 - AMQPExchange::declare example
  • Example#3744 - AMQPExchange::delete example
  • Example#3745 - AMQPQueue::ack example with AMQPQueue::get
  • Example#3746 - AMQPQueue::ack example with AMQPQueue::consume
  • Example#3747 - AMQPQueue::consume example
  • Example#3748 - AMQPQueue::get example
  • Example#3749 - Creating a chdb file
  • Example#3750 - Loading and looking up a chdb file
  • Example#3751 - chdb::get example
  • Example#3752 - chdb_create example
  • Example#3753 - Using PHP's cURL module to fetch the example.com homepage
  • Example#3754 - Initializing a new cURL session and fetching a web page
  • Example#3755 - Copying a cURL handle
  • Example#3756 - curl_errno example
  • Example#3757 - curl_error example
  • Example#3758 - Fetching a web page
  • Example#3759 - curl_getinfo example
  • Example#3760 - Initializing a new cURL session and fetching a web page
  • Example#3761 - curl_multi_add_handle example
  • Example#3762 - curl_multi_close example
  • Example#3763 - curl_multi_exec example
  • Example#3764 - A curl_multi_info_read example
  • Example#3765 - curl_multi_init example
  • Example#3766 - Initializing a new cURL session and fetching a web page
  • Example#3767 - Our own implementation of curl_setopt_array
  • Example#3768 - Initializing a new cURL session and fetching a web page
  • Example#3769 - Uploading file
  • Example#3770 - curl_version example
  • Example#3771 - FTP example
  • Example#3772 - ftp_alloc example
  • Example#3773 - Przykład użycia ftp_cdup
  • Example#3774 - Przykład użycia ftp_chdir
  • Example#3775 - ftp_chmod example
  • Example#3776 - Przykład użycia ftp_close
  • Example#3777 - Przykład użycia ftp_connect
  • Example#3778 - Przykład użycia ftp_delete
  • Example#3779 - Przykład użycia ftp_exec
  • Example#3780 - Przykład użycia ftp_fget
  • Example#3781 - Przykład użycia ftp_fput
  • Example#3782 - Przykład użycia ftp_get_option
  • Example#3783 - Przykład użycia ftp_get
  • Example#3784 - Przykład użycia ftp_login
  • Example#3785 - Przykład użycia ftp_mdtm
  • Example#3786 - Przykład użycia ftp_mkdir
  • Example#3787 - ftp_nb_continue example
  • Example#3788 - ftp_nb_fget example
  • Example#3789 - ftp_nb_fput example
  • Example#3790 - ftp_nb_get example
  • Example#3791 - Resuming a download with ftp_nb_get
  • Example#3792 - Resuming a download at position 100 to a new file with ftp_nb_get
  • Example#3793 - ftp_nb_put example
  • Example#3794 - Resuming an upload with ftp_nb_put
  • Example#3795 - Przykład użycia ftp_nlist
  • Example#3796 - Przykład użycia ftp_pasv
  • Example#3797 - Przykład użycia ftp_put
  • Example#3798 - Przykład użycia ftp_pwd
  • Example#3799 - Using ftp_raw to login to an FTP server manually.
  • Example#3800 - Przykład użycia ftp_rawlist
  • Example#3801 - Przykład użycia ftp_rename
  • Example#3802 - Przykład użycia ftp_rmdir
  • Example#3803 - Przykład użycia ftp_set_option
  • Example#3804 - Wysyłanie polecenia SITE do serwera FTP
  • Example#3805 - Przykład użycia ftp_size
  • Example#3806 - ftp_ssl_connect example
  • Example#3807 - Przykład użycia ftp_systype
  • Example#3808 - Basic Gearman client and worker
  • Example#3809 - Basic Gearman client and worker, background
  • Example#3810 - Basic Gearman client and worker, submitting tasks
  • Example#3811 - Adding two job servers
  • Example#3812 - Add two job servers
  • Example#3813 - Basic submission of two tasks
  • Example#3814 - Basic submission of two tasks with passing application context
  • Example#3815 - Two tasks, one background and one not
  • Example#3816 - A high priority task along with two normal tasks
  • Example#3817 - A low priority task along with two normal tasks
  • Example#3818 - Monitor completion of multiple background tasks
  • Example#3819 - Simple job submission with immediate return
  • Example#3820 - Submitting a job and retrieving incremental status
  • Example#3821 - Submit and monitor a background job
  • Example#3822 - Simple job submission with immediate return
  • Example#3823 - Submitting a job and retrieving incremental status
  • Example#3824 - Get the status of a long running job
  • Example#3825 - Monitor the status of a long running background job
  • Example#3826 - Simple worker making use of extra application context data
  • Example#3827 - Add alternate Gearman servers
  • Example#3828 - Add two job servers
  • Example#3829 - A simple worker with a 5 second timeout
  • Example#3830 - Running worker in non-blocking mode
  • Example#3831 - GearmanWorker::work example
  • Example#3832 - Hypothetical output from gopher://gopher.example.com/
  • Example#3833 - Using gopher_parsedir
  • Example#3834 - Search for all UPnP devices and services.
  • Example#3835 - Implementing light server
  • Example#3836 - Implementing light client
  • Example#3837 - Create new UPnP context and get IP address of the host
  • Example#3838 - Create new UPnP context and get port number
  • Example#3839 - Create new UPnP context and set host path
  • Example#3840 - Create new UPnP context
  • Example#3841 - Create new UPnP context and set callback
  • Example#3842 - Create new UPnP context and start browsing
  • Example#3843 - Create new UPnP context and start browsing
  • Example#3844 - Create new UPnP context and get device info service
  • Example#3845 - Create new UPnP context and get device info service
  • Example#3846 - A HttpDeflateStream example
  • Example#3847 - A HttpInflateStream example
  • Example#3848 - A HttpRequest::addCookies example
  • Example#3849 - GET example
  • Example#3850 - POST example
  • Example#3851 - A HttpRequestPool example
  • Example#3852 - A HttpRequestPool::socketPerform example
  • Example#3853 - A HttpResponse::capture example
  • Example#3854 - A HttpResponse::send example
  • Example#3855 - A http_cache_etag example
  • Example#3856 - A http_cache_last_modified example
  • Example#3857 - A http_chunked_decode example
  • Example#3858 - A http_support example
  • Example#3859 - Using http_negotiate_charset
  • Example#3860 - Using http_negotiate_content_type
  • Example#3861 - Using http_negotiate_language
  • Example#3862 - Using http_parse_cookie
  • Example#3863 - Using http_parse_headers
  • Example#3864 - Using http_parse_message
  • Example#3865 - A http_parse_params example
  • Example#3866 - A http_persistent_handles_count example
  • Example#3867 - A http_persistent_handles_ident example
  • Example#3868 - A http_get example
  • Example#3869 - A http_post_fields example
  • Example#3870 - A http_redirect example
  • Example#3871 - A http_send_file example
  • Example#3872 - A http_throttle example
  • Example#3873 - A http_build_url example
  • Example#3874 - modifying an attribute
  • Example#3875 - adding a completely new attribute
  • Example#3876 - modifying Title attribute
  • Example#3877 - modifying Title attribute
  • Example#3878 - removing attribute
  • Example#3879 - Retrieve an object
  • Example#3880 - Java Example
  • Example#3881 - AWT Example
  • Example#3882 - Java exception handler
  • Example#3883 - LDAP search example
  • Example#3884 - Complete example with authenticated bind
  • Example#3885 - Using LDAP Bind
  • Example#3886 - Using LDAP Bind Anonymously
  • Example#3887 - Complete example of password check
  • Example#3888 - Example of connecting to LDAP server.
  • Example#3889 - Example of connecting securely to LDAP server.
  • Example#3890 - Enumerating all LDAP error messages
  • Example#3891 - Generating and catching an error
  • Example#3892 - Show the list of attributes held for a particular directory entry
  • Example#3893 - Check protocol version
  • Example#3894 - List all values of the "mail" attribute for a directory entry
  • Example#3895 - Produce a list of all organizational units of an organization
  • Example#3896 - LDAP search
  • Example#3897 - Set protocol version
  • Example#3898 - Set server controls
  • Example#3899 - memcache extension overview example
  • Example#3900 - Using memcache session handler
  • Example#3901 - Memcache::add example
  • Example#3902 - Memcache::addServer example
  • Example#3903 - Memcache::close example
  • Example#3904 - Memcache::connect example
  • Example#3905 - Memcache::decrement example
  • Example#3906 - Memcache::delete example
  • Example#3907 - Memcache::flush example
  • Example#3908 - Memcache::get example
  • Example#3909 - Memcache::getExtendedStats example
  • Example#3910 - Memcache::getServerStatus example
  • Example#3911 - Memcache::getVersion example
  • Example#3912 - Memcache::increment example
  • Example#3913 - Memcache::pconnect example
  • Example#3914 - Memcache::replace example
  • Example#3915 - Memcache::set example
  • Example#3916 - Memcache::set example
  • Example#3917 - Memcache::setCompressThreshold example
  • Example#3918 - Memcache::setServerParams example
  • Example#3919 - Result callback example
  • Example#3920 - Read-through callback example
  • Example#3921 - Memcached::addServer example
  • Example#3922 - Memcached::addServers example
  • Example#3923 - Memcached::append example
  • Example#3924 - Memcached::cas example
  • Example#3925 - Creating a Memcached object
  • Example#3926 - Memcached::decrement example
  • Example#3927 - Memcached::delete example
  • Example#3928 - Memcached::fetch example
  • Example#3929 - Memcached::getDelayed example
  • Example#3930 - Memcached::flush example
  • Example#3931 - Memcached::get example #1
  • Example#3932 - Memcached::get example #2
  • Example#3933 - Memcached::getDelayed example
  • Example#3934 - Memcached::getMulti example
  • Example#3935 - Memcached::GET_PRESERVE_ORDER example
  • Example#3936 - Retrieving Memcached options
  • Example#3937 - Memcached::getResultCode example
  • Example#3938 - Memcached::getResultMessage example
  • Example#3939 - Memcached::getServerByKey example
  • Example#3940 - Memcached::getServerList example
  • Example#3941 - Memcached::getStats example
  • Example#3942 - Memcached::getVersion example
  • Example#3943 - Memcached::increment example
  • Example#3944 - Memcached::prepend example
  • Example#3945 - Memcached::set example
  • Example#3946 - Memcached::setByKey example
  • Example#3947 - Memcached::setMulti example
  • Example#3948 - Setting a Memcached option
  • Example#3949 - mqseries_back example
  • Example#3950 - mqseries_begin example
  • Example#3951 - mqseries_close example
  • Example#3952 - mqseries_cmit example
  • Example#3953 - mqseries_conn example
  • Example#3954 - mqseries_connx example
  • Example#3955 - mqseries_disc example
  • Example#3956 - mqseries_get example
  • Example#3957 - mqseries_inq example
  • Example#3958 - mqseries_open example
  • Example#3959 - mqseries_put example
  • Example#3960 - mqseries_strerror example
  • Example#3961 - define_syslog_variables example
  • Example#3962 - Using dns_get_record
  • Example#3963 - Using dns_get_record and DNS_ANY
  • Example#3964 - fsockopen Example
  • Example#3965 - Using UDP connection
  • Example#3966 - A simple gethostbyaddr example
  • Example#3967 - A simple gethostbyname example
  • Example#3968 - gethostbynamel example
  • Example#3969 - A simple gethostname example
  • Example#3970 - getprotobyname example
  • Example#3971 - getservbyname example
  • Example#3972 - header_register_callback example
  • Example#3973 - Unsetting specific header.
  • Example#3974 - Unsetting all previously set headers.
  • Example#3975 - Download dialog
  • Example#3976 - Caching directives
  • Example#3977 - Examples using headers_list
  • Example#3978 - Przykład użycia headers_sent
  • Example#3979 - Examples using headers_list
  • Example#3980 - inet_ntop Example
  • Example#3981 - inet_pton Example
  • Example#3982 - ip2long Example
  • Example#3983 - Displaying an IP address
  • Example#3984 - IP validation
  • Example#3985 - setcookie send example
  • Example#3986 - setcookie delete example
  • Example#3987 - setcookie and arrays
  • Example#3988 - Using syslog
  • Example#3989 - Procedural usage of rrd
  • Example#3990 - OO usage of rrd
  • Example#3991 - RRDGraph::setOptions examples
  • Example#3992 - RRDUpdater::update examples
  • Example#3993 - Creating a connection and connecting to a remote WebSphere MQSeries Messaging Server
  • Example#3994 - Creating a connection and connecting to a remote WebSphere Application Server
  • Example#3995 - Creating a connection and connecting to an MQTT server
  • Example#3996 - Creating a message with a simple text body
  • Example#3997 - Setting a text format property using the default syntax
  • Example#3998 - Setting a property using a type hint
  • Example#3999 - Retrieving a property from a message header
  • Example#4000 - Adding a message to a queue and receiving a response
  • Example#4001 - Creating a durable subscription to a topic
  • Example#4002 - Subscribing to a topic using a WebSphere Platform Messaging (WPM) server
  • Example#4003 - Receiving published data using a durable subscription
  • Example#4004 - Deleting a durable subscription to a topic
  • Example#4005 - Handling an error from a method that returns no result
  • Example#4006 - Handling an error from a method that returns a result
  • Example#4007 - Committing the current unit of work
  • Example#4008 - Creating a connection to a Messaging Server using the IBM MQSeries protocol (WMQ)
  • Example#4009 - Creating a connection with application transaction control and default host and port values
  • Example#4010 - Creating a connection to a Messaging Server using the IBM WebSphere Platform Messaging protocol (WPM)
  • Example#4011 - Creating a connection object and connecting to a Messaging Server
  • Example#4012 - Disconnecting from a Messaging Server
  • Example#4013 - Using the error number and description properties
  • Example#4014 - Using the error number and description properties
  • Example#4015 - Checking whether there us a connection to a Messaging Server
  • Example#4016 - Retrieve the next message from a queue without removing it
  • Example#4017 - Retrieve a specific message from a queue without removing it from the queue
  • Example#4018 - Retrieve all messages in a queue without removing them
  • Example#4019 - Retrieve all messages from a queue with a matching correlation id
  • Example#4020 - Receiving a message from a queue
  • Example#4021 - Receiving a message from a queue with options
  • Example#4022 - Receiving a message from a subscription
  • Example#4023 - Removing a message from a queue by message id
  • Example#4024 - Cancelling an in-flight unit of work
  • Example#4025 - Send a message to a queue
  • Example#4026 - Publish a message to a topic
  • Example#4027 - Send a request and receive a response
  • Example#4028 - Turn on debugging output
  • Example#4029 - Turn off debugging output
  • Example#4030 - Subscribe to a topic
  • Example#4031 - Delete a subscription
  • Example#4032 - Setting a text string into the body of a message
  • Example#4033 - Creating a message
  • Example#4034 - Creating a message with a simple text payload
  • Example#4035 - Setting a text format property using the default syntax
  • Example#4036 - Setting a text format property using a type hint
  • Example#4037 - Setting properties as the sender of a message
  • Example#4038 - Retreiving property values from a message
  • Example#4039 - snmp_get_quick_print example
  • Example#4040 - Using snmp_get_valueretrieval
  • Example#4041 - Using snmp_read_mib
  • Example#4042 - Using snmp_set_enum_print
  • Example#4043 - Using snmprealwalk
  • Example#4044 - Using snmp_set_quick_print
  • Example#4045 - Using snmp_set_valueretrieval
  • Example#4046 - Using snmp2_get
  • Example#4047 - Using snmp2_get_next
  • Example#4048 - Using snmp2_real_walk
  • Example#4049 - Using snmp2_set
  • Example#4050 - Using snmp2_set for setting BITS SNMP object id
  • Example#4051 - snm2_pwalk Example
  • Example#4052 - Using snmp3_get
  • Example#4053 - Using snmp3_getnext
  • Example#4054 - Using snmp3_real_walk
  • Example#4055 - Using snmp3_set
  • Example#4056 - Using snmp3_set for setting BITS SNMP object id
  • Example#4057 - snmp3_walk Example
  • Example#4058 - Using snmpget
  • Example#4059 - Using snmpgetnext
  • Example#4060 - Using snmprealwalk
  • Example#4061 - Using snmpset
  • Example#4062 - Using snmpset for setting BITS SNMP object id
  • Example#4063 - snmpwalk Example
  • Example#4064 - snmpwalkoid Example
  • Example#4065 - SNMP::close example
  • Example#4066 - Fetching sysLocation
  • Example#4067 - Single SNMP object
  • Example#4068 - Miltiple SNMP objects
  • Example#4069 - SNMP::getErrno example
  • Example#4070 - SNMP::getError example
  • Example#4071 - Single SNMP object
  • Example#4072 - Miltiple SNMP objects
  • Example#4073 - Set single SNMP object id
  • Example#4074 - Set multiple values using single SNMP::set call
  • Example#4075 - Using SNMP::set for setting BITS SNMP object id
  • Example#4076 - SNMP::setSecurity example
  • Example#4077 - SNMP::walk example
  • Example#4078 - suffix_as_key example
  • Example#4079 - Socket example: Simple TCP/IP server
  • Example#4080 - Socket example: Simple TCP/IP client
  • Example#4081 - Using socket_bind to set the source address
  • Example#4082 - socket_create_pair example
  • Example#4083 - socket_create_pair IPC example
  • Example#4084 - socket_set_option example
  • Example#4085 - socket_last_error example
  • Example#4086 - socket_recv example
  • Example#4087 - socket_recvfrom example
  • Example#4088 - Using NULL with socket_select
  • Example#4089 - Understanding socket_select's result
  • Example#4090 - socket_select example
  • Example#4091 - socket_sendto Example
  • Example#4092 - socket_set_block example
  • Example#4093 - socket_set_nonblock example
  • Example#4094 - socket_set_option example
  • Example#4095 - socket_strerror example
  • Example#4096 - Authentication using a public hostkey
  • Example#4097 - Retrieving a list of authentication methods
  • Example#4098 - Authenticating with a password
  • Example#4099 - Authentication using a public key
  • Example#4100 - ssh2_connect example
  • Example#4101 - Executing a command
  • Example#4102 - Opening a shell and retrieving the stderr stream associated with it
  • Example#4103 - Checking the fingerprint against a known value
  • Example#4104 - Determining what methods were negotiated
  • Example#4105 - Adding a publickey with ssh2_publickey_add
  • Example#4106 - Listing authorized keys with ssh2_publickey_list
  • Example#4107 - Downloading a file via SCP
  • Example#4108 - Uploading a file via SCP
  • Example#4109 - Stating a symbolic link via SFTP
  • Example#4110 - Creating a directory on a remote server
  • Example#4111 - Reading a symbolic link
  • Example#4112 - Resolving a pathname
  • Example#4113 - Renaming a file via sftp
  • Example#4114 - Removing a directory on a remote server
  • Example#4115 - Stating a file via SFTP
  • Example#4116 - Creating a symbolic link
  • Example#4117 - Deleting a file
  • Example#4118 - Opening a file via SFTP
  • Example#4119 - Executing a command
  • Example#4120 - Opening a tunnel to an arbitrary host
  • Example#4121 - Styl obiektowy
  • Example#4122 - Styl proceduralny
  • Example#4123 - stomp_connect_error example
  • Example#4124 - stomp_version example
  • Example#4125 - Styl obiektowy
  • Example#4126 - Styl proceduralny
  • Example#4127 - Styl obiektowy
  • Example#4128 - Styl proceduralny
  • Example#4129 - Styl obiektowy
  • Example#4130 - Styl proceduralny
  • Example#4131 - Styl obiektowy
  • Example#4132 - Styl proceduralny
  • Example#4133 - Styl obiektowy
  • Example#4134 - Styl proceduralny
  • Example#4135 - Styl obiektowy
  • Example#4136 - Styl proceduralny
  • Example#4137 - Styl obiektowy
  • Example#4138 - Styl proceduralny
  • Example#4139 - Styl obiektowy
  • Example#4140 - Styl proceduralny
  • Example#4141 - Styl obiektowy
  • Example#4142 - Styl proceduralny
  • Example#4143 - Train from array
  • Example#4144 - Train from a file
  • Example#4145 - svn_add example
  • Example#4146 - Default authentication example
  • Example#4147 - svn_blame example
  • Example#4148 - Basic example
  • Example#4149 - Basic example
  • Example#4150 - Basic example
  • Example#4151 - Basic example
  • Example#4152 - Basic example
  • Example#4153 - Basic example
  • Example#4154 - Diffing two revisions of a repository path
  • Example#4155 - Portably diffing two local files
  • Example#4156 - svn_export example
  • Example#4157 - Basic example
  • Example#4158 - svn_log example
  • Example#4159 - svn_ls example
  • Example#4160 - Basic example
  • Example#4161 - Basic example
  • Example#4162 - Deny all connections from localhost
  • Example#4163 - Ban an URL
  • Example#4164 - Get statistic snapshot
  • Example#4165 - Read varnish shared memory log
  • Example#4166 - VarnishAdmin::__construct example
  • Example#4167 - Parallel searching using Yaz
  • Example#4168 - CCL configuration
  • Example#4169 - CCL Parsing
  • Example#4170 - Record Update
  • Example#4171 - Array for GRS-1 record
  • Example#4172 - Working with MARCXML
  • Example#4173 - PHP function that scans titles
  • Example#4174 - Query Examples
  • Example#4175 - Sort Criterias
  • Example#4176 - Example for NIS errors
  • Example#4177 - Example for the NIS first
  • Example#4178 - Example for the default domain
  • Example#4179 - Example for the NIS master
  • Example#4180 - Example for NIS match
  • Example#4181 - Example for NIS next
  • Example#4182 - Example for the NIS order
  • Example#4183 -
  • Example#4184 - udm_api_version example
  • Example#4185 - udm_cat_listexample
  • Example#4186 - Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'
  • Example#4187 - udm_load_ispell_data example
  • Example#4188 - udm_load_ispell_data example
  • Example#4189 - solr_get_version example
  • Example#4190 - Contents of the BootStrap file
  • Example#4191 - Adding a document to the index
  • Example#4192 - Merging one document into another document
  • Example#4193 - Searching for documents - SolrObject responses
  • Example#4194 - Searching for documents - SolrDocument responses
  • Example#4195 - Simple TermsComponent example - basic
  • Example#4196 - Simple TermsComponent example - using a prefix
  • Example#4197 - Simple TermsComponent example - specifying a minimum frequency
  • Example#4198 - Simple Facet Example
  • Example#4199 - Simple Facet Example - with optional field override for mincount
  • Example#4200 - Connecting to SSL-Enabled Server
  • Example#4201 - SolrDocument::toArray example
  • Example#4202 - SolrObject::__construct example
  • Example#4203 - SolrObject::offsetUnset example
  • Example#4204 - SolrClient::addDocument example
  • Example#4205 - SolrClient::addDocuments example
  • Example#4206 - SolrClient::__construct example
  • Example#4207 - SolrClient::ping example
  • Example#4208 - SolrClient::query example
  • Example#4209 - SolrClient::request example
  • Example#4210 - SolrClient::setResponseWriter example
  • Example#4211 - SolrParams::setParam example
  • Example#4212 - Basic usage example
  • Example#4213 - Basic search query
  • Example#4214 - A Swish::__construct example
  • Example#4215 - Basic Swish::getMetaList example
  • Example#4216 - Basic Swish::getPropertyList example
  • Example#4217 - Basic Swish::prepare example
  • Example#4218 - Basic Swish::query example
  • Example#4219 - Basic SwishResult::stem example
  • Example#4220 - Basic SwishResults::getParsedWords example
  • Example#4221 - Basic SwishResults::nextResult example
  • Example#4222 - Basic SwishResults::seekResult example
  • Example#4223 - Basic SwishSearch::execute example
  • Example#4224 - Basic SwishSearch::resetLimit example
  • Example#4225 - Basic SwishSearch::setLimit example
  • Example#4226 - Basic SwishSearch::setPhraseDelimiter example
  • Example#4227 - Basic SwishSearch::setSort example
  • Example#4228 - Basic SwishSearch::setStructure example
  • Example#4229 - Turning off PHP parsing for a directory using .htaccess
  • Example#4230 - apache_get_modules example
  • Example#4231 - apache_get_version example
  • Example#4232 - apache_getenv example
  • Example#4233 - apache_lookup_uri przykład
  • Example#4234 - apache_request_headers example
  • Example#4235 - Przykład apache_response_headers
  • Example#4236 - Ustawianie zmiennej środowiskowej Apache używając apache_setenv
  • Example#4237 - nsapi_request_headers example
  • Example#4238 - Registering a variable with $_SESSION.
  • Example#4239 - Unregistering a variable with $_SESSION and register_globals disabled.
  • Example#4240 - Counting the number of hits of a single user
  • Example#4241 - Example information
  • Example#4242 - Przykład użycia session_cache_expire
  • Example#4243 - Przykłady session_cache_limiter
  • Example#4244 - Niszczenie sesji przy użyciu $_SESSION
  • Example#4245 - Przykłady session_name
  • Example#4246 - Przykład session_regenerate_id
  • Example#4247 - Przykład session_set_save_handler
  • Example#4248 - Przykład sesji: page1.php
  • Example#4249 - Przykład sesji: page2.php
  • Example#4250 - bbcode_add_smiley usage example
  • Example#4251 - bbcode_create example
  • Example#4252 - bbcode_set_arg_parser usage example
  • Example#4253 - bbcode_set_flags usage example
  • Example#4254 - Examples of valid patterns
  • Example#4255 - Examples of invalid patterns
  • Example#4256 - Example comparing preg_filter with preg_replace
  • Example#4257 - preg_grep example
  • Example#4258 - preg_last_error example
  • Example#4259 - Getting all phone numbers out of some text.
  • Example#4260 - Find matching HTML tags (greedy)
  • Example#4261 - Using named subpattern
  • Example#4262 - Find the string of text "php"
  • Example#4263 - Find the word "web"
  • Example#4264 - Getting the domain name out of a URL
  • Example#4265 - Using named subpattern
  • Example#4266 - preg_quote example
  • Example#4267 - Italicizing a word within some text
  • Example#4268 - preg_replace_callback and create_function
  • Example#4269 - preg_replace_callback example
  • Example#4270 - preg_replace_callback using recursive structure to handle encapsulated BB code
  • Example#4271 - Using backreferences followed by numeric literals
  • Example#4272 - Using indexed arrays with preg_replace
  • Example#4273 - Replacing several values
  • Example#4274 - Strip whitespace
  • Example#4275 - Using the count parameter
  • Example#4276 - preg_split example : Get the parts of a search string
  • Example#4277 - Splitting a string into component characters
  • Example#4278 - Splitting a string into matches and their offsets
  • Example#4279 - Regular Expression Examples
  • Example#4280 - ereg_replace example
  • Example#4281 - ereg_replace example
  • Example#4282 - Replace URLs with links
  • Example#4283 - ereg example
  • Example#4284 - Highlight search results
  • Example#4285 - eregi example
  • Example#4286 - split example
  • Example#4287 - split example
  • Example#4288 - spliti example
  • Example#4289 - sql_regcase example
  • Example#4290 - addcslashes example
  • Example#4291 - An addslashes example
  • Example#4292 - chr example
  • Example#4293 - chunk_split example
  • Example#4294 - convert_uudecode example
  • Example#4295 - convert_uuencode example
  • Example#4296 - count_chars example
  • Example#4297 - Displaying a crc32 checksum
  • Example#4298 - crypt examples
  • Example#4299 - Using crypt with htpasswd
  • Example#4300 - Using crypt with different hash types
  • Example#4301 - echo examples
  • Example#4302 - explode examples
  • Example#4303 - limit parameter examples
  • Example#4304 - fprintf: zero-padded integers
  • Example#4305 - fprintf: formatting currency
  • Example#4306 - Translation Table Example
  • Example#4307 - hex2bin example
  • Example#4308 - Decoding HTML entities
  • Example#4309 - A htmlentities example
  • Example#4310 - Usage of ENT_IGNORE
  • Example#4311 - A htmlspecialchars_decode example
  • Example#4312 - htmlspecialchars example
  • Example#4313 - implode example
  • Example#4314 - lcfirst example
  • Example#4315 - levenshtein example
  • Example#4316 - localeconv example
  • Example#4317 - Usage example of ltrim
  • Example#4318 - Usage example of md5_file
  • Example#4319 - A md5 example
  • Example#4320 - metaphone basic example
  • Example#4321 - Using the phonemes parameter
  • Example#4322 - money_format Example
  • Example#4323 - Using nl2br
  • Example#4324 - Generating valid HTML markup using the is_xhtml parameter
  • Example#4325 - Various newline separators
  • Example#4326 - number_format - przykłady
  • Example#4327 - ord example
  • Example#4328 - Using parse_str
  • Example#4329 - print examples
  • Example#4330 - Usage example of rtrim
  • Example#4331 - setlocale Examples
  • Example#4332 - setlocale Examples for Windows
  • Example#4333 - sha1_file example
  • Example#4334 - A sha1 example
  • Example#4335 - Soundex Examples
  • Example#4336 - Argument swapping
  • Example#4337 - Argument swapping
  • Example#4338 - Argument swapping
  • Example#4339 - Argument swapping
  • Example#4340 - Position specifier with other specifiers
  • Example#4341 - printf: various examples
  • Example#4342 - printf: string specifiers
  • Example#4343 - sprintf: zero-padded integers
  • Example#4344 - sprintf: formatting currency
  • Example#4345 - sprintf: scientific notation
  • Example#4346 - sscanf Example
  • Example#4347 - sscanf - using optional parameters
  • Example#4348 - str_ireplace example
  • Example#4349 - str_pad example
  • Example#4350 - str_repeat example
  • Example#4351 - Basic str_replace examples
  • Example#4352 - Examples of potential str_replace gotchas
  • Example#4353 - str_rot13 example
  • Example#4354 - str_shuffle example
  • Example#4355 - Example uses of str_split
  • Example#4356 - A str_word_count example
  • Example#4357 - strcasecmp example
  • Example#4358 - strcspn example
  • Example#4359 - strip_tags example
  • Example#4360 - stripos examples
  • Example#4361 - A stripslashes example
  • Example#4362 - Using stripslashes on an array
  • Example#4363 - stristr example
  • Example#4364 - Testing if a string is found or not
  • Example#4365 - Using a non "string" needle
  • Example#4366 - A strlen example
  • Example#4367 - strpbrk example
  • Example#4368 - Using ===
  • Example#4369 - Using !==
  • Example#4370 - Using an offset
  • Example#4371 - strrchr przykład
  • Example#4372 - Odwracanie ciągu znaków przez strrev
  • Example#4373 - A simple strripos example
  • Example#4374 - strspn example
  • Example#4375 - strstr example
  • Example#4376 - strtok example
  • Example#4377 - Old strtok behavior
  • Example#4378 - New strtok behavior
  • Example#4379 - strtolower przykład
  • Example#4380 - strtoupper przykład
  • Example#4381 - strtr example
  • Example#4382 - strtr example with two arguments
  • Example#4383 - strtr behavior comparison
  • Example#4384 - A substr_compare example
  • Example#4385 - A substr_count example
  • Example#4386 - substr_replace przykłady
  • Example#4387 - Using a negative start
  • Example#4388 - Using a negative length
  • Example#4389 - Basic substr usage
  • Example#4390 - substr casting behaviour
  • Example#4391 -
  • Example#4392 - Usage example of trim
  • Example#4393 - Trimming array values with trim
  • Example#4394 - ucfirst example
  • Example#4395 - ucwords example
  • Example#4396 - vfprintf: zero-padded integers
  • Example#4397 - vprintf: zero-padded integers
  • Example#4398 - vsprintf: zero-padded integers
  • Example#4399 - wordwrap przykład
  • Example#4400 - wordwrap przykład
  • Example#4401 - Przykład użycia array_change_key_case
  • Example#4402 - Przykład użycia array_chunk
  • Example#4403 - Przykład użycia array_combine
  • Example#4404 - Przykład użycia array_count_values
  • Example#4405 - Przykład użycia array_diff_assoc
  • Example#4406 - Przykład użycia array_diff_key
  • Example#4407 - Przykład użycia array_diff_uassoc
  • Example#4408 - Przykład użycia funkcji array_diff_ukey
  • Example#4409 - Przykład użycia array_diff
  • Example#4410 - array_fill_keys example
  • Example#4411 - Przykład użycia array_fill
  • Example#4412 - Przykład użycia array_filter
  • Example#4413 - array_filter bez parametru funkcja_zwrotna
  • Example#4414 - Przykład użycia array_flip
  • Example#4415 - Przykład użycia array_flip : kolizja
  • Example#4416 - Przykład użycia array_intersect_assoc
  • Example#4417 - array_intersect_key example
  • Example#4418 - array_intersect_uassoc example
  • Example#4419 - array_intersect_ukey example
  • Example#4420 - Przykład użycia array_intersect
  • Example#4421 - Przykład użycia array_key_exists
  • Example#4422 - array_key_exists a isset
  • Example#4423 - Przykład array_keys
  • Example#4424 - Przykład użycia array_map
  • Example#4425 - array_map - używanie większej ilości tablic
  • Example#4426 - Tworzenie tablicy tablic
  • Example#4427 - Przykład użycia array_merge_recursive
  • Example#4428 - Przykład użycia array_merge
  • Example#4429 - Prosty przykład użycia array_merge
  • Example#4430 - Przykład użycia array_merge w PHP 5
  • Example#4431 - Sortowanie wielu tablic
  • Example#4432 - Sortowanie wielowymiarowych tablic
  • Example#4433 - Sortowanie wyników zapytań do baz danych
  • Example#4434 - Sortowanie z ignorowaniem wielkości znaków
  • Example#4435 - Przykład użycia array_pad
  • Example#4436 - Przykład użycia array_pop
  • Example#4437 - array_product examples
  • Example#4438 - Przykład użycia array_push
  • Example#4439 - Przykład użycia array_rand
  • Example#4440 - Przykład użycia array_reduce
  • Example#4441 - array_replace_recursive example
  • Example#4442 - array_replace_recursive and recursive behavior
  • Example#4443 - array_replace example
  • Example#4444 - Przykład użycia array_reverse
  • Example#4445 - Przykład użycia array_search
  • Example#4446 - Przykład użycia array_shift
  • Example#4447 - Przykład użycia array_slice
  • Example#4448 - Przykład użycia array_splice
  • Example#4449 - Przykład użycia array_sum
  • Example#4450 - array_udiff_assoc example
  • Example#4451 - array_udiff_uassoc example
  • Example#4452 - array_udiff example
  • Example#4453 - Przykład użycia array_uintersect_assoc
  • Example#4454 - array_uintersect_uassoc example
  • Example#4455 - array_uintersect example
  • Example#4456 - Przykład użycia array_unique
  • Example#4457 - array_unique i typy
  • Example#4458 - Przykład użycia array_unshift
  • Example#4459 - Przykład użycia array_values
  • Example#4460 - array_walk_recursive example
  • Example#4461 - Przykład użycia array_walk
  • Example#4462 - Przykład użycia array
  • Example#4463 - Automatyczne indeksowanie w funkcji array
  • Example#4464 - Indeksowanie od 1 w array
  • Example#4465 - Odczytywanie elementu tablicy wewnątrz cudzysłowów
  • Example#4466 - Przykład użycia arsort
  • Example#4467 - Przykład użycia asort
  • Example#4468 - Przykład użycia compact
  • Example#4469 - Przykład użycia count
  • Example#4470 - Przykład rekurencyjnego przetwarzania przez count (PHP >= 4.2.0)
  • Example#4471 - Przykład użycia funkcji current i innych podobnych
  • Example#4472 - Przykłady użycia each
  • Example#4473 - Przechodzenie przez zmienną korzystając z funkcji each
  • Example#4474 - Prosty przykład użycia funkcji end
  • Example#4475 - Przykład użycia extract
  • Example#4476 - Przykład użycia in_array
  • Example#4477 - Przykład użycia in_array z parametrem strict
  • Example#4478 - in_array z tablicą jako igła
  • Example#4479 - Przykład użycia funkcji key
  • Example#4480 - Przykład użycia krsort
  • Example#4481 - Przykład użycia ksort
  • Example#4482 - Przykłady użycia list
  • Example#4483 - Przykład użycia list
  • Example#4484 - Przykład użycia list z indeksowaną tablicą
  • Example#4485 - natcasesort example
  • Example#4486 - Przykład użycia natsort
  • Example#4487 - Przykład użycia funkcji next i podobnych
  • Example#4488 - Przykład użycia funkcji prev i podobnych
  • Example#4489 - Przykłady użycia funkcji range
  • Example#4490 - Przykład użycia funkcji reset
  • Example#4491 - Przykład użycia rsort
  • Example#4492 - Przykład użycia shuffle
  • Example#4493 - Przykład użycia sort
  • Example#4494 - Przykład użycia uksort
  • Example#4495 - Przykład użycia usort
  • Example#4496 - Przykład użycia usort do sortowania wielowymiarowych tablic
  • Example#4497 - Przykład użycia usort używając funkcji składowej obiektu
  • Example#4498 - classes.inc
  • Example#4499 - test_script.php
  • Example#4500 - Alternatywa dla call_user_method_array
  • Example#4501 - Alternatywa dla call_user_method
  • Example#4502 - class_alias example
  • Example#4503 - Przykład class_exists
  • Example#4504 - Przykład z parametrem autoload
  • Example#4505 - Using get_called_class
  • Example#4506 - Przykład użycia get_class_methods
  • Example#4507 - Przykład użycia get_class_vars
  • Example#4508 - Przykład użycia get_class
  • Example#4509 - get_declared_classes przykład
  • Example#4510 - get_declared_interfaces example
  • Example#4511 - Przykład użycia get_object_vars
  • Example#4512 - Przykład użycia get_parent_class
  • Example#4513 - interface_exists example
  • Example#4514 - is_a przykład
  • Example#4515 - Użycie operatora instanceof w PHP 5
  • Example#4516 - is_subclass_of przykład
  • Example#4517 - method_exists przykład
  • Example#4518 - A property_exists example
  • Example#4519 - classkit_import example
  • Example#4520 - classkit_method_add example
  • Example#4521 - classkit_method_copy example
  • Example#4522 - classkit_method_redefine example
  • Example#4523 - classkit_method_remove example
  • Example#4524 - classkit_method_rename example
  • Example#4525 - A ctype_alnum example (using the default locale)
  • Example#4526 - A ctype_alpha example (using the default locale)
  • Example#4527 - A ctype_cntrl example
  • Example#4528 - A ctype_digit example
  • Example#4529 - A ctype_digit example comparing strings with integers
  • Example#4530 - A ctype_graph example
  • Example#4531 - A ctype_lower example (using the default locale)
  • Example#4532 - A ctype_print example
  • Example#4533 - A ctype_punct example
  • Example#4534 - A ctype_space example
  • Example#4535 - A ctype_upper example (using the default locale)
  • Example#4536 - A ctype_xdigit example
  • Example#4537 - Validating email addresses with filter_var
  • Example#4538 - Validating IP addresses with filter_var
  • Example#4539 - Passing options to filter_var
  • Example#4540 - Sanitizing and validating email addresses
  • Example#4541 - A filter_input_array example
  • Example#4542 - A filter_input example
  • Example#4543 - A filter_list example
  • Example#4544 - A filter_var_array example
  • Example#4545 - A filter_var example
  • Example#4546 - call_user_func_array example
  • Example#4547 - call_user_func_array using namespace name
  • Example#4548 - Using lambda function
  • Example#4549 - call_user_func example and references
  • Example#4550 - call_user_func example
  • Example#4551 - call_user_func using namespace name
  • Example#4552 - Using a class method with call_user_func
  • Example#4553 - Using lambda function with call_user_func
  • Example#4554 - Creating an anonymous function with create_function
  • Example#4555 - Making a general processing function with create_function
  • Example#4556 - Using anonymous functions as callback functions
  • Example#4557 - forward_static_call_array example
  • Example#4558 - forward_static_call example
  • Example#4559 - func_get_arg example
  • Example#4560 - func_get_arg example before and after PHP 5.3
  • Example#4561 - func_get_arg example of byref and byval arguments
  • Example#4562 - func_get_args example
  • Example#4563 - func_get_args example before and after PHP 5.3
  • Example#4564 - func_get_args example of byref and byval arguments
  • Example#4565 - func_num_args example
  • Example#4566 - func_num_args example before and after PHP 5.3
  • Example#4567 - function_exists example
  • Example#4568 - get_defined_functions example
  • Example#4569 - register_shutdown_function example
  • Example#4570 - register_tick_function example
  • Example#4571 - Class association
  • Example#4572 - Object association
  • Example#4573 - storage_classes.inc
  • Example#4574 - test_aggregation.php
  • Example#4575 - Using aggregate_info
  • Example#4576 - Quickhash Example
  • Example#4577 - Quickhash ArrayAccess Example
  • Example#4578 - Quickhash Iterator Example
  • Example#4579 - Quickhash String Values Example
  • Example#4580 - QuickHashIntSet::add example
  • Example#4581 - QuickHashIntSet::__construct example
  • Example#4582 - QuickHashIntSet::delete example
  • Example#4583 - QuickHashIntSet::exists example
  • Example#4584 - QuickHashIntSet::getSize example
  • Example#4585 - QuickHashIntSet::loadFromFile example
  • Example#4586 - QuickHashIntSet::loadFromString example
  • Example#4587 - QuickHashIntSet::saveToFile example
  • Example#4588 - QuickHashIntSet::saveToString example
  • Example#4589 - QuickHashIntHash::add example
  • Example#4590 - QuickHashIntHash::__construct example
  • Example#4591 - QuickHashIntHash::delete example
  • Example#4592 - QuickHashIntHash::exists example
  • Example#4593 - QuickHashIntHash::get example
  • Example#4594 - QuickHashIntHash::getSize example
  • Example#4595 - QuickHash IntHash file format
  • Example#4596 - QuickHash IntHash file format
  • Example#4597 - QuickHashIntHash::loadFromFile example
  • Example#4598 - QuickHashIntHash::loadFromString example
  • Example#4599 - QuickHashIntHash::saveToFile example
  • Example#4600 - QuickHashIntHash::saveToString example
  • Example#4601 - QuickHashIntHash::set example
  • Example#4602 - QuickHashIntHash::update example
  • Example#4603 - QuickHashStringIntHash::add example
  • Example#4604 - QuickHashStringIntHash::__construct example
  • Example#4605 - QuickHashStringIntHash::delete example
  • Example#4606 - QuickHashStringIntHash::get example
  • Example#4607 - QuickHashStringIntHash::getSize example
  • Example#4608 - QuickHash StringIntHash file format
  • Example#4609 - QuickHash IntHash file format
  • Example#4610 - QuickHashStringIntHash::loadFromFile example
  • Example#4611 - QuickHashStringIntHash::loadFromString example
  • Example#4612 - QuickHashStringIntHash::saveToFile example
  • Example#4613 - QuickHashStringIntHash::saveToString example
  • Example#4614 - QuickHashStringIntHash::set example
  • Example#4615 - QuickHashStringIntHash::update example
  • Example#4616 - QuickHashIntStringHash::add example
  • Example#4617 - QuickHashIntStringHash::__construct example
  • Example#4618 - QuickHashIntStringHash::delete example
  • Example#4619 - QuickHashIntStringHash::get example
  • Example#4620 - QuickHashIntStringHash::getSize example
  • Example#4621 - QuickHash IntString file format
  • Example#4622 - QuickHash IntString file format
  • Example#4623 - QuickHashIntStringHash::loadFromFile example
  • Example#4624 - QuickHashIntStringHash::loadFromString example
  • Example#4625 - QuickHashIntStringHash::saveToFile example
  • Example#4626 - QuickHashIntStringHash::saveToString example
  • Example#4627 - QuickHashIntStringHash::set example
  • Example#4628 - QuickHashIntStringHash::update example
  • Example#4629 - Reflection Example from Shell (a Terminal)
  • Example#4630 - Extending the built-in classes
  • Example#4631 - Basic usage ReflectionClass
  • Example#4632 - ReflectionClass::getDefaultProperties example
  • Example#4633 - ReflectionClass::getDocComment example
  • Example#4634 - ReflectionClass::getEndLine example
  • Example#4635 - ReflectionClass::getInterfaceNames example
  • Example#4636 - ReflectionClass::getInterfaces example
  • Example#4637 - ReflectionClass::getName example
  • Example#4638 - ReflectionClass::getNamespaceName example
  • Example#4639 - ReflectionClass::getProperties filtering example
  • Example#4640 - ReflectionClass::getShortName example
  • Example#4641 - ReflectionClass::hasConstant example
  • Example#4642 - ReflectionClass::hasMethod example
  • Example#4643 - ReflectionClass::hasProperty example
  • Example#4644 - ReflectionClass::inNamespace example
  • Example#4645 - ReflectionClass::isAbstract example
  • Example#4646 - ReflectionClass::isAbstract example
  • Example#4647 - ReflectionClass::isInstance related examples
  • Example#4648 - ReflectionClass::isInstantiable example
  • Example#4649 - ReflectionClass::isIterateable example
  • Example#4650 - ReflectionClass::__toString example
  • Example#4651 - ReflectionExtension example
  • Example#4652 - ReflectionExtension::getClasses example
  • Example#4653 - ReflectionExtension::getClassNames example
  • Example#4654 - ReflectionExtension::getConstants example
  • Example#4655 - ReflectionExtension::getDependencies example
  • Example#4656 - ReflectionExtension::getFunctions example
  • Example#4657 - ReflectionExtension::getINIEntries example
  • Example#4658 - ReflectionExtension::getName example
  • Example#4659 - ReflectionExtension::getVersion example
  • Example#4660 - ReflectionExtension::info example
  • Example#4661 - ReflectionFunction::__construct example
  • Example#4662 - ReflectionFunction::invoke example
  • Example#4663 - ReflectionFunction::invokeArgs example
  • Example#4664 - ReflectionFunction::invokeArgs with references example
  • Example#4665 - ReflectionFunction::__toString example
  • Example#4666 - ReflectionFunctionAbstract::isDeprecated example
  • Example#4667 - ReflectionMethod::__construct example
  • Example#4668 - ReflectionMethod::getDeclaringClass example
  • Example#4669 - ReflectionMethod::getModifiers example
  • Example#4670 - ReflectionMethod::getPrototype example
  • Example#4671 - ReflectionMethod::invoke example
  • Example#4672 - ReflectionMethod::invokeArgs example
  • Example#4673 - ReflectionMethod::__toString example
  • Example#4674 - Using the ReflectionParameter class
  • Example#4675 - Getting
  • Example#4676 - ReflectionProperty::__construct example
  • Example#4677 - Getting value from private and protected properties using ReflectionProperty class
  • Example#4678 - ReflectionProperty::getValue example
  • Example#4679 - ReflectionProperty::setValue example
  • Example#4680 - debug_zval_dump example
  • Example#4681 -
  • Example#4682 -
  • Example#4683 - A simple empty / isset comparison.
  • Example#4684 - empty on String Offsets
  • Example#4685 - floatval Example
  • Example#4686 - get_defined_vars Example
  • Example#4687 - get_resource_type example
  • Example#4688 - gettype example
  • Example#4689 - import_request_variables example
  • Example#4690 - intval examples
  • Example#4691 - Check that variable is an array
  • Example#4692 - is_bool examples
  • Example#4693 - is_callable example
  • Example#4694 - is_float example
  • Example#4695 - is_int example
  • Example#4696 - is_null example
  • Example#4697 - is_numeric examples
  • Example#4698 - is_object example
  • Example#4699 - is_resource example
  • Example#4700 - is_scalar example
  • Example#4701 - is_string example
  • Example#4702 - isset Examples
  • Example#4703 - isset on String Offsets
  • Example#4704 - print_r example
  • Example#4705 - return parameter example
  • Example#4706 - serialize example
  • Example#4707 - settype example
  • Example#4708 - strval example using PHP 5's magic __toString() method.
  • Example#4709 - unserialize example
  • Example#4710 - unserialize_callback_func example
  • Example#4711 - unset example
  • Example#4712 - Using (unset) casting
  • Example#4713 - var_dump example
  • Example#4714 - var_export Examples
  • Example#4715 - Exporting classes since PHP 5.1.0
  • Example#4716 - Using __set_state() (since PHP 5.1.0)
  • Example#4717 -
  • Example#4718 - OAuth::fetch example
  • Example#4719 - OAuth::getAccessToken example
  • Example#4720 - OAuth::getRequestToken example
  • Example#4721 - OAuth::setRequestEngine example
  • Example#4722 - An OAuth::setRsaCertificate example
  • Example#4723 - OAuth::setToken example
  • Example#4724 - OAuthProvider::__construct example
  • Example#4725 - Example OAuthProvider::consumerHandler callback
  • Example#4726 - OAuthProvider::generateToken example
  • Example#4727 - OAuthProvider::is2LeggedEndpoint example
  • Example#4728 - Example OAuthProvider::timestampNonceHandler callback
  • Example#4729 - Example OAuthProvider::tokenHandler callback
  • Example#4730 - A sample SCA component
  • Example#4731 - The structure of an SCA for PHP component
  • Example#4732 - Obtaining a proxy for a local PHP class
  • Example#4733 - Obtaining a proxy for a web service
  • Example#4734 - Calling services
  • Example#4735 - Obtaining a proxy using getService
  • Example#4736 - Making calls on the proxy
  • Example#4737 - StockQuote Service
  • Example#4738 - Generated WSDL
  • Example#4739 - Generated WSDL
  • Example#4740 - location attribute
  • Example#4741 - method with two arguments
  • Example#4742 - types section illustrating named parameters
  • Example#4743 - A Component that uses Data Structures
  • Example#4744 - An SCA::getService example
  • Example#4745 - is_soap_fault example
  • Example#4746 - SOAP's standard method for error reporting is exceptions
  • Example#4747 - SoapClient::__doRequest example
  • Example#4748 - SoapClient::__getFunctions example
  • Example#4749 - SoapClient::__getLastRequest() example
  • Example#4750 - SoapClient::__getLastRequest() example
  • Example#4751 - SoapClient::__getLastResponse() example
  • Example#4752 - SoapClient::__getLastResponse() example
  • Example#4753 - SoapClient::__getTypes example
  • Example#4754 - SoapClient::__setLocation example
  • Example#4755 - SoapClient::__setSoapHeaders example
  • Example#4756 - Set Multiple Headers
  • Example#4757 - SoapClient::__soapCall example
  • Example#4758 - SoapClient::SoapClient example
  • Example#4759 - SoapServer::addFunction example
  • Example#4760 - SoapServer::getFunctions example
  • Example#4761 - SoapServer::handle example
  • Example#4762 - SoapServer::setPersistence example
  • Example#4763 - SoapServer::SoapServer example
  • Example#4764 - Some examples
  • Example#4765 - Some examples
  • Example#4766 - SoapHeader::SoapHeader example
  • Example#4767 - SoapParam::SoapParam example
  • Example#4768 - SoapVar::SoapVar example
  • Example#4769 - XMLRPC client functions example
  • Example#4770 - XML-RPC type example
  • Example#4771 - A xmlrpc_set_type example
  • Example#4772 - For Each in ASP
  • Example#4773 - while() ... Next() in PHP 4
  • Example#4774 - foreach in PHP 5
  • Example#4775 - COM example (1)
  • Example#4776 - COM example (2)
  • Example#4777 - DOTNET example
  • Example#4778 - Variant example, PHP 4.x style
  • Example#4779 - Variant example, PHP 5 style
  • Example#4780 - COM event sink example
  • Example#4781 - OO syntax
  • Example#4782 - Don't use com_invoke(), use OO syntax instead
  • Example#4783 - OO syntax
  • Example#4784 - OO syntax
  • Example#4785 - printer_abort example
  • Example#4786 - printer_close example
  • Example#4787 - printer_create_dc example
  • Example#4788 - printer_draw_bmp example
  • Example#4789 - printer_draw_chord example
  • Example#4790 - printer_draw_elipse example
  • Example#4791 - printer_draw_line example
  • Example#4792 - printer_draw_pie example
  • Example#4793 - printer_draw_rectangle example
  • Example#4794 - printer_draw_roundrect example
  • Example#4795 - printer_draw_text example
  • Example#4796 - printer_get_option example
  • Example#4797 - printer_list example
  • Example#4798 - printer_logical_fontheight example
  • Example#4799 - printer_open example
  • Example#4800 - printer_select_brush example
  • Example#4801 - printer_select_font example
  • Example#4802 - printer_select_pen example
  • Example#4803 - printer_set_option example
  • Example#4804 - printer_start_doc example
  • Example#4805 - printer_write example
  • Example#4806 - Get the uptime and display it in a message box
  • Example#4807 - Statistics about the current PHP process
  • Example#4808 - Statistics about global memory utilization
  • Example#4809 - Registering a PHP script to run as a service
  • Example#4810 - Unregistering a service
  • Example#4811 - Running as a service
  • Example#4812 - A win32_create_service example
  • Example#4813 - A win32_delete_service example
  • Example#4814 - A win32_start_service_ctrl_dispatcher example
  • Example#4815 - Creating a new DOMAttr object
  • Example#4816 - DOMAttr::isId() Example
  • Example#4817 - Creating a new DOMCdataSection object
  • Example#4818 - Creating a new DOMComment
  • Example#4819 - Creating a new DOMDocument
  • Example#4820 - Creating a new element and inserting it as root
  • Example#4821 - Creating a new element and inserting it as root
  • Example#4822 - A namespace prefix example
  • Example#4823 - DOMDocument::getElementById() Example
  • Example#4824 - Basic Usage Example
  • Example#4825 - Get all the XInclude elements
  • Example#4826 - DOMDocument::importNode example
  • Example#4827 - Creating a Document
  • Example#4828 - Creating a Document
  • Example#4829 - Creating a Document
  • Example#4830 - Creating a Document
  • Example#4831 - Static invocation of loadXML
  • Example#4832 - Adding a new method to DOMElement to ease our code
  • Example#4833 - Retrieving elements as custom class
  • Example#4834 - Retrieving owner document
  • Example#4835 - Saving a DOM tree into a file
  • Example#4836 - Saving a HTML tree into a string
  • Example#4837 - Saving a HTML tree into a file
  • Example#4838 - Saving a DOM tree into a string
  • Example#4839 - Example of DTD validation
  • Example#4840 - DOMDocument::xinclude() example
  • Example#4841 - Appending XML data to your document
  • Example#4842 - Creating a new DOMElement
  • Example#4843 - Setting an attribute
  • Example#4844 - Creating a new DOMEntityReference
  • Example#4845 - Creating a document with an attached DTD
  • Example#4846 - Testing your DOM Implementation
  • Example#4847 - Adding a child
  • Example#4848 - DOMNode::getLineNo example
  • Example#4849 - DOMNode::getNodePath example
  • Example#4850 - Removing a child
  • Example#4851 - Preserving the parent node's namespace URI
  • Example#4852 - Traversing all the entries of the table
  • Example#4853 - Creating a new DOMProcessingInstruction object
  • Example#4854 - Creating a new DOMText
  • Example#4855 - Getting the count of all the english books
  • Example#4856 - Getting all the english books
  • Example#4857 - book.xml
  • Example#4858 - DOMXPath::registerPHPFunctions with php:functionString
  • Example#4859 - DOMXPath::registerPHPFunctions with php:function
  • Example#4860 - Import SimpleXML into DOM with dom_import_simplexml
  • Example#4861 - Include file example.inc with XML string
  • Example#4862 - Getting all the attributes of a node
  • Example#4863 - Creating a simple HTML document header
  • Example#4864 - Retrieving root element
  • Example#4865 - Creating a simple HTML document header
  • Example#4866 - Creating a simple HTML document header
  • Example#4867 - Creating a simple HTML document header
  • Example#4868 - Substituting Xincludes
  • Example#4869 - Getting the document type's name
  • Example#4870 - Retrieving the public id
  • Example#4871 - Retrieving the system id
  • Example#4872 - Getting an attribute node
  • Example#4873 - Getting the value of an attribute
  • Example#4874 - Getting a content
  • Example#4875 - Testing the existence of an attribute
  • Example#4876 - Setting an attribute
  • Example#4877 - Getting the node name
  • Example#4878 - Adding a child
  • Example#4879 - Adding a child
  • Example#4880 - Adding a child
  • Example#4881 - Getting a content
  • Example#4882 - Adding a child
  • Example#4883 - Iterate over children
  • Example#4884 -
  • Example#4885 - Finding the document of a node
  • Example#4886 - Finding the document of a node
  • Example#4887 - Removing a child
  • Example#4888 - Saving the result of a XSLT transformation in a file
  • Example#4889 - Outputting the result of a XSLT transformation
  • Example#4890 - Opening an XML document from a file
  • Example#4891 - Opening an XML document in a string
  • Example#4892 - domxml_version Example
  • Example#4893 - domxml_xslt_version Example
  • Example#4894 - xpath_eval_expression Example
  • Example#4895 - A libxml_get_errors example
  • Example#4896 - A libxml_set_streams_context example
  • Example#4897 - A libxml_use_internal_errors example
  • Example#4898 - Access via property name
  • Example#4899 - Access via property name as array index
  • Example#4900 - Data Object iteration
  • Example#4901 - Access many-valued property by name
  • Example#4902 - Many-valued element access
  • Example#4903 - Many-valued property iteration
  • Example#4904 - Chained property access
  • Example#4905 - XPath navigation
  • Example#4906 - XPath querying
  • Example#4907 - Creating child data objects
  • Example#4908 - Unset a primitive property
  • Example#4909 - Unset a data object
  • Example#4910 - Unset a referenced data object
  • Example#4911 - Access via property index
  • Example#4912 - Getting the SDO_Sequence interface
  • Example#4913 - Get/set sequence values
  • Example#4914 - Sequence iteration
  • Example#4915 - Sequence versus Data Object
  • Example#4916 - Adding to a sequence
  • Example#4917 - Removing from a sequence
  • Example#4918 - Reflecting on a Data Object
  • Example#4919 - Accessing the type information
  • Example#4920 - A SDO_DAS_DataFactory::addPropertyToType example
  • Example#4921 - A SDO_DAS_DataFactory::addType example
  • Example#4922 - Creating a data object
  • Example#4923 - Retrieving a data object
  • Example#4924 - Updating a data object
  • Example#4925 - Deleting a data object
  • Example#4926 - One company, one department - Create
  • Example#4927 - One company, one department - Retrieve and Update
  • Example#4928 - One company, two departments - Retrieve and Delete
  • Example#4929 - One company, one department, one employee - Create
  • Example#4930 - One company, one department, one employee - Retrieve and update
  • Example#4931 - One company, two departments, two employees - Retrieve and delete
  • Example#4932 - Retrieving a data object using executePreparedQuery
  • Example#4933 - Loading, altering, and saving an XML document
  • Example#4934 - Creating a new XML document
  • Example#4935 - Setting XML document properties
  • Example#4936 - Using an open type
  • Example#4937 - Finding out what you can from the document
  • Example#4938 - Printing the SDO model
  • Example#4939 - Include file example.php with XML string
  • Example#4940 - Getting <plot>
  • Example#4941 - Getting <line>
  • Example#4942 - Accessing non-unique elements in SimpleXML
  • Example#4943 - Using attributes
  • Example#4944 - Comparing Elements and Attributes with Text
  • Example#4945 - Comparing Two Elements
  • Example#4946 - Using XPath
  • Example#4947 - Setting values
  • Example#4948 - Adding elements and attributes
  • Example#4949 - DOM Interoperability
  • Example#4950 - Loading broken XML string
  • Example#4951 - Add attributes and children to a SimpleXML element
  • Example#4952 - Add attributes and children to a SimpleXML element
  • Example#4953 - Get XML
  • Example#4954 - Using asXML() on SimpleXMLElement::xpath results
  • Example#4955 - Interpret an XML string
  • Example#4956 - Traversing a children() pseudo-array
  • Example#4957 - Using namespaces
  • Example#4958 - Create a SimpleXMLElement object
  • Example#4959 - Create a SimpleXMLElement object from a URL
  • Example#4960 - Counting the number of children
  • Example#4961 - Get document namespaces
  • Example#4962 - Working with multiple namespaces
  • Example#4963 - Get XML element names
  • Example#4964 - Get document namespaces in use
  • Example#4965 - Setting a namespace prefix to use in an XPath query
  • Example#4966 - Xpath
  • Example#4967 - Return the current element
  • Example#4968 - Return the sub-elements of the current element
  • Example#4969 - Check whether the current element has sub-elements
  • Example#4970 - Get the current XML tag key
  • Example#4971 - Move to the next element
  • Example#4972 - Rewind to the first element
  • Example#4973 - Check whether the current element is valid
  • Example#4974 - Importing DOM
  • Example#4975 - Interpret an XML document
  • Example#4976 - Interpret an XML string
  • Example#4977 - Serializing a single value with WDDX
  • Example#4978 - Using incremental packets with WDDX
  • Example#4979 - wddx_serialize_vars example
  • Example#4980 - Show XML Element Structure
  • Example#4981 - Map XML to HTML
  • Example#4982 - External Entity Example
  • Example#4983 - xmltest.xml
  • Example#4984 - xmltest2.xml
  • Example#4985 - xml_parse_into_struct example
  • Example#4986 - moldb.xml - small database of molecular information
  • Example#4987 - parsemoldb.php - parses moldb.xml into an array of molecular objects
  • Example#4988 - xml_set_object example
  • Example#4989 - Validating XML
  • Example#4990 - collection.xml
  • Example#4991 - collection.xsl
  • Example#4992 - Creating an XSLTProcessor
  • Example#4993 - Testing EXSLT support
  • Example#4994 - Simple PHP Function call from a stylesheet
  • Example#4995 - Changing the owner before the transformation
  • Example#4996 - Example profiling output
  • Example#4997 - Transforming to a DOMDocument
  • Example#4998 - Transforming to a HTML file
  • Example#4999 - Transforming to a string
  • Example#5000 - xslt_backend_name example
  • Example#5001 - xslt_backend_version example
  • Example#5002 - xslt_create example
  • Example#5003 - Handling errors using the xslt_error and xslt_errno functions.
  • Example#5004 - Using the xslt_process to transform an XML file and a XSL file to a new XML file
  • Example#5005 - Using the xslt_process to transform an XML file and a XSL file to a variable containing the resulting XML data
  • Example#5006 - Using the xslt_process to transform a variable containing XML data and a variable containing XSL data into a variable containing the resulting XML data
  • Example#5007 - Passing PHP variables to XSL files
  • Example#5008 - xslt_set_error_handler Example
  • Example#5009 - Using the XSLT Logging features
  • Example#5010 - Using your own error handler as a method
  • Example#5011 - xslt_set_sax_handlers Example
  • Example#5012 - Object oriented handler
  • Example#5013 - xslt_set_scheme_handlers example
  • Example#5014 - xslt_setopt Example
  • Example#5015 - "counter"'s basic interface
  • Example#5016 - "counter"'s extended interface
  • Example#5017 - "counter"'s objective interface
  • Example#5018 - An example config.m4 file
  • Example#5019 - Sample configure output
  • Example#5020 - counter's config.m4 file
  • Example#5021 - An example config.w32 file
  • Example#5022 - counter's config.w32 file
  • Example#5023 - Files in the counter extension, in no particular order
  • Example#5024 - zend_module declaration in the counter extension
  • Example#5025 - zend_module definition in PHP 5.3
  • Example#5026 - Counter extension module definition
  • Example#5027 - The wrong way to store the basic counter interface's value
  • Example#5028 - The counter module's globals
  • Example#5029 - The counter module's global structure declaration
  • Example#5030 - Accessor macros for per-module globals
  • Example#5031 - The right way to store the basic counter interface's value
  • Example#5032 - counter's PHP_MINFO function
  • Example#5033 - PHP's leak warnings
  • Example#5034 - Minimal PHP extension with one function
  • Example#5035 - A simple function
  • Example#5036 - Example macros for invoking pdo_SKEL_error
  • Example#5037 - Using pdo_parse_params
  • Example#5038 - Implementing preparer for drivers that don't support native prepared statements
  • Example#5039 - simple stream example that displays the PHP home page
  • Example#5040 - How to accept a stream as a parameter
  • Example#5041 - How to return a stream from a function
  • Example#5042 - The default config.m4.
  • Example#5043 - A simple extension.
  • Example#5044 - A test file for first_module.so.
  • Example#5045 - Internal declaration of zend_function_entry.
  • Example#5046 - Internal declaration of zend_module_entry.
  • Example#5047 - PHP's implementation of variable arguments in fsockopen().
  • Example#5048 - PHP/Zend zval type definition.
  • Example#5049 - Testing for referenced parameter passing.
  • Example#5050 - Creating variables with different scopes.
  • Example#5051 - Creation of a long.
  • Example#5052 - Adding an element to an associative array.
  • Example#5053 - Adding an element to an indexed array.
  • Example#5054 - Source code and screenshot for output in phpinfo.
  • Example#5055 - Printing execution information.
  • Example#5056 - Calling user functions.
  • Example#5057 - A hidden HTML form element
  • Example#5058 - Data to be edited by the user
  • Example#5059 - In a URL
  • Example#5060 - Generating Javascript with PHP
  • Example#5061 - Emulating Register Globals
  • Example#5062 - Example PHP/FI Code
  • Example#5063 - In PHP Core
  • Example#5064 - Object Oriented Code in PHP Core
  • Example#5065 - In the bzip2 Extension
  • Example#5066 - In the datetime Extension
  • Example#5067 - In the dBase Extension
  • Example#5068 - In the mcrypt Extension
  • Example#5069 - In the oci8 Extension
  • Example#5070 - In the SPL Extension
  • Example#5071 - In the Semaphore (sysvmsg) extension
  • Example#5072 - A 5.2.1+ Zip Example
  • Example#5073 - strrpos and strripos now use the entire string as a needle
  • Example#5074 - An object with no properties is no longer considered "empty"
  • Example#5075 - In some cases classes must be declared before used
  • Example#5076 - Migrating Apache configuration files for PHP 5
  • Example#5077 - Migrating Apache configuration files for PHP 5, CGI mode
  • Example#5078 - Example of object comparison in PHP 4
  • Example#5079 - Compound object comparisons in PHP 4
  • Example#5080 - Activate full on-screen error reporting for dev. domain
  • Example#5081 - Add security script for protected areas
  • Example#5082 - Unix include_path
  • Example#5083 - Windows include_path
  • Example#5084 - string.rot13
  • Example#5085 - string.toupper
  • Example#5086 - string.tolower
  • Example#5087 - string.strip_tags
  • Example#5088 - convert.base64-encode & convert.base64-decode
  • Example#5089 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5090 - zlib.deflate and zlib.inflate
  • Example#5091 - zlib.deflate simple
  • Example#5092 - bzip2.compress and bzip2.decompress
  • Example#5093 - Encrypting file output using 3DES
  • Example#5094 - Reading an encrypted file
Wykaz funkcji i metod
Wersja HTML Help
Indeks


Wersja HTML Help

  • About This Edition
  • Using PHP Manual CHM Edition
    • The HTML Help Toolbar
    • The Navigation Pane
    • Keyboard Shortcuts
  • The Full Text Search
    • General searching rules
    • Searching for words or phrases
    • Defining search terms
    • Using nested expressions when searching
  • Specialities of this Edition
    • User Preferences
    • Presentational Specialities
  • Integrating the PHP Manual
  • Skin development
    • Page Display Process
    • Page Elements
    • CSS classes
  • CHM Edition Credits
Wykaz przykładów
About This Edition
Podręcznik PHP


About This Edition

The Windows HTML Help Edition of the PHP Manual is aimed at developers, who want the manual at hand every time, and would like to read manual pages and user notes without waiting for a remote web page to download. This edition gives you the full content of the manual plus the user notes, with some great features provided by the viewer application by the scripts we use to generate this format and by other contributors in the form of skins.

This distribution of the PHP Manual contains many files, including the main manual file php_manual_en.chm. You can view the manual by double clicking on this file (as you already guessed). You may also see a php_manual_en.chw file in the directory, it's generated the first time you use the index tab, and it contains an index with the manual's pages.

For those interested in technical details about Microsoft HTML Help, » http://www.helpware.net/ is a great resource. For more information and positioning of Windows HTML Help in the Microsoft help formats and services history, see this » WinWriters article.

Wersja HTML Help
Using PHP Manual CHM Edition
Wersja HTML Help


Using PHP Manual CHM Edition

Spis treści

  • The HTML Help Toolbar
  • The Navigation Pane
  • Keyboard Shortcuts

When you double click on a CHM, a HTML Help Viewer window opens with three panes. On the left side of the window is the Navigation pane. It contains four navigational tabs: the Contents, Index, Search and Favorites tabs. On the right side of the window is the Topic pane. It displays the selected help topic, or the default help topic on startup. The help pages are all separate HTML files, your Internet Explorer displays the pages in the Topic pane. The third pane is the toolbar, which is located below the help window title bar. You can adjust the horizontal layout with dragging the vertical border between the Navigation pane and the Topic pane.

Note, that when you open the CHM the first time, it may appear in a strange position and size. From then, Windows remembers the window position, size and the last opened tab. All these including your favorites are stored in a file named hh.dat. If you move your file to another directory, all these remembered settings will be lost (including your favorites listing!). If you replace your CHM file with a new one, with the same name, this is not a problem though. The file names and path values are stored in hh.dat.

About This Edition
The HTML Help Toolbar
Wersja HTML Help


The HTML Help Toolbar

The HTML Help Toolbar contains the following icons, when you view the PHP Manual:

  • Hide/Show - Hides/shows the navigation pane.
  • Locate - Locates a topic in the contents tab (in case you reached a topic with search, index or favorites, and would like to see where it is in the table of contents tree view).
  • Back - Goes back in the history.
  • Forward - Goes forward in the history.
  • Refresh - Reloads the current page.
  • Home - Opens the startup page of the CHM.
  • Print - Opens the print dialog box.
  • Options - Provides a dropdown with more options.
Using this toolbar is really easy, many of the toolbar icons are strongly related to their Internet Explorer equivalents.

Using PHP Manual CHM Edition
The Navigation Pane
Using PHP Manual CHM Edition


The Navigation Pane

The Navigation Pane contains four navigational tabs: the Contents, Index, Search and Favorites tabs. These all provide different methods to access a topic in the help file.

  • The contents tab reveals a tree like table of contents, where you can navigate to the desired topic by opening and closing parts of the tree. You can even access the deepest sections using this TOC. If you right click on an item here and choose "Print...", you'll have the option to print the selected topic or the selected topic and all subtopics. However printing is not the initial goal of this representation of the manual (the PDF version is suitable for printing).
  • The index tab lists a huge number of "keywords" (actually manual page titles). You can pick one, or start to type a keyword, see the list adjusting to your input, and then click on a topic, or press enter if the selected topic is the one you would like to see.
  • The search tab shows one of the most powerful features of the HTML Help Viewer, the full text search (also known as FTS). Here you can type in your search expression, optionally connecting words with AND/OR/NEAR/NOT. Before you click 'List topics', you can also set some options at the bottom. After the search results are displayed, you'll realize that manual text and user note results are separated. To sort out the two types, click on the 'Location' column header. Now from the search results list, you can pick a topic, and see it's page. The keywords you searched for are highlighted on the page.
  • The favorites tab enables you to store your most used topics in a list, easily accessible. Here you can see the list, add the current topic to it, remove one, or display a selected item. You can also specify your own title for the favorite, by typing it into the 'Current topic:' box. The user note page titles are prepended with a 'N:' string so you can distinguish them from normal manual pages in the favorites listing.

The HTML Help Toolbar
Keyboard Shortcuts
Using PHP Manual CHM Edition


Keyboard Shortcuts

There are many keyboard shortcuts you can use to increase your productivity. Many users find it more appropriate to use these keyboard shortcuts to access topics, instead of clicking.

General Help Viewer Shortcuts
To | Press
Close the Help Viewer | ALT+F4
Display the Options menu | ALT+O
Hide or show the Navigation pane | ALT+O, and then T
Print a topic | ALT+O, and then P
Move back to the previous topic | ALT+LEFT ARROW
Move forward to the next topic (provided you have viewed it just previously) | ALT+RIGHT ARROW
Turn on or off search highlighting. | ALT+O, and then O
Return to the help file home page | ALT+O, and then H
Switch between the Navigation pane and the Topic pane | F6
Scroll through all the links in a topic or through all the options on a Navigation pane tab | TAB
Display context (right click) menu [see the User Preferences section] | SHIFT+F10
Contents Tab Shortcuts
To | Press
Display the Contents tab | ALT+C
Open and close a book or folder | PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic | DOWN ARROW and UP ARROW
Display the selected topic | ENTER
Index Tab Shortcuts
To | Press
Display the Index tab | ALT+N
Type a keyword to search for | ALT+W, and then type the word
Select a keyword in the list | UP ARROW and DOWN ARROW
Display the associated topic | ENTER or ALT+D
Search Tab shortcuts
To | Press
Display the Search tab | ALT+S
Type a keyword to search for | ALT+W, and then type the word
Start a search | ALT+L
Select a topic in the results list | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Search for a keyword in the result list of a prior search | ALT+U
Search for words similar to the keyword. For example, to find words like "running" and "runs" for the keyword "run" | ALT+M
Only search through topic titles | ALT+R
Favorites Tab Shortcuts
To | Press
Display the Favorites tab | ALT+I
Add the currently displayed topic to the Favorites list | ALT+A
Select a topic in the Favorites list | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Remove the selected topic from the list | ALT+R
Topic Pane Shortcuts
To | Press
Index Lookup | Select the words you would like to look up and press F1
Find on page | CTRL+F, and then adjust options
Refresh page | F5

The Navigation Pane
The Full Text Search
Using PHP Manual CHM Edition


The Full Text Search

Spis treści

  • General searching rules
  • Searching for words or phrases
  • Defining search terms
  • Using nested expressions when searching

This edition of the PHP Manual includes an advanced full text search possibility provided by the viewer application. This enables users to search through every word in the help file to find a match. For example, if a user does a full-text search on the word "Apache", every topic that contains the word "Apache" will be listed. Advanced full-text search allows a user to search using boolean, wildcard, and nested expressions. A user can also limit the search to previous results, match similar words, or search topic titles only.

The usage of the search feature is fairly straightforward. Click on the search tab, type in the desired words and press ENTER (or click on "List Topics"). Then you'll receive a list of matches from the PHP Manual (and the notes). You can use the button with a right arrow on it to add boolean operators to your search (or you can type them in). As you see the results, you can use the column headings (Title, Location and Rank) to sort the topic list. The default order is by Rank. You can also adjust some parameters at the bottom of this tab.

The words found are highlighted on the current page in the Topic pane by default. You can turn off this feature by choosing the "Search Highlight Off" menu item in the Options menu. To can get this feature back similarly. If you are viewing a long topic, only the first 500 instances of a search word or phrase will be highlighted, due to a limitation of the viewer.

Keyboard Shortcuts
General searching rules
Wersja HTML Help


General searching rules

A basic search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are as follows:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.
  • You may search for any combination of letters (a-z) and numbers (0-9). You cannot search for single letters (a, b, c, etc.) and common words, like: an, and, as, at, be, but, by, do, for, from, have, he, in, it, not, of, on, or, she, that, the, there, they, this, to, we, which, with, you.
  • Punctuation marks such as the period (.), colon (:), semicolon (;), comma (,), and hyphen (-) are ignored during a search.
  • Group the elements of your search using double quotes or parentheses to set apart each element. You cannot search for quotation marks.

Informacja:

If you are searching for a file name with an extension, you should group the entire string in double quotes, ("filename.ext"). Otherwise, the period will break the file name into two separate terms. The default operation between terms is AND, so you will create the logical equivalent to "filename AND ext."

The Full Text Search
Searching for words or phrases
The Full Text Search


Searching for words or phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table below describes the results of these different kinds of searches.

Word and phrase searches
Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase | "new operator" or new operator | Topics that contain the literal phrase "new operator" and all its grammatical variations. Without the quotation marks, the query is equivalent to specifying "new AND operator," which will find topics containing both of the individual words, instead of the phrase.
Wildcard expressions | esc* or HT?? | Results for the first example include topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term. Results for the second example include topics that contain the terms "HTTP", "HTML" and so on. The question mark cannot be the only character in the term.

Informacja:

Select the Match similar words check box to include minor grammatical variations for the phrase you search. This feature only locates variations of the word with common suffixes. For example, a search on the word "add" will find "added," but it will not find "additive". This option is independent of other options or syntax. If you do a titles-only search, variations in titles will be matched. If you use quotes (or any other query operator) any variation of the word can appear; for example, "stemmed search" will also match "stemming search".

General searching rules
Defining search terms
The Full Text Search


Defining search terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If no operator is specified, AND is used. For example, the query "server cgi security" is equivalent to "server AND cgi AND security".

Search operators
Search for | Example | Results
Both terms in the same topic | http AND apache | Topics containing both the words "http" and "apache".
Either term in a topic | ming OR swflib | Topics containing either the word "ming" or the word "swflib" or both.
The first term without the second term | xml NOT expat | Topics containing the word "xml" but not the word "expat".
Both terms in the same topic, close together | database NEAR security | Topics containing the word "database" within eight words of the word "security".

Informacja:

The |, &, and ! characters can also be used in place of OR AND and NOT respectively. This may not work if you use a very old version of the viewer.

Searching for words or phrases
Using nested expressions when searching
The Full Text Search


Using nested expressions when searching

Nested expressions allow you to create complex searches for information. For example, "html AND ((smtp OR pop3) NEAR mail)" finds topics containing the word "html" along with the words "smtp" and "mail" close together, or containing "html" along with the words "pop3" and "mail" close together.

The basic rules for searching help topics using nested expressions are as follows:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.
  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "mail NOT pop3 OR smtp" finds topics containing the word "mail" without the word "pop3" or topics containing the word "smtp". On the other hand, "mail NOT (pop3 OR smtp)" finds topics containing the word "mail" without either of the words "pop3" or "smtp".
  • You cannot nest expressions more than five levels deep.

Defining search terms
Specialities of this Edition
The Full Text Search


Specialities of this Edition

Spis treści

  • User Preferences
  • Presentational Specialities

The HTML Help Edition of the PHP Manual over-performs the presentational and interactive capabilities offered by other editions (including the online manual).

Using nested expressions when searching
User Preferences
Wersja HTML Help


User Preferences

Most of the interactive features of this manual are provided by the viewer application (including full text search, index, favorites list), but we extended this list with PHP Manual specific tools. All these can be adjusted to your needs using a simple desktop application named php_manual_prefs.exe. If you run this program you can see three groups of settings: Online Functions, Context Menu, and Skin. All your settings are stored in php_manual_prefs.js.

Online functions enable you to have elements connected to websites. The two ones you can see on all manual pages are "This page online" and "Report a bug". As you can figure out the first one shows you the same page in the online manual, the second one opens a page from » http://bugs.php.net/ and prefills some bug data for you. You need to select a mirror site to use for "php.net sensitive" online functions. We recommend choosing a close mirror site to get the best speed. Other components that may be limited by this online functions setting include context menu items opening new websites ("Google search selection" for example). Custom designs may also include elements restricted by this setting.

The context menu settings enables you to choose which context menu you prefer. This application provides you with an option to define your own context menu adding elements to it from a predefined set. You can have this custom context menu for the right click of your mouse, and have the original menu for CTRL+right click, or the opposite way. Three special types of custom context menu items exist:

Context menu items
Type | Examples | Comments
Page Jump | Function Reference, Function Index | These items jump to a specific page in the CHM. Page Jump options are not restricted to point inside the CHM though. They can point to websites or other resources. Page jump options with a protocol part in the URL open in new window.
Function Call | Print page, Select all, Copy selection to clipboard, Google Search Selection | These are "function calls" for internally defined context menu functions. The last two examples have the speciality that they only show up in the menu if you rightclicked on a selection. Currently there is no way to extend the context menu with skin defined functions.
Special display | Google SearchBox, AlltheWeb SearchBox | These are displayed as HTML forms, where you can enter search keywords, press ENTER, and receive a new window with the search issued in the appropriate search engine. Currently there is no way to extend the set of specially displayed context menu items.
Possible context menu elements and their "abstract implementations" are stored in context.ini. You have the ability to add possible page jump options there, but there is no way currently to extend the context menu system with user (skin) defined functions. The possible mirror sites are listed in mirrors.ini. Feel free to suggest more bundled context menu items to us at » php-doc-chm@lists.php.net.

The skins setting enables you to choose from the two bundled default skins, or from any user defined skins. The Low skin is optimized to display correctly at any small size, the High skin is optimized for your viewing pleasure. Other skins may be developed according to our skins development guide. The recommended place for skins on the file system is the skins/SKINNAME subfolder of the PHP Manual directory. Though this is not required, some skins may define other rules (not recommended). We included sample skins for you to see examples of how to develop skins for the PHP Manual.

You have three buttons to choose from at the bottom. The Apply button applies your changes without exiting, the OK button applies and closes the application, the Cancel button does not modify your settings and closes the program.

Specialities of this Edition
Presentational Specialities
Specialities of this Edition


Presentational Specialities

This edition of the PHP Manual is highly optimized for screen presentation. Skins may be developed to better support printing, as this was not the goal of the included skins. This approach allowed us to make many modifications to the presentation of different parts of the manual.

The first thing you'll notice is that all examples are color coded, using the PHP function show_source(). The actual colors used are defined by CSS classes. Examples also have links to PHP functions used in them to provide quick access to reference material. All code examples have a "copy to clipboard" link by the side of them with which you can copy the text contents of the example to the clipboard.

External links are marked with a special » sign, and open in a new browser window. We also included the "path to this page" information on all pages for you to easily identify where you are and navigate as needed.

Other parts of the manual are quite similar to the online ones by default, though custom skins can modify many elements on the pages.

User Preferences
Integrating the PHP Manual
Specialities of this Edition


Integrating the PHP Manual

Informacja:

The information provided here is mainly aimed at IDE authors, or advanced users who would like to integrate this CHM file to their favorite IDEs or other production environment components.

There are several editors out there with support for CHM integration, but you may need to know a few things about what the CHM contains to successfully integrate the manual into your environment.

The CHM is built using XSL style sheets from XML sources. This is unique currently in the PHP Manual family, as all other versions are generated using DSSSL style sheets. This also means, that non-intentional rendering differences may come up. A special conversion script is run on the XSLT output, adding several cute features, and packing up the manual with the preferences files and skin examples.

If you never worked with CHMs, you can think of them as compressed files with OS supported access for files inside and some added search and index support. However CHMs can only be viewed using the HTML Help Viewer, you can directly access files inside them using a special URL prefix, the CHM file name and the file you request from inside. As all the help content is stored in HTML files, you can show pages of the CHM in Internet Explorer.

Assume that you placed your php_manual_en.chm to c:\phpmanual the index file in the manual (which you see the first time) can be accessed with the following URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Here mk:@MSITStore: is the special "protocol", C:\phpmanual\php_manual_en.chm is the CHM with it's full path. The /_index.html part is the path to the index file inside the CHM and :: is just what you need to put between the CHM path and this file path.

Informacja:

All files are in the root directory of the CHM, unlike the previous CHM versions which included a language directory. Images, style sheets and other supplemental files have names starting with an underscore (like the main index shown above), to avoid name collisions.

The names of generated files follow the same rules as the online manual, except that the extension is .html and not .php. The most important is that function documentation files are named function.FUNCNAME.html where FUNCNAME is the function name, with all underscores converted to hyphens. Some examples are function.echo.html, function.mysql-close.html, function.imagecopy.html.

Using all this information, you can show a manual page for a function requested by a user. A simple example is included in the distribution, named php_quickref.hta. This is a » HTML Application to demonstrate the simple process of showing a manual page for a function. The quickRef() function defined therein does the job.

If you would like to integrate the manual into an IDE without direct support for the PHP manual (actually the underscore to hyphen conversion), you can use the included _function.html file to access a function page. This file is simply a redirector, and can be parameterized via the URL, as _function.html#mysql_close. This page will redirect you to the mysql_close function page (function.mysql-close.html) automatically. You can provide the full path of this file if your IDE supports context sensitive help, and provide the IDE specified string as the parameter. An example for this is the UltraEdit 9 intergation (see the edition's website).

The index of the manual (accessible via the index tab on the navigation pane) can also be used for integrational purposes. All the HTML pages are included in the index with their titles as index terms (including function description pages).

If you are a desktop application developer and would like to tightly integrate the CHM into your program (such as displaying the TOC tree in your IDE's help box), you can find more information at » http://www.helpware.net/, as well as links to other useful resources. The official site for HTML Help is at » http://www.microsoft.com/download/en/details.aspx?id=21138.

Presentational Specialities
Skin development
Wersja HTML Help


Skin development

Spis treści

  • Page Display Process
  • Page Elements
  • CSS classes

This edition of the PHP Manual allows users to choose from skins to display the contents, as well as develop custom skins to meet some special needs. We decided to support skins because we realized that one skin cannot satisfy everybody's needs in a such heavily used edition.

We included two skins by default inside the CHM. These cannot be modified or removed, so if you have the CHM, you have these two skins inside. The Low skin is optimized for small window display, the High skin is a variation of the Low one with some graphics added to spice it up.

A skin must have at least two files, a skin loader JavaScript file and a CSS file. The two inline skins have these files inside the CHM. The skin loader JS should at least load in the CSS file and display the page contents to the viewer. Theoretically there are two kinds of skins: CSS skins and Full skins. CSS skins only modify the CSS and does not amend the page layout. Full skins also modify the page layout. We have included sample skins for both the CSS skin type and the Full skin type ("greenlinks" and "headernostalgia" respectively).

Ostrzeżenie

Note that though the current skin development methods are quite final, there may be heavy changes in used CSS classes or page elements while we refine the skin development ideas. As this edition is currently in development stage, the information described herein is not to be considered completely stable.

Integrating the PHP Manual
Page Display Process
Wersja HTML Help


Page Display Process

If you are going to develop your own skin, you should know how one page is loaded and displayed to the user, and how a skin fits in this process. For these paragraphs, we assume that you have put your CHM into c:\phpmanual, so it's accessible as c:\phpmanual\php_manual_LANG.chm (where LANG is the language code), and you would like to see the function page of "echo", which is function.echo.html inside the CHM. See the sections about integration for more information on CHM contents.

  • First of all the HTML content is loaded in from function.echo.html from inside the CHM.
  • At the top of this file, there is a HTML <script> tag, which loads in the _script.js file from the CHM. This file contains all the JS code needed to move on with the process. Most importantly this JS defines many variables (like where the CHM is, or what is the actual page viewed) and many functions to print out the context menu or handle online functions.
  • At last _script.js loads in the preferences file from outside the CHM (c:\phpmanual\php_manual_prefs.js in our example). This JS file defines the preference variables, and calls back prefHandler() which is also defined in _script.js.
  • That function loads in the skin JS file as the preferences dictate. The skin JS file should load in the needed CSS file, and define a displayPage() function, which displays the page if called.
  • The HTML file (function.echo.html in this example) also contains a function call to load in the user notes, which simply puts the notes into this HTML file using DHTML to be displayed as if they were here before...
  • The HTML file also contains a body onload attribute which calls the skin-defined displayPage() function to show the page to the user. This is the last function called, it should present the page in it's complete form to the user.
Every action is synchronized with calling back a function in the previously loaded file when the JS is in memory. The notes loading and skin JS loading is only synchronized with the page's onload event (which as the Microsoft documentation says only fires if the page is completely loaded).

This load and callback chain may seem to be too complicated, but so far this seemed to be the best way to do as many things as possible parallel, while also synchronize some calls.

As you can see your skin JavaScript file is loaded in by _script.js and it's displayPage() function is called by the body onload event.

Skin development
Page Elements
Skin development


Page Elements

The PHP Manual pages are all HTML files with several HTML tags in them for both presentational and divisional purposes. The HTML pages contain divisions to be used for skinning purposes and misc divisions added by the DocBook XSL sheets.

A HTML page can be either a function reference page or another kind of page (like a feature description). Skins should get ready to skin these two kinds of pages separately most of the time (depending on the actual design).

The pages are structured using <div> tags with appropriate IDs to ease the skin writers work. A page consists of these parts:

  • <div id="pageContent"></div> contains all the page contents. This begins right after <body> and ends just before </body>. This division is hidden by default, you need to show it after you are ready with the page rewriting process.
  • <div id="pageHeaders"></div> contains the page header parts. This includes the text only main title (in a <span id="pageTitle"></span>) and function properties, in case this is a function page (contained in <span id="funcPurpose"></span>, <span id="funcAvail"></span> and <span id="funcUsage"></span>). In case one of these three is not available, the current page is not a function page.
  • <div id="pageText"></div> contains the majority of the page contents, including examples, manual notes, warnings, etc. This also includes see also parts for now, as we still cannot differentiate between see also and normal text parts (may be a thing to change in the future).
  • <div id="pageNotes"></div> contains the user notes (itself loaded in from another HTML file by JS). It contains a heading, and then a <div> without ID for every user note and spans in that divs for every element of a user note (with "email", "date" and "text" IDs respectively).
  • <div id="pageNav"></div> contains the
navigation table, which is further divided into spans (<span
id="navPrev"></span>, <span
id="navPath"></span>, <span
id="navNext"></span>, <span
id="navOnline"></span>, <span
id="navThisOnline"></span> and <span
id="navReportBug"></span>), where navThisOnline
and navReportBug is inside navOnline.
If you would like to rewrite the page, you should first read in the parts you need from the page to JS variables, then clear the contents of pageContent (or just the part you would like to rewrite), write in the new content and show the pageContent div for the user. If you would not like to make any structural changes, you can simply display the pageContent div and only specify a special style sheet in your skin JS file (see the "greenlinks" skin for an example).

You can find a "Full skin" developed to show you how to make skins built on top of this structure. The skin name is "headernostalgia". It rewrites the header part and removes the footer navigational table.

Page Display Process
CSS classes
Skin development


CSS classes

We cannot provide accurate documentation currently on usable CSS classes, as some of the DocBook XSL sheets classes are not used and some classes are added. Please see the sample CSS files included for first time reference.

Page Elements
CHM Edition Credits
Skin development


CHM Edition Credits

This enhanced version of the PHP Manual would never come to existence, if the following people would not help with their contribution to the project (in no particular order):

  • Holger Eggert, who created the two default designs, and provided many usability tips
  • Gonzalo De la Pena Andreu, who added many comments on how it would be ideal to provide the skinnable interface
  • Olexandr Vynnychenko added countless comments and testing all the time
  • Brendan Ferguson, who provided many optimizations, improvements to the HTML and JS codes behind the manual pages
  • Sandor Hojtsy, who coded the manual preferences desktop application
  • And at last but not least, everybody, who provided feedback through our mailing list, and in the user survey

CSS classes
Wersja HTML Help